Compare commits
19 Commits
f9ea8e380a
...
e1716a741f
| Author | SHA1 | Date | |
|---|---|---|---|
| e1716a741f | |||
| e24707c847 | |||
| 7c4b8c307f | |||
| 109318aeaf | |||
| 1f2657cea0 | |||
| 382c435bac | |||
| 130fe4ca5d | |||
| 31ba3fe127 | |||
| f68b31158f | |||
| 653ca9a72d | |||
| ba7857f4df | |||
| 23e617ea21 | |||
| cdf5a5229c | |||
| f841a35a53 | |||
| efd31237be | |||
| 6502822583 | |||
| a9e6f2b2a5 | |||
| 510a94b42c | |||
| d805be47ce |
@@ -76,6 +76,10 @@ else()
|
||||
set(DUSK_LIBRARY_TARGET_NAME "${DUSK_BINARY_TARGET_NAME}" CACHE INTERNAL ${DUSK_CACHE_TARGET})
|
||||
endif()
|
||||
|
||||
if(NOT DEFINED DUSK_VERSION)
|
||||
string(TIMESTAMP DUSK_VERSION "debug-%y%m%d%H%M%S")
|
||||
endif()
|
||||
|
||||
# Definitions
|
||||
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
@@ -84,6 +88,7 @@ target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME}
|
||||
DUSK_GAME_AUTHOR="${DUSK_GAME_AUTHOR}"
|
||||
DUSK_GAME_SHORT_DESCRIPTION="${DUSK_GAME_SHORT_DESCRIPTION}"
|
||||
DUSK_GAME_LONG_DESCRIPTION="${DUSK_GAME_LONG_DESCRIPTION}"
|
||||
DUSK_VERSION="${DUSK_VERSION}"
|
||||
)
|
||||
|
||||
# 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;
|
||||
@@ -1,93 +0,0 @@
|
||||
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') {
|
||||
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("b", INPUT_ACTION_CANCEL);
|
||||
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') {
|
||||
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);
|
||||
Input.bind("right", INPUT_ACTION_RIGHT);
|
||||
Input.bind("up", INPUT_ACTION_UP);
|
||||
Input.bind("down", INPUT_ACTION_DOWN);
|
||||
|
||||
Input.bind("enter", INPUT_ACTION_ACCEPT);
|
||||
Input.bind("e", INPUT_ACTION_ACCEPT);
|
||||
|
||||
Input.bind("q", INPUT_ACTION_CANCEL);
|
||||
|
||||
Input.bind("escape", INPUT_ACTION_RAGEQUIT);
|
||||
Input.bind("`", INPUT_ACTION_CONSOLE);
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -1,96 +0,0 @@
|
||||
# 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})
|
||||
@@ -16,6 +16,9 @@ else()
|
||||
)
|
||||
endif()
|
||||
|
||||
# Export symbols so backtrace_symbols() can resolve function names.
|
||||
target_link_options(${DUSK_LIBRARY_TARGET_NAME} PUBLIC -rdynamic)
|
||||
|
||||
# Link required libraries.
|
||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||
SDL2
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# Fixes some problems building JerryScript
|
||||
set(CMAKE_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
|
||||
set(CMAKE_RANLIB "$ENV{PSPDEV}/bin/psp-ranlib" CACHE FILEPATH "" FORCE)
|
||||
set(CMAKE_C_COMPILER_AR "$ENV{PSPDEV}/bin/psp-ar" CACHE FILEPATH "" FORCE)
|
||||
@@ -8,9 +7,7 @@ set(CMAKE_C_ARCHIVE_APPEND "$ENV{PSPDEV}/bin/psp-ar q <TARGET> <LINK_FLAGS> <OBJ
|
||||
set(CMAKE_C_ARCHIVE_FINISH "$ENV{PSPDEV}/bin/psp-ranlib <TARGET>")
|
||||
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF CACHE BOOL "" FORCE)
|
||||
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_C OFF CACHE BOOL "" FORCE)
|
||||
set(JERRY_LTO OFF CACHE BOOL "" FORCE)
|
||||
|
||||
find_package(jerryscript REQUIRED)
|
||||
find_package(SDL2 REQUIRED)
|
||||
find_package(OpenGL REQUIRED)
|
||||
target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
||||
@@ -42,10 +39,6 @@ target_link_libraries(${DUSK_BINARY_TARGET_NAME} PUBLIC
|
||||
pspnet_apctl
|
||||
psphttp
|
||||
pspssl
|
||||
|
||||
jerryscript::core
|
||||
jerryscript::ext
|
||||
jerryscript::port
|
||||
)
|
||||
|
||||
target_include_directories(${DUSK_BINARY_TARGET_NAME} PRIVATE
|
||||
|
||||
@@ -32,15 +32,6 @@ if(NOT yyjson_FOUND)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(NOT jerryscript_FOUND)
|
||||
find_package(jerryscript REQUIRED)
|
||||
target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
|
||||
jerryscript::core
|
||||
jerryscript::ext
|
||||
jerryscript::port
|
||||
)
|
||||
endif()
|
||||
|
||||
# Includes
|
||||
target_include_directories(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
@@ -71,7 +62,6 @@ add_subdirectory(input)
|
||||
add_subdirectory(locale)
|
||||
add_subdirectory(physics)
|
||||
add_subdirectory(scene)
|
||||
add_subdirectory(script)
|
||||
add_subdirectory(system)
|
||||
add_subdirectory(time)
|
||||
add_subdirectory(ui)
|
||||
|
||||
@@ -9,6 +9,24 @@
|
||||
#include "log/log.h"
|
||||
#include "util/string.h"
|
||||
|
||||
#ifdef DUSK_LINUX
|
||||
#include <execinfo.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
static void assertLogBacktrace(void) {
|
||||
void *frames[64];
|
||||
int count = backtrace(frames, 64);
|
||||
char **symbols = backtrace_symbols(frames, count);
|
||||
logError("Stack trace:\n");
|
||||
if(symbols) {
|
||||
for(int i = 0; i < count; i++) {
|
||||
logError(" %s\n", symbols[i]);
|
||||
}
|
||||
free(symbols);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef DUSK_ASSERTIONS_FAKED
|
||||
#ifdef DUSK_TEST_ASSERT
|
||||
void assertTrueImpl(
|
||||
@@ -33,11 +51,14 @@
|
||||
) {
|
||||
if(x != true) {
|
||||
logError(
|
||||
"Assertion Failed in %s:%i\n\n%s\n",
|
||||
"Assertion Failed in %s:%i\n\n%s\n\n",
|
||||
file,
|
||||
line,
|
||||
message
|
||||
);
|
||||
#ifdef DUSK_LINUX
|
||||
assertLogBacktrace();
|
||||
#endif
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
asset.c
|
||||
assetfile.c
|
||||
assetcache.c
|
||||
assetbatch.c
|
||||
)
|
||||
|
||||
# Subdirs
|
||||
|
||||
@@ -16,11 +16,12 @@ asset_t ASSET;
|
||||
|
||||
errorret_t assetInit(void) {
|
||||
memoryZero(&ASSET, sizeof(asset_t));
|
||||
|
||||
|
||||
// assetInitPlatform must either define ASSET.zip or throw an error.
|
||||
errorChain(assetInitPlatform());
|
||||
assertNotNull(ASSET.zip, "Asset zip null without error.");
|
||||
|
||||
assetCacheInit(&ASSET.cache);
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -50,13 +51,15 @@ errorret_t assetLoad(
|
||||
}
|
||||
|
||||
errorret_t assetDispose(void) {
|
||||
assetCacheDispose(&ASSET.cache);
|
||||
|
||||
if(ASSET.zip != NULL) {
|
||||
if(zip_close(ASSET.zip) != 0) {
|
||||
errorThrow("Failed to close asset zip archive.");
|
||||
}
|
||||
ASSET.zip = NULL;
|
||||
}
|
||||
|
||||
|
||||
errorChain(assetDisposePlatform());
|
||||
errorOk();
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "error/error.h"
|
||||
#include "asset/assetplatform.h"
|
||||
#include "assetfile.h"
|
||||
#include "assetcache.h"
|
||||
|
||||
#ifndef assetInitPlatform
|
||||
#error "Platform must define assetInitPlatform function."
|
||||
@@ -23,6 +24,7 @@
|
||||
typedef struct asset_s {
|
||||
zip_t *zip;
|
||||
assetplatform_t platform;
|
||||
assetcache_t cache;
|
||||
} asset_t;
|
||||
|
||||
extern asset_t ASSET;
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* 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 "util/memory.h"
|
||||
#include "util/string.h"
|
||||
#include "assert/assert.h"
|
||||
|
||||
void assetBatchInit(
|
||||
assetbatch_t *batch,
|
||||
assetbatchcomplete_t onComplete,
|
||||
assetbatcherror_t onError,
|
||||
void *context
|
||||
) {
|
||||
memoryZero(batch, sizeof(assetbatch_t));
|
||||
batch->onComplete = onComplete;
|
||||
batch->onError = onError;
|
||||
batch->context = context;
|
||||
}
|
||||
|
||||
void assetBatchAdd(
|
||||
assetbatch_t *batch,
|
||||
const char_t *path,
|
||||
assetfileloader_t loader,
|
||||
const void *params,
|
||||
size_t paramsSize,
|
||||
size_t dataSize,
|
||||
assetcachedisposer_t disposer,
|
||||
void **outPtr
|
||||
) {
|
||||
assertTrue(batch->count < ASSET_BATCH_MAX, "Asset batch is full.");
|
||||
assertTrue(paramsSize <= ASSET_BATCH_PARAMS_SIZE, "Asset batch params too large.");
|
||||
assertNotNull(outPtr, "Batch output pointer cannot be NULL.");
|
||||
|
||||
assetbatchitem_t *item = &batch->items[batch->count++];
|
||||
stringCopy(item->path, path, ASSET_FILE_NAME_MAX);
|
||||
item->loader = loader;
|
||||
if (params != NULL && paramsSize > 0) {
|
||||
memoryCopy(item->params, params, paramsSize);
|
||||
}
|
||||
item->dataSize = dataSize;
|
||||
item->disposer = disposer;
|
||||
item->outPtr = outPtr;
|
||||
}
|
||||
|
||||
errorret_t assetBatchLoad(assetbatch_t *batch) {
|
||||
for (uint8_t i = 0; i < batch->count; i++) {
|
||||
assetbatchitem_t *item = &batch->items[i];
|
||||
|
||||
void *cached = assetCacheLookup(&ASSET.cache, item->path);
|
||||
if (cached != NULL) {
|
||||
assetCacheRetain(&ASSET.cache, item->path);
|
||||
*item->outPtr = cached;
|
||||
continue;
|
||||
}
|
||||
|
||||
void *data = memoryAllocate(item->dataSize);
|
||||
errorret_t err = assetLoad(item->path, item->loader, item->params, data);
|
||||
if (err.code != ERROR_OK) {
|
||||
memoryFree(data);
|
||||
if (batch->onError != NULL) {
|
||||
batch->onError(batch, batch->context, err);
|
||||
}
|
||||
return errorChainImpl(err, __FILE__, __func__, __LINE__);
|
||||
}
|
||||
|
||||
assetCacheInsert(&ASSET.cache, item->path, data, item->disposer);
|
||||
*item->outPtr = data;
|
||||
}
|
||||
|
||||
if (batch->onComplete != NULL) {
|
||||
batch->onComplete(batch, batch->context);
|
||||
}
|
||||
|
||||
errorOk();
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "assetcache.h"
|
||||
#include "error/error.h"
|
||||
|
||||
#ifndef ASSET_BATCH_MAX
|
||||
#define ASSET_BATCH_MAX 16
|
||||
#endif
|
||||
|
||||
#define ASSET_BATCH_PARAMS_SIZE 16
|
||||
|
||||
typedef struct assetbatch_s assetbatch_t;
|
||||
|
||||
typedef void (*assetbatchcomplete_t)(assetbatch_t *batch, void *context);
|
||||
typedef void (*assetbatcherror_t)(
|
||||
assetbatch_t *batch,
|
||||
void *context,
|
||||
errorret_t error
|
||||
);
|
||||
|
||||
typedef struct {
|
||||
char_t path[ASSET_FILE_NAME_MAX];
|
||||
assetfileloader_t loader;
|
||||
uint8_t params[ASSET_BATCH_PARAMS_SIZE];
|
||||
size_t dataSize;
|
||||
assetcachedisposer_t disposer;
|
||||
void **outPtr;
|
||||
} assetbatchitem_t;
|
||||
|
||||
struct assetbatch_s {
|
||||
assetbatchitem_t items[ASSET_BATCH_MAX];
|
||||
uint8_t count;
|
||||
assetbatchcomplete_t onComplete;
|
||||
assetbatcherror_t onError;
|
||||
void *context;
|
||||
};
|
||||
|
||||
/**
|
||||
* Initializes a batch, optionally with completion and error callbacks.
|
||||
*
|
||||
* @param batch The batch to initialize.
|
||||
* @param onComplete Called when all items have loaded successfully. May be NULL.
|
||||
* @param onError Called if any item fails to load. May be NULL.
|
||||
* @param context Passed through to both callbacks.
|
||||
*/
|
||||
void assetBatchInit(
|
||||
assetbatch_t *batch,
|
||||
assetbatchcomplete_t onComplete,
|
||||
assetbatcherror_t onError,
|
||||
void *context
|
||||
);
|
||||
|
||||
/**
|
||||
* Adds an item to the batch. Params are copied into inline storage.
|
||||
*
|
||||
* @param batch The batch to add to.
|
||||
* @param path Asset path, used as the cache key.
|
||||
* @param loader The loader function for this asset type.
|
||||
* @param params Loader-specific parameters. Copied — safe to pass stack address.
|
||||
* @param paramsSize Size of params in bytes. Must be <= ASSET_BATCH_PARAMS_SIZE.
|
||||
* @param dataSize Size in bytes to allocate for the output struct.
|
||||
* @param disposer Called on the data before freeing when released. May be NULL.
|
||||
* @param outPtr Caller's pointer variable. Set to the cache-owned data on load.
|
||||
*/
|
||||
void assetBatchAdd(
|
||||
assetbatch_t *batch,
|
||||
const char_t *path,
|
||||
assetfileloader_t loader,
|
||||
const void *params,
|
||||
size_t paramsSize,
|
||||
size_t dataSize,
|
||||
assetcachedisposer_t disposer,
|
||||
void **outPtr
|
||||
);
|
||||
|
||||
/**
|
||||
* Loads all items in the batch, checking the cache for each. Fires onComplete
|
||||
* on success or onError on the first failure. Also returns the error for
|
||||
* synchronous callers.
|
||||
*
|
||||
* @param batch The batch to execute.
|
||||
* @return Error if any item failed to load.
|
||||
*/
|
||||
errorret_t assetBatchLoad(assetbatch_t *batch);
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "assetcache.h"
|
||||
#include "util/memory.h"
|
||||
#include "util/string.h"
|
||||
#include "assert/assert.h"
|
||||
|
||||
void assetCacheInit(assetcache_t *cache) {
|
||||
memoryZero(cache, sizeof(assetcache_t));
|
||||
}
|
||||
|
||||
void *assetCacheLookup(assetcache_t *cache, const char_t *path) {
|
||||
for(uint8_t i = 0; i < cache->count; i++) {
|
||||
if(stringCompare(cache->entries[i].path, path) == 0) {
|
||||
return cache->entries[i].data;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void assetCacheInsert(
|
||||
assetcache_t *cache,
|
||||
const char_t *path,
|
||||
void *data,
|
||||
assetcachedisposer_t disposer
|
||||
) {
|
||||
assertTrue(cache->count < ASSET_CACHE_MAX, "Asset cache is full.");
|
||||
|
||||
assetcacheentry_t *entry = &cache->entries[cache->count++];
|
||||
stringCopy(entry->path, path, ASSET_FILE_NAME_MAX);
|
||||
entry->data = data;
|
||||
entry->refcount = 1;
|
||||
entry->disposer = disposer;
|
||||
}
|
||||
|
||||
void assetCacheRetain(assetcache_t *cache, const char_t *path) {
|
||||
for (uint8_t i = 0; i < cache->count; i++) {
|
||||
if (stringCompare(cache->entries[i].path, path) == 0) {
|
||||
cache->entries[i].refcount++;
|
||||
return;
|
||||
}
|
||||
}
|
||||
assertTrue(false, "Asset not found in cache for retain.");
|
||||
}
|
||||
|
||||
static void assetCacheEntryDispose(assetcacheentry_t *entry) {
|
||||
if (entry->disposer != NULL) {
|
||||
entry->disposer(entry->data);
|
||||
}
|
||||
memoryFree(entry->data);
|
||||
}
|
||||
|
||||
void assetCacheRelease(assetcache_t *cache, const char_t *path) {
|
||||
for (uint8_t i = 0; i < cache->count; i++) {
|
||||
if (stringCompare(cache->entries[i].path, path) == 0) {
|
||||
assetcacheentry_t *entry = &cache->entries[i];
|
||||
entry->refcount--;
|
||||
if (entry->refcount == 0) {
|
||||
assetCacheEntryDispose(entry);
|
||||
for (uint8_t j = i; j < cache->count - 1; j++) {
|
||||
cache->entries[j] = cache->entries[j + 1];
|
||||
}
|
||||
cache->count--;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
assertTrue(false, "Asset not found in cache for release.");
|
||||
}
|
||||
|
||||
void assetCacheDispose(assetcache_t *cache) {
|
||||
for (uint8_t i = 0; i < cache->count; i++) {
|
||||
assetCacheEntryDispose(&cache->entries[i]);
|
||||
}
|
||||
memoryZero(cache, sizeof(assetcache_t));
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "assetfile.h"
|
||||
|
||||
#ifndef ASSET_CACHE_MAX
|
||||
#define ASSET_CACHE_MAX 64
|
||||
#endif
|
||||
|
||||
typedef void (*assetcachedisposer_t)(void *data);
|
||||
|
||||
typedef struct {
|
||||
char_t path[ASSET_FILE_NAME_MAX];
|
||||
void *data;
|
||||
uint32_t refcount;
|
||||
assetcachedisposer_t disposer;
|
||||
} assetcacheentry_t;
|
||||
|
||||
typedef struct {
|
||||
assetcacheentry_t entries[ASSET_CACHE_MAX];
|
||||
uint8_t count;
|
||||
} assetcache_t;
|
||||
|
||||
/**
|
||||
* Initializes the asset cache.
|
||||
*
|
||||
* @param cache The cache to initialize.
|
||||
*/
|
||||
void assetCacheInit(assetcache_t *cache);
|
||||
|
||||
/**
|
||||
* Looks up a cached asset by path.
|
||||
*
|
||||
* @param cache The cache to search.
|
||||
* @param path The asset path to look up.
|
||||
* @return Pointer to the cached data, or NULL if not found.
|
||||
*/
|
||||
void *assetCacheLookup(assetcache_t *cache, const char_t *path);
|
||||
|
||||
/**
|
||||
* Inserts a newly loaded asset into the cache with refcount 1.
|
||||
*
|
||||
* @param cache The cache to insert into.
|
||||
* @param path The asset path key.
|
||||
* @param data Heap-allocated asset data. The cache takes ownership.
|
||||
* @param disposer Called with data before freeing when refcount reaches 0.
|
||||
*/
|
||||
void assetCacheInsert(
|
||||
assetcache_t *cache,
|
||||
const char_t *path,
|
||||
void *data,
|
||||
assetcachedisposer_t disposer
|
||||
);
|
||||
|
||||
/**
|
||||
* Increments the refcount for a cached asset.
|
||||
*
|
||||
* @param cache The cache containing the asset.
|
||||
* @param path The asset path.
|
||||
*/
|
||||
void assetCacheRetain(assetcache_t *cache, const char_t *path);
|
||||
|
||||
/**
|
||||
* Decrements the refcount. Disposes and frees the asset when it reaches 0.
|
||||
*
|
||||
* @param cache The cache containing the asset.
|
||||
* @param path The asset path.
|
||||
*/
|
||||
void assetCacheRelease(assetcache_t *cache, const char_t *path);
|
||||
|
||||
/**
|
||||
* Disposes all remaining cache entries and resets the cache.
|
||||
*
|
||||
* @param cache The cache to dispose.
|
||||
*/
|
||||
void assetCacheDispose(assetcache_t *cache);
|
||||
@@ -8,5 +8,4 @@
|
||||
# Subdirs
|
||||
add_subdirectory(display)
|
||||
add_subdirectory(locale)
|
||||
add_subdirectory(script)
|
||||
add_subdirectory(json)
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
#include "assettextureloader.h"
|
||||
#include "asset/assetbatch.h"
|
||||
#include "assert/assert.h"
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#include "stb_image.h"
|
||||
@@ -112,4 +113,26 @@ errorret_t assetTextureLoad(
|
||||
.format = format
|
||||
};
|
||||
return assetLoad(path, assetTextureLoader, ¶ms, out);
|
||||
}
|
||||
|
||||
static void assetTextureCacheDispose(void *data) {
|
||||
errorCatch(textureDispose((texture_t*)data));
|
||||
}
|
||||
|
||||
void assetBatchTexture(
|
||||
assetbatch_t *batch,
|
||||
const char_t *path,
|
||||
textureformat_t format,
|
||||
texture_t **out
|
||||
) {
|
||||
assettextureloaderparams_t params = { .format = format };
|
||||
assetBatchAdd(
|
||||
batch,
|
||||
path,
|
||||
assetTextureLoader,
|
||||
¶ms, sizeof(params),
|
||||
sizeof(texture_t),
|
||||
assetTextureCacheDispose,
|
||||
(void**)out
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "asset/assetbatch.h"
|
||||
#include "display/texture/texture.h"
|
||||
|
||||
typedef struct {
|
||||
@@ -47,4 +48,20 @@ errorret_t assetTextureLoad(
|
||||
const char_t *path,
|
||||
texture_t *out,
|
||||
const textureformat_t format
|
||||
);
|
||||
|
||||
/**
|
||||
* Adds a texture load request to a batch. The cache-owned texture_t* is
|
||||
* written to *out when the batch completes.
|
||||
*
|
||||
* @param batch The batch to add to.
|
||||
* @param path Path to the texture asset.
|
||||
* @param format Format of the texture to load.
|
||||
* @param out Receives a pointer to the loaded texture on completion.
|
||||
*/
|
||||
void assetBatchTexture(
|
||||
assetbatch_t *batch,
|
||||
const char_t *path,
|
||||
textureformat_t format,
|
||||
texture_t **out
|
||||
);
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
#include "assettilesetloader.h"
|
||||
#include "asset/assetbatch.h"
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include "util/endian.h"
|
||||
@@ -77,4 +78,20 @@ errorret_t assetTilesetLoad(
|
||||
tileset_t *out
|
||||
) {
|
||||
return assetLoad(path, assetTilesetLoader, NULL, out);
|
||||
}
|
||||
|
||||
void assetBatchTileset(
|
||||
assetbatch_t *batch,
|
||||
const char_t *path,
|
||||
tileset_t **out
|
||||
) {
|
||||
assetBatchAdd(
|
||||
batch,
|
||||
path,
|
||||
assetTilesetLoader,
|
||||
NULL, 0,
|
||||
sizeof(tileset_t),
|
||||
NULL,
|
||||
(void**)out
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "asset/assetbatch.h"
|
||||
#include "display/texture/tileset.h"
|
||||
|
||||
/**
|
||||
@@ -27,4 +28,18 @@ errorret_t assetTilesetLoader(assetfile_t *file);
|
||||
errorret_t assetTilesetLoad(
|
||||
const char_t *path,
|
||||
tileset_t *out
|
||||
);
|
||||
|
||||
/**
|
||||
* Adds a tileset load request to a batch. The cache-owned tileset_t* is
|
||||
* written to *out when the batch completes.
|
||||
*
|
||||
* @param batch The batch to add to.
|
||||
* @param path Path to the tileset asset.
|
||||
* @param out Receives a pointer to the loaded tileset on completion.
|
||||
*/
|
||||
void assetBatchTileset(
|
||||
assetbatch_t *batch,
|
||||
const char_t *path,
|
||||
tileset_t **out
|
||||
);
|
||||
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "assetscriptloader.h"
|
||||
#include "assert/assert.h"
|
||||
#include <stdlib.h>
|
||||
#include <zip.h>
|
||||
|
||||
errorret_t assetScriptLoader(assetfile_t *file) {
|
||||
assertNotNull(file, "Asset file cannot be NULL");
|
||||
assertNull(file->zipFile, "Asset file zip handle must be NULL before open");
|
||||
assertNotNull(file->output, "Asset file output cannot be NULL");
|
||||
|
||||
assetscript_t *script = (assetscript_t *)file->output;
|
||||
|
||||
errorChain(assetFileOpen(file));
|
||||
|
||||
// Accumulate full source into a dynamically grown buffer.
|
||||
size_t srcLen = 0;
|
||||
size_t capacity = ASSET_SCRIPT_CHUNK_SIZE;
|
||||
char_t *src = (char_t *)malloc(capacity + 1);
|
||||
if(!src) {
|
||||
assetFileClose(file);
|
||||
errorThrow("Out of memory reading script: %s", file->filename);
|
||||
}
|
||||
|
||||
while(1) {
|
||||
if(srcLen + ASSET_SCRIPT_CHUNK_SIZE > capacity) {
|
||||
capacity = srcLen + ASSET_SCRIPT_CHUNK_SIZE;
|
||||
char_t *tmp = (char_t *)realloc(src, capacity + 1);
|
||||
if(!tmp) {
|
||||
free(src);
|
||||
assetFileClose(file);
|
||||
errorThrow("Out of memory reading script: %s", file->filename);
|
||||
}
|
||||
src = tmp;
|
||||
}
|
||||
zip_int64_t n = zip_fread(
|
||||
file->zipFile, src + srcLen, ASSET_SCRIPT_CHUNK_SIZE
|
||||
);
|
||||
if(n <= 0) break;
|
||||
srcLen += (size_t)n;
|
||||
}
|
||||
src[srcLen] = '\0';
|
||||
|
||||
errorret_t closeRet = assetFileClose(file);
|
||||
|
||||
jerry_value_t result = jerry_eval(
|
||||
(const jerry_char_t *)src,
|
||||
srcLen,
|
||||
JERRY_PARSE_NO_OPTS
|
||||
);
|
||||
free(src);
|
||||
|
||||
if(jerry_value_is_exception(result)) {
|
||||
jerry_value_t errVal = jerry_exception_value(result, false);
|
||||
jerry_value_t errStr = jerry_value_to_string(errVal);
|
||||
char_t buf[256];
|
||||
jerry_size_t len = jerry_string_to_buffer(
|
||||
errStr, JERRY_ENCODING_UTF8, (jerry_char_t *)buf, sizeof(buf) - 1
|
||||
);
|
||||
buf[len] = '\0';
|
||||
jerry_value_free(errStr);
|
||||
jerry_value_free(errVal);
|
||||
jerry_value_free(result);
|
||||
errorThrow("Script error in '%s': %s", file->filename, buf);
|
||||
}
|
||||
|
||||
if(script->resultOut != NULL) {
|
||||
*(script->resultOut) = result;
|
||||
} else {
|
||||
jerry_value_free(result);
|
||||
}
|
||||
|
||||
return closeRet;
|
||||
}
|
||||
|
||||
errorret_t assetScriptLoad(
|
||||
const char_t *path,
|
||||
jerry_value_t *resultOut
|
||||
) {
|
||||
assertNotNull(path, "Script path cannot be NULL");
|
||||
|
||||
assetscript_t scriptData;
|
||||
scriptData.resultOut = resultOut;
|
||||
|
||||
return assetLoad(path, assetScriptLoader, NULL, &scriptData);
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
|
||||
#define ASSET_SCRIPT_CHUNK_SIZE 1024
|
||||
|
||||
typedef struct {
|
||||
jerry_value_t *resultOut;
|
||||
} assetscript_t;
|
||||
|
||||
/**
|
||||
* Handler for script assets. Reads the full source, evaluates it with
|
||||
* JerryScript, and optionally stores the result.
|
||||
*
|
||||
* @param file Asset file to load the script from.
|
||||
* @return Any error that occurs during loading.
|
||||
*/
|
||||
errorret_t assetScriptLoader(assetfile_t *file);
|
||||
|
||||
/**
|
||||
* Loads a script from the specified path.
|
||||
*
|
||||
* @param path Path to the script asset.
|
||||
* @param resultOut Optional out-parameter for the script return value.
|
||||
* Caller must call jerry_value_free() if non-NULL.
|
||||
* Pass NULL to discard the return value.
|
||||
* @return Any error that occurs during loading.
|
||||
*/
|
||||
errorret_t assetScriptLoad(
|
||||
const char_t *path,
|
||||
jerry_value_t *resultOut
|
||||
);
|
||||
+2
-110
@@ -12,7 +12,6 @@
|
||||
#include "input/input.h"
|
||||
#include "log/log.h"
|
||||
#include "engine/engine.h"
|
||||
#include "script/scriptmanager.h"
|
||||
#include "display/shader/shaderunlit.h"
|
||||
#include "display/text/text.h"
|
||||
#include "display/spritebatch/spritebatch.h"
|
||||
@@ -23,10 +22,7 @@ void consoleInit(void) {
|
||||
memoryZero(&CONSOLE, sizeof(console_t));
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadInit(&CONSOLE.thread, consoleInputThread);
|
||||
threadMutexInit(&CONSOLE.execMutex);
|
||||
threadMutexInit(&CONSOLE.printMutex);
|
||||
threadStartRequest(&CONSOLE.thread);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -56,30 +52,6 @@ void consolePrint(const char_t *message, ...) {
|
||||
logDebug("%s\n", buffer);
|
||||
}
|
||||
|
||||
void consoleExec(const char_t *line) {
|
||||
assertNotNull(line, "line must not be NULL");
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadMutexLock(&CONSOLE.execMutex);
|
||||
#endif
|
||||
|
||||
assertTrue(
|
||||
CONSOLE.execBufferCount < CONSOLE_EXEC_BUFFER_MAX,
|
||||
"Console exec buffer is full"
|
||||
);
|
||||
|
||||
stringCopy(
|
||||
CONSOLE.execBuffer[CONSOLE.execBufferCount],
|
||||
line,
|
||||
CONSOLE_LINE_MAX
|
||||
);
|
||||
CONSOLE.execBufferCount++;
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadMutexUnlock(&CONSOLE.execMutex);
|
||||
#endif
|
||||
}
|
||||
|
||||
void consoleUpdate(void) {
|
||||
#ifdef DUSK_TIME_DYNAMIC
|
||||
if(TIME.dynamicUpdate) return;
|
||||
@@ -88,40 +60,6 @@ void consoleUpdate(void) {
|
||||
if(inputPressed(INPUT_ACTION_CONSOLE)) {
|
||||
CONSOLE.visible = !CONSOLE.visible;
|
||||
}
|
||||
|
||||
if(CONSOLE.execBufferCount == 0) return;
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadMutexLock(&CONSOLE.execMutex);
|
||||
#endif
|
||||
|
||||
char_t execBuffer[CONSOLE_EXEC_BUFFER_MAX][CONSOLE_LINE_MAX];
|
||||
uint32_t execBufferCount = CONSOLE.execBufferCount;
|
||||
memoryCopy(execBuffer, CONSOLE.execBuffer, sizeof(execBuffer));
|
||||
CONSOLE.execBufferCount = 0;
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadMutexUnlock(&CONSOLE.execMutex);
|
||||
#endif
|
||||
|
||||
for(uint32_t i = 0; i < execBufferCount; i++) {
|
||||
jerry_value_t result = 0;
|
||||
errorret_t err = scriptManagerExec(execBuffer[i], &result);
|
||||
if(err.code != ERROR_OK) {
|
||||
consolePrint("Error: %s", err.state->message);
|
||||
errorCatch(err);
|
||||
} else if(!jerry_value_is_undefined(result)) {
|
||||
jerry_value_t strVal = jerry_value_to_string(result);
|
||||
char_t buf[CONSOLE_LINE_MAX];
|
||||
jerry_size_t len = jerry_string_to_buffer(
|
||||
strVal, JERRY_ENCODING_UTF8, (jerry_char_t*)buf, sizeof(buf) - 1
|
||||
);
|
||||
buf[len] = '\0';
|
||||
jerry_value_free(strVal);
|
||||
consolePrint("%s", buf);
|
||||
}
|
||||
if(result != 0) jerry_value_free(result);
|
||||
}
|
||||
}
|
||||
|
||||
errorret_t consoleDraw(void) {
|
||||
@@ -129,7 +67,7 @@ errorret_t consoleDraw(void) {
|
||||
|
||||
for(uint32_t i = 0; i < CONSOLE_HISTORY_MAX; i++) {
|
||||
errorChain(textDraw(
|
||||
0, FONT_DEFAULT.tileset.tileHeight * i,
|
||||
0, FONT_DEFAULT.tileset->tileHeight * i,
|
||||
CONSOLE.line[i],
|
||||
COLOR_WHITE,
|
||||
&FONT_DEFAULT
|
||||
@@ -140,52 +78,6 @@ errorret_t consoleDraw(void) {
|
||||
|
||||
void consoleDispose(void) {
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
threadStop(&CONSOLE.thread);
|
||||
threadMutexDispose(&CONSOLE.execMutex);
|
||||
threadMutexDispose(&CONSOLE.printMutex);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
void consoleInputThread(thread_t *thread) {
|
||||
assertNotNull(thread, "Thread cannot be NULL.");
|
||||
|
||||
char_t line[CONSOLE_LINE_MAX];
|
||||
|
||||
struct pollfd pfd = {
|
||||
.fd = STDIN_FILENO,
|
||||
.events = POLLIN
|
||||
};
|
||||
|
||||
while(!threadShouldStop(thread) && ENGINE.running) {
|
||||
int32_t rc = poll(&pfd, 1, CONSOLE_POSIX_POLL_RATE);
|
||||
|
||||
if(rc == 0) continue;
|
||||
if(rc < 0) {
|
||||
if(errno == EINTR) continue;
|
||||
assertUnreachable("poll() failed with unexpected error.");
|
||||
}
|
||||
|
||||
if(pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) break;
|
||||
if(!(pfd.revents & POLLIN)) {
|
||||
pfd.revents = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(!fgets(line, CONSOLE_LINE_MAX, stdin)) {
|
||||
if(feof(stdin)) break;
|
||||
clearerr(stdin);
|
||||
continue;
|
||||
}
|
||||
|
||||
size_t len = strlen(line);
|
||||
while(len && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
|
||||
line[--len] = '\0';
|
||||
}
|
||||
|
||||
if(len > 0) consoleExec(line);
|
||||
|
||||
pfd.revents = 0;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -21,12 +21,7 @@ typedef struct {
|
||||
char_t line[CONSOLE_HISTORY_MAX][CONSOLE_LINE_MAX];
|
||||
bool_t visible;
|
||||
|
||||
char_t execBuffer[CONSOLE_EXEC_BUFFER_MAX][CONSOLE_LINE_MAX];
|
||||
uint32_t execBufferCount;
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
thread_t thread;
|
||||
threadmutex_t execMutex;
|
||||
threadmutex_t printMutex;
|
||||
#endif
|
||||
} console_t;
|
||||
@@ -45,13 +40,6 @@ void consoleInit(void);
|
||||
*/
|
||||
void consolePrint(const char_t *message, ...);
|
||||
|
||||
/**
|
||||
* Queues a JS string for execution on the main thread. Thread-safe.
|
||||
*
|
||||
* @param line The JS source line to execute.
|
||||
*/
|
||||
void consoleExec(const char_t *line);
|
||||
|
||||
/**
|
||||
* Processes pending queued script lines. Call once per frame from main thread.
|
||||
*/
|
||||
@@ -67,13 +55,4 @@ errorret_t consoleDraw(void);
|
||||
/**
|
||||
* Disposes of the console.
|
||||
*/
|
||||
void consoleDispose(void);
|
||||
|
||||
#ifdef DUSK_CONSOLE_POSIX
|
||||
/**
|
||||
* Input thread handler for POSIX stdin.
|
||||
*
|
||||
* @param thread The thread that is running.
|
||||
*/
|
||||
void consoleInputThread(thread_t *thread);
|
||||
#endif
|
||||
void consoleDispose(void);
|
||||
+13
-104
@@ -6,102 +6,13 @@
|
||||
#include "cutscene.h"
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include "script/module/modulebase.h"
|
||||
#include "script/module/cutscene/modulecutscene.h"
|
||||
#include "console/console.h"
|
||||
#include "time/time.h"
|
||||
|
||||
cutscene_t CUTSCENE;
|
||||
|
||||
static errorret_t cutsceneCallMethod(const char_t *method) {
|
||||
if(CUTSCENE.scriptRef == CUTSCENE_SCRIPT_REF_NONE) errorOk();
|
||||
|
||||
jerry_value_t key = jerry_string_sz(method);
|
||||
jerry_value_t fn = jerry_object_get(CUTSCENE.scriptRef, key);
|
||||
jerry_value_free(key);
|
||||
|
||||
if(!jerry_value_is_function(fn)) {
|
||||
jerry_value_free(fn);
|
||||
errorOk();
|
||||
}
|
||||
|
||||
jerry_value_t result = jerry_call(fn, CUTSCENE.scriptRef, NULL, 0);
|
||||
jerry_value_free(fn);
|
||||
|
||||
if(jerry_value_is_exception(result)) {
|
||||
cutsceneevent_t *event = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
char_t errMsg[512];
|
||||
moduleBaseExceptionMessage(result, errMsg, sizeof(errMsg));
|
||||
jerry_value_free(result);
|
||||
errorThrow(
|
||||
"Cutscene event '%s' %s failed: %s",
|
||||
event->script.script, method, errMsg
|
||||
);
|
||||
}
|
||||
|
||||
jerry_value_free(result);
|
||||
errorOk();
|
||||
}
|
||||
|
||||
static errorret_t cutsceneEventStart(void) {
|
||||
cutsceneevent_t *event = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
|
||||
if(event->type == CUTSCENE_EVENT_TYPE_NATIVE) {
|
||||
if(event->native.onStart) errorChain(event->native.onStart());
|
||||
} else if(event->type == CUTSCENE_EVENT_TYPE_SCRIPT) {
|
||||
jerry_value_t eventClass = CUTSCENE_SCRIPT_REF_NONE;
|
||||
errorChain(scriptManagerExecFile(event->script.script, &eventClass));
|
||||
|
||||
if(!jerry_value_is_function(eventClass)) {
|
||||
if(eventClass != CUTSCENE_SCRIPT_REF_NONE) jerry_value_free(eventClass);
|
||||
errorThrow(
|
||||
"Cutscene event '%s' must export a constructor function",
|
||||
event->script.script
|
||||
);
|
||||
}
|
||||
|
||||
jerry_value_t eventObj = jerry_construct(eventClass, NULL, 0);
|
||||
jerry_value_free(eventClass);
|
||||
|
||||
if(jerry_value_is_exception(eventObj)) {
|
||||
char_t errMsg[512];
|
||||
moduleBaseExceptionMessage(eventObj, errMsg, sizeof(errMsg));
|
||||
jerry_value_free(eventObj);
|
||||
errorThrow(
|
||||
"Cutscene event '%s' constructor threw: %s",
|
||||
event->script.script, errMsg
|
||||
);
|
||||
}
|
||||
|
||||
CUTSCENE.scriptRef = eventObj;
|
||||
errorChain(cutsceneCallMethod("onStart"));
|
||||
}
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
static errorret_t cutsceneEventEnd(void) {
|
||||
cutsceneevent_t *event = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
|
||||
if(event->type == CUTSCENE_EVENT_TYPE_NATIVE) {
|
||||
if(event->native.onEnd) errorChain(event->native.onEnd());
|
||||
} else if(event->type == CUTSCENE_EVENT_TYPE_SCRIPT) {
|
||||
errorret_t err = cutsceneCallMethod("onEnd");
|
||||
if(CUTSCENE.scriptRef != CUTSCENE_SCRIPT_REF_NONE) {
|
||||
jerry_value_free(CUTSCENE.scriptRef);
|
||||
CUTSCENE.scriptRef = CUTSCENE_SCRIPT_REF_NONE;
|
||||
}
|
||||
errorChain(err);
|
||||
}
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t cutsceneInit(void) {
|
||||
memoryZero(&CUTSCENE, sizeof(cutscene_t));
|
||||
CUTSCENE.scriptRef = CUTSCENE_SCRIPT_REF_NONE;
|
||||
CUTSCENE.activeRef = CUTSCENE_SCRIPT_REF_NONE;
|
||||
consolePrint("Cutscene init");
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -112,18 +23,10 @@ errorret_t cutsceneUpdate(void) {
|
||||
}
|
||||
#endif
|
||||
|
||||
errorChain(moduleCutsceneUpdate());
|
||||
|
||||
if(!CUTSCENE.active) errorOk();
|
||||
|
||||
cutsceneevent_t *event = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
|
||||
if(event->type == CUTSCENE_EVENT_TYPE_NATIVE) {
|
||||
if(event->native.onUpdate) errorChain(event->native.onUpdate());
|
||||
} else if(event->type == CUTSCENE_EVENT_TYPE_SCRIPT) {
|
||||
errorChain(cutsceneCallMethod("onUpdate"));
|
||||
}
|
||||
|
||||
if(event->onUpdate) errorChain(event->onUpdate());
|
||||
errorOk();
|
||||
}
|
||||
|
||||
@@ -147,23 +50,26 @@ errorret_t cutscenePlay(
|
||||
CUTSCENE.eventCurrent = 0;
|
||||
CUTSCENE.active = true;
|
||||
|
||||
errorChain(cutsceneEventStart());
|
||||
consolePrint("Cutscene play");
|
||||
cutsceneevent_t *firstEvent = &CUTSCENE.events[0];
|
||||
if(firstEvent->onStart) errorChain(firstEvent->onStart());
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t cutsceneAdvance(void) {
|
||||
if(!CUTSCENE.active) errorOk();
|
||||
|
||||
errorChain(cutsceneEventEnd());
|
||||
cutsceneevent_t *currentEvent = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
if(currentEvent->onEnd) errorChain(currentEvent->onEnd());
|
||||
CUTSCENE.eventCurrent++;
|
||||
|
||||
if(CUTSCENE.eventCurrent >= CUTSCENE.eventCount) {
|
||||
if(CUTSCENE.onStop) errorChain(CUTSCENE.onStop());
|
||||
CUTSCENE.active = false;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorChain(cutsceneEventStart());
|
||||
cutsceneevent_t *nextEvent = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
if(nextEvent->onStart) errorChain(nextEvent->onStart());
|
||||
consolePrint("Cutscene advance");
|
||||
errorOk();
|
||||
}
|
||||
@@ -171,9 +77,12 @@ errorret_t cutsceneAdvance(void) {
|
||||
errorret_t cutsceneStop(void) {
|
||||
if(!CUTSCENE.active) errorOk();
|
||||
|
||||
errorChain(cutsceneEventEnd());
|
||||
cutsceneevent_t *currentEvent = &CUTSCENE.events[CUTSCENE.eventCurrent];
|
||||
if(currentEvent->onEnd) errorChain(currentEvent->onEnd());
|
||||
|
||||
if(CUTSCENE.onStop) errorChain(CUTSCENE.onStop());
|
||||
|
||||
CUTSCENE.active = false;
|
||||
consolePrint("Cutscene stop");
|
||||
errorOk();
|
||||
}
|
||||
|
||||
|
||||
@@ -4,42 +4,22 @@
|
||||
// https://opensource.org/licenses/MIT
|
||||
|
||||
#pragma once
|
||||
#include "script/scriptmanager.h"
|
||||
#include "error/error.h"
|
||||
|
||||
#define CUTSCENE_EVENT_COUNT_MAX 16
|
||||
#define CUTSCENE_SCRIPT_REF_NONE ((jerry_value_t)0)
|
||||
|
||||
typedef enum {
|
||||
CUTSCENE_EVENT_TYPE_NULL,
|
||||
CUTSCENE_EVENT_TYPE_NATIVE,
|
||||
CUTSCENE_EVENT_TYPE_SCRIPT,
|
||||
CUTSCENE_EVENT_TYPE_COUNT
|
||||
} cutsceneeventtype_t;
|
||||
|
||||
typedef struct {
|
||||
cutsceneeventtype_t type;
|
||||
|
||||
union {
|
||||
struct {
|
||||
errorret_t (*onStart)(void);
|
||||
errorret_t (*onEnd)(void);
|
||||
errorret_t (*onUpdate)(void);
|
||||
} native;
|
||||
|
||||
struct {
|
||||
const char_t *script;
|
||||
} script;
|
||||
};
|
||||
errorret_t (*onStart)(void);
|
||||
errorret_t (*onEnd)(void);
|
||||
errorret_t (*onUpdate)(void);
|
||||
} cutsceneevent_t;
|
||||
|
||||
typedef struct {
|
||||
cutsceneevent_t events[CUTSCENE_EVENT_COUNT_MAX];
|
||||
uint8_t eventCount;
|
||||
uint8_t eventCurrent;
|
||||
errorret_t (*onStop)(void);
|
||||
bool_t active;
|
||||
jerry_value_t scriptRef;
|
||||
jerry_value_t activeRef;
|
||||
} cutscene_t;
|
||||
|
||||
extern cutscene_t CUTSCENE;
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
#include "util/memory.h"
|
||||
#include "util/string.h"
|
||||
#include "asset/asset.h"
|
||||
#include "display/shader/shaderunlit.h"
|
||||
#include "display/shader/shaderlist.h"
|
||||
#include "time/time.h"
|
||||
|
||||
display_t DISPLAY = { 0 };
|
||||
@@ -53,31 +53,8 @@ errorret_t displayInit(void) {
|
||||
errorChain(screenInit());
|
||||
|
||||
// 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(
|
||||
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));
|
||||
errorChain(shaderListInit());
|
||||
|
||||
errorOk();
|
||||
}
|
||||
@@ -119,7 +96,7 @@ errorret_t displaySetState(displaystate_t state) {
|
||||
}
|
||||
|
||||
errorret_t displayDispose(void) {
|
||||
errorChain(shaderDispose(&SHADER_UNLIT));
|
||||
errorChain(shaderListDispose());
|
||||
errorChain(spriteBatchDispose());
|
||||
screenDispose();
|
||||
errorChain(textDispose());
|
||||
|
||||
@@ -7,5 +7,6 @@
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
shader.c
|
||||
shaderlist.c
|
||||
shaderunlit.c
|
||||
)
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "shader.h"
|
||||
#include "shadermaterial.h"
|
||||
#include "assert/assert.h"
|
||||
#include "log/log.h"
|
||||
|
||||
shader_t *bound = NULL;
|
||||
|
||||
@@ -57,6 +58,7 @@ errorret_t shaderSetColor(
|
||||
) {
|
||||
assertNotNull(shader, "Shader cannot be null");
|
||||
assertStrLenMin(name, 1, "Uniform name cannot be empty");
|
||||
assertTrue(bound == shader, "Shader must be bound.");
|
||||
errorChain(shaderSetColorPlatform(shader, name, color));
|
||||
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
|
||||
#include "display/shader/shaderunlit.h"
|
||||
#include "display/shader/shaderlist.h"
|
||||
|
||||
typedef union shadermaterial_u {
|
||||
shaderunlitmaterial_t unlit;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Copyright (c) 2025 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
@@ -9,13 +9,13 @@
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include "util/math.h"
|
||||
#include "display/shader/shadermaterial.h"
|
||||
|
||||
meshvertex_t SPRITEBATCH_VERTICES[SPRITEBATCH_VERTEX_COUNT];
|
||||
spritebatch_t SPRITEBATCH;
|
||||
|
||||
errorret_t spriteBatchInit() {
|
||||
memoryZero(&SPRITEBATCH, sizeof(spritebatch_t));
|
||||
|
||||
errorChain(meshInit(
|
||||
&SPRITEBATCH.mesh,
|
||||
QUAD_PRIMITIVE_TYPE,
|
||||
@@ -25,176 +25,102 @@ errorret_t spriteBatchInit() {
|
||||
errorOk();
|
||||
}
|
||||
|
||||
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
|
||||
errorret_t spriteBatchBuffer(
|
||||
const spritebatchsprite_t *sprites,
|
||||
const uint32_t count,
|
||||
shader_t *shader,
|
||||
const shadermaterial_t material
|
||||
) {
|
||||
size_t offset = 0;
|
||||
while(offset < count) {
|
||||
if(SPRITEBATCH.spriteCount >= SPRITEBATCH_SPRITES_MAX_PER_FLUSH) {
|
||||
errorChain(spriteBatchFlush());
|
||||
}
|
||||
assertNotNull(sprites, "Sprites cannot be null");
|
||||
assertTrue(count > 0, "Count must be greater than zero");
|
||||
assertNotNull(shader, "Shader cannot be null");
|
||||
|
||||
size_t available = (size_t)(
|
||||
SPRITEBATCH_SPRITES_MAX_PER_FLUSH - SPRITEBATCH.spriteCount
|
||||
);
|
||||
size_t toPush = mathMin(count - offset, available);
|
||||
// Did the shader or material data change?
|
||||
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;
|
||||
}
|
||||
|
||||
meshvertex_t *start = &SPRITEBATCH_VERTICES[
|
||||
// Buffer the vertices.
|
||||
for(uint32_t i = 0; i < count; i++ ){
|
||||
spritebatchsprite_t sprite = sprites[i];
|
||||
|
||||
meshvertex_t *v = &SPRITEBATCH_VERTICES[
|
||||
(SPRITEBATCH.spriteCount + (SPRITEBATCH.spriteFlush *
|
||||
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];
|
||||
|
||||
// Fill all toPush sprites field-by-field, one memoryCopyInterleaved per
|
||||
// vertex-slot per field. Vertex layout matches quadBuffer3D:
|
||||
// v0=(minX,minY,z,u0,v0) v1=(maxX,minY,z,u1,v0) v2=(maxX,maxY,z,u1,v1)
|
||||
// v3=(minX,minY,z,u0,v0) v4=(maxX,maxY,z,u1,v1) v5=(minX,maxY,z,u0,v1)
|
||||
const size_t dstStride = sizeof(meshvertex_t) * QUAD_VERTEX_COUNT;
|
||||
const size_t fSz = sizeof(float_t);
|
||||
const float_t *sMinX = minX + offset;
|
||||
const float_t *sMaxX = maxX + offset;
|
||||
const float_t *sMinY = minY + offset;
|
||||
const float_t *sMaxY = maxY + offset;
|
||||
const float_t *sZ = z + offset;
|
||||
const float_t *sU0 = u0 + offset;
|
||||
const float_t *sU1 = u1 + offset;
|
||||
const float_t *sV0 = v0 + offset;
|
||||
const float_t *sV1 = v1 + offset;
|
||||
v[0].uv[0] = sprite.uvMin[0];
|
||||
v[0].uv[1] = sprite.uvMin[1];
|
||||
|
||||
#define memshVertCopy(vi, field, srcArr) \
|
||||
memoryCopyInterleaved( \
|
||||
&start[vi].field, dstStride, srcArr, fSz, fSz, toPush \
|
||||
)
|
||||
|
||||
memshVertCopy(0, pos[0], sMinX);
|
||||
memshVertCopy(0, pos[1], sMinY);
|
||||
memshVertCopy(0, pos[2], sZ);
|
||||
memshVertCopy(0, uv[0], sU0);
|
||||
memshVertCopy(0, uv[1], sV0);
|
||||
v[1].pos[0] = sprite.max[0];
|
||||
v[1].pos[1] = sprite.min[1];
|
||||
v[1].pos[2] = sprite.min[2];
|
||||
|
||||
memshVertCopy(1, pos[0], sMaxX);
|
||||
memshVertCopy(1, pos[1], sMinY);
|
||||
memshVertCopy(1, pos[2], sZ);
|
||||
memshVertCopy(1, uv[0], sU1);
|
||||
memshVertCopy(1, uv[1], sV0);
|
||||
v[1].uv[0] = sprite.uvMax[0];
|
||||
v[1].uv[1] = sprite.uvMin[1];
|
||||
|
||||
memshVertCopy(2, pos[0], sMaxX);
|
||||
memshVertCopy(2, pos[1], sMaxY);
|
||||
memshVertCopy(2, pos[2], sZ);
|
||||
memshVertCopy(2, uv[0], sU1);
|
||||
memshVertCopy(2, uv[1], sV1);
|
||||
|
||||
memshVertCopy(3, pos[0], sMinX);
|
||||
memshVertCopy(3, pos[1], sMinY);
|
||||
memshVertCopy(3, pos[2], sZ);
|
||||
memshVertCopy(3, uv[0], sU0);
|
||||
memshVertCopy(3, uv[1], sV0);
|
||||
v[2].pos[0] = sprite.max[0];
|
||||
v[2].pos[1] = sprite.max[1];
|
||||
v[2].pos[2] = sprite.max[2];
|
||||
|
||||
memshVertCopy(4, pos[0], sMaxX);
|
||||
memshVertCopy(4, pos[1], sMaxY);
|
||||
memshVertCopy(4, pos[2], sZ);
|
||||
memshVertCopy(4, uv[0], sU1);
|
||||
memshVertCopy(4, uv[1], sV1);
|
||||
v[2].uv[0] = sprite.uvMax[0];
|
||||
v[2].uv[1] = sprite.uvMax[1];
|
||||
|
||||
memshVertCopy(5, pos[0], sMinX);
|
||||
memshVertCopy(5, pos[1], sMaxY);
|
||||
memshVertCopy(5, pos[2], sZ);
|
||||
memshVertCopy(5, uv[0], sU0);
|
||||
memshVertCopy(5, uv[1], sV1);
|
||||
|
||||
#undef memshVertCopy
|
||||
v[3].pos[0] = sprite.min[0];
|
||||
v[3].pos[1] = sprite.min[1];
|
||||
v[3].pos[2] = sprite.min[2];
|
||||
|
||||
#if MESH_ENABLE_COLOR
|
||||
for(uint8_t vi = 0; vi < QUAD_VERTEX_COUNT; vi++) {
|
||||
memoryCopyInterleaved(
|
||||
&start[vi].color, dstStride,
|
||||
color + offset, sizeof(color_t), sizeof(color_t), toPush
|
||||
);
|
||||
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++;
|
||||
if(SPRITEBATCH.spriteCount >= SPRITEBATCH_SPRITES_MAX_PER_FLUSH) {
|
||||
errorChain(spriteBatchFlush());
|
||||
}
|
||||
#endif
|
||||
|
||||
SPRITEBATCH.spriteCount += (int32_t)toPush;
|
||||
offset += toPush;
|
||||
}
|
||||
|
||||
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
|
||||
) {
|
||||
return spriteBatchPushv(
|
||||
&minX, &minY, &maxX, &maxY, &(float_t){0},
|
||||
#if MESH_ENABLE_COLOR
|
||||
&color,
|
||||
#endif
|
||||
&u0, &v0, &u1, &v1,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
errorret_t spriteBatchPush3D(
|
||||
const vec3 min,
|
||||
const vec3 max,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
const vec2 uv0,
|
||||
const vec2 uv1
|
||||
) {
|
||||
return spriteBatchPushv(
|
||||
&min[0], &min[1],
|
||||
&max[0], &max[1],
|
||||
&min[2],
|
||||
#if MESH_ENABLE_COLOR
|
||||
&color,
|
||||
#endif
|
||||
&uv0[0], &uv0[1],
|
||||
&uv1[0], &uv1[1],
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
errorret_t spriteBatchBufferSprite(const spritebatchsprite_t *sprite) {
|
||||
if(sprite->texture != SPRITEBATCH.currentTexture) {
|
||||
errorChain(spriteBatchFlush());
|
||||
SPRITEBATCH.currentTexture = sprite->texture;
|
||||
}
|
||||
return spriteBatchPush3D(
|
||||
sprite->min,
|
||||
sprite->max,
|
||||
#if MESH_ENABLE_COLOR
|
||||
sprite->color,
|
||||
#endif
|
||||
sprite->uvMin,
|
||||
sprite->uvMax
|
||||
);
|
||||
}
|
||||
|
||||
void spriteBatchClear() {
|
||||
SPRITEBATCH.spriteCount = 0;
|
||||
SPRITEBATCH.spriteFlush = 0;
|
||||
SPRITEBATCH.currentTexture = NULL;
|
||||
SPRITEBATCH.shader = NULL;
|
||||
memoryZero(&SPRITEBATCH.material, sizeof(shadermaterial_t));
|
||||
}
|
||||
|
||||
errorret_t spriteBatchFlush() {
|
||||
@@ -207,6 +133,9 @@ errorret_t spriteBatchFlush() {
|
||||
SPRITEBATCH.spriteFlush * SPRITEBATCH_SPRITES_MAX_PER_FLUSH *
|
||||
QUAD_VERTEX_COUNT
|
||||
);
|
||||
|
||||
errorChain(shaderBind(SPRITEBATCH.shader));
|
||||
errorChain(shaderSetMaterial(SPRITEBATCH.shader, &SPRITEBATCH.material));
|
||||
errorChain(meshFlush(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
|
||||
errorChain(meshDraw(&SPRITEBATCH.mesh, vertexOffset, vertexCount));
|
||||
|
||||
@@ -222,4 +151,4 @@ errorret_t spriteBatchFlush() {
|
||||
errorret_t spriteBatchDispose() {
|
||||
errorChain(meshDispose(&SPRITEBATCH.mesh));
|
||||
errorOk();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Copyright (c) 2025 Dominic Masters
|
||||
*
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
@@ -8,6 +8,7 @@
|
||||
#pragma once
|
||||
#include "display/mesh/quad.h"
|
||||
#include "display/texture/texture.h"
|
||||
#include "display/shader/shadermaterial.h"
|
||||
|
||||
#define SPRITEBATCH_SPRITES_MAX 512
|
||||
#define SPRITEBATCH_VERTEX_COUNT (SPRITEBATCH_SPRITES_MAX * QUAD_VERTEX_COUNT)
|
||||
@@ -21,141 +22,66 @@ typedef struct {
|
||||
vec3 max;
|
||||
vec2 uvMin;
|
||||
vec2 uvMax;
|
||||
texture_t *texture;
|
||||
#if MESH_ENABLE_COLOR
|
||||
color_t color;
|
||||
#endif
|
||||
} spritebatchsprite_t;
|
||||
|
||||
typedef struct {
|
||||
mesh_t mesh;
|
||||
int32_t spriteCount;
|
||||
int32_t spriteFlush;
|
||||
texture_t *currentTexture;
|
||||
|
||||
shader_t *shader;
|
||||
shadermaterial_t material;
|
||||
} 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 spritebatch_t SPRITEBATCH;
|
||||
|
||||
/**
|
||||
* Initializes a sprite batch.
|
||||
*
|
||||
* @param spriteBatch The sprite batch to initialize.
|
||||
* @return An error code indicating success or failure.
|
||||
* Initializes the global sprite batch and its internal mesh buffer.
|
||||
*
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t spriteBatchInit();
|
||||
|
||||
/**
|
||||
* Pushes multiple sprites to the batch using arrays of values.
|
||||
* Lowest-level buffer function. Writes sprites into the internal vertex buffer.
|
||||
* 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 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.
|
||||
* @param sprites Pointer to the sprite array.
|
||||
* @param count Number of sprites to buffer.
|
||||
* @param shader Shader to use when flushing.
|
||||
* @param material Material information passed to the shader when flushing.
|
||||
* @return Error state.
|
||||
*/
|
||||
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
|
||||
errorret_t spriteBatchBuffer(
|
||||
const spritebatchsprite_t *sprites,
|
||||
const uint32_t count,
|
||||
shader_t *shader,
|
||||
const shadermaterial_t material
|
||||
);
|
||||
|
||||
/**
|
||||
* Pushes a sprite to the batch. This basically "queues" it to render (well
|
||||
* technically it is buffering the vertices to the mesh at the moment, but
|
||||
* that is likely to change when we switch to VAOs or VBOs or even Shader UBOs).
|
||||
*
|
||||
* Currently changing texture pointer will cause the buffer to flush but this is
|
||||
* also likely to change in the future.
|
||||
*
|
||||
* @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 The texture coordinate for the top-left corner of the sprite.
|
||||
* @param v0 The texture coordinate for the top-left corner of the sprite.
|
||||
* @param u1 The texture coordinate for the bottom-right corner of the sprite.
|
||||
* @param v1 The texture coordinate for the bottom-right corner of the sprite.
|
||||
* @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. This is like spriteBatchPush but takes
|
||||
* 3D coordinates instead of 2D.
|
||||
*
|
||||
* @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 The texture coordinate for the top-left corner of the sprite.
|
||||
* @param uvMax The texture coordinate for the bottom-right corner of the sprite
|
||||
* @return An error code indicating success or failure.
|
||||
*/
|
||||
errorret_t spriteBatchPush3D(
|
||||
const vec3 min,
|
||||
const vec3 max,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
const vec2 uvMin,
|
||||
const vec2 uvMax
|
||||
);
|
||||
|
||||
/**
|
||||
* Buffers a sprite defined by a spritebatchsprite_t. Automatically flushes
|
||||
* if the texture changes from the previously buffered sprite.
|
||||
*
|
||||
* @param sprite The sprite to buffer.
|
||||
* @return An error code indicating success or failure.
|
||||
*/
|
||||
errorret_t spriteBatchBufferSprite(const spritebatchsprite_t *sprite);
|
||||
|
||||
/**
|
||||
* Clears the sprite batch. This will mean calling flush renders nothing.
|
||||
* Resets sprite and flush counters and clears the current material state.
|
||||
* Calling spriteBatchFlush after this renders nothing.
|
||||
*/
|
||||
void spriteBatchClear();
|
||||
|
||||
/**
|
||||
* Flushes the sprite batch, rendering all queued sprites.
|
||||
*
|
||||
* @return An error code indicating success or failure.
|
||||
* 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 Error state.
|
||||
*/
|
||||
errorret_t spriteBatchFlush();
|
||||
|
||||
/**
|
||||
* Disposes of the sprite batch, freeing any allocated resources.
|
||||
*
|
||||
* @return An error code indicating success or failure.
|
||||
* Disposes of the sprite batch and frees its internal mesh buffer.
|
||||
*
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t spriteBatchDispose();
|
||||
errorret_t spriteBatchDispose();
|
||||
|
||||
@@ -10,6 +10,6 @@
|
||||
#include "display/texture/tileset.h"
|
||||
|
||||
typedef struct {
|
||||
texture_t texture;
|
||||
tileset_t tileset;
|
||||
texture_t *texture;
|
||||
tileset_t *tileset;
|
||||
} font_t;
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
#include "assert/assert.h"
|
||||
#include "util/memory.h"
|
||||
#include "display/spritebatch/spritebatch.h"
|
||||
#include "asset/asset.h"
|
||||
#include "asset/assetbatch.h"
|
||||
#include "asset/loader/display/assettextureloader.h"
|
||||
#include "asset/loader/display/assettilesetloader.h"
|
||||
#include "display/shader/shaderunlit.h"
|
||||
@@ -16,49 +18,53 @@
|
||||
font_t FONT_DEFAULT;
|
||||
|
||||
errorret_t textInit(void) {
|
||||
errorChain(assetTextureLoad(
|
||||
"ui/minogram.png", &FONT_DEFAULT.texture, TEXTURE_FORMAT_RGBA
|
||||
));
|
||||
errorChain(assetTilesetLoad("ui/minogram.dtf", &FONT_DEFAULT.tileset));
|
||||
assetbatch_t batch;
|
||||
assetBatchInit(&batch, NULL, NULL, NULL);
|
||||
assetBatchTexture(&batch, "ui/minogram.png", TEXTURE_FORMAT_RGBA, &FONT_DEFAULT.texture);
|
||||
assetBatchTileset(&batch, "ui/minogram.dtf", &FONT_DEFAULT.tileset);
|
||||
errorChain(assetBatchLoad(&batch));
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t textDispose(void) {
|
||||
errorChain(textureDispose(&FONT_DEFAULT.texture));
|
||||
assetCacheRelease(&ASSET.cache, "ui/minogram.png");
|
||||
assetCacheRelease(&ASSET.cache, "ui/minogram.dtf");
|
||||
FONT_DEFAULT.texture = NULL;
|
||||
FONT_DEFAULT.tileset = NULL;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t textDrawChar(
|
||||
const float_t x,
|
||||
const float_t y,
|
||||
const char_t c,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
font_t *font
|
||||
spritebatchsprite_t textGetSprite(
|
||||
const vec2 pos, const char_t c, const 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;
|
||||
if(tileIndex < 0 || tileIndex >= font->tileset.tileCount) {
|
||||
if(tileIndex < 0 || tileIndex >= font->tileset->tileCount) {
|
||||
tileIndex = ((int32_t)'@') - TEXT_CHAR_START;
|
||||
}
|
||||
assertTrue(
|
||||
tileIndex >= 0 && tileIndex <= font->tileset.tileCount,
|
||||
tileIndex >= 0 && tileIndex <= font->tileset->tileCount,
|
||||
"Character is out of bounds for font tiles"
|
||||
);
|
||||
|
||||
// Create sprite.
|
||||
vec4 uv;
|
||||
tilesetTileGetUV(&font->tileset, tileIndex, uv);
|
||||
tilesetTileGetUV(font->tileset, tileIndex, uv);
|
||||
|
||||
errorChain(spriteBatchPush(
|
||||
x, y,
|
||||
x + font->tileset.tileWidth,
|
||||
y + font->tileset.tileHeight,
|
||||
#if MESH_ENABLE_COLOR
|
||||
color,
|
||||
#endif
|
||||
uv[0], uv[1], uv[2], uv[3]
|
||||
));
|
||||
errorOk();
|
||||
spritebatchsprite_t sprite;
|
||||
sprite.min[0] = pos[0];
|
||||
sprite.min[1] = pos[1];
|
||||
sprite.min[2] = 0.0f;
|
||||
sprite.max[0] = pos[0] + font->tileset->tileWidth;
|
||||
sprite.max[1] = pos[1] + font->tileset->tileHeight;
|
||||
sprite.max[2] = 0.0f;
|
||||
sprite.uvMin[0] = uv[0];
|
||||
sprite.uvMin[1] = uv[1];
|
||||
sprite.uvMax[0] = uv[2];
|
||||
sprite.uvMax[1] = uv[3];
|
||||
return sprite;
|
||||
}
|
||||
|
||||
errorret_t textDraw(
|
||||
@@ -70,10 +76,18 @@ errorret_t textDraw(
|
||||
) {
|
||||
assertNotNull(text, "Text cannot be NULL");
|
||||
|
||||
spritebatchsprite_t sprite;
|
||||
shadermaterial_t material = {
|
||||
.unlit = {
|
||||
.color = color,
|
||||
.texture = font->texture
|
||||
}
|
||||
};
|
||||
|
||||
float_t posX = x;
|
||||
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
|
||||
#else
|
||||
@@ -85,23 +99,18 @@ errorret_t textDraw(
|
||||
while((c = text[i++]) != '\0') {
|
||||
if(c == '\n') {
|
||||
posX = x;
|
||||
posY += font->tileset.tileHeight;
|
||||
posY += font->tileset->tileHeight;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(c == ' ') {
|
||||
posX += font->tileset.tileWidth;
|
||||
posX += font->tileset->tileWidth;
|
||||
continue;
|
||||
}
|
||||
|
||||
errorChain(textDrawChar(
|
||||
posX, posY, c,
|
||||
#if MESH_ENABLE_COLOR
|
||||
color,
|
||||
#endif
|
||||
font
|
||||
));
|
||||
posX += font->tileset.tileWidth;
|
||||
sprite = textGetSprite((vec2){posX, posY}, c, font);
|
||||
errorChain(spriteBatchBuffer(&sprite, 1, &SHADER_UNLIT, material));
|
||||
posX += font->tileset->tileWidth;
|
||||
}
|
||||
errorOk();
|
||||
}
|
||||
@@ -117,7 +126,7 @@ void textMeasure(
|
||||
assertNotNull(outHeight, "Output height pointer cannot be NULL");
|
||||
|
||||
int32_t width = 0;
|
||||
int32_t height = font->tileset.tileHeight;
|
||||
int32_t height = font->tileset->tileHeight;
|
||||
int32_t lineWidth = 0;
|
||||
|
||||
char_t c;
|
||||
@@ -126,11 +135,11 @@ void textMeasure(
|
||||
if(c == '\n') {
|
||||
if(lineWidth > width) width = lineWidth;
|
||||
lineWidth = 0;
|
||||
height += font->tileset.tileHeight;
|
||||
height += font->tileset->tileHeight;
|
||||
continue;
|
||||
}
|
||||
|
||||
lineWidth += font->tileset.tileWidth;
|
||||
lineWidth += font->tileset->tileWidth;
|
||||
}
|
||||
|
||||
if(lineWidth > width) width = lineWidth;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#pragma once
|
||||
#include "asset/asset.h"
|
||||
#include "display/text/font.h"
|
||||
#include "display/spritebatch/spritebatch.h"
|
||||
|
||||
#define TEXT_CHAR_START '!'
|
||||
|
||||
@@ -28,23 +29,17 @@ errorret_t textInit(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 y The y-coordinate to draw the character at.
|
||||
* @param c The character to draw.
|
||||
* @param color The color to draw the character in.
|
||||
* @param font Font to use for rendering.
|
||||
* @return Either an error or success result.
|
||||
* @param pos The (x, y) position of the character in screen/world space.
|
||||
* @param c The character to build a sprite for.
|
||||
* @param font Font to use for tile lookup.
|
||||
* @return The populated sprite ready for spriteBatchBuffer.
|
||||
*/
|
||||
errorret_t textDrawChar(
|
||||
const float_t x,
|
||||
const float_t y,
|
||||
spritebatchsprite_t textGetSprite(
|
||||
const vec2 pos,
|
||||
const char_t c,
|
||||
#if MESH_ENABLE_COLOR
|
||||
const color_t color,
|
||||
#endif
|
||||
font_t *font
|
||||
const font_t *font
|
||||
);
|
||||
|
||||
/**
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
#include <cglm/cglm.h>
|
||||
#include <cglm/types.h>
|
||||
#include <cglm/vec2.h>
|
||||
#include <jerryscript.h>
|
||||
|
||||
#include "duskplatform.h"
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
#include "asset/asset.h"
|
||||
#include "ui/ui.h"
|
||||
#include "ui/uitextbox.h"
|
||||
#include "script/scriptmanager.h"
|
||||
#include "assert/assert.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/physics/entityphysics.h"
|
||||
@@ -27,16 +26,6 @@
|
||||
#include "item/backpack.h"
|
||||
#include "save/save.h"
|
||||
|
||||
double jerry_port_current_time(void) {
|
||||
dusktimeepoch_t epoch = timeGetEpoch();
|
||||
return epoch.time * 1000.0;
|
||||
}
|
||||
|
||||
int32_t jerry_port_local_tza(double unix_ms) {
|
||||
(void) unix_ms;
|
||||
return 0;
|
||||
}
|
||||
|
||||
engine_t ENGINE;
|
||||
|
||||
errorret_t engineInit(const int32_t argc, const char_t **argv) {
|
||||
@@ -44,6 +33,7 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
|
||||
ENGINE.running = true;
|
||||
ENGINE.argc = argc;
|
||||
ENGINE.argv = argv;
|
||||
ENGINE.version = DUSK_VERSION;
|
||||
|
||||
// Init systems. Order is important.
|
||||
errorChain(systemInit());
|
||||
@@ -53,7 +43,6 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
|
||||
errorChain(assetInit());
|
||||
// errorChain(saveInit());
|
||||
errorChain(localeManagerInit());
|
||||
errorChain(scriptManagerInit());
|
||||
errorChain(displayInit());
|
||||
errorChain(uiInit());
|
||||
errorChain(uiTextboxInit());
|
||||
@@ -67,7 +56,7 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
|
||||
|
||||
/* Run the init script. */
|
||||
consolePrint("Engine initialized");
|
||||
errorChain(scriptManagerExecFile("init.js", NULL));
|
||||
sceneSet(SCENE_TYPE_OVERWORLD);
|
||||
|
||||
errorOk();
|
||||
}
|
||||
@@ -78,18 +67,15 @@ errorret_t engineUpdate(void) {
|
||||
timeUpdate();
|
||||
inputUpdate();
|
||||
consoleUpdate();
|
||||
entityManagerUpdate();
|
||||
uiUpdate();
|
||||
errorChain(uiTextboxUpdate());
|
||||
physicsManagerUpdate();
|
||||
errorChain(displayUpdate());
|
||||
|
||||
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());
|
||||
|
||||
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ typedef struct {
|
||||
bool_t running;
|
||||
int32_t argc;
|
||||
const char_t **argv;
|
||||
const char_t *version;
|
||||
} engine_t;
|
||||
|
||||
extern engine_t ENGINE;
|
||||
|
||||
@@ -12,12 +12,13 @@
|
||||
componentdefinition_t COMPONENT_DEFINITIONS[] = {
|
||||
[COMPONENT_TYPE_NULL] = { 0 },
|
||||
|
||||
#define X(enm, type, field, iMethod, dMethod) \
|
||||
#define X(enm, type, field, iMethod, dMethod, rMethod) \
|
||||
[COMPONENT_TYPE_##enm] = { \
|
||||
.enumName = #enm, \
|
||||
.name = #field, \
|
||||
.init = iMethod, \
|
||||
.dispose = dMethod \
|
||||
.dispose = dMethod, \
|
||||
.render = rMethod \
|
||||
},
|
||||
|
||||
#include "componentlist.h"
|
||||
@@ -114,6 +115,19 @@ entityid_t componentGetEntitiesWithComponent(
|
||||
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(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
#pragma once
|
||||
#include "entitybase.h"
|
||||
|
||||
#define X(enumName, type, field, init, dispose) \
|
||||
#define X(enumName, type, field, init, dispose, render) \
|
||||
// do nothing
|
||||
#include "componentlist.h"
|
||||
#undef X
|
||||
|
||||
typedef union {
|
||||
#define X(enumName, type, field, init, dispose) type field;
|
||||
#define X(enumName, type, field, init, dispose, render) type field;
|
||||
#include "componentlist.h"
|
||||
#undef X
|
||||
} componentdata_t;
|
||||
@@ -24,12 +24,13 @@ typedef struct {
|
||||
const char_t *name;
|
||||
void (*init)(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;
|
||||
|
||||
typedef enum {
|
||||
COMPONENT_TYPE_NULL,
|
||||
|
||||
#define X(enumName, type, field, init, dispose) \
|
||||
#define X(enumName, type, field, init, dispose, render) \
|
||||
COMPONENT_TYPE_##enumName,
|
||||
#include "componentlist.h"
|
||||
#undef X
|
||||
@@ -100,11 +101,20 @@ entityid_t componentGetEntitiesWithComponent(
|
||||
|
||||
/**
|
||||
* Disposes of a component for the entity with component ID.
|
||||
*
|
||||
*
|
||||
* @param entityId The entity ID.
|
||||
* @param componentId The component ID.
|
||||
*/
|
||||
void componentDispose(
|
||||
const entityid_t entityId,
|
||||
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);
|
||||
@@ -4,6 +4,7 @@
|
||||
# https://opensource.org/licenses/MIT
|
||||
|
||||
add_subdirectory(display)
|
||||
add_subdirectory(overworld)
|
||||
add_subdirectory(physics)
|
||||
add_subdirectory(script)
|
||||
add_subdirectory(trigger)
|
||||
@@ -16,7 +16,7 @@ void entityCameraInit(const entityid_t ent, const componentid_t comp) {
|
||||
ent, comp, COMPONENT_TYPE_CAMERA
|
||||
);
|
||||
cam->nearClip = 0.1f;
|
||||
cam->farClip = 100.0f;
|
||||
cam->farClip = 5000.0f;
|
||||
cam->projType = ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE;
|
||||
cam->perspective.fov = glm_rad(45.0f);
|
||||
}
|
||||
@@ -66,7 +66,7 @@ entityid_t entityCameraGetCurrent(void) {
|
||||
entityid_t count = componentGetEntitiesWithComponent(
|
||||
COMPONENT_TYPE_CAMERA, camEnts, camComps
|
||||
);
|
||||
if(count == 0) return ENTITY_COUNT_MAX;
|
||||
if(count == 0) return ENTITY_ID_INVALID;
|
||||
return camEnts[0];
|
||||
}
|
||||
|
||||
@@ -83,6 +83,30 @@ void entityCameraGetForward(const entityid_t entityId, vec2 out) {
|
||||
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) {
|
||||
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
|
||||
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.
|
||||
*/
|
||||
entityid_t entityCameraGetCurrent(void);
|
||||
@@ -76,4 +76,24 @@ void entityCameraGetForward(const entityid_t entityId, vec2 out);
|
||||
* @param entityId The camera entity ID.
|
||||
* @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"
|
||||
|
||||
// Lazily recompute worldTransform from the parent chain.
|
||||
static void entityPositionUpdateWorld(entityposition_t *pos) {
|
||||
if(!pos->dirty) return;
|
||||
// Decompose localTransform into the PRS cache. Only called when PRS_DIRTY.
|
||||
static void entityPositionEnsurePRS(entityposition_t *pos) {
|
||||
if(!(pos->flags & ENTITY_POSITION_FLAG_PRS_DIRTY)) return;
|
||||
entityPositionDecompose(pos);
|
||||
pos->flags &= ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||
}
|
||||
|
||||
if(pos->parentEntityId == ENTITY_ID_INVALID) {
|
||||
glm_mat4_copy(pos->localTransform, pos->worldTransform);
|
||||
} else {
|
||||
// Rebuild localTransform from the PRS cache. Only rebuilds what changed.
|
||||
static void entityPositionEnsureLocal(entityposition_t *pos) {
|
||||
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(
|
||||
pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
entityPositionUpdateWorld(parent);
|
||||
entityPositionEnsureWorld(parent);
|
||||
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) {
|
||||
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++) {
|
||||
entityposition_t *child = componentGetData(
|
||||
pos->childEntityIds[i], pos->childComponentIds[i], COMPONENT_TYPE_POSITION
|
||||
@@ -42,29 +99,31 @@ void entityPositionInit(
|
||||
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->rotation);
|
||||
glm_vec3_one(pos->scale);
|
||||
glm_mat4_identity(pos->localTransform);
|
||||
glm_mat4_identity(pos->worldTransform);
|
||||
pos->dirty = false;
|
||||
pos->parentEntityId = ENTITY_ID_INVALID;
|
||||
pos->parentComponentId = COMPONENT_ID_INVALID;
|
||||
pos->childCount = 0;
|
||||
}
|
||||
|
||||
void entityPositionLookAt(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
vec3 eye,
|
||||
vec3 target,
|
||||
vec3 up,
|
||||
vec3 eye
|
||||
vec3 up
|
||||
) {
|
||||
entityposition_t *pos = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -76,8 +135,11 @@ void entityPositionGetTransform(
|
||||
entityposition_t *pos = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
entityPositionUpdateWorld(pos);
|
||||
glm_mat4_copy(pos->worldTransform, dest);
|
||||
entityPositionEnsureWorld(pos);
|
||||
glm_mat4_copy(
|
||||
pos->parentEntityId == ENTITY_ID_INVALID ? pos->localTransform : pos->worldTransform,
|
||||
dest
|
||||
);
|
||||
}
|
||||
|
||||
void entityPositionGetLocalTransform(
|
||||
@@ -88,10 +150,11 @@ void entityPositionGetLocalTransform(
|
||||
entityposition_t *pos = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
entityPositionEnsureLocal(pos);
|
||||
glm_mat4_copy(pos->localTransform, dest);
|
||||
}
|
||||
|
||||
void entityPositionGetPosition(
|
||||
void entityPositionGetLocalPosition(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
vec3 dest
|
||||
@@ -99,10 +162,59 @@ void entityPositionGetPosition(
|
||||
entityposition_t *pos = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
entityPositionEnsurePRS(pos);
|
||||
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 componentid_t componentId,
|
||||
vec3 position
|
||||
@@ -111,10 +223,12 @@ void entityPositionSetPosition(
|
||||
entityId, componentId, COMPONENT_TYPE_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 componentid_t componentId,
|
||||
vec3 dest
|
||||
@@ -122,10 +236,48 @@ void entityPositionGetRotation(
|
||||
entityposition_t *pos = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
entityPositionEnsurePRS(pos);
|
||||
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 componentid_t componentId,
|
||||
vec3 rotation
|
||||
@@ -134,10 +286,87 @@ void entityPositionSetRotation(
|
||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
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 componentid_t componentId,
|
||||
vec3 dest
|
||||
@@ -145,10 +374,31 @@ void entityPositionGetScale(
|
||||
entityposition_t *pos = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
entityPositionEnsurePRS(pos);
|
||||
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 componentid_t componentId,
|
||||
vec3 scale
|
||||
@@ -157,7 +407,40 @@ void entityPositionSetScale(
|
||||
entityId, componentId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
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(
|
||||
@@ -218,12 +501,8 @@ entityposition_t *entityPositionGet(
|
||||
}
|
||||
|
||||
void entityPositionRebuild(entityposition_t *pos) {
|
||||
glm_mat4_identity(pos->localTransform);
|
||||
glm_translate(pos->localTransform, pos->position);
|
||||
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);
|
||||
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY | ENTITY_POSITION_FLAG_POSITION_DIRTY)
|
||||
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
|
||||
entityPositionMarkDirty(pos);
|
||||
}
|
||||
|
||||
@@ -281,36 +560,33 @@ void entityPositionDecompose(entityposition_t *pos) {
|
||||
pos->localTransform[2][2] * pos->localTransform[2][2]
|
||||
);
|
||||
|
||||
// Normalize columns to isolate the rotation matrix.
|
||||
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;
|
||||
float invS2 = pos->scale[2] > 0.0f ? 1.0f / pos->scale[2] : 0.0f;
|
||||
// Normalize columns to isolate the rotation matrix (9 floats, no mat4 needed).
|
||||
const float invS0 = pos->scale[0] > 0.0f ? 1.0f / pos->scale[0] : 0.0f;
|
||||
const float invS1 = pos->scale[1] > 0.0f ? 1.0f / pos->scale[1] : 0.0f;
|
||||
const float invS2 = pos->scale[2] > 0.0f ? 1.0f / pos->scale[2] : 0.0f;
|
||||
|
||||
mat4 r;
|
||||
glm_mat4_identity(r);
|
||||
r[0][0] = pos->localTransform[0][0] * invS0;
|
||||
r[0][1] = pos->localTransform[0][1] * invS0;
|
||||
r[0][2] = pos->localTransform[0][2] * invS0;
|
||||
r[1][0] = pos->localTransform[1][0] * invS1;
|
||||
r[1][1] = pos->localTransform[1][1] * invS1;
|
||||
r[1][2] = pos->localTransform[1][2] * invS1;
|
||||
r[2][0] = pos->localTransform[2][0] * invS2;
|
||||
r[2][1] = pos->localTransform[2][1] * invS2;
|
||||
r[2][2] = pos->localTransform[2][2] * invS2;
|
||||
const float r00 = pos->localTransform[0][0] * invS0;
|
||||
const float r01 = pos->localTransform[0][1] * invS0;
|
||||
const float r02 = pos->localTransform[0][2] * invS0;
|
||||
const float r10 = pos->localTransform[1][0] * invS1;
|
||||
const float r11 = pos->localTransform[1][1] * invS1;
|
||||
const float r20 = pos->localTransform[2][0] * invS2;
|
||||
const float r21 = pos->localTransform[2][1] * invS2;
|
||||
const float r22 = pos->localTransform[2][2] * invS2;
|
||||
|
||||
// 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);
|
||||
float cosBeta = cosf(pos->rotation[1]);
|
||||
const float cosBeta = cosf(pos->rotation[1]);
|
||||
|
||||
if(fabsf(cosBeta) > 1e-6f) {
|
||||
pos->rotation[0] = atan2f(-r[2][1], r[2][2]);
|
||||
pos->rotation[2] = atan2f(-r[1][0], r[0][0]);
|
||||
pos->rotation[0] = atan2f(-r21, r22);
|
||||
pos->rotation[2] = atan2f(-r10, r00);
|
||||
} else {
|
||||
// Gimbal lock: pin Z to 0, recover X.
|
||||
pos->rotation[2] = 0.0f;
|
||||
pos->rotation[0] = (sinBeta > 0.0f)
|
||||
? atan2f(r[0][1], r[1][1])
|
||||
: -atan2f(r[0][1], r[1][1]);
|
||||
? atan2f(r01, r11)
|
||||
: -atan2f(r01, r11);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,24 +8,81 @@
|
||||
#pragma once
|
||||
#include "entity/entitybase.h"
|
||||
|
||||
/** Maximum number of child position components this node can track. */
|
||||
#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 {
|
||||
mat4 localTransform;
|
||||
mat4 worldTransform;
|
||||
vec3 position;
|
||||
vec3 rotation;
|
||||
vec3 scale;
|
||||
bool dirty;
|
||||
/*
|
||||
* Hot fields — flag checks and parent/child traversal (markDirty, ensureWorld)
|
||||
* only touch these. Kept at the front so they share the first cache line.
|
||||
*/
|
||||
|
||||
/** Bitmask of ENTITY_POSITION_FLAG_* values describing which caches are stale. */
|
||||
uint8_t flags;
|
||||
/** Entity ID of the parent node, or ENTITY_ID_INVALID if none. */
|
||||
entityid_t parentEntityId;
|
||||
/** Component ID of the parent position component, or COMPONENT_ID_INVALID if none. */
|
||||
componentid_t parentComponentId;
|
||||
/** Number of currently registered children. */
|
||||
uint8_t childCount;
|
||||
/** Entity IDs of child nodes. */
|
||||
entityid_t childEntityIds[ENTITY_POSITION_CHILDREN_MAX];
|
||||
/** Component IDs of child position components. */
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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(
|
||||
const entityid_t entityId,
|
||||
@@ -35,26 +92,26 @@ void entityPositionInit(
|
||||
/**
|
||||
* 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 target The target point to look at.
|
||||
* @param up The up vector.
|
||||
* @param eye The eye/camera position.
|
||||
* @param eye The eye/camera position.
|
||||
* @param target The target point to look at.
|
||||
* @param up The up vector.
|
||||
*/
|
||||
void entityPositionLookAt(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
vec3 eye,
|
||||
vec3 target,
|
||||
vec3 up,
|
||||
vec3 eye
|
||||
vec3 up
|
||||
);
|
||||
|
||||
/**
|
||||
* 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 dest Destination matrix.
|
||||
* @param dest Destination matrix.
|
||||
*/
|
||||
void entityPositionGetTransform(
|
||||
const entityid_t entityId,
|
||||
@@ -65,9 +122,9 @@ void entityPositionGetTransform(
|
||||
/**
|
||||
* 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 dest Destination matrix.
|
||||
* @param dest Destination matrix.
|
||||
*/
|
||||
void entityPositionGetLocalTransform(
|
||||
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 componentid_t componentId,
|
||||
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 componentid_t componentId,
|
||||
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 componentid_t componentId,
|
||||
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 componentid_t componentId,
|
||||
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 componentid_t componentId,
|
||||
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 componentid_t componentId,
|
||||
vec3 scale
|
||||
@@ -133,9 +307,9 @@ void entityPositionSetScale(
|
||||
* Sets the parent of this entity's position component.
|
||||
* Pass ENTITY_ID_INVALID / COMPONENT_ID_INVALID to detach from any parent.
|
||||
*
|
||||
* @param entityId The child entity ID.
|
||||
* @param componentId The child component ID.
|
||||
* @param parentEntityId The parent entity ID.
|
||||
* @param entityId The child entity ID.
|
||||
* @param componentId The child component ID.
|
||||
* @param parentEntityId The parent entity ID.
|
||||
* @param parentComponentId The parent component ID.
|
||||
*/
|
||||
void entityPositionSetParent(
|
||||
@@ -147,7 +321,13 @@ void entityPositionSetParent(
|
||||
|
||||
/**
|
||||
* 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(
|
||||
const entityid_t entityId,
|
||||
@@ -155,13 +335,22 @@ entityposition_t *entityPositionGet(
|
||||
);
|
||||
|
||||
/**
|
||||
* Rebuilds the local transform matrix from the cached position/rotation/scale,
|
||||
* then marks this node and all descendants dirty.
|
||||
* Signals that the PRS cache was modified externally. Sets both
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
@@ -169,7 +358,7 @@ void entityPositionMarkDirty(entityposition_t *pos);
|
||||
* Disposes this entity and all of its position-component descendants
|
||||
* 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.
|
||||
*/
|
||||
void entityPositionDisposeDeep(
|
||||
@@ -180,5 +369,7 @@ void entityPositionDisposeDeep(
|
||||
/**
|
||||
* Decomposes the local transform matrix back into the position, rotation
|
||||
* (XYZ euler, radians), and scale cache fields.
|
||||
*
|
||||
* @param pos The position component to decompose.
|
||||
*/
|
||||
void entityPositionDecompose(entityposition_t *pos);
|
||||
|
||||
@@ -7,8 +7,12 @@
|
||||
|
||||
#include "entityrenderable.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "display/shader/shadermaterial.h"
|
||||
#include "display/shader/shaderunlit.h"
|
||||
#include "display/display.h"
|
||||
#include "display/mesh/cube.h"
|
||||
#include "util/memory.h"
|
||||
#include "assert/assert.h"
|
||||
|
||||
void entityRenderableInit(
|
||||
const entityid_t entityId,
|
||||
@@ -17,20 +21,22 @@ void entityRenderableInit(
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
r->type = ENTITY_RENDERABLE_TYPE_MATERIAL;
|
||||
r->mesh = &CUBE_MESH_SIMPLE;
|
||||
r->shader = &SHADER_UNLIT;
|
||||
r->material.unlit.color = COLOR_WHITE;
|
||||
memoryZero(r, sizeof(entityrenderable_t));
|
||||
r->type = ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL;
|
||||
r->data.material.shaderType = SHADER_LIST_SHADER_UNLIT;
|
||||
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 componentid_t componentId
|
||||
) {
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
return r->type;
|
||||
|
||||
}
|
||||
|
||||
void entityRenderableSetType(
|
||||
@@ -44,106 +50,79 @@ void entityRenderableSetType(
|
||||
r->type = type;
|
||||
}
|
||||
|
||||
mesh_t * entityRenderableGetMesh(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
return r->mesh;
|
||||
}
|
||||
|
||||
void entityRenderableSetMesh(
|
||||
void entityRenderableSetPriority(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
mesh_t *mesh
|
||||
const int8_t priority
|
||||
) {
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
r->mesh = mesh;
|
||||
r->priority = priority;
|
||||
}
|
||||
|
||||
shader_t * entityRenderableGetShader(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
return r->shader;
|
||||
}
|
||||
|
||||
void entityRenderableSetShader(
|
||||
void entityRenderableSetDraw(
|
||||
const entityid_t entityId,
|
||||
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(
|
||||
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(
|
||||
errorret_t entityRenderableDraw(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
return &r->material;
|
||||
}
|
||||
|
||||
void entityRenderableSetColor(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
const color_t color
|
||||
) {
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
r->material.unlit.color = color;
|
||||
}
|
||||
switch(r->type) {
|
||||
case ENTITY_RENDERABLE_TYPE_SPRITEBATCH: {
|
||||
const entityrenderablespritebatch_t *sb = &r->data.spritebatch;
|
||||
errorChain(displaySetState((displaystate_t){
|
||||
.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 entityRenderableSpriteBatchAdd(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
const spritebatchsprite_t *sprite
|
||||
) {
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
if(r->spritebatch.spriteCount >= ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX) return;
|
||||
r->spritebatch.sprites[r->spritebatch.spriteCount++] = *sprite;
|
||||
}
|
||||
case ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL: {
|
||||
const entityrenderablematerial_t *m = &r->data.material;
|
||||
errorChain(displaySetState(m->state));
|
||||
shader_t *shader = SHADER_LIST_DEFS[m->shaderType].shader;
|
||||
assertNotNull(shader, "Shader cannot be null for material type");
|
||||
errorChain(shaderBind(shader));
|
||||
errorChain(shaderSetMaterial(shader, &m->material));
|
||||
for(uint8_t i = 0; i < m->meshCount; i++) {
|
||||
errorChain(meshDraw(m->meshes[i], m->meshOffsets[i], m->meshCounts[i]));
|
||||
}
|
||||
errorOk();
|
||||
}
|
||||
|
||||
void entityRenderableSpriteBatchClear(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
r->spritebatch.spriteCount = 0;
|
||||
}
|
||||
|
||||
void entityRenderableDispose(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
if(
|
||||
r->type == ENTITY_RENDERABLE_TYPE_CALLBACK &&
|
||||
r->userFree &&
|
||||
r->user
|
||||
) {
|
||||
r->userFree(r->user);
|
||||
r->user = NULL;
|
||||
case ENTITY_RENDERABLE_TYPE_CUSTOM:
|
||||
return r->data.custom.draw(entityId, componentId, r->data.custom.drawUser);
|
||||
|
||||
default:
|
||||
assertUnreachable("Invalid renderable type");
|
||||
}
|
||||
r->mesh = NULL;
|
||||
r->shader = NULL;
|
||||
}
|
||||
|
||||
@@ -10,49 +10,66 @@
|
||||
#include "display/mesh/mesh.h"
|
||||
#include "display/shader/shadermaterial.h"
|
||||
#include "display/spritebatch/spritebatch.h"
|
||||
#include "display/displaystate.h"
|
||||
|
||||
#define ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX 64
|
||||
#define ENTITY_RENDERABLE_MESHES_MAX 8
|
||||
|
||||
typedef enum {
|
||||
ENTITY_RENDERABLE_TYPE_MATERIAL = 0,
|
||||
ENTITY_RENDERABLE_TYPE_CUSTOM = 0,
|
||||
ENTITY_RENDERABLE_TYPE_SPRITEBATCH,
|
||||
ENTITY_RENDERABLE_TYPE_CALLBACK,
|
||||
ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL,
|
||||
} 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 {
|
||||
spritebatchsprite_t sprites[ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX];
|
||||
uint16_t spriteCount;
|
||||
uint32_t spriteCount;
|
||||
texture_t *texture;
|
||||
} 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 {
|
||||
entityrenderabletype_t type;
|
||||
shader_t *shader;
|
||||
union {
|
||||
struct {
|
||||
mesh_t *mesh;
|
||||
shadermaterial_t material;
|
||||
};
|
||||
entityrenderablespritebatch_t spritebatch;
|
||||
struct {
|
||||
entityrenderablecallback_t callback;
|
||||
void (*userFree)(void *user);
|
||||
void *user;
|
||||
};
|
||||
};
|
||||
entityrenderabledata_t data;
|
||||
|
||||
/**
|
||||
* Render priority. 0 = auto (derived from type/flags). Higher values render
|
||||
* later (on top of lower values). Range: [-128..127] with 0 is auto.
|
||||
*/
|
||||
int8_t priority;
|
||||
} entityrenderable_t;
|
||||
|
||||
/**
|
||||
* 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(
|
||||
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(
|
||||
const entityid_t entityId,
|
||||
@@ -68,15 +88,12 @@ void entityRenderableDispose(
|
||||
);
|
||||
|
||||
/**
|
||||
* Gets the renderable type.
|
||||
*/
|
||||
entityrenderabletype_t entityRenderableGetType(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets the renderable type.
|
||||
* Sets the rendering type for the renderable component. Resets type-specific
|
||||
* data to zero.
|
||||
*
|
||||
* @param entityId The entity to configure.
|
||||
* @param componentId The renderable component.
|
||||
* @param type The rendering type to use.
|
||||
*/
|
||||
void entityRenderableSetType(
|
||||
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(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets the mesh pointer (ENTITY_RENDERABLE_TYPE_MATERIAL only).
|
||||
*/
|
||||
void entityRenderableSetMesh(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
mesh_t *mesh
|
||||
);
|
||||
|
||||
/**
|
||||
* Gets the shader pointer.
|
||||
*/
|
||||
shader_t * entityRenderableGetShader(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets the shader pointer.
|
||||
*/
|
||||
void entityRenderableSetShader(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
shader_t *shader
|
||||
);
|
||||
|
||||
/**
|
||||
* Gets a pointer to the shader material union
|
||||
* (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(
|
||||
void entityRenderableSetPriority(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
const int8_t priority
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets the draw callback, switching the type to ENTITY_RENDERABLE_TYPE_CUSTOM.
|
||||
*
|
||||
* @param entityId The entity to configure.
|
||||
* @param componentId The renderable component of the entity.
|
||||
* @param draw The draw callback to assign.
|
||||
* @param user Userdata passed to the callback.
|
||||
*/
|
||||
void entityRenderableSetDraw(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
errorret_t (*draw)(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
),
|
||||
void *user
|
||||
);
|
||||
|
||||
/**
|
||||
* Draws the entity using its renderable component data.
|
||||
*
|
||||
* @param entityId The entity to draw.
|
||||
* @param componentId The renderable component of the entity.
|
||||
* @return Any error state that happened.
|
||||
*/
|
||||
errorret_t entityRenderableDraw(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# Copyright (c) 2026 Dominic Masters
|
||||
#
|
||||
# This software is released under the MIT License.
|
||||
# https://opensource.org/licenses/MIT
|
||||
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
entityinteractable.c
|
||||
entityoverworld.c
|
||||
entityoverworldcamera.c
|
||||
entityoverworldtrigger.c
|
||||
entityplayer.c
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "entityinteractable.h"
|
||||
#include "entity/entitymanager.h"
|
||||
|
||||
void entityInteractableInit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityinteractable_t *inter = entityInteractableGet(entityId, componentId);
|
||||
inter->onInteract = NULL;
|
||||
inter->user = NULL;
|
||||
}
|
||||
|
||||
entityinteractable_t * entityInteractableGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
return componentGetData(entityId, componentId, COMPONENT_TYPE_INTERACTABLE);
|
||||
}
|
||||
|
||||
void entityInteractableSetCallback(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void (*onInteract)(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
),
|
||||
void *user
|
||||
) {
|
||||
entityinteractable_t *inter = entityInteractableGet(entityId, componentId);
|
||||
inter->onInteract = onInteract;
|
||||
inter->user = user;
|
||||
}
|
||||
|
||||
void entityInteractableTrigger(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityinteractable_t *inter = entityInteractableGet(entityId, componentId);
|
||||
if(inter->onInteract == NULL) return;
|
||||
inter->onInteract(entityId, componentId, inter->user);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "entity/entitybase.h"
|
||||
|
||||
typedef struct {
|
||||
void (*onInteract)(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
);
|
||||
void *user;
|
||||
} entityinteractable_t;
|
||||
|
||||
/**
|
||||
* Initializes the interactable component, clearing the callback and user pointer.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
*/
|
||||
void entityInteractableInit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns a pointer to the interactable component data.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
* @return Pointer to the entityinteractable_t data.
|
||||
*/
|
||||
entityinteractable_t * entityInteractableGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets the callback invoked when this interactable is triggered.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
* @param onInteract Function called on interaction, or NULL to clear.
|
||||
* @param user Arbitrary pointer forwarded to the callback.
|
||||
*/
|
||||
void entityInteractableSetCallback(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void (*onInteract)(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
),
|
||||
void *user
|
||||
);
|
||||
|
||||
/**
|
||||
* Fires the interactable's callback if one is set.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
*/
|
||||
void entityInteractableTrigger(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "entityoverworld.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/display/entityrenderable.h"
|
||||
#include "display/shader/shaderunlit.h"
|
||||
#include "display/mesh/cube.h"
|
||||
|
||||
void entityOverworldInit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityoverworld_t *ow = entityOverworldGet(entityId, componentId);
|
||||
ow->type = OVERWORLD_ENTITY_TYPE_NPC;
|
||||
ow->facing = FACING_DIR_DOWN;
|
||||
ow->renderCompId = entityGetComponent(entityId, COMPONENT_TYPE_RENDERABLE);
|
||||
if(ow->renderCompId != COMPONENT_ID_INVALID) {
|
||||
entityRenderableSetDraw(entityId, ow->renderCompId, entityOverworldDraw, NULL);
|
||||
}
|
||||
ow->physCompId = entityGetComponent(entityId, COMPONENT_TYPE_PHYSICS);
|
||||
}
|
||||
|
||||
entityoverworld_t * entityOverworldGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
return componentGetData(entityId, componentId, COMPONENT_TYPE_OVERWORLD);
|
||||
}
|
||||
|
||||
void entityOverworldSetType(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
const entityoverworldtype_t type
|
||||
) {
|
||||
entityOverworldGet(entityId, componentId)->type = type;
|
||||
}
|
||||
|
||||
errorret_t entityOverworldDraw(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
) {
|
||||
componentid_t owCompId = entityGetComponent(entityId, COMPONENT_TYPE_OVERWORLD);
|
||||
entityoverworld_t *ow = entityOverworldGet(entityId, owCompId);
|
||||
|
||||
color_t col = ow->type == OVERWORLD_ENTITY_TYPE_PLAYER ? COLOR_WHITE : COLOR_BLUE;
|
||||
errorChain(shaderSetColor(&SHADER_UNLIT, SHADER_UNLIT_COLOR, col));
|
||||
errorChain(shaderSetTexture(&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, NULL));
|
||||
return meshDraw(&CUBE_MESH_SIMPLE, 0, -1);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "error/error.h"
|
||||
#include "entity/entitybase.h"
|
||||
#include "overworld/facingdir.h"
|
||||
|
||||
typedef enum {
|
||||
OVERWORLD_ENTITY_TYPE_PLAYER = 0,
|
||||
OVERWORLD_ENTITY_TYPE_NPC = 1,
|
||||
} entityoverworldtype_t;
|
||||
|
||||
typedef struct {
|
||||
entityoverworldtype_t type;
|
||||
facingdir_t facing;
|
||||
componentid_t renderCompId;
|
||||
componentid_t physCompId;
|
||||
} entityoverworld_t;
|
||||
|
||||
/**
|
||||
* Initializes the overworld component, wiring up the draw callback if a
|
||||
* renderable component is already present on the entity.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
*/
|
||||
void entityOverworldInit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns a pointer to the overworld component data.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
* @return Pointer to the entityoverworld_t data.
|
||||
*/
|
||||
entityoverworld_t * entityOverworldGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets the overworld entity type.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
* @param type The type to assign.
|
||||
*/
|
||||
void entityOverworldSetType(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
const entityoverworldtype_t type
|
||||
);
|
||||
|
||||
/**
|
||||
* Draw callback registered on the renderable component.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId The renderable component's ID.
|
||||
* @param user Unused.
|
||||
* @return Error result.
|
||||
*/
|
||||
errorret_t entityOverworldDraw(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
);
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "entityoverworldcamera.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/display/entityposition.h"
|
||||
#include "entity/component/display/entitycamera.h"
|
||||
|
||||
void entityOverworldCameraInit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityoverworldcamera_t *cam = entityOverworldCameraGet(entityId, componentId);
|
||||
cam->targetEntityId = ENTITY_ID_INVALID;
|
||||
cam->targetPosCompId = COMPONENT_ID_INVALID;
|
||||
glm_vec3_zero(cam->targetOffset);
|
||||
glm_vec3_zero(cam->eyeOffset);
|
||||
cam->scale = 1.0f;
|
||||
}
|
||||
|
||||
entityoverworldcamera_t * entityOverworldCameraGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
return componentGetData(entityId, componentId, COMPONENT_TYPE_OVERWORLD_CAMERA);
|
||||
}
|
||||
|
||||
void entityOverworldCameraSetTarget(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
const entityid_t targetEntityId,
|
||||
const componentid_t targetPosCompId
|
||||
) {
|
||||
entityoverworldcamera_t *cam = entityOverworldCameraGet(entityId, componentId);
|
||||
cam->targetEntityId = targetEntityId;
|
||||
cam->targetPosCompId = targetPosCompId;
|
||||
}
|
||||
|
||||
errorret_t entityOverworldCameraRender(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityoverworldcamera_t *cam = entityOverworldCameraGet(entityId, componentId);
|
||||
|
||||
vec3 targetPos;
|
||||
entityPositionGetWorldPosition(
|
||||
cam->targetEntityId, cam->targetPosCompId, targetPos
|
||||
);
|
||||
|
||||
vec3 center = {
|
||||
targetPos[0] + cam->targetOffset[0],
|
||||
targetPos[1] + cam->targetOffset[1],
|
||||
targetPos[2] + cam->targetOffset[2]
|
||||
};
|
||||
|
||||
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
|
||||
componentid_t camComp = entityGetComponent(entityId, COMPONENT_TYPE_CAMERA);
|
||||
entityCameraLookAtPixelPerfect(
|
||||
entityId, posComp, camComp, center, cam->eyeOffset, cam->scale
|
||||
);
|
||||
errorOk();
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "entity/entitybase.h"
|
||||
#include "error/error.h"
|
||||
|
||||
typedef struct {
|
||||
entityid_t targetEntityId;
|
||||
componentid_t targetPosCompId;
|
||||
vec3 targetOffset;
|
||||
vec3 eyeOffset;
|
||||
float_t scale;
|
||||
} entityoverworldcamera_t;
|
||||
|
||||
/**
|
||||
* Initializes the overworld camera component.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
*/
|
||||
void entityOverworldCameraInit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns a pointer to the overworld camera component data.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
* @return Pointer to the entityoverworldcamera_t data.
|
||||
*/
|
||||
entityoverworldcamera_t * entityOverworldCameraGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets the entity and position component the camera will follow.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
* @param targetEntityId Entity to follow.
|
||||
* @param targetPosCompId Position component on the target entity.
|
||||
*/
|
||||
void entityOverworldCameraSetTarget(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
const entityid_t targetEntityId,
|
||||
const componentid_t targetPosCompId
|
||||
);
|
||||
|
||||
/**
|
||||
* Render callback: updates the camera position to track the target entity.
|
||||
* Called automatically each frame via componentRenderAll.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t entityOverworldCameraRender(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "entityoverworldtrigger.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/display/entityposition.h"
|
||||
|
||||
static void entityOverworldTriggerUpdate(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
) {
|
||||
entityoverworldtrigger_t *t = entityOverworldTriggerGet(entityId, componentId);
|
||||
|
||||
// Find the player position.
|
||||
vec3 playerPos;
|
||||
bool_t playerFound = false;
|
||||
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
|
||||
if((ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) == 0) continue;
|
||||
if(entityGetComponent(i, COMPONENT_TYPE_PLAYER) == COMPONENT_ID_INVALID) continue;
|
||||
componentid_t posComp = entityGetComponent(i, COMPONENT_TYPE_POSITION);
|
||||
if(posComp == COMPONENT_ID_INVALID) continue;
|
||||
entityPositionGetWorldPosition(i, posComp, playerPos);
|
||||
playerFound = true;
|
||||
break;
|
||||
}
|
||||
|
||||
bool_t wasInside = t->playerInside;
|
||||
bool_t nowInside = playerFound && (
|
||||
playerPos[0] >= t->min[0] && playerPos[0] <= t->max[0] &&
|
||||
playerPos[1] >= t->min[1] && playerPos[1] <= t->max[1] &&
|
||||
playerPos[2] >= t->min[2] && playerPos[2] <= t->max[2]
|
||||
);
|
||||
t->playerInside = nowInside;
|
||||
|
||||
if(nowInside) {
|
||||
if(!wasInside && t->onEnter) t->onEnter(entityId, componentId, t->user);
|
||||
if(t->onStay) t->onStay(entityId, componentId, t->user);
|
||||
} else {
|
||||
if(wasInside && t->onExit) t->onExit(entityId, componentId, t->user);
|
||||
if(t->onOutside) t->onOutside(entityId, componentId, t->user);
|
||||
}
|
||||
}
|
||||
|
||||
void entityOverworldTriggerInit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityoverworldtrigger_t *t = entityOverworldTriggerGet(entityId, componentId);
|
||||
glm_vec3_zero(t->min);
|
||||
glm_vec3_zero(t->max);
|
||||
t->playerInside = false;
|
||||
t->onEnter = NULL;
|
||||
t->onExit = NULL;
|
||||
t->onStay = NULL;
|
||||
t->onOutside = NULL;
|
||||
t->user = NULL;
|
||||
entityUpdateAdd(entityId, entityOverworldTriggerUpdate, componentId, NULL);
|
||||
}
|
||||
|
||||
entityoverworldtrigger_t * entityOverworldTriggerGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
return componentGetData(
|
||||
entityId, componentId, COMPONENT_TYPE_OVERWORLD_TRIGGER
|
||||
);
|
||||
}
|
||||
|
||||
void entityOverworldTriggerSetBounds(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
const vec3 min,
|
||||
const vec3 max
|
||||
) {
|
||||
entityoverworldtrigger_t *t = entityOverworldTriggerGet(entityId, componentId);
|
||||
glm_vec3_copy((float_t*)min, t->min);
|
||||
glm_vec3_copy((float_t*)max, t->max);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "entity/entitybase.h"
|
||||
|
||||
typedef void (*entityoverworldtriggercallback_t)(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
);
|
||||
|
||||
typedef struct {
|
||||
vec3 min;
|
||||
vec3 max;
|
||||
bool_t playerInside;
|
||||
entityoverworldtriggercallback_t onEnter;
|
||||
entityoverworldtriggercallback_t onExit;
|
||||
entityoverworldtriggercallback_t onStay;
|
||||
entityoverworldtriggercallback_t onOutside;
|
||||
void *user;
|
||||
} entityoverworldtrigger_t;
|
||||
|
||||
/**
|
||||
* Initializes the overworld trigger component and registers its update
|
||||
* callback with the entity manager. The trigger is entirely self-contained
|
||||
* after init — no scene-level wiring required.
|
||||
*/
|
||||
void entityOverworldTriggerInit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns a pointer to the overworld trigger component data.
|
||||
*/
|
||||
entityoverworldtrigger_t * entityOverworldTriggerGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets the trigger AABB bounds.
|
||||
*/
|
||||
void entityOverworldTriggerSetBounds(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
const vec3 min,
|
||||
const vec3 max
|
||||
);
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "entityplayer.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/display/entityposition.h"
|
||||
#include "entity/component/physics/entityphysics.h"
|
||||
#include "entity/component/overworld/entityoverworld.h"
|
||||
#include "entity/component/overworld/entityinteractable.h"
|
||||
#include "input/input.h"
|
||||
|
||||
void entityPlayerInit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityplayer_t *player = entityPlayerGet(entityId, componentId);
|
||||
player->speed = ENTITY_PLAYER_SPEED;
|
||||
player->runSpeed = ENTITY_PLAYER_RUN_SPEED;
|
||||
}
|
||||
|
||||
entityplayer_t * entityPlayerGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
return componentGetData(entityId, componentId, COMPONENT_TYPE_PLAYER);
|
||||
}
|
||||
|
||||
void entityPlayerUpdate(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
) {
|
||||
entityplayer_t *player = entityPlayerGet(entityId, componentId);
|
||||
|
||||
vec2 dir;
|
||||
inputAngle2D(
|
||||
INPUT_ACTION_LEFT, INPUT_ACTION_RIGHT,
|
||||
INPUT_ACTION_UP, INPUT_ACTION_DOWN,
|
||||
dir
|
||||
);
|
||||
|
||||
float_t speed = (
|
||||
inputIsDown(INPUT_ACTION_CANCEL) ? player->runSpeed : player->speed
|
||||
);
|
||||
|
||||
componentid_t owCompId = entityGetComponent(entityId, COMPONENT_TYPE_OVERWORLD);
|
||||
entityoverworld_t *ow = entityOverworldGet(entityId, owCompId);
|
||||
|
||||
if(ow && glm_vec2_norm(dir) > 0.0f) {
|
||||
if(fabsf(dir[0]) >= fabsf(dir[1])) {
|
||||
ow->facing = dir[0] > 0.0f ? FACING_DIR_RIGHT : FACING_DIR_LEFT;
|
||||
} else {
|
||||
ow->facing = dir[1] > 0.0f ? FACING_DIR_DOWN : FACING_DIR_UP;
|
||||
}
|
||||
}
|
||||
|
||||
vec3 vel;
|
||||
entityPhysicsGetVelocity(entityId, ow->physCompId, vel);
|
||||
vel[0] = dir[0] * speed;
|
||||
vel[2] = dir[1] * speed;
|
||||
entityPhysicsSetVelocity(entityId, ow->physCompId, vel);
|
||||
|
||||
if(!inputPressed(INPUT_ACTION_ACCEPT)) return;
|
||||
|
||||
vec3 playerPos;
|
||||
componentid_t playerPosCompId = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
|
||||
if(playerPosCompId == COMPONENT_ID_INVALID) return;
|
||||
entityPositionGetWorldPosition(entityId, playerPosCompId, playerPos);
|
||||
|
||||
vec2 facingDir;
|
||||
facingDirToVec2(ow ? ow->facing : FACING_DIR_DOWN, facingDir);
|
||||
|
||||
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
|
||||
if((ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) == 0) continue;
|
||||
if(i == entityId) continue;
|
||||
|
||||
componentid_t interComp = entityGetComponent(i, COMPONENT_TYPE_INTERACTABLE);
|
||||
if(interComp == COMPONENT_ID_INVALID) continue;
|
||||
|
||||
componentid_t posComp = entityGetComponent(i, COMPONENT_TYPE_POSITION);
|
||||
if(posComp == COMPONENT_ID_INVALID) continue;
|
||||
|
||||
vec3 targetPos;
|
||||
entityPositionGetWorldPosition(i, posComp, targetPos);
|
||||
|
||||
vec2 toTarget = {
|
||||
targetPos[0] - playerPos[0],
|
||||
targetPos[2] - playerPos[2],
|
||||
};
|
||||
float_t forward = glm_vec2_dot(facingDir, toTarget);
|
||||
if(forward <= 0.0f || forward > ENTITY_PLAYER_INTERACT_RANGE) continue;
|
||||
|
||||
float_t lateral = fabsf(
|
||||
facingDir[0] * toTarget[1] - facingDir[1] * toTarget[0]
|
||||
);
|
||||
if(lateral > ENTITY_PLAYER_INTERACT_LATERAL) continue;
|
||||
|
||||
entityInteractableTrigger(i, interComp);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "error/error.h"
|
||||
#include "entity/entitybase.h"
|
||||
|
||||
#define ENTITY_PLAYER_SPEED 4.0f
|
||||
#define ENTITY_PLAYER_RUN_SPEED 8.0f
|
||||
#define ENTITY_PLAYER_INTERACT_RANGE 1.5f
|
||||
#define ENTITY_PLAYER_INTERACT_LATERAL 0.6f
|
||||
|
||||
typedef struct {
|
||||
float_t speed;
|
||||
float_t runSpeed;
|
||||
} entityplayer_t;
|
||||
|
||||
/**
|
||||
* Initializes the player component.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
*/
|
||||
void entityPlayerInit(const entityid_t entityId, const componentid_t componentId);
|
||||
|
||||
/**
|
||||
* Returns a pointer to the player component data.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
* @return Pointer to the entityplayer_t data.
|
||||
*/
|
||||
entityplayer_t * entityPlayerGet(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
|
||||
/**
|
||||
* Reads input, moves the player, updates facing direction, and checks for
|
||||
* interactable entities in front of the player when accept is pressed.
|
||||
*
|
||||
* @param entityId The owning entity.
|
||||
* @param componentId This component's ID.
|
||||
*/
|
||||
void entityPlayerUpdate(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId
|
||||
);
|
||||
@@ -10,15 +10,26 @@
|
||||
#include "entity/component/display/entityrenderable.h"
|
||||
#include "entity/component/physics/entityphysics.h"
|
||||
#include "entity/component/trigger/entitytrigger.h"
|
||||
#include "entity/component/overworld/entityoverworld.h"
|
||||
#include "entity/component/overworld/entityoverworldtrigger.h"
|
||||
#include "entity/component/overworld/entityplayer.h"
|
||||
#include "entity/component/overworld/entityinteractable.h"
|
||||
#include "entity/component/overworld/entityoverworldcamera.h"
|
||||
|
||||
// Name (Uppercase)
|
||||
// Structure
|
||||
// Field name (lowercase)
|
||||
// Init function (optional)
|
||||
// Dispose function (optional)
|
||||
// Render function (optional)
|
||||
|
||||
X(POSITION, entityposition_t, position, entityPositionInit, NULL)
|
||||
X(CAMERA, entitycamera_t, camera, entityCameraInit, NULL)
|
||||
X(RENDERABLE, entityrenderable_t, renderable, entityRenderableInit, entityRenderableDispose)
|
||||
X(PHYSICS, entityphysics_t, physics, entityPhysicsInit, entityPhysicsDispose)
|
||||
X(TRIGGER, entitytrigger_t, trigger, entityTriggerInit, NULL)
|
||||
X(POSITION, entityposition_t, position, entityPositionInit, NULL, NULL)
|
||||
X(CAMERA, entitycamera_t, camera, entityCameraInit, NULL, NULL)
|
||||
X(RENDERABLE, entityrenderable_t, renderable, entityRenderableInit, entityRenderableDispose, NULL)
|
||||
X(PHYSICS, entityphysics_t, physics, entityPhysicsInit, entityPhysicsDispose, NULL)
|
||||
X(TRIGGER, entitytrigger_t, trigger, entityTriggerInit, NULL, NULL)
|
||||
X(OVERWORLD, entityoverworld_t, overworld, entityOverworldInit, NULL, NULL)
|
||||
X(PLAYER, entityplayer_t, player, entityPlayerInit, NULL, NULL)
|
||||
X(INTERACTABLE, entityinteractable_t, interactable, entityInteractableInit, NULL, NULL)
|
||||
X(OVERWORLD_CAMERA, entityoverworldcamera_t, overworldCamera, entityOverworldCameraInit, NULL, entityOverworldCameraRender)
|
||||
X(OVERWORLD_TRIGGER, entityoverworldtrigger_t, overworldTrigger, entityOverworldTriggerInit, NULL, NULL)
|
||||
|
||||
@@ -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) {
|
||||
componentindex_t compInd;
|
||||
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++) {
|
||||
compInd = componentGetIndex(entityId, i);
|
||||
componenttype_t type = ENTITY_MANAGER.components[compInd].type;
|
||||
@@ -95,4 +106,66 @@ void entityDispose(const entityid_t entityId) {
|
||||
}
|
||||
|
||||
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_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 {
|
||||
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;
|
||||
|
||||
/**
|
||||
@@ -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.
|
||||
*/
|
||||
@@ -60,4 +85,47 @@ void entityDispose(const entityid_t entityId);
|
||||
*
|
||||
* @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
|
||||
#include "dusk.h"
|
||||
|
||||
#define ENTITY_COUNT_MAX 20
|
||||
#define ENTITY_COMPONENT_COUNT_MAX 8
|
||||
#define ENTITY_COUNT_MAX 64
|
||||
#define ENTITY_COMPONENT_COUNT_MAX 16
|
||||
|
||||
#define ENTITY_ID_INVALID 0xFF
|
||||
#define COMPONENT_ID_INVALID 0xFF
|
||||
#define ENTITY_ID_INVALID 0xFF
|
||||
#define COMPONENT_ID_INVALID 0xFF
|
||||
|
||||
typedef uint8_t entityid_t;
|
||||
typedef uint8_t componentid_t;
|
||||
|
||||
@@ -16,7 +16,7 @@ void entityManagerInit(void) {
|
||||
memoryZero(&ENTITY_MANAGER, sizeof(entitymanager_t));
|
||||
memorySet(
|
||||
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(
|
||||
@@ -36,6 +36,16 @@ entityid_t entityManagerAdd() {
|
||||
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) {
|
||||
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
|
||||
if((ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) == 0) continue;
|
||||
|
||||
@@ -28,6 +28,11 @@ void entityManagerInit(void);
|
||||
*/
|
||||
entityid_t entityManagerAdd();
|
||||
|
||||
/**
|
||||
* Updates all active entities.
|
||||
*/
|
||||
void entityManagerUpdate(void);
|
||||
|
||||
/**
|
||||
* Disposes of the entity manager, in turn freeing all entities and components.
|
||||
*/
|
||||
|
||||
+22
-2
@@ -162,6 +162,28 @@ void inputAxis2D(
|
||||
result[1] = inputAxis(negY, posY);
|
||||
}
|
||||
|
||||
void inputAngle2D(
|
||||
const inputaction_t negX, const inputaction_t posX,
|
||||
const inputaction_t negY, const inputaction_t posY,
|
||||
vec2 result
|
||||
) {
|
||||
assertNotNull(result, "Result vector cannot be null");
|
||||
float_t x = inputAxis(negX, posX);
|
||||
float_t y = inputAxis(negY, posY);
|
||||
float_t mag = sqrtf(x * x + y * y);
|
||||
if(mag <= 0.0f) {
|
||||
result[0] = 0.0f;
|
||||
result[1] = 0.0f;
|
||||
return;
|
||||
}
|
||||
if(mag > 1.0f) {
|
||||
x /= mag;
|
||||
y /= mag;
|
||||
}
|
||||
result[0] = x;
|
||||
result[1] = y;
|
||||
}
|
||||
|
||||
void inputBind(const inputbutton_t button, const inputaction_t act) {
|
||||
assertTrue(
|
||||
act < INPUT_ACTION_COUNT,
|
||||
@@ -177,8 +199,6 @@ void inputBind(const inputbutton_t button, const inputaction_t act) {
|
||||
data->action = act;
|
||||
}
|
||||
|
||||
|
||||
|
||||
float_t inputDeadzone(const float_t rawValue, const float_t deadzone) {
|
||||
if(rawValue < deadzone) return 0.0f;
|
||||
return (rawValue - deadzone) / (1.0f - deadzone);
|
||||
|
||||
@@ -126,6 +126,22 @@ void inputAxis2D(
|
||||
vec2 result
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns an angled 2D vector based on the input of 4 actions. Functionally
|
||||
* using atan2 to get the angle of the input then multiplying by a unit vector.
|
||||
*
|
||||
* @param negX The action representing the negative direction of the X axis.
|
||||
* @param posX The action representing the positive direction of the X axis.
|
||||
* @param negY The action representing the negative direction of the Y axis.
|
||||
* @param posY The action representing the positive direction of the Y axis.
|
||||
* @param result A vec2 to store the resulting axis values (-1.0f to 1.0f).
|
||||
*/
|
||||
void inputAngle2D(
|
||||
const inputaction_t negX, const inputaction_t posX,
|
||||
const inputaction_t negY, const inputaction_t posY,
|
||||
vec2 result
|
||||
);
|
||||
|
||||
/**
|
||||
* Binds an input button to an action.
|
||||
*
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
facingdir.c
|
||||
maptypes.c
|
||||
map.c
|
||||
mapchunk.c
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "facingdir.h"
|
||||
|
||||
void facingDirToVec2(facingdir_t facing, vec2 dest) {
|
||||
switch(facing) {
|
||||
case FACING_DIR_UP: dest[0] = 0.0f; dest[1] = -1.0f; return;
|
||||
case FACING_DIR_LEFT: dest[0] = -1.0f; dest[1] = 0.0f; return;
|
||||
case FACING_DIR_RIGHT: dest[0] = 1.0f; dest[1] = 0.0f; return;
|
||||
default: dest[0] = 0.0f; dest[1] = 1.0f; return;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "dusk.h"
|
||||
|
||||
typedef enum {
|
||||
FACING_DIR_DOWN = 0,
|
||||
FACING_DIR_UP = 1,
|
||||
FACING_DIR_LEFT = 2,
|
||||
FACING_DIR_RIGHT = 3,
|
||||
FACING_DIR_SOUTH = FACING_DIR_DOWN,
|
||||
FACING_DIR_NORTH = FACING_DIR_UP,
|
||||
FACING_DIR_WEST = FACING_DIR_LEFT,
|
||||
FACING_DIR_EAST = FACING_DIR_RIGHT,
|
||||
} facingdir_t;
|
||||
|
||||
/**
|
||||
* Converts a facing direction to a normalized XZ vec2.
|
||||
*
|
||||
* @param facing The facing direction.
|
||||
* @param dest Output vec2 — [0] is X, [1] is Z.
|
||||
*/
|
||||
void facingDirToVec2(facingdir_t facing, vec2 dest);
|
||||
@@ -11,7 +11,6 @@
|
||||
#include "util/memory.h"
|
||||
#include "util/string.h"
|
||||
#include "console/console.h"
|
||||
#include "script/module/overworld/modulemap.h"
|
||||
|
||||
map_t MAP;
|
||||
|
||||
@@ -29,7 +28,6 @@ chunkindex_t mapChunkRelToIndex(
|
||||
|
||||
void mapInit(void) {
|
||||
memoryZero(&MAP, sizeof(map_t));
|
||||
MAP.scriptRef = MAP_SCRIPT_REF_NONE;
|
||||
}
|
||||
|
||||
errorret_t mapLoad(const char_t *handle) {
|
||||
@@ -39,31 +37,11 @@ errorret_t mapLoad(const char_t *handle) {
|
||||
if(mapIsLoaded()) mapDispose();
|
||||
|
||||
memoryZero(&MAP, sizeof(map_t));
|
||||
MAP.scriptRef = MAP_SCRIPT_REF_NONE;
|
||||
stringCopy(MAP.handle, handle, MAP_HANDLE_MAX);
|
||||
|
||||
char_t path[ASSET_FILE_NAME_MAX];
|
||||
stringFormat(path, sizeof(path), "maps/%s/init.js", handle);
|
||||
|
||||
jerry_value_t mapClass = MAP_SCRIPT_REF_NONE;
|
||||
errorChain(scriptManagerExecFile(path, &mapClass));
|
||||
|
||||
if(!jerry_value_is_function(mapClass)) {
|
||||
if(mapClass != MAP_SCRIPT_REF_NONE) jerry_value_free(mapClass);
|
||||
errorThrow("Map '%s' must export a constructor function", handle);
|
||||
}
|
||||
|
||||
jerry_value_t mapObj = jerry_construct(mapClass, NULL, 0);
|
||||
jerry_value_free(mapClass);
|
||||
|
||||
if(jerry_value_is_exception(mapObj)) {
|
||||
char_t errMsg[512];
|
||||
moduleBaseExceptionMessage(mapObj, errMsg, sizeof(errMsg));
|
||||
jerry_value_free(mapObj);
|
||||
errorThrow("Map '%s' constructor threw: %s", handle, errMsg);
|
||||
}
|
||||
|
||||
MAP.scriptRef = mapObj;
|
||||
consolePrint("Map loaded: %s", handle);
|
||||
errorOk();
|
||||
}
|
||||
@@ -160,16 +138,11 @@ mapchunk_t *mapGetChunkAt(chunkpos_t pos) {
|
||||
|
||||
errorret_t mapUpdate(void) {
|
||||
if(!MAP.loaded) errorOk();
|
||||
errorChain(moduleMapCall("update"));
|
||||
errorOk();
|
||||
}
|
||||
|
||||
void mapDispose(void) {
|
||||
consolePrint("Map disposing: %s", MAP.handle);
|
||||
if(MAP.scriptRef != MAP_SCRIPT_REF_NONE) {
|
||||
moduleMapCall("dispose");
|
||||
moduleMapReset();
|
||||
}
|
||||
if(!MAP.loaded) return;
|
||||
for(chunkindex_t i = 0; i < MAP_CHUNKS_COUNT; i++) {
|
||||
mapChunkUnload(&MAP.chunks[i]);
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
#pragma once
|
||||
#include "mapchunk.h"
|
||||
#include "error/error.h"
|
||||
#include "script/scriptmanager.h"
|
||||
|
||||
#define MAP_NAME_MAX 64
|
||||
#define MAP_HANDLE_MAX 32
|
||||
@@ -27,12 +26,8 @@ typedef struct {
|
||||
mapchunk_t *chunkOrder[MAP_CHUNKS_COUNT];
|
||||
chunkpos_t chunkPosition;
|
||||
bool_t loaded;
|
||||
jerry_value_t scriptRef;
|
||||
} map_t;
|
||||
|
||||
/** Sentinel value meaning no map script is loaded. */
|
||||
#define MAP_SCRIPT_REF_NONE ((jerry_value_t)0)
|
||||
|
||||
extern map_t MAP;
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,11 +12,9 @@
|
||||
#include "util/string.h"
|
||||
#include "asset/asset.h"
|
||||
#include "console/console.h"
|
||||
#include "script/module/overworld/modulemapchunk.h"
|
||||
|
||||
errorret_t mapChunkLoad(mapchunk_t *chunk) {
|
||||
chunk->entityCount = 0;
|
||||
chunk->scriptRef = MAP_CHUNK_SCRIPT_REF_NONE;
|
||||
memoryZero(chunk->entities, sizeof(chunk->entities));
|
||||
|
||||
if(MAP.handle[0] == '\0') errorOk();
|
||||
@@ -33,31 +31,6 @@ errorret_t mapChunkLoad(mapchunk_t *chunk) {
|
||||
|
||||
if(!assetFileExists(path)) errorOk();
|
||||
|
||||
jerry_value_t chunkClass = MAP_CHUNK_SCRIPT_REF_NONE;
|
||||
errorChain(scriptManagerExecFile(path, &chunkClass));
|
||||
|
||||
if(!jerry_value_is_function(chunkClass)) {
|
||||
if(chunkClass != MAP_CHUNK_SCRIPT_REF_NONE) jerry_value_free(chunkClass);
|
||||
errorThrow("Chunk script '%s' must export a constructor", path);
|
||||
}
|
||||
|
||||
jerry_value_t args[3] = {
|
||||
jerry_number((double)chunk->position.x),
|
||||
jerry_number((double)chunk->position.y),
|
||||
jerry_number((double)chunk->position.z),
|
||||
};
|
||||
jerry_value_t chunkObj = jerry_construct(chunkClass, args, 3);
|
||||
jerry_value_free(chunkClass);
|
||||
jerry_value_free(args[0]);
|
||||
jerry_value_free(args[1]);
|
||||
jerry_value_free(args[2]);
|
||||
|
||||
if(jerry_value_is_exception(chunkObj)) {
|
||||
jerry_value_free(chunkObj);
|
||||
errorThrow("Chunk script '%s' constructor threw", path);
|
||||
}
|
||||
|
||||
chunk->scriptRef = chunkObj;
|
||||
consolePrint(
|
||||
"Chunk loaded: %s [%d,%d,%d]",
|
||||
path,
|
||||
@@ -75,19 +48,6 @@ void mapChunkUnload(mapchunk_t *chunk) {
|
||||
(int)chunk->position.y,
|
||||
(int)chunk->position.z
|
||||
);
|
||||
if(chunk->scriptRef != MAP_CHUNK_SCRIPT_REF_NONE) {
|
||||
jerry_value_t key = jerry_string_sz("dispose");
|
||||
jerry_value_t fn = jerry_object_get(chunk->scriptRef, key);
|
||||
jerry_value_free(key);
|
||||
|
||||
if(jerry_value_is_function(fn)) {
|
||||
jerry_value_t result = jerry_call(fn, chunk->scriptRef, NULL, 0);
|
||||
jerry_value_free(result);
|
||||
}
|
||||
jerry_value_free(fn);
|
||||
jerry_value_free(chunk->scriptRef);
|
||||
chunk->scriptRef = MAP_CHUNK_SCRIPT_REF_NONE;
|
||||
}
|
||||
|
||||
for(uint8_t i = 0; i < chunk->entityCount; i++) {
|
||||
entityDispose(chunk->entities[i]);
|
||||
|
||||
@@ -9,18 +9,13 @@
|
||||
#include "maptypes.h"
|
||||
#include "entity/entitybase.h"
|
||||
#include "error/error.h"
|
||||
#include "script/scriptmanager.h"
|
||||
|
||||
#define MAP_CHUNK_ENTITY_COUNT_MAX 64
|
||||
|
||||
/** Sentinel value meaning no chunk script is loaded. */
|
||||
#define MAP_CHUNK_SCRIPT_REF_NONE ((jerry_value_t)0)
|
||||
|
||||
typedef struct {
|
||||
chunkpos_t position;
|
||||
entityid_t entities[MAP_CHUNK_ENTITY_COUNT_MAX];
|
||||
uint8_t entityCount;
|
||||
jerry_value_t scriptRef;
|
||||
} mapchunk_t;
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,4 +7,10 @@
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
scene.c
|
||||
)
|
||||
scenerenderpipeline.c
|
||||
)
|
||||
|
||||
# Subdirectories
|
||||
add_subdirectory(initial)
|
||||
add_subdirectory(test)
|
||||
add_subdirectory(overworld)
|
||||
@@ -6,5 +6,5 @@
|
||||
# Sources
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
assetscriptloader.c
|
||||
initialscene.c
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "initialscene.h"
|
||||
#include "console/console.h"
|
||||
#include "scene/scene.h"
|
||||
#include "time/time.h"
|
||||
#include "ui/uiloading.h"
|
||||
|
||||
void initialSceneInit(void) {
|
||||
consolePrint("Initial scene initialized");
|
||||
SCENE.data.initial.timer = 0.0f;
|
||||
SCENE.data.initial.hiding = false;
|
||||
uiLoadingShow(NULL, NULL);
|
||||
}
|
||||
|
||||
errorret_t initialSceneUpdate(void) {
|
||||
initialscene_t *scene = &SCENE.data.initial;
|
||||
if(scene->hiding) errorOk();
|
||||
|
||||
scene->timer += TIME.delta;
|
||||
if(scene->timer >= INITIAL_SCENE_WAIT) {
|
||||
scene->hiding = true;
|
||||
uiLoadingHide(NULL, NULL);
|
||||
}
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
void initialSceneDispose(void) {
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "error/error.h"
|
||||
|
||||
#define INITIAL_SCENE_WAIT 2.0f
|
||||
|
||||
typedef struct {
|
||||
float_t timer;
|
||||
bool_t hiding;
|
||||
} initialscene_t;
|
||||
|
||||
void initialSceneInit(void);
|
||||
errorret_t initialSceneUpdate(void);
|
||||
void initialSceneDispose(void);
|
||||
@@ -0,0 +1,12 @@
|
||||
# Copyright (c) 2026 Dominic Masters
|
||||
#
|
||||
# This software is released under the MIT License.
|
||||
# https://opensource.org/licenses/MIT
|
||||
|
||||
target_sources(${DUSK_LIBRARY_TARGET_NAME}
|
||||
PUBLIC
|
||||
overworldground.c
|
||||
overworldnpc.c
|
||||
overworldplayer.c
|
||||
overworldscene.c
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "overworldground.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/physics/entityphysics.h"
|
||||
|
||||
#define OVERWORLD_GROUND_SIZE 20.0f
|
||||
|
||||
void overworldGroundAdd(overworldground_t *ground) {
|
||||
ground->entityId = entityManagerAdd();
|
||||
ground->posCompId = entityAddComponent(
|
||||
ground->entityId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
entityAddComponent(ground->entityId, COMPONENT_TYPE_RENDERABLE);
|
||||
vec3 pos = { -OVERWORLD_GROUND_SIZE, 0.0f, -OVERWORLD_GROUND_SIZE };
|
||||
vec3 scale = { OVERWORLD_GROUND_SIZE * 2.0f, 1.0f, OVERWORLD_GROUND_SIZE * 2.0f };
|
||||
entityPositionSetLocalPosition(ground->entityId, ground->posCompId, pos);
|
||||
entityPositionSetLocalScale(ground->entityId, ground->posCompId, scale);
|
||||
|
||||
// Separate physics entity centered on the finite ground area.
|
||||
// The visual entity's position is its corner {-size, 0, -size}, not its
|
||||
// center, so a box collider on it would be misplaced. This entity sits at
|
||||
// the true center {0, -0.5, 0} with halfExtents matching the visual extent.
|
||||
ground->floorEntityId = entityManagerAdd();
|
||||
componentid_t floorPosComp = entityAddComponent(
|
||||
ground->floorEntityId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
componentid_t floorPhysComp = entityAddComponent(
|
||||
ground->floorEntityId, COMPONENT_TYPE_PHYSICS
|
||||
);
|
||||
|
||||
vec3 floorPos = { 0.0f, -0.5f, 0.0f };
|
||||
entityPositionSetLocalPosition(ground->floorEntityId, floorPosComp, floorPos);
|
||||
entityPhysicsSetBodyType(ground->floorEntityId, floorPhysComp, PHYSICS_BODY_STATIC);
|
||||
physicsshape_t shape = {
|
||||
.type = PHYSICS_SHAPE_CUBE,
|
||||
.data.cube = { .halfExtents = {
|
||||
OVERWORLD_GROUND_SIZE,
|
||||
0.5f,
|
||||
OVERWORLD_GROUND_SIZE
|
||||
}}
|
||||
};
|
||||
entityPhysicsSetShape(ground->floorEntityId, floorPhysComp, shape);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "entity/entitybase.h"
|
||||
|
||||
typedef struct {
|
||||
entityid_t entityId;
|
||||
componentid_t posCompId;
|
||||
entityid_t floorEntityId;
|
||||
} overworldground_t;
|
||||
|
||||
/**
|
||||
* Creates the ground entity and adds it to the world.
|
||||
*
|
||||
* @param ground The ground state to initialize.
|
||||
*/
|
||||
void overworldGroundAdd(overworldground_t *ground);
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "overworldnpc.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/physics/entityphysics.h"
|
||||
#include "entity/component/trigger/entitytrigger.h"
|
||||
#include "entity/component/overworld/entityoverworld.h"
|
||||
#include "entity/component/overworld/entityinteractable.h"
|
||||
|
||||
void overworldNpcAdd(overworldnpc_t *npc, vec3 position) {
|
||||
npc->entityId = entityManagerAdd();
|
||||
npc->posCompId = entityAddComponent(npc->entityId, COMPONENT_TYPE_POSITION);
|
||||
entityAddComponent(npc->entityId, COMPONENT_TYPE_RENDERABLE);
|
||||
entityAddComponent(npc->entityId, COMPONENT_TYPE_PHYSICS);
|
||||
npc->overworldCompId = entityAddComponent(npc->entityId, COMPONENT_TYPE_OVERWORLD);
|
||||
npc->triggerCompId = entityAddComponent(npc->entityId, COMPONENT_TYPE_TRIGGER);
|
||||
npc->interactableCompId = entityAddComponent(
|
||||
npc->entityId, COMPONENT_TYPE_INTERACTABLE
|
||||
);
|
||||
|
||||
entityPositionSetLocalPosition(npc->entityId, npc->posCompId, position);
|
||||
|
||||
componentid_t physCompId = entityOverworldGet(npc->entityId, npc->overworldCompId)->physCompId;
|
||||
entityPhysicsSetBodyType(npc->entityId, physCompId, PHYSICS_BODY_STATIC);
|
||||
physicsshape_t shape = {
|
||||
.type = PHYSICS_SHAPE_CAPSULE,
|
||||
.data.capsule = { .radius = 0.4f, .halfHeight = 0.1f }
|
||||
};
|
||||
entityPhysicsSetShape(npc->entityId, physCompId, shape);
|
||||
|
||||
vec3 min = {
|
||||
position[0] - OVERWORLD_NPC_INTERACT_RANGE,
|
||||
position[1] - OVERWORLD_NPC_INTERACT_RANGE,
|
||||
position[2] - OVERWORLD_NPC_INTERACT_RANGE
|
||||
};
|
||||
vec3 max = {
|
||||
position[0] + OVERWORLD_NPC_INTERACT_RANGE,
|
||||
position[1] + OVERWORLD_NPC_INTERACT_RANGE,
|
||||
position[2] + OVERWORLD_NPC_INTERACT_RANGE
|
||||
};
|
||||
entityTriggerSetBounds(npc->entityId, npc->triggerCompId, min, max);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "entity/entitybase.h"
|
||||
|
||||
#define OVERWORLD_NPC_INTERACT_RANGE 1.5f
|
||||
|
||||
typedef struct {
|
||||
entityid_t entityId;
|
||||
componentid_t posCompId;
|
||||
componentid_t overworldCompId;
|
||||
componentid_t triggerCompId;
|
||||
componentid_t interactableCompId;
|
||||
} overworldnpc_t;
|
||||
|
||||
/**
|
||||
* Creates the NPC entity at the given world position.
|
||||
*
|
||||
* @param npc The NPC state to initialize.
|
||||
* @param position World-space position to spawn the NPC at.
|
||||
*/
|
||||
void overworldNpcAdd(overworldnpc_t *npc, vec3 position);
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "overworldplayer.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/physics/entityphysics.h"
|
||||
#include "entity/component/overworld/entityoverworld.h"
|
||||
#include "entity/component/overworld/entityplayer.h"
|
||||
|
||||
void overworldPlayerAdd(overworldplayer_t *player) {
|
||||
player->entityId = entityManagerAdd();
|
||||
player->posCompId = entityAddComponent(player->entityId, COMPONENT_TYPE_POSITION);
|
||||
entityAddComponent(player->entityId, COMPONENT_TYPE_RENDERABLE);
|
||||
entityAddComponent(player->entityId, COMPONENT_TYPE_PHYSICS);
|
||||
componentid_t owCompId = entityAddComponent(player->entityId, COMPONENT_TYPE_OVERWORLD);
|
||||
entityOverworldSetType(player->entityId, owCompId, OVERWORLD_ENTITY_TYPE_PLAYER);
|
||||
player->playerCompId = entityAddComponent(player->entityId, COMPONENT_TYPE_PLAYER);
|
||||
|
||||
vec3 pos = { 0.0f, 0.5f, 0.0f };
|
||||
entityPositionSetLocalPosition(player->entityId, player->posCompId, pos);
|
||||
|
||||
componentid_t physCompId = entityOverworldGet(player->entityId, owCompId)->physCompId;
|
||||
entityPhysicsSetBodyType(player->entityId, physCompId, PHYSICS_BODY_DYNAMIC);
|
||||
physicsshape_t shape = {
|
||||
.type = PHYSICS_SHAPE_CAPSULE,
|
||||
.data.capsule = { .radius = 0.4f, .halfHeight = 0.1f }
|
||||
};
|
||||
entityPhysicsSetShape(player->entityId, physCompId, shape);
|
||||
entityPhysicsGet(player->entityId, physCompId)->gravityScale = 1.0f;
|
||||
}
|
||||
|
||||
void overworldPlayerUpdate(overworldplayer_t *player) {
|
||||
entityPlayerUpdate(player->entityId, player->playerCompId);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "entity/entitybase.h"
|
||||
|
||||
typedef struct {
|
||||
entityid_t entityId;
|
||||
componentid_t posCompId;
|
||||
componentid_t playerCompId;
|
||||
} overworldplayer_t;
|
||||
|
||||
/**
|
||||
* Creates the player entity and adds it to the world.
|
||||
*
|
||||
* @param player The player state to initialize.
|
||||
*/
|
||||
void overworldPlayerAdd(overworldplayer_t *player);
|
||||
|
||||
/**
|
||||
* Updates the player entity, reading input and moving on the XZ plane.
|
||||
*
|
||||
* @param player The player state to update.
|
||||
*/
|
||||
void overworldPlayerUpdate(overworldplayer_t *player);
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#include "overworldscene.h"
|
||||
#include "overworldplayer.h"
|
||||
#include "overworldground.h"
|
||||
#include "overworldnpc.h"
|
||||
#include "console/console.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/display/entityrenderable.h"
|
||||
#include "display/shader/shaderlist.h"
|
||||
#include "entity/component/overworld/entityinteractable.h"
|
||||
#include "entity/component/overworld/entityoverworldcamera.h"
|
||||
#include "entity/component/overworld/entityoverworldtrigger.h"
|
||||
#include "display/mesh/cube.h"
|
||||
#include "display/mesh/plane.h"
|
||||
#include "display/displaystate.h"
|
||||
#include "scene/scene.h"
|
||||
#include "assert/assert.h"
|
||||
|
||||
#define OVERWORLD (SCENE.data.overworld)
|
||||
|
||||
static void overworldSceneTestTriggerEnter(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
) {
|
||||
consolePrint("Test trigger: player entered");
|
||||
}
|
||||
|
||||
static void overworldSceneTestTriggerExit(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
) {
|
||||
consolePrint("Test trigger: player exited");
|
||||
}
|
||||
|
||||
static void overworldSceneNpcInteract(
|
||||
const entityid_t entityId,
|
||||
const componentid_t componentId,
|
||||
void *user
|
||||
) {
|
||||
consolePrint("NPC interacted with!");
|
||||
}
|
||||
|
||||
void overworldSceneConfigureShaderMaterial(
|
||||
const entityid_t entityId,
|
||||
const color_t color,
|
||||
mesh_t *mesh
|
||||
) {
|
||||
assertNotNull(mesh, "Mesh cannot be null");
|
||||
componentid_t renderComp = entityGetComponent(
|
||||
entityId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
entityRenderableSetType(entityId, renderComp, ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL);
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, renderComp, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
r->data.material.shaderType = SHADER_LIST_SHADER_UNLIT;
|
||||
r->data.material.material.unlit.color = color;
|
||||
r->data.material.material.unlit.texture = NULL;
|
||||
r->data.material.state.flags = DISPLAY_STATE_FLAG_DEPTH_TEST;
|
||||
r->data.material.meshes[0] = mesh;
|
||||
r->data.material.meshOffsets[0] = 0;
|
||||
r->data.material.meshCounts[0] = -1;
|
||||
r->data.material.meshCount = 1;
|
||||
}
|
||||
|
||||
void overworldSceneConfigureSprite(
|
||||
const entityid_t entityId,
|
||||
const color_t color,
|
||||
texture_t *texture
|
||||
) {
|
||||
componentid_t renderComp = entityGetComponent(
|
||||
entityId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
entityRenderableSetType(entityId, renderComp, ENTITY_RENDERABLE_TYPE_SPRITEBATCH);
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, renderComp, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
r->data.spritebatch.texture = texture;
|
||||
r->data.spritebatch.spriteCount = 1;
|
||||
|
||||
r->data.spritebatch.sprites[0].min[0] = -0.5f;
|
||||
r->data.spritebatch.sprites[0].min[1] = -0.0f;
|
||||
r->data.spritebatch.sprites[0].min[2] = -0.5f;
|
||||
|
||||
r->data.spritebatch.sprites[0].max[0] = 0.5f;
|
||||
r->data.spritebatch.sprites[0].max[1] = 0.0f;
|
||||
r->data.spritebatch.sprites[0].max[2] = 0.5f;
|
||||
|
||||
r->data.spritebatch.sprites[0].uvMin[0] = 0.0f;
|
||||
r->data.spritebatch.sprites[0].uvMin[1] = 0.0f;
|
||||
r->data.spritebatch.sprites[0].uvMax[0] = 1.0f;
|
||||
r->data.spritebatch.sprites[0].uvMax[1] = 1.0f;
|
||||
}
|
||||
|
||||
void overworldSceneInit(void) {
|
||||
consolePrint("Overworld scene initialized");
|
||||
|
||||
overworldGroundAdd(&OVERWORLD.ground);
|
||||
overworldSceneConfigureShaderMaterial(
|
||||
OVERWORLD.ground.entityId, COLOR_MAGENTA, &PLANE_MESH_SIMPLE
|
||||
);
|
||||
|
||||
overworldPlayerAdd(&OVERWORLD.player);
|
||||
overworldSceneConfigureSprite(OVERWORLD.player.entityId, COLOR_GREEN, NULL);
|
||||
|
||||
vec3 npcPos = { 3.0f, 0.5f, 3.0f };
|
||||
overworldNpcAdd(&OVERWORLD.npc, npcPos);
|
||||
overworldSceneConfigureSprite(OVERWORLD.npc.entityId, COLOR_BLUE, NULL);
|
||||
|
||||
OVERWORLD.cameraEntityId = entityManagerAdd();
|
||||
entityAddComponent(OVERWORLD.cameraEntityId, COMPONENT_TYPE_POSITION);
|
||||
entityAddComponent(OVERWORLD.cameraEntityId, COMPONENT_TYPE_CAMERA);
|
||||
OVERWORLD.cameraOverworldCompId = entityAddComponent(
|
||||
OVERWORLD.cameraEntityId, COMPONENT_TYPE_OVERWORLD_CAMERA
|
||||
);
|
||||
entityOverworldCameraSetTarget(
|
||||
OVERWORLD.cameraEntityId, OVERWORLD.cameraOverworldCompId,
|
||||
OVERWORLD.player.entityId, OVERWORLD.player.posCompId
|
||||
);
|
||||
entityoverworldcamera_t *camData = entityOverworldCameraGet(
|
||||
OVERWORLD.cameraEntityId, OVERWORLD.cameraOverworldCompId
|
||||
);
|
||||
glm_vec3_zero(camData->targetOffset);
|
||||
glm_vec3_copy((vec3){ 0.0f, 0.0f, 5.0f }, camData->eyeOffset);
|
||||
camData->scale = 32.0f;
|
||||
entityInteractableSetCallback(
|
||||
OVERWORLD.npc.entityId, OVERWORLD.npc.interactableCompId,
|
||||
overworldSceneNpcInteract, NULL
|
||||
);
|
||||
|
||||
OVERWORLD.testTriggerId = entityManagerAdd();
|
||||
OVERWORLD.testTriggerCompId = entityAddComponent(
|
||||
OVERWORLD.testTriggerId, COMPONENT_TYPE_OVERWORLD_TRIGGER
|
||||
);
|
||||
entityOverworldTriggerSetBounds(
|
||||
OVERWORLD.testTriggerId, OVERWORLD.testTriggerCompId,
|
||||
(vec3){ -2.0f, -1.0f, -2.0f },
|
||||
(vec3){ 2.0f, 1.0f, 2.0f }
|
||||
);
|
||||
entityoverworldtrigger_t *testTrigger = entityOverworldTriggerGet(
|
||||
OVERWORLD.testTriggerId, OVERWORLD.testTriggerCompId
|
||||
);
|
||||
testTrigger->onEnter = overworldSceneTestTriggerEnter;
|
||||
testTrigger->onExit = overworldSceneTestTriggerExit;
|
||||
}
|
||||
|
||||
errorret_t overworldSceneUpdate(void) {
|
||||
overworldPlayerUpdate(&OVERWORLD.player);
|
||||
errorOk();
|
||||
}
|
||||
|
||||
void overworldSceneDispose(void) {
|
||||
OVERWORLD.cameraEntityId = ENTITY_ID_INVALID;
|
||||
OVERWORLD.cameraOverworldCompId = COMPONENT_ID_INVALID;
|
||||
OVERWORLD.ground.entityId = ENTITY_ID_INVALID;
|
||||
OVERWORLD.ground.posCompId = COMPONENT_ID_INVALID;
|
||||
OVERWORLD.ground.floorEntityId = ENTITY_ID_INVALID;
|
||||
OVERWORLD.player.entityId = ENTITY_ID_INVALID;
|
||||
OVERWORLD.player.posCompId = COMPONENT_ID_INVALID;
|
||||
OVERWORLD.npc.entityId = ENTITY_ID_INVALID;
|
||||
OVERWORLD.npc.posCompId = COMPONENT_ID_INVALID;
|
||||
OVERWORLD.npc.overworldCompId = COMPONENT_ID_INVALID;
|
||||
OVERWORLD.npc.triggerCompId = COMPONENT_ID_INVALID;
|
||||
OVERWORLD.npc.interactableCompId = COMPONENT_ID_INVALID;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Dominic Masters
|
||||
*
|
||||
* This software is released under the MIT License.
|
||||
* https://opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include "error/error.h"
|
||||
#include "entity/entitybase.h"
|
||||
#include "display/color.h"
|
||||
#include "display/mesh/mesh.h"
|
||||
#include "display/texture/texture.h"
|
||||
#include "scene/overworld/overworldplayer.h"
|
||||
#include "scene/overworld/overworldground.h"
|
||||
#include "scene/overworld/overworldnpc.h"
|
||||
|
||||
typedef struct {
|
||||
entityid_t cameraEntityId;
|
||||
componentid_t cameraOverworldCompId;
|
||||
overworldplayer_t player;
|
||||
overworldground_t ground;
|
||||
overworldnpc_t npc;
|
||||
entityid_t testTriggerId;
|
||||
componentid_t testTriggerCompId;
|
||||
} overworldscene_t;
|
||||
|
||||
/**
|
||||
* Configures a SHADER_MATERIAL renderable on an entity with the unlit shader,
|
||||
* depth testing enabled, no blending, and a single mesh.
|
||||
*
|
||||
* @param entityId The entity to configure.
|
||||
* @param color Unlit diffuse color.
|
||||
* @param mesh Mesh to render.
|
||||
*/
|
||||
void overworldSceneConfigureShaderMaterial(
|
||||
const entityid_t entityId,
|
||||
const color_t color,
|
||||
mesh_t *mesh
|
||||
);
|
||||
|
||||
/**
|
||||
* Configures a SPRITEBATCH renderable on an entity as a single 1x1 billboard
|
||||
* sprite centered at the entity's origin.
|
||||
*
|
||||
* @param entityId The entity to configure.
|
||||
* @param color Per-vertex sprite tint color.
|
||||
* @param texture Texture to use, or NULL for untextured.
|
||||
*/
|
||||
void overworldSceneConfigureSprite(
|
||||
const entityid_t entityId,
|
||||
const color_t color,
|
||||
texture_t *texture
|
||||
);
|
||||
|
||||
/**
|
||||
* Initializes the overworld scene, spawning all entities and configuring
|
||||
* the camera, player, ground, and NPC.
|
||||
*/
|
||||
void overworldSceneInit(void);
|
||||
|
||||
/**
|
||||
* Updates the overworld scene each frame.
|
||||
*
|
||||
* @return Error state.
|
||||
*/
|
||||
errorret_t overworldSceneUpdate(void);
|
||||
|
||||
/**
|
||||
* Disposes the overworld scene, invalidating all entity and component IDs.
|
||||
*/
|
||||
void overworldSceneDispose(void);
|
||||
+56
-166
@@ -10,224 +10,114 @@
|
||||
#include "time/time.h"
|
||||
#include "display/screen/screen.h"
|
||||
#include "entity/entitymanager.h"
|
||||
#include "entity/component/display/entityrenderable.h"
|
||||
#include "display/shader/shaderunlit.h"
|
||||
#include "display/spritebatch/spritebatch.h"
|
||||
#include "display/screen/screen.h"
|
||||
#include "display/display.h"
|
||||
#include "console/console.h"
|
||||
#include "util/string.h"
|
||||
#include "script/scriptmanager.h"
|
||||
#include "script/module/scene/modulescene.h"
|
||||
#include "script/module/cutscene/modulecutscene.h"
|
||||
#include "ui/ui.h"
|
||||
#include "scene/scenerenderpipeline.h"
|
||||
#include "entity/component.h"
|
||||
|
||||
scenefuncs_t SCENE_FUNCTIONS[SCENE_TYPE_COUNT] = {
|
||||
{ 0 },
|
||||
#define X(structName, varName, varNameUpper, initFunc, updateFunc, disposeFunc) \
|
||||
{ initFunc, updateFunc, disposeFunc },
|
||||
#include "scene/scenelist.h"
|
||||
#undef X
|
||||
};
|
||||
|
||||
scene_t SCENE;
|
||||
|
||||
errorret_t sceneInit(void) {
|
||||
memoryZero(&SCENE, sizeof(scene_t));
|
||||
SCENE.scriptRef = SCENE_SCRIPT_REF_NONE;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t sceneUpdate(void) {
|
||||
// Handle scene change
|
||||
if(SCENE.nextType != SCENE_TYPE_NULL) {
|
||||
// Dispose current scene.
|
||||
if(SCENE.type != SCENE_TYPE_NULL) {
|
||||
if(SCENE_FUNCTIONS[SCENE.type].dispose) {
|
||||
SCENE_FUNCTIONS[SCENE.type].dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// Init new scene
|
||||
SCENE.type = SCENE.nextType;
|
||||
SCENE.nextType = SCENE_TYPE_NULL;
|
||||
|
||||
if(SCENE.type != SCENE_TYPE_NULL) {
|
||||
if(SCENE_FUNCTIONS[SCENE.type].init) {
|
||||
SCENE_FUNCTIONS[SCENE.type].init();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update scene
|
||||
#ifdef DUSK_TIME_DYNAMIC
|
||||
if(TIME.dynamicUpdate) {
|
||||
errorOk();
|
||||
}
|
||||
#endif
|
||||
|
||||
if(stringCompare(SCENE.sceneNext, SCENE.sceneCurrent) != 0) {
|
||||
errorChain(sceneSetImmediate(SCENE.sceneNext));
|
||||
}
|
||||
|
||||
if(SCENE.sceneActive) {
|
||||
errorChain(moduleSceneCall("update"));
|
||||
if(SCENE.type != SCENE_TYPE_NULL && SCENE_FUNCTIONS[SCENE.type].update) {
|
||||
errorChain(SCENE_FUNCTIONS[SCENE.type].update());
|
||||
}
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
dusktimeepoch_t LAST;
|
||||
|
||||
errorret_t sceneRender(void) {
|
||||
entityid_t camEnts[ENTITY_COUNT_MAX];
|
||||
componentid_t camComps[ENTITY_COUNT_MAX];
|
||||
entityid_t camCount = componentGetEntitiesWithComponent(
|
||||
COMPONENT_TYPE_CAMERA, camEnts, camComps
|
||||
);
|
||||
mat4 proj, view, ident;
|
||||
glm_mat4_identity(ident);
|
||||
|
||||
shader_t *shaderCurrent = NULL;
|
||||
mat4 view, proj, model;
|
||||
|
||||
errorChain(displaySetState((displaystate_t){
|
||||
// .flags = DISPLAY_STATE_FLAG_CULL | DISPLAY_STATE_FLAG_DEPTH_TEST
|
||||
.flags = 0
|
||||
}));
|
||||
|
||||
// For each camera
|
||||
for(entityid_t camIndex = 0; camIndex < camCount; camIndex++) {
|
||||
entityid_t camEnt = camEnts[camIndex];
|
||||
componentid_t camComp = camComps[camIndex];
|
||||
componentid_t camPos = entityGetComponent(camEnt, COMPONENT_TYPE_POSITION);
|
||||
if(camPos == COMPONENT_ID_INVALID) {
|
||||
logError("Camera entity without entity position found\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
entityCameraGetProjection(camEnt, camComp, proj);
|
||||
entityPositionGetTransform(camEnt, camPos, view);
|
||||
|
||||
for(entityid_t entityId = 0; entityId < ENTITY_COUNT_MAX; entityId++) {
|
||||
componentid_t renderComp = entityGetComponent(
|
||||
entityId, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
if(renderComp == COMPONENT_ID_INVALID) continue;
|
||||
|
||||
entityrenderable_t *r = componentGetData(
|
||||
entityId, renderComp, COMPONENT_TYPE_RENDERABLE
|
||||
);
|
||||
|
||||
componentid_t posComp = entityGetComponent(
|
||||
entityId, COMPONENT_TYPE_POSITION
|
||||
);
|
||||
if(posComp == COMPONENT_ID_INVALID) {
|
||||
glm_mat4_identity(model);
|
||||
} else {
|
||||
entityPositionGetTransform(entityId, posComp, model);
|
||||
}
|
||||
|
||||
switch(r->type) {
|
||||
case ENTITY_RENDERABLE_TYPE_CALLBACK: {
|
||||
if(!r->callback) break;
|
||||
errorChain(r->callback(
|
||||
entityId, renderComp, view, proj, model, r->user
|
||||
));
|
||||
break;
|
||||
}
|
||||
|
||||
case ENTITY_RENDERABLE_TYPE_MATERIAL: {
|
||||
shader_t *shader = r->shader;
|
||||
if(!shader) break;
|
||||
if(!r->mesh) break;
|
||||
if(shaderCurrent != shader) {
|
||||
shaderCurrent = shader;
|
||||
errorChain(shaderBind(shaderCurrent));
|
||||
errorChain(shaderSetMatrix(shader, SHADER_UNLIT_PROJECTION, proj));
|
||||
errorChain(shaderSetMatrix(shader, SHADER_UNLIT_VIEW, view));
|
||||
}
|
||||
errorChain(shaderSetMatrix(shader, SHADER_UNLIT_MODEL, model));
|
||||
errorChain(shaderSetMaterial(shader, &r->material));
|
||||
errorChain(meshDraw(r->mesh, 0, -1));
|
||||
break;
|
||||
}
|
||||
|
||||
case ENTITY_RENDERABLE_TYPE_SPRITEBATCH: {
|
||||
if(r->spritebatch.spriteCount == 0) break;
|
||||
shader_t *shader = r->shader;
|
||||
if(!shader) break;
|
||||
if(shaderCurrent != shader) {
|
||||
shaderCurrent = shader;
|
||||
errorChain(shaderBind(shaderCurrent));
|
||||
errorChain(shaderSetMatrix(shader, SHADER_UNLIT_PROJECTION, proj));
|
||||
errorChain(shaderSetMatrix(shader, SHADER_UNLIT_VIEW, view));
|
||||
}
|
||||
errorChain(shaderSetMatrix(shader, SHADER_UNLIT_MODEL, model));
|
||||
for(uint16_t si = 0; si < r->spritebatch.spriteCount; si++) {
|
||||
errorChain(spriteBatchBufferSprite(&r->spritebatch.sprites[si]));
|
||||
}
|
||||
errorChain(spriteBatchFlush());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
errorChain(componentRenderAll());
|
||||
errorChain(sceneRenderPipeline(entityCameraGetCurrent()));
|
||||
|
||||
// UI Rendering
|
||||
errorChain(shaderBind(&SHADER_UNLIT));
|
||||
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_MODEL, ident));
|
||||
|
||||
glm_ortho(
|
||||
0.0f, SCREEN.width,
|
||||
SCREEN.height, 0.0f,
|
||||
0.1f, 100.0f,
|
||||
proj
|
||||
);
|
||||
errorChain(shaderSetMatrix(&SHADER_UNLIT, SHADER_UNLIT_PROJECTION, proj));
|
||||
|
||||
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_mat4_identity(model);
|
||||
|
||||
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(displaySetState((displaystate_t){
|
||||
.flags = DISPLAY_STATE_FLAG_BLEND
|
||||
}));
|
||||
|
||||
errorChain(uiRender());
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
errorret_t sceneSetImmediate(const char_t *scene) {
|
||||
if(scene != SCENE.sceneNext) {
|
||||
stringCopy(
|
||||
SCENE.sceneNext,
|
||||
scene == NULL ? "" : scene,
|
||||
ASSET_FILE_NAME_MAX
|
||||
);
|
||||
}
|
||||
|
||||
if(SCENE.sceneActive) {
|
||||
errorChain(moduleSceneCall("dispose"));
|
||||
SCENE.sceneActive = false;
|
||||
}
|
||||
|
||||
moduleCutsceneReset();
|
||||
moduleSceneReset();
|
||||
|
||||
stringCopy(
|
||||
SCENE.sceneCurrent,
|
||||
scene == NULL ? "" : scene,
|
||||
ASSET_FILE_NAME_MAX
|
||||
);
|
||||
|
||||
if(scene != NULL) {
|
||||
jerry_value_t sceneClass = SCENE_SCRIPT_REF_NONE;
|
||||
errorChain(scriptManagerExecFile(scene, &sceneClass));
|
||||
|
||||
if(!jerry_value_is_function(sceneClass)) {
|
||||
if(sceneClass != SCENE_SCRIPT_REF_NONE) jerry_value_free(sceneClass);
|
||||
errorThrow("Scene '%s' must export a constructor function", scene);
|
||||
}
|
||||
|
||||
jerry_value_t sceneObj = jerry_construct(sceneClass, NULL, 0);
|
||||
jerry_value_free(sceneClass);
|
||||
|
||||
if(jerry_value_is_exception(sceneObj)) {
|
||||
char_t errMsg[512];
|
||||
moduleBaseExceptionMessage(sceneObj, errMsg, sizeof(errMsg));
|
||||
jerry_value_free(sceneObj);
|
||||
errorThrow("Scene '%s' constructor threw: %s", scene, errMsg);
|
||||
}
|
||||
|
||||
SCENE.scriptRef = sceneObj;
|
||||
SCENE.sceneActive = true;
|
||||
}
|
||||
|
||||
errorOk();
|
||||
}
|
||||
|
||||
void sceneSet(const char_t *scene) {
|
||||
stringCopy(
|
||||
SCENE.sceneNext,
|
||||
scene == NULL ? "" : scene,
|
||||
ASSET_FILE_NAME_MAX
|
||||
void sceneSet(const scenetype_t type) {
|
||||
assertTrue(
|
||||
type > SCENE_TYPE_NULL && type < SCENE_TYPE_COUNT,
|
||||
"Invalid scene type"
|
||||
);
|
||||
SCENE.nextType = type;
|
||||
}
|
||||
|
||||
errorret_t sceneDispose(void) {
|
||||
errorChain(moduleSceneCall("dispose"));
|
||||
if(SCENE.type != SCENE_TYPE_NULL) {
|
||||
if(SCENE_FUNCTIONS[SCENE.type].dispose) {
|
||||
SCENE_FUNCTIONS[SCENE.type].dispose();
|
||||
}
|
||||
}
|
||||
SCENE.type = SCENE_TYPE_NULL;
|
||||
SCENE.nextType = SCENE_TYPE_NULL;
|
||||
errorOk();
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user