refactor(component): group the component files by the client's families

Physics/, Activity/ (activity, scripted activity, shooting gallery,
quickbuild, minigame control, racing control base, racing control, gate rush),
Vendor/, Character/ (what the client makes with a character, plus ghost,
minifig and mission), Sound/ and Property/; the rest stays where it was.
File moves only; DLU_COMPONENT_INCLUDE_DIRS gives every target the folders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aaron Kimbrell
2026-10-01 15:37:45 -05:00
parent 8f09121ad4
commit 9a464ac35f
76 changed files with 37 additions and 34 deletions

View File

@@ -0,0 +1,441 @@
#include "ActivityComponent.h"
#include "ChatServerLink.h"
#include "ChatPackets.h"
#include "GameMessages.h"
#include "ActivityMessages.h"
#include "CDClientManager.h"
#include "MissionComponent.h"
#include "Character.h"
#include "dZoneManager.h"
#include "Game.h"
#include "Logger.h"
#include "ClientPackets.h"
#include "EntityManager.h"
#include "ChatPackets.h"
#include "BitStreamUtils.h"
#include "dServer.h"
#include "GeneralUtils.h"
#include "dZoneManager.h"
#include "dConfig.h"
#include "InventoryComponent.h"
#include "DestroyableComponent.h"
#include "Loot.h"
#include "eMissionTaskType.h"
#include "eMatchUpdate.h"
#include "ServiceType.h"
#include "MessageType/Chat.h"
#include "CDActivityRewardsTable.h"
#include "CDActivitiesTable.h"
#include "LeaderboardManager.h"
#include "CharacterComponent.h"
#include "Amf3.h"
#include <ranges>
namespace {
const ActivityInstance g_EmptyInstance{ nullptr, CDActivities{} };
}
ActivityComponent::ActivityComponent(Entity* parent, int32_t componentID) : Component(parent, componentID) {
RegisterMsg(&ActivityComponent::OnGetObjectReportInfo);
}
/*
* This is precisely what the client does functionally
* Use the component id as the default activity id and load its data from the database
* if activityID is specified and if that column exists in the activities table, update the activity info with that data.
*/
void ActivityComponent::LoadDataFromTemplate() {
m_ActivityID = m_ComponentID;
LoadActivityData(m_ComponentID);
}
// The level config's activityID, when there, replaces it
void ActivityComponent::LoadConfigData() {
if (m_Parent->HasVar(u"activityID")) {
m_ActivityID = m_Parent->GetVar<int32_t>(u"activityID");
LoadActivityData(m_ActivityID);
}
}
void ActivityComponent::LoadActivityData(const int32_t activityId) {
CDActivitiesTable* activitiesTable = CDClientManager::GetTable<CDActivitiesTable>();
std::vector<CDActivities> activities = activitiesTable->Query([activityId](CDActivities entry) {return (entry.ActivityID == activityId); });
bool soloRacing = Game::config->GetValue("solo_racing") == "1";
for (CDActivities activity : activities) {
m_ActivityInfo = activity;
if (static_cast<Leaderboard::Type>(activity.leaderboardType) == Leaderboard::Type::Racing && soloRacing) {
m_ActivityInfo.minTeamSize = 1;
m_ActivityInfo.minTeams = 1;
}
if (m_ActivityInfo.instanceMapID == -1) {
const auto& transferOverride = m_Parent->GetVarAsString(u"transferZoneID");
if (!transferOverride.empty()) {
m_ActivityInfo.instanceMapID =
GeneralUtils::TryParse<uint32_t>(transferOverride).value_or(m_ActivityInfo.instanceMapID);
}
}
}
}
void ActivityComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) {
outBitStream.Write(m_DirtyActivityInfo);
if (m_DirtyActivityInfo) {
outBitStream.Write<uint32_t>(m_ActivityPlayers.size());
if (!m_ActivityPlayers.empty()) {
for (const auto& [playerID, values] : m_ActivityPlayers) {
outBitStream.Write<LWOOBJID>(playerID);
for (const auto& activityValue : values) {
outBitStream.Write<float_t>(activityValue);
}
}
}
if (!bIsInitialUpdate) m_DirtyActivityInfo = false;
}
}
void ActivityComponent::ReloadConfig() {
CDActivitiesTable* activitiesTable = CDClientManager::GetTable<CDActivitiesTable>();
std::vector<CDActivities> activities = activitiesTable->Query([this](CDActivities entry) {return (entry.ActivityID == m_ActivityID); });
for (auto activity : activities) {
auto mapID = m_ActivityInfo.instanceMapID;
if (static_cast<Leaderboard::Type>(activity.leaderboardType) == Leaderboard::Type::Racing && Game::config->GetValue("solo_racing") == "1") {
m_ActivityInfo.minTeamSize = 1;
m_ActivityInfo.minTeams = 1;
} else {
m_ActivityInfo.minTeamSize = activity.minTeamSize;
m_ActivityInfo.minTeams = activity.minTeams;
}
}
}
void ActivityComponent::HandleMessageBoxResponse(Entity* player, const std::string& id) {
if (id == "LobbyExit") {
PlayerLeave(player->GetObjectID());
} else if (id == "PlayButton") {
PlayerJoin(player);
}
}
void ActivityComponent::PlayerJoin(Entity* player, const std::string& playerChoices) {
// If we have a lobby, queue the player and allow others to join, otherwise spin up an instance on the spot
if (HasLobby()) {
PlayerJoinLobby(player, playerChoices);
} else if (!IsPlayedBy(player)) {
NewInstance().AddParticipant(player);
}
}
namespace {
void SendMatchRequest(const LWOOBJID playerID, const ChatPackets::eMatchRequestType type, const int32_t value) {
ChatPackets::MatchRequest request;
request.playerID = playerID;
request.type = type;
request.value = value;
ChatServerLink::Send(request);
}
}
void ActivityComponent::PlayerJoinLobby(Entity* player, const std::string& playerChoices) {
if (!m_Parent->HasComponent(eReplicaComponentType::QUICK_BUILD)) {
GameMessages::MatchResponse matchResponse;
matchResponse.target = player->GetObjectID();
matchResponse.response = 0;
matchResponse.SendToClient(player->GetSystemAddress()); // tell the client they joined a lobby
}
auto* character = player->GetCharacter();
if (character != nullptr)
character->SetLastNonInstanceZoneID(Game::zoneManager->GetZone()->GetWorldID());
// The lobbies are the chat server's, so players of every instance of this zone wait together (docs/Matchmaking.md).
// It gets what this world read from the activity, overrides (solo racing, transfer zone) included.
ChatPackets::MatchRequest request;
request.playerID = player->GetObjectID();
request.type = ChatPackets::eMatchRequestType::JOIN;
request.activityID = m_ActivityInfo.ActivityID;
request.playerName = character != nullptr ? character->GetName() : "";
request.playerChoices = playerChoices;
request.instanceMapID = m_ActivityInfo.instanceMapID;
request.minTeams = m_ActivityInfo.minTeams;
request.maxTeams = m_ActivityInfo.maxTeams;
request.minTeamSize = m_ActivityInfo.minTeamSize;
request.maxTeamSize = m_ActivityInfo.maxTeamSize;
request.waitTime = m_ActivityInfo.waitTime;
request.startDelay = m_ActivityInfo.startDelay;
ChatServerLink::Send(request);
}
void ActivityComponent::PlayerLeave(LWOOBJID playerID) {
// Not applicable for non-lobby instances
if (!HasLobby()) return;
SendMatchRequest(playerID, ChatPackets::eMatchRequestType::LEAVE, 0);
}
void ActivityComponent::StartMatch(const ChatPackets::MatchTransfer& transfer) {
auto& instance = NewInstance();
for (const auto playerID : transfer.players) {
auto* const entity = Game::entityManager->GetEntity(playerID);
if (entity == nullptr || !CheckCost(entity)) {
continue;
}
instance.AddParticipant(entity);
}
instance.TransferParticipants(transfer);
}
bool ActivityComponent::HasLobby() const {
// If the player is not in the world he has to be, create a lobby for the transfer
return m_ActivityInfo.instanceMapID != UINT_MAX && m_ActivityInfo.instanceMapID != Game::server->GetZoneID();
}
bool ActivityComponent::IsPlayedBy(Entity* player) const {
for (const auto& instance : m_Instances) {
for (const auto* instancePlayer : instance.GetParticipants()) {
if (instancePlayer != nullptr && instancePlayer->GetObjectID() == player->GetObjectID())
return true;
}
}
return false;
}
bool ActivityComponent::IsPlayedBy(LWOOBJID playerID) const {
for (const auto& instance : m_Instances) {
for (const auto* instancePlayer : instance.GetParticipants()) {
if (instancePlayer != nullptr && instancePlayer->GetObjectID() == playerID)
return true;
}
}
return false;
}
bool ActivityComponent::CheckCost(Entity* player) const {
if (m_ActivityInfo.optionalCostLOT <= 0 || m_ActivityInfo.optionalCostCount <= 0)
return true;
auto* inventoryComponent = player->GetComponent<InventoryComponent>();
if (inventoryComponent == nullptr)
return false;
if (inventoryComponent->GetLotCount(m_ActivityInfo.optionalCostLOT) < m_ActivityInfo.optionalCostCount)
return false;
return true;
}
bool ActivityComponent::TakeCost(Entity* player) const {
auto* inventoryComponent = player->GetComponent<InventoryComponent>();
return CheckCost(player) && inventoryComponent && inventoryComponent->RemoveItem(m_ActivityInfo.optionalCostLOT, m_ActivityInfo.optionalCostCount, eInventoryType::ALL);
}
void ActivityComponent::PlayerReady(Entity* player, bool bReady) {
SendMatchRequest(player->GetObjectID(), ChatPackets::eMatchRequestType::READY, bReady ? 1 : 0);
}
ActivityInstance& ActivityComponent::NewInstance() {
m_Instances.push_back(ActivityInstance(m_Parent, m_ActivityInfo));
return m_Instances.back();
}
const ActivityInstance& ActivityComponent::GetInstance(const LWOOBJID playerID) const {
for (const auto& instance : m_Instances) {
for (const auto* participant : instance.GetParticipants()) {
if (participant->GetObjectID() == playerID)
return instance;
}
}
return g_EmptyInstance;
}
bool ActivityComponent::PlayerHasActivityData(LWOOBJID playerID) const {
return m_ActivityPlayers.contains(playerID);
}
void ActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) {
m_ActivityPlayers.erase(playerID);
m_DirtyActivityInfo = true;
}
float_t ActivityComponent::GetActivityValue(LWOOBJID playerID, uint32_t index) const {
float value = -1.0f;
const auto& data = m_ActivityPlayers.find(playerID);
if (data != m_ActivityPlayers.cend()) {
value = data->second[std::min(index, static_cast<uint32_t>(9))];
}
LOG_DEBUG("Player %llu has score %f at index %i", playerID, value, index);
return value;
}
void ActivityComponent::SetActivityValue(LWOOBJID playerID, uint32_t index, float_t value) {
auto& data = m_ActivityPlayers[playerID];
data[std::min(index, static_cast<uint32_t>(9))] = value;
LOG_DEBUG("%llu index %i has score of %f", playerID, index, value);
m_DirtyActivityInfo = true;
Game::entityManager->SerializeEntity(m_Parent);
}
void ActivityComponent::PlayerRemove(LWOOBJID playerID) {
for (int i = 0; i < m_Instances.size(); i++) {
auto& instance = m_Instances[i];
auto participants = instance.GetParticipants();
for (const auto* participant : participants) {
if (participant != nullptr && participant->GetObjectID() == playerID) {
instance.RemoveParticipant(participant);
RemoveActivityPlayerData(playerID);
// If the instance is empty after the delete of the participant, delete the instance too
if (instance.GetParticipants().empty()) {
m_Instances.erase(m_Instances.begin() + i);
}
return;
}
}
}
}
void ActivityInstance::TransferParticipants(const ChatPackets::MatchTransfer& transfer) {
const auto zoneID = transfer.zoneID.GetMapID();
const auto zoneInstance = transfer.zoneID.GetInstanceID();
const auto zoneClone = transfer.zoneID.GetCloneID();
for (Entity* player : GetParticipants()) {
LOG("Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", player->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, transfer.mythranShift == true ? "true" : "false", transfer.serverIP.c_str(), transfer.serverPort);
if (player->GetCharacter()) {
auto* characterComponent = player->GetComponent<CharacterComponent>();
if (characterComponent) {
characterComponent->AddVisitedLevel(LWOZONEID(zoneID, LWOINSTANCEID_INVALID, zoneClone));
}
player->GetCharacter()->SetZoneID(zoneID);
player->GetCharacter()->SetZoneInstance(zoneInstance);
player->GetCharacter()->SetZoneClone(zoneClone);
}
ClientPackets::TransferToWorld transferToWorld;
transferToWorld.serverIP = LUString(transfer.serverIP);
transferToWorld.serverPort = transfer.serverPort;
transferToWorld.mythranShift = transfer.mythranShift;
transferToWorld.Send(player->GetSystemAddress());
}
m_NextZoneCloneID++;
}
void ActivityInstance::RewardParticipant(Entity* participant) {
auto* missionComponent = participant->GetComponent<MissionComponent>();
if (missionComponent) {
missionComponent->Progress(eMissionTaskType::ACTIVITY, m_ActivityInfo.ActivityID);
}
// First, get the activity data
auto* activityRewardsTable = CDClientManager::GetTable<CDActivityRewardsTable>();
std::vector<CDActivityRewards> activityRewards = activityRewardsTable->Query([this](CDActivityRewards entry) { return (entry.objectTemplate == m_ActivityInfo.ActivityID); });
if (!activityRewards.empty()) {
const auto [minCoins, maxCoins] = Loot::GetActivityCoinRange(activityRewards[0]);
Loot::DropLoot(participant, m_Parent->GetObjectID(), activityRewards[0].LootMatrixIndex, minCoins, maxCoins);
}
}
std::vector<Entity*> ActivityInstance::GetParticipants() const {
std::vector<Entity*> entities;
entities.reserve(m_Participants.size());
for (const auto& id : m_Participants) {
auto* entity = Game::entityManager->GetEntity(id);
if (entity != nullptr)
entities.push_back(entity);
}
return entities;
}
void ActivityInstance::AddParticipant(Entity* participant) {
const auto id = participant->GetObjectID();
if (std::count(m_Participants.begin(), m_Participants.end(), id))
return;
m_Participants.push_back(id);
}
void ActivityInstance::RemoveParticipant(const Entity* participant) {
const auto loadedParticipant = std::find(m_Participants.begin(), m_Participants.end(), participant->GetObjectID());
if (loadedParticipant != m_Participants.end()) {
m_Participants.erase(loadedParticipant);
}
}
uint32_t ActivityInstance::GetScore() const {
return score;
}
void ActivityInstance::SetScore(uint32_t score) {
this->score = score;
}
bool ActivityComponent::OnGetObjectReportInfo(GameMessages::GetObjectReportInfo& reportInfo) {
auto& activityInfo = reportInfo.info->PushDebug("Activity");
auto& instances = activityInfo.PushDebug("Instances: " + std::to_string(m_Instances.size()));
size_t i = 0;
for (const auto& activityInstance : m_Instances) {
auto& instance = instances.PushDebug("Instance " + std::to_string(i++));
instance.PushDebug<AMFIntValue>("Score") = activityInstance.GetScore();
instance.PushDebug<AMFIntValue>("Next Zone Clone ID") = activityInstance.GetNextZoneCloneID();
{
auto& activityInfo = instance.PushDebug("Activity Info");
const auto& instanceActInfo = activityInstance.GetActivityInfo();
activityInfo.PushDebug<AMFIntValue>("ActivityID") = instanceActInfo.ActivityID;
activityInfo.PushDebug<AMFIntValue>("locStatus") = instanceActInfo.locStatus;
activityInfo.PushDebug<AMFIntValue>("instanceMapID") = instanceActInfo.instanceMapID;
activityInfo.PushDebug<AMFIntValue>("minTeams") = instanceActInfo.minTeams;
activityInfo.PushDebug<AMFIntValue>("maxTeams") = instanceActInfo.maxTeams;
activityInfo.PushDebug<AMFIntValue>("minTeamSize") = instanceActInfo.minTeamSize;
activityInfo.PushDebug<AMFIntValue>("maxTeamSize") = instanceActInfo.maxTeamSize;
activityInfo.PushDebug<AMFIntValue>("waitTime") = instanceActInfo.waitTime;
activityInfo.PushDebug<AMFIntValue>("startDelay") = instanceActInfo.startDelay;
activityInfo.PushDebug<AMFBoolValue>("requiresUniqueData") = instanceActInfo.requiresUniqueData;
activityInfo.PushDebug<AMFIntValue>("leaderboardType") = instanceActInfo.leaderboardType;
activityInfo.PushDebug<AMFBoolValue>("localize") = instanceActInfo.localize;
activityInfo.PushDebug<AMFIntValue>("optionalCostLOT") = instanceActInfo.optionalCostLOT;
activityInfo.PushDebug<AMFIntValue>("optionalCostCount") = instanceActInfo.optionalCostCount;
activityInfo.PushDebug<AMFBoolValue>("showUIRewards") = instanceActInfo.showUIRewards;
activityInfo.PushDebug<AMFIntValue>("CommunityActivityFlagID") = instanceActInfo.CommunityActivityFlagID;
activityInfo.PushDebug<AMFStringValue>("gate_version") = instanceActInfo.gate_version;
activityInfo.PushDebug<AMFBoolValue>("noTeamLootOnDeath") = instanceActInfo.noTeamLootOnDeath;
activityInfo.PushDebug<AMFDoubleValue>("optionalPercentage") = instanceActInfo.optionalPercentage;
}
auto& participants = instance.PushDebug("Participants");
for (const auto* participant : activityInstance.GetParticipants()) {
if (!participant) continue;
auto* character = participant->GetCharacter();
if (!character) continue;
participants.PushDebug<AMFStringValue>(std::to_string(participant->GetObjectID()) + ": " + character->GetName()) = "";
}
}
auto& activityPlayers = activityInfo.PushDebug("Activity Players");
for (const auto& [playerID, playerScores] : m_ActivityPlayers) {
auto* const activityPlayerEntity = Game::entityManager->GetEntity(playerID);
if (!activityPlayerEntity) continue;
auto* character = activityPlayerEntity->GetCharacter();
if (!character) continue;
auto& playerData = activityPlayers.PushDebug(std::to_string(playerID) + " " + character->GetName());
auto& scores = playerData.PushDebug("Scores");
for (size_t i = 0; i < 10; ++i) {
scores.PushDebug<AMFDoubleValue>(std::to_string(i)) = playerScores[i];
}
}
activityInfo.PushDebug<AMFIntValue>("ActivityID") = m_ActivityID;
return true;
}

