Compare commits

...

17 Commits

Author SHA1 Message Date
jadebenn
4c4ea2ae71 replaced a few more macro instances 2024-03-13 20:47:41 -05:00
jadebenn
cfb0826d22 updated more logs 2024-03-12 21:10:01 -05:00
jadebenn
3164bad9af cmake fix 2024-03-12 20:35:17 -05:00
jadebenn
ceb1d5d82a converting more format strings 2024-03-09 03:09:17 -06:00
jadebenn
494c2b5784 fix cmake 2024-03-08 15:44:59 -06:00
jadebenn
0bcae8e555 Merge branch 'fmtlib-experiment' of https://github.com/DarkflameUniverse/DarkflameServer into fmtlib-experiment 2024-03-08 15:44:05 -06:00
jadebenn
7250aa51f6 experimenting; not looking to pr 2024-03-08 15:44:02 -06:00
jadebenn
ac6c68ecff cmake 2024-03-07 22:52:11 -06:00
jadebenn
642c86a449 Merge remote-tracking branch 'upstream/main' into fmtlib-experiment 2024-03-06 23:47:34 -06:00
jadebenn
3a6313a3ba chore: Table Loading Improvements (#1492)
* Assorted pet improvements

* remove unecessary include

* updates to address some feedback

* fixed database code for testing

* messinng around with tables

* updated to address feedback

* fix world hang

* Remove at() in CDLootTableTable.cpp

* Uncapitalize LOT variable

* Uncapitalize LOT variable
2024-03-06 23:45:24 -06:00
jadebenn
6e3b5acede chore: Less verbose name for enum underlying type casts (#1494)
* Less verbose name for enum underlying type casts

* Remove redundant call
2024-03-06 23:45:04 -06:00
jadebenn
73312cb948 add fmtlib 2024-03-06 22:15:54 -06:00
David Markowitz
fe4b29f643 fix: commendation vendor cant accept missions (#1497)
* fix: incorrect serialization for commendation

* Update VendorComponent.h
2024-03-06 19:50:21 -06:00
David Markowitz
fcb89b3c7a Remove multiple Script syntax (#1496) 2024-03-06 19:49:29 -06:00
David Markowitz
1a0aaf3123 add info to debug logs (#1495) 2024-03-06 19:46:16 -06:00
jadebenn
9a26ba0a72 feat: Provide SerializeEntity constant reference overload (#1491) 2024-03-06 19:23:24 -06:00
jadebenn
6c9c826e19 chore: Set default symbol visibility to hidden in CMAKE (#1490)
* set default symbol visibility to hidden in CMAKE

* Update CMakeLists.txt with additional comments

* whoops, wrong comment type
2024-03-06 07:49:40 -06:00
166 changed files with 894 additions and 897 deletions

3
.gitmodules vendored
View File

@@ -17,3 +17,6 @@
[submodule "thirdparty/magic_enum"] [submodule "thirdparty/magic_enum"]
path = thirdparty/magic_enum path = thirdparty/magic_enum
url = https://github.com/Neargye/magic_enum.git url = https://github.com/Neargye/magic_enum.git
[submodule "thirdparty/fmt"]
path = thirdparty/fmt
url = https://github.com/fmtlib/fmt.git

View File

@@ -4,6 +4,8 @@ include(CTest)
set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD 20)
set(CXX_STANDARD_REQUIRED ON) set(CXX_STANDARD_REQUIRED ON)
set(CMAKE_POLICY_DEFAULT_CMP0063 NEW) # Set CMAKE visibility policy to NEW on project and subprojects
set(CMAKE_CXX_VISIBILITY_PRESET hidden) # Set C++ symbol visibility to default to hidden
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
# Read variables from file # Read variables from file
@@ -285,7 +287,7 @@ add_subdirectory(dPhysics)
add_subdirectory(dServer) add_subdirectory(dServer)
# Create a list of common libraries shared between all binaries # 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 # Add platform specific common libraries
if(UNIX) if(UNIX)

View File

@@ -54,14 +54,14 @@ int main(int argc, char** argv) {
Server::SetupLogger("AuthServer"); Server::SetupLogger("AuthServer");
if (!Game::logger) return EXIT_FAILURE; if (!Game::logger) return EXIT_FAILURE;
LOG("Starting Auth server..."); Log::Info("Starting Auth server...");
LOG("Version: %s", PROJECT_VERSION); Log::Info("Version: {:s}", PROJECT_VERSION);
LOG("Compiled on: %s", __TIMESTAMP__); Log::Info("Compiled on: {:s}", __TIMESTAMP__);
try { try {
Database::Connect(); Database::Connect();
} catch (sql::SQLException& ex) { } 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"); Database::Destroy("AuthServer");
delete Game::server; delete Game::server;
delete Game::logger; delete Game::logger;
@@ -77,7 +77,7 @@ int main(int argc, char** argv) {
masterIP = masterInfo->ip; masterIP = masterInfo->ip;
masterPort = masterInfo->port; 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)); Game::randomEngine = std::mt19937(time(0));
@@ -110,7 +110,7 @@ int main(int argc, char** argv) {
framesSinceMasterDisconnect++; framesSinceMasterDisconnect++;
if (framesSinceMasterDisconnect >= authFramerate) { if (framesSinceMasterDisconnect >= authFramerate) {
LOG("No connection to master!"); Log::Info("No connection to master!");
break; //Exit our loop, shut down. break; //Exit our loop, shut down.
} }
} else framesSinceMasterDisconnect = 0; } else framesSinceMasterDisconnect = 0;
@@ -151,7 +151,7 @@ int main(int argc, char** argv) {
std::this_thread::sleep_until(t); 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: //Delete our objects here:
Database::Destroy("AuthServer"); Database::Destroy("AuthServer");
delete Game::server; delete Game::server;

View File

@@ -1,6 +1,6 @@
add_executable(AuthServer "AuthServer.cpp") 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) target_include_directories(AuthServer PRIVATE ${PROJECT_SOURCE_DIR}/dServer)

View File

@@ -11,6 +11,6 @@ add_compile_definitions(ChatServer PRIVATE PROJECT_VERSION="\"${PROJECT_VERSION}
add_library(dChatServer ${DCHATSERVER_SOURCES}) add_library(dChatServer ${DCHATSERVER_SOURCES})
target_include_directories(dChatServer PRIVATE "${PROJECT_SOURCE_DIR}/dServer") target_include_directories(dChatServer PRIVATE "${PROJECT_SOURCE_DIR}/dServer")
target_link_libraries(dChatServer ${COMMON_LIBRARIES} dChatFilter) target_link_libraries(dChatServer PRIVATE ${COMMON_LIBRARIES} dChatFilter)
target_link_libraries(ChatServer ${COMMON_LIBRARIES} dChatFilter dChatServer dServer) target_link_libraries(ChatServer PRIVATE ${COMMON_LIBRARIES} dChatFilter dChatServer dServer)

View File

@@ -27,16 +27,16 @@ void ChatIgnoreList::GetIgnoreList(Packet* packet) {
auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId); auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId);
if (!receiver) { 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; return;
} }
if (!receiver.ignoredPlayers.empty()) { 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 { } else {
auto ignoreList = Database::Get()->GetIgnoreList(static_cast<uint32_t>(playerId)); auto ignoreList = Database::Get()->GetIgnoreList(static_cast<uint32_t>(playerId));
if (ignoreList.empty()) { if (ignoreList.empty()) {
LOG_DEBUG("Player %llu has no ignores", playerId); Log::Debug("Player {:d} has no ignores", playerId);
return; return;
} }
@@ -69,13 +69,13 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId); auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId);
if (!receiver) { 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; return;
} }
constexpr int32_t MAX_IGNORES = 32; constexpr int32_t MAX_IGNORES = 32;
if (receiver.ignoredPlayers.size() > MAX_IGNORES) { 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; return;
} }
@@ -91,11 +91,11 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
// Check if the player exists // Check if the player exists
LWOOBJID ignoredPlayerId = LWOOBJID_EMPTY; LWOOBJID ignoredPlayerId = LWOOBJID_EMPTY;
if (toIgnoreStr == receiver.playerName || toIgnoreStr.find("[GM]") == 0) { 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); bitStream.Write(ChatIgnoreList::AddResponse::GENERAL_ERROR);
} else if (std::count(receiver.ignoredPlayers.begin(), receiver.ignoredPlayers.end(), toIgnoreStr) > 0) { } 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); bitStream.Write(ChatIgnoreList::AddResponse::ALREADY_IGNORED);
} else { } else {
@@ -105,7 +105,7 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
// Fall back to query // Fall back to query
auto player = Database::Get()->GetCharacterInfo(toIgnoreStr); auto player = Database::Get()->GetCharacterInfo(toIgnoreStr);
if (!player || player->name != toIgnoreStr) { if (!player || player->name != toIgnoreStr) {
LOG_DEBUG("Player %s not found", toIgnoreStr.c_str()); Log::Debug("Player {:s} not found", toIgnoreStr);
} else { } else {
ignoredPlayerId = player->id; ignoredPlayerId = player->id;
} }
@@ -119,7 +119,7 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
GeneralUtils::SetBit(ignoredPlayerId, eObjectBits::PERSISTENT); GeneralUtils::SetBit(ignoredPlayerId, eObjectBits::PERSISTENT);
receiver.ignoredPlayers.emplace_back(toIgnoreStr, ignoredPlayerId); 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); bitStream.Write(ChatIgnoreList::AddResponse::SUCCESS);
} else { } else {
@@ -141,7 +141,7 @@ void ChatIgnoreList::RemoveIgnore(Packet* packet) {
auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId); auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId);
if (!receiver) { 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; return;
} }
@@ -153,7 +153,7 @@ void ChatIgnoreList::RemoveIgnore(Packet* packet) {
auto toRemove = std::remove(receiver.ignoredPlayers.begin(), receiver.ignoredPlayers.end(), removedIgnoreStr); auto toRemove = std::remove(receiver.ignoredPlayers.begin(), receiver.ignoredPlayers.end(), removedIgnoreStr);
if (toRemove == receiver.ignoredPlayers.end()) { 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; return;
} }

View File

@@ -93,7 +93,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) {
auto& requestor = Game::playerContainer.GetPlayerDataMutable(requestorPlayerID); auto& requestor = Game::playerContainer.GetPlayerDataMutable(requestorPlayerID);
if (!requestor) { 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; return;
} }
@@ -376,7 +376,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) {
LUWString message(size); LUWString message(size);
inStream.Read(message); 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) { switch (channel) {
case eChatChannel::TEAM: { case eChatChannel::TEAM: {
@@ -391,7 +391,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) {
break; break;
} }
default: default:
LOG("Unhandled Chat channel [%s]", StringifiedEnum::ToString(channel).data()); Log::Info("Unhandled Chat channel [{:s}]", StringifiedEnum::ToString(channel));
break; break;
} }
} }
@@ -412,7 +412,7 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) {
inStream.IgnoreBytes(4); inStream.IgnoreBytes(4);
inStream.Read(channel); 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.Read(size);
inStream.IgnoreBytes(77); inStream.IgnoreBytes(77);
@@ -424,7 +424,7 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) {
LUWString message(size); LUWString message(size);
inStream.Read(message); 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); const auto& receiver = Game::playerContainer.GetPlayerData(receiverName);
if (!receiver) { if (!receiver) {
@@ -506,13 +506,13 @@ void ChatPacketHandler::HandleTeamInvite(Packet* packet) {
if (team->memberIDs.size() > 3) { if (team->memberIDs.size() > 3) {
// no more teams greater than 4 // 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; return;
} }
SendTeamInvite(other, player); 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) { void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) {
@@ -526,7 +526,7 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) {
LWOOBJID leaderID = LWOOBJID_EMPTY; LWOOBJID leaderID = LWOOBJID_EMPTY;
inStream.Read(leaderID); inStream.Read(leaderID);
LOG("Accepted invite: %llu -> %llu (%d)", playerID, leaderID, declined); Log::Info("Accepted invite: {:d} -> {:d} ({:d})", playerID, leaderID, declined);
if (declined) { if (declined) {
return; return;
@@ -535,13 +535,13 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) {
auto* team = Game::playerContainer.GetTeam(leaderID); auto* team = Game::playerContainer.GetTeam(leaderID);
if (team == nullptr) { 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); team = Game::playerContainer.GetTeam(playerID);
} }
if (team == nullptr) { if (team == nullptr) {
LOG("Failed to find team for player (%llu)", playerID); Log::Info("Failed to find team for player ({:d})", playerID);
return; return;
} }
@@ -557,7 +557,7 @@ void ChatPacketHandler::HandleTeamLeave(Packet* packet) {
auto* team = Game::playerContainer.GetTeam(playerID); auto* team = Game::playerContainer.GetTeam(playerID);
LOG("(%llu) leaving team", playerID); Log::Info("({:d}) leaving team", playerID);
if (team != nullptr) { if (team != nullptr) {
Game::playerContainer.RemoveMember(team, playerID, false, false, true); Game::playerContainer.RemoveMember(team, playerID, false, false, true);
@@ -575,7 +575,7 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) {
inStream.Read(kickedPlayer); 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()); const auto& kicked = Game::playerContainer.GetPlayerData(kickedPlayer.GetAsString());
@@ -608,7 +608,7 @@ void ChatPacketHandler::HandleTeamPromote(Packet* packet) {
inStream.IgnoreBytes(4); inStream.IgnoreBytes(4);
inStream.Read(promotedPlayer); 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()); const auto& promoted = Game::playerContainer.GetPlayerData(promotedPlayer.GetAsString());

View File

@@ -60,9 +60,9 @@ int main(int argc, char** argv) {
//Read our config: //Read our config:
LOG("Starting Chat server..."); Log::Info("Starting Chat server...");
LOG("Version: %s", PROJECT_VERSION); Log::Info("Version: {:s}", PROJECT_VERSION);
LOG("Compiled on: %s", __TIMESTAMP__); Log::Info("Compiled on: {:s}", __TIMESTAMP__);
try { try {
std::string clientPathStr = Game::config->GetValue("client_location"); std::string clientPathStr = Game::config->GetValue("client_location");
@@ -74,7 +74,7 @@ int main(int argc, char** argv) {
Game::assetManager = new AssetManager(clientPath); Game::assetManager = new AssetManager(clientPath);
} catch (std::runtime_error& ex) { } 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; return EXIT_FAILURE;
} }
@@ -83,7 +83,7 @@ int main(int argc, char** argv) {
try { try {
Database::Connect(); Database::Connect();
} catch (sql::SQLException& ex) { } 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"); Database::Destroy("ChatServer");
delete Game::server; delete Game::server;
delete Game::logger; delete Game::logger;
@@ -181,11 +181,11 @@ int main(int argc, char** argv) {
void HandlePacket(Packet* packet) { void HandlePacket(Packet* packet) {
if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { 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) { 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. if (packet->length < 4) return; // Nothing left to process. Need 4 bytes to continue.
@@ -216,7 +216,7 @@ void HandlePacket(Packet* packet) {
} }
default: default:
LOG("Unknown CHAT_INTERNAL id: %i", int(packet->data[3])); Log::Info("Unknown CHAT_INTERNAL id: {:d}", static_cast<int>(packet->data[3]));
} }
} }
@@ -343,22 +343,22 @@ void HandlePacket(Packet* packet) {
case eChatMessageType::PRG_CSR_COMMAND: case eChatMessageType::PRG_CSR_COMMAND:
case eChatMessageType::HEARTBEAT_REQUEST_FROM_WORLD: case eChatMessageType::HEARTBEAT_REQUEST_FROM_WORLD:
case eChatMessageType::UPDATE_FREE_TRIAL_STATUS: 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; break;
default: 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<eConnectionType>(packet->data[1]) == eConnectionType::WORLD) { if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::WORLD) {
switch (static_cast<eWorldMessageType>(packet->data[3])) { switch (static_cast<eWorldMessageType>(packet->data[3])) {
case eWorldMessageType::ROUTE_PACKET: { case eWorldMessageType::ROUTE_PACKET: {
LOG("Routing packet from world"); Log::Info("Routing packet from world");
break; break;
} }
default: default:
LOG("Unknown World id: %i", int(packet->data[3])); Log::Info("Unknown World id: {:d}", static_cast<int>(packet->data[3]));
} }
} }
} }

View File

@@ -28,7 +28,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) {
CINSTREAM_SKIP_HEADER; CINSTREAM_SKIP_HEADER;
LWOOBJID playerId; LWOOBJID playerId;
if (!inStream.Read(playerId)) { if (!inStream.Read(playerId)) {
LOG("Failed to read player ID"); Log::Warn("Failed to read player ID");
return; return;
} }
@@ -50,7 +50,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) {
m_Names[data.playerID] = GeneralUtils::UTF8ToUTF16(data.playerName); 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()); Database::Get()->UpdateActivityLog(data.playerID, eActivityType::PlayerLoggedIn, data.zoneID.GetMapID());
} }
@@ -64,7 +64,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) {
const auto& player = GetPlayerData(playerID); const auto& player = GetPlayerData(playerID);
if (!player) { if (!player) {
LOG("Failed to find user: %llu", playerID); Log::Info("Failed to find user: {:d}", playerID);
return; 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); m_Players.erase(playerID);
Database::Get()->UpdateActivityLog(playerID, eActivityType::PlayerLoggedOut, player.zoneID.GetMapID()); Database::Get()->UpdateActivityLog(playerID, eActivityType::PlayerLoggedOut, player.zoneID.GetMapID());
@@ -103,7 +103,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) {
auto& player = this->GetPlayerDataMutable(playerID); auto& player = this->GetPlayerDataMutable(playerID);
if (!player) { if (!player) {
LOG("Failed to find user: %llu", playerID); Log::Warn("Failed to find user: {:d}", playerID);
return; return;
} }
@@ -207,7 +207,7 @@ TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) {
void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) { void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) {
if (team->memberIDs.size() >= 4) { 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); const auto& player = GetPlayerData(playerID);
if (!player) return; if (!player) return;
ChatPackets::SendSystemMessage(player.sysAddr, u"The teams is full! You have not been added to a team!"); ChatPackets::SendSystemMessage(player.sysAddr, u"The teams is full! You have not been added to a team!");

View File

@@ -29,7 +29,7 @@ void RakNet::BitStream::Write<AMFBaseValue&>(AMFBaseValue& value) {
break; break;
} }
default: { default: {
LOG("Encountered unwritable AMFType %i!", type); Log::Warn("Encountered unwritable AMFType {:d}!", GeneralUtils::ToUnderlying(type));
} }
case eAmf::Undefined: case eAmf::Undefined:
case eAmf::Null: case eAmf::Null:

View File

@@ -54,14 +54,14 @@ uint32_t BrickByBrickFix::TruncateBrokenBrickByBrickXml() {
completeUncompressedModel.append(reinterpret_cast<char*>(uncompressedChunk.get())); completeUncompressedModel.append(reinterpret_cast<char*>(uncompressedChunk.get()));
completeUncompressedModel.resize(previousSize + actualUncompressedSize); completeUncompressedModel.resize(previousSize + actualUncompressedSize);
} else { } else {
LOG("Failed to inflate chunk %i for model %llu. Error: %i", chunkCount, model.id, err); Log::Warn("Failed to inflate chunk {} for model %llu. Error: {}", chunkCount, model.id, err);
break; break;
} }
chunkCount++; chunkCount++;
} }
std::unique_ptr<tinyxml2::XMLDocument> document = std::make_unique<tinyxml2::XMLDocument>(); std::unique_ptr<tinyxml2::XMLDocument> document = std::make_unique<tinyxml2::XMLDocument>();
if (!document) { if (!document) {
LOG("Failed to initialize tinyxml document. Aborting."); Log::Warn("Failed to initialize tinyxml document. Aborting.");
return 0; return 0;
} }
@@ -70,13 +70,13 @@ uint32_t BrickByBrickFix::TruncateBrokenBrickByBrickXml() {
"</LXFML>", "</LXFML>",
completeUncompressedModel.length() >= 15 ? completeUncompressedModel.length() - 15 : 0) == std::string::npos completeUncompressedModel.length() >= 15 ? completeUncompressedModel.length() - 15 : 0) == std::string::npos
) { ) {
LOG("Brick-by-brick model %llu will be deleted!", model.id); Log::Info("Brick-by-brick model {} will be deleted!", model.id);
Database::Get()->DeleteUgcModelData(model.id); Database::Get()->DeleteUgcModelData(model.id);
modelsTruncated++; modelsTruncated++;
} }
} }
} else { } else {
LOG("Brick-by-brick model %llu will be deleted!", model.id); Log::Info("Brick-by-brick model {} will be deleted!", model.id);
Database::Get()->DeleteUgcModelData(model.id); Database::Get()->DeleteUgcModelData(model.id);
modelsTruncated++; modelsTruncated++;
} }
@@ -121,11 +121,11 @@ uint32_t BrickByBrickFix::UpdateBrickByBrickModelsToSd0() {
try { try {
Database::Get()->UpdateUgcModelData(model.id, outputStringStream); Database::Get()->UpdateUgcModelData(model.id, outputStringStream);
LOG("Updated model %i to sd0", model.id); Log::Info("Updated model {} to sd0", model.id);
updatedModels++; updatedModels++;
} catch (sql::SQLException exception) { } catch (sql::SQLException exception) {
LOG("Failed to update model %i. This model should be inspected manually to see why." Log::Warn("Failed to update model {}. This model should be inspected manually to see why."
"The database error is %s", model.id, exception.what()); "The database error is {}", model.id, exception.what());
} }
} }
} }

