This commit is contained in:
@clasher113 2024-06-13 16:59:09 +03:00
commit c88bbe7fcb
220 changed files with 3524 additions and 3112 deletions

View File

@ -2,7 +2,7 @@ name: C/C++ AppImage
on: on:
push: push:
branches: [ "main" ] branches: [ "main", "release-**"]
pull_request: pull_request:
branches: [ "main" ] branches: [ "main" ]
@ -24,8 +24,15 @@ jobs:
run: | run: |
sudo apt-get update 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 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/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 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 - name: configure
run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DVOXELENGINE_BUILD_APPDIR=1 run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DVOXELENGINE_BUILD_APPDIR=1
- name: build - name: build

View File

@ -36,8 +36,15 @@ jobs:
run: | run: |
sudo apt-get update 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 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/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 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 - name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only

View File

@ -17,7 +17,7 @@ jobs:
- name: Install dependencies from brew - name: Install dependencies from brew
run: | 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 - name: Install specific version of GLM
run: | run: |

2
.gitignore vendored
View File

@ -13,6 +13,8 @@ Debug/voxel_engine
/worlds/**/* /worlds/**/*
/settings.toml /settings.toml
/controls.json /controls.json
/controls.toml
/latest.log
/.idea /.idea
.vscode .vscode

View File

@ -84,6 +84,9 @@ find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED) find_package(GLEW REQUIRED)
find_package(OpenAL REQUIRED) find_package(OpenAL REQUIRED)
find_package(ZLIB REQUIRED) find_package(ZLIB REQUIRED)
if (NOT APPLE)
find_package(EnTT REQUIRED)
endif()
if (WIN32) if (WIN32)
if(VOXELENGINE_BUILD_WINDOWS_VCPKG) if(VOXELENGINE_BUILD_WINDOWS_VCPKG)
@ -120,7 +123,6 @@ else()
set(LUA_LIBRARIES ${LUAJIT_LIBRARIES}) set(LUA_LIBRARIES ${LUAJIT_LIBRARIES})
set(LUA_INCLUDE_DIR ${LUAJIT_INCLUDE_DIRS}) set(LUA_INCLUDE_DIR ${LUAJIT_INCLUDE_DIRS})
find_package(PNG REQUIRED) find_package(PNG REQUIRED)
find_package(Lua REQUIRED)
set(PNGLIB PNG::PNG) set(PNGLIB PNG::PNG)
set(VORBISLIB ${VORBIS_LDFLAGS}) set(VORBISLIB ${VORBIS_LDFLAGS})
endif() endif()

View File

@ -29,6 +29,14 @@ cmake --build .
## Install libs: ## 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: #### Debian-based distro:
```sh ```sh
sudo apt install libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev 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: #### 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). 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).

View File

@ -10,4 +10,7 @@
- [Скриптинг](8.Скриптинг.md) - [Скриптинг](8.Скриптинг.md)
- [Модуль core:bit_converter](8.1.Модуль-Lua-core_bit_converter.md) - [Модуль core:bit_converter](8.1.Модуль-Lua-core_bit_converter.md)
- [Модуль core:data_buffer](8.2.Модуль-Lua-core_data_buffer.md) - [Модуль core:data_buffer](8.2.Модуль-Lua-core_data_buffer.md)
- [Пользовательский ввод](Пользовательский-ввод.md)
- [Файловая система и сериализация](Файловая-система-и-сериализация.md)
- [Консоль](Консоль.md)
- [Модели блоков](9.Модели-блоков.md) - [Модели блоков](9.Модели-блоков.md)

View File

@ -0,0 +1,5 @@
{
"steps-sound": "steps/carpet",
"place-sound": "blocks/carpet_place",
"break-sound": "blocks/carpet_break"
}

View File

@ -1,5 +1,5 @@
{ {
"steps-sound": "steps/wood", "steps-sound": "steps/glass",
"place-sound": "blocks/wood_place", "place-sound": "blocks/glass_place",
"break-sound": "blocks/glass_break" "break-sound": "blocks/glass_break"
} }

View File

@ -0,0 +1,5 @@
{
"steps-sound": "steps/metal",
"place-sound": "blocks/metal_place",
"break-sound": "blocks/metal_break"
}

View File

@ -1,5 +1,5 @@
{ {
"steps-sound": "steps/sand", "steps-sound": "steps/sand",
"steps-sound": "blocks/ground_place", "place-sound": "blocks/ground_place",
"break-sound": "blocks/ground_break" "break-sound": "blocks/ground_break"
} }

View File

@ -1,4 +1,5 @@
{ {
"texture": "blue_lamp", "texture": "blue_lamp",
"emission": [0, 0, 15] "emission": [0, 0, 15],
"material": "base:glass"
} }

View File

@ -1,4 +1,5 @@
{ {
"texture": "green_lamp", "texture": "green_lamp",
"emission": [0, 15, 0] "emission": [0, 15, 0],
"material": "base:glass"
} }

View File

@ -6,5 +6,6 @@
"hitbox": [0.25, 0.0, 0.25, 0.5, 0.5, 0.5], "hitbox": [0.25, 0.0, 0.25, 0.5, 0.5, 0.5],
"rotation": "pipe", "rotation": "pipe",
"light-passing": true, "light-passing": true,
"sky-light-passing": true "sky-light-passing": true,
"material": "base:glass"
} }

View File

@ -1,3 +1,4 @@
{ {
"texture": "metal" "texture": "metal",
"material": "base:metal"
} }

View File

@ -10,5 +10,6 @@
"model": "aabb", "model": "aabb",
"hitbox": [0.25, 0.0, 0.25, 0.5, 1.0, 0.5], "hitbox": [0.25, 0.0, 0.25, 0.5, 1.0, 0.5],
"light-passing": true, "light-passing": true,
"rotation": "pipe" "rotation": "pipe",
"material": "base:metal"
} }

View File

@ -1,4 +1,5 @@
{ {
"texture": "red_lamp", "texture": "red_lamp",
"emission": [15, 0, 0] "emission": [15, 0, 0],
"material": "base:glass"
} }

View File

@ -1,3 +1,4 @@
{ {
"texture": "rust" "texture": "rust",
"material": "base:metal"
} }

View File

@ -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]
}

View File

@ -25,6 +25,7 @@
"pane", "pane",
"pipe", "pipe",
"lightbulb", "lightbulb",
"torch" "torch",
"wooden_door"
] ]
} }

View File

@ -1,6 +1,6 @@
{ {
"id": "base", "id": "base",
"title": "Base", "title": "Base",
"version": "0.21", "version": "0.22",
"description": "basic content package" "description": "basic content package"
} }

View File

@ -0,0 +1,6 @@
{
"sounds": [
"blocks/door_open",
"blocks/door_close"
]
}

View File

@ -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

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

View File

@ -38,12 +38,7 @@ function submit(text)
document.log.caret = -1 document.log.caret = -1
local status, result = pcall(function() return console.execute(text) end) local status, result = pcall(function() return console.execute(text) end)
if result ~= nil then if result ~= nil then
local prevtext = document.log.text console.log(result)
if #prevtext == 0 then
document.log:paste(tostring(result))
else
document.log:paste('\n'..tostring(result))
end
end end
document.prompt.text = "" document.prompt.text = ""
document.prompt.focused = true document.prompt.focused = true

View File

@ -203,6 +203,24 @@ function time.post_runnable(runnable)
table.insert(__post_runnables, runnable) table.insert(__post_runnables, runnable)
end 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) function gui.template(name, params)
local text = file.read(file.find("layouts/templates/"..name..".xml")) local text = file.read(file.find("layouts/templates/"..name..".xml"))
for k,v in pairs(params) do for k,v in pairs(params) do

View File

@ -13,58 +13,62 @@ error.dependency-not-found=Käytetty riippuvuutta ei löytynyt
pack.remove-confirm=Poistetaanko kaikki pakettien sisältö maailmasta (peruuttamattomasti)? pack.remove-confirm=Poistetaanko kaikki pakettien sisältö maailmasta (peruuttamattomasti)?
# Меню # Меню
menu.New World=Uusi Maailma menu.Apply=Tallenna
menu.Quit=Poistu menu.Audio=Ääni
menu.Continue=Jatka menu.Back to Main Menu=Takaisin Valikkoon
menu.Save and Quit to Menu=Tallenna ja poistu valikkoon menu.Content Error=Virhe Sisällössä
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.Content=Sisältö 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.Seed=Siemen
world.Name=Nimi world.Name=Nimi
world.World generator=Maailma Generaatori
world.World generator=Maailman generaattori
world.generators.default=Tavallinen world.generators.default=Tavallinen
world.generators.flat=Tasainen world.generators.flat=Tasainen
menu.Create World=Luo Maailma world.Create World=Luo Maailma
world.convert-request=Indekseissä on muutoksia! Kääntää maailman?
world.convert-request=Indeksit ovat muuttuneet! Luodaanko maailma uudeleen? world.delete-confirm=Poistetaanko maailma pysyvästi?
world.delete-confirm=Poistetaanko maailma peruuttamattomasti?
# Настройки # Настройки
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.Ambient=Tausta
settings.Music=Musiikki settings.Backlight=Taustavalo
settings.Camera Shaking=Tärisevä kamera
settings.FOV=Näkökenttä settings.Fog Curve=Sumukäurä
settings.Mouse Sensitivity=Hiiren nopeus settings.FOV=Näkokenttä
settings.Fullscreen=Koko näyttö
settings.Gamma=Gamma
settings.Language=Kieli 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.forward=Eteenpäin
movement.back=Taaksepäin movement.back=Taaksepäin
movement.left=Vaseemalle movement.left=Vaseemmalle
movement.right=Oikealle movement.right=Oikealle
movement.jump=Hyppy movement.jump=Hyppy
movement.sprint=Juoksu movement.sprint=Kiihtyvyys
movement.crouch=Hiipiä movement.crouch=Hiipiä
movement.cheat=Huijata movement.cheat=Huijata
hud.inventory=Varasto hud.inventory=Varasto
player.pick=Ottaa lohko player.pick=Valitse lohko
player.attack=Lyödä / Rikkoa player.attack=Lyödä / Rikkoa
player.build=Aseta lohko player.build=Aseta lohko
player.flight=Lento player.flight=Lento
camera.zoom=Lähentäminen camera.zoom=Lähentäminen
camera.mode=Vaihda Kameratila camera.mode=Vaihda kameratilaa

View File

@ -11,59 +11,59 @@
Assets::~Assets() { Assets::~Assets() {
} }
Texture* Assets::getTexture(std::string name) const { Texture* Assets::getTexture(const std::string& name) const {
auto found = textures.find(name); auto found = textures.find(name);
if (found == textures.end()) if (found == textures.end())
return nullptr; return nullptr;
return found->second.get(); return found->second.get();
} }
void Assets::store(std::unique_ptr<Texture> texture, std::string name){ void Assets::store(std::unique_ptr<Texture> texture, const std::string& name){
textures.emplace(name, std::move(texture)); 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); auto found = shaders.find(name);
if (found == shaders.end()) if (found == shaders.end())
return nullptr; return nullptr;
return found->second.get(); return found->second.get();
} }
void Assets::store(std::unique_ptr<Shader> shader, std::string name){ void Assets::store(std::unique_ptr<Shader> shader, const std::string& name){
shaders.emplace(name, std::move(shader)); 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); auto found = fonts.find(name);
if (found == fonts.end()) if (found == fonts.end())
return nullptr; return nullptr;
return found->second.get(); return found->second.get();
} }
void Assets::store(std::unique_ptr<Font> font, std::string name){ void Assets::store(std::unique_ptr<Font> font, const std::string& name){
fonts.emplace(name, std::move(font)); 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); auto found = atlases.find(name);
if (found == atlases.end()) if (found == atlases.end())
return nullptr; return nullptr;
return found->second.get(); return found->second.get();
} }
void Assets::store(std::unique_ptr<Atlas> atlas, std::string name){ void Assets::store(std::unique_ptr<Atlas> atlas, const std::string& name){
atlases.emplace(name, std::move(atlas)); 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); auto found = sounds.find(name);
if (found == sounds.end()) if (found == sounds.end())
return nullptr; return nullptr;
return found->second.get(); return found->second.get();
} }
void Assets::store(std::unique_ptr<audio::Sound> sound, std::string name) { void Assets::store(std::unique_ptr<audio::Sound> sound, const std::string& name) {
sounds.emplace(name, std::move(sound)); sounds.emplace(name, std::move(sound));
} }
@ -75,13 +75,13 @@ void Assets::store(const TextureAnimation& animation) {
animations.emplace_back(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); auto found = layouts.find(name);
if (found == layouts.end()) if (found == layouts.end())
return nullptr; return nullptr;
return found->second.get(); return found->second.get();
} }
void Assets::store(std::unique_ptr<UiDocument> layout, std::string name) { void Assets::store(std::unique_ptr<UiDocument> layout, const std::string& name) {
layouts[name] = std::shared_ptr<UiDocument>(std::move(layout)); layouts[name] = std::shared_ptr<UiDocument>(std::move(layout));
} }