View File

@@ -0,0 +1,311 @@
#ifndef ACTIVITYCOMPONENT_H
#define ACTIVITYCOMPONENT_H
#include "CDClientManager.h"
#include "BitStream.h"
#include "Entity.h"
#include "Component.h"
#include "eReplicaComponentType.h"
#include "CDActivitiesTable.h"
#include <array>
namespace GameMessages {
class GameMsg;
};
namespace ChatPackets {
struct MatchTransfer;
};
/**
* Represents an instance of an activity, having participants and score
*/
class ActivityInstance {
public:
ActivityInstance(Entity* parent, CDActivities activityInfo) { m_Parent = parent; m_ActivityInfo = activityInfo; };
//~ActivityInstance();
/**
* Adds an entity to this activity
* @param participant the entity to add
*/
void AddParticipant(Entity* participant);
/**
* Removes all the participants from this activity
*/
void ClearParticipants() { m_Participants.clear(); };
/**
* Sends the participants to the activity's instance that master started (the chat server's matchmaking found it)
* @param transfer the instance's zone, address and the players chat sent here
*/
void TransferParticipants(const ChatPackets::MatchTransfer& transfer);
/**
* Gives the rewards for completing this activity to some participant
* @param participant the participant to give rewards to
*/
void RewardParticipant(Entity* participant);
/**
* Removes a participant from this activity
* @param participant the participant to remove
*/
void RemoveParticipant(const Entity* participant);
/**
* Returns all the participants of this activity
* @return all the participants of this activity
*/
std::vector<Entity*> GetParticipants() const;
/**
* Currently unused
*/
uint32_t GetScore() const;
/**
* Currently unused
*/
void SetScore(uint32_t score);
[[nodiscard]] uint32_t GetNextZoneCloneID() const noexcept { return m_NextZoneCloneID; }
const CDActivities& GetActivityInfo() const noexcept { return m_ActivityInfo; }
private:
/**
* Currently unused
*/
uint32_t score = 0;
/**
* The instance ID of this activity
*/
uint32_t m_NextZoneCloneID = 0;
/**
* The database information for this activity
*/
CDActivities m_ActivityInfo{};
/**
* The entity that owns this activity (the entity that has the ScriptedActivityComponent)
*/
Entity* m_Parent{};
/**
* All the participants of this activity
*/
std::vector<LWOOBJID> m_Participants;
};
/**
* Represents the score for the player in an activity, one index might represent score, another one time, etc.
*/
struct ActivityPlayer {
/**
* The entity that the score is tracked for
*/
LWOOBJID playerID{};
/**
* The list of score for this entity
*/
float values[10]{};
};
/**
* Welcome to the absolute behemoth that is the scripted activity component. I have now clue how this was managed in
* live but I figure somewhat similarly and it's terrible. In a nutshell, this components handles any activity that
* can be done in the game from quick builds to boss fights to races. On top of that, this component handles instancing
* and lobbying.
*/
class ActivityComponent : public Component {
public:
ActivityComponent(Entity* parent, int32_t activityID);
void LoadDataFromTemplate() override;
void LoadConfigData() override;
void LoadActivityData(const int32_t activityId);
void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override;
/**
* Makes some entity join the minigame, if it's a lobbied one, the entity will be placed in the lobby
* @param player the entity to join the game
* @param playerChoices the name-value text of the client's MatchRequest (a racing car), shown to the lobby
*/
void PlayerJoin(Entity* player, const std::string& playerChoices = "");
/**
* Makes an entity join the lobby for this minigame. The lobbies are the chat server's, across every world
* (docs/Matchmaking.md).
* @param player the entity to join
* @param playerChoices the name-value text of the client's MatchRequest
*/
void PlayerJoinLobby(Entity* player, const std::string& playerChoices = "");
/**
* Makes the player leave the lobby (the chat server's)
* @param playerID the entity to leave the lobby
*/
void PlayerLeave(LWOOBJID playerID);
/**
* Removes the entity from the minigame (and its score)
* @param playerID the entity to remove from the minigame
*/
void PlayerRemove(LWOOBJID playerID);
/**
* A lobby's match for this activity has its instance: the players of it in this world who can pay go there
* @param transfer the instance and the players, from the chat server
*/
void StartMatch(const ChatPackets::MatchTransfer& transfer);
/**
* Marks a player as (un)ready in the lobby they wait in (the chat server knows which)
* @param player the entity to mark
* @param bReady true if the entity is ready, false otherwise
*/
static void PlayerReady(Entity* player, bool bReady);
/**
* Returns the ID of this activity
* @return the ID of this activity
*/
int GetActivityID() { return m_ActivityInfo.ActivityID; }
// Whether or not team loot should be dropped on death for this activity
// if true, and a player is supposed to get loot, they are skipped
bool GetNoTeamLootOnDeath() const { return m_ActivityInfo.noTeamLootOnDeath; }
/**
* Returns if this activity has a lobby, e.g. if it needs to instance players to some other map
* @return true if this activity has a lobby, false otherwise
*/
bool HasLobby() const;
/**
* Checks if an entity is currently playing this activity
* @param player the entity to check
* @return true if the entity is playing this lobby, false otherwise
*/
bool IsPlayedBy(Entity* player) const;
/**
* Checks if an entity is currently playing this activity
* @param playerID the entity to check
* @return true if the entity is playing this lobby, false otherwise
*/
bool IsPlayedBy(LWOOBJID playerID) const;
/**
* Checks if the entity has enough cost to play this activity
* @param player the entity to check
* @return true if the entity has enough cost to play this activity, false otherwise
*/
bool CheckCost(Entity* player) const;
/**
* Removes the cost of the activity (e.g. green imaginate) for the entity that plays this activity
* @param player the entity to take cost for
* @return true if the cost was taken, false otherwise
*/
bool TakeCost(Entity* player) const;
/**
* Handles any response from a player clicking on a lobby / instance menu
* @param player the entity that clicked
* @param id the message that was passed
*/
void HandleMessageBoxResponse(Entity* player, const std::string& id);
/**
* Creates a new instance for this activity
* @return a new instance for this activity
*/
ActivityInstance& NewInstance();
/**
* Returns the instance that some entity is currently playing in
* @param playerID the entity to check for
* @return if any, the instance that the entity is currently in
*/
const ActivityInstance& GetInstance(const LWOOBJID playerID) const;
/**
* @brief Reloads the config settings for this component
*
*/
void ReloadConfig();
/**
* Returns activity data for a specific entity (e.g. score and such).
* @param playerID the entity to get data for
* @return the activity data (score) for the passed player in this activity, if it exists
*/
bool PlayerHasActivityData(LWOOBJID playerID) const;
/**
* Sets some score value for an entity
* @param playerID the entity to set score for
* @param index the score index to set
* @param value the value to set in for that index
*/
void SetActivityValue(LWOOBJID playerID, uint32_t index, float_t value);
/**
* Returns activity score for the passed parameters
* @param playerID the entity to get score for
* @param index the index to get score for
* @return activity score for the passed parameters
*/
float_t GetActivityValue(LWOOBJID playerID, uint32_t index) const;
/**
* Removes activity score tracking for some entity
* @param playerID the entity to remove score for
*/
void RemoveActivityPlayerData(LWOOBJID playerID);
/**
* Sets the mapID that this activity points to
* @param mapID the map ID to set
*/
void SetInstanceMapID(uint32_t mapID) { m_ActivityInfo.instanceMapID = mapID; };
private:
bool OnGetObjectReportInfo(GameMessages::GetObjectReportInfo& msg);
/**
* The database information for this activity
*/
CDActivities m_ActivityInfo{};
/**
* All the active instances of this activity
*/
std::vector<ActivityInstance> m_Instances;
/**
* All the activity score for the players in this activity
*/
std::map<LWOOBJID, std::array<float, 10>> m_ActivityPlayers;
/**
* The activity id
*/
int32_t m_ActivityID;
/**
* If the Activity info is dirty
*/
bool m_DirtyActivityInfo = true;
};
#endif // ACTIVITYCOMPONENT_H