View File

@@ -70,5 +70,6 @@ else ()
endif () endif ()
target_link_libraries(dCommon target_link_libraries(dCommon
PUBLIC fmt
PRIVATE ZLIB::ZLIB bcrypt tinyxml2 PRIVATE ZLIB::ZLIB bcrypt tinyxml2
INTERFACE dDatabase) INTERFACE dDatabase)

View File

@@ -28,7 +28,7 @@ void make_minidump(EXCEPTION_POINTERS* e) {
"_%4d%02d%02d_%02d%02d%02d.dmp", "_%4d%02d%02d_%02d%02d%02d.dmp",
t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); 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); auto hFile = CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile == INVALID_HANDLE_VALUE) if (hFile == INVALID_HANDLE_VALUE)
return; return;
@@ -83,7 +83,7 @@ struct bt_ctx {
static inline void Bt(struct backtrace_state* state) { static inline void Bt(struct backtrace_state* state) {
std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; 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+"); FILE* file = fopen(fileName.c_str(), "w+");
if (file != nullptr) { if (file != nullptr) {
backtrace_print(state, 2, file); 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) { static void ErrorCallback(void* data, const char* msg, int errnum) {
auto* ctx = (struct bt_ctx*)data; auto* ctx = (struct bt_ctx*)data;
fprintf(stderr, "ERROR: %s (%d)", msg, errnum); fmt::print(stderr, "ERROR: {:s} ({:d})", msg, errnum);
ctx->error = 1; ctx->error = 1;
std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log";
FILE* file = fopen(fileName.c_str(), "w+"); FILE* file = fopen(fileName.c_str(), "w+");
if (file != nullptr) { if (file != nullptr) {
fprintf(file, "ERROR: %s (%d)", msg, errnum); fmt::print(file, "ERROR: {:s} ({:d})", msg, errnum);
fclose(file); fclose(file);
} }
} }
@@ -119,13 +119,13 @@ void CatchUnhandled(int sig) {
try { try {
if (eptr) std::rethrow_exception(eptr); if (eptr) std::rethrow_exception(eptr);
} catch(const std::exception& e) { } catch(const std::exception& e) {
LOG("Caught exception: '%s'", e.what()); Log::Warn("Caught exception: '{:s}'", e.what());
} }
#ifndef INCLUDE_BACKTRACE #ifndef INCLUDE_BACKTRACE
std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; 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()) { if (Diagnostics::GetProduceMemoryDump()) {
GenerateDump(); GenerateDump();
} }
@@ -143,7 +143,7 @@ void CatchUnhandled(int sig) {
FILE* file = fopen(fileName.c_str(), "w+"); FILE* file = fopen(fileName.c_str(), "w+");
if (file != NULL) { if (file != NULL) {
fprintf(file, "Error: signal %d:\n", sig); fmt::println(file, "Error: signal {:d}:", sig);
} }
// Print the stack trace // Print the stack trace
for (size_t i = 0; i < size; i++) { 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) { if (file != NULL) {
fprintf(file, "[%02zu] %s\n", i, functionName.c_str()); fmt::println(file, "[{:02d}] {:s}", i, functionName);
} }
} }
# else // defined(__GNUG__) # else // defined(__GNUG__)
@@ -208,7 +208,7 @@ void MakeBacktrace() {
sigaction(SIGFPE, &sigact, nullptr) != 0 || sigaction(SIGFPE, &sigact, nullptr) != 0 ||
sigaction(SIGABRT, &sigact, nullptr) != 0 || sigaction(SIGABRT, &sigact, nullptr) != 0 ||
sigaction(SIGILL, &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, SIGSEGV,
strsignal(SIGSEGV)); strsignal(SIGSEGV));

View File

@@ -42,7 +42,7 @@ bool FdbToSqlite::Convert::ConvertDatabase(AssetStream& buffer) {
CDClientDatabase::ExecuteQuery("COMMIT;"); CDClientDatabase::ExecuteQuery("COMMIT;");
} catch (CppSQLite3Exception& e) { } 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; return false;
} }

View File

@@ -264,8 +264,8 @@ namespace GeneralUtils {
* @returns The enum entry's value in its underlying type * @returns The enum entry's value in its underlying type
*/ */
template <Enum eType> template <Enum eType>
constexpr typename std::underlying_type_t<eType> CastUnderlyingType(const eType entry) noexcept { constexpr std::underlying_type_t<eType> ToUnderlying(const eType entry) noexcept {
return static_cast<typename std::underlying_type_t<eType>>(entry); return static_cast<std::underlying_type_t<eType>>(entry);
} }
// on Windows we need to undef these or else they conflict with our numeric limits calls // on Windows we need to undef these or else they conflict with our numeric limits calls

View File

@@ -48,7 +48,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
try { try {
type = static_cast<eLDFType>(strtol(ldfTypeAndValue.first.data(), &storage, 10)); type = static_cast<eLDFType>(strtol(ldfTypeAndValue.first.data(), &storage, 10));
} catch (std::exception) { } 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; return nullptr;
} }
@@ -63,7 +63,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_S32: { case LDF_TYPE_S32: {
const auto data = GeneralUtils::TryParse<int32_t>(ldfTypeAndValue.second); const auto data = GeneralUtils::TryParse<int32_t>(ldfTypeAndValue.second);
if (!data) { 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; return nullptr;
} }
returnValue = new LDFData<int32_t>(key, data.value()); returnValue = new LDFData<int32_t>(key, data.value());
@@ -74,7 +74,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_FLOAT: { case LDF_TYPE_FLOAT: {
const auto data = GeneralUtils::TryParse<float>(ldfTypeAndValue.second); const auto data = GeneralUtils::TryParse<float>(ldfTypeAndValue.second);
if (!data) { 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; return nullptr;
} }
returnValue = new LDFData<float>(key, data.value()); returnValue = new LDFData<float>(key, data.value());
@@ -84,7 +84,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_DOUBLE: { case LDF_TYPE_DOUBLE: {
const auto data = GeneralUtils::TryParse<double>(ldfTypeAndValue.second); const auto data = GeneralUtils::TryParse<double>(ldfTypeAndValue.second);
if (!data) { 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; return nullptr;
} }
returnValue = new LDFData<double>(key, data.value()); returnValue = new LDFData<double>(key, data.value());
@@ -102,7 +102,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
} else { } else {
const auto dataOptional = GeneralUtils::TryParse<uint32_t>(ldfTypeAndValue.second); const auto dataOptional = GeneralUtils::TryParse<uint32_t>(ldfTypeAndValue.second);
if (!dataOptional) { 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; return nullptr;
} }
data = dataOptional.value(); data = dataOptional.value();
@@ -122,7 +122,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
} else { } else {
const auto dataOptional = GeneralUtils::TryParse<bool>(ldfTypeAndValue.second); const auto dataOptional = GeneralUtils::TryParse<bool>(ldfTypeAndValue.second);
if (!dataOptional) { 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; return nullptr;
} }
data = dataOptional.value(); data = dataOptional.value();
@@ -135,7 +135,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_U64: { case LDF_TYPE_U64: {
const auto data = GeneralUtils::TryParse<uint64_t>(ldfTypeAndValue.second); const auto data = GeneralUtils::TryParse<uint64_t>(ldfTypeAndValue.second);
if (!data) { 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; return nullptr;
} }
returnValue = new LDFData<uint64_t>(key, data.value()); returnValue = new LDFData<uint64_t>(key, data.value());
@@ -145,7 +145,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_OBJID: { case LDF_TYPE_OBJID: {
const auto data = GeneralUtils::TryParse<LWOOBJID>(ldfTypeAndValue.second); const auto data = GeneralUtils::TryParse<LWOOBJID>(ldfTypeAndValue.second);
if (!data) { 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; return nullptr;
} }
returnValue = new LDFData<LWOOBJID>(key, data.value()); returnValue = new LDFData<LWOOBJID>(key, data.value());
@@ -159,12 +159,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
} }
case LDF_TYPE_UNKNOWN: { 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; break;
} }
default: { 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; break;
} }
} }

View File

