From 0993960920d887e8079bec4a502a52fb361d9e69 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Fri, 20 Mar 2026 21:26:59 -0400 Subject: [PATCH 01/25] add angelscript --- .gitmodules | 3 +++ CMakeLists.txt | 6 +++++- src/main.cpp | 3 +++ src/util/angle_script/as_logging.hpp | 3 +++ src/util/angle_script/as_tests.cpp | 19 +++++++++++++++++++ src/util/angle_script/as_tests.hpp | 10 ++++++++++ vendor/angelscript | 1 + 7 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/util/angle_script/as_logging.hpp create mode 100644 src/util/angle_script/as_tests.cpp create mode 100644 src/util/angle_script/as_tests.hpp create mode 160000 vendor/angelscript diff --git a/.gitmodules b/.gitmodules index 4e14bb77..39929d1f 100644 --- a/.gitmodules +++ b/.gitmodules @@ -19,3 +19,6 @@ [submodule "vendor/whereami"] path = vendor/whereami url = https://github.com/gpakosz/whereami.git +[submodule "vendor/angelscript"] + path = vendor/angelscript + url = https://github.com/anjo76/angelscript.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 0fce8114..1f6e655d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,11 +14,12 @@ project(FunGame VERSION 0.1.0) file(GLOB_RECURSE SOURCES1 "src/*.cpp") # this is one json file and whereami +file(GLOB SOURCES3 "vendor/angelscript/sdk/angelscript/source/*.c*") file(GLOB SOURCES4 "vendor/whereami/src/*.c*") file(GLOB SOURCES6 "vendor/imgui/imgui/*.c*") file(GLOB SOURCES7 "vendor/imgui/imgui/backends/imgui_impl_opengl3.cpp") file(GLOB SOURCES8 "vendor/imgui/imgui/backends/imgui_impl_glfw.cpp") -add_executable(FunGame ${SOURCES1} ${SOURCES4} ${SOURCES6} ${SOURCES7} ${SOURCES8}) +add_executable(FunGame ${SOURCES1} ${SOURCES3} ${SOURCES4} ${SOURCES6} ${SOURCES7} ${SOURCES8}) # Set standard version set_property(TARGET FunGame PROPERTY CXX_STANDARD 23) @@ -88,6 +89,8 @@ target_include_directories(FunGame PRIVATE "vendor/thread-pool/include") target_include_directories(FunGame PRIVATE "vendor/glaze/include") target_include_directories(FunGame PRIVATE "vendor/imgui") target_include_directories(FunGame PRIVATE "vendor/imgui/imgui") +target_include_directories(FunGame PRIVATE "vendor/angelscript/sdk/angelscript/include") +target_include_directories(FunGame PRIVATE "vendor/angelscript/sdk/angelscript/source") target_include_directories(FunGame PRIVATE "src") target_include_directories(FunGame PRIVATE "${PROJECT_BINARY_DIR}") @@ -144,4 +147,5 @@ add_test(NAME LuaLogging COMMAND FunGame Test Lua Logging) add_test(NAME LuaLoadTime COMMAND FunGame Test Lua LoadTime) add_test(NAME LuaLoadScript COMMAND FunGame Test Lua LoadScript) add_test(NAME LuaTransferScript COMMAND FunGame Test Lua TransferScript) +add_test(NAME AngelScript COMMAND FunGame Test AngelScript) add_test(NAME EngineTest COMMAND FunGame Test EngineTest) diff --git a/src/main.cpp b/src/main.cpp index c030092c..b8c9cf6c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -12,6 +12,7 @@ #include "util/files.hpp" #include "util/lua/lua_logging.hpp" #include "util/lua/lua_tests.hpp" +#include "util/angle_script/as_tests.hpp" #include "util/mesh.hpp" #include "util/png_image.hpp" #include "util/time.hpp" @@ -469,6 +470,8 @@ tests(const argh::parser& cmdl) { return gui::opengl_tests(); } else if (run_function == "Lua") { return lua_tests(cmdl); + } else if (run_function == "AngelScript") { + return as_test::test(); } else { std::cout << "No known command" << std::endl; return 1; diff --git a/src/util/angle_script/as_logging.hpp b/src/util/angle_script/as_logging.hpp new file mode 100644 index 00000000..45dcbb04 --- /dev/null +++ b/src/util/angle_script/as_logging.hpp @@ -0,0 +1,3 @@ +#pragma once + + diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angle_script/as_tests.cpp new file mode 100644 index 00000000..7f207cff --- /dev/null +++ b/src/util/angle_script/as_tests.cpp @@ -0,0 +1,19 @@ + +#include "logging.hpp" +#include // TODO linker error determine how to build AS +namespace as_test { + +int +test() { + asIScriptEngine *engine = asCreateScriptEngine(); + if (!engine) { + LOG_ERROR(logging::main_logger, "Could no start Angle Script engine."); + return 1; + } + + engine->ShutDownAndRelease(); + return 0; +} + +} + diff --git a/src/util/angle_script/as_tests.hpp b/src/util/angle_script/as_tests.hpp new file mode 100644 index 00000000..217a9439 --- /dev/null +++ b/src/util/angle_script/as_tests.hpp @@ -0,0 +1,10 @@ + +#pragma once + +namespace as_test { + +int +test(); + +} + diff --git a/vendor/angelscript b/vendor/angelscript new file mode 160000 index 00000000..629ed800 --- /dev/null +++ b/vendor/angelscript @@ -0,0 +1 @@ +Subproject commit 629ed8008f68d12c2b8205e4c6f1c18a4e850fbe From a3a131d4982250e1eec6139905f1cdae1cb69cc6 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Fri, 20 Mar 2026 23:17:17 -0400 Subject: [PATCH 02/25] slightly cleanup cmake file --- CMakeLists.txt | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1f6e655d..6926aaaf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,16 +10,26 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) # set the project name project(FunGame VERSION 0.1.0) +# AngelScript +file(GLOB ANGELSCRIPT_SOURCE "vendor/angelscript/sdk/angelscript/source/*.c*") +add_library(angelscript OBJECT ${ANGELSCRIPT_SOURCE}) +target_include_directories(angelscript PRIVATE "vendor/angelscript/sdk/angelscript/include") + +# where am I +file(GLOB WHEREAMI_SOURCE "vendor/whereami/src/**") +add_library(whereami OBJECT ${WHEREAMI_SOURCE}) +target_include_directories(whereami PRIVATE "vendor/whereami/src") + +# ImGUI +file(GLOB IMGUI_SOURCES1 "vendor/imgui/imgui/*.c*") +file(GLOB IMGUI_SOURCES2 "vendor/imgui/imgui/backends/imgui_impl_opengl3.cpp") +file(GLOB IMGUI_SOURCES3 "vendor/imgui/imgui/backends/imgui_impl_glfw.cpp") +add_library(dear_imgui OBJECT ${IMGUI_SOURCES1} ${IMGUI_SOURCES2} ${IMGUI_SOURCES3}) +target_include_directories(dear_imgui PRIVATE "vendor/imgui/imgui") + # add the executable file(GLOB_RECURSE SOURCES1 "src/*.cpp") - -# this is one json file and whereami -file(GLOB SOURCES3 "vendor/angelscript/sdk/angelscript/source/*.c*") -file(GLOB SOURCES4 "vendor/whereami/src/*.c*") -file(GLOB SOURCES6 "vendor/imgui/imgui/*.c*") -file(GLOB SOURCES7 "vendor/imgui/imgui/backends/imgui_impl_opengl3.cpp") -file(GLOB SOURCES8 "vendor/imgui/imgui/backends/imgui_impl_glfw.cpp") -add_executable(FunGame ${SOURCES1} ${SOURCES3} ${SOURCES4} ${SOURCES6} ${SOURCES7} ${SOURCES8}) +add_executable(FunGame ${SOURCES1}) # Set standard version set_property(TARGET FunGame PROPERTY CXX_STANDARD 23) @@ -77,11 +87,15 @@ find_package(Lua REQUIRED) include_directories(${LUA_INCLUDE_DIR}) # add quill and sol2 -target_link_libraries_system(FunGame PRIVATE quill::quill) +target_link_libraries(FunGame PRIVATE quill::quill) target_link_libraries_system(FunGame PRIVATE sol2::sol2) target_link_libraries(FunGame PRIVATE ${LUA_LIBRARIES}) +target_link_libraries(FunGame PRIVATE whereami) +target_link_libraries(FunGame PRIVATE dear_imgui) +target_link_libraries(FunGame PRIVATE angelscript) + # Add include dirs target_include_directories(FunGame PRIVATE "vendor/whereami/src") target_include_directories(FunGame PRIVATE "vendor/argh") @@ -90,7 +104,6 @@ target_include_directories(FunGame PRIVATE "vendor/glaze/include") target_include_directories(FunGame PRIVATE "vendor/imgui") target_include_directories(FunGame PRIVATE "vendor/imgui/imgui") target_include_directories(FunGame PRIVATE "vendor/angelscript/sdk/angelscript/include") -target_include_directories(FunGame PRIVATE "vendor/angelscript/sdk/angelscript/source") target_include_directories(FunGame PRIVATE "src") target_include_directories(FunGame PRIVATE "${PROJECT_BINARY_DIR}") From b2b9af6e79693249d5013b018cee8cd9f9acc5cf Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Sat, 4 Apr 2026 00:06:32 -0400 Subject: [PATCH 03/25] add tests --- README.md | 3 +- resources/as/test.as | 12 +++++ src/global_context.hpp | 10 ++++ src/local_context.hpp | 7 +++ src/util/angle_script/as_logging.cpp | 72 ++++++++++++++++++++++++++++ src/util/angle_script/as_logging.hpp | 23 +++++++++ src/util/angle_script/as_tests.cpp | 49 ++++++++++++++++++- 7 files changed, 173 insertions(+), 3 deletions(-) create mode 100644 resources/as/test.as create mode 100644 src/util/angle_script/as_logging.cpp diff --git a/README.md b/README.md index 28ac4335..d29f6265 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,7 @@ pacman -Su \ mingw-w64-x86_64-ninja \ mingw-w64-x86_64-glew \ mingw-w64-x86_64-glfw \ - mingw-w64-x86_64-glm \ - mingw-w64-x86_64-lua # not 100% sure this is the right lua version + mingw-w64-x86_64-glm ``` ## Building diff --git a/resources/as/test.as b/resources/as/test.as new file mode 100644 index 00000000..568787bd --- /dev/null +++ b/resources/as/test.as @@ -0,0 +1,12 @@ +void test1() { + int x = 5; + return; +} + +int test2() { + int x = 1 * 2 * 3 * 4 * 5 * 6; + if (x % 2 == 0) { + return 2; + } + return 1; +} \ No newline at end of file diff --git a/src/global_context.hpp b/src/global_context.hpp index fdd9ba29..9a2aadbb 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -28,6 +28,7 @@ #define BS_THREAD_POOL_ENABLE_PRIORITY #include #include +#include #include #include @@ -43,6 +44,7 @@ * @details In particular this will contain the thread pool. */ + class GlobalContext { private: BS::thread_pool thread_pool_; @@ -57,6 +59,10 @@ class GlobalContext { std::mutex global_lua_mutex_; + asIScriptEngine* engine_; + + std::mutex global_as_mutex_; + #if DEBUG() std::thread::id main_thread_id; @@ -158,4 +164,8 @@ class GlobalContext { void load_script_file(const std::filesystem::path& path); std::optional get_from_lua(const std::string& command); + + auto as_engine() { + return engine_; + } }; diff --git a/src/local_context.hpp b/src/local_context.hpp index 292bb3ce..6d55e123 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -26,12 +26,17 @@ #pragma once #include +#include + +class asContextWrapper; class LocalContext { private: LocalContext(); sol::state lua_state; + asIScriptFunction* context_; + sol::object copy(sol::state& lua, const sol::object& object); public: @@ -49,4 +54,6 @@ class LocalContext { bool load_into_this_lua_state(const std::string& command); std::optional get_from_lua(const std::string& command); + + auto run_function(asIScriptFunction* function); }; diff --git a/src/util/angle_script/as_logging.cpp b/src/util/angle_script/as_logging.cpp new file mode 100644 index 00000000..722fa81c --- /dev/null +++ b/src/util/angle_script/as_logging.cpp @@ -0,0 +1,72 @@ +#include "logging.hpp" +#include "local_context.hpp" +#include +#include + +namespace as_logging { + +inline void +as_log_backtrace(std::string message) { + // get engine from local context + //auto& localcontext = LocalContext::instance(); + //auto engine = localcontext.as_engine(); + + std::string file(""); + int line = 5; + LOG_BACKTRACE( + logging::main_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", file, line), message + ); +} + +inline void +as_log_info(std::string message) { + std::string file(""); + int line = 5; + LOG_INFO( + logging::main_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", file, line), message + ); +} + +inline void +as_log_debug(std::string message) { + std::string file(""); + int line = 5; + LOG_DEBUG( + logging::main_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", file, line), message + ); +} + +inline void +as_log_warning(std::string message) { + std::string file(""); + int line = 5; + LOG_WARNING( + logging::main_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", file, line), message + ); +} + +inline void +as_log_error(std::string message) { + std::string file(""); + int line = 5; + LOG_ERROR( + logging::main_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", file, line), message + ); +} + +inline void +as_log_critical(std::string message) { + std::string file(""); + int line = 5; + LOG_CRITICAL( + logging::main_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", file, line), message + ); +} + +} // namespace name diff --git a/src/util/angle_script/as_logging.hpp b/src/util/angle_script/as_logging.hpp index 45dcbb04..0086b923 100644 --- a/src/util/angle_script/as_logging.hpp +++ b/src/util/angle_script/as_logging.hpp @@ -1,3 +1,26 @@ #pragma once +#include + +namespace as_logging { + +inline void +as_log_backtrace(std::string message); + +inline void +as_log_info(std::string message); + +inline void +as_log_debug(std::string message); + +inline void +as_log_warning(std::string message); + +inline void +as_log_error(std::string message); + +inline void +as_log_critical(std::string message); + +} // namespace name diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angle_script/as_tests.cpp index 7f207cff..f7f11d5c 100644 --- a/src/util/angle_script/as_tests.cpp +++ b/src/util/angle_script/as_tests.cpp @@ -1,6 +1,7 @@ #include "logging.hpp" -#include // TODO linker error determine how to build AS +#include +#include "util/files.hpp" namespace as_test { int @@ -11,6 +12,52 @@ test() { return 1; } + asIScriptModule* mod = engine->GetModule("test_module", asGM_CREATE_IF_NOT_EXISTS); + std::ostringstream script; + auto file = files::open_file(files::get_resources_path() / "as" / "test.as"); + if (! file) { + engine->ShutDownAndRelease(); + return 1; + } + + script << file.value().rdbuf(); + mod->AddScriptSection("test.as", script.str().c_str()); + + int result = mod->Build(); + if (result > 0) { + engine->ShutDownAndRelease(); + return 1; + } + + asIScriptFunction* funct1 = engine->GetModule("test_module")->GetFunctionByDecl("void test1()"); + + asIScriptContext* ctx = engine->CreateContext(); + ctx->Prepare(funct1); +// ctx->SetArgDWord(); + result = ctx->Execute(); + if (result != asEXECUTION_FINISHED) { + ctx->Release(); + engine->ShutDownAndRelease(); + return 1; + } + + asIScriptFunction* funct2 = engine->GetModule("test_module")->GetFunctionByDecl("int test2()"); + + ctx->Prepare(funct2); +// ctx->SetArgDWord(); + result = ctx->Execute(); + if (result != asEXECUTION_FINISHED) { + ctx->Release(); + engine->ShutDownAndRelease(); + return 1; + } + int returnvalue = ctx->GetReturnDWord(); + if (returnvalue == 1 || returnvalue == 0){ + ctx->Release(); + engine->ShutDownAndRelease(); + return 1; + } + engine->ShutDownAndRelease(); return 0; } From 6fddc68ba5d2eaf878c3b18850d25ab20a3d25ec Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Sun, 12 Apr 2026 18:10:08 -0400 Subject: [PATCH 04/25] Angelscript tests and loading --- CMakeLists.txt | 6 +- data/Base/biome_map.as | 78 +++++++++++++++ src/exceptions.hpp | 8 +- src/global_context.cpp | 64 ++++++++++++- src/global_context.hpp | 19 +++- src/gui/gui_logging.hpp | 2 +- src/gui/render/gpu_data/frame_buffer.cpp | 24 ++--- .../gpu_data/frame_buffer_multisample.cpp | 23 +++-- src/gui/render/gpu_data/render_buffer.hpp | 3 +- src/gui/render/gpu_data/shadow_map.cpp | 3 +- src/gui/render/gpu_data/texture.cpp | 6 +- .../render/gpu_data/vertex_buffer_object.hpp | 5 +- .../graphics_shaders/program_handler.cpp | 15 ++- .../graphics_shaders/program_handler.hpp | 2 +- .../graphics_shaders/shader_program.cpp | 3 +- .../graphics_shaders/shader_program.hpp | 19 ++-- .../structures/floating_instanced_i_mesh.cpp | 4 +- .../structures/floating_instanced_i_mesh.hpp | 8 +- .../render/structures/instanced_i_mesh.cpp | 4 +- src/gui/render/structures/model.hpp | 2 +- src/gui/render/structures/static_mesh.hpp | 3 +- src/gui/render/structures/terrain_mesh.cpp | 3 +- src/gui/render/structures/terrain_mesh.hpp | 4 +- src/gui/render/structures/uniform_types.hpp | 14 +-- src/gui/scene/scene.hpp | 3 +- src/gui/ui/imgui_gui.cpp | 11 ++- src/gui/ui/imgui_windows.cpp | 3 +- src/gui/ui/scene_setup.cpp | 6 +- src/local_context.cpp | 7 +- src/local_context.hpp | 29 +++++- src/main.cpp | 26 ++++- src/manifest/manifest.hpp | 3 +- src/manifest/object_handler.hpp | 6 +- src/util/angle_script/as_logging.cpp | 38 ++++---- src/util/angle_script/as_logging.hpp | 21 ++-- src/util/angle_script/as_tests.cpp | 42 ++++++-- src/util/angle_script/as_tests.hpp | 6 +- src/util/image.hpp | 13 +-- src/util/mesh.hpp | 7 +- src/util/png_image.hpp | 4 +- src/world/biome.cpp | 19 +++- src/world/object/entity/entity.cpp | 12 +-- src/world/object/entity/entity.hpp | 2 +- .../object/entity/implemented_entity.hpp | 3 +- src/world/object/entity/object.hpp | 4 +- src/world/object/entity/tile_object.cpp | 8 +- src/world/object/entity_controller.cpp | 11 ++- src/world/object/entity_controller.hpp | 6 +- src/world/plant.hpp | 7 +- src/world/terrain/chunk.cpp | 9 +- src/world/terrain/chunk.hpp | 4 +- .../terrain/generation/land_generator.cpp | 14 +-- .../terrain/generation/land_generator.hpp | 6 +- .../terrain/generation/lua_interface.cpp | 96 +++++++++++++++++++ .../terrain/generation/lua_interface.hpp | 3 + src/world/terrain/generation/map_tile.hpp | 4 +- src/world/terrain/generation/mat_tile.cpp | 4 +- src/world/terrain/generation/noise.cpp | 5 +- src/world/terrain/generation/noise.hpp | 20 ++++ .../generation/terrain_genreration_types.hpp | 12 +-- src/world/terrain/generation/terrain_map.hpp | 10 +- src/world/terrain/generation/worley_noise.cpp | 5 +- src/world/terrain/generation/worley_noise.hpp | 11 ++- src/world/terrain/material.cpp | 6 +- src/world/terrain/material.hpp | 12 +-- src/world/terrain/path/node.hpp | 4 +- src/world/terrain/path/node_group.cpp | 4 +- src/world/terrain/path/node_wrappers.hpp | 2 +- src/world/terrain/path/tile_iterator.cpp | 4 +- src/world/terrain/terrain.cpp | 13 +-- src/world/terrain/terrain.hpp | 4 +- src/world/terrain/terrain_helper-impls.cpp | 10 +- src/world/terrain/terrain_helper.cpp | 2 +- src/world/world.cpp | 23 ++--- 74 files changed, 634 insertions(+), 272 deletions(-) create mode 100644 data/Base/biome_map.as diff --git a/CMakeLists.txt b/CMakeLists.txt index 6926aaaf..a81c38f0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,10 @@ project(FunGame VERSION 0.1.0) # AngelScript file(GLOB ANGELSCRIPT_SOURCE "vendor/angelscript/sdk/angelscript/source/*.c*") -add_library(angelscript OBJECT ${ANGELSCRIPT_SOURCE}) +file(GLOB ANGELSCRIPT_SOURCE_STRING "vendor/angelscript/sdk/add_on/scriptstdstring/*.c*") +file(GLOB ANGELSCRIPT_SOURCE_ARRAY "vendor/angelscript/sdk/add_on/scriptarray/*.c*") +add_library(angelscript OBJECT ${ANGELSCRIPT_SOURCE} ${ANGELSCRIPT_SOURCE_STRING} ${ANGELSCRIPT_SOURCE_ARRAY}) +target_compile_definitions(angelscript PRIVATE "AS_USE_STLNAMES") target_include_directories(angelscript PRIVATE "vendor/angelscript/sdk/angelscript/include") # where am I @@ -104,6 +107,7 @@ target_include_directories(FunGame PRIVATE "vendor/glaze/include") target_include_directories(FunGame PRIVATE "vendor/imgui") target_include_directories(FunGame PRIVATE "vendor/imgui/imgui") target_include_directories(FunGame PRIVATE "vendor/angelscript/sdk/angelscript/include") +target_include_directories(FunGame PRIVATE "vendor/angelscript/sdk/add_on/scriptstdstring") target_include_directories(FunGame PRIVATE "src") target_include_directories(FunGame PRIVATE "${PROJECT_BINARY_DIR}") diff --git a/data/Base/biome_map.as b/data/Base/biome_map.as new file mode 100644 index 00000000..029698cc --- /dev/null +++ b/data/Base/biome_map.as @@ -0,0 +1,78 @@ +// Biome map files must define a function that returns a structure with a "map". +// The map function is called from c++ and reads the x and y lengths. Using this +// information the "map" key of the returned structure can be used as if it were +// a 2D array. + +// Anyway, do something like this and it should work as long as there are +// correctly defined tile types and tile macros. + +// Base = Base or {} +// Base.biome_map = Base.biome_map or {} + +// Base.biome_map.spacing = .8 + +namespace Base { + +namespace biomes { + +class biome_map { + + TerrainGeneration::FractalNoise noise; + TerrainGeneration::AlternativeWorleyNoise flower_noise; + float spacing; + + biome_map() { + noise = TerrainGeneration::FractalNoise(4, 0.6, 3); + flower_noise = TerrainGeneration::AlternativeWorleyNoise(32, 0.5, 32); + spacing = 0.8; + } + + int sample(int x, int y) { + // sample noise and set a value + float height = 12.0 * noise.sample(float(x) * spacing, float(y) * spacing) - 4.0; + // each value must be integers. math.floor changes doubles to ints + int height_map_value = int(height) ; + // This biome only defines tile types between 0, and 6 + if (height_map_value > 6) { + height_map_value = 6; + } + else if (height_map_value < 0) { + height_map_value = 0; + } + return height_map_value; + } + + // Maps for trees and bushes + // name should be used in json file + float sample_plants(string plant_id, int x, int y) { + if (plant_id == "Trees_1") { + int height = sample(x, y); + if (height == 1) { + return 0.1; + } + else { + return 0.0; + } + } + else if (plant_id == "Flower_1") { + int flower_height = flower_noise.sample(x * 4, y * 4); + if (flower_height > 0) { + return 0.10; + } + else { + return 0.0; + } + } + else { + return 0.0; + } + } +} + +} + +} + +void do_something() { + Base::biomes::biome_map map = Base::biomes::biome_map(); +} diff --git a/src/exceptions.hpp b/src/exceptions.hpp index 7e9993df..1d1e217e 100644 --- a/src/exceptions.hpp +++ b/src/exceptions.hpp @@ -18,8 +18,8 @@ class file_not_found_error : public std::runtime_error { file_not_found_error(const file_not_found_error& other) noexcept = default; - file_not_found_error& operator=(const file_not_found_error& other - ) noexcept = default; + file_not_found_error& + operator=(const file_not_found_error& other) noexcept = default; [[nodiscard]] virtual inline const std::filesystem::path path() const noexcept { @@ -35,8 +35,8 @@ class not_implemented_error : public std::logic_error { not_implemented_error(const not_implemented_error& other) noexcept = default; - not_implemented_error& operator=(const not_implemented_error& other - ) noexcept = default; + not_implemented_error& + operator=(const not_implemented_error& other) noexcept = default; }; } // namespace exc diff --git a/src/global_context.cpp b/src/global_context.cpp index 5d824e71..2b17808a 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -2,6 +2,30 @@ #include "local_context.hpp" #include "logging.hpp" +#include "scriptstdstring.h" +#include "util/files.hpp" +#include "world/terrain/generation/lua_interface.hpp" + +// Implement a simple message callback function +void +MessageCallback(const asSMessageInfo* msg, void* param) { + if (msg->type == asMSGTYPE_ERROR) { + LOG_ERROR( + logging::lua_script_logger, "{} ({}, {}) : {}", msg->section, msg->row, + msg->col, msg->message + ); + } else if (msg->type == asMSGTYPE_WARNING) { + LOG_WARNING( + logging::lua_script_logger, "{} ({}, {}) : {}", msg->section, msg->row, + msg->col, msg->message + ); + } else if (msg->type == asMSGTYPE_INFORMATION) { + LOG_WARNING( + logging::lua_script_logger, "{} ({}, {}) : {}", msg->section, msg->row, + msg->col, msg->message + ); + } +} void GlobalContext::run_opengl_queue() { @@ -26,7 +50,16 @@ GlobalContext::run_opengl_queue() { } GlobalContext::GlobalContext() : - thread_pool_([] { quill::detail::set_thread_name("BS Thread"); }) {} + thread_pool_([] { quill::detail::set_thread_name("BS Thread"); }), + engine_(asCreateScriptEngine()) { + engine_->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); + RegisterStdString(engine_); + terrain::generation::init_as_interface(engine_); +} + +GlobalContext::~GlobalContext() { + engine_->ShutDownAndRelease(); +} std::optional GlobalContext::get_from_lua(const std::string& command) { @@ -103,3 +136,32 @@ GlobalContext::load_script_file(const std::filesystem::path& path) { LOG_ERROR(logging::lua_logger, "{}", what); } } + +// TODO this needs to return a status +void +GlobalContext::load_file(std::string module, std::filesystem::path path) { + asIScriptModule* mod = + engine_->GetModule(module.c_str(), asGM_CREATE_IF_NOT_EXISTS); + + std::ostringstream script; + auto file = files::open_file(path); + if (!file) { + return; + } + + script << file.value().rdbuf(); + mod->AddScriptSection(path.filename().c_str(), script.str().c_str()); + + int result = mod->Build(); + if (result > 0) { + LOG_ERROR(logging::lua_logger, "{}", result); + return; + } +} + +asIScriptFunction* +GlobalContext::get_function(std::string module, std::string function_signature) const { + asIScriptFunction* function = engine_->GetModule(module.c_str()) + ->GetFunctionByDecl(function_signature.c_str()); + return function; +} diff --git a/src/global_context.hpp b/src/global_context.hpp index 9a2aadbb..718c1cbf 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -26,9 +26,9 @@ #include "logging.hpp" #define BS_THREAD_POOL_ENABLE_PRIORITY +#include #include #include -#include #include #include @@ -44,7 +44,6 @@ * @details In particular this will contain the thread pool. */ - class GlobalContext { private: BS::thread_pool thread_pool_; @@ -80,6 +79,8 @@ class GlobalContext { void operator=(GlobalContext&&) = delete; void operator=(GlobalContext const&) = delete; + ~GlobalContext(); + inline void set_main_thread() { #if DEBUG() @@ -108,8 +109,9 @@ class GlobalContext { } // this must be run before exit if lua has been initialized on thread local - // - inline void close_threads() { + // + inline void + close_threads() { thread_pool_.reset(0); } @@ -165,7 +167,14 @@ class GlobalContext { std::optional get_from_lua(const std::string& command); - auto as_engine() { + auto + as_engine() { return engine_; } + + // load as script file + void load_file(std::string module, std::filesystem::path path); + + // get function from module + asIScriptFunction* get_function(std::string module, std::string function) const; }; diff --git a/src/gui/gui_logging.hpp b/src/gui/gui_logging.hpp index 265fe5d9..b2416bf1 100644 --- a/src/gui/gui_logging.hpp +++ b/src/gui/gui_logging.hpp @@ -28,9 +28,9 @@ #include #include +#include #include #include -#include namespace gui { diff --git a/src/gui/render/gpu_data/frame_buffer.cpp b/src/gui/render/gpu_data/frame_buffer.cpp index 0c8b2d39..0c80292d 100644 --- a/src/gui/render/gpu_data/frame_buffer.cpp +++ b/src/gui/render/gpu_data/frame_buffer.cpp @@ -11,9 +11,7 @@ namespace gpu_data { FrameBufferBase::FrameBufferBase( screen_size_t width, screen_size_t height, FrameBufferSettings settings -) : - width_(width), - height_(height), settings_(settings) { +) : width_(width), height_(height), settings_(settings) { // frame buffer (the container for the other two) // ----------------- glGenFramebuffers(1, &frame_buffer); @@ -22,15 +20,17 @@ FrameBufferBase::FrameBufferBase( FrameBuffer::FrameBuffer( screen_size_t width, screen_size_t height, FrameBufferSettings settings -) : - FrameBufferBase(width, height, settings) { - connect_depth_texture(std::make_shared( - width_, height_, - TextureSettings{ - .internal_format = GPUPixelStorageFormat::DEPTH, - .read_format = GPUPixelReadFormat::DEPTH_COMPONENT}, - false - )); +) : FrameBufferBase(width, height, settings) { + connect_depth_texture( + std::make_shared( + width_, height_, + TextureSettings{ + .internal_format = GPUPixelStorageFormat::DEPTH, + .read_format = GPUPixelReadFormat::DEPTH_COMPONENT + }, + false + ) + ); connect_render_texture( std::make_shared( width_, height_, diff --git a/src/gui/render/gpu_data/frame_buffer_multisample.cpp b/src/gui/render/gpu_data/frame_buffer_multisample.cpp index 52fcea94..3aeabfe4 100644 --- a/src/gui/render/gpu_data/frame_buffer_multisample.cpp +++ b/src/gui/render/gpu_data/frame_buffer_multisample.cpp @@ -11,22 +11,25 @@ namespace gpu_data { FrameBufferMultisample::FrameBufferMultisample( screen_size_t width, screen_size_t height, FrameBufferSettings settings -) : - FrameBufferBase(width, height, settings) { - connect_depth_texture(std::make_shared( - width_, height_, - RenderBufferSettings{ - .samples = settings_.samples, - .multisample = settings_.samples > 1, - .internal_format = GPUPixelStorageFormat::DEPTH} - )); +) : FrameBufferBase(width, height, settings) { + connect_depth_texture( + std::make_shared( + width_, height_, + RenderBufferSettings{ + .samples = settings_.samples, + .multisample = settings_.samples > 1, + .internal_format = GPUPixelStorageFormat::DEPTH + } + ) + ); connect_render_texture( std::make_shared( width_, height_, TextureSettings{ .samples = settings.samples, .multisample = (settings_.samples > 1), - .internal_format = GPUPixelStorageFormat::RGB8}, + .internal_format = GPUPixelStorageFormat::RGB8 + }, false ), 0 diff --git a/src/gui/render/gpu_data/render_buffer.hpp b/src/gui/render/gpu_data/render_buffer.hpp index e74f5c99..5519c155 100644 --- a/src/gui/render/gpu_data/render_buffer.hpp +++ b/src/gui/render/gpu_data/render_buffer.hpp @@ -28,8 +28,7 @@ class RenderBuffer : virtual public GPUDataRenderBuffer { inline RenderBuffer( screen_size_t width, screen_size_t height, RenderBufferSettings settings - ) : - RenderBuffer(settings) { + ) : RenderBuffer(settings) { bind(); if (settings_.multisample) { glRenderbufferStorageMultisample( diff --git a/src/gui/render/gpu_data/shadow_map.cpp b/src/gui/render/gpu_data/shadow_map.cpp index a46dca73..c79349b2 100644 --- a/src/gui/render/gpu_data/shadow_map.cpp +++ b/src/gui/render/gpu_data/shadow_map.cpp @@ -23,7 +23,8 @@ ShadowMap::ShadowMap(screen_size_t w, screen_size_t h, FrameBufferSettings setti .internal_format = GPUPixelStorageFormat::DEPTH_16, .read_format = GPUPixelReadFormat::DEPTH_COMPONENT, .type = GPUPixelType::HALF_FLOAT, - .min_filter = GL_LINEAR}; + .min_filter = GL_LINEAR + }; connect_depth_texture( std::make_shared(width_, height_, depth_texture_settings, false) diff --git a/src/gui/render/gpu_data/texture.cpp b/src/gui/render/gpu_data/texture.cpp index 21822536..c2323d9f 100644 --- a/src/gui/render/gpu_data/texture.cpp +++ b/src/gui/render/gpu_data/texture.cpp @@ -119,8 +119,7 @@ Texture2D::setup(std::shared_ptr image) { Texture2D::Texture2D( screen_size_t width, screen_size_t height, TextureSettings settings, bool differed -) : - width_(width), height_(height), settings_(settings) { +) : width_(width), height_(height), settings_(settings) { if (differed) { GlobalContext& context = GlobalContext::instance(); context.push_opengl_task([this]() { setup(nullptr); }); @@ -131,8 +130,7 @@ Texture2D::Texture2D( Texture2D::Texture2D( std::shared_ptr image, TextureSettings settings, bool differed -) : - settings_(settings) { +) : settings_(settings) { if (!image) { return; } diff --git a/src/gui/render/gpu_data/vertex_buffer_object.hpp b/src/gui/render/gpu_data/vertex_buffer_object.hpp index d401b38f..e30f3bb6 100644 --- a/src/gui/render/gpu_data/vertex_buffer_object.hpp +++ b/src/gui/render/gpu_data/vertex_buffer_object.hpp @@ -69,9 +69,8 @@ struct GPUStructureType { uint8_t major_size_, uint8_t minor_size_, uint8_t type_size, bool is_int, GPUArayType draw_type ) : - major_size(major_size_), - minor_size(minor_size_), type_size(type_size), is_int(is_int), - draw_type(draw_type) {} + major_size(major_size_), minor_size(minor_size_), type_size(type_size), + is_int(is_int), draw_type(draw_type) {} template < uint8_t major_size_T, uint8_t minor_size_T, uint8_t type_size_T, bool is_int_T, diff --git a/src/gui/render/graphics_shaders/program_handler.cpp b/src/gui/render/graphics_shaders/program_handler.cpp index dcd4235b..e8fc137d 100644 --- a/src/gui/render/graphics_shaders/program_handler.cpp +++ b/src/gui/render/graphics_shaders/program_handler.cpp @@ -170,23 +170,28 @@ Program::get_status_string() const { "OK", "This program and its corresponding shaders have compiled successfully. If " "there is still some error check that Uniforms and Locations are set " - "correctly."}; + "correctly." + }; static std::pair linking_failed_string = { "Linking Failed", "There is an error when connecting different shader types together. Check that " - "the inputs and output between shaders align."}; + "the inputs and output between shaders align." + }; static std::pair invalid_shader_string = { "Shader Failed", "Error compiling constituent shader(s). Check the log file " - "for more information."}; + "for more information." + }; static std::pair empty_program_string = { - "No Program; Reload", "Program has not been loaded. Click the reload button."}; + "No Program; Reload", "Program has not been loaded. Click the reload button." + }; static std::pair other_string = { "This should not happen", - "This is a bug that should be reported to the developers."}; + "This is a bug that should be reported to the developers." + }; switch (status_) { case ProgramStatus::OK: diff --git a/src/gui/render/graphics_shaders/program_handler.hpp b/src/gui/render/graphics_shaders/program_handler.hpp index 5d379676..efb5bb6e 100644 --- a/src/gui/render/graphics_shaders/program_handler.hpp +++ b/src/gui/render/graphics_shaders/program_handler.hpp @@ -498,7 +498,7 @@ class ShaderHandler { /** * @brief construct a new ShaderHandler */ - inline ShaderHandler(){}; + inline ShaderHandler() {}; inline ~ShaderHandler() {} }; diff --git a/src/gui/render/graphics_shaders/shader_program.cpp b/src/gui/render/graphics_shaders/shader_program.cpp index 7ab7778b..41974494 100644 --- a/src/gui/render/graphics_shaders/shader_program.cpp +++ b/src/gui/render/graphics_shaders/shader_program.cpp @@ -259,7 +259,8 @@ ShaderProgram_MultiElements::render( GL_TRIANGLES, // mode mesh->get_num_vertices().data(), // count static_cast(element_type), // type - reinterpret_cast(mesh->get_elements_position().data() + reinterpret_cast( + mesh->get_elements_position().data() ), // indices mesh->get_num_objects(), // drawcount mesh->get_base_vertex().data() diff --git a/src/gui/render/graphics_shaders/shader_program.hpp b/src/gui/render/graphics_shaders/shader_program.hpp index ef5f8cde..cb7ae074 100644 --- a/src/gui/render/graphics_shaders/shader_program.hpp +++ b/src/gui/render/graphics_shaders/shader_program.hpp @@ -113,9 +113,7 @@ class Render_Base { public: inline Render_Base( shader::Program& shader_program, const std::function setup_commands - ) : - opengl_program_(shader_program), - setup_(setup_commands) { + ) : opengl_program_(shader_program), setup_(setup_commands) { LOG_DEBUG( logging::opengl_logger, "Program ID: {}, Name: {}", opengl_program_.get_program_ID(), opengl_program_.get_name() @@ -143,8 +141,7 @@ class ShaderProgram_Standard : inline ShaderProgram_Standard( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_Standard() {} @@ -165,8 +162,7 @@ class ShaderProgram_Elements : inline ShaderProgram_Elements( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_Elements() {} @@ -187,8 +183,7 @@ class ShaderProgram_Instanced : inline ShaderProgram_Instanced( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_Instanced() {} @@ -209,8 +204,7 @@ class ShaderProgram_ElementsInstanced : inline ShaderProgram_ElementsInstanced( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_ElementsInstanced() {} @@ -231,8 +225,7 @@ class ShaderProgram_MultiElements : inline ShaderProgram_MultiElements( shader::Program& shader_program, const std::function setup_commands - ) : - Render_Base(shader_program, setup_commands) {} + ) : Render_Base(shader_program, setup_commands) {} inline virtual ~ShaderProgram_MultiElements() {} diff --git a/src/gui/render/structures/floating_instanced_i_mesh.cpp b/src/gui/render/structures/floating_instanced_i_mesh.cpp index 168364e0..e5a4719d 100644 --- a/src/gui/render/structures/floating_instanced_i_mesh.cpp +++ b/src/gui/render/structures/floating_instanced_i_mesh.cpp @@ -15,9 +15,7 @@ namespace gpu_data { FloatingInstancedIMeshGPU::FloatingInstancedIMeshGPU( const util::Mesh& mesh, const std::vector& model_transforms -) : - IMeshGPU(mesh, false), - transforms_array_(model_transforms, 1) { +) : IMeshGPU(mesh, false), transforms_array_(model_transforms, 1) { // InstancedInt does not have a color texture. One must inherit from this // class and define a method that creates a color texture, and sets its id // as color_texture_. diff --git a/src/gui/render/structures/floating_instanced_i_mesh.hpp b/src/gui/render/structures/floating_instanced_i_mesh.hpp index 09a6f3a4..e6c87b0e 100644 --- a/src/gui/render/structures/floating_instanced_i_mesh.hpp +++ b/src/gui/render/structures/floating_instanced_i_mesh.hpp @@ -54,10 +54,10 @@ class FloatingInstancedIMeshGPU : inline FloatingInstancedIMeshGPU(const FloatingInstancedIMeshGPU& obj) = delete; inline FloatingInstancedIMeshGPU(FloatingInstancedIMeshGPU&& other) = default; // copy operator - inline FloatingInstancedIMeshGPU& operator=(const FloatingInstancedIMeshGPU& obj - ) = delete; - inline FloatingInstancedIMeshGPU& operator=(FloatingInstancedIMeshGPU&& other - ) = default; + inline FloatingInstancedIMeshGPU& + operator=(const FloatingInstancedIMeshGPU& obj) = delete; + inline FloatingInstancedIMeshGPU& + operator=(FloatingInstancedIMeshGPU&& other) = default; inline FloatingInstancedIMeshGPU(const util::Mesh& mesh) : FloatingInstancedIMeshGPU(mesh, {}) {} diff --git a/src/gui/render/structures/instanced_i_mesh.cpp b/src/gui/render/structures/instanced_i_mesh.cpp index 2bd435ce..52bdc1a0 100644 --- a/src/gui/render/structures/instanced_i_mesh.cpp +++ b/src/gui/render/structures/instanced_i_mesh.cpp @@ -16,8 +16,8 @@ namespace gpu_data { InstancedIMeshGPU::InstancedIMeshGPU( const util::Mesh& mesh, const std::vector& model_transforms ) : - IMeshGPU(mesh, false), - transforms_array_(model_transforms, 1), num_models_(model_transforms.size()) { + IMeshGPU(mesh, false), transforms_array_(model_transforms, 1), + num_models_(model_transforms.size()) { // InstancedInt does not have a color texture. One must inherit from this // class and define a method that creates a color texture, and sets its id // as color_texture_. diff --git a/src/gui/render/structures/model.hpp b/src/gui/render/structures/model.hpp index ecc8c466..517e34bf 100644 --- a/src/gui/render/structures/model.hpp +++ b/src/gui/render/structures/model.hpp @@ -95,7 +95,7 @@ class ModelController : virtual public gui::gpu_data::GPUDataElementsInstanced { model_mesh_(std::move(other.model_mesh_)), model_textures_(std::move(other.model_textures_)), texture_id_(std::move(other.texture_id_)), - placements_(std::move(other.placements_)), offset_(std::move(other.offset_)){}; + placements_(std::move(other.placements_)), offset_(std::move(other.offset_)) {}; // copy operator inline ModelController& operator=(const ModelController& obj) = delete; ModelController& operator=(ModelController&& other) = default; diff --git a/src/gui/render/structures/static_mesh.hpp b/src/gui/render/structures/static_mesh.hpp index ae50a62d..4d8a7ccf 100644 --- a/src/gui/render/structures/static_mesh.hpp +++ b/src/gui/render/structures/static_mesh.hpp @@ -44,8 +44,7 @@ class StaticMesh : public virtual InstancedIMeshGPU { inline StaticMesh( const util::Mesh& mesh, const std::vector& model_transforms - ) : - InstancedIMeshGPU(mesh, model_transforms) {} + ) : InstancedIMeshGPU(mesh, model_transforms) {} inline virtual ~StaticMesh() {} diff --git a/src/gui/render/structures/terrain_mesh.cpp b/src/gui/render/structures/terrain_mesh.cpp index 0555eca8..d1977664 100644 --- a/src/gui/render/structures/terrain_mesh.cpp +++ b/src/gui/render/structures/terrain_mesh.cpp @@ -6,7 +6,8 @@ namespace gpu_data { namespace detail { -coalesced_data::coalesced_data(const std::unordered_map mesh_map +coalesced_data::coalesced_data( + const std::unordered_map mesh_map ) { size_t total_size = 0; size_t total_elements_size = 0; diff --git a/src/gui/render/structures/terrain_mesh.hpp b/src/gui/render/structures/terrain_mesh.hpp index c16d1f98..b1134069 100644 --- a/src/gui/render/structures/terrain_mesh.hpp +++ b/src/gui/render/structures/terrain_mesh.hpp @@ -177,10 +177,10 @@ class TerrainMesh : public virtual IMeshMultiGPU { public: inline TerrainMesh() : - color_texture_(terrain::TerrainColorMapping::get_color_texture()){}; + color_texture_(terrain::TerrainColorMapping::get_color_texture()) {}; inline TerrainMesh(Texture1D& color_texture_id) : - color_texture_(color_texture_id){}; + color_texture_(color_texture_id) {}; inline TerrainMesh( const std::unordered_map mesh_map, diff --git a/src/gui/render/structures/uniform_types.hpp b/src/gui/render/structures/uniform_types.hpp index 7eb6dfc0..a1a006b0 100644 --- a/src/gui/render/structures/uniform_types.hpp +++ b/src/gui/render/structures/uniform_types.hpp @@ -18,7 +18,7 @@ namespace render { class LightEnvironment { private: public: - virtual ~LightEnvironment(){}; + virtual ~LightEnvironment() {}; virtual glm::vec3 get_light_direction() const = 0; virtual glm::vec3 get_diffuse_light() const = 0; @@ -27,7 +27,7 @@ class LightEnvironment { class StarRotation { public: - virtual ~StarRotation(){}; + virtual ~StarRotation() {}; virtual glm::mat4 get_sky_rotation() const = 0; }; @@ -39,7 +39,7 @@ class LightDirection : public shader::UniformExecutor { LightDirection(std::shared_ptr lighting) : UniformExecutor(gpu_data::GPUArayType::FLOAT_VEC3), lighting_(lighting) {} - virtual ~LightDirection(){}; + virtual ~LightDirection() {}; virtual void bind(GLint uniform_ID) const override { @@ -66,7 +66,7 @@ class DiffuseLight : public shader::UniformExecutor { DiffuseLight(std::shared_ptr lighting) : UniformExecutor(gpu_data::GPUArayType::FLOAT_VEC3), lighting_(lighting) {} - virtual ~DiffuseLight(){}; + virtual ~DiffuseLight() {}; virtual void bind(GLint uniform_ID) const override { @@ -93,7 +93,7 @@ class SpectralLight : public shader::UniformExecutor { SpectralLight(std::shared_ptr lighting) : UniformExecutor(gpu_data::GPUArayType::FLOAT_VEC3), lighting_(lighting) {} - virtual ~SpectralLight(){}; + virtual ~SpectralLight() {}; inline virtual void bind(GLint uniform_ID) const override { @@ -117,7 +117,7 @@ class MatrixViewProjection : public shader::UniformExecutor { MatrixViewProjection(std::shared_ptr controller) : UniformExecutor(gpu_data::GPUArayType::FLOAT_MAT4), controller_(controller) {} - virtual ~MatrixViewProjection(){}; + virtual ~MatrixViewProjection() {}; inline virtual void bind(GLint uniform_ID) const override { @@ -141,7 +141,7 @@ class ViewMatrix : public shader::UniformExecutor { ViewMatrix(std::shared_ptr controller) : UniformExecutor(gpu_data::GPUArayType::FLOAT_MAT4), controller_(controller) {} - virtual ~ViewMatrix(){}; + virtual ~ViewMatrix() {}; inline virtual void bind(GLint uniform_ID) const override { diff --git a/src/gui/scene/scene.hpp b/src/gui/scene/scene.hpp index 5a5fc16f..7700f90f 100644 --- a/src/gui/scene/scene.hpp +++ b/src/gui/scene/scene.hpp @@ -204,7 +204,8 @@ class Scene { * @param render object that can render to a framebuffer. */ inline void - add_background_ground_renderer(const std::shared_ptr render + add_background_ground_renderer( + const std::shared_ptr render ) { background_frame_buffer_.push_back(render); } diff --git a/src/gui/ui/imgui_gui.cpp b/src/gui/ui/imgui_gui.cpp index 5ce2dc92..f9690f97 100644 --- a/src/gui/ui/imgui_gui.cpp +++ b/src/gui/ui/imgui_gui.cpp @@ -83,8 +83,9 @@ imgui_entry(GLFWwindow* window, world::World& world, world::Climate& climate) { std::shared_ptr controller = std::make_shared(key_mapping); scene::InputHandler::set_window(window); - scene::InputHandler::forward_inputs_to(static_pointer_cast(controller - )); + scene::InputHandler::forward_inputs_to( + static_pointer_cast(controller) + ); // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); @@ -146,7 +147,8 @@ imgui_entry(GLFWwindow* window, world::World& world, world::Climate& climate) { // 2. Show a simple window that we create ourselves. We use a Begin/End pair to // create a named window. { - ImGui::Begin("Hello, world!" + ImGui::Begin( + "Hello, world!" ); // Create a window called "Hello, world!" and append into it. if (scene::InputHandler::escape()) { @@ -156,7 +158,8 @@ imgui_entry(GLFWwindow* window, world::World& world, world::Climate& climate) { scene::InputHandler::clear_escape(); } - ImGui::Text("This is some useful text." + ImGui::Text( + "This is some useful text." ); // Display some text (you can use a format strings too) ImGui::Checkbox("Position Window", &show_position_window); ImGui::Checkbox("Show Light Controls", &show_light_controls); diff --git a/src/gui/ui/imgui_windows.cpp b/src/gui/ui/imgui_windows.cpp index a713db5e..198529bc 100644 --- a/src/gui/ui/imgui_windows.cpp +++ b/src/gui/ui/imgui_windows.cpp @@ -108,7 +108,8 @@ display_data(const manifest::ObjectHandler& object_handler, bool& show) { for (auto& [id, object] : object_handler) { // Display a data item - ImGui::PushID(std::hash{}(id) + ImGui::PushID( + std::hash{}(id) ); // maybe not grate to call hashes like this ImGui::TableNextRow(); ImGui::TableNextColumn(); diff --git a/src/gui/ui/scene_setup.cpp b/src/gui/ui/scene_setup.cpp index 13d50f15..80eb9f16 100644 --- a/src/gui/ui/scene_setup.cpp +++ b/src/gui/ui/scene_setup.cpp @@ -295,7 +295,8 @@ setup( star_pipeline->data.push_back(star_data); sun_pipeline->data.push_back(star_shape); - terrain_mesh->set_shadow_texture(scene.get_shadow_map().get_depth_buffer()->value() + terrain_mesh->set_shadow_texture( + scene.get_shadow_map().get_depth_buffer()->value() ); chunks_render_pipeline->data.push_back(terrain_mesh.get()); chunks_shadow_pipeline->data.push_back(terrain_mesh.get()); @@ -306,7 +307,8 @@ setup( render_programs_t object_render_programs{ .entity_render_program = entity_render_pipeline, - .tile_object_render_program = tile_entity_render_pipeline}; + .tile_object_render_program = tile_entity_render_pipeline + }; // attach the world objects to the render program for (auto& [id, object] : *world.get_object_handler()) { diff --git a/src/local_context.cpp b/src/local_context.cpp index 807c2abf..194db241 100644 --- a/src/local_context.cpp +++ b/src/local_context.cpp @@ -6,7 +6,8 @@ // #include -LocalContext::LocalContext() { +LocalContext::LocalContext() : + context_(GlobalContext::instance().as_engine()->CreateContext()) { lua_state.open_libraries(sol::lib::base); lua_state.open_libraries(sol::lib::math); lua_state.open_libraries(sol::lib::string); @@ -15,6 +16,10 @@ LocalContext::LocalContext() { terrain::generation::init_lua_interface(lua_state); } +LocalContext::~LocalContext() { + context_->Release(); +} + LocalContext& LocalContext::instance() { static thread_local LocalContext local_ctx; diff --git a/src/local_context.hpp b/src/local_context.hpp index 6d55e123..58b65eaa 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -25,8 +25,10 @@ #pragma once -#include #include +#include + +#include class asContextWrapper; @@ -35,12 +37,13 @@ class LocalContext { LocalContext(); sol::state lua_state; - asIScriptFunction* context_; + asIScriptContext* context_; sol::object copy(sol::state& lua, const sol::object& object); public: [[nodiscard]] static LocalContext& instance(); + ~LocalContext(); [[nodiscard]] inline sol::state& get_lua_state() { @@ -55,5 +58,25 @@ class LocalContext { std::optional get_from_lua(const std::string& command); - auto run_function(asIScriptFunction* function); + template + std::expected + run_function(asIScriptFunction* function) { + context_->Prepare(function); + // set args maybe + int result = context_->Execute(); + if (result != asEXECUTION_FINISHED) { + return std::unexpected(result); + } + T object = *static_cast(context_->GetReturnObject()); + + return object; + } + + int + run_function(asIScriptFunction* function) { + context_->Prepare(function); + // set args maybe + int result = context_->Execute(); + return result; + } }; diff --git a/src/main.cpp b/src/main.cpp index b8c9cf6c..8b276b24 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -9,10 +9,10 @@ #include "local_context.hpp" #include "logging.hpp" #include "manifest/object_handler.hpp" +#include "util/angle_script/as_tests.hpp" #include "util/files.hpp" #include "util/lua/lua_logging.hpp" #include "util/lua/lua_tests.hpp" -#include "util/angle_script/as_tests.hpp" #include "util/mesh.hpp" #include "util/png_image.hpp" #include "util/time.hpp" @@ -438,6 +438,28 @@ lua_tests(const argh::parser& cmdl) { } } +int +as_tests(const argh::parser& cmdl) { + if (cmdl.size() < 3) { + return as_test::test(); + } + + std::string run_function = cmdl(3).str(); + + if (run_function == "Map") { + return 1; // MacroMap(cmdl); + } else if (run_function == "Logging") { + return 1; // as_test::lua_log_test(); + } else if (run_function == "LoadTime") { + return 1; // as_test::lua_loadtime_test(); + } else if (run_function == "LoadScript") { + return as_test::as_load_tests(); + } else { + std::cout << "No known command" << std::endl; + return 1; + } +} + // for tests. Probably should make a bash script to test each test inline int tests(const argh::parser& cmdl) { @@ -471,7 +493,7 @@ tests(const argh::parser& cmdl) { } else if (run_function == "Lua") { return lua_tests(cmdl); } else if (run_function == "AngelScript") { - return as_test::test(); + return as_tests(cmdl); } else { std::cout << "No known command" << std::endl; return 1; diff --git a/src/manifest/manifest.hpp b/src/manifest/manifest.hpp index c0458eda..07f50ec0 100644 --- a/src/manifest/manifest.hpp +++ b/src/manifest/manifest.hpp @@ -31,7 +31,8 @@ struct manifest_t { } // namespace manifest template <> -inline glz::detail::any_t::operator std::vector() const { +inline glz::detail::any_t:: +operator std::vector() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/manifest/object_handler.hpp b/src/manifest/object_handler.hpp index d59e29c0..fea7715f 100644 --- a/src/manifest/object_handler.hpp +++ b/src/manifest/object_handler.hpp @@ -156,9 +156,9 @@ class ObjectHandler { for (const auto& directory_entry : std::filesystem::directory_iterator(manifest_folder)) { - auto manifest_opt = - files::read_json_from_file(directory_entry.path() - ); + auto manifest_opt = files::read_json_from_file( + directory_entry.path() + ); if (!manifest_opt) { if constexpr (opengl) { diff --git a/src/util/angle_script/as_logging.cpp b/src/util/angle_script/as_logging.cpp index 722fa81c..f8a5aeaf 100644 --- a/src/util/angle_script/as_logging.cpp +++ b/src/util/angle_script/as_logging.cpp @@ -1,21 +1,23 @@ -#include "logging.hpp" #include "local_context.hpp" -#include +#include "logging.hpp" + #include +#include + namespace as_logging { inline void as_log_backtrace(std::string message) { // get engine from local context - //auto& localcontext = LocalContext::instance(); - //auto engine = localcontext.as_engine(); - + // auto& localcontext = LocalContext::instance(); + // auto engine = localcontext.as_engine(); + std::string file(""); int line = 5; LOG_BACKTRACE( - logging::main_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message + logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + message ); } @@ -24,8 +26,8 @@ as_log_info(std::string message) { std::string file(""); int line = 5; LOG_INFO( - logging::main_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message + logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + message ); } @@ -34,8 +36,8 @@ as_log_debug(std::string message) { std::string file(""); int line = 5; LOG_DEBUG( - logging::main_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message + logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + message ); } @@ -44,8 +46,8 @@ as_log_warning(std::string message) { std::string file(""); int line = 5; LOG_WARNING( - logging::main_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message + logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + message ); } @@ -54,8 +56,8 @@ as_log_error(std::string message) { std::string file(""); int line = 5; LOG_ERROR( - logging::main_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message + logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + message ); } @@ -64,9 +66,9 @@ as_log_critical(std::string message) { std::string file(""); int line = 5; LOG_CRITICAL( - logging::main_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message + logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + message ); } -} // namespace name +} // namespace as_logging diff --git a/src/util/angle_script/as_logging.hpp b/src/util/angle_script/as_logging.hpp index 0086b923..66cf7e69 100644 --- a/src/util/angle_script/as_logging.hpp +++ b/src/util/angle_script/as_logging.hpp @@ -4,23 +4,16 @@ namespace as_logging { -inline void -as_log_backtrace(std::string message); +inline void as_log_backtrace(std::string message); -inline void -as_log_info(std::string message); +inline void as_log_info(std::string message); -inline void -as_log_debug(std::string message); +inline void as_log_debug(std::string message); -inline void -as_log_warning(std::string message); +inline void as_log_warning(std::string message); -inline void -as_log_error(std::string message); +inline void as_log_error(std::string message); -inline void -as_log_critical(std::string message); - -} // namespace name +inline void as_log_critical(std::string message); +} // namespace as_logging diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angle_script/as_tests.cpp index f7f11d5c..7bb25900 100644 --- a/src/util/angle_script/as_tests.cpp +++ b/src/util/angle_script/as_tests.cpp @@ -1,12 +1,16 @@ +#include "global_context.hpp" +#include "local_context.hpp" #include "logging.hpp" -#include #include "util/files.hpp" + +#include + namespace as_test { int test() { - asIScriptEngine *engine = asCreateScriptEngine(); + asIScriptEngine* engine = asCreateScriptEngine(); if (!engine) { LOG_ERROR(logging::main_logger, "Could no start Angle Script engine."); return 1; @@ -15,7 +19,7 @@ test() { asIScriptModule* mod = engine->GetModule("test_module", asGM_CREATE_IF_NOT_EXISTS); std::ostringstream script; auto file = files::open_file(files::get_resources_path() / "as" / "test.as"); - if (! file) { + if (!file) { engine->ShutDownAndRelease(); return 1; } @@ -29,11 +33,12 @@ test() { return 1; } - asIScriptFunction* funct1 = engine->GetModule("test_module")->GetFunctionByDecl("void test1()"); + asIScriptFunction* funct1 = + engine->GetModule("test_module")->GetFunctionByDecl("void test1()"); asIScriptContext* ctx = engine->CreateContext(); ctx->Prepare(funct1); -// ctx->SetArgDWord(); + // ctx->SetArgDWord(); result = ctx->Execute(); if (result != asEXECUTION_FINISHED) { ctx->Release(); @@ -41,10 +46,11 @@ test() { return 1; } - asIScriptFunction* funct2 = engine->GetModule("test_module")->GetFunctionByDecl("int test2()"); + asIScriptFunction* funct2 = + engine->GetModule("test_module")->GetFunctionByDecl("int test2()"); ctx->Prepare(funct2); -// ctx->SetArgDWord(); + // ctx->SetArgDWord(); result = ctx->Execute(); if (result != asEXECUTION_FINISHED) { ctx->Release(); @@ -52,7 +58,7 @@ test() { return 1; } int returnvalue = ctx->GetReturnDWord(); - if (returnvalue == 1 || returnvalue == 0){ + if (returnvalue == 1 || returnvalue == 0) { ctx->Release(); engine->ShutDownAndRelease(); return 1; @@ -62,5 +68,25 @@ test() { return 0; } +int +as_load_tests() { + GlobalContext& context = GlobalContext::instance(); + + context.load_file("main", files::get_resources_path() / "as" / "test.as"); + + context.load_file("Base", files::get_data_path() / "Base" / "biome_map.as"); + + auto function = context.get_function("Base", "void do_something()"); + + LocalContext& local_context = LocalContext::instance(); + int result = local_context.run_function(function); + + if (result != asEXECUTION_FINISHED) { + LOG_ERROR(logging::main_logger, "Failed AngelScript Test"); + return 1; + } + + return 0; } +} // namespace as_test diff --git a/src/util/angle_script/as_tests.hpp b/src/util/angle_script/as_tests.hpp index 217a9439..6daaba0d 100644 --- a/src/util/angle_script/as_tests.hpp +++ b/src/util/angle_script/as_tests.hpp @@ -3,8 +3,8 @@ namespace as_test { -int -test(); +int test(); -} +int as_load_tests(); +} // namespace as_test diff --git a/src/util/image.hpp b/src/util/image.hpp index 4fe4cbb4..78556f94 100644 --- a/src/util/image.hpp +++ b/src/util/image.hpp @@ -70,9 +70,7 @@ class Image { inline Image( std::shared_ptr data, size_t width, size_t height, size_t data_size - ) : - width_(width), - height_(height), data_size_(data_size), data_(data){}; + ) : width_(width), height_(height), data_size_(data_size), data_(data) {}; virtual ~Image() {} }; @@ -107,8 +105,7 @@ class FloatMonochromeImage : public virtual MonochromeImage { FloatMonochromeImage( std::shared_ptr data, size_t width, size_t height, size_t data_size - ) : - Image(data, width, height, data_size) {} + ) : Image(data, width, height, data_size) {} inline virtual size_t get_width() const { @@ -131,8 +128,7 @@ class FloatPolychromeImage : public virtual PolychromeImage { FloatPolychromeImage( std::shared_ptr data, size_t width, size_t height, size_t data_size - ) : - Image(data, width, height, data_size) {} + ) : Image(data, width, height, data_size) {} inline virtual size_t get_width() const { @@ -162,8 +158,7 @@ class FloatPolychromeAlphaImage : public virtual PolychromeAlphaImage { FloatPolychromeAlphaImage( std::shared_ptr data, size_t width, size_t height, size_t data_size - ) : - Image(data, width, height, data_size) {} + ) : Image(data, width, height, data_size) {} FloatPolychromeAlphaImage(std::vector> data) : FloatPolychromeAlphaImage(pad_color_data(data)) {} diff --git a/src/util/mesh.hpp b/src/util/mesh.hpp index 33c7e534..ff3dbf27 100644 --- a/src/util/mesh.hpp +++ b/src/util/mesh.hpp @@ -49,10 +49,9 @@ class Mesh { const std::vector& indexed_normals, const std::vector& color_map, glm::ivec3 size, glm::ivec3 center ) : - size_(size), - center_(center), indices_(indices), indexed_vertices_(indexed_vertices), - indexed_color_ids_(indexed_color_ids), indexed_normals_(indexed_normals), - color_map_(color_map) {} + size_(size), center_(center), indices_(indices), + indexed_vertices_(indexed_vertices), indexed_color_ids_(indexed_color_ids), + indexed_normals_(indexed_normals), color_map_(color_map) {} Mesh() : size_({0, 0, 0}), center_({0, 0, 0}), indices_({}), indexed_vertices_({}), diff --git a/src/util/png_image.hpp b/src/util/png_image.hpp index 556dfc97..31c3c968 100644 --- a/src/util/png_image.hpp +++ b/src/util/png_image.hpp @@ -181,7 +181,7 @@ void log_result(write_result_t result, const std::filesystem::path& path); class ImageTest { public: - ImageTest(){}; + ImageTest() {}; size_t get_height() const { @@ -324,7 +324,7 @@ write_image(T image, const std::filesystem::path& path) { class ColorImageTest { public: - ColorImageTest(){}; + ColorImageTest() {}; size_t get_height() const { diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 8e23448c..666b1ef0 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -91,11 +91,22 @@ Biome::Biome(biome_json_data biome_data, size_t seed) : TerrainMacroMap Biome::get_map(MacroDim size) const { + auto& global_context = GlobalContext::instance(); + auto function = global_context.get_function("base", "biome_map"); + + if (function == nullptr) { + // log warning return + } + std::vector out; LocalContext& local_context = LocalContext::instance(); auto biome_map_query = local_context.get_from_lua(id_name_ + "\\biome_map"); + auto terrain_map = local_context.run_function(function); + + // get result + if (!biome_map_query) { LOG_ERROR(logging::lua_logger, "Could not copy biome map."); return {}; @@ -278,9 +289,11 @@ Biome::get_plant_map(Dim length) const { std::string type_as_string = flora_type.as(); - out.emplace(std::make_pair( - std::move(type_as_string), {type_map, x_map_tiles, y_map_tiles} - )); + out.emplace( + std::make_pair( + std::move(type_as_string), {type_map, x_map_tiles, y_map_tiles} + ) + ); } return out; diff --git a/src/world/object/entity/entity.cpp b/src/world/object/entity/entity.cpp index f03c94e2..233ccfaf 100644 --- a/src/world/object/entity/entity.cpp +++ b/src/world/object/entity/entity.cpp @@ -14,9 +14,11 @@ namespace object { namespace entity { Entity::Entity(const util::Mesh& mesh) : - mesh_and_positions_(std::make_shared( - mesh, std::vector() - )) { + mesh_and_positions_( + std::make_shared( + mesh, std::vector() + ) + ) { LOG_WARNING( logging::main_logger, "Entity constructor Entity(const Mesh& mesh) is depreciated!" @@ -25,9 +27,7 @@ Entity::Entity(const util::Mesh& mesh) : Entity::Entity( const object_t& object_data, const manifest::descriptor_t& identification_data -) : - name_(object_data.name), - identification_(identification_data.identification) { +) : name_(object_data.name), identification_(identification_data.identification) { const auto& model_data = object_data.models[0]; // read mesh from path std::filesystem::path object_path_copy = identification_data.path; diff --git a/src/world/object/entity/entity.hpp b/src/world/object/entity/entity.hpp index 453cd45e..e825d7d1 100644 --- a/src/world/object/entity/entity.hpp +++ b/src/world/object/entity/entity.hpp @@ -83,7 +83,7 @@ class Entity : public virtual Object, public virtual Cognition { Entity(const object_t& object_data, const manifest::descriptor_t& model_path); - virtual ~Entity(){}; + virtual ~Entity() {}; inline void reserve(size_t size) const { diff --git a/src/world/object/entity/implemented_entity.hpp b/src/world/object/entity/implemented_entity.hpp index dcd93bda..efad9069 100644 --- a/src/world/object/entity/implemented_entity.hpp +++ b/src/world/object/entity/implemented_entity.hpp @@ -12,8 +12,7 @@ class ImplementedEntity : public virtual Entity { public: ImplementedEntity( const object_t& object_data, const manifest::descriptor_t& model_path - ) : - Entity(object_data, model_path) {} + ) : Entity(object_data, model_path) {} [[nodiscard]] virtual glm::vec3 decision(EntityInstance* entity_instance) override; }; diff --git a/src/world/object/entity/object.hpp b/src/world/object/entity/object.hpp index c5a042ae..80229d99 100644 --- a/src/world/object/entity/object.hpp +++ b/src/world/object/entity/object.hpp @@ -110,8 +110,8 @@ struct glz::meta { }; template <> -inline glz::detail::any_t::operator std::vector( -) const { +inline glz::detail::any_t:: +operator std::vector() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/world/object/entity/tile_object.cpp b/src/world/object/entity/tile_object.cpp index 0514f3e6..4a899e26 100644 --- a/src/world/object/entity/tile_object.cpp +++ b/src/world/object/entity/tile_object.cpp @@ -11,9 +11,7 @@ namespace entity { TileObjectInstance::TileObjectInstance( std::shared_ptr object_type, uint8_t model_id, gui::Placement placement -) : - placement_(placement), - model_id_(model_id), object_type_(object_type) { +) : placement_(placement), model_id_(model_id), object_type_(object_type) { object_type->get_model(model_id_).insert(placement_); } @@ -48,9 +46,7 @@ TileObject::num_models() const noexcept { TileObject::TileObject( const object_t& object_data, const manifest::descriptor_t& identification_data -) : - name_(object_data.name), - identification_(identification_data.identification) { +) : name_(object_data.name), identification_(identification_data.identification) { for (const model_t& model_data : object_data.models) { // each object may have multiple models std::filesystem::path object_path_copy = identification_data.path; diff --git a/src/world/object/entity_controller.cpp b/src/world/object/entity_controller.cpp index c0711a11..70a7f252 100644 --- a/src/world/object/entity_controller.cpp +++ b/src/world/object/entity_controller.cpp @@ -61,7 +61,8 @@ EntityController::spawn_entity(std::string identification, glm::vec3 position) { } void -EntityController::remove_entity(std::shared_ptr entity_instance +EntityController::remove_entity( + std::shared_ptr entity_instance ) { // get position ChunkPos chunk_position = @@ -107,9 +108,11 @@ EntityController::spawn_tile_object( // tile_object_instances_.at(position).insert(object); auto inserted = object_instances_.at(chunk_position) - .insert(std::make_shared( - tile_object_type, model_id, placement - )); + .insert( + std::make_shared( + tile_object_type, model_id, placement + ) + ); return *inserted.first; } diff --git a/src/world/object/entity_controller.hpp b/src/world/object/entity_controller.hpp index 21d2aa68..879ed392 100644 --- a/src/world/object/entity_controller.hpp +++ b/src/world/object/entity_controller.hpp @@ -25,7 +25,7 @@ class EntityController { public: EntityController(manifest::ObjectHandler* object_handler) : - object_handler_(object_handler){}; + object_handler_(object_handler) {}; void update_entities(glm::mat4 transforms_matrix); @@ -39,8 +39,8 @@ class EntityController { std::string identification, uint8_t model_id, gui::Placement placement ); - void remove_tile_object(std::shared_ptr entity_instance - ); + void + remove_tile_object(std::shared_ptr entity_instance); void load_to_gup(); diff --git a/src/world/plant.hpp b/src/world/plant.hpp index 7910c1c3..d7f341c7 100644 --- a/src/world/plant.hpp +++ b/src/world/plant.hpp @@ -28,8 +28,8 @@ struct plant_t { // path to lua file that contains function map_name std::optional map_generator_path; - [[nodiscard]] inline std::strong_ordering operator<=>(const plant_t& other - ) const = default; + [[nodiscard]] inline std::strong_ordering + operator<=>(const plant_t& other) const = default; }; } // namespace generation @@ -46,7 +46,8 @@ struct std::hash { }; template <> -inline glz::detail::any_t::operator std::filesystem::path() const { +inline glz::detail::any_t:: +operator std::filesystem::path() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/world/terrain/chunk.cpp b/src/world/terrain/chunk.cpp index 9ac83160..7cb04f8f 100644 --- a/src/world/terrain/chunk.cpp +++ b/src/world/terrain/chunk.cpp @@ -55,7 +55,8 @@ Chunk::stamp_tile_region( void Chunk::init_nodegroups() { - std::unordered_map temporary_position_to_nodegroup_map({} + std::unordered_map temporary_position_to_nodegroup_map( + {} ); // for all tiles: @@ -171,7 +172,8 @@ Chunk::add_nodegroup_adjacent_mp() { continue; } std::scoped_lock lock{ - mut_, ter_->get_chunk(adjacent_chunk)->get_mutex()}; + mut_, ter_->get_chunk(adjacent_chunk)->get_mutex() + }; NG.add_adjacent(to_add, 31); } } @@ -207,7 +209,8 @@ Chunk::add_nodegroup_adjacent_all() { continue; } std::scoped_lock lock{ - mut_, ter_->get_chunk(adjacent_chunk)->get_mutex()}; + mut_, ter_->get_chunk(adjacent_chunk)->get_mutex() + }; NG.add_adjacent(to_add, 31); } } diff --git a/src/world/terrain/chunk.hpp b/src/world/terrain/chunk.hpp index 4c6d51a4..b856c106 100644 --- a/src/world/terrain/chunk.hpp +++ b/src/world/terrain/chunk.hpp @@ -65,7 +65,7 @@ class Chunk : public voxel_utility::VoxelBase { * @param bz chunk z position * @param ter the terrain this chunk is in */ - Chunk(Dim bx, Dim by, Dim bz, Terrain* ter) : Chunk({bx, by, bz}, ter){}; + Chunk(Dim bx, Dim by, Dim bz, Terrain* ter) : Chunk({bx, by, bz}, ter) {}; Chunk(TerrainDim3 chunk_position, Terrain* ter); @@ -238,7 +238,7 @@ class ChunkData : public voxel_utility::VoxelBase { inline ChunkData(const Chunk& chunk) : data_(get_mat_color_from_chunk(chunk)), offset_(chunk.get_offset()), - color_ids_(chunk.get_color_ids()){}; + color_ids_(chunk.get_color_ids()) {}; /** * @brief Used for getting mesh diff --git a/src/world/terrain/generation/land_generator.cpp b/src/world/terrain/generation/land_generator.cpp index ab2ad8c5..526342f2 100644 --- a/src/world/terrain/generation/land_generator.cpp +++ b/src/world/terrain/generation/land_generator.cpp @@ -67,8 +67,9 @@ LandGenerator::next() { namespace stamps { TileStamp -StampGenerator::get_volume(glm::imat2x2 center, std::default_random_engine& rand_engine) - const { +StampGenerator::get_volume( + glm::imat2x2 center, std::default_random_engine& rand_engine +) const { // center_x between center[1][0] and center[0][0] inclusive std::uniform_int_distribution center_x_dist( center[0][0], center[1][0] @@ -172,9 +173,7 @@ FromRadius::get_stamp( FromPosition::FromPosition( const generation_stamp_t& data, const stamp_generation_position_data_t& type_data -) : - StampGenerator(data), - center_variance_(data.center_range) { +) : StampGenerator(data), center_variance_(data.center_range) { points_.reserve(type_data.positions.size()); for (const auto& [x, y] : type_data.positions) { @@ -196,8 +195,9 @@ FromPosition::get_stamp( } TileStamp -FromGrid::get_stamp(size_t current_sub_region, std::default_random_engine& rand_engine) - const { +FromGrid::get_stamp( + size_t current_sub_region, std::default_random_engine& rand_engine +) const { TerrainOffset x_center = (1 + 2 * (current_sub_region % number_)) * (radius_ / number_) - radius_; TerrainOffset y_center = diff --git a/src/world/terrain/generation/land_generator.hpp b/src/world/terrain/generation/land_generator.hpp index 50aef3bb..6bdf3cee 100644 --- a/src/world/terrain/generation/land_generator.hpp +++ b/src/world/terrain/generation/land_generator.hpp @@ -175,8 +175,7 @@ class FromRadius : public StampGenerator { FromRadius( const generation_stamp_t& data, const stamp_generation_radius_data_t& type_data ) : - StampGenerator(data), - radius_(type_data.radius), number_(type_data.number), + StampGenerator(data), radius_(type_data.radius), number_(type_data.number), center_variance_(data.center_range) {} FromRadius(const generation_stamp_t& data) : @@ -202,8 +201,7 @@ class FromGrid : public StampGenerator { FromGrid( const generation_stamp_t& data, const stamp_generation_grid_data_t& type_data ) : - StampGenerator(data), - radius_(type_data.radius), number_(type_data.number), + StampGenerator(data), radius_(type_data.radius), number_(type_data.number), center_variance_(data.center_range) {} FromGrid(const generation_stamp_t& data) : FromGrid(data, data.grid.value()) {} diff --git a/src/world/terrain/generation/lua_interface.cpp b/src/world/terrain/generation/lua_interface.cpp index 3c3e3477..59427301 100644 --- a/src/world/terrain/generation/lua_interface.cpp +++ b/src/world/terrain/generation/lua_interface.cpp @@ -86,5 +86,101 @@ init_lua_interface(sol::state& lua) { "sample", &AlternativeWorleyNoise::get_noise ); } + +FractalNoise* +FractalNoise_factory(int x, double y, int z) { + // The class constructor is initializing the reference counter to 1 + return new FractalNoise(x, y, z); +} + +WorleyNoise* +WorleyNoise_factory(NoisePosition x, NoisePosition y) { + // The class constructor is initializing the reference counter to 1 + return new WorleyNoise(x, y); +} + +AlternativeWorleyNoise* +AlternativeWorleyNoise_factory(NoisePosition x, double y, NoisePosition z) { + // The class constructor is initializing the reference counter to 1 + return new AlternativeWorleyNoise(x, y, z); +} + +void +init_as_interface(asIScriptEngine* engine) { + int r = engine->SetDefaultNamespace("TerrainGeneration"); + assert(r >= 0); + + // Registering the class method + r = engine->RegisterObjectType("FractalNoise", 0, asOBJ_REF); + assert(r >= 0); + r = engine->RegisterObjectBehaviour( + "FractalNoise", asBEHAVE_FACTORY, "FractalNoise@ f(int, double, int)", + asFUNCTION(FractalNoise_factory), asCALL_CDECL + ); + assert(r >= 0); + r = engine->RegisterObjectBehaviour( + "FractalNoise", asBEHAVE_ADDREF, "void f()", asMETHOD(FractalNoise, add_ref), + asCALL_THISCALL + ); + assert(r >= 0); + r = engine->RegisterObjectBehaviour( + "FractalNoise", asBEHAVE_RELEASE, "void f()", + asMETHOD(FractalNoise, release_ref), asCALL_THISCALL + ); + assert(r >= 0); + r = engine->RegisterObjectMethod( + "FractalNoise", "double sample(double, double)", + asMETHOD(FractalNoise, get_noise), asCALL_THISCALL + ); + assert(r >= 0); + + r = engine->RegisterObjectType("WorleyNoise", 0, asOBJ_REF); + assert(r >= 0); + r = engine->RegisterObjectBehaviour( + "WorleyNoise", asBEHAVE_FACTORY, "WorleyNoise@ f(double, double)", + asFUNCTION(WorleyNoise_factory), asCALL_CDECL + ); + assert(r >= 0); + r = engine->RegisterObjectBehaviour( + "WorleyNoise", asBEHAVE_ADDREF, "void f()", asMETHOD(WorleyNoise, add_ref), + asCALL_THISCALL + ); + assert(r >= 0); + r = engine->RegisterObjectBehaviour( + "WorleyNoise", asBEHAVE_RELEASE, "void f()", asMETHOD(WorleyNoise, release_ref), + asCALL_THISCALL + ); + assert(r >= 0); + r = engine->RegisterObjectMethod( + "WorleyNoise", "double sample(double, double)", + asMETHOD(WorleyNoise, get_noise), asCALL_THISCALL + ); + assert(r >= 0); + + r = engine->RegisterObjectType("AlternativeWorleyNoise", 0, asOBJ_REF); + assert(r >= 0); + r = engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", asBEHAVE_FACTORY, + "AlternativeWorleyNoise@ f(double, double, double)", + asFUNCTION(AlternativeWorleyNoise_factory), asCALL_CDECL + ); + assert(r >= 0); + r = engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", asBEHAVE_ADDREF, "void f()", + asMETHOD(AlternativeWorleyNoise, add_ref), asCALL_THISCALL + ); + assert(r >= 0); + r = engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", asBEHAVE_RELEASE, "void f()", + asMETHOD(AlternativeWorleyNoise, release_ref), asCALL_THISCALL + ); + assert(r >= 0); + r = engine->RegisterObjectMethod( + "AlternativeWorleyNoise", "double sample(double, double)", + asMETHOD(AlternativeWorleyNoise, get_noise), asCALL_THISCALL + ); + assert(r >= 0); +} + } // namespace generation } // namespace terrain diff --git a/src/world/terrain/generation/lua_interface.hpp b/src/world/terrain/generation/lua_interface.hpp index 5216ecdd..b15925e0 100644 --- a/src/world/terrain/generation/lua_interface.hpp +++ b/src/world/terrain/generation/lua_interface.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include namespace terrain { @@ -8,6 +9,8 @@ namespace generation { void init_lua_interface(sol::state& lua); +void init_as_interface(asIScriptEngine* engine); + } // namespace generation } // namespace terrain diff --git a/src/world/terrain/generation/map_tile.hpp b/src/world/terrain/generation/map_tile.hpp index 695b744b..b71b1164 100644 --- a/src/world/terrain/generation/map_tile.hpp +++ b/src/world/terrain/generation/map_tile.hpp @@ -123,7 +123,7 @@ class MapTile { rand_engine_( Noise::get_double((seed ^ tile_type.get_tile_type()) % RANDOM_NUMBER, x, y) * INT32_MAX - ){}; + ) {}; /** * @brief Get the x coordinate @@ -191,7 +191,7 @@ class PlantMap { * * @details Default constructor */ - inline PlantMap() : width_(0), height_(0){}; + inline PlantMap() : width_(0), height_(0) {}; /** * @brief Construct a new PlantMap object diff --git a/src/world/terrain/generation/mat_tile.cpp b/src/world/terrain/generation/mat_tile.cpp index 3949c1cf..4f971c20 100644 --- a/src/world/terrain/generation/mat_tile.cpp +++ b/src/world/terrain/generation/mat_tile.cpp @@ -9,9 +9,7 @@ TileType::TileType( const std::unordered_set land_generators, MapTile_t tile_type, const std::vector& layer_effect_generators, const std::unordered_map materials -) : - land_generators_(land_generators), - tile_type_(tile_type) { +) : land_generators_(land_generators), tile_type_(tile_type) { Dim max_height = 0; ColorId stamp_color_id = 0; diff --git a/src/world/terrain/generation/noise.cpp b/src/world/terrain/generation/noise.cpp index 60c7cc64..4ba8aa12 100644 --- a/src/world/terrain/generation/noise.cpp +++ b/src/world/terrain/generation/noise.cpp @@ -38,8 +38,9 @@ Noise::get_double(size_t i, NoiseTileIndex x, NoiseTileIndex y) { } double -generation::FractalNoise::smoothed_noise_(size_t i, NoiseTileIndex x, NoiseTileIndex y) - const { +generation::FractalNoise::smoothed_noise_( + size_t i, NoiseTileIndex x, NoiseTileIndex y +) const { // clang-format off double corners = (get_double(i, x - 1, y - 1) + get_double(i, x + 1, y - 1) diff --git a/src/world/terrain/generation/noise.hpp b/src/world/terrain/generation/noise.hpp index 72dd4eac..5fa17d5f 100644 --- a/src/world/terrain/generation/noise.hpp +++ b/src/world/terrain/generation/noise.hpp @@ -23,6 +23,9 @@ namespace terrain { namespace generation { class Noise { + private: + size_t ref_count; + protected: // The length of Noise::primes static constexpr uint16_t NUM_PRIMES = 10; @@ -57,6 +60,20 @@ class Noise { } virtual ~Noise() {} + + // TODO what I want to do is create some sort of template that does this for me + // Also might want the reference counter to be mutable in the template; + inline void + add_ref() { + ref_count++; + } + + inline void + release_ref() { + if (--ref_count == 0) { + delete this; + } + } }; template @@ -96,6 +113,9 @@ class FractalNoise : protected Noise { */ virtual double get_noise(NoisePosition x, NoisePosition y) const override; + using Noise::add_ref; + using Noise::release_ref; + private: double smoothed_noise_(size_t i, NoiseTileIndex x, NoiseTileIndex y) const; // cosine interpolation diff --git a/src/world/terrain/generation/terrain_genreration_types.hpp b/src/world/terrain/generation/terrain_genreration_types.hpp index a24b4f13..ed2251f4 100644 --- a/src/world/terrain/generation/terrain_genreration_types.hpp +++ b/src/world/terrain/generation/terrain_genreration_types.hpp @@ -146,22 +146,22 @@ struct glz::meta { // error with glaze // when using optional glaze causes compiler errors and this suppresses those errors template <> -inline glz::detail::any_t::operator terrain::generation::stamp_generation_grid_data_t( -) const { +inline glz::detail::any_t:: +operator terrain::generation::stamp_generation_grid_data_t() const { assert(false && "Not Implemented"); return {}; } template <> -inline glz::detail::any_t::operator terrain::generation:: - stamp_generation_position_data_t() const { +inline glz::detail::any_t:: +operator terrain::generation::stamp_generation_position_data_t() const { assert(false && "Not Implemented"); return {}; } template <> -inline glz::detail::any_t::operator terrain::generation::stamp_generation_radius_data_t( -) const { +inline glz::detail::any_t:: +operator terrain::generation::stamp_generation_radius_data_t() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/world/terrain/generation/terrain_map.hpp b/src/world/terrain/generation/terrain_map.hpp index a401a91c..4d98702a 100644 --- a/src/world/terrain/generation/terrain_map.hpp +++ b/src/world/terrain/generation/terrain_map.hpp @@ -23,7 +23,7 @@ class TerrainMacroMap { * * @details default constructor */ - inline TerrainMacroMap() : width_(0), height_(0){}; + inline TerrainMacroMap() : width_(0), height_(0) {}; /** * @brief Create a new TerrainMacroMap @@ -34,9 +34,7 @@ class TerrainMacroMap { */ inline TerrainMacroMap( std::vector terrain_map, size_t width, size_t height - ) : - width_(width), - height_(height), terrain_map_(terrain_map) { + ) : width_(width), height_(height), terrain_map_(terrain_map) { assert(terrain_map_.size() == width_ * height_); }; @@ -133,8 +131,8 @@ class TerrainMapRepresentation { const TerrainMacroMap& map, unsigned int tile_size = 4, unsigned int tile_border = 1 ) : - terrain_map_(map), - tile_size_in_pixels_(tile_size), tile_border_size_(tile_border) {} + terrain_map_(map), tile_size_in_pixels_(tile_size), + tile_border_size_(tile_border) {} [[nodiscard]] inline size_t get_height() const { diff --git a/src/world/terrain/generation/worley_noise.cpp b/src/world/terrain/generation/worley_noise.cpp index 6ec9081e..3688362b 100644 --- a/src/world/terrain/generation/worley_noise.cpp +++ b/src/world/terrain/generation/worley_noise.cpp @@ -33,8 +33,9 @@ WorleyNoise::get_noise(NoisePosition x, NoisePosition y) const { } std::set -WorleyNoise::get_points_(NoiseTileIndex xt, NoiseTileIndex yt, NoiseTileIndex range) - const { +WorleyNoise::get_points_( + NoiseTileIndex xt, NoiseTileIndex yt, NoiseTileIndex range +) const { // assert(range % 2 == 0 && "range must be even"); std::set out; // compute index of worley tile diff --git a/src/world/terrain/generation/worley_noise.hpp b/src/world/terrain/generation/worley_noise.hpp index b0afc454..992a5981 100644 --- a/src/world/terrain/generation/worley_noise.hpp +++ b/src/world/terrain/generation/worley_noise.hpp @@ -80,7 +80,7 @@ class WorleyNoise : protected Noise { * @details Default constructor sets tile_size to 1; */ inline WorleyNoise(NoisePosition tile_size, NoisePosition point_radius) : - tile_size_(tile_size), point_radius_(point_radius){}; + tile_size_(tile_size), point_radius_(point_radius) {}; /** * @brief Get the noise value at given position. @@ -88,6 +88,9 @@ class WorleyNoise : protected Noise { [[nodiscard]] virtual double get_noise(NoisePosition x, NoisePosition y) const override; + using Noise::add_ref; + using Noise::release_ref; + protected: [[nodiscard]] std::set get_points_(NoiseTileIndex x_t, NoiseTileIndex y_t, NoiseTileIndex range) const; @@ -112,14 +115,16 @@ class AlternativeWorleyNoise : public WorleyNoise { */ inline AlternativeWorleyNoise( NoisePosition tile_size, double positive_chance, NoisePosition radius - ) : - WorleyNoise(tile_size, radius) { + ) : WorleyNoise(tile_size, radius) { positive_chance_ = positive_chance; } [[nodiscard]] virtual double get_noise(NoisePosition x, NoisePosition y) const override; + using WorleyNoise::add_ref; + using WorleyNoise::release_ref; + private: [[nodiscard]] double modified_cos_(NoisePosition distance, NoisePosition effective_radius) const; diff --git a/src/world/terrain/material.cpp b/src/world/terrain/material.cpp index 3fa8cda9..dae86c6c 100644 --- a/src/world/terrain/material.cpp +++ b/src/world/terrain/material.cpp @@ -79,9 +79,9 @@ MaterialGroup::insert( return false; } -MaterialGroup::MaterialGroup(const std::vector& data -) : - contain_all_materials(false) { +MaterialGroup::MaterialGroup( + const std::vector& data +) : contain_all_materials(false) { // want to generated a group that represents the given data // There will be elements with no requirements on the color // materials_no_color_requirement_ diff --git a/src/world/terrain/material.hpp b/src/world/terrain/material.hpp index 2ebdb9e1..c1ae6f65 100644 --- a/src/world/terrain/material.hpp +++ b/src/world/terrain/material.hpp @@ -199,9 +199,9 @@ class MaterialGroup { * * @details Default constructor. Nothing will be in the group. */ - inline MaterialGroup() : contain_all_materials(false){}; + inline MaterialGroup() : contain_all_materials(false) {}; - inline MaterialGroup(bool all_materials) : contain_all_materials(all_materials){}; + inline MaterialGroup(bool all_materials) : contain_all_materials(all_materials) {}; /** * @brief Construct new MaterialGroup object. @@ -215,9 +215,8 @@ class MaterialGroup { std::unordered_set materials, std::unordered_map> materials_w_color ) : - contain_all_materials(false), - materials_no_color_requirement_(materials), - materials_with_color_requirement_(materials_w_color){}; + contain_all_materials(false), materials_no_color_requirement_(materials), + materials_with_color_requirement_(materials_w_color) {}; /** * @brief Read the materials and colors that this stamp can overwrite in @@ -342,7 +341,8 @@ struct glz::meta { }; template <> -inline glz::detail::any_t::operator terrain::grass_data_t() const { +inline glz::detail::any_t:: +operator terrain::grass_data_t() const { assert(false && "Not Implemented"); return {}; } diff --git a/src/world/terrain/path/node.hpp b/src/world/terrain/path/node.hpp index eb798d24..903ea9c6 100644 --- a/src/world/terrain/path/node.hpp +++ b/src/world/terrain/path/node.hpp @@ -59,12 +59,12 @@ class Node { // Used to find paths. */ Node(T* tile, float hc) : tile_(tile), parent_node_(nullptr), g_cost_(0), h_cost_(hc), - f_cost_(g_cost_ + h_cost_), explored_(false){}; + f_cost_(g_cost_ + h_cost_), explored_(false) {}; /** * @brief Construct a new Node object (default initializer) * @deprecated should not be used */ - Node() : Node(nullptr, 0){}; + Node() : Node(nullptr, 0) {}; /** * @brief Explore this node diff --git a/src/world/terrain/path/node_group.cpp b/src/world/terrain/path/node_group.cpp index 17051968..c448722e 100644 --- a/src/world/terrain/path/node_group.cpp +++ b/src/world/terrain/path/node_group.cpp @@ -9,8 +9,8 @@ namespace terrain { NodeGroup::NodeGroup( ChunkPos chunk_position, LocalPosition tile_position, UnitPath path_type ) : - chunk_position_(chunk_position), - path_type_(path_type), tile_positions_({tile_position}), center_x(tile_position.x), + chunk_position_(chunk_position), path_type_(path_type), + tile_positions_({tile_position}), center_x(tile_position.x), center_y(tile_position.y), center_z(tile_position.z) {} void diff --git a/src/world/terrain/path/node_wrappers.hpp b/src/world/terrain/path/node_wrappers.hpp index bc347f8f..4a39ac3a 100644 --- a/src/world/terrain/path/node_wrappers.hpp +++ b/src/world/terrain/path/node_wrappers.hpp @@ -8,7 +8,7 @@ class PositionWrapper { TerrainOffset3 position_; public: - inline PositionWrapper(){}; + inline PositionWrapper() {}; inline PositionWrapper(TerrainOffset3 position) : position_(position) {} diff --git a/src/world/terrain/path/tile_iterator.cpp b/src/world/terrain/path/tile_iterator.cpp index 4b06a075..a1bbd449 100644 --- a/src/world/terrain/path/tile_iterator.cpp +++ b/src/world/terrain/path/tile_iterator.cpp @@ -59,8 +59,8 @@ get_indexed_offsets(uint8_t index) { AdjacentIterator::AdjacentIterator( const Terrain& parent, TerrainOffset3 xyz, UnitPath path_type ) : - parent_(parent), - path_type_constraint_(path_type), pos_(xyz), path_type_(0), dpos_(0) { + parent_(parent), path_type_constraint_(path_type), pos_(xyz), path_type_(0), + dpos_(0) { update_path(); if (!path_type_.compatible(path_type_constraint_) || !is_valid_end_position()) { iterate_to_next_available(); diff --git a/src/world/terrain/terrain.cpp b/src/world/terrain/terrain.cpp index 198d784b..288d981b 100644 --- a/src/world/terrain/terrain.cpp +++ b/src/world/terrain/terrain.cpp @@ -82,9 +82,8 @@ Terrain::Terrain( TerrainOffset z, const generation::Biome& biome, generation::TerrainMacroMap macro_map ) : - area_size_(area_size_), - biome_(biome), X_MAX(x_map_tiles * area_size_), Y_MAX(y_map_tiles * area_size_), - Z_MAX(z) { + area_size_(area_size_), biome_(biome), X_MAX(x_map_tiles * area_size_), + Y_MAX(y_map_tiles * area_size_), Z_MAX(z) { // srand(seed); LOG_INFO(logging::terrain_logger, "Start of land generator."); @@ -174,7 +173,8 @@ Terrain::qb_read( if (color == 0) { // if the qb voxel is transparent. mat_color = &materials_inverse.at(0); // set the materials to air - } else if (materials_inverse.count(color + } else if (materials_inverse.count( + color )) { // if the color is known mat_color = &materials_inverse.at(color); } else { // the color is unknown @@ -545,8 +545,9 @@ Terrain::set_tile_material( } ColorId -Terrain::natural_color(TerrainOffset3 xyz, const material_t* mat, ColorId color_id) - const { +Terrain::natural_color( + TerrainOffset3 xyz, const material_t* mat, ColorId color_id +) const { auto mat_id = mat->material_id; if (mat_id == DIRT_ID) { // being set to dirt // adds striations to the dirt. (This should be done by lua in the future) diff --git a/src/world/terrain/terrain.hpp b/src/world/terrain/terrain.hpp index 902deda5..2fb9aa9b 100644 --- a/src/world/terrain/terrain.hpp +++ b/src/world/terrain/terrain.hpp @@ -641,8 +641,8 @@ class Terrain : public voxel_utility::VoxelBase { * @return true can stand * @return false cannot stand */ - [[nodiscard]] bool can_stand_1(TerrainOffset3 xyz - ) const; // this might be faster, and used for looping + [[nodiscard]] bool + can_stand_1(TerrainOffset3 xyz) const; // this might be faster, and used for looping /** * @brief test if dxy x dyx x dz object can stand at given position diff --git a/src/world/terrain/terrain_helper-impls.cpp b/src/world/terrain/terrain_helper-impls.cpp index 8a1bf059..4727d895 100644 --- a/src/world/terrain/terrain_helper-impls.cpp +++ b/src/world/terrain/terrain_helper-impls.cpp @@ -36,12 +36,14 @@ namespace terrain { // implementations of start of iteration template void helper::grow_grass_recursive< - helper::edge_detector_low, helper::getter_low, - helper::setter_low>(Terrain&, std::unordered_set); + helper::edge_detector_low, helper::getter_low, helper::setter_low>( + Terrain&, std::unordered_set +); template void helper::grow_grass_recursive< - helper::edge_detector_high, helper::getter_high, - helper::setter_high>(Terrain&, std::unordered_set); + helper::edge_detector_high, helper::getter_high, helper::setter_high>( + Terrain&, std::unordered_set +); // implementations of inner recursive loop template void helper::grow_grass_inner( diff --git a/src/world/terrain/terrain_helper.cpp b/src/world/terrain/terrain_helper.cpp index 0ad8a073..d758f548 100644 --- a/src/world/terrain/terrain_helper.cpp +++ b/src/world/terrain/terrain_helper.cpp @@ -20,7 +20,7 @@ namespace helper { * given a set of grass tiles gets the adjacent grass tiles that have height * equal to given hight. Then next to those tiles set the grass height to * hight-1 if this is higher than the saved height. -*/ + */ template void grow_grass_inner( diff --git a/src/world/world.cpp b/src/world/world.cpp index a41c737c..4d39ef0a 100644 --- a/src/world/world.cpp +++ b/src/world/world.cpp @@ -49,18 +49,17 @@ World::World( manifest::ObjectHandler* object_handler, const std::string& biome_name, const std::string& path, size_t seed ) : - biome_(biome_name, seed), - terrain_main_(path, biome_), controller_(object_handler) {} + biome_(biome_name, seed), terrain_main_(path, biome_), controller_(object_handler) { +} World::World( manifest::ObjectHandler* object_handler, const std::string& biome_name, MacroDim x_tiles, MacroDim y_tiles, size_t seed ) : - biome_(biome_name, seed), - terrain_main_( - x_tiles, y_tiles, macro_tile_size, height, biome_, - std::move(biome_.get_map(x_tiles)) - ), + biome_(biome_name, seed), terrain_main_( + x_tiles, y_tiles, macro_tile_size, height, biome_, + std::move(biome_.get_map(x_tiles)) + ), controller_(object_handler) {} World::World( @@ -151,8 +150,9 @@ void World::update_marked_chunks_mesh() { for (auto chunk_pos : chunks_to_update_) { GlobalContext& context = GlobalContext::instance(); - context.submit_task([this, chunk_pos]() { this->update_single_mesh(chunk_pos); } - ); + context.submit_task([this, chunk_pos]() { + this->update_single_mesh(chunk_pos); + }); } chunks_to_update_.clear(); } @@ -231,8 +231,9 @@ World::remove_entity(std::shared_ptr entity) { } std::optional> -World::pathfind_to_object(TerrainOffset3 start_position, const std::string& object_id) - const { +World::pathfind_to_object( + TerrainOffset3 start_position, const std::string& object_id +) const { auto object = get_object_handler()->get_object(object_id); if (!object) { LOG_WARNING(logging::terrain_logger, "Object {} not found.", object_id); From 2384df54af2ed3897b60674df52d4239ddc4fe55 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Tue, 14 Apr 2026 18:01:11 -0400 Subject: [PATCH 05/25] initialize reference count to one. --- data/Base/biome_map.as | 4 ++-- src/world/terrain/generation/noise.hpp | 14 ++++++++------ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/data/Base/biome_map.as b/data/Base/biome_map.as index 029698cc..60afe402 100644 --- a/data/Base/biome_map.as +++ b/data/Base/biome_map.as @@ -55,7 +55,7 @@ class biome_map { } } else if (plant_id == "Flower_1") { - int flower_height = flower_noise.sample(x * 4, y * 4); + int flower_height = int(flower_noise.sample(x * 4, y * 4)); if (flower_height > 0) { return 0.10; } @@ -74,5 +74,5 @@ class biome_map { } void do_something() { - Base::biomes::biome_map map = Base::biomes::biome_map(); + Base::biomes::biome_map@ map = Base::biomes::biome_map(); } diff --git a/src/world/terrain/generation/noise.hpp b/src/world/terrain/generation/noise.hpp index 5fa17d5f..3fb749da 100644 --- a/src/world/terrain/generation/noise.hpp +++ b/src/world/terrain/generation/noise.hpp @@ -24,7 +24,7 @@ namespace generation { class Noise { private: - size_t ref_count; + size_t ref_count = 1; protected: // The length of Noise::primes @@ -83,14 +83,16 @@ concept NoiseGenerator = std::is_base_of::value; * @brief Generates two dimensional Perlin noise. * * @details FractalNoise generates two dimensional Perlin noise with cosine - * interpolation, and geometric persistance. The noise consists of different + * interpolation, and geometric persistence. The noise consists of different * layers. The first layer is between -1, and 1. Subsequent have twice the - * frequency, and amplitude of persistance times the previous amplitude. + * frequency, and amplitude of persistence times the previous amplitude. */ class FractalNoise : protected Noise { - int num_octaves_ = 7; - double persistence_ = 0.5; - int primeIndex_ = 0; + int num_octaves_; + double persistence_; + int primeIndex_; + + size_t ref_count = 1; public: /** From 501ce464e1ff25ea3d3cbd9f147b1e780dc2d819 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Wed, 15 Apr 2026 09:28:00 -0400 Subject: [PATCH 06/25] angelscript return types --- src/global_context.cpp | 6 ++++++ src/global_context.hpp | 3 +++ src/local_context.hpp | 21 +++++++++++++++++++++ src/util/angle_script/as_tests.cpp | 19 +++++++++++++++++++ 4 files changed, 49 insertions(+) diff --git a/src/global_context.cpp b/src/global_context.cpp index 2b17808a..6ac488a0 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -165,3 +165,9 @@ GlobalContext::get_function(std::string module, std::string function_signature) ->GetFunctionByDecl(function_signature.c_str()); return function; } + +asITypeInfo* GlobalContext::get_type(std::string module, std::string type_signature) const { + asITypeInfo* type = engine_->GetModule(module.c_str())->GetTypeInfoByDecl(type_signature.c_str()); + return type; +} + diff --git a/src/global_context.hpp b/src/global_context.hpp index 718c1cbf..e95a6810 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -177,4 +177,7 @@ class GlobalContext { // get function from module asIScriptFunction* get_function(std::string module, std::string function) const; + + // get type from module + asITypeInfo* get_type(std::string module, std::string type_signature) const; }; diff --git a/src/local_context.hpp b/src/local_context.hpp index 58b65eaa..9212a8ba 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -79,4 +79,25 @@ class LocalContext { int result = context_->Execute(); return result; } + + // this might crash. should probably do some tests + asIScriptObject* get_return_object() const { + auto out = context_->GetAddressOfReturnValue(); + if (out == nullptr){ + return nullptr; + } + return *(asIScriptObject**)out; + + } + + int + run_method(asIScriptObject* object, asIScriptFunction* function) { + context_->Prepare(function); + context_->SetObject(object); + // set args maybe + int result = context_->Execute(); + return result; + } + + }; diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angle_script/as_tests.cpp index 7bb25900..854ea534 100644 --- a/src/util/angle_script/as_tests.cpp +++ b/src/util/angle_script/as_tests.cpp @@ -86,6 +86,25 @@ as_load_tests() { return 1; } + auto type = context.get_type("Base::biomes", "biome_map"); + + auto factory_function = type->GetFactoryByDecl("biome_map @biome_map()"); + + result = local_context.run_function(factory_function); + if (result != asEXECUTION_FINISHED) { + LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); + return 1; + } + + asIScriptObject *biome_map = local_context.get_return_object(); + if (biome_map == nullptr) { + LOG_ERROR(logging::main_logger, "Failed to get object"); + return 1; + } + biome_map->AddRef(); + + asIScriptFunction* method = type->GetMethodByDecl("int sample(double, double)"); + local_context.run_function(); return 0; } From 8deeb91a4e22580ec47a83c524a984ed35a863c1 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Thu, 16 Apr 2026 16:59:01 -0400 Subject: [PATCH 07/25] angelscript logging and other tests --- CMakeLists.txt | 5 +- resources/as/test.as | 13 +++ src/global_context.cpp | 10 ++- src/global_context.hpp | 3 + src/local_context.hpp | 114 ++++++++++++++++++++++++++- src/main.cpp | 2 +- src/util/angle_script/as_logging.cpp | 92 ++++++++++++++------- src/util/angle_script/as_logging.hpp | 15 ++-- src/util/angle_script/as_tests.cpp | 87 +++++++++++++++++++- src/util/angle_script/as_tests.hpp | 2 + 10 files changed, 296 insertions(+), 47 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a81c38f0..d1ecd91f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -164,5 +164,8 @@ add_test(NAME LuaLogging COMMAND FunGame Test Lua Logging) add_test(NAME LuaLoadTime COMMAND FunGame Test Lua LoadTime) add_test(NAME LuaLoadScript COMMAND FunGame Test Lua LoadScript) add_test(NAME LuaTransferScript COMMAND FunGame Test Lua TransferScript) -add_test(NAME AngelScript COMMAND FunGame Test AngelScript) +add_test(NAME AngelScriptNap COMMAND FunGame Test AngelScript Map) +add_test(NAME AngelScriptLogging COMMAND FunGame Test AngelScript Logging) +add_test(NAME AngelScriptLoadTime COMMAND FunGame Test AngelScript LoadTime) +add_test(NAME AngelScriptLoadScript COMMAND FunGame Test AngelScript LoadScript) add_test(NAME EngineTest COMMAND FunGame Test EngineTest) diff --git a/resources/as/test.as b/resources/as/test.as index 568787bd..13010efa 100644 --- a/resources/as/test.as +++ b/resources/as/test.as @@ -9,4 +9,17 @@ int test2() { return 2; } return 1; +} + +int test3() { + LOGGING::LOG_BACKTRACE("Backtrace log 1"); + LOGGING::LOG_BACKTRACE("Backtrace log 2"); + + LOGGING::LOG_INFO("Welcome to AngelScript!"); + LOGGING::LOG_ERROR("An error message. error code 123"); + LOGGING::LOG_WARNING("A warning message."); + LOGGING::LOG_CRITICAL("A critical error."); + LOGGING::LOG_DEBUG("Debugging foo 1234"); + + return 0; } \ No newline at end of file diff --git a/src/global_context.cpp b/src/global_context.cpp index 6ac488a0..ec7b9618 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -5,23 +5,24 @@ #include "scriptstdstring.h" #include "util/files.hpp" #include "world/terrain/generation/lua_interface.hpp" +#include "util/angle_script/as_logging.hpp" // Implement a simple message callback function void MessageCallback(const asSMessageInfo* msg, void* param) { if (msg->type == asMSGTYPE_ERROR) { LOG_ERROR( - logging::lua_script_logger, "{} ({}, {}) : {}", msg->section, msg->row, + logging::lua_script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); } else if (msg->type == asMSGTYPE_WARNING) { LOG_WARNING( - logging::lua_script_logger, "{} ({}, {}) : {}", msg->section, msg->row, + logging::lua_script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); } else if (msg->type == asMSGTYPE_INFORMATION) { LOG_WARNING( - logging::lua_script_logger, "{} ({}, {}) : {}", msg->section, msg->row, + logging::lua_script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); } @@ -55,6 +56,8 @@ GlobalContext::GlobalContext() : engine_->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); RegisterStdString(engine_); terrain::generation::init_as_interface(engine_); + as_logging::init_as_interface(engine_); + } GlobalContext::~GlobalContext() { @@ -167,6 +170,7 @@ GlobalContext::get_function(std::string module, std::string function_signature) } asITypeInfo* GlobalContext::get_type(std::string module, std::string type_signature) const { + // TODO check that the module exists. In this and the above function. asITypeInfo* type = engine_->GetModule(module.c_str())->GetTypeInfoByDecl(type_signature.c_str()); return type; } diff --git a/src/global_context.hpp b/src/global_context.hpp index e95a6810..309f6b58 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -38,6 +38,9 @@ #include #include +void +MessageCallback(const asSMessageInfo* msg, void* param); + /** * @brief Any global context that are needed will go in this class. * diff --git a/src/local_context.hpp b/src/local_context.hpp index 9212a8ba..011b51f1 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -27,6 +27,7 @@ #include #include +#include #include @@ -41,6 +42,67 @@ class LocalContext { sol::object copy(sol::state& lua, const sol::object& object); + inline int set_arg(size_t i, bool arg) { + return context_->SetArgByte(i, arg); + } + + inline int set_arg(size_t i, int8_t arg) { + return context_->SetArgByte(i, arg); + } + inline int set_arg(size_t i, uint8_t arg) { + return context_->SetArgByte(i, arg); + } + inline int set_arg(size_t i, int16_t arg) { + return context_->SetArgWord(i, arg); + } + inline int set_arg(size_t i, uint16_t arg) { + return context_->SetArgWord(i, arg); + } + inline int set_arg(size_t i, int32_t arg) { + return context_->SetArgDWord(i, arg); + } + inline int set_arg(size_t i, uint32_t arg) { + return context_->SetArgDWord(i, arg); + } + inline int set_arg(size_t i, int64_t arg) { + return context_->SetArgQWord(i, arg); + } + inline int set_arg(size_t i, uint64_t arg) { + return context_->SetArgQWord(i, arg); + } + + inline int set_arg(size_t i, float arg) { + return context_->SetArgFloat(i, arg); + } + + inline int set_arg(size_t i, double arg) { + return context_->SetArgDouble(i, arg); + } + + inline int set_arg(size_t i, void* arg) { + return context_->SetArgObject(i, arg); + } + + template + inline int set_all_args(const size_t i, const A&& a) { + int result = set_arg(i, a); + if (result != 0) { + LOG_ERROR(logging::main_logger, "An error occurred {} at parameter {}", result, i); + } + return result; + } + + template + inline int set_all_args(const size_t i, const A&& a, const Args&&... args) { + int result = set_arg(i, a); + if (result != 0) { + LOG_ERROR(logging::main_logger, "An error occurred {} at parameter {}", result, i); + return result; + } + return set_all_args(i+1, std::forward(args)...); + } + + public: [[nodiscard]] static LocalContext& instance(); ~LocalContext(); @@ -75,11 +137,22 @@ class LocalContext { int run_function(asIScriptFunction* function) { context_->Prepare(function); - // set args maybe int result = context_->Execute(); return result; } + template + inline int + run_function(asIScriptFunction* function, const Args&&... args) { + context_->Prepare(function); + int result = set_all_args(0, std::forward(args)...); + if (result != 0) { + return result; + } + result = context_->Execute(); + return result; + } + // this might crash. should probably do some tests asIScriptObject* get_return_object() const { auto out = context_->GetAddressOfReturnValue(); @@ -87,17 +160,52 @@ class LocalContext { return nullptr; } return *(asIScriptObject**)out; - } int run_method(asIScriptObject* object, asIScriptFunction* function) { context_->Prepare(function); context_->SetObject(object); - // set args maybe int result = context_->Execute(); return result; } + template + inline int + run_method(asIScriptObject* object, asIScriptFunction* function, const Args&&... args) { + context_->Prepare(function); + context_->SetObject(object); + int result = set_all_args(0, std::forward(args)...); + if (result != 0) { + return result; + } + result = context_->Execute(); + return result; + } + + // TODO add a check between the return signature of the current function and + // the template type. Maybe in debug mode only +// template +// int get_return_value(T& value) { +// auto address = context_->GetReturnAddress(); + +// if (address == nullptr) { +// return -1; +// } + // good way to seg fault +// value = *((T*)address); +// return 0; +// } + +// template + int get_return_value(int& value){ + // if this is zero then could be right could be wrong. + value = context_->GetReturnDWord(); + + return 0; + } + inline int get_line_number(int stack_level, int* column, const char** section_name) const { + return context_->GetLineNumber(stack_level, column, section_name); + } }; diff --git a/src/main.cpp b/src/main.cpp index 8b276b24..195a3f97 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -449,7 +449,7 @@ as_tests(const argh::parser& cmdl) { if (run_function == "Map") { return 1; // MacroMap(cmdl); } else if (run_function == "Logging") { - return 1; // as_test::lua_log_test(); + return as_test::logging_test(); } else if (run_function == "LoadTime") { return 1; // as_test::lua_loadtime_test(); } else if (run_function == "LoadScript") { diff --git a/src/util/angle_script/as_logging.cpp b/src/util/angle_script/as_logging.cpp index f8a5aeaf..33f72829 100644 --- a/src/util/angle_script/as_logging.cpp +++ b/src/util/angle_script/as_logging.cpp @@ -7,68 +7,102 @@ namespace as_logging { -inline void -as_log_backtrace(std::string message) { - // get engine from local context - // auto& localcontext = LocalContext::instance(); - // auto engine = localcontext.as_engine(); +struct script_location { + std::string file; + int line; + int column; +}; + +script_location get_script_location() { + script_location location_data; + asIScriptContext* context = asGetActiveContext(); + if (context == nullptr) { + location_data.file = "Invoked from c++"; + location_data.line = -1; + } else { + char* section_name; + location_data.line = context->GetLineNumber(0, &location_data.column, const_cast(§ion_name)); + if (section_name == nullptr){ + location_data.file = "Unknown"; + } else { + location_data.file = std::string(section_name); + } + } + return location_data; +} - std::string file(""); - int line = 5; +void +as_log_backtrace(std::string message) { + script_location location = get_script_location(); LOG_BACKTRACE( - logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } -inline void +void as_log_info(std::string message) { - std::string file(""); - int line = 5; + script_location location = get_script_location(); LOG_INFO( - logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } -inline void -as_log_debug(std::string message) { - std::string file(""); - int line = 5; +void +as_log_debug(std::string message) { LocalContext& local_context = LocalContext::instance(); + script_location location = get_script_location(); LOG_DEBUG( - logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } -inline void +void as_log_warning(std::string message) { - std::string file(""); - int line = 5; + script_location location = get_script_location(); LOG_WARNING( - logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } -inline void +void as_log_error(std::string message) { - std::string file(""); - int line = 5; + script_location location = get_script_location(); LOG_ERROR( - logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } -inline void +void as_log_critical(std::string message) { - std::string file(""); - int line = 5; + script_location location = get_script_location(); LOG_CRITICAL( - logging::main_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", file, line), + logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } +void +init_as_interface(asIScriptEngine* engine) { + int r = engine->SetDefaultNamespace("LOGGING"); + assert(r >= 0); + + // Registering + r = engine->RegisterGlobalFunction("void LOG_BACKTRACE(string)", asFUNCTION(as_log_backtrace), asCALL_CDECL); + assert(r >= 0); + r = engine->RegisterGlobalFunction("void LOG_INFO(string)", asFUNCTION(as_log_info), asCALL_CDECL); + assert(r >= 0); + r = engine->RegisterGlobalFunction("void LOG_DEBUG(string)", asFUNCTION(as_log_debug), asCALL_CDECL); + assert(r >= 0); + r = engine->RegisterGlobalFunction("void LOG_WARNING(string)", asFUNCTION(as_log_warning), asCALL_CDECL); + assert(r >= 0); + r = engine->RegisterGlobalFunction("void LOG_ERROR(string)", asFUNCTION(as_log_error), asCALL_CDECL); + assert(r >= 0); + r = engine->RegisterGlobalFunction("void LOG_CRITICAL(string)", asFUNCTION(as_log_critical), asCALL_CDECL); + assert(r >= 0); + +} } // namespace as_logging diff --git a/src/util/angle_script/as_logging.hpp b/src/util/angle_script/as_logging.hpp index 66cf7e69..565cad80 100644 --- a/src/util/angle_script/as_logging.hpp +++ b/src/util/angle_script/as_logging.hpp @@ -4,16 +4,19 @@ namespace as_logging { -inline void as_log_backtrace(std::string message); +void as_log_backtrace(std::string message); -inline void as_log_info(std::string message); +void as_log_info(std::string message); -inline void as_log_debug(std::string message); +void as_log_debug(std::string message); -inline void as_log_warning(std::string message); +void as_log_warning(std::string message); -inline void as_log_error(std::string message); +void as_log_error(std::string message); -inline void as_log_critical(std::string message); +void as_log_critical(std::string message); + +void +init_as_interface(asIScriptEngine* engine); } // namespace as_logging diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angle_script/as_tests.cpp index 854ea534..41953195 100644 --- a/src/util/angle_script/as_tests.cpp +++ b/src/util/angle_script/as_tests.cpp @@ -3,14 +3,67 @@ #include "local_context.hpp" #include "logging.hpp" #include "util/files.hpp" +#include "as_logging.hpp" +#include "scriptstdstring.h" // hm #include namespace as_test { +int logging_test() { + as_logging::as_log_backtrace("Backtrace"); + LOG_ERROR(logging::lua_script_logger, ""); + + asIScriptEngine* engine = asCreateScriptEngine(); + engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); + RegisterStdString(engine); + as_logging::init_as_interface(engine); + + if (!engine) { + LOG_ERROR(logging::main_logger, "Could no start Angle Script engine."); + return 1; + } + + asIScriptModule* mod = engine->GetModule("test_module", asGM_CREATE_IF_NOT_EXISTS); + std::ostringstream script; + auto file = files::open_file(files::get_resources_path() / "as" / "test.as"); + if (!file) { + engine->ShutDownAndRelease(); + return 1; + } + + script << file.value().rdbuf(); + mod->AddScriptSection("test.as", script.str().c_str()); + + int result = mod->Build(); + if (result > 0) { + engine->ShutDownAndRelease(); + return 1; + } + + asIScriptFunction* funct1 = + engine->GetModule("test_module")->GetFunctionByDecl("int test3()"); + + + asIScriptContext* ctx = engine->CreateContext(); + ctx->Prepare(funct1); + // ctx->SetArgDWord(); + result = ctx->Execute(); + if (result != asEXECUTION_FINISHED) { + ctx->Release(); + engine->ShutDownAndRelease(); + return 1; + } + ctx->Release(); + engine->ShutDownAndRelease(); + return 0; +} + int test() { asIScriptEngine* engine = asCreateScriptEngine(); + engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); + if (!engine) { LOG_ERROR(logging::main_logger, "Could no start Angle Script engine."); return 1; @@ -86,9 +139,21 @@ as_load_tests() { return 1; } - auto type = context.get_type("Base::biomes", "biome_map"); + auto type = context.get_type("Base", "Base::biomes::biome_map"); + + int factory_count = type->GetFactoryCount(); + LOG_DEBUG(logging::main_logger, "Found {} factory functions", factory_count); - auto factory_function = type->GetFactoryByDecl("biome_map @biome_map()"); + auto factory_function = type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); + auto factory_function_2 = type->GetFactoryByIndex(0); + + auto declaration = factory_function_2->GetDeclaration(true, true, true); + + auto factory_function_3 = type->GetFactoryByDecl(declaration); + + LOG_DEBUG(logging::main_logger, "{}, {}, {}", factory_function != nullptr, factory_function_2 != nullptr, factory_function_3 != nullptr); + + LOG_DEBUG(logging::main_logger, "{}", declaration); result = local_context.run_function(factory_function); if (result != asEXECUTION_FINISHED) { @@ -103,8 +168,22 @@ as_load_tests() { } biome_map->AddRef(); - asIScriptFunction* method = type->GetMethodByDecl("int sample(double, double)"); - local_context.run_function(); + asIScriptFunction* method = type->GetMethodByDecl("int sample(int, int)"); + result = local_context.run_method(biome_map, method, 5, 5); + if (result != asEXECUTION_FINISHED) { + LOG_ERROR(logging::main_logger, "Failed AngelScript run sample"); + return 1; + } + + int return_value; + result = local_context.get_return_value(return_value); + if (result != 0) { + LOG_ERROR(logging::main_logger, "Failed to get result from sample. Error: {}", result); + return 1; + } + + LOG_DEBUG(logging::main_logger, "Got result {}.", return_value); + biome_map->Release(); return 0; } diff --git a/src/util/angle_script/as_tests.hpp b/src/util/angle_script/as_tests.hpp index 6daaba0d..1fce0b35 100644 --- a/src/util/angle_script/as_tests.hpp +++ b/src/util/angle_script/as_tests.hpp @@ -5,6 +5,8 @@ namespace as_test { int test(); +int logging_test(); + int as_load_tests(); } // namespace as_test From da884973ffe83c3e1b42677583f133ada00af1e7 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Thu, 16 Apr 2026 17:09:00 -0400 Subject: [PATCH 08/25] comment out angelscript code in biome map --- src/world/biome.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 666b1ef0..3acc86e0 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -91,19 +91,19 @@ Biome::Biome(biome_json_data biome_data, size_t seed) : TerrainMacroMap Biome::get_map(MacroDim size) const { - auto& global_context = GlobalContext::instance(); - auto function = global_context.get_function("base", "biome_map"); + //auto& global_context = GlobalContext::instance(); + //auto function = global_context.get_function("base", "biome_map"); - if (function == nullptr) { + //if (function == nullptr) { // log warning return - } + //} std::vector out; LocalContext& local_context = LocalContext::instance(); auto biome_map_query = local_context.get_from_lua(id_name_ + "\\biome_map"); - auto terrain_map = local_context.run_function(function); + //auto terrain_map = local_context.run_function(function); // get result From 073b13e09798038b0e0d947ccf9d84fb1ce344a7 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Thu, 16 Apr 2026 21:50:21 -0400 Subject: [PATCH 09/25] remove memory leaks from multithreading --- src/global_context.cpp | 15 ++-- src/global_context.hpp | 3 +- src/local_context.cpp | 1 + src/local_context.hpp | 115 +++++++++++++++++---------- src/main.cpp | 2 + src/util/angle_script/as_logging.cpp | 64 +++++++++------ src/util/angle_script/as_logging.hpp | 4 +- src/util/angle_script/as_tests.cpp | 48 ++++++++--- src/util/angle_script/as_tests.hpp | 2 + src/world/biome.cpp | 10 +-- 10 files changed, 171 insertions(+), 93 deletions(-) diff --git a/src/global_context.cpp b/src/global_context.cpp index ec7b9618..3af53272 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -3,9 +3,9 @@ #include "local_context.hpp" #include "logging.hpp" #include "scriptstdstring.h" +#include "util/angle_script/as_logging.hpp" #include "util/files.hpp" #include "world/terrain/generation/lua_interface.hpp" -#include "util/angle_script/as_logging.hpp" // Implement a simple message callback function void @@ -51,13 +51,13 @@ GlobalContext::run_opengl_queue() { } GlobalContext::GlobalContext() : - thread_pool_([] { quill::detail::set_thread_name("BS Thread"); }), - engine_(asCreateScriptEngine()) { + thread_pool_([] { quill::detail::set_thread_name("BS Thread"); }) { + asPrepareMultithread(); + engine_ = asCreateScriptEngine(); engine_->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); RegisterStdString(engine_); terrain::generation::init_as_interface(engine_); as_logging::init_as_interface(engine_); - } GlobalContext::~GlobalContext() { @@ -169,9 +169,10 @@ GlobalContext::get_function(std::string module, std::string function_signature) return function; } -asITypeInfo* GlobalContext::get_type(std::string module, std::string type_signature) const { +asITypeInfo* +GlobalContext::get_type(std::string module, std::string type_signature) const { // TODO check that the module exists. In this and the above function. - asITypeInfo* type = engine_->GetModule(module.c_str())->GetTypeInfoByDecl(type_signature.c_str()); + asITypeInfo* type = + engine_->GetModule(module.c_str())->GetTypeInfoByDecl(type_signature.c_str()); return type; } - diff --git a/src/global_context.hpp b/src/global_context.hpp index 309f6b58..28543878 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -38,8 +38,7 @@ #include #include -void -MessageCallback(const asSMessageInfo* msg, void* param); +void MessageCallback(const asSMessageInfo* msg, void* param); /** * @brief Any global context that are needed will go in this class. diff --git a/src/local_context.cpp b/src/local_context.cpp index 194db241..0e218e1d 100644 --- a/src/local_context.cpp +++ b/src/local_context.cpp @@ -18,6 +18,7 @@ LocalContext::LocalContext() : LocalContext::~LocalContext() { context_->Release(); + asThreadCleanup(); } LocalContext& diff --git a/src/local_context.hpp b/src/local_context.hpp index 011b51f1..860937d2 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -26,8 +26,8 @@ #pragma once #include -#include #include +#include #include @@ -42,66 +42,90 @@ class LocalContext { sol::object copy(sol::state& lua, const sol::object& object); - inline int set_arg(size_t i, bool arg) { + inline int + set_arg(size_t i, bool arg) { return context_->SetArgByte(i, arg); } - inline int set_arg(size_t i, int8_t arg) { + inline int + set_arg(size_t i, int8_t arg) { return context_->SetArgByte(i, arg); } - inline int set_arg(size_t i, uint8_t arg) { + + inline int + set_arg(size_t i, uint8_t arg) { return context_->SetArgByte(i, arg); } - inline int set_arg(size_t i, int16_t arg) { + + inline int + set_arg(size_t i, int16_t arg) { return context_->SetArgWord(i, arg); } - inline int set_arg(size_t i, uint16_t arg) { + + inline int + set_arg(size_t i, uint16_t arg) { return context_->SetArgWord(i, arg); } - inline int set_arg(size_t i, int32_t arg) { + + inline int + set_arg(size_t i, int32_t arg) { return context_->SetArgDWord(i, arg); } - inline int set_arg(size_t i, uint32_t arg) { + + inline int + set_arg(size_t i, uint32_t arg) { return context_->SetArgDWord(i, arg); } - inline int set_arg(size_t i, int64_t arg) { + + inline int + set_arg(size_t i, int64_t arg) { return context_->SetArgQWord(i, arg); } - inline int set_arg(size_t i, uint64_t arg) { + + inline int + set_arg(size_t i, uint64_t arg) { return context_->SetArgQWord(i, arg); } - inline int set_arg(size_t i, float arg) { + inline int + set_arg(size_t i, float arg) { return context_->SetArgFloat(i, arg); } - inline int set_arg(size_t i, double arg) { + inline int + set_arg(size_t i, double arg) { return context_->SetArgDouble(i, arg); } - inline int set_arg(size_t i, void* arg) { + inline int + set_arg(size_t i, void* arg) { return context_->SetArgObject(i, arg); } - template - inline int set_all_args(const size_t i, const A&& a) { + template + inline int + set_all_args(const size_t i, const A&& a) { int result = set_arg(i, a); if (result != 0) { - LOG_ERROR(logging::main_logger, "An error occurred {} at parameter {}", result, i); + LOG_ERROR( + logging::main_logger, "An error occurred {} at parameter {}", result, i + ); } return result; } - template - inline int set_all_args(const size_t i, const A&& a, const Args&&... args) { + template + inline int + set_all_args(const size_t i, const A&& a, const Args&&... args) { int result = set_arg(i, a); if (result != 0) { - LOG_ERROR(logging::main_logger, "An error occurred {} at parameter {}", result, i); + LOG_ERROR( + logging::main_logger, "An error occurred {} at parameter {}", result, i + ); return result; } - return set_all_args(i+1, std::forward(args)...); + return set_all_args(i + 1, std::forward(args)...); } - public: [[nodiscard]] static LocalContext& instance(); @@ -141,7 +165,7 @@ class LocalContext { return result; } - template + template inline int run_function(asIScriptFunction* function, const Args&&... args) { context_->Prepare(function); @@ -154,9 +178,10 @@ class LocalContext { } // this might crash. should probably do some tests - asIScriptObject* get_return_object() const { + asIScriptObject* + get_return_object() const { auto out = context_->GetAddressOfReturnValue(); - if (out == nullptr){ + if (out == nullptr) { return nullptr; } return *(asIScriptObject**)out; @@ -170,9 +195,11 @@ class LocalContext { return result; } - template + template inline int - run_method(asIScriptObject* object, asIScriptFunction* function, const Args&&... args) { + run_method( + asIScriptObject* object, asIScriptFunction* function, const Args&&... args + ) { context_->Prepare(function); context_->SetObject(object); int result = set_all_args(0, std::forward(args)...); @@ -185,27 +212,29 @@ class LocalContext { // TODO add a check between the return signature of the current function and // the template type. Maybe in debug mode only -// template -// int get_return_value(T& value) { -// auto address = context_->GetReturnAddress(); - -// if (address == nullptr) { -// return -1; -// } - // good way to seg fault -// value = *((T*)address); -// return 0; -// } - -// template - int get_return_value(int& value){ + // template + // int get_return_value(T& value) { + // auto address = context_->GetReturnAddress(); + + // if (address == nullptr) { + // return -1; + // } + // good way to seg fault + // value = *((T*)address); + // return 0; + // } + + // template + int + get_return_value(int& value) { // if this is zero then could be right could be wrong. value = context_->GetReturnDWord(); return 0; } - inline int get_line_number(int stack_level, int* column, const char** section_name) const { - return context_->GetLineNumber(stack_level, column, section_name); - } + inline int + get_line_number(int stack_level, int* column, const char** section_name) const { + return context_->GetLineNumber(stack_level, column, section_name); + } }; diff --git a/src/main.cpp b/src/main.cpp index 195a3f97..d68fd9c2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -452,6 +452,8 @@ as_tests(const argh::parser& cmdl) { return as_test::logging_test(); } else if (run_function == "LoadTime") { return 1; // as_test::lua_loadtime_test(); + } else if (run_function == "Threading") { + return as_test::as_threading(); } else if (run_function == "LoadScript") { return as_test::as_load_tests(); } else { diff --git a/src/util/angle_script/as_logging.cpp b/src/util/angle_script/as_logging.cpp index 33f72829..7ce0e9db 100644 --- a/src/util/angle_script/as_logging.cpp +++ b/src/util/angle_script/as_logging.cpp @@ -13,7 +13,8 @@ struct script_location { int column; }; -script_location get_script_location() { +script_location +get_script_location() { script_location location_data; asIScriptContext* context = asGetActiveContext(); if (context == nullptr) { @@ -21,8 +22,10 @@ script_location get_script_location() { location_data.line = -1; } else { char* section_name; - location_data.line = context->GetLineNumber(0, &location_data.column, const_cast(§ion_name)); - if (section_name == nullptr){ + location_data.line = context->GetLineNumber( + 0, &location_data.column, const_cast(§ion_name) + ); + if (section_name == nullptr) { location_data.file = "Unknown"; } else { location_data.file = std::string(section_name); @@ -35,8 +38,8 @@ void as_log_backtrace(std::string message) { script_location location = get_script_location(); LOG_BACKTRACE( - logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), - message + logging::lua_script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message ); } @@ -44,17 +47,18 @@ void as_log_info(std::string message) { script_location location = get_script_location(); LOG_INFO( - logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), - message + logging::lua_script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message ); } void -as_log_debug(std::string message) { LocalContext& local_context = LocalContext::instance(); +as_log_debug(std::string message) { + LocalContext& local_context = LocalContext::instance(); script_location location = get_script_location(); LOG_DEBUG( - logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), - message + logging::lua_script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message ); } @@ -62,8 +66,8 @@ void as_log_warning(std::string message) { script_location location = get_script_location(); LOG_WARNING( - logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), - message + logging::lua_script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message ); } @@ -71,8 +75,8 @@ void as_log_error(std::string message) { script_location location = get_script_location(); LOG_ERROR( - logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), - message + logging::lua_script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message ); } @@ -80,29 +84,41 @@ void as_log_critical(std::string message) { script_location location = get_script_location(); LOG_CRITICAL( - logging::lua_script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), - message + logging::lua_script_logger, "[{:<18}] - {}", + fmtquill::format("{}:{}", location.file, location.line), message ); } + void init_as_interface(asIScriptEngine* engine) { int r = engine->SetDefaultNamespace("LOGGING"); assert(r >= 0); - // Registering - r = engine->RegisterGlobalFunction("void LOG_BACKTRACE(string)", asFUNCTION(as_log_backtrace), asCALL_CDECL); + // Registering + r = engine->RegisterGlobalFunction( + "void LOG_BACKTRACE(string)", asFUNCTION(as_log_backtrace), asCALL_CDECL + ); assert(r >= 0); - r = engine->RegisterGlobalFunction("void LOG_INFO(string)", asFUNCTION(as_log_info), asCALL_CDECL); + r = engine->RegisterGlobalFunction( + "void LOG_INFO(string)", asFUNCTION(as_log_info), asCALL_CDECL + ); assert(r >= 0); - r = engine->RegisterGlobalFunction("void LOG_DEBUG(string)", asFUNCTION(as_log_debug), asCALL_CDECL); + r = engine->RegisterGlobalFunction( + "void LOG_DEBUG(string)", asFUNCTION(as_log_debug), asCALL_CDECL + ); assert(r >= 0); - r = engine->RegisterGlobalFunction("void LOG_WARNING(string)", asFUNCTION(as_log_warning), asCALL_CDECL); + r = engine->RegisterGlobalFunction( + "void LOG_WARNING(string)", asFUNCTION(as_log_warning), asCALL_CDECL + ); assert(r >= 0); - r = engine->RegisterGlobalFunction("void LOG_ERROR(string)", asFUNCTION(as_log_error), asCALL_CDECL); + r = engine->RegisterGlobalFunction( + "void LOG_ERROR(string)", asFUNCTION(as_log_error), asCALL_CDECL + ); assert(r >= 0); - r = engine->RegisterGlobalFunction("void LOG_CRITICAL(string)", asFUNCTION(as_log_critical), asCALL_CDECL); + r = engine->RegisterGlobalFunction( + "void LOG_CRITICAL(string)", asFUNCTION(as_log_critical), asCALL_CDECL + ); assert(r >= 0); - } } // namespace as_logging diff --git a/src/util/angle_script/as_logging.hpp b/src/util/angle_script/as_logging.hpp index 565cad80..175b6aec 100644 --- a/src/util/angle_script/as_logging.hpp +++ b/src/util/angle_script/as_logging.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include namespace as_logging { @@ -16,7 +17,6 @@ void as_log_error(std::string message); void as_log_critical(std::string message); -void -init_as_interface(asIScriptEngine* engine); +void init_as_interface(asIScriptEngine* engine); } // namespace as_logging diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angle_script/as_tests.cpp index 41953195..eef51d4e 100644 --- a/src/util/angle_script/as_tests.cpp +++ b/src/util/angle_script/as_tests.cpp @@ -1,16 +1,17 @@ +#include "as_logging.hpp" #include "global_context.hpp" #include "local_context.hpp" #include "logging.hpp" -#include "util/files.hpp" -#include "as_logging.hpp" #include "scriptstdstring.h" // hm +#include "util/files.hpp" #include namespace as_test { -int logging_test() { +int +logging_test() { as_logging::as_log_backtrace("Backtrace"); LOG_ERROR(logging::lua_script_logger, ""); @@ -44,7 +45,6 @@ int logging_test() { asIScriptFunction* funct1 = engine->GetModule("test_module")->GetFunctionByDecl("int test3()"); - asIScriptContext* ctx = engine->CreateContext(); ctx->Prepare(funct1); // ctx->SetArgDWord(); @@ -121,6 +121,28 @@ test() { return 0; } +int +as_threading() { + GlobalContext& context = GlobalContext::instance(); + + std::future future = context.submit_task([]() { + GlobalContext& context = GlobalContext::instance(); + + context.load_file("test_module", files::get_resources_path() / "as" / "test.as"); + + LocalContext& local_context = LocalContext::instance(); + + auto function = context.get_function("test_module", "int text3()"); + + int result = local_context.run_function(function); + return result; + }); + + int result = future.get(); + + return result; +} + int as_load_tests() { GlobalContext& context = GlobalContext::instance(); @@ -144,14 +166,18 @@ as_load_tests() { int factory_count = type->GetFactoryCount(); LOG_DEBUG(logging::main_logger, "Found {} factory functions", factory_count); - auto factory_function = type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); + auto factory_function = + type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); auto factory_function_2 = type->GetFactoryByIndex(0); - + auto declaration = factory_function_2->GetDeclaration(true, true, true); - + auto factory_function_3 = type->GetFactoryByDecl(declaration); - LOG_DEBUG(logging::main_logger, "{}, {}, {}", factory_function != nullptr, factory_function_2 != nullptr, factory_function_3 != nullptr); + LOG_DEBUG( + logging::main_logger, "{}, {}, {}", factory_function != nullptr, + factory_function_2 != nullptr, factory_function_3 != nullptr + ); LOG_DEBUG(logging::main_logger, "{}", declaration); @@ -161,7 +187,7 @@ as_load_tests() { return 1; } - asIScriptObject *biome_map = local_context.get_return_object(); + asIScriptObject* biome_map = local_context.get_return_object(); if (biome_map == nullptr) { LOG_ERROR(logging::main_logger, "Failed to get object"); return 1; @@ -178,7 +204,9 @@ as_load_tests() { int return_value; result = local_context.get_return_value(return_value); if (result != 0) { - LOG_ERROR(logging::main_logger, "Failed to get result from sample. Error: {}", result); + LOG_ERROR( + logging::main_logger, "Failed to get result from sample. Error: {}", result + ); return 1; } diff --git a/src/util/angle_script/as_tests.hpp b/src/util/angle_script/as_tests.hpp index 1fce0b35..b8a30417 100644 --- a/src/util/angle_script/as_tests.hpp +++ b/src/util/angle_script/as_tests.hpp @@ -7,6 +7,8 @@ int test(); int logging_test(); +int as_threading(); + int as_load_tests(); } // namespace as_test diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 3acc86e0..91f10409 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -91,11 +91,11 @@ Biome::Biome(biome_json_data biome_data, size_t seed) : TerrainMacroMap Biome::get_map(MacroDim size) const { - //auto& global_context = GlobalContext::instance(); - //auto function = global_context.get_function("base", "biome_map"); + // auto& global_context = GlobalContext::instance(); + // auto function = global_context.get_function("base", "biome_map"); - //if (function == nullptr) { - // log warning return + // if (function == nullptr) { + // log warning return //} std::vector out; @@ -103,7 +103,7 @@ Biome::get_map(MacroDim size) const { LocalContext& local_context = LocalContext::instance(); auto biome_map_query = local_context.get_from_lua(id_name_ + "\\biome_map"); - //auto terrain_map = local_context.run_function(function); + // auto terrain_map = local_context.run_function(function); // get result From 9f7b440659c562286c8611dc59cc7734241e7b45 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Thu, 16 Apr 2026 22:06:15 -0400 Subject: [PATCH 10/25] clean up --- src/util/angle_script/as_tests.cpp | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angle_script/as_tests.cpp index eef51d4e..2bd02fd0 100644 --- a/src/util/angle_script/as_tests.cpp +++ b/src/util/angle_script/as_tests.cpp @@ -10,6 +10,8 @@ namespace as_test { + // TODO want to use the engine from global context and not create our own. + int logging_test() { as_logging::as_log_backtrace("Backtrace"); @@ -124,16 +126,13 @@ test() { int as_threading() { GlobalContext& context = GlobalContext::instance(); + context.load_file("test_module", files::get_resources_path() / "as" / "test.as"); std::future future = context.submit_task([]() { GlobalContext& context = GlobalContext::instance(); - - context.load_file("test_module", files::get_resources_path() / "as" / "test.as"); - LocalContext& local_context = LocalContext::instance(); auto function = context.get_function("test_module", "int text3()"); - int result = local_context.run_function(function); return result; }); @@ -146,23 +145,19 @@ as_threading() { int as_load_tests() { GlobalContext& context = GlobalContext::instance(); + LocalContext& local_context = LocalContext::instance(); context.load_file("main", files::get_resources_path() / "as" / "test.as"); - context.load_file("Base", files::get_data_path() / "Base" / "biome_map.as"); auto function = context.get_function("Base", "void do_something()"); - - LocalContext& local_context = LocalContext::instance(); int result = local_context.run_function(function); - if (result != asEXECUTION_FINISHED) { LOG_ERROR(logging::main_logger, "Failed AngelScript Test"); return 1; } auto type = context.get_type("Base", "Base::biomes::biome_map"); - int factory_count = type->GetFactoryCount(); LOG_DEBUG(logging::main_logger, "Found {} factory functions", factory_count); From a31234f7f7f10509a9c59950f50937f77319b451 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Sat, 18 Apr 2026 10:33:21 -0400 Subject: [PATCH 11/25] angelscript map test --- src/main.cpp | 34 ++++++++++++++++++++- src/world/biome.cpp | 73 +++++++++++++++++++++++++++++++++++++++++++++ src/world/biome.hpp | 2 ++ 3 files changed, 108 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index d68fd9c2..844ae0ab 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -140,6 +140,38 @@ MacroMap(const argh::parser& cmdl) { return 0; } +int +MacroMapAS(const argh::parser& cmdl) { + std::string biome_name; + cmdl("biome-name", BIOME_BASE_NAME) >> biome_name; + size_t seed; + cmdl("seed", SEED) >> seed; + size_t size; + cmdl("size", 4) >> size; + + manifest::ObjectHandler object_handler; + object_handler.load_all_manifests(); + + terrain::generation::Biome biome(biome_name, seed); + + // test terrain generation + auto map = biome.get_map_as(size); + + assert( + map.get_width() == size && map.get_width() == size + && "Size should match the width and height." + ); + + std::vector int_map; + for (const auto& map_tile : map) { + int_map.push_back(map_tile.get_type_id()); + } + + LOG_INFO(logging::main_logger, "Map: {}", int_map); + + return 0; +} + int image_test(const argh::parser& cmdl) { if (cmdl.size() < 2) { @@ -447,7 +479,7 @@ as_tests(const argh::parser& cmdl) { std::string run_function = cmdl(3).str(); if (run_function == "Map") { - return 1; // MacroMap(cmdl); + return MacroMapAS(cmdl); } else if (run_function == "Logging") { return as_test::logging_test(); } else if (run_function == "LoadTime") { diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 91f10409..36e860fc 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -187,6 +187,79 @@ Biome::get_map(MacroDim size) const { return TerrainMacroMap(out, x_map_tiles, y_map_tiles); } +TerrainMacroMap +Biome::get_map_as(MacroDim size) const { + auto& global_context = GlobalContext::instance(); + auto& local_context = LocalContext::instance(); + + global_context.load_file("Base", files::get_data_path() / "Base" / "biome_map.as"); + + auto type = global_context.get_type("Base", "Base::biomes::biome_map"); + int factory_count = type->GetFactoryCount(); + LOG_DEBUG(logging::main_logger, "Found {} factory functions", factory_count); + + auto factory_function = + type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); + + int result = local_context.run_function(factory_function); + if (result != asEXECUTION_FINISHED) { + LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); + return {}; + } + + asIScriptObject* biome_map = local_context.get_return_object(); + if (biome_map == nullptr) { + LOG_ERROR(logging::main_logger, "Failed to get object"); + return {}; + } + biome_map->AddRef(); + + asIScriptFunction* method = type->GetMethodByDecl("int sample(int, int)"); + result = local_context.run_method(biome_map, method, 5, 5); + if (method == nullptr) { + LOG_WARNING(logging::main_logger, "Could not find biome map function."); + return {}; + } + + std::vector out; + + MacroDim x_map_tiles = size; + MacroDim y_map_tiles = size; + + out.reserve(x_map_tiles * y_map_tiles); + for (MacroDim x = 0; x < x_map_tiles; x++) { + for (MacroDim y = 0; y < y_map_tiles; y++) { + int x_copy = x; + int y_copy = y; + result = local_context.run_method(biome_map, method, std::move(x_copy), std::move(y_copy)); + if (result == asCONTEXT_NOT_PREPARED) { + LOG_ERROR(logging::main_logger, "Context not prepared"); + return {}; + } else if (result == asINVALID_ARG) { + LOG_ERROR(logging::main_logger, "To many arguments"); + return {}; + } else if (result == asINVALID_TYPE) { + LOG_ERROR(logging::main_logger, "Invalid arg type"); + return {}; + } + + int tile_id; + result = local_context.get_return_value(tile_id); + if (result !=0) { + LOG_ERROR(logging::main_logger, "Non zero return value in get map as ({})", result); + return {}; + } + + const TileType& tile_type = macro_tile_types_[tile_id]; + out.emplace_back(tile_type, seed, x, y); + } + } + + biome_map->Release(); + + return TerrainMacroMap(out, x_map_tiles, y_map_tiles); +} + const std::unordered_map Biome::get_plant_map(Dim length) const { std::unordered_map out; diff --git a/src/world/biome.hpp b/src/world/biome.hpp index 518295e0..8fdce159 100644 --- a/src/world/biome.hpp +++ b/src/world/biome.hpp @@ -156,6 +156,8 @@ class Biome { */ [[nodiscard]] TerrainMacroMap get_map(MacroDim length) const; + [[nodiscard]] TerrainMacroMap get_map_as(MacroDim length) const; + /** * @brief Get plant map * From 5388f28a5b3400d13f35f6b055927ae139d025a4 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Sat, 18 Apr 2026 12:01:30 -0400 Subject: [PATCH 12/25] Add a load time test --- resources/as/test.as | 11 +++- src/local_context.hpp | 7 ++ src/main.cpp | 2 +- src/util/angle_script/as_logging.cpp | 1 - src/util/angle_script/as_logging.hpp | 3 +- src/util/angle_script/as_tests.cpp | 99 +++++++++++++++++++++++++++- src/util/angle_script/as_tests.hpp | 3 + src/world/biome.cpp | 15 +++-- 8 files changed, 131 insertions(+), 10 deletions(-) diff --git a/resources/as/test.as b/resources/as/test.as index 13010efa..07784379 100644 --- a/resources/as/test.as +++ b/resources/as/test.as @@ -22,4 +22,13 @@ int test3() { LOGGING::LOG_DEBUG("Debugging foo 1234"); return 0; -} \ No newline at end of file +} + +bool is_prime(int N) { + for (int x = 2; x * x < N; x++) { + if (N % x == 0) { + return false; + } + } + return true; +} diff --git a/src/local_context.hpp b/src/local_context.hpp index 860937d2..8d0df271 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -233,6 +233,13 @@ class LocalContext { return 0; } + int + get_return_value(bool& value) { + // if this is zero then could be right could be wrong. + value = context_->GetReturnByte(); + return 0; + } + inline int get_line_number(int stack_level, int* column, const char** section_name) const { return context_->GetLineNumber(stack_level, column, section_name); diff --git a/src/main.cpp b/src/main.cpp index 844ae0ab..a2e75c02 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -483,7 +483,7 @@ as_tests(const argh::parser& cmdl) { } else if (run_function == "Logging") { return as_test::logging_test(); } else if (run_function == "LoadTime") { - return 1; // as_test::lua_loadtime_test(); + return as_test::as_loadtime_test(); } else if (run_function == "Threading") { return as_test::as_threading(); } else if (run_function == "LoadScript") { diff --git a/src/util/angle_script/as_logging.cpp b/src/util/angle_script/as_logging.cpp index 7ce0e9db..eb2de079 100644 --- a/src/util/angle_script/as_logging.cpp +++ b/src/util/angle_script/as_logging.cpp @@ -54,7 +54,6 @@ as_log_info(std::string message) { void as_log_debug(std::string message) { - LocalContext& local_context = LocalContext::instance(); script_location location = get_script_location(); LOG_DEBUG( logging::lua_script_logger, "[{:<18}] - {}", diff --git a/src/util/angle_script/as_logging.hpp b/src/util/angle_script/as_logging.hpp index 175b6aec..4cf6ee32 100644 --- a/src/util/angle_script/as_logging.hpp +++ b/src/util/angle_script/as_logging.hpp @@ -1,8 +1,9 @@ #pragma once -#include #include +#include + namespace as_logging { void as_log_backtrace(std::string message); diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angle_script/as_tests.cpp index 2bd02fd0..cc4b13c2 100644 --- a/src/util/angle_script/as_tests.cpp +++ b/src/util/angle_script/as_tests.cpp @@ -5,12 +5,109 @@ #include "logging.hpp" #include "scriptstdstring.h" // hm #include "util/files.hpp" +#include "util/time.hpp" #include namespace as_test { - // TODO want to use the engine from global context and not create our own. +// TODO want to use the engine from global context and not create our own. + +int +as_loadtime_test() { + LOG_INFO(logging::main_logger, "Getting Local Lua State."); + GlobalContext& context = GlobalContext::instance(); + LocalContext& local_context = LocalContext::instance(); + + { + context.load_file( + "test_module", files::get_resources_path() / "as" / "test.as" + ); + auto is_prime_function = + context.get_function("test_module", "bool is_prime(int)"); + + LOG_INFO(logging::main_logger, "Got as function, calling."); + + auto function_result = local_context.run_function(is_prime_function, 97); + + // TODO write a better error logging mechanism + if (function_result != asEXECUTION_FINISHED) { + return 1; + } + + bool is_prime_result; + local_context.get_return_value(is_prime_result); + + std::string log_value = is_prime_result ? "correct" : "incorrect"; + LOG_INFO( + logging::main_logger, "Got {} from as function. Is {} value.", + is_prime_result, log_value + ); + } + + { + std::vector load_times; + std::vector run_times; + + for (size_t y = 0; y < 100; y++) { + auto l_start = time_util::get_time_nanoseconds(); + +// context.load_file( +// "test_module", files::get_resources_path() / "as" / "test.as" +// ); + + auto is_prime_function = + context.get_function("test_module", "bool is_prime(int)"); + auto l_end = time_util::get_time_nanoseconds(); + + auto r_start = time_util::get_time_nanoseconds(); + + auto function_result = local_context.run_function(is_prime_function, 97); + + // TODO write a better error logging mechanism + if (function_result != asEXECUTION_FINISHED) { + return 1; + } + + bool is_prime_result; + local_context.get_return_value(is_prime_result); + + auto r_end = time_util::get_time_nanoseconds(); + + load_times.push_back(l_end - l_start); + + run_times.push_back(r_end - r_start); + } + + std::chrono::nanoseconds r_mean(0); + for (size_t i = 1; i < run_times.size(); i++) { + std::chrono::nanoseconds duration = run_times[i]; + r_mean += duration; + } + r_mean /= (run_times.size() - 1); + + std::chrono::nanoseconds l_mean(0); + for (size_t i = 1; i < load_times.size(); i++) { + std::chrono::nanoseconds duration = load_times[i]; + l_mean += duration; + } + l_mean /= (load_times.size() - 1); + + LOG_INFO( + logging::main_logger, + "Mean load time of {} samples is {}ns. First load time is {}ns", + (load_times.size() - 1), int64_t(l_mean.count()), load_times[0].count() + ); + + LOG_INFO( + logging::main_logger, + "Mean execution time of {} samples is {}ns. First execution time is {}ns.", + (run_times.size() - 1), int64_t(r_mean.count()), run_times[0].count() + ); + } + + return 0; +} int logging_test() { diff --git a/src/util/angle_script/as_tests.hpp b/src/util/angle_script/as_tests.hpp index b8a30417..29331c72 100644 --- a/src/util/angle_script/as_tests.hpp +++ b/src/util/angle_script/as_tests.hpp @@ -5,6 +5,9 @@ namespace as_test { int test(); +int +as_loadtime_test(); + int logging_test(); int as_threading(); diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 36e860fc..2157c31c 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -220,9 +220,9 @@ Biome::get_map_as(MacroDim size) const { LOG_WARNING(logging::main_logger, "Could not find biome map function."); return {}; } - + std::vector out; - + MacroDim x_map_tiles = size; MacroDim y_map_tiles = size; @@ -231,7 +231,9 @@ Biome::get_map_as(MacroDim size) const { for (MacroDim y = 0; y < y_map_tiles; y++) { int x_copy = x; int y_copy = y; - result = local_context.run_method(biome_map, method, std::move(x_copy), std::move(y_copy)); + result = local_context.run_method( + biome_map, method, std::move(x_copy), std::move(y_copy) + ); if (result == asCONTEXT_NOT_PREPARED) { LOG_ERROR(logging::main_logger, "Context not prepared"); return {}; @@ -245,8 +247,11 @@ Biome::get_map_as(MacroDim size) const { int tile_id; result = local_context.get_return_value(tile_id); - if (result !=0) { - LOG_ERROR(logging::main_logger, "Non zero return value in get map as ({})", result); + if (result != 0) { + LOG_ERROR( + logging::main_logger, "Non zero return value in get map as ({})", + result + ); return {}; } From 27242b0fc6af8ef4d06ad9b6ffb604e32122ee2c Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Tue, 3 Mar 2026 12:18:43 -0500 Subject: [PATCH 13/25] maybe clang 19 --- .github/workflows/build-test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 0f6c9c5b..b02444c9 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -25,7 +25,7 @@ jobs: # - macos-latest compiler: [ { cc: "gcc", cxx: "g++"}, - { cc: "clang", cxx: "clang++"} + { cc: "clang-19", cxx: "clang++-19"} ] build: - Release From 8b422f646d2218fd40eb0733f5d977ca223aac2a Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Tue, 3 Mar 2026 12:51:01 -0500 Subject: [PATCH 14/25] apt install --- .github/workflows/build-test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index b02444c9..c8c7a118 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -44,10 +44,11 @@ jobs: with: submodules: 'recursive' - - name: Install Ninja + - name: Install Ninja & Clang-19 run: | sudo apt update sudo apt install ninja-build -y + sudo apt install clang-19 -y - name: Install Dependencies run: | From bae239c599d13c9d8674c979f41ff7273769dc9f Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Sun, 19 Apr 2026 12:30:49 -0400 Subject: [PATCH 15/25] remove sol and lua --- .github/workflows/build-test.yml | 1 - .gitmodules | 3 - CMakeLists.txt | 17 +- TODO.txt | 2 + data/Base/biome_data.json | 4 +- data/Base/biomes/Test_Biome.json | 4 +- data/Base/models/Test_Entity/Test.json | 2 +- data/Base/models/Test_Entity/ai.lua | 2 + resources/lua/is_prime_test.lua | 14 - resources/lua/logging.lua | 58 --- src/global_context.cpp | 86 +---- src/global_context.hpp | 20 +- src/local_context.cpp | 213 ----------- src/local_context.hpp | 33 +- src/logging.cpp | 24 +- src/logging.hpp | 8 +- src/main.cpp | 71 +--- src/manifest/object_handler.cpp | 2 +- src/manifest/object_handler.hpp | 1 + src/util/angle_script/as_logging.cpp | 12 +- src/util/angle_script/as_math.hpp | 3 + src/util/angle_script/as_tests.cpp | 11 +- src/util/angle_script/as_tests.hpp | 3 +- src/util/lua/lua_logging.hpp | 79 ----- src/util/lua/lua_tests.cpp | 330 ------------------ src/util/lua/lua_tests.hpp | 17 - src/world/biome.cpp | 247 +++---------- src/world/biome.hpp | 11 +- src/world/object/entity/entity.cpp | 49 +-- src/world/plant.hpp | 2 +- .../{lua_interface.cpp => interface.cpp} | 82 +---- .../{lua_interface.hpp => interface.hpp} | 3 - src/world/terrain/terrain.cpp | 3 +- vendor/sol2 | 1 - 34 files changed, 149 insertions(+), 1269 deletions(-) delete mode 100644 resources/lua/is_prime_test.lua delete mode 100644 resources/lua/logging.lua create mode 100644 src/util/angle_script/as_math.hpp delete mode 100644 src/util/lua/lua_logging.hpp delete mode 100644 src/util/lua/lua_tests.cpp delete mode 100644 src/util/lua/lua_tests.hpp rename src/world/terrain/generation/{lua_interface.cpp => interface.cpp} (51%) rename src/world/terrain/generation/{lua_interface.hpp => interface.hpp} (73%) delete mode 160000 vendor/sol2 diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index c8c7a118..9d8f65f9 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -55,7 +55,6 @@ jobs: sudo apt update sudo apt install \ - lua5.3 liblua5.3-dev \ libglfw3 libglfw3-dev \ libglew-dev \ libglm-dev \ diff --git a/.gitmodules b/.gitmodules index 39929d1f..81aeff00 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,6 @@ [submodule "vendor/quill"] path = vendor/quill url = https://github.com/odygrd/quill.git -[submodule "vendor/sol2"] - path = vendor/sol2 - url = https://github.com/ThePhD/sol2.git [submodule "vendor/imgui"] path = vendor/imgui/imgui url = https://github.com/ocornut/imgui diff --git a/CMakeLists.txt b/CMakeLists.txt index d1ecd91f..393f5a83 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,7 +40,7 @@ set_property(TARGET FunGame PROPERTY C_STANDARD 17) target_compile_definitions(FunGame PUBLIC GLM_ENABLE_EXPERIMENTAL) -# compile quill and sol2 +# compile quill block() set(QUILL_BUILD_EXAMPLES OFF) set(QUILL_BUILD_TESTS OFF) @@ -50,8 +50,6 @@ block() add_subdirectory("vendor/quill") endblock() -add_subdirectory("vendor/sol2") - add_subdirectory("vendor/glaze") add_subdirectory("vendor/argh") @@ -83,18 +81,10 @@ else() target_link_libraries(FunGame PRIVATE glm::glm) endif() -# Lua 5.2 just uses the name "Lua" while 5.1, and 5.0 used "Lua51", and "Lua50" -# respectivly. -find_package(Lua REQUIRED) - -include_directories(${LUA_INCLUDE_DIR}) # add quill and sol2 target_link_libraries(FunGame PRIVATE quill::quill) -target_link_libraries_system(FunGame PRIVATE sol2::sol2) -target_link_libraries(FunGame PRIVATE ${LUA_LIBRARIES}) - target_link_libraries(FunGame PRIVATE whereami) target_link_libraries(FunGame PRIVATE dear_imgui) target_link_libraries(FunGame PRIVATE angelscript) @@ -159,11 +149,6 @@ add_test(NAME Logging COMMAND FunGame Test Logging) add_test(NAME ChunkDataTest COMMAND FunGame Test ChunkDataTest) add_test(NAME LoadManifest COMMAND FunGame Test LoadManifest) add_test(NAME PathFinderTest COMMAND FunGame Test PathFinderTest) -add_test(NAME LuaMap COMMAND FunGame Test Lua Map) -add_test(NAME LuaLogging COMMAND FunGame Test Lua Logging) -add_test(NAME LuaLoadTime COMMAND FunGame Test Lua LoadTime) -add_test(NAME LuaLoadScript COMMAND FunGame Test Lua LoadScript) -add_test(NAME LuaTransferScript COMMAND FunGame Test Lua TransferScript) add_test(NAME AngelScriptNap COMMAND FunGame Test AngelScript Map) add_test(NAME AngelScriptLogging COMMAND FunGame Test AngelScript Logging) add_test(NAME AngelScriptLoadTime COMMAND FunGame Test AngelScript LoadTime) diff --git a/TODO.txt b/TODO.txt index 323842eb..a2e8e818 100644 --- a/TODO.txt +++ b/TODO.txt @@ -18,3 +18,5 @@ GUI make trees function like entities # here same shader etc +Generally fix TODOs in the code +Want to get the correct module name for as code, and make sure modules can communicate with needed. diff --git a/data/Base/biome_data.json b/data/Base/biome_data.json index d21b9a3c..a096dab1 100644 --- a/data/Base/biome_data.json +++ b/data/Base/biome_data.json @@ -1,5 +1,5 @@ { - "map_generator_path": "./biome_map.lua", + "map_generator_path": "./biome_map.as", "image_path": "path/to/image", "description": "This is a test biome", "name": "Base", @@ -730,7 +730,7 @@ { "identification": "base/Flower_Test", "map_name": "Flower_1", - "map_generator_path": "biome_map.lua" + "map_generator_path": "biome_map.as" } ] } \ No newline at end of file diff --git a/data/Base/biomes/Test_Biome.json b/data/Base/biomes/Test_Biome.json index 0ec7d5f5..f1bc59ee 100644 --- a/data/Base/biomes/Test_Biome.json +++ b/data/Base/biomes/Test_Biome.json @@ -1,5 +1,5 @@ { - "map_generator_path": "../biome_map.lua", + "map_generator_path": "../biome_map.as", "image_path": "path/to/image", "description": "This is a test biome", "name": "Base", @@ -730,7 +730,7 @@ { "identification": "base/Flower_Test", "map_name": "Flower_1", - "map_generator_path": "../biome_map.lua" + "map_generator_path": "../biome_map.as" } ] } \ No newline at end of file diff --git a/data/Base/models/Test_Entity/Test.json b/data/Base/models/Test_Entity/Test.json index 79c5ac91..5295b6bd 100644 --- a/data/Base/models/Test_Entity/Test.json +++ b/data/Base/models/Test_Entity/Test.json @@ -17,5 +17,5 @@ } ], "listeners":"", - "ai":"ai.lua" + "ai":"ai.as" } diff --git a/data/Base/models/Test_Entity/ai.lua b/data/Base/models/Test_Entity/ai.lua index dab82bc4..c07d2ef8 100644 --- a/data/Base/models/Test_Entity/ai.lua +++ b/data/Base/models/Test_Entity/ai.lua @@ -1,3 +1,5 @@ +-- Leaving this one for now because I need it to chang to as + Base = Base or {} Base.entities = Base.entities or {} Base.entities.Test_Entity = Base.entities.Test_Entity or {} diff --git a/resources/lua/is_prime_test.lua b/resources/lua/is_prime_test.lua deleted file mode 100644 index 2d5e4f26..00000000 --- a/resources/lua/is_prime_test.lua +++ /dev/null @@ -1,14 +0,0 @@ -tests = tests or {} - -function tests.is_prime(N) - for x = 2, N^(1/2) do - if N % x == 0 then - return 0 - end - return 1 - end -end - -__ = {} -__.tests = tests -return __ diff --git a/resources/lua/logging.lua b/resources/lua/logging.lua deleted file mode 100644 index 9117312f..00000000 --- a/resources/lua/logging.lua +++ /dev/null @@ -1,58 +0,0 @@ -Logging = Logging or {} - -function Logging.LOG_BACKTRACE(message) - local info = debug.getinfo(2) - if info == nil then - lua_log_backtrace("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_backtrace(filename, info.currentline, message) - end -end - -function Logging.LOG_INFO(message) - local info = debug.getinfo(2) - if info == nil then - lua_log_info("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_info(filename, info.currentline, message) - end -end - -function Logging.LOG_DEBUG(message) - local info = debug.getinfo(2) - if info == nil then - lua_log_debug("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_debug(filename, info.currentline, message) - end -end - -function Logging.LOG_WARNING(message) - local info = debug.getinfo(2) - if info == nil then - lua_log_warning("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_warning(filename, info.currentline, message) - end -end - -function Logging.LOG_CRITICAL(message) - - local info = debug.getinfo(2) - if info == nil then - lua_log_critical("Invoked from c++", -1, message) - else - local filename = info.source:match("^.+/(.+)$") - lua_log_critical(filename, info.currentline, message) - end -end - -Logging.LOG_BACKTRACE("Finished lua logging initialization.") - -__ = {} -__.Logging = Logging -return __ \ No newline at end of file diff --git a/src/global_context.cpp b/src/global_context.cpp index 3af53272..c71466eb 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -5,24 +5,24 @@ #include "scriptstdstring.h" #include "util/angle_script/as_logging.hpp" #include "util/files.hpp" -#include "world/terrain/generation/lua_interface.hpp" +#include "world/terrain/generation/interface.hpp" // Implement a simple message callback function void MessageCallback(const asSMessageInfo* msg, void* param) { if (msg->type == asMSGTYPE_ERROR) { LOG_ERROR( - logging::lua_script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, + logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); } else if (msg->type == asMSGTYPE_WARNING) { LOG_WARNING( - logging::lua_script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, + logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); } else if (msg->type == asMSGTYPE_INFORMATION) { LOG_WARNING( - logging::lua_script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, + logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); } @@ -64,82 +64,6 @@ GlobalContext::~GlobalContext() { engine_->ShutDownAndRelease(); } -std::optional -GlobalContext::get_from_lua(const std::string& command) { - LOG_BACKTRACE(logging::lua_logger, "Attempting to index {}.", command); - - std::stringstream command_stream(command); - - std::string key; - - std::getline(command_stream, key, '\\'); - - auto raw_result = lua_.get>(key); - - if (!raw_result) { - LOG_BACKTRACE(logging::lua_logger, "{} not valid.", key); - return {}; - } - - sol::table result; - - while (std::getline(command_stream, key, '\\')) { - if (!raw_result->is()) { - LOG_BACKTRACE(logging::lua_logger, "{} not index of table.", key); - return {}; - } - result = raw_result.value(); - - if (!result.valid()) { - LOG_BACKTRACE(logging::lua_logger, "Could not find {}.", key); - return {}; - } - - if (result == sol::lua_nil) { - LOG_BACKTRACE( - logging::lua_logger, "Attempting to index {}. nil value at {}.", - command, key - ); - return {}; - } - - if (!result.is()) { - LOG_BACKTRACE( - logging::lua_logger, "Attempting to index {}. {} not index of table.", - command, key - ); - return {}; - } - - raw_result = result.get>(key); - - if (!raw_result) { - LOG_BACKTRACE(logging::lua_logger, "{} not valid.", key); - return {}; - } - } - - // a sol object - return raw_result.value(); -} - -void -GlobalContext::load_script_file(const std::filesystem::path& path) { - if (!std::filesystem::exists(path)) { - LOG_WARNING(logging::file_io_logger, "File {} does not exists.", path); - return; - } - // i think you also want this on the result valid but it might not matter - std::scoped_lock lock(global_lua_mutex_); - auto result = lua_.safe_script_file(path.lexically_normal().string()); - - if (!result.valid()) { - sol::error err = result; // who designed this? - std::string what = err.what(); - LOG_ERROR(logging::lua_logger, "{}", what); - } -} - // TODO this needs to return a status void GlobalContext::load_file(std::string module, std::filesystem::path path) { @@ -157,7 +81,7 @@ GlobalContext::load_file(std::string module, std::filesystem::path path) { int result = mod->Build(); if (result > 0) { - LOG_ERROR(logging::lua_logger, "{}", result); + LOG_ERROR(logging::as_logger, "{}", result); return; } } diff --git a/src/global_context.hpp b/src/global_context.hpp index 28543878..5280f0e9 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -28,7 +28,6 @@ #define BS_THREAD_POOL_ENABLE_PRIORITY #include #include -#include #include #include @@ -56,13 +55,9 @@ class GlobalContext { std::mutex opengl_queue_mutex; - sol::state lua_; - - std::mutex global_lua_mutex_; - asIScriptEngine* engine_; - std::mutex global_as_mutex_; + // std::mutex global_as_mutex_; #if DEBUG() @@ -110,8 +105,13 @@ class GlobalContext { return obj; } - // this must be run before exit if lua has been initialized on thread local - // + /** + * @brief Close all threads in thread pool. + * + * @details This function will close the threads in the thread pool. This + * may be necessary if things allocated in thread local memory need to be + * deallocated before things on the main thread are deallocated. + */ inline void close_threads() { thread_pool_.reset(0); @@ -165,10 +165,6 @@ class GlobalContext { // oh boy time to start wrapping tread_pool - void load_script_file(const std::filesystem::path& path); - - std::optional get_from_lua(const std::string& command); - auto as_engine() { return engine_; diff --git a/src/local_context.cpp b/src/local_context.cpp index 0e218e1d..e1f5ba35 100644 --- a/src/local_context.cpp +++ b/src/local_context.cpp @@ -1,19 +1,9 @@ #include "local_context.hpp" #include "global_context.hpp" -#include "util/lua/lua_logging.hpp" -#include "world/terrain/generation/lua_interface.hpp" - -// #include LocalContext::LocalContext() : context_(GlobalContext::instance().as_engine()->CreateContext()) { - lua_state.open_libraries(sol::lib::base); - lua_state.open_libraries(sol::lib::math); - lua_state.open_libraries(sol::lib::string); - lua_state.open_libraries(sol::lib::debug); - lua_logging::setup_lua_logging(lua_state); - terrain::generation::init_lua_interface(lua_state); } LocalContext::~LocalContext() { @@ -26,206 +16,3 @@ LocalContext::instance() { static thread_local LocalContext local_ctx; return local_ctx; } - -std::optional -LocalContext::get_from_this_lua_state(const std::string& command) { - LOG_BACKTRACE(logging::lua_logger, "Attempting to index {}.", command); - sol::state& lua = get_lua_state(); - - std::stringstream command_stream(command); - - std::string key; - - std::getline(command_stream, key, '\\'); - - auto raw_result = lua.get>(key); - - if (!raw_result) { - LOG_BACKTRACE(logging::lua_logger, "{} not valid.", key); - return {}; - } - - sol::table result; - - while (std::getline(command_stream, key, '\\')) { - if (!raw_result->is()) { - LOG_BACKTRACE(logging::lua_logger, "{} not index of table.", key); - return {}; - } - result = raw_result.value(); - - if (!result.valid()) { - LOG_BACKTRACE(logging::lua_logger, "Could not find {}.", key); - return {}; - } - - if (result == sol::lua_nil) { - LOG_BACKTRACE( - logging::lua_logger, "Attempting to index {}. nil value at {}.", - command, key - ); - return {}; - } - - if (!result.is()) { - LOG_BACKTRACE( - logging::lua_logger, "Attempting to index {}. {} not index of table.", - command, key - ); - return {}; - } - - raw_result = result.get>(key); - - if (!raw_result) { - LOG_BACKTRACE(logging::lua_logger, "{} not valid.", key); - return {}; - } - LOG_BACKTRACE(logging::lua_logger, "{} valid.", key); - } - - // a sol object - return raw_result.value(); -} - -void -LocalContext::set_to_this_lua_state( - const std::string& command, const sol::object& object -) { - if (command.length() == 0) { - LOG_WARNING(logging::lua_logger, "Cannot set table with no name."); - return; - } - LOG_BACKTRACE(logging::lua_logger, "Attempting to index {}.", command); - sol::state& lua = get_lua_state(); - - std::stringstream command_stream(command); - std::string key; - - sol::optional raw_result; - - while (std::getline(command_stream, key, '\\')) { - LOG_BACKTRACE(logging::lua_logger, "Locking up {}.", key); - // if last part of command - if (command_stream.tellg() == -1) { - if (raw_result) { - if (raw_result->is()) { - sol::table result = raw_result.value(); - result.set(key, object); - } else { - LOG_ERROR(logging::lua_logger, "Object at {} is not a table.", key); - } - - } else { - lua.set(key, object); - } - continue; - // will return here - } - if (raw_result) { - if (raw_result->is()) { - sol::table result = raw_result.value(); - raw_result = result.get>(key); - if (!raw_result) { - result.set(key, lua.create_table()); - raw_result = result.get>(key); - } - } else { - LOG_ERROR(logging::lua_logger, "Object at {} is not a table.", key); - } - } else { - raw_result = lua.get>(key); - if (!raw_result) { - lua.set(key, lua.create_table()); - raw_result = lua.get>(key); - } - } - if (!raw_result) { - LOG_ERROR(logging::lua_logger, "Could not find key {}", key); - return; - } - } -} - -bool -LocalContext::load_into_this_lua_state(const std::string& command) { - GlobalContext& context = GlobalContext::instance(); - std::optional object_result = context.get_from_lua(command); - - if (!object_result) { - LOG_WARNING(logging::lua_logger, "Command {} not found.", command); - return false; - } - - sol::object object_this_state = copy(lua_state, object_result.value()); - -#if DEBUG() - if (object_this_state.is()) { - sol::table table_copy = object_this_state; - - for (auto& [key, value] : table_copy) { - LOG_DEBUG(logging::lua_logger, "key: {}", key.as()); - } - } -#endif - - set_to_this_lua_state(command, object_this_state); - return true; -} - -sol::object -LocalContext::copy(sol::state& lua_state, const sol::object& object) { - sol::type type = object.get_type(); - switch (type) { - case sol::type::number: - { - double number = object.as(); - return sol::make_object(lua_state, number); - } - case sol::type::string: - { - std::string string = object.as(); - return sol::make_object(lua_state, string); - } - case sol::type::boolean: - { - bool b = object.as(); - return sol::make_object(lua_state, b); - } - case sol::type::table: - { - sol::table table = object.as(); - sol::table table_copy = lua_state.create_table(); - for (auto& [key, value] : table) { - table_copy.set(copy(lua_state, key), copy(lua_state, value)); - } - return table_copy; - } - case sol::type::function: - { - sol::protected_function funct = object.as(); - sol::bytecode target_bc = funct.dump(); - auto result = lua_state.load(target_bc.as_string_view()); - sol::protected_function loaded_function = result; - return loaded_function; - } - case sol::type::lua_nil: - case sol::type::none: - return {}; - default: - return {}; - } -} - -std::optional -LocalContext::get_from_lua(const std::string& command) { - std::optional in_this_state = get_from_this_lua_state(command); - if (in_this_state) { - return in_this_state; - } - bool load_secsess = load_into_this_lua_state(command); - if (!load_secsess) { - return {}; - } - return get_from_this_lua_state(command); -} diff --git a/src/local_context.hpp b/src/local_context.hpp index 8d0df271..7ca74d94 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -18,7 +18,7 @@ * * @brief Defines Local Context class * - * @details Creates a local Lua environment. Helpfull for multithreading. + * @details Creates a local environment. Helpfull for multithreading. * * @ingroup -- */ @@ -27,21 +27,15 @@ #include #include -#include #include -class asContextWrapper; - class LocalContext { private: LocalContext(); - sol::state lua_state; asIScriptContext* context_; - sol::object copy(sol::state& lua, const sol::object& object); - inline int set_arg(size_t i, bool arg) { return context_->SetArgByte(i, arg); @@ -102,6 +96,11 @@ class LocalContext { return context_->SetArgObject(i, arg); } + inline int + set_arg(size_t i, std::string arg) { + return context_->SetArgObject(i, &arg); + } + template inline int set_all_args(const size_t i, const A&& a) { @@ -131,19 +130,6 @@ class LocalContext { [[nodiscard]] static LocalContext& instance(); ~LocalContext(); - [[nodiscard]] inline sol::state& - get_lua_state() { - return lua_state; - } - - std::optional get_from_this_lua_state(const std::string& command); - - void set_to_this_lua_state(const std::string& command, const sol::object& object); - - bool load_into_this_lua_state(const std::string& command); - - std::optional get_from_lua(const std::string& command); - template std::expected run_function(asIScriptFunction* function) { @@ -240,6 +226,13 @@ class LocalContext { return 0; } + int + get_return_value(float& value) { + // if this is zero then could be right could be wrong. + value = context_->GetReturnFloat(); + return 0; + } + inline int get_line_number(int stack_level, int* column, const char** section_name) const { return context_->GetLineNumber(stack_level, column, section_name); diff --git a/src/logging.cpp b/src/logging.cpp index 275a0c99..5885b62e 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -29,11 +29,11 @@ static const std::string LOGLINE_FORMAT = #if defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__) \ || defined(QUILL_NO_THREAD_NAME_SUPPORT) -static const std::string LOGLINE_FORMAT_LUA = +static const std::string LOGLINE_FORMAT_SCRIPT = "%(time) [%(thread_id:>6)] %(log_level:<10) [%(logger:<10)] " "%(message)"; #else -static const std::string LOGLINE_FORMAT_LUA = +static const std::string LOGLINE_FORMAT_SCRIPT = "%(time) [%(thread_id:>6):%(thread_name:<16)] %(log_level:<10) " "[%(logger:<10)] %(message)"; @@ -52,8 +52,8 @@ quill::Logger* terrain_logger; // for terrain, chunk, tile class quill::Logger* game_map_logger; // for terrain generation quill::Logger* voxel_logger; // for voxel logic like mesh creation quill::Logger* file_io_logger; // for file io -quill::Logger* lua_logger; // for lua -quill::Logger* lua_script_logger; // for lua +quill::Logger* as_logger; // for AngelScript +quill::Logger* script_logger; // for scripts const static std::filesystem::path LOG_FILE = files::get_log_path() / "app.log"; @@ -127,10 +127,10 @@ init(bool console, quill::LogLevel log_level) { quill::Frontend::create_or_get_logger("voxel", file_sink, LOGLINE_FORMAT); file_io_logger = quill::Frontend::create_or_get_logger("file_io", file_sink, LOGLINE_FORMAT); - lua_logger = - quill::Frontend::create_or_get_logger("lua", file_sink, LOGLINE_FORMAT); - lua_script_logger = - quill::Frontend::create_or_get_logger("script", file_sink, LOGLINE_FORMAT_LUA); + as_logger = + quill::Frontend::create_or_get_logger("as", file_sink, LOGLINE_FORMAT); + script_logger = + quill::Frontend::create_or_get_logger("script", file_sink, LOGLINE_FORMAT_SCRIPT); main_logger->set_log_level(_LOG_LEVEL); opengl_logger->set_log_level(_LOG_LEVEL); @@ -138,8 +138,8 @@ init(bool console, quill::LogLevel log_level) { game_map_logger->set_log_level(_LOG_LEVEL); voxel_logger->set_log_level(_LOG_LEVEL); file_io_logger->set_log_level(_LOG_LEVEL); - lua_logger->set_log_level(_LOG_LEVEL); - lua_script_logger->set_log_level(_LOG_LEVEL); + as_logger->set_log_level(_LOG_LEVEL); + script_logger->set_log_level(_LOG_LEVEL); // initialize backtrace on all loggers // is there a better way? @@ -149,8 +149,8 @@ init(bool console, quill::LogLevel log_level) { game_map_logger->init_backtrace(5, quill::LogLevel::Error); voxel_logger->init_backtrace(5, quill::LogLevel::Error); file_io_logger->init_backtrace(5, quill::LogLevel::Error); - lua_logger->init_backtrace(5, quill::LogLevel::Error); - lua_script_logger->init_backtrace(5, quill::LogLevel::Error); + as_logger->init_backtrace(5, quill::LogLevel::Error); + script_logger->init_backtrace(5, quill::LogLevel::Error); LOG_INFO(main_logger, "Logging initialized!"); } diff --git a/src/logging.hpp b/src/logging.hpp index eb2ee2f8..943c9375 100644 --- a/src/logging.hpp +++ b/src/logging.hpp @@ -30,8 +30,8 @@ extern quill::Logger* terrain_logger; // for terrain, chunk, tile class extern quill::Logger* game_map_logger; // for terrain generation extern quill::Logger* voxel_logger; // for voxel logic like mesh creation extern quill::Logger* file_io_logger; // for file io -extern quill::Logger* lua_logger; // for lua logging -extern quill::Logger* lua_script_logger; // for lua logging +extern quill::Logger* as_logger; // for as logging +extern quill::Logger* script_logger; // for script logging inline void set_thread_name(std::string name) { @@ -52,8 +52,8 @@ flush() { game_map_logger->flush_log(); voxel_logger->flush_log(); file_io_logger->flush_log(); - lua_logger->flush_log(); - lua_script_logger->flush_log(); + as_logger->flush_log(); + script_logger->flush_log(); } } // namespace logging diff --git a/src/main.cpp b/src/main.cpp index a2e75c02..a782f9ba 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -11,8 +11,6 @@ #include "manifest/object_handler.hpp" #include "util/angle_script/as_tests.hpp" #include "util/files.hpp" -#include "util/lua/lua_logging.hpp" -#include "util/lua/lua_tests.hpp" #include "util/mesh.hpp" #include "util/png_image.hpp" #include "util/time.hpp" @@ -140,38 +138,6 @@ MacroMap(const argh::parser& cmdl) { return 0; } -int -MacroMapAS(const argh::parser& cmdl) { - std::string biome_name; - cmdl("biome-name", BIOME_BASE_NAME) >> biome_name; - size_t seed; - cmdl("seed", SEED) >> seed; - size_t size; - cmdl("size", 4) >> size; - - manifest::ObjectHandler object_handler; - object_handler.load_all_manifests(); - - terrain::generation::Biome biome(biome_name, seed); - - // test terrain generation - auto map = biome.get_map_as(size); - - assert( - map.get_width() == size && map.get_width() == size - && "Size should match the width and height." - ); - - std::vector int_map; - for (const auto& map_tile : map) { - int_map.push_back(map_tile.get_type_id()); - } - - LOG_INFO(logging::main_logger, "Map: {}", int_map); - - return 0; -} - int image_test(const argh::parser& cmdl) { if (cmdl.size() < 2) { @@ -435,14 +401,14 @@ LogTest() { }); LOG_INFO( - logging::lua_script_logger, - "Using Lua logger. The lua logger should not log the cpp " - "file, but instead the lua file." + logging::script_logger, + "Using script logger. The script logger should not log the cpp " + "file, but instead the script file." ); LOG_INFO( - logging::lua_script_logger, - "[{}.lua:{}] - This is what a lua log should look like.", "example_file", 37 + logging::script_logger, + "[{}.as:{}] - This is what a script log should look like.", "example_file", 37 ); future.wait(); @@ -450,26 +416,6 @@ LogTest() { return 0; } -int -lua_tests(const argh::parser& cmdl) { - std::string run_function = cmdl(3).str(); - - if (run_function == "Map") { - return MacroMap(cmdl); - } else if (run_function == "Logging") { - return util::lua_tests::lua_log_test(); - } else if (run_function == "LoadTime") { - return util::lua_tests::lua_loadtime_test(); - } else if (run_function == "LoadScript") { - return util::lua_tests::lua_load_tests(); - } else if (run_function == "TransferScript") { - return util::lua_tests::lua_transfertime_test(); - } else { - std::cout << "No known command" << std::endl; - return 1; - } -} - int as_tests(const argh::parser& cmdl) { if (cmdl.size() < 3) { @@ -479,7 +425,7 @@ as_tests(const argh::parser& cmdl) { std::string run_function = cmdl(3).str(); if (run_function == "Map") { - return MacroMapAS(cmdl); + return MacroMap(cmdl); } else if (run_function == "Logging") { return as_test::logging_test(); } else if (run_function == "LoadTime") { @@ -524,8 +470,6 @@ tests(const argh::parser& cmdl) { return object_handler.load_all_manifests(); } else if (run_function == "EngineTest") { return gui::opengl_tests(); - } else if (run_function == "Lua") { - return lua_tests(cmdl); } else if (run_function == "AngelScript") { return as_tests(cmdl); } else { @@ -545,7 +489,6 @@ main(int argc, char** argv) { "-c", "--console" // Enable console logging }); cmdl.add_param("biome-name"); - // cmdl.add_param("materials"); materials should be dictated by biome cmdl.add_params({"--imgui", "-g"}); // int seed for generation @@ -568,7 +511,7 @@ main(int argc, char** argv) { LOG_INFO(logger, "FunGame v{}.{}.{}", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); LOG_INFO(logger, "Running from {}.", files::get_root_path().string()); - // main thread for opengl and lua loading + // main thread for opengl and script loading GlobalContext& context = GlobalContext::instance(); context.set_main_thread(); diff --git a/src/manifest/object_handler.cpp b/src/manifest/object_handler.cpp index 7e79953c..58754f7a 100644 --- a/src/manifest/object_handler.cpp +++ b/src/manifest/object_handler.cpp @@ -31,7 +31,7 @@ ObjectHandler::read_biome(const descriptor_t& biome_descriptor) { std::filesystem::path path_copy = biome_descriptor.path; - context.load_script_file( + context.load_file("Base", files::get_data_path() / path_copy.remove_filename() / biome_data->map_generator_path ); diff --git a/src/manifest/object_handler.hpp b/src/manifest/object_handler.hpp index fea7715f..9fedd01d 100644 --- a/src/manifest/object_handler.hpp +++ b/src/manifest/object_handler.hpp @@ -184,6 +184,7 @@ class ObjectHandler { // iterate through objects in manifest and queue them to be loaded for (const manifest::descriptor_t& entity_data : *manifest.entities) { auto future = context.submit_task([this, entity_data]() { + // manifest.name int result = read_object(entity_data); return result; }); diff --git a/src/util/angle_script/as_logging.cpp b/src/util/angle_script/as_logging.cpp index eb2de079..03b7f836 100644 --- a/src/util/angle_script/as_logging.cpp +++ b/src/util/angle_script/as_logging.cpp @@ -38,7 +38,7 @@ void as_log_backtrace(std::string message) { script_location location = get_script_location(); LOG_BACKTRACE( - logging::lua_script_logger, "[{:<18}] - {}", + logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } @@ -47,7 +47,7 @@ void as_log_info(std::string message) { script_location location = get_script_location(); LOG_INFO( - logging::lua_script_logger, "[{:<18}] - {}", + logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } @@ -56,7 +56,7 @@ void as_log_debug(std::string message) { script_location location = get_script_location(); LOG_DEBUG( - logging::lua_script_logger, "[{:<18}] - {}", + logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } @@ -65,7 +65,7 @@ void as_log_warning(std::string message) { script_location location = get_script_location(); LOG_WARNING( - logging::lua_script_logger, "[{:<18}] - {}", + logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } @@ -74,7 +74,7 @@ void as_log_error(std::string message) { script_location location = get_script_location(); LOG_ERROR( - logging::lua_script_logger, "[{:<18}] - {}", + logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } @@ -83,7 +83,7 @@ void as_log_critical(std::string message) { script_location location = get_script_location(); LOG_CRITICAL( - logging::lua_script_logger, "[{:<18}] - {}", + logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message ); } diff --git a/src/util/angle_script/as_math.hpp b/src/util/angle_script/as_math.hpp new file mode 100644 index 00000000..b08f4ac6 --- /dev/null +++ b/src/util/angle_script/as_math.hpp @@ -0,0 +1,3 @@ +// TODO want to write math here +// There is some as math functions that need to be added, along with glm vectors +// Also want to add the array library. diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angle_script/as_tests.cpp index cc4b13c2..38968e9c 100644 --- a/src/util/angle_script/as_tests.cpp +++ b/src/util/angle_script/as_tests.cpp @@ -15,7 +15,7 @@ namespace as_test { int as_loadtime_test() { - LOG_INFO(logging::main_logger, "Getting Local Lua State."); + LOG_INFO(logging::main_logger, "Getting global and local context."); GlobalContext& context = GlobalContext::instance(); LocalContext& local_context = LocalContext::instance(); @@ -52,9 +52,10 @@ as_loadtime_test() { for (size_t y = 0; y < 100; y++) { auto l_start = time_util::get_time_nanoseconds(); -// context.load_file( -// "test_module", files::get_resources_path() / "as" / "test.as" -// ); + // context.load_file( + // "test_module", files::get_resources_path() / "as" / + // "test.as" + // ); auto is_prime_function = context.get_function("test_module", "bool is_prime(int)"); @@ -112,7 +113,7 @@ as_loadtime_test() { int logging_test() { as_logging::as_log_backtrace("Backtrace"); - LOG_ERROR(logging::lua_script_logger, ""); + LOG_ERROR(logging::script_logger, ""); asIScriptEngine* engine = asCreateScriptEngine(); engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); diff --git a/src/util/angle_script/as_tests.hpp b/src/util/angle_script/as_tests.hpp index 29331c72..6d61e53e 100644 --- a/src/util/angle_script/as_tests.hpp +++ b/src/util/angle_script/as_tests.hpp @@ -5,8 +5,7 @@ namespace as_test { int test(); -int -as_loadtime_test(); +int as_loadtime_test(); int logging_test(); diff --git a/src/util/lua/lua_logging.hpp b/src/util/lua/lua_logging.hpp deleted file mode 100644 index 07fb7529..00000000 --- a/src/util/lua/lua_logging.hpp +++ /dev/null @@ -1,79 +0,0 @@ -#pragma once - -#include "logging.hpp" -#include "util/files.hpp" - -#include -#include - -namespace lua_logging { - -inline void -lua_log_backtrace(std::string file, int line, std::string message) { - LOG_BACKTRACE( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_info(std::string file, int line, std::string message) { - LOG_INFO( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_debug(std::string file, int line, std::string message) { - LOG_DEBUG( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_warning(std::string file, int line, std::string message) { - LOG_WARNING( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_error(std::string file, int line, std::string message) { - LOG_ERROR( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -lua_log_critical(std::string file, int line, std::string message) { - LOG_CRITICAL( - logging::lua_script_logger, "[{:<18}] - {}", - fmtquill::format("{}:{}", file, line), message - ); -} - -inline void -setup_lua_logging(sol::state& lua) { - lua.set_function("lua_log_backtrace", lua_log_backtrace); - lua.set_function("lua_log_info", lua_log_info); - lua.set_function("lua_log_debug", lua_log_debug); - lua.set_function("lua_log_warning", lua_log_warning); - lua.set_function("lua_log_error", lua_log_error); - lua.set_function("lua_log_critical", lua_log_critical); - - std::filesystem::path logging_file_path = - files::get_resources_path() / "lua" / "logging.lua"; - - sol::table logging_library = - lua.require_file("Logging", logging_file_path.string(), false); - - if (!logging_library.valid()) { - LOG_WARNING(logging::main_logger, "Logging library did not load correctly."); - } -} - -} // namespace lua_logging diff --git a/src/util/lua/lua_tests.cpp b/src/util/lua/lua_tests.cpp deleted file mode 100644 index 40570259..00000000 --- a/src/util/lua/lua_tests.cpp +++ /dev/null @@ -1,330 +0,0 @@ -#include "lua_tests.hpp" - -#include "global_context.hpp" -#include "local_context.hpp" -#include "logging.hpp" -#include "util/files.hpp" -#include "util/time.hpp" - -#include - -namespace util { - -namespace lua_tests { - -int -lua_loadtime_test() { - LOG_INFO(logging::main_logger, "Getting Local Lua State."); - LocalContext& local_context = LocalContext::instance(); - sol::state& lua = local_context.get_lua_state(); - LOG_INFO(logging::main_logger, "Got Local Lua State."); - LOG_INFO(logging::main_logger, "Loading Lua File."); - - std::filesystem::path lua_script_path = - files::get_resources_path() / "lua" / "is_prime_test.lua"; - - sol::table result = - lua.require_file("is_prime_test", lua_script_path.string(), false); - - if (!result.valid()) { - LOG_WARNING(logging::main_logger, "is prime test failed to import."); - return 1; - } - - for (const auto& key : result) { - if (key.first.is()) { - std::string string_key = key.first.as(); - LOG_INFO(logging::main_logger, "{}", string_key); - } - } - - { - sol::protected_function is_prime_function = result["tests"]["is_prime"]; - - LOG_INFO(logging::main_logger, "Got Lua function, calling."); - - auto function_result = is_prime_function.call(97); - - if (!function_result.valid()) { - sol::error err = function_result; - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - return 1; - } - - int is_prime_result = function_result; - - std::string log_value = is_prime_result == 1 ? "correct" : "incorrect"; - LOG_INFO( - logging::main_logger, "Got Lua {} from Lua function. Is {} value.", - is_prime_result, log_value - ); - } - - { - std::vector load_times; - std::vector run_times; - - for (size_t y = 0; y < 100; y++) { - auto l_start = time_util::get_time_nanoseconds(); - - std::filesystem::path prime_test_file_path = - files::get_resources_path() / "lua" / "is_prime_test.lua"; - - sol::table biome_library = - lua.require_file("is_prime_test", prime_test_file_path.string(), false); - - sol::protected_function is_prime_function = - biome_library["tests"]["is_prime"]; - - auto l_end = time_util::get_time_nanoseconds(); - load_times.push_back(l_end - l_start); - - auto r_start = time_util::get_time_nanoseconds(); - - auto function_result = is_prime_function.call(97); - - if (!function_result.valid()) { - sol::error err = function_result; - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - return 1; - } - - auto r_end = time_util::get_time_nanoseconds(); - - run_times.push_back(r_end - r_start); - } - - std::chrono::nanoseconds r_mean(0); - for (size_t i = 1; i < run_times.size(); i++) { - std::chrono::nanoseconds duration = run_times[i]; - r_mean += duration; - } - r_mean /= (run_times.size() - 1); - - std::chrono::nanoseconds l_mean(0); - for (size_t i = 1; i < load_times.size(); i++) { - std::chrono::nanoseconds duration = load_times[i]; - l_mean += duration; - } - l_mean /= (load_times.size() - 1); - - LOG_INFO( - logging::main_logger, - "Mean load time of {} samples is {}ns. First load time is {}ns", - (load_times.size() - 1), int64_t(l_mean.count()), load_times[0].count() - ); - - LOG_INFO( - logging::main_logger, - "Mean execution time of {} samples is {}ns. First execution time is {}ns.", - (run_times.size() - 1), int64_t(r_mean.count()), run_times[0].count() - ); - } - - return 0; -} - -int -lua_log_test() { - LocalContext& local_context = LocalContext::instance(); - sol::state& lua = local_context.get_lua_state(); - - sol::protected_function lua_log_critical = lua["Logging"]["LOG_CRITICAL"]; - - auto result = lua_log_critical.call("Critical message from cpp!!"); - - if (!result.valid()) { - sol::error err = result; // who designed this? - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - } - - return 0; -} - -int -lua_transfertime_test() { - LOG_INFO(logging::main_logger, "Loading Lua File."); - - std::filesystem::path lua_script_path = - files::get_resources_path() / "lua" / "is_prime_test.lua"; - - GlobalContext& context = GlobalContext::instance(); - context.load_script_file(lua_script_path); - - { - std::optional result = context.get_from_lua("tests\\is_prime"); - - if (!result) { - return 1; - } - if (!result->is()) { - return 1; - } - - sol::protected_function is_prime_function = - result->as(); - - auto function_result = is_prime_function.call(97); - - if (!function_result.valid()) { - sol::error err = function_result; - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - return 1; - } - - int is_prime_result = function_result; - - std::string log_value = is_prime_result == 1 ? "correct" : "incorrect"; - LOG_INFO( - logging::main_logger, "Got Lua {} from Lua function. Is {} value.", - is_prime_result, log_value - ); - } - - std::future future_result = context.submit_task([]() { - std::vector load_times; - std::vector run_times; - - for (size_t y = 0; y < 101; y++) { - auto l_start = time_util::get_time_nanoseconds(); - - LocalContext& local_context = LocalContext::instance(); - - std::optional result = - local_context.get_from_lua("tests\\is_prime"); - - if (!result) { - LOG_CRITICAL(logging::lua_logger, "Could not find is_prime."); - return 1; - } - if (!result->is()) { - return 1; - } - - sol::protected_function is_prime_function = - result->as(); - - auto l_end = time_util::get_time_nanoseconds(); - - load_times.push_back(l_end - l_start); - - auto r_start = time_util::get_time_nanoseconds(); - - auto function_result = is_prime_function.call(97); - - if (!function_result.valid()) { - sol::error err = function_result; - std::string what = err.what(); - LOG_DEBUG(logging::main_logger, "{}", what); - return 1; - } - - auto r_end = time_util::get_time_nanoseconds(); - - run_times.push_back(r_end - r_start); - } - - std::chrono::nanoseconds r_mean(0); - for (size_t i = 1; i < run_times.size(); i++) { - std::chrono::nanoseconds duration = run_times[i]; - r_mean += duration; - } - r_mean /= (run_times.size() - 1); - - std::chrono::nanoseconds l_mean(0); - for (size_t i = 1; i < load_times.size(); i++) { - std::chrono::nanoseconds duration = load_times[i]; - l_mean += duration; - } - l_mean /= (load_times.size() - 1); - - LOG_INFO( - logging::main_logger, - "Mean load time of {} samples is {}ns. First load time is {}ns", - (load_times.size() - 1), int64_t(l_mean.count()), load_times[0].count() - ); - - LOG_INFO( - logging::main_logger, - "Mean execution time of {} samples is {}ns. First execution time is {}ns.", - (run_times.size() - 1), int64_t(r_mean.count()), run_times[0].count() - ); - - return 0; - }); - - int subprocess_status = future_result.get(); - - return subprocess_status; -} - -int -lua_load_tests() { - // load is_prime_test.lua - LOG_INFO(logging::main_logger, "Loading Lua File."); - - std::filesystem::path lua_script_path = - files::get_resources_path() / "lua" / "is_prime_test.lua"; - - GlobalContext& context = GlobalContext::instance(); - context.load_script_file(lua_script_path); - - // this should work - std::future future_1 = context.submit_task([]() { - LocalContext& local_context = LocalContext::instance(); - bool return_status = local_context.load_into_this_lua_state("tests"); - // true when no erro -> 0 (!true) - return static_cast(!return_status); - }); - - int value_1 = future_1.get(); - if (value_1 != 0) { - LOG_ERROR(logging::lua_logger, "load_into_this_lua_state failed"); - return 1; - } - - // this should also work - std::future future_2 = context.submit_task([]() { - LocalContext& local_context = LocalContext::instance(); - bool return_status = local_context.load_into_this_lua_state("tests"); - if (!return_status) { - return 1; - } - std::optional tests_table = - local_context.get_from_this_lua_state("tests"); - if (tests_table) { - if (tests_table->is()) { - sol::table tests_table_table = tests_table.value(); - for (auto& [key, value] : tests_table_table) { - LOG_INFO(logging::lua_logger, "key: {}", key.as()); - } - } - } - - std::optional is_prime_function = - local_context.get_from_this_lua_state("tests\\is_prime"); - if (!is_prime_function) { - LOG_ERROR(logging::lua_logger, "Could not load tests table."); - return 1; - } - local_context.set_to_this_lua_state( - "tests\\is_not_not_prime", is_prime_function.value() - ); - return 0; - }); - - int value_2 = future_2.get(); - if (value_2 != 0) { - LOG_ERROR(logging::lua_logger, "get from and set to this lua state failed"); - return 1; - } - return 0; -} - -} // namespace lua_tests - -} // namespace util diff --git a/src/util/lua/lua_tests.hpp b/src/util/lua/lua_tests.hpp deleted file mode 100644 index 8db67af7..00000000 --- a/src/util/lua/lua_tests.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -namespace util { - -namespace lua_tests { - -int lua_loadtime_test(); - -int lua_load_tests(); - -int lua_transfertime_test(); - -int lua_log_test(); - -} // namespace lua_tests - -} // namespace util diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 2157c31c..7e923614 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -4,7 +4,6 @@ #include "local_context.hpp" #include "logging.hpp" #include "manifest/object_handler.hpp" -#include "terrain/generation/lua_interface.hpp" #include "terrain/generation/noise.hpp" #include "terrain/generation/worley_noise.hpp" @@ -13,8 +12,6 @@ #include #pragma clang diagnostic pop -#include - #include #include #include @@ -69,7 +66,7 @@ Biome::Biome(biome_json_data biome_data, size_t seed) : materials_(init_materials_(biome_data.materials_data)), generate_plants_(biome_data.biome_data.generate_plants), grass_data_(biome_data.materials_data.at("Dirt").gradient), - lua_map_generator_file_( + map_generator_file_( files::get_data_path() / biome_data.biome_name / biome_data.biome_data.map_generator_path ), @@ -82,122 +79,21 @@ Biome::Biome(biome_json_data biome_data, size_t seed) : read_add_to_top_data_(biome_data.biome_data.layer_effects); - if (!std::filesystem::exists(lua_map_generator_file_)) [[unlikely]] { + if (!std::filesystem::exists(map_generator_file_)) [[unlikely]] { LOG_ERROR( - logging::lua_logger, "File, {}, not found", lua_map_generator_file_.string() + logging::as_logger, "File, {}, not found", map_generator_file_.string() ); } } TerrainMacroMap Biome::get_map(MacroDim size) const { - // auto& global_context = GlobalContext::instance(); - // auto function = global_context.get_function("base", "biome_map"); - - // if (function == nullptr) { - // log warning return - //} - - std::vector out; - - LocalContext& local_context = LocalContext::instance(); - auto biome_map_query = local_context.get_from_lua(id_name_ + "\\biome_map"); - - // auto terrain_map = local_context.run_function(function); - - // get result - - if (!biome_map_query) { - LOG_ERROR(logging::lua_logger, "Could not copy biome map."); - return {}; - } - if (!biome_map_query->is()) { - LOG_ERROR(logging::lua_logger, "Could not copy biome map."); - return {}; - } - - sol::table biome_map = biome_map_query.value(); - - auto biome_map_function = - biome_map.get>("map"); - - if (!biome_map_function) { - LOG_ERROR(logging::lua_logger, "map does not exists"); - return {}; - } - - sol::protected_function map_function = biome_map_function.value(); - - if (!map_function.valid()) [[unlikely]] { - LOG_ERROR(logging::lua_logger, "Function map not defined."); - return {}; - } - - auto function_output = map_function(size); - - if (!function_output.valid()) { - LOG_ERROR(logging::lua_logger, "Function result not valid."); - sol::error err = function_output; - sol::call_status status = function_output.status(); - LOG_ERROR(logging::lua_logger, "{}: {}", sol::to_string(status), err.what()); - return {}; - } - - if (!(function_output.get_type() == sol::type::table)) { - LOG_ERROR(logging::lua_logger, "Function output must be a table."); - return {}; - } - - sol::table map = function_output; - - auto tile_map_map = map["map"]; - if (!(tile_map_map.get_type() == sol::type::table)) { - LOG_ERROR(logging::lua_logger, "Invalid map"); - return {}; - } - - auto table_x_value = map["x"]; - if (!(table_x_value.get_type() == sol::type::number)) { - LOG_ERROR(logging::lua_logger, "Invalid x value"); - return {}; - } - MacroDim x_map_tiles = table_x_value; - - auto table_y_value = map["y"]; - if (!(table_y_value.get_type() == sol::type::number)) { - LOG_ERROR(logging::lua_logger, "Invalid y value"); - return {}; - } - MacroDim y_map_tiles = table_y_value; - - assert( - ((y_map_tiles == x_map_tiles) && (x_map_tiles == size)) - && "Map tile input and out put must all match" - ); - out.reserve(x_map_tiles * y_map_tiles); - for (MacroDim x = 0; x < x_map_tiles; x++) { - for (MacroDim y = 0; y < y_map_tiles; y++) { - size_t map_index = x * y_map_tiles + y; - int tile_id = tile_map_map[map_index].get_or(0); - const TileType& tile_type = macro_tile_types_[tile_id]; - out.emplace_back(tile_type, seed, x, y); - } - } - - return TerrainMacroMap(out, x_map_tiles, y_map_tiles); -} - -TerrainMacroMap -Biome::get_map_as(MacroDim size) const { auto& global_context = GlobalContext::instance(); auto& local_context = LocalContext::instance(); global_context.load_file("Base", files::get_data_path() / "Base" / "biome_map.as"); auto type = global_context.get_type("Base", "Base::biomes::biome_map"); - int factory_count = type->GetFactoryCount(); - LOG_DEBUG(logging::main_logger, "Found {} factory functions", factory_count); - auto factory_function = type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); @@ -206,7 +102,6 @@ Biome::get_map_as(MacroDim size) const { LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return {}; } - asIScriptObject* biome_map = local_context.get_return_object(); if (biome_map == nullptr) { LOG_ERROR(logging::main_logger, "Failed to get object"); @@ -269,111 +164,81 @@ const std::unordered_map Biome::get_plant_map(Dim length) const { std::unordered_map out; - LocalContext& local_context = LocalContext::instance(); - auto biome_map_query = local_context.get_from_lua(id_name_ + "\\biome_map"); - - if (!biome_map_query) { - LOG_ERROR(logging::lua_logger, "Could not copy biome map."); - return {}; - } - if (!biome_map_query->is()) { - LOG_ERROR(logging::lua_logger, "Could not copy biome map."); - return {}; - } - sol::table biome_map = biome_map_query.value(); - - auto biome_map_function = - biome_map.get>("map"); - - if (!biome_map_function) { - LOG_ERROR(logging::lua_logger, "map does not exists"); - return {}; - } - - sol::protected_function map_function = biome_map_function.value(); + auto& global_context = GlobalContext::instance(); + auto& local_context = LocalContext::instance(); - if (!map_function.valid()) [[unlikely]] { - LOG_ERROR(logging::lua_logger, "Function map not defined."); - return {}; - } + // global_context.load_file("Base", files::get_data_path() / "Base" / + // "biome_map.as"); - auto biome_plant_map_function = - biome_map.get>("plants_map"); + auto type = global_context.get_type("Base", "Base::biomes::biome_map"); + auto factory_function = + type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); - if (!biome_plant_map_function) { - LOG_ERROR(logging::lua_logger, "map does not exists"); + int result = local_context.run_function(factory_function); + if (result != asEXECUTION_FINISHED) { + LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return {}; } - - sol::protected_function plant_map = biome_plant_map_function.value(); - - if (!plant_map.valid()) { - LOG_ERROR(logging::lua_logger, "Error with plant_map in {}.", id_name_); + asIScriptObject* biome_map = local_context.get_return_object(); + if (biome_map == nullptr) { + LOG_ERROR(logging::main_logger, "Failed to get object"); return {}; } + biome_map->AddRef(); - sol::protected_function_result macro_map = map_function(length); - - if (!macro_map.valid()) { - sol::error err = macro_map; - sol::call_status status = macro_map.status(); - LOG_ERROR(logging::lua_logger, "{}: {}", sol::to_string(status), err.what()); - return {}; - } else if (macro_map.get_type() != sol::type::table) { - LOG_WARNING(logging::lua_logger, "map function result is not a table."); + asIScriptFunction* method = + type->GetMethodByDecl("float sample_plants(string, int, int)"); + result = local_context.run_method(biome_map, method, 5, 5); + if (method == nullptr) { + LOG_WARNING(logging::main_logger, "Could not find biome map function."); return {}; } - sol::table macro_map_table = macro_map; - - sol::table map = plant_map(length, macro_map_table); + for (auto& plant : generate_plants_) { + std::string plant_id = plant.identification; - MacroDim x_map_tiles = map["x"]; - MacroDim y_map_tiles = map["y"]; + std::vector plant_data; - LOG_DEBUG( - logging::lua_logger, "Input length: {}, (x, y) = ({}, {})", length, x_map_tiles, - y_map_tiles - ); - - assert( - ((y_map_tiles == x_map_tiles) && (x_map_tiles == length)) - && "Map tile input and out put must all match" - ); + MacroDim x_map_tiles = length; + MacroDim y_map_tiles = length; - auto maps = sol::table(map["map"]); - for (const auto& plant_sub_map : maps) { - std::vector type_map; - - sol::object flora_type = plant_sub_map.first; - - type_map.reserve(x_map_tiles * y_map_tiles); - - LOG_DEBUG(logging::lua_logger, "Key is {}", flora_type.as()); - - auto tile_map_map = maps[flora_type]; + out.reserve(x_map_tiles * y_map_tiles); for (MacroDim x = 0; x < x_map_tiles; x++) { for (MacroDim y = 0; y < y_map_tiles; y++) { - size_t map_index = x * y_map_tiles + y; - auto value = tile_map_map[map_index]; + int x_copy = x; + int y_copy = y; + result = local_context.run_method( + biome_map, method, &plant_id, std::move(x_copy), std::move(y_copy) + ); + if (result == asCONTEXT_NOT_PREPARED) { + LOG_ERROR(logging::main_logger, "Context not prepared"); + return {}; + } else if (result == asINVALID_ARG) { + LOG_ERROR(logging::main_logger, "To many arguments"); + return {}; + } else if (result == asINVALID_TYPE) { + LOG_ERROR(logging::main_logger, "Invalid arg type"); + return {}; + } - if (value.is()) { - type_map.emplace_back(value.get()); - } else { - LOG_ERROR(logging::lua_logger, "Value is not a float."); + float plant_probability; + result = local_context.get_return_value(plant_probability); + if (result != 0) { + LOG_ERROR( + logging::main_logger, + "Non zero return value in get map as ({})", result + ); + return {}; } + + plant_data.push_back(plant_probability); } } - - std::string type_as_string = flora_type.as(); - - out.emplace( - std::make_pair( - std::move(type_as_string), {type_map, x_map_tiles, y_map_tiles} - ) - ); + out.emplace(plant_id, PlantMap(plant_data, length, length)); } + biome_map->Release(); + return out; } diff --git a/src/world/biome.hpp b/src/world/biome.hpp index 8fdce159..96bf556b 100644 --- a/src/world/biome.hpp +++ b/src/world/biome.hpp @@ -26,8 +26,6 @@ #include "terrain/generation/terrain_map.hpp" #include "util/files.hpp" -#include - #include #include @@ -123,7 +121,7 @@ class Biome { GrassData grass_data_; - const std::filesystem::path lua_map_generator_file_; + const std::filesystem::path map_generator_file_; // display name const std::string name_; @@ -156,8 +154,6 @@ class Biome { */ [[nodiscard]] TerrainMacroMap get_map(MacroDim length) const; - [[nodiscard]] TerrainMacroMap get_map_as(MacroDim length) const; - /** * @brief Get plant map * @@ -289,9 +285,8 @@ class Biome { [[nodiscard]] std::unordered_map get_colors_inverse_map() const; - static TerrainMacroMap map_generation_test( - const std::filesystem::path& lua_map_generator_file, size_t size - ); + static TerrainMacroMap + map_generation_test(const std::filesystem::path& map_generator_file, size_t size); [[nodiscard]] static biome_json_data get_json_data(const std::filesystem::path& biome_file_folder); diff --git a/src/world/object/entity/entity.cpp b/src/world/object/entity/entity.cpp index 233ccfaf..14f64c39 100644 --- a/src/world/object/entity/entity.cpp +++ b/src/world/object/entity/entity.cpp @@ -5,8 +5,6 @@ #include "logging.hpp" #include "util/files.hpp" -#include - namespace world { namespace object { @@ -46,10 +44,9 @@ Entity::Entity( / object_path_copy.remove_filename() / object_data.ai.value(); - // load into All Lua - // need access control + // load into the angelscript engine GlobalContext& context = GlobalContext::instance(); - context.load_script_file(ai_path); + context.load_file("Base", ai_path); has_ai_ = true; } @@ -75,44 +72,16 @@ Entity::sync_data_to_gpu() { glm::vec3 Entity::decision(EntityInstance* entity_instance) { LocalContext& local_context = LocalContext::instance(); - std::optional update_function_query = - local_context.get_from_lua(identification_ + "\\update"); - if (!update_function_query) { - LOG_ERROR( - logging::lua_logger, "Could not find Update function for entity {}.", - identification_ - ); - return entity_instance->get_position(); - } else if (!update_function_query->is()) { - LOG_ERROR( - logging::lua_logger, "Update is not a function for entity {}.", - identification_ - ); - return entity_instance->get_position(); - } - sol::protected_function update_function = update_function_query.value(); - if (!update_function.valid()) { - LOG_ERROR( - logging::lua_logger, "Update function for entity {} not valid.", - identification_ - ); - return entity_instance->get_position(); - } - sol::protected_function_result result = update_function(entity_instance); + GlobalContext& global_context = GlobalContext::instance(); + // global_context.get_function(identification_, "vec3 update(Base::entity)"); + // TODO + // need to add glm vec3 to as + // and need to add the entity virtual class - if (!result.valid()) { - sol::error err = result; - sol::call_status status = result.status(); - LOG_ERROR(logging::lua_logger, "{}: {}", sol::to_string(status), err.what()); - return entity_instance->get_position(); - } + // Then call function and pass the entity instance object to it. - sol::table vector_table = result; - glm::vec3 position; - position.x = vector_table["x"]; - position.y = vector_table["y"]; - position.z = vector_table["z"]; + glm::vec3 position(0); return position; } diff --git a/src/world/plant.hpp b/src/world/plant.hpp index d7f341c7..830e3610 100644 --- a/src/world/plant.hpp +++ b/src/world/plant.hpp @@ -25,7 +25,7 @@ struct plant_t { std::string identification; // The map that generates these plants eg Trees_1 std::string map_name; - // path to lua file that contains function map_name + // path to script file that contains function map_name std::optional map_generator_path; [[nodiscard]] inline std::strong_ordering diff --git a/src/world/terrain/generation/lua_interface.cpp b/src/world/terrain/generation/interface.cpp similarity index 51% rename from src/world/terrain/generation/lua_interface.cpp rename to src/world/terrain/generation/interface.cpp index 59427301..c5eaa330 100644 --- a/src/world/terrain/generation/lua_interface.cpp +++ b/src/world/terrain/generation/interface.cpp @@ -1,91 +1,11 @@ -#include "lua_interface.hpp" +#include "interface.hpp" #include "noise.hpp" #include "worley_noise.hpp" -#include namespace terrain { namespace generation { -void -init_lua_interface(sol::state& lua) { - lua.new_usertype( - "FractalNoise", sol::meta_function::construct, - sol::factories( - // FractalNoise.new(...) -- dot syntax, no "self" value - // passed in - [](int num_octaves, double persistence, int prime_index) { - return std::make_shared( - num_octaves, persistence, prime_index - ); - }, - // FractalNoise:new(...) -- colon syntax, passes in the - // "self" value as first argument implicitly - [](sol::object, int num_octaves, double persistence, int prime_index) { - return std::make_shared( - num_octaves, persistence, prime_index - ); - } - ), - // FractalNoise(...) syntax, only - sol::call_constructor, - sol::factories([](int num_octaves, double persistence, int prime_index) { - return std::make_shared( - num_octaves, persistence, prime_index - ); - }), - "sample", &FractalNoise::get_noise - ); - - lua.new_usertype( - "WorleyNoise", sol::meta_function::construct, - sol::factories( - // WorleyNoise.new(...) -- dot syntax, no "self" value - // passed in - [](int tile_size, double radius) { - return std::make_shared(tile_size, radius); - }, - // WorleyNoise:new(...) -- colon syntax, passes in the - // "self" value as first argument implicitly - [](sol::object, int tile_size, double radius) { - return std::make_shared(tile_size, radius); - } - ), - // WorleyNoise(...) syntax, only - sol::call_constructor, sol::factories([](int tile_size, double radius) { - return std::make_shared(tile_size, radius); - }), - "sample", &WorleyNoise::get_noise - ); - - lua.new_usertype( - "AlternativeWorleyNoise", sol::meta_function::construct, - sol::factories( - // AlternativeWorleyNoise.new(...) -- dot syntax, no "self" value - // passed in - [](int tile_size, double positive_chance, double radius) { - return std::make_shared( - tile_size, positive_chance, radius - ); - }, - // AlternativeWorleyNoise:new(...) -- colon syntax, passes in the - // "self" value as first argument implicitly - [](sol::object, int tile_size, double positive_chance, double radius) { - return std::make_shared( - tile_size, positive_chance, radius - ); - } - ), - // AlternativeWorleyNoise(...) syntax, only - sol::call_constructor, - sol::factories([](int tile_size, double positive_chance, double radius) { - return std::make_shared( - tile_size, positive_chance, radius - ); - }), - "sample", &AlternativeWorleyNoise::get_noise - ); -} FractalNoise* FractalNoise_factory(int x, double y, int z) { diff --git a/src/world/terrain/generation/lua_interface.hpp b/src/world/terrain/generation/interface.hpp similarity index 73% rename from src/world/terrain/generation/lua_interface.hpp rename to src/world/terrain/generation/interface.hpp index b15925e0..54273e1b 100644 --- a/src/world/terrain/generation/lua_interface.hpp +++ b/src/world/terrain/generation/interface.hpp @@ -1,14 +1,11 @@ #pragma once #include -#include namespace terrain { namespace generation { -void init_lua_interface(sol::state& lua); - void init_as_interface(asIScriptEngine* engine); } // namespace generation diff --git a/src/world/terrain/terrain.cpp b/src/world/terrain/terrain.cpp index 288d981b..d36f7b5f 100644 --- a/src/world/terrain/terrain.cpp +++ b/src/world/terrain/terrain.cpp @@ -550,7 +550,8 @@ Terrain::natural_color( ) const { auto mat_id = mat->material_id; if (mat_id == DIRT_ID) { // being set to dirt - // adds striations to the dirt. (This should be done by lua in the future) + // adds striations to the dirt. (This should be done by angelscript in the + // future) color_id = (xyz.z + (xyz.x / 16 + xyz.y / 16) % 2) / 3 % 2 + NUM_GRASS; } diff --git a/vendor/sol2 b/vendor/sol2 deleted file mode 160000 index 9c882a28..00000000 --- a/vendor/sol2 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9c882a28fdb6f4ad79a53a4191b43ce48a661175 From 70ef9aaed4ed26fd2b2de782330e97ce5c6bc15e Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Sat, 25 Apr 2026 12:03:29 -0400 Subject: [PATCH 16/25] use plant map name for map --- src/world/biome.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 7e923614..c129fc0f 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -195,7 +195,7 @@ Biome::get_plant_map(Dim length) const { } for (auto& plant : generate_plants_) { - std::string plant_id = plant.identification; + std::string plant_map_name = plant.map_name; std::vector plant_data; @@ -208,7 +208,7 @@ Biome::get_plant_map(Dim length) const { int x_copy = x; int y_copy = y; result = local_context.run_method( - biome_map, method, &plant_id, std::move(x_copy), std::move(y_copy) + biome_map, method, &plant_map_name, std::move(x_copy), std::move(y_copy) ); if (result == asCONTEXT_NOT_PREPARED) { LOG_ERROR(logging::main_logger, "Context not prepared"); @@ -234,7 +234,7 @@ Biome::get_plant_map(Dim length) const { plant_data.push_back(plant_probability); } } - out.emplace(plant_id, PlantMap(plant_data, length, length)); + out.emplace(plant_map_name, PlantMap(plant_data, length, length)); } biome_map->Release(); From 97e2d746685e3dbe40ae66cf0ae2ad7d8d8e7bf1 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Mon, 27 Apr 2026 14:28:49 -0400 Subject: [PATCH 17/25] formatting documentations and include --- src/global_context.hpp | 2 +- src/local_context.cpp | 3 +- src/logging.cpp | 18 +++--- src/logging.hpp | 16 ++--- src/main.cpp | 8 --- src/manifest/object_handler.cpp | 6 +- src/util/angle_script/as_logging.hpp | 75 ++++++++++++++++++++++ src/util/angle_script/as_tests.hpp | 21 ++++++ src/util/image.hpp | 22 +++++++ src/util/mesh.hpp | 2 - src/world/biome.cpp | 8 +-- src/world/biome.hpp | 1 - src/world/terrain/generation/interface.cpp | 1 - src/world/world.cpp | 12 ++-- src/world/world.hpp | 3 +- 15 files changed, 149 insertions(+), 49 deletions(-) diff --git a/src/global_context.hpp b/src/global_context.hpp index 5280f0e9..11e20bf1 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -107,7 +107,7 @@ class GlobalContext { /** * @brief Close all threads in thread pool. - * + * * @details This function will close the threads in the thread pool. This * may be necessary if things allocated in thread local memory need to be * deallocated before things on the main thread are deallocated. diff --git a/src/local_context.cpp b/src/local_context.cpp index e1f5ba35..c7eb639a 100644 --- a/src/local_context.cpp +++ b/src/local_context.cpp @@ -3,8 +3,7 @@ #include "global_context.hpp" LocalContext::LocalContext() : - context_(GlobalContext::instance().as_engine()->CreateContext()) { -} + context_(GlobalContext::instance().as_engine()->CreateContext()) {} LocalContext::~LocalContext() { context_->Release(); diff --git a/src/logging.cpp b/src/logging.cpp index 5885b62e..87c901db 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -46,14 +46,14 @@ using cc = quill::ConsoleColours; LogLevel _LOG_LEVEL; -quill::Logger* main_logger; // for everything else -quill::Logger* opengl_logger; // for glfw, glew etc -quill::Logger* terrain_logger; // for terrain, chunk, tile class -quill::Logger* game_map_logger; // for terrain generation -quill::Logger* voxel_logger; // for voxel logic like mesh creation -quill::Logger* file_io_logger; // for file io -quill::Logger* as_logger; // for AngelScript -quill::Logger* script_logger; // for scripts +quill::Logger* main_logger; // for everything else +quill::Logger* opengl_logger; // for glfw, glew etc +quill::Logger* terrain_logger; // for terrain, chunk, tile class +quill::Logger* game_map_logger; // for terrain generation +quill::Logger* voxel_logger; // for voxel logic like mesh creation +quill::Logger* file_io_logger; // for file io +quill::Logger* as_logger; // for AngelScript +quill::Logger* script_logger; // for scripts const static std::filesystem::path LOG_FILE = files::get_log_path() / "app.log"; @@ -115,6 +115,7 @@ init(bool console, quill::LogLevel log_level) { #endif // create all loggers + // clang-format off main_logger = quill::Frontend::create_or_get_logger("main", file_sink, LOGLINE_FORMAT); opengl_logger = @@ -131,6 +132,7 @@ init(bool console, quill::LogLevel log_level) { quill::Frontend::create_or_get_logger("as", file_sink, LOGLINE_FORMAT); script_logger = quill::Frontend::create_or_get_logger("script", file_sink, LOGLINE_FORMAT_SCRIPT); + // clang-format on main_logger->set_log_level(_LOG_LEVEL); opengl_logger->set_log_level(_LOG_LEVEL); diff --git a/src/logging.hpp b/src/logging.hpp index 943c9375..eb83bacd 100644 --- a/src/logging.hpp +++ b/src/logging.hpp @@ -24,14 +24,14 @@ static constexpr quill::LogLevel DEFAULT_LOG_LEVEL = quill::LogLevel::Info; extern quill::LogLevel _LOG_LEVEL; -extern quill::Logger* main_logger; // for general logging -extern quill::Logger* opengl_logger; // for glfw, glew etc -extern quill::Logger* terrain_logger; // for terrain, chunk, tile class -extern quill::Logger* game_map_logger; // for terrain generation -extern quill::Logger* voxel_logger; // for voxel logic like mesh creation -extern quill::Logger* file_io_logger; // for file io -extern quill::Logger* as_logger; // for as logging -extern quill::Logger* script_logger; // for script logging +extern quill::Logger* main_logger; // for general logging +extern quill::Logger* opengl_logger; // for glfw, glew etc +extern quill::Logger* terrain_logger; // for terrain, chunk, tile class +extern quill::Logger* game_map_logger; // for terrain generation +extern quill::Logger* voxel_logger; // for voxel logic like mesh creation +extern quill::Logger* file_io_logger; // for file io +extern quill::Logger* as_logger; // for as logging +extern quill::Logger* script_logger; // for script logging inline void set_thread_name(std::string name) { diff --git a/src/main.cpp b/src/main.cpp index a782f9ba..dd5bdd08 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,20 +1,13 @@ #include "config.h" #include "graphics_main.hpp" -#include "gui/render/graphics_shaders/program_handler.hpp" -#include "gui/scene/controls.hpp" #include "gui/tests.hpp" -#include "gui/ui/gui_test.hpp" #include "gui/ui/imgui_gui.hpp" -#include "gui/ui/opengl_gui.hpp" -#include "local_context.hpp" #include "logging.hpp" #include "manifest/object_handler.hpp" #include "util/angle_script/as_tests.hpp" #include "util/files.hpp" -#include "util/mesh.hpp" #include "util/png_image.hpp" #include "util/time.hpp" -#include "util/voxel_io.hpp" #include "world/biome.hpp" #include "world/terrain/generation/terrain_map.hpp" #include "world/terrain/terrain.hpp" @@ -38,7 +31,6 @@ #include #include -#include #include #include diff --git a/src/manifest/object_handler.cpp b/src/manifest/object_handler.cpp index 58754f7a..975d1fad 100644 --- a/src/manifest/object_handler.cpp +++ b/src/manifest/object_handler.cpp @@ -31,9 +31,9 @@ ObjectHandler::read_biome(const descriptor_t& biome_descriptor) { std::filesystem::path path_copy = biome_descriptor.path; - context.load_file("Base", - files::get_data_path() / path_copy.remove_filename() - / biome_data->map_generator_path + context.load_file( + "Base", files::get_data_path() / path_copy.remove_filename() + / biome_data->map_generator_path ); } diff --git a/src/util/angle_script/as_logging.hpp b/src/util/angle_script/as_logging.hpp index 4cf6ee32..44d39fff 100644 --- a/src/util/angle_script/as_logging.hpp +++ b/src/util/angle_script/as_logging.hpp @@ -1,3 +1,25 @@ +// -*- lsst-c++ -*- +/* + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +/** + * @file as_logging.hpp + * + * @author @AlemSnyder + * + * @brief Defines functions that initialize AngelScript logging + * + */ + #pragma once #include @@ -6,18 +28,71 @@ namespace as_logging { +/** + * @brief Backtrace Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_backtrace(std::string message); +/** + * @brief Info Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_info(std::string message); +/** + * @brief Debug Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_debug(std::string message); +/** + * @brief Warning Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_warning(std::string message); +/** + * @brief Error Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_error(std::string message); +/** + * @brief Critical Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_critical(std::string message); +/** + * @brief Initialize Logging interface on given engine + * + * @param asIScriptEngine* engine the engine logging will be initialized on. + */ void init_as_interface(asIScriptEngine* engine); } // namespace as_logging diff --git a/src/util/angle_script/as_tests.hpp b/src/util/angle_script/as_tests.hpp index 6d61e53e..7b8bc218 100644 --- a/src/util/angle_script/as_tests.hpp +++ b/src/util/angle_script/as_tests.hpp @@ -1,3 +1,24 @@ +// -*- lsst-c++ -*- +/* + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +/** + * @file as_tests.hpp + * + * @author @AlemSnyder + * + * @brief Define AngelScript Tests + * + */ #pragma once diff --git a/src/util/image.hpp b/src/util/image.hpp index 78556f94..fcf6d6a4 100644 --- a/src/util/image.hpp +++ b/src/util/image.hpp @@ -1,3 +1,25 @@ +// -*- lsst-c++ -*- +/* + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +/** + * @file image.hpp + * + * @author @AlemSnyder + * + * @brief Defines Image Templates and Classes + * + */ + #pragma once #include "types.hpp" diff --git a/src/util/mesh.hpp b/src/util/mesh.hpp index ff3dbf27..3a9182cf 100644 --- a/src/util/mesh.hpp +++ b/src/util/mesh.hpp @@ -15,8 +15,6 @@ * * @brief Defines Mesh Class * - * @ingroup ENTITY - * */ #pragma once diff --git a/src/world/biome.cpp b/src/world/biome.cpp index c129fc0f..f9271132 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -3,9 +3,7 @@ #include "global_context.hpp" #include "local_context.hpp" #include "logging.hpp" -#include "manifest/object_handler.hpp" -#include "terrain/generation/noise.hpp" -#include "terrain/generation/worley_noise.hpp" +#include "util/files.hpp" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmissing-braces" @@ -13,7 +11,6 @@ #pragma clang diagnostic pop #include -#include #include #include #include @@ -208,7 +205,8 @@ Biome::get_plant_map(Dim length) const { int x_copy = x; int y_copy = y; result = local_context.run_method( - biome_map, method, &plant_map_name, std::move(x_copy), std::move(y_copy) + biome_map, method, &plant_map_name, std::move(x_copy), + std::move(y_copy) ); if (result == asCONTEXT_NOT_PREPARED) { LOG_ERROR(logging::main_logger, "Context not prepared"); diff --git a/src/world/biome.hpp b/src/world/biome.hpp index 96bf556b..c20305c6 100644 --- a/src/world/biome.hpp +++ b/src/world/biome.hpp @@ -24,7 +24,6 @@ #include "terrain/generation/land_generator.hpp" #include "terrain/generation/map_tile.hpp" #include "terrain/generation/terrain_map.hpp" -#include "util/files.hpp" #include #include diff --git a/src/world/terrain/generation/interface.cpp b/src/world/terrain/generation/interface.cpp index c5eaa330..b435724a 100644 --- a/src/world/terrain/generation/interface.cpp +++ b/src/world/terrain/generation/interface.cpp @@ -3,7 +3,6 @@ #include "noise.hpp" #include "worley_noise.hpp" - namespace terrain { namespace generation { diff --git a/src/world/world.cpp b/src/world/world.cpp index 4d39ef0a..e7f74f4d 100644 --- a/src/world/world.cpp +++ b/src/world/world.cpp @@ -22,19 +22,15 @@ #include "world.hpp" -#include "glm/gtx/transform.hpp" #include "global_context.hpp" #include "logging.hpp" #include "manifest/object_handler.hpp" -#include "object/entity/tile_object.hpp" #include "terrain/generation/map_tile.hpp" #include "terrain/material.hpp" #include "terrain/terrain.hpp" -#include "util/files.hpp" #include "util/mesh.hpp" #include -#include #include #include @@ -56,10 +52,10 @@ World::World( manifest::ObjectHandler* object_handler, const std::string& biome_name, MacroDim x_tiles, MacroDim y_tiles, size_t seed ) : - biome_(biome_name, seed), terrain_main_( - x_tiles, y_tiles, macro_tile_size, height, biome_, - std::move(biome_.get_map(x_tiles)) - ), + biome_(biome_name, seed), + terrain_main_( + x_tiles, y_tiles, macro_tile_size, height, biome_, biome_.get_map(x_tiles) + ), controller_(object_handler) {} World::World( diff --git a/src/world/world.hpp b/src/world/world.hpp index e749c16f..45242de9 100644 --- a/src/world/world.hpp +++ b/src/world/world.hpp @@ -26,7 +26,6 @@ #include "gui/render/structures/terrain_mesh.hpp" #include "manifest/object_handler.hpp" #include "object/entity/entity.hpp" -#include "object/entity/tile_object.hpp" #include "object/entity_controller.hpp" #include "terrain/material.hpp" #include "terrain/terrain.hpp" @@ -99,7 +98,7 @@ class World { /** * @brief Get object handler */ - const auto + auto get_object_handler() const { return controller_.get_object_handler(); } From b7c8f9c95c51315f85163bfa2fbedbacb009f0da Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Wed, 6 May 2026 22:30:54 -0400 Subject: [PATCH 18/25] suggested changes --- src/global_context.cpp | 33 ++++++++++++------- src/global_context.hpp | 6 ++-- src/local_context.hpp | 9 +---- src/main.cpp | 2 +- .../as_logging.cpp | 18 +++++----- .../as_logging.hpp | 0 .../as_math.hpp | 0 .../as_tests.cpp | 0 .../as_tests.hpp | 0 src/world/biome.cpp | 6 ++-- src/world/terrain/generation/interface.cpp | 4 +++ 11 files changed, 43 insertions(+), 35 deletions(-) rename src/util/{angle_script => angel_script}/as_logging.cpp (87%) rename src/util/{angle_script => angel_script}/as_logging.hpp (100%) rename src/util/{angle_script => angel_script}/as_math.hpp (100%) rename src/util/{angle_script => angel_script}/as_tests.cpp (100%) rename src/util/{angle_script => angel_script}/as_tests.hpp (100%) diff --git a/src/global_context.cpp b/src/global_context.cpp index c71466eb..66623184 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -3,7 +3,7 @@ #include "local_context.hpp" #include "logging.hpp" #include "scriptstdstring.h" -#include "util/angle_script/as_logging.hpp" +#include "util/angel_script/as_logging.hpp" #include "util/files.hpp" #include "world/terrain/generation/interface.hpp" @@ -21,10 +21,14 @@ MessageCallback(const asSMessageInfo* msg, void* param) { msg->col, msg->message ); } else if (msg->type == asMSGTYPE_INFORMATION) { - LOG_WARNING( + LOG_INFO( logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); + } else { + LOG_ERROR( + logging::script_logger, "Unknown message type." + ); } } @@ -66,9 +70,9 @@ GlobalContext::~GlobalContext() { // TODO this needs to return a status void -GlobalContext::load_file(std::string module, std::filesystem::path path) { +GlobalContext::load_file(const std::string& mod_name, std::filesystem::path path) { asIScriptModule* mod = - engine_->GetModule(module.c_str(), asGM_CREATE_IF_NOT_EXISTS); + engine_->GetModule(mod_name.c_str(), asGM_CREATE_IF_NOT_EXISTS); std::ostringstream script; auto file = files::open_file(path); @@ -87,16 +91,23 @@ GlobalContext::load_file(std::string module, std::filesystem::path path) { } asIScriptFunction* -GlobalContext::get_function(std::string module, std::string function_signature) const { - asIScriptFunction* function = engine_->GetModule(module.c_str()) - ->GetFunctionByDecl(function_signature.c_str()); +GlobalContext::get_function(const std::string& module, std::string function_signature) const { + // check that the module exists. + asIScriptModule* mod; + if ((mod = engine_->GetModule(module.c_str())) == nullptr) { + return nullptr; + } + asIScriptFunction* function = mod->GetFunctionByDecl(function_signature.c_str()); return function; } asITypeInfo* -GlobalContext::get_type(std::string module, std::string type_signature) const { - // TODO check that the module exists. In this and the above function. - asITypeInfo* type = - engine_->GetModule(module.c_str())->GetTypeInfoByDecl(type_signature.c_str()); +GlobalContext::get_type(const std::string& module, std::string type_signature) const { + // check that the module exists. + asIScriptModule* mod; + if ((mod = engine_->GetModule(module.c_str())) == nullptr) { + return nullptr; + } + asITypeInfo* type = mod->GetTypeInfoByDecl(type_signature.c_str()); return type; } diff --git a/src/global_context.hpp b/src/global_context.hpp index 11e20bf1..c298cbe8 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -171,11 +171,11 @@ class GlobalContext { } // load as script file - void load_file(std::string module, std::filesystem::path path); + void load_file(const std::string& module, std::filesystem::path path); // get function from module - asIScriptFunction* get_function(std::string module, std::string function) const; + asIScriptFunction* get_function(const std::string& module, std::string function) const; // get type from module - asITypeInfo* get_type(std::string module, std::string type_signature) const; + asITypeInfo* get_type(const std::string& module, std::string type_signature) const; }; diff --git a/src/local_context.hpp b/src/local_context.hpp index 7ca74d94..bf316db3 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -131,7 +131,7 @@ class LocalContext { ~LocalContext(); template - std::expected + inline std::expected run_function(asIScriptFunction* function) { context_->Prepare(function); // set args maybe @@ -144,13 +144,6 @@ class LocalContext { return object; } - int - run_function(asIScriptFunction* function) { - context_->Prepare(function); - int result = context_->Execute(); - return result; - } - template inline int run_function(asIScriptFunction* function, const Args&&... args) { diff --git a/src/main.cpp b/src/main.cpp index dd5bdd08..2f0ae451 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,7 +4,7 @@ #include "gui/ui/imgui_gui.hpp" #include "logging.hpp" #include "manifest/object_handler.hpp" -#include "util/angle_script/as_tests.hpp" +#include "util/angel_script/as_tests.hpp" #include "util/files.hpp" #include "util/png_image.hpp" #include "util/time.hpp" diff --git a/src/util/angle_script/as_logging.cpp b/src/util/angel_script/as_logging.cpp similarity index 87% rename from src/util/angle_script/as_logging.cpp rename to src/util/angel_script/as_logging.cpp index 03b7f836..c531a339 100644 --- a/src/util/angle_script/as_logging.cpp +++ b/src/util/angel_script/as_logging.cpp @@ -7,15 +7,15 @@ namespace as_logging { -struct script_location { +struct script_location_t { std::string file; int line; int column; }; -script_location +script_location_t get_script_location() { - script_location location_data; + script_location_t location_data; asIScriptContext* context = asGetActiveContext(); if (context == nullptr) { location_data.file = "Invoked from c++"; @@ -36,7 +36,7 @@ get_script_location() { void as_log_backtrace(std::string message) { - script_location location = get_script_location(); + script_location_t location = get_script_location(); LOG_BACKTRACE( logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message @@ -45,7 +45,7 @@ as_log_backtrace(std::string message) { void as_log_info(std::string message) { - script_location location = get_script_location(); + script_location_t location = get_script_location(); LOG_INFO( logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message @@ -54,7 +54,7 @@ as_log_info(std::string message) { void as_log_debug(std::string message) { - script_location location = get_script_location(); + script_location_t location = get_script_location(); LOG_DEBUG( logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message @@ -63,7 +63,7 @@ as_log_debug(std::string message) { void as_log_warning(std::string message) { - script_location location = get_script_location(); + script_location_t location = get_script_location(); LOG_WARNING( logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message @@ -72,7 +72,7 @@ as_log_warning(std::string message) { void as_log_error(std::string message) { - script_location location = get_script_location(); + script_location_t location = get_script_location(); LOG_ERROR( logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message @@ -81,7 +81,7 @@ as_log_error(std::string message) { void as_log_critical(std::string message) { - script_location location = get_script_location(); + script_location_t location = get_script_location(); LOG_CRITICAL( logging::script_logger, "[{:<18}] - {}", fmtquill::format("{}:{}", location.file, location.line), message diff --git a/src/util/angle_script/as_logging.hpp b/src/util/angel_script/as_logging.hpp similarity index 100% rename from src/util/angle_script/as_logging.hpp rename to src/util/angel_script/as_logging.hpp diff --git a/src/util/angle_script/as_math.hpp b/src/util/angel_script/as_math.hpp similarity index 100% rename from src/util/angle_script/as_math.hpp rename to src/util/angel_script/as_math.hpp diff --git a/src/util/angle_script/as_tests.cpp b/src/util/angel_script/as_tests.cpp similarity index 100% rename from src/util/angle_script/as_tests.cpp rename to src/util/angel_script/as_tests.cpp diff --git a/src/util/angle_script/as_tests.hpp b/src/util/angel_script/as_tests.hpp similarity index 100% rename from src/util/angle_script/as_tests.hpp rename to src/util/angel_script/as_tests.hpp diff --git a/src/world/biome.cpp b/src/world/biome.cpp index f9271132..27514ff5 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -107,14 +107,14 @@ Biome::get_map(MacroDim size) const { biome_map->AddRef(); asIScriptFunction* method = type->GetMethodByDecl("int sample(int, int)"); - result = local_context.run_method(biome_map, method, 5, 5); if (method == nullptr) { LOG_WARNING(logging::main_logger, "Could not find biome map function."); return {}; } - + result = local_context.run_method(biome_map, method, 5, 5); + std::vector out; - + MacroDim x_map_tiles = size; MacroDim y_map_tiles = size; diff --git a/src/world/terrain/generation/interface.cpp b/src/world/terrain/generation/interface.cpp index b435724a..a261dbd7 100644 --- a/src/world/terrain/generation/interface.cpp +++ b/src/world/terrain/generation/interface.cpp @@ -6,6 +6,8 @@ namespace terrain { namespace generation { +namespace { + FractalNoise* FractalNoise_factory(int x, double y, int z) { // The class constructor is initializing the reference counter to 1 @@ -24,6 +26,8 @@ AlternativeWorleyNoise_factory(NoisePosition x, double y, NoisePosition z) { return new AlternativeWorleyNoise(x, y, z); } +} + void init_as_interface(asIScriptEngine* engine) { int r = engine->SetDefaultNamespace("TerrainGeneration"); From 1cf7b628f8fdd7174a8954182bff1b0298b4a300 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Wed, 13 May 2026 16:50:36 -0400 Subject: [PATCH 19/25] suggested changes and angelscript namespace --- CMakeLists.txt | 2 + src/global_context.cpp | 41 +++--- src/global_context.hpp | 10 +- src/local_context.cpp | 2 +- src/local_context.hpp | 159 ++++++++++++--------- src/util/angel_script/as_logging.cpp | 104 ++++++++++++-- src/util/angel_script/as_logging.hpp | 67 +-------- src/util/angel_script/as_tests.cpp | 51 ++++--- src/world/biome.cpp | 44 +++--- src/world/terrain/generation/interface.cpp | 57 ++++---- src/world/terrain/generation/interface.hpp | 2 +- 11 files changed, 307 insertions(+), 232 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 393f5a83..a9851725 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,6 +15,7 @@ file(GLOB ANGELSCRIPT_SOURCE "vendor/angelscript/sdk/angelscript/source/*.c*") file(GLOB ANGELSCRIPT_SOURCE_STRING "vendor/angelscript/sdk/add_on/scriptstdstring/*.c*") file(GLOB ANGELSCRIPT_SOURCE_ARRAY "vendor/angelscript/sdk/add_on/scriptarray/*.c*") add_library(angelscript OBJECT ${ANGELSCRIPT_SOURCE} ${ANGELSCRIPT_SOURCE_STRING} ${ANGELSCRIPT_SOURCE_ARRAY}) +target_compile_definitions(angelscript PRIVATE "AS_USE_NAMESPACE") target_compile_definitions(angelscript PRIVATE "AS_USE_STLNAMES") target_include_directories(angelscript PRIVATE "vendor/angelscript/sdk/angelscript/include") @@ -38,6 +39,7 @@ add_executable(FunGame ${SOURCES1}) set_property(TARGET FunGame PROPERTY CXX_STANDARD 23) set_property(TARGET FunGame PROPERTY C_STANDARD 17) +target_compile_definitions(FunGame PRIVATE "AS_USE_NAMESPACE") target_compile_definitions(FunGame PUBLIC GLM_ENABLE_EXPERIMENTAL) # compile quill diff --git a/src/global_context.cpp b/src/global_context.cpp index 66623184..29c25379 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -9,26 +9,24 @@ // Implement a simple message callback function void -MessageCallback(const asSMessageInfo* msg, void* param) { - if (msg->type == asMSGTYPE_ERROR) { +MessageCallback(const AngelScript::asSMessageInfo* msg, void* param) { + if (msg->type == AngelScript::asMSGTYPE_ERROR) { LOG_ERROR( logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); - } else if (msg->type == asMSGTYPE_WARNING) { + } else if (msg->type == AngelScript::asMSGTYPE_WARNING) { LOG_WARNING( logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); - } else if (msg->type == asMSGTYPE_INFORMATION) { + } else if (msg->type == AngelScript::asMSGTYPE_INFORMATION) { LOG_INFO( logging::script_logger, "[ {} :({}, {}) ] - {}", msg->section, msg->row, msg->col, msg->message ); } else { - LOG_ERROR( - logging::script_logger, "Unknown message type." - ); + LOG_ERROR(logging::script_logger, "Unknown message type."); } } @@ -56,9 +54,11 @@ GlobalContext::run_opengl_queue() { GlobalContext::GlobalContext() : thread_pool_([] { quill::detail::set_thread_name("BS Thread"); }) { - asPrepareMultithread(); - engine_ = asCreateScriptEngine(); - engine_->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); + AngelScript::asPrepareMultithread(); + engine_ = AngelScript::asCreateScriptEngine(); + engine_->SetMessageCallback( + AngelScript::asFUNCTION(MessageCallback), 0, AngelScript::asCALL_CDECL + ); RegisterStdString(engine_); terrain::generation::init_as_interface(engine_); as_logging::init_as_interface(engine_); @@ -71,8 +71,8 @@ GlobalContext::~GlobalContext() { // TODO this needs to return a status void GlobalContext::load_file(const std::string& mod_name, std::filesystem::path path) { - asIScriptModule* mod = - engine_->GetModule(mod_name.c_str(), asGM_CREATE_IF_NOT_EXISTS); + AngelScript::asIScriptModule* mod = + engine_->GetModule(mod_name.c_str(), AngelScript::asGM_CREATE_IF_NOT_EXISTS); std::ostringstream script; auto file = files::open_file(path); @@ -90,24 +90,27 @@ GlobalContext::load_file(const std::string& mod_name, std::filesystem::path path } } -asIScriptFunction* -GlobalContext::get_function(const std::string& module, std::string function_signature) const { +AngelScript::asIScriptFunction* +GlobalContext::get_function( + const std::string& module, std::string function_signature +) const { // check that the module exists. - asIScriptModule* mod; + AngelScript::asIScriptModule* mod; if ((mod = engine_->GetModule(module.c_str())) == nullptr) { return nullptr; } - asIScriptFunction* function = mod->GetFunctionByDecl(function_signature.c_str()); + AngelScript::asIScriptFunction* function = + mod->GetFunctionByDecl(function_signature.c_str()); return function; } -asITypeInfo* +AngelScript::asITypeInfo* GlobalContext::get_type(const std::string& module, std::string type_signature) const { // check that the module exists. - asIScriptModule* mod; + AngelScript::asIScriptModule* mod; if ((mod = engine_->GetModule(module.c_str())) == nullptr) { return nullptr; } - asITypeInfo* type = mod->GetTypeInfoByDecl(type_signature.c_str()); + AngelScript::asITypeInfo* type = mod->GetTypeInfoByDecl(type_signature.c_str()); return type; } diff --git a/src/global_context.hpp b/src/global_context.hpp index c298cbe8..d46369c9 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -37,7 +37,7 @@ #include #include -void MessageCallback(const asSMessageInfo* msg, void* param); +void MessageCallback(const AngelScript::asSMessageInfo* msg, void* param); /** * @brief Any global context that are needed will go in this class. @@ -55,7 +55,7 @@ class GlobalContext { std::mutex opengl_queue_mutex; - asIScriptEngine* engine_; + AngelScript::asIScriptEngine* engine_; // std::mutex global_as_mutex_; @@ -174,8 +174,10 @@ class GlobalContext { void load_file(const std::string& module, std::filesystem::path path); // get function from module - asIScriptFunction* get_function(const std::string& module, std::string function) const; + AngelScript::asIScriptFunction* + get_function(const std::string& module, std::string function) const; // get type from module - asITypeInfo* get_type(const std::string& module, std::string type_signature) const; + AngelScript::asITypeInfo* + get_type(const std::string& module, std::string type_signature) const; }; diff --git a/src/local_context.cpp b/src/local_context.cpp index c7eb639a..1bf7f5ae 100644 --- a/src/local_context.cpp +++ b/src/local_context.cpp @@ -7,7 +7,7 @@ LocalContext::LocalContext() : LocalContext::~LocalContext() { context_->Release(); - asThreadCleanup(); + AngelScript::asThreadCleanup(); } LocalContext& diff --git a/src/local_context.hpp b/src/local_context.hpp index bf316db3..a60b08cd 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -34,92 +34,100 @@ class LocalContext { private: LocalContext(); - asIScriptContext* context_; - - inline int + AngelScript::asIScriptContext* context_; + + // Return values + // asSUCCESS Success + // asCONTEXT_NOT_PREPARED The context is not in prepared state. + // asINVALID_ARG The arg is larger than the number of arguments in the + // prepared function. asINVALID_TYPE The argument is not an object or + // handle. + inline AngelScript::asERetCodes set_arg(size_t i, bool arg) { - return context_->SetArgByte(i, arg); + return static_cast(context_->SetArgByte(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, int8_t arg) { - return context_->SetArgByte(i, arg); + return static_cast(context_->SetArgByte(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, uint8_t arg) { - return context_->SetArgByte(i, arg); + return static_cast(context_->SetArgByte(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, int16_t arg) { - return context_->SetArgWord(i, arg); + return static_cast(context_->SetArgWord(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, uint16_t arg) { - return context_->SetArgWord(i, arg); + return static_cast(context_->SetArgWord(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, int32_t arg) { - return context_->SetArgDWord(i, arg); + return static_cast(context_->SetArgDWord(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, uint32_t arg) { - return context_->SetArgDWord(i, arg); + return static_cast(context_->SetArgDWord(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, int64_t arg) { - return context_->SetArgQWord(i, arg); + return static_cast(context_->SetArgQWord(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, uint64_t arg) { - return context_->SetArgQWord(i, arg); + return static_cast(context_->SetArgQWord(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, float arg) { - return context_->SetArgFloat(i, arg); + return static_cast(context_->SetArgFloat(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, double arg) { - return context_->SetArgDouble(i, arg); + return static_cast(context_->SetArgDouble(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, void* arg) { - return context_->SetArgObject(i, arg); + return static_cast(context_->SetArgObject(i, arg)); } - inline int + inline AngelScript::asERetCodes set_arg(size_t i, std::string arg) { - return context_->SetArgObject(i, &arg); + return static_cast(context_->SetArgObject(i, &arg)); } template - inline int + inline AngelScript::asERetCodes set_all_args(const size_t i, const A&& a) { - int result = set_arg(i, a); - if (result != 0) { + AngelScript::asERetCodes result = set_arg(i, a); + if (result != AngelScript::asERetCodes::asSUCCESS) { LOG_ERROR( - logging::main_logger, "An error occurred {} at parameter {}", result, i + logging::main_logger, "An error occurred {} at parameter {}", + std::to_underlying(result), i ); } return result; } template - inline int + inline AngelScript::asERetCodes set_all_args(const size_t i, const A&& a, const Args&&... args) { - int result = set_arg(i, a); - if (result != 0) { + AngelScript::asERetCodes result = set_arg(i, a); + if (result != AngelScript::asERetCodes::asSUCCESS) { LOG_ERROR( - logging::main_logger, "An error occurred {} at parameter {}", result, i + logging::main_logger, "An error occurred {} at parameter {}", + std::to_underlying(result), i ); return result; } @@ -131,12 +139,13 @@ class LocalContext { ~LocalContext(); template - inline std::expected - run_function(asIScriptFunction* function) { + inline std::expected + run_function(AngelScript::asIScriptFunction* function) { context_->Prepare(function); // set args maybe - int result = context_->Execute(); - if (result != asEXECUTION_FINISHED) { + AngelScript::asEContextState result = + static_cast(context_->Execute()); + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { return std::unexpected(result); } T object = *static_cast(context_->GetReturnObject()); @@ -144,48 +153,71 @@ class LocalContext { return object; } + AngelScript::asEContextState + run_function(AngelScript::asIScriptFunction* function) { + context_->Prepare(function); + AngelScript::asEContextState result = + static_cast(context_->Execute()); + return result; + } + template - inline int - run_function(asIScriptFunction* function, const Args&&... args) { + inline AngelScript::asEContextState + run_function(AngelScript::asIScriptFunction* function, const Args&&... args) { context_->Prepare(function); - int result = set_all_args(0, std::forward(args)...); - if (result != 0) { - return result; + AngelScript::asERetCodes args_result = + set_all_args(0, std::forward(args)...); + if (args_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_WARNING( + logging::as_logger, "Setting script arguments did not secseed." + ); + return AngelScript::asEContextState::asEXECUTION_SUSPENDED; } - result = context_->Execute(); + AngelScript::asEContextState result = + static_cast(context_->Execute()); + return result; } // this might crash. should probably do some tests - asIScriptObject* + AngelScript::asIScriptObject* get_return_object() const { auto out = context_->GetAddressOfReturnValue(); if (out == nullptr) { return nullptr; } - return *(asIScriptObject**)out; + return *(AngelScript::asIScriptObject**)out; } - int - run_method(asIScriptObject* object, asIScriptFunction* function) { + AngelScript::asEContextState + run_method( + AngelScript::asIScriptObject* object, AngelScript::asIScriptFunction* function + ) { context_->Prepare(function); context_->SetObject(object); - int result = context_->Execute(); + AngelScript::asEContextState result = + static_cast(context_->Execute()); return result; } template - inline int + inline AngelScript::asEContextState run_method( - asIScriptObject* object, asIScriptFunction* function, const Args&&... args + AngelScript::asIScriptObject* object, AngelScript::asIScriptFunction* function, + const Args&&... args ) { context_->Prepare(function); context_->SetObject(object); - int result = set_all_args(0, std::forward(args)...); - if (result != 0) { - return result; + AngelScript::asERetCodes args_result = + set_all_args(0, std::forward(args)...); + if (args_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_WARNING( + logging::as_logger, "Setting script arguments did not secseed." + ); + return AngelScript::asEContextState::asEXECUTION_SUSPENDED; } - result = context_->Execute(); + AngelScript::asEContextState result = + static_cast(context_->Execute()); return result; } @@ -204,26 +236,25 @@ class LocalContext { // } // template - int + AngelScript::asEContextState get_return_value(int& value) { // if this is zero then could be right could be wrong. value = context_->GetReturnDWord(); - - return 0; + return AngelScript::asEContextState::asEXECUTION_FINISHED; } - int + AngelScript::asEContextState get_return_value(bool& value) { // if this is zero then could be right could be wrong. value = context_->GetReturnByte(); - return 0; + return AngelScript::asEContextState::asEXECUTION_FINISHED; } - int + AngelScript::asEContextState get_return_value(float& value) { // if this is zero then could be right could be wrong. value = context_->GetReturnFloat(); - return 0; + return AngelScript::asEContextState::asEXECUTION_FINISHED; } inline int diff --git a/src/util/angel_script/as_logging.cpp b/src/util/angel_script/as_logging.cpp index c531a339..1171dd10 100644 --- a/src/util/angel_script/as_logging.cpp +++ b/src/util/angel_script/as_logging.cpp @@ -7,6 +7,74 @@ namespace as_logging { +namespace { + +/** + * @brief Backtrace Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void as_log_backtrace(std::string message); + +/** + * @brief Info Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void as_log_info(std::string message); + +/** + * @brief Debug Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void as_log_debug(std::string message); + +/** + * @brief Warning Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void as_log_warning(std::string message); + +/** + * @brief Error Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void as_log_error(std::string message); + +/** + * @brief Critical Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ +void as_log_critical(std::string message); + +/** + * @brief Initialize Logging interface on given engine + * + * @param asIScriptEngine* engine the engine logging will be initialized on. + */ + struct script_location_t { std::string file; int line; @@ -16,7 +84,7 @@ struct script_location_t { script_location_t get_script_location() { script_location_t location_data; - asIScriptContext* context = asGetActiveContext(); + AngelScript::asIScriptContext* context = AngelScript::asGetActiveContext(); if (context == nullptr) { location_data.file = "Invoked from c++"; location_data.line = -1; @@ -88,34 +156,54 @@ as_log_critical(std::string message) { ); } +} // namespace + void -init_as_interface(asIScriptEngine* engine) { +init_as_interface(AngelScript::asIScriptEngine* engine) { + // Return values + // asINVALID_ARG The namespace is null. + // asINVALID_DECLARATION The namespace is invalid. int r = engine->SetDefaultNamespace("LOGGING"); assert(r >= 0); + // Return values + // asNOT_SUPPORTED The calling convention is not supported. + // asWRONG_CALLING_CONV The function's calling convention doesn't match + // callConv. asINVALID_DECLARATION The function declaration is invalid. + // asNAME_TAKEN The function name is already used elsewhere. + // asALREADY_REGISTERED The function has already been registered with the same + // parameter list. asINVALID_ARG The auxiliary pointer wasn't set + // according to calling convention. + // Registering r = engine->RegisterGlobalFunction( - "void LOG_BACKTRACE(string)", asFUNCTION(as_log_backtrace), asCALL_CDECL + "void LOG_BACKTRACE(string)", AngelScript::asFUNCTION(as_log_backtrace), + AngelScript::asCALL_CDECL ); assert(r >= 0); r = engine->RegisterGlobalFunction( - "void LOG_INFO(string)", asFUNCTION(as_log_info), asCALL_CDECL + "void LOG_INFO(string)", AngelScript::asFUNCTION(as_log_info), + AngelScript::asCALL_CDECL ); assert(r >= 0); r = engine->RegisterGlobalFunction( - "void LOG_DEBUG(string)", asFUNCTION(as_log_debug), asCALL_CDECL + "void LOG_DEBUG(string)", AngelScript::asFUNCTION(as_log_debug), + AngelScript::asCALL_CDECL ); assert(r >= 0); r = engine->RegisterGlobalFunction( - "void LOG_WARNING(string)", asFUNCTION(as_log_warning), asCALL_CDECL + "void LOG_WARNING(string)", AngelScript::asFUNCTION(as_log_warning), + AngelScript::asCALL_CDECL ); assert(r >= 0); r = engine->RegisterGlobalFunction( - "void LOG_ERROR(string)", asFUNCTION(as_log_error), asCALL_CDECL + "void LOG_ERROR(string)", AngelScript::asFUNCTION(as_log_error), + AngelScript::asCALL_CDECL ); assert(r >= 0); r = engine->RegisterGlobalFunction( - "void LOG_CRITICAL(string)", asFUNCTION(as_log_critical), asCALL_CDECL + "void LOG_CRITICAL(string)", AngelScript::asFUNCTION(as_log_critical), + AngelScript::asCALL_CDECL ); assert(r >= 0); } diff --git a/src/util/angel_script/as_logging.hpp b/src/util/angel_script/as_logging.hpp index 44d39fff..0598a4e0 100644 --- a/src/util/angel_script/as_logging.hpp +++ b/src/util/angel_script/as_logging.hpp @@ -28,71 +28,6 @@ namespace as_logging { -/** - * @brief Backtrace Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_backtrace(std::string message); - -/** - * @brief Info Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_info(std::string message); - -/** - * @brief Debug Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_debug(std::string message); - -/** - * @brief Warning Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_warning(std::string message); - -/** - * @brief Error Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_error(std::string message); - -/** - * @brief Critical Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_critical(std::string message); - -/** - * @brief Initialize Logging interface on given engine - * - * @param asIScriptEngine* engine the engine logging will be initialized on. - */ -void init_as_interface(asIScriptEngine* engine); +void init_as_interface(AngelScript::asIScriptEngine* engine); } // namespace as_logging diff --git a/src/util/angel_script/as_tests.cpp b/src/util/angel_script/as_tests.cpp index 38968e9c..dde41b10 100644 --- a/src/util/angel_script/as_tests.cpp +++ b/src/util/angel_script/as_tests.cpp @@ -31,7 +31,7 @@ as_loadtime_test() { auto function_result = local_context.run_function(is_prime_function, 97); // TODO write a better error logging mechanism - if (function_result != asEXECUTION_FINISHED) { + if (function_result != AngelScript::asEXECUTION_FINISHED) { return 1; } @@ -66,7 +66,7 @@ as_loadtime_test() { auto function_result = local_context.run_function(is_prime_function, 97); // TODO write a better error logging mechanism - if (function_result != asEXECUTION_FINISHED) { + if (function_result != AngelScript::asEXECUTION_FINISHED) { return 1; } @@ -112,11 +112,13 @@ as_loadtime_test() { int logging_test() { - as_logging::as_log_backtrace("Backtrace"); + // as_logging::as_log_backtrace("Backtrace"); LOG_ERROR(logging::script_logger, ""); - asIScriptEngine* engine = asCreateScriptEngine(); - engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); + AngelScript::asIScriptEngine* engine = AngelScript::asCreateScriptEngine(); + engine->SetMessageCallback( + asFUNCTION(MessageCallback), 0, AngelScript::asCALL_CDECL + ); RegisterStdString(engine); as_logging::init_as_interface(engine); @@ -125,7 +127,8 @@ logging_test() { return 1; } - asIScriptModule* mod = engine->GetModule("test_module", asGM_CREATE_IF_NOT_EXISTS); + AngelScript::asIScriptModule* mod = + engine->GetModule("test_module", AngelScript::asGM_CREATE_IF_NOT_EXISTS); std::ostringstream script; auto file = files::open_file(files::get_resources_path() / "as" / "test.as"); if (!file) { @@ -142,14 +145,14 @@ logging_test() { return 1; } - asIScriptFunction* funct1 = + AngelScript::asIScriptFunction* funct1 = engine->GetModule("test_module")->GetFunctionByDecl("int test3()"); - asIScriptContext* ctx = engine->CreateContext(); + AngelScript::asIScriptContext* ctx = engine->CreateContext(); ctx->Prepare(funct1); // ctx->SetArgDWord(); result = ctx->Execute(); - if (result != asEXECUTION_FINISHED) { + if (result != AngelScript::asEXECUTION_FINISHED) { ctx->Release(); engine->ShutDownAndRelease(); return 1; @@ -161,15 +164,18 @@ logging_test() { int test() { - asIScriptEngine* engine = asCreateScriptEngine(); - engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); + AngelScript::asIScriptEngine* engine = AngelScript::asCreateScriptEngine(); + engine->SetMessageCallback( + asFUNCTION(MessageCallback), 0, AngelScript::asCALL_CDECL + ); if (!engine) { LOG_ERROR(logging::main_logger, "Could no start Angle Script engine."); return 1; } - asIScriptModule* mod = engine->GetModule("test_module", asGM_CREATE_IF_NOT_EXISTS); + AngelScript::asIScriptModule* mod = + engine->GetModule("test_module", AngelScript::asGM_CREATE_IF_NOT_EXISTS); std::ostringstream script; auto file = files::open_file(files::get_resources_path() / "as" / "test.as"); if (!file) { @@ -186,26 +192,26 @@ test() { return 1; } - asIScriptFunction* funct1 = + AngelScript::asIScriptFunction* funct1 = engine->GetModule("test_module")->GetFunctionByDecl("void test1()"); - asIScriptContext* ctx = engine->CreateContext(); + AngelScript::asIScriptContext* ctx = engine->CreateContext(); ctx->Prepare(funct1); // ctx->SetArgDWord(); result = ctx->Execute(); - if (result != asEXECUTION_FINISHED) { + if (result != AngelScript::asEXECUTION_FINISHED) { ctx->Release(); engine->ShutDownAndRelease(); return 1; } - asIScriptFunction* funct2 = + AngelScript::asIScriptFunction* funct2 = engine->GetModule("test_module")->GetFunctionByDecl("int test2()"); ctx->Prepare(funct2); // ctx->SetArgDWord(); result = ctx->Execute(); - if (result != asEXECUTION_FINISHED) { + if (result != AngelScript::asEXECUTION_FINISHED) { ctx->Release(); engine->ShutDownAndRelease(); return 1; @@ -250,7 +256,7 @@ as_load_tests() { auto function = context.get_function("Base", "void do_something()"); int result = local_context.run_function(function); - if (result != asEXECUTION_FINISHED) { + if (result != AngelScript::asEXECUTION_FINISHED) { LOG_ERROR(logging::main_logger, "Failed AngelScript Test"); return 1; } @@ -275,21 +281,22 @@ as_load_tests() { LOG_DEBUG(logging::main_logger, "{}", declaration); result = local_context.run_function(factory_function); - if (result != asEXECUTION_FINISHED) { + if (result != AngelScript::asEXECUTION_FINISHED) { LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return 1; } - asIScriptObject* biome_map = local_context.get_return_object(); + AngelScript::asIScriptObject* biome_map = local_context.get_return_object(); if (biome_map == nullptr) { LOG_ERROR(logging::main_logger, "Failed to get object"); return 1; } biome_map->AddRef(); - asIScriptFunction* method = type->GetMethodByDecl("int sample(int, int)"); + AngelScript::asIScriptFunction* method = + type->GetMethodByDecl("int sample(int, int)"); result = local_context.run_method(biome_map, method, 5, 5); - if (result != asEXECUTION_FINISHED) { + if (result != AngelScript::asEXECUTION_FINISHED) { LOG_ERROR(logging::main_logger, "Failed AngelScript run sample"); return 1; } diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 27514ff5..c570fc37 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -94,27 +94,28 @@ Biome::get_map(MacroDim size) const { auto factory_function = type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); - int result = local_context.run_function(factory_function); - if (result != asEXECUTION_FINISHED) { + AngelScript::asEContextState result = local_context.run_function(factory_function); + if (result != AngelScript::asEXECUTION_FINISHED) { LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return {}; } - asIScriptObject* biome_map = local_context.get_return_object(); + AngelScript::asIScriptObject* biome_map = local_context.get_return_object(); if (biome_map == nullptr) { LOG_ERROR(logging::main_logger, "Failed to get object"); return {}; } biome_map->AddRef(); - asIScriptFunction* method = type->GetMethodByDecl("int sample(int, int)"); + AngelScript::asIScriptFunction* method = + type->GetMethodByDecl("int sample(int, int)"); if (method == nullptr) { LOG_WARNING(logging::main_logger, "Could not find biome map function."); return {}; } result = local_context.run_method(biome_map, method, 5, 5); - + std::vector out; - + MacroDim x_map_tiles = size; MacroDim y_map_tiles = size; @@ -126,13 +127,13 @@ Biome::get_map(MacroDim size) const { result = local_context.run_method( biome_map, method, std::move(x_copy), std::move(y_copy) ); - if (result == asCONTEXT_NOT_PREPARED) { + if (result == AngelScript::asCONTEXT_NOT_PREPARED) { LOG_ERROR(logging::main_logger, "Context not prepared"); return {}; - } else if (result == asINVALID_ARG) { + } else if (result == AngelScript::asINVALID_ARG) { LOG_ERROR(logging::main_logger, "To many arguments"); return {}; - } else if (result == asINVALID_TYPE) { + } else if (result == AngelScript::asINVALID_TYPE) { LOG_ERROR(logging::main_logger, "Invalid arg type"); return {}; } @@ -142,7 +143,7 @@ Biome::get_map(MacroDim size) const { if (result != 0) { LOG_ERROR( logging::main_logger, "Non zero return value in get map as ({})", - result + std::to_underlying(result) ); return {}; } @@ -171,22 +172,22 @@ Biome::get_plant_map(Dim length) const { auto factory_function = type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); - int result = local_context.run_function(factory_function); - if (result != asEXECUTION_FINISHED) { + AngelScript::asEContextState result = local_context.run_function(factory_function); + if (result != AngelScript::asEXECUTION_FINISHED) { LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return {}; } - asIScriptObject* biome_map = local_context.get_return_object(); + AngelScript::asIScriptObject* biome_map = local_context.get_return_object(); if (biome_map == nullptr) { LOG_ERROR(logging::main_logger, "Failed to get object"); return {}; } biome_map->AddRef(); - asIScriptFunction* method = + AngelScript::asIScriptFunction* script_method = type->GetMethodByDecl("float sample_plants(string, int, int)"); - result = local_context.run_method(biome_map, method, 5, 5); - if (method == nullptr) { + result = local_context.run_method(biome_map, script_method, 5, 5); + if (script_method == nullptr) { LOG_WARNING(logging::main_logger, "Could not find biome map function."); return {}; } @@ -205,16 +206,16 @@ Biome::get_plant_map(Dim length) const { int x_copy = x; int y_copy = y; result = local_context.run_method( - biome_map, method, &plant_map_name, std::move(x_copy), + biome_map, script_method, &plant_map_name, std::move(x_copy), std::move(y_copy) ); - if (result == asCONTEXT_NOT_PREPARED) { + if (result == AngelScript::asCONTEXT_NOT_PREPARED) { LOG_ERROR(logging::main_logger, "Context not prepared"); return {}; - } else if (result == asINVALID_ARG) { + } else if (result == AngelScript::asINVALID_ARG) { LOG_ERROR(logging::main_logger, "To many arguments"); return {}; - } else if (result == asINVALID_TYPE) { + } else if (result == AngelScript::asINVALID_TYPE) { LOG_ERROR(logging::main_logger, "Invalid arg type"); return {}; } @@ -224,7 +225,8 @@ Biome::get_plant_map(Dim length) const { if (result != 0) { LOG_ERROR( logging::main_logger, - "Non zero return value in get map as ({})", result + "Non zero return value in get map as ({})", + std::to_underlying(result) ); return {}; } diff --git a/src/world/terrain/generation/interface.cpp b/src/world/terrain/generation/interface.cpp index a261dbd7..3a253486 100644 --- a/src/world/terrain/generation/interface.cpp +++ b/src/world/terrain/generation/interface.cpp @@ -26,81 +26,86 @@ AlternativeWorleyNoise_factory(NoisePosition x, double y, NoisePosition z) { return new AlternativeWorleyNoise(x, y, z); } -} +} // namespace void -init_as_interface(asIScriptEngine* engine) { +init_as_interface(AngelScript::asIScriptEngine* engine) { int r = engine->SetDefaultNamespace("TerrainGeneration"); assert(r >= 0); // Registering the class method - r = engine->RegisterObjectType("FractalNoise", 0, asOBJ_REF); + r = engine->RegisterObjectType("FractalNoise", 0, AngelScript::asOBJ_REF); assert(r >= 0); r = engine->RegisterObjectBehaviour( - "FractalNoise", asBEHAVE_FACTORY, "FractalNoise@ f(int, double, int)", - asFUNCTION(FractalNoise_factory), asCALL_CDECL + "FractalNoise", AngelScript::asBEHAVE_FACTORY, + "FractalNoise@ f(int, double, int)", + AngelScript::asFUNCTION(FractalNoise_factory), AngelScript::asCALL_CDECL ); assert(r >= 0); r = engine->RegisterObjectBehaviour( - "FractalNoise", asBEHAVE_ADDREF, "void f()", asMETHOD(FractalNoise, add_ref), - asCALL_THISCALL + "FractalNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(FractalNoise, add_ref), AngelScript::asCALL_THISCALL ); assert(r >= 0); r = engine->RegisterObjectBehaviour( - "FractalNoise", asBEHAVE_RELEASE, "void f()", - asMETHOD(FractalNoise, release_ref), asCALL_THISCALL + "FractalNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(FractalNoise, release_ref), AngelScript::asCALL_THISCALL ); assert(r >= 0); r = engine->RegisterObjectMethod( "FractalNoise", "double sample(double, double)", - asMETHOD(FractalNoise, get_noise), asCALL_THISCALL + AngelScript::asMETHOD(FractalNoise, get_noise), AngelScript::asCALL_THISCALL ); assert(r >= 0); - r = engine->RegisterObjectType("WorleyNoise", 0, asOBJ_REF); + r = engine->RegisterObjectType("WorleyNoise", 0, AngelScript::asOBJ_REF); assert(r >= 0); r = engine->RegisterObjectBehaviour( - "WorleyNoise", asBEHAVE_FACTORY, "WorleyNoise@ f(double, double)", - asFUNCTION(WorleyNoise_factory), asCALL_CDECL + "WorleyNoise", AngelScript::asBEHAVE_FACTORY, "WorleyNoise@ f(double, double)", + AngelScript::asFUNCTION(WorleyNoise_factory), AngelScript::asCALL_CDECL ); assert(r >= 0); r = engine->RegisterObjectBehaviour( - "WorleyNoise", asBEHAVE_ADDREF, "void f()", asMETHOD(WorleyNoise, add_ref), - asCALL_THISCALL + "WorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(WorleyNoise, add_ref), AngelScript::asCALL_THISCALL ); assert(r >= 0); r = engine->RegisterObjectBehaviour( - "WorleyNoise", asBEHAVE_RELEASE, "void f()", asMETHOD(WorleyNoise, release_ref), - asCALL_THISCALL + "WorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(WorleyNoise, release_ref), AngelScript::asCALL_THISCALL ); assert(r >= 0); r = engine->RegisterObjectMethod( "WorleyNoise", "double sample(double, double)", - asMETHOD(WorleyNoise, get_noise), asCALL_THISCALL + AngelScript::asMETHOD(WorleyNoise, get_noise), AngelScript::asCALL_THISCALL ); assert(r >= 0); - r = engine->RegisterObjectType("AlternativeWorleyNoise", 0, asOBJ_REF); + r = engine->RegisterObjectType("AlternativeWorleyNoise", 0, AngelScript::asOBJ_REF); assert(r >= 0); r = engine->RegisterObjectBehaviour( - "AlternativeWorleyNoise", asBEHAVE_FACTORY, + "AlternativeWorleyNoise", AngelScript::asBEHAVE_FACTORY, "AlternativeWorleyNoise@ f(double, double, double)", - asFUNCTION(AlternativeWorleyNoise_factory), asCALL_CDECL + AngelScript::asFUNCTION(AlternativeWorleyNoise_factory), + AngelScript::asCALL_CDECL ); assert(r >= 0); r = engine->RegisterObjectBehaviour( - "AlternativeWorleyNoise", asBEHAVE_ADDREF, "void f()", - asMETHOD(AlternativeWorleyNoise, add_ref), asCALL_THISCALL + "AlternativeWorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(AlternativeWorleyNoise, add_ref), + AngelScript::asCALL_THISCALL ); assert(r >= 0); r = engine->RegisterObjectBehaviour( - "AlternativeWorleyNoise", asBEHAVE_RELEASE, "void f()", - asMETHOD(AlternativeWorleyNoise, release_ref), asCALL_THISCALL + "AlternativeWorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(AlternativeWorleyNoise, release_ref), + AngelScript::asCALL_THISCALL ); assert(r >= 0); r = engine->RegisterObjectMethod( "AlternativeWorleyNoise", "double sample(double, double)", - asMETHOD(AlternativeWorleyNoise, get_noise), asCALL_THISCALL + AngelScript::asMETHOD(AlternativeWorleyNoise, get_noise), + AngelScript::asCALL_THISCALL ); assert(r >= 0); } diff --git a/src/world/terrain/generation/interface.hpp b/src/world/terrain/generation/interface.hpp index 54273e1b..8f371ff6 100644 --- a/src/world/terrain/generation/interface.hpp +++ b/src/world/terrain/generation/interface.hpp @@ -6,7 +6,7 @@ namespace terrain { namespace generation { -void init_as_interface(asIScriptEngine* engine); +void init_as_interface(AngelScript::asIScriptEngine* engine); } // namespace generation From 2dc938bdbc1f716a6d275277a52ec4f0ba473f07 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Thu, 14 May 2026 14:21:43 -0400 Subject: [PATCH 20/25] add error checking to interface --- src/global_context.cpp | 68 ++++++-- src/global_context.hpp | 13 +- src/main.cpp | 10 +- src/manifest/object_handler.cpp | 2 + src/util/angel_script/as_logging.cpp | 7 +- src/util/angel_script/as_logging.hpp | 7 +- src/util/angel_script/as_tests.cpp | 16 +- src/util/angel_script/as_tests.hpp | 7 +- src/util/angel_script/error_checks.cpp | 163 +++++++++++++++++ src/util/angel_script/error_checks.hpp | 22 +++ src/world/biome.cpp | 5 +- src/world/terrain/generation/interface.cpp | 194 +++++++++++++-------- src/world/terrain/terrain.cpp | 1 + 13 files changed, 401 insertions(+), 114 deletions(-) create mode 100644 src/util/angel_script/error_checks.cpp create mode 100644 src/util/angel_script/error_checks.hpp diff --git a/src/global_context.cpp b/src/global_context.cpp index 29c25379..ab2054c9 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -61,33 +61,81 @@ GlobalContext::GlobalContext() : ); RegisterStdString(engine_); terrain::generation::init_as_interface(engine_); - as_logging::init_as_interface(engine_); + util::scripting::init_as_interface(engine_); } GlobalContext::~GlobalContext() { engine_->ShutDownAndRelease(); } -// TODO this needs to return a status -void +AngelScript::asERetCodes GlobalContext::load_file(const std::string& mod_name, std::filesystem::path path) { - AngelScript::asIScriptModule* mod = - engine_->GetModule(mod_name.c_str(), AngelScript::asGM_CREATE_IF_NOT_EXISTS); + AngelScript::asIScriptModule* mod; + if (mod = engine_->GetModule(mod_name.c_str(), AngelScript::asGM_ONLY_IF_EXISTS)) { + LOG_BACKTRACE( + logging::as_logger, "Loading file from \"{}\" into module \"{}\".", + path.lexically_normal().string(), mod_name + ); + } else if (mod = engine_->GetModule( + mod_name.c_str(), AngelScript::asGM_CREATE_IF_NOT_EXISTS + )) { + LOG_BACKTRACE( + logging::as_logger, "Creating module \"{}\" from file \"{}\".", mod_name, + path.lexically_normal().string() + ); + } else { + LOG_ERROR( + logging::as_logger, "Could not find or create module \"{}\".", mod_name + ); + return AngelScript::asERetCodes::asERROR; + } std::ostringstream script; auto file = files::open_file(path); if (!file) { - return; + LOG_ERROR(logging::as_logger, "Could not open file."); + return AngelScript::asERetCodes::asERROR; } script << file.value().rdbuf(); mod->AddScriptSection(path.filename().c_str(), script.str().c_str()); - int result = mod->Build(); - if (result > 0) { - LOG_ERROR(logging::as_logger, "{}", result); - return; + AngelScript::asERetCodes result = + static_cast(mod->Build()); + + switch (result) { + case AngelScript::asINVALID_CONFIGURATION: + LOG_ERROR(logging::as_logger, "The engine configuration is invalid."); + return result; + case AngelScript::asERROR: + LOG_ERROR(logging::as_logger, "The script failed to build."); + return result; + case AngelScript::asBUILD_IN_PROGRESS: + LOG_ERROR(logging::as_logger, "Another thread is currently building."); + return result; + case AngelScript::asINIT_GLOBAL_VARS_FAILED: + LOG_ERROR( + logging::as_logger, "It was not possible to initialize at least one of " + "the global variables." + ); + return result; + case AngelScript::asNOT_SUPPORTED: + LOG_ERROR( + logging::as_logger, "Compiler support is disabled in the engine." + ); + return result; + case AngelScript::asMODULE_IS_IN_USE: + LOG_ERROR( + logging::as_logger, + "The code in the module is still being used and and cannot be removed." + ); + return result; + + default: + break; } + + return AngelScript::asERetCodes::asSUCCESS; } AngelScript::asIScriptFunction* diff --git a/src/global_context.hpp b/src/global_context.hpp index d46369c9..a7726959 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -143,7 +143,7 @@ class GlobalContext { * @param BS::priority_t priority = BS::pr::normal */ template >> - auto + [[nodiscard]] auto submit_task(F&& function, BS::priority_t priority = BS::pr::normal) { return thread_pool_.submit_task(function, priority); } @@ -158,26 +158,27 @@ class GlobalContext { } // Might want to expose these in the future. - auto + [[nodiscard]] auto wait_for_tasks() { return thread_pool_.wait(); } // oh boy time to start wrapping tread_pool - auto + [[nodiscard]] auto as_engine() { return engine_; } // load as script file - void load_file(const std::string& module, std::filesystem::path path); + [[nodiscard]] AngelScript::asERetCodes + load_file(const std::string& module, std::filesystem::path path); // get function from module - AngelScript::asIScriptFunction* + [[nodiscard]] AngelScript::asIScriptFunction* get_function(const std::string& module, std::string function) const; // get type from module - AngelScript::asITypeInfo* + [[nodiscard]] AngelScript::asITypeInfo* get_type(const std::string& module, std::string type_signature) const; }; diff --git a/src/main.cpp b/src/main.cpp index 2f0ae451..6edfe72c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -411,7 +411,7 @@ LogTest() { int as_tests(const argh::parser& cmdl) { if (cmdl.size() < 3) { - return as_test::test(); + return util::scripting::test(); } std::string run_function = cmdl(3).str(); @@ -419,13 +419,13 @@ as_tests(const argh::parser& cmdl) { if (run_function == "Map") { return MacroMap(cmdl); } else if (run_function == "Logging") { - return as_test::logging_test(); + return util::scripting::logging_test(); } else if (run_function == "LoadTime") { - return as_test::as_loadtime_test(); + return util::scripting::as_loadtime_test(); } else if (run_function == "Threading") { - return as_test::as_threading(); + return util::scripting::as_threading(); } else if (run_function == "LoadScript") { - return as_test::as_load_tests(); + return util::scripting::as_load_tests(); } else { std::cout << "No known command" << std::endl; return 1; diff --git a/src/manifest/object_handler.cpp b/src/manifest/object_handler.cpp index 975d1fad..38426ec0 100644 --- a/src/manifest/object_handler.cpp +++ b/src/manifest/object_handler.cpp @@ -31,6 +31,8 @@ ObjectHandler::read_biome(const descriptor_t& biome_descriptor) { std::filesystem::path path_copy = biome_descriptor.path; + + // TODO just need to know what module to load this into context.load_file( "Base", files::get_data_path() / path_copy.remove_filename() / biome_data->map_generator_path diff --git a/src/util/angel_script/as_logging.cpp b/src/util/angel_script/as_logging.cpp index 1171dd10..7e587ea5 100644 --- a/src/util/angel_script/as_logging.cpp +++ b/src/util/angel_script/as_logging.cpp @@ -5,7 +5,8 @@ #include -namespace as_logging { +namespace util { +namespace scripting { namespace { @@ -208,4 +209,6 @@ init_as_interface(AngelScript::asIScriptEngine* engine) { assert(r >= 0); } -} // namespace as_logging +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/as_logging.hpp b/src/util/angel_script/as_logging.hpp index 0598a4e0..8521ce56 100644 --- a/src/util/angel_script/as_logging.hpp +++ b/src/util/angel_script/as_logging.hpp @@ -26,8 +26,11 @@ #include -namespace as_logging { +namespace util { +namespace scripting { void init_as_interface(AngelScript::asIScriptEngine* engine); -} // namespace as_logging +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/as_tests.cpp b/src/util/angel_script/as_tests.cpp index dde41b10..0c80e21e 100644 --- a/src/util/angel_script/as_tests.cpp +++ b/src/util/angel_script/as_tests.cpp @@ -9,9 +9,8 @@ #include -namespace as_test { - -// TODO want to use the engine from global context and not create our own. +namespace util { +namespace scripting { int as_loadtime_test() { @@ -52,11 +51,6 @@ as_loadtime_test() { for (size_t y = 0; y < 100; y++) { auto l_start = time_util::get_time_nanoseconds(); - // context.load_file( - // "test_module", files::get_resources_path() / "as" / - // "test.as" - // ); - auto is_prime_function = context.get_function("test_module", "bool is_prime(int)"); auto l_end = time_util::get_time_nanoseconds(); @@ -120,7 +114,7 @@ logging_test() { asFUNCTION(MessageCallback), 0, AngelScript::asCALL_CDECL ); RegisterStdString(engine); - as_logging::init_as_interface(engine); + init_as_interface(engine); if (!engine) { LOG_ERROR(logging::main_logger, "Could no start Angle Script engine."); @@ -315,4 +309,6 @@ as_load_tests() { return 0; } -} // namespace as_test +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/as_tests.hpp b/src/util/angel_script/as_tests.hpp index 7b8bc218..b36db6c4 100644 --- a/src/util/angel_script/as_tests.hpp +++ b/src/util/angel_script/as_tests.hpp @@ -22,7 +22,8 @@ #pragma once -namespace as_test { +namespace util { +namespace scripting { int test(); @@ -34,4 +35,6 @@ int as_threading(); int as_load_tests(); -} // namespace as_test +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/error_checks.cpp b/src/util/angel_script/error_checks.cpp new file mode 100644 index 00000000..4896dc6e --- /dev/null +++ b/src/util/angel_script/error_checks.cpp @@ -0,0 +1,163 @@ +#include "error_checks.hpp" + +#include "angelscript.h" +#include "logging.hpp" + +namespace util { + +namespace scripting { + +AngelScript::asERetCodes +check_SetDefaultNamespace(int r) { + if (r == AngelScript::asERetCodes::asINVALID_ARG) { + LOG_ERROR(logging::as_logger, "The namespace is invalid."); + } + return static_cast(r); +} + +AngelScript::asERetCodes +check_RegisterObjectType(int r) { + switch (r) { + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR(logging::as_logger, "The flags are invalid."); + break; + case AngelScript::asERetCodes::asINVALID_NAME: + LOG_ERROR(logging::as_logger, "The name is invalid."); + break; + case AngelScript::asERetCodes::asALREADY_REGISTERED: + LOG_ERROR( + logging::as_logger, "Another type of the same name already exists." + ); + break; + case AngelScript::asERetCodes::asNAME_TAKEN: + LOG_ERROR( + logging::as_logger, "The name conflicts with other symbol names." + ); + break; + case AngelScript::asERetCodes::asLOWER_ARRAY_DIMENSION_NOT_REGISTERED: + LOG_ERROR( + logging::as_logger, "When registering an array type the array element " + "must be a primitive or a registered type." + ); + break; + case AngelScript::asERetCodes::asINVALID_TYPE: + LOG_ERROR(logging::as_logger, "The array type was not properly formed."); + break; + case AngelScript::asERetCodes::asNOT_SUPPORTED: + LOG_ERROR( + logging::as_logger, "The array type is not supported, or already in " + "use preventing it from being overloaded." + ); + break; + default: + break; + } + return static_cast(r); +} + +AngelScript::asERetCodes +check_RegisterObjectBehaviour(int r) { + switch (r) { + case AngelScript::asERetCodes::asWRONG_CONFIG_GROUP: + LOG_ERROR( + logging::as_logger, + "The object type was registered in a different configuration group." + ); + break; + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR( + logging::as_logger, + "obj is not set, or a global behaviour is given in behaviour, or the " + "objForThiscall pointer wasn't set according to calling convention." + ); + break; + case AngelScript::asERetCodes::asWRONG_CALLING_CONV: + LOG_ERROR( + logging::as_logger, + "The function's calling convention isn't compatible with callConv." + ); + break; + case AngelScript::asERetCodes::asNOT_SUPPORTED: + LOG_ERROR( + logging::as_logger, + "The calling convention or the behaviour signature is not supported." + ); + break; + case AngelScript::asERetCodes::asINVALID_TYPE: + LOG_ERROR( + logging::as_logger, "The obj parameter is not a valid object name." + ); + break; + case AngelScript::asERetCodes::asINVALID_DECLARATION: + LOG_ERROR(logging::as_logger, "The declaration is invalid."); + break; + case AngelScript::asERetCodes::asILLEGAL_BEHAVIOUR_FOR_TYPE: + LOG_ERROR( + logging::as_logger, "The behaviour is not allowed for this type." + ); + break; + case AngelScript::asERetCodes::asALREADY_REGISTERED: + LOG_ERROR( + logging::as_logger, + "The behaviour is already registered with the same signature." + ); + break; + default: + break; + } + return static_cast(r); +} + +AngelScript::asERetCodes +check_RegisterObjectMethod(int r) { + switch (r) { + case AngelScript::asERetCodes::asWRONG_CONFIG_GROUP: + LOG_ERROR( + logging::as_logger, + "The object type was registered in a different configuration group." + ); + break; + case AngelScript::asERetCodes::asNOT_SUPPORTED: + LOG_ERROR(logging::as_logger, "The calling convention is not supported."); + break; + case AngelScript::asERetCodes::asINVALID_TYPE: + LOG_ERROR( + logging::as_logger, "The obj parameter is not a valid object name." + ); + break; + case AngelScript::asERetCodes::asINVALID_DECLARATION: + LOG_ERROR(logging::as_logger, "The declaration is invalid."); + break; + case AngelScript::asERetCodes::asNAME_TAKEN: + LOG_ERROR(logging::as_logger, "The name conflicts with other members."); + break; + case AngelScript::asERetCodes::asWRONG_CALLING_CONV: + LOG_ERROR( + logging::as_logger, + "The function's calling convention isn't compatible with callConv." + ); + break; + case AngelScript::asERetCodes::asALREADY_REGISTERED: + LOG_ERROR( + logging::as_logger, + "The method has already been registered with the same parameter list." + ); + break; + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR( + logging::as_logger, + "The auxiliary pointer wasn't set according to calling convention." + ); + break; + default: + break; + } + return static_cast(r); +} + +// AngelScript::asERetCodes check_RegisterObjectType(int r) { + +//} +} // namespace scripting + +} // namespace util diff --git a/src/util/angel_script/error_checks.hpp b/src/util/angel_script/error_checks.hpp new file mode 100644 index 00000000..4024e63b --- /dev/null +++ b/src/util/angel_script/error_checks.hpp @@ -0,0 +1,22 @@ + + +#pragma once + +#include "angelscript.h" + +namespace util { +namespace scripting { + +AngelScript::asERetCodes check_SetDefaultNamespace(int); + +AngelScript::asERetCodes check_RegisterObjectType(int); + +AngelScript::asERetCodes check_RegisterObjectBehaviour(int); + +AngelScript::asERetCodes check_RegisterObjectMethod(int); + +AngelScript::asERetCodes check_RegisterObjectType(int); + +} // namespace scripting + +} // namespace util \ No newline at end of file diff --git a/src/world/biome.cpp b/src/world/biome.cpp index c570fc37..0cbf0edb 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -88,9 +88,10 @@ Biome::get_map(MacroDim size) const { auto& global_context = GlobalContext::instance(); auto& local_context = LocalContext::instance(); - global_context.load_file("Base", files::get_data_path() / "Base" / "biome_map.as"); - auto type = global_context.get_type("Base", "Base::biomes::biome_map"); + if (type == nullptr) { + return {}; + } auto factory_function = type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); diff --git a/src/world/terrain/generation/interface.cpp b/src/world/terrain/generation/interface.cpp index 3a253486..9a22e7d1 100644 --- a/src/world/terrain/generation/interface.cpp +++ b/src/world/terrain/generation/interface.cpp @@ -1,6 +1,8 @@ #include "interface.hpp" +#include "logging.hpp" #include "noise.hpp" +#include "util/angel_script/error_checks.hpp" #include "worley_noise.hpp" namespace terrain { @@ -30,84 +32,126 @@ AlternativeWorleyNoise_factory(NoisePosition x, double y, NoisePosition z) { void init_as_interface(AngelScript::asIScriptEngine* engine) { - int r = engine->SetDefaultNamespace("TerrainGeneration"); - assert(r >= 0); + if (util::scripting::check_SetDefaultNamespace( + engine->SetDefaultNamespace("TerrainGeneration") + ) + < 0) { + return; + } // Registering the class method - r = engine->RegisterObjectType("FractalNoise", 0, AngelScript::asOBJ_REF); - assert(r >= 0); - r = engine->RegisterObjectBehaviour( - "FractalNoise", AngelScript::asBEHAVE_FACTORY, - "FractalNoise@ f(int, double, int)", - AngelScript::asFUNCTION(FractalNoise_factory), AngelScript::asCALL_CDECL - ); - assert(r >= 0); - r = engine->RegisterObjectBehaviour( - "FractalNoise", AngelScript::asBEHAVE_ADDREF, "void f()", - AngelScript::asMETHOD(FractalNoise, add_ref), AngelScript::asCALL_THISCALL - ); - assert(r >= 0); - r = engine->RegisterObjectBehaviour( - "FractalNoise", AngelScript::asBEHAVE_RELEASE, "void f()", - AngelScript::asMETHOD(FractalNoise, release_ref), AngelScript::asCALL_THISCALL - ); - assert(r >= 0); - r = engine->RegisterObjectMethod( - "FractalNoise", "double sample(double, double)", - AngelScript::asMETHOD(FractalNoise, get_noise), AngelScript::asCALL_THISCALL - ); - assert(r >= 0); + if (util::scripting::check_RegisterObjectType( + engine->RegisterObjectType("FractalNoise", 0, AngelScript::asOBJ_REF) + ) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( + "FractalNoise", AngelScript::asBEHAVE_FACTORY, + "FractalNoise@ f(int, double, int)", + AngelScript::asFUNCTION(FractalNoise_factory), AngelScript::asCALL_CDECL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( + "FractalNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(FractalNoise, add_ref), AngelScript::asCALL_THISCALL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( + "FractalNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(FractalNoise, release_ref), + AngelScript::asCALL_THISCALL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectMethod(engine->RegisterObjectMethod( + "FractalNoise", "double sample(double, double)", + AngelScript::asMETHOD(FractalNoise, get_noise), AngelScript::asCALL_THISCALL + )) + < 0) { + return; + } - r = engine->RegisterObjectType("WorleyNoise", 0, AngelScript::asOBJ_REF); - assert(r >= 0); - r = engine->RegisterObjectBehaviour( - "WorleyNoise", AngelScript::asBEHAVE_FACTORY, "WorleyNoise@ f(double, double)", - AngelScript::asFUNCTION(WorleyNoise_factory), AngelScript::asCALL_CDECL - ); - assert(r >= 0); - r = engine->RegisterObjectBehaviour( - "WorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", - AngelScript::asMETHOD(WorleyNoise, add_ref), AngelScript::asCALL_THISCALL - ); - assert(r >= 0); - r = engine->RegisterObjectBehaviour( - "WorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", - AngelScript::asMETHOD(WorleyNoise, release_ref), AngelScript::asCALL_THISCALL - ); - assert(r >= 0); - r = engine->RegisterObjectMethod( - "WorleyNoise", "double sample(double, double)", - AngelScript::asMETHOD(WorleyNoise, get_noise), AngelScript::asCALL_THISCALL - ); - assert(r >= 0); - - r = engine->RegisterObjectType("AlternativeWorleyNoise", 0, AngelScript::asOBJ_REF); - assert(r >= 0); - r = engine->RegisterObjectBehaviour( - "AlternativeWorleyNoise", AngelScript::asBEHAVE_FACTORY, - "AlternativeWorleyNoise@ f(double, double, double)", - AngelScript::asFUNCTION(AlternativeWorleyNoise_factory), - AngelScript::asCALL_CDECL - ); - assert(r >= 0); - r = engine->RegisterObjectBehaviour( - "AlternativeWorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", - AngelScript::asMETHOD(AlternativeWorleyNoise, add_ref), - AngelScript::asCALL_THISCALL - ); - assert(r >= 0); - r = engine->RegisterObjectBehaviour( - "AlternativeWorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", - AngelScript::asMETHOD(AlternativeWorleyNoise, release_ref), - AngelScript::asCALL_THISCALL - ); - assert(r >= 0); - r = engine->RegisterObjectMethod( - "AlternativeWorleyNoise", "double sample(double, double)", - AngelScript::asMETHOD(AlternativeWorleyNoise, get_noise), - AngelScript::asCALL_THISCALL - ); - assert(r >= 0); + if (util::scripting::check_RegisterObjectType( + engine->RegisterObjectType("WorleyNoise", 0, AngelScript::asOBJ_REF) + ) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( + "WorleyNoise", AngelScript::asBEHAVE_FACTORY, + "WorleyNoise@ f(double, double)", + AngelScript::asFUNCTION(WorleyNoise_factory), AngelScript::asCALL_CDECL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( + "WorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(WorleyNoise, add_ref), AngelScript::asCALL_THISCALL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( + "WorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(WorleyNoise, release_ref), + AngelScript::asCALL_THISCALL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectMethod(engine->RegisterObjectMethod( + "WorleyNoise", "double sample(double, double)", + AngelScript::asMETHOD(WorleyNoise, get_noise), AngelScript::asCALL_THISCALL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectType(engine->RegisterObjectType( + "AlternativeWorleyNoise", 0, AngelScript::asOBJ_REF + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", AngelScript::asBEHAVE_FACTORY, + "AlternativeWorleyNoise@ f(double, double, double)", + AngelScript::asFUNCTION(AlternativeWorleyNoise_factory), + AngelScript::asCALL_CDECL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(AlternativeWorleyNoise, add_ref), + AngelScript::asCALL_THISCALL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(AlternativeWorleyNoise, release_ref), + AngelScript::asCALL_THISCALL + )) + < 0) { + return; + } + if (util::scripting::check_RegisterObjectMethod(engine->RegisterObjectMethod( + "AlternativeWorleyNoise", "double sample(double, double)", + AngelScript::asMETHOD(AlternativeWorleyNoise, get_noise), + AngelScript::asCALL_THISCALL + )) + < 0) { + return; + } } } // namespace generation diff --git a/src/world/terrain/terrain.cpp b/src/world/terrain/terrain.cpp index d36f7b5f..7447f23a 100644 --- a/src/world/terrain/terrain.cpp +++ b/src/world/terrain/terrain.cpp @@ -191,6 +191,7 @@ Terrain::qb_read( } }); } + // TODO instead of waiting should collect futures context.wait_for_tasks(); for (ColorInt color : unknown_colors) { From 2dc1f609f9d26de2e9ca9a410748a3c6c838b627 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Mon, 25 May 2026 20:28:55 -0400 Subject: [PATCH 21/25] suggested changes --- src/manifest/object_handler.cpp | 1 - src/util/angel_script/as_logging.cpp | 157 +++++++++----------- src/util/angel_script/as_logging.hpp | 5 + src/util/angel_script/error_checks.cpp | 16 ++ src/util/angel_script/error_checks.hpp | 2 + src/world/terrain/generation/interface.cpp | 161 ++++++++++----------- 6 files changed, 168 insertions(+), 174 deletions(-) diff --git a/src/manifest/object_handler.cpp b/src/manifest/object_handler.cpp index 38426ec0..3ac5ded1 100644 --- a/src/manifest/object_handler.cpp +++ b/src/manifest/object_handler.cpp @@ -31,7 +31,6 @@ ObjectHandler::read_biome(const descriptor_t& biome_descriptor) { std::filesystem::path path_copy = biome_descriptor.path; - // TODO just need to know what module to load this into context.load_file( "Base", files::get_data_path() / path_copy.remove_filename() diff --git a/src/util/angel_script/as_logging.cpp b/src/util/angel_script/as_logging.cpp index 7e587ea5..8d409f7d 100644 --- a/src/util/angel_script/as_logging.cpp +++ b/src/util/angel_script/as_logging.cpp @@ -1,3 +1,4 @@ +#include "error_checks.hpp" #include "local_context.hpp" #include "logging.hpp" @@ -10,72 +11,6 @@ namespace scripting { namespace { -/** - * @brief Backtrace Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_backtrace(std::string message); - -/** - * @brief Info Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_info(std::string message); - -/** - * @brief Debug Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_debug(std::string message); - -/** - * @brief Warning Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_warning(std::string message); - -/** - * @brief Error Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_error(std::string message); - -/** - * @brief Critical Log API - * - * @param std::string message message to be logged - * - * @details Given a message this will log it to the log file. This function will - * determine the AngelScript line and file from the calling context. - */ -void as_log_critical(std::string message); - -/** - * @brief Initialize Logging interface on given engine - * - * @param asIScriptEngine* engine the engine logging will be initialized on. - */ - struct script_location_t { std::string file; int line; @@ -103,6 +38,14 @@ get_script_location() { return location_data; } +/** + * @brief Backtrace Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_backtrace(std::string message) { script_location_t location = get_script_location(); @@ -112,6 +55,14 @@ as_log_backtrace(std::string message) { ); } +/** + * @brief Info Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_info(std::string message) { script_location_t location = get_script_location(); @@ -121,6 +72,14 @@ as_log_info(std::string message) { ); } +/** + * @brief Debug Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_debug(std::string message) { script_location_t location = get_script_location(); @@ -130,6 +89,14 @@ as_log_debug(std::string message) { ); } +/** + * @brief Warning Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_warning(std::string message) { script_location_t location = get_script_location(); @@ -139,6 +106,14 @@ as_log_warning(std::string message) { ); } +/** + * @brief Error Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_error(std::string message) { script_location_t location = get_script_location(); @@ -148,6 +123,14 @@ as_log_error(std::string message) { ); } +/** + * @brief Critical Log API + * + * @param std::string message message to be logged + * + * @details Given a message this will log it to the log file. This function will + * determine the AngelScript line and file from the calling context. + */ void as_log_critical(std::string message) { script_location_t location = get_script_location(); @@ -161,52 +144,52 @@ as_log_critical(std::string message) { void init_as_interface(AngelScript::asIScriptEngine* engine) { - // Return values - // asINVALID_ARG The namespace is null. - // asINVALID_DECLARATION The namespace is invalid. int r = engine->SetDefaultNamespace("LOGGING"); - assert(r >= 0); - - // Return values - // asNOT_SUPPORTED The calling convention is not supported. - // asWRONG_CALLING_CONV The function's calling convention doesn't match - // callConv. asINVALID_DECLARATION The function declaration is invalid. - // asNAME_TAKEN The function name is already used elsewhere. - // asALREADY_REGISTERED The function has already been registered with the same - // parameter list. asINVALID_ARG The auxiliary pointer wasn't set - // according to calling convention. - - // Registering + if (util::scripting::check_SetDefaultNamespace(r) < 0) { + return; + } r = engine->RegisterGlobalFunction( "void LOG_BACKTRACE(string)", AngelScript::asFUNCTION(as_log_backtrace), AngelScript::asCALL_CDECL ); - assert(r >= 0); + if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + return; + } r = engine->RegisterGlobalFunction( "void LOG_INFO(string)", AngelScript::asFUNCTION(as_log_info), AngelScript::asCALL_CDECL ); - assert(r >= 0); + if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + return; + } r = engine->RegisterGlobalFunction( "void LOG_DEBUG(string)", AngelScript::asFUNCTION(as_log_debug), AngelScript::asCALL_CDECL ); - assert(r >= 0); + if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + return; + } r = engine->RegisterGlobalFunction( "void LOG_WARNING(string)", AngelScript::asFUNCTION(as_log_warning), AngelScript::asCALL_CDECL ); - assert(r >= 0); + if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + return; + } r = engine->RegisterGlobalFunction( "void LOG_ERROR(string)", AngelScript::asFUNCTION(as_log_error), AngelScript::asCALL_CDECL ); - assert(r >= 0); + if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + return; + } r = engine->RegisterGlobalFunction( "void LOG_CRITICAL(string)", AngelScript::asFUNCTION(as_log_critical), AngelScript::asCALL_CDECL ); - assert(r >= 0); + if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + return; + } } } // namespace scripting diff --git a/src/util/angel_script/as_logging.hpp b/src/util/angel_script/as_logging.hpp index 8521ce56..7348d93a 100644 --- a/src/util/angel_script/as_logging.hpp +++ b/src/util/angel_script/as_logging.hpp @@ -29,6 +29,11 @@ namespace util { namespace scripting { +/** + * @brief Initialize Logging interface on given engine + * + * @param asIScriptEngine* engine the engine logging will be initialized on. + */ void init_as_interface(AngelScript::asIScriptEngine* engine); } // namespace scripting diff --git a/src/util/angel_script/error_checks.cpp b/src/util/angel_script/error_checks.cpp index 4896dc6e..d36591c6 100644 --- a/src/util/angel_script/error_checks.cpp +++ b/src/util/angel_script/error_checks.cpp @@ -15,6 +15,22 @@ check_SetDefaultNamespace(int r) { return static_cast(r); } +AngelScript::asERetCodes +check_RegisterGlobalFunction(int r) { + switch (r) { + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR(logging::as_logger, "The namespace is null."); + break; + case AngelScript::asERetCodes::asINVALID_DECLARATION: + LOG_ERROR(logging::as_logger, "The namespace is invalid."); + break; + + default: + break; + } + return static_cast(r); +} + AngelScript::asERetCodes check_RegisterObjectType(int r) { switch (r) { diff --git a/src/util/angel_script/error_checks.hpp b/src/util/angel_script/error_checks.hpp index 4024e63b..8c0e95e7 100644 --- a/src/util/angel_script/error_checks.hpp +++ b/src/util/angel_script/error_checks.hpp @@ -9,6 +9,8 @@ namespace scripting { AngelScript::asERetCodes check_SetDefaultNamespace(int); +AngelScript::asERetCodes check_RegisterGlobalFunction(int); + AngelScript::asERetCodes check_RegisterObjectType(int); AngelScript::asERetCodes check_RegisterObjectBehaviour(int); diff --git a/src/world/terrain/generation/interface.cpp b/src/world/terrain/generation/interface.cpp index 9a22e7d1..8673105d 100644 --- a/src/world/terrain/generation/interface.cpp +++ b/src/world/terrain/generation/interface.cpp @@ -32,124 +32,113 @@ AlternativeWorleyNoise_factory(NoisePosition x, double y, NoisePosition z) { void init_as_interface(AngelScript::asIScriptEngine* engine) { - if (util::scripting::check_SetDefaultNamespace( - engine->SetDefaultNamespace("TerrainGeneration") - ) - < 0) { + int r = engine->SetDefaultNamespace("TerrainGeneration"); + + if (util::scripting::check_SetDefaultNamespace(r) < 0) { return; } + r = engine->RegisterObjectType("FractalNoise", 0, AngelScript::asOBJ_REF); - // Registering the class method - if (util::scripting::check_RegisterObjectType( - engine->RegisterObjectType("FractalNoise", 0, AngelScript::asOBJ_REF) - ) - < 0) { + if (util::scripting::check_RegisterObjectType(r) < 0) { return; } - if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( - "FractalNoise", AngelScript::asBEHAVE_FACTORY, - "FractalNoise@ f(int, double, int)", - AngelScript::asFUNCTION(FractalNoise_factory), AngelScript::asCALL_CDECL - )) - < 0) { + r = engine->RegisterObjectBehaviour( + "FractalNoise", AngelScript::asBEHAVE_FACTORY, + "FractalNoise@ f(int, double, int)", + AngelScript::asFUNCTION(FractalNoise_factory), AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { return; } - if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( - "FractalNoise", AngelScript::asBEHAVE_ADDREF, "void f()", - AngelScript::asMETHOD(FractalNoise, add_ref), AngelScript::asCALL_THISCALL - )) - < 0) { + r = engine->RegisterObjectBehaviour( + "FractalNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(FractalNoise, add_ref), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { return; } - if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( - "FractalNoise", AngelScript::asBEHAVE_RELEASE, "void f()", - AngelScript::asMETHOD(FractalNoise, release_ref), - AngelScript::asCALL_THISCALL - )) - < 0) { + r = engine->RegisterObjectBehaviour( + "FractalNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(FractalNoise, release_ref), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { return; } - if (util::scripting::check_RegisterObjectMethod(engine->RegisterObjectMethod( - "FractalNoise", "double sample(double, double)", - AngelScript::asMETHOD(FractalNoise, get_noise), AngelScript::asCALL_THISCALL - )) - < 0) { + r = engine->RegisterObjectMethod( + "FractalNoise", "double sample(double, double)", + AngelScript::asMETHOD(FractalNoise, get_noise), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectMethod(r) < 0) { return; } + r = engine->RegisterObjectType("WorleyNoise", 0, AngelScript::asOBJ_REF); - if (util::scripting::check_RegisterObjectType( - engine->RegisterObjectType("WorleyNoise", 0, AngelScript::asOBJ_REF) - ) - < 0) { + if (util::scripting::check_RegisterObjectType(r) < 0) { return; } - if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( - "WorleyNoise", AngelScript::asBEHAVE_FACTORY, - "WorleyNoise@ f(double, double)", - AngelScript::asFUNCTION(WorleyNoise_factory), AngelScript::asCALL_CDECL - )) - < 0) { + r = engine->RegisterObjectBehaviour( + "WorleyNoise", AngelScript::asBEHAVE_FACTORY, "WorleyNoise@ f(double, double)", + AngelScript::asFUNCTION(WorleyNoise_factory), AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { return; } - if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( - "WorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", - AngelScript::asMETHOD(WorleyNoise, add_ref), AngelScript::asCALL_THISCALL - )) - < 0) { + r = engine->RegisterObjectBehaviour( + "WorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(WorleyNoise, add_ref), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { return; } - if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( - "WorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", - AngelScript::asMETHOD(WorleyNoise, release_ref), - AngelScript::asCALL_THISCALL - )) - < 0) { + r = engine->RegisterObjectBehaviour( + "WorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(WorleyNoise, release_ref), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { return; } - if (util::scripting::check_RegisterObjectMethod(engine->RegisterObjectMethod( - "WorleyNoise", "double sample(double, double)", - AngelScript::asMETHOD(WorleyNoise, get_noise), AngelScript::asCALL_THISCALL - )) - < 0) { + r = engine->RegisterObjectMethod( + "WorleyNoise", "double sample(double, double)", + AngelScript::asMETHOD(WorleyNoise, get_noise), AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectMethod(r) < 0) { return; } - if (util::scripting::check_RegisterObjectType(engine->RegisterObjectType( - "AlternativeWorleyNoise", 0, AngelScript::asOBJ_REF - )) - < 0) { + r = engine->RegisterObjectType("AlternativeWorleyNoise", 0, AngelScript::asOBJ_REF); + if (util::scripting::check_RegisterObjectType(r) < 0) { return; } - if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( - "AlternativeWorleyNoise", AngelScript::asBEHAVE_FACTORY, - "AlternativeWorleyNoise@ f(double, double, double)", - AngelScript::asFUNCTION(AlternativeWorleyNoise_factory), - AngelScript::asCALL_CDECL - )) - < 0) { + r = engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", AngelScript::asBEHAVE_FACTORY, + "AlternativeWorleyNoise@ f(double, double, double)", + AngelScript::asFUNCTION(AlternativeWorleyNoise_factory), + AngelScript::asCALL_CDECL + ); + if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { return; } - if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( - "AlternativeWorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", - AngelScript::asMETHOD(AlternativeWorleyNoise, add_ref), - AngelScript::asCALL_THISCALL - )) - < 0) { + r = engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", + AngelScript::asMETHOD(AlternativeWorleyNoise, add_ref), + AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { return; } - if (util::scripting::check_RegisterObjectBehaviour(engine->RegisterObjectBehaviour( - "AlternativeWorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", - AngelScript::asMETHOD(AlternativeWorleyNoise, release_ref), - AngelScript::asCALL_THISCALL - )) - < 0) { + r = engine->RegisterObjectBehaviour( + "AlternativeWorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", + AngelScript::asMETHOD(AlternativeWorleyNoise, release_ref), + AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { return; } - if (util::scripting::check_RegisterObjectMethod(engine->RegisterObjectMethod( - "AlternativeWorleyNoise", "double sample(double, double)", - AngelScript::asMETHOD(AlternativeWorleyNoise, get_noise), - AngelScript::asCALL_THISCALL - )) - < 0) { + r = engine->RegisterObjectMethod( + "AlternativeWorleyNoise", "double sample(double, double)", + AngelScript::asMETHOD(AlternativeWorleyNoise, get_noise), + AngelScript::asCALL_THISCALL + ); + if (util::scripting::check_RegisterObjectMethod(r) < 0) { return; } } From 1c759f670320a829b10b60ddfc4ceb1de94f68ed Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Mon, 25 May 2026 20:48:53 -0400 Subject: [PATCH 22/25] error checking --- src/global_context.cpp | 36 ++-------------- src/local_context.hpp | 2 +- src/util/angel_script/error_checks.cpp | 58 ++++++++++++++++++++++++-- src/util/angel_script/error_checks.hpp | 2 + 4 files changed, 62 insertions(+), 36 deletions(-) diff --git a/src/global_context.cpp b/src/global_context.cpp index ab2054c9..1f881adf 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -1,5 +1,6 @@ #include "global_context.hpp" +#include "util/angel_script/error_checks.hpp" #include "local_context.hpp" #include "logging.hpp" #include "scriptstdstring.h" @@ -101,40 +102,11 @@ GlobalContext::load_file(const std::string& mod_name, std::filesystem::path path mod->AddScriptSection(path.filename().c_str(), script.str().c_str()); AngelScript::asERetCodes result = - static_cast(mod->Build()); + util::scripting::check_ScriptModule_Build(mod->Build()); - switch (result) { - case AngelScript::asINVALID_CONFIGURATION: - LOG_ERROR(logging::as_logger, "The engine configuration is invalid."); - return result; - case AngelScript::asERROR: - LOG_ERROR(logging::as_logger, "The script failed to build."); - return result; - case AngelScript::asBUILD_IN_PROGRESS: - LOG_ERROR(logging::as_logger, "Another thread is currently building."); - return result; - case AngelScript::asINIT_GLOBAL_VARS_FAILED: - LOG_ERROR( - logging::as_logger, "It was not possible to initialize at least one of " - "the global variables." - ); - return result; - case AngelScript::asNOT_SUPPORTED: - LOG_ERROR( - logging::as_logger, "Compiler support is disabled in the engine." - ); - return result; - case AngelScript::asMODULE_IS_IN_USE: - LOG_ERROR( - logging::as_logger, - "The code in the module is still being used and and cannot be removed." - ); - return result; - - default: - break; + if (result < 0) { + return result; } - return AngelScript::asERetCodes::asSUCCESS; } diff --git a/src/local_context.hpp b/src/local_context.hpp index a60b08cd..033a7f04 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -103,7 +103,7 @@ class LocalContext { } inline AngelScript::asERetCodes - set_arg(size_t i, std::string arg) { + set_arg(size_t i, std::string& arg) { return static_cast(context_->SetArgObject(i, &arg)); } diff --git a/src/util/angel_script/error_checks.cpp b/src/util/angel_script/error_checks.cpp index d36591c6..19f351c4 100644 --- a/src/util/angel_script/error_checks.cpp +++ b/src/util/angel_script/error_checks.cpp @@ -9,8 +9,15 @@ namespace scripting { AngelScript::asERetCodes check_SetDefaultNamespace(int r) { - if (r == AngelScript::asERetCodes::asINVALID_ARG) { - LOG_ERROR(logging::as_logger, "The namespace is invalid."); + switch (r) { + case AngelScript::asERetCodes::asINVALID_ARG: + LOG_ERROR(logging::as_logger, "The namespace is invalid."); + break; + case AngelScript::asERetCodes::asSUCCESS: + break; + default: + LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); + break; } return static_cast(r); } @@ -24,8 +31,10 @@ check_RegisterGlobalFunction(int r) { case AngelScript::asERetCodes::asINVALID_DECLARATION: LOG_ERROR(logging::as_logger, "The namespace is invalid."); break; - + case AngelScript::asERetCodes::asSUCCESS: + break; default: + LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); break; } return static_cast(r); @@ -65,7 +74,10 @@ check_RegisterObjectType(int r) { "use preventing it from being overloaded." ); break; + case AngelScript::asERetCodes::asSUCCESS: + break; default: + LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); break; } return static_cast(r); @@ -118,7 +130,10 @@ check_RegisterObjectBehaviour(int r) { "The behaviour is already registered with the same signature." ); break; + case AngelScript::asERetCodes::asSUCCESS: + break; default: + LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); break; } return static_cast(r); @@ -165,12 +180,49 @@ check_RegisterObjectMethod(int r) { "The auxiliary pointer wasn't set according to calling convention." ); break; + case AngelScript::asERetCodes::asSUCCESS: + break; + default: + LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); + break; + } + return static_cast(r); +} + +AngelScript::asERetCodes +check_ScriptModule_Build(int r) { + + switch (r) { + case AngelScript::asINVALID_CONFIGURATION: + LOG_ERROR(logging::as_logger, "The engine configuration is invalid."); + case AngelScript::asERROR: + LOG_ERROR(logging::as_logger, "The script failed to build."); + case AngelScript::asBUILD_IN_PROGRESS: + LOG_ERROR(logging::as_logger, "Another thread is currently building."); + case AngelScript::asINIT_GLOBAL_VARS_FAILED: + LOG_ERROR( + logging::as_logger, "It was not possible to initialize at least one of " + "the global variables." + ); + case AngelScript::asNOT_SUPPORTED: + LOG_ERROR( + logging::as_logger, "Compiler support is disabled in the engine." + ); + case AngelScript::asMODULE_IS_IN_USE: + LOG_ERROR( + logging::as_logger, + "The code in the module is still being used and and cannot be removed." + ); + case AngelScript::asERetCodes::asSUCCESS: + break; default: + LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); break; } return static_cast(r); } + // AngelScript::asERetCodes check_RegisterObjectType(int r) { //} diff --git a/src/util/angel_script/error_checks.hpp b/src/util/angel_script/error_checks.hpp index 8c0e95e7..d6992b99 100644 --- a/src/util/angel_script/error_checks.hpp +++ b/src/util/angel_script/error_checks.hpp @@ -9,6 +9,8 @@ namespace scripting { AngelScript::asERetCodes check_SetDefaultNamespace(int); +AngelScript::asERetCodes check_ScriptModule_Build(int); + AngelScript::asERetCodes check_RegisterGlobalFunction(int); AngelScript::asERetCodes check_RegisterObjectType(int); From 5cf688c7c11a4bc528a24c85c6ec6b42979b0f92 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Mon, 25 May 2026 23:30:42 -0400 Subject: [PATCH 23/25] remove message callback from global context --- src/global_context.hpp | 2 - src/local_context.hpp | 17 +++-- src/util/angel_script/as_logging.hpp | 2 - src/util/angel_script/as_tests.cpp | 106 ++++++--------------------- 4 files changed, 33 insertions(+), 94 deletions(-) diff --git a/src/global_context.hpp b/src/global_context.hpp index a7726959..0afd2ae9 100644 --- a/src/global_context.hpp +++ b/src/global_context.hpp @@ -37,8 +37,6 @@ #include #include -void MessageCallback(const AngelScript::asSMessageInfo* msg, void* param); - /** * @brief Any global context that are needed will go in this class. * diff --git a/src/local_context.hpp b/src/local_context.hpp index 033a7f04..ab909fcc 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -238,22 +238,29 @@ class LocalContext { // template AngelScript::asEContextState get_return_value(int& value) { - // if this is zero then could be right could be wrong. + AngelScript::asEContextState state = context_->GetState(); + if (state != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return state; + } value = context_->GetReturnDWord(); return AngelScript::asEContextState::asEXECUTION_FINISHED; } AngelScript::asEContextState get_return_value(bool& value) { - // if this is zero then could be right could be wrong. - value = context_->GetReturnByte(); + AngelScript::asEContextState state = context_->GetState(); + if (state != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return state; + } value = context_->GetReturnByte(); return AngelScript::asEContextState::asEXECUTION_FINISHED; } AngelScript::asEContextState get_return_value(float& value) { - // if this is zero then could be right could be wrong. - value = context_->GetReturnFloat(); + AngelScript::asEContextState state = context_->GetState(); + if (state != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return state; + } value = context_->GetReturnFloat(); return AngelScript::asEContextState::asEXECUTION_FINISHED; } diff --git a/src/util/angel_script/as_logging.hpp b/src/util/angel_script/as_logging.hpp index 7348d93a..1bd0487f 100644 --- a/src/util/angel_script/as_logging.hpp +++ b/src/util/angel_script/as_logging.hpp @@ -24,8 +24,6 @@ #include -#include - namespace util { namespace scripting { diff --git a/src/util/angel_script/as_tests.cpp b/src/util/angel_script/as_tests.cpp index 0c80e21e..69579817 100644 --- a/src/util/angel_script/as_tests.cpp +++ b/src/util/angel_script/as_tests.cpp @@ -106,118 +106,54 @@ as_loadtime_test() { int logging_test() { - // as_logging::as_log_backtrace("Backtrace"); - LOG_ERROR(logging::script_logger, ""); - - AngelScript::asIScriptEngine* engine = AngelScript::asCreateScriptEngine(); - engine->SetMessageCallback( - asFUNCTION(MessageCallback), 0, AngelScript::asCALL_CDECL - ); - RegisterStdString(engine); - init_as_interface(engine); + GlobalContext& context = GlobalContext::instance(); + LocalContext& local_context = LocalContext::instance(); - if (!engine) { - LOG_ERROR(logging::main_logger, "Could no start Angle Script engine."); - return 1; - } + auto result_1 = context.load_file("test_module", files::get_resources_path() / "as" / "test.as"); - AngelScript::asIScriptModule* mod = - engine->GetModule("test_module", AngelScript::asGM_CREATE_IF_NOT_EXISTS); - std::ostringstream script; - auto file = files::open_file(files::get_resources_path() / "as" / "test.as"); - if (!file) { - engine->ShutDownAndRelease(); - return 1; - } - - script << file.value().rdbuf(); - mod->AddScriptSection("test.as", script.str().c_str()); + AngelScript::asIScriptFunction* funct1 = + context.get_function("test_module", "int test3()"); - int result = mod->Build(); - if (result > 0) { - engine->ShutDownAndRelease(); + if (funct1 == nullptr) { return 1; } - - AngelScript::asIScriptFunction* funct1 = - engine->GetModule("test_module")->GetFunctionByDecl("int test3()"); - - AngelScript::asIScriptContext* ctx = engine->CreateContext(); - ctx->Prepare(funct1); - // ctx->SetArgDWord(); - result = ctx->Execute(); - if (result != AngelScript::asEXECUTION_FINISHED) { - ctx->Release(); - engine->ShutDownAndRelease(); + auto result_2 = local_context.run_function(funct1); + if (result_2 != AngelScript::asEXECUTION_FINISHED) { return 1; } - ctx->Release(); - engine->ShutDownAndRelease(); return 0; } int test() { - AngelScript::asIScriptEngine* engine = AngelScript::asCreateScriptEngine(); - engine->SetMessageCallback( - asFUNCTION(MessageCallback), 0, AngelScript::asCALL_CDECL - ); + LOG_ERROR(logging::script_logger, ""); - if (!engine) { - LOG_ERROR(logging::main_logger, "Could no start Angle Script engine."); - return 1; - } + GlobalContext& context = GlobalContext::instance(); + LocalContext& local_context = LocalContext::instance(); - AngelScript::asIScriptModule* mod = - engine->GetModule("test_module", AngelScript::asGM_CREATE_IF_NOT_EXISTS); - std::ostringstream script; - auto file = files::open_file(files::get_resources_path() / "as" / "test.as"); - if (!file) { - engine->ShutDownAndRelease(); - return 1; - } + auto result_1 = context.load_file("test_module", files::get_resources_path() / "as" / "test.as"); - script << file.value().rdbuf(); - mod->AddScriptSection("test.as", script.str().c_str()); + AngelScript::asIScriptFunction* funct1 = + context.get_function("test_module", "int test1()"); - int result = mod->Build(); - if (result > 0) { - engine->ShutDownAndRelease(); + if (funct1 == nullptr) { return 1; } - - AngelScript::asIScriptFunction* funct1 = - engine->GetModule("test_module")->GetFunctionByDecl("void test1()"); - - AngelScript::asIScriptContext* ctx = engine->CreateContext(); - ctx->Prepare(funct1); - // ctx->SetArgDWord(); - result = ctx->Execute(); - if (result != AngelScript::asEXECUTION_FINISHED) { - ctx->Release(); - engine->ShutDownAndRelease(); + auto result_2 = local_context.run_function(funct1); + if (result_2 != AngelScript::asEXECUTION_FINISHED) { return 1; } - AngelScript::asIScriptFunction* funct2 = - engine->GetModule("test_module")->GetFunctionByDecl("int test2()"); + context.get_function("test_module", "int test1()"); - ctx->Prepare(funct2); - // ctx->SetArgDWord(); - result = ctx->Execute(); - if (result != AngelScript::asEXECUTION_FINISHED) { - ctx->Release(); - engine->ShutDownAndRelease(); + if (funct2 == nullptr) { return 1; } - int returnvalue = ctx->GetReturnDWord(); - if (returnvalue == 1 || returnvalue == 0) { - ctx->Release(); - engine->ShutDownAndRelease(); + result_2 = local_context.run_function(funct2); + if (result_2 != AngelScript::asEXECUTION_FINISHED) { return 1; } - engine->ShutDownAndRelease(); return 0; } From b26c21d7203453d905ab62360ccf4f82d1315bba Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Fri, 29 May 2026 21:16:02 -0400 Subject: [PATCH 24/25] one run function --- src/global_context.cpp | 2 +- src/local_context.hpp | 157 ++++++++++++++----------- src/util/angel_script/as_tests.cpp | 94 +++++++++------ src/util/angel_script/error_checks.cpp | 48 ++++++-- src/world/biome.cpp | 53 +++------ 5 files changed, 200 insertions(+), 154 deletions(-) diff --git a/src/global_context.cpp b/src/global_context.cpp index 1f881adf..201f63fa 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -1,10 +1,10 @@ #include "global_context.hpp" -#include "util/angel_script/error_checks.hpp" #include "local_context.hpp" #include "logging.hpp" #include "scriptstdstring.h" #include "util/angel_script/as_logging.hpp" +#include "util/angel_script/error_checks.hpp" #include "util/files.hpp" #include "world/terrain/generation/interface.hpp" diff --git a/src/local_context.hpp b/src/local_context.hpp index ab909fcc..3518db5a 100644 --- a/src/local_context.hpp +++ b/src/local_context.hpp @@ -138,45 +138,51 @@ class LocalContext { [[nodiscard]] static LocalContext& instance(); ~LocalContext(); - template + template inline std::expected - run_function(AngelScript::asIScriptFunction* function) { - context_->Prepare(function); - // set args maybe + run_function(AngelScript::asIScriptFunction* function, const Args&&... args) { AngelScript::asEContextState result = - static_cast(context_->Execute()); + static_cast(context_->Prepare(function)); if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { return std::unexpected(result); } - T object = *static_cast(context_->GetReturnObject()); + if constexpr (sizeof...(args) != 0) { + AngelScript::asERetCodes args_result = + set_all_args(0, std::forward(args)...); + if (args_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_WARNING( + logging::as_logger, "Setting script arguments did not secseed." + ); + return std::unexpected(AngelScript::asEContextState::asEXECUTION_ERROR); + } + } - return object; - } + result = static_cast(context_->Execute()); - AngelScript::asEContextState - run_function(AngelScript::asIScriptFunction* function) { - context_->Prepare(function); - AngelScript::asEContextState result = - static_cast(context_->Execute()); - return result; - } + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return std::unexpected(result); + } - template - inline AngelScript::asEContextState - run_function(AngelScript::asIScriptFunction* function, const Args&&... args) { - context_->Prepare(function); - AngelScript::asERetCodes args_result = - set_all_args(0, std::forward(args)...); - if (args_result != AngelScript::asERetCodes::asSUCCESS) { - LOG_WARNING( - logging::as_logger, "Setting script arguments did not secseed." - ); - return AngelScript::asEContextState::asEXECUTION_SUSPENDED; + if constexpr (std::is_same::value) { + return nullptr; } - AngelScript::asEContextState result = - static_cast(context_->Execute()); - return result; + AngelScript::asEContextState error; + if constexpr (std::is_pointer::value) { + void* pointer = context_->GetReturnObject(); + if (pointer) { + T object = *static_cast(pointer); + return object; + } + error = AngelScript::asEContextState::asEXECUTION_ERROR; + } else { + T out; + error = get_return_value(out); + if (error == AngelScript::asEContextState::asEXECUTION_FINISHED) { + return out; + } + } + return std::unexpected(error); } // this might crash. should probably do some tests @@ -189,53 +195,60 @@ class LocalContext { return *(AngelScript::asIScriptObject**)out; } - AngelScript::asEContextState - run_method( - AngelScript::asIScriptObject* object, AngelScript::asIScriptFunction* function - ) { - context_->Prepare(function); - context_->SetObject(object); - AngelScript::asEContextState result = - static_cast(context_->Execute()); - return result; - } - - template - inline AngelScript::asEContextState + template + inline std::expected run_method( AngelScript::asIScriptObject* object, AngelScript::asIScriptFunction* function, const Args&&... args ) { - context_->Prepare(function); - context_->SetObject(object); - AngelScript::asERetCodes args_result = - set_all_args(0, std::forward(args)...); - if (args_result != AngelScript::asERetCodes::asSUCCESS) { - LOG_WARNING( - logging::as_logger, "Setting script arguments did not secseed." - ); - return AngelScript::asEContextState::asEXECUTION_SUSPENDED; - } AngelScript::asEContextState result = - static_cast(context_->Execute()); - return result; + static_cast(context_->Prepare(function)); + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return std::unexpected(result); + } + result = static_cast(context_->SetObject(object)); + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return std::unexpected(result); + } + if constexpr (sizeof...(args) != 0) { + AngelScript::asERetCodes args_result = + set_all_args(0, std::forward(args)...); + if (args_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_WARNING( + logging::as_logger, "Setting script arguments did not secseed." + ); + return std::unexpected(AngelScript::asEContextState::asEXECUTION_ERROR); + } + } + + result = static_cast(context_->Execute()); + + if (result != AngelScript::asEContextState::asEXECUTION_FINISHED) { + return std::unexpected(result); + } + + if constexpr (std::is_same::value) { + return nullptr; + } + + AngelScript::asEContextState error; + if constexpr (std::is_pointer::value) { + void* pointer = context_->GetReturnObject(); + if (pointer) { + T object_out = *static_cast(pointer); + return object_out; + } + error = AngelScript::asEContextState::asEXECUTION_ERROR; + } else { + T out; + error = get_return_value(out); + if (error == AngelScript::asEContextState::asEXECUTION_FINISHED) { + return out; + } + } + return std::unexpected(error); } - // TODO add a check between the return signature of the current function and - // the template type. Maybe in debug mode only - // template - // int get_return_value(T& value) { - // auto address = context_->GetReturnAddress(); - - // if (address == nullptr) { - // return -1; - // } - // good way to seg fault - // value = *((T*)address); - // return 0; - // } - - // template AngelScript::asEContextState get_return_value(int& value) { AngelScript::asEContextState state = context_->GetState(); @@ -251,7 +264,8 @@ class LocalContext { AngelScript::asEContextState state = context_->GetState(); if (state != AngelScript::asEContextState::asEXECUTION_FINISHED) { return state; - } value = context_->GetReturnByte(); + } + value = context_->GetReturnByte(); return AngelScript::asEContextState::asEXECUTION_FINISHED; } @@ -260,7 +274,8 @@ class LocalContext { AngelScript::asEContextState state = context_->GetState(); if (state != AngelScript::asEContextState::asEXECUTION_FINISHED) { return state; - } value = context_->GetReturnFloat(); + } + value = context_->GetReturnFloat(); return AngelScript::asEContextState::asEXECUTION_FINISHED; } diff --git a/src/util/angel_script/as_tests.cpp b/src/util/angel_script/as_tests.cpp index 69579817..6a5dcbc6 100644 --- a/src/util/angel_script/as_tests.cpp +++ b/src/util/angel_script/as_tests.cpp @@ -19,9 +19,14 @@ as_loadtime_test() { LocalContext& local_context = LocalContext::instance(); { - context.load_file( + auto file_result = context.load_file( "test_module", files::get_resources_path() / "as" / "test.as" ); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } + auto is_prime_function = context.get_function("test_module", "bool is_prime(int)"); @@ -29,8 +34,7 @@ as_loadtime_test() { auto function_result = local_context.run_function(is_prime_function, 97); - // TODO write a better error logging mechanism - if (function_result != AngelScript::asEXECUTION_FINISHED) { + if (!function_result) { return 1; } @@ -59,8 +63,7 @@ as_loadtime_test() { auto function_result = local_context.run_function(is_prime_function, 97); - // TODO write a better error logging mechanism - if (function_result != AngelScript::asEXECUTION_FINISHED) { + if (!function_result) { return 1; } @@ -109,16 +112,21 @@ logging_test() { GlobalContext& context = GlobalContext::instance(); LocalContext& local_context = LocalContext::instance(); - auto result_1 = context.load_file("test_module", files::get_resources_path() / "as" / "test.as"); - + auto file_result = context.load_file( + "test_module", files::get_resources_path() / "as" / "test.as" + ); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } AngelScript::asIScriptFunction* funct1 = - context.get_function("test_module", "int test3()"); + context.get_function("test_module", "int test3()"); if (funct1 == nullptr) { return 1; } auto result_2 = local_context.run_function(funct1); - if (result_2 != AngelScript::asEXECUTION_FINISHED) { + if (!result_2) { return 1; } return 0; @@ -131,26 +139,33 @@ test() { GlobalContext& context = GlobalContext::instance(); LocalContext& local_context = LocalContext::instance(); - auto result_1 = context.load_file("test_module", files::get_resources_path() / "as" / "test.as"); + auto result_1 = context.load_file( + "test_module", files::get_resources_path() / "as" / "test.as" + ); + + if (result_1 != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } AngelScript::asIScriptFunction* funct1 = - context.get_function("test_module", "int test1()"); + context.get_function("test_module", "int test1()"); if (funct1 == nullptr) { return 1; } auto result_2 = local_context.run_function(funct1); - if (result_2 != AngelScript::asEXECUTION_FINISHED) { + if (!result_2) { return 1; } AngelScript::asIScriptFunction* funct2 = - context.get_function("test_module", "int test1()"); + context.get_function("test_module", "int test1()"); if (funct2 == nullptr) { return 1; } result_2 = local_context.run_function(funct2); - if (result_2 != AngelScript::asEXECUTION_FINISHED) { + if (!result_2) { return 1; } @@ -160,15 +175,24 @@ test() { int as_threading() { GlobalContext& context = GlobalContext::instance(); - context.load_file("test_module", files::get_resources_path() / "as" / "test.as"); + auto file_result = context.load_file( + "test_module", files::get_resources_path() / "as" / "test.as" + ); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } std::future future = context.submit_task([]() { GlobalContext& context = GlobalContext::instance(); LocalContext& local_context = LocalContext::instance(); auto function = context.get_function("test_module", "int text3()"); - int result = local_context.run_function(function); - return result; + auto result = local_context.run_function(function); + if (!result) { + return 1; + } + return 0; }); int result = future.get(); @@ -181,12 +205,22 @@ as_load_tests() { GlobalContext& context = GlobalContext::instance(); LocalContext& local_context = LocalContext::instance(); - context.load_file("main", files::get_resources_path() / "as" / "test.as"); - context.load_file("Base", files::get_data_path() / "Base" / "biome_map.as"); + auto file_result = + context.load_file("main", files::get_resources_path() / "as" / "test.as"); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } + file_result = + context.load_file("Base", files::get_data_path() / "Base" / "biome_map.as"); + if (file_result != AngelScript::asERetCodes::asSUCCESS) { + LOG_ERROR(logging::script_logger, "Could not open file."); + return 1; + } auto function = context.get_function("Base", "void do_something()"); - int result = local_context.run_function(function); - if (result != AngelScript::asEXECUTION_FINISHED) { + auto result = local_context.run_function(function); + if (!result) { LOG_ERROR(logging::main_logger, "Failed AngelScript Test"); return 1; } @@ -211,7 +245,7 @@ as_load_tests() { LOG_DEBUG(logging::main_logger, "{}", declaration); result = local_context.run_function(factory_function); - if (result != AngelScript::asEXECUTION_FINISHED) { + if (!result) { LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return 1; } @@ -225,22 +259,16 @@ as_load_tests() { AngelScript::asIScriptFunction* method = type->GetMethodByDecl("int sample(int, int)"); - result = local_context.run_method(biome_map, method, 5, 5); - if (result != AngelScript::asEXECUTION_FINISHED) { - LOG_ERROR(logging::main_logger, "Failed AngelScript run sample"); - return 1; - } - - int return_value; - result = local_context.get_return_value(return_value); - if (result != 0) { + auto result_2 = local_context.run_method(biome_map, method, 5, 5); + if (!result) { LOG_ERROR( - logging::main_logger, "Failed to get result from sample. Error: {}", result + logging::main_logger, "Failed AngelScript run sample, with error {}.", + std::to_underlying(result_2.error()) ); return 1; } - LOG_DEBUG(logging::main_logger, "Got result {}.", return_value); + LOG_DEBUG(logging::main_logger, "Got result {}.", result_2.value()); biome_map->Release(); return 0; } diff --git a/src/util/angel_script/error_checks.cpp b/src/util/angel_script/error_checks.cpp index 19f351c4..8cba2b59 100644 --- a/src/util/angel_script/error_checks.cpp +++ b/src/util/angel_script/error_checks.cpp @@ -9,14 +9,19 @@ namespace scripting { AngelScript::asERetCodes check_SetDefaultNamespace(int r) { - switch (r) { - case AngelScript::asERetCodes::asINVALID_ARG: + switch (r) { + case AngelScript::asERetCodes::asINVALID_ARG: LOG_ERROR(logging::as_logger, "The namespace is invalid."); break; case AngelScript::asERetCodes::asSUCCESS: break; default: - LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); break; } return static_cast(r); @@ -34,7 +39,12 @@ check_RegisterGlobalFunction(int r) { case AngelScript::asERetCodes::asSUCCESS: break; default: - LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); break; } return static_cast(r); @@ -77,7 +87,12 @@ check_RegisterObjectType(int r) { case AngelScript::asERetCodes::asSUCCESS: break; default: - LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); break; } return static_cast(r); @@ -133,7 +148,12 @@ check_RegisterObjectBehaviour(int r) { case AngelScript::asERetCodes::asSUCCESS: break; default: - LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); break; } return static_cast(r); @@ -183,7 +203,12 @@ check_RegisterObjectMethod(int r) { case AngelScript::asERetCodes::asSUCCESS: break; default: - LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); break; } return static_cast(r); @@ -191,7 +216,6 @@ check_RegisterObjectMethod(int r) { AngelScript::asERetCodes check_ScriptModule_Build(int r) { - switch (r) { case AngelScript::asINVALID_CONFIGURATION: LOG_ERROR(logging::as_logger, "The engine configuration is invalid."); @@ -216,13 +240,17 @@ check_ScriptModule_Build(int r) { case AngelScript::asERetCodes::asSUCCESS: break; default: - LOG_WARNING(logging::as_logger, "Error {} does not match function call. Are you using the correct error handler?", r); + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); break; } return static_cast(r); } - // AngelScript::asERetCodes check_RegisterObjectType(int r) { //} diff --git a/src/world/biome.cpp b/src/world/biome.cpp index 0cbf0edb..d6fd57d9 100644 --- a/src/world/biome.cpp +++ b/src/world/biome.cpp @@ -95,8 +95,8 @@ Biome::get_map(MacroDim size) const { auto factory_function = type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); - AngelScript::asEContextState result = local_context.run_function(factory_function); - if (result != AngelScript::asEXECUTION_FINISHED) { + auto result = local_context.run_function(factory_function); + if (!result) { LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return {}; } @@ -125,30 +125,18 @@ Biome::get_map(MacroDim size) const { for (MacroDim y = 0; y < y_map_tiles; y++) { int x_copy = x; int y_copy = y; - result = local_context.run_method( + auto result_2 = local_context.run_method( biome_map, method, std::move(x_copy), std::move(y_copy) ); - if (result == AngelScript::asCONTEXT_NOT_PREPARED) { - LOG_ERROR(logging::main_logger, "Context not prepared"); - return {}; - } else if (result == AngelScript::asINVALID_ARG) { - LOG_ERROR(logging::main_logger, "To many arguments"); - return {}; - } else if (result == AngelScript::asINVALID_TYPE) { - LOG_ERROR(logging::main_logger, "Invalid arg type"); - return {}; - } - - int tile_id; - result = local_context.get_return_value(tile_id); - if (result != 0) { + if (!result_2) { LOG_ERROR( - logging::main_logger, "Non zero return value in get map as ({})", - std::to_underlying(result) + logging::main_logger, "Error code {}", + static_cast(result_2.error()) ); return {}; } + int tile_id = result_2.value(); const TileType& tile_type = macro_tile_types_[tile_id]; out.emplace_back(tile_type, seed, x, y); } @@ -173,8 +161,8 @@ Biome::get_plant_map(Dim length) const { auto factory_function = type->GetFactoryByDecl("Base::biomes::biome_map@ biome_map()"); - AngelScript::asEContextState result = local_context.run_function(factory_function); - if (result != AngelScript::asEXECUTION_FINISHED) { + auto result = local_context.run_function(factory_function); + if (!result) { LOG_ERROR(logging::main_logger, "Failed AngelScript getting biome map"); return {}; } @@ -206,32 +194,19 @@ Biome::get_plant_map(Dim length) const { for (MacroDim y = 0; y < y_map_tiles; y++) { int x_copy = x; int y_copy = y; - result = local_context.run_method( + auto result_2 = local_context.run_method( biome_map, script_method, &plant_map_name, std::move(x_copy), std::move(y_copy) ); - if (result == AngelScript::asCONTEXT_NOT_PREPARED) { - LOG_ERROR(logging::main_logger, "Context not prepared"); - return {}; - } else if (result == AngelScript::asINVALID_ARG) { - LOG_ERROR(logging::main_logger, "To many arguments"); - return {}; - } else if (result == AngelScript::asINVALID_TYPE) { - LOG_ERROR(logging::main_logger, "Invalid arg type"); - return {}; - } - - float plant_probability; - result = local_context.get_return_value(plant_probability); - if (result != 0) { + if (!result) { LOG_ERROR( - logging::main_logger, - "Non zero return value in get map as ({})", - std::to_underlying(result) + logging::script_logger, "Error code {}", + static_cast(result.error()) ); return {}; } + float plant_probability = result_2.value(); plant_data.push_back(plant_probability); } } From 93ad8c7d697bcfc34bcf93b81931bf82abfd4a70 Mon Sep 17 00:00:00 2001 From: Alem Snyder Date: Sun, 31 May 2026 11:51:46 -0400 Subject: [PATCH 25/25] change how errors are processed --- src/global_context.cpp | 13 +- src/util/angel_script/as_logging.cpp | 14 +- src/util/angel_script/error_checks.cpp | 184 +++++++++++---------- src/util/angel_script/error_checks.hpp | 14 +- src/world/terrain/generation/interface.cpp | 32 ++-- 5 files changed, 134 insertions(+), 123 deletions(-) diff --git a/src/global_context.cpp b/src/global_context.cpp index 201f63fa..f23ec5b2 100644 --- a/src/global_context.cpp +++ b/src/global_context.cpp @@ -57,9 +57,12 @@ GlobalContext::GlobalContext() : thread_pool_([] { quill::detail::set_thread_name("BS Thread"); }) { AngelScript::asPrepareMultithread(); engine_ = AngelScript::asCreateScriptEngine(); - engine_->SetMessageCallback( + int r = engine_->SetMessageCallback( AngelScript::asFUNCTION(MessageCallback), 0, AngelScript::asCALL_CDECL ); + if (r < 0) { + LOG_ERROR(logging::as_logger, "Could not set Message Callback."); + } RegisterStdString(engine_); terrain::generation::init_as_interface(engine_); util::scripting::init_as_interface(engine_); @@ -101,11 +104,9 @@ GlobalContext::load_file(const std::string& mod_name, std::filesystem::path path script << file.value().rdbuf(); mod->AddScriptSection(path.filename().c_str(), script.str().c_str()); - AngelScript::asERetCodes result = - util::scripting::check_ScriptModule_Build(mod->Build()); - - if (result < 0) { - return result; + int result = mod->Build(); + if (util::scripting::check_ScriptModule_Build(result)) { + return static_cast(result); } return AngelScript::asERetCodes::asSUCCESS; } diff --git a/src/util/angel_script/as_logging.cpp b/src/util/angel_script/as_logging.cpp index 8d409f7d..2f771c01 100644 --- a/src/util/angel_script/as_logging.cpp +++ b/src/util/angel_script/as_logging.cpp @@ -145,49 +145,49 @@ as_log_critical(std::string message) { void init_as_interface(AngelScript::asIScriptEngine* engine) { int r = engine->SetDefaultNamespace("LOGGING"); - if (util::scripting::check_SetDefaultNamespace(r) < 0) { + if (util::scripting::check_SetDefaultNamespace(r)) { return; } r = engine->RegisterGlobalFunction( "void LOG_BACKTRACE(string)", AngelScript::asFUNCTION(as_log_backtrace), AngelScript::asCALL_CDECL ); - if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + if (util::scripting::check_RegisterGlobalFunction(r)) { return; } r = engine->RegisterGlobalFunction( "void LOG_INFO(string)", AngelScript::asFUNCTION(as_log_info), AngelScript::asCALL_CDECL ); - if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + if (util::scripting::check_RegisterGlobalFunction(r)) { return; } r = engine->RegisterGlobalFunction( "void LOG_DEBUG(string)", AngelScript::asFUNCTION(as_log_debug), AngelScript::asCALL_CDECL ); - if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + if (util::scripting::check_RegisterGlobalFunction(r)) { return; } r = engine->RegisterGlobalFunction( "void LOG_WARNING(string)", AngelScript::asFUNCTION(as_log_warning), AngelScript::asCALL_CDECL ); - if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + if (util::scripting::check_RegisterGlobalFunction(r)) { return; } r = engine->RegisterGlobalFunction( "void LOG_ERROR(string)", AngelScript::asFUNCTION(as_log_error), AngelScript::asCALL_CDECL ); - if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + if (util::scripting::check_RegisterGlobalFunction(r)) { return; } r = engine->RegisterGlobalFunction( "void LOG_CRITICAL(string)", AngelScript::asFUNCTION(as_log_critical), AngelScript::asCALL_CDECL ); - if (util::scripting::check_RegisterGlobalFunction(r) < 0) { + if (util::scripting::check_RegisterGlobalFunction(r)) { return; } } diff --git a/src/util/angel_script/error_checks.cpp b/src/util/angel_script/error_checks.cpp index 8cba2b59..6f11b94e 100644 --- a/src/util/angel_script/error_checks.cpp +++ b/src/util/angel_script/error_checks.cpp @@ -7,98 +7,104 @@ namespace util { namespace scripting { -AngelScript::asERetCodes +bool check_SetDefaultNamespace(int r) { switch (r) { case AngelScript::asERetCodes::asINVALID_ARG: LOG_ERROR(logging::as_logger, "The namespace is invalid."); - break; + return true; case AngelScript::asERetCodes::asSUCCESS: - break; + return false; default: - LOG_WARNING( - logging::as_logger, - "Error {} does not match function call. Are you using the correct " - "error handler?", - r - ); - break; + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; } - return static_cast(r); } -AngelScript::asERetCodes +bool check_RegisterGlobalFunction(int r) { switch (r) { case AngelScript::asERetCodes::asINVALID_ARG: LOG_ERROR(logging::as_logger, "The namespace is null."); - break; + return true; case AngelScript::asERetCodes::asINVALID_DECLARATION: LOG_ERROR(logging::as_logger, "The namespace is invalid."); - break; + return true; case AngelScript::asERetCodes::asSUCCESS: - break; + return false; default: - LOG_WARNING( - logging::as_logger, - "Error {} does not match function call. Are you using the correct " - "error handler?", - r - ); - break; + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; } - return static_cast(r); } -AngelScript::asERetCodes +bool check_RegisterObjectType(int r) { switch (r) { case AngelScript::asERetCodes::asINVALID_ARG: LOG_ERROR(logging::as_logger, "The flags are invalid."); - break; + return true; case AngelScript::asERetCodes::asINVALID_NAME: LOG_ERROR(logging::as_logger, "The name is invalid."); - break; + return true; case AngelScript::asERetCodes::asALREADY_REGISTERED: LOG_ERROR( logging::as_logger, "Another type of the same name already exists." ); - break; + return true; case AngelScript::asERetCodes::asNAME_TAKEN: LOG_ERROR( logging::as_logger, "The name conflicts with other symbol names." ); - break; + return true; case AngelScript::asERetCodes::asLOWER_ARRAY_DIMENSION_NOT_REGISTERED: LOG_ERROR( logging::as_logger, "When registering an array type the array element " "must be a primitive or a registered type." ); - break; + return true; case AngelScript::asERetCodes::asINVALID_TYPE: LOG_ERROR(logging::as_logger, "The array type was not properly formed."); - break; + return true; case AngelScript::asERetCodes::asNOT_SUPPORTED: LOG_ERROR( logging::as_logger, "The array type is not supported, or already in " "use preventing it from being overloaded." ); - break; + return true; case AngelScript::asERetCodes::asSUCCESS: - break; + return false; default: - LOG_WARNING( - logging::as_logger, - "Error {} does not match function call. Are you using the correct " - "error handler?", - r - ); - break; + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; } - return static_cast(r); } -AngelScript::asERetCodes +bool check_RegisterObjectBehaviour(int r) { switch (r) { case AngelScript::asERetCodes::asWRONG_CONFIG_GROUP: @@ -106,60 +112,62 @@ check_RegisterObjectBehaviour(int r) { logging::as_logger, "The object type was registered in a different configuration group." ); - break; + return true; case AngelScript::asERetCodes::asINVALID_ARG: LOG_ERROR( logging::as_logger, "obj is not set, or a global behaviour is given in behaviour, or the " "objForThiscall pointer wasn't set according to calling convention." ); - break; + return true; case AngelScript::asERetCodes::asWRONG_CALLING_CONV: LOG_ERROR( logging::as_logger, "The function's calling convention isn't compatible with callConv." ); - break; + return true; case AngelScript::asERetCodes::asNOT_SUPPORTED: LOG_ERROR( logging::as_logger, "The calling convention or the behaviour signature is not supported." ); - break; + return true; case AngelScript::asERetCodes::asINVALID_TYPE: LOG_ERROR( logging::as_logger, "The obj parameter is not a valid object name." ); - break; + return true; case AngelScript::asERetCodes::asINVALID_DECLARATION: LOG_ERROR(logging::as_logger, "The declaration is invalid."); - break; + return true; case AngelScript::asERetCodes::asILLEGAL_BEHAVIOUR_FOR_TYPE: LOG_ERROR( logging::as_logger, "The behaviour is not allowed for this type." ); - break; + return true; case AngelScript::asERetCodes::asALREADY_REGISTERED: LOG_ERROR( logging::as_logger, "The behaviour is already registered with the same signature." ); - break; + return true; case AngelScript::asERetCodes::asSUCCESS: - break; + return false; default: - LOG_WARNING( - logging::as_logger, - "Error {} does not match function call. Are you using the correct " - "error handler?", - r - ); - break; + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; } - return static_cast(r); } -AngelScript::asERetCodes +bool check_RegisterObjectMethod(int r) { switch (r) { case AngelScript::asERetCodes::asWRONG_CONFIG_GROUP: @@ -167,54 +175,56 @@ check_RegisterObjectMethod(int r) { logging::as_logger, "The object type was registered in a different configuration group." ); - break; + return true; case AngelScript::asERetCodes::asNOT_SUPPORTED: LOG_ERROR(logging::as_logger, "The calling convention is not supported."); - break; + return true; case AngelScript::asERetCodes::asINVALID_TYPE: LOG_ERROR( logging::as_logger, "The obj parameter is not a valid object name." ); - break; + return true; case AngelScript::asERetCodes::asINVALID_DECLARATION: LOG_ERROR(logging::as_logger, "The declaration is invalid."); - break; + return true; case AngelScript::asERetCodes::asNAME_TAKEN: LOG_ERROR(logging::as_logger, "The name conflicts with other members."); - break; + return true; case AngelScript::asERetCodes::asWRONG_CALLING_CONV: LOG_ERROR( logging::as_logger, "The function's calling convention isn't compatible with callConv." ); - break; + return true; case AngelScript::asERetCodes::asALREADY_REGISTERED: LOG_ERROR( logging::as_logger, "The method has already been registered with the same parameter list." ); - break; + return true; case AngelScript::asERetCodes::asINVALID_ARG: LOG_ERROR( logging::as_logger, "The auxiliary pointer wasn't set according to calling convention." ); - break; + return true; case AngelScript::asERetCodes::asSUCCESS: - break; + return false; default: - LOG_WARNING( - logging::as_logger, - "Error {} does not match function call. Are you using the correct " - "error handler?", - r - ); - break; + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; } - return static_cast(r); } -AngelScript::asERetCodes +bool check_ScriptModule_Build(int r) { switch (r) { case AngelScript::asINVALID_CONFIGURATION: @@ -238,17 +248,19 @@ check_ScriptModule_Build(int r) { "The code in the module is still being used and and cannot be removed." ); case AngelScript::asERetCodes::asSUCCESS: - break; + return false; default: - LOG_WARNING( - logging::as_logger, - "Error {} does not match function call. Are you using the correct " - "error handler?", - r - ); - break; + if (r < 0) { + LOG_WARNING( + logging::as_logger, + "Error {} does not match function call. Are you using the correct " + "error handler?", + r + ); + return true; + } + return false; } - return static_cast(r); } // AngelScript::asERetCodes check_RegisterObjectType(int r) { diff --git a/src/util/angel_script/error_checks.hpp b/src/util/angel_script/error_checks.hpp index d6992b99..9c2d517e 100644 --- a/src/util/angel_script/error_checks.hpp +++ b/src/util/angel_script/error_checks.hpp @@ -7,19 +7,17 @@ namespace util { namespace scripting { -AngelScript::asERetCodes check_SetDefaultNamespace(int); +bool check_SetDefaultNamespace(int); -AngelScript::asERetCodes check_ScriptModule_Build(int); +bool check_ScriptModule_Build(int); -AngelScript::asERetCodes check_RegisterGlobalFunction(int); +bool check_RegisterGlobalFunction(int); -AngelScript::asERetCodes check_RegisterObjectType(int); +bool check_RegisterObjectBehaviour(int); -AngelScript::asERetCodes check_RegisterObjectBehaviour(int); +bool check_RegisterObjectMethod(int); -AngelScript::asERetCodes check_RegisterObjectMethod(int); - -AngelScript::asERetCodes check_RegisterObjectType(int); +bool check_RegisterObjectType(int); } // namespace scripting diff --git a/src/world/terrain/generation/interface.cpp b/src/world/terrain/generation/interface.cpp index 8673105d..49829dbf 100644 --- a/src/world/terrain/generation/interface.cpp +++ b/src/world/terrain/generation/interface.cpp @@ -34,12 +34,12 @@ void init_as_interface(AngelScript::asIScriptEngine* engine) { int r = engine->SetDefaultNamespace("TerrainGeneration"); - if (util::scripting::check_SetDefaultNamespace(r) < 0) { + if (util::scripting::check_SetDefaultNamespace(r)) { return; } r = engine->RegisterObjectType("FractalNoise", 0, AngelScript::asOBJ_REF); - if (util::scripting::check_RegisterObjectType(r) < 0) { + if (util::scripting::check_RegisterObjectType(r)) { return; } r = engine->RegisterObjectBehaviour( @@ -47,65 +47,65 @@ init_as_interface(AngelScript::asIScriptEngine* engine) { "FractalNoise@ f(int, double, int)", AngelScript::asFUNCTION(FractalNoise_factory), AngelScript::asCALL_CDECL ); - if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { + if (util::scripting::check_RegisterObjectBehaviour(r)) { return; } r = engine->RegisterObjectBehaviour( "FractalNoise", AngelScript::asBEHAVE_ADDREF, "void f()", AngelScript::asMETHOD(FractalNoise, add_ref), AngelScript::asCALL_THISCALL ); - if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { + if (util::scripting::check_RegisterObjectBehaviour(r)) { return; } r = engine->RegisterObjectBehaviour( "FractalNoise", AngelScript::asBEHAVE_RELEASE, "void f()", AngelScript::asMETHOD(FractalNoise, release_ref), AngelScript::asCALL_THISCALL ); - if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { + if (util::scripting::check_RegisterObjectBehaviour(r)) { return; } r = engine->RegisterObjectMethod( "FractalNoise", "double sample(double, double)", AngelScript::asMETHOD(FractalNoise, get_noise), AngelScript::asCALL_THISCALL ); - if (util::scripting::check_RegisterObjectMethod(r) < 0) { + if (util::scripting::check_RegisterObjectMethod(r)) { return; } r = engine->RegisterObjectType("WorleyNoise", 0, AngelScript::asOBJ_REF); - if (util::scripting::check_RegisterObjectType(r) < 0) { + if (util::scripting::check_RegisterObjectType(r)) { return; } r = engine->RegisterObjectBehaviour( "WorleyNoise", AngelScript::asBEHAVE_FACTORY, "WorleyNoise@ f(double, double)", AngelScript::asFUNCTION(WorleyNoise_factory), AngelScript::asCALL_CDECL ); - if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { + if (util::scripting::check_RegisterObjectBehaviour(r)) { return; } r = engine->RegisterObjectBehaviour( "WorleyNoise", AngelScript::asBEHAVE_ADDREF, "void f()", AngelScript::asMETHOD(WorleyNoise, add_ref), AngelScript::asCALL_THISCALL ); - if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { + if (util::scripting::check_RegisterObjectBehaviour(r)) { return; } r = engine->RegisterObjectBehaviour( "WorleyNoise", AngelScript::asBEHAVE_RELEASE, "void f()", AngelScript::asMETHOD(WorleyNoise, release_ref), AngelScript::asCALL_THISCALL ); - if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { + if (util::scripting::check_RegisterObjectBehaviour(r)) { return; } r = engine->RegisterObjectMethod( "WorleyNoise", "double sample(double, double)", AngelScript::asMETHOD(WorleyNoise, get_noise), AngelScript::asCALL_THISCALL ); - if (util::scripting::check_RegisterObjectMethod(r) < 0) { + if (util::scripting::check_RegisterObjectMethod(r)) { return; } r = engine->RegisterObjectType("AlternativeWorleyNoise", 0, AngelScript::asOBJ_REF); - if (util::scripting::check_RegisterObjectType(r) < 0) { + if (util::scripting::check_RegisterObjectType(r)) { return; } r = engine->RegisterObjectBehaviour( @@ -114,7 +114,7 @@ init_as_interface(AngelScript::asIScriptEngine* engine) { AngelScript::asFUNCTION(AlternativeWorleyNoise_factory), AngelScript::asCALL_CDECL ); - if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { + if (util::scripting::check_RegisterObjectBehaviour(r)) { return; } r = engine->RegisterObjectBehaviour( @@ -122,7 +122,7 @@ init_as_interface(AngelScript::asIScriptEngine* engine) { AngelScript::asMETHOD(AlternativeWorleyNoise, add_ref), AngelScript::asCALL_THISCALL ); - if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { + if (util::scripting::check_RegisterObjectBehaviour(r)) { return; } r = engine->RegisterObjectBehaviour( @@ -130,7 +130,7 @@ init_as_interface(AngelScript::asIScriptEngine* engine) { AngelScript::asMETHOD(AlternativeWorleyNoise, release_ref), AngelScript::asCALL_THISCALL ); - if (util::scripting::check_RegisterObjectBehaviour(r) < 0) { + if (util::scripting::check_RegisterObjectBehaviour(r)) { return; } r = engine->RegisterObjectMethod( @@ -138,7 +138,7 @@ init_as_interface(AngelScript::asIScriptEngine* engine) { AngelScript::asMETHOD(AlternativeWorleyNoise, get_noise), AngelScript::asCALL_THISCALL ); - if (util::scripting::check_RegisterObjectMethod(r) < 0) { + if (util::scripting::check_RegisterObjectMethod(r)) { return; } }