Snapshot for release 2026.10.27.1 (internal 48d0d60)

This commit is contained in:
Tom Bohar 2026-10-27 08:41:02 -04:00
commit 2dd532963f
31 changed files with 2995 additions and 118 deletions

View file

@ -29,6 +29,7 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.cs" Link="Linked\DungeonPathfinder.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.Rooms.cs" Link="Linked\DungeonPathfinder.Rooms.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.Sweep.cs" Link="Linked\DungeonPathfinder.Sweep.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.Portals.cs" Link="Linked\DungeonPathfinder.Portals.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonGeometry.cs" Link="Linked\DungeonGeometry.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPatrolOptions.cs" Link="Linked\DungeonPatrolOptions.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonHazardSurfaces.cs" Link="Linked\DungeonHazardSurfaces.cs" />

View file

@ -27,6 +27,8 @@ namespace RynthCore.PatrolProof;
// floors off, wall distances, look-in sizes): patrol cells, waypoints, lap length
// pockets for each start, the dead-end areas off the reachable cells (largest first, the
// ones hanging off the trunk), their rooms and the smaller areas inside them
// portal x,y,z[,r] a portal the patrol keeps out of (world metres; r the keep-out radius, default
// 3.5 m), as BuildDunPatrol passes the live ones; repeatable. One line per portal.
// The start cell is handled as BuildDunPatrol does: a start in a hazard moves to NearestSafeCell.
internal static class Waypoints
{
@ -40,6 +42,7 @@ internal static class Waypoints
var inv = CultureInfo.InvariantCulture;
var extra = new HashSet<uint>();
var fileCells = new HashSet<uint>();
var portals = new List<PatrolPortal>();
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
@ -66,6 +69,12 @@ internal static class Waypoints
if (uint.TryParse(l.Replace("0x", ""), NumberStyles.HexNumber, null, out uint c)) fileCells.Add(c);
}
}
else if (a == "portal" && i + 1 < args.Length)
{
double[] v = args[++i].Split(',').Select(t => double.Parse(t, inv)).ToArray();
portals.Add(new PatrolPortal { Id = (uint)portals.Count + 1, Name = "given", X = v[0], Y = v[1], Z = v[2],
Radius = v.Length > 3 ? v[3] : DungeonPathfinder.PortalKeepOutDefault });
}
else if (a == "hz" && i + 1 < args.Length)
foreach (string t in args[++i].Split(',', StringSplitOptions.RemoveEmptyEntries))
extra.Add(uint.Parse(t.Replace("0x", ""), NumberStyles.HexNumber));
@ -80,7 +89,7 @@ internal static class Waypoints
if (!loader.Initialize(acDir)) { Console.WriteLine("Geometry loader failed: " + loader.StatusMessage); return 1; }
var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
var surfaceCells = DungeonHazardSurfaces.ComputeHazardCells(lb, loader.CellDat, loader.PortalDat);
var surfaceCells = DungeonHazardSurfaces.ComputeHazardCells(lb, loader.DungeonLOS, loader.PortalDat);
Console.WriteLine($"Landblock 0x{lb:X4}: {graph.Count} cells; hazard textures {DungeonHazardSurfaces.HazardTextureCount} -> {surfaceCells.Count} Detector C cells: {Ids(surfaceCells)}");
if (fileCells.Count > 0) Console.WriteLine($" hzfile cells: {Ids(fileCells)}");
if (extra.Count > 0) Console.WriteLine($" hz cells: {Ids(extra)}");
@ -120,15 +129,22 @@ internal static class Waypoints
var log = new Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo>(ReferenceEqualityComparer.Instance);
DungeonPathfinder.PointLog = log;
NavRouteParser route;
try { route = DungeonPathfinder.BuildPatrolRoute(graph, start, hazards, geo, opt); }
List<PortalAvoidance> avoided;
try
{
route = DungeonPathfinder.BuildPatrolRoute(graph, start, hazards, geo, opt, portals);
avoided = DungeonPathfinder.LastPortalAvoidance;
}
finally { DungeonPathfinder.PointLog = null; }
var lines = DungeonPathfinder.DescribePatrol(route, graph, geo, hazards, log);
if (avoided != null) lines.AddRange(avoided.Select(r => "wp " + r.Describe()));
Console.WriteLine();
Console.WriteLine($"== start {s0:X8}{(start != s0 ? $" (moved to safe {start:X8})" : "")}, hazards {name} ({cells.Count})");
Console.WriteLine(" " + EnteredRooms(route, graph, geo, hazards, log));
foreach (string l in lines)
{
bool isSummary = l.StartsWith("wp summary", StringComparison.Ordinal) || l.StartsWith("wp main route", StringComparison.Ordinal);
bool isSummary = l.StartsWith("wp summary", StringComparison.Ordinal) || l.StartsWith("wp main route", StringComparison.Ordinal)
|| l.StartsWith("wp portal", StringComparison.Ordinal);
if (summaryOnly && !isSummary) continue;
if (tinyOnly && !isSummary && !IsTiny(l)) continue;
Console.WriteLine(" " + l);

View file

@ -23,6 +23,9 @@ internal static class Program
/// <summary>CreatureProfileStore's folder before Main pointed it at the scratch folder.</summary>
public static string LiveCreatureFolder { get; private set; } = "";
/// <summary>DungeonHazardSurfaces' folder (HazardTextures.txt) before Main pointed it at the scratch folder.</summary>
public static string LiveHazardTextureFolder { get; private set; } = "";
private static int Main(string[] args)
{
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
@ -39,6 +42,10 @@ internal static class Program
// A sighted lava/acid hotspot is persisted under C:\Games\RynthSuite\RynthAi\DungeonHazards.
LiveHazardFolder = RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder;
RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder = Path.Combine(TempRoot, "DungeonHazards");
// Detector C's flagged floor textures are persisted to C:\Games\RynthSuite\RynthAi\HazardTextures.txt.
LiveHazardTextureFolder = RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Folder;
RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Folder = Path.Combine(TempRoot, "HazardTextures");
RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Reload();
// Appraised creatures are saved to C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json.
LiveCreatureFolder = RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder;
RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder = Path.Combine(TempRoot, "CreatureData");
@ -64,6 +71,7 @@ internal static class Program
PatrolDoorwayTests.Register(runner);
PatrolSettingsTests.Register(runner);
PatrolPocketTests.Register(runner);
PatrolPortalTests.Register(runner);
BuffTests.Register(runner);
SpellCatalogTests.Register(runner);
CombatMathTests.Register(runner);
@ -110,6 +118,7 @@ internal static class Program
NavOverlayTests.Register(runner);
ActionPacingTests.Register(runner);
HazardEscapeTests.Register(runner);
HazardFloorTests.Register(runner);
ManaStoneChoiceTests.Register(runner);
CustomDebuffTests.Register(runner);
DebuffRenewTests.Register(runner);

View file

@ -62,6 +62,7 @@ internal static class ActionPacingTests
r.Add("refusal: a refused peace-before-open is asked again inside the 2.5 s ceiling; exactly one accepted request goes out before the open", PeaceBeforeOpenRefusedRetried);
r.Add("refusal: a streak that went quiet for 10 s+ (a death, a logout) is over - 600 s later a refusal starts a fresh streak, and Forget ends one", RefusalStreakExpires);
r.Add("refusal: wand wielded, a request accepted then dropped (a teleport), 9 s of refusals - the stuck clock restarts, no re-equip UseObject", StuckClockRestartsOnRefusal);
r.Add("stance clock (Drakkon 10-23): Magic seen ends the episode; a request a minute after the last starts a new one (no 'stuck 1123s')", StuckClockEndsInMagicAndAfterAGap);
r.Add("refusal: the stall watchdog's refused mode toggle spends no ladder step (Unfire) and is asked again next tick", StallToggleRefusedSpendsNoStep);
r.Add("refusal: missile crafting asks for peace until accepted, and combines after the 2.5 s ceiling; already in peace it combines on the first tick with no mode request", CraftingPeaceRefusal);
r.Add("pacing (stance): a refused ChangeCombatMode burns no try and no backoff step, and the next tick asks again (pacing on and off)", RefusedStanceBurnsNothing);
@ -751,6 +752,49 @@ internal static class ActionPacingTests
finally { PaceOff(); }
}
// Drakkon 10-23 22:30: the launcher killed him on "[BuffStance] ChangeCombatMode(Magic) retry #4 (stuck 1123s)".
// The clock had started on a Magic request 18 minutes before and never ended: Magic was reached while
// EnsureMagicMode wasn't looking (combat took the stance back to its weapons first).
private static void StuckClockEndsInMagicAndAfterAGap()
{
PaceOff();
try
{
var r = new BuffRig(CombatMode.NonCombat);
SetupBuffRigVitals(r);
FakeHost.Names[Wand] = "Academy Wand";
FakeHost.ItemTypes[Wand] = 0x8000;
FakeHost.Ints[(Wand, 10)] = 0x01000000; // in hand
r.S.WieldUnlistedWandWhenNoneListed = true;
r.B.SetWorldObjectCache(FakeHost.MakeCache(r.Host, Player, new[] { Wand }));
var since = typeof(BuffManager).GetField("_buffStanceStuckSince", Priv)!;
var lastTry = typeof(BuffManager).GetField("_lastBuffStanceAttempt", Priv)!;
var noteMode = typeof(BuffManager).GetMethod("NoteModeChange", Priv)!;
r.At(0); r.B.OnHeartbeat();
Check.True((DateTime)since.GetValue(r.B)! != DateTime.MinValue, "set-up: a Magic request started the stuck clock");
// The client reaches Magic and combat swaps back to its weapons before the buff step looks.
FakeHost.CombatModeValue = CombatMode.Magic;
noteMode.Invoke(r.B, null);
Check.True((DateTime)since.GetValue(r.B)! == DateTime.MinValue, "seen in Magic: the episode is over, the clock stopped");
FakeHost.CombatModeValue = CombatMode.Melee;
noteMode.Invoke(r.B, null);
// A clock left running anyway (any other way out): 20 minutes on, the next request starts afresh.
since.SetValue(r.B, r.T0.AddMinutes(-20));
lastTry.SetValue(r.B, r.T0.AddMinutes(-20));
FakeHost.CombatModeValue = CombatMode.NonCombat;
noteMode.Invoke(r.B, null);
FakeHost.Logs.Clear();
r.At(1); r.B.OnHeartbeat();
string retry = FakeHost.Logs.FirstOrDefault(l => l.Contains("[BuffStance] ChangeCombatMode(Magic) retry")) ?? "";
Check.True(retry.Contains("retry #1 (stuck 0s"), "a new episode: retry #1, stuck 0 s, not 1200 s: " + retry);
Check.True((r.NowAt - (DateTime)since.GetValue(r.B)!).TotalSeconds < 3, "the clock starts now");
}
finally { PaceOff(); }
}
private static void StallToggleRefusedSpendsNoStep()
{
PaceOff();

View file

@ -34,6 +34,29 @@ internal static class BlastTests
r.Add("known spells: a name with several ids resolves to the id the character knows", DuplicateNameIds);
r.Add("monster rules: UseBlast saves and loads; old files load with it off", RuleJson);
r.Add("blast override: Blast Range off keeps today's shape; on, the base is the other shape; defaults 0 / 3", BlastOverrideSettings);
r.Add("rings (10-25): the level-5 rings from tier 5 (named or plain), the level-7 II from tier 7", RingLevels);
}
// The rings are level 5 (Cassius' Ring of Fire, Halo of Frost, ..., and the plain Flame / Acid / Force /
// Lightning Ring) and level 7 (the named II). A tier-5 caster used to get no ring at all: the named one
// waited for tier 6 and the plain ones were looked for as "Ring of Fire V" and the like.
private static void RingLevels()
{
var find = typeof(CombatManager).GetMethod("FindBestRingSpell",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
string Ring(int tier, string element, params string[] known)
{
var rig = new CastRig(tier, known);
return NameOf((int)find.Invoke(rig.C, new object[] { element, RynthCore.Loot.AcSkillType.WarMagic })!);
}
Check.Eq(Ring(5, "Fire", "Cassius' Ring of Fire"), "Cassius' Ring of Fire", "tier 5: the named level-5 ring");
Check.Eq(Ring(5, "Fire", "Flame Ring"), "Flame Ring", "tier 5: the plain level-5 ring when that is the one known");
Check.Eq(Ring(5, "Lightning", "Lightning Ring"), "Lightning Ring", "Lightning's plain ring");
Check.Eq(Ring(6, "Cold", "Halo of Frost"), "Halo of Frost", "tier 6: the level-5 ring");
Check.Eq(Ring(7, "Cold", "Halo of Frost", "Halo of Frost II"), "Halo of Frost II", "tier 7: the II");
Check.Eq(Ring(7, "Cold", "Halo of Frost"), "Halo of Frost", "tier 7 without the II known: the level-5 one");
Check.Eq(Ring(6, "Cold", "Halo of Frost", "Halo of Frost II"), "Halo of Frost", "tier 6 knowing the II: not yet (level 7)");
Check.Eq(Ring(4, "Cold", "Halo of Frost"), "(none)", "tier 4: no ring (none below level 5)");
}
// ── Rig ───────────────────────────────────────────────────────────────────

View file

@ -29,6 +29,171 @@ internal static class CastNoDamageTests
r.Add("no-damage casts: the chat after a combat cast is logged, swings at us left out, capped, 4 s", CastChatTrace);
r.Add("no-damage casts (flight 63260): 3 magic casts landing nothing -> one short real sidestep, no cast meanwhile; a hit resets; 30 s apart", ResyncSidestep);
r.Add("no-damage casts (R-20261021 c788): a corpse selected mid-fight stops the target's health; its chat hits still count, it is not blacklisted", SelectionElsewhereChatHitsCount);
r.Add("kill shot (R-20261025 727b): cast #37 of ~37 is no kill with ~155k of a 450k boss left", KillShotVetoedByHpPool);
r.Add("kill shot (R-20261025 727b): fresh server health vetoes it; stale health doesn't", KillShotVetoedByFreshHealth);
r.Add("kill shot (R-20261025 727b): a normal 3-cast mob is still predicted on its last cast", KillShotNormalMobStillPredicted);
r.Add("kill shot (R-20261025 727b): the armed cast's own hit calls the swap off; the previous bolt's doesn't", ArmedSwapCalledOffByHit);
}
// ── A boss swapped off as dead (report R-20261025-183343-727b, Conquest) ─────────────────────
// "Predicted kill shot 0x80621EBC 'Curator of Torment' (cast#37 hp~450250 dealt~294989)": the
// learned casts-to-kill (~37) fired on the count alone with ~155,000 HP left; the bot locked a
// Rynthid that died at once and looted a corpse while the Curator (34%) hit the player.
private const uint Boss = 0x80621EBC, Rynthid = 0x80539C4E, BossWcid = 40001, RynthidWcid = 40010;
private const int FlameBolt8 = 8;
private const string BossHit = "You singe Curator of Torment for 8194 points with Incantation of Flame Bolt.";
private sealed class BossRig
{
public readonly LegacyUiSettings S = new() { MonsterRange = 30 };
public readonly MonsterDamageStore Store = new();
public readonly CombatManager C;
public DateTime Now = new(2026, 10, 25, 19, 29, 24);
/// <param name="pool">The Curator's HP (the Damage panel's manual HP); 0 = unknown.</param>
/// <param name="castsToKill">What the store learned: casts of Flame Bolt VIII to kill one.</param>
public BossRig(double pool, int castsToKill, uint wcid = BossWcid)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[Player] = "Me";
FakeHost.Positions[Player] = (Lb | 0x0141, 96f, 96f, 0f);
FakeHost.PlayerPose = (Lb | 0x0141, 96f, 96f, 0f);
FakeHost.Names[Boss] = "Curator of Torment";
FakeHost.Positions[Boss] = (Lb | 0x0141, 96f, 97.9f, 0f);
FakeHost.ItemTypes[Boss] = 0x10;
FakeHost.Wcids[Boss] = wcid;
FakeHost.Names[Rynthid] = "Discorporate Rynthid of Rage";
FakeHost.Positions[Rynthid] = (Lb | 0x0141, 97.7f, 96f, 0f);
FakeHost.ItemTypes[Rynthid] = 0x10;
FakeHost.Wcids[Rynthid] = RynthidWcid;
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, new[] { Boss, Rynthid }, null);
C = new CombatManager(host, S, cache);
C.SetPlayerId(Player);
C.SetDamageStores(null, Store);
C.TargetClock = () => Now;
for (int i = 0; i < 3; i++)
{
Store.RecordKill(Wand, wcid, "Curator of Torment", "Fire", FlameBolt8, castsToKill, 0);
Store.RecordHit(Wand, wcid, "Curator of Torment", "Fire", FlameBolt8, 8194, false);
}
if (pool > 0) Store.SetManualHp(wcid, pool, "Curator of Torment");
C.SetScannedTargetsForTests(new[]
{
new CombatManager.ScannedTarget { Id = unchecked((int)Boss), Distance = 1.9, Angle = 0, Bearing = double.NaN, Name = "Curator of Torment" },
new CombatManager.ScannedTarget { Id = unchecked((int)Rynthid), Distance = 1.7, Angle = 87, Bearing = double.NaN, Name = "Discorporate Rynthid of Rage" },
});
C.EngageForTest(unchecked((int)Boss));
}
public bool Cast() => C.CastAndPredictForTest(Wand, "Fire", FlameBolt8);
/// <summary><paramref name="casts"/> casts, each landing <paramref name="hit"/>, 3.7 s apart; false if any predicted a kill.</summary>
public bool CastAndHit(int casts, string hit)
{
bool any = false;
for (int i = 0; i < casts; i++)
{
any |= Cast();
Now = Now.AddSeconds(3.7);
C.HandleChatForDamage(hit, 7);
}
return any;
}
public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
}
private static void KillShotVetoedByHpPool()
{
var r = new BossRig(pool: 450250, castsToKill: 37);
Check.False(r.CastAndHit(36, BossHit), "casts 1-36: no prediction (count not reached, ~155k+ left)");
Check.False(r.Cast(), "cast #37: the count is reached but ~155k of 450k HP are left: no kill predicted");
Check.Eq(r.LogCount("Kill shot not predicted for 0x80621EBC 'Curator of Torment'"), 1, "said, naming the boss");
Check.True(r.LogCount("of its ~450250 HP are left") == 1, "with the HP evidence");
Check.False(r.Cast(), "cast #38: still none");
Check.Eq(r.LogCount("Kill shot not predicted"), 1, "the line is once a fight, not per cast");
Check.Eq(unchecked((uint)r.C.activeTargetId), Boss, "still on the Curator");
// Hit on until the evidence agrees: predicted once what is left is within a cast and a half.
int hits = 36;
bool predicted = false;
while (!predicted && hits < 60)
{
r.C.HandleChatForDamage(BossHit, 7);
hits++;
double before = 450250 - hits * 8194.0;
predicted = r.Cast();
if (!predicted)
Check.True(before > 1.5 * 8194, $"not predicted only while more than 1.5 casts are left (~{before:0})");
}
double leftAt = 450250 - hits * 8194.0;
Check.True(predicted, "the finishing cast is still predicted");
Check.True(leftAt > 0 && leftAt <= 1.5 * 8194, $"with ~{leftAt:0} left (within a cast and a half)");
}
private static void KillShotVetoedByFreshHealth()
{
// HP pool unknown: only the server's health can say. 36 casts landed (~295k), the Curator at 34%.
var r = new BossRig(pool: 0, castsToKill: 37);
r.CastAndHit(36, BossHit);
r.C.NoteServerHealth(unchecked((int)Boss), 0.34f); // came with the last hit (selected)
Check.False(r.Cast(), "cast #37 at 34% health (~152k left by the damage dealt): no kill predicted");
Check.True(r.LogCount("the server says its health is 34%") == 1, "the health is the reason given");
// The same fight with a health reading from before the last hit: it doesn't count that
// hit, so it is no evidence, and the count alone predicts as before.
r = new BossRig(pool: 0, castsToKill: 37);
r.CastAndHit(35, BossHit);
r.C.NoteServerHealth(unchecked((int)Boss), 0.34f);
r.CastAndHit(1, BossHit); // a hit 3.7 s after the reading
Check.True(r.Cast(), "stale health: cast #37 is predicted (no evidence against it)");
Check.Eq(r.LogCount("Kill shot not predicted"), 0, "nothing vetoed");
// Another monster's health is not the fight target's.
r = new BossRig(pool: 0, castsToKill: 37);
r.CastAndHit(36, BossHit);
r.C.NoteServerHealth(unchecked((int)Rynthid), 0.34f);
Check.True(r.Cast(), "the Rynthid's health says nothing about the Curator");
}
private static void KillShotNormalMobStillPredicted()
{
// A mob of 24,000 HP that 3 bolts kill: cast #3 is the kill, by count and by the damage left.
const string hit = "You singe Curator of Torment for 8000 points with Incantation of Flame Bolt.";
var r = new BossRig(pool: 24000, castsToKill: 3, wcid: 40020);
Check.False(r.CastAndHit(2, hit), "casts 1-2: no prediction");
Check.True(r.Cast(), "cast #3: predicted (8,000 left, one cast ~8,000)");
// With its health in: 33% left of 24,000 agrees.
r = new BossRig(pool: 24000, castsToKill: 3, wcid: 40020);
r.CastAndHit(2, hit);
r.C.NoteServerHealth(unchecked((int)Boss), 0.33f);
Check.True(r.Cast(), "fresh health at 33% agrees: predicted");
// A low roll on the way (dealt 13,000 of 24,000): 11,000 left is within reach of one cast, still predicted.
r = new BossRig(pool: 24000, castsToKill: 3, wcid: 40020);
r.CastAndHit(1, hit);
r.CastAndHit(1, "You singe Curator of Torment for 5000 points with Incantation of Flame Bolt.");
Check.True(r.Cast(), "a low roll before the last cast doesn't hold the prediction back");
Check.Eq(r.LogCount("Kill shot not predicted"), 0, "nothing vetoed for the normal mob");
}
private static void ArmedSwapCalledOffByHit()
{
var r = new BossRig(pool: 0, castsToKill: 37);
r.C.ArmPredictedSwapForTest(castAgoMs: 2900); // the bolt went out 2.9 s ago
r.C.HandleChatForDamage("You singe Curator of Torment for 7883 points with Incantation of Flame Bolt.", 7);
Check.False(r.C.PredictedSwapArmed, "its hit landed and it is alive: the swap is called off");
Check.Eq(r.LogCount("Predicted kill shot 0x80621EBC 'Curator of Torment' called off"), 1, "and logged");
Check.Eq(unchecked((uint)r.C.activeTargetId), Boss, "still on the Curator");
r = new BossRig(pool: 0, castsToKill: 37);
r.C.ArmPredictedSwapForTest(castAgoMs: 200); // the line can't be this cast's: no windup is that short
r.C.HandleChatForDamage(BossHit, 7);
Check.True(r.C.PredictedSwapArmed, "the previous bolt landing just after the arming cast doesn't call it off");
r.C.HandleChatForDamage("Discorporate Rynthid of Rage catches your attack, with dire consequences!", 0);
Check.True(r.C.PredictedSwapArmed, "nor does another monster's line");
}
// ── A corpse selected during the fight (report R-20261021-191720-c788, Conquest) ─────────────