@@ -29,7 +29,7 @@ void Writer::Flush() {
FileWriter::FileWriter(const char* outpath) { FileWriter::FileWriter(const char* outpath) {
m_Outfile = fopen(outpath, "wt"); 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_Outpath = outpath;
m_IsConsoleWriter = false; m_IsConsoleWriter = false;
} }

View File

@@ -1,6 +1,14 @@
#pragma once #pragma once
// fmt includes:
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/chrono.h>
// C++ includes:
#include <chrono>
#include <memory> #include <memory>
#include <source_location>
#include <string> #include <string>
#include <vector> #include <vector>
@@ -15,22 +23,88 @@
// Calculate the filename at compile time from the path. // 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. // 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) { constexpr const char* GetFileNameFromAbsolutePath(const char* path) {
const char* file = path; const char* file = path;
while (*path) { while (*path) {
char nextChar = *path++; const char nextChar = *path++;
if (nextChar == '/' || nextChar == '\\') { if (nextChar == '/' || nextChar == '\\') {
file = path; file = path;
} }
} }
return file; return file;
}
/**
* Location wrapper class
* Used to implicitly forward source location information without adding a function parameter
*/
template <typename T>
class location_wrapper {
public:
// Constructor
template <typename U = T>
consteval location_wrapper(const U& val, const std::source_location& loc = std::source_location::current())
: m_File(GetFileNameFromAbsolutePath(loc.file_name()))
, m_Loc(loc)
, m_Obj(val) {
}
// Methods
[[nodiscard]] constexpr const char* file() const noexcept { return m_File; }
[[nodiscard]] constexpr const std::source_location& loc() const noexcept { return m_Loc; }
[[nodiscard]] constexpr const T& get() const noexcept { return m_Obj; }
protected:
const char* m_File{};
std::source_location m_Loc{};
T m_Obj{};
};
/**
* Logging functions (EXPERIMENTAL)
*/
namespace Log {
template <typename... Ts>
[[nodiscard]] inline tm Time() { // TODO: Move?
return fmt::localtime(std::time(nullptr));
}
template <typename... Ts>
using FormatString = location_wrapper<fmt::format_string<Ts...>>;
template <typename... Ts>
inline void Info(const FormatString<Ts...> fmt_str, Ts&&... args) {
fmt::print("[{:%d-%m-%y %H:%M:%S} {}:{}] ", Time(), fmt_str.file(), fmt_str.loc().line());
fmt::println(fmt_str.get(), std::forward<Ts>(args)...);
}
template <typename... Ts>
inline void Warn(const FormatString<Ts...> fmt_str, Ts&&... args) {
fmt::print("[{:%d-%m-%y %H:%M:%S} {}:{}] Warning: ", Time(), fmt_str.file(), fmt_str.loc().line());
fmt::println(fmt_str.get(), std::forward<Ts>(args)...);
}
template <typename... Ts>
inline void Debug(const FormatString<Ts...> fmt_str, Ts&&... args) {
// if (!m_logDebugStatements) return;
Log::Info(fmt_str, std::forward<Ts>(args)...);
}
} }
// These have to have a constexpr variable to store the filename_and_line result in a local variable otherwise // 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! // 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 // 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. // 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(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 {\
const auto now = std::chrono::time_point_cast<std::chrono::seconds>(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_OPT__(,) __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_OPT__(,) __VA_ARGS__)
// Writer class for writing data to files. // Writer class for writing data to files.
class Writer { class Writer {

View File

@@ -23,7 +23,7 @@ PackIndex::PackIndex(const std::filesystem::path& filePath) {
m_PackFileIndices.push_back(packFileIndex); 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) { for (auto& item : m_PackPaths) {
std::replace(item.begin(), item.end(), '\\', '/'); std::replace(item.begin(), item.end(), '\\', '/');

View File

@@ -6,10 +6,10 @@
namespace StringifiedEnum { namespace StringifiedEnum {
template<typename T> template<typename T>
const std::string_view ToString(const T e) { constexpr std::string_view ToString(const T e) {
static_assert(std::is_enum_v<T>, "Not an enum"); // Check type static_assert(std::is_enum_v<T>, "Not an enum"); // Check type
constexpr auto& sv = magic_enum::enum_entries<T>(); constexpr const auto& sv = magic_enum::enum_entries<T>();
const auto it = std::lower_bound( const auto it = std::lower_bound(
sv.begin(), sv.end(), e, sv.begin(), sv.end(), e,

View File

@@ -157,7 +157,7 @@ void CDClientManager::LoadValuesFromDatabase() {
} }
void CDClientManager::LoadValuesFromDefaults() { void CDClientManager::LoadValuesFromDefaults() {
LOG("Loading default CDClient tables!"); Log::Info("Loading default CDClient tables!");
CDPetComponentTable::Instance().LoadValuesFromDefaults(); CDPetComponentTable::Instance().LoadValuesFromDefaults();
} }

View File

@@ -58,7 +58,7 @@ void CDLootTableTable::LoadValuesFromDatabase() {
CDLootTable entry; CDLootTable entry;
uint32_t lootTableIndex = tableData.getIntField("LootTableIndex", -1); uint32_t lootTableIndex = tableData.getIntField("LootTableIndex", -1);
entries[lootTableIndex].push_back(ReadRow(tableData)); entries[lootTableIndex].emplace_back(ReadRow(tableData));
tableData.nextRow(); tableData.nextRow();
} }
for (auto& [id, table] : entries) { for (auto& [id, table] : entries) {
@@ -66,7 +66,7 @@ void CDLootTableTable::LoadValuesFromDatabase() {
} }
} }
const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { const LootTableEntries& CDLootTableTable::GetTable(const uint32_t tableId) {
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
auto itr = entries.find(tableId); auto itr = entries.find(tableId);
if (itr != entries.end()) { if (itr != entries.end()) {
@@ -79,7 +79,7 @@ const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) {
while (!tableData.eof()) { while (!tableData.eof()) {
CDLootTable entry; CDLootTable entry;
entries[tableId].push_back(ReadRow(tableData)); entries[tableId].emplace_back(ReadRow(tableData));
tableData.nextRow(); tableData.nextRow();
} }
SortTable(entries[tableId]); SortTable(entries[tableId]);

View File

@@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDLootTable { struct CDLootTable {
uint32_t itemid; //!< The LOT of the item uint32_t itemid; //!< The LOT of the item
uint32_t LootTableIndex; //!< The Loot Table Index uint32_t LootTableIndex; //!< The Loot Table Index
@@ -20,6 +22,5 @@ private:
public: public:
void LoadValuesFromDatabase(); void LoadValuesFromDatabase();
// Queries the table with a custom "where" clause // Queries the table with a custom "where" clause
const LootTableEntries& GetTable(uint32_t tableId); const LootTableEntries& GetTable(const uint32_t tableId);
}; };

View File

@@ -20,7 +20,7 @@ void CDMissionEmailTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMissionEmail entry; auto& entry = entries.emplace_back();
entry.ID = tableData.getIntField("ID", -1); entry.ID = tableData.getIntField("ID", -1);
entry.messageType = tableData.getIntField("messageType", -1); entry.messageType = tableData.getIntField("messageType", -1);
entry.notificationGroup = tableData.getIntField("notificationGroup", -1); entry.notificationGroup = tableData.getIntField("notificationGroup", -1);
@@ -30,11 +30,8 @@ void CDMissionEmailTable::LoadValuesFromDatabase() {
entry.locStatus = tableData.getIntField("locStatus", -1); entry.locStatus = tableData.getIntField("locStatus", -1);
entry.gate_version = tableData.getStringField("gate_version", ""); entry.gate_version = tableData.getStringField("gate_version", "");
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
//! Queries the table with a custom "where" clause //! Queries the table with a custom "where" clause

View File

@@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDMissionEmail { struct CDMissionEmail {
uint32_t ID; uint32_t ID;
uint32_t messageType; uint32_t messageType;

View File

@@ -20,18 +20,15 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMissionNPCComponent entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
entry.missionID = tableData.getIntField("missionID", -1); entry.missionID = tableData.getIntField("missionID", -1);
entry.offersMission = tableData.getIntField("offersMission", -1) == 1 ? true : false; entry.offersMission = tableData.getIntField("offersMission", -1) == 1 ? true : false;
entry.acceptsMission = tableData.getIntField("acceptsMission", -1) == 1 ? true : false; entry.acceptsMission = tableData.getIntField("acceptsMission", -1) == 1 ? true : false;
entry.gate_version = tableData.getStringField("gate_version", ""); entry.gate_version = tableData.getStringField("gate_version", "");
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
//! Queries the table with a custom "where" clause //! Queries the table with a custom "where" clause

View File

@@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDMissionNPCComponent { struct CDMissionNPCComponent {
uint32_t id; //!< The ID uint32_t id; //!< The ID
uint32_t missionID; //!< The Mission ID uint32_t missionID; //!< The Mission ID
@@ -17,4 +19,3 @@ public:
// Queries the table with a custom "where" clause // Queries the table with a custom "where" clause
std::vector<CDMissionNPCComponent> Query(std::function<bool(CDMissionNPCComponent)> predicate); std::vector<CDMissionNPCComponent> Query(std::function<bool(CDMissionNPCComponent)> predicate);
}; };

View File

@@ -20,7 +20,7 @@ void CDMissionTasksTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMissionTasks entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1));
entry.taskType = tableData.getIntField("taskType", -1); entry.taskType = tableData.getIntField("taskType", -1);
@@ -35,11 +35,8 @@ void CDMissionTasksTable::LoadValuesFromDatabase() {
UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false); UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false);
UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.gate_version = tableData.getStringField("gate_version", ""));
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
std::vector<CDMissionTasks> CDMissionTasksTable::Query(std::function<bool(CDMissionTasks)> predicate) { std::vector<CDMissionTasks> CDMissionTasksTable::Query(std::function<bool(CDMissionTasks)> predicate) {
@@ -51,7 +48,7 @@ std::vector<CDMissionTasks> CDMissionTasksTable::Query(std::function<bool(CDMiss
return data; return data;
} }
std::vector<CDMissionTasks*> CDMissionTasksTable::GetByMissionID(uint32_t missionID) { std::vector<CDMissionTasks*> CDMissionTasksTable::GetByMissionID(const uint32_t missionID) {
std::vector<CDMissionTasks*> tasks; std::vector<CDMissionTasks*> tasks;
// TODO: this should not be linear(?) and also shouldnt need to be a pointer // TODO: this should not be linear(?) and also shouldnt need to be a pointer

View File

@@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDMissionTasks { struct CDMissionTasks {
uint32_t id; //!< The Mission ID that the task belongs to uint32_t id; //!< The Mission ID that the task belongs to
UNUSED(uint32_t locStatus); //!< ??? UNUSED(uint32_t locStatus); //!< ???
@@ -25,7 +27,7 @@ public:
// Queries the table with a custom "where" clause // Queries the table with a custom "where" clause
std::vector<CDMissionTasks> Query(std::function<bool(CDMissionTasks)> predicate); std::vector<CDMissionTasks> Query(std::function<bool(CDMissionTasks)> predicate);
std::vector<CDMissionTasks*> GetByMissionID(uint32_t missionID); std::vector<CDMissionTasks*> GetByMissionID(const uint32_t missionID);
// TODO: Remove this and replace it with a proper lookup function. // TODO: Remove this and replace it with a proper lookup function.
const CDTable::StorageType& GetEntries() const; const CDTable::StorageType& GetEntries() const;

View File

@@ -22,7 +22,7 @@ void CDMissionsTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMissions entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
entry.defined_type = tableData.getStringField("defined_type", ""); entry.defined_type = tableData.getStringField("defined_type", "");
entry.defined_subtype = tableData.getStringField("defined_subtype", ""); entry.defined_subtype = tableData.getStringField("defined_subtype", "");
@@ -76,7 +76,6 @@ void CDMissionsTable::LoadValuesFromDatabase() {
UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1));
entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1); entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1);
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize(); tableData.finalize();

View File

@@ -75,4 +75,3 @@ public:
static CDMissions Default; static CDMissions Default;
}; };

View File

@@ -20,7 +20,7 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovementAIComponent"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovementAIComponent");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMovementAIComponent entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
entry.MovementType = tableData.getStringField("MovementType", ""); entry.MovementType = tableData.getStringField("MovementType", "");
entry.WanderChance = tableData.getFloatField("WanderChance", -1.0f); entry.WanderChance = tableData.getFloatField("WanderChance", -1.0f);
@@ -30,11 +30,8 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() {
entry.WanderRadius = tableData.getFloatField("WanderRadius", -1.0f); entry.WanderRadius = tableData.getFloatField("WanderRadius", -1.0f);
entry.attachedPath = tableData.getStringField("attachedPath", ""); entry.attachedPath = tableData.getStringField("attachedPath", "");
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
std::vector<CDMovementAIComponent> CDMovementAIComponentTable::Query(std::function<bool(CDMovementAIComponent)> predicate) { std::vector<CDMovementAIComponent> CDMovementAIComponentTable::Query(std::function<bool(CDMovementAIComponent)> predicate) {

View File

@@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDMovementAIComponent { struct CDMovementAIComponent {
uint32_t id; uint32_t id;
std::string MovementType; std::string MovementType;

View File

@@ -20,17 +20,14 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills");
while (!tableData.eof()) { while (!tableData.eof()) {
CDObjectSkills entry; auto &entry = entries.emplace_back();
entry.objectTemplate = tableData.getIntField("objectTemplate", -1); entry.objectTemplate = tableData.getIntField("objectTemplate", -1);
entry.skillID = tableData.getIntField("skillID", -1); entry.skillID = tableData.getIntField("skillID", -1);
entry.castOnType = tableData.getIntField("castOnType", -1); entry.castOnType = tableData.getIntField("castOnType", -1);
entry.AICombatWeight = tableData.getIntField("AICombatWeight", -1); entry.AICombatWeight = tableData.getIntField("AICombatWeight", -1);
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
std::vector<CDObjectSkills> CDObjectSkillsTable::Query(std::function<bool(CDObjectSkills)> predicate) { std::vector<CDObjectSkills> CDObjectSkillsTable::Query(std::function<bool(CDObjectSkills)> predicate) {

View File

@@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDObjectSkills { struct CDObjectSkills {
uint32_t objectTemplate; //!< The LOT of the item uint32_t objectTemplate; //!< The LOT of the item
uint32_t skillID; //!< The Skill ID of the object uint32_t skillID; //!< The Skill ID of the object

View File

@@ -1,7 +1,7 @@
#include "CDObjectsTable.h" #include "CDObjectsTable.h"
namespace { namespace {
CDObjects m_default; CDObjects ObjDefault;
}; };
void CDObjectsTable::LoadValuesFromDatabase() { void CDObjectsTable::LoadValuesFromDatabase() {
@@ -20,8 +20,10 @@ void CDObjectsTable::LoadValuesFromDatabase() {
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects");
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
while (!tableData.eof()) { while (!tableData.eof()) {
CDObjects entry; const uint32_t lot = tableData.getIntField("id", 0);
entry.id = tableData.getIntField("id", -1);
auto& entry = entries[lot];
entry.id = lot;
entry.name = tableData.getStringField("name", ""); entry.name = tableData.getStringField("name", "");
UNUSED_COLUMN(entry.placeable = tableData.getIntField("placeable", -1);) UNUSED_COLUMN(entry.placeable = tableData.getIntField("placeable", -1);)
entry.type = tableData.getStringField("type", ""); entry.type = tableData.getStringField("type", "");
@@ -36,35 +38,34 @@ void CDObjectsTable::LoadValuesFromDatabase() {
UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "");) UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "");)
UNUSED_COLUMN(entry.HQ_valid = tableData.getIntField("HQ_valid", -1);) UNUSED_COLUMN(entry.HQ_valid = tableData.getIntField("HQ_valid", -1);)
entries.insert(std::make_pair(entry.id, entry));
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize(); ObjDefault.id = 0;
m_default.id = 0;
} }
const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { const CDObjects& CDObjectsTable::GetByID(const uint32_t lot) {
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
const auto& it = entries.find(LOT); const auto& it = entries.find(lot);
if (it != entries.end()) { if (it != entries.end()) {
return it->second; return it->second;
} }
auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM Objects WHERE id = ?;"); auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM Objects WHERE id = ?;");
query.bind(1, static_cast<int32_t>(LOT)); query.bind(1, static_cast<int32_t>(lot));
auto tableData = query.execQuery(); auto tableData = query.execQuery();
if (tableData.eof()) { if (tableData.eof()) {
entries.insert(std::make_pair(LOT, m_default)); entries.emplace(lot, ObjDefault);
return m_default; return ObjDefault;
} }
// Now get the data // Now get the data
while (!tableData.eof()) { while (!tableData.eof()) {
CDObjects entry; const uint32_t lot = tableData.getIntField("id", 0);
entry.id = tableData.getIntField("id", -1);
auto& entry = entries[lot];
entry.id = lot;
entry.name = tableData.getStringField("name", ""); entry.name = tableData.getStringField("name", "");
UNUSED(entry.placeable = tableData.getIntField("placeable", -1)); UNUSED(entry.placeable = tableData.getIntField("placeable", -1));
entry.type = tableData.getStringField("type", ""); entry.type = tableData.getStringField("type", "");
@@ -79,17 +80,15 @@ const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) {
UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.gate_version = tableData.getStringField("gate_version", ""));
UNUSED(entry.HQ_valid = tableData.getIntField("HQ_valid", -1)); UNUSED(entry.HQ_valid = tableData.getIntField("HQ_valid", -1));
entries.insert(std::make_pair(entry.id, entry));
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize(); tableData.finalize();
const auto& it2 = entries.find(LOT); const auto& it2 = entries.find(lot);
if (it2 != entries.end()) { if (it2 != entries.end()) {
return it2->second; return it2->second;
} }
return m_default; return ObjDefault;
} }

View File

@@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDObjects { struct CDObjects {
uint32_t id; //!< The LOT of the object uint32_t id; //!< The LOT of the object
std::string name; //!< The internal name of the object std::string name; //!< The internal name of the object
@@ -24,6 +26,6 @@ class CDObjectsTable : public CDTable<CDObjectsTable, std::map<uint32_t, CDObjec
public: public:
void LoadValuesFromDatabase(); void LoadValuesFromDatabase();
// Gets an entry by ID // Gets an entry by ID
const CDObjects& GetByID(uint32_t LOT); const CDObjects& GetByID(const uint32_t lot);
}; };

View File

@@ -19,12 +19,11 @@ void CDPackageComponentTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PackageComponent"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PackageComponent");
while (!tableData.eof()) { while (!tableData.eof()) {
CDPackageComponent entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1);
entry.packageType = tableData.getIntField("packageType", -1); entry.packageType = tableData.getIntField("packageType", -1);
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }

View File

@@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDPackageComponent { struct CDPackageComponent {
uint32_t id; uint32_t id;
uint32_t LootMatrixIndex; uint32_t LootMatrixIndex;

View File

@@ -57,7 +57,7 @@ CDPetComponent& CDPetComponentTable::GetByID(const uint32_t componentID) {
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
auto itr = entries.find(componentID); auto itr = entries.find(componentID);
if (itr == entries.end()) { 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 defaultEntry;
} }
return itr->second; return itr->second;

View File

@@ -4,32 +4,31 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() {
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent");
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
while (!tableData.eof()) { while (!tableData.eof()) {
CDPhysicsComponent entry; const uint32_t componentID = tableData.getIntField("id", -1);
entry.id = tableData.getIntField("id", -1);
auto& entry = entries[componentID];
entry.id = componentID;
entry.bStatic = tableData.getIntField("static", -1) != 0; entry.bStatic = tableData.getIntField("static", -1) != 0;
entry.physicsAsset = tableData.getStringField("physics_asset", ""); entry.physicsAsset = tableData.getStringField("physics_asset", "");
UNUSED(entry->jump = tableData.getIntField("jump", -1) != 0); UNUSED_COLUMN(entry.jump = tableData.getIntField("jump", -1) != 0;)
UNUSED(entry->doublejump = tableData.getIntField("doublejump", -1) != 0); UNUSED_COLUMN(entry.doubleJump = tableData.getIntField("doublejump", -1) != 0;)
entry.speed = tableData.getFloatField("speed", -1); entry.speed = static_cast<float>(tableData.getFloatField("speed", -1));
UNUSED(entry->rotSpeed = tableData.getFloatField("rotSpeed", -1)); UNUSED_COLUMN(entry.rotSpeed = tableData.getFloatField("rotSpeed", -1);)
entry.playerHeight = tableData.getFloatField("playerHeight"); entry.playerHeight = static_cast<float>(tableData.getFloatField("playerHeight"));
entry.playerRadius = tableData.getFloatField("playerRadius"); entry.playerRadius = static_cast<float>(tableData.getFloatField("playerRadius"));
entry.pcShapeType = tableData.getIntField("pcShapeType"); entry.pcShapeType = tableData.getIntField("pcShapeType");
entry.collisionGroup = tableData.getIntField("collisionGroup"); entry.collisionGroup = tableData.getIntField("collisionGroup");
UNUSED(entry->airSpeed = tableData.getFloatField("airSpeed")); UNUSED_COLUMN(entry.airSpeed = tableData.getFloatField("airSpeed");)
UNUSED(entry->boundaryAsset = tableData.getStringField("boundaryAsset")); UNUSED_COLUMN(entry.boundaryAsset = tableData.getStringField("boundaryAsset");)
UNUSED(entry->jumpAirSpeed = tableData.getFloatField("jumpAirSpeed")); UNUSED_COLUMN(entry.jumpAirSpeed = tableData.getFloatField("jumpAirSpeed");)
UNUSED(entry->friction = tableData.getFloatField("friction")); UNUSED_COLUMN(entry.friction = tableData.getFloatField("friction");)
UNUSED(entry->gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset")); UNUSED_COLUMN(entry.gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset");)
entries.insert(std::make_pair(entry.id, entry));
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
CDPhysicsComponent* CDPhysicsComponentTable::GetByID(uint32_t componentID) { CDPhysicsComponent* CDPhysicsComponentTable::GetByID(const uint32_t componentID) {
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
auto itr = entries.find(componentID); auto itr = entries.find(componentID);
return itr != entries.end() ? &itr->second : nullptr; return itr != entries.end() ? &itr->second : nullptr;

View File

@@ -1,5 +1,6 @@
#pragma once #pragma once
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
#include <string> #include <string>
struct CDPhysicsComponent { struct CDPhysicsComponent {
@@ -7,7 +8,7 @@ struct CDPhysicsComponent {
bool bStatic; bool bStatic;
std::string physicsAsset; std::string physicsAsset;
UNUSED(bool jump); UNUSED(bool jump);
UNUSED(bool doublejump); UNUSED(bool doubleJump);
float speed; float speed;
UNUSED(float rotSpeed); UNUSED(float rotSpeed);
float playerHeight; float playerHeight;
@@ -26,5 +27,5 @@ public:
void LoadValuesFromDatabase(); void LoadValuesFromDatabase();
static const std::string GetTableName() { return "PhysicsComponent"; }; static const std::string GetTableName() { return "PhysicsComponent"; };
CDPhysicsComponent* GetByID(uint32_t componentID); CDPhysicsComponent* GetByID(const uint32_t componentID);
}; };

View File

@@ -15,7 +15,7 @@ target_include_directories(dDatabaseCDClient PUBLIC "."
"${PROJECT_SOURCE_DIR}/dCommon" "${PROJECT_SOURCE_DIR}/dCommon"
"${PROJECT_SOURCE_DIR}/dCommon/dEnums" "${PROJECT_SOURCE_DIR}/dCommon/dEnums"
) )
target_link_libraries(dDatabaseCDClient PRIVATE sqlite3) target_link_libraries(dDatabaseCDClient PRIVATE fmt sqlite3)
if (${CDCLIENT_CACHE_ALL}) if (${CDCLIENT_CACHE_ALL})
add_compile_definitions(dDatabaseCDClient PRIVATE CDCLIENT_CACHE_ALL=${CDCLIENT_CACHE_ALL}) add_compile_definitions(dDatabaseCDClient PRIVATE CDCLIENT_CACHE_ALL=${CDCLIENT_CACHE_ALL})

View File

@@ -4,4 +4,5 @@ add_subdirectory(GameDatabase)
add_library(dDatabase STATIC "MigrationRunner.cpp") add_library(dDatabase STATIC "MigrationRunner.cpp")
target_include_directories(dDatabase PUBLIC ".") target_include_directories(dDatabase PUBLIC ".")
target_link_libraries(dDatabase target_link_libraries(dDatabase
PUBLIC dDatabaseCDClient dDatabaseGame) PUBLIC dDatabaseCDClient dDatabaseGame
PRIVATE fmt)

View File

@@ -16,6 +16,7 @@ target_include_directories(dDatabaseGame PUBLIC "."
) )
target_link_libraries(dDatabaseGame target_link_libraries(dDatabaseGame
PUBLIC MariaDB::ConnCpp PUBLIC MariaDB::ConnCpp
PRIVATE fmt
INTERFACE dCommon) INTERFACE dCommon)
# Glob together all headers that need to be precompiled # Glob together all headers that need to be precompiled

View File

@@ -13,7 +13,7 @@ namespace {
void Database::Connect() { void Database::Connect() {
if (database) { if (database) {
LOG("Tried to connect to database when it's already connected!"); Log::Warn("Tried to connect to database when it's already connected!");
return; return;
} }
@@ -23,7 +23,7 @@ void Database::Connect() {
GameDatabase* Database::Get() { GameDatabase* Database::Get() {
if (!database) { if (!database) {
LOG("Tried to get database when it's not connected!"); Log::Warn("Tried to get database when it's not connected!");
Connect(); Connect();
} }
return database; return database;
@@ -35,6 +35,6 @@ void Database::Destroy(std::string source) {
delete database; delete database;
database = nullptr; database = nullptr;
} else { } else {
LOG("Trying to destroy database when it's not connected!"); Log::Warn("Trying to destroy database when it's not connected!");
} }
} }

View File

@@ -30,7 +30,7 @@ namespace sql {
}; };
#ifdef _DEBUG #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 #else
# define DLU_SQL_TRY_CATCH_RETHROW(x) x # define DLU_SQL_TRY_CATCH_RETHROW(x) x
#endif // _DEBUG #endif // _DEBUG

View File

@@ -53,8 +53,8 @@ void MySQLDatabase::Connect() {
void MySQLDatabase::Destroy(std::string source) { void MySQLDatabase::Destroy(std::string source) {
if (!con) return; if (!con) return;
if (source.empty()) LOG("Destroying MySQL connection!"); if (source.empty()) Log::Info("Destroying MySQL connection!");
else LOG("Destroying MySQL connection from %s!", source.c_str()); else Log::Info("Destroying MySQL connection from {:s}!", source);
con->close(); con->close();
delete con; delete con;
@@ -68,7 +68,7 @@ void MySQLDatabase::ExecuteCustomQuery(const std::string_view query) {
sql::PreparedStatement* MySQLDatabase::CreatePreppedStmt(const std::string& query) { sql::PreparedStatement* MySQLDatabase::CreatePreppedStmt(const std::string& query) {
if (!con) { if (!con) {
Connect(); Connect();
LOG("Trying to reconnect to MySQL"); Log::Info("Trying to reconnect to MySQL");
} }
if (!con->isValid() || con->isClosed()) { if (!con->isValid() || con->isClosed()) {
@@ -77,7 +77,7 @@ sql::PreparedStatement* MySQLDatabase::CreatePreppedStmt(const std::string& quer
con = nullptr; con = nullptr;
Connect(); 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())); return con->prepareStatement(sql::SQLString(query.c_str(), query.length()));

View File

@@ -147,91 +147,91 @@ private:
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::string_view param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::string_view param) {
// LOG("%s", param.data()); // Log::Info("{}", param);
stmt->setString(index, param.data()); stmt->setString(index, param.data());
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const char* param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const char* param) {
// LOG("%s", param); // Log::Info("{}", param);
stmt->setString(index, param); stmt->setString(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::string param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::string param) {
// LOG("%s", param.c_str()); // Log::Info("{}", param);
stmt->setString(index, param.c_str()); stmt->setString(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int8_t param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int8_t param) {
// LOG("%u", param); // Log::Info("{}", param);
stmt->setByte(index, param); stmt->setByte(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint8_t param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint8_t param) {
// LOG("%d", param); // Log::Info("{}", param);
stmt->setByte(index, param); stmt->setByte(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int16_t param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int16_t param) {
// LOG("%u", param); // Log::Info("{}", param);
stmt->setShort(index, param); stmt->setShort(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint16_t param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint16_t param) {
// LOG("%d", param); // Log::Info("{}", param);
stmt->setShort(index, param); stmt->setShort(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint32_t param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint32_t param) {
// LOG("%u", param); // Log::Info("{}", param);
stmt->setUInt(index, param); stmt->setUInt(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int32_t param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int32_t param) {
// LOG("%d", param); // Log::Info("{}", param);
stmt->setInt(index, param); stmt->setInt(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int64_t param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int64_t param) {
// LOG("%llu", param); // Log::Info("{}", param);
stmt->setInt64(index, param); stmt->setInt64(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint64_t param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint64_t param) {
// LOG("%llu", param); // Log::Info("{}", param);
stmt->setUInt64(index, param); stmt->setUInt64(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const float param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const float param) {
// LOG("%f", param); // Log::Info({}", param);
stmt->setFloat(index, param); stmt->setFloat(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const double param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const double param) {
// LOG("%f", param); // Log::Info("{}", param);
stmt->setDouble(index, param); stmt->setDouble(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const bool param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const bool param) {
// LOG("%d", param); // Log::Info("{}", param);
stmt->setBoolean(index, param); stmt->setBoolean(index, param);
} }
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::istream* param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::istream* param) {
// LOG("Blob"); // Log::Info("Blob");
// This is the one time you will ever see me use const_cast. // This is the one time you will ever see me use const_cast.
stmt->setBlob(index, const_cast<std::istream*>(param)); stmt->setBlob(index, const_cast<std::istream*>(param));
} }
@@ -239,10 +239,10 @@ inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::istr
template<> template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::optional<uint32_t> param) { inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::optional<uint32_t> param) {
if (param) { if (param) {
// LOG("%d", param.value()); // Log::Info("{}", param.value());
stmt->setInt(index, param.value()); stmt->setInt(index, param.value());
} else { } else {
// LOG("Null"); // Log::Info("Null");
stmt->setNull(index, sql::DataType::SQLNULL); stmt->setNull(index, sql::DataType::SQLNULL);
} }
} }

View File

@@ -38,8 +38,8 @@ void MySQLDatabase::InsertNewPropertyModel(const LWOOBJID& propertyId, const IPr
0, // behavior 4. TODO implement this. 0, // behavior 4. TODO implement this.
0 // behavior 5. TODO implement this. 0 // behavior 5. TODO implement this.
); );
} catch (sql::SQLException& e) { } catch (const sql::SQLException& e) {
LOG("Error inserting new property model: %s", e.what()); Log::Warn("Error inserting new property model: {:s}", e.what());
} }
} }

View File

@@ -45,7 +45,7 @@ void MigrationRunner::RunMigrations() {
if (Database::Get()->IsMigrationRun(migration.name)) continue; 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") { if (migration.name == "dlu/5_brick_model_sd0.sql") {
runSd0Migrations = true; runSd0Migrations = true;
} else { } else {
@@ -56,7 +56,7 @@ void MigrationRunner::RunMigrations() {
} }
if (finalSQL.empty() && !runSd0Migrations) { if (finalSQL.empty() && !runSd0Migrations) {
LOG("Server database is up to date."); Log::Info("Server database is up to date.");
return; return;
} }
@@ -67,7 +67,7 @@ void MigrationRunner::RunMigrations() {
if (query.empty()) continue; if (query.empty()) continue;
Database::Get()->ExecuteCustomQuery(query.c_str()); Database::Get()->ExecuteCustomQuery(query.c_str());
} catch (sql::SQLException& e) { } 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. // Do this last on the off chance none of the other migrations have been run yet.
if (runSd0Migrations) { if (runSd0Migrations) {
uint32_t numberOfUpdatedModels = BrickByBrickFix::UpdateBrickByBrickModelsToSd0(); 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(); 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. // 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". // 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;"); CDClientDatabase::ExecuteQuery("BEGIN TRANSACTION;");
for (const auto& dml : GeneralUtils::SplitString(migration.data, ';')) { for (const auto& dml : GeneralUtils::SplitString(migration.data, ';')) {
if (dml.empty()) continue; if (dml.empty()) continue;
try { try {
CDClientDatabase::ExecuteDML(dml.c_str()); CDClientDatabase::ExecuteDML(dml.c_str());
} catch (CppSQLite3Exception& e) { } 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;"); CDClientDatabase::ExecuteQuery("COMMIT;");
} }
LOG("CDServer database is up to date."); Log::Info("CDServer database is up to date.");
} }

View File

@@ -82,16 +82,16 @@ void Character::DoQuickXMLDataParse() {
if (!m_Doc) return; if (!m_Doc) return;
if (m_Doc->Parse(m_XMLData.c_str(), m_XMLData.size()) == 0) { 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 { } else {
LOG("Failed to load xmlData!"); Log::Warn("Failed to load xmlData!");
//Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true); //Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true);
return; return;
} }
tinyxml2::XMLElement* mf = m_Doc->FirstChildElement("obj")->FirstChildElement("mf"); tinyxml2::XMLElement* mf = m_Doc->FirstChildElement("obj")->FirstChildElement("mf");
if (!mf) { if (!mf) {
LOG("Failed to find mf tag!"); Log::Warn("Failed to find mf tag!");
return; return;
} }
@@ -110,14 +110,14 @@ void Character::DoQuickXMLDataParse() {
tinyxml2::XMLElement* inv = m_Doc->FirstChildElement("obj")->FirstChildElement("inv"); tinyxml2::XMLElement* inv = m_Doc->FirstChildElement("obj")->FirstChildElement("inv");
if (!inv) { if (!inv) {
LOG("Char has no inv!"); Log::Warn("Char has no inv!");
return; return;
} }
tinyxml2::XMLElement* bag = inv->FirstChildElement("items")->FirstChildElement("in"); tinyxml2::XMLElement* bag = inv->FirstChildElement("items")->FirstChildElement("in");
if (!bag) { if (!bag) {
LOG("Couldn't find bag0!"); Log::Warn("Couldn't find bag0!");
return; return;
} }
@@ -310,7 +310,7 @@ void Character::SaveXMLToDatabase() {
//Call upon the entity to update our xmlDoc: //Call upon the entity to update our xmlDoc:
if (!m_OurEntity) { 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; return;
} }
@@ -321,7 +321,7 @@ void Character::SaveXMLToDatabase() {
//For metrics, log the time it took to save: //For metrics, log the time it took to save:
auto end = std::chrono::system_clock::now(); auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed = end - start; std::chrono::duration<double> 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() { void Character::SetIsNewLogin() {
@@ -334,7 +334,7 @@ void Character::SetIsNewLogin() {
auto* nextChild = currentChild->NextSiblingElement(); auto* nextChild = currentChild->NextSiblingElement();
if (currentChild->Attribute("si")) { if (currentChild->Attribute("si")) {
flags->DeleteChild(currentChild); 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(); WriteToDatabase();
} }
currentChild = nextChild; currentChild = nextChild;

View File

@@ -138,25 +138,23 @@ Entity::Entity(const LWOOBJID& objectID, EntityInfo info, User* parentUser, Enti
Entity::~Entity() { Entity::~Entity() {
if (IsPlayer()) { if (IsPlayer()) {
LOG("Deleted player"); Log::Info("Deleted player");
// Make sure the player exists first. Remove afterwards to prevent the OnPlayerExist functions from not being able to find the player. // Make sure the player exists first. Remove afterwards to prevent the OnPlayerExist functions from not being able to find the player.
if (!PlayerManager::RemovePlayer(this)) { if (!PlayerManager::RemovePlayer(this)) {
LOG("Unable to find player to remove from manager."); Log::Warn("Unable to find player to remove from manager.");
return; return;
} }
Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); auto* zoneControl = Game::entityManager->GetZoneControlEntity();
for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { if (zoneControl) {
script->OnPlayerExit(zoneControl, this); zoneControl->GetScript()->OnPlayerExit(zoneControl, this);
} }
std::vector<Entity*> scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); std::vector<Entity*> scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY);
for (Entity* scriptEntity : scriptedActs) { for (Entity* scriptEntity : scriptedActs) {
if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds
for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { scriptEntity->GetScript()->OnPlayerExit(scriptEntity, this);
script->OnPlayerExit(scriptEntity, this);
}
} }
} }
} }
@@ -762,9 +760,7 @@ void Entity::Initialize() {
// Hacky way to trigger these when the object has had a chance to get constructed // Hacky way to trigger these when the object has had a chance to get constructed
AddCallbackTimer(0, [this]() { AddCallbackTimer(0, [this]() {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { this->GetScript()->OnStartup(this);
script->OnStartup(this);
}
}); });
if (!m_Character && Game::entityManager->GetGhostingEnabled()) { if (!m_Character && Game::entityManager->GetGhostingEnabled()) {
@@ -839,15 +835,6 @@ bool Entity::HasComponent(const eReplicaComponentType componentId) const {
return m_Components.find(componentId) != m_Components.end(); return m_Components.find(componentId) != m_Components.end();
} }
std::vector<ScriptComponent*> Entity::GetScriptComponents() {
std::vector<ScriptComponent*> comps;
auto* scriptComponent = GetComponent<ScriptComponent>();
if (scriptComponent) comps.push_back(scriptComponent);
return comps;
}
void Entity::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName) { void Entity::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName) {
if (notificationName == "HitOrHealResult" || notificationName == "Hit") { if (notificationName == "HitOrHealResult" || notificationName == "Hit") {
auto* destroyableComponent = GetComponent<DestroyableComponent>(); auto* destroyableComponent = GetComponent<DestroyableComponent>();
@@ -1276,9 +1263,7 @@ void Entity::Update(const float deltaTime) {
// Remove the timer from the list of timers first so that scripts and events can remove timers without causing iterator invalidation // Remove the timer from the list of timers first so that scripts and events can remove timers without causing iterator invalidation
auto timerName = timer.GetName(); auto timerName = timer.GetName();
m_Timers.erase(m_Timers.begin() + timerPosition); m_Timers.erase(m_Timers.begin() + timerPosition);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnTimerDone(this, timerName);
script->OnTimerDone(this, timerName);
}
TriggerEvent(eTriggerEventType::TIMER_DONE, this); TriggerEvent(eTriggerEventType::TIMER_DONE, this);
} else { } else {
@@ -1324,9 +1309,7 @@ void Entity::Update(const float deltaTime) {
Wake(); Wake();
} }
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnUpdate(this);
script->OnUpdate(this);
}
for (const auto& pair : m_Components) { for (const auto& pair : m_Components) {
if (pair.second == nullptr) continue; if (pair.second == nullptr) continue;
@@ -1343,9 +1326,7 @@ void Entity::OnCollisionProximity(LWOOBJID otherEntity, const std::string& proxN
Entity* other = Game::entityManager->GetEntity(otherEntity); Entity* other = Game::entityManager->GetEntity(otherEntity);
if (!other) return; if (!other) return;
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnProximityUpdate(this, other, proxName, status);
script->OnProximityUpdate(this, other, proxName, status);
}
RocketLaunchpadControlComponent* rocketComp = GetComponent<RocketLaunchpadControlComponent>(); RocketLaunchpadControlComponent* rocketComp = GetComponent<RocketLaunchpadControlComponent>();
if (!rocketComp) return; if (!rocketComp) return;
@@ -1357,9 +1338,7 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) {
auto* other = Game::entityManager->GetEntity(otherEntity); auto* other = Game::entityManager->GetEntity(otherEntity);
if (!other) return; if (!other) return;
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnCollisionPhantom(this, other);
script->OnCollisionPhantom(this, other);
}
for (const auto& callback : m_PhantomCollisionCallbacks) { for (const auto& callback : m_PhantomCollisionCallbacks) {
callback(other); callback(other);
@@ -1398,9 +1377,7 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) {
auto* other = Game::entityManager->GetEntity(otherEntity); auto* other = Game::entityManager->GetEntity(otherEntity);
if (!other) return; if (!other) return;
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnOffCollisionPhantom(this, other);
script->OnOffCollisionPhantom(this, other);
}
TriggerEvent(eTriggerEventType::EXIT, other); TriggerEvent(eTriggerEventType::EXIT, other);
@@ -1417,46 +1394,32 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) {
} }
void Entity::OnFireEventServerSide(Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { void Entity::OnFireEventServerSide(Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnFireEventServerSide(this, sender, args, param1, param2, param3);
script->OnFireEventServerSide(this, sender, args, param1, param2, param3);
}
} }
void Entity::OnActivityStateChangeRequest(LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) { void Entity::OnActivityStateChangeRequest(LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue);
script->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue);
}
} }
void Entity::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, void Entity::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName,
float_t pathTime, float_t totalTime, int32_t waypoint) { float_t pathTime, float_t totalTime, int32_t waypoint) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint);
script->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint);
}
} }
void Entity::NotifyObject(Entity* sender, const std::string& name, int32_t param1, int32_t param2) { void Entity::NotifyObject(Entity* sender, const std::string& name, int32_t param1, int32_t param2) {
GameMessages::SendNotifyObject(GetObjectID(), sender->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendNotifyObject(GetObjectID(), sender->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnNotifyObject(this, sender, name, param1, param2);
script->OnNotifyObject(this, sender, name, param1, param2);
}
} }
void Entity::OnEmoteReceived(const int32_t emote, Entity* target) { void Entity::OnEmoteReceived(const int32_t emote, Entity* target) {
for (auto* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnEmoteReceived(this, emote, target);
script->OnEmoteReceived(this, emote, target);
}
} }
void Entity::OnUse(Entity* originator) { void Entity::OnUse(Entity* originator) {
TriggerEvent(eTriggerEventType::INTERACT, originator); TriggerEvent(eTriggerEventType::INTERACT, originator);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnUse(this, originator);
script->OnUse(this, originator);
}
// component base class when
for (const auto& pair : m_Components) { for (const auto& pair : m_Components) {
if (pair.second == nullptr) continue; if (pair.second == nullptr) continue;
@@ -1466,82 +1429,63 @@ void Entity::OnUse(Entity* originator) {
} }
void Entity::OnHitOrHealResult(Entity* attacker, int32_t damage) { void Entity::OnHitOrHealResult(Entity* attacker, int32_t damage) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnHitOrHealResult(this, attacker, damage);
script->OnHitOrHealResult(this, attacker, damage);
}
} }
void Entity::OnHit(Entity* attacker) { void Entity::OnHit(Entity* attacker) {
TriggerEvent(eTriggerEventType::HIT, attacker); TriggerEvent(eTriggerEventType::HIT, attacker);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnHit(this, attacker);
script->OnHit(this, attacker);
}
} }
void Entity::OnZonePropertyEditBegin() { void Entity::OnZonePropertyEditBegin() {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyEditBegin(this);
script->OnZonePropertyEditBegin(this);
}
} }
void Entity::OnZonePropertyEditEnd() { void Entity::OnZonePropertyEditEnd() {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyEditEnd(this);
script->OnZonePropertyEditEnd(this);
}
} }
void Entity::OnZonePropertyModelEquipped() { void Entity::OnZonePropertyModelEquipped() {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelEquipped(this);
script->OnZonePropertyModelEquipped(this);
}
} }
void Entity::OnZonePropertyModelPlaced(Entity* player) { void Entity::OnZonePropertyModelPlaced(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelPlaced(this, player);
script->OnZonePropertyModelPlaced(this, player);
}
} }
void Entity::OnZonePropertyModelPickedUp(Entity* player) { void Entity::OnZonePropertyModelPickedUp(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelPickedUp(this, player);
script->OnZonePropertyModelPickedUp(this, player);
}
} }
void Entity::OnZonePropertyModelRemoved(Entity* player) { void Entity::OnZonePropertyModelRemoved(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelRemoved(this, player);
script->OnZonePropertyModelRemoved(this, player);
}
} }
void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) { void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelRemovedWhileEquipped(this, player);
script->OnZonePropertyModelRemovedWhileEquipped(this, player);
}
} }
void Entity::OnZonePropertyModelRotated(Entity* player) { void Entity::OnZonePropertyModelRotated(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelRotated(this, player);
script->OnZonePropertyModelRotated(this, player);
}
} }
void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnMessageBoxResponse(this, sender, button, identifier, userData);
script->OnMessageBoxResponse(this, sender, button, identifier, userData);
}
} }
void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier);
script->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier);
}
} }
void Entity::RequestActivityExit(Entity* sender, LWOOBJID player, bool canceled) { void Entity::RequestActivityExit(Entity* sender, LWOOBJID player, bool canceled) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnRequestActivityExit(sender, player, canceled);
script->OnRequestActivityExit(sender, player, canceled); }
}
CppScripts::Script* const Entity::GetScript() {
auto* scriptComponent = GetComponent<ScriptComponent>();
auto* script = scriptComponent ? scriptComponent->GetScript() : CppScripts::GetInvalidScript();
DluAssert(script != nullptr);
return script;
} }
void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType) { void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType) {
@@ -1574,9 +1518,7 @@ void Entity::Kill(Entity* murderer, const eKillType killType) {
//OMAI WA MOU, SHINDERIU //OMAI WA MOU, SHINDERIU
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnDie(this, murderer);
script->OnDie(this, murderer);
}
if (m_Spawner != nullptr) { if (m_Spawner != nullptr) {
m_Spawner->NotifyOfEntityDeath(m_ObjectID); m_Spawner->NotifyOfEntityDeath(m_ObjectID);

View File

@@ -146,7 +146,8 @@ public:
void AddComponent(eReplicaComponentType componentId, Component* component); void AddComponent(eReplicaComponentType componentId, Component* component);
std::vector<ScriptComponent*> GetScriptComponents(); // This is expceted to never return nullptr, an assert checks this.
CppScripts::Script* const GetScript();
void Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName); void Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName);
void Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName); void Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName);

View File

@@ -201,7 +201,7 @@ void EntityManager::KillEntities() {
auto* entity = GetEntity(toKill); auto* entity = GetEntity(toKill);
if (!entity) { if (!entity) {
LOG("Attempting to kill null entity %llu", toKill); Log::Warn("Attempting to kill null entity {}", toKill);
continue; continue;
} }
@@ -231,7 +231,7 @@ void EntityManager::DeleteEntities() {
if (ghostingToDelete != m_EntitiesToGhost.end()) m_EntitiesToGhost.erase(ghostingToDelete); if (ghostingToDelete != m_EntitiesToGhost.end()) m_EntitiesToGhost.erase(ghostingToDelete);
} else { } else {
LOG("Attempted to delete non-existent entity %llu", toDelete); Log::Warn("Attempted to delete non-existent entity {}", toDelete);
} }
m_Entities.erase(toDelete); m_Entities.erase(toDelete);
} }
@@ -322,7 +322,7 @@ const std::unordered_map<std::string, LWOOBJID>& EntityManager::GetSpawnPointEnt
void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr, const bool skipChecks) { void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr, const bool skipChecks) {
if (!entity) { if (!entity) {
LOG("Attempted to construct null entity"); Log::Warn("Attempted to construct null entity");
return; return;
} }
@@ -418,10 +418,16 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr)
} }
void EntityManager::SerializeEntity(Entity* entity) { void EntityManager::SerializeEntity(Entity* entity) {
if (!entity || entity->GetNetworkId() == 0) return; if (!entity) return;
EntityManager::SerializeEntity(*entity);
}
if (std::find(m_EntitiesToSerialize.begin(), m_EntitiesToSerialize.end(), entity->GetObjectID()) == m_EntitiesToSerialize.end()) { void EntityManager::SerializeEntity(const Entity& entity) {
m_EntitiesToSerialize.push_back(entity->GetObjectID()); if (entity.GetNetworkId() == 0) return;
if (std::find(m_EntitiesToSerialize.cbegin(), m_EntitiesToSerialize.cend(), entity.GetObjectID()) == m_EntitiesToSerialize.cend()) {
m_EntitiesToSerialize.push_back(entity.GetObjectID());
} }
} }

View File

@@ -45,6 +45,7 @@ public:
void ConstructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, bool skipChecks = false); void ConstructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, bool skipChecks = false);
void DestructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void DestructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS);
void SerializeEntity(Entity* entity); void SerializeEntity(Entity* entity);
void SerializeEntity(const Entity& entity);
void ConstructAllEntities(const SystemAddress& sysAddr); void ConstructAllEntities(const SystemAddress& sysAddr);
void DestructAllEntities(const SystemAddress& sysAddr); void DestructAllEntities(const SystemAddress& sysAddr);

View File

@@ -236,7 +236,7 @@ void Leaderboard::SetupLeaderboard(bool weekly, uint32_t resultStart, uint32_t r
baseLookup += std::to_string(static_cast<uint32_t>(this->relatedPlayer)); baseLookup += std::to_string(static_cast<uint32_t>(this->relatedPlayer));
} }
baseLookup += " LIMIT 1"; baseLookup += " LIMIT 1";
LOG_DEBUG("query is %s", baseLookup.c_str()); Log::Debug("query is {:s}", baseLookup);
std::unique_ptr<sql::PreparedStatement> baseQuery(Database::Get()->CreatePreppedStmt(baseLookup)); std::unique_ptr<sql::PreparedStatement> baseQuery(Database::Get()->CreatePreppedStmt(baseLookup));
baseQuery->setInt(1, this->gameID); baseQuery->setInt(1, this->gameID);
std::unique_ptr<sql::ResultSet> baseResult(baseQuery->executeQuery()); std::unique_ptr<sql::ResultSet> 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); int32_t res = snprintf(lookupBuffer.get(), STRING_LENGTH, queryBase.c_str(), orderBase.data(), filter.c_str(), resultStart, resultEnd);
DluAssert(res != -1); DluAssert(res != -1);
std::unique_ptr<sql::PreparedStatement> query(Database::Get()->CreatePreppedStmt(lookupBuffer.get())); std::unique_ptr<sql::PreparedStatement> 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); query->setInt(1, this->gameID);
if (this->infoType == InfoType::Friends) { if (this->infoType == InfoType::Friends) {
query->setInt(2, this->relatedPlayer); query->setInt(2, this->relatedPlayer);
@@ -358,7 +358,7 @@ void LeaderboardManager::SaveScore(const LWOOBJID& playerID, const GameID activi
} }
case Leaderboard::Type::None: case Leaderboard::Type::None:
default: 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; return;
} }
bool newHighScore = lowerScoreBetter ? newScore < oldScore : newScore > oldScore; bool newHighScore = lowerScoreBetter ? newScore < oldScore : newScore > oldScore;
@@ -377,7 +377,7 @@ void LeaderboardManager::SaveScore(const LWOOBJID& playerID, const GameID activi
} else { } else {
saveQuery = FormatInsert(leaderboardType, newScore, false); 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<sql::PreparedStatement> saveStatement(Database::Get()->CreatePreppedStmt(saveQuery)); std::unique_ptr<sql::PreparedStatement> saveStatement(Database::Get()->CreatePreppedStmt(saveQuery));
saveStatement->setInt(1, playerID); saveStatement->setInt(1, playerID);
saveStatement->setInt(2, activityId); saveStatement->setInt(2, activityId);

View File

@@ -67,7 +67,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) {
if (participant == m_ParticipantA) { if (participant == m_ParticipantA) {
m_AcceptedA = !value; m_AcceptedA = !value;
LOG("Accepted from A (%d), B: (%d)", value, m_AcceptedB); Log::Info("Accepted from A ({}), B: ({})", value, m_AcceptedB);
auto* entityB = GetParticipantBEntity(); auto* entityB = GetParticipantBEntity();
@@ -77,7 +77,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) {
} else if (participant == m_ParticipantB) { } else if (participant == m_ParticipantB) {
m_AcceptedB = !value; m_AcceptedB = !value;
LOG("Accepted from B (%d), A: (%d)", value, m_AcceptedA); Log::Info("Accepted from B ({}), A: ({})", value, m_AcceptedA);
auto* entityA = GetParticipantAEntity(); auto* entityA = GetParticipantAEntity();
@@ -125,7 +125,7 @@ void Trade::Complete() {
// First verify both players have the coins and items requested for the trade. // First verify both players have the coins and items requested for the trade.
if (characterA->GetCoins() < m_CoinsA || characterB->GetCoins() < m_CoinsB) { 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; return;
} }
@@ -133,11 +133,11 @@ void Trade::Complete() {
auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId); auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId);
if (itemToRemove) { if (itemToRemove) {
if (itemToRemove->GetCount() < tradeItem.itemCount) { 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; return;
} }
} else { } 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; return;
} }
} }
@@ -146,11 +146,11 @@ void Trade::Complete() {
auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId); auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId);
if (itemToRemove) { if (itemToRemove) {
if (itemToRemove->GetCount() < tradeItem.itemCount) { 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; return;
} }
} else { } 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; return;
} }
} }
@@ -194,7 +194,7 @@ void Trade::SendUpdateToOther(LWOOBJID participant) {
uint64_t coins; uint64_t coins;
std::vector<TradeItem> itemIds; std::vector<TradeItem> itemIds;
LOG("Attempting to send trade update"); Log::Info("Attempting to send trade update");
if (participant == m_ParticipantA) { if (participant == m_ParticipantA) {
other = GetParticipantBEntity(); other = GetParticipantBEntity();
@@ -228,7 +228,7 @@ void Trade::SendUpdateToOther(LWOOBJID participant) {
items.push_back(tradeItem); items.push_back(tradeItem);
} }
LOG("Sending trade update"); Log::Info("Sending trade update");
GameMessages::SendServerTradeUpdate(other->GetObjectID(), coins, items, other->GetSystemAddress()); GameMessages::SendServerTradeUpdate(other->GetObjectID(), coins, items, other->GetSystemAddress());
} }
@@ -281,7 +281,7 @@ Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) {
trades[tradeId] = trade; trades[tradeId] = trade;
LOG("Created new trade between (%llu) <-> (%llu)", participantA, participantB); Log::Info("Created new trade between ({}) <-> ({})", participantA, participantB);
return trade; return trade;
} }

