RynthSuite/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs

913 lines
46 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
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;
// 2026-10-12: with Looting on, a chest the player or a meta opened is looted by the corpse
// looter (RynthAiPlugin.ChestLoot.cs): matching items picked up, the rest left, no walk and no
// open, closed when done, never marked done for good (chests regenerate). Not the player's own
// packs, not house storage, nothing with Looting off.
internal static class ChestLootTests
{
private const uint Player = 0x50000D01;
private const uint Chest = 0x7A9B4001; // a landblock chest (static id)
private const uint Gem = 0x80263101;
private const uint Spoon = 0x80263102;
private const uint Gem2 = 0x80263103;
private const uint Cap = 0x80263104;
private const uint SidePack = 0x80263200;
private const uint PackGem = 0x80263201;
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800, ItemTypeMisc = 0x80, ItemTypeArmor = 0x2;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("chest loot: an opened chest's matching items are picked up, the rest left; no walk, no open, closed when done", OpenedChestLooted);
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 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: Pickup with macro off leaves the chest open and says so with Leave the chest open (off by default: it closes it)", PickupLeavesChestOpen);
r.Add("chest loot (R-20261120-173459-ea5d): Pickup with macro off taking nothing leaves the chest open, Leave the chest open or not", PickupTakingNothingLeavesOpen);
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);
r.Add("chest loot: an open chest is looted before a fight further than 5 yd off (a chest closes when you walk away)", OpenChestBeforeDistantFight);
r.Add("chest loot: closed mid-loot -> the looter opens it again and takes the rest", ClosedMidLootReopened);
r.Add("chest loot: a chest that keeps closing is opened again twice in a minute, then left", ReopenIsBounded);
r.Add("chest loot: a chest the player opened with the macro off is not reopened when it closes", ManualChestNotReopened);
r.Add("chest loot: Pickup with macro off opens a chest the client closed out of reach again, once, and takes the rest", ManualChestClosedOutOfReachReopened);
r.Add("chest loot: Pickup with macro off: no use radius readable -> moved away counts, standing still is the player's close", ManualChestReopenWithoutRadius);
r.Add("chest loot: Pickup with macro off: something else opened before the reopen -> it is dropped", ManualChestReopenDroppedForOtherOpen);
r.Add("chest loot: Pickup with macro off with the macro on and Looting off: the reopen waits for the fight", ManualChestReopenWaitsForFight);
r.Add("chest loot: an open chest that closes before the looter gets to it (a fight had the tick) is opened again", ClosedBeforeTakenReopened);
r.Add("chest loot: no jump-loot from a chest (a hop can take the character out of its use radius)", NoJumpLootFromChest);
r.Add("chest loot: a chest gets 2 minutes (not the 12 s corpse timeout), restarted by each pickup", ChestTimeoutLongAndRestarted);
r.Add("chest loot: an item the server would refuse for burden (past 300%) is left unsent, with a chat line; one that fits still goes", OverBurdenLeft);
r.Add("loot burden: ACE's carrying capacity and 300% limit", OverBurdenMath);
}
// ── World set-up ──────────────────────────────────────────────────────────
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
private static void BaseWorld(string chestName = "Chest")
{
FakeHost.Reset();
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
FakeHost.Names[Player] = "Dargoth Hera";
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[Chest] = chestName;
FakeHost.ItemTypes[Chest] = ItemTypeContainer;
FakeHost.Positions[Chest] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
FakeHost.NotAttackable.Add(Chest);
FakeHost.Containers[Chest] = 0; // lies in the world (ownership readable, nobody holds it)
AddItem(Gem, "Black Opal", ItemTypeGem, Chest);
AddItem(Spoon, "Rusty Spoon", ItemTypeMisc, Chest);
}
private static void AddItem(uint id, string name, uint type, uint container)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = type;
FakeHost.Containers[id] = container;
FakeHost.Appraised.Add(id);
}
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new()
{
IsMacroRunning = true,
EnableLooting = true,
EnableCombat = false,
LootOwnership = 0,
LootContentSettleMs = 0,
LootEmptyCorpseMs = 0,
StopLootingWhenPackFull = false,
};
public readonly WorldObjectCache Cache;
public Bot(RynthCoreHost host, bool salvageRule = false)
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true); // a stand-in with its profile in memory
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Cache = new WorldObjectCache(host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
string profile = Path.Combine(Program.TempRoot, salvageRule ? "loot-chest-salvage.json" : "loot-chest-test.json");
var p = new LootProfile { Name = "chest" };
var gems = new LootRule { Name = "Gems", Action = LootAction.Keep };
gems.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
p.Rules.Add(gems);
if (salvageRule)
{
var armor = new LootRule { Name = "Salvage armor", Action = LootAction.Salvage };
armor.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Armor });
p.Rules.Add(armor);
}
p.Save(profile);
S.CurrentLootPath = profile;
}
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);
public bool HasLootWork() => (bool)Call("HasLootWork", S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!;
public void Tick(BotActivity act = BotActivity.Looting)
{
Set("_activity", act);
Call("TickCorpseOpening");
}
public void Create(params uint[] ids)
{
foreach (uint id in ids) Cache.OnCreateObject(id);
Cache.Tick();
}
/// <summary>The server opens <paramref name="container"/> for the player (ViewContents, then the inventory update).</summary>
public void ServerOpens(uint container)
{
FakeHost.GroundContainer = container;
P.OnViewObjectContents(container);
P.OnUpdateObjectInventory(container);
}
/// <summary>The server's answer to a close: the window goes.</summary>
public void ServerCloses(uint container)
{
if (FakeHost.GroundContainer == container) FakeHost.GroundContainer = 0;
P.OnStopViewingObjectContents(container);
}
public void TickUntil(Func<bool> done, int max = 200)
{
for (int i = 0; i < max && !done(); i++)
{
Tick();
Thread.Sleep(10);
}
}
public void TickFor(int ms, BotActivity act = BotActivity.Looting)
{
long end = Environment.TickCount64 + ms;
while (Environment.TickCount64 < end)
{
Tick(act);
Thread.Sleep(10);
}
}
public bool Moved(uint id) => FakeHost.ExternalMoves.Any(m => m.Id == id);
public bool Marked(uint id) => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)id));
}
private static string Moves() => string.Join(",", FakeHost.ExternalMoves.Select(m => $"{m.Id:X8}->{m.Target:X8}"));
/// <summary>Loots the chest's gem: picked up, lands in the pack, the chest is closed. Returns the bot.</summary>
private static void LootGemAndFinish(Bot bot, uint gem)
{
bot.TickUntil(() => bot.Moved(gem));
Check.True(FakeHost.ExternalMoves.Contains((gem, Player, 0)), $"the gem 0x{gem:X8} is moved into the main pack (moves: {Moves()})");
int closesBefore = FakeHost.Closes.Count;
FakeHost.Containers[gem] = Player; // it lands in the pack
bot.TickUntil(() => FakeHost.Closes.Count > closesBefore);
}
// ── Tests ─────────────────────────────────────────────────────────────────
private static void OpenedChestLooted()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
Check.False(bot.HasLootWork(), "a closed chest is no loot work");
bot.ServerOpens(Chest);
Check.True(bot.HasLootWork(), "an open chest is loot work (the arbiter gives Looting the tick, nav stops)");
LootGemAndFinish(bot, Gem);
Check.False(bot.Moved(Spoon), "the spoon matches nothing and stays in the chest");
Check.False(FakeHost.Uses.Contains(Chest), "no open sent: the chest was open already");
Check.False(FakeHost.AutoRunCalls.Any(on => on), "no walk toward it");
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Chest:X8}", "closed once when done, as a finished corpse is");
Check.False(bot.Marked(Chest), "never put in the completed-corpse set");
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the looter lets go of it");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: looting open chest")), "the start is logged as Chest loot");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: picking up") && l.Contains($"{Gem:X8}")), "the pickup is logged as Chest loot");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: done with chest")), "the finish is logged");
// The server's answer to the close; nothing more happens.
bot.ServerCloses(Chest);
bot.TickFor(100);
Check.Eq(FakeHost.Closes.Count, 1, "still one close");
Check.False(bot.HasLootWork(), "no loot work left");
}
// R-20261123-065337-d200: a kept item past the burden limit was refused 94 ms after each send with
// no code, read as "too busy" and sent 6 times a chest (the Item Tool keyed the chest again).
private static void OverBurdenLeft()
{
foreach ((int gemBurden, bool fits) in new[] { (1_500, false), (1_000, true) })
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
// Strength 100, one carrying capacity augmentation: capacity 18,000, the server's limit 54,000.
FakeHost.Attributes[(Player, 1u, 0)] = 100;
FakeHost.Ints[(Player, 230u)] = 1;
FakeHost.Ints[(Player, 5u)] = 53_000;
FakeHost.Ints[(Gem, 5u)] = gemBurden; // 54,500: over; 54,000: exactly the limit, allowed
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
if (fits)
{
LootGemAndFinish(bot, Gem);
Check.False(FakeHost.Logs.Any(l => l.Contains("too heavy")), "at the limit: nothing left for burden");
continue;
}
bot.TickUntil(() => FakeHost.Closes.Count > 0);
Check.False(FakeHost.ExternalMoves.Any(m => m.Item1 == Gem), $"over the limit: no move sent (moves: {Moves()})");
Check.True(FakeHost.Logs.Any(l => l.Contains("too heavy") && l.Contains($"{Gem:X8}") && l.Contains("54500")),
"the log says why, with the numbers");
Check.True(FakeHost.Chat.Any(l => l.Contains("Too heavy to loot") && l.Contains("300%")), "one chat line says why");
Check.Eq(FakeHost.Closes.Count, 1, "the chest is still finished and closed");
}
}
private static void OverBurdenMath()
{
Check.Eq(RynthAiPlugin.CarryCapacity(100, 0), 15_000L, "150 per Strength");
Check.Eq(RynthAiPlugin.CarryCapacity(100, 5), 30_000L, "plus 30 per Strength per augmentation");
Check.False(RynthAiPlugin.PickupOverBurdenLimit(44_000, 1_000, 100, 0, out long limit), "exactly 300%: the server takes it");
Check.Eq(limit, 45_000L, "the limit is 3 x capacity");
Check.True(RynthAiPlugin.PickupOverBurdenLimit(44_001, 1_000, 100, 0, out _), "one over: refused");
Check.False(RynthAiPlugin.PickupOverBurdenLimit(90_000, 1_000, 0, 0, out _), "no Strength known: the server decides");
Check.False(RynthAiPlugin.PickupOverBurdenLimit(90_000, 0, 100, 0, out _), "no burden known on the item: the server decides");
}
private static void ChestTimeoutLongAndRestarted()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootCorpseTimeoutMs = 12000;
// A corpse keeps the setting.
bot.Set("_targetCorpseId", 0x7A9B4002);
Check.Eq((int)bot.Call("GetCorpseTimeoutMs", bot.S)!, 12000, "a corpse: the Corpse Timeout setting");
// A chest: 2 minutes, or the setting when that is longer.
bot.Set("_targetCorpseId", unchecked((int)Chest));
bot.Set("_lootChestId", unchecked((int)Chest));
Check.Eq((int)bot.Call("GetCorpseTimeoutMs", bot.S)!, RynthAiPlugin.ChestLootTimeoutMs, "a chest: ChestLootTimeoutMs");
Check.Eq(RynthAiPlugin.ChestLootTimeoutMs, 120_000, "2 minutes");
bot.S.LootCorpseTimeoutMs = 300_000;
Check.Eq((int)bot.Call("GetCorpseTimeoutMs", bot.S)!, 300_000, "a longer Corpse Timeout still wins");
bot.S.LootCorpseTimeoutMs = 12000;
// 100 s into the session, a pickup: the clock restarts, so the session isn't timed out.
long now = 1_000_000;
bot.Set("_corpseTargetSince", now - 100_000);
bot.Set("_currentLootItemId", unchecked((int)Gem));
bot.Call("ConfirmCurrentLootItemMoved", now, "test");
Check.Eq(bot.Get<long>("_corpseTargetSince"), now, "a confirmed pickup restarts the chest's clock");
Check.False((bool)bot.Call("HasCorpseTimedOut", bot.S, now + 119_000)!, "119 s after the last pickup: still going");
Check.True((bool)bot.Call("HasCorpseTimedOut", bot.S, now + 120_000)!, "120 s with no pickup: timed out");
// A corpse pickup doesn't touch the corpse clock.
bot.Set("_lootChestId", 0);
bot.Set("_targetCorpseId", 0x7A9B4002);
bot.Set("_corpseTargetSince", now - 5_000);
bot.Set("_currentLootItemId", unchecked((int)Gem2));
bot.Call("ConfirmCurrentLootItemMoved", now, "test");
Check.Eq(bot.Get<long>("_corpseTargetSince"), now - 5_000, "a corpse keeps one timeout for the whole corpse");
}
private static void OwnSidePackNotLooted()
{
BaseWorld();
FakeHost.Names[SidePack] = "Pack";
FakeHost.ItemTypes[SidePack] = ItemTypeContainer;
FakeHost.Containers[SidePack] = Player; // in the main pack
AddItem(PackGem, "Black Opal", ItemTypeGem, SidePack);
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(SidePack, PackGem);
bot.ServerOpens(SidePack); // ACE sends ViewContents for side packs at login
Check.False(bot.HasLootWork(), "your own side pack is no loot work");
bot.TickFor(300);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing moved out of your own pack");
Check.Eq(FakeHost.Closes.Count, 0, "and it is not closed");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: not looting") && l.Contains("in your inventory")), "the reason is logged");
// The main pack itself never counts either.
bot.ServerOpens(Player);
Check.False(bot.HasLootWork(), "the main pack is no loot work");
}
private static void HouseStorageNotLooted()
{
BaseWorld();
FakeHost.InstanceIds[(Chest, 32)] = 0x50000ABC; // HouseOwner: a house-linked object of an owned house
var host = FakeHost.Create(Player);
Check.True(host.HasGetObjectInstanceIdProperty, "the host reads STypeIID properties");
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
Check.False(bot.HasLootWork(), "house storage is no loot work");
bot.TickFor(300);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken out of house storage");
Check.Eq(FakeHost.Closes.Count, 0, "and it is left open for the player");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: not looting") && l.Contains("house storage")), "the reason is logged");
}
private static void HouseStorageByNameNotLooted()
{
BaseWorld(chestName: "Storage");
var host = FakeHost.Create(Player);
Check.False(host.HasGetObjectInstanceIdProperty, "no STypeIID read here");
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
Check.False(bot.HasLootWork(), "a container named Storage is no loot work");
bot.TickFor(300);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken");
Check.True(RynthAiPlugin.IsHouseStorageName("Wall Hook"), "hooks are house objects too");
Check.False(RynthAiPlugin.IsHouseStorageName("Ornate Chest"), "a treasure chest is not");
}
private static void LootingOffNothing()
{
BaseWorld();
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);
Check.False(bot.HasLootWork(), "no loot work with Looting off");
bot.TickFor(300, BotActivity.Navigating);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken");
Check.Eq(FakeHost.Closes.Count, 0, "and it is not closed");
Check.False(FakeHost.Logs.Any(l => l.Contains("Chest loot:")), "no chest-loot lines at all");
Check.True(FakeHost.Chat.Any(c => c.Contains("Black Opal") || c.Contains("Rusty Spoon") || c.Contains("loot profile")),
"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 PickupLeavesChestOpen()
{
Check.False(new LegacyUiSettings().LootChestsMacroOffLeaveOpen, "Leave the chest open is off by default (the chest is closed)");
foreach (bool leaveOpen in new[] { true, false })
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.IsMacroRunning = false;
bot.S.LootChestsMacroOffLeaveOpen = leaveOpen;
string what = leaveOpen ? "leave open" : "close";
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Moved(Gem));
FakeHost.Containers[Gem] = Player; // it lands in the pack
if (leaveOpen)
{
bot.TickUntil(() => FakeHost.Chat.Any(c => c.Contains("Left it open")));
Check.Eq(FakeHost.Closes.Count, 0, $"{what}: the chest is not closed");
Check.True(FakeHost.Chat.Any(c => c.Contains("Pickup with macro off: done with") && c.Contains("took 1 item(s)") && c.Contains("Left it open")),
$"{what}: chat says what was taken and that it's open (chat: {string.Join(" | ", FakeHost.Chat)})");
Check.False(bot.HasLootWork(), $"{what}: the looter is done with it");
}
else
{
bot.TickUntil(() => FakeHost.Closes.Count > 0);
Check.Eq(FakeHost.Closes.Count, 1, $"{what}: the chest is closed once when done");
Check.False(FakeHost.Chat.Any(c => c.Contains("Left it open")), $"{what}: no left-open line");
}
}
// The macro's own chest looting (macro and Looting on) still closes: the option is Pickup with macro off's.
BaseWorld();
var h2 = FakeHost.Create(Player);
var b2 = new Bot(h2);
b2.Create(Chest, Gem, Spoon);
b2.ServerOpens(Chest);
LootGemAndFinish(b2, Gem);
Check.Eq(FakeHost.Closes.Count, 1, "macro on: the chest is closed when done, as before");
Check.False(FakeHost.Chat.Any(c => c.Contains("Left it open")), "macro on: no left-open line");
}
// 2026.11.19.1: the player opened a chest by hand to take an item the profile leaves; the pickup matched
// nothing and closed it about 1 ms later, every open, until the setting was turned off.
private static void PickupTakingNothingLeavesOpen()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.IsMacroRunning = false;
bot.S.LootChestsMacroOffLeaveOpen = false; // the default
bot.Create(Chest, Spoon); // only an item the profile leaves
bot.ServerOpens(Chest);
bot.TickUntil(() => FakeHost.Chat.Any(c => c.Contains("Left it open")));
Check.Eq(FakeHost.Closes.Count, 0, "nothing taken: the chest is not closed");
Check.True(FakeHost.Chat.Any(c => c.Contains("Pickup with macro off: done with") && c.Contains("Left it open")),
$"chat says it was left open (chat: {string.Join(" | ", FakeHost.Chat)})");
Check.False(bot.HasLootWork(), "the looter is done with it");
for (int i = 0; i < 20; i++) bot.Tick();
Check.Eq(FakeHost.Closes.Count, 0, "and it stays open");
}
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();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
LootGemAndFinish(bot, Gem);
bot.ServerCloses(Chest);
Check.Eq(FakeHost.Closes.Count, 1, "the first open ends with one close");
// The chest regenerates: a new gem; a meta uses it again.
AddItem(Gem2, "Fire Opal", ItemTypeGem, Chest);
bot.Create(Gem2);
bot.ServerOpens(Chest);
Check.True(bot.HasLootWork(), "the reopened chest is loot work again");
LootGemAndFinish(bot, Gem2);
Check.Eq(FakeHost.Closes.Count, 2, "and is closed again when done");
Check.False(bot.Moved(Spoon), "the spoon is still left");
}
private static void SalvageWithoutUstLeft()
{
BaseWorld();
AddItem(Cap, "Leather Cap", ItemTypeArmor, Chest);
var host = FakeHost.Create(Player);
var bot = new Bot(host, salvageRule: true);
bot.Set("_salvageManager", new SalvageManager(host, bot.S, bot.Cache));
bot.Create(Chest, Gem, Spoon, Cap);
bot.ServerOpens(Chest);
LootGemAndFinish(bot, Gem);
Check.False(bot.Moved(Cap), "the salvage-only cap stays in the chest: no UST to salvage it with");
Check.True(FakeHost.Logs.Any(l => l.Contains("Leather Cap") && l.Contains("no UST carried")), "logged as for corpses");
Check.True(FakeHost.Chat.Any(c => c.Contains("No UST in your pack")), "and said once in chat");
}
private static void ChestWaitsForCombat()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
Check.True(bot.HasLootWork(), "the chest wants the tick");
// Combat owns the tick: nothing taken, the chest waits.
bot.TickFor(300, BotActivity.Combat);
Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken while combat holds the tick");
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the chest isn't taken as the loot container yet");
// The fight ends, the chest is still open: looted.
LootGemAndFinish(bot, Gem);
Check.Eq(FakeHost.Closes.Count, 1, "looted and closed after the fight");
}
private const uint Monster = 0x80263301;
/// <summary>The chest world with a monster <paramref name="meters"/> off and combat on.</summary>
private static Bot ChestWithMonster(float meters, out CombatManager combat)
{
BaseWorld("Unearthed Cache");
FakeHost.Names[Monster] = "Drumtaken Ironstone Golem";
FakeHost.ItemTypes[Monster] = 0x10; // creature
FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + meters, Me0.Y + 0.5f, Me0.Z);
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.EnableCombat = true;
bot.S.MonsterRange = 50;
bot.Create(Chest, Gem, Spoon);
_ = bot.Cache[unchecked((int)Monster)];
bot.Cache.OnUpdateHealth(Monster, 1f);
bot.Cache.Tick();
combat = new CombatManager(host, bot.S, bot.Cache);
combat.SetPlayerId(Player);
typeof(CombatManager).GetField("_lastScanTime", Any)?.SetValue(combat, DateTime.MinValue);
combat.ScanNearbyTargets();
bot.Set("_combatManager", combat);
return bot;
}
// 2026-11-07: a meta opened a treasure cache with a golem 32 m off; combat walked to the golem, the
// cache closed and nothing was taken.
private static void OpenChestBeforeDistantFight()
{
var bot = ChestWithMonster(30f, out var combat);
Check.True(combat.HasEngageableTarget, "a monster 30 m off: combat wants the tick");
Check.False((bool)bot.Call("IsOpenChestTurn", true, true)!, "no chest open: no chest turn");
bot.ServerOpens(Chest);
Check.True(bot.HasLootWork(), "the open chest wants the tick");
Check.True((bool)bot.Call("IsOpenChestTurn", true, true)!, "open chest, nothing within 5 yd: the chest goes first");
Check.False((bool)bot.Call("IsOpenChestTurn", false, true)!, "(only when there is loot work)");
var inputs = new ArbiterInputs(true, false, true, true, false, false, lootStarved: true);
Check.Eq(ActivityArbiter.Decide(in inputs), BotActivity.Looting, "the arbiter gives Looting the tick");
bot.Set("_lootStarveTurn", true);
LootGemAndFinish(bot, Gem);
Check.True(FakeHost.Closes.Count >= 1, "the gem taken before the fight, the chest closed");
Check.True(FakeHost.Logs.Any(l => l.Contains("looted before the fight")), "logged");
Check.Eq(bot.Get<uint>("_lastChestLootedId"), Chest, "ralastchestlooted[] names the chest looted to the end");
var close = ChestWithMonster(2f, out var combat2);
Check.True(combat2.HasCloseThreat(RynthAiPlugin.LootStarveCloseYards), "a monster within 5 yd");
close.ServerOpens(Chest);
Check.False((bool)close.Call("IsOpenChestTurn", true, true)!, "a monster at the chest is fought first");
}
private static int ChestUses() => FakeHost.Uses.Count(u => u == Chest);
// 2026-11-12: the client closes a container once the character is outside its use radius at its
// once-a-second check (a jump-loot hop, the walk back for the next item, a step toward a monster).
// 8 of 134 chest loots in a week of logs ended that way with items left; a corpse was reopened,
// a chest was not.
private static void ClosedMidLootReopened()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Moved(Gem));
Check.True(bot.Moved(Gem), "the gem's move is sent");
// The chest closes before the gem arrives.
bot.ServerCloses(Chest);
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the session ends");
Check.Eq(bot.Get<uint>("_lastChestLootedId"), 0u, "a chest closed mid-loot doesn't count as looted");
Check.Eq(FakeHost.Closes.Count, 0, "nothing to close: it is closed already");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before looting finished; opening it again (1 of 2)")), "logged");
Check.True(bot.HasLootWork(), "the chest to open again is loot work: Looting keeps the tick");
bot.Tick();
Check.Eq(ChestUses(), 0, "not at once: the close settles first");
bot.TickUntil(() => ChestUses() > 0);
Check.Eq(ChestUses(), 1, "then the looter uses the chest to open it again");
bot.TickFor(200);
Check.Eq(ChestUses(), 1, "one use, not one a tick, while it waits for the chest to open");
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "and nothing else is claimed meanwhile");
// It opens: the gem is still in it and is taken, then the chest is closed as usual.
int movesBefore = FakeHost.ExternalMoves.Count;
bot.ServerOpens(Chest);
bot.TickUntil(() => FakeHost.ExternalMoves.Count > movesBefore);
Check.True(FakeHost.ExternalMoves.Count > movesBefore, "the gem's move is sent again");
FakeHost.Containers[Gem] = Player;
bot.TickUntil(() => FakeHost.Closes.Count > 0);
Check.Eq(FakeHost.Closes.Count, 1, "closed when done");
Check.Eq(bot.Get<uint>("_lastChestLootedId"), Chest, "now it counts as looted to the end");
Check.False(bot.Moved(Spoon), "the spoon is still left");
Check.False(bot.Marked(Chest), "and the chest is still never marked");
Check.Eq(ChestUses(), 1, "no further use");
}
private static void ReopenIsBounded()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Moved(Gem));
// It closes mid-loot, is opened again, and closes again: twice.
for (int round = 1; round <= RynthAiPlugin.ChestReopenMax; round++)
{
bot.ServerCloses(Chest);
bot.TickUntil(() => ChestUses() >= round);
Check.Eq(ChestUses(), round, $"close {round}: the looter opens it again");
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Get<int>("_openedContainerId") != 0);
Check.Eq(bot.Get<int>("_openedContainerId"), unchecked((int)Chest), $"close {round}: and takes it again");
}
// The third close in a minute: left alone.
bot.ServerCloses(Chest);
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), RynthAiPlugin.ChestReopenMax, "no third use");
Check.False(bot.HasLootWork(), "and nothing left to do");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("so it is left")), "logged");
}
private static void ManualChestNotReopened()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.IsMacroRunning = false; // Pickup with macro off takes the chest the player opened
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Moved(Gem));
Check.True(bot.Moved(Gem), "the gem's move is sent");
bot.ServerCloses(Chest); // the player closes it
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), 0, "the player's close (where looting began) is the player's: not reopened");
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("not reopening it") && l.Contains("your own close")),
"logged, with why");
}
// ── Pickup with macro off: one reopen of a chest the client closed (2026-11-23) ──────────────
// A treasure cache a script opened closed three times with items left; the LootWindowProbe named
// the client's once-a-second range check (CPlayerSystem::CalculateObjectRangeChecks) each time,
// with the character 2.5-3.7 m off. Salvage was not involved.
private const uint OtherChest = 0x7A9B4005;
private const uint UseRadiusFloat = 54;
/// <summary>Puts the character <paramref name="meters"/> west of the chest (the chest is at Me0.X + 1).</summary>
private static void StandFromChest(float meters)
{
var at = (Me0.Cell, Me0.X + 1.0f - meters, Me0.Y, Me0.Z);
FakeHost.Positions[Player] = at;
FakeHost.PlayerPose = at;
}
/// <summary>Macro off, the chest opened by the player and the gem's pickup sent.</summary>
private static Bot ManualChestMidLoot(bool macroOn = false)
{
var host = FakeHost.Create(Player);
var bot = new Bot(host);
if (macroOn) bot.S.EnableLooting = false; else bot.S.IsMacroRunning = false;
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Moved(Gem));
Check.True(bot.Moved(Gem), "the gem's move is sent");
return bot;
}
private static void ManualChestClosedOutOfReachReopened()
{
BaseWorld();
FakeHost.Doubles[(Chest, UseRadiusFloat)] = 2.0; // the chest's use radius (its PublicWeenieDesc)
var bot = ManualChestMidLoot();
// A step back past its reach: the client's range check closes it.
StandFromChest(3.5f);
bot.ServerCloses(Chest);
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the session ends");
Check.True(FakeHost.Logs.Any(l => l.Contains("Pickup with macro off: chest") && l.Contains("by the client")
&& l.Contains("past its 2.0 m reach") && l.Contains("opening it again (once)")), "booked and logged with why");
Check.False(bot.HasLootWork(), "not macro loot work: the arbiter is not asked for Looting");
bot.Tick();
Check.Eq(ChestUses(), 0, "not at once: the close settles first");
bot.TickUntil(() => ChestUses() > 0);
Check.Eq(ChestUses(), 1, "then the chest is used to open it again");
bot.TickFor(200);
Check.Eq(ChestUses(), 1, "one use while it waits for the chest to open");
// It opens (the server walked the character back): Pickup with macro off takes it again.
StandFromChest(1.0f);
int movesBefore = FakeHost.ExternalMoves.Count;
bot.ServerOpens(Chest);
bot.TickUntil(() => FakeHost.ExternalMoves.Count > movesBefore);
Check.True(FakeHost.ExternalMoves.Count > movesBefore, "the gem's move is sent again");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("Pickup with macro off: looting the opened chest")), 2, "taken a second time");
// It closes out of reach again within the minute: once is all.
StandFromChest(3.5f);
bot.ServerCloses(Chest);
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), 1, "no second reopen in a minute");
Check.True(FakeHost.Logs.Any(l => l.Contains("not reopening it") && l.Contains("opened again once in the last minute")), "logged");
// A close inside its reach is the player's (the close button, a second use): not reopened.
BaseWorld();
FakeHost.Doubles[(Chest, UseRadiusFloat)] = 2.0;
var bot2 = ManualChestMidLoot();
StandFromChest(1.5f);
bot2.ServerCloses(Chest);
bot2.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), 0, "closed within its reach: the player's close, not reopened");
Check.True(FakeHost.Logs.Any(l => l.Contains("not reopening it") && l.Contains("inside its 2.0 m reach") && l.Contains("your own close")), "logged with why");
}
private static void ManualChestReopenWithoutRadius()
{
// No use radius readable: a close after the character moved away is the client's.
BaseWorld();
var bot = ManualChestMidLoot();
StandFromChest(1.0f + (float)RynthAiPlugin.ManualChestMovedMeters + 0.5f);
bot.ServerCloses(Chest);
Check.True(FakeHost.Logs.Any(l => l.Contains("by the client") && l.Contains("farther than when looting began")), "booked: it moved away");
bot.TickUntil(() => ChestUses() > 0);
Check.Eq(ChestUses(), 1, "opened again");
// Standing where looting began (0.2 m is within the margin): the player's close.
BaseWorld();
var bot2 = ManualChestMidLoot();
StandFromChest(1.2f);
bot2.ServerCloses(Chest);
bot2.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), 0, "not reopened");
// Pickup with macro off turned off meanwhile: the booking goes.
BaseWorld();
var bot3 = ManualChestMidLoot();
StandFromChest(3.0f);
bot3.ServerCloses(Chest);
bot3.S.LootChestsMacroOff = false;
bot3.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), 0, "the setting went off: not reopened");
}
private static void ManualChestReopenDroppedForOtherOpen()
{
BaseWorld();
FakeHost.Doubles[(Chest, UseRadiusFloat)] = 2.0;
FakeHost.Names[OtherChest] = "Chest";
FakeHost.ItemTypes[OtherChest] = ItemTypeContainer;
FakeHost.Positions[OtherChest] = (Me0.Cell, Me0.X - 4.0f, Me0.Y, Me0.Z);
FakeHost.NotAttackable.Add(OtherChest);
FakeHost.Containers[OtherChest] = 0;
var bot = ManualChestMidLoot();
bot.Create(OtherChest);
StandFromChest(3.5f);
bot.ServerCloses(Chest);
Check.True(FakeHost.Logs.Any(l => l.Contains("opening it again (once)")), "booked");
// The player opens another chest before the reopen goes out (the server closed the first for it).
bot.ServerOpens(OtherChest);
Check.True(FakeHost.Logs.Any(l => l.Contains("Pickup with macro off: not opening chest") && l.Contains("was opened instead")), "dropped and logged");
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), 0, "the first chest is not used again");
// A vendor opening drops it too.
BaseWorld();
FakeHost.Doubles[(Chest, UseRadiusFloat)] = 2.0;
var bot2 = ManualChestMidLoot();
StandFromChest(3.5f);
bot2.ServerCloses(Chest);
bot2.P.OnVendorOpen(0x7A9B4006);
bot2.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 400);
Check.Eq(ChestUses(), 0, "a vendor opened: not reopened");
}
private static void ManualChestReopenWaitsForFight()
{
BaseWorld();
FakeHost.Doubles[(Chest, UseRadiusFloat)] = 2.0;
var bot = ManualChestMidLoot(macroOn: true); // the macro on, Looting off: Pickup with macro off has the chest
Check.True(FakeHost.Logs.Any(l => l.Contains("Pickup with macro off: looting the opened chest")), "Pickup with macro off took it");
StandFromChest(3.5f); // a step toward a monster
bot.ServerCloses(Chest);
Check.True(FakeHost.Logs.Any(l => l.Contains("opening it again (once)")), "booked");
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 300, BotActivity.Combat);
Check.Eq(ChestUses(), 0, "no use while the fight has the tick");
bot.TickUntil(() => ChestUses() > 0);
Check.Eq(ChestUses(), 1, "used once the fight is over");
}
// The 2026-11-11 20:02 case: a meta opened a cache while the looter was on a corpse; the corpse's
// open closed the cache untouched. Here a fight holds the tick instead: same thing, never taken.
private static void ClosedBeforeTakenReopened()
{
BaseWorld();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickFor(150, BotActivity.Combat);
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "open, but the looter hasn't taken it");
bot.ServerCloses(Chest);
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before the looter got to it; opening it again (1 of 2)")), "booked and logged");
bot.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 200, BotActivity.Combat);
Check.Eq(ChestUses(), 0, "no use while the fight has the tick");
bot.TickUntil(() => ChestUses() > 0);
Check.Eq(ChestUses(), 1, "used once Looting has the tick");
bot.ServerOpens(Chest);
LootGemAndFinish(bot, Gem);
Check.Eq(FakeHost.Closes.Count, 1, "looted and closed");
Check.Eq(bot.Get<uint>("_lastChestLootedId"), Chest, "and counts as looted to the end");
// Looting off: a chest that closes books nothing.
BaseWorld();
var bot2 = new Bot(FakeHost.Create(Player));
bot2.S.LootChestsMacroOff = false;
bot2.S.EnableLooting = false;
bot2.Create(Chest, Gem, Spoon);
bot2.ServerOpens(Chest);
bot2.TickFor(100);
bot2.ServerCloses(Chest);
bot2.S.EnableLooting = true;
bot2.TickFor((int)RynthAiPlugin.ChestReopenDelayMs + 300);
Check.Eq(ChestUses(), 0, "Looting was off when it closed: not reopened");
}
private static void NoJumpLootFromChest()
{
BaseWorld();
FakeHost.TapJumpCalls = true;
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootJumpEnabled = true;
bot.Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
bot.Create(Chest, Gem, Spoon);
bot.ServerOpens(Chest);
bot.TickUntil(() => bot.Get<int>("_openedContainerId") != 0);
Check.False((bool)bot.Call("ShouldJumpLoot", bot.S)!, "no jump-loot while the open container is a chest");
bot.Set("_lootChestId", 0);
Check.True((bool)bot.Call("ShouldJumpLoot", bot.S)!, "control: the same state with a corpse open jumps");
bot.Set("_lootChestId", unchecked((int)Chest));
LootGemAndFinish(bot, Gem);
Check.True(bot.Moved(Gem), "the gem is taken");
Check.Eq(FakeHost.TapJumps, 0, "and no jump was sent for it");
}
}