View file

@ -0,0 +1,226 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Detector C, "Avoid Lava/Acid Floors" (2026-10-23): a cell is a hazard when a texture in
// HazardTextures.txt is on its walkable FLOOR (a render polygon facing up at least as steeply as
// AC's FloorZ 0.66417), not merely in its surface palette. Before, the palette test flagged cells
// for their walls: Tiny Hive (0x0289) on +Buffy patrolled 2 waypoints, because the learned
// 0x0500279D is the Olthoi hive wall texture (on walls in 3,530 cells of the dats, on a floor in
// none) and 12 cells round the entrance were "hazards". Learning (/ra hazard learnhere) looks at
// floors too, so it can't learn a wall texture again.
//
// Synthetic polygons for the rule; the real Tiny Hive cells when the dat files are on this PC
// (C:\Turbine\Asheron's Call, as DungeonMapBakeTests and FloodPerfTests). The texture set lives in
// the scratch folder (Program.Main points DungeonHazardSurfaces there).
internal static class HazardFloorTests
{
private const string AcDir = @"C:\Turbine\Asheron's Call";
public static void Register(Runner r)
{
r.Add("hazard floors: a polygon facing up at FloorZ or more is floor; walls, ceilings, steep slopes are not", WalkableFloor);
r.Add("hazard floors: a cell's floor surfaces are its floor polygons', not its walls', ceiling's or portals'", FloorSurfaces);
r.Add("hazard floors: a hazard texture on a cell's wall doesn't make it a hazard; on its floor it does", WallVersusFloor);
r.Add("hazard floors: learnhere takes a rare floor texture, never a wall texture", LearnIgnoresWalls);
r.Add("hazard floors: Tiny Hive 0x0289 on the real dats - the wall texture flags nothing, the floor texture its floors", TinyHiveRealDats);
}
// ── Synthetic geometry ──────────────────────────────────────────────────
private static Vector3 V(float x, float y, float z) => new Vector3(x, y, z);
// A 2 x 2 square at height z, counter-clockwise seen from above: faces up.
private static Vector3[] FloorSquare(float z = 0) => new[] { V(0, 0, z), V(2, 0, z), V(2, 2, z), V(0, 2, z) };
// The same square wound the other way: faces down (a ceiling).
private static Vector3[] CeilingSquare(float z = 3) => FloorSquare(z).Reverse().ToArray();
// Upright, facing -y.
private static Vector3[] WallSquare() => new[] { V(0, 0, 0), V(0, 0, 3), V(2, 0, 3), V(2, 0, 0) };
// A ramp rising along +x at the given angle from horizontal, facing up.
private static Vector3[] Ramp(double degrees)
{
float rise = (float)(2 * Math.Tan(degrees * Math.PI / 180));
return new[] { V(0, 0, 0), V(2, 0, rise), V(2, 2, rise), V(0, 2, 0) };
}
private static (IReadOnlyList<Vector3> Verts, short PosSurface, bool IsPortal) P(Vector3[] v, short surf, bool portal = false) => (v, surf, portal);
private static void WalkableFloor()
{
Check.True(DungeonLOS.IsWalkableFloor(FloorSquare()), "flat floor");
Check.False(DungeonLOS.IsWalkableFloor(CeilingSquare()), "ceiling (faces down)");
Check.False(DungeonLOS.IsWalkableFloor(WallSquare()), "upright wall");
Check.True(DungeonLOS.IsWalkableFloor(Ramp(30)), "30 degree ramp (nz 0.87, Tiny Hive's bowl floors are 0.81-0.86)");
Check.True(DungeonLOS.IsWalkableFloor(Ramp(45)), "45 degree ramp (nz 0.71)");
Check.False(DungeonLOS.IsWalkableFloor(Ramp(50)), "50 degree slope (nz 0.64, steeper than FloorZ)");
Check.False(DungeonLOS.IsWalkableFloor(new[] { V(0, 0, 0), V(1, 1, 0) }), "two points");
Check.False(DungeonLOS.IsWalkableFloor(new[] { V(0, 0, 0), V(1, 1, 0), V(2, 2, 0) }), "collinear");
Check.Near(DungeonLOS.FloorZ, 0.66417, 1e-5, "FloorZ is AC's PhysicsGlobals.FloorZ");
}
// Palette: 0 = wall surface, 1 = floor surface, 2 = ceiling surface, 3 = portal surface, 4 = unused.
private const ushort SWall = 0x04C7, SFloor = 0x0112, SCeil = 0x0113, SPortal = 0x0034, SUnused = 0x04C6;
private static readonly ushort[] Palette = { SWall, SFloor, SCeil, SPortal, SUnused };
private static void FloorSurfaces()
{
var polys = new[]
{
P(WallSquare(), 0), P(WallSquare(), 0),
P(FloorSquare(), 1), P(Ramp(30), 1),
P(CeilingSquare(), 2),
P(FloorSquare(), 3, portal: true), // a floor-level portal (a shaft) is an opening
P(FloorSquare(), -1), // no front surface
P(FloorSquare(), 9), // index past the palette
};
var floor = DungeonLOS.FloorSurfaceIds(Palette, polys);
Check.Eq(string.Join(",", floor.Select(s => s.ToString("X4"))), SFloor.ToString("X4"), "only the floor's surface");
// A cap cell: ceiling and portals only - no floor surfaces at all.
Check.Eq(DungeonLOS.FloorSurfaceIds(Palette, new[] { P(CeilingSquare(), 2), P(FloorSquare(), 3, portal: true) }).Count, 0, "ceiling-only cell has no floor");
Check.Eq(DungeonLOS.FloorSurfaceIds(null!, polys).Count, 0, "no palette");
}
// Surface -> texture as portal.dat would resolve it.
private const uint TLava = 0x0500AAA1, TStone = 0x0500AAA2, TWallRare = 0x0500AAA3, TCeil = 0x0500AAA4;
private static HashSet<uint> Textures(ushort[] palette, (IReadOnlyList<Vector3>, short, bool)[] polys, Dictionary<ushort, uint> surfTex)
=> DungeonLOS.FloorSurfaceIds(palette, polys).Select(s => surfTex[s]).ToHashSet();
private static void ResetSet()
{
DungeonHazardSurfaces.Reload();
foreach (uint t in DungeonHazardSurfaces.ListHazardTextures()) DungeonHazardSurfaces.RemoveHazardTexture(t);
}
private static void WallVersusFloor()
{
Check.True(DungeonHazardSurfaces.Folder.StartsWith(Program.TempRoot, StringComparison.OrdinalIgnoreCase), "texture set is in the scratch folder: " + DungeonHazardSurfaces.Folder);
ResetSet();
try
{
const ushort SHz = 0x0700, SStone = 0x0701;
var surfTex = new Dictionary<ushort, uint> { [SHz] = TLava, [SStone] = TStone };
ushort[] pal = { SHz, SStone };
var floors = new Dictionary<uint, HashSet<uint>>
{
// A: hazard texture on the walls, stone floor.
[0xA] = Textures(pal, new[] { P(WallSquare(), 0), P(FloorSquare(), 1) }, surfTex),
// B: stone walls, hazard texture on the floor.
[0xB] = Textures(pal, new[] { P(WallSquare(), 1), P(FloorSquare(), 0) }, surfTex),
// C: hazard texture in the palette and on the ceiling only.
[0xC] = Textures(pal, new[] { P(CeilingSquare(), 0), P(FloorSquare(), 1) }, surfTex),
// D: part of the floor is the hazard texture (a pool in a stone room).
[0xD] = Textures(pal, new[] { P(FloorSquare(), 1), P(FloorSquare(), 0) }, surfTex),
};
Check.True(DungeonHazardSurfaces.AddHazardTexture(TLava), "flag the texture");
Check.True(File.Exists(Path.Combine(Program.TempRoot, "HazardTextures", "HazardTextures.txt")), "persisted to the scratch folder");
var hz = DungeonHazardSurfaces.HazardCellsFrom(floors);
Check.False(hz.Contains(0xA), "wall uses the hazard texture: not a hazard");
Check.True(hz.Contains(0xB), "floor uses the hazard texture: hazard");
Check.False(hz.Contains(0xC), "ceiling uses the hazard texture: not a hazard");
Check.True(hz.Contains(0xD), "part of the floor uses it: hazard");
Check.Eq(hz.Count, 2, "two hazard cells");
}
finally { ResetSet(); }
}
private static void LearnIgnoresWalls()
{
ResetSet();
try
{
const ushort SStone = 0x0701, SWallRare = 0x0702, SLava = 0x0703, SCeilS = 0x0704;
var surfTex = new Dictionary<ushort, uint> { [SStone] = TStone, [SWallRare] = TWallRare, [SLava] = TLava, [SCeilS] = TCeil };
ushort[] pal = { SStone, SWallRare, SLava, SCeilS };
var floors = new Dictionary<uint, HashSet<uint>>();
// 20 ordinary rooms: stone floor and walls, ceiling texture overhead.
for (uint c = 0x100; c < 0x114; c++)
floors[c] = Textures(pal, new[] { P(FloorSquare(), 0), P(WallSquare(), 0), P(CeilingSquare(), 3) }, surfTex);
// A room with a rare WALL texture (only this cell has it) and the common stone floor.
const uint RareWallRoom = 0x200;
floors[RareWallRoom] = Textures(pal, new[] { P(FloorSquare(), 0), P(WallSquare(), 1) }, surfTex);
// A lava room: lava floor, stone walls.
const uint LavaRoom = 0x201;
floors[LavaRoom] = Textures(pal, new[] { P(FloorSquare(), 2), P(WallSquare(), 0) }, surfTex);
Check.Eq(DungeonHazardSurfaces.RareFloorTextures(RareWallRoom, floors, 0.25).Count, 0, "rare wall texture is not learned (its floor is common stone)");
var lava = DungeonHazardSurfaces.RareFloorTextures(LavaRoom, floors, 0.25);
Check.Eq(string.Join(",", lava.Select(t => t.ToString("X8"))), TLava.ToString("X8"), "the lava room's floor texture is learned");
Check.Eq(DungeonHazardSurfaces.RareFloorTextures(0x100, floors, 0.25).Count, 0, "a common floor is never learned");
Check.Eq(DungeonHazardSurfaces.RareFloorTextures(0x999, floors, 0.25).Count, 0, "a cell without floor data learns nothing");
Check.False(floors.Values.Any(s => s.Contains(TWallRare) || s.Contains(TCeil)), "wall and ceiling textures never reach the floor map");
}
finally { ResetSet(); }
}
// ── The real dats ───────────────────────────────────────────────────────
private static GeometryLoader? _geo;
private static bool _geoTried;
private static GeometryLoader? Geo()
{
if (!_geoTried)
{
_geoTried = true;
if (Directory.Exists(AcDir))
{
var g = new GeometryLoader();
if (g.Initialize(AcDir)) _geo = g;
else Console.WriteLine(" geometry loader failed: " + g.StatusMessage);
}
}
return _geo;
}
private const uint TinyHive = 0x0289;
private const uint HiveFloor = 0x0500279C, HiveWall = 0x0500279D; // the two ids in the live HazardTextures.txt
private static string Ids(IEnumerable<uint> cells) => string.Join(",", cells.OrderBy(c => c).Select(c => (c & 0xFFFF).ToString("X4")));
private static void TinyHiveRealDats()
{
var geo = Geo();
if (geo?.DungeonLOS is null || geo.PortalDat is null) { Console.WriteLine(" skipped: no dats at " + AcDir); return; }
var los = geo.DungeonLOS;
ResetSet();
try
{
var floors = DungeonHazardSurfaces.GetFloorTextures(TinyHive, los, geo.PortalDat);
Check.True(floors.Count > 300, $"floor textures for most of Tiny Hive's 450 cells ({floors.Count})");
Check.False(floors.Values.Any(s => s.Contains(HiveWall)), "0x0500279D is on no floor in Tiny Hive");
// The wall texture alone flags nothing (before: 02A2-02B0, the 12 cells round the entrance).
DungeonHazardSurfaces.AddHazardTexture(HiveWall);
var wallOnly = DungeonHazardSurfaces.ComputeHazardCells(TinyHive, los, geo.PortalDat);
Console.WriteLine($" 0x0500279D flagged: {wallOnly.Count} cells {Ids(wallOnly)}");
Check.Eq(wallOnly.Count, 0, "wall texture flags no cell");
// The floor texture flags the cells it's the floor of: 02A6 (walls only), 02A8 and
// 02A9 (in the palette, on no polygon / a different floor) are not among them.
DungeonHazardSurfaces.AddHazardTexture(HiveFloor);
var floorCells = DungeonHazardSurfaces.ComputeHazardCells(TinyHive, los, geo.PortalDat);
Console.WriteLine($" + 0x0500279C flagged: {floorCells.Count} cells {Ids(floorCells)}");
Check.Eq(Ids(floorCells), "02A2,02A3,02A4,02A7,02AA,02AB,02AE,02AF,02B0", "exactly the cells whose floor is 0x0500279C");
Check.False(floorCells.Contains(0x028902A5), "the entrance cell 02A5 is not a hazard");
// Learning standing in 02A6 (hive wall texture on its walls, common floor 0x05002627)
// takes nothing; before, the palette rule offered both 0x0500279C and 0x0500279D.
ResetSet();
var learned = DungeonHazardSurfaces.LearnFromCell(0x028902A6, los, geo.PortalDat);
Check.Eq(learned.Count, 0, "learnhere in 02A6 learns nothing: " + string.Join(",", learned.Select(t => t.ToString("X8"))));
Check.Eq(DungeonHazardSurfaces.HazardTextureCount, 0, "and the set stays empty");
}
finally { ResetSet(); }
}
}

