diff --git a/CMakeLists.txt b/CMakeLists.txt index c256724c..f0b47ece 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -287,7 +287,7 @@ add_subdirectory(dPhysics) add_subdirectory(dServer) # Create a list of common libraries shared between all binaries -set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "MariaDB::ConnCpp" "magic_enum") +set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "fmt" "raknet" "MariaDB::ConnCpp" "magic_enum") # Add platform specific common libraries if(UNIX) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 476e1a68..f9aa0622 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -54,14 +54,14 @@ int main(int argc, char** argv) { Server::SetupLogger("AuthServer"); if (!Game::logger) return EXIT_FAILURE; - LOG("Starting Auth server..."); - LOG("Version: %s", PROJECT_VERSION); - LOG("Compiled on: %s", __TIMESTAMP__); + Log::Info("Starting Auth server..."); + Log::Info("Version: {:s}", PROJECT_VERSION); + Log::Info("Compiled on: {:s}", __TIMESTAMP__); try { Database::Connect(); } catch (sql::SQLException& ex) { - LOG("Got an error while connecting to the database: %s", ex.what()); + Log::Info("Got an error while connecting to the database: {:s}", ex.what()); Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; @@ -77,7 +77,7 @@ int main(int argc, char** argv) { masterIP = masterInfo->ip; masterPort = masterInfo->port; } - LOG("Master is at %s:%d", masterIP.c_str(), masterPort); + Log::Info("Master is at {:s}:{:d}", masterIP, masterPort); Game::randomEngine = std::mt19937(time(0)); @@ -110,7 +110,7 @@ int main(int argc, char** argv) { framesSinceMasterDisconnect++; if (framesSinceMasterDisconnect >= authFramerate) { - LOG("No connection to master!"); + Log::Info("No connection to master!"); break; //Exit our loop, shut down. } } else framesSinceMasterDisconnect = 0; @@ -151,7 +151,7 @@ int main(int argc, char** argv) { std::this_thread::sleep_until(t); } - LOG("Exited Main Loop! (signal %d)", Game::lastSignal); + Log::Info("Exited Main Loop! (signal {:d})", Game::lastSignal); //Delete our objects here: Database::Destroy("AuthServer"); delete Game::server; diff --git a/dAuthServer/CMakeLists.txt b/dAuthServer/CMakeLists.txt index 7dcbf041..451e669b 100644 --- a/dAuthServer/CMakeLists.txt +++ b/dAuthServer/CMakeLists.txt @@ -1,6 +1,6 @@ add_executable(AuthServer "AuthServer.cpp") -target_link_libraries(AuthServer ${COMMON_LIBRARIES} dServer) +target_link_libraries(AuthServer PRIVATE ${COMMON_LIBRARIES} dServer) target_include_directories(AuthServer PRIVATE ${PROJECT_SOURCE_DIR}/dServer) diff --git a/dChatServer/CMakeLists.txt b/dChatServer/CMakeLists.txt index c7eea041..33ce5cda 100644 --- a/dChatServer/CMakeLists.txt +++ b/dChatServer/CMakeLists.txt @@ -11,6 +11,6 @@ add_compile_definitions(ChatServer PRIVATE PROJECT_VERSION="\"${PROJECT_VERSION} add_library(dChatServer ${DCHATSERVER_SOURCES}) target_include_directories(dChatServer PRIVATE "${PROJECT_SOURCE_DIR}/dServer") -target_link_libraries(dChatServer ${COMMON_LIBRARIES} dChatFilter) -target_link_libraries(ChatServer ${COMMON_LIBRARIES} dChatFilter dChatServer dServer) +target_link_libraries(dChatServer PRIVATE ${COMMON_LIBRARIES} dChatFilter) +target_link_libraries(ChatServer PRIVATE ${COMMON_LIBRARIES} dChatFilter dChatServer dServer) diff --git a/dChatServer/ChatIgnoreList.cpp b/dChatServer/ChatIgnoreList.cpp index f0c55eb0..7aae05e7 100644 --- a/dChatServer/ChatIgnoreList.cpp +++ b/dChatServer/ChatIgnoreList.cpp @@ -27,16 +27,16 @@ void ChatIgnoreList::GetIgnoreList(Packet* packet) { auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId); if (!receiver) { - LOG("Tried to get ignore list, but player %llu not found in container", playerId); + Log::Info("Tried to get ignore list, but player {:d} not found in container", playerId); return; } if (!receiver.ignoredPlayers.empty()) { - LOG_DEBUG("Player %llu already has an ignore list, but is requesting it again.", playerId); + Log::Debug("Player {:d} already has an ignore list, but is requesting it again.", playerId); } else { auto ignoreList = Database::Get()->GetIgnoreList(static_cast(playerId)); if (ignoreList.empty()) { - LOG_DEBUG("Player %llu has no ignores", playerId); + Log::Debug("Player {:d} has no ignores", playerId); return; } @@ -69,13 +69,13 @@ void ChatIgnoreList::AddIgnore(Packet* packet) { auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId); if (!receiver) { - LOG("Tried to get ignore list, but player %llu not found in container", playerId); + Log::Info("Tried to get ignore list, but player {:d} not found in container", playerId); return; } constexpr int32_t MAX_IGNORES = 32; if (receiver.ignoredPlayers.size() > MAX_IGNORES) { - LOG_DEBUG("Player %llu has too many ignores", playerId); + Log::Debug("Player {:d} has too many ignores", playerId); return; } @@ -91,11 +91,11 @@ void ChatIgnoreList::AddIgnore(Packet* packet) { // Check if the player exists LWOOBJID ignoredPlayerId = LWOOBJID_EMPTY; if (toIgnoreStr == receiver.playerName || toIgnoreStr.find("[GM]") == 0) { - LOG_DEBUG("Player %llu tried to ignore themselves", playerId); + Log::Debug("Player {:d} tried to ignore themselves", playerId); bitStream.Write(ChatIgnoreList::AddResponse::GENERAL_ERROR); } else if (std::count(receiver.ignoredPlayers.begin(), receiver.ignoredPlayers.end(), toIgnoreStr) > 0) { - LOG_DEBUG("Player %llu is already ignoring %s", playerId, toIgnoreStr.c_str()); + Log::Debug("Player {:d} is already ignoring {:s}", playerId, toIgnoreStr); bitStream.Write(ChatIgnoreList::AddResponse::ALREADY_IGNORED); } else { @@ -105,7 +105,7 @@ void ChatIgnoreList::AddIgnore(Packet* packet) { // Fall back to query auto player = Database::Get()->GetCharacterInfo(toIgnoreStr); if (!player || player->name != toIgnoreStr) { - LOG_DEBUG("Player %s not found", toIgnoreStr.c_str()); + Log::Debug("Player {:s} not found", toIgnoreStr); } else { ignoredPlayerId = player->id; } @@ -119,7 +119,7 @@ void ChatIgnoreList::AddIgnore(Packet* packet) { GeneralUtils::SetBit(ignoredPlayerId, eObjectBits::PERSISTENT); receiver.ignoredPlayers.emplace_back(toIgnoreStr, ignoredPlayerId); - LOG_DEBUG("Player %llu is ignoring %s", playerId, toIgnoreStr.c_str()); + Log::Debug("Player {:d} is ignoring {:s}", playerId, toIgnoreStr); bitStream.Write(ChatIgnoreList::AddResponse::SUCCESS); } else { @@ -141,7 +141,7 @@ void ChatIgnoreList::RemoveIgnore(Packet* packet) { auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId); if (!receiver) { - LOG("Tried to get ignore list, but player %llu not found in container", playerId); + Log::Info("Tried to get ignore list, but player {:d} not found in container", playerId); return; } @@ -153,7 +153,7 @@ void ChatIgnoreList::RemoveIgnore(Packet* packet) { auto toRemove = std::remove(receiver.ignoredPlayers.begin(), receiver.ignoredPlayers.end(), removedIgnoreStr); if (toRemove == receiver.ignoredPlayers.end()) { - LOG_DEBUG("Player %llu is not ignoring %s", playerId, removedIgnoreStr.c_str()); + Log::Debug("Player {:d} is not ignoring {:s}", playerId, removedIgnoreStr); return; } diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 5e2e58d7..faa4b2a3 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -93,7 +93,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { auto& requestor = Game::playerContainer.GetPlayerDataMutable(requestorPlayerID); if (!requestor) { - LOG("No requestor player %llu sent to %s found.", requestorPlayerID, playerName.c_str()); + Log::Info("No requestor player {:d} sent to {:s} found.", requestorPlayerID, playerName); return; } @@ -376,7 +376,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) { LUWString message(size); inStream.Read(message); - LOG("Got a message from (%s) via [%s]: %s", sender.playerName.c_str(), StringifiedEnum::ToString(channel).data(), message.GetAsString().c_str()); + Log::Info("Got a message from ({:s}) via [{:s}]: {:s}", sender.playerName, StringifiedEnum::ToString(channel), message.GetAsString()); switch (channel) { case eChatChannel::TEAM: { @@ -391,7 +391,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) { break; } default: - LOG("Unhandled Chat channel [%s]", StringifiedEnum::ToString(channel).data()); + Log::Info("Unhandled Chat channel [{:s}]", StringifiedEnum::ToString(channel)); break; } } @@ -412,7 +412,7 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) { inStream.IgnoreBytes(4); inStream.Read(channel); - if (channel != eChatChannel::PRIVATE_CHAT) LOG("WARNING: Received Private chat with the wrong channel!"); + if (channel != eChatChannel::PRIVATE_CHAT) Log::Info("WARNING: Received Private chat with the wrong channel!"); inStream.Read(size); inStream.IgnoreBytes(77); @@ -424,7 +424,7 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) { LUWString message(size); inStream.Read(message); - LOG("Got a message from (%s) via [%s]: %s to %s", sender.playerName.c_str(), StringifiedEnum::ToString(channel).data(), message.GetAsString().c_str(), receiverName.c_str()); + Log::Info("Got a message from ({:s}) via [{:s}]: {:s} to {:s}", sender.playerName, StringifiedEnum::ToString(channel), message.GetAsString(), receiverName); const auto& receiver = Game::playerContainer.GetPlayerData(receiverName); if (!receiver) { @@ -506,13 +506,13 @@ void ChatPacketHandler::HandleTeamInvite(Packet* packet) { if (team->memberIDs.size() > 3) { // no more teams greater than 4 - LOG("Someone tried to invite a 5th player to a team"); + Log::Info("Someone tried to invite a 5th player to a team"); return; } SendTeamInvite(other, player); - LOG("Got team invite: %llu -> %s", playerID, invitedPlayer.GetAsString().c_str()); + Log::Info("Got team invite: {:d} -> {:s}", playerID, invitedPlayer.GetAsString()); } void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) { @@ -526,7 +526,7 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) { LWOOBJID leaderID = LWOOBJID_EMPTY; inStream.Read(leaderID); - LOG("Accepted invite: %llu -> %llu (%d)", playerID, leaderID, declined); + Log::Info("Accepted invite: {:d} -> {:d} ({:d})", playerID, leaderID, declined); if (declined) { return; @@ -535,13 +535,13 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) { auto* team = Game::playerContainer.GetTeam(leaderID); if (team == nullptr) { - LOG("Failed to find team for leader (%llu)", leaderID); + Log::Info("Failed to find team for leader ({:d})", leaderID); team = Game::playerContainer.GetTeam(playerID); } if (team == nullptr) { - LOG("Failed to find team for player (%llu)", playerID); + Log::Info("Failed to find team for player ({:d})", playerID); return; } @@ -557,7 +557,7 @@ void ChatPacketHandler::HandleTeamLeave(Packet* packet) { auto* team = Game::playerContainer.GetTeam(playerID); - LOG("(%llu) leaving team", playerID); + Log::Info("({:d}) leaving team", playerID); if (team != nullptr) { Game::playerContainer.RemoveMember(team, playerID, false, false, true); @@ -575,7 +575,7 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) { inStream.Read(kickedPlayer); - LOG("(%llu) kicking (%s) from team", playerID, kickedPlayer.GetAsString().c_str()); + Log::Info("({:d}) kicking ({:s}) from team", playerID, kickedPlayer.GetAsString()); const auto& kicked = Game::playerContainer.GetPlayerData(kickedPlayer.GetAsString()); @@ -608,7 +608,7 @@ void ChatPacketHandler::HandleTeamPromote(Packet* packet) { inStream.IgnoreBytes(4); inStream.Read(promotedPlayer); - LOG("(%llu) promoting (%s) to team leader", playerID, promotedPlayer.GetAsString().c_str()); + Log::Info("({:d}) promoting ({:s}) to team leader", playerID, promotedPlayer.GetAsString()); const auto& promoted = Game::playerContainer.GetPlayerData(promotedPlayer.GetAsString()); diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 84104726..9da3dc3f 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -60,9 +60,9 @@ int main(int argc, char** argv) { //Read our config: - LOG("Starting Chat server..."); - LOG("Version: %s", PROJECT_VERSION); - LOG("Compiled on: %s", __TIMESTAMP__); + Log::Info("Starting Chat server..."); + Log::Info("Version: {:s}", PROJECT_VERSION); + Log::Info("Compiled on: {:s}", __TIMESTAMP__); try { std::string clientPathStr = Game::config->GetValue("client_location"); @@ -74,7 +74,7 @@ int main(int argc, char** argv) { Game::assetManager = new AssetManager(clientPath); } catch (std::runtime_error& ex) { - LOG("Got an error while setting up assets: %s", ex.what()); + Log::Info("Got an error while setting up assets: {:s}", ex.what()); return EXIT_FAILURE; } @@ -83,7 +83,7 @@ int main(int argc, char** argv) { try { Database::Connect(); } catch (sql::SQLException& ex) { - LOG("Got an error while connecting to the database: %s", ex.what()); + Log::Info("Got an error while connecting to the database: {:s}", ex.what()); Database::Destroy("ChatServer"); delete Game::server; delete Game::logger; @@ -181,11 +181,11 @@ int main(int argc, char** argv) { void HandlePacket(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - LOG("A server has disconnected, erasing their connected players from the list."); + Log::Info("A server has disconnected, erasing their connected players from the list."); } if (packet->data[0] == ID_NEW_INCOMING_CONNECTION) { - LOG("A server is connecting, awaiting user list."); + Log::Info("A server is connecting, awaiting user list."); } if (packet->length < 4) return; // Nothing left to process. Need 4 bytes to continue. @@ -216,7 +216,7 @@ void HandlePacket(Packet* packet) { } default: - LOG("Unknown CHAT_INTERNAL id: %i", int(packet->data[3])); + Log::Info("Unknown CHAT_INTERNAL id: {:d}", static_cast(packet->data[3])); } } @@ -343,22 +343,22 @@ void HandlePacket(Packet* packet) { case eChatMessageType::PRG_CSR_COMMAND: case eChatMessageType::HEARTBEAT_REQUEST_FROM_WORLD: case eChatMessageType::UPDATE_FREE_TRIAL_STATUS: - LOG("Unhandled CHAT Message id: %s (%i)", StringifiedEnum::ToString(chat_message_type).data(), chat_message_type); + Log::Info("Unhandled CHAT Message id: {:s} {:d}", StringifiedEnum::ToString(chat_message_type), GeneralUtils::ToUnderlying(chat_message_type)); break; default: - LOG("Unknown CHAT Message id: %i", chat_message_type); + Log::Info("Unknown CHAT Message id: {:d}", GeneralUtils::ToUnderlying(chat_message_type)); } } if (static_cast(packet->data[1]) == eConnectionType::WORLD) { switch (static_cast(packet->data[3])) { case eWorldMessageType::ROUTE_PACKET: { - LOG("Routing packet from world"); + Log::Info("Routing packet from world"); break; } default: - LOG("Unknown World id: %i", int(packet->data[3])); + Log::Info("Unknown World id: {:d}", static_cast(packet->data[3])); } } } diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 4e4d1be5..0cbdd257 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -28,7 +28,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) { CINSTREAM_SKIP_HEADER; LWOOBJID playerId; if (!inStream.Read(playerId)) { - LOG("Failed to read player ID"); + Log::Warn("Failed to read player ID"); return; } @@ -50,7 +50,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) { m_Names[data.playerID] = GeneralUtils::UTF8ToUTF16(data.playerName); - LOG("Added user: %s (%llu), zone: %i", data.playerName.c_str(), data.playerID, data.zoneID.GetMapID()); + Log::Info("Added user: {:s} ({:d}), zone: {:d}", data.playerName, data.playerID, data.zoneID.GetMapID()); Database::Get()->UpdateActivityLog(data.playerID, eActivityType::PlayerLoggedIn, data.zoneID.GetMapID()); } @@ -64,7 +64,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { const auto& player = GetPlayerData(playerID); if (!player) { - LOG("Failed to find user: %llu", playerID); + Log::Info("Failed to find user: {:d}", playerID); return; } @@ -87,7 +87,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { } } - LOG("Removed user: %llu", playerID); + Log::Info("Removed user: {:d}", playerID); m_Players.erase(playerID); Database::Get()->UpdateActivityLog(playerID, eActivityType::PlayerLoggedOut, player.zoneID.GetMapID()); @@ -103,7 +103,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) { auto& player = this->GetPlayerDataMutable(playerID); if (!player) { - LOG("Failed to find user: %llu", playerID); + Log::Warn("Failed to find user: {:d}", playerID); return; } @@ -207,7 +207,7 @@ TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) { void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) { if (team->memberIDs.size() >= 4) { - LOG("Tried to add player to team that already had 4 players"); + Log::Warn("Tried to add player to team that already had 4 players"); const auto& player = GetPlayerData(playerID); if (!player) return; ChatPackets::SendSystemMessage(player.sysAddr, u"The teams is full! You have not been added to a team!"); diff --git a/dCommon/AmfSerialize.cpp b/dCommon/AmfSerialize.cpp index e11ae1de..5a9476d3 100644 --- a/dCommon/AmfSerialize.cpp +++ b/dCommon/AmfSerialize.cpp @@ -29,7 +29,7 @@ void RakNet::BitStream::Write(AMFBaseValue& value) { break; } default: { - LOG("Encountered unwritable AMFType %i!", type); + Log::Warn("Encountered unwritable AMFType {:d}!", GeneralUtils::ToUnderlying(type)); } case eAmf::Undefined: case eAmf::Null: diff --git a/dCommon/BrickByBrickFix.cpp b/dCommon/BrickByBrickFix.cpp index b771c986..aa606924 100644 --- a/dCommon/BrickByBrickFix.cpp +++ b/dCommon/BrickByBrickFix.cpp @@ -54,14 +54,14 @@ uint32_t BrickByBrickFix::TruncateBrokenBrickByBrickXml() { completeUncompressedModel.append(reinterpret_cast(uncompressedChunk.get())); completeUncompressedModel.resize(previousSize + actualUncompressedSize); } else { - LOG("Failed to inflate chunk %i for model %llu. Error: %i", chunkCount, model.id, err); + Log::Warn("Failed to inflate chunk {:d} for model %llu. Error: {:d}", chunkCount, model.id, err); break; } chunkCount++; } std::unique_ptr document = std::make_unique(); if (!document) { - LOG("Failed to initialize tinyxml document. Aborting."); + Log::Warn("Failed to initialize tinyxml document. Aborting."); return 0; } @@ -121,11 +121,11 @@ uint32_t BrickByBrickFix::UpdateBrickByBrickModelsToSd0() { try { Database::Get()->UpdateUgcModelData(model.id, outputStringStream); - LOG("Updated model %i to sd0", model.id); + Log::Info("Updated model {:d} to sd0", model.id); updatedModels++; } catch (sql::SQLException exception) { - LOG("Failed to update model %i. This model should be inspected manually to see why." - "The database error is %s", model.id, exception.what()); + Log::Warn("Failed to update model {:d}. This model should be inspected manually to see why." + "The database error is {:s}", model.id, exception.what()); } } } diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index d020ff72..cf7745b5 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -70,5 +70,6 @@ else () endif () target_link_libraries(dCommon + PUBLIC fmt PRIVATE ZLIB::ZLIB bcrypt tinyxml2 INTERFACE dDatabase) diff --git a/dCommon/Diagnostics.cpp b/dCommon/Diagnostics.cpp index 46c17e43..b26a4f03 100644 --- a/dCommon/Diagnostics.cpp +++ b/dCommon/Diagnostics.cpp @@ -28,7 +28,7 @@ void make_minidump(EXCEPTION_POINTERS* e) { "_%4d%02d%02d_%02d%02d%02d.dmp", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); } - LOG("Creating crash dump %s", name); + Log::Info("Creating crash dump {:s}", name); auto hFile = CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (hFile == INVALID_HANDLE_VALUE) return; @@ -83,7 +83,7 @@ struct bt_ctx { static inline void Bt(struct backtrace_state* state) { std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; - LOG("backtrace is enabled, crash dump located at %s", fileName.c_str()); + Log::Info("backtrace is enabled, crash dump located at {:s}", fileName); FILE* file = fopen(fileName.c_str(), "w+"); if (file != nullptr) { backtrace_print(state, 2, file); @@ -95,13 +95,13 @@ static inline void Bt(struct backtrace_state* state) { static void ErrorCallback(void* data, const char* msg, int errnum) { auto* ctx = (struct bt_ctx*)data; - fprintf(stderr, "ERROR: %s (%d)", msg, errnum); + fmt::print(stderr, "ERROR: {:s} ({:d})", msg, errnum); ctx->error = 1; std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; FILE* file = fopen(fileName.c_str(), "w+"); if (file != nullptr) { - fprintf(file, "ERROR: %s (%d)", msg, errnum); + fmt::print(file, "ERROR: {:s} ({:d})", msg, errnum); fclose(file); } } @@ -119,13 +119,13 @@ void CatchUnhandled(int sig) { try { if (eptr) std::rethrow_exception(eptr); } catch(const std::exception& e) { - LOG("Caught exception: '%s'", e.what()); + Log::Warn("Caught exception: '{:s}'", e.what()); } #ifndef INCLUDE_BACKTRACE std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; - LOG("Encountered signal %i, creating crash dump %s", sig, fileName.c_str()); + Log::Warn("Encountered signal {:d}, creating crash dump {:s}", sig, fileName); if (Diagnostics::GetProduceMemoryDump()) { GenerateDump(); } @@ -143,7 +143,7 @@ void CatchUnhandled(int sig) { FILE* file = fopen(fileName.c_str(), "w+"); if (file != NULL) { - fprintf(file, "Error: signal %d:\n", sig); + fmt::println(file, "Error: signal {:d}:", sig); } // Print the stack trace for (size_t i = 0; i < size; i++) { @@ -165,9 +165,9 @@ void CatchUnhandled(int sig) { } } - LOG("[%02zu] %s", i, functionName.c_str()); + Log::Info("[{:02d}] {:s}", i, functionName); if (file != NULL) { - fprintf(file, "[%02zu] %s\n", i, functionName.c_str()); + fmt::println(file, "[{:02d}] {:s}", i, functionName); } } # else // defined(__GNUG__) @@ -208,7 +208,7 @@ void MakeBacktrace() { sigaction(SIGFPE, &sigact, nullptr) != 0 || sigaction(SIGABRT, &sigact, nullptr) != 0 || sigaction(SIGILL, &sigact, nullptr) != 0) { - fprintf(stderr, "error setting signal handler for %d (%s)\n", + fmt::println(stderr, "error setting signal handler for {:d} ({:s})", SIGSEGV, strsignal(SIGSEGV)); diff --git a/dCommon/FdbToSqlite.cpp b/dCommon/FdbToSqlite.cpp index d8409cd5..3349da25 100644 --- a/dCommon/FdbToSqlite.cpp +++ b/dCommon/FdbToSqlite.cpp @@ -42,7 +42,7 @@ bool FdbToSqlite::Convert::ConvertDatabase(AssetStream& buffer) { CDClientDatabase::ExecuteQuery("COMMIT;"); } catch (CppSQLite3Exception& e) { - LOG("Encountered error %s converting FDB to SQLite", e.errorMessage()); + Log::Warn("Encountered error {:s} converting FDB to SQLite", e.errorMessage()); return false; } diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index da28ae6e..e7f70ece 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -48,7 +48,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { try { type = static_cast(strtol(ldfTypeAndValue.first.data(), &storage, 10)); } catch (std::exception) { - LOG("Attempted to process invalid ldf type (%s) from string (%s)", ldfTypeAndValue.first.data(), format.data()); + Log::Warn("Attempted to process invalid ldf type ({:s}) from string ({:s})", ldfTypeAndValue.first, format); return nullptr; } @@ -63,7 +63,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { case LDF_TYPE_S32: { const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); if (!data) { - LOG("Warning: Attempted to process invalid int32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + Log::Warn("Attempted to process invalid int32 value ({:s}) from string ({:s})", ldfTypeAndValue.second, format); return nullptr; } returnValue = new LDFData(key, data.value()); @@ -74,7 +74,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { case LDF_TYPE_FLOAT: { const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); if (!data) { - LOG("Warning: Attempted to process invalid float value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + Log::Warn("Attempted to process invalid float value ({:s}) from string ({:s})", ldfTypeAndValue.second, format); return nullptr; } returnValue = new LDFData(key, data.value()); @@ -84,7 +84,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { case LDF_TYPE_DOUBLE: { const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); if (!data) { - LOG("Warning: Attempted to process invalid double value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + Log::Warn("Attempted to process invalid double value ({:s}) from string ({:s})", ldfTypeAndValue.second, format); return nullptr; } returnValue = new LDFData(key, data.value()); @@ -102,7 +102,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else { const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); if (!dataOptional) { - LOG("Warning: Attempted to process invalid uint32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + Log::Warn("Attempted to process invalid uint32 value ({:s}) from string ({:s})", ldfTypeAndValue.second, format); return nullptr; } data = dataOptional.value(); @@ -122,7 +122,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else { const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); if (!dataOptional) { - LOG("Warning: Attempted to process invalid bool value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + Log::Warn("Attempted to process invalid bool value ({:s}) from string ({:s})", ldfTypeAndValue.second, format); return nullptr; } data = dataOptional.value(); @@ -135,7 +135,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { case LDF_TYPE_U64: { const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); if (!data) { - LOG("Warning: Attempted to process invalid uint64 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + Log::Warn("Attempted to process invalid uint64 value ({:s}) from string ({:s})", ldfTypeAndValue.second, format); return nullptr; } returnValue = new LDFData(key, data.value()); @@ -145,7 +145,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { case LDF_TYPE_OBJID: { const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); if (!data) { - LOG("Warning: Attempted to process invalid LWOOBJID value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + Log::Warn("Attempted to process invalid LWOOBJID value ({:s}) from string ({:s})", ldfTypeAndValue.second, format); return nullptr; } returnValue = new LDFData(key, data.value()); @@ -159,12 +159,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } case LDF_TYPE_UNKNOWN: { - LOG("Warning: Attempted to process invalid unknown value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + Log::Warn("Attempted to process invalid unknown value ({:s}) from string ({:s})", ldfTypeAndValue.second, format); break; } default: { - LOG("Warning: Attempted to process invalid LDF type (%d) from string (%s)", type, format.data()); + Log::Warn("Attempted to process invalid LDF type ({:d}) from string ({:s})", GeneralUtils::ToUnderlying(type), format); break; } } diff --git a/dCommon/Logger.cpp b/dCommon/Logger.cpp index 1888f1eb..da088d89 100644 --- a/dCommon/Logger.cpp +++ b/dCommon/Logger.cpp @@ -29,7 +29,7 @@ void Writer::Flush() { FileWriter::FileWriter(const char* outpath) { m_Outfile = fopen(outpath, "wt"); - if (!m_Outfile) printf("Couldn't open %s for writing!\n", outpath); + if (!m_Outfile) fmt::println("Couldn't open {:s} for writing!", outpath); m_Outpath = outpath; m_IsConsoleWriter = false; } diff --git a/dCommon/Logger.h b/dCommon/Logger.h index 5754d9ac..bd361a50 100644 --- a/dCommon/Logger.h +++ b/dCommon/Logger.h @@ -1,6 +1,14 @@ #pragma once +// fmt includes: +#include +#include +#include + +// C++ includes: +#include #include +#include #include #include @@ -15,22 +23,90 @@ // Calculate the filename at compile time from the path. // We just do this by scanning the path for the last '/' or '\' character and returning the string after it. constexpr const char* GetFileNameFromAbsolutePath(const char* path) { - const char* file = path; - while (*path) { + const char* file = path; + while (*path) { char nextChar = *path++; - if (nextChar == '/' || nextChar == '\\') { - file = path; - } - } - return file; + if (nextChar == '/' || nextChar == '\\') { + file = path; + } + } + return file; +} + +/** + * Location wrapper class + * Used to implicitly forward source location information without adding a function parameter +*/ +template +class location_wrapper { +public: + // Constructor + template U = T> + consteval location_wrapper(const U val, const std::source_location loc = std::source_location::current()) + : m_Obj(val) + , m_Loc(loc) { + } + + // Methods + [[nodiscard]] constexpr const T& get() const noexcept { return m_Obj; } + + [[nodiscard]] constexpr const std::source_location& loc() const noexcept { return m_Loc; } + + // Operator overloads + location_wrapper& operator=(const location_wrapper& other) = default; + + constexpr operator T& () const noexcept { return get(); } + +protected: + T m_Obj{}; + std::source_location m_Loc{}; +}; + +/** + * Logging functions (EXPERIMENTAL) +*/ +namespace Log { + template + constexpr tm Time() { // TODO: Move? + return fmt::localtime(std::time(nullptr)); + } + + template + constexpr void Info(const location_wrapper> fmt_str, Ts&&... args) { + const auto filename = GetFileNameFromAbsolutePath(fmt_str.loc().file_name()); + + fmt::print("[{:%d-%m-%y %H:%M:%S} {:s}:{:d}] ", Time(), filename, fmt_str.loc().line()); + fmt::println(fmt_str.get(), std::forward(args)...); + } + + template + constexpr void Warn(const location_wrapper> fmt_str, Ts&&... args) { + const auto filename = GetFileNameFromAbsolutePath(fmt_str.loc().file_name()); + + fmt::print("[{:%d-%m-%y %H:%M:%S} {:s}:{:d}] Warning: ", Time(), filename, fmt_str.loc().line()); + fmt::println(fmt_str.get(), std::forward(args)...); + } + + template + constexpr void Debug(const location_wrapper> fmt_str, Ts&&... args) { + // if (!m_logDebugStatements) return; + Log::Info(fmt_str, std::forward(args)...); + } } // These have to have a constexpr variable to store the filename_and_line result in a local variable otherwise // they will not be valid constexpr and will be evaluated at runtime instead of compile time! // The full string is still stored in the binary, however the offset of the filename in the absolute paths // is used in the instruction instead of the start of the absolute path. -#define LOG(message, ...) do { auto str = FILENAME_AND_LINE; Game::logger->Log(str, message, ##__VA_ARGS__); } while(0) -#define LOG_DEBUG(message, ...) do { auto str = FILENAME_AND_LINE; Game::logger->LogDebug(str, message, ##__VA_ARGS__); } while(0) +//#define LOG(message, ...) do { auto str = FILENAME_AND_LINE; Game::logger->Log(str, message, ##__VA_ARGS__); } while(0) +//#define LOG(message, ...) do {\ + const auto now = std::chrono::time_point_cast(std::chrono::system_clock::now());\ + fmt::println("[{:%d-%m-%y %H:%M:%S} {:s}] " message, now, FILENAME_AND_LINE, ##__VA_ARGS__);\ +} while(0) +#define LOG(message, ...) Log::Info(message, ##__VA_ARGS__) + +//#define LOG_DEBUG(message, ...) do { auto str = FILENAME_AND_LINE; Game::logger->LogDebug(str, message, ##__VA_ARGS__); } while(0) +#define LOG_DEBUG(message, ...) Log::Debug(message, ##__VA_ARGS__) // Writer class for writing data to files. class Writer { diff --git a/dCommon/dClient/PackIndex.cpp b/dCommon/dClient/PackIndex.cpp index 0d7a7fe9..c1743c93 100644 --- a/dCommon/dClient/PackIndex.cpp +++ b/dCommon/dClient/PackIndex.cpp @@ -23,7 +23,7 @@ PackIndex::PackIndex(const std::filesystem::path& filePath) { m_PackFileIndices.push_back(packFileIndex); } - LOG("Loaded pack catalog with %i pack files and %i files", m_PackPaths.size(), m_PackFileIndices.size()); + Log::Info("Loaded pack catalog with {:d} pack files and {:d} files", m_PackPaths.size(), m_PackFileIndices.size()); for (auto& item : m_PackPaths) { std::replace(item.begin(), item.end(), '\\', '/'); diff --git a/dCommon/dEnums/StringifiedEnum.h b/dCommon/dEnums/StringifiedEnum.h index 1816d705..d82f178b 100644 --- a/dCommon/dEnums/StringifiedEnum.h +++ b/dCommon/dEnums/StringifiedEnum.h @@ -6,10 +6,10 @@ namespace StringifiedEnum { template - const std::string_view ToString(const T e) { + constexpr std::string_view ToString(const T e) { static_assert(std::is_enum_v, "Not an enum"); // Check type - constexpr auto& sv = magic_enum::enum_entries(); + constexpr const auto& sv = magic_enum::enum_entries(); const auto it = std::lower_bound( sv.begin(), sv.end(), e, diff --git a/dDatabase/CDClientDatabase/CDClientManager.cpp b/dDatabase/CDClientDatabase/CDClientManager.cpp index 0e05c0b8..1ab6e84d 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.cpp +++ b/dDatabase/CDClientDatabase/CDClientManager.cpp @@ -157,7 +157,7 @@ void CDClientManager::LoadValuesFromDatabase() { } void CDClientManager::LoadValuesFromDefaults() { - LOG("Loading default CDClient tables!"); + Log::Info("Loading default CDClient tables!"); CDPetComponentTable::Instance().LoadValuesFromDefaults(); } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp index f3371ecb..14ca6c6e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp @@ -57,7 +57,7 @@ CDPetComponent& CDPetComponentTable::GetByID(const uint32_t componentID) { auto& entries = GetEntriesMutable(); auto itr = entries.find(componentID); if (itr == entries.end()) { - LOG("Unable to load pet component (ID %i) values from database! Using default values instead.", componentID); + Log::Warn("Unable to load pet component (ID {:d}) values from database! Using default values instead.", componentID); return defaultEntry; } return itr->second; diff --git a/dDatabase/CDClientDatabase/CMakeLists.txt b/dDatabase/CDClientDatabase/CMakeLists.txt index 13d59ffb..9a2251b6 100644 --- a/dDatabase/CDClientDatabase/CMakeLists.txt +++ b/dDatabase/CDClientDatabase/CMakeLists.txt @@ -15,7 +15,7 @@ target_include_directories(dDatabaseCDClient PUBLIC "." "${PROJECT_SOURCE_DIR}/dCommon" "${PROJECT_SOURCE_DIR}/dCommon/dEnums" ) -target_link_libraries(dDatabaseCDClient PRIVATE sqlite3) +target_link_libraries(dDatabaseCDClient PRIVATE fmt sqlite3) if (${CDCLIENT_CACHE_ALL}) add_compile_definitions(dDatabaseCDClient PRIVATE CDCLIENT_CACHE_ALL=${CDCLIENT_CACHE_ALL}) diff --git a/dDatabase/CMakeLists.txt b/dDatabase/CMakeLists.txt index 004bdc14..ce431d21 100644 --- a/dDatabase/CMakeLists.txt +++ b/dDatabase/CMakeLists.txt @@ -4,4 +4,5 @@ add_subdirectory(GameDatabase) add_library(dDatabase STATIC "MigrationRunner.cpp") target_include_directories(dDatabase PUBLIC ".") target_link_libraries(dDatabase - PUBLIC dDatabaseCDClient dDatabaseGame) + PUBLIC dDatabaseCDClient dDatabaseGame + PRIVATE fmt) diff --git a/dDatabase/GameDatabase/CMakeLists.txt b/dDatabase/GameDatabase/CMakeLists.txt index 09ca7251..31fa63c7 100644 --- a/dDatabase/GameDatabase/CMakeLists.txt +++ b/dDatabase/GameDatabase/CMakeLists.txt @@ -16,6 +16,7 @@ target_include_directories(dDatabaseGame PUBLIC "." ) target_link_libraries(dDatabaseGame PUBLIC MariaDB::ConnCpp + PRIVATE fmt INTERFACE dCommon) # Glob together all headers that need to be precompiled diff --git a/dDatabase/GameDatabase/GameDatabase.h b/dDatabase/GameDatabase/GameDatabase.h index bcd8550b..6991aa51 100644 --- a/dDatabase/GameDatabase/GameDatabase.h +++ b/dDatabase/GameDatabase/GameDatabase.h @@ -30,7 +30,7 @@ namespace sql { }; #ifdef _DEBUG -# define DLU_SQL_TRY_CATCH_RETHROW(x) do { try { x; } catch (sql::SQLException& ex) { LOG("SQL Error: %s", ex.what()); throw; } } while(0) +# define DLU_SQL_TRY_CATCH_RETHROW(x) do { try { x; } catch (sql::SQLException& ex) { Log::Warn("SQL Error: {:s}", ex.what()); throw; } } while(0) #else # define DLU_SQL_TRY_CATCH_RETHROW(x) x #endif // _DEBUG diff --git a/dDatabase/GameDatabase/MySQL/MySQLDatabase.cpp b/dDatabase/GameDatabase/MySQL/MySQLDatabase.cpp index 259c3866..56fd88e3 100644 --- a/dDatabase/GameDatabase/MySQL/MySQLDatabase.cpp +++ b/dDatabase/GameDatabase/MySQL/MySQLDatabase.cpp @@ -53,8 +53,8 @@ void MySQLDatabase::Connect() { void MySQLDatabase::Destroy(std::string source) { if (!con) return; - if (source.empty()) LOG("Destroying MySQL connection!"); - else LOG("Destroying MySQL connection from %s!", source.c_str()); + if (source.empty()) Log::Info("Destroying MySQL connection!"); + else Log::Info("Destroying MySQL connection from {:s}!", source); con->close(); delete con; @@ -68,7 +68,7 @@ void MySQLDatabase::ExecuteCustomQuery(const std::string_view query) { sql::PreparedStatement* MySQLDatabase::CreatePreppedStmt(const std::string& query) { if (!con) { Connect(); - LOG("Trying to reconnect to MySQL"); + Log::Info("Trying to reconnect to MySQL"); } if (!con->isValid() || con->isClosed()) { @@ -77,7 +77,7 @@ sql::PreparedStatement* MySQLDatabase::CreatePreppedStmt(const std::string& quer con = nullptr; Connect(); - LOG("Trying to reconnect to MySQL from invalid or closed connection"); + Log::Info("Trying to reconnect to MySQL from invalid or closed connection"); } return con->prepareStatement(sql::SQLString(query.c_str(), query.length())); diff --git a/dDatabase/GameDatabase/MySQL/MySQLDatabase.h b/dDatabase/GameDatabase/MySQL/MySQLDatabase.h index 836ab56c..a7d2e17f 100644 --- a/dDatabase/GameDatabase/MySQL/MySQLDatabase.h +++ b/dDatabase/GameDatabase/MySQL/MySQLDatabase.h @@ -147,85 +147,85 @@ private: template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::string_view param) { - // LOG("%s", param.data()); + // Log::Info("{:s}", param); stmt->setString(index, param.data()); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const char* param) { - // LOG("%s", param); + // Log::Info("{:s}", param); stmt->setString(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::string param) { - // LOG("%s", param.c_str()); - stmt->setString(index, param.c_str()); + // Log::Info("{:s}", param); + stmt->setString(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int8_t param) { - // LOG("%u", param); + // Log::Info("{:d}", param); stmt->setByte(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint8_t param) { - // LOG("%d", param); + // Log::Info("{:d}", param); stmt->setByte(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int16_t param) { - // LOG("%u", param); + // Log::Info("{:d}", param); stmt->setShort(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint16_t param) { - // LOG("%d", param); + // Log::Info("{:d}", param); stmt->setShort(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint32_t param) { - // LOG("%u", param); + // Log::Info("{:d}", param); stmt->setUInt(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int32_t param) { - // LOG("%d", param); + // Log::Info("{:d}", param); stmt->setInt(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int64_t param) { - // LOG("%llu", param); + // Log::Info("{:d}", param); stmt->setInt64(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint64_t param) { - // LOG("%llu", param); + // Log::Info("{:d}", param); stmt->setUInt64(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const float param) { - // LOG("%f", param); + // Log::Info({:f}", param); stmt->setFloat(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const double param) { - // LOG("%f", param); + // Log::Info("{:f}", param); stmt->setDouble(index, param); } template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const bool param) { - // LOG("%d", param); + // Log::Info("{:d}", param); stmt->setBoolean(index, param); } @@ -239,10 +239,10 @@ inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::istr template<> inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::optional param) { if (param) { - // LOG("%d", param.value()); + // Log::Info("{:f}", param.value()); stmt->setInt(index, param.value()); } else { - // LOG("Null"); + // Log::Info("Null"); stmt->setNull(index, sql::DataType::SQLNULL); } } diff --git a/dDatabase/GameDatabase/MySQL/Tables/PropertyContents.cpp b/dDatabase/GameDatabase/MySQL/Tables/PropertyContents.cpp index dba82d56..38f351ca 100644 --- a/dDatabase/GameDatabase/MySQL/Tables/PropertyContents.cpp +++ b/dDatabase/GameDatabase/MySQL/Tables/PropertyContents.cpp @@ -38,8 +38,8 @@ void MySQLDatabase::InsertNewPropertyModel(const LWOOBJID& propertyId, const IPr 0, // behavior 4. TODO implement this. 0 // behavior 5. TODO implement this. ); - } catch (sql::SQLException& e) { - LOG("Error inserting new property model: %s", e.what()); + } catch (const sql::SQLException& e) { + Log::Warn("Error inserting new property model: {:s}", e.what()); } } diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 8034a3e2..ba0b9b19 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -45,7 +45,7 @@ void MigrationRunner::RunMigrations() { if (Database::Get()->IsMigrationRun(migration.name)) continue; - LOG("Running migration: %s", migration.name.c_str()); + Log::Info("Running migration: {:s}", migration.name); if (migration.name == "dlu/5_brick_model_sd0.sql") { runSd0Migrations = true; } else { @@ -56,7 +56,7 @@ void MigrationRunner::RunMigrations() { } if (finalSQL.empty() && !runSd0Migrations) { - LOG("Server database is up to date."); + Log::Info("Server database is up to date."); return; } @@ -67,7 +67,7 @@ void MigrationRunner::RunMigrations() { if (query.empty()) continue; Database::Get()->ExecuteCustomQuery(query.c_str()); } catch (sql::SQLException& e) { - LOG("Encountered error running migration: %s", e.what()); + Log::Info("Encountered error running migration: {:s}", e.what()); } } } @@ -75,9 +75,9 @@ void MigrationRunner::RunMigrations() { // Do this last on the off chance none of the other migrations have been run yet. if (runSd0Migrations) { uint32_t numberOfUpdatedModels = BrickByBrickFix::UpdateBrickByBrickModelsToSd0(); - LOG("%i models were updated from zlib to sd0.", numberOfUpdatedModels); + Log::Info("{:d} models were updated from zlib to sd0.", numberOfUpdatedModels); uint32_t numberOfTruncatedModels = BrickByBrickFix::TruncateBrokenBrickByBrickXml(); - LOG("%i models were truncated from the database.", numberOfTruncatedModels); + Log::Info("{:d} models were truncated from the database.", numberOfTruncatedModels); } } @@ -111,14 +111,14 @@ void MigrationRunner::RunSQLiteMigrations() { // Doing these 1 migration at a time since one takes a long time and some may think it is crashing. // This will at the least guarentee that the full migration needs to be run in order to be counted as "migrated". - LOG("Executing migration: %s. This may take a while. Do not shut down server.", migration.name.c_str()); + Log::Info("Executing migration: {:s}. This may take a while. Do not shut down server.", migration.name); CDClientDatabase::ExecuteQuery("BEGIN TRANSACTION;"); for (const auto& dml : GeneralUtils::SplitString(migration.data, ';')) { if (dml.empty()) continue; try { CDClientDatabase::ExecuteDML(dml.c_str()); } catch (CppSQLite3Exception& e) { - LOG("Encountered error running DML command: (%i) : %s", e.errorCode(), e.errorMessage()); + Log::Warn("Encountered error running DML command: ({:d}) : {:s}", e.errorCode(), e.errorMessage()); } } @@ -129,5 +129,5 @@ void MigrationRunner::RunSQLiteMigrations() { CDClientDatabase::ExecuteQuery("COMMIT;"); } - LOG("CDServer database is up to date."); + Log::Info("CDServer database is up to date."); } diff --git a/dGame/Character.cpp b/dGame/Character.cpp index eab7583f..3b0328ec 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -82,16 +82,16 @@ void Character::DoQuickXMLDataParse() { if (!m_Doc) return; if (m_Doc->Parse(m_XMLData.c_str(), m_XMLData.size()) == 0) { - LOG("Loaded xmlData for character %s (%i)!", m_Name.c_str(), m_ID); + Log::Info("Loaded xmlData for character {:s} ({:d})!", m_Name, m_ID); } else { - LOG("Failed to load xmlData!"); + Log::Warn("Failed to load xmlData!"); //Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true); return; } tinyxml2::XMLElement* mf = m_Doc->FirstChildElement("obj")->FirstChildElement("mf"); if (!mf) { - LOG("Failed to find mf tag!"); + Log::Warn("Failed to find mf tag!"); return; } @@ -110,14 +110,14 @@ void Character::DoQuickXMLDataParse() { tinyxml2::XMLElement* inv = m_Doc->FirstChildElement("obj")->FirstChildElement("inv"); if (!inv) { - LOG("Char has no inv!"); + Log::Warn("Char has no inv!"); return; } tinyxml2::XMLElement* bag = inv->FirstChildElement("items")->FirstChildElement("in"); if (!bag) { - LOG("Couldn't find bag0!"); + Log::Warn("Couldn't find bag0!"); return; } @@ -310,7 +310,7 @@ void Character::SaveXMLToDatabase() { //Call upon the entity to update our xmlDoc: if (!m_OurEntity) { - LOG("%i:%s didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!", this->GetID(), this->GetName().c_str()); + Log::Warn("{:d}:{:s} didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!", this->GetID(), this->GetName()); return; } @@ -321,7 +321,7 @@ void Character::SaveXMLToDatabase() { //For metrics, log the time it took to save: auto end = std::chrono::system_clock::now(); std::chrono::duration elapsed = end - start; - LOG("%i:%s Saved character to Database in: %fs", this->GetID(), this->GetName().c_str(), elapsed.count()); + Log::Info("{:d}:{:s} Saved character to Database in: {:f}s", this->GetID(), this->GetName(), elapsed.count()); } void Character::SetIsNewLogin() { @@ -334,7 +334,7 @@ void Character::SetIsNewLogin() { auto* nextChild = currentChild->NextSiblingElement(); if (currentChild->Attribute("si")) { flags->DeleteChild(currentChild); - LOG("Removed isLoggedIn flag from character %i:%s, saving character to database", GetID(), GetName().c_str()); + Log::Info("Removed isLoggedIn flag from character {:d}:{:s}, saving character to database", GetID(), GetName()); WriteToDatabase(); } currentChild = nextChild; diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index 347bd68e..adaf90dd 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -236,7 +236,7 @@ void Leaderboard::SetupLeaderboard(bool weekly, uint32_t resultStart, uint32_t r baseLookup += std::to_string(static_cast(this->relatedPlayer)); } baseLookup += " LIMIT 1"; - LOG_DEBUG("query is %s", baseLookup.c_str()); + Log::Debug("query is {:s}", baseLookup); std::unique_ptr baseQuery(Database::Get()->CreatePreppedStmt(baseLookup)); baseQuery->setInt(1, this->gameID); std::unique_ptr baseResult(baseQuery->executeQuery()); @@ -251,7 +251,7 @@ void Leaderboard::SetupLeaderboard(bool weekly, uint32_t resultStart, uint32_t r int32_t res = snprintf(lookupBuffer.get(), STRING_LENGTH, queryBase.c_str(), orderBase.data(), filter.c_str(), resultStart, resultEnd); DluAssert(res != -1); std::unique_ptr query(Database::Get()->CreatePreppedStmt(lookupBuffer.get())); - LOG_DEBUG("Query is %s vars are %i %i %i", lookupBuffer.get(), this->gameID, this->relatedPlayer, relatedPlayerLeaderboardId); + Log::Debug("Query is {:s} vars are {:d} {:d} {:d}", lookupBuffer.get(), this->gameID, this->relatedPlayer, relatedPlayerLeaderboardId); query->setInt(1, this->gameID); if (this->infoType == InfoType::Friends) { query->setInt(2, this->relatedPlayer); @@ -358,7 +358,7 @@ void LeaderboardManager::SaveScore(const LWOOBJID& playerID, const GameID activi } case Leaderboard::Type::None: default: - LOG("Unknown leaderboard type %i for game %i. Cannot save score!", leaderboardType, activityId); + Log::Warn("Unknown leaderboard type {:d} for game {:d}. Cannot save score!", GeneralUtils::ToUnderlying(leaderboardType), activityId); return; } bool newHighScore = lowerScoreBetter ? newScore < oldScore : newScore > oldScore; @@ -377,7 +377,7 @@ void LeaderboardManager::SaveScore(const LWOOBJID& playerID, const GameID activi } else { saveQuery = FormatInsert(leaderboardType, newScore, false); } - LOG("save query %s %i %i", saveQuery.c_str(), playerID, activityId); + Log::Info("save query {:s} {:d} {:d}", saveQuery, playerID, activityId); std::unique_ptr saveStatement(Database::Get()->CreatePreppedStmt(saveQuery)); saveStatement->setInt(1, playerID); saveStatement->setInt(2, activityId); diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index c7143354..5932a2ed 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -125,7 +125,7 @@ void Trade::Complete() { // First verify both players have the coins and items requested for the trade. if (characterA->GetCoins() < m_CoinsA || characterB->GetCoins() < m_CoinsB) { - LOG("Possible coin trade cheating attempt! Aborting trade."); + Log::Warn("Possible coin trade cheating attempt! Aborting trade."); return; } @@ -133,11 +133,11 @@ void Trade::Complete() { auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId); if (itemToRemove) { if (itemToRemove->GetCount() < tradeItem.itemCount) { - LOG("Possible cheating attempt from %s in trading!!! Aborting trade", characterA->GetName().c_str()); + Log::Warn("Possible cheating attempt from {:s} in trading!!! Aborting trade", characterA->GetName()); return; } } else { - LOG("Possible cheating attempt from %s in trading due to item not being available!!!", characterA->GetName().c_str()); + Log::Warn("Possible cheating attempt from {:s} in trading due to item not being available!!!", characterA->GetName()); return; } } @@ -146,11 +146,11 @@ void Trade::Complete() { auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId); if (itemToRemove) { if (itemToRemove->GetCount() < tradeItem.itemCount) { - LOG("Possible cheating attempt from %s in trading!!! Aborting trade", characterB->GetName().c_str()); + Log::Warn("Possible cheating attempt from {:s} in trading!!! Aborting trade", characterB->GetName()); return; } } else { - LOG("Possible cheating attempt from %s in trading due to item not being available!!! Aborting trade", characterB->GetName().c_str()); + Log::Warn("Possible cheating attempt from {:s} in trading due to item not being available!!! Aborting trade", characterB->GetName()); return; } } diff --git a/dGame/User.cpp b/dGame/User.cpp index 0b2c3c3f..898b400a 100644 --- a/dGame/User.cpp +++ b/dGame/User.cpp @@ -38,7 +38,7 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: Character* character = new Character(lastUsedCharacterId, this); character->UpdateFromDatabase(); m_Characters.push_back(character); - LOG("Loaded %i as it is the last used char", lastUsedCharacterId); + Log::Info("Loaded {:d} as it is the last used char", lastUsedCharacterId); } } } @@ -106,7 +106,7 @@ void User::UserOutOfSync() { m_AmountOfTimesOutOfSync++; if (m_AmountOfTimesOutOfSync > m_MaxDesyncAllowed) { //YEET - LOG("User %s was out of sync %i times out of %i, disconnecting for suspected speedhacking.", m_Username.c_str(), m_AmountOfTimesOutOfSync, m_MaxDesyncAllowed); + Log::Warn("User {:s} was out of sync {:d} times out of {:d}, disconnecting for suspected speedhacking.", m_Username, m_AmountOfTimesOutOfSync, m_MaxDesyncAllowed); Game::server->Disconnect(this->m_SystemAddress, eServerDisconnectIdentifiers::PLAY_SCHEDULE_TIME_DONE); } } diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 0fde2eb6..399dbb37 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -45,7 +45,7 @@ void UserManager::Initialize() { auto fnStream = Game::assetManager->GetFile("names/minifigname_first.txt"); if (!fnStream) { - LOG("Failed to load %s", (Game::assetManager->GetResPath() / "names/minifigname_first.txt").string().c_str()); + Log::Warn("Failed to load {:s}", (Game::assetManager->GetResPath() / "names/minifigname_first.txt").string()); throw std::runtime_error("Aborting initialization due to missing minifigure name file."); } @@ -57,7 +57,7 @@ void UserManager::Initialize() { auto mnStream = Game::assetManager->GetFile("names/minifigname_middle.txt"); if (!mnStream) { - LOG("Failed to load %s", (Game::assetManager->GetResPath() / "names/minifigname_middle.txt").string().c_str()); + Log::Warn("Failed to load {:s}", (Game::assetManager->GetResPath() / "names/minifigname_middle.txt").string()); throw std::runtime_error("Aborting initialization due to missing minifigure name file."); } @@ -69,7 +69,7 @@ void UserManager::Initialize() { auto lnStream = Game::assetManager->GetFile("names/minifigname_last.txt"); if (!lnStream) { - LOG("Failed to load %s", (Game::assetManager->GetResPath() / "names/minifigname_last.txt").string().c_str()); + Log::Warn("Failed to load {:s}", (Game::assetManager->GetResPath() / "names/minifigname_last.txt").string()); throw std::runtime_error("Aborting initialization due to missing minifigure name file."); } @@ -82,7 +82,7 @@ void UserManager::Initialize() { // Load our pre-approved names: auto chatListStream = Game::assetManager->GetFile("chatplus_en_us.txt"); if (!chatListStream) { - LOG("Failed to load %s", (Game::assetManager->GetResPath() / "chatplus_en_us.txt").string().c_str()); + Log::Warn("Failed to load {:s}", (Game::assetManager->GetResPath() / "chatplus_en_us.txt").string()); throw std::runtime_error("Aborting initialization due to missing chat whitelist file."); } @@ -145,7 +145,7 @@ bool UserManager::DeleteUser(const SystemAddress& sysAddr) { void UserManager::DeletePendingRemovals() { for (auto* user : m_UsersToDelete) { - LOG("Deleted user %i", user->GetAccountID()); + Log::Info("Deleted user {:d}", user->GetAccountID()); delete user; } @@ -306,27 +306,27 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) LOT pantsLOT = FindCharPantsID(pantsColor); if (!name.empty() && Database::Get()->GetCharacterInfo(name)) { - LOG("AccountID: %i chose unavailable name: %s", u->GetAccountID(), name.c_str()); + Log::Info("AccountID: {:d} chose unavailable name: {:s}", u->GetAccountID(), name); WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::CUSTOM_NAME_IN_USE); return; } if (Database::Get()->GetCharacterInfo(predefinedName)) { - LOG("AccountID: %i chose unavailable predefined name: %s", u->GetAccountID(), predefinedName.c_str()); + Log::Info("AccountID: {:d} chose unavailable predefined name: {:s}", u->GetAccountID(), predefinedName); WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::PREDEFINED_NAME_IN_USE); return; } if (name.empty()) { - LOG("AccountID: %i is creating a character with predefined name: %s", u->GetAccountID(), predefinedName.c_str()); + Log::Info("AccountID: {:d} is creating a character with predefined name: {:s}", u->GetAccountID(), predefinedName); } else { - LOG("AccountID: %i is creating a character with name: %s (temporary: %s)", u->GetAccountID(), name.c_str(), predefinedName.c_str()); + Log::Info("AccountID: {:d} is creating a character with name: {:s} (temporary: {:s})", u->GetAccountID(), name, predefinedName); } //Now that the name is ok, we can get an objectID from Master: ObjectIDManager::RequestPersistentID([=, this](uint32_t objectID) mutable { if (Database::Get()->GetCharacterInfo(objectID)) { - LOG("Character object id unavailable, check object_id_tracker!"); + Log::Warn("Character object id unavailable, check object_id_tracker!"); WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::OBJECT_ID_UNAVAILABLE); return; } @@ -397,7 +397,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) { User* u = GetUser(sysAddr); if (!u) { - LOG("Couldn't get user to delete character"); + Log::Warn("Couldn't get user to delete character"); return; } @@ -406,7 +406,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) inStream.Read(objectID); uint32_t charID = static_cast(objectID); - LOG("Received char delete req for ID: %llu (%u)", objectID, charID); + Log::Info("Received char delete req for ID: {:d} ({:d})", objectID, charID); bool hasCharacter = CheatDetection::VerifyLwoobjidIsSender( objectID, @@ -418,7 +418,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) if (!hasCharacter) { WorldPackets::SendCharacterDeleteResponse(sysAddr, false); } else { - LOG("Deleting character %i", charID); + Log::Info("Deleting character {:d}", charID); Database::Get()->DeleteCharacter(charID); CBITSTREAM; @@ -433,7 +433,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) { User* u = GetUser(sysAddr); if (!u) { - LOG("Couldn't get user to delete character"); + Log::Warn("Couldn't get user to delete character"); return; } @@ -444,7 +444,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) GeneralUtils::ClearBit(objectID, eObjectBits::PERSISTENT); uint32_t charID = static_cast(objectID); - LOG("Received char rename request for ID: %llu (%u)", objectID, charID); + Log::Info("Received char rename request for ID: {:d} ({:d})", objectID, charID); LUWString LUWStringName; inStream.Read(LUWStringName); @@ -479,12 +479,12 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) if (!Database::Get()->GetCharacterInfo(newName)) { if (IsNamePreapproved(newName)) { Database::Get()->SetCharacterName(charID, newName); - LOG("Character %s now known as %s", character->GetName().c_str(), newName.c_str()); + Log::Info("Character {:s} now known as {:s}", character->GetName(), newName); WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::SUCCESS); UserManager::RequestCharacterList(sysAddr); } else { Database::Get()->SetPendingCharacterName(charID, newName); - LOG("Character %s has been renamed to %s and is pending approval by a moderator.", character->GetName().c_str(), newName.c_str()); + Log::Info("Character {:s} has been renamed to {:s} and is pending approval by a moderator.", character->GetName(), newName); WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::SUCCESS); UserManager::RequestCharacterList(sysAddr); } @@ -492,7 +492,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::NAME_IN_USE); } } else { - LOG("Unknown error occurred when renaming character, either hasCharacter or character variable != true."); + Log::Warn("Unknown error occurred when renaming character, either hasCharacter or character variable != true."); WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::UNKNOWN_ERROR); } } @@ -500,7 +500,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID) { User* u = GetUser(sysAddr); if (!u) { - LOG("Couldn't get user to log in character"); + Log::Warn("Couldn't get user to log in character"); return; } @@ -519,7 +519,7 @@ void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID if (zoneID == LWOZONEID_INVALID) zoneID = 1000; //Send char to VE ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneID, character->GetZoneClone(), false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - LOG("Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Log::Info("Transferring {:s} to Zone {:d} (Instance {:d} | Clone {:d} | Mythran Shift: {:s}) with IP {:s} and Port {:d}", character->GetName(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP, serverPort); if (character) { character->SetZoneID(zoneID); character->SetZoneInstance(zoneInstance); @@ -529,7 +529,7 @@ void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID return; }); } else { - LOG("Unknown error occurred when logging in a character, either hasCharacter or character variable != true."); + Log::Warn("Unknown error occurred when logging in a character, either hasCharacter or character variable != true."); } } @@ -546,7 +546,7 @@ uint32_t FindCharShirtID(uint32_t shirtColor, uint32_t shirtStyle) { tableData.finalize(); return shirtLOT; } catch (const std::exception& ex) { - LOG("Could not look up shirt %i %i: %s", shirtColor, shirtStyle, ex.what()); + Log::Warn("Could not look up shirt {:d} {:d}: {:s}", shirtColor, shirtStyle, ex.what()); // in case of no shirt found in CDServer, return problematic red vest. return 4069; } @@ -564,7 +564,7 @@ uint32_t FindCharPantsID(uint32_t pantsColor) { tableData.finalize(); return pantsLOT; } catch (const std::exception& ex) { - LOG("Could not look up pants %i: %s", pantsColor, ex.what()); + Log::Warn("Could not look up pants {:d}: {:s}", pantsColor, ex.what()); // in case of no pants color found in CDServer, return red pants. return 2508; } diff --git a/dGame/dBehaviors/AirMovementBehavior.cpp b/dGame/dBehaviors/AirMovementBehavior.cpp index 46d18680..7925864f 100644 --- a/dGame/dBehaviors/AirMovementBehavior.cpp +++ b/dGame/dBehaviors/AirMovementBehavior.cpp @@ -9,7 +9,7 @@ void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bi uint32_t handle{}; if (!bitStream.Read(handle)) { - LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read handle from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; } @@ -26,14 +26,14 @@ void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitS uint32_t behaviorId{}; if (!bitStream.Read(behaviorId)) { - LOG("Unable to read behaviorId from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read behaviorId from bitStream, aborting Sync! {:d}", bitStream.GetNumberOfUnreadBits()); return; } LWOOBJID target{}; if (!bitStream.Read(target)) { - LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read target from bitStream, aborting Sync! {:d}", bitStream.GetNumberOfUnreadBits()); return; } diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index ce41785f..4d435afd 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -16,7 +16,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& b uint32_t targetCount{}; if (!bitStream.Read(targetCount)) { - LOG("Unable to read targetCount from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read targetCount from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; } @@ -28,7 +28,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& b } if (targetCount > this->m_maxTargets) { - LOG("Serialized size is greater than max targets! Size: %i, Max: %i", targetCount, this->m_maxTargets); + Log::Warn("Serialized size is greater than max targets! Size: {:d}, Max: {:d}", targetCount, this->m_maxTargets); return; } @@ -41,7 +41,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& b for (auto i = 0u; i < targetCount; ++i) { LWOOBJID target{}; if (!bitStream.Read(target)) { - LOG("failed to read in target %i from bitStream, aborting target Handle!", i); + Log::Warn("failed to read in target {:d} from bitStream, aborting target Handle!", i); }; targets.push_back(target); } diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index 105a1327..63554275 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -8,7 +8,7 @@ void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bi uint32_t handle{}; if (!bitStream.Read(handle)) { - LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read handle from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; }; diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index 3d45d9a7..b9d2512b 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -34,10 +34,10 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bi uint16_t allocatedBits{}; if (!bitStream.Read(allocatedBits) || allocatedBits == 0) { - LOG_DEBUG("No allocated bits"); + Log::Debug("No allocated bits"); return; } - LOG_DEBUG("Number of allocated bits %i", allocatedBits); + Log::Debug("Number of allocated bits {:d}", allocatedBits); const auto baseAddress = bitStream.GetReadOffset(); DoHandleBehavior(context, bitStream, branch); @@ -48,13 +48,13 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bi void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* targetEntity = Game::entityManager->GetEntity(branch.target); if (!targetEntity) { - LOG("Target targetEntity %llu not found.", branch.target); + Log::Warn("Target targetEntity {:d} not found.", branch.target); return; } auto* destroyableComponent = targetEntity->GetComponent(); if (!destroyableComponent) { - LOG("No destroyable found on the obj/lot %llu/%i", branch.target, targetEntity->GetLOT()); + Log::Warn("No destroyable found on the obj/lot {:d}/{:d}", branch.target, targetEntity->GetLOT()); return; } @@ -63,7 +63,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit bool isSuccess{}; if (!bitStream.Read(isBlocked)) { - LOG("Unable to read isBlocked"); + Log::Warn("Unable to read isBlocked"); return; } @@ -136,7 +136,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit break; default: if (static_cast(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) { - LOG("Unknown success state (%i)!", successState); + Log::Warn("Unknown success state ({:d})!", successState); return; } this->m_OnFailImmune->Handle(context, bitStream, branch); @@ -241,7 +241,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet break; default: if (static_cast(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) { - LOG("Unknown success state (%i)!", successState); + Log::Warn("Unknown success state ({:d})!", GeneralUtils::ToUnderlying(successState)); break; } this->m_OnFailImmune->Calculate(context, bitStream, branch); diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index 36607a66..c43b957a 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -281,12 +281,12 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { case BehaviorTemplates::BEHAVIOR_MOUNT: break; case BehaviorTemplates::BEHAVIOR_SKILL_SET: break; default: - //LOG("Failed to load behavior with invalid template id (%i)!", templateId); + //Log::Warn("Failed to load behavior with invalid template id ({:d})!", templateId); break; } if (behavior == nullptr) { - //LOG("Failed to load unimplemented template id (%i)!", templateId); + //Log::Warn("Failed to load unimplemented template id ({:d})!", templateId); behavior = new EmptyBehavior(behaviorId); } @@ -309,7 +309,7 @@ BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { } if (templateID == BehaviorTemplates::BEHAVIOR_EMPTY && behaviorId != 0) { - LOG("Failed to load behavior template with id (%i)!", behaviorId); + Log::Warn("Failed to load behavior template with id ({:d})!", behaviorId); } return templateID; @@ -429,7 +429,7 @@ Behavior::Behavior(const uint32_t behaviorId) { // Make sure we do not proceed if we are trying to load an invalid behavior if (templateInDatabase.behaviorID == 0) { - LOG("Failed to load behavior with id (%i)!", behaviorId); + Log::Warn("Failed to load behavior with id ({:d})!", behaviorId); this->m_effectId = 0; this->m_effectHandle = nullptr; diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index 5ca335b1..4dfc1e71 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -126,7 +126,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream& bit } if (!found) { - LOG("Failed to find behavior sync entry with sync id (%i)!", syncId); + Log::Warn("Failed to find behavior sync entry with sync id ({:d})!", syncId); return; } @@ -135,7 +135,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream& bit const auto branch = entry.branchContext; if (behavior == nullptr) { - LOG("Invalid behavior for sync id (%i)!", syncId); + Log::Warn("Invalid behavior for sync id ({:d})!", syncId); return; } @@ -317,7 +317,7 @@ void BehaviorContext::FilterTargets(std::vector& targets, std::forward_ // if the caster is not there, return empty targets list auto* caster = Game::entityManager->GetEntity(this->caster); if (!caster) { - LOG_DEBUG("Invalid caster for (%llu)!", this->originator); + Log::Debug("Invalid caster for ({:d})!", this->originator); targets.clear(); return; } diff --git a/dGame/dBehaviors/ChainBehavior.cpp b/dGame/dBehaviors/ChainBehavior.cpp index feb27988..3e9c245d 100644 --- a/dGame/dBehaviors/ChainBehavior.cpp +++ b/dGame/dBehaviors/ChainBehavior.cpp @@ -7,7 +7,7 @@ void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStrea uint32_t chainIndex{}; if (!bitStream.Read(chainIndex)) { - LOG("Unable to read chainIndex from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read chainIndex from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; } @@ -16,7 +16,7 @@ void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStrea if (chainIndex < this->m_behaviors.size()) { this->m_behaviors.at(chainIndex)->Handle(context, bitStream, branch); } else { - LOG("chainIndex out of bounds, aborting handle of chain %i bits unread %i", chainIndex, bitStream.GetNumberOfUnreadBits()); + Log::Warn("chainIndex out of bounds, aborting handle of chain {:d} bits unread {:d}", chainIndex, bitStream.GetNumberOfUnreadBits()); } } diff --git a/dGame/dBehaviors/ForceMovementBehavior.cpp b/dGame/dBehaviors/ForceMovementBehavior.cpp index 83c6fabc..0a8c0e1d 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.cpp +++ b/dGame/dBehaviors/ForceMovementBehavior.cpp @@ -13,7 +13,7 @@ void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream& uint32_t handle{}; if (!bitStream.Read(handle)) { - LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read handle from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; } context->RegisterSyncBehavior(handle, this, branch, this->m_Duration); @@ -22,13 +22,13 @@ void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream& void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { uint32_t next{}; if (!bitStream.Read(next)) { - LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read target from bitStream, aborting Sync! {:d}", bitStream.GetNumberOfUnreadBits()); return; } LWOOBJID target{}; if (!bitStream.Read(target)) { - LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read target from bitStream, aborting Sync! {:d}", bitStream.GetNumberOfUnreadBits()); return; } diff --git a/dGame/dBehaviors/InterruptBehavior.cpp b/dGame/dBehaviors/InterruptBehavior.cpp index 0b23c34d..2b26c281 100644 --- a/dGame/dBehaviors/InterruptBehavior.cpp +++ b/dGame/dBehaviors/InterruptBehavior.cpp @@ -12,7 +12,7 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitS bool unknown = false; if (!bitStream.Read(unknown)) { - LOG("Unable to read unknown1 from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read unknown1 from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; }; @@ -23,7 +23,7 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitS bool unknown = false; if (!bitStream.Read(unknown)) { - LOG("Unable to read unknown2 from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read unknown2 from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; }; @@ -35,7 +35,7 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitS bool unknown = false; if (!bitStream.Read(unknown)) { - LOG("Unable to read unknown3 from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read unknown3 from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; }; } diff --git a/dGame/dBehaviors/KnockbackBehavior.cpp b/dGame/dBehaviors/KnockbackBehavior.cpp index 4d7bf2ea..420bb588 100644 --- a/dGame/dBehaviors/KnockbackBehavior.cpp +++ b/dGame/dBehaviors/KnockbackBehavior.cpp @@ -13,7 +13,7 @@ void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitS bool unknown{}; if (!bitStream.Read(unknown)) { - LOG("Unable to read unknown from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read unknown from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; }; } diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index cc2d7b34..07c628ee 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -15,7 +15,7 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream& this->m_movingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { return; } - LOG("Unable to read movementType from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read movementType from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; }; diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 3e5118f7..700cc3bd 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -12,14 +12,14 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea LWOOBJID target{}; if (!bitStream.Read(target)) { - LOG("Unable to read target from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read target from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; }; auto* entity = Game::entityManager->GetEntity(context->originator); if (entity == nullptr) { - LOG("Failed to find originator (%llu)!", context->originator); + Log::Warn("Failed to find originator ({:d})!", context->originator); return; } @@ -27,7 +27,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea auto* skillComponent = entity->GetComponent(); if (skillComponent == nullptr) { - LOG("Failed to find skill component for (%llu)!", -context->originator); + Log::Warn("Failed to find skill component for ({:d})!", -context->originator); return; } @@ -35,7 +35,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea if (m_useMouseposit && !branch.isSync) { NiPoint3 targetPosition = NiPoint3Constant::ZERO; if (!bitStream.Read(targetPosition)) { - LOG("Unable to read targetPosition from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read targetPosition from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; }; } @@ -46,7 +46,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea LWOOBJID projectileId{}; if (!bitStream.Read(projectileId)) { - LOG("Unable to read projectileId from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); + Log::Warn("Unable to read projectileId from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits()); return; }; diff --git a/dGame/dBehaviors/PropertyTeleportBehavior.cpp b/dGame/dBehaviors/PropertyTeleportBehavior.cpp index 7e9ecee0..64cc39d5 100644 --- a/dGame/dBehaviors/PropertyTeleportBehavior.cpp +++ b/dGame/dBehaviors/PropertyTeleportBehavior.cpp @@ -40,7 +40,7 @@ void PropertyTeleportBehavior::Handle(BehaviorContext* context, RakNet::BitStrea if (zoneClone != 0) ChatPackets::SendSystemMessage(sysAddr, u"Transfering to your property!"); else ChatPackets::SendSystemMessage(sysAddr, u"Transfering back to previous world!"); - LOG("Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Log::Info("Transferring {:s} to Zone {:d} (Instance {:d} | Clone {:d} | Mythran Shift: {:s}) with IP {:s} and Port {:d}", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP, serverPort); if (entity->GetCharacter()) { entity->GetCharacter()->SetZoneID(zoneID); entity->GetCharacter()->SetZoneInstance(zoneInstance); diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index e033d368..e9619753 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -45,7 +45,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStrea ); if (entity == nullptr) { - LOG("Failed to spawn entity (%i)!", this->m_lot); + Log::Warn("Failed to spawn entity ({:d})!", this->m_lot); return; } diff --git a/dGame/dComponents/ActivityComponent.cpp b/dGame/dComponents/ActivityComponent.cpp index ce82abe0..27a76ed7 100644 --- a/dGame/dComponents/ActivityComponent.cpp +++ b/dGame/dComponents/ActivityComponent.cpp @@ -524,7 +524,7 @@ void ActivityInstance::StartZone() { if (player == nullptr) return; - LOG("Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", player->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Log::Info("Transferring {:s} to Zone {:d} (Instance {:d} | Clone {:d} | Mythran Shift: {:s}) with IP {:s} and Port {:d}", player->GetCharacter()->GetName(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP, serverPort); if (player->GetCharacter()) { player->GetCharacter()->SetZoneID(zoneID); player->GetCharacter()->SetZoneInstance(zoneInstance); diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 8b76e423..2ff1404d 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -110,7 +110,7 @@ void BuffComponent::Update(float deltaTime) { const std::string& GetFxName(const std::string& buffname) { const auto& toReturn = BuffFx[buffname]; if (toReturn.empty()) { - LOG_DEBUG("No fx name for %s", buffname.c_str()); + Log::Debug("No fx name for {:s}", buffname); } return toReturn; } @@ -122,7 +122,7 @@ void BuffComponent::ApplyBuffFx(uint32_t buffId, const BuffParameter& buff) { if (buffName.empty()) return; fxToPlay += std::to_string(buffId); - LOG_DEBUG("Playing %s %i", fxToPlay.c_str(), buff.effectId); + Log::Debug("Playing {:s} {:d}", fxToPlay, buff.effectId); GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), buff.effectId, u"cast", fxToPlay, LWOOBJID_EMPTY, 1.07f, 1.0f, false); } @@ -133,7 +133,7 @@ void BuffComponent::RemoveBuffFx(uint32_t buffId, const BuffParameter& buff) { if (buffName.empty()) return; fxToPlay += std::to_string(buffId); - LOG_DEBUG("Stopping %s", fxToPlay.c_str()); + Log::Debug("Stopping {:s}", fxToPlay); GameMessages::SendStopFXEffect(m_Parent, false, fxToPlay); } @@ -460,7 +460,7 @@ const std::vector& BuffComponent::GetBuffParameters(int32_t buffI param.values.push_back(value); } catch (std::invalid_argument& exception) { - LOG("Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); + Log::Warn("Failed to parse value ({:s}): ({:s})!", token, exception.what()); } } } diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 161d7b91..6c0fcbb4 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -200,7 +200,7 @@ void InventoryComponent::AddItem( const auto slot = preferredSlot != -1 && inventory->IsSlotEmpty(preferredSlot) ? preferredSlot : inventory->FindEmptySlot(); if (slot == -1) { - LOG("Failed to find empty slot for inventory (%i)!", inventoryType); + Log::Warn("Failed to find empty slot for inventory ({:d})!", GeneralUtils::ToUnderlying(inventoryType)); return; } @@ -1379,7 +1379,7 @@ std::vector InventoryComponent::GenerateProxies(Item* parent) { try { lots.push_back(std::stoi(segment)); } catch (std::invalid_argument& exception) { - LOG("Failed to parse proxy (%s): (%s)!", segment.c_str(), exception.what()); + Log::Warn("Failed to parse proxy ({:s}): ({:s})!", segment, exception.what()); } } diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 151fcf2f..5feebc9d 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -364,7 +364,7 @@ const std::vector MissionComponent::LookForAchievements(eMissionTaskTy break; } } catch (std::invalid_argument& exception) { - LOG("Failed to parse target (%s): (%s)!", token.c_str(), exception.what()); + Log::Warn("Failed to parse target ({:s}): ({:s})!", token, exception.what()); } } diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 7f26ed72..6eed3b23 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -130,7 +130,7 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi randomMissionPool.push_back(value); } catch (std::invalid_argument& exception) { - LOG("Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); + Log::Warn("Failed to parse value ({:s}): ({:s})!", token, exception.what()); } } diff --git a/dGame/dComponents/MovingPlatformComponent.cpp b/dGame/dComponents/MovingPlatformComponent.cpp index 77acbb8d..37afa90c 100644 --- a/dGame/dComponents/MovingPlatformComponent.cpp +++ b/dGame/dComponents/MovingPlatformComponent.cpp @@ -63,7 +63,7 @@ MovingPlatformComponent::MovingPlatformComponent(Entity* parent, const std::stri m_NoAutoStart = false; if (m_Path == nullptr) { - LOG("Path not found: %s", pathName.c_str()); + Log::Warn("Path not found: {:s}", pathName); } } diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index a6bb00fb..600dae54 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -229,7 +229,7 @@ void PetComponent::OnUse(Entity* originator) { if (bricks.empty()) { ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to load the puzzle minigame for this pet."); - LOG("Couldn't find %s for minigame!", buildFile.c_str()); + Log::Warn("Couldn't find {:s} for minigame!", buildFile); return; } @@ -640,7 +640,7 @@ void PetComponent::RequestSetPetName(std::u16string name) { return; } - LOG("Got set pet name (%s)", GeneralUtils::UTF16ToWTF8(name).c_str()); + Log::Info("Got set pet name ({:s})", GeneralUtils::UTF16ToWTF8(name)); auto* inventoryComponent = tamer->GetComponent(); diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 276184b1..7961320b 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -182,7 +182,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : PhysicsCompon m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 390.496826f, 111.467964f, 600.821534f, true); m_Position.y -= (111.467964f * m_Scale) / 2; } else { - // LOG_DEBUG("This one is supposed to have %s", info->physicsAsset.c_str()); + // Log::Debug("This one is supposed to have {:s}", info->physicsAsset); //add fallback cube: m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 2.0f, 2.0f, 2.0f); diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 2acc6a5d..6b85abe1 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -114,7 +114,7 @@ std::vector PropertyManagementComponent::GetPaths() const { points.push_back(value); } catch (std::invalid_argument& exception) { - LOG("Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); + Log::Warn("Failed to parse value ({:s}): ({:s})!", token, exception.what()); } } diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index 2067ef2a..a6950abc 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -33,7 +33,7 @@ RenderComponent::RenderComponent(Entity* const parentEntity, const int32_t compo const auto groupIdInt = GeneralUtils::TryParse(groupId); if (!groupIdInt) { - LOG("bad animation group Id %s", groupId.c_str()); + Log::Warn("bad animation group Id {:s}", groupId); continue; } @@ -176,6 +176,6 @@ float RenderComponent::DoAnimation(Entity* self, const std::string& animation, b } } if (sendAnimation) GameMessages::SendPlayAnimation(self, GeneralUtils::ASCIIToUTF16(animation), priority, scale); - if (returnlength == 0.0f) LOG("WARNING: Unable to find animation %s for lot %i in any group.", animation.c_str(), self->GetLOT()); + if (returnlength == 0.0f) LOG("WARNING: Unable to find animation {:s} for lot {:d} in any group.", animation, self->GetLOT()); return returnlength; } diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index e43ebc5d..2b73e4ca 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -154,7 +154,7 @@ void TriggerComponent::HandleTriggerCommand(LUTriggers::Command* command, Entity case eTriggerCommandType::DEACTIVATE_MIXER_PROGRAM: break; // DEPRECATED BLOCK END default: - LOG_DEBUG("Event %i was not handled!", command->id); + Log::Debug("Event {:d} was not handled!", GeneralUtils::ToUnderlying(command->id)); break; } } @@ -194,7 +194,7 @@ void TriggerComponent::HandleDestroyObject(Entity* targetEntity, std::string arg void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string args){ auto* triggerComponent = targetEntity->GetComponent(); if (!triggerComponent) { - LOG_DEBUG("Trigger component not found!"); + Log::Debug("Trigger component not found!"); return; } triggerComponent->SetTriggerEnabled(args == "1"); @@ -203,7 +203,7 @@ void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string arg void TriggerComponent::HandleResetRebuild(Entity* targetEntity, std::string args){ auto* quickBuildComponent = targetEntity->GetComponent(); if (!quickBuildComponent) { - LOG_DEBUG("Rebuild component not found!"); + Log::Debug("Rebuild component not found!"); return; } quickBuildComponent->ResetQuickBuild(args == "1"); @@ -233,7 +233,7 @@ void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vectorGetComponent(); if (!phantomPhysicsComponent) { - LOG_DEBUG("Phantom Physics component not found!"); + Log::Debug("Phantom Physics component not found!"); return; } phantomPhysicsComponent->SetPhysicsEffectActive(true); @@ -249,7 +249,7 @@ void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vectorGetComponent(); if (!phantomPhysicsComponent) { - LOG_DEBUG("Phantom Physics component not found!"); + Log::Debug("Phantom Physics component not found!"); return; } const float forceMultiplier = GeneralUtils::TryParse(args).value_or(1.0f); @@ -272,7 +272,7 @@ void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) void TriggerComponent::HandleSetTimer(Entity* targetEntity, std::vector argArray){ if (argArray.size() != 2) { - LOG_DEBUG("Not enough variables!"); + Log::Debug("Not enough variables!"); return; } const float time = GeneralUtils::TryParse(argArray.at(1)).value_or(0.0f); @@ -312,7 +312,7 @@ void TriggerComponent::HandlePlayCinematic(Entity* targetEntity, std::vectorGetCharacter(); if (!character) { - LOG_DEBUG("Character was not found!"); + Log::Debug("Character was not found!"); return; } bool buildMode = !(character->GetBuildMode()); @@ -328,7 +328,7 @@ void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vectorGetComponent(); if (!missionComponent){ - LOG_DEBUG("Mission component not found!"); + Log::Debug("Mission component not found!"); return; } missionComponent->Progress(eMissionTaskType::EXPLORE, 0, 0, argArray.at(4)); @@ -351,7 +351,7 @@ void TriggerComponent::HandlePlayEffect(Entity* targetEntity, std::vectorGetComponent(); if (!skillComponent) { - LOG_DEBUG("Skill component not found!"); + Log::Debug("Skill component not found!"); return; } const uint32_t skillId = GeneralUtils::TryParse(args).value_or(0); @@ -361,7 +361,7 @@ void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::vector argArray) { auto* phantomPhysicsComponent = targetEntity->GetComponent(); if (!phantomPhysicsComponent) { - LOG_DEBUG("Phantom Physics component not found!"); + Log::Debug("Phantom Physics component not found!"); return; } phantomPhysicsComponent->SetPhysicsEffectActive(true); @@ -395,7 +395,7 @@ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::v void TriggerComponent::HandleSetPhysicsVolumeStatus(Entity* targetEntity, std::string args) { auto* phantomPhysicsComponent = targetEntity->GetComponent(); if (!phantomPhysicsComponent) { - LOG_DEBUG("Phantom Physics component not found!"); + Log::Debug("Phantom Physics component not found!"); return; } phantomPhysicsComponent->SetPhysicsEffectActive(args == "On"); @@ -432,6 +432,6 @@ void TriggerComponent::HandleActivatePhysics(Entity* targetEntity, std::string a } else if (args == "false"){ // TODO remove Phsyics entity if there is one } else { - LOG_DEBUG("Invalid argument for ActivatePhysics Trigger: %s", args.c_str()); + Log::Debug("Invalid argument for ActivatePhysics Trigger: {:s}", args); } } diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index d2432e36..da1ee8fe 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -49,11 +49,11 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream& inStream, const System User* usr = UserManager::Instance()->GetUser(sysAddr); if (!entity) { - LOG("Failed to find associated entity (%llu), aborting GM: %4i, %s!", objectID, messageID, StringifiedEnum::ToString(messageID).data()); + Log::Warn("Failed to find associated entity ({:d}), aborting GM: {:4d}, {:s}!", objectID, GeneralUtils::ToUnderlying(messageID), StringifiedEnum::ToString(messageID)); return; } - if (messageID != eGameMessageType::READY_FOR_UPDATES) LOG_DEBUG("Received GM with ID and name: %4i, %s", messageID, StringifiedEnum::ToString(messageID).data()); + if (messageID != eGameMessageType::READY_FOR_UPDATES) Log::Debug("Received GM with ID and name: {:4d}, {:s}", GeneralUtils::ToUnderlying(messageID), StringifiedEnum::ToString(messageID)); switch (messageID) { @@ -167,7 +167,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream& inStream, const System character->OnZoneLoad(); } - LOG("Player %s (%llu) loaded.", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); + Log::Info("Player {:s} ({:d}) loaded.", entity->GetCharacter()->GetName(), entity->GetObjectID()); // After we've done our thing, tell the client they're ready GameMessages::SendPlayerReady(entity, sysAddr); @@ -686,7 +686,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream& inStream, const System GameMessages::SendVendorStatusUpdate(entity, sysAddr, true); break; default: - LOG_DEBUG("Received Unknown GM with ID: %4i, %s", messageID, StringifiedEnum::ToString(messageID).data()); + Log::Info("Received Unknown GM with ID: {:4d}, {:s}", GeneralUtils::ToUnderlying(messageID), StringifiedEnum::ToString(messageID)); break; } } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index c144675b..3511991a 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -1713,7 +1713,7 @@ void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream& inStream, auto* assosiate = Game::entityManager->GetEntity(objectID); - LOG("%s [%i, %i] from %i to %i", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); + Log::Info("{:s} [{:d}, {:d}] from {:d} to {:d}", GeneralUtils::UTF16ToWTF8(stringValue), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SHOOTING_GALLERY); for (Entity* scriptEntity : scriptedActs) { @@ -3810,7 +3810,7 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream& inStream, Entity* userData.push_back(character); } - LOG("Button: %d; LOT: %u identifier: %s; userData: %s", iButton, entity->GetLOT(), GeneralUtils::UTF16ToWTF8(identifier).c_str(), GeneralUtils::UTF16ToWTF8(userData).c_str()); + Log::Info("Button: {:d}; LOT: {:d} identifier: {:s}; userData: {:s}", iButton, entity->GetLOT(), GeneralUtils::UTF16ToWTF8(identifier), GeneralUtils::UTF16ToWTF8(userData)); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -3866,7 +3866,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream& inStream, Entity* e identifier.push_back(character); } - LOG("Button: %d; LOT: %u buttonIdentifier: %s; userData: %s", iButton, entity->GetLOT(), GeneralUtils::UTF16ToWTF8(buttonIdentifier).c_str(), GeneralUtils::UTF16ToWTF8(identifier).c_str()); + Log::Info("Button: {:d}; LOT: {:d} buttonIdentifier: {:s}; userData: {:s}", iButton, entity->GetLOT(), GeneralUtils::UTF16ToWTF8(buttonIdentifier), GeneralUtils::UTF16ToWTF8(identifier)); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -4046,10 +4046,10 @@ void GameMessages::HandleAcknowledgePossession(RakNet::BitStream& inStream, Enti void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { auto* moduleAssemblyComponent = entity->GetComponent(); - LOG("Got Query from %i", entity->GetLOT()); + Log::Info("Got Query from {:d}", entity->GetLOT()); if (moduleAssemblyComponent != nullptr) { - LOG("Returning assembly %s", GeneralUtils::UTF16ToWTF8(moduleAssemblyComponent->GetAssemblyPartsLOTs()).c_str()); + Log::Info("Returning assembly {:s}", GeneralUtils::UTF16ToWTF8(moduleAssemblyComponent->GetAssemblyPartsLOTs())); SendModuleAssemblyDBDataForClient(entity->GetObjectID(), moduleAssemblyComponent->GetSubKey(), moduleAssemblyComponent->GetAssemblyPartsLOTs(), UNASSIGNED_SYSTEM_ADDRESS); } @@ -4872,7 +4872,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream& inStream, Entity mapId = Game::zoneManager->GetZoneID().GetMapID(); // Fallback to sending the player back to the same zone. } - LOG("Player %llu has requested zone transfer to (%i, %i).", sender->GetObjectID(), static_cast(mapId), static_cast(cloneId)); + Log::Info("Player {:d} has requested zone transfer to ({:d}, {:d}).", sender->GetObjectID(), static_cast(mapId), static_cast(cloneId)); auto* character = player->GetCharacter(); @@ -4881,7 +4881,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream& inStream, Entity } ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, mapId, cloneId, false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - LOG("Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Log::Info("Transferring {:s} to Zone {:d} (Instance {:d} | Clone {:d} | Mythran Shift: {:s}) with IP {:s} and Port {:d}", character->GetName(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP, serverPort); if (character) { character->SetZoneID(zoneID); diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index d3f15315..1704a24b 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -100,7 +100,7 @@ Item::Item( if (isModMoveAndEquip) { Equip(); - LOG("Move and equipped (%i) from (%i)", this->lot, this->inventory->GetType()); + Log::Info("Move and equipped ({:d}) from ({:d})", this->lot, GeneralUtils::ToUnderlying(this->inventory->GetType())); Game::entityManager->SerializeEntity(inventory->GetComponent()->GetParent()); } @@ -355,7 +355,7 @@ void Item::UseNonEquip(Item* item) { } } } - LOG_DEBUG("Player %llu %s used item %i", playerEntity->GetObjectID(), success ? "successfully" : "unsuccessfully", thisLot); + Log::Debug("Player {:d} {:s} used item {:d}", playerEntity->GetObjectID(), success ? "successfully" : "unsuccessfully", thisLot); GameMessages::SendUseItemResult(playerInventoryComponent->GetParent(), thisLot, success); } } @@ -426,7 +426,7 @@ void Item::DisassembleModel(uint32_t numToDismantle) { auto file = Game::assetManager->GetFile(lxfmlPath.c_str()); if (!file) { - LOG("Failed to load %s to disassemble model into bricks, check that this file exists", lxfmlPath.c_str()); + Log::Warn("Failed to load {:s} to disassemble model into bricks, check that this file exists", lxfmlPath); return; } @@ -472,7 +472,7 @@ void Item::DisassembleModel(uint32_t numToDismantle) { if (designID) { const auto designId = GeneralUtils::TryParse(designID); if (!designId) { - LOG("Failed to parse designID %s", designID); + Log::Warn("Failed to parse designID {:s}", designID); continue; } parts[designId.value()]++; diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp index 35b9cf0d..8b53cfef 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp @@ -10,5 +10,5 @@ AddActionMessage::AddActionMessage(const AMFArrayValue& arguments) m_Action = Action{ *actionValue }; - LOG_DEBUG("actionIndex %i stripId %i stateId %i type %s valueParameterName %s valueParameterString %s valueParameterDouble %f m_BehaviorId %i", m_ActionIndex, m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_Action.GetType().c_str(), m_Action.GetValueParameterName().c_str(), m_Action.GetValueParameterString().c_str(), m_Action.GetValueParameterDouble(), m_BehaviorId); + Log::Debug("actionIndex {:d} stripId {:d} stateId {:d} type {:s} valueParameterName {:s} valueParameterString {:s} valueParameterDouble {:f} m_BehaviorId {:d}", m_ActionIndex, m_ActionContext.GetStripId(), GeneralUtils::ToUnderlying(m_ActionContext.GetStateId()), m_Action.GetType(), m_Action.GetValueParameterName(), m_Action.GetValueParameterString(), m_Action.GetValueParameterDouble(), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp index c7207b33..c8baa21e 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp @@ -19,7 +19,7 @@ AddStripMessage::AddStripMessage(const AMFArrayValue& arguments) m_ActionsToAdd.emplace_back(*actionValue); - LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i t %s valueParameterName %s valueParameterString %s valueParameterDouble %f", m_Position.GetX(), m_Position.GetY(), m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_BehaviorId, m_ActionsToAdd.back().GetType().c_str(), m_ActionsToAdd.back().GetValueParameterName().c_str(), m_ActionsToAdd.back().GetValueParameterString().c_str(), m_ActionsToAdd.back().GetValueParameterDouble()); + Log::Debug("xPosition {:f} yPosition {:f} stripId {:d} stateId {:d} behaviorId {:d} t {:s} valueParameterName {:s} valueParameterString {:s} valueParameterDouble {:f}", m_Position.GetX(), m_Position.GetY(), m_ActionContext.GetStripId(), GeneralUtils::ToUnderlying(m_ActionContext.GetStateId()), m_BehaviorId, m_ActionsToAdd.back().GetType(), m_ActionsToAdd.back().GetValueParameterName(), m_ActionsToAdd.back().GetValueParameterString(), m_ActionsToAdd.back().GetValueParameterDouble()); } - LOG_DEBUG("number of actions %i", m_ActionsToAdd.size()); + Log::Debug("number of actions {:d}", m_ActionsToAdd.size()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp index 1efc5aee..e0de6b9b 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp @@ -6,6 +6,6 @@ MergeStripsMessage::MergeStripsMessage(const AMFArrayValue& arguments) , m_SourceActionContext{ arguments, "srcStateID", "srcStripID" } , m_DestinationActionContext{ arguments, "dstStateID", "dstStripID" } { - LOG_DEBUG("srcstripId %i dststripId %i srcstateId %i dststateId %i dstactionIndex %i behaviorId %i", m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), m_SourceActionContext.GetStateId(), m_DestinationActionContext.GetStateId(), m_DstActionIndex, m_BehaviorId); + Log::Debug("srcstripId {:d} dststripId {:d} srcstateId {:d} dststateId {:d} dstactionIndex {:d} behaviorId {:d}", m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), GeneralUtils::ToUnderlying(m_SourceActionContext.GetStateId()), GeneralUtils::ToUnderlying(m_DestinationActionContext.GetStateId()), m_DstActionIndex, m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp index 9791bc2a..18271510 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp @@ -7,5 +7,5 @@ MigrateActionsMessage::MigrateActionsMessage(const AMFArrayValue& arguments) , m_SourceActionContext{ arguments, "srcStateID", "srcStripID" } , m_DestinationActionContext{ arguments, "dstStateID", "dstStripID" } { - LOG_DEBUG("srcactionIndex %i dstactionIndex %i srcstripId %i dststripId %i srcstateId %i dststateId %i behaviorId %i", m_SrcActionIndex, m_DstActionIndex, m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), m_SourceActionContext.GetStateId(), m_DestinationActionContext.GetStateId(), m_BehaviorId); + Log::Debug("srcactionIndex {:d} dstactionIndex {:d} srcstripId {:d} dststripId {:d} srcstateId {:d} dststateId {:d} behaviorId {:d}", m_SrcActionIndex, m_DstActionIndex, m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), GeneralUtils::ToUnderlying(m_SourceActionContext.GetStateId()), GeneralUtils::ToUnderlying(m_DestinationActionContext.GetStateId()), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp index 99fe6f6a..5dcb6f3f 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp @@ -6,5 +6,5 @@ RearrangeStripMessage::RearrangeStripMessage(const AMFArrayValue& arguments) , m_DstActionIndex{ GetActionIndexFromArgument(arguments, "dstActionIndex") } , m_ActionContext{ arguments } { - LOG_DEBUG("srcactionIndex %i dstactionIndex %i stripId %i behaviorId %i stateId %i", m_SrcActionIndex, m_DstActionIndex, m_ActionContext.GetStripId(), m_BehaviorId, m_ActionContext.GetStateId()); + Log::Debug("srcactionIndex {:d} dstactionIndex {:d} stripId {:d} behaviorId {:d} stateId {:d}", m_SrcActionIndex, m_DstActionIndex, m_ActionContext.GetStripId(), m_BehaviorId, GeneralUtils::ToUnderlying(m_ActionContext.GetStateId())); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp index 15407012..9ab4192c 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp @@ -5,5 +5,5 @@ RemoveActionsMessage::RemoveActionsMessage(const AMFArrayValue& arguments) , m_ActionIndex{ GetActionIndexFromArgument(arguments) } , m_ActionContext{ arguments } { - LOG_DEBUG("behaviorId %i actionIndex %i stripId %i stateId %i", m_BehaviorId, m_ActionIndex, m_ActionContext.GetStripId(), m_ActionContext.GetStateId()); + Log::Debug("behaviorId {:d} actionIndex {:d} stripId {:d} stateId {:d}", m_BehaviorId, m_ActionIndex, m_ActionContext.GetStripId(), GeneralUtils::ToUnderlying(m_ActionContext.GetStateId())); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp index f0275377..63e4ca4b 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp @@ -4,5 +4,5 @@ RemoveStripMessage::RemoveStripMessage(const AMFArrayValue& arguments) : BehaviorMessageBase{ arguments } , m_ActionContext{ arguments } { - LOG_DEBUG("stripId %i stateId %i behaviorId %i", m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_BehaviorId); + Log::Debug("stripId {:d} stateId {:d} behaviorId {:d}", m_ActionContext.GetStripId(), GeneralUtils::ToUnderlying(m_ActionContext.GetStateId()), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp index 6003c982..55e24d02 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp @@ -7,5 +7,5 @@ SplitStripMessage::SplitStripMessage(const AMFArrayValue& arguments) , m_DestinationActionContext{ arguments, "dstStateID", "dstStripID" } , m_DestinationPosition{ arguments, "dstStripUI" } { - LOG_DEBUG("behaviorId %i xPosition %f yPosition %f sourceStrip %i destinationStrip %i sourceState %i destinationState %i srcActindex %i", m_BehaviorId, m_DestinationPosition.GetX(), m_DestinationPosition.GetY(), m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), m_SourceActionContext.GetStateId(), m_DestinationActionContext.GetStateId(), m_SrcActionIndex); + Log::Debug("behaviorId {:d} xPosition {:f} yPosition {:f} sourceStrip {:d} destinationStrip {:d} sourceState {:d} destinationState {:d} srcActindex {:d}", m_BehaviorId, m_DestinationPosition.GetX(), m_DestinationPosition.GetY(), m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), GeneralUtils::ToUnderlying(m_SourceActionContext.GetStateId()), GeneralUtils::ToUnderlying(m_DestinationActionContext.GetStateId()), m_SrcActionIndex); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp index fabf2726..067ac4e7 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp @@ -12,5 +12,5 @@ UpdateActionMessage::UpdateActionMessage(const AMFArrayValue& arguments) m_Action = Action{ *actionValue }; - LOG_DEBUG("type %s valueParameterName %s valueParameterString %s valueParameterDouble %f behaviorId %i actionIndex %i stripId %i stateId %i", m_Action.GetType().c_str(), m_Action.GetValueParameterName().c_str(), m_Action.GetValueParameterString().c_str(), m_Action.GetValueParameterDouble(), m_BehaviorId, m_ActionIndex, m_ActionContext.GetStripId(), m_ActionContext.GetStateId()); + Log::Debug("type {:s} valueParameterName {:s} valueParameterString {:s} valueParameterDouble {:f} behaviorId {:d} actionIndex {:d} stripId {:d} stateId {:d}", m_Action.GetType(), m_Action.GetValueParameterName(), m_Action.GetValueParameterString(), m_Action.GetValueParameterDouble(), m_BehaviorId, m_ActionIndex, m_ActionContext.GetStripId(), GeneralUtils::ToUnderlying(m_ActionContext.GetStateId())); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp index badb8c7a..0b916db9 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp @@ -5,5 +5,5 @@ UpdateStripUiMessage::UpdateStripUiMessage(const AMFArrayValue& arguments) , m_Position{ arguments } , m_ActionContext{ arguments } { - LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i", m_Position.GetX(), m_Position.GetY(), m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_BehaviorId); + Log::Debug("xPosition {:f} yPosition {:f} stripId {:d} stateId {:d} behaviorId {:d}", m_Position.GetX(), m_Position.GetY(), m_ActionContext.GetStripId(), GeneralUtils::ToUnderlying(m_ActionContext.GetStateId()), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp index 2e074409..c9a6e9d0 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -190,14 +190,14 @@ ControlBehaviors::ControlBehaviors() { auto ret = m_Doc.Parse(buffer.c_str()); if (ret == tinyxml2::XML_SUCCESS) { - LOG_DEBUG("Successfully parsed the blocksdef file!"); + Log::Debug("Successfully parsed the blocksdef file!"); } else { - LOG("Failed to parse BlocksDef xmlData due to error %i!", ret); + Log::Warn("Failed to parse BlocksDef xmlData due to error {:d}!", GeneralUtils::ToUnderlying(ret)); return; } auto* blockLibrary = m_Doc.FirstChildElement(); if (!blockLibrary) { - LOG("No Block Library child element found."); + Log::Warn("No Block Library child element found."); return; } diff --git a/dGame/dPropertyBehaviors/PropertyBehavior.cpp b/dGame/dPropertyBehaviors/PropertyBehavior.cpp index 423751c4..5e00ed33 100644 --- a/dGame/dPropertyBehaviors/PropertyBehavior.cpp +++ b/dGame/dPropertyBehaviors/PropertyBehavior.cpp @@ -96,12 +96,12 @@ void PropertyBehavior::VerifyLastEditedState() { for (const auto& [stateId, state] : m_States) { if (state.IsEmpty()) continue; - LOG_DEBUG("Updating last edited state to %i because %i is empty.", stateId, m_LastEditedState); + Log::Debug("Updating last edited state to {:d} because {:d} is empty.", GeneralUtils::ToUnderlying(stateId), GeneralUtils::ToUnderlying(m_LastEditedState)); m_LastEditedState = stateId; return; } - LOG_DEBUG("No states found, sending default state"); + Log::Debug("No states found, sending default state"); m_LastEditedState = BehaviorState::HOME_STATE; } @@ -112,7 +112,7 @@ void PropertyBehavior::SendBehaviorBlocksToClient(AMFArrayValue& args) const { for (const auto& [stateId, state] : m_States) { if (state.IsEmpty()) continue; - LOG_DEBUG("Serializing state %i", stateId); + Log::Debug("Serializing state {:d}", GeneralUtils::ToUnderlying(stateId)); auto* const stateArgs = stateArray->PushArray(); stateArgs->Insert("id", static_cast(stateId)); state.SendBehaviorBlocksToClient(*stateArgs); diff --git a/dGame/dUtilities/CheatDetection.cpp b/dGame/dUtilities/CheatDetection.cpp index a87157a1..f74e7bba 100644 --- a/dGame/dUtilities/CheatDetection.cpp +++ b/dGame/dUtilities/CheatDetection.cpp @@ -25,7 +25,7 @@ Entity* GetPossessedEntity(const LWOOBJID& objId) { void ReportCheat(User* user, const SystemAddress& sysAddr, const char* messageIfNotSender, va_list args) { if (!user) { - LOG("WARNING: User is null, using defaults."); + Log::Warn("User is null, using defaults."); } IPlayerCheatDetections::Info info; @@ -42,7 +42,7 @@ void ReportCheat(User* user, const SystemAddress& sysAddr, const char* messageIf Database::Get()->InsertCheatDetection(info); - LOG("Anti-cheat message: %s", extraMsg); + Log::Info("Anti-cheat message: {:s}", extraMsg); } void LogAndSaveFailedAntiCheatCheck(const LWOOBJID& id, const SystemAddress& sysAddr, const CheckType checkType, const char* messageIfNotSender, va_list args) { @@ -54,20 +54,20 @@ void LogAndSaveFailedAntiCheatCheck(const LWOOBJID& id, const SystemAddress& sys // If player exists and entity exists in world, use both for logging info. if (entity && player) { - LOG("Player (%s) (%llu) at system address (%s) with sending player (%s) (%llu) does not match their own.", - player->GetCharacter()->GetName().c_str(), player->GetObjectID(), + Log::Warn("Player ({:s}) ({:d}) at system address ({:s}) with sending player ({:s}) ({:d}) does not match their own.", + player->GetCharacter()->GetName(), player->GetObjectID(), sysAddr.ToString(), - entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); + entity->GetCharacter()->GetName(), entity->GetObjectID()); if (player->GetCharacter()) toReport = player->GetCharacter()->GetParentUser(); // In the case that the target entity id did not exist, just log the player info. } else if (player) { - LOG("Player (%s) (%llu) at system address (%s) with sending player (%llu) does not match their own.", - player->GetCharacter()->GetName().c_str(), player->GetObjectID(), + Log::Warn("Player ({:s}) ({:d}) at system address ({:s}) with sending player ({:d}) does not match their own.", + player->GetCharacter()->GetName(), player->GetObjectID(), sysAddr.ToString(), id); if (player->GetCharacter()) toReport = player->GetCharacter()->GetParentUser(); // In the rare case that the player does not exist, just log the system address and who the target id was. } else { - LOG("Player at system address (%s) with sending player (%llu) does not match their own.", + Log::Warn("Player at system address ({:s}) with sending player ({:d}) does not match their own.", sysAddr.ToString(), id); } break; @@ -76,11 +76,11 @@ void LogAndSaveFailedAntiCheatCheck(const LWOOBJID& id, const SystemAddress& sys auto* user = UserManager::Instance()->GetUser(sysAddr); if (user) { - LOG("User at system address (%s) (%s) (%llu) sent a packet as (%i) which is not an id they own.", - sysAddr.ToString(), user->GetLastUsedChar()->GetName().c_str(), user->GetLastUsedChar()->GetObjectID(), static_cast(id)); + Log::Warn("User at system address ({:s}) ({:s}) ({:d}) sent a packet as ({:d}) which is not an id they own.", + sysAddr.ToString(), user->GetLastUsedChar()->GetName(), user->GetLastUsedChar()->GetObjectID(), id); // Can't know sending player. Just log system address for IP banning. } else { - LOG("No user found for system address (%s).", sysAddr.ToString()); + Log::Warn("No user found for system address ({:s}).", sysAddr.ToString()); } toReport = user; break; @@ -113,7 +113,7 @@ bool CheatDetection::VerifyLwoobjidIsSender(const LWOOBJID& id, const SystemAddr // Check here if the system address has a character with id matching the lwoobjid after unsetting the flag bits. auto* sendingUser = UserManager::Instance()->GetUser(sysAddr); if (!sendingUser) { - LOG("No user found for system address (%s).", sysAddr.ToString()); + Log::Warn("No user found for system address ({:s}).", sysAddr.ToString()); return false; } invalidPacket = true; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index d0620121..74cc657c 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -145,7 +145,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit WorldPackets::SendGMLevelChange(sysAddr, success, user->GetMaxGMLevel(), entity->GetGMLevel(), level); GameMessages::SendChatModeUpdate(entity->GetObjectID(), level); entity->SetGMLevel(level); - LOG("User %s (%i) has changed their GM level to %i for charID %llu", user->GetUsername().c_str(), user->GetAccountID(), level, entity->GetObjectID()); + Log::Info("User {:s} ({:d}) has changed their GM level to {:d} for charID {:d}", user->GetUsername(), user->GetAccountID(), GeneralUtils::ToUnderlying(level), entity->GetObjectID()); } } diff --git a/dMasterServer/CMakeLists.txt b/dMasterServer/CMakeLists.txt index 260e4f16..444268d2 100644 --- a/dMasterServer/CMakeLists.txt +++ b/dMasterServer/CMakeLists.txt @@ -12,8 +12,8 @@ target_include_directories(dMasterServer PUBLIC "." ${PROJECT_SOURCE_DIR}/dServer/ # BinaryPathFinder.h ) -target_link_libraries(dMasterServer ${COMMON_LIBRARIES}) -target_link_libraries(MasterServer ${COMMON_LIBRARIES} bcrypt dMasterServer dServer) +target_link_libraries(dMasterServer PRIVATE ${COMMON_LIBRARIES}) +target_link_libraries(MasterServer PRIVATE ${COMMON_LIBRARIES} bcrypt dMasterServer dServer) if(WIN32) add_dependencies(MasterServer WorldServer AuthServer ChatServer) diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 3ec42634..c990fc81 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -30,13 +30,13 @@ InstanceManager::~InstanceManager() { } Instance* InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneID) { - LOG("Searching for an instance for mapID %i/%i", mapID, cloneID); + Log::Info("Searching for an instance for mapID {:d}/{:d}", mapID, cloneID); Instance* instance = FindInstance(mapID, isFriendTransfer, cloneID); if (instance) return instance; // If we are shutting down, return a nullptr so a new instance is not created. if (m_IsShuttingDown) { - LOG("Tried to create a new instance map/instance/clone %i/%i/%i, but Master is shutting down.", + Log::Warn("Tried to create a new instance map/instance/clone {:d}/{:d}/{:d}, but Master is shutting down.", mapID, m_LastInstanceID + 1, cloneID); @@ -64,9 +64,11 @@ Instance* InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LW m_Instances.push_back(instance); if (instance) { - LOG("Created new instance: %i/%i/%i with min/max %i/%i", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); + Log::Info("Created new instance: {:d}/{:d}/{:d} with min/max {:d}/{:d}", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); return instance; - } else LOG("Failed to create a new instance!"); + } else { + Log::Warn("Failed to create a new instance!"); + } return nullptr; } @@ -154,7 +156,7 @@ void InstanceManager::ReadyInstance(Instance* instance) { for (const auto& request : pending) { const auto& zoneId = instance->GetZoneID(); - LOG("Responding to pending request %llu -> %i (%i)", request, zoneId.GetMapID(), zoneId.GetCloneID()); + Log::Info("Responding to pending request {:d} -> {:d} ({:d})", request.id, zoneId.GetMapID(), zoneId.GetCloneID()); MasterPackets::SendZoneTransferResponse( Game::server, diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 4104f5ea..56bf9f9f 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -82,28 +82,28 @@ int main(int argc, char** argv) { Server::SetupLogger("MasterServer"); if (!Game::logger) return EXIT_FAILURE; - if (!dConfig::Exists("authconfig.ini")) LOG("Could not find authconfig.ini, using default settings"); - if (!dConfig::Exists("chatconfig.ini")) LOG("Could not find chatconfig.ini, using default settings"); - if (!dConfig::Exists("masterconfig.ini")) LOG("Could not find masterconfig.ini, using default settings"); - if (!dConfig::Exists("sharedconfig.ini")) LOG("Could not find sharedconfig.ini, using default settings"); - if (!dConfig::Exists("worldconfig.ini")) LOG("Could not find worldconfig.ini, using default settings"); + if (!dConfig::Exists("authconfig.ini")) Log::Info("Could not find authconfig.ini, using default settings"); + if (!dConfig::Exists("chatconfig.ini")) Log::Info("Could not find chatconfig.ini, using default settings"); + if (!dConfig::Exists("masterconfig.ini")) Log::Info("Could not find masterconfig.ini, using default settings"); + if (!dConfig::Exists("sharedconfig.ini")) Log::Info("Could not find sharedconfig.ini, using default settings"); + if (!dConfig::Exists("worldconfig.ini")) Log::Info("Could not find worldconfig.ini, using default settings"); const auto clientNetVersionString = Game::config->GetValue("client_net_version"); const uint32_t clientNetVersion = GeneralUtils::TryParse(clientNetVersionString).value_or(171022); - LOG("Using net version %i", clientNetVersion); + Log::Info("Using net version {:d}", clientNetVersion); - LOG("Starting Master server..."); - LOG("Version: %s", PROJECT_VERSION); - LOG("Compiled on: %s", __TIMESTAMP__); + Log::Info("Starting Master server..."); + Log::Info("Version: {:s}", PROJECT_VERSION); + Log::Info("Compiled on: {:s}", __TIMESTAMP__); //Connect to the MySQL Database try { Database::Connect(); } catch (sql::SQLException& ex) { - LOG("Got an error while connecting to the database: %s", ex.what()); - LOG("Migrations not run"); + Log::Warn("Got an error while connecting to the database: {:s}", ex.what()); + Log::Warn("Migrations not run"); return EXIT_FAILURE; } @@ -117,8 +117,8 @@ int main(int argc, char** argv) { Game::assetManager = new AssetManager(clientPath); } catch (std::runtime_error& ex) { - LOG("Got an error while setting up assets: %s", ex.what()); - LOG("Is the provided client_location in Windows Onedrive? If so, remove it from Onedrive."); + Log::Warn("Got an error while setting up assets: {:s}", ex.what()); + Log::Warn("Is the provided client_location in Windows Onedrive? If so, remove it from Onedrive."); return EXIT_FAILURE; } @@ -130,9 +130,9 @@ int main(int argc, char** argv) { const bool resServerPathExists = std::filesystem::is_directory(resServerPath); if (!resServerPathExists) { - LOG("%s does not exist, creating it.", (resServerPath).c_str()); + Log::Info("{:s} does not exist, creating it.", (resServerPath).string()); if (!std::filesystem::create_directories(resServerPath)) { - LOG("Failed to create %s", (resServerPath).string().c_str()); + Log::Warn("Failed to create {:s}", (resServerPath).string()); return EXIT_FAILURE; } } @@ -140,24 +140,24 @@ int main(int argc, char** argv) { if (!cdServerExists) { if (oldCDServerExists) { // If the file doesn't exist in the new CDServer location, copy it there. We copy because we may not have write permissions from the previous directory. - LOG("CDServer.sqlite is not located at resServer, but is located at res path. Copying file..."); + Log::Info("CDServer.sqlite is not located at resServer, but is located at res path. Copying file..."); std::filesystem::copy_file(Game::assetManager->GetResPath() / "CDServer.sqlite", resServerPath / "CDServer.sqlite"); } else { - LOG("%s could not be found in resServer or res. Looking for %s to convert to sqlite.", - (resServerPath / "CDServer.sqlite").string().c_str(), - (Game::assetManager->GetResPath() / "cdclient.fdb").string().c_str()); + Log::Info("{:s} could not be found in resServer or res. Looking for {:s} to convert to sqlite.", + (resServerPath / "CDServer.sqlite").string(), + (Game::assetManager->GetResPath() / "cdclient.fdb").string()); auto cdclientStream = Game::assetManager->GetFile("cdclient.fdb"); if (!cdclientStream) { - LOG("Failed to load %s", (Game::assetManager->GetResPath() / "cdclient.fdb").string().c_str()); + Log::Warn("Failed to load {:s}", (Game::assetManager->GetResPath() / "cdclient.fdb").string()); throw std::runtime_error("Aborting initialization due to missing cdclient.fdb."); } - LOG("Found %s. Converting to SQLite", (Game::assetManager->GetResPath() / "cdclient.fdb").string().c_str()); + Log::Info("Found {:s}. Converting to SQLite", (Game::assetManager->GetResPath() / "cdclient.fdb").string()); Game::logger->Flush(); if (FdbToSqlite::Convert(resServerPath.string()).ConvertDatabase(cdclientStream) == false) { - LOG("Failed to convert fdb to sqlite."); + Log::Warn("Failed to convert fdb to sqlite."); return EXIT_FAILURE; } } @@ -167,9 +167,9 @@ int main(int argc, char** argv) { try { CDClientDatabase::Connect((BinaryPathFinder::GetBinaryDir() / "resServer" / "CDServer.sqlite").string()); } catch (CppSQLite3Exception& e) { - LOG("Unable to connect to CDServer SQLite Database"); - LOG("Error: %s", e.errorMessage()); - LOG("Error Code: %i", e.errorCode()); + Log::Warn("Unable to connect to CDServer SQLite Database"); + Log::Warn("Error: {:s}", e.errorMessage()); + Log::Warn("Error Code: {:d}", e.errorCode()); return EXIT_FAILURE; } @@ -188,7 +188,7 @@ int main(int argc, char** argv) { auto accountId = Database::Get()->GetAccountInfo(username); if (accountId) { - LOG("Account with name \"%s\" already exists", username.c_str()); + Log::Info("Account with name \"{:s}\" already exists", username); std::cout << "Do you want to change the password of that account? [y/n]?"; std::string prompt = ""; std::cin >> prompt; @@ -215,9 +215,9 @@ int main(int argc, char** argv) { Database::Get()->UpdateAccountPassword(accountId->id, std::string(hash, BCRYPT_HASHSIZE)); - LOG("Account \"%s\" password updated successfully!", username.c_str()); + Log::Info("Account \"{:s}\" password updated successfully!", username); } else { - LOG("Account \"%s\" was not updated.", username.c_str()); + Log::Info("Account \"{:s}\" was not updated.", username); } return EXIT_SUCCESS; } @@ -244,11 +244,11 @@ int main(int argc, char** argv) { try { Database::Get()->InsertNewAccount(username, std::string(hash, BCRYPT_HASHSIZE)); } catch (sql::SQLException& e) { - LOG("A SQL error occurred!:\n %s", e.what()); + Log::Warn("A SQL error occurred!:\n {:s}", e.what()); return EXIT_FAILURE; } - LOG("Account created successfully!"); + Log::Info("Account created successfully!"); return EXIT_SUCCESS; } @@ -383,14 +383,14 @@ int main(int argc, char** argv) { void HandlePacket(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION) { - LOG("A server has disconnected"); + Log::Info("A server has disconnected"); //Since this disconnection is intentional, we'll just delete it as //we'll start a new one anyway if needed: Instance* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); if (instance) { - LOG("Actually disconnected from zone %i clone %i instance %i port %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); + Log::Info("Actually disconnected from zone {:d} clone {:d} instance {:d} port {:d}", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); Game::im->RemoveInstance(instance); //Delete the old } @@ -406,7 +406,7 @@ void HandlePacket(Packet* packet) { } if (packet->data[0] == ID_CONNECTION_LOST) { - LOG("A server has lost the connection"); + Log::Info("A server has lost the connection"); Instance* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); @@ -431,7 +431,7 @@ void HandlePacket(Packet* packet) { if (static_cast(packet->data[1]) == eConnectionType::MASTER) { switch (static_cast(packet->data[3])) { case eMasterMessageType::REQUEST_PERSISTENT_ID: { - LOG("A persistent ID req"); + Log::Info("A persistent ID req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint64_t requestID = 0; @@ -443,7 +443,7 @@ void HandlePacket(Packet* packet) { } case eMasterMessageType::REQUEST_ZONE_TRANSFER: { - LOG("Received zone transfer req"); + Log::Info("Received zone transfer req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint64_t requestID = 0; @@ -456,24 +456,24 @@ void HandlePacket(Packet* packet) { inStream.Read(zoneID); inStream.Read(zoneClone); if (shutdownSequenceStarted) { - LOG("Shutdown sequence has been started. Not creating a new zone."); + Log::Info("Shutdown sequence has been started. Not creating a new zone."); break; } Instance* in = Game::im->GetInstance(zoneID, false, zoneClone); for (auto* instance : Game::im->GetInstances()) { - LOG("Instance: %i/%i/%i -> %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance == in); + Log::Info("Instance: {:d}/{:d}/{:d} -> {:d}", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance == in); } if (in && !in->GetIsReady()) //Instance not ready, make a pending request { in->GetPendingRequests().push_back({ requestID, static_cast(mythranShift), packet->systemAddress }); - LOG("Server not ready, adding pending request %llu %i %i", requestID, zoneID, zoneClone); + Log::Info("Server not ready, adding pending request {:d} {:d} {:d}", requestID, zoneID, zoneClone); break; } //Instance is ready, transfer - LOG("Responding to transfer request %llu for zone %i %i", requestID, zoneID, zoneClone); + Log::Info("Responding to transfer request {:d} for zone {:d} {:d}", requestID, zoneID, zoneClone); Game::im->RequestAffirmation(in, { requestID, static_cast(mythranShift), packet->systemAddress }); break; } @@ -534,7 +534,7 @@ void HandlePacket(Packet* packet) { authServerMasterPeerSysAddr = copy; } - LOG("Received server info, instance: %i port: %i", theirInstanceID, theirPort); + Log::Info("Received server info, instance: {:d} port: {:d}", theirInstanceID, theirPort); break; } @@ -561,7 +561,7 @@ void HandlePacket(Packet* packet) { } activeSessions.insert(std::make_pair(sessionKey, username.string)); - LOG("Got sessionKey %i for user %s", sessionKey, username.string.c_str()); + Log::Info("Got sessionKey {:d} for user {:s}", sessionKey, username.string); break; } @@ -569,7 +569,7 @@ void HandlePacket(Packet* packet) { CINSTREAM_SKIP_HEADER; LUWString username; inStream.Read(username); - LOG("Requesting session key for %s", username.GetAsString().c_str()); + Log::Info("Requesting session key for {:s}", username.GetAsString()); for (auto key : activeSessions) { if (key.second == username.GetAsString()) { CBITSTREAM; @@ -640,7 +640,7 @@ void HandlePacket(Packet* packet) { password += character; } - Game::im->CreatePrivateInstance(mapId, cloneId, password.c_str()); + Game::im->CreatePrivateInstance(mapId, cloneId, password); break; } @@ -665,9 +665,9 @@ void HandlePacket(Packet* packet) { password += character; } - auto* instance = Game::im->FindPrivateInstance(password.c_str()); + auto* instance = Game::im->FindPrivateInstance(password); - LOG("Join private zone: %llu %d %s %p", requestID, mythranShift, password.c_str(), instance); + Log::Info("Join private zone: {:d} {:d} {:s} {:p}", requestID, mythranShift, password, fmt::ptr(instance)); if (instance == nullptr) { return; @@ -690,16 +690,16 @@ void HandlePacket(Packet* packet) { inStream.Read(zoneID); inStream.Read(instanceID); - LOG("Got world ready %i %i", zoneID, instanceID); + Log::Info("Got world ready {:d} {:d}", zoneID, instanceID); auto* instance = Game::im->FindInstance(zoneID, instanceID); if (instance == nullptr) { - LOG("Failed to find zone to ready"); + Log::Warn("Failed to find zone to ready"); return; } - LOG("Ready zone %i", zoneID); + Log::Info("Ready zone {:d}", zoneID); Game::im->ReadyInstance(instance); break; } @@ -711,10 +711,10 @@ void HandlePacket(Packet* packet) { int32_t zoneID; inStream.Read(zoneID); if (shutdownSequenceStarted) { - LOG("Shutdown sequence has been started. Not prepping a new zone."); + Log::Info("Shutdown sequence has been started. Not prepping a new zone."); break; } else { - LOG("Prepping zone %i", zoneID); + Log::Info("Prepping zone {:d}", zoneID); Game::im->GetInstance(zoneID, false, 0); } break; @@ -728,7 +728,7 @@ void HandlePacket(Packet* packet) { inStream.Read(requestID); - LOG("Got affirmation of transfer %llu", requestID); + Log::Info("Got affirmation of transfer {:d}", requestID); auto* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); @@ -736,7 +736,7 @@ void HandlePacket(Packet* packet) { return; Game::im->AffirmTransfer(instance, requestID); - LOG("Affirmation complete %llu", requestID); + Log::Info("Affirmation complete {:d}", requestID); break; } @@ -750,28 +750,28 @@ void HandlePacket(Packet* packet) { return; } - LOG("Got shutdown response from zone %i clone %i instance %i port %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); + Log::Info("Got shutdown response from zone {:d} clone {:d} instance {:d} port {:d}", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); instance->SetIsShuttingDown(true); break; } case eMasterMessageType::SHUTDOWN_UNIVERSE: { - LOG("Received shutdown universe command, shutting down in 10 minutes."); + Log::Info("Received shutdown universe command, shutting down in 10 minutes."); Game::universeShutdownRequested = true; break; } default: - LOG("Unknown master packet ID from server: %i", packet->data[3]); + Log::Info("Unknown master packet ID from server: {:d}", packet->data[3]); } } } int ShutdownSequence(int32_t signal) { if (!Game::logger) return -1; - LOG("Recieved Signal %d", signal); + Log::Info("Recieved Signal {:d}", signal); if (shutdownSequenceStarted) { - LOG("Duplicate Shutdown Sequence"); + Log::Info("Duplicate Shutdown Sequence"); return -1; } @@ -787,11 +787,11 @@ int ShutdownSequence(int32_t signal) { CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SHUTDOWN); Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); - LOG("Triggered master shutdown"); + Log::Info("Triggered master shutdown"); } PersistentIDManager::SaveToDatabase(); - LOG("Saved ObjectIDTracker to DB"); + Log::Info("Saved ObjectIDTracker to DB"); // A server might not be finished spinning up yet, remove all of those here. for (auto* instance : Game::im->GetInstances()) { @@ -804,7 +804,7 @@ int ShutdownSequence(int32_t signal) { instance->SetIsShuttingDown(true); } - LOG("Attempting to shutdown instances, max 60 seconds..."); + Log::Info("Attempting to shutdown instances, max 60 seconds..."); auto t = std::chrono::high_resolution_clock::now(); uint32_t framesSinceShutdownStart = 0; @@ -832,7 +832,7 @@ int ShutdownSequence(int32_t signal) { } if (allInstancesShutdown && authServerMasterPeerSysAddr == UNASSIGNED_SYSTEM_ADDRESS && chatServerMasterPeerSysAddr == UNASSIGNED_SYSTEM_ADDRESS) { - LOG("Finished shutting down MasterServer!"); + Log::Info("Finished shutting down MasterServer!"); break; } @@ -842,7 +842,7 @@ int ShutdownSequence(int32_t signal) { framesSinceShutdownStart++; if (framesSinceShutdownStart == maxShutdownTime) { - LOG("Finished shutting down by timeout!"); + Log::Info("Finished shutting down by timeout!"); break; } } diff --git a/dNet/CMakeLists.txt b/dNet/CMakeLists.txt index 15cdda42..aca663e0 100644 --- a/dNet/CMakeLists.txt +++ b/dNet/CMakeLists.txt @@ -8,7 +8,7 @@ set(DNET_SOURCES "AuthPackets.cpp" "ZoneInstanceManager.cpp") add_library(dNet STATIC ${DNET_SOURCES}) -target_link_libraries(dNet PRIVATE bcrypt MD5) +target_link_libraries(dNet PRIVATE bcrypt fmt MD5) target_include_directories(dNet PRIVATE "${PROJECT_SOURCE_DIR}/dCommon" "${PROJECT_SOURCE_DIR}/dCommon/dEnums" diff --git a/dPhysics/CMakeLists.txt b/dPhysics/CMakeLists.txt index 65588b4b..4cc63054 100644 --- a/dPhysics/CMakeLists.txt +++ b/dPhysics/CMakeLists.txt @@ -12,5 +12,5 @@ target_include_directories(dPhysics PUBLIC "." "${PROJECT_SOURCE_DIR}/dCommon/dEnums" ) target_link_libraries(dPhysics - PUBLIC Recast Detour + PUBLIC fmt Recast Detour INTERFACE dNavigation dCommon) diff --git a/dServer/CMakeLists.txt b/dServer/CMakeLists.txt index ca4e6198..ab14627a 100644 --- a/dServer/CMakeLists.txt +++ b/dServer/CMakeLists.txt @@ -3,6 +3,8 @@ set(DSERVER_SOURCES add_library(dServer STATIC ${DSERVER_SOURCES}) +target_link_libraries(dServer PRIVATE fmt) + target_include_directories(dServer PUBLIC ".") target_include_directories(dServer PRIVATE diff --git a/dWorldServer/CMakeLists.txt b/dWorldServer/CMakeLists.txt index 62a3767a..3c3fd97f 100644 --- a/dWorldServer/CMakeLists.txt +++ b/dWorldServer/CMakeLists.txt @@ -13,7 +13,7 @@ target_include_directories(WorldServer PRIVATE "${PROJECT_SOURCE_DIR}/dServer" # BinaryPathFinder.h ) -target_link_libraries(WorldServer ${COMMON_LIBRARIES} +target_link_libraries(WorldServer PRIVATE ${COMMON_LIBRARIES} dScripts dGameBase dComponents diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index fde5a2a6..26c9b6bc 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -150,9 +150,9 @@ int main(int argc, char** argv) { Server::SetupLogger("WorldServer_" + std::to_string(zoneID) + "_" + std::to_string(instanceID)); if (!Game::logger) return EXIT_FAILURE; - LOG("Starting World server..."); - LOG("Version: %s", Game::projectVersion.c_str()); - LOG("Compiled on: %s", __TIMESTAMP__); + Log::Info("Starting World server..."); + Log::Info("Version: {:s}", Game::projectVersion); + Log::Info("Compiled on: {:s}", __TIMESTAMP__); if (Game::config->GetValue("disable_chat") == "1") chatDisabled = true; @@ -165,7 +165,7 @@ int main(int argc, char** argv) { } Game::assetManager = new AssetManager(clientPath); } catch (std::runtime_error& ex) { - LOG("Got an error while setting up assets: %s", ex.what()); + Log::Warn("Got an error while setting up assets: {:s}", ex.what()); return EXIT_FAILURE; } @@ -174,9 +174,9 @@ int main(int argc, char** argv) { try { CDClientDatabase::Connect((BinaryPathFinder::GetBinaryDir() / "resServer" / "CDServer.sqlite").string()); } catch (CppSQLite3Exception& e) { - LOG("Unable to connect to CDServer SQLite Database"); - LOG("Error: %s", e.errorMessage()); - LOG("Error Code: %i", e.errorCode()); + Log::Warn("Unable to connect to CDServer SQLite Database"); + Log::Warn("Error: {:s}", e.errorMessage()); + Log::Warn("Error Code: %i", e.errorCode()); return EXIT_FAILURE; } @@ -192,7 +192,7 @@ int main(int argc, char** argv) { try { Database::Connect(); } catch (sql::SQLException& ex) { - LOG("Got an error while connecting to the database: %s", ex.what()); + Log::Warn("Got an error while connecting to the database: {:s}", ex.what()); return EXIT_FAILURE; } @@ -300,7 +300,7 @@ int main(int argc, char** argv) { delete md5; - LOG("FDB Checksum calculated as: %s", databaseChecksum.c_str()); + Log::Info("FDB Checksum calculated as: {:s}", databaseChecksum); } uint32_t currentFrameDelta = highFrameDelta; @@ -335,10 +335,10 @@ int main(int argc, char** argv) { // Update to the new framerate and scale all timings to said new framerate if (newFrameDelta != currentFrameDelta) { - float_t ratioBeforeToAfter = (float)currentFrameDelta / (float)newFrameDelta; + float_t ratioBeforeToAfter = static_cast(currentFrameDelta) / static_cast(newFrameDelta); currentFrameDelta = newFrameDelta; currentFramerate = MS_TO_FRAMES(newFrameDelta); - LOG_DEBUG("Framerate for zone/instance/clone %i/%i/%i is now %i", zoneID, instanceID, cloneID, currentFramerate); + Log::Debug("Framerate for zone/instance/clone {:d}/{:d}/{:d} is now {:d}", zoneID, instanceID, cloneID, currentFramerate); logFlushTime = 15 * currentFramerate; // 15 seconds in frames framesSinceLastFlush *= ratioBeforeToAfter; shutdownTimeout = 10 * 60 * currentFramerate; // 10 minutes in frames @@ -357,7 +357,7 @@ int main(int argc, char** argv) { //Warning if we ran slow if (deltaTime > currentFrameDelta) { - LOG("We're running behind, dT: %f > %f (framerate %i)", deltaTime, currentFrameDelta, currentFramerate); + Log::Info("We're running behind, dT: {:f} > {:d} (framerate {:d})", deltaTime, currentFrameDelta, currentFramerate); } //Check if we're still connected to master: @@ -365,7 +365,7 @@ int main(int argc, char** argv) { framesSinceMasterDisconnect++; if (framesSinceMasterDisconnect >= noMasterConnectionTimeout && !Game::ShouldShutdown()) { - LOG("Game loop running but no connection to master for %d frames, shutting down", noMasterConnectionTimeout); + Log::Warn("Game loop running but no connection to master for {:d} frames, shutting down!", noMasterConnectionTimeout); Game::lastSignal = -1; } } else framesSinceMasterDisconnect = 0; @@ -506,7 +506,7 @@ int main(int argc, char** argv) { framesSinceMasterStatus++; if (framesSinceMasterStatus >= 200) { - LOG("Finished loading world with zone (%i), ready up!", Game::server->GetZoneID()); + Log::Info("Finished loading world with zone ({:d}), ready up!", Game::server->GetZoneID()); MasterPackets::SendWorldReady(Game::server, Game::server->GetZoneID(), Game::server->GetInstanceID()); @@ -528,13 +528,13 @@ int main(int argc, char** argv) { void HandlePacketChat(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - LOG("Lost our connection to chat, zone(%i), instance(%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); + Log::Info("Lost our connection to chat, zone({:d}), instance({:d})", Game::server->GetZoneID(), Game::server->GetInstanceID()); chatConnected = false; } if (packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED) { - LOG("Established connection to chat, zone(%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); + Log::Info("Established connection to chat, zone({:d}), instance ({:d})", Game::server->GetZoneID(), Game::server->GetInstanceID()); Game::chatSysAddr = packet->systemAddress; chatConnected = true; @@ -630,20 +630,20 @@ void HandlePacketChat(Packet* packet) { if (deleteTeam) { TeamManager::Instance()->DeleteTeam(teamID); - LOG("Deleting team (%llu)", teamID); + Log::Info("Deleting team (%llu)", teamID); break; } inStream.Read(lootOption); inStream.Read(memberCount); - LOG("Updating team (%llu), (%i), (%i)", teamID, lootOption, memberCount); + Log::Info("Updating team (%llu), ({:d}), ({:d})", teamID, lootOption, memberCount); for (char i = 0; i < memberCount; i++) { LWOOBJID member = LWOOBJID_EMPTY; inStream.Read(member); members.push_back(member); - LOG("Updating team member (%llu)", member); + Log::Info("Updating team member (%llu)", member); } TeamManager::Instance()->UpdateTeam(teamID, lootOption, members); @@ -652,7 +652,7 @@ void HandlePacketChat(Packet* packet) { } default: - LOG("Received an unknown chat internal: %i", int(packet->data[3])); + Log::Info("Received an unknown chat internal: {:d}", static_cast(packet->data[3])); } } } @@ -690,11 +690,11 @@ void HandleMasterPacket(Packet* packet) { //Verify it: if (userHash != it->second.hash) { - LOG("SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s", userHash.c_str(), it->second.hash.c_str()); + Log::Info("SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: {:s} != master: {:s}", userHash, it->second.hash); Game::server->Disconnect(it->second.sysAddr, eServerDisconnectIdentifiers::INVALID_SESSION_KEY); return; } else { - LOG("User %s authenticated with correct key.", username.GetAsString().c_str()); + Log::Info("User {:s} authenticated with correct key.", username.GetAsString()); UserManager::Instance()->DeleteUser(packet->systemAddress); @@ -740,7 +740,7 @@ void HandleMasterPacket(Packet* packet) { CINSTREAM_SKIP_HEADER; uint64_t requestID; inStream.Read(requestID); - LOG("Got affirmation request of transfer %llu", requestID); + Log::Info("Got affirmation request of transfer %llu", requestID); CBITSTREAM; @@ -753,7 +753,7 @@ void HandleMasterPacket(Packet* packet) { case eMasterMessageType::SHUTDOWN: { Game::lastSignal = -1; - LOG("Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); + Log::Info("Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); break; } @@ -763,24 +763,24 @@ void HandleMasterPacket(Packet* packet) { LUString username; inStream.Read(username); - LOG("Got new session alert for user %s", username.string.c_str()); + Log::Info("Got new session alert for user {:s}", username.string); //Find them: - User* user = UserManager::Instance()->GetUser(username.string.c_str()); + User* user = UserManager::Instance()->GetUser(username.string); if (!user) { - LOG("But they're not logged in?"); + Log::Info("But they're not logged in?"); return; } //Check the key: if (sessionKey != std::atoi(user->GetSessionKey().c_str())) { - LOG("But the session key is invalid!", username.string.c_str()); + Log::Info("But the session key is invalid!", username.string.c_str()); Game::server->Disconnect(user->GetSystemAddress(), eServerDisconnectIdentifiers::INVALID_SESSION_KEY); return; } break; } default: - LOG("Unknown packet ID from master %i", int(packet->data[3])); + Log::Info("Unknown packet ID from master %i", int(packet->data[3])); } } @@ -810,7 +810,7 @@ void HandlePacket(Packet* packet) { entity->GetCharacter()->SaveXMLToDatabase(); - LOG("Deleting player %llu", entity->GetObjectID()); + Log::Info("Deleting player %llu", entity->GetObjectID()); Game::entityManager->DestroyEntity(entity); } @@ -860,7 +860,7 @@ void HandlePacket(Packet* packet) { if (Game::config->GetValue("check_fdb") == "1" && !databaseChecksum.empty()) { auto accountInfo = Database::Get()->GetAccountInfo(username.GetAsString()); if (!accountInfo) { - LOG("Client's account does not exist in the database, aborting connection."); + Log::Info("Client's account does not exist in the database, aborting connection."); Game::server->Disconnect(packet->systemAddress, eServerDisconnectIdentifiers::CHARACTER_NOT_FOUND); return; } @@ -869,7 +869,7 @@ void HandlePacket(Packet* packet) { if (clientDatabaseChecksum.string != databaseChecksum) { if (accountInfo->maxGmLevel < eGameMasterLevel::DEVELOPER) { - LOG("Client's database checksum does not match the server's, aborting connection."); + Log::Info("Client's database checksum does not match the server's, aborting connection."); std::vector stamps; // Using the LoginResponse here since the UI is still in the login screen state @@ -885,8 +885,8 @@ void HandlePacket(Packet* packet) { args.Insert("message", Game::config->GetValue("cdclient_mismatch_message")); GameMessages::SendUIMessageServerToSingleClient("ToggleAnnounce", args, packet->systemAddress); - LOG("Account (%s) with GmLevel (%s) does not have a matching FDB, but is a developer and will skip this check." - , username.GetAsString().c_str(), StringifiedEnum::ToString(accountInfo->maxGmLevel).data()); + Log::Info("Account ({:s}) with GmLevel ({:s}) does not have a matching FDB, but is a developer and will skip this check." + , username.GetAsString(), StringifiedEnum::ToString(accountInfo->maxGmLevel)); } } } @@ -1008,7 +1008,7 @@ void HandlePacket(Packet* packet) { } case eWorldMessageType::LEVEL_LOAD_COMPLETE: { - LOG("Received level load complete from user."); + Log::Info("Received level load complete from user."); User* user = UserManager::Instance()->GetUser(packet->systemAddress); if (user) { Character* c = user->GetLastUsedChar(); @@ -1047,15 +1047,15 @@ void HandlePacket(Packet* packet) { case eCharacterVersion::RELEASE: // TODO: Implement, super low priority case eCharacterVersion::LIVE: - LOG("Updating Character Flags"); + Log::Info("Updating Character Flags"); c->SetRetroactiveFlags(); levelComponent->SetCharacterVersion(eCharacterVersion::PLAYER_FACTION_FLAGS); case eCharacterVersion::PLAYER_FACTION_FLAGS: - LOG("Updating Vault Size"); + Log::Info("Updating Vault Size"); player->RetroactiveVaultSize(); levelComponent->SetCharacterVersion(eCharacterVersion::VAULT_SIZE); case eCharacterVersion::VAULT_SIZE: - LOG("Updaing Speedbase"); + Log::Info("Updaing Speedbase"); levelComponent->SetRetroactiveBaseSpeed(); levelComponent->SetCharacterVersion(eCharacterVersion::UP_TO_DATE); case eCharacterVersion::UP_TO_DATE: @@ -1084,11 +1084,11 @@ void HandlePacket(Packet* packet) { LWOOBJID propertyId = LWOOBJID_EMPTY; if (propertyInfo) propertyId = propertyInfo->id; else { - LOG("Couldn't find property ID for zone %i, clone %i", zoneId, cloneId); + Log::Info("Couldn't find property ID for zone %i, clone %i", zoneId, cloneId); goto noBBB; } for (auto& bbbModel : Database::Get()->GetUgcModels(propertyId)) { - LOG("Getting lxfml ugcID: %llu", bbbModel.id); + Log::Info("Getting lxfml ugcID: %llu", bbbModel.id); bbbModel.lxfmlData.seekg(0, std::ios::end); size_t lxfmlSize = bbbModel.lxfmlData.tellg(); @@ -1149,11 +1149,11 @@ void HandlePacket(Packet* packet) { Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); } } else { - LOG("Couldn't find character to log in with for user %s (%i)!", user->GetUsername().c_str(), user->GetAccountID()); + Log::Warn("Couldn't find character to log in with for user {:s} (%i)!", user->GetUsername(), user->GetAccountID()); Game::server->Disconnect(packet->systemAddress, eServerDisconnectIdentifiers::CHARACTER_NOT_FOUND); } } else { - LOG("Couldn't get user for level load complete!"); + Log::Warn("Couldn't get user for level load complete!"); } break; } @@ -1163,7 +1163,7 @@ void HandlePacket(Packet* packet) { User* user = UserManager::Instance()->GetUser(packet->systemAddress); if (!user) { - LOG("Unable to get user to parse position update"); + Log::Warn("Unable to get user to parse position update"); return; } @@ -1188,7 +1188,7 @@ void HandlePacket(Packet* packet) { inStream.Read(size); if (size > 20000) { - LOG("Tried to route a packet with a read size > 20000, so likely a false packet."); + Log::Warn("Tried to route a packet with a read size > 20000, so likely a false packet."); return; } @@ -1221,14 +1221,14 @@ void HandlePacket(Packet* packet) { // TODO: Find a good home for the logic in this case. User* user = UserManager::Instance()->GetUser(packet->systemAddress); if (!user) { - LOG("Unable to get user to parse chat moderation request"); + Log::Warn("Unable to get user to parse chat moderation request"); return; } auto* entity = PlayerManager::GetPlayer(packet->systemAddress); if (entity == nullptr) { - LOG("Unable to get player to parse chat moderation request"); + Log::Warn("Unable to get player to parse chat moderation request"); return; } @@ -1296,7 +1296,7 @@ void HandlePacket(Packet* packet) { // TODO: Find a good home for the logic in this case. User* user = UserManager::Instance()->GetUser(packet->systemAddress); if (!user) { - LOG("Unable to get user to parse chat message"); + Log::Warn("Unable to get user to parse chat message"); return; } @@ -1307,12 +1307,12 @@ void HandlePacket(Packet* packet) { std::string playerName = user->GetLastUsedChar()->GetName(); bool isMythran = user->GetLastUsedChar()->GetGMLevel() > eGameMasterLevel::CIVILIAN; bool isOk = Game::chatFilter->IsSentenceOkay(GeneralUtils::UTF16ToWTF8(chatMessage.message), user->GetLastUsedChar()->GetGMLevel()).empty(); - LOG_DEBUG("Msg: %s was approved previously? %i", GeneralUtils::UTF16ToWTF8(chatMessage.message).c_str(), user->GetLastChatMessageApproved()); + Log::Debug("Msg: {:s} was approved previously? %i", GeneralUtils::UTF16ToWTF8(chatMessage.message), user->GetLastChatMessageApproved()); if (!isOk) return; if (!isOk && !isMythran) return; std::string sMessage = GeneralUtils::UTF16ToWTF8(chatMessage.message); - LOG("%s: %s", playerName.c_str(), sMessage.c_str()); + Log::Info("{:s}: {:s}", playerName, sMessage); ChatPackets::SendChatMessage(packet->systemAddress, chatMessage.chatChannel, playerName, user->GetLoggedInChar(), isMythran, chatMessage.message); } @@ -1374,39 +1374,39 @@ void HandlePacket(Packet* packet) { } default: - const auto messageId = *reinterpret_cast(&packet->data[3]); - const std::string_view messageIdString = StringifiedEnum::ToString(messageId); - LOG("Unknown world packet received: %4i, %s", messageId, messageIdString.data()); + const auto& messageId = reinterpret_cast(packet->data[3]); + const auto messageIdString = StringifiedEnum::ToString(messageId); + Log::Info("Unknown world packet received: {:4d}, {:s}", GeneralUtils::ToUnderlying(messageId), messageIdString); } } void WorldShutdownProcess(uint32_t zoneId) { - LOG("Saving map %i instance %i", zoneId, instanceID); + Log::Info("Saving map %i instance %i", zoneId, instanceID); for (auto i = 0; i < Game::server->GetReplicaManager()->GetParticipantCount(); ++i) { const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(i); auto* entity = PlayerManager::GetPlayer(player); - LOG("Saving data!"); + Log::Info("Saving data!"); if (entity != nullptr && entity->GetCharacter() != nullptr) { auto* skillComponent = entity->GetComponent(); if (skillComponent != nullptr) { skillComponent->Reset(); } - LOG("Saving character %s...", entity->GetCharacter()->GetName().c_str()); + Log::Info("Saving character {:s}...", entity->GetCharacter()->GetName()); entity->GetCharacter()->SaveXMLToDatabase(); - LOG("Character data for %s was saved!", entity->GetCharacter()->GetName().c_str()); + Log::Info("Character data for {:s} was saved!", entity->GetCharacter()->GetName()); } } if (PropertyManagementComponent::Instance() != nullptr) { - LOG("Saving ALL property data for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + Log::Info("Saving ALL property data for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); PropertyManagementComponent::Instance()->Save(); Database::Get()->RemoveUnreferencedUgcModels(); - LOG("ALL property data saved for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + Log::Info("ALL property data saved for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); } - LOG("ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!", zoneId, instanceID); + Log::Info("ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!", zoneId, instanceID); while (Game::server->GetReplicaManager()->GetParticipantCount() > 0) { const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(0); @@ -1428,13 +1428,13 @@ void WorldShutdownSequence() { if (!Game::logger) return; - LOG("Zone (%i) instance (%i) shutting down outside of main loop!", Game::server->GetZoneID(), instanceID); + Log::Info("Zone (%i) instance (%i) shutting down outside of main loop!", Game::server->GetZoneID(), instanceID); WorldShutdownProcess(Game::server->GetZoneID()); FinalizeShutdown(); } void FinalizeShutdown() { - LOG("Shutdown complete, zone (%i), instance (%i)", Game::server->GetZoneID(), instanceID); + Log::Info("Shutdown complete, zone (%i), instance (%i)", Game::server->GetZoneID(), instanceID); //Delete our objects here: Metrics::Clear(); diff --git a/tests/dCommonTests/CMakeLists.txt b/tests/dCommonTests/CMakeLists.txt index ef7c4cba..acfe16e1 100644 --- a/tests/dCommonTests/CMakeLists.txt +++ b/tests/dCommonTests/CMakeLists.txt @@ -32,7 +32,7 @@ add_custom_command(TARGET dCommonTests POST_BUILD endif() # Link needed libraries -target_link_libraries(dCommonTests ${COMMON_LIBRARIES} GTest::gtest_main) +target_link_libraries(dCommonTests PRIVATE ${COMMON_LIBRARIES} GTest::gtest_main) # Copy test files to testing directory add_subdirectory(TestBitStreams) diff --git a/tests/dCommonTests/dEnumsTests/MagicEnumTests.cpp b/tests/dCommonTests/dEnumsTests/MagicEnumTests.cpp index 0ca2e2ea..d1af7fc0 100644 --- a/tests/dCommonTests/dEnumsTests/MagicEnumTests.cpp +++ b/tests/dCommonTests/dEnumsTests/MagicEnumTests.cpp @@ -3,6 +3,7 @@ #include +#include "GeneralUtils.h" #include "StringifiedEnum.h" #include "Logger.h" #include "Game.h" @@ -11,7 +12,7 @@ #include "magic_enum.hpp" #define ENUM_EQ(e, y, z)\ - LOG("%s %s", StringifiedEnum::ToString(static_cast(y)).data(), #z);\ + Log::Info("{:s} {:s}", StringifiedEnum::ToString(static_cast(y)), #z);\ ASSERT_STREQ(StringifiedEnum::ToString(static_cast(y)).data(), #z); #define ENUM_NE(e, y)\ @@ -64,10 +65,10 @@ TEST(MagicEnumTest, eWorldMessageTypeTest) { volatile auto f = StringifiedEnum::ToString(static_cast(i)).data(); // To ensure the compiler doesn't optimize out the call, I print it at random intervals - if (rand() % 100000 == 0) LOG("%i, %s", i, f); + if (rand() % 100000 == 0) Log::Info("{:d}, {:s}", i, f); } auto end = std::chrono::high_resolution_clock::now(); - LOG("Time: %lld", std::chrono::duration_cast(end - begin).count()); + Log::Info("Time: {:d}", std::chrono::duration_cast(end - begin).count()); delete Game::logger; } @@ -108,15 +109,15 @@ TEST(MagicEnumTest, eGameMessageTypeTest) { volatile auto f = StringifiedEnum::ToString(static_cast(i)).data(); // To ensure the compiler doesn't optimize out the call, I print it at random intervals - if (rand() % 100000 == 0) LOG("%i, %s", i, f); + if (rand() % 100000 == 0) Log::Info("{:d}, {:s}", i, f); } auto end = std::chrono::high_resolution_clock::now(); - LOG("Time: %lld", std::chrono::duration_cast(end - begin).count()); + Log::Info("Time: {:d}", std::chrono::duration_cast(end - begin).count()); delete Game::logger; } -#define LOG_EARRAY(EARRAY_VAR, INDICE, ENTRY) LOG(#EARRAY_VAR"[%i] = %i, %s", INDICE, ENTRY, magic_enum::enum_name(ENTRY).data()); +#define LOG_EARRAY(EARRAY_VAR, INDICE, ENTRY) Log::Info(#EARRAY_VAR"[{:d}] = {:d}, {:s}", INDICE, GeneralUtils::ToUnderlying(ENTRY), magic_enum::enum_name(ENTRY)); namespace { template diff --git a/tests/dGameTests/CMakeLists.txt b/tests/dGameTests/CMakeLists.txt index 58f213e0..cada200d 100644 --- a/tests/dGameTests/CMakeLists.txt +++ b/tests/dGameTests/CMakeLists.txt @@ -22,7 +22,7 @@ add_custom_command(TARGET dGameTests POST_BUILD WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) endif() -target_link_libraries(dGameTests ${COMMON_LIBRARIES} GTest::gtest_main +target_link_libraries(dGameTests PRIVATE ${COMMON_LIBRARIES} GTest::gtest_main dGame dScripts dPhysics Detour Recast tinyxml2 dWorldServer dZoneManager dChatFilter dNavigation) # Discover the tests diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index 41135a80..5a0268d8 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -1,6 +1,9 @@ # Source Code for recast add_subdirectory(recastnavigation) +# Add fmtlib +add_subdirectory(fmt SYSTEM) + # Turn off tinyxml2 testing set(tinyxml2_BUILD_TESTING OFF) # Source Code for tinyxml2