View File

@@ -38,7 +38,7 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std:
Character* character = new Character(lastUsedCharacterId, this); Character* character = new Character(lastUsedCharacterId, this);
character->UpdateFromDatabase(); character->UpdateFromDatabase();
m_Characters.push_back(character); 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++; m_AmountOfTimesOutOfSync++;
if (m_AmountOfTimesOutOfSync > m_MaxDesyncAllowed) { if (m_AmountOfTimesOutOfSync > m_MaxDesyncAllowed) {
//YEET //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); Game::server->Disconnect(this->m_SystemAddress, eServerDisconnectIdentifiers::PLAY_SCHEDULE_TIME_DONE);
} }
} }

View File

@@ -45,7 +45,7 @@ void UserManager::Initialize() {
auto fnStream = Game::assetManager->GetFile("names/minifigname_first.txt"); auto fnStream = Game::assetManager->GetFile("names/minifigname_first.txt");
if (!fnStream) { 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."); 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"); auto mnStream = Game::assetManager->GetFile("names/minifigname_middle.txt");
if (!mnStream) { 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."); 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"); auto lnStream = Game::assetManager->GetFile("names/minifigname_last.txt");
if (!lnStream) { 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."); throw std::runtime_error("Aborting initialization due to missing minifigure name file.");
} }
@@ -82,7 +82,7 @@ void UserManager::Initialize() {
// Load our pre-approved names: // Load our pre-approved names:
auto chatListStream = Game::assetManager->GetFile("chatplus_en_us.txt"); auto chatListStream = Game::assetManager->GetFile("chatplus_en_us.txt");
if (!chatListStream) { 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."); 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() { void UserManager::DeletePendingRemovals() {
for (auto* user : m_UsersToDelete) { for (auto* user : m_UsersToDelete) {
LOG("Deleted user %i", user->GetAccountID()); Log::Info("Deleted user {:d}", user->GetAccountID());
delete user; delete user;
} }
@@ -306,27 +306,27 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet)
LOT pantsLOT = FindCharPantsID(pantsColor); LOT pantsLOT = FindCharPantsID(pantsColor);
if (!name.empty() && Database::Get()->GetCharacterInfo(name)) { 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); WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::CUSTOM_NAME_IN_USE);
return; return;
} }
if (Database::Get()->GetCharacterInfo(predefinedName)) { 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); WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::PREDEFINED_NAME_IN_USE);
return; return;
} }
if (name.empty()) { 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 { } 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: //Now that the name is ok, we can get an objectID from Master:
ObjectIDManager::RequestPersistentID([=, this](uint32_t objectID) mutable { ObjectIDManager::RequestPersistentID([=, this](uint32_t objectID) mutable {
if (Database::Get()->GetCharacterInfo(objectID)) { 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); WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::OBJECT_ID_UNAVAILABLE);
return; return;
} }
@@ -397,7 +397,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet)
void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) { void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) {
User* u = GetUser(sysAddr); User* u = GetUser(sysAddr);
if (!u) { if (!u) {
LOG("Couldn't get user to delete character"); Log::Warn("Couldn't get user to delete character");
return; return;
} }
@@ -406,7 +406,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet)
inStream.Read(objectID); inStream.Read(objectID);
uint32_t charID = static_cast<uint32_t>(objectID); uint32_t charID = static_cast<uint32_t>(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( bool hasCharacter = CheatDetection::VerifyLwoobjidIsSender(
objectID, objectID,
@@ -418,7 +418,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet)
if (!hasCharacter) { if (!hasCharacter) {
WorldPackets::SendCharacterDeleteResponse(sysAddr, false); WorldPackets::SendCharacterDeleteResponse(sysAddr, false);
} else { } else {
LOG("Deleting character %i", charID); Log::Info("Deleting character {:d}", charID);
Database::Get()->DeleteCharacter(charID); Database::Get()->DeleteCharacter(charID);
CBITSTREAM; CBITSTREAM;
@@ -433,7 +433,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet)
void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) { void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) {
User* u = GetUser(sysAddr); User* u = GetUser(sysAddr);
if (!u) { if (!u) {
LOG("Couldn't get user to delete character"); Log::Warn("Couldn't get user to delete character");
return; return;
} }
@@ -444,7 +444,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet)
GeneralUtils::ClearBit(objectID, eObjectBits::PERSISTENT); GeneralUtils::ClearBit(objectID, eObjectBits::PERSISTENT);
uint32_t charID = static_cast<uint32_t>(objectID); uint32_t charID = static_cast<uint32_t>(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; LUWString LUWStringName;
inStream.Read(LUWStringName); inStream.Read(LUWStringName);
@@ -479,12 +479,12 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet)
if (!Database::Get()->GetCharacterInfo(newName)) { if (!Database::Get()->GetCharacterInfo(newName)) {
if (IsNamePreapproved(newName)) { if (IsNamePreapproved(newName)) {
Database::Get()->SetCharacterName(charID, 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); WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::SUCCESS);
UserManager::RequestCharacterList(sysAddr); UserManager::RequestCharacterList(sysAddr);
} else { } else {
Database::Get()->SetPendingCharacterName(charID, newName); 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); WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::SUCCESS);
UserManager::RequestCharacterList(sysAddr); UserManager::RequestCharacterList(sysAddr);
} }
@@ -492,7 +492,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet)
WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::NAME_IN_USE); WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::NAME_IN_USE);
} }
} else { } 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); 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) { void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID) {
User* u = GetUser(sysAddr); User* u = GetUser(sysAddr);
if (!u) { if (!u) {
LOG("Couldn't get user to log in character"); Log::Warn("Couldn't get user to log in character");
return; return;
} }
@@ -519,7 +519,7 @@ void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID
if (zoneID == LWOZONEID_INVALID) zoneID = 1000; //Send char to VE 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) { 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) { if (character) {
character->SetZoneID(zoneID); character->SetZoneID(zoneID);
character->SetZoneInstance(zoneInstance); character->SetZoneInstance(zoneInstance);
@@ -529,7 +529,7 @@ void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID
return; return;
}); });
} else { } 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(); tableData.finalize();
return shirtLOT; return shirtLOT;
} catch (const std::exception& ex) { } 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. // in case of no shirt found in CDServer, return problematic red vest.
return 4069; return 4069;
} }
@@ -564,7 +564,7 @@ uint32_t FindCharPantsID(uint32_t pantsColor) {
tableData.finalize(); tableData.finalize();
return pantsLOT; return pantsLOT;
} catch (const std::exception& ex) { } 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. // in case of no pants color found in CDServer, return red pants.
return 2508; return 2508;
} }