View File

@@ -0,0 +1,15 @@
#ifndef BASERACINGCONTROLCOMPONENT_H
#define BASERACINGCONTROLCOMPONENT_H
#include "ActivityComponent.h"
/**
* The base of the racing controls, as the client's LWOBaseRacingControlComponent: an activity component that racing
* control (71) and gate rush control (103) are built on (its function table extends the activity component's).
*/
class BaseRacingControlComponent : public ActivityComponent {
protected:
BaseRacingControlComponent(Entity* parent, const int32_t componentID) : ActivityComponent(parent, componentID) {}
};
#endif // BASERACINGCONTROLCOMPONENT_H

View File

@@ -0,0 +1,18 @@
#ifndef GATERUSHCOMPONENT_H
#define GATERUSHCOMPONENT_H
#include "BaseRacingControlComponent.h"
#include "eReplicaComponentType.h"
/**
* Gate rush control, as the client's LWOGateRushControlComponent makes it from the registry: a racing control
* (BaseRacingControlComponent). Nothing of it is sent or done on the server yet.
*/
class GateRushComponent final : public BaseRacingControlComponent {
public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::GATE_RUSH_CONTROL;
GateRushComponent(Entity* parent, const int32_t componentID) : BaseRacingControlComponent(parent, componentID) {}
};
#endif // GATERUSHCOMPONENT_H

View File

@@ -0,0 +1,18 @@
#ifndef __MINIGAMECONTROLCOMPONENT__H__
#define __MINIGAMECONTROLCOMPONENT__H__
#include "ActivityComponent.h"
#include "eReplicaComponentType.h"
/**
* Minigame control (50), the zone control object's: an activity component as in the client (LWOMinigameComponent),
* which also sends what an activity sends.
*/
class MiniGameControlComponent final : public ActivityComponent {
public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MINI_GAME_CONTROL;
MiniGameControlComponent(Entity* parent, const int32_t componentID) : ActivityComponent(parent, componentID) {}
};
#endif //!__MINIGAMECONTROLCOMPONENT__H__

View File

