This commit is contained in:
2026-06-10 19:06:19 -05:00
parent 8131bcd4d4
commit 5be21a21d5
221 changed files with 2254 additions and 12533 deletions
-96
View File
@@ -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})
-43
View File
@@ -1,43 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# dusk_embed_js(TARGET JS_FILE [NAME identifier])
#
# Converts a JS file into a C string header in DUSK_GENERATED_HEADERS_DIR.
# The generated header defines:
# static const char <NAME>[] = "...";
# static const size_t <NAME>_SIZE = sizeof(<NAME>) - 1;
#
# NAME defaults to the uppercase stem + "_JS" (e.g. scene.js -> SCENE_JS).
function(dusk_embed_js TARGET JS_FILE)
cmake_parse_arguments(ARG "" "NAME" "" ${ARGN})
get_filename_component(JS_ABS "${JS_FILE}" ABSOLUTE)
get_filename_component(JS_STEM "${JS_FILE}" NAME_WE)
set(OUTPUT_HEADER "${DUSK_GENERATED_HEADERS_DIR}/${JS_STEM}_js.h")
set(NAME_ARG "")
if(ARG_NAME)
set(NAME_ARG "--name" "${ARG_NAME}")
endif()
add_custom_command(
OUTPUT "${OUTPUT_HEADER}"
COMMAND ${Python3_EXECUTABLE} -m tools.js2c
--input "${JS_ABS}"
--output "${OUTPUT_HEADER}"
${NAME_ARG}
WORKING_DIRECTORY "${DUSK_ROOT_DIR}"
DEPENDS "${JS_ABS}"
COMMENT "js2c: ${JS_STEM}.js -> ${JS_STEM}_js.h"
VERBATIM
)
file(RELATIVE_PATH JS_REL "${DUSK_ROOT_DIR}" "${JS_ABS}")
string(MAKE_C_IDENTIFIER "dusk_js2c_${JS_REL}" JS_TARGET)
add_custom_target(${JS_TARGET} DEPENDS "${OUTPUT_HEADER}")
add_dependencies(${TARGET} ${JS_TARGET})
endfunction()
+1 -15
View File
@@ -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()
if(DUSK_BACKTRACE)
target_link_options(${DUSK_LIBRARY_TARGET_NAME} PUBLIC -rdynamic)
target_compile_definitions(${DUSK_BINARY_TARGET_NAME} PUBLIC
@@ -66,24 +57,19 @@ add_subdirectory(event)
add_subdirectory(assert)
add_subdirectory(asset)
add_subdirectory(cutscene)
add_subdirectory(item)
add_subdirectory(story)
add_subdirectory(console)
add_subdirectory(display)
add_subdirectory(log)
add_subdirectory(engine)
add_subdirectory(entity)
add_subdirectory(error)
add_subdirectory(input)
add_subdirectory(locale)
add_subdirectory(physics)
add_subdirectory(rpg)
add_subdirectory(scene)
add_subdirectory(script)
add_subdirectory(system)
add_subdirectory(time)
add_subdirectory(ui)
add_subdirectory(network)
add_subdirectory(overworld)
add_subdirectory(save)
add_subdirectory(util)
add_subdirectory(thread)
-15
View File
@@ -411,21 +411,6 @@ errorret_t assetDispose(void) {
assertIsMainThread("Must be called from the main thread.");
threadStop(&ASSET.loadThread);
// Free any script read-buffers left behind by an in-flight async load
// that was interrupted before the sync eval phase ran.
for(size_t i = 0; i < ASSET_LOADING_COUNT_MAX; i++) {
assetloading_t *loading = &ASSET.loading[i];
if(
loading->entry != NULL &&
loading->type == ASSET_LOADER_TYPE_SCRIPT &&
loading->loading.script.buffer != NULL
) {
memoryFree(loading->loading.script.buffer);
loading->loading.script.buffer = NULL;
}
threadMutexDispose(&loading->mutex);
}
// Dispose every non-null entry so type-specific dispose callbacks
// (e.g. assetScriptDispose freeing jerry values) run before the
// scripting engine is torn down.
-1
View File
@@ -15,4 +15,3 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
add_subdirectory(display)
add_subdirectory(locale)
add_subdirectory(json)
add_subdirectory(script)
-6
View File
@@ -39,10 +39,4 @@ assetloadercallbacks_t ASSET_LOADER_CALLBACKS[ASSET_LOADER_TYPE_COUNT] = {
.loadAsync = assetJsonLoaderAsync,
.dispose = assetJsonDispose
},
[ASSET_LOADER_TYPE_SCRIPT] = {
.loadSync = assetScriptLoaderSync,
.loadAsync = assetScriptLoaderAsync,
.dispose = assetScriptDispose
},
};
-5
View File
@@ -11,7 +11,6 @@
#include "asset/loader/display/assettilesetloader.h"
#include "asset/loader/locale/assetlocaleloader.h"
#include "asset/loader/json/assetjsonloader.h"
#include "asset/loader/script/assetscriptloader.h"
typedef enum {
ASSET_LOADER_TYPE_NULL,
@@ -21,7 +20,6 @@ typedef enum {
ASSET_LOADER_TYPE_TILESET,
ASSET_LOADER_TYPE_LOCALE,
ASSET_LOADER_TYPE_JSON,
ASSET_LOADER_TYPE_SCRIPT,
ASSET_LOADER_TYPE_COUNT
} assetloadertype_t;
@@ -32,7 +30,6 @@ typedef union {
assettilesetloaderinput_t tileset;
assetlocaleloaderinput_t locale;
assetjsonloaderinput_t json;
assetscriptloaderinput_t script;
} assetloaderinput_t;
typedef union {
@@ -41,7 +38,6 @@ typedef union {
assettilesetloaderloading_t tileset;
assetlocaleloaderloading_t locale;
assetjsonloaderloading_t json;
assetscriptloaderloading_t script;
} assetloaderloading_t;
typedef union {
@@ -50,7 +46,6 @@ typedef union {
assettilesetoutput_t tileset;
assetlocaleoutput_t locale;
assetjsonoutput_t json;
assetscriptoutput_t script;
} assetloaderoutput_t;
typedef struct assetloading_s assetloading_t;
@@ -1,9 +0,0 @@
# 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
assetscriptloader.c
)
@@ -1,137 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "assetscriptloader.h"
#include "asset/loader/assetloading.h"
#include "asset/loader/assetentry.h"
#include "asset/loader/assetloader.h"
#include "script/module/require/modulerequire.h"
#include "util/memory.h"
#include "assert/assert.h"
#include <jerryscript.h>
errorret_t assetScriptLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Async loader should not be on main thread.");
if(loading->loading.script.state != ASSET_SCRIPT_LOADING_STATE_READ_FILE) {
errorOk();
}
assertNull(loading->loading.script.buffer, "Buffer already defined?");
assetfile_t *file = &loading->loading.script.file;
assetLoaderErrorChain(
loading, assetFileInit(file, loading->entry->name, NULL, NULL)
);
uint8_t *buffer = NULL;
size_t size = 0;
assetLoaderErrorChain(loading, assetFileReadEntire(file, &buffer, &size));
assetLoaderErrorChain(loading, assetFileDispose(file));
// Null-terminate for jerry_eval.
memoryResize((void **)&buffer, size, size + 1);
buffer[size] = '\0';
loading->loading.script.buffer = buffer;
loading->loading.script.size = size;
loading->loading.script.state = ASSET_SCRIPT_LOADING_STATE_EXEC;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk();
}
errorret_t assetScriptLoaderSync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertTrue(loading->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
switch(loading->loading.script.state) {
case ASSET_SCRIPT_LOADING_STATE_INITIAL:
loading->loading.script.state = ASSET_SCRIPT_LOADING_STATE_READ_FILE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_ASYNC;
errorOk();
break;
case ASSET_SCRIPT_LOADING_STATE_EXEC:
break;
default:
errorOk();
}
// Get read buffer
uint8_t *buffer = loading->loading.script.buffer;
assertNotNull(buffer, "Script buffer should have been loaded by now.");
// Get the current global script realm
jerry_value_t global = jerry_current_realm();
// Replace globalThis.module with a new `module = {}`
jerry_value_t oldModule = jerry_object_get_sz(global, "module");
jerry_value_t module = jerry_object();
jerry_object_set_sz(global, "module", module);
// Eval the script, we handle failure later down the code.
jerry_value_t result = jerry_eval(
buffer,
loading->loading.script.size,
JERRY_PARSE_NO_OPTS
);
// Free the read buffer
memoryFree(buffer);
loading->loading.script.buffer = NULL;
// Restore globalThis.module
jerry_object_set_sz(global, "module", oldModule);
jerry_value_free(oldModule);
jerry_value_free(global);
if(jerry_value_is_exception(result)) {
jerry_value_free(module);
loading->entry->data.script.exports = jerry_undefined();
loading->entry->state = ASSET_ENTRY_STATE_ERROR;
// Get error string
char_t buf[256];
moduleBaseExceptionMessage(result, buf, sizeof(buf));
jerry_value_free(result);
assetLoaderErrorThrow(
loading,
"Script execution failed: %s: %s", loading->entry->name, buf
);
}
// Get module.exports
jerry_value_t exports = jerry_object_get_sz(module, "exports");
jerry_value_free(result);
jerry_value_free(module);
// Store the exports.
loading->entry->data.script.exports = exports;
loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk();
}
errorret_t assetScriptDispose(assetentry_t *entry) {
assertNotNull(entry, "Asset entry cannot be NULL");
assertTrue(entry->type == ASSET_LOADER_TYPE_SCRIPT, "Invalid type.");
assertIsMainThread("Must be called from the main thread.");
if(
entry->data.script.exports != 0 &&
!jerry_value_is_undefined(entry->data.script.exports)
) {
jerry_value_free(entry->data.script.exports);
entry->data.script.exports = 0;
}
errorOk();
}
@@ -1,60 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/assetfile.h"
#include "script/scriptmodule.h"
#define ASSET_SCRIPT_CHUNK_SIZE 1024
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
typedef struct {
void *nothing;
} assetscriptloaderinput_t;
typedef scriptmodule_t assetscriptoutput_t;
typedef enum {
ASSET_SCRIPT_LOADING_STATE_INITIAL,
ASSET_SCRIPT_LOADING_STATE_READ_FILE,
ASSET_SCRIPT_LOADING_STATE_EXEC,
ASSET_SCRIPT_LOADING_STATE_DONE
} assetscriptloadingstate_t;
typedef struct {
assetfile_t file;
assetscriptloadingstate_t state;
uint8_t *buffer;
size_t size;
} assetscriptloaderloading_t;
/**
* Asynchronous loader for a script asset/module.
*
* @param loading The loading context.
* @returns An error code and state.
*/
errorret_t assetScriptLoaderAsync(assetloading_t *loading);
/**
* Synchronous loader for a script asset/module. This executes the script after
* it has been loaded by the async loader.
*
* @param loading The loading context.
* @returns An error code and state.
*/
errorret_t assetScriptLoaderSync(assetloading_t *loading);
/**
* Disposes of a loaded script asset/module.
*
* @param entry The asset entry to dispose.
* @returns An error code and state.
*/
errorret_t assetScriptDispose(assetentry_t *entry);
+6
View File
@@ -38,6 +38,10 @@ errorret_t displayInit(void) {
&TEXTURE_WHITE, 4, 4,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_WHITE_PIXELS }
));
errorChain(textureInit(
&TEXTURE_TEST, 4, 4,
TEXTURE_FORMAT_RGBA, (texturedata_t){ .rgbaColors = TEXTURE_TEST_PIXELS }
));
// Standard meshes
errorChain(quadInit());
@@ -100,6 +104,8 @@ errorret_t displayDispose(void) {
errorChain(spriteBatchDispose());
screenDispose();
errorChain(textDispose());
errorChain(textureDispose(&TEXTURE_WHITE));
errorChain(textureDispose(&TEXTURE_TEST));
#ifdef displayPlatformDispose
displayPlatformDispose();
-9
View File
@@ -93,15 +93,6 @@ errorret_t textDraw(
float_t posX = x;
float_t posY = y;
errorChain(shaderSetTexture(
&SHADER_UNLIT, SHADER_UNLIT_TEXTURE, font->texture
));
#if MESH_ENABLE_COLOR
#else
errorChain(shaderSetColor(&SHADER_UNLIT, SHADER_UNLIT_COLOR, color));
#endif
char_t c;
int32_t i = 0;
while((c = text[i++]) != '\0') {
+8
View File
@@ -19,6 +19,14 @@ color_t TEXTURE_WHITE_PIXELS[4*4] = {
COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE,
};
texture_t TEXTURE_TEST;
color_t TEXTURE_TEST_PIXELS[4*4] = {
COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA,
COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK,
COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA,
COLOR_MAGENTA, COLOR_BLACK, COLOR_MAGENTA, COLOR_BLACK,
};
errorret_t textureInit(
texture_t *texture,
const int32_t width,
+2
View File
@@ -30,6 +30,8 @@ typedef union texturedata_u {
extern texture_t TEXTURE_WHITE;
extern color_t TEXTURE_WHITE_PIXELS[4*4];
extern texture_t TEXTURE_TEST;
extern color_t TEXTURE_TEST_PIXELS[4*4];
/**
* Initializes a texture.
+7 -16
View File
@@ -10,6 +10,7 @@
#include "time/time.h"
#include "input/input.h"
#include "locale/localemanager.h"
#include "rpg/rpg.h"
#include "display/display.h"
#include "scene/scene.h"
#include "cutscene/cutscene.h"
@@ -17,14 +18,9 @@
#include "ui/ui.h"
#include "ui/uitextbox.h"
#include "assert/assert.h"
#include "entity/entitymanager.h"
#include "entity/component/physics/entityphysics.h"
#include "physics/physicsmanager.h"
#include "network/network.h"
#include "system/system.h"
#include "console/console.h"
#include "script/script.h"
#include "item/backpack.h"
#include "save/save.h"
engine_t ENGINE;
@@ -49,15 +45,12 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
errorChain(uiInit());
errorChain(uiTextboxInit());
errorChain(cutsceneInit());
entityManagerInit();
backpackInit();
physicsManagerInit();
errorChain(rpgInit());
errorChain(networkInit());
errorChain(scriptInit());
errorChain(sceneInit());
consolePrint("Engine initialized");
errorChain(scriptExecFile("init.js"));
sceneSet(SCENE_TYPE_OVERWORLD);
errorOk();
}
@@ -68,16 +61,15 @@ errorret_t engineUpdate(void) {
timeUpdate();
inputUpdate();
consoleUpdate();
entityManagerUpdate();
errorChain(rpgUpdate());
uiUpdate();
errorChain(uiTextboxUpdate());
physicsManagerUpdate();
errorChain(displayUpdate());
errorChain(cutsceneUpdate());
errorChain(sceneUpdate());
errorChain(assetUpdate());
errorChain(scriptUpdate());
// Render
errorChain(displayUpdate());
if(inputPressed(INPUT_ACTION_RAGEQUIT)) ENGINE.running = false;
errorOk();
}
@@ -90,9 +82,8 @@ errorret_t engineDispose(void) {
uiTextboxDispose();
cutsceneDispose();
errorChain(sceneDispose());
errorChain(scriptDispose());
errorChain(networkDispose());
entityManagerDispose();
rpgDispose();
localeManagerDispose();
uiDispose();
consoleDispose();
-149
View File
@@ -1,149 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entitymanager.h"
#include "assert/assert.h"
#include "util/memory.h"
componentdefinition_t COMPONENT_DEFINITIONS[] = {
[COMPONENT_TYPE_NULL] = { 0 },
#define X(enm, type, field, iMethod, dMethod, rMethod) \
[COMPONENT_TYPE_##enm] = { \
.enumName = #enm, \
.name = #field, \
.init = iMethod, \
.dispose = dMethod, \
.render = rMethod \
},
#include "componentlist.h"
#undef X
[COMPONENT_TYPE_COUNT] = { 0 }
};
void componentInit(
const entityid_t entityId,
const componentid_t componentId,
const componenttype_t type
) {
assertTrue(entityId < ENTITY_COUNT_MAX, "Entity ID OOB");
assertTrue(componentId < ENTITY_COMPONENT_COUNT_MAX, "Component ID OOB");
assertTrue(type < COMPONENT_TYPE_COUNT, "Component type OOB");
assertTrue(type != COMPONENT_TYPE_NULL, "Cannot initialize null component");
componentindex_t index = componentGetIndex(entityId, componentId);
component_t *cmp = &ENTITY_MANAGER.components[index];
memoryZero(cmp, sizeof(component_t));
cmp->type = type;
if(COMPONENT_DEFINITIONS[type].init) {
COMPONENT_DEFINITIONS[type].init(entityId, componentId);
}
}
void * componentGetData(
const entityid_t entityId,
const componentid_t componentId,
const componenttype_t type
) {
assertTrue(entityId < ENTITY_COUNT_MAX, "Entity ID OOB");
assertTrue(componentId < ENTITY_COMPONENT_COUNT_MAX, "Component ID OOB");
assertTrue(type < COMPONENT_TYPE_COUNT, "Component type OOB");
assertTrue(type != COMPONENT_TYPE_NULL, "Cannot get data of null component");
componentindex_t index = componentGetIndex(entityId, componentId);
component_t *cmp = &ENTITY_MANAGER.components[index];
assertTrue(cmp->type == type, "Component type mismatch");
return &cmp->data;
}
componentindex_t componentGetIndex(
const entityid_t entityId,
const componentid_t componentId
) {
assertTrue(entityId < ENTITY_COUNT_MAX, "Entity ID OOB");
assertTrue(componentId < ENTITY_COMPONENT_COUNT_MAX, "Component ID OOB");
return (entityId * ENTITY_COMPONENT_COUNT_MAX) + componentId;
}
entityid_t componentGetEntitiesWithComponent(
const componenttype_t type,
entityid_t outEntities[ENTITY_COUNT_MAX],
componentid_t outComponents[ENTITY_COUNT_MAX]
) {
assertTrue(type < COMPONENT_TYPE_COUNT, "Component type OOB");
assertTrue(type != COMPONENT_TYPE_NULL, "Cannot check NULL type");
assertNotNull(outEntities, "Output entities array cannot be null");
assertNotNull(outComponents, "Output components array cannot be null");
entityid_t written = 0;
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
componentid_t used = ENTITY_MANAGER.entitiesWithComponent[
type * ENTITY_COUNT_MAX + i
];
if(used == COMPONENT_ID_INVALID) continue;
assertTrue(
ENTITY_MANAGER.components[componentGetIndex(i, used)].type == type,
"Component type mismatch in entitiesWithComponent lookup"
);
assertTrue(
(ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) != 0,
"Inactive entity in entitiesWithComponent lookup"
);
assertTrue(
used < ENTITY_COMPONENT_COUNT_MAX,
"Component ID OOB in entitiesWithComponent lookup"
);
assertTrue(
componentGetIndex(i,used) < ENTITY_COUNT_MAX*ENTITY_COMPONENT_COUNT_MAX,
"Component index OOB in entitiesWithComponent lookup"
);
assertTrue(
ENTITY_MANAGER.components[componentGetIndex(i,used)].type == type,
"Component type mismatch in entitiesWithComponent lookup"
);
outComponents[written] = used;
outEntities[written++] = i;
}
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
) {
assertTrue(entityId < ENTITY_COUNT_MAX, "Entity ID OOB");
assertTrue(componentId < ENTITY_COMPONENT_COUNT_MAX, "Component ID OOB");
componentindex_t index = componentGetIndex(entityId, componentId);
component_t *cmp = &ENTITY_MANAGER.components[index];
if(cmp->type == COMPONENT_TYPE_NULL) return;
if(COMPONENT_DEFINITIONS[cmp->type].dispose) {
COMPONENT_DEFINITIONS[cmp->type].dispose(entityId, componentId);
}
cmp->type = COMPONENT_TYPE_NULL;
}
-120
View File
@@ -1,120 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entitybase.h"
#define X(enumName, type, field, init, dispose, render) \
// do nothing
#include "componentlist.h"
#undef X
typedef union {
#define X(enumName, type, field, init, dispose, render) type field;
#include "componentlist.h"
#undef X
} componentdata_t;
typedef struct {
const char_t *enumName;
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, render) \
COMPONENT_TYPE_##enumName,
#include "componentlist.h"
#undef X
COMPONENT_TYPE_COUNT
} componenttype_t;
typedef struct {
componenttype_t type;
componentdata_t data;
} component_t;
extern componentdefinition_t COMPONENT_DEFINITIONS[];
/**
* Initializes a component of the given type for the entity with component ID.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param type The type of the component to initialize.
*/
void componentInit(
const entityid_t entityId,
const componentid_t componentId,
const componenttype_t type
);
/**
* Gets the pointer to the data of a component for the entity with component ID.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param type The type of the component to get, only used for assertion.
* @return A pointer to the component data.
*/
void * componentGetData(
const entityid_t entityId,
const componentid_t componentId,
const componenttype_t type
);
/**
* Gets the index of a component for the entity with component ID.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @return The index of the component in the component array.
*/
componentindex_t componentGetIndex(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Gets the entity IDs of all entities with a component of the given type.
*
* @param type The type of the component to get entities for.
* @param outEntities An array to write the entity IDs to, must be at least
* ENTITY_COUNT_MAX in size.
* @param outComponents An array to write the component IDs to.
* @return The number of entity IDs written to outEntities.
*/
entityid_t componentGetEntitiesWithComponent(
const componenttype_t type,
entityid_t outEntities[ENTITY_COUNT_MAX],
componentid_t outComponents[ENTITY_COUNT_MAX]
);
/**
* 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);
-8
View File
@@ -1,8 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
add_subdirectory(display)
add_subdirectory(physics)
add_subdirectory(trigger)
@@ -1,12 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
entityposition.c
entitycamera.c
entityrenderable.c
)
@@ -1,120 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entity/entitymanager.h"
#include "entity/entity.h"
#include "entity/component/display/entityposition.h"
#include "display/framebuffer/framebuffer.h"
#include "display/screen/screen.h"
void entityCameraInit(const entityid_t ent, const componentid_t comp) {
entitycamera_t *cam = (entitycamera_t *)componentGetData(
ent, comp, COMPONENT_TYPE_CAMERA
);
cam->nearClip = 0.1f;
cam->farClip = 5000.0f;
cam->projType = ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE;
cam->perspective.fov = glm_rad(45.0f);
}
void entityCameraGetProjection(
const entityid_t ent,
const componentid_t comp,
mat4 out
) {
entitycamera_t *cam = (entitycamera_t *)componentGetData(
ent, comp, COMPONENT_TYPE_CAMERA
);
if(
cam->projType == ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE ||
cam->projType == ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED
) {
glm_mat4_identity(out);
glm_perspective(
cam->perspective.fov,
SCREEN.aspect,
cam->nearClip,
cam->farClip,
out
);
if(cam->projType == ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED) {
out[1][1] *= -1.0f;
}
} else if(cam->projType == ENTITY_CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC) {
glm_mat4_identity(out);
glm_ortho(
cam->orthographic.left,
cam->orthographic.right,
cam->orthographic.top,
cam->orthographic.bottom,
cam->nearClip,
cam->farClip,
out
);
}
}
entityid_t entityCameraGetCurrent(void) {
entityid_t camEnts[ENTITY_COUNT_MAX];
componentid_t camComps[ENTITY_COUNT_MAX];
entityid_t count = componentGetEntitiesWithComponent(
COMPONENT_TYPE_CAMERA, camEnts, camComps
);
if(count == 0) return ENTITY_ID_INVALID;
return camEnts[0];
}
void entityCameraGetForward(const entityid_t entityId, vec2 out) {
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
entityposition_t *pos = entityPositionGet(entityId, posComp);
// View matrix column layout: M[col][row],
// forward = {-M[0][2], -M[1][2], -M[2][2]}
float_t fx = -pos->worldTransform[0][2];
float_t fz = -pos->worldTransform[2][2];
float_t len = sqrtf(fx * fx + fz * fz);
if(len > 1e-6f) { fx /= len; fz /= len; }
out[0] = fx;
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);
// View matrix column layout: right = {M[0][0], M[1][0], M[2][0]}
float_t rx = pos->worldTransform[0][0];
float_t rz = pos->worldTransform[2][0];
float_t len = sqrtf(rx * rx + rz * rz);
if(len > 1e-6f) { rx /= len; rz /= len; }
out[0] = rx;
out[1] = rz;
}
@@ -1,99 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
typedef enum {
ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE,
ENTITY_CAMERA_PROJECTION_TYPE_PERSPECTIVE_FLIPPED,
ENTITY_CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC
} entitycameraprojectiontype_t;
typedef struct {
union {
struct {
float_t fov;
} perspective;
struct {
float_t left;
float_t right;
float_t top;
float_t bottom;
} orthographic;
};
float_t nearClip;
float_t farClip;
entitycameraprojectiontype_t projType;
} entitycamera_t;
/**
* Initializes an entity camera component.
*
* @param ent The entity ID.
* @param comp The component ID.
*/
void entityCameraInit(const entityid_t ent, const componentid_t comp);
/**
* Renders out the projection matrix for the given camera.
*
* @param ent The entity ID.
* @param comp The component ID.
* @param out The output projection matrix.
*/
void entityCameraGetProjection(
const entityid_t ent,
const componentid_t comp,
mat4 out
);
/**
* Returns the entity ID of the first active camera, or ENTITY_ID_INVALID if
* none are active.
*/
entityid_t entityCameraGetCurrent(void);
/**
* Gets the camera's horizontal forward direction (XZ plane) from its position
* component. Automatically finds the position component on the entity.
*
* @param entityId The camera entity ID.
* @param out Output vec2: {forwardX, forwardZ} normalized.
*/
void entityCameraGetForward(const entityid_t entityId, vec2 out);
/**
* Gets the camera's horizontal right direction (XZ plane) from its position
* component. Automatically finds the position component on the entity.
*
* @param entityId The camera entity ID.
* @param out Output vec2: {rightX, rightZ} normalized.
*/
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
);
@@ -1,630 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entity/entitymanager.h"
// 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;
}
// 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 cols 0-2 analytically (XYZ euler).
const float_t c0 = cosf(pos->rotation[0]), s0 = sinf(pos->rotation[0]);
const float_t c1 = cosf(pos->rotation[1]), s1 = sinf(pos->rotation[1]);
const float_t c2 = cosf(pos->rotation[2]), s2 = sinf(pos->rotation[2]);
const float_t s0s1 = s0 * s1;
const float_t 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 x 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
);
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->flags &= ~ENTITY_POSITION_FLAG_WORLD_DIRTY;
}
void entityPositionMarkDirty(entityposition_t *pos) {
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
);
entityPositionMarkDirty(child);
}
}
void entityPositionInit(
const entityid_t entityId,
const componentid_t componentId
) {
entityposition_t *pos = componentGetData(
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);
}
void entityPositionLookAt(
const entityid_t entityId,
const componentid_t componentId,
vec3 eye,
vec3 target,
vec3 up
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
glm_lookat(eye, target, up, pos->localTransform);
// 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);
}
void entityPositionGetTransform(
const entityid_t entityId,
const componentid_t componentId,
mat4 dest
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsureWorld(pos);
glm_mat4_copy(
pos->parentEntityId == ENTITY_ID_INVALID
? pos->localTransform : pos->worldTransform,
dest
);
}
void entityPositionGetLocalTransform(
const entityid_t entityId,
const componentid_t componentId,
mat4 dest
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsureLocal(pos);
glm_mat4_copy(pos->localTransform, dest);
}
void entityPositionGetLocalPosition(
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsurePRS(pos);
glm_vec3_copy(pos->position, dest);
}
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
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
glm_vec3_copy(position, pos->position);
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_POSITION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(pos);
}
void entityPositionGetLocalRotation(
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsurePRS(pos);
glm_vec3_copy(pos->rotation, dest);
}
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_t (*wt)[4] = pos->worldTransform;
const float_t sx = sqrtf(
wt[0][0]*wt[0][0] + wt[0][1]*wt[0][1] + wt[0][2]*wt[0][2]
);
const float_t sy = sqrtf(
wt[1][0]*wt[1][0] + wt[1][1]*wt[1][1] + wt[1][2]*wt[1][2]
);
const float_t sz = sqrtf(
wt[2][0]*wt[2][0] + wt[2][1]*wt[2][1] + wt[2][2]*wt[2][2]
);
const float_t r00 = sx > 0.0f ? wt[0][0]/sx : 0.0f;
const float_t r10 = sy > 0.0f ? wt[1][0]/sy : 0.0f;
const float_t r20 = sz > 0.0f ? wt[2][0]/sz : 0.0f;
const float_t r01 = sx > 0.0f ? wt[0][1]/sx : 0.0f;
const float_t r11 = sy > 0.0f ? wt[1][1]/sy : 0.0f;
const float_t r21 = sz > 0.0f ? wt[2][1]/sz : 0.0f;
const float_t r22 = sz > 0.0f ? wt[2][2]/sz : 0.0f;
const float_t sinBeta = glm_clamp(r20, -1.0f, 1.0f);
dest[1] = asinf(sinBeta);
const float_t 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
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
glm_vec3_copy(rotation, pos->rotation);
pos->flags = (pos->flags | ENTITY_POSITION_FLAG_ROTATION_DIRTY)
& ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(pos);
}
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_t c0 = cosf(rotation[0]), s0 = sinf(rotation[0]);
const float_t c1 = cosf(rotation[1]), s1 = sinf(rotation[1]);
const float_t c2 = cosf(rotation[2]), s2 = sinf(rotation[2]);
const float_t s0s1 = s0*s1, c0s1 = c0*s1;
// Named wr[col_stored][row_stored] matching cglm column-major layout.
const float_t wr00 = c1*c2;
const float_t wr01 = c0*s2 + s0s1*c2;
const float_t wr02 = s0*s2 - c0s1*c2;
const float_t wr10 = -c1*s2;
const float_t wr11 = c0*c2 - s0s1*s2;
const float_t wr12 = s0*c2 + c0s1*s2;
const float_t wr20 = s1;
const float_t wr21 = -s0*c1;
const float_t wr22 = c0*c1;
// Normalize parent world columns to extract pure rotation.
const float_t (*pt)[4] = parent->worldTransform;
const float_t psx = sqrtf(
pt[0][0]*pt[0][0] + pt[0][1]*pt[0][1] + pt[0][2]*pt[0][2]
);
const float_t psy = sqrtf(
pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][2]
);
const float_t psz = sqrtf(
pt[2][0]*pt[2][0] + pt[2][1]*pt[2][1] + pt[2][2]*pt[2][2]
);
const float_t pr00 = psx > 0.f ? pt[0][0]/psx : 0.f;
const float_t pr01 = psx > 0.f ? pt[0][1]/psx : 0.f;
const float_t pr02 = psx > 0.f ? pt[0][2]/psx : 0.f;
const float_t pr10 = psy > 0.f ? pt[1][0]/psy : 0.f;
const float_t pr11 = psy > 0.f ? pt[1][1]/psy : 0.f;
const float_t pr12 = psy > 0.f ? pt[1][2]/psy : 0.f;
const float_t pr20 = psz > 0.f ? pt[2][0]/psz : 0.f;
const float_t pr21 = psz > 0.f ? pt[2][1]/psz : 0.f;
const float_t pr22 = psz > 0.f ? pt[2][2]/psz : 0.f;
// local_R = parent_R^T * world_R (R^-1 == R^T for orthogonal matrices).
// 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_t lr00 = pr00*wr00 + pr01*wr10 + pr02*wr20; // math[0][0]
const float_t lr10 = pr00*wr01 + pr01*wr11 + pr02*wr21; // math[0][1]
const float_t lr20 = pr00*wr02 + pr01*wr12 + pr02*wr22; // [0][2] -> sinBeta
const float_t lr01 = pr10*wr00 + pr11*wr10 + pr12*wr20; // math[1][0]
const float_t lr11 = pr10*wr01 + pr11*wr11 + pr12*wr21; // math[1][1]
const float_t lr21 = pr10*wr02 + pr11*wr12 + pr12*wr22; // [1][2] -> r21
const float_t lr22 = pr20*wr02 + pr21*wr12 + pr22*wr22; // [2][2] -> r22
const float_t sinBeta = glm_clamp(lr20, -1.0f, 1.0f);
pos->rotation[1] = asinf(sinBeta);
const float_t 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
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
entityPositionEnsurePRS(pos);
glm_vec3_copy(pos->scale, dest);
}
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_t (*wt)[4] = pos->worldTransform;
dest[0] = sqrtf(wt[0][0]*wt[0][0] + wt[0][1]*wt[0][1] + wt[0][2]*wt[0][2]);
dest[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
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
glm_vec3_copy(scale, pos->scale);
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_t (*pt)[4] = parent->worldTransform;
const float_t psx = sqrtf(
pt[0][0]*pt[0][0] + pt[0][1]*pt[0][1] + pt[0][2]*pt[0][2]
);
const float_t psy = sqrtf(
pt[1][0]*pt[1][0] + pt[1][1]*pt[1][1] + pt[1][2]*pt[1][2]
);
const float_t psz = sqrtf(
pt[2][0]*pt[2][0] + pt[2][1]*pt[2][1] + pt[2][2]*pt[2][2]
);
pos->scale[0] = psx > 0.0f ? scale[0] / psx : scale[0];
pos->scale[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(
const entityid_t entityId,
const componentid_t componentId,
const entityid_t parentEntityId,
const componentid_t parentComponentId
) {
entityposition_t *pos = componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
// Remove from old parent's child list.
if(pos->parentEntityId != ENTITY_ID_INVALID) {
entityposition_t *oldParent = componentGetData(
pos->parentEntityId, pos->parentComponentId, COMPONENT_TYPE_POSITION
);
for(uint8_t i = 0; i < oldParent->childCount; i++) {
if(
oldParent->childEntityIds[i] == entityId &&
oldParent->childComponentIds[i] == componentId
) {
oldParent->childCount--;
for(uint8_t j = i; j < oldParent->childCount; j++) {
oldParent->childEntityIds[j] = oldParent->childEntityIds[j + 1];
oldParent->childComponentIds[j] = oldParent->childComponentIds[j + 1];
}
break;
}
}
}
pos->parentEntityId = parentEntityId;
pos->parentComponentId = parentComponentId;
// Register with new parent.
if(parentEntityId != ENTITY_ID_INVALID) {
entityposition_t *parent = componentGetData(
parentEntityId, parentComponentId, COMPONENT_TYPE_POSITION
);
if(parent->childCount < ENTITY_POSITION_CHILDREN_MAX) {
parent->childEntityIds[parent->childCount] = entityId;
parent->childComponentIds[parent->childCount] = componentId;
parent->childCount++;
}
}
entityPositionMarkDirty(pos);
}
entityposition_t *entityPositionGet(
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(
entityId, componentId, COMPONENT_TYPE_POSITION
);
}
void entityPositionRebuild(entityposition_t *pos) {
pos->flags = (
pos->flags |
ENTITY_POSITION_FLAG_ROTATION_DIRTY |
ENTITY_POSITION_FLAG_POSITION_DIRTY
) & ~ENTITY_POSITION_FLAG_PRS_DIRTY;
entityPositionMarkDirty(pos);
}
void entityPositionDisposeDeep(
const entityid_t entityId,
const componentid_t componentId
) {
entityposition_t *pos = entityPositionGet(entityId, componentId);
// Detach from parent so the parent's child list stays consistent.
if(pos->parentEntityId != ENTITY_ID_INVALID) {
entityPositionSetParent(
entityId, componentId, ENTITY_ID_INVALID, COMPONENT_ID_INVALID
);
}
// Copy the child list before disposing self (entityDispose invalidates pos).
uint8_t childCount = pos->childCount;
entityid_t childEntityIds[ENTITY_POSITION_CHILDREN_MAX];
componentid_t childComponentIds[ENTITY_POSITION_CHILDREN_MAX];
for(uint8_t i = 0; i < childCount; i++) {
childEntityIds[i] = pos->childEntityIds[i];
childComponentIds[i] = pos->childComponentIds[i];
// Sever child's parent link so it won't try to modify our disposed data.
entityposition_t *child = entityPositionGet(
childEntityIds[i], childComponentIds[i]
);
child->parentEntityId = ENTITY_ID_INVALID;
child->parentComponentId = COMPONENT_ID_INVALID;
}
entityDispose(entityId);
for(uint8_t i = 0; i < childCount; i++) {
entityPositionDisposeDeep(childEntityIds[i], childComponentIds[i]);
}
}
void entityPositionDecompose(entityposition_t *pos) {
// Translation: column 3
pos->position[0] = pos->localTransform[3][0];
pos->position[1] = pos->localTransform[3][1];
pos->position[2] = pos->localTransform[3][2];
// Scale: length of each basis column (xyz only)
pos->scale[0] = sqrtf(
pos->localTransform[0][0] * pos->localTransform[0][0] +
pos->localTransform[0][1] * pos->localTransform[0][1] +
pos->localTransform[0][2] * pos->localTransform[0][2]
);
pos->scale[1] = sqrtf(
pos->localTransform[1][0] * pos->localTransform[1][0] +
pos->localTransform[1][1] * pos->localTransform[1][1] +
pos->localTransform[1][2] * pos->localTransform[1][2]
);
pos->scale[2] = sqrtf(
pos->localTransform[2][0] * pos->localTransform[2][0] +
pos->localTransform[2][1] * pos->localTransform[2][1] +
pos->localTransform[2][2] * pos->localTransform[2][2]
);
// Normalize columns to isolate the rotation matrix (no mat4 needed).
const float_t invS0 = pos->scale[0] > 0.0f ? 1.0f / pos->scale[0] : 0.0f;
const float_t invS1 = pos->scale[1] > 0.0f ? 1.0f / pos->scale[1] : 0.0f;
const float_t invS2 = pos->scale[2] > 0.0f ? 1.0f / pos->scale[2] : 0.0f;
const float_t r00 = pos->localTransform[0][0] * invS0;
const float_t r01 = pos->localTransform[0][1] * invS0;
const float_t r02 = pos->localTransform[0][2] * invS0;
const float_t r10 = pos->localTransform[1][0] * invS1;
const float_t r11 = pos->localTransform[1][1] * invS1;
const float_t r20 = pos->localTransform[2][0] * invS2;
const float_t r21 = pos->localTransform[2][1] * invS2;
const float_t r22 = pos->localTransform[2][2] * invS2;
// Extract XYZ euler angles (R = Rx * Ry * Rz, column-major)
const float_t sinBeta = glm_clamp(r20, -1.0f, 1.0f);
pos->rotation[1] = asinf(sinBeta);
const float_t cosBeta = cosf(pos->rotation[1]);
if(fabsf(cosBeta) > 1e-6f) {
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(r01, r11)
: -atan2f(r01, r11);
}
}
@@ -1,375 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
/** 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; worldTransform must be recomputed before world data can be read.
*/
#define ENTITY_POSITION_FLAG_WORLD_DIRTY (1 << 3)
typedef struct {
/*
* Hot fields - flag checks, parent/child traversal (markDirty, ensureWorld)
* only touch these. Kept at the front so they share the first cache line.
*/
/** ENTITY_POSITION_FLAG_* bitmask; describes 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, 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). Stale when PRS_DIRTY is set. */
vec3 position;
/** Cached local rotation (XYZ euler, radians). Stale when PRS_DIRTY. */
vec3 rotation;
/** Cached local scale (XYZ). Stale when 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;
/**
* 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,
const componentid_t componentId
);
/**
* Transforms the entity's local transform to look at a target point.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @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
);
/**
* Gets the world-space transform matrix, recomputing it lazily if dirty.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination matrix.
*/
void entityPositionGetTransform(
const entityid_t entityId,
const componentid_t componentId,
mat4 dest
);
/**
* Gets the local transform matrix (does not include parent transforms).
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest Destination matrix.
*/
void entityPositionGetLocalTransform(
const entityid_t entityId,
const componentid_t componentId,
mat4 dest
);
/**
* 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 entityPositionGetLocalPosition(
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
);
/**
* 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 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
);
/**
* 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 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
);
/**
* 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 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
);
/**
* 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 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
);
/**
* 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 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
);
/**
* 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 parentComponentId The parent component ID.
*/
void entityPositionSetParent(
const entityid_t entityId,
const componentid_t componentId,
const entityid_t parentEntityId,
const componentid_t parentComponentId
);
/**
* Returns a direct pointer to the entity position component data.
* 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,
const componentid_t componentId
);
/**
* 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, 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);
/**
* 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);
/**
* Disposes this entity and all of its position-component descendants
* recursively. Detaches from any parent before destroying.
*
* @param entityId The root entity ID.
* @param componentId The root position component ID.
*/
void entityPositionDisposeDeep(
const entityid_t entityId,
const componentid_t componentId
);
/**
* 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);
@@ -1,142 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#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,
const componentid_t componentId
) {
entityrenderable_t *r = componentGetData(
entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
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;
}
void entityRenderableDispose(
const entityid_t entityId,
const componentid_t componentId
) {
}
void entityRenderableSetType(
const entityid_t entityId,
const componentid_t componentId,
const entityrenderabletype_t type
) {
entityrenderable_t *r = componentGetData(
entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
r->type = type;
}
void entityRenderableSetPriority(
const entityid_t entityId,
const componentid_t componentId,
const int8_t priority
) {
entityrenderable_t *r = componentGetData(
entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
r->priority = priority;
}
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
) {
assertNotNull(draw, "Draw callback cannot be null");
entityrenderable_t *r = componentGetData(
entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
r->type = ENTITY_RENDERABLE_TYPE_CUSTOM;
r->data.custom.draw = draw;
r->data.custom.drawUser = user;
}
static errorret_t entityRenderableDrawSpritebatch(
const entityrenderablespritebatch_t *sb
) {
if(sb->spriteCount == 0) errorOk();
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();
}
static errorret_t entityRenderableDrawMaterial(
const entityrenderablematerial_t *m
) {
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();
}
static errorret_t entityRenderableDrawCustom(
const entityid_t entityId,
const componentid_t componentId,
const entityrenderablecustom_t *custom
) {
return custom->draw(entityId, componentId, custom->drawUser);
}
errorret_t entityRenderableDraw(
const entityid_t entityId,
const componentid_t componentId
) {
entityrenderable_t *r = componentGetData(
entityId, componentId, COMPONENT_TYPE_RENDERABLE
);
switch(r->type) {
case ENTITY_RENDERABLE_TYPE_SPRITEBATCH:
return entityRenderableDrawSpritebatch(&r->data.spritebatch);
case ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL:
return entityRenderableDrawMaterial(&r->data.material);
case ENTITY_RENDERABLE_TYPE_CUSTOM:
return entityRenderableDrawCustom(entityId, componentId, &r->data.custom);
default:
assertUnreachable("Invalid renderable type");
}
}
@@ -1,147 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
#include "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_CUSTOM = 0,
ENTITY_RENDERABLE_TYPE_SPRITEBATCH,
ENTITY_RENDERABLE_TYPE_SHADER_MATERIAL,
} entityrenderabletype_t;
typedef struct {
spritebatchsprite_t sprites[ENTITY_RENDERABLE_SPRITEBATCH_SPRITES_MAX];
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;
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_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,
const componentid_t componentId
);
/**
* 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,
const componentid_t componentId
);
/**
* 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,
const componentid_t componentId,
const entityrenderabletype_t type
);
/**
* 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.
*/
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
);
@@ -1,126 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityphysics.h"
#include "entity/entitymanager.h"
#include "entity/component/display/entityposition.h"
#include "physics/physicsmanager.h"
#include "assert/assert.h"
#include "util/memory.h"
void entityPhysicsInit(
const entityid_t entityId,
const componentid_t componentId
) {
entityphysics_t *phys = entityPhysicsGet(entityId, componentId);
assertNotNull(phys, "Failed to get physics component data");
memoryZero(phys, sizeof(entityphysics_t));
// Default to cube
phys->type = PHYSICS_BODY_DYNAMIC;
phys->shape.type = PHYSICS_SHAPE_CUBE;
phys->shape.data.cube.halfExtents[0] = 0.5f;
phys->shape.data.cube.halfExtents[1] = 0.5f;
phys->shape.data.cube.halfExtents[2] = 0.5f;
phys->gravityScale = 1.0f;
phys->onGround = false;
}
entityphysics_t *entityPhysicsGet(
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(entityId, componentId, COMPONENT_TYPE_PHYSICS);
}
void entityPhysicsSetShape(
const entityid_t entityId,
const componentid_t componentId,
const physicsshape_t shape
) {
entityphysics_t *phys = entityPhysicsGet(entityId, componentId);
assertNotNull(phys, "Failed to get physics component data");
phys->shape = shape;
// TODO: Do I need to reset the state for ground/active?
}
physicsshape_t entityPhysicsGetShape(
const entityid_t entityId,
const componentid_t componentId
) {
entityphysics_t *phys = entityPhysicsGet(entityId, componentId);
assertNotNull(phys, "Failed to get physics component data");
return phys->shape;
}
void entityPhysicsGetVelocity(
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
) {
entityphysics_t *phys = entityPhysicsGet(entityId, componentId);
assertNotNull(phys, "Failed to get physics component data");
glm_vec3_copy(phys->velocity, dest);
}
void entityPhysicsSetVelocity(
const entityid_t entityId,
const componentid_t componentId,
vec3 velocity
) {
entityphysics_t *phys = entityPhysicsGet(entityId, componentId);
assertNotNull(phys, "Failed to get physics component data");
glm_vec3_copy(velocity, phys->velocity);
}
void entityPhysicsApplyImpulse(
const entityid_t entityId,
const componentid_t componentId,
vec3 impulse
) {
entityphysics_t *phys = entityPhysicsGet(entityId, componentId);
assertNotNull(phys, "Failed to get physics component data");
if(phys->type == PHYSICS_BODY_STATIC) return;
glm_vec3_add(phys->velocity, impulse, phys->velocity);
}
bool_t entityPhysicsIsOnGround(
const entityid_t entityId,
const componentid_t componentId
) {
entityphysics_t *phys = entityPhysicsGet(entityId, componentId);
assertNotNull(phys, "Failed to get physics component data");
return phys->onGround;
}
void entityPhysicsSetBodyType(
const entityid_t entityId,
const componentid_t componentId,
const physicsbodytype_t type
) {
entityphysics_t *phys = entityPhysicsGet(entityId, componentId);
assertNotNull(phys, "Failed to get physics component data");
phys->type = type;
}
physicsbodytype_t entityPhysicsGetBodyType(
const entityid_t entityId,
const componentid_t componentId
) {
entityphysics_t *phys = entityPhysicsGet(entityId, componentId);
assertNotNull(phys, "Failed to get physics component data");
return phys->type;
}
void entityPhysicsDispose(
const entityid_t entityId,
const componentid_t componentId
) {
}
@@ -1,157 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
#include "physics/physicsshape.h"
#include "physics/physicsbodytype.h"
typedef struct {
physicsbodytype_t type;
physicsshape_t shape;
vec3 velocity;
float_t gravityScale;
bool_t onGround;
} entityphysics_t;
/**
* Initializes the physics component: allocates a body in PHYSICS_WORLD.
* Asserts if the world body limit is reached.
*/
void entityPhysicsInit(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Gets the underlying physics structure (temporarily) for the given entity.
* This is really just intended for doing operations faster than using the
* getters and setters, but it is preferred that you use those.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @return The physics component data for the given entity and component ID.
*/
entityphysics_t *entityPhysicsGet(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets the shape of the entity's physics body. This will not reset the body
* state, so if you change from a cube to a sphere, it will keep the same
* velocity and onGround state.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param shape The new shape to set on the physics body.
*/
void entityPhysicsSetShape(
const entityid_t entityId,
const componentid_t componentId,
const physicsshape_t shape
);
/**
* Gets the shape of the entity's physics body.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @return The shape of the physics body.
*/
physicsshape_t entityPhysicsGetShape(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Gets the velocity of the entity's physics body.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param dest The destination vec3 to write the velocity to.
*/
void entityPhysicsGetVelocity(
const entityid_t entityId,
const componentid_t componentId,
vec3 dest
);
/**
* Sets the velocity of the entity's physics body. This is not an impulse, so
* it will be affected by mass and drag.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param velocity The new velocity to set on the physics body.
*/
void entityPhysicsSetVelocity(
const entityid_t entityId,
const componentid_t componentId,
vec3 velocity
);
/**
* Applies an impulse to the entity's physics body. This is an immediate
* velocity change that is not affected by mass or drag. No-op on STATIC bodies.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param impulse The impulse to apply to the physics body.
*/
void entityPhysicsApplyImpulse(
const entityid_t entityId,
const componentid_t componentId,
vec3 impulse
);
/**
* Returns true if the entity's physics body rested on a surface during the last
* step or move.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @return True if the body is on the ground, false otherwise.
*/
bool_t entityPhysicsIsOnGround(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Sets the body type of the entity's physics body.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @param type The body type to set.
*/
void entityPhysicsSetBodyType(
const entityid_t entityId,
const componentid_t componentId,
const physicsbodytype_t type
);
/**
* Gets the body type of the entity's physics body.
*
* @param entityId The entity ID.
* @param componentId The component ID.
* @return The body type of the physics body.
*/
physicsbodytype_t entityPhysicsGetBodyType(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Releases the body slot back to PHYSICS_WORLD. Called automatically when
* the component is disposed via the component system.
*/
void entityPhysicsDispose(
const entityid_t entityId,
const componentid_t componentId
);
@@ -1,54 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entity/entitymanager.h"
void entityTriggerInit(
const entityid_t entityId,
const componentid_t componentId
) {
entitytrigger_t *t = componentGetData(
entityId, componentId, COMPONENT_TYPE_TRIGGER
);
glm_vec3_zero(t->min);
glm_vec3_zero(t->max);
}
entitytrigger_t * entityTriggerGet(
const entityid_t entityId,
const componentid_t componentId
) {
return componentGetData(entityId, componentId, COMPONENT_TYPE_TRIGGER);
}
bool_t entityTriggerContains(
const entityid_t entityId,
const componentid_t componentId,
const vec3 point
) {
entitytrigger_t *t = componentGetData(
entityId, componentId, COMPONENT_TYPE_TRIGGER
);
return (
point[0] >= t->min[0] && point[0] <= t->max[0] &&
point[1] >= t->min[1] && point[1] <= t->max[1] &&
point[2] >= t->min[2] && point[2] <= t->max[2]
);
}
void entityTriggerSetBounds(
const entityid_t entityId,
const componentid_t componentId,
const vec3 min,
const vec3 max
) {
entitytrigger_t *t = componentGetData(
entityId, componentId, COMPONENT_TYPE_TRIGGER
);
glm_vec3_copy((float_t*)min, t->min);
glm_vec3_copy((float_t*)max, t->max);
}
@@ -1,49 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity/entitybase.h"
typedef struct {
vec3 min;
vec3 max;
} entitytrigger_t;
/**
* Initializes the trigger component with zeroed bounds.
*/
void entityTriggerInit(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Returns a pointer to the trigger component data.
*/
entitytrigger_t * entityTriggerGet(
const entityid_t entityId,
const componentid_t componentId
);
/**
* Returns true if the given world-space point lies within [min, max].
*/
bool_t entityTriggerContains(
const entityid_t entityId,
const componentid_t componentId,
const vec3 point
);
/**
* Sets both bounds at once.
*/
void entityTriggerSetBounds(
const entityid_t entityId,
const componentid_t componentId,
const vec3 min,
const vec3 max
);
-27
View File
@@ -1,27 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entity/component/display/entityposition.h"
#include "entity/component/display/entitycamera.h"
#include "entity/component/display/entityrenderable.h"
#include "entity/component/physics/entityphysics.h"
#include "entity/component/trigger/entitytrigger.h"
// Name (Uppercase)
// Structure
// Field name (lowercase)
// Init function (optional)
// Dispose function (optional)
// Render function (optional)
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)
-179
View File
@@ -1,179 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entitymanager.h"
#include "component/display/entityposition.h"
#include "util/memory.h"
#include "assert/assert.h"
void entityInit(const entityid_t entityId) {
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
memoryZero(ent, sizeof(entity_t));
// Mark all component types not using this entity.
for(
componenttype_t compType = 0;
compType < COMPONENT_TYPE_COUNT;
compType++
) {
ENTITY_MANAGER.entitiesWithComponent[
compType * ENTITY_COUNT_MAX + entityId
] = COMPONENT_ID_INVALID;
}
ent->state |= ENTITY_STATE_ACTIVE;
}
componentid_t entityAddComponent(
const entityid_t entityId,
const componenttype_t type
) {
componentindex_t compInd;
entity_t *ent = &ENTITY_MANAGER.entities[entityId];
for(componentid_t i = 0; i < ENTITY_COMPONENT_COUNT_MAX; i++) {
compInd = componentGetIndex(entityId, i);
if(ENTITY_MANAGER.components[compInd].type != COMPONENT_TYPE_NULL) {
assertTrue(
ENTITY_MANAGER.components[compInd].type != type,
"Entity already has component of this type"
);
continue;
}
componentInit(entityId, i, type);
ENTITY_MANAGER.entitiesWithComponent[
type * ENTITY_COUNT_MAX + entityId
] = i;
return i;
}
assertUnreachable("Entity has no more component slots available");
return COMPONENT_ID_INVALID;
}
componentid_t entityGetComponent(
const entityid_t entityId,
const componenttype_t type
) {
componentid_t compId = ENTITY_MANAGER.entitiesWithComponent[
type * ENTITY_COUNT_MAX + entityId
];
if(compId == COMPONENT_ID_INVALID) return compId;
assertTrue(
ENTITY_MANAGER.components[componentGetIndex(entityId, compId)].type == type,
"Component type mismatch"
);
return compId;
}
void entityDisposeDeep(const entityid_t entityId) {
componentid_t posComp = entityGetComponent(entityId, COMPONENT_TYPE_POSITION);
if(posComp != COMPONENT_ID_INVALID) {
entityPositionDisposeDeep(entityId, posComp);
} else {
entityDispose(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;
if(type == COMPONENT_TYPE_NULL) continue;
ENTITY_MANAGER.entitiesWithComponent[
type * ENTITY_COUNT_MAX + entityId
] = COMPONENT_ID_INVALID;
componentDispose(entityId, i);
}
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;
}
}
-137
View File
@@ -1,137 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "component.h"
#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;
/**
* Initializes an entity with the given ID.
*
* @param entityId The ID of the entity to initialize.
*/
void entityInit(const entityid_t entityId);
/**
* Adds a component of the given type to the entity with the given ID.
*
* @param entityId The ID of the entity to add the component to.
* @param type The type of the component to add.
* @return The ID of the entity with component.
*/
componentid_t entityAddComponent(
const entityid_t entityId,
const componenttype_t type
);
/**
* Gets the ID of the component of the given type on the entity with the given
* ID, or COMPONENT_ID_INVALID if the entity lacks the component.
*
* @param entityId The ID of the entity to get the component from.
* @param type The type of the component to get.
* @return The ID of the component.
*/
componentid_t entityGetComponent(
const entityid_t entityId,
const componenttype_t type
);
/**
* 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.
*/
void entityDispose(const entityid_t entityId);
/**
* Disposes of an entity and all of its position-component descendants
* recursively. If the entity has no position component, behaves like
* entityDispose.
*
* @param entityId The root entity ID.
*/
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
);
-19
View File
@@ -1,19 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#define ENTITY_COUNT_MAX 64
#define ENTITY_COMPONENT_COUNT_MAX 16
#define ENTITY_ID_INVALID 0xFF
#define COMPONENT_ID_INVALID 0xFF
typedef uint8_t entityid_t;
typedef uint8_t componentid_t;
typedef uint16_t componentindex_t;
-54
View File
@@ -1,54 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entitymanager.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "console/console.h"
entitymanager_t ENTITY_MANAGER;
void entityManagerInit(void) {
memoryZero(&ENTITY_MANAGER, sizeof(entitymanager_t));
memorySet(
ENTITY_MANAGER.entitiesWithComponent, COMPONENT_ID_INVALID,
sizeof(componentid_t) * COMPONENT_TYPE_COUNT * ENTITY_COUNT_MAX
);
consolePrint(
"Entity Manager size: %zu bytes (%.2f KB)",
sizeof(entitymanager_t),
sizeof(entitymanager_t) / 1024.0f
);
}
entityid_t entityManagerAdd() {
for(entityid_t i = 0; i < ENTITY_COUNT_MAX; i++) {
if((ENTITY_MANAGER.entities[i].state & ENTITY_STATE_ACTIVE) != 0) continue;
entityInit(i);
return i;
}
assertUnreachable("No more entity IDs available");
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;
entityDispose(i);
}
}
-39
View File
@@ -1,39 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entity.h"
typedef struct {
entity_t entities[ENTITY_COUNT_MAX];
component_t components[ENTITY_COUNT_MAX * ENTITY_COMPONENT_COUNT_MAX];
componentid_t entitiesWithComponent[COMPONENT_TYPE_COUNT * ENTITY_COUNT_MAX];
} entitymanager_t;
extern entitymanager_t ENTITY_MANAGER;
/**
* Initializes the entity manager.
*/
void entityManagerInit(void);
/**
* Adds / Reserves a new entity ID.
*
* @return The new entity ID.
*/
entityid_t entityManagerAdd();
/**
* Updates all active entities.
*/
void entityManagerUpdate(void);
/**
* Disposes of the entity manager, in turn freeing all entities and components.
*/
void entityManagerDispose(void);
-17
View File
@@ -1,17 +0,0 @@
/**
* 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;
}
}
-28
View File
@@ -1,28 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#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);
-151
View File
@@ -1,151 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "map.h"
#include "assert/assert.h"
#include "asset/assetfile.h"
#include "util/memory.h"
#include "util/string.h"
#include "console/console.h"
map_t MAP;
chunkindex_t mapChunkRelToIndex(
chunkunit_t rx,
chunkunit_t ry,
chunkunit_t rz
) {
return (chunkindex_t)(
rz * (MAP_CHUNKS_WIDE * MAP_CHUNKS_HIGH) +
ry * MAP_CHUNKS_WIDE +
rx
);
}
void mapInit(void) {
memoryZero(&MAP, sizeof(map_t));
}
errorret_t mapLoad(const char_t *handle) {
assertStrLenMin(handle, 1, "Map handle cannot be empty");
assertStrLenMax(handle, MAP_HANDLE_MAX - 1, "Map handle too long");
if(mapIsLoaded()) mapDispose();
memoryZero(&MAP, sizeof(map_t));
stringCopy(MAP.handle, handle, MAP_HANDLE_MAX);
char_t path[ASSET_FILE_NAME_MAX];
stringFormat(path, sizeof(path), "maps/%s/init.js", handle);
consolePrint("Map loaded: %s", handle);
errorOk();
}
bool_t mapIsLoaded(void) {
return MAP.loaded;
}
errorret_t mapPositionSet(tilepos_t tilePos) {
assertTrue(MAP.chunkTileWidth > 0, "chunkTileWidth not set");
assertTrue(MAP.chunkTileHeight > 0, "chunkTileHeight not set");
assertTrue(MAP.chunkTileDepth > 0, "chunkTileDepth not set");
// Convert tile position to chunk-space window origin.
chunkpos_t newPos = {
.x = (chunkunit_t)(tilePos.x / MAP.chunkTileWidth),
.y = (chunkunit_t)(tilePos.y / MAP.chunkTileHeight),
.z = (chunkunit_t)(tilePos.z / MAP.chunkTileDepth),
};
if(MAP.loaded && chunkPosEqual(MAP.chunkPosition, newPos)) errorOk();
// Categorise existing chunks as remaining or freed.
chunkindex_t remaining[MAP_CHUNKS_COUNT];
chunkindex_t freed[MAP_CHUNKS_COUNT];
chunkindex_t remainingCount = 0;
chunkindex_t freedCount = 0;
for(chunkindex_t i = 0; i < MAP_CHUNKS_COUNT; i++) {
mapchunk_t *chunk = &MAP.chunks[i];
chunkpos_t p = chunk->position;
bool_t stays = MAP.loaded &&
p.x >= newPos.x && p.x < newPos.x + MAP_CHUNKS_WIDE &&
p.y >= newPos.y && p.y < newPos.y + MAP_CHUNKS_HIGH &&
p.z >= newPos.z && p.z < newPos.z + MAP_CHUNKS_DEEP;
if(stays) {
remaining[remainingCount++] = i;
} else {
if(MAP.loaded) mapChunkUnload(chunk);
freed[freedCount++] = i;
}
}
// Build chunkOrder for the new window, loading into freed slots as needed.
chunkindex_t orderIndex = 0;
for(chunkunit_t zOff = 0; zOff < MAP_CHUNKS_DEEP; zOff++) {
for(chunkunit_t yOff = 0; yOff < MAP_CHUNKS_HIGH; yOff++) {
for(chunkunit_t xOff = 0; xOff < MAP_CHUNKS_WIDE; xOff++) {
chunkpos_t target = {
.x = (chunkunit_t)(newPos.x + xOff),
.y = (chunkunit_t)(newPos.y + yOff),
.z = (chunkunit_t)(newPos.z + zOff),
};
// Check if the target chunk is already loaded.
chunkindex_t poolIdx = -1;
for(chunkindex_t r = 0; r < remainingCount; r++) {
if(chunkPosEqual(MAP.chunks[remaining[r]].position, target)) {
poolIdx = remaining[r];
break;
}
}
// Otherwise recycle a freed slot.
if(poolIdx == -1) {
poolIdx = freed[--freedCount];
MAP.chunks[poolIdx].position = target;
errorChain(mapChunkLoad(&MAP.chunks[poolIdx]));
}
MAP.chunkOrder[orderIndex++] = &MAP.chunks[poolIdx];
}}}
MAP.chunkPosition = newPos;
MAP.loaded = true;
errorOk();
}
mapchunk_t *mapGetChunkAt(chunkpos_t pos) {
if(!MAP.loaded) return NULL;
chunkpos_t p = MAP.chunkPosition;
if(
pos.x < p.x || pos.x >= p.x + MAP_CHUNKS_WIDE ||
pos.y < p.y || pos.y >= p.y + MAP_CHUNKS_HIGH ||
pos.z < p.z || pos.z >= p.z + MAP_CHUNKS_DEEP
) return NULL;
chunkindex_t idx = mapChunkRelToIndex(
pos.x - p.x, pos.y - p.y, pos.z - p.z
);
return MAP.chunkOrder[idx];
}
errorret_t mapUpdate(void) {
if(!MAP.loaded) errorOk();
errorOk();
}
void mapDispose(void) {
consolePrint("Map disposing: %s", MAP.handle);
if(!MAP.loaded) return;
for(chunkindex_t i = 0; i < MAP_CHUNKS_COUNT; i++) {
mapChunkUnload(&MAP.chunks[i]);
}
MAP.loaded = false;
}
-97
View File
@@ -1,97 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "mapchunk.h"
#include "error/error.h"
#define MAP_NAME_MAX 64
#define MAP_HANDLE_MAX 32
#define MAP_CHUNKS_WIDE 3
#define MAP_CHUNKS_HIGH 3
#define MAP_CHUNKS_DEEP 2
#define MAP_CHUNKS_COUNT (MAP_CHUNKS_WIDE * MAP_CHUNKS_HIGH * MAP_CHUNKS_DEEP)
typedef struct {
char_t name[MAP_NAME_MAX];
char_t handle[MAP_HANDLE_MAX];
uint16_t chunkTileWidth;
uint16_t chunkTileHeight;
uint16_t chunkTileDepth;
mapchunk_t chunks[MAP_CHUNKS_COUNT];
mapchunk_t *chunkOrder[MAP_CHUNKS_COUNT];
chunkpos_t chunkPosition;
bool_t loaded;
} map_t;
extern map_t MAP;
/**
* Initializes the map, zeroing all state.
*/
void mapInit(void);
/**
* Prepares the map for use with the given handle. If a map is already loaded
* it is disposed first. Chunk positions are not set until mapPositionSet is
* called.
*
* @param handle Short identifier for this map (max MAP_HANDLE_MAX - 1 chars).
* @return An error code.
*/
errorret_t mapLoad(const char_t *handle);
/**
* Returns true if a map is currently loaded.
*
* @return true if a map is loaded, false otherwise.
*/
bool_t mapIsLoaded(void);
/**
* Converts a chunk position relative to the window origin to its pool index.
*
* @param rx Relative chunk X offset within the window.
* @param ry Relative chunk Y offset within the window.
* @param rz Relative chunk Z offset within the window.
* @return The flat pool index for that relative position.
*/
chunkindex_t mapChunkRelToIndex(
chunkunit_t rx,
chunkunit_t ry,
chunkunit_t rz
);
/**
* Slides the loaded chunk window so its origin is the chunk that contains
* the given tile-space position. Only the delta is loaded/unloaded.
*
* @param tilePos Tile-space position of the new window origin.
* @return An error code.
*/
errorret_t mapPositionSet(tilepos_t tilePos);
/**
* Updates the map each frame.
*
* @return An error code.
*/
errorret_t mapUpdate(void);
/**
* Disposes the map, unloading all chunks.
*/
void mapDispose(void);
/**
* Returns the chunk at the given absolute chunk-space position, or NULL if
* it is outside the currently loaded window.
*
* @param pos Absolute chunk-space position to look up.
* @return Pointer to the chunk, or NULL if not loaded.
*/
mapchunk_t *mapGetChunkAt(chunkpos_t pos);
-56
View File
@@ -1,56 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "mapchunk.h"
#include "map.h"
#include "entity/entitymanager.h"
#include "util/memory.h"
#include "util/string.h"
#include "asset/asset.h"
#include "console/console.h"
errorret_t mapChunkLoad(mapchunk_t *chunk) {
chunk->entityCount = 0;
memoryZero(chunk->entities, sizeof(chunk->entities));
if(MAP.handle[0] == '\0') errorOk();
char_t path[ASSET_FILE_NAME_MAX];
stringFormat(
path, sizeof(path),
"maps/%s/chunks/%d_%d_%d.js",
MAP.handle,
(int)chunk->position.x,
(int)chunk->position.y,
(int)chunk->position.z
);
if(!assetFileExists(path)) errorOk();
consolePrint(
"Chunk loaded: %s [%d,%d,%d]",
path,
(int)chunk->position.x,
(int)chunk->position.y,
(int)chunk->position.z
);
errorOk();
}
void mapChunkUnload(mapchunk_t *chunk) {
consolePrint(
"Chunk unloading: [%d,%d,%d]",
(int)chunk->position.x,
(int)chunk->position.y,
(int)chunk->position.z
);
for(uint8_t i = 0; i < chunk->entityCount; i++) {
entityDispose(chunk->entities[i]);
}
chunk->entityCount = 0;
}
-34
View File
@@ -1,34 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "maptypes.h"
#include "entity/entitybase.h"
#include "error/error.h"
#define MAP_CHUNK_ENTITY_COUNT_MAX 64
typedef struct {
chunkpos_t position;
entityid_t entities[MAP_CHUNK_ENTITY_COUNT_MAX];
uint8_t entityCount;
} mapchunk_t;
/**
* Loads content into a chunk at its current position.
*
* @param chunk The chunk to load.
* @return An error code.
*/
errorret_t mapChunkLoad(mapchunk_t *chunk);
/**
* Disposes all entities owned by the chunk and resets its state.
*
* @param chunk The chunk to unload.
*/
void mapChunkUnload(mapchunk_t *chunk);
-12
View File
@@ -1,12 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "maptypes.h"
bool_t chunkPosEqual(chunkpos_t a, chunkpos_t b) {
return a.x == b.x && a.y == b.y && a.z == b.z;
}
-30
View File
@@ -1,30 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef int16_t chunkunit_t;
typedef int16_t chunkindex_t;
typedef int32_t tileunit_t;
typedef struct {
chunkunit_t x, y, z;
} chunkpos_t;
typedef struct {
tileunit_t x, y, z;
} tilepos_t;
/**
* Checks if two chunk positions are equal.
*
* @param a The first chunk position.
* @param b The second chunk position.
* @return true if the positions are equal, false otherwise.
*/
bool_t chunkPosEqual(chunkpos_t a, chunkpos_t b);
-12
View File
@@ -1,12 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
physicsmanager.c
physicsworld.c
physicstest.c
)
-27
View File
@@ -1,27 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef enum {
/**
* Never moves. Acts as an immovable collision surface.
*/
PHYSICS_BODY_STATIC,
/**
* Simulated by the world step: gravity, forces, and collision response.
*/
PHYSICS_BODY_DYNAMIC,
/**
* Moved programmatically via physicsWorldMoveBody; collides but is not
* driven by the simulation. Typical use: player character controller.
*/
PHYSICS_BODY_KINEMATIC
} physicsbodytype_t;
-21
View File
@@ -1,21 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "physicsmanager.h"
#include "time/time.h"
void physicsManagerInit(void) {
physicsWorldInit();
}
void physicsManagerUpdate() {
#if DUSK_TIME_DYNAMIC
if(TIME.dynamicUpdate) return; // Don't update on dynamic updates.
#endif
physicsWorldStep(TIME.delta);
}
-19
View File
@@ -1,19 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "physicsworld.h"
/**
* Initializes the physics manager.
*/
void physicsManagerInit(void);
/**
* Advances the physics simulation.
*/
void physicsManagerUpdate();
-46
View File
@@ -1,46 +0,0 @@
/**
* 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 {
PHYSICS_SHAPE_CUBE,
PHYSICS_SHAPE_SPHERE,
PHYSICS_SHAPE_CAPSULE,
PHYSICS_SHAPE_PLANE
} physicshapetype_t;
typedef struct {
vec3 halfExtents;
} physicsshapecube_t;
typedef struct {
float_t radius;
} physicsshapesphere_t;
typedef struct {
float_t radius;
float_t halfHeight;
} physicsshapecapsule_t;
typedef struct {
vec3 normal;
float_t distance;
} physicsshapeplane_t;
typedef union {
physicsshapecube_t cube;
physicsshapesphere_t sphere;
physicsshapecapsule_t capsule;
physicsshapeplane_t plane;
} physicsshapedata_t;
typedef struct {
physicshapetype_t type;
physicsshapedata_t data;
} physicsshape_t;
-402
View File
@@ -1,402 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "physicstest.h"
bool_t physicsTestAabbVsAabb(
const vec3 ac, const vec3 ah,
const vec3 bc, const vec3 bh,
vec3 outNormal, float_t *outDepth
) {
float_t dx = ac[0] - bc[0];
float_t dy = ac[1] - bc[1];
float_t dz = ac[2] - bc[2];
float_t px = (ah[0] + bh[0]) - fabsf(dx);
float_t py = (ah[1] + bh[1]) - fabsf(dy);
float_t pz = (ah[2] + bh[2]) - fabsf(dz);
if(px <= 0.0f || py <= 0.0f || pz <= 0.0f) return false;
outNormal[0] = outNormal[1] = outNormal[2] = 0.0f;
if(px < py && px < pz) {
*outDepth = px;
outNormal[0] = dx >= 0.0f ? 1.0f : -1.0f;
} else if(py < pz) {
*outDepth = py;
outNormal[1] = dy >= 0.0f ? 1.0f : -1.0f;
} else {
*outDepth = pz;
outNormal[2] = dz >= 0.0f ? 1.0f : -1.0f;
}
return true;
}
bool_t physicsTestSphereVsSphere(
const vec3 ac, const float_t ar,
const vec3 bc, const float_t br,
vec3 outNormal, float_t *outDepth
) {
vec3 diff;
glm_vec3_sub((float_t *)ac, (float_t *)bc, diff);
float_t dist2 = glm_vec3_norm2(diff);
float_t sumR = ar + br;
if(dist2 >= sumR * sumR) return false;
float_t dist = sqrtf(dist2);
*outDepth = sumR - dist;
if(dist > 1e-6f) {
glm_vec3_scale(diff, 1.0f / dist, outNormal);
} else {
outNormal[0] = 0.0f;
outNormal[1] = 1.0f;
outNormal[2] = 0.0f;
}
return true;
}
bool_t physicsTestSphereVsAabb(
const vec3 sc, const float_t sr,
const vec3 ac, const vec3 ah,
vec3 outNormal, float_t *outDepth
) {
vec3 closest = {
glm_clamp(sc[0], ac[0] - ah[0], ac[0] + ah[0]),
glm_clamp(sc[1], ac[1] - ah[1], ac[1] + ah[1]),
glm_clamp(sc[2], ac[2] - ah[2], ac[2] + ah[2])
};
vec3 diff;
glm_vec3_sub((float_t *)sc, closest, diff);
float_t dist2 = glm_vec3_norm2(diff);
bool_t inside = (dist2 < 1e-10f);
if(!inside && dist2 >= sr * sr) return false;
if(!inside) {
float_t dist = sqrtf(dist2);
*outDepth = sr - dist;
glm_vec3_scale(diff, 1.0f / dist, outNormal);
} else {
float_t faces[6] = {
(ac[0] + ah[0]) - sc[0],
sc[0] - (ac[0] - ah[0]),
(ac[1] + ah[1]) - sc[1],
sc[1] - (ac[1] - ah[1]),
(ac[2] + ah[2]) - sc[2],
sc[2] - (ac[2] - ah[2])
};
const float_t normals[6][3] = {
{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}
};
int_t mi = 0;
for(int_t k = 1; k < 6; k++) {
if(faces[k] < faces[mi]) mi = k;
}
*outDepth = sr + faces[mi];
outNormal[0] = normals[mi][0];
outNormal[1] = normals[mi][1];
outNormal[2] = normals[mi][2];
}
return true;
}
bool_t physicsTestSphereVsPlane(
const vec3 sc, const float_t sr,
const vec3 pn, const float_t pd,
vec3 outNormal, float_t *outDepth
) {
float_t signedDist = glm_vec3_dot((float_t *)pn, (float_t *)sc) - pd;
*outDepth = sr - signedDist;
if(*outDepth <= 0.0f) return false;
glm_vec3_copy((float_t *)pn, outNormal);
return true;
}
bool_t physicsTestAabbVsPlane(
const vec3 ac, const vec3 ah,
const vec3 pn, const float_t pd,
vec3 outNormal, float_t *outDepth
) {
float_t proj = fabsf(pn[0] * ah[0])
+ fabsf(pn[1] * ah[1])
+ fabsf(pn[2] * ah[2]);
float_t signedDist = glm_vec3_dot((float_t *)pn, (float_t *)ac) - pd;
*outDepth = proj - signedDist;
if(*outDepth <= 0.0f) return false;
glm_vec3_copy((float_t *)pn, outNormal);
return true;
}
void physicsTestClosestPointOnSegment(
const vec3 a, const vec3 b, const vec3 p, vec3 out
) {
vec3 ab, ap;
glm_vec3_sub((float_t *)b, (float_t *)a, ab);
glm_vec3_sub((float_t *)p, (float_t *)a, ap);
float_t denom = glm_vec3_dot(ab, ab);
float_t t = (denom > 1e-10f)
? glm_clamp(glm_vec3_dot(ap, ab) / denom, 0.0f, 1.0f)
: 0.0f;
glm_vec3_lerp((float_t *)a, (float_t *)b, t, out);
}
void physicsTestClosestPointsBetweenSegments(
const vec3 a1, const vec3 b1,
const vec3 a2, const vec3 b2,
vec3 outP1, vec3 outP2
) {
vec3 d1, d2, r;
glm_vec3_sub((float_t *)b1, (float_t *)a1, d1);
glm_vec3_sub((float_t *)b2, (float_t *)a2, d2);
glm_vec3_sub((float_t *)a1, (float_t *)a2, r);
float_t a = glm_vec3_dot(d1, d1);
float_t e = glm_vec3_dot(d2, d2);
float_t f = glm_vec3_dot(d2, r);
float_t s, t;
if(a <= 1e-10f && e <= 1e-10f) {
glm_vec3_copy((float_t *)a1, outP1);
glm_vec3_copy((float_t *)a2, outP2);
return;
}
if(a <= 1e-10f) {
t = 0.0f;
s = glm_clamp(f / e, 0.0f, 1.0f);
} else {
float_t c = glm_vec3_dot(d1, r);
if(e <= 1e-10f) {
s = 0.0f;
t = glm_clamp(-c / a, 0.0f, 1.0f);
} else {
float_t b = glm_vec3_dot(d1, d2);
float_t denom = a * e - b * b;
t = (fabsf(denom) > 1e-10f)
? glm_clamp((b * f - c * e) / denom, 0.0f, 1.0f)
: 0.0f;
s = glm_clamp((b * t + f) / e, 0.0f, 1.0f);
t = glm_clamp((b * s - c) / a, 0.0f, 1.0f);
}
}
glm_vec3_lerp((float_t *)a1, (float_t *)b1, t, outP1);
glm_vec3_lerp((float_t *)a2, (float_t *)b2, s, outP2);
}
bool_t physicsTestCapsuleVsSphere(
const vec3 cc, const float_t cr, const float_t chh,
const vec3 sc, const float_t sr,
vec3 outNormal, float_t *outDepth
) {
vec3 capA = { cc[0], cc[1] - chh, cc[2] };
vec3 capB = { cc[0], cc[1] + chh, cc[2] };
vec3 closest;
physicsTestClosestPointOnSegment(capA, capB, sc, closest);
return physicsTestSphereVsSphere(
closest, cr, sc, sr, outNormal, outDepth
);
}
bool_t physicsTestCapsuleVsAabb(
const vec3 cc, const float_t cr, const float_t chh,
const vec3 ac, const vec3 ah,
vec3 outNormal, float_t *outDepth
) {
vec3 capA = { cc[0], cc[1] - chh, cc[2] };
vec3 capB = { cc[0], cc[1] + chh, cc[2] };
vec3 closest;
physicsTestClosestPointOnSegment(capA, capB, ac, closest);
return physicsTestSphereVsAabb(
closest, cr, ac, ah, outNormal, outDepth
);
}
bool_t physicsTestCapsuleVsPlane(
const vec3 cc, const float_t cr, const float_t chh,
const vec3 pn, const float_t pd,
vec3 outNormal, float_t *outDepth
) {
vec3 capA = { cc[0], cc[1] - chh, cc[2] };
vec3 capB = { cc[0], cc[1] + chh, cc[2] };
float_t da = glm_vec3_dot((float_t *)pn, capA) - pd;
float_t db = glm_vec3_dot((float_t *)pn, capB) - pd;
float_t minDist = (da < db) ? da : db;
*outDepth = cr - minDist;
if(*outDepth <= 0.0f) return false;
glm_vec3_copy((float_t *)pn, outNormal);
return true;
}
bool_t physicsTestCapsuleVsCapsule(
const vec3 c1, const float_t r1, const float_t hh1,
const vec3 c2, const float_t r2, const float_t hh2,
vec3 outNormal, float_t *outDepth
) {
vec3 a1 = { c1[0], c1[1] - hh1, c1[2] };
vec3 b1 = { c1[0], c1[1] + hh1, c1[2] };
vec3 a2 = { c2[0], c2[1] - hh2, c2[2] };
vec3 b2 = { c2[0], c2[1] + hh2, c2[2] };
vec3 p1, p2;
physicsTestClosestPointsBetweenSegments(a1, b1, a2, b2, p1, p2);
return physicsTestSphereVsSphere(p1, r1, p2, r2, outNormal, outDepth);
}
bool_t physicsTestDispatch(
const vec3 aPos, const physicsshape_t aShape,
const vec3 bPos, const physicsshape_t bShape,
vec3 outNormal, float_t *outDepth
) {
physicshapetype_t ta = aShape.type;
physicshapetype_t tb = bShape.type;
if(tb == PHYSICS_SHAPE_PLANE) {
const float_t *pn = bShape.data.plane.normal;
const float_t pd = bShape.data.plane.distance;
switch(ta) {
case PHYSICS_SHAPE_CUBE:
return physicsTestAabbVsPlane(
aPos, aShape.data.cube.halfExtents,
pn, pd, outNormal, outDepth
);
case PHYSICS_SHAPE_SPHERE:
return physicsTestSphereVsPlane(
aPos, aShape.data.sphere.radius,
pn, pd, outNormal, outDepth
);
case PHYSICS_SHAPE_CAPSULE:
return physicsTestCapsuleVsPlane(
aPos,
aShape.data.capsule.radius,
aShape.data.capsule.halfHeight,
pn, pd, outNormal, outDepth
);
default:
return false;
}
}
if(ta == PHYSICS_SHAPE_PLANE) {
vec3 tmp; float_t d;
if(!physicsTestDispatch(
bPos, bShape, aPos, aShape, tmp, &d
)) return false;
glm_vec3_scale(tmp, -1.0f, outNormal);
*outDepth = d;
return true;
}
switch(ta) {
case PHYSICS_SHAPE_CUBE: {
const float_t *ac = aPos;
const float_t *ah = aShape.data.cube.halfExtents;
switch(tb) {
case PHYSICS_SHAPE_CUBE:
return physicsTestAabbVsAabb(
ac, ah,
bPos, bShape.data.cube.halfExtents,
outNormal, outDepth
);
case PHYSICS_SHAPE_SPHERE: {
vec3 tmp; float_t d;
if(!physicsTestSphereVsAabb(
bPos, bShape.data.sphere.radius,
ac, ah, tmp, &d
)) return false;
glm_vec3_scale(tmp, -1.0f, outNormal);
*outDepth = d;
return true;
}
case PHYSICS_SHAPE_CAPSULE: {
vec3 tmp; float_t d;
if(!physicsTestCapsuleVsAabb(
bPos,
bShape.data.capsule.radius,
bShape.data.capsule.halfHeight,
ac, ah, tmp, &d
)) return false;
glm_vec3_scale(tmp, -1.0f, outNormal);
*outDepth = d;
return true;
}
default: return false;
}
}
case PHYSICS_SHAPE_SPHERE: {
const float_t sr = aShape.data.sphere.radius;
switch(tb) {
case PHYSICS_SHAPE_CUBE:
return physicsTestSphereVsAabb(
aPos, sr,
bPos, bShape.data.cube.halfExtents,
outNormal, outDepth
);
case PHYSICS_SHAPE_SPHERE:
return physicsTestSphereVsSphere(
aPos, sr,
bPos, bShape.data.sphere.radius,
outNormal, outDepth
);
case PHYSICS_SHAPE_CAPSULE: {
vec3 tmp; float_t d;
if(!physicsTestCapsuleVsSphere(
bPos,
bShape.data.capsule.radius,
bShape.data.capsule.halfHeight,
aPos, sr, tmp, &d
)) return false;
glm_vec3_scale(tmp, -1.0f, outNormal);
*outDepth = d;
return true;
}
default: return false;
}
}
case PHYSICS_SHAPE_CAPSULE: {
const float_t cr = aShape.data.capsule.radius;
const float_t chh = aShape.data.capsule.halfHeight;
switch(tb) {
case PHYSICS_SHAPE_CUBE:
return physicsTestCapsuleVsAabb(
aPos, cr, chh,
bPos, bShape.data.cube.halfExtents,
outNormal, outDepth
);
case PHYSICS_SHAPE_SPHERE:
return physicsTestCapsuleVsSphere(
aPos, cr, chh,
bPos, bShape.data.sphere.radius,
outNormal, outDepth
);
case PHYSICS_SHAPE_CAPSULE:
return physicsTestCapsuleVsCapsule(
aPos, cr, chh,
bPos,
bShape.data.capsule.radius,
bShape.data.capsule.halfHeight,
outNormal, outDepth
);
default: return false;
}
}
default: return false;
}
}
bool_t physicsTestShapeVsShape(
const vec3 aPos, const physicsshape_t aShape,
const vec3 bPos, const physicsshape_t bShape,
vec3 outNormal, float_t *outDepth
) {
return physicsTestDispatch(
aPos, aShape, bPos, bShape, outNormal, outDepth
);
}
-247
View File
@@ -1,247 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "physicsshape.h"
/**
* Tests overlap between two axis-aligned bounding boxes.
* outNormal points from B toward A.
*
* @param ac Center of AABB A.
* @param ah Half-extents of AABB A.
* @param bc Center of AABB B.
* @param bh Half-extents of AABB B.
* @param outNormal Push-out normal (B toward A).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestAabbVsAabb(
const vec3 ac, const vec3 ah,
const vec3 bc, const vec3 bh,
vec3 outNormal, float_t *outDepth
);
/**
* Tests overlap between two spheres.
* outNormal points from B toward A.
*
* @param ac Center of sphere A.
* @param ar Radius of sphere A.
* @param bc Center of sphere B.
* @param br Radius of sphere B.
* @param outNormal Push-out normal (B toward A).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestSphereVsSphere(
const vec3 ac, const float_t ar,
const vec3 bc, const float_t br,
vec3 outNormal, float_t *outDepth
);
/**
* Tests overlap between a sphere and an axis-aligned bounding box.
* outNormal points from the AABB toward the sphere.
*
* @param sc Center of the sphere.
* @param sr Radius of the sphere.
* @param ac Center of the AABB.
* @param ah Half-extents of the AABB.
* @param outNormal Push-out normal (AABB toward sphere).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestSphereVsAabb(
const vec3 sc, const float_t sr,
const vec3 ac, const vec3 ah,
vec3 outNormal, float_t *outDepth
);
/**
* Tests overlap between a sphere and an infinite plane.
* outNormal equals the plane normal (pointing away from the surface).
*
* @param sc Center of the sphere.
* @param sr Radius of the sphere.
* @param pn Plane normal (unit vector, world-space).
* @param pd Plane offset: dot(pn, surfacePoint) == pd.
* @param outNormal Push-out normal (equals pn).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestSphereVsPlane(
const vec3 sc, const float_t sr,
const vec3 pn, const float_t pd,
vec3 outNormal, float_t *outDepth
);
/**
* Tests overlap between an AABB and an infinite plane.
* outNormal equals the plane normal.
*
* @param ac Center of the AABB.
* @param ah Half-extents of the AABB.
* @param pn Plane normal (unit vector, world-space).
* @param pd Plane offset (see physicsTestSphereVsPlane).
* @param outNormal Push-out normal (equals pn).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestAabbVsPlane(
const vec3 ac, const vec3 ah,
const vec3 pn, const float_t pd,
vec3 outNormal, float_t *outDepth
);
/**
* Finds the closest point on segment [a, b] to query point p.
*
* @param a Start of the segment.
* @param b End of the segment.
* @param p Query point.
* @param out Receives the closest point on [a, b] to p.
*/
void physicsTestClosestPointOnSegment(
const vec3 a, const vec3 b, const vec3 p, vec3 out
);
/**
* Finds the closest points between two line segments.
*
* @param a1 Start of segment 1.
* @param b1 End of segment 1.
* @param a2 Start of segment 2.
* @param b2 End of segment 2.
* @param outP1 Receives the closest point on segment 1.
* @param outP2 Receives the closest point on segment 2.
*/
void physicsTestClosestPointsBetweenSegments(
const vec3 a1, const vec3 b1,
const vec3 a2, const vec3 b2,
vec3 outP1, vec3 outP2
);
/**
* Tests overlap between a Y-axis-aligned capsule and a sphere.
* outNormal points from the sphere toward the capsule.
*
* @param cc Center of the capsule.
* @param cr Radius of the capsule.
* @param chh Half-height of the capsule's cylindrical segment.
* @param sc Center of the sphere.
* @param sr Radius of the sphere.
* @param outNormal Push-out normal (sphere toward capsule).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestCapsuleVsSphere(
const vec3 cc, const float_t cr, const float_t chh,
const vec3 sc, const float_t sr,
vec3 outNormal, float_t *outDepth
);
/**
* Tests overlap between a Y-axis-aligned capsule and an AABB.
* outNormal points from the AABB toward the capsule.
*
* @param cc Center of the capsule.
* @param cr Radius of the capsule.
* @param chh Half-height of the capsule's cylindrical segment.
* @param ac Center of the AABB.
* @param ah Half-extents of the AABB.
* @param outNormal Push-out normal (AABB toward capsule).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestCapsuleVsAabb(
const vec3 cc, const float_t cr, const float_t chh,
const vec3 ac, const vec3 ah,
vec3 outNormal, float_t *outDepth
);
/**
* Tests overlap between a Y-axis-aligned capsule and an infinite plane.
* outNormal equals the plane normal.
*
* @param cc Center of the capsule.
* @param cr Radius of the capsule.
* @param chh Half-height of the capsule's cylindrical segment.
* @param pn Plane normal (unit vector, world-space).
* @param pd Plane offset (see physicsTestSphereVsPlane).
* @param outNormal Push-out normal (equals pn).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestCapsuleVsPlane(
const vec3 cc, const float_t cr, const float_t chh,
const vec3 pn, const float_t pd,
vec3 outNormal, float_t *outDepth
);
/**
* Tests overlap between two Y-axis-aligned capsules.
* outNormal points from capsule B toward capsule A.
*
* @param c1 Center of capsule A.
* @param r1 Radius of capsule A.
* @param hh1 Half-height of capsule A's cylindrical segment.
* @param c2 Center of capsule B.
* @param r2 Radius of capsule B.
* @param hh2 Half-height of capsule B's cylindrical segment.
* @param outNormal Push-out normal (B toward A).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestCapsuleVsCapsule(
const vec3 c1, const float_t r1, const float_t hh1,
const vec3 c2, const float_t r2, const float_t hh2,
vec3 outNormal, float_t *outDepth
);
/**
* Routes a shape-pair collision test to the correct primitive.
* When A is a plane, delegates with swapped arguments and negates
* the resulting normal. outNormal points from B toward A.
*
* @param aPos Position of shape A.
* @param aShape Shape descriptor of A.
* @param bPos Position of shape B.
* @param bShape Shape descriptor of B.
* @param outNormal Push-out normal (B toward A).
* @param outDepth Penetration depth.
* @return true if overlapping.
*/
bool_t physicsTestDispatch(
const vec3 aPos, const physicsshape_t aShape,
const vec3 bPos, const physicsshape_t bShape,
vec3 outNormal, float_t *outDepth
);
/**
* Tests for collision between two shapes. Returns true if they
* overlap, and if so, outputs the push-out normal and depth.
*
* outNormal always points from shape B toward shape A, so adding
* (outNormal * outDepth) to A's position separates the two shapes.
*
* @param aPos Position of shape A.
* @param aShape Shape descriptor of A.
* @param bPos Position of shape B.
* @param bShape Shape descriptor of B.
* @param outNormal Push-out normal, pointing from B toward A.
* @param outDepth Penetration depth (positive when overlapping).
* @return true if the shapes overlap, false otherwise.
*/
bool_t physicsTestShapeVsShape(
const vec3 aPos,
const physicsshape_t aShape,
const vec3 bPos,
const physicsshape_t bShape,
vec3 outNormal,
float_t *outDepth
);
-151
View File
@@ -1,151 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "physicsworld.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "entity/entity.h"
#include "entity/component.h"
#include "physicstest.h"
physicsworld_t PHYSICS_WORLD;
void physicsWorldInit() {
memoryZero(&PHYSICS_WORLD, sizeof(physicsworld_t));
PHYSICS_WORLD.gravity[0] = 0.0f;
PHYSICS_WORLD.gravity[1] = -9.81f;
PHYSICS_WORLD.gravity[2] = 0.0f;
}
void physicsWorldStep(const float_t dt) {
assertTrue(dt > 0.0f, "Delta time must be positive");
entityid_t physEnts[ENTITY_COUNT_MAX];
componentid_t physComps[ENTITY_COUNT_MAX];
entityid_t physCount = componentGetEntitiesWithComponent(
COMPONENT_TYPE_PHYSICS, physEnts, physComps
);
/* Pre-fetch all position and physics pointers once. */
entityposition_t *positions[ENTITY_COUNT_MAX];
entityphysics_t *physBodies[ENTITY_COUNT_MAX];
for(entityid_t i = 0; i < physCount; i++) {
componentid_t posComp = entityGetComponent(
physEnts[i], COMPONENT_TYPE_POSITION
);
positions[i] = (posComp != 0xFF)
? entityPositionGet(physEnts[i], posComp)
: NULL;
physBodies[i] = entityPhysicsGet(physEnts[i], physComps[i]);
}
/* Phase 1: integrate dynamic bodies (gravity + velocity -> position).
* Writes directly to pos->position, matrix rebuilt at end. */
for(entityid_t i = 0; i < physCount; i++) {
if(!positions[i]) continue;
entityphysics_t *phys = physBodies[i];
if(phys->type != PHYSICS_BODY_DYNAMIC) continue;
phys->onGround = false;
phys->velocity[0] += PHYSICS_WORLD.gravity[0] * phys->gravityScale * dt;
phys->velocity[1] += PHYSICS_WORLD.gravity[1] * phys->gravityScale * dt;
phys->velocity[2] += PHYSICS_WORLD.gravity[2] * phys->gravityScale * dt;
float_t *pos = positions[i]->position;
pos[0] += phys->velocity[0] * dt;
pos[1] += phys->velocity[1] * dt;
pos[2] += phys->velocity[2] * dt;
}
/* Phase 2: dynamic vs static/kinematic. */
for(entityid_t i = 0; i < physCount; i++) {
if(!positions[i]) continue;
entityphysics_t *phys = physBodies[i];
if(phys->type != PHYSICS_BODY_DYNAMIC) continue;
float_t *pos = positions[i]->position;
for(entityid_t j = 0; j < physCount; j++) {
if(i == j || !positions[j]) continue;
entityphysics_t *otherPhys = physBodies[j];
if(otherPhys->type == PHYSICS_BODY_DYNAMIC) continue;
vec3 normal; float_t depth;
if(!physicsTestShapeVsShape(
pos, phys->shape,
positions[j]->position, otherPhys->shape,
normal, &depth
)) continue;
pos[0] += normal[0] * depth;
pos[1] += normal[1] * depth;
pos[2] += normal[2] * depth;
float_t vn = glm_vec3_dot(phys->velocity, normal);
if(vn < 0.0f) {
phys->velocity[0] -= vn * normal[0];
phys->velocity[1] -= vn * normal[1];
phys->velocity[2] -= vn * normal[2];
}
if(normal[1] > PHYSICS_GROUND_THRESHOLD) phys->onGround = true;
}
}
/* Phase 3: dynamic vs dynamic. */
for(entityid_t i = 0; i < physCount; i++) {
if(!positions[i]) continue;
entityphysics_t *physA = physBodies[i];
if(physA->type != PHYSICS_BODY_DYNAMIC) continue;
float_t *posA = positions[i]->position;
for(entityid_t j = i + 1; j < physCount; j++) {
if(!positions[j]) continue;
entityphysics_t *physB = physBodies[j];
if(physB->type != PHYSICS_BODY_DYNAMIC) continue;
float_t *posB = positions[j]->position;
vec3 normal; float_t depth;
if(!physicsTestShapeVsShape(
posA, physA->shape, posB, physB->shape, normal, &depth
)) continue;
posA[0] += normal[0] * depth * 0.5f;
posA[1] += normal[1] * depth * 0.5f;
posA[2] += normal[2] * depth * 0.5f;
posB[0] -= normal[0] * depth * 0.5f;
posB[1] -= normal[1] * depth * 0.5f;
posB[2] -= normal[2] * depth * 0.5f;
float_t v_rel = glm_vec3_dot(physA->velocity, normal)
- glm_vec3_dot(physB->velocity, normal);
if(v_rel < 0.0f) {
physA->velocity[0] -= v_rel * normal[0];
physA->velocity[1] -= v_rel * normal[1];
physA->velocity[2] -= v_rel * normal[2];
physB->velocity[0] += v_rel * normal[0];
physB->velocity[1] += v_rel * normal[1];
physB->velocity[2] += v_rel * normal[2];
}
if( normal[1] > PHYSICS_GROUND_THRESHOLD) physA->onGround = true;
if(-normal[1] > PHYSICS_GROUND_THRESHOLD) physB->onGround = true;
}
}
/* Rebuild transforms for all dynamic bodies once, after all phases. */
for(entityid_t i = 0; i < physCount; i++) {
if(!positions[i]) continue;
if(physBodies[i]->type != PHYSICS_BODY_DYNAMIC) continue;
entityPositionRebuild(positions[i]);
}
}
-30
View File
@@ -1,30 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "physics/physicsshape.h"
#include "physics/physicsbodytype.h"
#define PHYSICS_GROUND_THRESHOLD 0.707f
typedef struct {
vec3 gravity;
} physicsworld_t;
extern physicsworld_t PHYSICS_WORLD;
/**
* Initializes the physics world.
*/
void physicsWorldInit(void);
/**
* Steps the physics simulation forward.
*
* @param dt The time delta in seconds since the last step.
*/
void physicsWorldStep(const float_t dt);
+20
View File
@@ -0,0 +1,20 @@
# Copyright (c) 2025 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
rpg.c
rpgcamera.c
rpgtextbox.c
)
# Subdirs
add_subdirectory(cutscene)
add_subdirectory(entity)
add_subdirectory(overworld)
add_subdirectory(story)
add_subdirectory(item)
@@ -1,13 +1,14 @@
# Copyright (c) 2026 Dominic Masters
# Copyright (c) 2025 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
modulecomponent.c
moduleentity.c
cutscenesystem.c
cutscenemode.c
)
# Subdirs
add_subdirectory(component)
add_subdirectory(item)
+14
View File
@@ -0,0 +1,14 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/cutscene/item/cutsceneitem.h"
typedef struct cutscene_s {
const cutsceneitem_t *items;
uint8_t itemCount;
} cutscene_t;
+19
View File
@@ -0,0 +1,19 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/cutscenesystem.h"
bool_t cutsceneModeIsInputAllowed() {
switch(CUTSCENE_SYSTEM.mode) {
case CUTSCENE_MODE_FULL_FREEZE:
case CUTSCENE_MODE_INPUT_FREEZE:
return false;
default:
return true;
}
}
+26
View File
@@ -0,0 +1,26 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef enum {
CUTSCENE_MODE_NONE,
CUTSCENE_MODE_FULL_FREEZE,
CUTSCENE_MODE_INPUT_FREEZE,
CUTSCENE_MODE_GAMEPLAY
} cutscenemode_t;
// Default mode for all cutscenes.
#define CUTSCENE_MODE_INITIAL CUTSCENE_MODE_INPUT_FREEZE
/**
* Check if input is allowed in the current cutscene mode.
*
* @return true if input is allowed, false otherwise.
*/
bool_t cutsceneModeIsInputAllowed();
+56
View File
@@ -0,0 +1,56 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "cutscenesystem.h"
#include "util/memory.h"
cutscenesystem_t CUTSCENE_SYSTEM;
void cutsceneSystemInit() {
memoryZero(&CUTSCENE_SYSTEM, sizeof(cutscenesystem_t));
}
void cutsceneSystemStartCutscene(const cutscene_t *cutscene) {
CUTSCENE_SYSTEM.scene = cutscene;
CUTSCENE_SYSTEM.mode = CUTSCENE_MODE_INITIAL;
CUTSCENE_SYSTEM.currentItem = 0xFF;// Set to 0xFF so start wraps.
cutsceneSystemNext();
}
void cutsceneSystemUpdate() {
if(CUTSCENE_SYSTEM.scene == NULL) return;
const cutsceneitem_t *item = cutsceneSystemGetCurrentItem();
cutsceneItemUpdate(item, &CUTSCENE_SYSTEM.data);
}
void cutsceneSystemNext() {
if(CUTSCENE_SYSTEM.scene == NULL) return;
CUTSCENE_SYSTEM.currentItem++;
// End of the cutscene?
if(
CUTSCENE_SYSTEM.currentItem >= CUTSCENE_SYSTEM.scene->itemCount
) {
CUTSCENE_SYSTEM.scene = NULL;
CUTSCENE_SYSTEM.currentItem = 0xFF;
CUTSCENE_SYSTEM.mode = CUTSCENE_MODE_NONE;
return;
}
// Start item.
const cutsceneitem_t *item = cutsceneSystemGetCurrentItem();
memset(&CUTSCENE_SYSTEM.data, 0, sizeof(CUTSCENE_SYSTEM.data));
cutsceneItemStart(item, &CUTSCENE_SYSTEM.data);
}
const cutsceneitem_t * cutsceneSystemGetCurrentItem() {
if(CUTSCENE_SYSTEM.scene == NULL) return NULL;
return &CUTSCENE_SYSTEM.scene->items[CUTSCENE_SYSTEM.currentItem];
}
+50
View File
@@ -0,0 +1,50 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "cutscene.h"
#include "cutscenemode.h"
typedef struct {
const cutscene_t *scene;
uint8_t currentItem;
// Data (used by the current item).
cutsceneitemdata_t data;
cutscenemode_t mode;
} cutscenesystem_t;
extern cutscenesystem_t CUTSCENE_SYSTEM;
/**
* Initialize the cutscene system.
*/
void cutsceneSystemInit();
/**
* Start a cutscene.
*
* @param cutscene Pointer to the cutscene to start.
*/
void cutsceneSystemStartCutscene(const cutscene_t *cutscene);
/**
* Advance to the next item in the cutscene.
*/
void cutsceneSystemNext();
/**
* Update the cutscene system for one frame.
*/
void cutsceneSystemUpdate();
/**
* Get the current cutscene item.
*
* @return Pointer to the current cutscene item.
*/
const cutsceneitem_t * cutsceneSystemGetCurrentItem();
@@ -1,4 +1,4 @@
# Copyright (c) 2026 Dominic Masters
# Copyright (c) 2025 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
@@ -6,5 +6,5 @@
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
entityphysics.c
cutsceneitem.c
)
@@ -0,0 +1,11 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef void (*cutscenecallback_t)(void);
+54
View File
@@ -0,0 +1,54 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/cutscenesystem.h"
#include "input/input.h"
#include "time/time.h"
void cutsceneItemStart(const cutsceneitem_t *item, cutsceneitemdata_t *data) {
switch(item->type) {
case CUTSCENE_ITEM_TYPE_TEXT: {
rpgTextboxShow(
item->text.position,
item->text.text
);
break;
}
case CUTSCENE_ITEM_TYPE_WAIT:
data->wait = item->wait;
break;
case CUTSCENE_ITEM_TYPE_CALLBACK:
if(item->callback != NULL) item->callback();
break;
case CUTSCENE_ITEM_TYPE_CUTSCENE:
if(item->cutscene != NULL) cutsceneSystemStartCutscene(item->cutscene);
break;
default:
break;
}
}
void cutsceneItemUpdate(const cutsceneitem_t *item, cutsceneitemdata_t *data) {
switch(item->type) {
case CUTSCENE_ITEM_TYPE_TEXT:
if(rpgTextboxIsVisible()) return;
cutsceneSystemNext();
break;
case CUTSCENE_ITEM_TYPE_WAIT:
data->wait -= TIME.delta;
if(data->wait <= 0) cutsceneSystemNext();
break;
default:
break;
}
}
+53
View File
@@ -0,0 +1,53 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "cutscenewait.h"
#include "cutscenecallback.h"
#include "cutscenetext.h"
typedef struct cutscene_s cutscene_t;
typedef enum {
CUTSCENE_ITEM_TYPE_NULL,
CUTSCENE_ITEM_TYPE_TEXT,
CUTSCENE_ITEM_TYPE_CALLBACK,
CUTSCENE_ITEM_TYPE_WAIT,
CUTSCENE_ITEM_TYPE_CUTSCENE
} cutsceneitemtype_t;
typedef struct cutsceneitem_s {
cutsceneitemtype_t type;
// Arguments/Data that will be used when this item is invoked.
union {
cutscenetext_t text;
cutscenecallback_t callback;
cutscenewait_t wait;
const cutscene_t *cutscene;
};
} cutsceneitem_t;
typedef union {
cutscenewaitdata_t wait;
} cutsceneitemdata_t;
/**
* Start the given cutscene item.
*
* @param item The cutscene item to start.
* @param data The cutscene item data storage.
*/
void cutsceneItemStart(const cutsceneitem_t *item, cutsceneitemdata_t *data);
/**
* Tick the given cutscene item (one frame).
*
* @param item The cutscene item to tick.
* @param data The cutscene item data storage.
*/
void cutsceneItemUpdate(const cutsceneitem_t *item, cutsceneitemdata_t *data);
+14
View File
@@ -0,0 +1,14 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/rpgtextbox.h"
typedef struct {
char_t text[RPG_TEXTBOX_MAX_CHARS];
rpgtextboxpos_t position;
} cutscenetext_t;
+12
View File
@@ -0,0 +1,12 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef float_t cutscenewait_t;
typedef float_t cutscenewaitdata_t;
+30
View File
@@ -0,0 +1,30 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/cutscene/cutscenesystem.h"
static const cutsceneitem_t TEST_CUTSCENE_ONE_ITEMS[] = {
{ .type = CUTSCENE_ITEM_TYPE_TEXT, .text = { .text = "This is a test cutscene.", .position = RPG_TEXTBOX_POS_BOTTOM } },
{ .type = CUTSCENE_ITEM_TYPE_WAIT, .wait = 2.0f },
{ .type = CUTSCENE_ITEM_TYPE_TEXT, .text = { .text = "It has multiple lines of text.\nAnd waits in between.", .position = RPG_TEXTBOX_POS_TOP } },
};
static const cutscene_t TEST_CUTSCENE_ONE = {
.items = TEST_CUTSCENE_ONE_ITEMS,
.itemCount = sizeof(TEST_CUTSCENE_ONE_ITEMS) / sizeof(cutsceneitem_t)
};
static const cutsceneitem_t TEST_CUTSCENE_TWO_ITEMS[] = {
{ .type = CUTSCENE_ITEM_TYPE_WAIT, .wait = 1.0f },
{ .type = CUTSCENE_ITEM_TYPE_CUTSCENE, .cutscene = &TEST_CUTSCENE_ONE },
};
static const cutscene_t TEST_CUTSCENE = {
.items = TEST_CUTSCENE_TWO_ITEMS,
.itemCount = sizeof(TEST_CUTSCENE_TWO_ITEMS) / sizeof(cutsceneitem_t)
};
@@ -1,4 +1,4 @@
# Copyright (c) 2026 Dominic Masters
# Copyright (c) 2025 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
@@ -7,9 +7,8 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
entity.c
entitymanager.c
component.c
entityanim.c
npc.c
player.c
entitydir.c
)
# Subdirs
add_subdirectory(component)
+201
View File
@@ -0,0 +1,201 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entity.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "time/time.h"
#include "util/math.h"
#include "rpg/cutscene/cutscenemode.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/tile.h"
entity_t ENTITIES[ENTITY_COUNT];
void entityInit(entity_t *entity, const entitytype_t type) {
assertNotNull(entity, "Entity pointer cannot be NULL");
assertTrue(type < ENTITY_TYPE_COUNT, "Invalid entity type");
assertTrue(type != ENTITY_TYPE_NULL, "Cannot have NULL entity type");
assertTrue(
entity >= ENTITIES && entity < ENTITIES + ENTITY_COUNT,
"Entity pointer is out of bounds"
);
memoryZero(entity, sizeof(entity_t));
entity->id = (uint8_t)(entity - ENTITIES);
entity->type = type;
if(ENTITY_CALLBACKS[type].init != NULL) ENTITY_CALLBACKS[type].init(entity);
}
void entityUpdate(entity_t *entity) {
assertNotNull(entity, "Entity pointer cannot be NULL");
assertTrue(entity->type < ENTITY_TYPE_COUNT, "Invalid entity type");
assertTrue(entity->type != ENTITY_TYPE_NULL, "Cannot have NULL entity type");
// What state is the entity in?
if(entity->animation != ENTITY_ANIM_IDLE) {
// Entity is mid animation, tick it (down).
entity->animTime -= TIME.delta;
if(entity->animTime <= 0) {
entity->animation = ENTITY_ANIM_IDLE;
entity->animTime = 0;
}
return;
}
// Movement code.
if(
cutsceneModeIsInputAllowed() &&
ENTITY_CALLBACKS[entity->type].movement != NULL
) {
ENTITY_CALLBACKS[entity->type].movement(entity);
}
}
void entityTurn(entity_t *entity, const entitydir_t direction) {
entity->direction = direction;
entity->animation = ENTITY_ANIM_TURN;
entity->animTime = ENTITY_ANIM_TURN_DURATION;
}
void entityWalk(entity_t *entity, const entitydir_t direction) {
// TODO: Animation, delay, etc.
entity->direction = direction;
// Where are we moving?
worldpos_t newPos = entity->position;
{
worldunits_t relX, relY;
entityDirGetRelative(direction, &relX, &relY);
newPos.x += relX;
newPos.y += relY;
}
// Get tile under foot
tile_t tileCurrent = mapGetTile(entity->position);
tile_t tileNew = mapGetTile(newPos);
bool_t fall = false;
bool_t raise = false;
// Are we walking up a ramp?
if(
tileIsRamp(tileCurrent) &&
(
// Can only walk UP the direction the ramp faces.
(direction+TILE_SHAPE_RAMP_SOUTH) == tileCurrent ||
// If diagonal ramp, can go up one of two ways only.
(
(
tileCurrent == TILE_SHAPE_RAMP_SOUTHEAST &&
(direction == ENTITY_DIR_SOUTH || direction == ENTITY_DIR_EAST)
) ||
(
tileCurrent == TILE_SHAPE_RAMP_SOUTHWEST &&
(direction == ENTITY_DIR_SOUTH || direction == ENTITY_DIR_WEST)
) ||
(
tileCurrent == TILE_SHAPE_RAMP_NORTHEAST &&
(direction == ENTITY_DIR_NORTH || direction == ENTITY_DIR_EAST)
) ||
(
tileCurrent == TILE_SHAPE_RAMP_NORTHWEST &&
(direction == ENTITY_DIR_NORTH || direction == ENTITY_DIR_WEST)
)
)
// Must be able to walk up.
)
) {
tileNew = TILE_SHAPE_NULL;// Force check for ramp above.
worldpos_t abovePos = newPos;
abovePos.z += 1;
tile_t tileAbove = mapGetTile(abovePos);
if(tileAbove != TILE_SHAPE_NULL && tileIsWalkable(tileAbove)) {
// We can go up the ramp.
raise = true;
}
} else if(tileNew == TILE_SHAPE_NULL && newPos.z > 0) {
// Falling down?
worldpos_t belowPos = newPos;
belowPos.z -= 1;
tile_t tileBelow = mapGetTile(belowPos);
if(
tileBelow != TILE_SHAPE_NULL &&
tileIsRamp(tileBelow) &&
(
// This handles regular cardinal ramps
(entityDirGetOpposite(direction)+TILE_SHAPE_RAMP_SOUTH) == tileBelow ||
// This handles diagonal ramps
(
(
tileBelow == TILE_SHAPE_RAMP_SOUTHEAST &&
(direction == ENTITY_DIR_NORTH || direction == ENTITY_DIR_WEST)
) ||
(
tileBelow == TILE_SHAPE_RAMP_SOUTHWEST &&
(direction == ENTITY_DIR_NORTH || direction == ENTITY_DIR_EAST)
) ||
(
tileBelow == TILE_SHAPE_RAMP_NORTHEAST &&
(direction == ENTITY_DIR_SOUTH || direction == ENTITY_DIR_WEST)
) ||
(
tileBelow == TILE_SHAPE_RAMP_NORTHWEST &&
(direction == ENTITY_DIR_SOUTH || direction == ENTITY_DIR_EAST)
)
)
)
) {
// We will fall to this tile.
fall = true;
}
}
// Can we walk here?
if(!raise && !fall && !tileIsWalkable(tileNew)) return;// Blocked
// Entity in way?
entity_t *other = ENTITIES;
do {
if(other == entity) continue;
if(other->type == ENTITY_TYPE_NULL) continue;
if(!worldPosIsEqual(other->position, newPos)) continue;
return;// Blocked
} while(++other, other < &ENTITIES[ENTITY_COUNT]);
entity->lastPosition = entity->position;
entity->position = newPos;
entity->animation = ENTITY_ANIM_WALK;
entity->animTime = ENTITY_ANIM_WALK_DURATION;// TODO: Running vs walking
if(raise) {
entity->position.z += 1;
} else if(fall) {
entity->position.z -= 1;
}
}
entity_t * entityGetAt(const worldpos_t position) {
entity_t *ent = ENTITIES;
do {
if(ent->type == ENTITY_TYPE_NULL) continue;
if(!worldPosIsEqual(ent->position, position)) continue;
return ent;
} while(++ent, ent < &ENTITIES[ENTITY_COUNT]);
return NULL;
}
uint8_t entityGetAvailable() {
entity_t *ent = ENTITIES;
do {
if(ent->type == ENTITY_TYPE_NULL) return ent - ENTITIES;
} while(++ent, ent < &ENTITIES[ENTITY_COUNT]);
return 0xFF;
}
+77
View File
@@ -0,0 +1,77 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "entitydir.h"
#include "entityanim.h"
#include "entitytype.h"
#include "npc.h"
typedef struct map_s map_t;
typedef struct entity_s {
uint8_t id;
entitytype_t type;
entitytypedata_t data;
// Movement
entitydir_t direction;
worldpos_t position;
worldpos_t lastPosition;
entityanim_t animation;
float_t animTime;
} entity_t;
extern entity_t ENTITIES[ENTITY_COUNT];
/**
* Initializes an entity structure.
*
* @param entity Pointer to the entity structure to initialize.
* @param type The type of the entity.
*/
void entityInit(entity_t *entity, const entitytype_t type);
/**
* Updates an entity.
*
* @param entity Pointer to the entity structure to update.
*/
void entityUpdate(entity_t *entity);
/**
* Turn an entity to face a new direction.
*
* @param entity Pointer to the entity to turn.
* @param direction The direction to face.
*/
void entityTurn(entity_t *entity, const entitydir_t direction);
/**
* Make an entity walk in a direction.
*
* @param entity Pointer to the entity to make walk.
* @param direction The direction to walk in.
*/
void entityWalk(entity_t *entity, const entitydir_t direction);
/**
* Gets the entity at a specific world position.
*
* @param map Pointer to the map to check.
* @param pos The world position to check.
* @return Pointer to the entity at the position, or NULL if none.
*/
entity_t *entityGetAt(const worldpos_t pos);
/**
* Gets an available entity index.
*
* @return The index of an available entity, or 0xFF if none are available.
*/
uint8_t entityGetAvailable();
+9
View File
@@ -0,0 +1,9 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entityanim.h"
+18
View File
@@ -0,0 +1,18 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#define ENTITY_ANIM_TURN_DURATION 0.06f
#define ENTITY_ANIM_WALK_DURATION 0.1f
typedef enum {
ENTITY_ANIM_IDLE,
ENTITY_ANIM_TURN,
ENTITY_ANIM_WALK,
} entityanim_t;
+51
View File
@@ -0,0 +1,51 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entitydir.h"
#include "assert/assert.h"
entitydir_t entityDirGetOpposite(const entitydir_t dir) {
switch(dir) {
case ENTITY_DIR_NORTH: return ENTITY_DIR_SOUTH;
case ENTITY_DIR_SOUTH: return ENTITY_DIR_NORTH;
case ENTITY_DIR_EAST: return ENTITY_DIR_WEST;
case ENTITY_DIR_WEST: return ENTITY_DIR_EAST;
default: return dir;
}
}
void entityDirGetRelative(
const entitydir_t from,
worldunits_t *outX,
worldunits_t *outY
) {
assertValidEntityDir(from, "Invalid direction provided");
assertNotNull(outX, "Output X pointer cannot be NULL");
assertNotNull(outY, "Output Y pointer cannot be NULL");
switch(from) {
case ENTITY_DIR_NORTH:
*outX = 0;
*outY = -1;
break;
case ENTITY_DIR_EAST:
*outX = 1;
*outY = 0;
break;
case ENTITY_DIR_SOUTH:
*outX = 0;
*outY = 1;
break;
case ENTITY_DIR_WEST:
*outX = -1;
*outY = 0;
break;
}
}
+54
View File
@@ -0,0 +1,54 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/overworld/worldpos.h"
typedef enum {
ENTITY_DIR_NORTH,
ENTITY_DIR_EAST,
ENTITY_DIR_SOUTH,
ENTITY_DIR_WEST,
ENTITY_DIR_UP = ENTITY_DIR_NORTH,
ENTITY_DIR_DOWN = ENTITY_DIR_SOUTH,
ENTITY_DIR_LEFT = ENTITY_DIR_WEST,
ENTITY_DIR_RIGHT = ENTITY_DIR_EAST,
} entitydir_t;
/**
* Gets the opposite direction of a given direction.
*
* @param dir The direction to get the opposite of.
* @return entitydir_t The opposite direction.
*/
entitydir_t entityDirGetOpposite(const entitydir_t dir);
/**
* Asserts a given direction is valid.
*
* @param dir The direction to validate.
* @param msg The message to display if the assertion fails.
*/
#define assertValidEntityDir(dir, msg) \
assertTrue( \
(dir) == ENTITY_DIR_NORTH || \
(dir) == ENTITY_DIR_EAST || \
(dir) == ENTITY_DIR_SOUTH || \
(dir) == ENTITY_DIR_WEST, \
msg \
)
/**
* Gets the relative x and y offsets for a given direction.
*
* @param dir The direction to get offsets for.
* @param relX Pointer to store the relative x offset.
* @param relY Pointer to store the relative y offset.
*/
void entityDirGetRelative(
const entitydir_t dir, worldunits_t *relX, worldunits_t *relY
);
+63
View File
@@ -0,0 +1,63 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/entity/player.h"
#include "npc.h"
typedef enum {
ENTITY_TYPE_NULL,
ENTITY_TYPE_PLAYER,
ENTITY_TYPE_NPC,
ENTITY_TYPE_COUNT
} entitytype_enum_t;
typedef uint8_t entitytype_t;
typedef union {
player_t player;
npc_t npc;
} entitytypedata_t;
typedef struct {
/**
* Initialization callback for the entity type.
* @param entity Pointer to the entity to initialize.
*/
void (*init)(entity_t *entity);
/**
* Movement callback for the entity type.
* @param entity Pointer to the entity to move.
*/
void (*movement)(entity_t *entity);
/**
* Interaction callback for the entity type.
* @param player Pointer to the player entity.
* @param entity Pointer to the entity to interact with.
* @return True if the entity handled the interaction, false otherwise.
*/
bool_t (*interact)(entity_t *player, entity_t *entity);
} entitycallback_t;
static const entitycallback_t ENTITY_CALLBACKS[ENTITY_TYPE_COUNT] = {
[ENTITY_TYPE_NULL] = { NULL },
[ENTITY_TYPE_PLAYER] = {
.init = playerInit,
.movement = playerInput
},
[ENTITY_TYPE_NPC] = {
.init = npcInit,
.movement = npcMovement,
.interact = npcInteract
}
};
+31
View File
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entity.h"
#include "assert/assert.h"
#include "rpg/cutscene/scene/testcutscene.h"
#include "rpg/rpgtextbox.h"
void npcInit(entity_t *entity) {
assertNotNull(entity, "Entity pointer cannot be NULL");
}
void npcMovement(entity_t *entity) {
assertNotNull(entity, "Entity pointer cannot be NULL");
}
bool_t npcInteract(entity_t *player, entity_t *npc) {
assertNotNull(player, "Player entity pointer cannot be NULL");
assertNotNull(npc, "NPC entity pointer cannot be NULL");
cutsceneSystemStartCutscene(&TEST_CUTSCENE);
// rpgTextboxShow(RPG_TEXTBOX_POS_BOTTOM, "Hello World!");
return false;
};
+37
View File
@@ -0,0 +1,37 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct entity_s entity_t;
typedef struct {
void *nothing;
} npc_t;
/**
* Initializes an NPC entity.
*
* @param entity Pointer to the entity structure to initialize.
*/
void npcInit(entity_t *entity);
/**
* Updates an NPC entity.
*
* @param entity Pointer to the entity structure to update.
*/
void npcMovement(entity_t *entity);
/**
* Handles interaction with an NPC entity.
*
* @param player Pointer to the player entity.
* @param npc Pointer to the NPC entity.
*/
bool_t npcInteract(entity_t *player, entity_t *npc);
+54
View File
@@ -0,0 +1,54 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "entity.h"
#include "assert/assert.h"
#include "rpg/rpgcamera.h"
#include "util/memory.h"
#include "time/time.h"
void playerInit(entity_t *entity) {
assertNotNull(entity, "Entity pointer cannot be NULL");
}
void playerInput(entity_t *entity) {
assertNotNull(entity, "Entity pointer cannot be NULL");
// Turn
const playerinputdirmap_t *dirMap = PLAYER_INPUT_DIR_MAP;
do {
if(!inputIsDown(dirMap->action)) continue;
if(entity->direction == dirMap->direction) continue;
return entityTurn(entity, dirMap->direction);
} while((++dirMap)->action != 0xFF);
// Walk
dirMap = PLAYER_INPUT_DIR_MAP;
do {
if(!inputIsDown(dirMap->action)) continue;
if(entity->direction != dirMap->direction) continue;
return entityWalk(entity, dirMap->direction);
} while((++dirMap)->action != 0xFF);
// Interaction
if(inputPressed(INPUT_ACTION_ACCEPT)) {
worldunit_t x, y, z;
{
worldunits_t relX, relY;
entityDirGetRelative(entity->direction, &relX, &relY);
x = entity->position.x + relX;
y = entity->position.y + relY;
z = entity->position.z;
}
entity_t *interact = entityGetAt((worldpos_t){ x, y, z });
if(interact != NULL && ENTITY_CALLBACKS[interact->type].interact != NULL) {
if(ENTITY_CALLBACKS[interact->type].interact(entity, interact)) return;
}
}
}
+43
View File
@@ -0,0 +1,43 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "input/input.h"
typedef struct entity_s entity_t;
typedef struct {
void *nothing;
} player_t;
typedef struct {
inputaction_t action;
entitydir_t direction;
} playerinputdirmap_t;
static const playerinputdirmap_t PLAYER_INPUT_DIR_MAP[] = {
{ INPUT_ACTION_UP, ENTITY_DIR_NORTH },
{ INPUT_ACTION_DOWN, ENTITY_DIR_SOUTH },
{ INPUT_ACTION_LEFT, ENTITY_DIR_WEST },
{ INPUT_ACTION_RIGHT, ENTITY_DIR_EAST },
{ 0xFF, 0xFF }
};
/**
* Initializes a player entity.
*
* @param entity Pointer to the entity structure to initialize.
*/
void playerInit(entity_t *entity);
/**
* Handles movement logic for the player entity.
*
* @param entity Pointer to the player entity structure.
*/
void playerInput(entity_t *entity);
@@ -15,6 +15,6 @@ dusk_run_python(
dusk_item_csv_defs
tools.item.csv
--csv ${CMAKE_CURRENT_SOURCE_DIR}/item.csv
--output ${DUSK_GENERATED_HEADERS_DIR}/item/item.h
--output ${DUSK_GENERATED_HEADERS_DIR}/rpg/item/item.h
)
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} dusk_item_csv_defs)
@@ -6,7 +6,7 @@
*/
#pragma once
#include "item/item.h"
#include "rpg/item/item.h"
#define ITEM_STACK_QUANTITY_MAX UINT8_MAX
@@ -1,12 +1,13 @@
# Copyright (c) 2026 Dominic Masters
# Copyright (c) 2025 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
facingdir.c
maptypes.c
chunk.c
map.c
mapchunk.c
worldpos.c
tile.c
)
+20
View File
@@ -0,0 +1,20 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "chunk.h"
uint32_t chunkGetTileIndex(const chunkpos_t position) {
return (
(position.z * CHUNK_WIDTH * CHUNK_HEIGHT) +
(position.y * CHUNK_WIDTH) +
position.x
);
}
bool_t chunkPositionIsEqual(const chunkpos_t a, const chunkpos_t b) {
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z);
}
+46
View File
@@ -0,0 +1,46 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/overworld/tile.h"
#include "worldpos.h"
#include "display/mesh/quad.h"
#include "display/spritebatch/spritebatch.h"
// #define CHUNK_MESH_COUNT_MAX 3
// #define CHUNK_VERTEX_COUNT_MAX (QUAD_VERTEX_COUNT * CHUNK_MESH_COUNT_MAX)
#define CHUNK_ENTITY_COUNT_MAX 10
typedef struct chunk_s {
chunkpos_t position;
tile_t tiles[CHUNK_TILE_COUNT];
spritebatchsprite_t sprites[CHUNK_TILE_COUNT];
uint32_t spriteCount;
// uint8_t meshCount;
// meshvertex_t vertices[CHUNK_VERTEX_COUNT_MAX];
// mesh_t meshes[CHUNK_MESH_COUNT_MAX];
uint8_t entities[CHUNK_ENTITY_COUNT_MAX];
} chunk_t;
/**
* Gets the tile index for a tile position within a chunk.
*
* @param position The position within the chunk.
* @return The tile index within the chunk.
*/
uint32_t chunkGetTileIndex(const chunkpos_t position);
/**
* Checks if two chunk positions are equal.
*
* @param a The first chunk position.
* @param b The second chunk position.
* @return true if equal, false otherwise.
*/
bool_t chunkPositionIsEqual(const chunkpos_t a, const chunkpos_t b);
+239
View File
@@ -0,0 +1,239 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "map.h"
#include "util/memory.h"
#include "assert/assert.h"
#include "asset/asset.h"
#include "rpg/entity/entity.h"
#include "util/string.h"
map_t MAP;
errorret_t mapInit() {
memoryZero(&MAP, sizeof(map_t));
errorOk();
}
bool_t mapIsLoaded() {
return MAP.filePath[0] != '\0';
}
errorret_t mapLoad(const char_t *path, const chunkpos_t position) {
assertStrLenMin(path, 1, "Map file path cannot be empty");
assertStrLenMax(path, MAP_FILE_PATH_MAX - 1, "Map file path too long");
if(stringCompare(MAP.filePath, path) == 0) {
// Same map, no need to reload
errorOk();
}
chunkindex_t i;
// Unload all loaded chunks
if(mapIsLoaded()) {
for(i = 0; i < MAP_CHUNK_COUNT; i++) {
mapChunkUnload(&MAP.chunks[i]);
}
}
// Store the map file path
stringCopy(MAP.filePath, path, MAP_FILE_PATH_MAX);
// Determine directory path (it is dirname)
stringCopy(MAP.dirPath, path, MAP_FILE_PATH_MAX);
char_t *last = stringFindLastChar(MAP.dirPath, '/');
if(last == NULL) errorThrow("Invalid map file path");
// Store filename, sans extension
stringCopy(MAP.fileName, last + 1, MAP_FILE_PATH_MAX);
*last = '\0'; // Terminate to get directory path
last = stringFindLastChar(MAP.fileName, '.');
if(last == NULL) errorThrow("Map file name has no extension");
*last = '\0'; // Terminate to remove extension
// Reset map position
MAP.chunkPosition = position;
// Perform "initial load"
i = 0;
for(chunkunit_t z = 0; z < MAP_CHUNK_DEPTH; z++) {
for(chunkunit_t y = 0; y < MAP_CHUNK_HEIGHT; y++) {
for(chunkunit_t x = 0; x < MAP_CHUNK_WIDTH; x++) {
chunk_t *chunk = &MAP.chunks[i];
chunk->position.x = x + position.x;
chunk->position.y = y + position.y;
chunk->position.z = z + position.z;
MAP.chunkOrder[i] = chunk;
errorChain(mapChunkLoad(chunk));
i++;
}
}
}
errorOk();
}
errorret_t mapPositionSet(const chunkpos_t newPos) {
if(!mapIsLoaded()) errorThrow("No map loaded");
const chunkpos_t curPos = MAP.chunkPosition;
if(chunkPositionIsEqual(curPos, newPos)) {
errorOk();
}
// Determine which chunks remain loaded
chunkindex_t chunksRemaining[MAP_CHUNK_COUNT] = {0};
chunkindex_t chunksFreed[MAP_CHUNK_COUNT] = {0};
uint32_t remainingCount = 0;
uint32_t freedCount = 0;
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
// Will this chunk remain loaded?
chunk_t *chunk = &MAP.chunks[i];
if(
chunk->position.x >= newPos.x &&
chunk->position.x < newPos.x + MAP_CHUNK_WIDTH &&
chunk->position.y >= newPos.y &&
chunk->position.y < newPos.y + MAP_CHUNK_HEIGHT &&
chunk->position.z >= newPos.z &&
chunk->position.z < newPos.z + MAP_CHUNK_DEPTH
) {
// Stays loaded
chunksRemaining[remainingCount++] = i;
continue;
}
// Not remaining loaded
chunksFreed[freedCount++] = i;
}
// Unload the freed chunks
for(chunkindex_t i = 0; i < freedCount; i++) {
chunk_t *chunk = &MAP.chunks[chunksFreed[i]];
mapChunkUnload(chunk);
}
// This can probably be optimized later, for now we check each chunk and see
// if it needs loading or not, and update the chunk order
chunkindex_t orderIndex = 0;
for(chunkunit_t zOff = 0; zOff < MAP_CHUNK_DEPTH; zOff++) {
for(chunkunit_t yOff = 0; yOff < MAP_CHUNK_HEIGHT; yOff++) {
for(chunkunit_t xOff = 0; xOff < MAP_CHUNK_WIDTH; xOff++) {
const chunkpos_t newChunkPos = {
newPos.x + xOff, newPos.y + yOff, newPos.z + zOff
};
// Is this chunk already loaded (was not unloaded earlier)?
chunkindex_t chunkIndex = -1;
for(chunkindex_t i = 0; i < remainingCount; i++) {
chunk_t *chunk = &MAP.chunks[chunksRemaining[i]];
if(!chunkPositionIsEqual(chunk->position, newChunkPos)) continue;
chunkIndex = chunksRemaining[i];
break;
}
// Need to load this chunk
if(chunkIndex == -1) {
// Find a freed chunk to reuse
chunkIndex = chunksFreed[--freedCount];
chunk_t *chunk = &MAP.chunks[chunkIndex];
chunk->position = newChunkPos;
errorChain(mapChunkLoad(chunk));
}
MAP.chunkOrder[orderIndex++] = &MAP.chunks[chunkIndex];
}
}
}
// Update map position
MAP.chunkPosition = newPos;
errorOk();
}
void mapUpdate() {
}
void mapDispose() {
for(chunkindex_t i = 0; i < MAP_CHUNK_COUNT; i++) {
mapChunkUnload(&MAP.chunks[i]);
}
}
void mapChunkUnload(chunk_t* chunk) {
for(uint8_t i = 0; i < CHUNK_ENTITY_COUNT_MAX; i++) {
if(chunk->entities[i] == 0xFF) break;
entity_t *entity = &ENTITIES[chunk->entities[i]];
entity->type = ENTITY_TYPE_NULL;
}
for(uint8_t i = 0; i < chunk->meshCount; i++) {
if(chunk->meshes[i].vertexCount == 0) continue;
meshDispose(&chunk->meshes[i]);
}
}
errorret_t mapChunkLoad(chunk_t* chunk) {
if(!mapIsLoaded()) errorThrow("No map loaded");
char_t buffer[64];
// TODO: Can probably move this to asset load logic?
chunk->meshCount = 0;
memoryZero(chunk->meshes, sizeof(chunk->meshes));
memorySet(chunk->entities, 0xFF, sizeof(chunk->entities));
// Load.
errorOk();
}
chunkindex_t mapGetChunkIndexAt(const chunkpos_t position) {
if(!mapIsLoaded()) return -1;
chunkpos_t relPos = {
position.x - MAP.chunkPosition.x,
position.y - MAP.chunkPosition.y,
position.z - MAP.chunkPosition.z
};
if(
relPos.x < 0 || relPos.y < 0 || relPos.z < 0 ||
relPos.x >= MAP_CHUNK_WIDTH ||
relPos.y >= MAP_CHUNK_HEIGHT ||
relPos.z >= MAP_CHUNK_DEPTH
) {
return -1;
}
return chunkPosToIndex(&relPos);
}
chunk_t* mapGetChunk(const uint8_t index) {
if(index >= MAP_CHUNK_COUNT) return NULL;
if(!mapIsLoaded()) return NULL;
return MAP.chunkOrder[index];
}
tile_t mapGetTile(const worldpos_t position) {
if(!mapIsLoaded()) return TILE_SHAPE_NULL;
chunkpos_t chunkPos;
worldPosToChunkPos(&position, &chunkPos);
chunkindex_t chunkIndex = mapGetChunkIndexAt(chunkPos);
if(chunkIndex == -1) return TILE_SHAPE_NULL;
chunk_t *chunk = mapGetChunk(chunkIndex);
assertNotNull(chunk, "Chunk pointer cannot be NULL");
chunktileindex_t tileIndex = worldPosToChunkTileIndex(&position);
return chunk->tiles[tileIndex];
}
+106
View File
@@ -0,0 +1,106 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/overworld/chunk.h"
#define MAP_FILE_PATH_MAX 128
typedef struct map_s {
char_t filePath[MAP_FILE_PATH_MAX];
char_t dirPath[MAP_FILE_PATH_MAX];
char_t fileName[MAP_FILE_PATH_MAX];
chunk_t chunks[MAP_CHUNK_COUNT];
chunk_t *chunkOrder[MAP_CHUNK_COUNT];
chunkpos_t chunkPosition;
} map_t;
extern map_t MAP;
/**
* Initializes the map.
*
* @return An error code.
*/
errorret_t mapInit();
/**
* Checks if a map is loaded.
*
* @return true if a map is loaded, false otherwise.
*/
bool_t mapIsLoaded();
/**
* Loads a map from the given file path.
*
* @param path The file path.
* @param position The initial chunk position.
* @return An error code.
*/
errorret_t mapLoad(
const char_t *path,
const chunkpos_t position
);
/**
* Updates the map.
*/
void mapUpdate();
/**
* Disposes of the map.
*/
void mapDispose();
/**
* Sets the map position and updates chunks accordingly.
*
* @param newPos The new chunk position.
* @return An error code.
*/
errorret_t mapPositionSet(const chunkpos_t newPos);
/**
* Unloads a chunk.
*
* @param chunk The chunk to unload.
*/
void mapChunkUnload(chunk_t* chunk);
/**
* Loads a chunk.
*
* @param chunk The chunk to load.
* @return An error code.
*/
errorret_t mapChunkLoad(chunk_t* chunk);
/**
* Gets the index of a chunk, within the world, at the given position.
*
* @param position The chunk position.
* @return The index of the chunk, or -1 if out of bounds.
*/
chunkindex_t mapGetChunkIndexAt(const chunkpos_t position);
/**
* Gets a chunk by its index.
*
* @param chunkIndex The index of the chunk.
* @return A pointer to the chunk.
*/
chunk_t * mapGetChunk(const uint8_t chunkIndex);
/**
* Gets the tile at the given world position.
*
* @param position The world position.
* @return The tile at that position, or TILE_NULL if the chunk is unloaded.
*/
tile_t mapGetTile(const worldpos_t position);
+35
View File
@@ -0,0 +1,35 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "tile.h"
bool_t tileIsWalkable(const tile_t tile) {
switch(tile) {
case TILE_SHAPE_NULL:
return false;
default:
return true;
}
}
bool_t tileIsRamp(const tile_t tile) {
switch(tile) {
case TILE_SHAPE_RAMP_NORTH:
case TILE_SHAPE_RAMP_SOUTH:
case TILE_SHAPE_RAMP_EAST:
case TILE_SHAPE_RAMP_WEST:
case TILE_SHAPE_RAMP_NORTHEAST:
case TILE_SHAPE_RAMP_NORTHWEST:
case TILE_SHAPE_RAMP_SOUTHEAST:
case TILE_SHAPE_RAMP_SOUTHWEST:
return true;
default:
return false;
}
}
+42
View File
@@ -0,0 +1,42 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/entity/entitydir.h"
typedef enum {
TILE_SHAPE_NULL,
TILE_SHAPE_SOLID,
TILE_SHAPE_RAMP_NORTH,
TILE_SHAPE_RAMP_SOUTH,
TILE_SHAPE_RAMP_EAST,
TILE_SHAPE_RAMP_WEST,
TILE_SHAPE_RAMP_NORTHEAST,
TILE_SHAPE_RAMP_NORTHWEST,
TILE_SHAPE_RAMP_SOUTHEAST,
TILE_SHAPE_RAMP_SOUTHWEST,
TILE_SHAPE_COUNT
} tile_t;
/**
* Returns whether or not the given tile is walkable.
*
* @param tile The tile to check.
* @return bool_t True if walkable, false if not.
*/
bool_t tileIsWalkable(const tile_t tile);
/**
* Returns whether or not the given tile is a ramp tile.
*
* @param tile The tile to check.
* @return bool_t True if ramp, false if not.
*/
bool_t tileIsRamp(const tile_t tile);
+97
View File
@@ -0,0 +1,97 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "worldpos.h"
#include "assert/assert.h"
bool_t worldPosIsEqual(const worldpos_t a, const worldpos_t b) {
return a.x == b.x && a.y == b.y && a.z == b.z;
}
void chunkPosToWorldPos(const chunkpos_t* chunkPos, worldpos_t* out) {
assertNotNull(chunkPos, "Chunk position pointer cannot be NULL");
assertNotNull(out, "Output world position pointer cannot be NULL");
out->x = (worldunit_t)(chunkPos->x * CHUNK_WIDTH);
out->y = (worldunit_t)(chunkPos->y * CHUNK_HEIGHT);
out->z = (worldunit_t)(chunkPos->z * CHUNK_DEPTH);
}
void worldPosToChunkPos(const worldpos_t* worldPos, chunkpos_t* out) {
assertNotNull(worldPos, "World position pointer cannot be NULL");
assertNotNull(out, "Output chunk position pointer cannot be NULL");
if(worldPos->x < 0) {
out->x = (chunkunit_t)((worldPos->x - (CHUNK_WIDTH - 1)) / CHUNK_WIDTH);
} else {
out->x = (chunkunit_t)(worldPos->x / CHUNK_WIDTH);
}
if(worldPos->y < 0) {
out->y = (chunkunit_t)((worldPos->y - (CHUNK_HEIGHT - 1)) / CHUNK_HEIGHT);
} else {
out->y = (chunkunit_t)(worldPos->y / CHUNK_HEIGHT);
}
if(worldPos->z < 0) {
out->z = (chunkunit_t)((worldPos->z - (CHUNK_DEPTH - 1)) / CHUNK_DEPTH);
} else {
out->z = (chunkunit_t)(worldPos->z / CHUNK_DEPTH);
}
}
chunktileindex_t worldPosToChunkTileIndex(const worldpos_t* worldPos) {
assertNotNull(worldPos, "World position pointer cannot be NULL");
uint8_t localX, localY, localZ;
if(worldPos->x < 0) {
localX = (uint8_t)(
(CHUNK_WIDTH - 1) - ((-worldPos->x - 1) % CHUNK_WIDTH)
);
} else {
localX = (uint8_t)(worldPos->x % CHUNK_WIDTH);
}
if(worldPos->y < 0) {
localY = (uint8_t)(
(CHUNK_HEIGHT - 1) - ((-worldPos->y - 1) % CHUNK_HEIGHT)
);
} else {
localY = (uint8_t)(worldPos->y % CHUNK_HEIGHT);
}
if(worldPos->z < 0) {
localZ = (uint8_t)(
(CHUNK_DEPTH - 1) - ((-worldPos->z - 1) % CHUNK_DEPTH)
);
} else {
localZ = (uint8_t)(worldPos->z % CHUNK_DEPTH);
}
chunktileindex_t chunkTileIndex = (chunktileindex_t)(
(localZ * CHUNK_WIDTH * CHUNK_HEIGHT) +
(localY * CHUNK_WIDTH) +
localX
);
assertTrue(
chunkTileIndex < CHUNK_TILE_COUNT,
"Calculated chunk tile index is out of bounds"
);
return chunkTileIndex;
}
chunkindex_t chunkPosToIndex(const chunkpos_t* pos) {
assertNotNull(pos, "Chunk position pointer cannot be NULL");
chunkindex_t chunkIndex = (chunkindex_t)(
(pos->z * MAP_CHUNK_WIDTH * MAP_CHUNK_HEIGHT) +
(pos->y * MAP_CHUNK_WIDTH) +
pos->x
);
return chunkIndex;
}
+80
View File
@@ -0,0 +1,80 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#define CHUNK_WIDTH 16
#define CHUNK_HEIGHT CHUNK_WIDTH
#define CHUNK_DEPTH 8
#define CHUNK_TILE_COUNT (CHUNK_WIDTH * CHUNK_HEIGHT * CHUNK_DEPTH)
#define MAP_CHUNK_WIDTH 3
#define MAP_CHUNK_HEIGHT 3
#define MAP_CHUNK_DEPTH 3
#define MAP_CHUNK_COUNT (MAP_CHUNK_WIDTH * MAP_CHUNK_HEIGHT * MAP_CHUNK_DEPTH)
#define ENTITY_COUNT 64
typedef int16_t worldunit_t;
typedef int16_t chunkunit_t;
typedef int16_t chunkindex_t;
typedef uint32_t chunktileindex_t;
typedef int32_t worldunits_t;
typedef int32_t chunkunits_t;
typedef struct worldpos_s {
worldunit_t x, y, z;
} worldpos_t;
typedef struct chunkpos_t {
chunkunit_t x, y, z;
} chunkpos_t;
/**
* Compares two world positions for equality.
*
* @param a The first world position.
* @param b The second world position.
* @return true if equal, false otherwise.
*/
bool_t worldPosIsEqual(const worldpos_t a, const worldpos_t b);
/**
* Converts a world position to a chunk position.
*
* @param worldPos The world position.
* @param out The output chunk position.
*/
void chunkPosToWorldPos(const chunkpos_t* chunkPos, worldpos_t* out);
/**
* Converts a chunk position to a world position.
*
* @param worldPos The world position.
* @param out The output chunk position.
*/
void worldPosToChunkPos(const worldpos_t* worldPos, chunkpos_t* out);
/**
* Converts a position in world-space to an index inside a chunk that the tile
* resides in.
*
* @param worldPos The world position.
* @return The tile index within the chunk.
*/
chunktileindex_t worldPosToChunkTileIndex(const worldpos_t* worldPos);
/**
* Converts a chunk position to a world position.
*
* @param worldPos The world position.
* @param out The output chunk position.
*/
chunkindex_t chunkPosToIndex(const chunkpos_t* pos);
+66
View File
@@ -0,0 +1,66 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg.h"
#include "entity/entity.h"
#include "rpg/overworld/map.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "time/time.h"
#include "rpgcamera.h"
#include "rpgtextbox.h"
#include "util/memory.h"
#include "assert/assert.h"
errorret_t rpgInit(void) {
memoryZero(ENTITIES, sizeof(ENTITIES));
// Init cutscene subsystem
cutsceneSystemInit();
errorChain(mapInit());
rpgCameraInit();
rpgTextboxInit();
// TEST: Create some entities.
uint8_t entIndex = entityGetAvailable();
assertTrue(entIndex != 0xFF, "No available entity slots!.");
entity_t *ent = &ENTITIES[entIndex];
entityInit(ent, ENTITY_TYPE_PLAYER);
// RPG_CAMERA.mode = RPG_CAMERA_MODE_FOLLOW_ENTITY;
// RPG_CAMERA.followEntity.followEntityId = ent->id;
ent->position.x = 2, ent->position.y = 2;
// All Good!
errorOk();
}
errorret_t rpgUpdate(void) {
#if TIME_FIXED == 0
if(TIME.dynamicUpdate) {
errorOk();
}
#endif
// TODO: Do not update if the scene is not the map scene?
mapUpdate();
// Update overworld ents.
entity_t *ent = &ENTITIES[0];
do {
if(ent->type == ENTITY_TYPE_NULL) continue;
entityUpdate(ent);
} while(++ent < &ENTITIES[ENTITY_COUNT]);
cutsceneSystemUpdate();
errorChain(rpgCameraUpdate());
errorOk();
}
void rpgDispose(void) {
mapDispose();
}
+32
View File
@@ -0,0 +1,32 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
typedef struct {
int32_t nothing;
} rpg_t;
/**
* Initialize the RPG subsystem.
*
* @return An error code and state.
*/
errorret_t rpgInit(void);
/**
* Update the RPG subsystem.
*
* @return An error code.
*/
errorret_t rpgUpdate(void);
/**
* Dispose of the RPG subsystem.
*/
void rpgDispose(void);
+59
View File
@@ -0,0 +1,59 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpgcamera.h"
#include "util/memory.h"
#include "rpg/entity/entity.h"
#include "rpg/overworld/map.h"
#include "assert/assert.h"
rpgcamera_t RPG_CAMERA;
void rpgCameraInit(void) {
memoryZero(&RPG_CAMERA, sizeof(rpgcamera_t));
}
errorret_t rpgCameraUpdate(void) {
glm_lookat(
(vec3){ 3, 3, 3 },
(vec3){ 0, 0, 0 }, // center
(vec3){ 0, 1, 0 }, // up
RPG_CAMERA.eye
);
if(!mapIsLoaded()) errorOk();
chunkpos_t chunkPos;
switch(RPG_CAMERA.mode) {
case RPG_CAMERA_MODE_FREE:
worldPosToChunkPos(&RPG_CAMERA.free, &chunkPos);
break;
case RPG_CAMERA_MODE_FOLLOW_ENTITY: {
entity_t *entity = &ENTITIES[RPG_CAMERA.followEntity.followEntityId];
if(entity->type == ENTITY_TYPE_NULL) {
errorOk();
}
// Update map position to match camera. By default map wants to know the
// top left but we want to set the center, so we need to sub half map size
worldPosToChunkPos(&entity->position, &chunkPos);
break;
}
default:
assertUnreachable("Invalid RPG camera mode");
}
errorChain(mapPositionSet((chunkpos_t){
.x = chunkPos.x - (MAP_CHUNK_WIDTH / 2),
.y = chunkPos.y - (MAP_CHUNK_HEIGHT / 2),
.z = chunkPos.z - (MAP_CHUNK_DEPTH / 2)
}));
errorOk();
}
+42
View File
@@ -0,0 +1,42 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/overworld/worldpos.h"
#include "error/error.h"
typedef enum {
RPG_CAMERA_MODE_FREE,
RPG_CAMERA_MODE_FOLLOW_ENTITY,
} rpgcameramode_t;
typedef struct {
rpgcameramode_t mode;
union {
worldpos_t free;
struct {
uint8_t followEntityId;
} followEntity;
};
mat4 eye;
} rpgcamera_t;
extern rpgcamera_t RPG_CAMERA;
/**
* Initializes the RPG camera.
*/
void rpgCameraInit(void);
/**
* Updates the RPG camera.
*
* @return An error code.
*/
errorret_t rpgCameraUpdate(void);
+39
View File
@@ -0,0 +1,39 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpgtextbox.h"
#include "util/memory.h"
#include "util/string.h"
#include "assert/assert.h"
rpgtextbox_t RPG_TEXTBOX;
void rpgTextboxInit() {
memoryZero(&RPG_TEXTBOX, sizeof(rpgtextbox_t));
}
void rpgTextboxShow(
const rpgtextboxpos_t position,
const char_t *text
) {
RPG_TEXTBOX.position = position;
RPG_TEXTBOX.visible = true;
stringCopy(
RPG_TEXTBOX.text,
text,
RPG_TEXTBOX_MAX_CHARS
);
}
void rpgTextboxHide() {
RPG_TEXTBOX.visible = false;
}
bool_t rpgTextboxIsVisible() {
return RPG_TEXTBOX.visible;
}
+52
View File
@@ -0,0 +1,52 @@
/**
* Copyright (c) 2025 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#define RPG_TEXTBOX_MAX_CHARS 256
typedef enum {
RPG_TEXTBOX_POS_TOP,
RPG_TEXTBOX_POS_BOTTOM,
} rpgtextboxpos_t;
typedef struct {
rpgtextboxpos_t position;
bool_t visible;
char_t text[RPG_TEXTBOX_MAX_CHARS];
} rpgtextbox_t;
extern rpgtextbox_t RPG_TEXTBOX;
/**
* Initializes the RPG textbox.
*/
void rpgTextboxInit();
/**
* Shows the RPG textbox at a specified position.
*
* @param position The position to show the textbox at.
* @param text The text to display in the textbox (copied).
*/
void rpgTextboxShow(
const rpgtextboxpos_t position,
const char_t *text
);
/**
* Hides the RPG textbox.
*/
void rpgTextboxHide();
/**
* Checks if the RPG textbox is currently visible.
*
* @return true if the textbox is visible, false otherwise.
*/
bool_t rpgTextboxIsVisible();
@@ -14,6 +14,6 @@ dusk_run_python(
dusk_story_defs
tools.story.csv
--csv ${CMAKE_CURRENT_SOURCE_DIR}/storyflag.csv
--output ${DUSK_GENERATED_HEADERS_DIR}/story/storyflagvalue.h
--output ${DUSK_GENERATED_HEADERS_DIR}/rpg/story/storyflagvalue.h
)
add_dependencies(${DUSK_LIBRARY_TARGET_NAME} dusk_story_defs)

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