View File

@@ -9,7 +9,7 @@ void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bi
uint32_t handle{}; uint32_t handle{};
if (!bitStream.Read(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; return;
} }
@@ -26,14 +26,14 @@ void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitS
uint32_t behaviorId{}; uint32_t behaviorId{};
if (!bitStream.Read(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; return;
} }
LWOOBJID target{}; LWOOBJID target{};
if (!bitStream.Read(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; return;
} }

View File

@@ -16,7 +16,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& b
uint32_t targetCount{}; uint32_t targetCount{};
if (!bitStream.Read(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; return;
} }
@@ -28,7 +28,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& b
} }
if (targetCount > this->m_maxTargets) { 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; return;
} }
@@ -41,7 +41,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& b
for (auto i = 0u; i < targetCount; ++i) { for (auto i = 0u; i < targetCount; ++i) {
LWOOBJID target{}; LWOOBJID target{};
if (!bitStream.Read(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); targets.push_back(target);
} }

View File

@@ -8,7 +8,7 @@ void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bi
uint32_t handle{}; uint32_t handle{};
if (!bitStream.Read(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; return;
}; };

View File

@@ -34,10 +34,10 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bi
uint16_t allocatedBits{}; uint16_t allocatedBits{};
if (!bitStream.Read(allocatedBits) || allocatedBits == 0) { if (!bitStream.Read(allocatedBits) || allocatedBits == 0) {
LOG_DEBUG("No allocated bits"); Log::Debug("No allocated bits");
return; return;
} }
LOG_DEBUG("Number of allocated bits %i", allocatedBits); Log::Debug("Number of allocated bits {:d}", allocatedBits);
const auto baseAddress = bitStream.GetReadOffset(); const auto baseAddress = bitStream.GetReadOffset();
DoHandleBehavior(context, bitStream, branch); 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) { void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
auto* targetEntity = Game::entityManager->GetEntity(branch.target); auto* targetEntity = Game::entityManager->GetEntity(branch.target);
if (!targetEntity) { if (!targetEntity) {
LOG("Target targetEntity %llu not found.", branch.target); Log::Warn("Target targetEntity {:d} not found.", branch.target);
return; return;
} }
auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>(); auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>();
if (!destroyableComponent) { 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; return;
} }
@@ -63,7 +63,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
bool isSuccess{}; bool isSuccess{};
if (!bitStream.Read(isBlocked)) { if (!bitStream.Read(isBlocked)) {
LOG("Unable to read isBlocked"); Log::Warn("Unable to read isBlocked");
return; return;
} }
@@ -75,31 +75,31 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
} }
if (!bitStream.Read(isImmune)) { if (!bitStream.Read(isImmune)) {
LOG("Unable to read isImmune"); Log::Warn("Unable to read isImmune");
return; return;
} }
if (isImmune) { if (isImmune) {
LOG_DEBUG("Target targetEntity %llu is immune!", branch.target); Log::Debug("Target targetEntity {} is immune!", branch.target);
this->m_OnFailImmune->Handle(context, bitStream, branch); this->m_OnFailImmune->Handle(context, bitStream, branch);
return; return;
} }
if (!bitStream.Read(isSuccess)) { if (!bitStream.Read(isSuccess)) {
LOG("failed to read success from bitstream"); Log::Warn("failed to read success from bitstream");
return; return;
} }
if (isSuccess) { if (isSuccess) {
uint32_t armorDamageDealt{}; uint32_t armorDamageDealt{};
if (!bitStream.Read(armorDamageDealt)) { if (!bitStream.Read(armorDamageDealt)) {
LOG("Unable to read armorDamageDealt"); Log::Warn("Unable to read armorDamageDealt");
return; return;
} }
uint32_t healthDamageDealt{}; uint32_t healthDamageDealt{};
if (!bitStream.Read(healthDamageDealt)) { if (!bitStream.Read(healthDamageDealt)) {
LOG("Unable to read healthDamageDealt"); Log::Warn("Unable to read healthDamageDealt");
return; return;
} }
@@ -112,7 +112,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
bool died{}; bool died{};
if (!bitStream.Read(died)) { if (!bitStream.Read(died)) {
LOG("Unable to read died"); Log::Warn("Unable to read died");
return; return;
} }
auto previousArmor = destroyableComponent->GetArmor(); auto previousArmor = destroyableComponent->GetArmor();
@@ -123,7 +123,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
uint8_t successState{}; uint8_t successState{};
if (!bitStream.Read(successState)) { if (!bitStream.Read(successState)) {
LOG("Unable to read success state"); Log::Warn("Unable to read success state");
return; return;
} }
@@ -136,7 +136,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
break; break;
default: default:
if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) { if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) {
LOG("Unknown success state (%i)!", successState); Log::Warn("Unknown success state ({})!", successState);
return; return;
} }
this->m_OnFailImmune->Handle(context, bitStream, branch); this->m_OnFailImmune->Handle(context, bitStream, branch);
@@ -166,13 +166,13 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream&
void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
auto* targetEntity = Game::entityManager->GetEntity(branch.target); auto* targetEntity = Game::entityManager->GetEntity(branch.target);
if (!targetEntity) { if (!targetEntity) {
LOG("Target entity %llu is null!", branch.target); Log::Warn("Target entity {} is null!", branch.target);
return; return;
} }
auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>(); auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>();
if (!destroyableComponent || !destroyableComponent->GetParent()) { if (!destroyableComponent || !destroyableComponent->GetParent()) {
LOG("No destroyable component on %llu", branch.target); Log::Warn("No destroyable component on {}", branch.target);
return; return;
} }
@@ -191,7 +191,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet
bitStream.Write(isImmune); bitStream.Write(isImmune);
if (isImmune) { if (isImmune) {
LOG_DEBUG("Target targetEntity %llu is immune!", branch.target); Log::Debug("Target targetEntity {} is immune!", branch.target);
this->m_OnFailImmune->Calculate(context, bitStream, branch); this->m_OnFailImmune->Calculate(context, bitStream, branch);
return; return;
} }
@@ -241,7 +241,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet
break; break;
default: default:
if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) { if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) {
LOG("Unknown success state (%i)!", successState); Log::Warn("Unknown success state ({})!", GeneralUtils::ToUnderlying(successState));
break; break;
} }
this->m_OnFailImmune->Calculate(context, bitStream, branch); this->m_OnFailImmune->Calculate(context, bitStream, branch);