View file

@ -118,6 +118,7 @@ internal static class InstallPathsTests
Check.Eq(PrivateStatic(typeof(RynthCore.Plugin.RynthAi.RadarWallRenderer), "ExploredDir"), @"C:\Games\RynthSuite\RynthAi\ExploredDungeons", "explored dungeons");
// The tests point the store at their scratch folder (Program.Main); this is its value before that.
Check.Eq(Program.LiveHazardFolder, @"C:\Games\RynthSuite\RynthAi\DungeonHazards", "dungeon hazards");
Check.Eq(Program.LiveHazardTextureFolder, @"C:\Games\RynthSuite\RynthAi", "hazard floor textures (HazardTextures.txt)");
Check.Eq(Program.LiveCreatureFolder, @"C:\Games\RynthSuite\RynthAi\CreatureData", "creature data");
}

View file

@ -53,6 +53,8 @@ internal static class LootCorpseTests
r.Add("boost loot: the wait ends after BoostLootKillWaitMs, for a close monster, and with Boost Loot off", BoostLootHoldLimits);
r.Add("boost loot: looting the kill's corpse ends the wait; an older corpse does not", BoostLootWaitEndsOnKillCorpse);
r.Add("monster ignore: a close Priority 0 monster neither holds combat nor starves the corpse", IgnoredMonsterDoesNotHoldLoot);
r.Add("loot gate (R-20261025 727b): a predicted kill still alive holds the corpse; after its window combat has it again", PredictedKillHoldsCorpse);
r.Add("loot gate (R-20261025 727b): the kill notice, health 0 or a hit after the swap settle a predicted kill at once", PredictedKillSettled);
r.Add("corpse close: a finished corpse is closed once (CloseContainer, API v76)", FinishedCorpseClosedOnce);
r.Add("corpse close: an engine without CloseContainer leaves it to the next open (no close)", FinishedCorpseNotClosedOnOldEngine);
r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed);
@ -400,6 +402,96 @@ internal static class LootCorpseTests
Check.Eq(ActivityArbiter.Decide(in inputs), BotActivity.Looting, "so looting has the tick without needing a starved turn");
}
// ── A predicted kill that is still alive (report R-20261025-183343-727b, Conquest) ─────────
// The bot swapped off a Curator of Torment as a predicted kill (34% health left), the Rynthid it
// locked next died at once, and with the Curator kept out of the scan HasTargets went false:
// "Corpse loot: claimed corpse target", 4.6 s of looting with the live Curator 1.9 m away.
/// <summary>The Water Elemental 2 m away fought, then swapped off as a predicted kill (dropped,
/// out of the scan), with combat's target clock at <paramref name="now"/>.</summary>
private static Bot PredictedKillWorld(out CombatManager combat, Func<DateTime> now)
{
var bot = StarvationWorld(2f, out combat);
FakeHost.Wcids[Monster] = 40030;
combat.TargetClock = now;
combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
combat.EngageForTest(unchecked((int)Monster));
combat.CastAndPredictForTest(0x8008AB76, "Fire", 8); // one cast at it (the kill notice credits it)
combat.PredictedSwapForTest();
Rescan(combat);
return bot;
}
private static void Rescan(CombatManager combat)
{
typeof(CombatManager).GetField("_lastScanTime", Any)?.SetValue(combat, DateTime.MinValue);
combat.ScanNearbyTargets();
}
private static void PredictedKillHoldsCorpse()
{
DateTime now = new(2026, 10, 25, 19, 32, 58);
var bot = PredictedKillWorld(out var combat, () => now);
int mob = unchecked((int)Monster);
Check.Eq(combat.activeTargetId, 0, "the swap dropped it");
Check.False(combat.ScannedTargets.Any(t => t.Id == mob), "and the scan is kept off it (its death animation)");
Check.True(combat.HasTargets, "but it still counts as a target in range (corpse gates, nav hold)");
Check.True(combat.HasCloseThreat(RynthAiPlugin.LootStarveCloseYards), "and as a close threat (no starved loot turn)");
Check.True(combat.HasEngageableTarget, "so combat keeps the tick");
Check.True(bot.HasLootWork(), "the corpse is lootable");
bot.Tick(BotActivity.Combat);
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "no corpse claimed while combat holds the tick");
Check.True(FakeHost.Logs.Any(l => l.Contains($"corpse 0x{Corpse:X8} waits for combat")), "the corpse waits for combat, and says so");
bot.Tick(BotActivity.Looting);
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "nor with the Looting tick (the claim gate holds too)");
Check.False(FakeHost.Uses.Contains(Corpse), "the corpse is not opened");
AgeCorpse(bot, RynthAiPlugin.LootStarveMs + 1000);
bot.HasLootWork();
Check.False((bool)bot.Call("IsLootStarvedTurn", true, true)!, "a long-waiting corpse gets no starved turn past it either");
// Its window passes with no word of its death: it is a target again at once.
now = now.AddSeconds(2.1);
Rescan(combat);
Check.True(combat.ScannedTargets.Any(t => t.Id == mob), "after the window it is scanned again");
Check.True(FakeHost.Logs.Any(l => l.Contains("not confirmed 2.1 s after the swap and it is still alive: it is a target again")),
"said once the window ends");
combat.HandleCombatTrigger();
Check.Eq(combat.activeTargetId, mob, "and combat locks it again");
}
private static void PredictedKillSettled()
{
DateTime now = new(2026, 10, 25, 19, 32, 58);
int mob = unchecked((int)Monster);
// The kill notice confirms it: the corpse may be looted.
var bot = PredictedKillWorld(out var combat, () => now);
combat.OnKillNotification("You killed the Ancient Water Elemental!");
Check.False(combat.HasTargets, "kill notice: dead, nothing in range");
Check.False(combat.HasEngageableTarget, "combat lets the tick go");
Check.True(combat.IsKillSuppressed(mob), "the scan stays off it while its corpse forms");
bot.HasLootWork();
bot.Tick(BotActivity.Looting);
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)Corpse), "the corpse is claimed");
// Health 0 from the server: dead too.
bot = PredictedKillWorld(out combat, () => now);
Check.True(combat.HasTargets, "pending");
bot.Cache.OnUpdateHealth(Monster, 0f); // the bot's cache is combat's world filter
Check.False(combat.HasTargets, "health 0: dead, nothing in range");
// A damage line on it after the swap (a killing blow sends none): alive, back in the scan now.
PredictedKillWorld(out combat, () => now);
combat.HandleChatForDamage("You singe Ancient Water Elemental for 7883 points with Incantation of Flame Bolt.", 7);
Check.False(combat.IsKillSuppressed(mob), "the hit lifts the suppression");
Check.True(FakeHost.Logs.Any(l => l.Contains("took a 7883-point hit after the swap")), "and says so");
Rescan(combat);
Check.True(combat.ScannedTargets.Any(t => t.Id == mob), "scanned again before the window ends");
combat.HandleCombatTrigger();
Check.Eq(combat.activeTargetId, mob, "combat goes back to it at once");
}
// ── Boost Loot Priority: one kill, one loot (2026-10-14, Kelpie: the next target was locked
// 6 ms after each kill, the corpse came 3 s later, and corpses were looted in batches) ──

