Compare commits

..

20 Commits

Author SHA1 Message Date
bb8d4f2eb7 impl mover and rotator loadconfigdata 2024-02-18 00:55:20 -06:00
7e42efa82e Merge branch 'main' into movingPlatformWork 2024-02-17 03:28:33 -06:00
d4ca011466 fix tests 2024-02-17 03:21:41 -06:00
52228ece16 Make the test have the capability of passing if the code is correct
Before the platform was not moving and the positions werent; getting updated
2024-02-17 02:41:17 -06:00
92696606e1 Expand tests to cover path types and edge cases 2024-02-17 02:14:36 -06:00
c35ab1f9e3 Add test logs, fix seg faults in tests 2024-02-12 10:43:58 -06:00
David Markowitz
1ae57dc6e8 Fix one failing test 2024-02-10 19:53:20 -08:00
David Markowitz
944d3e1bac branch back to working state 2024-02-10 19:23:35 -08:00
David Markowitz
790505ba6f Merge branch 'main' into movingPlatformWork 2024-02-10 19:10:55 -08:00
David Markowitz
af8bc2c458 refactor to class style and not c style 2023-08-05 01:21:59 -07:00
David Markowitz
42de987e25 Keep updating 2023-08-04 00:54:48 -07:00
David Markowitz
e6fe2edfae better tests for advancing waypoint 2023-08-03 21:37:08 -07:00
David Markowitz
e31b6ca54b Merge branch 'main' into movingPlatformWork 2023-08-03 20:32:26 -07:00
David Markowitz
2252088e1b TDD 2023-08-03 01:50:34 -07:00
David Markowitz
c293b7a9d7 moving platform work 2023-08-02 00:02:02 -07:00
David Markowitz
4336cb7f50 quick notes 2023-08-01 01:36:24 -07:00
David Markowitz
43657324e9 Further work on subcomponents
serialization is improved, next is re-implementing the actual functionality.
2023-08-01 01:19:07 -07:00
David Markowitz
ba409b6ee2 add serialization test 2023-07-31 18:38:26 -07:00
David Markowitz
a7eb28279e finish construction serialization test 2023-07-31 18:36:14 -07:00
David Markowitz
3cf460cc52 throw away the old impl 2023-07-31 02:13:19 -07:00
448 changed files with 5875 additions and 5681 deletions

3
.gitmodules vendored
View File

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

View File