View File

@@ -281,12 +281,12 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) {
case BehaviorTemplates::BEHAVIOR_MOUNT: break; case BehaviorTemplates::BEHAVIOR_MOUNT: break;
case BehaviorTemplates::BEHAVIOR_SKILL_SET: break; case BehaviorTemplates::BEHAVIOR_SKILL_SET: break;
default: 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; break;
} }
if (behavior == nullptr) { 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); behavior = new EmptyBehavior(behaviorId);
} }
@@ -309,7 +309,7 @@ BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) {
} }
if (templateID == BehaviorTemplates::BEHAVIOR_EMPTY && behaviorId != 0) { 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; 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 // Make sure we do not proceed if we are trying to load an invalid behavior
if (templateInDatabase.behaviorID == 0) { 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_effectId = 0;
this->m_effectHandle = nullptr; this->m_effectHandle = nullptr;

View File

@@ -31,7 +31,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const {
auto* entity = Game::entityManager->GetEntity(this->originator); auto* entity = Game::entityManager->GetEntity(this->originator);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Invalid entity for (%llu)!", this->originator); Log::Warn("Invalid entity for ({})!", this->originator);
return 0; return 0;
} }
@@ -39,7 +39,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const {
auto* component = entity->GetComponent<SkillComponent>(); auto* component = entity->GetComponent<SkillComponent>();
if (component == nullptr) { if (component == nullptr) {
LOG("No skill component attached to (%llu)!", this->originator);; Log::Warn("No skill component attached to ({})!", this->originator);;
return 0; return 0;
} }
@@ -126,7 +126,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream& bit
} }
if (!found) { 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 ({})!", syncId);
return; return;
} }
@@ -135,7 +135,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream& bit
const auto branch = entry.branchContext; const auto branch = entry.branchContext;
if (behavior == nullptr) { if (behavior == nullptr) {
LOG("Invalid behavior for sync id (%i)!", syncId); Log::Warn("Invalid behavior for sync id ({})!", syncId);
return; return;
} }
@@ -317,7 +317,7 @@ void BehaviorContext::FilterTargets(std::vector<Entity*>& targets, std::forward_
// if the caster is not there, return empty targets list // if the caster is not there, return empty targets list
auto* caster = Game::entityManager->GetEntity(this->caster); auto* caster = Game::entityManager->GetEntity(this->caster);
if (!caster) { if (!caster) {
LOG_DEBUG("Invalid caster for (%llu)!", this->originator); Log::Debug("Invalid caster for ({})!", this->originator);
targets.clear(); targets.clear();
return; return;
} }

View File

@@ -13,7 +13,7 @@ void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStrea
auto* entity = Game::entityManager->GetEntity(target); auto* entity = Game::entityManager->GetEntity(target);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Failed to find target (%llu)!", branch.target); Log::Warn("Failed to find target ({})!", branch.target);
return; return;
} }
@@ -43,7 +43,7 @@ void BlockBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branc
auto* entity = Game::entityManager->GetEntity(target); auto* entity = Game::entityManager->GetEntity(target);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Failed to find target (%llu)!", branch.target); Log::Warn("Failed to find target ({})!", branch.target);
return; return;
} }