View file

@ -26,6 +26,8 @@ internal static class ManaStoneChoiceTests
r.Add("mana charges: used up, the next charge of that name is found (retail: each use destroys one)", NextChargeFoundByName);
r.Add("mana charges: never taken for the empty stone to drain loot into", ChargeIsNeverEmptyStone);
r.Add("mana charges: refill gear even when ManaStone rules name only other stones", ChargesIgnoreStoneRules);
r.Add("mana stones (Drakkon 10-23): a mana kit typed ManaStone in Items is no stone rule: the ordinary stones still refill gear", KitIsNoStoneRule);
r.Add("mana tapping (Drakkon 10-24): mana kits are no empty stones: nothing looted for them; the item goes into the real stone", KitsAreNoEmptyStones);
r.Add("mana stones: the server's 'low on Mana' refills gear whose read is stale-high", ServerLowRefills);
r.Add("mana stones: worn gear is identified again, so a stale-high read follows the gear", GearReadRefreshed);
r.Add("mana stones: worn means worn per the tracker - a packed item with a stale wield record takes no appraisals, gear it says is worn gets refilled", WornPerTracker);
@ -124,6 +126,39 @@ internal static class ManaStoneChoiceTests
Check.True(m.IsRefillStone(W("Tiny Mana Charge")), "tapping off too");
}
// Drakkon 10-23: "Greater Mana Kit" (a kit for his own mana) was in Items typed ManaStone. As the only stone
// rule it switched the ordinary stones off: his Greater and Major Mana Stones were never used, his shirt ran
// dry, and RynthAi tried to drain his necklace into the kit ("Cannot use the Greater Mana Kit with the Necklace").
private static void KitIsNoStoneRule()
{
FakeHost.Reset();
var host = FakeHost.Create();
var cache = new WorldObjectCache(host);
var s = new LegacyUiSettings { EnableManaTapping = true };
s.ConsumableRules.Add(new ConsumableRule { Name = "Greater Mana Kit", Type = "ManaStone" });
var m = new ManaStoneManager(host, s, cache);
WorldObject W(string name, AcObjectClass cls = AcObjectClass.ManaStone) => new(0x60001000, name, cls);
Check.True(m.IsManaStone(W("Greater Mana Stone")) && m.IsManaStone(W("Major Mana Stone")), "the ordinary stones count again");
Check.True(m.IsRefillStone(W("Major Mana Stone")), "and refill worn gear");
Check.False(m.IsManaStone(W("Greater Mana Kit", AcObjectClass.HealingKit)), "the kit is no stone (nothing drained into it)");
Check.True(FakeHost.Logs.Count(l => l.Contains("'Greater Mana Kit' is in Items as a mana stone but is a kit")) == 1, "said once");
s.EnableManaTapping = false;
Check.True(m.IsRefillStone(W("Greater Mana Stone")), "tapping off: still refills gear");
// A real stone named in Items still means "only the named ones".
s.EnableManaTapping = true;
s.ConsumableRules.Add(new ConsumableRule { Name = "Major Mana Stone", Type = "ManaStone" });
Check.True(m.IsManaStone(W("Major Mana Stone")), "the named stone");
Check.False(m.IsManaStone(W("Greater Mana Stone")), "not the unnamed one");
// Adding one to Items types it ManaKit now, and a kit in the pack is no healing kit.
var detect = typeof(LegacyWeaponsUi).GetMethod("DetectConsumableType", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)!;
Check.Eq((string)detect.Invoke(null, new object[] { W("Greater Mana Kit", AcObjectClass.HealingKit) })!, "ManaKit", "Items types a mana kit ManaKit");
Check.Eq((string)detect.Invoke(null, new object[] { W("Greater Mana Stone") })!, "ManaStone", "and a stone ManaStone");
Check.Eq(LegacyWeaponsUi.PackConsumableType(W("Greater Mana Kit", AcObjectClass.HealingKit)), "ManaKit", "a mana kit in the pack is not a healing kit");
Check.Eq(LegacyWeaponsUi.PackConsumableType(W("Treated Healing Kit", AcObjectClass.HealingKit)), "HealthKit", "a healing kit still is");
}
private static void ServerLowRefills()
{
// The mace was identified at 90% and reads that forever (the fake never updates it).
@ -384,6 +419,32 @@ internal static class ManaStoneChoiceTests
Check.Eq(rig.OnPlayer[0], StoneA, "stone A");
}
// Drakkon 10-23/24: with "Greater Mana Kit" typed ManaStone, his 5 kits were empty stones to RynthAi. It looted
// an item for each, every drain into a kit was refused, it gave up after 3 and looted the next: a hundred items.
// Tom: the stone first, then one item for it, drained, and the next only with another empty stone.
private static void KitsAreNoEmptyStones()
{
const uint KitA = 0x80400031, KitB = 0x80400032;
void Kits(List<uint> ids)
{
foreach (uint k in new[] { KitA, KitB }) { FakeHost.Names[k] = "Greater Mana Kit"; FakeHost.Containers[k] = Player; ids.Add(k); }
}
using (var rig = new Rig(tapping: true, Array.Empty<(uint, int?)>(), maceMana: 5000, before: Kits))
{
rig.S.ConsumableRules.Add(new ConsumableRule { Name = "Greater Mana Kit", Type = "ManaStone" });
Check.Eq(rig.M.CountEmptyStones(), 0, "kits only: no empty stone");
Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "so no item is looted to tap");
}
using (var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null) }, ringToDrain: true, stoneName: "Major Mana Stone", maceMana: 5000, before: Kits))
{
rig.S.ConsumableRules.Add(new ConsumableRule { Name = "Greater Mana Kit", Type = "ManaStone" });
Check.Eq(rig.M.CountEmptyStones(), 1, "one empty Major Mana Stone (the kits don't count)");
rig.Run(1600);
Check.True(rig.OnRing.Count == 1 && rig.OnRing[0] == StoneA, $"the ring is drained into the stone, never a kit ({string.Join(",", rig.OnRing.Select(x => $"0x{x:X8}"))})");
Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "and no second item while that drain is out");
}
}
private static void OneTapItemAtATime()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (StoneB, null), (StoneC, null) }, maceMana: 5000);

