diff --git a/dDashboardServer/routes/CharacterXmlCheck.h b/dDashboardServer/routes/CharacterXmlCheck.h index 69ffe9cbf..0a83cbc6e 100644 --- a/dDashboardServer/routes/CharacterXmlCheck.h +++ b/dDashboardServer/routes/CharacterXmlCheck.h @@ -135,7 +135,7 @@ namespace CharacterXmlCheck { Numbers(c, where, eKind::INT, { "gm", "ft" }); Numbers(c, where, eKind::UINT, { "lwid", "lnzid", "acct" }); Numbers(c, where, eKind::UINT64, { "lzid", "co", "co1", "co2", "co3", "time" }); - Numbers(c, where, eKind::FLOAT, { "lzx", "lzy", "lzz", "lzrx", "lzry", "lzrz", "lzrw" }); + Numbers(c, where, eKind::FLOAT, { "lzx", "lzy", "lzz", "lzrx", "lzry", "lzrz", "lzrw", "stime" }); if (c.Attribute("acct") && Parses(c, "acct", eKind::UINT) && c.UnsignedAttribute("acct") != context.ownerAccountId) { Error(where + ": acct=\"" + c.Attribute("acct") + "\" is not the account of this character (" + std::to_string(context.ownerAccountId) + ")"); diff --git a/dDatabase/GameDatabase/ITables/ICharInfo.h b/dDatabase/GameDatabase/ITables/ICharInfo.h index 2d8654746..a92479199 100644 --- a/dDatabase/GameDatabase/ITables/ICharInfo.h +++ b/dDatabase/GameDatabase/ITables/ICharInfo.h @@ -20,6 +20,8 @@ public: bool needsRename{}; LWOCLONEID cloneId{}; ePermissionMap permissionMap{}; + // charinfo.last_login: when the character was last picked on the character list (unix seconds) + uint64_t lastLogin{}; }; // Get the approved names of all characters. diff --git a/dDatabase/GameDatabase/MySQL/Tables/CharInfo.cpp b/dDatabase/GameDatabase/MySQL/Tables/CharInfo.cpp index edeb762bd..feb1214e4 100644 --- a/dDatabase/GameDatabase/MySQL/Tables/CharInfo.cpp +++ b/dDatabase/GameDatabase/MySQL/Tables/CharInfo.cpp @@ -27,17 +27,18 @@ std::optional CharInfoFromQueryResult(PreparedStmtResultSet& st toReturn.cloneId = stmt->getUInt64("prop_clone_id"); toReturn.accountId = stmt->getUInt("account_id"); toReturn.permissionMap = static_cast(stmt->getUInt("permission_map")); + toReturn.lastLogin = stmt->getUInt64("last_login"); return toReturn; } std::optional MySQLDatabase::GetCharacterInfo(const LWOOBJID charId) { - auto result = ExecuteSelect("SELECT name, pending_name, needs_rename, prop_clone_id, permission_map, id, account_id FROM charinfo WHERE id = ? LIMIT 1;", charId); + auto result = ExecuteSelect("SELECT name, pending_name, needs_rename, prop_clone_id, permission_map, id, account_id, last_login FROM charinfo WHERE id = ? LIMIT 1;", charId); return CharInfoFromQueryResult(result); } std::optional MySQLDatabase::GetCharacterInfo(const std::string_view name) { - auto result = ExecuteSelect("SELECT name, pending_name, needs_rename, prop_clone_id, permission_map, id, account_id FROM charinfo WHERE name = ? LIMIT 1;", name); + auto result = ExecuteSelect("SELECT name, pending_name, needs_rename, prop_clone_id, permission_map, id, account_id, last_login FROM charinfo WHERE name = ? LIMIT 1;", name); return CharInfoFromQueryResult(result); } diff --git a/dDatabase/GameDatabase/SQLite/Tables/CharInfo.cpp b/dDatabase/GameDatabase/SQLite/Tables/CharInfo.cpp index ee540795b..42e671ac4 100644 --- a/dDatabase/GameDatabase/SQLite/Tables/CharInfo.cpp +++ b/dDatabase/GameDatabase/SQLite/Tables/CharInfo.cpp @@ -28,19 +28,20 @@ std::optional CharInfoFromQueryResult(CppSQLite3Query stmt) { toReturn.cloneId = stmt.getInt64Field("prop_clone_id"); toReturn.accountId = stmt.getIntField("account_id"); toReturn.permissionMap = static_cast(stmt.getIntField("permission_map")); + toReturn.lastLogin = static_cast(stmt.getInt64Field("last_login")); return toReturn; } std::optional SQLiteDatabase::GetCharacterInfo(const LWOOBJID charId) { return CharInfoFromQueryResult( - ExecuteSelect("SELECT name, pending_name, needs_rename, prop_clone_id, permission_map, id, account_id FROM charinfo WHERE id = ? LIMIT 1;", charId).second + ExecuteSelect("SELECT name, pending_name, needs_rename, prop_clone_id, permission_map, id, account_id, last_login FROM charinfo WHERE id = ? LIMIT 1;", charId).second ); } std::optional SQLiteDatabase::GetCharacterInfo(const std::string_view name) { return CharInfoFromQueryResult( - ExecuteSelect("SELECT name, pending_name, needs_rename, prop_clone_id, permission_map, id, account_id FROM charinfo WHERE name = ? LIMIT 1;", name).second + ExecuteSelect("SELECT name, pending_name, needs_rename, prop_clone_id, permission_map, id, account_id, last_login FROM charinfo WHERE name = ? LIMIT 1;", name).second ); } diff --git a/dGame/Character.cpp b/dGame/Character.cpp index 1f4a7bbb6..84131e0ed 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -54,6 +54,7 @@ void Character::UpdateInfoFromDatabase() { m_NameRejected = charInfo->needsRename; m_PropertyCloneID = charInfo->cloneId; m_PermissionMap = charInfo->permissionMap; + m_SessionLogin = charInfo->lastLogin; } // Load the xmlData now. Loading takes the character over: saves from any server that loaded it before are refused. @@ -290,6 +291,8 @@ void Character::SaveXMLToDatabase() { lzidConcat = (lzidConcat << 16) | uint16_t(zoneInfo.GetInstanceID()); lzidConcat = (lzidConcat << 16) | uint16_t(zoneInfo.GetMapID()); character->SetAttribute("lzid", lzidConcat); + // The checksum of that zone, as live wrote next to it (LWOCharacterComponent::LoadFromSaveData 0x00ca4910 reads it) + character->SetAttribute("lzcs", Game::zoneManager->GetZone()->GetChecksum()); character->SetAttribute("lnzid", GetLastNonInstanceZoneID()); //Darwin's backup: diff --git a/dGame/Character.h b/dGame/Character.h index 0154c09a6..7d37f18e5 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -133,6 +133,13 @@ public: */ uint64_t GetLastLogin() const { return m_LastLogin; } + /** + * When this character was picked on the character list for the session it is in (charinfo.last_login, unix + * seconds); 0 when not known. Live saved it as and started a new session's play time there. + */ + uint64_t GetSessionLogin() const { return m_SessionLogin; } + void SetSessionLogin(const uint64_t value) { m_SessionLogin = value; } + /** * Gets the default shirt color for this character @@ -693,6 +700,11 @@ private: */ uint64_t m_LastLogin{}; + /** + * charinfo.last_login as it was when this character was loaded + */ + uint64_t m_SessionLogin{}; + /** * Flags only set for the duration of a session * diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 73b5f309e..8c30bd591 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -760,6 +760,14 @@ namespace { * The order the client reads components in (it builds an object's component list in this order in * ObjectLoader2::DoObjectComponentLoad). CHARACTER is preceded by POSSESSOR, LEVEL_PROGRESSION and * PLAYER_FORCED_MOVEMENT, which WriteComponents writes with it. + * + * LWOGameObject::Deserialize (0x00f99690) calls each component's Deserialize in the order of the object's component + * list, which DoObjectComponentLoad (0x0105ebb0) fills in the order of ObjectLoader2::FillComponentOrder + * (0x0101f8e0). From that list: ROLLER (105) comes after SHOOTING_GALLERY (19) and before SCRIPTED_ACTIVITY (39) and + * MOVING_PLATFORM (25); CHOICE_BUILD (52) after MOVING_PLATFORM and before LUP_EXHIBIT (75) and MODEL (42); CHEST (22) + * after MINI_GAME_CONTROL (50) and before RENDER (2). They are placed here against the components their objects + * have (roller: physics, script, skill, inventory, moving platform, render; choice build: physics, destroyable, + * script, render; chest: phantom physics, render). */ constexpr auto SERIALIZATION_ORDER = [] { using enum eReplicaComponentType; @@ -767,8 +775,8 @@ namespace { POSSESSABLE, MODULE_ASSEMBLY, CONTROLLABLE_PHYSICS, SIMPLE_PHYSICS, RIGID_BODY_PHANTOM_PHYSICS, HAVOK_VEHICLE_PHYSICS, PHANTOM_PHYSICS, SOUND_TRIGGER, RACING_SOUND_TRIGGER, BUFF, DESTROYABLE, COLLECTIBLE, PET, PLAYER_FORCED_MOVEMENT, CHARACTER, INVENTORY, - SCRIPT, SKILL, BASE_COMBAT_AI, ITEM, QUICK_BUILD, MOVING_PLATFORM, SWITCH, VENDOR, DONATION_VENDOR, ACHIEVEMENT_VENDOR, - BOUNCER, SCRIPTED_ACTIVITY, SHOOTING_GALLERY, RACING_CONTROL, LUP_EXHIBIT, MODEL, RENDER, MINI_GAME_CONTROL, BBB, + SCRIPT, SKILL, BASE_COMBAT_AI, ITEM, QUICK_BUILD, ROLLER, MOVING_PLATFORM, SWITCH, VENDOR, DONATION_VENDOR, ACHIEVEMENT_VENDOR, + BOUNCER, SCRIPTED_ACTIVITY, SHOOTING_GALLERY, RACING_CONTROL, CHOICE_BUILD, LUP_EXHIBIT, MODEL, CHEST, RENDER, MINI_GAME_CONTROL, BBB, }; }(); @@ -810,6 +818,16 @@ void Entity::WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType } component->Serialize(outBitStream, bIsInitialUpdate); } + + // The client makes the trigger component of an object whose header sets the trigger bit after the others, so it is + // read last. LWOTriggerComponent::Deserialize (0x00bd78c0): a flag and the pick type; live constructions carried + // the flag and -1 (no pick type). + const auto* const triggerComponent = GetComponent(); + const auto* const trigger = triggerComponent ? triggerComponent->GetTrigger() : nullptr; + if (trigger && !trigger->events.empty()) { + outBitStream.Write(bIsInitialUpdate); + if (bIsInitialUpdate) outBitStream.Write(-1); + } } void Entity::UpdateXMLDoc(tinyxml2::XMLDocument& doc) { diff --git a/dGame/dBehaviors/JetPackBehavior.cpp b/dGame/dBehaviors/JetPackBehavior.cpp index 61afc2385..4d2d9f27d 100644 --- a/dGame/dBehaviors/JetPackBehavior.cpp +++ b/dGame/dBehaviors/JetPackBehavior.cpp @@ -1,4 +1,5 @@ #include "JetPackBehavior.h" +#include "ControllablePhysicsComponent.h" #include "BehaviorBranchContext.h" #include "GameMessages.h" @@ -21,6 +22,7 @@ void JetPackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_st jetPackMode.fVertVel = this->m_VerticalVelocity; jetPackMode.iWarningEffectID = this->m_WarningEffectID; jetPackMode.Send(UNASSIGNED_SYSTEM_ADDRESS); + if (auto* const physics = entity->GetComponent()) physics->SetJetPackMode(jetPackMode.bUse, jetPackMode.effectID, jetPackMode.bBypassChecks); if (entity->IsPlayer()) { auto* character = entity->GetCharacter(); @@ -39,6 +41,7 @@ void JetPackBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext bra jetPackMode.target = entity->GetObjectID(); jetPackMode.bUse = false; jetPackMode.Send(UNASSIGNED_SYSTEM_ADDRESS); + if (auto* const physics = entity->GetComponent()) physics->SetJetPackMode(jetPackMode.bUse, jetPackMode.effectID, jetPackMode.bBypassChecks); if (entity->IsPlayer()) { auto* character = entity->GetCharacter(); diff --git a/dGame/dComponents/Activity/ActivityComponent.cpp b/dGame/dComponents/Activity/ActivityComponent.cpp index a0fbc517d..ac2dfb0d4 100644 --- a/dGame/dComponents/Activity/ActivityComponent.cpp +++ b/dGame/dComponents/Activity/ActivityComponent.cpp @@ -80,8 +80,11 @@ void ActivityComponent::LoadActivityData(const int32_t activityId) { } void ActivityComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { - outBitStream.Write(m_DirtyActivityInfo); - if (m_DirtyActivityInfo) { + // A construction always carries the players: it is the only way a client coming into range learns who is in the + // activity (LWOActivityComponent::Deserialize 0x00d002b0), and live wrote the block, empty or not, on every one + const bool writeActivityInfo = m_DirtyActivityInfo || bIsInitialUpdate; + outBitStream.Write(writeActivityInfo); + if (writeActivityInfo) { outBitStream.Write(m_ActivityPlayers.size()); if (!m_ActivityPlayers.empty()) { for (const auto& [playerID, values] : m_ActivityPlayers) { diff --git a/dGame/dComponents/Activity/QuickBuildComponent.cpp b/dGame/dComponents/Activity/QuickBuildComponent.cpp index b4bba0e0f..6953773f1 100644 --- a/dGame/dComponents/Activity/QuickBuildComponent.cpp +++ b/dGame/dComponents/Activity/QuickBuildComponent.cpp @@ -162,7 +162,7 @@ void QuickBuildComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsIni outBitStream.Write(m_ActivatorPosition); outBitStream.Write(m_RepositionPlayer); } - m_StateDirty = false; + if (!bIsInitialUpdate) m_StateDirty = false; } } diff --git a/dGame/dComponents/Activity/RacingControlComponent.cpp b/dGame/dComponents/Activity/RacingControlComponent.cpp index 63fbdb8d2..652cefeb5 100644 --- a/dGame/dComponents/Activity/RacingControlComponent.cpp +++ b/dGame/dComponents/Activity/RacingControlComponent.cpp @@ -3,6 +3,7 @@ */ #include "RacingControlComponent.h" +#include "ControllablePhysicsComponent.h" #include "CharacterComponent.h" #include "DestroyableComponent.h" @@ -276,6 +277,7 @@ void RacingControlComponent::LoadPlayerVehicle(Entity* player, jetPackMode.target = player->GetObjectID(); jetPackMode.bUse = false; jetPackMode.Send(UNASSIGNED_SYSTEM_ADDRESS); + if (auto* const physics = player->GetComponent()) physics->SetJetPackMode(jetPackMode.bUse, jetPackMode.effectID, jetPackMode.bBypassChecks); // Set the vehicle's state. GameMessages::NotifyVehicleOfRacingObject notifyVehicle; diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 986bd7471..abb402483 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -551,7 +551,7 @@ void BaseCombatAIComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsI if (m_DirtyStateOrTarget || bIsInitialUpdate) { outBitStream.Write(m_State); outBitStream.Write(m_Target); - m_DirtyStateOrTarget = false; + if (!bIsInitialUpdate) m_DirtyStateOrTarget = false; } } diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt index 18d82a797..9c42910b4 100644 --- a/dGame/dComponents/CMakeLists.txt +++ b/dGame/dComponents/CMakeLists.txt @@ -16,6 +16,7 @@ set(DGAME_DCOMPONENTS_SOURCES "Character/LevelProgressionComponent.cpp" "LUPExhibitComponent.cpp" "Character/MissionComponent.cpp" + "Character/MountControlComponent.cpp" "MissionOfferComponent.cpp" "ModelComponent.cpp" "ModuleAssemblyComponent.cpp" @@ -33,6 +34,7 @@ set(DGAME_DCOMPONENTS_SOURCES "ProximityMonitorComponent.cpp" "Activity/RacingControlComponent.cpp" "RailActivatorComponent.cpp" + "RollerComponent.cpp" "Activity/QuickBuildComponent.cpp" "RenderComponent.cpp" "Physics/RigidbodyPhantomPhysicsComponent.cpp" diff --git a/dGame/dComponents/Character/CharacterComponent.cpp b/dGame/dComponents/Character/CharacterComponent.cpp index e7bf138a9..9249d74a5 100644 --- a/dGame/dComponents/Character/CharacterComponent.cpp +++ b/dGame/dComponents/Character/CharacterComponent.cpp @@ -1,3 +1,4 @@ +#include #include "CharacterComponent.h" #include "WorldPackets.h" #include "BitStream.h" @@ -81,7 +82,7 @@ bool CharacterComponent::OnGetObjectReportInfo(GameMessages::GetObjectReportInfo cmptType.PushDebug("Component ID") = GeneralUtils::ToUnderlying(ComponentType); cmptType.PushDebug("Character's account ID") = m_Character->GetParentUser()->GetAccountID(); cmptType.PushDebug("Last log out time") = m_Character->GetLastLogin(); - cmptType.PushDebug("Seconds played this session") = 0; + cmptType.PushDebug("Seconds played this session") = m_SessionTimePlayed; cmptType.PushDebug("Editor enabled") = false; cmptType.PushDebug("Total number of seconds played") = m_TotalTimePlayed; cmptType.PushDebug("Total currency") = std::to_string(m_Character->GetCoins()); @@ -246,11 +247,15 @@ void CharacterComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInit outBitStream.Write(m_GMLevel); outBitStream.Write(m_EditorEnabled); outBitStream.Write(m_EditorLevel); + if (!bIsInitialUpdate) m_DirtyGMInfo = false; } const bool writeCurrentActivity = bIsInitialUpdate || m_DirtyCurrentActivity; outBitStream.Write(writeCurrentActivity); - if (writeCurrentActivity) outBitStream.Write(m_CurrentActivity); + if (writeCurrentActivity) { + outBitStream.Write(m_CurrentActivity); + if (!bIsInitialUpdate) m_DirtyCurrentActivity = false; + } const bool writeSocialInfo = bIsInitialUpdate || m_DirtySocialInfo; outBitStream.Write(writeSocialInfo); @@ -325,6 +330,12 @@ void CharacterComponent::LoadFromSaveData(const tinyxml2::XMLDocument& doc) { m_TooltipFlags = 0; character->QueryUnsigned64Attribute("ttip", &m_TooltipFlags); + // Saves from before these were written have neither: a full day's votes, filled up at the next save + m_VotesLeft = VOTES_PER_DAY; + m_VoteDay = 0; + character->QueryIntAttribute("v", &m_VotesLeft); + character->QueryUnsigned64Attribute("vd", &m_VoteDay); + // Load the statistics const auto* statisticsAttribute = character->FindAttribute("stt"); if (statisticsAttribute) { @@ -388,11 +399,22 @@ void CharacterComponent::LoadFromSaveData(const tinyxml2::XMLDocument& doc) { LoadGuild(); - if (character->FindAttribute("time")) { - character->QueryUnsigned64Attribute("time", &m_TotalTimePlayed); - } else { - m_TotalTimePlayed = 0; - } + // Play time as live saved it and the client reads it (LWOCharacterComponent::LoadFromSaveData 0x00ca4910): time is + // the total before the session, stime the seconds of the session so far; the client shows their sum (SendMessage + // 0x00d34330, GetTimePlayed). Saves from before stime was written hold everything in time. + uint64_t timeBeforeSession = 0; + character->QueryUnsigned64Attribute("time", &timeBeforeSession); + double savedSessionTime = 0.0; // the client reads a float + character->QueryDoubleAttribute("stime", &savedSessionTime); + m_SessionTimePlayed = savedSessionTime > 0.0 ? static_cast(savedSessionTime) : 0; + m_TotalTimePlayed = timeBeforeSession + m_SessionTimePlayed; + + // A session starts when the character is picked on the character list; live's llog (and time) changed there and + // stayed over the session's world transfers. A save of another login: its session is over, a new one starts at 0. + uint64_t savedSessionLogin = 0; + character->QueryUnsigned64Attribute("llog", &savedSessionLogin); + const auto sessionLogin = m_Character ? m_Character->GetSessionLogin() : 0; + if (sessionLogin != 0 && sessionLogin != savedSessionLogin) m_SessionTimePlayed = 0; if (!m_Character) return; @@ -445,6 +467,36 @@ void CharacterComponent::WriteSaveData(tinyxml2::XMLDocument& doc) { character->SetAttribute("ls", m_Uscore); // Live wrote ttip on every character, 0 when no tooltip was flagged character->SetAttribute("ttip", m_TooltipFlags); + // Live wrote these on every character (450 of 450 saves that had been saved once); the client reads them in + // LWOCharacterComponent::LoadFromSaveData (0x00ca4910). + // cm, the most coins the character can hold: always 9223372036854775807 on live, the client's own value without + // it. Nothing here caps coins by it, and one that is already in the save is left as it is. + if (!character->FindAttribute("cm")) character->SetAttribute("cm", std::numeric_limits::max()); + // edit, the editor level: the client takes anything but 0 as the editor being on + character->SetAttribute("edit", m_EditorEnabled ? static_cast(m_EditorLevel) : 0u); + // mldt, when the property moderation notice was last shown: not kept here, 0 as on most live saves + if (!character->FindAttribute("mldt")) character->SetAttribute("mldt", 0); + // gid and gn, the guild (0 and empty without one) + character->SetAttribute("gid", static_cast(m_GuildID)); + character->SetAttribute("gn", GeneralUtils::UTF16ToWTF8(m_GuildName).c_str()); + // v and vd, the votes left and the day they are for: a new day fills them up + const uint64_t today = static_cast(std::time(nullptr)) / 86400; + if (m_VoteDay != today) { + m_VotesLeft = VOTES_PER_DAY; + m_VoteDay = today; + } + character->SetAttribute("v", m_VotesLeft); + character->SetAttribute("vd", m_VoteDay); + // lrx.., the last respawn point reached, once one was reached in this world + if (m_respawnPos != NiPoint3Constant::ZERO) { + character->SetAttribute("lrx", m_respawnPos.x); + character->SetAttribute("lry", m_respawnPos.y); + character->SetAttribute("lrz", m_respawnPos.z); + character->SetAttribute("lrrx", m_respawnRot.x); + character->SetAttribute("lrry", m_respawnRot.y); + character->SetAttribute("lrrz", m_respawnRot.z); + character->SetAttribute("lrrw", m_respawnRot.w); + } // Custom attribute to keep track of reputation. character->SetAttribute("rpt", GetReputation()); character->SetAttribute("stt", StatisticsToString().c_str()); @@ -490,8 +542,13 @@ void CharacterComponent::WriteSaveData(tinyxml2::XMLDocument& doc) { auto newUpdateTimestamp = std::time(nullptr); LOG("Time since last save: %d", newUpdateTimestamp - m_LastUpdateTimestamp); - m_TotalTimePlayed += newUpdateTimestamp - m_LastUpdateTimestamp; - character->SetAttribute("time", m_TotalTimePlayed); + const auto sinceLastSave = newUpdateTimestamp > m_LastUpdateTimestamp ? static_cast(newUpdateTimestamp - m_LastUpdateTimestamp) : 0; + m_TotalTimePlayed += sinceLastSave; + m_SessionTimePlayed += sinceLastSave; + // As live: the total before this session and the session's seconds (see LoadFromSaveData); their sum is the total + character->SetAttribute("time", m_TotalTimePlayed - m_SessionTimePlayed); + character->SetAttribute("stime", m_SessionTimePlayed); + if (m_Character && m_Character->GetSessionLogin() != 0) character->SetAttribute("llog", m_Character->GetSessionLogin()); m_LastUpdateTimestamp = newUpdateTimestamp; } diff --git a/dGame/dComponents/Character/CharacterComponent.h b/dGame/dComponents/Character/CharacterComponent.h index 74e20b532..a1770744e 100644 --- a/dGame/dComponents/Character/CharacterComponent.h +++ b/dGame/dComponents/Character/CharacterComponent.h @@ -368,8 +368,20 @@ public: void SetTooltipFlag(int32_t tooltip, bool flag); uint64_t GetTooltipFlags() const { return m_TooltipFlags; } + // WorldConfig's character_votes_per_day + static constexpr int32_t VOTES_PER_DAY = 3; + int32_t GetVotesLeft() const { return m_VotesLeft; } + uint64_t GetVoteDay() const { return m_VoteDay; } + + // Every second played, the running session included (saved as + ) uint64_t GetTotalTimePlayed() const { return m_TotalTimePlayed; }; + // The seconds played since the character was picked on the character list (saved as ) + uint64_t GetSessionTimePlayed() const { return m_SessionTimePlayed; }; + + // When the play time was last counted (construction, then every save); tests move it back to let time pass + void SetLastUpdateTimestamp(const time_t value) { m_LastUpdateTimestamp = value; } + /** * Character info regarding this character, including clothing styles, etc. */ @@ -408,6 +420,11 @@ private: // The tooltips the player has seen, one bit each (char@ttip) uint64_t m_TooltipFlags{}; + // The votes the character has left today (char@v) and the day, in days since 1970, they were last filled up on + // (char@vd), as LWOCharacterComponent::LoadFromSaveData (0x00ca4910) reads them for GetVotesLeft + int32_t m_VotesLeft = VOTES_PER_DAY; + uint64_t m_VoteDay{}; + /** * The lifetime reputation earned by the entity */ @@ -523,6 +540,11 @@ private: */ uint64_t m_TotalTimePlayed; + /** + * The part of m_TotalTimePlayed that was played in the running session, in seconds + */ + uint64_t m_SessionTimePlayed = 0; + /** * The total amount of currency collected by this character */ diff --git a/dGame/dComponents/Character/LevelProgressionComponent.cpp b/dGame/dComponents/Character/LevelProgressionComponent.cpp index c8ffd2f05..30b374f39 100644 --- a/dGame/dComponents/Character/LevelProgressionComponent.cpp +++ b/dGame/dComponents/Character/LevelProgressionComponent.cpp @@ -41,7 +41,8 @@ void LevelProgressionComponent::LoadFromSaveData(const tinyxml2::XMLDocument& do void LevelProgressionComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { outBitStream.Write(bIsInitialUpdate || m_DirtyLevelInfo); if (bIsInitialUpdate || m_DirtyLevelInfo) outBitStream.Write(m_Level); - m_DirtyLevelInfo = false; + // A construction goes to one client; the players already watching still need a waiting change + if (!bIsInitialUpdate) m_DirtyLevelInfo = false; } void LevelProgressionComponent::HandleLevelUp() { diff --git a/dGame/dComponents/Character/MountControlComponent.cpp b/dGame/dComponents/Character/MountControlComponent.cpp new file mode 100644 index 000000000..e079e1284 --- /dev/null +++ b/dGame/dComponents/Character/MountControlComponent.cpp @@ -0,0 +1,21 @@ +#include "MountControlComponent.h" + + +#include "tinyxml2.h" + +void MountControlComponent::LoadFromSaveData(const tinyxml2::XMLDocument& doc) { + const auto* const obj = doc.FirstChildElement("obj"); + const auto* const mount = obj ? obj->FirstChildElement("mnt") : nullptr; + if (mount) mount->QueryInt64Attribute("a", &m_SavedMountItemID); +} + +void MountControlComponent::WriteSaveData(tinyxml2::XMLDocument& doc) { + auto* const obj = doc.FirstChildElement("obj"); + if (!obj) return; + + auto* mount = obj->FirstChildElement("mnt"); + if (!mount) mount = obj->InsertNewChildElement("mnt"); + + // 0 in every live save looked at (450), so 0 is written, riding or not + mount->SetAttribute("a", 0); +} diff --git a/dGame/dComponents/Character/MountControlComponent.h b/dGame/dComponents/Character/MountControlComponent.h index 00cf101f2..847cf6de7 100644 --- a/dGame/dComponents/Character/MountControlComponent.h +++ b/dGame/dComponents/Character/MountControlComponent.h @@ -2,17 +2,31 @@ #define MOUNTCONTROLCOMPONENT_H #include "Component.h" +#include "dCommonVars.h" #include "eReplicaComponentType.h" /** * Mount control (111): the character's riding of mounts, as the client's LWOMountControlComponent: the client makes it (componentID -1) with every character - * (LWOCharacterComponent::Factory). Nothing of it is sent or done on the server yet. + * (LWOCharacterComponent::Factory). It writes the mount element of the character's save as live did: in + * all 450 live saves looked at, so always 0. */ class MountControlComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MOUNT_CONTROL; MountControlComponent(Entity* parent, const int32_t componentID) : Component(parent, componentID) {} + + // LWOMountControlComponent::LoadFromSaveData (0x00bf99c0): , the mount item of the save + void LoadFromSaveData(const tinyxml2::XMLDocument& doc) override; + + // Writes , as live did, also while a mount is ridden + void WriteSaveData(tinyxml2::XMLDocument& doc) override; + + // The mount item the save named (a save may hold one that is not 0). Nothing is mounted from it. + LWOOBJID GetSavedMountItemID() const { return m_SavedMountItemID; } + +private: + LWOOBJID m_SavedMountItemID = LWOOBJID_EMPTY; }; #endif // MOUNTCONTROLCOMPONENT_H diff --git a/dGame/dComponents/Character/PlayerForcedMovementComponent.cpp b/dGame/dComponents/Character/PlayerForcedMovementComponent.cpp index 82c46a6d5..6a0c8fbe4 100644 --- a/dGame/dComponents/Character/PlayerForcedMovementComponent.cpp +++ b/dGame/dComponents/Character/PlayerForcedMovementComponent.cpp @@ -14,7 +14,7 @@ void PlayerForcedMovementComponent::Serialize(RakNet::BitStream& outBitStream, b outBitStream.Write(m_PlayerOnRail); outBitStream.Write(m_ShowBillboard); } - m_DirtyInfo = false; + if (!bIsInitialUpdate) m_DirtyInfo = false; } void PlayerForcedMovementComponent::Allocator(Entity& entity, ObjectLoadState& state) { diff --git a/dGame/dComponents/Character/PossessorComponent.cpp b/dGame/dComponents/Character/PossessorComponent.cpp index 399c41f92..56d72acdc 100644 --- a/dGame/dComponents/Character/PossessorComponent.cpp +++ b/dGame/dComponents/Character/PossessorComponent.cpp @@ -38,7 +38,7 @@ PossessorComponent::~PossessorComponent() { void PossessorComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { outBitStream.Write(m_DirtyPossesor || bIsInitialUpdate); if (m_DirtyPossesor || bIsInitialUpdate) { - m_DirtyPossesor = false; + if (!bIsInitialUpdate) m_DirtyPossesor = false; outBitStream.Write(m_Possessable != LWOOBJID_EMPTY); if (m_Possessable != LWOOBJID_EMPTY) { outBitStream.Write(m_Possessable); @@ -70,6 +70,7 @@ void PossessorComponent::Mount(Entity* mount) { jetPackMode.target = m_Parent->GetObjectID(); jetPackMode.bUse = false; jetPackMode.Send(UNASSIGNED_SYSTEM_ADDRESS); + if (auto* const physics = m_Parent->GetComponent()) physics->SetJetPackMode(jetPackMode.bUse, jetPackMode.effectID, jetPackMode.bBypassChecks); if (mount->GetComponent()) { auto characterComponent = m_Parent->GetComponent(); if (characterComponent) characterComponent->SetIsRacing(true); diff --git a/dGame/dComponents/ChestComponent.h b/dGame/dComponents/ChestComponent.h index 391904202..7e74cc2a9 100644 --- a/dGame/dComponents/ChestComponent.h +++ b/dGame/dComponents/ChestComponent.h @@ -1,17 +1,40 @@ #ifndef CHESTCOMPONENT_H #define CHESTCOMPONENT_H +#include "BitStream.h" #include "Component.h" +#include "dCommonVars.h" #include "eReplicaComponentType.h" /** - * Chest, as the client's LWOChestComponent makes it from the registry. Nothing of it is sent or done on the server yet. + * Chest, as the client's LWOChestComponent makes it from the registry (LOT 2196). Its construction carries the player + * the chest is for and the number of loot offers in it; nothing else of it is done on the server yet. */ class ChestComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::CHEST; ChestComponent(Entity* parent, const int32_t componentID) : Component(parent, componentID) {} + + // LWOChestComponent::Deserialize (0x00c22010) reads on construction only: the player (u64) and the loot offer count + // (u32), which it keeps when the chest is the local player's. Nothing in an update. + void Serialize(RakNet::BitStream& outBitStream, const bool isConstruction) override { + if (!isConstruction) return; + outBitStream.Write(m_PlayerID); + outBitStream.Write(m_LootOfferCount); + } + + LWOOBJID GetPlayerID() const { return m_PlayerID; } + void SetPlayerID(const LWOOBJID value) { m_PlayerID = value; } + uint32_t GetLootOfferCount() const { return m_LootOfferCount; } + void SetLootOfferCount(const uint32_t value) { m_LootOfferCount = value; } + +private: + // The player the chest belongs to; none (the client's own start value) until something gives it one + LWOOBJID m_PlayerID = LWOOBJID_EMPTY; + + // The loot offers in the chest + uint32_t m_LootOfferCount = 0; }; #endif // CHESTCOMPONENT_H diff --git a/dGame/dComponents/ChoiceBuildComponent.h b/dGame/dComponents/ChoiceBuildComponent.h index 74c2b61f3..363450653 100644 --- a/dGame/dComponents/ChoiceBuildComponent.h +++ b/dGame/dComponents/ChoiceBuildComponent.h @@ -1,17 +1,61 @@ #ifndef CHOICEBUILDCOMPONENT_H #define CHOICEBUILDCOMPONENT_H +#include "BitStream.h" #include "Component.h" +#include "dCommonVars.h" #include "eReplicaComponentType.h" /** - * Choice build, as the client's LWOChoiceBuildComponent makes it from the registry. Nothing of it is sent or done on the server yet. + * Choice build, as the client's LWOChoiceBuildComponent makes it from the registry (LOTs 5668, 6414, 6462, 7002, 16205). + * Its state, the object built and the player using it are sent; nothing else of it is done on the server yet. */ class ChoiceBuildComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::CHOICE_BUILD; + // The client's states (its constructor starts at Waiting) + enum class eState : uint32_t { + Waiting = 0, + Building = 1, + }; + ChoiceBuildComponent(Entity* parent, const int32_t componentID) : Component(parent, componentID) {} + + // LWOChoiceBuildComponent::Deserialize (0x00bf26d0) reads, in constructions and updates alike: a flag, then the + // state (u32), the built object (u64) and the user (u64). A construction always carries them. + void Serialize(RakNet::BitStream& outBitStream, const bool isConstruction) override { + outBitStream.Write(isConstruction || m_Dirty); + if (isConstruction || m_Dirty) { + outBitStream.Write(m_State); + outBitStream.Write(m_ChildObject); + outBitStream.Write(m_UserID); + } + if (!isConstruction) m_Dirty = false; + } + + eState GetState() const { return m_State; } + LWOOBJID GetChildObject() const { return m_ChildObject; } + LWOOBJID GetUserID() const { return m_UserID; } + + // Changes what the clients are told with the next update (the caller serializes the object) + void SetState(const eState state, const LWOOBJID childObject, const LWOOBJID userID) { + m_State = state; + m_ChildObject = childObject; + m_UserID = userID; + m_Dirty = true; + } + +private: + eState m_State = eState::Waiting; + + // The object the choice build made, none while waiting + LWOOBJID m_ChildObject = LWOOBJID_EMPTY; + + // The player using the choice build, none while waiting + LWOOBJID m_UserID = LWOOBJID_EMPTY; + + bool m_Dirty = false; }; #endif // CHOICEBUILDCOMPONENT_H diff --git a/dGame/dComponents/CollectibleComponent.cpp b/dGame/dComponents/CollectibleComponent.cpp index fe9d2759a..3d2137e6c 100644 --- a/dGame/dComponents/CollectibleComponent.cpp +++ b/dGame/dComponents/CollectibleComponent.cpp @@ -42,8 +42,9 @@ bool CollectibleComponent::CountsFor(const Entity& player) const { } } +// LWOCollectibleComponent::Deserialize (0x00c45ec0) reads the id on construction only void CollectibleComponent::Serialize(RakNet::BitStream& outBitStream, bool isConstruction) { - outBitStream.Write(GetCollectibleId()); + if (isConstruction) outBitStream.Write(GetCollectibleId()); } bool CollectibleComponent::MsgGetObjectReportInfo(GameMessages::GetObjectReportInfo& reportMsg) { diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 4b007954d..85c288e88 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -259,13 +259,14 @@ void DestroyableComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsIn if (m_ExplodeFactor != 1.0f) outBitStream.Write(m_ExplodeFactor); } } - m_DirtyHealth = false; + // A construction goes to one client; the players already watching still need a waiting change + if (!bIsInitialUpdate) m_DirtyHealth = false; } outBitStream.Write(m_DirtyThreatList || bIsInitialUpdate); if (m_DirtyThreatList || bIsInitialUpdate) { outBitStream.Write(m_HasThreats); - m_DirtyThreatList = false; + if (!bIsInitialUpdate) m_DirtyThreatList = false; } } @@ -532,6 +533,8 @@ void DestroyableComponent::AddFaction(const int32_t factionID, const bool ignore bool DestroyableComponent::IsEnemy(const Entity* other) const { if (IsEnemyImplentation.ExecuteWithDefault(other, false)) return true; if (m_Parent->IsPlayer() && other->IsPlayer()) { + // A player is never its own PVP target + if (other == m_Parent) return false; auto* thisCharacterComponent = m_Parent->GetComponent(); if (!thisCharacterComponent) return false; auto* otherCharacterComponent = other->GetComponent(); diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index a16ee8aa5..f4ef4fe3e 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -32,6 +32,7 @@ #include "ZoneMessages.h" #include "MovementMessages.h" #include "SkillComponent.h" +#include "Behavior.h" #include "Character.h" #include "EntityManager.h" #include "ItemSet.h" @@ -1048,7 +1049,8 @@ void InventoryComponent::Serialize(RakNet::BitStream& outBitStream, const bool b outBitStream.Write(item.bound); } - m_Dirty = false; + // A construction goes to one client; the players already watching still need a waiting equipment change + if (!bIsInitialUpdate) m_Dirty = false; } else { outBitStream.Write(false); } @@ -1693,6 +1695,20 @@ std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip return buffs; } +std::vector InventoryComponent::FindEquippedJetPacks() const { + std::vector jetPacks; + for (const auto& equipped : m_Equipped | std::views::values) { + for (const auto behaviorID : FindBuffs(FindItemById(equipped.id), false)) { + if (Behavior::GetBehaviorTemplate(behaviorID) == BehaviorTemplate::JETPACK) jetPacks.push_back(behaviorID); + } + } + return jetPacks; +} + +void InventoryComponent::RecastEquippedJetPacks() const { + for (const auto behaviorID : FindEquippedJetPacks()) SkillComponent::HandleUnmanaged(behaviorID, m_Parent->GetObjectID()); +} + void InventoryComponent::SetNPCItems(const std::vector& items) { m_Equipped.clear(); diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index 332ce2674..ebbff31e0 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -364,6 +364,17 @@ public: */ std::vector FindBuffs(Item* item, bool castOnEquip) const; + /** + * The jetpack behaviors among the equip skills of the equipped items + */ + std::vector FindEquippedJetPacks() const; + + /** + * Puts a player that wears a jetpack back in jetpack mode after a world load: live sent SetJetPackMode again + * shortly after the player's own construction in the next world, as the equip skill sends it + */ + void RecastEquippedJetPacks() const; + /** * One DeletionRestrictions row (CheckDeletionRestrictionIndex @ 00c94c20). visited stops rows that refer back to * themselves; the client lets such rows through. diff --git a/dGame/dComponents/LUPExhibitComponent.cpp b/dGame/dComponents/LUPExhibitComponent.cpp index 2680b0b2b..69315672a 100644 --- a/dGame/dComponents/LUPExhibitComponent.cpp +++ b/dGame/dComponents/LUPExhibitComponent.cpp @@ -16,8 +16,11 @@ void LUPExhibitComponent::NextLUPExhibit() { } void LUPExhibitComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { - outBitStream.Write(m_DirtyLUPExhibit); - if (m_DirtyLUPExhibit) { + // LWOLUPExhibitComponent::Deserialize (0x00c63790) only learns the exhibit from this block, so a client the object + // comes into range of gets it too + const bool writeExhibit = bIsInitialUpdate || m_DirtyLUPExhibit; + outBitStream.Write(writeExhibit); + if (writeExhibit) { outBitStream.Write(m_LUPExhibits[m_LUPExhibitIndex % m_LUPExhibits.size()]); if (!bIsInitialUpdate) m_DirtyLUPExhibit = false; } diff --git a/dGame/dComponents/Physics/ControllablePhysicsComponent.cpp b/dGame/dComponents/Physics/ControllablePhysicsComponent.cpp index d195546c4..a04ffaa99 100644 --- a/dGame/dComponents/Physics/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/Physics/ControllablePhysicsComponent.cpp @@ -125,7 +125,9 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bo outBitStream.Write(m_DirtyEquippedItemInfo || bIsInitialUpdate); if (m_DirtyEquippedItemInfo || bIsInitialUpdate) { outBitStream.Write(m_PickupRadius); - outBitStream.Write(m_InJetpackMode); + // LWOControllablePhysComponent::Deserialize (0x00c45770) reads this into the same flag as the jetpack block's + // flying bit; live wrote 0, also for players in jetpack mode (10,069 player constructions) + outBitStream.Write(m_JetpackFlying); if (!bIsInitialUpdate) m_DirtyEquippedItemInfo = false; } @@ -181,6 +183,12 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bo } } +void ControllablePhysicsComponent::SetJetPackMode(const bool use, const int32_t effectID, const bool bypassChecks) { + m_InJetpackMode = use; + m_JetpackEffectID = effectID; + m_JetpackBypassChecks = bypassChecks; +} + // A character's save, then where it comes into this world void ControllablePhysicsComponent::LoadFromSaveData(const tinyxml2::XMLDocument& doc) { ReadSaveData(doc); @@ -325,8 +333,7 @@ void ControllablePhysicsComponent::RemovePickupRadiusScale(float value) { void ControllablePhysicsComponent::AddSpeedboost(float value) { m_ActiveSpeedBoosts.push_back(value); - m_SpeedBoost = value; - SetSpeedMultiplier(value / 500.0f); // 500 being the base speed + UpdateSpeedBoost(); } void ControllablePhysicsComponent::RemoveSpeedboost(float value) { @@ -338,16 +345,35 @@ void ControllablePhysicsComponent::RemoveSpeedboost(float value) { return; } - // Recalculate speedboost since we removed one - m_SpeedBoost = 500.0f; // Entities without level progression (enemies, pets) go back to the normal multiplier of 1 - if (m_ActiveSpeedBoosts.empty()) { // no active speed boosts left, so return to base speed + UpdateSpeedBoost(); + Game::entityManager->SerializeEntity(m_Parent); +} + +void ControllablePhysicsComponent::UpdateSpeedBoost() { + // The client's rule (LWOControllablePhysComponent::msgAddRunspeedModifier 0x00be0af0, msgRemoveRunSpeedModifier + // 0x00be0720): a modifier over 1000 or of exactly the base 500 counts for nothing; with any slow (under 500) the + // lowest one is the speed, otherwise the highest boost is + constexpr float baseSpeed = 500.0f; + constexpr float maxModifier = 1000.0f; + float lowestSlow = baseSpeed; + float highestBoost = baseSpeed; + for (const auto boost : m_ActiveSpeedBoosts) { + if (boost > maxModifier) continue; + if (boost < lowestSlow) lowestSlow = boost; + if (boost > highestBoost) highestBoost = boost; + } + + if (lowestSlow < baseSpeed) { + m_SpeedBoost = lowestSlow; + } else if (highestBoost > baseSpeed) { + m_SpeedBoost = highestBoost; + } else { + // No modifier counts: entities without level progression (enemies, pets) go back to the normal multiplier of 1 + m_SpeedBoost = baseSpeed; auto* levelProgressionComponent = m_Parent->GetComponent(); if (levelProgressionComponent) m_SpeedBoost = levelProgressionComponent->GetSpeedBase(); - } else { // Used the last applied speedboost - m_SpeedBoost = m_ActiveSpeedBoosts.back(); } - SetSpeedMultiplier(m_SpeedBoost / 500.0f); // 500 being the base speed - Game::entityManager->SerializeEntity(m_Parent); + SetSpeedMultiplier(m_SpeedBoost / baseSpeed); } void ControllablePhysicsComponent::ActivateBubbleBuff(eBubbleType bubbleType, bool specialAnims) { diff --git a/dGame/dComponents/Physics/ControllablePhysicsComponent.h b/dGame/dComponents/Physics/ControllablePhysicsComponent.h index d82564ca8..27765cdc5 100644 --- a/dGame/dComponents/Physics/ControllablePhysicsComponent.h +++ b/dGame/dComponents/Physics/ControllablePhysicsComponent.h @@ -150,6 +150,12 @@ public: */ const bool GetJetpackBypassChecks() const { return m_JetpackBypassChecks; } + /** + * Keeps what a SetJetPackMode sent to the clients said, for the construction of this object: use, effect and + * bypass checks, as LWOControllablePhysComponent::SendMessage (0x00d2f020) keeps them + */ + void SetJetPackMode(bool use, int32_t effectID, bool bypassChecks); + /** * Set the jetpack effect ID * @param effectID the effect to play while using the jetpack @@ -337,12 +343,12 @@ private: /** * Whether or not this entity is currently flying a jetpack */ - bool m_JetpackFlying; + bool m_JetpackFlying{ false }; /** - * Bypass jetpack checks, currently unused + * Bypass jetpack checks, from the last SetJetPackMode */ - bool m_JetpackBypassChecks; + bool m_JetpackBypassChecks{ false }; /** * The effect that plays while using the jetpack @@ -389,6 +395,11 @@ private: */ bool m_IsTeleporting; + /** + * Works the speed out of the active speed boosts: the lowest slow if there is one, otherwise the highest boost + */ + void UpdateSpeedBoost(); + /** * The list of speed boosts for this entity */ diff --git a/dGame/dComponents/Physics/PhantomPhysicsComponent.cpp b/dGame/dComponents/Physics/PhantomPhysicsComponent.cpp index 6e56088f6..c29dfed77 100644 --- a/dGame/dComponents/Physics/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/Physics/PhantomPhysicsComponent.cpp @@ -3,6 +3,7 @@ * Copyright 2018 */ +#include #include #include @@ -136,13 +137,13 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bI outBitStream.Write(m_EffectType); outBitStream.Write(m_DirectionalMultiplier); - // forgive me father for i have sinned - outBitStream.Write0(); - //outBitStream.Write(m_MinMax); - //if (m_MinMax) { - //outBitStream.Write(m_Min); - //outBitStream.Write(m_Max); - //} + // Live wrote the distances as the client keeps them: "true,150,175" went out as 1 and 175 + outBitStream.Write(m_MinMax); + if (m_MinMax) { + const float min = std::min(m_Min, 1.0f); + outBitStream.Write(min); + outBitStream.Write(std::max(m_Max, min)); + } outBitStream.Write(m_IsDirectional); if (m_IsDirectional) { @@ -152,7 +153,8 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bI } } - m_EffectInfoDirty = false; + // A construction goes to the one client the volume came into range of; the others still need the change + if (!bIsInitialUpdate) m_EffectInfoDirty = false; } } @@ -244,18 +246,50 @@ void PhantomPhysicsComponent::SetEffectType(ePhysicsEffectType type) { m_EffectInfoDirty = true; } -void PhantomPhysicsComponent::SetMin(uint32_t min) { +void PhantomPhysicsComponent::SetMin(const float min) { m_Min = min; m_MinMax = true; m_EffectInfoDirty = true; } -void PhantomPhysicsComponent::SetMax(uint32_t max) { +void PhantomPhysicsComponent::SetMax(const float max) { m_Max = max; m_MinMax = true; m_EffectInfoDirty = true; } +void PhantomPhysicsComponent::SetVolumeEffect(std::vector args) { + for (auto& arg : args) { + arg.erase(0, arg.find_first_not_of(' ')); + arg.erase(arg.find_last_not_of(' ') + 1); + } + + SetPhysicsEffectActive(true); + ePhysicsEffectType effectType = ePhysicsEffectType::PUSH; + if (!args.empty()) { + std::transform(args.at(0).begin(), args.at(0).end(), args.at(0).begin(), ::tolower); + if (args.at(0) == "push") effectType = ePhysicsEffectType::PUSH; + else if (args.at(0) == "attract") effectType = ePhysicsEffectType::ATTRACT; + else if (args.at(0) == "repulse") effectType = ePhysicsEffectType::REPULSE; + else if (args.at(0) == "gravity") effectType = ePhysicsEffectType::GRAVITY_SCALE; + else if (args.at(0) == "friction") effectType = ePhysicsEffectType::FRICTION; + } + + SetEffectType(effectType); + if (args.size() > 1) SetDirectionalMultiplier(GeneralUtils::TryParse(args.at(1), 0.0f)); + if (args.size() > 4) { + // Live sent the direction with the amount as its length ("Push,50,0.91,-0.34,-0.22" as 45.68, -17.07, -11.04) + // and none when it was zero ("Repulse,150,0,0,0,true,25,100") + const NiPoint3 direction = GeneralUtils::TryParse(args.at(2), args.at(3), args.at(4), NiPoint3Constant::ZERO); + if (direction != NiPoint3Constant::ZERO) SetDirection(direction.Unitize()); + } + // Live sent the distances for "true" only: volumes with "1,20,50" went out without them + if (args.size() > 7 && args.at(5) == "true") { + SetMin(GeneralUtils::TryParse(args.at(6), 0.0f)); + SetMax(GeneralUtils::TryParse(args.at(7), 0.0f)); + } +} + void PhantomPhysicsComponent::SetPosition(const NiPoint3& pos) { PhysicsComponent::SetPosition(pos); if (m_dpEntity) m_dpEntity->SetPosition(pos); @@ -281,8 +315,8 @@ bool PhantomPhysicsComponent::OnGetObjectReportInfo(GameMessages::GetObjectRepor if (m_MinMax) { auto& minMaxInfo = info.PushDebug("Min Max Info"); - minMaxInfo.PushDebug("Min") = m_Min; - minMaxInfo.PushDebug("Max") = m_Max; + minMaxInfo.PushDebug("Min") = m_Min; + minMaxInfo.PushDebug("Max") = m_Max; } if (m_IsRespawnVolume) { diff --git a/dGame/dComponents/Physics/PhantomPhysicsComponent.h b/dGame/dComponents/Physics/PhantomPhysicsComponent.h index 5fdb9d8be..bf739f875 100644 --- a/dGame/dComponents/Physics/PhantomPhysicsComponent.h +++ b/dGame/dComponents/Physics/PhantomPhysicsComponent.h @@ -120,14 +120,16 @@ public: void SpawnVertices() const; /** - * Legacy stuff no clue what this does + * The distances the effect scales between; written only once one of them is set. + * LWOPhantomPhysicsComponent::Deserialize (0x00c34db0) keeps the least of the min and 1, and a max of at least that. */ - void SetMin(uint32_t min); + void SetMin(float min); + void SetMax(float max); /** - * Legacy stuff no clue what this does + * A trigger's SetPhysicsVolumeEffect: type, amount, direction x, y, z, use distance, min, max */ - void SetMax(uint32_t max); + void SetVolumeEffect(std::vector args); private: bool OnGetObjectReportInfo(GameMessages::GetObjectReportInfo& reportInfo); @@ -158,8 +160,8 @@ private: float m_DirectionalMultiplier; bool m_MinMax; - uint32_t m_Min; - uint32_t m_Max; + float m_Min; + float m_Max; /** * Whether or not this physics object is pointed in some direction diff --git a/dGame/dComponents/Physics/SimplePhysicsComponent.cpp b/dGame/dComponents/Physics/SimplePhysicsComponent.cpp index a3fb23ae5..5df12647c 100644 --- a/dGame/dComponents/Physics/SimplePhysicsComponent.cpp +++ b/dGame/dComponents/Physics/SimplePhysicsComponent.cpp @@ -73,13 +73,14 @@ void SimplePhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bIs outBitStream.Write(m_Velocity); outBitStream.Write(m_AngularVelocity); } - if (writeVelocity || bIsInitialUpdate) m_DirtyVelocity = false; + // A construction goes to the one client the object came into range of; the others still need the change + if (writeVelocity && !bIsInitialUpdate) m_DirtyVelocity = false; // Physics motion state outBitStream.Write(m_DirtyPhysicsMotionState || bIsInitialUpdate); if (m_DirtyPhysicsMotionState || bIsInitialUpdate) { outBitStream.Write(m_PhysicsMotionState); - m_DirtyPhysicsMotionState = false; + if (!bIsInitialUpdate) m_DirtyPhysicsMotionState = false; } PhysicsComponent::Serialize(outBitStream, bIsInitialUpdate); } diff --git a/dGame/dComponents/PossessableComponent.cpp b/dGame/dComponents/PossessableComponent.cpp index 86330f5c4..61fb6d54a 100644 --- a/dGame/dComponents/PossessableComponent.cpp +++ b/dGame/dComponents/PossessableComponent.cpp @@ -37,7 +37,7 @@ void PossessableComponent::LoadDataFromTemplate() { void PossessableComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { outBitStream.Write(m_DirtyPossessable || bIsInitialUpdate); if (m_DirtyPossessable || bIsInitialUpdate) { - m_DirtyPossessable = false; // reset flag + if (!bIsInitialUpdate) m_DirtyPossessable = false; // reset flag outBitStream.Write(m_Possessor != LWOOBJID_EMPTY); if (m_Possessor != LWOOBJID_EMPTY) outBitStream.Write(m_Possessor); @@ -45,7 +45,7 @@ void PossessableComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsIn if (m_AnimationFlag != eAnimationFlags::IDLE_NONE) outBitStream.Write(m_AnimationFlag); outBitStream.Write(m_ImmediatelyDepossess); - m_ImmediatelyDepossess = false; // reset flag + if (!bIsInitialUpdate) m_ImmediatelyDepossess = false; // reset flag } } diff --git a/dGame/dComponents/Property/PropertyVendorComponent.cpp b/dGame/dComponents/Property/PropertyVendorComponent.cpp index bf1992894..8a6192fdc 100644 --- a/dGame/dComponents/Property/PropertyVendorComponent.cpp +++ b/dGame/dComponents/Property/PropertyVendorComponent.cpp @@ -10,14 +10,32 @@ #include "Logger.h" #include "PropertyManagementComponent.h" #include "UserManager.h" +#include "Mission.h" +#include "MissionComponent.h" PropertyVendorComponent::PropertyVendorComponent(Entity* parent, const int32_t componentID) : Component(parent, componentID) { RegisterMsg(&PropertyVendorComponent::OnRequestUse); } +uint32_t PropertyVendorComponent::GetRequiredMission() const { + return m_Parent->GetVarAs(u"property_required_mission"); +} + +bool PropertyVendorComponent::MayRent(Entity& player) const { + const auto required = GetRequiredMission(); + if (required == 0) return true; + + const auto* const missions = player.GetComponent(); + const auto* const mission = missions ? missions->GetMission(required) : nullptr; + // The client asks its list of finished missions: one that was completed and is repeated counts as well + return mission != nullptr && (mission->IsComplete() || mission->GetCompletions() > 0); +} + bool PropertyVendorComponent::OnRequestUse(GameMessages::RequestUseEvent& event) { if (event.msg.IsMissionChoice()) return false; auto* const originator = event.user; + // LWOPropertyVendorComponent::onCheckUseRequirements (0x00c2e210): no use without the level's mission + if (!MayRent(*originator)) return true; if (PropertyManagementComponent::Instance() == nullptr) return true; OnQueryPropertyData(originator, originator->GetSystemAddress()); @@ -41,6 +59,15 @@ void PropertyVendorComponent::OnQueryPropertyData(Entity* originator, const Syst } void PropertyVendorComponent::OnBuyFromVendor(Entity* originator, const bool confirmed, const LOT lot, const uint32_t count) { + if (!MayRent(*originator)) { + LOG("Player %llu rents a property without mission %u", originator->GetObjectID(), GetRequiredMission()); + GameMessages::PropertyRentalResponse refused; + refused.target = m_Parent->GetObjectID(); + refused.code = RENTAL_MISSING_ACHIEVEMENT; + refused.Send(originator->GetSystemAddress()); + return; + } + if (PropertyManagementComponent::Instance() == nullptr) return; if (PropertyManagementComponent::Instance()->Claim(originator->GetObjectID()) == false) { diff --git a/dGame/dComponents/Property/PropertyVendorComponent.h b/dGame/dComponents/Property/PropertyVendorComponent.h index 4b706a7e8..d479111c0 100644 --- a/dGame/dComponents/Property/PropertyVendorComponent.h +++ b/dGame/dComponents/Property/PropertyVendorComponent.h @@ -34,4 +34,16 @@ public: * @param count unused */ void OnBuyFromVendor(Entity* originator, bool confirmed, LOT lot, uint32_t count); + + // PropertyRentalResponse code the client shows as "you failed to rent" with UGG_PROPRENT_Dont_have_achievement + // (LWOPropertyVendorComponent::onPropertyRentalResponse 0x00c56d70; 0 is a rented property) + static constexpr uint32_t RENTAL_MISSING_ACHIEVEMENT = 9; + + // The level's property_required_mission (LWOPropertyVendorComponent::LoadConfigData 0x00c2e550), 0 without one + uint32_t GetRequiredMission() const; + + // Whether the player has finished the level's property_required_mission, which the client asks for before the + // vendor can be used (LWOPropertyVendorComponent::onCheckUseRequirements 0x00c2e210). A vendor without the key + // asks for nothing here. + bool MayRent(Entity& player) const; }; diff --git a/dGame/dComponents/ProximityMonitorComponent.cpp b/dGame/dComponents/ProximityMonitorComponent.cpp index 112fc2429..6a7fb696a 100644 --- a/dGame/dComponents/ProximityMonitorComponent.cpp +++ b/dGame/dComponents/ProximityMonitorComponent.cpp @@ -1,5 +1,6 @@ #include "ProximityMonitorComponent.h" #include "CDClientManager.h" +#include "CDClientDatabase.h" #include "CDProximityMonitorComponentTable.h" #include "GameMessages.h" #include "dZoneManager.h" @@ -19,20 +20,29 @@ ProximityMonitorComponent::ProximityMonitorComponent(Entity* parent, const int32 RegisterMsg(&ProximityMonitorComponent::OnGetObjectReportInfo); } -// The ProximityMonitorComponent row's radii, "small,large" (one value, as LOT 9833's "4", is both): the rocket -// launch radii +// The ProximityMonitorComponent row lists ProximityTypes ids ("7,8": RocketSign and WorldLauncher), not radii. Each +// type has a name, a radius and where it is loaded: LWOProximityMonitorComponent::LoadDataFromTemplate (0x00c2dfb0) +// keeps the ids and SendMessage (0x00cbb930), on AddedToWorld, sets a proximity up under the type's name for each one +// that has LoadOnClient. The server's are the ones with LoadOnServer, of a row that has it too. void ProximityMonitorComponent::LoadDataFromTemplate() { if (m_ComponentID <= 0) return; const auto componentID = m_ComponentID; const auto proxCompData = CDClientManager::GetTable()->Query([componentID](const CDProximityMonitorComponent& entry) { return (entry.id == componentID); }); - if (proxCompData.empty()) return; + if (proxCompData.empty() || !proxCompData[0].LoadOnServer) return; - const auto radii = GeneralUtils::SplitString(proxCompData[0].Proximities, ','); - const auto small = radii.empty() ? std::nullopt : GeneralUtils::TryParse(radii[0]); - const auto large = radii.size() > 1 ? GeneralUtils::TryParse(radii[1]) : small; - if (!small || !large) return; - SetProximityRadius(*small, "rocketSmall"); - SetProximityRadius(*large, "rocketLarge"); + for (const auto& typeString : GeneralUtils::SplitString(proxCompData[0].Proximities, ',')) { + const auto typeID = GeneralUtils::TryParse(typeString); + if (!typeID) continue; + auto query = CDClientDatabase::CreatePreppedStmt("SELECT Name, Radius, LoadOnServer FROM ProximityTypes WHERE id = ?;"); + query.bind(1, *typeID); + auto result = query.execQuery(); + if (result.eof() || result.getIntField("LoadOnServer", 0) == 0) continue; + const std::string name = result.getStringField("Name", ""); + if (name.empty()) continue; + // A missing or non-positive radius is 30, as the client takes it + const auto radius = result.getIntField("Radius", 30); + SetProximityRadius(static_cast(radius > 0 ? radius : 30), name); + } } ProximityMonitorComponent::~ProximityMonitorComponent() { diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index bd2066c4d..0c07e06e8 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -9,6 +9,7 @@ #include "CombatMessages.h" #include "MovementMessages.h" #include "QuickBuildComponent.h" +#include "Preconditions.h" #include "Game.h" #include "Logger.h" #include "RenderComponent.h" @@ -42,6 +43,7 @@ void RailActivatorComponent::LoadDataFromTemplate() { m_ShowNameBillboard = tableData.showNameBillboard; m_CameraLocked = tableData.cameraLocked; m_CollisionEnabled = tableData.playerCollision; + m_Preconditions = tableData.preconditions; } // The level config: a key, when there, replaces the row's value, as StartRailMovement's flags replace the row's in @@ -71,6 +73,11 @@ bool RailActivatorComponent::OnRequestUse(GameMessages::RequestUseEvent& event) if (quickBuildComponent != nullptr && quickBuildComponent->GetState() != eQuickBuildState::COMPLETED) return true; + // LWORailActivatorComponent::msgCheckUseRequirements (0x00c2c5b0): after the quick build, the row's preconditions + // have to pass and the rail has to be on; the client does not send a use otherwise ("-1": the table has none) + if (!m_Active) return true; + if (!m_Preconditions.empty() && m_Preconditions != "-1" && !PreconditionExpression(m_Preconditions).Check(originator)) return true; + if (quickBuildComponent != nullptr) { // Don't want it to be destroyed while a player is using it quickBuildComponent->SetResetTime(quickBuildComponent->GetResetTime() + 10.0f); diff --git a/dGame/dComponents/RailActivatorComponent.h b/dGame/dComponents/RailActivatorComponent.h index 7be3f5a07..5c0b88ef6 100644 --- a/dGame/dComponents/RailActivatorComponent.h +++ b/dGame/dComponents/RailActivatorComponent.h @@ -46,6 +46,9 @@ public: * Whether the rail can be used (level key rail_activator_active; every rail in the live levels has it set) */ bool GetActive() const { return m_Active; } + + // The players that used the rail and have not left it yet + const std::vector& GetEntitiesOnRail() const { return m_EntitiesOnRail; } bool GetNoAggro() const { return m_NoAggro; } bool GetShowNameBillboard() const { return m_ShowNameBillboard; } private: @@ -131,6 +134,11 @@ private: */ bool m_UseDB; + /** + * The row's preconditions a player has to pass to use the rail + */ + std::string m_Preconditions; + /** * Client flag */ diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.cpp b/dGame/dComponents/RocketLaunchpadControlComponent.cpp index f5148d3a2..3ebc7a145 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.cpp +++ b/dGame/dComponents/RocketLaunchpadControlComponent.cpp @@ -30,7 +30,7 @@ RocketLaunchpadControlComponent::RocketLaunchpadControlComponent(Entity* parent, // The RocketLaunchpadControlComponent row void RocketLaunchpadControlComponent::LoadDataFromTemplate() { auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT targetZone, defaultZoneID, targetScene, altLandingPrecondition, altLandingSpawnPointName FROM RocketLaunchpadControlComponent WHERE id = ?;"); + "SELECT targetZone, defaultZoneID, targetScene, altLandingPrecondition, altLandingSpawnPointName, gmLevel, useLaunchPrecondition, launchPrecondition FROM RocketLaunchpadControlComponent WHERE id = ?;"); query.bind(1, m_ComponentID); auto result = query.execQuery(); @@ -41,11 +41,30 @@ void RocketLaunchpadControlComponent::LoadDataFromTemplate() { m_TargetScene = result.getStringField("targetScene"); m_AltPrecondition = new PreconditionExpression(result.getStringField("altLandingPrecondition")); m_AltLandingScene = result.getStringField("altLandingSpawnPointName"); + m_GMLevel = result.getIntField("gmLevel", 0); + if (result.getIntField("useLaunchPrecondition", 0) != 0) m_LaunchPrecondition = result.getStringField("launchPrecondition", ""); } result.finalize(); } +// The level's keys. LWORocketLaunchComponentCommon::LoadConfigData (0x00c55150) reads them into the fields the row +// would fill, and the row replaces them only while rocketLaunchUseDBDefaults is true, its default (0x00c12ea0). A pad +// that turns it off is ruled by its level: 31 pads in the 1.10.64 maps, whose zones and scenes are their rows' but +// whose launch preconditions only the level has (the Venture Explorer's and Avant Gardens' pads). +void RocketLaunchpadControlComponent::LoadConfigData() { + if (!m_Parent->HasVar(u"rocketLaunchUseDBDefaults") || m_Parent->GetVarAs(u"rocketLaunchUseDBDefaults")) return; + + if (m_Parent->HasVar(u"targetZone")) m_TargetZone = m_Parent->GetVarAs(u"targetZone"); + m_DefaultZone = m_Parent->GetVarAs(u"propertyDefaultTargetZone"); + m_TargetScene = m_Parent->GetVarAsString(u"targetScene"); + m_GMLevel = m_Parent->GetVarAs(u"GMLevel"); + m_LaunchPrecondition = m_Parent->GetVarAs(u"rocketUseLaunchPrecondition") ? m_Parent->GetVarAsString(u"rocketLaunchPreCondition") : ""; + m_AltLandingScene = m_Parent->GetVarAsString(u"rocketAltLandingSpawnName"); + delete m_AltPrecondition; + m_AltPrecondition = new PreconditionExpression(m_Parent->GetVarAsString(u"rocketAltLandingPrecondition")); +} + RocketLaunchpadControlComponent::~RocketLaunchpadControlComponent() { delete m_AltPrecondition; } @@ -57,6 +76,11 @@ GameMessages::FireEventClientSide RocketLaunchpadControlComponent::MakeRocketEqu return rocketEquipped; } +bool RocketLaunchpadControlComponent::MayLaunch(Entity& player) const { + if (static_cast(player.GetGMLevel()) < m_GMLevel) return false; + return m_LaunchPrecondition.empty() || PreconditionExpression(m_LaunchPrecondition).Check(&player); +} + void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, LWOCLONEID cloneId, int32_t worldIndex) { auto zone = mapId == LWOMAPID_INVALID ? m_TargetZone : mapId; @@ -64,6 +88,8 @@ void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, return; } + if (!MayLaunch(*originator)) return; + // This also gets triggered by a proximity monitor + item equip, I will set that up when havok is ready auto* characterComponent = originator->GetComponent(); auto* character = originator->GetCharacter(); diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.h b/dGame/dComponents/RocketLaunchpadControlComponent.h index c2e63ee36..a4e72b81a 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.h +++ b/dGame/dComponents/RocketLaunchpadControlComponent.h @@ -28,6 +28,16 @@ public: ~RocketLaunchpadControlComponent() override; void LoadDataFromTemplate() override; + void LoadConfigData() override; + + const std::string& GetTargetScene() const { return m_TargetScene; } + + /** + * Whether the player may launch from this pad: LWORocketLaunchComponentCommon refuses a player under the pad's GM + * level (msgFireEventClientSide 0x00cb78b0) or that fails its launch precondition (msgCheckUseRequirements + * 0x00c7d0d0), so a client does not ask + */ + bool MayLaunch(Entity& player) const; /** * Launches some entity to another world @@ -136,7 +146,18 @@ private: /** * Some precondition that needs to be met to trigger the alternative landing scene */ - PreconditionExpression* m_AltPrecondition; + PreconditionExpression* m_AltPrecondition{}; + + /** + * The GM level a player needs to launch from this pad (the row's gmLevel, or the level's GMLevel) + */ + int32_t m_GMLevel{}; + + /** + * The row's launchPrecondition, when its useLaunchPrecondition is set: what a player has to pass to launch. For a pad + * whose level turns rocketLaunchUseDBDefaults off, the level's rocketLaunchPreCondition and rocketUseLaunchPrecondition. + */ + std::string m_LaunchPrecondition; /** * Notifies the master server to prepare some world for a player to be able to travel to it diff --git a/dGame/dComponents/RollerComponent.cpp b/dGame/dComponents/RollerComponent.cpp new file mode 100644 index 000000000..0b6185732 --- /dev/null +++ b/dGame/dComponents/RollerComponent.cpp @@ -0,0 +1,17 @@ +#include "RollerComponent.h" + +#include "Entity.h" +#include "GeneralUtils.h" + +namespace { + // A level point: the three numbers with character 31 between them + NiPoint3 LevelPoint(const Entity& entity, const std::u16string& key) { + const auto parts = GeneralUtils::SplitString(entity.GetVarAsString(key), '\x1f'); + return GeneralUtils::TryParse(parts).value_or(NiPoint3Constant::ZERO); + } +} + +void RollerComponent::LoadConfigData() { + m_CameraPosition = LevelPoint(*m_Parent, u"activity_camera_pos"); + m_CameraLookAt = LevelPoint(*m_Parent, u"activity_camera_lookat_pos"); +} diff --git a/dGame/dComponents/RollerComponent.h b/dGame/dComponents/RollerComponent.h index 0cd64106b..9d2f6df9c 100644 --- a/dGame/dComponents/RollerComponent.h +++ b/dGame/dComponents/RollerComponent.h @@ -1,17 +1,54 @@ #ifndef ROLLERCOMPONENT_H #define ROLLERCOMPONENT_H +#include "BitStream.h" #include "Component.h" +#include "NiPoint3.h" +#include "dCommonVars.h" #include "eReplicaComponentType.h" /** - * Roller, as the client's LWORollerComponent makes it from the registry. Nothing of it is sent or done on the server yet. + * Roller (a launcher a player fires from: LOTs 2714, 13951), as the client's LWORollerComponent makes it from the + * registry. Its construction carries the activity camera and the projectile skill; nobody uses one on the server + * yet, so the block about its user is never sent. */ class RollerComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::ROLLER; + // The projectile skill the client's constructor starts with (LWORollerComponent::Initialize 0x00cc7e30) + static constexpr uint32_t DEFAULT_PROJECTILE_SKILL = 1348; + RollerComponent(Entity* parent, const int32_t componentID) : Component(parent, componentID) {} + + // The level's activity_camera_pos and activity_camera_lookat_pos (LWORollerComponent::LoadConfigData 0x00c31820); + // both stay at the origin without the key, as in the client + void LoadConfigData() override; + + // LWORollerComponent::Deserialize (0x00c15920) reads on construction: the camera position and what it looks at + // (3 floats each) and the projectile skill (u32). Then, in constructions and updates alike, a flag in front of the + // block about the player using it (3 x u64, 3 floats, a float, 3 floats, the player u64, a float): never set here. + void Serialize(RakNet::BitStream& outBitStream, const bool isConstruction) override { + if (isConstruction) { + outBitStream.Write(m_CameraPosition.x); + outBitStream.Write(m_CameraPosition.y); + outBitStream.Write(m_CameraPosition.z); + outBitStream.Write(m_CameraLookAt.x); + outBitStream.Write(m_CameraLookAt.y); + outBitStream.Write(m_CameraLookAt.z); + outBitStream.Write(m_ProjectileSkill); + } + outBitStream.Write0(); + } + + const NiPoint3& GetCameraPosition() const { return m_CameraPosition; } + const NiPoint3& GetCameraLookAt() const { return m_CameraLookAt; } + uint32_t GetProjectileSkill() const { return m_ProjectileSkill; } + +private: + NiPoint3 m_CameraPosition = NiPoint3Constant::ZERO; + NiPoint3 m_CameraLookAt = NiPoint3Constant::ZERO; + uint32_t m_ProjectileSkill = DEFAULT_PROJECTILE_SKILL; }; #endif // ROLLERCOMPONENT_H diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index 7aa97f65c..dd1f7fd94 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -407,34 +407,7 @@ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::v LOG_DEBUG("Phantom Physics component not found!"); return; } - phantomPhysicsComponent->SetPhysicsEffectActive(true); - ePhysicsEffectType effectType = ePhysicsEffectType::PUSH; - if (!argArray.empty()) { - std::transform(argArray.at(0).begin(), argArray.at(0).end(), argArray.at(0).begin(), ::tolower); //Transform to lowercase - if (argArray.at(0) == "push") effectType = ePhysicsEffectType::PUSH; - else if (argArray.at(0) == "attract") effectType = ePhysicsEffectType::ATTRACT; - else if (argArray.at(0) == "repulse") effectType = ePhysicsEffectType::REPULSE; - else if (argArray.at(0) == "gravity") effectType = ePhysicsEffectType::GRAVITY_SCALE; - else if (argArray.at(0) == "friction") effectType = ePhysicsEffectType::FRICTION; - } - - phantomPhysicsComponent->SetEffectType(effectType); - if (argArray.size() > 1) { - phantomPhysicsComponent->SetDirectionalMultiplier(GeneralUtils::TryParse(argArray.at(1), 0.0f)); - } - if (argArray.size() > 4) { - const NiPoint3 direction = - GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4), NiPoint3Constant::ZERO); - - phantomPhysicsComponent->SetDirection(direction); - } - if (argArray.size() > 6) { - const uint32_t min = GeneralUtils::TryParse(argArray.at(6), 0); - phantomPhysicsComponent->SetMin(min); - - const uint32_t max = GeneralUtils::TryParse(argArray.at(7), 0); - phantomPhysicsComponent->SetMax(max); - } + phantomPhysicsComponent->SetVolumeEffect(argArray); Game::entityManager->SerializeEntity(targetEntity); } diff --git a/dGame/dGameMessages/ZoneMessages.cpp b/dGame/dGameMessages/ZoneMessages.cpp index 5937a01e4..362519f71 100644 --- a/dGame/dGameMessages/ZoneMessages.cpp +++ b/dGame/dGameMessages/ZoneMessages.cpp @@ -151,6 +151,9 @@ namespace GameMessages { character->OnZoneLoad(); } + // A jetpack that is worn works again in the new world (jetpack mode is not saved) + if (auto* const inventory = entity->GetComponent()) inventory->RecastEquippedJetPacks(); + // Moved here from another instance: put back what their save doesn't keep (the pet that was out) WorldMigration::OnPlayerLoaded(entity); diff --git a/dGame/dUtilities/ReplicaDecoder.cpp b/dGame/dUtilities/ReplicaDecoder.cpp index 6a2acfde4..6c5f4328a 100644 --- a/dGame/dUtilities/ReplicaDecoder.cpp +++ b/dGame/dUtilities/ReplicaDecoder.cpp @@ -389,7 +389,8 @@ namespace { } if (r.Bit()) j["onThreatList"] = r.Bit(); } }, - { COLLECTIBLE, [](Reader& r, json& j, bool, const auto&) { j["collectibleID"] = r.Get(); } }, + // LWOCollectibleComponent::Deserialize: the id on construction only + { COLLECTIBLE, [](Reader& r, json& j, bool initial, const auto&) { if (initial) j["collectibleID"] = r.Get(); } }, // LWOPetComponent::Deserialize: everything under the dirty bit, the names on updates too { PET, [](Reader& r, json& j, bool, const auto&) { if (!r.Bit()) return; diff --git a/dGame/dUtilities/SlashCommands/GMGreaterThanZeroCommands.cpp b/dGame/dUtilities/SlashCommands/GMGreaterThanZeroCommands.cpp index bb35b3563..d5a6c8448 100644 --- a/dGame/dUtilities/SlashCommands/GMGreaterThanZeroCommands.cpp +++ b/dGame/dUtilities/SlashCommands/GMGreaterThanZeroCommands.cpp @@ -1,4 +1,5 @@ #include "GMGreaterThanZeroCommands.h" +#include "ControllablePhysicsComponent.h" #include "ChatServerLink.h" #include "DashboardNotify.h" #include "SlashCommandHandler.h" @@ -206,6 +207,7 @@ namespace GMGreaterThanZeroCommands { jetPackMode.target = entity->GetObjectID(); jetPackMode.bUse = false; jetPackMode.Send(UNASSIGNED_SYSTEM_ADDRESS); + if (auto* const physics = entity->GetComponent()) physics->SetJetPackMode(jetPackMode.bUse, jetPackMode.effectID, jetPackMode.bBypassChecks); character->SetIsFlying(false); } else { @@ -235,6 +237,7 @@ namespace GMGreaterThanZeroCommands { jetPackMode.fMaxAirspeed = maxAirSpeed; jetPackMode.fVertVel = verticalVelocity; jetPackMode.Send(UNASSIGNED_SYSTEM_ADDRESS); + if (auto* const physics = entity->GetComponent()) physics->SetJetPackMode(jetPackMode.bUse, jetPackMode.effectID, jetPackMode.bBypassChecks); character->SetIsFlying(true); } diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 424803d8e..45c181713 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -248,9 +248,24 @@ namespace ClientPackets { ldfData.Insert(u"name", name); ldfData.Insert(u"gmlevel", static_cast(gmLevel)); ldfData.Insert(u"chatmode", chatMode); - ldfData.Insert(u"reputation", reputation); + // Live sent reputation as LDF type 8 (451 of 451 character data packets); the old packet has it as type 9 + if (sendWorldKeys) ldfData.Insert(u"reputation", static_cast(reputation)); + else ldfData.Insert(u"reputation", reputation); ldfData.Insert(u"propertycloneid", propertyCloneID); if (txfring) ldfData.Insert(u"txfring", true); + if (sendWorldKeys) { + ldfData.Insert(u"legoclub", legoClub); + ldfData.Insert(u"freetrial", freeTrial); + ldfData.Insert(u"requiresrename", requiresRename); + ldfData.Insert(u"levelid", levelID); + ldfData.Insert(u"position.x", position.x); + ldfData.Insert(u"position.y", position.y); + ldfData.Insert(u"position.z", position.z); + ldfData.Insert(u"rotation.x", rotation.x); + ldfData.Insert(u"rotation.y", rotation.y); + ldfData.Insert(u"rotation.z", rotation.z); + ldfData.Insert(u"rotation.w", rotation.w); + } data.Write(ldfData.values.size()); for (const auto& toSerialize : ldfData | std::views::values) toSerialize->WriteToPacket(data); @@ -309,6 +324,8 @@ namespace ClientPackets { RakNet::BitStream data(uncompressed.data(), uncompressed.size(), false); txfring = false; // the client's value without the key + sendWorldKeys = false; + legoClub = false; uint32_t count{}; VALIDATE_READ(data.Read(count)); for (uint32_t i = 0; i < count; i++) { @@ -349,6 +366,28 @@ namespace ClientPackets { uint8_t value{}; VALIDATE_READ(data.Read(value)); if (key == u"txfring") txfring = value != 0; + else if (key == u"legoclub") legoClub = value != 0; + else if (key == u"freetrial") freeTrial = value != 0; + else if (key == u"requiresrename") requiresRename = value != 0; + break; + } + case LDF_TYPE_U64: { + uint64_t value{}; + VALIDATE_READ(data.Read(value)); + if (key == u"levelid") { levelID = value; sendWorldKeys = true; } + else if (key == u"reputation") reputation = static_cast(value); + break; + } + case LDF_TYPE_FLOAT: { + float value{}; + VALIDATE_READ(data.Read(value)); + if (key == u"position.x") position.x = value; + else if (key == u"position.y") position.y = value; + else if (key == u"position.z") position.z = value; + else if (key == u"rotation.x") rotation.x = value; + else if (key == u"rotation.y") rotation.y = value; + else if (key == u"rotation.z") rotation.z = value; + else if (key == u"rotation.w") rotation.w = value; break; } default: diff --git a/dNet/ClientPackets.h b/dNet/ClientPackets.h index c40a39315..b48c09b63 100644 --- a/dNet/ClientPackets.h +++ b/dNet/ClientPackets.h @@ -27,6 +27,7 @@ #include "MessageType/Client.h" #include "MessageType/Game.h" #include "NiPoint3.h" +#include "NiQuaternion.h" #include "Stamps.h" enum class eCharacterCreationResponse : uint8_t; @@ -189,6 +190,15 @@ namespace ClientPackets { // packet, and with it false the client shows inventory-full tips on every world load. Not written when false // (the client's default). bool txfring = true; + // The keys below were in every live character data packet. LWOCharacterComponent::LoadConfigData (0x00c70f00) + // reads requiresrename, legoclub and freetrial. Not written when sendWorldKeys is false. + bool sendWorldKeys = true; + bool legoClub = true; + bool freeTrial = false; + bool requiresRename = false; // The name was refused and a new one is asked for + uint64_t levelID{}; // map id, instance id << 16, clone id << 32 + NiPoint3 position{}; + NiQuaternion rotation = QuatUtils::IDENTITY; CreateCharacter() : LUBitStream(ServiceType::CLIENT, MessageType::Client::CREATE_CHARACTER) {} void Serialize(RakNet::BitStream& bitStream) const override; diff --git a/dNet/PacketFields.inc b/dNet/PacketFields.inc index 61f6e6169..c7903f44f 100644 --- a/dNet/PacketFields.inc +++ b/dNet/PacketFields.inc @@ -640,6 +640,13 @@ json ToJson(const ClientPackets::CreateCharacter& m) { j["reputation"] = ToJson(m.reputation); j["propertyCloneID"] = ToJson(m.propertyCloneID); j["txfring"] = ToJson(m.txfring); + j["sendWorldKeys"] = ToJson(m.sendWorldKeys); + j["legoClub"] = ToJson(m.legoClub); + j["freeTrial"] = ToJson(m.freeTrial); + j["requiresRename"] = ToJson(m.requiresRename); + j["levelID"] = ToJson(m.levelID); + j["position"] = ToJson(m.position); + j["rotation"] = ToJson(m.rotation); return j; } json ToJson(const ClientPackets::ChatModerationString& m) { diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 96f79385e..a9d0ca019 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -1019,6 +1019,17 @@ void HandleMasterPacket(Packet* packet) { } } +// What every live character data packet also carried: the world the player loads into, where it stands there and +// whether its name was refused (LWOCharacterComponent::LoadConfigData 0x00c70f00 reads requiresrename) +void SetWorldKeys(ClientPackets::CreateCharacter& createCharacter, const Entity& player, const Character& character) { + const auto& zoneID = Game::zoneManager->GetZoneID(); + createCharacter.levelID = static_cast(zoneID.GetMapID()) | static_cast(zoneID.GetInstanceID()) << 16 | + static_cast(zoneID.GetCloneID()) << 32; + createCharacter.position = player.GetPosition(); + createCharacter.rotation = player.GetRotation(); + createCharacter.requiresRename = character.GetNameRejected(); +} + // Creates the player's entity and sends the client everything in the world: after the client loaded the zone // (LEVEL_LOAD_COMPLETE), or at once when it kept its scene (an experimental seamless migration) // A player already in the world whose client reloaded the zone: its character again (from its current save), every @@ -1037,6 +1048,7 @@ void ReloadPlayerInPlace(const SystemAddress& sysAddr, Entity& player, Character createCharacter.chatMode = static_cast(character.GetGMLevel()); createCharacter.reputation = characterComponent->GetReputation(); createCharacter.propertyCloneID = character.GetPropertyCloneID(); + SetWorldKeys(createCharacter, player, character); createCharacter.Send(sysAddr); ClientPackets::ServerStates serverStates; serverStates.Send(sysAddr); @@ -1194,6 +1206,7 @@ void LoadPlayer(const SystemAddress& sysAddr) { createCharacter.chatMode = static_cast(c->GetGMLevel()); createCharacter.reputation = characterComponent->GetReputation(); createCharacter.propertyCloneID = c->GetPropertyCloneID(); + SetWorldKeys(createCharacter, *player, *c); createCharacter.Send(sysAddr); LOG("Sent CreateCharacter for ID: %llu", player->GetObjectID()); ClientPackets::ServerStates serverStates; diff --git a/tests/dGameTests/dComponentsTests/CMakeLists.txt b/tests/dGameTests/dComponentsTests/CMakeLists.txt index efc31b5aa..45d4e2242 100644 --- a/tests/dGameTests/dComponentsTests/CMakeLists.txt +++ b/tests/dGameTests/dComponentsTests/CMakeLists.txt @@ -4,7 +4,11 @@ set(DCOMPONENTS_TESTS "InventorySaveTests.cpp" "EquipMessagesTests.cpp" "DestroyableLevelConfigTests.cpp" + "ProximityMonitorComponentTests.cpp" "RailActivatorComponentTests.cpp" + "MountControlComponentTests.cpp" + "ConstructionOnlyComponentTests.cpp" + "PropertyVendorComponentTests.cpp" "VendorBuybackTests.cpp" "RacingWrongWayTests.cpp" "DestroyableComponentTests.cpp" diff --git a/tests/dGameTests/dComponentsTests/CharacterSaveFieldsTests.cpp b/tests/dGameTests/dComponentsTests/CharacterSaveFieldsTests.cpp index 1204a7451..3c3357804 100644 --- a/tests/dGameTests/dComponentsTests/CharacterSaveFieldsTests.cpp +++ b/tests/dGameTests/dComponentsTests/CharacterSaveFieldsTests.cpp @@ -17,6 +17,7 @@ #include "tinyxml2.h" +#include #include #include @@ -115,6 +116,196 @@ TEST_F(CharacterSaveFieldsTests, TooltipFlagsMissingInOldSave) { EXPECT_STREQ(doc.FirstChildElement("obj")->FirstChildElement("char")->Attribute("ttip"), "0"); } +// The attributes live wrote on every character and the client reads: cm, edit, mldt, gid, gn, v, vd and the +// last respawn point. A save that has them keeps what the server does not own, and nothing touches the coins. +TEST_F(CharacterSaveFieldsTests, LiveCharacterAttributesRoundTrip) { + tinyxml2::XMLDocument doc; + Parse(doc, R"()"); + + Character character(1, nullptr); + Entity player(40, info); + auto* const characterComponent = player.AddComponent(-1, &character, UNASSIGNED_SYSTEM_ADDRESS); + characterComponent->LoadFromSaveData(doc); + EXPECT_EQ(characterComponent->GetVotesLeft(), 1); + EXPECT_EQ(characterComponent->GetVoteDay(), 1u); + + characterComponent->WriteSaveData(doc); + const auto* const saved = doc.FirstChildElement("obj")->FirstChildElement("char"); + EXPECT_STREQ(saved->Attribute("cc"), "22609"); + EXPECT_STREQ(saved->Attribute("cm"), "5000"); // kept, not replaced and not applied + EXPECT_STREQ(saved->Attribute("mldt"), "1301715419"); + EXPECT_STREQ(saved->Attribute("edit"), "0"); + EXPECT_STREQ(saved->Attribute("gid"), "0"); + EXPECT_STREQ(saved->Attribute("gn"), ""); + // A new day: the votes are filled up + const uint64_t today = static_cast(std::time(nullptr)) / 86400; + EXPECT_LE(saved->Unsigned64Attribute("vd") - today, 1u); // (the day may turn during the test) + EXPECT_STREQ(saved->Attribute("v"), "3"); + // No respawn point was reached in this world: the saved one stays + EXPECT_STREQ(saved->Attribute("lrx"), "1"); + EXPECT_STREQ(saved->Attribute("lrrw"), "0.5"); + // The session goes on (no other login is known): its seconds are kept + EXPECT_GE(saved->Unsigned64Attribute("stime"), 349u); + EXPECT_LE(saved->Unsigned64Attribute("stime"), 351u); + // Not written by the server: left alone + EXPECT_STREQ(saved->Attribute("lzcs"), "2233038349"); + + // The same day: the votes left are kept + Entity reloaded(41, info); + auto* const reloadedComponent = reloaded.AddComponent(-1, &character, UNASSIGNED_SYSTEM_ADDRESS); + doc.FirstChildElement("obj")->FirstChildElement("char")->SetAttribute("v", 2); + reloadedComponent->LoadFromSaveData(doc); + EXPECT_EQ(reloadedComponent->GetVotesLeft(), 2); + reloadedComponent->SetGuild(77, u"Builders"); + reloadedComponent->WriteSaveData(doc); + EXPECT_STREQ(saved->Attribute("v"), "2"); + EXPECT_STREQ(saved->Attribute("gid"), "77"); + EXPECT_STREQ(saved->Attribute("gn"), "Builders"); +} + +// Saves from before they were written load as before and gain them with the values live had: the coins are not +// touched and cm is the client's own "no limit". +TEST_F(CharacterSaveFieldsTests, LiveCharacterAttributesMissingInOldSave) { + tinyxml2::XMLDocument doc; + Parse(doc, R"()"); + + Character character(1, nullptr); + Entity player(42, info); + auto* const characterComponent = player.AddComponent(-1, &character, UNASSIGNED_SYSTEM_ADDRESS); + characterComponent->LoadFromSaveData(doc); + EXPECT_EQ(characterComponent->GetVotesLeft(), 3); + EXPECT_EQ(characterComponent->GetTooltipFlags(), 4u); + EXPECT_EQ(characterComponent->GetUScore(), 15700); + + characterComponent->WriteSaveData(doc); + const auto* const saved = doc.FirstChildElement("obj")->FirstChildElement("char"); + EXPECT_STREQ(saved->Attribute("cc"), "123456789012"); + EXPECT_STREQ(saved->Attribute("acct"), "1"); + EXPECT_STREQ(saved->Attribute("ls"), "15700"); + EXPECT_STREQ(saved->Attribute("cm"), "9223372036854775807"); + EXPECT_STREQ(saved->Attribute("edit"), "0"); + EXPECT_STREQ(saved->Attribute("mldt"), "0"); + EXPECT_STREQ(saved->Attribute("gid"), "0"); + EXPECT_STREQ(saved->Attribute("gn"), ""); + EXPECT_STREQ(saved->Attribute("v"), "3"); + EXPECT_NE(saved->Attribute("vd"), nullptr); + EXPECT_EQ(saved->Attribute("lrx"), nullptr); // no respawn point reached yet + EXPECT_NE(saved->Attribute("stime"), nullptr); +} + +namespace { + // Loads with the given attributes for a character whose login (charinfo.last_login) is sessionLogin, lets + // seconds pass and saves. Returns the saved . + const tinyxml2::XMLElement* LoadPlayAndSave(tinyxml2::XMLDocument& doc, Character& character, CharacterComponent& component, + const std::string& attributes, const uint64_t sessionLogin, const int64_t seconds) { + const auto xml = R"("; + EXPECT_EQ(doc.Parse(xml.c_str()), tinyxml2::XML_SUCCESS); + character.SetSessionLogin(sessionLogin); + component.LoadFromSaveData(doc); + component.SetLastUpdateTimestamp(std::time(nullptr) - seconds); + component.WriteSaveData(doc); + return doc.FirstChildElement("obj")->FirstChildElement("char"); + } + + // The seconds asked for, or one more when the clock ticked during the test + void ExpectAbout(const uint64_t value, const uint64_t expected) { + EXPECT_GE(value, expected); + EXPECT_LE(value, expected + 1); + } +} + +// Play time as live saved it: time is the total before the session, stime the session's seconds, and the client +// shows time + stime (LWOCharacterComponent::LoadFromSaveData 0x00ca4910, SendMessage 0x00d34330 GetTimePlayed). +// A save from before stime was written has every past session in time: the total stays what it was. +TEST_F(CharacterSaveFieldsTests, OldSavePlayTimeKeepsItsTotal) { + tinyxml2::XMLDocument doc; + Character character(1, nullptr); + Entity player(60, info); + auto* const component = player.AddComponent(-1, &character, UNASSIGNED_SYSTEM_ADDRESS); + const auto* const saved = LoadPlayAndSave(doc, character, *component, R"(llog="1700000000" time="54390")", 1700090000, 0); + EXPECT_EQ(component->GetTotalTimePlayed() - component->GetSessionTimePlayed(), 54390u); + ExpectAbout(component->GetTotalTimePlayed(), 54390); + EXPECT_STREQ(saved->Attribute("time"), "54390"); + ExpectAbout(saved->Unsigned64Attribute("stime"), 0); + EXPECT_STREQ(saved->Attribute("llog"), "1700090000"); + EXPECT_EQ(saved->Unsigned64Attribute("time") + saved->Unsigned64Attribute("stime"), component->GetTotalTimePlayed()); + + // The same without a known login (no charinfo row): nothing is lost and llog is left alone + tinyxml2::XMLDocument unknownDoc; + Character unknown(2, nullptr); + Entity other(61, info); + auto* const otherComponent = other.AddComponent(-1, &unknown, UNASSIGNED_SYSTEM_ADDRESS); + const auto* const otherSaved = LoadPlayAndSave(unknownDoc, unknown, *otherComponent, R"(llog="1700000000" time="54390")", 0, 0); + EXPECT_STREQ(otherSaved->Attribute("time"), "54390"); + EXPECT_STREQ(otherSaved->Attribute("llog"), "1700000000"); + ExpectAbout(otherComponent->GetTotalTimePlayed(), 54390); +} + +// A session in progress: the seconds since the last save go to stime, time stays, and a world transfer in the same +// session (the same login) goes on counting in stime. Live: time=262486 with stime=6795, then 7259 in the next world. +TEST_F(CharacterSaveFieldsTests, SessionPlayTimeGrowsInStime) { + tinyxml2::XMLDocument doc; + Character character(1, nullptr); + Entity player(62, info); + auto* const component = player.AddComponent(-1, &character, UNASSIGNED_SYSTEM_ADDRESS); + const auto* saved = LoadPlayAndSave(doc, character, *component, R"(llog="1327837739" time="262486" stime="6795")", 1327837739, 464); + EXPECT_STREQ(saved->Attribute("time"), "262486"); + ExpectAbout(saved->Unsigned64Attribute("stime"), 7259); + EXPECT_STREQ(saved->Attribute("llog"), "1327837739"); + ExpectAbout(component->GetTotalTimePlayed(), 262486 + 7259); + ExpectAbout(component->GetSessionTimePlayed(), 7259); + + // A second save in the same world adds only what passed since the first + component->SetLastUpdateTimestamp(std::time(nullptr) - 10); + component->WriteSaveData(doc); + EXPECT_STREQ(saved->Attribute("time"), "262486"); + EXPECT_GE(saved->Unsigned64Attribute("stime"), 7269u); + EXPECT_LE(saved->Unsigned64Attribute("stime"), 7271u); + + // The next world of the session loads what this one saved and goes on + tinyxml2::XMLPrinter printer(nullptr, true); + doc.Print(&printer); + const std::string written = printer.CStr(); + tinyxml2::XMLDocument next; + ASSERT_EQ(next.Parse(written.c_str()), tinyxml2::XML_SUCCESS); + Entity inNextWorld(63, info); + auto* const nextComponent = inNextWorld.AddComponent(-1, &character, UNASSIGNED_SYSTEM_ADDRESS); + nextComponent->LoadFromSaveData(next); + EXPECT_EQ(nextComponent->GetTotalTimePlayed(), component->GetTotalTimePlayed()); + EXPECT_EQ(nextComponent->GetSessionTimePlayed(), component->GetSessionTimePlayed()); + nextComponent->SetLastUpdateTimestamp(std::time(nullptr) - 30); + nextComponent->WriteSaveData(next); + const auto* const nextSaved = next.FirstChildElement("obj")->FirstChildElement("char"); + EXPECT_STREQ(nextSaved->Attribute("time"), "262486"); + EXPECT_GE(nextSaved->Unsigned64Attribute("stime"), 7299u); + EXPECT_LE(nextSaved->Unsigned64Attribute("stime"), 7302u); +} + +// The next login: the last session's seconds join time and stime starts over. Live: time=262486 stime=7344 at the +// end of one session, time=269830 in the next. The total is the same before and after. +TEST_F(CharacterSaveFieldsTests, ANewSessionMovesStimeIntoTime) { + tinyxml2::XMLDocument doc; + Character character(1, nullptr); + Entity player(64, info); + auto* const component = player.AddComponent(-1, &character, UNASSIGNED_SYSTEM_ADDRESS); + const auto* const saved = LoadPlayAndSave(doc, character, *component, R"(llog="1327837739" time="262486" stime="7344")", 1327848273, 74); + EXPECT_STREQ(saved->Attribute("time"), "269830"); + ExpectAbout(saved->Unsigned64Attribute("stime"), 74); + EXPECT_STREQ(saved->Attribute("llog"), "1327848273"); + ExpectAbout(component->GetTotalTimePlayed(), 269830 + 74); +} + +// The client reads stime as a float; a fraction written by something else is read, not refused +TEST_F(CharacterSaveFieldsTests, FractionalStimeIsRead) { + tinyxml2::XMLDocument doc; + Character character(1, nullptr); + Entity player(65, info); + auto* const component = player.AddComponent(-1, &character, UNASSIGNED_SYSTEM_ADDRESS); + const auto* const saved = LoadPlayAndSave(doc, character, *component, R"(time="100" stime="15.6958")", 0, 0); + EXPECT_STREQ(saved->Attribute("time"), "100"); + ExpectAbout(saved->Unsigned64Attribute("stime"), 15); +} + // : the cooldown groups still running and the seconds left, as live wrote them (sc="17:15.6958;") and the // client reads them (split on ';' and ':'). TEST_F(CharacterSaveFieldsTests, SkillCooldownsRoundTrip) { diff --git a/tests/dGameTests/dComponentsTests/CollectibleComponentTests.cpp b/tests/dGameTests/dComponentsTests/CollectibleComponentTests.cpp index 930265c76..74f16c1c8 100644 --- a/tests/dGameTests/dComponentsTests/CollectibleComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/CollectibleComponentTests.cpp @@ -2,6 +2,7 @@ // the player has that mission. #include "GameDependencies.h" +#include "BitStream.h" #include "GameMessages.h" #include "CDClientDatabase.h" #include "CDClientManager.h" @@ -60,6 +61,24 @@ TEST_F(CollectibleComponentTests, RequirementMissionIsRead) { EXPECT_EQ(other.AddComponent(999, 5)->GetRequirementMission(), -1); // no row } +// LWOCollectibleComponent::Deserialize reads the 16-bit id on construction and nothing on an update. DLU wrote the id +// on updates too, which the client read as the next components' flag bits. +TEST_F(CollectibleComponentTests, TheIdIsWrittenOnConstructionOnly) { + Entity object(22, info); + auto* const collectible = object.AddComponent(78, 5); + + RakNet::BitStream construction; + collectible->Serialize(construction, true); + ASSERT_EQ(construction.GetNumberOfBitsUsed(), 16u); + int16_t id{}; + construction.Read(id); + EXPECT_EQ(id, 5); + + RakNet::BitStream update; + collectible->Serialize(update, false); + EXPECT_EQ(update.GetNumberOfBitsUsed(), 0u); +} + TEST_F(CollectibleComponentTests, AchievementsAndMissingMissionsAlwaysCount) { Entity player(42, info); player.AddComponent(-1); diff --git a/tests/dGameTests/dComponentsTests/ConstructionOnlyComponentTests.cpp b/tests/dGameTests/dComponentsTests/ConstructionOnlyComponentTests.cpp new file mode 100644 index 000000000..ef58f8714 --- /dev/null +++ b/tests/dGameTests/dComponentsTests/ConstructionOnlyComponentTests.cpp @@ -0,0 +1,113 @@ +// What the client reads for a chest, a choice build and a roller: LWOChestComponent::Deserialize (0x00c22010), +// LWOChoiceBuildComponent::Deserialize (0x00bf26d0) and LWORollerComponent::Deserialize (0x00c15920). Where they are +// read among an object's components is in ReplicaComponentOrderTests. +#include "GameDependencies.h" + +#include "BitStream.h" +#include "ChestComponent.h" +#include "ChoiceBuildComponent.h" +#include "Entity.h" +#include "RollerComponent.h" + +#include +#include + +class ConstructionOnlyComponentTests : public GameDependenciesTest { +protected: + void SetUp() override { SetUpDependencies(); } + void TearDown() override { TearDownDependencies(); } + + template + static std::vector Bytes(Component& component, const bool construction, uint32_t* const bits = nullptr) { + RakNet::BitStream stream; + component.Serialize(stream, construction); + if (bits) *bits = stream.GetNumberOfBitsUsed(); + return { stream.GetData(), stream.GetData() + stream.GetNumberOfBytesUsed() }; + } +}; + +// Construction: the player (u64) and the loot offer count (u32); nothing in an update +TEST_F(ConstructionOnlyComponentTests, Chest) { + Entity entity(15, info); + auto* const chest = entity.AddComponent(0); + uint32_t bits{}; + EXPECT_EQ(Bytes(*chest, true, &bits), (std::vector{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); + EXPECT_EQ(bits, 96u); + + chest->SetPlayerID(0x1000000000000001LL); + chest->SetLootOfferCount(3); + EXPECT_EQ(Bytes(*chest, true, &bits), (std::vector{ 0x01, 0, 0, 0, 0, 0, 0, 0x10, 0x03, 0, 0, 0 })); + EXPECT_EQ(bits, 96u); + + EXPECT_TRUE(Bytes(*chest, false, &bits).empty()); + EXPECT_EQ(bits, 0u); +} + +// A flag, then the state (u32), the built object (u64) and the user (u64): always in a construction, in an update +// after a change only +TEST_F(ConstructionOnlyComponentTests, ChoiceBuild) { + Entity entity(15, info); + auto* const choiceBuild = entity.AddComponent(1); + uint32_t bits{}; + // 1 flag bit, then 160 zero bits: waiting, nothing built, nobody using it (the client's own start values) + std::vector waiting(21, 0); + waiting[0] = 0x80; + EXPECT_EQ(Bytes(*choiceBuild, true, &bits), waiting); + EXPECT_EQ(bits, 161u); + + EXPECT_EQ(Bytes(*choiceBuild, false, &bits), (std::vector{ 0x00 })); + EXPECT_EQ(bits, 1u); + + choiceBuild->SetState(ChoiceBuildComponent::eState::Building, 0x0000400000000002LL, 0x1000000000000001LL); + // The same fields shifted by the flag bit: state 1, object 0x0000400000000002, user 0x1000000000000001 + RakNet::BitStream expected; + expected.Write1(); + expected.Write(1); + expected.Write(0x0000400000000002LL); + expected.Write(0x1000000000000001LL); + const std::vector building{ expected.GetData(), expected.GetData() + expected.GetNumberOfBytesUsed() }; + EXPECT_EQ(building[0], 0x80); // the flag, then the low byte of the state (1) one bit on + EXPECT_EQ(building[1], 0x80); + EXPECT_EQ(Bytes(*choiceBuild, false, &bits), building); + EXPECT_EQ(bits, 161u); + // Sent once + EXPECT_EQ(Bytes(*choiceBuild, false, &bits), (std::vector{ 0x00 })); + // A later construction carries the state as it is + EXPECT_EQ(Bytes(*choiceBuild, true, &bits), building); +} + +// Construction: camera position and look-at (3 floats each), the projectile skill (u32, the client starts at 1348), +// then the flag of the user block, which is never set. An update is that flag alone. +TEST_F(ConstructionOnlyComponentTests, Roller) { + Entity entity(15, info); + auto* const roller = entity.AddComponent(13951); + uint32_t bits{}; + std::vector expected(29, 0); + expected[24] = 0x44; // 1348 = 0x544 + expected[25] = 0x05; + EXPECT_EQ(Bytes(*roller, true, &bits), expected); + EXPECT_EQ(bits, 225u); + + EXPECT_EQ(Bytes(*roller, false, &bits), (std::vector{ 0x00 })); + EXPECT_EQ(bits, 1u); +} + +// The level's activity_camera_pos / activity_camera_lookat_pos: three numbers with character 31 between them +TEST_F(ConstructionOnlyComponentTests, RollerCameraComesFromTheLevel) { + Entity entity(15, info); + entity.SetVar(u"activity_camera_pos", u"-327.861\x1f" u"256.91\x1f" u".64822"); + entity.SetVar(u"activity_camera_lookat_pos", u"1\x1f" u"2\x1f" u"-0.5"); + auto* const roller = entity.AddComponent(13951); // loads the level's keys + EXPECT_EQ(roller->GetCameraPosition(), NiPoint3(-327.861f, 256.91f, 0.64822f)); + EXPECT_EQ(roller->GetCameraLookAt(), NiPoint3(1.0f, 2.0f, -0.5f)); + + RakNet::BitStream expected; + for (const float value : { -327.861f, 256.91f, 0.64822f, 1.0f, 2.0f, -0.5f }) expected.Write(value); + expected.Write(1348); + expected.Write0(); + uint32_t bits{}; + EXPECT_EQ(Bytes(*roller, true, &bits), (std::vector{ expected.GetData(), expected.GetData() + expected.GetNumberOfBytesUsed() })); + EXPECT_EQ(bits, 225u); + // 1.0f little endian, the first look-at number + EXPECT_EQ(Bytes(*roller, true)[12 + 3], 0x3f); +} diff --git a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp index b3600d867..63382366b 100644 --- a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp @@ -622,6 +622,63 @@ TEST_F(DestroyableTest, PlayerDieDoesNotClaimAClientDeath) { player.SetCharacter(nullptr); } +// A construction goes to the one client the object came into range of; it must not use up the health change the +// players already watching are waiting for (LWODestroyableComponent::Deserialize reads it behind a flag bit). +TEST_F(DestroyableTest, AConstructionKeepsThePendingHealthChange) { + destroyableComponent->SetHealth(3); + RakNet::BitStream construction; + destroyableComponent->Serialize(construction, true); + + RakNet::BitStream update; + destroyableComponent->Serialize(update, false); + bool hasHealth{}; + uint32_t health{}; + ASSERT_TRUE(update.Read(hasHealth)); + ASSERT_TRUE(hasHealth); + ASSERT_TRUE(update.Read(health)); + EXPECT_EQ(health, 3u); + + // Written once + RakNet::BitStream again; + destroyableComponent->Serialize(again, false); + EXPECT_EQ(again.GetNumberOfBitsUsed(), 2u); +} + +// LWOCharacterComponent::SendMessage, IsValidPVPTarget: two players with PVP on are enemies, a player is never its own +TEST_F(DestroyableTest, APlayerWithPvpIsNotItsOwnEnemy) { + auto playerInfo = info; + playerInfo.lot = 1; + SystemAddress address; + address.binaryAddress = 0x0100007f; + address.port = 2003; + + Entity player(0x1000000000000001LL, playerInfo); + Character character(1, nullptr); + player.SetCharacter(&character); + character.SetEntity(&player); + auto* playerCharacter = player.AddComponent(-1, &character, address); + auto* destroyable = player.AddComponent(-1); + + Entity other(0x1000000000000002LL, playerInfo); + Character otherCharacter(2, nullptr); + other.SetCharacter(&otherCharacter); + otherCharacter.SetEntity(&other); + auto* otherCharacterComponent = other.AddComponent(-1, &otherCharacter, address); + other.AddComponent(-1); + ASSERT_TRUE(player.IsPlayer()); + ASSERT_TRUE(other.IsPlayer()); + + EXPECT_FALSE(destroyable->IsEnemy(&other)); + playerCharacter->SetPvpEnabled(true); + EXPECT_FALSE(destroyable->IsEnemy(&other)); + otherCharacterComponent->SetPvpEnabled(true); + EXPECT_TRUE(destroyable->IsEnemy(&other)); + EXPECT_FALSE(destroyable->IsEnemy(&player)); + + player.SetCharacter(nullptr); + other.SetCharacter(nullptr); +} + // BasicAttack's dir_angle_* are degrees; live's Die carries them as these exact floats. TEST_F(DestroyableTest, DeathDirectionDegreesMatchLiveBits) { const auto bits = [](float value) { uint32_t out; std::memcpy(&out, &value, sizeof(out)); return out; }; diff --git a/tests/dGameTests/dComponentsTests/EquipMessagesTests.cpp b/tests/dGameTests/dComponentsTests/EquipMessagesTests.cpp index 773038b5a..f129a79a8 100644 --- a/tests/dGameTests/dComponentsTests/EquipMessagesTests.cpp +++ b/tests/dGameTests/dComponentsTests/EquipMessagesTests.cpp @@ -6,7 +6,10 @@ #include "CDClientDatabase.h" #include "CDComponentsRegistryTable.h" #include "CDItemComponentTable.h" +#include "CDBehaviorTemplateTable.h" #include "CDObjectSkillsTable.h" +#include "CDSkillBehaviorTable.h" +#include "BehaviorTemplate.h" #include "Character.h" #include "CharacterComponent.h" #include "EffectsMessages.h" @@ -210,3 +213,41 @@ TEST_F(EquipMessagesTests, UnequippingAndSlotsWithoutAnEffect) { sent = Messages(Capture([&] { rocket->Equip(true); })); EXPECT_EQ(sent, (std::vector{ { CHANGE_OBJECT_WORLD_STATE, rocket->GetId(), true, "ATTACHED" } })); } + +// A worn jetpack is found again after a world load, so jetpack mode can be sent again: live sent SetJetPackMode (use, +// bypass checks, effect 167) about 100 packets after the player's own construction in 12 of 28 world loads of a player +// with a jetpack, and constructed the player in jetpack mode in the other 16. +TEST_F(EquipMessagesTests, AWornJetPackIsFoundAfterAWorldLoad) { + constexpr LOT JETPACK = 1727; // skill 306, behavior 3569 on equip + RegisterLot(JETPACK, "back"); + CDClientManager::GetEntriesMutable().push_back({ JETPACK, 306, 1, 0 }); + CDClientManager::GetEntriesMutable().push_back({ SWORD, 400, 0, 0 }); // a use skill, not an equip one + auto& skills = CDClientManager::GetEntriesMutable(); + CDSkillBehavior jetPackSkill{}; + jetPackSkill.skillID = 306; + jetPackSkill.behaviorID = 3569; + skills.insert_or_assign(306, jetPackSkill); + CDSkillBehavior hoodSkill{}; + hoodSkill.skillID = 362; + hoodSkill.behaviorID = 4000; + skills.insert_or_assign(362, hoodSkill); + auto& templates = CDClientManager::GetEntriesMutable(); + CDBehaviorTemplate jetPackTemplate{}; + jetPackTemplate.behaviorID = 3569; + jetPackTemplate.templateID = static_cast(BehaviorTemplate::JETPACK); + templates.insert_or_assign(3569, jetPackTemplate); + CDBehaviorTemplate buffTemplate{}; + buffTemplate.behaviorID = 4000; + buffTemplate.templateID = static_cast(BehaviorTemplate::BUFF); + templates.insert_or_assign(4000, buffTemplate); + + EXPECT_TRUE(inventory->FindEquippedJetPacks().empty()); + // What a save puts back: the equipped items, without their equip skills cast + auto* const hood = Give(HOOD); + auto* const jetPack = Give(JETPACK); + Give(SWORD); + inventory->UpdateSlot("hair", { hood->GetId(), HOOD, 1, 0 }); + EXPECT_TRUE(inventory->FindEquippedJetPacks().empty()); + inventory->UpdateSlot("back", { jetPack->GetId(), JETPACK, 1, 1 }); + EXPECT_EQ(inventory->FindEquippedJetPacks(), std::vector{ 3569 }); +} diff --git a/tests/dGameTests/dComponentsTests/MountControlComponentTests.cpp b/tests/dGameTests/dComponentsTests/MountControlComponentTests.cpp new file mode 100644 index 000000000..6f22c2f5b --- /dev/null +++ b/tests/dGameTests/dComponentsTests/MountControlComponentTests.cpp @@ -0,0 +1,70 @@ +// The mount element of a character's save: LWOMountControlComponent::LoadFromSaveData (0x00bf99c0) reads , and +// every live save had the element, always as (450 looked at). +#include "GameDependencies.h" + +#include "Entity.h" +#include "MountControlComponent.h" +#include "PossessorComponent.h" + +#include "tinyxml2.h" + +#include +#include + +class MountControlComponentTests : public GameDependenciesTest { +protected: + void SetUp() override { SetUpDependencies(); } + void TearDown() override { TearDownDependencies(); } + + static std::string Print(const tinyxml2::XMLDocument& doc) { + tinyxml2::XMLPrinter printer(nullptr, true); + doc.Print(&printer); + return printer.CStr(); + } +}; + +// A save from before the element was written gains it, and nothing else changes +TEST_F(MountControlComponentTests, OldSaveGainsTheElement) { + tinyxml2::XMLDocument doc; + ASSERT_EQ(doc.Parse(R"()"), tinyxml2::XML_SUCCESS); + Entity player(70, info); + auto* const mountControl = player.AddComponent(-1); + mountControl->LoadFromSaveData(doc); + EXPECT_EQ(mountControl->GetSavedMountItemID(), LWOOBJID_EMPTY); + mountControl->WriteSaveData(doc); + EXPECT_EQ(Print(doc), R"()"); + // Saving again changes nothing + mountControl->WriteSaveData(doc); + EXPECT_EQ(Print(doc), R"()"); +} + +// Live wrote 0 in every save, so 0 is written while a mount is ridden as well. A save that holds another value is +// read without failing and gets 0 at the next save. +TEST_F(MountControlComponentTests, ZeroIsWrittenAlsoWhileRiding) { + tinyxml2::XMLDocument doc; + ASSERT_EQ(doc.Parse(R"()"), tinyxml2::XML_SUCCESS); + Entity player(71, info); + auto* const possessor = player.AddComponent(-1); + auto* const mountControl = player.AddComponent(-1); + mountControl->LoadFromSaveData(doc); + EXPECT_EQ(mountControl->GetSavedMountItemID(), 1152921510436607007LL); + + mountControl->WriteSaveData(doc); + EXPECT_EQ(Print(doc), R"()"); + + possessor->SetMountItemID(1152921510436607123LL); + mountControl->WriteSaveData(doc); + EXPECT_EQ(Print(doc), R"()"); +} + +// An a that is not a number is not an error: nothing is read and 0 is written +TEST_F(MountControlComponentTests, AnUnreadableValueDoesNotFail) { + tinyxml2::XMLDocument doc; + ASSERT_EQ(doc.Parse(R"()"), tinyxml2::XML_SUCCESS); + Entity player(72, info); + auto* const mountControl = player.AddComponent(-1); + mountControl->LoadFromSaveData(doc); + EXPECT_EQ(mountControl->GetSavedMountItemID(), LWOOBJID_EMPTY); + mountControl->WriteSaveData(doc); + EXPECT_EQ(Print(doc), R"()"); +} diff --git a/tests/dGameTests/dComponentsTests/PropertyVendorComponentTests.cpp b/tests/dGameTests/dComponentsTests/PropertyVendorComponentTests.cpp new file mode 100644 index 000000000..f07043b7b --- /dev/null +++ b/tests/dGameTests/dComponentsTests/PropertyVendorComponentTests.cpp @@ -0,0 +1,113 @@ +// The property guard's mission: LWOPropertyVendorComponent::onCheckUseRequirements (0x00c2e210) lets a player use the +// guard only with the level's property_required_mission finished. +#include "GameDependencies.h" +#include "dGameMessagesTests/GameMessageTestUtils.h" + +#include "CDClientDatabase.h" +#include "CDClientManager.h" +#include "CDMissionsTable.h" +#include "Entity.h" +#include "MissionComponent.h" +#include "PropertyMessages.h" +#include "PropertyVendorComponent.h" + +#include "tinyxml2.h" + +#include + +using namespace GameMessageTestUtils; + +namespace { + // Mission IDs only these tests use + constexpr uint32_t REQUIRED = 993001; + constexpr uint32_t REPEATED = 993002; +} + +class PropertyVendorComponentTests : public GameDependenciesTest { +protected: + void SetUp() override { + SetUpDependencies(); + CDClientDatabase::Connect(":memory:"); // MissionComponent counts the achievements + CDClientDatabase::ExecuteDML("CREATE TABLE Missions (id INTEGER, isMission INTEGER);"); + auto& missions = CDClientManager::GetEntriesMutable(); + for (const auto id : { REQUIRED, REPEATED }) { + CDMissions row{}; + row.id = id; + row.isMission = true; + row.repeatable = id == REPEATED; + missions.push_back(row); + } + guard = std::make_unique(GUARD, info); + vendor = guard->AddComponent(-1); + player = std::make_unique(PLAYER, info); + missions_ = player->AddComponent(-1); + } + + void TearDown() override { + player.reset(); + guard.reset(); + CDClientManager::GetEntriesMutable().clear(); + TearDownDependencies(); + } + + void Load(const std::string& done, const std::string& cur) { + tinyxml2::XMLDocument doc; + const auto xml = R"()" + done + "" + cur + ""; + ASSERT_EQ(doc.Parse(xml.c_str()), tinyxml2::XML_SUCCESS); + missions_->LoadFromSaveData(doc); + } + + static constexpr LWOOBJID GUARD = 0x0000400000112233LL; + static constexpr LWOOBJID PLAYER = 0x1000000000000001LL; + std::unique_ptr guard; + std::unique_ptr player; + PropertyVendorComponent* vendor = nullptr; + MissionComponent* missions_ = nullptr; +}; + +TEST_F(PropertyVendorComponentTests, AGuardWithoutAMissionAsksForNone) { + EXPECT_EQ(vendor->GetRequiredMission(), 0u); + EXPECT_TRUE(vendor->MayRent(*player)); +} + +TEST_F(PropertyVendorComponentTests, TheMissionMustBeFinished) { + guard->SetVar(u"property_required_mission", REQUIRED); + EXPECT_EQ(vendor->GetRequiredMission(), REQUIRED); + EXPECT_FALSE(vendor->MayRent(*player)); // never taken + + Load("", R"()"); + EXPECT_FALSE(vendor->MayRent(*player)); // in progress +} + +TEST_F(PropertyVendorComponentTests, AFinishedMissionRents) { + guard->SetVar(u"property_required_mission", REQUIRED); + Load(R"()", ""); + EXPECT_TRUE(vendor->MayRent(*player)); +} + +// The client's list of finished missions keeps a mission that is being repeated +TEST_F(PropertyVendorComponentTests, AFinishedMissionThatIsRepeatedRents) { + guard->SetVar(u"property_required_mission", REPEATED); + Load(R"()", R"()"); + EXPECT_TRUE(vendor->MayRent(*player)); +} + +// A rent request without the mission is answered with code 9, which the client shows as "you failed to rent" and +// UGG_PROPRENT_Dont_have_achievement (LWOPropertyVendorComponent::onPropertyRentalResponse 0x00c56d70): +// clone u32 0, code u32 9, property u64 0, rent due i64 0 +TEST_F(PropertyVendorComponentTests, RentingWithoutTheMissionIsRefused) { + guard->SetVar(u"property_required_mission", REQUIRED); + const auto packets = Capture([&] { vendor->OnBuyFromVendor(player.get(), true, 0, 1); }); + ASSERT_EQ(packets.size(), 1u); + EXPECT_PACKET_EQ(FromHex( + "53 05 00 0c 00 00 00 00 33 22 11 00 00 40 00 00 ee 02 " + "00 00 00 00 09 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", 336), FromCapture(packets[0])); +} + +// With the mission, the request goes on to the property (none in this test: nothing is sent, nothing refused) +TEST_F(PropertyVendorComponentTests, RentingWithTheMissionIsNotRefused) { + guard->SetVar(u"property_required_mission", REQUIRED); + Load(R"()", ""); + const auto packets = Capture([&] { vendor->OnBuyFromVendor(player.get(), true, 0, 1); }); + EXPECT_TRUE(packets.empty()); +} diff --git a/tests/dGameTests/dComponentsTests/ProximityMonitorComponentTests.cpp b/tests/dGameTests/dComponentsTests/ProximityMonitorComponentTests.cpp new file mode 100644 index 000000000..919d140cd --- /dev/null +++ b/tests/dGameTests/dComponentsTests/ProximityMonitorComponentTests.cpp @@ -0,0 +1,59 @@ +#include "GameDependencies.h" + +#include "CDClientDatabase.h" +#include "CDClientManager.h" +#include "CDProximityMonitorComponentTable.h" +#include "Entity.h" +#include "GameMessages.h" +#include "ProximityMonitorComponent.h" +#include "dpEntity.h" + +#include + +// A ProximityMonitorComponent row lists ProximityTypes ids, as LWOProximityMonitorComponent::LoadDataFromTemplate +// (0x00c2dfb0) reads it; the types say their name, radius and where they are loaded. +class ProximityMonitorComponentTests : public GameDependenciesTest { +protected: + void SetUp() override { + SetUpDependencies(); + CDClientDatabase::Connect(":memory:"); + CDClientDatabase::ExecuteDML("CREATE TABLE ProximityTypes (id INTEGER, Name TEXT, Radius INTEGER, CollisionGroup INTEGER, PassiveChecks INTEGER, IconID INTEGER, LoadOnClient INTEGER, LoadOnServer INTEGER);"); + CDClientDatabase::ExecuteDML("INSERT INTO ProximityTypes VALUES (2, 'Test Proximity', 10, 1, 1, 1, 1, 0);"); + CDClientDatabase::ExecuteDML("INSERT INTO ProximityTypes VALUES (3, 'Test Prox Large', 20, 1, 1, 3, 1, 1);"); + CDClientDatabase::ExecuteDML("INSERT INTO ProximityTypes VALUES (7, 'RocketSign', 30, 1, 1, -1, 1, 0);"); + CDClientDatabase::ExecuteDML("INSERT INTO ProximityTypes VALUES (8, 'WorldLauncher', 80, 1, 1, 74, 1, 0);"); + CDClientDatabase::ExecuteDML("INSERT INTO ProximityTypes VALUES (11, 'NoRadius', 0, 1, 1, 0, 1, 1);"); + auto& rows = CDClientManager::GetEntriesMutable(); + rows.push_back({ 3, "2,3", true, true }); + rows.push_back({ 6, "7,8", true, false }); + rows.push_back({ 50, "3,11,99", true, true }); + } + + void TearDown() override { + TearDownDependencies(); + } +}; + +// A rocket launch pad's "7,8" are the client's sign and launch proximities, not radii of 7 and 8: nothing for the server +TEST_F(ProximityMonitorComponentTests, ClientOnlyProximitiesAreNotMadeOnTheServer) { + Entity launchpad(1, info); + auto* const proximity = launchpad.AddComponent(6); + proximity->LoadDataFromTemplate(); + EXPECT_TRUE(proximity->GetProximitiesData().empty()); +} + +TEST_F(ProximityMonitorComponentTests, ServerProximitiesTakeTheTypesNameAndRadius) { + Entity object(2, info); + auto* const proximity = object.AddComponent(3); + proximity->LoadDataFromTemplate(); + const auto& made = proximity->GetProximitiesData(); + ASSERT_EQ(made.size(), 1u); + ASSERT_TRUE(made.contains("Test Prox Large")); + + // A radius of 0 is 30, and a type that does not exist is skipped + Entity other(3, info); + auto* const otherProximity = other.AddComponent(50); + otherProximity->LoadDataFromTemplate(); + EXPECT_EQ(otherProximity->GetProximitiesData().size(), 2u); + EXPECT_TRUE(otherProximity->GetProximitiesData().contains("NoRadius")); +} diff --git a/tests/dGameTests/dComponentsTests/RailActivatorComponentTests.cpp b/tests/dGameTests/dComponentsTests/RailActivatorComponentTests.cpp index a1138f3f2..a81c3b47a 100644 --- a/tests/dGameTests/dComponentsTests/RailActivatorComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/RailActivatorComponentTests.cpp @@ -5,6 +5,7 @@ #include "CDRailActivatorComponent.h" #include "Entity.h" #include "MovementMessages.h" +#include "ObjectMessages.h" #include "dGameMessagesTests/GameMessageTestUtils.h" #include "RailActivatorComponent.h" @@ -82,3 +83,24 @@ TEST_F(RailActivatorComponentTests, InactiveRailIsReportedInactive) { notify.bActive = false; EXPECT_FALSE(RoundTrip(notify).bActive); } + +// A rail that is off is not ridden: LWORailActivatorComponent::msgCheckUseRequirements (0x00c2c5b0) refuses the use, so a +// client never asks for it +TEST_F(RailActivatorComponentTests, ARailThatIsOffIsNotUsed) { + entity->SetVar(u"rail_activator_active", false); + auto* const rail = entity->AddComponent(COMPONENT_ID); + Entity user(77, info); + GameMessages::RequestUse use; + GameMessages::RequestUseEvent event(use, user); + EXPECT_TRUE(rail->OnRequestUse(event)); + EXPECT_TRUE(rail->GetEntitiesOnRail().empty()); +} + +TEST_F(RailActivatorComponentTests, ARailThatIsOnIsUsed) { + auto* const rail = entity->AddComponent(COMPONENT_ID); + Entity user(78, info); + GameMessages::RequestUse use; + GameMessages::RequestUseEvent event(use, user); + EXPECT_TRUE(rail->OnRequestUse(event)); + EXPECT_EQ(rail->GetEntitiesOnRail(), std::vector{ 78 }); +} diff --git a/tests/dGameTests/dComponentsTests/ReplicaComponentOrderTests.cpp b/tests/dGameTests/dComponentsTests/ReplicaComponentOrderTests.cpp index caa34c288..5b62663e5 100644 --- a/tests/dGameTests/dComponentsTests/ReplicaComponentOrderTests.cpp +++ b/tests/dGameTests/dComponentsTests/ReplicaComponentOrderTests.cpp @@ -18,6 +18,9 @@ #include "BouncerComponent.h" #include "BuffComponent.h" #include "CharacterComponent.h" +#include "ChestComponent.h" +#include "ChoiceBuildComponent.h" +#include "RollerComponent.h" #include "CollectibleComponent.h" #include "ControllablePhysicsComponent.h" #include "DestroyableComponent.h" @@ -561,3 +564,102 @@ TEST_F(ReplicaComponentOrderTest, EveryListedComponent) { entity.AddComponent(-1); }); } + +namespace { + // The bits of `expected` are the first bits of `actual` + void ExpectStartsWith(RakNet::BitStream& actual, RakNet::BitStream& expected) { + ASSERT_GE(actual.GetNumberOfBitsUsed(), expected.GetNumberOfBitsUsed()); + actual.ResetReadPointer(); + expected.ResetReadPointer(); + for (uint32_t i = 0; i < expected.GetNumberOfBitsUsed(); i++) { + ASSERT_EQ(actual.ReadBit(), expected.ReadBit()) << "bit " << i; + } + } +} + +// LWOGameObject::Deserialize (0x00f99690) reads the components in the order ObjectLoader2::FillComponentOrder +// (0x0101f8e0) lists them: a chest (22) after its phantom physics (40) and before its render component (2). +// LOT 2196: phantom physics, chest, render. +TEST_F(ReplicaComponentOrderTest, ChestIsWrittenBeforeRender) { + Entity entity(15, info); + auto* const physics = entity.AddComponent(-1); + auto* const chest = entity.AddComponent(0); + chest->SetPlayerID(0x1000000000000001LL); + chest->SetLootOfferCount(3); + auto* const render = entity.AddComponent(-1); + + RakNet::BitStream actual; + entity.WriteComponents(actual, eReplicaPacketType::CONSTRUCTION); + + Entity copy(15, info); + RakNet::BitStream expected; + copy.AddComponent(-1)->Serialize(expected, true); + expected.Write(0x1000000000000001LL); + expected.Write(3); + copy.AddComponent(-1)->Serialize(expected, true); + ExpectStartsWith(actual, expected); + static_cast(physics); + static_cast(render); +} + +// A choice build (52) is read after physics, destroyable and script and before render. LOT 6414: simple physics, +// destroyable, choice build, render; LOT 5668 has a script in place of the destroyable. +TEST_F(ReplicaComponentOrderTest, ChoiceBuildIsWrittenAfterScriptAndBeforeRender) { + const auto build = [](Entity& entity) { + entity.AddComponent(-1); + entity.AddComponent(-1); + entity.AddComponent(-1)->SetMaxHealth(1.0f); + entity.AddComponent(-1, "", true); + entity.AddComponent(1); + entity.AddComponent(-1); + }; + Entity entity(15, info); + build(entity); + RakNet::BitStream actual; + entity.WriteComponents(actual, eReplicaPacketType::CONSTRUCTION); + + Entity copy(15, info); + build(copy); + RakNet::BitStream expected; + copy.GetComponent()->Serialize(expected, true); + copy.GetComponent()->Serialize(expected, true); + copy.GetComponent()->Serialize(expected, true); + copy.GetComponent()->Serialize(expected, true); + expected.Write1(); + expected.Write(0); // waiting + expected.Write(0); // nothing built + expected.Write(0); // nobody using it + copy.GetComponent()->Serialize(expected, true); + ExpectStartsWith(actual, expected); +} + +// A roller (105) is read after script, skill and inventory and before the moving platform (25) and render. +// LOT 2714: simple physics, roller, moving platform, render; LOT 13951 adds script, skill and inventory. +TEST_F(ReplicaComponentOrderTest, RollerIsWrittenBeforeTheMovingPlatform) { + const auto build = [](Entity& entity) { + entity.AddComponent(-1); + entity.AddComponent(-1, "", true); + entity.AddComponent(-1); + entity.AddComponent(13951); + entity.AddComponent(-1, ""); + entity.AddComponent(-1); + }; + for (const auto packetType : { eReplicaPacketType::CONSTRUCTION, eReplicaPacketType::SERIALIZATION }) { + const bool construction = packetType == eReplicaPacketType::CONSTRUCTION; + Entity entity(15, info); + build(entity); + RakNet::BitStream actual; + entity.WriteComponents(actual, packetType); + + Entity copy(15, info); + build(copy); + RakNet::BitStream expected; + copy.GetComponent()->Serialize(expected, construction); + copy.GetComponent()->Serialize(expected, construction); + copy.GetComponent()->Serialize(expected, construction); + copy.GetComponent()->Serialize(expected, construction); + copy.GetComponent()->Serialize(expected, construction); + copy.GetComponent()->Serialize(expected, construction); + ExpectStartsWith(actual, expected); + } +} diff --git a/tests/dGameTests/dComponentsTests/ReplicaConstructionTests.cpp b/tests/dGameTests/dComponentsTests/ReplicaConstructionTests.cpp index 798089e8c..8d082274f 100644 --- a/tests/dGameTests/dComponentsTests/ReplicaConstructionTests.cpp +++ b/tests/dGameTests/dComponentsTests/ReplicaConstructionTests.cpp @@ -18,11 +18,17 @@ #include "Entity.h" #include "InventoryComponent.h" #include "ItemComponent.h" +#include "LevelProgressionComponent.h" +#include "LUPExhibitComponent.h" +#include "PlayerForcedMovementComponent.h" +#include "ScriptedActivityComponent.h" #include "Item.h" #include "ModelComponent.h" #include "MovingPlatformComponent.h" +#include "PhantomPhysicsComponent.h" #include "SimplePhysicsComponent.h" #include "User.h" +#include "eGameActivity.h" #include "eReplicaComponentType.h" #include "eReplicaPacketType.h" @@ -130,6 +136,270 @@ TEST_F(ReplicaConstructionTest, CharacterConstructionAlwaysWritesGmActivityAndSo player.SetCharacter(nullptr); } +// A current-activity or PVP change is written once, as a guild change is: LWOCharacterComponent::Deserialize reads each +// block behind its own flag bit. +TEST_F(ReplicaConstructionTest, CharacterActivityAndPvpChangesAreWrittenOnce) { + User user(UNASSIGNED_SYSTEM_ADDRESS, "tester", "key"); + Character character(1, &user); + info.lot = 1; + Entity player(1152921506064087005, info); + player.SetCharacter(&character); + character.SetEntity(&player); + auto* const component = player.AddComponent(-1, &character, UNASSIGNED_SYSTEM_ADDRESS); + + component->SetCurrentActivity(eGameActivity::QUICKBUILDING); + component->SetPvpEnabled(true); + RakNet::BitStream serialization; + component->Serialize(serialization, false); + RakNet::BitStream expected; + expected.Write1(); // gm_pvp_info + expected.Write1(); // pvp_enabled + expected.Write0(); // is_gm + expected.Write(0); // gm_level + expected.Write0(); // editor_enabled + expected.Write(0); // editor_level + expected.Write1(); // current_activity + expected.Write(eGameActivity::QUICKBUILDING); + expected.Write0(); // social_info + ExpectSameBits(serialization, expected); + + RakNet::BitStream again; + component->Serialize(again, false); + EXPECT_EQ(again.GetNumberOfBitsUsed(), 3u); + + // A construction in between (another player coming into range) doesn't swallow a pending change + component->SetCurrentActivity(eGameActivity::NONE); + RakNet::BitStream construction; + component->Serialize(construction, true); + RakNet::BitStream after; + component->Serialize(after, false); + EXPECT_EQ(after.GetNumberOfBitsUsed(), 3u + 32u); + + player.SetCharacter(nullptr); +} + +// A player in jetpack mode is constructed in it: live player constructions carried the jetpack block (effect 167, +// flying 0, bypass checks 1) and a 0 after the pickup radius. LWOControllablePhysComponent::Deserialize reads both. +TEST_F(ReplicaConstructionTest, ControllablePhysicsConstructionCarriesJetPackMode) { + Entity player(1152921506064087006, info); + auto* const physics = player.AddComponent(-1); + + const auto construct = [physics]() { + RakNet::BitStream construction; + physics->Serialize(construction, true); + return Bits(construction); + }; + const auto bits = [](const RakNet::BitStream& stream) { return Bits(stream); }; + + // No jetpack: one 0 bit, then the stun immunities + const auto plain = construct(); + EXPECT_EQ(plain.substr(0, 2), "01"); + + physics->SetJetPackMode(true, 167, true); + RakNet::BitStream head; + head.Write1(); // jetpack + head.Write(167); // effect + head.Write0(); // flying + head.Write1(); // bypass checks + head.Write1(); // stun immunities + const auto jetpack = construct(); + EXPECT_EQ(jetpack.substr(0, head.GetNumberOfBitsUsed()), bits(head)); + // After the 7 immunity counts: no cheats, then the pickup radius and a 0 (not the jetpack flag) + const size_t afterImmunities = head.GetNumberOfBitsUsed() + 7 * 32; + EXPECT_EQ(jetpack.substr(afterImmunities, 2), "01"); + EXPECT_EQ(jetpack[afterImmunities + 2 + 32], '0'); + // The rest is what a player without a jetpack gets + EXPECT_EQ(jetpack.substr(head.GetNumberOfBitsUsed()), plain.substr(2)); + + physics->SetJetPackMode(false, -1, false); + EXPECT_EQ(construct(), plain); +} + +namespace { + struct VolumeEffect { + uint32_t type{}; + float amount{}; + bool hasDistance{}; + float min{}; + float max{}; + bool isDirectional{}; + NiPoint3 direction{}; + }; + + // A phantom volume looks its LOT up in the registry when it is made + void ConnectRegistry() { + if (CDClientDatabase::isConnected) return; + CDClientDatabase::Connect(":memory:"); + CDClientDatabase::ExecuteDML("CREATE TABLE ComponentsRegistry (id INTEGER, component_type INTEGER, component_id INTEGER);"); + } + + // The effect block of a phantom physics update made from a trigger's SetPhysicsVolumeEffect arguments + VolumeEffect ReadVolumeEffect(Entity& volume, const std::vector& args) { + auto* const phantom = volume.AddComponent(-1); + phantom->SetVolumeEffect(args); + RakNet::BitStream stream; + phantom->Serialize(stream, false); + + VolumeEffect effect; + bool flag{}; + stream.Read(flag); + if (flag) stream.IgnoreBits(7 * 32); // position and rotation + stream.Read(flag); + EXPECT_TRUE(flag); // the effect block + stream.Read(flag); + EXPECT_TRUE(flag); // active + stream.Read(effect.type); + stream.Read(effect.amount); + stream.Read(effect.hasDistance); + if (effect.hasDistance) { + stream.Read(effect.min); + stream.Read(effect.max); + } + stream.Read(effect.isDirectional); + if (effect.isDirectional) { + stream.Read(effect.direction.x); + stream.Read(effect.direction.y); + stream.Read(effect.direction.z); + } + EXPECT_EQ(stream.GetNumberOfUnreadBits(), 0u); + return effect; + } +} + +// Trigger volume effects as live sent them (phantom physics constructions in the live captures; the client reads +// them in LWOPhantomPhysicsComponent::Deserialize): the direction has the amount as its length, the distances go out +// for "true" only and as 1 and the max, and a zero direction is no direction. +TEST_F(ReplicaConstructionTest, PhantomPhysicsVolumeEffectsAsLive) { + ConnectRegistry(); + Entity pushWithDistance(1001, info); + auto effect = ReadVolumeEffect(pushWithDistance, { "Push", "50", "0.91", "-0.34", "-0.22", "true", "20", "50" }); + EXPECT_EQ(effect.type, 0u); + EXPECT_EQ(effect.amount, 50.0f); + EXPECT_TRUE(effect.hasDistance); + EXPECT_EQ(effect.min, 1.0f); + EXPECT_EQ(effect.max, 50.0f); + EXPECT_TRUE(effect.isDirectional); + EXPECT_NEAR(effect.direction.x, 45.68f, 0.01f); + EXPECT_NEAR(effect.direction.y, -17.07f, 0.01f); + EXPECT_NEAR(effect.direction.z, -11.04f, 0.01f); + + Entity pushFar(1002, info); + effect = ReadVolumeEffect(pushFar, { "Push", "200", "1", "0", "0", "true", "150", "175" }); + EXPECT_TRUE(effect.hasDistance); + EXPECT_EQ(effect.min, 1.0f); + EXPECT_EQ(effect.max, 175.0f); + EXPECT_EQ(effect.direction, NiPoint3(200.0f, 0.0f, 0.0f)); + + // "1" is not "true": no distances + Entity updraft(1003, info); + effect = ReadVolumeEffect(updraft, { "Push", "40.0", "0", "1", "0", "1", "20", "50" }); + EXPECT_EQ(effect.amount, 40.0f); + EXPECT_FALSE(effect.hasDistance); + EXPECT_TRUE(effect.isDirectional); + EXPECT_EQ(effect.direction, NiPoint3(0.0f, 40.0f, 0.0f)); + + Entity repulse(1004, info); + effect = ReadVolumeEffect(repulse, { "Repulse", "150", "0", "0", "0", "true", "25", "100" }); + EXPECT_EQ(effect.type, 2u); + EXPECT_EQ(effect.amount, 150.0f); + EXPECT_TRUE(effect.hasDistance); + EXPECT_EQ(effect.min, 1.0f); + EXPECT_EQ(effect.max, 100.0f); + EXPECT_FALSE(effect.isDirectional); + + Entity slanted(1005, info); + effect = ReadVolumeEffect(slanted, { "Push", " 35", " .79", " 0", " .61" }); + EXPECT_FALSE(effect.hasDistance); + EXPECT_NEAR(effect.direction.x, 27.70f, 0.01f); + EXPECT_NEAR(effect.direction.z, 21.39f, 0.01f); + + Entity friction(1006, info); + effect = ReadVolumeEffect(friction, { "Friction", "0" }); + EXPECT_EQ(effect.type, 4u); + EXPECT_FALSE(effect.hasDistance); + EXPECT_FALSE(effect.isDirectional); + + // The amount is a float all the way: LWOPhantomPhysicsComponent::Deserialize (0x00c34db0) reads 32 bits into a + // float, and trigger commands are run by the server only, so a fraction is kept as the zone file has it + Entity lowFriction(1007, info); + effect = ReadVolumeEffect(lowFriction, { "Friction", "0.1" }); + EXPECT_EQ(effect.type, 4u); + EXPECT_EQ(effect.amount, 0.1f); +} + +// A construction (the volume coming into one player's range) doesn't use up an effect change the players already +// watching it still have to get. +TEST_F(ReplicaConstructionTest, PhantomPhysicsConstructionKeepsThePendingEffect) { + ConnectRegistry(); + Entity volume(1007, info); + auto* const phantom = volume.AddComponent(-1); + RakNet::BitStream first; + phantom->Serialize(first, false); + const auto idle = first.GetNumberOfBitsUsed(); + + phantom->SetVolumeEffect({ "Friction", "0" }); + RakNet::BitStream construction; + phantom->Serialize(construction, true); + RakNet::BitStream update; + phantom->Serialize(update, false); + EXPECT_EQ(update.GetNumberOfBitsUsed(), 2u + 1 + 32 + 32 + 1 + 1); + RakNet::BitStream again; + phantom->Serialize(again, false); + EXPECT_EQ(again.GetNumberOfBitsUsed(), 2u); + EXPECT_LE(again.GetNumberOfBitsUsed(), idle); +} + +// A construction goes to the one client the object came into range of. It must not use up a change the clients +// already watching are still waiting for (the level, rail and billboard flags are each read behind a flag bit). +TEST_F(ReplicaConstructionTest, AConstructionKeepsPendingLevelAndForcedMovementChanges) { + Entity player(1152921506064087008, info); + auto* const level = player.AddComponent(-1); + auto* const forcedMovement = player.AddComponent(-1); + + level->SetLevel(7); + forcedMovement->SetPlayerOnRail(true); + RakNet::BitStream construction; + level->Serialize(construction, true); + forcedMovement->Serialize(construction, true); + + RakNet::BitStream update; + level->Serialize(update, false); + forcedMovement->Serialize(update, false); + RakNet::BitStream expected; + expected.Write1(); + expected.Write(7); + expected.Write1(); + expected.Write1(); // on rail + expected.Write0(); // show billboard + ExpectSameBits(update, expected); + + RakNet::BitStream again; + level->Serialize(again, false); + forcedMovement->Serialize(again, false); + EXPECT_EQ(again.GetNumberOfBitsUsed(), 2u); +} + +// The client learns the exhibit's LOT only from the component's block (LWOLUPExhibitComponent::Deserialize: a flag +// and the LOT). DLU wrote it on a construction only while it was dirty, so a player who came into range after the +// first update saw no exhibit until the next one was picked. +TEST_F(ReplicaConstructionTest, LupExhibitConstructionAlwaysCarriesTheExhibit) { + Entity exhibit(1009, info); + auto* const component = exhibit.AddComponent(-1); + + RakNet::BitStream update; + component->Serialize(update, false); + RakNet::BitStream idle; + component->Serialize(idle, false); + EXPECT_EQ(idle.GetNumberOfBitsUsed(), 1u); + + RakNet::BitStream construction; + component->Serialize(construction, true); + RakNet::BitStream expected; + expected.Write1(); + expected.Write(11121); + ExpectSameBits(construction, expected); +} + // A guild change (docs/Guilds.md) is written once: the client reads guild id, a u8 length and 16-bit characters, and // redraws the name billboard every time it reads a name. TEST_F(ReplicaConstructionTest, CharacterGuildChangeIsWrittenOnce) { @@ -170,6 +440,81 @@ TEST_F(ReplicaConstructionTest, CharacterGuildChangeIsWrittenOnce) { player.SetCharacter(nullptr); } +// A client that comes into range of an activity is told its players, whether or not they changed since the last +// update. Live finish line constructions (LOT 4967): flag 1 and the count in 40 of 40, one of them with a player. +TEST_F(ReplicaConstructionTest, AnActivityConstructionAlwaysCarriesItsPlayers) { + ConnectRegistry(); + Entity activity(1010, info); + auto* const component = activity.AddComponent(-1); + const LWOOBJID player = 1152921506064087006; + component->SetActivityValue(player, 1, 42.0f); + + RakNet::BitStream update; + component->Serialize(update, false); + RakNet::BitStream idle; + component->Serialize(idle, false); + EXPECT_EQ(Bits(idle), "0"); // nothing changed since + + RakNet::BitStream construction; + component->Serialize(construction, true); + EXPECT_EQ(Bits(construction), Bits(update)); + EXPECT_TRUE(construction.ReadBit()); + uint32_t count{}; + ASSERT_TRUE(construction.Read(count)); + EXPECT_EQ(count, 1u); + LWOOBJID id{}; + ASSERT_TRUE(construction.Read(id)); + EXPECT_EQ(id, player); + for (uint32_t i = 0; i < 10; i++) { + float value{}; + ASSERT_TRUE(construction.Read(value)); + EXPECT_EQ(value, i == 1 ? 42.0f : 0.0f); + } + EXPECT_EQ(construction.GetNumberOfUnreadBits(), 0u); + + // Without players: the flag and a count of 0 + component->RemoveActivityPlayerData(player); + RakNet::BitStream cleared; + component->Serialize(cleared, false); + RakNet::BitStream empty; + component->Serialize(empty, true); + EXPECT_EQ(Bits(empty), "1" + std::string(32, '0')); +} + +// Run speed modifiers stack as in LWOControllablePhysComponent::msgAddRunspeedModifier (0x00be0af0) and +// msgRemoveRunSpeedModifier (0x00be0720): the lowest slow wins, otherwise the highest boost; 500 and anything over 1000 +// count for nothing +TEST_F(ReplicaConstructionTest, RunSpeedModifiersStackAsTheClientDoes) { + Entity entity(15, info); + auto* const physics = entity.AddComponent(-1); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 1.0f); + + physics->AddSpeedboost(750.0f); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 1.5f); + physics->AddSpeedboost(550.0f); // a smaller boost applied later does not replace the bigger one + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 1.5f); + physics->AddSpeedboost(250.0f); // any slow beats every boost + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 0.5f); + physics->AddSpeedboost(133.0f); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 133.0f / 500.0f); + physics->AddSpeedboost(350.0f); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 133.0f / 500.0f); + physics->AddSpeedboost(1500.0f); + physics->AddSpeedboost(500.0f); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 133.0f / 500.0f); + + physics->RemoveSpeedboost(133.0f); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 0.5f); + physics->RemoveSpeedboost(250.0f); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 0.7f); + physics->RemoveSpeedboost(350.0f); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 1.5f); + physics->RemoveSpeedboost(750.0f); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 1.1f); + physics->RemoveSpeedboost(550.0f); + EXPECT_FLOAT_EQ(physics->GetSpeedMultiplier(), 1.0f); // 1500 and 500 are left and count for nothing +} + // Live wrote the cheat block (gravity scale, speed multiplier) on construction only when one of them was changed: 216 // of 20,617 controllable-physics constructions had it (players at run speed 1.05, enemies with gravity 0), never 1/1. TEST_F(ReplicaConstructionTest, ControllablePhysicsConstructionWritesCheatsOnlyWhenChanged) { @@ -438,6 +783,11 @@ TEST_F(InventoryConstructionTest, NpcItemsLikeLive) { coleExpected.Write(0); ExpectSameBits(coleConstruction, coleExpected); + // The equipment put on before the construction still goes to the clients already watching, once + RakNet::BitStream pending; + coleInventory->Serialize(pending, false); + EXPECT_GT(pending.GetNumberOfBitsUsed(), 2u); + // A serialization with nothing changed writes neither list RakNet::BitStream serialization; coleInventory->Serialize(serialization, false); diff --git a/tests/dGameTests/dComponentsTests/RocketLaunchTests.cpp b/tests/dGameTests/dComponentsTests/RocketLaunchTests.cpp index 45f0ff75b..a0aa844d9 100644 --- a/tests/dGameTests/dComponentsTests/RocketLaunchTests.cpp +++ b/tests/dGameTests/dComponentsTests/RocketLaunchTests.cpp @@ -1,6 +1,8 @@ #include "GameDependencies.h" #include "dGameMessagesTests/GameMessageTestUtils.h" +#include "CDClientDatabase.h" +#include "Entity.h" #include "ObjectMessages.h" #include "RocketLaunchpadControlComponent.h" @@ -49,3 +51,107 @@ TEST_F(RocketLaunchTests, RocketEquippedIsBroadcast) { ASSERT_EQ(sent.size(), 1u); EXPECT_TRUE(sent[0].broadcast); } + +// A pad's row can ask for a GM level (the AG test pad: 9); LWORocketLaunchComponentCommon::msgFireEventClientSide +// (0x00cb78b0) does not launch a player under it +TEST_F(RocketLaunchTests, APadWithAGmLevelLaunchesOnlyThoseAtIt) { + CDClientDatabase::Connect(":memory:"); + CDClientDatabase::ExecuteDML("CREATE TABLE RocketLaunchpadControlComponent (id INTEGER, targetZone INTEGER, defaultZoneID INTEGER, targetScene TEXT, gmLevel INTEGER, useLaunchPrecondition INTEGER, launchPrecondition TEXT, useAltLandingPrecondition INTEGER, altLandingPrecondition TEXT, altLandingSpawnPointName TEXT);"); + CDClientDatabase::ExecuteDML("INSERT INTO RocketLaunchpadControlComponent VALUES (1, 1100, 0, 'AGLaunch', 9, 0, '', 0, '', '');"); + CDClientDatabase::ExecuteDML("INSERT INTO RocketLaunchpadControlComponent VALUES (2, 1200, 0, 'NS_NT', 0, 0, '47', 0, '', '');"); + + Entity gmPad(PAD, info); + auto* const gmOnly = gmPad.AddComponent(1); + gmOnly->LoadDataFromTemplate(); + Entity openPad(PAD + 1, info); + auto* const open = openPad.AddComponent(2); + open->LoadDataFromTemplate(); + + Entity player(PLAYER, info); + EXPECT_FALSE(gmOnly->MayLaunch(player)); + EXPECT_TRUE(open->MayLaunch(player)); // its precondition is not in use + player.SetGMLevel(eGameMasterLevel::OPERATOR); + EXPECT_TRUE(gmOnly->MayLaunch(player)); +} + +namespace { + void MakePadTables() { + CDClientDatabase::Connect(":memory:"); + CDClientDatabase::ExecuteDML("CREATE TABLE RocketLaunchpadControlComponent (id INTEGER, targetZone INTEGER, defaultZoneID INTEGER, targetScene TEXT, gmLevel INTEGER, useLaunchPrecondition INTEGER, launchPrecondition TEXT, useAltLandingPrecondition INTEGER, altLandingPrecondition TEXT, altLandingSpawnPointName TEXT);"); + // Row 3 is the Venture Explorer pad's (LOT 14214): no precondition in the table + // No precondition is known: one that is asked for fails for a player without components + CDClientDatabase::ExecuteDML("CREATE TABLE Preconditions (id INTEGER, type INTEGER, targetLOT TEXT, targetGroup TEXT, targetCount INTEGER, iconID INTEGER, localize INTEGER, validContexts INTEGER);"); + CDClientDatabase::ExecuteDML("INSERT INTO RocketLaunchpadControlComponent VALUES (3, 1100, 0, 'AGLanding', 0, 0, NULL, 0, NULL, NULL);"); + // Row 16: a Nimbus Station pad with the precondition in the table + CDClientDatabase::ExecuteDML("INSERT INTO RocketLaunchpadControlComponent VALUES (16, 1300, 0, 'GFLanding', 0, 1, '0', 0, '', '');"); + } +} + +// A pad whose level sets rocketLaunchUseDBDefaults to false is ruled by the level's keys, not its row: +// LWORocketLaunchComponentCommon::LoadConfigData (0x00c55150) reads them and the row is only loaded while the key is +// true (0x00c12ea0). The Venture Explorer's pads: the row has no precondition, the level has +// "237;8;127|128;6|55;107;282" with rocketUseLaunchPrecondition. +TEST_F(RocketLaunchTests, APadThatDoesNotUseTheTableIsRuledByItsLevel) { + MakePadTables(); + Entity pad(PAD, info); + pad.SetVar(u"rocketLaunchUseDBDefaults", false); + pad.SetVar(u"targetZone", 1100); + pad.SetVar(u"targetScene", u"AGLanding"); + pad.SetVar(u"GMLevel", 0); + pad.SetVar(u"rocketUseLaunchPrecondition", true); + pad.SetVar(u"rocketLaunchPreCondition", u"0"); // an empty precondition table: nobody passes "0" + // AddComponent loads the row, then the level's keys + auto* const component = pad.AddComponent(3); + + Entity player(PLAYER, info); + // The row alone asks for nothing + Entity rowPad(PAD + 2, info); + EXPECT_TRUE(rowPad.AddComponent(3)->MayLaunch(player)); + EXPECT_EQ(component->GetTargetZone(), 1100); + EXPECT_EQ(component->GetTargetScene(), "AGLanding"); + EXPECT_FALSE(component->MayLaunch(player)); + + // The level's GM level counts as well (the test pads to the Gnarled Forest and Forbidden Valley properties: 9) + Entity gmPad(PAD + 1, info); + gmPad.SetVar(u"rocketLaunchUseDBDefaults", false); + gmPad.SetVar(u"targetZone", 1100); + gmPad.SetVar(u"GMLevel", 9); + auto* const gmOnly = gmPad.AddComponent(3); + EXPECT_FALSE(gmOnly->MayLaunch(player)); + player.SetGMLevel(eGameMasterLevel::OPERATOR); + EXPECT_TRUE(gmOnly->MayLaunch(player)); +} + +// The level's precondition is only used with the level's rocketUseLaunchPrecondition (Nimbus Station's pad to +// Forbidden Valley's property has "115" without it) +TEST_F(RocketLaunchTests, ALevelPreconditionThatIsNotInUseIsNotChecked) { + MakePadTables(); + Entity pad(PAD, info); + pad.SetVar(u"rocketLaunchUseDBDefaults", false); + pad.SetVar(u"targetZone", 1450); + pad.SetVar(u"rocketUseLaunchPrecondition", false); + pad.SetVar(u"rocketLaunchPreCondition", u"0"); + auto* const component = pad.AddComponent(3); + Entity player(PLAYER, info); + EXPECT_TRUE(component->MayLaunch(player)); + EXPECT_EQ(component->GetTargetZone(), 1450); +} + +// With rocketLaunchUseDBDefaults true (the client's default, and 12 pads in the maps say so) the row rules and the +// level's keys are not looked at +TEST_F(RocketLaunchTests, APadThatUsesTheTableIgnoresItsLevelKeys) { + MakePadTables(); + for (const bool withKey : { true, false }) { + Entity pad(PAD, info); + if (withKey) pad.SetVar(u"rocketLaunchUseDBDefaults", true); + pad.SetVar(u"targetZone", 1400); + pad.SetVar(u"targetScene", u"FVGate"); + pad.SetVar(u"GMLevel", 9); + pad.SetVar(u"rocketUseLaunchPrecondition", false); + auto* const component = pad.AddComponent(16); + EXPECT_EQ(component->GetTargetZone(), 1300); + EXPECT_EQ(component->GetTargetScene(), "GFLanding"); + Entity player(PLAYER, info); + EXPECT_FALSE(component->MayLaunch(player)); // the row's precondition, not the level's "none" + } +} diff --git a/tests/dGameTests/dComponentsTests/SimplePhysicsComponentTests.cpp b/tests/dGameTests/dComponentsTests/SimplePhysicsComponentTests.cpp index 32d0d26c8..88c9c3889 100644 --- a/tests/dGameTests/dComponentsTests/SimplePhysicsComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/SimplePhysicsComponentTests.cpp @@ -131,6 +131,35 @@ TEST_F(SimplePhysicsTest, SimplePhysicsConstructionTest) { ASSERT_EQ(rotation, NiQuaternion(1.0f, 2.0f, 3.0f, 4.0f)); } +// A construction (the object coming into one player's range) doesn't use up a velocity or motion state change the +// players already watching it still have to get. LWOSimplePhysicsComponent::Deserialize (0x00be4b00) reads each +// behind its own flag bit. +TEST_F(SimplePhysicsTest, AConstructionKeepsPendingChangesForTheNextUpdate) { + RakNet::BitStream construction; + simplePhysicsComponent->Serialize(construction, true); + + simplePhysicsComponent->Serialize(bitStream, false); + bool hasVelocity{}; + bitStream.Read(hasVelocity); + ASSERT_TRUE(hasVelocity); + NiPoint3 velocity; + NiPoint3 angularVelocity; + bitStream.Read(velocity); + bitStream.Read(angularVelocity); + EXPECT_EQ(velocity, NiPoint3(5.0f, 6.0f, 7.0f)); + bool hasMotionState{}; + bitStream.Read(hasMotionState); + ASSERT_TRUE(hasMotionState); + uint32_t motionState{}; + bitStream.Read(motionState); + EXPECT_EQ(motionState, 2u); + + // Written once + RakNet::BitStream again; + simplePhysicsComponent->Serialize(again, false); + EXPECT_EQ(again.GetNumberOfBitsUsed(), 3u); +} + TEST_F(SimplePhysicsTest, SimplePhysicsGettersAndSettersTest) { ASSERT_EQ(simplePhysicsComponent->GetClimabbleType(), eClimbableType::CLIMBABLE_TYPE_WALL); ASSERT_EQ(simplePhysicsComponent->GetPosition(), NiPoint3(1.0f, 2.0f, 3.0f)); diff --git a/tests/dGameTests/dNetTests/WorldPacketsTests.cpp b/tests/dGameTests/dNetTests/WorldPacketsTests.cpp index e613f0b5f..a4aa9d638 100644 --- a/tests/dGameTests/dNetTests/WorldPacketsTests.cpp +++ b/tests/dGameTests/dNetTests/WorldPacketsTests.cpp @@ -1,3 +1,5 @@ +#include "ZCompression.h" +#include "LDFFormat.h" #include "ChatPackets.h" #include "ClientPackets.h" #include "GameDependencies.h" @@ -310,6 +312,7 @@ TEST_F(WorldPacketsTests, CreateCharacterMatchesLegacy) { packet.reputation = reputation; packet.propertyCloneID = cloneID; packet.txfring = false; // the legacy sender never wrote it + packet.sendWorldKeys = false; // nor the world keys ExpectSameSend([&](const SystemAddress& a) { LegacyWorldPackets::SendCreateCharacter(a, reputation, objectID, xml, name, gm, cloneID); }, packet); const auto copy = RoundTrip(packet); @@ -340,6 +343,90 @@ TEST_F(WorldPacketsTests, CreateCharacterSendsTxfring) { EXPECT_FALSE(RoundTrip(packet).txfring); } +// Live sent legoclub=1, freetrial=0, requiresrename=0, levelid and position / rotation in 451 of 451 character data packets +TEST_F(WorldPacketsTests, CreateCharacterSendsTheWorldKeys) { + ClientPackets::CreateCharacter packet; + packet.xmlData = ""; + packet.requiresRename = true; + packet.levelID = 1200ULL | 7ULL << 16 | 99ULL << 32; + packet.position = NiPoint3(1.5f, -2.0f, 3.25f); + packet.rotation = NiQuaternion(0.5f, 0.1f, 0.2f, 0.3f); + const auto copy = RoundTrip(packet); + EXPECT_TRUE(copy.sendWorldKeys); + EXPECT_TRUE(copy.legoClub); + EXPECT_FALSE(copy.freeTrial); + EXPECT_TRUE(copy.requiresRename); + EXPECT_EQ(copy.levelID, packet.levelID); + EXPECT_EQ(copy.position, packet.position); + EXPECT_EQ(copy.rotation, packet.rotation); + + packet.sendWorldKeys = false; + const auto without = RoundTrip(packet); + EXPECT_FALSE(without.sendWorldKeys); + EXPECT_FALSE(without.legoClub); // the client's value without the key + EXPECT_FALSE(without.requiresRename); +} + +// Live sent reputation as LDF type 8 (a 64-bit number), not as an object ID (type 9), in every character data packet. +// The entries are sorted by key: reputation follows propertycloneid. +TEST_F(WorldPacketsTests, CreateCharacterSendsReputationAsLdfType8) { + const auto reputationType = [](const ClientPackets::CreateCharacter& packet) { + RakNet::BitStream bitStream; + packet.Serialize(bitStream); + // The LDF is compressed: size + 9, the compressed flag, the size, the compressed size, the data + uint32_t sizePlusHeader{}; + uint8_t compressed{}; + uint32_t uncompressedSize{}; + uint32_t compressedSize{}; + EXPECT_TRUE(bitStream.Read(sizePlusHeader)); + EXPECT_TRUE(bitStream.Read(compressed)); + EXPECT_TRUE(bitStream.Read(uncompressedSize)); + EXPECT_TRUE(bitStream.Read(compressedSize)); + std::vector compressedData(compressedSize); + EXPECT_TRUE(bitStream.ReadAlignedBytes(compressedData.data(), compressedSize)); + std::vector uncompressed(uncompressedSize); + int32_t error{}; + EXPECT_EQ(ZCompression::Decompress(compressedData.data(), compressedSize, uncompressed.data(), uncompressedSize, error), static_cast(uncompressedSize)); + RakNet::BitStream data(uncompressed.data(), uncompressed.size(), false); + uint32_t count{}; + EXPECT_TRUE(data.Read(count)); + for (uint32_t i = 0; i < count; i++) { + uint8_t keyBytes{}; + EXPECT_TRUE(data.Read(keyBytes)); + std::u16string key(keyBytes / 2, u'\0'); + for (auto& character : key) EXPECT_TRUE(data.Read(character)); + uint8_t type{}; + EXPECT_TRUE(data.Read(type)); + if (key == u"reputation") { + int64_t value{}; + EXPECT_TRUE(data.Read(value)); + EXPECT_EQ(value, 300); + return static_cast(type); + } + switch (type) { + case LDF_TYPE_S32: case LDF_TYPE_U32: case LDF_TYPE_FLOAT: data.IgnoreBytes(4); break; + case LDF_TYPE_BOOLEAN: data.IgnoreBytes(1); break; + case LDF_TYPE_U64: case LDF_TYPE_OBJID: data.IgnoreBytes(8); break; + case LDF_TYPE_UTF_16: { uint32_t length{}; EXPECT_TRUE(data.Read(length)); data.IgnoreBytes(length * 2); break; } + case LDF_TYPE_UTF_8: { uint32_t length{}; EXPECT_TRUE(data.Read(length)); data.IgnoreBytes(length); break; } + default: ADD_FAILURE() << "LDF type " << static_cast(type); return -1; + } + } + return -1; + }; + + ClientPackets::CreateCharacter packet; + packet.xmlData = ""; + packet.reputation = 300; + EXPECT_EQ(reputationType(packet), 8); + EXPECT_EQ(RoundTrip(packet).reputation, 300); + + // The packet from before the world keys keeps its type + packet.sendWorldKeys = false; + EXPECT_EQ(reputationType(packet), 9); + EXPECT_EQ(RoundTrip(packet).reputation, 300); +} + TEST_F(WorldPacketsTests, CharacterListMatchesLegacy) { FakeCharacter first; FakeCharacter second;