@@ -0,0 +1,781 @@
#include "QuickBuildComponent.h"
#include "CDClientManager.h"
#include "CDRebuildComponentTable.h"
#include "Entity.h"
#include "DestroyableComponent.h"
#include "GameMessages.h"
#include "EffectsMessages.h"
#include "CombatMessages.h"
#include "ObjectMessages.h"
#include "QuickBuildMessages.h"
#include "EntityManager.h"
#include "Game.h"
#include "Logger.h"
#include "CharacterComponent.h"
#include "MissionComponent.h"
#include "InventoryComponent.h"
#include "eMissionTaskType.h"
#include "eTriggerEventType.h"
#include "eQuickBuildFailReason.h"
#include "eTerminateType.h"
#include "eGameActivity.h"
#include "dServer.h"
#include "Spawner.h"
#include "MovingPlatformComponent.h"
#include "Preconditions.h"
#include "Loot.h"
#include "TeamManager.h"
#include "RenderComponent.h"
#include "CppScripts.h"
#include "StringifiedEnum.h"
#include "Amf3.h"
#include "EconomyLedger.h"
QuickBuildComponent::QuickBuildComponent(Entity* const entity, const int32_t componentID) : ActivityComponent{ entity, componentID } {
RegisterMsg(&QuickBuildComponent::OnRequestUse);
RegisterMsg(&QuickBuildComponent::OnGetObjectReportInfo);
}
// The level config: the precondition and the activator's position, then the activator
// The RebuildComponent row, its activity among them (LWOQuickBuildComponent is an activity component in the client)
void QuickBuildComponent::LoadDataFromTemplate() {
const auto componentID = m_ComponentID;
const std::vector<CDRebuildComponent> rebCompData = CDClientManager::GetTable<CDRebuildComponentTable>()->Query([componentID](CDRebuildComponent entry) { return (entry.id == static_cast<uint32_t>(componentID)); });
if (rebCompData.empty()) return;
SetResetTime(rebCompData[0].reset_time);
SetCompleteTime(rebCompData[0].complete_time);
SetTakeImagination(rebCompData[0].take_imagination);
SetInterruptible(rebCompData[0].interruptible);
SetSelfActivator(rebCompData[0].self_activator);
SetActivityId(rebCompData[0].activityID);
SetPostImaginationCost(rebCompData[0].post_imagination_cost);
SetTimeBeforeSmash(rebCompData[0].time_before_smash);
LoadActivityData(rebCompData[0].activityID);
m_HasRow = true;
}
void QuickBuildComponent::LoadConfigData() {
std::u16string checkPreconditions = m_Parent->GetVar<std::u16string>(u"CheckPrecondition");
if (!checkPreconditions.empty()) {
m_Precondition = new PreconditionExpression(GeneralUtils::UTF16ToWTF8(checkPreconditions));
}
// Should a setting that has the build activator position exist, fetch that setting here and parse it for position.
// It is assumed that the user who sets this setting uses the correct character delimiter (character 31 or in hex 0x1F)
auto positionAsVector = GeneralUtils::SplitString(m_Parent->GetVarAsString(u"rebuild_activators"), 0x1F);
const auto activatorPositionValid = GeneralUtils::TryParse<NiPoint3>(positionAsVector);
if (positionAsVector.size() == 3 && activatorPositionValid) {
m_ActivatorPosition = activatorPositionValid.value();
} else {
LOG("Failed to find activator position for lot %i. Defaulting to parents position.", m_Parent->GetLOT());
m_ActivatorPosition = m_Parent->GetPosition();
}
// The activator is spawned as it was before the row loaded in LoadDataFromTemplate: without looking at
// self_activator (unchanged behaviour; whether live made activators for self-activating quickbuilds is unchecked)
const bool selfActivator = m_SelfActivator;
m_SelfActivator = false;
SpawnActivator();
m_SelfActivator = selfActivator;
// The level's settings over the row's
if (!m_HasRow) return;
const auto rebuildResetTime = m_Parent->GetVar<float>(u"rebuild_reset_time");
if (rebuildResetTime != 0.0f) SetResetTime(rebuildResetTime);
// The level's activityID replaces the template's. The client (LWOQuickBuildComponent::LoadDataFromTemplate)
// reads RebuildComponent.activityID over it unless the level sets actIDovrd, but live used the level's:
// the AM Center draw bridge (LOT 12047: level activityID 12047 without actIDovrd, template activity 6,
// the quickbuild rewards) dropped no loot in 4 of 4 live completions.
const auto activityID = m_Parent->GetVar<int32_t>(u"activityID");
if (activityID > 0) {
SetActivityId(activityID);
Loot::CacheMatrix(activityID);
}
const auto timeBeforeSmash = m_Parent->GetVar<float>(u"tmeSmsh");
if (timeBeforeSmash > 0) SetTimeBeforeSmash(timeBeforeSmash);
const auto compTime = m_Parent->GetVar<float>(u"compTime");
if (compTime > 0) SetCompleteTime(compTime);
}
QuickBuildComponent::~QuickBuildComponent() {
delete m_Precondition;
Entity* builder = GetBuilder();
if (builder) {
CancelQuickBuild(builder, eQuickBuildFailReason::BUILD_ENDED, true);
}
DespawnActivator();
}
void QuickBuildComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) {
if (m_Parent->GetComponent(eReplicaComponentType::DESTROYABLE) == nullptr) {
if (bIsInitialUpdate) {
outBitStream.Write(false);
}
outBitStream.Write(false);
outBitStream.Write(false);
}
// BEGIN Scripted Activity
outBitStream.Write1();
Entity* builder = GetBuilder();
if (builder) {
outBitStream.Write<uint32_t>(1);
outBitStream.Write(builder->GetObjectID());
for (int i = 0; i < 10; i++) {
outBitStream.Write(0.0f);
}
} else {
outBitStream.Write<uint32_t>(0);
}
// END Scripted Activity
outBitStream.Write(m_StateDirty || bIsInitialUpdate);
if (m_StateDirty || bIsInitialUpdate) {
outBitStream.Write(m_State);
outBitStream.Write(m_ShowResetEffect);
outBitStream.Write(m_Activator != nullptr);
outBitStream.Write(m_Timer);
outBitStream.Write(m_TimerIncomplete);
if (bIsInitialUpdate) {
outBitStream.Write(false); // IsChoiceBuild
outBitStream.Write(m_ActivatorPosition);
outBitStream.Write(m_RepositionPlayer);
}
m_StateDirty = false;
}
}
void QuickBuildComponent::Run(float deltaTime) {
SetActivator(GetActivator());
switch (m_State) {
case eQuickBuildState::OPEN: {
SpawnActivator();
m_TimeBeforeDrain = 0;
auto* spawner = m_Parent->GetSpawner();
const bool isSmashGroup = spawner != nullptr ? spawner->GetIsSpawnSmashGroup() : false;
if (isSmashGroup) {
ModifyIncompleteTimer(deltaTime);
// For reset times < 0 this has to be handled manually
if (m_TimeBeforeSmash > 0) {
if (m_TimerIncomplete >= m_TimeBeforeSmash - 4.0f && !m_ShowResetEffect) {
SetShowResetEffect(true);
Game::entityManager->SerializeEntity(m_Parent);
}
if (m_TimerIncomplete >= m_TimeBeforeSmash) {
m_Builder = LWOOBJID_EMPTY;
GameMessages::Die die;
die.target = m_Parent->GetObjectID();
die.bClientDeath = false;
die.bSpawnLoot = true;
die.killerID = LWOOBJID_EMPTY;
die.Send(UNASSIGNED_SYSTEM_ADDRESS);
ResetQuickBuild(false);
}
}
}
break;
}
case eQuickBuildState::COMPLETED: {
ModifyTimer(deltaTime);
// For reset times < 0 this has to be handled manually
if (m_ResetTime > 0) {
if (m_Timer >= m_ResetTime - 4.0f && !m_ShowResetEffect) {
SetShowResetEffect(true);
Game::entityManager->SerializeEntity(m_Parent);
}
if (m_Timer >= m_ResetTime) {
GameMessages::Die die;
die.target = m_Parent->GetObjectID();
die.bClientDeath = false;
die.bSpawnLoot = true;
die.directionRelative_Force = 7.0f;
die.killerID = LWOOBJID_EMPTY;
die.Send(UNASSIGNED_SYSTEM_ADDRESS);
ResetQuickBuild(false);
}
}
break;
}
case eQuickBuildState::BUILDING:
{
Entity* builder = GetBuilder();
if (!builder) {
ResetQuickBuild(false);
return;
}
m_TimeBeforeDrain -= deltaTime;
ModifyTimer(deltaTime);
SetIncompleteTimer(0.0f);
SetShowResetEffect(false);
if (m_TimeBeforeDrain <= 0.0f) {
m_TimeBeforeDrain = m_CompleteTime / static_cast<float>(m_TakeImagination);
DestroyableComponent* destComp = builder->GetComponent<DestroyableComponent>();
if (!destComp) break;
++m_DrainedImagination;
const int32_t imaginationCostRemaining = m_TakeImagination - m_DrainedImagination;
const int32_t newImagination = destComp->GetImagination() - 1;
destComp->SetImagination(newImagination);
Game::entityManager->SerializeEntity(builder);
if (newImagination <= 0 && imaginationCostRemaining > 0) {
CancelQuickBuild(builder, eQuickBuildFailReason::OUT_OF_IMAGINATION, true);
break;
}
}
if (m_Timer >= m_CompleteTime && m_DrainedImagination >= m_TakeImagination) {
CompleteQuickBuild(builder);
}
break;
}
case eQuickBuildState::INCOMPLETE: {
ModifyIncompleteTimer(deltaTime);
// For reset times < 0 this has to be handled manually
if (m_TimeBeforeSmash > 0) {
if (m_TimerIncomplete >= m_TimeBeforeSmash - 4.0f && !m_ShowResetEffect) {
SetShowResetEffect(true);
Game::entityManager->SerializeEntity(m_Parent);
}
if (m_TimerIncomplete >= m_TimeBeforeSmash) {
m_Builder = LWOOBJID_EMPTY;
GameMessages::Die die;
die.target = m_Parent->GetObjectID();
die.bClientDeath = false;
die.bSpawnLoot = true;
die.killerID = LWOOBJID_EMPTY;
die.Send(UNASSIGNED_SYSTEM_ADDRESS);
ResetQuickBuild(false);
}
}
break;
}
case eQuickBuildState::RESETTING: break;
}
}
bool QuickBuildComponent::OnRequestUse(GameMessages::RequestUseEvent& event) {
if (event.msg.IsMissionChoice()) return false;
auto* const originator = event.user;
if (GetBuilder() != nullptr || m_State == eQuickBuildState::COMPLETED) {
return true;
}
if (m_Precondition != nullptr && !m_Precondition->Check(originator)) {
return true;
}
StartQuickBuild(originator);
return true;
}
void QuickBuildComponent::SpawnActivator() {
if (!m_SelfActivator || m_ActivatorPosition != NiPoint3Constant::ZERO) {
if (!m_Activator) {
EntityInfo info;
info.lot = 6604;
info.spawnerID = m_Parent->GetObjectID();
info.pos = m_ActivatorPosition == NiPoint3Constant::ZERO ? m_Parent->GetPosition() : m_ActivatorPosition;
SetActivator(Game::entityManager->CreateEntity(info, nullptr, m_Parent));
if (m_Activator) {
m_ActivatorId = m_Activator->GetObjectID();
Game::entityManager->ConstructEntity(m_Activator);
}
Game::entityManager->SerializeEntity(m_Parent);
}
}
}
void QuickBuildComponent::DespawnActivator() {
if (m_Activator) {
Game::entityManager->DestructEntity(m_Activator);
m_Activator->ScheduleKillAfterUpdate();
SetActivator(nullptr);
m_ActivatorId = LWOOBJID_EMPTY;
}
}
Entity* QuickBuildComponent::GetActivator() const {
return Game::entityManager->GetEntity(m_ActivatorId);
}
NiPoint3 QuickBuildComponent::GetActivatorPosition() const noexcept {
return m_ActivatorPosition;
}
float QuickBuildComponent::GetResetTime() const noexcept {
return m_ResetTime;
}
float QuickBuildComponent::GetCompleteTime() const noexcept {
return m_CompleteTime;
}
int32_t QuickBuildComponent::GetTakeImagination() const noexcept {
return m_TakeImagination;
}
bool QuickBuildComponent::GetInterruptible() const noexcept {
return m_Interruptible;
}
bool QuickBuildComponent::GetSelfActivator() const noexcept {
return m_SelfActivator;
}
std::vector<int32_t> QuickBuildComponent::GetCustomModules() const noexcept {
return m_CustomModules;
}
int32_t QuickBuildComponent::GetActivityId() const noexcept {
return m_ActivityId;
}
int32_t QuickBuildComponent::GetPostImaginationCost() const noexcept {
return m_PostImaginationCost;
}
float QuickBuildComponent::GetTimeBeforeSmash() const noexcept {
return m_TimeBeforeSmash;
}
eQuickBuildState QuickBuildComponent::GetState() const noexcept {
return m_State;
}
Entity* QuickBuildComponent::GetBuilder() const {
auto* const builder = Game::entityManager->GetEntity(m_Builder);
return builder;
}
bool QuickBuildComponent::GetRepositionPlayer() const noexcept {
return m_RepositionPlayer;
}
void QuickBuildComponent::SetActivatorPosition(const NiPoint3& value) noexcept {
m_ActivatorPosition = value;
}
void QuickBuildComponent::SetResetTime(const float value) noexcept {
m_ResetTime = value;
}
void QuickBuildComponent::SetCompleteTime(const float value) noexcept {
if (value < 0) {
m_CompleteTime = 4.5f;
} else {
m_CompleteTime = value;
}
}
void QuickBuildComponent::SetTakeImagination(const int32_t value) noexcept {
m_TakeImagination = value;
}
void QuickBuildComponent::SetInterruptible(const bool value) noexcept {
m_Interruptible = value;
}
void QuickBuildComponent::SetSelfActivator(const bool value) noexcept {
m_SelfActivator = value;
}
void QuickBuildComponent::SetCustomModules(const std::vector<int32_t>& value) noexcept {
m_CustomModules = value;
}
void QuickBuildComponent::SetActivityId(const int32_t value) noexcept {
m_ActivityId = value;
}
void QuickBuildComponent::SetPostImaginationCost(const int32_t value) noexcept {
m_PostImaginationCost = value;
}
void QuickBuildComponent::SetTimeBeforeSmash(const float value) noexcept {
if (value < 0) {
m_TimeBeforeSmash = 10.0f;
} else {
m_TimeBeforeSmash = value;
}
}
void QuickBuildComponent::SetRepositionPlayer(const bool value) noexcept {
m_RepositionPlayer = value;
}
void QuickBuildComponent::StartQuickBuild(Entity* const user) {
if (m_State == eQuickBuildState::OPEN || m_State == eQuickBuildState::COMPLETED || m_State == eQuickBuildState::INCOMPLETE) {
m_Builder = user->GetObjectID();
auto* character = user->GetComponent<CharacterComponent>();
if (character) character->SetCurrentActivity(eGameActivity::QUICKBUILDING);
Game::entityManager->SerializeEntity(user);
GameMessages::RebuildNotifyState notifyState;
notifyState.target = m_Parent->GetObjectID();
notifyState.prevState = m_State;
notifyState.state = eQuickBuildState::BUILDING;
notifyState.player = user->GetObjectID();
notifyState.Send(UNASSIGNED_SYSTEM_ADDRESS);
GameMessages::EnableRebuild enableRebuild;
enableRebuild.target = m_Parent->GetObjectID();
enableRebuild.bEnable = true;
enableRebuild.bFail = false;
enableRebuild.bSuccess = false;
enableRebuild.eFailReason = eQuickBuildFailReason::NOT_GIVEN;
enableRebuild.fDuration = 0.0f;
enableRebuild.user = user->GetObjectID();
enableRebuild.Send(UNASSIGNED_SYSTEM_ADDRESS);
SetState(eQuickBuildState::BUILDING);
Game::entityManager->SerializeEntity(m_Parent);
TakeItemCosts(*user);
auto* movingPlatform = m_Parent->GetComponent<MovingPlatformComponent>();
if (movingPlatform != nullptr) {
movingPlatform->OnQuickBuildInitilized();
}
auto* script = m_Parent->GetScript();
script->OnQuickBuildStart(m_Parent, user);
// Notify scripts and possible subscribers
script->OnQuickBuildNotifyState(m_Parent, m_State);
for (const auto& cb : m_QuickBuildStateCallbacks)
cb(m_State);
}
}
void QuickBuildComponent::CompleteQuickBuild(Entity* const user) {
if (!user) return;
auto* characterComponent = user->GetComponent<CharacterComponent>();
if (characterComponent != nullptr) {
characterComponent->SetCurrentActivity(eGameActivity::NONE);
EconomyLedger::RecordMapEvent(IEconomyLedger::eMapEvent::QUICKBUILDS_COMPLETED, m_Parent->GetLOT(), m_Parent->GetPosition(), 1, user);
} else {
LOG("Some user tried to finish the rebuild but they didn't have a character somehow.");
return;
}
Game::entityManager->SerializeEntity(user);
GameMessages::RebuildNotifyState notifyState;
notifyState.target = m_Parent->GetObjectID();
notifyState.prevState = m_State;
notifyState.state = eQuickBuildState::COMPLETED;
notifyState.player = user->GetObjectID();
notifyState.Send(UNASSIGNED_SYSTEM_ADDRESS);
GameMessages::PlayFXEffect fx(m_Parent->GetObjectID(), 507, u"create", "BrickFadeUpVisCompleteEffect");
fx.priority = 0.4f;
fx.Send(UNASSIGNED_SYSTEM_ADDRESS);
// Live: RebuildNotifyState(Completed), the effect, then QuickBuildsCompleted, then EnableRebuild
characterComponent->TrackQuickBuildComplete();
GameMessages::EnableRebuild enableRebuild;
enableRebuild.target = m_Parent->GetObjectID();
enableRebuild.bEnable = false;
enableRebuild.bFail = false;
enableRebuild.bSuccess = true;
enableRebuild.eFailReason = eQuickBuildFailReason::NOT_GIVEN;
// Live sent no duration on success (744 of 744); cancels carry the time spent building.
enableRebuild.fDuration = 0.0f;
enableRebuild.user = user->GetObjectID();
enableRebuild.Send(UNASSIGNED_SYSTEM_ADDRESS);
characterComponent->SendZoneStatisticIncrement(u"QuickBuildsCompleted");
GameMessages::TerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()).Send(UNASSIGNED_SYSTEM_ADDRESS);
SetState(eQuickBuildState::COMPLETED);
SetTimer(0.0f);
m_DrainedImagination = 0;
Game::entityManager->SerializeEntity(m_Parent);
// The items taken when the build started are used up
m_TakenItems.clear();
m_TakenItemsFrom = LWOOBJID_EMPTY;
DespawnActivator();
// Set owner override so that entities smashed by this quickbuild will result in the builder getting rewards.
m_Parent->SetOwnerOverride(user->GetObjectID());
auto* builder = GetBuilder();
if (builder) {
auto* team = TeamManager::Instance()->GetTeam(builder->GetObjectID());
if (team) {
for (const auto memberId : team->members) { // progress missions for all team members
auto* member = Game::entityManager->GetEntity(memberId);
if (member) {
auto* missionComponent = member->GetComponent<MissionComponent>();
if (missionComponent) missionComponent->Progress(eMissionTaskType::ACTIVITY, m_ActivityId);
}
}
} else {
auto* missionComponent = builder->GetComponent<MissionComponent>();
if (missionComponent) missionComponent->Progress(eMissionTaskType::ACTIVITY, m_ActivityId);
}
Loot::DropActivityLoot(builder, m_Parent->GetObjectID(), m_ActivityId, 1);
}
// A built platform sets off before the scripts hear of it, so a script that stops it (live's L_AG_QB_ELEVATOR and
// L_PROP_PLATFORM stop theirs) keeps it stopped
auto* movingPlatform = m_Parent->GetComponent<MovingPlatformComponent>();
if (movingPlatform != nullptr) {
movingPlatform->OnCompleteQuickBuild();
}
// Notify scripts
auto* script = m_Parent->GetScript();
script->OnQuickBuildComplete(m_Parent, user);
script->OnQuickBuildNotifyState(m_Parent, m_State);
// Notify subscribers
for (const auto& callback : m_QuickBuildStateCallbacks)
callback(m_State);
for (const auto& callback : m_QuickBuildCompleteCallbacks)
callback(user);
m_Parent->TriggerEvent(eTriggerEventType::REBUILD_COMPLETE, user);
// Set flag
auto* character = user->GetCharacter();
if (character != nullptr) {
const auto flagNumber = m_Parent->GetVar<int32_t>(u"quickbuild_single_build_player_flag");
if (flagNumber != 0) {
character->SetPlayerFlag(flagNumber, true);
}
}
RenderComponent::PlayAnimation(user, u"rebuild-celebrate", 1.09f);
}
void QuickBuildComponent::ResetQuickBuild(const bool failed) {
Entity* builder = GetBuilder();
if (m_State == eQuickBuildState::BUILDING && builder) {
GameMessages::EnableRebuild enableRebuild;
enableRebuild.target = m_Parent->GetObjectID();
enableRebuild.bEnable = false;
enableRebuild.bFail = false;
enableRebuild.bSuccess = failed;
enableRebuild.eFailReason = eQuickBuildFailReason::NOT_GIVEN;
enableRebuild.fDuration = m_ResetTime;
enableRebuild.user = builder->GetObjectID();
enableRebuild.Send(UNASSIGNED_SYSTEM_ADDRESS);
if (failed) {
RenderComponent::PlayAnimation(builder, u"rebuild-fail");
}
}
GameMessages::RebuildNotifyState notifyState;
notifyState.target = m_Parent->GetObjectID();
notifyState.prevState = m_State;
notifyState.state = eQuickBuildState::RESETTING;
notifyState.player = LWOOBJID_EMPTY;
notifyState.Send(UNASSIGNED_SYSTEM_ADDRESS);
RefundItemCosts();
SetState(eQuickBuildState::RESETTING);
SetTimer(0.0f);
SetIncompleteTimer(0.0f);
SetShowResetEffect(false);
m_DrainedImagination = 0;
Game::entityManager->SerializeEntity(m_Parent);
// Notify scripts and possible subscribers
m_Parent->GetScript()->OnQuickBuildNotifyState(m_Parent, m_State);
for (const auto& cb : m_QuickBuildStateCallbacks)
cb(m_State);
m_Parent->ScheduleKillAfterUpdate();
if (m_Activator) {
m_Activator->ScheduleKillAfterUpdate();
}
}
void QuickBuildComponent::CancelQuickBuild(Entity* const entity, const eQuickBuildFailReason failReason, const bool skipChecks) {
if (m_State != eQuickBuildState::COMPLETED || skipChecks) {
m_Builder = LWOOBJID_EMPTY;
const auto entityID = entity != nullptr ? entity->GetObjectID() : LWOOBJID_EMPTY;
// Notify the client that a state has changed
GameMessages::RebuildNotifyState notifyState;
notifyState.target = m_Parent->GetObjectID();
notifyState.prevState = m_State;
notifyState.state = eQuickBuildState::INCOMPLETE;
notifyState.player = entityID;
notifyState.Send(UNASSIGNED_SYSTEM_ADDRESS);
GameMessages::EnableRebuild enableRebuild;
enableRebuild.target = m_Parent->GetObjectID();
enableRebuild.bEnable = false;
enableRebuild.bFail = true;
enableRebuild.bSuccess = false;
enableRebuild.eFailReason = failReason;
enableRebuild.fDuration = m_Timer;
enableRebuild.user = entityID;
enableRebuild.Send(UNASSIGNED_SYSTEM_ADDRESS);
// Now terminate any interaction with the rebuild
GameMessages::TerminateInteraction(entityID, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()).Send(UNASSIGNED_SYSTEM_ADDRESS);
GameMessages::TerminateInteraction(m_Parent->GetObjectID(), eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()).Send(UNASSIGNED_SYSTEM_ADDRESS);
// Now update the component itself
SetState(eQuickBuildState::INCOMPLETE);
RefundItemCosts();
// Notify scripts and possible subscribers
m_Parent->GetScript()->OnQuickBuildNotifyState(m_Parent, m_State);
for (const auto& cb : m_QuickBuildStateCallbacks)
cb(m_State);
Game::entityManager->SerializeEntity(m_Parent);
}
if (!entity) return;
CharacterComponent* characterComponent = entity->GetComponent<CharacterComponent>();
if (characterComponent) {
characterComponent->SetCurrentActivity(eGameActivity::NONE);
Game::entityManager->SerializeEntity(entity);
}
}
void QuickBuildComponent::CancelBuildsBy(Entity& player) {
for (auto* const entity : Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::QUICK_BUILD)) {
auto* const quickBuild = entity->GetComponent<QuickBuildComponent>();
if (quickBuild && quickBuild->m_State == eQuickBuildState::BUILDING && quickBuild->m_Builder == player.GetObjectID()) {
quickBuild->CancelQuickBuild(&player, eQuickBuildFailReason::BUILD_ENDED, true);
}
}
}
void QuickBuildComponent::TakeItemCosts(Entity& user) {
RefundItemCosts();
if (!m_Precondition) return;
auto* const inventoryComponent = user.GetComponent<InventoryComponent>();
if (!inventoryComponent) return;
// Live took the precondition items (for example the FV Stone Warrior pedestal's 5 Maelstrom Infected Bricks)
// when the build started and gave them back when it was cancelled. The removal names the quickbuild as its loot
// source (Quickbuild, the quickbuild's object ID), as live's did.
const ItemRemovalSource removalSource{ eLootSourceType::QUICKBUILD, m_Parent->GetObjectID() };
for (const auto& cost : m_Precondition->GetItemCosts(&user)) {
if (inventoryComponent->RemoveItem(cost.lot, cost.count, eInventoryType::ALL, false, false, removalSource)) m_TakenItems.push_back(cost);
}
if (!m_TakenItems.empty()) m_TakenItemsFrom = user.GetObjectID();
}
void QuickBuildComponent::RefundItemCosts() {
if (m_TakenItems.empty()) return;
auto* const taker = Game::entityManager->GetEntity(m_TakenItemsFrom);
auto* const inventoryComponent = taker ? taker->GetComponent<InventoryComponent>() : nullptr;
if (inventoryComponent) {
for (const auto& cost : m_TakenItems) inventoryComponent->AddItem(cost.lot, cost.count, eLootSourceType::QUICKBUILD);
} else {
LOG("Quickbuild %llu could not give back the items it took from %llu", m_Parent->GetObjectID(), m_TakenItemsFrom);
}
m_TakenItems.clear();
m_TakenItemsFrom = LWOOBJID_EMPTY;
}
void QuickBuildComponent::AddQuickBuildCompleteCallback(const std::function<void(Entity* user)>& callback) {
m_QuickBuildCompleteCallbacks.push_back(callback);
}
void QuickBuildComponent::AddQuickBuildStateCallback(const std::function<void(eQuickBuildState state)>& callback) {
m_QuickBuildStateCallbacks.push_back(callback);
}
bool QuickBuildComponent::OnGetObjectReportInfo(GameMessages::GetObjectReportInfo& reportInfo) {
auto& quickbuild = reportInfo.info->PushDebug("Quick Build");
quickbuild.PushDebug<AMFStringValue>("State") = StringifiedEnum::ToString(m_State).data();
quickbuild.PushDebug<AMFDoubleValue>("Timer") = m_Timer;
quickbuild.PushDebug<AMFDoubleValue>("Timer Incomplete") = m_TimerIncomplete;
quickbuild.PushDebug("Activator Position").PushDebug(m_ActivatorPosition);
quickbuild.PushDebug<AMFStringValue>("Activator ID", "LWOOBJID") = std::to_string(m_ActivatorId);
quickbuild.PushDebug<AMFBoolValue>("Show Reset Effect") = m_ShowResetEffect;
quickbuild.PushDebug<AMFDoubleValue>("Taken") = m_Taken;
quickbuild.PushDebug<AMFDoubleValue>("Reset Time") = m_ResetTime;
quickbuild.PushDebug<AMFDoubleValue>("Complete Time") = m_CompleteTime;
quickbuild.PushDebug<AMFIntValue>("Take Imagination") = m_TakeImagination;
quickbuild.PushDebug<AMFBoolValue>("Interruptible") = m_Interruptible;
quickbuild.PushDebug<AMFBoolValue>("Self Activator") = m_SelfActivator;
auto& modules = quickbuild.PushDebug("Custom Modules");
for (const auto cmodule : m_CustomModules) modules.PushDebug<AMFIntValue>("Module") = cmodule;
quickbuild.PushDebug<AMFIntValue>("Activity Id") = m_ActivityId;
quickbuild.PushDebug<AMFIntValue>("Post Imagination Cost") = m_PostImaginationCost;
quickbuild.PushDebug<AMFDoubleValue>("Time Before Smash") = m_TimeBeforeSmash;
quickbuild.PushDebug<AMFDoubleValue>("Time Before Drain") = m_TimeBeforeDrain;
quickbuild.PushDebug<AMFIntValue>("Drained Imagination") = m_DrainedImagination;
quickbuild.PushDebug<AMFBoolValue>("Reposition Player") = m_RepositionPlayer;
quickbuild.PushDebug<AMFDoubleValue>("Soft Timer") = m_SoftTimer;
quickbuild.PushDebug<AMFStringValue>("Builder", "LWOOBJID") = std::to_string(m_Builder);
return true;
}

