From 7a1c035f01644b859236d921060185ee4a38ea3e Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Sun, 7 Jul 2024 23:53:27 +0300 Subject: [PATCH 01/23] add: lua func --- src/logic/scripting/lua/libcore.cpp | 31 +++++++++++++++++++ src/logic/scripting/lua/libplayer.cpp | 44 +++++++++++++++++++++++++++ src/logic/scripting/lua/libworld.cpp | 19 ++++++++++++ src/objects/Player.cpp | 13 ++++++-- src/objects/Player.hpp | 4 +++ src/world/World.cpp | 2 +- src/world/World.hpp | 5 ++- 7 files changed, 114 insertions(+), 4 deletions(-) diff --git a/src/logic/scripting/lua/libcore.cpp b/src/logic/scripting/lua/libcore.cpp index 61b8340d..4298890e 100644 --- a/src/logic/scripting/lua/libcore.cpp +++ b/src/logic/scripting/lua/libcore.cpp @@ -11,6 +11,7 @@ #include "../../../window/Events.hpp" #include "../../../window/Window.hpp" #include "../../../world/WorldGenerators.hpp" +#include "../../../constants.hpp" #include #include @@ -158,6 +159,35 @@ static int l_get_generators(lua::State* L) { return 1; } +static int l_get_constants(lua::State* L) { + + lua::createtable(L, 0, 20); + + const std::pair numberConstants[] = { + {"ENGINE_VERSION_MAJOR", ENGINE_VERSION_MAJOR}, + {"ENGINE_VERSION_MINOR", ENGINE_VERSION_MINOR}, + {"BLOCK_AIR", BLOCK_AIR}, + {"ITEM_EMPTY", ITEM_EMPTY}, + {"CHUNK_W", CHUNK_W}, + {"CHUNK_H", CHUNK_H}, + {"CHUNK_D", CHUNK_D}, + {"VOXEL_USER_BITS", VOXEL_USER_BITS}, + {"VOXEL_USER_BITS_OFFSET", VOXEL_USER_BITS_OFFSET}, + {"ITEM_ICON_SIZE", ITEM_ICON_SIZE}, + {"CHUNK_VOL", CHUNK_VOL}, + {"BLOCK_VOID", BLOCK_VOID}, + {"ITEM_VOID", ITEM_VOID}, + {"MAX_BLOCKS", MAX_BLOCKS} + }; + + for (const auto& constant : numberConstants) { + lua::pushnumber(L, constant.second); + lua::setfield(L, constant.first); + } + + return 1; +} + const luaL_Reg corelib [] = { {"new_world", lua::wrap}, {"open_world", lua::wrap}, @@ -172,5 +202,6 @@ const luaL_Reg corelib [] = { {"quit", lua::wrap}, {"get_default_generator", lua::wrap}, {"get_generators", lua::wrap}, + {"get_constants", lua::wrap}, {NULL, NULL} }; diff --git a/src/logic/scripting/lua/libplayer.cpp b/src/logic/scripting/lua/libplayer.cpp index b9315de7..98c23c25 100644 --- a/src/logic/scripting/lua/libplayer.cpp +++ b/src/logic/scripting/lua/libplayer.cpp @@ -126,6 +126,46 @@ static int l_player_get_selected_block(lua::State* L) { return 0; } +static int l_player_get_spawnpoint(lua::State* L) { + if (auto player = get_player(L, 1)) { + return lua::pushvec3(L, player->getSpawnPoint()); + } + return 0; +} + + +static int l_player_set_spawnpoint(lua::State* L) { + auto player = get_player(L, 1); + + if (player) { + auto x = lua::tonumber(L, 2); + auto y = lua::tonumber(L, 3); + auto z = lua::tonumber(L, 4); + player->setSpawnPoint(glm::vec3(x, y, z)); + } + + return 0; +} + +static int l_player_set_jump_force(lua::State* L) { + + if (auto player = get_player(L, 1)) { + player->setJumpForce(std::abs(lua::tonumber(L, 2))); + } + + return 0; +} + +static int l_player_get_jump_force(lua::State* L) { + + if (auto player = get_player(L, 1)) { + return lua::pushnumber(L, player->getJumpForce()); + } + + return 0; +} + + const luaL_Reg playerlib [] = { {"get_pos", lua::wrap}, {"set_pos", lua::wrap}, @@ -139,5 +179,9 @@ const luaL_Reg playerlib [] = { {"is_noclip", lua::wrap}, {"set_noclip", lua::wrap}, {"get_selected_block", lua::wrap}, + {"set_spawnpoint", lua::wrap}, + {"get_spawnpoint", lua::wrap}, + {"get_jump_force", lua::wrap}, + {"set_jump_force", lua::wrap}, {NULL, NULL} }; diff --git a/src/logic/scripting/lua/libworld.cpp b/src/logic/scripting/lua/libworld.cpp index 642c85d8..aca3bb7f 100644 --- a/src/logic/scripting/lua/libworld.cpp +++ b/src/logic/scripting/lua/libworld.cpp @@ -54,6 +54,12 @@ static int l_world_set_day_time(lua::State* L) { return 0; } +static int l_wolrd_set_speed_time(lua::State* L) { + auto value = lua::tonumber(L, 1); + level->getWorld()->factorSpeedTime = std::abs(value); + return 0; +} + static int l_world_get_seed(lua::State* L) { return lua::pushinteger(L, level->getWorld()->getSeed()); } @@ -64,12 +70,25 @@ static int l_world_exists(lua::State* L) { return lua::pushboolean(L, fs::is_directory(worldsDir)); } +static int l_world_is_day(lua::State* L) { + auto daytime = level->getWorld()->daytime; + return lua::pushboolean(L, daytime >= 0.2 && daytime <= 0.8); +} + +static int l_world_is_night(lua::State* L) { + auto daytime = level->getWorld()->daytime; + return lua::pushboolean(L, daytime < 0.2 || daytime > 0.8); +} + const luaL_Reg worldlib [] = { {"get_list", lua::wrap}, {"get_total_time", lua::wrap}, {"get_day_time", lua::wrap}, {"set_day_time", lua::wrap}, + {"set_speed_time", lua::wrap}, {"get_seed", lua::wrap}, + {"is_day", lua::wrap}, + {"is_night", lua::wrap}, {"exists", lua::wrap}, {NULL, NULL} }; diff --git a/src/objects/Player.cpp b/src/objects/Player.cpp index fe81a5c7..df71c0c3 100644 --- a/src/objects/Player.cpp +++ b/src/objects/Player.cpp @@ -18,7 +18,7 @@ const float PLAYER_GROUND_DAMPING = 10.0f; const float PLAYER_AIR_DAMPING = 7.0f; const float FLIGHT_SPEED_MUL = 4.0f; const float CHEAT_SPEED_MUL = 5.0f; -const float JUMP_FORCE = 8.0f; +const float JUMP_FACTOR = 8.0f; Player::Player(glm::vec3 position, float speed, std::shared_ptr inv) : speed(speed), @@ -96,7 +96,7 @@ void Player::updateInput( } if (input.jump && hitbox->grounded){ - hitbox->velocity.y = JUMP_FORCE; + hitbox->velocity.y = JUMP_FACTOR * jumpForce; } if ((input.flight && !noclip) || @@ -106,6 +106,7 @@ void Player::updateInput( hitbox->grounded = false; } } + if (input.noclip) { noclip = !noclip; } @@ -184,6 +185,14 @@ void Player::setNoclip(bool flag) { this->noclip = flag; } +float Player::getJumpForce() const { + return jumpForce; +} + +void Player::setJumpForce(float value) { + jumpForce = value; +} + std::shared_ptr Player::getInventory() const { return inventory; } diff --git a/src/objects/Player.hpp b/src/objects/Player.hpp index fdae39b5..4a9c154d 100644 --- a/src/objects/Player.hpp +++ b/src/objects/Player.hpp @@ -45,6 +45,7 @@ class Player : public Object, public Serializable { int chosenSlot; glm::vec3 spawnpoint {}; std::shared_ptr inventory; + float jumpForce = 1.0f; bool flight = false; bool noclip = false; public: @@ -73,6 +74,9 @@ public: bool isNoclip() const; void setNoclip(bool flag); + + float getJumpForce() const; + void setJumpForce(float value); std::shared_ptr getInventory() const; diff --git a/src/world/World.cpp b/src/world/World.cpp index 3e92ccb6..5d559a46 100644 --- a/src/world/World.cpp +++ b/src/world/World.cpp @@ -44,7 +44,7 @@ World::~World(){ } void World::updateTimers(float delta) { - daytime += delta * daytimeSpeed; + daytime += delta * daytimeSpeed * factorSpeedTime; daytime = fmod(daytime, 1.0f); totalTime += delta; } diff --git a/src/world/World.hpp b/src/world/World.hpp index 904ed027..81be7af0 100644 --- a/src/world/World.hpp +++ b/src/world/World.hpp @@ -42,8 +42,11 @@ public: /// 0.5 - is noon float daytime = timeutil::time_value(10, 00, 00); + // factor speed time + float factorSpeedTime = 1.0f; + // looking bad - float daytimeSpeed = 1.0f/60.0f/24.0f; + float daytimeSpeed = 0.000694444444444f; //1.0f/60.0f/24.0f; /// @brief total time passed in the world (not depending on daytimeSpeed) double totalTime = 0.0; From 62a2360d2b6e0cc60f7aaf9bab4f5d10ced8fde1 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Sun, 7 Jul 2024 23:55:49 +0300 Subject: [PATCH 02/23] add: docs for en, ru --- doc/en/scripting.md | 32 ++++++++++++++++++++++++++++++++ doc/ru/scripting.md | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/doc/en/scripting.md b/doc/en/scripting.md index 1a1c5d38..38caddb9 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -91,6 +91,20 @@ player.set_noclip(bool) Getter and setter for player noclip mode (collisions disabled) +``` python +player.set_spawnpoint(playerid: int, x: number, y: number, z: number) +player.get_spawnpoint(playerid: int) -> number, number, number +``` + +Point setter and getter added by player + +```python +player.set_jump_force(playerid: int, force: number) +player.get_jump_force(playerid: int) -> number +``` + +Player jump force setter and getter + ```python player.get_selected_block(playerid: int) -> x,y,z ``` @@ -122,6 +136,12 @@ world.set_day_time(time: number) Set day time value. +```python +world.set_speed_time(value: number) +``` + +Sets the specified speed for the game time + ```python world.get_total_time() -> number ``` @@ -134,6 +154,18 @@ world.get_seed() -> int Returns world seed. +``` python +world.is_day() -> boolean +``` + +Proves that this is the current time during the day. From 0.2(8 am) to 0.8(8 pm) + +``` python +world.is_night() -> bool +``` + +Checks that it is the current time at night. From 0.8(8 pm) to 0.2(8 am) + ```python world.exists() -> bool ``` diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index cd85c39d..879c1eca 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -87,6 +87,20 @@ player.set_noclip(bool) Геттер и сеттер noclip режима (выключенная коллизия игрока) +```python +player.set_spawnpoint(playerid: int, x: number, y: number, z: number) +player.get_spawnpoint(playerid: int) -> number, number, number +``` + +Сеттер и геттер точки спавна игрока + +```python +player.set_jump_force(playerid: int, force: number) +player.get_jump_force(playerid: int) -> number +``` + +Сеттер и геттер силы прыжка игрока + ```python player.get_selected_block(playerid: int) -> x,y,z ``` @@ -116,6 +130,12 @@ world.set_day_time(time: number) Устанавливает указанное игровое время. +```python +world.set_speed_time(value: number) +``` + +Устанавливает указанную скорость для игрового времени. + ```python world.get_total_time() -> number ``` @@ -134,6 +154,18 @@ world.exists() -> bool Проверяет существование мира по имени. +```python +world.is_day() -> bool +``` + +Проверяет является ли текущее время днём. От 0.2(8 утра) до 0.8(8 вечера) + +```python +world.is_night() -> bool +``` + +Проверяет является ли текущее время ночью. От 0.8(8 вечера) до 0.2(8 утра) + ## Библиотека *pack* ```python From aed072d3b0510fd22a3b2834448f025c05c3a867 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 11:37:22 +0300 Subject: [PATCH 03/23] add docs for libcore.cpp --- src/logic/scripting/lua/libcore.cpp | 33 +++++++++++++++++++++++++++++ src/world/World.hpp | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/logic/scripting/lua/libcore.cpp b/src/logic/scripting/lua/libcore.cpp index 4298890e..6776cf30 100644 --- a/src/logic/scripting/lua/libcore.cpp +++ b/src/logic/scripting/lua/libcore.cpp @@ -18,6 +18,10 @@ using namespace scripting; +/// @brief Creating new world +/// @param name Name world +/// @param seed Seed world +/// @param generator Type of generation static int l_new_world(lua::State* L) { auto name = lua::require_string(L, 1); auto seed = lua::require_string(L, 2); @@ -27,6 +31,8 @@ static int l_new_world(lua::State* L) { return 0; } +/// @brief Open world +/// @param name Name world static int l_open_world(lua::State* L) { auto name = lua::require_string(L, 1); @@ -35,12 +41,15 @@ static int l_open_world(lua::State* L) { return 0; } +/// @brief Reopen world static int l_reopen_world(lua::State*) { auto controller = engine->getController(); controller->reopenWorld(level->getWorld()); return 0; } +/// @brief Close world +/// @param flag Save world (bool) static int l_close_world(lua::State* L) { if (controller == nullptr) { throw std::runtime_error("no world open"); @@ -56,6 +65,8 @@ static int l_close_world(lua::State* L) { return 0; } +/// @brief Delete world +/// @param name Name world static int l_delete_world(lua::State* L) { auto name = lua::require_string(L, 1); auto controller = engine->getController(); @@ -63,6 +74,9 @@ static int l_delete_world(lua::State* L) { return 0; } +/// @brief Reconfigure packs +/// @param addPacks An array of packs to add +/// @param remPacks An array of packs to remove static int l_reconfig_packs(lua::State* L) { if (!lua::istable(L, 1)) { throw std::runtime_error("strings array expected as the first argument"); @@ -96,12 +110,18 @@ static int l_reconfig_packs(lua::State* L) { return 0; } +/// @brief Get a setting value +/// @param name The name of the setting +/// @return The value of the setting static int l_get_setting(lua::State* L) { auto name = lua::require_string(L, 1); const auto value = engine->getSettingsHandler().getValue(name); return lua::pushvalue(L, value); } +/// @brief Set a setting value +/// @param name The name of the setting +/// @param value The new value for the setting static int l_set_setting(lua::State* L) { auto name = lua::require_string(L, 1); const auto value = lua::tovalue(L, 2); @@ -109,12 +129,18 @@ static int l_set_setting(lua::State* L) { return 0; } +/// @brief Convert a setting value to a string +/// @param name The name of the setting +/// @return The string representation of the setting value static int l_str_setting(lua::State* L) { auto name = lua::require_string(L, 1); const auto string = engine->getSettingsHandler().toString(name); return lua::pushstring(L, string); } +/// @brief Get information about a setting +/// @param name The name of the setting +/// @return A table with information about the setting static int l_get_setting_info(lua::State* L) { auto name = lua::require_string(L, 1); auto setting = engine->getSettingsHandler().getSetting(name); @@ -137,15 +163,20 @@ static int l_get_setting_info(lua::State* L) { throw std::runtime_error("unsupported setting type"); } +/// @brief Quit the game static int l_quit(lua::State*) { Window::setShouldClose(true); return 0; } +/// @brief Get the default world generator +/// @return The ID of the default world generator static int l_get_default_generator(lua::State* L) { return lua::pushstring(L, WorldGenerators::getDefaultGeneratorID()); } +/// @brief Get a list of all world generators +/// @return A table with the IDs of all world generators static int l_get_generators(lua::State* L) { const auto& generators = WorldGenerators::getGeneratorsIDs(); lua::createtable(L, generators.size(), 0); @@ -159,6 +190,8 @@ static int l_get_generators(lua::State* L) { return 1; } +/// @brief Get engine constants +/// @return A table with engine constants static int l_get_constants(lua::State* L) { lua::createtable(L, 0, 20); diff --git a/src/world/World.hpp b/src/world/World.hpp index 81be7af0..1015dec3 100644 --- a/src/world/World.hpp +++ b/src/world/World.hpp @@ -46,7 +46,7 @@ public: float factorSpeedTime = 1.0f; // looking bad - float daytimeSpeed = 0.000694444444444f; //1.0f/60.0f/24.0f; + float daytimeSpeed = 1.0f/1440.0f; //1.0f/60.0f/24.0f; /// @brief total time passed in the world (not depending on daytimeSpeed) double totalTime = 0.0; From 42b753d485d86464d7e40208edd9e9285fcf1570 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 12:26:01 +0300 Subject: [PATCH 04/23] ref set/get_vel_time() --- src/logic/scripting/lua/libworld.cpp | 11 ++++++++--- src/world/World.cpp | 3 ++- src/world/World.hpp | 5 +---- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/logic/scripting/lua/libworld.cpp b/src/logic/scripting/lua/libworld.cpp index aca3bb7f..6db890d7 100644 --- a/src/logic/scripting/lua/libworld.cpp +++ b/src/logic/scripting/lua/libworld.cpp @@ -54,12 +54,16 @@ static int l_world_set_day_time(lua::State* L) { return 0; } -static int l_wolrd_set_speed_time(lua::State* L) { +static int l_wolrd_set_vel_time(lua::State* L) { auto value = lua::tonumber(L, 1); - level->getWorld()->factorSpeedTime = std::abs(value); + level->getWorld()->daytimeSpeed = std::abs(value); return 0; } +static int l_wolrd_get_vel_time(lua::State* L) { + return lua::pushnumber(L, level->getWorld()->daytimeSpeed); +} + static int l_world_get_seed(lua::State* L) { return lua::pushinteger(L, level->getWorld()->getSeed()); } @@ -85,7 +89,8 @@ const luaL_Reg worldlib [] = { {"get_total_time", lua::wrap}, {"get_day_time", lua::wrap}, {"set_day_time", lua::wrap}, - {"set_speed_time", lua::wrap}, + {"set_vel_time", lua::wrap}, + {"get_vel_time", lua::wrap}, {"get_seed", lua::wrap}, {"is_day", lua::wrap}, {"is_night", lua::wrap}, diff --git a/src/world/World.cpp b/src/world/World.cpp index 5d559a46..39b7aeab 100644 --- a/src/world/World.cpp +++ b/src/world/World.cpp @@ -19,6 +19,7 @@ #include static debug::Logger logger("world"); +const float DAYIME_SPECIFIC_SPEED = 1.0f/1440.0f; //1.0f/60.0f/24.0f; world_load_error::world_load_error(const std::string& message) : std::runtime_error(message) { @@ -44,7 +45,7 @@ World::~World(){ } void World::updateTimers(float delta) { - daytime += delta * daytimeSpeed * factorSpeedTime; + daytime += delta * daytimeSpeed * DAYIME_SPECIFIC_SPEED; daytime = fmod(daytime, 1.0f); totalTime += delta; } diff --git a/src/world/World.hpp b/src/world/World.hpp index 1015dec3..9b0acf36 100644 --- a/src/world/World.hpp +++ b/src/world/World.hpp @@ -42,11 +42,8 @@ public: /// 0.5 - is noon float daytime = timeutil::time_value(10, 00, 00); - // factor speed time - float factorSpeedTime = 1.0f; - // looking bad - float daytimeSpeed = 1.0f/1440.0f; //1.0f/60.0f/24.0f; + float daytimeSpeed = 1.0f; /// @brief total time passed in the world (not depending on daytimeSpeed) double totalTime = 0.0; From a039b2f667985872c588fd886be66fdb69d1e87e Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 12:33:28 +0300 Subject: [PATCH 05/23] small ref libvecn.cpp --- src/logic/scripting/lua/libvecn.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index 9a1b4f9b..0837a03b 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -92,8 +92,8 @@ const luaL_Reg vec2lib [] = { {"sub", lua::wrap>}, {"mul", lua::wrap>}, {"div", lua::wrap>}, - {"normalize", lua::wrap>}, - {"length", lua::wrap>}, + {"norm", lua::wrap>}, + {"len", lua::wrap>}, {"tostring", lua::wrap>}, {NULL, NULL} }; @@ -103,8 +103,8 @@ const luaL_Reg vec3lib [] = { {"sub", lua::wrap>}, {"mul", lua::wrap>}, {"div", lua::wrap>}, - {"normalize", lua::wrap>}, - {"length", lua::wrap>}, + {"norm", lua::wrap>}, + {"len", lua::wrap>}, {"tostring", lua::wrap>}, {NULL, NULL} }; @@ -114,8 +114,8 @@ const luaL_Reg vec4lib [] = { {"sub", lua::wrap>}, {"mul", lua::wrap>}, {"div", lua::wrap>}, - {"normalize", lua::wrap>}, - {"length", lua::wrap>}, + {"norm", lua::wrap>}, + {"len", lua::wrap>}, {"tostring", lua::wrap>}, {NULL, NULL} }; From 9a43940bafe89a00d7e92efbb6e59488e53f9753 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 14:32:59 +0300 Subject: [PATCH 06/23] ref stdcmd.lua, libvecn.cpp --- res/scripts/stdcmd.lua | 54 ++++++++++++++++++++++++-- src/logic/scripting/lua/libvecn.cpp | 60 +++++++++++++++++++++++------ 2 files changed, 98 insertions(+), 16 deletions(-) diff --git a/res/scripts/stdcmd.lua b/res/scripts/stdcmd.lua index 33f5721b..4368174b 100644 --- a/res/scripts/stdcmd.lua +++ b/res/scripts/stdcmd.lua @@ -26,24 +26,34 @@ console.add_command( "help name:str=''", "Show help infomation for the specified command", function (args, kwargs) + local name = args[1] if #name == 0 then + local commands = console.get_commands_list() table.sort(commands) local str = "Available commands:" + for i,k in ipairs(commands) do str = str.."\n "..build_scheme(console.get_command_info(k)) end + return str.."\nuse 'help '" + end + local command = console.get_command_info(name) + if command == nil then return string.format("command %q not found", name) end - local where = "" + + local where = ":" local str = SEPARATOR.."\n"..command.description.."\n"..name.." " - for i,arg in ipairs(command.args) do + + for _, arg in ipairs(command.args) do where = where.."\n "..arg.name.." - "..arg.type + if arg.optional then str = str.."["..arg.name.."] " where = where.." (optional)" @@ -51,11 +61,47 @@ console.add_command( str = str.."<"..arg.name.."> " end end - if #command.args then + + if #command.args > 0 then str = str.."\nwhere"..where end - + return str.."\n"..SEPARATOR + + end +) + +console.add_command( + "time.uptime", + "Get time elapsed since the engine started", + function() + + local uptime = time.uptime() + local years = math.floor(uptime / 31536000) + local days = math.floor((uptime % 31536000) / 86400) % 365 + local hours = math.floor((uptime % 86400) / 3600) % 24 + local minutes = math.floor((uptime % 3600) / 60) % 60 + local seconds = math.floor(uptime % 60) + + local formatted_uptime = "" + + if years > 0 then + formatted_uptime = formatted_uptime .. years .. "y " + end + if days > 0 or years > 0 then + formatted_uptime = formatted_uptime .. days .. "d " + end + if hours > 0 or days > 0 or years > 0 then + formatted_uptime = formatted_uptime .. hours .. "h " + end + if minutes > 0 or hours > 0 or days > 0 or years > 0 then + formatted_uptime = formatted_uptime .. minutes .. "m " + end + if seconds > 0 or minutes > 0 or hours > 0 or days > 0 or years > 0 then + formatted_uptime = formatted_uptime .. seconds .. "s" + end + + return uptime .. " (" .. formatted_uptime .. ")" end ) diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index 0837a03b..38e9c0c8 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -3,7 +3,7 @@ #include #include -template class Op> +template class Operation> static int l_binop(lua::State* L) { uint argc = lua::gettop(L); if (argc != 2 && argc != 3) { @@ -13,7 +13,7 @@ static int l_binop(lua::State* L) { if (lua::isnumber(L, 2)) { // scalar second operand overload auto b = lua::tonumber(L, 2); - Op op; + Operation op; if (argc == 2) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { @@ -26,7 +26,7 @@ static int l_binop(lua::State* L) { } } else { auto b = lua::tovec(L, 2); - Op op; + Operation op; if (argc == 2) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { @@ -62,11 +62,38 @@ static int l_unaryop(lua::State* L) { template&)> static int l_scalar_op(lua::State* L) { - auto vec = lua::tovec(L, 1); if (lua::gettop(L) != 1) { throw std::runtime_error("invalid arguments number (1 expected)"); } - return lua::pushnumber(L, func(vec)); + return lua::pushnumber(L, func(lua::tovec(L, 1)/*vector a*/)); +} + +template +static int l_pow(lua::State* L) { + if (lua::gettop(L) != 2) { + throw std::runtime_error("invalid arguments number (2 expected)"); + } + auto a = lua::tovec(L, 1); //vector + auto b = lua::tonumber(L, 2); //scalar (pow) + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b); + } + return lua::setvec(L, 1, result_vector); +} + +template +static int l_dot(lua::State* L) { + if (lua::gettop(L)!= 2) { + throw std::runtime_error("invalid arguments number (2 expected)"); + } + auto a = lua::tovec(L, 1); + auto b = lua::tovec(L, 2); + float result_vector = 0; + for (int i = 0; i < n; i++) { + result_vector += a[i] * b[i]; + } + return lua::pushnumber(L, result_vector); } template @@ -92,9 +119,12 @@ const luaL_Reg vec2lib [] = { {"sub", lua::wrap>}, {"mul", lua::wrap>}, {"div", lua::wrap>}, - {"norm", lua::wrap>}, - {"len", lua::wrap>}, + {"norm", lua::wrap>}, + {"len", lua::wrap>}, + {"abs", lua::wrap>}, {"tostring", lua::wrap>}, + {"pow", lua::wrap>}, + {"dot", lua::wrap>}, {NULL, NULL} }; @@ -103,9 +133,12 @@ const luaL_Reg vec3lib [] = { {"sub", lua::wrap>}, {"mul", lua::wrap>}, {"div", lua::wrap>}, - {"norm", lua::wrap>}, - {"len", lua::wrap>}, + {"norm", lua::wrap>}, + {"len", lua::wrap>}, + {"abs", lua::wrap>}, {"tostring", lua::wrap>}, + {"pow", lua::wrap>}, + {"dot", lua::wrap>}, {NULL, NULL} }; @@ -114,8 +147,11 @@ const luaL_Reg vec4lib [] = { {"sub", lua::wrap>}, {"mul", lua::wrap>}, {"div", lua::wrap>}, - {"norm", lua::wrap>}, - {"len", lua::wrap>}, + {"abs", lua::wrap>}, + {"norm", lua::wrap>}, + {"len", lua::wrap>}, {"tostring", lua::wrap>}, + {"pow", lua::wrap>}, + {"dot", lua::wrap>}, {NULL, NULL} -}; +}; \ No newline at end of file From 9c45f187f83087a7174eb9dc09e88cf4406ad3b0 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 14:54:19 +0300 Subject: [PATCH 07/23] ref vectors --- src/logic/scripting/lua/libvecn.cpp | 40 +++++++++++++++++++---------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index 38e9c0c8..a6d1ef18 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -9,10 +9,10 @@ static int l_binop(lua::State* L) { if (argc != 2 && argc != 3) { throw std::runtime_error("invalid arguments number (2 or 3 expected)"); } - auto a = lua::tovec(L, 1); + const auto& a = lua::tovec(L, 1); if (lua::isnumber(L, 2)) { // scalar second operand overload - auto b = lua::tonumber(L, 2); + const auto& b = lua::tonumber(L, 2); Operation op; if (argc == 2) { lua::createtable(L, n, 0); @@ -25,7 +25,7 @@ static int l_binop(lua::State* L) { return lua::setvec(L, 3, op(a, glm::vec(b))); } } else { - auto b = lua::tovec(L, 2); + const auto& b = lua::tovec(L, 2); Operation op; if (argc == 2) { lua::createtable(L, n, 0); @@ -43,7 +43,7 @@ static int l_binop(lua::State* L) { template(*func)(const glm::vec&)> static int l_unaryop(lua::State* L) { uint argc = lua::gettop(L); - auto vec = func(lua::tovec(L, 1)); + const auto& vec = func(lua::tovec(L, 1)); switch (argc) { case 1: lua::createtable(L, n, 0); @@ -73,8 +73,8 @@ static int l_pow(lua::State* L) { if (lua::gettop(L) != 2) { throw std::runtime_error("invalid arguments number (2 expected)"); } - auto a = lua::tovec(L, 1); //vector - auto b = lua::tonumber(L, 2); //scalar (pow) + const auto& a = lua::tovec(L, 1); //vector + const auto& b = lua::tonumber(L, 2); //scalar (pow) glm::vec result_vector; for (int i = 0; i < n; i++) { result_vector[i] = pow(a[i], b); @@ -84,21 +84,30 @@ static int l_pow(lua::State* L) { template static int l_dot(lua::State* L) { - if (lua::gettop(L)!= 2) { + if (lua::gettop(L) != 2) { throw std::runtime_error("invalid arguments number (2 expected)"); } - auto a = lua::tovec(L, 1); - auto b = lua::tovec(L, 2); - float result_vector = 0; - for (int i = 0; i < n; i++) { - result_vector += a[i] * b[i]; + return lua::pushnumber(L, glm::dot(lua::tovec(L, 1), // vector a + lua::tovec(L, 2) // vector b + )); +} + +template +static int l_round(lua::State* L) { + if (lua::gettop(L)!= 1) { + throw std::runtime_error("invalid arguments number (1 expected)"); } - return lua::pushnumber(L, result_vector); + const auto& vec = lua::tovec(L, 1); + glm::vec rounded_vector; + for (int i = 0; i < n; i++) { + rounded_vector[i] = std::round(vec[i]); + } + return lua::setvec(L, 1, rounded_vector); } template static int l_tostring(lua::State* L) { - auto vec = lua::tovec(L, 1); + const auto& vec = lua::tovec(L, 1); if (lua::gettop(L) != 1) { throw std::runtime_error("invalid arguments number (1 expected)"); } @@ -125,6 +134,7 @@ const luaL_Reg vec2lib [] = { {"tostring", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, + {"round", lua::wrap>}, {NULL, NULL} }; @@ -139,6 +149,7 @@ const luaL_Reg vec3lib [] = { {"tostring", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, + {"round", lua::wrap>}, {NULL, NULL} }; @@ -153,5 +164,6 @@ const luaL_Reg vec4lib [] = { {"tostring", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, + {"round", lua::wrap>}, {NULL, NULL} }; \ No newline at end of file From 18ed0e6353357b5a7d4b5874445010b8db8d5432 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 16:12:42 +0300 Subject: [PATCH 08/23] update vectors --- src/logic/scripting/lua/libvecn.cpp | 73 ++++++++++++++++++++++------- 1 file changed, 56 insertions(+), 17 deletions(-) diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index a6d1ef18..4933a7f3 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -13,29 +13,29 @@ static int l_binop(lua::State* L) { if (lua::isnumber(L, 2)) { // scalar second operand overload const auto& b = lua::tonumber(L, 2); - Operation op; + Operation oper; if (argc == 2) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { - lua::pushnumber(L, op(a[i], b)); + lua::pushnumber(L, oper(a[i], b)); lua::rawseti(L, i+1); } return 1; } else { - return lua::setvec(L, 3, op(a, glm::vec(b))); + return lua::setvec(L, 3, oper(a, glm::vec(b))); } } else { const auto& b = lua::tovec(L, 2); - Operation op; + Operation oper; if (argc == 2) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { - lua::pushnumber(L, op(a[i], b[i])); + lua::pushnumber(L, oper(a[i], b[i])); lua::rawseti(L, i+1); } return 1; } else { - return lua::setvec(L, 3, op(a, b)); + return lua::setvec(L, 3, oper(a, b)); } } } @@ -93,16 +93,49 @@ static int l_dot(lua::State* L) { } template -static int l_round(lua::State* L) { - if (lua::gettop(L)!= 1) { - throw std::runtime_error("invalid arguments number (1 expected)"); +static int l_rotate(lua::State* L) { + if (lua::gettop(L) != 2) { + throw std::runtime_error("invalid arguments number (2 expected)"); } - const auto& vec = lua::tovec(L, 1); - glm::vec rounded_vector; - for (int i = 0; i < n; i++) { - rounded_vector[i] = std::round(vec[i]); + + const auto& vec = lua::tovec(L, 1); // vector + const auto& angle = lua::tonumber(L, 2); // scalar (in radians) + + const float _cos = std::cos(angle); + const float _sin = std::sin(angle); + + glm::vec result_vector = vec; + + for (int i = 0; i < n - 1; ++i) { + float temp = result_vector[i] * _cos - result_vector[i + 1] * _sin; + result_vector[i + 1] = result_vector[i] * _sin + result_vector[i + 1] * _cos; + result_vector[i] = temp; + } + + return lua::setvec(L, 1, result_vector); +} + +template +static int l_cross(lua::State* L) { + if (lua::gettop(L)!= 2) { + throw std::runtime_error("invalid arguments number (2 expected)"); + } + const auto& a = lua::tovec(L, 1); + const auto& b = lua::tovec(L, 2); + + glm::vec result_vector; + + if (n == 2) { + result_vector.x = a.x * b.y - a.y * b.x; + return lua::pushnumber(L, result_vector.x); + } else { + for (int i = 0; i < n; ++i) { + int j = (i + 1) % n; + int k = (i + 2) % n; + result_vector[i] = a[j] * b[k] - a[k] * b[j]; + } + return lua::setvec(L, 1, result_vector); } - return lua::setvec(L, 1, rounded_vector); } template @@ -131,10 +164,12 @@ const luaL_Reg vec2lib [] = { {"norm", lua::wrap>}, {"len", lua::wrap>}, {"abs", lua::wrap>}, + {"round", lua::wrap>}, {"tostring", lua::wrap>}, + {"cross", lua::wrap>}, + {"rot", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, - {"round", lua::wrap>}, {NULL, NULL} }; @@ -146,10 +181,12 @@ const luaL_Reg vec3lib [] = { {"norm", lua::wrap>}, {"len", lua::wrap>}, {"abs", lua::wrap>}, + {"round", lua::wrap>}, {"tostring", lua::wrap>}, + {"cross", lua::wrap>}, + {"rot", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, - {"round", lua::wrap>}, {NULL, NULL} }; @@ -161,9 +198,11 @@ const luaL_Reg vec4lib [] = { {"abs", lua::wrap>}, {"norm", lua::wrap>}, {"len", lua::wrap>}, + {"round", lua::wrap>}, {"tostring", lua::wrap>}, + {"cross", lua::wrap>}, + {"rot", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, - {"round", lua::wrap>}, {NULL, NULL} }; \ No newline at end of file From 98504b9f484c5b42829d70565e9a8950f1a1b21d Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 17:11:36 +0300 Subject: [PATCH 09/23] add docs for vectors --- doc/ru/scripting/builtins/libvecn.md | 147 +++++++++++++++++++++++++++ src/logic/scripting/lua/libvecn.cpp | 18 +++- 2 files changed, 164 insertions(+), 1 deletion(-) create mode 100644 doc/ru/scripting/builtins/libvecn.md diff --git a/doc/ru/scripting/builtins/libvecn.md b/doc/ru/scripting/builtins/libvecn.md new file mode 100644 index 00000000..d72cbb96 --- /dev/null +++ b/doc/ru/scripting/builtins/libvecn.md @@ -0,0 +1,147 @@ +# Библиотека Vec*n* + +*vecn* содержит набор функций для работы с векторами размерностью 2, 3 или 4. +Большинство функций имеют несколько вариантов списка аргументов (перегрузок). + +> [!WARNING] +> +> vecn, где n |-> размерность вектора (2, 3, 4), т.е vec2, vec3, vec4 +> + +## Типы данных + +На данной странице будут использоваться условные обозначения типов. +- vector - массив из двух, трех или четырех чисел +- vec2 - массив из двух чисел +- vec3 - массив из трех чисел +- vec4 - массив из четырех чисел + +> [!WARNING] +> +> Аннотации типов являются частью документации и не указываются при вызове использовании. + + +## Операции с векторами + +#### Сложение - *vecn.add(...)* + +```lua +-- возвращает результат сложения векторов +vecn.add(a: vector, b: vector) + +-- возвращает результат сложения вектора и скаляра +vecn.add(a: vector, b: number) +``` + +#### Вычитание - *vecn.sub(...)* + +```lua +-- возвращает результат вычитания векторов +vecn.sub(a: vector, b: vector) + +-- возвращает результат вычитания скаляра из вектора +vecn.sub(a: vector, b: number) +``` + +#### Умножение - *vecn.mul(...)* + +```lua +-- возвращает результат умножения векторов +vecn.mul(a: vector, b: vector) + +-- возвращает результат умножения вектора на скаляр +vecn.mul(a: vector, b: number) +``` + +#### Инверсия - *vecn.inv(...)* + +```lua +-- возвращает результат инверсии (противоположный) вектора +vecn.inv(a: vector) +``` + +#### Деление - *vecn.div(...)* + +```lua +-- возвращает результат деления векторов +vecn.div(a: vector, b: vector) + +-- возвращает результат деления вектора на скаляр +vecn.div(a: vector, b: number) +``` + +#### Нормализация - *vecn.norm(...)* + +```lua +-- возвращает нормализованный вектор +vecn.norm(a: vector) +``` +#### Длина вектора - *vecn.len(...)* + +```lua +-- возвращает длину вектора +vecn.len(a: vector) +``` + +#### Абсолютное значение - *vecn.abs(...)* + +```lua +-- возвращает вектор с абсолютными значениями +vecn.abs(a: vector) +``` + +#### Округление - *vecn.round(...)* + +```lua +-- возвращает вектор с округленными значениями +vecn.round(a: vector) +``` + +#### Степень - *vecn.pow(...)* + +```lua +-- возвращает вектор с элементами, возведенными в степень +vecn.pow(a: vector, b: number) +``` + +#### Скалярное произведение - *vecn.dot(...)* +```lua +-- возвращает скалярное произведение векторов +vecn.dot(a: vector, b: vector) +``` + +#### Векторное произведение - *vecn.cross(...)* +```lua +-- возвращает векторное произведение векторов +vecn.cross(a: vector, b: vector) +``` + +#### Поворот - *vecn.rot(...)* +> [!WARNING] +> Угол поворота (angle) указывается в радианах. + +```lua +-- возвращает вектор, повернутый на заданный угол +vecn.rot(a: vector, angle: number) +``` + +#### Перевод в строку - *vecn.tostring(...)* +> [!WARNING] +> Возвращает только тогда, когда содержимым является вектор +```lua +-- возвращает строку представляющую содержимое вектора +vecn.tostring(a: vector) +``` + + +## Пример +```lua +-- создание векторов разной размерности +local v1_3d = {1, 2, 2} +local v2_3d = {10, 20, 40} +local v3_4d = {1, 2, 4, 1} +local v4_2d = {1, 1} +local scal = 6 -- обычный скаляр + + +``` diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index 4933a7f3..289b54f3 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -124,7 +124,7 @@ static int l_cross(lua::State* L) { const auto& b = lua::tovec(L, 2); glm::vec result_vector; - + if (n == 2) { result_vector.x = a.x * b.y - a.y * b.x; return lua::pushnumber(L, result_vector.x); @@ -138,6 +138,19 @@ static int l_cross(lua::State* L) { } } +template +static int l_inverse(lua::State* L) { + if (lua::gettop(L)!= 1) { + throw std::runtime_error("invalid arguments number (1 expected)"); + } + const auto& vec = lua::tovec(L, 1); + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = -vec[i]; + } + return lua::setvec(L, 1, result_vector); +} + template static int l_tostring(lua::State* L) { const auto& vec = lua::tovec(L, 1); @@ -166,6 +179,7 @@ const luaL_Reg vec2lib [] = { {"abs", lua::wrap>}, {"round", lua::wrap>}, {"tostring", lua::wrap>}, + {"inv", lua::wrap>}, {"cross", lua::wrap>}, {"rot", lua::wrap>}, {"pow", lua::wrap>}, @@ -183,6 +197,7 @@ const luaL_Reg vec3lib [] = { {"abs", lua::wrap>}, {"round", lua::wrap>}, {"tostring", lua::wrap>}, + {"inv", lua::wrap>}, {"cross", lua::wrap>}, {"rot", lua::wrap>}, {"pow", lua::wrap>}, @@ -200,6 +215,7 @@ const luaL_Reg vec4lib [] = { {"len", lua::wrap>}, {"round", lua::wrap>}, {"tostring", lua::wrap>}, + {"inv", lua::wrap>}, {"cross", lua::wrap>}, {"rot", lua::wrap>}, {"pow", lua::wrap>}, From 97b0d99ce64fabbabe132e6ae935caa5754ac505 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 19:36:09 +0300 Subject: [PATCH 10/23] upd: docs for vectors, libvecn.cpp --- doc/ru/scripting/builtins/libvecn.md | 52 +++++++++++++++++++---- src/logic/scripting/lua/libvecn.cpp | 62 ++++++++-------------------- 2 files changed, 62 insertions(+), 52 deletions(-) diff --git a/doc/ru/scripting/builtins/libvecn.md b/doc/ru/scripting/builtins/libvecn.md index d72cbb96..ad0f61da 100644 --- a/doc/ru/scripting/builtins/libvecn.md +++ b/doc/ru/scripting/builtins/libvecn.md @@ -5,7 +5,7 @@ > [!WARNING] > -> vecn, где n |-> размерность вектора (2, 3, 4), т.е vec2, vec3, vec4 +> vecn, где n == размерность вектора (2, 3, 4), т.е vec2, vec3, vec4 > ## Типы данных @@ -110,12 +110,6 @@ vecn.pow(a: vector, b: number) vecn.dot(a: vector, b: vector) ``` -#### Векторное произведение - *vecn.cross(...)* -```lua --- возвращает векторное произведение векторов -vecn.cross(a: vector, b: vector) -``` - #### Поворот - *vecn.rot(...)* > [!WARNING] > Угол поворота (angle) указывается в радианах. @@ -140,8 +134,50 @@ vecn.tostring(a: vector) local v1_3d = {1, 2, 2} local v2_3d = {10, 20, 40} local v3_4d = {1, 2, 4, 1} -local v4_2d = {1, 1} +local v4_2d = {1, 0} local scal = 6 -- обычный скаляр +-- сложение векторов +local result_add = vec3.add(v1_3d, v2_3d) +print("add: " .. vec3.tostring(result_add)) -- {11, 22, 42} +-- вычитание векторов +local result_sub = vec3.sub(v2_3d, v1_3d) +print("sub: " .. vec3.tostring(result_sub)) -- {9, 18, 38} + +-- умножение векторов +local result_mul = vec3.mul(v1_3d, v2_3d) +print("mul: " .. vec3.tostring(result_mul)) -- {10, 40, 80} + +-- умножение вектора на скаляр +local result_mul_scal = vec3.mul(v1_3d, scal) +print("mul_scal: " .. vec3.tostring(result_mul_scal)) -- {6, 12, 12} + +-- нормализация вектора +local result_norm = vec3.norm(v1_3d) +print("norm: " .. vec3.tostring(result_norm)) -- {0.333, 0.667, 0.667} + +-- длина вектора +local result_len = vec3.len(v1_3d) +print("len: " .. result_len) -- 3 + +-- абсолютное значение вектора +local result_abs = vec3.abs(v1_3d) +print("abs: " .. vec3.tostring(result_abs)) -- {1, 2, 2} + +-- округление вектора +local result_round = vec3.round(v1_3d) +print("round: " .. vec3.tostring(result_round)) -- {1, 2, 2} + +-- степень вектора +local result_pow = vec3.pow(v1_3d, 2) +print("pow: " .. vec3.tostring(result_pow)) -- {1, 4, 4} + +-- скалярное произведение векторов +local result_dot = vec3.dot(v1_3d, v2_3d) +print("dot: " .. result_dot) -- 250 + +-- поворот вектора +local result_rot = vec2.rot(v4_2d, math.pi / 4) +print("rot: " .. vec2.tostring(result_rot)) -- {0.707107, 0.707107} ``` diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index 289b54f3..813aae9b 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -1,7 +1,9 @@ #include "api_lua.hpp" +#define GLM_ENABLE_EXPERIMENTAL #include #include +#include template class Operation> static int l_binop(lua::State* L) { @@ -87,9 +89,8 @@ static int l_dot(lua::State* L) { if (lua::gettop(L) != 2) { throw std::runtime_error("invalid arguments number (2 expected)"); } - return lua::pushnumber(L, glm::dot(lua::tovec(L, 1), // vector a - lua::tovec(L, 2) // vector b - )); + return lua::pushnumber(L, glm::dot(lua::tovec(L, 1), + lua::tovec(L, 2))); } template @@ -97,56 +98,34 @@ static int l_rotate(lua::State* L) { if (lua::gettop(L) != 2) { throw std::runtime_error("invalid arguments number (2 expected)"); } - const auto& vec = lua::tovec(L, 1); // vector - const auto& angle = lua::tonumber(L, 2); // scalar (in radians) + const auto& angle = lua::tonumber(L, 2); // scalar (angle) - const float _cos = std::cos(angle); - const float _sin = std::sin(angle); + const auto _cos = std::cos(angle); + const auto _sin = std::sin(angle); - glm::vec result_vector = vec; + glm::vec result_vector; - for (int i = 0; i < n - 1; ++i) { - float temp = result_vector[i] * _cos - result_vector[i + 1] * _sin; - result_vector[i + 1] = result_vector[i] * _sin + result_vector[i + 1] * _cos; - result_vector[i] = temp; + switch (n) { + case 2: + result_vector.x = vec.x * _cos - vec.y * _sin; + result_vector.y = vec.x * _sin + vec.y * _cos; + break; + // TODO } return lua::setvec(L, 1, result_vector); } template -static int l_cross(lua::State* L) { - if (lua::gettop(L)!= 2) { +static int l_inverse(lua::State* L) { + if (lua::gettop(L) != 1) { throw std::runtime_error("invalid arguments number (2 expected)"); } - const auto& a = lua::tovec(L, 1); - const auto& b = lua::tovec(L, 2); - - glm::vec result_vector; - - if (n == 2) { - result_vector.x = a.x * b.y - a.y * b.x; - return lua::pushnumber(L, result_vector.x); - } else { - for (int i = 0; i < n; ++i) { - int j = (i + 1) % n; - int k = (i + 2) % n; - result_vector[i] = a[j] * b[k] - a[k] * b[j]; - } - return lua::setvec(L, 1, result_vector); - } -} - -template -static int l_inverse(lua::State* L) { - if (lua::gettop(L)!= 1) { - throw std::runtime_error("invalid arguments number (1 expected)"); - } - const auto& vec = lua::tovec(L, 1); + const auto& _vector = lua::tovec(L, 1); //vector glm::vec result_vector; for (int i = 0; i < n; i++) { - result_vector[i] = -vec[i]; + result_vector[i] = -_vector[i]; } return lua::setvec(L, 1, result_vector); } @@ -180,7 +159,6 @@ const luaL_Reg vec2lib [] = { {"round", lua::wrap>}, {"tostring", lua::wrap>}, {"inv", lua::wrap>}, - {"cross", lua::wrap>}, {"rot", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, @@ -198,8 +176,6 @@ const luaL_Reg vec3lib [] = { {"round", lua::wrap>}, {"tostring", lua::wrap>}, {"inv", lua::wrap>}, - {"cross", lua::wrap>}, - {"rot", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, {NULL, NULL} @@ -216,8 +192,6 @@ const luaL_Reg vec4lib [] = { {"round", lua::wrap>}, {"tostring", lua::wrap>}, {"inv", lua::wrap>}, - {"cross", lua::wrap>}, - {"rot", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, {NULL, NULL} From 1858a59dce0827008cd0c57240c38b16fa88cf07 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 19:45:55 +0300 Subject: [PATCH 11/23] fix docs (scripting.md) --- doc/ru/scripting.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index 879c1eca..e8e2b0d1 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -136,6 +136,12 @@ world.set_speed_time(value: number) Устанавливает указанную скорость для игрового времени. +```python +world.get_speed_time() -> number +``` + +Возвращает скорость для игрового времени. + ```python world.get_total_time() -> number ``` From e7501a17accafb22fdc451aa60024465dff4d6db Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 20:20:37 +0300 Subject: [PATCH 12/23] ref: libcore, libvecn --- src/logic/scripting/lua/libcore.cpp | 32 ------------ src/logic/scripting/lua/libvecn.cpp | 80 ++++++++++------------------- 2 files changed, 27 insertions(+), 85 deletions(-) diff --git a/src/logic/scripting/lua/libcore.cpp b/src/logic/scripting/lua/libcore.cpp index 6776cf30..2b3e2ca8 100644 --- a/src/logic/scripting/lua/libcore.cpp +++ b/src/logic/scripting/lua/libcore.cpp @@ -190,37 +190,6 @@ static int l_get_generators(lua::State* L) { return 1; } -/// @brief Get engine constants -/// @return A table with engine constants -static int l_get_constants(lua::State* L) { - - lua::createtable(L, 0, 20); - - const std::pair numberConstants[] = { - {"ENGINE_VERSION_MAJOR", ENGINE_VERSION_MAJOR}, - {"ENGINE_VERSION_MINOR", ENGINE_VERSION_MINOR}, - {"BLOCK_AIR", BLOCK_AIR}, - {"ITEM_EMPTY", ITEM_EMPTY}, - {"CHUNK_W", CHUNK_W}, - {"CHUNK_H", CHUNK_H}, - {"CHUNK_D", CHUNK_D}, - {"VOXEL_USER_BITS", VOXEL_USER_BITS}, - {"VOXEL_USER_BITS_OFFSET", VOXEL_USER_BITS_OFFSET}, - {"ITEM_ICON_SIZE", ITEM_ICON_SIZE}, - {"CHUNK_VOL", CHUNK_VOL}, - {"BLOCK_VOID", BLOCK_VOID}, - {"ITEM_VOID", ITEM_VOID}, - {"MAX_BLOCKS", MAX_BLOCKS} - }; - - for (const auto& constant : numberConstants) { - lua::pushnumber(L, constant.second); - lua::setfield(L, constant.first); - } - - return 1; -} - const luaL_Reg corelib [] = { {"new_world", lua::wrap}, {"open_world", lua::wrap}, @@ -235,6 +204,5 @@ const luaL_Reg corelib [] = { {"quit", lua::wrap}, {"get_default_generator", lua::wrap}, {"get_generators", lua::wrap}, - {"get_constants", lua::wrap}, {NULL, NULL} }; diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index 813aae9b..aa4e6142 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -1,43 +1,41 @@ #include "api_lua.hpp" -#define GLM_ENABLE_EXPERIMENTAL #include #include -#include -template class Operation> +template class Op> static int l_binop(lua::State* L) { uint argc = lua::gettop(L); if (argc != 2 && argc != 3) { throw std::runtime_error("invalid arguments number (2 or 3 expected)"); } - const auto& a = lua::tovec(L, 1); + auto a = lua::tovec(L, 1); if (lua::isnumber(L, 2)) { // scalar second operand overload - const auto& b = lua::tonumber(L, 2); - Operation oper; + auto b = lua::tonumber(L, 2); + Op op; if (argc == 2) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { - lua::pushnumber(L, oper(a[i], b)); + lua::pushnumber(L, op(a[i], b)); lua::rawseti(L, i+1); } return 1; } else { - return lua::setvec(L, 3, oper(a, glm::vec(b))); + return lua::setvec(L, 3, op(a, glm::vec(b))); } } else { - const auto& b = lua::tovec(L, 2); - Operation oper; + auto b = lua::tovec(L, 2); + Op op; if (argc == 2) { lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { - lua::pushnumber(L, oper(a[i], b[i])); + lua::pushnumber(L, op(a[i], b[i])); lua::rawseti(L, i+1); } return 1; } else { - return lua::setvec(L, 3, oper(a, b)); + return lua::setvec(L, 3, op(a, b)); } } } @@ -45,7 +43,7 @@ static int l_binop(lua::State* L) { template(*func)(const glm::vec&)> static int l_unaryop(lua::State* L) { uint argc = lua::gettop(L); - const auto& vec = func(lua::tovec(L, 1)); + auto vec = func(lua::tovec(L, 1)); switch (argc) { case 1: lua::createtable(L, n, 0); @@ -64,10 +62,11 @@ static int l_unaryop(lua::State* L) { template&)> static int l_scalar_op(lua::State* L) { + auto vec = lua::tovec(L, 1); if (lua::gettop(L) != 1) { throw std::runtime_error("invalid arguments number (1 expected)"); } - return lua::pushnumber(L, func(lua::tovec(L, 1)/*vector a*/)); + return lua::pushnumber(L, func(vec)); } template @@ -93,30 +92,6 @@ static int l_dot(lua::State* L) { lua::tovec(L, 2))); } -template -static int l_rotate(lua::State* L) { - if (lua::gettop(L) != 2) { - throw std::runtime_error("invalid arguments number (2 expected)"); - } - const auto& vec = lua::tovec(L, 1); // vector - const auto& angle = lua::tonumber(L, 2); // scalar (angle) - - const auto _cos = std::cos(angle); - const auto _sin = std::sin(angle); - - glm::vec result_vector; - - switch (n) { - case 2: - result_vector.x = vec.x * _cos - vec.y * _sin; - result_vector.y = vec.x * _sin + vec.y * _cos; - break; - // TODO - } - - return lua::setvec(L, 1, result_vector); -} - template static int l_inverse(lua::State* L) { if (lua::gettop(L) != 1) { @@ -132,7 +107,7 @@ static int l_inverse(lua::State* L) { template static int l_tostring(lua::State* L) { - const auto& vec = lua::tovec(L, 1); + auto vec = lua::tovec(L, 1); if (lua::gettop(L) != 1) { throw std::runtime_error("invalid arguments number (1 expected)"); } @@ -153,13 +128,12 @@ const luaL_Reg vec2lib [] = { {"sub", lua::wrap>}, {"mul", lua::wrap>}, {"div", lua::wrap>}, - {"norm", lua::wrap>}, - {"len", lua::wrap>}, + {"normalize", lua::wrap>}, + {"length", lua::wrap>}, + {"tostring", lua::wrap>}, {"abs", lua::wrap>}, {"round", lua::wrap>}, - {"tostring", lua::wrap>}, - {"inv", lua::wrap>}, - {"rot", lua::wrap>}, + {"inverse", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, {NULL, NULL} @@ -170,12 +144,12 @@ const luaL_Reg vec3lib [] = { {"sub", lua::wrap>}, {"mul", lua::wrap>}, {"div", lua::wrap>}, - {"norm", lua::wrap>}, - {"len", lua::wrap>}, + {"normalize", lua::wrap>}, + {"length", lua::wrap>}, + {"tostring", lua::wrap>}, {"abs", lua::wrap>}, {"round", lua::wrap>}, - {"tostring", lua::wrap>}, - {"inv", lua::wrap>}, + {"inverse", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, {NULL, NULL} @@ -186,12 +160,12 @@ const luaL_Reg vec4lib [] = { {"sub", lua::wrap>}, {"mul", lua::wrap>}, {"div", lua::wrap>}, - {"abs", lua::wrap>}, - {"norm", lua::wrap>}, - {"len", lua::wrap>}, - {"round", lua::wrap>}, + {"normalize", lua::wrap>}, + {"length", lua::wrap>}, {"tostring", lua::wrap>}, - {"inv", lua::wrap>}, + {"abs", lua::wrap>}, + {"round", lua::wrap>}, + {"inverse", lua::wrap>}, {"pow", lua::wrap>}, {"dot", lua::wrap>}, {NULL, NULL} From 87193f92001d60a143940719e04492023c0e6fcb Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 20:23:52 +0300 Subject: [PATCH 13/23] fix docs for libvecn --- doc/ru/scripting/builtins/libvecn.md | 23 +++++------------------ 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/doc/ru/scripting/builtins/libvecn.md b/doc/ru/scripting/builtins/libvecn.md index ad0f61da..9f20dfed 100644 --- a/doc/ru/scripting/builtins/libvecn.md +++ b/doc/ru/scripting/builtins/libvecn.md @@ -57,7 +57,7 @@ vecn.mul(a: vector, b: number) ```lua -- возвращает результат инверсии (противоположный) вектора -vecn.inv(a: vector) +vecn.inverse(a: vector) ``` #### Деление - *vecn.div(...)* @@ -74,13 +74,13 @@ vecn.div(a: vector, b: number) ```lua -- возвращает нормализованный вектор -vecn.norm(a: vector) +vecn.normalize(a: vector) ``` #### Длина вектора - *vecn.len(...)* ```lua -- возвращает длину вектора -vecn.len(a: vector) +vecn.length(a: vector) ``` #### Абсолютное значение - *vecn.abs(...)* @@ -110,15 +110,6 @@ vecn.pow(a: vector, b: number) vecn.dot(a: vector, b: vector) ``` -#### Поворот - *vecn.rot(...)* -> [!WARNING] -> Угол поворота (angle) указывается в радианах. - -```lua --- возвращает вектор, повернутый на заданный угол -vecn.rot(a: vector, angle: number) -``` - #### Перевод в строку - *vecn.tostring(...)* > [!WARNING] > Возвращает только тогда, когда содержимым является вектор @@ -154,11 +145,11 @@ local result_mul_scal = vec3.mul(v1_3d, scal) print("mul_scal: " .. vec3.tostring(result_mul_scal)) -- {6, 12, 12} -- нормализация вектора -local result_norm = vec3.norm(v1_3d) +local result_norm = vec3.normalize(v1_3d) print("norm: " .. vec3.tostring(result_norm)) -- {0.333, 0.667, 0.667} -- длина вектора -local result_len = vec3.len(v1_3d) +local result_len = vec3.length(v1_3d) print("len: " .. result_len) -- 3 -- абсолютное значение вектора @@ -176,8 +167,4 @@ print("pow: " .. vec3.tostring(result_pow)) -- {1, 4, 4} -- скалярное произведение векторов local result_dot = vec3.dot(v1_3d, v2_3d) print("dot: " .. result_dot) -- 250 - --- поворот вектора -local result_rot = vec2.rot(v4_2d, math.pi / 4) -print("rot: " .. vec2.tostring(result_rot)) -- {0.707107, 0.707107} ``` From b9936f3b81fff205aabb1b6d4c9a2fe739613bff Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 20:31:18 +0300 Subject: [PATCH 14/23] small fix docs --- doc/ru/scripting.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index e8e2b0d1..f3e07fbe 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -131,13 +131,13 @@ world.set_day_time(time: number) Устанавливает указанное игровое время. ```python -world.set_speed_time(value: number) +world.set_vel_time(value: number) ``` Устанавливает указанную скорость для игрового времени. ```python -world.get_speed_time() -> number +world.get_vel_time() -> number ``` Возвращает скорость для игрового времени. From 59c50e727b51ac25c01ea129c1f5d14c8397dd42 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 20:36:56 +0300 Subject: [PATCH 15/23] reverse: libplayer --- doc/ru/scripting.md | 12 ------------ src/logic/scripting/lua/libplayer.cpp | 21 --------------------- src/objects/Player.cpp | 15 +++------------ src/objects/Player.hpp | 6 +----- 4 files changed, 4 insertions(+), 50 deletions(-) diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index f3e07fbe..12bf028f 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -136,18 +136,6 @@ world.set_vel_time(value: number) Устанавливает указанную скорость для игрового времени. -```python -world.get_vel_time() -> number -``` - -Возвращает скорость для игрового времени. - -```python -world.get_total_time() -> number -``` - -Возвращает общее суммарное время, прошедшее в мире - ```python world.get_seed() -> int ``` diff --git a/src/logic/scripting/lua/libplayer.cpp b/src/logic/scripting/lua/libplayer.cpp index 98c23c25..4002ad5b 100644 --- a/src/logic/scripting/lua/libplayer.cpp +++ b/src/logic/scripting/lua/libplayer.cpp @@ -147,25 +147,6 @@ static int l_player_set_spawnpoint(lua::State* L) { return 0; } -static int l_player_set_jump_force(lua::State* L) { - - if (auto player = get_player(L, 1)) { - player->setJumpForce(std::abs(lua::tonumber(L, 2))); - } - - return 0; -} - -static int l_player_get_jump_force(lua::State* L) { - - if (auto player = get_player(L, 1)) { - return lua::pushnumber(L, player->getJumpForce()); - } - - return 0; -} - - const luaL_Reg playerlib [] = { {"get_pos", lua::wrap}, {"set_pos", lua::wrap}, @@ -181,7 +162,5 @@ const luaL_Reg playerlib [] = { {"get_selected_block", lua::wrap}, {"set_spawnpoint", lua::wrap}, {"get_spawnpoint", lua::wrap}, - {"get_jump_force", lua::wrap}, - {"set_jump_force", lua::wrap}, {NULL, NULL} }; diff --git a/src/objects/Player.cpp b/src/objects/Player.cpp index df71c0c3..590e625b 100644 --- a/src/objects/Player.cpp +++ b/src/objects/Player.cpp @@ -18,7 +18,7 @@ const float PLAYER_GROUND_DAMPING = 10.0f; const float PLAYER_AIR_DAMPING = 7.0f; const float FLIGHT_SPEED_MUL = 4.0f; const float CHEAT_SPEED_MUL = 5.0f; -const float JUMP_FACTOR = 8.0f; +const float JUMP_FORCE = 8.0f; Player::Player(glm::vec3 position, float speed, std::shared_ptr inv) : speed(speed), @@ -96,7 +96,7 @@ void Player::updateInput( } if (input.jump && hitbox->grounded){ - hitbox->velocity.y = JUMP_FACTOR * jumpForce; + hitbox->velocity.y = JUMP_FORCE; } if ((input.flight && !noclip) || @@ -106,7 +106,6 @@ void Player::updateInput( hitbox->grounded = false; } } - if (input.noclip) { noclip = !noclip; } @@ -185,14 +184,6 @@ void Player::setNoclip(bool flag) { this->noclip = flag; } -float Player::getJumpForce() const { - return jumpForce; -} - -void Player::setJumpForce(float value) { - jumpForce = value; -} - std::shared_ptr Player::getInventory() const { return inventory; } @@ -284,4 +275,4 @@ void Player::convert(dynamic::Map* data, const ContentLUT* lut) { Inventory::convert(inventory, lut); } } -} +} \ No newline at end of file diff --git a/src/objects/Player.hpp b/src/objects/Player.hpp index 4a9c154d..e35162b0 100644 --- a/src/objects/Player.hpp +++ b/src/objects/Player.hpp @@ -45,7 +45,6 @@ class Player : public Object, public Serializable { int chosenSlot; glm::vec3 spawnpoint {}; std::shared_ptr inventory; - float jumpForce = 1.0f; bool flight = false; bool noclip = false; public: @@ -74,9 +73,6 @@ public: bool isNoclip() const; void setNoclip(bool flag); - - float getJumpForce() const; - void setJumpForce(float value); std::shared_ptr getInventory() const; @@ -93,4 +89,4 @@ public: } }; -#endif // SRC_OBJECTS_PLAYER_HPP_ +#endif // SRC_OBJECTS_PLAYER_HPP_ \ No newline at end of file From a1283d7f7bdd8f347d1ce3d9669e0e1ce62d9eb6 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 20:38:30 +0300 Subject: [PATCH 16/23] fix docs --- doc/ru/scripting.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index 12bf028f..adf58025 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -94,13 +94,6 @@ player.get_spawnpoint(playerid: int) -> number, number, number Сеттер и геттер точки спавна игрока -```python -player.set_jump_force(playerid: int, force: number) -player.get_jump_force(playerid: int) -> number -``` - -Сеттер и геттер силы прыжка игрока - ```python player.get_selected_block(playerid: int) -> x,y,z ``` @@ -136,6 +129,18 @@ world.set_vel_time(value: number) Устанавливает указанную скорость для игрового времени. +```python +world.get_vel_time() -> number +``` + +Возвращает скорость для игрового времени. + +```python +world.get_total_time() -> number +``` + +Возвращает общее суммарное время, прошедшее в мире + ```python world.get_seed() -> int ``` From 75344023d8475cba78a1909aae4d4a534edc43b7 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 21:29:16 +0300 Subject: [PATCH 17/23] ref: name in libworld.cpp & docs --- doc/en/scripting.md | 17 ++++++++--------- doc/ru/scripting.md | 4 ++-- src/logic/scripting/lua/libworld.cpp | 8 ++++---- 3 files changed, 14 insertions(+), 15 deletions(-) diff --git a/doc/en/scripting.md b/doc/en/scripting.md index 38caddb9..ce062577 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -98,13 +98,6 @@ player.get_spawnpoint(playerid: int) -> number, number, number Point setter and getter added by player -```python -player.set_jump_force(playerid: int, force: number) -player.get_jump_force(playerid: int) -> number -``` - -Player jump force setter and getter - ```python player.get_selected_block(playerid: int) -> x,y,z ``` @@ -137,10 +130,16 @@ world.set_day_time(time: number) Set day time value. ```python -world.set_speed_time(value: number) +world.set_day_time_speed(value: number) ``` -Sets the specified speed for the game time +Sets the specified speed for game time. + +```python +world.get_day_time_speed() -> number +``` + +Returns the speed for game time. ```python world.get_total_time() -> number diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index adf58025..6d2a0d53 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -124,13 +124,13 @@ world.set_day_time(time: number) Устанавливает указанное игровое время. ```python -world.set_vel_time(value: number) +world.set_day_time_speed(value: number) ``` Устанавливает указанную скорость для игрового времени. ```python -world.get_vel_time() -> number +world.get_day_time_speed() -> number ``` Возвращает скорость для игрового времени. diff --git a/src/logic/scripting/lua/libworld.cpp b/src/logic/scripting/lua/libworld.cpp index 6db890d7..e7d24005 100644 --- a/src/logic/scripting/lua/libworld.cpp +++ b/src/logic/scripting/lua/libworld.cpp @@ -54,13 +54,13 @@ static int l_world_set_day_time(lua::State* L) { return 0; } -static int l_wolrd_set_vel_time(lua::State* L) { +static int l_world_set_day_time_speed(lua::State* L) { auto value = lua::tonumber(L, 1); level->getWorld()->daytimeSpeed = std::abs(value); return 0; } -static int l_wolrd_get_vel_time(lua::State* L) { +static int l_world_get_day_time_speed(lua::State* L) { return lua::pushnumber(L, level->getWorld()->daytimeSpeed); } @@ -89,8 +89,8 @@ const luaL_Reg worldlib [] = { {"get_total_time", lua::wrap}, {"get_day_time", lua::wrap}, {"set_day_time", lua::wrap}, - {"set_vel_time", lua::wrap}, - {"get_vel_time", lua::wrap}, + {"set_day_time_speed", lua::wrap}, + {"get_day_time_speed", lua::wrap}, {"get_seed", lua::wrap}, {"is_day", lua::wrap}, {"is_night", lua::wrap}, From c8dc491e4e6248f574296c196a19aa8a84145c79 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 21:43:54 +0300 Subject: [PATCH 18/23] add: overloading for functions in libvecn.cpp --- src/logic/scripting/lua/libvecn.cpp | 35 ++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index aa4e6142..64a416fb 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -71,31 +71,44 @@ static int l_scalar_op(lua::State* L) { template static int l_pow(lua::State* L) { - if (lua::gettop(L) != 2) { + uint argc = lua::gettop(L); + if (argc != 2) { throw std::runtime_error("invalid arguments number (2 expected)"); } const auto& a = lua::tovec(L, 1); //vector - const auto& b = lua::tonumber(L, 2); //scalar (pow) - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b); + if (lua::isnumber(L, 2)) { // scalar second operand overload + const auto& b = lua::tonumber(L, 2); //scalar (pow) + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b); + } + return lua::setvec(L, 1, result_vector); + } else { + const auto& b = lua::tovec(L, 2); //vector + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b[i]); + } + return lua::setvec(L, 1, result_vector); } - return lua::setvec(L, 1, result_vector); } template static int l_dot(lua::State* L) { - if (lua::gettop(L) != 2) { + uint argc = lua::gettop(L); + if (argc != 2) { throw std::runtime_error("invalid arguments number (2 expected)"); } - return lua::pushnumber(L, glm::dot(lua::tovec(L, 1), - lua::tovec(L, 2))); + const auto& a = lua::tovec(L, 1); + const auto& b = lua::tovec(L, 2); + return lua::pushnumber(L, glm::dot(a, b)); } template static int l_inverse(lua::State* L) { - if (lua::gettop(L) != 1) { - throw std::runtime_error("invalid arguments number (2 expected)"); + uint argc = lua::gettop(L); + if (argc != 1) { + throw std::runtime_error("invalid arguments number (1 expected)"); } const auto& _vector = lua::tovec(L, 1); //vector glm::vec result_vector; From ae62494dd27ec50c5bbd189ee6690b0054a46d41 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 22:10:55 +0300 Subject: [PATCH 19/23] final overload for functions --- src/logic/scripting/lua/libvecn.cpp | 105 +++++++++++++++++++--------- 1 file changed, 73 insertions(+), 32 deletions(-) diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index 64a416fb..d711a13a 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -72,50 +72,91 @@ static int l_scalar_op(lua::State* L) { template static int l_pow(lua::State* L) { uint argc = lua::gettop(L); - if (argc != 2) { - throw std::runtime_error("invalid arguments number (2 expected)"); - } - const auto& a = lua::tovec(L, 1); //vector - if (lua::isnumber(L, 2)) { // scalar second operand overload - const auto& b = lua::tonumber(L, 2); //scalar (pow) - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b); + if (argc == 2) { + const auto& a = lua::tovec(L, 1); //vector + if (lua::isnumber(L, 2)) { // scalar second operand overload + const auto& b = lua::tonumber(L, 2); //scalar (pow) + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b); + } + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, result_vector[i]); + lua::rawseti(L, i+1); + } + return 1; + } else { + const auto& b = lua::tovec(L, 2); //vector + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b[i]); + } + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, result_vector[i]); + lua::rawseti(L, i+1); + } + return 1; + } + } else if (argc == 3) { + const auto& a = lua::tovec(L, 1); //vector + if (lua::isnumber(L, 2)) { // scalar second operand overload + const auto& b = lua::tonumber(L, 2); //scalar (pow) + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b); + } + return lua::setvec(L, 3, result_vector); + } else { + const auto& b = lua::tovec(L, 2); //vector + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b[i]); + } + return lua::setvec(L, 3, result_vector); } - return lua::setvec(L, 1, result_vector); } else { - const auto& b = lua::tovec(L, 2); //vector + throw std::runtime_error("invalid arguments number (2 or 3 expected)"); + } +} + +template +static int l_inverse(lua::State* L) { + uint argc = lua::gettop(L); + if (argc == 1) { + const auto& _vector = lua::tovec(L, 1); //vector glm::vec result_vector; + for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b[i]); + result_vector[i] = -_vector[i]; } - return lua::setvec(L, 1, result_vector); + + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, result_vector[i]); + lua::rawseti(L, i+1); + } + return 1; + } else { + throw std::runtime_error("invalid arguments number (1 expected)"); } } template static int l_dot(lua::State* L) { uint argc = lua::gettop(L); - if (argc != 2) { - throw std::runtime_error("invalid arguments number (2 expected)"); + if (argc == 2) { + const auto& a = lua::tovec(L, 1); + const auto& b = lua::tovec(L, 2); + return lua::pushnumber(L, glm::dot(a, b));; + } else if (argc == 3) { + const auto& a = lua::tovec(L, 1); + const auto& b = lua::tovec(L, 2); + return lua::pushnumber(L, glm::dot(a, b)); + } else { + throw std::runtime_error("invalid arguments number (2 or 3 expected)"); } - const auto& a = lua::tovec(L, 1); - const auto& b = lua::tovec(L, 2); - return lua::pushnumber(L, glm::dot(a, b)); -} - -template -static int l_inverse(lua::State* L) { - uint argc = lua::gettop(L); - if (argc != 1) { - throw std::runtime_error("invalid arguments number (1 expected)"); - } - const auto& _vector = lua::tovec(L, 1); //vector - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = -_vector[i]; - } - return lua::setvec(L, 1, result_vector); } template From 48f5926f1dba54b82e0728a9a45b7b96ae10c207 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 22:13:16 +0300 Subject: [PATCH 20/23] small fix in libvecn.cpp --- src/logic/scripting/lua/libvecn.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index d711a13a..a0e15499 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -149,7 +149,7 @@ static int l_dot(lua::State* L) { if (argc == 2) { const auto& a = lua::tovec(L, 1); const auto& b = lua::tovec(L, 2); - return lua::pushnumber(L, glm::dot(a, b));; + return lua::pushnumber(L, glm::dot(a, b)); } else if (argc == 3) { const auto& a = lua::tovec(L, 1); const auto& b = lua::tovec(L, 2); From 783050c488e9ff7b871f52226f54ab3d1a626d36 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 22:29:29 +0300 Subject: [PATCH 21/23] ref: func in libvecn.cpp --- src/logic/scripting/lua/libvecn.cpp | 68 +++++++++++------------------ 1 file changed, 25 insertions(+), 43 deletions(-) diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index a0e15499..9d92084c 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -72,49 +72,34 @@ static int l_scalar_op(lua::State* L) { template static int l_pow(lua::State* L) { uint argc = lua::gettop(L); - if (argc == 2) { - const auto& a = lua::tovec(L, 1); //vector - if (lua::isnumber(L, 2)) { // scalar second operand overload - const auto& b = lua::tonumber(L, 2); //scalar (pow) + if (argc == 2 || argc == 3) { + const auto& a = lua::tovec(L, 1); // vector + bool is_b_scalar = lua::isnumber(L, 2); + if (is_b_scalar || (argc == 3 && lua::isnumber(L, 2))) { + + const auto& b = is_b_scalar + ? lua::tonumber(L, 2) // scalar (pow) + : lua::tovec(L, 2)[0]; // vector (pow) + glm::vec result_vector; + for (int i = 0; i < n; i++) { result_vector[i] = pow(a[i], b); } - lua::createtable(L, n, 0); - for (uint i = 0; i < n; i++) { - lua::pushnumber(L, result_vector[i]); - lua::rawseti(L, i+1); + + if (argc == 2) { + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, result_vector[i]); + lua::rawseti(L, i+1); + } + return 1; + + } else { + return lua::setvec(L, 3, result_vector); } - return 1; } else { - const auto& b = lua::tovec(L, 2); //vector - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b[i]); - } - lua::createtable(L, n, 0); - for (uint i = 0; i < n; i++) { - lua::pushnumber(L, result_vector[i]); - lua::rawseti(L, i+1); - } - return 1; - } - } else if (argc == 3) { - const auto& a = lua::tovec(L, 1); //vector - if (lua::isnumber(L, 2)) { // scalar second operand overload - const auto& b = lua::tonumber(L, 2); //scalar (pow) - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b); - } - return lua::setvec(L, 3, result_vector); - } else { - const auto& b = lua::tovec(L, 2); //vector - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b[i]); - } - return lua::setvec(L, 3, result_vector); + throw std::runtime_error("invalid arguments number (2 or 3 expected)"); } } else { throw std::runtime_error("invalid arguments number (2 or 3 expected)"); @@ -146,14 +131,11 @@ static int l_inverse(lua::State* L) { template static int l_dot(lua::State* L) { uint argc = lua::gettop(L); - if (argc == 2) { + if (argc == 2 || argc == 3) { const auto& a = lua::tovec(L, 1); const auto& b = lua::tovec(L, 2); - return lua::pushnumber(L, glm::dot(a, b)); - } else if (argc == 3) { - const auto& a = lua::tovec(L, 1); - const auto& b = lua::tovec(L, 2); - return lua::pushnumber(L, glm::dot(a, b)); + lua::pushnumber(L, glm::dot(a, b)); + return 1; } else { throw std::runtime_error("invalid arguments number (2 or 3 expected)"); } From e55d6a36e36fec5c02b3a7b495cd5f0a001effc6 Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 22:48:05 +0300 Subject: [PATCH 22/23] fix func in libvecn --- doc/ru/scripting/builtins/libvecn.md | 26 ++++++ src/logic/scripting/lua/libvecn.cpp | 127 ++++++++++++++++++--------- 2 files changed, 111 insertions(+), 42 deletions(-) diff --git a/doc/ru/scripting/builtins/libvecn.md b/doc/ru/scripting/builtins/libvecn.md index 9f20dfed..bc847bf9 100644 --- a/doc/ru/scripting/builtins/libvecn.md +++ b/doc/ru/scripting/builtins/libvecn.md @@ -31,6 +31,9 @@ vecn.add(a: vector, b: vector) -- возвращает результат сложения вектора и скаляра vecn.add(a: vector, b: number) + +-- записывает результат сложения двух векторов в dst +vec.add(a: vector, b: vector, dst: vector) ``` #### Вычитание - *vecn.sub(...)* @@ -41,6 +44,9 @@ vecn.sub(a: vector, b: vector) -- возвращает результат вычитания скаляра из вектора vecn.sub(a: vector, b: number) + +-- записывает результат вычитания двух векторов в dst +vec.sub(a: vector, b: vector, dst: vector) ``` #### Умножение - *vecn.mul(...)* @@ -58,6 +64,9 @@ vecn.mul(a: vector, b: number) ```lua -- возвращает результат инверсии (противоположный) вектора vecn.inverse(a: vector) + +-- записывает инвертированный вектор в dst +vec.inverse(v: vector, dst: vector) ``` #### Деление - *vecn.div(...)* @@ -68,6 +77,9 @@ vecn.div(a: vector, b: vector) -- возвращает результат деления вектора на скаляр vecn.div(a: vector, b: number) + +-- записывает результат деления двух векторов в dst +vec.div(a: vector, b: vector, dst: vector) ``` #### Нормализация - *vecn.norm(...)* @@ -75,12 +87,17 @@ vecn.div(a: vector, b: number) ```lua -- возвращает нормализованный вектор vecn.normalize(a: vector) + +-- записывает нормализованный вектор в dst +vec.normalize(v: vector, dst: vector) ``` + #### Длина вектора - *vecn.len(...)* ```lua -- возвращает длину вектора vecn.length(a: vector) + ``` #### Абсолютное значение - *vecn.abs(...)* @@ -88,6 +105,9 @@ vecn.length(a: vector) ```lua -- возвращает вектор с абсолютными значениями vecn.abs(a: vector) + +-- записывает абсолютное значение вектора в dst +vec.abs(v: vector, dst: vector) ``` #### Округление - *vecn.round(...)* @@ -95,6 +115,9 @@ vecn.abs(a: vector) ```lua -- возвращает вектор с округленными значениями vecn.round(a: vector) + +-- записывает округленный вектор в dst +vec.round(v: vector, dst: vector) ``` #### Степень - *vecn.pow(...)* @@ -102,6 +125,9 @@ vecn.round(a: vector) ```lua -- возвращает вектор с элементами, возведенными в степень vecn.pow(a: vector, b: number) + +-- записывает вектор, возведенный в степень, в dst +vec.pow(v: vector, exponent: number, dst: vector) ``` #### Скалярное произведение - *vecn.dot(...)* diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index 9d92084c..a045f84c 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -72,51 +72,100 @@ static int l_scalar_op(lua::State* L) { template static int l_pow(lua::State* L) { uint argc = lua::gettop(L); - if (argc == 2 || argc == 3) { - const auto& a = lua::tovec(L, 1); // vector - bool is_b_scalar = lua::isnumber(L, 2); - if (is_b_scalar || (argc == 3 && lua::isnumber(L, 2))) { - - const auto& b = is_b_scalar - ? lua::tonumber(L, 2) // scalar (pow) - : lua::tovec(L, 2)[0]; // vector (pow) + if (argc != 2 && argc != 3) { + throw std::runtime_error("invalid arguments number (2 or 3 expected)"); + } + const auto& a = lua::tovec(L, 1); //vector + if (lua::isnumber(L, 2)) { // scalar second operand overload + const auto& b = lua::tonumber(L, 2); //scalar (pow) + if (argc == 2) { glm::vec result_vector; - for (int i = 0; i < n; i++) { result_vector[i] = pow(a[i], b); } - - if (argc == 2) { - lua::createtable(L, n, 0); - for (uint i = 0; i < n; i++) { - lua::pushnumber(L, result_vector[i]); - lua::rawseti(L, i+1); - } - return 1; - - } else { - return lua::setvec(L, 3, result_vector); + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, result_vector[i]); + lua::rawseti(L, i+1); } + return 1; } else { - throw std::runtime_error("invalid arguments number (2 or 3 expected)"); + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b); + } + lua::pushvalue(L, 3); + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, result_vector[i]); + lua::rawseti(L, i+1); + } + lua_settable(L, 3); + return 0; } } else { + const auto& b = lua::tovec(L, 2); //vector + if (argc == 2) { + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b[i]); + } + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, result_vector[i]); + lua::rawseti(L, i+1); + } + return 1; + } else { + glm::vec result_vector; + for (int i = 0; i < n; i++) { + result_vector[i] = pow(a[i], b[i]); + } + lua::pushvalue(L, 3); + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, result_vector[i]); + lua::rawseti(L, i+1); + } + lua_settable(L, 3); + return 0; + } + } +} + +template +static int l_dot(lua::State* L) { + uint argc = lua::gettop(L); + if (argc != 2 && argc != 3) { throw std::runtime_error("invalid arguments number (2 or 3 expected)"); } + const auto& a = lua::tovec(L, 1); + const auto& b = lua::tovec(L, 2); + if (argc == 2) { + lua::pushnumber(L, glm::dot(a, b)); + return 1; + } else { + lua::pushnumber(L, glm::dot(a, b)); + lua_settable(L, 3); + return 0; + } } template static int l_inverse(lua::State* L) { uint argc = lua::gettop(L); + if (argc != 1 && argc != 2) { + throw std::runtime_error("invalid arguments number (1 or 2 expected)"); + } + const auto& _vector = lua::tovec(L, 1); //vector + glm::vec result_vector; + + for (int i = 0; i < n; i++) { + result_vector[i] = -_vector[i]; + } + if (argc == 1) { - const auto& _vector = lua::tovec(L, 1); //vector - glm::vec result_vector; - - for (int i = 0; i < n; i++) { - result_vector[i] = -_vector[i]; - } - lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { lua::pushnumber(L, result_vector[i]); @@ -124,20 +173,14 @@ static int l_inverse(lua::State* L) { } return 1; } else { - throw std::runtime_error("invalid arguments number (1 expected)"); - } -} - -template -static int l_dot(lua::State* L) { - uint argc = lua::gettop(L); - if (argc == 2 || argc == 3) { - const auto& a = lua::tovec(L, 1); - const auto& b = lua::tovec(L, 2); - lua::pushnumber(L, glm::dot(a, b)); - return 1; - } else { - throw std::runtime_error("invalid arguments number (2 or 3 expected)"); + lua::pushvalue(L, 2); + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, result_vector[i]); + lua::rawseti(L, i+1); + } + lua_settable(L, 2); + return 0; } } From 175cfdf48863321bf2603d4177cfe5dab9564b4e Mon Sep 17 00:00:00 2001 From: Cogi Asd Date: Mon, 8 Jul 2024 23:15:53 +0300 Subject: [PATCH 23/23] fix func --- src/logic/scripting/lua/libvecn.cpp | 97 +++++++---------------------- 1 file changed, 24 insertions(+), 73 deletions(-) diff --git a/src/logic/scripting/lua/libvecn.cpp b/src/logic/scripting/lua/libvecn.cpp index a045f84c..875a0562 100644 --- a/src/logic/scripting/lua/libvecn.cpp +++ b/src/logic/scripting/lua/libvecn.cpp @@ -75,61 +75,31 @@ static int l_pow(lua::State* L) { if (argc != 2 && argc != 3) { throw std::runtime_error("invalid arguments number (2 or 3 expected)"); } - const auto& a = lua::tovec(L, 1); //vector + auto a = lua::tovec(L, 1); - if (lua::isnumber(L, 2)) { // scalar second operand overload - const auto& b = lua::tonumber(L, 2); //scalar (pow) + if (lua::isnumber(L, 2)) { + auto b = lua::tonumber(L, 2); if (argc == 2) { - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b); - } lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { - lua::pushnumber(L, result_vector[i]); + lua::pushnumber(L, pow(a[i], b)); lua::rawseti(L, i+1); } return 1; } else { - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b); - } - lua::pushvalue(L, 3); - lua::createtable(L, n, 0); - for (uint i = 0; i < n; i++) { - lua::pushnumber(L, result_vector[i]); - lua::rawseti(L, i+1); - } - lua_settable(L, 3); - return 0; + return lua::setvec(L, 3, pow(a, glm::vec(b))); } } else { - const auto& b = lua::tovec(L, 2); //vector + auto b = lua::tovec(L, 2); if (argc == 2) { - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b[i]); - } lua::createtable(L, n, 0); for (uint i = 0; i < n; i++) { - lua::pushnumber(L, result_vector[i]); + lua::pushnumber(L, pow(a[i], b[i])); lua::rawseti(L, i+1); } return 1; } else { - glm::vec result_vector; - for (int i = 0; i < n; i++) { - result_vector[i] = pow(a[i], b[i]); - } - lua::pushvalue(L, 3); - lua::createtable(L, n, 0); - for (uint i = 0; i < n; i++) { - lua::pushnumber(L, result_vector[i]); - lua::rawseti(L, i+1); - } - lua_settable(L, 3); - return 0; + return lua::setvec(L, 3, pow(a, b)); } } } @@ -137,50 +107,31 @@ static int l_pow(lua::State* L) { template static int l_dot(lua::State* L) { uint argc = lua::gettop(L); - if (argc != 2 && argc != 3) { - throw std::runtime_error("invalid arguments number (2 or 3 expected)"); + if (argc != 1) { + throw std::runtime_error("invalid arguments number (1 expected)"); } const auto& a = lua::tovec(L, 1); const auto& b = lua::tovec(L, 2); - if (argc == 2) { - lua::pushnumber(L, glm::dot(a, b)); - return 1; - } else { - lua::pushnumber(L, glm::dot(a, b)); - lua_settable(L, 3); - return 0; - } + return lua::pushnumber(L, glm::dot(a, b)); } template static int l_inverse(lua::State* L) { uint argc = lua::gettop(L); - if (argc != 1 && argc != 2) { - throw std::runtime_error("invalid arguments number (1 or 2 expected)"); - } - const auto& _vector = lua::tovec(L, 1); //vector - glm::vec result_vector; - - for (int i = 0; i < n; i++) { - result_vector[i] = -_vector[i]; - } - - if (argc == 1) { - lua::createtable(L, n, 0); - for (uint i = 0; i < n; i++) { - lua::pushnumber(L, result_vector[i]); - lua::rawseti(L, i+1); + auto vec = lua::tovec(L, 1); + switch (argc) { + case 1: + lua::createtable(L, n, 0); + for (uint i = 0; i < n; i++) { + lua::pushnumber(L, (-1)*vec[i]); + lua::rawseti(L, i+1); + } + return 1; + case 2: + return lua::setvec(L, 2, -vec); + default: { + throw std::runtime_error("invalid arguments number (1 or 2 expected)"); } - return 1; - } else { - lua::pushvalue(L, 2); - lua::createtable(L, n, 0); - for (uint i = 0; i < n; i++) { - lua::pushnumber(L, result_vector[i]); - lua::rawseti(L, i+1); - } - lua_settable(L, 2); - return 0; } }