#include "MovementAIComponent.h" #include "CDClientManager.h" #include "CDMovementAIComponentTable.h" #include #include #include "ControllablePhysicsComponent.h" #include "BaseCombatAIComponent.h" #include "dpCommon.h" #include "dpWorld.h" #include "EntityManager.h" #include "SimplePhysicsComponent.h" #include "CDClientManager.h" #include "Game.h" #include "dZoneManager.h" #include "Zone.h" #include "CDComponentsRegistryTable.h" #include "QuickBuildComponent.h" #include "CDPhysicsComponentTable.h" #include "Amf3.h" #include "dNavMesh.h" #include "eWaypointCommandType.h" #include "StringifiedEnum.h" #include "SkillComponent.h" #include "GeneralUtils.h" #include "RenderComponent.h" #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 { /** * Cache of all lots and their respective speeds */ std::map m_PhysicsSpeedCache; // Half the height of a character: how far a short knockback may drop onto the ground (the client uses its // character's height / 2) constexpr float KNOCKBACK_MAX_DROP = 2.0f; // The client's gravity when WorldConfig has none constexpr float DEFAULT_GRAVITY = 9.8f; } MovementAIComponent::MovementAIComponent(Entity* parent, const int32_t componentID, MovementAIInfo info) : Component(parent, componentID) { m_Info = info; m_AtFinalWaypoint = true; m_BaseCombatAI = m_Parent->GetComponent(); m_BaseSpeed = GetBaseSpeed(m_Parent->GetLOT()); m_NextWaypoint = m_Parent->GetPosition(); m_Acceleration = 0.4f; m_PullingToPoint = false; m_PullPoint = NiPoint3Constant::ZERO; m_HaltDistance = 0; m_TimeToTravel = 0; m_TimeTravelled = 0; m_CurrentSpeed = 0; m_MaxSpeed = 0; m_LockRotation = false; m_Path = nullptr; m_SourcePosition = m_Parent->GetPosition(); m_Paused = false; m_SavedVelocity = NiPoint3Constant::ZERO; m_IsBounced = false; RegisterMsg(&MovementAIComponent::OnGetObjectReportInfo); } // The level config: the attached path // The MovementAIComponent row (an object made without one gets its info from the constructor) void MovementAIComponent::LoadDataFromTemplate() { if (m_ComponentID <= 0) return; const auto componentID = m_ComponentID; const auto moveAIComp = CDClientManager::GetTable()->Query([componentID](const CDMovementAIComponent& entry) { return (entry.id == componentID); }); if (moveAIComp.empty()) return; m_Info.movementType = moveAIComp[0].MovementType; m_Info.wanderRadius = moveAIComp[0].WanderRadius; m_Info.wanderSpeed = moveAIComp[0].WanderSpeed; m_Info.wanderChance = moveAIComp[0].WanderChance; m_Info.wanderDelayMin = moveAIComp[0].WanderDelayMin; m_Info.wanderDelayMax = moveAIComp[0].WanderDelayMax; } void MovementAIComponent::LoadConfigData() { // The level's wanderRadius over the row's, unless usewanderdb if (m_ComponentID > 0 && !m_Parent->GetVar(u"usewanderdb")) { const auto wanderOverride = m_Parent->GetVarAs(u"wanderRadius"); if (wanderOverride != 0.0f) m_Info.wanderRadius = wanderOverride; } //Try and fix the insane values: if (m_Info.wanderRadius > 5.0f) m_Info.wanderRadius *= 0.5f; if (m_Info.wanderRadius > 8.0f) m_Info.wanderRadius = 8.0f; if (m_Info.wanderSpeed > 0.5f) m_Info.wanderSpeed *= 0.5f; // A movement AI the object has only because it is scripted or has a path (id 0) follows only a movement path: a // moving platform's path belongs to its moving platform const auto pathName = m_Parent->GetVarAsString(u"attached_path"); if (m_ComponentID == 0) { if (pathName.empty()) return; const auto* const path = Game::zoneManager->GetZone()->GetPath(pathName); if (!path || path->pathType != PathType::Movement) return; } // attached_path_start is the waypoint it walks to first (LWOMovementAIComponent::LoadConfigData) SetPath(pathName, m_Parent->GetVarAs(u"attached_path_start")); } void MovementAIComponent::SetPath(const std::string pathName, const uint32_t startWaypoint) { const auto* const path = Game::zoneManager->GetZone()->GetPath(pathName); if (!pathName.empty()) LOG("WARNING: %s path %s", path ? "Found" : "Failed to find", pathName.c_str()); SetPath(path, startWaypoint); } void MovementAIComponent::SetPath(const Path* const path, const uint32_t startWaypoint) { m_Path = path; if (!m_Path) return; SetMaxSpeed(1); SetCurrentSpeed(m_BaseSpeed); m_IsBounced = false; const auto& waypoints = m_Path->pathWaypoints; const uint32_t first = startWaypoint < waypoints.size() ? startWaypoint : 0; SetPath(std::vector(waypoints.begin() + first, waypoints.end())); m_CurrentPathStart = first; } void MovementAIComponent::Pause() { if (m_Paused) return; m_Paused = true; // A stun doesn't stop a knockback mid air; the entity stays put once it lands if (IsKnockedBack()) { m_SavedVelocity = NiPoint3Constant::ZERO; return; } SetPosition(ApproximateLocation()); m_SavedVelocity = GetVelocity(); SetVelocity(NiPoint3Constant::ZERO); Game::entityManager->SerializeEntity(m_Parent); } void MovementAIComponent::Resume() { if (!m_Paused) return; m_Paused = false; if (IsKnockedBack()) return; SetVelocity(m_SavedVelocity); m_SavedVelocity = NiPoint3Constant::ZERO; SetRotation(QuatUtils::LookAt(m_Parent->GetPosition(), m_NextWaypoint)); Game::entityManager->SerializeEntity(m_Parent); } void MovementAIComponent::Run(const float deltaTime) { if (IsKnockedBack()) { UpdateKnockback(deltaTime); return; } if (m_Paused) return; if (m_ActionsRunning) { if (m_BaseCombatAI && m_BaseCombatAI->GetState() != AiState::idle) { // A fight ends the wait m_ActionsRunning = false; m_WaypointPaused = false; } else { // 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; if (m_PullingToPoint) { const auto source = GetCurrentWaypoint(); const auto speed = deltaTime * 2.5f; NiPoint3 velocity = (m_PullPoint - source) * speed; SetPosition(source + velocity); if (Vector3::DistanceSquared(m_Parent->GetPosition(), m_PullPoint) < std::pow(2, 2)) { m_PullingToPoint = false; } return; } // A follow with a radius halts short of the target: it walks after it again once it is out of the radius, or the // follow ends there without keepFollowing if (m_FollowedTarget != LWOOBJID_EMPTY && m_FollowRadius > 0.0f && AtFinalWaypoint()) { if (m_KeepFollowing) ResumeFollow(); else m_FollowedTarget = LWOOBJID_EMPTY; } // Are we done? if (AtFinalWaypoint()) return; if (m_HaltDistance > 0) { // Prevent us from hugging the target if (Vector3::DistanceSquared(ApproximateLocation(), GetDestination()) < std::pow(m_HaltDistance, 2)) { Stop(); return; } } // A pathing speed of 0 holds it where it is if (m_BaseSpeed <= 0.0f) return; m_TimeTravelled += deltaTime; const auto approxPos = ApproximateLocation(); SetPosition(approxPos); // Set the AIs new home based on where our current waypoint is IF wehave a path, we're idle, not out of combat (grace period if you left the radius), // and we're not tethering to home, that way we can return to this // when resuming the pathing after losing aggro while moving the aggro hitbox with us const bool idleNotResetting = m_Path && m_BaseCombatAI && m_BaseCombatAI->GetState() == AiState::idle && !m_BaseCombatAI->GetOutOfCombat() && !m_BaseCombatAI->GetIsTethering(); if (idleNotResetting) { m_BaseCombatAI->SetStartingPosition(approxPos); } if (m_TimeTravelled < m_TimeToTravel) return; m_TimeTravelled = 0.0f; const auto source = GetCurrentWaypoint(); SetPosition(source); m_SourcePosition = source; if (m_Acceleration > 0 && m_BaseSpeed > 0 && AdvanceWaypointIndex()) // Do we have another waypoint to seek? { m_NextWaypoint = GetCurrentWaypoint(); if (m_NextWaypoint == source) { m_TimeToTravel = 0.0f; } else { m_CurrentSpeed = std::min(m_CurrentSpeed + m_Acceleration, m_MaxSpeed); // scale speed based on base speed, and by any speed buffs or slows on this entity auto speed = m_CurrentSpeed * m_BaseSpeed; const auto* const controllablePhysics = m_Parent->GetComponent(); if (controllablePhysics && controllablePhysics->GetSpeedMultiplier() > 0.0f) speed *= controllablePhysics->GetSpeedMultiplier(); const auto delta = m_NextWaypoint - source; // Normalize the vector const auto length = delta.Length(); if (length > 0.0f) { SetVelocity((delta / length) * speed); } // Calclute the time it will take to reach the next waypoint with the current speed m_TimeTravelled = 0.0f; m_TimeToTravel = length / speed; SetRotation(QuatUtils::LookAt(source, m_NextWaypoint)); } } else { // Only try to renew or continue the path if we're in the idle or spawn state and we actually have a combatAI component 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; ArriveAtWaypoint(waypointNum); } else { Stop(); } } Game::entityManager->SerializeEntity(m_Parent); } bool MovementAIComponent::ContinuePath() { if (m_CurrentPath.empty()) { if (m_Path) { if (m_Path->pathBehavior == PathBehavior::Loop) { SetPath(m_Path->pathWaypoints); } else if (m_Path->pathBehavior == PathBehavior::Bounce) { m_IsBounced = !m_IsBounced; std::vector waypoints = m_Path->pathWaypoints; if (m_IsBounced) std::ranges::reverse(waypoints); // It turns round at the end: on to the waypoint before it, not to the end again // (PathFollowWaypointsHelper: waypoint 1, or count - 2) const bool turns = waypoints.size() > 1; if (turns) waypoints.erase(waypoints.begin()); SetPath(waypoints); if (turns && !m_IsBounced) m_CurrentPathStart = 1; } else if (m_Path->pathBehavior == PathBehavior::Once) { // In this case we intended to follow a path and once we've followed it we camp there, otherwise we'd just wander home again. Stop(); return false; } } else { Stop(); if (m_FollowedTarget != LWOOBJID_EMPTY && !m_KeepFollowing) { // It arrived: a follow that does not keep following ends here m_FollowedTarget = LWOOBJID_EMPTY; } else if (m_FollowedTarget != LWOOBJID_EMPTY && m_FollowRadius <= 0.0f) { GameMessages::GetPosition getPos; if (!getPos.Send(m_FollowedTarget)) { LOG("Target %llu does not exist anymore to follow", m_FollowedTarget); m_FollowedTarget = LWOOBJID_EMPTY; } else { SetDestination(getPos.pos); } } return false; } } else { SetDestination(m_CurrentPath.top().position); m_CurrentPath.pop(); } return true; } const MovementAIInfo& MovementAIComponent::GetInfo() const { return m_Info; } bool MovementAIComponent::AdvanceWaypointIndex() { if (m_PathIndex >= m_InterpolatedWaypoints.size()) { return false; } m_PathIndex++; return true; } NiPoint3 MovementAIComponent::GetCurrentWaypoint() const { return m_PathIndex >= m_InterpolatedWaypoints.size() ? m_Parent->GetPosition() : m_InterpolatedWaypoints[m_PathIndex]; } NiPoint3 MovementAIComponent::ApproximateLocation() const { auto source = m_SourcePosition; if (AtFinalWaypoint()) return m_Parent->GetPosition(); auto destination = m_NextWaypoint; auto percentageToWaypoint = m_TimeToTravel > 0 ? m_TimeTravelled / m_TimeToTravel : 0; auto approximation = source + ((destination - source) * percentageToWaypoint); if (dpWorld::IsLoaded()) { approximation.y = dpWorld::GetNavMesh()->GetHeightAtPoint(approximation); } return approximation; } bool MovementAIComponent::Warp(const NiPoint3& point) { m_Knockback.Cancel(); m_DestinationAfterKnockback.reset(); Stop(); NiPoint3 destination = point; if (dpWorld::IsLoaded()) { destination.y = dpWorld::GetNavMesh()->GetHeightAtPoint(point); if (std::abs(destination.y - point.y) > 3) { return false; } } SetPosition(destination); Game::entityManager->SerializeEntity(m_Parent); return true; } 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()); SetVelocity(NiPoint3Constant::ZERO); m_TimeToTravel = 0; m_TimeTravelled = 0; m_AtFinalWaypoint = true; m_InterpolatedWaypoints.clear(); while (!m_CurrentPath.empty()) m_CurrentPath.pop(); m_CurrentPathWaypointCount = 0; m_PathIndex = 0; m_CurrentSpeed = 0; Game::entityManager->SerializeEntity(m_Parent); } void MovementAIComponent::PullToPoint(const NiPoint3& point) { m_Knockback.Cancel(); Stop(); m_PullingToPoint = true; m_PullPoint = point; } void MovementAIComponent::SetPath(std::vector path) { if (path.empty()) return; m_CurrentPathStart = 0; while (!m_CurrentPath.empty()) m_CurrentPath.pop(); std::for_each(path.rbegin(), path.rend() - 1, [this](const PathWaypoint& point) { this->m_CurrentPath.push(point); }); m_CurrentPathWaypointCount = path.size(); SetDestination(path.front().position); } float MovementAIComponent::GetBaseSpeed(LOT lot) { // Check if the lot is in the cache const auto& it = m_PhysicsSpeedCache.find(lot); if (it != m_PhysicsSpeedCache.end()) { return it->second; } CDComponentsRegistryTable* componentRegistryTable = CDClientManager::GetTable(); CDPhysicsComponentTable* physicsComponentTable = CDClientManager::GetTable(); int32_t componentID; CDPhysicsComponent* physicsComponent = nullptr; componentID = componentRegistryTable->GetByIDAndType(lot, eReplicaComponentType::CONTROLLABLE_PHYSICS, -1); if (componentID == -1) { componentID = componentRegistryTable->GetByIDAndType(lot, eReplicaComponentType::SIMPLE_PHYSICS, -1); } physicsComponent = physicsComponentTable->GetByID(componentID); // Client defaults speed to 10 and if the speed is also null in the table, it defaults to 10. float speed = physicsComponent != nullptr ? physicsComponent->speed : 10.0f; float delta = fabs(speed) - 1.0f; if (delta <= std::numeric_limits::epsilon()) speed = 10.0f; m_PhysicsSpeedCache[lot] = speed; return speed; } float MovementAIComponent::GetRemainingPathDistance() const { if (m_InterpolatedWaypoints.empty() || m_PathIndex >= m_InterpolatedWaypoints.size()) { return 0.0f; } float total = NiPoint3::Distance(m_Parent->GetPosition(), m_InterpolatedWaypoints[m_PathIndex]); for (size_t i = m_PathIndex; i + 1 < m_InterpolatedWaypoints.size(); ++i) { total += NiPoint3::Distance(m_InterpolatedWaypoints[i], m_InterpolatedWaypoints[i + 1]); } return total; } void MovementAIComponent::SetPosition(const NiPoint3& value) { m_Parent->SetPosition(value); } void MovementAIComponent::SetRotation(const NiQuaternion& value) { if (!m_LockRotation) m_Parent->SetRotation(value); } NiPoint3 MovementAIComponent::GetVelocity() const { auto* controllablePhysicsComponent = m_Parent->GetComponent(); if (controllablePhysicsComponent != nullptr) { return controllablePhysicsComponent->GetVelocity(); } auto* simplePhysicsComponent = m_Parent->GetComponent(); if (simplePhysicsComponent != nullptr) { return simplePhysicsComponent->GetVelocity(); } return NiPoint3Constant::ZERO; } void MovementAIComponent::SetVelocity(const NiPoint3& value) { auto* controllablePhysicsComponent = m_Parent->GetComponent(); if (controllablePhysicsComponent != nullptr) { controllablePhysicsComponent->SetVelocity(value); return; } auto* simplePhysicsComponent = m_Parent->GetComponent(); if (simplePhysicsComponent != nullptr) { simplePhysicsComponent->SetVelocity(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; } const auto location = ApproximateLocation(); if (!AtFinalWaypoint()) { SetPosition(location); } m_SourcePosition = location; std::vector computedPath; if (dpWorld::IsLoaded()) { computedPath = dpWorld::GetNavMesh()->GetPath(m_Parent->GetPosition(), destination, m_Info.wanderSpeed); } // Somehow failed if (computedPath.empty()) { // Than take 10 points between the current position and the destination and make that the path auto start = location; auto delta = destination - start; auto step = delta / 10.0f; for (int i = 0; i < 10; i++) { start += step; computedPath.push_back(start); } } // The path is walked without collision, so an enemy's stops at walls it can't cross (navmesh carvers, enemy only // blockers); with nothing left to walk it stays where it is. A patrol along its level path is left as designed. // Pets are walked here too, and their group (3) is the one the pet ranch's "PR - Pet Blocker" (group 18) touches: // the client's filter lets pets collide with it and players through. const bool patrolling = m_Path && m_BaseCombatAI && m_BaseCombatAI->GetState() == AiState::idle; const bool isPet = m_Parent->HasComponent(eReplicaComponentType::PET); if ((m_BaseCombatAI && !patrolling) || isPet) { computedPath = dpWorld::ClampPath(m_Parent->GetPosition(), std::move(computedPath), static_cast(m_Parent->GetCollisionGroup())); if (computedPath.empty()) computedPath.push_back(m_Parent->GetPosition()); } m_InterpolatedWaypoints.clear(); // Simply path for (auto& point : computedPath) { if (dpWorld::IsLoaded()) { point.y = dpWorld::GetNavMesh()->GetHeightAtPoint(point); } m_InterpolatedWaypoints.push_back(point); } m_PathIndex = 0; m_TimeTravelled = 0; m_TimeToTravel = 0; m_AtFinalWaypoint = false; } NiPoint3 MovementAIComponent::GetDestination() const { return m_InterpolatedWaypoints.empty() ? m_Parent->GetPosition() : m_InterpolatedWaypoints.back(); } void MovementAIComponent::SetMaxSpeed(const float value) { if (value == m_MaxSpeed) return; m_MaxSpeed = value; m_Acceleration = value / 5.0f; } 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; } // _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)); } } m_ActionDelay = BOUNCE_ACTION_DELAY; return false; } 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) { auto& movementInfo = reportInfo.info->PushDebug("MovementAI"); if (m_Path) { movementInfo.PushDebug("Path") = m_Path->pathName; } auto& movementAiInfo = movementInfo.PushDebug("Movement AI Info"); movementAiInfo.PushDebug("Movement Type") = m_Info.movementType; movementAiInfo.PushDebug("Wander Radius") = m_Info.wanderRadius; movementAiInfo.PushDebug("Wander Speed") = m_Info.wanderSpeed; movementAiInfo.PushDebug("Wander Chance") = m_Info.wanderChance; movementAiInfo.PushDebug("Wander Delay Min") = m_Info.wanderDelayMin; movementAiInfo.PushDebug("Wander Delay Max") = m_Info.wanderDelayMax; auto& speedInfo = movementInfo.PushDebug("Speed Info"); speedInfo.PushDebug("Base Speed") = m_BaseSpeed; speedInfo.PushDebug("Max Speed") = m_MaxSpeed; speedInfo.PushDebug("Current Speed") = m_CurrentSpeed; speedInfo.PushDebug("Acceleration") = m_Acceleration; movementInfo.PushDebug("Halt Distance") = m_HaltDistance; movementInfo.PushDebug("Time To Travel") = m_TimeToTravel; movementInfo.PushDebug("Time Travelled") = m_TimeTravelled; movementInfo.PushDebug("Lock Rotation") = m_LockRotation; movementInfo.PushDebug("Paused") = m_Paused; movementInfo.PushDebug("Pulling To Point") = m_PullingToPoint; movementInfo.PushDebug("At Final Waypoint") = m_AtFinalWaypoint; auto& pullPointInfo = movementInfo.PushDebug("Pull Point").PushDebug(m_PullPoint); // movementInfo.PushDebug("Delay") = m_Delay; auto& waypoints = movementInfo.PushDebug("Interpolated Waypoints"); int i = 0; for (const auto& point : m_InterpolatedWaypoints) { waypoints.PushDebug("Waypoint " + std::to_string(++i)).PushDebug(point); } i = 0; auto& currentPath = movementInfo.PushDebug("Current Path"); auto pathCopy = m_CurrentPath; // Copy to avoid modifying the original stack while (!pathCopy.empty()) { const auto& waypoint = pathCopy.top(); currentPath.PushDebug("Waypoint " + std::to_string(++i)).PushDebug(waypoint.position); pathCopy.pop(); } movementInfo.PushDebug("Followed Target") = std::to_string(m_FollowedTarget); return true; } void MovementAIComponent::FollowTarget(const LWOOBJID target) { FollowTarget(target, 0.0f, 1.0f, true); } void MovementAIComponent::FollowTarget(const LWOOBJID target, const float radius, const float speed, const bool keepFollowing) { // The halt distance of an earlier follow with a radius goes with it if (m_FollowRadius > 0.0f && radius <= 0.0f) SetHaltDistance(0.0f); m_FollowRadius = radius; m_FollowSpeed = speed; m_KeepFollowing = keepFollowing; if (target == LWOOBJID_EMPTY) { m_FollowedTarget = target; return; } GameMessages::GetPosition getPos; if (!getPos.Send(target)) { LOG("Tried to follow target %llu but they don't exist", target); m_FollowedTarget = LWOOBJID_EMPTY; return; } m_FollowedTarget = target; if (radius > 0.0f) SetHaltDistance(radius); SetMaxSpeed(speed); m_CurrentSpeed = speed; SetDestination(getPos.pos); } void MovementAIComponent::ResumeFollow() { GameMessages::GetPosition getPos; if (!getPos.Send(m_FollowedTarget)) { LOG("Target %llu does not exist anymore to follow", m_FollowedTarget); m_FollowedTarget = LWOOBJID_EMPTY; return; } if (Vector3::DistanceSquared(m_Parent->GetPosition(), getPos.pos) <= m_FollowRadius * m_FollowRadius) return; SetHaltDistance(m_FollowRadius); SetMaxSpeed(m_FollowSpeed); m_CurrentSpeed = m_FollowSpeed; SetDestination(getPos.pos); } void MovementAIComponent::Knockback(const NiPoint3& vector) { // Whatever we were walking to is forgotten, like a knocked back character losing its movement input m_PullingToPoint = false; Stop(); const auto position = m_Parent->GetPosition(); m_KnockbackStartHeight = position.y; auto* const controllablePhysics = m_Parent->GetComponent(); const auto ground = [this](const NiPoint3& point) { return GetGroundHeight(point); }; if (!m_Knockback.Start(position, vector)) { // Too weak to launch: just shoved along the ground SetPosition(dpKnockback::Nudge(position, vector, KNOCKBACK_MAX_DROP, ground)); Game::entityManager->SerializeEntity(m_Parent); return; } SetPosition(m_Knockback.GetPosition()); SetVelocity(m_Knockback.GetVelocity()); if (controllablePhysics) controllablePhysics->SetIsOnGround(false); Game::entityManager->SerializeEntity(m_Parent); } void MovementAIComponent::UpdateKnockback(const float deltaTime) { auto* const controllablePhysics = m_Parent->GetComponent(); auto gravity = Game::zoneManager ? Game::zoneManager->GetWorldConfig().peGravityValue : 0.0f; if (gravity <= 0.0f) gravity = DEFAULT_GRAVITY; if (controllablePhysics && controllablePhysics->GetGravityScale() > 0.0f) gravity *= controllablePhysics->GetGravityScale(); const bool flying = m_Knockback.Step(deltaTime, gravity, [this](const NiPoint3& point) { return GetGroundHeight(point); }); if (flying) { SetPosition(m_Knockback.GetPosition()); SetVelocity(m_Knockback.GetVelocity()); Game::entityManager->SerializeEntity(m_Parent); return; } // Landed: put it back on the navmesh so pathing picks up from a walkable spot auto landing = m_Knockback.GetPosition(); if (dpWorld::IsLoaded()) landing = dpWorld::GetNavMesh()->NearestPoint(landing); SetPosition(landing); SetVelocity(NiPoint3Constant::ZERO); if (controllablePhysics) controllablePhysics->SetIsOnGround(true); m_SourcePosition = landing; m_NextWaypoint = landing; Game::entityManager->SerializeEntity(m_Parent); if (m_DestinationAfterKnockback) { const auto destination = *m_DestinationAfterKnockback; m_DestinationAfterKnockback.reset(); if (!m_Paused) SetDestination(destination); } } float MovementAIComponent::GetGroundHeight(const NiPoint3& point) const { if (dpWorld::IsLoaded()) return dpWorld::GetNavMesh()->GetHeightAtPoint(point); return m_KnockbackStartHeight; } void MovementAIComponent::Allocator(Entity& entity, ObjectLoadState& state) { const int movementAIID = state.GetComponentID(eReplicaComponentType::MOVEMENT_AI); if (movementAIID > 0) { // Its row and the level's wanderRadius load in the component entity.AddComponent(movementAIID, MovementAIInfo{}); } else if (state.GetComponentID(eReplicaComponentType::PET) > 0 || state.GetComponentID(eReplicaComponentType::BASE_COMBAT_AI) > 0 && BaseCombatAIComponent::TetherSpeedOf(state.GetComponentID(eReplicaComponentType::BASE_COMBAT_AI)) > 0) { MovementAIInfo moveInfo{ .movementType = "", .wanderRadius = 16, .wanderSpeed = 2.5f, .wanderChance = 0, .wanderDelayMin = 2, .wanderDelayMax = 5, }; entity.AddComponent(-1, moveInfo); } else if (state.addsMovementAI) { // ApplyMovementAiIfNeeded: a scripted object or one with an attached path has one (id 0: no row) entity.AddComponent(0, MovementAIInfo{}); } }