View File

@@ -0,0 +1,443 @@
#ifndef QUICKBUILDCOMPONENT_H
#define QUICKBUILDCOMPONENT_H
#include "BitStream.h"
#include <vector>
#include <string>
#include "dCommonVars.h"
#include "NiPoint3.h"
#include "ActivityComponent.h"
#include "ScriptedActivityComponent.h"
#include "Preconditions.h"
#include "Component.h"
#include "eReplicaComponentType.h"
#include "eQuickBuildState.h"
class Entity;
enum class eQuickBuildFailReason : uint32_t;
/**
* Component that handles entities that can be built into other entities using the quick build mechanic. Generally
* consists of an activator that shows a popup and then the actual entity that the bricks are built into. Note
* that quick builds are also scripted activities so this shared some logic with the ScriptedActivityComponent.
*/
class QuickBuildComponent final : public ActivityComponent {
public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::QUICK_BUILD;
QuickBuildComponent(Entity* const entity, const int32_t componentID);
void LoadDataFromTemplate() override;
void LoadConfigData() override;
~QuickBuildComponent() override;
void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override;
void Run(float deltaTime) override;
/**
* Handles a RequestUse from some entity, initiating the quick build
* @param originator the entity that triggered the event
*/
bool OnRequestUse(GameMessages::RequestUseEvent& event);
/**
* Spawns the activator that can be used to initiate the quickbuild
*/
void SpawnActivator();
/**
* Despawns the activiator that can be used to initiate the quickbuild
*/
void DespawnActivator();
/**
* Returns the entity that acts as the activator for this quickbuild
* @return the entity that acts as the activator for this quickbuild
*/
[[nodiscard]] Entity* GetActivator() const;
/**
* Returns the spawn position of the activator for this quickbuild, if any
* @return the spawn position of the activator for this quickbuild, if any
*/
[[nodiscard]] NiPoint3 GetActivatorPosition() const noexcept;
/**
* Sets the spawn position for the activator of this quickbuild
* @param value the spawn position to set for the activator
*/
void SetActivatorPosition(const NiPoint3& value) noexcept;
/**
* Returns the time it takes for the quickbuild to reset after being built
* @return the time it takes for the quickbuild to reset after being built
*/
[[nodiscard]] float GetResetTime() const noexcept;
/**
* Sets the time it takes for the quickbuild to reset after being built
* @param value the reset time to set
*/
void SetResetTime(const float value) noexcept;
/**
* Returns the time it takes to complete the quickbuild
* @return the time it takes to complete the quickbuild
*/
[[nodiscard]] float GetCompleteTime() const noexcept;
/**
* Sets the time it takes to complete the quickbuild
* @param value the completion time to set
*/
void SetCompleteTime(const float value) noexcept;
/**
* Returns the imagination that's taken when completing the quickbuild
* @return the imagination that's taken when completing the quickbuild
*/
[[nodiscard]] int32_t GetTakeImagination() const noexcept;
/**
* Sets the imagination that's taken when completing the quickbuild
* @param value the imagination deduction to set
*/
void SetTakeImagination(const int32_t value) noexcept;
/**
* Returns if the quickbuild can be interrupted, currently unused
* @return if the quickbuild can be interrupted
*/
[[nodiscard]] bool GetInterruptible() const noexcept;
/**
* Sets whether or not the quickbuild can be interrupted, currently unused
* @param value true if the quickbuild may be interrupted, false otherwise
*/
void SetInterruptible(const bool value) noexcept;
/**
* Returns whether or not this entity contains a built-in activator
* @return whether or not this entity contains a built-in activator
*/
[[nodiscard]] bool GetSelfActivator() const noexcept;
/**
* Sets whether or not this entity contains a built-in activator. If set to false this will spawn activators on
* each new quickbuild.
* @param value whether or not this entity contains a built-in activator
*/
void SetSelfActivator(const bool value) noexcept;
/**
* Currently unused
*/
[[nodiscard]] std::vector<int32_t> GetCustomModules() const noexcept;
/**
* Currently unused
*/
void SetCustomModules(const std::vector<int32_t>& value) noexcept;
/**
* Returns the activity ID for participating in this quickbuild
* @return the activity ID for participating in this quickbuild
*/
[[nodiscard]] int32_t GetActivityId() const noexcept;
/**
* Sets the activity ID for participating in this quickbuild
* @param value the activity ID to set
*/
void SetActivityId(const int32_t value) noexcept;
/**
* Currently unused
*/
[[nodiscard]] int32_t GetPostImaginationCost() const noexcept;
/**
* Currently unused
*/
void SetPostImaginationCost(const int32_t value) noexcept;
/**
* Returns the time it takes for an incomplete quickbuild to be smashed automatically
* @return the time it takes for an incomplete quickbuild to be smashed automatically
*/
[[nodiscard]] float GetTimeBeforeSmash() const noexcept;
/**
* Sets the time it takes for an incomplete quickbuild to be smashed automatically
* @param value the time to set
*/
void SetTimeBeforeSmash(const float value) noexcept;
/**
* Returns the current quickbuild state
* @return the current quickbuild state
*/
[[nodiscard]] eQuickBuildState GetState() const noexcept;
/**
* Returns the player that is currently building this quickbuild
* @return the player that is currently building this quickbuild
*/
[[nodiscard]] Entity* GetBuilder() const;
/**
* Returns whether or not the player is repositioned when initiating the quickbuild
* @return whether or not the player is repositioned when initiating the quickbuild
*/
[[nodiscard]] bool GetRepositionPlayer() const noexcept;
/**
* Sets whether or not the player is repositioned when initiating the quickbuild
* @param value whether or not the player is repositioned when initiating the quickbuild
*/
void SetRepositionPlayer(const bool value) noexcept;
/**
* Adds a callback that is called when the quickbuild is completed
* @param callback the callback to add
*/
void AddQuickBuildCompleteCallback(const std::function<void(Entity* user)>& callback);
/**
* Adds a callback when the quickbuild state is updated
* @param callback the callback to add
*/
void AddQuickBuildStateCallback(const std::function<void(eQuickBuildState state)>& callback);
/**
* Resets the quickbuild
* @param failed whether or not the player failed to complete the quickbuild, triggers an extra animation
*/
void ResetQuickBuild(const bool failed);
/**
* Cancels the quickbuild if it wasn't completed
* @param builder the player that's currently building
* @param failReason the reason the quickbuild was cancelled
* @param skipChecks whether or not to skip the check for the quickbuild not being completed
*/
void CancelQuickBuild(Entity* const builder, const eQuickBuildFailReason failReason, const bool skipChecks = false);
/**
* Cancels the quickbuilds the player is building, giving back the items they took. For a player leaving the world.
* @param player the player
*/
static void CancelBuildsBy(Entity& player);
void SetState(const eQuickBuildState state) {
if (m_State == state) return;
m_State = state;
m_StateDirty = true;
}
void SetShowResetEffect(const bool value) {
if (m_ShowResetEffect == value) return;
m_ShowResetEffect = value;
m_StateDirty = true;
}
void SetActivator(Entity* const activator) {
if (m_Activator == activator) return;
m_Activator = activator;
m_StateDirty = true;
}
void SetTimer(const float value) {
if (m_Timer == value) return;
m_Timer = value;
m_StateDirty = true;
}
void ModifyTimer(const float value) {
if (value == 0.0f) return;
m_Timer += value;
m_StateDirty = true;
}
void SetIncompleteTimer(const float value) {
if (m_TimerIncomplete == value) return;
m_TimerIncomplete = value;
m_StateDirty = true;
}
void ModifyIncompleteTimer(const float value) {
if (value == 0.0f) return;
m_TimerIncomplete += value;
m_StateDirty = true;
}
private:
bool OnGetObjectReportInfo(GameMessages::GetObjectReportInfo& reportInfo);
/**
* Whether or not the quickbuild state has been changed since we last serialized it.
*/
bool m_StateDirty = true;
/**
* The state the quickbuild is currently in
*/
eQuickBuildState m_State = eQuickBuildState::OPEN;
/**
* The time that has passed since initiating the quickbuild
*/
float m_Timer = 0;
/**
* The time that has passed before completing the quickbuild
*/
float m_TimerIncomplete = 0;
/**
* The position that the quickbuild activator is spawned at
*/
NiPoint3 m_ActivatorPosition = NiPoint3Constant::ZERO;
/**
* The entity that represents the quickbuild activator
*/
Entity* m_Activator = nullptr;
/**
* The ID of the entity that represents the quickbuild activator
*/
LWOOBJID m_ActivatorId = LWOOBJID_EMPTY;
/**
* Triggers the blinking that indicates that the quickbuild is resetting
*/
bool m_ShowResetEffect = false;
/**
* Currently unused
*/
float m_Taken = 0;
/**
* The callbacks that are called when the quickbuild is completed
*/
std::vector<std::function<void(Entity* user)>> m_QuickBuildCompleteCallbacks{};
/**
* The callbacks that are called when the quickbuild state is updated
*/
std::vector<std::function<void(eQuickBuildState state)>> m_QuickBuildStateCallbacks{};
/**
* The time it takes for the quickbuild to reset after being completed
*/
float m_ResetTime = 0;
/**
* The time it takes to complete the quickbuild
*/
float m_CompleteTime = 0;
/**
* The imagination that's deducted when completing the quickbuild
*/
int32_t m_TakeImagination = 0;
/**
* Currently unused
*/
bool m_Interruptible = false;
/**
* Whether or not this quickbuild entity also has an activator attached. If not a new one will be spawned
*/
bool m_SelfActivator = false;
/**
* Currently unused
*/
std::vector<int32_t> m_CustomModules{};
/**
* The activity ID that players partake in when doing this quickbuild
*/
int32_t m_ActivityId = 0;
// Whether the RebuildComponent row was found (the level's settings only apply over a row)
bool m_HasRow = false;
/**
* Currently unused
*/
int32_t m_PostImaginationCost = 0;
/**
* The time it takes for the quickbuild to reset when it's not completed yet
*/
float m_TimeBeforeSmash = 0;
/**
* The time it takes to drain imagination
*/
float m_TimeBeforeDrain = 0;
/**
* The amount of imagination that was drained when building this quickbuild
*/
int32_t m_DrainedImagination = 0;
/**
* Whether to reposition the player or not when building
*/
bool m_RepositionPlayer = true;
/**
* Currently unused
*/
int32_t m_SoftTimer = 0;
/**
* The ID of the entity that's currently building the quickbuild
*/
LWOOBJID m_Builder = LWOOBJID_EMPTY;
/**
* Preconditions to be met before being able to start the quickbuild
*/
PreconditionExpression* m_Precondition = nullptr;
/**
* The items the preconditions took from the builder when the build started, given back if it is cancelled
*/
std::vector<ItemCost> m_TakenItems;
/**
* The player the items in m_TakenItems were taken from
*/
LWOOBJID m_TakenItemsFrom = LWOOBJID_EMPTY;
/**
* Takes the item costs of the preconditions from the builder, as live did when a build started
* @param user the builder
*/
void TakeItemCosts(Entity& user);
/**
* Gives back the items TakeItemCosts took, as live did when a build was cancelled
*/
void RefundItemCosts();
/**
* Starts the quickbuild for a certain entity
* @param user the entity to start the quickbuild
*/
void StartQuickBuild(Entity* const user);
/**
* Completes the quickbuild for an entity, dropping loot and despawning the activator
* @param user the entity that completed the quickbuild
*/
void CompleteQuickBuild(Entity* const user);
};
#endif // QUICKBUILDCOMPONENT_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,299 @@
/**
* Thanks to Simon for his early research on the racing system.
*/
#pragma once
#include "BitStream.h"
#include "Entity.h"
#include "BaseRacingControlComponent.h"
#include "eReplicaComponentType.h"
#include <chrono>
/**
* Information for each player in the race
*/
struct RacingPlayerInfo {
/**
* The ID of the player
*/
LWOOBJID playerID;
/**
* The ID of the car the player is driving
*/
LWOOBJID vehicleID;
/**
* The index of this player in the list of players
*/
uint32_t playerIndex;
/**
* Whether the player has finished loading or not
*/
bool playerLoaded;
/**
* Scripted activity component score
*/
float data[10]{};
/**
* Point that the player will respawn at if they smash their car
*/
NiPoint3 respawnPosition;
/**
* Rotation that the player will respawn at if they smash their car
*/
NiQuaternion respawnRotation = QuatUtils::IDENTITY;
/**
* The index in the respawn point the player is now at
*/
uint32_t respawnIndex;
/**
* The number of laps the player has completed
*/
uint32_t lap;
/**
* Whether or not the player has finished the race
*/
uint32_t finished;
/**
* Unused
*/
uint16_t reachedPoints;
/**
* The fastest lap time of the player
*/
std::chrono::milliseconds bestLapTime;
/**
* The current lap time of the player
*/
std::chrono::high_resolution_clock::time_point lapTime;
/**
* The number of times this player smashed their car
*/
uint32_t smashedTimes = 0;
/**
* Whether or not the player should be smashed if the game is reloaded
*/
bool noSmashOnReload = false;
/**
* Whether or not this player has collected their rewards from completing the race
*/
bool collectedRewards = false;
/**
* Unused
*/
std::chrono::milliseconds raceTime;
/**
* The reset planes (path waypoints) the player is between, and how many planes they have driven back through
* since they last went forward through one, tracked the way the client tracks them
* (LWORacingControlComponent::HandlePlayerAddedToRace @ 00cba0c0 starts them at 0 and 1).
*/
uint32_t lastPlane = 0;
uint32_t upcomingPlane = 1;
uint32_t wrongWayCount = 0;
/**
* Seconds left until a player going the wrong way is put back on the track, negative when not counting down
*/
float wrongWayTime = -1.0f;
};
/**
* Component that's attached to a manager entity in each race zone that loads player vehicles, keep scores, etc.
*/
struct Path;
struct PathWaypoint;
class RacingControlComponent final : public BaseRacingControlComponent {
public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::RACING_CONTROL;
RacingControlComponent(Entity* parentEntity, const int32_t componentID);
void LoadConfigData() override;
~RacingControlComponent();
void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override;
void Run(float deltaTime) override;
/**
* Invoked when a player loads into the zone.
*/
void OnPlayerLoaded(Entity* player);
/**
* Moves the player's reset planes as they drive through them and puts them back on the track when they have been
* going the wrong way for as long as the client counts down.
*/
void UpdateWrongWay(RacingPlayerInfo& player, const Entity& vehicle, const Path& path, float deltaTime);
/**
* Moves the player's reset planes for the car being at position, like the client does each frame, and starts the
* wrong way countdown when they have driven back through a second plane.
*/
static void StepResetPlanes(RacingPlayerInfo& player, const std::vector<PathWaypoint>& waypoints, const NiPoint3& position);
/**
* Initalize the player's vehicle.
*
* @param player The player who's vehicle to initialize.
* @param initialLoad Is this the first time the player is loading in this race?
*/
void LoadPlayerVehicle(Entity* player, uint32_t positionNumber, bool initialLoad = false);
/**
* Invoked when the client says it has loaded in.
*/
void OnRacingClientReady(Entity* player);
/**
* Invoked when the client says it should be smashed.
*/
void OnRequestDie(Entity* player, const std::u16string& deathType = u"");
/**
* Invoked when the player has finished respawning.
*/
void OnRacingPlayerInfoResetFinished(Entity* player);
/**
* Invoked when the player responds to the GUI.
*/
void HandleMessageBoxResponse(Entity* player, int32_t button, const std::string& id);
/**
* Get the racing data from a player's LWOOBJID.
*/
RacingPlayerInfo* GetPlayerData(LWOOBJID playerID);
bool MsgConfigureRacingControl(const GameMessages::ConfigureRacingControl& msg);
private:
/**
* The players that are currently racing
*/
std::vector<RacingPlayerInfo> m_RacingPlayers;
/**
* The paths that are followed for the camera scenes
* Configurable in the ConfigureRacingControl msg with the key `Race_PathName`.
*/
std::u16string m_PathName;
/**
* The ID of the activity for participating in this race
* Configurable in the ConfigureRacingControl msg with the key `activityID`.
*/
uint32_t m_ActivityID;
/**
* The world the players return to when they finish the race
*/
uint32_t m_MainWorld;
/**
* The number of laps that are remaining for the winning player
*/
uint16_t m_RemainingLaps;
/**
* The ID of the player that's currently winning the race
*/
LWOOBJID m_LeadingPlayer;
/**
* The overall best lap from all the players
*/
float m_RaceBestLap;
/**
* The overall best time from all the players
*/
float m_RaceBestTime;
/**
* Whether or not the race has started
*/
bool m_Started;
/**
* The time left until the race will start
*/
float m_StartTimer;
/**
* The time left for loading the players
*/
float m_LoadTimer;
/**
* Whether or not all players have loaded
*/
bool m_Loaded;
/**
* The number of loaded players
*/
uint32_t m_LoadedPlayers;
/**
* All the players that are in the lobby, loaded or not
*/
std::vector<LWOOBJID> m_LobbyPlayers;
/**
* The number of players that have finished the race
*/
uint32_t m_Finished;
/**
* The time the race was started
*/
std::chrono::high_resolution_clock::time_point m_StartTime;
/**
* Timer for tracking how long a player was alone in this race
*/
float m_EmptyTimer;
bool m_SoloRacing;
/**
* Value for message box response to know if we are exiting the race via the activity dialogue
*/
const int32_t m_ActivityExitConfirm = 1;
bool m_AllPlayersReady = false;
/**
* @brief The number of laps in this race. Configurable in the ConfigureRacingControl msg
* with the key `Number_of_Laps`.
*
*/
int32_t m_NumberOfLaps{ 3 };
/**
* @brief The minimum number of players required to progress group achievements.
* Configurable with the ConfigureRacingControl msg with the key `Minimum_Players_for_Group_Achievements`.
*
*/
int32_t m_MinimumPlayersForGroupAchievements{ 2 };
};