View File

@ -38,26 +38,26 @@ public:
Assets(const Assets&) = delete; Assets(const Assets&) = delete;
~Assets(); ~Assets();
Texture* getTexture(std::string name) const; Texture* getTexture(const std::string& name) const;
void store(std::unique_ptr<Texture> texture, std::string name); void store(std::unique_ptr<Texture> texture, const std::string& name);
Shader* getShader(std::string name) const; Shader* getShader(const std::string& name) const;
void store(std::unique_ptr<Shader> shader, std::string name); void store(std::unique_ptr<Shader> shader, const std::string& name);
Font* getFont(std::string name) const; Font* getFont(const std::string& name) const;
void store(std::unique_ptr<Font> font, std::string name); void store(std::unique_ptr<Font> font, const std::string& name);
Atlas* getAtlas(std::string name) const; Atlas* getAtlas(const std::string& name) const;
void store(std::unique_ptr<Atlas> atlas, std::string name); void store(std::unique_ptr<Atlas> atlas, const std::string& name);
audio::Sound* getSound(std::string name) const; audio::Sound* getSound(const std::string& name) const;
void store(std::unique_ptr<audio::Sound> sound, std::string name); void store(std::unique_ptr<audio::Sound> sound, const std::string& name);
const std::vector<TextureAnimation>& getAnimations(); const std::vector<TextureAnimation>& getAnimations();
void store(const TextureAnimation& animation); void store(const TextureAnimation& animation);
UiDocument* getLayout(std::string name) const; UiDocument* getLayout(const std::string& name) const;
void store(std::unique_ptr<UiDocument> layout, std::string name); void store(std::unique_ptr<UiDocument> layout, const std::string& name);
}; };
#endif // ASSETS_ASSETS_HPP_ #endif // ASSETS_ASSETS_HPP_

View File

