diff --git a/.github/workflows/appimage.yml b/.github/workflows/appimage.yml index 398c3b5c..00b7e0be 100644 --- a/.github/workflows/appimage.yml +++ b/.github/workflows/appimage.yml @@ -2,7 +2,7 @@ name: C/C++ AppImage on: push: - branches: [ "main" ] + branches: [ "main", "release-**"] pull_request: branches: [ "main" ] @@ -24,8 +24,15 @@ jobs: run: | sudo apt-get update sudo apt-get install -y build-essential libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev cmake squashfs-tools + # fix luajit paths sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua5.1.a sudo ln -s /usr/include/luajit-2.1 /usr/include/lua + # install EnTT + git clone https://github.com/skypjack/entt.git + cd entt/build + cmake -DCMAKE_BUILD_TYPE=Release .. + sudo make install + cd ../.. - name: configure run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DVOXELENGINE_BUILD_APPDIR=1 - name: build diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 075c4b74..dce8c120 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -36,8 +36,15 @@ jobs: run: | sudo apt-get update sudo apt-get install libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev + # fix luajit paths sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua-5.1.a sudo ln -s /usr/include/luajit-2.1 /usr/include/lua + # install EnTT + git clone https://github.com/skypjack/entt.git + cd entt/build + cmake -DCMAKE_BUILD_TYPE=Release .. + sudo make install + cd ../.. - name: Configure CMake # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 371e1ac1..dd7152ab 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -17,7 +17,7 @@ jobs: - name: Install dependencies from brew run: | - brew install glfw3 glew libpng openal-soft luajit libvorbis + brew install glfw3 glew libpng openal-soft luajit libvorbis skypjack/entt/entt - name: Install specific version of GLM run: | @@ -48,4 +48,4 @@ jobs: uses: actions/upload-artifact@v4 with: name: VoxelEngineMacOs - path: VoxelEngineMacApp.dmg \ No newline at end of file + path: VoxelEngineMacApp.dmg diff --git a/.gitignore b/.gitignore index 72fa6d1a..d7b5168d 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,8 @@ Debug/voxel_engine /worlds/**/* /settings.toml /controls.json +/controls.toml +/latest.log /.idea .vscode diff --git a/CMakeLists.txt b/CMakeLists.txt index 2ec2faab..11a01b7e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -84,6 +84,9 @@ find_package(OpenGL REQUIRED) find_package(GLEW REQUIRED) find_package(OpenAL REQUIRED) find_package(ZLIB REQUIRED) +if (NOT APPLE) + find_package(EnTT REQUIRED) +endif() if (WIN32) if(VOXELENGINE_BUILD_WINDOWS_VCPKG) @@ -120,7 +123,6 @@ else() set(LUA_LIBRARIES ${LUAJIT_LIBRARIES}) set(LUA_INCLUDE_DIR ${LUAJIT_INCLUDE_DIRS}) find_package(PNG REQUIRED) - find_package(Lua REQUIRED) set(PNGLIB PNG::PNG) set(VORBISLIB ${VORBIS_LDFLAGS}) endif() diff --git a/README.md b/README.md index b248c8ed..65422cfc 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,14 @@ cmake --build . ## Install libs: +#### Install EnTT +```sh +git clone https://github.com/skypjack/entt.git +cd entt/build +cmake -DCMAKE_BUILD_TYPE=Release .. +sudo make install +``` + #### Debian-based distro: ```sh sudo apt install libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev @@ -59,7 +67,7 @@ sudo pacman -S glfw-wayland glew glm libpng libvorbis openal luajit #### macOS: ``` -brew install glfw3 glew glm libpng libvorbis lua luajit openal-soft +brew install glfw3 glew glm libpng libvorbis lua luajit openal-soft skypjack/entt/entt ``` If homebrew for some reason could not install the necessary packages: ```lua luajit openal-soft```, then download, install and compile them manually (Lua, LuaJIT and OpenAL). diff --git a/doc/ru/0.Главная.md b/doc/ru/0.Главная.md index ae961c9e..3a638d98 100644 --- a/doc/ru/0.Главная.md +++ b/doc/ru/0.Главная.md @@ -10,4 +10,7 @@ - [Скриптинг](8.Скриптинг.md) - [Модуль core:bit_converter](8.1.Модуль-Lua-core_bit_converter.md) - [Модуль core:data_buffer](8.2.Модуль-Lua-core_data_buffer.md) + - [Пользовательский ввод](Пользовательский-ввод.md) + - [Файловая система и сериализация](Файловая-система-и-сериализация.md) +- [Консоль](Консоль.md) - [Модели блоков](9.Модели-блоков.md) diff --git a/res/content/base/block_materials/carpet.json b/res/content/base/block_materials/carpet.json new file mode 100644 index 00000000..4d4d11dc --- /dev/null +++ b/res/content/base/block_materials/carpet.json @@ -0,0 +1,5 @@ +{ + "steps-sound": "steps/carpet", + "place-sound": "blocks/carpet_place", + "break-sound": "blocks/carpet_break" +} diff --git a/res/content/base/block_materials/glass.json b/res/content/base/block_materials/glass.json index 86693a6e..fd2e2323 100644 --- a/res/content/base/block_materials/glass.json +++ b/res/content/base/block_materials/glass.json @@ -1,5 +1,5 @@ { - "steps-sound": "steps/wood", - "place-sound": "blocks/wood_place", + "steps-sound": "steps/glass", + "place-sound": "blocks/glass_place", "break-sound": "blocks/glass_break" } diff --git a/res/content/base/block_materials/metal.json b/res/content/base/block_materials/metal.json new file mode 100644 index 00000000..6f45903e --- /dev/null +++ b/res/content/base/block_materials/metal.json @@ -0,0 +1,5 @@ +{ + "steps-sound": "steps/metal", + "place-sound": "blocks/metal_place", + "break-sound": "blocks/metal_break" +} diff --git a/res/content/base/block_materials/sand.json b/res/content/base/block_materials/sand.json index 00901142..67316ba3 100644 --- a/res/content/base/block_materials/sand.json +++ b/res/content/base/block_materials/sand.json @@ -1,5 +1,5 @@ { "steps-sound": "steps/sand", - "steps-sound": "blocks/ground_place", + "place-sound": "blocks/ground_place", "break-sound": "blocks/ground_break" } diff --git a/res/content/base/blocks/blue_lamp.json b/res/content/base/blocks/blue_lamp.json index ca6f81cc..18f48ae3 100644 --- a/res/content/base/blocks/blue_lamp.json +++ b/res/content/base/blocks/blue_lamp.json @@ -1,4 +1,5 @@ { "texture": "blue_lamp", - "emission": [0, 0, 15] -} \ No newline at end of file + "emission": [0, 0, 15], + "material": "base:glass" +} diff --git a/res/content/base/blocks/green_lamp.json b/res/content/base/blocks/green_lamp.json index debfb505..4f7e2cfa 100644 --- a/res/content/base/blocks/green_lamp.json +++ b/res/content/base/blocks/green_lamp.json @@ -1,4 +1,5 @@ { "texture": "green_lamp", - "emission": [0, 15, 0] -} \ No newline at end of file + "emission": [0, 15, 0], + "material": "base:glass" +} diff --git a/res/content/base/blocks/lightbulb.json b/res/content/base/blocks/lightbulb.json index f8aa71b3..a22cfaf3 100644 --- a/res/content/base/blocks/lightbulb.json +++ b/res/content/base/blocks/lightbulb.json @@ -6,5 +6,6 @@ "hitbox": [0.25, 0.0, 0.25, 0.5, 0.5, 0.5], "rotation": "pipe", "light-passing": true, - "sky-light-passing": true + "sky-light-passing": true, + "material": "base:glass" } diff --git a/res/content/base/blocks/metal.json b/res/content/base/blocks/metal.json index 8c02159d..c52d79a2 100644 --- a/res/content/base/blocks/metal.json +++ b/res/content/base/blocks/metal.json @@ -1,3 +1,4 @@ { - "texture": "metal" -} \ No newline at end of file + "texture": "metal", + "material": "base:metal" +} diff --git a/res/content/base/blocks/pipe.json b/res/content/base/blocks/pipe.json index eaaaff3c..ad297987 100644 --- a/res/content/base/blocks/pipe.json +++ b/res/content/base/blocks/pipe.json @@ -10,5 +10,6 @@ "model": "aabb", "hitbox": [0.25, 0.0, 0.25, 0.5, 1.0, 0.5], "light-passing": true, - "rotation": "pipe" + "rotation": "pipe", + "material": "base:metal" } diff --git a/res/content/base/blocks/red_lamp.json b/res/content/base/blocks/red_lamp.json index fc3a41ac..fe7e8cb1 100644 --- a/res/content/base/blocks/red_lamp.json +++ b/res/content/base/blocks/red_lamp.json @@ -1,4 +1,5 @@ { "texture": "red_lamp", - "emission": [15, 0, 0] -} \ No newline at end of file + "emission": [15, 0, 0], + "material": "base:glass" +} diff --git a/res/content/base/blocks/rust.json b/res/content/base/blocks/rust.json index 680c9da2..90e19363 100644 --- a/res/content/base/blocks/rust.json +++ b/res/content/base/blocks/rust.json @@ -1,3 +1,4 @@ { - "texture": "rust" -} \ No newline at end of file + "texture": "rust", + "material": "base:metal" +} diff --git a/res/content/base/blocks/wooden_door.json b/res/content/base/blocks/wooden_door.json new file mode 100644 index 00000000..9a1eb666 --- /dev/null +++ b/res/content/base/blocks/wooden_door.json @@ -0,0 +1,17 @@ +{ + "material": "base:wood", + "texture-faces": [ + "wooden_door_side", + "wooden_door_side", + "wooden_door_top", + "wooden_door_top", + "wooden_door", + "wooden_door" + ], + "light-passing": true, + "sky-light-passing": true, + "size": [1, 2, 1], + "rotation": "pane", + "model": "aabb", + "hitbox": [0.0, 0.0, 0.8, 1.0, 2.0, 0.2] +} diff --git a/res/content/base/content.json b/res/content/base/content.json index ef2f084b..0e6dc07f 100644 --- a/res/content/base/content.json +++ b/res/content/base/content.json @@ -25,6 +25,7 @@ "pane", "pipe", "lightbulb", - "torch" + "torch", + "wooden_door" ] } \ No newline at end of file diff --git a/res/content/base/package.json b/res/content/base/package.json index db620a3d..eeb24ed0 100644 --- a/res/content/base/package.json +++ b/res/content/base/package.json @@ -1,6 +1,6 @@ { "id": "base", "title": "Base", - "version": "0.21", + "version": "0.22", "description": "basic content package" } diff --git a/res/content/base/preload.json b/res/content/base/preload.json new file mode 100644 index 00000000..801938a6 --- /dev/null +++ b/res/content/base/preload.json @@ -0,0 +1,6 @@ +{ + "sounds": [ + "blocks/door_open", + "blocks/door_close" + ] +} diff --git a/res/content/base/scripts/wooden_door.lua b/res/content/base/scripts/wooden_door.lua new file mode 100644 index 00000000..b922464d --- /dev/null +++ b/res/content/base/scripts/wooden_door.lua @@ -0,0 +1,13 @@ +function on_interact(x, y, z) + local inc = 1 + if block.get_user_bits(x, y, z, 0, 1) > 0 then + inc = 3 + block.set_user_bits(x, y, z, 0, 1, 0) + audio.play_sound("blocks/door_close", x+0.5, y+1, z+0.5, 1, 1) + else + block.set_user_bits(x, y, z, 0, 1, 1) + audio.play_sound("blocks/door_open", x+0.5, y+1, z+0.5, 1, 1) + end + block.set_rotation(x, y, z, (block.get_rotation(x, y, z) + inc) % 4) + return true +end diff --git a/res/content/base/sounds/blocks/carpet_break.ogg b/res/content/base/sounds/blocks/carpet_break.ogg new file mode 100644 index 00000000..49f4592e Binary files /dev/null and b/res/content/base/sounds/blocks/carpet_break.ogg differ diff --git a/res/content/base/sounds/blocks/carpet_place.ogg b/res/content/base/sounds/blocks/carpet_place.ogg new file mode 100644 index 00000000..aac944ef Binary files /dev/null and b/res/content/base/sounds/blocks/carpet_place.ogg differ diff --git a/res/content/base/sounds/blocks/door_close.ogg b/res/content/base/sounds/blocks/door_close.ogg new file mode 100644 index 00000000..53ead574 Binary files /dev/null and b/res/content/base/sounds/blocks/door_close.ogg differ diff --git a/res/content/base/sounds/blocks/door_open.ogg b/res/content/base/sounds/blocks/door_open.ogg new file mode 100644 index 00000000..77aadf80 Binary files /dev/null and b/res/content/base/sounds/blocks/door_open.ogg differ diff --git a/res/content/base/sounds/blocks/glass_break.ogg b/res/content/base/sounds/blocks/glass_break.ogg index 1da0b6a4..80c30ca2 100644 Binary files a/res/content/base/sounds/blocks/glass_break.ogg and b/res/content/base/sounds/blocks/glass_break.ogg differ diff --git a/res/content/base/sounds/blocks/glass_place.ogg b/res/content/base/sounds/blocks/glass_place.ogg new file mode 100644 index 00000000..f1969e2f Binary files /dev/null and b/res/content/base/sounds/blocks/glass_place.ogg differ diff --git a/res/content/base/sounds/blocks/metal_break.ogg b/res/content/base/sounds/blocks/metal_break.ogg new file mode 100644 index 00000000..13a7ae4a Binary files /dev/null and b/res/content/base/sounds/blocks/metal_break.ogg differ diff --git a/res/content/base/sounds/blocks/metal_place_0.ogg b/res/content/base/sounds/blocks/metal_place_0.ogg new file mode 100644 index 00000000..0cac1de5 Binary files /dev/null and b/res/content/base/sounds/blocks/metal_place_0.ogg differ diff --git a/res/content/base/sounds/blocks/metal_place_1.ogg b/res/content/base/sounds/blocks/metal_place_1.ogg new file mode 100644 index 00000000..f57f9d0d Binary files /dev/null and b/res/content/base/sounds/blocks/metal_place_1.ogg differ diff --git a/res/content/base/sounds/steps/carpet_0.ogg b/res/content/base/sounds/steps/carpet_0.ogg new file mode 100644 index 00000000..b0df423a Binary files /dev/null and b/res/content/base/sounds/steps/carpet_0.ogg differ diff --git a/res/content/base/sounds/steps/carpet_1.ogg b/res/content/base/sounds/steps/carpet_1.ogg new file mode 100644 index 00000000..26ead41d Binary files /dev/null and b/res/content/base/sounds/steps/carpet_1.ogg differ diff --git a/res/content/base/sounds/steps/carpet_2.ogg b/res/content/base/sounds/steps/carpet_2.ogg new file mode 100644 index 00000000..622f3f16 Binary files /dev/null and b/res/content/base/sounds/steps/carpet_2.ogg differ diff --git a/res/content/base/sounds/steps/carpet_3.ogg b/res/content/base/sounds/steps/carpet_3.ogg new file mode 100644 index 00000000..2250bd06 Binary files /dev/null and b/res/content/base/sounds/steps/carpet_3.ogg differ diff --git a/res/content/base/sounds/steps/glass_0.ogg b/res/content/base/sounds/steps/glass_0.ogg new file mode 100644 index 00000000..cfa2ff24 Binary files /dev/null and b/res/content/base/sounds/steps/glass_0.ogg differ diff --git a/res/content/base/sounds/steps/glass_1.ogg b/res/content/base/sounds/steps/glass_1.ogg new file mode 100644 index 00000000..47937c42 Binary files /dev/null and b/res/content/base/sounds/steps/glass_1.ogg differ diff --git a/res/content/base/sounds/steps/glass_2.ogg b/res/content/base/sounds/steps/glass_2.ogg new file mode 100644 index 00000000..b983e072 Binary files /dev/null and b/res/content/base/sounds/steps/glass_2.ogg differ diff --git a/res/content/base/sounds/steps/glass_3.ogg b/res/content/base/sounds/steps/glass_3.ogg new file mode 100644 index 00000000..aef7174c Binary files /dev/null and b/res/content/base/sounds/steps/glass_3.ogg differ diff --git a/res/content/base/sounds/steps/metal_0.ogg b/res/content/base/sounds/steps/metal_0.ogg new file mode 100644 index 00000000..ecac2834 Binary files /dev/null and b/res/content/base/sounds/steps/metal_0.ogg differ diff --git a/res/content/base/sounds/steps/metal_1.ogg b/res/content/base/sounds/steps/metal_1.ogg new file mode 100644 index 00000000..e9985c6a Binary files /dev/null and b/res/content/base/sounds/steps/metal_1.ogg differ diff --git a/res/content/base/sounds/steps/metal_2.ogg b/res/content/base/sounds/steps/metal_2.ogg new file mode 100644 index 00000000..7a441b8b Binary files /dev/null and b/res/content/base/sounds/steps/metal_2.ogg differ diff --git a/res/content/base/sounds/steps/metal_3.ogg b/res/content/base/sounds/steps/metal_3.ogg new file mode 100644 index 00000000..c8ce9401 Binary files /dev/null and b/res/content/base/sounds/steps/metal_3.ogg differ diff --git a/res/content/base/sounds/steps/stone_0.ogg b/res/content/base/sounds/steps/stone_0.ogg index 1ff4a84c..15d22bf2 100644 Binary files a/res/content/base/sounds/steps/stone_0.ogg and b/res/content/base/sounds/steps/stone_0.ogg differ diff --git a/res/content/base/sounds/steps/stone_1.ogg b/res/content/base/sounds/steps/stone_1.ogg index 71b8b388..c45ee998 100644 Binary files a/res/content/base/sounds/steps/stone_1.ogg and b/res/content/base/sounds/steps/stone_1.ogg differ diff --git a/res/content/base/sounds/steps/stone_2.ogg b/res/content/base/sounds/steps/stone_2.ogg index 6802e5f9..a2701542 100644 Binary files a/res/content/base/sounds/steps/stone_2.ogg and b/res/content/base/sounds/steps/stone_2.ogg differ diff --git a/res/content/base/sounds/steps/stone_3.ogg b/res/content/base/sounds/steps/stone_3.ogg index 87d2377f..5d3fdcec 100644 Binary files a/res/content/base/sounds/steps/stone_3.ogg and b/res/content/base/sounds/steps/stone_3.ogg differ diff --git a/res/content/base/textures/blocks/wooden_door.png b/res/content/base/textures/blocks/wooden_door.png new file mode 100644 index 00000000..ad651ac6 Binary files /dev/null and b/res/content/base/textures/blocks/wooden_door.png differ diff --git a/res/content/base/textures/blocks/wooden_door_side.png b/res/content/base/textures/blocks/wooden_door_side.png new file mode 100644 index 00000000..9201f08c Binary files /dev/null and b/res/content/base/textures/blocks/wooden_door_side.png differ diff --git a/res/content/base/textures/blocks/wooden_door_top.png b/res/content/base/textures/blocks/wooden_door_top.png new file mode 100644 index 00000000..96e2a73d Binary files /dev/null and b/res/content/base/textures/blocks/wooden_door_top.png differ diff --git a/res/layouts/console.xml.lua b/res/layouts/console.xml.lua index 31314ca5..f71920ce 100644 --- a/res/layouts/console.xml.lua +++ b/res/layouts/console.xml.lua @@ -38,12 +38,7 @@ function submit(text) document.log.caret = -1 local status, result = pcall(function() return console.execute(text) end) if result ~= nil then - local prevtext = document.log.text - if #prevtext == 0 then - document.log:paste(tostring(result)) - else - document.log:paste('\n'..tostring(result)) - end + console.log(result) end document.prompt.text = "" document.prompt.focused = true diff --git a/res/scripts/stdlib.lua b/res/scripts/stdlib.lua index 877d38a4..1873dd3e 100644 --- a/res/scripts/stdlib.lua +++ b/res/scripts/stdlib.lua @@ -203,6 +203,24 @@ function time.post_runnable(runnable) table.insert(__post_runnables, runnable) end +local log_element = Document.new("core:console").log +function console.log(...) + local args = {...} + local text = '' + for i,v in ipairs(args) do + if i ~= 1 then + text = text..' '..v + else + text = text..v + end + end + log_element.caret = -1 + if log_element.caret > 0 then + text = '\n'..text + end + log_element:paste(text) +end + function gui.template(name, params) local text = file.read(file.find("layouts/templates/"..name..".xml")) for k,v in pairs(params) do diff --git a/res/texts/fi_FI.txt b/res/texts/fi_FI.txt index ceadc3ad..6a84f24d 100644 --- a/res/texts/fi_FI.txt +++ b/res/texts/fi_FI.txt @@ -13,58 +13,62 @@ error.dependency-not-found=Käytetty riippuvuutta ei löytynyt pack.remove-confirm=Poistetaanko kaikki pakettien sisältö maailmasta (peruuttamattomasti)? # Меню -menu.New World=Uusi Maailma -menu.Quit=Poistu -menu.Continue=Jatka -menu.Save and Quit to Menu=Tallenna ja poistu valikkoon -menu.missing-content=Ei ole sisältöä! -menu.Content Error=Sisältövirhe -menu.Controls=Ohjaus -menu.Back to Main Menu=Takaisin Valikoon -menu.Settings=Asetukset +menu.Apply=Tallenna +menu.Audio=Ääni +menu.Back to Main Menu=Takaisin Valikkoon +menu.Content Error=Virhe Sisällössä menu.Content=Sisältö -menu.Audio=Audio +menu.Continue=Jatka +menu.Controls=Ohjaus +menu.Graphics=Grafiikka +menu.missing-content=Sisältö Puuttuu! +menu.New World=Uusi Maailma +menu.Page not found=Sivu ei löytynyt! +menu.Quit=Poistu +menu.Save and Quit to Menu=Tallenna ja Takaisin Valikkoon +menu.Settings=Asetukset + world.Seed=Siemen world.Name=Nimi - -world.World generator=Maailman generaattori +world.World generator=Maailma Generaatori world.generators.default=Tavallinen world.generators.flat=Tasainen -menu.Create World=Luo Maailma - -world.convert-request=Indeksit ovat muuttuneet! Luodaanko maailma uudeleen? -world.delete-confirm=Poistetaanko maailma peruuttamattomasti? +world.Create World=Luo Maailma +world.convert-request=Indekseissä on muutoksia! Kääntää maailman? +world.delete-confirm=Poistetaanko maailma pysyvästi? # Настройки -settings.Load Distance=Latausalue -settings.Load Speed=Latausnopeus -settings.Fog Curve=Sumun tiheys -settings.Backlight=Taustavalo -settings.V-Sync=Pystytahdistus -settings.Camera Shaking=Kameran tärähdys -settings.Master Volume=Pää-äänekkyys -settings.Regular Sounds=Tavalliset äänet -settings.UI Sounds=Käyttöliittymän äänet settings.Ambient=Tausta -settings.Music=Musiikki - -settings.FOV=Näkökenttä -settings.Mouse Sensitivity=Hiiren nopeus +settings.Backlight=Taustavalo +settings.Camera Shaking=Tärisevä kamera +settings.Fog Curve=Sumukäurä +settings.FOV=Näkokenttä +settings.Fullscreen=Koko näyttö +settings.Gamma=Gamma settings.Language=Kieli +settings.Load Distance=Latausetäisyys +settings.Load Speed=Latausnopeus +settings.Master Volume=Yleinen äänen voimakkuus +settings.Mouse Sensitivity=Hiiren herkkyys +settings.Music=Musiikki +settings.Regular Sounds=Tavalliset Äänet +settings.UI Sounds=Käyttöliittymän äänet +settings.V-Sync=Pystytahdistus # Управление +devtools.console=Konsoli movement.forward=Eteenpäin movement.back=Taaksepäin -movement.left=Vaseemalle +movement.left=Vaseemmalle movement.right=Oikealle movement.jump=Hyppy -movement.sprint=Juoksu +movement.sprint=Kiihtyvyys movement.crouch=Hiipiä movement.cheat=Huijata hud.inventory=Varasto -player.pick=Ottaa lohko +player.pick=Valitse lohko player.attack=Lyödä / Rikkoa player.build=Aseta lohko player.flight=Lento camera.zoom=Lähentäminen -camera.mode=Vaihda Kameratila +camera.mode=Vaihda kameratilaa diff --git a/src/assets/Assets.cpp b/src/assets/Assets.cpp index 12a3db65..73ed5ede 100644 --- a/src/assets/Assets.cpp +++ b/src/assets/Assets.cpp @@ -11,59 +11,59 @@ Assets::~Assets() { } -Texture* Assets::getTexture(std::string name) const { +Texture* Assets::getTexture(const std::string& name) const { auto found = textures.find(name); if (found == textures.end()) return nullptr; return found->second.get(); } -void Assets::store(std::unique_ptr texture, std::string name){ +void Assets::store(std::unique_ptr texture, const std::string& name){ textures.emplace(name, std::move(texture)); } -Shader* Assets::getShader(std::string name) const{ +Shader* Assets::getShader(const std::string& name) const{ auto found = shaders.find(name); if (found == shaders.end()) return nullptr; return found->second.get(); } -void Assets::store(std::unique_ptr shader, std::string name){ +void Assets::store(std::unique_ptr shader, const std::string& name){ shaders.emplace(name, std::move(shader)); } -Font* Assets::getFont(std::string name) const { +Font* Assets::getFont(const std::string& name) const { auto found = fonts.find(name); if (found == fonts.end()) return nullptr; return found->second.get(); } -void Assets::store(std::unique_ptr font, std::string name){ +void Assets::store(std::unique_ptr font, const std::string& name){ fonts.emplace(name, std::move(font)); } -Atlas* Assets::getAtlas(std::string name) const { +Atlas* Assets::getAtlas(const std::string& name) const { auto found = atlases.find(name); if (found == atlases.end()) return nullptr; return found->second.get(); } -void Assets::store(std::unique_ptr atlas, std::string name){ +void Assets::store(std::unique_ptr atlas, const std::string& name){ atlases.emplace(name, std::move(atlas)); } -audio::Sound* Assets::getSound(std::string name) const { +audio::Sound* Assets::getSound(const std::string& name) const { auto found = sounds.find(name); if (found == sounds.end()) return nullptr; return found->second.get(); } -void Assets::store(std::unique_ptr sound, std::string name) { +void Assets::store(std::unique_ptr sound, const std::string& name) { sounds.emplace(name, std::move(sound)); } @@ -75,13 +75,13 @@ void Assets::store(const TextureAnimation& animation) { animations.emplace_back(animation); } -UiDocument* Assets::getLayout(std::string name) const { +UiDocument* Assets::getLayout(const std::string& name) const { auto found = layouts.find(name); if (found == layouts.end()) return nullptr; return found->second.get(); } -void Assets::store(std::unique_ptr layout, std::string name) { +void Assets::store(std::unique_ptr layout, const std::string& name) { layouts[name] = std::shared_ptr(std::move(layout)); } diff --git a/src/assets/Assets.hpp b/src/assets/Assets.hpp index c06e764f..d4b0f31d 100644 --- a/src/assets/Assets.hpp +++ b/src/assets/Assets.hpp @@ -38,26 +38,26 @@ public: Assets(const Assets&) = delete; ~Assets(); - Texture* getTexture(std::string name) const; - void store(std::unique_ptr texture, std::string name); + Texture* getTexture(const std::string& name) const; + void store(std::unique_ptr texture, const std::string& name); - Shader* getShader(std::string name) const; - void store(std::unique_ptr shader, std::string name); + Shader* getShader(const std::string& name) const; + void store(std::unique_ptr shader, const std::string& name); - Font* getFont(std::string name) const; - void store(std::unique_ptr font, std::string name); + Font* getFont(const std::string& name) const; + void store(std::unique_ptr font, const std::string& name); - Atlas* getAtlas(std::string name) const; - void store(std::unique_ptr atlas, std::string name); + Atlas* getAtlas(const std::string& name) const; + void store(std::unique_ptr atlas, const std::string& name); - audio::Sound* getSound(std::string name) const; - void store(std::unique_ptr sound, std::string name); + audio::Sound* getSound(const std::string& name) const; + void store(std::unique_ptr sound, const std::string& name); const std::vector& getAnimations(); void store(const TextureAnimation& animation); - UiDocument* getLayout(std::string name) const; - void store(std::unique_ptr layout, std::string name); + UiDocument* getLayout(const std::string& name) const; + void store(std::unique_ptr layout, const std::string& name); }; #endif // ASSETS_ASSETS_HPP_ diff --git a/src/assets/AssetsLoader.cpp b/src/assets/AssetsLoader.cpp index 1f194c21..f55902e9 100644 --- a/src/assets/AssetsLoader.cpp +++ b/src/assets/AssetsLoader.cpp @@ -17,6 +17,7 @@ #include #include +#include static debug::Logger logger("assets-loader"); @@ -32,11 +33,11 @@ AssetsLoader::AssetsLoader(Assets* assets, const ResPaths* paths) } void AssetsLoader::addLoader(AssetType tag, aloader_func func) { - loaders[tag] = func; + loaders[tag] = std::move(func); } -void AssetsLoader::add(AssetType tag, const std::string filename, const std::string alias, std::shared_ptr settings) { - entries.push(aloader_entry{tag, filename, alias, settings}); +void AssetsLoader::add(AssetType tag, const std::string& filename, const std::string& alias, std::shared_ptr settings) { + entries.push(aloader_entry{tag, filename, alias, std::move(settings)}); } bool AssetsLoader::hasNext() const { @@ -69,12 +70,12 @@ bool AssetsLoader::loadNext() { } } -void addLayouts(scriptenv env, const std::string& prefix, const fs::path& folder, AssetsLoader& loader) { +void addLayouts(const scriptenv& env, const std::string& prefix, const fs::path& folder, AssetsLoader& loader) { if (!fs::is_directory(folder)) { return; } for (auto& entry : fs::directory_iterator(folder)) { - const fs::path file = entry.path(); + const fs::path& file = entry.path(); if (file.extension().u8string() != ".xml") continue; std::string name = prefix+":"+file.stem().u8string(); @@ -82,7 +83,7 @@ void addLayouts(scriptenv env, const std::string& prefix, const fs::path& folder } } -void AssetsLoader::tryAddSound(std::string name) { +void AssetsLoader::tryAddSound(const std::string& name) { if (name.empty()) { return; } @@ -148,7 +149,7 @@ void AssetsLoader::processPreloadList(AssetType tag, dynamic::List* list) { } } -void AssetsLoader::processPreloadConfig(fs::path file) { +void AssetsLoader::processPreloadConfig(const fs::path& file) { auto root = files::read_json(file); processPreloadList(AssetType::font, root->list("fonts")); processPreloadList(AssetType::shader, root->list("shaders")); @@ -209,7 +210,7 @@ void AssetsLoader::addDefaults(AssetsLoader& loader, const Content* content) { bool AssetsLoader::loadExternalTexture( Assets* assets, const std::string& name, - std::vector alternatives + const std::vector& alternatives ) { if (assets->getTexture(name) != nullptr) { return true; @@ -255,7 +256,7 @@ std::shared_ptr AssetsLoader::startTask(runnable onDone) { func(assets); } ); - pool->setOnComplete(onDone); + pool->setOnComplete(std::move(onDone)); while (!entries.empty()) { const aloader_entry& entry = entries.front(); auto ptr = std::make_shared(entry); diff --git a/src/assets/AssetsLoader.hpp b/src/assets/AssetsLoader.hpp index ffb03c03..b2d81916 100644 --- a/src/assets/AssetsLoader.hpp +++ b/src/assets/AssetsLoader.hpp @@ -12,6 +12,7 @@ #include #include #include +#include namespace dynamic { class Map; @@ -38,7 +39,7 @@ struct AssetCfg { struct LayoutCfg : AssetCfg { scriptenv env; - LayoutCfg(scriptenv env) : env(env) {} + LayoutCfg(scriptenv env) : env(std::move(env)) {} }; struct SoundCfg : AssetCfg { @@ -68,11 +69,11 @@ class AssetsLoader { std::queue entries; const ResPaths* paths; - void tryAddSound(std::string name); + void tryAddSound(const std::string& name); void processPreload(AssetType tag, const std::string& name, dynamic::Map* map); void processPreloadList(AssetType tag, dynamic::List* list); - void processPreloadConfig(std::filesystem::path file); + void processPreloadConfig(const std::filesystem::path& file); void processPreloadConfigs(const Content* content); public: AssetsLoader(Assets* assets, const ResPaths* paths); @@ -85,8 +86,8 @@ public: /// @param settings asset loading settings (based on asset type) void add( AssetType tag, - const std::string filename, - const std::string alias, + const std::string& filename, + const std::string& alias, std::shared_ptr settings=nullptr ); @@ -106,7 +107,7 @@ public: static bool loadExternalTexture( Assets* assets, const std::string& name, - std::vector alternatives + const std::vector& alternatives ); }; diff --git a/src/assets/assetload_funcs.cpp b/src/assets/assetload_funcs.cpp index bfe799bb..b30bd6da 100644 --- a/src/assets/assetload_funcs.cpp +++ b/src/assets/assetload_funcs.cpp @@ -36,9 +36,9 @@ static bool animation( assetload::postfunc assetload::texture( AssetsLoader*, const ResPaths* paths, - const std::string filename, - const std::string name, - std::shared_ptr + const std::string& filename, + const std::string& name, + const std::shared_ptr& ) { std::shared_ptr image ( imageio::read(paths->find(filename+".png").u8string()).release() @@ -51,9 +51,9 @@ assetload::postfunc assetload::texture( assetload::postfunc assetload::shader( AssetsLoader*, const ResPaths* paths, - const std::string filename, - const std::string name, - std::shared_ptr + const std::string& filename, + const std::string& name, + const std::shared_ptr& ) { fs::path vertexFile = paths->find(filename+".glslv"); fs::path fragmentFile = paths->find(filename+".glslf"); @@ -88,9 +88,9 @@ static bool append_atlas(AtlasBuilder& atlas, const fs::path& file) { assetload::postfunc assetload::atlas( AssetsLoader*, const ResPaths* paths, - const std::string directory, - const std::string name, - std::shared_ptr + const std::string& directory, + const std::string& name, + const std::shared_ptr& ) { AtlasBuilder builder; for (const auto& file : paths->listdir(directory)) { @@ -113,9 +113,9 @@ assetload::postfunc assetload::atlas( assetload::postfunc assetload::font( AssetsLoader*, const ResPaths* paths, - const std::string filename, - const std::string name, - std::shared_ptr + const std::string& filename, + const std::string& name, + const std::shared_ptr& ) { auto pages = std::make_shared>>(); for (size_t i = 0; i <= 4; i++) { @@ -136,9 +136,9 @@ assetload::postfunc assetload::font( assetload::postfunc assetload::layout( AssetsLoader*, const ResPaths* paths, - const std::string file, - const std::string name, - std::shared_ptr config + const std::string& file, + const std::string& name, + const std::shared_ptr& config ) { return [=](auto assets) { try { @@ -154,9 +154,9 @@ assetload::postfunc assetload::layout( assetload::postfunc assetload::sound( AssetsLoader*, const ResPaths* paths, - const std::string file, - const std::string name, - std::shared_ptr config + const std::string& file, + const std::string& name, + const std::shared_ptr& config ) { auto cfg = std::dynamic_pointer_cast(config); bool keepPCM = cfg ? cfg->keepPCM : false; diff --git a/src/assets/assetload_funcs.hpp b/src/assets/assetload_funcs.hpp index c021e1e8..f017dcb4 100644 --- a/src/assets/assetload_funcs.hpp +++ b/src/assets/assetload_funcs.hpp @@ -17,45 +17,45 @@ namespace assetload { postfunc texture( AssetsLoader*, const ResPaths* paths, - const std::string filename, - const std::string name, - std::shared_ptr settings + const std::string& filename, + const std::string &name, + const std::shared_ptr& settings ); postfunc shader( AssetsLoader*, const ResPaths* paths, - const std::string filename, - const std::string name, - std::shared_ptr settings + const std::string& filename, + const std::string &name, + const std::shared_ptr& settings ); postfunc atlas( AssetsLoader*, const ResPaths* paths, - const std::string directory, - const std::string name, - std::shared_ptr settings + const std::string &directory, + const std::string &name, + const std::shared_ptr& settings ); postfunc font( AssetsLoader*, const ResPaths* paths, - const std::string filename, - const std::string name, - std::shared_ptr settings + const std::string& filename, + const std::string &name, + const std::shared_ptr& settings ); postfunc layout( AssetsLoader*, const ResPaths* paths, - const std::string file, - const std::string name, - std::shared_ptr settings + const std::string& file, + const std::string &name, + const std::shared_ptr& settings ); postfunc sound( AssetsLoader*, const ResPaths* paths, - const std::string file, - const std::string name, - std::shared_ptr settings + const std::string& file, + const std::string &name, + const std::shared_ptr& settings ); } diff --git a/src/audio/AL/ALAudio.cpp b/src/audio/AL/ALAudio.cpp index 939aa4ad..05cd4c56 100644 --- a/src/audio/AL/ALAudio.cpp +++ b/src/audio/AL/ALAudio.cpp @@ -4,12 +4,13 @@ #include "../../debug/Logger.hpp" #include +#include static debug::Logger logger("al-audio"); using namespace audio; -ALSound::ALSound(ALAudio* al, uint buffer, std::shared_ptr pcm, bool keepPCM) +ALSound::ALSound(ALAudio* al, uint buffer, const std::shared_ptr& pcm, bool keepPCM) : al(al), buffer(buffer) { duration = pcm->getDuration(); @@ -36,7 +37,7 @@ std::unique_ptr ALSound::newInstance(int priority, int channel) const { } ALStream::ALStream(ALAudio* al, std::shared_ptr source, bool keepSource) -: al(al), source(source), keepSource(keepSource) { +: al(al), source(std::move(source)), keepSource(keepSource) { } ALStream::~ALStream() { @@ -457,7 +458,7 @@ std::vector ALAudio::getAvailableDevices() const { const char* ptr = devices; do { - devicesVec.push_back(std::string(ptr)); + devicesVec.emplace_back(ptr); ptr += devicesVec.back().size() + 1; } while (ptr[0]); diff --git a/src/audio/AL/ALAudio.hpp b/src/audio/AL/ALAudio.hpp index f0a22dde..69d84a0c 100644 --- a/src/audio/AL/ALAudio.hpp +++ b/src/audio/AL/ALAudio.hpp @@ -29,7 +29,7 @@ namespace audio { std::shared_ptr pcm; duration_t duration; public: - ALSound(ALAudio* al, uint buffer, std::shared_ptr pcm, bool keepPCM); + ALSound(ALAudio* al, uint buffer, const std::shared_ptr& pcm, bool keepPCM); ~ALSound(); duration_t getDuration() const override { diff --git a/src/audio/NoAudio.cpp b/src/audio/NoAudio.cpp index 04dd2b77..337b1192 100644 --- a/src/audio/NoAudio.cpp +++ b/src/audio/NoAudio.cpp @@ -2,7 +2,7 @@ using namespace audio; -NoSound::NoSound(std::shared_ptr pcm, bool keepPCM) { +NoSound::NoSound(const std::shared_ptr& pcm, bool keepPCM) { duration = pcm->getDuration(); if (keepPCM) { this->pcm = pcm; diff --git a/src/audio/NoAudio.hpp b/src/audio/NoAudio.hpp index bc105139..f1068e4d 100644 --- a/src/audio/NoAudio.hpp +++ b/src/audio/NoAudio.hpp @@ -8,7 +8,7 @@ namespace audio { std::shared_ptr pcm; duration_t duration; public: - NoSound(std::shared_ptr pcm, bool keepPCM); + NoSound(const std::shared_ptr& pcm, bool keepPCM); ~NoSound() {} duration_t getDuration() const override { @@ -28,7 +28,7 @@ namespace audio { std::shared_ptr source; duration_t duration; public: - NoStream(std::shared_ptr source, bool keepSource) { + NoStream(const std::shared_ptr& source, bool keepSource) { duration = source->getTotalDuration(); if (keepSource) { this->source = source; diff --git a/src/audio/audio.cpp b/src/audio/audio.cpp index 9fe62de0..b6a36e42 100644 --- a/src/audio/audio.cpp +++ b/src/audio/audio.cpp @@ -8,6 +8,7 @@ #include #include +#include namespace audio { static speakerid_t nextId = 1; @@ -19,7 +20,7 @@ namespace audio { using namespace audio; -Channel::Channel(std::string name) : name(name) { +Channel::Channel(std::string name) : name(std::move(name)) { } float Channel::getVolume() const { @@ -175,7 +176,7 @@ std::unique_ptr audio::load_sound(const fs::path& file, bool keepPCM) { } std::unique_ptr audio::create_sound(std::shared_ptr pcm, bool keepPCM) { - return backend->createSound(pcm, keepPCM); + return backend->createSound(std::move(pcm), keepPCM); } std::unique_ptr audio::open_PCM_stream(const fs::path& file) { @@ -204,7 +205,7 @@ std::unique_ptr audio::open_stream(const fs::path& file, bool keepSource } std::unique_ptr audio::open_stream(std::shared_ptr stream, bool keepSource) { - return backend->openStream(stream, keepSource); + return backend->openStream(std::move(stream), keepSource); } @@ -276,7 +277,7 @@ speakerid_t audio::play( } speakerid_t audio::play( - std::shared_ptr stream, + const std::shared_ptr& stream, glm::vec3 position, bool relative, float volume, diff --git a/src/audio/audio.hpp b/src/audio/audio.hpp index daf26a9b..4656de6f 100644 --- a/src/audio/audio.hpp +++ b/src/audio/audio.hpp @@ -437,7 +437,7 @@ namespace audio { /// @param channel channel index /// @return speaker id or 0 speakerid_t play( - std::shared_ptr stream, + const std::shared_ptr& stream, glm::vec3 position, bool relative, float volume, diff --git a/src/coders/GLSLExtension.cpp b/src/coders/GLSLExtension.cpp index 84aece78..1e25c934 100644 --- a/src/coders/GLSLExtension.cpp +++ b/src/coders/GLSLExtension.cpp @@ -8,29 +8,30 @@ #include #include #include +#include namespace fs = std::filesystem; void GLSLExtension::setVersion(std::string version) { - this->version = version; + this->version = std::move(version); } void GLSLExtension::setPaths(const ResPaths* paths) { this->paths = paths; } -void GLSLExtension::loadHeader(std::string name) { +void GLSLExtension::loadHeader(const std::string& name) { fs::path file = paths->find("shaders/lib/"+name+".glsl"); std::string source = files::read_string(file); addHeader(name, source); } -void GLSLExtension::addHeader(std::string name, std::string source) { - headers[name] = source; +void GLSLExtension::addHeader(const std::string& name, std::string source) { + headers[name] = std::move(source); } -void GLSLExtension::define(std::string name, std::string value) { - defines[name] = value; +void GLSLExtension::define(const std::string& name, std::string value) { + defines[name] = std::move(value); } const std::string& GLSLExtension::getHeader(const std::string& name) const { @@ -41,10 +42,10 @@ const std::string& GLSLExtension::getHeader(const std::string& name) const { return found->second; } -const std::string GLSLExtension::getDefine(const std::string& name) const { +const std::string& GLSLExtension::getDefine(const std::string& name) const { auto found = defines.find(name); if (found == defines.end()) { - return ""; + throw std::runtime_error("name '"+name+"' is not defined"); } return found->second; } @@ -57,7 +58,7 @@ bool GLSLExtension::hasHeader(const std::string& name) const { return headers.find(name) != headers.end(); } -void GLSLExtension::undefine(std::string name) { +void GLSLExtension::undefine(const std::string& name) { if (hasDefine(name)) { defines.erase(name); } @@ -66,7 +67,7 @@ void GLSLExtension::undefine(std::string name) { inline std::runtime_error parsing_error( const fs::path& file, uint linenum, - const std::string message) { + const std::string& message) { return std::runtime_error("file "+file.string()+": "+message+ " at line "+std::to_string(linenum)); } @@ -74,7 +75,7 @@ inline std::runtime_error parsing_error( inline void parsing_warning( const fs::path& file, uint linenum, const - std::string message) { + std::string& message) { std::cerr << "file "+file.string()+": warning: "+message+ " at line "+std::to_string(linenum) << std::endl; } @@ -83,7 +84,7 @@ inline void source_line(std::stringstream& ss, uint linenum) { ss << "#line " << linenum << "\n"; } -const std::string GLSLExtension::process(const fs::path& file, const std::string& source) { +std::string GLSLExtension::process(const fs::path& file, const std::string& source) { std::stringstream ss; size_t pos = 0; uint linenum = 1; diff --git a/src/coders/GLSLExtension.hpp b/src/coders/GLSLExtension.hpp index 2a106d38..98884c28 100644 --- a/src/coders/GLSLExtension.hpp +++ b/src/coders/GLSLExtension.hpp @@ -14,22 +14,22 @@ class GLSLExtension { std::string version = "330 core"; const ResPaths* paths = nullptr; - void loadHeader(std::string name); + void loadHeader(const std::string& name); public: void setPaths(const ResPaths* paths); void setVersion(std::string version); - void define(std::string name, std::string value); - void undefine(std::string name); - void addHeader(std::string name, std::string source); + void define(const std::string& name, std::string value); + void undefine(const std::string& name); + void addHeader(const std::string& name, std::string source); const std::string& getHeader(const std::string& name) const; - const std::string getDefine(const std::string& name) const; + const std::string& getDefine(const std::string& name) const; bool hasHeader(const std::string& name) const; bool hasDefine(const std::string& name) const; - const std::string process( + std::string process( const std::filesystem::path& file, const std::string& source ); diff --git a/src/coders/commons.cpp b/src/coders/commons.cpp index df59fcb3..1bc111c2 100644 --- a/src/coders/commons.cpp +++ b/src/coders/commons.cpp @@ -15,7 +15,7 @@ inline double power(double base, int64_t power) { } parsing_error::parsing_error( - std::string message, + const std::string& message, std::string_view filename, std::string_view source, uint pos, @@ -332,6 +332,6 @@ std::string BasicParser::parseString(char quote, bool closeRequired) { return ss.str(); } -parsing_error BasicParser::error(std::string message) { +parsing_error BasicParser::error(const std::string& message) { return parsing_error(message, filename, source, pos, line, linestart); } diff --git a/src/coders/commons.hpp b/src/coders/commons.hpp index 1584c92d..f8f1b0e9 100644 --- a/src/coders/commons.hpp +++ b/src/coders/commons.hpp @@ -60,7 +60,7 @@ public: uint linestart; parsing_error( - std::string message, + const std::string& message, std::string_view filename, std::string_view source, uint pos, @@ -92,7 +92,7 @@ protected: dynamic::Value parseNumber(int sign); std::string parseString(char chr, bool closeRequired=true); - parsing_error error(std::string message); + parsing_error error(const std::string& message); public: std::string_view readUntil(char c); diff --git a/src/coders/ogg.cpp b/src/coders/ogg.cpp index 5c337893..6069aa8c 100644 --- a/src/coders/ogg.cpp +++ b/src/coders/ogg.cpp @@ -80,7 +80,7 @@ class OggStream : public PCMStream { size_t totalSamples = 0; bool seekable; public: - OggStream(OggVorbis_File vf) : vf(std::move(vf)) { + OggStream(OggVorbis_File vf) : vf(vf) { vorbis_info* info = ov_info(&vf, -1); channels = info->channels; sampleRate = info->rate; @@ -158,5 +158,5 @@ std::unique_ptr ogg::create_stream(const fs::path& file) { if ((code = ov_fopen(file.u8string().c_str(), &vf))) { throw std::runtime_error("vorbis: "+vorbis_error_message(code)); } - return std::make_unique(std::move(vf)); + return std::make_unique(vf); } diff --git a/src/coders/xml.cpp b/src/coders/xml.cpp index 0f96efed..51c3046b 100644 --- a/src/coders/xml.cpp +++ b/src/coders/xml.cpp @@ -5,12 +5,13 @@ #include #include #include +#include using namespace xml; Attribute::Attribute(std::string name, std::string text) - : name(name), - text(text) { + : name(std::move(name)), + text(std::move(text)) { } const std::string& Attribute::getName() const { @@ -104,14 +105,14 @@ glm::vec4 Attribute::asColor() const { } } -Node::Node(std::string tag) : tag(tag) { +Node::Node(std::string tag) : tag(std::move(tag)) { } -void Node::add(xmlelement element) { +void Node::add(const xmlelement& element) { elements.push_back(element); } -void Node::set(std::string name, std::string text) { +void Node::set(const std::string& name, const std::string &text) { attrs[name] = Attribute(name, text); } @@ -119,7 +120,7 @@ const std::string& Node::getTag() const { return tag; } -const xmlattribute Node::attr(const std::string& name) const { +const xmlattribute& Node::attr(const std::string& name) const { auto found = attrs.find(name); if (found == attrs.end()) { throw std::runtime_error("element <"+tag+" ...> missing attribute "+name); @@ -127,7 +128,7 @@ const xmlattribute Node::attr(const std::string& name) const { return found->second; } -const xmlattribute Node::attr(const std::string& name, const std::string& def) const { +xmlattribute Node::attr(const std::string& name, const std::string& def) const { auto found = attrs.find(name); if (found == attrs.end()) { return Attribute(name, def); @@ -157,11 +158,11 @@ const xmlelements_map& Node::getAttributes() const { } Document::Document(std::string version, std::string encoding) - : version(version), - encoding(encoding) { + : version(std::move(version)), + encoding(std::move(encoding)) { } -void Document::setRoot(xmlelement element) { +void Document::setRoot(const xmlelement &element) { this->root = element; } @@ -336,7 +337,7 @@ xmldocument Parser::parse() { return document; } -xmldocument xml::parse(std::string filename, std::string source) { +xmldocument xml::parse(const std::string& filename, const std::string& source) { Parser parser(filename, source); return parser.parse(); } @@ -357,7 +358,7 @@ inline void newline( static void stringifyElement( std::stringstream& ss, - const xmlelement element, + const xmlelement& element, bool nice, const std::string& indentStr, int indent @@ -414,7 +415,7 @@ static void stringifyElement( } std::string xml::stringify( - const xmldocument document, + const xmldocument& document, bool nice, const std::string& indentStr ) { diff --git a/src/coders/xml.hpp b/src/coders/xml.hpp index aff5288c..c70ce9c2 100644 --- a/src/coders/xml.hpp +++ b/src/coders/xml.hpp @@ -46,12 +46,12 @@ namespace xml { Node(std::string tag); /// @brief Add sub-element - void add(xmlelement element); + void add(const xmlelement& element); /// @brief Set attribute value. Creates attribute if does not exists /// @param name attribute name /// @param text attribute value - void set(std::string name, std::string text); + void set(const std::string& name, const std::string &text); /// @brief Get element tag const std::string& getTag() const; @@ -68,14 +68,14 @@ namespace xml { /// @param name attribute name /// @throws std::runtime_error if element has no attribute /// @return xmlattribute - {name, value} - const xmlattribute attr(const std::string& name) const; + const xmlattribute& attr(const std::string& name) const; /// @brief Get attribute by name /// @param name attribute name /// @param def default value will be returned wrapped in xmlattribute /// if element has no attribute /// @return xmlattribute - {name, value} or {name, def} if not found*/ - const xmlattribute attr(const std::string& name, const std::string& def) const; + xmlattribute attr(const std::string& name, const std::string& def) const; /// @brief Check if element has attribute /// @param name attribute name @@ -101,7 +101,7 @@ namespace xml { public: Document(std::string version, std::string encoding); - void setRoot(xmlelement element); + void setRoot(const xmlelement &element); xmlelement getRoot() const; const std::string& getVersion() const; @@ -129,7 +129,7 @@ namespace xml { /// @param indentStr indentation characters sequence (default - 4 spaces) /// @return XML string extern std::string stringify( - const xmldocument document, + const xmldocument& document, bool nice=true, const std::string& indentStr=" " ); @@ -138,7 +138,7 @@ namespace xml { /// @param filename file name will be shown in error messages /// @param source xml source code string /// @return xml document - extern xmldocument parse(std::string filename, std::string source); + extern xmldocument parse(const std::string& filename, const std::string& source); } #endif // CODERS_XML_HPP_ diff --git a/src/constants.hpp b/src/constants.hpp index de6b23dc..e666563a 100644 --- a/src/constants.hpp +++ b/src/constants.hpp @@ -7,7 +7,7 @@ #include inline constexpr int ENGINE_VERSION_MAJOR = 0; -inline constexpr int ENGINE_VERSION_MINOR = 21; +inline constexpr int ENGINE_VERSION_MINOR = 22; #ifdef NDEBUG inline constexpr bool ENGINE_DEBUG_BUILD = false; @@ -15,7 +15,7 @@ inline constexpr bool ENGINE_DEBUG_BUILD = false; inline constexpr bool ENGINE_DEBUG_BUILD = true; #endif // NDEBUG -inline const std::string ENGINE_VERSION_STRING = "0.21"; +inline const std::string ENGINE_VERSION_STRING = "0.22"; inline constexpr blockid_t BLOCK_AIR = 0; inline constexpr itemid_t ITEM_EMPTY = 0; diff --git a/src/content/Content.cpp b/src/content/Content.cpp index 4de7367c..8e0b0749 100644 --- a/src/content/Content.cpp +++ b/src/content/Content.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include "../voxels/Block.hpp" #include "../items/ItemDef.hpp" @@ -13,8 +14,8 @@ ContentIndices::ContentIndices( std::vector blockDefs, std::vector itemDefs -) : blockDefs(blockDefs), - itemDefs(itemDefs) +) : blockDefs(std::move(blockDefs)), + itemDefs(std::move(itemDefs)) {} Content::Content( @@ -35,7 +36,7 @@ Content::Content( Content::~Content() { } -Block* Content::findBlock(std::string id) const { +Block* Content::findBlock(const std::string& id) const { auto found = blockDefs.find(id); if (found == blockDefs.end()) { return nullptr; @@ -43,7 +44,7 @@ Block* Content::findBlock(std::string id) const { return found->second.get(); } -Block& Content::requireBlock(std::string id) const { +Block& Content::requireBlock(const std::string& id) const { auto found = blockDefs.find(id); if (found == blockDefs.end()) { throw std::runtime_error("missing block "+id); @@ -51,7 +52,7 @@ Block& Content::requireBlock(std::string id) const { return *found->second; } -ItemDef* Content::findItem(std::string id) const { +ItemDef* Content::findItem(const std::string& id) const { auto found = itemDefs.find(id); if (found == itemDefs.end()) { return nullptr; @@ -59,7 +60,7 @@ ItemDef* Content::findItem(std::string id) const { return found->second.get(); } -ItemDef& Content::requireItem(std::string id) const { +ItemDef& Content::requireItem(const std::string& id) const { auto found = itemDefs.find(id); if (found == itemDefs.end()) { throw std::runtime_error("missing item "+id); @@ -67,7 +68,7 @@ ItemDef& Content::requireItem(std::string id) const { return *found->second; } -const BlockMaterial* Content::findBlockMaterial(std::string id) const { +const BlockMaterial* Content::findBlockMaterial(const std::string& id) const { auto found = blockMaterials.find(id); if (found == blockMaterials.end()) { return nullptr; @@ -75,7 +76,7 @@ const BlockMaterial* Content::findBlockMaterial(std::string id) const { return found->second.get(); } -const ContentPackRuntime* Content::getPackRuntime(std::string id) const { +const ContentPackRuntime* Content::getPackRuntime(const std::string& id) const { auto found = packs.find(id); if (found == packs.end()) { return nullptr; diff --git a/src/content/Content.hpp b/src/content/Content.hpp index c9df8417..75237757 100644 --- a/src/content/Content.hpp +++ b/src/content/Content.hpp @@ -107,15 +107,15 @@ public: return indices.get(); } - Block* findBlock(std::string id) const; - Block& requireBlock(std::string id) const; + Block* findBlock(const std::string& id) const; + Block& requireBlock(const std::string& id) const; - ItemDef* findItem(std::string id) const; - ItemDef& requireItem(std::string id) const; + ItemDef* findItem(const std::string& id) const; + ItemDef& requireItem(const std::string& id) const; - const BlockMaterial* findBlockMaterial(std::string id) const; + const BlockMaterial* findBlockMaterial(const std::string& id) const; - const ContentPackRuntime* getPackRuntime(std::string id) const; + const ContentPackRuntime* getPackRuntime(const std::string& id) const; const std::unordered_map>& getBlockMaterials() const; const std::unordered_map>& getPacks() const; diff --git a/src/content/ContentBuilder.cpp b/src/content/ContentBuilder.cpp index c95f5e5a..a660ca9a 100644 --- a/src/content/ContentBuilder.cpp +++ b/src/content/ContentBuilder.cpp @@ -6,7 +6,7 @@ void ContentBuilder::add(std::unique_ptr pack) { packs[pack->getId()] = std::move(pack); } -Block& ContentBuilder::createBlock(std::string id) { +Block& ContentBuilder::createBlock(const std::string& id) { auto found = blockDefs.find(id); if (found != blockDefs.end()) { return *found->second; @@ -17,7 +17,7 @@ Block& ContentBuilder::createBlock(std::string id) { return *blockDefs[id]; } -ItemDef& ContentBuilder::createItem(std::string id) { +ItemDef& ContentBuilder::createItem(const std::string& id) { auto found = itemDefs.find(id); if (found != itemDefs.end()) { return *found->second; @@ -28,21 +28,21 @@ ItemDef& ContentBuilder::createItem(std::string id) { return *itemDefs[id]; } -BlockMaterial& ContentBuilder::createBlockMaterial(std::string id) { +BlockMaterial& ContentBuilder::createBlockMaterial(const std::string& id) { blockMaterials[id] = std::make_unique(); auto& material = *blockMaterials[id]; material.name = id; return material; } -void ContentBuilder::checkIdentifier(std::string id) { +void ContentBuilder::checkIdentifier(const std::string& id) { contenttype result; if (((result = checkContentType(id)) != contenttype::none)) { throw namereuse_error("name "+id+" is already used", result); } } -contenttype ContentBuilder::checkContentType(std::string id) { +contenttype ContentBuilder::checkContentType(const std::string& id) { if (blockDefs.find(id) != blockDefs.end()) { return contenttype::block; } @@ -62,6 +62,7 @@ std::unique_ptr ContentBuilder::build() { def.rt.id = blockDefsIndices.size(); def.rt.emissive = *reinterpret_cast(def.emission); def.rt.solid = def.model == BlockModel::block; + def.rt.extended = def.size.x > 1 || def.size.y > 1 || def.size.z > 1; if (def.rotatable) { for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) { diff --git a/src/content/ContentBuilder.hpp b/src/content/ContentBuilder.hpp index f6bcbd5e..0c7a6d31 100644 --- a/src/content/ContentBuilder.hpp +++ b/src/content/ContentBuilder.hpp @@ -24,12 +24,12 @@ public: void add(std::unique_ptr pack); - Block& createBlock(std::string id); - ItemDef& createItem(std::string id); - BlockMaterial& createBlockMaterial(std::string id); + Block& createBlock(const std::string& id); + ItemDef& createItem(const std::string& id); + BlockMaterial& createBlockMaterial(const std::string& id); - void checkIdentifier(std::string id); - contenttype checkContentType(std::string id); + void checkIdentifier(const std::string& id); + contenttype checkContentType(const std::string& id); std::unique_ptr build(); }; diff --git a/src/content/ContentLUT.cpp b/src/content/ContentLUT.cpp index 779277d5..bb7ed390 100644 --- a/src/content/ContentLUT.cpp +++ b/src/content/ContentLUT.cpp @@ -19,7 +19,7 @@ ContentLUT::ContentLUT(const Content* content, size_t blocksCount, size_t itemsC blockNames.push_back(indices->getBlockDef(i)->name); } for (size_t i = indices->countBlockDefs(); i < blocksCount; i++) { - blockNames.push_back(""); + blockNames.emplace_back(""); } for (size_t i = 0; i < itemsCount; i++) { @@ -29,7 +29,7 @@ ContentLUT::ContentLUT(const Content* content, size_t blocksCount, size_t itemsC itemNames.push_back(indices->getItemDef(i)->name); } for (size_t i = indices->countItemDefs(); i < itemsCount; i++) { - itemNames.push_back(""); + itemNames.emplace_back(); } } diff --git a/src/content/ContentLUT.hpp b/src/content/ContentLUT.hpp index 46204d19..f7c8a799 100644 --- a/src/content/ContentLUT.hpp +++ b/src/content/ContentLUT.hpp @@ -7,6 +7,7 @@ #include "../constants.hpp" #include +#include #include #include @@ -44,7 +45,7 @@ public: inline void setBlock(blockid_t index, std::string name, blockid_t id) { blocks[index] = id; - blockNames[index] = name; + blockNames[index] = std::move(name); if (id == BLOCK_VOID) { missingContent = true; } else if (index != id) { @@ -62,7 +63,7 @@ public: inline void setItem(itemid_t index, std::string name, itemid_t id) { items[index] = id; - itemNames[index] = name; + itemNames[index] = std::move(name); if (id == ITEM_VOID) { missingContent = true; } else if (index != id) { diff --git a/src/content/ContentLoader.cpp b/src/content/ContentLoader.cpp index 5b7e30b3..68cb44d7 100644 --- a/src/content/ContentLoader.cpp +++ b/src/content/ContentLoader.cpp @@ -28,15 +28,15 @@ ContentLoader::ContentLoader(ContentPack* pack) : pack(pack) { } bool ContentLoader::fixPackIndices( - fs::path folder, + const fs::path& folder, dynamic::Map* indicesRoot, - std::string contentSection + const std::string& contentSection ) { std::vector detected; std::vector indexed; if (fs::is_directory(folder)) { - for (auto entry : fs::directory_iterator(folder)) { - fs::path file = entry.path(); + for (const auto& entry : fs::directory_iterator(folder)) { + const fs::path& file = entry.path(); if (fs::is_regular_file(file) && file.extension() == ".json") { std::string name = file.stem().string(); if (name[0] == '_') @@ -46,8 +46,8 @@ bool ContentLoader::fixPackIndices( std::string space = file.stem().string(); if (space[0] == '_') continue; - for (auto entry : fs::directory_iterator(file)) { - fs::path file = entry.path(); + for (const auto& entry : fs::directory_iterator(file)) { + const fs::path& file = entry.path(); if (fs::is_regular_file(file) && file.extension() == ".json") { std::string name = file.stem().string(); if (name[0] == '_') @@ -109,7 +109,7 @@ void ContentLoader::fixPackIndices() { } } -void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) { +void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::path& file) { auto root = files::read_json(file); root->str("caption", def.caption); @@ -137,16 +137,14 @@ void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) { def.model = BlockModel::custom; if (root->has("model-primitives")) { loadCustomBlockModel(def, root->map("model-primitives")); - } - else { - std::cerr << "ERROR occured while block " - << name << " parsed: no \"model-primitives\" found" << std::endl; + } else { + logger.error() << name << ": no 'model-primitives' found"; } } else if (model == "X") def.model = BlockModel::xsprite; else if (model == "none") def.model = BlockModel::none; else { - std::cerr << "unknown model " << model << std::endl; + logger.error() << "unknown model " << model; def.model = BlockModel::none; } @@ -156,12 +154,12 @@ void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) { std::string profile = "none"; root->str("rotation", profile); def.rotatable = profile != "none"; - if (profile == "pipe") { + if (profile == BlockRotProfile::PIPE_NAME) { def.rotations = BlockRotProfile::PIPE; - } else if (profile == "pane") { + } else if (profile == BlockRotProfile::PANE_NAME) { def.rotations = BlockRotProfile::PANE; } else if (profile != "none") { - std::cerr << "unknown rotation profile " << profile << std::endl; + logger.error() << "unknown rotation profile " << profile; def.rotatable = false; } @@ -175,29 +173,37 @@ void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) { def.hitboxes[i].b = glm::vec3(box->num(3), box->num(4), box->num(5)); def.hitboxes[i].b += def.hitboxes[i].a; } + } else if (auto boxarr = root->list("hitbox")){ + AABB aabb; + aabb.a = glm::vec3(boxarr->num(0), boxarr->num(1), boxarr->num(2)); + aabb.b = glm::vec3(boxarr->num(3), boxarr->num(4), boxarr->num(5)); + aabb.b += aabb.a; + def.hitboxes = { aabb }; + } else if (!def.modelBoxes.empty()) { + def.hitboxes = def.modelBoxes; } else { - boxarr = root->list("hitbox"); - if (boxarr) { - AABB aabb; - aabb.a = glm::vec3(boxarr->num(0), boxarr->num(1), boxarr->num(2)); - aabb.b = glm::vec3(boxarr->num(3), boxarr->num(4), boxarr->num(5)); - aabb.b += aabb.a; - def.hitboxes = { aabb }; - } else if (!def.modelBoxes.empty()) { - def.hitboxes = def.modelBoxes; - } else { - def.hitboxes = { AABB() }; - } + def.hitboxes = { AABB() }; } // block light emission [r, g, b] where r,g,b in range [0..15] - auto emissionarr = root->list("emission"); - if (emissionarr) { + if (auto emissionarr = root->list("emission")) { def.emission[0] = emissionarr->num(0); def.emission[1] = emissionarr->num(1); def.emission[2] = emissionarr->num(2); } + // block size + if (auto sizearr = root->list("size")) { + def.size.x = sizearr->num(0); + def.size.y = sizearr->num(1); + def.size.z = sizearr->num(2); + if (def.model == BlockModel::block && + (def.size.x != 1 || def.size.y != 1 || def.size.z != 1)) { + def.model = BlockModel::aabb; + def.hitboxes = {AABB(def.size)}; + } + } + // primitive properties root->flag("obstacle", def.obstacle); root->flag("replaceable", def.replaceable); @@ -244,7 +250,7 @@ void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) { } else for (uint j = 6; j < 12; j++) { - def.modelTextures.push_back("notfound"); + def.modelTextures.emplace_back("notfound"); } } } @@ -254,8 +260,8 @@ void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) { /* Parse tetragon to points */ auto tgonobj = modeltetragons->list(i); glm::vec3 p1(tgonobj->num(0), tgonobj->num(1), tgonobj->num(2)), - xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)), - yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8)); + xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)), + yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8)); def.modelExtraPoints.push_back(p1); def.modelExtraPoints.push_back(p1+xw); def.modelExtraPoints.push_back(p1+xw+yh); @@ -266,7 +272,7 @@ void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) { } } -void ContentLoader::loadItem(ItemDef& def, std::string name, fs::path file) { +void ContentLoader::loadItem(ItemDef& def, const std::string& name, const fs::path& file) { auto root = files::read_json(file); root->str("caption", def.caption); @@ -279,7 +285,7 @@ void ContentLoader::loadItem(ItemDef& def, std::string name, fs::path file) { } else if (iconTypeStr == "sprite") { def.iconType = item_icon_type::sprite; } else if (iconTypeStr.length()){ - std::cerr << "unknown icon type" << iconTypeStr << std::endl; + logger.error() << name << ": unknown icon type" << iconTypeStr; } root->str("icon", def.icon); root->str("placing-block", def.placingBlock); @@ -295,7 +301,7 @@ void ContentLoader::loadItem(ItemDef& def, std::string name, fs::path file) { } } -void ContentLoader::loadBlock(Block& def, std::string full, std::string name) { +void ContentLoader::loadBlock(Block& def, const std::string& full, const std::string& name) { auto folder = pack->folder; fs::path configFile = folder/fs::path("blocks/"+name+".json"); @@ -307,7 +313,7 @@ void ContentLoader::loadBlock(Block& def, std::string full, std::string name) { } } -void ContentLoader::loadItem(ItemDef& def, std::string full, std::string name) { +void ContentLoader::loadItem(ItemDef& def, const std::string& full, const std::string& name) { auto folder = pack->folder; fs::path configFile = folder/fs::path("items/"+name+".json"); @@ -319,7 +325,7 @@ void ContentLoader::loadItem(ItemDef& def, std::string full, std::string name) { } } -void ContentLoader::loadBlockMaterial(BlockMaterial& def, fs::path file) { +void ContentLoader::loadBlockMaterial(BlockMaterial& def, const fs::path& file) { auto root = files::read_json(file); root->str("steps-sound", def.stepsSound); root->str("place-sound", def.placeSound); @@ -394,8 +400,8 @@ void ContentLoader::load(ContentBuilder& builder) { fs::path materialsDir = folder / fs::u8path("block_materials"); if (fs::is_directory(materialsDir)) { - for (auto entry : fs::directory_iterator(materialsDir)) { - fs::path file = entry.path(); + for (const auto& entry : fs::directory_iterator(materialsDir)) { + const fs::path& file = entry.path(); std::string name = pack->id+":"+file.stem().u8string(); loadBlockMaterial(builder.createBlockMaterial(name), file); } diff --git a/src/content/ContentLoader.hpp b/src/content/ContentLoader.hpp index 515d742a..fa1c4b61 100644 --- a/src/content/ContentLoader.hpp +++ b/src/content/ContentLoader.hpp @@ -22,21 +22,21 @@ class ContentLoader { const ContentPack* pack; scriptenv env; - void loadBlock(Block& def, std::string full, std::string name); + void loadBlock(Block& def, const std::string& full, const std::string& name); void loadCustomBlockModel(Block& def, dynamic::Map* primitives); - void loadItem(ItemDef& def, std::string full, std::string name); - void loadBlockMaterial(BlockMaterial& def, fs::path file); + void loadItem(ItemDef& def, const std::string& full, const std::string& name); + void loadBlockMaterial(BlockMaterial& def, const fs::path& file); public: ContentLoader(ContentPack* pack); bool fixPackIndices( - fs::path folder, + const fs::path& folder, dynamic::Map* indicesRoot, - std::string contentSection + const std::string& contentSection ); void fixPackIndices(); - void loadBlock(Block& def, std::string name, fs::path file); - void loadItem(ItemDef& def, std::string name, fs::path file); + void loadBlock(Block& def, const std::string& name, const fs::path& file); + void loadItem(ItemDef& def, const std::string& name, const fs::path& file); void load(ContentBuilder& builder); }; diff --git a/src/content/ContentPack.cpp b/src/content/ContentPack.cpp index a054e426..e3a5f0f1 100644 --- a/src/content/ContentPack.cpp +++ b/src/content/ContentPack.cpp @@ -2,6 +2,7 @@ #include #include +#include #include "../coders/json.hpp" #include "../files/files.hpp" @@ -21,8 +22,8 @@ const std::vector ContentPack::RESERVED_NAMES = { contentpack_error::contentpack_error( std::string packId, fs::path folder, - std::string message) - : std::runtime_error(message), packId(packId), folder(folder) { + const std::string& message) + : std::runtime_error(message), packId(std::move(packId)), folder(std::move(folder)) { } std::string contentpack_error::getPackId() const { @@ -36,7 +37,7 @@ fs::path ContentPack::getContentFile() const { return folder/fs::path(CONTENT_FILENAME); } -bool ContentPack::is_pack(fs::path folder) { +bool ContentPack::is_pack(const fs::path& folder) { return fs::is_regular_file(folder/fs::path(PACKAGE_FILENAME)); } @@ -61,7 +62,7 @@ static void checkContentPackId(const std::string& id, const fs::path& folder) { } } -ContentPack ContentPack::read(fs::path folder) { +ContentPack ContentPack::read(const fs::path& folder) { auto root = files::read_json(folder/fs::path(PACKAGE_FILENAME)); ContentPack pack; root->str("id", pack.id); @@ -89,14 +90,14 @@ ContentPack ContentPack::read(fs::path folder) { } void ContentPack::scanFolder( - fs::path folder, + const fs::path& folder, std::vector& packs ) { if (!fs::is_directory(folder)) { return; } - for (auto entry : fs::directory_iterator(folder)) { - fs::path folder = entry.path(); + for (const auto& entry : fs::directory_iterator(folder)) { + const fs::path& folder = entry.path(); if (!fs::is_directory(folder)) continue; if (!is_pack(folder)) @@ -112,7 +113,7 @@ void ContentPack::scanFolder( } } -std::vector ContentPack::worldPacksList(fs::path folder) { +std::vector ContentPack::worldPacksList(const fs::path& folder) { fs::path listfile = folder / fs::path("packs.list"); if (!fs::is_regular_file(listfile)) { std::cerr << "warning: packs.list not found (will be created)"; @@ -122,7 +123,7 @@ std::vector ContentPack::worldPacksList(fs::path folder) { return files::read_list(listfile); } -fs::path ContentPack::findPack(const EnginePaths* paths, fs::path worldDir, std::string name) { +fs::path ContentPack::findPack(const EnginePaths* paths, const fs::path& worldDir, const std::string& name) { fs::path folder = worldDir / fs::path("content") / fs::path(name); if (fs::is_directory(folder)) { return folder; @@ -141,7 +142,7 @@ fs::path ContentPack::findPack(const EnginePaths* paths, fs::path worldDir, std: ContentPackRuntime::ContentPackRuntime( ContentPack info, scriptenv env -) : info(info), env(std::move(env)) +) : info(std::move(info)), env(std::move(env)) { } diff --git a/src/content/ContentPack.hpp b/src/content/ContentPack.hpp index 7ff4b972..ca0aff2e 100644 --- a/src/content/ContentPack.hpp +++ b/src/content/ContentPack.hpp @@ -16,7 +16,7 @@ class contentpack_error : public std::runtime_error { std::string packId; fs::path folder; public: - contentpack_error(std::string packId, fs::path folder, std::string message); + contentpack_error(std::string packId, fs::path folder, const std::string& message); std::string getPackId() const; fs::path getFolder() const; @@ -52,20 +52,20 @@ struct ContentPack { static const fs::path ITEMS_FOLDER; static const std::vector RESERVED_NAMES; - static bool is_pack(fs::path folder); - static ContentPack read(fs::path folder); + static bool is_pack(const fs::path& folder); + static ContentPack read(const fs::path& folder); static void scanFolder( - fs::path folder, + const fs::path& folder, std::vector& packs ); - static std::vector worldPacksList(fs::path folder); + static std::vector worldPacksList(const fs::path& folder); static fs::path findPack( const EnginePaths* paths, - fs::path worldDir, - std::string name + const fs::path& worldDir, + const std::string& name ); }; diff --git a/src/data/dynamic.cpp b/src/data/dynamic.cpp index 6b87f97c..0cc88103 100644 --- a/src/data/dynamic.cpp +++ b/src/data/dynamic.cpp @@ -110,7 +110,7 @@ void Map::str(const std::string& key, std::string& dst) const { dst = get(key, dst); } -std::string Map::get(const std::string& key, const std::string def) const { +std::string Map::get(const std::string& key, const std::string& def) const { auto found = values.find(key); if (found == values.end()) return def; @@ -213,7 +213,7 @@ void Map::flag(const std::string& key, bool& dst) const { dst = get(key, dst); } -Map& Map::put(std::string key, const Value& value) { +Map& Map::put(const std::string& key, const Value& value) { values[key] = value; return *this; } @@ -222,13 +222,13 @@ void Map::remove(const std::string& key) { values.erase(key); } -List& Map::putList(std::string key) { +List& Map::putList(const std::string& key) { auto arr = create_list(); put(key, arr); return *arr; } -Map& Map::putMap(std::string key) { +Map& Map::putMap(const std::string& key) { auto obj = create_map(); put(key, obj); return *obj; diff --git a/src/data/dynamic.hpp b/src/data/dynamic.hpp index 4c5b602c..ff0342df 100644 --- a/src/data/dynamic.hpp +++ b/src/data/dynamic.hpp @@ -101,7 +101,7 @@ namespace dynamic { return get(key, T()); } - std::string get(const std::string& key, const std::string def) const; + std::string get(const std::string& key, const std::string& def) const; number_t get(const std::string& key, double def) const; integer_t get(const std::string& key, integer_t def) const; bool get(const std::string& key, bool def) const; @@ -155,12 +155,12 @@ namespace dynamic { Map& put(std::string key, const char* value) { return put(key, Value(value)); } - Map& put(std::string key, const Value& value); + Map& put(const std::string& key, const Value& value); void remove(const std::string& key); - List& putList(std::string key); - Map& putMap(std::string key); + List& putList(const std::string& key); + Map& putMap(const std::string& key); bool has(const std::string& key) const; size_t size() const; diff --git a/src/debug/Logger.cpp b/src/debug/Logger.cpp index b14d441b..1463d66b 100644 --- a/src/debug/Logger.cpp +++ b/src/debug/Logger.cpp @@ -4,6 +4,7 @@ #include #include #include +#include using namespace debug; @@ -16,10 +17,10 @@ LogMessage::~LogMessage() { logger->log(level, ss.str()); } -Logger::Logger(std::string name) : name(name) { +Logger::Logger(std::string name) : name(std::move(name)) { } -void Logger::log(LogLevel level, const std::string& name, std::string message) { +void Logger::log(LogLevel level, const std::string& name, const std::string& message) { using namespace std::chrono; std::stringstream ss; @@ -72,5 +73,5 @@ void Logger::flush() { } void Logger::log(LogLevel level, std::string message) { - log(level, name, message); + log(level, name, std::move(message)); } diff --git a/src/debug/Logger.hpp b/src/debug/Logger.hpp index b3024b0a..779e8580 100644 --- a/src/debug/Logger.hpp +++ b/src/debug/Logger.hpp @@ -35,7 +35,7 @@ namespace debug { std::string name; - static void log(LogLevel level, const std::string& name, std::string message); + static void log(LogLevel level, const std::string& name, const std::string& message); public: static void init(const std::string& filename); static void flush(); diff --git a/src/engine.cpp b/src/engine.cpp index 4720f909..b7396ff3 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -42,6 +42,7 @@ #include #include #include +#include static debug::Logger logger("engine"); @@ -65,6 +66,7 @@ Engine::Engine(EngineSettings& settings, SettingsHandler& settingsHandler, Engin : settings(settings), settingsHandler(settingsHandler), paths(paths), interpreter(std::make_unique()) { + paths->prepare(); loadSettings(); controller = std::make_unique(this); @@ -115,14 +117,6 @@ void Engine::loadControls() { logger.info() << "loading controls"; std::string text = files::read_string(controls_file); Events::loadBindings(controls_file.u8string(), text); - } else { - controls_file = paths->getControlsFileOld(); - if (fs::is_regular_file(controls_file)) { - logger.info() << "loading controls (old)"; - std::string text = files::read_string(controls_file); - Events::loadBindingsOld(controls_file.u8string(), text); - fs::remove(controls_file); - } } } @@ -347,11 +341,11 @@ double Engine::getDelta() const { void Engine::setScreen(std::shared_ptr screen) { audio::reset_channel(audio::get_channel_index("regular")); audio::reset_channel(audio::get_channel_index("ambient")); - this->screen = screen; + this->screen = std::move(screen); } void Engine::setLanguage(std::string locale) { - langs::setup(paths->getResources(), locale, contentPacks); + langs::setup(paths->getResources(), std::move(locale), contentPacks); gui->getMenu()->setPageLoader(menus::create_page_loader(this)); } @@ -391,7 +385,7 @@ std::shared_ptr Engine::getScreen() { return screen; } -void Engine::postRunnable(runnable callback) { +void Engine::postRunnable(const runnable& callback) { std::lock_guard lock(postRunnablesMutex); postRunnables.push(callback); } diff --git a/src/engine.hpp b/src/engine.hpp index e9ebeb8a..2b601743 100644 --- a/src/engine.hpp +++ b/src/engine.hpp @@ -137,7 +137,7 @@ public: std::shared_ptr getScreen(); /// @brief Enqueue function call to the end of current frame in draw thread - void postRunnable(runnable callback); + void postRunnable(const runnable& callback); void saveScreenshot(); diff --git a/src/files/WorldConverter.cpp b/src/files/WorldConverter.cpp index 602c26de..1f0b7ad2 100644 --- a/src/files/WorldConverter.cpp +++ b/src/files/WorldConverter.cpp @@ -13,6 +13,7 @@ #include #include #include +#include namespace fs = std::filesystem; @@ -22,7 +23,7 @@ class ConverterWorker : public util::Worker { std::shared_ptr converter; public: ConverterWorker(std::shared_ptr converter) - : converter(converter) {} + : converter(std::move(converter)) {} int operator()(const std::shared_ptr& task) override { converter->convert(*task); @@ -31,11 +32,11 @@ public: }; WorldConverter::WorldConverter( - fs::path folder, + const fs::path& folder, const Content* content, std::shared_ptr lut ) : wfile(std::make_unique(folder)), - lut(lut), + lut(std::move(lut)), content(content) { fs::path regionsFolder = wfile->getRegions().getRegionsFolder(REGION_LAYER_VOXELS); @@ -44,7 +45,7 @@ WorldConverter::WorldConverter( return; } tasks.push(convert_task {convert_task_type::player, wfile->getPlayerFile()}); - for (auto file : fs::directory_iterator(regionsFolder)) { + for (const auto& file : fs::directory_iterator(regionsFolder)) { tasks.push(convert_task {convert_task_type::region, file.path()}); } } @@ -53,10 +54,10 @@ WorldConverter::~WorldConverter() { } std::shared_ptr WorldConverter::startTask( - fs::path folder, + const fs::path& folder, const Content* content, - std::shared_ptr lut, - runnable onDone, + const std::shared_ptr& lut, + const runnable& onDone, bool multithreading ) { auto converter = std::make_shared(folder, content, lut); @@ -85,7 +86,7 @@ std::shared_ptr WorldConverter::startTask( return pool; } -void WorldConverter::convertRegion(fs::path file) const { +void WorldConverter::convertRegion(const fs::path& file) const { int x, z; std::string name = file.stem().string(); if (!WorldRegions::parseRegionFilename(name, x, z)) { @@ -101,14 +102,14 @@ void WorldConverter::convertRegion(fs::path file) const { }); } -void WorldConverter::convertPlayer(fs::path file) const { +void WorldConverter::convertPlayer(const fs::path& file) const { logger.info() << "converting player " << file.u8string(); auto map = files::read_json(file); Player::convert(map.get(), lut.get()); files::write_json(file, map.get()); } -void WorldConverter::convert(convert_task task) const { +void WorldConverter::convert(const convert_task& task) const { if (!fs::is_regular_file(task.file)) return; @@ -134,7 +135,7 @@ void WorldConverter::convertNext() { } void WorldConverter::setOnComplete(runnable callback) { - this->onComplete = callback; + this->onComplete = std::move(callback); } void WorldConverter::update() { diff --git a/src/files/WorldConverter.hpp b/src/files/WorldConverter.hpp index 4e6159e0..9fb6307a 100644 --- a/src/files/WorldConverter.hpp +++ b/src/files/WorldConverter.hpp @@ -32,17 +32,17 @@ class WorldConverter : public Task { runnable onComplete; uint tasksDone = 0; - void convertPlayer(fs::path file) const; - void convertRegion(fs::path file) const; + void convertPlayer(const fs::path& file) const; + void convertRegion(const fs::path& file) const; public: WorldConverter( - fs::path folder, + const fs::path& folder, const Content* content, std::shared_ptr lut ); ~WorldConverter(); - void convert(convert_task task) const; + void convert(const convert_task& task) const; void convertNext(); void setOnComplete(runnable callback); void write(); @@ -55,10 +55,10 @@ public: uint getWorkDone() const override; static std::shared_ptr startTask( - fs::path folder, + const fs::path& folder, const Content* content, - std::shared_ptr lut, - runnable onDone, + const std::shared_ptr& lut, + const runnable& onDone, bool multithreading ); }; diff --git a/src/files/WorldFiles.cpp b/src/files/WorldFiles.cpp index b5d68c85..26cef6a6 100644 --- a/src/files/WorldFiles.cpp +++ b/src/files/WorldFiles.cpp @@ -27,14 +27,15 @@ #include #include #include +#include #define WORLD_FORMAT_MAGIC ".VOXWLD" -WorldFiles::WorldFiles(fs::path directory) : directory(directory), regions(directory) { +WorldFiles::WorldFiles(const fs::path& directory) : directory(directory), regions(directory) { } -WorldFiles::WorldFiles(fs::path directory, const DebugSettings& settings) - : WorldFiles(directory) +WorldFiles::WorldFiles(const fs::path& directory, const DebugSettings& settings) + : WorldFiles(directory) { generatorTestMode = settings.generatorTestMode.get(); doWriteLights = settings.doWriteLights.get(); diff --git a/src/files/WorldFiles.hpp b/src/files/WorldFiles.hpp index f2938416..67d942ea 100644 --- a/src/files/WorldFiles.hpp +++ b/src/files/WorldFiles.hpp @@ -41,8 +41,8 @@ class WorldFiles { void writeWorldInfo(const World* world); void writeIndices(const ContentIndices* indices); public: - WorldFiles(fs::path directory); - WorldFiles(fs::path directory, const DebugSettings& settings); + WorldFiles(const fs::path &directory); + WorldFiles(const fs::path &directory, const DebugSettings& settings); ~WorldFiles(); fs::path getPlayerFile() const; diff --git a/src/files/WorldRegions.cpp b/src/files/WorldRegions.cpp index af3aadd4..44aa8449 100644 --- a/src/files/WorldRegions.cpp +++ b/src/files/WorldRegions.cpp @@ -8,10 +8,11 @@ #include "../util/data_io.hpp" #include +#include #define REGION_FORMAT_MAGIC ".VOXREG" -regfile::regfile(fs::path filename) : file(filename) { +regfile::regfile(fs::path filename) : file(std::move(filename)) { if (file.length() < REGION_HEADER_SIZE) throw std::runtime_error("incomplete region file header"); char header[REGION_HEADER_SIZE]; @@ -49,17 +50,12 @@ std::unique_ptr regfile::read(int index, uint32_t& length) { return data; } -WorldRegion::WorldRegion() { - chunksData = new ubyte*[REGION_CHUNKS_COUNT]{}; - sizes = new uint32_t[REGION_CHUNKS_COUNT]{}; -} +WorldRegion::WorldRegion() + : chunksData(std::make_unique[]>(REGION_CHUNKS_COUNT)), + sizes(std::make_unique(REGION_CHUNKS_COUNT)) +{} WorldRegion::~WorldRegion() { - for (uint i = 0; i < REGION_CHUNKS_COUNT; i++) { - delete[] chunksData[i]; - } - delete[] sizes; - delete[] chunksData; } void WorldRegion::setUnsaved(bool unsaved) { @@ -69,30 +65,29 @@ bool WorldRegion::isUnsaved() const { return unsaved; } -ubyte** WorldRegion::getChunks() const { - return chunksData; +std::unique_ptr* WorldRegion::getChunks() const { + return chunksData.get(); } uint32_t* WorldRegion::getSizes() const { - return sizes; + return sizes.get(); } void WorldRegion::put(uint x, uint z, ubyte* data, uint32_t size) { size_t chunk_index = z * REGION_SIZE + x; - delete[] chunksData[chunk_index]; - chunksData[chunk_index] = data; + chunksData[chunk_index].reset(data); sizes[chunk_index] = size; } ubyte* WorldRegion::getChunkData(uint x, uint z) { - return chunksData[z * REGION_SIZE + x]; + return chunksData[z * REGION_SIZE + x].get(); } uint WorldRegion::getChunkDataSize(uint x, uint z) { return sizes[z * REGION_SIZE + x]; } -WorldRegions::WorldRegions(fs::path directory) : directory(directory) { +WorldRegions::WorldRegions(const fs::path& directory) : directory(directory) { for (uint i = 0; i < sizeof(layers)/sizeof(RegionsLayer); i++) { layers[i].layer = i; } @@ -108,19 +103,21 @@ WorldRegion* WorldRegions::getRegion(int x, int z, int layer) { RegionsLayer& regions = layers[layer]; std::lock_guard lock(regions.mutex); auto found = regions.regions.find(glm::ivec2(x, z)); - if (found == regions.regions.end()) + if (found == regions.regions.end()) { return nullptr; + } return found->second.get(); } WorldRegion* WorldRegions::getOrCreateRegion(int x, int z, int layer) { - WorldRegion* region = getRegion(x, z, layer); - if (region == nullptr) { - RegionsLayer& regions = layers[layer]; - std::lock_guard lock(regions.mutex); - region = new WorldRegion(); - regions.regions[glm::ivec2(x, z)].reset(region); + if (auto region = getRegion(x, z, layer)) { + return region; } + RegionsLayer& regions = layers[layer]; + std::lock_guard lock(regions.mutex); + auto region_ptr = std::make_unique(); + auto region = region_ptr.get(); + regions.regions[{x, z}] = std::move(region_ptr); return region; } @@ -152,10 +149,7 @@ inline void calc_reg_coords( } std::unique_ptr WorldRegions::readChunkData( - int x, - int z, - uint32_t& length, - regfile* rfile + int x, int z, uint32_t& length, regfile* rfile ){ int regionX, regionZ, localX, localZ; calc_reg_coords(x, z, regionX, regionZ, localX, localZ); @@ -165,14 +159,14 @@ std::unique_ptr WorldRegions::readChunkData( /// @brief Read missing chunks data (null pointers) from region file void WorldRegions::fetchChunks(WorldRegion* region, int x, int z, regfile* file) { - ubyte** chunks = region->getChunks(); + auto* chunks = region->getChunks(); uint32_t* sizes = region->getSizes(); for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) { int chunk_x = (i % REGION_SIZE) + x * REGION_SIZE; int chunk_z = (i / REGION_SIZE) + z * REGION_SIZE; if (chunks[i] == nullptr) { - chunks[i] = readChunkData(chunk_x, chunk_z, sizes[i], file).release(); + chunks[i] = readChunkData(chunk_x, chunk_z, sizes[i], file); } } } @@ -205,13 +199,10 @@ ubyte* WorldRegions::getData( return nullptr; } -std::shared_ptr WorldRegions::useRegFile(glm::ivec3 coord) { +regfile_ptr WorldRegions::useRegFile(glm::ivec3 coord) { auto* file = openRegFiles[coord].get(); file->inUse = true; - return std::shared_ptr(file, [this](regfile* ptr) { - ptr->inUse = false; - regFilesCv.notify_one(); - }); + return regfile_ptr(file, ®FilesCv); } void WorldRegions::closeRegFile(glm::ivec3 coord) { @@ -220,7 +211,7 @@ void WorldRegions::closeRegFile(glm::ivec3 coord) { } // Marks regfile as used and unmarks when shared_ptr dies -std::shared_ptr WorldRegions::getRegFile(glm::ivec3 coord, bool create) { +regfile_ptr WorldRegions::getRegFile(glm::ivec3 coord, bool create) { { std::lock_guard lock(regFilesMutex); const auto found = openRegFiles.find(coord); @@ -237,7 +228,7 @@ std::shared_ptr WorldRegions::getRegFile(glm::ivec3 coord, bool create) return nullptr; } -std::shared_ptr WorldRegions::createRegFile(glm::ivec3 coord) { +regfile_ptr WorldRegions::createRegFile(glm::ivec3 coord) { fs::path file = layers[coord[2]].folder/getRegionFilename(coord[0], coord[1]); if (!fs::exists(file)) { return nullptr; @@ -281,6 +272,7 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){ fetchChunks(entry, x, z, regfile.get()); std::lock_guard lock(regFilesMutex); + regfile.reset(); closeRegFile(regcoord); } @@ -294,18 +286,18 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){ char intbuf[4]{}; uint offsets[REGION_CHUNKS_COUNT]{}; - ubyte** region = entry->getChunks(); + auto* region = entry->getChunks(); uint32_t* sizes = entry->getSizes(); for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) { - ubyte* chunk = region[i]; + ubyte* chunk = region[i].get(); if (chunk == nullptr){ offsets[i] = 0; } else { offsets[i] = offset; size_t compressedSize = sizes[i]; - dataio::write_int32_big(compressedSize, (ubyte*)intbuf, 0); + dataio::write_int32_big(compressedSize, reinterpret_cast(intbuf), 0); offset += 4 + compressedSize; file.write(intbuf, 4); @@ -313,7 +305,7 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){ } } for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) { - dataio::write_int32_big(offsets[i], (ubyte*)intbuf, 0); + dataio::write_int32_big(offsets[i], reinterpret_cast(intbuf), 0); file.write(intbuf, 4); } } @@ -357,15 +349,20 @@ static std::unique_ptr write_inventories(Chunk* chunk, uint& datasize) auto datavec = builder.data(); datasize = builder.size(); auto data = std::make_unique(datasize); - for (uint i = 0; i < datasize; i++) { - data[i] = datavec[i]; - } + std::memcpy(data.get(), datavec, datasize); return data; } -/// @brief Store chunk (voxels and lights) in region (existing or new) +/// @brief Store chunk data (voxels and lights) in region (existing or new) void WorldRegions::put(Chunk* chunk){ assert(chunk != nullptr); + if (!chunk->flags.lighted) { + return; + } + bool lightsUnsaved = !chunk->flags.loadedLights && doWriteLights; + if (!chunk->flags.unsaved && !lightsUnsaved) { + return; + } int regionX, regionZ, localX, localZ; calc_reg_coords(chunk->x, chunk->z, regionX, regionZ, localX, localZ); @@ -408,11 +405,12 @@ std::unique_ptr WorldRegions::getLights(int x, int z) { } chunk_inventories_map WorldRegions::fetchInventories(int x, int z) { - chunk_inventories_map inventories; + chunk_inventories_map meta; uint32_t bytesSize; const ubyte* data = getData(x, z, REGION_LAYER_INVENTORIES, bytesSize); - if (data == nullptr) - return inventories; + if (data == nullptr) { + return meta; + } ByteReader reader(data, bytesSize); int count = reader.getInt32(); for (int i = 0; i < count; i++) { @@ -422,12 +420,12 @@ chunk_inventories_map WorldRegions::fetchInventories(int x, int z) { reader.skip(size); auto inv = std::make_shared(0, 0); inv->deserialize(map.get()); - inventories[index] = inv; + meta[index] = inv; } - return inventories; + return meta; } -void WorldRegions::processRegionVoxels(int x, int z, regionproc func) { +void WorldRegions::processRegionVoxels(int x, int z, const regionproc& func) { if (getRegion(x, z, REGION_LAYER_VOXELS)) { throw std::runtime_error("not implemented for in-memory regions"); } @@ -465,8 +463,9 @@ void WorldRegions::write() { bool WorldRegions::parseRegionFilename(const std::string& name, int& x, int& z) { size_t sep = name.find('_'); - if (sep == std::string::npos || sep == 0 || sep == name.length()-1) + if (sep == std::string::npos || sep == 0 || sep == name.length()-1) { return false; + } try { x = std::stoi(name.substr(0, sep)); z = std::stoi(name.substr(sep+1)); diff --git a/src/files/WorldRegions.hpp b/src/files/WorldRegions.hpp index ae727c09..7ad16037 100644 --- a/src/files/WorldRegions.hpp +++ b/src/files/WorldRegions.hpp @@ -38,8 +38,8 @@ public: }; class WorldRegion { - ubyte** chunksData; - uint32_t* sizes; + std::unique_ptr[]> chunksData; + std::unique_ptr sizes; bool unsaved = false; public: WorldRegion(); @@ -52,7 +52,7 @@ public: void setUnsaved(bool unsaved); bool isUnsaved() const; - ubyte** getChunks() const; + std::unique_ptr* getChunks() const; uint32_t* getSizes() const; }; @@ -77,6 +77,43 @@ struct RegionsLayer { std::mutex mutex; }; +class regfile_ptr { + regfile* file; + std::condition_variable* cv; +public: + regfile_ptr( + regfile* file, + std::condition_variable* cv + ) : file(file), cv(cv) {} + + regfile_ptr(const regfile_ptr&) = delete; + + regfile_ptr(std::nullptr_t) : file(nullptr), cv(nullptr) {} + + bool operator==(std::nullptr_t) const { + return file == nullptr; + } + bool operator!=(std::nullptr_t) const { + return file != nullptr; + } + operator bool() const { + return file != nullptr; + } + ~regfile_ptr() { + reset(); + } + regfile* get() { + return file; + } + void reset() { + if (file) { + file->inUse = false; + cv->notify_one(); + file = nullptr; + } + } +}; + class WorldRegions { fs::path directory; std::unordered_map> openRegFiles; @@ -110,10 +147,10 @@ class WorldRegions { ubyte* getData(int x, int z, int layer, uint32_t& size); - std::shared_ptr getRegFile(glm::ivec3 coord, bool create=true); + regfile_ptr getRegFile(glm::ivec3 coord, bool create=true); void closeRegFile(glm::ivec3 coord); - std::shared_ptr useRegFile(glm::ivec3 coord); - std::shared_ptr createRegFile(glm::ivec3 coord); + regfile_ptr useRegFile(glm::ivec3 coord); + regfile_ptr createRegFile(glm::ivec3 coord); fs::path getRegionFilename(int x, int y) const; @@ -128,7 +165,7 @@ public: bool generatorTestMode = false; bool doWriteLights = true; - WorldRegions(fs::path directory); + WorldRegions(const fs::path& directory); WorldRegions(const WorldRegions&) = delete; ~WorldRegions(); @@ -148,7 +185,7 @@ public: std::unique_ptr getLights(int x, int z); chunk_inventories_map fetchInventories(int x, int z); - void processRegionVoxels(int x, int z, regionproc func); + void processRegionVoxels(int x, int z, const regionproc& func); fs::path getRegionsFolder(int layer) const; diff --git a/src/files/engine_paths.cpp b/src/files/engine_paths.cpp index 15e80325..c08d6bd2 100644 --- a/src/files/engine_paths.cpp +++ b/src/files/engine_paths.cpp @@ -4,15 +4,24 @@ #include #include #include +#include #include "../util/stringutil.hpp" #include "../typedefs.hpp" #include "WorldFiles.hpp" const fs::path SCREENSHOTS_FOLDER {"screenshots"}; +const fs::path CONTENT_FOLDER {"content"}; const fs::path CONTROLS_FILE {"controls.toml"}; const fs::path SETTINGS_FILE {"settings.toml"}; +void EnginePaths::prepare() { + fs::path contentFolder = userfiles/fs::path(CONTENT_FOLDER); + if (!fs::is_directory(contentFolder)) { + fs::create_directories(contentFolder); + } +} + fs::path EnginePaths::getUserfiles() const { return userfiles; } @@ -21,7 +30,7 @@ fs::path EnginePaths::getResources() const { return resources; } -fs::path EnginePaths::getScreenshotFile(std::string ext) { +fs::path EnginePaths::getScreenshotFile(const std::string& ext) { fs::path folder = userfiles/fs::path(SCREENSHOTS_FOLDER); if (!fs::is_directory(folder)) { fs::create_directory(folder); @@ -60,10 +69,6 @@ fs::path EnginePaths::getControlsFile() { return userfiles/fs::path(CONTROLS_FILE); } -fs::path EnginePaths::getControlsFileOld() { - return userfiles/fs::path("controls.json"); -} - fs::path EnginePaths::getSettingsFile() { return userfiles/fs::path(SETTINGS_FILE); } @@ -75,11 +80,11 @@ std::vector EnginePaths::scanForWorlds() { if (!fs::is_directory(folder)) return folders; - for (auto entry : fs::directory_iterator(folder)) { + for (const auto& entry : fs::directory_iterator(folder)) { if (!entry.is_directory()) { continue; } - fs::path worldFolder = entry.path(); + const fs::path& worldFolder = entry.path(); fs::path worldFile = worldFolder/fs::u8path(WorldFiles::WORLD_FILE); if (!fs::is_regular_file(worldFile)) { continue; @@ -94,20 +99,20 @@ std::vector EnginePaths::scanForWorlds() { return folders; } -bool EnginePaths::isWorldNameUsed(std::string name) { +bool EnginePaths::isWorldNameUsed(const std::string& name) { return fs::exists(EnginePaths::getWorldsFolder()/fs::u8path(name)); } void EnginePaths::setUserfiles(fs::path folder) { - this->userfiles = folder; + this->userfiles = std::move(folder); } void EnginePaths::setResources(fs::path folder) { - this->resources = folder; + this->resources = std::move(folder); } void EnginePaths::setWorldFolder(fs::path folder) { - this->worldFolder = folder; + this->worldFolder = std::move(folder); } void EnginePaths::setContentPacks(std::vector* contentPacks) { @@ -139,7 +144,7 @@ static fs::path toCanonic(fs::path path) { return path; } -fs::path EnginePaths::resolve(std::string path, bool throwErr) { +fs::path EnginePaths::resolve(const std::string& path, bool throwErr) { size_t separator = path.find(':'); if (separator == std::string::npos) { throw files_access_error("no entry point specified"); @@ -172,7 +177,7 @@ fs::path EnginePaths::resolve(std::string path, bool throwErr) { } ResPaths::ResPaths(fs::path mainRoot, std::vector roots) - : mainRoot(mainRoot), roots(roots) { + : mainRoot(std::move(mainRoot)), roots(std::move(roots)) { } fs::path ResPaths::find(const std::string& filename) const { diff --git a/src/files/engine_paths.hpp b/src/files/engine_paths.hpp index 92353e65..025835ac 100644 --- a/src/files/engine_paths.hpp +++ b/src/files/engine_paths.hpp @@ -21,17 +21,18 @@ class EnginePaths { fs::path worldFolder; std::vector* contentPacks = nullptr; public: + void prepare(); + fs::path getUserfiles() const; fs::path getResources() const; - fs::path getScreenshotFile(std::string ext); + fs::path getScreenshotFile(const std::string& ext); fs::path getWorldsFolder(); fs::path getWorldFolder(); fs::path getWorldFolder(const std::string& name); fs::path getControlsFile(); - fs::path getControlsFileOld(); // TODO: remove in 0.22 fs::path getSettingsFile(); - bool isWorldNameUsed(std::string name); + bool isWorldNameUsed(const std::string& name); void setUserfiles(fs::path folder); void setResources(fs::path folder); @@ -40,7 +41,7 @@ public: std::vector scanForWorlds(); - fs::path resolve(std::string path, bool throwErr=true); + fs::path resolve(const std::string& path, bool throwErr=true); }; struct PathsRoot { diff --git a/src/files/files.cpp b/src/files/files.cpp index bd9e1716..644e8716 100644 --- a/src/files/files.cpp +++ b/src/files/files.cpp @@ -15,7 +15,7 @@ namespace fs = std::filesystem; -files::rafile::rafile(fs::path filename) +files::rafile::rafile(const fs::path& filename) : file(filename, std::ios::binary | std::ios::ate) { if (!file) { throw std::runtime_error("could not to open file "+filename.string()); @@ -36,7 +36,7 @@ void files::rafile::read(char* buffer, std::streamsize size) { file.read(buffer, size); } -bool files::write_bytes(fs::path filename, const ubyte* data, size_t size) { +bool files::write_bytes(const fs::path& filename, const ubyte* data, size_t size) { std::ofstream output(filename, std::ios::binary); if (!output.is_open()) return false; @@ -45,7 +45,7 @@ bool files::write_bytes(fs::path filename, const ubyte* data, size_t size) { return true; } -uint files::append_bytes(fs::path filename, const ubyte* data, size_t size) { +uint files::append_bytes(const fs::path& filename, const ubyte* data, size_t size) { std::ofstream output(filename, std::ios::binary | std::ios::app); if (!output.is_open()) return 0; @@ -55,7 +55,7 @@ uint files::append_bytes(fs::path filename, const ubyte* data, size_t size) { return position; } -bool files::read(fs::path filename, char* data, size_t size) { +bool files::read(const fs::path& filename, char* data, size_t size) { std::ifstream output(filename, std::ios::binary); if (!output.is_open()) return false; @@ -64,7 +64,7 @@ bool files::read(fs::path filename, char* data, size_t size) { return true; } -std::unique_ptr files::read_bytes(fs::path filename, size_t& length) { +std::unique_ptr files::read_bytes(const fs::path& filename, size_t& length) { std::ifstream input(filename, std::ios::binary); if (!input.is_open()) return nullptr; @@ -78,7 +78,7 @@ std::unique_ptr files::read_bytes(fs::path filename, size_t& length) { return data; } -std::string files::read_string(fs::path filename) { +std::string files::read_string(const fs::path& filename) { size_t size; std::unique_ptr bytes (read_bytes(filename, size)); if (bytes == nullptr) { @@ -88,7 +88,7 @@ std::string files::read_string(fs::path filename) { return std::string((const char*)bytes.get(), size); } -bool files::write_string(fs::path filename, const std::string content) { +bool files::write_string(const fs::path& filename, const std::string content) { std::ofstream file(filename); if (!file) { return false; @@ -97,16 +97,16 @@ bool files::write_string(fs::path filename, const std::string content) { return true; } -bool files::write_json(fs::path filename, const dynamic::Map* obj, bool nice) { +bool files::write_json(const fs::path& filename, const dynamic::Map* obj, bool nice) { return files::write_string(filename, json::stringify(obj, nice, " ")); } -bool files::write_binary_json(fs::path filename, const dynamic::Map* obj, bool compression) { +bool files::write_binary_json(const fs::path& filename, const dynamic::Map* obj, bool compression) { auto bytes = json::to_binary(obj, compression); return files::write_bytes(filename, bytes.data(), bytes.size()); } -std::shared_ptr files::read_json(fs::path filename) { +std::shared_ptr files::read_json(const fs::path& filename) { std::string text = files::read_string(filename); try { return json::parse(filename.string(), text);; @@ -116,17 +116,17 @@ std::shared_ptr files::read_json(fs::path filename) { } } -std::shared_ptr files::read_binary_json(fs::path file) { +std::shared_ptr files::read_binary_json(const fs::path& file) { size_t size; std::unique_ptr bytes (files::read_bytes(file, size)); return json::from_binary(bytes.get(), size); } -std::shared_ptr files::read_toml(fs::path file) { +std::shared_ptr files::read_toml(const fs::path& file) { return toml::parse(file.u8string(), files::read_string(file)); } -std::vector files::read_list(fs::path filename) { +std::vector files::read_list(const fs::path& filename) { std::ifstream file(filename); if (!file) { throw std::runtime_error("could not to open file "+filename.u8string()); diff --git a/src/files/files.hpp b/src/files/files.hpp index 142deb25..4e6ad960 100644 --- a/src/files/files.hpp +++ b/src/files/files.hpp @@ -20,7 +20,7 @@ namespace files { std::ifstream file; size_t filelength; public: - rafile(fs::path filename); + rafile(const fs::path& filename); void seekg(std::streampos pos); void read(char* buffer, std::streamsize size); @@ -31,40 +31,40 @@ namespace files { /// @param file target file /// @param data data bytes array /// @param size size of data bytes array - bool write_bytes(fs::path file, const ubyte* data, size_t size); + bool write_bytes(const fs::path& file, const ubyte* data, size_t size); /// @brief Append bytes array to the file without any extra data /// @param file target file /// @param data data bytes array /// @param size size of data bytes array - uint append_bytes(fs::path file, const ubyte* data, size_t size); + uint append_bytes(const fs::path& file, const ubyte* data, size_t size); /// @brief Write string to the file - bool write_string(fs::path filename, const std::string content); + bool write_string(const fs::path& filename, const std::string content); /// @brief Write dynamic data to the JSON file /// @param nice if true, human readable format will be used, otherwise minimal - bool write_json(fs::path filename, const dynamic::Map* obj, bool nice=true); + bool write_json(const fs::path& filename, const dynamic::Map* obj, bool nice=true); /// @brief Write dynamic data to the binary JSON file /// (see src/coders/binary_json_spec.md) /// @param compressed use gzip compression bool write_binary_json( - fs::path filename, + const fs::path& filename, const dynamic::Map* obj, bool compressed=false ); - bool read(fs::path, char* data, size_t size); - std::unique_ptr read_bytes(fs::path, size_t& length); - std::string read_string(fs::path filename); + bool read(const fs::path&, char* data, size_t size); + std::unique_ptr read_bytes(const fs::path&, size_t& length); + std::string read_string(const fs::path& filename); /// @brief Read JSON or BJSON file /// @param file *.json or *.bjson file - std::shared_ptr read_json(fs::path file); - std::shared_ptr read_binary_json(fs::path file); - std::shared_ptr read_toml(fs::path file); - std::vector read_list(fs::path file); + std::shared_ptr read_json(const fs::path& file); + std::shared_ptr read_binary_json(const fs::path& file); + std::shared_ptr read_toml(const fs::path& file); + std::vector read_list(const fs::path& file); } #endif /* FILES_FILES_HPP_ */ diff --git a/src/files/settings_io.cpp b/src/files/settings_io.cpp index 66fced1d..373dc45c 100644 --- a/src/files/settings_io.cpp +++ b/src/files/settings_io.cpp @@ -8,6 +8,7 @@ #include "../settings.hpp" #include +#include static debug::Logger logger("settings_io"); @@ -22,10 +23,10 @@ struct SectionsBuilder { } void section(std::string name) { - sections.push_back(Section {name, {}}); + sections.push_back(Section {std::move(name), {}}); } - void add(std::string name, Setting* setting, bool writeable=true) { + void add(const std::string& name, Setting* setting, bool writeable=true) { Section& section = sections.at(sections.size()-1); map[section.name+"."+name] = setting; section.keys.push_back(name); diff --git a/src/frontend/UiDocument.cpp b/src/frontend/UiDocument.cpp index b593f9e0..3951e4e9 100644 --- a/src/frontend/UiDocument.cpp +++ b/src/frontend/UiDocument.cpp @@ -1,5 +1,7 @@ #include "UiDocument.hpp" +#include + #include "../files/files.hpp" #include "../graphics/ui/elements/UINode.hpp" #include "../graphics/ui/elements/InventoryView.hpp" @@ -9,9 +11,9 @@ UiDocument::UiDocument( std::string id, uidocscript script, - std::shared_ptr root, + const std::shared_ptr& root, scriptenv env -) : id(id), script(script), root(root), env(env) { +) : id(std::move(id)), script(script), root(root), env(std::move(env)) { gui::UINode::getIndices(root, map); } @@ -31,11 +33,11 @@ const std::string& UiDocument::getId() const { return id; } -const std::shared_ptr UiDocument::getRoot() const { +std::shared_ptr UiDocument::getRoot() const { return root; } -const std::shared_ptr UiDocument::get(const std::string& id) const { +std::shared_ptr UiDocument::get(const std::string& id) const { auto found = map.find(id); if (found == map.end()) { return nullptr; @@ -51,7 +53,7 @@ scriptenv UiDocument::getEnvironment() const { return env; } -std::unique_ptr UiDocument::read(scriptenv penv, std::string name, fs::path file) { +std::unique_ptr UiDocument::read(const scriptenv& penv, const std::string& name, const fs::path& file) { const std::string text = files::read_string(file); auto xmldoc = xml::parse(file.u8string(), text); @@ -72,7 +74,7 @@ std::unique_ptr UiDocument::read(scriptenv penv, std::string name, f return std::make_unique(name, script, view, env); } -std::shared_ptr UiDocument::readElement(fs::path file) { +std::shared_ptr UiDocument::readElement(const fs::path& file) { auto document = read(nullptr, file.filename().u8string(), file); return document->getRoot(); } diff --git a/src/frontend/UiDocument.hpp b/src/frontend/UiDocument.hpp index d45b8783..504411a9 100644 --- a/src/frontend/UiDocument.hpp +++ b/src/frontend/UiDocument.hpp @@ -32,7 +32,7 @@ public: UiDocument( std::string id, uidocscript script, - std::shared_ptr root, + const std::shared_ptr &root, scriptenv env ); @@ -41,13 +41,13 @@ public: const std::string& getId() const; const uinodes_map& getMap() const; uinodes_map& getMapWriteable(); - const std::shared_ptr getRoot() const; - const std::shared_ptr get(const std::string& id) const; + std::shared_ptr getRoot() const; + std::shared_ptr get(const std::string& id) const; const uidocscript& getScript() const; scriptenv getEnvironment() const; - static std::unique_ptr read(scriptenv parent_env, std::string name, fs::path file); - static std::shared_ptr readElement(fs::path file); + static std::unique_ptr read(const scriptenv& parent_env, const std::string& name, const fs::path& file); + static std::shared_ptr readElement(const fs::path& file); }; #endif // FRONTEND_UI_DOCUMENT_HPP_ diff --git a/src/frontend/debug_panel.cpp b/src/frontend/debug_panel.cpp index 529d5acf..d61e021f 100644 --- a/src/frontend/debug_panel.cpp +++ b/src/frontend/debug_panel.cpp @@ -8,6 +8,7 @@ #include "../graphics/ui/elements/TrackBar.hpp" #include "../graphics/ui/elements/InputBindBox.hpp" #include "../graphics/render/WorldRenderer.hpp" +#include "../logic/scripting/scripting.hpp" #include "../objects/Player.hpp" #include "../physics/Hitbox.hpp" #include "../util/stringutil.hpp" @@ -21,12 +22,13 @@ #include #include #include +#include using namespace gui; static std::shared_ptr