diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 7d9d3dfc4..10e5dddbe 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -30,6 +30,13 @@ #include "InventoryComponent.h" #include "Entity.h" #include "ObjectLoadState.h" +#include "DestroyableComponent.h" +#include "ProximityMonitorComponent.h" +#include "EffectsMessages.h" +#include "eKillType.h" +#include "EntityInfo.h" + +#include namespace { /** @@ -162,19 +169,21 @@ void MovementAIComponent::Run(const float deltaTime) { if (m_Paused) return; - if (m_WaitingAtWaypoint) { + if (m_ActionsRunning) { if (m_BaseCombatAI && m_BaseCombatAI->GetState() != AiState::idle) { // A fight ends the wait - m_WaitingAtWaypoint = false; + m_ActionsRunning = false; + m_WaypointPaused = false; } else { - m_WaypointDelay -= deltaTime; - if (m_WaypointDelay > 0.0f) return; - m_WaitingAtWaypoint = false; - if (RunWaypointCommands(m_DelayedWaypoint, m_DelayedCommand) && ContinuePath()) Game::entityManager->SerializeEntity(m_Parent); - return; + // The action delay counts down, then the actions after the one that paused run + if (m_ActionDelay > 0.0f) m_ActionDelay -= deltaTime; + if (m_ActionDelay <= 0.0f) RunWaypointActions(); } } + // Held at a waypoint with actions until ContinueWaypoints + if (m_WaypointPaused) return; + auto* const quickBuildComponent = m_Parent->GetComponent(); if (quickBuildComponent && quickBuildComponent->GetState() != eQuickBuildState::COMPLETED) return; @@ -212,6 +221,9 @@ void MovementAIComponent::Run(const float deltaTime) { } } + // A pathing speed of 0 holds it where it is + if (m_BaseSpeed <= 0.0f) return; + m_TimeTravelled += deltaTime; const auto approxPos = ApproximateLocation(); @@ -264,12 +276,7 @@ void MovementAIComponent::Run(const float deltaTime) { if (!m_BaseCombatAI || (idleNotResetting)) { // Check if there are more waypoints in the queue, if so set our next destination to the next waypoint const auto waypointNum = m_IsBounced ? m_CurrentPath.size() : m_CurrentPathStart + m_CurrentPathWaypointCount - m_CurrentPath.size() - 1; - if (!RunWaypointCommands(waypointNum)) { - // A delay: it stands here, then goes on with the waypoint's other commands - Game::entityManager->SerializeEntity(m_Parent); - return; - } - if (!ContinuePath()) return; + ArriveAtWaypoint(waypointNum); } else { Stop(); } @@ -279,11 +286,6 @@ void MovementAIComponent::Run(const float deltaTime) { } bool MovementAIComponent::ContinuePath() { - if (m_PathChangedByCommand) { - // SetPath already has it heading for the new path's start waypoint - m_PathChangedByCommand = false; - return true; - } if (m_CurrentPath.empty()) { if (m_Path) { if (m_Path->pathBehavior == PathBehavior::Loop) { @@ -386,6 +388,9 @@ bool MovementAIComponent::Warp(const NiPoint3& point) { void MovementAIComponent::Stop() { m_DestinationAfterKnockback.reset(); + // StopPathing ends the path following, and any wait at a waypoint with it + m_WaypointPaused = false; + m_MoveOrders++; if (AtFinalWaypoint()) return; SetPosition(ApproximateLocation()); @@ -419,7 +424,6 @@ void MovementAIComponent::PullToPoint(const NiPoint3& point) { void MovementAIComponent::SetPath(std::vector path) { if (path.empty()) return; m_CurrentPathStart = 0; - m_WaitingAtWaypoint = false; while (!m_CurrentPath.empty()) m_CurrentPath.pop(); std::for_each(path.rbegin(), path.rend() - 1, [this](const PathWaypoint& point) { this->m_CurrentPath.push(point); @@ -518,6 +522,9 @@ void MovementAIComponent::SetVelocity(const NiPoint3& value) { void MovementAIComponent::SetDestination(const NiPoint3 destination) { if (m_PullingToPoint) return; + // A new GoTo (or the next waypoint, or another path) replaces the wait at a waypoint + m_WaypointPaused = false; + m_MoveOrders++; if (IsKnockedBack()) { m_DestinationAfterKnockback = destination; return; @@ -593,89 +600,256 @@ void MovementAIComponent::SetMaxSpeed(const float value) { m_Acceleration = value / 5.0f; } -bool MovementAIComponent::RunWaypointCommands(const uint32_t waypointNum, const uint32_t firstCommand) { - if (firstCommand == 0) { - m_Parent->GetScript()->OnWaypointReached(m_Parent, waypointNum); - // A callback may add another - const auto callbacks = m_WaypointReachedCallbacks; - for (const auto& callback : callbacks) callback(waypointNum); +void MovementAIComponent::ArriveAtWaypoint(const uint32_t waypointNum) { + const auto* const path = m_Path; + const bool hasActions = path && waypointNum < path->pathWaypoints.size() && !path->pathWaypoints[waypointNum].actions.empty(); + m_ActionsRunning = false; + m_ActionPath = path; + m_ActionWaypoint = waypointNum; + m_Arriving = true; + // It holds here until ContinueWaypoints; a waypoint without actions never holds it + if (hasActions) SetVelocity(NiPoint3Constant::ZERO); + const auto orders = m_MoveOrders; + m_WaypointPaused = hasActions; + + // Arrived + m_Parent->GetScript()->OnWaypointReached(m_Parent, waypointNum); + // A callback may add another + const auto callbacks = m_WaypointReachedCallbacks; + for (const auto& callback : callbacks) callback(waypointNum); + + // The movement AI runs them unless the object's Lua AI does + if (hasActions && !m_ScriptRunsWaypointActions && m_WaypointPaused && orders == m_MoveOrders) { + m_NextAction = 0; + m_ActionDelay = 0.0f; + m_ActionsEndPath = path->pathBehavior == PathBehavior::Once && waypointNum + 1 == path->pathWaypoints.size(); + m_ActionsRunning = true; + RunWaypointActions(); + } + m_Arriving = false; + + // Nothing held it here and nothing gave it somewhere else to go: on to the next waypoint + if (!m_WaypointPaused && orders == m_MoveOrders) ContinuePath(); +} + +void MovementAIComponent::RunWaypointActions() { + if (!m_ActionsRunning || !m_ActionPath || m_ActionWaypoint >= m_ActionPath->pathWaypoints.size()) { + m_ActionsRunning = false; + return; + } + const auto& actions = m_ActionPath->pathWaypoints[m_ActionWaypoint].actions; + while (m_ActionsRunning && m_NextAction < actions.size()) { + const auto [name, value] = actions[m_NextAction++]; + if (!RunWaypointAction(name, value)) return; + } + if (!m_ActionsRunning) return; + m_ActionsRunning = false; + // The end of a once path has nowhere to go on to: no ContinueWaypoints, and unless an action sent it elsewhere it + // stops there + if (!m_ActionsEndPath) ContinueWaypoints(); + else if (m_WaypointPaused) Stop(); +} + +void MovementAIComponent::ContinueWaypoints() { + if (!m_WaypointPaused) return; + m_WaypointPaused = false; + // Sent while it arrives: it goes on once the arrival is done + if (m_Arriving) return; + if (ContinuePath()) Game::entityManager->SerializeEntity(m_Parent); +} + +namespace { + // The client's lists split at any of ",;:" + std::vector SplitActionValue(const std::string& value) { + std::vector parts; + size_t start = 0; + while (true) { + const auto end = value.find_first_of(",;:", start); + parts.push_back(value.substr(start, end == std::string::npos ? std::string::npos : end - start)); + if (end == std::string::npos) break; + start = end + 1; + } + return parts; } - if (!m_Path || waypointNum >= m_Path->pathWaypoints.size()) return true; - const auto& commands = m_Path->pathWaypoints[waypointNum].commands; - for (uint32_t i = firstCommand; i < commands.size(); i++) { - const auto& [command, data] = commands[i]; - LOG_DEBUG("%s %s %s", StringifiedEnum::ToString(command).data(), m_Path->pathName.c_str(), data.c_str()); - switch (command) { - case eWaypointCommandType::INVALID: break; - case eWaypointCommandType::BOUNCE: break; - case eWaypointCommandType::STOP: Pause(); break; - case eWaypointCommandType::GROUP_EMOTE: break; - case eWaypointCommandType::SET_VARIABLE: break; // Empty in the client - case eWaypointCommandType::CAST_SKILL: { - const auto skill = GeneralUtils::TryParse(data); - if (skill) { - auto* const skillComponent = m_Parent->GetComponent(); - if (skillComponent) skillComponent->CastSkill(skill.value()); + // _wtoi and _wtof: the number at the start of the text, 0 without one + int32_t ToInt(const std::string& value) { return std::atoi(value.c_str()); } + float ToFloat(const std::string& value) { return static_cast(std::atof(value.c_str())); } +} + +bool MovementAIComponent::RunWaypointAction(const std::string& name, const std::string& value) { + LOG_DEBUG("Waypoint action %s=%s on %llu", name.c_str(), value.c_str(), m_Parent->GetObjectID()); + const auto* const path = m_ActionPath; + const auto selfID = m_Parent->GetObjectID(); + + if (name == "bounce") { + if (path) { + const auto count = static_cast(path->pathWaypoints.size()); + // A path of one waypoint has nowhere to bounce to + if (count == 1) return false; + if (count > 1) { + // Two waypoints on: a loop path wraps round, a once path stops at its end; next to an end it is the + // waypoint on the other side + const auto current = m_ActionWaypoint; + auto target = current + 2; + if (path->pathBehavior == PathBehavior::Once) while (target >= count) target--; + if (path->pathBehavior != PathBehavior::Bounce && target >= count) target -= count; + if (current == count - 2) target = count - 1; + else if (current == count - 1) target = count - 2; + if (target < count) BounceTo(path->pathWaypoints[target].position, ToFloat(value)); } - break; - } - case eWaypointCommandType::EQUIP_INVENTORY: { - auto* const inventoryComponent = m_Parent->GetComponent(); - if (inventoryComponent) { - // items should always exist - auto* const item = inventoryComponent->GetInventory(eInventoryType::ITEMS)->FindItemBySlot(0); - if (item) inventoryComponent->EquipItem(item); - } - break; - } - case eWaypointCommandType::UNEQUIP_INVENTORY: { - auto* const inventoryComponent = m_Parent->GetComponent(); - if (inventoryComponent) { - // items should always exist - auto* const item = inventoryComponent->GetInventory(eInventoryType::ITEMS)->FindItemBySlot(0); - if (item) inventoryComponent->UnEquipItem(item); - } - break; - } - case eWaypointCommandType::DELAY: { - // The commands after it wait until the delay is over (LWOMovementAIComponent::ProcessDelayAction - // sets the delay and stops LWOMovementAIComponent::msgArrived at this command) - m_WaypointDelay = GeneralUtils::TryParse(data).value_or(0.0f); - m_DelayedWaypoint = waypointNum; - m_DelayedCommand = i + 1; - m_WaitingAtWaypoint = true; - SetVelocity(NiPoint3Constant::ZERO); - return false; - } - case eWaypointCommandType::EMOTE: { - // m_Delay = RenderComponent::GetAnimationTime(m_Parent, data); - // const auto emoteID = GeneralUtils::TryParse(data); - // if (emoteID) GameMessages::SendPlayEmote(m_Parent->GetObjectID(), emoteID.value(), LWOOBJID_EMPTY, UNASSIGNED_SYSTEM_ADDRESS); - break; - } - case eWaypointCommandType::TELEPORT: break; - case eWaypointCommandType::PATH_SPEED: m_BaseSpeed = GetBaseSpeed(m_Parent->GetLOT()) * GeneralUtils::TryParse(data).value_or(1.0f); break; - case eWaypointCommandType::REMOVE_NPC: break; - case eWaypointCommandType::CHANGE_WAYPOINT: { - // "path" or "path,waypoint", split at any of ",;:" (LWOMovementAIComponent::ProgessChangeWPAciton) - const auto pathEnd = data.find_first_of(",;:"); - uint32_t startWaypoint = 0; - if (pathEnd != std::string::npos) { - const auto startEnd = data.find_first_of(",;:", pathEnd + 1); - startWaypoint = GeneralUtils::TryParse(data.substr(pathEnd + 1, startEnd == std::string::npos ? startEnd : startEnd - pathEnd - 1)).value_or(0); - } - SetPath(data.substr(0, pathEnd), startWaypoint); - m_PathChangedByCommand = m_Path != nullptr; - break; - } - case eWaypointCommandType::DELETE_SELF: break; - case eWaypointCommandType::KILL_SELF: m_Parent->Smash(); break; - case eWaypointCommandType::SPAWN_OBJECT: break; - case eWaypointCommandType::PLAY_SOUND: break; } + m_ActionDelay = BOUNCE_ACTION_DELAY; + return false; } - return true; + if (name == "stop") { + // StopMoving + Stop(); + return false; + } + if (name == "groupemote") { + // "group,emoteID,LOT,LOT...": the group's objects (itself too) of one of the LOTs play the emote + const auto parts = SplitActionValue(value); + const auto emoteID = parts.size() > 1 ? ToInt(parts[1]) : 0; + for (auto* const member : Game::entityManager->GetEntitiesInGroup(parts[0])) { + for (size_t i = 2; i < parts.size(); i++) { + if (member->GetLOT() != ToInt(parts[i])) continue; + GameMessages::PlayEmote emote; + emote.target = member->GetObjectID(); + emote.emoteID = emoteID; + emote.Send(UNASSIGNED_SYSTEM_ADDRESS); + } + } + return true; + } + if (name == "setvar") return true; // Empty in the client + if (name == "castskill") { + if (!value.empty()) { + auto* const skillComponent = m_Parent->GetComponent(); + if (skillComponent) skillComponent->CastSkill(ToInt(value)); + } + return true; + } + if (name == "eqInvent" || name == "unInvent") { + auto* const inventoryComponent = m_Parent->GetComponent(); + if (inventoryComponent) { + // GetInventoryItemInSlot: the value is not read + auto* const item = inventoryComponent->GetInventory(eInventoryType::ITEMS)->FindItemBySlot(0); + if (item && name == "eqInvent") inventoryComponent->EquipItem(item); + else if (item) inventoryComponent->UnEquipItem(item); + } + return true; + } + if (name == "delay") { + m_ActionDelay = ToFloat(value); + return false; + } + if (name == "emote" || name == "femote") { + // It waits for the animation of that name, and plays the emote of that number + m_ActionDelay = RenderComponent::GetAnimationTime(m_Parent, GeneralUtils::ASCIIToUTF16(value)); + GameMessages::PlayEmote emote; + emote.target = selfID; + emote.emoteID = ToInt(value); + emote.Send(UNASSIGNED_SYSTEM_ADDRESS); + return false; + } + if (name == "teleport") { + const auto parts = SplitActionValue(value); + if (parts.size() >= 3) { + SetPosition({ ToFloat(parts[0]), ToFloat(parts[1]), ToFloat(parts[2]) }); + m_SourcePosition = m_Parent->GetPosition(); + Game::entityManager->SerializeEntity(m_Parent); + } + return true; + } + if (name == "pathspeed") { + // SetPathingSpeed: below 0 is 0 + m_BaseSpeed = GetBaseSpeed(m_Parent->GetLOT()) * std::max(ToFloat(value), 0.0f); + return true; + } + if (name == "removeNPC") { + // The objects of the faction in its KillOBJS proximity go a second later + const auto* const proximity = m_Parent->GetComponent(); + if (!proximity) return true; + const auto faction = ToInt(value); + for (const auto objectID : proximity->GetProximityObjects(KILL_OBJECTS_PROXIMITY)) { + const auto* const other = Game::entityManager->GetEntity(objectID); + const auto* const destroyable = other ? other->GetComponent() : nullptr; + if (!destroyable || !destroyable->HasFaction(faction)) continue; + m_Parent->AddCallbackTimer(DELETE_ACTION_DELAY, [objectID]() { + auto* const target = Game::entityManager->GetEntity(objectID); + if (target) Game::entityManager->DestroyEntity(target); + }); + } + return true; + } + if (name == "changeWP") { + // "path" or "path,waypoint" (LWOMovementAIComponent::ProgessChangeWPAciton) + const auto parts = SplitActionValue(value); + SetPath(parts[0], parts.size() > 1 ? static_cast(std::max(ToInt(parts[1]), 0)) : 0); + return true; + } + if (name == "DeleteSelf" || name == "removeself") { + m_Parent->AddCallbackTimer(DELETE_ACTION_DELAY, [selfID]() { + auto* const self = Game::entityManager->GetEntity(selfID); + if (self) Game::entityManager->DestroyEntity(self); + }); + return true; + } + if (name == "killself") { + m_Parent->Smash(selfID, eKillType::SILENT); + return true; + } + if (name == "spawnOBJ") { + // The LOT where it stands, owned by it, with its pathset and SpawnedVar; then it dies + EntityInfo info{}; + info.lot = ToInt(value); + info.pos = m_Parent->GetPosition(); + info.rot = m_Parent->GetRotation(); + info.spawnerID = selfID; + const auto pathset = m_Parent->GetVar(u"pathset"); + if (!pathset.empty()) { + info.settings.Insert(u"pathset", pathset); + info.settings.Insert(u"SpawnedVar", m_Parent->GetVar(u"SpawnedVar")); + } + auto* const spawned = Game::entityManager->CreateEntity(info, nullptr, m_Parent); + if (spawned) Game::entityManager->ConstructEntity(spawned); + m_Parent->Smash(selfID, eKillType::SILENT); + return true; + } + if (name == "playSound") { + GameMessages::PlayNDAudioEmitter(selfID, value).Send(UNASSIGNED_SYSTEM_ADDRESS); + return true; + } + // Any other name holds it until the next frame + return false; +} + +void MovementAIComponent::BounceTo(const NiPoint3& destination, const float speed) { + auto gravity = Game::zoneManager ? Game::zoneManager->GetWorldConfig().peGravityValue : 0.0f; + if (gravity <= 0.0f) gravity = DEFAULT_GRAVITY; + const auto start = m_Parent->GetPosition(); + // Up at the bounce speed, falling onto the point + const float up = std::max(speed, 0.0f); + const float drop = start.y - destination.y; + const float root = up * up + 2.0f * gravity * drop; + if (root < 0.0f || up + std::sqrt(root) <= 0.0f) { + SetPosition(destination); + return; + } + const float time = (up + std::sqrt(root)) / gravity; + const NiPoint3 vector{ (destination.x - start.x) / time, up, (destination.z - start.z) / time }; + + // The path is still followed after the landing + auto path = m_CurrentPath; + const auto count = m_CurrentPathWaypointCount; + const auto pathStart = m_CurrentPathStart; + const auto paused = m_WaypointPaused; + Knockback(vector); + m_CurrentPath = std::move(path); + m_CurrentPathWaypointCount = count; + m_CurrentPathStart = pathStart; + m_WaypointPaused = paused; } bool MovementAIComponent::OnGetObjectReportInfo(GameMessages::GetObjectReportInfo& reportInfo) { diff --git a/dGame/dComponents/MovementAIComponent.h b/dGame/dComponents/MovementAIComponent.h index 100ed83d7..cbe423df5 100644 --- a/dGame/dComponents/MovementAIComponent.h +++ b/dGame/dComponents/MovementAIComponent.h @@ -205,6 +205,35 @@ public: */ void AddWaypointReachedCallback(const std::function& callback) { m_WaypointReachedCallbacks.push_back(callback); } + /** + * The ContinueWaypoints game message: a waypoint with any actions holds the object there until this (from anyone; + * a second one does nothing) + */ + void ContinueWaypoints(); + + // Waiting at a waypoint with actions for ContinueWaypoints + bool IsWaitingAtWaypoint() const { return m_WaypointPaused; } + + /** + * Runs one waypoint action as the client's LWOMovementAIComponent does (ArrivedAtWaypointLogic), for the waypoint + * last reached + * @return true to go on with the next action (CONTINUE), false to wait for the action delay first (PAUSE) + */ + bool RunWaypointAction(const std::string& name, const std::string& value); + + // The object's script runs the waypoint actions and sends ContinueWaypoints itself (the Lua AI) + void SetScriptRunsWaypointActions(const bool value) { m_ScriptRunsWaypointActions = value; } + + // What a waypoint's actions wait for before the next one runs + float GetWaypointActionDelay() const { return m_ActionDelay; } + + // The bounce action's wait (LWOMovementAIComponent::ProcessBounceAction) + static constexpr float BOUNCE_ACTION_DELAY = 5.0f; + // The delete actions delete the object this long after (LWODeleteObject posted with 1 s) + static constexpr float DELETE_ACTION_DELAY = 1.0f; + // The proximity the removeNPC action deletes its faction's objects from + static constexpr const char* KILL_OBJECTS_PROXIMITY = "KillOBJS"; + /** * Renders the entity stationary */ @@ -289,11 +318,15 @@ private: */ float GetGroundHeight(const NiPoint3& point) const; - /** - * Runs the commands on a waypoint if a path exists, from one of them on - * @return false when a delay holds the object at the waypoint; the commands after it run once it is over - */ - bool RunWaypointCommands(uint32_t waypointNum, uint32_t firstCommand = 0); + // The object reached a waypoint of its path: Arrived for its scripts, then its actions (msgArrived) + void ArriveAtWaypoint(uint32_t waypointNum); + + // Runs the reached waypoint's actions from the next one on until one pauses; once all have run, ContinueWaypoints + // (LWOMovementAIComponent::RunWaypointActions) + void RunWaypointActions(); + + // The bounce action: thrown in an arc to the point + void BounceTo(const NiPoint3& destination, float speed); /** * Sets the current position of the entity @@ -414,19 +447,28 @@ private: // The level path's waypoint the walked waypoints start at uint32_t m_CurrentPathStart{ 0 }; - // A waypoint's delay command: the time left, and the waypoint and command to go on with - bool m_WaitingAtWaypoint{ false }; - float m_WaypointDelay{ 0.0f }; - uint32_t m_DelayedWaypoint{ 0 }; - uint32_t m_DelayedCommand{ 0 }; + // Held at a waypoint with actions until ContinueWaypoints + bool m_WaypointPaused{ false }; + // Inside ArriveAtWaypoint: a ContinueWaypoints there goes on once the arrival is done + bool m_Arriving{ false }; + // Counts the movement orders (SetDestination, Stop): an arrival whose hooks or actions gave another does not go on + uint32_t m_MoveOrders{ 0 }; + + // The waypoint actions being run: the path and waypoint, the next action, and the delay before it + bool m_ActionsRunning{ false }; + const Path* m_ActionPath{ nullptr }; + uint32_t m_ActionWaypoint{ 0 }; + uint32_t m_NextAction{ 0 }; + float m_ActionDelay{ 0.0f }; + // The last waypoint of a once path: its actions do not send ContinueWaypoints + bool m_ActionsEndPath{ false }; + + bool m_ScriptRunsWaypointActions{ false }; // Where to after a waypoint's commands: the next waypoint, the path again, or nowhere. False when nothing is // left to serialize bool ContinuePath(); - // A waypoint's changeWP put the object on another path: it heads for that path's start waypoint - bool m_PathChangedByCommand{ false }; - std::vector> m_WaypointReachedCallbacks; LWOOBJID m_FollowedTarget{ LWOOBJID_EMPTY }; diff --git a/tests/dGameTests/dComponentsTests/MovementAIPathTests.cpp b/tests/dGameTests/dComponentsTests/MovementAIPathTests.cpp index ea88422c7..ca6d72322 100644 --- a/tests/dGameTests/dComponentsTests/MovementAIPathTests.cpp +++ b/tests/dGameTests/dComponentsTests/MovementAIPathTests.cpp @@ -21,6 +21,8 @@ protected: CDClientDatabase::Connect(":memory:"); CDClientDatabase::ExecuteDML("CREATE TABLE ComponentsRegistry (id INTEGER, component_type INTEGER, component_id INTEGER);"); } + // No rows: the default gravity (the bounce action's arc) + CDClientDatabase::ExecuteDML("CREATE TABLE IF NOT EXISTS WorldConfig (pegravityvalue REAL);"); CDClientManager::GetEntriesMutable().insert_or_assign(static_cast(info.lot), 0); } @@ -90,7 +92,7 @@ TEST_F(MovementAIPathTest, StartWaypointPastTheEndWalksTheWholePath) { // Avant Gardens Survival sends its enemies on with "RaceTrack_01,6": the other path, from its waypoint 6 TEST_F(MovementAIPathTest, ChangeWaypointCommandGoesToTheNamedWaypointOfTheOtherPath) { auto first = MakePath("FirstPath", 2, PathBehavior::Once); - first.pathWaypoints[1].commands.push_back({ eWaypointCommandType::CHANGE_WAYPOINT, "SecondPath,2" }); + first.pathWaypoints[1].actions.push_back({ "changeWP", "SecondPath,2" }); AddPath(first); auto second = MakePath("SecondPath", 4, PathBehavior::Once); for (auto& waypoint : second.pathWaypoints) waypoint.position.z = 50.0f; @@ -110,7 +112,7 @@ TEST_F(MovementAIPathTest, ChangeWaypointCommandGoesToTheNamedWaypointOfTheOther TEST_F(MovementAIPathTest, ChangeWaypointCommandWithoutAWaypointStartsAtTheFirst) { auto first = MakePath("LonePath", 1, PathBehavior::Once); - first.pathWaypoints[0].commands.push_back({ eWaypointCommandType::CHANGE_WAYPOINT, "OtherPath" }); + first.pathWaypoints[0].actions.push_back({ "changeWP", "OtherPath" }); AddPath(first); AddPath(MakePath("OtherPath", 3, PathBehavior::Once)); @@ -137,12 +139,12 @@ TEST_F(MovementAIPathTest, BouncePathReachesEachEndOnce) { for (size_t i = 0; i < expectedX.size(); i++) EXPECT_NEAR(reachedX[i], expectedX[i], 0.01f) << i; } -// LWOMovementAIComponent::ProcessDelayAction: the object stands at the waypoint for the delay, and the commands after +// LWOMovementAIComponent::ProcessDelayAction: the object stands at the waypoint for the delay, and the actions after // the delay wait for it TEST_F(MovementAIPathTest, DelayCommandHoldsTheObjectAtTheWaypoint) { auto path = MakePath("DelayPath", 2, PathBehavior::Once); - path.pathWaypoints[0].commands.push_back({ eWaypointCommandType::DELAY, "5" }); - path.pathWaypoints[0].commands.push_back({ eWaypointCommandType::CHANGE_WAYPOINT, "AfterDelay,1" }); + path.pathWaypoints[0].actions.push_back({ "delay", "5" }); + path.pathWaypoints[0].actions.push_back({ "changeWP", "AfterDelay,1" }); AddPath(path); auto after = MakePath("AfterDelay", 2, PathBehavior::Once); for (auto& waypoint : after.pathWaypoints) waypoint.position.z = 50.0f; @@ -169,7 +171,7 @@ TEST_F(MovementAIPathTest, DelayCommandHoldsTheObjectAtTheWaypoint) { TEST_F(MovementAIPathTest, DelayAtEachEndOfALoopPath) { auto path = MakePath("DelayLoop", 2, PathBehavior::Loop); - path.pathWaypoints[1].commands.push_back({ eWaypointCommandType::DELAY, "2" }); + path.pathWaypoints[1].actions.push_back({ "delay", "2" }); AddPath(path); Entity entity(306, info); @@ -180,3 +182,162 @@ TEST_F(MovementAIPathTest, DelayAtEachEndOfALoopPath) { reached.resize(4); EXPECT_EQ(reached, (std::vector{ 0, 1, 0, 1 })); } + +// A waypoint with any actions holds it until ContinueWaypoints; here its script runs them (the Lua AI) +TEST_F(MovementAIPathTest, WaypointWithActionsWaitsForContinueWaypoints) { + auto path = MakePath("HoldPath", 3, PathBehavior::Once); + path.pathWaypoints[1].actions.push_back({ "setvar", "" }); + AddPath(path); + Entity entity(307, info); + auto* const movement = Walker(entity); + movement->SetScriptRunsWaypointActions(true); + movement->SetPath("HoldPath"); + Walk(*movement, 30.0f); + ASSERT_EQ(reached, (std::vector{ 0, 1 })); + EXPECT_TRUE(movement->IsWaitingAtWaypoint()); + EXPECT_NEAR(entity.GetPosition().x, 20.0f, 0.01f); + + movement->ContinueWaypoints(); + // A second one does nothing + movement->ContinueWaypoints(); + Walk(*movement, 30.0f); + EXPECT_EQ(reached, (std::vector{ 0, 1, 2 })); + EXPECT_NEAR(entity.GetPosition().x, 30.0f, 0.01f); +} + +// The movement AI runs them itself and sends ContinueWaypoints once all of them continue +TEST_F(MovementAIPathTest, ContinuingActionsGoOnAtOnce) { + auto path = MakePath("ContinuePath", 3, PathBehavior::Once); + path.pathWaypoints[1].actions.push_back({ "setvar", "x" }); + path.pathWaypoints[1].actions.push_back({ "castskill", "" }); + AddPath(path); + Entity entity(308, info); + auto* const movement = Walker(entity); + movement->SetPath("ContinuePath"); + Walk(*movement, 30.0f); + EXPECT_EQ(reached, (std::vector{ 0, 1, 2 })); + EXPECT_FALSE(movement->IsWaitingAtWaypoint()); +} + +// A name the client does not know pauses the list until the next frame +TEST_F(MovementAIPathTest, UnknownActionPausesOneFrame) { + Entity entity(309, info); + auto* const movement = Walker(entity); + EXPECT_FALSE(movement->RunWaypointAction("notAnAction", "1")); + EXPECT_FLOAT_EQ(movement->GetWaypointActionDelay(), 0.0f); +} + +TEST_F(MovementAIPathTest, ActionsThatContinue) { + Entity entity(310, info); + auto* const movement = Walker(entity); + for (const auto* const name : { "setvar", "castskill", "eqInvent", "unInvent", "pathspeed", "removeNPC", "changeWP", "playSound", "groupemote" }) { + EXPECT_TRUE(movement->RunWaypointAction(name, "")) << name; + } +} + +TEST_F(MovementAIPathTest, DelayAndEmoteActionsPause) { + Entity entity(311, info); + auto* const movement = Walker(entity); + EXPECT_FALSE(movement->RunWaypointAction("delay", "2.5")); + EXPECT_FLOAT_EQ(movement->GetWaypointActionDelay(), 2.5f); + // The emote's wait is its animation's time (none without a render component) + EXPECT_FALSE(movement->RunWaypointAction("emote", "5")); + EXPECT_FLOAT_EQ(movement->GetWaypointActionDelay(), 0.0f); + EXPECT_FALSE(movement->RunWaypointAction("femote", "5")); +} + +// stop: StopMoving, and the path is not followed on +TEST_F(MovementAIPathTest, StopActionLeavesItStanding) { + auto path = MakePath("StopPath", 3, PathBehavior::Once); + path.pathWaypoints[1].actions.push_back({ "stop", "" }); + AddPath(path); + Entity entity(312, info); + auto* const movement = Walker(entity); + movement->SetPath("StopPath"); + Walk(*movement, 30.0f); + EXPECT_EQ(reached, (std::vector{ 0, 1 })); + EXPECT_TRUE(movement->AtFinalWaypoint()); + EXPECT_NEAR(entity.GetPosition().x, 20.0f, 0.01f); +} + +TEST_F(MovementAIPathTest, TeleportActionMovesIt) { + Entity entity(313, info); + auto* const movement = Walker(entity); + EXPECT_TRUE(movement->RunWaypointAction("teleport", "1,2;3")); + EXPECT_EQ(entity.GetPosition(), (NiPoint3{ 1.0f, 2.0f, 3.0f })); +} + +// SetPathingSpeed: below 0 is 0, and at 0 it stands +TEST_F(MovementAIPathTest, PathSpeedActionBelowZeroStandsIt) { + auto path = MakePath("SlowPath", 3, PathBehavior::Once); + path.pathWaypoints[0].actions.push_back({ "pathspeed", "-2" }); + AddPath(path); + Entity entity(314, info); + auto* const movement = Walker(entity); + movement->SetPath("SlowPath"); + Walk(*movement, 30.0f); + EXPECT_EQ(reached, (std::vector{ 0 })); + EXPECT_NEAR(entity.GetPosition().x, 10.0f, 0.01f); +} + +TEST_F(MovementAIPathTest, PathSpeedActionScalesTheSpeed) { + auto path = MakePath("FastPath", 2, PathBehavior::Once); + path.pathWaypoints[0].actions.push_back({ "pathspeed", "2" }); + AddPath(path); + Entity slowEntity(315, info); + auto* const slow = Walker(slowEntity); + slow->SetPath("FastPath"); + while (reached.empty()) slow->Run(0.05f); + Walk(*slow, 0.5f); + const auto fastX = slowEntity.GetPosition().x; + + AddPath(MakePath("PlainPath", 2, PathBehavior::Once)); + reached.clear(); + Entity plainEntity(316, info); + auto* const plain = Walker(plainEntity); + plain->SetPath("PlainPath"); + while (reached.empty()) plain->Run(0.05f); + Walk(*plain, 0.5f); + EXPECT_GT(fastX - 10.0f, plainEntity.GetPosition().x - 10.0f); +} + +// bounce: a path of one waypoint pauses without a wait; otherwise it is thrown two waypoints on and waits 5 s +TEST_F(MovementAIPathTest, BounceActionThrowsItTwoWaypointsOn) { + auto lone = MakePath("LoneBounce", 1, PathBehavior::Once); + lone.pathWaypoints[0].actions.push_back({ "bounce", "10" }); + AddPath(lone); + Entity loneEntity(317, info); + auto* const loneWalker = Walker(loneEntity); + loneWalker->SetPath("LoneBounce"); + while (reached.empty()) loneWalker->Run(0.05f); + EXPECT_FLOAT_EQ(loneWalker->GetWaypointActionDelay(), 0.0f); + + auto path = MakePath("BounceAction", 4, PathBehavior::Loop); + path.pathWaypoints[0].actions.push_back({ "bounce", "10" }); + AddPath(path); + reached.clear(); + Entity entity(318, info); + auto* const movement = Walker(entity); + movement->SetPath("BounceAction"); + while (reached.empty()) movement->Run(0.05f); + EXPECT_FLOAT_EQ(movement->GetWaypointActionDelay(), MovementAIComponent::BOUNCE_ACTION_DELAY); + EXPECT_TRUE(movement->IsKnockedBack()); + while (movement->IsKnockedBack()) movement->Run(0.05f); + // Waypoint 2 + EXPECT_NEAR(entity.GetPosition().x, 30.0f, 1.0f); +} + +// The last waypoint of a once path: its actions do not send it on +TEST_F(MovementAIPathTest, OncePathEndActionsStopIt) { + auto path = MakePath("EndPath", 2, PathBehavior::Once); + path.pathWaypoints[1].actions.push_back({ "delay", "1" }); + AddPath(path); + Entity entity(319, info); + auto* const movement = Walker(entity); + movement->SetPath("EndPath"); + Walk(*movement, 30.0f); + EXPECT_EQ(reached, (std::vector{ 0, 1 })); + EXPECT_TRUE(movement->AtFinalWaypoint()); + EXPECT_FALSE(movement->IsWaitingAtWaypoint()); +} +