View file

@ -0,0 +1,471 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
using V3 = RynthCore.Plugin.RynthAi.Raycasting.Vector3;
namespace RynthCore.RynthAiHostTests.Tests;
// The Dungeon Patrol keeps out of portals (DungeonPathfinder.Portals.cs, 2026-10-23). Tom, Tiny Hive
// (0x0289): with coverage Everything the patrol "takes me right into the portal": waypoint 1 was the
// exit point 1.2 m into the dead-end nook 028902BA, 0.02 m from the Surface Portal, and a client that
// began its lap there was teleported out. On small hand-built dungeons (world metres, floors at z 0,
// as in PatrolDoorwayTests):
// - a patrol across a room with a portal in it: every point and leg stays outside the circle, the
// crossing bends round it, and every doorway is still walked through;
// - a portal at the back of a dead-end nook (Tiny Hive's layout): the nook's doorway is closed, the
// patrol turns round in the corridor before it (without the portal a point was on it); the cell
// walk without map geometry keeps out too;
// - a start next to a portal: the character walks straight away from it first, then round it to the
// first point; a portal across the start's corridor leaves the patrol the side the character is on;
// - a portal on another level changes nothing;
// - Tiny Hive itself on the real dats (when they are on this PC);
// - the plugin: the client's portal objects in the dungeon are the circles, and one that comes into
// view after the build makes the running patrol rebuild.
internal static class PatrolPortalTests
{
public static void Register(Runner r)
{
r.Add("patrol portals: a patrol through a room with a portal keeps its points and legs outside the circle, doorways all walked", RoomWithPortal);
r.Add("patrol portals: a portal in a dead end (Tiny Hive's nook) is turned round before; it used to get a point on it", DeadEndTurnedRoundBefore);
r.Add("patrol portals: without the map geometry (cell walk) the patrol keeps out too", CellWalkKeepsOut);
r.Add("patrol portals: a start next to a portal walks straight away from it first, then round it", StartNextToPortalWalksAway);
r.Add("patrol portals: a portal across the start's corridor leaves the patrol the side the character is on", PortalSplitsStartCorridor);
r.Add("patrol portals: a portal on another level changes nothing", OtherLevelIgnored);
r.Add("patrol portals: Tiny Hive 0x0289 on the real dats keeps out of the Surface Portal (if the dats are here)", TinyHiveRealDats);
r.Add("patrol portals: the client's portals in the dungeon are the circles; one coming into view rebuilds the patrol", PluginCollectsPortals);
}
// ── Fixture builder ──────────────────────────────────────────────────────
private sealed class Dungeon
{
public readonly Dictionary<uint, DungeonNavNode> Graph = new();
public readonly List<(uint, V3[])> Portals = new();
public readonly List<(uint, V3[])> Floors = new();
public readonly List<(uint, V3[])> Walls = new();
private uint _next = 0x7E7E0100;
/// <summary>A cell whose floor is the rectangle (x0,y0)-(x1,y1) at height z; its origin is the middle.</summary>
public uint Cell(double x0, double y0, double x1, double y1, double z = 0)
{
uint id = _next++;
Graph[id] = new DungeonNavNode
{
CellId = id,
EW = DungeonGeometry.WorldToNav((x0 + x1) / 2),
NS = DungeonGeometry.WorldToNav((y0 + y1) / 2),
Z = (float)z,
};
Floors.Add((id, Rect(x0, y0, x1, y1, z)));
return id;
}
public void OpenX(uint a, uint b, double x, double y0, double y1) => Open(a, b, Quad(x, y0, x, y1));
public void OpenY(uint a, uint b, double y, double x0, double x1) => Open(a, b, Quad(x0, y, x1, y));
private void Open(uint a, uint b, V3[] quad)
{
Graph[a].Neighbors.Add(b);
Graph[b].Neighbors.Add(a);
Portals.Add((a, quad));
Portals.Add((b, quad.Reverse().ToArray()));
}
public DungeonGeometry Geo() => DungeonGeometry.Build(Graph, Portals, Floors, Walls);
}
private static V3[] Rect(double x0, double y0, double x1, double y1, double z) => new[]
{
new V3((float)x0, (float)y0, (float)z), new V3((float)x1, (float)y0, (float)z),
new V3((float)x1, (float)y1, (float)z), new V3((float)x0, (float)y1, (float)z),
};
private static V3[] Quad(double x0, double y0, double x1, double y1) => new[]
{
new V3((float)x0, (float)y0, 0f), new V3((float)x1, (float)y1, 0f),
new V3((float)x1, (float)y1, 3f), new V3((float)x0, (float)y0, 3f),
};
private static double X(NavPoint p) => DungeonGeometry.NavToWorld(p.EW);
private static double Y(NavPoint p) => DungeonGeometry.NavToWorld(p.NS);
private static NavPoint At(double x, double y, double z = 0) => new()
{
Type = NavPointType.Point, EW = DungeonGeometry.WorldToNav(x), NS = DungeonGeometry.WorldToNav(y), Z = z / 240.0,
};
private static PatrolPortal Portal(double x, double y, double z = 0, double r = DungeonPathfinder.PortalKeepOutDefault)
=> new() { Id = 0x7E7E9001, Name = "Test Portal", X = x, Y = y, Z = z, Radius = r };
private static string Pts(List<NavPoint> pts) => string.Join(" ", pts.Select(p => $"({X(p):F1},{Y(p):F1})"));
private static double SegDist(double px, double py, double ax, double ay, double bx, double by)
{
double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
double t = l2 < 1e-12 ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / l2, 0, 1);
double cx = ax + dx * t - px, cy = ay + dy * t - py;
return Math.Sqrt(cx * cx + cy * cy);
}
// The nearest any point, and any leg of the loop, comes to (px, py): checked here independently of
// the code under test.
private static (double Point, double Leg) Nearest(List<NavPoint> pts, double px, double py, bool closed = true)
{
double point = double.MaxValue, leg = double.MaxValue;
for (int i = 0; i < pts.Count; i++)
{
point = Math.Min(point, Math.Sqrt((X(pts[i]) - px) * (X(pts[i]) - px) + (Y(pts[i]) - py) * (Y(pts[i]) - py)));
if (i + 1 < pts.Count || (closed && pts.Count > 1))
{
var b = pts[(i + 1) % pts.Count];
leg = Math.Min(leg, SegDist(px, py, X(pts[i]), Y(pts[i]), X(b), Y(b)));
}
}
return (point, leg);
}
private static void KeptOut(NavRouteParser route, PatrolPortal p, string what)
{
var (point, leg) = Nearest(route.Points, p.X, p.Y);
Check.True(route.Points.Count >= 2, $"{what}: a patrol ({route.Points.Count} points)");
Check.True(point >= p.Radius - 0.02, $"{what}: every point {p.Radius} m or more from the portal (nearest {point:F2} m): {Pts(route.Points)}");
Check.True(leg >= p.Radius - 0.02, $"{what}: every leg {p.Radius} m or more from the portal (nearest {leg:F2} m)");
}
// ── A room with a portal in it ───────────────────────────────────────────
// PatrolDoorwayTests' loop dungeon: a 3x3 room of 10 m cells (x 0..30, y 0..30, wide openings
// inside) entered by a doorway on its west side (y 25) and left by one on its east side (y 5),
// and a corridor loop round its north back to the west corridor. The crossing from door to door
// runs straight through the room's middle.
private static (Dungeon D, uint West) LoopDungeon()
{
var d = new Dungeon();
var c = new uint[3, 3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
c[i, j] = d.Cell(i * 10, j * 10, i * 10 + 10, j * 10 + 10);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
if (i < 2) d.OpenX(c[i, j], c[i + 1, j], i * 10 + 10, j * 10, j * 10 + 10);
if (j < 2) d.OpenY(c[i, j], c[i, j + 1], j * 10 + 10, i * 10, i * 10 + 10);
}
uint west = d.Cell(-10, 22.35, 0, 27.65);
uint east = d.Cell(30, 2.35, 40, 7.65);
d.OpenX(west, c[0, 2], 0, 22.35, 27.65);
d.OpenX(c[2, 0], east, 30, 2.35, 7.65);
uint up1 = d.Cell(-10, 27.65, -4.7, 37.65);
d.OpenY(west, up1, 27.65, -10, -4.7);
uint top1 = d.Cell(-10, 37.65, 10, 42.95);
d.OpenY(up1, top1, 37.65, -10, -4.7);
uint top2 = d.Cell(10, 37.65, 30, 42.95);
d.OpenX(top1, top2, 10, 37.65, 42.95);
uint top3 = d.Cell(30, 37.65, 45.3, 42.95);
d.OpenX(top2, top3, 30, 37.65, 42.95);
uint down1 = d.Cell(40, 7.65, 45.3, 37.65);
d.OpenY(down1, top3, 37.65, 40, 45.3);
uint corner = d.Cell(40, 2.35, 45.3, 7.65);
d.OpenY(corner, down1, 7.65, 40, 45.3);
d.OpenX(east, corner, 40, 2.35, 7.65);
return (d, west);
}
private static void RoomWithPortal()
{
var (d, west) = LoopDungeon();
var geo = d.Geo();
var p = Portal(15, 15);
var before = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo);
Check.True(Nearest(before.Points, p.X, p.Y).Leg < 1.0, $"without the portal the crossing runs through the room's middle ({Nearest(before.Points, p.X, p.Y).Leg:F2} m)");
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, null, new[] { p });
KeptOut(route, p, "portal in the room");
var report = DungeonPathfinder.LastPortalAvoidance;
Check.True(report != null && report.Count == 1, "one line for the one portal");
Check.True(report![0].Bent >= 1, $"the crossing is bent round it ({report[0].Describe()})");
Check.True(report[0].Closed.Count == 0 && report[0].CutCells.Count == 0, "nothing closed: the room is wide enough to go round");
Check.True(report[0].Clear, "the report says clear: " + report[0].Describe());
// Every doorway (narrow opening) still passed through near its centre.
foreach (var (a, b) in d.Graph.Values.SelectMany(n => n.Neighbors.Select(m => (n.CellId, m))).Where(e => e.CellId < e.m))
{
if (!geo.TryGetDoorway(a, b, out var door) || door.IsWide) continue;
double best = double.MaxValue;
for (int i = 0; i < route.Points.Count; i++)
{
var q = route.Points[i]; var s = route.Points[(i + 1) % route.Points.Count];
best = Math.Min(best, SegDist(door.X, door.Y, X(q), Y(q), X(s), Y(s)));
}
Check.True(best < 0.3, $"still through the opening at ({door.X:F1}, {door.Y:F1}) ({best:F2} m off its centre)");
}
// The corners round it are on the room's floor.
foreach (var q in route.Points)
Check.True(geo.OnWalkableFloor(X(q), Y(q), q.Z * 240.0), $"({X(q):F1}, {Y(q):F1}) is on walkable floor");
// A bigger keep-out (a longer nav point reach) keeps further out.
var far = Portal(15, 15, 0, DungeonPathfinder.PortalKeepOutRadius(3.0));
Check.Near(far.Radius, 5.0, 1e-9, "reach 3 yd: keep-out 1.9 + 3.1 m");
KeptOut(DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, null, new[] { far }), far, "a 6 m keep-out");
}
// ── A portal at the back of a dead-end nook (Tiny Hive) ──────────────────
// A 3x3 room of 10 m cells (x 0..30, y -30..0); north of its middle the start cell, a corridor piece
// 5.3 m wide (y 0..10, Tiny Hive's 028902A5), then another (y 10..20, the ramp 028902BB) and a nook
// 4 m deep (y 20..24, 028902BA) with the portal 1.5 m in.
private static (Dungeon D, uint Start, uint Corridor, uint Nook, PatrolPortal P) NookDungeon()
{
var d = new Dungeon();
var c = new uint[3, 3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
c[i, j] = d.Cell(i * 10, -30 + j * 10, i * 10 + 10, -20 + j * 10);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
if (i < 2) d.OpenX(c[i, j], c[i + 1, j], i * 10 + 10, -30 + j * 10, -20 + j * 10);
if (j < 2) d.OpenY(c[i, j], c[i, j + 1], -20 + j * 10, i * 10, i * 10 + 10);
}
uint start = d.Cell(12.35, 0, 17.65, 10);
uint corridor = d.Cell(12.35, 10, 17.65, 20);
uint nook = d.Cell(12.35, 20, 17.65, 24);
d.OpenY(c[1, 2], start, 0, 12.35, 17.65);
d.OpenY(start, corridor, 10, 12.35, 17.65);
d.OpenY(corridor, nook, 20, 12.35, 17.65);
return (d, start, corridor, nook, Portal(15, 21.5));
}
private static readonly DungeonPatrolOptions Everything = new() { Coverage = PatrolCoverage.Everything, LookInRoomMeters = 20 };
private static void DeadEndTurnedRoundBefore()
{
var (d, start, corridor, nook, p) = NookDungeon();
var geo = d.Geo();
var before = DungeonPathfinder.BuildPatrolRoute(d.Graph, start, null, geo, Everything);
Check.True(Nearest(before.Points, p.X, p.Y).Point < DungeonPathfinder.PortalTouchMeters,
$"without the portal a point is within touching distance of it ({Nearest(before.Points, p.X, p.Y).Point:F2} m): {Pts(before.Points)}");
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, start, null, geo, Everything, new[] { p });
KeptOut(route, p, "portal in the nook");
var r = DungeonPathfinder.LastPortalAvoidance![0];
Check.True(r.Closed.Any(e => (e.A == corridor && e.B == nook) || (e.A == nook && e.B == corridor)),
"the nook's doorway is closed: " + r.Describe());
double north = route.Points.Max(Y);
Check.True(north > 10 && north < p.Y - p.Radius,
$"it turns round in the corridor before the portal (northmost point y {north:F1}; corridor 10..20, portal at {p.Y})");
Check.True(r.Nearest < p.Radius + 4.0, $"close up to it, not a whole cell short ({r.Nearest:F1} m)");
Check.True(route.Points.Any(q => Y(q) < -5), "the room south of the start is still walked");
}
private static void CellWalkKeepsOut()
{
// Without the map geometry (DungeonLOS not up yet) the old cell walk: points 30% / 50% of the
// way between cell centres. A portal 1.5 m past the start's north opening.
var (d, start, corridor, _, _) = NookDungeon();
var p = Portal(15, 11.5);
var before = DungeonPathfinder.BuildPatrolRoute(d.Graph, start, null, null, Everything);
Check.True(Nearest(before.Points, p.X, p.Y).Point < DungeonPathfinder.PortalTouchMeters,
$"the cell walk turned round within touching distance of it ({Nearest(before.Points, p.X, p.Y).Point:F2} m): {Pts(before.Points)}");
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, start, null, null, Everything, new[] { p });
KeptOut(route, p, "cell walk, portal past the start's opening");
var r = DungeonPathfinder.LastPortalAvoidance![0];
Check.True(r.Closed.Contains((start, corridor)) || r.Closed.Contains((corridor, start)), "the opening by it is closed: " + r.Describe());
}
// ── A start next to a portal ─────────────────────────────────────────────
private static void StartNextToPortalWalksAway()
{
// An open room (x 0..20, y 0..20) with doorways west and east (y 10) and a loop round its
// north; the portal in its middle, the character 2 m north of it (inside the circle).
var d = new Dungeon();
uint room = d.Cell(0, 0, 20, 20);
uint w = d.Cell(-10, 7.35, 0, 12.65), e = d.Cell(20, 7.35, 30, 12.65);
d.OpenX(w, room, 0, 7.35, 12.65);
d.OpenX(room, e, 20, 7.35, 12.65);
uint wn = d.Cell(-10, 12.65, -4.7, 30), top = d.Cell(-10, 30, 30, 35.3), en = d.Cell(24.7, 12.65, 30, 30);
d.OpenY(w, wn, 12.65, -10, -4.7);
d.OpenY(wn, top, 30, -10, -4.7);
d.OpenY(en, top, 30, 24.7, 30);
d.OpenY(e, en, 12.65, 24.7, 30);
var geo = d.Geo();
var p = Portal(10, 10);
double px = 10, py = 12;
var portals = new[] { p };
var walk = DungeonPathfinder.PortalWalkOut(geo, portals, px, py, 0, 1.0);
Check.NotNull(walk, "standing inside the circle: a spot to walk out to");
double wd = Math.Sqrt((X(walk!) - p.X) * (X(walk) - p.X) + (Y(walk) - p.Y) * (Y(walk) - p.Y));
Check.True(wd >= p.Radius, $"the spot is outside the circle ({wd:F2} m)");
Check.True((X(walk) - px) * (px - p.X) + (Y(walk) - py) * (py - p.Y) > 0, $"straight away from the portal: ({X(walk):F1}, {Y(walk):F1})");
// The walk there never gets nearer the portal than the character already is.
for (int i = 0; i <= 20; i++)
{
double t = i / 20.0, x = px + (X(walk) - px) * t, y = py + (Y(walk) - py) * t;
Check.True(Math.Sqrt((x - p.X) * (x - p.X) + (y - p.Y) * (y - p.Y)) >= 2.0 - 1e-6, $"walking out, {t:F2} of the way: no nearer the portal");
}
Check.Null(DungeonPathfinder.PortalWalkOut(geo, portals, 3, 3, 0, 1.0), "outside the circle: nothing to walk out of");
// The patrol from there keeps out, and the way from the walk-out spot to a first point on the
// portal's other side (south) goes round it.
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, room, null, geo, null, portals, (X(walk), Y(walk), 0));
KeptOut(route, p, "start next to a portal");
var first = At(10, 3);
var lead = DungeonPathfinder.PortalLeadIn(d.Graph, geo, portals, walk, first, 1.0);
Check.True(lead.Count >= 1, "corners round the portal to the first point");
var way = new List<NavPoint> { walk };
way.AddRange(lead);
way.Add(first);
var (_, leg) = Nearest(way, p.X, p.Y, closed: false);
Check.True(leg >= p.Radius - 0.02, $"the way to the first point keeps out ({leg:F2} m): {Pts(way)}");
Check.True(DungeonPathfinder.PortalLeadIn(d.Graph, geo, portals, At(3, 3), At(3, 17), 1.0).Count == 0, "a clear walk needs no corners");
}
private static void PortalSplitsStartCorridor()
{
// A corridor (x 0..5.3, y 0..20) between a room south (y -10..0) and a room north (y 20..30),
// nothing else joining them; the portal across the corridor's middle.
var d = new Dungeon();
uint south = d.Cell(-5, -10, 10.3, 0), corr = d.Cell(0, 0, 5.3, 20), north = d.Cell(-5, 20, 10.3, 30);
uint sw = d.Cell(-15, -7.65, -5, -2.35), nw = d.Cell(-15, 22.35, -5, 27.65);
d.OpenY(south, corr, 0, 0, 5.3);
d.OpenY(corr, north, 20, 0, 5.3);
d.OpenX(sw, south, -5, -7.65, -2.35);
d.OpenX(nw, north, -5, 22.35, 27.65);
var geo = d.Geo();
var p = Portal(2.65, 10);
var portals = new[] { p };
var n = DungeonPathfinder.BuildPatrolRoute(d.Graph, corr, null, geo, Everything, portals, (2.65, 16, 0));
KeptOut(n, p, "character north of the portal");
Check.True(n.Points.All(q => Y(q) > p.Y), $"only the north side: {Pts(n.Points)}");
Check.True(n.Points.Any(q => Y(q) > 20), "the room north is walked");
var s = DungeonPathfinder.BuildPatrolRoute(d.Graph, corr, null, geo, Everything, portals, (2.65, 4, 0));
KeptOut(s, p, "character south of the portal");
Check.True(s.Points.All(q => Y(q) < p.Y), $"only the south side: {Pts(s.Points)}");
Check.True(s.Points.Any(q => Y(q) < 0), "the room south is walked");
}
private static void OtherLevelIgnored()
{
var (d, west) = LoopDungeon();
var geo = d.Geo();
var plain = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo);
var up = Portal(15, 15, 6.0); // a floor 6 m above
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, null, new[] { up });
Check.Eq(Pts(route.Points), Pts(plain.Points), "the same patrol as without it");
var r = DungeonPathfinder.LastPortalAvoidance![0];
Check.True(double.IsPositiveInfinity(r.Nearest) && r.Closed.Count == 0 && r.Bent == 0, "nothing done about it: " + r.Describe());
}
// ── Tiny Hive on the real dats ───────────────────────────────────────────
private const string AcDir = @"C:\Turbine\Asheron's Call";
private static void TinyHiveRealDats()
{
if (!Directory.Exists(AcDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; }
var loader = new GeometryLoader();
if (!loader.Initialize(AcDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; }
try
{
const uint lb = 0x0289, start = 0x028902A5, nook = 0x028902BA, ramp = 0x028902BB;
var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
Check.True(graph.Count > 400 && geo != null, $"Tiny Hive loaded ({graph.Count} cells)");
// +Buffy's settings on 2026-10-23: coverage Everything, floors walked, rooms looked into from 20 m.
var opt = new DungeonPatrolOptions { Coverage = PatrolCoverage.Everything, AvoidHazardFloors = false, LookInRoomMeters = 20 };
// The Surface Portal (weenie 11218, 0x7028905D): cell 028902BA, local (110, -3.77927, -23.995).
var p = new PatrolPortal { Id = 0x7028905D, Name = "Surface Portal", Cell = nook, X = 2 * 192 + 110, Y = 0x89 * 192 - 3.77927, Z = -23.995 };
var before = DungeonPathfinder.BuildPatrolRoute(graph, start, null, geo, opt);
Check.Eq(before.Points.Count, 355, "the 355-point patrol of the report");
Check.True(Nearest(before.Points, p.X, p.Y).Point < 0.1, $"its waypoint 1 sat on the portal ({Nearest(before.Points, p.X, p.Y).Point:F2} m)");
var route = DungeonPathfinder.BuildPatrolRoute(graph, start, null, geo, opt, new[] { p });
KeptOut(route, p, "Tiny Hive");
var r = DungeonPathfinder.LastPortalAvoidance![0];
Check.True(r.Closed.Contains((nook, ramp)) || r.Closed.Contains((ramp, nook)), "the nook's doorway closed: " + r.Describe());
Check.True(route.Points.Count > 300, $"the rest of the dungeon still patrolled ({route.Points.Count} points)");
Console.WriteLine(" " + r.Describe());
}
finally { DungeonPathfinder.InvalidateCache(); }
}
// ── The plugin side ──────────────────────────────────────────────────────
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const uint Player = 0x50000001;
private static void PluginCollectsPortals()
{
FakeHost.Reset();
const uint surface = 0x7028905D, other = 0x7028905E, lamp = 0x70289060, outside = 0x7029A001;
FakeHost.Names[Player] = "Tester";
FakeHost.Positions[Player] = (0x028902A5, 110f, 92f, -30f);
FakeHost.PlayerPose = (0x028902A5, 110f, 92f, -30f);
FakeHost.Names[surface] = "Surface Portal";
FakeHost.ItemTypes[surface] = 0x00010000;
FakeHost.Positions[surface] = (0x028902BA, 110f, -3.77927f, -23.995f);
FakeHost.Names[lamp] = "Lamp";
FakeHost.ItemTypes[lamp] = 0x00000080;
FakeHost.Positions[lamp] = (0x028902BA, 111f, -3f, -24f);
FakeHost.Names[outside] = "Tiny Hive Portal";
FakeHost.ItemTypes[outside] = 0x00010000;
FakeHost.Positions[outside] = (0x24BD002F, 50f, 50f, 0f);
var host = FakeHost.Create(Player);
var plugin = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
var settings = new LegacyUiSettings();
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, settings);
void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(plugin, v);
object? Call(string m, params object?[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(plugin, a);
Set("_dashboard", dash);
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
Set("_objectCache", cache);
foreach (uint id in new[] { surface, lamp, outside }) cache.OnCreateObject(id);
cache.Tick();
var portals = (List<PatrolPortal>)Call("PatrolPortalsIn", 0x0289u)!;
Check.Eq(portals.Count, 1, "one portal in Tiny Hive (not the lamp, not the one outside)");
var p = portals[0];
Check.Eq(p.Id, surface, "the Surface Portal");
Check.Eq(p.Cell, 0x028902BAu, "its cell");
Check.Near(p.X, 494.0, 1e-3, "world x = 2 x 192 + 110");
Check.Near(p.Y, 26300.22, 1e-2, "world y = 0x89 x 192 - 3.78");
Check.Near(p.Z, -23.995, 1e-3, "its height");
Check.Near(p.Radius, DungeonPathfinder.PortalKeepOutDefault, 1e-9, "keep-out 3.5 m at the default nav point reach");
settings.FollowNavMin = 3.0f;
Check.True(((List<PatrolPortal>)Call("PatrolPortalsIn", 0x0289u)!)[0].Radius > 5.5, "a 3 yd reach keeps further out");
settings.FollowNavMin = 1.5f;
// Built round it: no rebuild. Another one comes into view: rebuild.
Set("_dunPatrolLandblock", 0x0289u);
Call("MarkPatrolPortals", portals);
Set("_dunPatrolPortalCheckAt", 0L);
Check.False((bool)Call("PatrolPortalAppeared")!, "the portals it was built round: nothing to do");
FakeHost.Names[other] = "Portal to the Hive Depths";
FakeHost.ItemTypes[other] = 0x00010000;
FakeHost.Positions[other] = (0x02890270, 100f, 50f, -36f);
cache.OnCreateObject(other);
cache.Tick();
Set("_dunPatrolPortalCheckAt", 0L);
Check.True((bool)Call("PatrolPortalAppeared")!, "a new portal in the dungeon: rebuild");
Check.True(FakeHost.Logs.Any(l => l.Contains("came into view") && l.Contains("0x7028905E")), "and it says which");
Check.False((bool)Call("PatrolPortalAppeared")!, "checked at most once a second");
}
}

View file

@ -23,6 +23,7 @@ internal static class StuckCastTests
{
r.Add("stuck cast: after a 'too busy' UseDone nothing starts until the server answers; no timer re-send while our cast is open", NoResendAfterTooBusy);
r.Add("stuck cast: with no cast of ours open, one probe after 1.5 s, then doubling; a UseDone(0) clears", ProbeWhenNothingOpen);
r.Add("too busy (Conquest 10-25): a try held by another check (animating) is not spent; the next asker (combat) gets it", TryNotSpentWhenHeld);
r.Add("stuck cast: a held cast is turned to its target at cycle + 1 s, broken by a jump TurnGraceMs after the turn; a normal 4 s cast trips neither", TurnThenJump);
r.Add("stuck cast: already facing the target (no turn), the jump is at cycle + 2 s", JumpWithoutTurn);
r.Add("stuck cast: no starts in the air; after landing, no UseDone in 3 s -> Peace mode, 3 s more -> going on", AfterTheJump);
@ -342,6 +343,36 @@ internal static class StuckCastTests
finally { Done(); }
}
// Conquest report R-20261025-183343 (Dargoth Hera): a corpse pickup and a cast went out together, the
// cast was refused 'too busy', and the buff step took all three tries after it while the character was
// still animating, so it sent nothing; combat never got a try and the fight stood for the latch's 15 s.
private static void TryNotSpentWhenHeld()
{
var host = Setup();
try
{
Check.True(MayAs(host, "Combat", HealNeed.None), "free");
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused next to a pickup (no UseDone of its own)
Check.False(MayAs(host, "Combat", HealNeed.None), "held right after the 0x1D");
_t += ActionPacer.BusyProbeMs;
FakeHost.CastBusy = 1; // the client still animates
Check.False(MayAs(host, "Buff", HealNeed.None), "the buff step's try is held by the animation");
FakeHost.CastBusy = 0;
Check.True(MayAs(host, "Combat", HealNeed.None), "combat gets the try the buff step couldn't use");
Check.False(MayAs(host, "Buff", HealNeed.None), "and only one start has it");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("one try (#1)")), 1, "one try logged");
Check.True(FakeHost.Logs.Any(l => l.Contains("Combat: one try (#1)")), "and it was combat's");
// The next try is counted from the one that went (doubling as before).
_t += ActionPacer.BusyProbeMs * 2 - 1;
Check.False(MayAs(host, "Combat", HealNeed.None), "the next try waits twice as long");
_t += 1;
Check.True(MayAs(host, "Combat", HealNeed.None), "then goes");
}
finally { Done(); }
}
private static void ProbeWhenNothingOpen()
{
var host = Setup();

View file

@ -23,7 +23,7 @@ internal static class VitalsTests
r.Add("vitals: Stamina to Health follows its own health line and stamina floor", StaminaToHealthThresholds);
r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults);
r.Add("vitals: Re-stam To keeps a started recharge going to its line; off = one recharge as before", RestamTo);
r.Add("vitals: a recharge started in a fight finishes to Re-stam To after the fight", RestamRunOutlivesFight);
r.Add("vitals: a recharge started in a fight, or under Re-stam At just after one, finishes to Re-stam To", RestamRunOutlivesFight);
r.Add("vitals: a Re-stam To run counts casts sent, not the ticks spent waiting for one", RestamRunCountsSentCasts);
r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst);
r.Add("vitals: a listed potion whose stack ran out is drunk from the next stack of that name", ListedPotionNextStack);
@ -336,6 +336,21 @@ internal static class VitalsTests
Check.Eq(BuffManager.StaminaLine(false, 91, s, ref run, ref casts), 60, "reached 90: done, the top-off line again");
Check.False(run, "the recharge ended");
Check.Eq(BuffManager.StaminaLine(false, 55, s, ref run, ref casts), 60, "no recharge running: idle uses Top Stam");
// Drakkon, 10-23: the fight ended with stamina under Re-stam At before a recharge started (a
// Stamina to Health drained 174 just before the kill): the top-off stopped at 60.
run = false; casts = 0;
Check.Eq(BuffManager.StaminaLine(false, 20, s, ref run, ref casts), 90, "no monster, 20%: under Re-stam At, recharge to 90");
Check.True(run, "a recharge started");
casts++;
Check.Eq(BuffManager.StaminaLine(false, 65, s, ref run, ref casts), 90, "65% after one kit: still to 90, not Top Stam 60");
casts++;
Check.Eq(BuffManager.StaminaLine(false, 92, s, ref run, ref casts), 60, "reached 90: done");
Check.Eq(BuffManager.StaminaLine(false, 40, s, ref run, ref casts), 60, "40% with no recharge running (over Re-stam At): Top Stam as before");
var off = new LegacyUiSettings { RestamAt = 35, RestamTo = 0, TopOffStam = 60 };
run = false; casts = 0;
Check.Eq(BuffManager.StaminaLine(false, 20, off, ref run, ref casts), 60, "Re-stam To off: Top Stam as before");
Check.False(run, "and no recharge run");
}
// Drakkon, 2026-10-20: every Re-stam To run stopped after one Robustification. The stamina chain also