View File

@@ -13,7 +13,7 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream
auto* entity = Game::entityManager->GetEntity(target); auto* entity = Game::entityManager->GetEntity(target);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Invalid target (%llu)!", target); Log::Warn("Invalid target ({})!", target);
return; return;
} }
@@ -21,7 +21,7 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream
auto* component = entity->GetComponent<DestroyableComponent>(); auto* component = entity->GetComponent<DestroyableComponent>();
if (component == nullptr) { if (component == nullptr) {
LOG("Invalid target, no destroyable component (%llu)!", target); Log::Warn("Invalid target, no destroyable component ({})!", target);
return; return;
} }
@@ -47,7 +47,7 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch
auto* entity = Game::entityManager->GetEntity(target); auto* entity = Game::entityManager->GetEntity(target);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Invalid target (%llu)!", target); Log::Warn("Invalid target ({})!", target);
return; return;
} }
@@ -55,7 +55,7 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch
auto* component = entity->GetComponent<DestroyableComponent>(); auto* component = entity->GetComponent<DestroyableComponent>();
if (component == nullptr) { if (component == nullptr) {
LOG("Invalid target, no destroyable component (%llu)!", target); Log::Warn("Invalid target, no destroyable component ({})!", target);
return; return;
} }

View File

@@ -17,7 +17,7 @@ void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitSt
return; return;
} }
LOG("Activating car boost!"); Log::Info("Activating car boost!");
auto* possessableComponent = entity->GetComponent<PossessableComponent>(); auto* possessableComponent = entity->GetComponent<PossessableComponent>();
if (possessableComponent != nullptr) { if (possessableComponent != nullptr) {
@@ -27,7 +27,7 @@ void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitSt
auto* characterComponent = possessor->GetComponent<CharacterComponent>(); auto* characterComponent = possessor->GetComponent<CharacterComponent>();
if (characterComponent != nullptr) { if (characterComponent != nullptr) {
LOG("Tracking car boost!"); Log::Info("Tracking car boost!");
characterComponent->UpdatePlayerStatistic(RacingCarBoostsActivated); characterComponent->UpdatePlayerStatistic(RacingCarBoostsActivated);
} }
} }

View File

@@ -7,7 +7,7 @@ void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStrea
uint32_t chainIndex{}; uint32_t chainIndex{};
if (!bitStream.Read(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; return;
} }
@@ -16,7 +16,7 @@ void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStrea
if (chainIndex < this->m_behaviors.size()) { if (chainIndex < this->m_behaviors.size()) {
this->m_behaviors.at(chainIndex)->Handle(context, bitStream, branch); this->m_behaviors.at(chainIndex)->Handle(context, bitStream, branch);
} else { } 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());
} }
} }

View File

@@ -8,7 +8,7 @@ void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitSt
uint32_t handle{}; uint32_t handle{};
if (!bitStream.Read(handle)) { if (!bitStream.Read(handle)) {
LOG("Unable to read handle from bitStream, aborting Handle! variable_type"); Log::Warn("Unable to read handle from bitStream, aborting Handle! variable_type");
return; return;
}; };

View File

@@ -11,7 +11,7 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea
auto* target = Game::entityManager->GetEntity(branch.target); auto* target = Game::entityManager->GetEntity(branch.target);
if (target == nullptr) { if (target == nullptr) {
LOG("Failed to find target (%llu)!", branch.target); Log::Warn("Failed to find target ({})!", branch.target);
return; return;
} }
@@ -37,7 +37,7 @@ void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchCon
auto* target = Game::entityManager->GetEntity(second); auto* target = Game::entityManager->GetEntity(second);
if (target == nullptr) { if (target == nullptr) {
LOG("Failed to find target (%llu)!", second); Log::Warn("Failed to find target ({})!", second);
return; return;
} }

View File

@@ -11,7 +11,7 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream
auto* target = Game::entityManager->GetEntity(branch.target); auto* target = Game::entityManager->GetEntity(branch.target);
if (target == nullptr) { if (target == nullptr) {
LOG("Failed to find target (%llu)!", branch.target); Log::Warn("Failed to find target ({})!", branch.target);
return; return;
} }
@@ -35,7 +35,7 @@ void DamageReductionBehavior::Timer(BehaviorContext* context, BehaviorBranchCont
auto* target = Game::entityManager->GetEntity(second); auto* target = Game::entityManager->GetEntity(second);
if (target == nullptr) { if (target == nullptr) {
LOG("Failed to find target (%llu)!", second); Log::Warn("Failed to find target ({})!", second);
return; return;
} }

View File

@@ -13,7 +13,7 @@ void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream&
uint32_t handle{}; uint32_t handle{};
if (!bitStream.Read(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; return;
} }
context->RegisterSyncBehavior(handle, this, branch, this->m_Duration); 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) { void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
uint32_t next{}; uint32_t next{};
if (!bitStream.Read(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; return;
} }
LWOOBJID target{}; LWOOBJID target{};
if (!bitStream.Read(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; return;
} }

View File

@@ -11,7 +11,7 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_strea
auto* entity = Game::entityManager->GetEntity(branch.target); auto* entity = Game::entityManager->GetEntity(branch.target);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Failed to find entity for (%llu)!", branch.target); Log::Warn("Failed to find entity for ({})!", branch.target);
return; return;
} }
@@ -19,7 +19,7 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_strea
auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE));
if (destroyable == nullptr) { if (destroyable == nullptr) {
LOG("Failed to find destroyable component for %(llu)!", branch.target); Log::Warn("Failed to find destroyable component for ({})!", branch.target);
return; return;
} }

View File

@@ -13,7 +13,7 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitSt
auto* target = Game::entityManager->GetEntity(branch.target); auto* target = Game::entityManager->GetEntity(branch.target);
if (!target) { if (!target) {
LOG("Failed to find target (%llu)!", branch.target); Log::Warn("Failed to find target ({})!", branch.target);
return; return;
} }
@@ -59,7 +59,7 @@ void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext bra
auto* target = Game::entityManager->GetEntity(second); auto* target = Game::entityManager->GetEntity(second);
if (!target) { if (!target) {
LOG("Failed to find target (%llu)!", second); Log::Warn("Failed to find target ({})!", second);
return; return;
} }

View File

@@ -12,7 +12,7 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitS
bool unknown = false; bool unknown = false;
if (!bitStream.Read(unknown)) { 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; return;
}; };
@@ -23,7 +23,7 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitS
bool unknown = false; bool unknown = false;
if (!bitStream.Read(unknown)) { 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; return;
}; };
@@ -35,7 +35,7 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitS
bool unknown = false; bool unknown = false;
if (!bitStream.Read(unknown)) { 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; return;
}; };
} }

View File

@@ -13,7 +13,7 @@ void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitS
bool unknown{}; bool unknown{};
if (!bitStream.Read(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; return;
}; };
} }

View File

@@ -15,7 +15,7 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream&
this->m_movingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { this->m_movingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) {
return; 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; return;
}; };

View File

@@ -12,14 +12,14 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea
LWOOBJID target{}; LWOOBJID target{};
if (!bitStream.Read(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; return;
}; };
auto* entity = Game::entityManager->GetEntity(context->originator); auto* entity = Game::entityManager->GetEntity(context->originator);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Failed to find originator (%llu)!", context->originator); Log::Warn("Failed to find originator ({:d})!", context->originator);
return; return;
} }
@@ -27,7 +27,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea
auto* skillComponent = entity->GetComponent<SkillComponent>(); auto* skillComponent = entity->GetComponent<SkillComponent>();
if (skillComponent == nullptr) { 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; return;
} }
@@ -35,7 +35,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea
if (m_useMouseposit && !branch.isSync) { if (m_useMouseposit && !branch.isSync) {
NiPoint3 targetPosition = NiPoint3Constant::ZERO; NiPoint3 targetPosition = NiPoint3Constant::ZERO;
if (!bitStream.Read(targetPosition)) { 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; return;
}; };
} }
@@ -46,7 +46,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea
LWOOBJID projectileId{}; LWOOBJID projectileId{};
if (!bitStream.Read(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; return;
}; };
@@ -64,7 +64,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt
auto* entity = Game::entityManager->GetEntity(context->originator); auto* entity = Game::entityManager->GetEntity(context->originator);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Failed to find originator (%llu)!", context->originator); Log::Warn("Failed to find originator ({})!", context->originator);
return; return;
} }
@@ -72,7 +72,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt
auto* skillComponent = entity->GetComponent<SkillComponent>(); auto* skillComponent = entity->GetComponent<SkillComponent>();
if (skillComponent == nullptr) { if (skillComponent == nullptr) {
LOG("Failed to find skill component for (%llu)!", context->originator); Log::Warn("Failed to find skill component for ({})!", context->originator);
return; return;
@@ -81,7 +81,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt
auto* other = Game::entityManager->GetEntity(branch.target); auto* other = Game::entityManager->GetEntity(branch.target);
if (other == nullptr) { if (other == nullptr) {
LOG("Invalid projectile target (%llu)!", branch.target); Log::Warn("Invalid projectile target ({})!", branch.target);
return; return;
} }

View File

@@ -40,7 +40,7 @@ void PropertyTeleportBehavior::Handle(BehaviorContext* context, RakNet::BitStrea
if (zoneClone != 0) ChatPackets::SendSystemMessage(sysAddr, u"Transfering to your property!"); if (zoneClone != 0) ChatPackets::SendSystemMessage(sysAddr, u"Transfering to your property!");
else ChatPackets::SendSystemMessage(sysAddr, u"Transfering back to previous world!"); 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()) { if (entity->GetCharacter()) {
entity->GetCharacter()->SetZoneID(zoneID); entity->GetCharacter()->SetZoneID(zoneID);
entity->GetCharacter()->SetZoneInstance(zoneInstance); entity->GetCharacter()->SetZoneInstance(zoneInstance);

View File

@@ -11,7 +11,7 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_str
auto* entity = Game::entityManager->GetEntity(branch.target); auto* entity = Game::entityManager->GetEntity(branch.target);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Failed to find entity for (%llu)!", branch.target); Log::Warn("Failed to find entity for ({})!", branch.target);
return; return;
} }
@@ -19,7 +19,7 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_str
auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE));
if (destroyable == nullptr) { if (destroyable == nullptr) {
LOG("Failed to find destroyable component for %(llu)!", branch.target); Log::Warn("Failed to find destroyable component for ({})!", branch.target);
return; return;
} }

View File

@@ -3,15 +3,14 @@
#include "BehaviorContext.h" #include "BehaviorContext.h"
#include "EntityManager.h" #include "EntityManager.h"
#include "CppScripts.h" #include "CppScripts.h"
#include "Entity.h"
void SkillEventBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { void SkillEventBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
auto* target = Game::entityManager->GetEntity(branch.target); auto* target = Game::entityManager->GetEntity(branch.target);
auto* caster = Game::entityManager->GetEntity(context->originator); auto* caster = Game::entityManager->GetEntity(context->originator);
if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { target->GetScript()->OnSkillEventFired(target, caster, *this->m_effectHandle);
script->OnSkillEventFired(target, caster, *this->m_effectHandle);
}
} }
} }
@@ -21,8 +20,6 @@ SkillEventBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitSt
auto* caster = Game::entityManager->GetEntity(context->originator); auto* caster = Game::entityManager->GetEntity(context->originator);
if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { target->GetScript()->OnSkillEventFired(target, caster, *this->m_effectHandle);
script->OnSkillEventFired(target, caster, *this->m_effectHandle);
}
} }
} }

View File

@@ -15,7 +15,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStrea
auto* origin = Game::entityManager->GetEntity(context->originator); auto* origin = Game::entityManager->GetEntity(context->originator);
if (origin == nullptr) { if (origin == nullptr) {
LOG("Failed to find self entity (%llu)!", context->originator); Log::Warn("Failed to find self entity ({})!", context->originator);
return; return;
} }
@@ -45,7 +45,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStrea
); );
if (entity == nullptr) { if (entity == nullptr) {
LOG("Failed to spawn entity (%i)!", this->m_lot); Log::Warn("Failed to spawn entity ({})!", this->m_lot);
return; return;
} }
@@ -82,7 +82,7 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext
auto* entity = Game::entityManager->GetEntity(second); auto* entity = Game::entityManager->GetEntity(second);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Failed to find spawned entity (%llu)!", second); Log::Warn("Failed to find spawned entity ({})!", second);
return; return;
} }

View File