@@ -4,8 +4,6 @@ include(CTest)
set(CMAKE_CXX_STANDARD 20)
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")
# Read variables from file
@@ -79,7 +77,6 @@ endif()
# Our output dir
set(CMAKE_BINARY_DIR ${PROJECT_BINARY_DIR})
#set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON) # unfortunately, forces all libraries to be built in series, which will slow down the build process
# TODO make this not have to override the build type directories
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR})
@@ -93,8 +90,6 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
find_package(MariaDB)
# Create a /resServer directory
make_directory(${CMAKE_BINARY_DIR}/resServer)
@@ -184,7 +179,7 @@ file(ARCHIVE_EXTRACT INPUT ${PROJECT_BINARY_DIR}/navmeshes.zip DESTINATION ${PRO
file(REMOVE ${PROJECT_BINARY_DIR}/navmeshes.zip)
# Copy vanity files on first build
set(VANITY_FILES "CREDITS.md" "INFO.md" "TESTAMENT.md" "root.xml" "dev-tribute.xml" "atm.xml" "demo.xml")
set(VANITY_FILES "CREDITS.md" "INFO.md" "TESTAMENT.md" "NPC.xml")
foreach(file ${VANITY_FILES})
configure_file("${CMAKE_SOURCE_DIR}/vanity/${file}" "${CMAKE_BINARY_DIR}/vanity/${file}" COPYONLY)
@@ -207,19 +202,39 @@ foreach(file ${SQL_FILES})
configure_file(${CMAKE_SOURCE_DIR}/migrations/cdserver/${file} ${PROJECT_BINARY_DIR}/migrations/cdserver/${file})
endforeach()
# Add system specfic includes for Apple, Windows and Other Unix OS' (including Linux)
if (APPLE)
include_directories("/usr/local/include/")
endif()
# Load all of our third party directories
add_subdirectory(thirdparty)
# Create our list of include directories
set(INCLUDED_DIRECTORIES
"dCommon"
"dCommon/dClient"
"dCommon/dEnums"
"dChatFilter"
"dGame"
"dGame/dBehaviors"
"dGame/dComponents"
"dGame/dGameMessages"
"dGame/dInventory"
"dGame/dMission"
"dGame/dEntity"
"dGame/dPropertyBehaviors"
"dGame/dPropertyBehaviors/ControlBehaviorMessages"
"dGame/dUtilities"
"dPhysics"
"dNavigation"
"dNavigation/dTerrain"
"dZoneManager"
"dDatabase"
"dDatabase/CDClientDatabase"
"dDatabase/CDClientDatabase/CDClientTables"
"dDatabase/GameDatabase"
"dDatabase/GameDatabase/ITables"
"dDatabase/GameDatabase/MySQL"
"dDatabase/GameDatabase/MySQL/Tables"
"dNet"
@@ -239,7 +254,6 @@ set(INCLUDED_DIRECTORIES
)
# Add system specfic includes for Apple, Windows and Other Unix OS' (including Linux)
# TODO: Should probably not do this.
if(APPLE)
include_directories("/usr/local/include/")
endif()
@@ -249,10 +263,30 @@ foreach(dir ${INCLUDED_DIRECTORIES})
include_directories(${PROJECT_SOURCE_DIR}/${dir})
endforeach()
if(NOT WIN32)
include_directories("${PROJECT_SOURCE_DIR}/thirdparty/libbcrypt/include/bcrypt")
endif()
include_directories("${PROJECT_SOURCE_DIR}/thirdparty/libbcrypt/include")
# Add linking directories:
link_directories(${PROJECT_BINARY_DIR})
# Load all of our third party directories
add_subdirectory(thirdparty)
if (UNIX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
endif()
# Glob together all headers that need to be precompiled
file(
GLOB HEADERS_DDATABASE
LIST_DIRECTORIES false
${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase/*.h
${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase/CDClientTables/*.h
${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase/ITables/*.h
${PROJECT_SOURCE_DIR}/thirdparty/SQLite/*.h
)
file(
GLOB HEADERS_DZONEMANAGER
LIST_DIRECTORIES false
@@ -287,7 +321,7 @@ add_subdirectory(dPhysics)
add_subdirectory(dServer)
# Create a list of common libraries shared between all binaries
set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "fmt" "raknet" "MariaDB::ConnCpp" "magic_enum")
set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp" "magic_enum" "MD5")
# Add platform specific common libraries
if(UNIX)
@@ -309,6 +343,12 @@ target_precompile_headers(
${HEADERS_DZONEMANAGER}
)
# Need to specify to use the CXX compiler language here or else we get errors including <string>.
target_precompile_headers(
dDatabase PRIVATE
"$<$<COMPILE_LANGUAGE:CXX>:${HEADERS_DDATABASE}>"
)
target_precompile_headers(
dCommon PRIVATE
${HEADERS_DCOMMON}

View File

@@ -23,7 +23,8 @@ RUN --mount=type=cache,id=build-apt-cache,target=/var/cache/apt \
rm -rf /var/lib/apt/lists/*
# Grab libraries and load them
COPY --from=build /app/build/mariadbcpp/libmariadbcpp.so /usr/local/lib/
COPY --from=build /app/build/mariadbcpp/src/mariadb_connector_cpp-build/libmariadbcpp.so /usr/local/lib/
COPY --from=build /app/build/mariadbcpp/src/mariadb_connector_cpp-build/libmariadb/libmariadb/libmariadb.so.3 /usr/local/lib
RUN ldconfig
# Server bins

View File

@@ -1,17 +0,0 @@
include(FetchContent)
message(STATUS "Fetching gtest...")
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.12.1
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(GoogleTest)
message(STATUS "gtest fetched and is now ready.")
set(GoogleTest_FOUND TRUE)

View File

@@ -54,14 +54,14 @@ int main(int argc, char** argv) {
Server::SetupLogger("AuthServer");
if (!Game::logger) return EXIT_FAILURE;
Log::Info("Starting Auth server...");
Log::Info("Version: {:s}", PROJECT_VERSION);
Log::Info("Compiled on: {:s}", __TIMESTAMP__);
LOG("Starting Auth server...");
LOG("Version: %s", PROJECT_VERSION);
LOG("Compiled on: %s", __TIMESTAMP__);
try {
Database::Connect();
} catch (sql::SQLException& ex) {
Log::Info("Got an error while connecting to the database: {:s}", ex.what());
LOG("Got an error while connecting to the database: %s", ex.what());
Database::Destroy("AuthServer");
delete Game::server;
delete Game::logger;
@@ -77,7 +77,7 @@ int main(int argc, char** argv) {
masterIP = masterInfo->ip;
masterPort = masterInfo->port;
}
Log::Info("Master is at {:s}:{:d}", masterIP, masterPort);
LOG("Master is at %s:%d", masterIP.c_str(), masterPort);
Game::randomEngine = std::mt19937(time(0));
@@ -110,7 +110,7 @@ int main(int argc, char** argv) {
framesSinceMasterDisconnect++;
if (framesSinceMasterDisconnect >= authFramerate) {
Log::Info("No connection to master!");
LOG("No connection to master!");
break; //Exit our loop, shut down.
}
} else framesSinceMasterDisconnect = 0;
@@ -151,7 +151,7 @@ int main(int argc, char** argv) {
std::this_thread::sleep_until(t);
}
Log::Info("Exited Main Loop! (signal {:d})", Game::lastSignal);
LOG("Exited Main Loop! (signal %d)", Game::lastSignal);
//Delete our objects here:
Database::Destroy("AuthServer");
delete Game::server;

View File

@@ -1,6 +1,6 @@
add_executable(AuthServer "AuthServer.cpp")
target_link_libraries(AuthServer PRIVATE ${COMMON_LIBRARIES} dServer)
target_link_libraries(AuthServer ${COMMON_LIBRARIES} dServer)
target_include_directories(AuthServer PRIVATE ${PROJECT_SOURCE_DIR}/dServer)

View File

@@ -5,12 +5,10 @@ set(DCHATSERVER_SOURCES
)
add_executable(ChatServer "ChatServer.cpp")
target_include_directories(ChatServer PRIVATE "${PROJECT_SOURCE_DIR}/dChatFilter")
add_library(dChatServer ${DCHATSERVER_SOURCES})
target_include_directories(dChatServer PRIVATE ${PROJECT_SOURCE_DIR}/dServer)
add_compile_definitions(ChatServer PRIVATE PROJECT_VERSION="\"${PROJECT_VERSION}\"")
add_library(dChatServer ${DCHATSERVER_SOURCES})
target_include_directories(dChatServer PRIVATE "${PROJECT_SOURCE_DIR}/dServer")
target_link_libraries(dChatServer PRIVATE ${COMMON_LIBRARIES} dChatFilter)
target_link_libraries(ChatServer PRIVATE ${COMMON_LIBRARIES} dChatFilter dChatServer dServer)
target_link_libraries(dChatServer ${COMMON_LIBRARIES} dChatFilter)
target_link_libraries(ChatServer ${COMMON_LIBRARIES} dChatFilter dChatServer dServer)

View File

@@ -27,16 +27,16 @@ void ChatIgnoreList::GetIgnoreList(Packet* packet) {
auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId);
if (!receiver) {
Log::Info("Tried to get ignore list, but player {:d} not found in container", playerId);
LOG("Tried to get ignore list, but player %llu not found in container", playerId);
return;
}
if (!receiver.ignoredPlayers.empty()) {
Log::Debug("Player {:d} already has an ignore list, but is requesting it again.", playerId);
LOG_DEBUG("Player %llu already has an ignore list, but is requesting it again.", playerId);
} else {
auto ignoreList = Database::Get()->GetIgnoreList(static_cast<uint32_t>(playerId));
if (ignoreList.empty()) {
Log::Debug("Player {:d} has no ignores", playerId);
LOG_DEBUG("Player %llu has no ignores", playerId);
return;
}
@@ -59,7 +59,7 @@ void ChatIgnoreList::GetIgnoreList(Packet* packet) {
bitStream.Write(LUWString(ignoredPlayer.playerName, 36));
}
Game::server->Send(bitStream, packet->systemAddress, false);
Game::server->Send(&bitStream, packet->systemAddress, false);
}
void ChatIgnoreList::AddIgnore(Packet* packet) {
@@ -69,13 +69,13 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId);
if (!receiver) {
Log::Info("Tried to get ignore list, but player {:d} not found in container", playerId);
LOG("Tried to get ignore list, but player %llu not found in container", playerId);
return;
}
constexpr int32_t MAX_IGNORES = 32;
if (receiver.ignoredPlayers.size() > MAX_IGNORES) {
Log::Debug("Player {:d} has too many ignores", playerId);
LOG_DEBUG("Player %llu has too many ignores", playerId);
return;
}
@@ -91,11 +91,11 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
// Check if the player exists
LWOOBJID ignoredPlayerId = LWOOBJID_EMPTY;
if (toIgnoreStr == receiver.playerName || toIgnoreStr.find("[GM]") == 0) {
Log::Debug("Player {:d} tried to ignore themselves", playerId);
LOG_DEBUG("Player %llu tried to ignore themselves", playerId);
bitStream.Write(ChatIgnoreList::AddResponse::GENERAL_ERROR);
} else if (std::count(receiver.ignoredPlayers.begin(), receiver.ignoredPlayers.end(), toIgnoreStr) > 0) {
Log::Debug("Player {:d} is already ignoring {:s}", playerId, toIgnoreStr);
LOG_DEBUG("Player %llu is already ignoring %s", playerId, toIgnoreStr.c_str());
bitStream.Write(ChatIgnoreList::AddResponse::ALREADY_IGNORED);
} else {
@@ -105,7 +105,7 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
// Fall back to query
auto player = Database::Get()->GetCharacterInfo(toIgnoreStr);
if (!player || player->name != toIgnoreStr) {
Log::Debug("Player {:s} not found", toIgnoreStr);
LOG_DEBUG("Player %s not found", toIgnoreStr.c_str());
} else {
ignoredPlayerId = player->id;
}
@@ -119,7 +119,7 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
GeneralUtils::SetBit(ignoredPlayerId, eObjectBits::PERSISTENT);
receiver.ignoredPlayers.emplace_back(toIgnoreStr, ignoredPlayerId);
Log::Debug("Player {:d} is ignoring {:s}", playerId, toIgnoreStr);
LOG_DEBUG("Player %llu is ignoring %s", playerId, toIgnoreStr.c_str());
bitStream.Write(ChatIgnoreList::AddResponse::SUCCESS);
} else {
@@ -131,7 +131,7 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
bitStream.Write(playerNameSend);
bitStream.Write(ignoredPlayerId);
Game::server->Send(bitStream, packet->systemAddress, false);
Game::server->Send(&bitStream, packet->systemAddress, false);
}
void ChatIgnoreList::RemoveIgnore(Packet* packet) {
@@ -141,7 +141,7 @@ void ChatIgnoreList::RemoveIgnore(Packet* packet) {
auto& receiver = Game::playerContainer.GetPlayerDataMutable(playerId);
if (!receiver) {
Log::Info("Tried to get ignore list, but player {:d} not found in container", playerId);
LOG("Tried to get ignore list, but player %llu not found in container", playerId);
return;
}
@@ -153,7 +153,7 @@ void ChatIgnoreList::RemoveIgnore(Packet* packet) {
auto toRemove = std::remove(receiver.ignoredPlayers.begin(), receiver.ignoredPlayers.end(), removedIgnoreStr);
if (toRemove == receiver.ignoredPlayers.end()) {
Log::Debug("Player {:d} is not ignoring {:s}", playerId, removedIgnoreStr);
LOG_DEBUG("Player %llu is not ignoring %s", playerId, removedIgnoreStr.c_str());
return;
}
@@ -167,5 +167,5 @@ void ChatIgnoreList::RemoveIgnore(Packet* packet) {
LUWString playerNameSend(removedIgnoreStr, 33);
bitStream.Write(playerNameSend);
Game::server->Send(bitStream, packet->systemAddress, false);
Game::server->Send(&bitStream, packet->systemAddress, false);
}

View File

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

View File

@@ -60,9 +60,9 @@ int main(int argc, char** argv) {
//Read our config:
Log::Info("Starting Chat server...");
Log::Info("Version: {:s}", PROJECT_VERSION);
Log::Info("Compiled on: {:s}", __TIMESTAMP__);
LOG("Starting Chat server...");
LOG("Version: %s", PROJECT_VERSION);
LOG("Compiled on: %s", __TIMESTAMP__);
try {
std::string clientPathStr = Game::config->GetValue("client_location");
@@ -74,7 +74,7 @@ int main(int argc, char** argv) {
Game::assetManager = new AssetManager(clientPath);
} catch (std::runtime_error& ex) {
Log::Info("Got an error while setting up assets: {:s}", ex.what());
LOG("Got an error while setting up assets: %s", ex.what());
return EXIT_FAILURE;
}
@@ -83,7 +83,7 @@ int main(int argc, char** argv) {
try {
Database::Connect();
} catch (sql::SQLException& ex) {
Log::Info("Got an error while connecting to the database: {:s}", ex.what());
LOG("Got an error while connecting to the database: %s", ex.what());
Database::Destroy("ChatServer");
delete Game::server;
delete Game::logger;
@@ -101,7 +101,7 @@ int main(int argc, char** argv) {
//It's safe to pass 'localhost' here, as the IP is only used as the external IP.
std::string ourIP = "localhost";
const uint32_t maxClients = GeneralUtils::TryParse<uint32_t>(Game::config->GetValue("max_clients")).value_or(999);
const uint32_t ourPort = GeneralUtils::TryParse<uint32_t>(Game::config->GetValue("chat_server_port")).value_or(2005);
const uint32_t ourPort = GeneralUtils::TryParse<uint32_t>(Game::config->GetValue("chat_server_port")).value_or(1501);
const auto externalIPString = Game::config->GetValue("external_ip");
if (!externalIPString.empty()) ourIP = externalIPString;
@@ -181,11 +181,11 @@ int main(int argc, char** argv) {
void HandlePacket(Packet* packet) {
if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) {
Log::Info("A server has disconnected, erasing their connected players from the list.");
LOG("A server has disconnected, erasing their connected players from the list.");
}
if (packet->data[0] == ID_NEW_INCOMING_CONNECTION) {
Log::Info("A server is connecting, awaiting user list.");
LOG("A server is connecting, awaiting user list.");
}
if (packet->length < 4) return; // Nothing left to process. Need 4 bytes to continue.
@@ -211,12 +211,12 @@ void HandlePacket(Packet* packet) {
case eChatInternalMessageType::ANNOUNCEMENT: {
//we just forward this packet to every connected server
CINSTREAM;
Game::server->Send(inStream, packet->systemAddress, true); //send to everyone except origin
Game::server->Send(&inStream, packet->systemAddress, true); //send to everyone except origin
break;
}
default:
Log::Info("Unknown CHAT_INTERNAL id: {:d}", static_cast<int>(packet->data[3]));
LOG("Unknown CHAT_INTERNAL id: %i", int(packet->data[3]));
}
}
@@ -343,22 +343,22 @@ void HandlePacket(Packet* packet) {
case eChatMessageType::PRG_CSR_COMMAND:
case eChatMessageType::HEARTBEAT_REQUEST_FROM_WORLD:
case eChatMessageType::UPDATE_FREE_TRIAL_STATUS:
Log::Info("Unhandled CHAT Message id: {:s} {:d}", StringifiedEnum::ToString(chat_message_type), GeneralUtils::ToUnderlying(chat_message_type));
LOG("Unhandled CHAT Message id: %s (%i)", StringifiedEnum::ToString(chat_message_type).data(), chat_message_type);
break;
default:
Log::Info("Unknown CHAT Message id: {:d}", GeneralUtils::ToUnderlying(chat_message_type));
LOG("Unknown CHAT Message id: %i", chat_message_type);
}
}
if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::WORLD) {
switch (static_cast<eWorldMessageType>(packet->data[3])) {
case eWorldMessageType::ROUTE_PACKET: {
Log::Info("Routing packet from world");
LOG("Routing packet from world");
break;
}
default:
Log::Info("Unknown World id: {:d}", static_cast<int>(packet->data[3]));
LOG("Unknown World id: %i", int(packet->data[3]));
}
}
}

View File

@@ -28,7 +28,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) {
CINSTREAM_SKIP_HEADER;
LWOOBJID playerId;
if (!inStream.Read(playerId)) {
Log::Warn("Failed to read player ID");
LOG("Failed to read player ID");
return;
}
@@ -50,7 +50,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) {
m_Names[data.playerID] = GeneralUtils::UTF8ToUTF16(data.playerName);
Log::Info("Added user: {:s} ({:d}), zone: {:d}", data.playerName, data.playerID, data.zoneID.GetMapID());
LOG("Added user: %s (%llu), zone: %i", data.playerName.c_str(), data.playerID, data.zoneID.GetMapID());
Database::Get()->UpdateActivityLog(data.playerID, eActivityType::PlayerLoggedIn, data.zoneID.GetMapID());
}
@@ -64,7 +64,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) {
const auto& player = GetPlayerData(playerID);
if (!player) {
Log::Info("Failed to find user: {:d}", playerID);
LOG("Failed to find user: %llu", playerID);
return;
}
@@ -87,7 +87,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) {
}
}
Log::Info("Removed user: {:d}", playerID);
LOG("Removed user: %llu", playerID);
m_Players.erase(playerID);
Database::Get()->UpdateActivityLog(playerID, eActivityType::PlayerLoggedOut, player.zoneID.GetMapID());
@@ -103,7 +103,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) {
auto& player = this->GetPlayerDataMutable(playerID);
if (!player) {
Log::Warn("Failed to find user: {:d}", playerID);
LOG("Failed to find user: %llu", playerID);
return;
}
@@ -150,7 +150,7 @@ void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) {
bitStream.Write(player);
bitStream.Write(time);
Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true);
Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true);
}
TeamData* PlayerContainer::CreateLocalTeam(std::vector<LWOOBJID> members) {
@@ -207,7 +207,7 @@ TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) {
void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) {
if (team->memberIDs.size() >= 4) {
Log::Warn("Tried to add player to team that already had 4 players");
LOG("Tried to add player to team that already had 4 players");
const auto& player = GetPlayerData(playerID);
if (!player) return;
ChatPackets::SendSystemMessage(player.sysAddr, u"The teams is full! You have not been added to a team!");
@@ -365,7 +365,7 @@ void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) {
}
}
Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true);
Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true);
}
std::u16string PlayerContainer::GetName(LWOOBJID playerID) {

View File

@@ -9,11 +9,12 @@
* AMF3 Deserializer written by EmosewaMC
*/
AMFBaseValue* AMFDeserialize::Read(RakNet::BitStream& inStream) {
AMFBaseValue* AMFDeserialize::Read(RakNet::BitStream* inStream) {
if (!inStream) return nullptr;
AMFBaseValue* returnValue = nullptr;
// Read in the value type from the bitStream
eAmf marker;
inStream.Read(marker);
inStream->Read(marker);
// Based on the typing, create the value associated with that and return the base value class
switch (marker) {
case eAmf::Undefined: {
@@ -78,13 +79,13 @@ AMFBaseValue* AMFDeserialize::Read(RakNet::BitStream& inStream) {
return returnValue;
}
uint32_t AMFDeserialize::ReadU29(RakNet::BitStream& inStream) {
uint32_t AMFDeserialize::ReadU29(RakNet::BitStream* inStream) {
bool byteFlag = true;
uint32_t actualNumber{};
uint8_t numberOfBytesRead{};
while (byteFlag && numberOfBytesRead < 4) {
uint8_t byte{};
inStream.Read(byte);
inStream->Read(byte);
// Parse the byte
if (numberOfBytesRead < 3) {
byteFlag = byte & static_cast<uint8_t>(1 << 7);
@@ -100,7 +101,7 @@ uint32_t AMFDeserialize::ReadU29(RakNet::BitStream& inStream) {
return actualNumber;
}
const std::string AMFDeserialize::ReadString(RakNet::BitStream& inStream) {
const std::string AMFDeserialize::ReadString(RakNet::BitStream* inStream) {
auto length = ReadU29(inStream);
// Check if this is a reference
bool isReference = length % 2 == 1;
@@ -108,7 +109,7 @@ const std::string AMFDeserialize::ReadString(RakNet::BitStream& inStream) {
length = length >> 1;
if (isReference) {
std::string value(length, 0);
inStream.Read(&value[0], length);
inStream->Read(&value[0], length);
// Empty strings are never sent by reference
if (!value.empty()) accessedElements.push_back(value);
return value;
@@ -118,20 +119,20 @@ const std::string AMFDeserialize::ReadString(RakNet::BitStream& inStream) {
}
}
AMFBaseValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream& inStream) {
AMFBaseValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream* inStream) {
double value;
inStream.Read<double>(value);
inStream->Read<double>(value);
return new AMFDoubleValue(value);
}
AMFBaseValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream& inStream) {
AMFBaseValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) {
auto arrayValue = new AMFArrayValue();
// Read size of dense array
const auto sizeOfDenseArray = (ReadU29(inStream) >> 1);
auto sizeOfDenseArray = (ReadU29(inStream) >> 1);
// Then read associative portion
while (true) {
const auto key = ReadString(inStream);
auto key = ReadString(inStream);
// No more associative values when we encounter an empty string key
if (key.size() == 0) break;
arrayValue->Insert(key, Read(inStream));
@@ -143,10 +144,10 @@ AMFBaseValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream& inStream) {
return arrayValue;
}
AMFBaseValue* AMFDeserialize::ReadAmfString(RakNet::BitStream& inStream) {
AMFBaseValue* AMFDeserialize::ReadAmfString(RakNet::BitStream* inStream) {
return new AMFStringValue(ReadString(inStream));
}
AMFBaseValue* AMFDeserialize::ReadAmfInteger(RakNet::BitStream& inStream) {
AMFBaseValue* AMFDeserialize::ReadAmfInteger(RakNet::BitStream* inStream) {
return new AMFIntValue(ReadU29(inStream));
}

View File

@@ -15,7 +15,7 @@ public:
* @param inStream inStream to read value from.
* @return Returns an AMFValue with all the information from the bitStream in it.
*/
AMFBaseValue* Read(RakNet::BitStream& inStream);
AMFBaseValue* Read(RakNet::BitStream* inStream);
private:
/**
* @brief Private method to read a U29 integer from a bitstream
@@ -23,7 +23,7 @@ private:
* @param inStream bitstream to read data from
* @return The number as an unsigned 29 bit integer
*/
static uint32_t ReadU29(RakNet::BitStream& inStream);
uint32_t ReadU29(RakNet::BitStream* inStream);
/**
* @brief Reads a string from a bitstream
@@ -31,7 +31,7 @@ private:
* @param inStream bitStream to read data from
* @return The read string
*/
const std::string ReadString(RakNet::BitStream& inStream);
const std::string ReadString(RakNet::BitStream* inStream);
/**
* @brief Read an AMFDouble value from a bitStream
@@ -39,7 +39,7 @@ private:
* @param inStream bitStream to read data from
* @return Double value represented as an AMFValue
*/
AMFBaseValue* ReadAmfDouble(RakNet::BitStream& inStream);
AMFBaseValue* ReadAmfDouble(RakNet::BitStream* inStream);
/**
* @brief Read an AMFArray from a bitStream
@@ -47,7 +47,7 @@ private:
* @param inStream bitStream to read data from
* @return Array value represented as an AMFValue
*/
AMFBaseValue* ReadAmfArray(RakNet::BitStream& inStream);
AMFBaseValue* ReadAmfArray(RakNet::BitStream* inStream);
/**
* @brief Read an AMFString from a bitStream
@@ -55,7 +55,7 @@ private:
* @param inStream bitStream to read data from
* @return String value represented as an AMFValue
*/
AMFBaseValue* ReadAmfString(RakNet::BitStream& inStream);
AMFBaseValue* ReadAmfString(RakNet::BitStream* inStream);
/**
* @brief Read an AMFInteger from a bitStream
@@ -63,7 +63,7 @@ private:
* @param inStream bitStream to read data from
* @return Integer value represented as an AMFValue
*/
AMFBaseValue* ReadAmfInteger(RakNet::BitStream& inStream);
AMFBaseValue* ReadAmfInteger(RakNet::BitStream* inStream);
/**
* List of strings read so far saved to be read by reference.

View File

@@ -41,14 +41,12 @@ template <typename ValueType>
class AMFValue : public AMFBaseValue {
public:
AMFValue() = default;
AMFValue(const ValueType value) : m_Data{ value } {}
AMFValue(const ValueType value) { m_Data = value; }
virtual ~AMFValue() override = default;
[[nodiscard]] constexpr eAmf GetValueType() const noexcept override;
[[nodiscard]] const ValueType& GetValue() const { return m_Data; }
void SetValue(const ValueType value) { m_Data = value; }
protected:
@@ -56,7 +54,7 @@ protected:
};
// Explicit template class instantiations
template class AMFValue<std::nullptr_t>;
template class AMFValue<std::nullptr_t>;
template class AMFValue<bool>;
template class AMFValue<int32_t>;
template class AMFValue<uint32_t>;
@@ -112,7 +110,7 @@ public:
[[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::Array; }
~AMFArrayValue() override {
for (const auto* valueToDelete : GetDense()) {
for (auto valueToDelete : GetDense()) {
if (valueToDelete) {
delete valueToDelete;
valueToDelete = nullptr;
@@ -129,12 +127,12 @@ public:
/**
* Returns the Associative portion of the object
*/
[[nodiscard]] inline const AMFAssociative& GetAssociative() const noexcept { return m_Associative; }
[[nodiscard]] inline AMFAssociative& GetAssociative() noexcept { return this->associative; }
/**
* Returns the dense portion of the object
*/
[[nodiscard]] inline const AMFDense& GetDense() const noexcept { return m_Dense; }
[[nodiscard]] inline AMFDense& GetDense() noexcept { return this->dense; }
/**
* Inserts an AMFValue into the associative portion with the given key.
@@ -152,12 +150,12 @@ public:
*/
template <typename ValueType>
[[maybe_unused]] std::pair<AMFValue<ValueType>*, bool> Insert(const std::string& key, const ValueType value) {
const auto element = m_Associative.find(key);
auto element = associative.find(key);
AMFValue<ValueType>* val = nullptr;
bool found = true;
if (element == m_Associative.cend()) {
if (element == associative.end()) {
val = new AMFValue<ValueType>(value);
m_Associative.emplace(key, val);
associative.insert(std::make_pair(key, val));
} else {
val = dynamic_cast<AMFValue<ValueType>*>(element->second);
found = false;
@@ -167,12 +165,12 @@ public:
// Associates an array with a string key
[[maybe_unused]] std::pair<AMFBaseValue*, bool> Insert(const std::string& key) {
const auto element = m_Associative.find(key);
auto element = associative.find(key);
AMFArrayValue* val = nullptr;
bool found = true;
if (element == m_Associative.cend()) {
if (element == associative.end()) {
val = new AMFArrayValue();
m_Associative.emplace(key, val);
associative.insert(std::make_pair(key, val));
} else {
val = dynamic_cast<AMFArrayValue*>(element->second);
found = false;
@@ -184,13 +182,13 @@ public:
[[maybe_unused]] std::pair<AMFBaseValue*, bool> Insert(const size_t index) {
AMFArrayValue* val = nullptr;
bool inserted = false;
if (index >= m_Dense.size()) {
m_Dense.resize(index + 1);
if (index >= dense.size()) {
dense.resize(index + 1);
val = new AMFArrayValue();
m_Dense.at(index) = val;
dense.at(index) = val;
inserted = true;
}
return std::make_pair(dynamic_cast<AMFArrayValue*>(m_Dense.at(index)), inserted);
return std::make_pair(dynamic_cast<AMFArrayValue*>(dense.at(index)), inserted);
}
/**
@@ -207,13 +205,13 @@ public:
[[maybe_unused]] std::pair<AMFValue<ValueType>*, bool> Insert(const size_t index, const ValueType value) {
AMFValue<ValueType>* val = nullptr;
bool inserted = false;
if (index >= m_Dense.size()) {
m_Dense.resize(index + 1);
if (index >= this->dense.size()) {
this->dense.resize(index + 1);
val = new AMFValue<ValueType>(value);
m_Dense.at(index) = val;
this->dense.at(index) = val;
inserted = true;
}
return std::make_pair(dynamic_cast<AMFValue<ValueType>*>(m_Dense.at(index)), inserted);
return std::make_pair(dynamic_cast<AMFValue<ValueType>*>(this->dense.at(index)), inserted);
}
/**
@@ -226,12 +224,12 @@ public:
* @param value The value to insert
*/
void Insert(const std::string& key, AMFBaseValue* const value) {
const auto element = m_Associative.find(key);
if (element != m_Associative.cend() && element->second) {
auto element = associative.find(key);
if (element != associative.end() && element->second) {
delete element->second;
element->second = value;
} else {
m_Associative.emplace(key, value);
associative.insert(std::make_pair(key, value));
}
}
@@ -245,13 +243,13 @@ public:
* @param value The value to insert
*/
void Insert(const size_t index, AMFBaseValue* const value) {
if (index < m_Dense.size()) {
const AMFDense::const_iterator itr = m_Dense.cbegin() + index;
if (*itr) delete m_Dense.at(index);
if (index < dense.size()) {
AMFDense::iterator itr = dense.begin() + index;
if (*itr) delete dense.at(index);
} else {
m_Dense.resize(index + 1);
dense.resize(index + 1);
}
m_Dense.at(index) = value;
dense.at(index) = value;
}
/**
@@ -266,7 +264,7 @@ public:
*/
template <typename ValueType>
[[maybe_unused]] inline AMFValue<ValueType>* Push(const ValueType value) {
return Insert(m_Dense.size(), value).first;
return Insert(this->dense.size(), value).first;
}
/**
@@ -277,10 +275,10 @@ public:
* @param key The key to remove from the associative portion
*/
void Remove(const std::string& key, const bool deleteValue = true) {
const AMFAssociative::const_iterator it = m_Associative.find(key);
if (it != m_Associative.cend()) {
AMFAssociative::iterator it = this->associative.find(key);
if (it != this->associative.end()) {
if (deleteValue) delete it->second;
m_Associative.erase(it);
this->associative.erase(it);
}
}
@@ -288,24 +286,27 @@ public:
* Pops the last element in the dense portion, deleting it in the process.
*/
void Remove(const size_t index) {
if (!m_Dense.empty() && index < m_Dense.size()) {
const auto itr = m_Dense.cbegin() + index;
if (!this->dense.empty() && index < this->dense.size()) {
auto itr = this->dense.begin() + index;
if (*itr) delete (*itr);
m_Dense.erase(itr);
this->dense.erase(itr);
}
}
void Pop() {
if (!m_Dense.empty()) Remove(m_Dense.size() - 1);
if (!this->dense.empty()) Remove(this->dense.size() - 1);
}
[[nodiscard]] AMFArrayValue* GetArray(const std::string& key) const {
const AMFAssociative::const_iterator it = m_Associative.find(key);
return it != m_Associative.cend() ? dynamic_cast<AMFArrayValue*>(it->second) : nullptr;
[[nodiscard]] AMFArrayValue* GetArray(const std::string& key) {
AMFAssociative::const_iterator it = this->associative.find(key);
if (it != this->associative.end()) {
return dynamic_cast<AMFArrayValue*>(it->second);
}
return nullptr;
}
[[nodiscard]] AMFArrayValue* GetArray(const size_t index) const {
return index < m_Dense.size() ? dynamic_cast<AMFArrayValue*>(m_Dense.at(index)) : nullptr;
[[nodiscard]] AMFArrayValue* GetArray(const size_t index) {
return index >= this->dense.size() ? nullptr : dynamic_cast<AMFArrayValue*>(this->dense.at(index));
}
[[maybe_unused]] inline AMFArrayValue* InsertArray(const std::string& key) {
@@ -317,7 +318,7 @@ public:
}
[[maybe_unused]] inline AMFArrayValue* PushArray() {
return static_cast<AMFArrayValue*>(Insert(m_Dense.size()).first);
return static_cast<AMFArrayValue*>(Insert(this->dense.size()).first);
}
/**
@@ -331,16 +332,16 @@ public:
*/
template <typename AmfType>
[[nodiscard]] AMFValue<AmfType>* Get(const std::string& key) const {
const AMFAssociative::const_iterator it = m_Associative.find(key);
return it != m_Associative.cend() ?
AMFAssociative::const_iterator it = this->associative.find(key);
return it != this->associative.end() ?
dynamic_cast<AMFValue<AmfType>*>(it->second) :
nullptr;
}
// Get from the array but dont cast it
[[nodiscard]] AMFBaseValue* Get(const std::string& key) const {
const AMFAssociative::const_iterator it = m_Associative.find(key);
return it != m_Associative.cend() ? it->second : nullptr;
AMFAssociative::const_iterator it = this->associative.find(key);
return it != this->associative.end() ? it->second : nullptr;
}
/**
@@ -354,27 +355,27 @@ public:
*/
template <typename AmfType>
[[nodiscard]] AMFValue<AmfType>* Get(const size_t index) const {
return index < m_Dense.size() ?
dynamic_cast<AMFValue<AmfType>*>(m_Dense.at(index)) :
return index < this->dense.size() ?
dynamic_cast<AMFValue<AmfType>*>(this->dense.at(index)) :
nullptr;
}
// Get from the dense but dont cast it
[[nodiscard]] AMFBaseValue* Get(const size_t index) const {
return index < m_Dense.size() ? m_Dense.at(index) : nullptr;
return index < this->dense.size() ? this->dense.at(index) : nullptr;
}
private:
/**
* The associative portion. These values are key'd with strings to an AMFValue.
*/
AMFAssociative m_Associative;
AMFAssociative associative;
/**
* The dense portion. These AMFValue's are stored one after
* another with the most recent addition being at the back.
*/
AMFDense m_Dense;
AMFDense dense;
};
#endif //!__AMF3__H__

View File

@@ -29,7 +29,7 @@ void RakNet::BitStream::Write<AMFBaseValue&>(AMFBaseValue& value) {
break;
}
default: {
Log::Warn("Encountered unwritable AMFType {:d}!", GeneralUtils::ToUnderlying(type));
LOG("Encountered unwritable AMFType %i!", type);
}
case eAmf::Undefined:
case eAmf::Null:
@@ -53,7 +53,7 @@ void RakNet::BitStream::Write<AMFBaseValue&>(AMFBaseValue& value) {
* A private function to write an value to a RakNet::BitStream
* RakNet writes in the correct byte order - do not reverse this.
*/
void WriteUInt29(RakNet::BitStream& bs, uint32_t v) {
void WriteUInt29(RakNet::BitStream* bs, uint32_t v) {
unsigned char b4 = static_cast<unsigned char>(v);
if (v < 0x00200000) {
b4 = b4 & 0x7F;
@@ -65,10 +65,10 @@ void WriteUInt29(RakNet::BitStream& bs, uint32_t v) {
unsigned char b2;
v = v >> 7;
b2 = static_cast<unsigned char>(v) | 0x80;
bs.Write(b2);
bs->Write(b2);
}
bs.Write(b3);
bs->Write(b3);
}
} else {
unsigned char b1;
@@ -82,19 +82,19 @@ void WriteUInt29(RakNet::BitStream& bs, uint32_t v) {
v = v >> 7;
b1 = static_cast<unsigned char>(v) | 0x80;
bs.Write(b1);
bs.Write(b2);
bs.Write(b3);
bs->Write(b1);
bs->Write(b2);
bs->Write(b3);
}
bs.Write(b4);
bs->Write(b4);
}
/**
* Writes a flag number to a RakNet::BitStream
* RakNet writes in the correct byte order - do not reverse this.
*/
void WriteFlagNumber(RakNet::BitStream& bs, uint32_t v) {
void WriteFlagNumber(RakNet::BitStream* bs, uint32_t v) {
v = (v << 1) | 0x01;
WriteUInt29(bs, v);
}
@@ -104,9 +104,9 @@ void WriteFlagNumber(RakNet::BitStream& bs, uint32_t v) {
*
* RakNet writes in the correct byte order - do not reverse this.
*/
void WriteAMFString(RakNet::BitStream& bs, const std::string& str) {
void WriteAMFString(RakNet::BitStream* bs, const std::string& str) {
WriteFlagNumber(bs, static_cast<uint32_t>(str.size()));
bs.Write(str.c_str(), static_cast<uint32_t>(str.size()));
bs->Write(str.c_str(), static_cast<uint32_t>(str.size()));
}
/**
@@ -114,8 +114,8 @@ void WriteAMFString(RakNet::BitStream& bs, const std::string& str) {
*
* RakNet writes in the correct byte order - do not reverse this.
*/
void WriteAMFU16(RakNet::BitStream& bs, uint16_t value) {
bs.Write(value);
void WriteAMFU16(RakNet::BitStream* bs, uint16_t value) {
bs->Write(value);
}
/**
@@ -123,8 +123,8 @@ void WriteAMFU16(RakNet::BitStream& bs, uint16_t value) {
*
* RakNet writes in the correct byte order - do not reverse this.
*/
void WriteAMFU32(RakNet::BitStream& bs, uint32_t value) {
bs.Write(value);
void WriteAMFU32(RakNet::BitStream* bs, uint32_t value) {
bs->Write(value);
}
/**
@@ -132,40 +132,40 @@ void WriteAMFU32(RakNet::BitStream& bs, uint32_t value) {
*
* RakNet writes in the correct byte order - do not reverse this.
*/
void WriteAMFU64(RakNet::BitStream& bs, uint64_t value) {
bs.Write(value);
void WriteAMFU64(RakNet::BitStream* bs, uint64_t value) {
bs->Write(value);
}
// Writes an AMFIntegerValue to BitStream
template<>
void RakNet::BitStream::Write<AMFIntValue&>(AMFIntValue& value) {
WriteUInt29(*this, value.GetValue());
WriteUInt29(this, value.GetValue());
}
// Writes an AMFDoubleValue to BitStream
template<>
void RakNet::BitStream::Write<AMFDoubleValue&>(AMFDoubleValue& value) {
double d = value.GetValue();
WriteAMFU64(*this, *reinterpret_cast<uint64_t*>(&d));
WriteAMFU64(this, *reinterpret_cast<uint64_t*>(&d));
}
// Writes an AMFStringValue to BitStream
template<>
void RakNet::BitStream::Write<AMFStringValue&>(AMFStringValue& value) {
WriteAMFString(*this, value.GetValue());
WriteAMFString(this, value.GetValue());
}
// Writes an AMFArrayValue to BitStream
template<>
void RakNet::BitStream::Write<AMFArrayValue&>(AMFArrayValue& value) {
uint32_t denseSize = value.GetDense().size();
WriteFlagNumber(*this, denseSize);
WriteFlagNumber(this, denseSize);
auto it = value.GetAssociative().begin();
auto end = value.GetAssociative().end();
while (it != end) {
WriteAMFString(*this, it->first);
WriteAMFString(this, it->first);
this->Write<AMFBaseValue&>(*it->second);
it++;
}

View File

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

View File

@@ -30,15 +30,11 @@ foreach(file ${DCOMMON_DCLIENT_SOURCES})
set(DCOMMON_SOURCES ${DCOMMON_SOURCES} "dClient/${file}")
endforeach()
include_directories(${PROJECT_SOURCE_DIR}/dCommon/)
add_library(dCommon STATIC ${DCOMMON_SOURCES})
target_include_directories(dCommon
PUBLIC "." "dClient" "dEnums"
PRIVATE
"${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase"
"${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase/ITables"
"${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase"
"${PROJECT_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include"
)
target_link_libraries(dCommon bcrypt dDatabase tinyxml2)
if (UNIX)
find_package(ZLIB REQUIRED)
@@ -69,7 +65,4 @@ else ()
)
endif ()
target_link_libraries(dCommon
PUBLIC fmt
PRIVATE ZLIB::ZLIB bcrypt tinyxml2
INTERFACE dDatabase)
target_link_libraries(dCommon ZLIB::ZLIB)

View File

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

View File

@@ -2,6 +2,7 @@
#define __DLUASSERT__H__
#include <assert.h>
#define _DEBUG
#ifdef _DEBUG
# define DluAssert(expression) assert(expression)

View File

@@ -42,7 +42,7 @@ bool FdbToSqlite::Convert::ConvertDatabase(AssetStream& buffer) {
CDClientDatabase::ExecuteQuery("COMMIT;");
} catch (CppSQLite3Exception& e) {
Log::Warn("Encountered error {:s} converting FDB to SQLite", e.errorMessage());
LOG("Encountered error %s converting FDB to SQLite", e.errorMessage());
return false;
}

View File

@@ -278,14 +278,14 @@ std::vector<std::string> GeneralUtils::SplitString(const std::string& str, char
return vector;
}
std::u16string GeneralUtils::ReadWString(RakNet::BitStream& inStream) {
std::u16string GeneralUtils::ReadWString(RakNet::BitStream* inStream) {
uint32_t length;
inStream.Read<uint32_t>(length);
inStream->Read<uint32_t>(length);
std::u16string string;
for (auto i = 0; i < length; i++) {
uint16_t c;
inStream.Read(c);
inStream->Read(c);
string.push_back(c);
}
@@ -294,50 +294,28 @@ std::u16string GeneralUtils::ReadWString(RakNet::BitStream& inStream) {
std::vector<std::string> GeneralUtils::GetSqlFileNamesFromFolder(const std::string& folder) {
// Because we dont know how large the initial number before the first _ is we need to make it a map like so.
std::map<uint32_t, std::string> filenames{};
std::map<uint32_t, std::string> filenames{};
for (auto& t : std::filesystem::directory_iterator(folder)) {
auto filename = t.path().filename().string();
auto index = std::stoi(GeneralUtils::SplitString(filename, '_').at(0));
filenames.insert(std::make_pair(index, filename));
auto filename = t.path().filename().string();
auto index = std::stoi(GeneralUtils::SplitString(filename, '_').at(0));
filenames.insert(std::make_pair(index, filename));
}
// Now sort the map by the oldest migration.
std::vector<std::string> sortedFiles{};
auto fileIterator = filenames.begin();
std::map<uint32_t, std::string>::iterator oldest = filenames.begin();
while (!filenames.empty()) {
auto fileIterator = filenames.begin();
std::map<uint32_t, std::string>::iterator oldest = filenames.begin();
while (!filenames.empty()) {
if (fileIterator == filenames.end()) {
sortedFiles.push_back(oldest->second);
filenames.erase(oldest);
fileIterator = filenames.begin();
oldest = filenames.begin();
continue;
sortedFiles.push_back(oldest->second);
filenames.erase(oldest);
fileIterator = filenames.begin();
oldest = filenames.begin();
continue;
}
if (oldest->first > fileIterator->first) oldest = fileIterator;
fileIterator++;
if (oldest->first > fileIterator->first) oldest = fileIterator;
fileIterator++;
}
return sortedFiles;
}
#ifdef DARKFLAME_PLATFORM_MACOS
// MacOS floating-point parse function specializations
namespace GeneralUtils::details {
template <>
[[nodiscard]] float _parse<float>(const std::string_view str, size_t& parseNum) {
return std::stof(std::string{ str }, &parseNum);
}
template <>
[[nodiscard]] double _parse<double>(const std::string_view str, size_t& parseNum) {
return std::stod(std::string{ str }, &parseNum);
}
template <>
[[nodiscard]] long double _parse<long double>(const std::string_view str, size_t& parseNum) {
return std::stold(std::string{ str }, &parseNum);
}
}
#endif

View File

@@ -116,7 +116,7 @@ namespace GeneralUtils {
bool ReplaceInString(std::string& str, const std::string& from, const std::string& to);
std::u16string ReadWString(RakNet::BitStream& inStream);
std::u16string ReadWString(RakNet::BitStream* inStream);
std::vector<std::wstring> SplitString(std::wstring& str, wchar_t delimiter);
@@ -168,10 +168,25 @@ namespace GeneralUtils {
#ifdef DARKFLAME_PLATFORM_MACOS
// MacOS floating-point parse helper function specializations
namespace details {
// Anonymous namespace containing MacOS floating-point parse function specializations
namespace {
template <std::floating_point T>
[[nodiscard]] T _parse(const std::string_view str, size_t& parseNum);
[[nodiscard]] T Parse(const std::string_view str, size_t* parseNum);
template <>
[[nodiscard]] float Parse<float>(const std::string_view str, size_t* parseNum) {
return std::stof(std::string{ str }, parseNum);
}
template <>
[[nodiscard]] double Parse<double>(const std::string_view str, size_t* parseNum) {
return std::stod(std::string{ str }, parseNum);
}
template <>
[[nodiscard]] long double Parse<long double>(const std::string_view str, size_t* parseNum) {
return std::stold(std::string{ str }, parseNum);
}
}
/**
@@ -181,10 +196,9 @@ namespace GeneralUtils {
* @returns An std::optional containing the desired value if it is equivalent to the string
*/
template <std::floating_point T>
[[nodiscard]] std::optional<T> TryParse(const std::string_view str) noexcept
try {
[[nodiscard]] std::optional<T> TryParse(const std::string_view str) noexcept try {
size_t parseNum;
const T result = details::_parse<T>(str, parseNum);
const T result = Parse<T>(str, &parseNum);
const bool isParsed = str.length() == parseNum;
return isParsed ? result : std::optional<T>{};
@@ -264,8 +278,8 @@ namespace GeneralUtils {
* @returns The enum entry's value in its underlying type
*/
template <Enum eType>
constexpr std::underlying_type_t<eType> ToUnderlying(const eType entry) noexcept {
return static_cast<std::underlying_type_t<eType>>(entry);
constexpr typename std::underlying_type_t<eType> CastUnderlyingType(const eType entry) noexcept {
return static_cast<typename std::underlying_type_t<eType>>(entry);
}
// 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 {
type = static_cast<eLDFType>(strtol(ldfTypeAndValue.first.data(), &storage, 10));
} catch (std::exception) {
Log::Warn("Attempted to process invalid ldf type ({:s}) from string ({:s})", ldfTypeAndValue.first, format);
LOG("Attempted to process invalid ldf type (%s) from string (%s)", ldfTypeAndValue.first.data(), format.data());
return nullptr;
}
@@ -63,7 +63,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_S32: {
const auto data = GeneralUtils::TryParse<int32_t>(ldfTypeAndValue.second);
if (!data) {
Log::Warn("Attempted to process invalid int32 value ({:s}) from string ({:s})", ldfTypeAndValue.second, format);
LOG("Warning: Attempted to process invalid int32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data());
return nullptr;
}
returnValue = new LDFData<int32_t>(key, data.value());
@@ -74,7 +74,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_FLOAT: {
const auto data = GeneralUtils::TryParse<float>(ldfTypeAndValue.second);
if (!data) {
Log::Warn("Attempted to process invalid float value ({:s}) from string ({:s})", ldfTypeAndValue.second, format);
LOG("Warning: Attempted to process invalid float value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data());
return nullptr;
}
returnValue = new LDFData<float>(key, data.value());
@@ -84,7 +84,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_DOUBLE: {
const auto data = GeneralUtils::TryParse<double>(ldfTypeAndValue.second);
if (!data) {
Log::Warn("Attempted to process invalid double value ({:s}) from string ({:s})", ldfTypeAndValue.second, format);
LOG("Warning: Attempted to process invalid double value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data());
return nullptr;
}
returnValue = new LDFData<double>(key, data.value());
@@ -102,7 +102,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
} else {
const auto dataOptional = GeneralUtils::TryParse<uint32_t>(ldfTypeAndValue.second);
if (!dataOptional) {
Log::Warn("Attempted to process invalid uint32 value ({:s}) from string ({:s})", ldfTypeAndValue.second, format);
LOG("Warning: Attempted to process invalid uint32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data());
return nullptr;
}
data = dataOptional.value();
@@ -122,7 +122,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
} else {
const auto dataOptional = GeneralUtils::TryParse<bool>(ldfTypeAndValue.second);
if (!dataOptional) {
Log::Warn("Attempted to process invalid bool value ({:s}) from string ({:s})", ldfTypeAndValue.second, format);
LOG("Warning: Attempted to process invalid bool value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data());
return nullptr;
}
data = dataOptional.value();
@@ -135,7 +135,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_U64: {
const auto data = GeneralUtils::TryParse<uint64_t>(ldfTypeAndValue.second);
if (!data) {
Log::Warn("Attempted to process invalid uint64 value ({:s}) from string ({:s})", ldfTypeAndValue.second, format);
LOG("Warning: Attempted to process invalid uint64 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data());
return nullptr;
}
returnValue = new LDFData<uint64_t>(key, data.value());
@@ -145,7 +145,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
case LDF_TYPE_OBJID: {
const auto data = GeneralUtils::TryParse<LWOOBJID>(ldfTypeAndValue.second);
if (!data) {
Log::Warn("Attempted to process invalid LWOOBJID value ({:s}) from string ({:s})", ldfTypeAndValue.second, format);
LOG("Warning: Attempted to process invalid LWOOBJID value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data());
return nullptr;
}
returnValue = new LDFData<LWOOBJID>(key, data.value());
@@ -159,12 +159,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) {
}
case LDF_TYPE_UNKNOWN: {
Log::Warn("Attempted to process invalid unknown value ({:s}) from string ({:s})", ldfTypeAndValue.second, format);
LOG("Warning: Attempted to process invalid unknown value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data());
break;
}
default: {
Log::Warn("Attempted to process invalid LDF type ({:d}) from string ({:s})", GeneralUtils::ToUnderlying(type), format);
LOG("Warning: Attempted to process invalid LDF type (%d) from string (%s)", type, format.data());
break;
}
}

View File

@@ -31,7 +31,7 @@ public:
virtual ~LDFBaseData() {}
virtual void WriteToPacket(RakNet::BitStream& packet) = 0;
virtual void WriteToPacket(RakNet::BitStream* packet) = 0;
virtual const std::u16string& GetKey() = 0;
@@ -62,17 +62,17 @@ private:
T value;
//! Writes the key to the packet
void WriteKey(RakNet::BitStream& packet) {
packet.Write<uint8_t>(this->key.length() * sizeof(uint16_t));
void WriteKey(RakNet::BitStream* packet) {
packet->Write<uint8_t>(this->key.length() * sizeof(uint16_t));
for (uint32_t i = 0; i < this->key.length(); ++i) {
packet.Write<uint16_t>(this->key[i]);
packet->Write<uint16_t>(this->key[i]);
}
}
//! Writes the value to the packet
void WriteValue(RakNet::BitStream& packet) {
packet.Write<uint8_t>(this->GetValueType());
packet.Write(this->value);
void WriteValue(RakNet::BitStream* packet) {
packet->Write<uint8_t>(this->GetValueType());
packet->Write(this->value);
}
public:
@@ -108,7 +108,7 @@ public:
/*!
\param packet The packet
*/
void WriteToPacket(RakNet::BitStream& packet) override {
void WriteToPacket(RakNet::BitStream* packet) override {
this->WriteKey(packet);
this->WriteValue(packet);
}
@@ -178,31 +178,31 @@ template<> inline eLDFType LDFData<std::string>::GetValueType(void) { return LDF
// The specialized version for std::u16string (UTF-16)
template<>
inline void LDFData<std::u16string>::WriteValue(RakNet::BitStream& packet) {
packet.Write<uint8_t>(this->GetValueType());
inline void LDFData<std::u16string>::WriteValue(RakNet::BitStream* packet) {
packet->Write<uint8_t>(this->GetValueType());
packet.Write<uint32_t>(this->value.length());
packet->Write<uint32_t>(this->value.length());
for (uint32_t i = 0; i < this->value.length(); ++i) {
packet.Write<uint16_t>(this->value[i]);
packet->Write<uint16_t>(this->value[i]);
}
}
// The specialized version for bool
template<>
inline void LDFData<bool>::WriteValue(RakNet::BitStream& packet) {
packet.Write<uint8_t>(this->GetValueType());
inline void LDFData<bool>::WriteValue(RakNet::BitStream* packet) {
packet->Write<uint8_t>(this->GetValueType());
packet.Write<uint8_t>(this->value);
packet->Write<uint8_t>(this->value);
}
// The specialized version for std::string (UTF-8)
template<>
inline void LDFData<std::string>::WriteValue(RakNet::BitStream& packet) {
packet.Write<uint8_t>(this->GetValueType());
inline void LDFData<std::string>::WriteValue(RakNet::BitStream* packet) {
packet->Write<uint8_t>(this->GetValueType());
packet.Write<uint32_t>(this->value.length());
packet->Write<uint32_t>(this->value.length());
for (uint32_t i = 0; i < this->value.length(); ++i) {
packet.Write<uint8_t>(this->value[i]);
packet->Write<uint8_t>(this->value[i]);
}
}

View File

@@ -29,7 +29,7 @@ void Writer::Flush() {
FileWriter::FileWriter(const char* outpath) {
m_Outfile = fopen(outpath, "wt");
if (!m_Outfile) fmt::println("Couldn't open {:s} for writing!", outpath);
if (!m_Outfile) printf("Couldn't open %s for writing!\n", outpath);
m_Outpath = outpath;
m_IsConsoleWriter = false;
}

View File

@@ -1,14 +1,6 @@
#pragma once
// fmt includes:
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/chrono.h>
// C++ includes:
#include <chrono>
#include <memory>
#include <source_location>
#include <string>
#include <vector>
@@ -23,88 +15,23 @@
// Calculate the filename at compile time from the path.
// We just do this by scanning the path for the last '/' or '\' character and returning the string after it.
constexpr const char* GetFileNameFromAbsolutePath(const char* path) {
const char* file = path;
while (*path) {
const char nextChar = *path++;
if (nextChar == '/' || nextChar == '\\') {
file = path;
}
}
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)...);
}
const char* file = path;
while (*path) {
char nextChar = *path++;
if (nextChar == '/' || nextChar == '\\') {
file = path;
}
}
return file;
}
// These have to have a constexpr variable to store the filename_and_line result in a local variable otherwise
// they will not be valid constexpr and will be evaluated at runtime instead of compile time!
// The full string is still stored in the binary, however the offset of the filename in the absolute paths
// is used in the instruction instead of the start of the absolute path.
//#define LOG(message, ...) do { auto str = FILENAME_AND_LINE; Game::logger->Log(str, message, ##__VA_ARGS__); } while(0)
//#define LOG(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__)
#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_TEST(message, ...) do { auto str = FILENAME_AND_LINE; Game::logger->LogDebug(str, message, ##__VA_ARGS__); Game::logger->Flush();} while(0)
// Writer class for writing data to files.
class Writer {

View File

@@ -6,14 +6,28 @@
struct RemoteInputInfo {
RemoteInputInfo() {
m_RemoteInputX = 0;
m_RemoteInputY = 0;
m_IsPowersliding = false;
m_IsModified = false;
}
void operator=(const RemoteInputInfo& other) {
m_RemoteInputX = other.m_RemoteInputX;
m_RemoteInputY = other.m_RemoteInputY;
m_IsPowersliding = other.m_IsPowersliding;
m_IsModified = other.m_IsModified;
}
bool operator==(const RemoteInputInfo& other) {
return m_RemoteInputX == other.m_RemoteInputX && m_RemoteInputY == other.m_RemoteInputY && m_IsPowersliding == other.m_IsPowersliding && m_IsModified == other.m_IsModified;
}
float m_RemoteInputX = 0;
float m_RemoteInputY = 0;
bool m_IsPowersliding = false;
bool m_IsModified = false;
float m_RemoteInputX;
float m_RemoteInputY;
bool m_IsPowersliding;
bool m_IsModified;
};
struct LocalSpaceInfo {

View File

@@ -23,7 +23,7 @@ PackIndex::PackIndex(const std::filesystem::path& filePath) {
m_PackFileIndices.push_back(packFileIndex);
}
Log::Info("Loaded pack catalog with {:d} pack files and {:d} files", m_PackPaths.size(), m_PackFileIndices.size());
LOG("Loaded pack catalog with %i pack files and %i files", m_PackPaths.size(), m_PackFileIndices.size());
for (auto& item : m_PackPaths) {
std::replace(item.begin(), item.end(), '\\', '/');

View File

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

View File

@@ -34,8 +34,8 @@ constexpr uint32_t lowFrameDelta = FRAMES_TO_MS(lowFramerate);
#define CINSTREAM RakNet::BitStream inStream(packet->data, packet->length, false);
#define CINSTREAM_SKIP_HEADER CINSTREAM if (inStream.GetNumberOfUnreadBits() >= BYTES_TO_BITS(HEADER_SIZE)) inStream.IgnoreBytes(HEADER_SIZE); else inStream.IgnoreBits(inStream.GetNumberOfUnreadBits());
#define CMSGHEADER BitStreamUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::GAME_MSG);
#define SEND_PACKET Game::server->Send(bitStream, sysAddr, false);
#define SEND_PACKET_BROADCAST Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true);
#define SEND_PACKET Game::server->Send(&bitStream, sysAddr, false);
#define SEND_PACKET_BROADCAST Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true);
//=========== TYPEDEFS ==========

View File

@@ -1,16 +0,0 @@
#ifndef __EMOVEMENTPLATFORMSTATE__H__
#define __EMOVEMENTPLATFORMSTATE__H__
#include <cstdint>
/**
* The different types of platform movement state, supposedly a bitmap
*/
enum class eMovementPlatformState : uint32_t
{
Moving = 0b00010,
Stationary = 0b11001,
Stopped = 0b01100
};
#endif //!__EMOVEMENTPLATFORMSTATE__H__

View File

@@ -106,7 +106,7 @@ enum class eReplicaComponentType : uint32_t {
INTERACTION_MANAGER,
DONATION_VENDOR,
COMBAT_MEDIATOR,
ACHIEVEMENT_VENDOR,
COMMENDATION_VENDOR,
GATE_RUSH_CONTROL,
RAIL_ACTIVATOR,
ROLLER,

View File

@@ -1,15 +0,0 @@
#ifndef __EVENDORTRANSACTIONRESULT__
#define __EVENDORTRANSACTIONRESULT__
#include <cstdint>
enum class eVendorTransactionResult : uint32_t {
SELL_SUCCESS = 0,
SELL_FAIL,
PURCHASE_SUCCESS,
PURCHASE_FAIL,
DONATION_FAIL,
DONATION_FULL
};
#endif // !__EVENDORTRANSACTIONRESULT__

View File

@@ -40,6 +40,7 @@
#include "CDRailActivatorComponent.h"
#include "CDRewardCodesTable.h"
#include "CDPetComponentTable.h"
#include "CDMovingPlatformComponentTable.h"
#include <exception>
@@ -110,6 +111,7 @@ DEFINE_TABLE_STORAGE(CDScriptComponentTable);
DEFINE_TABLE_STORAGE(CDSkillBehaviorTable);
DEFINE_TABLE_STORAGE(CDVendorComponentTable);
DEFINE_TABLE_STORAGE(CDZoneTableTable);
DEFINE_TABLE_STORAGE(CDMovingPlatformComponentTable);
void CDClientManager::LoadValuesFromDatabase() {
if (!CDClientDatabase::isConnected) throw CDClientConnectionException();
@@ -157,7 +159,7 @@ void CDClientManager::LoadValuesFromDatabase() {
}
void CDClientManager::LoadValuesFromDefaults() {
Log::Info("Loading default CDClient tables!");
LOG("Loading default CDClient tables!");
CDPetComponentTable::Instance().LoadValuesFromDefaults();
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -22,7 +22,7 @@ void CDMissionsTable::LoadValuesFromDatabase() {
// Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions");
while (!tableData.eof()) {
auto& entry = entries.emplace_back();
CDMissions entry;
entry.id = tableData.getIntField("id", -1);
entry.defined_type = tableData.getStringField("defined_type", "");
entry.defined_subtype = tableData.getStringField("defined_subtype", "");
@@ -76,8 +76,10 @@ void CDMissionsTable::LoadValuesFromDatabase() {
UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1));
entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1);
entries.push_back(entry);
tableData.nextRow();
}
tableData.finalize();
Default.id = -1;
@@ -116,12 +118,3 @@ const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& foun
return Default;
}
const std::set<int32_t> CDMissionsTable::GetMissionsForReward(LOT lot) {
std::set<int32_t> toReturn {};
for (const auto& entry : GetEntries()) {
if (lot == entry.reward_item1 || lot == entry.reward_item2 || lot == entry.reward_item3 || lot == entry.reward_item4) {
toReturn.insert(entry.id);
}
}
return toReturn;
}

View File

@@ -70,8 +70,6 @@ public:
const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const;
const std::set<int32_t> GetMissionsForReward(LOT lot);
static CDMissions Default;
};

View File

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

View File

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

View File

@@ -0,0 +1,48 @@
#include "CDMovingPlatformComponentTable.h"
CDMovingPlatformComponentTable::CDMovingPlatformComponentTable() {
auto& entries = GetEntriesMutable();
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovingPlatforms");
while (!tableData.eof()) {
CDMovingPlatformTableEntry entry;
entry.platformIsSimpleMover = tableData.getIntField("platformIsSimpleMover", 0) == 1;
entry.platformStartAtEnd = tableData.getIntField("platformStartAtEnd", 0) == 1;
entry.platformMove.x = tableData.getFloatField("platformMoveX", 0.0f);
entry.platformMove.y = tableData.getFloatField("platformMoveY", 0.0f);
entry.platformMove.z = tableData.getFloatField("platformMoveZ", 0.0f);
entry.moveTime = tableData.getFloatField("platformMoveTime", -1.0f);
DluAssert(entries.insert(std::make_pair(tableData.getIntField("id", -1), entry)).second);
tableData.nextRow();
}
}
void CDMovingPlatformComponentTable::CachePlatformEntry(ComponentID id) {
auto& entries = GetEntriesMutable();
auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM MovingPlatforms WHERE id = ?;");
query.bind(1, static_cast<int32_t>(id));
auto tableData = query.execQuery();
while (!tableData.eof()) {
CDMovingPlatformTableEntry entry;
entry.platformIsSimpleMover = tableData.getIntField("platformIsSimpleMover", 0) == 1;
entry.platformStartAtEnd = tableData.getIntField("platformStartAtEnd", 0) == 1;
entry.platformMove.x = tableData.getFloatField("platformMoveX", 0.0f);
entry.platformMove.y = tableData.getFloatField("platformMoveY", 0.0f);
entry.platformMove.z = tableData.getFloatField("platformMoveZ", 0.0f);
entry.moveTime = tableData.getFloatField("platformMoveTime", -1.0f);
DluAssert(entries.insert(std::make_pair(tableData.getIntField("id", -1), entry)).second);
tableData.nextRow();
}
}
const std::optional<CDMovingPlatformTableEntry> CDMovingPlatformComponentTable::GetPlatformEntry(ComponentID id) {
auto& entries = GetEntriesMutable();
auto itr = entries.find(id);
if (itr == entries.end()) {
CachePlatformEntry(id);
itr = entries.find(id);
}
return itr != entries.end() ? std::make_optional<CDMovingPlatformTableEntry>(itr->second) : std::nullopt;
}

View File

@@ -0,0 +1,25 @@
#ifndef __CDMOVINGPLATFORMCOMPONENTTABLE__H__
#define __CDMOVINGPLATFORMCOMPONENTTABLE__H__
#include "CDTable.h"
#include "NiPoint3.h"
#include <optional>
typedef uint32_t ComponentID;
struct CDMovingPlatformTableEntry {
NiPoint3 platformMove;
float moveTime;
bool platformIsSimpleMover;
bool platformStartAtEnd;
};
class CDMovingPlatformComponentTable : public CDTable<CDMovingPlatformComponentTable, std::map<ComponentID, CDMovingPlatformTableEntry>> {
public:
CDMovingPlatformComponentTable();
void CachePlatformEntry(ComponentID id);
const std::optional<CDMovingPlatformTableEntry> GetPlatformEntry(ComponentID id);
};
#endif //!__CDMOVINGPLATFORMCOMPONENTTABLE__H__

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -57,7 +57,7 @@ CDPetComponent& CDPetComponentTable::GetByID(const uint32_t componentID) {
auto& entries = GetEntriesMutable();
auto itr = entries.find(componentID);
if (itr == entries.end()) {
Log::Warn("Unable to load pet component (ID {:d}) values from database! Using default values instead.", componentID);
LOG("Unable to load pet component (ID %i) values from database! Using default values instead.", componentID);
return defaultEntry;
}
return itr->second;

View File

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

View File

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

View File

@@ -16,6 +16,7 @@ set(DDATABASE_CDCLIENTDATABASE_CDCLIENTTABLES_SOURCES "CDActivitiesTable.cpp"
"CDLevelProgressionLookupTable.cpp"
"CDLootMatrixTable.cpp"
"CDLootTableTable.cpp"
"CDMovingPlatformComponentTable.cpp"
"CDMissionEmailTable.cpp"
"CDMissionNPCComponentTable.cpp"
"CDMissionsTable.cpp"

View File

@@ -9,28 +9,4 @@ foreach(file ${DDATABASE_CDCLIENTDATABASE_CDCLIENTTABLES_SOURCES})
set(DDATABASE_CDCLIENTDATABASE_SOURCES ${DDATABASE_CDCLIENTDATABASE_SOURCES} "CDClientTables/${file}")
endforeach()
add_library(dDatabaseCDClient STATIC ${DDATABASE_CDCLIENTDATABASE_SOURCES})
target_include_directories(dDatabaseCDClient PUBLIC "."
"CDClientTables"
"${PROJECT_SOURCE_DIR}/dCommon"
"${PROJECT_SOURCE_DIR}/dCommon/dEnums"
)
target_link_libraries(dDatabaseCDClient PRIVATE fmt sqlite3)
if (${CDCLIENT_CACHE_ALL})
add_compile_definitions(dDatabaseCDClient PRIVATE CDCLIENT_CACHE_ALL=${CDCLIENT_CACHE_ALL})
endif()
file(
GLOB HEADERS_DDATABASE_CDCLIENT
LIST_DIRECTORIES false
${PROJECT_SOURCE_DIR}/thirdparty/SQLite/*.h
CDClientTables/*.h
*.h
)
# Need to specify to use the CXX compiler language here or else we get errors including <string>.
target_precompile_headers(
dDatabaseCDClient PRIVATE
"$<$<COMPILE_LANGUAGE:CXX>:${HEADERS_DDATABASE_CDCLIENT}>"
)
set(DDATABASE_CDCLIENTDATABASE_SOURCES ${DDATABASE_CDCLIENTDATABASE_SOURCES} PARENT_SCOPE)

View File

@@ -1,8 +1,20 @@
set(DDATABASE_SOURCES)
add_subdirectory(CDClientDatabase)
foreach(file ${DDATABASE_CDCLIENTDATABASE_SOURCES})
set(DDATABASE_SOURCES ${DDATABASE_SOURCES} "CDClientDatabase/${file}")
endforeach()
add_subdirectory(GameDatabase)
add_library(dDatabase STATIC "MigrationRunner.cpp")
target_include_directories(dDatabase PUBLIC ".")
target_link_libraries(dDatabase
PUBLIC dDatabaseCDClient dDatabaseGame
PRIVATE fmt)
foreach(file ${DDATABASE_GAMEDATABASE_SOURCES})
set(DDATABASE_SOURCES ${DDATABASE_SOURCES} "GameDatabase/${file}")
endforeach()
add_library(dDatabase STATIC ${DDATABASE_SOURCES})
target_link_libraries(dDatabase sqlite3 mariadbConnCpp)
if (${CDCLIENT_CACHE_ALL})
add_compile_definitions(dDatabase CDCLIENT_CACHE_ALL=${CDCLIENT_CACHE_ALL})
endif()

View File

@@ -1,5 +1,6 @@
set(DDATABASE_GAMEDATABASE_SOURCES
"Database.cpp"
"MigrationRunner.cpp"
)
add_subdirectory(MySQL)
@@ -8,26 +9,4 @@ foreach(file ${DDATABSE_DATABSES_MYSQL_SOURCES})
set(DDATABASE_GAMEDATABASE_SOURCES ${DDATABASE_GAMEDATABASE_SOURCES} "MySQL/${file}")
endforeach()
add_library(dDatabaseGame STATIC ${DDATABASE_GAMEDATABASE_SOURCES})
target_include_directories(dDatabaseGame PUBLIC "."
"ITables" PRIVATE "MySQL"
"${PROJECT_SOURCE_DIR}/dCommon"
"${PROJECT_SOURCE_DIR}/dCommon/dEnums"
)
target_link_libraries(dDatabaseGame
PUBLIC MariaDB::ConnCpp
PRIVATE fmt
INTERFACE dCommon)
# Glob together all headers that need to be precompiled
file(
GLOB HEADERS_DDATABASE_GAME
LIST_DIRECTORIES false
ITables/*.h
)
# Need to specify to use the CXX compiler language here or else we get errors including <string>.
target_precompile_headers(
dDatabaseGame PRIVATE
"$<$<COMPILE_LANGUAGE:CXX>:${HEADERS_DDATABASE_GAME}>"
)
set(DDATABASE_GAMEDATABASE_SOURCES ${DDATABASE_GAMEDATABASE_SOURCES} PARENT_SCOPE)

View File

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

View File

@@ -30,7 +30,7 @@ namespace sql {
};
#ifdef _DEBUG
# define DLU_SQL_TRY_CATCH_RETHROW(x) do { try { x; } catch (sql::SQLException& ex) { Log::Warn("SQL Error: {:s}", ex.what()); throw; } } while(0)
# define DLU_SQL_TRY_CATCH_RETHROW(x) do { try { x; } catch (sql::SQLException& ex) { LOG("SQL Error: %s", ex.what()); throw; } } while(0)
#else
# define DLU_SQL_TRY_CATCH_RETHROW(x) x
#endif // _DEBUG

View File

@@ -3,7 +3,6 @@
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
enum class eGameMasterLevel : uint8_t;

View File

@@ -45,7 +45,7 @@ void MigrationRunner::RunMigrations() {
if (Database::Get()->IsMigrationRun(migration.name)) continue;
Log::Info("Running migration: {:s}", migration.name);
LOG("Running migration: %s", migration.name.c_str());
if (migration.name == "dlu/5_brick_model_sd0.sql") {
runSd0Migrations = true;
} else {
@@ -56,7 +56,7 @@ void MigrationRunner::RunMigrations() {
}
if (finalSQL.empty() && !runSd0Migrations) {
Log::Info("Server database is up to date.");
LOG("Server database is up to date.");
return;
}
@@ -67,7 +67,7 @@ void MigrationRunner::RunMigrations() {
if (query.empty()) continue;
Database::Get()->ExecuteCustomQuery(query.c_str());
} catch (sql::SQLException& e) {
Log::Info("Encountered error running migration: {:s}", e.what());
LOG("Encountered error running migration: %s", e.what());
}
}
}
@@ -75,9 +75,9 @@ void MigrationRunner::RunMigrations() {
// Do this last on the off chance none of the other migrations have been run yet.
if (runSd0Migrations) {
uint32_t numberOfUpdatedModels = BrickByBrickFix::UpdateBrickByBrickModelsToSd0();
Log::Info("{:d} models were updated from zlib to sd0.", numberOfUpdatedModels);
LOG("%i models were updated from zlib to sd0.", numberOfUpdatedModels);
uint32_t numberOfTruncatedModels = BrickByBrickFix::TruncateBrokenBrickByBrickXml();
Log::Info("{:d} models were truncated from the database.", numberOfTruncatedModels);
LOG("%i models were truncated from the database.", numberOfTruncatedModels);
}
}
@@ -111,14 +111,14 @@ void MigrationRunner::RunSQLiteMigrations() {
// Doing these 1 migration at a time since one takes a long time and some may think it is crashing.
// This will at the least guarentee that the full migration needs to be run in order to be counted as "migrated".
Log::Info("Executing migration: {:s}. This may take a while. Do not shut down server.", migration.name);
LOG("Executing migration: %s. This may take a while. Do not shut down server.", migration.name.c_str());
CDClientDatabase::ExecuteQuery("BEGIN TRANSACTION;");
for (const auto& dml : GeneralUtils::SplitString(migration.data, ';')) {
if (dml.empty()) continue;
try {
CDClientDatabase::ExecuteDML(dml.c_str());
} catch (CppSQLite3Exception& e) {
Log::Warn("Encountered error running DML command: ({:d}) : {:s}", e.errorCode(), e.errorMessage());
LOG("Encountered error running DML command: (%i) : %s", e.errorCode(), e.errorMessage());
}
}
@@ -129,5 +129,5 @@ void MigrationRunner::RunSQLiteMigrations() {
CDClientDatabase::ExecuteQuery("COMMIT;");
}
Log::Info("CDServer database is up to date.");
LOG("CDServer database is up to date.");
}

View File

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

View File

@@ -147,91 +147,91 @@ private:
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::string_view param) {
// Log::Info("{}", param);
// LOG("%s", param.data());
stmt->setString(index, param.data());
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const char* param) {
// Log::Info("{}", param);
// LOG("%s", param);
stmt->setString(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::string param) {
// Log::Info("{}", param);
stmt->setString(index, param);
// LOG("%s", param.c_str());
stmt->setString(index, param.c_str());
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int8_t param) {
// Log::Info("{}", param);
// LOG("%u", param);
stmt->setByte(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint8_t param) {
// Log::Info("{}", param);
// LOG("%d", param);
stmt->setByte(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int16_t param) {
// Log::Info("{}", param);
// LOG("%u", param);
stmt->setShort(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint16_t param) {
// Log::Info("{}", param);
// LOG("%d", param);
stmt->setShort(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint32_t param) {
// Log::Info("{}", param);
// LOG("%u", param);
stmt->setUInt(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int32_t param) {
// Log::Info("{}", param);
// LOG("%d", param);
stmt->setInt(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const int64_t param) {
// Log::Info("{}", param);
// LOG("%llu", param);
stmt->setInt64(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const uint64_t param) {
// Log::Info("{}", param);
// LOG("%llu", param);
stmt->setUInt64(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const float param) {
// Log::Info({}", param);
// LOG("%f", param);
stmt->setFloat(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const double param) {
// Log::Info("{}", param);
// LOG("%f", param);
stmt->setDouble(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const bool param) {
// Log::Info("{}", param);
// LOG("%d", param);
stmt->setBoolean(index, param);
}
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::istream* param) {
// Log::Info("Blob");
// LOG("Blob");
// This is the one time you will ever see me use const_cast.
stmt->setBlob(index, const_cast<std::istream*>(param));
}
@@ -239,10 +239,10 @@ inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::istr
template<>
inline void SetParam(UniquePreppedStmtRef stmt, const int index, const std::optional<uint32_t> param) {
if (param) {
// Log::Info("{}", param.value());
// LOG("%d", param.value());
stmt->setInt(index, param.value());
} else {
// Log::Info("Null");
// LOG("Null");
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 5. TODO implement this.
);
} catch (const sql::SQLException& e) {
Log::Warn("Error inserting new property model: {:s}", e.what());
} catch (sql::SQLException& e) {
LOG("Error inserting new property model: %s", e.what());
}
}

View File

@@ -13,25 +13,11 @@ include_directories(
${PROJECT_SOURCE_DIR}/dGame
)
add_library(dGameBase OBJECT ${DGAME_SOURCES})
add_library(dGameBase ${DGAME_SOURCES})
target_precompile_headers(dGameBase PRIVATE ${HEADERS_DGAME})
target_include_directories(dGameBase PUBLIC "." "dEntity"
PRIVATE "dComponents" "dGameMessages" "dBehaviors" "dMission" "dUtilities" "dInventory"
$<TARGET_PROPERTY:dPropertyBehaviors,INTERFACE_INCLUDE_DIRECTORIES>
"${PROJECT_SOURCE_DIR}/dCommon"
"${PROJECT_SOURCE_DIR}/dCommon/dEnums"
"${PROJECT_SOURCE_DIR}/dCommon/dClient"
# dDatabase
"${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase"
"${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase/CDClientTables"
"${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase"
"${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase/ITables"
"${PROJECT_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include"
# dPhysics
"${PROJECT_SOURCE_DIR}/thirdparty/recastnavigation/Recast/Include"
"${PROJECT_SOURCE_DIR}/thirdparty/recastnavigation/Detour/Include"
"${PROJECT_SOURCE_DIR}/dZoneManager"
)
target_link_libraries(dGameBase
PUBLIC dDatabase dPhysics
INTERFACE dComponents dEntity)
add_subdirectory(dBehaviors)
add_subdirectory(dComponents)
@@ -42,26 +28,7 @@ add_subdirectory(dMission)
add_subdirectory(dPropertyBehaviors)
add_subdirectory(dUtilities)
add_library(dGame STATIC
$<TARGET_OBJECTS:dGameBase>
$<TARGET_OBJECTS:dBehaviors>
$<TARGET_OBJECTS:dComponents>
$<TARGET_OBJECTS:dEntity>
$<TARGET_OBJECTS:dGameMessages>
$<TARGET_OBJECTS:dInventory>
$<TARGET_OBJECTS:dMission>
$<TARGET_OBJECTS:dPropertyBehaviors>
$<TARGET_OBJECTS:dUtilities>
)
target_link_libraries(dGame INTERFACE dNet)
target_include_directories(dGame INTERFACE
$<TARGET_PROPERTY:dGameBase,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dBehaviors,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dComponents,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dEntity,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dGameMessages,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dInventory,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dMission,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dPropertyBehaviors,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dUtilities,INTERFACE_INCLUDE_DIRECTORIES>
add_library(dGame INTERFACE)
target_link_libraries(dGame INTERFACE
dGameBase dBehaviors dComponents dEntity dGameMessages dInventory dMission dPropertyBehaviors dUtilities dScripts
)

View File

@@ -82,16 +82,16 @@ void Character::DoQuickXMLDataParse() {
if (!m_Doc) return;
if (m_Doc->Parse(m_XMLData.c_str(), m_XMLData.size()) == 0) {
Log::Info("Loaded xmlData for character {:s} ({:d})!", m_Name, m_ID);
LOG("Loaded xmlData for character %s (%i)!", m_Name.c_str(), m_ID);
} else {
Log::Warn("Failed to load xmlData!");
LOG("Failed to load xmlData!");
//Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true);
return;
}
tinyxml2::XMLElement* mf = m_Doc->FirstChildElement("obj")->FirstChildElement("mf");
if (!mf) {
Log::Warn("Failed to find mf tag!");
LOG("Failed to find mf tag!");
return;
}
@@ -110,14 +110,14 @@ void Character::DoQuickXMLDataParse() {
tinyxml2::XMLElement* inv = m_Doc->FirstChildElement("obj")->FirstChildElement("inv");
if (!inv) {
Log::Warn("Char has no inv!");
LOG("Char has no inv!");
return;
}
tinyxml2::XMLElement* bag = inv->FirstChildElement("items")->FirstChildElement("in");
if (!bag) {
Log::Warn("Couldn't find bag0!");
LOG("Couldn't find bag0!");
return;
}
@@ -310,7 +310,7 @@ void Character::SaveXMLToDatabase() {
//Call upon the entity to update our xmlDoc:
if (!m_OurEntity) {
Log::Warn("{:d}:{:s} didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!", this->GetID(), this->GetName());
LOG("%i:%s didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!", this->GetID(), this->GetName().c_str());
return;
}
@@ -321,7 +321,7 @@ void Character::SaveXMLToDatabase() {
//For metrics, log the time it took to save:
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed = end - start;
Log::Info("{:d}:{:s} Saved character to Database in: {:f}s", this->GetID(), this->GetName(), elapsed.count());
LOG("%i:%s Saved character to Database in: %fs", this->GetID(), this->GetName().c_str(), elapsed.count());
}
void Character::SetIsNewLogin() {
@@ -334,7 +334,7 @@ void Character::SetIsNewLogin() {
auto* nextChild = currentChild->NextSiblingElement();
if (currentChild->Attribute("si")) {
flags->DeleteChild(currentChild);
Log::Info("Removed isLoggedIn flag from character {:d}:{:s}, saving character to database", GetID(), GetName());
LOG("Removed isLoggedIn flag from character %i:%s, saving character to database", GetID(), GetName().c_str());
WriteToDatabase();
}
currentChild = nextChild;

View File

@@ -82,7 +82,6 @@
#include "CollectibleComponent.h"
#include "ItemComponent.h"
#include "GhostComponent.h"
#include "AchievementVendorComponent.h"
// Table includes
#include "CDComponentsRegistryTable.h"
@@ -138,23 +137,25 @@ Entity::Entity(const LWOOBJID& objectID, EntityInfo info, User* parentUser, Enti
Entity::~Entity() {
if (IsPlayer()) {
Log::Info("Deleted player");
LOG("Deleted 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)) {
Log::Warn("Unable to find player to remove from manager.");
LOG("Unable to find player to remove from manager.");
return;
}
auto* zoneControl = Game::entityManager->GetZoneControlEntity();
if (zoneControl) {
zoneControl->GetScript()->OnPlayerExit(zoneControl, this);
Entity* zoneControl = Game::entityManager->GetZoneControlEntity();
for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) {
script->OnPlayerExit(zoneControl, this);
}
std::vector<Entity*> scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY);
for (Entity* scriptEntity : scriptedActs) {
if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds
scriptEntity->GetScript()->OnPlayerExit(scriptEntity, this);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) {
script->OnPlayerExit(scriptEntity, this);
}
}
}
}
@@ -614,8 +615,6 @@ void Entity::Initialize() {
AddComponent<VendorComponent>();
} else if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::DONATION_VENDOR, -1) != -1)) {
AddComponent<DonationVendorComponent>();
} else if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::ACHIEVEMENT_VENDOR, -1) != -1)) {
AddComponent<AchievementVendorComponent>();
}
if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROPERTY_VENDOR, -1) != -1) {
@@ -760,7 +759,9 @@ void Entity::Initialize() {
// Hacky way to trigger these when the object has had a chance to get constructed
AddCallbackTimer(0, [this]() {
this->GetScript()->OnStartup(this);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnStartup(this);
}
});
if (!m_Character && Game::entityManager->GetGhostingEnabled()) {
@@ -835,6 +836,17 @@ bool Entity::HasComponent(const eReplicaComponentType componentId) const {
return m_Components.find(componentId) != m_Components.end();
}
std::vector<ScriptComponent*> Entity::GetScriptComponents() {
std::vector<ScriptComponent*> comps;
for (std::pair<eReplicaComponentType, void*> p : m_Components) {
if (p.first == eReplicaComponentType::SCRIPT) {
comps.push_back(static_cast<ScriptComponent*>(p.second));
}
}
return comps;
}
void Entity::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName) {
if (notificationName == "HitOrHealResult" || notificationName == "Hit") {
auto* destroyableComponent = GetComponent<DestroyableComponent>();
@@ -884,34 +896,34 @@ void Entity::SetGMLevel(eGameMasterLevel value) {
}
}
void Entity::WriteBaseReplicaData(RakNet::BitStream& outBitStream, eReplicaPacketType packetType) {
void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacketType packetType) {
if (packetType == eReplicaPacketType::CONSTRUCTION) {
outBitStream.Write(m_ObjectID);
outBitStream.Write(m_TemplateID);
outBitStream->Write(m_ObjectID);
outBitStream->Write(m_TemplateID);
if (IsPlayer()) {
std::string name = m_Character != nullptr ? m_Character->GetName() : "Invalid";
outBitStream.Write<uint8_t>(uint8_t(name.size()));
outBitStream->Write<uint8_t>(uint8_t(name.size()));
for (size_t i = 0; i < name.size(); ++i) {
outBitStream.Write<uint16_t>(name[i]);
outBitStream->Write<uint16_t>(name[i]);
}
} else {
const auto& name = GetVar<std::string>(u"npcName");
outBitStream.Write<uint8_t>(uint8_t(name.size()));
outBitStream->Write<uint8_t>(uint8_t(name.size()));
for (size_t i = 0; i < name.size(); ++i) {
outBitStream.Write<uint16_t>(name[i]);
outBitStream->Write<uint16_t>(name[i]);
}
}
outBitStream.Write<uint32_t>(0); //Time since created on server
outBitStream->Write<uint32_t>(0); //Time since created on server
const auto& syncLDF = GetVar<std::vector<std::u16string>>(u"syncLDF");
// Only sync for models.
if (m_Settings.size() > 0 && (GetComponent<ModelComponent>() && !GetComponent<PetComponent>())) {
outBitStream.Write1(); //ldf data
outBitStream->Write1(); //ldf data
RakNet::BitStream settingStream;
int32_t numberOfValidKeys = m_Settings.size();
@@ -928,13 +940,13 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream& outBitStream, eReplicaPacke
for (LDFBaseData* data : m_Settings) {
if (data && data->GetValueType() != eLDFType::LDF_TYPE_UNKNOWN) {
data->WriteToPacket(settingStream);
data->WriteToPacket(&settingStream);
}
}
outBitStream.Write(settingStream.GetNumberOfBytesUsed() + 1);
outBitStream.Write<uint8_t>(0); //no compression used
outBitStream.Write(settingStream);
outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1);
outBitStream->Write<uint8_t>(0); //no compression used
outBitStream->Write(settingStream);
} else if (!syncLDF.empty()) {
std::vector<LDFBaseData*> ldfData;
@@ -942,79 +954,79 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream& outBitStream, eReplicaPacke
ldfData.push_back(GetVarData(data));
}
outBitStream.Write1(); //ldf data
outBitStream->Write1(); //ldf data
RakNet::BitStream settingStream;
settingStream.Write<uint32_t>(ldfData.size());
for (LDFBaseData* data : ldfData) {
if (data) {
data->WriteToPacket(settingStream);
data->WriteToPacket(&settingStream);
}
}
outBitStream.Write(settingStream.GetNumberOfBytesUsed() + 1);
outBitStream.Write<uint8_t>(0); //no compression used
outBitStream.Write(settingStream);
outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1);
outBitStream->Write<uint8_t>(0); //no compression used
outBitStream->Write(settingStream);
} else {
outBitStream.Write0(); //No ldf data
outBitStream->Write0(); //No ldf data
}
TriggerComponent* triggerComponent;
if (TryGetComponent(eReplicaComponentType::TRIGGER, triggerComponent)) {
// has trigger component, check to see if we have events to handle
auto* trigger = triggerComponent->GetTrigger();
outBitStream.Write<bool>(trigger && trigger->events.size() > 0);
outBitStream->Write<bool>(trigger && trigger->events.size() > 0);
} else { // no trigger componenet, so definitely no triggers
outBitStream.Write0();
outBitStream->Write0();
}
if (m_ParentEntity != nullptr || m_SpawnerID != 0) {
outBitStream.Write1();
if (m_ParentEntity != nullptr) outBitStream.Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), static_cast<uint32_t>(eObjectBits::CLIENT)));
else if (m_Spawner != nullptr && m_Spawner->m_Info.isNetwork) outBitStream.Write(m_SpawnerID);
else outBitStream.Write(GeneralUtils::SetBit(m_SpawnerID, static_cast<uint32_t>(eObjectBits::CLIENT)));
} else outBitStream.Write0();
outBitStream->Write1();
if (m_ParentEntity != nullptr) outBitStream->Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), static_cast<uint32_t>(eObjectBits::CLIENT)));
else if (m_Spawner != nullptr && m_Spawner->m_Info.isNetwork) outBitStream->Write(m_SpawnerID);
else outBitStream->Write(GeneralUtils::SetBit(m_SpawnerID, static_cast<uint32_t>(eObjectBits::CLIENT)));
} else outBitStream->Write0();
outBitStream.Write(m_HasSpawnerNodeID);
if (m_HasSpawnerNodeID) outBitStream.Write(m_SpawnerNodeID);
outBitStream->Write(m_HasSpawnerNodeID);
if (m_HasSpawnerNodeID) outBitStream->Write(m_SpawnerNodeID);
//outBitStream.Write0(); //Spawner node id
//outBitStream->Write0(); //Spawner node id
if (m_Scale == 1.0f || m_Scale == 0.0f) outBitStream.Write0();
if (m_Scale == 1.0f || m_Scale == 0.0f) outBitStream->Write0();
else {
outBitStream.Write1();
outBitStream.Write(m_Scale);
outBitStream->Write1();
outBitStream->Write(m_Scale);
}
outBitStream.Write0(); //ObjectWorldState
outBitStream->Write0(); //ObjectWorldState
if (m_GMLevel != eGameMasterLevel::CIVILIAN) {
outBitStream.Write1();
outBitStream.Write(m_GMLevel);
} else outBitStream.Write0(); //No GM Level
outBitStream->Write1();
outBitStream->Write(m_GMLevel);
} else outBitStream->Write0(); //No GM Level
}
// Only serialize parent / child info should the info be dirty (changed) or if this is the construction of the entity.
outBitStream.Write(m_IsParentChildDirty || packetType == eReplicaPacketType::CONSTRUCTION);
outBitStream->Write(m_IsParentChildDirty || packetType == eReplicaPacketType::CONSTRUCTION);
if (m_IsParentChildDirty || packetType == eReplicaPacketType::CONSTRUCTION) {
m_IsParentChildDirty = false;
outBitStream.Write(m_ParentEntity != nullptr);
outBitStream->Write(m_ParentEntity != nullptr);
if (m_ParentEntity) {
outBitStream.Write(m_ParentEntity->GetObjectID());
outBitStream.Write0();
outBitStream->Write(m_ParentEntity->GetObjectID());
outBitStream->Write0();
}
outBitStream.Write(m_ChildEntities.size() > 0);
outBitStream->Write(m_ChildEntities.size() > 0);
if (m_ChildEntities.size() > 0) {
outBitStream.Write<uint16_t>(m_ChildEntities.size());
outBitStream->Write<uint16_t>(m_ChildEntities.size());
for (Entity* child : m_ChildEntities) {
outBitStream.Write<uint64_t>(child->GetObjectID());
outBitStream->Write<uint64_t>(child->GetObjectID());
}
}
}
}
void Entity::WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType packetType) {
void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType packetType) {
/**
* This has to be done in a specific order.
@@ -1102,7 +1114,7 @@ void Entity::WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType
possessorComponent->Serialize(outBitStream, bIsInitialUpdate);
} else {
// Should never happen, but just to be safe
outBitStream.Write0();
outBitStream->Write0();
}
LevelProgressionComponent* levelProgressionComponent;
@@ -1110,7 +1122,7 @@ void Entity::WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType
levelProgressionComponent->Serialize(outBitStream, bIsInitialUpdate);
} else {
// Should never happen, but just to be safe
outBitStream.Write0();
outBitStream->Write0();
}
PlayerForcedMovementComponent* playerForcedMovementComponent;
@@ -1118,7 +1130,7 @@ void Entity::WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType
playerForcedMovementComponent->Serialize(outBitStream, bIsInitialUpdate);
} else {
// Should never happen, but just to be safe
outBitStream.Write0();
outBitStream->Write0();
}
characterComponent->Serialize(outBitStream, bIsInitialUpdate);
@@ -1179,11 +1191,6 @@ void Entity::WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType
donationVendorComponent->Serialize(outBitStream, bIsInitialUpdate);
}
AchievementVendorComponent* achievementVendorComponent;
if (TryGetComponent(eReplicaComponentType::ACHIEVEMENT_VENDOR, achievementVendorComponent)) {
achievementVendorComponent->Serialize(outBitStream, bIsInitialUpdate);
}
BouncerComponent* bouncerComponent;
if (TryGetComponent(eReplicaComponentType::BOUNCER, bouncerComponent)) {
bouncerComponent->Serialize(outBitStream, bIsInitialUpdate);
@@ -1235,7 +1242,7 @@ void Entity::WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType
// BBB Component, unused currently
// Need to to write0 so that is serialized correctly
// TODO: Implement BBB Component
outBitStream.Write0();
outBitStream->Write0();
}
void Entity::UpdateXMLDoc(tinyxml2::XMLDocument* doc) {
@@ -1263,7 +1270,9 @@ 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
auto timerName = timer.GetName();
m_Timers.erase(m_Timers.begin() + timerPosition);
GetScript()->OnTimerDone(this, timerName);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnTimerDone(this, timerName);
}
TriggerEvent(eTriggerEventType::TIMER_DONE, this);
} else {
@@ -1309,7 +1318,9 @@ void Entity::Update(const float deltaTime) {
Wake();
}
GetScript()->OnUpdate(this);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnUpdate(this);
}
for (const auto& pair : m_Components) {
if (pair.second == nullptr) continue;
@@ -1326,7 +1337,9 @@ void Entity::OnCollisionProximity(LWOOBJID otherEntity, const std::string& proxN
Entity* other = Game::entityManager->GetEntity(otherEntity);
if (!other) return;
GetScript()->OnProximityUpdate(this, other, proxName, status);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnProximityUpdate(this, other, proxName, status);
}
RocketLaunchpadControlComponent* rocketComp = GetComponent<RocketLaunchpadControlComponent>();
if (!rocketComp) return;
@@ -1338,7 +1351,9 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) {
auto* other = Game::entityManager->GetEntity(otherEntity);
if (!other) return;
GetScript()->OnCollisionPhantom(this, other);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnCollisionPhantom(this, other);
}
for (const auto& callback : m_PhantomCollisionCallbacks) {
callback(other);
@@ -1377,7 +1392,9 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) {
auto* other = Game::entityManager->GetEntity(otherEntity);
if (!other) return;
GetScript()->OnOffCollisionPhantom(this, other);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnOffCollisionPhantom(this, other);
}
TriggerEvent(eTriggerEventType::EXIT, other);
@@ -1394,32 +1411,46 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) {
}
void Entity::OnFireEventServerSide(Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) {
GetScript()->OnFireEventServerSide(this, sender, args, param1, param2, param3);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnFireEventServerSide(this, sender, args, param1, param2, param3);
}
}
void Entity::OnActivityStateChangeRequest(LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) {
GetScript()->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue);
}
}
void Entity::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName,
float_t pathTime, float_t totalTime, int32_t waypoint) {
GetScript()->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint);
}
}
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);
GetScript()->OnNotifyObject(this, sender, name, param1, param2);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnNotifyObject(this, sender, name, param1, param2);
}
}
void Entity::OnEmoteReceived(const int32_t emote, Entity* target) {
GetScript()->OnEmoteReceived(this, emote, target);
for (auto* script : CppScripts::GetEntityScripts(this)) {
script->OnEmoteReceived(this, emote, target);
}
}
void Entity::OnUse(Entity* originator) {
TriggerEvent(eTriggerEventType::INTERACT, originator);
GetScript()->OnUse(this, originator);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnUse(this, originator);
}
// component base class when
for (const auto& pair : m_Components) {
if (pair.second == nullptr) continue;
@@ -1429,63 +1460,82 @@ void Entity::OnUse(Entity* originator) {
}
void Entity::OnHitOrHealResult(Entity* attacker, int32_t damage) {
GetScript()->OnHitOrHealResult(this, attacker, damage);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnHitOrHealResult(this, attacker, damage);
}
}
void Entity::OnHit(Entity* attacker) {
TriggerEvent(eTriggerEventType::HIT, attacker);
GetScript()->OnHit(this, attacker);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnHit(this, attacker);
}
}
void Entity::OnZonePropertyEditBegin() {
GetScript()->OnZonePropertyEditBegin(this);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnZonePropertyEditBegin(this);
}
}
void Entity::OnZonePropertyEditEnd() {
GetScript()->OnZonePropertyEditEnd(this);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnZonePropertyEditEnd(this);
}
}
void Entity::OnZonePropertyModelEquipped() {
GetScript()->OnZonePropertyModelEquipped(this);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnZonePropertyModelEquipped(this);
}
}
void Entity::OnZonePropertyModelPlaced(Entity* player) {
GetScript()->OnZonePropertyModelPlaced(this, player);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnZonePropertyModelPlaced(this, player);
}
}
void Entity::OnZonePropertyModelPickedUp(Entity* player) {
GetScript()->OnZonePropertyModelPickedUp(this, player);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnZonePropertyModelPickedUp(this, player);
}
}
void Entity::OnZonePropertyModelRemoved(Entity* player) {
GetScript()->OnZonePropertyModelRemoved(this, player);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnZonePropertyModelRemoved(this, player);
}
}
void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) {
GetScript()->OnZonePropertyModelRemovedWhileEquipped(this, player);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnZonePropertyModelRemovedWhileEquipped(this, player);
}
}
void Entity::OnZonePropertyModelRotated(Entity* player) {
GetScript()->OnZonePropertyModelRotated(this, player);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnZonePropertyModelRotated(this, player);
}
}
void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) {
GetScript()->OnMessageBoxResponse(this, sender, button, identifier, userData);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnMessageBoxResponse(this, sender, button, identifier, userData);
}
}
void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) {
GetScript()->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier);
}
}
void Entity::RequestActivityExit(Entity* sender, LWOOBJID player, bool canceled) {
GetScript()->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;
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnRequestActivityExit(sender, player, canceled);
}
}
void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType) {
@@ -1518,7 +1568,9 @@ void Entity::Kill(Entity* murderer, const eKillType killType) {
//OMAI WA MOU, SHINDERIU
GetScript()->OnDie(this, murderer);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) {
script->OnDie(this, murderer);
}
if (m_Spawner != nullptr) {
m_Spawner->NotifyOfEntityDeath(m_ObjectID);
@@ -2066,7 +2118,9 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) {
havokVehiclePhysicsComponent->SetIsOnGround(update.onGround);
havokVehiclePhysicsComponent->SetIsOnRail(update.onRail);
havokVehiclePhysicsComponent->SetVelocity(update.velocity);
havokVehiclePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3Constant::ZERO);
havokVehiclePhysicsComponent->SetAngularVelocity(update.angularVelocity);
havokVehiclePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3Constant::ZERO);
havokVehiclePhysicsComponent->SetRemoteInputInfo(update.remoteInputInfo);
} else {
// Need to get the mount's controllable physics
@@ -2077,7 +2131,9 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) {
possessedControllablePhysicsComponent->SetIsOnGround(update.onGround);
possessedControllablePhysicsComponent->SetIsOnRail(update.onRail);
possessedControllablePhysicsComponent->SetVelocity(update.velocity);
possessedControllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3Constant::ZERO);
possessedControllablePhysicsComponent->SetAngularVelocity(update.angularVelocity);
possessedControllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3Constant::ZERO);
}
Game::entityManager->SerializeEntity(possassableEntity);
}
@@ -2099,7 +2155,9 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) {
controllablePhysicsComponent->SetIsOnGround(update.onGround);
controllablePhysicsComponent->SetIsOnRail(update.onRail);
controllablePhysicsComponent->SetVelocity(update.velocity);
controllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3Constant::ZERO);
controllablePhysicsComponent->SetAngularVelocity(update.angularVelocity);
controllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3Constant::ZERO);
auto* ghostComponent = GetComponent<GhostComponent>();
if (ghostComponent) ghostComponent->SetGhostReferencePoint(update.position);

View File

@@ -146,8 +146,7 @@ public:
void AddComponent(eReplicaComponentType componentId, Component* component);
// This is expceted to never return nullptr, an assert checks this.
CppScripts::Script* const GetScript();
std::vector<ScriptComponent*> GetScriptComponents();
void Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName);
void Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName);
@@ -172,8 +171,8 @@ public:
std::unordered_map<eReplicaComponentType, Component*>& GetComponents() { return m_Components; } // TODO: Remove
void WriteBaseReplicaData(RakNet::BitStream& outBitStream, eReplicaPacketType packetType);
void WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType packetType);
void WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacketType packetType);
void WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType packetType);
void UpdateXMLDoc(tinyxml2::XMLDocument* doc);
void Update(float deltaTime);
@@ -296,9 +295,6 @@ public:
void ProcessPositionUpdate(PositionUpdate& update);
// Scale will only be communicated to the client when the construction packet is sent
void SetScale(const float scale) { m_Scale = scale; };
protected:
LWOOBJID m_ObjectID;

View File

@@ -178,18 +178,18 @@ void EntityManager::SerializeEntities() {
stream.Write<char>(ID_REPLICA_MANAGER_SERIALIZE);
stream.Write<unsigned short>(entity->GetNetworkId());
entity->WriteBaseReplicaData(stream, eReplicaPacketType::SERIALIZATION);
entity->WriteComponents(stream, eReplicaPacketType::SERIALIZATION);
entity->WriteBaseReplicaData(&stream, eReplicaPacketType::SERIALIZATION);
entity->WriteComponents(&stream, eReplicaPacketType::SERIALIZATION);
if (entity->GetIsGhostingCandidate()) {
for (auto* player : PlayerManager::GetAllPlayers()) {
auto* ghostComponent = player->GetComponent<GhostComponent>();
if (ghostComponent && ghostComponent->IsObserved(toSerialize)) {
Game::server->Send(stream, player->GetSystemAddress(), false);
Game::server->Send(&stream, player->GetSystemAddress(), false);
}
}
} else {
Game::server->Send(stream, UNASSIGNED_SYSTEM_ADDRESS, true);
Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true);
}
}
m_EntitiesToSerialize.clear();
@@ -201,7 +201,7 @@ void EntityManager::KillEntities() {
auto* entity = GetEntity(toKill);
if (!entity) {
Log::Warn("Attempting to kill null entity {}", toKill);
LOG("Attempting to kill null entity %llu", toKill);
continue;
}
@@ -231,7 +231,7 @@ void EntityManager::DeleteEntities() {
if (ghostingToDelete != m_EntitiesToGhost.end()) m_EntitiesToGhost.erase(ghostingToDelete);
} else {
Log::Warn("Attempted to delete non-existent entity {}", toDelete);
LOG("Attempted to delete non-existent entity %llu", toDelete);
}
m_Entities.erase(toDelete);
}
@@ -315,14 +315,14 @@ Entity* EntityManager::GetSpawnPointEntity(const std::string& spawnName) const {
// Check if the spawn point entity is valid just in case
return spawnPoint == m_SpawnPoints.end() ? nullptr : GetEntity(spawnPoint->second);
}
#include <thread>
const std::unordered_map<std::string, LWOOBJID>& EntityManager::GetSpawnPointEntities() const {
return m_SpawnPoints;
}
void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr, const bool skipChecks) {
if (!entity) {
Log::Warn("Attempted to construct null entity");
LOG("Attempted to construct null entity");
return;
}
@@ -359,16 +359,16 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr
stream.Write(true);
stream.Write<uint16_t>(entity->GetNetworkId());
entity->WriteBaseReplicaData(stream, eReplicaPacketType::CONSTRUCTION);
entity->WriteComponents(stream, eReplicaPacketType::CONSTRUCTION);
entity->WriteBaseReplicaData(&stream, eReplicaPacketType::CONSTRUCTION);
entity->WriteComponents(&stream, eReplicaPacketType::CONSTRUCTION);
if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) {
if (skipChecks) {
Game::server->Send(stream, UNASSIGNED_SYSTEM_ADDRESS, true);
Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true);
} else {
for (auto* player : PlayerManager::GetAllPlayers()) {
if (player->GetPlayerReadyForUpdates()) {
Game::server->Send(stream, player->GetSystemAddress(), false);
Game::server->Send(&stream, player->GetSystemAddress(), false);
} else {
auto* ghostComponent = player->GetComponent<GhostComponent>();
if (ghostComponent) ghostComponent->AddLimboConstruction(entity->GetObjectID());
@@ -376,7 +376,7 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr
}
}
} else {
Game::server->Send(stream, sysAddr, false);
Game::server->Send(&stream, sysAddr, false);
}
if (entity->IsPlayer()) {
@@ -407,7 +407,7 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr)
stream.Write<uint8_t>(ID_REPLICA_MANAGER_DESTRUCTION);
stream.Write<uint16_t>(entity->GetNetworkId());
Game::server->Send(stream, sysAddr, sysAddr == UNASSIGNED_SYSTEM_ADDRESS);
Game::server->Send(&stream, sysAddr, sysAddr == UNASSIGNED_SYSTEM_ADDRESS);
for (auto* player : PlayerManager::GetAllPlayers()) {
if (!player->GetPlayerReadyForUpdates()) {
@@ -418,16 +418,10 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr)
}
void EntityManager::SerializeEntity(Entity* entity) {
if (!entity) return;
EntityManager::SerializeEntity(*entity);
}
if (!entity || entity->GetNetworkId() == 0) return;
void EntityManager::SerializeEntity(const Entity& entity) {
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());
if (std::find(m_EntitiesToSerialize.begin(), m_EntitiesToSerialize.end(), entity->GetObjectID()) == m_EntitiesToSerialize.end()) {
m_EntitiesToSerialize.push_back(entity->GetObjectID());
}
}
@@ -581,13 +575,13 @@ void EntityManager::ScheduleForKill(Entity* entity) {
const auto objectId = entity->GetObjectID();
if (std::find(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId) == m_EntitiesToKill.end()) {
if (std::find(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId) != m_EntitiesToKill.end()) {
m_EntitiesToKill.push_back(objectId);
}
}
void EntityManager::ScheduleForDeletion(LWOOBJID entity) {
if (std::find(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity) == m_EntitiesToDelete.end()) {
if (std::find(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity) != m_EntitiesToDelete.end()) {
m_EntitiesToDelete.push_back(entity);
}
}

View File

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

View File

@@ -43,9 +43,9 @@ inline void WriteLeaderboardRow(std::ostringstream& leaderboard, const uint32_t&
leaderboard << "\nResult[0].Row[" << index << "]." << data->GetString();
}
void Leaderboard::Serialize(RakNet::BitStream& bitStream) const {
bitStream.Write(gameID);
bitStream.Write(infoType);
void Leaderboard::Serialize(RakNet::BitStream* bitStream) const {
bitStream->Write(gameID);
bitStream->Write(infoType);
std::ostringstream leaderboard;
@@ -64,12 +64,12 @@ void Leaderboard::Serialize(RakNet::BitStream& bitStream) const {
// Serialize the thing to a BitStream
uint32_t leaderboardSize = leaderboard.tellp();
bitStream.Write<uint32_t>(leaderboardSize);
bitStream->Write<uint32_t>(leaderboardSize);
// Doing this all in 1 call so there is no possbility of a dangling pointer.
bitStream.WriteAlignedBytes(reinterpret_cast<const unsigned char*>(GeneralUtils::ASCIIToUTF16(leaderboard.str()).c_str()), leaderboardSize * sizeof(char16_t));
if (leaderboardSize > 0) bitStream.Write<uint16_t>(0);
bitStream.Write0();
bitStream.Write0();
bitStream->WriteAlignedBytes(reinterpret_cast<const unsigned char*>(GeneralUtils::ASCIIToUTF16(leaderboard.str()).c_str()), leaderboardSize * sizeof(char16_t));
if (leaderboardSize > 0) bitStream->Write<uint16_t>(0);
bitStream->Write0();
bitStream->Write0();
}
void Leaderboard::QueryToLdf(std::unique_ptr<sql::ResultSet>& rows) {
@@ -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 += " LIMIT 1";
Log::Debug("query is {:s}", baseLookup);
LOG_DEBUG("query is %s", baseLookup.c_str());
std::unique_ptr<sql::PreparedStatement> baseQuery(Database::Get()->CreatePreppedStmt(baseLookup));
baseQuery->setInt(1, this->gameID);
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);
DluAssert(res != -1);
std::unique_ptr<sql::PreparedStatement> query(Database::Get()->CreatePreppedStmt(lookupBuffer.get()));
Log::Debug("Query is {:s} vars are {:d} {:d} {:d}", lookupBuffer.get(), this->gameID, this->relatedPlayer, relatedPlayerLeaderboardId);
LOG_DEBUG("Query is %s vars are %i %i %i", lookupBuffer.get(), this->gameID, this->relatedPlayer, relatedPlayerLeaderboardId);
query->setInt(1, this->gameID);
if (this->infoType == InfoType::Friends) {
query->setInt(2, this->relatedPlayer);
@@ -358,7 +358,7 @@ void LeaderboardManager::SaveScore(const LWOOBJID& playerID, const GameID activi
}
case Leaderboard::Type::None:
default:
Log::Warn("Unknown leaderboard type {:d} for game {:d}. Cannot save score!", GeneralUtils::ToUnderlying(leaderboardType), activityId);
LOG("Unknown leaderboard type %i for game %i. Cannot save score!", leaderboardType, activityId);
return;
}
bool newHighScore = lowerScoreBetter ? newScore < oldScore : newScore > oldScore;
@@ -377,7 +377,7 @@ void LeaderboardManager::SaveScore(const LWOOBJID& playerID, const GameID activi
} else {
saveQuery = FormatInsert(leaderboardType, newScore, false);
}
Log::Info("save query {:s} {:d} {:d}", saveQuery, playerID, activityId);
LOG("save query %s %i %i", saveQuery.c_str(), playerID, activityId);
std::unique_ptr<sql::PreparedStatement> saveStatement(Database::Get()->CreatePreppedStmt(saveQuery));
saveStatement->setInt(1, playerID);
saveStatement->setInt(2, activityId);

View File

@@ -88,7 +88,7 @@ public:
*
* Expensive! Leaderboards are very string intensive so be wary of performatnce calling this method.
*/
void Serialize(RakNet::BitStream& bitStream) const;
void Serialize(RakNet::BitStream* bitStream) const;
/**
* Builds the leaderboard from the database based on the associated gameID

View File

@@ -67,7 +67,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) {
if (participant == m_ParticipantA) {
m_AcceptedA = !value;
Log::Info("Accepted from A ({}), B: ({})", value, m_AcceptedB);
LOG("Accepted from A (%d), B: (%d)", value, m_AcceptedB);
auto* entityB = GetParticipantBEntity();
@@ -77,7 +77,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) {
} else if (participant == m_ParticipantB) {
m_AcceptedB = !value;
Log::Info("Accepted from B ({}), A: ({})", value, m_AcceptedA);
LOG("Accepted from B (%d), A: (%d)", value, m_AcceptedA);
auto* entityA = GetParticipantAEntity();
@@ -125,7 +125,7 @@ void Trade::Complete() {
// First verify both players have the coins and items requested for the trade.
if (characterA->GetCoins() < m_CoinsA || characterB->GetCoins() < m_CoinsB) {
Log::Warn("Possible coin trade cheating attempt! Aborting trade.");
LOG("Possible coin trade cheating attempt! Aborting trade.");
return;
}
@@ -133,11 +133,11 @@ void Trade::Complete() {
auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId);
if (itemToRemove) {
if (itemToRemove->GetCount() < tradeItem.itemCount) {
Log::Warn("Possible cheating attempt from {:s} in trading!!! Aborting trade", characterA->GetName());
LOG("Possible cheating attempt from %s in trading!!! Aborting trade", characterA->GetName().c_str());
return;
}
} else {
Log::Warn("Possible cheating attempt from {:s} in trading due to item not being available!!!", characterA->GetName());
LOG("Possible cheating attempt from %s in trading due to item not being available!!!", characterA->GetName().c_str());
return;
}
}
@@ -146,11 +146,11 @@ void Trade::Complete() {
auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId);
if (itemToRemove) {
if (itemToRemove->GetCount() < tradeItem.itemCount) {
Log::Warn("Possible cheating attempt from {:s} in trading!!! Aborting trade", characterB->GetName());
LOG("Possible cheating attempt from %s in trading!!! Aborting trade", characterB->GetName().c_str());
return;
}
} else {
Log::Warn("Possible cheating attempt from {:s} in trading due to item not being available!!! Aborting trade", characterB->GetName());
LOG("Possible cheating attempt from %s in trading due to item not being available!!! Aborting trade", characterB->GetName().c_str());
return;
}
}
@@ -194,7 +194,7 @@ void Trade::SendUpdateToOther(LWOOBJID participant) {
uint64_t coins;
std::vector<TradeItem> itemIds;
Log::Info("Attempting to send trade update");
LOG("Attempting to send trade update");
if (participant == m_ParticipantA) {
other = GetParticipantBEntity();
@@ -228,7 +228,7 @@ void Trade::SendUpdateToOther(LWOOBJID participant) {
items.push_back(tradeItem);
}
Log::Info("Sending trade update");
LOG("Sending trade update");
GameMessages::SendServerTradeUpdate(other->GetObjectID(), coins, items, other->GetSystemAddress());
}
@@ -281,7 +281,7 @@ Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) {
trades[tradeId] = trade;
Log::Info("Created new trade between ({}) <-> ({})", participantA, participantB);
LOG("Created new trade between (%llu) <-> (%llu)", participantA, participantB);
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->UpdateFromDatabase();
m_Characters.push_back(character);
Log::Info("Loaded {:d} as it is the last used char", lastUsedCharacterId);
LOG("Loaded %i as it is the last used char", lastUsedCharacterId);
}
}
}
@@ -106,7 +106,7 @@ void User::UserOutOfSync() {
m_AmountOfTimesOutOfSync++;
if (m_AmountOfTimesOutOfSync > m_MaxDesyncAllowed) {
//YEET
Log::Warn("User {:s} was out of sync {:d} times out of {:d}, disconnecting for suspected speedhacking.", m_Username, m_AmountOfTimesOutOfSync, m_MaxDesyncAllowed);
LOG("User %s was out of sync %i times out of %i, disconnecting for suspected speedhacking.", m_Username.c_str(), m_AmountOfTimesOutOfSync, m_MaxDesyncAllowed);
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");
if (!fnStream) {
Log::Warn("Failed to load {:s}", (Game::assetManager->GetResPath() / "names/minifigname_first.txt").string());
LOG("Failed to load %s", (Game::assetManager->GetResPath() / "names/minifigname_first.txt").string().c_str());
throw std::runtime_error("Aborting initialization due to missing minifigure name file.");
}
@@ -57,7 +57,7 @@ void UserManager::Initialize() {
auto mnStream = Game::assetManager->GetFile("names/minifigname_middle.txt");
if (!mnStream) {
Log::Warn("Failed to load {:s}", (Game::assetManager->GetResPath() / "names/minifigname_middle.txt").string());
LOG("Failed to load %s", (Game::assetManager->GetResPath() / "names/minifigname_middle.txt").string().c_str());
throw std::runtime_error("Aborting initialization due to missing minifigure name file.");
}
@@ -69,7 +69,7 @@ void UserManager::Initialize() {
auto lnStream = Game::assetManager->GetFile("names/minifigname_last.txt");
if (!lnStream) {
Log::Warn("Failed to load {:s}", (Game::assetManager->GetResPath() / "names/minifigname_last.txt").string());
LOG("Failed to load %s", (Game::assetManager->GetResPath() / "names/minifigname_last.txt").string().c_str());
throw std::runtime_error("Aborting initialization due to missing minifigure name file.");
}
@@ -82,7 +82,7 @@ void UserManager::Initialize() {
// Load our pre-approved names:
auto chatListStream = Game::assetManager->GetFile("chatplus_en_us.txt");
if (!chatListStream) {
Log::Warn("Failed to load {:s}", (Game::assetManager->GetResPath() / "chatplus_en_us.txt").string());
LOG("Failed to load %s", (Game::assetManager->GetResPath() / "chatplus_en_us.txt").string().c_str());
throw std::runtime_error("Aborting initialization due to missing chat whitelist file.");
}
@@ -145,7 +145,7 @@ bool UserManager::DeleteUser(const SystemAddress& sysAddr) {
void UserManager::DeletePendingRemovals() {
for (auto* user : m_UsersToDelete) {
Log::Info("Deleted user {:d}", user->GetAccountID());
LOG("Deleted user %i", user->GetAccountID());
delete user;
}
@@ -306,27 +306,27 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet)
LOT pantsLOT = FindCharPantsID(pantsColor);
if (!name.empty() && Database::Get()->GetCharacterInfo(name)) {
Log::Info("AccountID: {:d} chose unavailable name: {:s}", u->GetAccountID(), name);
LOG("AccountID: %i chose unavailable name: %s", u->GetAccountID(), name.c_str());
WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::CUSTOM_NAME_IN_USE);
return;
}
if (Database::Get()->GetCharacterInfo(predefinedName)) {
Log::Info("AccountID: {:d} chose unavailable predefined name: {:s}", u->GetAccountID(), predefinedName);
LOG("AccountID: %i chose unavailable predefined name: %s", u->GetAccountID(), predefinedName.c_str());
WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::PREDEFINED_NAME_IN_USE);
return;
}
if (name.empty()) {
Log::Info("AccountID: {:d} is creating a character with predefined name: {:s}", u->GetAccountID(), predefinedName);
LOG("AccountID: %i is creating a character with predefined name: %s", u->GetAccountID(), predefinedName.c_str());
} else {
Log::Info("AccountID: {:d} is creating a character with name: {:s} (temporary: {:s})", u->GetAccountID(), name, predefinedName);
LOG("AccountID: %i is creating a character with name: %s (temporary: %s)", u->GetAccountID(), name.c_str(), predefinedName.c_str());
}
//Now that the name is ok, we can get an objectID from Master:
ObjectIDManager::RequestPersistentID([=, this](uint32_t objectID) mutable {
if (Database::Get()->GetCharacterInfo(objectID)) {
Log::Warn("Character object id unavailable, check object_id_tracker!");
LOG("Character object id unavailable, check object_id_tracker!");
WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::OBJECT_ID_UNAVAILABLE);
return;
}
@@ -397,7 +397,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet)
void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) {
User* u = GetUser(sysAddr);
if (!u) {
Log::Warn("Couldn't get user to delete character");
LOG("Couldn't get user to delete character");
return;
}
@@ -406,7 +406,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet)
inStream.Read(objectID);
uint32_t charID = static_cast<uint32_t>(objectID);
Log::Info("Received char delete req for ID: {:d} ({:d})", objectID, charID);
LOG("Received char delete req for ID: %llu (%u)", objectID, charID);
bool hasCharacter = CheatDetection::VerifyLwoobjidIsSender(
objectID,
@@ -418,7 +418,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet)
if (!hasCharacter) {
WorldPackets::SendCharacterDeleteResponse(sysAddr, false);
} else {
Log::Info("Deleting character {:d}", charID);
LOG("Deleting character %i", charID);
Database::Get()->DeleteCharacter(charID);
CBITSTREAM;
@@ -433,7 +433,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet)
void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) {
User* u = GetUser(sysAddr);
if (!u) {
Log::Warn("Couldn't get user to delete character");
LOG("Couldn't get user to delete character");
return;
}
@@ -444,7 +444,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet)
GeneralUtils::ClearBit(objectID, eObjectBits::PERSISTENT);
uint32_t charID = static_cast<uint32_t>(objectID);
Log::Info("Received char rename request for ID: {:d} ({:d})", objectID, charID);
LOG("Received char rename request for ID: %llu (%u)", objectID, charID);
LUWString LUWStringName;
inStream.Read(LUWStringName);
@@ -479,12 +479,12 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet)
if (!Database::Get()->GetCharacterInfo(newName)) {
if (IsNamePreapproved(newName)) {
Database::Get()->SetCharacterName(charID, newName);
Log::Info("Character {:s} now known as {:s}", character->GetName(), newName);
LOG("Character %s now known as %s", character->GetName().c_str(), newName.c_str());
WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::SUCCESS);
UserManager::RequestCharacterList(sysAddr);
} else {
Database::Get()->SetPendingCharacterName(charID, newName);
Log::Info("Character {:s} has been renamed to {:s} and is pending approval by a moderator.", character->GetName(), newName);
LOG("Character %s has been renamed to %s and is pending approval by a moderator.", character->GetName().c_str(), newName.c_str());
WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::SUCCESS);
UserManager::RequestCharacterList(sysAddr);
}
@@ -492,7 +492,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet)
WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::NAME_IN_USE);
}
} else {
Log::Warn("Unknown error occurred when renaming character, either hasCharacter or character variable != true.");
LOG("Unknown error occurred when renaming character, either hasCharacter or character variable != true.");
WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::UNKNOWN_ERROR);
}
}
@@ -500,7 +500,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet)
void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID) {
User* u = GetUser(sysAddr);
if (!u) {
Log::Warn("Couldn't get user to log in character");
LOG("Couldn't get user to log in character");
return;
}
@@ -519,7 +519,7 @@ void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID
if (zoneID == LWOZONEID_INVALID) zoneID = 1000; //Send char to VE
ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneID, character->GetZoneClone(), false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) {
Log::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);
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);
if (character) {
character->SetZoneID(zoneID);
character->SetZoneInstance(zoneInstance);
@@ -529,7 +529,7 @@ void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID
return;
});
} else {
Log::Warn("Unknown error occurred when logging in a character, either hasCharacter or character variable != true.");
LOG("Unknown error occurred when logging in a character, either hasCharacter or character variable != true.");
}
}
@@ -546,7 +546,7 @@ uint32_t FindCharShirtID(uint32_t shirtColor, uint32_t shirtStyle) {
tableData.finalize();
return shirtLOT;
} catch (const std::exception& ex) {
Log::Warn("Could not look up shirt {:d} {:d}: {:s}", shirtColor, shirtStyle, ex.what());
LOG("Could not look up shirt %i %i: %s", shirtColor, shirtStyle, ex.what());
// in case of no shirt found in CDServer, return problematic red vest.
return 4069;
}
@@ -564,7 +564,7 @@ uint32_t FindCharPantsID(uint32_t pantsColor) {
tableData.finalize();
return pantsLOT;
} catch (const std::exception& ex) {
Log::Warn("Could not look up pants {:d}: {:s}", pantsColor, ex.what());
LOG("Could not look up pants %i: %s", pantsColor, ex.what());
// in case of no pants color found in CDServer, return red pants.
return 2508;
}

View File

@@ -5,35 +5,35 @@
#include "Game.h"
#include "Logger.h"
void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
uint32_t handle{};
if (!bitStream.Read(handle)) {
Log::Warn("Unable to read handle from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits());
if (!bitStream->Read(handle)) {
LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
}
context->RegisterSyncBehavior(handle, this, branch, this->m_Timeout);
}
void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
const auto handle = context->GetUniqueSkillId();
bitStream.Write(handle);
bitStream->Write(handle);
}
void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
uint32_t behaviorId{};
if (!bitStream.Read(behaviorId)) {
Log::Warn("Unable to read behaviorId from bitStream, aborting Sync! {:d}", bitStream.GetNumberOfUnreadBits());
if (!bitStream->Read(behaviorId)) {
LOG("Unable to read behaviorId from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits());
return;
}
LWOOBJID target{};
if (!bitStream.Read(target)) {
Log::Warn("Unable to read target from bitStream, aborting Sync! {:d}", bitStream.GetNumberOfUnreadBits());
if (!bitStream->Read(target)) {
LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits());
return;
}

View File

@@ -6,11 +6,11 @@ class AirMovementBehavior final : public Behavior
public:
explicit AirMovementBehavior(const uint32_t behavior_id) : Behavior(behavior_id) {}
void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Load() override;
private:

View File

@@ -3,13 +3,13 @@
#include "Game.h"
#include "Logger.h"
void AndBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) {
void AndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
for (auto* behavior : this->m_behaviors) {
behavior->Handle(context, bitStream, branch);
}
}
void AndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) {
void AndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
for (auto* behavior : this->m_behaviors) {
behavior->Calculate(context, bitStream, branch);
}

View File

@@ -15,9 +15,9 @@ public:
explicit AndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {
}
void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override;

View File

@@ -5,7 +5,7 @@
#include "BuffComponent.h"
void ApplyBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void ApplyBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
auto* entity = Game::entityManager->GetEntity(branch.target == LWOOBJID_EMPTY ? context->originator : branch.target);
if (entity == nullptr) return;
@@ -30,7 +30,7 @@ void ApplyBuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext b
buffComponent->RemoveBuff(m_BuffId);
}
void ApplyBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void ApplyBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
Handle(context, bitStream, branch);
}

View File

@@ -24,11 +24,11 @@ public:
explicit ApplyBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {
}
void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Load() override;
private:

View File

@@ -12,11 +12,11 @@
#include "Game.h"
#include "Logger.h"
void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
uint32_t targetCount{};
if (!bitStream.Read(targetCount)) {
Log::Warn("Unable to read targetCount from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits());
if (!bitStream->Read(targetCount)) {
LOG("Unable to read targetCount from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
}
@@ -28,7 +28,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& b
}
if (targetCount > this->m_maxTargets) {
Log::Warn("Serialized size is greater than max targets! Size: {:d}, Max: {:d}", targetCount, this->m_maxTargets);
LOG("Serialized size is greater than max targets! Size: %i, Max: %i", targetCount, this->m_maxTargets);
return;
}
@@ -40,8 +40,8 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& b
for (auto i = 0u; i < targetCount; ++i) {
LWOOBJID target{};
if (!bitStream.Read(target)) {
Log::Warn("failed to read in target {:d} from bitStream, aborting target Handle!", i);
if (!bitStream->Read(target)) {
LOG("failed to read in target %i from bitStream, aborting target Handle!", i);
};
targets.push_back(target);
}
@@ -54,7 +54,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& b
PlayFx(u"cast", context->originator);
}
void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
auto* caster = Game::entityManager->GetEntity(context->caster);
if (!caster) return;
@@ -83,7 +83,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream
// resize if we have more than max targets allows
if (targets.size() > this->m_maxTargets) targets.resize(this->m_maxTargets);
bitStream.Write<uint32_t>(targets.size());
bitStream->Write<uint32_t>(targets.size());
if (targets.size() == 0) {
PlayFx(u"miss", context->originator);
@@ -92,7 +92,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream
context->foundTarget = true;
// write all the targets to the bitstream
for (auto* target : targets) {
bitStream.Write(target->GetObjectID());
bitStream->Write(target->GetObjectID());
}
// then cast all the actions

View File

@@ -6,8 +6,8 @@ class AreaOfEffectBehavior final : public Behavior
{
public:
explicit AreaOfEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {}
void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Load() override;
private:
Behavior* m_action;

View File

@@ -4,11 +4,11 @@
#include "Game.h"
#include "Logger.h"
void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) {
void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
uint32_t handle{};
if (!bitStream.Read(handle)) {
Log::Warn("Unable to read handle from bitStream, aborting Handle! {:d}", bitStream.GetNumberOfUnreadBits());
if (!bitStream->Read(handle)) {
LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
@@ -17,10 +17,10 @@ void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bi
}
}
void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) {
void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
const auto handle = context->GetUniqueSkillId();
bitStream.Write(handle);
bitStream->Write(handle);
context->foundTarget = true;
@@ -31,11 +31,11 @@ void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream&
}
}
void AttackDelayBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) {
void AttackDelayBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
this->m_action->Handle(context, bitStream, branch);
}
void AttackDelayBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) {
void AttackDelayBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
PlayFx(u"cast", context->originator);
this->m_action->Calculate(context, bitStream, branch);

View File

@@ -19,13 +19,13 @@ public:
explicit AttackDelayBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {
}
void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Load() override;
};

View File

@@ -9,7 +9,7 @@
#include "BehaviorContext.h"
#include "eBasicAttackSuccessTypes.h"
void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
if (context->unmanaged) {
auto* entity = Game::entityManager->GetEntity(branch.target);
@@ -30,31 +30,31 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bi
return;
}
bitStream.AlignReadToByteBoundary();
bitStream->AlignReadToByteBoundary();
uint16_t allocatedBits{};
if (!bitStream.Read(allocatedBits) || allocatedBits == 0) {
Log::Debug("No allocated bits");
if (!bitStream->Read(allocatedBits) || allocatedBits == 0) {
LOG_DEBUG("No allocated bits");
return;
}
Log::Debug("Number of allocated bits {:d}", allocatedBits);
const auto baseAddress = bitStream.GetReadOffset();
LOG_DEBUG("Number of allocated bits %i", allocatedBits);
const auto baseAddress = bitStream->GetReadOffset();
DoHandleBehavior(context, bitStream, branch);
bitStream.SetReadOffset(baseAddress + allocatedBits);
bitStream->SetReadOffset(baseAddress + allocatedBits);
}
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);
if (!targetEntity) {
Log::Warn("Target targetEntity {:d} not found.", branch.target);
LOG("Target targetEntity %llu not found.", branch.target);
return;
}
auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>();
if (!destroyableComponent) {
Log::Warn("No destroyable found on the obj/lot {:d}/{:d}", branch.target, targetEntity->GetLOT());
LOG("No destroyable found on the obj/lot %llu/%i", branch.target, targetEntity->GetLOT());
return;
}
@@ -62,8 +62,8 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
bool isImmune{};
bool isSuccess{};
if (!bitStream.Read(isBlocked)) {
Log::Warn("Unable to read isBlocked");
if (!bitStream->Read(isBlocked)) {
LOG("Unable to read isBlocked");
return;
}
@@ -74,32 +74,32 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
return;
}
if (!bitStream.Read(isImmune)) {
Log::Warn("Unable to read isImmune");
if (!bitStream->Read(isImmune)) {
LOG("Unable to read isImmune");
return;
}
if (isImmune) {
Log::Debug("Target targetEntity {} is immune!", branch.target);
LOG_DEBUG("Target targetEntity %llu is immune!", branch.target);
this->m_OnFailImmune->Handle(context, bitStream, branch);
return;
}
if (!bitStream.Read(isSuccess)) {
Log::Warn("failed to read success from bitstream");
if (!bitStream->Read(isSuccess)) {
LOG("failed to read success from bitstream");
return;
}
if (isSuccess) {
uint32_t armorDamageDealt{};
if (!bitStream.Read(armorDamageDealt)) {
Log::Warn("Unable to read armorDamageDealt");
if (!bitStream->Read(armorDamageDealt)) {
LOG("Unable to read armorDamageDealt");
return;
}
uint32_t healthDamageDealt{};
if (!bitStream.Read(healthDamageDealt)) {
Log::Warn("Unable to read healthDamageDealt");
if (!bitStream->Read(healthDamageDealt)) {
LOG("Unable to read healthDamageDealt");
return;
}
@@ -111,8 +111,8 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
}
bool died{};
if (!bitStream.Read(died)) {
Log::Warn("Unable to read died");
if (!bitStream->Read(died)) {
LOG("Unable to read died");
return;
}
auto previousArmor = destroyableComponent->GetArmor();
@@ -122,8 +122,8 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
}
uint8_t successState{};
if (!bitStream.Read(successState)) {
Log::Warn("Unable to read success state");
if (!bitStream->Read(successState)) {
LOG("Unable to read success state");
return;
}
@@ -136,7 +136,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
break;
default:
if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) {
Log::Warn("Unknown success state ({})!", successState);
LOG("Unknown success state (%i)!", successState);
return;
}
this->m_OnFailImmune->Handle(context, bitStream, branch);
@@ -144,41 +144,41 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
}
}
void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
bitStream.AlignWriteToByteBoundary();
void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
bitStream->AlignWriteToByteBoundary();
const auto allocatedAddress = bitStream.GetWriteOffset();
const auto allocatedAddress = bitStream->GetWriteOffset();
bitStream.Write<uint16_t>(0);
bitStream->Write<uint16_t>(0);
const auto startAddress = bitStream.GetWriteOffset();
const auto startAddress = bitStream->GetWriteOffset();
DoBehaviorCalculation(context, bitStream, branch);
const auto endAddress = bitStream.GetWriteOffset();
const auto endAddress = bitStream->GetWriteOffset();
const uint16_t allocate = endAddress - startAddress;
bitStream.SetWriteOffset(allocatedAddress);
bitStream.Write(allocate);
bitStream.SetWriteOffset(startAddress + allocate);
bitStream->SetWriteOffset(allocatedAddress);
bitStream->Write(allocate);
bitStream->SetWriteOffset(startAddress + allocate);
}
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);
if (!targetEntity) {
Log::Warn("Target entity {} is null!", branch.target);
LOG("Target entity %llu is null!", branch.target);
return;
}
auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>();
if (!destroyableComponent || !destroyableComponent->GetParent()) {
Log::Warn("No destroyable component on {}", branch.target);
LOG("No destroyable component on %llu", branch.target);
return;
}
const bool isBlocking = destroyableComponent->GetAttacksToBlock() > 0;
bitStream.Write(isBlocking);
bitStream->Write(isBlocking);
if (isBlocking) {
destroyableComponent->SetAttacksToBlock(destroyableComponent->GetAttacksToBlock() - 1);
@@ -188,10 +188,10 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet
}
const bool isImmune = destroyableComponent->IsImmune() || destroyableComponent->IsCooldownImmune();
bitStream.Write(isImmune);
bitStream->Write(isImmune);
if (isImmune) {
Log::Debug("Target targetEntity {} is immune!", branch.target);
LOG_DEBUG("Target targetEntity %llu is immune!", branch.target);
this->m_OnFailImmune->Calculate(context, bitStream, branch);
return;
}
@@ -210,7 +210,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet
const uint32_t healthDamageDealt = previousHealth - destroyableComponent->GetHealth();
isSuccess = armorDamageDealt > 0 || healthDamageDealt > 0 || (armorDamageDealt + healthDamageDealt) > 0;
bitStream.Write(isSuccess);
bitStream->Write(isSuccess);
//Handle player damage cooldown
if (isSuccess && targetEntity->IsPlayer() && !this->m_DontApplyImmune) {
@@ -225,12 +225,12 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet
successState = this->m_OnFailArmor->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY ? eBasicAttackSuccessTypes::FAILIMMUNE : eBasicAttackSuccessTypes::FAILARMOR;
}
bitStream.Write(armorDamageDealt);
bitStream.Write(healthDamageDealt);
bitStream.Write(targetEntity->GetIsDead());
bitStream->Write(armorDamageDealt);
bitStream->Write(healthDamageDealt);
bitStream->Write(targetEntity->GetIsDead());
}
bitStream.Write(successState);
bitStream->Write(successState);
switch (static_cast<eBasicAttackSuccessTypes>(successState)) {
case eBasicAttackSuccessTypes::SUCCESS:
@@ -241,7 +241,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet
break;
default:
if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) {
Log::Warn("Unknown success state ({})!", GeneralUtils::ToUnderlying(successState));
LOG("Unknown success state (%i)!", successState);
break;
}
this->m_OnFailImmune->Calculate(context, bitStream, branch);

View File

@@ -12,7 +12,7 @@ public:
* is then offset to after the allocated bits for this stream.
*
*/
void DoHandleBehavior(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch);
void DoHandleBehavior(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch);
/**
* @brief Handles a client initialized Basic Attack Behavior cast to be deserialized and verified on the server.
@@ -22,14 +22,14 @@ public:
* and will fail gracefully if an overread is detected.
* @param branch The context of this specific branch of the Skill Behavior. Changes based on which branch you are going down.
*/
void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
/**
* @brief Writes a 16bit short to the bitStream and when the actual behavior calculation finishes with all of its branches, the number
* of bits used is then written to where the 16bit short initially was.
*
*/
void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
/**
* @brief Calculates a server initialized Basic Attack Behavior cast to be serialized to the client
@@ -38,7 +38,7 @@ public:
* @param bitStream The bitStream to serialize to.
* @param branch The context of this specific branch of the Skill Behavior. Changes based on which branch you are going down.
*/
void DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch);
void DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch);
/**
* @brief Loads this Behaviors parameters from the database. For this behavior specifically:

View File

@@ -281,12 +281,12 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) {
case BehaviorTemplates::BEHAVIOR_MOUNT: break;
case BehaviorTemplates::BEHAVIOR_SKILL_SET: break;
default:
//Log::Warn("Failed to load behavior with invalid template id ({:d})!", templateId);
//LOG("Failed to load behavior with invalid template id (%i)!", templateId);
break;
}
if (behavior == nullptr) {
//Log::Warn("Failed to load unimplemented template id ({:d})!", templateId);
//LOG("Failed to load unimplemented template id (%i)!", templateId);
behavior = new EmptyBehavior(behaviorId);
}
@@ -309,7 +309,7 @@ BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) {
}
if (templateID == BehaviorTemplates::BEHAVIOR_EMPTY && behaviorId != 0) {
Log::Warn("Failed to load behavior template with id ({:d})!", behaviorId);
LOG("Failed to load behavior template with id (%i)!", behaviorId);
}
return templateID;
@@ -429,7 +429,7 @@ Behavior::Behavior(const uint32_t behaviorId) {
// Make sure we do not proceed if we are trying to load an invalid behavior
if (templateInDatabase.behaviorID == 0) {
Log::Warn("Failed to load behavior with id ({:d})!", behaviorId);
LOG("Failed to load behavior with id (%i)!", behaviorId);
this->m_effectId = 0;
this->m_effectHandle = nullptr;
@@ -487,10 +487,10 @@ std::map<std::string, float> Behavior::GetParameterNames() const {
void Behavior::Load() {
}
void Behavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void Behavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
}
void Behavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void Behavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
}
void Behavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) {
@@ -502,10 +502,10 @@ void Behavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWO
void Behavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) {
}
void Behavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void Behavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
}
void Behavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
void Behavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
}
Behavior::~Behavior() {

View File

@@ -68,9 +68,9 @@ public:
virtual void Load();
// Player side
virtual void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch);
virtual void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch);
virtual void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch);
virtual void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch);
virtual void UnCast(BehaviorContext* context, BehaviorBranchContext branch);
@@ -79,9 +79,9 @@ public:
virtual void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second);
// Npc side
virtual void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch);
virtual void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch);
virtual void SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch);
virtual void SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch);
/*
* Creations/destruction

View File

@@ -31,7 +31,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const {
auto* entity = Game::entityManager->GetEntity(this->originator);
if (entity == nullptr) {
Log::Warn("Invalid entity for ({})!", this->originator);
LOG("Invalid entity for (%llu)!", this->originator);
return 0;
}
@@ -39,7 +39,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const {
auto* component = entity->GetComponent<SkillComponent>();
if (component == nullptr) {
Log::Warn("No skill component attached to ({})!", this->originator);;
LOG("No skill component attached to (%llu)!", this->originator);;
return 0;
}
@@ -105,7 +105,7 @@ void BehaviorContext::ExecuteUpdates() {
this->scheduledUpdates.clear();
}
void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream& bitStream) {
void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bitStream) {
BehaviorSyncEntry entry;
auto found = false;
@@ -126,7 +126,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream& bit
}
if (!found) {
Log::Warn("Failed to find behavior sync entry with sync id ({})!", syncId);
LOG("Failed to find behavior sync entry with sync id (%i)!", syncId);
return;
}
@@ -135,7 +135,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream& bit
const auto branch = entry.branchContext;
if (behavior == nullptr) {
Log::Warn("Invalid behavior for sync id ({})!", syncId);
LOG("Invalid behavior for sync id (%i)!", syncId);
return;
}
@@ -243,25 +243,27 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) {
echo.uiBehaviorHandle = entry.handle;
echo.uiSkillHandle = this->skillUId;
RakNet::BitStream bitStream{};
auto* bitStream = new RakNet::BitStream();
// Calculate sync
entry.behavior->SyncCalculation(this, bitStream, entry.branchContext);
if (!clientInitalized) {
echo.sBitStream.assign(reinterpret_cast<char*>(bitStream.GetData()), bitStream.GetNumberOfBytesUsed());
echo.sBitStream.assign(reinterpret_cast<char*>(bitStream->GetData()), bitStream->GetNumberOfBytesUsed());
// Write message
RakNet::BitStream message;
BitStreamUtils::WriteHeader(message, eConnectionType::CLIENT, eClientMessageType::GAME_MSG);
message.Write(this->originator);
echo.Serialize(message);
echo.Serialize(&message);
Game::server->Send(message, UNASSIGNED_SYSTEM_ADDRESS, true);
Game::server->Send(&message, UNASSIGNED_SYSTEM_ADDRESS, true);
}
ExecuteUpdates();
delete bitStream;
}
std::vector<BehaviorSyncEntry> valid;
@@ -317,7 +319,7 @@ void BehaviorContext::FilterTargets(std::vector<Entity*>& targets, std::forward_
// if the caster is not there, return empty targets list
auto* caster = Game::entityManager->GetEntity(this->caster);
if (!caster) {
Log::Debug("Invalid caster for ({})!", this->originator);
LOG_DEBUG("Invalid caster for (%llu)!", this->originator);
targets.clear();
return;
}

View File

@@ -93,7 +93,7 @@ struct BehaviorContext
void ExecuteUpdates();
void SyncBehavior(uint32_t syncId, RakNet::BitStream& bitStream);
void SyncBehavior(uint32_t syncId, RakNet::BitStream* bitStream);
void Update(float deltaTime);

View File

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

View File

@@ -13,9 +13,9 @@ public:
explicit BlockBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {
}
void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override;

View File

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

View File

@@ -16,7 +16,7 @@ public:
explicit BuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {
}
void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override;

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