View File

@@ -0,0 +1,15 @@
#ifndef __SCRIPTEDACTIVITYCOMPONENT__H__
#define __SCRIPTEDACTIVITYCOMPONENT__H__
#include "ActivityComponent.h"
#include "eReplicaComponentType.h"
class Entity;
class ScriptedActivityComponent final : public ActivityComponent {
public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::SCRIPTED_ACTIVITY;
ScriptedActivityComponent(Entity* parent, const int32_t componentID) : ActivityComponent(parent, componentID){};
};
#endif //!__SCRIPTEDACTIVITYCOMPONENT__H__

View File

@@ -0,0 +1,65 @@
#include "ShootingGalleryComponent.h"
#include "EntityManager.h"
#include "ScriptedActivityComponent.h"
ShootingGalleryComponent::ShootingGalleryComponent(Entity* parent, const int32_t componentID) : ActivityComponent(parent, componentID) {
}
void ShootingGalleryComponent::SetStaticParams(const StaticShootingGalleryParams& params) {
m_StaticParams = params;
}
void ShootingGalleryComponent::SetDynamicParams(const DynamicShootingGalleryParams& params) {
m_DynamicParams = params;
m_Dirty = true;
Game::entityManager->SerializeEntity(m_Parent);
}
void ShootingGalleryComponent::Serialize(RakNet::BitStream& outBitStream, bool isInitialUpdate) {
// Start ScriptedActivityComponent
outBitStream.Write<bool>(true);
if (m_CurrentPlayerID == LWOOBJID_EMPTY) {
outBitStream.Write<uint32_t>(0);
} else {
outBitStream.Write<uint32_t>(1);
outBitStream.Write<LWOOBJID>(m_CurrentPlayerID);
for (size_t i = 0; i < 10; i++) {
outBitStream.Write<float_t>(0.0f);
}
}
// End ScriptedActivityComponent
if (isInitialUpdate) {
outBitStream.Write<float_t>(m_StaticParams.cameraPosition.GetX());
outBitStream.Write<float_t>(m_StaticParams.cameraPosition.GetY());
outBitStream.Write<float_t>(m_StaticParams.cameraPosition.GetZ());
outBitStream.Write<float_t>(m_StaticParams.cameraLookatPosition.GetX());
outBitStream.Write<float_t>(m_StaticParams.cameraLookatPosition.GetY());
outBitStream.Write<float_t>(m_StaticParams.cameraLookatPosition.GetZ());
}
outBitStream.Write<bool>(m_Dirty || isInitialUpdate);
if (m_Dirty || isInitialUpdate) {
outBitStream.Write<double_t>(m_DynamicParams.cannonVelocity);
outBitStream.Write<double_t>(m_DynamicParams.cannonRefireRate);
outBitStream.Write<double_t>(m_DynamicParams.cannonMinDistance);
outBitStream.Write<float_t>(m_DynamicParams.cameraBarrelOffset.GetX());
outBitStream.Write<float_t>(m_DynamicParams.cameraBarrelOffset.GetY());
outBitStream.Write<float_t>(m_DynamicParams.cameraBarrelOffset.GetZ());
outBitStream.Write<float_t>(m_DynamicParams.cannonAngle);
outBitStream.Write<float_t>(m_DynamicParams.facing.GetX());
outBitStream.Write<float_t>(m_DynamicParams.facing.GetY());
outBitStream.Write<float_t>(m_DynamicParams.facing.GetZ());
outBitStream.Write<LWOOBJID>(m_CurrentPlayerID);
outBitStream.Write<float_t>(m_DynamicParams.cannonTimeout);
outBitStream.Write<float_t>(m_DynamicParams.cannonFOV);
if (!isInitialUpdate) m_Dirty = false;
}
}

