diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3540fb3d2..6be8a91ea 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,6 +4,10 @@ file(GLOB_RECURSE headers ${CMAKE_CURRENT_SOURCE_DIR}/*.hpp) file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) list(REMOVE_ITEM sources ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) +file(GLOB_RECURSE wayland_sources + ${CMAKE_CURRENT_SOURCE_DIR}/window/wayland/*.cpp) +list(REMOVE_ITEM sources ${wayland_sources}) + add_library(VoxelCoreSrc STATIC ${sources} ${headers}) find_package(OpenGL REQUIRED) @@ -120,7 +124,8 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND) # tablet is referenced by cursor-shape-v1 voxel_wayland_protocol(tablet-unstable-v2.xml tablet-unstable-v2) - target_sources(VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES}) + target_sources( + VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources}) target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED}) target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1) target_link_libraries( diff --git a/src/engine/Engine.cpp b/src/engine/Engine.cpp index 9f33892b9..4f39f9356 100644 --- a/src/engine/Engine.cpp +++ b/src/engine/Engine.cpp @@ -1,481 +1,481 @@ -#include "Engine.hpp" -#include "WindowBar.hpp" - -#ifndef GLEW_STATIC -#define GLEW_STATIC -#endif - -#include "AssetsManagement.hpp" -#include "audio/audio.hpp" -#include "coders/commons.hpp" -#include "coders/GLSLExtension.hpp" -#include "coders/toml.hpp" -#include "coders/vector_fonts.hpp" -#include "content/ContentControl.hpp" -#include "core_defs.hpp" -#include "debug/Logger.hpp" -#include "devtools/AppScriptsControl.hpp" -#include "devtools/DebuggingServer.hpp" -#include "devtools/Editor.hpp" -#include "devtools/Project.hpp" -#include "devtools/stdin_cmd_reader.hpp" -#include "EnginePaths.hpp" -#include "frontend/locale.hpp" -#include "frontend/menu.hpp" -#include "frontend/screens/Screen.hpp" -#include "graphics/core/DrawContext.hpp" -#include "graphics/core/Shader.hpp" -#include "graphics/ui/elements/Menu.hpp" -#include "graphics/ui/GUI.hpp" -#include "io/io.hpp" -#include "io/settings_io.hpp" -#include "logic/CommandsInterpreter.hpp" -#include "logic/EngineController.hpp" -#include "logic/scripting/scripting_hud.hpp" -#include "logic/scripting/scripting.hpp" -#include "Mainloop.hpp" -#include "network/Network.hpp" -#include "ServerMainloop.hpp" -#include "util/platform.hpp" -#include "util/stringutil.hpp" -#include "window/input.hpp" -#include "window/Window.hpp" -#include "WindowControl.hpp" -#include "world/Level.hpp" - -#include -#include -#include -#include - -static debug::Logger logger("engine"); - -Engine::Engine() = default; -Engine::~Engine() = default; - -static std::unique_ptr instance = nullptr; - -Engine& Engine::getInstance() { - if (!instance) { - instance = std::make_unique(); - } - return *instance; -} - -void Engine::onContentLoad() { - editor->loadTools(); - langs::setup(langs::get_current(), paths->resPaths.collectRoots()); - - if (isHeadless()) { - return; - } - for (auto& pack : content->getAllContentPacks()) { - auto configFolder = pack.folder / "config"; - auto bindsFile = configFolder / "bindings.toml"; - logger.info() << "loading bindings: " << bindsFile.string(); - if (io::is_regular_file(bindsFile)) { - input->getBindings().read( - toml::parse( - bindsFile.string(), io::read_string(bindsFile) - ), - BindType::BIND - ); - } - } - loadAssets(); -} - -void Engine::initializeClient() { - assets = std::make_unique(*this); - windowControl = std::make_unique(*this); - auto [window, input] = windowControl->initialize(); - - this->window = std::move(window); - this->input = std::move(input); - - loadControls(); - - gui = std::make_unique(*this); - if (ENGINE_DEBUG_BUILD) { - menus::create_version_label(*gui); - } - keepAlive(settings.display.windowMode.observe( - [this](int value) { - WindowMode mode = static_cast(value); - if (mode != this->window->getMode()) { - this->window->setMode(mode); - } - }, - true - )); - keepAlive(settings.debug.doTraceShaders.observe( - [](bool value) { - Shader::preprocessor->setTraceOutput(value); - }, - true - )); - - keepAlive(this->input->addKeyCallback(Keycode::ESCAPE, [this]() { - auto& menu = *gui->getMenu(); - if (menu.hasOpenPage() && menu.back()) { - return true; - } - return false; - })); -} - -void Engine::initialize(CoreParameters coreParameters) { - params = std::move(coreParameters); - settingsHandler = std::make_unique(settings); - - logger.info() << "engine version: " << ENGINE_VERSION_STRING; - if (params.headless) { - logger.info() << "engine runs in headless mode"; - } - if (params.projectFolder.empty()) { - params.projectFolder = params.resFolder; - } - paths = std::make_unique(params); - loadProject(); - paths->setupProject(*project); - - editor = std::make_unique(*this); - cmd = std::make_unique(); - - if (project->permissions.has(Permissions::NETWORK) || - !params.debugServerString.empty()) { - network = network::Network::create(settings.network); - } - - if (!params.debugServerString.empty()) { - try { - debuggingServer = std::make_unique( - *this, params.debugServerString - ); - } catch (const std::runtime_error& err) { - throw initialize_error( - "debugging server error: " + std::string(err.what()) - ); - } - } - loadSettings(); - - controller = std::make_unique(*this); - if (!params.headless) { - initializeClient(); - } - audio::initialize( - !params.headless, - project->permissions.has(Permissions::RECORD_AUDIO), - settings.audio - ); - - vector_fonts::initialize(); - - if (settings.ui.language.get() == "auto") { - settings.ui.language.set( - langs::locale_by_envlocale(platform::detect_locale()) - ); - } - content = std::make_unique( - *project, *paths, input.get(), [this]() { onContentLoad(); } - ); - scripting::initialize(*this); - - if (!isHeadless()) { - gui->getMenu()->setPageLoader(scripting::create_page_loader()); - } - keepAlive(settings.ui.language.observe([this](auto lang) { - langs::setup(lang, paths->resPaths.collectRoots()); - }, true)); - - keepAlive(settings.audio.inputDevice.observe([](auto name) { - audio::set_input_device(name == "auto" ? "" : name); - })); - - appScripts = std::make_unique(params); - - if (params.stdinCommands) { - cmd::start_stdin_cmd_reader(*this); - } -} - -void Engine::loadSettings() { - io::path settings_file = EnginePaths::SETTINGS_FILE; - if (io::is_regular_file(settings_file)) { - logger.info() << "loading settings"; - std::string text = io::read_string(settings_file); - try { - toml::parse(*settingsHandler, settings_file.string(), text); - } catch (const parsing_error& err) { - logger.error() << err.errorLog(); - throw; - } - } -} - -void Engine::loadControls() { - io::path controls_file = EnginePaths::CONTROLS_FILE; - if (io::is_regular_file(controls_file)) { - logger.info() << "loading controls"; - std::string text = io::read_string(controls_file); - input->getBindings().read( - toml::parse(controls_file.string(), text), BindType::BIND - ); - } -} - -void Engine::updateHotkeys() { - if (input->jpressed(Keycode::F2)) { - windowControl->saveScreenshot(); - } - if (input->pressed(Keycode::LEFT_CONTROL) && input->pressed(Keycode::F3) && - input->jpressed(Keycode::U)) { - gui->toggleDebug(); - } - if (input->jpressed(Keycode::F11)) { - windowControl->toggleFullscreen(); - } -} - -void Engine::run() { - if (params.headless) { - ServerMainloop(*this).run(); - } else { - Mainloop(*this).run(); - } -} - -void Engine::postUpdate() { - if (network) { - network->update(); - } - postRunnables.run(); - scripting::process_post_runnables(); - - if (debuggingServer) { - debuggingServer->update(); - } -} - -void Engine::detachDebugger() { - debuggingServer.reset(); -} - -void Engine::applicationTick() { - appScripts->tick(); -} - -void Engine::updateFrontend() { - double delta = time.getDelta(); - assets->update(); - updateHotkeys(); - audio::update(delta); - gui->act(delta, window->getSize()); - screen->update(delta); - gui->postAct(); -} - -void Engine::nextFrame(bool waitForRefresh) { - windowControl->nextFrame(waitForRefresh); -} - -void Engine::startPauseLoop() { - assert (network != nullptr); - - bool initialCursorLocked = false; - if (!isHeadless()) { - initialCursorLocked = input->isCursorLocked(); - if (initialCursorLocked) { - input->toggleCursor(); - } - } - while (!isQuitSignal() && debuggingServer) { - network->update(); - if (debuggingServer->update()) { - break; - } - if (isHeadless()) { - platform::sleep(1.0 / params.tps * 1000); - } else { - nextFrame(false); - } - } - if (initialCursorLocked) { - input->toggleCursor(); - } -} - -void Engine::renderFrame() { - if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) { - input->toggleCursor(); - } - screen->draw(time.getDelta()); - - DrawContext ctx(nullptr, *window, nullptr); - gui->draw(ctx, *assets->getStorage()); - draw_window_bar(*this); -} - -void Engine::saveSettings() { - logger.info() << "saving settings"; - io::write_string(EnginePaths::SETTINGS_FILE, toml::stringify(*settingsHandler)); - if (!params.headless) { - logger.info() << "saving bindings"; - if (input) { - io::write_string( - EnginePaths::CONTROLS_FILE, input->getBindings().write() - ); - } - } -} - -void Engine::close() { - saveSettings(); - logger.info() << "shutting down"; - if (screen) { - screen->onEngineShutdown(); - screen.reset(); - } - content.reset(); - assets.reset(); - cmd.reset(); - if (gui) { - gui.reset(); - logger.info() << "gui finished"; - } - if (!isHeadless()) { - vector_fonts::finalize(); - } - audio::close(); - debuggingServer.reset(); - network.reset(); - clearKeepedObjects(); - project.reset(); - appScripts.reset(); - scripting::close(); - logger.info() << "scripting finished"; - if (!params.headless) { - window.reset(); - logger.info() << "window closed"; - } - logger.info() << "engine finished"; -} - -void Engine::terminate() { - instance->close(); - instance.reset(); -} - -EngineController* Engine::getController() { - return controller.get(); -} - -void Engine::setLevelConsumer(OnWorldOpen levelConsumer) { - this->levelConsumer = std::move(levelConsumer); -} - -void Engine::loadAssets() { - assets->loadAssets(content->get()); -} - -void Engine::loadProject() { - io::path projectFile = "project:project.toml"; - project = std::make_unique(); - project->path = "project:"; - project->deserialize(io::read_object(projectFile)); - logger.info() << "loaded project " << util::quote(project->name); -} - -void Engine::setScreen(std::shared_ptr screen) { - if (this->screen) { - appScripts->onScreenChange(this->screen->getName(), false); - } - // reset audio channels (stop all sources) - audio::reset_channel(audio::get_channel_index("regular")); - audio::reset_channel(audio::get_channel_index("ambient")); - this->screen = std::move(screen); - if (this->screen) { - this->screen->onOpen(); - } - if (this->screen) { - appScripts->onScreenChange(this->screen->getName(), true); - window->setShouldRefresh(); - } -} - -void Engine::onWorldOpen(std::unique_ptr level, int64_t localPlayer) { - logger.info() << "world open"; - levelConsumer(std::move(level), localPlayer); -} - -void Engine::onWorldClosed() { - logger.info() << "world closed"; - levelConsumer(nullptr, -1); -} - -void Engine::quit() { - logger.info() << "quitSignal set to true"; - quitSignal = true; - if (!isHeadless()) { - window->setShouldClose(true); - } -} - -bool Engine::isQuitSignal() const { - return quitSignal; -} - -EngineSettings& Engine::getSettings() { - return settings; -} - -Assets* Engine::getAssets() { - return assets ? assets->getStorage() : nullptr; -} - -Assets& Engine::requireAssets() { - if (isHeadless()) { - throw std::runtime_error("assets are not available in headless mode"); - } - return *assets->getStorage(); -} - -AssetsLoader& Engine::acquireBackgroundLoader() { - if (isHeadless()) { - throw std::runtime_error("assets are not available in headless mode"); - } - return assets->acquireBackgroundLoader(); -} - -EnginePaths& Engine::getPaths() { - return *paths; -} - -ResPaths& Engine::getResPaths() { - return paths->resPaths; -} - -std::shared_ptr Engine::getScreen() { - return screen; -} - -SettingsHandler& Engine::getSettingsHandler() { - return *settingsHandler; -} - -Time& Engine::getTime() { - return time; -} - -const CoreParameters& Engine::getCoreParameters() const { - return params; -} - -bool Engine::isHeadless() const { - return params.headless; -} - -ContentControl& Engine::getContentControl() { - return *content; -} +#include "Engine.hpp" +#include "WindowBar.hpp" + +#ifndef GLEW_STATIC +#define GLEW_STATIC +#endif + +#include "AssetsManagement.hpp" +#include "audio/audio.hpp" +#include "coders/commons.hpp" +#include "coders/GLSLExtension.hpp" +#include "coders/toml.hpp" +#include "coders/vector_fonts.hpp" +#include "content/ContentControl.hpp" +#include "core_defs.hpp" +#include "debug/Logger.hpp" +#include "devtools/AppScriptsControl.hpp" +#include "devtools/DebuggingServer.hpp" +#include "devtools/Editor.hpp" +#include "devtools/Project.hpp" +#include "devtools/stdin_cmd_reader.hpp" +#include "EnginePaths.hpp" +#include "frontend/locale.hpp" +#include "frontend/menu.hpp" +#include "frontend/screens/Screen.hpp" +#include "graphics/core/DrawContext.hpp" +#include "graphics/core/Shader.hpp" +#include "graphics/ui/elements/Menu.hpp" +#include "graphics/ui/GUI.hpp" +#include "io/io.hpp" +#include "io/settings_io.hpp" +#include "logic/CommandsInterpreter.hpp" +#include "logic/EngineController.hpp" +#include "logic/scripting/scripting_hud.hpp" +#include "logic/scripting/scripting.hpp" +#include "Mainloop.hpp" +#include "network/Network.hpp" +#include "ServerMainloop.hpp" +#include "util/platform.hpp" +#include "util/stringutil.hpp" +#include "window/input.hpp" +#include "window/Window.hpp" +#include "WindowControl.hpp" +#include "world/Level.hpp" + +#include +#include +#include +#include + +static debug::Logger logger("engine"); + +Engine::Engine() = default; +Engine::~Engine() = default; + +static std::unique_ptr instance = nullptr; + +Engine& Engine::getInstance() { + if (!instance) { + instance = std::make_unique(); + } + return *instance; +} + +void Engine::onContentLoad() { + editor->loadTools(); + langs::setup(langs::get_current(), paths->resPaths.collectRoots()); + + if (isHeadless()) { + return; + } + for (auto& pack : content->getAllContentPacks()) { + auto configFolder = pack.folder / "config"; + auto bindsFile = configFolder / "bindings.toml"; + logger.info() << "loading bindings: " << bindsFile.string(); + if (io::is_regular_file(bindsFile)) { + input->getBindings().read( + toml::parse( + bindsFile.string(), io::read_string(bindsFile) + ), + BindType::BIND + ); + } + } + loadAssets(); +} + +void Engine::initializeClient() { + assets = std::make_unique(*this); + windowControl = std::make_unique(*this); + auto [window, input] = windowControl->initialize(); + + this->window = std::move(window); + this->input = std::move(input); + + loadControls(); + + gui = std::make_unique(*this); + if (ENGINE_DEBUG_BUILD) { + menus::create_version_label(*gui); + } + keepAlive(settings.display.windowMode.observe( + [this](int value) { + WindowMode mode = static_cast(value); + if (mode != this->window->getMode()) { + this->window->setMode(mode); + } + }, + true + )); + keepAlive(settings.debug.doTraceShaders.observe( + [](bool value) { + Shader::preprocessor->setTraceOutput(value); + }, + true + )); + + keepAlive(this->input->addKeyCallback(Keycode::ESCAPE, [this]() { + auto& menu = *gui->getMenu(); + if (menu.hasOpenPage() && menu.back()) { + return true; + } + return false; + })); +} + +void Engine::initialize(CoreParameters coreParameters) { + params = std::move(coreParameters); + settingsHandler = std::make_unique(settings); + + logger.info() << "engine version: " << ENGINE_VERSION_STRING; + if (params.headless) { + logger.info() << "engine runs in headless mode"; + } + if (params.projectFolder.empty()) { + params.projectFolder = params.resFolder; + } + paths = std::make_unique(params); + loadProject(); + paths->setupProject(*project); + + editor = std::make_unique(*this); + cmd = std::make_unique(); + + if (project->permissions.has(Permissions::NETWORK) || + !params.debugServerString.empty()) { + network = network::Network::create(settings.network); + } + + if (!params.debugServerString.empty()) { + try { + debuggingServer = std::make_unique( + *this, params.debugServerString + ); + } catch (const std::runtime_error& err) { + throw initialize_error( + "debugging server error: " + std::string(err.what()) + ); + } + } + loadSettings(); + + controller = std::make_unique(*this); + if (!params.headless) { + initializeClient(); + } + audio::initialize( + !params.headless, + project->permissions.has(Permissions::RECORD_AUDIO), + settings.audio + ); + + vector_fonts::initialize(); + + if (settings.ui.language.get() == "auto") { + settings.ui.language.set( + langs::locale_by_envlocale(platform::detect_locale()) + ); + } + content = std::make_unique( + *project, *paths, input.get(), [this]() { onContentLoad(); } + ); + scripting::initialize(*this); + + if (!isHeadless()) { + gui->getMenu()->setPageLoader(scripting::create_page_loader()); + } + keepAlive(settings.ui.language.observe([this](auto lang) { + langs::setup(lang, paths->resPaths.collectRoots()); + }, true)); + + keepAlive(settings.audio.inputDevice.observe([](auto name) { + audio::set_input_device(name == "auto" ? "" : name); + })); + + appScripts = std::make_unique(params); + + if (params.stdinCommands) { + cmd::start_stdin_cmd_reader(*this); + } +} + +void Engine::loadSettings() { + io::path settings_file = EnginePaths::SETTINGS_FILE; + if (io::is_regular_file(settings_file)) { + logger.info() << "loading settings"; + std::string text = io::read_string(settings_file); + try { + toml::parse(*settingsHandler, settings_file.string(), text); + } catch (const parsing_error& err) { + logger.error() << err.errorLog(); + throw; + } + } +} + +void Engine::loadControls() { + io::path controls_file = EnginePaths::CONTROLS_FILE; + if (io::is_regular_file(controls_file)) { + logger.info() << "loading controls"; + std::string text = io::read_string(controls_file); + input->getBindings().read( + toml::parse(controls_file.string(), text), BindType::BIND + ); + } +} + +void Engine::updateHotkeys() { + if (input->jpressed(Keycode::F2)) { + windowControl->saveScreenshot(); + } + if (input->pressed(Keycode::LEFT_CONTROL) && input->pressed(Keycode::F3) && + input->jpressed(Keycode::U)) { + gui->toggleDebug(); + } + if (input->jpressed(Keycode::F11)) { + windowControl->toggleFullscreen(); + } +} + +void Engine::run() { + if (params.headless) { + ServerMainloop(*this).run(); + } else { + Mainloop(*this).run(); + } +} + +void Engine::postUpdate() { + if (network) { + network->update(); + } + postRunnables.run(); + scripting::process_post_runnables(); + + if (debuggingServer) { + debuggingServer->update(); + } +} + +void Engine::detachDebugger() { + debuggingServer.reset(); +} + +void Engine::applicationTick() { + appScripts->tick(); +} + +void Engine::updateFrontend() { + double delta = time.getDelta(); + assets->update(); + updateHotkeys(); + audio::update(delta); + gui->act(delta, window->getSize()); + screen->update(delta); + gui->postAct(); +} + +void Engine::nextFrame(bool waitForRefresh) { + windowControl->nextFrame(waitForRefresh); +} + +void Engine::startPauseLoop() { + assert (network != nullptr); + + bool initialCursorLocked = false; + if (!isHeadless()) { + initialCursorLocked = input->isCursorLocked(); + if (initialCursorLocked) { + input->toggleCursor(); + } + } + while (!isQuitSignal() && debuggingServer) { + network->update(); + if (debuggingServer->update()) { + break; + } + if (isHeadless()) { + platform::sleep(1.0 / params.tps * 1000); + } else { + nextFrame(false); + } + } + if (initialCursorLocked) { + input->toggleCursor(); + } +} + +void Engine::renderFrame() { + if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) { + input->toggleCursor(); + } + screen->draw(time.getDelta()); + + DrawContext ctx(nullptr, *window, nullptr); + gui->draw(ctx, *assets->getStorage()); + draw_window_bar(*this); +} + +void Engine::saveSettings() { + logger.info() << "saving settings"; + io::write_string(EnginePaths::SETTINGS_FILE, toml::stringify(*settingsHandler)); + if (!params.headless) { + logger.info() << "saving bindings"; + if (input) { + io::write_string( + EnginePaths::CONTROLS_FILE, input->getBindings().write() + ); + } + } +} + +void Engine::close() { + saveSettings(); + logger.info() << "shutting down"; + if (screen) { + screen->onEngineShutdown(); + screen.reset(); + } + content.reset(); + assets.reset(); + cmd.reset(); + if (gui) { + gui.reset(); + logger.info() << "gui finished"; + } + if (!isHeadless()) { + vector_fonts::finalize(); + } + audio::close(); + debuggingServer.reset(); + network.reset(); + clearKeepedObjects(); + project.reset(); + appScripts.reset(); + scripting::close(); + logger.info() << "scripting finished"; + if (!params.headless) { + window.reset(); + logger.info() << "window closed"; + } + logger.info() << "engine finished"; +} + +void Engine::terminate() { + instance->close(); + instance.reset(); +} + +EngineController* Engine::getController() { + return controller.get(); +} + +void Engine::setLevelConsumer(OnWorldOpen levelConsumer) { + this->levelConsumer = std::move(levelConsumer); +} + +void Engine::loadAssets() { + assets->loadAssets(content->get()); +} + +void Engine::loadProject() { + io::path projectFile = "project:project.toml"; + project = std::make_unique(); + project->path = "project:"; + project->deserialize(io::read_object(projectFile)); + logger.info() << "loaded project " << util::quote(project->name); +} + +void Engine::setScreen(std::shared_ptr screen) { + if (this->screen) { + appScripts->onScreenChange(this->screen->getName(), false); + } + // reset audio channels (stop all sources) + audio::reset_channel(audio::get_channel_index("regular")); + audio::reset_channel(audio::get_channel_index("ambient")); + this->screen = std::move(screen); + if (this->screen) { + this->screen->onOpen(); + } + if (this->screen) { + appScripts->onScreenChange(this->screen->getName(), true); + window->setShouldRefresh(); + } +} + +void Engine::onWorldOpen(std::unique_ptr level, int64_t localPlayer) { + logger.info() << "world open"; + levelConsumer(std::move(level), localPlayer); +} + +void Engine::onWorldClosed() { + logger.info() << "world closed"; + levelConsumer(nullptr, -1); +} + +void Engine::quit() { + logger.info() << "quitSignal set to true"; + quitSignal = true; + if (!isHeadless()) { + window->setShouldClose(true); + } +} + +bool Engine::isQuitSignal() const { + return quitSignal; +} + +EngineSettings& Engine::getSettings() { + return settings; +} + +Assets* Engine::getAssets() { + return assets ? assets->getStorage() : nullptr; +} + +Assets& Engine::requireAssets() { + if (isHeadless()) { + throw std::runtime_error("assets are not available in headless mode"); + } + return *assets->getStorage(); +} + +AssetsLoader& Engine::acquireBackgroundLoader() { + if (isHeadless()) { + throw std::runtime_error("assets are not available in headless mode"); + } + return assets->acquireBackgroundLoader(); +} + +EnginePaths& Engine::getPaths() { + return *paths; +} + +ResPaths& Engine::getResPaths() { + return paths->resPaths; +} + +std::shared_ptr Engine::getScreen() { + return screen; +} + +SettingsHandler& Engine::getSettingsHandler() { + return *settingsHandler; +} + +Time& Engine::getTime() { + return time; +} + +const CoreParameters& Engine::getCoreParameters() const { + return params; +} + +bool Engine::isHeadless() const { + return params.headless; +} + +ContentControl& Engine::getContentControl() { + return *content; +} diff --git a/src/graphics/ui/GUI.hpp b/src/graphics/ui/GUI.hpp index 3cf8406fb..e8b284a65 100644 --- a/src/graphics/ui/GUI.hpp +++ b/src/graphics/ui/GUI.hpp @@ -1,193 +1,193 @@ -#pragma once - -#include "delegates.hpp" - -#include -#include -#include -#include -#include -#include -#include - -class DrawContext; -class Assets; -class Camera; -class Batch2D; -struct CursorState; -class Engine; -class Input; -class Window; -struct FontStylesScheme; - -namespace devtools { - class Editor; -} - -class UiDocument; - -/* - Some info about padding and margin. - Padding is element inner space, margin is outer - glm::vec4 usage: - x - left - y - top - z - right - w - bottom - - Outer element - +======================================================================+ - | . . . . | - | .padding.y . . . | - | padding.x . . . . padding.z | - |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | - | . . . . | - | . .margin.y . . | - | .margin.x . . margin.z. | - |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | - | . | Inner element | . | - |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | - | . . . . | - | . .margin.w . . | - | . . . . | - |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | - | . . . . | - | .padding.w . . . | - | . . . . | - +======================================================================+ -*/ - -namespace gui { - class UINode; - class Container; - class Menu; - class Frame; - - /// @brief The main UI controller - class GUI { - Engine& engine; - Input& input; - std::unique_ptr batch2D; - std::shared_ptr container; - std::shared_ptr hover; - std::shared_ptr pressed; - std::shared_ptr focus; - const UINode* focusedOnStart = nullptr; - std::shared_ptr tooltip; - std::shared_ptr rootDocument; - std::unique_ptr syntaxColorScheme; - std::unordered_map> storage; - std::shared_ptr activeFrame; - - std::unique_ptr uicamera; - std::shared_ptr menu; - std::queue postRunnables; - std::vector> mouseOver; - std::unordered_map> frames; - vec2supplier cursorLocator; - - float tooltipTimer = 0.0f; - float doubleClickTimer = 0.0f; - float doubleClickDelay = 0.5f; - bool doubleClicked = false; - bool debug = false; - - void actMouse(Frame& frame, float delta, const CursorState& cursor); - void actFocused(); - void updateTooltip(float delta); - void resetTooltip(); - public: - static inline std::string CORE_MAIN = "core:main"; - static constexpr int CONTEXT_MENU_ZINDEX = 999; - - GUI(Engine& engine); - ~GUI(); - - /// @brief Get the main menu (Menu) node - std::shared_ptr getMenu(); - - /// @brief Get current focused node - /// @return focused node or nullptr - std::shared_ptr getFocused() const; - - /// @brief Check if all user input is caught by some element like TextBox - bool isFocusCaught() const; - - /// @brief Main input handling and logic update method - /// @param delta delta time - /// @param viewport window size - void act(float delta, const glm::uvec2& viewport); - - /// @brief Draw all visible elements on main container - /// @param pctx parent graphics context - /// @param assets active assets storage - void draw(const DrawContext& pctx, Assets& assets); - - Batch2D* getBatch2D() { - return batch2D.get(); - } - - void postAct(); - - /// @brief Add element to the main container - /// @param node UI element - void add(std::shared_ptr node); - - void addFrame(std::shared_ptr frame); - - void setActiveFrame( - const std::string& id, vec2supplier cursorLocator = nullptr - ); - - std::shared_ptr getActiveFrame() const; - - std::shared_ptr getFrame(const std::string& id); - - /// @brief Remove node from the main container - void remove(UINode* node) noexcept; - - void remove(const std::shared_ptr& node) noexcept { - return remove(node.get()); - } - - /// @brief Store node in the GUI nodes dictionary - /// (does not add node to the main container) - /// @param name node key - /// @param node target node - void store(const std::string& name, std::shared_ptr node); - - /// @brief Get node from the GUI nodes dictionary - /// @param name node key - /// @return stored node or nullptr - std::shared_ptr get(const std::string& name) noexcept; - - /// @brief Remove node from the GUI nodes dictionary - /// @param name node key - void remove(const std::string& name) noexcept; - - /// @brief Set node as focused - /// @param node new focused node or nullptr to remove focus - void setFocus(std::shared_ptr node); - - /// @brief Get the main container - /// @deprecated - std::shared_ptr getContainer() const; - - void setSyntaxColorScheme(std::unique_ptr scheme); - FontStylesScheme* getSyntaxColorScheme() const; - - void onAssetsLoad(Assets* assets); - - void postRunnable(const runnable& callback); - - void setDoubleClickDelay(float delay); - float getDoubleClickDelay() const; - - void toggleDebug(); - const Input& getInput() const; - Input& getInput(); - Window& getWindow(); - devtools::Editor& getEditor(); - Engine& getEngine(); - }; -} +#pragma once + +#include "delegates.hpp" + +#include +#include +#include +#include +#include +#include +#include + +class DrawContext; +class Assets; +class Camera; +class Batch2D; +struct CursorState; +class Engine; +class Input; +class Window; +struct FontStylesScheme; + +namespace devtools { + class Editor; +} + +class UiDocument; + +/* + Some info about padding and margin. + Padding is element inner space, margin is outer + glm::vec4 usage: + x - left + y - top + z - right + w - bottom + + Outer element + +======================================================================+ + | . . . . | + | .padding.y . . . | + | padding.x . . . . padding.z | + |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | + | . . . . | + | . .margin.y . . | + | .margin.x . . margin.z. | + |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | + | . | Inner element | . | + |- - - - - - + - - - - - +====================+- - - - - + - - - - - - | + | . . . . | + | . .margin.w . . | + | . . . . | + |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | + | . . . . | + | .padding.w . . . | + | . . . . | + +======================================================================+ +*/ + +namespace gui { + class UINode; + class Container; + class Menu; + class Frame; + + /// @brief The main UI controller + class GUI { + Engine& engine; + Input& input; + std::unique_ptr batch2D; + std::shared_ptr container; + std::shared_ptr hover; + std::shared_ptr pressed; + std::shared_ptr focus; + const UINode* focusedOnStart = nullptr; + std::shared_ptr tooltip; + std::shared_ptr rootDocument; + std::unique_ptr syntaxColorScheme; + std::unordered_map> storage; + std::shared_ptr activeFrame; + + std::unique_ptr uicamera; + std::shared_ptr menu; + std::queue postRunnables; + std::vector> mouseOver; + std::unordered_map> frames; + vec2supplier cursorLocator; + + float tooltipTimer = 0.0f; + float doubleClickTimer = 0.0f; + float doubleClickDelay = 0.5f; + bool doubleClicked = false; + bool debug = false; + + void actMouse(Frame& frame, float delta, const CursorState& cursor); + void actFocused(); + void updateTooltip(float delta); + void resetTooltip(); + public: + static inline std::string CORE_MAIN = "core:main"; + static constexpr int CONTEXT_MENU_ZINDEX = 999; + + GUI(Engine& engine); + ~GUI(); + + /// @brief Get the main menu (Menu) node + std::shared_ptr getMenu(); + + /// @brief Get current focused node + /// @return focused node or nullptr + std::shared_ptr getFocused() const; + + /// @brief Check if all user input is caught by some element like TextBox + bool isFocusCaught() const; + + /// @brief Main input handling and logic update method + /// @param delta delta time + /// @param viewport window size + void act(float delta, const glm::uvec2& viewport); + + /// @brief Draw all visible elements on main container + /// @param pctx parent graphics context + /// @param assets active assets storage + void draw(const DrawContext& pctx, Assets& assets); + + Batch2D* getBatch2D() { + return batch2D.get(); + } + + void postAct(); + + /// @brief Add element to the main container + /// @param node UI element + void add(std::shared_ptr node); + + void addFrame(std::shared_ptr frame); + + void setActiveFrame( + const std::string& id, vec2supplier cursorLocator = nullptr + ); + + std::shared_ptr getActiveFrame() const; + + std::shared_ptr getFrame(const std::string& id); + + /// @brief Remove node from the main container + void remove(UINode* node) noexcept; + + void remove(const std::shared_ptr& node) noexcept { + return remove(node.get()); + } + + /// @brief Store node in the GUI nodes dictionary + /// (does not add node to the main container) + /// @param name node key + /// @param node target node + void store(const std::string& name, std::shared_ptr node); + + /// @brief Get node from the GUI nodes dictionary + /// @param name node key + /// @return stored node or nullptr + std::shared_ptr get(const std::string& name) noexcept; + + /// @brief Remove node from the GUI nodes dictionary + /// @param name node key + void remove(const std::string& name) noexcept; + + /// @brief Set node as focused + /// @param node new focused node or nullptr to remove focus + void setFocus(std::shared_ptr node); + + /// @brief Get the main container + /// @deprecated + std::shared_ptr getContainer() const; + + void setSyntaxColorScheme(std::unique_ptr scheme); + FontStylesScheme* getSyntaxColorScheme() const; + + void onAssetsLoad(Assets* assets); + + void postRunnable(const runnable& callback); + + void setDoubleClickDelay(float delay); + float getDoubleClickDelay() const; + + void toggleDebug(); + const Input& getInput() const; + Input& getInput(); + Window& getWindow(); + devtools::Editor& getEditor(); + Engine& getEngine(); + }; +} diff --git a/src/window/input.cpp b/src/window/input.cpp index cc07b7bb3..27c9f63e5 100644 --- a/src/window/input.cpp +++ b/src/window/input.cpp @@ -1,267 +1,267 @@ -#include "input.hpp" - -#include "debug/Logger.hpp" -#include "util/stringutil.hpp" -#include "data/dv.hpp" - -#include - -#include -#include - -#ifdef _WIN32 -#include -#endif // _WIN32 - -static debug::Logger logger("input"); - -static std::unordered_map keycodes { - {"enter", GLFW_KEY_ENTER}, - {"space", GLFW_KEY_SPACE}, - {"backspace", GLFW_KEY_BACKSPACE}, - {"caps-lock", GLFW_KEY_CAPS_LOCK}, - {"escape", GLFW_KEY_ESCAPE}, - {"delete", GLFW_KEY_DELETE}, - {"home", GLFW_KEY_HOME}, - {"end", GLFW_KEY_END}, - {"tab", GLFW_KEY_TAB}, - {"insert", GLFW_KEY_INSERT}, - {"page-down", GLFW_KEY_PAGE_DOWN}, - {"page-up", GLFW_KEY_PAGE_UP}, - {"left-shift", GLFW_KEY_LEFT_SHIFT}, - {"right-shift", GLFW_KEY_RIGHT_SHIFT}, - {"left-ctrl", GLFW_KEY_LEFT_CONTROL}, - {"right-ctrl", GLFW_KEY_RIGHT_CONTROL}, - {"left-alt", GLFW_KEY_LEFT_ALT}, - {"right-alt", GLFW_KEY_RIGHT_ALT}, - {"left-super", GLFW_KEY_LEFT_SUPER}, - {"right-super", GLFW_KEY_RIGHT_SUPER}, - {"grave-accent", GLFW_KEY_GRAVE_ACCENT}, - {"left", GLFW_KEY_LEFT}, - {"right", GLFW_KEY_RIGHT}, - {"down", GLFW_KEY_DOWN}, - {"up", GLFW_KEY_UP}, - {"num-lock", GLFW_KEY_NUM_LOCK}, - {"print-screen", GLFW_KEY_PRINT_SCREEN}, - {"num-add", GLFW_KEY_KP_ADD}, - {"num-multiply", GLFW_KEY_KP_MULTIPLY}, - {"num-divide", GLFW_KEY_KP_DIVIDE}, - {"num-subtract", GLFW_KEY_KP_SUBTRACT}, - {"num-enter", GLFW_KEY_KP_ENTER}, - {"num-equal", GLFW_KEY_KP_EQUAL}, - {"num-decimal", GLFW_KEY_KP_DECIMAL}, -}; - -static std::unordered_map mousecodes { - {"left", GLFW_MOUSE_BUTTON_1}, - {"right", GLFW_MOUSE_BUTTON_2}, - {"middle", GLFW_MOUSE_BUTTON_3}, - {"side1", GLFW_MOUSE_BUTTON_4}, - {"side2", GLFW_MOUSE_BUTTON_5}, - {"side3", GLFW_MOUSE_BUTTON_6}, - {"side4", GLFW_MOUSE_BUTTON_7}, - {"side5", GLFW_MOUSE_BUTTON_8}, -}; - -static std::unordered_map keynames {}; -static std::unordered_map buttonsnames{}; - -std::string input_util::get_name(Mousecode code) { - const auto found = buttonsnames.find(static_cast(code)); - if (found == buttonsnames.end()) { - return "unknown"; - } - return found->second; -} - -std::string input_util::get_name(Keycode code) { - const auto found = keynames.find(static_cast(code)); - if (found == keynames.end()) { - return "unknown"; - } - return found->second; -} - -void Binding::reset(InputType type, int code) { - this->type = type; - this->code = code; -} - -void Binding::reset(Keycode code) { - reset(InputType::KEYBOARD, static_cast(code)); -} - -void Binding::reset(Mousecode code) { - reset(InputType::MOUSE, static_cast(code)); -} - -void input_util::initialize() { - for (int i = 0; i <= 9; i++) { - keycodes[std::to_string(i)] = GLFW_KEY_0 + i; - } - for (int i = 0; i < 25; i++) { - keycodes["f" + std::to_string(i + 1)] = GLFW_KEY_F1 + i; - } - for (char i = 'a'; i <= 'z'; i++) { - keycodes[std::string({i})] = GLFW_KEY_A - 'a' + i; - } - for (int i = 0; i <= 9; i++) { - keycodes["num-" + std::to_string(i)] = GLFW_KEY_KP_0 + i; - } - for (const auto& entry : keycodes) { - keynames[entry.second] = entry.first; - } - for (const auto& entry : mousecodes) { - buttonsnames[entry.second] = entry.first; - } -} - -Keycode input_util::keycode_from(const std::string& name) { - const auto& found = keycodes.find(name); - if (found == keycodes.end()) { - return Keycode::UNKNOWN; - } - return static_cast(found->second); -} - -Mousecode input_util::mousecode_from(const std::string& name) { - const auto& found = mousecodes.find(name); - if (found == mousecodes.end()) { - return Mousecode::UNKNOWN; - } - return static_cast(found->second); -} - -static const char* numpad_key_names[] { - "Num 0", - "Num 1", - "Num 2", - "Num 3", - "Num 4", - "Num 5", - "Num 6", - "Num 7", - "Num 8", - "Num 9", - "Num .", - "Num /", - "Num *", - "Num -", - "Num +", - "Num Enter", - "Num =", -}; - -std::string input_util::to_string(Keycode code) { - int icode_repr = static_cast(code); - if (icode_repr == -1) { - return "Unknown"; - } - if (icode_repr >= GLFW_KEY_KP_0 && icode_repr <= GLFW_KEY_KP_EQUAL) { - return numpad_key_names[icode_repr - GLFW_KEY_KP_0]; - } - const auto found = keynames.find(icode_repr); - if (found == keynames.end()) { - return "Unknown"; - } - std::string result; - bool capitalize = true; - for (char c : found->second) { - if (c == '-') { - result += ' '; - capitalize = true; - continue; - } - result += capitalize ? static_cast(std::toupper(c)) : c; - capitalize = false; - } - return result; -} - -std::string input_util::to_string(Mousecode code) { - switch (code) { - case Mousecode::BUTTON_1: - return "LMB"; - case Mousecode::BUTTON_2: - return "RMB"; - case Mousecode::BUTTON_3: - return "MMB"; - case Mousecode::BUTTON_4: - case Mousecode::BUTTON_5: - case Mousecode::BUTTON_6: - case Mousecode::BUTTON_7: - case Mousecode::BUTTON_8: - return "XButton " + std::to_string(static_cast(code) - - static_cast(Mousecode::BUTTON_3)); - default: - return "unknown button"; - } -} - -const Binding& Bindings::require(const std::string& name) const { - if (const auto found = get(name)) { - return *found; - } - throw std::runtime_error("binding '" + name + "' does not exist"); -} - -Binding& Bindings::require(const std::string& name) { - if (const auto found = get(name)) { - return *found; - } - throw std::runtime_error("binding '" + name + "' does not exist"); -} - -void Bindings::read(const dv::value& map, BindType bindType) { - for (auto& [sectionName, section] : map.asObject()) { - for (auto& [name, value] : section.asObject()) { - auto key = sectionName + "." + name; - auto [prefix, codename] = util::split_at(value.asString(), ':'); - InputType type; - int code; - if (prefix == "key") { - type = InputType::KEYBOARD; - code = static_cast(input_util::keycode_from(codename)); - } else if (prefix == "mouse") { - type = InputType::MOUSE; - code = static_cast(input_util::mousecode_from(codename)); - } else { - logger.error() - << "unknown input type: " << prefix << " (binding " - << util::quote(key) << ")"; - continue; - } - if (bindType == BindType::BIND) { - bind(key, type, code); - } else if (bindType == BindType::REBIND) { - rebind(key, type, code); - } - } - } -} - -#include "coders/toml.hpp" - -std::string Bindings::write() const { - auto obj = dv::object(); - for (auto& entry : bindings) { - const auto& binding = entry.second; - std::string value; - switch (binding.type) { - case InputType::KEYBOARD: - value = - "key:" + - input_util::get_name(static_cast(binding.code)); - break; - case InputType::MOUSE: - value = - "mouse:" + - input_util::get_name(static_cast(binding.code)); - break; - default: - throw std::runtime_error("unsupported control type"); - } - obj[entry.first] = std::move(value); - } - return toml::stringify(obj); -} +#include "input.hpp" + +#include "debug/Logger.hpp" +#include "util/stringutil.hpp" +#include "data/dv.hpp" + +#include + +#include +#include + +#ifdef _WIN32 +#include +#endif // _WIN32 + +static debug::Logger logger("input"); + +static std::unordered_map keycodes { + {"enter", GLFW_KEY_ENTER}, + {"space", GLFW_KEY_SPACE}, + {"backspace", GLFW_KEY_BACKSPACE}, + {"caps-lock", GLFW_KEY_CAPS_LOCK}, + {"escape", GLFW_KEY_ESCAPE}, + {"delete", GLFW_KEY_DELETE}, + {"home", GLFW_KEY_HOME}, + {"end", GLFW_KEY_END}, + {"tab", GLFW_KEY_TAB}, + {"insert", GLFW_KEY_INSERT}, + {"page-down", GLFW_KEY_PAGE_DOWN}, + {"page-up", GLFW_KEY_PAGE_UP}, + {"left-shift", GLFW_KEY_LEFT_SHIFT}, + {"right-shift", GLFW_KEY_RIGHT_SHIFT}, + {"left-ctrl", GLFW_KEY_LEFT_CONTROL}, + {"right-ctrl", GLFW_KEY_RIGHT_CONTROL}, + {"left-alt", GLFW_KEY_LEFT_ALT}, + {"right-alt", GLFW_KEY_RIGHT_ALT}, + {"left-super", GLFW_KEY_LEFT_SUPER}, + {"right-super", GLFW_KEY_RIGHT_SUPER}, + {"grave-accent", GLFW_KEY_GRAVE_ACCENT}, + {"left", GLFW_KEY_LEFT}, + {"right", GLFW_KEY_RIGHT}, + {"down", GLFW_KEY_DOWN}, + {"up", GLFW_KEY_UP}, + {"num-lock", GLFW_KEY_NUM_LOCK}, + {"print-screen", GLFW_KEY_PRINT_SCREEN}, + {"num-add", GLFW_KEY_KP_ADD}, + {"num-multiply", GLFW_KEY_KP_MULTIPLY}, + {"num-divide", GLFW_KEY_KP_DIVIDE}, + {"num-subtract", GLFW_KEY_KP_SUBTRACT}, + {"num-enter", GLFW_KEY_KP_ENTER}, + {"num-equal", GLFW_KEY_KP_EQUAL}, + {"num-decimal", GLFW_KEY_KP_DECIMAL}, +}; + +static std::unordered_map mousecodes { + {"left", GLFW_MOUSE_BUTTON_1}, + {"right", GLFW_MOUSE_BUTTON_2}, + {"middle", GLFW_MOUSE_BUTTON_3}, + {"side1", GLFW_MOUSE_BUTTON_4}, + {"side2", GLFW_MOUSE_BUTTON_5}, + {"side3", GLFW_MOUSE_BUTTON_6}, + {"side4", GLFW_MOUSE_BUTTON_7}, + {"side5", GLFW_MOUSE_BUTTON_8}, +}; + +static std::unordered_map keynames {}; +static std::unordered_map buttonsnames{}; + +std::string input_util::get_name(Mousecode code) { + const auto found = buttonsnames.find(static_cast(code)); + if (found == buttonsnames.end()) { + return "unknown"; + } + return found->second; +} + +std::string input_util::get_name(Keycode code) { + const auto found = keynames.find(static_cast(code)); + if (found == keynames.end()) { + return "unknown"; + } + return found->second; +} + +void Binding::reset(InputType type, int code) { + this->type = type; + this->code = code; +} + +void Binding::reset(Keycode code) { + reset(InputType::KEYBOARD, static_cast(code)); +} + +void Binding::reset(Mousecode code) { + reset(InputType::MOUSE, static_cast(code)); +} + +void input_util::initialize() { + for (int i = 0; i <= 9; i++) { + keycodes[std::to_string(i)] = GLFW_KEY_0 + i; + } + for (int i = 0; i < 25; i++) { + keycodes["f" + std::to_string(i + 1)] = GLFW_KEY_F1 + i; + } + for (char i = 'a'; i <= 'z'; i++) { + keycodes[std::string({i})] = GLFW_KEY_A - 'a' + i; + } + for (int i = 0; i <= 9; i++) { + keycodes["num-" + std::to_string(i)] = GLFW_KEY_KP_0 + i; + } + for (const auto& entry : keycodes) { + keynames[entry.second] = entry.first; + } + for (const auto& entry : mousecodes) { + buttonsnames[entry.second] = entry.first; + } +} + +Keycode input_util::keycode_from(const std::string& name) { + const auto& found = keycodes.find(name); + if (found == keycodes.end()) { + return Keycode::UNKNOWN; + } + return static_cast(found->second); +} + +Mousecode input_util::mousecode_from(const std::string& name) { + const auto& found = mousecodes.find(name); + if (found == mousecodes.end()) { + return Mousecode::UNKNOWN; + } + return static_cast(found->second); +} + +static const char* numpad_key_names[] { + "Num 0", + "Num 1", + "Num 2", + "Num 3", + "Num 4", + "Num 5", + "Num 6", + "Num 7", + "Num 8", + "Num 9", + "Num .", + "Num /", + "Num *", + "Num -", + "Num +", + "Num Enter", + "Num =", +}; + +std::string input_util::to_string(Keycode code) { + int icode_repr = static_cast(code); + if (icode_repr == -1) { + return "Unknown"; + } + if (icode_repr >= GLFW_KEY_KP_0 && icode_repr <= GLFW_KEY_KP_EQUAL) { + return numpad_key_names[icode_repr - GLFW_KEY_KP_0]; + } + const auto found = keynames.find(icode_repr); + if (found == keynames.end()) { + return "Unknown"; + } + std::string result; + bool capitalize = true; + for (char c : found->second) { + if (c == '-') { + result += ' '; + capitalize = true; + continue; + } + result += capitalize ? static_cast(std::toupper(c)) : c; + capitalize = false; + } + return result; +} + +std::string input_util::to_string(Mousecode code) { + switch (code) { + case Mousecode::BUTTON_1: + return "LMB"; + case Mousecode::BUTTON_2: + return "RMB"; + case Mousecode::BUTTON_3: + return "MMB"; + case Mousecode::BUTTON_4: + case Mousecode::BUTTON_5: + case Mousecode::BUTTON_6: + case Mousecode::BUTTON_7: + case Mousecode::BUTTON_8: + return "XButton " + std::to_string(static_cast(code) - + static_cast(Mousecode::BUTTON_3)); + default: + return "unknown button"; + } +} + +const Binding& Bindings::require(const std::string& name) const { + if (const auto found = get(name)) { + return *found; + } + throw std::runtime_error("binding '" + name + "' does not exist"); +} + +Binding& Bindings::require(const std::string& name) { + if (const auto found = get(name)) { + return *found; + } + throw std::runtime_error("binding '" + name + "' does not exist"); +} + +void Bindings::read(const dv::value& map, BindType bindType) { + for (auto& [sectionName, section] : map.asObject()) { + for (auto& [name, value] : section.asObject()) { + auto key = sectionName + "." + name; + auto [prefix, codename] = util::split_at(value.asString(), ':'); + InputType type; + int code; + if (prefix == "key") { + type = InputType::KEYBOARD; + code = static_cast(input_util::keycode_from(codename)); + } else if (prefix == "mouse") { + type = InputType::MOUSE; + code = static_cast(input_util::mousecode_from(codename)); + } else { + logger.error() + << "unknown input type: " << prefix << " (binding " + << util::quote(key) << ")"; + continue; + } + if (bindType == BindType::BIND) { + bind(key, type, code); + } else if (bindType == BindType::REBIND) { + rebind(key, type, code); + } + } + } +} + +#include "coders/toml.hpp" + +std::string Bindings::write() const { + auto obj = dv::object(); + for (auto& entry : bindings) { + const auto& binding = entry.second; + std::string value; + switch (binding.type) { + case InputType::KEYBOARD: + value = + "key:" + + input_util::get_name(static_cast(binding.code)); + break; + case InputType::MOUSE: + value = + "mouse:" + + input_util::get_name(static_cast(binding.code)); + break; + default: + throw std::runtime_error("unsupported control type"); + } + obj[entry.first] = std::move(value); + } + return toml::stringify(obj); +}