View file

@ -30,6 +30,34 @@ internal static class WallTests
r.Add("walls: far off the target, it turns first and casts after the settle; facing it, no turn", WallFacing);
r.Add("walls: the cast itself waits for the turn, then goes as an area cast", WallCastThroughAttack);
r.Add("walls: UseWall, Wall Range and Min Wall Targets load off / 0 / 3 from old files", OldSettings);
r.Add("rings: a ring is due only when one is known; Void has none, so a Void caster casts its bolt (#rynth-issues 2026-10-23)", RingNeedsAKnownRing);
}
// A Void caster on DreamWeave with Use Ring on stood in the fight once 3+ monsters were near:
// the ring override picked "Nether Ring", which doesn't exist, and nothing else was tried
// ("No spell found: elem=Nether warTier=1 voidTier=7").
private static void RingNeedsAKnownRing()
{
var rig = new Rig(7, "Nether Bolt VII", "Nether Streak VII", "Frost Bolt VI", "Halo of Frost", "Frost Ring II");
rig.S.RingRange = 20; rig.S.MinRingTargets = 3; rig.S.WallRange = 0;
int near = 4;
rig.C.RingCountOverride = () => near;
var boltRing = new MonsterRule { Name = "Gilded Shade", UseBolt = true, UseRing = true };
Check.Eq(rig.Cast("Nether", boltRing), ("Nether Bolt VII", "Bolt"), "Void, 4 near (3 needed), no Void ring exists: Nether Bolt");
var streakRing = new MonsterRule { Name = "Gilded Shade", UseBolt = false, UseStreak = true, UseRing = true };
Check.Eq(rig.Cast("Nether", streakRing), ("Nether Streak VII", "Streak"), "Void, Streak + Ring: Nether Streak");
Check.True(FakeHost.Logs.Any(l => l.Contains("no Nether ring spell known")), "logged once");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("no Nether ring spell known")), 1, "only once");
Check.Eq(rig.Cast("Cold", boltRing).Shape, "Ring", "War with a cold ring known: still the ring");
near = 2;
Check.Eq(rig.Cast("Cold", boltRing), ("Frost Bolt VI", "Bolt"), "too few near: Bolt");
var noRing = new Rig(7, "Flame Bolt VI");
noRing.S.RingRange = 20; noRing.S.MinRingTargets = 3; noRing.S.WallRange = 0;
noRing.C.RingCountOverride = () => 5;
Check.Eq(noRing.Cast("Fire", boltRing), ("Flame Bolt VI", "Bolt"), "War with no fire ring known: Flame Bolt, not nothing");
}
private static int Id(string name) => SpellTable.Named(name).Select(r => r.Id).First();