View File

@@ -0,0 +1,138 @@
#pragma once
#include "dCommonVars.h"
#include "NiPoint3.h"
#include "Entity.h"
#include "Component.h"
#include "eReplicaComponentType.h"
#include "ActivityComponent.h"
/**
* Parameters for the shooting gallery that change during playtime
*/
struct DynamicShootingGalleryParams {
/**
* The distance from the camera to the barrel
*/
Vector3 cameraBarrelOffset;
/**
* The area the barrel is looking at
*/
Vector3 facing;
/**
* The velocity of the cannonballs
*/
double_t cannonVelocity;
/**
* The max firerate of the cannon
*/
double_t cannonRefireRate;
/**
* The min distance the cannonballs traverse
*/
double_t cannonMinDistance;
/**
* The angle at which the cannon is shooting
*/
float_t cannonAngle;
/**
* The timeout between cannon shots
*/
float_t cannonTimeout;
/**
* The FOV while in the canon
*/
float_t cannonFOV;
};
/**
* Parameters for the shooting gallery that don't change over time
*/
struct StaticShootingGalleryParams {
/**
* The position of the camera
*/
Vector3 cameraPosition;
/**
* The position that the camera is looking at
*/
Vector3 cameraLookatPosition;
};
/**
* A very ancient component that was used to guide shooting galleries, it's still kind of used but a lot of logic is
* also in the related scripts.
*/
class ShootingGalleryComponent final : public ActivityComponent {
public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::SHOOTING_GALLERY;
explicit ShootingGalleryComponent(Entity* parent, const int32_t componentID);
void Serialize(RakNet::BitStream& outBitStream, bool isInitialUpdate) override;
/**
* Returns the static params for the shooting gallery
* @return the static params for the shooting gallery
*/
const StaticShootingGalleryParams& GetStaticParams() const { return m_StaticParams; };
/**
* Sets the static parameters for the shooting gallery, see `StaticShootingGalleryParams`
* @param params the params to set
*/
void SetStaticParams(const StaticShootingGalleryParams& params);
/**
* Returns the dynamic params for the shooting gallery
* @return the dynamic params for the shooting gallery
*/
const DynamicShootingGalleryParams& GetDynamicParams() const { return m_DynamicParams; };
/**
* Sets the mutable params for the shooting gallery, see `DynamicShootingGalleryParams`
* @param params the params to set
*/
void SetDynamicParams(const DynamicShootingGalleryParams& params);
/**
* Sets the entity that's currently playing the shooting gallery
* @param playerID the entity to set
*/
void SetCurrentPlayerID(LWOOBJID playerID) { m_CurrentPlayerID = playerID; m_Dirty = true; };
/**
* Returns the player that's currently playing the shooting gallery
* @return the player that's currently playing the shooting gallery
*/
LWOOBJID GetCurrentPlayerID() const { return m_CurrentPlayerID; };
private:
/**
* The player that's currently playing the shooting gallery
*/
LWOOBJID m_CurrentPlayerID = LWOOBJID_EMPTY;
/**
* The static parameters for the shooting gallery, see `StaticShootingGalleryParams`
*/
StaticShootingGalleryParams m_StaticParams{};
/**
* The dynamic params for the shooting gallery, see `DynamicShootingGalleryParams`
*/
DynamicShootingGalleryParams m_DynamicParams{};
/**
* Whether or not the component should be serialized
*/
bool m_Dirty = false;
};