From 1e891094fe403b44ce7de8ce99dea6992547a51a Mon Sep 17 00:00:00 2001 From: Kamron Batman <3953314+kamronbatman@users.noreply.github.com> Date: Mon, 14 Sep 2026 23:14:30 -0700 Subject: [PATCH] fix(ai): FamiliarAI owns familiar movement and combat; herding reaches its tile; ForcedAI read once (#2644) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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. --- .../Tests/Mobiles/AI/ApproachOutcomeTests.cs | 130 ++++ .../Tests/Mobiles/AI/ApproachTargetTests.cs | 2 +- .../Tests/Mobiles/AI/FamiliarAITests.cs | 557 ++++++++++++++++++ .../Tests/Mobiles/AI/ForcedAITests.cs | 59 ++ .../Tests/Mobiles/AI/HerdingTests.cs | 51 ++ .../UOContent/Items/Weapons/BaseWeapon.cs | 6 +- .../UOContent/Mobiles/AI/BaseAI/AIMovement.cs | 48 +- .../Mobiles/AI/BaseAI/ApproachOutcome.cs | 30 + .../UOContent/Mobiles/AI/BaseAI/BaseAI.cs | 4 +- Projects/UOContent/Mobiles/AI/FamiliarAI.cs | 268 +++++++++ Projects/UOContent/Mobiles/BaseCreature.cs | 20 +- .../Mobiles/Familiars/BaseFamiliar.cs | 100 ++-- .../UOContent/Mobiles/Familiars/DeathAdder.cs | 2 + .../Mobiles/Familiars/HordeMinion.cs | 71 ++- .../UOContent/Mobiles/Familiars/ShadowWisp.cs | 2 + Projects/UOContent/Skills/AnimalTaming.cs | 5 +- dev-docs/content-patterns.md | 10 + dev-docs/pathfinding.md | 15 + 18 files changed, 1265 insertions(+), 115 deletions(-) create mode 100644 Projects/UOContent.Tests/Tests/Mobiles/AI/ApproachOutcomeTests.cs create mode 100644 Projects/UOContent.Tests/Tests/Mobiles/AI/FamiliarAITests.cs create mode 100644 Projects/UOContent.Tests/Tests/Mobiles/AI/ForcedAITests.cs create mode 100644 Projects/UOContent.Tests/Tests/Mobiles/AI/HerdingTests.cs create mode 100644 Projects/UOContent/Mobiles/AI/BaseAI/ApproachOutcome.cs create mode 100644 Projects/UOContent/Mobiles/AI/FamiliarAI.cs diff --git a/Projects/UOContent.Tests/Tests/Mobiles/AI/ApproachOutcomeTests.cs b/Projects/UOContent.Tests/Tests/Mobiles/AI/ApproachOutcomeTests.cs new file mode 100644 index 000000000..fe8e397a1 --- /dev/null +++ b/Projects/UOContent.Tests/Tests/Mobiles/AI/ApproachOutcomeTests.cs @@ -0,0 +1,130 @@ +using System.Collections.Generic; +using Server; +using Server.Engines.Pathing.Cache; +using Server.Mobiles; +using Server.Tests; +using Server.Tests.Mobiles.AI; +using Xunit; + +namespace UOContent.Tests.Mobiles.AI; + +// Driven manually against live map statics; the pathfinder's buffers are not reentrant. +[Collection("Sequential Pathfinding Tests")] +public class ApproachOutcomeTests +{ + private sealed class Stub : BaseCreature + { + public Stub(Serial serial) : base(serial) => Body = 0xC9; + } + + private sealed class Target : Mobile + { + public Target() => Body = 0xC9; + } + + private static (Stub bc, BaseAI ai) NewFollower(Map map, int x, int y) + { + map.GetAverageZ(x, y, out _, out var z, out _); + var bc = new Stub(World.NewMobile); + bc.DefaultMobileInit(); + bc.MoveToWorld(new Point3D(x, y, (sbyte)z), map); + BaseAI ai = new AnimalAI(bc); + ai.AITimer?.Stop(); + return (bc, ai); + } + + private static Target NewTarget(Map map, int x, int y) + { + map.GetAverageZ(x, y, out _, out var z, out _); + var t = new Target(); + t.MoveToWorld(new Point3D(x, y, (sbyte)z), map); + return t; + } + + [SkippableFact] + public void OpenGround_ReportsDirectProgress_ThenArrived() + { + TileDataRequirement.SkipIfMissing(); + var map = Map.Maps[1]; + var (bc, ai) = NewFollower(map, 1500, 1600); + var target = NewTarget(map, 1497, 1600); + StepCache.Instance.Clear(); + + try + { + ai.NextMove = 0; + ai.MoveTo(target, 1); + Assert.Equal(ApproachOutcome.DirectProgress, ai.LastApproach); + + ai.MoveTo(target, 1); // budget consumed: no step + Assert.Equal(ApproachOutcome.Waiting, ai.LastApproach); + + ai.NextMove = 0; + ai.MoveTo(target, 1); // lands adjacent: still a progress step + Assert.Equal(ApproachOutcome.DirectProgress, ai.LastApproach); + + ai.NextMove = 0; + ai.MoveTo(target, 1); + Assert.Equal(ApproachOutcome.Arrived, ai.LastApproach); + } + finally + { + bc.Delete(); + target.Delete(); + } + } + + [SkippableFact] + public void WalledTarget_ReportsGaveUp() + { + TileDataRequirement.SkipIfMissing(); + var map = Map.Maps[1]; + var (bc, ai) = NewFollower(map, 1500, 1601); + var target = NewTarget(map, 1500, 1596); + var ring = new List(); + var id = ApproachTargetTests.FirstImpassableItemId(); + Assert.NotEqual(0, id); + + // Impassable ring around the target: unreachable. + for (var x = 1499; x <= 1501; x++) + { + for (var y = 1595; y <= 1597; y++) + { + if (x == 1500 && y == 1596) + { + continue; + } + + map.GetAverageZ(x, y, out _, out var rz, out _); + ring.Add(new Item(World.NewItem) { ItemID = id, Map = map, Location = new Point3D(x, y, (sbyte)rz) }); + } + } + + StepCache.Instance.Clear(); + + try + { + var sawRouting = false; + + for (var i = 0; i < 120; i++) + { + ai.NextMove = 0; + ai.MoveTo(target, 1); + sawRouting |= ai.LastApproach is ApproachOutcome.Routing or ApproachOutcome.Blocked; + } + + Assert.True(sawRouting, "a walled target must route or block before giving up"); + Assert.Equal(ApproachOutcome.GaveUp, ai.LastApproach); + } + finally + { + bc.Delete(); + target.Delete(); + + for (var i = 0; i < ring.Count; i++) + { + ring[i].Delete(); + } + } + } +} diff --git a/Projects/UOContent.Tests/Tests/Mobiles/AI/ApproachTargetTests.cs b/Projects/UOContent.Tests/Tests/Mobiles/AI/ApproachTargetTests.cs index a952252a6..f3869ffef 100644 --- a/Projects/UOContent.Tests/Tests/Mobiles/AI/ApproachTargetTests.cs +++ b/Projects/UOContent.Tests/Tests/Mobiles/AI/ApproachTargetTests.cs @@ -49,7 +49,7 @@ public class ApproachTargetTests return false; } - private static ushort FirstImpassableItemId() + internal static ushort FirstImpassableItemId() { for (ushort id = 1; id < TileData.MaxItemValue; id++) { diff --git a/Projects/UOContent.Tests/Tests/Mobiles/AI/FamiliarAITests.cs b/Projects/UOContent.Tests/Tests/Mobiles/AI/FamiliarAITests.cs new file mode 100644 index 000000000..7d39e2963 --- /dev/null +++ b/Projects/UOContent.Tests/Tests/Mobiles/AI/FamiliarAITests.cs @@ -0,0 +1,557 @@ +using System; +using System.Collections.Generic; +using Server; +using Server.Items; +using Server.Mobiles; +using Server.Tests; +using Server.Tests.Mobiles.AI; +using Xunit; + +namespace UOContent.Tests.Mobiles.AI; + +// Timer-wheel driven (the real AITimer thinks and moves) against live Trammel statics. +[Collection("Sequential Pathfinding Tests")] +public class FamiliarAITests : IDisposable +{ + // NPCSpeeds is not configured in the fixture; pin the speeds. + private sealed class Wolf : DarkWolfFamiliar + { + public override void GetSpeeds(out double a, out double p) { a = 0.1; p = 0.1; } + } + + private sealed class Bat : VampireBatFamiliar + { + public override void GetSpeeds(out double a, out double p) { a = 0.1; p = 0.1; } + } + + private sealed class Wisp : ShadowWispFamiliar + { + public override void GetSpeeds(out double a, out double p) { a = 0.1; p = 0.1; } + } + + private sealed class Adder : DeathAdder + { + public override void GetSpeeds(out double a, out double p) { a = 0.1; p = 0.1; } + } + + private sealed class Minion : HordeMinionFamiliar + { + public override void GetSpeeds(out double a, out double p) { a = 0.1; p = 0.1; } + } + + private sealed class EnemyStub : Mobile + { + public EnemyStub() + { + Body = 0x190; + Str = 100; + } + } + + private static readonly Map _map = Map.Maps[1]; + private readonly List _created = new(); + + public FamiliarAITests() + { + TileDataRequirement.SkipIfMissing(); + Core._tickCount = 0; + Timer.Init(0); + } + + public void Dispose() + { + for (var i = _created.Count - 1; i >= 0; i--) + { + _created[i].Delete(); + } + } + + private static Point3D At(int x, int y) + { + _map.GetAverageZ(x, y, out _, out var z, out _); + return new Point3D(x, y, (sbyte)z); + } + + private PlayerMobile Master(int x, int y) + { + var p = new PlayerMobile(World.NewMobile); + p.DefaultMobileInit(); + p.Player = true; + p.Body = 0x190; + p.Str = p.Dex = p.Int = 100; + p.AddItem(new Backpack()); + p.MoveToWorld(At(x, y), _map); + _created.Add(p); + return p; + } + + private BaseFamiliar Familiar(int kind, PlayerMobile master, int x, int y) + { + BaseFamiliar f = kind switch + { + 0 => new Wolf(), + 1 => new Bat(), + 2 => new Wisp(), + 3 => new Adder(), + _ => new Minion() + }; + + Assert.True(BaseCreature.Summon(f, master, At(x, y), -1, TimeSpan.FromHours(1))); + _created.Add(f); + return f; + } + + private EnemyStub Enemy(int x, int y) + { + var e = new EnemyStub(); + e.MoveToWorld(At(x, y), _map); + _created.Add(e); + return e; + } + + // 8ms lockstep keeps the wheel and Core.TickCount in sync. + private static void RunFor(long ms) + { + var deadline = Core._tickCount + ms; + + while (Core._tickCount - deadline < 0) + { + Core._tickCount += 8; + Timer.Slice(Core._tickCount); + } + } + + private static bool RunUntil(Func condition, long maxMs) + { + var deadline = Core._tickCount + maxMs; + + while (Core._tickCount - deadline < 0) + { + if (condition()) + { + return true; + } + + Core._tickCount += 8; + Timer.Slice(Core._tickCount); + } + + return condition(); + } + + [SkippableFact] + public void UsesFamiliarAI_AndStaysOnComeOrder() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1500, 1600); + + Assert.IsType(f.AIObject); + Assert.Equal(OrderType.Come, f.ControlOrder); + Assert.Equal(0.1, f.ActiveSpeed); + Assert.Equal(0.1, f.PassiveSpeed); + } + + [SkippableFact] + public void Follows_WithoutBacktracking() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1500, 1600); + RunFor(400); // past the activation spread + p.MoveToWorld(At(1494, 1600), _map); + + var best = f.GetDistanceToSqrt(p); + var regressed = false; + var arrived = RunUntil( + () => + { + var d = f.GetDistanceToSqrt(p); + + if (d > best + 0.01) + { + regressed = true; + } + + best = Math.Min(best, d); + return f.InRange(p, 1); + }, + 3000 + ); + + Assert.True(arrived, "familiar must reach range 1 of its master"); + Assert.False(regressed, "familiar must never step away from the master while following"); + Assert.Equal(OrderType.Come, f.ControlOrder); + Assert.Equal(Point3D.Zero, f.Home); + } + + [SkippableFact] + public void Orders_AreInert() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1500, 1600); + RunFor(400); + + f.IssueOrder(OrderType.Stay, p); + + Assert.Equal(Point3D.Zero, f.Home); + Assert.Equal(0.1, f.CurrentSpeed); + + p.MoveToWorld(At(1495, 1600), _map); + Assert.True(RunUntil(() => f.InRange(p, 1), 3000), "a familiar under a Stay order still follows"); + } + + [SkippableTheory] + [InlineData(0, true)] // dark wolf + [InlineData(1, true)] // vampire bat + [InlineData(2, false)] // shadow wisp + [InlineData(3, false)] // death adder + [InlineData(4, true)] // horde minion + public void AssistsMastersTarget_OnlyIfCombatCapable(int kind, bool assists) + { + var p = Master(1500, 1600); + var f = Familiar(kind, p, 1501, 1600); + var e = Enemy(1495, 1600); + RunFor(400); + + p.Warmode = true; + p.Combatant = e; + + if (assists) + { + Assert.True( + RunUntil(() => f.Combatant == e && f.InRange(e, f.RangeFight), 4000), + "a combat familiar must engage the caster's target" + ); + Assert.True(f.Warmode); + Assert.Equal(OrderType.Come, f.ControlOrder); + } + else + { + RunFor(2000); + Assert.Null(f.Combatant); + Assert.False(f.Warmode); + Assert.True(f.InRange(p, 1), "a non-combat familiar stays with the caster"); + } + } + + [SkippableFact] + public void DropsTarget_WhenMasterHides() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1501, 1600); + var e = Enemy(1495, 1600); + RunFor(400); + p.Warmode = true; + p.Combatant = e; + Assert.True(RunUntil(() => f.Combatant == e, 2000)); + + p.Hidden = true; + Assert.True(RunUntil(() => f.Combatant == null && f.Hidden, 1000)); + } + + [SkippableFact] + public void Leash_NeverEngagesATargetFarFromTheMaster() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1501, 1600); + var e = Enemy(1500 - f.RangePerception - 4, 1600); // beyond the leash + RunFor(400); + p.Warmode = true; + p.Combatant = e; + RunFor(4000); + + Assert.Null(f.Combatant); + Assert.True(f.InRange(p, 1), "assist must not carry the familiar past the leash"); + } + + [SkippableFact] + public void Retaliates_IfCombatCapable_AndStaysOnComeOrder() + { + var p = Master(1500, 1600); + var wolf = Familiar(0, p, 1501, 1600); + var wisp = Familiar(2, p, 1499, 1600); + var e = Enemy(1503, 1600); + RunFor(400); + + // Combatant setter → DoHarmful → AggressiveAction with ChangingCombatant: the path that + // issues a stand-down pet an Attack order. + e.Combatant = wolf; + Assert.True(RunUntil(() => wolf.Combatant == e, 1000), "a combat familiar fights back"); + Assert.Equal(OrderType.Come, wolf.ControlOrder); + + e.Combatant = wisp; + RunFor(1000); + Assert.Null(wisp.Combatant); + Assert.False(wisp.Warmode); + } + + [SkippableFact] + public void KeepUp_SnapsWhenFarOnOpenGround() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1500, 1600); + RunFor(400); + + p.MoveToWorld(At(1500 - BaseFamiliar.KeepUpRange - 2, 1600), _map); + RunFor(300); // one think with a greedy step + + Assert.True(f.InRange(p, 1), "familiar must snap adjacent to a master 12 tiles away on open ground"); + } + + [SkippableFact] + public void KeepUp_DoesNotSnapWhileRouting() + { + // Britain inn L-desk: master north, familiar south; ~17-step detour. + var p = Master(1494, 1605); + var f = Familiar(0, p, 1493, 1614); + p.MoveToWorld(new Point3D(1494, 1605, 21), _map); + f.MoveToWorld(new Point3D(1493, 1614, 20), _map); + Server.Engines.Pathing.Cache.StepCache.Instance.Clear(); + + // Observed from the first tick so an early snap cannot hide behind "arrived". + var teleported = false; + var last = f.Location; + var arrived = RunUntil( + () => + { + if (f.Location != last && !f.InRange(last, 1)) + { + teleported = true; + } + + last = f.Location; + return f.InRange(p, 1); + }, + 8000 + ); + + Assert.True(arrived, "familiar walks the detour"); + Assert.False(teleported, "a working detour must not be short-circuited by a snap"); + } + + [SkippableFact] + public void KeepUp_SnapsAfterGiveUp() + { + var p = Master(1500, 1596); + var f = Familiar(0, p, 1500, 1602); + + // 5x5 ring, open 3x3 interior: a landing tile exists, no route reaches it. + var id = ApproachTargetTests.FirstImpassableItemId(); + Assert.NotEqual(0, id); + + for (var x = 1498; x <= 1502; x++) + { + for (var y = 1594; y <= 1598; y++) + { + if (x is > 1498 and < 1502 && y is > 1594 and < 1598) + { + continue; + } + + _map.GetAverageZ(x, y, out _, out var rz, out _); + _created.Add(new Item(World.NewItem) { ItemID = id, Map = _map, Location = new Point3D(x, y, (sbyte)rz) }); + } + } + + Server.Engines.Pathing.Cache.StepCache.Instance.Clear(); + RunFor(400); + + Assert.True( + RunUntil(() => f.InRange(p, 1), 15000), + "after giving up on an unreachable master the familiar snaps to it" + ); + } + + [SkippableFact] + public void MirrorsHidden_EvenWhileWalking() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1500, 1600); + RunFor(400); + + p.Hidden = true; + p.MoveToWorld(At(1495, 1600), _map); + Assert.True(RunUntil(() => f.Hidden, 500)); + + var stayedHidden = true; + var arrived = RunUntil( + () => + { + stayedHidden &= f.Hidden; + return f.InRange(p, 1); + }, + 3000 + ); + + Assert.True(arrived); + Assert.True(stayedHidden, "steps must not strip the mirror"); + + p.Hidden = false; + Assert.True(RunUntil(() => !f.Hidden, 500)); + } + + [SkippableFact] + public void Herding_TargetLocation_WinsAndClears() + { + var p = Master(1500, 1600); + var f = Familiar(4, p, 1500, 1600); + RunFor(400); + + var goal = new Point2D(1500, 1594); + f.TargetLocation = goal; + + Assert.True(RunUntil(() => f.TargetLocation == null, 6000), "familiar walks to the herding target"); + Assert.True(f.InRange(goal, 1)); + } + + [SkippableFact] + public void NonCombatFamiliar_RefusesAnyCombatant() + { + var p = Master(1500, 1600); + var wisp = Familiar(2, p, 1501, 1600); + var e = Enemy(1502, 1600); + + wisp.Combatant = e; + Assert.Null(wisp.Combatant); + } + + [SkippableFact] + public void HiddenCaster_FamiliarRefusesRetaliation() + { + var p = Master(1500, 1600); + var wolf = Familiar(0, p, 1501, 1600); + var e = Enemy(1502, 1600); + RunFor(400); + p.Hidden = true; + Assert.True(RunUntil(() => wolf.Hidden, 500)); + + e.Combatant = wolf; + + // Synchronous: the veto is at the setter. + Assert.Null(wolf.Combatant); + Assert.False(wolf.Warmode); + RunFor(500); + Assert.Null(wolf.Combatant); + Assert.True(wolf.Hidden); + } + + [SkippableFact] + public void LeftBehind_StandsDown() + { + var p = Master(1500, 1600); + var wolf = Familiar(0, p, 1501, 1600); + var e = Enemy(1495, 1600); + RunFor(400); + p.Warmode = true; + p.Combatant = e; + Assert.True(RunUntil(() => wolf.Combatant == e, 2000)); + + p.MoveToWorld(new Point3D(1500, 1600, p.Z), Map.Felucca); + Assert.True(RunUntil(() => wolf.Combatant == null && !wolf.Warmode, 500)); + } + + [SkippableFact] + public void Herding_OutranksCombat_AndStandsDown() + { + var p = Master(1500, 1600); + var f = Familiar(4, p, 1501, 1600); + var e = Enemy(1502, 1600); + RunFor(400); + p.Warmode = true; + p.Combatant = e; + Assert.True(RunUntil(() => f.Combatant == e, 2000)); + + // Caster visible and fighting: only herding clears this. + var goal = new Point2D(1500, 1594); + f.TargetLocation = goal; + var distBefore = f.GetDistanceToSqrt(goal); + RunFor(300); + + Assert.Null(f.Combatant); + Assert.False(f.Warmode); + Assert.NotNull(f.TargetLocation); + Assert.True(f.GetDistanceToSqrt(goal) < distBefore, "the fetch makes progress while combat is set aside"); + Assert.Same(e, p.Combatant); + } + + [SkippableFact] + public void AssistsAgainstWhatTheCastersPetIsFighting() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1501, 1600); + var e = Enemy(1496, 1600); + var pet = new PetTestStub(); + pet.MoveToWorld(At(1497, 1600), _map); + pet.SetControlMaster(p); + _created.Add(pet); + RunFor(400); + + // The pet attacks; the caster is credited indirectly without a Combatant. + pet.Combatant = e; + p.DoHarmful(e, true); + e.Combatant = pet; + Assert.Null(p.Combatant); + + Assert.True( + RunUntil(() => f.Combatant == e && f.InRange(e, f.RangeFight), 4000), + "familiar joins the fight the caster's pet is in" + ); + } + + [SkippableFact] + public void DefendsAnAttackedCaster_WhoseOwnCombatantExpired() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1501, 1600); + var e = Enemy(1496, 1600); + RunFor(400); + + e.Combatant = p; + p.Combatant = null; // expired + Assert.Null(p.Combatant); + + Assert.True( + RunUntil(() => f.Combatant == e && f.InRange(e, f.RangeFight), 4000), + "familiar defends the caster from a live aggressor" + ); + } + + [SkippableFact] + public void DropsATarget_ThatNoLongerFightsAnyone() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1501, 1600); + var e = Enemy(1495, 1600); + RunFor(400); + p.Warmode = true; + p.Combatant = e; + Assert.True(RunUntil(() => f.Combatant == e, 2000)); + + // Caster stops, target disengages. + p.Combatant = null; + p.Warmode = false; + e.Combatant = null; + + Assert.True(RunUntil(() => f.Combatant == null && f.InRange(p, 1), 4000), "familiar disengages and returns"); + } + + [SkippableFact] + public void AssistEnd_LeavesNoStaleMoveIntent() + { + var p = Master(1500, 1600); + var f = Familiar(0, p, 1501, 1600); + var e = Enemy(1495, 1600); + RunFor(400); + p.Warmode = true; + p.Combatant = e; + Assert.True(RunUntil(() => f.Combatant == e, 2000)); + + // Assist ends with the familiar already beside the caster (MoveTo's arrival return). + f.MoveToWorld(At(1501, 1600), _map); + p.Combatant = null; + p.Warmode = false; + e.Combatant = null; + Assert.True(RunUntil(() => f.Combatant == null, 500)); + + Assert.False(f.AIObject.TryGetMoveWake(out _), "no pursuit may survive the stand-down"); + } +} diff --git a/Projects/UOContent.Tests/Tests/Mobiles/AI/ForcedAITests.cs b/Projects/UOContent.Tests/Tests/Mobiles/AI/ForcedAITests.cs new file mode 100644 index 000000000..e21390ef3 --- /dev/null +++ b/Projects/UOContent.Tests/Tests/Mobiles/AI/ForcedAITests.cs @@ -0,0 +1,59 @@ +using Server; +using Server.Mobiles; +using Xunit; + +namespace UOContent.Tests.Mobiles.AI; + +[Collection("Sequential UOContent Tests")] +public class ForcedAITests +{ + private sealed class CountingAI : BaseAI + { + public CountingAI(BaseCreature m) : base(m) + { + } + } + + private sealed class ForcedStub : BaseCreature + { + public int Constructions; + + public ForcedStub() : base(AIType.AI_Melee) + { + } + + public override void GetSpeeds(out double activeSpeed, out double passiveSpeed) + { + activeSpeed = 0.2; + passiveSpeed = 0.4; + } + + // Not sector-gated: a BaseAI ctor starts its timer immediately. + public override bool PlayerRangeSensitive => false; + + protected override BaseAI ForcedAI + { + get + { + Constructions++; + return new CountingAI(this); + } + } + } + + [Fact] + public void ChangeAIType_ConstructsForcedAIOnce() + { + var bc = new ForcedStub(); + + try + { + Assert.Equal(1, bc.Constructions); + Assert.IsType(bc.AIObject); + } + finally + { + bc.Delete(); + } + } +} diff --git a/Projects/UOContent.Tests/Tests/Mobiles/AI/HerdingTests.cs b/Projects/UOContent.Tests/Tests/Mobiles/AI/HerdingTests.cs new file mode 100644 index 000000000..357a39979 --- /dev/null +++ b/Projects/UOContent.Tests/Tests/Mobiles/AI/HerdingTests.cs @@ -0,0 +1,51 @@ +using Server; +using Server.Engines.Pathing.Cache; +using Server.Mobiles; +using Server.Tests; +using Xunit; + +namespace UOContent.Tests.Mobiles.AI; + +// Driven manually against live map statics; the pathfinder's buffers are not reentrant. +[Collection("Sequential Pathfinding Tests")] +public class HerdingTests +{ + private sealed class Stub : BaseCreature + { + public Stub(Serial serial) : base(serial) => Body = 0xC9; + } + + [SkippableFact] + public void HerdedCreature_ReachesTheTile_AndClearsTargetLocation() + { + TileDataRequirement.SkipIfMissing(); + var map = Map.Maps[1]; + map.GetAverageZ(1500, 1600, out _, out var z, out _); + + var bc = new Stub(World.NewMobile); + bc.DefaultMobileInit(); + bc.MoveToWorld(new Point3D(1500, 1600, (sbyte)z), map); + BaseAI ai = new AnimalAI(bc); + ai.AITimer?.Stop(); + StepCache.Instance.Clear(); + + try + { + var goal = new Point2D(1500, 1595); + bc.TargetLocation = goal; + + for (var i = 0; i < 40 && bc.TargetLocation != null; i++) + { + ai.NextMove = 0; + ai.CheckHerding(); + } + + Assert.Null(bc.TargetLocation); + Assert.Equal(goal, new Point2D(bc.X, bc.Y)); + } + finally + { + bc.Delete(); + } + } +} diff --git a/Projects/UOContent/Items/Weapons/BaseWeapon.cs b/Projects/UOContent/Items/Weapons/BaseWeapon.cs index d48824670..df5361a13 100644 --- a/Projects/UOContent/Items/Weapons/BaseWeapon.cs +++ b/Projects/UOContent/Items/Weapons/BaseWeapon.cs @@ -2102,14 +2102,10 @@ public abstract partial class BaseWeapon { var caster = bc.ControlMaster ?? bc.SummonMaster; - if (caster != null && caster.Map == bc.Map && caster.InRange(bc, 2)) + if (caster != null && caster.Map == bc.Map) { caster.Hits += damage; } - else - { - bc.Hits += damage; - } } if (Core.AOS) diff --git a/Projects/UOContent/Mobiles/AI/BaseAI/AIMovement.cs b/Projects/UOContent/Mobiles/AI/BaseAI/AIMovement.cs index 381958d68..5878f0552 100644 --- a/Projects/UOContent/Mobiles/AI/BaseAI/AIMovement.cs +++ b/Projects/UOContent/Mobiles/AI/BaseAI/AIMovement.cs @@ -39,6 +39,11 @@ public abstract partial class BaseAI private bool _approachGaveUp; private Point3D _approachGaveUpGoalLoc; + /// Which exit the last (via or + /// ) took. A retreat step does not + /// classify. + 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; } /// /// 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 (0 = onto the tile). Returns false on + /// arrival or when genuinely unable to make progress. /// - 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; } + /// Drops the path, stall state, and move intent (after a relocation). + 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; } diff --git a/Projects/UOContent/Mobiles/AI/BaseAI/ApproachOutcome.cs b/Projects/UOContent/Mobiles/AI/BaseAI/ApproachOutcome.cs new file mode 100644 index 000000000..b7671b2bc --- /dev/null +++ b/Projects/UOContent/Mobiles/AI/BaseAI/ApproachOutcome.cs @@ -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 . * + ************************************************************************/ + +namespace Server.Mobiles; + +/// Which exit took, for policies that need more +/// than its bool. +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 +} diff --git a/Projects/UOContent/Mobiles/AI/BaseAI/BaseAI.cs b/Projects/UOContent/Mobiles/AI/BaseAI/BaseAI.cs index e762c5c61..3b5e1dc5e 100644 --- a/Projects/UOContent/Mobiles/AI/BaseAI/BaseAI.cs +++ b/Projects/UOContent/Mobiles/AI/BaseAI/BaseAI.cs @@ -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; } diff --git a/Projects/UOContent/Mobiles/AI/FamiliarAI.cs b/Projects/UOContent/Mobiles/AI/FamiliarAI.cs new file mode 100644 index 000000000..fcaf96c69 --- /dev/null +++ b/Projects/UOContent/Mobiles/AI/FamiliarAI.cs @@ -0,0 +1,268 @@ +/************************************************************************* + * ModernUO * + * Copyright 2019-2026 - ModernUO Development Team * + * Email: hi@modernuo.com * + * File: FamiliarAI.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 . * + ************************************************************************/ + +using System.Collections.Generic; + +namespace Server.Mobiles; + +/// +/// Necromancy familiars: command-immune, glued to the caster, assist its fights if combat-capable, +/// snap to it when outpaced or stuck. and share one decision. +/// +public class FamiliarAI : BaseAI +{ + public FamiliarAI(BaseFamiliar familiar) : base(familiar) + { + } + + private BaseFamiliar Familiar => (BaseFamiliar)Mobile; + + // Assist targets, and the familiar itself, stay within this of the caster. + public int LeashRange => Mobile.RangePerception; + + public override bool CanDetectHidden => false; + + public override bool Think() => Act(); + + public override bool Obey() => Act(); + + // Command immunity: no issue-phase side effects; rests on Come so TeleportPets still applies. + public override OrderType IssueOrder( + OrderType order, OrderType previous, Mobile issuer, bool resuming, Mobile interruptedTarget + ) + { + AITimer.Prod(); + return Mobile.Controlled ? OrderType.Come : OrderType.None; + } + + public override void OnAggressiveAction(Mobile aggressor) + { + if (!Familiar.AssistsMaster || aggressor.Hidden || Familiar.ControlMaster?.Hidden == true) + { + return; + } + + if (Mobile.Combatant == null) + { + Mobile.Warmode = true; + Mobile.Combatant = aggressor; + return; + } + + base.OnAggressiveAction(aggressor); + } + + private bool Act() + { + var master = Familiar.ControlMaster; + + // Deletion is BaseFamiliar.OnThink's. + if (Mobile.Deleted || master?.Deleted != false) + { + return true; + } + + // Left behind: stand down until TeleportPets or the unsummon. + if (master.Map != Mobile.Map) + { + StandDown(); + return true; + } + + // Herding outranks combat. + if (Mobile.TargetLocation != null) + { + StandDown(); + + if (CheckHerding()) + { + DebugSay("Fetching for my master."); + return true; + } + } + + if (Familiar.AssistsMaster && !master.Hidden && TryAssist(master)) + { + return true; + } + + Follow(master); + return true; + } + + // The caster's target; else the closest mobile in a fight with the caster's side that is + // still fighting one of us (the caster's own Combatant expires while a monster keeps hitting). + private bool TryAssist(Mobile master) + { + var target = master.Combatant; + + if (!IsValidAssistTarget(master, target)) + { + target = Mobile.Combatant; + + if (!IsValidAssistTarget(master, target) || !IsFightingUs(master, target)) + { + target = FindAggressor(master); + + if (target == null) + { + return false; + } + } + } + + if (!Mobile.InRange(master, LeashRange)) + { + DebugSay("Too far from my master; returning."); + return false; + } + + Mobile.Warmode = true; + Mobile.Combatant = target; + + if (Mobile.Combatant != target) + { + return false; // setter refused it + } + + Mobile.SetCurrentSpeedToActive(); + this.DebugSayFormatted($"Assisting my master against {target.Name}."); + MoveTo(target, Mobile.RangeFight); + return true; + } + + private bool IsFightingUs(Mobile master, Mobile target) + { + var combatant = target.Combatant; + + return combatant == Mobile || combatant == master || + combatant is BaseCreature { Controlled: true } pet && pet.ControlMaster == master; + } + + // Closest mobile in a fight with the caster's side. + private Mobile FindAggressor(Mobile master) + { + Mobile best = null; + var bestDist = double.MaxValue; + + ScanAggression(master, master.Aggressors, false, ref best, ref bestDist); + ScanAggression(master, Mobile.Aggressors, false, ref best, ref bestDist); + ScanAggression(master, master.Aggressed, true, ref best, ref bestDist); + + return best; + } + + // defenders: an Aggressed list, read the Defender. + private void ScanAggression( + Mobile master, List list, bool defenders, ref Mobile best, ref double bestDist + ) + { + for (var i = 0; i < list.Count; i++) + { + var info = list[i]; + + if (info.Expired) + { + continue; + } + + var other = defenders ? info.Defender : info.Attacker; + + if (other == best || !IsValidAssistTarget(master, other) || !IsFightingUs(master, other)) + { + continue; + } + + var dist = master.GetDistanceToSqrt(other); + + if (dist < bestDist) + { + best = other; + bestDist = dist; + } + } + } + + private bool IsValidAssistTarget(Mobile master, Mobile target) => + target?.Deleted == false && target != Mobile && target != master && target.Alive && + !target.Hidden && target.Map == Mobile.Map && !target.IsDeadBondedPet && + target.AccessLevel == AccessLevel.Player && master.InRange(target, LeashRange) && + Mobile.CanBeHarmful(target, false); + + // Clears the move intent too, or a move-wake resumes the abandoned pursuit. + private void StandDown() + { + Mobile.Warmode = false; + Mobile.Combatant = null; + Mobile.SetCurrentSpeedToActive(); + ClearMoveIntent(); + } + + private void Follow(Mobile master) + { + StandDown(); + + MoveTo(master, 1); + TryKeepUp(master); + } + + // Outpaced on open ground, or given up: snap. A live detour finishes; Blocked is still counting. + private void TryKeepUp(Mobile master) + { + var snap = LastApproach switch + { + ApproachOutcome.GaveUp => true, + ApproachOutcome.DirectProgress => !Mobile.InRange(master, BaseFamiliar.KeepUpRange), + _ => false + }; + + if (!snap || !TryFindLanding(master, out var loc)) + { + return; + } + + DebugSay("Keeping up with my master."); + Mobile.SetLocation(loc, true); + ResetApproachState(); + } + + private static readonly (int dx, int dy)[] _landingRing = + [ + (0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, 1), (1, -1), (-1, -1) + ]; + + // An adjacent tile on the caster's floor this creature can stand on. + private bool TryFindLanding(Mobile master, out Point3D loc) + { + var map = master.Map; + var start = Utility.Random(_landingRing.Length); // no favoured side + + for (var i = 0; i < _landingRing.Length; i++) + { + var (dx, dy) = _landingRing[(start + i) % _landingRing.Length]; + var x = master.X + dx; + var y = master.Y + dy; + + if (map.CanSpawnMobile(x, y, master.Z - 5, master.Z + 5, Mobile.CanSwim, Mobile.CantWalk, out var z)) + { + loc = new Point3D(x, y, z); + return true; + } + } + + loc = Point3D.Zero; + return false; + } +} diff --git a/Projects/UOContent/Mobiles/BaseCreature.cs b/Projects/UOContent/Mobiles/BaseCreature.cs index 077e47174..be4eea9e9 100644 --- a/Projects/UOContent/Mobiles/BaseCreature.cs +++ b/Projects/UOContent/Mobiles/BaseCreature.cs @@ -2524,9 +2524,12 @@ namespace Server.Mobiles { AIObject?.AITimer.Stop(); - if (ForcedAI != null) + // Read once: each read constructs an AI whose ctor may start its timer. + var forced = ForcedAI; + + if (forced != null) { - AIObject = ForcedAI; + AIObject = forced; return; } @@ -3102,13 +3105,20 @@ namespace Server.Mobiles pack?.DisplayTo(from); } - if (DeathAdderCharmable && from.CanBeHarmful(this, false)) + if (DeathAdderCharmable && from.CanBeHarmful(this, false) && + SummonFamiliarSpell.Table.TryGetValue(from, out var bc) && bc is DeathAdder { Deleted: false } deathAddr && + deathAddr.Map == from.Map) { - if (SummonFamiliarSpell.Table.TryGetValue(from, out var bc) && (bc as DeathAdder)?.Deleted == false) + if (from.NetState.HasProtocolChanges(ProtocolChanges.Version7000)) + { + from.SendLocalizedMessage(1114362); // You charm the snake. Select a target to attack. + } + else { from.SendAsciiMessage("You charm the snake. Select a target to attack."); - from.Target = new DeathAdderCharmTarget(this); } + + from.Target = new DeathAdderCharmTarget(this); } if (MLQuestSystem.Enabled && CanGiveMLQuest && from is PlayerMobile mobile) diff --git a/Projects/UOContent/Mobiles/Familiars/BaseFamiliar.cs b/Projects/UOContent/Mobiles/Familiars/BaseFamiliar.cs index 46d939f3b..6da24edfe 100644 --- a/Projects/UOContent/Mobiles/Familiars/BaseFamiliar.cs +++ b/Projects/UOContent/Mobiles/Familiars/BaseFamiliar.cs @@ -8,13 +8,16 @@ namespace Server.Mobiles; [SerializationGenerator(0, false)] public abstract partial class BaseFamiliar : BaseCreature { - private bool m_LastHidden; + // Open-ground distance beyond which the familiar snaps to the caster. + public const int KeepUpRange = 10; public BaseFamiliar() : base(AIType.AI_Melee) { - SetSpeed(0.1, 0.11); + SetSpeed(0.1, 0.1); } + protected override BaseAI ForcedAI => new FamiliarAI(this); + public override bool BardImmune => true; public override Poison PoisonImmune => Poison.Lethal; public override bool Commandable => false; @@ -22,89 +25,68 @@ public abstract partial class BaseFamiliar : BaseCreature public override bool PlayerRangeSensitive => false; - public virtual void RangeCheck() + // Joins the caster's fights; false never fights. + public virtual bool AssistsMaster => true; + + // FamiliarAI decides whether it fights, not the ML stand-down rule. + public override bool StandsDownOnCommand => false; + + // A wounded familiar still keeps up. + public override bool ReduceSpeedWithDamage => false; + + // The one choke point for "never fights" / "not while the caster is hidden": + // BaseCreature.AggressiveAction assigns Combatant unconditionally. GetCPA does not inherit. + [CommandProperty(AccessLevel.GameMaster)] + public override Mobile Combatant { - if (Deleted || ControlMaster?.Deleted != false) + get => base.Combatant; + set { - return; - } - - var range = RangeHome - 2; - - if (InRange(ControlMaster.Location, RangeHome)) - { - return; - } - - var master = ControlMaster; - - var m_Loc = Point3D.Zero; - - if (Map != master.Map) - { - return; - } - - var x = X > master.X ? master.X + range : master.X - range; - var y = Y > master.Y ? master.Y + range : master.Y - range; - - for (var i = 0; i < 10; i++) - { - m_Loc.X = x + Utility.RandomMinMax(-1, 1); - m_Loc.Y = y + Utility.RandomMinMax(-1, 1); - - m_Loc.Z = Map.GetAverageZ(m_Loc.X, m_Loc.Y); - - if (Map.CanSpawnMobile(m_Loc)) + if (value != null && (!AssistsMaster || ControlMaster?.Hidden == true)) { - break; + return; } - m_Loc = master.Location; - } - - if (!Deleted) - { - SetLocation(m_Loc, true); + base.Combatant = value; } } public override void OnThink() { - var master = ControlMaster; + base.OnThink(); if (Deleted) { return; } + var master = ControlMaster; + if (master?.Deleted != false) { DropPackContents(); - EndRelease(null); + Delete(); return; } - RangeCheck(); - - if (m_LastHidden != master.Hidden) + // Compare our own state: Mobile.OnMove reveals a stepping NPC. + if (Hidden != master.Hidden) { - Hidden = m_LastHidden = master.Hidden; + Hidden = master.Hidden; + + if (Hidden) + { + Warmode = false; // nulls Combatant + } } + } - if (AIObject?.WalkMobileRange(master, 5, 1, 1) == true) + // Nothing reveals a hidden caster's familiar. + public override void RevealingAction() + { + if (ControlMaster?.Hidden != true) { - Warmode = master.Warmode; - Combatant = master.Combatant; - - CurrentSpeed = 0.1; - } - else - { - Warmode = false; - FocusMob = Combatant = null; - - CurrentSpeed = 0.01; + base.RevealingAction(); } } diff --git a/Projects/UOContent/Mobiles/Familiars/DeathAdder.cs b/Projects/UOContent/Mobiles/Familiars/DeathAdder.cs index ebf174ddc..2a802ab67 100644 --- a/Projects/UOContent/Mobiles/Familiars/DeathAdder.cs +++ b/Projects/UOContent/Mobiles/Familiars/DeathAdder.cs @@ -40,5 +40,7 @@ public partial class DeathAdder : BaseFamiliar public override string CorpseName => "a death adder corpse"; public override string DefaultName => "a death adder"; + public override bool AssistsMaster => false; + public override Poison HitPoison => Utility.RandomDouble() < 0.8 ? Poison.Greater : Poison.Deadly; } diff --git a/Projects/UOContent/Mobiles/Familiars/HordeMinion.cs b/Projects/UOContent/Mobiles/Familiars/HordeMinion.cs index 23750daef..8df0f92fa 100644 --- a/Projects/UOContent/Mobiles/Familiars/HordeMinion.cs +++ b/Projects/UOContent/Mobiles/Familiars/HordeMinion.cs @@ -10,7 +10,7 @@ namespace Server.Mobiles; [SerializationGenerator(0, false)] public partial class HordeMinionFamiliar : BaseFamiliar { - private DateTime m_NextPickup; + private long _nextPickup; public HordeMinionFamiliar() { @@ -59,51 +59,60 @@ public partial class HordeMinionFamiliar : BaseFamiliar { base.OnThink(); - if (Core.Now < m_NextPickup) + if (Core.TickCount - _nextPickup <= 0) { return; } - m_NextPickup = Core.Now + TimeSpan.FromSeconds(Utility.RandomMinMax(5, 10)); - - var pack = Backpack; - - if (pack == null) - { - return; - } - - using var queue = PooledRefQueue.Create(); - foreach (var item in GetItemsInRange(2)) - { - if (item.Movable && item.Stackable) - { - queue.Enqueue(item); - } - } - var pickedUp = 3; - while (pickedUp > 0 && queue.Count > 0) + try { - var item = queue.Dequeue(); + var pack = Backpack; - if (!pack.CheckHold(this, item, false, true)) + if (pack == null) { return; } - NextActionTime = Core.TickCount; - - Lift(item, item.Amount, out var rejected, out var _); - - if (rejected) + using var queue = PooledRefQueue.Create(); + foreach (var item in GetItemsInRange(2)) { - continue; + if (item.Movable && item.Stackable) + { + queue.Enqueue(item); + } } - Drop(this, Point3D.Zero); - pickedUp--; + while (pickedUp > 0 && queue.Count > 0) + { + var item = queue.Dequeue(); + + if (!pack.CheckHold(this, item, false, true)) + { + return; + } + + NextActionTime = Core.TickCount; + + Lift(item, item.Amount, out var rejected, out var _); + + if (rejected) + { + continue; + } + + Drop(this, Point3D.Zero); + pickedUp--; + } + } + finally + { + if (pickedUp < 3) + { + // 5-10s + _nextPickup = Core.TickCount + Utility.Random(5000, 5000); + } } } diff --git a/Projects/UOContent/Mobiles/Familiars/ShadowWisp.cs b/Projects/UOContent/Mobiles/Familiars/ShadowWisp.cs index 989ebf354..004d9cb9f 100644 --- a/Projects/UOContent/Mobiles/Familiars/ShadowWisp.cs +++ b/Projects/UOContent/Mobiles/Familiars/ShadowWisp.cs @@ -41,6 +41,8 @@ public partial class ShadowWispFamiliar : BaseFamiliar public override string CorpseName => "a shadow wisp corpse"; public override string DefaultName => "a shadow wisp"; + public override bool AssistsMaster => false; + public override void OnThink() { base.OnThink(); diff --git a/Projects/UOContent/Skills/AnimalTaming.cs b/Projects/UOContent/Skills/AnimalTaming.cs index b34017fb7..5132ea2f2 100644 --- a/Projects/UOContent/Skills/AnimalTaming.cs +++ b/Projects/UOContent/Skills/AnimalTaming.cs @@ -37,9 +37,8 @@ namespace Server.SkillHandlers } public static bool CheckMastery(Mobile tamer, BaseCreature creature) => - SummonFamiliarSpell.Table.TryGetValue(tamer, out var bc) - && bc is DarkWolfFamiliar { Deleted: false } - && creature is DireWolf or GreyWolf or TimberWolf or WhiteWolf or BakeKitsune; + SummonFamiliarSpell.Table.TryGetValue(tamer, out var bc) && + bc is DarkWolfFamiliar { Deleted: false } && creature is DireWolf or GreyWolf or TimberWolf or WhiteWolf; public static bool MustBeSubdued(BaseCreature bc) => bc.Owners.Count <= 0 && bc.SubdueBeforeTame && bc.Hits > bc.HitsMax / 10; diff --git a/dev-docs/content-patterns.md b/dev-docs/content-patterns.md index d2d301306..85ce6075c 100644 --- a/dev-docs/content-patterns.md +++ b/dev-docs/content-patterns.md @@ -222,6 +222,16 @@ public partial class ForestWolf : BaseCreature | `AI_Berserk` | Mindless aggressors | | `AI_Thief` | Pickpockets | +**Bespoke policy: `ForcedAI`.** A creature whose behavior is not one of the stock AIs +overrides `protected override BaseAI ForcedAI => new MyAI(this);` and `ChangeAIType` uses that +instance regardless of `AIType` (`CloneAI` for mirror images, `FamiliarAI` for necromancy +familiars, `FactionGuardAI`, `SpellbinderAI`). The property is read exactly once per +`ChangeAIType`; do not put side effects in it. Movement or order decisions belong in the AI +class — `OnThink` is for content extras (see the excess-call contract below). A controlled +creature is dispatched through `Obey()`, an uncontrolled one through `Think()`; an AI that owns +both routes them into one decision (`FamiliarAI.Act`). Overriding `IssueOrder` to return a +fixed order is how "command immunity" is expressed without bypassing the order machinery. + ### Fight Modes | FightMode | Behavior | |---|---| diff --git a/dev-docs/pathfinding.md b/dev-docs/pathfinding.md index 861a41d75..907cdea47 100644 --- a/dev-docs/pathfinding.md +++ b/dev-docs/pathfinding.md @@ -55,6 +55,21 @@ Per think-tick decision: Open terrain stays on the greedy fast path and never builds a `PathFollower` — pathfinding only engages when greedy movement stalls. +### Approach outcome + +`ApproachTarget` returns a `bool` for its callers, but records which exit it took in +`BaseAI.LastApproach` (`ApproachOutcome`): `Arrived`, `Waiting` (frozen/casting/throttled), +`DirectProgress` (greedy step closed the distance), `Routing` (a `PathFollower` is working a +detour), `Blocked` (move-eligible tick, no step, stall counter still running), `GaveUp`, or +`InvalidGoal`. A policy that needs to distinguish "outpaced on open ground" from "stuck" +reads this after its `MoveTo`/`WalkMobileRange` call instead of running a second scheduler — +`FamiliarAI.TryKeepUp` is the reference use: snap to the caster on `DirectProgress` beyond +`KeepUpRange`, or on `GaveUp`; never on `Routing`. After a policy-driven relocation call +`ResetApproachState()` so the next approach starts fresh (`OnTeleported` only repaths). + +`MoveToPoint(goal, range)` takes the arrival range explicitly; herding passes 0 because +`CheckHerding` ends on the tile (its exit is `distance < 1`), and the default 1 stops beside it. + ## The algorithm: windowed A* with hard limits `BitmapAStarAlgorithm` (`Find`) is a **bounded local** pathfinder, not a global one. Key