@@ -17,14 +17,14 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream
bool blocked{}; bool blocked{};
if (!bitStream.Read(blocked)) { if (!bitStream.Read(blocked)) {
LOG("Unable to read blocked from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); Log::Warn("Unable to read blocked from bitStream, aborting Handle! {}", bitStream.GetNumberOfUnreadBits());
return; return;
}; };
auto* target = Game::entityManager->GetEntity(branch.target); auto* target = Game::entityManager->GetEntity(branch.target);
if (target == nullptr) { if (target == nullptr) {
LOG("Failed to find target (%llu)!", branch.target); Log::Warn("Failed to find target ({})!", branch.target);
return; return;
} }
@@ -47,7 +47,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStr
auto* self = Game::entityManager->GetEntity(context->originator); auto* self = Game::entityManager->GetEntity(context->originator);
if (self == nullptr) { if (self == nullptr) {
LOG("Invalid self entity (%llu)!", context->originator); Log::Warn("Invalid self entity ({})!", context->originator);
return; return;
} }
@@ -82,7 +82,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStr
bitStream.Write(blocked); bitStream.Write(blocked);
if (target == nullptr) { if (target == nullptr) {
LOG("Failed to find target (%llu)!", branch.target); Log::Warn("Failed to find target ({})!", branch.target);
return; return;
} }

View File

@@ -11,7 +11,7 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStre
if (this->m_imagination > 0 || !this->m_isEnemyFaction) { if (this->m_imagination > 0 || !this->m_isEnemyFaction) {
if (!bitStream.Read(state)) { if (!bitStream.Read(state)) {
LOG("Unable to read state from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); Log::Warn("Unable to read state from bitStream, aborting Handle! {}", bitStream.GetNumberOfUnreadBits());
return; return;
}; };
} }
@@ -28,7 +28,7 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStre
return; return;
} }
LOG_DEBUG("[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); Log::Debug("[{}] State: ({}), imagination: ({}) / ({})", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination());
if (state) { if (state) {
this->m_actionTrue->Handle(context, bitStream, branch); this->m_actionTrue->Handle(context, bitStream, branch);

View File

@@ -13,7 +13,7 @@ void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream&
float value{}; float value{};
if (!bitStream.Read(value)) { if (!bitStream.Read(value)) {
LOG("Unable to read value from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); Log::Warn("Unable to read value from bitStream, aborting Handle! {}", bitStream.GetNumberOfUnreadBits());
return; return;
}; };

View File

@@ -16,7 +16,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStre
if (this->m_usePickedTarget && branch.target != LWOOBJID_EMPTY) { if (this->m_usePickedTarget && branch.target != LWOOBJID_EMPTY) {
auto target = Game::entityManager->GetEntity(branch.target); auto target = Game::entityManager->GetEntity(branch.target);
if (!target) LOG("target %llu is null", branch.target); if (!target) Log::Warn("target {} is null", branch.target);
else { else {
targets.push_back(target); targets.push_back(target);
context->FilterTargets(targets, this->m_ignoreFactionList, this->m_includeFactionList, this->m_targetSelf, this->m_targetEnemy, this->m_targetFriend, this->m_targetTeam); context->FilterTargets(targets, this->m_ignoreFactionList, this->m_includeFactionList, this->m_targetSelf, this->m_targetEnemy, this->m_targetFriend, this->m_targetTeam);
@@ -29,7 +29,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStre
bool hasTargets = false; bool hasTargets = false;
if (!bitStream.Read(hasTargets)) { if (!bitStream.Read(hasTargets)) {
LOG("Unable to read hasTargets from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); Log::Warn("Unable to read hasTargets from bitStream, aborting Handle! {}", bitStream.GetNumberOfUnreadBits());
return; return;
}; };
@@ -37,7 +37,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStre
bool blocked = false; bool blocked = false;
if (!bitStream.Read(blocked)) { if (!bitStream.Read(blocked)) {
LOG("Unable to read blocked from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); Log::Warn("Unable to read blocked from bitStream, aborting Handle! {}", bitStream.GetNumberOfUnreadBits());
return; return;
}; };
@@ -50,12 +50,12 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStre
if (hasTargets) { if (hasTargets) {
uint32_t count = 0; uint32_t count = 0;
if (!bitStream.Read(count)) { if (!bitStream.Read(count)) {
LOG("Unable to read count from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); Log::Warn("Unable to read count from bitStream, aborting Handle! {}", bitStream.GetNumberOfUnreadBits());
return; return;
}; };
if (count > m_maxTargets) { if (count > m_maxTargets) {
LOG("Bitstream has too many targets Max:%i Recv:%i", this->m_maxTargets, count); Log::Warn("Bitstream has too many targets Max:{} Recv:{}", this->m_maxTargets, count);
return; return;
} }
@@ -63,7 +63,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStre
LWOOBJID id{}; LWOOBJID id{};
if (!bitStream.Read(id)) { if (!bitStream.Read(id)) {
LOG("Unable to read id from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); Log::Warn("Unable to read id from bitStream, aborting Handle! {}", bitStream.GetNumberOfUnreadBits());
return; return;
}; };
@@ -71,7 +71,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStre
auto* canidate = Game::entityManager->GetEntity(id); auto* canidate = Game::entityManager->GetEntity(id);
if (canidate) targets.push_back(canidate); if (canidate) targets.push_back(canidate);
} else { } else {
LOG("Bitstream has LWOOBJID_EMPTY as a target!"); Log::Warn("Bitstream has LWOOBJID_EMPTY as a target!");
} }
} }
@@ -85,7 +85,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStre
void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
auto* self = Game::entityManager->GetEntity(context->originator); auto* self = Game::entityManager->GetEntity(context->originator);
if (self == nullptr) { if (self == nullptr) {
LOG("Invalid self for (%llu)!", context->originator); Log::Warn("Invalid self for ({})!", context->originator);
return; return;
} }

View File

@@ -10,7 +10,7 @@ void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStrea
auto* target = Game::entityManager->GetEntity(branch.target); auto* target = Game::entityManager->GetEntity(branch.target);
if (target == nullptr) { if (target == nullptr) {
LOG("Failed to find target (%llu)!", branch.target); Log::Warn("Failed to find target ({})!", branch.target);
return; return;
} }
@@ -26,7 +26,7 @@ void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitSt
auto* target = Game::entityManager->GetEntity(branch.target); auto* target = Game::entityManager->GetEntity(branch.target);
if (target == nullptr) { if (target == nullptr) {
LOG("Failed to find target (%llu)!", branch.target); Log::Warn("Failed to find target ({})!", branch.target);
return; return;
} }

View File

@@ -18,7 +18,7 @@ void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitS
auto* self = Game::entityManager->GetEntity(context->originator); auto* self = Game::entityManager->GetEntity(context->originator);
if (self == nullptr) { if (self == nullptr) {
LOG("Invalid self for (%llu)", context->originator); Log::Warn("Invalid self for ({})", context->originator);
return; return;
} }

View File

@@ -9,11 +9,15 @@
#include "UserManager.h" #include "UserManager.h"
#include "CDMissionsTable.h" #include "CDMissionsTable.h"
AchievementVendorComponent::AchievementVendorComponent(Entity* parent) : VendorComponent(parent) {
RefreshInventory(true);
};
bool AchievementVendorComponent::SellsItem(Entity* buyer, const LOT lot) { bool AchievementVendorComponent::SellsItem(Entity* buyer, const LOT lot) {
auto* missionComponent = buyer->GetComponent<MissionComponent>(); auto* missionComponent = buyer->GetComponent<MissionComponent>();
if (!missionComponent) return false; if (!missionComponent) return false;
if (m_PlayerPurchasableItems[buyer->GetObjectID()].contains(lot)){ if (m_PlayerPurchasableItems[buyer->GetObjectID()].contains(lot)) {
return true; return true;
} }
@@ -35,7 +39,7 @@ void AchievementVendorComponent::Buy(Entity* buyer, LOT lot, uint32_t count) {
int itemCompID = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::ITEM); int itemCompID = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::ITEM);
CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID);
uint32_t costLOT = itemComp.commendationLOT; uint32_t costLOT = itemComp.commendationLOT;
if (costLOT == -1 || !SellsItem(buyer, lot)) { if (costLOT == -1 || !SellsItem(buyer, lot)) {
auto* user = UserManager::Instance()->GetUser(buyer->GetSystemAddress()); auto* user = UserManager::Instance()->GetUser(buyer->GetSystemAddress());
CheatDetection::ReportCheat(user, buyer->GetSystemAddress(), "Attempted to buy item %i from achievement vendor %i that is not purchasable", lot, m_Parent->GetLOT()); CheatDetection::ReportCheat(user, buyer->GetSystemAddress(), "Attempted to buy item %i from achievement vendor %i that is not purchasable", lot, m_Parent->GetLOT());
@@ -44,7 +48,7 @@ void AchievementVendorComponent::Buy(Entity* buyer, LOT lot, uint32_t count) {
} }
auto* inventoryComponent = buyer->GetComponent<InventoryComponent>(); auto* inventoryComponent = buyer->GetComponent<InventoryComponent>();
if (!inventoryComponent) { if (!inventoryComponent) {
GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return; return;
} }
@@ -69,4 +73,9 @@ void AchievementVendorComponent::Buy(Entity* buyer, LOT lot, uint32_t count) {
inventoryComponent->AddItem(lot, count, eLootSourceType::VENDOR); inventoryComponent->AddItem(lot, count, eLootSourceType::VENDOR);
GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_SUCCESS); GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_SUCCESS);
} }
void AchievementVendorComponent::RefreshInventory(bool isCreation) {
SetHasStandardCostItems(true);
Game::entityManager->SerializeEntity(m_Parent);
}

View File

@@ -11,7 +11,9 @@ class Entity;
class AchievementVendorComponent final : public VendorComponent { class AchievementVendorComponent final : public VendorComponent {
public: public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::ACHIEVEMENT_VENDOR; static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::ACHIEVEMENT_VENDOR;
AchievementVendorComponent(Entity* parent) : VendorComponent(parent) {}; AchievementVendorComponent(Entity* parent);
void RefreshInventory(bool isCreation = false) override;
bool SellsItem(Entity* buyer, const LOT lot); bool SellsItem(Entity* buyer, const LOT lot);
void Buy(Entity* buyer, LOT lot, uint32_t count); void Buy(Entity* buyer, LOT lot, uint32_t count);

View File

@@ -273,7 +273,7 @@ void ActivityComponent::Update(float deltaTime) {
// The timer has elapsed, start the instance // The timer has elapsed, start the instance
if (lobby->timer <= 0.0f) { if (lobby->timer <= 0.0f) {
LOG("Setting up instance."); Log::Info("Setting up instance.");
ActivityInstance* instance = NewInstance(); ActivityInstance* instance = NewInstance();
LoadPlayersIntoInstance(instance, lobby->players); LoadPlayersIntoInstance(instance, lobby->players);
instance->StartZone(); instance->StartZone();
@@ -524,7 +524,7 @@ void ActivityInstance::StartZone() {
if (player == nullptr) if (player == nullptr)
return; 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()) { if (player->GetCharacter()) {
player->GetCharacter()->SetZoneID(zoneID); player->GetCharacter()->SetZoneID(zoneID);
player->GetCharacter()->SetZoneInstance(zoneInstance); player->GetCharacter()->SetZoneInstance(zoneInstance);

View File

@@ -540,7 +540,7 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const {
auto* entity = Game::entityManager->GetEntity(target); auto* entity = Game::entityManager->GetEntity(target);
if (entity == nullptr) { if (entity == nullptr) {
LOG("Invalid entity for checking validity (%llu)!", target); Log::Warn("Invalid entity for checking validity ({})!", target);
return false; return false;
} }
@@ -554,7 +554,7 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const {
auto* referenceDestroyable = m_Parent->GetComponent<DestroyableComponent>(); auto* referenceDestroyable = m_Parent->GetComponent<DestroyableComponent>();
if (referenceDestroyable == nullptr) { if (referenceDestroyable == nullptr) {
LOG("Invalid reference destroyable component on (%llu)!", m_Parent->GetObjectID()); Log::Warn("Invalid reference destroyable component on ({})!", m_Parent->GetObjectID());
return false; return false;
} }

View File

@@ -81,13 +81,13 @@ void BouncerComponent::LookupPetSwitch() {
Game::entityManager->SerializeEntity(m_Parent); Game::entityManager->SerializeEntity(m_Parent);
LOG("Loaded pet bouncer"); Log::Info("Loaded pet bouncer");
} }
} }
} }
if (!m_PetSwitchLoaded) { if (!m_PetSwitchLoaded) {
LOG("Failed to load pet bouncer"); Log::Warn("Failed to load pet bouncer");
m_Parent->AddCallbackTimer(0.5f, [this]() { m_Parent->AddCallbackTimer(0.5f, [this]() {
LookupPetSwitch(); LookupPetSwitch();

View File

@@ -110,7 +110,7 @@ void BuffComponent::Update(float deltaTime) {
const std::string& GetFxName(const std::string& buffname) { const std::string& GetFxName(const std::string& buffname) {
const auto& toReturn = BuffFx[buffname]; const auto& toReturn = BuffFx[buffname];
if (toReturn.empty()) { if (toReturn.empty()) {
LOG_DEBUG("No fx name for %s", buffname.c_str()); Log::Debug("No fx name for {:s}", buffname);
} }
return toReturn; return toReturn;
} }
@@ -122,7 +122,7 @@ void BuffComponent::ApplyBuffFx(uint32_t buffId, const BuffParameter& buff) {
if (buffName.empty()) return; if (buffName.empty()) return;
fxToPlay += std::to_string(buffId); 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); 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; if (buffName.empty()) return;
fxToPlay += std::to_string(buffId); fxToPlay += std::to_string(buffId);
LOG_DEBUG("Stopping %s", fxToPlay.c_str()); Log::Debug("Stopping {:s}", fxToPlay);
GameMessages::SendStopFXEffect(m_Parent, false, fxToPlay); GameMessages::SendStopFXEffect(m_Parent, false, fxToPlay);
} }
@@ -460,7 +460,7 @@ const std::vector<BuffParameter>& BuffComponent::GetBuffParameters(int32_t buffI
param.values.push_back(value); param.values.push_back(value);
} catch (std::invalid_argument& exception) { } 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());
} }
} }
} }

View File

@@ -24,7 +24,7 @@ void BuildBorderComponent::OnUse(Entity* originator) {
if (!entities.empty()) { if (!entities.empty()) {
buildArea = entities[0]->GetObjectID(); buildArea = entities[0]->GetObjectID();
LOG("Using PropertyPlaque"); Log::Info("Using PropertyPlaque");
} }
auto* inventoryComponent = originator->GetComponent<InventoryComponent>(); auto* inventoryComponent = originator->GetComponent<InventoryComponent>();
@@ -41,7 +41,7 @@ void BuildBorderComponent::OnUse(Entity* originator) {
inventoryComponent->PushEquippedItems(); inventoryComponent->PushEquippedItems();
LOG("Starting with %llu", buildArea); Log::Info("Starting with {}", buildArea);
if (PropertyManagementComponent::Instance() != nullptr) { if (PropertyManagementComponent::Instance() != nullptr) {
GameMessages::SendStartArrangingWithItem( GameMessages::SendStartArrangingWithItem(

View File

@@ -48,6 +48,7 @@ set(DGAME_DCOMPONENTS_SOURCES
"HavokVehiclePhysicsComponent.cpp" "HavokVehiclePhysicsComponent.cpp"
"VendorComponent.cpp" "VendorComponent.cpp"
"MiniGameControlComponent.cpp" "MiniGameControlComponent.cpp"
"ScriptComponent.cpp"
) )
add_library(dComponents OBJECT ${DGAME_DCOMPONENTS_SOURCES}) add_library(dComponents OBJECT ${DGAME_DCOMPONENTS_SOURCES})

View File

@@ -190,7 +190,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) {
tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char");
if (!character) { if (!character) {
LOG("Failed to find char tag while loading XML!"); Log::Warn("Failed to find char tag while loading XML!");
return; return;
} }
if (character->QueryAttribute("rpt", &m_Reputation) == tinyxml2::XML_NO_ATTRIBUTE) { if (character->QueryAttribute("rpt", &m_Reputation) == tinyxml2::XML_NO_ATTRIBUTE) {
@@ -302,7 +302,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) {
void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) {
tinyxml2::XMLElement* minifig = doc->FirstChildElement("obj")->FirstChildElement("mf"); tinyxml2::XMLElement* minifig = doc->FirstChildElement("obj")->FirstChildElement("mf");
if (!minifig) { if (!minifig) {
LOG("Failed to find mf tag while updating XML!"); Log::Warn("Failed to find mf tag while updating XML!");
return; return;
} }
@@ -322,7 +322,7 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) {
tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char");
if (!character) { if (!character) {
LOG("Failed to find char tag while updating XML!"); Log::Warn("Failed to find char tag while updating XML!");
return; return;
} }
@@ -375,7 +375,7 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) {
// //
auto newUpdateTimestamp = std::time(nullptr); auto newUpdateTimestamp = std::time(nullptr);
LOG("Time since last save: %d", newUpdateTimestamp - m_LastUpdateTimestamp); Log::Warn("Time since last save: {:d}", newUpdateTimestamp - m_LastUpdateTimestamp);
m_TotalTimePlayed += newUpdateTimestamp - m_LastUpdateTimestamp; m_TotalTimePlayed += newUpdateTimestamp - m_LastUpdateTimestamp;
character->SetAttribute("time", m_TotalTimePlayed); character->SetAttribute("time", m_TotalTimePlayed);
@@ -405,7 +405,7 @@ Item* CharacterComponent::GetRocket(Entity* player) {
} }
if (!rocket) { if (!rocket) {
LOG("Unable to find rocket to equip!"); Log::Warn("Unable to find rocket to equip!");
return rocket; return rocket;
} }
return rocket; return rocket;
@@ -772,7 +772,7 @@ void CharacterComponent::AwardClaimCodes() {
auto* cdrewardCodes = CDClientManager::GetTable<CDRewardCodesTable>(); auto* cdrewardCodes = CDClientManager::GetTable<CDRewardCodesTable>();
for (auto const rewardCode : rewardCodes) { for (auto const rewardCode : rewardCodes) {
LOG_DEBUG("Processing RewardCode %i", rewardCode); Log::Debug("Processing RewardCode {:d}", rewardCode);
const uint32_t rewardCodeIndex = rewardCode >> 6; const uint32_t rewardCodeIndex = rewardCode >> 6;
const uint32_t bitIndex = rewardCode % 64; const uint32_t bitIndex = rewardCode % 64;
if (GeneralUtils::CheckBit(m_ClaimCodes[rewardCodeIndex], bitIndex)) continue; if (GeneralUtils::CheckBit(m_ClaimCodes[rewardCodeIndex], bitIndex)) continue;

View File

@@ -50,7 +50,7 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Phy
return; return;
if (entity->GetLOT() == 1) { if (entity->GetLOT() == 1) {
LOG("Using patch to load minifig physics"); Log::Info("Using patch to load minifig physics");
float radius = 1.5f; float radius = 1.5f;
m_dpEntity = new dpEntity(m_Parent->GetObjectID(), radius, false); m_dpEntity = new dpEntity(m_Parent->GetObjectID(), radius, false);
@@ -161,7 +161,7 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bo
void ControllablePhysicsComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { void ControllablePhysicsComponent::LoadFromXml(tinyxml2::XMLDocument* doc) {
tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char");
if (!character) { if (!character) {
LOG("Failed to find char tag!"); Log::Warn("Failed to find char tag!");
return; return;
} }
@@ -181,7 +181,7 @@ void ControllablePhysicsComponent::LoadFromXml(tinyxml2::XMLDocument* doc) {
void ControllablePhysicsComponent::UpdateXml(tinyxml2::XMLDocument* doc) { void ControllablePhysicsComponent::UpdateXml(tinyxml2::XMLDocument* doc) {
tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char");
if (!character) { if (!character) {
LOG("Failed to find char tag while updating XML!"); Log::Warn("Failed to find char tag while updating XML!");
return; return;
} }
@@ -298,7 +298,7 @@ void ControllablePhysicsComponent::RemoveSpeedboost(float value) {
void ControllablePhysicsComponent::ActivateBubbleBuff(eBubbleType bubbleType, bool specialAnims) { void ControllablePhysicsComponent::ActivateBubbleBuff(eBubbleType bubbleType, bool specialAnims) {
if (m_IsInBubble) { if (m_IsInBubble) {
LOG("Already in bubble"); Log::Warn("Already in bubble");
return; return;
} }
m_BubbleType = bubbleType; m_BubbleType = bubbleType;

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