fix(ai): FamiliarAI owns familiar movement and combat; herding reaches its tile; ForcedAI read once (#2644)

## Problem

`BaseFamiliar.OnThink` drove its own movement (`WalkMobileRange` toward the master) while the familiar was also a controlled pet running `Obey()`. `Summon → SetControlMaster` issues `Come`; `DoOrderCome` converts it to `Stay` within two tiles and anchors `Home`; from then on `OnThink` walked toward the caster while `DoOrderStay` greedy-stepped back toward the stale post — the backtracking. Combat never approached anything: main only copied `Combatant` while already adjacent to the caster. `CurrentSpeed = 0.01` was a 10 ms think / 50 ms step sprint hack, and `RangeCheck` teleported the familiar to a spot eight tiles *from* the caster.

## Change

A dedicated `FamiliarAI : BaseAI` (registered through `ForcedAI`, like `CloneAI`) owns every familiar decision, for both the controlled (`Obey`) and uncontrolled (`Think`) dispatch:

1. **Lifecycle** — caster gone → drop pack, delete. Caster on another map → stand down and wait for `TeleportPets`.
2. **Herding** (Dark Tides) — stands down, then `CheckHerding()`. Outranks combat.
3. **Assist** — combat-capable familiars (dark wolf, vampire bat, horde minion) engage the caster's target; otherwise anything in a fight with the caster's side — attacked the caster or the familiar, or attacked by the caster (a pet's attack is credited to the caster) — that is still fighting the caster, the familiar, or one of the caster's pets. Leashed to `RangePerception` of the caster; dropped when the caster hides. Shadow wisp and death adder never fight (`AssistsMaster => false`, enforced at the `Combatant` setter so no path can hand them a target).
4. **Follow** — `MoveTo(master, 1)` through the centralized `ApproachTarget` (greedy step / persistent `PathFollower` / stall detection).
5. **Keep-up** — snap to a validated tile beside the caster (on the caster's floor) when outpaced on open ground beyond 10 tiles, or when `ApproachTarget` gave up; never while a detour is working.

**Command immunity** is expressed inside the order machinery rather than around it: `FamiliarAI.IssueOrder` does nothing and rests the order on `Come`, so `TeleportPets` keeps working and no system-issued `Attack` (retaliation on ML's stand-down rule) can strand the familiar. `StandsDownOnCommand => false` so the ML rule never mutes it.

**Visibility** mirrors the caster from the familiar's own state (a step reveals a hidden NPC in `Mobile.OnMove`; the old cache compared the caster's previous state), `RevealingAction` is suppressed while the caster is hidden, and becoming hidden drops Warmode so no swing gives the caster away.

**Speed** is a flat 0.1 (`ReduceSpeedWithDamage => false`).

### Engine-side (all `Projects/UOContent`)

- `ApproachTarget` records which exit it took in `BaseAI.LastApproach` (`ApproachOutcome`: Arrived / Waiting / DirectProgress / Routing / Blocked / GaveUp / InvalidGoal). Callers' booleans are unchanged; keep-up reads this instead of running a second scheduler. `MoveTo`'s arrival return now also clears the move intent, as `ApproachTarget`'s own arrival does.
- `MoveToPoint(goal, range = 1)`; `CheckHerding` passes 0. **Fixes a main regression from #2591:** herding stopped one tile short, never cleared `TargetLocation`, and left the creature pinned to the herding pace — affects the shepherd's crook and the Dark Tides scroll fetch for every herded creature, not just familiars.
- `ChangeAIType` reads `ForcedAI` once. It read it twice, and each `BaseAI` ctor activates its timer for a non-sector-gated creature, so a `ForcedAI` creature with `PlayerRangeSensitive => false` got an orphan AI ticking it.

## Tests

`FamiliarAITests` are timer-wheel driven (the real `AITimer` thinks and moves; `PetPacingTests` style) against live Trammel statics, gated on client map data: follow without backtracking, the five-way assist theory, leash, retaliation, aggressor fallback (caster's own `Combatant` expired; caster's pet in the fight), target dropped when it stops fighting, keep-up on open ground / not while routing / after give-up, hidden mirror across steps, herding priority with a visible fighting caster, stand-down when left behind, no stale move intent. `ApproachOutcomeTests`, `HerdingTests` (fails on main), `ForcedAITests` (fails on main) cover the engine-side pieces.

Against `origin/main` with the familiar tests dropped in: 16/16 fail, including the reported backtracking. On this branch: `UOContent.Tests` 1082 passed / 2 skipped, `Server.Tests` 891/891, solution builds with 0 warnings.
This commit is contained in:
Kamron Batman 2026-09-14 23:14:30 -07:00 • committed by GitHub
parent 459674ce3b
commit 1e891094fe
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 1265 additions and 115 deletions

View file

@ -39,6 +39,11 @@ public abstract partial class BaseAI
private bool _approachGaveUp;
private Point3D _approachGaveUpGoalLoc;
/// <summary>Which exit the last <see cref="ApproachTarget"/> (via <see cref="MoveTo"/> or
/// <see cref="WalkMobileRange"/>) took. A <see cref="WalkMobileRange"/> retreat step does not
/// classify.</summary>
public ApproachOutcome LastApproach { get; private set; }
// --- Move intent (see ContinueMove) ------------------------------------------------
// Durable movement goal renewed by en-route ApproachTarget/MoveToPoint calls; while
// live, the AITimer wakes at NextMove between think ticks to advance the step.
@ -359,12 +364,14 @@ public abstract partial class BaseAI
{
if (Mobile.Deleted || Mobile.DisallowAllMoves || target?.Deleted != false)
{
LastApproach = ApproachOutcome.InvalidGoal;
ClearMoveIntent();
return false;
}
if (Mobile.InRange(target, range))
{
LastApproach = ApproachOutcome.Arrived;
ResetApproach();
ClearMoveIntent();
return true;
@ -375,6 +382,7 @@ public abstract partial class BaseAI
{
if (target.Location == _approachGaveUpGoalLoc)
{
LastApproach = ApproachOutcome.GaveUp;
ClearMoveIntent();
return false;
}
@ -398,12 +406,13 @@ public abstract partial class BaseAI
if (res == MoveResult.BadState)
{
LastApproach = ApproachOutcome.Waiting;
return true; // not allowed to move this tick (frozen/casting/throttled); not a failure
}
if (res == MoveResult.Success && Mobile.GetDistanceToSqrt(target) < distBefore)
{
LastApproach = ApproachOutcome.DirectProgress;
ResetApproach();
return true; // healthy en-route progress
}
@ -414,7 +423,6 @@ public abstract partial class BaseAI
// PLANNING PATH: a persistent PathFollower, never discarded by a greedy step.
if (Path == null || Path.Goal != target)
{
Path = new PathFollower(Mobile, target) { Mover = DoMoveImpl };
}
@ -425,24 +433,33 @@ public abstract partial class BaseAI
if (Path.Follow(range))
{
LastApproach = ApproachOutcome.Arrived;
ResetApproach();
return true;
}
TrackApproachProgress(target, couldMove);
if (_approachGaveUp)
{
LastApproach = ApproachOutcome.GaveUp;
return false;
}
// En-route progress is success; failure only when a move-eligible tick took no step
// (no working path), or the approach has given up.
var progressed = !_approachGaveUp && (Mobile.Location != locBefore || !couldMove);
// (no working path).
var progressed = Mobile.Location != locBefore || !couldMove;
LastApproach = progressed ? ApproachOutcome.Routing : ApproachOutcome.Blocked;
return progressed;
}
/// <summary>
/// Walks toward a fixed point (e.g. a target's last-known position), pathfinding around
/// obstacles. Returns false on arrival or when genuinely unable to make progress.
/// obstacles, until within <paramref name="range"/> (0 = onto the tile). Returns false on
/// arrival or when genuinely unable to make progress.
/// </summary>
public bool MoveToPoint(IPoint3D goal)
public bool MoveToPoint(IPoint3D goal, int range = 1)
{
if (Mobile.Deleted || Mobile.DisallowAllMoves || goal == null)
{
@ -455,12 +472,12 @@ public abstract partial class BaseAI
Path = new PathFollower(Mobile, goal) { Mover = DoMoveImpl };
}
RenewMoveIntent(null, goal, 1);
RenewMoveIntent(null, goal, range);
var couldMove = CanMoveNow(out _) && !IsInBadState();
var locBefore = Mobile.Location;
if (Path.Follow(1))
if (Path.Follow(range))
{
Path = null;
ClearMoveIntent();
@ -536,6 +553,13 @@ public abstract partial class BaseAI
_approachGaveUp = false;
}
/// <summary>Drops the path, stall state, and move intent (after a relocation).</summary>
public void ResetApproachState()
{
ResetApproach();
ClearMoveIntent();
}
private void RenewMoveIntent(Mobile target, IPoint3D point, int range)
{
_moveIntentTarget = target;
@ -580,7 +604,7 @@ public abstract partial class BaseAI
}
else
{
MoveToPoint(_moveIntentPoint);
MoveToPoint(_moveIntentPoint, _moveIntentRange);
}
}
@ -588,12 +612,16 @@ public abstract partial class BaseAI
{
if (Mobile.Deleted || Mobile.DisallowAllMoves || m?.Deleted != false)
{
LastApproach = ApproachOutcome.InvalidGoal;
ClearMoveIntent();
return false;
}
if (Mobile.InRange(m, range))
{
LastApproach = ApproachOutcome.Arrived;
ResetApproach();
ClearMoveIntent();
return true;
}
@ -676,6 +704,7 @@ public abstract partial class BaseAI
{
if (Mobile.Deleted || Mobile.DisallowAllMoves || m == null)
{
LastApproach = ApproachOutcome.InvalidGoal;
return false;
}
@ -685,6 +714,7 @@ public abstract partial class BaseAI
if (iCurrDist >= iWantDistMin && iCurrDist <= iWantDistMax)
{
LastApproach = ApproachOutcome.Arrived;
return true;
}

View file

@ -0,0 +1,30 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ApproachOutcome.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
************************************************************************/
namespace Server.Mobiles;
/// <summary>Which exit <see cref="BaseAI.ApproachTarget"/> took, for policies that need more
/// than its bool.</summary>
public enum ApproachOutcome
{
None,
Arrived, // already within range
Waiting, // frozen, casting, or the move budget has not elapsed
DirectProgress, // greedy step succeeded and closed the distance (open ground)
Routing, // a PathFollower is active and working the detour
Blocked, // move-eligible tick took no step; stall counter still running
GaveUp, // stall counter exhausted on a stationary goal
InvalidGoal // deleted target, deleted self, or DisallowAllMoves
}

View file

@ -632,13 +632,13 @@ public abstract partial class BaseAI
{
// A cached boxed goal keeps the PathFollower persistent across ticks; walking
// through MoveToPoint paces herding on the movement clock and paths around
// obstacles.
// obstacles. Range 0: the exit below is distance < 1.
if (_herdGoal == null || _herdGoal.X != target.X || _herdGoal.Y != target.Y)
{
_herdGoal = new Point3D(target.X, target.Y, Mobile.Map?.GetAverageZ(target.X, target.Y) ?? Mobile.Z);
}
MoveToPoint(_herdGoal);
MoveToPoint(_herdGoal, 0);
return true;
}