Files
DarkflameServer/dScripts/ai/LuaAI/LuaAIMachine.h
Aaron Kimbrell 9df7deb468 feat(ai): shared Lua AI Follow state and name override
Port o_Movement's Follow state (Set.FollowActive): the Followers
proximity, the faction 7 line and its PointInLine / Imfollowing vars,
the flip emote and the follow at radius 3, speed 3. loadOnce now applies
Set.OverRideName; the binding only logs SetName, which DLU does not send
yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:46:28 -06:00

337 lines
14 KiB
C++

#pragma once
// The shared Lua AI of the original server scripts (State, o_StateCreate, o_Main, o_mis, o_onEvent, o_Movement):
// a script fills its Set table, then runs loadOnce, getVarables, CreateStates and oStart. This is that state
// machine, fed by the same Set table and driven through a Host, so it can be tested without an entity and bound to
// one by LuaAIScript.
//
// Ported: the Idle, Meander, aggro, tether, GoHome, combat, AiDisable, AiEnable, Dead and WayPointEvent states, the
// aggroRadius proximity, hits, the tether, the wander and aggro emotes, the attack heartbeat, waypoint paths
// (Set.WayPointSet, attached_path, groupID: o_WayPointEvents), the template timers, the Follow state
// (Set.FollowActive) and the name override (Set.OverRideName).
// Not ported yet: pets (Set.Pet_Active), helpers (Set.Helper) and the custom state.
#include "dCommonVars.h"
#include "NiPoint3.h"
#include "NiQuaternion.h"
#include <optional>
#include <string>
#include <vector>
namespace LuaAI {
// Set['Aggression']; a script that sets none acts as Neutral
enum class Aggression : uint8_t { Neutral, Aggressive, Passive, PassiveAggres };
// Set['MovementType']; a script that sets none gets no movement state at all
enum class MovementType : uint8_t { None, Guard, Wander, Frozen };
enum class State : uint8_t { None, Idle, Meander, Aggro, Tether, GoHome, AiDisable, AiEnable, Combat, Dead, WayPointEvent, Follow };
const char* StateName(State state);
// The proximity oStart makes for an Aggressive one
constexpr const char* AGGRO_PROXIMITY = "aggroRadius";
// The proximity Follow.onEnter looks in for the end of the line (a script of its own makes it)
constexpr const char* FOLLOWERS_PROXIMITY = "Followers";
// Follow.onEnter: the faction whose objects are the line, its FollowTarget and the name it takes
constexpr int32_t FOLLOW_FACTION = 7;
constexpr float FOLLOW_RADIUS = 3.0f;
constexpr float FOLLOW_SPEED = 3.0f;
constexpr const char16_t* FOLLOW_NAME = u"scared";
constexpr const char16_t* FOLLOW_EMOTE = u"flip";
// aggro.onEnter: INITIAL_ATTACK_TIME
constexpr float INITIAL_ATTACK_TIME = 1.0f;
// The FollowTarget of the aggro state without AggroDist and AggroSpeed
constexpr float DEFAULT_AGGRO_DIST = 3.0f;
constexpr float DEFAULT_AGGRO_SPEED = 1.0f;
// GoHome.onEnter: GoTo { speed = 1 }
constexpr float GO_HOME_SPEED = 1.0f;
// The timers the shared Lua uses
namespace Timers {
constexpr const char* ATTACK_HEART_BEAT = "AttackHeartBeat";
constexpr const char* MEANDER_PAUSE = "MeanderPause";
constexpr const char* AGGRO_EMOTE = "AggroEmote";
constexpr const char* DELAY_KILL_SELF = "DealyKillSelf";
constexpr const char* DELETE_OBJECT = "TimerDeleteObject";
// The waypoint delay and emote actions
constexpr const char* DELAY_ACTION = "DealyAction";
constexpr const char* DELAY_ACTION_EMOTE = "DelayActionEmote";
};
// A waypoint action of onArrived's msg.actions; a value the waypoint leaves nil is "noValue"
struct WaypointAction {
std::string name;
std::string value;
};
constexpr const char* NO_VALUE = "noValue";
// onArrived's msg: the arrival of a GoTo, a follow or a waypoint of a path
struct Arrived {
uint32_t wayPoint = 0;
std::string pathName;
bool isLastPoint = false;
// nil unless the waypoint has actions
std::optional<std::vector<WaypointAction>> actions;
};
// The Set table keys the shared AI reads. Keys a script leaves nil keep these defaults.
struct Settings {
// RADIUS
float aggroRadius = 0.0f;
float tetherRadius = 0.0f;
// tether.onEnter: GoTo { speed = Set.tetherSpeed }
float tetherSpeed = 1.0f;
// Meander: math.random(-r, r) on x and z, so it is an integer
int32_t wanderRadius = 0;
// AGGRO
Aggression aggression = Aggression::Neutral;
// FollowTarget { radius = AggroDist, speed = AggroSpeed * 2 } when both are set
std::optional<float> aggroDist;
std::optional<float> aggroSpeed;
bool aggroEmote = false;
std::u16string aggroEmoteType;
float aggroEmoteDelay = 1.0f;
// MOVEMENT
MovementType movementType = MovementType::None;
int32_t wanderChance = 0;
// math.random(WanderDelayMin, WanderDelayMax): integers
int32_t wanderDelayMin = 0;
int32_t wanderDelayMax = 0;
float wanderSpeed = 1.0f;
bool wanderEmote = false;
// WEmote_2 set: two weighted emotes, WEmote_1 is the first one's weight
bool wanderEmoteTwo = false;
int32_t wanderEmoteWeight = 0;
std::u16string wanderEmoteType1;
std::u16string wanderEmoteType2;
// Hand fights to the object's own combat AI (the combat state) / no Lua movement states
bool suspendLuaAI = false;
bool suspendLuaMovementAI = false;
// SKILLS: the attack is the object's last skill unless overridden
bool overrideAttackSkill = false;
uint32_t attackSkill = 0;
bool useOptionalTargetOnAttack = false;
// SKILLS block: loadOnce
bool overrideHealth = false;
int32_t health = 1;
// WAYPOINTS: Set.WayPointSet (the path loadOnce attaches) and the object's attached_path and groupID config
std::string wayPointSet;
std::string attachedPath;
bool hasGroupID = false;
// Set.FollowActive: the Follow state
bool followActive = false;
// Set.OverRideName / Set.Name
bool overrideName = false;
std::u16string name;
};
// What the machine needs from the object it runs on: the script API calls the shared Lua makes
class Host {
public:
virtual ~Host() = default;
virtual NiPoint3 GetPosition() const = 0;
virtual NiQuaternion GetRotation() const = 0;
virtual void SetRotation(const NiQuaternion& rotation) = 0;
// self:GoTo { speed, target }
virtual void GoTo(const NiPoint3& target, float speed) = 0;
// self:FollowTarget { targetID, radius, speed, keepFollowing }
virtual void FollowTarget(LWOOBJID target, float radius, float speed, bool keepFollowing) = 0;
// self:FaceTarget { target, keepFacingTarget = true }
virtual void FaceTarget(LWOOBJID target) = 0;
virtual void StopPathing() = 0;
virtual void AddTimer(const std::string& name, float time) = 0;
virtual void CancelTimer(const std::string& name) = 0;
virtual void SetProximityRadius(float radius, const std::string& name) = 0;
virtual std::vector<LWOOBJID> GetProximityObjects(const std::string& name) const = 0;
virtual bool Exists(LWOOBJID object) const = 0;
// True for an object that does not exist
virtual bool IsDead(LWOOBJID object) const = 0;
virtual bool IsSelfDead() const = 0;
virtual bool IsEnemy(LWOOBJID object) const = 0;
// obj:GetType().objType: the Objects table type ("Enemies", "NPC" for players, "Rebuildables", ...)
virtual std::string GetObjectType(LWOOBJID object) const = 0;
// self:GetSkills().skills, in order
virtual std::vector<uint32_t> GetSkills() const = 0;
// self:GetSkillInfo { skillID }.cooldown
virtual float GetSkillCooldown(uint32_t skill) const = 0;
virtual void CastSkill(uint32_t skill, LWOOBJID optionalTarget) = 0;
virtual void SetImmunity(bool immune) = 0;
// self:SetHealth { health = self:GetMaxHealth{}.health }
virtual void RestoreHealth() = 0;
// Set.OverRideHealth: SetMaxHealth and SetHealth
virtual void SetMaxHealth(int32_t health) = 0;
// PlayFXEffect { priority = 1.5, effectType }
virtual void PlayEmote(const std::u16string& effectType) = 0;
// self:Die { killerID = self, killType = "SILENT" }
virtual void DieSilently() = 0;
// math.random(min, max), both inclusive
virtual int32_t Random(int32_t min, int32_t max) = 0;
// self:FollowWaypoints {} on the attached path, from its waypoint start on; with a new path:
// FollowWaypoints { bUseNewPath = true, newPathName, newStartingPoint }
virtual void FollowWaypoints(const std::string& path, uint32_t start) = 0;
virtual void ContinueWaypoints() = 0;
// self:GetAnimationTime { animationID }.time
virtual float GetAnimationTime(const std::u16string& animation) const = 0;
// The waypoint actions that act on other objects or the world (bounce, groupemote, setvar, eqInvent, unInvent,
// teleport, pathspeed, removeNPC, DeleteSelf, removeself, spawnOBJ); the machine runs the rest
virtual void RunWaypointAction(const std::string& name, const std::string& value, std::optional<uint32_t> savedWayPoint) = 0;
virtual LWOOBJID GetObjectID() const = 0;
// self:SetName { name }
virtual void SetName(const std::u16string& name) = 0;
// obj:BelongsToFaction { factionID }.bIsInFaction
virtual bool BelongsToFaction(LWOOBJID object, int32_t faction) const = 0;
// The PointInLine and Imfollowing vars of the Follow state, which other objects of the line read and set
virtual bool GetPointInLine(LWOOBJID object) const = 0;
virtual void SetPointInLine(LWOOBJID object, bool pointInLine) = 0;
// obj:GetVar("Imfollowing") == "done"
virtual bool IsFollowingDone(LWOOBJID object) const = 0;
// self:SetVar("Imfollowing", true)
virtual void SetImFollowing() = 0;
};
class Machine {
public:
Machine(Host& host, const Settings& settings) : m_Host(host), m_Set(settings) {}
// loadOnce, getVarables, CreateStates and oStart
void Start();
// setState: onExit of the current state, then onEnter of the new one (again for the same state)
void SetState(State state);
State GetState() const { return m_State; }
// The messages the states and o_onEvent handle
void OnProximityEnter(LWOOBJID object, const std::string& name);
void OnHit(LWOOBJID attacker);
// The state's onTimerDone; false when it has none for the timer (the script's onTimerDone runs then)
bool OnStateTimerDone(const std::string& name);
// o_onEvent onTimerDone, the script's one unless it has its own
void OnTimerDone(const std::string& name);
// The state's onArrived, else the global one (o_WayPointEvents)
void OnArrived(const Arrived& msg = {});
void OnCancelled();
void OnLeftTetherRadius();
void OnDeath();
// o_onEvent onNotifyObject
void OnNotifyObject(const std::string& name);
// o_onEvent onFireEvent: "startpath,<path>,<waypoint>"
void OnFireEvent(const std::string& args);
// onResetScriptedAIState
void ResetState() { SetResetState(); }
// The tether check, every frame: onLeftTetherRadius once it leaves the radius
void Update();
// self:SetTetherPoint { tetherPt, radius }; radius 0 turns it off
void SetTetherPoint(const NiPoint3& point, float radius);
const Settings& GetSettings() const { return m_Set; }
LWOOBJID GetAttackingTarget() const { return m_AttackingTarget; }
const NiPoint3& GetHomePoint() const { return m_Home; }
const NiPoint3& GetMeanderPoint() const { return m_MeanderPoint; }
const NiPoint3& GetTetherPoint() const { return m_TetherPoint; }
float GetTetherRadius() const { return m_TetherRadius; }
int32_t GetAggroTarget() const { return m_AggroTarget; }
bool GetReadyToAttack() const { return m_ReadyToAttack; }
bool GetAggroed() const { return m_Aggroed; }
bool GetAiDisabled() const { return m_AiDisabled; }
std::optional<float> GetSkillTime() const { return m_SkillTime; }
const std::string& GetAttachedPath() const { return m_AttachedPath; }
std::optional<uint32_t> GetSavedWayPoint() const { return m_SavedWP; }
const std::string& GetPathName() const { return m_PathName; }
int32_t GetWayPointEventNum() const { return m_WPEventNum; }
const std::vector<std::string>& GetTemplateTimers() const { return m_TemplateTimers; }
private:
bool HasState(State state) const;
void EnterState(State state);
void ExitState(State state);
// o_mis
void LoadOnce();
void GetVarables();
void SetResetState();
void StoreHomePoint();
// o_Movement / o_main
void MeanderEnter();
void MeanderArrived();
void TetherEnter();
void TetherArrived();
void GoHomeEnter();
void GoHomeArrived();
void AiDisableEnter();
void AiEnableEnter();
void FollowEnter();
// o_main / o_onEvent
void AggroEnter();
void AggroTimerDone(const std::string& name);
void DoAttack();
bool CanAttackTarget();
void ProximityPuls();
bool IsAttackable(LWOOBJID object) const;
void AggroEmote(LWOOBJID target);
// o_WayPointEvents / o_main
void WayPointArrived(const Arrived& msg);
void WayPointEventEnter();
void WayPointEventFunc(const std::string& name, const std::string& value);
void NextWayPointEvent();
void FollowWaypoints();
void FollowNewPath(const std::string& path, uint32_t start);
// SetStoreTimmer / CancelTemplateTimers
void SetStoreTimer(float time, const std::string& name);
void CancelTemplateTimers();
Host& m_Host;
Settings m_Set;
State m_State = State::None;
// storeHomePoint: myx/myy/myz and rot
NiPoint3 m_Home = NiPoint3Constant::ZERO;
NiQuaternion m_HomeRotation = QuatUtils::IDENTITY;
// storeMeanderPoint: Meadx/Meady/Meadz
NiPoint3 m_MeanderPoint = NiPoint3Constant::ZERO;
NiPoint3 m_TetherPoint = NiPoint3Constant::ZERO;
float m_TetherRadius = 0.0f;
bool m_InsideTether = true;
// The global myPos the Meander state leaves behind, which onOnHit tethers to
std::optional<NiPoint3> m_GlobalMyPos;
// The vars: AttackingTarget ("NoTarget" is LWOOBJID_EMPTY), aggrotarget (0 none, 1 fighting, 2 tethering)
LWOOBJID m_AttackingTarget = LWOOBJID_EMPTY;
int32_t m_AggroTarget = 0;
bool m_ReadyToAttack = true;
bool m_AggroEmoteDelay = true;
bool m_InPursuit = false;
bool m_AiDisabled = false;
bool m_Aggroed = false;
int32_t m_AggroOnce = 0;
std::optional<float> m_SkillTime;
// attached_path and attached_path_start; SavedWP and PathName, the last waypoint reached
bool m_HasWayPointState = false;
std::string m_AttachedPath;
uint32_t m_AttachedPathStart = 0;
std::optional<uint32_t> m_SavedWP;
std::string m_PathName;
// Act_N / Act_V and WPEvent_NUM (1-based)
std::vector<WaypointAction> m_Actions;
int32_t m_WPEventNum = 1;
// The Timers var: the names SetStoreTimmer started (its "blank" first entry left out)
std::vector<std::string> m_TemplateTimers;
// EndOfLineTarget: the object of the line Follow.onEnter found last
LWOOBJID m_EndOfLineTarget = LWOOBJID_EMPTY;
};
};