From 276786b8c5e1c189d50b200a02d939c1cff1e894 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 06:08:44 -0500 Subject: [PATCH 01/20] feat: add Singleton dependency and update compiler options --- CMakeLists.txt | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 24e737e7..37eb4a82 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -105,7 +105,14 @@ FetchContent_Declare( GIT_TAG v3.11.3 ) +FetchContent_Declare( + Singleton + GIT_REPOSITORY https://github.com/MasterLaplace/Singleton.git + GIT_TAG v1.0.2 +) + FetchContent_MakeAvailable(nlohmann_json) +FetchContent_MakeAvailable(Singleton) # Separate Build Artifacts: set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/build) @@ -122,9 +129,9 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) if (MSVC) add_compile_options(/W4) elseif (WIN32) - add_compile_options(-Wall -Wextra) + add_compile_options(-Wall -Wextra -ggdb -O0 -g3) else() - add_compile_options(-Wall -Wextra) + add_compile_options(-Wall -Wextra -ggdb -O0 -g3) endif() # Create the executable @@ -132,6 +139,7 @@ add_executable(flakkari ${SOURCES} ${HEADERS}) # Include Directories: target_include_directories(flakkari PRIVATE ${CMAKE_SOURCE_DIR}/Flakkari) +target_include_directories(flakkari PRIVATE ${singleton_SOURCE_DIR}) # Link Libraries: target_link_libraries(flakkari PRIVATE nlohmann_json::nlohmann_json) From 5aa05859a0c45da5e6ad4ed8d573537a65302114 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 06:12:43 -0500 Subject: [PATCH 02/20] feat: add compile-time configuration parameters file for Flakkari note: based on the Laplace-Project config file template --- Flakkari/config.h.in | 493 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 472 insertions(+), 21 deletions(-) diff --git a/Flakkari/config.h.in b/Flakkari/config.h.in index 7c3326ec..8264a92a 100644 --- a/Flakkari/config.h.in +++ b/Flakkari/config.h.in @@ -1,38 +1,489 @@ /************************************************************************** * Flakkari Library v0.3.0 * - * Flakkari Library is a C++ Library for Network. - * @file config.h - * @brief Flakkari Library configuration file. + * Flakkari is a server/client game library that is designed to be fast and easy + * to use. * - * Flakkari Library is under MIT License. - * https://opensource.org/licenses/MIT - * © 2023 @MasterLaplace + * This file is part of the Flakkari project that is under Anti-NN License. + * https://github.com/MasterLaplace/Anti-NN_LICENSE + * Copyright © 2024 by @MasterLaplace, All rights reserved. + * + * Flakkari is a free software: you can redistribute it and/or modify + * it under the terms of the Anti-NN License as published by MasterLaplace. + * See the Anti-NN License for more details. + * + * @file config.h.in + * @brief Compile-Time Configuration Parameters for Flakkari. + * + * @author @MasterLaplace * @version 0.3.0 * @date 2023-01-06 **************************************************************************/ -#ifndef VERSION_H_ - #define VERSION_H_ +// clang-format off +#ifndef FLAKKARI_CONFIG_H_ + #define FLAKKARI_CONFIG_H_ + +#ifdef __cplusplus + #include + #include + + #include + #include +#else + #include + #include +#endif + + +#ifndef CONFIG_UTILS + #define CONFIG_UTILS + +//////////////////////////////////////////////////////////// +// Define shared portable macros for various compilers +//////////////////////////////////////////////////////////// +#define NEED_COMMA struct _ +#define ATTRIBUTE(key) __attribute__((key)) +#define UNUSED_ATTRIBUTE ATTRIBUTE(unused) +#define UNUSED(x) (void)(x) + +//////////////////////////////////////////////////////////// +// Define portable NULL pointer using C++11 nullptr keyword +//////////////////////////////////////////////////////////// +#ifdef __cplusplus && __cplusplus >= 201103L +#elif !defined(NULL) + #define nullptr ((void*)0) +#else + #define nullptr NULL +#endif + +//////////////////////////////////////////////////////////// +// Define boolean type and values +//////////////////////////////////////////////////////////// +#if defined(__cplusplus) +#elif !defined(__bool_true_false_are_defined) + #define bool _Bool + #define true 1 + #define false 0 + #define __bool_true_false_are_defined 1 +#endif + +#if defined __GNUC__ && defined __GNUC_MINOR__ +# define __GNUC_PREREQ(maj, min) \ + ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) +#else +# define __GNUC_PREREQ(maj, min) 0 +#endif + +//////////////////////////////////////////////////////////// +// Define a portable way for packing structures +//////////////////////////////////////////////////////////// +/** Usage: + * @example + * PACKED(struct MyStruct + * { + * int a; + * char b; + * ... + * }); +\**********************************************************/ +#if defined(__GNUC__) || defined(__GNUG__) + #define PACKED( __Declaration__ ) __Declaration__ __attribute__((__packed__)) +#elif _MSC_VER + #define PACKED( __Declaration__ ) __pragma(pack(push, 1)) __Declaration__ __pragma(pack(pop)) +#else + #define PACKED( __Declaration__ ) __Declaration__ +#endif + +//////////////////////////////////////////////////////////// +// Helper macro to convert a macro to a string +//////////////////////////////////////////////////////////// +#define STRINGIFY(x) #x +#define TOSTRING(x) STRINGIFY(x) + +#endif /* !CONFIG_UTILS */ + + +#ifndef FLAKKARI_DISTRIBUTION_H_ + #define FLAKKARI_DISTRIBUTION_H_ + +//////////////////////////////////////////////////////////// +// Identify the Compiler +//////////////////////////////////////////////////////////// +#if defined(_MSC_VER) || defined(_MSVC_LANG) + #define FLAKKARI_COMPILER_MSVC + #define FLAKKARI_COMPILER_STRING "MSVC" +#elif defined(__GNUC__) || defined(__GNUG__) + #define FLAKKARI_COMPILER_GCC + #define FLAKKARI_COMPILER_STRING "GCC" +#elif defined(__clang__) || defined(__llvm__) + #define FLAKKARI_COMPILER_CLANG + #define FLAKKARI_COMPILER_STRING "Clang" +#elif defined(__MINGW32__) || defined(__MINGW64__) + #define FLAKKARI_COMPILER_MINGW + #define FLAKKARI_COMPILER_STRING "MinGW" +#elif defined(__CYGWIN__) + #define FLAKKARI_COMPILER_CYGWIN + #define FLAKKARI_COMPILER_STRING "Cygwin" +#else + #error [Config@Distribution]: This compiler is not supported by FLAKKARI library. +#endif + + +//////////////////////////////////////////////////////////// +// Identify the Operating System +//////////////////////////////////////////////////////////// +#if defined(_WIN32) || defined(__WIN32__) || defined(FLAKKARI_COMPILER_MINGW) || defined(FLAKKARI_COMPILER_CYGWIN) + + #define FLAKKARI_SYSTEM_WINDOWS + #define FLAKKARI_SYSTEM_STRING "Windows" + +// Android is based on the Linux FLAKKARI, so it has to appear before Linux +#elif defined(__ANDROID__) + + #define FLAKKARI_SYSTEM_ANDROID + #define FLAKKARI_SYSTEM_STRING "Android" + +#elif defined(linux) || defined(__linux) + + #define FLAKKARI_SYSTEM_LINUX + #define FLAKKARI_SYSTEM_STRING "Linux" + +#elif defined(__unix) || defined(__unix__) + + #define FLAKKARI_SYSTEM_UNIX + #define FLAKKARI_SYSTEM_STRING "Unix" + +#elif defined(__APPLE__) || defined(MACOSX) || defined(macintosh) || defined(Macintosh) + + #define FLAKKARI_SYSTEM_MACOS + #define FLAKKARI_SYSTEM_STRING "MacOS" + +#elif defined(__FreeBSD__) || defined(__FreeBSD_FLAKKARI__) + + #define FLAKKARI_SYSTEM_FREEBSD + #define FLAKKARI_SYSTEM_STRING "FreeBSD" + +#elif defined(LAPLACE_KERNEL_PANIC) + + #define FLAKKARI_SYSTEM_KERNEL + #define FLAKKARI_SYSTEM_STRING "Laplace Kernel" + +#else + #error [Config@Distribution]: This operating system is not supported by FLAKKARI library. +#endif + +#ifdef __cplusplus + #define FLAKKARI_EXTERN_C extern "C" + + #if __cplusplus >= 202203L + #define FLAKKARI_CPP23(_) _ + #define FLAKKARI_CPP20(_) _ + #define FLAKKARI_CPP17(_) _ + #define FLAKKARI_CPP14(_) _ + #define FLAKKARI_CPP11(_) _ + #define FLAKKARI_CPP99(_) _ + #elif __cplusplus >= 202002L + #define FLAKKARI_CPP23(_) + #define FLAKKARI_CPP20(_) _ + #define FLAKKARI_CPP17(_) _ + #define FLAKKARI_CPP14(_) _ + #define FLAKKARI_CPP11(_) _ + #define FLAKKARI_CPP99(_) _ + #elif __cplusplus >= 201703L + #define FLAKKARI_CPP23(_) + #define FLAKKARI_CPP20(_) + #define FLAKKARI_CPP17(_) _ + #define FLAKKARI_CPP14(_) _ + #define FLAKKARI_CPP11(_) _ + #define FLAKKARI_CPP99(_) _ + #elif __cplusplus >= 201402L + #define FLAKKARI_CPP23(_) + #define FLAKKARI_CPP20(_) + #define FLAKKARI_CPP17(_) + #define FLAKKARI_CPP14(_) _ + #define FLAKKARI_CPP11(_) _ + #define FLAKKARI_CPP99(_) _ + #elif __cplusplus >= 201103L + #define FLAKKARI_CPP23(_) + #define FLAKKARI_CPP20(_) + #define FLAKKARI_CPP17(_) + #define FLAKKARI_CPP14(_) + #define FLAKKARI_CPP11(_) _ + #define FLAKKARI_CPP99(_) _ + #elif __cplusplus >= 199711L + #define FLAKKARI_CPP23(_) + #define FLAKKARI_CPP20(_) + #define FLAKKARI_CPP17(_) + #define FLAKKARI_CPP14(_) + #define FLAKKARI_CPP11(_) + #define FLAKKARI_CPP99(_) _ + #else + #define FLAKKARI_CPP23(_) + #define FLAKKARI_CPP20(_) + #define FLAKKARI_CPP17(_) + #define FLAKKARI_CPP14(_) + #define FLAKKARI_CPP11(_) + #define FLAKKARI_CPP99(_) + #endif + + //////////////////////////////////////////////////////////// + // Define a macro to handle cpp features compatibility + //////////////////////////////////////////////////////////// + /** Usage: + * @example + * void func() FLAKKARI_CPP14([[deprecated]]); + * + * @example + * void func() FLAKKARI_CPP([[deprecated]], 14); + \**********************************************************/ + #define FLAKKARI_CPP(_, version) FLAKKARI_CPP##version(_) + +#else + #define FLAKKARI_EXTERN_C extern + + #define FLAKKARI_CPP23(_) + #define FLAKKARI_CPP20(_) + #define FLAKKARI_CPP17(_) + #define FLAKKARI_CPP14(_) + #define FLAKKARI_CPP11(_) + #define FLAKKARI_CPP99(_) + #define FLAKKARI_CPP(_, version) +#endif + +//////////////////////////////////////////////////////////// +// Define helpers to create portable import / export macros for each module +//////////////////////////////////////////////////////////// +#if defined(FLAKKARI_SYSTEM_WINDOWS) + + // Windows compilers need specific (and different) keywords for export and import + #define FLAKKARI_API_EXPORT extern "C" __declspec(dllexport) + #define FLAKKARI_API_IMPORT FLAKKARI_EXTERN_C __declspec(dllimport) + + // For Visual C++ compilers, we also need to turn off this annoying C4251 warning + #ifdef _MSC_VER + + #pragma warning(disable : 4251) + + #endif + +#else // Linux, FreeBSD, Mac OS X + + #if __GNUC__ >= 4 + + // GCC 4 has special keywords for showing/hidding symbols, + // the same keyword is used for both importing and exporting + #define FLAKKARI_API_EXPORT extern "C" __attribute__ ((__visibility__ ("default"))) + #define FLAKKARI_API_IMPORT FLAKKARI_EXTERN_C __attribute__ ((__visibility__ ("default"))) + + #else + + // GCC < 4 has no mechanism to explicitely hide symbols, everything's exported + #define FLAKKARI_API_EXPORT extern "C" + #define FLAKKARI_API_IMPORT FLAKKARI_EXTERN_C + + #endif + +#endif + + +#ifdef FLAKKARI_SYSTEM_WINDOWS + + // Windows compilers use a different name for the main function + #define FLAKKARI_GUI_MAIN(hInstance, hPrevInstance, lpCmdLine, nCmdShow) WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) + #define FLAKKARI_MAIN(ac, av, env) main(int ac, char *av[], char *env[]) + +#elif defined(FLAKKARI_SYSTEM_ANDROID) + + // Android doesn't need a main function + #define FLAKKARI_GUI_MAIN(app) android_main(struct android_app* app) + #define FLAKKARI_MAIN + +#elif defined(FLAKKARI_SYSTEM_MACOS) + + // On MacOS X, we use a Unix main function + #define FLAKKARI_MAIN(ac, av, env, apple) main(int ac, char *av[], char *env[], char *apple[]) + +#else + + // Other platforms should use the standard main function + #define FLAKKARI_MAIN(ac, av, env) main(int ac, char *av[], char *env[]) +#endif + +//////////////////////////////////////////////////////////// +// Define a portable debug macro +//////////////////////////////////////////////////////////// +#if (defined(_DEBUG) || defined(DEBUG)) && !defined(NDEBUG) + + #define FLAKKARI_DEBUG + #define FLAKKARI_DEBUG_STRING "Debug" + +#else + #define FLAKKARI_DEBUG_STRING "Release" +#endif + +//////////////////////////////////////////////////////////// +// Define a portable way to declare a function as deprecated +//////////////////////////////////////////////////////////// +/** Usage: + * @example "for functions" + * FLAKKARI_DEPRECATED void func(); + * @example "for structs" + * struct FLAKKARI_DEPRECATED MyStruct { ... }; + * @example "for enums" + * enum FLAKKARI_DEPRECATED MyEnum { ... }; + * enum MyEnum { + * MyEnum1 = 0, + * MyEnum2 FLAKKARI_DEPRECATED, + * MyEnum3 + * }; + * @example "for classes" + * class FLAKKARI_DEPRECATED MyClass { ... }; +\**********************************************************/ +#ifdef FLAKKARI_DISABLE_DEPRECATION + + #define FLAKKARI_DEPRECATED + #define FLAKKARI_DEPRECATED_MSG(message) + #define FLAKKARI_DEPRECATED_VMSG(version, message) + +#elif defined(__cplusplus) && (__cplusplus >= 201402) + + #define FLAKKARI_DEPRECATED [[deprecated]] + + #if (__cplusplus >= 201402) && (__cplusplus < 201703) + + #define FLAKKARI_DEPRECATED_MSG(message) [[deprecated(message)]] + #define FLAKKARI_DEPRECATED_VMSG(version, message) \ + [[deprecated("since " # version ". " message)]] + + #else + #define FLAKKARI_DEPRECATED_MSG(message) [[deprecated]] + #define FLAKKARI_DEPRECATED_VMSG(version, message) [[deprecated]] + #endif + +#elif defined(FLAKKARI_COMPILER_MSVC) && (_MSC_VER >= 1400) + + #define FLAKKARI_DEPRECATED __declspec(deprecated) + + #if (_MSC_VER >= 1900) + + #define FLAKKARI_DEPRECATED_MSG(message) __declspec(deprecated(message)) + #define FLAKKARI_DEPRECATED_VMSG(version, message) \ + __declspec(deprecated("since " # version ". " message)) + + #else + #define FLAKKARI_DEPRECATED_MSG(message) __declspec(deprecated) + #define FLAKKARI_DEPRECATED_VMSG(version, message) __declspec(deprecated) + #endif + +#elif defined(FLAKKARI_COMPILER_CLANG) && defined(__has_feature) + + #define FLAKKARI_DEPRECATED __attribute__((deprecated)) + + #if __has_feature(attribute_deprecated_with_message) + + #define FLAKKARI_DEPRECATED_MSG(message) __attribute__((deprecated(message))) + #define FLAKKARI_DEPRECATED_VMSG(version, message) \ + __attribute__((deprecated("since " # version ". " message))) + + #else + #define FLAKKARI_DEPRECATED_MSG(message) __attribute__((deprecated)) + #define FLAKKARI_DEPRECATED_VMSG(version, message) __attribute__((deprecated)) + #endif + +#elif defined(FLAKKARI_COMPILER_GCC) && defined(__GNUC__) && __GNUC_PREREQ(4, 5) + + #define FLAKKARI_DEPRECATED __attribute__((deprecated)) + + #if defined(FLAKKARI_COMPILER_GCC) && defined(__GNUC__) && __GNUC_PREREQ(4, 9) + + #define FLAKKARI_DEPRECATED_MSG(message) __attribute__((deprecated(message))) + #define FLAKKARI_DEPRECATED_VMSG(version, message) \ + __attribute__((deprecated("since " # version ". " message))) + + #else + #define FLAKKARI_DEPRECATED_MSG(message) __attribute__((deprecated)) + #define FLAKKARI_DEPRECATED_VMSG(version, message) __attribute__((deprecated)) + #endif + +#else + + #pragma message("WARNING: FLAKKARI_DEPRECATED not supported on this compiler") + #define FLAKKARI_DEPRECATED + #define FLAKKARI_DEPRECATED_MSG(message) + #define FLAKKARI_DEPRECATED_VMSG(version, message) +#endif + +#endif /* !FLAKKARI_DISTRIBUTION_H_ */ + + +#ifndef FLAKKARI_VERSION_H_ + #define FLAKKARI_VERSION_H_ //////////////////////////////////////////////////////////// -// Define the Flakkari version +// Define the FLAKKARI version //////////////////////////////////////////////////////////// -#define PROJECT_VERSION_MAJOR 0 -#define PROJECT_VERSION_MINOR 2 -#define PROJECT_VERSION_PATCH 0 -#define PROJECT_VERSION_TWEAK 0 +#ifdef FLAG_VERSION_MAJOR + #define FLAKKARI_VERSION_MAJOR FLAG_VERSION_MAJOR +#else + #define FLAKKARI_VERSION_MAJOR 0 +#endif +#ifdef FLAG_VERSION_MINOR + #define FLAKKARI_VERSION_MINOR FLAG_VERSION_MINOR +#else + #define FLAKKARI_VERSION_MINOR 2 +#endif + +#ifdef FLAG_VERSION_PATCH + #define FLAKKARI_VERSION_PATCH FLAG_VERSION_PATCH +#else + #define FLAKKARI_VERSION_PATCH 0 +#endif + +#ifdef FLAG_VERSION_TWEAK + #define FLAKKARI_VERSION_TWEAK FLAG_VERSION_TWEAK +#else + #define FLAKKARI_VERSION_TWEAK 0 +#endif + +//////////////////////////////////////////////////////////// +// Define the FLAKKARI version number //////////////////////////////////////////////////////////// -// Define the Flakkari version string +#define FLAKKARI_VERSION \ + (FLAKKARI_VERSION_MAJOR * 1000000 + \ + FLAKKARI_VERSION_MINOR * 10000 + \ + FLAKKARI_VERSION_PATCH * 100 + \ + FLAKKARI_VERSION_TWEAK) + +#define FLAKKARI_PREREQ_VERSION(maj, min, pat) (FLAKKARI_VERSION >= (maj * 1000000 + min * 10000 + pat * 100)) + //////////////////////////////////////////////////////////// -#define STRINGIFY(x) STRINGIFY_(x) -#define STRINGIFY_(x) #x +// Define the FLAKKARI version concatenated +//////////////////////////////////////////////////////////// +#define FLAKKARI_VERSION_CCT FLAKKARI_VERSION_MAJOR##_##FLAKKARI_VERSION_MINOR##_##FLAKKARI_VERSION_PATCH##_##FLAKKARI_VERSION_TWEAK + +//////////////////////////////////////////////////////////// +// Define the FLAKKARI version string +//////////////////////////////////////////////////////////// #define FLAKKARI_VERSION_STRING \ - STRINGIFY(PROJECT_VERSION_MAJOR) "." \ - STRINGIFY(PROJECT_VERSION_MINOR) "." \ - STRINGIFY(PROJECT_VERSION_PATCH) "." \ - STRINGIFY(PROJECT_VERSION_TWEAK) + TOSTRING(FLAKKARI_VERSION_MAJOR) "." \ + TOSTRING(FLAKKARI_VERSION_MINOR) "." \ + TOSTRING(FLAKKARI_VERSION_PATCH) "." \ + TOSTRING(FLAKKARI_VERSION_TWEAK) + +#endif /* !FLAKKARI_VERSION_H_ */ + + +//////////////////////////////////////////////////////////// +// Compile-Time Configuration Parameters +//////////////////////////////////////////////////////////// +#define FLAKKARI_CONFIG_STRING \ + "FLAKKARI_VERSION=" FLAKKARI_VERSION_STRING "\n" \ + "FLAKKARI_SYSTEM=" FLAKKARI_SYSTEM_STRING "\n" \ + "FLAKKARI_COMPILER=" FLAKKARI_COMPILER_STRING "\n" \ + "FLAKKARI_DEBUG=" FLAKKARI_DEBUG_STRING "\n" -#endif /* !VERSION_H_ */ +#endif /* !FLAKKARI_CONFIG_H_ */ +// clang-format on From 71ae9852f90c82c3aef5bd28f57e148d08f5461b Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 06:22:43 -0500 Subject: [PATCH 03/20] refactor: update ClientManager to use Singleton pattern and improve instance management --- Flakkari/Server/Client/ClientManager.cpp | 139 ++++++--------- Flakkari/Server/Client/ClientManager.hpp | 218 +++++++++++------------ Flakkari/Server/Game/Game.cpp | 12 +- Flakkari/Server/UDPServer.cpp | 16 +- 4 files changed, 171 insertions(+), 214 deletions(-) diff --git a/Flakkari/Server/Client/ClientManager.cpp b/Flakkari/Server/Client/ClientManager.cpp index 6c201918..cf9756fe 100644 --- a/Flakkari/Server/Client/ClientManager.cpp +++ b/Flakkari/Server/Client/ClientManager.cpp @@ -14,31 +14,15 @@ namespace Flakkari { -std::shared_ptr ClientManager::_instance = nullptr; -std::mutex ClientManager::_mutex; - -std::shared_ptr ClientManager::getInstance() -{ - std::lock_guard lock(_mutex); - if (!_instance) - _instance = std::make_shared(); - return _instance; -} - -void ClientManager::setSocket(std::shared_ptr socket) { getInstance()->_socket = socket; } - void ClientManager::addClient(std::shared_ptr client, Network::Buffer &buffer) { - auto &clients = getInstance()->_clients; - - if (ClientManager::isBanned(client)) - { + if (this->isBanned(client)) { FLAKKARI_LOG_LOG("Client " + client->toString().value_or("Unknown") + " tried to connect but is banned"); return; } - if (clients.find(client->toString().value_or("")) != clients.end()) - return clients[client->toString().value_or("")]->keepAlive(), void(); + if (_clients.find(client->toString().value_or("")) != _clients.end()) + return _clients[client->toString().value_or("")]->keepAlive(), void(); Protocol::Packet packet; if (!packet.deserialize(buffer)) @@ -54,119 +38,99 @@ void ClientManager::addClient(std::shared_ptr client, Network: } std::string name = packet.extractString(); - clients[client->toString().value_or("")] = std::make_shared(client, name); + _clients[client->toString().value_or("")] = std::make_shared(client, name); FLAKKARI_LOG_LOG("Client " + client->toString().value_or("Unknown") + " connected"); - GameManager::addClientToGame(name, clients[client->toString().value_or("")]); + GameManager::GetInstance().addClientToGame(name, _clients[client->toString().value_or("")]); + GameManager::UnlockInstance(); } void ClientManager::removeClient(std::shared_ptr client) { - auto &clients = getInstance()->_clients; - - if (clients.find(client->toString().value_or("")) == clients.end()) + if (_clients.find(client->toString().value_or("")) == _clients.end()) return; - auto _client = clients[client->toString().value_or("")]; + auto _client = _clients[client->toString().value_or("")]; - GameManager::removeClientFromGame(_client->getGameName(), _client); - clients.erase(client->toString().value_or("")); + GameManager::GetInstance().removeClientFromGame(_client->getGameName(), _client); + GameManager::UnlockInstance(); + _clients.erase(client->toString().value_or("")); } void ClientManager::banClient(std::shared_ptr client) { - auto &clients = getInstance()->_clients; - auto &bannedClients = getInstance()->_bannedClients; - - if (clients.find(client->toString().value_or("")) == clients.end()) + if (_clients.find(client->toString().value_or("")) == _clients.end()) return; - bannedClients.push_back(client->getIp().value()); + _bannedClients.push_back(client->getIp().value()); FLAKKARI_LOG_LOG("Client " + client->toString().value_or("Unknown") + " banned"); - auto _client = clients[client->toString().value_or("")]; - GameManager::removeClientFromGame(_client->getGameName(), _client); - clients.erase(client->toString().value_or("")); + auto _client = _clients[client->toString().value_or("")]; + GameManager::GetInstance().removeClientFromGame(_client->getGameName(), _client); + GameManager::UnlockInstance(); + _clients.erase(client->toString().value_or("")); } bool ClientManager::isBanned(std::shared_ptr client) { - auto &bannedClients = getInstance()->_bannedClients; - - return std::find(bannedClients.begin(), bannedClients.end(), client->getIp().value_or("")) != bannedClients.end(); + return std::find(_bannedClients.begin(), _bannedClients.end(), client->getIp().value_or("")) != _bannedClients.end(); } void ClientManager::checkInactiveClients() { - auto &clients = getInstance()->_clients; - - for (auto it = clients.begin(); it != clients.end();) - { - if (!it->second->isConnected()) - { + for (auto it = _clients.begin(); it != _clients.end();) { + if (!it->second->isConnected()) { FLAKKARI_LOG_LOG("Client " + it->first + " disconnected"); - it = clients.erase(it); - } - else - { + it = _clients.erase(it); + } else { ++it; } } } -void ClientManager::sendPacketToClient(std::shared_ptr client, const Network::Buffer &packet) -{ - auto socket = getInstance()->_socket; - - std::thread([socket, client, packet] { socket->sendTo(client, packet); }).detach(); +void ClientManager::sendPacketToClient ( + std::shared_ptr client, const Network::Buffer &packet +) { + std::thread([this, client, packet] { + _socket->sendTo(client, packet); + }).detach(); } void ClientManager::sendPacketToAllClients(const Network::Buffer &packet) { - auto instance = getInstance(); - auto clients = instance->_clients; - auto socket = instance->_socket; - - for (auto &tmp_client : clients) - { + for (auto &tmp_client : _clients) { if (tmp_client.second->isConnected()) - socket->sendTo(tmp_client.second->getAddress(), packet); + _socket->sendTo(tmp_client.second->getAddress(), packet); } } -void ClientManager::sendPacketToAllClientsExcept(std::shared_ptr client, - const Network::Buffer &packet) -{ - auto instance = getInstance(); - auto clients = instance->_clients; - auto socket = instance->_socket; +void ClientManager::sendPacketToAllClientsExcept ( + std::shared_ptr client, const Network::Buffer &packet +) { auto clientKey = client->toString().value_or(""); - for (auto &tmp_client : clients) - { + for (auto &tmp_client : _clients) { auto tmp_clientKey = tmp_client.second->getName().value_or(""); if (tmp_client.second->isConnected() && tmp_clientKey != clientKey) - socket->sendTo(tmp_client.second->getAddress(), packet); + _socket->sendTo(tmp_client.second->getAddress(), packet); } } -void ClientManager::receivePacketFromClient(std::shared_ptr client, const Network::Buffer &buffer) -{ - auto &clients = getInstance()->_clients; - auto &bannedClients = getInstance()->_bannedClients; +void ClientManager::receivePacketFromClient ( + std::shared_ptr client, const Network::Buffer &buffer +) { auto clientName = client->toString().value_or(""); auto ip = client->getIp().value_or(""); - if (std::find(bannedClients.begin(), bannedClients.end(), ip) != bannedClients.end()) - { + if (std::find(_bannedClients.begin(), _bannedClients.end(), ip) != _bannedClients.end()) { FLAKKARI_LOG_LOG("Client " + clientName + " tried to connect but is banned"); return; } - if (clients.find(clientName) == clients.end()) + if (_clients.find(clientName) == _clients.end()) return; - auto &tmp_client = clients[clientName]; + auto &tmp_client = _clients[clientName]; Protocol::Packet packet; if (packet.deserialize(buffer)) @@ -183,22 +147,23 @@ void ClientManager::receivePacketFromClient(std::shared_ptr cl FLAKKARI_LOG_LOG("Client " + clientName + " has been banned"); - bannedClients.push_back(ip); + _bannedClients.push_back(ip); FLAKKARI_LOG_LOG("Client " + clientName + " banned"); - GameManager::removeClientFromGame(tmp_client->getGameName(), tmp_client); - clients.erase(clientName); + GameManager::GetInstance().removeClientFromGame(tmp_client->getGameName(), tmp_client); + GameManager::UnlockInstance(); + _clients.erase(clientName); } -std::shared_ptr ClientManager::getClient(std::shared_ptr client) -{ - return getInstance()->_clients[client->toString().value_or("")]; +std::shared_ptr ClientManager::getClient(std::shared_ptr client) { + return _clients[client->toString().value_or("")]; } -std::shared_ptr ClientManager::getClient(std::string id) { return getInstance()->_clients[id]; } +std::shared_ptr ClientManager::getClient(std::string id) { + return _clients[id]; +} -std::shared_ptr ClientManager::getAddress(std::string id) -{ - return getInstance()->_clients[id]->getAddress(); +std::shared_ptr ClientManager::getAddress(std::string id) { + return _clients[id]->getAddress(); } std::shared_ptr ClientManager::operator[](std::string id) { return _clients[id]; } diff --git a/Flakkari/Server/Client/ClientManager.hpp b/Flakkari/Server/Client/ClientManager.hpp index ff2d8cf2..ff0791d8 100644 --- a/Flakkari/Server/Client/ClientManager.hpp +++ b/Flakkari/Server/Client/ClientManager.hpp @@ -20,6 +20,9 @@ #include "Network/Network.hpp" #include "Network/Serializer.hpp" +#define SINGLETON_IMPLEMENTATION +#include +#include #include #include #include @@ -46,29 +49,21 @@ namespace Flakkari { * Flakkari::ClientManager::checkInactiveClients(); * @endcode */ -class ClientManager { +class ClientManager : public Singleton { private: - static std::shared_ptr _instance; - static std::mutex _mutex; - - using id_t = short; + std::unordered_map> _clients; + std::vector _bannedClients; + std::shared_ptr _socket; - public: - std::unordered_map> _clients; - std::vector _bannedClients; - std::shared_ptr _socket; + using id_t = short; public: - ClientManager(const ClientManager &) = delete; - ClientManager(const std::shared_ptr &) = delete; - void operator=(const ClientManager &) = delete; - void operator=(const std::shared_ptr &) = delete; - - /** - * @brief Construct a new ClientManager object - * - */ - ClientManager() = default; + /** + * @brief Construct a new ClientManager object + * + * @param socket The server's socket + */ + explicit ClientManager(std::shared_ptr socket) : _socket(socket) {} /** * @brief Destroy the ClientManager object @@ -76,103 +71,94 @@ class ClientManager { */ ~ClientManager() = default; - static void setSocket(std::shared_ptr socket); - - /** - * @brief Get the instance of the client manager - * - * @return std::shared_ptr The instance of the client manager - */ - static std::shared_ptr getInstance(); - - /** - * @brief Add a client to the client manager or update the last activity of the client - * - * @param client The client's address - */ - static void addClient(std::shared_ptr client, Network::Buffer &buffer); - - /** - * @brief Remove a client from the client manager - * - * @param client The client's address - */ - static void removeClient(std::shared_ptr client); - - /** - * @brief Ban a client from the server - * - * @param client The client's address - */ - static void banClient(std::shared_ptr client); - - [[nodiscard]] static bool isBanned(std::shared_ptr client); - - /** - * @brief Check if the clients are still connected to the server - * and remove the inactive clients from the client manager - * (inactive clients are clients that didn't send any packet to the server - * for more than 5 seconds) - * - * @see Client::isConnected() - * @see Client::keepAlive() - */ - static void checkInactiveClients(); - - /** - * @brief Send a packet to a client - * - * @param client The client's address - * @param packet The packet to send - */ - static void sendPacketToClient(std::shared_ptr client, const Network::Buffer &packet); - - /** - * @brief Send a packet to all clients - * - * @param packet The packet to send - */ - static void sendPacketToAllClients(const Network::Buffer &packet); - - /** - * @brief Send a packet to all clients except one - * - * @param client The client's address - * @param packet The packet to send - */ - static void sendPacketToAllClientsExcept(std::shared_ptr client, const Network::Buffer &packet); - - /** - * @brief Receive a packet from a client - * - * @param client The client's address - * @param packet The packet received - */ - static void receivePacketFromClient(std::shared_ptr client, const Network::Buffer &packet); - - /** - * @brief Get the Client object - * - * @param client The client's address - * @return std::shared_ptr The client object - */ - static std::shared_ptr getClient(std::shared_ptr client); - - /** - * @brief Get the Client object - * - * @param id The client's id - * @return std::shared_ptr The client object - */ - static std::shared_ptr getClient(std::string id); - - /** - * @brief Get the Address object - * - * @param id The client's id - * @return std::shared_ptr The client's address - */ - static std::shared_ptr getAddress(std::string id); + /** + * @brief Add a client to the client manager or update the last activity of the client + * + * @param client The client's address + */ + void addClient(std::shared_ptr client, Network::Buffer &buffer); + + /** + * @brief Remove a client from the client manager + * + * @param client The client's address + */ + void removeClient(std::shared_ptr client); + + /** + * @brief Ban a client from the server + * + * @param client The client's address + */ + void banClient(std::shared_ptr client); + + [[nodiscard]] bool isBanned(std::shared_ptr client); + + /** + * @brief Check if the clients are still connected to the server + * and remove the inactive clients from the client manager + * (inactive clients are clients that didn't send any packet to the server + * for more than 5 seconds) + * + * @see Client::isConnected() + * @see Client::keepAlive() + */ + void checkInactiveClients(); + + /** + * @brief Send a packet to a client + * + * @param client The client's address + * @param packet The packet to send + */ + void sendPacketToClient(std::shared_ptr client, const Network::Buffer &packet); + + /** + * @brief Send a packet to all clients + * + * @param packet The packet to send + */ + void sendPacketToAllClients(const Network::Buffer &packet); + + /** + * @brief Send a packet to all clients except one + * + * @param client The client's address + * @param packet The packet to send + */ + void sendPacketToAllClientsExcept(std::shared_ptr client, const Network::Buffer &packet); + + /** + * @brief Receive a packet from a client + * + * @param client The client's address + * @param packet The packet received + */ + void receivePacketFromClient(std::shared_ptr client, const Network::Buffer &packet); + + /** + * @brief Get the Client object + * + * @param client The client's address + * @return std::shared_ptr The client object + */ + std::shared_ptr getClient(std::shared_ptr client); + + /** + * @brief Get the Client object + * + * @param id The client's id + * @return std::shared_ptr The client object + */ + std::shared_ptr getClient(std::string id); + + /** + * @brief Get the Address object + * + * @param id The client's id + * @return std::shared_ptr The client's address + */ + std::shared_ptr getAddress(std::string id); /** * @brief Get the client object from the client manager diff --git a/Flakkari/Server/Game/Game.cpp b/Flakkari/Server/Game/Game.cpp index f9f2af4a..b79b8465 100644 --- a/Flakkari/Server/Game/Game.cpp +++ b/Flakkari/Server/Game/Game.cpp @@ -34,7 +34,8 @@ void Game::sendAllEntities(const std::string &sceneName, std::shared_ptr packet.injectString(sceneName); Protocol::PacketFactory::addComponentsToPacketByEntity(packet, registry, i); - ClientManager::sendPacketToClient(player->getAddress(), packet.serialize()); + ClientManager::GetInstance().sendPacketToClient(player->getAddress(), packet.serialize()); + ClientManager::UnlockInstance(); } } @@ -224,7 +225,8 @@ void Game::sendOnSameScene(const std::string &sceneName, const Network::Buffer & if (player->getSceneName() != sceneName) continue; - ClientManager::sendPacketToClient(player->getAddress(), message); + ClientManager::GetInstance().sendPacketToClient(player->getAddress(), message); + ClientManager::UnlockInstance(); } } @@ -242,7 +244,8 @@ void Game::sendOnSameSceneExcept(const std::string &sceneName, const Network::Bu if (player == except) continue; - ClientManager::sendPacketToClient(player->getAddress(), message); + ClientManager::GetInstance().sendPacketToClient(player->getAddress(), message); + ClientManager::UnlockInstance(); } } @@ -470,7 +473,8 @@ bool Game::addPlayer(std::shared_ptr player) packet.injectString(sceneGame); packet.injectString(player->getName().value_or("")); packet.injectString(p_Template); - ClientManager::sendPacketToClient(address, packet.serialize()); + ClientManager::GetInstance().sendPacketToClient(address, packet.serialize()); + ClientManager::DestroyInstance(); Protocol::Packet packet2; packet2.header._commandId = Protocol::CommandId::REQ_ENTITY_SPAWN; diff --git a/Flakkari/Server/UDPServer.cpp b/Flakkari/Server/UDPServer.cpp index 6719c658..8582a32f 100644 --- a/Flakkari/Server/UDPServer.cpp +++ b/Flakkari/Server/UDPServer.cpp @@ -25,12 +25,12 @@ UDPServer::UDPServer(std::string ip, unsigned short port) _io->addSocket((int) _socket->getSocket()); _io->addSocket(STDIN_FILENO); - ClientManager::setSocket(_socket); - GameManager::getInstance(); + ClientManager::CreateInstance(_socket); } UDPServer::~UDPServer() { + ClientManager::DestroyInstance(); Network::cleanup(); FLAKKARI_LOG_INFO("UDPServer is now stopped"); } @@ -40,7 +40,8 @@ bool UDPServer::handleTimeout(int event) if (event != 0) return false; FLAKKARI_LOG_DEBUG(XSTR(IO_SELECTED) " timed out"); - ClientManager::checkInactiveClients(); + ClientManager::GetInstance().checkInactiveClients(); + ClientManager::UnlockInstance(); return true; } @@ -57,10 +58,11 @@ bool UDPServer::handleInput(int fd) void UDPServer::handlePacket() { auto packet = _socket->receiveFrom(); - ClientManager::addClient(packet->first, packet->second); - ClientManager::checkInactiveClients(); - - ClientManager::receivePacketFromClient(packet->first, packet->second); + auto instance = ClientManager::GetInstance(); + instance.addClient(packet->first, packet->second); + instance.checkInactiveClients(); + instance.receivePacketFromClient(packet->first, packet->second); + ClientManager::UnlockInstance(); } void UDPServer::run() From 571959c36104a65a884daf49f4ee3ff8507386ed Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 7 Nov 2024 11:23:04 +0000 Subject: [PATCH 04/20] style: apply linter --- Flakkari/Server/Client/ClientManager.cpp | 56 +++---- Flakkari/Server/Client/ClientManager.hpp | 197 +++++++++++------------ 2 files changed, 127 insertions(+), 126 deletions(-) diff --git a/Flakkari/Server/Client/ClientManager.cpp b/Flakkari/Server/Client/ClientManager.cpp index cf9756fe..192d371d 100644 --- a/Flakkari/Server/Client/ClientManager.cpp +++ b/Flakkari/Server/Client/ClientManager.cpp @@ -16,7 +16,8 @@ namespace Flakkari { void ClientManager::addClient(std::shared_ptr client, Network::Buffer &buffer) { - if (this->isBanned(client)) { + if (this->isBanned(client)) + { FLAKKARI_LOG_LOG("Client " + client->toString().value_or("Unknown") + " tried to connect but is banned"); return; } @@ -73,43 +74,47 @@ void ClientManager::banClient(std::shared_ptr client) bool ClientManager::isBanned(std::shared_ptr client) { - return std::find(_bannedClients.begin(), _bannedClients.end(), client->getIp().value_or("")) != _bannedClients.end(); + return std::find(_bannedClients.begin(), _bannedClients.end(), client->getIp().value_or("")) != + _bannedClients.end(); } void ClientManager::checkInactiveClients() { - for (auto it = _clients.begin(); it != _clients.end();) { - if (!it->second->isConnected()) { + for (auto it = _clients.begin(); it != _clients.end();) + { + if (!it->second->isConnected()) + { FLAKKARI_LOG_LOG("Client " + it->first + " disconnected"); it = _clients.erase(it); - } else { + } + else + { ++it; } } } -void ClientManager::sendPacketToClient ( - std::shared_ptr client, const Network::Buffer &packet -) { - std::thread([this, client, packet] { - _socket->sendTo(client, packet); - }).detach(); +void ClientManager::sendPacketToClient(std::shared_ptr client, const Network::Buffer &packet) +{ + std::thread([this, client, packet] { _socket->sendTo(client, packet); }).detach(); } void ClientManager::sendPacketToAllClients(const Network::Buffer &packet) { - for (auto &tmp_client : _clients) { + for (auto &tmp_client : _clients) + { if (tmp_client.second->isConnected()) _socket->sendTo(tmp_client.second->getAddress(), packet); } } -void ClientManager::sendPacketToAllClientsExcept ( - std::shared_ptr client, const Network::Buffer &packet -) { +void ClientManager::sendPacketToAllClientsExcept(std::shared_ptr client, + const Network::Buffer &packet) +{ auto clientKey = client->toString().value_or(""); - for (auto &tmp_client : _clients) { + for (auto &tmp_client : _clients) + { auto tmp_clientKey = tmp_client.second->getName().value_or(""); if (tmp_client.second->isConnected() && tmp_clientKey != clientKey) @@ -117,13 +122,13 @@ void ClientManager::sendPacketToAllClientsExcept ( } } -void ClientManager::receivePacketFromClient ( - std::shared_ptr client, const Network::Buffer &buffer -) { +void ClientManager::receivePacketFromClient(std::shared_ptr client, const Network::Buffer &buffer) +{ auto clientName = client->toString().value_or(""); auto ip = client->getIp().value_or(""); - if (std::find(_bannedClients.begin(), _bannedClients.end(), ip) != _bannedClients.end()) { + if (std::find(_bannedClients.begin(), _bannedClients.end(), ip) != _bannedClients.end()) + { FLAKKARI_LOG_LOG("Client " + clientName + " tried to connect but is banned"); return; } @@ -154,17 +159,14 @@ void ClientManager::receivePacketFromClient ( _clients.erase(clientName); } -std::shared_ptr ClientManager::getClient(std::shared_ptr client) { +std::shared_ptr ClientManager::getClient(std::shared_ptr client) +{ return _clients[client->toString().value_or("")]; } -std::shared_ptr ClientManager::getClient(std::string id) { - return _clients[id]; -} +std::shared_ptr ClientManager::getClient(std::string id) { return _clients[id]; } -std::shared_ptr ClientManager::getAddress(std::string id) { - return _clients[id]->getAddress(); -} +std::shared_ptr ClientManager::getAddress(std::string id) { return _clients[id]->getAddress(); } std::shared_ptr ClientManager::operator[](std::string id) { return _clients[id]; } diff --git a/Flakkari/Server/Client/ClientManager.hpp b/Flakkari/Server/Client/ClientManager.hpp index ff0791d8..488473fd 100644 --- a/Flakkari/Server/Client/ClientManager.hpp +++ b/Flakkari/Server/Client/ClientManager.hpp @@ -22,7 +22,6 @@ #define SINGLETON_IMPLEMENTATION #include -#include #include #include #include @@ -51,19 +50,19 @@ namespace Flakkari { */ class ClientManager : public Singleton { private: - std::unordered_map> _clients; - std::vector _bannedClients; - std::shared_ptr _socket; + std::unordered_map> _clients; + std::vector _bannedClients; + std::shared_ptr _socket; - using id_t = short; + using id_t = short; public: - /** - * @brief Construct a new ClientManager object - * - * @param socket The server's socket - */ - explicit ClientManager(std::shared_ptr socket) : _socket(socket) {} + /** + * @brief Construct a new ClientManager object + * + * @param socket The server's socket + */ + explicit ClientManager(std::shared_ptr socket) : _socket(socket) {} /** * @brief Destroy the ClientManager object @@ -71,94 +70,94 @@ class ClientManager : public Singleton { */ ~ClientManager() = default; - /** - * @brief Add a client to the client manager or update the last activity of the client - * - * @param client The client's address - */ - void addClient(std::shared_ptr client, Network::Buffer &buffer); - - /** - * @brief Remove a client from the client manager - * - * @param client The client's address - */ - void removeClient(std::shared_ptr client); - - /** - * @brief Ban a client from the server - * - * @param client The client's address - */ - void banClient(std::shared_ptr client); - - [[nodiscard]] bool isBanned(std::shared_ptr client); - - /** - * @brief Check if the clients are still connected to the server - * and remove the inactive clients from the client manager - * (inactive clients are clients that didn't send any packet to the server - * for more than 5 seconds) - * - * @see Client::isConnected() - * @see Client::keepAlive() - */ - void checkInactiveClients(); - - /** - * @brief Send a packet to a client - * - * @param client The client's address - * @param packet The packet to send - */ - void sendPacketToClient(std::shared_ptr client, const Network::Buffer &packet); - - /** - * @brief Send a packet to all clients - * - * @param packet The packet to send - */ - void sendPacketToAllClients(const Network::Buffer &packet); - - /** - * @brief Send a packet to all clients except one - * - * @param client The client's address - * @param packet The packet to send - */ - void sendPacketToAllClientsExcept(std::shared_ptr client, const Network::Buffer &packet); - - /** - * @brief Receive a packet from a client - * - * @param client The client's address - * @param packet The packet received - */ - void receivePacketFromClient(std::shared_ptr client, const Network::Buffer &packet); - - /** - * @brief Get the Client object - * - * @param client The client's address - * @return std::shared_ptr The client object - */ - std::shared_ptr getClient(std::shared_ptr client); - - /** - * @brief Get the Client object - * - * @param id The client's id - * @return std::shared_ptr The client object - */ - std::shared_ptr getClient(std::string id); - - /** - * @brief Get the Address object - * - * @param id The client's id - * @return std::shared_ptr The client's address - */ - std::shared_ptr getAddress(std::string id); + /** + * @brief Add a client to the client manager or update the last activity of the client + * + * @param client The client's address + */ + void addClient(std::shared_ptr client, Network::Buffer &buffer); + + /** + * @brief Remove a client from the client manager + * + * @param client The client's address + */ + void removeClient(std::shared_ptr client); + + /** + * @brief Ban a client from the server + * + * @param client The client's address + */ + void banClient(std::shared_ptr client); + + [[nodiscard]] bool isBanned(std::shared_ptr client); + + /** + * @brief Check if the clients are still connected to the server + * and remove the inactive clients from the client manager + * (inactive clients are clients that didn't send any packet to the server + * for more than 5 seconds) + * + * @see Client::isConnected() + * @see Client::keepAlive() + */ + void checkInactiveClients(); + + /** + * @brief Send a packet to a client + * + * @param client The client's address + * @param packet The packet to send + */ + void sendPacketToClient(std::shared_ptr client, const Network::Buffer &packet); + + /** + * @brief Send a packet to all clients + * + * @param packet The packet to send + */ + void sendPacketToAllClients(const Network::Buffer &packet); + + /** + * @brief Send a packet to all clients except one + * + * @param client The client's address + * @param packet The packet to send + */ + void sendPacketToAllClientsExcept(std::shared_ptr client, const Network::Buffer &packet); + + /** + * @brief Receive a packet from a client + * + * @param client The client's address + * @param packet The packet received + */ + void receivePacketFromClient(std::shared_ptr client, const Network::Buffer &packet); + + /** + * @brief Get the Client object + * + * @param client The client's address + * @return std::shared_ptr The client object + */ + std::shared_ptr getClient(std::shared_ptr client); + + /** + * @brief Get the Client object + * + * @param id The client's id + * @return std::shared_ptr The client object + */ + std::shared_ptr getClient(std::string id); + + /** + * @brief Get the Address object + * + * @param id The client's id + * @return std::shared_ptr The client's address + */ + std::shared_ptr getAddress(std::string id); /** * @brief Get the client object from the client manager From 90eb2bb8cf96a2a06f6286b32473858cd02d8445 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 06:24:13 -0500 Subject: [PATCH 05/20] feat: refactor ResourceManager to implement Singleton pattern and update scene management methods --- Flakkari/Server/Game/Game.cpp | 6 +- Flakkari/Server/Game/ResourceManager.cpp | 51 ++++---------- Flakkari/Server/Game/ResourceManager.hpp | 90 ++++++++++-------------- Flakkari/Server/UDPServer.cpp | 2 + 4 files changed, 55 insertions(+), 94 deletions(-) diff --git a/Flakkari/Server/Game/Game.cpp b/Flakkari/Server/Game/Game.cpp index b79b8465..9a0df2c2 100644 --- a/Flakkari/Server/Game/Game.cpp +++ b/Flakkari/Server/Game/Game.cpp @@ -49,7 +49,8 @@ Game::Game(const std::string &name, std::shared_ptr config) throw std::runtime_error("Game: no scenes found"); loadScene((*_config)["startGame"]); - ResourceManager::addScene(config, (*_config)["startGame"]); + ResourceManager::GetInstance().addScene(config, (*_config)["startGame"]); + ResourceManager::UnlockInstance(); } Game::~Game() @@ -449,9 +450,10 @@ bool Game::addPlayer(std::shared_ptr player) Engine::ECS::Entity newEntity = registry.spawn_entity(); auto p_Template = (*_config)["playerTemplate"]; - auto player_info = ResourceManager::getTemplateById(_name, sceneGame, p_Template); + auto player_info = ResourceManager::GetInstance().getTemplateById(_name, sceneGame, p_Template); loadComponents(registry, player_info.value_or(nullptr), newEntity); + ResourceManager::UnlockInstance(); registry.registerComponent(); registry.add_component( diff --git a/Flakkari/Server/Game/ResourceManager.cpp b/Flakkari/Server/Game/ResourceManager.cpp index 7c5339e4..9cc08dbe 100644 --- a/Flakkari/Server/Game/ResourceManager.cpp +++ b/Flakkari/Server/Game/ResourceManager.cpp @@ -11,43 +11,7 @@ namespace Flakkari { -std::shared_ptr ResourceManager::_instance = nullptr; -std::mutex ResourceManager::_mutex; - -std::shared_ptr ResourceManager::getInstance() -{ - std::lock_guard lock(_mutex); - if (_instance == nullptr) - _instance = std::make_shared(); - return _instance; -} - void ResourceManager::addScene(std::shared_ptr config, const std::string &scene) -{ - std::lock_guard lock(_mutex); - if (_instance == nullptr) - _instance = std::make_shared(); - _instance->loadConfig(config, scene); -} - -void ResourceManager::deleteScene(const std::string &game, const std::string &scene) -{ - std::lock_guard lock(_mutex); - if (_instance == nullptr) - return; - _instance->_templates[game].erase(scene); -} - -std::optional -ResourceManager::getTemplateById(const std::string &game, const std::string &scene, const std::string &templateId) -{ - std::lock_guard lock(_mutex); - if (_instance == nullptr) - return std::nullopt; - return _instance->_templates[game][scene][templateId]; -} - -void ResourceManager::loadConfig(std::shared_ptr config, const std::string &scene) { for (auto &_scene : (*config)["scenes"].items()) { @@ -59,12 +23,21 @@ void ResourceManager::loadConfig(std::shared_ptr config, const s for (auto &template_ : sceneInfo.value()["templates"].items()) { for (auto &templateInfo : template_.value().items()) - { _templates[(*config)["title"]][sceneInfo.key()][templateInfo.key()] = templateInfo.value(); - } } } } } -} // namespace Flakkari +void ResourceManager::deleteScene(const std::string &game, const std::string &scene) +{ + _templates[game].erase(scene); +} + +std::optional ResourceManager::getTemplateById ( + const std::string &game, const std::string &scene, const std::string &templateId +) { + return _templates[game][scene][templateId]; +} + +} // namespace Engine::Resource diff --git a/Flakkari/Server/Game/ResourceManager.hpp b/Flakkari/Server/Game/ResourceManager.hpp index d0beaebf..0d600d93 100644 --- a/Flakkari/Server/Game/ResourceManager.hpp +++ b/Flakkari/Server/Game/ResourceManager.hpp @@ -16,6 +16,9 @@ #ifndef RESOURCEMANAGER_HPP_ #define RESOURCEMANAGER_HPP_ +#define SINGLETON_IMPLEMENTATION +#include +#include #include #include #include @@ -47,63 +50,44 @@ namespace Flakkari { * TODO: add a way to unload resources * TODO: add a way to load multiple config files cause multiple scenes could be used for multiple windows */ -class ResourceManager { +class ResourceManager : public Singleton { private: - static std::shared_ptr _instance; - static std::mutex _mutex; - - using nl_template = nlohmann::json; - - public: - std::map>> - _templates; + using nl_template = nlohmann::json; - ResourceManager() = default; - ~ResourceManager() = default; + private: + std::map>> _templates; public: - ResourceManager(const ResourceManager &) = delete; - ResourceManager(const std::shared_ptr &) = delete; - void operator=(const ResourceManager &) = delete; - void operator=(const std::shared_ptr &) = delete; - - /** - * @brief Get the ResourceManager instance - * - * @param configPath The path to the config file - * @return ResourceManager & The ResourceManager instance - */ - static std::shared_ptr getInstance(); - - /** - * @brief Add a scene to the ResourceManager instance - * - * @param configPath The path to the config file of the game to add - * @param scene The scene to add to the ResourceManager instance - */ - static void addScene(std::shared_ptr config, const std::string &scene); - - /** - * @brief Delete a scene from the ResourceManager instance - * - * @param configPath The path to the config file of the game to delete - * @param scene The scene to delete from the ResourceManager instance - */ - static void deleteScene(const std::string &game, const std::string &scene); - - /** - * @brief Get the Template By Id object from the config file of the game - * - * @param game The game to get the template from (name of the file in Games/ folder) - * @param scene The scene to get the template from (name of the file in Games//Scenes/ folder) - * @param templateId The id of the template to get (name of the template in the config file) - * @return std::optional The template if found, std::nullopt otherwise - */ - [[nodiscard]] static std::optional getTemplateById(const std::string &game, const std::string &scene, - const std::string &templateId); - - private: - void loadConfig(std::shared_ptr config, const std::string &scene); + explicit ResourceManager() = default; + ~ResourceManager() = default; + + /** + * @brief Add a scene to the ResourceManager instance + * + * @param configPath The path to the config file of the game to add + * @param scene The scene to add to the ResourceManager instance + */ + void addScene(std::shared_ptr config, const std::string &scene); + + /** + * @brief Delete a scene from the ResourceManager instance + * + * @param configPath The path to the config file of the game to delete + * @param scene The scene to delete from the ResourceManager instance + */ + void deleteScene(const std::string &game, const std::string &scene); + + /** + * @brief Get the Template By Id object from the config file of the game + * + * @param game The game to get the template from (name of the file in Games/ folder) + * @param scene The scene to get the template from (name of the file in Games//Scenes/ folder) + * @param templateId The id of the template to get (name of the template in the config file) + * @return std::optional The template if found, std::nullopt otherwise + */ + [[nodiscard]] std::optional getTemplateById ( + const std::string &game, const std::string &scene, const std::string &templateId + ); }; } /* namespace Flakkari */ diff --git a/Flakkari/Server/UDPServer.cpp b/Flakkari/Server/UDPServer.cpp index 8582a32f..2fb7007b 100644 --- a/Flakkari/Server/UDPServer.cpp +++ b/Flakkari/Server/UDPServer.cpp @@ -26,11 +26,13 @@ UDPServer::UDPServer(std::string ip, unsigned short port) _io->addSocket(STDIN_FILENO); ClientManager::CreateInstance(_socket); + ResourceManager::CreateInstance(); } UDPServer::~UDPServer() { ClientManager::DestroyInstance(); + ResourceManager::DestroyInstance(); Network::cleanup(); FLAKKARI_LOG_INFO("UDPServer is now stopped"); } From 14f9c87a4ea6510401b7f71bed7a3af471efeb8f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 7 Nov 2024 11:24:34 +0000 Subject: [PATCH 06/20] style: apply linter --- Flakkari/Server/Game/ResourceManager.cpp | 13 ++---- Flakkari/Server/Game/ResourceManager.hpp | 59 ++++++++++++------------ 2 files changed, 34 insertions(+), 38 deletions(-) diff --git a/Flakkari/Server/Game/ResourceManager.cpp b/Flakkari/Server/Game/ResourceManager.cpp index 9cc08dbe..241491d9 100644 --- a/Flakkari/Server/Game/ResourceManager.cpp +++ b/Flakkari/Server/Game/ResourceManager.cpp @@ -29,15 +29,12 @@ void ResourceManager::addScene(std::shared_ptr config, const std } } -void ResourceManager::deleteScene(const std::string &game, const std::string &scene) -{ - _templates[game].erase(scene); -} +void ResourceManager::deleteScene(const std::string &game, const std::string &scene) { _templates[game].erase(scene); } -std::optional ResourceManager::getTemplateById ( - const std::string &game, const std::string &scene, const std::string &templateId -) { +std::optional +ResourceManager::getTemplateById(const std::string &game, const std::string &scene, const std::string &templateId) +{ return _templates[game][scene][templateId]; } -} // namespace Engine::Resource +} // namespace Flakkari diff --git a/Flakkari/Server/Game/ResourceManager.hpp b/Flakkari/Server/Game/ResourceManager.hpp index 0d600d93..d8de1290 100644 --- a/Flakkari/Server/Game/ResourceManager.hpp +++ b/Flakkari/Server/Game/ResourceManager.hpp @@ -18,7 +18,6 @@ #define SINGLETON_IMPLEMENTATION #include -#include #include #include #include @@ -52,42 +51,42 @@ namespace Flakkari { */ class ResourceManager : public Singleton { private: - using nl_template = nlohmann::json; + using nl_template = nlohmann::json; private: - std::map>> _templates; + std::map>> + _templates; public: - explicit ResourceManager() = default; - ~ResourceManager() = default; + explicit ResourceManager() = default; + ~ResourceManager() = default; - /** - * @brief Add a scene to the ResourceManager instance - * - * @param configPath The path to the config file of the game to add - * @param scene The scene to add to the ResourceManager instance - */ - void addScene(std::shared_ptr config, const std::string &scene); + /** + * @brief Add a scene to the ResourceManager instance + * + * @param configPath The path to the config file of the game to add + * @param scene The scene to add to the ResourceManager instance + */ + void addScene(std::shared_ptr config, const std::string &scene); - /** - * @brief Delete a scene from the ResourceManager instance - * - * @param configPath The path to the config file of the game to delete - * @param scene The scene to delete from the ResourceManager instance - */ - void deleteScene(const std::string &game, const std::string &scene); + /** + * @brief Delete a scene from the ResourceManager instance + * + * @param configPath The path to the config file of the game to delete + * @param scene The scene to delete from the ResourceManager instance + */ + void deleteScene(const std::string &game, const std::string &scene); - /** - * @brief Get the Template By Id object from the config file of the game - * - * @param game The game to get the template from (name of the file in Games/ folder) - * @param scene The scene to get the template from (name of the file in Games//Scenes/ folder) - * @param templateId The id of the template to get (name of the template in the config file) - * @return std::optional The template if found, std::nullopt otherwise - */ - [[nodiscard]] std::optional getTemplateById ( - const std::string &game, const std::string &scene, const std::string &templateId - ); + /** + * @brief Get the Template By Id object from the config file of the game + * + * @param game The game to get the template from (name of the file in Games/ folder) + * @param scene The scene to get the template from (name of the file in Games//Scenes/ folder) + * @param templateId The id of the template to get (name of the template in the config file) + * @return std::optional The template if found, std::nullopt otherwise + */ + [[nodiscard]] std::optional getTemplateById(const std::string &game, const std::string &scene, + const std::string &templateId); }; } /* namespace Flakkari */ From f370cf783063601a2b88fefda2b781608eb88f73 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 06:27:13 -0500 Subject: [PATCH 07/20] refactor: GameManager to implement Singleton pattern and streamline game management methods --- Flakkari/Server/Game/GameManager.cpp | 66 ++----- Flakkari/Server/Game/GameManager.hpp | 191 +++++++++---------- Flakkari/Server/Internals/CommandManager.cpp | 24 +-- Flakkari/Server/UDPServer.cpp | 2 + 4 files changed, 118 insertions(+), 165 deletions(-) diff --git a/Flakkari/Server/Game/GameManager.cpp b/Flakkari/Server/Game/GameManager.cpp index 9d95a7fa..ff92c7b5 100644 --- a/Flakkari/Server/Game/GameManager.cpp +++ b/Flakkari/Server/Game/GameManager.cpp @@ -14,9 +14,6 @@ namespace Flakkari { -std::shared_ptr GameManager::_instance = nullptr; -std::mutex GameManager::_mutex; - #define STR_ADDRESS std::string(*client->getAddress()) GameManager::GameManager() @@ -68,19 +65,8 @@ GameManager::GameManager() } } -std::shared_ptr GameManager::getInstance() -{ - std::lock_guard lock(_mutex); - if (!_instance) - _instance = std::make_shared(); - return _instance; -} - int GameManager::addGame(std::string gameName) { - auto &_gamesStore = getInstance()->_gamesStore; - auto _game_dir = getInstance()->_game_dir; - if (_gamesStore.find(gameName) != _gamesStore.end()) return FLAKKARI_LOG_ERROR("game already loaded"), 1; std::ifstream configFile(_game_dir + "/" + gameName + "/config.cfg"); @@ -100,7 +86,6 @@ int GameManager::addGame(std::string gameName) std::shared_ptr GameManager::getGame(std::string gameName) { - auto &_gamesStore = getInstance()->_gamesStore; if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), nullptr; return std::make_shared(gameName, _gamesStore[gameName]); @@ -108,7 +93,6 @@ std::shared_ptr GameManager::getGame(std::string gameName) std::vector> GameManager::getGamesInstances() { - auto &_gamesInstances = getInstance()->_gamesInstances; std::vector> gamesInstances; for (auto &game : _gamesInstances) @@ -118,9 +102,6 @@ std::vector> GameManager::getGamesInstances() int GameManager::updateGame(std::string gameName) { - auto &_gamesStore = getInstance()->_gamesStore; - auto _game_dir = getInstance()->_game_dir; - if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), 1; std::ifstream configFile(_game_dir + "/" + gameName + "/config.cfg"); @@ -137,7 +118,6 @@ int GameManager::updateGame(std::string gameName) int GameManager::removeGame(std::string gameName) { - auto &_gamesStore = getInstance()->_gamesStore; if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), 1; @@ -149,7 +129,6 @@ int GameManager::removeGame(std::string gameName) void GameManager::listGames() { - auto &_gamesStore = getInstance()->_gamesStore; std::string gamesList = "Games list:\n"; for (const auto &game : _gamesStore) @@ -159,20 +138,14 @@ void GameManager::listGames() void GameManager::addClientToGame(std::string gameName, std::shared_ptr client) { - auto current = getInstance(); - auto &gamesStore = current->_gamesStore; - auto &gamesInstances = current->_gamesInstances; - auto &waitingClients = current->_waitingClients; - - if (gamesStore.find(gameName) == gamesStore.end()) - { + if (_gamesStore.find(gameName) == _gamesStore.end()) { FLAKKARI_LOG_ERROR("game not found"); client.reset(); return; } - auto &gameStore = gamesStore[gameName]; - auto &gameInstance = gamesInstances[gameName]; + auto &gameStore = _gamesStore[gameName]; + auto &gameInstance = _gamesInstances[gameName]; auto minPlayers = gameStore->at("minPlayers").get(); auto maxPlayers = gameStore->at("maxPlayers").get(); @@ -188,7 +161,7 @@ void GameManager::addClientToGame(std::string gameName, std::shared_ptr if (gameInstance.size() >= maxInstances) { FLAKKARI_LOG_ERROR("game \"" + gameName + "\"is full"); - waitingClients[gameName].push(client); + _waitingClients[gameName].push(client); return; } gameInstance.push_back(std::make_shared(gameName, gameStore)); @@ -209,25 +182,23 @@ void GameManager::addClientToGame(std::string gameName, std::shared_ptr void GameManager::removeClientFromGame(std::string gameName, std::shared_ptr client) { - auto &gamesStore = getInstance()->_gamesStore; - auto &gamesInstances = getInstance()->_gamesInstances; - auto &waitingClients = getInstance()->_waitingClients; - if (gamesStore.find(gameName) == gamesStore.end()) + if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), void(); - auto &waitingQueue = waitingClients[gameName]; + auto &waitingQueue = _waitingClients[gameName]; - auto minPlayers = gamesStore[gameName]->at("minPlayers").get(); + auto minPlayers = _gamesStore[gameName]->at("minPlayers").get(); - for (auto &instance : gamesInstances[gameName]) - { + for (auto &instance : _gamesInstances[gameName]) { if (!instance->removePlayer(client)) continue; - if (instance->getPlayers().empty()) - { - gamesInstances[gameName].erase( - std::find(gamesInstances[gameName].begin(), gamesInstances[gameName].end(), instance)); + if (instance->getPlayers().empty()) { + _gamesInstances[gameName].erase( + std::find( + _gamesInstances[gameName].begin(), _gamesInstances[gameName].end(), instance + ) + ); FLAKKARI_LOG_INFO("game \"" + gameName + "\" removed"); } else if (instance->getPlayers().size() > minPlayers) @@ -252,14 +223,11 @@ void GameManager::removeClientFromGame(std::string gameName, std::shared_ptr client) { - auto &waitingClients = getInstance()->_waitingClients; - auto &gamesStore = getInstance()->_gamesStore; - if (gamesStore.find(gameName) == gamesStore.end()) + if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), -1; - auto tmpQueue = waitingClients[gameName]; - for (int i = 0; !tmpQueue.empty(); i++) - { + auto tmpQueue = _waitingClients[gameName]; + for (int i = 0; !tmpQueue.empty(); i++) { if (tmpQueue.front() == client) return FLAKKARI_LOG_INFO("client \"" + STR_ADDRESS + "\" found in waiting queue at " + std::to_string(i)), i; diff --git a/Flakkari/Server/Game/GameManager.hpp b/Flakkari/Server/Game/GameManager.hpp index a498efe3..e2662154 100644 --- a/Flakkari/Server/Game/GameManager.hpp +++ b/Flakkari/Server/Game/GameManager.hpp @@ -31,30 +31,20 @@ namespace Flakkari { -class GameManager { +class GameManager : public Singleton { private: - static std::shared_ptr _instance; - static std::mutex _mutex; + std::unordered_map> /*waitingClients*/> _waitingClients; + std::unordered_map> /*gamesInstances*/> _gamesInstances; + std::unordered_map /*data*/> _gamesStore; + std::string _game_dir; public: - std::unordered_map> /*waitingClients*/> - _waitingClients; - std::unordered_map> /*gamesInstances*/> _gamesInstances; - std::unordered_map /*data*/> _gamesStore; - std::string _game_dir; - - public: - GameManager(const GameManager &) = delete; - GameManager(const std::shared_ptr &) = delete; - void operator=(const GameManager &) = delete; - void operator=(const std::shared_ptr &) = delete; - - /** - * @brief Construct a new GameManager object and load all games - * already present in the Games folder - * - */ - GameManager(); + /** + * @brief Construct a new GameManager object and load all games + * already present in the Games folder + * + */ + explicit GameManager(); /** * @brief Destroy the GameManager object @@ -62,89 +52,82 @@ class GameManager { */ ~GameManager() = default; - /** - * @brief Get the instance of the GameManager - * - * @return std::shared_ptr instance of the GameManager - */ - static std::shared_ptr getInstance(); - - /** - * @brief Add a game to the GameManager and load it from the Games folder - * - * @param gameName Game to add - * @return 0 Game added - * @return 1 Game not added (already exists) - * @return 2 Game not added (certificate not valid) (not implemented) - * @return 3 Game not added (corrupted game) (not implemented) - */ - static int addGame(std::string gameName); - - /** - * @brief Get the Game object - * - * @param gameName Game to get - * @return std::shared_ptr Game - * - * @deprecated Use getGameInstance instead - */ - static std::shared_ptr getGame(std::string gameName); - - /** - * @brief Get the Games Instances object (all games loaded) - * - * @return std::vector> Games Instances - */ - static std::vector> getGamesInstances(); - - /** - * @brief Update a game from the GameManager - * - * @param gameName Game to update - * @return 0 Game updated - * @return 1 Game not updated (not found) - */ - static int updateGame(std::string gameName); - - /** - * @brief Remove a game from the GameManager - * - * @param gameName Game to remove - * @return 0 Game removed - * @return 1 Game not removed (not found) - */ - static int removeGame(std::string gameName); - - /** - * @brief List all games present in the GameManager - * - */ - static void listGames(); - - /** - * @brief Add a client to a game - * - * @param gameName Game to add the client to - * @param client Client to add to the game - */ - static void addClientToGame(std::string gameName, std::shared_ptr client); - - /** - * @brief Remove a client from a game - * - * @param gameName Game to remove the client from - * @param client Client to remove from the game - */ - static void removeClientFromGame(std::string gameName, std::shared_ptr client); - - /** - * @brief Get the index of a client in the waiting queue - * - * @param gameName Game to get the index from - * @param client Client to get the index of - * @return int Index of the client in the waiting queue - */ - static int getIndexInWaitingQueue(std::string gameName, std::shared_ptr client); + /** + * @brief Add a game to the GameManager and load it from the Games folder + * + * @param gameName Game to add + * @return 0 Game added + * @return 1 Game not added (already exists) + * @return 2 Game not added (certificate not valid) (not implemented) + * @return 3 Game not added (corrupted game) (not implemented) + */ + int addGame(std::string gameName); + + /** + * @brief Get the Game object + * + * @param gameName Game to get + * @return std::shared_ptr Game + * + * @deprecated Use getGameInstance instead + */ + std::shared_ptr getGame(std::string gameName); + + /** + * @brief Get the Games Instances object (all games loaded) + * + * @return std::vector> Games Instances + */ + std::vector> getGamesInstances(); + + /** + * @brief Update a game from the GameManager + * + * @param gameName Game to update + * @return 0 Game updated + * @return 1 Game not updated (not found) + */ + int updateGame(std::string gameName); + + /** + * @brief Remove a game from the GameManager + * + * @param gameName Game to remove + * @return 0 Game removed + * @return 1 Game not removed (not found) + */ + int removeGame(std::string gameName); + + /** + * @brief List all games present in the GameManager + * + */ + void listGames(); + + /** + * @brief Add a client to a game + * + * @param gameName Game to add the client to + * @param client Client to add to the game + */ + void addClientToGame(std::string gameName, std::shared_ptr client); + + /** + * @brief Remove a client from a game + * + * @param gameName Game to remove the client from + * @param client Client to remove from the game + */ + void removeClientFromGame(std::string gameName, std::shared_ptr client); + + /** + * @brief Get the index of a client in the waiting queue + * + * @param gameName Game to get the index from + * @param client Client to get the index of + * @return int Index of the client in the waiting queue + */ + int getIndexInWaitingQueue(std::string gameName, std::shared_ptr client); }; } /* namespace Flakkari */ diff --git a/Flakkari/Server/Internals/CommandManager.cpp b/Flakkari/Server/Internals/CommandManager.cpp index 661d6f91..90efef13 100644 --- a/Flakkari/Server/Internals/CommandManager.cpp +++ b/Flakkari/Server/Internals/CommandManager.cpp @@ -83,27 +83,27 @@ bool CommandManager::handleAdminCommand(const std::string &input) return true; } - if (std::regex_match(input, ADD_GAME_REGEX)) - { - GameManager::addGame(input.substr(8)); + if (std::regex_match(input, ADD_GAME_REGEX)) { + GameManager::GetInstance().addGame(input.substr(8)); + GameManager::UnlockInstance(); return true; } - if (std::regex_match(input, UPDATE_GAME_REGEX)) - { - GameManager::updateGame(input.substr(11)); + if (std::regex_match(input, UPDATE_GAME_REGEX)) { + GameManager::GetInstance().updateGame(input.substr(11)); + GameManager::UnlockInstance(); return true; } - if (std::regex_match(input, REMOVE_GAME_REGEX)) - { - GameManager::removeGame(input.substr(11)); + if (std::regex_match(input, REMOVE_GAME_REGEX)) { + GameManager::GetInstance().removeGame(input.substr(11)); + GameManager::UnlockInstance(); return true; } - if (input == "listGames") - { - GameManager::listGames(); + if (input == "listGames") { + GameManager::GetInstance().listGames(); + GameManager::UnlockInstance(); return true; } diff --git a/Flakkari/Server/UDPServer.cpp b/Flakkari/Server/UDPServer.cpp index 2fb7007b..7399eb18 100644 --- a/Flakkari/Server/UDPServer.cpp +++ b/Flakkari/Server/UDPServer.cpp @@ -27,12 +27,14 @@ UDPServer::UDPServer(std::string ip, unsigned short port) ClientManager::CreateInstance(_socket); ResourceManager::CreateInstance(); + GameManager::CreateInstance(); } UDPServer::~UDPServer() { ClientManager::DestroyInstance(); ResourceManager::DestroyInstance(); + GameManager::DestroyInstance(); Network::cleanup(); FLAKKARI_LOG_INFO("UDPServer is now stopped"); } From bbcd3dc3c7533a7635e493320f4f776824df7032 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 7 Nov 2024 11:27:35 +0000 Subject: [PATCH 08/20] style: apply linter --- Flakkari/Server/Game/GameManager.cpp | 17 +- Flakkari/Server/Game/GameManager.hpp | 173 ++++++++++--------- Flakkari/Server/Internals/CommandManager.cpp | 12 +- 3 files changed, 104 insertions(+), 98 deletions(-) diff --git a/Flakkari/Server/Game/GameManager.cpp b/Flakkari/Server/Game/GameManager.cpp index ff92c7b5..d9885648 100644 --- a/Flakkari/Server/Game/GameManager.cpp +++ b/Flakkari/Server/Game/GameManager.cpp @@ -138,7 +138,8 @@ void GameManager::listGames() void GameManager::addClientToGame(std::string gameName, std::shared_ptr client) { - if (_gamesStore.find(gameName) == _gamesStore.end()) { + if (_gamesStore.find(gameName) == _gamesStore.end()) + { FLAKKARI_LOG_ERROR("game not found"); client.reset(); return; @@ -189,16 +190,15 @@ void GameManager::removeClientFromGame(std::string gameName, std::shared_ptrat("minPlayers").get(); - for (auto &instance : _gamesInstances[gameName]) { + for (auto &instance : _gamesInstances[gameName]) + { if (!instance->removePlayer(client)) continue; - if (instance->getPlayers().empty()) { + if (instance->getPlayers().empty()) + { _gamesInstances[gameName].erase( - std::find( - _gamesInstances[gameName].begin(), _gamesInstances[gameName].end(), instance - ) - ); + std::find(_gamesInstances[gameName].begin(), _gamesInstances[gameName].end(), instance)); FLAKKARI_LOG_INFO("game \"" + gameName + "\" removed"); } else if (instance->getPlayers().size() > minPlayers) @@ -227,7 +227,8 @@ int GameManager::getIndexInWaitingQueue(std::string gameName, std::shared_ptr { private: - std::unordered_map> /*waitingClients*/> _waitingClients; - std::unordered_map> /*gamesInstances*/> _gamesInstances; - std::unordered_map /*data*/> _gamesStore; - std::string _game_dir; + std::unordered_map> /*waitingClients*/> + _waitingClients; + std::unordered_map> /*gamesInstances*/> _gamesInstances; + std::unordered_map /*data*/> _gamesStore; + std::string _game_dir; public: - /** - * @brief Construct a new GameManager object and load all games - * already present in the Games folder - * - */ - explicit GameManager(); + /** + * @brief Construct a new GameManager object and load all games + * already present in the Games folder + * + */ + explicit GameManager(); /** * @brief Destroy the GameManager object @@ -52,82 +53,82 @@ class GameManager : public Singleton { */ ~GameManager() = default; - /** - * @brief Add a game to the GameManager and load it from the Games folder - * - * @param gameName Game to add - * @return 0 Game added - * @return 1 Game not added (already exists) - * @return 2 Game not added (certificate not valid) (not implemented) - * @return 3 Game not added (corrupted game) (not implemented) - */ - int addGame(std::string gameName); - - /** - * @brief Get the Game object - * - * @param gameName Game to get - * @return std::shared_ptr Game - * - * @deprecated Use getGameInstance instead - */ - std::shared_ptr getGame(std::string gameName); - - /** - * @brief Get the Games Instances object (all games loaded) - * - * @return std::vector> Games Instances - */ - std::vector> getGamesInstances(); - - /** - * @brief Update a game from the GameManager - * - * @param gameName Game to update - * @return 0 Game updated - * @return 1 Game not updated (not found) - */ - int updateGame(std::string gameName); - - /** - * @brief Remove a game from the GameManager - * - * @param gameName Game to remove - * @return 0 Game removed - * @return 1 Game not removed (not found) - */ - int removeGame(std::string gameName); - - /** - * @brief List all games present in the GameManager - * - */ - void listGames(); - - /** - * @brief Add a client to a game - * - * @param gameName Game to add the client to - * @param client Client to add to the game - */ - void addClientToGame(std::string gameName, std::shared_ptr client); - - /** - * @brief Remove a client from a game - * - * @param gameName Game to remove the client from - * @param client Client to remove from the game - */ - void removeClientFromGame(std::string gameName, std::shared_ptr client); - - /** - * @brief Get the index of a client in the waiting queue - * - * @param gameName Game to get the index from - * @param client Client to get the index of - * @return int Index of the client in the waiting queue - */ - int getIndexInWaitingQueue(std::string gameName, std::shared_ptr client); + /** + * @brief Add a game to the GameManager and load it from the Games folder + * + * @param gameName Game to add + * @return 0 Game added + * @return 1 Game not added (already exists) + * @return 2 Game not added (certificate not valid) (not implemented) + * @return 3 Game not added (corrupted game) (not implemented) + */ + int addGame(std::string gameName); + + /** + * @brief Get the Game object + * + * @param gameName Game to get + * @return std::shared_ptr Game + * + * @deprecated Use getGameInstance instead + */ + std::shared_ptr getGame(std::string gameName); + + /** + * @brief Get the Games Instances object (all games loaded) + * + * @return std::vector> Games Instances + */ + std::vector> getGamesInstances(); + + /** + * @brief Update a game from the GameManager + * + * @param gameName Game to update + * @return 0 Game updated + * @return 1 Game not updated (not found) + */ + int updateGame(std::string gameName); + + /** + * @brief Remove a game from the GameManager + * + * @param gameName Game to remove + * @return 0 Game removed + * @return 1 Game not removed (not found) + */ + int removeGame(std::string gameName); + + /** + * @brief List all games present in the GameManager + * + */ + void listGames(); + + /** + * @brief Add a client to a game + * + * @param gameName Game to add the client to + * @param client Client to add to the game + */ + void addClientToGame(std::string gameName, std::shared_ptr client); + + /** + * @brief Remove a client from a game + * + * @param gameName Game to remove the client from + * @param client Client to remove from the game + */ + void removeClientFromGame(std::string gameName, std::shared_ptr client); + + /** + * @brief Get the index of a client in the waiting queue + * + * @param gameName Game to get the index from + * @param client Client to get the index of + * @return int Index of the client in the waiting queue + */ + int getIndexInWaitingQueue(std::string gameName, std::shared_ptr client); }; } /* namespace Flakkari */ diff --git a/Flakkari/Server/Internals/CommandManager.cpp b/Flakkari/Server/Internals/CommandManager.cpp index 90efef13..089be4fb 100644 --- a/Flakkari/Server/Internals/CommandManager.cpp +++ b/Flakkari/Server/Internals/CommandManager.cpp @@ -83,25 +83,29 @@ bool CommandManager::handleAdminCommand(const std::string &input) return true; } - if (std::regex_match(input, ADD_GAME_REGEX)) { + if (std::regex_match(input, ADD_GAME_REGEX)) + { GameManager::GetInstance().addGame(input.substr(8)); GameManager::UnlockInstance(); return true; } - if (std::regex_match(input, UPDATE_GAME_REGEX)) { + if (std::regex_match(input, UPDATE_GAME_REGEX)) + { GameManager::GetInstance().updateGame(input.substr(11)); GameManager::UnlockInstance(); return true; } - if (std::regex_match(input, REMOVE_GAME_REGEX)) { + if (std::regex_match(input, REMOVE_GAME_REGEX)) + { GameManager::GetInstance().removeGame(input.substr(11)); GameManager::UnlockInstance(); return true; } - if (input == "listGames") { + if (input == "listGames") + { GameManager::GetInstance().listGames(); GameManager::UnlockInstance(); return true; From 72016b6afe8c43c5f729925353b66a01e6d14099 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 06:29:37 -0500 Subject: [PATCH 09/20] refactor: consolidate build checker workflows into a single file for Windows, Ubuntu, and MacOS --- .github/workflows/build_checker.yml | 58 +++++++++++++++++++++ .github/workflows/build_checker_macos.yml | 27 ---------- .github/workflows/build_checker_ubuntu.yml | 27 ---------- .github/workflows/build_checker_windows.yml | 22 -------- .github/workflows/deploy_doxygen_page.yml | 7 +-- 5 files changed, 62 insertions(+), 79 deletions(-) create mode 100644 .github/workflows/build_checker.yml delete mode 100644 .github/workflows/build_checker_macos.yml delete mode 100644 .github/workflows/build_checker_ubuntu.yml delete mode 100644 .github/workflows/build_checker_windows.yml diff --git a/.github/workflows/build_checker.yml b/.github/workflows/build_checker.yml new file mode 100644 index 00000000..321c0280 --- /dev/null +++ b/.github/workflows/build_checker.yml @@ -0,0 +1,58 @@ +name: Build Checker Windows + +on: + push: + branches-ignore: + - 'ga-ignore-**' + - 'gh-pages' + +jobs: + build_checker_windows: + name: Build Checker Windows + runs-on: windows-latest + steps: + - name: Set up Git repository + uses: actions/checkout@v4 + + - name: Install dependencies + run: | + choco install cmake -y + + - name: Configure and Build + run: | + mkdir build && cd build + cmake .. && cmake --build . + + build_checker_ubuntu: + name: Build Checker Ubuntu + runs-on: ubuntu-latest + steps: + - name: Set up Git repository + uses: actions/checkout@v4 + + - name: Install dependencies + run: | + sudo apt update + sudo apt install cmake + + - name: Configure and Build + run: | + mkdir build && cd build + cmake .. && cmake --build . + + build_checker_macos: + name: Build Checker MacOS + runs-on: macos-latest + steps: + - name: Set up Git repository + uses: actions/checkout@v4 + + - name: Install dependencies + run: | + brew install cmake + brew install ninja + + - name: Configure and Build + run: | + mkdir build && cd build + cmake -G Ninja .. && ninja diff --git a/.github/workflows/build_checker_macos.yml b/.github/workflows/build_checker_macos.yml deleted file mode 100644 index bdd867aa..00000000 --- a/.github/workflows/build_checker_macos.yml +++ /dev/null @@ -1,27 +0,0 @@ -name: Build Checker MacOs - -on: - push: - branches-ignore: - - 'ga-ignore-**' - - 'gh-pages' - -jobs: - build_checker_macos: - runs-on: macos-latest - - steps: - - name: Set up Git repository - uses: actions/checkout@v4 - - - name: Install dependencies - run: | - brew install cmake - brew install ninja - - - name: Build - run: | - mkdir build - cd build - cmake -G Ninja .. - ninja diff --git a/.github/workflows/build_checker_ubuntu.yml b/.github/workflows/build_checker_ubuntu.yml deleted file mode 100644 index c2ffd652..00000000 --- a/.github/workflows/build_checker_ubuntu.yml +++ /dev/null @@ -1,27 +0,0 @@ -name: Build Checker Ubuntu - -on: - push: - branches-ignore: - - 'ga-ignore-**' - - 'gh-pages' - -jobs: - build_checker_ubuntu: - runs-on: ubuntu-latest - - steps: - - name: Set up Git repository - uses: actions/checkout@v4 - - - name: Install dependencies - run: | - sudo apt update - sudo apt install cmake - - - name: Build - run: | - mkdir build - cd build - cmake .. - cmake --build . diff --git a/.github/workflows/build_checker_windows.yml b/.github/workflows/build_checker_windows.yml deleted file mode 100644 index 48b587c1..00000000 --- a/.github/workflows/build_checker_windows.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: Build Checker Windows - -on: - push: - branches-ignore: - - 'ga-ignore-**' - - 'gh-pages' - -jobs: - build: - runs-on: windows-latest - steps: - - uses: actions/checkout@v4 - - - name: Install CMake - run: | - choco install cmake -y - - - name: Configure and Build - run: | - mkdir build && cd build - cmake .. && cmake --build . diff --git a/.github/workflows/deploy_doxygen_page.yml b/.github/workflows/deploy_doxygen_page.yml index b4817d64..580c8503 100644 --- a/.github/workflows/deploy_doxygen_page.yml +++ b/.github/workflows/deploy_doxygen_page.yml @@ -1,7 +1,8 @@ name: Doxygen GitHub Pages Deploy Action on: - release: - types: [released] + pull_request: + types: [closed] + branches: [master, main] jobs: generate: @@ -10,7 +11,7 @@ jobs: - name: Checkout repository uses: actions/checkout@v4 with: - submodules: "true" + submodules: true - name: Install Doxygen run: | From acf040de9ba3505c7c3ad0a6978eeb467f9d986f Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 06:42:31 -0500 Subject: [PATCH 10/20] refactor: update build checker and release workflows for clarity and efficiency --- .github/workflows/build_checker.yml | 1 - .github/workflows/create_release.yml | 21 +++++++-------------- 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/.github/workflows/build_checker.yml b/.github/workflows/build_checker.yml index 321c0280..189fc988 100644 --- a/.github/workflows/build_checker.yml +++ b/.github/workflows/build_checker.yml @@ -49,7 +49,6 @@ jobs: - name: Install dependencies run: | - brew install cmake brew install ninja - name: Configure and Build diff --git a/.github/workflows/create_release.yml b/.github/workflows/create_release.yml index 8a3a6760..9661889e 100644 --- a/.github/workflows/create_release.yml +++ b/.github/workflows/create_release.yml @@ -9,8 +9,8 @@ permissions: contents: write jobs: - bump_version: - name: Bump version + bump_version_and_create_release: + name: Bump version and create release runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -41,18 +41,13 @@ jobs: git commit -m "chore: bump the Flakkari version to ${{ steps.test_tag_version.outputs.new_tag }}" || true git push || true - create_release: - name: Create release - needs: bump_version - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Bump version and push tag + - name: Create Tag id: tag_version - uses: mathieudutour/github-tag-action@v6.2 - with: + env: github_token: ${{ secrets.GITHUB_TOKEN }} + run: | + git tag ${{ steps.test_tag_version.outputs.new_tag }} + git push origin ${{ steps.test_tag_version.outputs.new_tag }} - name: Create a GitHub release uses: ncipollo/release-action@v1.14.0 @@ -60,6 +55,4 @@ jobs: tag: ${{ steps.tag_version.outputs.new_tag }} name: Flakkari ${{ steps.tag_version.outputs.new_tag }} body: ${{ steps.tag_version.outputs.changelog }} - draft: false - prerelease: false generateReleaseNotes: true From 1936628416150377808bae853fa1919a9de64af9 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 07:34:51 -0500 Subject: [PATCH 11/20] refactor: update creation dates in header files to 2024 --- CMakeLists.txt | 3 +- .../Components/2D/Collider.hpp | 2 - .../Components/2D/Control.hpp | 2 +- .../Components/2D/Movable.hpp | 2 +- .../Components/2D/RigidBody.hpp | 4 +- .../Components/2D/Transform.hpp | 2 +- .../Components/Common/Child.hpp | 2 +- .../Components/Common/Evolve.hpp | 2 +- .../Components/Common/Health.hpp | 4 +- .../Components/Common/Id.hpp | 2 +- .../Components/Common/Level.hpp | 4 +- .../Components/Common/NetworkEvent.hpp | 2 +- .../Components/Common/Parent.hpp | 4 +- .../Components/Common/Spawned.hpp | 4 +- .../Components/Common/Tag.hpp | 2 +- .../Components/Common/Weapon.hpp | 4 +- .../Components/Components2D.hpp | 2 +- .../Components/ComponentsCommon.hpp | 2 +- .../Engine/EntityComponentSystem/Entity.hpp | 2 +- .../Engine/EntityComponentSystem/Registry.cpp | 2 +- .../Engine/EntityComponentSystem/Registry.hpp | 2 +- .../EntityComponentSystem/SparseArrays.hpp | 2 +- .../EntityComponentSystem/Systems/Systems.cpp | 2 +- .../EntityComponentSystem/Systems/Systems.hpp | 2 +- Flakkari/Engine/Math/Vector.cpp | 2 +- Flakkari/Engine/Math/Vector.hpp | 4 +- Flakkari/Logger/Logger.hpp | 37 ++++++++----- Flakkari/Network/Packed.hpp | 54 ------------------- Flakkari/Protocol/Events.hpp | 4 +- Flakkari/Protocol/Header.hpp | 3 +- Flakkari/Protocol/PacketFactory.hpp | 2 +- Flakkari/Server/Game/Game.cpp | 2 +- Flakkari/Server/Game/Game.hpp | 2 +- Flakkari/Server/Game/GameManager.cpp | 2 +- Flakkari/Server/Game/GameManager.hpp | 2 +- Flakkari/Server/Game/ResourceManager.cpp | 2 +- Flakkari/Server/Internals/CommandManager.cpp | 2 +- Flakkari/Server/Internals/CommandManager.hpp | 2 +- Flakkari/config.h.in | 10 +++- 39 files changed, 74 insertions(+), 117 deletions(-) delete mode 100644 Flakkari/Network/Packed.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 37eb4a82..2141254d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,7 +35,6 @@ set(HEADERS Flakkari/Logger/Logger.hpp Flakkari/Network/Network.hpp - Flakkari/Network/Packed.hpp Flakkari/Network/Address.hpp Flakkari/Network/Buffer.hpp Flakkari/Network/Socket.hpp @@ -78,7 +77,6 @@ set(HEADER_LIB_LOGGER set(HEADER_LIB_NETWORK Flakkari/Network/Network.hpp - Flakkari/Network/Packed.hpp Flakkari/Network/Address.hpp Flakkari/Network/Buffer.hpp Flakkari/Network/Socket.hpp @@ -198,6 +196,7 @@ add_library(flakkari_network SHARED ${SOURCES_LIB_NETWORK} ${HEADER_LIB_NETWORK} # Include Directories: target_include_directories(flakkari_network PRIVATE ${CMAKE_SOURCE_DIR}/Flakkari) +target_include_directories(flakkari_network PRIVATE ${singleton_SOURCE_DIR}) # Link Libraries: target_link_libraries(flakkari_network PRIVATE nlohmann_json::nlohmann_json) diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp index c8af2d07..04f4606c 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp @@ -13,8 +13,6 @@ #include "../../../Math/Vector.hpp" #include -#include "Network/Packed.hpp" - namespace Flakkari::Engine::ECS::Components::_2D { PACKED_START diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp index f960414b..a0290018 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-11 +** Created: 2024-01-11 ** File description: ** Control */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp index a7091e98..372deedb 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-06 +** Created: 2024-01-06 ** File description: ** Movable */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp index b45874c6..2122a01c 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-14 +** Created: 2024-01-14 ** File description: ** RigidBody */ @@ -12,8 +12,6 @@ #include "../../../Math/Vector.hpp" -#include "Network/Packed.hpp" - namespace Flakkari::Engine::ECS::Components::_2D { PACKED_START diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp index 598d6caa..19c1e280 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-06 +** Created: 2024-01-06 ** File description: ** Transform */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp index e423af38..f749edfc 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-06 +** Created: 2024-01-06 ** File description: ** Child */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp index 59dd17d2..3433c786 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-13 +** Created: 2024-01-13 ** File description: ** Evolve */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp index 43e2edbe..910678b1 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-14 +** Created: 2024-01-14 ** File description: ** Health */ @@ -12,7 +12,7 @@ #include -#include "Network/Packed.hpp" +#include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { PACKED_START diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp index f89eda98..d8dd97ba 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp @@ -12,7 +12,7 @@ #include -#include "Network/Packed.hpp" +#include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { PACKED_START diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Level.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Level.hpp index 15a6ed07..f6805123 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Level.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Level.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-14 +** Created: 2024-01-14 ** File description: ** Level */ @@ -13,7 +13,7 @@ #include #include -#include "Network/Packed.hpp" +#include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp index 1ca94073..70e33bef 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-14 +** Created: 2024-01-14 ** File description: ** NetworkEvent */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp index fc6da130..f4517f92 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-06 +** Created: 2024-01-06 ** File description: ** Parent */ @@ -12,7 +12,7 @@ #include -#include "Network/Packed.hpp" +#include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { PACKED_START diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp index 9754c96c..97ccf8a2 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-14 +** Created: 2024-01-14 ** File description: ** Spawned */ @@ -13,7 +13,7 @@ #include #include -#include "Network/Packed.hpp" +#include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { PACKED_START diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp index a674d6b5..eb4e0c85 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-06 +** Created: 2024-01-06 ** File description: ** Tag */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp index 02735a51..cd31d2e0 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-14 +** Created: 2024-01-14 ** File description: ** Weapon */ @@ -13,7 +13,7 @@ #include #include -#include "Network/Packed.hpp" +#include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { PACKED_START diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Components2D.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Components2D.hpp index 56d9d33e..ad831a61 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Components2D.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Components2D.hpp @@ -10,7 +10,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-06 + * @date 2024-01-06 **************************************************************************/ #ifndef FLAKKARI_COMPONENTS2D_HPP_ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/ComponentsCommon.hpp b/Flakkari/Engine/EntityComponentSystem/Components/ComponentsCommon.hpp index 664e82c7..0e3ce81d 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/ComponentsCommon.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/ComponentsCommon.hpp @@ -11,7 +11,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-06 + * @date 2024-01-06 **************************************************************************/ #ifndef FLAKKARI_COMPONENTSCOMMON_HPP_ diff --git a/Flakkari/Engine/EntityComponentSystem/Entity.hpp b/Flakkari/Engine/EntityComponentSystem/Entity.hpp index e666716b..f0061f1e 100644 --- a/Flakkari/Engine/EntityComponentSystem/Entity.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Entity.hpp @@ -9,7 +9,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-05 + * @date 2024-01-05 **************************************************************************/ #ifndef FLAKKARI_ENTITY_HPP_ diff --git a/Flakkari/Engine/EntityComponentSystem/Registry.cpp b/Flakkari/Engine/EntityComponentSystem/Registry.cpp index ae8f0577..8579cd1d 100644 --- a/Flakkari/Engine/EntityComponentSystem/Registry.cpp +++ b/Flakkari/Engine/EntityComponentSystem/Registry.cpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-05 +** Created: 2024-01-05 ** File description: ** Registry */ diff --git a/Flakkari/Engine/EntityComponentSystem/Registry.hpp b/Flakkari/Engine/EntityComponentSystem/Registry.hpp index c59713c9..fc807303 100644 --- a/Flakkari/Engine/EntityComponentSystem/Registry.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Registry.hpp @@ -9,7 +9,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-05 + * @date 2024-01-05 **************************************************************************/ #ifndef FLAKKARI_REGISTRY_HPP_ diff --git a/Flakkari/Engine/EntityComponentSystem/SparseArrays.hpp b/Flakkari/Engine/EntityComponentSystem/SparseArrays.hpp index 7c24015d..c10c522e 100644 --- a/Flakkari/Engine/EntityComponentSystem/SparseArrays.hpp +++ b/Flakkari/Engine/EntityComponentSystem/SparseArrays.hpp @@ -9,7 +9,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-05 + * @date 2024-01-05 **************************************************************************/ #ifndef FLAKKARI_SPARSEARRAYS_HPP_ diff --git a/Flakkari/Engine/EntityComponentSystem/Systems/Systems.cpp b/Flakkari/Engine/EntityComponentSystem/Systems/Systems.cpp index 96cbd429..2b466978 100644 --- a/Flakkari/Engine/EntityComponentSystem/Systems/Systems.cpp +++ b/Flakkari/Engine/EntityComponentSystem/Systems/Systems.cpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-06 +** Created: 2024-01-06 ** File description: ** Systems */ diff --git a/Flakkari/Engine/EntityComponentSystem/Systems/Systems.hpp b/Flakkari/Engine/EntityComponentSystem/Systems/Systems.hpp index ea455d14..41682860 100644 --- a/Flakkari/Engine/EntityComponentSystem/Systems/Systems.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Systems/Systems.hpp @@ -10,7 +10,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-06 + * @date 2024-01-06 **************************************************************************/ #ifndef FLAKKARI_SYSTEMS_HPP_ diff --git a/Flakkari/Engine/Math/Vector.cpp b/Flakkari/Engine/Math/Vector.cpp index 1a5c0861..733de04a 100644 --- a/Flakkari/Engine/Math/Vector.cpp +++ b/Flakkari/Engine/Math/Vector.cpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2023 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-05 +** Created: 2024-01-05 ** File description: ** Vector */ diff --git a/Flakkari/Engine/Math/Vector.hpp b/Flakkari/Engine/Math/Vector.hpp index 812cd01e..29bc308e 100644 --- a/Flakkari/Engine/Math/Vector.hpp +++ b/Flakkari/Engine/Math/Vector.hpp @@ -12,7 +12,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-05 + * @date 2024-01-05 **************************************************************************/ #ifndef FLAKKARI_VECTOR_HPP_ @@ -21,7 +21,7 @@ #include #include -#include "Network/Packed.hpp" +#include "config.h.in" namespace Flakkari::Engine::Math { diff --git a/Flakkari/Logger/Logger.hpp b/Flakkari/Logger/Logger.hpp index 5c55db78..59cabb30 100644 --- a/Flakkari/Logger/Logger.hpp +++ b/Flakkari/Logger/Logger.hpp @@ -1,13 +1,27 @@ -/* -** EPITECH PROJECT, 2023 -** Flakkari -** File description: -** Flakkari::Logger -*/ +/************************************************************************** + * Flakkari Library v0.3.0 + * + * Flakkari Library is a C++ Library for Network. + * @file Logger.hpp + * @brief Logger class header. Can be used to log messages. + * + * Flakkari Library is under MIT License. + * https://opensource.org/licenses/MIT + * © 2023 @MasterLaplace + * @version 0.3.0 + * @date 2023-12-19 + **************************************************************************/ #ifndef FLAKKARI_LOGGER_HPP_ #define FLAKKARI_LOGGER_HPP_ +#include "config.h.in" + +#include +#include +#include +#include + #define LOG_INFO 0 #define LOG_LOG 1 #define LOG_DEBUG 2 @@ -15,11 +29,6 @@ #define LOG_ERROR 4 #define LOG_FATAL 5 -#include -#include -#include -#include - #define FLAKKARI_LOG(level, message) Flakkari::Logger::log(level, message, __LINE__, __FILE__) #define FLAKKARI_LOG_INFO(message) FLAKKARI_LOG(LOG_INFO, message) #define FLAKKARI_LOG_LOG(message) FLAKKARI_LOG(LOG_LOG, message) @@ -28,7 +37,7 @@ #define FLAKKARI_LOG_ERROR(message) FLAKKARI_LOG(LOG_ERROR, message) #define FLAKKARI_LOG_FATAL(message) FLAKKARI_LOG(LOG_FATAL, message) -#ifdef _WIN32 +#ifdef FLAKKARI_SYSTEM_WINDOWS # define STD_ERROR \ []() -> std::string { \ char buffer[256]; \ @@ -42,7 +51,7 @@ # define SPECIAL_ERROR STD_ERROR #endif -#if _WIN32 +#ifdef FLAKKARI_SYSTEM_WINDOWS # define WIN32_LEAN_AND_MEAN # define _WINSOCK_DEPRECATED_NO_WARNINGS # define _CRT_SECURE_NO_WARNINGS @@ -86,6 +95,7 @@ #endif namespace Flakkari { + class Logger { public: enum class Mode { @@ -101,6 +111,7 @@ class Logger { static void log(int level, std::string message, int line, std::string file = "") noexcept; static void log(int level, std::string message) noexcept; }; + } /* namespace Flakkari */ #endif /* !FLAKKARI_LOGGER_HPP_ */ diff --git a/Flakkari/Network/Packed.hpp b/Flakkari/Network/Packed.hpp deleted file mode 100644 index e62c8631..00000000 --- a/Flakkari/Network/Packed.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/************************************************************************** - * Flakkari Library v0.3.0 - * - * Flakkari Library is a C++ Library for Network. - * @file Packed.hpp - * @brief Packed header. Contains PACKED macros. - * (PACKED_START, PACKED_END, PACKED) - * - * @details PACKED_START and PACKED_END macros are used to pack structs: - * PACKED_<_> macros are used to pack structs: - * PACKED_START struct _ {}; PACKED_END - * PACKED macros are used to pack structs: - * struct _ {} PACKED; - * - * Flakkari Library is under MIT License. - * https://opensource.org/licenses/MIT - * © 2023 @MasterLaplace - * @version 0.3.0 - * @date 2023-01-10 - **************************************************************************/ - -#ifndef PACKED_HPP_ -#define PACKED_HPP_ - -#ifdef _MSC_VER -# define PACKED_START __pragma(pack(push, 1)) -# define PACKED_END __pragma(pack(pop)) -#else -# define PACKED_START _Pragma("pack(1)") -# define PACKED_END _Pragma("pack()") -#endif - -#if __GNUC__ -# define __PACKED __attribute__((packed)) - -# define PACKED(name, body) \ - do \ - { \ - struct name body __PACKED; \ - } while (0) - -#else - -# define __PACKED(name, body) \ - do \ - { \ - PACKED_START \ - struct name body; \ - PACKED_END \ - } while (0) - -#endif - -#endif /* !PACKED_HPP_ */ diff --git a/Flakkari/Protocol/Events.hpp b/Flakkari/Protocol/Events.hpp index 01665c9c..86272e37 100644 --- a/Flakkari/Protocol/Events.hpp +++ b/Flakkari/Protocol/Events.hpp @@ -17,9 +17,7 @@ #ifndef EVENTS_HPP_ #define EVENTS_HPP_ -#include - -#include "../Network/Packed.hpp" +#include "config.h.in" namespace Flakkari::Protocol { diff --git a/Flakkari/Protocol/Header.hpp b/Flakkari/Protocol/Header.hpp index 602fb1b5..2d1d0c70 100644 --- a/Flakkari/Protocol/Header.hpp +++ b/Flakkari/Protocol/Header.hpp @@ -20,8 +20,9 @@ #define PROTOCOL_VERSION 1 +#include "config.h.in" + #include "../Network/Buffer.hpp" -#include "../Network/Packed.hpp" #include "Commands.hpp" #include diff --git a/Flakkari/Protocol/PacketFactory.hpp b/Flakkari/Protocol/PacketFactory.hpp index c1d90f7d..a873ce5c 100644 --- a/Flakkari/Protocol/PacketFactory.hpp +++ b/Flakkari/Protocol/PacketFactory.hpp @@ -17,7 +17,7 @@ #ifndef PACKETFACTORY_HPP_ #define PACKETFACTORY_HPP_ -#include "Packet.hpp" +#include "config.h.in" #include "Engine/EntityComponentSystem/Systems/Systems.hpp" diff --git a/Flakkari/Server/Game/Game.cpp b/Flakkari/Server/Game/Game.cpp index 9a0df2c2..9331e8a5 100644 --- a/Flakkari/Server/Game/Game.cpp +++ b/Flakkari/Server/Game/Game.cpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-06 +** Created: 2024-01-06 ** File description: ** Game */ diff --git a/Flakkari/Server/Game/Game.hpp b/Flakkari/Server/Game/Game.hpp index b242c52b..769f135c 100644 --- a/Flakkari/Server/Game/Game.hpp +++ b/Flakkari/Server/Game/Game.hpp @@ -13,7 +13,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-06 + * @date 2024-01-06 **************************************************************************/ #ifndef GAME_HPP_ diff --git a/Flakkari/Server/Game/GameManager.cpp b/Flakkari/Server/Game/GameManager.cpp index d9885648..d9205368 100644 --- a/Flakkari/Server/Game/GameManager.cpp +++ b/Flakkari/Server/Game/GameManager.cpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-07 +** Created: 2024-01-07 ** File description: ** GameManager */ diff --git a/Flakkari/Server/Game/GameManager.hpp b/Flakkari/Server/Game/GameManager.hpp index d99369a6..db56659c 100644 --- a/Flakkari/Server/Game/GameManager.hpp +++ b/Flakkari/Server/Game/GameManager.hpp @@ -11,7 +11,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-06 + * @date 2024-01-06 **************************************************************************/ #ifndef GAMEMANAGER_HPP_ diff --git a/Flakkari/Server/Game/ResourceManager.cpp b/Flakkari/Server/Game/ResourceManager.cpp index 241491d9..c7797df2 100644 --- a/Flakkari/Server/Game/ResourceManager.cpp +++ b/Flakkari/Server/Game/ResourceManager.cpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-12 +** Created: 2024-01-12 ** File description: ** ResourceManager */ diff --git a/Flakkari/Server/Internals/CommandManager.cpp b/Flakkari/Server/Internals/CommandManager.cpp index 089be4fb..06de46b9 100644 --- a/Flakkari/Server/Internals/CommandManager.cpp +++ b/Flakkari/Server/Internals/CommandManager.cpp @@ -2,7 +2,7 @@ ** EPITECH PROJECT, 2024 ** Title: Flakkari ** Author: MasterLaplace -** Created: 2023-01-05 +** Created: 2024-01-05 ** File description: ** CommandManager */ diff --git a/Flakkari/Server/Internals/CommandManager.hpp b/Flakkari/Server/Internals/CommandManager.hpp index d9786066..06572025 100644 --- a/Flakkari/Server/Internals/CommandManager.hpp +++ b/Flakkari/Server/Internals/CommandManager.hpp @@ -13,7 +13,7 @@ * https://opensource.org/licenses/MIT * © 2023 @MasterLaplace * @version 0.3.0 - * @date 2023-01-05 + * @date 2024-01-05 **************************************************************************/ #ifndef COMMANDMANAGER_HPP_ diff --git a/Flakkari/config.h.in b/Flakkari/config.h.in index 8264a92a..c46553ce 100644 --- a/Flakkari/config.h.in +++ b/Flakkari/config.h.in @@ -17,7 +17,7 @@ * * @author @MasterLaplace * @version 0.3.0 - * @date 2023-01-06 + * @date 2024-01-06 **************************************************************************/ // clang-format off @@ -50,7 +50,7 @@ //////////////////////////////////////////////////////////// // Define portable NULL pointer using C++11 nullptr keyword //////////////////////////////////////////////////////////// -#ifdef __cplusplus && __cplusplus >= 201103L +#if defined(__cplusplus) && __cplusplus >= 201103L #elif !defined(NULL) #define nullptr ((void*)0) #else @@ -89,10 +89,16 @@ \**********************************************************/ #if defined(__GNUC__) || defined(__GNUG__) #define PACKED( __Declaration__ ) __Declaration__ __attribute__((__packed__)) + #define PACKED_START _Pragma("pack(1)") + #define PACKED_END _Pragma("pack()") #elif _MSC_VER #define PACKED( __Declaration__ ) __pragma(pack(push, 1)) __Declaration__ __pragma(pack(pop)) + #define PACKED_START __pragma(pack(push, 1)) + #define PACKED_END __pragma(pack(pop)) #else #define PACKED( __Declaration__ ) __Declaration__ + #define PACKED_START _Pragma("pack(1)") + #define PACKED_END _Pragma("pack()") #endif //////////////////////////////////////////////////////////// From 8d0c2bdf521d966293dfd7b7e0667214b467d691 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 09:20:19 -0500 Subject: [PATCH 12/20] refactor: update Socket and UDPServer constructors to improve parameter handling and enforce game directory requirement --- Flakkari/Logger/Logger.cpp | 4 ++- Flakkari/Network/Socket.hpp | 4 +-- Flakkari/Protocol/PacketFactory.hpp | 37 ++++++++++++++-------------- Flakkari/Server/Game/GameManager.cpp | 32 ++++++++---------------- Flakkari/Server/Game/GameManager.hpp | 19 +++++++------- Flakkari/Server/UDPServer.cpp | 4 +-- Flakkari/Server/UDPServer.hpp | 3 ++- Flakkari/core.cpp | 6 ++--- 8 files changed, 51 insertions(+), 58 deletions(-) diff --git a/Flakkari/Logger/Logger.cpp b/Flakkari/Logger/Logger.cpp index a718d419..6064ae5f 100644 --- a/Flakkari/Logger/Logger.cpp +++ b/Flakkari/Logger/Logger.cpp @@ -7,7 +7,7 @@ #include "Logger.hpp" -using namespace Flakkari; +namespace Flakkari { #if defined(DEBUG) || defined(_DEBUG) || !defined(DEBUG) static Logger::Mode _mode = Logger::Mode::DEBUG; @@ -254,3 +254,5 @@ void Logger::log(int level, std::string message) noexcept if (level == LOG_FATAL) std::cout << fatal_error_message() << std::endl; } + +} /* namespace Flakkari */ diff --git a/Flakkari/Network/Socket.hpp b/Flakkari/Network/Socket.hpp index 497add1e..731b651b 100644 --- a/Flakkari/Network/Socket.hpp +++ b/Flakkari/Network/Socket.hpp @@ -129,8 +129,8 @@ class Socket { public: Socket() = default; - Socket(const Socket &) = default; - Socket(Socket &&) = default; + Socket(const Socket &) = delete; + Socket(Socket &&) = delete; ~Socket(); void create(std::shared_ptr
address); diff --git a/Flakkari/Protocol/PacketFactory.hpp b/Flakkari/Protocol/PacketFactory.hpp index a873ce5c..1e66bc0b 100644 --- a/Flakkari/Protocol/PacketFactory.hpp +++ b/Flakkari/Protocol/PacketFactory.hpp @@ -20,6 +20,7 @@ #include "config.h.in" #include "Engine/EntityComponentSystem/Systems/Systems.hpp" +#include "Packet.hpp" namespace Flakkari::Protocol { @@ -101,14 +102,14 @@ class PacketFactory { * @param entity Entity to get the components from. */ template - static void add2dToPacketByEntity(Protocol::Packet &packet, Engine::ECS::Registry ®istry, + static void add2dToPacketByEntity(Packet &packet, Engine::ECS::Registry ®istry, Engine::ECS::Entity entity) { auto transform = registry.getComponents()[entity]; if (transform.has_value()) { - packet << Protocol::ComponentId::TRANSFORM; + packet << ComponentId::TRANSFORM; packet << transform->position.vec.x; packet << transform->position.vec.y; packet << transform->rotation; @@ -120,7 +121,7 @@ class PacketFactory { if (movable.has_value()) { - packet << Protocol::ComponentId::MOVABLE; + packet << ComponentId::MOVABLE; packet << movable->velocity.vec.x; packet << movable->velocity.vec.y; packet << movable->acceleration.vec.x; @@ -131,7 +132,7 @@ class PacketFactory { if (control.has_value()) { - packet << Protocol::ComponentId::CONTROL; + packet << ComponentId::CONTROL; packet << control->up; packet << control->down; packet << control->left; @@ -143,7 +144,7 @@ class PacketFactory { if (collider.has_value()) { - packet << Protocol::ComponentId::COLLIDER; + packet << ComponentId::COLLIDER; packet << collider->_size.vec.x; packet << collider->_size.vec.y; } @@ -152,7 +153,7 @@ class PacketFactory { if (rigidbody.has_value()) { - packet << Protocol::ComponentId::RIGIDBODY; + packet << ComponentId::RIGIDBODY; packet << rigidbody->mass; packet << rigidbody->restitution; packet << rigidbody->friction; @@ -164,7 +165,7 @@ class PacketFactory { if (health.has_value()) { - packet << Protocol::ComponentId::HEALTH; + packet << ComponentId::HEALTH; packet << health->currentHealth; packet << health->maxHealth; packet << health->shield; @@ -175,7 +176,7 @@ class PacketFactory { if (weapon.has_value()) { - packet << Protocol::ComponentId::WEAPON; + packet << ComponentId::WEAPON; packet << weapon->damage; packet << weapon->fireRate; packet << weapon->level; @@ -185,7 +186,7 @@ class PacketFactory { if (level.has_value()) { - packet << Protocol::ComponentId::LEVEL; + packet << ComponentId::LEVEL; packet << level->level; packet.injectString(level->currentWeapon); packet << level->currentExp; @@ -196,7 +197,7 @@ class PacketFactory { if (spawned.has_value()) { - packet << Protocol::ComponentId::SPAWNED; + packet << ComponentId::SPAWNED; packet << spawned->has_spawned; } @@ -204,7 +205,7 @@ class PacketFactory { if (networkEvent.has_value()) { - packet << Protocol::ComponentId::NETWORK_EVENT; + packet << ComponentId::NETWORK_EVENT; packet << networkEvent->events.size(); for (auto &event : networkEvent->events) { @@ -216,7 +217,7 @@ class PacketFactory { if (templateName.has_value()) { - packet << Protocol::ComponentId::TEMPLATE; + packet << ComponentId::TEMPLATE; packet.injectString(templateName->name); } @@ -224,7 +225,7 @@ class PacketFactory { if (parent.has_value()) { - packet << Protocol::ComponentId::PARENT; + packet << ComponentId::PARENT; packet << parent->entity; } @@ -232,7 +233,7 @@ class PacketFactory { if (child.has_value()) { - packet << Protocol::ComponentId::CHILD; + packet << ComponentId::CHILD; packet.injectString(child->name); } @@ -240,7 +241,7 @@ class PacketFactory { if (tag.has_value()) { - packet << Protocol::ComponentId::TAG; + packet << ComponentId::TAG; packet.injectString(tag->tag); } } @@ -254,7 +255,7 @@ class PacketFactory { * @param entity Entity to get the components from. */ template - static void addComponentsToPacketByEntity(Protocol::Packet &packet, Engine::ECS::Registry ®istry, + static void addComponentsToPacketByEntity(Packet &packet, Engine::ECS::Registry ®istry, Engine::ECS::Entity entity) { /*_ Common Components _*/ @@ -275,7 +276,7 @@ class PacketFactory { * @param entity Entity to get the components from. */ template - static void addInfoToPacket(Protocol::Packet &packet, std::size_t size, const std::string &sceneName, + static void addInfoToPacket(Packet &packet, std::size_t size, const std::string &sceneName, Engine::ECS::Entity entity) { packet.injectString(sceneName); @@ -289,7 +290,7 @@ class PacketFactory { }; template - static void addUpdateMovementToPacket(Protocol::Packet &packet, Engine::ECS::Entity entity, + static void addUpdateMovementToPacket(Packet &packet, Engine::ECS::Entity entity, Engine::ECS::Components::_2D::Transform pos, Engine::ECS::Components::_2D::Movable vel) { diff --git a/Flakkari/Server/Game/GameManager.cpp b/Flakkari/Server/Game/GameManager.cpp index d9205368..817299bd 100644 --- a/Flakkari/Server/Game/GameManager.cpp +++ b/Flakkari/Server/Game/GameManager.cpp @@ -16,20 +16,8 @@ namespace Flakkari { #define STR_ADDRESS std::string(*client->getAddress()) -GameManager::GameManager() +GameManager::GameManager(const std::string &gameDir) : _game_dir(gameDir) { -#if !defined(_WIN32) && !defined(_WIN64) && !defined(MSVC) && !defined(_MSC_VER) - _game_dir = std::getenv("FLAKKARI_GAME_DIR"); -#else - char *gameDir = nullptr; - size_t len = 0; - errno_t err = _dupenv_s(&gameDir, &len, "FLAKKARI_GAME_DIR"); - if (err == 0 && gameDir != nullptr) - { - _game_dir = gameDir; - free(gameDir); - } -#endif if (_game_dir.empty()) FLAKKARI_LOG_FATAL("No game directory set: please set \"FLAKKARI_GAME_DIR\" environment variable"); @@ -65,7 +53,7 @@ GameManager::GameManager() } } -int GameManager::addGame(std::string gameName) +int GameManager::addGame(const std::string &gameName) { if (_gamesStore.find(gameName) != _gamesStore.end()) return FLAKKARI_LOG_ERROR("game already loaded"), 1; @@ -84,23 +72,23 @@ int GameManager::addGame(std::string gameName) return 0; } -std::shared_ptr GameManager::getGame(std::string gameName) +const std::shared_ptr &GameManager::getGame(const std::string &gameName) { if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), nullptr; return std::make_shared(gameName, _gamesStore[gameName]); } -std::vector> GameManager::getGamesInstances() +const std::vector> &GameManager::getGamesInstances() { - std::vector> gamesInstances; + std::vector> gamesInstances(_gamesInstances.size()); for (auto &game : _gamesInstances) gamesInstances.insert(gamesInstances.end(), game.second.begin(), game.second.end()); return gamesInstances; } -int GameManager::updateGame(std::string gameName) +int GameManager::updateGame(const std::string &gameName) { if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), 1; @@ -116,7 +104,7 @@ int GameManager::updateGame(std::string gameName) return 0; } -int GameManager::removeGame(std::string gameName) +int GameManager::removeGame(const std::string &gameName) { if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), 1; @@ -136,7 +124,7 @@ void GameManager::listGames() FLAKKARI_LOG_INFO(gamesList); } -void GameManager::addClientToGame(std::string gameName, std::shared_ptr client) +void GameManager::addClientToGame(const std::string &gameName, std::shared_ptr &client) { if (_gamesStore.find(gameName) == _gamesStore.end()) { @@ -181,7 +169,7 @@ void GameManager::addClientToGame(std::string gameName, std::shared_ptr FLAKKARI_LOG_ERROR("could not add client \"" + STR_ADDRESS + "\" to game \"" + gameName + "\""); } -void GameManager::removeClientFromGame(std::string gameName, std::shared_ptr client) +void GameManager::removeClientFromGame(const std::string &gameName, const std::shared_ptr &client) { if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), void(); @@ -221,7 +209,7 @@ void GameManager::removeClientFromGame(std::string gameName, std::shared_ptr client) +int GameManager::getIndexInWaitingQueue(const std::string &gameName, const std::shared_ptr &client) { if (_gamesStore.find(gameName) == _gamesStore.end()) return FLAKKARI_LOG_ERROR("game not found"), -1; diff --git a/Flakkari/Server/Game/GameManager.hpp b/Flakkari/Server/Game/GameManager.hpp index db56659c..b392fb33 100644 --- a/Flakkari/Server/Game/GameManager.hpp +++ b/Flakkari/Server/Game/GameManager.hpp @@ -44,8 +44,9 @@ class GameManager : public Singleton { * @brief Construct a new GameManager object and load all games * already present in the Games folder * + * @param gameDir Directory of the Games folder */ - explicit GameManager(); + explicit GameManager(const std::string &gameDir); /** * @brief Destroy the GameManager object @@ -62,7 +63,7 @@ class GameManager : public Singleton { * @return 2 Game not added (certificate not valid) (not implemented) * @return 3 Game not added (corrupted game) (not implemented) */ - int addGame(std::string gameName); + int addGame(const std::string &gameName); /** * @brief Get the Game object @@ -72,14 +73,14 @@ class GameManager : public Singleton { * * @deprecated Use getGameInstance instead */ - std::shared_ptr getGame(std::string gameName); + const std::shared_ptr &getGame(const std::string &gameName); /** * @brief Get the Games Instances object (all games loaded) * * @return std::vector> Games Instances */ - std::vector> getGamesInstances(); + const std::vector> &getGamesInstances(); /** * @brief Update a game from the GameManager @@ -88,7 +89,7 @@ class GameManager : public Singleton { * @return 0 Game updated * @return 1 Game not updated (not found) */ - int updateGame(std::string gameName); + int updateGame(const std::string &gameName); /** * @brief Remove a game from the GameManager @@ -97,7 +98,7 @@ class GameManager : public Singleton { * @return 0 Game removed * @return 1 Game not removed (not found) */ - int removeGame(std::string gameName); + int removeGame(const std::string &gameName); /** * @brief List all games present in the GameManager @@ -111,7 +112,7 @@ class GameManager : public Singleton { * @param gameName Game to add the client to * @param client Client to add to the game */ - void addClientToGame(std::string gameName, std::shared_ptr client); + void addClientToGame(const std::string &gameName, std::shared_ptr &client); /** * @brief Remove a client from a game @@ -119,7 +120,7 @@ class GameManager : public Singleton { * @param gameName Game to remove the client from * @param client Client to remove from the game */ - void removeClientFromGame(std::string gameName, std::shared_ptr client); + void removeClientFromGame(const std::string &gameName, const std::shared_ptr &client); /** * @brief Get the index of a client in the waiting queue @@ -128,7 +129,7 @@ class GameManager : public Singleton { * @param client Client to get the index of * @return int Index of the client in the waiting queue */ - int getIndexInWaitingQueue(std::string gameName, std::shared_ptr client); + int getIndexInWaitingQueue(const std::string &gameName, const std::shared_ptr &client); }; } /* namespace Flakkari */ diff --git a/Flakkari/Server/UDPServer.cpp b/Flakkari/Server/UDPServer.cpp index 7399eb18..af6187ba 100644 --- a/Flakkari/Server/UDPServer.cpp +++ b/Flakkari/Server/UDPServer.cpp @@ -11,7 +11,7 @@ using namespace Flakkari; -UDPServer::UDPServer(std::string ip, unsigned short port) +UDPServer::UDPServer(const std::string &gameDir, const std::string &ip, unsigned short port) { Network::init(); @@ -27,7 +27,7 @@ UDPServer::UDPServer(std::string ip, unsigned short port) ClientManager::CreateInstance(_socket); ResourceManager::CreateInstance(); - GameManager::CreateInstance(); + GameManager::CreateInstance(gameDir); } UDPServer::~UDPServer() diff --git a/Flakkari/Server/UDPServer.hpp b/Flakkari/Server/UDPServer.hpp index 89f265ba..d561e02b 100644 --- a/Flakkari/Server/UDPServer.hpp +++ b/Flakkari/Server/UDPServer.hpp @@ -57,10 +57,11 @@ class UDPServer { /** * @brief Construct a new UDPServer object * + * @param gameDir The directory of the games folder * @param ip The ip to bind the server to (default: localhost) * @param port The port to bind the server to (default: 8080) */ - UDPServer(std::string ip = "localhost", unsigned short port = 8080); + UDPServer(const std::string &gameDir, const std::string &ip = "localhost", unsigned short port = 8080); ~UDPServer(); /** diff --git a/Flakkari/core.cpp b/Flakkari/core.cpp index a11d59d2..87b8f756 100644 --- a/Flakkari/core.cpp +++ b/Flakkari/core.cpp @@ -9,11 +9,11 @@ int main(int ac, const char *av[]) { - if (ac != 3) - return FLAKKARI_LOG_ERROR("Usage: ./r-type_server "), 84; + if (ac != 4) + return FLAKKARI_LOG_ERROR("Usage: ./r-type_server "), 84; try { - Flakkari::UDPServer server(av[1], static_cast(std::stoi(av[2]))); + Flakkari::UDPServer server(av[1], av[2], static_cast(std::stoi(av[3]))); server.run(); } catch (const std::exception &e) From 7a5d15b509dccb505e903552c1761405d2225ffb Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 7 Nov 2024 14:20:47 +0000 Subject: [PATCH 13/20] style: apply linter --- Flakkari/Protocol/PacketFactory.hpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Flakkari/Protocol/PacketFactory.hpp b/Flakkari/Protocol/PacketFactory.hpp index 1e66bc0b..a412867e 100644 --- a/Flakkari/Protocol/PacketFactory.hpp +++ b/Flakkari/Protocol/PacketFactory.hpp @@ -102,8 +102,7 @@ class PacketFactory { * @param entity Entity to get the components from. */ template - static void add2dToPacketByEntity(Packet &packet, Engine::ECS::Registry ®istry, - Engine::ECS::Entity entity) + static void add2dToPacketByEntity(Packet &packet, Engine::ECS::Registry ®istry, Engine::ECS::Entity entity) { auto transform = registry.getComponents()[entity]; From 6e2c1d65eeae991a19d499746b3fd3b7e8c54007 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 09:37:05 -0500 Subject: [PATCH 14/20] refactor: implement assignment operators for various component structs --- .../Components/2D/Collider.hpp | 7 +++++++ .../Components/2D/Control.hpp | 13 +++++++++++++ .../Components/2D/Movable.hpp | 10 ++++++++++ .../Components/2D/RigidBody.hpp | 14 ++++++++++++++ .../Components/2D/Transform.hpp | 11 +++++++++++ .../Components/Common/Child.hpp | 7 +++++++ .../Components/Common/Evolve.hpp | 7 +++++++ .../Components/Common/Health.hpp | 12 ++++++++++++ .../Components/Common/Id.hpp | 7 +++++++ .../Components/Common/Level.hpp | 13 +++++++++++++ .../Components/Common/NetworkEvent.hpp | 7 +++++++ .../Components/Common/NetworkIp.hpp | 7 +++++++ .../Components/Common/Parent.hpp | 8 ++++++++ .../Components/Common/Spawned.hpp | 7 +++++++ .../Components/Common/Tag.hpp | 7 +++++++ .../Components/Common/Template.hpp | 7 +++++++ .../Components/Common/Weapon.hpp | 11 +++++++++++ Flakkari/Protocol/PacketFactory.hpp | 16 ---------------- Flakkari/Server/Game/GameManager.cpp | 16 ---------------- Flakkari/Server/Game/GameManager.hpp | 17 ----------------- 20 files changed, 155 insertions(+), 49 deletions(-) diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp index 04f4606c..da5d5115 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp @@ -28,6 +28,13 @@ struct Collider { Collider(Math::Vector2f nsize) : _size(nsize) {} Collider(const Collider &other) : _size(other._size) {} + Collider& operator=(const Collider& other) { + if (this != &other) + _size = other._size; + + return *this; + } + std::size_t size() const { return sizeof(_size); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp index a0290018..12a1297a 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp @@ -38,6 +38,19 @@ struct Control { Control(const Control &other) : up(other.up), down(other.down), left(other.left), right(other.right), shoot(other.shoot){}; + Control& operator=(const Control& other) { + if (this != &other) + { + up = other.up; + down = other.down; + left = other.left; + right = other.right; + shoot = other.shoot; + } + + return *this; + } + std::size_t size() const { return sizeof(*this); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp index 372deedb..deeed31d 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp @@ -24,6 +24,16 @@ struct Movable { : velocity(velocity), acceleration(acceleration){}; Movable(const Movable &other) : velocity(other.velocity), acceleration(other.acceleration){}; + Movable& operator=(const Movable& other) { + if (this != &other) + { + velocity = other.velocity; + acceleration = other.acceleration; + } + + return *this; + } + std::size_t size() const { return sizeof(*this); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp index 2122a01c..d2a5b5e2 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp @@ -35,6 +35,20 @@ struct RigidBody { : mass(mass), restitution(restitution), friction(friction), gravityScale(gravityScale), isGravityAffected(true), isKinematic(false){}; + RigidBody& operator=(const RigidBody& other) { + if (this != &other) + { + mass = other.mass; + restitution = other.restitution; + friction = other.friction; + gravityScale = other.gravityScale; + isGravityAffected = other.isGravityAffected; + isKinematic = other.isKinematic; + } + + return *this; + } + std::size_t size() const { return sizeof(*this); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp index 19c1e280..23c8f435 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp @@ -25,6 +25,17 @@ struct Transform { : position(position), scale(scale), rotation(rotation){}; Transform(const Transform &other) : position(other.position), scale(other.scale), rotation(other.rotation){}; + Transform& operator=(const Transform& other) { + if (this != &other) + { + position = other.position; + scale = other.scale; + rotation = other.rotation; + } + + return *this; + } + std::size_t size() const { return sizeof(*this); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp index f749edfc..44964b18 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp @@ -27,6 +27,13 @@ struct Child { Child(const std::string &nname) : name(nname) {} Child(const Child &other) : name(other.name) {} + Child &operator=(const Child &other) { + if (this != &other) + name = other.name; + + return *this; + } + std::size_t size() const { return name.size(); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp index 3433c786..f53ffb4b 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp @@ -27,6 +27,13 @@ struct Evolve { Evolve(const std::string &nname) : name(nname) {} Evolve(const Evolve &other) : name(other.name) {} + Evolve &operator=(const Evolve &other) { + if (this != &other) + name = other.name; + + return *this; + } + std::size_t size() const { return name.size(); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp index 910678b1..f8e25062 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp @@ -34,6 +34,18 @@ struct Health { : currentHealth(other.currentHealth), maxHealth(other.maxHealth), shield(other.shield), maxShield(other.maxShield){}; + Health& operator=(const Health& other) { + if (this != &other) + { + currentHealth = other.currentHealth; + maxHealth = other.maxHealth; + shield = other.shield; + maxShield = other.maxShield; + } + + return *this; + } + std::size_t size() const { return sizeof(*this); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp index d8dd97ba..fc6f6105 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp @@ -24,6 +24,13 @@ struct Id { Id(std::size_t id) : id(id) {} Id(const Id &other) : id(other.id) {} + Id &operator=(const Id &other) { + if (this != &other) + id = other.id; + + return *this; + } + std::size_t size() const { return sizeof(id); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Level.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Level.hpp index f6805123..aeb5e6c0 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Level.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Level.hpp @@ -38,6 +38,19 @@ struct Level { { } + Level &operator=(const Level &other) + { + if (this != &other) + { + level = other.level; + currentWeapon = other.currentWeapon; + currentExp = other.currentExp; + requiredExp = other.requiredExp; + } + + return *this; + } + std::size_t size() const { return sizeof(level) + currentWeapon.size() + sizeof(currentExp) + sizeof(requiredExp); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp index 70e33bef..521ce009 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp @@ -21,6 +21,13 @@ struct NetworkEvent { NetworkEvent(const NetworkEvent &other) : events(other.events){}; NetworkEvent(const std::vector &events) : events(events){}; + NetworkEvent &operator=(const NetworkEvent &other) { + if (this != &other) + events = other.events; + + return *this; + } + std::size_t size() const { return events.size() * sizeof(unsigned short); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkIp.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkIp.hpp index f6283090..98af95fe 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkIp.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkIp.hpp @@ -21,6 +21,13 @@ struct NetworkIp { NetworkIp(std::string ip) : ip(ip) {} NetworkIp(const NetworkIp &other) : ip(other.ip) {} + NetworkIp &operator=(const NetworkIp &other) { + if (this != &other) + ip = other.ip; + + return *this; + } + std::size_t size() const { return ip.size(); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp index f4517f92..a531e8f3 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp @@ -28,6 +28,14 @@ struct Parent { Parent() : entity(0) {} Parent(const std::size_t &entity) : entity(entity) {} Parent(const Parent &other) : entity(other.entity) {} + + Parent &operator=(const Parent &other) { + if (this != &other) + entity = other.entity; + + return *this; + } + std::size_t size() const { return sizeof(*this); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp index 97ccf8a2..8b17f207 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp @@ -30,6 +30,13 @@ struct Spawned { Spawned(bool spawed) : has_spawned(spawed) {} Spawned(const Spawned &other) : has_spawned(other.has_spawned) {} + Spawned& operator=(const Spawned& other) { + if (this != &other) + has_spawned = other.has_spawned; + + return *this; + } + std::size_t size() const { return sizeof(has_spawned); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp index eb4e0c85..0c2ce994 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp @@ -26,6 +26,13 @@ struct Tag { Tag(const std::string &ntag) : tag(ntag) {} Tag(const Tag &other) : tag(other.tag) {} + Tag &operator=(const Tag &other) { + if (this != &other) + tag = other.tag; + + return *this; + } + std::size_t size() const { return tag.size(); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Template.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Template.hpp index 30e6f9d2..0c8074e1 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Template.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Template.hpp @@ -21,6 +21,13 @@ struct Template { Template(const std::string &nname) : name(nname) {} Template(const Template &other) : name(other.name) {} + Template &operator=(const Template &other) { + if (this != &other) + name = other.name; + + return *this; + } + std::size_t size() const { return name.size(); } }; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp index cd31d2e0..2ff81d2a 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp @@ -43,6 +43,17 @@ struct Weapon { Weapon(const Weapon &other) = default; Weapon(std::size_t dmg, float rate, std::size_t lvl) : damage(dmg), fireRate(rate), level(lvl){}; + Weapon &operator=(const Weapon &other) { + if (this != &other) + { + damage = other.damage; + fireRate = other.fireRate; + level = other.level; + } + + return *this; + } + std::size_t size() const { return sizeof(*this); }; }; diff --git a/Flakkari/Protocol/PacketFactory.hpp b/Flakkari/Protocol/PacketFactory.hpp index a412867e..94e18aed 100644 --- a/Flakkari/Protocol/PacketFactory.hpp +++ b/Flakkari/Protocol/PacketFactory.hpp @@ -266,22 +266,6 @@ class PacketFactory { add2dToPacketByEntity(packet, registry, entity); } - /** - * @brief Add requirement information for Command that use components. - * @tparam Id Type of the entity id. - * @param packet Packet to add the components to. - * @param size Size of the packet. - * @param sceneName Name of the scene. - * @param entity Entity to get the components from. - */ - template - static void addInfoToPacket(Packet &packet, std::size_t size, const std::string &sceneName, - Engine::ECS::Entity entity) - { - packet.injectString(sceneName); - packet << entity; - } - struct UpdateMovement { Engine::ECS::Entity entity; Engine::ECS::Components::_2D::Transform pos; diff --git a/Flakkari/Server/Game/GameManager.cpp b/Flakkari/Server/Game/GameManager.cpp index 817299bd..dd1bce8a 100644 --- a/Flakkari/Server/Game/GameManager.cpp +++ b/Flakkari/Server/Game/GameManager.cpp @@ -72,22 +72,6 @@ int GameManager::addGame(const std::string &gameName) return 0; } -const std::shared_ptr &GameManager::getGame(const std::string &gameName) -{ - if (_gamesStore.find(gameName) == _gamesStore.end()) - return FLAKKARI_LOG_ERROR("game not found"), nullptr; - return std::make_shared(gameName, _gamesStore[gameName]); -} - -const std::vector> &GameManager::getGamesInstances() -{ - std::vector> gamesInstances(_gamesInstances.size()); - - for (auto &game : _gamesInstances) - gamesInstances.insert(gamesInstances.end(), game.second.begin(), game.second.end()); - return gamesInstances; -} - int GameManager::updateGame(const std::string &gameName) { if (_gamesStore.find(gameName) == _gamesStore.end()) diff --git a/Flakkari/Server/Game/GameManager.hpp b/Flakkari/Server/Game/GameManager.hpp index b392fb33..1f132c89 100644 --- a/Flakkari/Server/Game/GameManager.hpp +++ b/Flakkari/Server/Game/GameManager.hpp @@ -65,23 +65,6 @@ class GameManager : public Singleton { */ int addGame(const std::string &gameName); - /** - * @brief Get the Game object - * - * @param gameName Game to get - * @return std::shared_ptr Game - * - * @deprecated Use getGameInstance instead - */ - const std::shared_ptr &getGame(const std::string &gameName); - - /** - * @brief Get the Games Instances object (all games loaded) - * - * @return std::vector> Games Instances - */ - const std::vector> &getGamesInstances(); - /** * @brief Update a game from the GameManager * From 8224c8f4374b93744ce6149942a5e84598be7417 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 09:52:12 -0500 Subject: [PATCH 15/20] refactor: update event handling to use size_t and unsigned short for better type safety --- Flakkari/Server/Game/Game.cpp | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Flakkari/Server/Game/Game.cpp b/Flakkari/Server/Game/Game.cpp index 9331e8a5..889b7e9a 100644 --- a/Flakkari/Server/Game/Game.cpp +++ b/Flakkari/Server/Game/Game.cpp @@ -307,9 +307,9 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetup) { - if (netEvent->events.size() < int(event.id)) - netEvent->events.resize(int(event.id) + 1); - netEvent->events[int(event.id)] = int(event.state); + if (netEvent->events.size() < size_t(event.id)) + netEvent->events.resize(size_t(event.id) + 1); + netEvent->events[size_t(event.id)] = (unsigned short)event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); @@ -322,9 +322,9 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetdown) { - if (netEvent->events.size() < int(event.id)) - netEvent->events.resize(int(event.id) + 1); - netEvent->events[int(event.id)] = int(event.state); + if (netEvent->events.size() < size_t(event.id)) + netEvent->events.resize(size_t(event.id) + 1); + netEvent->events[size_t(event.id)] = (unsigned short)event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); @@ -337,9 +337,9 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetleft) { - if (netEvent->events.size() < int(event.id)) - netEvent->events.resize(int(event.id) + 1); - netEvent->events[int(event.id)] = int(event.state); + if (netEvent->events.size() < size_t(event.id)) + netEvent->events.resize(size_t(event.id) + 1); + netEvent->events[size_t(event.id)] = (unsigned short)event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); @@ -352,9 +352,9 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetright) { - if (netEvent->events.size() < int(event.id)) - netEvent->events.resize(int(event.id) + 1); - netEvent->events[int(event.id)] = int(event.state); + if (netEvent->events.size() < size_t(event.id)) + netEvent->events.resize(size_t(event.id) + 1); + netEvent->events[size_t(event.id)] = (unsigned short)event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); @@ -367,9 +367,9 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetshoot) { - if (netEvent->events.size() < int(event.id)) - netEvent->events.resize(int(event.id) + 1); - netEvent->events[int(event.id)] = int(event.state); + if (netEvent->events.size() < size_t(event.id)) + netEvent->events.resize(size_t(event.id) + 1); + netEvent->events[size_t(event.id)] = (unsigned short)event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); From deaaf670ed40a6c2be1139c399444fb2fedf61b7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 7 Nov 2024 14:52:41 +0000 Subject: [PATCH 16/20] style: apply linter --- .../EntityComponentSystem/Components/2D/Collider.hpp | 3 ++- .../EntityComponentSystem/Components/2D/Control.hpp | 3 ++- .../EntityComponentSystem/Components/2D/Movable.hpp | 3 ++- .../EntityComponentSystem/Components/2D/RigidBody.hpp | 3 ++- .../EntityComponentSystem/Components/2D/Transform.hpp | 3 ++- .../EntityComponentSystem/Components/Common/Child.hpp | 3 ++- .../EntityComponentSystem/Components/Common/Evolve.hpp | 3 ++- .../EntityComponentSystem/Components/Common/Health.hpp | 3 ++- .../EntityComponentSystem/Components/Common/Id.hpp | 3 ++- .../Components/Common/NetworkEvent.hpp | 3 ++- .../Components/Common/NetworkIp.hpp | 3 ++- .../EntityComponentSystem/Components/Common/Parent.hpp | 3 ++- .../Components/Common/Spawned.hpp | 3 ++- .../EntityComponentSystem/Components/Common/Tag.hpp | 3 ++- .../Components/Common/Template.hpp | 3 ++- .../EntityComponentSystem/Components/Common/Weapon.hpp | 3 ++- Flakkari/Server/Game/Game.cpp | 10 +++++----- 17 files changed, 37 insertions(+), 21 deletions(-) diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp index da5d5115..2fd5cc10 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp @@ -28,7 +28,8 @@ struct Collider { Collider(Math::Vector2f nsize) : _size(nsize) {} Collider(const Collider &other) : _size(other._size) {} - Collider& operator=(const Collider& other) { + Collider &operator=(const Collider &other) + { if (this != &other) _size = other._size; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp index 12a1297a..0157a984 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp @@ -38,7 +38,8 @@ struct Control { Control(const Control &other) : up(other.up), down(other.down), left(other.left), right(other.right), shoot(other.shoot){}; - Control& operator=(const Control& other) { + Control &operator=(const Control &other) + { if (this != &other) { up = other.up; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp index deeed31d..1feeb760 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp @@ -24,7 +24,8 @@ struct Movable { : velocity(velocity), acceleration(acceleration){}; Movable(const Movable &other) : velocity(other.velocity), acceleration(other.acceleration){}; - Movable& operator=(const Movable& other) { + Movable &operator=(const Movable &other) + { if (this != &other) { velocity = other.velocity; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp index d2a5b5e2..4336cb6d 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp @@ -35,7 +35,8 @@ struct RigidBody { : mass(mass), restitution(restitution), friction(friction), gravityScale(gravityScale), isGravityAffected(true), isKinematic(false){}; - RigidBody& operator=(const RigidBody& other) { + RigidBody &operator=(const RigidBody &other) + { if (this != &other) { mass = other.mass; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp index 23c8f435..6b986304 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp @@ -25,7 +25,8 @@ struct Transform { : position(position), scale(scale), rotation(rotation){}; Transform(const Transform &other) : position(other.position), scale(other.scale), rotation(other.rotation){}; - Transform& operator=(const Transform& other) { + Transform &operator=(const Transform &other) + { if (this != &other) { position = other.position; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp index 44964b18..e4c23db3 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Child.hpp @@ -27,7 +27,8 @@ struct Child { Child(const std::string &nname) : name(nname) {} Child(const Child &other) : name(other.name) {} - Child &operator=(const Child &other) { + Child &operator=(const Child &other) + { if (this != &other) name = other.name; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp index f53ffb4b..13c7708a 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Evolve.hpp @@ -27,7 +27,8 @@ struct Evolve { Evolve(const std::string &nname) : name(nname) {} Evolve(const Evolve &other) : name(other.name) {} - Evolve &operator=(const Evolve &other) { + Evolve &operator=(const Evolve &other) + { if (this != &other) name = other.name; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp index f8e25062..3ed30c1a 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp @@ -34,7 +34,8 @@ struct Health { : currentHealth(other.currentHealth), maxHealth(other.maxHealth), shield(other.shield), maxShield(other.maxShield){}; - Health& operator=(const Health& other) { + Health &operator=(const Health &other) + { if (this != &other) { currentHealth = other.currentHealth; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp index fc6f6105..7d2502a7 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp @@ -24,7 +24,8 @@ struct Id { Id(std::size_t id) : id(id) {} Id(const Id &other) : id(other.id) {} - Id &operator=(const Id &other) { + Id &operator=(const Id &other) + { if (this != &other) id = other.id; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp index 521ce009..859b4f6c 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkEvent.hpp @@ -21,7 +21,8 @@ struct NetworkEvent { NetworkEvent(const NetworkEvent &other) : events(other.events){}; NetworkEvent(const std::vector &events) : events(events){}; - NetworkEvent &operator=(const NetworkEvent &other) { + NetworkEvent &operator=(const NetworkEvent &other) + { if (this != &other) events = other.events; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkIp.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkIp.hpp index 98af95fe..6e9990ad 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkIp.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/NetworkIp.hpp @@ -21,7 +21,8 @@ struct NetworkIp { NetworkIp(std::string ip) : ip(ip) {} NetworkIp(const NetworkIp &other) : ip(other.ip) {} - NetworkIp &operator=(const NetworkIp &other) { + NetworkIp &operator=(const NetworkIp &other) + { if (this != &other) ip = other.ip; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp index a531e8f3..87c24fed 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp @@ -29,7 +29,8 @@ struct Parent { Parent(const std::size_t &entity) : entity(entity) {} Parent(const Parent &other) : entity(other.entity) {} - Parent &operator=(const Parent &other) { + Parent &operator=(const Parent &other) + { if (this != &other) entity = other.entity; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp index 8b17f207..527ff653 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp @@ -30,7 +30,8 @@ struct Spawned { Spawned(bool spawed) : has_spawned(spawed) {} Spawned(const Spawned &other) : has_spawned(other.has_spawned) {} - Spawned& operator=(const Spawned& other) { + Spawned &operator=(const Spawned &other) + { if (this != &other) has_spawned = other.has_spawned; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp index 0c2ce994..97561777 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Tag.hpp @@ -26,7 +26,8 @@ struct Tag { Tag(const std::string &ntag) : tag(ntag) {} Tag(const Tag &other) : tag(other.tag) {} - Tag &operator=(const Tag &other) { + Tag &operator=(const Tag &other) + { if (this != &other) tag = other.tag; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Template.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Template.hpp index 0c8074e1..9cff97b1 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Template.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Template.hpp @@ -21,7 +21,8 @@ struct Template { Template(const std::string &nname) : name(nname) {} Template(const Template &other) : name(other.name) {} - Template &operator=(const Template &other) { + Template &operator=(const Template &other) + { if (this != &other) name = other.name; diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp index 2ff81d2a..34ef415f 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp @@ -43,7 +43,8 @@ struct Weapon { Weapon(const Weapon &other) = default; Weapon(std::size_t dmg, float rate, std::size_t lvl) : damage(dmg), fireRate(rate), level(lvl){}; - Weapon &operator=(const Weapon &other) { + Weapon &operator=(const Weapon &other) + { if (this != &other) { damage = other.damage; diff --git a/Flakkari/Server/Game/Game.cpp b/Flakkari/Server/Game/Game.cpp index 889b7e9a..d048f716 100644 --- a/Flakkari/Server/Game/Game.cpp +++ b/Flakkari/Server/Game/Game.cpp @@ -309,7 +309,7 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetevents.size() < size_t(event.id)) netEvent->events.resize(size_t(event.id) + 1); - netEvent->events[size_t(event.id)] = (unsigned short)event.state; + netEvent->events[size_t(event.id)] = (unsigned short) event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); @@ -324,7 +324,7 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetevents.size() < size_t(event.id)) netEvent->events.resize(size_t(event.id) + 1); - netEvent->events[size_t(event.id)] = (unsigned short)event.state; + netEvent->events[size_t(event.id)] = (unsigned short) event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); @@ -339,7 +339,7 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetevents.size() < size_t(event.id)) netEvent->events.resize(size_t(event.id) + 1); - netEvent->events[size_t(event.id)] = (unsigned short)event.state; + netEvent->events[size_t(event.id)] = (unsigned short) event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); @@ -354,7 +354,7 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetevents.size() < size_t(event.id)) netEvent->events.resize(size_t(event.id) + 1); - netEvent->events[size_t(event.id)] = (unsigned short)event.state; + netEvent->events[size_t(event.id)] = (unsigned short) event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); @@ -369,7 +369,7 @@ void Game::handleEvent(std::shared_ptr player, Protocol::Packetevents.size() < size_t(event.id)) netEvent->events.resize(size_t(event.id) + 1); - netEvent->events[size_t(event.id)] = (unsigned short)event.state; + netEvent->events[size_t(event.id)] = (unsigned short) event.state; FLAKKARI_LOG_INFO("event: " + std::to_string(int(event.id)) + " " + std::to_string(int(event.state))); From b993a1ce9ee110639602f67edd5cfa81009774c3 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Thu, 7 Nov 2024 22:38:08 -0500 Subject: [PATCH 17/20] refactor: update WSA class to improve socket handling and error management --- Flakkari/Network/IOMultiplexer.cpp | 82 +++++++++++++++++------------- Flakkari/Network/IOMultiplexer.hpp | 35 +++++++++---- 2 files changed, 74 insertions(+), 43 deletions(-) diff --git a/Flakkari/Network/IOMultiplexer.cpp b/Flakkari/Network/IOMultiplexer.cpp index 31b86000..2e6da583 100644 --- a/Flakkari/Network/IOMultiplexer.cpp +++ b/Flakkari/Network/IOMultiplexer.cpp @@ -182,24 +182,29 @@ bool PPOLL::isReady(FileDescriptor socket) return false; } +bool PPOLL::skipableError() { return errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK; } + #endif #if defined(_WSA_) -WSA::WSA(long int seconds, long int microseconds) +WSA::WSA(FileDescriptor socket, int seconds, int microseconds) { - _timeoutInMs = seconds * 1000 + microseconds / 1000; // Convert to milliseconds - _hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); // Create a manual-reset event - if (_hEvent == NULL) - throw std::runtime_error("Failed to create event."); -} + if (socket == -1) + FLAKKARI_LOG_FATAL("Socket is -1"); -WSA::~WSA() -{ - for (auto &socket : _sockets) - WSAEventSelect(socket, NULL, 0); + _sockets.reserve(MAX_POLLFD); + _fdArray.reserve(MAX_POLLFD); + _freeSpace.reserve(MAX_POLLFD); - CloseHandle(_hEvent); + _timeoutInMs = seconds * 1000 + microseconds / 1000; + + WSAPOLLFD pollFd; + pollFd.fd = socket; + pollFd.events = POLLIN | POLLOUT; + pollFd.revents = 0; + _fdArray.emplace_back(pollFd); + _sockets.emplace_back(socket); } void WSA::addSocket(FileDescriptor socket) @@ -207,12 +212,24 @@ void WSA::addSocket(FileDescriptor socket) if (socket == -1) throw std::runtime_error("Socket is -1"); - if (_events.find(socket) != _events.end()) - throw std::runtime_error("Socket already added."); + if (std::find(_sockets.begin(), _sockets.end(), socket) != _sockets.end()) + return; - _events[socket] = _hEvent; - WSAEventSelect(socket, _hEvent, FD_READ | FD_ACCEPT); - _sockets.push_back(socket); + WSAPOLLFD pollFd; + pollFd.fd = socket; + pollFd.events = POLLIN | POLLOUT; + pollFd.revents = 0; + if (_freeSpace.empty()) + { + _fdArray.emplace_back(pollFd); + _sockets.emplace_back(socket); + return; + } + + size_t index = _freeSpace.back(); + _fdArray[index] = pollFd; + _sockets[index] = socket; + _freeSpace.pop_back(); } void WSA::removeSocket(FileDescriptor socket) @@ -220,26 +237,19 @@ void WSA::removeSocket(FileDescriptor socket) if (socket == -1) throw std::runtime_error("Socket is -1"); - auto it = std::remove(_sockets.begin(), _sockets.end(), socket); - if (it != _sockets.end()) - { - WSAEventSelect(socket, NULL, 0); - _sockets.erase(it, _sockets.end()); - _events.erase(socket); - } + auto it = std::find(_sockets.begin(), _sockets.end(), socket); + if (it == _sockets.end()) + throw std::runtime_error("Socket not found"); + + size_t index = std::distance(_sockets.begin(), it); + _fdArray[index].fd = 0; + _sockets[index] = 0; + _freeSpace.emplace_back(index); } int WSA::wait() { - DWORD waitResult = WSAWaitForMultipleEvents(1, &_hEvent, FALSE, _timeoutInMs, FALSE); - if (waitResult == WAIT_FAILED) - return -1; - else if (waitResult == WAIT_TIMEOUT) - return 0; - - WSAResetEvent(_hEvent); - - return static_cast(_sockets.size()); + return WSAPoll(_fdArray.data(), (ULONG)_fdArray.size(), _timeoutInMs); } bool WSA::isReady(FileDescriptor socket) @@ -247,8 +257,12 @@ bool WSA::isReady(FileDescriptor socket) if (socket == -1) throw std::runtime_error("Socket is -1"); - DWORD result = WSAEnumNetworkEvents(socket, _events[socket], nullptr); - return (result == 0); + auto it = std::find(_sockets.begin(), _sockets.end(), socket); + if (it == _sockets.end()) + throw std::runtime_error("Socket not found"); + + size_t index = std::distance(_sockets.begin(), it); + return _fdArray[index].revents & (POLLIN | POLLOUT); } bool WSA::skipableError() diff --git a/Flakkari/Network/IOMultiplexer.hpp b/Flakkari/Network/IOMultiplexer.hpp index 1484f2cc..6b887904 100644 --- a/Flakkari/Network/IOMultiplexer.hpp +++ b/Flakkari/Network/IOMultiplexer.hpp @@ -210,8 +210,8 @@ class PPOLL { pollfd &operator[](std::size_t index); pollfd &operator[](FileDescriptor socket); - std::vector::iterator begin() { return _pollfds.begin(); } - std::vector::iterator end() { return _pollfds.end(); } + std::vector::const_iterator begin() const { return _pollfds.begin(); } + std::vector::const_iterator end() const { return _pollfds.end(); } /** * @brief Check if a socket is ready to read from @@ -231,6 +231,14 @@ class PPOLL { */ [[nodiscard]] bool isReady(FileDescriptor socket); + /** + * @brief Check if the error is skipable + * + * @return true If the error is skipable + * @return false If the error is not skipable + */ + [[nodiscard]] bool skipableError(); + protected: private: std::vector _pollfds; @@ -240,6 +248,8 @@ class PPOLL { #if defined(_WSA_) +#define MAX_POLLFD 1024 + /** * @brief WSA is a class that represents a WSA * @@ -272,8 +282,15 @@ class WSA { using FileDescriptor = SOCKET; public: - WSA(long int seconds = 1, long int microseconds = 0); - ~WSA(); + /** + * @brief Construct a new WSA object with a timeout of 1 second by default + * + * @param socket The server socket + * @param seconds The seconds to wait for an event + * @param microseconds The microseconds to wait for an event + */ + WSA(FileDescriptor socket, int seconds = 1, int microseconds = 0); + ~WSA() = default; /** * @brief Add a socket to the WSA list @@ -297,8 +314,8 @@ class WSA { */ int wait(); - std::vector::iterator begin() { return _sockets.begin(); } - std::vector::iterator end() { return _sockets.end(); } + std::vector::const_iterator begin() const { return _sockets.cbegin(); } + std::vector::const_iterator end() const { return _sockets.cend(); } /** * @brief Check if a socket is ready to read from @@ -320,9 +337,9 @@ class WSA { protected: private: std::vector _sockets; - std::unordered_map _events; - HANDLE _hEvent; - long int _timeoutInMs; + std::vector _fdArray; + std::vector _freeSpace; + INT _timeoutInMs; }; #endif From 9718db5aca78f45c522bffb3a920b1fabe434bf8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 8 Nov 2024 03:38:31 +0000 Subject: [PATCH 18/20] style: apply linter --- Flakkari/Network/IOMultiplexer.cpp | 5 +---- Flakkari/Network/IOMultiplexer.hpp | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/Flakkari/Network/IOMultiplexer.cpp b/Flakkari/Network/IOMultiplexer.cpp index 2e6da583..fb3206a7 100644 --- a/Flakkari/Network/IOMultiplexer.cpp +++ b/Flakkari/Network/IOMultiplexer.cpp @@ -247,10 +247,7 @@ void WSA::removeSocket(FileDescriptor socket) _freeSpace.emplace_back(index); } -int WSA::wait() -{ - return WSAPoll(_fdArray.data(), (ULONG)_fdArray.size(), _timeoutInMs); -} +int WSA::wait() { return WSAPoll(_fdArray.data(), (ULONG) _fdArray.size(), _timeoutInMs); } bool WSA::isReady(FileDescriptor socket) { diff --git a/Flakkari/Network/IOMultiplexer.hpp b/Flakkari/Network/IOMultiplexer.hpp index 6b887904..9882f956 100644 --- a/Flakkari/Network/IOMultiplexer.hpp +++ b/Flakkari/Network/IOMultiplexer.hpp @@ -248,7 +248,7 @@ class PPOLL { #if defined(_WSA_) -#define MAX_POLLFD 1024 +# define MAX_POLLFD 1024 /** * @brief WSA is a class that represents a WSA From c2a70c379c3fb9c60798fd2c290922c8d4cb8e05 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Fri, 8 Nov 2024 00:39:14 -0500 Subject: [PATCH 19/20] refactor: replace PACKED macros with LPL_PACKED macros for better struct packing --- .../Components/2D/Collider.hpp | 4 +- .../Components/2D/Control.hpp | 4 +- .../Components/2D/Movable.hpp | 4 +- .../Components/2D/RigidBody.hpp | 4 +- .../Components/2D/Transform.hpp | 4 +- .../Components/Common/Health.hpp | 4 +- .../Components/Common/Id.hpp | 4 +- .../Components/Common/Parent.hpp | 4 +- .../Components/Common/Spawned.hpp | 4 +- .../Components/Common/Weapon.hpp | 4 +- Flakkari/Engine/Math/Vector.hpp | 4 +- Flakkari/Network/Packed.hpp | 41 +++++++++++++ Flakkari/Protocol/Events.hpp | 4 +- Flakkari/Protocol/Header.hpp | 4 +- Flakkari/config.h.in | 60 +++++++++---------- 15 files changed, 97 insertions(+), 56 deletions(-) create mode 100644 Flakkari/Network/Packed.hpp diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp index 2fd5cc10..3ad413e0 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Collider.hpp @@ -14,7 +14,7 @@ #include namespace Flakkari::Engine::ECS::Components::_2D { -PACKED_START +LPL_PACKED_START /** * @brief Collider component for ECS entities that have a script attached to them @@ -39,7 +39,7 @@ struct Collider { std::size_t size() const { return sizeof(_size); } }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::_2D #endif /* !COLLIDER_HPP_ */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp index 0157a984..ec22c8ba 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Control.hpp @@ -13,7 +13,7 @@ #include "../../../Math/Vector.hpp" namespace Flakkari::Engine::ECS::Components::_2D { -PACKED_START +LPL_PACKED_START /** * @brief Control component for 2D entities (player, enemies, etc...) @@ -55,7 +55,7 @@ struct Control { std::size_t size() const { return sizeof(*this); } }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::_2D #endif /* !FLAKKARI_CONTROL_HPP_ */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp index 1feeb760..92c1d1fe 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Movable.hpp @@ -13,7 +13,7 @@ #include "../../../Math/Vector.hpp" namespace Flakkari::Engine::ECS::Components::_2D { -PACKED_START +LPL_PACKED_START struct Movable { Math::Vector2f velocity; // pixels / second @@ -38,7 +38,7 @@ struct Movable { std::size_t size() const { return sizeof(*this); } }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::_2D #endif /* !FLAKKARI_MOVABLE_HPP_ */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp index 4336cb6d..da9214cc 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/RigidBody.hpp @@ -13,7 +13,7 @@ #include "../../../Math/Vector.hpp" namespace Flakkari::Engine::ECS::Components::_2D { -PACKED_START +LPL_PACKED_START /** * @brief RigidBody represent the physical properties of a rigid body in a game engine @@ -53,7 +53,7 @@ struct RigidBody { std::size_t size() const { return sizeof(*this); } }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::_2D #endif /* !RIGIDBODY_HPP_ */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp b/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp index 6b986304..012445a9 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/2D/Transform.hpp @@ -13,7 +13,7 @@ #include "../../../Math/Vector.hpp" namespace Flakkari::Engine::ECS::Components::_2D { -PACKED_START +LPL_PACKED_START struct Transform { Math::Vector2f position; @@ -40,7 +40,7 @@ struct Transform { std::size_t size() const { return sizeof(*this); } }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::_2D #endif /* !FLAKKARI_TRANSFORM_HPP_ */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp index 3ed30c1a..a967e4aa 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Health.hpp @@ -15,7 +15,7 @@ #include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { -PACKED_START +LPL_PACKED_START /** * @brief Health is a structure that represents the life of an "living object" @@ -50,7 +50,7 @@ struct Health { std::size_t size() const { return sizeof(*this); } }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::Common #endif /* !Health_HPP_ */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp index 7d2502a7..3a65fe60 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Id.hpp @@ -15,7 +15,7 @@ #include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { -PACKED_START +LPL_PACKED_START struct Id { std::size_t id; @@ -35,7 +35,7 @@ struct Id { std::size_t size() const { return sizeof(id); } }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::Common #endif /* !FLAKKARI_ID_HPP_ */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp index 87c24fed..b5ca6ef8 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Parent.hpp @@ -15,7 +15,7 @@ #include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { -PACKED_START +LPL_PACKED_START /** * @brief Parent component for ECS entities that have a parent entity attached to them @@ -40,7 +40,7 @@ struct Parent { std::size_t size() const { return sizeof(*this); } }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::Common #endif /* !FLAKKARI_PARENT_HPP_ */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp index 527ff653..a536edb0 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Spawned.hpp @@ -16,7 +16,7 @@ #include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { -PACKED_START +LPL_PACKED_START /** * @brief Spawned component for ECS entities that have a script attached to them @@ -41,7 +41,7 @@ struct Spawned { std::size_t size() const { return sizeof(has_spawned); } }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::Common #endif /* !SPAWNED_HPP_ */ diff --git a/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp b/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp index 34ef415f..d3d01924 100644 --- a/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp +++ b/Flakkari/Engine/EntityComponentSystem/Components/Common/Weapon.hpp @@ -16,7 +16,7 @@ #include "config.h.in" namespace Flakkari::Engine::ECS::Components::Common { -PACKED_START +LPL_PACKED_START /** * @brief Weapon is a structure that defines the characteristics of a weapon. @@ -58,7 +58,7 @@ struct Weapon { std::size_t size() const { return sizeof(*this); }; }; -PACKED_END +LPL_PACKED_END } // namespace Flakkari::Engine::ECS::Components::Common #endif /* !WEAPON_HPP_ */ diff --git a/Flakkari/Engine/Math/Vector.hpp b/Flakkari/Engine/Math/Vector.hpp index 29bc308e..06e011b0 100644 --- a/Flakkari/Engine/Math/Vector.hpp +++ b/Flakkari/Engine/Math/Vector.hpp @@ -27,7 +27,7 @@ namespace Flakkari::Engine::Math { template struct Vector { - PACKED_START + LPL_PACKED_START union { struct { Type x; @@ -56,7 +56,7 @@ template struct Vector { Vector(Type x, Type y) : v{x, y, 0, 1} {}; Vector(Type x) : v{x, 0, 0, 1} {}; Vector(const Vector &other) : v{other.v[0], other.v[1], other.v[2], other.v[3]} {}; - PACKED_END + LPL_PACKED_END Vector &operator=(const Vector &other) { diff --git a/Flakkari/Network/Packed.hpp b/Flakkari/Network/Packed.hpp new file mode 100644 index 00000000..d68e227f --- /dev/null +++ b/Flakkari/Network/Packed.hpp @@ -0,0 +1,41 @@ +/************************************************************************** + * Flakkari Library v0.3.0 + * + * Flakkari Library is a C++ Library for Network. + * @file Packed.hpp + * @brief Packed header. Contains PACKED macros. + * (LPL_PACKED_START, LPL_PACKED_END, PACKED) + * + * @details LPL_PACKED_START and LPL_PACKED_END macros are used to pack structs: + * PACKED_<_> macros are used to pack structs: + * LPL_PACKED_START struct _ {}; LPL_PACKED_END + * PACKED macros are used to pack structs: + * struct _ {} PACKED; + * + * Flakkari Library is under MIT License. + * https://opensource.org/licenses/MIT + * © 2023 @MasterLaplace + * @version 0.3.0 + * @date 2023-01-10 + **************************************************************************/ + +#ifndef PACKED_HPP_ +#define PACKED_HPP_ + +#ifdef LPL_PACKED_START +# undef LPL_PACKED_START +#endif + +#ifdef LPL_PACKED_END +# undef LPL_PACKED_END +#endif + +#ifdef _MSC_VER +# define LPL_PACKED_START __pragma(pack(push, 1)) +# define LPL_PACKED_END __pragma(pack(pop)) +#else +# define LPL_PACKED_START _Pragma("pack(1)") +# define LPL_PACKED_END _Pragma("pack()") +#endif + +#endif /* !PACKED_HPP_ */ diff --git a/Flakkari/Protocol/Events.hpp b/Flakkari/Protocol/Events.hpp index 86272e37..0c3b1d8e 100644 --- a/Flakkari/Protocol/Events.hpp +++ b/Flakkari/Protocol/Events.hpp @@ -39,14 +39,14 @@ enum class EventState : uint8_t { MAX_STATE }; -PACKED_START +LPL_PACKED_START struct Event { EventId id; EventState state; }; -PACKED_END +LPL_PACKED_END } /* namespace V_0 */ diff --git a/Flakkari/Protocol/Header.hpp b/Flakkari/Protocol/Header.hpp index 2d1d0c70..f4fa79bf 100644 --- a/Flakkari/Protocol/Header.hpp +++ b/Flakkari/Protocol/Header.hpp @@ -57,7 +57,7 @@ enum class Priority : byte { MAX_PRIORITY = 4 }; -PACKED_START +LPL_PACKED_START template struct Header { Priority _priority : 4 = Priority::LOW; @@ -69,7 +69,7 @@ template struct Header { .count()); }; -PACKED_END +LPL_PACKED_END } // namespace V_0 diff --git a/Flakkari/config.h.in b/Flakkari/config.h.in index c46553ce..c812d19b 100644 --- a/Flakkari/config.h.in +++ b/Flakkari/config.h.in @@ -36,32 +36,32 @@ #endif -#ifndef CONFIG_UTILS - #define CONFIG_UTILS +#ifndef LAPLACE_CONFIG_UTILS + #define LAPLACE_CONFIG_UTILS //////////////////////////////////////////////////////////// // Define shared portable macros for various compilers //////////////////////////////////////////////////////////// -#define NEED_COMMA struct _ -#define ATTRIBUTE(key) __attribute__((key)) -#define UNUSED_ATTRIBUTE ATTRIBUTE(unused) -#define UNUSED(x) (void)(x) +#define LPL_NEED_COMMA struct _ +#define LPL_ATTRIBUTE(key) __attribute__((key)) +#define LPL_UNUSED_ATTRIBUTE LPL_ATTRIBUTE(unused) +#define LPL_UNUSED(x) (void)(x) //////////////////////////////////////////////////////////// // Define portable NULL pointer using C++11 nullptr keyword //////////////////////////////////////////////////////////// #if defined(__cplusplus) && __cplusplus >= 201103L + #define lpl_nullptr nullptr #elif !defined(NULL) - #define nullptr ((void*)0) + #define lpl_nullptr ((void*)0) #else - #define nullptr NULL + #define lpl_nullptr NULL #endif //////////////////////////////////////////////////////////// // Define boolean type and values //////////////////////////////////////////////////////////// -#if defined(__cplusplus) -#elif !defined(__bool_true_false_are_defined) +#if !defined(__bool_true_false_are_defined) && !defined(__cplusplus) #define bool _Bool #define true 1 #define false 0 @@ -71,7 +71,7 @@ #if defined __GNUC__ && defined __GNUC_MINOR__ # define __GNUC_PREREQ(maj, min) \ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) -#else +#elif !defined(__GNUC_PREREQ) # define __GNUC_PREREQ(maj, min) 0 #endif @@ -80,34 +80,34 @@ //////////////////////////////////////////////////////////// /** Usage: * @example - * PACKED(struct MyStruct + * LPL_PACKED(struct MyStruct * { * int a; * char b; * ... * }); \**********************************************************/ -#if defined(__GNUC__) || defined(__GNUG__) - #define PACKED( __Declaration__ ) __Declaration__ __attribute__((__packed__)) - #define PACKED_START _Pragma("pack(1)") - #define PACKED_END _Pragma("pack()") -#elif _MSC_VER - #define PACKED( __Declaration__ ) __pragma(pack(push, 1)) __Declaration__ __pragma(pack(pop)) - #define PACKED_START __pragma(pack(push, 1)) - #define PACKED_END __pragma(pack(pop)) +#if defined(_MSC_VER) || defined(_MSVC_LANG) + #define LPL_PACKED( __Declaration__ ) __pragma(pack(push, 1)) __Declaration__ __pragma(pack(pop)) + #define LPL_PACKED_START __pragma(pack(push, 1)) + #define LPL_PACKED_END __pragma(pack(pop)) +#elif defined(__GNUC__) || defined(__GNUG__) + #define LPL_PACKED( __Declaration__ ) __Declaration__ __attribute__((__packed__)) + #define LPL_PACKED_START _Pragma("pack(1)") + #define LPL_PACKED_END _Pragma("pack()") #else - #define PACKED( __Declaration__ ) __Declaration__ - #define PACKED_START _Pragma("pack(1)") - #define PACKED_END _Pragma("pack()") + #define LPL_PACKED( __Declaration__ ) __Declaration__ + #define LPL_PACKED_START + #define LPL_PACKED_END #endif //////////////////////////////////////////////////////////// // Helper macro to convert a macro to a string //////////////////////////////////////////////////////////// -#define STRINGIFY(x) #x -#define TOSTRING(x) STRINGIFY(x) +#define LPL_STRINGIFY(x) #x +#define LPL_TOSTRING(x) LPL_STRINGIFY(x) -#endif /* !CONFIG_UTILS */ +#endif /* !LAPLACE_CONFIG_UTILS */ #ifndef FLAKKARI_DISTRIBUTION_H_ @@ -474,10 +474,10 @@ // Define the FLAKKARI version string //////////////////////////////////////////////////////////// #define FLAKKARI_VERSION_STRING \ - TOSTRING(FLAKKARI_VERSION_MAJOR) "." \ - TOSTRING(FLAKKARI_VERSION_MINOR) "." \ - TOSTRING(FLAKKARI_VERSION_PATCH) "." \ - TOSTRING(FLAKKARI_VERSION_TWEAK) + LPL_TOSTRING(FLAKKARI_VERSION_MAJOR) "." \ + LPL_TOSTRING(FLAKKARI_VERSION_MINOR) "." \ + LPL_TOSTRING(FLAKKARI_VERSION_PATCH) "." \ + LPL_TOSTRING(FLAKKARI_VERSION_TWEAK) #endif /* !FLAKKARI_VERSION_H_ */ From c5216554527b7536456d363801b32128452e5ec9 Mon Sep 17 00:00:00 2001 From: MasterLaplace Date: Fri, 8 Nov 2024 00:42:45 -0500 Subject: [PATCH 20/20] refactor: update Client and ClientManager methods for consistent reference passing and improved return types --- Flakkari/Network/Packed.hpp | 41 ------------------------ Flakkari/Server/Client/Client.cpp | 4 +-- Flakkari/Server/Client/Client.hpp | 4 +-- Flakkari/Server/Client/ClientManager.cpp | 34 ++++++++++++-------- Flakkari/Server/Client/ClientManager.hpp | 29 ++++++++++------- Flakkari/Server/Game/ResourceManager.cpp | 2 +- Flakkari/Server/Game/ResourceManager.hpp | 2 +- Flakkari/Server/UDPServer.cpp | 8 +++-- 8 files changed, 49 insertions(+), 75 deletions(-) delete mode 100644 Flakkari/Network/Packed.hpp diff --git a/Flakkari/Network/Packed.hpp b/Flakkari/Network/Packed.hpp deleted file mode 100644 index d68e227f..00000000 --- a/Flakkari/Network/Packed.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/************************************************************************** - * Flakkari Library v0.3.0 - * - * Flakkari Library is a C++ Library for Network. - * @file Packed.hpp - * @brief Packed header. Contains PACKED macros. - * (LPL_PACKED_START, LPL_PACKED_END, PACKED) - * - * @details LPL_PACKED_START and LPL_PACKED_END macros are used to pack structs: - * PACKED_<_> macros are used to pack structs: - * LPL_PACKED_START struct _ {}; LPL_PACKED_END - * PACKED macros are used to pack structs: - * struct _ {} PACKED; - * - * Flakkari Library is under MIT License. - * https://opensource.org/licenses/MIT - * © 2023 @MasterLaplace - * @version 0.3.0 - * @date 2023-01-10 - **************************************************************************/ - -#ifndef PACKED_HPP_ -#define PACKED_HPP_ - -#ifdef LPL_PACKED_START -# undef LPL_PACKED_START -#endif - -#ifdef LPL_PACKED_END -# undef LPL_PACKED_END -#endif - -#ifdef _MSC_VER -# define LPL_PACKED_START __pragma(pack(push, 1)) -# define LPL_PACKED_END __pragma(pack(pop)) -#else -# define LPL_PACKED_START _Pragma("pack(1)") -# define LPL_PACKED_END _Pragma("pack()") -#endif - -#endif /* !PACKED_HPP_ */ diff --git a/Flakkari/Server/Client/Client.cpp b/Flakkari/Server/Client/Client.cpp index 05805ca0..a6bb0f3e 100644 --- a/Flakkari/Server/Client/Client.cpp +++ b/Flakkari/Server/Client/Client.cpp @@ -11,7 +11,7 @@ namespace Flakkari { -Client::Client(std::shared_ptr address, std::string name) +Client::Client(const std::shared_ptr &address, const std::string &name) : _address(address), _gameName(name), _name(address->toString().value_or("")) { _lastActivity = std::chrono::steady_clock::now(); @@ -33,7 +33,7 @@ bool Client::isConnected(float timeout) void Client::keepAlive() { _lastActivity = std::chrono::steady_clock::now(); } -void Client::addPacketToHistory(Network::Buffer packet) +void Client::addPacketToHistory(const Network::Buffer &packet) { if (_packetHistory.size() >= _maxPacketHistory) _packetHistory.erase(_packetHistory.begin()); diff --git a/Flakkari/Server/Client/Client.hpp b/Flakkari/Server/Client/Client.hpp index 72d427db..43d00fd6 100644 --- a/Flakkari/Server/Client/Client.hpp +++ b/Flakkari/Server/Client/Client.hpp @@ -47,7 +47,7 @@ class Client { * @param address The client's address * @param name The Game's name */ - Client(std::shared_ptr address, std::string name); + Client(const std::shared_ptr &address, const std::string &name); ~Client(); /** @@ -70,7 +70,7 @@ class Client { * * @param packet The packet to add */ - void addPacketToHistory(Network::Buffer packet); + void addPacketToHistory(const Network::Buffer &packet); /** * @brief Increment the warning count of the client diff --git a/Flakkari/Server/Client/ClientManager.cpp b/Flakkari/Server/Client/ClientManager.cpp index 192d371d..d05cca4a 100644 --- a/Flakkari/Server/Client/ClientManager.cpp +++ b/Flakkari/Server/Client/ClientManager.cpp @@ -14,28 +14,29 @@ namespace Flakkari { -void ClientManager::addClient(std::shared_ptr client, Network::Buffer &buffer) +bool ClientManager::addClient(const std::shared_ptr &client, Network::Buffer &buffer) { if (this->isBanned(client)) { FLAKKARI_LOG_LOG("Client " + client->toString().value_or("Unknown") + " tried to connect but is banned"); - return; + return false; } if (_clients.find(client->toString().value_or("")) != _clients.end()) - return _clients[client->toString().value_or("")]->keepAlive(), void(); + return _clients[client->toString().value_or("")]->keepAlive(), true; Protocol::Packet packet; if (!packet.deserialize(buffer)) { FLAKKARI_LOG_WARNING("Client " + client->toString().value_or("Unknown") + " sent an invalid packet"); - return; + _bannedClients.push_back(client->getIp().value()); + return false; } if (packet.header._commandId != Protocol::CommandId::REQ_CONNECT) { FLAKKARI_LOG_WARNING("Client " + client->toString().value_or("Unknown") + " sent an invalid packet"); - return; + return false; } std::string name = packet.extractString(); @@ -44,9 +45,10 @@ void ClientManager::addClient(std::shared_ptr client, Network: FLAKKARI_LOG_LOG("Client " + client->toString().value_or("Unknown") + " connected"); GameManager::GetInstance().addClientToGame(name, _clients[client->toString().value_or("")]); GameManager::UnlockInstance(); + return true; } -void ClientManager::removeClient(std::shared_ptr client) +void ClientManager::removeClient(const std::shared_ptr &client) { if (_clients.find(client->toString().value_or("")) == _clients.end()) return; @@ -58,7 +60,7 @@ void ClientManager::removeClient(std::shared_ptr client) _clients.erase(client->toString().value_or("")); } -void ClientManager::banClient(std::shared_ptr client) +void ClientManager::banClient(const std::shared_ptr &client) { if (_clients.find(client->toString().value_or("")) == _clients.end()) return; @@ -72,7 +74,7 @@ void ClientManager::banClient(std::shared_ptr client) _clients.erase(client->toString().value_or("")); } -bool ClientManager::isBanned(std::shared_ptr client) +bool ClientManager::isBanned(const std::shared_ptr &client) { return std::find(_bannedClients.begin(), _bannedClients.end(), client->getIp().value_or("")) != _bannedClients.end(); @@ -108,7 +110,7 @@ void ClientManager::sendPacketToAllClients(const Network::Buffer &packet) } } -void ClientManager::sendPacketToAllClientsExcept(std::shared_ptr client, +void ClientManager::sendPacketToAllClientsExcept(const std::shared_ptr &client, const Network::Buffer &packet) { auto clientKey = client->toString().value_or(""); @@ -122,7 +124,8 @@ void ClientManager::sendPacketToAllClientsExcept(std::shared_ptr client, const Network::Buffer &buffer) +void ClientManager::receivePacketFromClient(const std::shared_ptr &client, + const Network::Buffer &buffer) { auto clientName = client->toString().value_or(""); auto ip = client->getIp().value_or(""); @@ -159,15 +162,18 @@ void ClientManager::receivePacketFromClient(std::shared_ptr cl _clients.erase(clientName); } -std::shared_ptr ClientManager::getClient(std::shared_ptr client) +std::shared_ptr ClientManager::getClient(const std::shared_ptr &client) { return _clients[client->toString().value_or("")]; } -std::shared_ptr ClientManager::getClient(std::string id) { return _clients[id]; } +std::shared_ptr ClientManager::getClient(const std::string &id) { return _clients[id]; } -std::shared_ptr ClientManager::getAddress(std::string id) { return _clients[id]->getAddress(); } +std::shared_ptr ClientManager::getAddress(const std::string &id) +{ + return _clients[id]->getAddress(); +} -std::shared_ptr ClientManager::operator[](std::string id) { return _clients[id]; } +std::shared_ptr ClientManager::operator[](const std::string &id) { return _clients[id]; } } /* namespace Flakkari */ diff --git a/Flakkari/Server/Client/ClientManager.hpp b/Flakkari/Server/Client/ClientManager.hpp index 488473fd..d905bd28 100644 --- a/Flakkari/Server/Client/ClientManager.hpp +++ b/Flakkari/Server/Client/ClientManager.hpp @@ -62,7 +62,7 @@ class ClientManager : public Singleton { * * @param socket The server's socket */ - explicit ClientManager(std::shared_ptr socket) : _socket(socket) {} + explicit ClientManager(const std::shared_ptr &socket) : _socket(socket) {} /** * @brief Destroy the ClientManager object @@ -75,23 +75,30 @@ class ClientManager : public Singleton { * * @param client The client's address */ - void addClient(std::shared_ptr client, Network::Buffer &buffer); + bool addClient(const std::shared_ptr &client, Network::Buffer &buffer); /** * @brief Remove a client from the client manager * * @param client The client's address */ - void removeClient(std::shared_ptr client); + void removeClient(const std::shared_ptr &client); /** * @brief Ban a client from the server * * @param client The client's address */ - void banClient(std::shared_ptr client); + void banClient(const std::shared_ptr &client); - [[nodiscard]] bool isBanned(std::shared_ptr client); + /** + * @brief Check if a client is banned + * + * @param client The client's address + * @return true If the client is banned + * @return false If the client is not banned + */ + [[nodiscard]] bool isBanned(const std::shared_ptr &client); /** * @brief Check if the clients are still connected to the server @@ -125,7 +132,7 @@ class ClientManager : public Singleton { * @param client The client's address * @param packet The packet to send */ - void sendPacketToAllClientsExcept(std::shared_ptr client, const Network::Buffer &packet); + void sendPacketToAllClientsExcept(const std::shared_ptr &client, const Network::Buffer &packet); /** * @brief Receive a packet from a client @@ -133,7 +140,7 @@ class ClientManager : public Singleton { * @param client The client's address * @param packet The packet received */ - void receivePacketFromClient(std::shared_ptr client, const Network::Buffer &packet); + void receivePacketFromClient(const std::shared_ptr &client, const Network::Buffer &packet); /** * @brief Get the Client object @@ -141,7 +148,7 @@ class ClientManager : public Singleton { * @param client The client's address * @return std::shared_ptr The client object */ - std::shared_ptr getClient(std::shared_ptr client); + std::shared_ptr getClient(const std::shared_ptr &client); /** * @brief Get the Client object @@ -149,7 +156,7 @@ class ClientManager : public Singleton { * @param id The client's id * @return std::shared_ptr The client object */ - std::shared_ptr getClient(std::string id); + std::shared_ptr getClient(const std::string &id); /** * @brief Get the Address object @@ -157,7 +164,7 @@ class ClientManager : public Singleton { * @param id The client's id * @return std::shared_ptr The client's address */ - std::shared_ptr getAddress(std::string id); + std::shared_ptr getAddress(const std::string &id); /** * @brief Get the client object from the client manager @@ -165,7 +172,7 @@ class ClientManager : public Singleton { * @param id The client's id * @return std::shared_ptr The client object */ - std::shared_ptr operator[](std::string id); + std::shared_ptr operator[](const std::string &id); }; } /* namespace Flakkari */ diff --git a/Flakkari/Server/Game/ResourceManager.cpp b/Flakkari/Server/Game/ResourceManager.cpp index c7797df2..6a783b5d 100644 --- a/Flakkari/Server/Game/ResourceManager.cpp +++ b/Flakkari/Server/Game/ResourceManager.cpp @@ -11,7 +11,7 @@ namespace Flakkari { -void ResourceManager::addScene(std::shared_ptr config, const std::string &scene) +void ResourceManager::addScene(const std::shared_ptr &config, const std::string &scene) { for (auto &_scene : (*config)["scenes"].items()) { diff --git a/Flakkari/Server/Game/ResourceManager.hpp b/Flakkari/Server/Game/ResourceManager.hpp index d8de1290..17d7bdb5 100644 --- a/Flakkari/Server/Game/ResourceManager.hpp +++ b/Flakkari/Server/Game/ResourceManager.hpp @@ -67,7 +67,7 @@ class ResourceManager : public Singleton { * @param configPath The path to the config file of the game to add * @param scene The scene to add to the ResourceManager instance */ - void addScene(std::shared_ptr config, const std::string &scene); + void addScene(const std::shared_ptr &config, const std::string &scene); /** * @brief Delete a scene from the ResourceManager instance diff --git a/Flakkari/Server/UDPServer.cpp b/Flakkari/Server/UDPServer.cpp index af6187ba..9030a9c7 100644 --- a/Flakkari/Server/UDPServer.cpp +++ b/Flakkari/Server/UDPServer.cpp @@ -62,10 +62,12 @@ bool UDPServer::handleInput(int fd) void UDPServer::handlePacket() { auto packet = _socket->receiveFrom(); - auto instance = ClientManager::GetInstance(); - instance.addClient(packet->first, packet->second); + auto &instance = ClientManager::GetInstance(); + + bool result = instance.addClient(packet->first, packet->second); instance.checkInactiveClients(); - instance.receivePacketFromClient(packet->first, packet->second); + if (result) + instance.receivePacketFromClient(packet->first, packet->second); ClientManager::UnlockInstance(); }