@ -17,6 +17,7 @@
#include <iostream> #include <iostream>
#include <memory> #include <memory>
#include <utility>
static debug::Logger logger("assets-loader"); 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) { 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<AssetCfg> settings) { void AssetsLoader::add(AssetType tag, const std::string& filename, const std::string& alias, std::shared_ptr<AssetCfg> settings) {
entries.push(aloader_entry{tag, filename, alias, settings}); entries.push(aloader_entry{tag, filename, alias, std::move(settings)});
} }
bool AssetsLoader::hasNext() const { 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)) { if (!fs::is_directory(folder)) {
return; return;
} }
for (auto& entry : fs::directory_iterator(folder)) { for (auto& entry : fs::directory_iterator(folder)) {
const fs::path file = entry.path(); const fs::path& file = entry.path();
if (file.extension().u8string() != ".xml") if (file.extension().u8string() != ".xml")
continue; continue;
std::string name = prefix+":"+file.stem().u8string(); 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()) { if (name.empty()) {
return; 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); auto root = files::read_json(file);
processPreloadList(AssetType::font, root->list("fonts")); processPreloadList(AssetType::font, root->list("fonts"));
processPreloadList(AssetType::shader, root->list("shaders")); processPreloadList(AssetType::shader, root->list("shaders"));
@ -209,7 +210,7 @@ void AssetsLoader::addDefaults(AssetsLoader& loader, const Content* content) {
bool AssetsLoader::loadExternalTexture( bool AssetsLoader::loadExternalTexture(
Assets* assets, Assets* assets,
const std::string& name, const std::string& name,
std::vector<std::filesystem::path> alternatives const std::vector<std::filesystem::path>& alternatives
) { ) {
if (assets->getTexture(name) != nullptr) { if (assets->getTexture(name) != nullptr) {
return true; return true;
@ -255,7 +256,7 @@ std::shared_ptr<Task> AssetsLoader::startTask(runnable onDone) {
func(assets); func(assets);
} }
); );
pool->setOnComplete(onDone); pool->setOnComplete(std::move(onDone));
while (!entries.empty()) { while (!entries.empty()) {
const aloader_entry& entry = entries.front(); const aloader_entry& entry = entries.front();
auto ptr = std::make_shared<aloader_entry>(entry); auto ptr = std::make_shared<aloader_entry>(entry);

View File

@ -12,6 +12,7 @@
#include <functional> #include <functional>
#include <map> #include <map>
#include <queue> #include <queue>
#include <utility>
namespace dynamic { namespace dynamic {
class Map; class Map;
@ -38,7 +39,7 @@ struct AssetCfg {
struct LayoutCfg : AssetCfg { struct LayoutCfg : AssetCfg {
scriptenv env; scriptenv env;
LayoutCfg(scriptenv env) : env(env) {} LayoutCfg(scriptenv env) : env(std::move(env)) {}
}; };
struct SoundCfg : AssetCfg { struct SoundCfg : AssetCfg {
@ -68,11 +69,11 @@ class AssetsLoader {
std::queue<aloader_entry> entries; std::queue<aloader_entry> entries;
const ResPaths* paths; 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 processPreload(AssetType tag, const std::string& name, dynamic::Map* map);
void processPreloadList(AssetType tag, dynamic::List* list); 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); void processPreloadConfigs(const Content* content);
public: public:
AssetsLoader(Assets* assets, const ResPaths* paths); AssetsLoader(Assets* assets, const ResPaths* paths);
@ -85,8 +86,8 @@ public:
/// @param settings asset loading settings (based on asset type) /// @param settings asset loading settings (based on asset type)
void add( void add(
AssetType tag, AssetType tag,
const std::string filename, const std::string& filename,
const std::string alias, const std::string& alias,
std::shared_ptr<AssetCfg> settings=nullptr std::shared_ptr<AssetCfg> settings=nullptr
); );
@ -106,7 +107,7 @@ public:
static bool loadExternalTexture( static bool loadExternalTexture(
Assets* assets, Assets* assets,
const std::string& name, const std::string& name,
std::vector<std::filesystem::path> alternatives const std::vector<std::filesystem::path>& alternatives
); );
}; };

View File

@ -36,9 +36,9 @@ static bool animation(
assetload::postfunc assetload::texture( assetload::postfunc assetload::texture(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string filename, const std::string& filename,
const std::string name, const std::string& name,
std::shared_ptr<AssetCfg> const std::shared_ptr<AssetCfg>&
) { ) {
std::shared_ptr<ImageData> image ( std::shared_ptr<ImageData> image (
imageio::read(paths->find(filename+".png").u8string()).release() imageio::read(paths->find(filename+".png").u8string()).release()
@ -51,9 +51,9 @@ assetload::postfunc assetload::texture(
assetload::postfunc assetload::shader( assetload::postfunc assetload::shader(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string filename, const std::string& filename,
const std::string name, const std::string& name,
std::shared_ptr<AssetCfg> const std::shared_ptr<AssetCfg>&
) { ) {
fs::path vertexFile = paths->find(filename+".glslv"); fs::path vertexFile = paths->find(filename+".glslv");
fs::path fragmentFile = paths->find(filename+".glslf"); 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( assetload::postfunc assetload::atlas(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string directory, const std::string& directory,
const std::string name, const std::string& name,
std::shared_ptr<AssetCfg> const std::shared_ptr<AssetCfg>&
) { ) {
AtlasBuilder builder; AtlasBuilder builder;
for (const auto& file : paths->listdir(directory)) { for (const auto& file : paths->listdir(directory)) {
@ -113,9 +113,9 @@ assetload::postfunc assetload::atlas(
assetload::postfunc assetload::font( assetload::postfunc assetload::font(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string filename, const std::string& filename,
const std::string name, const std::string& name,
std::shared_ptr<AssetCfg> const std::shared_ptr<AssetCfg>&
) { ) {
auto pages = std::make_shared<std::vector<std::unique_ptr<ImageData>>>(); auto pages = std::make_shared<std::vector<std::unique_ptr<ImageData>>>();
for (size_t i = 0; i <= 4; i++) { for (size_t i = 0; i <= 4; i++) {
@ -136,9 +136,9 @@ assetload::postfunc assetload::font(
assetload::postfunc assetload::layout( assetload::postfunc assetload::layout(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string file, const std::string& file,
const std::string name, const std::string& name,
std::shared_ptr<AssetCfg> config const std::shared_ptr<AssetCfg>& config
) { ) {
return [=](auto assets) { return [=](auto assets) {
try { try {
@ -154,9 +154,9 @@ assetload::postfunc assetload::layout(
assetload::postfunc assetload::sound( assetload::postfunc assetload::sound(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string file, const std::string& file,
const std::string name, const std::string& name,
std::shared_ptr<AssetCfg> config const std::shared_ptr<AssetCfg>& config
) { ) {
auto cfg = std::dynamic_pointer_cast<SoundCfg>(config); auto cfg = std::dynamic_pointer_cast<SoundCfg>(config);
bool keepPCM = cfg ? cfg->keepPCM : false; bool keepPCM = cfg ? cfg->keepPCM : false;

View File

@ -17,45 +17,45 @@ namespace assetload {
postfunc texture( postfunc texture(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string filename, const std::string& filename,
const std::string name, const std::string &name,
std::shared_ptr<AssetCfg> settings const std::shared_ptr<AssetCfg>& settings
); );
postfunc shader( postfunc shader(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string filename, const std::string& filename,
const std::string name, const std::string &name,
std::shared_ptr<AssetCfg> settings const std::shared_ptr<AssetCfg>& settings
); );
postfunc atlas( postfunc atlas(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string directory, const std::string &directory,
const std::string name, const std::string &name,
std::shared_ptr<AssetCfg> settings const std::shared_ptr<AssetCfg>& settings
); );
postfunc font( postfunc font(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string filename, const std::string& filename,
const std::string name, const std::string &name,
std::shared_ptr<AssetCfg> settings const std::shared_ptr<AssetCfg>& settings
); );
postfunc layout( postfunc layout(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string file, const std::string& file,
const std::string name, const std::string &name,
std::shared_ptr<AssetCfg> settings const std::shared_ptr<AssetCfg>& settings
); );
postfunc sound( postfunc sound(
AssetsLoader*, AssetsLoader*,
const ResPaths* paths, const ResPaths* paths,
const std::string file, const std::string& file,
const std::string name, const std::string &name,
std::shared_ptr<AssetCfg> settings const std::shared_ptr<AssetCfg>& settings
); );
} }

View File

@ -4,12 +4,13 @@
#include "../../debug/Logger.hpp" #include "../../debug/Logger.hpp"
#include <string> #include <string>
#include <utility>
static debug::Logger logger("al-audio"); static debug::Logger logger("al-audio");
using namespace audio; using namespace audio;
ALSound::ALSound(ALAudio* al, uint buffer, std::shared_ptr<PCM> pcm, bool keepPCM) ALSound::ALSound(ALAudio* al, uint buffer, const std::shared_ptr<PCM>& pcm, bool keepPCM)
: al(al), buffer(buffer) : al(al), buffer(buffer)
{ {
duration = pcm->getDuration(); duration = pcm->getDuration();
@ -36,7 +37,7 @@ std::unique_ptr<Speaker> ALSound::newInstance(int priority, int channel) const {
} }
ALStream::ALStream(ALAudio* al, std::shared_ptr<PCMStream> source, bool keepSource) ALStream::ALStream(ALAudio* al, std::shared_ptr<PCMStream> source, bool keepSource)
: al(al), source(source), keepSource(keepSource) { : al(al), source(std::move(source)), keepSource(keepSource) {
} }
ALStream::~ALStream() { ALStream::~ALStream() {
@ -457,7 +458,7 @@ std::vector<std::string> ALAudio::getAvailableDevices() const {
const char* ptr = devices; const char* ptr = devices;
do { do {
devicesVec.push_back(std::string(ptr)); devicesVec.emplace_back(ptr);
ptr += devicesVec.back().size() + 1; ptr += devicesVec.back().size() + 1;
} }
while (ptr[0]); while (ptr[0]);

View File

@ -29,7 +29,7 @@ namespace audio {
std::shared_ptr<PCM> pcm; std::shared_ptr<PCM> pcm;
duration_t duration; duration_t duration;
public: public:
ALSound(ALAudio* al, uint buffer, std::shared_ptr<PCM> pcm, bool keepPCM); ALSound(ALAudio* al, uint buffer, const std::shared_ptr<PCM>& pcm, bool keepPCM);
~ALSound(); ~ALSound();
duration_t getDuration() const override { duration_t getDuration() const override {

View File

@ -2,7 +2,7 @@
using namespace audio; using namespace audio;
NoSound::NoSound(std::shared_ptr<PCM> pcm, bool keepPCM) { NoSound::NoSound(const std::shared_ptr<PCM>& pcm, bool keepPCM) {
duration = pcm->getDuration(); duration = pcm->getDuration();
if (keepPCM) { if (keepPCM) {
this->pcm = pcm; this->pcm = pcm;

View File

@ -8,7 +8,7 @@ namespace audio {
std::shared_ptr<PCM> pcm; std::shared_ptr<PCM> pcm;
duration_t duration; duration_t duration;
public: public:
NoSound(std::shared_ptr<PCM> pcm, bool keepPCM); NoSound(const std::shared_ptr<PCM>& pcm, bool keepPCM);
~NoSound() {} ~NoSound() {}
duration_t getDuration() const override { duration_t getDuration() const override {
@ -28,7 +28,7 @@ namespace audio {
std::shared_ptr<PCMStream> source; std::shared_ptr<PCMStream> source;
duration_t duration; duration_t duration;
public: public:
NoStream(std::shared_ptr<PCMStream> source, bool keepSource) { NoStream(const std::shared_ptr<PCMStream>& source, bool keepSource) {
duration = source->getTotalDuration(); duration = source->getTotalDuration();
if (keepSource) { if (keepSource) {
this->source = source; this->source = source;

View File

@ -8,6 +8,7 @@
#include <iostream> #include <iostream>
#include <stdexcept> #include <stdexcept>
#include <utility>
namespace audio { namespace audio {
static speakerid_t nextId = 1; static speakerid_t nextId = 1;
@ -19,7 +20,7 @@ namespace audio {
using 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 { float Channel::getVolume() const {
@ -175,7 +176,7 @@ std::unique_ptr<Sound> audio::load_sound(const fs::path& file, bool keepPCM) {
} }
std::unique_ptr<Sound> audio::create_sound(std::shared_ptr<PCM> pcm, bool keepPCM) { std::unique_ptr<Sound> audio::create_sound(std::shared_ptr<PCM> pcm, bool keepPCM) {
return backend->createSound(pcm, keepPCM); return backend->createSound(std::move(pcm), keepPCM);
} }
std::unique_ptr<PCMStream> audio::open_PCM_stream(const fs::path& file) { std::unique_ptr<PCMStream> audio::open_PCM_stream(const fs::path& file) {
@ -204,7 +205,7 @@ std::unique_ptr<Stream> audio::open_stream(const fs::path& file, bool keepSource
} }
std::unique_ptr<Stream> audio::open_stream(std::shared_ptr<PCMStream> stream, bool keepSource) { std::unique_ptr<Stream> audio::open_stream(std::shared_ptr<PCMStream> 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( speakerid_t audio::play(
std::shared_ptr<Stream> stream, const std::shared_ptr<Stream>& stream,
glm::vec3 position, glm::vec3 position,
bool relative, bool relative,
float volume, float volume,

View File

@ -437,7 +437,7 @@ namespace audio {
/// @param channel channel index /// @param channel channel index
/// @return speaker id or 0 /// @return speaker id or 0
speakerid_t play( speakerid_t play(
std::shared_ptr<Stream> stream, const std::shared_ptr<Stream>& stream,
glm::vec3 position, glm::vec3 position,
bool relative, bool relative,
float volume, float volume,

View File

@ -8,29 +8,30 @@
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
#include <utility>
namespace fs = std::filesystem; namespace fs = std::filesystem;
void GLSLExtension::setVersion(std::string version) { void GLSLExtension::setVersion(std::string version) {
this->version = version; this->version = std::move(version);
} }
void GLSLExtension::setPaths(const ResPaths* paths) { void GLSLExtension::setPaths(const ResPaths* paths) {
this->paths = 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"); fs::path file = paths->find("shaders/lib/"+name+".glsl");
std::string source = files::read_string(file); std::string source = files::read_string(file);
addHeader(name, source); addHeader(name, source);
} }
void GLSLExtension::addHeader(std::string name, std::string source) { void GLSLExtension::addHeader(const std::string& name, std::string source) {
headers[name] = source; headers[name] = std::move(source);
} }
void GLSLExtension::define(std::string name, std::string value) { void GLSLExtension::define(const std::string& name, std::string value) {
defines[name] = value; defines[name] = std::move(value);
} }
const std::string& GLSLExtension::getHeader(const std::string& name) const { 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; 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); auto found = defines.find(name);
if (found == defines.end()) { if (found == defines.end()) {
return ""; throw std::runtime_error("name '"+name+"' is not defined");
} }
return found->second; return found->second;
} }
@ -57,7 +58,7 @@ bool GLSLExtension::hasHeader(const std::string& name) const {
return headers.find(name) != headers.end(); return headers.find(name) != headers.end();
} }
void GLSLExtension::undefine(std::string name) { void GLSLExtension::undefine(const std::string& name) {
if (hasDefine(name)) { if (hasDefine(name)) {
defines.erase(name); defines.erase(name);
} }
@ -66,7 +67,7 @@ void GLSLExtension::undefine(std::string name) {
inline std::runtime_error parsing_error( inline std::runtime_error parsing_error(
const fs::path& file, const fs::path& file,
uint linenum, uint linenum,
const std::string message) { const std::string& message) {
return std::runtime_error("file "+file.string()+": "+message+ return std::runtime_error("file "+file.string()+": "+message+
" at line "+std::to_string(linenum)); " at line "+std::to_string(linenum));
} }
@ -74,7 +75,7 @@ inline std::runtime_error parsing_error(
inline void parsing_warning( inline void parsing_warning(
const fs::path& file, const fs::path& file,
uint linenum, const uint linenum, const
std::string message) { std::string& message) {
std::cerr << "file "+file.string()+": warning: "+message+ std::cerr << "file "+file.string()+": warning: "+message+
" at line "+std::to_string(linenum) << std::endl; " 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"; 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; std::stringstream ss;
size_t pos = 0; size_t pos = 0;
uint linenum = 1; uint linenum = 1;

View File

@ -14,22 +14,22 @@ class GLSLExtension {
std::string version = "330 core"; std::string version = "330 core";
const ResPaths* paths = nullptr; const ResPaths* paths = nullptr;
void loadHeader(std::string name); void loadHeader(const std::string& name);
public: public:
void setPaths(const ResPaths* paths); void setPaths(const ResPaths* paths);
void setVersion(std::string version); void setVersion(std::string version);
void define(std::string name, std::string value); void define(const std::string& name, std::string value);
void undefine(std::string name); void undefine(const std::string& name);
void addHeader(std::string name, std::string source); void addHeader(const std::string& name, std::string source);
const std::string& getHeader(const std::string& name) const; 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 hasHeader(const std::string& name) const;
bool hasDefine(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::filesystem::path& file,
const std::string& source const std::string& source
); );

View File

@ -15,7 +15,7 @@ inline double power(double base, int64_t power) {
} }
parsing_error::parsing_error( parsing_error::parsing_error(
std::string message, const std::string& message,
std::string_view filename, std::string_view filename,
std::string_view source, std::string_view source,
uint pos, uint pos,
@ -332,6 +332,6 @@ std::string BasicParser::parseString(char quote, bool closeRequired) {
return ss.str(); 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); return parsing_error(message, filename, source, pos, line, linestart);
} }

View File

@ -60,7 +60,7 @@ public:
uint linestart; uint linestart;
parsing_error( parsing_error(
std::string message, const std::string& message,
std::string_view filename, std::string_view filename,
std::string_view source, std::string_view source,
uint pos, uint pos,
@ -92,7 +92,7 @@ protected:
dynamic::Value parseNumber(int sign); dynamic::Value parseNumber(int sign);
std::string parseString(char chr, bool closeRequired=true); std::string parseString(char chr, bool closeRequired=true);
parsing_error error(std::string message); parsing_error error(const std::string& message);
public: public:
std::string_view readUntil(char c); std::string_view readUntil(char c);

View File

@ -80,7 +80,7 @@ class OggStream : public PCMStream {
size_t totalSamples = 0; size_t totalSamples = 0;
bool seekable; bool seekable;
public: public:
OggStream(OggVorbis_File vf) : vf(std::move(vf)) { OggStream(OggVorbis_File vf) : vf(vf) {
vorbis_info* info = ov_info(&vf, -1); vorbis_info* info = ov_info(&vf, -1);
channels = info->channels; channels = info->channels;
sampleRate = info->rate; sampleRate = info->rate;
@ -158,5 +158,5 @@ std::unique_ptr<PCMStream> ogg::create_stream(const fs::path& file) {
if ((code = ov_fopen(file.u8string().c_str(), &vf))) { if ((code = ov_fopen(file.u8string().c_str(), &vf))) {
throw std::runtime_error("vorbis: "+vorbis_error_message(code)); throw std::runtime_error("vorbis: "+vorbis_error_message(code));
} }
return std::make_unique<OggStream>(std::move(vf)); return std::make_unique<OggStream>(vf);
} }

View File

@ -5,12 +5,13 @@
#include <charconv> #include <charconv>
#include <stdexcept> #include <stdexcept>
#include <sstream> #include <sstream>
#include <utility>
using namespace xml; using namespace xml;
Attribute::Attribute(std::string name, std::string text) Attribute::Attribute(std::string name, std::string text)
: name(name), : name(std::move(name)),
text(text) { text(std::move(text)) {
} }
const std::string& Attribute::getName() const { 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); 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); attrs[name] = Attribute(name, text);
} }
@ -119,7 +120,7 @@ const std::string& Node::getTag() const {
return tag; 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); auto found = attrs.find(name);
if (found == attrs.end()) { if (found == attrs.end()) {
throw std::runtime_error("element <"+tag+" ...> missing attribute "+name); 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; 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); auto found = attrs.find(name);
if (found == attrs.end()) { if (found == attrs.end()) {
return Attribute(name, def); return Attribute(name, def);
@ -157,11 +158,11 @@ const xmlelements_map& Node::getAttributes() const {
} }
Document::Document(std::string version, std::string encoding) Document::Document(std::string version, std::string encoding)
: version(version), : version(std::move(version)),
encoding(encoding) { encoding(std::move(encoding)) {
} }
void Document::setRoot(xmlelement element) { void Document::setRoot(const xmlelement &element) {
this->root = element; this->root = element;
} }
@ -336,7 +337,7 @@ xmldocument Parser::parse() {
return document; 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); Parser parser(filename, source);
return parser.parse(); return parser.parse();
} }
@ -357,7 +358,7 @@ inline void newline(
static void stringifyElement( static void stringifyElement(
std::stringstream& ss, std::stringstream& ss,
const xmlelement element, const xmlelement& element,
bool nice, bool nice,
const std::string& indentStr, const std::string& indentStr,
int indent int indent
@ -414,7 +415,7 @@ static void stringifyElement(
} }
std::string xml::stringify( std::string xml::stringify(
const xmldocument document, const xmldocument& document,
bool nice, bool nice,
const std::string& indentStr const std::string& indentStr
) { ) {

View File

@ -46,12 +46,12 @@ namespace xml {
Node(std::string tag); Node(std::string tag);
/// @brief Add sub-element /// @brief Add sub-element
void add(xmlelement element); void add(const xmlelement& element);
/// @brief Set attribute value. Creates attribute if does not exists /// @brief Set attribute value. Creates attribute if does not exists
/// @param name attribute name /// @param name attribute name
/// @param text attribute value /// @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 /// @brief Get element tag
const std::string& getTag() const; const std::string& getTag() const;
@ -68,14 +68,14 @@ namespace xml {
/// @param name attribute name /// @param name attribute name
/// @throws std::runtime_error if element has no attribute /// @throws std::runtime_error if element has no attribute
/// @return xmlattribute - {name, value} /// @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 /// @brief Get attribute by name
/// @param name attribute name /// @param name attribute name
/// @param def default value will be returned wrapped in xmlattribute /// @param def default value will be returned wrapped in xmlattribute
/// if element has no attribute /// if element has no attribute
/// @return xmlattribute - {name, value} or {name, def} if not found*/ /// @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 /// @brief Check if element has attribute
/// @param name attribute name /// @param name attribute name
@ -101,7 +101,7 @@ namespace xml {
public: public:
Document(std::string version, std::string encoding); Document(std::string version, std::string encoding);
void setRoot(xmlelement element); void setRoot(const xmlelement &element);
xmlelement getRoot() const; xmlelement getRoot() const;
const std::string& getVersion() const; const std::string& getVersion() const;
@ -129,7 +129,7 @@ namespace xml {
/// @param indentStr indentation characters sequence (default - 4 spaces) /// @param indentStr indentation characters sequence (default - 4 spaces)
/// @return XML string /// @return XML string
extern std::string stringify( extern std::string stringify(
const xmldocument document, const xmldocument& document,
bool nice=true, bool nice=true,
const std::string& indentStr=" " const std::string& indentStr=" "
); );
@ -138,7 +138,7 @@ namespace xml {
/// @param filename file name will be shown in error messages /// @param filename file name will be shown in error messages
/// @param source xml source code string /// @param source xml source code string
/// @return xml document /// @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_ #endif // CODERS_XML_HPP_

View File

@ -7,7 +7,7 @@
#include <string> #include <string>
inline constexpr int ENGINE_VERSION_MAJOR = 0; inline constexpr int ENGINE_VERSION_MAJOR = 0;
inline constexpr int ENGINE_VERSION_MINOR = 21; inline constexpr int ENGINE_VERSION_MINOR = 22;
#ifdef NDEBUG #ifdef NDEBUG
inline constexpr bool ENGINE_DEBUG_BUILD = false; 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; inline constexpr bool ENGINE_DEBUG_BUILD = true;
#endif // NDEBUG #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 blockid_t BLOCK_AIR = 0;
inline constexpr itemid_t ITEM_EMPTY = 0; inline constexpr itemid_t ITEM_EMPTY = 0;

View File

@ -3,6 +3,7 @@
#include <memory> #include <memory>
#include <stdexcept> #include <stdexcept>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <utility>
#include "../voxels/Block.hpp" #include "../voxels/Block.hpp"
#include "../items/ItemDef.hpp" #include "../items/ItemDef.hpp"
@ -13,8 +14,8 @@
ContentIndices::ContentIndices( ContentIndices::ContentIndices(
std::vector<Block*> blockDefs, std::vector<Block*> blockDefs,
std::vector<ItemDef*> itemDefs std::vector<ItemDef*> itemDefs
) : blockDefs(blockDefs), ) : blockDefs(std::move(blockDefs)),
itemDefs(itemDefs) itemDefs(std::move(itemDefs))
{} {}
Content::Content( Content::Content(
@ -35,7 +36,7 @@ Content::Content(
Content::~Content() { Content::~Content() {
} }
Block* Content::findBlock(std::string id) const { Block* Content::findBlock(const std::string& id) const {
auto found = blockDefs.find(id); auto found = blockDefs.find(id);
if (found == blockDefs.end()) { if (found == blockDefs.end()) {
return nullptr; return nullptr;
@ -43,7 +44,7 @@ Block* Content::findBlock(std::string id) const {
return found->second.get(); return found->second.get();
} }
Block& Content::requireBlock(std::string id) const { Block& Content::requireBlock(const std::string& id) const {
auto found = blockDefs.find(id); auto found = blockDefs.find(id);
if (found == blockDefs.end()) { if (found == blockDefs.end()) {
throw std::runtime_error("missing block "+id); throw std::runtime_error("missing block "+id);
@ -51,7 +52,7 @@ Block& Content::requireBlock(std::string id) const {
return *found->second; return *found->second;
} }
ItemDef* Content::findItem(std::string id) const { ItemDef* Content::findItem(const std::string& id) const {
auto found = itemDefs.find(id); auto found = itemDefs.find(id);
if (found == itemDefs.end()) { if (found == itemDefs.end()) {
return nullptr; return nullptr;
@ -59,7 +60,7 @@ ItemDef* Content::findItem(std::string id) const {
return found->second.get(); return found->second.get();
} }
ItemDef& Content::requireItem(std::string id) const { ItemDef& Content::requireItem(const std::string& id) const {
auto found = itemDefs.find(id); auto found = itemDefs.find(id);
if (found == itemDefs.end()) { if (found == itemDefs.end()) {
throw std::runtime_error("missing item "+id); throw std::runtime_error("missing item "+id);
@ -67,7 +68,7 @@ ItemDef& Content::requireItem(std::string id) const {
return *found->second; 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); auto found = blockMaterials.find(id);
if (found == blockMaterials.end()) { if (found == blockMaterials.end()) {
return nullptr; return nullptr;
@ -75,7 +76,7 @@ const BlockMaterial* Content::findBlockMaterial(std::string id) const {
return found->second.get(); 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); auto found = packs.find(id);
if (found == packs.end()) { if (found == packs.end()) {
return nullptr; return nullptr;

View File

@ -107,15 +107,15 @@ public:
return indices.get(); return indices.get();
} }
Block* findBlock(std::string id) const; Block* findBlock(const std::string& id) const;
Block& requireBlock(std::string id) const; Block& requireBlock(const std::string& id) const;
ItemDef* findItem(std::string id) const; ItemDef* findItem(const std::string& id) const;
ItemDef& requireItem(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<std::string, std::unique_ptr<BlockMaterial>>& getBlockMaterials() const; const std::unordered_map<std::string, std::unique_ptr<BlockMaterial>>& getBlockMaterials() const;
const std::unordered_map<std::string, std::unique_ptr<ContentPackRuntime>>& getPacks() const; const std::unordered_map<std::string, std::unique_ptr<ContentPackRuntime>>& getPacks() const;

View File

@ -6,7 +6,7 @@ void ContentBuilder::add(std::unique_ptr<ContentPackRuntime> pack) {
packs[pack->getId()] = std::move(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); auto found = blockDefs.find(id);
if (found != blockDefs.end()) { if (found != blockDefs.end()) {
return *found->second; return *found->second;
@ -17,7 +17,7 @@ Block& ContentBuilder::createBlock(std::string id) {
return *blockDefs[id]; return *blockDefs[id];
} }
ItemDef& ContentBuilder::createItem(std::string id) { ItemDef& ContentBuilder::createItem(const std::string& id) {
auto found = itemDefs.find(id); auto found = itemDefs.find(id);
if (found != itemDefs.end()) { if (found != itemDefs.end()) {
return *found->second; return *found->second;
@ -28,21 +28,21 @@ ItemDef& ContentBuilder::createItem(std::string id) {
return *itemDefs[id]; return *itemDefs[id];
} }
BlockMaterial& ContentBuilder::createBlockMaterial(std::string id) { BlockMaterial& ContentBuilder::createBlockMaterial(const std::string& id) {
blockMaterials[id] = std::make_unique<BlockMaterial>(); blockMaterials[id] = std::make_unique<BlockMaterial>();
auto& material = *blockMaterials[id]; auto& material = *blockMaterials[id];
material.name = id; material.name = id;
return material; return material;
} }
void ContentBuilder::checkIdentifier(std::string id) { void ContentBuilder::checkIdentifier(const std::string& id) {
contenttype result; contenttype result;
if (((result = checkContentType(id)) != contenttype::none)) { if (((result = checkContentType(id)) != contenttype::none)) {
throw namereuse_error("name "+id+" is already used", result); 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()) { if (blockDefs.find(id) != blockDefs.end()) {
return contenttype::block; return contenttype::block;
} }
@ -62,6 +62,7 @@ std::unique_ptr<Content> ContentBuilder::build() {
def.rt.id = blockDefsIndices.size(); def.rt.id = blockDefsIndices.size();
def.rt.emissive = *reinterpret_cast<uint32_t*>(def.emission); def.rt.emissive = *reinterpret_cast<uint32_t*>(def.emission);
def.rt.solid = def.model == BlockModel::block; 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) { if (def.rotatable) {
for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) { for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) {

View File

@ -24,12 +24,12 @@ public:
void add(std::unique_ptr<ContentPackRuntime> pack); void add(std::unique_ptr<ContentPackRuntime> pack);
Block& createBlock(std::string id); Block& createBlock(const std::string& id);
ItemDef& createItem(std::string id); ItemDef& createItem(const std::string& id);
BlockMaterial& createBlockMaterial(std::string id); BlockMaterial& createBlockMaterial(const std::string& id);
void checkIdentifier(std::string id); void checkIdentifier(const std::string& id);
contenttype checkContentType(std::string id); contenttype checkContentType(const std::string& id);
std::unique_ptr<Content> build(); std::unique_ptr<Content> build();
}; };

View File

@ -19,7 +19,7 @@ ContentLUT::ContentLUT(const Content* content, size_t blocksCount, size_t itemsC
blockNames.push_back(indices->getBlockDef(i)->name); blockNames.push_back(indices->getBlockDef(i)->name);
} }
for (size_t i = indices->countBlockDefs(); i < blocksCount; i++) { for (size_t i = indices->countBlockDefs(); i < blocksCount; i++) {
blockNames.push_back(""); blockNames.emplace_back("");
} }
for (size_t i = 0; i < itemsCount; i++) { 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); itemNames.push_back(indices->getItemDef(i)->name);
} }
for (size_t i = indices->countItemDefs(); i < itemsCount; i++) { for (size_t i = indices->countItemDefs(); i < itemsCount; i++) {
itemNames.push_back(""); itemNames.emplace_back();
} }
} }

View File

@ -7,6 +7,7 @@
#include "../constants.hpp" #include "../constants.hpp"
#include <string> #include <string>
#include <utility>
#include <vector> #include <vector>
#include <filesystem> #include <filesystem>
@ -44,7 +45,7 @@ public:
inline void setBlock(blockid_t index, std::string name, blockid_t id) { inline void setBlock(blockid_t index, std::string name, blockid_t id) {
blocks[index] = id; blocks[index] = id;
blockNames[index] = name; blockNames[index] = std::move(name);
if (id == BLOCK_VOID) { if (id == BLOCK_VOID) {
missingContent = true; missingContent = true;
} else if (index != id) { } else if (index != id) {
@ -62,7 +63,7 @@ public:
inline void setItem(itemid_t index, std::string name, itemid_t id) { inline void setItem(itemid_t index, std::string name, itemid_t id) {
items[index] = id; items[index] = id;
itemNames[index] = name; itemNames[index] = std::move(name);
if (id == ITEM_VOID) { if (id == ITEM_VOID) {
missingContent = true; missingContent = true;
} else if (index != id) { } else if (index != id) {

View File

@ -28,15 +28,15 @@ ContentLoader::ContentLoader(ContentPack* pack) : pack(pack) {
} }
bool ContentLoader::fixPackIndices( bool ContentLoader::fixPackIndices(
fs::path folder, const fs::path& folder,
dynamic::Map* indicesRoot, dynamic::Map* indicesRoot,
std::string contentSection const std::string& contentSection
) { ) {
std::vector<std::string> detected; std::vector<std::string> detected;
std::vector<std::string> indexed; std::vector<std::string> indexed;
if (fs::is_directory(folder)) { if (fs::is_directory(folder)) {
for (auto entry : fs::directory_iterator(folder)) { for (const auto& entry : fs::directory_iterator(folder)) {
fs::path file = entry.path(); const fs::path& file = entry.path();
if (fs::is_regular_file(file) && file.extension() == ".json") { if (fs::is_regular_file(file) && file.extension() == ".json") {
std::string name = file.stem().string(); std::string name = file.stem().string();
if (name[0] == '_') if (name[0] == '_')
@ -46,8 +46,8 @@ bool ContentLoader::fixPackIndices(
std::string space = file.stem().string(); std::string space = file.stem().string();
if (space[0] == '_') if (space[0] == '_')
continue; continue;
for (auto entry : fs::directory_iterator(file)) { for (const auto& entry : fs::directory_iterator(file)) {
fs::path file = entry.path(); const fs::path& file = entry.path();
if (fs::is_regular_file(file) && file.extension() == ".json") { if (fs::is_regular_file(file) && file.extension() == ".json") {
std::string name = file.stem().string(); std::string name = file.stem().string();
if (name[0] == '_') 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); auto root = files::read_json(file);
root->str("caption", def.caption); root->str("caption", def.caption);
@ -137,16 +137,14 @@ void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) {
def.model = BlockModel::custom; def.model = BlockModel::custom;
if (root->has("model-primitives")) { if (root->has("model-primitives")) {
loadCustomBlockModel(def, root->map("model-primitives")); loadCustomBlockModel(def, root->map("model-primitives"));
} } else {
else { logger.error() << name << ": no 'model-primitives' found";
std::cerr << "ERROR occured while block "
<< name << " parsed: no \"model-primitives\" found" << std::endl;
} }
} }
else if (model == "X") def.model = BlockModel::xsprite; else if (model == "X") def.model = BlockModel::xsprite;
else if (model == "none") def.model = BlockModel::none; else if (model == "none") def.model = BlockModel::none;
else { else {
std::cerr << "unknown model " << model << std::endl; logger.error() << "unknown model " << model;
def.model = BlockModel::none; def.model = BlockModel::none;
} }
@ -156,12 +154,12 @@ void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) {
std::string profile = "none"; std::string profile = "none";
root->str("rotation", profile); root->str("rotation", profile);
def.rotatable = profile != "none"; def.rotatable = profile != "none";
if (profile == "pipe") { if (profile == BlockRotProfile::PIPE_NAME) {
def.rotations = BlockRotProfile::PIPE; def.rotations = BlockRotProfile::PIPE;
} else if (profile == "pane") { } else if (profile == BlockRotProfile::PANE_NAME) {
def.rotations = BlockRotProfile::PANE; def.rotations = BlockRotProfile::PANE;
} else if (profile != "none") { } else if (profile != "none") {
std::cerr << "unknown rotation profile " << profile << std::endl; logger.error() << "unknown rotation profile " << profile;
def.rotatable = false; 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 = glm::vec3(box->num(3), box->num(4), box->num(5));
def.hitboxes[i].b += def.hitboxes[i].a; 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 { } else {
boxarr = root->list("hitbox"); def.hitboxes = { AABB() };
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() };
}
} }
// block light emission [r, g, b] where r,g,b in range [0..15] // block light emission [r, g, b] where r,g,b in range [0..15]
auto emissionarr = root->list("emission"); if (auto emissionarr = root->list("emission")) {
if (emissionarr) {
def.emission[0] = emissionarr->num(0); def.emission[0] = emissionarr->num(0);
def.emission[1] = emissionarr->num(1); def.emission[1] = emissionarr->num(1);
def.emission[2] = emissionarr->num(2); 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 // primitive properties
root->flag("obstacle", def.obstacle); root->flag("obstacle", def.obstacle);
root->flag("replaceable", def.replaceable); root->flag("replaceable", def.replaceable);
@ -244,7 +250,7 @@ void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) {
} }
else else
for (uint j = 6; j < 12; j++) { 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 */ /* Parse tetragon to points */
auto tgonobj = modeltetragons->list(i); auto tgonobj = modeltetragons->list(i);
glm::vec3 p1(tgonobj->num(0), tgonobj->num(1), tgonobj->num(2)), glm::vec3 p1(tgonobj->num(0), tgonobj->num(1), tgonobj->num(2)),
xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)), xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)),
yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8)); yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8));
def.modelExtraPoints.push_back(p1); def.modelExtraPoints.push_back(p1);
def.modelExtraPoints.push_back(p1+xw); def.modelExtraPoints.push_back(p1+xw);
def.modelExtraPoints.push_back(p1+xw+yh); 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); auto root = files::read_json(file);
root->str("caption", def.caption); root->str("caption", def.caption);
@ -279,7 +285,7 @@ void ContentLoader::loadItem(ItemDef& def, std::string name, fs::path file) {
} else if (iconTypeStr == "sprite") { } else if (iconTypeStr == "sprite") {
def.iconType = item_icon_type::sprite; def.iconType = item_icon_type::sprite;
} else if (iconTypeStr.length()){ } 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("icon", def.icon);
root->str("placing-block", def.placingBlock); 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; auto folder = pack->folder;
fs::path configFile = folder/fs::path("blocks/"+name+".json"); 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; auto folder = pack->folder;
fs::path configFile = folder/fs::path("items/"+name+".json"); 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); auto root = files::read_json(file);
root->str("steps-sound", def.stepsSound); root->str("steps-sound", def.stepsSound);
root->str("place-sound", def.placeSound); root->str("place-sound", def.placeSound);
@ -394,8 +400,8 @@ void ContentLoader::load(ContentBuilder& builder) {
fs::path materialsDir = folder / fs::u8path("block_materials"); fs::path materialsDir = folder / fs::u8path("block_materials");
if (fs::is_directory(materialsDir)) { if (fs::is_directory(materialsDir)) {
for (auto entry : fs::directory_iterator(materialsDir)) { for (const auto& entry : fs::directory_iterator(materialsDir)) {
fs::path file = entry.path(); const fs::path& file = entry.path();
std::string name = pack->id+":"+file.stem().u8string(); std::string name = pack->id+":"+file.stem().u8string();
loadBlockMaterial(builder.createBlockMaterial(name), file); loadBlockMaterial(builder.createBlockMaterial(name), file);
} }

View File

@ -22,21 +22,21 @@ class ContentLoader {
const ContentPack* pack; const ContentPack* pack;
scriptenv env; 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 loadCustomBlockModel(Block& def, dynamic::Map* primitives);
void loadItem(ItemDef& def, std::string full, std::string name); void loadItem(ItemDef& def, const std::string& full, const std::string& name);
void loadBlockMaterial(BlockMaterial& def, fs::path file); void loadBlockMaterial(BlockMaterial& def, const fs::path& file);
public: public:
ContentLoader(ContentPack* pack); ContentLoader(ContentPack* pack);
bool fixPackIndices( bool fixPackIndices(
fs::path folder, const fs::path& folder,
dynamic::Map* indicesRoot, dynamic::Map* indicesRoot,
std::string contentSection const std::string& contentSection
); );
void fixPackIndices(); void fixPackIndices();
void loadBlock(Block& def, std::string name, fs::path file); void loadBlock(Block& def, const std::string& name, const fs::path& file);
void loadItem(ItemDef& def, std::string name, fs::path file); void loadItem(ItemDef& def, const std::string& name, const fs::path& file);
void load(ContentBuilder& builder); void load(ContentBuilder& builder);
}; };

View File

@ -2,6 +2,7 @@
#include <iostream> #include <iostream>
#include <algorithm> #include <algorithm>
#include <utility>
#include "../coders/json.hpp" #include "../coders/json.hpp"
#include "../files/files.hpp" #include "../files/files.hpp"
@ -21,8 +22,8 @@ const std::vector<std::string> ContentPack::RESERVED_NAMES = {
contentpack_error::contentpack_error( contentpack_error::contentpack_error(
std::string packId, std::string packId,
fs::path folder, fs::path folder,
std::string message) const std::string& message)
: std::runtime_error(message), packId(packId), folder(folder) { : std::runtime_error(message), packId(std::move(packId)), folder(std::move(folder)) {
} }
std::string contentpack_error::getPackId() const { std::string contentpack_error::getPackId() const {
@ -36,7 +37,7 @@ fs::path ContentPack::getContentFile() const {
return folder/fs::path(CONTENT_FILENAME); 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)); 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)); auto root = files::read_json(folder/fs::path(PACKAGE_FILENAME));
ContentPack pack; ContentPack pack;
root->str("id", pack.id); root->str("id", pack.id);
@ -89,14 +90,14 @@ ContentPack ContentPack::read(fs::path folder) {
} }
void ContentPack::scanFolder( void ContentPack::scanFolder(
fs::path folder, const fs::path& folder,
std::vector<ContentPack>& packs std::vector<ContentPack>& packs
) { ) {
if (!fs::is_directory(folder)) { if (!fs::is_directory(folder)) {
return; return;
} }
for (auto entry : fs::directory_iterator(folder)) { for (const auto& entry : fs::directory_iterator(folder)) {
fs::path folder = entry.path(); const fs::path& folder = entry.path();
if (!fs::is_directory(folder)) if (!fs::is_directory(folder))
continue; continue;
if (!is_pack(folder)) if (!is_pack(folder))
@ -112,7 +113,7 @@ void ContentPack::scanFolder(
} }
} }
std::vector<std::string> ContentPack::worldPacksList(fs::path folder) { std::vector<std::string> ContentPack::worldPacksList(const fs::path& folder) {
fs::path listfile = folder / fs::path("packs.list"); fs::path listfile = folder / fs::path("packs.list");
if (!fs::is_regular_file(listfile)) { if (!fs::is_regular_file(listfile)) {
std::cerr << "warning: packs.list not found (will be created)"; std::cerr << "warning: packs.list not found (will be created)";
@ -122,7 +123,7 @@ std::vector<std::string> ContentPack::worldPacksList(fs::path folder) {
return files::read_list(listfile); 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); fs::path folder = worldDir / fs::path("content") / fs::path(name);
if (fs::is_directory(folder)) { if (fs::is_directory(folder)) {
return folder; return folder;
@ -141,7 +142,7 @@ fs::path ContentPack::findPack(const EnginePaths* paths, fs::path worldDir, std:
ContentPackRuntime::ContentPackRuntime( ContentPackRuntime::ContentPackRuntime(
ContentPack info, ContentPack info,
scriptenv env scriptenv env
) : info(info), env(std::move(env)) ) : info(std::move(info)), env(std::move(env))
{ {
} }

View File

@ -16,7 +16,7 @@ class contentpack_error : public std::runtime_error {
std::string packId; std::string packId;
fs::path folder; fs::path folder;
public: 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; std::string getPackId() const;
fs::path getFolder() const; fs::path getFolder() const;
@ -52,20 +52,20 @@ struct ContentPack {
static const fs::path ITEMS_FOLDER; static const fs::path ITEMS_FOLDER;
static const std::vector<std::string> RESERVED_NAMES; static const std::vector<std::string> RESERVED_NAMES;
static bool is_pack(fs::path folder); static bool is_pack(const fs::path& folder);
static ContentPack read(fs::path folder); static ContentPack read(const fs::path& folder);
static void scanFolder( static void scanFolder(
fs::path folder, const fs::path& folder,
std::vector<ContentPack>& packs std::vector<ContentPack>& packs
); );
static std::vector<std::string> worldPacksList(fs::path folder); static std::vector<std::string> worldPacksList(const fs::path& folder);
static fs::path findPack( static fs::path findPack(
const EnginePaths* paths, const EnginePaths* paths,
fs::path worldDir, const fs::path& worldDir,
std::string name const std::string& name
); );
}; };

View File

@ -110,7 +110,7 @@ void Map::str(const std::string& key, std::string& dst) const {
dst = get(key, dst); 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); auto found = values.find(key);
if (found == values.end()) if (found == values.end())
return def; return def;
@ -213,7 +213,7 @@ void Map::flag(const std::string& key, bool& dst) const {
dst = get(key, dst); 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; values[key] = value;
return *this; return *this;
} }
@ -222,13 +222,13 @@ void Map::remove(const std::string& key) {
values.erase(key); values.erase(key);
} }
List& Map::putList(std::string key) { List& Map::putList(const std::string& key) {
auto arr = create_list(); auto arr = create_list();
put(key, arr); put(key, arr);
return *arr; return *arr;
} }
Map& Map::putMap(std::string key) { Map& Map::putMap(const std::string& key) {
auto obj = create_map(); auto obj = create_map();
put(key, obj); put(key, obj);
return *obj; return *obj;

View File

@ -101,7 +101,7 @@ namespace dynamic {
return get(key, T()); 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; number_t get(const std::string& key, double def) const;
integer_t get(const std::string& key, integer_t def) const; integer_t get(const std::string& key, integer_t def) const;
bool get(const std::string& key, bool 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) { Map& put(std::string key, const char* value) {
return put(key, Value(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); void remove(const std::string& key);
List& putList(std::string key); List& putList(const std::string& key);
Map& putMap(std::string key); Map& putMap(const std::string& key);
bool has(const std::string& key) const; bool has(const std::string& key) const;
size_t size() const; size_t size() const;

View File

@ -4,6 +4,7 @@
#include <iomanip> #include <iomanip>
#include <chrono> #include <chrono>
#include <iostream> #include <iostream>
#include <utility>
using namespace debug; using namespace debug;
@ -16,10 +17,10 @@ LogMessage::~LogMessage() {
logger->log(level, ss.str()); 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; using namespace std::chrono;
std::stringstream ss; std::stringstream ss;
@ -72,5 +73,5 @@ void Logger::flush() {
} }
void Logger::log(LogLevel level, std::string message) { void Logger::log(LogLevel level, std::string message) {
log(level, name, message); log(level, name, std::move(message));
} }

View File

@ -35,7 +35,7 @@ namespace debug {
std::string name; 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: public:
static void init(const std::string& filename); static void init(const std::string& filename);
static void flush(); static void flush();

View File

@ -42,6 +42,7 @@
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <unordered_set> #include <unordered_set>
#include <functional> #include <functional>
#include <utility>
static debug::Logger logger("engine"); static debug::Logger logger("engine");
@ -65,6 +66,7 @@ Engine::Engine(EngineSettings& settings, SettingsHandler& settingsHandler, Engin
: settings(settings), settingsHandler(settingsHandler), paths(paths), : settings(settings), settingsHandler(settingsHandler), paths(paths),
interpreter(std::make_unique<cmd::CommandsInterpreter>()) interpreter(std::make_unique<cmd::CommandsInterpreter>())
{ {
paths->prepare();
loadSettings(); loadSettings();
controller = std::make_unique<EngineController>(this); controller = std::make_unique<EngineController>(this);
@ -115,14 +117,6 @@ void Engine::loadControls() {
logger.info() << "loading controls"; logger.info() << "loading controls";
std::string text = files::read_string(controls_file); std::string text = files::read_string(controls_file);
Events::loadBindings(controls_file.u8string(), text); 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> screen) { void Engine::setScreen(std::shared_ptr<Screen> screen) {
audio::reset_channel(audio::get_channel_index("regular")); audio::reset_channel(audio::get_channel_index("regular"));
audio::reset_channel(audio::get_channel_index("ambient")); audio::reset_channel(audio::get_channel_index("ambient"));
this->screen = screen; this->screen = std::move(screen);
} }
void Engine::setLanguage(std::string locale) { 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)); gui->getMenu()->setPageLoader(menus::create_page_loader(this));
} }
@ -391,7 +385,7 @@ std::shared_ptr<Screen> Engine::getScreen() {
return screen; return screen;
} }
void Engine::postRunnable(runnable callback) { void Engine::postRunnable(const runnable& callback) {
std::lock_guard<std::recursive_mutex> lock(postRunnablesMutex); std::lock_guard<std::recursive_mutex> lock(postRunnablesMutex);
postRunnables.push(callback); postRunnables.push(callback);
} }

View File

@ -137,7 +137,7 @@ public:
std::shared_ptr<Screen> getScreen(); std::shared_ptr<Screen> getScreen();
/// @brief Enqueue function call to the end of current frame in draw thread /// @brief Enqueue function call to the end of current frame in draw thread
void postRunnable(runnable callback); void postRunnable(const runnable& callback);
void saveScreenshot(); void saveScreenshot();

View File

@ -13,6 +13,7 @@
#include <memory> #include <memory>
#include <iostream> #include <iostream>
#include <stdexcept> #include <stdexcept>
#include <utility>
namespace fs = std::filesystem; namespace fs = std::filesystem;
@ -22,7 +23,7 @@ class ConverterWorker : public util::Worker<convert_task, int> {
std::shared_ptr<WorldConverter> converter; std::shared_ptr<WorldConverter> converter;
public: public:
ConverterWorker(std::shared_ptr<WorldConverter> converter) ConverterWorker(std::shared_ptr<WorldConverter> converter)
: converter(converter) {} : converter(std::move(converter)) {}
int operator()(const std::shared_ptr<convert_task>& task) override { int operator()(const std::shared_ptr<convert_task>& task) override {
converter->convert(*task); converter->convert(*task);
@ -31,11 +32,11 @@ public:
}; };
WorldConverter::WorldConverter( WorldConverter::WorldConverter(
fs::path folder, const fs::path& folder,
const Content* content, const Content* content,
std::shared_ptr<ContentLUT> lut std::shared_ptr<ContentLUT> lut
) : wfile(std::make_unique<WorldFiles>(folder)), ) : wfile(std::make_unique<WorldFiles>(folder)),
lut(lut), lut(std::move(lut)),
content(content) content(content)
{ {
fs::path regionsFolder = wfile->getRegions().getRegionsFolder(REGION_LAYER_VOXELS); fs::path regionsFolder = wfile->getRegions().getRegionsFolder(REGION_LAYER_VOXELS);
@ -44,7 +45,7 @@ WorldConverter::WorldConverter(
return; return;
} }
tasks.push(convert_task {convert_task_type::player, wfile->getPlayerFile()}); 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()}); tasks.push(convert_task {convert_task_type::region, file.path()});
} }
} }
@ -53,10 +54,10 @@ WorldConverter::~WorldConverter() {
} }
std::shared_ptr<Task> WorldConverter::startTask( std::shared_ptr<Task> WorldConverter::startTask(
fs::path folder, const fs::path& folder,
const Content* content, const Content* content,
std::shared_ptr<ContentLUT> lut, const std::shared_ptr<ContentLUT>& lut,
runnable onDone, const runnable& onDone,
bool multithreading bool multithreading
) { ) {
auto converter = std::make_shared<WorldConverter>(folder, content, lut); auto converter = std::make_shared<WorldConverter>(folder, content, lut);
@ -85,7 +86,7 @@ std::shared_ptr<Task> WorldConverter::startTask(
return pool; return pool;
} }
void WorldConverter::convertRegion(fs::path file) const { void WorldConverter::convertRegion(const fs::path& file) const {
int x, z; int x, z;
std::string name = file.stem().string(); std::string name = file.stem().string();
if (!WorldRegions::parseRegionFilename(name, x, z)) { 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(); logger.info() << "converting player " << file.u8string();
auto map = files::read_json(file); auto map = files::read_json(file);
Player::convert(map.get(), lut.get()); Player::convert(map.get(), lut.get());
files::write_json(file, map.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)) if (!fs::is_regular_file(task.file))
return; return;
@ -134,7 +135,7 @@ void WorldConverter::convertNext() {
} }
void WorldConverter::setOnComplete(runnable callback) { void WorldConverter::setOnComplete(runnable callback) {
this->onComplete = callback; this->onComplete = std::move(callback);
} }
void WorldConverter::update() { void WorldConverter::update() {

View File

@ -32,17 +32,17 @@ class WorldConverter : public Task {
runnable onComplete; runnable onComplete;
uint tasksDone = 0; uint tasksDone = 0;
void convertPlayer(fs::path file) const; void convertPlayer(const fs::path& file) const;
void convertRegion(fs::path file) const; void convertRegion(const fs::path& file) const;
public: public:
WorldConverter( WorldConverter(
fs::path folder, const fs::path& folder,
const Content* content, const Content* content,
std::shared_ptr<ContentLUT> lut std::shared_ptr<ContentLUT> lut
); );
~WorldConverter(); ~WorldConverter();
void convert(convert_task task) const; void convert(const convert_task& task) const;
void convertNext(); void convertNext();
void setOnComplete(runnable callback); void setOnComplete(runnable callback);
void write(); void write();
@ -55,10 +55,10 @@ public:
uint getWorkDone() const override; uint getWorkDone() const override;
static std::shared_ptr<Task> startTask( static std::shared_ptr<Task> startTask(
fs::path folder, const fs::path& folder,
const Content* content, const Content* content,
std::shared_ptr<ContentLUT> lut, const std::shared_ptr<ContentLUT>& lut,
runnable onDone, const runnable& onDone,
bool multithreading bool multithreading
); );
}; };

View File

@ -27,13 +27,14 @@
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
#include <cstring> #include <cstring>
#include <utility>
#define WORLD_FORMAT_MAGIC ".VOXWLD" #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::WorldFiles(const fs::path& directory, const DebugSettings& settings)
: WorldFiles(directory) : WorldFiles(directory)
{ {
generatorTestMode = settings.generatorTestMode.get(); generatorTestMode = settings.generatorTestMode.get();

View File

@ -41,8 +41,8 @@ class WorldFiles {
void writeWorldInfo(const World* world); void writeWorldInfo(const World* world);
void writeIndices(const ContentIndices* indices); void writeIndices(const ContentIndices* indices);
public: public:
WorldFiles(fs::path directory); WorldFiles(const fs::path &directory);
WorldFiles(fs::path directory, const DebugSettings& settings); WorldFiles(const fs::path &directory, const DebugSettings& settings);
~WorldFiles(); ~WorldFiles();
fs::path getPlayerFile() const; fs::path getPlayerFile() const;

View File

@ -8,10 +8,11 @@
#include "../util/data_io.hpp" #include "../util/data_io.hpp"
#include <cstring> #include <cstring>
#include <utility>
#define REGION_FORMAT_MAGIC ".VOXREG" #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) if (file.length() < REGION_HEADER_SIZE)
throw std::runtime_error("incomplete region file header"); throw std::runtime_error("incomplete region file header");
char header[REGION_HEADER_SIZE]; char header[REGION_HEADER_SIZE];
@ -49,17 +50,12 @@ std::unique_ptr<ubyte[]> regfile::read(int index, uint32_t& length) {
return data; return data;
} }
WorldRegion::WorldRegion() { WorldRegion::WorldRegion()
chunksData = new ubyte*[REGION_CHUNKS_COUNT]{}; : chunksData(std::make_unique<std::unique_ptr<ubyte[]>[]>(REGION_CHUNKS_COUNT)),
sizes = new uint32_t[REGION_CHUNKS_COUNT]{}; sizes(std::make_unique<uint32_t[]>(REGION_CHUNKS_COUNT))
} {}
WorldRegion::~WorldRegion() { WorldRegion::~WorldRegion() {
for (uint i = 0; i < REGION_CHUNKS_COUNT; i++) {
delete[] chunksData[i];
}
delete[] sizes;
delete[] chunksData;
} }
void WorldRegion::setUnsaved(bool unsaved) { void WorldRegion::setUnsaved(bool unsaved) {
@ -69,30 +65,29 @@ bool WorldRegion::isUnsaved() const {
return unsaved; return unsaved;
} }
ubyte** WorldRegion::getChunks() const { std::unique_ptr<ubyte[]>* WorldRegion::getChunks() const {
return chunksData; return chunksData.get();
} }
uint32_t* WorldRegion::getSizes() const { uint32_t* WorldRegion::getSizes() const {
return sizes; return sizes.get();
} }
void WorldRegion::put(uint x, uint z, ubyte* data, uint32_t size) { void WorldRegion::put(uint x, uint z, ubyte* data, uint32_t size) {
size_t chunk_index = z * REGION_SIZE + x; size_t chunk_index = z * REGION_SIZE + x;
delete[] chunksData[chunk_index]; chunksData[chunk_index].reset(data);
chunksData[chunk_index] = data;
sizes[chunk_index] = size; sizes[chunk_index] = size;
} }
ubyte* WorldRegion::getChunkData(uint x, uint z) { 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) { uint WorldRegion::getChunkDataSize(uint x, uint z) {
return sizes[z * REGION_SIZE + x]; 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++) { for (uint i = 0; i < sizeof(layers)/sizeof(RegionsLayer); i++) {
layers[i].layer = i; layers[i].layer = i;
} }
@ -108,19 +103,21 @@ WorldRegion* WorldRegions::getRegion(int x, int z, int layer) {
RegionsLayer& regions = layers[layer]; RegionsLayer& regions = layers[layer];
std::lock_guard lock(regions.mutex); std::lock_guard lock(regions.mutex);
auto found = regions.regions.find(glm::ivec2(x, z)); auto found = regions.regions.find(glm::ivec2(x, z));
if (found == regions.regions.end()) if (found == regions.regions.end()) {
return nullptr; return nullptr;
}
return found->second.get(); return found->second.get();
} }
WorldRegion* WorldRegions::getOrCreateRegion(int x, int z, int layer) { WorldRegion* WorldRegions::getOrCreateRegion(int x, int z, int layer) {
WorldRegion* region = getRegion(x, z, layer); if (auto region = getRegion(x, z, layer)) {
if (region == nullptr) { return region;
RegionsLayer& regions = layers[layer];
std::lock_guard lock(regions.mutex);
region = new WorldRegion();
regions.regions[glm::ivec2(x, z)].reset(region);
} }
RegionsLayer& regions = layers[layer];
std::lock_guard lock(regions.mutex);
auto region_ptr = std::make_unique<WorldRegion>();
auto region = region_ptr.get();
regions.regions[{x, z}] = std::move(region_ptr);
return region; return region;
} }
@ -152,10 +149,7 @@ inline void calc_reg_coords(
} }
std::unique_ptr<ubyte[]> WorldRegions::readChunkData( std::unique_ptr<ubyte[]> WorldRegions::readChunkData(
int x, int x, int z, uint32_t& length, regfile* rfile
int z,
uint32_t& length,
regfile* rfile
){ ){
int regionX, regionZ, localX, localZ; int regionX, regionZ, localX, localZ;
calc_reg_coords(x, z, regionX, regionZ, localX, localZ); calc_reg_coords(x, z, regionX, regionZ, localX, localZ);
@ -165,14 +159,14 @@ std::unique_ptr<ubyte[]> WorldRegions::readChunkData(
/// @brief Read missing chunks data (null pointers) from region file /// @brief Read missing chunks data (null pointers) from region file
void WorldRegions::fetchChunks(WorldRegion* region, int x, int z, regfile* 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(); uint32_t* sizes = region->getSizes();
for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) { for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) {
int chunk_x = (i % REGION_SIZE) + x * REGION_SIZE; int chunk_x = (i % REGION_SIZE) + x * REGION_SIZE;
int chunk_z = (i / REGION_SIZE) + z * REGION_SIZE; int chunk_z = (i / REGION_SIZE) + z * REGION_SIZE;
if (chunks[i] == nullptr) { 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; return nullptr;
} }
std::shared_ptr<regfile> WorldRegions::useRegFile(glm::ivec3 coord) { regfile_ptr WorldRegions::useRegFile(glm::ivec3 coord) {
auto* file = openRegFiles[coord].get(); auto* file = openRegFiles[coord].get();
file->inUse = true; file->inUse = true;
return std::shared_ptr<regfile>(file, [this](regfile* ptr) { return regfile_ptr(file, &regFilesCv);
ptr->inUse = false;
regFilesCv.notify_one();
});
} }
void WorldRegions::closeRegFile(glm::ivec3 coord) { 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 // Marks regfile as used and unmarks when shared_ptr dies
std::shared_ptr<regfile> WorldRegions::getRegFile(glm::ivec3 coord, bool create) { regfile_ptr WorldRegions::getRegFile(glm::ivec3 coord, bool create) {
{ {
std::lock_guard lock(regFilesMutex); std::lock_guard lock(regFilesMutex);
const auto found = openRegFiles.find(coord); const auto found = openRegFiles.find(coord);
@ -237,7 +228,7 @@ std::shared_ptr<regfile> WorldRegions::getRegFile(glm::ivec3 coord, bool create)
return nullptr; return nullptr;
} }
std::shared_ptr<regfile> WorldRegions::createRegFile(glm::ivec3 coord) { regfile_ptr WorldRegions::createRegFile(glm::ivec3 coord) {
fs::path file = layers[coord[2]].folder/getRegionFilename(coord[0], coord[1]); fs::path file = layers[coord[2]].folder/getRegionFilename(coord[0], coord[1]);
if (!fs::exists(file)) { if (!fs::exists(file)) {
return nullptr; return nullptr;
@ -281,6 +272,7 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){
fetchChunks(entry, x, z, regfile.get()); fetchChunks(entry, x, z, regfile.get());
std::lock_guard lock(regFilesMutex); std::lock_guard lock(regFilesMutex);
regfile.reset();
closeRegFile(regcoord); closeRegFile(regcoord);
} }
@ -294,18 +286,18 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){
char intbuf[4]{}; char intbuf[4]{};
uint offsets[REGION_CHUNKS_COUNT]{}; uint offsets[REGION_CHUNKS_COUNT]{};
ubyte** region = entry->getChunks(); auto* region = entry->getChunks();
uint32_t* sizes = entry->getSizes(); uint32_t* sizes = entry->getSizes();
for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) { for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) {
ubyte* chunk = region[i]; ubyte* chunk = region[i].get();
if (chunk == nullptr){ if (chunk == nullptr){
offsets[i] = 0; offsets[i] = 0;
} else { } else {
offsets[i] = offset; offsets[i] = offset;
size_t compressedSize = sizes[i]; size_t compressedSize = sizes[i];
dataio::write_int32_big(compressedSize, (ubyte*)intbuf, 0); dataio::write_int32_big(compressedSize, reinterpret_cast<ubyte*>(intbuf), 0);
offset += 4 + compressedSize; offset += 4 + compressedSize;
file.write(intbuf, 4); 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++) { 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<ubyte*>(intbuf), 0);
file.write(intbuf, 4); file.write(intbuf, 4);
} }
} }
@ -357,15 +349,20 @@ static std::unique_ptr<ubyte[]> write_inventories(Chunk* chunk, uint& datasize)
auto datavec = builder.data(); auto datavec = builder.data();
datasize = builder.size(); datasize = builder.size();
auto data = std::make_unique<ubyte[]>(datasize); auto data = std::make_unique<ubyte[]>(datasize);
for (uint i = 0; i < datasize; i++) { std::memcpy(data.get(), datavec, datasize);
data[i] = datavec[i];
}
return data; 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){ void WorldRegions::put(Chunk* chunk){
assert(chunk != nullptr); 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; int regionX, regionZ, localX, localZ;
calc_reg_coords(chunk->x, chunk->z, regionX, regionZ, localX, localZ); calc_reg_coords(chunk->x, chunk->z, regionX, regionZ, localX, localZ);
@ -408,11 +405,12 @@ std::unique_ptr<light_t[]> WorldRegions::getLights(int x, int z) {
} }
chunk_inventories_map WorldRegions::fetchInventories(int x, int z) { chunk_inventories_map WorldRegions::fetchInventories(int x, int z) {
chunk_inventories_map inventories; chunk_inventories_map meta;
uint32_t bytesSize; uint32_t bytesSize;
const ubyte* data = getData(x, z, REGION_LAYER_INVENTORIES, bytesSize); const ubyte* data = getData(x, z, REGION_LAYER_INVENTORIES, bytesSize);
if (data == nullptr) if (data == nullptr) {
return inventories; return meta;
}
ByteReader reader(data, bytesSize); ByteReader reader(data, bytesSize);
int count = reader.getInt32(); int count = reader.getInt32();
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
@ -422,12 +420,12 @@ chunk_inventories_map WorldRegions::fetchInventories(int x, int z) {
reader.skip(size); reader.skip(size);
auto inv = std::make_shared<Inventory>(0, 0); auto inv = std::make_shared<Inventory>(0, 0);
inv->deserialize(map.get()); 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)) { if (getRegion(x, z, REGION_LAYER_VOXELS)) {
throw std::runtime_error("not implemented for in-memory regions"); 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) { bool WorldRegions::parseRegionFilename(const std::string& name, int& x, int& z) {
size_t sep = name.find('_'); 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; return false;
}
try { try {
x = std::stoi(name.substr(0, sep)); x = std::stoi(name.substr(0, sep));
z = std::stoi(name.substr(sep+1)); z = std::stoi(name.substr(sep+1));

View File

@ -38,8 +38,8 @@ public:
}; };
class WorldRegion { class WorldRegion {
ubyte** chunksData; std::unique_ptr<std::unique_ptr<ubyte[]>[]> chunksData;
uint32_t* sizes; std::unique_ptr<uint32_t[]> sizes;
bool unsaved = false; bool unsaved = false;
public: public:
WorldRegion(); WorldRegion();
@ -52,7 +52,7 @@ public:
void setUnsaved(bool unsaved); void setUnsaved(bool unsaved);
bool isUnsaved() const; bool isUnsaved() const;
ubyte** getChunks() const; std::unique_ptr<ubyte[]>* getChunks() const;
uint32_t* getSizes() const; uint32_t* getSizes() const;
}; };
@ -77,6 +77,43 @@ struct RegionsLayer {
std::mutex mutex; 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 { class WorldRegions {
fs::path directory; fs::path directory;
std::unordered_map<glm::ivec3, std::unique_ptr<regfile>> openRegFiles; std::unordered_map<glm::ivec3, std::unique_ptr<regfile>> openRegFiles;
@ -110,10 +147,10 @@ class WorldRegions {
ubyte* getData(int x, int z, int layer, uint32_t& size); ubyte* getData(int x, int z, int layer, uint32_t& size);
std::shared_ptr<regfile> getRegFile(glm::ivec3 coord, bool create=true); regfile_ptr getRegFile(glm::ivec3 coord, bool create=true);
void closeRegFile(glm::ivec3 coord); void closeRegFile(glm::ivec3 coord);
std::shared_ptr<regfile> useRegFile(glm::ivec3 coord); regfile_ptr useRegFile(glm::ivec3 coord);
std::shared_ptr<regfile> createRegFile(glm::ivec3 coord); regfile_ptr createRegFile(glm::ivec3 coord);
fs::path getRegionFilename(int x, int y) const; fs::path getRegionFilename(int x, int y) const;
@ -128,7 +165,7 @@ public:
bool generatorTestMode = false; bool generatorTestMode = false;
bool doWriteLights = true; bool doWriteLights = true;
WorldRegions(fs::path directory); WorldRegions(const fs::path& directory);
WorldRegions(const WorldRegions&) = delete; WorldRegions(const WorldRegions&) = delete;
~WorldRegions(); ~WorldRegions();
@ -148,7 +185,7 @@ public:
std::unique_ptr<light_t[]> getLights(int x, int z); std::unique_ptr<light_t[]> getLights(int x, int z);
chunk_inventories_map fetchInventories(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; fs::path getRegionsFolder(int layer) const;

View File

@ -4,15 +4,24 @@
#include <sstream> #include <sstream>
#include <filesystem> #include <filesystem>
#include <algorithm> #include <algorithm>
#include <utility>
#include "../util/stringutil.hpp" #include "../util/stringutil.hpp"
#include "../typedefs.hpp" #include "../typedefs.hpp"
#include "WorldFiles.hpp" #include "WorldFiles.hpp"
const fs::path SCREENSHOTS_FOLDER {"screenshots"}; const fs::path SCREENSHOTS_FOLDER {"screenshots"};
const fs::path CONTENT_FOLDER {"content"};
const fs::path CONTROLS_FILE {"controls.toml"}; const fs::path CONTROLS_FILE {"controls.toml"};
const fs::path SETTINGS_FILE {"settings.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 { fs::path EnginePaths::getUserfiles() const {
return userfiles; return userfiles;
} }
@ -21,7 +30,7 @@ fs::path EnginePaths::getResources() const {
return resources; 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); fs::path folder = userfiles/fs::path(SCREENSHOTS_FOLDER);
if (!fs::is_directory(folder)) { if (!fs::is_directory(folder)) {
fs::create_directory(folder); fs::create_directory(folder);
@ -60,10 +69,6 @@ fs::path EnginePaths::getControlsFile() {
return userfiles/fs::path(CONTROLS_FILE); return userfiles/fs::path(CONTROLS_FILE);
} }
fs::path EnginePaths::getControlsFileOld() {
return userfiles/fs::path("controls.json");
}
fs::path EnginePaths::getSettingsFile() { fs::path EnginePaths::getSettingsFile() {
return userfiles/fs::path(SETTINGS_FILE); return userfiles/fs::path(SETTINGS_FILE);
} }
@ -75,11 +80,11 @@ std::vector<fs::path> EnginePaths::scanForWorlds() {
if (!fs::is_directory(folder)) if (!fs::is_directory(folder))
return folders; return folders;
for (auto entry : fs::directory_iterator(folder)) { for (const auto& entry : fs::directory_iterator(folder)) {
if (!entry.is_directory()) { if (!entry.is_directory()) {
continue; continue;
} }
fs::path worldFolder = entry.path(); const fs::path& worldFolder = entry.path();
fs::path worldFile = worldFolder/fs::u8path(WorldFiles::WORLD_FILE); fs::path worldFile = worldFolder/fs::u8path(WorldFiles::WORLD_FILE);
if (!fs::is_regular_file(worldFile)) { if (!fs::is_regular_file(worldFile)) {
continue; continue;
@ -94,20 +99,20 @@ std::vector<fs::path> EnginePaths::scanForWorlds() {
return folders; return folders;
} }
bool EnginePaths::isWorldNameUsed(std::string name) { bool EnginePaths::isWorldNameUsed(const std::string& name) {
return fs::exists(EnginePaths::getWorldsFolder()/fs::u8path(name)); return fs::exists(EnginePaths::getWorldsFolder()/fs::u8path(name));
} }
void EnginePaths::setUserfiles(fs::path folder) { void EnginePaths::setUserfiles(fs::path folder) {
this->userfiles = folder; this->userfiles = std::move(folder);
} }
void EnginePaths::setResources(fs::path folder) { void EnginePaths::setResources(fs::path folder) {
this->resources = folder; this->resources = std::move(folder);
} }
void EnginePaths::setWorldFolder(fs::path folder) { void EnginePaths::setWorldFolder(fs::path folder) {
this->worldFolder = folder; this->worldFolder = std::move(folder);
} }
void EnginePaths::setContentPacks(std::vector<ContentPack>* contentPacks) { void EnginePaths::setContentPacks(std::vector<ContentPack>* contentPacks) {
@ -139,7 +144,7 @@ static fs::path toCanonic(fs::path path) {
return 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(':'); size_t separator = path.find(':');
if (separator == std::string::npos) { if (separator == std::string::npos) {
throw files_access_error("no entry point specified"); 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<PathsRoot> roots) ResPaths::ResPaths(fs::path mainRoot, std::vector<PathsRoot> roots)
: mainRoot(mainRoot), roots(roots) { : mainRoot(std::move(mainRoot)), roots(std::move(roots)) {
} }
fs::path ResPaths::find(const std::string& filename) const { fs::path ResPaths::find(const std::string& filename) const {

View File

@ -21,17 +21,18 @@ class EnginePaths {
fs::path worldFolder; fs::path worldFolder;
std::vector<ContentPack>* contentPacks = nullptr; std::vector<ContentPack>* contentPacks = nullptr;
public: public:
void prepare();
fs::path getUserfiles() const; fs::path getUserfiles() const;
fs::path getResources() const; fs::path getResources() const;
fs::path getScreenshotFile(std::string ext); fs::path getScreenshotFile(const std::string& ext);
fs::path getWorldsFolder(); fs::path getWorldsFolder();
fs::path getWorldFolder(); fs::path getWorldFolder();
fs::path getWorldFolder(const std::string& name); fs::path getWorldFolder(const std::string& name);
fs::path getControlsFile(); fs::path getControlsFile();
fs::path getControlsFileOld(); // TODO: remove in 0.22
fs::path getSettingsFile(); fs::path getSettingsFile();
bool isWorldNameUsed(std::string name); bool isWorldNameUsed(const std::string& name);
void setUserfiles(fs::path folder); void setUserfiles(fs::path folder);
void setResources(fs::path folder); void setResources(fs::path folder);
@ -40,7 +41,7 @@ public:
std::vector<fs::path> scanForWorlds(); std::vector<fs::path> scanForWorlds();
fs::path resolve(std::string path, bool throwErr=true); fs::path resolve(const std::string& path, bool throwErr=true);
}; };
struct PathsRoot { struct PathsRoot {

View File

@ -15,7 +15,7 @@
namespace fs = std::filesystem; 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) { : file(filename, std::ios::binary | std::ios::ate) {
if (!file) { if (!file) {
throw std::runtime_error("could not to open file "+filename.string()); 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); 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); std::ofstream output(filename, std::ios::binary);
if (!output.is_open()) if (!output.is_open())
return false; return false;
@ -45,7 +45,7 @@ bool files::write_bytes(fs::path filename, const ubyte* data, size_t size) {
return true; 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); std::ofstream output(filename, std::ios::binary | std::ios::app);
if (!output.is_open()) if (!output.is_open())
return 0; return 0;
@ -55,7 +55,7 @@ uint files::append_bytes(fs::path filename, const ubyte* data, size_t size) {
return position; 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); std::ifstream output(filename, std::ios::binary);
if (!output.is_open()) if (!output.is_open())
return false; return false;
@ -64,7 +64,7 @@ bool files::read(fs::path filename, char* data, size_t size) {
return true; return true;
} }
std::unique_ptr<ubyte[]> files::read_bytes(fs::path filename, size_t& length) { std::unique_ptr<ubyte[]> files::read_bytes(const fs::path& filename, size_t& length) {
std::ifstream input(filename, std::ios::binary); std::ifstream input(filename, std::ios::binary);
if (!input.is_open()) if (!input.is_open())
return nullptr; return nullptr;
@ -78,7 +78,7 @@ std::unique_ptr<ubyte[]> files::read_bytes(fs::path filename, size_t& length) {
return data; return data;
} }
std::string files::read_string(fs::path filename) { std::string files::read_string(const fs::path& filename) {
size_t size; size_t size;
std::unique_ptr<ubyte[]> bytes (read_bytes(filename, size)); std::unique_ptr<ubyte[]> bytes (read_bytes(filename, size));
if (bytes == nullptr) { if (bytes == nullptr) {
@ -88,7 +88,7 @@ std::string files::read_string(fs::path filename) {
return std::string((const char*)bytes.get(), size); 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); std::ofstream file(filename);
if (!file) { if (!file) {
return false; return false;
@ -97,16 +97,16 @@ bool files::write_string(fs::path filename, const std::string content) {
return true; 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, " ")); 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); auto bytes = json::to_binary(obj, compression);
return files::write_bytes(filename, bytes.data(), bytes.size()); return files::write_bytes(filename, bytes.data(), bytes.size());
} }
std::shared_ptr<dynamic::Map> files::read_json(fs::path filename) { std::shared_ptr<dynamic::Map> files::read_json(const fs::path& filename) {
std::string text = files::read_string(filename); std::string text = files::read_string(filename);
try { try {
return json::parse(filename.string(), text);; return json::parse(filename.string(), text);;
@ -116,17 +116,17 @@ std::shared_ptr<dynamic::Map> files::read_json(fs::path filename) {
} }
} }
std::shared_ptr<dynamic::Map> files::read_binary_json(fs::path file) { std::shared_ptr<dynamic::Map> files::read_binary_json(const fs::path& file) {
size_t size; size_t size;
std::unique_ptr<ubyte[]> bytes (files::read_bytes(file, size)); std::unique_ptr<ubyte[]> bytes (files::read_bytes(file, size));
return json::from_binary(bytes.get(), size); return json::from_binary(bytes.get(), size);
} }
std::shared_ptr<dynamic::Map> files::read_toml(fs::path file) { std::shared_ptr<dynamic::Map> files::read_toml(const fs::path& file) {
return toml::parse(file.u8string(), files::read_string(file)); return toml::parse(file.u8string(), files::read_string(file));
} }
std::vector<std::string> files::read_list(fs::path filename) { std::vector<std::string> files::read_list(const fs::path& filename) {
std::ifstream file(filename); std::ifstream file(filename);
if (!file) { if (!file) {
throw std::runtime_error("could not to open file "+filename.u8string()); throw std::runtime_error("could not to open file "+filename.u8string());

View File

@ -20,7 +20,7 @@ namespace files {
std::ifstream file; std::ifstream file;
size_t filelength; size_t filelength;
public: public:
rafile(fs::path filename); rafile(const fs::path& filename);
void seekg(std::streampos pos); void seekg(std::streampos pos);
void read(char* buffer, std::streamsize size); void read(char* buffer, std::streamsize size);
@ -31,40 +31,40 @@ namespace files {
/// @param file target file /// @param file target file
/// @param data data bytes array /// @param data data bytes array
/// @param size size of 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 /// @brief Append bytes array to the file without any extra data
/// @param file target file /// @param file target file
/// @param data data bytes array /// @param data data bytes array
/// @param size size of 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 /// @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 /// @brief Write dynamic data to the JSON file
/// @param nice if true, human readable format will be used, otherwise minimal /// @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 /// @brief Write dynamic data to the binary JSON file
/// (see src/coders/binary_json_spec.md) /// (see src/coders/binary_json_spec.md)
/// @param compressed use gzip compression /// @param compressed use gzip compression
bool write_binary_json( bool write_binary_json(
fs::path filename, const fs::path& filename,
const dynamic::Map* obj, const dynamic::Map* obj,
bool compressed=false bool compressed=false
); );
bool read(fs::path, char* data, size_t size); bool read(const fs::path&, char* data, size_t size);
std::unique_ptr<ubyte[]> read_bytes(fs::path, size_t& length); std::unique_ptr<ubyte[]> read_bytes(const fs::path&, size_t& length);
std::string read_string(fs::path filename); std::string read_string(const fs::path& filename);
/// @brief Read JSON or BJSON file /// @brief Read JSON or BJSON file
/// @param file *.json or *.bjson file /// @param file *.json or *.bjson file
std::shared_ptr<dynamic::Map> read_json(fs::path file); std::shared_ptr<dynamic::Map> read_json(const fs::path& file);
std::shared_ptr<dynamic::Map> read_binary_json(fs::path file); std::shared_ptr<dynamic::Map> read_binary_json(const fs::path& file);
std::shared_ptr<dynamic::Map> read_toml(fs::path file); std::shared_ptr<dynamic::Map> read_toml(const fs::path& file);
std::vector<std::string> read_list(fs::path file); std::vector<std::string> read_list(const fs::path& file);
} }
#endif /* FILES_FILES_HPP_ */ #endif /* FILES_FILES_HPP_ */

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