Snapshot for release 2026.11.2.1 (internal 03dbb32)
This commit is contained in:
parent
ce1cc11ebe
commit
79cbb84d61
77 changed files with 8622 additions and 224 deletions
|
|
@ -130,6 +130,9 @@ internal static unsafe class FakeHost
|
|||
public static bool AttackSendCalls;
|
||||
/// <summary>Every melee or missile attack (kind, target, height, power), in order (opt-in with <see cref="AttackSendCalls"/>).</summary>
|
||||
public static readonly List<(string Kind, uint Target, int Height, float Power)> AttackCalls = new();
|
||||
/// <summary>Opt-in (set before Create): wires CancelAttack; calls are counted in <see cref="CancelAttacks"/>.</summary>
|
||||
public static bool CancelAttackCalls;
|
||||
public static int CancelAttacks;
|
||||
/// <summary>Opt-in: wires SetMotion; calls land in <see cref="MotionCalls"/>.</summary>
|
||||
public static bool SetMotionCalls;
|
||||
/// <summary>Every SetMotion (motion, on), in order (opt-in with <see cref="SetMotionCalls"/>).</summary>
|
||||
|
|
@ -307,7 +310,7 @@ internal static unsafe class FakeHost
|
|||
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
|
||||
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
|
||||
Logs.Clear(); Chat.Clear(); ChatTypes.Clear(); ChatCommands.Clear(); AfterCastSpell = null;
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null;
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); CancelAttackCalls = false; CancelAttacks = 0; Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null;
|
||||
Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1;
|
||||
RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true;
|
||||
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
|
||||
|
|
@ -431,6 +434,8 @@ internal static unsafe class FakeHost
|
|||
}
|
||||
if (CombatModeCalls)
|
||||
api.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&ChangeCombatMode;
|
||||
if (CancelAttackCalls)
|
||||
api.CancelAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&CancelAttack;
|
||||
if (TargetVitals.Count > 0)
|
||||
api.GetTargetVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, uint*, uint*, uint*, int>)&GetTargetVitals;
|
||||
if (LiveObjectsCalls)
|
||||
|
|
@ -872,6 +877,9 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); Sent.Add(AutoRun ? "autorun on" : "autorun off"); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int CancelAttack() { CancelAttacks++; return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int MeleeAttack(uint target, int height, float power) { AttackCalls.Add(("melee", target, height, power)); return 1; }
|
||||
|
||||
|
|
|
|||
|
|
@ -88,13 +88,17 @@ internal static class Program
|
|||
VTankYieldTests.Register(runner);
|
||||
OffhandTests.Register(runner);
|
||||
HandSwapTests.Register(runner);
|
||||
OutdoorHuntTests.Register(runner);
|
||||
HuntBuildingTests.Register(runner);
|
||||
FloodPerfTests.Register(runner);
|
||||
LootSalvageTests.Register(runner);
|
||||
LootCorpseTests.Register(runner);
|
||||
LootRetryTimingTests.Register(runner);
|
||||
LootClaimMismatchTests.Register(runner);
|
||||
BoostNavTests.Register(runner);
|
||||
LootNothingLineTests.Register(runner);
|
||||
ChestLootTests.Register(runner);
|
||||
ItemToolTests.Register(runner);
|
||||
OwnCorpseTests.Register(runner);
|
||||
UseRefusalTests.Register(runner);
|
||||
CorpseKillerTests.Register(runner);
|
||||
|
|
@ -170,6 +174,7 @@ internal static class Program
|
|||
SkCombatAddonTests.Register(runner);
|
||||
DoorTests.Register(runner);
|
||||
ServerPolicyTests.Register(runner);
|
||||
PatrolModeTests.Register(runner);
|
||||
BlankLoadTests.Register(runner);
|
||||
GiveProfileTests.Register(runner);
|
||||
TinkerTests.Register(runner);
|
||||
|
|
|
|||
267
Tools/RynthCore.RynthAiHostTests/Tests/BoostNavTests.cs
Normal file
267
Tools/RynthCore.RynthAiHostTests/Tests/BoostNavTests.cs
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Boost Nav Priority, owner's rule (2026-11-02): with the flag on RynthAi ONLY navigates. No hunting,
|
||||
// no looting, and no fighting back even with a monster attacking it; with a route (or a follow) it
|
||||
// navigates, with nothing to navigate it stands idle. Buffing and vitals still run, buffing on top.
|
||||
// R-20261102-041824-3f7c: the flag came on through NavLootPrio (or a hunting meta), there was no
|
||||
// route, and the arbiter's WantNav-guarded clause let combat win, so the bot hunted as usual and the
|
||||
// player never noticed the flag; they only saw that it would not loot. The first fight or corpse
|
||||
// the flag skips now says so in chat, once per session.
|
||||
internal static class BoostNavTests
|
||||
{
|
||||
private const uint Player = 0x50000F51;
|
||||
private const uint Lb = 0xA9B40000;
|
||||
private const uint Mob = 0x80000451;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("boost nav (owner, 2026-11-02): the arbiter never picks Combat or Looting with the flag on, route or not; buffing stays on top", ArbiterRule);
|
||||
r.Add("boost nav: no route, a monster attacking: never Combat or Looting, no attack sent, no target locked", NoRouteNeverFights);
|
||||
r.Add("boost nav: with a route: Navigating every tick, no attack sent even with a monster on top", RouteNavigatesOnly);
|
||||
r.Add("boost nav: turned on mid-fight: the target is dropped, the server attack cancelled, the stance back to Peace", MidFightDisengages);
|
||||
r.Add("boost nav: turned off again: hunting resumes (target locked, attack sent)", OffResumesHunting);
|
||||
r.Add("boost nav: the skipped fight is said in chat and the log once per session, never with the flag off", NoticeOncePerSession);
|
||||
}
|
||||
|
||||
// ── 1. The pure rule ──────────────────────────────────────────────────────
|
||||
|
||||
private static BotActivity D(bool buff = false, bool combat = false, bool loot = false, bool salv = false, bool nav = false,
|
||||
bool engaged = false, bool boostNav = true, bool boostLoot = false, bool starved = false,
|
||||
bool forced = false, bool follow = false)
|
||||
=> ActivityArbiter.Decide(new ArbiterInputs(true, buff, combat, loot, salv, nav,
|
||||
combatEngaged: engaged, boostNav: boostNav, boostLoot: boostLoot, followActive: follow,
|
||||
lootStarved: starved, forcedLoot: forced));
|
||||
|
||||
private static void ArbiterRule()
|
||||
{
|
||||
// Every combination of combat / engaged / loot / loot-starved / Boost Loot, no route: Idle.
|
||||
for (int bits = 0; bits < 32; bits++)
|
||||
{
|
||||
bool combat = (bits & 1) != 0, engaged = (bits & 2) != 0, loot = (bits & 4) != 0,
|
||||
starved = (bits & 8) != 0, boostLoot = (bits & 16) != 0;
|
||||
var noRoute = D(combat: combat, engaged: engaged, loot: loot, starved: starved, boostLoot: boostLoot);
|
||||
Check.Eq(noRoute, BotActivity.Idle, $"no route (combat={combat} engaged={engaged} loot={loot} starved={starved} boostLoot={boostLoot}): Idle");
|
||||
var route = D(combat: combat, engaged: engaged, loot: loot, starved: starved, boostLoot: boostLoot, nav: true);
|
||||
Check.Eq(route, BotActivity.Navigating, $"a route (combat={combat} engaged={engaged} loot={loot}): Navigating");
|
||||
}
|
||||
Check.Eq(D(combat: true, engaged: true, nav: true, follow: true), BotActivity.Navigating, "a follow is navigating too");
|
||||
Check.Eq(D(buff: true, combat: true, nav: true), BotActivity.Buffing, "buffing still outranks it");
|
||||
Check.Eq(D(buff: true, combat: true), BotActivity.Buffing, "buffing with no route too");
|
||||
Check.Eq(D(loot: true, forced: true), BotActivity.Looting, "a /ra lootthis container is still looted (no route)");
|
||||
Check.Eq(D(loot: true, forced: true, nav: true), BotActivity.Navigating, "with a route nav keeps the tick, as before");
|
||||
Check.Eq(D(salv: true, combat: true), BotActivity.Salvaging, "the salvage queue (an inventory chore) still runs");
|
||||
Check.Eq(D(combat: true, nav: true, boostNav: false), BotActivity.Combat, "flag off: combat outranks nav as usual");
|
||||
Check.Eq(D(loot: true, boostNav: false), BotActivity.Looting, "flag off: looting as usual");
|
||||
Check.Eq(ActivityArbiter.ToBotAction(BotActivity.Idle), "Default", "Idle shows as Default (the dashboard reads Idle)");
|
||||
}
|
||||
|
||||
// ── A melee rig, ticked the way OnTick ticks it ───────────────────────────
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly CombatManager C;
|
||||
public bool Route;
|
||||
public readonly List<BotActivity> Decisions = new();
|
||||
|
||||
public Rig(float mobY)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.AttackSendCalls = true;
|
||||
FakeHost.CancelAttackCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Melee;
|
||||
Place(Player, "Me", 96, 96, creature: false);
|
||||
Place(Mob, "Drudge Skulker", 96, mobY);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
FakeHost.HeadingDeg = 0;
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
MonsterRange = 50, IsMacroRunning = true, EnableCombat = true, EnableLooting = true,
|
||||
MonsterRules = new List<MonsterRule> { new() { Name = "Default" } },
|
||||
};
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { Mob });
|
||||
C = new CombatManager(host, S, cache);
|
||||
C.SetPlayerId(Player);
|
||||
C.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
|
||||
C.ScanNearbyTargets();
|
||||
}
|
||||
|
||||
/// <summary>One tick: the arbiter decides from combat's own wants (as OnTick does), writes
|
||||
/// BotAction, and combat ticks. The attack cadence runs on the real clock, so it is reset.</summary>
|
||||
public BotActivity Tick()
|
||||
{
|
||||
bool wantCombat = S.EnableCombat && C.HasEngageableTarget;
|
||||
var inputs = new ArbiterInputs(S.IsMacroRunning, false, wantCombat, false, false, Route,
|
||||
combatEngaged: C.IsUnderCloseAttack, boostNav: S.BoostNavPriority, boostLoot: S.BoostLootPriority);
|
||||
BotActivity act = ActivityArbiter.Decide(in inputs);
|
||||
S.BotAction = ActivityArbiter.ToBotAction(act);
|
||||
LastAttackCmd.SetValue(C, DateTime.MinValue);
|
||||
C.OnHeartbeat();
|
||||
Decisions.Add(act);
|
||||
return act;
|
||||
}
|
||||
|
||||
public void Ticks(int n) { for (int i = 0; i < n; i++) Tick(); }
|
||||
|
||||
/// <summary>Ticks until an attack reaches the server (false if none does in 40 ticks).</summary>
|
||||
public bool TickToAttack()
|
||||
{
|
||||
int before = FakeHost.AttackCalls.Count;
|
||||
for (int i = 0; i < 40 && FakeHost.AttackCalls.Count == before; i++) Tick();
|
||||
return FakeHost.AttackCalls.Count > before;
|
||||
}
|
||||
|
||||
private static readonly FieldInfo LastAttackCmd = typeof(CombatManager).GetField("lastAttackCmd", Any)!;
|
||||
}
|
||||
|
||||
private static void Place(uint id, string name, float x, float y, bool creature = true)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
|
||||
if (creature) FakeHost.ItemTypes[id] = 0x10;
|
||||
}
|
||||
|
||||
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
|
||||
// ── 2. No route ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void NoRouteNeverFights()
|
||||
{
|
||||
var rig = new Rig(mobY: 97.5f); // 1.5 m: on top of us, the "attacking me" case
|
||||
rig.S.BoostNavPriority = true;
|
||||
Check.True(rig.C.HasEngageableTarget && rig.C.IsUnderCloseAttack, "rig: a monster close enough to be attacking");
|
||||
rig.Ticks(60);
|
||||
Check.False(rig.Decisions.Any(a => a is BotActivity.Combat or BotActivity.Looting), "never Combat or Looting");
|
||||
Check.True(rig.Decisions.All(a => a == BotActivity.Idle), "Idle the whole time (nothing to navigate)");
|
||||
Check.Eq(FakeHost.AttackCalls.Count, 0, "no attack sent");
|
||||
Check.Eq(rig.C.activeTargetId, 0, "no target locked");
|
||||
Check.True(rig.C.BoostNavStoodDown, "combat stands down for the flag");
|
||||
Check.True(Logged("Boost Nav Priority is on - no hunting and no fighting back"), "and the log says why");
|
||||
Check.True(rig.C.HasEngageableTarget, "the scan still runs (it is what the notice reads)");
|
||||
}
|
||||
|
||||
// ── 3. A route ────────────────────────────────────────────────────────────
|
||||
|
||||
private static void RouteNavigatesOnly()
|
||||
{
|
||||
var rig = new Rig(mobY: 97.5f);
|
||||
rig.S.BoostNavPriority = true;
|
||||
rig.Route = true;
|
||||
rig.Ticks(60);
|
||||
Check.True(rig.Decisions.All(a => a == BotActivity.Navigating), "Navigating every tick");
|
||||
Check.Eq(rig.S.BotAction, "Navigating", "BotAction says Navigating");
|
||||
Check.Eq(FakeHost.AttackCalls.Count, 0, "no attack sent");
|
||||
Check.Eq(rig.C.activeTargetId, 0, "no target locked");
|
||||
}
|
||||
|
||||
// ── 4. Mid-fight ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void MidFightDisengages()
|
||||
{
|
||||
var rig = new Rig(mobY: 99f); // 3 m north
|
||||
Check.True(rig.TickToAttack(), "flag off: the fight starts (an attack goes out)");
|
||||
Check.Eq((uint)rig.C.activeTargetId, Mob, "the Drudge is the target");
|
||||
Check.Eq(rig.Decisions[^1], BotActivity.Combat, "in Combat");
|
||||
int attacks = FakeHost.AttackCalls.Count;
|
||||
int cancels = FakeHost.CancelAttacks;
|
||||
FakeHost.CombatModeRequests.Clear();
|
||||
|
||||
rig.S.BoostNavPriority = true; // NavLootPrio, or a meta's SetOpt navpriorityboost
|
||||
Check.Eq(rig.Tick(), BotActivity.Idle, "the next tick: Idle, not Combat");
|
||||
Check.Eq(rig.C.activeTargetId, 0, "the target is dropped");
|
||||
Check.True(FakeHost.CancelAttacks > cancels, "the server's attack is cancelled (no more swings, no walk to the mob)");
|
||||
Check.True(Logged("DropTarget 0x80000451: Boost Nav Priority is on"), "the drop is logged with the reason");
|
||||
Check.True(FakeHost.CombatModeRequests.Contains(CombatMode.NonCombat), "Peace Mode When Idle: back to Peace, no stance left up");
|
||||
|
||||
FakeHost.CombatModeValue = CombatMode.NonCombat; // the server lands the swap
|
||||
int modeAsks = FakeHost.CombatModeRequests.Count;
|
||||
rig.Ticks(60);
|
||||
Check.Eq(FakeHost.AttackCalls.Count, attacks, "no attack after the flag came on");
|
||||
Check.Eq(rig.C.activeTargetId, 0, "nothing re-locked");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, modeAsks, "in Peace: no more mode changes");
|
||||
Check.False(rig.Decisions.Skip(rig.Decisions.Count - 60).Any(a => a == BotActivity.Combat), "never Combat again while it is on");
|
||||
}
|
||||
|
||||
// ── 5. Off again ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void OffResumesHunting()
|
||||
{
|
||||
var rig = new Rig(mobY: 99f);
|
||||
rig.S.BoostNavPriority = true;
|
||||
rig.Ticks(20);
|
||||
Check.Eq(FakeHost.AttackCalls.Count, 0, "on: nothing attacked");
|
||||
|
||||
rig.S.BoostNavPriority = false;
|
||||
Check.True(rig.TickToAttack(), "off: an attack goes out again");
|
||||
Check.Eq((uint)rig.C.activeTargetId, Mob, "the Drudge is locked");
|
||||
Check.True(rig.Decisions.Contains(BotActivity.Combat), "the arbiter gives Combat the tick again");
|
||||
Check.False(rig.C.BoostNavStoodDown, "combat no longer stands down");
|
||||
Check.True(Logged("Boost Nav Priority is off - hunting again"), "logged once it is off");
|
||||
// Looting coming back once the flag is off: LootClaimMismatchTests' Boost Nav test.
|
||||
}
|
||||
|
||||
// ── 6. The notice ─────────────────────────────────────────────────────────
|
||||
|
||||
private static RynthAiPlugin Plugin()
|
||||
{
|
||||
var p = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
return p;
|
||||
}
|
||||
|
||||
private static void Note(RynthAiPlugin p, LegacyUiSettings s, bool wantCombat)
|
||||
=> typeof(RynthAiPlugin).GetMethod("NoteBoostNavSkip", Any)!.Invoke(p, new object[] { s, wantCombat });
|
||||
|
||||
private static int NoticeCount() => FakeHost.Chat.Count(c => c == RynthAiPlugin.BoostNavNotice);
|
||||
|
||||
private static void NoticeOncePerSession()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Create(Player);
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, EnableLooting = false };
|
||||
var p = Plugin();
|
||||
|
||||
Note(p, s, wantCombat: true);
|
||||
Check.Eq(NoticeCount(), 0, "flag off: nothing said");
|
||||
|
||||
s.BoostNavPriority = true;
|
||||
Note(p, s, wantCombat: false);
|
||||
Check.Eq(NoticeCount(), 0, "flag on, nothing skipped (no monster, looting off): nothing said");
|
||||
|
||||
s.IsMacroRunning = false;
|
||||
Note(p, s, wantCombat: true);
|
||||
Check.Eq(NoticeCount(), 0, "macro off: nothing said");
|
||||
s.IsMacroRunning = true;
|
||||
|
||||
Note(p, s, wantCombat: true);
|
||||
Check.Eq(NoticeCount(), 1, "the first skipped fight: said in chat");
|
||||
Check.Eq(RynthAiPlugin.BoostNavNotice,
|
||||
"[RynthAi] Boost Nav Priority is on: RynthAi only navigates (no hunting, no looting). Turn it off to hunt and loot.",
|
||||
"the owner's wording");
|
||||
Check.True(Logged(RynthAiPlugin.BoostNavNotice + " (skipped a fight)"), "and in the log, with what was skipped");
|
||||
Check.Eq(FakeHost.ChatTypes[FakeHost.Chat.IndexOf(RynthAiPlugin.BoostNavNotice)], 2, "in the warning colour");
|
||||
|
||||
for (int i = 0; i < 50; i++) Note(p, s, wantCombat: true);
|
||||
s.BoostNavPriority = false; Note(p, s, true);
|
||||
s.BoostNavPriority = true; Note(p, s, true);
|
||||
Check.Eq(NoticeCount(), 1, "once per session: not again, not even after the flag goes off and on");
|
||||
|
||||
var next = Plugin(); // a new session (a login or a reload starts a new plugin instance)
|
||||
Note(next, s, wantCombat: true);
|
||||
Check.Eq(NoticeCount(), 2, "a new session says it again, once");
|
||||
}
|
||||
}
|
||||
|
|
@ -39,7 +39,9 @@ internal static class ChestLootTests
|
|||
r.Add("chest loot: your own side pack opened -> nothing taken", OwnSidePackNotLooted);
|
||||
r.Add("chest loot: house storage (HouseOwner set) -> nothing taken", HouseStorageNotLooted);
|
||||
r.Add("chest loot: house storage by name (engine without the HouseOwner read) -> nothing taken", HouseStorageByNameNotLooted);
|
||||
r.Add("chest loot: Looting off -> nothing taken, the loot check still runs", LootingOffNothing);
|
||||
r.Add("chest loot: Looting off and Pickup with macro off off -> nothing taken, the loot check still runs", LootingOffNothing);
|
||||
r.Add("chest loot: Pickup with macro off (on by default) loots an opened chest with the macro off or Looting off", PickupWithMacroOff);
|
||||
r.Add("chest loot: Pickup with macro off never takes from house storage or your own side pack", PickupWithMacroOffRefuses);
|
||||
r.Add("chest loot: reopening the chest loots it again (never marked done)", ReopenLootsAgain);
|
||||
r.Add("chest loot: a salvage-only item is left when no UST is carried, as on corpses", SalvageWithoutUstLeft);
|
||||
r.Add("chest loot: opened mid-fight it waits for combat, then is looted if still open", ChestWaitsForCombat);
|
||||
|
|
@ -317,6 +319,7 @@ internal static class ChestLootTests
|
|||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.S.EnableLooting = false;
|
||||
bot.S.LootChestsMacroOff = false;
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
|
||||
bot.ServerOpens(Chest);
|
||||
|
|
@ -329,6 +332,54 @@ internal static class ChestLootTests
|
|||
"the old loot check of a natively opened container still runs (chat: " + string.Join(" | ", FakeHost.Chat) + ")");
|
||||
}
|
||||
|
||||
// Owner, 2026-11-02: "even with looting and the macro off, it should pick up items from a chest when
|
||||
// it's open that match the loaded loot profile ... (Pickup with macro off)", on by default.
|
||||
private static void PickupWithMacroOff()
|
||||
{
|
||||
Check.True(new LegacyUiSettings().LootChestsMacroOff, "on by default");
|
||||
foreach (bool macroOff in new[] { true, false })
|
||||
{
|
||||
BaseWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
if (macroOff) bot.S.IsMacroRunning = false; else bot.S.EnableLooting = false;
|
||||
string what = macroOff ? "macro off" : "Looting off";
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickUntil(() => bot.Moved(Gem));
|
||||
Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), $"{what}: the gem is picked up (moves: {Moves()})");
|
||||
Check.False(bot.Moved(Spoon), $"{what}: the spoon matches nothing and stays");
|
||||
Check.False(FakeHost.Uses.Contains(Chest), $"{what}: no open sent");
|
||||
Check.False(FakeHost.AutoRunCalls.Any(on => on), $"{what}: no walk");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Pickup with macro off: looting the opened chest")), $"{what}: logged");
|
||||
}
|
||||
}
|
||||
|
||||
private static void PickupWithMacroOffRefuses()
|
||||
{
|
||||
BaseWorld();
|
||||
FakeHost.InstanceIds[(Chest, 32)] = 0x50000ABC; // house storage
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.S.IsMacroRunning = false;
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickFor(300);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken out of house storage");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Pickup with macro off: not looting") && l.Contains("house storage")), "the reason is logged");
|
||||
|
||||
BaseWorld();
|
||||
FakeHost.Containers[Chest] = Player; // a side pack the character carries
|
||||
host = FakeHost.Create(Player);
|
||||
bot = new Bot(host);
|
||||
bot.S.IsMacroRunning = false;
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickFor(300);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken out of your own side pack");
|
||||
}
|
||||
|
||||
private static void ReopenLootsAgain()
|
||||
{
|
||||
BaseWorld();
|
||||
|
|
|
|||
605
Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs
Normal file
605
Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs
Normal file
|
|
@ -0,0 +1,605 @@
|
|||
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;
|
||||
using V3 = RynthCore.Plugin.RynthAi.Raycasting.Vector3;
|
||||
using Vec = RynthCore.Plugin.RynthAi.OutdoorHunt.Vec;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The outdoor hunt into buildings (2026-10-25, Tom: "the entire radar range, also going inside houses").
|
||||
// RynthNav's map ends at a building's walls: a walk into one is RynthNav's way to the outside of a door,
|
||||
// then the building's rooms (BuildingMap, cell.dat); from inside, out through a door first.
|
||||
// - pure (OutdoorHunt with a fake building map and a straight-line RynthNav): which monster, which
|
||||
// door, the corners, the log line, the fallbacks;
|
||||
// - BuildingMap on a hand-built house (doors, windows, a shared opening, portals inside);
|
||||
// - BuildingMap on the real dats when they are on this PC (Holtburg A9B4 / A9B3, DF61).
|
||||
internal static class HuntBuildingTests
|
||||
{
|
||||
private const string AcDir = @"C:\Turbine\Asheron's Call";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("hunt buildings: a monster inside is picked when its walk is the shortest; the walk goes to the door, through it, then the rooms", IntoBuilding);
|
||||
r.Add("hunt buildings: of a building's two doors, the one giving the shorter walk (the other's way round never asked for)", NearerDoor);
|
||||
r.Add("hunt buildings: from inside, a monster outdoors is walked to out through the nearer door, then on RynthNav's map", OutOfBuilding);
|
||||
r.Add("hunt buildings: inside a building with no door known (or none known at all): back out the way in", NoDoorFallsBack);
|
||||
r.Add("hunt buildings: one in the same building through its rooms; one in another building out of one door and in by another", SameAndOtherBuilding);
|
||||
r.Add("hunt buildings: a door whose step out isn't on the ground is never used; a building it doesn't know is left alone", DoorOffTheGround);
|
||||
r.Add("building map: a hand-built house: its door faces out, a window and a slit are no doors, a shared opening joins two buildings", HandBuiltHouse);
|
||||
r.Add("building map: a portal inside: walks bend round it, one to a monster in its circle stops at its edge, a door it stands at isn't offered", PortalInside);
|
||||
r.Add("building map (real dats): Holtburg A9B4/A9B3: doors found, each step out off every floor and each step in on one, a walk from a door to every room", RealHoltburg);
|
||||
r.Add("building map (real dats): DF61 (a test hunt's): openings shared by two cell groups joined, doors onto the wall tops left out, walks through", RealDf61);
|
||||
r.Add("hunt buildings (real dats): into Holtburg's A9B4#0 from outdoors and back out, a portal in its rooms kept out of", RealHuntHoltburg);
|
||||
}
|
||||
|
||||
// ── Fakes ────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly DateTime T0 = new(2026, 10, 25, 12, 0, 0);
|
||||
private static Vec V(double x, double y, double z = 0) => new(x, y, z);
|
||||
private static Vec D(double x, double y, double z = 0) => new(x, y, z, true);
|
||||
|
||||
private const uint Outdoors = 0xA9B4003Au;
|
||||
private static OutdoorHunt.Candidate C(int id, Vec at, Vec me, uint cell = Outdoors, string? name = null)
|
||||
=> new(id, name ?? $"Monster {id}", at, at.DistanceTo(me), 1, cell);
|
||||
|
||||
/// <summary>A west-facing door at (x, y) of cell: inner point 1.5 east, outer 1.5 west.</summary>
|
||||
private static OutdoorHunt.Door West(uint cell, double x, double y) => new(cell, D(x + 1.5, y), D(x, y), D(x - 1.5, y));
|
||||
private static OutdoorHunt.Door East(uint cell, double x, double y) => new(cell, D(x - 1.5, y), D(x, y), D(x + 1.5, y));
|
||||
|
||||
/// <summary>Buildings as cells to building ids and doors; inside, a straight walk (NoPath between buildings or cells kept apart).</summary>
|
||||
private sealed class FakeBuildings : OutdoorHunt.IBuildings
|
||||
{
|
||||
public readonly Dictionary<uint, int> Of = new();
|
||||
public readonly Dictionary<int, List<OutdoorHunt.Door>> DoorsOf = new();
|
||||
public readonly HashSet<(uint, uint)> Apart = new();
|
||||
public int InsideCalls;
|
||||
public int BuildingOf(uint cell) => Of.TryGetValue(cell, out int b) ? b : 0;
|
||||
public IReadOnlyList<OutdoorHunt.Door> Doors(int b) => DoorsOf.TryGetValue(b, out var l) ? l : new List<OutdoorHunt.Door>();
|
||||
public OutdoorHunt.PathResult Inside(uint fc, Vec f, uint tc, Vec t)
|
||||
{
|
||||
InsideCalls++;
|
||||
int b = BuildingOf(fc);
|
||||
if (b == 0 || b != BuildingOf(tc) || Apart.Contains((fc, tc)) || Apart.Contains((tc, fc)))
|
||||
return new(OutdoorHunt.PathStatus.NoPath, Array.Empty<Vec>(), 0, 0);
|
||||
return new(OutdoorHunt.PathStatus.Ok, new[] { t }, f.DistanceTo(t), 0);
|
||||
}
|
||||
public string Name(int b) => $"house {b}";
|
||||
}
|
||||
|
||||
/// <summary>RynthNav: a straight walk, with per-goal overrides; every goal asked for is noted.</summary>
|
||||
private sealed class Nav
|
||||
{
|
||||
public readonly Dictionary<(double, double), OutdoorHunt.PathResult> Overrides = new();
|
||||
/// <summary>The map's ground at a doorstep (a path from a spot to itself): its height there.</summary>
|
||||
public readonly Dictionary<(double, double), double> Ground = new();
|
||||
public readonly List<(Vec A, Vec B)> Asked = new();
|
||||
public OutdoorHunt.PathResult Path(Vec a, Vec b)
|
||||
{
|
||||
Asked.Add((a, b));
|
||||
if (a.X == b.X && a.Y == b.Y && Ground.TryGetValue((b.X, b.Y), out double gz))
|
||||
return new(OutdoorHunt.PathStatus.Ok, new[] { V(b.X, b.Y, gz) }, Math.Abs(gz - b.Z), Math.Abs(gz - b.Z));
|
||||
if (Overrides.TryGetValue((b.X, b.Y), out var o)) return o;
|
||||
return new(OutdoorHunt.PathStatus.Ok, new[] { b with { Door = false } }, a.DistanceTo(b), 0);
|
||||
}
|
||||
public void Around(Vec to, double length) =>
|
||||
Overrides[(to.X, to.Y)] = new(OutdoorHunt.PathStatus.Ok, new[] { V(to.X - 5, to.Y + 8), to with { Door = false } }, length, 0);
|
||||
public int Walks => Asked.Count(q => q.A != q.B);
|
||||
}
|
||||
|
||||
private static List<OutdoorHunt.Candidate> Sorted(params OutdoorHunt.Candidate[] c) => c.OrderBy(x => x.Distance).ToList();
|
||||
private static int Idx(IReadOnlyList<Vec> c, Vec v)
|
||||
{
|
||||
for (int i = 0; i < c.Count; i++) if (c[i] == v) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string Pts(IReadOnlyList<Vec>? c) => c == null ? "(none)" : string.Join(" ", c.Select(v => $"{v.X:0.#},{v.Y:0.#}{(v.Door ? "D" : "")}"));
|
||||
|
||||
// A house: cells 0101 (west room) and 0102 (east room), x 1020..1030, y 995..1005; doors given per test.
|
||||
private const uint RoomW = 0xA9B40101, RoomE = 0xA9B40102, House2 = 0xA9B40110;
|
||||
|
||||
private static FakeBuildings House(params OutdoorHunt.Door[] doors)
|
||||
{
|
||||
var b = new FakeBuildings();
|
||||
b.Of[RoomW] = 1; b.Of[RoomE] = 1;
|
||||
b.DoorsOf[1] = doors.ToList();
|
||||
return b;
|
||||
}
|
||||
|
||||
// ── Pure ─────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void IntoBuilding()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
var house = House(West(RoomW, 1020, 1000));
|
||||
var inside = V(1025, 1000);
|
||||
var list = Sorted(C(1, inside, me, RoomW), C(2, V(1000, 1040), me));
|
||||
var d = h.Tick(T0, me, Outdoors, true, list, nav.Path, house);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 1, $"walks to the one inside (25 yd walk) before the one 40 yd away in the open: {d.Act} {d.TargetId}");
|
||||
var want = new[] { D(1018.5, 1000), D(1020, 1000), D(1021.5, 1000), inside };
|
||||
Check.True(d.Corners != null && d.Corners.SequenceEqual(want), "to the door's step out, through it, a step in, then the rooms to it: " + Pts(d.Corners));
|
||||
Check.True(h.Note.StartsWith("next: 'Monster 1', inside house 1") && h.Note.Contains($"cell {RoomW:X8}")
|
||||
&& h.Note.Contains("a 25 yd walk through the door at 1020,1000"), "logged: " + h.Note);
|
||||
|
||||
// The same building behind a long way round (RynthNav: 150 yd to the door): too far round (over 2x Hunt Range 60).
|
||||
var far = new OutdoorHunt { RangeYd = 60 };
|
||||
far.Start(T0, me);
|
||||
var nav2 = new Nav();
|
||||
nav2.Around(V(1018.5, 1000), 150);
|
||||
d = far.Tick(T0, me, Outdoors, true, Sorted(C(1, inside, me, RoomW), C(2, V(1000, 1040), me)), nav2.Path, house);
|
||||
Check.True(d.TargetId == 2 && far.IsSkipped(1, T0.AddSeconds(5)), $"a 150 yd walk into it is too far round: the other one ({d.TargetId})");
|
||||
}
|
||||
|
||||
private static void NearerDoor()
|
||||
{
|
||||
// East of the house; the west door is round the far side (RynthNav: 45 yd), the east door is 13.5 yd away.
|
||||
var me = V(1045, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
var west = West(RoomW, 1020, 1000);
|
||||
var east = East(RoomE, 1030, 1000);
|
||||
nav.Around(west.Outside, 45);
|
||||
var house = House(west, east);
|
||||
var d = h.Tick(T0, me, Outdoors, true, Sorted(C(1, V(1027, 1000), me, RoomE)), nav.Path, house);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners!.Contains(east.At) && !d.Corners!.Contains(west.At), "through the east door: " + Pts(d.Corners));
|
||||
Check.True(h.Note.Contains("through the door at 1030,1000"), "logged with that door: " + h.Note);
|
||||
Check.False(nav.Asked.Any(q => q.A != q.B && q.B.X == west.Outside.X && q.B.Y == west.Outside.Y),
|
||||
"the west door's way round is never asked for (it can't beat the east door even in a straight line)");
|
||||
Check.Eq(nav.Walks, 1, "one RynthNav walk for the pick (and a look at each doorstep)");
|
||||
}
|
||||
|
||||
private static void OutOfBuilding()
|
||||
{
|
||||
var me = V(1022, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, V(990, 1000));
|
||||
var nav = new Nav();
|
||||
var west = West(RoomW, 1020, 1000);
|
||||
var east = East(RoomE, 1030, 1000);
|
||||
var house = House(west, east);
|
||||
var target = V(990, 1000);
|
||||
var d = h.Tick(T0, me, RoomW, true, Sorted(C(1, target, me)), nav.Path, house);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 1, $"walks to it from inside: {d.Act}");
|
||||
var want = new[] { D(1021.5, 1000), D(1020, 1000), D(1018.5, 1000), target };
|
||||
Check.True(d.Corners != null && d.Corners.SequenceEqual(want), "a step in front of the west door, through it, its step out, then RynthNav's way: " + Pts(d.Corners));
|
||||
Check.True(nav.Asked.Any(q => q.A == west.Outside && q.B == target), "RynthNav asked from the west door's step out");
|
||||
Check.True(h.Note.Contains("out of house 1 through the door at 1020,1000") && !h.WalkingOut, "logged, not the way-back-out walk: " + h.Note);
|
||||
|
||||
// A monster east: out through the east door (the nearer one for that walk).
|
||||
var h2 = new OutdoorHunt();
|
||||
h2.Start(T0, me);
|
||||
d = h2.Tick(T0, me, RoomW, true, Sorted(C(2, V(1060, 1000), me)), new Nav().Path, house);
|
||||
Check.True(d.Corners != null && d.Corners.Contains(east.At) && !d.Corners.Contains(west.At), "east one: out of the east door: " + Pts(d.Corners));
|
||||
}
|
||||
|
||||
private static void NoDoorFallsBack()
|
||||
{
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, V(990, 1000));
|
||||
h.Track(V(1018, 1000), indoors: false); // the last spot outdoors, at the door
|
||||
h.Track(V(1020, 1000), indoors: true);
|
||||
h.Track(V(1022, 1000), indoors: true);
|
||||
var noDoors = House(); // known rooms, no door
|
||||
var nav = new Nav();
|
||||
var d = h.Tick(T0, V(1022, 1000), RoomW, true, Sorted(C(1, V(990, 1000), V(1022, 1000))), nav.Path, noDoors);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && h.WalkingOut && h.Note.Contains("back out the way in"), $"no door known: back out the way in ({d.Act}, {h.Note})");
|
||||
Check.True(d.Corners != null && d.Corners.Contains(V(1018, 1000)), "along the way in: " + Pts(d.Corners));
|
||||
Check.Eq(nav.Asked.Count, 0, "no RynthNav walk from inside");
|
||||
|
||||
var h2 = new OutdoorHunt();
|
||||
h2.Start(T0, V(990, 1000));
|
||||
h2.Track(V(1018, 1000), indoors: false);
|
||||
h2.Track(V(1021, 1000), indoors: true);
|
||||
d = h2.Tick(T0, V(1021, 1000), RoomW, true, Sorted(C(1, V(990, 1000), V(1021, 1000))), nav.Path, null);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && h2.WalkingOut, "no building map at all: the same");
|
||||
}
|
||||
|
||||
private static void SameAndOtherBuilding()
|
||||
{
|
||||
var me = V(1022, 1000);
|
||||
var west = West(RoomW, 1020, 1000);
|
||||
var house = House(west, East(RoomE, 1030, 1000));
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var d = h.Tick(T0, me, RoomW, true, Sorted(C(1, V(1028, 1002), me, RoomE)), new Nav().Path, house);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners!.SequenceEqual(new[] { V(1028, 1002) }), "same building: through its rooms only: " + Pts(d.Corners));
|
||||
Check.True(h.Note.Contains("through its rooms"), "logged: " + h.Note);
|
||||
|
||||
// Another house north, its door on its south wall at (1025, 1030), step out (1025, 1028.5).
|
||||
house.Of[House2] = 2;
|
||||
var south = new OutdoorHunt.Door(House2, D(1025, 1031.5), D(1025, 1030), D(1025, 1028.5));
|
||||
house.DoorsOf[2] = new List<OutdoorHunt.Door> { south };
|
||||
var h2 = new OutdoorHunt();
|
||||
h2.Start(T0, me);
|
||||
var goal = V(1025, 1035);
|
||||
d = h2.Tick(T0, me, RoomW, true, Sorted(C(2, goal, me, House2)), new Nav().Path, house);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners![^1] == goal && d.Corners.Contains(south.At)
|
||||
&& Idx(d.Corners, south.Outside) > Idx(d.Corners, west.Outside), "out of this house, across, in by the other's door: " + Pts(d.Corners));
|
||||
Check.True(h2.Note.Contains("inside house 2") && h2.Note.Contains("out of house 1") && h2.Note.Contains("in through the door at 1025,1030"), "logged: " + h2.Note);
|
||||
|
||||
// Two parts of one building that only the outside joins: out by one door and in by another.
|
||||
house.Apart.Add((RoomW, RoomE));
|
||||
var h3 = new OutdoorHunt();
|
||||
h3.Start(T0, me);
|
||||
d = h3.Tick(T0, me, RoomW, true, Sorted(C(3, V(1028, 1000), me, RoomE)), new Nav().Path, house);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners!.Contains(west.At) && d.Corners.Contains(D(1030, 1000)), "rooms not joined inside: out of the west door, in at the east: " + Pts(d.Corners));
|
||||
}
|
||||
|
||||
private static void DoorOffTheGround()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var balcony = new OutdoorHunt.Door(RoomW, D(1021.5, 1000, 4), D(1020, 1000, 4), D(1018.5, 1000, 4));
|
||||
var nav = new Nav();
|
||||
nav.Ground[(1018.5, 1000)] = 0; // the ground under the balcony's step out is 4 below it
|
||||
var house = House(balcony);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
h.ClearNotes();
|
||||
var d = h.Tick(T0, me, Outdoors, true, Sorted(C(1, V(1025, 1000, 4), me, RoomW), C(2, V(1000, 1040), me)), nav.Path, house);
|
||||
Check.True(d.TargetId == 2 && h.IsSkipped(1, T0.AddSeconds(5)), $"the only door is a balcony's: the one inside is left out ({d.TargetId})");
|
||||
Check.True(h.PendingNotes.Any(n => n.Contains("Monster 1") && n.Contains("no door of house 1 leads to it")), "and says why: " + string.Join(" | ", h.PendingNotes));
|
||||
|
||||
// With a door on the ground too: that one.
|
||||
var ground = East(RoomE, 1030, 1000);
|
||||
var house2 = House(balcony, ground);
|
||||
var h2 = new OutdoorHunt();
|
||||
h2.Start(T0, me);
|
||||
d = h2.Tick(T0, me, Outdoors, true, Sorted(C(1, V(1025, 1000, 4), me, RoomW)), nav.Path, house2);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners!.Contains(ground.At) && !d.Corners.Contains(balcony.At), "the ground door, round the far side: " + Pts(d.Corners));
|
||||
|
||||
// A monster in a building the map doesn't know: left alone (no walk, not left out, no log line).
|
||||
var h3 = new OutdoorHunt();
|
||||
h3.Start(T0, me);
|
||||
h3.ClearNotes();
|
||||
d = h3.Tick(T0, me, Outdoors, true, Sorted(C(1, V(1010, 1000), me, 0xA9B40150), C(2, V(1000, 1030), me)), new Nav().Path, house);
|
||||
Check.True(d.TargetId == 2 && !h3.IsSkipped(1, T0), $"an unknown building's monster is passed over ({d.TargetId})");
|
||||
Check.False(h3.PendingNotes.Any(n => n.Contains("Monster 1")), "without a word: " + string.Join(" | ", h3.PendingNotes));
|
||||
}
|
||||
|
||||
// ── A hand-built house ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
private const uint Lb = 0xA9B4;
|
||||
private const uint CellA = 0xA9B40100, CellB = 0xA9B40101, CellC = 0xA9B40102, CellD = 0xA9B40103;
|
||||
|
||||
private static V3[] Rect(double x0, double y0, double x1, double y1, double z = 0) => 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),
|
||||
};
|
||||
|
||||
/// <summary>An upright quad from (x0, y0) to (x1, y1), z0 to z1: a wall's opening.</summary>
|
||||
private static V3[] Upright(double x0, double y0, double x1, double y1, double z0 = 0, double z1 = 3) => new[]
|
||||
{
|
||||
new V3((float)x0, (float)y0, (float)z0), new V3((float)x1, (float)y1, (float)z0),
|
||||
new V3((float)x1, (float)y1, (float)z1), new V3((float)x0, (float)y0, (float)z1),
|
||||
};
|
||||
|
||||
private static DungeonNavNode Node(uint id, double cx, double cy) =>
|
||||
new() { CellId = id, EW = DungeonGeometry.WorldToNav(cx), NS = DungeonGeometry.WorldToNav(cy), Z = 0 };
|
||||
|
||||
/// <summary>
|
||||
/// House 1: A (100..110 x 100..110) and B (110..130 x 100..120), joined by a 4 m opening at x 110,
|
||||
/// y 103..107; a door in A's west wall (x 100, y 103..106), a window in A's north wall (foot 1 m
|
||||
/// up), a 0.5 m slit in B's east wall. House 2: C (200..210) and D (210..220), no portal record
|
||||
/// between them but one opening at x 210 that each sees as its way out; a door in C's west wall.
|
||||
/// </summary>
|
||||
private static BuildingMap.Block HouseBlock()
|
||||
{
|
||||
var graph = new Dictionary<uint, DungeonNavNode>
|
||||
{
|
||||
[CellA] = Node(CellA, 105, 105), [CellB] = Node(CellB, 120, 110),
|
||||
[CellC] = Node(CellC, 205, 105), [CellD] = Node(CellD, 215, 105),
|
||||
};
|
||||
graph[CellA].Neighbors.Add(CellB); graph[CellB].Neighbors.Add(CellA);
|
||||
var ab = Upright(110, 103, 110, 107);
|
||||
var portals = new List<(uint, V3[])> { (CellA, ab), (CellB, ab.Reverse().ToArray()) };
|
||||
var floors = new List<(uint, V3[])>
|
||||
{
|
||||
(CellA, Rect(100, 100, 110, 110)), (CellB, Rect(110, 100, 130, 120)),
|
||||
(CellC, Rect(200, 100, 210, 110)), (CellD, Rect(210, 100, 220, 110)),
|
||||
};
|
||||
var walls = new List<(uint, V3[])>();
|
||||
var door = Upright(100, 103, 100, 106);
|
||||
var window = Upright(103, 110, 105, 110, 1.0, 2.8);
|
||||
var slit = Upright(130, 110, 130, 110.5);
|
||||
var shared = Upright(210, 103, 210, 107);
|
||||
var doorC = Upright(200, 103, 200, 106);
|
||||
var exits = new List<(uint, V3[])>
|
||||
{
|
||||
(CellA, door), (CellA, window), (CellB, slit),
|
||||
(CellC, shared), (CellD, shared.Reverse().ToArray()), (CellC, doorC),
|
||||
};
|
||||
foreach (var e in exits) portals.Add(e);
|
||||
return BuildingMap.Build(Lb, graph, portals, floors, walls, exits);
|
||||
}
|
||||
|
||||
private static void HandBuiltHouse()
|
||||
{
|
||||
var blk = HouseBlock();
|
||||
Check.Eq(blk.Buildings.Count, 2, "two buildings (C and D joined by the opening they share)");
|
||||
Check.Eq(blk.SharedOpenings, 1, "one shared opening joined");
|
||||
var h1 = blk.ByCell[CellA];
|
||||
Check.True(blk.ByCell[CellB] == h1 && blk.ByCell[CellC] == blk.ByCell[CellD] && blk.ByCell[CellC] != h1, "A+B and C+D");
|
||||
Check.Eq(h1.Doors.Count, 1, "house 1: one door");
|
||||
var d = h1.Doors[0];
|
||||
Check.True(d.Cell == CellA && Math.Abs(d.At.X - 100) < 0.01 && Math.Abs(d.At.Y - 104.5) < 0.01, $"in A's west wall: {d.At}");
|
||||
Check.True(d.Outside.X < 100 && Math.Abs(d.Outside.X - (100 - BuildingMap.OutsideMeters)) < 0.01, $"its step out is west, outside: {d.Outside}");
|
||||
Check.True(d.Inner.X > 100 && blk.Geo!.OnCellFloor(CellA, d.Inner.X, d.Inner.Y, 0), $"its step in is on A's floor: {d.Inner}");
|
||||
Check.True(d.Inner.Door && d.At.Door && d.Outside.Door, "all three lined up on the door (Door)");
|
||||
Check.True(h1.NotDoors.Any(n => n.Contains("window")) && h1.NotDoors.Any(n => n.Contains("0.5 m wide")), "the window and the slit aren't doors: " + string.Join(" | ", h1.NotDoors));
|
||||
var h2 = blk.ByCell[CellC];
|
||||
Check.True(h2.Doors.Count == 1 && Math.Abs(h2.Doors[0].At.X - 200) < 0.01, $"house 2: only its west door (the shared opening is inside it now): {h2.Doors.Count}");
|
||||
Check.True(blk.Geo!.TryGetDoorway(CellC, CellD, out _), "and the shared opening is a doorway between C and D");
|
||||
|
||||
var map = new BuildingMap(null, null);
|
||||
map.Add(blk);
|
||||
Check.True(map.BuildingOf(CellA) != 0 && map.BuildingOf(CellA) == map.BuildingOf(CellB) && map.BuildingOf(0xA9B4003A) == 0, "BuildingOf: a cell's house; outdoors 0");
|
||||
Check.Eq(map.Name(map.BuildingOf(CellA)), "building A9B4#0", "named by landblock and index");
|
||||
var goal = V(125, 115);
|
||||
var p = map.Inside(CellA, d.Inner, CellB, goal);
|
||||
Check.True(p.Status == OutdoorHunt.PathStatus.Ok && p.Corners[^1] == goal, $"a walk from the door into B: {p.Status}");
|
||||
var way = new List<Vec> { d.Inner };
|
||||
way.AddRange(p.Corners);
|
||||
bool throughOpening = false;
|
||||
for (int i = 0; i + 1 < way.Count; i++)
|
||||
{
|
||||
var a = way[i]; var b = way[i + 1];
|
||||
if ((a.X - 110) * (b.X - 110) > 0) continue; // this leg doesn't cross x 110
|
||||
double t = (110 - a.X) / (b.X - a.X), y = a.Y + (b.Y - a.Y) * t;
|
||||
if (y >= 103 && y <= 107) throughOpening = true;
|
||||
}
|
||||
Check.True(throughOpening, "through the opening between A and B: " + Pts(way));
|
||||
var p2 = map.Inside(CellC, h2.Doors[0].Inner, CellD, V(217, 105));
|
||||
Check.True(p2.Status == OutdoorHunt.PathStatus.Ok, $"house 2: C to D through the shared opening ({p2.Status})");
|
||||
Check.Eq(map.Inside(CellA, d.Inner, CellC, V(205, 105)).Status, OutdoorHunt.PathStatus.NoPath, "no walk inside from one house to the other");
|
||||
}
|
||||
|
||||
private static void PortalInside()
|
||||
{
|
||||
var blk = HouseBlock();
|
||||
var map = new BuildingMap(null, null);
|
||||
map.Add(blk);
|
||||
var door = blk.ByCell[CellA].Doors[0];
|
||||
int house = map.BuildingOf(CellA);
|
||||
var portal = new BuildingMap.PortalSpot(0x7A9B4001, 118, 105, 0);
|
||||
map.Portals = new[] { portal };
|
||||
|
||||
var goal = V(126, 105);
|
||||
var p = map.Inside(CellA, door.Inner, CellB, goal);
|
||||
var way = new List<Vec> { door.Inner };
|
||||
way.AddRange(p.Corners);
|
||||
double nearest = double.MaxValue;
|
||||
for (int i = 0; i + 1 < way.Count; i++) nearest = Math.Min(nearest, SegDist(way[i], way[i + 1], portal.X, portal.Y));
|
||||
Check.True(p.Status == OutdoorHunt.PathStatus.Ok && p.Corners[^1] == goal, $"walks on past it ({p.Status})");
|
||||
Check.True(nearest >= portal.R - 0.01, $"never inside its {portal.R} m circle (nearest {nearest:F2} m): {Pts(way)}");
|
||||
|
||||
var inCircle = V(120, 106);
|
||||
p = map.Inside(CellA, door.Inner, CellB, inCircle);
|
||||
Check.True(p.Status == OutdoorHunt.PathStatus.Partial && p.Gap > 0, $"a monster in its circle: the walk ends short ({p.Status}, gap {p.Gap:F1})");
|
||||
Check.True(p.Corners.Count > 0 && Math.Sqrt(Math.Pow(p.Corners[^1].X - portal.X, 2) + Math.Pow(p.Corners[^1].Y - portal.Y, 2)) >= portal.R - 0.01,
|
||||
$"at its edge, not in it: {Pts(p.Corners)}");
|
||||
|
||||
Check.Eq(map.Doors(house).Count, 1, "a portal across the room: the door is still offered");
|
||||
map.Portals = new[] { new BuildingMap.PortalSpot(0x7A9B4002, 101, 104.5, 0) };
|
||||
Check.Eq(map.Doors(house).Count, 0, "a portal at the door: the door isn't offered");
|
||||
map.Portals = new[] { new BuildingMap.PortalSpot(0x7A9B4003, 97, 104.5, 0) };
|
||||
Check.Eq(map.Doors(house).Count, 0, "one outdoors by its step out: nor then (RynthNav's way to the step could end in its circle)");
|
||||
map.Portals = new[] { new BuildingMap.PortalSpot(0x7A9B4004, 90, 104.5, 0) };
|
||||
Check.Eq(map.Doors(house).Count, 1, "one farther off outdoors: it is (RynthNav's way keeps out of that one)");
|
||||
|
||||
// A corridor 2 m wide with a portal in it: no way round.
|
||||
var corridor = new List<Vec> { V(0, 0), V(20, 0) };
|
||||
var status = BuildingMap.KeepOutOfPortals(corridor, new[] { new BuildingMap.PortalSpot(1, 10, 0, 0) }, v => Math.Abs(v.Y) <= 1, null, out _);
|
||||
Check.Eq(status, OutdoorHunt.PathStatus.NoPath, "a portal across a narrow corridor: no way past it");
|
||||
// Standing in the ring round a portal (combat took it there): the walk past it steps away round it first.
|
||||
var ring = new[] { new BuildingMap.PortalSpot(1, 10, 0, 0) };
|
||||
var past = new List<Vec> { V(12, 0), V(0, 0) };
|
||||
Check.Eq(BuildingMap.KeepOutOfPortals(past, ring, null, null, out _), OutdoorHunt.PathStatus.Ok, "from inside its ring, a walk past it: " + Pts(past));
|
||||
Check.True(past.Count > 2 && (past[1].X - 10) * (past[1].X - 12) > 0 && Math.Abs(past[1].Y) > 3, "its first step leads away from it: " + Pts(past));
|
||||
for (int i = 1; i + 1 < past.Count; i++)
|
||||
Check.True(SegDist(past[i], past[i + 1], 10, 0) >= 3.5 - 0.01, $"then keeps out of the circle (leg {i})");
|
||||
// A corner of the way in the circle (a doorway beside it): left out, the legs bent round instead.
|
||||
var beside = new List<Vec> { V(0, 0), V(10, 1), V(20, 0) };
|
||||
Check.Eq(BuildingMap.KeepOutOfPortals(beside, ring, null, null, out _), OutdoorHunt.PathStatus.Ok, "a corner in the circle: still a way");
|
||||
Check.True(!beside.Any(v => BuildingMap.InPortal(ring[0], v)) && Enumerable.Range(0, beside.Count - 1).All(i => SegDist(beside[i], beside[i + 1], 10, 0) >= 3.5 - 0.01),
|
||||
"no corner or leg in it: " + Pts(beside));
|
||||
var other = new List<Vec> { V(0, 0), V(20, 0) };
|
||||
Check.Eq(BuildingMap.KeepOutOfPortals(other, new[] { new BuildingMap.PortalSpot(1, 10, 0, 8) }, v => Math.Abs(v.Y) <= 1, null, out _),
|
||||
OutdoorHunt.PathStatus.Ok, "one on the floor above (8 m up) doesn't count");
|
||||
}
|
||||
|
||||
/// <summary>On one of the cells' floors, or within 0.25 m of it (an opening's centre is on the seam between two floors).</summary>
|
||||
private static bool NearFloor(DungeonGeometry geo, IReadOnlyCollection<uint> cells, Vec v)
|
||||
{
|
||||
for (double dx = -0.25; dx <= 0.25; dx += 0.25)
|
||||
for (double dy = -0.25; dy <= 0.25; dy += 0.25)
|
||||
if (geo.OnFloorOfAny(cells, v.X + dx, v.Y + dy, v.Z + 0.1)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static double SegDist(Vec a, Vec b, double px, double py)
|
||||
{
|
||||
double dx = b.X - a.X, dy = b.Y - a.Y, l2 = dx * dx + dy * dy;
|
||||
double t = l2 < 1e-12 ? 0 : Math.Clamp(((px - a.X) * dx + (py - a.Y) * dy) / l2, 0, 1);
|
||||
return Math.Sqrt(Math.Pow(a.X + dx * t - px, 2) + Math.Pow(a.Y + dy * t - py, 2));
|
||||
}
|
||||
|
||||
// ── The real dats ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private static GeometryLoader? _geo;
|
||||
private static bool _geoTried;
|
||||
private static GeometryLoader? Dats()
|
||||
{
|
||||
if (_geoTried) return _geo;
|
||||
_geoTried = true;
|
||||
if (!Directory.Exists(AcDir)) return null;
|
||||
var g = new GeometryLoader();
|
||||
if (!g.Initialize(AcDir) || g.CellDat == null || g.DungeonLOS == null) return null;
|
||||
return _geo = g;
|
||||
}
|
||||
|
||||
/// <summary>A spot on the cell's floor: the middle of its biggest upward floor polygon (in doubles).</summary>
|
||||
private static bool FloorSpot(GeometryLoader g, BuildingMap.Block blk, uint cell, out Vec spot)
|
||||
{
|
||||
spot = default;
|
||||
double bestArea = 0;
|
||||
foreach (var p in g.DungeonLOS.GetDungeonMapFloorPolygons(blk.Landblock))
|
||||
{
|
||||
if (p.CellId != cell || p.Vertices == null || p.Vertices.Length < 3 || !DungeonGeometry.IsUpwardFloor(p.Vertices)) continue;
|
||||
double ox = p.Vertices[0].X, oy = p.Vertices[0].Y, area = 0, sx = 0, sy = 0, sz = 0;
|
||||
for (int i = 0; i < p.Vertices.Length; i++)
|
||||
{
|
||||
var a = p.Vertices[i]; var b = p.Vertices[(i + 1) % p.Vertices.Length];
|
||||
area += ((double)a.X - ox) * ((double)b.Y - oy) - ((double)b.X - ox) * ((double)a.Y - oy);
|
||||
sx += a.X; sy += a.Y; sz += a.Z;
|
||||
}
|
||||
area = Math.Abs(area) / 2;
|
||||
if (area <= bestArea) continue;
|
||||
int n = p.Vertices.Length;
|
||||
var c = new Vec(sx / n, sy / n, sz / n);
|
||||
if (!blk.Geo!.OnCellFloor(cell, c.X, c.Y, c.Z + 0.1)) continue;
|
||||
bestArea = area;
|
||||
spot = c;
|
||||
}
|
||||
return bestArea > 0.5;
|
||||
}
|
||||
|
||||
private static void CheckDoorsAndWalks(GeometryLoader g, BuildingMap.Block blk, string label, out int doors, out int rooms, out int walks)
|
||||
{
|
||||
doors = rooms = walks = 0;
|
||||
var map = new BuildingMap(null, null);
|
||||
map.Add(blk);
|
||||
var geo = blk.Geo!;
|
||||
foreach (var b in blk.Buildings)
|
||||
{
|
||||
foreach (var d in b.Doors)
|
||||
{
|
||||
doors++;
|
||||
Check.False(geo.TryFloorHeight(d.Outside.X, d.Outside.Y, d.Outside.Z - 6, 6.4, out _),
|
||||
$"{label} {map.Name(b.Id)} door {d.Cell:X8} at {d.At.X:F1},{d.At.Y:F1}: its step out is over no floor");
|
||||
Check.True(geo.OnFloorOfAny(b.Cells, d.Inner.X, d.Inner.Y, d.Inner.Z), $"{label} {map.Name(b.Id)} door {d.Cell:X8}: its step in is on the floor");
|
||||
Check.True(d.Inner.FlatDistanceTo(d.Outside) > 1.9 && d.Inner.FlatDistanceTo(d.At) + d.At.FlatDistanceTo(d.Outside) < d.Inner.FlatDistanceTo(d.Outside) + 0.01,
|
||||
$"{label} door {d.Cell:X8}: in, door, out in a line");
|
||||
}
|
||||
if (b.Doors.Count == 0) continue;
|
||||
var d0 = b.Doors[0];
|
||||
foreach (uint c in b.Cells)
|
||||
{
|
||||
if (!FloorSpot(g, blk, c, out var spot)) continue;
|
||||
rooms++;
|
||||
var p = map.Inside(d0.Cell, d0.Inner, c, spot);
|
||||
if (p.Status == OutdoorHunt.PathStatus.Ok) walks++;
|
||||
else Check.True(false, $"{label} {map.Name(b.Id)}: no walk from door {d0.Cell:X8} to {c:X8} ({p.Status})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void RealHoltburg()
|
||||
{
|
||||
var g = Dats();
|
||||
if (g == null) { Check.True(true, "no dats on this PC: skipped"); return; }
|
||||
var a9b4 = BuildingMap.Load(0xA9B4, g.CellDat, g.DungeonLOS);
|
||||
Check.True(a9b4.Graph.Count == 138 && a9b4.Buildings.Count == 15, $"A9B4 (Holtburg): {a9b4.Graph.Count} cells in {a9b4.Buildings.Count} buildings");
|
||||
Check.True(a9b4.Buildings.All(b => b.Doors.Count > 0), "every building in it has a door: " + string.Join(" ", a9b4.Buildings.Select(b => b.Doors.Count)));
|
||||
var b0 = a9b4.Buildings[0];
|
||||
Check.True(b0.Cells.Count == 17 && b0.Doors.Count == 3, $"A9B4#0: 17 cells, 3 doors ({b0.Cells.Count}, {b0.Doors.Count})");
|
||||
Check.True(b0.NotDoors.Any(n => n.Contains("window")), "and a window that isn't one");
|
||||
var b4 = a9b4.Buildings[4];
|
||||
Check.True(b4.NotDoors.Count(n => n.Contains("step out is over a floor")) == 2, "A9B4#4: its two upper-storey doors onto the roof below aren't doors: " + string.Join(" | ", b4.NotDoors));
|
||||
CheckDoorsAndWalks(g, a9b4, "A9B4", out int doors, out int rooms, out int walks);
|
||||
Check.True(doors >= 30 && rooms >= 60 && walks == rooms, $"A9B4: {doors} doors, a walk from a door to all {rooms} rooms with a floor ({walks})");
|
||||
Console.WriteLine($" A9B4: {a9b4.Graph.Count} cells, {a9b4.Buildings.Count} buildings, {doors} doors ({a9b4.Buildings.Sum(b => b.NotDoors.Count)} openings out that are not), {walks}/{rooms} rooms walked to from a door");
|
||||
|
||||
var a9b3 = BuildingMap.Load(0xA9B3, g.CellDat, g.DungeonLOS);
|
||||
CheckDoorsAndWalks(g, a9b3, "A9B3", out doors, out rooms, out walks);
|
||||
Check.True(a9b3.Buildings.Count == 2 && doors == 4 && walks == rooms && rooms > 0, $"A9B3: {a9b3.Buildings.Count} buildings, {doors} doors, {walks}/{rooms} rooms walked to");
|
||||
Console.WriteLine($" A9B3: {a9b3.Buildings.Count} buildings, {doors} doors, {walks}/{rooms} rooms walked to");
|
||||
var empty = BuildingMap.Load(0xA8B3, g.CellDat, g.DungeonLOS);
|
||||
Check.Eq(empty.Buildings.Count, 0, "A8B3: no buildings");
|
||||
}
|
||||
|
||||
private static void RealDf61()
|
||||
{
|
||||
var g = Dats();
|
||||
if (g == null) { Check.True(true, "no dats on this PC: skipped"); return; }
|
||||
var blk = BuildingMap.Load(0xDF61, g.CellDat, g.DungeonLOS);
|
||||
Check.True(blk.SharedOpenings >= 5 && blk.Buildings.Count == 6, $"DF61: {blk.SharedOpenings} shared openings joined, {blk.Graph.Count} cells in {blk.Buildings.Count} buildings (11 groups before)");
|
||||
int wallTops = blk.Buildings.Sum(b => b.NotDoors.Count(n => n.Contains("step out is over a floor")));
|
||||
Check.True(wallTops >= 5, $"{wallTops} openings onto the wall tops aren't doors");
|
||||
CheckDoorsAndWalks(g, blk, "DF61", out int doors, out int rooms, out int walks);
|
||||
Check.True(doors >= 8 && walks == rooms && rooms >= 15, $"DF61: {doors} doors, {walks}/{rooms} rooms walked to");
|
||||
Console.WriteLine($" DF61: {blk.Graph.Count} cells, {blk.SharedOpenings} shared openings joined, {blk.Buildings.Count} buildings, {doors} doors, {wallTops} wall-top openings left out, {walks}/{rooms} rooms walked to");
|
||||
}
|
||||
|
||||
private static void RealHuntHoltburg()
|
||||
{
|
||||
var g = Dats();
|
||||
if (g == null) { Check.True(true, "no dats on this PC: skipped"); return; }
|
||||
var map = new BuildingMap(null, null);
|
||||
var blk = BuildingMap.Load(0xA9B4, g.CellDat, g.DungeonLOS);
|
||||
map.Add(blk);
|
||||
var b0 = blk.Buildings[0];
|
||||
// The room farthest from the first door, and a spot 30 yd out from that door.
|
||||
var d0 = b0.Doors[0];
|
||||
uint room = 0; Vec spot = default; double far = -1;
|
||||
foreach (uint c in b0.Cells)
|
||||
if (FloorSpot(g, blk, c, out var s) && s.FlatDistanceTo(d0.At) > far) { far = s.FlatDistanceTo(d0.At); room = c; spot = s; }
|
||||
Check.True(room != 0, $"a room of A9B4#0 to hunt in: {room:X8} at {spot.X:F1},{spot.Y:F1},{spot.Z:F1}");
|
||||
var outward = new Vec(d0.Outside.X - d0.At.X, d0.Outside.Y - d0.At.Y, 0);
|
||||
double ol = Math.Sqrt(outward.X * outward.X + outward.Y * outward.Y);
|
||||
var me = new Vec(d0.At.X + outward.X / ol * 30, d0.At.Y + outward.Y / ol * 30, d0.At.Z);
|
||||
var nav = new Nav();
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var d = h.Tick(T0, me, 0xA9B4002Au, true, Sorted(C(1, spot, me, room)), nav.Path, map);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners != null && d.Corners[^1] == spot, $"walks in to it: {d.Act}");
|
||||
Check.True(h.Note.Contains("inside building A9B4#0") && h.Note.Contains("through the door at"), "logged: " + h.Note);
|
||||
Console.WriteLine(" " + h.Note);
|
||||
int door = d.Corners!.ToList().FindIndex(v => b0.Doors.Any(x => x.At == v));
|
||||
Check.True(door > 0, "through one of its doors: " + Pts(d.Corners));
|
||||
foreach (var v in d.Corners.Skip(door + 1))
|
||||
Check.True(NearFloor(blk.Geo!, b0.Cells, v), $"every corner past the door is on the building's floor ({v.X:F1},{v.Y:F1},{v.Z:F1})");
|
||||
|
||||
// From that room back out to a monster 40 yd out of the door: through a door, then on the map.
|
||||
var outside = new Vec(d0.At.X + outward.X / ol * 40, d0.At.Y + outward.Y / ol * 40, d0.At.Z);
|
||||
var h2 = new OutdoorHunt();
|
||||
h2.Start(T0, spot);
|
||||
d = h2.Tick(T0, spot, room, true, Sorted(C(2, outside, spot)), new Nav().Path, map);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners![^1] == outside && h2.Note.Contains("out of building A9B4#0 through the door at"), "and back out: " + h2.Note);
|
||||
Console.WriteLine(" " + h2.Note);
|
||||
var exit = b0.Doors.FirstOrDefault(x => d.Corners!.Contains(x.At));
|
||||
Check.True(exit.Cell != 0 && Idx(d.Corners!, exit.Outside) == Idx(d.Corners!, exit.At) + 1, "door, then its step out: " + Pts(d.Corners));
|
||||
|
||||
// A portal in the middle of the walk's longest leg: kept out of, or no walk at all; never through it.
|
||||
var way = new List<Vec> { d0.Inner };
|
||||
var direct = map.Inside(d0.Cell, d0.Inner, room, spot);
|
||||
way.AddRange(direct.Corners);
|
||||
int longest = 0;
|
||||
for (int i = 1; i + 1 < way.Count; i++)
|
||||
if (way[i].FlatDistanceTo(way[i + 1]) > way[longest].FlatDistanceTo(way[longest + 1])) longest = i;
|
||||
var la = way[longest]; var lb = way[longest + 1];
|
||||
Check.True(la.FlatDistanceTo(lb) >= 4, $"the walk in has a leg of 4 m or more ({la.FlatDistanceTo(lb):F1})");
|
||||
var mid = new Vec((la.X + lb.X) / 2, (la.Y + lb.Y) / 2, (la.Z + lb.Z) / 2);
|
||||
var portal = new BuildingMap.PortalSpot(1, mid.X, mid.Y, mid.Z, 1.5);
|
||||
map.Portals = new[] { portal };
|
||||
var round = map.Inside(d0.Cell, d0.Inner, room, spot);
|
||||
if (round.Status != OutdoorHunt.PathStatus.NoPath)
|
||||
{
|
||||
var w2 = new List<Vec> { d0.Inner };
|
||||
w2.AddRange(round.Corners);
|
||||
double nearest = double.MaxValue;
|
||||
for (int i = 0; i + 1 < w2.Count; i++) nearest = Math.Min(nearest, SegDist(w2[i], w2[i + 1], portal.X, portal.Y));
|
||||
Check.True(nearest >= portal.R - 0.01, $"a 1.5 m portal at {mid.X:F1},{mid.Y:F1}: the walk keeps {nearest:F2} m from it ({round.Status}): {Pts(w2)}");
|
||||
Console.WriteLine($" a 1.5 m portal at {mid.X:F1},{mid.Y:F1}: {round.Status}, the walk keeps {nearest:F2} m from it, {w2.Count - 1} corners (was {way.Count - 1})");
|
||||
}
|
||||
else Check.True(true, "a portal where the walk can't get round it: no walk");
|
||||
}
|
||||
}
|
||||
916
Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs
Normal file
916
Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs
Normal file
|
|
@ -0,0 +1,916 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.ItemTool;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The Item Tool (2026-10-17): the chest looter ("pick a chest, pick a key, it loots the chest with
|
||||
// the current loot profile until it is out of keys") and Quick give (a rapid give of one picked
|
||||
// item to one picked player or NPC). The state machines run here on a fake environment with a
|
||||
// clock the test moves; the plugin glue (commands, who may start Quick give, the loot hand-over,
|
||||
// the give path) runs on the fake host. The existing profile give (GiveTests, ExpressionTests) is
|
||||
// untouched: Quick give shares nothing with it.
|
||||
internal static class ItemToolTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
// Chest looter state machine
|
||||
r.Add("chest looter: key, open, loot, wait for the re-lock, repeat until the key is used up", ChestHappyPath);
|
||||
r.Add("chest looter: the next cycle waits for the chest's regen timer", ChestWaitsForRegen);
|
||||
r.Add("chest looter: a chest that was unlocked is opened without spending the key; later 'already unlocked' answers are probes, bounded", ChestAlreadyUnlockedProbes);
|
||||
r.Add("chest looter: a second key of the same name takes over when the first is gone", ChestSwitchesKey);
|
||||
r.Add("chest looter: wrong key, not a lock, chest open elsewhere -> stops with the reason", ChestKeyErrors);
|
||||
r.Add("chest looter: chest gone, no answer, chest won't open, looter never starts -> bounded, says why", ChestBoundedFailures);
|
||||
r.Add("chest looter: combat/busy holds every send, then the run stops after the cap", ChestHoldsThenStops);
|
||||
r.Add("chest looter: can't start without a chest, a key, a loaded near chest; Stop always works and ends the loot session", ChestStartRefusalsAndStop);
|
||||
r.Add("chest looter: a key that never runs out is cut off at MaxCycles", ChestMaxCycles);
|
||||
// Quick give state machine
|
||||
r.Add("quick give: one give at a time, each after the last landed, paced; done when none is left", GiveOneAtATime);
|
||||
r.Add("quick give: a refused item is left out; three refusals in a row stop it", GiveRefusals);
|
||||
r.Add("quick give: stops when the target vanishes, changes, moves away or a fight starts", GiveStopConditions);
|
||||
r.Add("quick give: refuses to start with the target far, unloaded, no item or in a fight; busy client waits", GiveStartRefusals);
|
||||
// Plugin glue
|
||||
r.Add("item tool: the chest looter picks the selected chest and key, unlocks, opens and loots with the macro off, stops when out of keys", PluginChestRun);
|
||||
r.Add("item tool: chest/key picks refuse the wrong things (a pack item as chest, a world object as key, house storage)", PluginChestPicks);
|
||||
r.Add("item tool: Quick give hands over exactly the picked item to the picked NPC, never worn gear or other names", PluginQuickGive);
|
||||
r.Add("item tool: Quick give starts only from the panel or a typed line, never from a meta, a script or a remote line; stop works from anywhere", PluginGiveTrust);
|
||||
r.Add("item tool: Quick give targets are players or NPCs only", PluginGiveTargets);
|
||||
}
|
||||
|
||||
// ── Fake environments ────────────────────────────────────────────────────
|
||||
|
||||
private sealed class ChestEnv : IChestKeyEnv
|
||||
{
|
||||
public long T = 1_000_000;
|
||||
public long Now => T;
|
||||
public bool Loaded = true;
|
||||
public double Meters = 3;
|
||||
public bool Unlimited; // FindKey always finds the key
|
||||
public readonly HashSet<int> Keys = new() { 11 };
|
||||
public string KeyName = "Aged Key";
|
||||
public string? Hold;
|
||||
public bool HasUseDone { get; set; } = true;
|
||||
public int Seq;
|
||||
public uint LastErr;
|
||||
public readonly List<string> Said = new(), Logs = new(), Sent = new();
|
||||
public long OpenedAt;
|
||||
public bool LootingNow, LootPending;
|
||||
public int LootStarts, Aborts;
|
||||
public bool? Locked;
|
||||
public bool SendFails;
|
||||
/// <summary>> 0: the corpse looter is played: it takes a requested chest and lets go this long after.</summary>
|
||||
public long AutoLootMs;
|
||||
public bool IgnoreStart; // StartLooting does nothing (the looter never takes the chest)
|
||||
private long _lootEnd;
|
||||
|
||||
// The server's script for the next key use / open: filled by the test, run on send.
|
||||
public Func<int, uint?>? OnKey; // returns an error to answer with (null = no answer)
|
||||
public Func<bool>? OnOpen; // true = the chest opens
|
||||
|
||||
public ChestKeyLooter Looter = null!;
|
||||
|
||||
public string NameOf(int id) => "x";
|
||||
public bool ChestLoaded(int chestId, out double meters) { meters = Meters; return Loaded; }
|
||||
public int FindKey(int keyId, string keyName, int excludeId)
|
||||
{
|
||||
if (Unlimited) return keyId != 0 ? keyId : 11;
|
||||
if (keyId != 0 && keyId != excludeId && Keys.Contains(keyId)) return keyId;
|
||||
foreach (int k in Keys) if (k != excludeId && k != keyId) return k;
|
||||
return 0;
|
||||
}
|
||||
public string? HoldReason() => Hold;
|
||||
public int UseDoneSeq() => Seq;
|
||||
public bool LastUseDone(out int seq, out uint error) { seq = Seq; error = LastErr; return true; }
|
||||
public bool SendKey(int keyId, int chestId)
|
||||
{
|
||||
if (SendFails) return false;
|
||||
Sent.Add("key " + keyId);
|
||||
uint? ans = OnKey?.Invoke(keyId);
|
||||
if (ans != null) { LastErr = ans.Value; Seq++; }
|
||||
return true;
|
||||
}
|
||||
public bool SendOpen(int chestId)
|
||||
{
|
||||
if (SendFails) return false;
|
||||
Sent.Add("open");
|
||||
bool opens = OnOpen?.Invoke() ?? true;
|
||||
if (opens) OpenedAt = T + 1;
|
||||
LastErr = 0; Seq++;
|
||||
return true;
|
||||
}
|
||||
public long ChestOpenedAt(int chestId) => OpenedAt;
|
||||
public void StartLooting(int chestId) { LootStarts++; if (!IgnoreStart) LootPending = true; }
|
||||
public bool Looting(int chestId) => LootPending || LootingNow;
|
||||
public void AbortLooting(int chestId) { Aborts++; LootPending = LootingNow = false; }
|
||||
public bool? ChestLockedHint(int chestId) => Locked;
|
||||
public void Say(string text) => Said.Add(text);
|
||||
public void Log(string text) => Logs.Add(text);
|
||||
|
||||
/// <summary>Advances the clock in 100 ms steps, ticking, until done or the time is up.</summary>
|
||||
public void Run(long ms, Func<bool>? until = null)
|
||||
{
|
||||
long end = T + ms;
|
||||
while (T < end && (until == null || !until()))
|
||||
{
|
||||
T += 100;
|
||||
if (AutoLootMs > 0)
|
||||
{
|
||||
if (LootPending) { LootPending = false; LootingNow = true; _lootEnd = T + AutoLootMs; }
|
||||
else if (LootingNow && T >= _lootEnd) LootingNow = false;
|
||||
}
|
||||
Looter.Tick();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ChestEnv NewChest(out ChestKeyLooter looter)
|
||||
{
|
||||
var env = new ChestEnv();
|
||||
looter = new ChestKeyLooter(env);
|
||||
env.Looter = looter;
|
||||
looter.SetChest(500, "Mana Forge Chest");
|
||||
looter.SetKey(11, "Aged Key");
|
||||
return env;
|
||||
}
|
||||
|
||||
/// <summary>A server for the chest: the key unlocks (and chats), the chest opens, the loot session runs a little and ends.</summary>
|
||||
private static void Serve(ChestEnv env, ChestKeyLooter looter, int usesPerKey = 1, bool spendKey = true)
|
||||
{
|
||||
int uses = usesPerKey;
|
||||
env.OnKey = key =>
|
||||
{
|
||||
looter.OnChat("The Mana Forge Chest has been unlocked.");
|
||||
if (spendKey)
|
||||
{
|
||||
uses--;
|
||||
if (uses <= 0) { looter.OnChat("Your key is used up."); env.Keys.Remove(key); uses = usesPerKey; }
|
||||
else looter.OnChat($"Your key has {uses} uses left.");
|
||||
}
|
||||
return 0u;
|
||||
};
|
||||
}
|
||||
|
||||
private static string Said(ChestEnv env) => string.Join(" | ", env.Said);
|
||||
|
||||
// ── Chest looter ─────────────────────────────────────────────────────────
|
||||
|
||||
private static void ChestHappyPath()
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Keys.Clear(); env.Keys.Add(11);
|
||||
Serve(env, ck);
|
||||
env.AutoLootMs = 1000;
|
||||
Check.True(ck.Start(out _), "starts with a chest, a key and the chest near");
|
||||
Check.True(env.Said.Any(s => s.Contains("starting on Mana Forge Chest with Aged Key")), "says what it will do");
|
||||
|
||||
env.Run(60_000, () => !ck.Running);
|
||||
Check.Eq(string.Join(",", env.Sent), "key 11,open", "the key goes on the chest, then the chest is opened");
|
||||
Check.Eq(env.LootStarts, 1, "the open chest is handed to the looter once");
|
||||
|
||||
// The loot session ran and ended; the key was the last use, so the run ends out of keys.
|
||||
Check.False(ck.Running, "stopped");
|
||||
Check.Eq(ck.Looted, 1, "one chest looted");
|
||||
Check.True(Said(env).Contains("out of keys after 1 chest(s)"), "says it is out of keys (" + Said(env) + ")");
|
||||
Check.Eq(env.Sent.Count, 2, "nothing more sent");
|
||||
}
|
||||
|
||||
private static void ChestWaitsForRegen()
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Keys.Clear(); env.Keys.Add(11); env.Keys.Add(12); // two keys of the same name
|
||||
Serve(env, ck);
|
||||
env.AutoLootMs = 1000;
|
||||
ck.Start(out _);
|
||||
env.Run(5000, () => env.LootStarts > 0);
|
||||
env.Run(3000, () => ck.State == ChestKeyLooter.Phase.Waiting);
|
||||
Check.True(ck.Running, "a second key is carried: the run goes on");
|
||||
Check.Eq(ck.State, ChestKeyLooter.Phase.Waiting, "waiting for the chest to re-lock");
|
||||
Check.True(ck.Status.Contains("Waiting for Mana Forge Chest to re-lock"), "the status says so: " + ck.Status);
|
||||
int sentBefore = env.Sent.Count;
|
||||
long openedAt = env.OpenedAt;
|
||||
|
||||
env.Run(ChestKeyLooter.RegenWaitMs - 20_000);
|
||||
Check.Eq(env.Sent.Count, sentBefore, "nothing sent while the regen timer runs");
|
||||
env.Run(40_000, () => env.Sent.Count > sentBefore);
|
||||
Check.True(env.Sent.Count > sentBefore, "the next key goes after the wait");
|
||||
Check.True(env.T - openedAt >= ChestKeyLooter.RegenWaitMs - 1000, $"not before {ChestKeyLooter.RegenWaitMs} ms after the open ({env.T - openedAt})");
|
||||
|
||||
env.Run(60_000, () => !ck.Running);
|
||||
// The second key is spent too -> out of keys.
|
||||
Check.False(ck.Running, "out of keys after the second chest");
|
||||
Check.Eq(ck.Looted, 2, "two chests looted");
|
||||
}
|
||||
|
||||
private static void ChestAlreadyUnlockedProbes()
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Unlimited = true;
|
||||
env.AutoLootMs = 1000;
|
||||
bool unlocked = false;
|
||||
env.OnKey = _ => unlocked ? ChestKeyLooter.ErrLockAlreadyUnlocked : 0u; // first: unlocks; later: the chest never re-locks
|
||||
ck.Start(out _);
|
||||
env.Run(3000, () => env.LootStarts > 0);
|
||||
unlocked = true;
|
||||
env.Run(3000, () => ck.State == ChestKeyLooter.Phase.Waiting);
|
||||
Check.Eq(env.Sent.Where(s => s.StartsWith("key")).Count(), 1, "one key use so far");
|
||||
env.Run(ChestKeyLooter.RegenWaitMs + 2000);
|
||||
Check.True(env.Sent.Count(s => s.StartsWith("key")) >= 2, "after the regen wait the key is tried again");
|
||||
Check.Eq(env.Sent.Count(s => s == "open"), 1, "'already unlocked' on a later cycle does NOT open the empty chest again");
|
||||
env.Run(ChestKeyLooter.ProbeMs * (ChestKeyLooter.MaxProbes + 2));
|
||||
Check.False(ck.Running, "gave up after the probes");
|
||||
Check.Eq(env.Sent.Count(s => s.StartsWith("key")), 1 + ChestKeyLooter.MaxProbes + 1, "bounded: first use + one per probe");
|
||||
Check.True(Said(env).Contains("hasn't re-locked"), "says the chest never re-locked: " + Said(env));
|
||||
|
||||
// First cycle on a chest that was never locked: opened, no key spent.
|
||||
var env2 = NewChest(out var ck2);
|
||||
env2.AutoLootMs = 1000;
|
||||
env2.OnKey = _ => ChestKeyLooter.ErrLockAlreadyUnlocked;
|
||||
ck2.Start(out _);
|
||||
env2.Run(3000, () => env2.LootStarts > 0);
|
||||
Check.Eq(string.Join(",", env2.Sent), "key 11,open", "'already unlocked' on the first cycle -> opens it");
|
||||
}
|
||||
|
||||
private static void ChestSwitchesKey()
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Keys.Clear(); env.Keys.Add(11); env.Keys.Add(12);
|
||||
Serve(env, ck);
|
||||
env.AutoLootMs = 1000;
|
||||
ck.Start(out _);
|
||||
env.Run(3000, () => env.LootStarts > 0);
|
||||
Check.Eq(ck.KeyId, 11, "starts with the picked key");
|
||||
env.Run(3000, () => ck.State == ChestKeyLooter.Phase.Waiting);
|
||||
env.Run(ChestKeyLooter.RegenWaitMs + 5000, () => env.Sent.Count(s => s.StartsWith("key")) >= 2);
|
||||
Check.Eq(env.Sent.Last(s => s.StartsWith("key")), "key 12", "the other key of the same name is used once the first is gone");
|
||||
Check.Eq(ck.KeyId, 12, "remembered");
|
||||
}
|
||||
|
||||
private static void ChestKeyErrors()
|
||||
{
|
||||
foreach (var (err, text) in new[]
|
||||
{
|
||||
(ChestKeyLooter.ErrKeyDoesntFit, "doesn't fit"),
|
||||
(ChestKeyLooter.ErrCannotLockOrUnlock, "can't be unlocked with a key"),
|
||||
})
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.OnKey = _ => err;
|
||||
ck.Start(out _);
|
||||
env.Run(5000, () => !ck.Running);
|
||||
Check.False(ck.Running, $"error 0x{err:X} stops the run");
|
||||
Check.True(Said(env).Contains(text), $"says why ({text}): " + Said(env));
|
||||
Check.Eq(env.Sent.Count, 1, "one try, no retry of a hopeless key");
|
||||
}
|
||||
|
||||
// The chest is open elsewhere: three waits, then it stops.
|
||||
var e3 = NewChest(out var c3);
|
||||
e3.OnKey = _ => ChestKeyLooter.ErrCannotLockWhatIsOpen;
|
||||
c3.Start(out _);
|
||||
e3.Run(60_000, () => !c3.Running);
|
||||
Check.False(c3.Running, "a chest that stays open ends the run");
|
||||
Check.Eq(e3.Sent.Count, ChestKeyLooter.MaxOpenElsewhere, "bounded tries");
|
||||
|
||||
// 'Too busy' backs off and is bounded.
|
||||
var e4 = NewChest(out var c4);
|
||||
e4.OnKey = _ => ChestKeyLooter.ErrTooBusy;
|
||||
c4.Start(out _);
|
||||
e4.Run(120_000, () => !c4.Running);
|
||||
Check.False(c4.Running, "endless 'too busy' ends the run");
|
||||
Check.Eq(e4.Sent.Count, ChestKeyLooter.MaxBusy, "bounded tries");
|
||||
}
|
||||
|
||||
private static void ChestBoundedFailures()
|
||||
{
|
||||
// The chest goes out of view.
|
||||
var env = NewChest(out var ck);
|
||||
env.OnKey = _ => null;
|
||||
ck.Start(out _);
|
||||
env.Run(500);
|
||||
env.Loaded = false;
|
||||
env.Run(ChestKeyLooter.GoneMs + 1000, () => !ck.Running);
|
||||
Check.False(ck.Running, "stopped when the chest is gone");
|
||||
Check.True(Said(env).Contains("is gone"), "says so");
|
||||
|
||||
// The server never answers the key use.
|
||||
var e2 = NewChest(out var c2);
|
||||
e2.OnKey = _ => null;
|
||||
c2.Start(out _);
|
||||
e2.Run(120_000, () => !c2.Running);
|
||||
Check.False(c2.Running, "no answer ends the run");
|
||||
Check.Eq(e2.Sent.Count, ChestKeyLooter.MaxTimeouts, "after that many tries");
|
||||
Check.True(Said(e2).Contains("no answer"), "says why: " + Said(e2));
|
||||
|
||||
// The chest never opens.
|
||||
var e3 = NewChest(out var c3);
|
||||
Serve(e3, c3, usesPerKey: 99);
|
||||
e3.Keys.Add(12);
|
||||
e3.OnOpen = () => false;
|
||||
c3.Start(out _);
|
||||
e3.Run(120_000, () => !c3.Running);
|
||||
Check.False(c3.Running, "a chest that won't open ends the run");
|
||||
Check.True(Said(e3).Contains("wouldn't open"), "says why: " + Said(e3));
|
||||
Check.Eq(e3.Sent.Count(s => s == "open"), ChestKeyLooter.MaxOpenFails, "bounded opens");
|
||||
|
||||
// The looter never takes the chest.
|
||||
var e4 = NewChest(out var c4);
|
||||
Serve(e4, c4);
|
||||
e4.IgnoreStart = true; // the corpse looter refused it
|
||||
c4.Start(out _);
|
||||
e4.Run(ChestKeyLooter.LootStartMs + 8000, () => !c4.Running);
|
||||
Check.False(c4.Running, "stopped");
|
||||
Check.True(Said(e4).Contains("never took"), "says why: " + Said(e4));
|
||||
|
||||
// The loot session never ends.
|
||||
var e5 = NewChest(out var c5);
|
||||
Serve(e5, c5);
|
||||
c5.Start(out _);
|
||||
e5.Run(3000, () => e5.LootStarts > 0);
|
||||
e5.LootPending = false; e5.LootingNow = true;
|
||||
e5.Run(ChestKeyLooter.LootMaxMs + 5000, () => !c5.Running);
|
||||
Check.False(c5.Running, "a stuck loot session is cut off");
|
||||
Check.Eq(e5.Aborts, 1, "and the session is ended");
|
||||
}
|
||||
|
||||
private static void ChestHoldsThenStops()
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
Serve(env, ck);
|
||||
env.Hold = "combat";
|
||||
ck.Start(out _);
|
||||
env.Run(ChestKeyLooter.HoldMaxMs - 5000);
|
||||
Check.Eq(env.Sent.Count, 0, "nothing is sent while combat holds");
|
||||
Check.True(ck.Status.Contains("combat"), "the status says why it waits: " + ck.Status);
|
||||
env.Hold = null;
|
||||
env.Run(3000, () => env.Sent.Count > 0);
|
||||
Check.True(env.Sent.Count > 0, "it goes on when the hold ends");
|
||||
|
||||
var e2 = NewChest(out var c2);
|
||||
e2.Hold = "the client is busy (1)";
|
||||
c2.Start(out _);
|
||||
e2.Run(ChestKeyLooter.HoldMaxMs + 5000, () => !c2.Running);
|
||||
Check.False(c2.Running, "a hold that never ends stops the run");
|
||||
Check.Eq(e2.Sent.Count, 0, "without sending anything");
|
||||
Check.True(Said(e2).Contains("waited"), "says why: " + Said(e2));
|
||||
}
|
||||
|
||||
private static void ChestStartRefusalsAndStop()
|
||||
{
|
||||
var env = new ChestEnv();
|
||||
var ck = new ChestKeyLooter(env);
|
||||
env.Looter = ck;
|
||||
Check.False(ck.Start(out string why), "no chest");
|
||||
Check.True(why.Contains("pick a chest"), why);
|
||||
ck.SetChest(500, "Chest");
|
||||
Check.False(ck.Start(out why), "no key");
|
||||
Check.True(why.Contains("pick a key"), why);
|
||||
ck.SetKey(11, "Aged Key");
|
||||
env.Meters = 40;
|
||||
Check.False(ck.Start(out why), "chest too far");
|
||||
Check.True(why.Contains("40 m away"), why);
|
||||
env.Meters = 3; env.Loaded = false;
|
||||
Check.False(ck.Start(out why), "chest not loaded");
|
||||
env.Loaded = true; env.Keys.Clear();
|
||||
Check.False(ck.Start(out why), "key gone");
|
||||
Check.True(why.Contains("no 'Aged Key'"), why);
|
||||
Check.True(env.Said.Count(s => s.Contains("can't start")) == 5, "each refusal is said in chat");
|
||||
|
||||
// Stop works in every phase and ends a loot session.
|
||||
env.Keys.Add(11);
|
||||
Serve(env, ck);
|
||||
ck.Start(out _);
|
||||
env.Run(3000, () => env.LootStarts > 0);
|
||||
env.LootPending = false; env.LootingNow = true;
|
||||
env.Run(300);
|
||||
Check.Eq(ck.State, ChestKeyLooter.Phase.Looting, "looting");
|
||||
ck.Stop("stopped by you");
|
||||
Check.False(ck.Running, "stopped");
|
||||
Check.Eq(env.Aborts, 1, "the loot session is ended and the chest closed");
|
||||
Check.True(Said(env).Contains("stopped by you"), "says it stopped");
|
||||
ck.Stop(); // already stopped
|
||||
Check.True(Said(env).Contains("not running"), "stopping a stopped looter says so");
|
||||
Check.False(ck.Running, "and does nothing");
|
||||
}
|
||||
|
||||
private static void ChestMaxCycles()
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Unlimited = true;
|
||||
env.AutoLootMs = 300;
|
||||
env.Locked = true; // the client reads the chest locked again at once; MinRelockMs still applies
|
||||
Serve(env, ck, spendKey: false);
|
||||
ck.Start(out _);
|
||||
env.Run(60_000_000, () => !ck.Running);
|
||||
Check.False(ck.Running, "ended");
|
||||
Check.Eq(ck.Looted, ChestKeyLooter.MaxCycles, "after MaxCycles chests");
|
||||
string said = Said(env);
|
||||
Check.True(said.Contains($"{ChestKeyLooter.MaxCycles} cycles"), "says why: " + said.Substring(Math.Max(0, said.Length - 200)));
|
||||
}
|
||||
|
||||
// ── Quick give state machine ─────────────────────────────────────────────
|
||||
|
||||
private sealed class GiveEnv : IQuickGiveEnv
|
||||
{
|
||||
public long T = 5_000_000;
|
||||
public long Now => T;
|
||||
public string TargetName = "Town Crier";
|
||||
public bool Loaded = true;
|
||||
public double Meters = 2;
|
||||
public bool Combat;
|
||||
public string? Hold;
|
||||
public readonly List<int> Items = new() { 1, 2, 3 }; // carried, in order
|
||||
public readonly Dictionary<int, int> Counts = new();
|
||||
public readonly List<(long At, int Item)> Sent = new();
|
||||
public readonly HashSet<int> Takes = new(); // items the server accepts (empty = all)
|
||||
public readonly HashSet<int> Refuses = new(); // items it refuses with an error
|
||||
public bool Silent; // never answers
|
||||
public int Refusals;
|
||||
public readonly List<string> Said = new(), Logs = new();
|
||||
public QuickGive Gv = null!;
|
||||
public int PendingLand; // item in flight, lands after LandMs
|
||||
public long LandAt;
|
||||
public long LandMs = 200;
|
||||
|
||||
public bool TargetLoaded(int targetId, out string name, out double meters) { name = TargetName; meters = Meters; return Loaded; }
|
||||
public bool InCombat() => Combat;
|
||||
public string? HoldReason() => Hold;
|
||||
public bool NextItem(GiveItemKey key, ISet<int> skip, out int itemId, out int count)
|
||||
{
|
||||
foreach (int i in Items)
|
||||
if (!skip.Contains(i)) { itemId = i; count = Counts.TryGetValue(i, out int c) ? c : 1; return true; }
|
||||
itemId = 0; count = 0; return false;
|
||||
}
|
||||
public int CountCarried(GiveItemKey key) => Items.Count;
|
||||
public bool Landed(int itemId, int count) => !Items.Contains(itemId);
|
||||
public bool Send(int itemId, int targetId)
|
||||
{
|
||||
Sent.Add((T, itemId));
|
||||
if (Silent) return true;
|
||||
if (Refuses.Contains(itemId)) { Refusals++; return true; }
|
||||
PendingLand = itemId; LandAt = T + LandMs;
|
||||
return true;
|
||||
}
|
||||
public int RefusalSeq() => Refusals;
|
||||
public void Say(string text) => Said.Add(text);
|
||||
public void Log(string text) => Logs.Add(text);
|
||||
|
||||
public void Run(long ms, Func<bool>? until = null)
|
||||
{
|
||||
long end = T + ms;
|
||||
while (T < end && (until == null || !until()))
|
||||
{
|
||||
T += 50;
|
||||
if (PendingLand != 0 && T >= LandAt) { Items.Remove(PendingLand); PendingLand = 0; }
|
||||
Gv.Tick();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static GiveEnv NewGive(out QuickGive qg)
|
||||
{
|
||||
var env = new GiveEnv();
|
||||
qg = new QuickGive(env);
|
||||
env.Gv = qg;
|
||||
qg.SetItem(1, new GiveItemKey(0x1234, "Mana Mote"));
|
||||
qg.SetTarget(900, "Town Crier");
|
||||
return env;
|
||||
}
|
||||
|
||||
private static void GiveOneAtATime()
|
||||
{
|
||||
var env = NewGive(out var qg);
|
||||
Check.True(qg.Start(out _), "starts");
|
||||
Check.True(env.Said[0].Contains("Town Crier") && env.Said[0].Contains("Mana Mote"), "the start line names the target and the item: " + env.Said[0]);
|
||||
env.Run(20_000, () => !qg.Running);
|
||||
Check.Eq(string.Join(",", env.Sent.Select(s => s.Item)), "1,2,3", "each item once, in order");
|
||||
for (int i = 1; i < env.Sent.Count; i++)
|
||||
Check.True(env.Sent[i].At - env.Sent[i - 1].At >= env.LandMs + QuickGive.PaceMs - 50, $"give {i + 1} waited for the last to land and the pace ({env.Sent[i].At - env.Sent[i - 1].At} ms)");
|
||||
Check.Eq(qg.Given, 3, "three given");
|
||||
Check.False(qg.Running, "done");
|
||||
Check.True(env.Said.Last().Contains("done"), "says it is done: " + env.Said.Last());
|
||||
Check.True(qg.Status.Contains("3 item(s)"), "the status keeps the result: " + qg.Status);
|
||||
}
|
||||
|
||||
private static void GiveRefusals()
|
||||
{
|
||||
// One refused item is skipped; the others go.
|
||||
var env = NewGive(out var qg);
|
||||
env.Refuses.Add(2);
|
||||
qg.Start(out _);
|
||||
env.Run(30_000, () => !qg.Running);
|
||||
Check.Eq(string.Join(",", env.Sent.Select(s => s.Item)), "1,2,3", "item 2 refused once, not retried; item 3 given");
|
||||
Check.Eq(qg.Given, 2, "two given");
|
||||
Check.False(qg.Running, "it ends when only the refused one is left");
|
||||
|
||||
// Three in a row stop it.
|
||||
var e2 = NewGive(out var q2);
|
||||
e2.Items.Clear(); e2.Items.AddRange(new[] { 1, 2, 3, 4, 5 });
|
||||
foreach (int i in e2.Items) e2.Refuses.Add(i);
|
||||
q2.Start(out _);
|
||||
e2.Run(60_000, () => !q2.Running);
|
||||
Check.False(q2.Running, "stopped");
|
||||
Check.Eq(e2.Sent.Count, QuickGive.MaxRefusals, "after that many refusals in a row, not the whole pack");
|
||||
Check.True(e2.Said.Last().Contains("refusals in a row"), "says why: " + e2.Said.Last());
|
||||
|
||||
// No answer at all counts as a refusal after the confirm timeout.
|
||||
var e3 = NewGive(out var q3);
|
||||
e3.Silent = true;
|
||||
q3.Start(out _);
|
||||
e3.Run(120_000, () => !q3.Running);
|
||||
Check.False(q3.Running, "stopped");
|
||||
Check.Eq(e3.Sent.Count, QuickGive.MaxRefusals, "unanswered gives are bounded the same way");
|
||||
Check.True(e3.Sent[1].At - e3.Sent[0].At >= QuickGive.ConfirmMs, "each waited the confirm time before the next");
|
||||
}
|
||||
|
||||
private static void GiveStopConditions()
|
||||
{
|
||||
void Case(string name, Action<GiveEnv> change, string expect)
|
||||
{
|
||||
var env = NewGive(out var qg);
|
||||
env.Items.Clear(); env.Items.AddRange(Enumerable.Range(1, 30));
|
||||
qg.Start(out _);
|
||||
env.Run(600);
|
||||
Check.True(qg.Running, name + ": running before");
|
||||
change(env);
|
||||
env.Run(5000, () => !qg.Running);
|
||||
Check.False(qg.Running, name + ": stops");
|
||||
Check.True(env.Said.Last().Contains(expect), $"{name}: says '{expect}' ({env.Said.Last()})");
|
||||
}
|
||||
Case("vanishes", e => e.Loaded = false, "is gone");
|
||||
Case("renamed", e => e.TargetName = "Somebody Else", "the target changed");
|
||||
Case("moves away", e => e.Meters = 30, "out of give range");
|
||||
Case("fight", e => e.Combat = true, "a fight started");
|
||||
|
||||
// A target that comes back within the grace is fine.
|
||||
var env2 = NewGive(out var q2);
|
||||
env2.Items.Clear(); env2.Items.AddRange(Enumerable.Range(1, 30));
|
||||
q2.Start(out _);
|
||||
env2.Run(300);
|
||||
env2.Loaded = false; env2.Run(500); env2.Loaded = true; env2.Run(500);
|
||||
Check.True(q2.Running, "a flicker shorter than the grace doesn't stop it");
|
||||
q2.Stop("stopped by you");
|
||||
Check.False(q2.Running, "Stop always works");
|
||||
}
|
||||
|
||||
private static void GiveStartRefusals()
|
||||
{
|
||||
var env = NewGive(out var qg);
|
||||
env.Meters = 12;
|
||||
Check.False(qg.Start(out string why), "target 12 m away");
|
||||
Check.True(why.Contains("give range is 10 m"), why);
|
||||
env.Meters = 2; env.Loaded = false;
|
||||
Check.False(qg.Start(out why), "target not loaded");
|
||||
env.Loaded = true; env.TargetName = "Other";
|
||||
Check.False(qg.Start(out why), "target is someone else now");
|
||||
env.TargetName = "Town Crier"; env.Combat = true;
|
||||
Check.False(qg.Start(out why), "in a fight");
|
||||
env.Combat = false; env.Items.Clear();
|
||||
Check.False(qg.Start(out why), "nothing to give");
|
||||
Check.False(qg.Running, "never started");
|
||||
Check.Eq(env.Sent.Count, 0, "nothing sent");
|
||||
|
||||
var e2 = new GiveEnv(); var q2 = new QuickGive(e2); e2.Gv = q2;
|
||||
Check.False(q2.Start(out why), "no item picked");
|
||||
q2.SetItem(1, new GiveItemKey(1, "X"));
|
||||
Check.False(q2.Start(out why), "no target picked");
|
||||
|
||||
// The client is busy: the give waits, then goes.
|
||||
var e3 = NewGive(out var q3);
|
||||
e3.Hold = "the client is busy (1)";
|
||||
q3.Start(out _);
|
||||
e3.Run(2000);
|
||||
Check.Eq(e3.Sent.Count, 0, "nothing while the client is busy");
|
||||
e3.Hold = null;
|
||||
e3.Run(500, () => e3.Sent.Count > 0);
|
||||
Check.True(e3.Sent.Count > 0, "it goes when the client is free");
|
||||
}
|
||||
|
||||
// ── Plugin glue ──────────────────────────────────────────────────────────
|
||||
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint Chest = 0x7A9B4101;
|
||||
private const uint Key = 0x80290001, Key2 = 0x80290002;
|
||||
private const uint Gem = 0x80290101;
|
||||
private const uint Npc = 0x80290200, Bystander = 0x80290201, Monster = 0x80290202, Corpse = 0x80290203;
|
||||
private const uint Mote1 = 0x80290301, Mote2 = 0x80290302, Mote3 = 0x80290303, WornMote = 0x80290304, OtherMote = 0x80290305, ClonedMote = 0x80290306;
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = false, // the Item Tool works with the macro off
|
||||
EnableLooting = false,
|
||||
EnableCombat = false,
|
||||
LootOwnership = 0,
|
||||
LootContentSettleMs = 0,
|
||||
LootEmptyCorpseMs = 0,
|
||||
StopLootingWhenPackFull = false,
|
||||
GiveQueueIntervalMs = 0,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public Bot(RynthCoreHost host, string profile, params uint[] objects)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
S.CurrentLootPath = profile;
|
||||
foreach (uint id in objects) Cache.OnCreateObject(id);
|
||||
Cache.Tick();
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
public object? Call(string m, params object?[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
|
||||
/// <summary>One plugin tick's worth: the Item Tool, then the loot tick (what OnTick runs).</summary>
|
||||
public void Tick()
|
||||
{
|
||||
Call("TickItemTool");
|
||||
Set("_activity", BotActivity.Looting);
|
||||
Call("TickCorpseOpening");
|
||||
}
|
||||
|
||||
public void TickUntil(Func<bool> done, int max = 600)
|
||||
{
|
||||
for (int i = 0; i < max && !done(); i++) { Tick(); Thread.Sleep(10); }
|
||||
}
|
||||
|
||||
public void ServerOpens(uint container)
|
||||
{
|
||||
FakeHost.GroundContainer = container;
|
||||
P.OnViewObjectContents(container);
|
||||
P.OnUpdateObjectInventory(container);
|
||||
}
|
||||
|
||||
public void ServerCloses(uint container)
|
||||
{
|
||||
if (FakeHost.GroundContainer == container) FakeHost.GroundContainer = 0;
|
||||
P.OnStopViewingObjectContents(container);
|
||||
}
|
||||
|
||||
/// <summary>The player types / presses: a trusted command.</summary>
|
||||
public void Cmd(string args) => P.QueueItemToolCommand(args, trusted: true);
|
||||
}
|
||||
|
||||
private static string ProfilePath(string name)
|
||||
{
|
||||
string path = System.IO.Path.Combine(Program.TempRoot, name);
|
||||
var p = new LootProfile { Name = "itemtool" };
|
||||
var gems = new LootRule { Name = "Gems", Action = LootAction.Keep };
|
||||
gems.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
|
||||
p.Rules.Add(gems);
|
||||
p.Save(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
private static void BaseWorld()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true;
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CloseContainerCalls = true;
|
||||
FakeHost.UseOnCalls = true;
|
||||
FakeHost.GiveCalls = true;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.WeenieErrorCalls = true;
|
||||
var pose = (0x1048002Au, 100f, 100f, 0f);
|
||||
FakeHost.Names[Player] = "Dargoth Hera";
|
||||
FakeHost.Positions[Player] = pose;
|
||||
FakeHost.PlayerPose = pose;
|
||||
|
||||
FakeHost.Names[Chest] = "Mana Forge Chest";
|
||||
FakeHost.ItemTypes[Chest] = 0x200;
|
||||
FakeHost.Positions[Chest] = (pose.Item1, 102f, 100f, 0f);
|
||||
FakeHost.NotAttackable.Add(Chest);
|
||||
FakeHost.Containers[Chest] = 0;
|
||||
FakeHost.Names[Key] = "Aged Key"; FakeHost.ItemTypes[Key] = 0x1000; FakeHost.Containers[Key] = Player;
|
||||
FakeHost.Names[Key2] = "Aged Key"; FakeHost.ItemTypes[Key2] = 0x1000; FakeHost.Containers[Key2] = Player;
|
||||
FakeHost.Names[Gem] = "Black Opal"; FakeHost.ItemTypes[Gem] = 0x800; FakeHost.Containers[Gem] = Chest; FakeHost.Appraised.Add(Gem);
|
||||
|
||||
FakeHost.Names[Npc] = "Town Crier"; FakeHost.ItemTypes[Npc] = 0x10; FakeHost.NotAttackable.Add(Npc);
|
||||
FakeHost.Positions[Npc] = (pose.Item1, 101f, 100f, 0f);
|
||||
FakeHost.Names[Bystander] = "Some Player"; FakeHost.ItemTypes[Bystander] = 0x10; FakeHost.Bitfields[Bystander] = 0x8; // BF_PLAYER
|
||||
FakeHost.Positions[Bystander] = (pose.Item1, 101f, 101f, 0f);
|
||||
FakeHost.Names[Monster] = "Drudge Lurker"; FakeHost.ItemTypes[Monster] = 0x10;
|
||||
FakeHost.Positions[Monster] = (pose.Item1, 103f, 100f, 0f);
|
||||
FakeHost.Bitfields[Monster] = 0x10; // BF_ATTACKABLE: a monster, not an NPC
|
||||
foreach (var (id, name) in new[] { (Mote1, "Mana Mote"), (Mote2, "Mana Mote"), (Mote3, "Mana Mote"), (WornMote, "Mana Mote"), (OtherMote, "Lesser Mana Mote"), (ClonedMote, "Mana Mote") })
|
||||
{
|
||||
FakeHost.Names[id] = name; FakeHost.Containers[id] = Player; FakeHost.ItemTypes[id] = 0x80;
|
||||
FakeHost.Wcids[id] = 0x1111;
|
||||
}
|
||||
FakeHost.Wcids[ClonedMote] = 0x2222; // same name, a different weenie: not the picked item
|
||||
FakeHost.Wielded[WornMote] = 0x8000;
|
||||
}
|
||||
|
||||
private static Bot MakeBot(string profile = "itemtool-chest.json")
|
||||
{
|
||||
var host = FakeHost.Create(Player);
|
||||
return new Bot(host, ProfilePath(profile), Chest, Key, Key2, Gem, Npc, Bystander, Monster, Mote1, Mote2, Mote3, WornMote, OtherMote, ClonedMote);
|
||||
}
|
||||
|
||||
private static string Chat() => string.Join(" | ", FakeHost.Chat);
|
||||
|
||||
private static void PluginChestRun()
|
||||
{
|
||||
BaseWorld();
|
||||
var bot = MakeBot();
|
||||
FakeHost.SelectedItem = Chest;
|
||||
bot.Cmd("chest set");
|
||||
bot.Tick();
|
||||
FakeHost.SelectedItem = Key;
|
||||
bot.Cmd("chest key");
|
||||
bot.Tick();
|
||||
Check.True(Chat().Contains("chest = Mana Forge Chest") && Chat().Contains("key = Aged Key"), "picks are confirmed in chat: " + Chat());
|
||||
Check.False(bot.S.IsMacroRunning, "the macro is off");
|
||||
|
||||
// The server: the key unlocks (chat + UseDone), the chest opens (ViewContents + contents + UseDone).
|
||||
FakeHost.OnUseObjectOn = (src, tgt) =>
|
||||
{
|
||||
Check.Eq(src, Key, "the key is the source");
|
||||
Check.Eq(tgt, Chest, "the chest is the target");
|
||||
bot.Call("ItemToolChat", "The Mana Forge Chest has been unlocked.");
|
||||
bot.Call("ItemToolChat", "Your key is used up.");
|
||||
FakeHost.Containers.Remove(Key); // the key is consumed
|
||||
FakeHost.UseDone(0);
|
||||
};
|
||||
FakeHost.OnUseObject = id =>
|
||||
{
|
||||
if (id != Chest) return;
|
||||
FakeHost.UseDone(0);
|
||||
bot.ServerOpens(Chest);
|
||||
};
|
||||
bot.Cmd("chest start");
|
||||
// Key2 has the same name: it goes on after the first, so the run continues until it is spent too.
|
||||
bot.TickUntil(() => FakeHost.Uses.Contains(Chest));
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "one key use");
|
||||
Check.True(FakeHost.Uses.Contains(Chest), "then the chest is used (opened)");
|
||||
bot.TickUntil(() => FakeHost.ExternalMoves.Any(m => m.Id == Gem), 800);
|
||||
Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "the loot profile's gem is taken (macro off, Looting off)");
|
||||
FakeHost.Containers[Gem] = Player;
|
||||
int closes = FakeHost.Closes.Count;
|
||||
bot.TickUntil(() => FakeHost.Closes.Count > closes);
|
||||
Check.True(FakeHost.Closes.Contains(Chest), "the chest is closed when done");
|
||||
bot.ServerCloses(Chest);
|
||||
bot.TickUntil(() => Chat().Contains("looted Mana Forge Chest"), 200);
|
||||
Check.True(Chat().Contains("looted Mana Forge Chest (1 so far)"), "says it looted: " + Chat());
|
||||
Check.True(Chat().Contains("Chest looter stopped") || Chat().Contains("Waiting") || bot.Get<ChestKeyLooter>("_chestKey").Running, "the second key keeps it going");
|
||||
|
||||
// Take the second key away: the next check ends the run, out of keys.
|
||||
FakeHost.Containers.Remove(Key2);
|
||||
bot.TickUntil(() => !bot.Get<ChestKeyLooter>("_chestKey").Running, 400);
|
||||
Check.False(bot.Get<ChestKeyLooter>("_chestKey").Running, "stopped");
|
||||
Check.True(Chat().Contains("out of keys"), "says it is out of keys: " + Chat());
|
||||
Check.Eq(bot.Get<int>("_forcedLootContainerId"), 0, "the forced-loot flag is cleared");
|
||||
}
|
||||
|
||||
private static void PluginChestPicks()
|
||||
{
|
||||
BaseWorld();
|
||||
var bot = MakeBot("itemtool-picks.json");
|
||||
FakeHost.SelectedItem = 0;
|
||||
bot.Cmd("chest set"); bot.Tick();
|
||||
Check.True(Chat().Contains("select the chest in the world"), "nothing selected: " + Chat());
|
||||
FakeHost.Chat.Clear();
|
||||
FakeHost.SelectedItem = Key;
|
||||
bot.Cmd("chest set"); bot.Tick();
|
||||
Check.True(Chat().Contains("in your pack"), "a pack item is not a chest: " + Chat());
|
||||
FakeHost.Chat.Clear();
|
||||
FakeHost.SelectedItem = Chest;
|
||||
bot.Cmd("chest key"); bot.Tick();
|
||||
Check.True(Chat().Contains("must be in your pack"), "a world object is not a key: " + Chat());
|
||||
FakeHost.Chat.Clear();
|
||||
FakeHost.SelectedItem = WornMote;
|
||||
bot.Cmd("chest key"); bot.Tick();
|
||||
Check.True(Chat().Contains("worn or wielded"), "worn gear is not a key: " + Chat());
|
||||
|
||||
// House storage is never a chest.
|
||||
FakeHost.Chat.Clear();
|
||||
FakeHost.Names[Corpse] = "Storage";
|
||||
FakeHost.Positions[Corpse] = (0x1048002Au, 101f, 99f, 0f);
|
||||
FakeHost.Containers[Corpse] = 0;
|
||||
bot.Cache.OnCreateObject(Corpse); bot.Cache.Tick();
|
||||
FakeHost.SelectedItem = Corpse;
|
||||
bot.Cmd("chest set"); bot.Tick();
|
||||
Check.True(Chat().Contains("house storage"), "storage is refused: " + Chat());
|
||||
|
||||
// Start with nothing picked says what is missing and sends nothing.
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("chest start"); bot.Tick();
|
||||
Check.True(Chat().Contains("pick a chest first"), "start without a chest: " + Chat());
|
||||
Check.Eq(FakeHost.UsesOn.Count + FakeHost.Uses.Count, 0, "nothing sent to the server");
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("chest stop"); bot.Tick();
|
||||
Check.True(Chat().Contains("not running"), "stop when idle: " + Chat());
|
||||
}
|
||||
|
||||
private static void PluginQuickGive()
|
||||
{
|
||||
BaseWorld();
|
||||
var bot = MakeBot("itemtool-give.json");
|
||||
FakeHost.SelectedItem = Mote1;
|
||||
bot.Cmd("giveitem");
|
||||
bot.Tick();
|
||||
FakeHost.SelectedItem = Npc;
|
||||
bot.Cmd("givetarget");
|
||||
bot.Tick();
|
||||
Check.True(Chat().Contains("item = Mana Mote") && Chat().Contains("target = Town Crier"), "picks are confirmed: " + Chat());
|
||||
bot.Cmd("give");
|
||||
bot.Tick();
|
||||
Check.True(Chat().Contains("giving every 'Mana Mote'") && Chat().Contains("to Town Crier"), "the start line names item and target: " + Chat());
|
||||
bot.TickUntil(() => !bot.Get<QuickGive>("_quickGive").Running, 1500);
|
||||
Check.False(bot.Get<QuickGive>("_quickGive").Running, "done");
|
||||
var given = FakeHost.Gives.Select(g => g.Item).ToArray();
|
||||
Check.Eq(string.Join(",", given.OrderBy(x => x).Select(x => x.ToString("X8"))), string.Join(",", new[] { Mote1, Mote2, Mote3 }.Select(x => x.ToString("X8"))), "exactly the three plain Mana Motes: not the worn one, 'Lesser Mana Mote' or the other weenie");
|
||||
Check.True(FakeHost.Gives.All(g => g.Target == Npc && g.Amount == 0), "all to the NPC, whole objects, with AC's give action");
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 0, "no MoveItemExternal");
|
||||
Check.True(Chat().Contains("Quick give stopped: done"), "ends with a result line: " + Chat());
|
||||
}
|
||||
|
||||
private static void PluginGiveTrust()
|
||||
{
|
||||
BaseWorld();
|
||||
var bot = MakeBot("itemtool-trust.json");
|
||||
FakeHost.SelectedItem = Mote1; bot.Cmd("giveitem"); bot.Tick();
|
||||
FakeHost.SelectedItem = Npc; bot.Cmd("givetarget"); bot.Tick();
|
||||
FakeHost.Chat.Clear();
|
||||
|
||||
// A meta's /ra line.
|
||||
bot.Call("HandleRaCommand", "/ra itemtool give");
|
||||
bot.Tick();
|
||||
Check.Eq(FakeHost.Gives.Count, 0, "a meta line gives nothing");
|
||||
Check.True(Chat().Contains("only from the Item Tool panel or a command you type yourself"), "and says why: " + Chat());
|
||||
Check.False(bot.Get<QuickGive>("_quickGive").Running, "not running");
|
||||
|
||||
// A script's SubmitCommand.
|
||||
FakeHost.Chat.Clear();
|
||||
bot.P.ScriptSubmitCommand("/ra itemtool give");
|
||||
bot.Tick();
|
||||
Check.Eq(FakeHost.Gives.Count, 0, "a script line gives nothing");
|
||||
Check.False(bot.Get<QuickGive>("_quickGive").Running, "not running");
|
||||
|
||||
// A typed line (the chat bar): runs.
|
||||
int eat = 0;
|
||||
bot.P.OnChatBarEnter("/ra itemtool give", ref eat);
|
||||
bot.Tick();
|
||||
Check.Eq(eat, 1, "the line is eaten");
|
||||
Check.True(bot.Get<QuickGive>("_quickGive").Running, "a typed line starts it");
|
||||
|
||||
// Stop from a meta works.
|
||||
bot.Call("HandleRaCommand", "/ra itemtool givestop");
|
||||
bot.Tick();
|
||||
Check.False(bot.Get<QuickGive>("_quickGive").Running, "a meta can stop it");
|
||||
// The panel's button.
|
||||
FakeHost.Gives.Clear();
|
||||
bot.Cmd("give");
|
||||
bot.TickUntil(() => FakeHost.Gives.Count > 0, 100);
|
||||
Check.True(FakeHost.Gives.Count > 0, "the panel's button starts it");
|
||||
bot.Cmd("stop"); bot.Tick();
|
||||
Check.False(bot.Get<QuickGive>("_quickGive").Running, "/ra itemtool stop ends it");
|
||||
}
|
||||
|
||||
private static void PluginGiveTargets()
|
||||
{
|
||||
BaseWorld();
|
||||
var bot = MakeBot("itemtool-targets.json");
|
||||
FakeHost.SelectedItem = Monster; bot.Cmd("givetarget"); bot.Tick();
|
||||
Check.True(Chat().Contains("player or an NPC"), "a monster is refused: " + Chat());
|
||||
FakeHost.Chat.Clear();
|
||||
FakeHost.SelectedItem = Mote2; bot.Cmd("givetarget"); bot.Tick();
|
||||
Check.True(Chat().Contains("in your pack"), "a pack item is refused: " + Chat());
|
||||
FakeHost.Chat.Clear();
|
||||
FakeHost.SelectedItem = Player; bot.Cmd("givetarget"); bot.Tick();
|
||||
Check.True(Chat().Contains("that is you"), "you are refused: " + Chat());
|
||||
FakeHost.Chat.Clear();
|
||||
FakeHost.SelectedItem = Bystander; bot.Cmd("givetarget"); bot.Tick();
|
||||
Check.True(Chat().Contains("target = PLAYER Some Player"), "a player is allowed and shown as one: " + Chat());
|
||||
FakeHost.SelectedItem = Mote1; bot.Cmd("giveitem"); bot.Tick();
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("give"); bot.Tick();
|
||||
Check.True(Chat().Contains("giving every 'Mana Mote'") && Chat().Contains("to Some Player"), "the start line names the player: " + Chat());
|
||||
bot.Cmd("stop"); bot.Tick();
|
||||
}
|
||||
}
|
||||
|
|
@ -42,6 +42,7 @@ internal static class LootClaimMismatchTests
|
|||
r.Add("loot claim (R-20261031-203155-cea0): Boost Nav Priority with no route: no loot work, never in Looting; looted once the flag is off", BoostNavNoRouteLoots);
|
||||
r.Add("loot claim (R-20261031-203155-cea0): Boost Nav Priority with a route, then none: nav has the tick, nothing claimed either way", BoostNavWithRouteYields);
|
||||
r.Add("loot claim (R-20261031-203155-cea0): Looting with nothing claimed is logged with the reason after 3 s, then throttled", LootStallLogged);
|
||||
r.Add("boost nav (R-20261102-041824-3f7c): a corpse it passes by is said once in chat; nothing claimed; looted once the flag is off", BoostNavCorpseNotice);
|
||||
}
|
||||
|
||||
// ── Clock and world ───────────────────────────────────────────────────────
|
||||
|
|
@ -288,4 +289,33 @@ internal static class LootClaimMismatchTests
|
|||
Check.Eq(bot.Claimed, unchecked((int)Corpse), "once the halt ends the corpse is claimed");
|
||||
Check.True(Logged("the Looting stall is over"), "and the end of the stall is logged");
|
||||
});
|
||||
|
||||
// ── 5. Boost Nav Priority says it skipped the corpse (owner, 2026-11-02) ───
|
||||
|
||||
private static void BoostNavCorpseNotice() => Clocked(() =>
|
||||
{
|
||||
World();
|
||||
var bot = RescuedCorpse();
|
||||
bot.S.BoostNavPriority = true; // NavLootPrio turned it on; no route, no monster
|
||||
int Notices() => FakeHost.Chat.Count(c => c == RynthAiPlugin.BoostNavNotice);
|
||||
void Note() => bot.Call("NoteBoostNavSkip", bot.S, false);
|
||||
|
||||
for (int i = 0; i < 200; i++) // 5 s of ticks, the notice looked at after each decision
|
||||
{
|
||||
Check.True(bot.Tick() != BotActivity.Looting, "never in Looting");
|
||||
Note();
|
||||
}
|
||||
Check.Eq(Notices(), 1, "the passed-by corpse is said once in chat");
|
||||
Check.True(Logged(RynthAiPlugin.BoostNavNotice + " (skipped a corpse)"), "and in the log, with what was skipped");
|
||||
Check.Eq(bot.Claimed, 0, "nothing claimed");
|
||||
Check.False(FakeHost.Uses.Contains(Corpse), "nothing opened");
|
||||
|
||||
bot.S.BoostNavPriority = false;
|
||||
Note();
|
||||
bot.Tick();
|
||||
Check.Eq(bot.Claimed, unchecked((int)Corpse), "flag off: the corpse is claimed");
|
||||
LootToTheEnd(bot);
|
||||
Check.True(bot.Completed, "and looted to the end");
|
||||
Check.Eq(Notices(), 1, "nothing more said");
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,6 +57,13 @@ internal static class NavEngineTests
|
|||
r.Add("nav engine: a hold is checked again every 3 s, so a wrong answer doesn't hold for good", AreaRecheck);
|
||||
r.Add("nav engine: at the last waypoint before the area change it walks on through for 6 s", AreaGraceWalk);
|
||||
r.Add("nav engine: with recovery off the area is never checked", AreaRecoveryOff);
|
||||
r.Add("nav area after a portal: a later waypoint in this area (a recall cast here, the loop's start) is carried on from", AreaCarryOnRecallHere);
|
||||
r.Add("nav area after a portal: a route that walks into the dungeon carries on at its first waypoint inside", AreaCarryOnIntoDungeon);
|
||||
r.Add("nav area after a portal: a Linear route looks to its end and back, and turns round for a point behind", AreaCarryOnLinearBack);
|
||||
r.Add("nav area: at the route's own way out it still walks through, it doesn't go back to an earlier point here", AreaBoundaryNotCarried);
|
||||
r.Add("nav area: nothing of the route here, in a dungeon: says once to load a route or press Patrol, offers Patrol", AreaNoneHereDungeon);
|
||||
r.Add("nav area: nothing of the route here, on the landscape: says to load a route for here, no Patrol", AreaNoneHereLandscape);
|
||||
r.Add("nav area: loading the route again over a hold says so again; a route for here (the Patrol) runs at once", AreaReloadAndPatrol);
|
||||
r.Add("nav area: the decision (same dungeon, other dungeon, landscape, off the map)", ClassifyArea);
|
||||
r.Add("nav recovery: a waypoint behind a wall is in the room whose floor holds it, not the nearest centre", ContainingCellByFloor);
|
||||
|
||||
|
|
@ -114,6 +121,9 @@ internal static class NavEngineTests
|
|||
private sealed class FakePlanner : INavRecoveryPlanner
|
||||
{
|
||||
public NavAreaCheck Area = NavAreaCheck.Match;
|
||||
/// <summary>Per-point answer (nav coordinates); used instead of <see cref="Area"/> when set.</summary>
|
||||
public Func<double, double, NavAreaCheck>? AreaAt;
|
||||
public string RouteArea = "dungeon 0x01D9", PlayerArea = "on the landscape";
|
||||
public int AreaCalls;
|
||||
public bool GivePlan;
|
||||
/// <summary>Per-target walk length (yd); null = no path. Used instead of GivePlan when set.</summary>
|
||||
|
|
@ -134,10 +144,11 @@ internal static class NavEngineTests
|
|||
public NavAreaCheck CheckArea(uint playerCell, double tNs, double tEw, out string routeArea, out string playerArea)
|
||||
{
|
||||
AreaCalls++;
|
||||
bool mis = Area == NavAreaCheck.Mismatch;
|
||||
routeArea = mis ? "dungeon 0x01D9" : string.Empty;
|
||||
playerArea = mis ? "on the landscape" : string.Empty;
|
||||
return Area;
|
||||
var a = AreaAt != null ? AreaAt(tNs, tEw) : Area;
|
||||
bool mis = a == NavAreaCheck.Mismatch;
|
||||
routeArea = mis ? RouteArea : string.Empty;
|
||||
playerArea = mis ? PlayerArea : string.Empty;
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -748,7 +759,8 @@ internal static class NavEngineTests
|
|||
|
||||
nav.Run(12);
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 1, "still one chat line after 12 s");
|
||||
Check.True(p.AreaCalls >= 4 && p.AreaCalls <= 5, $"asked again every 3 s while held ({p.AreaCalls} calls in 12 s)");
|
||||
// 1 for the waypoint, 1 for the one look along the route for a waypoint here (not repeated), 4 rechecks.
|
||||
Check.True(p.AreaCalls >= 5 && p.AreaCalls <= 6, $"asked again every 3 s while held ({p.AreaCalls} calls in 12 s)");
|
||||
Check.Eq(p.PlanTargets.Count, 0, "no detour is tried");
|
||||
Check.Eq(FakeHost.Jumps, 0, "no escape jumps");
|
||||
Check.Eq(nav.Idx, 1, "the waypoint is kept");
|
||||
|
|
@ -834,6 +846,129 @@ internal static class NavEngineTests
|
|||
Check.True(FakeHost.AutoRun, "walks toward the waypoint");
|
||||
}
|
||||
|
||||
// ── Different area after a portal / a load (2026-11-01) ──────────────────
|
||||
|
||||
/// <summary>A planner that says Match where <paramref name="here"/> holds (yards north, east of the origin), Mismatch elsewhere.</summary>
|
||||
private static FakePlanner AreaWhere(Func<double, double, bool> here, string routeArea = "the landscape", string playerArea = "in dungeon 0x5756")
|
||||
=> new() { AreaAt = (ns, ew) => here((ns - NS0) * 240.0, (ew - EW0) * 240.0) ? NavAreaCheck.Match : NavAreaCheck.Mismatch,
|
||||
RouteArea = routeArea, PlayerArea = playerArea };
|
||||
|
||||
/// <summary>Puts the fake character in an indoor cell of the landblock it stands in.</summary>
|
||||
private static void Indoors() => FakeHost.PlayerPose = ((FakeHost.PlayerPose.Cell & 0xFFFF0000u) | 0x0124, FakeHost.PlayerPose.X, FakeHost.PlayerPose.Y, FakeHost.PlayerPose.Z);
|
||||
|
||||
private static void AreaCarryOnRecallHere()
|
||||
{
|
||||
// The logged case: a Circular route that starts with a recall cast in the home dungeon, then walks
|
||||
// the landscape to a portal. Loaded (or the macro started) in the dungeon, nav was on [2] out on the
|
||||
// landscape (the "nearest" point by map distance) and held for good.
|
||||
FakeHost.Reset(); At(-500, -500); Indoors();
|
||||
var recall = Pt(-500, -500, T.Recall); recall.SpellId = 4198;
|
||||
var route = Route(RT.Circular, recall, Pt(100, 0), Pt(110, 0), Pt(120, 0));
|
||||
var p = AreaWhere((n, e) => n < -400);
|
||||
var nav = new Nav(route, idx: 2, planner: p);
|
||||
nav.Tick();
|
||||
Check.Eq(nav.Idx, 0, "carries on from [0], the recall cast here (the loop goes on to it)");
|
||||
Check.True(FakeHost.Chat.Exists(c => c.Contains("carrying on from [0]") && c.Contains("Recall")), "says so in chat, naming the step");
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 0, "no hold line");
|
||||
Check.False(nav.S.NavIsStuck, "not flagged stuck");
|
||||
Check.Eq(nav.Recovery, "none", "no area hold");
|
||||
nav.Run(1.0);
|
||||
Check.Eq(nav.E.GetStateSnapshot().PortalState, "FiringAction", "and casts the recall");
|
||||
}
|
||||
|
||||
private static void AreaCarryOnIntoDungeon()
|
||||
{
|
||||
// A Once route: landscape [0]-[1], the portal at [2] (used out there), then the dungeon [3]-[4].
|
||||
// The character went through (or was put) inside with nav still on [1]: on to [3], not a hold.
|
||||
FakeHost.Reset(); At(-300, 0); Indoors();
|
||||
var portal = Pt(20, 0, T.PortalNPC); portal.TargetName = "Abandoned Experiment";
|
||||
var route = Route(RT.Once, Pt(0, 0), Pt(10, 0), portal, Pt(-290, 0), Pt(-280, 0));
|
||||
var nav = new Nav(route, idx: 1, planner: AreaWhere((n, e) => n < -200));
|
||||
nav.Tick();
|
||||
Check.Eq(nav.Idx, 3, "carries on from [3], the first waypoint inside (the portal step out there is passed)");
|
||||
nav.Run(0.5);
|
||||
Check.True(FakeHost.AutoRun, "walks toward [3]");
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 0, "never held");
|
||||
|
||||
// Nothing is walked out of order on a Once route: points before the current one are never picked.
|
||||
FakeHost.Reset(); At(-330, 0); Indoors(); // 40 yd from [0]: not standing at the way out
|
||||
var back = new Nav(Route(RT.Once, Pt(-290, 0), Pt(10, 0), Pt(20, 0)), idx: 1, planner: AreaWhere((n, e) => n < -200));
|
||||
back.Tick();
|
||||
Check.Eq(back.Idx, 1, "a Once route never goes back to [0]");
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("nothing ahead on it is here")), 1, "it holds and says nothing ahead is here");
|
||||
}
|
||||
|
||||
private static void AreaCarryOnLinearBack()
|
||||
{
|
||||
FakeHost.Reset(); At(-330, 0); Indoors(); // 40 yd from [0]: not standing at the way out
|
||||
var nav = new Nav(Route(RT.Linear, Pt(-290, 0), Pt(10, 0), Pt(20, 0)), idx: 1, planner: AreaWhere((n, e) => n < -200));
|
||||
nav.Tick();
|
||||
Check.Eq(nav.Idx, 0, "nothing ahead to the end: back from it to [0]");
|
||||
Check.Eq(nav.E.GetStateSnapshot().LinearDir, -1, "reached heading back");
|
||||
}
|
||||
|
||||
private static void AreaBoundaryNotCarried()
|
||||
{
|
||||
// The route walks into a portal at [1]; [0] is in this area too. Standing at [1] (the way out), it
|
||||
// walks on through as before rather than turning back to [0].
|
||||
FakeHost.Reset(); At(0.5, 0);
|
||||
var nav = new Nav(Route(RT.Circular, Pt(-20, 0), Pt(0, 0), Pt(900, 0)), idx: 2, planner: AreaWhere((n, e) => n < 100, "dungeon 0x01D9", "on the landscape"));
|
||||
nav.Tick();
|
||||
Check.Eq(nav.Idx, 2, "keeps the waypoint past the portal");
|
||||
Check.True(nav.S.NavStatusLine.Contains("walking on through"), "the grace walk");
|
||||
Check.False(FakeHost.Chat.Exists(c => c.Contains("carrying on")), "no carry-on");
|
||||
}
|
||||
|
||||
private static void AreaNoneHereDungeon()
|
||||
{
|
||||
FakeHost.Reset(); At(-500, -500); Indoors();
|
||||
var nav = new Nav(Route(RT.Circular, Pt(100, 0), Pt(110, 0), Pt(120, 0)), idx: 1, planner: AreaWhere((n, e) => false));
|
||||
nav.Tick();
|
||||
Check.False(FakeHost.AutoRun, "held");
|
||||
var lines = FakeHost.Chat.Where(c => c.Contains("different area")).ToList();
|
||||
Check.Eq(lines.Count, 1, "one chat line");
|
||||
Check.True(lines.Count == 1 && lines[0].Contains("nothing ahead on it is here") && lines[0].Contains("press Patrol"),
|
||||
$"it says what to do ({(lines.Count > 0 ? lines[0] : "")})");
|
||||
Check.True(nav.S.NavStatusLine.Contains("press Patrol") && nav.S.NavStatusLine.Contains("the landscape"), $"status says it too ({nav.S.NavStatusLine})");
|
||||
Check.True(nav.S.NavAreaHoldOffersPatrol, "the nav window offers the Patrol button");
|
||||
nav.Run(12);
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 1, "still one line after 12 s of rechecks");
|
||||
Check.Eq(nav.Idx, 1, "the waypoint is kept");
|
||||
}
|
||||
|
||||
private static void AreaNoneHereLandscape()
|
||||
{
|
||||
FakeHost.Reset(); At(30, 0);
|
||||
var nav = new Nav(Route(RT.Circular, Pt(0, 0), Pt(50, 0)), idx: 1, planner: new FakePlanner { Area = NavAreaCheck.Mismatch });
|
||||
nav.Tick();
|
||||
var line = FakeHost.Chat.FirstOrDefault(c => c.Contains("different area")) ?? "";
|
||||
Check.True(line.Contains("load a route for here") && !line.Contains("Patrol"), $"load a route, no Patrol on the landscape ({line})");
|
||||
Check.False(nav.S.NavAreaHoldOffersPatrol, "no Patrol button");
|
||||
}
|
||||
|
||||
private static void AreaReloadAndPatrol()
|
||||
{
|
||||
FakeHost.Reset(); At(-500, -500); Indoors();
|
||||
var p = AreaWhere((n, e) => n < -400);
|
||||
var landscape = Route(RT.Circular, Pt(100, 0), Pt(110, 0));
|
||||
var nav = new Nav(landscape, idx: 1, planner: p);
|
||||
nav.Tick();
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 1, "held, said once");
|
||||
|
||||
// The player loads the same nav file again: a new route object, the same hold - and it says so again.
|
||||
nav.S.CurrentRoute = Route(RT.Circular, Pt(100, 0), Pt(110, 0));
|
||||
nav.Run(0.3);
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 2, "the load is answered: still nothing here, said again");
|
||||
|
||||
// Patrol (or a route for this dungeon) replaces it: walks at once, the hold and its button are gone.
|
||||
nav.S.CurrentRoute = Route(RT.Circular, Pt(-490, -500), Pt(-480, -500));
|
||||
nav.S.ActiveNavIndex = 0;
|
||||
nav.Run(0.5);
|
||||
Check.True(FakeHost.AutoRun, "walking the route for here");
|
||||
Check.Eq(nav.Recovery, "none", "no hold");
|
||||
Check.False(nav.S.NavAreaHoldOffersPatrol, "no Patrol button any more");
|
||||
}
|
||||
|
||||
private static void ContainingCellByFloor()
|
||||
{
|
||||
static RynthCore.Plugin.RynthAi.Raycasting.Vector3[] Sq(float x0, float y0, float x1, float y1, float z) => new[]
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ internal static class OffhandTests
|
|||
private const uint Wcid = 434343;
|
||||
private const uint Sword = 0x80000401, Dagger = 0x80000402, Great = 0x80000403, Shield = 0x80000404,
|
||||
Round = 0x80000405, Bow = 0x80000406, Arrows = 0x80000407, Wand = 0x80000408;
|
||||
// Two matched pairs of one-handed weapons for dual wield (an element each).
|
||||
private const uint ColdA = 0x80000411, ColdB = 0x80000412, FireA = 0x80000413, FireB = 0x80000414;
|
||||
private const uint Pack = 0x80000501;
|
||||
private const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000, MissileSlot = 0x00400000,
|
||||
AmmoSlot = 0x00800000, HeldSlot = 0x01000000, TwoHandedSlot = 0x02000000;
|
||||
|
|
@ -37,6 +39,10 @@ internal static class OffhandTests
|
|||
r.Add("swap speed: a weapon in hand -> one use of the wand (the client swaps); the pack move only as the fallback", CasterDirectSwap);
|
||||
r.Add("swap speed: the gate lets the next step go once the server is done, else after 3 s", SwapGateSettles);
|
||||
r.Add("offhand: dual wield with the Dual Wield skill", DualWield);
|
||||
r.Add("offhand: dual wield pairs, the element changes -> both hands swap to the pair", DualWieldPairSwap);
|
||||
r.Add("offhand: dual wield pairs, the off hand already right stays (no loop)", DualWieldPairStays);
|
||||
r.Add("offhand: dual wield pairs, the wanted weapon in the off hand -> its partner goes in the main hand", DualWieldPairPartnerToMain);
|
||||
r.Add("offhand: element pairs leave shield users and single weapons as they were", PairsLeaveShieldAndSingle);
|
||||
r.Add("offhand: the weapon in hand is the main hand's when the wielded slot reads 0 (the weenie's wielder record)", InHandFromWielderInfo);
|
||||
r.Add("weapons: a weapon refused 'skill too low' is left out of the choice (the off hand stays)", SkillTooLowLeftOut);
|
||||
r.Add("offhand: two weapons wielded and no slot read says which: the one RynthAi put in the off hand is the off hand's", OffhandRemembered);
|
||||
|
|
@ -146,7 +152,7 @@ internal static class OffhandTests
|
|||
private readonly FieldInfo _lastEquip = typeof(CombatManager).GetField("_lastEquipTime", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
|
||||
public Rig(bool dualWieldSkill = false, bool shieldOn = false, bool wieldCalls = true, bool wielderInfo = false, bool weenieErrors = false,
|
||||
bool contents = false, bool tracker = false)
|
||||
bool contents = false, bool tracker = false, bool pairs = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.EquippedCalls = tracker; // v87 GetWieldedItems (answering FakeHost.Equipped)
|
||||
|
|
@ -166,6 +172,13 @@ internal static class OffhandTests
|
|||
Item(Arrows, "Arrow", 0x100, AmmoSlot);
|
||||
FakeHost.Ints[(Arrows, 50)] = 1; FakeHost.Ints[(Arrows, 12)] = 100; FakeHost.Ints[(Arrows, 11)] = 250;
|
||||
Item(Wand, "Wand", 0x8000, HeldSlot);
|
||||
if (pairs)
|
||||
{
|
||||
Item(ColdA, "Cold Sword", 0x1, MeleeSlot, combatUse: 1);
|
||||
Item(ColdB, "Cold Dagger", 0x1, MeleeSlot, combatUse: 1);
|
||||
Item(FireA, "Fire Sword", 0x1, MeleeSlot, combatUse: 1);
|
||||
Item(FireB, "Fire Dagger", 0x1, MeleeSlot, combatUse: 1);
|
||||
}
|
||||
Wield(Sword, MeleeSlot);
|
||||
if (shieldOn) Wield(Shield, ShieldSlot);
|
||||
FakeHost.Wcids[Monster] = Wcid;
|
||||
|
|
@ -174,7 +187,9 @@ internal static class OffhandTests
|
|||
// ownership read (GetObjectOwnershipInfo: the item's own container field).
|
||||
if (contents) { FakeHost.Names[Pack] = "Pack"; FakeHost.ItemTypes[Pack] = 0x200; FakeHost.Containers[Pack] = Player; }
|
||||
var host = FakeHost.Create(wielderInfo ? Player : 0);
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { Sword, Dagger, Great, Shield, Round, Bow, Arrows, Wand });
|
||||
var ids = new List<uint> { Sword, Dagger, Great, Shield, Round, Bow, Arrows, Wand };
|
||||
if (pairs) ids.AddRange(new[] { ColdA, ColdB, FireA, FireB });
|
||||
var cache = FakeHost.MakeCache(host, Player, ids.ToArray());
|
||||
C = new CombatManager(host, S, cache);
|
||||
C.SetPlayerId(Player);
|
||||
C.SetDamageStores(null, Store);
|
||||
|
|
@ -197,6 +212,17 @@ internal static class OffhandTests
|
|||
Action = i == Shield || i == Round ? WeaponList.ShieldAction : "Weapon",
|
||||
}).ToList();
|
||||
|
||||
/// <summary>The Items list with an element set on each entry.</summary>
|
||||
public void ListWith(params (uint Id, string Element)[] items)
|
||||
{
|
||||
List(items.Select(i => i.Id).ToArray());
|
||||
foreach (var (id, elem) in items) S.ItemRules.First(r => r.Id == unchecked((int)id)).Element = elem;
|
||||
}
|
||||
|
||||
/// <summary>This monster's Monsters rule fights with <paramref name="element"/> (its DamageType).</summary>
|
||||
public void Element(string element, int offhandId = 0) =>
|
||||
S.MonsterRules = new List<MonsterRule> { new() { Name = "Default" }, new() { Name = "Test Dummy", DamageType = element, OffhandId = offhandId } };
|
||||
|
||||
public void Rule(int offhandId) =>
|
||||
S.MonsterRules = new List<MonsterRule> { new() { Name = "Default" }, new() { Name = "Test Dummy", OffhandId = offhandId } };
|
||||
|
||||
|
|
@ -462,6 +488,174 @@ internal static class OffhandTests
|
|||
Check.Eq(rig2.ShieldWields(Dagger), 1, "Monsters rule 'Offhand weapon': the dagger");
|
||||
}
|
||||
|
||||
// ── Dual wield pairs ──────────────────────────────────────────────────────
|
||||
|
||||
// 2026-11-02 report: a dual-wield character with a matched pair per element (a Cold pair, a
|
||||
// Fire pair). When the element changed only the main hand swapped; the off hand kept whatever
|
||||
// it held, because the off-hand pick was "the one already in the off hand, else list order"
|
||||
// and never looked at the element.
|
||||
private static (uint, string)[] Pairs => new[] { (ColdA, "Cold"), (ColdB, "Cold"), (FireA, "Fire"), (FireB, "Fire") };
|
||||
|
||||
private static Rig PairRig(uint main, uint off)
|
||||
{
|
||||
var rig = new Rig(dualWieldSkill: true, pairs: true);
|
||||
Rig.Unwield(Sword);
|
||||
Rig.Wield(main, MeleeSlot);
|
||||
Rig.Wield(off, ShieldSlot);
|
||||
rig.InHand = unchecked((int)main);
|
||||
rig.S.PreferDualWield = true;
|
||||
rig.ListWith(Pairs);
|
||||
return rig;
|
||||
}
|
||||
|
||||
private static void DualWieldPairSwap()
|
||||
{
|
||||
// The pure plan: the main weapon's partner (same element) first, whatever is in the off hand.
|
||||
var coldA = new OffhandCandidate(30, "Cold Sword", false, false, "Cold");
|
||||
var coldB = new OffhandCandidate(31, "Cold Dagger", false, false, "Cold");
|
||||
var fireA = new OffhandCandidate(40, "Fire Sword", false, false, "Fire");
|
||||
var fireB = new OffhandCandidate(41, "Fire Dagger", false, true, "Fire"); // in the off hand
|
||||
var pairs = new[] { coldA, coldB, fireA, fireB };
|
||||
OffhandPlan P(OffhandMode m, int main, string elem, bool pref = true, int pick = 0, bool isDefault = false)
|
||||
=> OffhandPlanner.Choose(m, MainHandKind.OneHandedMelee, main, pairs, true, pref, true, pick, "pick", elem, isDefault);
|
||||
Check.Eq(P(OffhandMode.Auto, 30, "Cold").Id, 31, "Auto, dual wield preferred, Cold main: the Cold partner, not the Fire one in the off hand");
|
||||
Check.Eq(P(OffhandMode.Weapon, 30, "Cold").Id, 31, "Offhand weapon, Cold main: the Cold partner");
|
||||
Check.True(P(OffhandMode.Weapon, 30, "Cold").Source.Contains("Cold"), "the log says why: " + P(OffhandMode.Weapon, 30, "Cold").Source);
|
||||
Check.Eq(P(OffhandMode.Weapon, 40, "Fire").Id, 41, "Fire main, the Fire partner already in the off hand: it stays");
|
||||
Check.Eq(P(OffhandMode.Weapon, 30, "").Id, 41, "main element not known: the one in the off hand stays, as before");
|
||||
Check.Eq(P(OffhandMode.Auto, 30, "Cold", pref: false).Id, 0, "Auto, dual wield not preferred, no shield: nothing, as before");
|
||||
Check.Eq(P(OffhandMode.Weapon, 30, "Cold", pick: 41).Id, 41, "a pick for this monster wins over the partner");
|
||||
Check.Eq(P(OffhandMode.Weapon, 30, "Cold", pick: 41, isDefault: true).Id, 31, "the Default row's pick gives way to the main weapon's partner");
|
||||
Check.Eq(P(OffhandMode.Weapon, 30, "Cold", pick: 31, isDefault: true).Id, 31, "the Default row's pick that is the partner: kept");
|
||||
Check.Eq(P(OffhandMode.Weapon, 31, "Cold", pick: 31, isDefault: true).Id, 30, "the Default row's pick is the main weapon: the other of its pair");
|
||||
|
||||
// In combat: the Fire pair in hand, the monster wants Cold.
|
||||
var rig = PairRig(FireA, FireB);
|
||||
rig.Element("Cold");
|
||||
Check.False(rig.Tick(), "Cold wanted: the main hand swaps");
|
||||
Check.Eq(FakeHost.Uses.LastOrDefault(), ColdA, "the main hand: the Cold sword");
|
||||
rig.Landed(ColdA, FireA, MeleeSlot);
|
||||
Check.False(rig.Tick(), "Cold sword in hand: the off hand goes next");
|
||||
Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0] == (FireB, Pack, 1), "the Fire dagger into the pack first");
|
||||
Rig.Unwield(FireB);
|
||||
Check.False(rig.Tick(), "off hand empty: the partner goes on");
|
||||
Check.Eq(rig.ShieldWields(ColdB), 1, "WieldItem(Cold dagger, Shield slot)");
|
||||
Rig.Wield(ColdB, ShieldSlot);
|
||||
Check.True(rig.Tick(), "the Cold pair in both hands: ready");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("off hand for") && l.Contains("Cold Dagger")), "the off-hand choice is logged");
|
||||
|
||||
// And back to Fire (another fight): both hands again.
|
||||
rig.C.SwapTracker.MinDwellMs = 0;
|
||||
rig.C.OffhandTracker.MinDwellMs = 0;
|
||||
rig.Element("Fire");
|
||||
rig.Tick();
|
||||
Check.Eq(FakeHost.Uses.LastOrDefault(), FireA, "Fire wanted: the Fire sword");
|
||||
rig.Landed(FireA, ColdA, MeleeSlot);
|
||||
rig.Tick();
|
||||
Check.True(FakeHost.Moves.Any(m => m.Id == ColdB), "the Cold dagger comes off");
|
||||
Rig.Unwield(ColdB);
|
||||
rig.Tick();
|
||||
Check.Eq(rig.ShieldWields(FireB), 1, "the Fire dagger goes on");
|
||||
Rig.Wield(FireB, ShieldSlot);
|
||||
Check.True(rig.Tick(), "the Fire pair: ready");
|
||||
}
|
||||
|
||||
private static void DualWieldPairStays()
|
||||
{
|
||||
var rig = PairRig(ColdA, ColdB);
|
||||
rig.Element("Cold");
|
||||
for (int i = 0; i < 10; i++) Check.True(rig.Tick(), $"the Cold pair for a Cold monster: ready (tick {i + 1})");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "no main-hand wield");
|
||||
Check.Eq(FakeHost.Wields.Count, 0, "no off-hand wield");
|
||||
Check.Eq(FakeHost.Moves.Count, 0, "nothing moved");
|
||||
|
||||
// The pair in hand the other way round (the B weapon in the main hand): still the pair, left alone.
|
||||
var rig2 = PairRig(FireB, FireA);
|
||||
rig2.Element("Fire");
|
||||
for (int i = 0; i < 10; i++) rig2.Tick();
|
||||
Check.True(rig2.Tick(), "the Fire pair, either way round: ready");
|
||||
Check.Eq(FakeHost.Uses.Count + FakeHost.Wields.Count + FakeHost.Moves.Count, 0, "no swap, no loop");
|
||||
|
||||
// After a swap to the pair, ticks on do nothing more (each swap pays a stance change).
|
||||
var rig3 = PairRig(FireA, FireB);
|
||||
rig3.Element("Cold");
|
||||
rig3.Tick();
|
||||
rig3.Landed(ColdA, FireA, MeleeSlot);
|
||||
rig3.Tick();
|
||||
Rig.Unwield(FireB);
|
||||
rig3.Tick();
|
||||
Rig.Wield(ColdB, ShieldSlot);
|
||||
int uses = FakeHost.Uses.Count, wields = FakeHost.Wields.Count, moves = FakeHost.Moves.Count;
|
||||
for (int i = 0; i < 20; i++) Check.True(rig3.Tick(), $"converged: ready (tick {i + 1})");
|
||||
Check.Eq(FakeHost.Uses.Count, uses, "no further main-hand wields");
|
||||
Check.Eq(FakeHost.Wields.Count, wields, "no further off-hand wields");
|
||||
Check.Eq(FakeHost.Moves.Count, moves, "no further moves");
|
||||
}
|
||||
|
||||
private static void DualWieldPairPartnerToMain()
|
||||
{
|
||||
// The Cold sword with the Fire dagger (half a swap, say), the Fire dagger listed first: the
|
||||
// weapon choice wants it, and it already swings in the off hand. Its partner, the Fire sword,
|
||||
// goes in the main hand; the off hand stays. Before, combat fought on with Cold + Fire.
|
||||
var rig = new Rig(dualWieldSkill: true, pairs: true);
|
||||
Rig.Unwield(Sword);
|
||||
Rig.Wield(ColdA, MeleeSlot);
|
||||
Rig.Wield(FireB, ShieldSlot);
|
||||
rig.InHand = unchecked((int)ColdA);
|
||||
rig.S.PreferDualWield = true;
|
||||
rig.ListWith((FireB, "Fire"), (FireA, "Fire"), (ColdA, "Cold"), (ColdB, "Cold"));
|
||||
rig.Element("Fire");
|
||||
Check.Eq(unchecked((uint)rig.C.PlanFor(rig.Target, rig.S.MonsterRules[1]).WeaponId), FireB, "the plan: the Fire dagger (listed first)");
|
||||
Check.False(rig.Tick(), "not ready: the main hand swaps");
|
||||
Check.Eq(FakeHost.Uses.LastOrDefault(), FireA, "the main hand: the Fire dagger's partner, the Fire sword");
|
||||
Check.Eq(FakeHost.Moves.Count, 0, "the Fire dagger isn't moved out of the off hand");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("its partner") && l.Contains("Fire Sword")), "logged");
|
||||
rig.Landed(FireA, ColdA, MeleeSlot);
|
||||
for (int i = 0; i < 5; i++) Check.True(rig.Tick(), $"the Fire pair: ready (tick {i + 1})");
|
||||
Check.Eq(FakeHost.Wields.Count, 0, "the off hand was right: no off-hand wield");
|
||||
Check.Eq(FakeHost.Moves.Count, 0, "nothing moved");
|
||||
}
|
||||
|
||||
private static void PairsLeaveShieldAndSingle()
|
||||
{
|
||||
// A shield user with a Cold and a Fire sword (dual wield skill, not preferred): the shield
|
||||
// stays through element changes; only the main hand swaps.
|
||||
var rig = new Rig(dualWieldSkill: true, shieldOn: true, pairs: true);
|
||||
Rig.Unwield(Sword);
|
||||
Rig.Wield(FireA, MeleeSlot);
|
||||
rig.InHand = unchecked((int)FireA);
|
||||
rig.ListWith((ColdA, "Cold"), (FireA, "Fire"), (Shield, ""));
|
||||
rig.Element("Cold");
|
||||
rig.Tick();
|
||||
Check.Eq(FakeHost.Uses.LastOrDefault(), ColdA, "the main hand: the Cold sword");
|
||||
rig.Landed(ColdA, FireA, MeleeSlot);
|
||||
for (int i = 0; i < 5; i++) Check.True(rig.Tick(), $"Cold sword and shield: ready (tick {i + 1})");
|
||||
Check.Eq(FakeHost.Wields.Count, 0, "the shield stays: no off-hand wield");
|
||||
Check.Eq(FakeHost.Moves.Count, 0, "nothing moved");
|
||||
|
||||
// Offhand Shield with dual wield preferred and a Cold pair listed: still the shield.
|
||||
var rig2 = new Rig(dualWieldSkill: true, shieldOn: true, pairs: true);
|
||||
Rig.Unwield(Sword);
|
||||
Rig.Wield(ColdA, MeleeSlot);
|
||||
rig2.InHand = unchecked((int)ColdA);
|
||||
rig2.S.PreferDualWield = true;
|
||||
rig2.ListWith((ColdA, "Cold"), (ColdB, "Cold"), (Shield, ""));
|
||||
rig2.Element("Cold", OffhandRules.RuleShield);
|
||||
for (int i = 0; i < 5; i++) Check.True(rig2.Tick(), $"Offhand Shield: sword and shield, ready (tick {i + 1})");
|
||||
Check.Eq(FakeHost.Wields.Count + FakeHost.Moves.Count, 0, "the Cold dagger never goes on");
|
||||
|
||||
// One weapon listed: it stays, nothing goes in the off hand.
|
||||
var rig3 = new Rig(dualWieldSkill: true, pairs: true);
|
||||
Rig.Unwield(Sword);
|
||||
Rig.Wield(ColdA, MeleeSlot);
|
||||
rig3.InHand = unchecked((int)ColdA);
|
||||
rig3.S.PreferDualWield = true;
|
||||
rig3.ListWith((ColdA, "Cold"));
|
||||
rig3.Element("Fire");
|
||||
for (int i = 0; i < 5; i++) Check.True(rig3.Tick(), $"a single weapon: ready (tick {i + 1})");
|
||||
Check.Eq(FakeHost.Uses.Count + FakeHost.Wields.Count + FakeHost.Moves.Count, 0, "nothing wielded or moved");
|
||||
}
|
||||
|
||||
// 2026-10-16: Drakkon dual wielding two Hand Wraps; CurrentWieldedLocation read 0, so both
|
||||
// counted as in hand and the later listed one (the off hand's) was taken for the main weapon.
|
||||
private static void InHandFromWielderInfo()
|
||||
|
|
|
|||
358
Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs
Normal file
358
Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs
Normal file
|
|
@ -0,0 +1,358 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Outdoor hunting (2026-10-23): walk from monster to monster around obstacles on RynthNav's map.
|
||||
// The path function here plays RynthNav: by default a straight walk, with per-monster overrides (a
|
||||
// building in the way makes the walk long; a cliff makes it impossible).
|
||||
internal static class OutdoorHuntTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("hunt: the next monster is the shortest walk, not the nearest in a straight line (one behind a building)", ShortestWalk);
|
||||
r.Add("hunt: a higher Priority comes first, whatever the walk", PriorityFirst);
|
||||
r.Add("hunt: no way to a monster (a cliff, water): left out for a while; a walk ending close enough still counts", Unreachable);
|
||||
r.Add("hunt: it stays within Hunt Radius of where it started (0 = anywhere)", Radius);
|
||||
r.Add("hunt: plans again when the monster moves, the walk runs out, or a while passes; not every tick", Replan);
|
||||
r.Add("hunt: nothing in range: it waits where it is (no walk back to the start); Hunt Radius defaults to anywhere", WaitsWhereItIs);
|
||||
r.Add("hunt: /ra hunt range|radius answer and cap; status and stop don't toggle it; panel opens the window", Commands);
|
||||
r.Add("hunt: the target dies: the next one; no pathfinder: it stands", NextAndNoPathfinder);
|
||||
r.Add("hunt: the settings round-trip with the rest (saved, copied, engine payload)", Settings);
|
||||
r.Add("hunt (test 10-23): a monster 12 yd away but a 143 yd walk is too far round; the one being walked to is kept past Hunt Range", FarRound);
|
||||
r.Add("hunt (test 10-23): at a wall with the monster on its far side: no 1 yd walks every half second; left out after NoFightSec", WallBetween);
|
||||
r.Add("hunt: a monster right beside it that combat doesn't take: stands, then leaves it out", RightHere);
|
||||
r.Add("hunt (test 10-23): in a building it walks back out the way it went in (the loops it made cut out)", WayBackOut);
|
||||
r.Add("hunt: in a building with no way in known, or the walks out ending still inside: it waits", IndoorsWaits);
|
||||
}
|
||||
|
||||
private static void WallBetween()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
nav.Walls[(1010, 1000)] = (V(1008.7, 1000), 1.3); // behind a wall: the walk ends 1.3 yd short, on this side
|
||||
var list = Sorted(C(1, 1010, 1000, me), C(2, 1000, 1030, me));
|
||||
var d = h.Tick(T0, me, true, list, nav.Path);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 1, "walks to the nearer one (its walk ends close enough to count)");
|
||||
// At the wall: combat can't see through it, so the hunt is asked again and again.
|
||||
var atWall = V(1008.7, 1000);
|
||||
var walks = 0;
|
||||
for (double t = 3; t < 3 + h.NoFightSec - 0.1; t += 0.25)
|
||||
{
|
||||
d = h.Tick(T0.AddSeconds(t), atWall, true, Sorted(C(1, 1010, 1000, atWall), C(2, 1000, 1030, atWall)), nav.Path);
|
||||
if (d.Act == OutdoorHunt.Act.Walk) walks++;
|
||||
}
|
||||
Check.Eq(walks, 0, "no 1 yd walks at the wall");
|
||||
Check.Eq(h.TargetId, 1, "still its target while combat has the time to take it");
|
||||
h.ClearNotes();
|
||||
d = h.Tick(T0.AddSeconds(3.5 + h.NoFightSec), atWall, true, Sorted(C(1, 1010, 1000, atWall), C(2, 1000, 1030, atWall)), nav.Path);
|
||||
Check.True(h.IsSkipped(1, T0.AddSeconds(30)), "left out after NoFightSec");
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 2, $"and on to the other one at once: {d.Act} {d.TargetId}");
|
||||
var notes = string.Join(" | ", h.PendingNotes);
|
||||
Check.True(h.PendingNotes.Count == 2 && h.PendingNotes[0].Contains("wall") && h.PendingNotes[1].StartsWith("next: 'Monster 2'"),
|
||||
"both logged, the why first: " + notes);
|
||||
}
|
||||
|
||||
private static void RightHere()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
var d = h.Tick(T0, me, true, Sorted(C(1, 1001.5, 1000, me)), nav.Path);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Idle && d.TargetId == 1, $"1.5 yd away: no walk, it stands with it as the target ({d.Act} {d.TargetId})");
|
||||
d = h.Tick(T0.AddSeconds(1), me, true, Sorted(C(1, 1001.5, 1000, me)), nav.Path);
|
||||
Check.True(d.Act != OutdoorHunt.Act.Walk && !h.IsSkipped(1, T0.AddSeconds(1)), "a second: still waiting for combat");
|
||||
h.Tick(T0.AddSeconds(h.NoFightSec + 0.6), me, true, Sorted(C(1, 1001.5, 1000, me)), nav.Path);
|
||||
Check.True(h.IsSkipped(1, T0.AddSeconds(h.NoFightSec + 1)), "combat never took it: left out");
|
||||
}
|
||||
|
||||
private static void WayBackOut()
|
||||
{
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, V(990, 1000));
|
||||
h.Track(V(1000, 1000), indoors: false); // the last spot outdoors, at the doorway
|
||||
for (int x = 1001; x <= 1010; x++) h.Track(V(x, 1000), indoors: true);
|
||||
h.Track(V(1010, 1002), indoors: true); // a fight took it up a side room...
|
||||
h.Track(V(1010, 1004), indoors: true);
|
||||
h.Track(V(1010, 1000.5), indoors: true); // ...and back
|
||||
Check.Eq(h.WayInSteps, 6, "the side room is cut out of the way in (the door and 5 steps)");
|
||||
var me = V(1010, 1000.5);
|
||||
var d = h.Indoors(T0, me, routeDone: true);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "walks out");
|
||||
var want = new[] { V(1008, 1000), V(1006, 1000), V(1004, 1000), V(1002, 1000), V(1000, 1000), V(1000 - h.OutPastYd, 1000) };
|
||||
Check.True(d.Corners!.SequenceEqual(want), "the way in backwards, then out past the doorway: " + string.Join(" ", d.Corners!.Select(c => $"{c.X:0.#},{c.Y:0.#}")));
|
||||
Check.True(h.WalkingOut && h.Note.Contains("back out"), "walking out: " + h.Note);
|
||||
Check.Eq(h.Indoors(T0.AddSeconds(2), V(1005, 1000), routeDone: false).Act, OutdoorHunt.Act.None, "on the way: keeps walking");
|
||||
h.Track(V(996, 1000), indoors: false);
|
||||
Check.False(h.WalkingOut, "outdoors again: done");
|
||||
Check.Eq(h.WayInSteps, 0, "and the way in forgotten");
|
||||
}
|
||||
|
||||
private static void IndoorsWaits()
|
||||
{
|
||||
var never = new OutdoorHunt();
|
||||
never.Start(T0, V(1000, 1000));
|
||||
never.Track(V(1005, 1000), indoors: true); // never seen outdoors (a reload inside, say)
|
||||
var d = never.Indoors(T0, V(1005, 1000), routeDone: true);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Idle, "no way in known: waits");
|
||||
Check.True(never.Note.Contains("no way out known"), never.Note);
|
||||
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, V(990, 1000));
|
||||
h.Track(V(1000, 1000), indoors: false);
|
||||
h.Track(V(1003, 1000), indoors: true);
|
||||
var t = T0;
|
||||
for (int i = 0; i < h.OutTriesMax; i++)
|
||||
{
|
||||
d = h.Indoors(t, V(1003, 1000), routeDone: true);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, $"walk out {i + 1}");
|
||||
t = t.AddSeconds(5);
|
||||
// It got to the end of the walk and the cell still says indoors.
|
||||
d = h.Indoors(t, d.Corners![^1], routeDone: true);
|
||||
if (i < h.OutTriesMax - 1) Check.Eq(d.Act, OutdoorHunt.Act.Walk, $"ended still inside: again ({i + 2})");
|
||||
t = t.AddSeconds(5);
|
||||
if (d.Act != OutdoorHunt.Act.Walk) break;
|
||||
}
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Idle, $"after {h.OutTriesMax} walks out ending inside: waits");
|
||||
Check.True(h.Note.Contains("ended still inside"), h.Note);
|
||||
}
|
||||
|
||||
private static readonly DateTime T0 = new(2026, 10, 23, 16, 0, 0);
|
||||
private static OutdoorHunt.Vec V(double x, double y) => new(x, y, 0);
|
||||
|
||||
private static OutdoorHunt.Candidate C(int id, double x, double y, OutdoorHunt.Vec me, int priority = 1, string? name = null)
|
||||
=> new(id, name ?? $"Monster {id}", V(x, y), V(x, y).DistanceTo(me), priority);
|
||||
|
||||
private sealed class Nav
|
||||
{
|
||||
public readonly Dictionary<(double, double), OutdoorHunt.PathResult> Overrides = new();
|
||||
/// <summary>A wall just in front of a monster: every walk to it ends at <c>end</c>, <c>gap</c> short.</summary>
|
||||
public readonly Dictionary<(double, double), (OutdoorHunt.Vec End, double Gap)> Walls = new();
|
||||
public int Calls;
|
||||
public bool Unavailable;
|
||||
|
||||
public OutdoorHunt.PathResult Path(OutdoorHunt.Vec a, OutdoorHunt.Vec b)
|
||||
{
|
||||
Calls++;
|
||||
if (Unavailable) return new(OutdoorHunt.PathStatus.Unavailable, Array.Empty<OutdoorHunt.Vec>(), 0, 0);
|
||||
if (Overrides.TryGetValue((b.X, b.Y), out var o)) return o;
|
||||
if (Walls.TryGetValue((b.X, b.Y), out var w)) return new(OutdoorHunt.PathStatus.Partial, new[] { w.End }, a.DistanceTo(w.End), w.Gap);
|
||||
return new(OutdoorHunt.PathStatus.Ok, new[] { b }, a.DistanceTo(b), 0);
|
||||
}
|
||||
|
||||
public void Around(double x, double y, double length) =>
|
||||
Overrides[(x, y)] = new(OutdoorHunt.PathStatus.Ok, new[] { V(x + 5, y + 5), V(x, y) }, length, 0);
|
||||
}
|
||||
|
||||
private static List<OutdoorHunt.Candidate> Sorted(params OutdoorHunt.Candidate[] c) => c.OrderBy(x => x.Distance).ToList();
|
||||
|
||||
private static void ShortestWalk()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
nav.Around(1010, 1000, 45); // 10 yd away, a building between: a 45 yd walk
|
||||
var list = Sorted(C(1, 1010, 1000, me), C(2, 1000, 1018, me));
|
||||
var d = h.Tick(T0, me, true, list, nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "walks");
|
||||
Check.Eq(d.TargetId, 2, "to the one 18 yd away in the open, not the one 10 yd away behind the building");
|
||||
Check.True(h.Note.Contains("18 yd walk"), "logged: " + h.Note);
|
||||
Check.Eq(d.Corners!.Last(), V(1000, 1018), "the walk ends at the monster");
|
||||
}
|
||||
|
||||
private static void PriorityFirst()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
var d = h.Tick(T0, me, true, Sorted(C(1, 1005, 1000, me, priority: 1), C(2, 1030, 1000, me, priority: 5)), nav.Path);
|
||||
Check.Eq(d.TargetId, 2, "Priority 5 at 30 yd before Priority 1 at 5 yd");
|
||||
}
|
||||
|
||||
private static void Unreachable()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
nav.Overrides[(1008, 1000)] = new(OutdoorHunt.PathStatus.NoPath, Array.Empty<OutdoorHunt.Vec>(), 0, 0); // up a cliff
|
||||
nav.Overrides[(1012, 1000)] = new(OutdoorHunt.PathStatus.Partial, new[] { V(1004, 1000) }, 4, 8); // in water: the walk ends 8 yd short
|
||||
nav.Overrides[(1020, 1000)] = new(OutdoorHunt.PathStatus.Partial, new[] { V(1018, 1000) }, 18, 2); // on a rock: 2 yd short is close enough
|
||||
var list = Sorted(C(1, 1008, 1000, me), C(2, 1012, 1000, me), C(3, 1020, 1000, me));
|
||||
var d = h.Tick(T0, me, true, list, nav.Path);
|
||||
Check.Eq(d.TargetId, 3, "the one whose walk ends 2 yd short; the cliff and the water ones are left out");
|
||||
Check.True(h.IsSkipped(1, T0.AddSeconds(60)) && h.IsSkipped(2, T0.AddSeconds(60)), "left out for a while");
|
||||
Check.False(h.IsSkipped(1, T0.AddSeconds(h.SkipSec + 1)), "and tried again after SkipSec");
|
||||
}
|
||||
|
||||
private static void Radius()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 50, RangeYd = 100 };
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var me = V(1040, 1000); // hunted out to 40 yd east
|
||||
var d = h.Tick(T0, me, true, Sorted(C(1, 1070, 1000, me), C(2, 1000, 1030, me)), nav.Path);
|
||||
Check.Eq(d.TargetId, 2, "the one 70 yd from the start is outside the 50 yd radius, even though it is closer");
|
||||
var any = new OutdoorHunt { RadiusYd = 0, RangeYd = 100 };
|
||||
any.Start(T0, start);
|
||||
Check.Eq(any.Tick(T0, me, true, Sorted(C(1, 1070, 1000, me), C(2, 1000, 1030, me)), nav.Path).TargetId, 1, "radius 0: anywhere, the nearest walk");
|
||||
}
|
||||
|
||||
private static void Replan()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
Check.Eq(h.Tick(T0, me, true, Sorted(C(1, 1030, 1000, me)), nav.Path).Act, OutdoorHunt.Act.Walk, "walks to it");
|
||||
int calls = nav.Calls;
|
||||
// Walking; it moved 2 yd: not worth a new plan.
|
||||
var d = h.Tick(T0.AddSeconds(2), V(1005, 1000), false, Sorted(C(1, 1032, 1000, me)), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.None, "it moved 2 yd: keep walking");
|
||||
Check.Eq(nav.Calls, calls, "no path asked for");
|
||||
// It moved 6 yd: plan again.
|
||||
d = h.Tick(T0.AddSeconds(3), V(1008, 1000), false, Sorted(C(1, 1036, 1000, me)), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "it moved 6 yd: a new walk");
|
||||
Check.Eq(d.Corners!.Last(), V(1036, 1000), "to where it is now");
|
||||
// Within a second: not again, even if it moves.
|
||||
d = h.Tick(T0.AddSeconds(3.5), V(1009, 1000), false, Sorted(C(1, 1045, 1000, me)), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.None, "not twice in a second");
|
||||
// The walk ran out short of it (the monster still out of combat's reach): plan again.
|
||||
d = h.Tick(T0.AddSeconds(4.2), V(1030, 1000), true, Sorted(C(1, 1036, 1000, me)), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "the walk ran out: again");
|
||||
// Nothing changed for ReplanMaxSec: again anyway.
|
||||
d = h.Tick(T0.AddSeconds(4.2 + h.ReplanMaxSec + 0.1), V(1030, 1000), false, Sorted(C(1, 1036, 1000, me)), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Walk, "a while with no change: again");
|
||||
}
|
||||
|
||||
// Tom 10-23: no walk back to the start ("it shouldn't bother").
|
||||
private static void WaitsWhereItIs()
|
||||
{
|
||||
var start = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RadiusYd = 100 };
|
||||
h.Start(T0, start);
|
||||
var nav = new Nav();
|
||||
var me = V(1060, 1000);
|
||||
h.ClearNotes();
|
||||
var d = h.Tick(T0, me, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Idle, "nothing to hunt, 60 yd from the start: waits there, no walk back");
|
||||
Check.Eq(nav.Calls, 0, "no path asked for");
|
||||
Check.True(h.Note.Contains("waiting here") && h.Note.Contains($"({h.RangeYd:0} yd)"), "says why, with Hunt Range: " + h.Note);
|
||||
h.Tick(T0.AddSeconds(2), me, true, new List<OutdoorHunt.Candidate>(), nav.Path);
|
||||
Check.Eq(h.PendingNotes.Count, 1, "said once, not every second");
|
||||
// A monster comes into range: hunted from there.
|
||||
d = h.Tick(T0.AddSeconds(4), me, true, Sorted(C(7, 1060, 1025, me)), nav.Path);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 7, $"a monster turns up: hunted ({d.Act} {d.TargetId})");
|
||||
Check.Eq(new OutdoorHunt().RadiusYd, 0.0, "Hunt Radius defaults to 0 (anywhere)");
|
||||
}
|
||||
|
||||
// Tom 10-23: "/mt opt set" gave no answer, and "/ra hunt status" toggled the hunt (the command read
|
||||
// the word "hunt" as its argument). The /ra hunt settings answer, and status/stop don't start it.
|
||||
private static void Commands()
|
||||
{
|
||||
const System.Reflection.BindingFlags Any = System.Reflection.BindingFlags.Instance
|
||||
| System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public;
|
||||
RynthCore.RynthAiHostTests.Fakes.FakeHost.Reset();
|
||||
var host = RynthCore.RynthAiHostTests.Fakes.FakeHost.Create();
|
||||
var p = new RynthAiPlugin();
|
||||
typeof(RynthCore.PluginCore.RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { RynthCore.RynthAiHostTests.Fakes.FakeHost.LastApi });
|
||||
var dash = new LegacyDashboardRenderer(host);
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash);
|
||||
var chat = RynthCore.RynthAiHostTests.Fakes.FakeHost.Chat;
|
||||
void Ra(string line)
|
||||
{
|
||||
chat.Clear();
|
||||
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(p, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
|
||||
}
|
||||
string All() => string.Join(" | ", chat);
|
||||
|
||||
Ra("/ra hunt range 150");
|
||||
Check.Eq(dash.Settings.OutdoorHuntRange, 150f, "range set");
|
||||
Check.True(All().Contains("Outdoor hunt set") && All().Contains("150 yd (Hunt Range)"), "and said: " + All());
|
||||
Ra("/ra hunt range 2000");
|
||||
Check.Eq(dash.Settings.OutdoorHuntRange, 2000f, "2000 is allowed (Tom 10-23)");
|
||||
Ra("/ra hunt range 5000");
|
||||
Check.Eq(dash.Settings.OutdoorHuntRange, (float)RynthAiPlugin.OutdoorHuntRangeMax, "capped at the most");
|
||||
Check.True(All().Contains("outside"), "and says it was capped: " + All());
|
||||
Ra("/ra hunt radius 0");
|
||||
Check.True(dash.Settings.OutdoorHuntRadius == 0 && All().Contains("anywhere"), "radius 0 = anywhere: " + All());
|
||||
Ra("/ra hunt range");
|
||||
Check.True(All().Contains("Hunt Range") && All().Contains("/ra hunt range <yd>"), "no number: shows the setting: " + All());
|
||||
Ra("/ra hunt status");
|
||||
Check.False(p.HuntActive, "status doesn't start it");
|
||||
Check.True(All().Contains("Outdoor hunt: off") && All().Contains("Hunt Range"), "status says off, with the distances: " + All());
|
||||
Ra("/ra hunt stop");
|
||||
Check.False(p.HuntActive, "stop doesn't start it");
|
||||
Ra("/ra hunt nonsense");
|
||||
Check.True(All().Contains("/ra hunt range <yd>"), "anything else: the usage: " + All());
|
||||
Ra("/ra hunt panel");
|
||||
Check.True((bool)typeof(RynthAiPlugin).GetField("_huntPanelOpen", Any)!.GetValue(p)!, "panel opens the window");
|
||||
}
|
||||
|
||||
private static void NextAndNoPathfinder()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt();
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
Check.Eq(h.Tick(T0, me, true, Sorted(C(1, 1010, 1000, me), C(2, 1030, 1000, me)), nav.Path).TargetId, 1, "the nearer first");
|
||||
// It died (combat killed it; it is gone from the list): the next one.
|
||||
var d = h.Tick(T0.AddSeconds(10), V(1009, 1000), true, Sorted(C(2, 1030, 1000, V(1009, 1000))), nav.Path);
|
||||
Check.Eq(d.TargetId, 2, "killed: on to the next");
|
||||
var none = new OutdoorHunt();
|
||||
none.Start(T0, me);
|
||||
var gone = new Nav { Unavailable = true };
|
||||
d = none.Tick(T0, me, true, Sorted(C(1, 1010, 1000, me)), gone.Path);
|
||||
Check.Eq(d.Act, OutdoorHunt.Act.Idle, "RynthNav missing: stands");
|
||||
Check.Eq(d.Why, "no pathfinder", "and says why");
|
||||
}
|
||||
|
||||
private static void FarRound()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var h = new OutdoorHunt { RangeYd = 60 };
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
nav.Around(1012, 1000, 143); // a buff bot inside a building: 12 yd away, a 143 yd walk
|
||||
var d = h.Tick(T0, me, true, Sorted(C(1, 1012, 1000, me), C(2, 1040, 1000, me)), nav.Path);
|
||||
Check.Eq(d.TargetId, 2, "the 143 yd walk (over twice Hunt Range) is too far round: the one 40 yd away instead");
|
||||
Check.True(h.IsSkipped(1, T0.AddSeconds(30)), "and it is left out for a while (no choosing it again every second)");
|
||||
Check.True(h.Note.Contains("40 yd walk"), "logged: " + h.Note);
|
||||
// Walking round to the 40 yd one took the character 70 yd from it (past Hunt Range): still its target.
|
||||
var far = V(970, 1000);
|
||||
var c2 = new OutdoorHunt.Candidate(2, "Monster 2", V(1040, 1000), 70, 1);
|
||||
d = h.Tick(T0.AddSeconds(2), far, false, new List<OutdoorHunt.Candidate> { c2 }, nav.Path);
|
||||
Check.True(d.Act != OutdoorHunt.Act.Idle && h.TargetId == 2, $"kept at 70 yd (Hunt Range 60): {d.Act}, target {h.TargetId}");
|
||||
}
|
||||
|
||||
private static void Settings()
|
||||
{
|
||||
var s = new LegacyUiSettings();
|
||||
// 2026-10-25 (Tom: "the entire radar range"): 192, the radar's default range (was 60).
|
||||
Check.Eq(s.OutdoorHuntRange, 192f, "Hunt Range defaults to 192 yd, the radar's range");
|
||||
Check.Eq(new OutdoorHunt().RangeYd, 192.0, "and the hunt's own default too");
|
||||
Check.Eq(s.OutdoorHuntRadius, 0f, "Hunt Radius defaults to 0 (anywhere)");
|
||||
var ctx = RynthAiJsonContext.Default.LegacyUiSettings;
|
||||
var saved = System.Text.Json.JsonSerializer.Deserialize(
|
||||
System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { OutdoorHuntRange = 90, OutdoorHuntRadius = 250 }, ctx), ctx)!;
|
||||
var live = new LegacyUiSettings();
|
||||
typeof(LegacyDashboardRenderer).GetMethod("CopySettings",
|
||||
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)!
|
||||
.Invoke(null, new object[] { saved, live });
|
||||
Check.True(live.OutdoorHuntRange == 90 && live.OutdoorHuntRadius == 250, "saved and copied");
|
||||
// A file saved before 10-23 evening still has "OutdoorHuntReturn": it loads (the setting is gone).
|
||||
var old = System.Text.Json.JsonSerializer.Deserialize("{\"OutdoorHuntRange\":70,\"OutdoorHuntRadius\":2000,\"OutdoorHuntReturn\":true}", ctx);
|
||||
Check.True(old != null && old.OutdoorHuntRange == 70 && old.OutdoorHuntRadius == 2000, "an old file with Back To Start loads");
|
||||
}
|
||||
}
|
||||
138
Tools/RynthCore.RynthAiHostTests/Tests/PatrolModeTests.cs
Normal file
138
Tools/RynthCore.RynthAiHostTests/Tests/PatrolModeTests.cs
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
using System;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The Dungeon Patrol as the chosen mode (2026-11-01): it stays the route through a macro stop and
|
||||
// start, ends (said in chat) only when another route is loaded in its place, and follows the
|
||||
// character through a portal into another dungeon (not after a death). The patrol tick
|
||||
// (TickDunPatrolHazardReroute) is driven directly, as ServerPolicyTests does.
|
||||
internal static class PatrolModeTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const uint PatrolCell = 0x57560124, OtherDungeonCell = 0x00830188, OutdoorCell = 0xC4B60002;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("patrol mode: a macro stop and start keeps the patrol as the route and as the mode", StopStartKeepsPatrol);
|
||||
r.Add("patrol mode: a nav file loaded in its place ends it, said in chat with the file's name", ReplacedSaysSo);
|
||||
r.Add("patrol mode: through a portal taken while it runs it follows into another dungeon; not after a death or with the macro off, not into a building, once per dungeon", FollowDecision);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new() { IsMacroRunning = true, EnableNavigation = true };
|
||||
|
||||
public Rig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
ServerPolicy.Forget();
|
||||
FakeHost.WorldName = "Conquest";
|
||||
FakeHost.Names[Player] = "Mage";
|
||||
FakeHost.PlayerPose = (PatrolCell, 70f, -80f, 0f);
|
||||
FakeHost.Create(Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(P, dash);
|
||||
}
|
||||
|
||||
private object? Get(string f) => typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P);
|
||||
private void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
|
||||
public bool Active => (bool)Get("_dunPatrolActive")!;
|
||||
public void Tick() => typeof(RynthAiPlugin).GetMethod("TickDunPatrolHazardReroute", Any)!.Invoke(P, null);
|
||||
|
||||
/// <summary>A patrol as BuildDunPatrol leaves it: the route, its object remembered, nav on, this dungeon.</summary>
|
||||
public NavRouteParser RunningPatrol()
|
||||
{
|
||||
var route = new NavRouteParser { RouteType = NavRouteType.Circular };
|
||||
route.Points.Add(new NavPoint { NS = -33.3, EW = -32.3 });
|
||||
route.Points.Add(new NavPoint { NS = -33.2, EW = -32.3 });
|
||||
S.CurrentNavPath = string.Empty;
|
||||
S.CurrentRoute = route;
|
||||
Set("_dunPatrolActive", true);
|
||||
Set("_dunPatrolRoute", route);
|
||||
Set("_dunPatrolLandblock", PatrolCell >> 16);
|
||||
return route;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Said(string text) => FakeHost.Chat.Exists(l => l.Contains(text, StringComparison.Ordinal));
|
||||
|
||||
private static void StopStartKeepsPatrol()
|
||||
{
|
||||
var b = new Rig();
|
||||
var patrol = b.RunningPatrol();
|
||||
b.Tick();
|
||||
Check.True(b.Active, "running: the patrol is the mode");
|
||||
|
||||
b.S.IsMacroRunning = false; // the player stops the macro
|
||||
b.Tick();
|
||||
Check.True(b.Active, "stopped: still the mode (it used to be stood down here)");
|
||||
Check.True(ReferenceEquals(b.S.CurrentRoute, patrol), "and still the route");
|
||||
|
||||
b.S.IsMacroRunning = true; // ... and starts it again
|
||||
b.Tick();
|
||||
Check.True(b.Active, "started again: the patrol carries on");
|
||||
Check.True(ReferenceEquals(b.S.CurrentRoute, patrol), "the same route, not the nav file loaded before it");
|
||||
|
||||
b.S.EnableNavigation = false; b.Tick(); b.S.EnableNavigation = true; b.Tick();
|
||||
Check.True(b.Active, "nav switched off and on: the same");
|
||||
Check.False(Said("Dungeon Patrol ended"), "nothing said");
|
||||
}
|
||||
|
||||
private static void ReplacedSaysSo()
|
||||
{
|
||||
var b = new Rig();
|
||||
b.RunningPatrol();
|
||||
b.Tick();
|
||||
// The player picks a nav file (LoadSelectedNav: the path and a new route).
|
||||
var file = new NavRouteParser { RouteType = NavRouteType.Circular };
|
||||
file.Points.Add(new NavPoint { NS = 42.4, EW = 54.9 });
|
||||
b.S.CurrentNavPath = @"C:\Games\RynthSuite\RynthAi\NavProfiles\ToSomewhere.nav";
|
||||
b.S.CurrentRoute = file;
|
||||
b.Tick();
|
||||
Check.False(b.Active, "the patrol ended");
|
||||
Check.True(Said("Dungeon Patrol ended: nav route 'ToSomewhere' is the route now"), "said in chat, naming the file");
|
||||
Check.True(FakeHost.Logs.Exists(l => l.Contains("DunNav-Patrol: ended")), "and logged");
|
||||
Check.True(ReferenceEquals(b.S.CurrentRoute, file), "the loaded route is left alone");
|
||||
|
||||
// A meta's route in its place is named as the meta's.
|
||||
var m = new Rig();
|
||||
m.RunningPatrol();
|
||||
var emb = new NavRouteParser { RouteType = NavRouteType.Linear };
|
||||
emb.Points.Add(new NavPoint { NS = 1, EW = 1 });
|
||||
m.S.CurrentNavPath = "<embedded:Hunt>";
|
||||
m.S.CurrentRoute = emb;
|
||||
m.Tick();
|
||||
Check.True(Said("the meta's route 'Hunt'"), "a meta's route is named as the meta's");
|
||||
}
|
||||
|
||||
private static void FollowDecision()
|
||||
{
|
||||
uint patrolLb = PatrolCell >> 16;
|
||||
var F = RynthAiPlugin.PatrolFollow.Follow;
|
||||
var N = RynthAiPlugin.PatrolFollow.None;
|
||||
var D = RynthAiPlugin.PatrolFollow.AfterDeath;
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, uint.MaxValue, -1, true), F, "portalled into another dungeon while running: follow");
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, uint.MaxValue, -1, false), RynthAiPlugin.PatrolFollow.CameWhileStopped, "got there with the macro off (a failsafe recall, by hand): says so, doesn't follow");
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, PatrolCell + 5, true, false, uint.MaxValue, -1, true), N, "same dungeon: nothing");
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OutdoorCell, false, false, uint.MaxValue, -1, true), N, "the landscape: nothing (nav holds and says so)");
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, 0xC4B60105, false, false, uint.MaxValue, -1, true), N, "a building on the landscape: not a dungeon");
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, true, uint.MaxValue, -1, true), N, "mid-portal: wait");
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, OtherDungeonCell >> 16, -1, true), N, "tried there already: once per dungeon");
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, uint.MaxValue, 30_000, true), D, "30 s after a death: says so, doesn't follow");
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, uint.MaxValue, RynthAiPlugin.PatrolFollowDeathMs + 1, true), F, "long after a death: follows");
|
||||
Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, 0, true, false, uint.MaxValue, -1, true), N, "no pose: nothing");
|
||||
}
|
||||
}
|
||||
|
|
@ -41,6 +41,19 @@ internal static class PetRefillTests
|
|||
r.Add("pets: the server's 'full' trust expires after 30 min", TrustExpires);
|
||||
r.Add("pets: a landed summon whose pet is not in the cache yet holds a second essence back for the 10 s window", LandedSummonHoldsWindow);
|
||||
r.Add("pets: failed summon (no charge drop) does not assume a pet; waits the 45 s essence cooldown", FailedSummonRespectsCooldown);
|
||||
r.Add("pets: Boost Nav Priority on (RynthAi only navigates): no summon with a monster near; off: it summons", BoostNavNoSummon);
|
||||
}
|
||||
|
||||
// Owner's rule (2026-11-02): with Boost Nav Priority on there is no fight, so no pet is called for one.
|
||||
private static void BoostNavNoSummon()
|
||||
{
|
||||
using var rig = new Rig(charges: 50);
|
||||
rig.S.BoostNavPriority = true;
|
||||
rig.Run(5000);
|
||||
Check.Eq(rig.AllSummons, 0, "flag on: no summon in 5 s with the monster 3 m away");
|
||||
rig.S.BoostNavPriority = false;
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Summons, 1, "flag off: it summons");
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -388,6 +388,7 @@ internal static class VTankHotkeyTests
|
|||
bot.UseGemProfile();
|
||||
bot.S.IsMacroRunning = false;
|
||||
bot.S.EnableLooting = false;
|
||||
bot.S.LootChestsMacroOff = false; // the chest waits for LootThisCont (Pickup with macro off would take it)
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
FakeHost.GroundContainer = Chest;
|
||||
bot.P.OnViewObjectContents(Chest);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ using DotRecast.Recast.Toolset;
|
|||
using DotRecast.Recast.Toolset.Builder;
|
||||
using RynthNav.Baker;
|
||||
using RynthNav.Routing;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
|
|
@ -36,8 +37,20 @@ internal static class Program
|
|||
Run(nameof(RouteFollower), RouteFollower);
|
||||
Run(nameof(EndToEndAroundAWall), EndToEndAroundAWall);
|
||||
Run(nameof(LandmassesAndSameLand), LandmassesAndSameLand);
|
||||
Run(nameof(FencedInGoalMovesToReachableGround), FencedInGoalMovesToReachableGround);
|
||||
Run(nameof(RealFencedInGoal), RealFencedInGoal);
|
||||
Run(nameof(PathGoesRoundAPortal), PathGoesRoundAPortal);
|
||||
Run(nameof(TripWalkFromTileFiles), TripWalkFromTileFiles);
|
||||
Run(nameof(PathInterfaceVersions), PathInterfaceVersions);
|
||||
Run(nameof(PathTileBox), PathTileBox);
|
||||
Run(nameof(PathExOpenFloorAndInfo), PathExOpenFloorAndInfo);
|
||||
Run(nameof(PathExRoundAPortal), PathExRoundAPortal);
|
||||
Run(nameof(PathExPartial), PathExPartial);
|
||||
Run(nameof(PathExNoMeshAndStartSnap), PathExNoMeshAndStartSnap);
|
||||
Run(nameof(PathExWallsAndBuffer), PathExWallsAndBuffer);
|
||||
Run(nameof(RaycastOnTheMesh), RaycastOnTheMesh);
|
||||
Run(nameof(RealPathEx), RealPathEx);
|
||||
Run(nameof(RealDoorsteps), RealDoorsteps);
|
||||
Run(nameof(RealTripWalk), RealTripWalk);
|
||||
Run(nameof(MeshViewFloorAndWalls), MeshViewFloorAndWalls);
|
||||
Run(nameof(MeshViewEmitBudgetAndFrame), MeshViewEmitBudgetAndFrame);
|
||||
|
|
@ -63,6 +76,10 @@ internal static class Program
|
|||
|
||||
/// <summary>Flat rectangles (x0, z0, x1, z1) at height 0, plus a corner marker so the grid starts at (0,0).</summary>
|
||||
private static string Bake(string name, params (float x0, float z0, float x1, float z1)[] floors)
|
||||
=> BakeLayers(name, floors.Select(f => (f.x0, f.z0, f.x1, f.z1, 0f)).ToArray());
|
||||
|
||||
/// <summary>Flat rectangles (x0, z0, x1, z1) each at its own height y: a floor with a roof over part of it.</summary>
|
||||
private static string BakeLayers(string name, params (float x0, float z0, float x1, float z1, float y)[] floors)
|
||||
{
|
||||
var verts = new List<float>(); var faces = new List<int>();
|
||||
void Quad(float x0, float z0, float x1, float z1, float y)
|
||||
|
|
@ -72,7 +89,7 @@ internal static class Program
|
|||
// Both windings: Recast keeps the upward-facing one as walkable.
|
||||
faces.AddRange(new[] { b, b + 1, b + 2, b, b + 2, b + 3, b, b + 2, b + 1, b, b + 3, b + 2 });
|
||||
}
|
||||
foreach (var f in floors) Quad(f.x0, f.z0, f.x1, f.z1, 0);
|
||||
foreach (var f in floors) Quad(f.x0, f.z0, f.x1, f.z1, f.y);
|
||||
// Pin the bounds to the landblock grid (unused vertices, as the baker does).
|
||||
float maxX = floors.Max(f => f.x1), maxZ = floors.Max(f => f.z1);
|
||||
verts.AddRange(new[] { 0f, -1f, 0f, (float)Math.Ceiling(maxX / 192) * 192f, 1f, (float)Math.Ceiling(maxZ / 192) * 192f });
|
||||
|
|
@ -311,6 +328,78 @@ internal static class Program
|
|||
Check(m != null && m.Count == 2 && m.Cost >= c.Cost - 1, $"with walked end legs too ({m?.Cost:F0})");
|
||||
}
|
||||
|
||||
private static void FencedInGoalMovesToReachableGround()
|
||||
{
|
||||
// 11-01: a /loc on ground fenced in by a building's walls. Two tiles of open ground; in tile 1
|
||||
// a small floor (300..320, 80..100) with a 10 m moat round it: a pocket region of its own,
|
||||
// with no border links. Every route search to it found nothing (0 expanded), and the walk
|
||||
// headed straight for the spot instead. The goal end now moves to the nearest ground a
|
||||
// walk can end on.
|
||||
string dir = Bake("pocket", (0, 10, 384, 70), (0, 110, 384, 180), (0, 70, 290, 110), (330, 70, 384, 110), (300, 80, 320, 100));
|
||||
BuildGraph(dir, out NavGraph g);
|
||||
g.BuildComponents();
|
||||
var nav = new DtNavMesh();
|
||||
var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 4, maxPolys = 1 << 16 };
|
||||
nav.Init(prm, 6);
|
||||
var regions = new Dictionary<uint, int[]>();
|
||||
foreach (uint lb in new uint[] { 0x0000, 0x0100 })
|
||||
{
|
||||
DtMeshData md = ReadTile(dir, lb);
|
||||
nav.AddTile(md, 0, 0, out _);
|
||||
regions[lb] = NavRegions.Build(md, out _);
|
||||
}
|
||||
var q = new DtNavMeshQuery(nav);
|
||||
NavCoarse.Probe? start = NavCoarse.ProbeNear(g, nav, q, 40, 0, 40, 12, regions);
|
||||
Check(start != null && g.RegionPortals(start.Region).Length > 0, "the start is on open ground with border links");
|
||||
|
||||
NavCoarse.Probe? pocket = NavCoarse.ProbeNear(g, nav, q, 310, 0, 90, 40, regions);
|
||||
Check(pocket != null && g.RegionPortals(pocket.Region).Length == 0, "the spot's own polygon is a pocket with no border links");
|
||||
var none = g.FindRoute(start!.Region, 40, 40, pocket!.Region, 310, 90, out _, out int expanded);
|
||||
Check(none == null && expanded == 0, $"to the pocket: no route, nothing expanded (the 11-01 log: '0 expanded') (expanded {expanded})");
|
||||
Check(!NavCoarse.Reachable(g, start.Region, pocket.Region) && NavCoarse.Reachable(g, start.Region, start.Region), "a pocket isn't reachable; the start's own region is");
|
||||
|
||||
NavCoarse.Probe? goal = NavCoarse.ProbeReachable(g, nav, q, 310, 0, 90, 40, regions, start.Region, out bool moved);
|
||||
double off = goal == null ? double.NaN : Math.Sqrt((goal.Pt.X - 310) * (goal.Pt.X - 310) + (goal.Pt.Z - 90) * (goal.Pt.Z - 90));
|
||||
Check(goal != null && moved && goal.Region != pocket.Region && NavCoarse.Reachable(g, start.Region, goal.Region),
|
||||
$"the goal moves to linked ground (region {goal?.Region}, moved {moved})");
|
||||
Check(off < 25, $"...the nearest such ground, beside the moat ({off:F1} u from the spot)");
|
||||
NavCoarse? c = NavCoarse.Plan(g, start, goal!, out _);
|
||||
Check(c != null && c.Count >= 1 && Math.Abs(c.GoalEw - goal!.Pt.X) < 0.01 && !double.IsNaN(c.GoalUp), "a route to it, ending on that ground (with its height)");
|
||||
|
||||
NavCoarse.Probe? fromFile = NavCoarse.ProbeFile(g, dir, 310, 0, 90, 40, start.Region, out bool movedFile);
|
||||
Check(fromFile != null && movedFile && fromFile.Region == goal!.Region, "the same from the tile file (the target's tile not loaded)");
|
||||
|
||||
NavCoarse.Probe? open = NavCoarse.ProbeReachable(g, nav, q, 250, 0, 150, 40, regions, start.Region, out bool movedOpen);
|
||||
Check(open != null && !movedOpen && Math.Abs(open.Pt.X - 250) < 0.5 && Math.Abs(open.Pt.Z - 150) < 0.5, "a spot on open ground stays where it is");
|
||||
}
|
||||
|
||||
private static void RealFencedInGoal()
|
||||
{
|
||||
// The 11-01 goto to 43.6N, 85.4W on the real navmesh: the spot probes onto a fenced-in
|
||||
// polygon (a region of its own, no border links); every search from 41.8N, 82.2W (and from
|
||||
// everywhere else on the way) found no route.
|
||||
string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData";
|
||||
string graphFile = Path.Combine(dir, NavGraph.FileName);
|
||||
if (!File.Exists(graphFile)) { Console.WriteLine(" (no real NavData here: skipped)"); return; }
|
||||
NavGraph g = NavGraph.Load(graphFile);
|
||||
g.BuildComponents();
|
||||
static double W(double map) => (map * 10.0 + 1019.5) * 24.0;
|
||||
double sx = W(-82.2), sy = W(41.8), tx = W(-85.4), ty = W(43.6);
|
||||
NavCoarse.Probe? start = NavCoarse.ProbeFile(g, dir, sx, 22, sy, 12);
|
||||
if (start == null) { Console.WriteLine(" (these tiles aren't the ones this test was written for: skipped)"); return; }
|
||||
NavCoarse.Probe? old = NavCoarse.ProbeFile(g, dir, tx, 22, ty, 40);
|
||||
NavCoarse.Probe? goal = NavCoarse.ProbeFile(g, dir, tx, 22, ty, 40, start.Region, out bool moved);
|
||||
Check(old != null && goal != null, "both probes find ground");
|
||||
if (old == null || goal == null) return;
|
||||
bool oldRoute = NavCoarse.Plan(g, start, old, out int oldExpanded) != null;
|
||||
NavCoarse? c = NavCoarse.Plan(g, start, goal, out int expanded);
|
||||
double off = Math.Sqrt((goal.Pt.X - tx) * (goal.Pt.X - tx) + (goal.Pt.Z - ty) * (goal.Pt.Z - ty));
|
||||
Console.WriteLine($" 43.6N 85.4W: the spot's own region {old.Region} ({g.RegionPortals(old.Region).Length} border links, route {(oldRoute ? "yes" : "none")}, {oldExpanded} expanded); "
|
||||
+ $"moved {moved} to region {goal.Region}, {off:F1} u off; route {(c == null ? "none" : $"{c.Count} crossings, ~{c.Cost:F0} u")} ({expanded} expanded)");
|
||||
Check(c != null, "a route to the ground beside the fenced-in spot");
|
||||
Check(off < 12, $"that ground is beside the spot ({off:F1} u)");
|
||||
}
|
||||
|
||||
private static void LandmassesAndSameLand()
|
||||
{
|
||||
// Two joined tiles (the mainland) and a tile two landblocks away (an island).
|
||||
|
|
@ -431,6 +520,407 @@ internal static class Program
|
|||
Check(own != null && Math.Abs(own[^1].X - 95) < 3, "walking into that portal: it's the goal, not avoided");
|
||||
}
|
||||
|
||||
// ── "RynthNav.Path" v2: FindPathEx and Raycast (NavPathQuery, the plugin's interface) ──
|
||||
|
||||
/// <summary>Every tile file of a bake in one navmesh, as the plugin has its loaded tiles.</summary>
|
||||
private static DtNavMeshQuery QueryOn(string dir)
|
||||
{
|
||||
var nav = new DtNavMesh();
|
||||
var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 64, maxPolys = 1 << 16 };
|
||||
nav.Init(prm, 6);
|
||||
foreach (string f in Directory.GetFiles(dir, "nav_*.tile"))
|
||||
{
|
||||
uint lb = Convert.ToUInt32(Path.GetFileNameWithoutExtension(f).Substring(4), 16);
|
||||
nav.AddTile(ReadTile(dir, lb), 0, 0, out _);
|
||||
}
|
||||
return new DtNavMeshQuery(nav);
|
||||
}
|
||||
|
||||
private static PathExResult Ex(DtNavMeshQuery q, double sx, double sy, double gx, double gy, int flags,
|
||||
AvoidFilter? portals = null, double clearance = 1.0, int maxCorners = 64, double sz = 0, double gz = 0)
|
||||
{
|
||||
var r = new PathExResult();
|
||||
int code = NavPathQuery.FindPathEx(q, sx, sy, sz, gx, gy, gz, flags, maxCorners, portals, clearance, r);
|
||||
if (code != r.Code) throw new InvalidOperationException("the returned code and the result's differ");
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>The path's closest pass to (x, y), flat.</summary>
|
||||
private static double Closest(PathExResult r, double x, double y)
|
||||
{
|
||||
double best = double.MaxValue;
|
||||
for (int i = 1; i < r.Corners.Count; i++)
|
||||
best = Math.Min(best, PortalAvoid.SegmentDistance(x, y, r.Corners[i - 1].X, r.Corners[i - 1].Y, r.Corners[i].X, r.Corners[i].Y));
|
||||
return best;
|
||||
}
|
||||
|
||||
private static double Flat((double X, double Y, double Z) a, double x, double y) => Math.Sqrt((a.X - x) * (a.X - x) + (a.Y - y) * (a.Y - y));
|
||||
|
||||
private static double Legs(PathExResult r)
|
||||
{
|
||||
double len = 0;
|
||||
for (int i = 1; i < r.Corners.Count; i++)
|
||||
{
|
||||
var a = r.Corners[i - 1]; var b = r.Corners[i];
|
||||
len += Math.Sqrt((b.X - a.X) * (b.X - a.X) + (b.Y - a.Y) * (b.Y - a.Y) + (b.Z - a.Z) * (b.Z - a.Z));
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The table is handed to v1 callers too (older RynthAi's stuck recovery asks for 1) and to v2 and
|
||||
/// v3 callers, never for 0 or a newer version; and the layout only ever grew at its end. v3
|
||||
/// (2026-10-25) added no field, only the PathStartOutdoors flag (RynthAi's hunt plans from a
|
||||
/// building's doorstep while the player is inside).
|
||||
/// </summary>
|
||||
private static unsafe void PathInterfaceVersions()
|
||||
{
|
||||
const string name = RynthNavPathApiV1.InterfaceName;
|
||||
Check(RynthNavPathApiV1.InterfaceVersion == 3, "the contract is version 3");
|
||||
Check(!NavPathQuery.ServesInterface(name, 0), "version 0: refused");
|
||||
Check(NavPathQuery.ServesInterface(name, 1), "version 1 (FindPath callers): served the same table");
|
||||
Check(NavPathQuery.ServesInterface(name, 2), "version 2: served");
|
||||
Check(NavPathQuery.ServesInterface(name, 3), "version 3: served");
|
||||
Check(!NavPathQuery.ServesInterface(name, 4) && !NavPathQuery.ServesInterface(name, uint.MaxValue), "a version newer than the one built: refused");
|
||||
Check(RynthNavPathApiV1.PathStartOutdoors == 16
|
||||
&& (RynthNavPathApiV1.PathStartOutdoors & (RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance
|
||||
| RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet)) == 0,
|
||||
"the v3 flag is a bit of its own");
|
||||
Check(!NavPathQuery.ServesInterface("RynthNav.path", 1) && !NavPathQuery.ServesInterface("", 2) && !NavPathQuery.ServesInterface(null, 2)
|
||||
&& !NavPathQuery.ServesInterface("RynthAi.Script", 1), "another interface's name: refused");
|
||||
|
||||
RynthNavPathApiV1 t = default;
|
||||
byte* b = (byte*)&t;
|
||||
int p = IntPtr.Size;
|
||||
Check((byte*)&t.Version - b == 0 && (byte*)&t.StructSize - b == 4 && (byte*)&t.FindPath - b == 8, "v1's fields where v1 callers read them");
|
||||
Check((byte*)&t.FindPathEx - b == 8 + p && (byte*)&t.Raycast - b == 8 + 2 * p && sizeof(RynthNavPathApiV1) == 8 + 3 * p,
|
||||
$"v2 appended after FindPath (size {sizeof(RynthNavPathApiV1)} with {p}-byte pointers)");
|
||||
Check(RynthNavPathApiV1.InfoLength == 6 && RynthNavPathApiV1.ResultPartial == 2 && RynthNavPathApiV1.RayClear == 1 && RynthNavPathApiV1.RayBlocked == 0,
|
||||
"the v2 constants");
|
||||
}
|
||||
|
||||
private static void PathTileBox()
|
||||
{
|
||||
Check(NavPathQuery.ClampMaxTiles(0) == 25 && NavPathQuery.ClampMaxTiles(-4) == 25, "maxTiles 0: the default 25");
|
||||
Check(NavPathQuery.ClampMaxTiles(9) == 9 && NavPathQuery.ClampMaxTiles(49) == 49 && NavPathQuery.ClampMaxTiles(1000) == 49, "else as asked, at most 49");
|
||||
double hx = 0xA9 * 192 + 96, hy = 0xB4 * 192 + 96; // the middle of Holtburg's landblock
|
||||
Check(NavPathQuery.TileBox(hx, hy, hx + 50, hy + 50, 25, false, out int x0, out int y0, out int x1, out int y1)
|
||||
&& x0 == 0xA8 && x1 == 0xAA && y0 == 0xB3 && y1 == 0xB5, "both ends in one landblock: it and the ring round it");
|
||||
Check(!NavPathQuery.TileBox(hx, hy, hx + 192, hy, 9, false, out _, out _, out _, out _), "FindPath (v1): 4x3 with the margin doesn't fit 9, no smaller box");
|
||||
Check(NavPathQuery.TileBox(hx, hy, hx + 192, hy, 9, true, out x0, out y0, out x1, out y1) && x0 == 0xA9 && x1 == 0xAA && y0 == 0xB4 && y1 == 0xB4,
|
||||
"FindPathEx: then the two landblocks alone");
|
||||
Check(NavPathQuery.TileBox(hx, hy, hx + 192, hy, 12, true, out x0, out _, out x1, out _) && x0 == 0xA8 && x1 == 0xAB, "with room for it, the margin stays");
|
||||
Check(NavPathQuery.TileBox(hx, hy, hx + 192 * 8, hy, 49, true, out _, out _, out _, out _), "nine landblocks in a row fit 49 without the margin (9 tiles)");
|
||||
Check(!NavPathQuery.TileBox(hx, hy, hx + 192 * 8, hy + 192 * 8, 49, true, out _, out _, out _, out _), "nine apart both ways (81 tiles): too far even for 49");
|
||||
Check(NavPathQuery.TileBox(10, 10, 20, 20, 25, false, out x0, out y0, out x1, out y1) && x0 == 0 && y0 == 0 && x1 == 1 && y1 == 1, "the box stops at the map's edge");
|
||||
Check(!NavPathQuery.TileBox(1e12, 0, 0, 0, 49, true, out _, out _, out _, out _), "a position far off the map: no box (and no overflow)");
|
||||
}
|
||||
|
||||
private static void PathExOpenFloorAndInfo()
|
||||
{
|
||||
var q = QueryOn(Bake("exfloor", (0, 0, 192, 192)));
|
||||
var r = Ex(q, 30, 96, 160, 96, 0);
|
||||
Check(r.Code == RynthNavPathApiV1.ResultOk && !r.Partial, $"open ground: ResultOk ({r.Code}, {r.Note})");
|
||||
Check(r.Corners.Count >= 2 && Flat(r.Corners[0], 30, 96) < 0.5 && Flat(r.Corners[^1], 160, 96) < 0.5, "start first, goal last");
|
||||
Check(Math.Abs(r.Length - Legs(r)) < 1e-9 && Math.Abs(r.Length - 130) < 1, $"info[0]: the sum of the legs ({r.Length:F2})");
|
||||
Check(r.EndDistance < 0.5, $"info[5]: at the goal ({r.EndDistance:F2})");
|
||||
Check(r.Corners.TrueForAll(c => Math.Abs(c.Z) < 0.5), "heights from the mesh (the floor's)");
|
||||
var up = Ex(q, 30, 96, 160, 96, 0, gz: 5);
|
||||
Check(up.Code == RynthNavPathApiV1.ResultOk && Math.Abs(up.EndDistance - 5) < 0.6, $"info[5] is 3D: a goal 5 u above the ground is ~5 u away ({up.EndDistance:F2})");
|
||||
var same = Ex(q, 50, 50, 50, 50, 0);
|
||||
Check(same.Code == RynthNavPathApiV1.ResultOk && same.Corners.Count == 2 && same.Length < 1e-6, "start = goal: two corners, length 0");
|
||||
var quiet = Ex(q, 30, 96, 160, 96, RynthNavPathApiV1.PathQuiet);
|
||||
Check(quiet.Code == r.Code && quiet.Corners.Count == r.Corners.Count && Math.Abs(quiet.Length - r.Length) < 1e-9, "PathQuiet changes only the log");
|
||||
}
|
||||
|
||||
private static void PathExRoundAPortal()
|
||||
{
|
||||
var q = QueryOn(Bake("exportal", (0, 0, 192, 192)));
|
||||
var spots = new PortalAvoid();
|
||||
spots.Set(new[] { new PortalAvoid.Spot(95, 96, PortalAvoid.LiveRadius, "Unwanted Portal") }, Array.Empty<PortalAvoid.Spot>());
|
||||
var filter = new AvoidFilter(spots);
|
||||
var over = Ex(q, 30, 96, 160, 96, 0, filter);
|
||||
Check(over.Code == RynthNavPathApiV1.ResultOk && Closest(over, 95, 96) < 1 && over.Portals == 0, "without PathAvoidPortals it walks over the portal");
|
||||
var round = Ex(q, 30, 96, 160, 96, RynthNavPathApiV1.PathAvoidPortals, filter);
|
||||
double gap = Closest(round, 95, 96);
|
||||
Console.WriteLine($" portal on the line: {over.Corners.Count} corners {over.Length:F1}u straight; avoided {round.Corners.Count} corners {round.Length:F1}u, closest {gap:F2}u, bent {round.Bent}");
|
||||
Check(round.Code == RynthNavPathApiV1.ResultOk && gap >= PortalAvoid.LiveRadius - 0.01, $"PathAvoidPortals: keeps out of the circle ({gap:F2} u)");
|
||||
Check(round.Portals == 1 && round.Corners.Count > over.Corners.Count && round.Length > over.Length, "bent round it, a little longer");
|
||||
Check(Flat(round.Corners[^1], 160, 96) < 0.5 && Math.Abs(round.Length - Legs(round)) < 1e-9, "still to the goal; the length counts the bend");
|
||||
Check(round.Corners.TrueForAll(c => double.IsFinite(c.Z) && Math.Abs(c.Z) < 0.5), "a bend corner gets the mesh's height");
|
||||
var into = Ex(q, 30, 96, 95, 96, RynthNavPathApiV1.PathAvoidPortals, filter);
|
||||
Check(into.Code == RynthNavPathApiV1.ResultOk && Flat(into.Corners[^1], 95, 96) < 1, "a goal inside a circle is still reached (its polygon is allowed)");
|
||||
var empty = new AvoidFilter(new PortalAvoid());
|
||||
Check(Ex(q, 30, 96, 160, 96, RynthNavPathApiV1.PathAvoidPortals, empty).Corners.Count == over.Corners.Count, "no portals near: the plain path");
|
||||
}
|
||||
|
||||
private static void PathExPartial()
|
||||
{
|
||||
var q = QueryOn(Bake("exisland", (10, 10, 70, 180), (110, 10, 180, 180)));
|
||||
var no = Ex(q, 40, 96, 150, 96, 0);
|
||||
Check(no.Code == RynthNavPathApiV1.ResultNoPath && no.Corners.Count == 0, "the other island without PathAllowPartial: ResultNoPath (as FindPath)");
|
||||
var part = Ex(q, 40, 96, 150, 96, RynthNavPathApiV1.PathAllowPartial);
|
||||
Check(part.Code == RynthNavPathApiV1.ResultPartial && part.Partial, $"with it: ResultPartial ({part.Code}, {part.Note})");
|
||||
if (part.Corners.Count == 0) return;
|
||||
var end = part.Corners[^1];
|
||||
Console.WriteLine($" partial: {part.Corners.Count} corners, ends at ({end.X:F1}, {end.Y:F1}), {part.EndDistance:F1}u from the goal");
|
||||
Check(end.X > 60 && end.X < 70 && Math.Abs(end.Y - 96) < 8, $"it ends on the near island's edge, facing the goal ({end.X:F1}, {end.Y:F1})");
|
||||
Check(Math.Abs(part.EndDistance - Math.Sqrt((150 - end.X) * (150 - end.X) + (96 - end.Y) * (96 - end.Y) + end.Z * end.Z)) < 1e-9 && part.EndDistance > 70,
|
||||
$"info[5]: what's left to the goal ({part.EndDistance:F1})");
|
||||
var all = Ex(q, 40, 96, 150, 96, RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance | RynthNavPathApiV1.PathQuiet,
|
||||
new AvoidFilter(new PortalAvoid()));
|
||||
Check(all.Code == RynthNavPathApiV1.ResultPartial, "with every flag at once too");
|
||||
var reach = Ex(q, 40, 96, 60, 150, RynthNavPathApiV1.PathAllowPartial);
|
||||
Check(reach.Code == RynthNavPathApiV1.ResultOk && !reach.Partial, "a goal it can reach is ResultOk, flag or not");
|
||||
}
|
||||
|
||||
private static void PathExNoMeshAndStartSnap()
|
||||
{
|
||||
var q = QueryOn(Bake("exsnap", (10, 10, 70, 180), (110, 10, 180, 180)));
|
||||
var far = Ex(q, 40, 96, 2000, 2000, 0);
|
||||
Check(far.Code == RynthNavPathApiV1.ResultNoMesh && far.Note.Contains("goal"), $"no tile at the goal: ResultNoMesh ({far.Note})");
|
||||
var gap = Ex(q, 90, 96, 40, 96, 0);
|
||||
Check(gap.Code == RynthNavPathApiV1.ResultNoMesh && gap.Note.Contains("start"), $"a start 20 u from any ground: ResultNoMesh ({gap.Note})");
|
||||
var off = Ex(q, 73, 96, 40, 96, 0);
|
||||
Check(off.Code == RynthNavPathApiV1.ResultOk && off.Corners[0].X < 69 && off.Corners[0].X > 60, $"a start a few yards off the mesh: the wide search finds the ground beside it ({(off.Corners.Count > 0 ? off.Corners[0].X : 0):F1})");
|
||||
|
||||
// A roof over part of a floor (3.5 u up: room to walk under it).
|
||||
var rq = QueryOn(BakeLayers("exroof", (0, 0, 192, 192, 0f), (60, 60, 130, 130, 3.5f)));
|
||||
var under = Ex(rq, 95, 95, 20, 95, 0, sz: 0.1);
|
||||
Check(under.Code == RynthNavPathApiV1.ResultOk && Math.Abs(under.Corners[0].Z) < 1, $"a start under a roof starts on the floor ({(under.Corners.Count > 0 ? under.Corners[0].Z : double.NaN):F2})");
|
||||
var onTop = Ex(rq, 95, 95, 100, 100, 0, sz: 3.6, gz: 3.6);
|
||||
Check(onTop.Code == RynthNavPathApiV1.ResultOk && Math.Abs(onTop.Corners[0].Z - 3.5) < 1, "one standing on the roof starts on the roof");
|
||||
var down = Ex(rq, 95, 95, 20, 95, RynthNavPathApiV1.PathAllowPartial, sz: 3.6, gz: 0);
|
||||
Check(down.Code == RynthNavPathApiV1.ResultPartial, "and the roof has no way down: partial");
|
||||
}
|
||||
|
||||
private static void PathExWallsAndBuffer()
|
||||
{
|
||||
// The wall: from the south of tile 0 to the south of tile 2, the only way is round the north.
|
||||
var q = QueryOn(Bake("exwall", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192)));
|
||||
var bare = Ex(q, 100, 20, 480, 20, 0);
|
||||
Check(bare.Code == RynthNavPathApiV1.ResultOk && bare.Corners.Count >= 4 && bare.Corners.Exists(c => c.Y > 150), $"round the wall through the north passage ({bare.Corners.Count} corners)");
|
||||
Check(bare.Length > 380 * 1.3 && bare.Length < 380 * 1.5, $"the length goes north and back ({bare.Length:F0}u, 380u straight)");
|
||||
var walls = Ex(q, 100, 20, 480, 20, RynthNavPathApiV1.PathWallClearance, clearance: 1.0);
|
||||
Check(walls.Code == RynthNavPathApiV1.ResultOk && walls.Pushed > 0 && walls.Corners.Count == bare.Corners.Count, $"PathWallClearance: corners pushed off the walls ({walls.Pushed})");
|
||||
int moved = 0; bool byClearance = true, away = true, onMesh = true;
|
||||
var plain = new DtQueryDefaultFilter();
|
||||
for (int i = 1; i + 1 < walls.Corners.Count && i < bare.Corners.Count; i++)
|
||||
{
|
||||
var a = bare.Corners[i]; var b = walls.Corners[i];
|
||||
double d = Flat(a, b.X, b.Y);
|
||||
onMesh &= NavPathQuery.OnMesh(q, plain, b.X, b.Y, (float)b.Z);
|
||||
if (d < 0.01) continue;
|
||||
moved++;
|
||||
byClearance &= Math.Abs(d - 1.0) < 0.01;
|
||||
// Away from the wall's own corner (the void is x 192..384, y 0..150).
|
||||
double ca = Math.Min(Flat(a, 192, 150), Flat(a, 384, 150)), cb = Math.Min(Flat(b, 192, 150), Flat(b, 384, 150));
|
||||
away &= cb > ca + 0.5;
|
||||
}
|
||||
Check(moved == walls.Pushed && byClearance, $"each moved corner moved the clearance, 1 u ({moved} moved)");
|
||||
Check(away, "out from the wall it turns round, not into it");
|
||||
Check(onMesh, "every corner on walkable ground");
|
||||
var zero = Ex(q, 100, 20, 480, 20, RynthNavPathApiV1.PathWallClearance, clearance: 0);
|
||||
Check(zero.Pushed == 0 && Math.Abs(zero.Length - bare.Length) < 1e-9, "a clearance of 0: nothing moves");
|
||||
|
||||
// More corners than the caller has room for.
|
||||
Check(Ex(q, 100, 20, 480, 20, 0, maxCorners: 2).Code == RynthNavPathApiV1.ResultNoPath, "no room for the corners: ResultNoPath (FindPath's rule)");
|
||||
var cut = Ex(q, 100, 20, 480, 20, RynthNavPathApiV1.PathAllowPartial, maxCorners: 3);
|
||||
Check(cut.Code == RynthNavPathApiV1.ResultPartial && cut.Corners.Count == 3 && cut.Truncated && cut.EndDistance > 6,
|
||||
$"with PathAllowPartial: the first stretch, partial ({cut.Corners.Count} corners, {cut.EndDistance:F0}u left)");
|
||||
}
|
||||
|
||||
private static void RaycastOnTheMesh()
|
||||
{
|
||||
var open = QueryOn(Bake("rayfloor", (0, 0, 192, 192)));
|
||||
Check(NavPathQuery.Raycast(open, 30, 96, 0, 160, 96, 0, out float t1) == RynthNavPathApiV1.RayClear && t1 >= 1, "open ground: clear");
|
||||
Check(NavPathQuery.Raycast(open, 30, 96, 0, 30, 96, 0, out _) == RynthNavPathApiV1.RayClear, "no distance at all: clear");
|
||||
var isl = QueryOn(Bake("rayisland", (10, 10, 70, 180), (110, 10, 180, 180)));
|
||||
Check(NavPathQuery.Raycast(isl, 40, 96, 0, 150, 96, 0, out float t2) == RynthNavPathApiV1.RayBlocked && t2 > 0.2f && t2 < 0.4f,
|
||||
$"across the gap: blocked at the island's edge (t {t2:F2})");
|
||||
Check(NavPathQuery.Raycast(isl, 90, 96, 0, 40, 96, 0, out _) == RynthNavPathApiV1.ResultNoMesh, "a start off the mesh: ResultNoMesh");
|
||||
Check(NavPathQuery.Raycast(isl, 40, 96, 0, 2000, 2000, 0, out _) == RynthNavPathApiV1.ResultNoMesh, "no mesh at the goal: ResultNoMesh");
|
||||
var wall = QueryOn(Bake("raywall", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192)));
|
||||
Check(NavPathQuery.Raycast(wall, 100, 20, 0, 480, 20, 0, out _) == RynthNavPathApiV1.RayBlocked, "straight through the wall: blocked");
|
||||
Check(NavPathQuery.Raycast(wall, 100, 20, 0, 100, 170, 0, out _) == RynthNavPathApiV1.RayClear, "north on open ground: clear");
|
||||
Check(NavPathQuery.Raycast(wall, 100, 170, 0, 480, 170, 0, out _) == RynthNavPathApiV1.RayClear, "along the passage, over two tile seams: clear");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The real map (read only, when it's installed): FindPathEx and Raycast round Holtburg on the tiles
|
||||
/// a short query loads, a ring of goals at 40/80/150 u; the answers agree, and how long they take.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// RynthAi's hunt into buildings (2026-10-25) walks to a door's step out (BuildingMap: 1.5 m out of
|
||||
/// the door, at its foot) and asks RynthNav where the ground is there (a path from the step to
|
||||
/// itself): within 3 yd across and 1.5 in height it is a door from the ground. The steps of
|
||||
/// Holtburg's doors (A9B4, as BuildingMap finds them on the real dats) on the real tiles.
|
||||
/// </summary>
|
||||
private static void RealDoorsteps()
|
||||
{
|
||||
string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData";
|
||||
if (!File.Exists(Path.Combine(dir, "nav_A9B4.tile"))) { Console.WriteLine(" (no real NavData here: skipped)"); return; }
|
||||
var nav = new DtNavMesh();
|
||||
nav.Init(new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 64, maxPolys = 1 << 16 }, 6);
|
||||
Check(NavPathQuery.TileBox(0xA9 * 192 + 96, 0xB4 * 192 + 96, 0xA9 * 192 + 96, 0xB4 * 192 + 96, NavPathQuery.DefaultMaxTiles, true, out int x0, out int y0, out int x1, out int y1), "A9B4's box");
|
||||
for (int x = x0; x <= x1; x++)
|
||||
for (int y = y0; y <= y1; y++)
|
||||
{
|
||||
uint lb = (uint)((x << 8) | y);
|
||||
if (File.Exists(Path.Combine(dir, $"nav_{lb:X4}.tile"))) nav.AddTile(ReadTile(dir, lb), 0, 0, out _);
|
||||
}
|
||||
var q = new DtNavMeshQuery(nav);
|
||||
// (door cell, step out x, y, z): every A9B4 door BuildingMap offers (its log, 2026-10-25).
|
||||
var steps = new (string Cell, double X, double Y, double Z)[]
|
||||
{
|
||||
("A9B40102", 32537.1, 34698.0, 67.0), ("A9B40107", 32527.6, 34700.5, 66.8), ("A9B4010B", 32519.6, 34691.5, 66.0),
|
||||
("A9B40113", 32474.7, 34714.7, 66.0), ("A9B40114", 32473.7, 34721.9, 67.0), ("A9B40115", 32482.7, 34714.6, 66.0),
|
||||
("A9B40116", 32598.0, 34688.1, 67.0), ("A9B40118", 32595.5, 34690.6, 66.0), ("A9B40119", 32608.8, 34695.0, 66.0),
|
||||
("A9B4011F", 32560.2, 34695.8, 70.0), ("A9B40120", 32555.4, 34702.6, 67.0), ("A9B40122", 32549.0, 34702.6, 67.0),
|
||||
("A9B40124", 32560.2, 34693.4, 66.0), ("A9B40125", 32552.2, 34702.6, 66.0), ("A9B4012B", 32499.3, 34694.9, 66.0),
|
||||
("A9B4012C", 32505.3, 34701.4, 66.0), ("A9B40133", 32506.9, 34701.4, 70.0), ("A9B40139", 32575.2, 34719.3, 66.0),
|
||||
("A9B4013D", 32585.8, 34708.7, 66.0), ("A9B4014C", 32577.6, 34578.6, 95.0), ("A9B4014F", 32587.4, 34581.0, 94.8),
|
||||
("A9B40150", 32580.5, 34578.6, 94.0), ("A9B40164", 32568.0, 34596.0, 94.0), ("A9B40165", 32544.0, 34596.0, 94.0),
|
||||
("A9B4016C", 32522.7, 34592.7, 94.0), ("A9B4016D", 32521.7, 34599.9, 95.0), ("A9B4016E", 32530.7, 34592.6, 94.0),
|
||||
("A9B40170", 32603.4, 34577.5, 94.0), ("A9B40177", 32508.8, 34716.5, 66.2), ("A9B40179", 32603.9, 34595.0, 96.0),
|
||||
("A9B4017F", 32605.3, 34667.5, 66.0), ("A9B40184", 32478.7, 34614.6, 78.0), ("A9B40189", 32556.1, 34649.0, 80.0),
|
||||
};
|
||||
int flags = RynthNavPathApiV1.PathWallClearance | RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet;
|
||||
var r = new PathExResult();
|
||||
int ground = 0;
|
||||
var off = new List<string>();
|
||||
foreach (var (cell, x, y, z) in steps)
|
||||
{
|
||||
int code = NavPathQuery.FindPathEx(q, x, y, z, x, y, z, flags, 64, null, 1.0, r);
|
||||
bool ok = code is RynthNavPathApiV1.ResultOk or RynthNavPathApiV1.ResultPartial && r.Corners.Count > 0;
|
||||
double flat = 99, dz = 99;
|
||||
if (ok)
|
||||
{
|
||||
var c = r.Corners[^1];
|
||||
flat = Math.Sqrt((c.X - x) * (c.X - x) + (c.Y - y) * (c.Y - y));
|
||||
dz = c.Z - z;
|
||||
}
|
||||
if (ok && flat <= 3 && Math.Abs(dz) <= 1.5) ground++;
|
||||
else off.Add($"{cell} ({(ok ? $"{flat:F1} across, {dz:+0.0;-0.0} high" : $"code {code}")})");
|
||||
}
|
||||
Console.WriteLine($" A9B4 doorsteps on RynthNav's ground: {ground} of {steps.Length}; not: {string.Join(", ", off)}");
|
||||
// 2026-10-25: 32 of 33; A9B4011F's step is 3.8 above the ground (an upper door with no floor under its step).
|
||||
Check(ground >= 30, $"Holtburg's door steps are on the ground ({ground} of {steps.Length})");
|
||||
Check(off.Any(o => o.StartsWith("A9B4011F")), "the upper door A9B4011F's isn't (the hunt leaves it alone)");
|
||||
}
|
||||
|
||||
private static void RealPathEx()
|
||||
{
|
||||
string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData";
|
||||
if (!File.Exists(Path.Combine(dir, "nav_A9B4.tile"))) { Console.WriteLine(" (no real NavData here: skipped)"); return; }
|
||||
var centre = RynthCore.Plugin.RynthNav.WorldPt.FromMap(42.08, 33.6);
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
var nav = new DtNavMesh();
|
||||
var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 64, maxPolys = 1 << 16 };
|
||||
nav.Init(prm, 6);
|
||||
int loaded = 0;
|
||||
Check(NavPathQuery.TileBox(centre.X, centre.Y, centre.X, centre.Y, NavPathQuery.DefaultMaxTiles, true, out int x0, out int y0, out int x1, out int y1), "Holtburg's box");
|
||||
for (int x = x0; x <= x1; x++)
|
||||
for (int y = y0; y <= y1; y++)
|
||||
{
|
||||
uint lb = (uint)((x << 8) | y);
|
||||
if (!File.Exists(Path.Combine(dir, $"nav_{lb:X4}.tile"))) continue;
|
||||
if (nav.AddTile(ReadTile(dir, lb), 0, 0, out _).Succeeded()) loaded++;
|
||||
}
|
||||
long loadMs = sw.ElapsedMilliseconds;
|
||||
var q = new DtNavMeshQuery(nav);
|
||||
|
||||
// The start: walkable ground at the town's centre (it's under a roof in places; the snap finds the ground).
|
||||
var plain = new DtQueryDefaultFilter();
|
||||
q.FindNearestPoly(new RcVec3f((float)centre.X, 0, (float)centre.Y), new RcVec3f(30, 600, 30), plain, out long sRef, out RcVec3f s0, out _);
|
||||
Check(sRef != 0, "ground at Holtburg's centre");
|
||||
if (sRef == 0) return;
|
||||
double sx = s0.X, sy = s0.Z, sz = s0.Y;
|
||||
|
||||
int flags = RynthNavPathApiV1.PathWallClearance | RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet;
|
||||
var counts = new Dictionary<int, int>();
|
||||
int rays = 0, clear = 0, agree = 0, compared = 0, queries = 0;
|
||||
double worst = 1, pathMs = 0, rayMs = 0;
|
||||
bool infoOk = true;
|
||||
var r = new PathExResult();
|
||||
var paths = new List<(double gx, double gy, double gz, double len)>();
|
||||
foreach (double dist in new[] { 40.0, 80.0, 150.0 })
|
||||
for (int k = 0; k < 8; k++)
|
||||
{
|
||||
double a = k * Math.PI / 4;
|
||||
double gx = sx + Math.Cos(a) * dist, gy = sy + Math.Sin(a) * dist;
|
||||
// A goal on the ground there (a monster stands on it), else the raw spot.
|
||||
q.FindNearestPoly(new RcVec3f((float)gx, (float)sz, (float)gy), new RcVec3f(2, 64, 2), plain, out long gr, out RcVec3f gp, out _);
|
||||
double gz = gr != 0 ? gp.Y : sz;
|
||||
long t0 = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
int code = NavPathQuery.FindPathEx(q, sx, sy, sz, gx, gy, gz, flags, 64, null, 1.0, r);
|
||||
pathMs += System.Diagnostics.Stopwatch.GetElapsedTime(t0).TotalMilliseconds; queries++;
|
||||
counts[code] = counts.GetValueOrDefault(code) + 1;
|
||||
if (code is RynthNavPathApiV1.ResultOk or RynthNavPathApiV1.ResultPartial)
|
||||
{
|
||||
infoOk &= Math.Abs(r.Length - Legs(r)) < 1e-6 && r.Corners.Count >= 2 && r.Corners.Count <= 64
|
||||
&& (code == RynthNavPathApiV1.ResultPartial) == r.Partial;
|
||||
if (code == RynthNavPathApiV1.ResultOk) paths.Add((gx, gy, gz, r.Length));
|
||||
}
|
||||
t0 = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
int ray = NavPathQuery.Raycast(q, sx, sy, sz, gx, gy, gz, out _);
|
||||
rayMs += System.Diagnostics.Stopwatch.GetElapsedTime(t0).TotalMilliseconds; rays++;
|
||||
if (ray == RynthNavPathApiV1.RayClear)
|
||||
{
|
||||
clear++;
|
||||
// A clear straight walk: the planned path is (about) the straight line.
|
||||
if (code == RynthNavPathApiV1.ResultOk)
|
||||
{
|
||||
compared++;
|
||||
double straight = Math.Sqrt((r.Corners[^1].X - sx) * (r.Corners[^1].X - sx) + (r.Corners[^1].Y - sy) * (r.Corners[^1].Y - sy));
|
||||
double ratio = straight < 1 ? 1 : r.Length / straight;
|
||||
worst = Math.Max(worst, ratio);
|
||||
if (ratio < 1.25) agree++;
|
||||
else Console.WriteLine($" clear ray, path x{ratio:F2}: goal ({gx - sx:F0},{gy - sy:F0}) from the start, {r.Corners.Count} corners, {r.Polys} polys, pushed {r.Pushed}: " + string.Join(" ", r.Corners.Select(c => $"({c.X - sx:F1},{c.Y - sy:F1},{c.Z - sz:F1})")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Portals: one on the way of each of the longer paths, kept out of (or the plain path when there's no way round).
|
||||
int portalTried = 0, keptOut = 0, fellBack = 0;
|
||||
foreach (var p in paths)
|
||||
{
|
||||
if (p.len < 30) continue;
|
||||
NavPathQuery.FindPathEx(q, sx, sy, sz, p.gx, p.gy, p.gz, 0, 64, null, 1.0, r);
|
||||
if (r.Corners.Count < 2) continue;
|
||||
var mid = (X: (r.Corners[0].X + r.Corners[1].X) / 2, Y: (r.Corners[0].Y + r.Corners[1].Y) / 2);
|
||||
if (Flat(r.Corners[0], mid.X, mid.Y) < PortalAvoid.LiveRadius + 3) continue; // the start would be inside it
|
||||
var spots = new PortalAvoid();
|
||||
spots.Set(new[] { new PortalAvoid.Spot(mid.X, mid.Y, PortalAvoid.LiveRadius, "test portal") }, Array.Empty<PortalAvoid.Spot>());
|
||||
int code = NavPathQuery.FindPathEx(q, sx, sy, sz, p.gx, p.gy, p.gz, flags | RynthNavPathApiV1.PathAvoidPortals, 64, new AvoidFilter(spots), 1.0, r);
|
||||
if (code is not (RynthNavPathApiV1.ResultOk or RynthNavPathApiV1.ResultPartial)) continue;
|
||||
portalTried++;
|
||||
if (Closest(r, mid.X, mid.Y) >= PortalAvoid.LiveRadius - 0.01) keptOut++;
|
||||
if (r.FellBack) fellBack++;
|
||||
}
|
||||
|
||||
// A typical short query, many times (the tiles already loaded, as in a hunt).
|
||||
var pick = paths.Count > 0 ? paths[0] : (sx + 40, sy, sz, 0.0);
|
||||
int reps = 500;
|
||||
long tr = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
for (int i = 0; i < reps; i++) NavPathQuery.FindPathEx(q, sx, sy, sz, pick.Item1, pick.Item2, pick.Item3, flags | RynthNavPathApiV1.PathAvoidPortals, 64, null, 1.0, r);
|
||||
double perPath = System.Diagnostics.Stopwatch.GetElapsedTime(tr).TotalMilliseconds / reps;
|
||||
tr = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
for (int i = 0; i < reps; i++) NavPathQuery.Raycast(q, sx, sy, sz, pick.Item1, pick.Item2, pick.Item3, out _);
|
||||
double perRay = System.Diagnostics.Stopwatch.GetElapsedTime(tr).TotalMilliseconds / reps;
|
||||
|
||||
string tally = string.Join(", ", counts.OrderBy(kv => -kv.Key).Select(kv => $"{(kv.Key switch { 1 => "ok", 2 => "partial", 0 => "no path", _ => "no mesh" })} {kv.Value}"));
|
||||
Console.WriteLine($" Holtburg: {loaded} tiles read in {loadMs} ms; {queries} FindPathEx ({tally}), {pathMs / queries:F2} ms each cold; "
|
||||
+ $"Raycast {clear}/{rays} clear, {rayMs / rays:F3} ms each; clear rays vs paths {agree}/{compared} near-straight (worst x{worst:F2}); "
|
||||
+ $"portal on the way: kept out {keptOut}/{portalTried} ({fellBack} plain fallback); a short query {perPath:F3} ms, its ray {perRay:F3} ms");
|
||||
Check(loaded >= 9, $"Holtburg's 3x3 tiles ({loaded})");
|
||||
Check(counts.GetValueOrDefault(RynthNavPathApiV1.ResultOk) >= 12, "most of the ring is reached");
|
||||
Check(infoOk, "info consistent with the corners on every path");
|
||||
Check(compared == 0 || agree >= compared - 1, $"a clear ray's path is the straight line (or near it): {agree}/{compared}");
|
||||
Check(portalTried == 0 || keptOut + fellBack >= portalTried, $"a portal on the way is kept out of, or the plain path is taken ({keptOut}+{fellBack}/{portalTried})");
|
||||
Check(perPath < 20 && perRay < 5, $"fast enough to ask several times a second ({perPath:F3} / {perRay:F3} ms)");
|
||||
}
|
||||
|
||||
// ── The navmesh view (NavMeshView) ───────────────────────────────────────────
|
||||
|
||||
private sealed class TriSink : RynthCore.Plugin.Shared.INav3DSink
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
<!--
|
||||
Offline tests for RynthNav's long-range route graph: region building (NavRegions), the
|
||||
baker's portal matching and costs (GraphBuild), the file format and A* (NavGraph) and the
|
||||
route follower (NavCoarse). Tiles are baked here from small made-up floors with the same
|
||||
route follower (NavCoarse), and the "RynthNav.Path" interface's FindPathEx and Raycast
|
||||
(NavPathQuery). Tiles are baked here from small made-up floors with the same
|
||||
Recast settings as the baker, written to %TEMP%, and removed afterwards.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
|
|
@ -13,6 +14,8 @@
|
|||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>RynthNav.GraphTests</RootNamespace>
|
||||
<!-- The linked RynthNav.Path contract holds function pointers. -->
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
@ -33,6 +36,9 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavCoords.cs" Link="Linked\NavCoords.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TownNet.cs" Link="Linked\TownNet.cs" />
|
||||
<Compile Include="..\RynthNav.PortalGraph\PortalRoute.cs" Link="Linked\PortalRoute.cs" />
|
||||
<!-- "RynthNav.Path" v2 (FindPathEx, Raycast) and the walker's planning steps it shares; the contract it answers. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavPathQuery.cs" Link="Linked\NavPathQuery.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\RynthNavPathApi.cs" Link="Linked\RynthNavPathApi.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ internal static partial class Program
|
|||
RunTravelPlan();
|
||||
RunTripExport();
|
||||
RunAutoRunGate();
|
||||
RunSteering();
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(_fails == 0 && _asserts > 0
|
||||
|
|
|
|||
|
|
@ -31,6 +31,8 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TravelPlan.cs" Link="Linked\TravelPlan.cs" />
|
||||
<!-- The goto's autorun, sent when it changes (AutoRunGateTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AutoRunGate.cs" Link="Linked\AutoRunGate.cs" />
|
||||
<!-- The goto's heading servo and path follower (SteeringTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\WalkSteer.cs" Link="Linked\WalkSteer.cs" />
|
||||
<!-- The planned trip, its path, the path markers and "save as nav route" (TripExportTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPlan.cs" Link="Linked\TripPlan.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPath.cs" Link="Linked\TripPath.cs" />
|
||||
|
|
|
|||
212
Tools/RynthNav.RouteTests/SteeringTests.cs
Normal file
212
Tools/RynthNav.RouteTests/SteeringTests.cs
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthNav.RouteTests;
|
||||
|
||||
// The goto's steering (WalkSteer, PathFollow). 11-01: "whenever I use auto navigation mode (Select
|
||||
// coordinates) it bounces left and right a lot with a lot of stopping": 862 turns and 21 stops in
|
||||
// 107 s of one goto. The old servo stopped the run for anything over 20 degrees and each path corner
|
||||
// was run to within 1.5 m, overshot and turned back to. A simulated character walks made-up paths
|
||||
// round buildings with the old and the new settings.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunSteering()
|
||||
{
|
||||
Run(nameof(ServoSmallCorrectionsOnTheRun), ServoSmallCorrectionsOnTheRun);
|
||||
Run(nameof(ServoBigTurnStandsAndResumes), ServoBigTurnStandsAndResumes);
|
||||
Run(nameof(ServoTurnRateLimited), ServoTurnRateLimited);
|
||||
Run(nameof(PathFollowCutsOnlyInPlainView), PathFollowCutsOnlyInPlainView);
|
||||
Run(nameof(UnstickPicksOpenGround), UnstickPicksOpenGround);
|
||||
Run(nameof(SimulatedWalkRoundBuildings), SimulatedWalkRoundBuildings);
|
||||
}
|
||||
|
||||
private static void ServoSmallCorrectionsOnTheRun()
|
||||
{
|
||||
var s = new WalkSteer();
|
||||
double t = s.Step(5, 0, 1000, out bool run);
|
||||
Check(run && double.IsNaN(t), "5 degrees off while running: no turn (dead zone), still running");
|
||||
t = s.Step(35, 0, 1100, out run);
|
||||
Check(run && !double.IsNaN(t) && t > 0 && t <= 35, $"35 degrees off: turns on the run ({t:F1})");
|
||||
var old = WalkSteer.Legacy();
|
||||
old.Step(35, 0, 1000, out bool oldRun);
|
||||
Check(!oldRun, "the old servo stopped the run for 35 degrees");
|
||||
Check(Math.Abs(WalkSteer.Diff(350, 10) + 20) < 1e-9 && Math.Abs(WalkSteer.Diff(10, 350) - 20) < 1e-9, "the shortest way round north");
|
||||
t = s.Step(345, 5, 1300, out _);
|
||||
Check(!double.IsNaN(t) && (t < 5 || t > 340), $"from 5 to 345 it turns left across north ({t:F1})");
|
||||
}
|
||||
|
||||
private static void ServoBigTurnStandsAndResumes()
|
||||
{
|
||||
var s = new WalkSteer();
|
||||
long now = 1000;
|
||||
double h = 0;
|
||||
s.Step(120, h, now, out bool run);
|
||||
Check(!run && s.TurnInPlace, "120 degrees off: stops to turn");
|
||||
int ticks = 0;
|
||||
while (!run && ticks++ < 200)
|
||||
{
|
||||
now += 18;
|
||||
double t = s.Step(120, h, now, out run);
|
||||
if (!double.IsNaN(t)) h = t;
|
||||
}
|
||||
Check(run && Math.Abs(WalkSteer.Diff(120, h)) <= 20.0 + 1e-9, $"runs again once within 20 degrees ({h:F1} after {ticks} ticks)");
|
||||
Check(ticks * 18 < 600, $"a 120 degree turn takes under 0.6 s ({ticks * 18} ms)");
|
||||
}
|
||||
|
||||
private static void ServoTurnRateLimited()
|
||||
{
|
||||
var s = new WalkSteer();
|
||||
int sent = 0;
|
||||
double h = 0;
|
||||
for (long now = 1000; now < 2000; now += 18)
|
||||
{
|
||||
double t = s.Step(h + 30, h, now, out _); // a target that keeps moving away
|
||||
if (!double.IsNaN(t)) { sent++; h = t; }
|
||||
}
|
||||
Check(sent <= 21, $"at most 20 turns a second (sent {sent} in 1 s; the old servo: one every tick, 56)");
|
||||
var old = WalkSteer.Legacy();
|
||||
int oldSent = 0; h = 0;
|
||||
for (long now = 1000; now < 2000; now += 18)
|
||||
{
|
||||
double t = old.Step(h + 30, h, now, out _);
|
||||
if (!double.IsNaN(t)) { oldSent++; h = t; }
|
||||
}
|
||||
Check(oldSent >= 50, $"(the old one sent {oldSent})");
|
||||
}
|
||||
|
||||
private static void PathFollowCutsOnlyInPlainView()
|
||||
{
|
||||
var path = new List<(double X, double Y)> { (0, 0), (10, 0), (10, 10), (20, 10) };
|
||||
Check(PathFollow.Advance(path, 1, 6, 0, 1.5, 7, 6, null) == 1, "without a view check: the corner is run to");
|
||||
Check(PathFollow.Advance(path, 1, 6, 0, 1.5, 7, 6, (ax, ay, bx, by) => true) == 2, "4 m from it with the next corner in view: on to the next");
|
||||
Check(PathFollow.Advance(path, 1, 6, 0, 1.5, 7, 6, (ax, ay, bx, by) => false) == 1, "...not when something is between");
|
||||
Check(PathFollow.Advance(path, 1, 2, 0, 1.5, 7, 6, (ax, ay, bx, by) => true) == 1, "not from farther than the look-ahead");
|
||||
Check(PathFollow.Advance(path, 1, 9, 0, 1.5, 7, 6, null) == 2, "within the corner reach: passed");
|
||||
Check(PathFollow.Advance(path, 3, 15, 10, 1.5, 7, 6, (ax, ay, bx, by) => true) == 4, "the end is reached at the arrival distance");
|
||||
}
|
||||
|
||||
private static void UnstickPicksOpenGround()
|
||||
{
|
||||
Check(Math.Abs(WalkSteer.UnstickHeading(0, 1, null) - 100) < 1e-9, "no view check: 100 degrees off on the given side");
|
||||
Check(Math.Abs(WalkSteer.UnstickHeading(0, -1, h => true) - 260) < 1e-9, "the other side when asked");
|
||||
// A river bank on the right (every heading from 30 to 180 blocked): the left.
|
||||
double left = WalkSteer.UnstickHeading(0, 1, h => !(h >= 30 && h <= 180));
|
||||
Check(Math.Abs(left - 260) < 1e-9, $"open ground on the other side ({left:F0})");
|
||||
Check(Math.Abs(WalkSteer.UnstickHeading(90, 1, h => false) - 270) < 1e-9, "nothing open: straight back");
|
||||
}
|
||||
|
||||
// ── A simulated walk ───────────────────────────────────────────────────────────
|
||||
|
||||
private sealed record Building(double X, double Y, double R);
|
||||
|
||||
private sealed class WalkResult
|
||||
{
|
||||
public bool Arrived;
|
||||
public double Seconds, Travelled, MinClearance = double.MaxValue;
|
||||
public int Turns, Stops;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A path like Detour's: every other corner turns 25..45 degrees round a round building, both
|
||||
/// legs tangent to its eroded edge (building radius + the 2 m agent radius); the corners
|
||||
/// between are 5..15 degree bends on open ground (polygon edges), nothing near.
|
||||
/// </summary>
|
||||
private static (List<(double X, double Y)> Path, List<Building> Buildings) WeavingPath()
|
||||
{
|
||||
var path = new List<(double X, double Y)> { (0, 0) };
|
||||
var buildings = new List<Building>();
|
||||
var rng = new Random(11_01);
|
||||
double x = 0, y = 0, heading = 45;
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
double leg = 6 + rng.NextDouble() * 8;
|
||||
x += Math.Sin(heading * Math.PI / 180) * leg; y += Math.Cos(heading * Math.PI / 180) * leg;
|
||||
path.Add((x, y));
|
||||
int sign = (i / 2) % 2 == 0 ? 1 : -1;
|
||||
bool round = i % 2 == 0;
|
||||
double turn = sign * (round ? 25 + rng.NextDouble() * 20 : 5 + rng.NextDouble() * 10);
|
||||
if (round)
|
||||
{
|
||||
// The building on the inside of the turn, tangent to both legs at the agent radius.
|
||||
double inner = heading + (turn > 0 ? 90 : -90) + turn / 2;
|
||||
double r = 3 + rng.NextDouble() * 3;
|
||||
double d = (r + 2) / Math.Cos(Math.Abs(turn) / 2 * Math.PI / 180);
|
||||
buildings.Add(new Building(x + Math.Sin(inner * Math.PI / 180) * d, y + Math.Cos(inner * Math.PI / 180) * d, r));
|
||||
}
|
||||
heading += turn;
|
||||
}
|
||||
x += Math.Sin(heading * Math.PI / 180) * 20; y += Math.Cos(heading * Math.PI / 180) * 20;
|
||||
path.Add((x, y));
|
||||
return (path, buildings);
|
||||
}
|
||||
|
||||
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, cy = ay + dy * t;
|
||||
return Math.Sqrt((px - cx) * (px - cx) + (py - cy) * (py - cy));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Walks the path at 30 ticks a second: the heading is what the last turn set (TurnToHeading is
|
||||
/// instant), a run covers 10 u/s, a stop halts at once, and a run takes 0.4 s to get going again
|
||||
/// (in the 11-01 log a stop and the run after it are 0.3..0.6 s apart).
|
||||
/// </summary>
|
||||
private static WalkResult Walk(List<(double X, double Y)> path, List<Building> buildings, WalkSteer servo, bool lookahead)
|
||||
{
|
||||
const long TickMs = 33;
|
||||
const double RunSpeed = 10.0, AgentRadius = 2.0;
|
||||
const long StartUpMs = 400;
|
||||
bool Clear(double ax, double ay, double bx, double by)
|
||||
{
|
||||
foreach (Building b in buildings) if (SegDist(b.X, b.Y, ax, ay, bx, by) < b.R + AgentRadius - 1e-6) return false;
|
||||
return true;
|
||||
}
|
||||
var res = new WalkResult();
|
||||
double x = path[0].X, y = path[0].Y;
|
||||
double h = Math.Atan2(path[1].X - x, path[1].Y - y) * 180 / Math.PI;
|
||||
int idx = 0;
|
||||
bool running = false;
|
||||
long runSince = 0;
|
||||
long now = 1_000_000;
|
||||
for (int tick = 0; tick < 30 * 180; tick++)
|
||||
{
|
||||
now += TickMs;
|
||||
idx = PathFollow.Advance(path, idx, x, y, 1.5, 7.0, 6.0, lookahead ? Clear : null);
|
||||
if (idx >= path.Count) { res.Arrived = true; break; }
|
||||
double desired = WalkSteer.Norm(Math.Atan2(path[idx].X - x, path[idx].Y - y) * 180 / Math.PI);
|
||||
double t = servo.Step(desired, h, now, out bool run);
|
||||
if (!double.IsNaN(t)) { res.Turns++; h = t; }
|
||||
if (running && !run) res.Stops++;
|
||||
if (!running && run) runSince = now;
|
||||
running = run;
|
||||
double step = running && now - runSince >= StartUpMs ? RunSpeed * TickMs / 1000.0 : 0;
|
||||
x += Math.Sin(h * Math.PI / 180) * step; y += Math.Cos(h * Math.PI / 180) * step;
|
||||
res.Travelled += step;
|
||||
foreach (Building b in buildings)
|
||||
res.MinClearance = Math.Min(res.MinClearance, Math.Sqrt((x - b.X) * (x - b.X) + (y - b.Y) * (y - b.Y)) - b.R);
|
||||
res.Seconds += TickMs / 1000.0;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
private static void SimulatedWalkRoundBuildings()
|
||||
{
|
||||
var (path, buildings) = WeavingPath();
|
||||
double len = 0;
|
||||
for (int i = 1; i < path.Count; i++) len += Math.Sqrt((path[i].X - path[i - 1].X) * (path[i].X - path[i - 1].X) + (path[i].Y - path[i - 1].Y) * (path[i].Y - path[i - 1].Y));
|
||||
WalkResult old = Walk(path, buildings, WalkSteer.Legacy(), lookahead: false);
|
||||
WalkResult now = Walk(path, buildings, new WalkSteer(), lookahead: true);
|
||||
Console.WriteLine($" {path.Count} corners, {buildings.Count} buildings, {len:F0} u: old {old.Seconds:F1} s, {old.Stops} stops, {old.Turns} turns, clearance {old.MinClearance:F1} u; "
|
||||
+ $"new {now.Seconds:F1} s, {now.Stops} stops, {now.Turns} turns, clearance {now.MinClearance:F1} u");
|
||||
Check(old.Arrived && now.Arrived, "both walks arrive");
|
||||
Check(old.Stops >= 10, $"the old servo stops at the corners ({old.Stops} stops)");
|
||||
Check(now.Stops <= old.Stops / 4, $"far fewer stops ({now.Stops} vs {old.Stops})");
|
||||
Check(now.Turns * 4 <= old.Turns * 3, $"a quarter fewer turn commands or better ({now.Turns} vs {old.Turns})");
|
||||
Check(now.Seconds < old.Seconds * 0.85, $"quicker ({now.Seconds:F1} s vs {old.Seconds:F1} s)");
|
||||
Check(now.MinClearance >= 1.0, $"never closer than 1 m to a building ({now.MinClearance:F2} u)");
|
||||
Check(now.Travelled < len * 1.05, $"no wandering: walked {now.Travelled:F0} u of a {len:F0} u path");
|
||||
}
|
||||
}
|
||||
173
Tools/RynthSort.Tests/PackColumnTests.cs
Normal file
173
Tools/RynthSort.Tests/PackColumnTests.cs
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
using RynthCore.Plugin.RynthSort.Ui;
|
||||
using RynthCore.Plugin.RynthSort.Views;
|
||||
|
||||
namespace RynthSort.Tests
|
||||
{
|
||||
// Pack numbers against the game's pack column: which containers are packs, the column's order
|
||||
// with foci, wielded and unloaded containers in it, why an order isn't known, and what each
|
||||
// pack's header says and does (icon, Select in game, its place in the column).
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void PackColumnKinds()
|
||||
{
|
||||
Check(InventoryReader.IsSidePack(false, true, 24, 0), "a pack whose capacity reads (empty): a pack");
|
||||
Check(!InventoryReader.IsSidePack(false, true, 0, 0), "a focus (capacity 0): not a pack");
|
||||
Check(!InventoryReader.IsSidePack(true, true, 24, 3), "a wielded container: not a pack");
|
||||
Check(InventoryReader.IsSidePack(false, false, 0, 5), "capacity not read yet but items inside: a pack (else every pack below it is numbered one too high)");
|
||||
Check(!InventoryReader.IsSidePack(false, false, 0, 0), "capacity not read and nothing inside: not guessed");
|
||||
}
|
||||
|
||||
private static void PackColumnOrder()
|
||||
{
|
||||
// Column, top first: pack 3, a focus, pack 1, pack 2. The main pack itself in the list changes nothing.
|
||||
SortInventory inv = Inv(3);
|
||||
Check(inv.ApplyPackOrder(new uint[] { 0x40000003, 0x40000F01, 0x40000001, Me, 0x40000002 }, 5), "foci and the main pack's own id in the list");
|
||||
Check(inv.PackOrderKnown && inv.OrderSource == PackOrderSource.Known, "known");
|
||||
Eq(string.Join(",", inv.Packs.Select(p => p.Id & 0xF)), "3,1,2", "pack 1 is the top pack");
|
||||
Eq(string.Join(",", inv.Packs.Select(p => p.ColumnSlot)), "1,3,5", "each pack's slot in the column, foci counted");
|
||||
Eq(inv.ColumnEntries, 5, "the column's entries");
|
||||
|
||||
// A wielded container is never read as a pack, so the column (main pack only) needn't have it.
|
||||
SortInventory worn = Inv(2);
|
||||
Check(worn.ApplyPackOrder(new uint[] { 0x40000002, 0x40000001 }, 2), "only carried packs need be in the column");
|
||||
|
||||
// An unloaded pack (read through its items) that the engine's list lacks.
|
||||
SortInventory miss = Inv(3);
|
||||
Check(!miss.ApplyPackOrder(new uint[] { 0x40000003, 0x40000001 }, 2), "a pack the list lacks: not known");
|
||||
Check(miss.OrderSource == PackOrderSource.Mismatch && miss.MissingFromColumn == 1, "says it is a mismatch, one pack short");
|
||||
Check(miss.Packs.All(p => p.ColumnSlot == 0), "no column slots claimed");
|
||||
Eq(string.Join(",", miss.Packs.Select(p => p.Id & 0xF)), "1,2,3", "object-id order kept (as the engine's Inventory panel falls back to)");
|
||||
|
||||
// A later good read clears the mismatch.
|
||||
Check(miss.ApplyPackOrder(new uint[] { 0x40000002, 0x40000003, 0x40000001 }, 3) && miss.MissingFromColumn == 0, "a full list again: known");
|
||||
|
||||
// The log lines (one when the source changes).
|
||||
Check(InventoryReader.OrderSourceLine(inv).Contains("follow the pack column"), "log: known");
|
||||
SortInventory notSeen = Inv(2);
|
||||
notSeen.OrderSource = PackOrderSource.NotSeen;
|
||||
Check(InventoryReader.OrderSourceLine(notSeen).Contains("no pack column list"), "log: not seen");
|
||||
Check(InventoryReader.OrderSourceLine(new SortInventory()).Contains("API 80"), "log: no engine support");
|
||||
Check(InventoryReader.OrderSourceLine(Inv(3).With(i => i.ApplyPackOrder(new uint[] { 0x40000001 }, 1))).Contains("lacks 2 of 3"), "log: a mismatch, counted");
|
||||
}
|
||||
|
||||
private static SortInventory With(this SortInventory inv, Action<SortInventory> a)
|
||||
{
|
||||
a(inv);
|
||||
return inv;
|
||||
}
|
||||
|
||||
private static SortView ViewOf(SortInventory inv)
|
||||
{
|
||||
var p = new SortPlanner();
|
||||
p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0);
|
||||
return p.View;
|
||||
}
|
||||
|
||||
private static void PackColumnLabels()
|
||||
{
|
||||
Eq(string.Join(",", new[] { 1, 2, 3, 4, 11, 12, 13, 21, 22, 23, 101, 111 }.Select(SortPanel.Ordinal)),
|
||||
"1st,2nd,3rd,4th,11th,12th,13th,21st,22nd,23rd,101st,111th", "ordinals");
|
||||
|
||||
SortInventory inv = Inv(3);
|
||||
for (uint i = 0; i < 14; i++) inv.Packs[2].Items.Add(It(500 + i, "Salvaged Iron", ObjectClasses.Salvage));
|
||||
inv.ApplyPackOrder(new uint[] { 0x40000003, 0x40000F01, 0x40000001, 0x40000002 }, 4);
|
||||
SortView v = ViewOf(inv);
|
||||
Check(v.PackOrderKnown && v.OrderSource == PackOrderSource.Known, "the view carries the order");
|
||||
Eq(v.Packs[0].ColumnSlot, 1, "the view carries each pack's slot");
|
||||
Eq(SortPanel.WhereText(v, v.Packs[0], 1), "1st pack from the top of the pack column - 14/24 items", "the top pack");
|
||||
Eq(SortPanel.WhereText(v, v.Packs[1], 2), "2nd pack from the top of the pack column - 0/24 items", "a pack below a focus: its pack number");
|
||||
Check(SortPanel.PackHeaderTooltip(v, 2).Contains("also shows the focus above it, so there it is the 3rd entry"), "and the tooltip says where the retail window has it");
|
||||
Check(!SortPanel.PackHeaderTooltip(v, 1).Contains("also shows"), "no focus above: nothing extra");
|
||||
string tip = SortPanel.PackHeaderTooltip(v, 1);
|
||||
Check(tip.StartsWith("Your Pack 3: 14 of 24 items (Salvage).", StringComparison.Ordinal), "header tooltip: which pack, its count and contents");
|
||||
Check(tip.Contains("It is the 1st pack from the top of your inventory's pack column."), "header tooltip: where it is");
|
||||
Check(tip.Contains("Select in game"), "header tooltip: how to see it in the game");
|
||||
Eq(SortPanel.NumberingNote(v), "", "known: no note above the packs");
|
||||
|
||||
SortInventory unknown = Inv(2);
|
||||
unknown.OrderSource = PackOrderSource.NotSeen;
|
||||
SortView u = ViewOf(unknown);
|
||||
Eq(SortPanel.WhereText(u, u.Packs[1], 2), "Place in the pack column not known - 0/24 items", "unknown: says so");
|
||||
Check(SortPanel.PackHeaderTooltip(u, 2).Contains("isn't known right now") && !SortPanel.PackHeaderTooltip(u, 2).Contains("from the top"), "unknown: the tooltip claims no place");
|
||||
Check(SortPanel.NumberingNote(u).Contains("hasn't seen your pack list") && SortPanel.NumberingNote(u).Contains("Log out and back in"), "not seen: why and the fix");
|
||||
unknown.ApplyPackOrder(new uint[] { 0x40000002 }, 1);
|
||||
Check(SortPanel.NumberingNote(ViewOf(unknown)).Contains("missing a pack"), "mismatch: why");
|
||||
Check(SortPanel.NumberingNote(ViewOf(Inv(2))).Contains("plugin API 80"), "no engine support: why");
|
||||
Eq(SortPanel.NumberingNote(ViewOf(Inv(0))), "", "no side packs: no note");
|
||||
}
|
||||
|
||||
private static void PackColumnWindow()
|
||||
{
|
||||
var c = new SortController();
|
||||
var selected = new List<uint>();
|
||||
var panel = new SortPanel(c, () => { })
|
||||
{
|
||||
Character = () => "Someone",
|
||||
Icons = () => true,
|
||||
CanSelect = () => true,
|
||||
SelectInGame = id => { selected.Add(id); return true; },
|
||||
};
|
||||
var host = new UiHost();
|
||||
UiWindow w = host.Add(new UiWindow("RynthSort/Main", "RynthSort") { Visible = true });
|
||||
SortInventory inv = Inv(3);
|
||||
Fill(inv.Packs[1], 5, 1000);
|
||||
inv.ApplyPackOrder(new uint[] { 0x40000002, 0x40000F01, 0x40000003, 0x40000001 }, 4);
|
||||
c.Planner.Plan(inv, c.Data.Rules, SortScope.Main, true, 0, 0);
|
||||
|
||||
Draw(w, panel);
|
||||
ParseAll(host, "pack headers with icons and Select", out int ops);
|
||||
Check(ops > 10 && ops < 1500, $"ops in range ({ops})");
|
||||
string body = BodyText(w);
|
||||
Check(body.Contains("Pack 1: Pack 2 (5/24)"), "the top pack (id 2) is pack 1");
|
||||
Check(body.Contains("Select in game###select.40000002") && body.Contains("Select in game###select.40000001"), "a Select in game button per pack");
|
||||
Check(body.Contains("1st pack from the top of the pack column - 5/24 items"), "where it is, with its item count");
|
||||
Check(body.Contains("2nd pack from the top of the pack column - 0/24 items"), "the next pack, below a focus");
|
||||
Check(body.Contains("so there it is the 3rd entry"), "the focus above it: said in its tooltip");
|
||||
Check(body.Contains("Selects this pack in the game"), "the button says what it does");
|
||||
Check(!body.Contains("oldest pack first, not"), "known: no numbering note");
|
||||
Check(ContainsOp(w.Body, UiFormat.OpImage), "the pack's icon drawn");
|
||||
w.MarkSubmitted(true);
|
||||
|
||||
Apply(host, Event(1, 1, w.Hash, w.KeyOf("select.40000003"), Click));
|
||||
Eq(string.Join(",", selected.Select(x => x.ToString("X8"))), "40000003", "Select in game selects that pack's object");
|
||||
Draw(w, panel);
|
||||
ParseAll(host, "after Select", out _);
|
||||
Check(BodyText(w).Contains("the game has your Pack 3 selected now"), "and says so under it");
|
||||
|
||||
// Without icon support or selection, neither is drawn (the layout doesn't shift on old engines).
|
||||
panel.Icons = () => false;
|
||||
panel.CanSelect = () => false;
|
||||
Draw(w, panel);
|
||||
ParseAll(host, "old engine", out _);
|
||||
Check(!BodyText(w).Contains("Select in game###") && !ContainsOp(w.Body, UiFormat.OpImage), "no icon or Select button when the engine can't");
|
||||
Check(BodyText(w).Contains("pack from the top of the pack column"), "the place is still said");
|
||||
|
||||
// Order unknown: the note above the packs, and no place claimed.
|
||||
SortInventory lost = Inv(2);
|
||||
lost.OrderSource = PackOrderSource.NotSeen;
|
||||
c.Planner.Plan(lost, c.Data.Rules, SortScope.Main, true, 0, 0);
|
||||
Draw(w, panel);
|
||||
ParseAll(host, "order unknown", out _);
|
||||
body = BodyText(w);
|
||||
Check(body.Contains("Pack numbers here go oldest pack first") && body.Contains("Log out and back in"), "the note says why and the fix");
|
||||
Check(body.Contains("Place in the pack column not known"), "each pack says its place isn't known");
|
||||
}
|
||||
|
||||
/// <summary>Whether the display list has an op of this kind (each op: u8 code, u8 flags, u16 payload length, payload).</summary>
|
||||
private static bool ContainsOp(ReadOnlySpan<byte> body, byte op)
|
||||
{
|
||||
int at = 0;
|
||||
while (at + 4 <= body.Length)
|
||||
{
|
||||
if (body[at] == op) return true;
|
||||
at += 4 + System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(body[(at + 2)..]);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -272,11 +272,11 @@ namespace RynthSort.Tests
|
|||
Eq(SortPanel.ShownPack(p.View, rule), 2, "the rule is listed under pack 2");
|
||||
SortPanel.SetPack(rule, p.View, 6);
|
||||
Check(rule.Pack == 6 && rule.PackId == 0 && rule.PackNote == "", "a number you don't have: no id");
|
||||
Check(!p.View.PackOrderKnown && SortPanel.PackTooltip(p.View).Contains("list order") && !SortPanel.PackTooltip(p.View).Contains("top of the pack column"),
|
||||
Check(!p.View.PackOrderKnown && SortPanel.PackTooltip(p.View).Contains("may not match") && !SortPanel.PackTooltip(p.View).Contains("top pack"),
|
||||
"pack order unknown: the tooltip doesn't claim screen order");
|
||||
inv.PackOrderKnown = true;
|
||||
p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0);
|
||||
Check(SortPanel.PackTooltip(p.View).Contains("top of the pack column"), "pack order known: numbered from the top");
|
||||
Check(SortPanel.PackTooltip(p.View).Contains("Pack 1 is the top pack in your inventory's pack column"), "pack order known: numbered from the top");
|
||||
|
||||
// Warnings sit with their pack: a rule that fell back to a number is listed (and warned
|
||||
// about) under the pack it uses; rules whose pack isn't carried are grouped by that pack.
|
||||
|
|
|
|||
|
|
@ -82,6 +82,10 @@ namespace RynthSort.Tests
|
|||
Run("store: old rules migrate to version 3", RuleMigration);
|
||||
Run("order: inside a pack (A-Z, fewest moves, every order of up to 7)", InPackOrder);
|
||||
Run("order: slot orders and the pack column", SlotOrders);
|
||||
Run("pack column: which containers are packs (foci, wielded, unloaded)", PackColumnKinds);
|
||||
Run("pack column: order with foci, wielded and unloaded packs, and why it isn't known", PackColumnOrder);
|
||||
Run("pack column: what a pack header says (place, count, why not known)", PackColumnLabels);
|
||||
Run("pack column: icons and Select in game in the window", PackColumnWindow);
|
||||
Run("plan: stacks and order inside packs", PlanInPack);
|
||||
Run("moves: answers for moves within a pack", MoveAnswersInPlace);
|
||||
Run("replies: every /rsort word answers", Replies);
|
||||
|
|
|
|||
Loading…
Reference in a new issue