Merge pull request #281 from Pugemon/pvs-fix
reformat, conversion, and PVS studio fixes
This commit is contained in:
commit
0f527c196c
@ -9,7 +9,7 @@ IndentCaseLabels: true
|
||||
NamespaceIndentation: All
|
||||
FixNamespaceComments: false
|
||||
SpaceBeforeCpp11BracedList: true
|
||||
AllowShortFunctionsOnASingleLine: false
|
||||
AllowShortFunctionsOnASingleLine: None
|
||||
IndentAccessModifiers: false
|
||||
AccessModifierOffset: -4
|
||||
EmptyLineBeforeAccessModifier: Never
|
||||
|
||||
@ -1,29 +1,21 @@
|
||||
#ifndef ASSETS_ASSETS_HPP_
|
||||
#define ASSETS_ASSETS_HPP_
|
||||
|
||||
#include "../graphics/core/TextureAnimation.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <optional>
|
||||
#include <functional>
|
||||
#include <unordered_map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <typeindex>
|
||||
#include <typeinfo>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "../graphics/core/TextureAnimation.hpp"
|
||||
|
||||
class Assets;
|
||||
|
||||
enum class AssetType {
|
||||
TEXTURE,
|
||||
SHADER,
|
||||
FONT,
|
||||
ATLAS,
|
||||
LAYOUT,
|
||||
SOUND,
|
||||
MODEL
|
||||
};
|
||||
enum class AssetType { TEXTURE, SHADER, FONT, ATLAS, LAYOUT, SOUND, MODEL };
|
||||
|
||||
namespace assetload {
|
||||
/// @brief final work to do in the main thread
|
||||
@ -31,7 +23,7 @@ namespace assetload {
|
||||
|
||||
using setupfunc = std::function<void(const Assets*)>;
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
void assets_setup(const Assets*);
|
||||
|
||||
class error : public std::runtime_error {
|
||||
@ -39,12 +31,11 @@ namespace assetload {
|
||||
std::string filename;
|
||||
std::string reason;
|
||||
public:
|
||||
error(
|
||||
AssetType type, std::string filename, std::string reason
|
||||
) : std::runtime_error(filename + ": " + reason),
|
||||
type(type),
|
||||
filename(std::move(filename)),
|
||||
reason(std::move(reason)) {
|
||||
error(AssetType type, std::string filename, std::string reason)
|
||||
: std::runtime_error(filename + ": " + reason),
|
||||
type(type),
|
||||
filename(std::move(filename)),
|
||||
reason(std::move(reason)) {
|
||||
}
|
||||
|
||||
AssetType getAssetType() const {
|
||||
@ -75,12 +66,12 @@ public:
|
||||
const std::vector<TextureAnimation>& getAnimations();
|
||||
void store(const TextureAnimation& animation);
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
void store(std::unique_ptr<T> asset, const std::string& name) {
|
||||
assets[typeid(T)][name].reset(asset.release());
|
||||
}
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
T* get(const std::string& name) const {
|
||||
const auto& mapIter = assets.find(typeid(T));
|
||||
if (mapIter == assets.end()) {
|
||||
@ -94,7 +85,7 @@ public:
|
||||
return static_cast<T*>(found->second.get());
|
||||
}
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
std::optional<const assets_map*> getMap() const {
|
||||
const auto& mapIter = assets.find(typeid(T));
|
||||
if (mapIter == assets.end()) {
|
||||
@ -114,7 +105,7 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
void assetload::assets_setup(const Assets* assets) {
|
||||
if (auto mapPtr = assets->getMap<T>()) {
|
||||
for (const auto& entry : **mapPtr) {
|
||||
@ -123,4 +114,4 @@ void assetload::assets_setup(const Assets* assets) {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // ASSETS_ASSETS_HPP_
|
||||
#endif // ASSETS_ASSETS_HPP_
|
||||
|
||||
@ -1,30 +1,29 @@
|
||||
#include "AssetsLoader.hpp"
|
||||
|
||||
#include "Assets.hpp"
|
||||
#include "assetload_funcs.hpp"
|
||||
#include "../util/ThreadPool.hpp"
|
||||
#include "../constants.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
#include "../coders/imageio.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../files/engine_paths.hpp"
|
||||
#include "../content/Content.hpp"
|
||||
#include "../content/ContentPack.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "../objects/rigging.hpp"
|
||||
#include "../graphics/core/Texture.hpp"
|
||||
#include "../logic/scripting/scripting.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "../coders/imageio.hpp"
|
||||
#include "../constants.hpp"
|
||||
#include "../content/Content.hpp"
|
||||
#include "../content/ContentPack.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
#include "../files/engine_paths.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../graphics/core/Texture.hpp"
|
||||
#include "../logic/scripting/scripting.hpp"
|
||||
#include "../objects/rigging.hpp"
|
||||
#include "../util/ThreadPool.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "Assets.hpp"
|
||||
#include "assetload_funcs.hpp"
|
||||
|
||||
static debug::Logger logger("assets-loader");
|
||||
|
||||
AssetsLoader::AssetsLoader(Assets* assets, const ResPaths* paths)
|
||||
: assets(assets), paths(paths)
|
||||
{
|
||||
AssetsLoader::AssetsLoader(Assets* assets, const ResPaths* paths)
|
||||
: assets(assets), paths(paths) {
|
||||
addLoader(AssetType::SHADER, assetload::shader);
|
||||
addLoader(AssetType::TEXTURE, assetload::texture);
|
||||
addLoader(AssetType::FONT, assetload::font);
|
||||
@ -38,8 +37,13 @@ void AssetsLoader::addLoader(AssetType tag, aloader_func func) {
|
||||
loaders[tag] = std::move(func);
|
||||
}
|
||||
|
||||
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, std::move(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, std::move(settings)});
|
||||
}
|
||||
|
||||
bool AssetsLoader::hasNext() const {
|
||||
@ -50,7 +54,7 @@ aloader_func AssetsLoader::getLoader(AssetType tag) {
|
||||
auto found = loaders.find(tag);
|
||||
if (found == loaders.end()) {
|
||||
throw std::runtime_error(
|
||||
"unknown asset tag "+std::to_string(static_cast<int>(tag))
|
||||
"unknown asset tag " + std::to_string(static_cast<int>(tag))
|
||||
);
|
||||
}
|
||||
return found->second;
|
||||
@ -61,7 +65,8 @@ void AssetsLoader::loadNext() {
|
||||
logger.info() << "loading " << entry.filename << " as " << entry.alias;
|
||||
try {
|
||||
aloader_func loader = getLoader(entry.tag);
|
||||
auto postfunc = loader(this, paths, entry.filename, entry.alias, entry.config);
|
||||
auto postfunc =
|
||||
loader(this, paths, entry.filename, entry.alias, entry.config);
|
||||
postfunc(assets);
|
||||
entries.pop();
|
||||
} catch (std::runtime_error& err) {
|
||||
@ -74,16 +79,25 @@ void AssetsLoader::loadNext() {
|
||||
}
|
||||
}
|
||||
|
||||
void addLayouts(const scriptenv& env, const std::string& prefix, const fs::path& folder, AssetsLoader& loader) {
|
||||
void addLayouts(
|
||||
const scriptenv& env,
|
||||
const std::string& prefix,
|
||||
const fs::path& folder,
|
||||
AssetsLoader& loader
|
||||
) {
|
||||
if (!fs::is_directory(folder)) {
|
||||
return;
|
||||
}
|
||||
for (auto& entry : fs::directory_iterator(folder)) {
|
||||
const fs::path& file = entry.path();
|
||||
if (file.extension().u8string() != ".xml")
|
||||
continue;
|
||||
std::string name = prefix+":"+file.stem().u8string();
|
||||
loader.add(AssetType::LAYOUT, file.u8string(), name, std::make_shared<LayoutCfg>(env));
|
||||
if (file.extension().u8string() != ".xml") continue;
|
||||
std::string name = prefix + ":" + file.stem().u8string();
|
||||
loader.add(
|
||||
AssetType::LAYOUT,
|
||||
file.u8string(),
|
||||
name,
|
||||
std::make_shared<LayoutCfg>(env)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -91,30 +105,35 @@ void AssetsLoader::tryAddSound(const std::string& name) {
|
||||
if (name.empty()) {
|
||||
return;
|
||||
}
|
||||
std::string file = SOUNDS_FOLDER+"/"+name;
|
||||
std::string file = SOUNDS_FOLDER + "/" + name;
|
||||
add(AssetType::SOUND, file, name);
|
||||
}
|
||||
|
||||
static std::string assets_def_folder(AssetType tag) {
|
||||
switch (tag) {
|
||||
case AssetType::FONT: return FONTS_FOLDER;
|
||||
case AssetType::SHADER: return SHADERS_FOLDER;
|
||||
case AssetType::TEXTURE: return TEXTURES_FOLDER;
|
||||
case AssetType::ATLAS: return TEXTURES_FOLDER;
|
||||
case AssetType::LAYOUT: return LAYOUTS_FOLDER;
|
||||
case AssetType::SOUND: return SOUNDS_FOLDER;
|
||||
case AssetType::MODEL: return MODELS_FOLDER;
|
||||
case AssetType::FONT:
|
||||
return FONTS_FOLDER;
|
||||
case AssetType::SHADER:
|
||||
return SHADERS_FOLDER;
|
||||
case AssetType::TEXTURE:
|
||||
return TEXTURES_FOLDER;
|
||||
case AssetType::ATLAS:
|
||||
return TEXTURES_FOLDER;
|
||||
case AssetType::LAYOUT:
|
||||
return LAYOUTS_FOLDER;
|
||||
case AssetType::SOUND:
|
||||
return SOUNDS_FOLDER;
|
||||
case AssetType::MODEL:
|
||||
return MODELS_FOLDER;
|
||||
}
|
||||
return "<error>";
|
||||
}
|
||||
|
||||
void AssetsLoader::processPreload(
|
||||
AssetType tag,
|
||||
const std::string& name,
|
||||
dynamic::Map* map
|
||||
AssetType tag, const std::string& name, dynamic::Map* map
|
||||
) {
|
||||
std::string defFolder = assets_def_folder(tag);
|
||||
std::string path = defFolder+"/"+name;
|
||||
std::string path = defFolder + "/" + name;
|
||||
if (map == nullptr) {
|
||||
add(tag, path, name);
|
||||
return;
|
||||
@ -122,9 +141,10 @@ void AssetsLoader::processPreload(
|
||||
map->str("path", path);
|
||||
switch (tag) {
|
||||
case AssetType::SOUND:
|
||||
add(tag, path, name, std::make_shared<SoundCfg>(
|
||||
map->get("keep-pcm", false)
|
||||
));
|
||||
add(tag,
|
||||
path,
|
||||
name,
|
||||
std::make_shared<SoundCfg>(map->get("keep-pcm", false)));
|
||||
break;
|
||||
default:
|
||||
add(tag, path, name);
|
||||
@ -166,7 +186,7 @@ void AssetsLoader::processPreloadConfig(const fs::path& file) {
|
||||
}
|
||||
|
||||
void AssetsLoader::processPreloadConfigs(const Content* content) {
|
||||
auto preloadFile = paths->getMainRoot()/fs::path("preload.json");
|
||||
auto preloadFile = paths->getMainRoot() / fs::path("preload.json");
|
||||
if (fs::exists(preloadFile)) {
|
||||
processPreloadConfig(preloadFile);
|
||||
}
|
||||
@ -192,7 +212,12 @@ void AssetsLoader::addDefaults(AssetsLoader& loader, const Content* content) {
|
||||
loader.tryAddSound(material.breakSound);
|
||||
}
|
||||
|
||||
addLayouts(0, "core", loader.getPaths()->getMainRoot()/fs::path("layouts"), loader);
|
||||
addLayouts(
|
||||
0,
|
||||
"core",
|
||||
loader.getPaths()->getMainRoot() / fs::path("layouts"),
|
||||
loader
|
||||
);
|
||||
for (auto& entry : content->getPacks()) {
|
||||
auto pack = entry.second.get();
|
||||
auto& info = pack->getInfo();
|
||||
@ -205,7 +230,9 @@ void AssetsLoader::addDefaults(AssetsLoader& loader, const Content* content) {
|
||||
for (auto& bone : skeleton.getBones()) {
|
||||
auto& model = bone->model.name;
|
||||
if (!model.empty()) {
|
||||
loader.add(AssetType::MODEL, MODELS_FOLDER+"/"+model, model);
|
||||
loader.add(
|
||||
AssetType::MODEL, MODELS_FOLDER + "/" + model, model
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -227,8 +254,8 @@ bool AssetsLoader::loadExternalTexture(
|
||||
assets->store(Texture::from(image.get()), name);
|
||||
return true;
|
||||
} catch (const std::exception& err) {
|
||||
logger.error() << "error while loading external "
|
||||
<< path.u8string() << ": " << err.what();
|
||||
logger.error() << "error while loading external "
|
||||
<< path.u8string() << ": " << err.what();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -245,22 +272,26 @@ public:
|
||||
LoaderWorker(AssetsLoader* loader) : loader(loader) {
|
||||
}
|
||||
|
||||
assetload::postfunc operator()(const std::shared_ptr<aloader_entry>& entry) override {
|
||||
assetload::postfunc operator()(const std::shared_ptr<aloader_entry>& entry
|
||||
) override {
|
||||
aloader_func loadfunc = loader->getLoader(entry->tag);
|
||||
return loadfunc(loader, loader->getPaths(), entry->filename, entry->alias, entry->config);
|
||||
return loadfunc(
|
||||
loader,
|
||||
loader->getPaths(),
|
||||
entry->filename,
|
||||
entry->alias,
|
||||
entry->config
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
std::shared_ptr<Task> AssetsLoader::startTask(runnable onDone) {
|
||||
auto pool = std::make_shared<
|
||||
util::ThreadPool<aloader_entry, assetload::postfunc>
|
||||
>(
|
||||
"assets-loader-pool",
|
||||
[=](){return std::make_shared<LoaderWorker>(this);},
|
||||
[=](assetload::postfunc& func) {
|
||||
func(assets);
|
||||
}
|
||||
);
|
||||
auto pool =
|
||||
std::make_shared<util::ThreadPool<aloader_entry, assetload::postfunc>>(
|
||||
"assets-loader-pool",
|
||||
[=]() { return std::make_shared<LoaderWorker>(this); },
|
||||
[=](assetload::postfunc& func) { func(assets); }
|
||||
);
|
||||
pool->setOnComplete(std::move(onDone));
|
||||
while (!entries.empty()) {
|
||||
const aloader_entry& entry = entries.front();
|
||||
|
||||
@ -1,19 +1,19 @@
|
||||
#ifndef ASSETS_ASSETS_LOADER_HPP_
|
||||
#define ASSETS_ASSETS_LOADER_HPP_
|
||||
|
||||
#include "Assets.hpp"
|
||||
#include "../interfaces/Task.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../delegates.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "../delegates.hpp"
|
||||
#include "../interfaces/Task.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "Assets.hpp"
|
||||
|
||||
namespace dynamic {
|
||||
class Map;
|
||||
class List;
|
||||
@ -24,28 +24,27 @@ class AssetsLoader;
|
||||
class Content;
|
||||
|
||||
struct AssetCfg {
|
||||
virtual ~AssetCfg() {}
|
||||
virtual ~AssetCfg() {
|
||||
}
|
||||
};
|
||||
|
||||
struct LayoutCfg : AssetCfg {
|
||||
scriptenv env;
|
||||
|
||||
LayoutCfg(scriptenv env) : env(std::move(env)) {}
|
||||
LayoutCfg(scriptenv env) : env(std::move(env)) {
|
||||
}
|
||||
};
|
||||
|
||||
struct SoundCfg : AssetCfg {
|
||||
bool keepPCM;
|
||||
|
||||
SoundCfg(bool keepPCM) : keepPCM(keepPCM) {}
|
||||
|
||||
SoundCfg(bool keepPCM) : keepPCM(keepPCM) {
|
||||
}
|
||||
};
|
||||
|
||||
using aloader_func = std::function<assetload::postfunc(
|
||||
AssetsLoader*,
|
||||
const ResPaths*,
|
||||
const std::string&,
|
||||
const std::string&,
|
||||
std::shared_ptr<AssetCfg>)
|
||||
>;
|
||||
using aloader_func = std::function<
|
||||
assetload::
|
||||
postfunc(AssetsLoader*, const ResPaths*, const std::string&, const std::string&, std::shared_ptr<AssetCfg>)>;
|
||||
|
||||
struct aloader_entry {
|
||||
AssetType tag;
|
||||
@ -62,7 +61,9 @@ class AssetsLoader {
|
||||
|
||||
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 processPreloadConfig(const std::filesystem::path& file);
|
||||
void processPreloadConfigs(const Content* content);
|
||||
@ -76,12 +77,12 @@ public:
|
||||
/// @param alias internal asset name
|
||||
/// @param settings asset loading settings (based on asset type)
|
||||
void add(
|
||||
AssetType tag,
|
||||
AssetType tag,
|
||||
const std::string& filename,
|
||||
const std::string& alias,
|
||||
std::shared_ptr<AssetCfg> settings=nullptr
|
||||
std::shared_ptr<AssetCfg> settings = nullptr
|
||||
);
|
||||
|
||||
|
||||
bool hasNext() const;
|
||||
|
||||
/// @throws assetload::error
|
||||
@ -104,4 +105,4 @@ public:
|
||||
);
|
||||
};
|
||||
|
||||
#endif // ASSETS_ASSETS_LOADER_HPP_
|
||||
#endif // ASSETS_ASSETS_LOADER_HPP_
|
||||
|
||||
@ -1,30 +1,30 @@
|
||||
#include "assetload_funcs.hpp"
|
||||
|
||||
#include "Assets.hpp"
|
||||
#include "AssetsLoader.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "../audio/audio.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../files/engine_paths.hpp"
|
||||
#include "../coders/GLSLExtension.hpp"
|
||||
#include "../coders/commons.hpp"
|
||||
#include "../coders/imageio.hpp"
|
||||
#include "../coders/json.hpp"
|
||||
#include "../coders/obj.hpp"
|
||||
#include "../coders/GLSLExtension.hpp"
|
||||
#include "../graphics/core/Shader.hpp"
|
||||
#include "../graphics/core/Texture.hpp"
|
||||
#include "../graphics/core/ImageData.hpp"
|
||||
#include "../constants.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../files/engine_paths.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../frontend/UiDocument.hpp"
|
||||
#include "../graphics/core/Atlas.hpp"
|
||||
#include "../graphics/core/Font.hpp"
|
||||
#include "../graphics/core/ImageData.hpp"
|
||||
#include "../graphics/core/Model.hpp"
|
||||
#include "../graphics/core/Shader.hpp"
|
||||
#include "../graphics/core/Texture.hpp"
|
||||
#include "../graphics/core/TextureAnimation.hpp"
|
||||
#include "../objects/rigging.hpp"
|
||||
#include "../frontend/UiDocument.hpp"
|
||||
#include "../constants.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <filesystem>
|
||||
#include "Assets.hpp"
|
||||
#include "AssetsLoader.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
@ -37,43 +37,38 @@ static bool animation(
|
||||
Atlas* dstAtlas
|
||||
);
|
||||
|
||||
assetload::postfunc assetload::texture(
|
||||
AssetsLoader*,
|
||||
const ResPaths* paths,
|
||||
const std::string& filename,
|
||||
const std::string& name,
|
||||
const std::shared_ptr<AssetCfg>&
|
||||
) {
|
||||
std::shared_ptr<ImageData> image (
|
||||
imageio::read(paths->find(filename+".png").u8string()).release()
|
||||
assetload::postfunc assetload::
|
||||
texture(AssetsLoader*, const ResPaths* paths, const std::string& filename, const std::string& name, const std::shared_ptr<AssetCfg>&) {
|
||||
std::shared_ptr<ImageData> image(
|
||||
imageio::read(paths->find(filename + ".png").u8string()).release()
|
||||
);
|
||||
return [name, image](auto assets) {
|
||||
assets->store(Texture::from(image.get()), name);
|
||||
};
|
||||
}
|
||||
|
||||
assetload::postfunc assetload::shader(
|
||||
AssetsLoader*,
|
||||
const ResPaths* paths,
|
||||
const std::string& filename,
|
||||
const std::string& name,
|
||||
const std::shared_ptr<AssetCfg>&
|
||||
) {
|
||||
fs::path vertexFile = paths->find(filename+".glslv");
|
||||
fs::path fragmentFile = paths->find(filename+".glslf");
|
||||
assetload::postfunc assetload::
|
||||
shader(AssetsLoader*, const ResPaths* paths, const std::string& filename, const std::string& name, const std::shared_ptr<AssetCfg>&) {
|
||||
fs::path vertexFile = paths->find(filename + ".glslv");
|
||||
fs::path fragmentFile = paths->find(filename + ".glslf");
|
||||
|
||||
std::string vertexSource = files::read_string(vertexFile);
|
||||
std::string fragmentSource = files::read_string(fragmentFile);
|
||||
|
||||
vertexSource = Shader::preprocessor->process(vertexFile, vertexSource);
|
||||
fragmentSource = Shader::preprocessor->process(fragmentFile, fragmentSource);
|
||||
fragmentSource =
|
||||
Shader::preprocessor->process(fragmentFile, fragmentSource);
|
||||
|
||||
return [=](auto assets) {
|
||||
assets->store(Shader::create(
|
||||
vertexFile.u8string(),
|
||||
fragmentFile.u8string(),
|
||||
vertexSource, fragmentSource
|
||||
), name);
|
||||
assets->store(
|
||||
Shader::create(
|
||||
vertexFile.u8string(),
|
||||
fragmentFile.u8string(),
|
||||
vertexSource,
|
||||
fragmentSource
|
||||
),
|
||||
name
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@ -89,19 +84,12 @@ static bool append_atlas(AtlasBuilder& atlas, const fs::path& file) {
|
||||
return true;
|
||||
}
|
||||
|
||||
assetload::postfunc assetload::atlas(
|
||||
AssetsLoader*,
|
||||
const ResPaths* paths,
|
||||
const std::string& directory,
|
||||
const std::string& name,
|
||||
const std::shared_ptr<AssetCfg>&
|
||||
) {
|
||||
assetload::postfunc assetload::
|
||||
atlas(AssetsLoader*, const ResPaths* paths, const std::string& directory, const std::string& name, const std::shared_ptr<AssetCfg>&) {
|
||||
AtlasBuilder builder;
|
||||
for (const auto& file : paths->listdir(directory)) {
|
||||
if (!imageio::is_read_supported(file.extension().u8string()))
|
||||
continue;
|
||||
if (!append_atlas(builder, file))
|
||||
continue;
|
||||
if (!imageio::is_read_supported(file.extension().u8string())) continue;
|
||||
if (!append_atlas(builder, file)) continue;
|
||||
}
|
||||
std::set<std::string> names = builder.getNames();
|
||||
Atlas* atlas = builder.build(2, false).release();
|
||||
@ -114,16 +102,11 @@ assetload::postfunc assetload::atlas(
|
||||
};
|
||||
}
|
||||
|
||||
assetload::postfunc assetload::font(
|
||||
AssetsLoader*,
|
||||
const ResPaths* paths,
|
||||
const std::string& filename,
|
||||
const std::string& name,
|
||||
const std::shared_ptr<AssetCfg>&
|
||||
) {
|
||||
assetload::postfunc assetload::
|
||||
font(AssetsLoader*, const ResPaths* paths, const std::string& filename, const std::string& name, const std::shared_ptr<AssetCfg>&) {
|
||||
auto pages = std::make_shared<std::vector<std::unique_ptr<ImageData>>>();
|
||||
for (size_t i = 0; i <= 4; i++) {
|
||||
std::string pagefile = filename + "_" + std::to_string(i) + ".png";
|
||||
std::string pagefile = filename + "_" + std::to_string(i) + ".png";
|
||||
pagefile = paths->find(pagefile).string();
|
||||
pages->push_back(imageio::read(pagefile));
|
||||
}
|
||||
@ -133,7 +116,9 @@ assetload::postfunc assetload::font(
|
||||
for (auto& page : *pages) {
|
||||
textures.emplace_back(Texture::from(page.get()));
|
||||
}
|
||||
assets->store(std::make_unique<Font>(std::move(textures), res, 4), name);
|
||||
assets->store(
|
||||
std::make_unique<Font>(std::move(textures), res, 4), name
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@ -150,7 +135,7 @@ assetload::postfunc assetload::layout(
|
||||
assets->store(UiDocument::read(cfg->env, name, file), name);
|
||||
} catch (const parsing_error& err) {
|
||||
throw std::runtime_error(
|
||||
"failed to parse layout XML '"+file+"':\n"+err.errorLog()
|
||||
"failed to parse layout XML '" + file + "':\n" + err.errorLog()
|
||||
);
|
||||
}
|
||||
};
|
||||
@ -171,13 +156,13 @@ assetload::postfunc assetload::sound(
|
||||
for (size_t i = 0; i < extensions.size(); i++) {
|
||||
extension = extensions[i];
|
||||
// looking for 'sound_name' as base sound
|
||||
auto soundFile = paths->find(file+extension);
|
||||
auto soundFile = paths->find(file + extension);
|
||||
if (fs::exists(soundFile)) {
|
||||
baseSound = audio::load_sound(soundFile, keepPCM);
|
||||
break;
|
||||
}
|
||||
// looking for 'sound_name_0' as base sound
|
||||
auto variantFile = paths->find(file+"_0"+extension);
|
||||
auto variantFile = paths->find(file + "_0" + extension);
|
||||
if (fs::exists(variantFile)) {
|
||||
baseSound = audio::load_sound(variantFile, keepPCM);
|
||||
break;
|
||||
@ -188,12 +173,14 @@ assetload::postfunc assetload::sound(
|
||||
}
|
||||
|
||||
// loading sound variants
|
||||
for (uint i = 1; ; i++) {
|
||||
auto variantFile = paths->find(file+"_"+std::to_string(i)+extension);
|
||||
for (uint i = 1;; i++) {
|
||||
auto variantFile =
|
||||
paths->find(file + "_" + std::to_string(i) + extension);
|
||||
if (!fs::exists(variantFile)) {
|
||||
break;
|
||||
}
|
||||
baseSound->variants.emplace_back(audio::load_sound(variantFile, keepPCM));
|
||||
baseSound->variants.emplace_back(audio::load_sound(variantFile, keepPCM)
|
||||
);
|
||||
}
|
||||
|
||||
auto sound = baseSound.release();
|
||||
@ -202,22 +189,19 @@ assetload::postfunc assetload::sound(
|
||||
};
|
||||
}
|
||||
|
||||
assetload::postfunc assetload::model(
|
||||
AssetsLoader* loader,
|
||||
const ResPaths* paths,
|
||||
const std::string& file,
|
||||
const std::string& name,
|
||||
const std::shared_ptr<AssetCfg>&
|
||||
) {
|
||||
auto path = paths->find(file+".obj");
|
||||
assetload::postfunc assetload::
|
||||
model(AssetsLoader* loader, const ResPaths* paths, const std::string& file, const std::string& name, const std::shared_ptr<AssetCfg>&) {
|
||||
auto path = paths->find(file + ".obj");
|
||||
auto text = files::read_string(path);
|
||||
try {
|
||||
auto model = obj::parse(path.u8string(), text).release();
|
||||
return [=](Assets* assets) {
|
||||
for (auto& mesh : model->meshes) {
|
||||
if (mesh.texture.find('$') == std::string::npos) {
|
||||
auto filename = TEXTURES_FOLDER+"/"+mesh.texture;
|
||||
loader->add(AssetType::TEXTURE, filename, mesh.texture, nullptr);
|
||||
auto filename = TEXTURES_FOLDER + "/" + mesh.texture;
|
||||
loader->add(
|
||||
AssetType::TEXTURE, filename, mesh.texture, nullptr
|
||||
);
|
||||
}
|
||||
}
|
||||
assets->store(std::unique_ptr<model::Model>(model), name);
|
||||
@ -272,8 +256,10 @@ static TextureAnimation create_animation(
|
||||
|
||||
const int extension = 2;
|
||||
|
||||
frame.dstPos = glm::ivec2(region.u1 * dstWidth, region.v1 * dstHeight) - extension;
|
||||
frame.size = glm::ivec2(region.u2 * dstWidth, region.v2 * dstHeight) - frame.dstPos + extension;
|
||||
frame.dstPos =
|
||||
glm::ivec2(region.u1 * dstWidth, region.v1 * dstHeight) - extension;
|
||||
frame.size = glm::ivec2(region.u2 * dstWidth, region.v2 * dstHeight) -
|
||||
frame.dstPos + extension;
|
||||
|
||||
for (const auto& elem : frameList) {
|
||||
if (!srcAtlas->has(elem.first)) {
|
||||
@ -284,7 +270,11 @@ static TextureAnimation create_animation(
|
||||
if (elem.second > 0) {
|
||||
frame.duration = static_cast<float>(elem.second) / 1000.0f;
|
||||
}
|
||||
frame.srcPos = glm::ivec2(region.u1 * srcWidth, srcHeight - region.v2 * srcHeight) - extension;
|
||||
frame.srcPos =
|
||||
glm::ivec2(
|
||||
region.u1 * srcWidth, srcHeight - region.v2 * srcHeight
|
||||
) -
|
||||
extension;
|
||||
animation.addFrame(frame);
|
||||
}
|
||||
return animation;
|
||||
@ -303,10 +293,10 @@ inline bool contains(
|
||||
}
|
||||
|
||||
static bool animation(
|
||||
Assets* assets,
|
||||
Assets* assets,
|
||||
const ResPaths* paths,
|
||||
const std::string& atlasName,
|
||||
const std::string& directory,
|
||||
const std::string& atlasName,
|
||||
const std::string& directory,
|
||||
const std::string& name,
|
||||
Atlas* dstAtlas
|
||||
) {
|
||||
@ -316,7 +306,7 @@ static bool animation(
|
||||
if (!fs::is_directory(folder)) continue;
|
||||
if (folder.filename().u8string() != name) continue;
|
||||
if (fs::is_empty(folder)) continue;
|
||||
|
||||
|
||||
AtlasBuilder builder;
|
||||
append_atlas(builder, paths->find(directory + "/" + name + ".png"));
|
||||
|
||||
@ -326,11 +316,11 @@ static bool animation(
|
||||
read_anim_file(animFile, frameList);
|
||||
}
|
||||
for (const auto& file : paths->listdir(animsDir + "/" + name)) {
|
||||
if (!frameList.empty() && !contains(frameList, file.stem().u8string())) {
|
||||
if (!frameList.empty() &&
|
||||
!contains(frameList, file.stem().u8string())) {
|
||||
continue;
|
||||
}
|
||||
if (!append_atlas(builder, file))
|
||||
continue;
|
||||
if (!append_atlas(builder, file)) continue;
|
||||
}
|
||||
auto srcAtlas = builder.build(2, true);
|
||||
if (frameList.empty()) {
|
||||
@ -341,7 +331,9 @@ static bool animation(
|
||||
auto animation = create_animation(
|
||||
srcAtlas.get(), dstAtlas, name, builder.getNames(), frameList
|
||||
);
|
||||
assets->store(std::move(srcAtlas), atlasName + "/" + name + "_animation");
|
||||
assets->store(
|
||||
std::move(srcAtlas), atlasName + "/" + name + "_animation"
|
||||
);
|
||||
assets->store(animation);
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
#ifndef ASSETS_ASSET_LOADERS_HPP_
|
||||
#define ASSETS_ASSET_LOADERS_HPP_
|
||||
|
||||
#include "Assets.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "Assets.hpp"
|
||||
|
||||
class ResPaths;
|
||||
class Assets;
|
||||
@ -30,7 +30,7 @@ namespace assetload {
|
||||
);
|
||||
postfunc atlas(
|
||||
AssetsLoader*,
|
||||
const ResPaths* paths,
|
||||
const ResPaths* paths,
|
||||
const std::string& directory,
|
||||
const std::string& name,
|
||||
const std::shared_ptr<AssetCfg>& settings
|
||||
@ -65,4 +65,4 @@ namespace assetload {
|
||||
);
|
||||
}
|
||||
|
||||
#endif // ASSETS_ASSET_LOADERS_HPP_
|
||||
#endif // ASSETS_ASSET_LOADERS_HPP_
|
||||
|
||||
@ -1,18 +1,19 @@
|
||||
#include "ALAudio.hpp"
|
||||
|
||||
#include "alutil.hpp"
|
||||
#include "../../debug/Logger.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "../../debug/Logger.hpp"
|
||||
#include "alutil.hpp"
|
||||
|
||||
static debug::Logger logger("al-audio");
|
||||
|
||||
using namespace audio;
|
||||
|
||||
ALSound::ALSound(ALAudio* al, uint buffer, const std::shared_ptr<PCM>& pcm, bool keepPCM)
|
||||
: al(al), buffer(buffer)
|
||||
{
|
||||
ALSound::ALSound(
|
||||
ALAudio* al, uint buffer, const std::shared_ptr<PCM>& pcm, bool keepPCM
|
||||
)
|
||||
: al(al), buffer(buffer) {
|
||||
duration = pcm->getDuration();
|
||||
if (keepPCM) {
|
||||
this->pcm = pcm;
|
||||
@ -36,8 +37,10 @@ std::unique_ptr<Speaker> ALSound::newInstance(int priority, int channel) const {
|
||||
return speaker;
|
||||
}
|
||||
|
||||
ALStream::ALStream(ALAudio* al, std::shared_ptr<PCMStream> source, bool keepSource)
|
||||
: al(al), source(std::move(source)), keepSource(keepSource) {
|
||||
ALStream::ALStream(
|
||||
ALAudio* al, std::shared_ptr<PCMStream> source, bool keepSource
|
||||
)
|
||||
: al(al), source(std::move(source)), keepSource(keepSource) {
|
||||
}
|
||||
|
||||
ALStream::~ALStream() {
|
||||
@ -60,40 +63,41 @@ std::shared_ptr<PCMStream> ALStream::getSource() const {
|
||||
|
||||
bool ALStream::preloadBuffer(uint buffer, bool loop) {
|
||||
size_t read = source->readFully(this->buffer, BUFFER_SIZE, loop);
|
||||
if (!read)
|
||||
return false;
|
||||
ALenum format = AL::to_al_format(source->getChannels(), source->getBitsPerSample());
|
||||
AL_CHECK(alBufferData(buffer, format, this->buffer, read, source->getSampleRate()));
|
||||
if (!read) return false;
|
||||
ALenum format =
|
||||
AL::to_al_format(source->getChannels(), source->getBitsPerSample());
|
||||
AL_CHECK(alBufferData(
|
||||
buffer, format, this->buffer, read, source->getSampleRate()
|
||||
));
|
||||
return true;
|
||||
}
|
||||
|
||||
std::unique_ptr<Speaker> ALStream::createSpeaker(bool loop, int channel) {
|
||||
this->loop = loop;
|
||||
uint source = al->getFreeSource();
|
||||
if (source == 0) {
|
||||
uint free_source = al->getFreeSource();
|
||||
if (free_source == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
for (uint i = 0; i < ALStream::STREAM_BUFFERS; i++) {
|
||||
uint buffer = al->getFreeBuffer();
|
||||
if (!preloadBuffer(buffer, loop)) {
|
||||
uint free_buffer = al->getFreeBuffer();
|
||||
if (!preloadBuffer(free_buffer, loop)) {
|
||||
break;
|
||||
}
|
||||
AL_CHECK(alSourceQueueBuffers(source, 1, &buffer));
|
||||
AL_CHECK(alSourceQueueBuffers(free_source, 1, &free_buffer));
|
||||
}
|
||||
return std::make_unique<ALSpeaker>(al, source, PRIORITY_HIGH, channel);
|
||||
return std::make_unique<ALSpeaker>(al, free_source, PRIORITY_HIGH, channel);
|
||||
}
|
||||
|
||||
|
||||
void ALStream::bindSpeaker(speakerid_t speaker) {
|
||||
void ALStream::bindSpeaker(speakerid_t speakerid) {
|
||||
auto sp = audio::get_speaker(this->speaker);
|
||||
if (sp) {
|
||||
sp->stop();
|
||||
}
|
||||
this->speaker = speaker;
|
||||
sp = audio::get_speaker(speaker);
|
||||
this->speaker = speakerid;
|
||||
sp = audio::get_speaker(speakerid);
|
||||
if (sp) {
|
||||
auto alspeaker = dynamic_cast<ALSpeaker*>(sp);
|
||||
alspeaker->stream = this;
|
||||
auto alspeaker = dynamic_cast<ALSpeaker*>(sp); //FIXME: Potentional null pointer
|
||||
alspeaker->stream = this; //-V522
|
||||
alspeaker->duration = source->getTotalDuration();
|
||||
}
|
||||
}
|
||||
@ -106,15 +110,15 @@ void ALStream::unqueueBuffers(uint alsource) {
|
||||
uint processed = AL::getSourcei(alsource, AL_BUFFERS_PROCESSED);
|
||||
|
||||
while (processed--) {
|
||||
uint buffer;
|
||||
AL_CHECK(alSourceUnqueueBuffers(alsource, 1, &buffer));
|
||||
unusedBuffers.push(buffer);
|
||||
uint bufferqueue;
|
||||
AL_CHECK(alSourceUnqueueBuffers(alsource, 1, &bufferqueue));
|
||||
unusedBuffers.push(bufferqueue);
|
||||
|
||||
uint bps = source->getBitsPerSample()/8;
|
||||
uint bps = source->getBitsPerSample()/ 8;
|
||||
uint channels = source->getChannels();
|
||||
|
||||
ALint bufferSize;
|
||||
alGetBufferi(buffer, AL_SIZE, &bufferSize);
|
||||
alGetBufferi(bufferqueue, AL_SIZE, &bufferSize);
|
||||
totalPlayedSamples += bufferSize / bps / channels;
|
||||
if (source->isSeekable()) {
|
||||
totalPlayedSamples %= source->getTotalSamples();
|
||||
@ -125,11 +129,11 @@ void ALStream::unqueueBuffers(uint alsource) {
|
||||
uint ALStream::enqueueBuffers(uint alsource) {
|
||||
uint preloaded = 0;
|
||||
if (!unusedBuffers.empty()) {
|
||||
uint buffer = unusedBuffers.front();
|
||||
if (preloadBuffer(buffer, loop)) {
|
||||
uint first_buffer = unusedBuffers.front();
|
||||
if (preloadBuffer(first_buffer, loop)) {
|
||||
preloaded++;
|
||||
unusedBuffers.pop();
|
||||
AL_CHECK(alSourceQueueBuffers(alsource, 1, &buffer));
|
||||
AL_CHECK(alSourceQueueBuffers(alsource, 1, &first_buffer));
|
||||
}
|
||||
}
|
||||
return preloaded;
|
||||
@ -139,37 +143,39 @@ void ALStream::update(double delta) {
|
||||
if (this->speaker == 0) {
|
||||
return;
|
||||
}
|
||||
auto speaker = audio::get_speaker(this->speaker);
|
||||
if (speaker == nullptr) {
|
||||
speaker = 0;
|
||||
auto p_speaker = audio::get_speaker(this->speaker);
|
||||
if (p_speaker == nullptr) {
|
||||
p_speaker = 0; //FIXME: Not used
|
||||
return;
|
||||
}
|
||||
ALSpeaker* alspeaker = dynamic_cast<ALSpeaker*>(speaker);
|
||||
if (alspeaker->stopped) {
|
||||
speaker = 0;
|
||||
ALSpeaker* alspeaker = dynamic_cast<ALSpeaker*>(p_speaker); //FIXME: Potentional null pointer
|
||||
if (alspeaker->stopped) { //-V522
|
||||
p_speaker = 0; //FIXME: Not used
|
||||
return;
|
||||
}
|
||||
|
||||
uint alsource = alspeaker->source;
|
||||
|
||||
|
||||
unqueueBuffers(alsource);
|
||||
uint preloaded = enqueueBuffers(alsource);
|
||||
|
||||
if (speaker->isStopped() && !alspeaker->stopped) {
|
||||
|
||||
if (p_speaker->isStopped() && !alspeaker->stopped) { //FIXME: !alspeaker->stopped always true //-V560
|
||||
if (preloaded) {
|
||||
speaker->play();
|
||||
p_speaker->play();
|
||||
} else {
|
||||
speaker->stop();
|
||||
p_speaker->stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
duration_t ALStream::getTime() const {
|
||||
uint total = totalPlayedSamples;
|
||||
auto alspeaker = dynamic_cast<ALSpeaker*>(audio::get_speaker(this->speaker));
|
||||
auto alspeaker =
|
||||
dynamic_cast<ALSpeaker*>(audio::get_speaker(this->speaker));
|
||||
if (alspeaker) {
|
||||
uint alsource = alspeaker->source;
|
||||
total += static_cast<duration_t>(AL::getSourcef(alsource, AL_SAMPLE_OFFSET));
|
||||
total +=
|
||||
static_cast<duration_t>(AL::getSourcef(alsource, AL_SAMPLE_OFFSET));
|
||||
if (source->isSeekable()) {
|
||||
total %= source->getTotalSamples();
|
||||
}
|
||||
@ -178,11 +184,11 @@ duration_t ALStream::getTime() const {
|
||||
}
|
||||
|
||||
void ALStream::setTime(duration_t time) {
|
||||
if (!source->isSeekable())
|
||||
return;
|
||||
if (!source->isSeekable()) return;
|
||||
uint sample = time * source->getSampleRate();
|
||||
source->seek(sample);
|
||||
auto alspeaker = dynamic_cast<ALSpeaker*>(audio::get_speaker(this->speaker));
|
||||
auto alspeaker =
|
||||
dynamic_cast<ALSpeaker*>(audio::get_speaker(this->speaker));
|
||||
if (alspeaker) {
|
||||
bool paused = alspeaker->isPaused();
|
||||
AL_CHECK(alSourceStop(alspeaker->source));
|
||||
@ -198,8 +204,8 @@ void ALStream::setTime(duration_t time) {
|
||||
}
|
||||
}
|
||||
|
||||
ALSpeaker::ALSpeaker(ALAudio* al, uint source, int priority, int channel)
|
||||
: al(al), priority(priority), channel(channel), source(source) {
|
||||
ALSpeaker::ALSpeaker(ALAudio* al, uint source, int priority, int channel)
|
||||
: al(al), priority(priority), channel(channel), source(source) {
|
||||
}
|
||||
|
||||
ALSpeaker::~ALSpeaker() {
|
||||
@ -209,11 +215,10 @@ ALSpeaker::~ALSpeaker() {
|
||||
}
|
||||
|
||||
void ALSpeaker::update(const Channel* channel) {
|
||||
if (source == 0)
|
||||
return;
|
||||
if (source == 0) return;
|
||||
float gain = this->volume * channel->getVolume();
|
||||
AL_CHECK(alSourcef(source, AL_GAIN, gain));
|
||||
|
||||
|
||||
if (!paused) {
|
||||
if (isPaused() && !channel->isPaused()) {
|
||||
play();
|
||||
@ -230,9 +235,12 @@ int ALSpeaker::getChannel() const {
|
||||
State ALSpeaker::getState() const {
|
||||
int state = AL::getSourcei(source, AL_SOURCE_STATE, AL_STOPPED);
|
||||
switch (state) {
|
||||
case AL_PLAYING: return State::playing;
|
||||
case AL_PAUSED: return State::paused;
|
||||
default: return State::stopped;
|
||||
case AL_PLAYING:
|
||||
return State::playing;
|
||||
case AL_PAUSED:
|
||||
return State::paused;
|
||||
default:
|
||||
return State::stopped;
|
||||
}
|
||||
}
|
||||
|
||||
@ -253,7 +261,7 @@ void ALSpeaker::setPitch(float pitch) {
|
||||
}
|
||||
|
||||
bool ALSpeaker::isLoop() const {
|
||||
return AL::getSourcei(source, AL_LOOPING) == AL_TRUE;
|
||||
return AL::getSourcei(source, AL_LOOPING) == AL_TRUE; //-V550
|
||||
}
|
||||
|
||||
void ALSpeaker::setLoop(bool loop) {
|
||||
@ -263,8 +271,12 @@ void ALSpeaker::setLoop(bool loop) {
|
||||
void ALSpeaker::play() {
|
||||
paused = false;
|
||||
stopped = false;
|
||||
auto channel = get_channel(this->channel);
|
||||
AL_CHECK(alSourcef(source, AL_GAIN, volume * channel->getVolume() * get_channel(0)->getVolume()));
|
||||
auto p_channel = get_channel(this->channel);
|
||||
AL_CHECK(alSourcef(
|
||||
source,
|
||||
AL_GAIN,
|
||||
volume * p_channel->getVolume() * get_channel(0)->getVolume()
|
||||
));
|
||||
AL_CHECK(alSourcePlay(source));
|
||||
}
|
||||
|
||||
@ -325,30 +337,30 @@ glm::vec3 ALSpeaker::getVelocity() const {
|
||||
}
|
||||
|
||||
void ALSpeaker::setRelative(bool relative) {
|
||||
AL_CHECK(alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE));
|
||||
AL_CHECK(
|
||||
alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE)
|
||||
);
|
||||
}
|
||||
|
||||
bool ALSpeaker::isRelative() const {
|
||||
return AL::getSourcei(source, AL_SOURCE_RELATIVE) == AL_TRUE;
|
||||
return AL::getSourcei(source, AL_SOURCE_RELATIVE) == AL_TRUE; //-V550
|
||||
}
|
||||
|
||||
int ALSpeaker::getPriority() const {
|
||||
return priority;
|
||||
}
|
||||
|
||||
|
||||
ALAudio::ALAudio(ALCdevice* device, ALCcontext* context)
|
||||
: device(device), context(context)
|
||||
{
|
||||
: device(device), context(context) {
|
||||
ALCint size;
|
||||
alcGetIntegerv(device, ALC_ATTRIBUTES_SIZE, 1, &size);
|
||||
std::vector<ALCint> attrs(size);
|
||||
alcGetIntegerv(device, ALC_ALL_ATTRIBUTES, size, &attrs[0]);
|
||||
for (size_t i = 0; i < attrs.size(); ++i){
|
||||
if (attrs[i] == ALC_MONO_SOURCES) {
|
||||
logger.info() << "max mono sources: " << attrs[i+1];
|
||||
maxSources = attrs[i+1];
|
||||
}
|
||||
for (size_t i = 0; i < attrs.size(); ++i) {
|
||||
if (attrs[i] == ALC_MONO_SOURCES) {
|
||||
logger.info() << "max mono sources: " << attrs[i + 1];
|
||||
maxSources = attrs[i + 1];
|
||||
}
|
||||
}
|
||||
auto devices = getAvailableDevices();
|
||||
logger.info() << "devices:";
|
||||
@ -366,7 +378,7 @@ ALAudio::~ALAudio() {
|
||||
AL_CHECK(alDeleteSources(1, &source));
|
||||
}
|
||||
|
||||
for (uint buffer : allbuffers){
|
||||
for (uint buffer : allbuffers) {
|
||||
AL_CHECK(alDeleteBuffers(1, &buffer));
|
||||
}
|
||||
|
||||
@ -379,23 +391,28 @@ ALAudio::~ALAudio() {
|
||||
context = nullptr;
|
||||
}
|
||||
|
||||
std::unique_ptr<Sound> ALAudio::createSound(std::shared_ptr<PCM> pcm, bool keepPCM) {
|
||||
std::unique_ptr<Sound> ALAudio::createSound(
|
||||
std::shared_ptr<PCM> pcm, bool keepPCM
|
||||
) {
|
||||
auto format = AL::to_al_format(pcm->channels, pcm->bitsPerSample);
|
||||
uint buffer = getFreeBuffer();
|
||||
AL_CHECK(alBufferData(buffer, format, pcm->data.data(), pcm->data.size(), pcm->sampleRate));
|
||||
AL_CHECK(alBufferData(
|
||||
buffer, format, pcm->data.data(), pcm->data.size(), pcm->sampleRate
|
||||
));
|
||||
return std::make_unique<ALSound>(this, buffer, pcm, keepPCM);
|
||||
}
|
||||
|
||||
std::unique_ptr<Stream> ALAudio::openStream(std::shared_ptr<PCMStream> stream, bool keepSource) {
|
||||
std::unique_ptr<Stream> ALAudio::openStream(
|
||||
std::shared_ptr<PCMStream> stream, bool keepSource
|
||||
) {
|
||||
return std::make_unique<ALStream>(this, stream, keepSource);
|
||||
}
|
||||
|
||||
std::unique_ptr<ALAudio> ALAudio::create() {
|
||||
ALCdevice* device = alcOpenDevice(nullptr);
|
||||
if (device == nullptr)
|
||||
return nullptr;
|
||||
if (device == nullptr) return nullptr;
|
||||
ALCcontext* context = alcCreateContext(device, nullptr);
|
||||
if (!alcMakeContextCurrent(context)){
|
||||
if (!alcMakeContextCurrent(context)) {
|
||||
alcCloseDevice(device);
|
||||
return nullptr;
|
||||
}
|
||||
@ -404,14 +421,15 @@ std::unique_ptr<ALAudio> ALAudio::create() {
|
||||
return std::make_unique<ALAudio>(device, context);
|
||||
}
|
||||
|
||||
uint ALAudio::getFreeSource(){
|
||||
if (!freesources.empty()){
|
||||
uint ALAudio::getFreeSource() {
|
||||
if (!freesources.empty()) {
|
||||
uint source = freesources.back();
|
||||
freesources.pop_back();
|
||||
return source;
|
||||
}
|
||||
if (allsources.size() == maxSources){
|
||||
logger.error() << "attempted to create new source, but limit is " << maxSources;
|
||||
if (allsources.size() == maxSources) {
|
||||
logger.error() << "attempted to create new source, but limit is "
|
||||
<< maxSources;
|
||||
return 0;
|
||||
}
|
||||
ALuint id;
|
||||
@ -423,8 +441,8 @@ uint ALAudio::getFreeSource(){
|
||||
return id;
|
||||
}
|
||||
|
||||
uint ALAudio::getFreeBuffer(){
|
||||
if (!freebuffers.empty()){
|
||||
uint ALAudio::getFreeBuffer() {
|
||||
if (!freebuffers.empty()) {
|
||||
uint buffer = freebuffers.back();
|
||||
freebuffers.pop_back();
|
||||
return buffer;
|
||||
@ -439,11 +457,11 @@ uint ALAudio::getFreeBuffer(){
|
||||
return id;
|
||||
}
|
||||
|
||||
void ALAudio::freeSource(uint source){
|
||||
void ALAudio::freeSource(uint source) {
|
||||
freesources.push_back(source);
|
||||
}
|
||||
|
||||
void ALAudio::freeBuffer(uint buffer){
|
||||
void ALAudio::freeBuffer(uint buffer) {
|
||||
freebuffers.push_back(buffer);
|
||||
}
|
||||
|
||||
@ -460,14 +478,15 @@ std::vector<std::string> ALAudio::getAvailableDevices() const {
|
||||
do {
|
||||
devicesVec.emplace_back(ptr);
|
||||
ptr += devicesVec.back().size() + 1;
|
||||
}
|
||||
while (ptr[0]);
|
||||
} while (ptr[0]);
|
||||
|
||||
return devicesVec;
|
||||
}
|
||||
|
||||
void ALAudio::setListener(glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up){
|
||||
ALfloat listenerOri[] = { at.x, at.y, at.z, up.x, up.y, up.z };
|
||||
void ALAudio::setListener(
|
||||
glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up
|
||||
) {
|
||||
ALfloat listenerOri[] = {at.x, at.y, at.z, up.x, up.y, up.z};
|
||||
|
||||
AL_CHECK(alListener3f(AL_POSITION, position.x, position.y, position.z));
|
||||
AL_CHECK(alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z));
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
#ifndef SRC_AUDIO_AUDIO_HPP_
|
||||
#define SRC_AUDIO_AUDIO_HPP_
|
||||
|
||||
#include "../audio.hpp"
|
||||
#include "../../typedefs.hpp"
|
||||
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <glm/glm.hpp>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "../../typedefs.hpp"
|
||||
#include "../audio.hpp"
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <OpenAL/al.h>
|
||||
@ -29,7 +29,12 @@ namespace audio {
|
||||
std::shared_ptr<PCM> pcm;
|
||||
duration_t duration;
|
||||
public:
|
||||
ALSound(ALAudio* al, uint buffer, const std::shared_ptr<PCM>& pcm, bool keepPCM);
|
||||
ALSound(
|
||||
ALAudio* al,
|
||||
uint buffer,
|
||||
const std::shared_ptr<PCM>& pcm,
|
||||
bool keepPCM
|
||||
);
|
||||
~ALSound();
|
||||
|
||||
duration_t getDuration() const override {
|
||||
@ -40,12 +45,13 @@ namespace audio {
|
||||
return pcm;
|
||||
}
|
||||
|
||||
std::unique_ptr<Speaker> newInstance(int priority, int channel) const override;
|
||||
std::unique_ptr<Speaker> newInstance(int priority, int channel)
|
||||
const override;
|
||||
};
|
||||
|
||||
class ALStream : public Stream {
|
||||
static inline constexpr size_t BUFFER_SIZE = 44100;
|
||||
|
||||
|
||||
ALAudio* al;
|
||||
std::shared_ptr<PCMStream> source;
|
||||
std::queue<uint> unusedBuffers;
|
||||
@ -60,19 +66,21 @@ namespace audio {
|
||||
public:
|
||||
size_t totalPlayedSamples = 0;
|
||||
|
||||
ALStream(ALAudio* al, std::shared_ptr<PCMStream> source, bool keepSource);
|
||||
ALStream(
|
||||
ALAudio* al, std::shared_ptr<PCMStream> source, bool keepSource
|
||||
);
|
||||
~ALStream();
|
||||
|
||||
std::shared_ptr<PCMStream> getSource() const override;
|
||||
void bindSpeaker(speakerid_t speaker) override;
|
||||
void bindSpeaker(speakerid_t speakerid) override;
|
||||
std::unique_ptr<Speaker> createSpeaker(bool loop, int channel) override;
|
||||
speakerid_t getSpeaker() const override;
|
||||
void update(double delta) override;
|
||||
|
||||
duration_t getTime() const override;
|
||||
void setTime(duration_t time) override;
|
||||
|
||||
static inline constexpr uint STREAM_BUFFERS = 3;
|
||||
duration_t getTime() const override;
|
||||
void setTime(duration_t time) override;
|
||||
|
||||
static inline constexpr uint STREAM_BUFFERS = 3;
|
||||
};
|
||||
|
||||
/// @brief AL source adapter
|
||||
@ -147,8 +155,12 @@ namespace audio {
|
||||
|
||||
std::vector<std::string> getAvailableDevices() const;
|
||||
|
||||
std::unique_ptr<Sound> createSound(std::shared_ptr<PCM> pcm, bool keepPCM) override;
|
||||
std::unique_ptr<Stream> openStream(std::shared_ptr<PCMStream> stream, bool keepSource) override;
|
||||
std::unique_ptr<Sound> createSound(
|
||||
std::shared_ptr<PCM> pcm, bool keepPCM
|
||||
) override;
|
||||
std::unique_ptr<Stream> openStream(
|
||||
std::shared_ptr<PCMStream> stream, bool keepSource
|
||||
) override;
|
||||
|
||||
void setListener(
|
||||
glm::vec3 position,
|
||||
@ -158,7 +170,7 @@ namespace audio {
|
||||
) override;
|
||||
|
||||
void update(double delta) override;
|
||||
|
||||
|
||||
bool isDummy() const override {
|
||||
return false;
|
||||
}
|
||||
@ -167,4 +179,4 @@ namespace audio {
|
||||
};
|
||||
}
|
||||
|
||||
#endif // SRC_AUDIO_AUDIO_HPP_
|
||||
#endif // SRC_AUDIO_AUDIO_HPP_
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
#include "alutil.hpp"
|
||||
|
||||
#include "../../debug/Logger.hpp"
|
||||
|
||||
#include <fstream>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <type_traits>
|
||||
|
||||
#include "../../debug/Logger.hpp"
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <OpenAL/al.h>
|
||||
#include <OpenAL/alc.h>
|
||||
@ -17,28 +17,34 @@
|
||||
|
||||
static debug::Logger logger("open-al");
|
||||
|
||||
bool AL::check_errors(const std::string& filename, const std::uint_fast32_t line){
|
||||
bool AL::check_errors(
|
||||
const std::string& filename, const std::uint_fast32_t line
|
||||
) {
|
||||
ALenum error = alGetError();
|
||||
if(error != AL_NO_ERROR){
|
||||
if (error != AL_NO_ERROR) {
|
||||
logger.error() << filename << ": " << line;
|
||||
switch(error){
|
||||
case AL_INVALID_NAME:
|
||||
logger.error() << "a bad name (ID) was passed to an OpenAL function";
|
||||
break;
|
||||
case AL_INVALID_ENUM:
|
||||
logger.error() << "an invalid enum value was passed to an OpenAL function";
|
||||
break;
|
||||
case AL_INVALID_VALUE:
|
||||
logger.error() << "an invalid value was passed to an OpenAL function";
|
||||
break;
|
||||
case AL_INVALID_OPERATION:
|
||||
logger.error() << "the requested operation is not valid";
|
||||
break;
|
||||
case AL_OUT_OF_MEMORY:
|
||||
logger.error() << "the requested operation resulted in OpenAL running out of memory";
|
||||
break;
|
||||
default:
|
||||
logger.error() << "UNKNOWN AL ERROR: " << error;
|
||||
switch (error) {
|
||||
case AL_INVALID_NAME:
|
||||
logger.error()
|
||||
<< "a bad name (ID) was passed to an OpenAL function";
|
||||
break;
|
||||
case AL_INVALID_ENUM:
|
||||
logger.error()
|
||||
<< "an invalid enum value was passed to an OpenAL function";
|
||||
break;
|
||||
case AL_INVALID_VALUE:
|
||||
logger.error()
|
||||
<< "an invalid value was passed to an OpenAL function";
|
||||
break;
|
||||
case AL_INVALID_OPERATION:
|
||||
logger.error() << "the requested operation is not valid";
|
||||
break;
|
||||
case AL_OUT_OF_MEMORY:
|
||||
logger.error() << "the requested operation resulted in OpenAL "
|
||||
"running out of memory";
|
||||
break;
|
||||
default:
|
||||
logger.error() << "UNKNOWN AL ERROR: " << error;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
#ifndef AUDIO_AUDIOUTIL_HPP_
|
||||
#define AUDIO_AUDIOUTIL_HPP_
|
||||
|
||||
#include "../../typedefs.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <cstdint>
|
||||
|
||||
#include "../../typedefs.hpp"
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <OpenAL/al.h>
|
||||
@ -15,22 +15,25 @@
|
||||
|
||||
#include <glm/glm.hpp>
|
||||
|
||||
#define AL_CHECK(STATEMENT) STATEMENT; AL::check_errors(__FILE__, __LINE__)
|
||||
#define AL_CHECK(STATEMENT) \
|
||||
STATEMENT; \
|
||||
AL::check_errors(__FILE__, __LINE__)
|
||||
#define AL_GET_ERROR() AL::check_errors(__FILE__, __LINE__)
|
||||
|
||||
namespace AL {
|
||||
/// @return true if no errors
|
||||
bool check_errors(const std::string& filename, const std::uint_fast32_t line);
|
||||
namespace AL {
|
||||
/// @return true if no errors
|
||||
bool check_errors(
|
||||
const std::string& filename, const std::uint_fast32_t line
|
||||
);
|
||||
|
||||
/// @brief alGetSourcef wrapper
|
||||
/// @param source target source
|
||||
/// @param field enum value
|
||||
/// @param def default value will be returned in case of error
|
||||
/// @return field value or default
|
||||
inline float getSourcef(uint source, ALenum field, float def=0.0f) {
|
||||
inline float getSourcef(uint source, ALenum field, float def = 0.0f) {
|
||||
float value = def;
|
||||
if (source == 0)
|
||||
return def;
|
||||
if (source == 0) return def;
|
||||
AL_CHECK(alGetSourcef(source, field, &value));
|
||||
return value;
|
||||
}
|
||||
@ -40,10 +43,11 @@ namespace AL {
|
||||
/// @param field enum value
|
||||
/// @param def default value will be returned in case of error
|
||||
/// @return field value or default
|
||||
inline glm::vec3 getSource3f(uint source, ALenum field, glm::vec3 def={}) {
|
||||
inline glm::vec3 getSource3f(
|
||||
uint source, ALenum field, glm::vec3 def = {}
|
||||
) {
|
||||
glm::vec3 value = def;
|
||||
if (source == 0)
|
||||
return def;
|
||||
if (source == 0) return def;
|
||||
AL_CHECK(alGetSource3f(source, field, &value.x, &value.y, &value.z));
|
||||
return value;
|
||||
}
|
||||
@ -53,32 +57,31 @@ namespace AL {
|
||||
/// @param field enum value
|
||||
/// @param def default value will be returned in case of error
|
||||
/// @return field value or default
|
||||
inline float getSourcei(uint source, ALenum field, int def=0) {
|
||||
inline float getSourcei(uint source, ALenum field, int def = 0) {
|
||||
int value = def;
|
||||
if (source == 0)
|
||||
return def;
|
||||
if (source == 0) return def;
|
||||
AL_CHECK(alGetSourcei(source, field, &value));
|
||||
return value;
|
||||
}
|
||||
|
||||
static inline ALenum to_al_format(short channels, short bitsPerSample){
|
||||
static inline ALenum to_al_format(short channels, short bitsPerSample) {
|
||||
bool stereo = (channels > 1);
|
||||
|
||||
switch (bitsPerSample) {
|
||||
case 16:
|
||||
if (stereo)
|
||||
return AL_FORMAT_STEREO16;
|
||||
else
|
||||
return AL_FORMAT_MONO16;
|
||||
case 8:
|
||||
if (stereo)
|
||||
return AL_FORMAT_STEREO8;
|
||||
else
|
||||
return AL_FORMAT_MONO8;
|
||||
default:
|
||||
return -1;
|
||||
case 16:
|
||||
if (stereo)
|
||||
return AL_FORMAT_STEREO16;
|
||||
else
|
||||
return AL_FORMAT_MONO16;
|
||||
case 8:
|
||||
if (stereo)
|
||||
return AL_FORMAT_STEREO8;
|
||||
else
|
||||
return AL_FORMAT_MONO8;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // AUDIO_AUDIOUTIL_HPP_
|
||||
#endif // AUDIO_AUDIOUTIL_HPP_
|
||||
|
||||
@ -9,11 +9,15 @@ NoSound::NoSound(const std::shared_ptr<PCM>& pcm, bool keepPCM) {
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<Sound> NoAudio::createSound(std::shared_ptr<PCM> pcm, bool keepPCM) {
|
||||
std::unique_ptr<Sound> NoAudio::createSound(
|
||||
std::shared_ptr<PCM> pcm, bool keepPCM
|
||||
) {
|
||||
return std::make_unique<NoSound>(pcm, keepPCM);
|
||||
}
|
||||
|
||||
std::unique_ptr<Stream> NoAudio::openStream(std::shared_ptr<PCMStream> stream, bool keepSource) {
|
||||
std::unique_ptr<Stream> NoAudio::openStream(
|
||||
std::shared_ptr<PCMStream> stream, bool keepSource
|
||||
) {
|
||||
return std::make_unique<NoStream>(stream, keepSource);
|
||||
}
|
||||
|
||||
|
||||
@ -9,7 +9,8 @@ namespace audio {
|
||||
duration_t duration;
|
||||
public:
|
||||
NoSound(const std::shared_ptr<PCM>& pcm, bool keepPCM);
|
||||
~NoSound() {}
|
||||
~NoSound() {
|
||||
}
|
||||
|
||||
duration_t getDuration() const override {
|
||||
return duration;
|
||||
@ -19,7 +20,8 @@ namespace audio {
|
||||
return pcm;
|
||||
}
|
||||
|
||||
std::unique_ptr<Speaker> newInstance(int priority, int channel) const override {
|
||||
std::unique_ptr<Speaker> newInstance(int priority, int channel)
|
||||
const override {
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
@ -42,7 +44,8 @@ namespace audio {
|
||||
void bindSpeaker(speakerid_t speaker) override {
|
||||
}
|
||||
|
||||
std::unique_ptr<Speaker> createSpeaker(bool loop, int channel) override {
|
||||
std::unique_ptr<Speaker> createSpeaker(bool loop, int channel)
|
||||
override {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@ -63,19 +66,23 @@ namespace audio {
|
||||
|
||||
class NoAudio : public Backend {
|
||||
public:
|
||||
~NoAudio() {}
|
||||
~NoAudio() {
|
||||
}
|
||||
|
||||
std::unique_ptr<Sound> createSound(std::shared_ptr<PCM> pcm, bool keepPCM) override;
|
||||
std::unique_ptr<Stream> openStream(std::shared_ptr<PCMStream> stream, bool keepSource) override;
|
||||
std::unique_ptr<Sound> createSound(
|
||||
std::shared_ptr<PCM> pcm, bool keepPCM
|
||||
) override;
|
||||
std::unique_ptr<Stream> openStream(
|
||||
std::shared_ptr<PCMStream> stream, bool keepSource
|
||||
) override;
|
||||
|
||||
void setListener(
|
||||
glm::vec3 position,
|
||||
glm::vec3 velocity,
|
||||
glm::vec3 at,
|
||||
glm::vec3 up
|
||||
) override {}
|
||||
glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up
|
||||
) override {
|
||||
}
|
||||
|
||||
void update(double delta) override {}
|
||||
void update(double delta) override {
|
||||
}
|
||||
|
||||
bool isDummy() const override {
|
||||
return true;
|
||||
@ -85,4 +92,4 @@ namespace audio {
|
||||
};
|
||||
}
|
||||
|
||||
#endif // AUDIO_NOAUDIO_HPP_
|
||||
#endif // AUDIO_NOAUDIO_HPP_
|
||||
|
||||
@ -1,15 +1,14 @@
|
||||
#include "audio.hpp"
|
||||
|
||||
#include "NoAudio.hpp"
|
||||
#include "AL/ALAudio.hpp"
|
||||
|
||||
#include "../coders/wav.hpp"
|
||||
#include "../coders/ogg.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
#include "../coders/ogg.hpp"
|
||||
#include "../coders/wav.hpp"
|
||||
#include "AL/ALAudio.hpp"
|
||||
#include "NoAudio.hpp"
|
||||
|
||||
namespace audio {
|
||||
static speakerid_t nextId = 1;
|
||||
static Backend* backend;
|
||||
@ -85,12 +84,12 @@ class PCMVoidSource : public PCMStream {
|
||||
bool seekable;
|
||||
bool closed = false;
|
||||
public:
|
||||
PCMVoidSource(size_t totalSamples, uint sampleRate, bool seekable)
|
||||
: totalSamples(totalSamples),
|
||||
remain(totalSamples),
|
||||
sampleRate(sampleRate),
|
||||
seekable(seekable)
|
||||
{}
|
||||
PCMVoidSource(size_t totalSamples, uint sampleRate, bool seekable)
|
||||
: totalSamples(totalSamples),
|
||||
remain(totalSamples),
|
||||
sampleRate(sampleRate),
|
||||
seekable(seekable) {
|
||||
}
|
||||
|
||||
size_t read(char*, size_t bufferSize) override {
|
||||
if (closed) {
|
||||
@ -117,7 +116,7 @@ public:
|
||||
}
|
||||
|
||||
duration_t getTotalDuration() const override {
|
||||
return static_cast<duration_t>(totalSamples) /
|
||||
return static_cast<duration_t>(totalSamples) /
|
||||
static_cast<duration_t>(sampleRate);
|
||||
}
|
||||
|
||||
@ -159,7 +158,7 @@ void audio::initialize(bool enabled) {
|
||||
|
||||
std::unique_ptr<PCM> audio::load_PCM(const fs::path& file, bool headerOnly) {
|
||||
if (!fs::exists(file)) {
|
||||
throw std::runtime_error("file not found '"+file.u8string()+"'");
|
||||
throw std::runtime_error("file not found '" + file.u8string() + "'");
|
||||
}
|
||||
std::string ext = file.extension().u8string();
|
||||
if (ext == ".wav" || ext == ".WAV") {
|
||||
@ -171,11 +170,15 @@ std::unique_ptr<PCM> audio::load_PCM(const fs::path& file, bool headerOnly) {
|
||||
}
|
||||
|
||||
std::unique_ptr<Sound> audio::load_sound(const fs::path& file, bool keepPCM) {
|
||||
std::shared_ptr<PCM> pcm(load_PCM(file, !keepPCM && backend->isDummy()).release());
|
||||
std::shared_ptr<PCM> pcm(
|
||||
load_PCM(file, !keepPCM && backend->isDummy()).release()
|
||||
);
|
||||
return create_sound(pcm, 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(std::move(pcm), keepPCM);
|
||||
}
|
||||
|
||||
@ -189,31 +192,32 @@ std::unique_ptr<PCMStream> audio::open_PCM_stream(const fs::path& file) {
|
||||
throw std::runtime_error("unsupported audio stream format");
|
||||
}
|
||||
|
||||
std::unique_ptr<Stream> audio::open_stream(const fs::path& file, bool keepSource) {
|
||||
std::unique_ptr<Stream> audio::open_stream(
|
||||
const fs::path& file, bool keepSource
|
||||
) {
|
||||
if (!keepSource && backend->isDummy()) {
|
||||
auto header = load_PCM(file, true);
|
||||
// using void source sized as audio instead of actual audio file
|
||||
return open_stream(
|
||||
std::make_shared<PCMVoidSource>(header->totalSamples, header->sampleRate, header->seekable),
|
||||
std::make_shared<PCMVoidSource>(
|
||||
header->totalSamples, header->sampleRate, header->seekable
|
||||
),
|
||||
keepSource
|
||||
);
|
||||
}
|
||||
return open_stream(
|
||||
std::shared_ptr<PCMStream>(open_PCM_stream(file)),
|
||||
keepSource
|
||||
std::shared_ptr<PCMStream>(open_PCM_stream(file)), 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(std::move(stream), keepSource);
|
||||
}
|
||||
|
||||
|
||||
void audio::set_listener(
|
||||
glm::vec3 position,
|
||||
glm::vec3 velocity,
|
||||
glm::vec3 lookAt,
|
||||
glm::vec3 up
|
||||
glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up
|
||||
) {
|
||||
backend->setListener(position, velocity, lookAt, up);
|
||||
}
|
||||
@ -317,7 +321,7 @@ speakerid_t audio::play_stream(
|
||||
bool loop,
|
||||
int channel
|
||||
) {
|
||||
std::shared_ptr<Stream> stream (open_stream(file, false));
|
||||
std::shared_ptr<Stream> stream(open_stream(file, false));
|
||||
return play(stream, position, relative, volume, pitch, loop, channel);
|
||||
}
|
||||
|
||||
@ -335,14 +339,14 @@ int audio::create_channel(const std::string& name) {
|
||||
return index;
|
||||
}
|
||||
channels.emplace_back(std::make_unique<Channel>(name));
|
||||
return channels.size()-1;
|
||||
return channels.size() - 1;
|
||||
}
|
||||
|
||||
int audio::get_channel_index(const std::string& name) {
|
||||
int index = 0;
|
||||
for (auto& channel : channels) {
|
||||
if (channel->getName() == name) {
|
||||
return index;
|
||||
return index;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
#ifndef AUDIO_AUDIO_HPP_
|
||||
#define AUDIO_AUDIO_HPP_
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <filesystem>
|
||||
#include <glm/glm.hpp>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
@ -29,14 +29,11 @@ namespace audio {
|
||||
class Speaker;
|
||||
|
||||
/// @brief Audio speaker states
|
||||
enum class State {
|
||||
playing,
|
||||
paused,
|
||||
stopped
|
||||
};
|
||||
enum class State { playing, paused, stopped };
|
||||
|
||||
/// @brief Mixer channel controls speakers volume and effects
|
||||
/// There is main channel 'master' and sub-channels like 'regular', 'music', 'ambient'...
|
||||
/// There is main channel 'master' and sub-channels like 'regular', 'music',
|
||||
/// 'ambient'...
|
||||
class Channel {
|
||||
/// @brief Channel name
|
||||
std::string name;
|
||||
@ -46,7 +43,7 @@ namespace audio {
|
||||
public:
|
||||
Channel(std::string name);
|
||||
|
||||
/// @brief Get channel volume
|
||||
/// @brief Get channel volume
|
||||
float getVolume() const;
|
||||
|
||||
/// @brief Set channel volume
|
||||
@ -57,8 +54,7 @@ namespace audio {
|
||||
const std::string& getName() const;
|
||||
|
||||
inline void setPaused(bool flag) {
|
||||
if (flag == paused)
|
||||
return;
|
||||
if (flag == paused) return;
|
||||
if (flag) {
|
||||
pause();
|
||||
} else {
|
||||
@ -92,24 +88,24 @@ namespace audio {
|
||||
/// @brief Audio source is seekable
|
||||
bool seekable;
|
||||
|
||||
PCM(
|
||||
std::vector<char> data,
|
||||
PCM(std::vector<char> data,
|
||||
size_t totalSamples,
|
||||
uint8_t channels,
|
||||
uint8_t bitsPerSample,
|
||||
uint sampleRate,
|
||||
bool seekable
|
||||
) : data(std::move(data)),
|
||||
totalSamples(totalSamples),
|
||||
channels(channels),
|
||||
bitsPerSample(bitsPerSample),
|
||||
sampleRate(sampleRate),
|
||||
seekable(seekable) {}
|
||||
bool seekable)
|
||||
: data(std::move(data)),
|
||||
totalSamples(totalSamples),
|
||||
channels(channels),
|
||||
bitsPerSample(bitsPerSample),
|
||||
sampleRate(sampleRate),
|
||||
seekable(seekable) {
|
||||
}
|
||||
|
||||
/// @brief Get total audio duration
|
||||
/// @return duration in seconds
|
||||
/// @return duration in seconds
|
||||
inline duration_t getDuration() const {
|
||||
return static_cast<duration_t>(totalSamples) /
|
||||
return static_cast<duration_t>(totalSamples) /
|
||||
static_cast<duration_t>(sampleRate);
|
||||
}
|
||||
};
|
||||
@ -123,38 +119,38 @@ namespace audio {
|
||||
/// @param buffer destination buffer
|
||||
/// @param bufferSize destination buffer size
|
||||
/// @param loop loop stream (seek to start when end reached)
|
||||
/// @return size of data received
|
||||
/// @return size of data received
|
||||
/// (always equals bufferSize if seekable and looped)
|
||||
virtual size_t readFully(char* buffer, size_t bufferSize, bool loop);
|
||||
|
||||
virtual size_t read(char* buffer, size_t bufferSize) = 0;
|
||||
|
||||
/// @brief Close stream
|
||||
virtual void close()=0;
|
||||
virtual void close() = 0;
|
||||
|
||||
/// @brief Check if stream is open
|
||||
virtual bool isOpen() const=0;
|
||||
virtual bool isOpen() const = 0;
|
||||
|
||||
/// @brief Get total samples number if seekable or 0
|
||||
virtual size_t getTotalSamples() const=0;
|
||||
virtual size_t getTotalSamples() const = 0;
|
||||
|
||||
/// @brief Get total audio track duration if seekable or 0.0
|
||||
virtual duration_t getTotalDuration() const=0;
|
||||
virtual duration_t getTotalDuration() const = 0;
|
||||
|
||||
/// @brief Get number of audio channels
|
||||
/// @return 1 if mono, 2 if stereo
|
||||
virtual uint getChannels() const=0;
|
||||
virtual uint getChannels() const = 0;
|
||||
|
||||
/// @brief Get audio sampling frequency
|
||||
/// @return number of mono samples per second
|
||||
virtual uint getSampleRate() const=0;
|
||||
virtual uint getSampleRate() const = 0;
|
||||
|
||||
/// @brief Get number of bits per mono sample
|
||||
/// @return 8 or 16
|
||||
virtual uint getBitsPerSample() const=0;
|
||||
virtual uint getBitsPerSample() const = 0;
|
||||
|
||||
/// @brief Check if the stream does support seek feature
|
||||
virtual bool isSeekable() const=0;
|
||||
virtual bool isSeekable() const = 0;
|
||||
|
||||
/// @brief Move playhead to the selected sample number
|
||||
/// @param position selected sample number
|
||||
@ -170,16 +166,18 @@ namespace audio {
|
||||
virtual ~Stream() {};
|
||||
|
||||
/// @brief Get pcm data source
|
||||
/// @return PCM stream or nullptr if audio::openStream
|
||||
/// @return PCM stream or nullptr if audio::openStream
|
||||
/// keepSource argument is set to false
|
||||
virtual std::shared_ptr<PCMStream> getSource() const = 0;
|
||||
|
||||
/// @brief Create new speaker bound to the Stream
|
||||
/// @brief Create new speaker bound to the Stream
|
||||
/// and having high priority
|
||||
/// @param loop is stream looped (required for correct buffers preload)
|
||||
/// @param channel channel index
|
||||
/// @return speaker id or 0
|
||||
virtual std::unique_ptr<Speaker> createSpeaker(bool loop, int channel) = 0;
|
||||
virtual std::unique_ptr<Speaker> createSpeaker(
|
||||
bool loop, int channel
|
||||
) = 0;
|
||||
|
||||
/// @brief Unbind previous speaker and bind new speaker to the stream
|
||||
/// @param speaker speaker id or 0 if all you need is unbind speaker
|
||||
@ -201,7 +199,7 @@ namespace audio {
|
||||
virtual void setTime(duration_t time) = 0;
|
||||
};
|
||||
|
||||
/// @brief Sound is an audio asset that supposed to support many
|
||||
/// @brief Sound is an audio asset that supposed to support many
|
||||
/// simultaneously playing instances (speakers).
|
||||
/// So it's audio data is stored in memory.
|
||||
class Sound {
|
||||
@ -209,7 +207,8 @@ namespace audio {
|
||||
/// @brief Sound variants will be chosen randomly to play
|
||||
std::vector<std::shared_ptr<Sound>> variants;
|
||||
|
||||
virtual ~Sound() {}
|
||||
virtual ~Sound() {
|
||||
}
|
||||
|
||||
/// @brief Get sound duration
|
||||
/// @return duration in seconds (>= 0.0)
|
||||
@ -220,19 +219,21 @@ namespace audio {
|
||||
virtual std::shared_ptr<PCM> getPCM() const = 0;
|
||||
|
||||
/// @brief Create new sound instance
|
||||
/// @param priority instance priority. High priority instance can
|
||||
/// @param priority instance priority. High priority instance can
|
||||
/// take out speaker from low priority instance
|
||||
/// @param channel channel index
|
||||
/// @return new speaker with sound bound or nullptr
|
||||
/// @return new speaker with sound bound or nullptr
|
||||
/// if all speakers are in use
|
||||
virtual std::unique_ptr<Speaker> newInstance(int priority, int channel) const = 0;
|
||||
virtual std::unique_ptr<Speaker> newInstance(int priority, int channel)
|
||||
const = 0;
|
||||
};
|
||||
|
||||
/// @brief Audio source controller interface.
|
||||
/// @attention Speaker is not supposed to be reused
|
||||
class Speaker {
|
||||
public:
|
||||
virtual ~Speaker() {}
|
||||
virtual ~Speaker() {
|
||||
}
|
||||
|
||||
/// @brief Synchronize the speaker with channel settings
|
||||
/// @param channel speaker channel
|
||||
@ -277,7 +278,7 @@ namespace audio {
|
||||
|
||||
/// @brief Stop and destroy speaker
|
||||
virtual void stop() = 0;
|
||||
|
||||
|
||||
/// @brief Get current time position of playing audio
|
||||
/// @return time position in seconds
|
||||
virtual duration_t getTime() const = 0;
|
||||
@ -316,17 +317,17 @@ namespace audio {
|
||||
/// @brief Determines if the position is relative to the listener
|
||||
virtual bool isRelative() const = 0;
|
||||
|
||||
/// @brief Check if speaker is playing
|
||||
/// @brief Check if speaker is playing
|
||||
inline bool isPlaying() const {
|
||||
return getState() == State::playing;
|
||||
}
|
||||
|
||||
/// @brief Check if speaker is paused
|
||||
/// @brief Check if speaker is paused
|
||||
inline bool isPaused() const {
|
||||
return getState() == State::paused;
|
||||
}
|
||||
|
||||
/// @brief Check if speaker is stopped
|
||||
/// @brief Check if speaker is stopped
|
||||
inline bool isStopped() const {
|
||||
return getState() == State::stopped;
|
||||
}
|
||||
@ -336,12 +337,16 @@ namespace audio {
|
||||
public:
|
||||
virtual ~Backend() {};
|
||||
|
||||
virtual std::unique_ptr<Sound> createSound(std::shared_ptr<PCM> pcm, bool keepPCM) = 0;
|
||||
virtual std::unique_ptr<Stream> openStream(std::shared_ptr<PCMStream> stream, bool keepSource) = 0;
|
||||
virtual std::unique_ptr<Sound> createSound(
|
||||
std::shared_ptr<PCM> pcm, bool keepPCM
|
||||
) = 0;
|
||||
virtual std::unique_ptr<Stream> openStream(
|
||||
std::shared_ptr<PCMStream> stream, bool keepSource
|
||||
) = 0;
|
||||
virtual void setListener(
|
||||
glm::vec3 position,
|
||||
glm::vec3 velocity,
|
||||
glm::vec3 lookAt,
|
||||
glm::vec3 position,
|
||||
glm::vec3 velocity,
|
||||
glm::vec3 lookAt,
|
||||
glm::vec3 up
|
||||
) = 0;
|
||||
virtual void update(double delta) = 0;
|
||||
@ -358,21 +363,23 @@ namespace audio {
|
||||
/// @brief Load audio file info and PCM data
|
||||
/// @param file audio file
|
||||
/// @param headerOnly read header only
|
||||
/// @throws std::runtime_error if I/O error ocurred or format is unknown
|
||||
/// @throws std::runtime_error if I/O error ocurred or format is unknown
|
||||
/// @return PCM audio data
|
||||
std::unique_ptr<PCM> load_PCM(const fs::path& file, bool headerOnly);
|
||||
|
||||
/// @brief Load sound from file
|
||||
/// @param file audio file path
|
||||
/// @param keepPCM store PCM data in sound to make it accessible with Sound::getPCM
|
||||
/// @throws std::runtime_error if I/O error ocurred or format is unknown
|
||||
/// @param keepPCM store PCM data in sound to make it accessible with
|
||||
/// Sound::getPCM
|
||||
/// @throws std::runtime_error if I/O error ocurred or format is unknown
|
||||
/// @return new Sound instance
|
||||
std::unique_ptr<Sound> load_sound(const fs::path& file, bool keepPCM);
|
||||
|
||||
/// @brief Create new sound from PCM data
|
||||
/// @param pcm PCM data
|
||||
/// @param keepPCM store PCM data in sound to make it accessible with Sound::getPCM
|
||||
/// @return new Sound instance
|
||||
/// @param keepPCM store PCM data in sound to make it accessible with
|
||||
/// Sound::getPCM
|
||||
/// @return new Sound instance
|
||||
std::unique_ptr<Sound> create_sound(std::shared_ptr<PCM> pcm, bool keepPCM);
|
||||
|
||||
/// @brief Open new PCM stream from file
|
||||
@ -383,15 +390,19 @@ namespace audio {
|
||||
|
||||
/// @brief Open new audio stream from file
|
||||
/// @param file audio file path
|
||||
/// @param keepSource store PCMStream in stream to make it accessible with Stream::getSource
|
||||
/// @param keepSource store PCMStream in stream to make it accessible with
|
||||
/// Stream::getSource
|
||||
/// @return new Stream instance
|
||||
std::unique_ptr<Stream> open_stream(const fs::path& file, bool keepSource);
|
||||
|
||||
/// @brief Open new audio stream from source
|
||||
/// @param stream PCM data source
|
||||
/// @param keepSource store PCMStream in stream to make it accessible with Stream::getSource
|
||||
/// @param keepSource store PCMStream in stream to make it accessible with
|
||||
/// Stream::getSource
|
||||
/// @return new Stream instance
|
||||
std::unique_ptr<Stream> open_stream(std::shared_ptr<PCMStream> stream, bool keepSource);
|
||||
std::unique_ptr<Stream> open_stream(
|
||||
std::shared_ptr<PCMStream> stream, bool keepSource
|
||||
);
|
||||
|
||||
/// @brief Configure 3D listener
|
||||
/// @param position listener position
|
||||
@ -399,10 +410,7 @@ namespace audio {
|
||||
/// @param lookAt point the listener look at
|
||||
/// @param up camera up vector
|
||||
void set_listener(
|
||||
glm::vec3 position,
|
||||
glm::vec3 velocity,
|
||||
glm::vec3 lookAt,
|
||||
glm::vec3 up
|
||||
glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up
|
||||
);
|
||||
|
||||
/// @brief Play 3D sound in the world
|
||||
@ -412,7 +420,7 @@ namespace audio {
|
||||
/// @param volume sound volume [0.0-1.0]
|
||||
/// @param pitch sound pitch multiplier [0.0-...]
|
||||
/// @param loop loop sound
|
||||
/// @param priority sound priority
|
||||
/// @param priority sound priority
|
||||
/// (PRIORITY_LOW, PRIORITY_NORMAL, PRIORITY_HIGH)
|
||||
/// @param channel channel index
|
||||
/// @return speaker id or 0
|
||||
@ -470,7 +478,7 @@ namespace audio {
|
||||
/// @return speaker or nullptr
|
||||
Speaker* get_speaker(speakerid_t id);
|
||||
|
||||
/// @brief Create new channel.
|
||||
/// @brief Create new channel.
|
||||
/// All non-builtin channels will be destroyed on audio::reset() call
|
||||
/// @param name channel name
|
||||
/// @return new channel index
|
||||
@ -499,7 +507,7 @@ namespace audio {
|
||||
/// @brief Get alive speakers number (including paused)
|
||||
size_t count_speakers();
|
||||
|
||||
/// @brief Get playing streams number (including paused)
|
||||
/// @brief Get playing streams number (including paused)
|
||||
size_t count_streams();
|
||||
|
||||
/// @brief Update audio streams and sound instanced
|
||||
@ -508,9 +516,9 @@ namespace audio {
|
||||
|
||||
/// @brief Stop all playing audio in channel, reset channel state
|
||||
void reset_channel(int channel);
|
||||
|
||||
|
||||
/// @brief Finalize audio system
|
||||
void close();
|
||||
};
|
||||
|
||||
#endif // AUDIO_AUDIO_HPP_
|
||||
#endif // AUDIO_AUDIO_HPP_
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
#include "GLSLExtension.hpp"
|
||||
|
||||
#include "../util/stringutil.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../files/engine_paths.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
#include "../files/engine_paths.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
void GLSLExtension::setVersion(std::string version) {
|
||||
@ -21,7 +21,7 @@ void GLSLExtension::setPaths(const ResPaths* paths) {
|
||||
}
|
||||
|
||||
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);
|
||||
addHeader(name, "");
|
||||
addHeader(name, process(file, source, true));
|
||||
@ -38,7 +38,7 @@ void GLSLExtension::define(const std::string& name, std::string value) {
|
||||
const std::string& GLSLExtension::getHeader(const std::string& name) const {
|
||||
auto found = headers.find(name);
|
||||
if (found == headers.end()) {
|
||||
throw std::runtime_error("no header '"+name+"' loaded");
|
||||
throw std::runtime_error("no header '" + name + "' loaded");
|
||||
}
|
||||
return found->second;
|
||||
}
|
||||
@ -46,7 +46,7 @@ const std::string& GLSLExtension::getHeader(const std::string& name) const {
|
||||
const std::string& GLSLExtension::getDefine(const std::string& name) const {
|
||||
auto found = defines.find(name);
|
||||
if (found == defines.end()) {
|
||||
throw std::runtime_error("name '"+name+"' is not defined");
|
||||
throw std::runtime_error("name '" + name + "' is not defined");
|
||||
}
|
||||
return found->second;
|
||||
}
|
||||
@ -66,26 +66,29 @@ void GLSLExtension::undefine(const std::string& name) {
|
||||
}
|
||||
|
||||
inline std::runtime_error parsing_error(
|
||||
const fs::path& file,
|
||||
uint linenum,
|
||||
const std::string& message) {
|
||||
return std::runtime_error("file "+file.string()+": "+message+
|
||||
" at line "+std::to_string(linenum));
|
||||
const fs::path& file, uint linenum, const std::string& message
|
||||
) {
|
||||
return std::runtime_error(
|
||||
"file " + file.string() + ": " + message + " at line " +
|
||||
std::to_string(linenum)
|
||||
);
|
||||
}
|
||||
|
||||
inline void parsing_warning(
|
||||
const fs::path& file,
|
||||
uint linenum, const
|
||||
std::string& message) {
|
||||
std::cerr << "file "+file.string()+": warning: "+message+
|
||||
" at line "+std::to_string(linenum) << std::endl;
|
||||
const fs::path& file, uint linenum, const std::string& message
|
||||
) {
|
||||
std::cerr << "file " + file.string() + ": warning: " + message +
|
||||
" at line " + std::to_string(linenum)
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
inline void source_line(std::stringstream& ss, uint linenum) {
|
||||
ss << "#line " << linenum << "\n";
|
||||
}
|
||||
|
||||
std::string GLSLExtension::process(const fs::path& file, const std::string& source, bool header) {
|
||||
std::string GLSLExtension::process(
|
||||
const fs::path& file, const std::string& source, bool header
|
||||
) {
|
||||
std::stringstream ss;
|
||||
size_t pos = 0;
|
||||
uint linenum = 1;
|
||||
@ -103,43 +106,45 @@ std::string GLSLExtension::process(const fs::path& file, const std::string& sour
|
||||
}
|
||||
// parsing preprocessor directives
|
||||
if (source[pos] == '#') {
|
||||
std::string line = source.substr(pos+1, endline-pos);
|
||||
std::string line = source.substr(pos + 1, endline - pos);
|
||||
util::trim(line);
|
||||
// parsing 'include' directive
|
||||
if (line.find("include") != std::string::npos) {
|
||||
line = line.substr(7);
|
||||
util::trim(line);
|
||||
if (line.length() < 3) {
|
||||
throw parsing_error(file, linenum,
|
||||
"invalid 'include' syntax");
|
||||
throw parsing_error(
|
||||
file, linenum, "invalid 'include' syntax"
|
||||
);
|
||||
}
|
||||
if (line[0] != '<' || line[line.length()-1] != '>') {
|
||||
throw parsing_error(file, linenum,
|
||||
"expected '#include <filename>' syntax");
|
||||
if (line[0] != '<' || line[line.length() - 1] != '>') {
|
||||
throw parsing_error(
|
||||
file, linenum, "expected '#include <filename>' syntax"
|
||||
);
|
||||
}
|
||||
std::string name = line.substr(1, line.length()-2);
|
||||
std::string name = line.substr(1, line.length() - 2);
|
||||
if (!hasHeader(name)) {
|
||||
loadHeader(name);
|
||||
}
|
||||
source_line(ss, 1);
|
||||
ss << getHeader(name) << '\n';
|
||||
pos = endline+1;
|
||||
pos = endline + 1;
|
||||
linenum++;
|
||||
source_line(ss, linenum);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// removing extra 'include' directives
|
||||
else if (line.find("version") != std::string::npos) {
|
||||
parsing_warning(file, linenum, "removed #version directive");
|
||||
pos = endline+1;
|
||||
pos = endline + 1;
|
||||
linenum++;
|
||||
source_line(ss, linenum);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
linenum++;
|
||||
ss << source.substr(pos, endline+1-pos);
|
||||
pos = endline+1;
|
||||
ss << source.substr(pos, endline + 1 - pos);
|
||||
pos = endline + 1;
|
||||
}
|
||||
return ss.str();
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
#ifndef CODERS_GLSL_EXTESION_HPP_
|
||||
#define CODERS_GLSL_EXTESION_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
class ResPaths;
|
||||
|
||||
@ -30,10 +30,10 @@ public:
|
||||
bool hasDefine(const std::string& name) const;
|
||||
|
||||
std::string process(
|
||||
const std::filesystem::path& file,
|
||||
const std::filesystem::path& file,
|
||||
const std::string& source,
|
||||
bool header=false
|
||||
bool header = false
|
||||
);
|
||||
};
|
||||
|
||||
#endif // CODERS_GLSL_EXTESION_HPP_
|
||||
#endif // CODERS_GLSL_EXTESION_HPP_
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
#include "binary_json.hpp"
|
||||
|
||||
#include "gzip.hpp"
|
||||
#include "byte_utils.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "byte_utils.hpp"
|
||||
#include "gzip.hpp"
|
||||
|
||||
using namespace json;
|
||||
using namespace dynamic;
|
||||
|
||||
@ -30,7 +30,7 @@ static void to_binary(ByteBuilder& builder, const Value& value) {
|
||||
if (val >= 0 && val <= 255) {
|
||||
builder.put(BJSON_TYPE_BYTE);
|
||||
builder.put(val);
|
||||
} else if (val >= INT16_MIN && val <= INT16_MAX){
|
||||
} else if (val >= INT16_MIN && val <= INT16_MAX) {
|
||||
builder.put(BJSON_TYPE_INT16);
|
||||
builder.putInt16(val);
|
||||
} else if (val >= INT32_MIN && val <= INT32_MAX) {
|
||||
@ -115,7 +115,7 @@ static Value value_from_binary(ByteReader& reader) {
|
||||
return reader.getString();
|
||||
default:
|
||||
throw std::runtime_error(
|
||||
"type "+std::to_string(typecode)+" is not supported"
|
||||
"type " + std::to_string(typecode) + " is not supported"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
#ifndef CODERS_BINARY_JSON_HPP_
|
||||
#define CODERS_BINARY_JSON_HPP_
|
||||
|
||||
#include "../data/dynamic_fwd.hpp"
|
||||
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "../data/dynamic_fwd.hpp"
|
||||
|
||||
namespace dynamic {
|
||||
class Map;
|
||||
@ -26,9 +26,13 @@ namespace json {
|
||||
inline constexpr int BJSON_TYPE_NULL = 0xC;
|
||||
inline constexpr int BJSON_TYPE_CDOCUMENT = 0x1F;
|
||||
|
||||
std::vector<ubyte> to_binary(const dynamic::Map* obj, bool compress=false);
|
||||
std::vector<ubyte> to_binary(const dynamic::Value& obj, bool compress=false);
|
||||
std::vector<ubyte> to_binary(
|
||||
const dynamic::Map* obj, bool compress = false
|
||||
);
|
||||
std::vector<ubyte> to_binary(
|
||||
const dynamic::Value& obj, bool compress = false
|
||||
);
|
||||
std::shared_ptr<dynamic::Map> from_binary(const ubyte* src, size_t size);
|
||||
}
|
||||
|
||||
#endif // CODERS_BINARY_JSON_HPP_
|
||||
#endif // CODERS_BINARY_JSON_HPP_
|
||||
|
||||
@ -9,7 +9,7 @@ void ByteBuilder::put(ubyte b) {
|
||||
}
|
||||
|
||||
void ByteBuilder::putCStr(const char* str) {
|
||||
size_t size = strlen(str)+1;
|
||||
size_t size = strlen(str) + 1;
|
||||
buffer.reserve(buffer.size() + size);
|
||||
for (size_t i = 0; i < size; i++) {
|
||||
buffer.push_back(str[i]);
|
||||
@ -37,21 +37,21 @@ void ByteBuilder::putInt16(int16_t val) {
|
||||
void ByteBuilder::putInt32(int32_t val) {
|
||||
buffer.reserve(buffer.size() + 4);
|
||||
buffer.push_back(static_cast<ubyte>(val >> 0 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 8 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 16 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 24 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 8 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 16 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 24 & 255));
|
||||
}
|
||||
|
||||
void ByteBuilder::putInt64(int64_t val) {
|
||||
buffer.reserve(buffer.size() + 8);
|
||||
buffer.push_back(static_cast<ubyte> (val >> 0 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 8 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 16 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 24 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 32 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 40 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 48 & 255));
|
||||
buffer.push_back(static_cast<ubyte> (val >> 56 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 0 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 8 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 16 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 24 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 32 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 40 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 48 & 255));
|
||||
buffer.push_back(static_cast<ubyte>(val >> 56 & 255));
|
||||
}
|
||||
|
||||
void ByteBuilder::putFloat32(float val) {
|
||||
@ -102,8 +102,7 @@ ByteReader::ByteReader(const ubyte* data, size_t size)
|
||||
: data(data), size(size), pos(0) {
|
||||
}
|
||||
|
||||
ByteReader::ByteReader(const ubyte* data)
|
||||
: data(data), size(4), pos(0) {
|
||||
ByteReader::ByteReader(const ubyte* data) : data(data), size(4), pos(0) {
|
||||
size = getInt32();
|
||||
}
|
||||
|
||||
@ -112,7 +111,7 @@ void ByteReader::checkMagic(const char* data, size_t size) {
|
||||
throw std::runtime_error("invalid magic number");
|
||||
}
|
||||
for (size_t i = 0; i < size; i++) {
|
||||
if (this->data[pos + i] != (ubyte)data[i]){
|
||||
if (this->data[pos + i] != (ubyte)data[i]) {
|
||||
throw std::runtime_error("invalid magic number");
|
||||
}
|
||||
}
|
||||
@ -130,11 +129,11 @@ ubyte ByteReader::peek() {
|
||||
if (pos == size) {
|
||||
throw std::runtime_error("buffer underflow");
|
||||
}
|
||||
return data[pos];
|
||||
return data[pos];
|
||||
}
|
||||
|
||||
int16_t ByteReader::getInt16() {
|
||||
if (pos+2 > size) {
|
||||
if (pos + 2 > size) {
|
||||
throw std::runtime_error("buffer underflow");
|
||||
}
|
||||
pos += 2;
|
||||
@ -143,7 +142,7 @@ int16_t ByteReader::getInt16() {
|
||||
}
|
||||
|
||||
int32_t ByteReader::getInt32() {
|
||||
if (pos+4 > size) {
|
||||
if (pos + 4 > size) {
|
||||
throw std::runtime_error("buffer underflow");
|
||||
}
|
||||
pos += 4;
|
||||
@ -154,7 +153,7 @@ int32_t ByteReader::getInt32() {
|
||||
}
|
||||
|
||||
int64_t ByteReader::getInt64() {
|
||||
if (pos+8 > size) {
|
||||
if (pos + 8 > size) {
|
||||
throw std::runtime_error("buffer underflow");
|
||||
}
|
||||
pos += 8;
|
||||
@ -183,18 +182,20 @@ double ByteReader::getFloat64() {
|
||||
}
|
||||
|
||||
const char* ByteReader::getCString() {
|
||||
const char* cstr = reinterpret_cast<const char*>(data+pos);
|
||||
const char* cstr = reinterpret_cast<const char*>(data + pos);
|
||||
pos += strlen(cstr) + 1;
|
||||
return cstr;
|
||||
}
|
||||
|
||||
std::string ByteReader::getString() {
|
||||
uint32_t length = (uint32_t)getInt32();
|
||||
if (pos+length > size) {
|
||||
if (pos + length > size) {
|
||||
throw std::runtime_error("buffer underflow");
|
||||
}
|
||||
pos += length;
|
||||
return std::string(reinterpret_cast<const char*>(data+pos-length), length);
|
||||
return std::string(
|
||||
reinterpret_cast<const char*>(data + pos - length), length
|
||||
);
|
||||
}
|
||||
|
||||
bool ByteReader::hasNext() const {
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
#ifndef CODERS_BYTE_UTILS_HPP_
|
||||
#define CODERS_BYTE_UTILS_HPP_
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
/* byteorder: little-endian */
|
||||
class ByteBuilder {
|
||||
std::vector<ubyte> buffer;
|
||||
@ -23,8 +23,8 @@ public:
|
||||
/* Write 32 bit floating-point number */
|
||||
void putFloat32(float val);
|
||||
/* Write 64 bit floating-point number */
|
||||
void putFloat64(double val);
|
||||
|
||||
void putFloat64(double val);
|
||||
|
||||
/* Write string (uint32 length + bytes) */
|
||||
void put(const std::string& s);
|
||||
/* Write sequence of bytes without any header */
|
||||
@ -80,4 +80,4 @@ public:
|
||||
void skip(size_t n);
|
||||
};
|
||||
|
||||
#endif // CODERS_BYTE_UTILS_HPP_
|
||||
#endif // CODERS_BYTE_UTILS_HPP_
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
#include "commons.hpp"
|
||||
|
||||
#include "../util/stringutil.hpp"
|
||||
#include <math.h>
|
||||
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <math.h>
|
||||
|
||||
#include "../util/stringutil.hpp"
|
||||
|
||||
inline double power(double base, int64_t power) {
|
||||
double result = 1.0;
|
||||
@ -21,21 +22,25 @@ parsing_error::parsing_error(
|
||||
uint pos,
|
||||
uint line,
|
||||
uint linestart
|
||||
) : std::runtime_error(message), filename(filename),
|
||||
pos(pos), line(line), linestart(linestart)
|
||||
{
|
||||
)
|
||||
: std::runtime_error(message),
|
||||
filename(filename),
|
||||
pos(pos),
|
||||
line(line),
|
||||
linestart(linestart) {
|
||||
size_t end = source.find("\n", linestart);
|
||||
if (end == std::string::npos) {
|
||||
end = source.length();
|
||||
}
|
||||
this->source = source.substr(linestart, end-linestart);
|
||||
this->source = source.substr(linestart, end - linestart);
|
||||
}
|
||||
|
||||
std::string parsing_error::errorLog() const {
|
||||
std::stringstream ss;
|
||||
uint linepos = pos - linestart;
|
||||
ss << "parsing error in file '" << filename;
|
||||
ss << "' at " << (line+1) << ":" << linepos << ": " << this->what() << "\n";
|
||||
ss << "' at " << (line + 1) << ":" << linepos << ": " << this->what()
|
||||
<< "\n";
|
||||
ss << source << "\n";
|
||||
for (uint i = 0; i < linepos; i++) {
|
||||
ss << " ";
|
||||
@ -44,10 +49,8 @@ std::string parsing_error::errorLog() const {
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
BasicParser::BasicParser(
|
||||
std::string_view file,
|
||||
std::string_view source
|
||||
) : filename(file), source(source) {
|
||||
BasicParser::BasicParser(std::string_view file, std::string_view source)
|
||||
: filename(file), source(source) {
|
||||
}
|
||||
|
||||
void BasicParser::skipWhitespace() {
|
||||
@ -67,7 +70,7 @@ void BasicParser::skipWhitespace() {
|
||||
}
|
||||
|
||||
void BasicParser::skip(size_t n) {
|
||||
n = std::min(n, source.length()-pos);
|
||||
n = std::min(n, source.length() - pos);
|
||||
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
char next = source[pos++];
|
||||
@ -93,10 +96,10 @@ void BasicParser::skipLine() {
|
||||
bool BasicParser::skipTo(const std::string& substring) {
|
||||
size_t idx = source.find(substring, pos);
|
||||
if (idx == std::string::npos) {
|
||||
skip(source.length()-pos);
|
||||
skip(source.length() - pos);
|
||||
return false;
|
||||
} else {
|
||||
skip(idx-pos);
|
||||
skip(idx - pos);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -122,17 +125,16 @@ char BasicParser::nextChar() {
|
||||
void BasicParser::expect(char expected) {
|
||||
char c = peek();
|
||||
if (c != expected) {
|
||||
throw error("'"+std::string({expected})+"' expected");
|
||||
throw error("'" + std::string({expected}) + "' expected");
|
||||
}
|
||||
pos++;
|
||||
}
|
||||
|
||||
void BasicParser::expect(const std::string& substring) {
|
||||
if (substring.empty())
|
||||
return;
|
||||
if (substring.empty()) return;
|
||||
for (uint i = 0; i < substring.length(); i++) {
|
||||
if (source.length() <= pos + i || source[pos+i] != substring[i]) {
|
||||
throw error(util::quote(substring)+" expected");
|
||||
if (source.length() <= pos + i || source[pos + i] != substring[i]) {
|
||||
throw error(util::quote(substring) + " expected");
|
||||
}
|
||||
}
|
||||
pos += substring.length();
|
||||
@ -158,7 +160,7 @@ void BasicParser::goBack(size_t count) {
|
||||
if (pos < count) {
|
||||
throw std::runtime_error("pos < jump");
|
||||
}
|
||||
if (pos) {
|
||||
if (pos) {
|
||||
pos -= count;
|
||||
}
|
||||
}
|
||||
@ -205,7 +207,7 @@ std::string_view BasicParser::readUntil(char c) {
|
||||
while (hasNext() && source[pos] != c) {
|
||||
pos++;
|
||||
}
|
||||
return source.substr(start, pos-start);
|
||||
return source.substr(start, pos - start);
|
||||
}
|
||||
|
||||
std::string_view BasicParser::readUntilEOL() {
|
||||
@ -213,7 +215,7 @@ std::string_view BasicParser::readUntilEOL() {
|
||||
while (hasNext() && source[pos] != '\r' && source[pos] != '\n') {
|
||||
pos++;
|
||||
}
|
||||
return source.substr(start, pos-start);
|
||||
return source.substr(start, pos - start);
|
||||
}
|
||||
|
||||
std::string BasicParser::parseName() {
|
||||
@ -229,7 +231,7 @@ std::string BasicParser::parseName() {
|
||||
while (hasNext() && is_identifier_part(source[pos])) {
|
||||
pos++;
|
||||
}
|
||||
return std::string(source.substr(start, pos-start));
|
||||
return std::string(source.substr(start, pos - start));
|
||||
}
|
||||
|
||||
int64_t BasicParser::parseSimpleInt(int base) {
|
||||
@ -272,14 +274,14 @@ dynamic::Value BasicParser::parseNumber() {
|
||||
dynamic::Value BasicParser::parseNumber(int sign) {
|
||||
char c = peek();
|
||||
int base = 10;
|
||||
if (c == '0' && pos + 1 < source.length() &&
|
||||
(base = is_box(source[pos+1])) != 10) {
|
||||
if (c == '0' && pos + 1 < source.length() &&
|
||||
(base = is_box(source[pos + 1])) != 10) {
|
||||
pos += 2;
|
||||
return parseSimpleInt(base);
|
||||
} else if (c == 'i' && pos + 2 < source.length() && source[pos+1] == 'n' && source[pos+2] == 'f') {
|
||||
} else if (c == 'i' && pos + 2 < source.length() && source[pos + 1] == 'n' && source[pos + 2] == 'f') {
|
||||
pos += 3;
|
||||
return INFINITY * sign;
|
||||
} else if (c == 'n' && pos + 2 < source.length() && source[pos+1] == 'a' && source[pos+2] == 'n') {
|
||||
} else if (c == 'n' && pos + 2 < source.length() && source[pos + 1] == 'a' && source[pos + 2] == 'n') {
|
||||
pos += 3;
|
||||
return NAN * sign;
|
||||
}
|
||||
@ -294,7 +296,7 @@ dynamic::Value BasicParser::parseNumber(int sign) {
|
||||
if (peek() == '-') {
|
||||
s = -1;
|
||||
pos++;
|
||||
} else if (peek() == '+'){
|
||||
} else if (peek() == '+') {
|
||||
pos++;
|
||||
}
|
||||
return sign * value * power(10.0, s * parseSimpleInt(10));
|
||||
@ -320,7 +322,7 @@ dynamic::Value BasicParser::parseNumber(int sign) {
|
||||
if (peek() == '-') {
|
||||
s = -1;
|
||||
pos++;
|
||||
} else if (peek() == '+'){
|
||||
} else if (peek() == '+') {
|
||||
pos++;
|
||||
}
|
||||
return sign * dvalue * power(10.0, s * parseSimpleInt(10));
|
||||
@ -347,19 +349,40 @@ std::string BasicParser::parseString(char quote, bool closeRequired) {
|
||||
continue;
|
||||
}
|
||||
switch (c) {
|
||||
case 'n': ss << '\n'; break;
|
||||
case 'r': ss << '\r'; break;
|
||||
case 'b': ss << '\b'; break;
|
||||
case 't': ss << '\t'; break;
|
||||
case 'f': ss << '\f'; break;
|
||||
case '\'': ss << '\\'; break;
|
||||
case '"': ss << '"'; break;
|
||||
case '\\': ss << '\\'; break;
|
||||
case '/': ss << '/'; break;
|
||||
case '\n': pos++; continue;
|
||||
case 'n':
|
||||
ss << '\n';
|
||||
break;
|
||||
case 'r':
|
||||
ss << '\r';
|
||||
break;
|
||||
case 'b':
|
||||
ss << '\b';
|
||||
break;
|
||||
case 't':
|
||||
ss << '\t';
|
||||
break;
|
||||
case 'f':
|
||||
ss << '\f';
|
||||
break;
|
||||
case '\'':
|
||||
ss << '\\';
|
||||
break;
|
||||
case '"':
|
||||
ss << '"';
|
||||
break;
|
||||
case '\\':
|
||||
ss << '\\';
|
||||
break;
|
||||
case '/':
|
||||
ss << '/';
|
||||
break;
|
||||
case '\n':
|
||||
pos++;
|
||||
continue;
|
||||
default:
|
||||
throw error("'\\" + std::string({c}) +
|
||||
"' is an illegal escape");
|
||||
throw error(
|
||||
"'\\" + std::string({c}) + "' is an illegal escape"
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
#ifndef CODERS_COMMONS_HPP_
|
||||
#define CODERS_COMMONS_HPP_
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <stdexcept>
|
||||
|
||||
inline int is_box(int c) {
|
||||
switch (c) {
|
||||
case 'B':
|
||||
@ -17,7 +17,7 @@ inline int is_box(int c) {
|
||||
return 8;
|
||||
case 'X':
|
||||
case 'x':
|
||||
return 16;
|
||||
return 16;
|
||||
}
|
||||
return 10;
|
||||
}
|
||||
@ -31,7 +31,8 @@ inline bool is_whitespace(int c) {
|
||||
}
|
||||
|
||||
inline bool is_identifier_start(int c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || c == '.';
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' ||
|
||||
c == '.';
|
||||
}
|
||||
|
||||
inline bool is_identifier_part(int c) {
|
||||
@ -61,10 +62,10 @@ public:
|
||||
|
||||
parsing_error(
|
||||
const std::string& message,
|
||||
std::string_view filename,
|
||||
std::string_view source,
|
||||
uint pos,
|
||||
uint line,
|
||||
std::string_view filename,
|
||||
std::string_view source,
|
||||
uint pos,
|
||||
uint line,
|
||||
uint linestart
|
||||
);
|
||||
std::string errorLog() const;
|
||||
@ -86,16 +87,15 @@ protected:
|
||||
void expect(const std::string& substring);
|
||||
bool isNext(const std::string& substring);
|
||||
void expectNewLine();
|
||||
void goBack(size_t count=1);
|
||||
void goBack(size_t count = 1);
|
||||
void reset();
|
||||
|
||||
int64_t parseSimpleInt(int base);
|
||||
dynamic::Value parseNumber(int sign);
|
||||
dynamic::Value parseNumber();
|
||||
std::string parseString(char chr, bool closeRequired=true);
|
||||
std::string parseString(char chr, bool closeRequired = true);
|
||||
|
||||
parsing_error error(const std::string& message);
|
||||
|
||||
public:
|
||||
std::string_view readUntil(char c);
|
||||
std::string_view readUntilEOL();
|
||||
@ -109,4 +109,4 @@ public:
|
||||
BasicParser(std::string_view file, std::string_view source);
|
||||
};
|
||||
|
||||
#endif // CODERS_COMMONS_HPP_
|
||||
#endif // CODERS_COMMONS_HPP_
|
||||
|
||||
@ -3,12 +3,13 @@
|
||||
#include "byte_utils.hpp"
|
||||
|
||||
#define ZLIB_CONST
|
||||
#include <zlib.h>
|
||||
#include <math.h>
|
||||
#include <zlib.h>
|
||||
|
||||
#include <memory>
|
||||
|
||||
std::vector<ubyte> gzip::compress(const ubyte* src, size_t size) {
|
||||
size_t buffer_size = 23+size*1.01;
|
||||
size_t buffer_size = 23 + size * 1.01;
|
||||
std::vector<ubyte> buffer;
|
||||
buffer.resize(buffer_size);
|
||||
|
||||
@ -23,8 +24,14 @@ std::vector<ubyte> gzip::compress(const ubyte* src, size_t size) {
|
||||
defstream.next_out = buffer.data();
|
||||
|
||||
// compression
|
||||
deflateInit2(&defstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
|
||||
16 + MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
|
||||
deflateInit2(
|
||||
&defstream,
|
||||
Z_DEFAULT_COMPRESSION,
|
||||
Z_DEFLATED,
|
||||
16 + MAX_WBITS,
|
||||
8,
|
||||
Z_DEFAULT_STRATEGY
|
||||
);
|
||||
deflate(&defstream, Z_FINISH);
|
||||
deflateEnd(&defstream);
|
||||
|
||||
@ -35,7 +42,8 @@ std::vector<ubyte> gzip::compress(const ubyte* src, size_t size) {
|
||||
|
||||
std::vector<ubyte> gzip::decompress(const ubyte* src, size_t size) {
|
||||
// getting uncompressed data length from gzip footer
|
||||
size_t decompressed_size = *reinterpret_cast<const uint32_t*>(src+size-4);
|
||||
size_t decompressed_size =
|
||||
*reinterpret_cast<const uint32_t*>(src + size - 4);
|
||||
std::vector<ubyte> buffer;
|
||||
buffer.resize(decompressed_size);
|
||||
|
||||
@ -49,7 +57,7 @@ std::vector<ubyte> gzip::decompress(const ubyte* src, size_t size) {
|
||||
infstream.avail_out = decompressed_size;
|
||||
infstream.next_out = buffer.data();
|
||||
|
||||
inflateInit2(&infstream, 16+MAX_WBITS);
|
||||
inflateInit2(&infstream, 16 + MAX_WBITS);
|
||||
inflate(&infstream, Z_NO_FLUSH);
|
||||
inflateEnd(&infstream);
|
||||
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
#ifndef CODERS_GZIP_HPP_
|
||||
#define CODERS_GZIP_HPP_
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
#include <vector>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
namespace gzip {
|
||||
const unsigned char MAGIC[] = "\x1F\x8B";
|
||||
|
||||
@ -11,11 +12,11 @@ namespace gzip {
|
||||
@param src source bytes array
|
||||
@param size length of source bytes array */
|
||||
std::vector<ubyte> compress(const ubyte* src, size_t size);
|
||||
|
||||
/* Decompress bytes array from GZIP
|
||||
|
||||
/* Decompress bytes array from GZIP
|
||||
@param src GZIP data
|
||||
@param size length of GZIP data */
|
||||
std::vector<ubyte> decompress(const ubyte* src, size_t size);
|
||||
}
|
||||
|
||||
#endif // CODERS_GZIP_HPP_
|
||||
#endif // CODERS_GZIP_HPP_
|
||||
|
||||
@ -1,15 +1,16 @@
|
||||
#include "imageio.hpp"
|
||||
|
||||
#include "png.hpp"
|
||||
#include "../graphics/core/ImageData.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "../graphics/core/ImageData.hpp"
|
||||
#include "png.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
using image_reader = std::function<std::unique_ptr<ImageData>(const std::string&)>;
|
||||
using image_reader =
|
||||
std::function<std::unique_ptr<ImageData>(const std::string&)>;
|
||||
using image_writer = std::function<void(const std::string&, const ImageData*)>;
|
||||
|
||||
static std::unordered_map<std::string, image_reader> readers {
|
||||
@ -35,7 +36,9 @@ inline std::string extensionOf(const std::string& filename) {
|
||||
std::unique_ptr<ImageData> imageio::read(const std::string& filename) {
|
||||
auto found = readers.find(extensionOf(filename));
|
||||
if (found == readers.end()) {
|
||||
throw std::runtime_error("file format is not supported (read): "+filename);
|
||||
throw std::runtime_error(
|
||||
"file format is not supported (read): " + filename
|
||||
);
|
||||
}
|
||||
return std::unique_ptr<ImageData>(found->second(filename));
|
||||
}
|
||||
@ -43,7 +46,9 @@ std::unique_ptr<ImageData> imageio::read(const std::string& filename) {
|
||||
void imageio::write(const std::string& filename, const ImageData* image) {
|
||||
auto found = writers.find(extensionOf(filename));
|
||||
if (found == writers.end()) {
|
||||
throw std::runtime_error("file format is not supported (write): "+filename);
|
||||
throw std::runtime_error(
|
||||
"file format is not supported (write): " + filename
|
||||
);
|
||||
}
|
||||
return found->second(filename, image);
|
||||
}
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
#ifndef CODERS_IMAGEIO_HPP_
|
||||
#define CODERS_IMAGEIO_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
class ImageData;
|
||||
|
||||
@ -16,4 +16,4 @@ namespace imageio {
|
||||
void write(const std::string& filename, const ImageData* image);
|
||||
}
|
||||
|
||||
#endif // CODERS_IMAGEIO_HPP_
|
||||
#endif // CODERS_IMAGEIO_HPP_
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
#include "json.hpp"
|
||||
|
||||
#include "commons.hpp"
|
||||
#include <math.h>
|
||||
|
||||
#include <iomanip>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
|
||||
#include <math.h>
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
#include <memory>
|
||||
#include "commons.hpp"
|
||||
|
||||
using namespace json;
|
||||
using namespace dynamic;
|
||||
@ -19,14 +19,12 @@ class Parser : BasicParser {
|
||||
dynamic::Value parseValue();
|
||||
public:
|
||||
Parser(std::string_view filename, std::string_view source);
|
||||
|
||||
|
||||
std::unique_ptr<dynamic::Map> parse();
|
||||
};
|
||||
|
||||
inline void newline(
|
||||
std::stringstream& ss,
|
||||
bool nice, uint indent,
|
||||
const std::string& indentstr
|
||||
std::stringstream& ss, bool nice, uint indent, const std::string& indentstr
|
||||
) {
|
||||
if (nice) {
|
||||
ss << "\n";
|
||||
@ -39,24 +37,23 @@ inline void newline(
|
||||
}
|
||||
|
||||
void stringifyObj(
|
||||
const Map* obj,
|
||||
std::stringstream& ss,
|
||||
int indent,
|
||||
const std::string& indentstr,
|
||||
const Map* obj,
|
||||
std::stringstream& ss,
|
||||
int indent,
|
||||
const std::string& indentstr,
|
||||
bool nice
|
||||
);
|
||||
|
||||
void stringifyValue(
|
||||
const Value& value,
|
||||
std::stringstream& ss,
|
||||
int indent,
|
||||
const std::string& indentstr,
|
||||
const Value& value,
|
||||
std::stringstream& ss,
|
||||
int indent,
|
||||
const std::string& indentstr,
|
||||
bool nice
|
||||
) {
|
||||
if (auto map = std::get_if<Map_sptr>(&value)) {
|
||||
stringifyObj(map->get(), ss, indent, indentstr, nice);
|
||||
}
|
||||
else if (auto listptr = std::get_if<List_sptr>(&value)) {
|
||||
} else if (auto listptr = std::get_if<List_sptr>(&value)) {
|
||||
auto list = *listptr;
|
||||
if (list->size() == 0) {
|
||||
ss << "[]";
|
||||
@ -68,7 +65,7 @@ void stringifyValue(
|
||||
if (i > 0 || nice) {
|
||||
newline(ss, nice, indent, indentstr);
|
||||
}
|
||||
stringifyValue(value, ss, indent+1, indentstr, nice);
|
||||
stringifyValue(value, ss, indent + 1, indentstr, nice);
|
||||
if (i + 1 < list->size()) {
|
||||
ss << ',';
|
||||
}
|
||||
@ -91,10 +88,10 @@ void stringifyValue(
|
||||
}
|
||||
|
||||
void stringifyObj(
|
||||
const Map* obj,
|
||||
std::stringstream& ss,
|
||||
int indent,
|
||||
const std::string& indentstr,
|
||||
const Map* obj,
|
||||
std::stringstream& ss,
|
||||
int indent,
|
||||
const std::string& indentstr,
|
||||
bool nice
|
||||
) {
|
||||
if (obj == nullptr) {
|
||||
@ -114,22 +111,20 @@ void stringifyObj(
|
||||
}
|
||||
const Value& value = entry.second;
|
||||
ss << util::escape(key) << ": ";
|
||||
stringifyValue(value, ss, indent+1, indentstr, nice);
|
||||
stringifyValue(value, ss, indent + 1, indentstr, nice);
|
||||
index++;
|
||||
if (index < obj->values.size()) {
|
||||
ss << ',';
|
||||
}
|
||||
}
|
||||
if (nice) {
|
||||
newline(ss, true, indent-1, indentstr);
|
||||
newline(ss, true, indent - 1, indentstr);
|
||||
}
|
||||
ss << '}';
|
||||
}
|
||||
|
||||
std::string json::stringify(
|
||||
const Map* obj,
|
||||
bool nice,
|
||||
const std::string& indent
|
||||
const Map* obj, bool nice, const std::string& indent
|
||||
) {
|
||||
std::stringstream ss;
|
||||
stringifyObj(obj, ss, 1, indent, nice);
|
||||
@ -137,17 +132,15 @@ std::string json::stringify(
|
||||
}
|
||||
|
||||
std::string json::stringify(
|
||||
const dynamic::Value& value,
|
||||
bool nice,
|
||||
const std::string& indent
|
||||
const dynamic::Value& value, bool nice, const std::string& indent
|
||||
) {
|
||||
std::stringstream ss;
|
||||
stringifyValue(value, ss, 1, indent, nice);
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
Parser::Parser(std::string_view filename, std::string_view source)
|
||||
: BasicParser(filename, source) {
|
||||
Parser::Parser(std::string_view filename, std::string_view source)
|
||||
: BasicParser(filename, source) {
|
||||
}
|
||||
|
||||
std::unique_ptr<Map> Parser::parse() {
|
||||
@ -239,10 +232,12 @@ Value Parser::parseValue() {
|
||||
pos++;
|
||||
return parseString(next);
|
||||
}
|
||||
throw error("unexpected character '"+std::string({next})+"'");
|
||||
throw error("unexpected character '" + std::string({next}) + "'");
|
||||
}
|
||||
|
||||
dynamic::Map_sptr json::parse(std::string_view filename, std::string_view source) {
|
||||
dynamic::Map_sptr json::parse(
|
||||
std::string_view filename, std::string_view source
|
||||
) {
|
||||
Parser parser(filename, source);
|
||||
return parser.parse();
|
||||
}
|
||||
|
||||
@ -1,28 +1,23 @@
|
||||
#ifndef CODERS_JSON_HPP_
|
||||
#define CODERS_JSON_HPP_
|
||||
|
||||
#include "binary_json.hpp"
|
||||
#include <string>
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
#include <string>
|
||||
#include "binary_json.hpp"
|
||||
|
||||
namespace json {
|
||||
dynamic::Map_sptr parse(std::string_view filename, std::string_view source);
|
||||
dynamic::Map_sptr parse(std::string_view source);
|
||||
|
||||
std::string stringify(
|
||||
const dynamic::Map* obj,
|
||||
bool nice,
|
||||
const std::string& indent
|
||||
const dynamic::Map* obj, bool nice, const std::string& indent
|
||||
);
|
||||
|
||||
std::string stringify(
|
||||
const dynamic::Value& value,
|
||||
bool nice,
|
||||
const std::string& indent
|
||||
const dynamic::Value& value, bool nice, const std::string& indent
|
||||
);
|
||||
}
|
||||
|
||||
#endif // CODERS_JSON_HPP_
|
||||
#endif // CODERS_JSON_HPP_
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
#include "obj.hpp"
|
||||
|
||||
#include "commons.hpp"
|
||||
#include "../graphics/core/Model.hpp"
|
||||
#include "commons.hpp"
|
||||
|
||||
using namespace model;
|
||||
|
||||
@ -34,8 +34,7 @@ class ObjParser : BasicParser {
|
||||
} while (peekInLine() != '\n' && ++i < 3);
|
||||
|
||||
vertices.push_back(Vertex {
|
||||
coords[indices[0]], uvs[indices[1]], normals[indices[2]]
|
||||
});
|
||||
coords[indices[0]], uvs[indices[1]], normals[indices[2]]});
|
||||
}
|
||||
}
|
||||
if (peekInLine() != '\n' && hasNext()) {
|
||||
@ -51,7 +50,8 @@ class ObjParser : BasicParser {
|
||||
}
|
||||
}
|
||||
public:
|
||||
ObjParser(const std::string_view file, const std::string_view src) : BasicParser(file, src) {
|
||||
ObjParser(const std::string_view file, const std::string_view src)
|
||||
: BasicParser(file, src) {
|
||||
}
|
||||
|
||||
std::unique_ptr<Model> parse() {
|
||||
@ -111,7 +111,7 @@ public:
|
||||
}
|
||||
skipLine();
|
||||
}
|
||||
} while(hasNext());
|
||||
} while (hasNext());
|
||||
model->clean();
|
||||
return model;
|
||||
}
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
#ifndef CODERS_OBJ_HPP_
|
||||
#define CODERS_OBJ_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
/// Wavefont OBJ files parser
|
||||
|
||||
@ -16,4 +16,4 @@ namespace obj {
|
||||
);
|
||||
}
|
||||
|
||||
#endif // CODERS_OBJ_HPP_
|
||||
#endif // CODERS_OBJ_HPP_
|
||||
|
||||
@ -1,13 +1,14 @@
|
||||
#include "ogg.hpp"
|
||||
|
||||
#include "../debug/Logger.hpp"
|
||||
#include "../audio/audio.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <vorbis/codec.h>
|
||||
#include <vorbis/vorbisfile.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "../audio/audio.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
static debug::Logger logger("ogg");
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
@ -15,14 +16,21 @@ using namespace audio;
|
||||
|
||||
static inline std::string vorbis_error_message(int code) {
|
||||
switch (code) {
|
||||
case 0: return "no error";
|
||||
case OV_EREAD: return "a read from media returned an error";
|
||||
case OV_ENOTVORBIS: return "the given file/data was not recognized as Ogg Vorbis data";
|
||||
case OV_EVERSION: return "vorbis version mismatch";
|
||||
case OV_EBADHEADER: return "invalid Vorbis bitstream header";
|
||||
case OV_EFAULT: return "internal logic fault";
|
||||
case OV_EINVAL: return "invalid read operation";
|
||||
case OV_EBADLINK:
|
||||
case 0:
|
||||
return "no error";
|
||||
case OV_EREAD:
|
||||
return "a read from media returned an error";
|
||||
case OV_ENOTVORBIS:
|
||||
return "the given file/data was not recognized as Ogg Vorbis data";
|
||||
case OV_EVERSION:
|
||||
return "vorbis version mismatch";
|
||||
case OV_EBADHEADER:
|
||||
return "invalid Vorbis bitstream header";
|
||||
case OV_EFAULT:
|
||||
return "internal logic fault";
|
||||
case OV_EINVAL:
|
||||
return "invalid read operation";
|
||||
case OV_EBADLINK:
|
||||
return "the given link exists in the Vorbis data stream,"
|
||||
" but is not decipherable due to garbacge or corruption";
|
||||
case OV_ENOSEEK:
|
||||
@ -30,15 +38,17 @@ static inline std::string vorbis_error_message(int code) {
|
||||
case OV_EIMPL:
|
||||
return "feature not implemented";
|
||||
default:
|
||||
return "unknown error ["+std::to_string(code)+"]";
|
||||
return "unknown error [" + std::to_string(code) + "]";
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<audio::PCM> ogg::load_pcm(const fs::path& file, bool headerOnly) {
|
||||
std::unique_ptr<audio::PCM> ogg::load_pcm(
|
||||
const fs::path& file, bool headerOnly
|
||||
) {
|
||||
OggVorbis_File vf;
|
||||
int code;
|
||||
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));
|
||||
}
|
||||
std::vector<char> data;
|
||||
|
||||
@ -59,9 +69,12 @@ std::unique_ptr<audio::PCM> ogg::load_pcm(const fs::path& file, bool headerOnly)
|
||||
if (ret == 0) {
|
||||
eof = true;
|
||||
} else if (ret < 0) {
|
||||
logger.error() << "ogg::load_pcm: " << vorbis_error_message(ret);
|
||||
logger.error()
|
||||
<< "ogg::load_pcm: " << vorbis_error_message(ret);
|
||||
} else {
|
||||
data.insert(data.end(), std::begin(buffer), std::begin(buffer)+ret);
|
||||
data.insert(
|
||||
data.end(), std::begin(buffer), std::begin(buffer) + ret
|
||||
);
|
||||
}
|
||||
}
|
||||
totalSamples = data.size() / channels / 2;
|
||||
@ -103,7 +116,8 @@ public:
|
||||
int bitstream = 0;
|
||||
long bytes = ov_read(&vf, buffer, bufferSize, 0, 2, true, &bitstream);
|
||||
if (bytes < 0) {
|
||||
logger.error() << "ogg::load_pcm: " << vorbis_error_message(bytes) << " " << bytes;
|
||||
logger.error() << "ogg::load_pcm: " << vorbis_error_message(bytes)
|
||||
<< " " << bytes;
|
||||
return PCMStream::ERROR;
|
||||
}
|
||||
return bytes;
|
||||
@ -156,7 +170,7 @@ std::unique_ptr<PCMStream> ogg::create_stream(const fs::path& file) {
|
||||
OggVorbis_File vf;
|
||||
int code;
|
||||
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>(vf);
|
||||
}
|
||||
|
||||
@ -9,8 +9,12 @@ namespace audio {
|
||||
}
|
||||
|
||||
namespace ogg {
|
||||
std::unique_ptr<audio::PCM> load_pcm(const std::filesystem::path& file, bool headerOnly);
|
||||
std::unique_ptr<audio::PCMStream> create_stream(const std::filesystem::path& file);
|
||||
std::unique_ptr<audio::PCM> load_pcm(
|
||||
const std::filesystem::path& file, bool headerOnly
|
||||
);
|
||||
std::unique_ptr<audio::PCMStream> create_stream(
|
||||
const std::filesystem::path& file
|
||||
);
|
||||
}
|
||||
|
||||
#endif // CODERS_OGG_HPP_
|
||||
#endif // CODERS_OGG_HPP_
|
||||
|
||||
@ -1,12 +1,13 @@
|
||||
#include "png.hpp"
|
||||
|
||||
#include "../graphics/core/ImageData.hpp"
|
||||
#include "../graphics/core/GLTexture.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
#include <GL/glew.h>
|
||||
|
||||
#include <iostream>
|
||||
#include <GL/glew.h>
|
||||
|
||||
#include "../debug/Logger.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../graphics/core/GLTexture.hpp"
|
||||
#include "../graphics/core/ImageData.hpp"
|
||||
|
||||
static debug::Logger logger("png-coder");
|
||||
|
||||
@ -18,7 +19,9 @@ static debug::Logger logger("png-coder");
|
||||
#include <png.h>
|
||||
|
||||
// returns 0 if all-right, 1 otherwise
|
||||
int _png_write(const char* filename, uint width, uint height, const ubyte* data, bool alpha) {
|
||||
int _png_write(
|
||||
const char* filename, uint width, uint height, const ubyte* data, bool alpha
|
||||
) {
|
||||
uint pixsize = alpha ? 4 : 3;
|
||||
|
||||
// Open file for writing (binary mode)
|
||||
@ -30,7 +33,9 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data,
|
||||
}
|
||||
|
||||
// Initialize write structure
|
||||
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
|
||||
png_structp png_ptr = png_create_write_struct(
|
||||
PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr
|
||||
);
|
||||
if (png_ptr == nullptr) {
|
||||
logger.error() << "could not allocate write struct";
|
||||
fclose(fp);
|
||||
@ -43,9 +48,8 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data,
|
||||
logger.error() << "could not allocate info struct";
|
||||
fclose(fp);
|
||||
png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
|
||||
png_destroy_write_struct(&png_ptr, (png_infopp)nullptr);
|
||||
png_destroy_write_struct(&png_ptr, (png_infopp) nullptr);
|
||||
return 1;
|
||||
|
||||
}
|
||||
|
||||
// Setup Exception handling
|
||||
@ -60,13 +64,17 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data,
|
||||
png_init_io(png_ptr, fp);
|
||||
|
||||
// Write header (8 bit colour depth)
|
||||
png_set_IHDR(png_ptr, info_ptr, width, height,
|
||||
8,
|
||||
alpha ? PNG_COLOR_TYPE_RGBA :
|
||||
PNG_COLOR_TYPE_RGB,
|
||||
PNG_INTERLACE_NONE,
|
||||
PNG_COMPRESSION_TYPE_BASE,
|
||||
PNG_FILTER_TYPE_BASE);
|
||||
png_set_IHDR(
|
||||
png_ptr,
|
||||
info_ptr,
|
||||
width,
|
||||
height,
|
||||
8,
|
||||
alpha ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_RGB,
|
||||
PNG_INTERLACE_NONE,
|
||||
PNG_COMPRESSION_TYPE_BASE,
|
||||
PNG_FILTER_TYPE_BASE
|
||||
);
|
||||
|
||||
png_write_info(png_ptr, info_ptr);
|
||||
|
||||
@ -75,7 +83,8 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data,
|
||||
for (uint y = 0; y < height; y++) {
|
||||
for (uint x = 0; x < width; x++) {
|
||||
for (uint i = 0; i < pixsize; i++) {
|
||||
row[x * pixsize + i] = (png_byte)data[(y * width + x) * pixsize + i];
|
||||
row[x * pixsize + i] =
|
||||
(png_byte)data[(y * width + x) * pixsize + i];
|
||||
}
|
||||
}
|
||||
png_write_row(png_ptr, row.get());
|
||||
@ -90,29 +99,31 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data,
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::unique_ptr<ImageData> _png_load(const char* file){
|
||||
std::unique_ptr<ImageData> _png_load(const char* file) {
|
||||
FILE* fp = nullptr;
|
||||
if ((fp = fopen(file, "rb")) == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
png_struct* png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
|
||||
png_struct* png = png_create_read_struct(
|
||||
PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr
|
||||
);
|
||||
if (png == nullptr) {
|
||||
fclose(fp);
|
||||
return nullptr;
|
||||
}
|
||||
png_info* info = png_create_info_struct(png);
|
||||
if (info == nullptr) {
|
||||
png_destroy_read_struct(&png, (png_info**) nullptr, (png_info**) nullptr);
|
||||
png_destroy_read_struct(&png, (png_info**)nullptr, (png_info**)nullptr);
|
||||
fclose(fp);
|
||||
return nullptr;
|
||||
}
|
||||
png_info* end_info = png_create_info_struct(png);
|
||||
if (end_info == nullptr) {
|
||||
png_destroy_read_struct(&png, (png_info**) nullptr, (png_info**) nullptr);
|
||||
png_destroy_read_struct(&png, (png_info**)nullptr, (png_info**)nullptr);
|
||||
fclose(fp);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
|
||||
if (setjmp(png_jmpbuf(png))) {
|
||||
png_destroy_read_struct(&png, &info, &end_info);
|
||||
fclose(fp);
|
||||
@ -122,46 +133,42 @@ std::unique_ptr<ImageData> _png_load(const char* file){
|
||||
png_init_io(png, fp);
|
||||
png_read_info(png, info);
|
||||
|
||||
int width = png_get_image_width(png, info);
|
||||
int height = png_get_image_height(png, info);
|
||||
int width = png_get_image_width(png, info);
|
||||
int height = png_get_image_height(png, info);
|
||||
png_byte color_type = png_get_color_type(png, info);
|
||||
int bit_depth = png_get_bit_depth(png, info);
|
||||
int bit_depth = png_get_bit_depth(png, info);
|
||||
|
||||
if(bit_depth == 16)
|
||||
png_set_strip_16(png);
|
||||
if (bit_depth == 16) png_set_strip_16(png);
|
||||
|
||||
if(color_type == PNG_COLOR_TYPE_PALETTE)
|
||||
png_set_palette_to_rgb(png);
|
||||
if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png);
|
||||
|
||||
if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
|
||||
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
|
||||
png_set_expand_gray_1_2_4_to_8(png);
|
||||
|
||||
if(png_get_valid(png, info, PNG_INFO_tRNS))
|
||||
png_set_tRNS_to_alpha(png);
|
||||
if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png);
|
||||
|
||||
// These color_type don't have an alpha channel then fill it with 0xff.
|
||||
if(color_type == PNG_COLOR_TYPE_RGB ||
|
||||
color_type == PNG_COLOR_TYPE_GRAY ||
|
||||
if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY ||
|
||||
color_type == PNG_COLOR_TYPE_PALETTE)
|
||||
png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
|
||||
|
||||
if(color_type == PNG_COLOR_TYPE_GRAY ||
|
||||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
|
||||
if (color_type == PNG_COLOR_TYPE_GRAY ||
|
||||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
|
||||
png_set_gray_to_rgb(png);
|
||||
|
||||
png_read_update_info(png, info);
|
||||
|
||||
int row_bytes = png_get_rowbytes(png, info);
|
||||
//color_type = png_get_color_type(png, info);
|
||||
// png_get_color_type returns 2 (RGB) but raster always have alpha channel
|
||||
// due to PNG_FILLER_AFTER
|
||||
// color_type = png_get_color_type(png, info);
|
||||
// png_get_color_type returns 2 (RGB) but raster always have alpha channel
|
||||
// due to PNG_FILLER_AFTER
|
||||
|
||||
color_type = 6;
|
||||
bit_depth = png_get_bit_depth(png, info);
|
||||
bit_depth = png_get_bit_depth(png, info);
|
||||
|
||||
auto image_data = std::make_unique<png_byte[]>(row_bytes * height);
|
||||
auto row_pointers = std::make_unique<png_byte*[]>(height);
|
||||
for (int i = 0; i < height; ++i ) {
|
||||
for (int i = 0; i < height; ++i) {
|
||||
row_pointers[height - 1 - i] = image_data.get() + i * row_bytes;
|
||||
}
|
||||
png_read_image(png, row_pointers.get());
|
||||
@ -175,29 +182,34 @@ std::unique_ptr<ImageData> _png_load(const char* file){
|
||||
format = ImageFormat::rgb888;
|
||||
break;
|
||||
default:
|
||||
logger.error() << "color type " << color_type << " is not supported!";
|
||||
logger.error() << "color type " << color_type
|
||||
<< " is not supported!";
|
||||
png_destroy_read_struct(&png, &info, &end_info);
|
||||
fclose(fp);
|
||||
return nullptr;
|
||||
}
|
||||
auto image = std::make_unique<ImageData>(format, width, height, std::move(image_data));
|
||||
auto image = std::make_unique<ImageData>(
|
||||
format, width, height, std::move(image_data)
|
||||
);
|
||||
png_destroy_read_struct(&png, &info, &end_info);
|
||||
fclose(fp);
|
||||
return image;
|
||||
}
|
||||
|
||||
#else
|
||||
#include <inttypes.h>
|
||||
#include <spng.h>
|
||||
#include <stdio.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
static const int SPNG_SUCCESS = 0;
|
||||
//returns spng result code
|
||||
int _png_write(const char* filename, uint width, uint height, const ubyte* data, bool alpha) {
|
||||
// returns spng result code
|
||||
int _png_write(
|
||||
const char* filename, uint width, uint height, const ubyte* data, bool alpha
|
||||
) {
|
||||
int fmt;
|
||||
int ret = 0;
|
||||
spng_ctx* ctx = nullptr;
|
||||
spng_ihdr ihdr = { 0 };
|
||||
spng_ihdr ihdr = {0};
|
||||
uint pixsize = alpha ? 4 : 3;
|
||||
|
||||
ctx = spng_ctx_new(SPNG_CTX_ENCODER);
|
||||
@ -205,12 +217,19 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data,
|
||||
|
||||
ihdr.width = width;
|
||||
ihdr.height = height;
|
||||
ihdr.color_type = alpha ? SPNG_COLOR_TYPE_TRUECOLOR_ALPHA : SPNG_COLOR_TYPE_TRUECOLOR;
|
||||
ihdr.color_type =
|
||||
alpha ? SPNG_COLOR_TYPE_TRUECOLOR_ALPHA : SPNG_COLOR_TYPE_TRUECOLOR;
|
||||
ihdr.bit_depth = 8;
|
||||
|
||||
spng_set_ihdr(ctx, &ihdr);
|
||||
fmt = SPNG_FMT_PNG;
|
||||
ret = spng_encode_image(ctx, data, (size_t)width * (size_t)height * pixsize , fmt, SPNG_ENCODE_FINALIZE);
|
||||
ret = spng_encode_image(
|
||||
ctx,
|
||||
data,
|
||||
(size_t)width * (size_t)height * pixsize,
|
||||
fmt,
|
||||
SPNG_ENCODE_FINALIZE
|
||||
);
|
||||
if (ret != SPNG_SUCCESS) {
|
||||
logger.error() << "spng_encode_image() error: " << spng_strerror(ret);
|
||||
spng_ctx_free(ctx);
|
||||
@ -222,21 +241,20 @@ int _png_write(const char* filename, uint width, uint height, const ubyte* data,
|
||||
|
||||
if (png_buf == nullptr) {
|
||||
logger.error() << "spng_get_png_buffer() error: " << spng_strerror(ret);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
files::write_bytes(filename, (const unsigned char*)png_buf, png_size);
|
||||
}
|
||||
spng_ctx_free(ctx);
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::unique_ptr<ImageData> _png_load(const char* file){
|
||||
std::unique_ptr<ImageData> _png_load(const char* file) {
|
||||
int r = 0;
|
||||
FILE *png = nullptr;
|
||||
spng_ctx *ctx = nullptr;
|
||||
FILE* png = nullptr;
|
||||
spng_ctx* ctx = nullptr;
|
||||
|
||||
png = fopen(file, "rb");
|
||||
if (png == nullptr){
|
||||
if (png == nullptr) {
|
||||
logger.error() << "could not to open file " << file;
|
||||
return nullptr;
|
||||
}
|
||||
@ -244,31 +262,32 @@ std::unique_ptr<ImageData> _png_load(const char* file){
|
||||
fseek(png, 0, SEEK_END);
|
||||
long siz_pngbuf = ftell(png);
|
||||
rewind(png);
|
||||
if(siz_pngbuf < 1) {
|
||||
if (siz_pngbuf < 1) {
|
||||
fclose(png);
|
||||
logger.error() << "could not to read file " << file;
|
||||
return nullptr;
|
||||
}
|
||||
auto pngbuf = std::make_unique<char[]>(siz_pngbuf);
|
||||
if(fread(pngbuf.get(), siz_pngbuf, 1, png) != 1){ //check of read elements count
|
||||
if (fread(pngbuf.get(), siz_pngbuf, 1, png) !=
|
||||
1) { // check of read elements count
|
||||
fclose(png);
|
||||
logger.error() << "fread() failed: " << file;
|
||||
return nullptr;
|
||||
}
|
||||
fclose(png); // <- finally closing file
|
||||
fclose(png); // <- finally closing file
|
||||
ctx = spng_ctx_new(0);
|
||||
if (ctx == nullptr){
|
||||
if (ctx == nullptr) {
|
||||
logger.error() << "spng_ctx_new() failed";
|
||||
return nullptr;
|
||||
}
|
||||
r = spng_set_crc_action(ctx, SPNG_CRC_USE, SPNG_CRC_USE);
|
||||
if (r != SPNG_SUCCESS){
|
||||
if (r != SPNG_SUCCESS) {
|
||||
spng_ctx_free(ctx);
|
||||
logger.error() << "spng_set_crc_action(): " << spng_strerror(r);
|
||||
return nullptr;
|
||||
}
|
||||
r = spng_set_png_buffer(ctx, pngbuf.get(), siz_pngbuf);
|
||||
if (r != SPNG_SUCCESS){
|
||||
if (r != SPNG_SUCCESS) {
|
||||
spng_ctx_free(ctx);
|
||||
logger.error() << "spng_set_png_buffer(): " << spng_strerror(r);
|
||||
return nullptr;
|
||||
@ -276,7 +295,7 @@ std::unique_ptr<ImageData> _png_load(const char* file){
|
||||
|
||||
spng_ihdr ihdr;
|
||||
r = spng_get_ihdr(ctx, &ihdr);
|
||||
if (r != SPNG_SUCCESS){
|
||||
if (r != SPNG_SUCCESS) {
|
||||
spng_ctx_free(ctx);
|
||||
logger.error() << "spng_get_ihdr(): " << spng_strerror(r);
|
||||
return nullptr;
|
||||
@ -284,28 +303,30 @@ std::unique_ptr<ImageData> _png_load(const char* file){
|
||||
|
||||
size_t out_size;
|
||||
r = spng_decoded_image_size(ctx, SPNG_FMT_RGBA8, &out_size);
|
||||
if (r != SPNG_SUCCESS){
|
||||
if (r != SPNG_SUCCESS) {
|
||||
spng_ctx_free(ctx);
|
||||
logger.error() << "spng_decoded_image_size(): " << spng_strerror(r);
|
||||
return nullptr;
|
||||
}
|
||||
auto out = std::make_unique<ubyte[]>(out_size);
|
||||
r = spng_decode_image(ctx, out.get(), out_size, SPNG_FMT_RGBA8, 0);
|
||||
if (r != SPNG_SUCCESS){
|
||||
if (r != SPNG_SUCCESS) {
|
||||
spng_ctx_free(ctx);
|
||||
logger.error() << "spng_decode_image(): " << spng_strerror(r);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto flipped = std::make_unique<ubyte[]>(out_size);
|
||||
for (size_t i = 0; i < ihdr.height; i+=1){
|
||||
size_t rowsize = ihdr.width*4;
|
||||
for (size_t j = 0; j < rowsize; j++){
|
||||
flipped[(ihdr.height-i-1)*rowsize+j] = out[i*rowsize+j];
|
||||
for (size_t i = 0; i < ihdr.height; i += 1) {
|
||||
size_t rowsize = ihdr.width * 4;
|
||||
for (size_t j = 0; j < rowsize; j++) {
|
||||
flipped[(ihdr.height - i - 1) * rowsize + j] = out[i * rowsize + j];
|
||||
}
|
||||
}
|
||||
|
||||
auto image = std::make_unique<ImageData>(ImageFormat::rgba8888, ihdr.width, ihdr.height, std::move(flipped));
|
||||
auto image = std::make_unique<ImageData>(
|
||||
ImageFormat::rgba8888, ihdr.width, ihdr.height, std::move(flipped)
|
||||
);
|
||||
spng_ctx_free(ctx);
|
||||
return image;
|
||||
}
|
||||
@ -314,7 +335,7 @@ std::unique_ptr<ImageData> _png_load(const char* file){
|
||||
std::unique_ptr<ImageData> png::load_image(const std::string& filename) {
|
||||
auto image = _png_load(filename.c_str());
|
||||
if (image == nullptr) {
|
||||
throw std::runtime_error("could not load image "+filename);
|
||||
throw std::runtime_error("could not load image " + filename);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
@ -328,10 +349,10 @@ std::unique_ptr<Texture> png::load_texture(const std::string& filename) {
|
||||
|
||||
void png::write_image(const std::string& filename, const ImageData* image) {
|
||||
_png_write(
|
||||
filename.c_str(),
|
||||
image->getWidth(),
|
||||
image->getHeight(),
|
||||
(const ubyte*)image->getData(),
|
||||
filename.c_str(),
|
||||
image->getWidth(),
|
||||
image->getHeight(),
|
||||
(const ubyte*)image->getData(),
|
||||
image->getFormat() == ImageFormat::rgba8888
|
||||
);
|
||||
}
|
||||
|
||||
@ -13,4 +13,4 @@ namespace png {
|
||||
std::unique_ptr<Texture> load_texture(const std::string& filename);
|
||||
}
|
||||
|
||||
#endif // CODERS_PNG_HPP_
|
||||
#endif // CODERS_PNG_HPP_
|
||||
|
||||
@ -26,8 +26,7 @@ size_t rle::encode(const ubyte* src, size_t srclen, ubyte* dst) {
|
||||
dst[offset++] = c;
|
||||
c = cnext;
|
||||
counter = 0;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
@ -36,7 +35,6 @@ size_t rle::encode(const ubyte* src, size_t srclen, ubyte* dst) {
|
||||
return offset;
|
||||
}
|
||||
|
||||
|
||||
size_t extrle::decode(const ubyte* src, size_t srclen, ubyte* dst) {
|
||||
size_t offset = 0;
|
||||
for (size_t i = 0; i < srclen;) {
|
||||
@ -66,23 +64,20 @@ size_t extrle::encode(const ubyte* src, size_t srclen, ubyte* dst) {
|
||||
if (counter >= 0x80) {
|
||||
dst[offset++] = 0x80 | (counter & 0x7F);
|
||||
dst[offset++] = counter >> 7;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
dst[offset++] = counter;
|
||||
}
|
||||
dst[offset++] = c;
|
||||
c = cnext;
|
||||
counter = 0;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
if (counter >= 0x80) {
|
||||
dst[offset++] = 0x80 | (counter & 0x7F);
|
||||
dst[offset++] = counter >> 7;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
dst[offset++] = counter;
|
||||
}
|
||||
dst[offset++] = c;
|
||||
|
||||
@ -14,4 +14,4 @@ namespace extrle {
|
||||
size_t decode(const ubyte* src, size_t length, ubyte* dst);
|
||||
}
|
||||
|
||||
#endif // CODERS_RLE_HPP_
|
||||
#endif // CODERS_RLE_HPP_
|
||||
|
||||
@ -1,15 +1,16 @@
|
||||
#include "toml.hpp"
|
||||
|
||||
#include "commons.hpp"
|
||||
#include "../data/setting.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
#include "../files/settings_io.hpp"
|
||||
|
||||
#include <assert.h>
|
||||
#include <math.h>
|
||||
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <assert.h>
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../data/setting.hpp"
|
||||
#include "../files/settings_io.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
#include "commons.hpp"
|
||||
|
||||
using namespace toml;
|
||||
|
||||
@ -48,7 +49,7 @@ class TomlReader : BasicParser {
|
||||
} else {
|
||||
rootMap = *map;
|
||||
}
|
||||
offset = index+1;
|
||||
offset = index + 1;
|
||||
} while (true);
|
||||
}
|
||||
|
||||
@ -93,12 +94,9 @@ class TomlReader : BasicParser {
|
||||
expectNewLine();
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
TomlReader(
|
||||
std::string_view file,
|
||||
std::string_view source)
|
||||
: BasicParser(file, source) {
|
||||
TomlReader(std::string_view file, std::string_view source)
|
||||
: BasicParser(file, source) {
|
||||
root = dynamic::create_map();
|
||||
}
|
||||
|
||||
@ -129,7 +127,7 @@ void toml::parse(
|
||||
for (auto& sectionEntry : (*sectionMap)->values) {
|
||||
const auto& name = sectionEntry.first;
|
||||
auto& value = sectionEntry.second;
|
||||
auto fullname = sectionName+"."+name;
|
||||
auto fullname = sectionName + "." + name;
|
||||
if (handler.has(fullname)) {
|
||||
handler.setValue(fullname, value);
|
||||
}
|
||||
@ -150,9 +148,11 @@ std::string toml::stringify(dynamic::Map& root, const std::string& name) {
|
||||
}
|
||||
for (auto& entry : root.values) {
|
||||
if (auto submap = std::get_if<dynamic::Map_sptr>(&entry.second)) {
|
||||
ss << "\n" << toml::stringify(
|
||||
**submap, name.empty() ? entry.first : name+"."+entry.first
|
||||
);
|
||||
ss << "\n"
|
||||
<< toml::stringify(
|
||||
**submap,
|
||||
name.empty() ? entry.first : name + "." + entry.first
|
||||
);
|
||||
}
|
||||
}
|
||||
return ss.str();
|
||||
@ -166,7 +166,7 @@ std::string toml::stringify(SettingsHandler& handler) {
|
||||
ss << "[" << section.name << "]\n";
|
||||
for (const std::string& key : section.keys) {
|
||||
ss << key << " = ";
|
||||
auto setting = handler.getSetting(section.name+"."+key);
|
||||
auto setting = handler.getSetting(section.name + "." + key);
|
||||
assert(setting != nullptr);
|
||||
if (auto integer = dynamic_cast<IntegerSetting*>(setting)) {
|
||||
ss << integer->get();
|
||||
|
||||
@ -1,21 +1,20 @@
|
||||
#ifndef CODERS_TOML_HPP_
|
||||
#define CODERS_TOML_HPP_
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
#include <string>
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
|
||||
class SettingsHandler;
|
||||
|
||||
namespace toml {
|
||||
std::string stringify(SettingsHandler& handler);
|
||||
std::string stringify(dynamic::Map& root, const std::string& name="");
|
||||
std::string stringify(dynamic::Map& root, const std::string& name = "");
|
||||
dynamic::Map_sptr parse(std::string_view file, std::string_view source);
|
||||
|
||||
void parse(
|
||||
SettingsHandler& handler,
|
||||
std::string_view file,
|
||||
std::string_view source
|
||||
SettingsHandler& handler, std::string_view file, std::string_view source
|
||||
);
|
||||
}
|
||||
|
||||
#endif // CODERS_TOML_HPP_
|
||||
#endif // CODERS_TOML_HPP_
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
#include "wav.hpp"
|
||||
|
||||
#include "../audio/audio.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../audio/audio.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
@ -20,12 +20,11 @@ bool is_big_endian() {
|
||||
return bytes[0] == 1;
|
||||
}
|
||||
|
||||
std::int32_t convert_to_int(char* buffer, std::size_t len){
|
||||
std::int32_t convert_to_int(char* buffer, std::size_t len) {
|
||||
std::int32_t a = 0;
|
||||
if (!is_big_endian()) {
|
||||
std::memcpy(&a, buffer, len);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
for (std::size_t i = 0; i < len; ++i) {
|
||||
reinterpret_cast<char*>(&a)[3 - i] = buffer[i];
|
||||
}
|
||||
@ -44,18 +43,18 @@ class WavStream : public audio::PCMStream {
|
||||
size_t initialPosition;
|
||||
public:
|
||||
WavStream(
|
||||
std::ifstream in,
|
||||
uint channels,
|
||||
std::ifstream in,
|
||||
uint channels,
|
||||
uint bitsPerSample,
|
||||
uint sampleRate,
|
||||
size_t size,
|
||||
size_t initialPosition
|
||||
) : in(std::move(in)),
|
||||
channels(channels),
|
||||
bytesPerSample(bitsPerSample/8),
|
||||
sampleRate(sampleRate),
|
||||
totalSize(size)
|
||||
{
|
||||
)
|
||||
: in(std::move(in)),
|
||||
channels(channels),
|
||||
bytesPerSample(bitsPerSample / 8),
|
||||
sampleRate(sampleRate),
|
||||
totalSize(size) {
|
||||
totalSamples = totalSize / channels / bytesPerSample;
|
||||
this->initialPosition = initialPosition;
|
||||
}
|
||||
@ -74,10 +73,9 @@ public:
|
||||
}
|
||||
return in.gcount();
|
||||
}
|
||||
|
||||
|
||||
void close() override {
|
||||
if (!isOpen())
|
||||
return;
|
||||
if (!isOpen()) return;
|
||||
in.close();
|
||||
}
|
||||
|
||||
@ -110,58 +108,66 @@ public:
|
||||
}
|
||||
|
||||
void seek(size_t position) override {
|
||||
if (!isOpen())
|
||||
return;
|
||||
if (!isOpen()) return;
|
||||
position %= totalSamples;
|
||||
in.clear();
|
||||
in.seekg(initialPosition + position * channels * bytesPerSample, std::ios_base::beg);
|
||||
in.seekg(
|
||||
initialPosition + position * channels * bytesPerSample,
|
||||
std::ios_base::beg
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
std::unique_ptr<audio::PCMStream> wav::create_stream(const fs::path& file) {
|
||||
std::ifstream in(file, std::ios::binary);
|
||||
if(!in.is_open()){
|
||||
throw std::runtime_error("could not to open file '"+file.u8string()+"'");
|
||||
if (!in.is_open()) {
|
||||
throw std::runtime_error(
|
||||
"could not to open file '" + file.u8string() + "'"
|
||||
);
|
||||
}
|
||||
|
||||
char buffer[6];
|
||||
// the RIFF
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not to read RIFF");
|
||||
}
|
||||
if(std::strncmp(buffer, "RIFF", 4) != 0){
|
||||
throw std::runtime_error("file is not a valid WAVE file (header doesn't begin with RIFF)");
|
||||
if (std::strncmp(buffer, "RIFF", 4) != 0) {
|
||||
throw std::runtime_error(
|
||||
"file is not a valid WAVE file (header doesn't begin with RIFF)"
|
||||
);
|
||||
}
|
||||
// the size of the file
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not read size of file");
|
||||
}
|
||||
// the WAVE
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not to read WAVE");
|
||||
}
|
||||
if(std::strncmp(buffer, "WAVE", 4) != 0){
|
||||
throw std::runtime_error("file is not a valid WAVE file (header doesn't contain WAVE)");
|
||||
if (std::strncmp(buffer, "WAVE", 4) != 0) {
|
||||
throw std::runtime_error(
|
||||
"file is not a valid WAVE file (header doesn't contain WAVE)"
|
||||
);
|
||||
}
|
||||
// "fmt/0"
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not read fmt/0");
|
||||
}
|
||||
// this is always 16, the size of the fmt data chunk
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not read the 16");
|
||||
}
|
||||
// PCM should be 1?
|
||||
if(!in.read(buffer, 2)){
|
||||
if (!in.read(buffer, 2)) {
|
||||
throw std::runtime_error("could not read PCM");
|
||||
}
|
||||
// the number of channels
|
||||
if(!in.read(buffer, 2)){
|
||||
if (!in.read(buffer, 2)) {
|
||||
throw std::runtime_error("could not read number of channels");
|
||||
}
|
||||
int channels = convert_to_int(buffer, 2);
|
||||
// sample rate
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not read sample rate");
|
||||
}
|
||||
int sampleRate = convert_to_int(buffer, 4);
|
||||
@ -170,16 +176,19 @@ std::unique_ptr<audio::PCMStream> wav::create_stream(const fs::path& file) {
|
||||
}
|
||||
|
||||
// bitsPerSample
|
||||
if(!in.read(buffer, 2)){
|
||||
if (!in.read(buffer, 2)) {
|
||||
throw std::runtime_error("could not read bits per sample");
|
||||
}
|
||||
int bitsPerSample = convert_to_int(buffer, 2);
|
||||
if (bitsPerSample >= 24) {
|
||||
throw std::runtime_error(std::to_string(bitsPerSample)+" bit depth is not supported by OpenAL");
|
||||
throw std::runtime_error(
|
||||
std::to_string(bitsPerSample) +
|
||||
" bit depth is not supported by OpenAL"
|
||||
);
|
||||
}
|
||||
|
||||
// data chunk header "data"
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not read data chunk header");
|
||||
}
|
||||
|
||||
@ -187,7 +196,7 @@ std::unique_ptr<audio::PCMStream> wav::create_stream(const fs::path& file) {
|
||||
// skip garbage in WAV
|
||||
if (std::strncmp(buffer, "LIST", 4) == 0) {
|
||||
// chunk size
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not read comment chunk size");
|
||||
}
|
||||
int chunkSize = convert_to_int(buffer, 4);
|
||||
@ -195,26 +204,28 @@ std::unique_ptr<audio::PCMStream> wav::create_stream(const fs::path& file) {
|
||||
|
||||
initialOffset += chunkSize + 4;
|
||||
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not read data chunk header");
|
||||
}
|
||||
}
|
||||
|
||||
if(std::strncmp(buffer, "data", 4) != 0){
|
||||
throw std::runtime_error("file is not a valid WAVE file (doesn't have 'data' tag)");
|
||||
if (std::strncmp(buffer, "data", 4) != 0) {
|
||||
throw std::runtime_error(
|
||||
"file is not a valid WAVE file (doesn't have 'data' tag)"
|
||||
);
|
||||
}
|
||||
|
||||
// size of data
|
||||
if(!in.read(buffer, 4)){
|
||||
if (!in.read(buffer, 4)) {
|
||||
throw std::runtime_error("could not read data size");
|
||||
}
|
||||
size_t size = convert_to_int(buffer, 4);
|
||||
|
||||
/* cannot be at the end of file */
|
||||
if(in.eof()){
|
||||
if (in.eof()) {
|
||||
throw std::runtime_error("reached EOF on the file");
|
||||
}
|
||||
if(in.fail()){
|
||||
if (in.fail()) {
|
||||
throw std::runtime_error("fail state set on the file");
|
||||
}
|
||||
return std::make_unique<WavStream>(
|
||||
@ -222,7 +233,9 @@ std::unique_ptr<audio::PCMStream> wav::create_stream(const fs::path& file) {
|
||||
);
|
||||
}
|
||||
|
||||
std::unique_ptr<audio::PCM> wav::load_pcm(const fs::path& file, bool headerOnly) {
|
||||
std::unique_ptr<audio::PCM> wav::load_pcm(
|
||||
const fs::path& file, bool headerOnly
|
||||
) {
|
||||
auto stream = wav::create_stream(file);
|
||||
|
||||
size_t totalSamples = stream->getTotalSamples();
|
||||
@ -232,9 +245,8 @@ std::unique_ptr<audio::PCM> wav::load_pcm(const fs::path& file, bool headerOnly)
|
||||
|
||||
std::vector<char> data;
|
||||
if (!headerOnly) {
|
||||
size_t size = stream->getTotalSamples() *
|
||||
(stream->getBitsPerSample()/8) *
|
||||
stream->getChannels();
|
||||
size_t size = stream->getTotalSamples() *
|
||||
(stream->getBitsPerSample() / 8) * stream->getChannels();
|
||||
data.resize(size);
|
||||
stream->readFully(data.data(), size, false);
|
||||
}
|
||||
|
||||
@ -9,8 +9,12 @@ namespace audio {
|
||||
}
|
||||
|
||||
namespace wav {
|
||||
std::unique_ptr<audio::PCM> load_pcm(const std::filesystem::path& file, bool headerOnly);
|
||||
std::unique_ptr<audio::PCMStream> create_stream(const std::filesystem::path& file);
|
||||
std::unique_ptr<audio::PCM> load_pcm(
|
||||
const std::filesystem::path& file, bool headerOnly
|
||||
);
|
||||
std::unique_ptr<audio::PCMStream> create_stream(
|
||||
const std::filesystem::path& file
|
||||
);
|
||||
}
|
||||
|
||||
#endif // CODERS_WAV_HPP_
|
||||
#endif // CODERS_WAV_HPP_
|
||||
|
||||
@ -1,17 +1,16 @@
|
||||
#include "xml.hpp"
|
||||
|
||||
#include "../util/stringutil.hpp"
|
||||
|
||||
#include <charconv>
|
||||
#include <stdexcept>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
#include "../util/stringutil.hpp"
|
||||
|
||||
using namespace xml;
|
||||
|
||||
Attribute::Attribute(std::string name, std::string text)
|
||||
: name(std::move(name)),
|
||||
text(std::move(text)) {
|
||||
: name(std::move(name)), text(std::move(text)) {
|
||||
}
|
||||
|
||||
const std::string& Attribute::getName() const {
|
||||
@ -42,7 +41,7 @@ glm::vec2 Attribute::asVec2() const {
|
||||
}
|
||||
return glm::vec2(
|
||||
util::parse_double(text, 0, pos),
|
||||
util::parse_double(text, pos+1, text.length()-pos-1)
|
||||
util::parse_double(text, pos + 1, text.length() - pos - 1)
|
||||
);
|
||||
}
|
||||
|
||||
@ -52,14 +51,14 @@ glm::vec3 Attribute::asVec3() const {
|
||||
if (pos1 == std::string::npos) {
|
||||
return glm::vec3(util::parse_double(text, 0, text.length()));
|
||||
}
|
||||
size_t pos2 = text.find(',', pos1+1);
|
||||
size_t pos2 = text.find(',', pos1 + 1);
|
||||
if (pos2 == std::string::npos) {
|
||||
throw std::runtime_error("invalid vec3 value "+util::quote(text));
|
||||
throw std::runtime_error("invalid vec3 value " + util::quote(text));
|
||||
}
|
||||
return glm::vec3(
|
||||
util::parse_double(text, 0, pos1),
|
||||
util::parse_double(text, pos1+1, pos2),
|
||||
util::parse_double(text, pos2+1, text.length()-pos2-1)
|
||||
util::parse_double(text, pos1 + 1, pos2),
|
||||
util::parse_double(text, pos2 + 1, text.length() - pos2 - 1)
|
||||
);
|
||||
}
|
||||
|
||||
@ -69,19 +68,19 @@ glm::vec4 Attribute::asVec4() const {
|
||||
if (pos1 == std::string::npos) {
|
||||
return glm::vec4(util::parse_double(text, 0, text.length()));
|
||||
}
|
||||
size_t pos2 = text.find(',', pos1+1);
|
||||
size_t pos2 = text.find(',', pos1 + 1);
|
||||
if (pos2 == std::string::npos) {
|
||||
throw std::runtime_error("invalid vec4 value "+util::quote(text));
|
||||
throw std::runtime_error("invalid vec4 value " + util::quote(text));
|
||||
}
|
||||
size_t pos3 = text.find(',', pos2+1);
|
||||
size_t pos3 = text.find(',', pos2 + 1);
|
||||
if (pos3 == std::string::npos) {
|
||||
throw std::runtime_error("invalid vec4 value "+util::quote(text));
|
||||
throw std::runtime_error("invalid vec4 value " + util::quote(text));
|
||||
}
|
||||
return glm::vec4(
|
||||
util::parse_double(text, 0, pos1),
|
||||
util::parse_double(text, pos1+1, pos2-pos1-1),
|
||||
util::parse_double(text, pos2+1, pos3-pos2-1),
|
||||
util::parse_double(text, pos3+1, text.length()-pos3-1)
|
||||
util::parse_double(text, pos1 + 1, pos2 - pos1 - 1),
|
||||
util::parse_double(text, pos2 + 1, pos3 - pos2 - 1),
|
||||
util::parse_double(text, pos3 + 1, text.length() - pos3 - 1)
|
||||
);
|
||||
}
|
||||
|
||||
@ -112,7 +111,7 @@ void Node::add(const xmlelement& element) {
|
||||
elements.push_back(element);
|
||||
}
|
||||
|
||||
void Node::set(const std::string& name, const std::string &text) {
|
||||
void Node::set(const std::string& name, const std::string& text) {
|
||||
attrs[name] = Attribute(name, text);
|
||||
}
|
||||
|
||||
@ -123,7 +122,9 @@ const std::string& Node::getTag() const {
|
||||
const xmlattribute& Node::attr(const std::string& name) const {
|
||||
auto found = attrs.find(name);
|
||||
if (found == attrs.end()) {
|
||||
throw std::runtime_error("element <"+tag+" ...> missing attribute "+name);
|
||||
throw std::runtime_error(
|
||||
"element <" + tag + " ...> missing attribute " + name
|
||||
);
|
||||
}
|
||||
return found->second;
|
||||
}
|
||||
@ -158,11 +159,10 @@ const xmlelements_map& Node::getAttributes() const {
|
||||
}
|
||||
|
||||
Document::Document(std::string version, std::string encoding)
|
||||
: version(std::move(version)),
|
||||
encoding(std::move(encoding)) {
|
||||
: version(std::move(version)), encoding(std::move(encoding)) {
|
||||
}
|
||||
|
||||
void Document::setRoot(const xmlelement &element) {
|
||||
void Document::setRoot(const xmlelement& element) {
|
||||
this->root = element;
|
||||
}
|
||||
|
||||
@ -178,7 +178,7 @@ const std::string& Document::getEncoding() const {
|
||||
return encoding;
|
||||
}
|
||||
|
||||
Parser::Parser(std::string_view filename, std::string_view source)
|
||||
Parser::Parser(std::string_view filename, std::string_view source)
|
||||
: BasicParser(filename, source) {
|
||||
}
|
||||
|
||||
@ -190,15 +190,14 @@ xmlelement Parser::parseOpenTag() {
|
||||
while (true) {
|
||||
skipWhitespace();
|
||||
c = peek();
|
||||
if (c == '/' || c == '>' || c == '?')
|
||||
break;
|
||||
if (c == '/' || c == '>' || c == '?') break;
|
||||
std::string attrname = parseXMLName();
|
||||
std::string attrtext = "";
|
||||
skipWhitespace();
|
||||
if (peek() == '=') {
|
||||
nextChar();
|
||||
skipWhitespace();
|
||||
|
||||
|
||||
char quote = peek();
|
||||
if (quote != '\'' && quote != '"') {
|
||||
throw error("string literal expected");
|
||||
@ -251,7 +250,7 @@ std::string Parser::parseText() {
|
||||
}
|
||||
nextChar();
|
||||
}
|
||||
return std::string(source.substr(start, pos-start));
|
||||
return std::string(source.substr(start, pos - start));
|
||||
}
|
||||
|
||||
inline bool is_xml_identifier_start(char c) {
|
||||
@ -259,7 +258,7 @@ inline bool is_xml_identifier_start(char c) {
|
||||
}
|
||||
|
||||
inline bool is_xml_identifier_part(char c) {
|
||||
return is_identifier_part(c) || c == '-' || c == '.' || c == ':';
|
||||
return is_identifier_part(c) || c == '-' || c == '.' || c == ':';
|
||||
}
|
||||
|
||||
std::string Parser::parseXMLName() {
|
||||
@ -271,7 +270,7 @@ std::string Parser::parseXMLName() {
|
||||
while (hasNext() && is_xml_identifier_part(source[pos])) {
|
||||
pos++;
|
||||
}
|
||||
return std::string(source.substr(start, pos-start));
|
||||
return std::string(source.substr(start, pos - start));
|
||||
}
|
||||
|
||||
xmlelement Parser::parseElement() {
|
||||
@ -300,12 +299,12 @@ xmlelement Parser::parseElement() {
|
||||
|
||||
auto element = parseOpenTag();
|
||||
char c = nextChar();
|
||||
|
||||
|
||||
// <element/>
|
||||
if (c == '/') {
|
||||
expect('>');
|
||||
}
|
||||
// <element>...</element>
|
||||
// <element>...</element>
|
||||
else if (c == '>') {
|
||||
skipWhitespace();
|
||||
while (!isNext("</")) {
|
||||
@ -319,7 +318,7 @@ xmlelement Parser::parseElement() {
|
||||
expect(element->getTag());
|
||||
expect('>');
|
||||
}
|
||||
// <element?>
|
||||
// <element?>
|
||||
else {
|
||||
throw error("invalid syntax");
|
||||
}
|
||||
@ -343,13 +342,9 @@ xmldocument xml::parse(const std::string& filename, const std::string& source) {
|
||||
}
|
||||
|
||||
inline void newline(
|
||||
std::stringstream& ss,
|
||||
bool nice,
|
||||
const std::string& indentStr,
|
||||
int indent
|
||||
std::stringstream& ss, bool nice, const std::string& indentStr, int indent
|
||||
) {
|
||||
if (!nice)
|
||||
return;
|
||||
if (!nice) return;
|
||||
ss << '\n';
|
||||
for (int i = 0; i < indent; i++) {
|
||||
ss << indentStr;
|
||||
@ -366,7 +361,7 @@ static void stringifyElement(
|
||||
if (element->isText()) {
|
||||
std::string text = element->attr("#").getText();
|
||||
util::replaceAll(text, "&", "&");
|
||||
util::replaceAll(text, "\"",""");
|
||||
util::replaceAll(text, "\"", """);
|
||||
util::replaceAll(text, "'", "'");
|
||||
util::replaceAll(text, "<", "<");
|
||||
util::replaceAll(text, ">", ">");
|
||||
@ -395,32 +390,29 @@ static void stringifyElement(
|
||||
auto& elements = element->getElements();
|
||||
if (elements.size() == 1 && elements[0]->isText()) {
|
||||
ss << ">";
|
||||
stringifyElement(ss, elements[0], nice, indentStr, indent+1);
|
||||
stringifyElement(ss, elements[0], nice, indentStr, indent + 1);
|
||||
ss << "</" << tag << ">";
|
||||
return;
|
||||
}
|
||||
if (!elements.empty()) {
|
||||
ss << '>';
|
||||
for (auto& sub : elements) {
|
||||
newline(ss, nice, indentStr, indent+1);
|
||||
stringifyElement(ss, sub, nice, indentStr, indent+1);
|
||||
newline(ss, nice, indentStr, indent + 1);
|
||||
stringifyElement(ss, sub, nice, indentStr, indent + 1);
|
||||
}
|
||||
newline(ss, nice, indentStr, indent);
|
||||
ss << "</" << tag << ">";
|
||||
|
||||
|
||||
} else {
|
||||
ss << "/>";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
std::string xml::stringify(
|
||||
const xmldocument& document,
|
||||
bool nice,
|
||||
const std::string& indentStr
|
||||
const xmldocument& document, bool nice, const std::string& indentStr
|
||||
) {
|
||||
std::stringstream ss;
|
||||
|
||||
|
||||
// XML declaration
|
||||
ss << "<?xml version=\"" << document->getVersion();
|
||||
ss << "\" encoding=\"UTF-8\" ?>";
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
#ifndef CODERS_XML_HPP_
|
||||
#define CODERS_XML_HPP_
|
||||
|
||||
#include "commons.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <glm/glm.hpp>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "commons.hpp"
|
||||
|
||||
namespace xml {
|
||||
class Node;
|
||||
@ -37,7 +37,8 @@ namespace xml {
|
||||
glm::vec4 asColor() const;
|
||||
};
|
||||
|
||||
/// @brief XML element class. Text element has tag 'text' and attribute 'text'
|
||||
/// @brief XML element class. Text element has tag 'text' and attribute
|
||||
/// 'text'
|
||||
class Node {
|
||||
std::string tag;
|
||||
std::unordered_map<std::string, xmlattribute> attrs;
|
||||
@ -51,8 +52,8 @@ namespace xml {
|
||||
/// @brief Set attribute value. Creates attribute if does not exists
|
||||
/// @param name attribute name
|
||||
/// @param text attribute value
|
||||
void set(const std::string& name, const std::string &text);
|
||||
|
||||
void set(const std::string& name, const std::string& text);
|
||||
|
||||
/// @brief Get element tag
|
||||
const std::string& getTag() const;
|
||||
|
||||
@ -66,16 +67,17 @@ namespace xml {
|
||||
|
||||
/// @brief Get attribute by 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}
|
||||
const xmlattribute& attr(const std::string& name) const;
|
||||
|
||||
|
||||
/// @brief Get attribute by name
|
||||
/// @param name attribute name
|
||||
/// @param def default value will be returned wrapped in xmlattribute
|
||||
/// if element has no attribute
|
||||
/// if element has no attribute
|
||||
/// @return xmlattribute - {name, value} or {name, def} if not found*/
|
||||
xmlattribute attr(const std::string& name, const std::string& def) const;
|
||||
xmlattribute attr(const std::string& name, const std::string& def)
|
||||
const;
|
||||
|
||||
/// @brief Check if element has attribute
|
||||
/// @param name attribute name
|
||||
@ -101,7 +103,7 @@ namespace xml {
|
||||
public:
|
||||
Document(std::string version, std::string encoding);
|
||||
|
||||
void setRoot(const xmlelement &element);
|
||||
void setRoot(const xmlelement& element);
|
||||
xmlelement getRoot() const;
|
||||
|
||||
const std::string& getVersion() const;
|
||||
@ -123,22 +125,24 @@ namespace xml {
|
||||
xmldocument parse();
|
||||
};
|
||||
|
||||
/// @brief Serialize XML Document to string
|
||||
/// @brief Serialize XML Document to string
|
||||
/// @param document serializing document
|
||||
/// @param nice use human readable format (with indents and line-separators)
|
||||
/// @param indentStr indentation characters sequence (default - 4 spaces)
|
||||
/// @return XML string
|
||||
extern std::string stringify(
|
||||
const xmldocument& document,
|
||||
bool nice=true,
|
||||
const std::string& indentStr=" "
|
||||
bool nice = true,
|
||||
const std::string& indentStr = " "
|
||||
);
|
||||
|
||||
|
||||
/// @brief Read XML Document from string
|
||||
/// @param filename file name will be shown in error messages
|
||||
/// @param source xml source code string
|
||||
/// @return xml document
|
||||
extern xmldocument parse(const std::string& filename, const std::string& source);
|
||||
extern xmldocument parse(
|
||||
const std::string& filename, const std::string& source
|
||||
);
|
||||
}
|
||||
|
||||
#endif // CODERS_XML_HPP_
|
||||
#endif // CODERS_XML_HPP_
|
||||
|
||||
@ -1,29 +1,29 @@
|
||||
#include "Content.hpp"
|
||||
|
||||
#include <glm/glm.hpp>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <glm/glm.hpp>
|
||||
#include <utility>
|
||||
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "../items/ItemDef.hpp"
|
||||
#include "../logic/scripting/scripting.hpp"
|
||||
#include "../objects/EntityDef.hpp"
|
||||
#include "../objects/rigging.hpp"
|
||||
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "ContentPack.hpp"
|
||||
#include "../logic/scripting/scripting.hpp"
|
||||
|
||||
ContentIndices::ContentIndices(
|
||||
ContentUnitIndices<Block> blocks,
|
||||
ContentUnitIndices<ItemDef> items,
|
||||
ContentUnitIndices<EntityDef> entities
|
||||
) : blocks(std::move(blocks)),
|
||||
items(std::move(items)),
|
||||
entities(std::move(entities))
|
||||
{}
|
||||
)
|
||||
: blocks(std::move(blocks)),
|
||||
items(std::move(items)),
|
||||
entities(std::move(entities)) {
|
||||
}
|
||||
|
||||
Content::Content(
|
||||
std::unique_ptr<ContentIndices> indices,
|
||||
std::unique_ptr<ContentIndices> indices,
|
||||
std::unique_ptr<DrawGroups> drawGroups,
|
||||
ContentUnitDefs<Block> blocks,
|
||||
ContentUnitDefs<ItemDef> items,
|
||||
@ -32,15 +32,15 @@ Content::Content(
|
||||
UptrsMap<std::string, BlockMaterial> blockMaterials,
|
||||
UptrsMap<std::string, rigging::SkeletonConfig> skeletons,
|
||||
ResourceIndicesSet resourceIndices
|
||||
) : indices(std::move(indices)),
|
||||
packs(std::move(packs)),
|
||||
blockMaterials(std::move(blockMaterials)),
|
||||
skeletons(std::move(skeletons)),
|
||||
blocks(std::move(blocks)),
|
||||
items(std::move(items)),
|
||||
entities(std::move(entities)),
|
||||
drawGroups(std::move(drawGroups))
|
||||
{
|
||||
)
|
||||
: indices(std::move(indices)),
|
||||
packs(std::move(packs)),
|
||||
blockMaterials(std::move(blockMaterials)),
|
||||
skeletons(std::move(skeletons)),
|
||||
blocks(std::move(blocks)),
|
||||
items(std::move(items)),
|
||||
entities(std::move(entities)),
|
||||
drawGroups(std::move(drawGroups)) {
|
||||
for (size_t i = 0; i < RESOURCE_TYPES_COUNT; i++) {
|
||||
this->resourceIndices[i] = std::move(resourceIndices[i]);
|
||||
}
|
||||
@ -48,7 +48,8 @@ Content::Content(
|
||||
|
||||
Content::~Content() = default;
|
||||
|
||||
const rigging::SkeletonConfig* Content::getSkeleton(const std::string& id) const {
|
||||
const rigging::SkeletonConfig* Content::getSkeleton(const std::string& id
|
||||
) const {
|
||||
auto found = skeletons.find(id);
|
||||
if (found == skeletons.end()) {
|
||||
return nullptr;
|
||||
@ -80,6 +81,7 @@ const UptrsMap<std::string, ContentPackRuntime>& Content::getPacks() const {
|
||||
return packs;
|
||||
}
|
||||
|
||||
const UptrsMap<std::string, rigging::SkeletonConfig>& Content::getSkeletons() const {
|
||||
const UptrsMap<std::string, rigging::SkeletonConfig>& Content::getSkeletons(
|
||||
) const {
|
||||
return skeletons;
|
||||
}
|
||||
|
||||
@ -1,20 +1,19 @@
|
||||
#ifndef CONTENT_CONTENT_HPP_
|
||||
#define CONTENT_CONTENT_HPP_
|
||||
|
||||
#include "content_fwd.hpp"
|
||||
|
||||
#include "../data/dynamic_fwd.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "../data/dynamic_fwd.hpp"
|
||||
#include "content_fwd.hpp"
|
||||
|
||||
using DrawGroups = std::set<ubyte>;
|
||||
template<class K, class V>
|
||||
template <class K, class V>
|
||||
using UptrsMap = std::unordered_map<K, std::unique_ptr<V>>;
|
||||
|
||||
class Block;
|
||||
@ -28,31 +27,37 @@ namespace rigging {
|
||||
|
||||
constexpr const char* contenttype_name(contenttype type) {
|
||||
switch (type) {
|
||||
case contenttype::none: return "none";
|
||||
case contenttype::block: return "block";
|
||||
case contenttype::item: return "item";
|
||||
case contenttype::entity: return "entity";
|
||||
case contenttype::none:
|
||||
return "none";
|
||||
case contenttype::block:
|
||||
return "block";
|
||||
case contenttype::item:
|
||||
return "item";
|
||||
case contenttype::entity:
|
||||
return "entity";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
class namereuse_error: public std::runtime_error {
|
||||
class namereuse_error : public std::runtime_error {
|
||||
contenttype type;
|
||||
public:
|
||||
namereuse_error(const std::string& msg, contenttype type)
|
||||
: std::runtime_error(msg), type(type) {}
|
||||
: std::runtime_error(msg), type(type) {
|
||||
}
|
||||
|
||||
inline contenttype getType() const {
|
||||
return type;
|
||||
}
|
||||
};
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
class ContentUnitIndices {
|
||||
std::vector<T*> defs;
|
||||
public:
|
||||
ContentUnitIndices(std::vector<T*> defs) : defs(std::move(defs)) {}
|
||||
ContentUnitIndices(std::vector<T*> defs) : defs(std::move(defs)) {
|
||||
}
|
||||
|
||||
inline T* get(blockid_t id) const {
|
||||
if (id >= defs.size()) {
|
||||
@ -84,12 +89,11 @@ public:
|
||||
);
|
||||
};
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
class ContentUnitDefs {
|
||||
UptrsMap<std::string, T> defs;
|
||||
public:
|
||||
ContentUnitDefs(UptrsMap<std::string, T> defs)
|
||||
: defs(std::move(defs)) {
|
||||
ContentUnitDefs(UptrsMap<std::string, T> defs) : defs(std::move(defs)) {
|
||||
}
|
||||
|
||||
T* find(const std::string& id) const {
|
||||
@ -102,7 +106,7 @@ public:
|
||||
T& require(const std::string& id) const {
|
||||
const auto& found = defs.find(id);
|
||||
if (found == defs.end()) {
|
||||
throw std::runtime_error("missing content unit "+id);
|
||||
throw std::runtime_error("missing content unit " + id);
|
||||
}
|
||||
return *found->second;
|
||||
}
|
||||
@ -113,8 +117,8 @@ class ResourceIndices {
|
||||
std::unordered_map<std::string, size_t> indices;
|
||||
std::unique_ptr<std::vector<dynamic::Map_sptr>> savedData;
|
||||
public:
|
||||
ResourceIndices()
|
||||
: savedData(std::make_unique<std::vector<dynamic::Map_sptr>>()){
|
||||
ResourceIndices()
|
||||
: savedData(std::make_unique<std::vector<dynamic::Map_sptr>>()) {
|
||||
}
|
||||
|
||||
static constexpr size_t MISSING = SIZE_MAX;
|
||||
@ -152,8 +156,10 @@ public:
|
||||
|
||||
constexpr const char* to_string(ResourceType type) {
|
||||
switch (type) {
|
||||
case ResourceType::CAMERA: return "camera";
|
||||
default: return "unknown";
|
||||
case ResourceType::CAMERA:
|
||||
return "camera";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
@ -180,7 +186,7 @@ public:
|
||||
ResourceIndicesSet resourceIndices {};
|
||||
|
||||
Content(
|
||||
std::unique_ptr<ContentIndices> indices,
|
||||
std::unique_ptr<ContentIndices> indices,
|
||||
std::unique_ptr<DrawGroups> drawGroups,
|
||||
ContentUnitDefs<Block> blocks,
|
||||
ContentUnitDefs<ItemDef> items,
|
||||
@ -209,4 +215,4 @@ public:
|
||||
const UptrsMap<std::string, rigging::SkeletonConfig>& getSkeletons() const;
|
||||
};
|
||||
|
||||
#endif // CONTENT_CONTENT_HPP_
|
||||
#endif // CONTENT_CONTENT_HPP_
|
||||
|
||||
@ -24,7 +24,7 @@ std::unique_ptr<Content> ContentBuilder::build() {
|
||||
auto groups = std::make_unique<DrawGroups>();
|
||||
for (const std::string& name : blocks.names) {
|
||||
Block& def = *blocks.defs[name];
|
||||
|
||||
|
||||
// Generating runtime info
|
||||
def.rt.id = blockDefsIndices.size();
|
||||
def.rt.emissive = *reinterpret_cast<uint32_t*>(def.emission);
|
||||
@ -48,7 +48,7 @@ std::unique_ptr<Content> ContentBuilder::build() {
|
||||
std::vector<ItemDef*> itemDefsIndices;
|
||||
for (const std::string& name : items.names) {
|
||||
ItemDef& def = *items.defs[name];
|
||||
|
||||
|
||||
// Generating runtime info
|
||||
def.rt.id = itemDefsIndices.size();
|
||||
def.rt.emissive = *reinterpret_cast<uint32_t*>(def.emission);
|
||||
@ -66,11 +66,10 @@ std::unique_ptr<Content> ContentBuilder::build() {
|
||||
|
||||
auto content = std::make_unique<Content>(
|
||||
std::make_unique<ContentIndices>(
|
||||
blockDefsIndices,
|
||||
itemDefsIndices,
|
||||
entityDefsIndices),
|
||||
blockDefsIndices, itemDefsIndices, entityDefsIndices
|
||||
),
|
||||
std::move(groups),
|
||||
blocks.build(),
|
||||
blocks.build(),
|
||||
items.build(),
|
||||
entities.build(),
|
||||
std::move(packs),
|
||||
|
||||
@ -1,17 +1,17 @@
|
||||
#ifndef CONTENT_CONTENT_BUILDER_HPP_
|
||||
#define CONTENT_CONTENT_BUILDER_HPP_
|
||||
|
||||
#include "../items/ItemDef.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "../objects/EntityDef.hpp"
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "../content/Content.hpp"
|
||||
#include "../content/ContentPack.hpp"
|
||||
#include "../items/ItemDef.hpp"
|
||||
#include "../objects/EntityDef.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
class ContentUnitBuilder {
|
||||
std::unordered_map<std::string, contenttype>& allNames;
|
||||
contenttype type;
|
||||
@ -19,17 +19,20 @@ class ContentUnitBuilder {
|
||||
void checkIdentifier(const std::string& id) {
|
||||
const auto& found = allNames.find(id);
|
||||
if (found != allNames.end()) {
|
||||
throw namereuse_error("name "+id+" is already used", found->second);
|
||||
throw namereuse_error(
|
||||
"name " + id + " is already used", found->second
|
||||
);
|
||||
}
|
||||
}
|
||||
public:
|
||||
UptrsMap<std::string, T> defs;
|
||||
std::vector<std::string> names;
|
||||
|
||||
|
||||
ContentUnitBuilder(
|
||||
std::unordered_map<std::string, contenttype>& allNames,
|
||||
contenttype type
|
||||
) : allNames(allNames), type(type) {}
|
||||
std::unordered_map<std::string, contenttype>& allNames, contenttype type
|
||||
)
|
||||
: allNames(allNames), type(type) {
|
||||
}
|
||||
|
||||
T& create(const std::string& id) {
|
||||
auto found = defs.find(id);
|
||||
@ -69,4 +72,4 @@ public:
|
||||
std::unique_ptr<Content> build();
|
||||
};
|
||||
|
||||
#endif // CONTENT_CONTENT_BUILDER_HPP_
|
||||
#endif // CONTENT_CONTENT_BUILDER_HPP_
|
||||
|
||||
@ -1,26 +1,30 @@
|
||||
#include "ContentLUT.hpp"
|
||||
|
||||
#include "Content.hpp"
|
||||
#include "../constants.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../coders/json.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "../items/ItemDef.hpp"
|
||||
#include <memory>
|
||||
|
||||
ContentLUT::ContentLUT(const ContentIndices* indices, size_t blocksCount, size_t itemsCount)
|
||||
: blocks(blocksCount, indices->blocks, BLOCK_VOID, contenttype::block),
|
||||
items(itemsCount, indices->items, ITEM_VOID, contenttype::item)
|
||||
{}
|
||||
#include "../coders/json.hpp"
|
||||
#include "../constants.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../items/ItemDef.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "Content.hpp"
|
||||
|
||||
template<class T> static constexpr size_t get_entries_count(
|
||||
const ContentUnitIndices<T>& indices, const dynamic::List_sptr& list) {
|
||||
ContentLUT::ContentLUT(
|
||||
const ContentIndices* indices, size_t blocksCount, size_t itemsCount
|
||||
)
|
||||
: blocks(blocksCount, indices->blocks, BLOCK_VOID, contenttype::block),
|
||||
items(itemsCount, indices->items, ITEM_VOID, contenttype::item) {
|
||||
}
|
||||
|
||||
template <class T>
|
||||
static constexpr size_t get_entries_count(
|
||||
const ContentUnitIndices<T>& indices, const dynamic::List_sptr& list
|
||||
) {
|
||||
return list ? std::max(list->size(), indices.count()) : indices.count();
|
||||
}
|
||||
|
||||
std::shared_ptr<ContentLUT> ContentLUT::create(
|
||||
const fs::path& filename,
|
||||
const Content* content
|
||||
const fs::path& filename, const Content* content
|
||||
) {
|
||||
auto root = files::read_json(filename);
|
||||
auto blocklist = root->list("blocks");
|
||||
|
||||
@ -1,16 +1,15 @@
|
||||
#ifndef CONTENT_CONTENT_LUT_HPP_
|
||||
#define CONTENT_CONTENT_LUT_HPP_
|
||||
|
||||
#include "Content.hpp"
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
#include "../constants.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <filesystem>
|
||||
|
||||
#include "../constants.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "Content.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
@ -19,7 +18,7 @@ struct contententry {
|
||||
std::string name;
|
||||
};
|
||||
|
||||
template<typename T, class U>
|
||||
template <typename T, class U>
|
||||
class ContentUnitLUT {
|
||||
std::vector<T> indices;
|
||||
std::vector<std::string> names;
|
||||
@ -28,13 +27,18 @@ class ContentUnitLUT {
|
||||
T missingValue;
|
||||
contenttype type;
|
||||
public:
|
||||
ContentUnitLUT(size_t count, const ContentUnitIndices<U>& unitIndices, T missingValue, contenttype type)
|
||||
: missingValue(missingValue), type(type) {
|
||||
ContentUnitLUT(
|
||||
size_t count,
|
||||
const ContentUnitIndices<U>& unitIndices,
|
||||
T missingValue,
|
||||
contenttype type
|
||||
)
|
||||
: missingValue(missingValue), type(type) {
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
indices.push_back(i);
|
||||
}
|
||||
for (size_t i = 0; i < unitIndices.count(); i++) {
|
||||
names.push_back(unitIndices.get(i)->name);
|
||||
names.push_back(unitIndices.get(i)->name); //FIXME: .get(i) potentional null pointer //-V522
|
||||
}
|
||||
for (size_t i = unitIndices.count(); i < count; i++) {
|
||||
names.emplace_back("");
|
||||
@ -47,7 +51,7 @@ public:
|
||||
if (auto def = defs.find(name)) {
|
||||
set(i, name, def->rt.id);
|
||||
} else {
|
||||
set(i, name, missingValue);
|
||||
set(i, name, missingValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -86,7 +90,7 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
/// @brief Content indices lookup table or report
|
||||
/// @brief Content indices lookup table or report
|
||||
/// used to convert world with different indices
|
||||
/// Building with indices.json
|
||||
class ContentLUT {
|
||||
@ -97,10 +101,9 @@ public:
|
||||
ContentLUT(const ContentIndices* indices, size_t blocks, size_t items);
|
||||
|
||||
static std::shared_ptr<ContentLUT> create(
|
||||
const fs::path& filename,
|
||||
const Content* content
|
||||
const fs::path& filename, const Content* content
|
||||
);
|
||||
|
||||
|
||||
inline bool hasContentReorder() const {
|
||||
return blocks.hasContentReorder() || items.hasContentReorder();
|
||||
}
|
||||
@ -111,4 +114,4 @@ public:
|
||||
std::vector<contententry> getMissingContent() const;
|
||||
};
|
||||
|
||||
#endif // CONTENT_CONTENT_LUT_HPP_
|
||||
#endif // CONTENT_CONTENT_LUT_HPP_
|
||||
|
||||
@ -1,34 +1,33 @@
|
||||
#include "ContentLoader.hpp"
|
||||
|
||||
#include "Content.hpp"
|
||||
#include "ContentPack.hpp"
|
||||
#include "ContentBuilder.hpp"
|
||||
#include <algorithm>
|
||||
#include <glm/glm.hpp>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "../coders/json.hpp"
|
||||
#include "../core_defs.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../items/ItemDef.hpp"
|
||||
#include "../objects/rigging.hpp"
|
||||
#include "../logic/scripting/scripting.hpp"
|
||||
#include "../objects/rigging.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../util/listutil.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <algorithm>
|
||||
#include <glm/glm.hpp>
|
||||
#include "Content.hpp"
|
||||
#include "ContentBuilder.hpp"
|
||||
#include "ContentPack.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
static debug::Logger logger("content-loader");
|
||||
|
||||
ContentLoader::ContentLoader(ContentPack* pack, ContentBuilder& builder)
|
||||
: pack(pack), builder(builder)
|
||||
{
|
||||
: pack(pack), builder(builder) {
|
||||
auto runtime = std::make_unique<ContentPackRuntime>(
|
||||
*pack, scripting::create_pack_environment(*pack)
|
||||
);
|
||||
@ -97,9 +96,9 @@ bool ContentLoader::fixPackIndices(
|
||||
void ContentLoader::fixPackIndices() {
|
||||
auto folder = pack->folder;
|
||||
auto indexFile = pack->getContentFile();
|
||||
auto blocksFolder = folder/ContentPack::BLOCKS_FOLDER;
|
||||
auto itemsFolder = folder/ContentPack::ITEMS_FOLDER;
|
||||
auto entitiesFolder = folder/ContentPack::ENTITIES_FOLDER;
|
||||
auto blocksFolder = folder / ContentPack::BLOCKS_FOLDER;
|
||||
auto itemsFolder = folder / ContentPack::ITEMS_FOLDER;
|
||||
auto entitiesFolder = folder / ContentPack::ENTITIES_FOLDER;
|
||||
|
||||
dynamic::Map_sptr root;
|
||||
if (fs::is_regular_file(indexFile)) {
|
||||
@ -113,13 +112,15 @@ void ContentLoader::fixPackIndices() {
|
||||
modified |= fixPackIndices(itemsFolder, root.get(), "items");
|
||||
modified |= fixPackIndices(entitiesFolder, root.get(), "entities");
|
||||
|
||||
if (modified){
|
||||
if (modified) {
|
||||
// rewrite modified json
|
||||
files::write_json(indexFile, root.get());
|
||||
}
|
||||
}
|
||||
|
||||
void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::path& file) {
|
||||
void ContentLoader::loadBlock(
|
||||
Block& def, const std::string& name, const fs::path& file
|
||||
) {
|
||||
auto root = files::read_json(file);
|
||||
|
||||
root->str("caption", def.caption);
|
||||
@ -169,7 +170,7 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat
|
||||
logger.error() << "unknown rotation profile " << profile;
|
||||
def.rotatable = false;
|
||||
}
|
||||
|
||||
|
||||
// block hitbox AABB [x, y, z, width, height, depth]
|
||||
auto boxarr = root->list("hitboxes");
|
||||
if (boxarr) {
|
||||
@ -181,16 +182,16 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat
|
||||
hitboxesIndex.b = glm::vec3(box->num(3), box->num(4), box->num(5));
|
||||
hitboxesIndex.b += hitboxesIndex.a;
|
||||
}
|
||||
} else if ((boxarr = root->list("hitbox"))){
|
||||
} else if ((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 };
|
||||
def.hitboxes = {aabb};
|
||||
} else if (!def.modelBoxes.empty()) {
|
||||
def.hitboxes = def.modelBoxes;
|
||||
} else {
|
||||
def.hitboxes = { AABB() };
|
||||
def.hitboxes = {AABB()};
|
||||
}
|
||||
|
||||
// block light emission [r, g, b] where r,g,b in range [0..15]
|
||||
@ -205,8 +206,8 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat
|
||||
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)) {
|
||||
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)};
|
||||
}
|
||||
@ -233,7 +234,7 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat
|
||||
def.tickInterval = 1;
|
||||
}
|
||||
|
||||
if (def.hidden && def.pickingItem == def.name+BLOCK_ITEM_SUFFIX) {
|
||||
if (def.hidden && def.pickingItem == def.name + BLOCK_ITEM_SUFFIX) {
|
||||
def.pickingItem = CORE_EMPTY;
|
||||
}
|
||||
}
|
||||
@ -241,12 +242,14 @@ void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::pat
|
||||
void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) {
|
||||
if (primitives->has("aabbs")) {
|
||||
auto modelboxes = primitives->list("aabbs");
|
||||
for (uint i = 0; i < modelboxes->size(); i++ ) {
|
||||
for (uint i = 0; i < modelboxes->size(); i++) {
|
||||
/* Parse aabb */
|
||||
auto boxarr = modelboxes->list(i);
|
||||
AABB modelbox;
|
||||
modelbox.a = glm::vec3(boxarr->num(0), boxarr->num(1), boxarr->num(2));
|
||||
modelbox.b = glm::vec3(boxarr->num(3), boxarr->num(4), boxarr->num(5));
|
||||
modelbox.a =
|
||||
glm::vec3(boxarr->num(0), boxarr->num(1), boxarr->num(2));
|
||||
modelbox.b =
|
||||
glm::vec3(boxarr->num(3), boxarr->num(4), boxarr->num(5));
|
||||
modelbox.b += modelbox.a;
|
||||
def.modelBoxes.push_back(modelbox);
|
||||
|
||||
@ -270,19 +273,21 @@ void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) {
|
||||
/* Parse tetragon to points */
|
||||
auto tgonobj = modeltetragons->list(i);
|
||||
glm::vec3 p1(tgonobj->num(0), tgonobj->num(1), tgonobj->num(2)),
|
||||
xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)),
|
||||
yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8));
|
||||
xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)),
|
||||
yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8));
|
||||
def.modelExtraPoints.push_back(p1);
|
||||
def.modelExtraPoints.push_back(p1+xw);
|
||||
def.modelExtraPoints.push_back(p1+xw+yh);
|
||||
def.modelExtraPoints.push_back(p1+yh);
|
||||
def.modelExtraPoints.push_back(p1 + xw);
|
||||
def.modelExtraPoints.push_back(p1 + xw + yh);
|
||||
def.modelExtraPoints.push_back(p1 + yh);
|
||||
|
||||
def.modelTextures.emplace_back(tgonobj->str(9));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ContentLoader::loadItem(ItemDef& def, const std::string& name, const fs::path& file) {
|
||||
void ContentLoader::loadItem(
|
||||
ItemDef& def, const std::string& name, const fs::path& file
|
||||
) {
|
||||
auto root = files::read_json(file);
|
||||
root->str("caption", def.caption);
|
||||
|
||||
@ -294,7 +299,7 @@ void ContentLoader::loadItem(ItemDef& def, const std::string& name, const fs::pa
|
||||
def.iconType = item_icon_type::block;
|
||||
} else if (iconTypeStr == "sprite") {
|
||||
def.iconType = item_icon_type::sprite;
|
||||
} else if (iconTypeStr.length()){
|
||||
} else if (iconTypeStr.length()) {
|
||||
logger.error() << name << ": unknown icon type" << iconTypeStr;
|
||||
}
|
||||
root->str("icon", def.icon);
|
||||
@ -310,7 +315,9 @@ void ContentLoader::loadItem(ItemDef& def, const std::string& name, const fs::pa
|
||||
}
|
||||
}
|
||||
|
||||
void ContentLoader::loadEntity(EntityDef& def, const std::string& name, const fs::path& file) {
|
||||
void ContentLoader::loadEntity(
|
||||
EntityDef& def, const std::string& name, const fs::path& file
|
||||
) {
|
||||
auto root = files::read_json(file);
|
||||
if (auto componentsarr = root->list("components")) {
|
||||
for (size_t i = 0; i < componentsarr->size(); i++) {
|
||||
@ -325,14 +332,21 @@ void ContentLoader::loadEntity(EntityDef& def, const std::string& name, const fs
|
||||
if (auto sensorarr = sensorsarr->list(i)) {
|
||||
auto sensorType = sensorarr->str(0);
|
||||
if (sensorType == "aabb") {
|
||||
def.boxSensors.emplace_back(i, AABB{
|
||||
{sensorarr->num(1), sensorarr->num(2), sensorarr->num(3)},
|
||||
{sensorarr->num(4), sensorarr->num(5), sensorarr->num(6)}
|
||||
});
|
||||
def.boxSensors.emplace_back(
|
||||
i,
|
||||
AABB {
|
||||
{sensorarr->num(1),
|
||||
sensorarr->num(2),
|
||||
sensorarr->num(3)},
|
||||
{sensorarr->num(4),
|
||||
sensorarr->num(5),
|
||||
sensorarr->num(6)}}
|
||||
);
|
||||
} else if (sensorType == "radius") {
|
||||
def.radialSensors.emplace_back(i, sensorarr->num(1));
|
||||
} else {
|
||||
logger.error() << name << ": sensor #" << i << " - unknown type "
|
||||
logger.error()
|
||||
<< name << ": sensor #" << i << " - unknown type "
|
||||
<< util::quote(sensorType);
|
||||
}
|
||||
}
|
||||
@ -354,29 +368,33 @@ void ContentLoader::loadEntity(EntityDef& def, const std::string& name, const fs
|
||||
root->flag("blocking", def.blocking);
|
||||
}
|
||||
|
||||
void ContentLoader::loadEntity(EntityDef& def, const std::string& full, const std::string& name) {
|
||||
void ContentLoader::loadEntity(
|
||||
EntityDef& def, const std::string& full, const std::string& name
|
||||
) {
|
||||
auto folder = pack->folder;
|
||||
auto configFile = folder/fs::path("entities/"+name+".json");
|
||||
auto configFile = folder / fs::path("entities/" + name + ".json");
|
||||
if (fs::exists(configFile)) loadEntity(def, full, configFile);
|
||||
}
|
||||
|
||||
void ContentLoader::loadBlock(Block& def, const std::string& full, const std::string& name) {
|
||||
void ContentLoader::loadBlock(
|
||||
Block& def, const std::string& full, const std::string& name
|
||||
) {
|
||||
auto folder = pack->folder;
|
||||
auto configFile = folder/fs::path("blocks/"+name+".json");
|
||||
auto configFile = folder / fs::path("blocks/" + name + ".json");
|
||||
if (fs::exists(configFile)) loadBlock(def, full, configFile);
|
||||
|
||||
auto scriptfile = folder/fs::path("scripts/"+def.scriptName+".lua");
|
||||
auto scriptfile = folder / fs::path("scripts/" + def.scriptName + ".lua");
|
||||
if (fs::is_regular_file(scriptfile)) {
|
||||
scripting::load_block_script(env, full, scriptfile, def.rt.funcsset);
|
||||
}
|
||||
if (!def.hidden) {
|
||||
auto& item = builder.items.create(full+BLOCK_ITEM_SUFFIX);
|
||||
auto& item = builder.items.create(full + BLOCK_ITEM_SUFFIX);
|
||||
item.generated = true;
|
||||
item.caption = def.caption;
|
||||
item.iconType = item_icon_type::block;
|
||||
item.icon = full;
|
||||
item.placingBlock = full;
|
||||
|
||||
|
||||
for (uint j = 0; j < 4; j++) {
|
||||
item.emission[j] = def.emission[j];
|
||||
}
|
||||
@ -384,18 +402,22 @@ void ContentLoader::loadBlock(Block& def, const std::string& full, const std::st
|
||||
}
|
||||
}
|
||||
|
||||
void ContentLoader::loadItem(ItemDef& def, const std::string& full, const std::string& name) {
|
||||
void ContentLoader::loadItem(
|
||||
ItemDef& def, const std::string& full, const std::string& name
|
||||
) {
|
||||
auto folder = pack->folder;
|
||||
auto configFile = folder/fs::path("items/"+name+".json");
|
||||
auto configFile = folder / fs::path("items/" + name + ".json");
|
||||
if (fs::exists(configFile)) loadItem(def, full, configFile);
|
||||
|
||||
auto scriptfile = folder/fs::path("scripts/"+def.scriptName+".lua");
|
||||
auto scriptfile = folder / fs::path("scripts/" + def.scriptName + ".lua");
|
||||
if (fs::is_regular_file(scriptfile)) {
|
||||
scripting::load_item_script(env, full, scriptfile, def.rt.funcsset);
|
||||
}
|
||||
}
|
||||
|
||||
void ContentLoader::loadBlockMaterial(BlockMaterial& def, const fs::path& file) {
|
||||
void ContentLoader::loadBlockMaterial(
|
||||
BlockMaterial& def, const fs::path& file
|
||||
) {
|
||||
auto root = files::read_json(file);
|
||||
root->str("steps-sound", def.stepsSound);
|
||||
root->str("place-sound", def.placeSound);
|
||||
@ -409,13 +431,14 @@ void ContentLoader::load() {
|
||||
|
||||
auto folder = pack->folder;
|
||||
|
||||
fs::path scriptFile = folder/fs::path("scripts/world.lua");
|
||||
fs::path scriptFile = folder / fs::path("scripts/world.lua");
|
||||
if (fs::is_regular_file(scriptFile)) {
|
||||
scripting::load_world_script(env, pack->id, scriptFile, runtime->worldfuncsset);
|
||||
scripting::load_world_script(
|
||||
env, pack->id, scriptFile, runtime->worldfuncsset
|
||||
);
|
||||
}
|
||||
|
||||
if (!fs::is_regular_file(pack->getContentFile()))
|
||||
return;
|
||||
if (!fs::is_regular_file(pack->getContentFile())) return;
|
||||
|
||||
auto root = files::read_json(pack->getContentFile());
|
||||
|
||||
@ -423,10 +446,12 @@ void ContentLoader::load() {
|
||||
for (size_t i = 0; i < blocksarr->size(); i++) {
|
||||
std::string name = blocksarr->str(i);
|
||||
auto colon = name.find(':');
|
||||
std::string full = colon == std::string::npos ? pack->id + ":" + name : name;
|
||||
std::string full =
|
||||
colon == std::string::npos ? pack->id + ":" + name : name;
|
||||
if (colon != std::string::npos) name[colon] = '/';
|
||||
auto& def = builder.blocks.create(full);
|
||||
if (colon != std::string::npos) def.scriptName = name.substr(0, colon) + '/' + def.scriptName;
|
||||
if (colon != std::string::npos)
|
||||
def.scriptName = name.substr(0, colon) + '/' + def.scriptName;
|
||||
loadBlock(def, full, name);
|
||||
stats->totalBlocks++;
|
||||
}
|
||||
@ -435,10 +460,12 @@ void ContentLoader::load() {
|
||||
for (size_t i = 0; i < itemsarr->size(); i++) {
|
||||
std::string name = itemsarr->str(i);
|
||||
auto colon = name.find(':');
|
||||
std::string full = colon == std::string::npos ? pack->id + ":" + name : name;
|
||||
std::string full =
|
||||
colon == std::string::npos ? pack->id + ":" + name : name;
|
||||
if (colon != std::string::npos) name[colon] = '/';
|
||||
auto& def = builder.items.create(full);
|
||||
if (colon != std::string::npos) def.scriptName = name.substr(0, colon) + '/' + def.scriptName;
|
||||
if (colon != std::string::npos)
|
||||
def.scriptName = name.substr(0, colon) + '/' + def.scriptName;
|
||||
loadItem(def, full, name);
|
||||
stats->totalItems++;
|
||||
}
|
||||
@ -448,7 +475,8 @@ void ContentLoader::load() {
|
||||
for (size_t i = 0; i < entitiesarr->size(); i++) {
|
||||
std::string name = entitiesarr->str(i);
|
||||
auto colon = name.find(':');
|
||||
std::string full = colon == std::string::npos ? pack->id + ":" + name : name;
|
||||
std::string full =
|
||||
colon == std::string::npos ? pack->id + ":" + name : name;
|
||||
if (colon != std::string::npos) name[colon] = '/';
|
||||
auto& def = builder.entities.create(full);
|
||||
loadEntity(def, full, name);
|
||||
@ -460,7 +488,7 @@ void ContentLoader::load() {
|
||||
if (fs::is_directory(materialsDir)) {
|
||||
for (const auto& entry : fs::directory_iterator(materialsDir)) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@ -469,9 +497,11 @@ void ContentLoader::load() {
|
||||
if (fs::is_directory(skeletonsDir)) {
|
||||
for (const auto& entry : fs::directory_iterator(skeletonsDir)) {
|
||||
const fs::path& file = entry.path();
|
||||
std::string name = pack->id+":"+file.stem().u8string();
|
||||
std::string name = pack->id + ":" + file.stem().u8string();
|
||||
std::string text = files::read_string(file);
|
||||
builder.add(rigging::SkeletonConfig::parse(text, file.u8string(), name));
|
||||
builder.add(
|
||||
rigging::SkeletonConfig::parse(text, file.u8string(), name)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -480,7 +510,7 @@ void ContentLoader::load() {
|
||||
for (const auto& entry : fs::directory_iterator(componentsDir)) {
|
||||
fs::path scriptfile = entry.path();
|
||||
if (fs::is_regular_file(scriptfile)) {
|
||||
auto name = pack->id+":"+scriptfile.stem().u8string();
|
||||
auto name = pack->id + ":" + scriptfile.stem().u8string();
|
||||
scripting::load_entity_component(name, scriptfile);
|
||||
}
|
||||
}
|
||||
@ -504,6 +534,7 @@ void ContentLoader::load() {
|
||||
void ContentLoader::loadResources(ResourceType type, dynamic::List* list) {
|
||||
for (size_t i = 0; i < list->size(); i++) {
|
||||
builder.resourceIndices[static_cast<size_t>(type)].add(
|
||||
pack->id+":"+list->str(i), nullptr);
|
||||
pack->id + ":" + list->str(i), nullptr
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
#ifndef CONTENT_CONTENT_LOADER_HPP_
|
||||
#define CONTENT_CONTENT_LOADER_HPP_
|
||||
|
||||
#include "content_fwd.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "content_fwd.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
@ -30,16 +30,28 @@ class ContentLoader {
|
||||
scriptenv env;
|
||||
ContentBuilder& builder;
|
||||
ContentPackStats* stats;
|
||||
|
||||
void loadBlock(Block& def, const std::string& full, const std::string& name);
|
||||
void loadItem(ItemDef& def, const std::string& full, const std::string& name);
|
||||
void loadEntity(EntityDef& def, const std::string& full, const std::string& name);
|
||||
|
||||
void loadBlock(
|
||||
Block& def, const std::string& full, const std::string& name
|
||||
);
|
||||
void loadItem(
|
||||
ItemDef& def, const std::string& full, const std::string& name
|
||||
);
|
||||
void loadEntity(
|
||||
EntityDef& def, const std::string& full, const std::string& name
|
||||
);
|
||||
|
||||
static void loadCustomBlockModel(Block& def, dynamic::Map* primitives);
|
||||
static void loadBlockMaterial(BlockMaterial& def, const fs::path& file);
|
||||
static void loadBlock(Block& def, const std::string& name, const fs::path& file);
|
||||
static void loadItem(ItemDef& def, const std::string& name, const fs::path& file);
|
||||
static void loadEntity(EntityDef& def, const std::string& name, const fs::path& file);
|
||||
static void loadBlock(
|
||||
Block& def, const std::string& name, const fs::path& file
|
||||
);
|
||||
static void loadItem(
|
||||
ItemDef& def, const std::string& name, const fs::path& file
|
||||
);
|
||||
static void loadEntity(
|
||||
EntityDef& def, const std::string& name, const fs::path& file
|
||||
);
|
||||
void loadResources(ResourceType type, dynamic::List* list);
|
||||
public:
|
||||
ContentLoader(ContentPack* pack, ContentBuilder& builder);
|
||||
@ -53,4 +65,4 @@ public:
|
||||
void load();
|
||||
};
|
||||
|
||||
#endif // CONTENT_CONTENT_LOADER_HPP_
|
||||
#endif // CONTENT_CONTENT_LOADER_HPP_
|
||||
|
||||
@ -1,25 +1,25 @@
|
||||
#include "ContentPack.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
#include "../coders/json.hpp"
|
||||
#include "../files/files.hpp"
|
||||
#include "../files/engine_paths.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../files/engine_paths.hpp"
|
||||
#include "../files/files.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
const std::vector<std::string> ContentPack::RESERVED_NAMES = {
|
||||
"res", "abs", "local", "core", "user", "world", "none", "null"
|
||||
};
|
||||
"res", "abs", "local", "core", "user", "world", "none", "null"};
|
||||
|
||||
contentpack_error::contentpack_error(
|
||||
std::string packId,
|
||||
fs::path folder,
|
||||
const std::string& message)
|
||||
: std::runtime_error(message), packId(std::move(packId)), folder(std::move(folder)) {
|
||||
std::string packId, fs::path folder, const std::string& message
|
||||
)
|
||||
: std::runtime_error(message),
|
||||
packId(std::move(packId)),
|
||||
folder(std::move(folder)) {
|
||||
}
|
||||
|
||||
std::string contentpack_error::getPackId() const {
|
||||
@ -30,36 +30,40 @@ fs::path contentpack_error::getFolder() const {
|
||||
}
|
||||
|
||||
fs::path ContentPack::getContentFile() const {
|
||||
return folder/fs::path(CONTENT_FILENAME);
|
||||
return folder / fs::path(CONTENT_FILENAME);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
static void checkContentPackId(const std::string& id, const fs::path& folder) {
|
||||
if (id.length() < 2 || id.length() > 24)
|
||||
throw contentpack_error(id, folder,
|
||||
"content-pack id length is out of range [2, 24]");
|
||||
if (isdigit(id[0]))
|
||||
throw contentpack_error(id, folder,
|
||||
"content-pack id must not start with a digit");
|
||||
throw contentpack_error(
|
||||
id, folder, "content-pack id length is out of range [2, 24]"
|
||||
);
|
||||
if (isdigit(id[0]))
|
||||
throw contentpack_error(
|
||||
id, folder, "content-pack id must not start with a digit"
|
||||
);
|
||||
for (char c : id) {
|
||||
if (!isalnum(c) && c != '_') {
|
||||
throw contentpack_error(id, folder,
|
||||
"illegal character in content-pack id");
|
||||
throw contentpack_error(
|
||||
id, folder, "illegal character in content-pack id"
|
||||
);
|
||||
}
|
||||
}
|
||||
if (std::find(ContentPack::RESERVED_NAMES.begin(),
|
||||
ContentPack::RESERVED_NAMES.end(), id)
|
||||
!= ContentPack::RESERVED_NAMES.end()) {
|
||||
throw contentpack_error(id, folder,
|
||||
"this content-pack id is reserved");
|
||||
if (std::find(
|
||||
ContentPack::RESERVED_NAMES.begin(),
|
||||
ContentPack::RESERVED_NAMES.end(),
|
||||
id
|
||||
) != ContentPack::RESERVED_NAMES.end()) {
|
||||
throw contentpack_error(id, folder, "this content-pack id is reserved");
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
root->str("id", pack.id);
|
||||
root->str("title", pack.title);
|
||||
@ -78,26 +82,24 @@ ContentPack ContentPack::read(const fs::path& folder) {
|
||||
}
|
||||
|
||||
if (pack.id == "none")
|
||||
throw contentpack_error(pack.id, folder,
|
||||
"content-pack id is not specified");
|
||||
throw contentpack_error(
|
||||
pack.id, folder, "content-pack id is not specified"
|
||||
);
|
||||
checkContentPackId(pack.id, folder);
|
||||
|
||||
return pack;
|
||||
}
|
||||
|
||||
void ContentPack::scanFolder(
|
||||
const fs::path& folder,
|
||||
std::vector<ContentPack>& packs
|
||||
const fs::path& folder, std::vector<ContentPack>& packs
|
||||
) {
|
||||
if (!fs::is_directory(folder)) {
|
||||
return;
|
||||
}
|
||||
for (const auto& entry : fs::directory_iterator(folder)) {
|
||||
const fs::path& folder = entry.path();
|
||||
if (!fs::is_directory(folder))
|
||||
continue;
|
||||
if (!is_pack(folder))
|
||||
continue;
|
||||
if (!fs::is_directory(folder)) continue;
|
||||
if (!is_pack(folder)) continue;
|
||||
try {
|
||||
packs.push_back(read(folder));
|
||||
} catch (const contentpack_error& err) {
|
||||
@ -119,7 +121,9 @@ std::vector<std::string> ContentPack::worldPacksList(const fs::path& folder) {
|
||||
return files::read_list(listfile);
|
||||
}
|
||||
|
||||
fs::path ContentPack::findPack(const EnginePaths* paths, const fs::path& worldDir, const std::string& name) {
|
||||
fs::path ContentPack::findPack(
|
||||
const EnginePaths* paths, const fs::path& worldDir, const std::string& name
|
||||
) {
|
||||
fs::path folder = worldDir / fs::path("content") / fs::path(name);
|
||||
if (fs::is_directory(folder)) {
|
||||
return folder;
|
||||
@ -130,16 +134,13 @@ fs::path ContentPack::findPack(const EnginePaths* paths, const fs::path& worldDi
|
||||
}
|
||||
folder = paths->getResources() / fs::path("content") / fs::path(name);
|
||||
if (fs::is_directory(folder)) {
|
||||
return folder;
|
||||
return folder; //-V523
|
||||
}
|
||||
return folder;
|
||||
return folder; // FIXME: V523 The 'then' statement is equivalent to the subsequent code fragment //-V523
|
||||
}
|
||||
|
||||
ContentPackRuntime::ContentPackRuntime(
|
||||
ContentPack info,
|
||||
scriptenv env
|
||||
) : info(std::move(info)), env(std::move(env))
|
||||
{
|
||||
ContentPackRuntime::ContentPackRuntime(ContentPack info, scriptenv env)
|
||||
: info(std::move(info)), env(std::move(env)) {
|
||||
}
|
||||
|
||||
ContentPackRuntime::~ContentPackRuntime() = default;
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
#ifndef CONTENT_CONTENT_PACK_HPP_
|
||||
#define CONTENT_CONTENT_PACK_HPP_
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
#include <filesystem>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
class EnginePaths;
|
||||
|
||||
@ -16,19 +16,20 @@ class contentpack_error : public std::runtime_error {
|
||||
std::string packId;
|
||||
fs::path folder;
|
||||
public:
|
||||
contentpack_error(std::string packId, fs::path folder, const std::string& message);
|
||||
contentpack_error(
|
||||
std::string packId, fs::path folder, const std::string& message
|
||||
);
|
||||
|
||||
std::string getPackId() const;
|
||||
fs::path getFolder() const;
|
||||
};
|
||||
|
||||
enum class DependencyLevel {
|
||||
required, // dependency must be installed
|
||||
optional, // dependency will be installed if found
|
||||
weak, // only affects packs order
|
||||
required, // dependency must be installed
|
||||
optional, // dependency will be installed if found
|
||||
weak, // only affects packs order
|
||||
};
|
||||
|
||||
|
||||
/// @brief Content-pack that should be installed earlier the dependent
|
||||
struct DependencyPack {
|
||||
DependencyLevel level;
|
||||
@ -57,14 +58,13 @@ struct ContentPack {
|
||||
static ContentPack read(const fs::path& folder);
|
||||
|
||||
static void scanFolder(
|
||||
const fs::path& folder,
|
||||
std::vector<ContentPack>& packs
|
||||
const fs::path& folder, std::vector<ContentPack>& packs
|
||||
);
|
||||
|
||||
|
||||
static std::vector<std::string> worldPacksList(const fs::path& folder);
|
||||
|
||||
static fs::path findPack(
|
||||
const EnginePaths* paths,
|
||||
const EnginePaths* paths,
|
||||
const fs::path& worldDir,
|
||||
const std::string& name
|
||||
);
|
||||
@ -92,10 +92,7 @@ class ContentPackRuntime {
|
||||
public:
|
||||
world_funcs_set worldfuncsset {};
|
||||
|
||||
ContentPackRuntime(
|
||||
ContentPack info,
|
||||
scriptenv env
|
||||
);
|
||||
ContentPackRuntime(ContentPack info, scriptenv env);
|
||||
~ContentPackRuntime();
|
||||
|
||||
inline const ContentPackStats& getStats() const {
|
||||
@ -119,4 +116,4 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
#endif // CONTENT_CONTENT_PACK_HPP_
|
||||
#endif // CONTENT_CONTENT_PACK_HPP_
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
#include "PacksManager.hpp"
|
||||
|
||||
#include "../util/listutil.hpp"
|
||||
|
||||
#include <queue>
|
||||
#include <sstream>
|
||||
|
||||
#include "../util/listutil.hpp"
|
||||
|
||||
PacksManager::PacksManager() = default;
|
||||
|
||||
void PacksManager::setSources(std::vector<fs::path> sources) {
|
||||
@ -13,7 +13,7 @@ void PacksManager::setSources(std::vector<fs::path> sources) {
|
||||
|
||||
void PacksManager::scan() {
|
||||
packs.clear();
|
||||
|
||||
|
||||
std::vector<ContentPack> packsList;
|
||||
for (auto& folder : sources) {
|
||||
ContentPack::scanFolder(folder, packsList);
|
||||
@ -35,7 +35,9 @@ std::vector<std::string> PacksManager::getAllNames() const {
|
||||
return names;
|
||||
}
|
||||
|
||||
std::vector<ContentPack> PacksManager::getAll(const std::vector<std::string>& names) const {
|
||||
std::vector<ContentPack> PacksManager::getAll(
|
||||
const std::vector<std::string>& names
|
||||
) const {
|
||||
std::vector<ContentPack> packsList;
|
||||
for (auto& name : names) {
|
||||
auto found = packs.find(name);
|
||||
@ -47,7 +49,9 @@ std::vector<ContentPack> PacksManager::getAll(const std::vector<std::string>& na
|
||||
return packsList;
|
||||
}
|
||||
|
||||
static contentpack_error on_circular_dependency(std::queue<const ContentPack*>& queue) {
|
||||
static contentpack_error on_circular_dependency(
|
||||
std::queue<const ContentPack*>& queue
|
||||
) {
|
||||
const ContentPack* lastPack = queue.back();
|
||||
// circular dependency
|
||||
std::stringstream ss;
|
||||
@ -66,10 +70,12 @@ static contentpack_error on_circular_dependency(std::queue<const ContentPack*>&
|
||||
/// @param allNames all already done or enqueued packs
|
||||
/// @param added packs with all dependencies resolved
|
||||
/// @param queue current pass queue
|
||||
/// @param resolveWeaks make weak dependencies resolved if found but not added to queue
|
||||
/// @return true if all dependencies are already added or not found (optional/weak)
|
||||
/// @param resolveWeaks make weak dependencies resolved if found but not added
|
||||
/// to queue
|
||||
/// @return true if all dependencies are already added or not found
|
||||
/// (optional/weak)
|
||||
/// @throws contentpack_error if required dependency is not found
|
||||
static bool resolve_dependencies (
|
||||
static bool resolve_dependencies(
|
||||
const ContentPack* pack,
|
||||
const std::unordered_map<std::string, ContentPack>& packs,
|
||||
std::vector<std::string>& allNames,
|
||||
@ -85,7 +91,9 @@ static bool resolve_dependencies (
|
||||
auto found = packs.find(dep.id);
|
||||
bool exists = found != packs.end();
|
||||
if (!exists && dep.level == DependencyLevel::required) {
|
||||
throw contentpack_error(dep.id, fs::path(), "dependency of '"+pack->id+"'");
|
||||
throw contentpack_error(
|
||||
dep.id, fs::path(), "dependency of '" + pack->id + "'"
|
||||
);
|
||||
}
|
||||
if (!exists) {
|
||||
// ignored for optional or weak dependencies
|
||||
@ -93,11 +101,13 @@ static bool resolve_dependencies (
|
||||
}
|
||||
if (resolveWeaks && dep.level == DependencyLevel::weak) {
|
||||
// dependency pack is found but not added yet
|
||||
// resolveWeaks is used on second iteration, so it's will not be added
|
||||
// resolveWeaks is used on second iteration, so it's will not be
|
||||
// added
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!util::contains(allNames, dep.id) && dep.level != DependencyLevel::weak) {
|
||||
if (!util::contains(allNames, dep.id) &&
|
||||
dep.level != DependencyLevel::weak) {
|
||||
allNames.push_back(dep.id);
|
||||
queue.push(&found->second);
|
||||
}
|
||||
@ -106,7 +116,9 @@ static bool resolve_dependencies (
|
||||
return satisfied;
|
||||
}
|
||||
|
||||
std::vector<std::string> PacksManager::assembly(const std::vector<std::string>& names) const {
|
||||
std::vector<std::string> PacksManager::assembly(
|
||||
const std::vector<std::string>& names
|
||||
) const {
|
||||
std::vector<std::string> allNames = names;
|
||||
std::vector<std::string> added;
|
||||
std::queue<const ContentPack*> queue;
|
||||
@ -126,10 +138,14 @@ std::vector<std::string> PacksManager::assembly(const std::vector<std::string>&
|
||||
while (!queue.empty()) {
|
||||
auto* pack = queue.front();
|
||||
queue.pop();
|
||||
|
||||
if (resolve_dependencies(pack, packs, allNames, added, queue, resolveWeaks)) {
|
||||
|
||||
if (resolve_dependencies(
|
||||
pack, packs, allNames, added, queue, resolveWeaks
|
||||
)) {
|
||||
if (util::contains(added, pack->id)) {
|
||||
throw contentpack_error(pack->id, pack->folder, "pack duplication");
|
||||
throw contentpack_error(
|
||||
pack->id, pack->folder, "pack duplication"
|
||||
);
|
||||
}
|
||||
added.push_back(pack->id);
|
||||
addedInIteration++;
|
||||
@ -148,7 +164,9 @@ std::vector<std::string> PacksManager::assembly(const std::vector<std::string>&
|
||||
return added;
|
||||
}
|
||||
|
||||
std::vector<std::string> PacksManager::getNames(const std::vector<ContentPack>& packs) {
|
||||
std::vector<std::string> PacksManager::getNames(
|
||||
const std::vector<ContentPack>& packs
|
||||
) {
|
||||
std::vector<std::string> result;
|
||||
for (const auto& pack : packs) {
|
||||
result.push_back(pack.id);
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
#ifndef CONTENT_PACKS_MANAGER_HPP_
|
||||
#define CONTENT_PACKS_MANAGER_HPP_
|
||||
|
||||
#include "ContentPack.hpp"
|
||||
|
||||
#include <vector>
|
||||
#include <filesystem>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "ContentPack.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
@ -31,17 +31,21 @@ public:
|
||||
/// @brief Get packs by names (id)
|
||||
/// @param names pack names
|
||||
/// @throws contentpack_error if pack not found
|
||||
std::vector<ContentPack> getAll(const std::vector<std::string>& names) const;
|
||||
std::vector<ContentPack> getAll(const std::vector<std::string>& names
|
||||
) const;
|
||||
|
||||
/// @brief Resolve all dependencies and fix packs order
|
||||
/// @param names required packs (method can add extra packs)
|
||||
/// @return resulting ordered vector of pack names
|
||||
/// @throws contentpack_error if required dependency not found or
|
||||
/// circular dependency detected
|
||||
std::vector<std::string> assembly(const std::vector<std::string>& names) const;
|
||||
std::vector<std::string> assembly(const std::vector<std::string>& names
|
||||
) const;
|
||||
|
||||
/// @brief Collect all pack names (identifiers) into a new vector
|
||||
static std::vector<std::string> getNames(const std::vector<ContentPack>& packs);
|
||||
static std::vector<std::string> getNames(
|
||||
const std::vector<ContentPack>& packs
|
||||
);
|
||||
};
|
||||
|
||||
#endif // CONTENT_PACKS_MANAGER_HPP_
|
||||
#endif // CONTENT_PACKS_MANAGER_HPP_
|
||||
|
||||
@ -6,15 +6,11 @@
|
||||
class Content;
|
||||
class ContentPackRuntime;
|
||||
|
||||
enum class contenttype {
|
||||
none, block, item, entity
|
||||
};
|
||||
enum class contenttype { none, block, item, entity };
|
||||
|
||||
enum class ResourceType : size_t {
|
||||
CAMERA,
|
||||
LAST=CAMERA
|
||||
};
|
||||
enum class ResourceType : size_t { CAMERA, LAST = CAMERA };
|
||||
|
||||
inline constexpr auto RESOURCE_TYPES_COUNT = static_cast<size_t>(ResourceType::LAST)+1;
|
||||
inline constexpr auto RESOURCE_TYPES_COUNT =
|
||||
static_cast<size_t>(ResourceType::LAST) + 1;
|
||||
|
||||
#endif // CONTENT_CONTENT_FWD_HPP_
|
||||
#endif // CONTENT_CONTENT_FWD_HPP_
|
||||
|
||||
@ -14,7 +14,9 @@ std::ostream& operator<<(std::ostream& stream, const dynamic::Map_sptr& value) {
|
||||
return stream;
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& stream, const dynamic::List_sptr& value) {
|
||||
std::ostream& operator<<(
|
||||
std::ostream& stream, const dynamic::List_sptr& value
|
||||
) {
|
||||
stream << json::stringify(value, false, " ");
|
||||
return stream;
|
||||
}
|
||||
@ -22,10 +24,14 @@ std::ostream& operator<<(std::ostream& stream, const dynamic::List_sptr& value)
|
||||
std::string List::str(size_t index) const {
|
||||
const auto& value = values[index];
|
||||
switch (static_cast<Type>(value.index())) {
|
||||
case Type::string: return std::get<std::string>(value);
|
||||
case Type::boolean: return std::get<bool>(value) ? "true" : "false";
|
||||
case Type::number: return std::to_string(std::get<double>(value));
|
||||
case Type::integer: return std::to_string(std::get<int64_t>(value));
|
||||
case Type::string:
|
||||
return std::get<std::string>(value);
|
||||
case Type::boolean:
|
||||
return std::get<bool>(value) ? "true" : "false";
|
||||
case Type::number:
|
||||
return std::to_string(std::get<double>(value));
|
||||
case Type::integer:
|
||||
return std::to_string(std::get<int64_t>(value));
|
||||
default:
|
||||
throw std::runtime_error("type error");
|
||||
}
|
||||
@ -34,10 +40,14 @@ std::string List::str(size_t index) const {
|
||||
number_t List::num(size_t index) const {
|
||||
const auto& value = values[index];
|
||||
switch (static_cast<Type>(value.index())) {
|
||||
case Type::number: return std::get<number_t>(value);
|
||||
case Type::integer: return std::get<integer_t>(value);
|
||||
case Type::string: return std::stoll(std::get<std::string>(value));
|
||||
case Type::boolean: return std::get<bool>(value);
|
||||
case Type::number:
|
||||
return std::get<number_t>(value);
|
||||
case Type::integer:
|
||||
return std::get<integer_t>(value);
|
||||
case Type::string:
|
||||
return std::stoll(std::get<std::string>(value));
|
||||
case Type::boolean:
|
||||
return std::get<bool>(value);
|
||||
default:
|
||||
throw std::runtime_error("type error");
|
||||
}
|
||||
@ -46,10 +56,14 @@ number_t List::num(size_t index) const {
|
||||
integer_t List::integer(size_t index) const {
|
||||
const auto& value = values[index];
|
||||
switch (static_cast<Type>(value.index())) {
|
||||
case Type::number: return std::get<number_t>(value);
|
||||
case Type::integer: return std::get<integer_t>(value);
|
||||
case Type::string: return std::stoll(std::get<std::string>(value));
|
||||
case Type::boolean: return std::get<bool>(value);
|
||||
case Type::number:
|
||||
return std::get<number_t>(value);
|
||||
case Type::integer:
|
||||
return std::get<integer_t>(value);
|
||||
case Type::string:
|
||||
return std::stoll(std::get<std::string>(value));
|
||||
case Type::boolean:
|
||||
return std::get<bool>(value);
|
||||
default:
|
||||
throw std::runtime_error("type error");
|
||||
}
|
||||
@ -74,8 +88,10 @@ List* List::list(size_t index) const {
|
||||
bool List::flag(size_t index) const {
|
||||
const auto& value = values[index];
|
||||
switch (static_cast<Type>(value.index())) {
|
||||
case Type::integer: return std::get<integer_t>(value);
|
||||
case Type::boolean: return std::get<bool>(value);
|
||||
case Type::integer:
|
||||
return std::get<integer_t>(value);
|
||||
case Type::boolean:
|
||||
return std::get<bool>(value);
|
||||
default:
|
||||
throw std::runtime_error("type error");
|
||||
}
|
||||
@ -112,55 +128,69 @@ void Map::str(const std::string& key, std::string& dst) const {
|
||||
|
||||
std::string Map::get(const std::string& key, const std::string& def) const {
|
||||
auto found = values.find(key);
|
||||
if (found == values.end())
|
||||
return def;
|
||||
if (found == values.end()) return def;
|
||||
auto& value = found->second;
|
||||
switch (static_cast<Type>(value.index())) {
|
||||
case Type::string: return std::get<std::string>(value);
|
||||
case Type::boolean: return std::get<bool>(value) ? "true" : "false";
|
||||
case Type::number: return std::to_string(std::get<number_t>(value));
|
||||
case Type::integer: return std::to_string(std::get<integer_t>(value));
|
||||
default: throw std::runtime_error("type error");
|
||||
case Type::string:
|
||||
return std::get<std::string>(value);
|
||||
case Type::boolean:
|
||||
return std::get<bool>(value) ? "true" : "false";
|
||||
case Type::number:
|
||||
return std::to_string(std::get<number_t>(value));
|
||||
case Type::integer:
|
||||
return std::to_string(std::get<integer_t>(value));
|
||||
default:
|
||||
throw std::runtime_error("type error");
|
||||
}
|
||||
}
|
||||
|
||||
number_t Map::get(const std::string& key, double def) const {
|
||||
auto found = values.find(key);
|
||||
if (found == values.end())
|
||||
return def;
|
||||
if (found == values.end()) return def;
|
||||
auto& value = found->second;
|
||||
switch (static_cast<Type>(value.index())) {
|
||||
case Type::number: return std::get<number_t>(value);
|
||||
case Type::integer: return std::get<integer_t>(value);
|
||||
case Type::string: return std::stoull(std::get<std::string>(value));
|
||||
case Type::boolean: return std::get<bool>(value);
|
||||
default: throw std::runtime_error("type error");
|
||||
case Type::number:
|
||||
return std::get<number_t>(value);
|
||||
case Type::integer:
|
||||
return std::get<integer_t>(value);
|
||||
case Type::string:
|
||||
return std::stoull(std::get<std::string>(value));
|
||||
case Type::boolean:
|
||||
return std::get<bool>(value);
|
||||
default:
|
||||
throw std::runtime_error("type error");
|
||||
}
|
||||
}
|
||||
|
||||
integer_t Map::get(const std::string& key, integer_t def) const {
|
||||
auto found = values.find(key);
|
||||
if (found == values.end())
|
||||
return def;
|
||||
if (found == values.end()) return def;
|
||||
auto& value = found->second;
|
||||
switch (static_cast<Type>(value.index())) {
|
||||
case Type::number: return std::get<number_t>(value);
|
||||
case Type::integer: return std::get<integer_t>(value);
|
||||
case Type::string: return std::stoull(std::get<std::string>(value));
|
||||
case Type::boolean: return std::get<bool>(value);
|
||||
default: throw std::runtime_error("type error");
|
||||
case Type::number:
|
||||
return std::get<number_t>(value);
|
||||
case Type::integer:
|
||||
return std::get<integer_t>(value);
|
||||
case Type::string:
|
||||
return std::stoull(std::get<std::string>(value));
|
||||
case Type::boolean:
|
||||
return std::get<bool>(value);
|
||||
default:
|
||||
throw std::runtime_error("type error");
|
||||
}
|
||||
}
|
||||
|
||||
bool Map::get(const std::string& key, bool def) const {
|
||||
auto found = values.find(key);
|
||||
if (found == values.end())
|
||||
return def;
|
||||
if (found == values.end()) return def;
|
||||
auto& value = found->second;
|
||||
switch (static_cast<Type>(value.index())) {
|
||||
case Type::integer: return std::get<integer_t>(value);
|
||||
case Type::boolean: return std::get<bool>(value);
|
||||
default: throw std::runtime_error("type error");
|
||||
case Type::integer:
|
||||
return std::get<integer_t>(value);
|
||||
case Type::boolean:
|
||||
return std::get<bool>(value);
|
||||
default:
|
||||
throw std::runtime_error("type error");
|
||||
}
|
||||
}
|
||||
|
||||
@ -204,8 +234,7 @@ Map_sptr Map::map(const std::string& key) const {
|
||||
|
||||
List_sptr Map::list(const std::string& key) const {
|
||||
auto found = values.find(key);
|
||||
if (found != values.end())
|
||||
return std::get<List_sptr>(found->second);
|
||||
if (found != values.end()) return std::get<List_sptr>(found->second);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@ -260,7 +289,9 @@ List_sptr dynamic::create_list(std::initializer_list<Value> values) {
|
||||
return std::make_shared<List>(values);
|
||||
}
|
||||
|
||||
Map_sptr dynamic::create_map(std::initializer_list<std::pair<const std::string, Value>> entries) {
|
||||
Map_sptr dynamic::create_map(
|
||||
std::initializer_list<std::pair<const std::string, Value>> entries
|
||||
) {
|
||||
return std::make_shared<Map>(entries);
|
||||
}
|
||||
|
||||
@ -270,12 +301,12 @@ number_t dynamic::get_number(const Value& value) {
|
||||
} else if (auto num = std::get_if<integer_t>(&value)) {
|
||||
return *num;
|
||||
}
|
||||
throw std::runtime_error("cannot cast "+type_name(value)+" to number");
|
||||
throw std::runtime_error("cannot cast " + type_name(value) + " to number");
|
||||
}
|
||||
|
||||
integer_t dynamic::get_integer(const Value& value) {
|
||||
if (auto num = std::get_if<integer_t>(&value)) {
|
||||
return *num;
|
||||
}
|
||||
throw std::runtime_error("cannot cast "+type_name(value)+" to integer");
|
||||
throw std::runtime_error("cannot cast " + type_name(value) + " to integer");
|
||||
}
|
||||
|
||||
@ -1,28 +1,27 @@
|
||||
#ifndef DATA_DYNAMIC_HPP_
|
||||
#define DATA_DYNAMIC_HPP_
|
||||
|
||||
#include "dynamic_fwd.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <ostream>
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "dynamic_fwd.hpp"
|
||||
|
||||
namespace dynamic {
|
||||
enum class Type {
|
||||
none=0, map, list, string, number, boolean, integer
|
||||
};
|
||||
enum class Type { none = 0, map, list, string, number, boolean, integer };
|
||||
|
||||
const std::string& type_name(const Value& value);
|
||||
List_sptr create_list(std::initializer_list<Value> values={});
|
||||
Map_sptr create_map(std::initializer_list<std::pair<const std::string, Value>> entries={});
|
||||
List_sptr create_list(std::initializer_list<Value> values = {});
|
||||
Map_sptr create_map(
|
||||
std::initializer_list<std::pair<const std::string, Value>> entries = {}
|
||||
);
|
||||
number_t get_number(const Value& value);
|
||||
integer_t get_integer(const Value& value);
|
||||
|
||||
|
||||
inline bool is_numeric(const Value& value) {
|
||||
return std::holds_alternative<number_t>(value) ||
|
||||
std::holds_alternative<integer_t>(value);
|
||||
@ -42,7 +41,8 @@ namespace dynamic {
|
||||
std::vector<Value> values;
|
||||
|
||||
List() = default;
|
||||
List(std::vector<Value> values) : values(std::move(values)) {}
|
||||
List(std::vector<Value> values) : values(std::move(values)) {
|
||||
}
|
||||
|
||||
std::string str(size_t index) const;
|
||||
number_t num(size_t index) const;
|
||||
@ -80,13 +80,13 @@ namespace dynamic {
|
||||
std::unordered_map<std::string, Value> values;
|
||||
|
||||
Map() = default;
|
||||
Map(std::unordered_map<std::string, Value> values)
|
||||
: values(std::move(values)) {};
|
||||
Map(std::unordered_map<std::string, Value> values)
|
||||
: values(std::move(values)) {};
|
||||
|
||||
template<typename T>
|
||||
template <typename T>
|
||||
T get(const std::string& key) const {
|
||||
if (!has(key)) {
|
||||
throw std::runtime_error("missing key '"+key+"'");
|
||||
throw std::runtime_error("missing key '" + key + "'");
|
||||
}
|
||||
return get(key, T());
|
||||
}
|
||||
@ -164,4 +164,4 @@ std::ostream& operator<<(std::ostream& stream, const dynamic::Value& value);
|
||||
std::ostream& operator<<(std::ostream& stream, const dynamic::Map_sptr& value);
|
||||
std::ostream& operator<<(std::ostream& stream, const dynamic::List_sptr& value);
|
||||
|
||||
#endif // DATA_DYNAMIC_HPP_
|
||||
#endif // DATA_DYNAMIC_HPP_
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
#ifndef DATA_DYNAMIC_FWD_HPP_
|
||||
#define DATA_DYNAMIC_FWD_HPP_
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <functional>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
namespace dynamic {
|
||||
class Map;
|
||||
@ -26,10 +26,9 @@ namespace dynamic {
|
||||
std::string,
|
||||
number_t,
|
||||
bool,
|
||||
integer_t
|
||||
>;
|
||||
integer_t>;
|
||||
|
||||
using to_string_func = std::function<std::string(const Value&)>;
|
||||
}
|
||||
|
||||
#endif // DATA_DYNAMIC_FWD_HPP_
|
||||
#endif // DATA_DYNAMIC_FWD_HPP_
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
#ifndef DATA_DYNAMIC_UTIL_HPP_
|
||||
#define DATA_DYNAMIC_UTIL_HPP_
|
||||
|
||||
#include "dynamic.hpp"
|
||||
|
||||
#include <glm/glm.hpp>
|
||||
|
||||
#include "dynamic.hpp"
|
||||
|
||||
namespace dynamic {
|
||||
template<int n>
|
||||
template <int n>
|
||||
inline dynamic::List_sptr to_value(glm::vec<n, float> vec) {
|
||||
auto list = dynamic::create_list();
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
@ -15,7 +15,7 @@ namespace dynamic {
|
||||
return list;
|
||||
}
|
||||
|
||||
template<int n, int m>
|
||||
template <int n, int m>
|
||||
inline dynamic::List_sptr to_value(glm::mat<n, m, float> mat) {
|
||||
auto list = dynamic::create_list();
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
@ -26,8 +26,12 @@ namespace dynamic {
|
||||
return list;
|
||||
}
|
||||
|
||||
template<int n>
|
||||
void get_vec(const dynamic::Map_sptr& root, const std::string& name, glm::vec<n, float>& vec) {
|
||||
template <int n>
|
||||
void get_vec(
|
||||
const dynamic::Map_sptr& root,
|
||||
const std::string& name,
|
||||
glm::vec<n, float>& vec
|
||||
) {
|
||||
if (const auto& list = root->list(name)) {
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
vec[i] = list->num(i);
|
||||
@ -35,8 +39,10 @@ namespace dynamic {
|
||||
}
|
||||
}
|
||||
|
||||
template<int n>
|
||||
void get_vec(const dynamic::List_sptr& root, size_t index, glm::vec<n, float>& vec) {
|
||||
template <int n>
|
||||
void get_vec(
|
||||
const dynamic::List_sptr& root, size_t index, glm::vec<n, float>& vec
|
||||
) {
|
||||
if (const auto& list = root->list(index)) {
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
vec[i] = list->num(i);
|
||||
@ -44,27 +50,33 @@ namespace dynamic {
|
||||
}
|
||||
}
|
||||
|
||||
template<int n, int m>
|
||||
void get_mat(const dynamic::Map_sptr& root, const std::string& name, glm::mat<n, m, float>& mat) {
|
||||
template <int n, int m>
|
||||
void get_mat(
|
||||
const dynamic::Map_sptr& root,
|
||||
const std::string& name,
|
||||
glm::mat<n, m, float>& mat
|
||||
) {
|
||||
if (const auto& list = root->list(name)) {
|
||||
for (size_t y = 0; y < n; y++) {
|
||||
for (size_t x = 0; x < m; x++) {
|
||||
mat[y][x] = list->num(y*m+x);
|
||||
mat[y][x] = list->num(y * m + x);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template<int n, int m>
|
||||
void get_mat(const dynamic::List_sptr& root, size_t index, glm::mat<n, m, float>& mat) {
|
||||
template <int n, int m>
|
||||
void get_mat(
|
||||
const dynamic::List_sptr& root, size_t index, glm::mat<n, m, float>& mat
|
||||
) {
|
||||
if (const auto& list = root->list(index)) {
|
||||
for (size_t y = 0; y < n; y++) {
|
||||
for (size_t x = 0; x < m; x++) {
|
||||
mat[y][x] = list->num(y*m+x);
|
||||
mat[y][x] = list->num(y * m + x);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // DATA_DYNAMIC_UTIL_HPP_
|
||||
#endif // DATA_DYNAMIC_UTIL_HPP_
|
||||
|
||||
@ -7,7 +7,8 @@ std::string NumberSetting::toString() const {
|
||||
case setting_format::simple:
|
||||
return util::to_string(value);
|
||||
case setting_format::percent:
|
||||
return std::to_string(static_cast<integer_t>(round(value * 100))) + "%";
|
||||
return std::to_string(static_cast<integer_t>(round(value * 100))) +
|
||||
"%";
|
||||
default:
|
||||
return "invalid format";
|
||||
}
|
||||
|
||||
@ -3,15 +3,13 @@
|
||||
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
#include "../delegates.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
enum class setting_format {
|
||||
simple, percent
|
||||
};
|
||||
enum class setting_format { simple, percent };
|
||||
|
||||
class Setting {
|
||||
protected:
|
||||
@ -20,7 +18,8 @@ public:
|
||||
Setting(setting_format format) : format(format) {
|
||||
}
|
||||
|
||||
virtual ~Setting() {}
|
||||
virtual ~Setting() {
|
||||
}
|
||||
|
||||
virtual void resetToDefault() = 0;
|
||||
|
||||
@ -31,7 +30,7 @@ public:
|
||||
virtual std::string toString() const = 0;
|
||||
};
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
class ObservableSetting : public Setting {
|
||||
int nextid = 1;
|
||||
std::unordered_map<int, consumer<T>> observers;
|
||||
@ -39,16 +38,17 @@ protected:
|
||||
T initial;
|
||||
T value;
|
||||
public:
|
||||
ObservableSetting(T value, setting_format format)
|
||||
: Setting(format), initial(value), value(value) {}
|
||||
ObservableSetting(T value, setting_format format)
|
||||
: Setting(format), initial(value), value(value) {
|
||||
}
|
||||
|
||||
observer_handler observe(consumer<T> callback, bool callOnStart=false) {
|
||||
observer_handler observe(consumer<T> callback, bool callOnStart = false) {
|
||||
const int id = nextid++;
|
||||
observers.emplace(id, callback);
|
||||
if (callOnStart) {
|
||||
callback(value);
|
||||
}
|
||||
return std::shared_ptr<int>(new int(id), [this](int* id) {
|
||||
return std::shared_ptr<int>(new int(id), [this](int* id) { //-V508
|
||||
observers.erase(*id);
|
||||
delete id;
|
||||
});
|
||||
@ -87,14 +87,13 @@ protected:
|
||||
number_t max;
|
||||
public:
|
||||
NumberSetting(
|
||||
number_t value,
|
||||
number_t min=std::numeric_limits<number_t>::min(),
|
||||
number_t max=std::numeric_limits<number_t>::max(),
|
||||
setting_format format=setting_format::simple
|
||||
) : ObservableSetting(value, format),
|
||||
min(min),
|
||||
max(max)
|
||||
{}
|
||||
number_t value,
|
||||
number_t min = std::numeric_limits<number_t>::min(),
|
||||
number_t max = std::numeric_limits<number_t>::max(),
|
||||
setting_format format = setting_format::simple
|
||||
)
|
||||
: ObservableSetting(value, format), min(min), max(max) {
|
||||
}
|
||||
|
||||
number_t& operator*() {
|
||||
return value;
|
||||
@ -129,14 +128,13 @@ protected:
|
||||
integer_t max;
|
||||
public:
|
||||
IntegerSetting(
|
||||
integer_t value,
|
||||
integer_t min=std::numeric_limits<integer_t>::min(),
|
||||
integer_t max=std::numeric_limits<integer_t>::max(),
|
||||
setting_format format=setting_format::simple
|
||||
) : ObservableSetting(value, format),
|
||||
min(min),
|
||||
max(max)
|
||||
{}
|
||||
integer_t value,
|
||||
integer_t min = std::numeric_limits<integer_t>::min(),
|
||||
integer_t max = std::numeric_limits<integer_t>::max(),
|
||||
setting_format format = setting_format::simple
|
||||
)
|
||||
: ObservableSetting(value, format), min(min), max(max) {
|
||||
}
|
||||
|
||||
integer_t getMin() const {
|
||||
return min;
|
||||
@ -155,10 +153,9 @@ public:
|
||||
|
||||
class FlagSetting : public ObservableSetting<bool> {
|
||||
public:
|
||||
FlagSetting(
|
||||
bool value,
|
||||
setting_format format=setting_format::simple
|
||||
) : ObservableSetting(value, format) {}
|
||||
FlagSetting(bool value, setting_format format = setting_format::simple)
|
||||
: ObservableSetting(value, format) {
|
||||
}
|
||||
|
||||
void toggle() {
|
||||
set(!get());
|
||||
@ -170,11 +167,12 @@ public:
|
||||
class StringSetting : public ObservableSetting<std::string> {
|
||||
public:
|
||||
StringSetting(
|
||||
std::string value,
|
||||
setting_format format=setting_format::simple
|
||||
) : ObservableSetting(value, format) {}
|
||||
std::string value, setting_format format = setting_format::simple
|
||||
)
|
||||
: ObservableSetting(value, format) {
|
||||
}
|
||||
|
||||
virtual std::string toString() const override;
|
||||
};
|
||||
|
||||
#endif // DATA_SETTING_HPP_
|
||||
#endif // DATA_SETTING_HPP_
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
#include "Logger.hpp"
|
||||
|
||||
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <iomanip>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
@ -20,15 +20,17 @@ LogMessage::~LogMessage() {
|
||||
Logger::Logger(std::string name) : name(std::move(name)) {
|
||||
}
|
||||
|
||||
void Logger::log(LogLevel level, const std::string& name, const std::string& message) {
|
||||
void Logger::log(
|
||||
LogLevel level, const std::string& name, const std::string& message
|
||||
) {
|
||||
using namespace std::chrono;
|
||||
|
||||
std::stringstream ss;
|
||||
switch (level) {
|
||||
case LogLevel::debug:
|
||||
# ifdef NDEBUG
|
||||
#ifdef NDEBUG
|
||||
return;
|
||||
# endif
|
||||
#endif
|
||||
ss << "[D]";
|
||||
break;
|
||||
case LogLevel::info:
|
||||
@ -42,10 +44,13 @@ void Logger::log(LogLevel level, const std::string& name, const std::string& mes
|
||||
break;
|
||||
}
|
||||
time_t tm = std::time(nullptr);
|
||||
auto ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()) % 1000;
|
||||
auto ms =
|
||||
duration_cast<milliseconds>(system_clock::now().time_since_epoch()) %
|
||||
1000;
|
||||
ss << " " << std::put_time(std::localtime(&tm), "%Y/%m/%d %T");
|
||||
ss << '.' << std::setfill('0') << std::setw(3) << ms.count();
|
||||
ss << utcOffset << " [" << std::setfill(' ') << std::setw(moduleLen) << name << "] ";
|
||||
ss << utcOffset << " [" << std::setfill(' ') << std::setw(moduleLen) << name
|
||||
<< "] ";
|
||||
ss << message;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
|
||||
@ -1,14 +1,12 @@
|
||||
#ifndef DEBUG_LOGGER_HPP_
|
||||
#define DEBUG_LOGGER_HPP_
|
||||
|
||||
#include <sstream>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
|
||||
namespace debug {
|
||||
enum class LogLevel {
|
||||
debug, info, warning, error
|
||||
};
|
||||
enum class LogLevel { debug, info, warning, error };
|
||||
|
||||
class Logger;
|
||||
|
||||
@ -17,10 +15,12 @@ namespace debug {
|
||||
LogLevel level;
|
||||
std::stringstream ss;
|
||||
public:
|
||||
LogMessage(Logger* logger, LogLevel level) : logger(logger), level(level) {}
|
||||
LogMessage(Logger* logger, LogLevel level)
|
||||
: logger(logger), level(level) {
|
||||
}
|
||||
~LogMessage();
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
LogMessage& operator<<(const T& x) {
|
||||
ss << x;
|
||||
return *this;
|
||||
@ -34,8 +34,10 @@ namespace debug {
|
||||
static unsigned moduleLen;
|
||||
|
||||
std::string name;
|
||||
|
||||
static void log(LogLevel level, const std::string& name, const std::string& message);
|
||||
|
||||
static void log(
|
||||
LogLevel level, const std::string& name, const std::string& message
|
||||
);
|
||||
public:
|
||||
static void init(const std::string& filename);
|
||||
static void flush();
|
||||
@ -62,4 +64,4 @@ namespace debug {
|
||||
};
|
||||
}
|
||||
|
||||
#endif // DEBUG_LOGGER_HPP_
|
||||
#endif // DEBUG_LOGGER_HPP_
|
||||
|
||||
@ -269,7 +269,7 @@ void Engine::loadAssets() {
|
||||
// no need
|
||||
// correct log messages order is more useful
|
||||
bool threading = false;
|
||||
if (threading) {
|
||||
if (threading) { // TODO: Why is always false?
|
||||
auto task = loader.startTask([=](){});
|
||||
task->waitForEnd();
|
||||
} else {
|
||||
|
||||
@ -1,6 +1,9 @@
|
||||
#include "WorldConverter.hpp"
|
||||
|
||||
#include "WorldFiles.hpp"
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
#include "../content/ContentLUT.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
@ -9,11 +12,7 @@
|
||||
#include "../objects/Player.hpp"
|
||||
#include "../util/ThreadPool.hpp"
|
||||
#include "../voxels/Chunk.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
#include "WorldFiles.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
@ -22,8 +21,9 @@ static debug::Logger logger("world-converter");
|
||||
class ConverterWorker : public util::Worker<convert_task, int> {
|
||||
std::shared_ptr<WorldConverter> converter;
|
||||
public:
|
||||
ConverterWorker(std::shared_ptr<WorldConverter> converter)
|
||||
: converter(std::move(converter)) {}
|
||||
ConverterWorker(std::shared_ptr<WorldConverter> converter)
|
||||
: converter(std::move(converter)) {
|
||||
}
|
||||
|
||||
int operator()(const std::shared_ptr<convert_task>& task) override {
|
||||
converter->convert(*task);
|
||||
@ -33,18 +33,20 @@ public:
|
||||
|
||||
WorldConverter::WorldConverter(
|
||||
const fs::path& folder,
|
||||
const Content* content,
|
||||
const Content* content,
|
||||
std::shared_ptr<ContentLUT> lut
|
||||
) : wfile(std::make_unique<WorldFiles>(folder)),
|
||||
lut(std::move(lut)),
|
||||
content(content)
|
||||
{
|
||||
fs::path regionsFolder = wfile->getRegions().getRegionsFolder(REGION_LAYER_VOXELS);
|
||||
)
|
||||
: wfile(std::make_unique<WorldFiles>(folder)),
|
||||
lut(std::move(lut)),
|
||||
content(content) {
|
||||
fs::path regionsFolder =
|
||||
wfile->getRegions().getRegionsFolder(REGION_LAYER_VOXELS);
|
||||
if (!fs::is_directory(regionsFolder)) {
|
||||
logger.error() << "nothing to convert";
|
||||
return;
|
||||
}
|
||||
tasks.push(convert_task {convert_task_type::player, wfile->getPlayerFile()});
|
||||
tasks.push(convert_task {convert_task_type::player, wfile->getPlayerFile()}
|
||||
);
|
||||
for (const auto& file : fs::directory_iterator(regionsFolder)) {
|
||||
tasks.push(convert_task {convert_task_type::region, file.path()});
|
||||
}
|
||||
@ -55,7 +57,7 @@ WorldConverter::~WorldConverter() {
|
||||
|
||||
std::shared_ptr<Task> WorldConverter::startTask(
|
||||
const fs::path& folder,
|
||||
const Content* content,
|
||||
const Content* content,
|
||||
const std::shared_ptr<ContentLUT>& lut,
|
||||
const runnable& onDone,
|
||||
bool multithreading
|
||||
@ -70,7 +72,7 @@ std::shared_ptr<Task> WorldConverter::startTask(
|
||||
}
|
||||
auto pool = std::make_shared<util::ThreadPool<convert_task, int>>(
|
||||
"converter-pool",
|
||||
[=](){return std::make_shared<ConverterWorker>(converter);},
|
||||
[=]() { return std::make_shared<ConverterWorker>(converter); },
|
||||
[=](int&) {}
|
||||
);
|
||||
auto& converterTasks = converter->tasks;
|
||||
@ -111,8 +113,7 @@ void WorldConverter::convertPlayer(const fs::path& file) const {
|
||||
}
|
||||
|
||||
void WorldConverter::convert(const convert_task& task) const {
|
||||
if (!fs::is_regular_file(task.file))
|
||||
return;
|
||||
if (!fs::is_regular_file(task.file)) return;
|
||||
|
||||
switch (task.type) {
|
||||
case convert_task_type::region:
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
#ifndef FILES_WORLD_CONVERTER_HPP_
|
||||
#define FILES_WORLD_CONVERTER_HPP_
|
||||
|
||||
#include <queue>
|
||||
#include <memory>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <queue>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
#include "../delegates.hpp"
|
||||
#include "../interfaces/Task.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
@ -15,9 +15,7 @@ class Content;
|
||||
class ContentLUT;
|
||||
class WorldFiles;
|
||||
|
||||
enum class convert_task_type {
|
||||
region, player
|
||||
};
|
||||
enum class convert_task_type { region, player };
|
||||
|
||||
struct convert_task {
|
||||
convert_task_type type;
|
||||
@ -37,7 +35,7 @@ class WorldConverter : public Task {
|
||||
public:
|
||||
WorldConverter(
|
||||
const fs::path& folder,
|
||||
const Content* content,
|
||||
const Content* content,
|
||||
std::shared_ptr<ContentLUT> lut
|
||||
);
|
||||
~WorldConverter();
|
||||
@ -56,11 +54,11 @@ public:
|
||||
|
||||
static std::shared_ptr<Task> startTask(
|
||||
const fs::path& folder,
|
||||
const Content* content,
|
||||
const Content* content,
|
||||
const std::shared_ptr<ContentLUT>& lut,
|
||||
const runnable& onDone,
|
||||
bool multithreading
|
||||
);
|
||||
};
|
||||
|
||||
#endif // FILES_WORLD_CONVERTER_HPP_
|
||||
#endif // FILES_WORLD_CONVERTER_HPP_
|
||||
|
||||
@ -1,5 +1,13 @@
|
||||
#include "WorldFiles.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
|
||||
#include "../coders/byte_utils.hpp"
|
||||
#include "../coders/json.hpp"
|
||||
#include "../constants.hpp"
|
||||
@ -11,11 +19,11 @@
|
||||
#include "../items/ItemDef.hpp"
|
||||
#include "../lighting/Lightmap.hpp"
|
||||
#include "../maths/voxmaths.hpp"
|
||||
#include "../objects/Player.hpp"
|
||||
#include "../objects/EntityDef.hpp"
|
||||
#include "../objects/Player.hpp"
|
||||
#include "../physics/Hitbox.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../settings.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../util/data_io.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "../voxels/Chunk.hpp"
|
||||
@ -23,24 +31,16 @@
|
||||
#include "../window/Camera.hpp"
|
||||
#include "../world/World.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
|
||||
#define WORLD_FORMAT_MAGIC ".VOXWLD"
|
||||
|
||||
static debug::Logger logger("world-files");
|
||||
|
||||
WorldFiles::WorldFiles(const fs::path& directory) : directory(directory), regions(directory) {
|
||||
WorldFiles::WorldFiles(const fs::path& directory)
|
||||
: directory(directory), regions(directory) {
|
||||
}
|
||||
|
||||
WorldFiles::WorldFiles(const fs::path& directory, const DebugSettings& settings)
|
||||
: WorldFiles(directory)
|
||||
{
|
||||
: WorldFiles(directory) {
|
||||
generatorTestMode = settings.generatorTestMode.get();
|
||||
doWriteLights = settings.doWriteLights.get();
|
||||
regions.generatorTestMode = generatorTestMode;
|
||||
@ -55,23 +55,23 @@ void WorldFiles::createDirectories() {
|
||||
}
|
||||
|
||||
fs::path WorldFiles::getPlayerFile() const {
|
||||
return directory/fs::path("player.json");
|
||||
return directory / fs::path("player.json");
|
||||
}
|
||||
|
||||
fs::path WorldFiles::getResourcesFile() const {
|
||||
return directory/fs::path("resources.json");
|
||||
return directory / fs::path("resources.json");
|
||||
}
|
||||
|
||||
fs::path WorldFiles::getWorldFile() const {
|
||||
return directory/fs::path(WORLD_FILE);
|
||||
return directory / fs::path(WORLD_FILE);
|
||||
}
|
||||
|
||||
fs::path WorldFiles::getIndicesFile() const {
|
||||
return directory/fs::path("indices.json");
|
||||
return directory / fs::path("indices.json");
|
||||
}
|
||||
|
||||
fs::path WorldFiles::getPacksFile() const {
|
||||
return directory/fs::path("packs.list");
|
||||
return directory / fs::path("packs.list");
|
||||
}
|
||||
|
||||
void WorldFiles::write(const World* world, const Content* content) {
|
||||
@ -84,7 +84,7 @@ void WorldFiles::write(const World* world, const Content* content) {
|
||||
if (generatorTestMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
writeIndices(content->getIndices());
|
||||
regions.write();
|
||||
}
|
||||
@ -99,11 +99,13 @@ void WorldFiles::writePacks(const std::vector<ContentPack>& packs) {
|
||||
files::write_string(packsFile, ss.str());
|
||||
}
|
||||
|
||||
template<class T>
|
||||
static void write_indices(const ContentUnitIndices<T>& indices, dynamic::List& list) {
|
||||
template <class T>
|
||||
static void write_indices(
|
||||
const ContentUnitIndices<T>& indices, dynamic::List& list
|
||||
) {
|
||||
size_t count = indices.count();
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
list.put(indices.get(i)->name);
|
||||
list.put(indices.get(i)->name); //FIXME: .get(i) potential null pointer //-V522
|
||||
}
|
||||
}
|
||||
|
||||
@ -131,9 +133,7 @@ bool WorldFiles::readWorldInfo(World* world) {
|
||||
}
|
||||
|
||||
static void read_resources_data(
|
||||
const Content* content,
|
||||
const dynamic::List_sptr& list,
|
||||
ResourceType type
|
||||
const Content* content, const dynamic::List_sptr& list, ResourceType type
|
||||
) {
|
||||
const auto& indices = content->getIndices(type);
|
||||
for (size_t i = 0; i < list->size(); i++) {
|
||||
@ -169,12 +169,11 @@ bool WorldFiles::readResourcesData(const Content* content) {
|
||||
}
|
||||
|
||||
static void erase_pack_indices(dynamic::Map* root, const std::string& id) {
|
||||
auto prefix = id+":";
|
||||
auto prefix = id + ":";
|
||||
auto blocks = root->list("blocks");
|
||||
for (uint i = 0; i < blocks->size(); i++) {
|
||||
auto name = blocks->str(i);
|
||||
if (name.find(prefix) != 0)
|
||||
continue;
|
||||
if (name.find(prefix) != 0) continue;
|
||||
auto value = blocks->getValueWriteable(i);
|
||||
*value = CORE_AIR;
|
||||
}
|
||||
@ -182,8 +181,7 @@ static void erase_pack_indices(dynamic::Map* root, const std::string& id) {
|
||||
auto items = root->list("items");
|
||||
for (uint i = 0; i < items->size(); i++) {
|
||||
auto name = items->str(i);
|
||||
if (name.find(prefix) != 0)
|
||||
continue;
|
||||
if (name.find(prefix) != 0) continue;
|
||||
auto value = items->getValueWriteable(i);
|
||||
*value = CORE_EMPTY;
|
||||
}
|
||||
|
||||
@ -1,19 +1,17 @@
|
||||
#ifndef FILES_WORLD_FILES_HPP_
|
||||
#define FILES_WORLD_FILES_HPP_
|
||||
|
||||
#include "WorldRegions.hpp"
|
||||
|
||||
#include "files.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../content/ContentPack.hpp"
|
||||
#include "../voxels/Chunk.hpp"
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <filesystem>
|
||||
|
||||
#include <glm/glm.hpp>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../content/ContentPack.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../voxels/Chunk.hpp"
|
||||
#include "WorldRegions.hpp"
|
||||
#include "files.hpp"
|
||||
#define GLM_ENABLE_EXPERIMENTAL
|
||||
#include "glm/gtx/hash.hpp"
|
||||
|
||||
@ -41,8 +39,8 @@ class WorldFiles {
|
||||
void writeWorldInfo(const World* world);
|
||||
void writeIndices(const ContentIndices* indices);
|
||||
public:
|
||||
WorldFiles(const fs::path &directory);
|
||||
WorldFiles(const fs::path &directory, const DebugSettings& settings);
|
||||
WorldFiles(const fs::path& directory);
|
||||
WorldFiles(const fs::path& directory, const DebugSettings& settings);
|
||||
~WorldFiles();
|
||||
|
||||
fs::path getPlayerFile() const;
|
||||
@ -75,4 +73,4 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
#endif // FILES_WORLD_FILES_HPP_
|
||||
#endif // FILES_WORLD_FILES_HPP_
|
||||
|
||||
@ -1,5 +1,9 @@
|
||||
#include "WorldRegions.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../coders/byte_utils.hpp"
|
||||
#include "../coders/rle.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
@ -7,10 +11,6 @@
|
||||
#include "../maths/voxmaths.hpp"
|
||||
#include "../util/data_io.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#define REGION_FORMAT_MAGIC ".VOXREG"
|
||||
|
||||
regfile::regfile(fs::path filename) : file(std::move(filename)) {
|
||||
@ -18,15 +18,16 @@ regfile::regfile(fs::path filename) : file(std::move(filename)) {
|
||||
throw std::runtime_error("incomplete region file header");
|
||||
char header[REGION_HEADER_SIZE];
|
||||
file.read(header, REGION_HEADER_SIZE);
|
||||
|
||||
|
||||
// avoid of use strcmp_s
|
||||
if (std::string(header, strlen(REGION_FORMAT_MAGIC)) != REGION_FORMAT_MAGIC) {
|
||||
if (std::string(header, strlen(REGION_FORMAT_MAGIC)) !=
|
||||
REGION_FORMAT_MAGIC) {
|
||||
throw std::runtime_error("invalid region file magic number");
|
||||
}
|
||||
version = header[8];
|
||||
if (uint(version) > REGION_FORMAT_VERSION) {
|
||||
throw illegal_region_format(
|
||||
"region format "+std::to_string(version)+" is not supported"
|
||||
"region format " + std::to_string(version) + " is not supported"
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -39,7 +40,7 @@ std::unique_ptr<ubyte[]> regfile::read(int index, uint32_t& length) {
|
||||
file.seekg(table_offset + index * 4);
|
||||
file.read(reinterpret_cast<char*>(&offset), 4);
|
||||
offset = dataio::read_int32_big(reinterpret_cast<const ubyte*>(&offset), 0);
|
||||
if (offset == 0){
|
||||
if (offset == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@ -52,9 +53,11 @@ std::unique_ptr<ubyte[]> regfile::read(int index, uint32_t& length) {
|
||||
}
|
||||
|
||||
WorldRegion::WorldRegion()
|
||||
: chunksData(std::make_unique<std::unique_ptr<ubyte[]>[]>(REGION_CHUNKS_COUNT)),
|
||||
sizes(std::make_unique<uint32_t[]>(REGION_CHUNKS_COUNT))
|
||||
{}
|
||||
: chunksData(
|
||||
std::make_unique<std::unique_ptr<ubyte[]>[]>(REGION_CHUNKS_COUNT)
|
||||
),
|
||||
sizes(std::make_unique<uint32_t[]>(REGION_CHUNKS_COUNT)) {
|
||||
}
|
||||
|
||||
WorldRegion::~WorldRegion() = default;
|
||||
|
||||
@ -88,13 +91,14 @@ uint WorldRegion::getChunkDataSize(uint x, uint z) {
|
||||
}
|
||||
|
||||
WorldRegions::WorldRegions(const fs::path& directory) : directory(directory) {
|
||||
for (size_t i = 0; i < sizeof(layers)/sizeof(RegionsLayer); i++) {
|
||||
for (size_t i = 0; i < sizeof(layers) / sizeof(RegionsLayer); i++) {
|
||||
layers[i].layer = i;
|
||||
}
|
||||
layers[REGION_LAYER_VOXELS].folder = directory/fs::path("regions");
|
||||
layers[REGION_LAYER_LIGHTS].folder = directory/fs::path("lights");
|
||||
layers[REGION_LAYER_INVENTORIES].folder = directory/fs::path("inventories");
|
||||
layers[REGION_LAYER_ENTITIES].folder = directory/fs::path("entities");
|
||||
layers[REGION_LAYER_VOXELS].folder = directory / fs::path("regions");
|
||||
layers[REGION_LAYER_LIGHTS].folder = directory / fs::path("lights");
|
||||
layers[REGION_LAYER_INVENTORIES].folder =
|
||||
directory / fs::path("inventories");
|
||||
layers[REGION_LAYER_ENTITIES].folder = directory / fs::path("entities");
|
||||
}
|
||||
|
||||
WorldRegions::~WorldRegions() = default;
|
||||
@ -121,10 +125,12 @@ WorldRegion* WorldRegions::getOrCreateRegion(int x, int z, int layer) {
|
||||
return region;
|
||||
}
|
||||
|
||||
std::unique_ptr<ubyte[]> WorldRegions::compress(const ubyte* src, size_t srclen, size_t& len) {
|
||||
std::unique_ptr<ubyte[]> WorldRegions::compress(
|
||||
const ubyte* src, size_t srclen, size_t& len
|
||||
) {
|
||||
auto buffer = bufferPool.get();
|
||||
auto bytes = buffer.get();
|
||||
|
||||
|
||||
len = extrle::encode(src, srclen, bytes);
|
||||
auto data = std::make_unique<ubyte[]>(len);
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
@ -133,7 +139,9 @@ std::unique_ptr<ubyte[]> WorldRegions::compress(const ubyte* src, size_t srclen,
|
||||
return data;
|
||||
}
|
||||
|
||||
std::unique_ptr<ubyte[]> WorldRegions::decompress(const ubyte* src, size_t srclen, size_t dstlen) {
|
||||
std::unique_ptr<ubyte[]> WorldRegions::decompress(
|
||||
const ubyte* src, size_t srclen, size_t dstlen
|
||||
) {
|
||||
auto decompressed = std::make_unique<ubyte[]>(dstlen);
|
||||
extrle::decode(src, srclen, decompressed.get());
|
||||
return decompressed;
|
||||
@ -157,8 +165,10 @@ std::unique_ptr<ubyte[]> WorldRegions::readChunkData(
|
||||
return rfile->read(chunkIndex, length);
|
||||
}
|
||||
|
||||
/// @brief Read missing chunks data (null pointers) from region file
|
||||
void WorldRegions::fetchChunks(WorldRegion* region, int x, int z, regfile* file) {
|
||||
/// @brief Read missing chunks data (null pointers) from region file
|
||||
void WorldRegions::fetchChunks(
|
||||
WorldRegion* region, int x, int z, regfile* file
|
||||
) {
|
||||
auto* chunks = region->getChunks();
|
||||
uint32_t* sizes = region->getSizes();
|
||||
|
||||
@ -226,7 +236,8 @@ regfile_ptr WorldRegions::getRegFile(glm::ivec3 coord, bool create) {
|
||||
}
|
||||
|
||||
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)) {
|
||||
return nullptr;
|
||||
}
|
||||
@ -261,8 +272,8 @@ fs::path WorldRegions::getRegionFilename(int x, int z) const {
|
||||
return fs::path(std::to_string(x) + "_" + std::to_string(z) + ".bin");
|
||||
}
|
||||
|
||||
void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){
|
||||
fs::path filename = layers[layer].folder/getRegionFilename(x, z);
|
||||
void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry) {
|
||||
fs::path filename = layers[layer].folder / getRegionFilename(x, z);
|
||||
|
||||
glm::ivec3 regcoord(x, z, layer);
|
||||
if (auto regfile = getRegFile(regcoord, false)) {
|
||||
@ -272,29 +283,31 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){
|
||||
regfile.reset();
|
||||
closeRegFile(regcoord);
|
||||
}
|
||||
|
||||
|
||||
char header[REGION_HEADER_SIZE] = REGION_FORMAT_MAGIC;
|
||||
header[8] = REGION_FORMAT_VERSION;
|
||||
header[9] = 0; // flags
|
||||
header[9] = 0; // flags
|
||||
std::ofstream file(filename, std::ios::out | std::ios::binary);
|
||||
file.write(header, REGION_HEADER_SIZE);
|
||||
|
||||
size_t offset = REGION_HEADER_SIZE;
|
||||
char intbuf[4]{};
|
||||
uint offsets[REGION_CHUNKS_COUNT]{};
|
||||
|
||||
char intbuf[4] {};
|
||||
uint offsets[REGION_CHUNKS_COUNT] {};
|
||||
|
||||
auto* region = entry->getChunks();
|
||||
uint32_t* sizes = entry->getSizes();
|
||||
|
||||
|
||||
for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) {
|
||||
ubyte* chunk = region[i].get();
|
||||
if (chunk == nullptr){
|
||||
if (chunk == nullptr) {
|
||||
offsets[i] = 0;
|
||||
} else {
|
||||
offsets[i] = offset;
|
||||
|
||||
size_t compressedSize = sizes[i];
|
||||
dataio::write_int32_big(compressedSize, reinterpret_cast<ubyte*>(intbuf), 0);
|
||||
dataio::write_int32_big(
|
||||
compressedSize, reinterpret_cast<ubyte*>(intbuf), 0
|
||||
);
|
||||
offset += 4 + compressedSize;
|
||||
|
||||
file.write(intbuf, 4);
|
||||
@ -302,13 +315,15 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){
|
||||
}
|
||||
}
|
||||
for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) {
|
||||
dataio::write_int32_big(offsets[i], reinterpret_cast<ubyte*>(intbuf), 0);
|
||||
dataio::write_int32_big(
|
||||
offsets[i], reinterpret_cast<ubyte*>(intbuf), 0
|
||||
);
|
||||
file.write(intbuf, 4);
|
||||
}
|
||||
}
|
||||
|
||||
void WorldRegions::writeRegions(int layer) {
|
||||
for (auto& it : layers[layer].regions){
|
||||
for (auto& it : layers[layer].regions) {
|
||||
WorldRegion* region = it.second.get();
|
||||
if (region->getChunks() == nullptr || !region->isUnsaved()) {
|
||||
continue;
|
||||
@ -318,7 +333,14 @@ void WorldRegions::writeRegions(int layer) {
|
||||
}
|
||||
}
|
||||
|
||||
void WorldRegions::put(int x, int z, int layer, std::unique_ptr<ubyte[]> data, size_t size, bool rle) {
|
||||
void WorldRegions::put(
|
||||
int x,
|
||||
int z,
|
||||
int layer,
|
||||
std::unique_ptr<ubyte[]> data,
|
||||
size_t size,
|
||||
bool rle
|
||||
) {
|
||||
if (rle) {
|
||||
size_t compressedSize;
|
||||
auto compressed = compress(data.get(), size, compressedSize);
|
||||
@ -333,7 +355,9 @@ void WorldRegions::put(int x, int z, int layer, std::unique_ptr<ubyte[]> data, s
|
||||
region->put(localX, localZ, data.release(), size);
|
||||
}
|
||||
|
||||
static std::unique_ptr<ubyte[]> write_inventories(Chunk* chunk, uint& datasize) {
|
||||
static std::unique_ptr<ubyte[]> write_inventories(
|
||||
Chunk* chunk, uint& datasize
|
||||
) {
|
||||
auto& inventories = chunk->inventories;
|
||||
ByteBuilder builder;
|
||||
builder.putInt32(inventories.size());
|
||||
@ -343,7 +367,7 @@ static std::unique_ptr<ubyte[]> write_inventories(Chunk* chunk, uint& datasize)
|
||||
auto bytes = json::to_binary(map.get(), true);
|
||||
builder.putInt32(bytes.size());
|
||||
builder.put(bytes.data(), bytes.size());
|
||||
}
|
||||
}
|
||||
auto datavec = builder.data();
|
||||
datasize = builder.size();
|
||||
auto data = std::make_unique<ubyte[]>(datasize);
|
||||
@ -352,7 +376,7 @@ static std::unique_ptr<ubyte[]> write_inventories(Chunk* chunk, uint& datasize)
|
||||
}
|
||||
|
||||
/// @brief Store chunk data (voxels and lights) in region (existing or new)
|
||||
void WorldRegions::put(Chunk* chunk, std::vector<ubyte> entitiesData){
|
||||
void WorldRegions::put(Chunk* chunk, std::vector<ubyte> entitiesData) {
|
||||
assert(chunk != nullptr);
|
||||
if (!chunk->flags.lighted) {
|
||||
return;
|
||||
@ -365,20 +389,32 @@ void WorldRegions::put(Chunk* chunk, std::vector<ubyte> entitiesData){
|
||||
int regionX, regionZ, localX, localZ;
|
||||
calc_reg_coords(chunk->x, chunk->z, regionX, regionZ, localX, localZ);
|
||||
|
||||
put(chunk->x, chunk->z, REGION_LAYER_VOXELS,
|
||||
chunk->encode(), CHUNK_DATA_LEN, true);
|
||||
put(chunk->x,
|
||||
chunk->z,
|
||||
REGION_LAYER_VOXELS,
|
||||
chunk->encode(),
|
||||
CHUNK_DATA_LEN,
|
||||
true);
|
||||
|
||||
// Writing lights cache
|
||||
if (doWriteLights && chunk->flags.lighted) {
|
||||
put(chunk->x, chunk->z, REGION_LAYER_LIGHTS,
|
||||
chunk->lightmap.encode(), LIGHTMAP_DATA_LEN, true);
|
||||
put(chunk->x,
|
||||
chunk->z,
|
||||
REGION_LAYER_LIGHTS,
|
||||
chunk->lightmap.encode(),
|
||||
LIGHTMAP_DATA_LEN,
|
||||
true);
|
||||
}
|
||||
// Writing block inventories
|
||||
if (!chunk->inventories.empty()) {
|
||||
uint datasize;
|
||||
auto data = write_inventories(chunk, datasize);
|
||||
put(chunk->x, chunk->z, REGION_LAYER_INVENTORIES,
|
||||
std::move(data), datasize, false);
|
||||
put(chunk->x,
|
||||
chunk->z,
|
||||
REGION_LAYER_INVENTORIES,
|
||||
std::move(data),
|
||||
datasize,
|
||||
false);
|
||||
}
|
||||
// Writing entities
|
||||
if (!entitiesData.empty()) {
|
||||
@ -386,12 +422,16 @@ void WorldRegions::put(Chunk* chunk, std::vector<ubyte> entitiesData){
|
||||
for (size_t i = 0; i < entitiesData.size(); i++) {
|
||||
data[i] = entitiesData[i];
|
||||
}
|
||||
put(chunk->x, chunk->z, REGION_LAYER_ENTITIES,
|
||||
std::move(data), entitiesData.size(), false);
|
||||
put(chunk->x,
|
||||
chunk->z,
|
||||
REGION_LAYER_ENTITIES,
|
||||
std::move(data),
|
||||
entitiesData.size(),
|
||||
false);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<ubyte[]> WorldRegions::getChunk(int x, int z){
|
||||
std::unique_ptr<ubyte[]> WorldRegions::getChunk(int x, int z) {
|
||||
uint32_t size;
|
||||
auto* data = getData(x, z, REGION_LAYER_VOXELS, size);
|
||||
if (data == nullptr) {
|
||||
@ -400,7 +440,7 @@ std::unique_ptr<ubyte[]> WorldRegions::getChunk(int x, int z){
|
||||
return decompress(data, size, CHUNK_DATA_LEN);
|
||||
}
|
||||
|
||||
/// @brief Get cached lights for chunk at x,z
|
||||
/// @brief Get cached lights for chunk at x,z
|
||||
/// @return lights data or nullptr
|
||||
std::unique_ptr<light_t[]> WorldRegions::getLights(int x, int z) {
|
||||
uint32_t size;
|
||||
@ -433,7 +473,7 @@ chunk_inventories_map WorldRegions::fetchInventories(int x, int z) {
|
||||
return meta;
|
||||
}
|
||||
|
||||
dynamic::Map_sptr WorldRegions::fetchEntities(int x, int z) {
|
||||
dynamic::Map_sptr WorldRegions::fetchEntities(int x, int z) {
|
||||
uint32_t bytesSize;
|
||||
const ubyte* data = getData(x, z, REGION_LAYER_ENTITIES, bytesSize);
|
||||
if (data == nullptr) {
|
||||
@ -444,7 +484,7 @@ chunk_inventories_map WorldRegions::fetchInventories(int x, int z) {
|
||||
return nullptr;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
void WorldRegions::processRegionVoxels(int x, int z, const regionproc& func) {
|
||||
if (getRegion(x, z, REGION_LAYER_VOXELS)) {
|
||||
@ -465,7 +505,12 @@ void WorldRegions::processRegionVoxels(int x, int z, const regionproc& func) {
|
||||
}
|
||||
data = decompress(data.get(), length, CHUNK_DATA_LEN);
|
||||
if (func(data.get())) {
|
||||
put(gx, gz, REGION_LAYER_VOXELS, std::move(data), CHUNK_DATA_LEN, true);
|
||||
put(gx,
|
||||
gz,
|
||||
REGION_LAYER_VOXELS,
|
||||
std::move(data),
|
||||
CHUNK_DATA_LEN,
|
||||
true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -475,7 +520,6 @@ fs::path WorldRegions::getRegionsFolder(int layer) const {
|
||||
return layers[layer].folder;
|
||||
}
|
||||
|
||||
|
||||
void WorldRegions::write() {
|
||||
for (auto& layer : layers) {
|
||||
fs::create_directories(layer.folder);
|
||||
@ -483,14 +527,16 @@ 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('_');
|
||||
if (sep == std::string::npos || sep == 0 || sep == name.length()-1) {
|
||||
if (sep == std::string::npos || sep == 0 || sep == name.length() - 1) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
x = std::stoi(name.substr(0, sep));
|
||||
z = std::stoi(name.substr(sep+1));
|
||||
z = std::stoi(name.substr(sep + 1));
|
||||
} catch (std::invalid_argument& err) {
|
||||
return false;
|
||||
} catch (std::out_of_range& err) {
|
||||
|
||||
@ -1,20 +1,19 @@
|
||||
#ifndef FILES_WORLD_REGIONS_HPP_
|
||||
#define FILES_WORLD_REGIONS_HPP_
|
||||
|
||||
#include "files.hpp"
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <glm/glm.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "../data/dynamic_fwd.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../util/BufferPool.hpp"
|
||||
#include "../voxels/Chunk.hpp"
|
||||
#include "../data/dynamic_fwd.hpp"
|
||||
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include <filesystem>
|
||||
#include <unordered_map>
|
||||
#include <condition_variable>
|
||||
|
||||
#include <glm/glm.hpp>
|
||||
#include "files.hpp"
|
||||
#define GLM_ENABLE_EXPERIMENTAL
|
||||
#include "glm/gtx/hash.hpp"
|
||||
|
||||
@ -35,8 +34,9 @@ inline constexpr uint MAX_OPEN_REGION_FILES = 16;
|
||||
|
||||
class illegal_region_format : public std::runtime_error {
|
||||
public:
|
||||
illegal_region_format(const std::string& message)
|
||||
: std::runtime_error(message) {}
|
||||
illegal_region_format(const std::string& message)
|
||||
: std::runtime_error(message) {
|
||||
}
|
||||
};
|
||||
|
||||
class WorldRegion {
|
||||
@ -83,14 +83,14 @@ class regfile_ptr {
|
||||
regfile* file;
|
||||
std::condition_variable* cv;
|
||||
public:
|
||||
regfile_ptr(
|
||||
regfile* file,
|
||||
std::condition_variable* cv
|
||||
) : file(file), cv(cv) {}
|
||||
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) {}
|
||||
regfile_ptr(std::nullptr_t) : file(nullptr), cv(nullptr) {
|
||||
}
|
||||
|
||||
bool operator==(std::nullptr_t) const {
|
||||
return file == nullptr;
|
||||
@ -123,8 +123,7 @@ class WorldRegions {
|
||||
std::condition_variable regFilesCv;
|
||||
RegionsLayer layers[4] {};
|
||||
util::BufferPool<ubyte> bufferPool {
|
||||
std::max(CHUNK_DATA_LEN, LIGHTMAP_DATA_LEN) * 2
|
||||
};
|
||||
std::max(CHUNK_DATA_LEN, LIGHTMAP_DATA_LEN) * 2};
|
||||
|
||||
WorldRegion* getRegion(int x, int z, int layer);
|
||||
WorldRegion* getOrCreateRegion(int x, int z, int layer);
|
||||
@ -134,22 +133,28 @@ class WorldRegions {
|
||||
/// @param srclen length of the source buffer
|
||||
/// @param len (out argument) length of result buffer
|
||||
/// @return compressed bytes array
|
||||
std::unique_ptr<ubyte[]> compress(const ubyte* src, size_t srclen, size_t& len);
|
||||
std::unique_ptr<ubyte[]> compress(
|
||||
const ubyte* src, size_t srclen, size_t& len
|
||||
);
|
||||
|
||||
/// @brief Decompress buffer with extrle
|
||||
/// @param src compressed buffer
|
||||
/// @param srclen length of compressed buffer
|
||||
/// @param dstlen max expected length of source buffer
|
||||
/// @return decompressed bytes array
|
||||
std::unique_ptr<ubyte[]> decompress(const ubyte* src, size_t srclen, size_t dstlen);
|
||||
std::unique_ptr<ubyte[]> decompress(
|
||||
const ubyte* src, size_t srclen, size_t dstlen
|
||||
);
|
||||
|
||||
std::unique_ptr<ubyte[]> readChunkData(int x, int y, uint32_t& length, regfile* file);
|
||||
std::unique_ptr<ubyte[]> readChunkData(
|
||||
int x, int y, uint32_t& length, regfile* file
|
||||
);
|
||||
|
||||
void fetchChunks(WorldRegion* region, int x, int y, regfile* file);
|
||||
|
||||
ubyte* getData(int x, int z, int layer, uint32_t& size);
|
||||
|
||||
regfile_ptr getRegFile(glm::ivec3 coord, bool create=true);
|
||||
regfile_ptr getRegFile(glm::ivec3 coord, bool create = true);
|
||||
void closeRegFile(glm::ivec3 coord);
|
||||
regfile_ptr useRegFile(glm::ivec3 coord);
|
||||
regfile_ptr createRegFile(glm::ivec3 coord);
|
||||
@ -174,19 +179,26 @@ public:
|
||||
/// @brief Put all chunk data to regions
|
||||
void put(Chunk* chunk, std::vector<ubyte> entitiesData);
|
||||
|
||||
/// @brief Store data in specified region
|
||||
/// @brief Store data in specified region
|
||||
/// @param x chunk.x
|
||||
/// @param z chunk.z
|
||||
/// @param layer regions layer
|
||||
/// @param data target data
|
||||
/// @param size data size
|
||||
/// @param rle compress with ext-RLE
|
||||
void put(int x, int z, int layer, std::unique_ptr<ubyte[]> data, size_t size, bool rle);
|
||||
void put(
|
||||
int x,
|
||||
int z,
|
||||
int layer,
|
||||
std::unique_ptr<ubyte[]> data,
|
||||
size_t size,
|
||||
bool rle
|
||||
);
|
||||
|
||||
std::unique_ptr<ubyte[]> getChunk(int x, int z);
|
||||
std::unique_ptr<light_t[]> getLights(int x, int z);
|
||||
chunk_inventories_map fetchInventories(int x, int z);
|
||||
dynamic::Map_sptr fetchEntities(int x, int z);
|
||||
dynamic::Map_sptr fetchEntities(int x, int z);
|
||||
|
||||
void processRegionVoxels(int x, int z, const regionproc& func);
|
||||
|
||||
@ -202,4 +214,4 @@ public:
|
||||
static bool parseRegionFilename(const std::string& name, int& x, int& y);
|
||||
};
|
||||
|
||||
#endif // FILES_WORLD_REGIONS_HPP_
|
||||
#endif // FILES_WORLD_REGIONS_HPP_
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
#include "engine_paths.hpp"
|
||||
|
||||
#include <stack>
|
||||
#include <sstream>
|
||||
#include <filesystem>
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <sstream>
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
|
||||
#include "../util/stringutil.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
#include "WorldFiles.hpp"
|
||||
|
||||
const fs::path SCREENSHOTS_FOLDER {"screenshots"};
|
||||
@ -16,7 +16,7 @@ const fs::path CONTROLS_FILE {"controls.toml"};
|
||||
const fs::path SETTINGS_FILE {"settings.toml"};
|
||||
|
||||
void EnginePaths::prepare() {
|
||||
fs::path contentFolder = userfiles/fs::path(CONTENT_FOLDER);
|
||||
fs::path contentFolder = userfiles / fs::path(CONTENT_FOLDER);
|
||||
if (!fs::is_directory(contentFolder)) {
|
||||
fs::create_directories(contentFolder);
|
||||
}
|
||||
@ -31,7 +31,7 @@ fs::path EnginePaths::getResources() const {
|
||||
}
|
||||
|
||||
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)) {
|
||||
fs::create_directory(folder);
|
||||
}
|
||||
@ -44,17 +44,21 @@ fs::path EnginePaths::getScreenshotFile(const std::string& ext) {
|
||||
ss << std::put_time(&tm, format);
|
||||
std::string datetimestr = ss.str();
|
||||
|
||||
fs::path filename = folder/fs::u8path("screenshot-"+datetimestr+"."+ext);
|
||||
fs::path filename =
|
||||
folder / fs::u8path("screenshot-" + datetimestr + "." + ext);
|
||||
uint index = 0;
|
||||
while (fs::exists(filename)) {
|
||||
filename = folder/fs::u8path("screenshot-"+datetimestr+"-"+std::to_string(index)+"."+ext);
|
||||
filename = folder / fs::u8path(
|
||||
"screenshot-" + datetimestr + "-" +
|
||||
std::to_string(index) + "." + ext
|
||||
);
|
||||
index++;
|
||||
}
|
||||
return filename;
|
||||
}
|
||||
|
||||
fs::path EnginePaths::getWorldsFolder() {
|
||||
return userfiles/fs::path("worlds");
|
||||
return userfiles / fs::path("worlds");
|
||||
}
|
||||
|
||||
fs::path EnginePaths::getWorldFolder() {
|
||||
@ -62,45 +66,44 @@ fs::path EnginePaths::getWorldFolder() {
|
||||
}
|
||||
|
||||
fs::path EnginePaths::getWorldFolder(const std::string& name) {
|
||||
return getWorldsFolder()/fs::path(name);
|
||||
return getWorldsFolder() / fs::path(name);
|
||||
}
|
||||
|
||||
fs::path EnginePaths::getControlsFile() {
|
||||
return userfiles/fs::path(CONTROLS_FILE);
|
||||
return userfiles / fs::path(CONTROLS_FILE);
|
||||
}
|
||||
|
||||
fs::path EnginePaths::getSettingsFile() {
|
||||
return userfiles/fs::path(SETTINGS_FILE);
|
||||
return userfiles / fs::path(SETTINGS_FILE);
|
||||
}
|
||||
|
||||
std::vector<fs::path> EnginePaths::scanForWorlds() {
|
||||
std::vector<fs::path> folders;
|
||||
|
||||
fs::path folder = getWorldsFolder();
|
||||
if (!fs::is_directory(folder))
|
||||
return folders;
|
||||
|
||||
if (!fs::is_directory(folder)) return folders;
|
||||
|
||||
for (const auto& entry : fs::directory_iterator(folder)) {
|
||||
if (!entry.is_directory()) {
|
||||
continue;
|
||||
}
|
||||
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)) {
|
||||
continue;
|
||||
}
|
||||
folders.push_back(worldFolder);
|
||||
}
|
||||
std::sort(folders.begin(), folders.end(), [](fs::path a, fs::path b) {
|
||||
a = a/fs::u8path(WorldFiles::WORLD_FILE);
|
||||
b = b/fs::u8path(WorldFiles::WORLD_FILE);
|
||||
a = a / fs::u8path(WorldFiles::WORLD_FILE);
|
||||
b = b / fs::u8path(WorldFiles::WORLD_FILE);
|
||||
return fs::last_write_time(a) > fs::last_write_time(b);
|
||||
});
|
||||
return folders;
|
||||
}
|
||||
|
||||
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) {
|
||||
@ -125,8 +128,7 @@ static fs::path toCanonic(fs::path path) {
|
||||
while (true) {
|
||||
parts.push(path.filename().u8string());
|
||||
path = path.parent_path();
|
||||
if (path.empty())
|
||||
break;
|
||||
if (path.empty()) break;
|
||||
}
|
||||
path = fs::u8path("");
|
||||
while (!parts.empty()) {
|
||||
@ -150,38 +152,38 @@ fs::path EnginePaths::resolve(const std::string& path, bool throwErr) {
|
||||
throw files_access_error("no entry point specified");
|
||||
}
|
||||
std::string prefix = path.substr(0, separator);
|
||||
std::string filename = path.substr(separator+1);
|
||||
std::string filename = path.substr(separator + 1);
|
||||
filename = toCanonic(fs::u8path(filename)).u8string();
|
||||
|
||||
if (prefix == "res" || prefix == "core") {
|
||||
return resources/fs::u8path(filename);
|
||||
return resources / fs::u8path(filename);
|
||||
}
|
||||
if (prefix == "user") {
|
||||
return userfiles/fs::u8path(filename);
|
||||
return userfiles / fs::u8path(filename);
|
||||
}
|
||||
if (prefix == "world") {
|
||||
return worldFolder/fs::u8path(filename);
|
||||
return worldFolder / fs::u8path(filename);
|
||||
}
|
||||
|
||||
if (contentPacks) {
|
||||
for (auto& pack : *contentPacks) {
|
||||
if (pack.id == prefix) {
|
||||
return pack.folder/fs::u8path(filename);
|
||||
return pack.folder / fs::u8path(filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (throwErr) {
|
||||
throw files_access_error("unknown entry point '"+prefix+"'");
|
||||
throw files_access_error("unknown entry point '" + prefix + "'");
|
||||
}
|
||||
return fs::path(filename);
|
||||
}
|
||||
|
||||
ResPaths::ResPaths(fs::path mainRoot, std::vector<PathsRoot> roots)
|
||||
ResPaths::ResPaths(fs::path mainRoot, std::vector<PathsRoot> roots)
|
||||
: mainRoot(std::move(mainRoot)), roots(std::move(roots)) {
|
||||
}
|
||||
|
||||
fs::path ResPaths::find(const std::string& filename) const {
|
||||
for (int i = roots.size()-1; i >= 0; i--) {
|
||||
for (int i = roots.size() - 1; i >= 0; i--) {
|
||||
auto& root = roots[i];
|
||||
fs::path file = root.path / fs::u8path(filename);
|
||||
if (fs::exists(file)) {
|
||||
@ -192,7 +194,7 @@ fs::path ResPaths::find(const std::string& filename) const {
|
||||
}
|
||||
|
||||
std::string ResPaths::findRaw(const std::string& filename) const {
|
||||
for (int i = roots.size()-1; i >= 0; i--) {
|
||||
for (int i = roots.size() - 1; i >= 0; i--) {
|
||||
auto& root = roots[i];
|
||||
if (fs::exists(root.path / fs::path(filename))) {
|
||||
return root.name + ":" + filename;
|
||||
@ -200,30 +202,29 @@ std::string ResPaths::findRaw(const std::string& filename) const {
|
||||
}
|
||||
auto resDir = mainRoot;
|
||||
if (fs::exists(resDir / fs::path(filename))) {
|
||||
return "core:"+filename;
|
||||
return "core:" + filename;
|
||||
}
|
||||
throw std::runtime_error("could not to find file "+util::quote(filename));
|
||||
throw std::runtime_error("could not to find file " + util::quote(filename));
|
||||
}
|
||||
|
||||
std::vector<std::string> ResPaths::listdirRaw(const std::string& folderName) const {
|
||||
std::vector<std::string> ResPaths::listdirRaw(const std::string& folderName
|
||||
) const {
|
||||
std::vector<std::string> entries;
|
||||
for (int i = roots.size()-1; i >= 0; i--) {
|
||||
for (int i = roots.size() - 1; i >= 0; i--) {
|
||||
auto& root = roots[i];
|
||||
fs::path folder = root.path / fs::u8path(folderName);
|
||||
if (!fs::is_directory(folder))
|
||||
continue;
|
||||
if (!fs::is_directory(folder)) continue;
|
||||
for (const auto& entry : fs::directory_iterator(folder)) {
|
||||
auto name = entry.path().filename().u8string();
|
||||
entries.emplace_back(root.name+":"+folderName+"/"+name);
|
||||
entries.emplace_back(root.name + ":" + folderName + "/" + name);
|
||||
}
|
||||
}
|
||||
{
|
||||
fs::path folder = mainRoot / fs::u8path(folderName);
|
||||
if (!fs::is_directory(folder))
|
||||
return entries;
|
||||
if (!fs::is_directory(folder)) return entries;
|
||||
for (const auto& entry : fs::directory_iterator(folder)) {
|
||||
auto name = entry.path().filename().u8string();
|
||||
entries.emplace_back("core:"+folderName+"/"+name);
|
||||
entries.emplace_back("core:" + folderName + "/" + name);
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
@ -231,19 +232,17 @@ std::vector<std::string> ResPaths::listdirRaw(const std::string& folderName) con
|
||||
|
||||
std::vector<fs::path> ResPaths::listdir(const std::string& folderName) const {
|
||||
std::vector<fs::path> entries;
|
||||
for (int i = roots.size()-1; i >= 0; i--) {
|
||||
for (int i = roots.size() - 1; i >= 0; i--) {
|
||||
auto& root = roots[i];
|
||||
fs::path folder = root.path / fs::u8path(folderName);
|
||||
if (!fs::is_directory(folder))
|
||||
continue;
|
||||
if (!fs::is_directory(folder)) continue;
|
||||
for (const auto& entry : fs::directory_iterator(folder)) {
|
||||
entries.push_back(entry.path());
|
||||
}
|
||||
}
|
||||
{
|
||||
fs::path folder = mainRoot / fs::u8path(folderName);
|
||||
if (!fs::is_directory(folder))
|
||||
return entries;
|
||||
if (!fs::is_directory(folder)) return entries;
|
||||
for (const auto& entry : fs::directory_iterator(folder)) {
|
||||
entries.push_back(entry.path());
|
||||
}
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
#ifndef FILES_ENGINE_PATHS_HPP_
|
||||
#define FILES_ENGINE_PATHS_HPP_
|
||||
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
#include <filesystem>
|
||||
|
||||
#include "../content/ContentPack.hpp"
|
||||
|
||||
@ -12,12 +12,13 @@ namespace fs = std::filesystem;
|
||||
|
||||
class files_access_error : public std::runtime_error {
|
||||
public:
|
||||
files_access_error(const std::string& msg) : std::runtime_error(msg) {}
|
||||
files_access_error(const std::string& msg) : std::runtime_error(msg) {
|
||||
}
|
||||
};
|
||||
|
||||
class EnginePaths {
|
||||
fs::path userfiles {"."};
|
||||
fs::path resources {"res"};
|
||||
fs::path resources {"res"};
|
||||
fs::path worldFolder;
|
||||
std::vector<ContentPack>* contentPacks = nullptr;
|
||||
public:
|
||||
@ -25,7 +26,7 @@ public:
|
||||
|
||||
fs::path getUserfiles() const;
|
||||
fs::path getResources() const;
|
||||
|
||||
|
||||
fs::path getScreenshotFile(const std::string& ext);
|
||||
fs::path getWorldsFolder();
|
||||
fs::path getWorldFolder();
|
||||
@ -41,7 +42,7 @@ public:
|
||||
|
||||
std::vector<fs::path> scanForWorlds();
|
||||
|
||||
fs::path resolve(const std::string& path, bool throwErr=true);
|
||||
fs::path resolve(const std::string& path, bool throwErr = true);
|
||||
};
|
||||
|
||||
struct PathsRoot {
|
||||
@ -53,11 +54,8 @@ class ResPaths {
|
||||
fs::path mainRoot;
|
||||
std::vector<PathsRoot> roots;
|
||||
public:
|
||||
ResPaths(
|
||||
fs::path mainRoot,
|
||||
std::vector<PathsRoot> roots
|
||||
);
|
||||
|
||||
ResPaths(fs::path mainRoot, std::vector<PathsRoot> roots);
|
||||
|
||||
fs::path find(const std::string& filename) const;
|
||||
std::string findRaw(const std::string& filename) const;
|
||||
std::vector<fs::path> listdir(const std::string& folder) const;
|
||||
@ -66,4 +64,4 @@ public:
|
||||
const fs::path& getMainRoot() const;
|
||||
};
|
||||
|
||||
#endif // FILES_ENGINE_PATHS_HPP_
|
||||
#endif // FILES_ENGINE_PATHS_HPP_
|
||||
|
||||
@ -1,24 +1,25 @@
|
||||
#include "files.hpp"
|
||||
|
||||
#include "../coders/commons.hpp"
|
||||
#include "../coders/json.hpp"
|
||||
#include "../coders/toml.hpp"
|
||||
#include "../coders/gzip.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include <stdint.h>
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <stdint.h>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "../coders/commons.hpp"
|
||||
#include "../coders/gzip.hpp"
|
||||
#include "../coders/json.hpp"
|
||||
#include "../coders/toml.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
files::rafile::rafile(const fs::path& filename)
|
||||
: file(filename, std::ios::binary | std::ios::ate) {
|
||||
if (!file) {
|
||||
throw std::runtime_error("could not to open file "+filename.string());
|
||||
throw std::runtime_error("could not to open file " + filename.string());
|
||||
}
|
||||
filelength = file.tellg();
|
||||
file.seekg(0);
|
||||
@ -36,19 +37,21 @@ void files::rafile::read(char* buffer, std::streamsize size) {
|
||||
file.read(buffer, size);
|
||||
}
|
||||
|
||||
bool files::write_bytes(const fs::path& filename, const ubyte* data, size_t size) {
|
||||
bool files::write_bytes(
|
||||
const fs::path& filename, const ubyte* data, size_t size
|
||||
) {
|
||||
std::ofstream output(filename, std::ios::binary);
|
||||
if (!output.is_open())
|
||||
return false;
|
||||
if (!output.is_open()) return false;
|
||||
output.write((const char*)data, size);
|
||||
output.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
uint files::append_bytes(const fs::path& filename, const ubyte* data, size_t size) {
|
||||
uint files::append_bytes(
|
||||
const fs::path& filename, const ubyte* data, size_t size
|
||||
) {
|
||||
std::ofstream output(filename, std::ios::binary | std::ios::app);
|
||||
if (!output.is_open())
|
||||
return 0;
|
||||
if (!output.is_open()) return 0;
|
||||
uint position = output.tellp();
|
||||
output.write((const char*)data, size);
|
||||
output.close();
|
||||
@ -57,17 +60,17 @@ uint files::append_bytes(const fs::path& filename, const ubyte* data, size_t siz
|
||||
|
||||
bool files::read(const fs::path& filename, char* data, size_t size) {
|
||||
std::ifstream output(filename, std::ios::binary);
|
||||
if (!output.is_open())
|
||||
return false;
|
||||
if (!output.is_open()) return false;
|
||||
output.read(data, size);
|
||||
output.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
std::unique_ptr<ubyte[]> files::read_bytes(const 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);
|
||||
if (!input.is_open())
|
||||
return nullptr;
|
||||
if (!input.is_open()) return nullptr;
|
||||
input.seekg(0, std::ios_base::end);
|
||||
length = input.tellg();
|
||||
input.seekg(0, std::ios_base::beg);
|
||||
@ -80,8 +83,7 @@ std::unique_ptr<ubyte[]> files::read_bytes(const fs::path& filename, size_t& len
|
||||
|
||||
std::vector<ubyte> files::read_bytes(const fs::path& filename) {
|
||||
std::ifstream input(filename, std::ios::binary);
|
||||
if (!input.is_open())
|
||||
return {};
|
||||
if (!input.is_open()) return {};
|
||||
input.seekg(0, std::ios_base::end);
|
||||
size_t length = input.tellg();
|
||||
input.seekg(0, std::ios_base::beg);
|
||||
@ -95,10 +97,11 @@ std::vector<ubyte> files::read_bytes(const fs::path& filename) {
|
||||
|
||||
std::string files::read_string(const fs::path& filename) {
|
||||
size_t size;
|
||||
std::unique_ptr<ubyte[]> bytes (read_bytes(filename, size));
|
||||
std::unique_ptr<ubyte[]> bytes(read_bytes(filename, size));
|
||||
if (bytes == nullptr) {
|
||||
throw std::runtime_error("could not to load file '"+
|
||||
filename.string()+"'");
|
||||
throw std::runtime_error(
|
||||
"could not to load file '" + filename.string() + "'"
|
||||
);
|
||||
}
|
||||
return std::string((const char*)bytes.get(), size);
|
||||
}
|
||||
@ -112,11 +115,15 @@ bool files::write_string(const fs::path& filename, const std::string content) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool files::write_json(const fs::path& filename, const dynamic::Map* obj, bool nice) {
|
||||
bool files::write_json(
|
||||
const fs::path& filename, const dynamic::Map* obj, bool nice
|
||||
) {
|
||||
return files::write_string(filename, json::stringify(obj, nice, " "));
|
||||
}
|
||||
|
||||
bool files::write_binary_json(const fs::path& filename, const dynamic::Map* obj, bool compression) {
|
||||
bool files::write_binary_json(
|
||||
const fs::path& filename, const dynamic::Map* obj, bool compression
|
||||
) {
|
||||
auto bytes = json::to_binary(obj, compression);
|
||||
return files::write_bytes(filename, bytes.data(), bytes.size());
|
||||
}
|
||||
@ -128,7 +135,7 @@ std::shared_ptr<dynamic::Map> files::read_json(const fs::path& filename) {
|
||||
|
||||
std::shared_ptr<dynamic::Map> files::read_binary_json(const fs::path& file) {
|
||||
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);
|
||||
}
|
||||
|
||||
@ -139,16 +146,16 @@ std::shared_ptr<dynamic::Map> files::read_toml(const fs::path& file) {
|
||||
std::vector<std::string> files::read_list(const fs::path& filename) {
|
||||
std::ifstream file(filename);
|
||||
if (!file) {
|
||||
throw std::runtime_error("could not to open file "+filename.u8string());
|
||||
throw std::runtime_error(
|
||||
"could not to open file " + filename.u8string()
|
||||
);
|
||||
}
|
||||
std::vector<std::string> lines;
|
||||
std::string line;
|
||||
while (std::getline(file, line)) {
|
||||
util::trim(line);
|
||||
if (line.length() == 0)
|
||||
continue;
|
||||
if (line[0] == '#')
|
||||
continue;
|
||||
if (line.length() == 0) continue;
|
||||
if (line[0] == '#') continue;
|
||||
lines.push_back(line);
|
||||
}
|
||||
return lines;
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
#ifndef FILES_FILES_HPP_
|
||||
#define FILES_FILES_HPP_
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <fstream>
|
||||
#include <filesystem>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
@ -43,16 +44,19 @@ namespace files {
|
||||
bool write_string(const fs::path& filename, const std::string content);
|
||||
|
||||
/// @brief Write dynamic data to the JSON file
|
||||
/// @param nice if true, human readable format will be used, otherwise minimal
|
||||
bool write_json(const fs::path& filename, const dynamic::Map* obj, bool nice=true);
|
||||
/// @param nice if true, human readable format will be used, otherwise
|
||||
/// minimal
|
||||
bool write_json(
|
||||
const fs::path& filename, const dynamic::Map* obj, bool nice = true
|
||||
);
|
||||
|
||||
/// @brief Write dynamic data to the binary JSON file
|
||||
/// (see src/coders/binary_json_spec.md)
|
||||
/// @param compressed use gzip compression
|
||||
bool write_binary_json(
|
||||
const fs::path& filename,
|
||||
const dynamic::Map* obj,
|
||||
bool compressed=false
|
||||
const dynamic::Map* obj,
|
||||
bool compressed = false
|
||||
);
|
||||
|
||||
bool read(const fs::path&, char* data, size_t size);
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
#include "settings_io.hpp"
|
||||
|
||||
#include "../window/Events.hpp"
|
||||
#include "../window/input.hpp"
|
||||
#include "../coders/toml.hpp"
|
||||
#include "../coders/json.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
#include "../settings.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "../coders/json.hpp"
|
||||
#include "../coders/toml.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
#include "../settings.hpp"
|
||||
#include "../window/Events.hpp"
|
||||
#include "../window/input.hpp"
|
||||
|
||||
static debug::Logger logger("settings_io");
|
||||
|
||||
struct SectionsBuilder {
|
||||
@ -19,16 +19,17 @@ struct SectionsBuilder {
|
||||
SectionsBuilder(
|
||||
std::unordered_map<std::string, Setting*>& map,
|
||||
std::vector<Section>& sections
|
||||
) : map(map), sections(sections) {
|
||||
)
|
||||
: map(map), sections(sections) {
|
||||
}
|
||||
|
||||
void section(std::string name) {
|
||||
sections.push_back(Section {std::move(name), {}});
|
||||
}
|
||||
|
||||
void add(const std::string& name, Setting* setting, bool writeable=true) {
|
||||
Section& section = sections.at(sections.size()-1);
|
||||
map[section.name+"."+name] = setting;
|
||||
void add(const std::string& name, Setting* setting, bool writeable = true) {
|
||||
Section& section = sections.at(sections.size() - 1);
|
||||
map[section.name + "." + name] = setting;
|
||||
section.keys.push_back(name);
|
||||
}
|
||||
};
|
||||
@ -82,7 +83,7 @@ SettingsHandler::SettingsHandler(EngineSettings& settings) {
|
||||
dynamic::Value SettingsHandler::getValue(const std::string& name) const {
|
||||
auto found = map.find(name);
|
||||
if (found == map.end()) {
|
||||
throw std::runtime_error("setting '"+name+"' does not exist");
|
||||
throw std::runtime_error("setting '" + name + "' does not exist");
|
||||
}
|
||||
auto setting = found->second;
|
||||
if (auto number = dynamic_cast<NumberSetting*>(setting)) {
|
||||
@ -94,14 +95,14 @@ dynamic::Value SettingsHandler::getValue(const std::string& name) const {
|
||||
} else if (auto string = dynamic_cast<StringSetting*>(setting)) {
|
||||
return string->get();
|
||||
} else {
|
||||
throw std::runtime_error("type is not implemented for '"+name+"'");
|
||||
throw std::runtime_error("type is not implemented for '" + name + "'");
|
||||
}
|
||||
}
|
||||
|
||||
std::string SettingsHandler::toString(const std::string& name) const {
|
||||
auto found = map.find(name);
|
||||
if (found == map.end()) {
|
||||
throw std::runtime_error("setting '"+name+"' does not exist");
|
||||
throw std::runtime_error("setting '" + name + "' does not exist");
|
||||
}
|
||||
auto setting = found->second;
|
||||
return setting->toString();
|
||||
@ -110,7 +111,7 @@ std::string SettingsHandler::toString(const std::string& name) const {
|
||||
Setting* SettingsHandler::getSetting(const std::string& name) const {
|
||||
auto found = map.find(name);
|
||||
if (found == map.end()) {
|
||||
throw std::runtime_error("setting '"+name+"' does not exist");
|
||||
throw std::runtime_error("setting '" + name + "' does not exist");
|
||||
}
|
||||
return found->second;
|
||||
}
|
||||
@ -119,7 +120,7 @@ bool SettingsHandler::has(const std::string& name) const {
|
||||
return map.find(name) != map.end();
|
||||
}
|
||||
|
||||
template<class T>
|
||||
template <class T>
|
||||
static void set_numeric_value(T* setting, const dynamic::Value& value) {
|
||||
if (auto num = std::get_if<integer_t>(&value)) {
|
||||
setting->set(*num);
|
||||
@ -132,10 +133,12 @@ static void set_numeric_value(T* setting, const dynamic::Value& value) {
|
||||
}
|
||||
}
|
||||
|
||||
void SettingsHandler::setValue(const std::string& name, const dynamic::Value& value) {
|
||||
void SettingsHandler::setValue(
|
||||
const std::string& name, const dynamic::Value& value
|
||||
) {
|
||||
auto found = map.find(name);
|
||||
if (found == map.end()) {
|
||||
throw std::runtime_error("setting '"+name+"' does not exist");
|
||||
throw std::runtime_error("setting '" + name + "' does not exist");
|
||||
}
|
||||
auto setting = found->second;
|
||||
if (auto number = dynamic_cast<NumberSetting*>(setting)) {
|
||||
@ -157,7 +160,9 @@ void SettingsHandler::setValue(const std::string& name, const dynamic::Value& va
|
||||
throw std::runtime_error("not implemented for type");
|
||||
}
|
||||
} else {
|
||||
throw std::runtime_error("type is not implement - setting '"+name+"'");
|
||||
throw std::runtime_error(
|
||||
"type is not implement - setting '" + name + "'"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
#ifndef FILES_SETTINGS_IO_HPP_
|
||||
#define FILES_SETTINGS_IO_HPP_
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
|
||||
class Setting;
|
||||
struct EngineSettings;
|
||||
@ -31,4 +31,4 @@ public:
|
||||
std::vector<Section>& getSections();
|
||||
};
|
||||
|
||||
#endif // FILES_SETTINGS_IO_HPP_
|
||||
#endif // FILES_SETTINGS_IO_HPP_
|
||||
|
||||
@ -18,9 +18,9 @@ ContentGfxCache::ContentGfxCache(const Content* content, Assets* assets) : conte
|
||||
auto atlas = assets->get<Atlas>("blocks");
|
||||
|
||||
for (uint i = 0; i < indices->blocks.count(); i++) {
|
||||
Block* def = indices->blocks.get(i);
|
||||
Block* def = indices->blocks.get(i); //FIXME: Potential null pointer
|
||||
for (uint side = 0; side < 6; side++) {
|
||||
const std::string& tex = def->textureFaces[side];
|
||||
const std::string& tex = def->textureFaces[side]; //-V522
|
||||
if (atlas->has(tex)) {
|
||||
sideregions[i * 6 + side] = atlas->get(tex);
|
||||
} else if (atlas->has(TEXTURE_NOTFOUND)) {
|
||||
|
||||
@ -6,6 +6,8 @@
|
||||
|
||||
#include <GL/glew.h>
|
||||
|
||||
#include <cmath>
|
||||
|
||||
inline constexpr uint B2D_VERTEX_SIZE = 8;
|
||||
|
||||
Batch2D::Batch2D(size_t capacity) : capacity(capacity), color(1.0f){
|
||||
@ -163,9 +165,10 @@ void Batch2D::rect(
|
||||
|
||||
float x1,y1,x2,y2,x3,y3,x4,y4;
|
||||
|
||||
if (angle != 0) {
|
||||
float s = sin(angle);
|
||||
float c = cos(angle);
|
||||
constexpr float epsilon = 1e-6f; // 0.000001
|
||||
if (std::fabs(angle) > epsilon) {
|
||||
float s = std::sin(angle);
|
||||
float c = std::cos(angle);
|
||||
|
||||
x1 = c * _x1 - s * _y1;
|
||||
y1 = s * _x1 + c * _y1;
|
||||
|
||||
@ -95,7 +95,7 @@ glshader compile_shader(GLenum type, const GLchar* source, const std::string& fi
|
||||
"vertex shader compilation failed ("+file+"):\n"+std::string(infoLog)
|
||||
);
|
||||
}
|
||||
return glshader(new GLuint(shader), shader_deleter);
|
||||
return glshader(new GLuint(shader), shader_deleter); //-V508
|
||||
}
|
||||
|
||||
std::unique_ptr<Shader> Shader::create(
|
||||
|
||||
@ -154,9 +154,9 @@ std::unique_ptr<Atlas> BlocksPreview::build(
|
||||
|
||||
fbo.bind();
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
auto def = indices->blocks.get(i);
|
||||
auto def = indices->blocks.get(i); //FIXME: Potentional null pointer
|
||||
atlas->getTexture()->bind();
|
||||
builder.add(def->name, draw(cache, shader, &fbo, &batch, def, iconSize));
|
||||
builder.add(def->name, draw(cache, shader, &fbo, &batch, def, iconSize)); //-V522
|
||||
}
|
||||
fbo.unbind();
|
||||
|
||||
|
||||
@ -11,6 +11,7 @@
|
||||
#include "../../window/Camera.hpp"
|
||||
#include "../../maths/UVRegion.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <GL/glew.h>
|
||||
#include <glm/glm.hpp>
|
||||
@ -76,14 +77,14 @@ void Skybox::drawStars(float angle, float opacity) {
|
||||
float rx = (random.randFloat()) - 0.5f;
|
||||
float ry = (random.randFloat()) - 0.5f;
|
||||
float z = (random.randFloat()) - 0.5f;
|
||||
float x = rx * sin(angle) + ry * -cos(angle);
|
||||
float y = rx * cos(angle) + ry * sin(angle);
|
||||
float x = rx * std::sin(angle) + ry * -std::cos(angle);
|
||||
float y = rx * std::cos(angle) + ry * std::sin(angle);
|
||||
|
||||
float sopacity = random.randFloat();
|
||||
if (y < 0.0f)
|
||||
continue;
|
||||
|
||||
sopacity *= (0.2f+sqrt(cos(angle))*0.5) - 0.05;
|
||||
sopacity *= (0.2f+std::sqrt(std::cos(angle))*0.5f) - 0.05f;
|
||||
glm::vec4 tint (1,1,1, sopacity * opacity);
|
||||
batch3d->point(glm::vec3(x, y, z), tint);
|
||||
}
|
||||
@ -106,26 +107,26 @@ void Skybox::draw(
|
||||
DrawContext ctx = pctx.sub();
|
||||
ctx.setBlendMode(BlendMode::addition);
|
||||
|
||||
auto shader = assets->get<Shader>("ui3d");
|
||||
shader->use();
|
||||
shader->uniformMatrix("u_projview", camera->getProjView(false));
|
||||
shader->uniformMatrix("u_apply", glm::mat4(1.0f));
|
||||
auto p_shader = assets->get<Shader>("ui3d");
|
||||
p_shader->use();
|
||||
p_shader->uniformMatrix("u_projview", camera->getProjView(false));
|
||||
p_shader->uniformMatrix("u_apply", glm::mat4(1.0f));
|
||||
batch3d->begin();
|
||||
|
||||
float angle = daytime * M_PI * 2;
|
||||
float angle = daytime * float(M_PI) * 2.0f;
|
||||
float opacity = glm::pow(1.0f-fog, 7.0f);
|
||||
|
||||
for (auto& sprite : sprites) {
|
||||
batch3d->texture(assets->get<Texture>(sprite.texture));
|
||||
|
||||
float sangle = daytime * M_PI*2 + sprite.phase;
|
||||
float sangle = daytime * float(M_PI)*2.0 + sprite.phase;
|
||||
float distance = sprite.distance;
|
||||
|
||||
glm::vec3 pos(-cos(sangle)*distance, sin(sangle)*distance, 0);
|
||||
glm::vec3 up(-sin(-sangle), cos(-sangle), 0.0f);
|
||||
glm::vec3 pos(-std::cos(sangle)*distance, std::sin(sangle)*distance, 0);
|
||||
glm::vec3 up(-std::sin(-sangle), std::cos(-sangle), 0.0f);
|
||||
glm::vec4 tint (1,1,1, opacity);
|
||||
if (!sprite.emissive) {
|
||||
tint *= 0.6f+cos(angle)*0.4;
|
||||
tint *= 0.6f+std::cos(angle)*0.4;
|
||||
}
|
||||
batch3d->sprite(pos, glm::vec3(0, 0, 1),
|
||||
up, 1, 1, UVRegion(), tint);
|
||||
@ -141,11 +142,11 @@ void Skybox::refresh(const DrawContext& pctx, float t, float mie, uint quality)
|
||||
ctx.setFramebuffer(fbo.get());
|
||||
ctx.setViewport(Viewport(size, size));
|
||||
|
||||
auto cubemap = dynamic_cast<Cubemap*>(fbo->getTexture());
|
||||
auto cubemap = dynamic_cast<Cubemap*>(fbo->getTexture()); //FIXME: Potentional null pointer
|
||||
|
||||
ready = true;
|
||||
glActiveTexture(GL_TEXTURE1);
|
||||
cubemap->bind();
|
||||
cubemap->bind(); //-V522
|
||||
shader->use();
|
||||
|
||||
const glm::vec3 xaxs[] = {
|
||||
|
||||
@ -172,10 +172,10 @@ void WorldRenderer::setupWorldShader(
|
||||
{
|
||||
auto inventory = player->getInventory();
|
||||
ItemStack& stack = inventory->getSlot(player->getChosenSlot());
|
||||
auto item = indices->items.get(stack.getItemId());
|
||||
auto item = indices->items.get(stack.getItemId()); //FIXME: Potentional null pointer
|
||||
float multiplier = 0.5f;
|
||||
shader->uniform3f("u_torchlightColor",
|
||||
item->emission[0] / 15.0f * multiplier,
|
||||
item->emission[0] / 15.0f * multiplier, //-V522
|
||||
item->emission[1] / 15.0f * multiplier,
|
||||
item->emission[2] / 15.0f * multiplier
|
||||
);
|
||||
@ -222,12 +222,12 @@ void WorldRenderer::renderBlockSelection() {
|
||||
const auto& selection = player->selection;
|
||||
auto indices = level->content->getIndices();
|
||||
blockid_t id = selection.vox.id;
|
||||
auto block = indices->blocks.get(id);
|
||||
auto block = indices->blocks.get(id); //FIXME: Potentional null pointer
|
||||
const glm::ivec3 pos = player->selection.position;
|
||||
const glm::vec3 point = selection.hitPosition;
|
||||
const glm::vec3 norm = selection.normal;
|
||||
|
||||
const std::vector<AABB>& hitboxes = block->rotatable
|
||||
const std::vector<AABB>& hitboxes = block->rotatable //-V522
|
||||
? block->rt.hitboxes[selection.vox.state.rotation]
|
||||
: block->hitboxes;
|
||||
|
||||
|
||||
@ -121,9 +121,9 @@ void SlotView::draw(const DrawContext* pctx, Assets* assets) {
|
||||
itemid_t itemid = bound->getItemId();
|
||||
if (itemid != prevItem) {
|
||||
if (itemid) {
|
||||
auto def = content->getIndices()->items.get(itemid);
|
||||
auto def = content->getIndices()->items.get(itemid); //FIXME: Potentional null pointer
|
||||
tooltip = util::pascal_case(
|
||||
langs::get(util::str2wstr_utf8(def->caption))
|
||||
langs::get(util::str2wstr_utf8(def->caption)) //-V522
|
||||
);
|
||||
} else {
|
||||
tooltip.clear();
|
||||
@ -159,8 +159,8 @@ void SlotView::draw(const DrawContext* pctx, Assets* assets) {
|
||||
auto previews = assets->get<Atlas>("block-previews");
|
||||
auto indices = content->getIndices();
|
||||
|
||||
ItemDef* item = indices->items.get(stack.getItemId());
|
||||
switch (item->iconType) {
|
||||
ItemDef* item = indices->items.get(stack.getItemId()); //FIXME: Potentional null pointer
|
||||
switch (item->iconType) { //-V522
|
||||
case item_icon_type::none:
|
||||
break;
|
||||
case item_icon_type::block: {
|
||||
@ -268,12 +268,12 @@ void SlotView::clicked(gui::GUI* gui, mousecode button) {
|
||||
stack.setCount(halfremain);
|
||||
}
|
||||
} else {
|
||||
auto stackDef = content->getIndices()->items.get(stack.getItemId());
|
||||
auto stackDef = content->getIndices()->items.get(stack.getItemId()); //FIXME: Potentional null pointer
|
||||
if (stack.isEmpty()) {
|
||||
stack.set(grabbed);
|
||||
stack.setCount(1);
|
||||
grabbed.setCount(grabbed.getCount()-1);
|
||||
} else if (stack.accepts(grabbed) && stack.getCount() < stackDef->stackSize){
|
||||
} else if (stack.accepts(grabbed) && stack.getCount() < stackDef->stackSize){ //-V522
|
||||
stack.setCount(stack.getCount()+1);
|
||||
grabbed.setCount(grabbed.getCount()-1);
|
||||
}
|
||||
|
||||
@ -203,7 +203,7 @@ static void _readPanel(UiXmlReader& reader, const xml::xmlelement& element, Pane
|
||||
panel.setMaxLength(element->attr("max-length").asInt());
|
||||
}
|
||||
if (element->has("orientation")) {
|
||||
auto oname = element->attr("orientation").getText();
|
||||
auto &oname = element->attr("orientation").getText();
|
||||
if (oname == "horizontal") {
|
||||
panel.setOrientation(Orientation::horizontal);
|
||||
}
|
||||
|
||||
@ -40,15 +40,13 @@ void Inventories::remove(int64_t id) {
|
||||
|
||||
std::shared_ptr<Inventory> Inventories::get(int64_t id) {
|
||||
auto found = map.find(id);
|
||||
if (found == map.end())
|
||||
return nullptr;
|
||||
if (found == map.end()) return nullptr;
|
||||
return found->second;
|
||||
}
|
||||
|
||||
std::shared_ptr<Inventory> Inventories::clone(int64_t id) {
|
||||
auto original = get(id);
|
||||
if (original == nullptr)
|
||||
return nullptr;
|
||||
if (original == nullptr) return nullptr;
|
||||
auto clone = std::make_shared<Inventory>(*original);
|
||||
clone->setId(level.getWorld()->getNextInventoryId());
|
||||
store(clone);
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
#ifndef ITEMS_INVENTORIES_HPP_
|
||||
#define ITEMS_INVENTORIES_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "Inventory.hpp"
|
||||
#include "../maths/util.hpp"
|
||||
#include "Inventory.hpp"
|
||||
|
||||
class Level;
|
||||
|
||||
@ -41,4 +41,4 @@ public:
|
||||
const inventories_map& getMap() const;
|
||||
};
|
||||
|
||||
#endif // ITEMS_INVENTORIES_HPP_
|
||||
#endif // ITEMS_INVENTORIES_HPP_
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
#include "Inventory.hpp"
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
#include "../content/ContentLUT.hpp"
|
||||
#include "../data/dynamic.hpp"
|
||||
|
||||
Inventory::Inventory(int64_t id, size_t size) : id(id), slots(size) {
|
||||
}
|
||||
@ -35,11 +35,8 @@ size_t Inventory::findSlotByItem(itemid_t id, size_t begin, size_t end) {
|
||||
}
|
||||
|
||||
void Inventory::move(
|
||||
ItemStack& item,
|
||||
const ContentIndices* indices,
|
||||
size_t begin,
|
||||
size_t end)
|
||||
{
|
||||
ItemStack& item, const ContentIndices* indices, size_t begin, size_t end
|
||||
) {
|
||||
end = std::min(slots.size(), end);
|
||||
for (size_t i = begin; i < end && !item.isEmpty(); i++) {
|
||||
ItemStack& slot = slots[i];
|
||||
@ -61,7 +58,7 @@ void Inventory::deserialize(dynamic::Map* src) {
|
||||
itemid_t id = item->get("id", ITEM_EMPTY);
|
||||
itemcount_t count = item->get("count", 0);
|
||||
auto& slot = slots[i];
|
||||
slot.set(ItemStack(id, count));
|
||||
slot.set(ItemStack(id, count));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,13 +1,12 @@
|
||||
#ifndef ITEMS_INVENTORY_HPP_
|
||||
#define ITEMS_INVENTORY_HPP_
|
||||
|
||||
#include "ItemStack.hpp"
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
#include "../interfaces/Serializable.hpp"
|
||||
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "../interfaces/Serializable.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "ItemStack.hpp"
|
||||
|
||||
namespace dynamic {
|
||||
class Map;
|
||||
@ -25,18 +24,19 @@ public:
|
||||
Inventory(const Inventory& orig);
|
||||
|
||||
ItemStack& getSlot(size_t index);
|
||||
size_t findEmptySlot(size_t begin=0, size_t end=-1) const;
|
||||
size_t findSlotByItem(itemid_t id, size_t begin=0, size_t end=-1);
|
||||
|
||||
size_t findEmptySlot(size_t begin = 0, size_t end = -1) const;
|
||||
size_t findSlotByItem(itemid_t id, size_t begin = 0, size_t end = -1);
|
||||
|
||||
inline size_t size() const {
|
||||
return slots.size();
|
||||
}
|
||||
|
||||
void move(
|
||||
ItemStack& item,
|
||||
const ContentIndices* indices,
|
||||
size_t begin=0,
|
||||
size_t end=-1);
|
||||
ItemStack& item,
|
||||
const ContentIndices* indices,
|
||||
size_t begin = 0,
|
||||
size_t end = -1
|
||||
);
|
||||
|
||||
/* deserializing inventory */
|
||||
void deserialize(dynamic::Map* src) override;
|
||||
@ -60,4 +60,4 @@ public:
|
||||
static const size_t npos;
|
||||
};
|
||||
|
||||
#endif // ITEMS_INVENTORY_HPP_
|
||||
#endif // ITEMS_INVENTORY_HPP_
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
#include "ItemDef.hpp"
|
||||
|
||||
#include "../util/stringutil.hpp"
|
||||
|
||||
ItemDef::ItemDef(const std::string& name) : name(name) {
|
||||
|
||||
@ -1,22 +1,22 @@
|
||||
#ifndef CONTENT_ITEMS_ITEM_DEF_HPP_
|
||||
#define CONTENT_ITEMS_ITEM_DEF_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <glm/glm.hpp>
|
||||
#include <string>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
struct item_funcs_set {
|
||||
bool init: 1;
|
||||
bool on_use: 1;
|
||||
bool on_use_on_block: 1;
|
||||
bool on_block_break_by: 1;
|
||||
bool init : 1;
|
||||
bool on_use : 1;
|
||||
bool on_use_on_block : 1;
|
||||
bool on_block_break_by : 1;
|
||||
};
|
||||
|
||||
enum class item_icon_type {
|
||||
none, // invisible (core:empty) must not be rendered
|
||||
sprite, // textured quad: icon is `atlas_name:texture_name`
|
||||
block, // block preview: icon is string block id
|
||||
none, // invisible (core:empty) must not be rendered
|
||||
sprite, // textured quad: icon is `atlas_name:texture_name`
|
||||
block, // block preview: icon is string block id
|
||||
};
|
||||
|
||||
struct ItemDef {
|
||||
@ -34,7 +34,7 @@ struct ItemDef {
|
||||
std::string icon = "blocks:notfound";
|
||||
|
||||
std::string placingBlock = "core:air";
|
||||
std::string scriptName = name.substr(name.find(':')+1);
|
||||
std::string scriptName = name.substr(name.find(':') + 1);
|
||||
|
||||
struct {
|
||||
itemid_t id;
|
||||
@ -47,4 +47,4 @@ struct ItemDef {
|
||||
ItemDef(const ItemDef&) = delete;
|
||||
};
|
||||
|
||||
#endif //CONTENT_ITEMS_ITEM_DEF_HPP_
|
||||
#endif // CONTENT_ITEMS_ITEM_DEF_HPP_
|
||||
|
||||
@ -1,12 +1,13 @@
|
||||
#include "ItemStack.hpp"
|
||||
|
||||
#include "ItemDef.hpp"
|
||||
#include "../content/Content.hpp"
|
||||
#include "ItemDef.hpp"
|
||||
|
||||
ItemStack::ItemStack() : item(ITEM_EMPTY), count(0) {
|
||||
}
|
||||
|
||||
ItemStack::ItemStack(itemid_t item, itemcount_t count) : item(item), count(count) {
|
||||
ItemStack::ItemStack(itemid_t item, itemcount_t count)
|
||||
: item(item), count(count) {
|
||||
}
|
||||
|
||||
void ItemStack::set(const ItemStack& item) {
|
||||
@ -25,14 +26,14 @@ bool ItemStack::accepts(const ItemStack& other) const {
|
||||
}
|
||||
|
||||
void ItemStack::move(ItemStack& item, const ContentIndices* indices) {
|
||||
auto def = indices->items.get(item.getItemId());
|
||||
int count = std::min(item.count, def->stackSize-this->count);
|
||||
auto def = indices->items.get(item.getItemId()); //FIXME: Potentional null pointer
|
||||
int count = std::min(item.count, def->stackSize - this->count); //-V522
|
||||
if (isEmpty()) {
|
||||
set(ItemStack(item.getItemId(), count));
|
||||
} else {
|
||||
setCount(this->count + count);
|
||||
}
|
||||
item.setCount(item.count-count);
|
||||
item.setCount(item.count - count);
|
||||
}
|
||||
|
||||
void ItemStack::setCount(itemcount_t count) {
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
#ifndef ITEMS_ITEM_STACK_HPP_
|
||||
#define ITEMS_ITEM_STACK_HPP_
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
#include "../constants.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
class ContentIndices;
|
||||
|
||||
@ -37,4 +37,4 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
#endif // ITEMS_ITEM_STACK_HPP_
|
||||
#endif // ITEMS_ITEM_STACK_HPP_
|
||||
|
||||
@ -149,7 +149,7 @@ void Lighting::onChunkLoaded(int cx, int cz, bool expand){
|
||||
}
|
||||
|
||||
void Lighting::onBlockSet(int x, int y, int z, blockid_t id){
|
||||
Block* block = content->getIndices()->blocks.get(id);
|
||||
Block* block = content->getIndices()->blocks.get(id); //FIXME: Potentional null pointer
|
||||
solverR->remove(x,y,z);
|
||||
solverG->remove(x,y,z);
|
||||
solverB->remove(x,y,z);
|
||||
@ -161,7 +161,7 @@ void Lighting::onBlockSet(int x, int y, int z, blockid_t id){
|
||||
if (chunks->getLight(x,y+1,z, 3) == 0xF){
|
||||
for (int i = y; i >= 0; i--){
|
||||
voxel* vox = chunks->get(x,i,z);
|
||||
if ((vox == nullptr || vox->id != 0) && block->skyLightPassing)
|
||||
if ((vox == nullptr || vox->id != 0) && block->skyLightPassing) //-V522
|
||||
break;
|
||||
solverS->add(x,i,z, 0xF);
|
||||
}
|
||||
|
||||
@ -1,23 +1,22 @@
|
||||
#include "BlocksController.hpp"
|
||||
|
||||
#include "../voxels/voxel.hpp"
|
||||
#include "../content/Content.hpp"
|
||||
#include "../items/Inventories.hpp"
|
||||
#include "../items/Inventory.hpp"
|
||||
#include "../lighting/Lighting.hpp"
|
||||
#include "../maths/fastmaths.hpp"
|
||||
#include "../util/timeutil.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "../voxels/Chunk.hpp"
|
||||
#include "../voxels/Chunks.hpp"
|
||||
#include "../voxels/voxel.hpp"
|
||||
#include "../world/Level.hpp"
|
||||
#include "../world/World.hpp"
|
||||
#include "../content/Content.hpp"
|
||||
#include "../lighting/Lighting.hpp"
|
||||
#include "../util/timeutil.hpp"
|
||||
#include "../maths/fastmaths.hpp"
|
||||
#include "../items/Inventory.hpp"
|
||||
#include "../items/Inventories.hpp"
|
||||
|
||||
#include "scripting/scripting.hpp"
|
||||
|
||||
BlocksController::BlocksController(Level* level, uint padding)
|
||||
: level(level),
|
||||
chunks(level->chunks.get()),
|
||||
BlocksController::BlocksController(Level* level, uint padding)
|
||||
: level(level),
|
||||
chunks(level->chunks.get()),
|
||||
lighting(level->lighting.get()),
|
||||
randTickClock(20, 3),
|
||||
blocksTickClock(20, 1),
|
||||
@ -26,26 +25,32 @@ BlocksController::BlocksController(Level* level, uint padding)
|
||||
}
|
||||
|
||||
void BlocksController::updateSides(int x, int y, int z) {
|
||||
updateBlock(x-1, y, z);
|
||||
updateBlock(x+1, y, z);
|
||||
updateBlock(x, y-1, z);
|
||||
updateBlock(x, y+1, z);
|
||||
updateBlock(x, y, z-1);
|
||||
updateBlock(x, y, z+1);
|
||||
updateBlock(x - 1, y, z);
|
||||
updateBlock(x + 1, y, z);
|
||||
updateBlock(x, y - 1, z);
|
||||
updateBlock(x, y + 1, z);
|
||||
updateBlock(x, y, z - 1);
|
||||
updateBlock(x, y, z + 1);
|
||||
}
|
||||
|
||||
void BlocksController::breakBlock(Player* player, const Block* def, int x, int y, int z) {
|
||||
void BlocksController::breakBlock(
|
||||
Player* player, const Block* def, int x, int y, int z
|
||||
) {
|
||||
onBlockInteraction(
|
||||
player, glm::ivec3(x, y, z), def, BlockInteraction::destruction);
|
||||
player, glm::ivec3(x, y, z), def, BlockInteraction::destruction
|
||||
);
|
||||
chunks->set(x, y, z, 0, {});
|
||||
lighting->onBlockSet(x, y, z, 0);
|
||||
scripting::on_block_broken(player, def, x, y, z);
|
||||
updateSides(x, y, z);
|
||||
}
|
||||
|
||||
void BlocksController::placeBlock(Player* player, const Block* def, blockstate state, int x, int y, int z) {
|
||||
void BlocksController::placeBlock(
|
||||
Player* player, const Block* def, blockstate state, int x, int y, int z
|
||||
) {
|
||||
onBlockInteraction(
|
||||
player, glm::ivec3(x, y, z), def, BlockInteraction::placing);
|
||||
player, glm::ivec3(x, y, z), def, BlockInteraction::placing
|
||||
);
|
||||
chunks->set(x, y, z, def->rt.id, state);
|
||||
lighting->onBlockSet(x, y, z, def->rt.id);
|
||||
if (def->rt.funcsset.onplaced) {
|
||||
@ -56,12 +61,11 @@ void BlocksController::placeBlock(Player* player, const Block* def, blockstate s
|
||||
|
||||
void BlocksController::updateBlock(int x, int y, int z) {
|
||||
voxel* vox = chunks->get(x, y, z);
|
||||
if (vox == nullptr)
|
||||
return;
|
||||
auto def = level->content->getIndices()->blocks.get(vox->id);
|
||||
if (def->grounded) {
|
||||
if (vox == nullptr) return;
|
||||
auto def = level->content->getIndices()->blocks.get(vox->id); //FIXME: Potentional null pointer
|
||||
if (def->grounded) { //-V522
|
||||
const auto& vec = get_ground_direction(def, vox->state.rotation);
|
||||
if (!chunks->isSolidBlock(x+vec.x, y+vec.y, z+vec.z)) {
|
||||
if (!chunks->isSolidBlock(x + vec.x, y + vec.y, z + vec.z)) {
|
||||
breakBlock(nullptr, def, x, y, z);
|
||||
return;
|
||||
}
|
||||
@ -88,10 +92,9 @@ void BlocksController::onBlocksTick(int tickid, int parts) {
|
||||
auto indices = content->getIndices();
|
||||
int tickRate = blocksTickClock.getTickRate();
|
||||
for (size_t id = 0; id < indices->blocks.count(); id++) {
|
||||
if ((id + tickid) % parts != 0)
|
||||
continue;
|
||||
auto def = indices->blocks.get(id);
|
||||
auto interval = def->tickInterval;
|
||||
if ((id + tickid) % parts != 0) continue;
|
||||
auto def = indices->blocks.get(id); //FIXME: Potentional null pointer
|
||||
auto interval = def->tickInterval; //-V522
|
||||
if (def->rt.funcsset.onblockstick && tickid / parts % interval == 0) {
|
||||
scripting::on_blocks_tick(def, tickRate / interval);
|
||||
}
|
||||
@ -109,12 +112,10 @@ void BlocksController::randomTick(
|
||||
int by = random.rand() % segheight + s * segheight;
|
||||
int bz = random.rand() % CHUNK_D;
|
||||
const voxel& vox = chunk.voxels[(by * CHUNK_D + bz) * CHUNK_W + bx];
|
||||
Block* block = indices->blocks.get(vox.id);
|
||||
if (block->rt.funcsset.randupdate) {
|
||||
Block* block = indices->blocks.get(vox.id); //FIXME: Potentional null pointer
|
||||
if (block->rt.funcsset.randupdate) { //-V522
|
||||
scripting::random_update_block(
|
||||
block,
|
||||
chunk.x * CHUNK_W + bx, by,
|
||||
chunk.z * CHUNK_D + bz
|
||||
block, chunk.x * CHUNK_W + bx, by, chunk.z * CHUNK_D + bz
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -126,9 +127,9 @@ void BlocksController::randomTick(int tickid, int parts) {
|
||||
const int w = chunks->w;
|
||||
const int d = chunks->d;
|
||||
int segments = 4;
|
||||
|
||||
for (uint z = padding; z < d-padding; z++){
|
||||
for (uint x = padding; x < w-padding; x++){
|
||||
|
||||
for (uint z = padding; z < d - padding; z++) {
|
||||
for (uint x = padding; x < w - padding; x++) {
|
||||
int index = z * w + x;
|
||||
if ((index + tickid) % parts != 0) {
|
||||
continue;
|
||||
@ -152,8 +153,8 @@ int64_t BlocksController::createBlockInventory(int x, int y, int z) {
|
||||
auto inv = chunk->getBlockInventory(lx, y, lz);
|
||||
if (inv == nullptr) {
|
||||
auto indices = level->content->getIndices();
|
||||
auto def = indices->blocks.get(chunk->voxels[vox_index(lx, y, lz)].id);
|
||||
int invsize = def->inventorySize;
|
||||
auto def = indices->blocks.get(chunk->voxels[vox_index(lx, y, lz)].id); //FIXME: Potentional null pointer
|
||||
int invsize = def->inventorySize; //-V522
|
||||
if (invsize == 0) {
|
||||
return 0;
|
||||
}
|
||||
@ -187,16 +188,15 @@ void BlocksController::unbindInventory(int x, int y, int z) {
|
||||
}
|
||||
|
||||
void BlocksController::onBlockInteraction(
|
||||
Player* player,
|
||||
glm::ivec3 pos,
|
||||
const Block* def,
|
||||
BlockInteraction type
|
||||
Player* player, glm::ivec3 pos, const Block* def, BlockInteraction type
|
||||
) {
|
||||
for (const auto& callback : blockInteractionCallbacks) {
|
||||
callback(player, pos, def, type);
|
||||
}
|
||||
}
|
||||
|
||||
void BlocksController::listenBlockInteraction(const on_block_interaction& callback) {
|
||||
void BlocksController::listenBlockInteraction(
|
||||
const on_block_interaction& callback
|
||||
) {
|
||||
blockInteractionCallbacks.push_back(callback);
|
||||
}
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
#ifndef LOGIC_BLOCKS_CONTROLLER_HPP_
|
||||
#define LOGIC_BLOCKS_CONTROLLER_HPP_
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
#include "../maths/fastmaths.hpp"
|
||||
#include "../voxels/voxel.hpp"
|
||||
#include "../util/Clock.hpp"
|
||||
|
||||
#include <functional>
|
||||
#include <glm/glm.hpp>
|
||||
|
||||
#include "../maths/fastmaths.hpp"
|
||||
#include "../typedefs.hpp"
|
||||
#include "../util/Clock.hpp"
|
||||
#include "../voxels/voxel.hpp"
|
||||
|
||||
class Player;
|
||||
class Block;
|
||||
class Level;
|
||||
@ -17,22 +17,17 @@ class Chunks;
|
||||
class Lighting;
|
||||
class ContentIndices;
|
||||
|
||||
enum class BlockInteraction {
|
||||
step,
|
||||
destruction,
|
||||
placing
|
||||
};
|
||||
enum class BlockInteraction { step, destruction, placing };
|
||||
|
||||
/// @brief Player argument is nullable
|
||||
using on_block_interaction = std::function<void(
|
||||
Player*, glm::ivec3, const Block*, BlockInteraction type
|
||||
)>;
|
||||
using on_block_interaction = std::function<
|
||||
void(Player*, glm::ivec3, const Block*, BlockInteraction type)>;
|
||||
|
||||
/// BlocksController manages block updates and data (inventories, metadata)
|
||||
class BlocksController {
|
||||
Level* level;
|
||||
Chunks* chunks;
|
||||
Lighting* lighting;
|
||||
Chunks* chunks;
|
||||
Lighting* lighting;
|
||||
util::Clock randTickClock;
|
||||
util::Clock blocksTickClock;
|
||||
util::Clock worldTickClock;
|
||||
@ -46,10 +41,14 @@ public:
|
||||
void updateBlock(int x, int y, int z);
|
||||
|
||||
void breakBlock(Player* player, const Block* def, int x, int y, int z);
|
||||
void placeBlock(Player* player, const Block* def, blockstate state, int x, int y, int z);
|
||||
void placeBlock(
|
||||
Player* player, const Block* def, blockstate state, int x, int y, int z
|
||||
);
|
||||
|
||||
void update(float delta);
|
||||
void randomTick(const Chunk& chunk, int segments, const ContentIndices* indices);
|
||||
void randomTick(
|
||||
const Chunk& chunk, int segments, const ContentIndices* indices
|
||||
);
|
||||
void randomTick(int tickid, int parts);
|
||||
void onBlocksTick(int tickid, int parts);
|
||||
int64_t createBlockInventory(int x, int y, int z);
|
||||
@ -57,14 +56,11 @@ public:
|
||||
void unbindInventory(int x, int y, int z);
|
||||
|
||||
void onBlockInteraction(
|
||||
Player* player,
|
||||
glm::ivec3 pos,
|
||||
const Block* def,
|
||||
BlockInteraction type
|
||||
Player* player, glm::ivec3 pos, const Block* def, BlockInteraction type
|
||||
);
|
||||
|
||||
/// @brief Add block interaction callback
|
||||
void listenBlockInteraction(const on_block_interaction& callback);
|
||||
};
|
||||
|
||||
#endif // LOGIC_BLOCKS_CONTROLLER_HPP_
|
||||
#endif // LOGIC_BLOCKS_CONTROLLER_HPP_
|
||||
|
||||
@ -1,33 +1,36 @@
|
||||
#include "ChunksController.hpp"
|
||||
|
||||
#include <limits.h>
|
||||
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
#include "../content/Content.hpp"
|
||||
#include "../files/WorldFiles.hpp"
|
||||
#include "../graphics/core/Mesh.hpp"
|
||||
#include "../lighting/Lighting.hpp"
|
||||
#include "../maths/voxmaths.hpp"
|
||||
#include "../util/timeutil.hpp"
|
||||
#include "../voxels/Block.hpp"
|
||||
#include "../voxels/Chunk.hpp"
|
||||
#include "../voxels/Chunks.hpp"
|
||||
#include "../voxels/ChunksStorage.hpp"
|
||||
#include "../voxels/WorldGenerator.hpp"
|
||||
#include "../world/WorldGenerators.hpp"
|
||||
#include "../graphics/core/Mesh.hpp"
|
||||
#include "../lighting/Lighting.hpp"
|
||||
#include "../files/WorldFiles.hpp"
|
||||
#include "../world/Level.hpp"
|
||||
#include "../world/World.hpp"
|
||||
#include "../maths/voxmaths.hpp"
|
||||
#include "../util/timeutil.hpp"
|
||||
|
||||
#include <limits.h>
|
||||
#include <memory>
|
||||
#include <iostream>
|
||||
#include "../world/WorldGenerators.hpp"
|
||||
|
||||
const uint MAX_WORK_PER_FRAME = 128;
|
||||
const uint MIN_SURROUNDING = 9;
|
||||
|
||||
ChunksController::ChunksController(Level* level, uint padding)
|
||||
: level(level),
|
||||
chunks(level->chunks.get()),
|
||||
lighting(level->lighting.get()),
|
||||
padding(padding),
|
||||
generator(WorldGenerators::createGenerator(level->getWorld()->getGenerator(), level->content)) {
|
||||
ChunksController::ChunksController(Level* level, uint padding)
|
||||
: level(level),
|
||||
chunks(level->chunks.get()),
|
||||
lighting(level->lighting.get()),
|
||||
padding(padding),
|
||||
generator(WorldGenerators::createGenerator(
|
||||
level->getWorld()->getGenerator(), level->content
|
||||
)) {
|
||||
}
|
||||
|
||||
ChunksController::~ChunksController() = default;
|
||||
@ -48,18 +51,18 @@ void ChunksController::update(int64_t maxDuration) {
|
||||
}
|
||||
}
|
||||
|
||||
bool ChunksController::loadVisible(){
|
||||
bool ChunksController::loadVisible() {
|
||||
const int w = chunks->w;
|
||||
const int d = chunks->d;
|
||||
|
||||
int nearX = 0;
|
||||
int nearZ = 0;
|
||||
int minDistance = ((w-padding*2)/2)*((w-padding*2)/2);
|
||||
for (uint z = padding; z < d-padding; z++){
|
||||
for (uint x = padding; x < w-padding; x++){
|
||||
int minDistance = ((w - padding * 2) / 2) * ((w - padding * 2) / 2);
|
||||
for (uint z = padding; z < d - padding; z++) {
|
||||
for (uint x = padding; x < w - padding; x++) {
|
||||
int index = z * w + x;
|
||||
auto& chunk = chunks->chunks[index];
|
||||
if (chunk != nullptr){
|
||||
if (chunk != nullptr) {
|
||||
if (chunk->flags.loaded && !chunk->flags.lighted) {
|
||||
if (buildLights(chunk)) {
|
||||
return true;
|
||||
@ -70,7 +73,7 @@ bool ChunksController::loadVisible(){
|
||||
int lx = x - w / 2;
|
||||
int lz = z - d / 2;
|
||||
int distance = (lx * lx + lz * lz);
|
||||
if (distance < minDistance){
|
||||
if (distance < minDistance) {
|
||||
minDistance = distance;
|
||||
nearX = x;
|
||||
nearZ = z;
|
||||
@ -85,16 +88,15 @@ bool ChunksController::loadVisible(){
|
||||
|
||||
const int ox = chunks->ox;
|
||||
const int oz = chunks->oz;
|
||||
createChunk(nearX+ox, nearZ+oz);
|
||||
createChunk(nearX + ox, nearZ + oz);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ChunksController::buildLights(const std::shared_ptr<Chunk>& chunk) {
|
||||
int surrounding = 0;
|
||||
for (int oz = -1; oz <= 1; oz++){
|
||||
for (int ox = -1; ox <= 1; ox++){
|
||||
if (chunks->getChunk(chunk->x+ox, chunk->z+oz))
|
||||
surrounding++;
|
||||
for (int oz = -1; oz <= 1; oz++) {
|
||||
for (int ox = -1; ox <= 1; ox++) {
|
||||
if (chunks->getChunk(chunk->x + ox, chunk->z + oz)) surrounding++;
|
||||
}
|
||||
}
|
||||
if (surrounding == MIN_SURROUNDING) {
|
||||
@ -115,18 +117,13 @@ void ChunksController::createChunk(int x, int z) {
|
||||
auto& chunkFlags = chunk->flags;
|
||||
|
||||
if (!chunkFlags.loaded) {
|
||||
generator->generate(
|
||||
chunk->voxels, x, z,
|
||||
level->getWorld()->getSeed()
|
||||
);
|
||||
generator->generate(chunk->voxels, x, z, level->getWorld()->getSeed());
|
||||
chunkFlags.unsaved = true;
|
||||
}
|
||||
chunk->updateHeights();
|
||||
|
||||
if (!chunkFlags.loadedLights) {
|
||||
Lighting::prebuildSkyLight(
|
||||
chunk.get(), level->content->getIndices()
|
||||
);
|
||||
Lighting::prebuildSkyLight(chunk.get(), level->content->getIndices());
|
||||
}
|
||||
chunkFlags.loaded = true;
|
||||
chunkFlags.ready = true;
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
#ifndef VOXELS_CHUNKSCONTROLLER_HPP_
|
||||
#define VOXELS_CHUNKSCONTROLLER_HPP_
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
#include <memory>
|
||||
|
||||
#include "../typedefs.hpp"
|
||||
|
||||
class Level;
|
||||
class Chunk;
|
||||
class Chunks;
|
||||
@ -31,4 +32,4 @@ public:
|
||||
void update(int64_t maxDuration);
|
||||
};
|
||||
|
||||
#endif // VOXELS_CHUNKSCONTROLLER_HPP_
|
||||
#endif // VOXELS_CHUNKSCONTROLLER_HPP_
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
#include "CommandsInterpreter.hpp"
|
||||
|
||||
#include "../coders/commons.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
#include "../coders/commons.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
|
||||
using namespace cmd;
|
||||
|
||||
inline bool is_cmd_identifier_part(char c, bool allowColon) {
|
||||
return is_identifier_part(c) || c == '.' || c == '$' ||
|
||||
return is_identifier_part(c) || c == '.' || c == '$' ||
|
||||
(allowColon && c == ':');
|
||||
}
|
||||
|
||||
@ -31,7 +31,7 @@ class CommandParser : BasicParser {
|
||||
while (hasNext() && is_cmd_identifier_part(source[pos], allowColon)) {
|
||||
pos++;
|
||||
}
|
||||
return std::string(source.substr(start, pos-start));
|
||||
return std::string(source.substr(start, pos - start));
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, ArgType> types {
|
||||
@ -42,8 +42,8 @@ class CommandParser : BasicParser {
|
||||
{"enum", ArgType::enumvalue},
|
||||
};
|
||||
public:
|
||||
CommandParser(std::string_view filename, std::string_view source)
|
||||
: BasicParser(filename, source) {
|
||||
CommandParser(std::string_view filename, std::string_view source)
|
||||
: BasicParser(filename, source) {
|
||||
}
|
||||
|
||||
ArgType parseType() {
|
||||
@ -55,7 +55,7 @@ public:
|
||||
if (found != types.end()) {
|
||||
return found->second;
|
||||
} else {
|
||||
throw error("unknown type "+util::quote(name));
|
||||
throw error("unknown type " + util::quote(name));
|
||||
}
|
||||
}
|
||||
|
||||
@ -83,7 +83,7 @@ public:
|
||||
if (is_digit(c)) {
|
||||
return parseNumber(1);
|
||||
}
|
||||
throw error("invalid character '"+std::string({c})+"'");
|
||||
throw error("invalid character '" + std::string({c}) + "'");
|
||||
}
|
||||
|
||||
std::string parseEnum() {
|
||||
@ -92,10 +92,10 @@ public:
|
||||
if (peek() == ']') {
|
||||
throw error("empty enumeration is not allowed");
|
||||
}
|
||||
auto enumvalue = "|"+std::string(readUntil(']'))+"|";
|
||||
auto enumvalue = "|" + std::string(readUntil(']')) + "|";
|
||||
size_t offset = enumvalue.find(' ');
|
||||
if (offset != std::string::npos) {
|
||||
goBack(enumvalue.length()-offset);
|
||||
goBack(enumvalue.length() - offset);
|
||||
throw error("use '|' as separator, not a space");
|
||||
}
|
||||
nextChar();
|
||||
@ -156,30 +156,34 @@ public:
|
||||
}
|
||||
}
|
||||
return Command(
|
||||
name, std::move(args), std::move(kwargs),
|
||||
std::string(description), std::move(executor)
|
||||
name,
|
||||
std::move(args),
|
||||
std::move(kwargs),
|
||||
std::string(description),
|
||||
std::move(executor)
|
||||
);
|
||||
}
|
||||
|
||||
inline parsing_error argumentError(
|
||||
const std::string& argname,
|
||||
const std::string& message
|
||||
const std::string& argname, const std::string& message
|
||||
) {
|
||||
return error("argument "+util::quote(argname)+": "+message);
|
||||
return error("argument " + util::quote(argname) + ": " + message);
|
||||
}
|
||||
|
||||
inline parsing_error typeError(
|
||||
const std::string& argname,
|
||||
const std::string& expected,
|
||||
const std::string& argname,
|
||||
const std::string& expected,
|
||||
const dynamic::Value& value
|
||||
) {
|
||||
return argumentError(
|
||||
argname, expected+" expected, got "+dynamic::type_name(value)
|
||||
argname, expected + " expected, got " + dynamic::type_name(value)
|
||||
);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline bool typeCheck(Argument* arg, const dynamic::Value& value, const std::string& tname) {
|
||||
template <typename T>
|
||||
inline bool typeCheck(
|
||||
Argument* arg, const dynamic::Value& value, const std::string& tname
|
||||
) {
|
||||
if (!std::holds_alternative<T>(value)) {
|
||||
if (arg->optional) {
|
||||
return false;
|
||||
@ -198,7 +202,7 @@ public:
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (arg->optional) {
|
||||
return false;
|
||||
} else {
|
||||
@ -211,9 +215,12 @@ public:
|
||||
case ArgType::enumvalue: {
|
||||
if (auto* string = std::get_if<std::string>(&value)) {
|
||||
auto& enumname = arg->enumname;
|
||||
if (enumname.find("|"+*string+"|") == std::string::npos) {
|
||||
throw error("argument "+util::quote(arg->name)+
|
||||
": invalid enumeration value");
|
||||
if (enumname.find("|" + *string + "|") ==
|
||||
std::string::npos) {
|
||||
throw error(
|
||||
"argument " + util::quote(arg->name) +
|
||||
": invalid enumeration value"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (arg->optional) {
|
||||
@ -245,7 +252,9 @@ public:
|
||||
return true;
|
||||
}
|
||||
|
||||
dynamic::Value fetchOrigin(CommandsInterpreter* interpreter, Argument* arg) {
|
||||
dynamic::Value fetchOrigin(
|
||||
CommandsInterpreter* interpreter, Argument* arg
|
||||
) {
|
||||
if (dynamic::is_numeric(arg->origin)) {
|
||||
return arg->origin;
|
||||
} else if (auto string = std::get_if<std::string>(&arg->origin)) {
|
||||
@ -255,9 +264,7 @@ public:
|
||||
}
|
||||
|
||||
dynamic::Value applyRelative(
|
||||
Argument* arg,
|
||||
dynamic::Value value,
|
||||
const dynamic::Value& origin
|
||||
Argument* arg, dynamic::Value value, const dynamic::Value& origin
|
||||
) {
|
||||
if (origin.index() == 0) {
|
||||
return value;
|
||||
@ -266,14 +273,17 @@ public:
|
||||
if (arg->type == ArgType::number) {
|
||||
return dynamic::get_number(origin) + dynamic::get_number(value);
|
||||
} else {
|
||||
return dynamic::get_integer(origin) + dynamic::get_integer(value);
|
||||
return dynamic::get_integer(origin) +
|
||||
dynamic::get_integer(value);
|
||||
}
|
||||
} catch (std::runtime_error& err) {
|
||||
throw argumentError(arg->name, err.what());
|
||||
}
|
||||
}
|
||||
|
||||
dynamic::Value parseRelativeValue(CommandsInterpreter* interpreter, Argument* arg) {
|
||||
dynamic::Value parseRelativeValue(
|
||||
CommandsInterpreter* interpreter, Argument* arg
|
||||
) {
|
||||
if (arg->type != ArgType::number && arg->type != ArgType::integer) {
|
||||
throw error("'~' operator is only allowed for numeric arguments");
|
||||
}
|
||||
@ -290,17 +300,18 @@ public:
|
||||
}
|
||||
|
||||
inline dynamic::Value performKeywordArg(
|
||||
CommandsInterpreter* interpreter, Command* command, const std::string& key
|
||||
CommandsInterpreter* interpreter,
|
||||
Command* command,
|
||||
const std::string& key
|
||||
) {
|
||||
if (auto arg = command->getArgument(key)) {
|
||||
nextChar();
|
||||
auto value = peek() == '~'
|
||||
? parseRelativeValue(interpreter, arg)
|
||||
: parseValue();
|
||||
auto value = peek() == '~' ? parseRelativeValue(interpreter, arg)
|
||||
: parseValue();
|
||||
typeCheck(arg, value);
|
||||
return value;
|
||||
} else {
|
||||
throw error("unknown keyword "+util::quote(key));
|
||||
throw error("unknown keyword " + util::quote(key));
|
||||
}
|
||||
}
|
||||
|
||||
@ -309,7 +320,7 @@ public:
|
||||
std::string name = parseIdentifier(true);
|
||||
auto command = repo->get(name);
|
||||
if (command == nullptr) {
|
||||
throw error("unknown command "+util::quote(name));
|
||||
throw error("unknown command " + util::quote(name));
|
||||
}
|
||||
auto args = dynamic::create_list();
|
||||
auto kwargs = dynamic::create_map();
|
||||
@ -324,7 +335,7 @@ public:
|
||||
value = static_cast<integer_t>(0);
|
||||
nextChar();
|
||||
}
|
||||
|
||||
|
||||
if (hasNext() && peekNoJump() != ' ') {
|
||||
value = parseValue();
|
||||
if (auto string = std::get_if<std::string>(&value)) {
|
||||
@ -336,7 +347,9 @@ public:
|
||||
// keyword argument
|
||||
if (!relative && hasNext() && peek() == '=') {
|
||||
auto key = std::get<std::string>(value);
|
||||
kwargs->put(key, performKeywordArg(interpreter, command, key));
|
||||
kwargs->put(
|
||||
key, performKeywordArg(interpreter, command, key)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -364,14 +377,15 @@ public:
|
||||
} while (!typeCheck(arg, value));
|
||||
|
||||
if (relative) {
|
||||
value = applyRelative(arg, value, fetchOrigin(interpreter, arg));
|
||||
value =
|
||||
applyRelative(arg, value, fetchOrigin(interpreter, arg));
|
||||
}
|
||||
args->put(value);
|
||||
}
|
||||
|
||||
while (auto arg = command->getArgument(arg_index++)) {
|
||||
if (!arg->optional) {
|
||||
throw error("missing argument "+util::quote(arg->name));
|
||||
throw error("missing argument " + util::quote(arg->name));
|
||||
} else {
|
||||
if (auto string = std::get_if<std::string>(&arg->def)) {
|
||||
if ((*string)[0] == '$') {
|
||||
@ -386,13 +400,18 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
Command Command::create(std::string_view scheme, std::string_view description, executor_func executor) {
|
||||
return CommandParser("<string>", scheme).parseScheme(std::move(executor), description);
|
||||
Command Command::create(
|
||||
std::string_view scheme,
|
||||
std::string_view description,
|
||||
executor_func executor
|
||||
) {
|
||||
return CommandParser("<string>", scheme)
|
||||
.parseScheme(std::move(executor), description);
|
||||
}
|
||||
|
||||
void CommandsRepository::add(
|
||||
std::string_view scheme,
|
||||
std::string_view description,
|
||||
std::string_view scheme,
|
||||
std::string_view description,
|
||||
executor_func executor
|
||||
) {
|
||||
Command command = Command::create(scheme, description, std::move(executor));
|
||||
|
||||
@ -1,26 +1,30 @@
|
||||
#ifndef LOGIC_COMMANDS_INTERPRETER_HPP_
|
||||
#define LOGIC_COMMANDS_INTERPRETER_HPP_
|
||||
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "../data/dynamic.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <functional>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace cmd {
|
||||
enum class ArgType {
|
||||
number, integer, enumvalue, selector, string
|
||||
};
|
||||
enum class ArgType { number, integer, enumvalue, selector, string };
|
||||
|
||||
inline std::string argtype_name(ArgType type) {
|
||||
switch (type) {
|
||||
case ArgType::number: return "number";
|
||||
case ArgType::integer: return "integer";
|
||||
case ArgType::enumvalue: return "enumeration";
|
||||
case ArgType::selector: return "selector";
|
||||
case ArgType::string: return "string";
|
||||
default: return "<unknown>";
|
||||
case ArgType::number:
|
||||
return "number";
|
||||
case ArgType::integer:
|
||||
return "integer";
|
||||
case ArgType::enumvalue:
|
||||
return "enumeration";
|
||||
case ArgType::selector:
|
||||
return "selector";
|
||||
case ArgType::string:
|
||||
return "string";
|
||||
default:
|
||||
return "<unknown>";
|
||||
}
|
||||
}
|
||||
|
||||
@ -38,14 +42,12 @@ namespace cmd {
|
||||
|
||||
struct Prompt {
|
||||
Command* command;
|
||||
dynamic::List_sptr args; // positional arguments list
|
||||
dynamic::Map_sptr kwargs; // keyword arguments table
|
||||
dynamic::List_sptr args; // positional arguments list
|
||||
dynamic::Map_sptr kwargs; // keyword arguments table
|
||||
};
|
||||
|
||||
using executor_func = std::function<dynamic::Value(
|
||||
CommandsInterpreter*,
|
||||
dynamic::List_sptr args,
|
||||
dynamic::Map_sptr kwargs
|
||||
CommandsInterpreter*, dynamic::List_sptr args, dynamic::Map_sptr kwargs
|
||||
)>;
|
||||
|
||||
class Command {
|
||||
@ -63,15 +65,16 @@ namespace cmd {
|
||||
std::unordered_map<std::string, Argument> kwargs,
|
||||
std::string description,
|
||||
executor_func executor
|
||||
) : name(name),
|
||||
args(std::move(args)),
|
||||
kwargs(std::move(kwargs)),
|
||||
description(description),
|
||||
executor(executor) {}
|
||||
|
||||
)
|
||||
: name(name),
|
||||
args(std::move(args)),
|
||||
kwargs(std::move(kwargs)),
|
||||
description(description),
|
||||
executor(executor) {
|
||||
}
|
||||
|
||||
Argument* getArgument(size_t index) {
|
||||
if (index >= args.size())
|
||||
return nullptr;
|
||||
if (index >= args.size()) return nullptr;
|
||||
return &args[index];
|
||||
}
|
||||
|
||||
@ -83,7 +86,9 @@ namespace cmd {
|
||||
return &found->second;
|
||||
}
|
||||
|
||||
dynamic::Value execute(CommandsInterpreter* interpreter, const Prompt& prompt) {
|
||||
dynamic::Value execute(
|
||||
CommandsInterpreter* interpreter, const Prompt& prompt
|
||||
) {
|
||||
return executor(interpreter, prompt.args, prompt.kwargs);
|
||||
}
|
||||
|
||||
@ -104,9 +109,7 @@ namespace cmd {
|
||||
}
|
||||
|
||||
static Command create(
|
||||
std::string_view scheme,
|
||||
std::string_view description,
|
||||
executor_func
|
||||
std::string_view scheme, std::string_view description, executor_func
|
||||
);
|
||||
};
|
||||
|
||||
@ -114,9 +117,7 @@ namespace cmd {
|
||||
std::unordered_map<std::string, Command> commands;
|
||||
public:
|
||||
void add(
|
||||
std::string_view scheme,
|
||||
std::string_view description,
|
||||
executor_func
|
||||
std::string_view scheme, std::string_view description, executor_func
|
||||
);
|
||||
Command* get(const std::string& name);
|
||||
|
||||
@ -129,12 +130,15 @@ namespace cmd {
|
||||
std::unique_ptr<CommandsRepository> repository;
|
||||
std::unordered_map<std::string, dynamic::Value> variables;
|
||||
public:
|
||||
CommandsInterpreter() : repository(std::make_unique<CommandsRepository>()) {}
|
||||
CommandsInterpreter()
|
||||
: repository(std::make_unique<CommandsRepository>()) {
|
||||
}
|
||||
|
||||
CommandsInterpreter(const CommandsInterpreter&) = delete;
|
||||
|
||||
CommandsInterpreter(std::unique_ptr<CommandsRepository> repository)
|
||||
: repository(std::move(repository)){}
|
||||
: repository(std::move(repository)) {
|
||||
}
|
||||
|
||||
Prompt parse(std::string_view text);
|
||||
|
||||
@ -156,4 +160,4 @@ namespace cmd {
|
||||
};
|
||||
}
|
||||
|
||||
#endif // LOGIC_COMMANDS_INTERPRETER_HPP_
|
||||
#endif // LOGIC_COMMANDS_INTERPRETER_HPP_
|
||||
|
||||
@ -1,27 +1,27 @@
|
||||
#include "EngineController.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
|
||||
#include "../coders/commons.hpp"
|
||||
#include "../content/ContentLUT.hpp"
|
||||
#include "../debug/Logger.hpp"
|
||||
#include "../engine.hpp"
|
||||
#include "../files/WorldFiles.hpp"
|
||||
#include "../files/WorldConverter.hpp"
|
||||
#include "../files/WorldFiles.hpp"
|
||||
#include "../frontend/locale.hpp"
|
||||
#include "../frontend/screens/MenuScreen.hpp"
|
||||
#include "../frontend/screens/LevelScreen.hpp"
|
||||
#include "../frontend/menu.hpp"
|
||||
#include "../frontend/screens/LevelScreen.hpp"
|
||||
#include "../frontend/screens/MenuScreen.hpp"
|
||||
#include "../graphics/ui/elements/Menu.hpp"
|
||||
#include "../graphics/ui/gui_util.hpp"
|
||||
#include "../interfaces/Task.hpp"
|
||||
#include "../util/stringutil.hpp"
|
||||
#include "../world/World.hpp"
|
||||
#include "../world/Level.hpp"
|
||||
#include "../world/World.hpp"
|
||||
#include "LevelController.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <filesystem>
|
||||
#include <algorithm>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
static debug::Logger logger("engine-control");
|
||||
@ -31,46 +31,62 @@ EngineController::EngineController(Engine* engine) : engine(engine) {
|
||||
|
||||
void EngineController::deleteWorld(const std::string& name) {
|
||||
fs::path folder = engine->getPaths()->getWorldFolder(name);
|
||||
guiutil::confirm(engine->getGUI(), langs::get(L"delete-confirm", L"world")+
|
||||
L" ("+util::str2wstr_utf8(folder.u8string())+L")", [=]() {
|
||||
logger.info() << "deleting " << folder.u8string();
|
||||
fs::remove_all(folder);
|
||||
});
|
||||
guiutil::confirm(
|
||||
engine->getGUI(),
|
||||
langs::get(L"delete-confirm", L"world") + L" (" +
|
||||
util::str2wstr_utf8(folder.u8string()) + L")",
|
||||
[=]() {
|
||||
logger.info() << "deleting " << folder.u8string();
|
||||
fs::remove_all(folder);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
std::shared_ptr<Task> create_converter(
|
||||
Engine* engine,
|
||||
const fs::path& folder,
|
||||
const Content* content,
|
||||
const Content* content,
|
||||
const std::shared_ptr<ContentLUT>& lut,
|
||||
const runnable& postRunnable)
|
||||
{
|
||||
return WorldConverter::startTask(folder, content, lut, [=](){
|
||||
auto menu = engine->getGUI()->getMenu();
|
||||
menu->reset();
|
||||
menu->setPage("main", false);
|
||||
engine->getGUI()->postRunnable([=]() {
|
||||
postRunnable();
|
||||
});
|
||||
}, true);
|
||||
const runnable& postRunnable
|
||||
) {
|
||||
return WorldConverter::startTask(
|
||||
folder,
|
||||
content,
|
||||
lut,
|
||||
[=]() {
|
||||
auto menu = engine->getGUI()->getMenu();
|
||||
menu->reset();
|
||||
menu->setPage("main", false);
|
||||
engine->getGUI()->postRunnable([=]() { postRunnable(); });
|
||||
},
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
void show_convert_request(
|
||||
Engine* engine,
|
||||
const Content* content,
|
||||
Engine* engine,
|
||||
const Content* content,
|
||||
const std::shared_ptr<ContentLUT>& lut,
|
||||
const fs::path& folder,
|
||||
const runnable& postRunnable
|
||||
) {
|
||||
guiutil::confirm(engine->getGUI(), langs::get(L"world.convert-request"), [=]() {
|
||||
auto converter = create_converter(engine, folder, content, lut, postRunnable);
|
||||
menus::show_process_panel(engine, converter, L"Converting world...");
|
||||
}, L"", langs::get(L"Cancel"));
|
||||
guiutil::confirm(
|
||||
engine->getGUI(),
|
||||
langs::get(L"world.convert-request"),
|
||||
[=]() {
|
||||
auto converter =
|
||||
create_converter(engine, folder, content, lut, postRunnable);
|
||||
menus::show_process_panel(
|
||||
engine, converter, L"Converting world..."
|
||||
);
|
||||
},
|
||||
L"",
|
||||
langs::get(L"Cancel")
|
||||
);
|
||||
}
|
||||
|
||||
static void show_content_missing(
|
||||
Engine* engine,
|
||||
const std::shared_ptr<ContentLUT>& lut
|
||||
Engine* engine, const std::shared_ptr<ContentLUT>& lut
|
||||
) {
|
||||
using namespace dynamic;
|
||||
auto root = create_map();
|
||||
@ -97,11 +113,13 @@ static void loadWorld(Engine* engine, const fs::path& folder) {
|
||||
auto& settings = engine->getSettings();
|
||||
|
||||
auto level = World::load(folder, settings, content, packs);
|
||||
engine->setScreen(std::make_shared<LevelScreen>(engine, std::move(level)));
|
||||
engine->setScreen(
|
||||
std::make_shared<LevelScreen>(engine, std::move(level))
|
||||
);
|
||||
} catch (const world_load_error& error) {
|
||||
guiutil::alert(
|
||||
engine->getGUI(), langs::get(L"Error")+L": "+
|
||||
util::str2wstr_utf8(error.what())
|
||||
engine->getGUI(),
|
||||
langs::get(L"Error") + L": " + util::str2wstr_utf8(error.what())
|
||||
);
|
||||
return;
|
||||
}
|
||||
@ -109,25 +127,33 @@ static void loadWorld(Engine* engine, const fs::path& folder) {
|
||||
|
||||
void EngineController::openWorld(const std::string& name, bool confirmConvert) {
|
||||
auto paths = engine->getPaths();
|
||||
auto folder = paths->getWorldsFolder()/fs::u8path(name);
|
||||
auto folder = paths->getWorldsFolder() / fs::u8path(name);
|
||||
if (!loadWorldContent(engine, folder)) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto* content = engine->getContent();
|
||||
|
||||
std::shared_ptr<ContentLUT> lut (World::checkIndices(folder, content));
|
||||
std::shared_ptr<ContentLUT> lut(World::checkIndices(folder, content));
|
||||
if (lut) {
|
||||
if (lut->hasMissingContent()) {
|
||||
engine->setScreen(std::make_shared<MenuScreen>(engine));
|
||||
show_content_missing(engine, lut);
|
||||
} else {
|
||||
if (confirmConvert) {
|
||||
menus::show_process_panel(engine, create_converter(engine, folder, content, lut, [=]() {
|
||||
openWorld(name, false);
|
||||
}), L"Converting world...");
|
||||
menus::show_process_panel(
|
||||
engine,
|
||||
create_converter(
|
||||
engine,
|
||||
folder,
|
||||
content,
|
||||
lut,
|
||||
[=]() { openWorld(name, false); }
|
||||
),
|
||||
L"Converting world..."
|
||||
);
|
||||
} else {
|
||||
show_convert_request(engine, content, lut, folder, [=](){
|
||||
show_convert_request(engine, content, lut, folder, [=]() {
|
||||
openWorld(name, false);
|
||||
});
|
||||
}
|
||||
@ -152,24 +178,27 @@ inline uint64_t str2seed(const std::string& seedstr) {
|
||||
}
|
||||
|
||||
void EngineController::createWorld(
|
||||
const std::string& name,
|
||||
const std::string& name,
|
||||
const std::string& seedstr,
|
||||
const std::string& generatorID
|
||||
) {
|
||||
uint64_t seed = str2seed(seedstr);
|
||||
|
||||
EnginePaths* paths = engine->getPaths();
|
||||
auto folder = paths->getWorldsFolder()/fs::u8path(name);
|
||||
auto folder = paths->getWorldsFolder() / fs::u8path(name);
|
||||
|
||||
if (!menus::call(engine, [this, paths, folder]() {
|
||||
engine->loadContent();
|
||||
paths->setWorldFolder(folder);
|
||||
})) {
|
||||
engine->loadContent();
|
||||
paths->setWorldFolder(folder);
|
||||
})) {
|
||||
return;
|
||||
}
|
||||
auto level = World::create(
|
||||
name, generatorID, folder, seed,
|
||||
engine->getSettings(),
|
||||
name,
|
||||
generatorID,
|
||||
folder,
|
||||
seed,
|
||||
engine->getSettings(),
|
||||
engine->getContent(),
|
||||
engine->getContentPacks()
|
||||
);
|
||||
@ -208,7 +237,8 @@ void EngineController::reconfigPacks(
|
||||
try {
|
||||
auto manager = engine->createPacksManager(fs::path(""));
|
||||
manager.scan();
|
||||
std::vector<std::string> names = PacksManager::getNames(engine->getContentPacks());
|
||||
std::vector<std::string> names =
|
||||
PacksManager::getNames(engine->getContentPacks());
|
||||
for (const auto& id : packsToAdd) {
|
||||
names.push_back(id);
|
||||
}
|
||||
@ -219,7 +249,9 @@ void EngineController::reconfigPacks(
|
||||
names = manager.assembly(names);
|
||||
engine->getContentPacks() = manager.getAll(names);
|
||||
} catch (const contentpack_error& err) {
|
||||
throw std::runtime_error(std::string(err.what())+" ["+err.getPackId()+"]");
|
||||
throw std::runtime_error(
|
||||
std::string(err.what()) + " [" + err.getPackId() + "]"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
auto world = controller->getLevel()->getWorld();
|
||||
@ -244,10 +276,10 @@ void EngineController::reconfigPacks(
|
||||
|
||||
if (hasIndices) {
|
||||
guiutil::confirm(
|
||||
engine->getGUI(),
|
||||
langs::get(L"remove-confirm", L"pack")+
|
||||
L" ("+util::str2wstr_utf8(ss.str())+L")",
|
||||
[=]() {removeFunc();}
|
||||
engine->getGUI(),
|
||||
langs::get(L"remove-confirm", L"pack") + L" (" +
|
||||
util::str2wstr_utf8(ss.str()) + L")",
|
||||
[=]() { removeFunc(); }
|
||||
);
|
||||
} else {
|
||||
removeFunc();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user