RynthSuite as of 2026-11-26 (internal 1db112e): release 2026.11.26.1

This commit is contained in:
Tom Bohar 2026-11-26 22:32:31 -05:00
commit 25552fa794
175 changed files with 23428 additions and 494 deletions

View file

@ -455,6 +455,10 @@ internal static class Program
Eq(AutoVendorPlanner.MostCarriedUnit(staleVotes), 5_000_000 / 79, "the vote alone picks the stale price");
Eq(AutoVendorPlanner.TrueUnit(staleVotes, 50_000), 50_000, "a split-off stack's fresh unit wins");
Eq(AutoVendorPlanner.TrueUnit(staleVotes, 0), 5_000_000 / 79, "no fresh unit: the vote");
// R-20261125-011308-9444: a split-off stack split again keeps the old Value: no longer fresh.
Check(AutoVendorPlanner.FreshSplitReading(42, 42), "a split's new stack, untouched: fresh");
Check(!AutoVendorPlanner.FreshSplitReading(42, 1), "split again down to 1: stale (it read 2,100,000 a pea)");
Check(!AutoVendorPlanner.FreshSplitReading(0, 5), "not made by a split: never fresh");
var lastFull = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { PyPea(1, 100) }, Pack(0, free: 44));
Eq(lastFull.Kind, PlanKind.Split, "44 free: split...");
Eq(lastFull.SplitAmount, 21, "...21 off");

View file

@ -132,6 +132,7 @@ internal static class Program
ChestLootTests.Register(runner);
ItemToolTests.Register(runner);
TimedCommandsTests.Register(runner);
CommandButtonsTests.Register(runner);
VanishedItemTests.Register(runner);
KitUsedUpTests.Register(runner);
VitalWandGateTests.Register(runner);
@ -240,6 +241,7 @@ internal static class Program
TinkerTests.Register(runner);
KitRunnerTests.Register(runner);
KitAutoPluginTests.Register(runner);
AmmoAutoPluginTests.Register(runner);
LauncherSwapTests.Register(runner);
MissileCraftingTests.Register(runner);
SelfRatingsTests.Register(runner);
@ -257,9 +259,13 @@ internal static class Program
FellowOpenTests.Register(runner);
WieldBanTests.Register(runner);
ActiveGearTests.Register(runner);
TradeShopPluginTests.Register(runner);
FeatureSearchTests.Register(runner);
FeatureCatalogTests.Register(runner);
AcMapsTests.Register(runner);
LootProfilePickerTests.Register(runner);
RechargeHoldTests.Register(runner);
LosLineTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,616 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using RynthCore.Engine.UI.Sections;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.AcMaps;
using RynthCore.Plugin.RynthAi.Huds;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// ACMAPS Maps (2026-11-26): the player's own ACMAPS dungeon map pack in game (RynthAiPlugin.AcMaps.cs,
// AcMaps/*). The index of a pack folder (images named by landblock, GoArrow's dungeons.txt, a GoArrow
// locations XML), the dungeon position <-> map pixel transform the player sets with "Place me here", the
// settings file, the image decode (Windows' WIC), the texture pieces, the window in the manifest and
// /ra acmaps. Every file these tests write is under the scratch folder; nothing in C:\Games is touched.
internal static class AcMapsTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
public static void Register(Runner r)
{
r.Add("acmaps: landblock from a map's file name (02CA, 0x02CA, 02CA0100, 02CA - Name)", FileNames);
r.Add("acmaps: dungeon list lines (02CA;Name, commas, tabs, reversed, quotes, comments)", DungeonList);
r.Add("acmaps: GoArrow locations XML (dungeon_id, retired, entities, entrance note)", LocationsXml);
r.Add("acmaps: index from files: names from the list, name-only images, parts, problems", BuildIndex);
r.Add("acmaps: scan a real folder (subfolders, other files skipped, missing folder)", ScanFolder);
r.Add("acmaps: search maps by name or landblock", Search);
r.Add("acmaps: one spot places a floor at GoArrow's scale, north up", OneSpot);
r.Add("acmaps: two spots measure the scale; pixel <-> position round trip", TwoSpots);
r.Add("acmaps: floors are separate; near spot moves; third spot replaces the nearer", Floors);
r.Add("acmaps: a mirrored or absurd second spot is refused", Refused);
r.Add("acmaps: clear floor, clear all, nudge scale, bad saved values", ClearAndNudge);
r.Add("acmaps: settings file round trip (folder, announce, spots), bad JSON", SettingsJson);
r.Add("acmaps: image decode size limits and texture pieces", SizesAndPieces);
r.Add("acmaps: decode a GIF and a PNG with Windows' decoder", Decode);
r.Add("acmaps: the chat line when a dungeon has a map", AnnounceLine);
r.Add("acmaps: the window is in the manifest with no bar button", Manifest);
r.Add("acmaps: /ra acmaps opens the window and says what's there; folder, scan, announce reply", Command);
}
private static string Dir(string name)
{
string d = Path.Combine(Program.TempRoot, "acmaps", name);
if (Directory.Exists(d)) Directory.Delete(d, true);
Directory.CreateDirectory(d);
return d;
}
// ── Index ────────────────────────────────────────────────────────────
private static void FileNames()
{
void Yes(string name, ushort lb, string rest)
{
bool ok = AcMapIndex.TryLandblockFromFileName(name, out ushort got, out string r);
Check.True(ok && got == lb && r == rest, $"'{name}' is {lb:X4} '{rest}' (got {ok} {got:X4} '{r}')");
}
void No(string name) => Check.False(AcMapIndex.TryLandblockFromFileName(name, out _, out _), $"'{name}' has no landblock");
Yes("02CA", 0x02CA, "");
Yes("02ca", 0x02CA, "");
Yes("0x02CA", 0x02CA, "");
Yes("02CA0100", 0x02CA, "");
Yes("0x02CA0100", 0x02CA, "");
Yes("02CA - Mosswart Maze", 0x02CA, "Mosswart Maze");
Yes("02CA_Mosswart Maze", 0x02CA, "Mosswart Maze");
Yes("02CA (Mosswart Maze)", 0x02CA, "Mosswart Maze");
Yes("02CA_2", 0x02CA, "2");
No("02CAB");
No("02C");
No("Mosswart Maze");
No("0000");
No("02CA01");
Check.Eq(AcMapIndex.ParseLandblock("02CA"), (ushort)0x02CA, "4 hex");
Check.Eq(AcMapIndex.ParseLandblock(" 0x02ca "), (ushort)0x02CA, "0x, lower case, spaces");
Check.Eq(AcMapIndex.ParseLandblock("02CA0107"), (ushort)0x02CA, "a full cell id: its landblock");
Check.Eq(AcMapIndex.ParseLandblock("2CA"), (ushort)0, "3 digits: not one");
Check.Eq(AcMapIndex.ParseLandblock("zz12"), (ushort)0, "not hex");
Check.Eq(AcMapIndex.NameKey("The Mosswart Maze!"), "themosswartmaze", "name key: letters and digits, lower case");
}
private static void DungeonList()
{
var names = new Dictionary<ushort, string>();
int n = AcMapIndex.ParseDungeonList(
"\uFEFF02CA;Mosswart Maze\r\n" +
"# a comment\n" +
"\n" +
"0x01E3,Abandoned Mine\n" +
"00AB\tTab Dungeon\n" +
"Reversed Hall;0123\n" +
"\"0456\";\"Quoted, Place\"\n" +
"nothing here\n" +
"0789;\n" +
"0ABC;0DEF\n", names);
Check.Eq(n, 5, "five dungeons: " + string.Join(", ", names.Select(k => $"{k.Key:X4}={k.Value}")));
Check.Eq(names.GetValueOrDefault((ushort)0x02CA), "Mosswart Maze", "semicolon (GoArrow's dungeons.txt), BOM skipped");
Check.Eq(names.GetValueOrDefault((ushort)0x01E3), "Abandoned Mine", "0x and a comma");
Check.Eq(names.GetValueOrDefault((ushort)0x00AB), "Tab Dungeon", "a tab");
Check.Eq(names.GetValueOrDefault((ushort)0x0123), "Reversed Hall", "name first");
Check.Eq(names.GetValueOrDefault((ushort)0x0456), "Quoted, Place", "quotes, and the comma inside them kept (the semicolon is the separator)");
Check.False(names.ContainsKey(0x0789), "no name: skipped");
Check.False(names.ContainsKey(0x0ABC), "two ids, no name: skipped");
// A later line for the same dungeon renames it, without counting twice.
Check.Eq(AcMapIndex.ParseDungeonList("02CA;Mosswart Maze (new)", names), 0, "a known dungeon isn't counted again");
Check.Eq(names[0x02CA], "Mosswart Maze (new)", "the later name wins");
}
private const string LocationsXmlSample =
"<?xml version=\"1.0\"?>\n<locations>\n" +
"<location>\n<id>1</id>\n<latitude>25.200</latitude>\n<longitude>19.400</longitude>\n" +
"<restrictions>Level 10+</restrictions>\n<name>Mosswart Maze</name>\n<type>Dungeon</type>\n" +
"<description>Quest(s): Mosswart &amp; friends &#8212; levers.</description>\n<dungeon_id>02CA</dungeon_id>\n<retired>N</retired>\n</location>\n" +
"<location>\n<id>2</id>\n<latitude>-10.000</latitude>\n<longitude>-5.500</longitude>\n<restrictions></restrictions>\n" +
"<name>North West Hole</name>\n<type>Dungeon</type>\n<description></description>\n<dungeon_id>0x0123</dungeon_id>\n</location>\n" +
"<location>\n<id>3</id>\n<name>Old Gone Place</name>\n<type>Dungeon</type>\n<dungeon_id>0456</dungeon_id>\n<retired>Y</retired>\n</location>\n" +
"<location>\n<id>4</id>\n<name>Some Shopkeeper</name>\n<type>NPC</type>\n<dungeon_id></dungeon_id>\n</location>\n" +
"</locations>\n";
private static void LocationsXml()
{
var names = new Dictionary<ushort, string>();
var notes = new Dictionary<ushort, string>();
int n = AcMapIndex.ParseLocationsXml(LocationsXmlSample, names, notes);
Check.Eq(n, 2, "two dungeons (the retired one and the NPC skipped)");
Check.Eq(names.GetValueOrDefault((ushort)0x02CA), "Mosswart Maze", "by dungeon_id");
Check.Eq(names.GetValueOrDefault((ushort)0x0123), "North West Hole", "0x dungeon_id");
Check.False(names.ContainsKey(0x0456), "retired Y: skipped");
string note = notes.GetValueOrDefault((ushort)0x02CA) ?? "";
Check.True(note.StartsWith("Entrance 25.2S, 19.4E.") && note.Contains("Level 10+.") && note.Contains("Mosswart & friends \u2014 levers."),
"the note: entrance (south and east positive), restrictions, description with entities: " + note);
Check.True((notes.GetValueOrDefault((ushort)0x0123) ?? "").StartsWith("Entrance 10.0N, 5.5W."), "north and west are negative in GoArrow's file");
Check.True(AcMapIndex.TryCoord("-22.2", 'S', 'N', out string c) && c == "22.2N", "a coordinate: " + c);
// A name the dungeon list gave is kept.
var named = new Dictionary<ushort, string> { [0x02CA] = "From The List" };
AcMapIndex.ParseLocationsXml(LocationsXmlSample, named, new Dictionary<ushort, string>());
Check.Eq(named[0x02CA], "From The List", "the dungeon list's name wins");
}
private static AcMapIndex SampleIndex() => AcMapIndex.Build(@"C:\maps",
new[]
{
"02CA.gif", "0x01E3.png", "Dead End.png", "Some Unknown Place.jpg", "packs\\0123_2.gif", "packs\\0123.gif",
"dungeons.txt", "data_cod.xml", "readme.txt", "notes.doc",
},
rel => rel switch
{
"dungeons.txt" => "02CA;Mosswart Maze\n01E3;Abandoned Mine\nDEAD;Dead End\n",
"data_cod.xml" => LocationsXmlSample,
"readme.txt" => "These maps are ACMAPS'. Enjoy!",
_ => null,
});
private static void BuildIndex()
{
AcMapIndex index = SampleIndex();
Check.Eq(index.Maps.Count, 6, "six images: " + string.Join(", ", index.Maps.Select(m => m.RelativePath)));
AcMapEntry? moss = index.ForLandblock(0x02CA).FirstOrDefault();
Check.True(moss != null && moss.Name == "Mosswart Maze" && moss.Label == "Mosswart Maze (02CA)", "named from dungeons.txt: " + moss?.Label);
Check.True(moss != null && moss.Notes.Contains("Entrance 25.2S"), "the locations file's note");
Check.Eq(index.ForLandblock(0x01E3).FirstOrDefault()?.Name, "Abandoned Mine", "0x02CA-style name");
Check.Eq(index.ForLandblock(0xDEAD).FirstOrDefault()?.RelativePath, "Dead End.png", "an image named by a listed dungeon's name (Dead End is DEAD in the list)");
AcMapEntry unknown = index.Maps.First(m => m.RelativePath == "Some Unknown Place.jpg");
Check.True(unknown.Landblock == 0 && unknown.Label == "Some Unknown Place", "an unknown name: shown, no landblock");
IReadOnlyList<AcMapEntry> parts = index.ForLandblock(0x0123);
Check.True(parts.Count == 2 && parts.All(p => p.Name == "North West Hole"), "two parts in a subfolder, named by the XML");
Check.True(index.Has(0x02CA) && !index.Has(0x0456), "Has");
Check.Eq(index.NameOf(0x0456), "", "a retired dungeon has no name");
Check.True(index.IndexFiles.Contains("dungeons.txt") && index.IndexFiles.Contains("data_cod.xml") && !index.IndexFiles.Contains("readme.txt"),
"index files: those that named something: " + string.Join(", ", index.IndexFiles));
Check.Eq(index.Problems.Count, 0, "no problems: " + string.Join(" ", index.Problems));
Check.True(index.Summary().StartsWith("6 maps, 4 dungeon names ("), "summary: " + index.Summary());
AcMapIndex none = AcMapIndex.Build(@"C:\x", new[] { "dungeons.txt" }, _ => "02CA;Mosswart Maze");
Check.True(none.Maps.Count == 0 && none.Problems.Count == 1 && none.Problems[0].StartsWith("No map images"), "no images: says so");
AcMapIndex noList = AcMapIndex.Build(@"C:\x", new[] { "02CA.gif" }, _ => null);
Check.True(noList.Maps.Count == 1 && noList.Maps[0].Label == "Dungeon 02CA" && noList.Problems.Any(p => p.Contains("dungeons.txt")),
"no list: shown by landblock, and says so");
AcMapIndex unreadable = AcMapIndex.Build(@"C:\x", new[] { "02CA.gif", "dungeons.txt" }, _ => null);
Check.True(unreadable.Problems.Any(p => p.Contains("Couldn't read dungeons.txt")), "an unreadable list: says so");
}
private static void ScanFolder()
{
string d = Dir("scan");
File.WriteAllBytes(Path.Combine(d, "02CA.gif"), TinyGif);
Directory.CreateDirectory(Path.Combine(d, "more"));
File.WriteAllBytes(Path.Combine(d, "more", "01E3.GIF"), TinyGif);
File.WriteAllText(Path.Combine(d, "dungeons.txt"), "02CA;Mosswart Maze\n01E3;Abandoned Mine\n");
File.WriteAllText(Path.Combine(d, "blacklist.xml"), "<blacklist></blacklist>");
File.WriteAllText(Path.Combine(d, "thumbs.db"), "x");
AcMapIndex index = AcMapIndex.Scan(d);
Check.Eq(index.Maps.Count, 2, "two images, one in a subfolder: " + string.Join(", ", index.Maps.Select(m => m.RelativePath)));
Check.True(index.Has(0x02CA) && index.Has(0x01E3), "both landblocks");
Check.Eq(index.ForLandblock(0x01E3)[0].RelativePath, Path.Combine("more", "01E3.GIF"), "relative path kept, any case of extension");
Check.Eq(index.Folder, Path.GetFullPath(d), "the folder, in full");
Check.Eq(index.Problems.Count, 0, "no problems (GoArrow's blacklist.xml is harmless): " + string.Join(" ", index.Problems));
AcMapIndex missing = AcMapIndex.Scan(Path.Combine(d, "not-here"));
Check.True(missing.Maps.Count == 0 && missing.Problems.Count == 1 && missing.Problems[0].Contains("isn't there"), "a missing folder: says so");
Check.True(AcMapIndex.Scan("").Problems.Count == 1, "no folder: says so");
}
private static void Search()
{
AcMapIndex index = SampleIndex();
Check.Eq(AcMapIndex.Search(index.Maps, "").Count, index.Maps.Count, "no words: every map");
Check.Eq(AcMapIndex.Search(index.Maps, "moss").Single().Landblock, (ushort)0x02CA, "a word of the name");
Check.Eq(AcMapIndex.Search(index.Maps, "02ca").Single().Landblock, (ushort)0x02CA, "the landblock");
Check.Eq(AcMapIndex.Search(index.Maps, "north hole").Count, 2, "words in any order (both parts)");
Check.Eq(AcMapIndex.Search(index.Maps, "packs").Count, 2, "the folder name");
Check.Eq(AcMapIndex.Search(index.Maps, "zzzz").Count, 0, "nothing");
}
// ── Calibration ──────────────────────────────────────────────────────
private static void OneSpot()
{
var c = new AcMapCalibration();
Check.False(c.TryToImage(10, 20, 0, out _), "nothing placed: no pixel");
Check.Eq(c.Place(50, 60, -6, 400, 300), PlaceResult.FloorPlaced, "first spot places the floor");
Check.True(c.TryToImage(50, 60, -6, out Vector2 p) && Near(p, new Vector2(400, 300)), "the spot itself is the clicked pixel: " + p);
Check.True(c.TryToImage(60, 60, -6, out p) && Near(p, new Vector2(430, 300)), "10 east: 30 px right (GoArrow's 3 a unit): " + p);
Check.True(c.TryToImage(50, 70, -6, out p) && Near(p, new Vector2(400, 270)), "10 north: 30 px up: " + p);
Check.True(c.TryToImage(50, 60, -4, out _), "a little higher (a ramp): the same floor");
Check.False(c.TryToImage(50, 60, -12, out _), "6 lower: another floor, not placed");
Check.False(c.ScaleMeasuredOrSet, "the scale is still GoArrow's");
Check.Eq(c.FloorCount(), 1, "one floor");
}
private static void TwoSpots()
{
var c = new AcMapCalibration();
c.Place(10, 10, 0, 100, 500);
// 40 east and 20 north at 2.5 px a unit: 100 px right, 50 px up.
Check.Eq(c.Place(50, 30, 0, 200, 450), PlaceResult.ScaleMeasured, "a second spot far enough away measures the scale");
Check.Near(c.Scale, 2.5, 1e-4, "the scale");
Check.True(c.ScaleMeasuredOrSet, "measured");
Check.True(c.TryToImage(10, 10, 0, out Vector2 a) && Near(a, new Vector2(100, 500)), "first spot: " + a);
Check.True(c.TryToImage(50, 30, 0, out Vector2 b) && Near(b, new Vector2(200, 450)), "second spot: " + b);
Check.True(c.TryToImage(30, 20, 0, out Vector2 m) && Near(m, new Vector2(150, 475)), "between them: " + m);
Check.True(c.TryToWorld(new Vector2(150, 475), 0, out float x, out float y) && Math.Abs(x - 30) < 1e-3 && Math.Abs(y - 20) < 1e-3,
$"pixel back to position: {x}, {y}");
// A slightly off click: the floor sits between the two (mean), scale from the least-squares fit.
var d = new AcMapCalibration();
d.Place(0, 0, 0, 0, 0);
d.Place(100, 0, 0, 302, 4);
Check.True(d.Scale > 2.9f && d.Scale < 3.1f, "an off click still gives about the scale: " + d.Scale);
Check.True(AcMapCalibration.TrySolveScale(new MapSpot(0, 0, 0, 0, 0), new MapSpot(0, 20, 0, 0, -60), out float s) && Math.Abs(s - 3) < 1e-4,
"north is up the image (pixel y falls): " + s);
}
private static void Floors()
{
var c = new AcMapCalibration();
c.Place(0, 0, 0, 100, 100);
c.Place(0, 0, -6, 700, 100); // the floor below, drawn to the right on the image
Check.Eq(c.FloorCount(), 2, "two floors");
Check.True(c.TryToImage(10, 0, 0, out Vector2 a) && Near(a, new Vector2(130, 100)), "top floor: " + a);
Check.True(c.TryToImage(10, 0, -6, out Vector2 b) && Near(b, new Vector2(730, 100)), "lower floor has its own place: " + b);
Check.Eq(c.Place(3, 0, 0, 112, 100), PlaceResult.Moved, "a spot near the floor's spot moves it");
Check.Eq(c.FloorSpots(0).Count, 1, "still one spot on the floor");
Check.True(c.TryToImage(3, 0, 0, out Vector2 moved) && Near(moved, new Vector2(112, 100)), "the moved spot: " + moved);
c.Place(43, 0, 0, 232, 100); // 40 east, 120 px: scale 3
Check.Eq(c.FloorSpots(0).Count, 2, "two spots on the floor");
// A third spot replaces the nearer of the two: (40 east of the first... near the second).
Check.Eq(c.Place(40, 30, 0, 223, 10), PlaceResult.ScaleMeasured, "a third spot: replaces the nearer, re-measures with the farther");
List<MapSpot> floor = c.FloorSpots(0);
Check.True(floor.Count == 2 && floor.Any(s => s.X == 3) && floor.Any(s => s.X == 40), "kept the farther (x 3) and the new (x 40): " + string.Join(" ", floor));
Check.True(c.TryToImage(0, 0, -6, out Vector2 lower) && Math.Abs(lower.X - 700) < 1e-3, "the other floor's spot untouched");
}
private static void Refused()
{
var c = new AcMapCalibration();
c.Place(0, 0, 0, 100, 100);
// Walked 20 east but clicked 60 px left: a mirrored map, or a wrong click.
Check.Eq(c.Place(20, 0, 0, 40, 100), PlaceResult.ScaleRefused, "mirrored: refused");
Check.Eq(c.Scale, AcMapCalibration.DefaultScale, "scale unchanged");
List<MapSpot> floor = c.FloorSpots(0);
Check.True(floor.Count == 1 && floor[0].X == 20, "the new spot alone places the floor");
Check.False(AcMapCalibration.TrySolveScale(new MapSpot(0, 0, 0, 0, 0), new MapSpot(20, 0, 0, 20000, 0), out _), "absurd scale (1000): refused");
Check.False(AcMapCalibration.TrySolveScale(new MapSpot(0, 0, 0, 0, 0), new MapSpot(20, 0, 0, 0, -60), out _), "90 degrees off: refused");
Check.False(AcMapCalibration.TrySolveScale(new MapSpot(0, 0, 0, 0, 0), new MapSpot(5, 0, 0, 15, 0), out _), "too close: refused");
}
private static void ClearAndNudge()
{
var c = new AcMapCalibration();
c.Place(0, 0, 0, 100, 100);
c.Place(0, 0, -6, 300, 100);
Check.True(c.ClearFloor(-6.5f), "clear the lower floor");
Check.False(c.FloorPlaced(-6), "it's gone");
Check.True(c.FloorPlaced(0), "the top floor stays");
Check.False(c.ClearFloor(-30), "nothing to clear");
c.NudgeScale(1.02f);
Check.Near(c.Scale, 3.06, 1e-4, "nudged 2%");
Check.True(c.ScaleMeasuredOrSet, "nudged counts as set");
for (int i = 0; i < 500; i++) c.NudgeScale(1.5f);
Check.Eq(c.Scale, AcMapCalibration.MaxScale, "kept in range");
c.NudgeScale(float.NaN);
Check.Eq(c.Scale, AcMapCalibration.MaxScale, "NaN ignored");
c.ClearAll();
Check.True(c.IsEmpty && c.Scale == AcMapCalibration.DefaultScale && !c.ScaleMeasuredOrSet, "clear all: back to the start");
var bad = new AcMapCalibration(-5f, true, new[] { new MapSpot(float.NaN, 0, 0, 0, 0), new MapSpot(1, 2, 3, 4, 5) });
Check.True(bad.Scale == AcMapCalibration.DefaultScale && !bad.ScaleMeasuredOrSet && bad.Spots.Count == 1, "a bad saved scale and spot are dropped");
}
// ── Settings ─────────────────────────────────────────────────────────
private static void SettingsJson()
{
var s = new AcMapSettings { Folder = @"D:\AC\Dungeon Map Cache", Announce = true };
s.For("02CA.gif").Place(10, 10, 0, 100, 500);
s.For("02CA.gif").Place(50, 30, 0, 200, 450);
s.For("packs\\0123.gif").Place(1, 2, -6, 3, 4);
s.For("empty.gif"); // nothing set: not written
string json = s.ToJson();
AcMapSettings back = AcMapSettings.FromJson(json);
Check.Eq(back.Folder, @"D:\AC\Dungeon Map Cache", "folder");
Check.True(back.Announce, "announce");
Check.Eq(back.Maps.Count, 2, "two maps with spots (the empty one isn't written): " + string.Join(", ", back.Maps.Keys));
AcMapCalibration c = back.For("02ca.GIF");
Check.True(c.Spots.Count == 2 && Math.Abs(c.Scale - 2.5f) < 1e-3 && c.ScaleMeasuredOrSet, "spots and scale, any case of the key");
Check.True(c.TryToImage(30, 20, 0, out Vector2 m) && Near(m, new Vector2(150, 475)), "the same transform after loading: " + m);
Check.Eq(back.For("packs\\0123.gif").Spots[0], new MapSpot(1, 2, -6, 3, 4), "a spot's numbers");
AcMapSettings junk = AcMapSettings.FromJson("{ not json");
Check.True(junk.Folder == "" && !junk.Announce && junk.Maps.Count == 0, "bad JSON: defaults");
AcMapSettings partial = AcMapSettings.FromJson("{\"announce\": \"yes\", \"maps\": {\"a.gif\": {\"spots\": [[1,2,3], [1,2,3,4,\"x\"], [1,2,3,4,5]]}}}");
Check.True(!partial.Announce && partial.For("a.gif").Spots.Count == 1, "bad values skipped, good ones kept");
Check.True(new AcMapSettings().FolderOrDefault.EndsWith(Path.Combine("RynthAi", "ACMaps")), "no folder: RynthSuite's own ACMaps folder");
string path = Path.Combine(Dir("settings"), "acmaps.json");
Check.Eq(AcMapSettings.Save(path, json), "", "saved");
Check.False(File.Exists(path + ".tmp"), "no temp file left");
Check.Eq(AcMapSettings.Load(path).Folder, @"D:\AC\Dungeon Map Cache", "loaded from disk");
Check.Eq(AcMapSettings.Load(path + ".missing").Maps.Count, 0, "a missing file: defaults");
}
// ── Image and textures ───────────────────────────────────────────────
// A 1 x 1 GIF whose one pixel is palette colour 0, red.
private static readonly byte[] TinyGif =
{
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3B,
};
private static void SizesAndPieces()
{
Check.Eq(WicImage.FitSize(1200, 900), (1200, 900), "a usual map: as it is");
Check.Eq(WicImage.FitSize(8192, 2048), (4096, 1024), "too wide: halved, aspect kept");
(int w, int h) = WicImage.FitSize(4000, 4000);
Check.True(w == h && (long)w * h <= WicImage.MaxPixels && w > 2800, $"too many pixels: down to {w} x {h}");
Check.Eq(WicImage.FitSize(0, 10), (0, 0), "empty");
Check.Eq(AcMapTexture.Pow2(1), 1, "pow2 1");
Check.Eq(AcMapTexture.Pow2(512), 512, "pow2 512");
Check.Eq(AcMapTexture.Pow2(513), 1024, "pow2 513");
var img = new DecodedImage { Width = 1200, Height = 700, SourceWidth = 2400, SourceHeight = 1400, Pixels = new uint[1200 * 700] };
Check.Near(img.Factor, 0.5, 1e-6, "a halved decode's factor");
var tex = new AcMapTexture(img);
Check.Eq(tex.PieceCount, 6, "1200 x 700 in 512 pieces: 3 x 2");
AcMapTexture.Piece last = tex.Pieces[^1];
Check.True(last.X == 1024 && last.Y == 512 && last.W == 176 && last.H == 188, $"the corner piece: {last.X},{last.Y} {last.W}x{last.H}");
Check.True(Math.Abs(last.Uv1.X - 176f / 256f) < 1e-6 && Math.Abs(last.Uv1.Y - 188f / 256f) < 1e-6, "its UVs use part of a 256 texture: " + last.Uv1);
Check.False(tex.Complete, "nothing made without a device");
tex.Upload(IntPtr.Zero);
Check.False(tex.Complete, "no device: still nothing");
}
private static void Decode()
{
string d = Dir("decode");
string gif = Path.Combine(d, "02CA.gif");
File.WriteAllBytes(gif, TinyGif);
DecodedImage? g = WicImage.Load(gif, out string error);
Check.True(g != null && g.Width == 1 && g.Height == 1 && g.SourceWidth == 1, "the GIF decodes: " + error);
Check.Eq(g?.Pixels[0] ?? 0, 0xFFFF0000u, "its pixel is opaque red (BGRA as A8R8G8B8)");
string png = Path.Combine(d, "0123.png");
File.WriteAllBytes(png, Png(3, 2, new uint[] { 0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0x80FFFFFF, 0xFF000000, 0x00000000 }));
DecodedImage? p = WicImage.Load(png, out error);
Check.True(p != null && p.Width == 3 && p.Height == 2, "the PNG decodes: " + error);
if (p != null)
{
Check.Eq(p.Pixels[0], 0xFF0000FFu, "blue, top left");
Check.Eq(p.Pixels[2], 0xFFFF0000u, "red, top right");
Check.Eq(p.Pixels[3], 0x80FFFFFFu, "half-clear white, bottom left (straight alpha)");
}
string notImage = Path.Combine(d, "dungeons.gif");
File.WriteAllText(notImage, "02CA;Mosswart Maze");
Check.Null(WicImage.Load(notImage, out error), "a text file named .gif: null");
Check.True(error.Length > 0, "and why: " + error);
Check.Null(WicImage.Load(Path.Combine(d, "missing.png"), out error), "a missing file: null");
// The async path hands the result over on its own thread.
var done = new TaskCompletionSource<(DecodedImage?, string)>();
WicImage.DecodeAsync(gif, (img, err) => done.TrySetResult((img, err)));
Check.True(done.Task.Wait(10000) && done.Task.Result.Item1?.Width == 1, "DecodeAsync");
}
/// <summary>A PNG of ARGB pixels (8-bit RGBA, no filter).</summary>
private static byte[] Png(int w, int h, uint[] argb)
{
using var raw = new MemoryStream();
for (int y = 0; y < h; y++)
{
raw.WriteByte(0);
for (int x = 0; x < w; x++)
{
uint c = argb[y * w + x];
raw.WriteByte((byte)(c >> 16)); raw.WriteByte((byte)(c >> 8)); raw.WriteByte((byte)c); raw.WriteByte((byte)(c >> 24));
}
}
byte[] idat;
using (var z = new MemoryStream())
{
using (var zs = new ZLibStream(z, CompressionLevel.Optimal, leaveOpen: true)) zs.Write(raw.ToArray());
idat = z.ToArray();
}
using var png = new MemoryStream();
png.Write(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A });
var ihdr = new byte[13];
Be(ihdr, 0, (uint)w); Be(ihdr, 4, (uint)h);
ihdr[8] = 8; ihdr[9] = 6;
Chunk(png, "IHDR", ihdr);
Chunk(png, "IDAT", idat);
Chunk(png, "IEND", Array.Empty<byte>());
return png.ToArray();
}
private static void Chunk(Stream s, string type, byte[] data)
{
var len = new byte[4]; Be(len, 0, (uint)data.Length); s.Write(len);
byte[] t = Encoding.ASCII.GetBytes(type);
s.Write(t); s.Write(data);
var crc = new byte[4]; Be(crc, 0, Crc(t.Concat(data).ToArray())); s.Write(crc);
}
private static void Be(byte[] b, int at, uint v) { b[at] = (byte)(v >> 24); b[at + 1] = (byte)(v >> 16); b[at + 2] = (byte)(v >> 8); b[at + 3] = (byte)v; }
private static uint Crc(byte[] data)
{
uint c = 0xFFFFFFFF;
foreach (byte b in data)
{
c ^= b;
for (int k = 0; k < 8; k++) c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1;
}
return c ^ 0xFFFFFFFF;
}
// ── Chat line, manifest, command ─────────────────────────────────────
private static void AnnounceLine()
{
AcMapIndex index = SampleIndex();
string? line = RynthAiPlugin.AcAnnounceLine(index, 0x02CA);
Check.True(line != null && line.Contains("Mosswart Maze") && line.Contains("Map (right-click)") && line.Contains("/ra acmaps"), "a map: the line says where: " + line);
Check.Null(RynthAiPlugin.AcAnnounceLine(index, 0x0456), "no map: no line");
Check.Null(RynthAiPlugin.AcAnnounceLine(index, 0), "outdoors: no line");
AcMapIndex noList = AcMapIndex.Build(@"C:\x", new[] { "02CA.gif" }, _ => null);
Check.True(RynthAiPlugin.AcAnnounceLine(noList, 0x02CA)?.Contains("Dungeon 02CA") == true, "no name: by landblock");
}
private static void Manifest()
{
string json = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, acMaps: true);
SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error);
Check.Eq(error, "", "parses");
SectionWindowDecl? w = m.Windows.FirstOrDefault(x => x.Title == RynthAiPlugin.AcMapsTitle);
Check.True(w != null && w.Surface == RynthAiPlugin.AcMapsSurface && !w.Bar, "the ACMAPS Maps window, no bar button");
string without = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections);
Check.False(without.Contains(RynthAiPlugin.AcMapsSurface), "not declared without plugin windows");
}
private static readonly List<(string Key, int Mode)> PanelCalls = new();
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint FakeUiColor(int token) => 0xFFFFFFFF;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr FakeUiFont(int font) => IntPtr.Zero;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static unsafe int FakeSetPanelOpen(byte* key, int mode)
{
PanelCalls.Add((Marshal.PtrToStringUTF8((IntPtr)key) ?? "", mode));
return mode == 0 ? 0 : 1;
}
private static unsafe void PluginWindows(ref RynthCoreApiNative api)
{
api.Version = Math.Max(api.Version, 89u);
api.GetUiColorFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, uint>)&FakeUiColor;
api.GetUiFontFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, IntPtr>)&FakeUiFont;
api.SetPanelOpenFn = (IntPtr)(delegate* unmanaged[Cdecl]<byte*, int, int>)&FakeSetPanelOpen;
}
private static void Command()
{
FakeHost.Reset();
PanelCalls.Clear();
FakeHost.ConfigureApi = PluginWindows;
FakeHost.Create(playerId: 0x50000F41);
var p = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
void Set(string f, object v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(p, v);
Set("_playerId", 0x50000F41u);
Set("_initialized", true);
Set("_loginComplete", true);
// Settings and maps in scratch: never the real RynthSuite folder.
string root = Dir("command");
string maps = Path.Combine(root, "maps");
Directory.CreateDirectory(maps);
File.WriteAllBytes(Path.Combine(maps, "02CA.gif"), TinyGif);
File.WriteAllText(Path.Combine(maps, "dungeons.txt"), "02CA;Mosswart Maze\n");
p.AcMapsSettingsPath = Path.Combine(root, "acmaps.json");
p.AcSettings.Folder = maps;
p.StartAcScan().Wait(10000);
Check.Eq(p.AcMapsIndexForTests.Maps.Count, 1, "the scratch folder is read");
List<string> Typed(string line)
{
int before = FakeHost.Chat.Count;
int eat = 0;
p.OnChatBarEnter(line, ref eat);
return FakeHost.Chat.Skip(before).ToList();
}
string Show(List<string> l) => string.Join(" | ", l);
// In the dungeon (an indoor cell of 02CA).
FakeHost.PlayerPose = (0x02CA0105u, 30f, -40f, -6f);
List<string> lines = Typed("/ra acmaps");
Check.True(lines.Count == 1 && lines[0].Contains("1 map in " + maps) && lines[0].Contains("this dungeon (Mosswart Maze, 02CA) has one")
&& lines[0].Contains("ACMAPS Maps open"), "opens and says what's there: " + Show(lines));
Check.True(PanelCalls.Count > 0 && PanelCalls[^1] == (RynthAiPlugin.AcMapsTitle, (int)RynthPanelOpen.Open), "opened by its panel key");
FakeHost.PlayerPose = (0x01E30105u, 30f, -40f, -6f);
lines = Typed("/ra acmaps");
Check.True(lines.Count == 1 && lines[0].Contains("none for this dungeon (01E3)"), "a dungeon without a map: says so: " + Show(lines));
lines = Typed("/ra acmaps folder relative\\path");
Check.True(lines.Count == 1 && lines[0].Contains("isn't a full folder path") && lines[0].Contains(RynthAiPlugin.AcMapsUsage), "a relative path: refused: " + Show(lines));
lines = Typed("/ra acmaps folder " + Path.Combine(root, "nope"));
Check.True(lines.Count == 1 && lines[0].Contains("there's no folder"), "a missing folder: refused: " + Show(lines));
lines = Typed("/ra acmaps folder");
Check.True(lines.Count == 1 && lines[0].Contains(maps), "no path: says the folder: " + Show(lines));
string other = Path.Combine(root, "other");
Directory.CreateDirectory(other);
lines = Typed("/ra acmaps folder " + other);
Check.True(lines.Count == 1 && lines[0].Contains("folder set to " + other), "folder set: " + Show(lines));
Check.Eq(p.AcSettings.Folder, other, "the setting changed");
lines = Typed("/ra acmaps folder " + maps);
Check.True(lines.Count == 1 && lines[0].Contains("folder set"), "back: " + Show(lines));
lines = Typed("/ra acmaps scan");
Check.True(lines.Count == 1 && lines[0].Contains("reading " + maps + " again"), "scan: " + Show(lines));
lines = Typed("/ra acmaps announce on");
Check.True(lines.Count == 1 && lines[0].Contains("ON"), "announce on: " + Show(lines));
Check.True(p.AcSettings.Announce, "the setting is on");
lines = Typed("/ra acmaps announce");
Check.True(lines.Count == 1 && lines[0].Contains("OFF") && !p.AcSettings.Announce, "announce alone: toggles: " + Show(lines));
lines = Typed("/ra acmaps announce maybe");
Check.True(lines.Count == 1 && lines[0].Contains("on or off"), "announce maybe: refused: " + Show(lines));
lines = Typed("/ra acmaps hide");
Check.True(lines.Count == 1 && lines[0].Contains("closed") && PanelCalls[^1].Mode == (int)RynthPanelOpen.Close, "hide: " + Show(lines));
lines = Typed("/ra acmaps wibble");
Check.True(lines.Count == 1 && lines[0].Contains("unknown option 'wibble'") && lines[0].Contains(RynthAiPlugin.AcMapsUsage), "unknown: " + Show(lines));
lines = Typed("/ra acmaps ?");
Check.True(lines.Count == 2 && lines.All(l => l.Contains("/ra acmaps")), "? says the usage: " + Show(lines));
lines = Typed("/ra help");
Check.True(lines.Any(l => l.Contains("/ra acmaps")), "/ra help lists it");
// The settings were written to scratch, and only there.
System.Threading.Thread.Sleep(800);
Check.True(File.Exists(p.AcMapsSettingsPath), "settings saved in scratch");
Check.Eq(AcMapSettings.Load(p.AcMapsSettingsPath).Folder, maps, "the saved folder");
// The chat line: announce on, walk into the dungeon (the scans above finished first).
p.StartAcScan().Wait(10000);
Typed("/ra acmaps announce on");
FakeHost.PlayerPose = (0x02CA0105u, 30f, -40f, -6f);
int chatBefore = FakeHost.Chat.Count;
typeof(RynthAiPlugin).GetMethod("TickAcMaps", Any)!.Invoke(p, null);
typeof(RynthAiPlugin).GetMethod("TickAcMaps", Any)!.Invoke(p, null);
List<string> said = FakeHost.Chat.Skip(chatBefore).ToList();
Check.True(said.Count == 1 && said[0].Contains("Mosswart Maze"), "one line on entering, not every tick: " + Show(said));
FakeHost.PlayerPose = (0x02CA0031u, 30f, -40f, -6f); // an outdoor cell: left
typeof(RynthAiPlugin).GetMethod("TickAcMaps", Any)!.Invoke(p, null);
FakeHost.PlayerPose = (0x02CA0105u, 30f, -40f, -6f);
typeof(RynthAiPlugin).GetMethod("TickAcMaps", Any)!.Invoke(p, null);
Check.Eq(FakeHost.Chat.Skip(chatBefore).Count(), 2, "again after leaving and coming back");
Typed("/ra acmaps announce off");
FakeHost.Reset();
}
private static bool Near(Vector2 a, Vector2 b) => Vector2.Distance(a, b) < 1e-3f;
}

View file

@ -0,0 +1,508 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.MiniRemote;
using RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Make ammo when low (a players' request, 2026-11-23: "set an amount of arrows and if we fall below it
// does it between combat"), on the real plugin and the fake engine: RynthAiPlugin.Ammo.cs decides when
// (the Make kits when low rules and checks), MissileCraftingManager's top-off makes the combines. A bow
// in hand, Greater Arrows in the quiver, bundles in the pack; the fake server makes 100 arrows a combine.
internal static class AmmoAutoPluginTests
{
public static void Register(Runner r)
{
r.Add("ammo when low (plugin): under N and quiet - holds the bot, makes up to M (3 combines for 40 -> 300), no wield over a full quiver, then hunts", TopsUp);
r.Add("ammo when low (plugin): a monster closing in stops the top-off at once, then 60 s before the next try", MonsterStops);
r.Add("ammo when low (plugin): a hit stops the top-off at once", HitStops);
r.Add("ammo when low (plugin): never goes to peace mode for a top-off in a fight (before it or during it)", NeverPeaceInFight);
r.Add("ammo when low (plugin): off by default - nothing changes; settings saved, loaded, copied and clamped", OffByDefault);
r.Add("ammo when low (plugin): the empty-quiver path still crafts in a fight with nothing to shoot", EmergencyPathStillWorks);
r.Add("ammo when low (plugin): an empty quiver between fights - the top-off wields the arrows it made", EquipsIntoEmptySlot);
r.Add("ammo when low (plugin): blockers - no launcher, untrained, too hard, a launcher swap, Missile Crafting off, enough carried", Blockers);
r.Add("ammo when low (plugin): /ra ammo make works with the macro off; /ra ammo stop stops it (10 min wait)", MakeNowAndStop);
r.Add("ammo when low: a combine's yield - 100 for a plain bundle, 1000 for a wrapped one", Yields);
}
private const uint Player = TickIsolationTests.Player;
private const uint Lb = 0xA9B40000;
private const uint Bow = 0x80520001, Quiver = 0x80520002, Heads = 0x80520003, Shafts = 0x80520004, PackArrows = 0x80520005;
private const uint Monster = 0x80520010;
private const uint StackKey = 12, ValidKey = 9;
private const int MissileSlot = 0x00400000, AmmoSlot = 0x00800000;
private const uint SkillFletching = 37;
private sealed class Rig
{
public readonly TickIsolationTests.Bot Bot;
public readonly MiniRemoteController Remote;
public readonly MissileCraftingManager Cm;
public LegacyUiSettings S => Bot.S;
public bool Fight; // the crafting manager's own fight signal (on top of the plugin's)
public bool FailAll;
private readonly List<(uint Src, uint Tgt)> _pending = new();
private uint _nextId = 0x80620001;
private static readonly DateTime Epoch = new(2026, 11, 23, 12, 0, 0);
public Rig(int quiver = 40, int bundles = 10, int fletching = 400, int training = 3, bool bow = true,
string heads = "Bundle of Greater Arrowheads", string shafts = "Bundle of Arrowshafts", int pack = 0)
{
Bot = new TickIsolationTests.Bot(combat: true, heal: false, arrange: () =>
{
FakeHost.SalvageCalls = true; // GetObjectWielderInfo
FakeHost.UseOnCalls = true;
FakeHost.CombatModeCalls = true; // peace mode requests recorded
FakeHost.CombatModeValue = CombatMode.NonCombat;
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.Skills[(Player, SkillFletching)] = (fletching, training);
if (bow)
{
Item(Bow, "Longbow", MissileSlot, 1);
FakeHost.Wielded[Bow] = MissileSlot; // in hand
}
if (quiver > 0)
{
Item(Quiver, "Greater Arrow", AmmoSlot, quiver);
FakeHost.Wielded[Quiver] = AmmoSlot;
}
if (pack > 0) { Item(PackArrows, "Greater Arrow", AmmoSlot, pack); FakeHost.Containers[PackArrows] = Player; }
if (bundles > 0)
{
Item(Heads, heads, 0, bundles);
FakeHost.Containers[Heads] = Player;
Item(Shafts, shafts, 0, bundles);
FakeHost.Containers[Shafts] = Player;
}
FakeHost.OnUseObjectOn = (src, tgt) => _pending.Add((src, tgt));
});
RynthClock.TestNow = () => Epoch.AddMilliseconds(Bot.Now);
foreach (uint id in new[] { Bow, Quiver, Heads, Shafts, PackArrows })
if (FakeHost.Names.ContainsKey(id)) _ = Bot.Cache[unchecked((int)id)];
S.MonsterRange = 20; // the safe radius is then 35 yd
S.EnableMissileCrafting = true;
S.MakeAmmoWhenLow = true;
S.MakeAmmoBelow = 100;
S.MakeAmmoUpTo = 300;
string dir = Path.Combine(Program.TempRoot, "ammoauto-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
var cache = Bot.Cache;
var s = S;
Remote = new MiniRemoteController(Bot.Host, dir, () => cache, () => s, () => null, () => { }, new ServerHubClient(Bot.Host));
Remote.Crafting.AutoKits.NowMs = () => Bot.Now; // KitNow: the plugin's clock for both
Bot.Set("_miniRemote", Remote);
Cm = new MissileCraftingManager(Bot.Host, S);
Cm.SetObjectCache(cache);
var skills = new CharacterSkills(Bot.Host);
skills.SetPlayerId(Player);
Cm.SetCharacterSkills(skills);
var combat = Combat;
Cm.HoldWhile = () => combat.AmmoSwapInProgress;
Cm.FightIsOn = () => Fight || Bot.P.FightIsOn();
Bot.Set("_missileCraftingManager", Cm);
Bot.Call("WireAmmoTopOff", Cm);
}
private static void Item(uint id, string name, int valid, int stack)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = 0x100;
if (valid != 0) FakeHost.Ints[(id, ValidKey)] = valid;
FakeHost.Ints[(id, StackKey)] = stack;
}
public CombatManager Combat => (CombatManager)Bot.Get("_combatManager")!;
/// <summary>One OnTick's worth: the danger checks, the kits' hold, the ammo hold, the server's answers. True = held.</summary>
public bool Tick(long ms = 100)
{
Bot.Now += ms;
Bot.Call("CheckAutoKitsDanger", S);
Bot.Call("CheckAutoAmmoDanger", S);
bool hold = (bool)Bot.Call("TickAutoAmmo", S)!;
ForceRescan();
var sent = _pending.ToList();
_pending.Clear();
foreach (var (src, tgt) in sent) Serve(src, tgt);
return hold;
}
public int TickUntil(Func<bool> until, int max = 600, long ms = 100)
{
int held = 0;
for (int i = 0; i < max && !until(); i++) if (Tick(ms)) held++;
return held;
}
/// <summary>The fake server: 100 Greater Arrows into the pack a combine (a head and a shaft bundle used).</summary>
private void Serve(uint src, uint tgt)
{
if (src != Heads || tgt != Shafts) return;
Take(Heads);
Take(Shafts);
if (FailAll) { Cm.HandleChat("You fail to make a bundle of greater arrows."); return; }
if (FakeHost.Containers.TryGetValue(PackArrows, out _) && FakeHost.Ints.ContainsKey((PackArrows, StackKey)))
FakeHost.Ints[(PackArrows, StackKey)] += 100;
else
{
uint id = PackArrows;
FakeHost.Names[id] = "Greater Arrow";
FakeHost.ItemTypes[id] = 0x100;
FakeHost.Ints[(id, ValidKey)] = AmmoSlot;
FakeHost.Ints[(id, StackKey)] = 100;
FakeHost.Containers[id] = Player;
_ = Bot.Cache[unchecked((int)id)];
}
Cm.HandleChat("You make a bundle of greater arrows.");
}
private void Take(uint id)
{
int n = FakeHost.Ints.GetValueOrDefault((id, StackKey), 1) - 1;
if (n > 0) { FakeHost.Ints[(id, StackKey)] = n; return; }
FakeHost.Ints.Remove((id, StackKey));
FakeHost.Containers.Remove(id);
Bot.Cache.OnDeleteObject(id);
}
public void ForceRescan()
{
typeof(WorldObjectCache).GetField("_lastDirectInventoryScan", BindingFlags.Instance | BindingFlags.NonPublic)!
.SetValue(Bot.Cache, DateTime.MinValue);
EquippedState.Invalidate();
}
public int Carried => Cm.LookTopOff(forceRefresh: true).Carried;
public int Combines => FakeHost.UsesOn.Count;
public bool PeaceAsked => FakeHost.CombatModeRequests.Contains(CombatMode.NonCombat);
public List<string> Lines => FakeHost.Chat.Where(c => c.Contains("Make ammo")).ToList();
public string Status => (string)Bot.Call("AmmoAutoStatusText", S)!;
public void MonsterAt(double yd) =>
Combat.SetScannedTargetsForTests(new[] { new CombatManager.ScannedTarget { Id = unchecked((int)Monster), Distance = yd, Name = "Drudge" } });
public List<string> Typed(string line)
{
Bot.Set("_initialized", true); // the chat bar reads typed commands once the plugin is up
int before = FakeHost.Chat.Count;
int eat = 0;
Bot.P.OnChatBarEnter(line, ref eat);
return FakeHost.Chat.Skip(before).ToList();
}
}
private static void Done()
{
RynthClock.TestNow = null;
TickIsolationTests.Done();
}
private static string Show(IEnumerable<string> lines) => string.Join(" | ", lines);
private static void TopsUp()
{
try
{
var rig = new Rig(quiver: 40);
Check.Eq(rig.Carried, 40, "40 arrows carried (the quiver)");
int held = rig.TickUntil(() => rig.Cm.TopOffRunning, max: 50);
Check.True(rig.Cm.TopOffRunning, "a top-off started by itself: " + rig.Status);
Check.True(held >= 9, $"the bot was held while getting ready ({held} ticks)");
Check.Eq(rig.Cm.TopOffPlanned, 3, "3 combines planned (40 + 3 x 100 reaches 300)");
string start = rig.Lines.FirstOrDefault(l => l.Contains("carried (under 100)")) ?? "";
Check.True(start.Contains("40 arrows carried (under 100); making 3 combines of Greater Arrow, about 300, toward 300"), "the start line says why: " + Show(rig.Lines));
Check.True(rig.Tick(), "held while it runs");
Check.True(rig.Status.StartsWith("running "), "status: " + rig.Status);
rig.TickUntil(() => !rig.Cm.TopOffRunning);
Check.Eq(rig.Combines, 3, "three combines sent");
Check.Eq(rig.Carried, 340, "340 carried now");
Check.False(FakeHost.Uses.Contains(PackArrows), "the quiver had arrows: nothing wielded");
Check.False(rig.Tick(), "over: the bot hunts as normal");
string line = rig.Lines.LastOrDefault() ?? "";
Check.True(line.Contains("made 3 combines of Greater Arrow (about 300 arrows)") && line.Contains("Stopped: made the 3 combines planned."),
"one summary line: " + line);
Check.False(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi Craft]")), "crafting's own lines stay in the log: " + Show(FakeHost.Chat));
int combines = rig.Combines;
for (int i = 0; i < 30; i++) rig.Tick(5_000);
Check.Eq(rig.Combines, combines, "340 carried (not under 100): no more top-offs");
Check.True(rig.Status.Contains("340 arrows carried"), "the status says why: " + rig.Status);
}
finally { Done(); }
}
private static void MonsterStops()
{
try
{
var rig = new Rig(quiver: 40);
rig.TickUntil(() => rig.Cm.TopOffRunning, max: 50);
rig.Tick(); // the first combine goes out
Check.True(rig.Cm.TopOffRunning, "running");
rig.MonsterAt(30);
Check.False(rig.Tick(), "a monster at 30 yd: no hold on this tick");
Check.False(rig.Cm.TopOffRunning, "the top-off stopped at once");
Check.False(rig.Cm.IsCrafting, "crafting let go of the bot");
string line = rig.Lines.LastOrDefault() ?? "";
Check.True(line.Contains("Stopped: a monster came within 30 yd.") && line.Contains("Next try in 60 s"), "says why and when: " + line);
rig.Combat.SetScannedTargetsForTests(Array.Empty<CombatManager.ScannedTarget>());
rig.S.MakeAmmoBelow = 250; // the one combine made 140: still under the line
int combines = rig.Combines;
for (int i = 0; i < 58; i++) rig.Tick(1_000);
Check.False(rig.Cm.TopOffRunning, "58 s later: still waiting");
Check.Eq(rig.Combines, combines, "nothing combined meanwhile");
rig.Tick(3_000);
rig.TickUntil(() => rig.Cm.TopOffRunning, max: 50);
Check.True(rig.Cm.TopOffRunning, "past 60 s: running again");
}
finally { Done(); }
try
{
var rig = new Rig(quiver: 40);
rig.MonsterAt(30);
for (int i = 0; i < 40; i++) rig.Tick();
Check.False(rig.Cm.TopOffRunning, "a monster 30 yd away: no start");
Check.Eq(rig.Combines, 0, "nothing combined");
Check.False(rig.PeaceAsked, "no peace mode asked for");
Check.True(rig.Status.Contains("monster 30 yd away"), "status: " + rig.Status);
}
finally { Done(); }
}
private static void HitStops()
{
try
{
var rig = new Rig(quiver: 40);
rig.TickUntil(() => rig.Cm.TopOffRunning, max: 50);
rig.Tick();
Check.True(rig.Cm.TopOffRunning, "running");
FakeHost.Vitals = (95, 100, 100, 100, 100, 100);
rig.Tick();
Check.False(rig.Cm.TopOffRunning, "a hit: stopped at once");
string line = rig.Lines.LastOrDefault() ?? "";
Check.True(line.Contains("Stopped: you were hit."), "says why: " + line);
}
finally { Done(); }
}
private static void NeverPeaceInFight()
{
// A fight before the top-off: in missile mode, a monster in range, under the line.
try
{
var rig = new Rig(quiver: 40);
FakeHost.CombatModeValue = CombatMode.Missile;
rig.MonsterAt(10);
for (int i = 0; i < 80; i++) rig.Tick();
Check.False(rig.PeaceAsked, "no peace mode asked for in a fight");
Check.Eq(rig.Combines, 0, "no combine");
Check.False(rig.Tick(), "and no hold: combat has the tick");
}
finally { Done(); }
// The crafting manager on its own: a top-off isn't started in a fight.
try
{
var rig = new Rig(quiver: 40);
rig.Fight = true;
string why = (string)typeof(MissileCraftingManager).GetMethod("StartTopOff", BindingFlags.Instance | BindingFlags.NonPublic)!
.Invoke(rig.Cm, new object?[] { 300, false, "test", null })!;
Check.Eq(why, "a fight is on", "StartTopOff refuses in a fight");
Check.False(rig.Cm.IsCrafting, "nothing started");
}
finally { Done(); }
// A fight starting during the top-off (seen first by crafting itself): it stops, no peace asked again.
try
{
var rig = new Rig(quiver: 40);
rig.TickUntil(() => rig.Cm.TopOffRunning, max: 50);
rig.Tick();
Check.True(rig.Cm.TopOffRunning, "running");
int combines = rig.Combines;
FakeHost.CombatModeRequests.Clear();
rig.Fight = true;
for (int i = 0; i < 40; i++) rig.Tick();
Check.False(rig.Cm.TopOffRunning, "a fight: stopped");
Check.Eq(rig.Combines, combines, "no combine after the fight began");
Check.False(rig.PeaceAsked, "no peace mode asked for after the fight began");
Check.True((rig.Lines.LastOrDefault() ?? "").Contains("Stopped: a fight."), "says why: " + Show(rig.Lines));
}
finally { Done(); }
}
private static void OffByDefault()
{
var d = new LegacyUiSettings();
Check.False(d.MakeAmmoWhenLow, "off by default");
Check.Eq(d.MakeAmmoBelow, 100, "under 100");
Check.Eq(d.MakeAmmoUpTo, 500, "up to 500");
var old = JsonSerializer.Deserialize("{\"EnableAutostack\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.False(old.MakeAmmoWhenLow, "a profile from before the setting: off");
Check.Eq(old.MakeAmmoBelow, 100, "and 100");
var saved = JsonSerializer.Deserialize(
JsonSerializer.Serialize(new LegacyUiSettings { MakeAmmoWhenLow = true, MakeAmmoBelow = 150, MakeAmmoUpTo = 900 }, RynthAiJsonContext.Default.LegacyUiSettings),
RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.True(saved.MakeAmmoWhenLow && saved.MakeAmmoBelow == 150 && saved.MakeAmmoUpTo == 900, "saved and loaded");
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { new LegacyUiSettings { MakeAmmoWhenLow = true, MakeAmmoBelow = 0, MakeAmmoUpTo = 99_999 }, dst });
Check.True(dst.MakeAmmoWhenLow, "a profile switch copies it");
Check.Eq(dst.MakeAmmoBelow, 1, "a bad count is clamped (1)");
Check.Eq(dst.MakeAmmoUpTo, MissileCraftingManager.MaxAmmoUpTo, "and the other (10000)");
try
{
var rig = new Rig(quiver: 40);
rig.S.MakeAmmoWhenLow = false;
for (int i = 0; i < 60; i++) Check.False(rig.Tick(), "off: never held");
Check.Eq(rig.Combines, 0, "off: nothing combined");
Check.False(rig.PeaceAsked, "off: no peace mode asked for");
Check.Eq(rig.Status, "off", "status: off");
Check.Eq(rig.Lines.Count, 0, "off: nothing said: " + Show(rig.Lines));
}
finally { Done(); }
}
private static readonly FieldInfo LastAmmoCheck =
typeof(MissileCraftingManager).GetField("_lastAmmoCheck", BindingFlags.Instance | BindingFlags.NonPublic)!;
private static void EmergencyPathStillWorks()
{
try
{
// Nothing to shoot at all, in a fight: the top-off stays out, the empty-quiver path makes one combine.
var rig = new Rig(quiver: 0);
FakeHost.CombatModeValue = CombatMode.Missile;
rig.MonsterAt(10);
rig.Fight = true;
for (int i = 0; i < 20; i++) rig.Tick();
Check.False(rig.Cm.TopOffRunning, "no top-off in the fight");
Check.Eq(rig.Combines, 0, "no top-off combine");
for (int i = 0; i < 6 && rig.Combines == 0; i++)
{
if (rig.Cm.State == MissileCraftingManager.CraftState.Idle) LastAmmoCheck.SetValue(rig.Cm, DateTime.MinValue);
rig.Bot.Now += 1_000;
rig.ForceRescan();
rig.Cm.ProcessCrafting(); // OnTick's crafting step
}
Check.Eq(rig.Combines, 1, "the empty-quiver path made its first combine, as before");
Check.True(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi Craft]") && c.Contains("Crafting Greater Arrow")),
"its own chat line, as before: " + Show(FakeHost.Chat));
}
finally { Done(); }
}
private static void EquipsIntoEmptySlot()
{
try
{
var rig = new Rig(quiver: 0);
rig.TickUntil(() => rig.Cm.TopOffRunning, max: 50);
Check.True(rig.Cm.TopOffRunning, "an empty quiver and nothing carried: a top-off between fights");
rig.TickUntil(() => !rig.Cm.TopOffRunning);
Check.Eq(rig.Combines, 3, "three combines (0 -> 300)");
Check.True(FakeHost.Uses.Contains(PackArrows), "the arrows made were wielded");
Check.True((rig.Lines.LastOrDefault() ?? "").Contains("Stopped: made the 3 combines planned."), "summary: " + Show(rig.Lines));
}
finally { Done(); }
}
private static void Blockers()
{
void NoStart(string name, Func<Rig> make, Action<Rig> set, string status)
{
try
{
var rig = make();
set(rig);
for (int i = 0; i < 40; i++) rig.Tick();
Check.False(rig.Cm.TopOffRunning, name + ": no top-off");
Check.Eq(rig.Combines, 0, name + ": nothing combined");
Check.False(rig.Tick(), name + ": the bot isn't held");
Check.True(rig.Status.Contains(status), $"{name}: the status says '{status}': {rig.Status}");
}
finally { Done(); }
}
NoStart("no launcher", () => new Rig(bow: false), _ => { }, "no bow, crossbow or atlatl in hand");
NoStart("untrained Fletching", () => new Rig(training: 1), _ => { }, "Fletching is untrained");
NoStart("too hard", () => new Rig(fletching: 100), _ => { }, "under the 90% line");
NoStart("Missile Crafting off", () => new Rig(), r => r.S.EnableMissileCrafting = false, "Enable Missile Crafting is off");
NoStart("macro off", () => new Rig(), r => r.S.IsMacroRunning = false, "macro is off");
NoStart("a heal line", () => new Rig(), _ => FakeHost.Vitals = (50, 100, 100, 100, 100, 100), "health 50%");
NoStart("enough carried", () => new Rig(quiver: 60, pack: 50), _ => { }, "110 arrows carried");
NoStart("no bundles", () => new Rig(bundles: 0), _ => { }, "no heads and shafts for arrows");
NoStart("a launcher swap", () => new Rig(), r =>
{
typeof(CombatManager).GetField("_ammoFollowUpFor", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(r.Combat, unchecked((int)Bow));
typeof(CombatManager).GetField("_ammoFollowUpUntil", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(r.Combat, RynthClock.Now.AddHours(1));
}, "a launcher swap");
}
private static void MakeNowAndStop()
{
try
{
var rig = new Rig(quiver: 150); // over the line (100), under Make up to (300)
rig.S.IsMacroRunning = false;
rig.S.MakeAmmoWhenLow = false;
var said = rig.Typed("/ra ammo make");
Check.True(said.Any(l => l.Contains("Make ammo now: making Greater Arrow up to 300 as soon as it is safe")), "the reply: " + Show(said));
rig.TickUntil(() => rig.Cm.TopOffRunning, max: 50);
Check.True(rig.Cm.TopOffRunning && rig.Cm.TopOffManual, "macro off: Make ammo now runs");
Check.Eq(rig.Cm.TopOffPlanned, 2, "2 combines (150 -> 350)");
rig.Tick();
said = rig.Typed("/ra ammo stop");
Check.False(rig.Cm.TopOffRunning, "/ra ammo stop: stopped");
Check.True(said.Any(l => l.Contains("Stopped: stopped by you.") && l.Contains("Next try in 10 min")), "the summary answers: " + Show(said));
said = rig.Typed("/ra ammo stop");
Check.True(said.Any(l => l.Contains("nothing is running")), "again: nothing is running: " + Show(said));
said = rig.Typed("/ra ammo");
Check.True(said.Any(l => l.Contains("carried for the launcher in hand")) && said.Any(l => l.Contains("Make ammo when low: off")), "status: " + Show(said));
said = rig.Typed("/ra ammo banana");
Check.True(said.Any(l => l.Contains("unknown option") && l.Contains(RynthAiPlugin.AmmoUsage)), "a wrong option: " + Show(said));
said = rig.Typed("/ra ammo auto upto 0");
Check.True(said.Any(l => l.Contains("from 1 to 10000")), "out of range: " + Show(said));
said = rig.Typed("/ra ammo auto on");
Check.True(rig.S.MakeAmmoWhenLow && said.Any(l => l.Contains("Make ammo when low: on")), "on: " + Show(said));
}
finally { Done(); }
// The panel's buttons go through the same path on the next tick.
try
{
var rig = new Rig(quiver: 150);
rig.S.MakeAmmoWhenLow = false;
rig.Cm.RequestMakeNow();
rig.TickUntil(() => rig.Cm.TopOffRunning, max: 50);
Check.True(rig.Cm.TopOffRunning, "the panel's Make ammo now started a top-off");
rig.Cm.RequestStop();
rig.Tick();
Check.False(rig.Cm.TopOffRunning, "the panel's Stop stopped it");
}
finally { Done(); }
}
private static void Yields()
{
AmmoRecipe Find(string head, string shaft) => AmmoRecipes.All.First(r => r.HeadName == head && r.ShaftName == shaft);
Check.Eq(AmmoRecipes.EstimatedYield(Find("Bundle of Greater Arrowheads", "Bundle of Arrowshafts")), 100, "a plain bundle: 100");
Check.Eq(AmmoRecipes.EstimatedYield(Find("Wrapped Bundle of Deadly Prismatic Arrowheads", "Wrapped Bundle of Arrowshafts")), 1000, "a wrapped bundle: 1000");
Check.True(AmmoRecipes.HeadIsInfinite(AmmoRecipes.All.First(r => r.HeadName.StartsWith("Infinite"))), "Infinite heads are never used up");
Check.Eq(MissileCraftingManager.AmmoText(1, WeaponCategory.Crossbow), "1 quarrel", "one quarrel");
Check.Eq(MissileCraftingManager.AmmoText(12, WeaponCategory.Atlatl), "12 darts", "darts");
}
}

View file

@ -37,6 +37,7 @@ internal static unsafe class AutoConfirmCraftTests
r.Add("autoconfirm: logout releases the arm", Logout);
r.Add("autoconfirm: settings - off at 100 by default, saved, copied, sent to the engine face as nullable fields", Settings);
r.Add("autoconfirm: /ra autoconfirm on|off|<percent>|status always answers", Command);
r.Add("/ub prepclick yes [ms] arms a Yes for the next yes/no prompt (5-60 s); no disarms (R-20261125-144721-b49a)", UbPrepClick);
}
// ── The fake engine's confirmation calls (static: function pointers can't capture) ──────────
@ -126,6 +127,38 @@ internal static unsafe class AutoConfirmCraftTests
}
}
// Coldeve: a meta turning alt currency in for promissory notes sent "/ub prepclick yes 100" and RynthAi ignored it.
private static void UbPrepClick()
{
var bot = new TickIsolationTests.Bot(arrange: () =>
{
ResetEngine();
FakeHost.ConfigureApi = (ref RynthCoreApiNative api) =>
{
api.ArmConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int, int>)&FakeArm;
api.GetLastConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, int*, int*, int*, int>)&FakeLast;
};
});
try
{
var handle = typeof(RynthAiPlugin).GetMethod("TryHandleUbCompat", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
bool Run(string line) => (bool)handle.Invoke(bot.P, new object[] { line.Split(' ')[1], line })!;
Check.True(Run("/ub prepclick yes 100"), "taken");
Check.Eq(ArmCalls.Count, 1, "one arm");
Check.Eq(ArmCalls[0], (RynthCoreHost.ConfirmationKind.YesNo, 0, RynthAiPlugin.PrepClickMinMs), "a Yes for the next yes/no prompt, 100 ms raised to 5 s");
Check.Eq(Prompt(0, RynthCoreHost.ConfirmationKind.YesNo), RynthCoreHost.ConfirmationOutcome.Accepted, "the prompt is answered Yes");
Check.False(FakeHost.Logs.Any(l => l.Contains("no RynthAi equivalent")), "no longer 'ignored'");
Run("/ub prepclick yes 999999");
Check.Eq(ArmCalls[^1].Timeout, RynthAiPlugin.PrepClickMaxMs, "at most 60 s");
Run("/ub prepclick no");
Check.Eq(ArmCalls[^1].Timeout, 0, "no: disarmed");
Check.Eq(Prompt(0, RynthCoreHost.ConfirmationKind.YesNo), RynthCoreHost.ConfirmationOutcome.Shown, "the next prompt is left to the client");
}
finally { TickIsolationTests.Done(); FakeHost.ConfigureApi = null; }
}
private static void ArmsAndReArms()
{
var rig = new Rig(Host());

View file

@ -58,6 +58,8 @@ internal static class ChestLootTests
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 ──────────────────────────────────────────────────────────
@ -231,6 +233,48 @@ internal static class ChestLootTests
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();

View file

@ -24,6 +24,7 @@ internal static class ChoresInFightTests
r.Add("chores: a fight is a monster in Monster Range or on top of us; never with the macro or combat off", FightSignal);
r.Add("chores: AutoCram waits while a monster is on us, and crams once the fight is over", CramWaitsForFight);
r.Add("chores: AutoCram stands down while RynthSort's auto-sort is on (they fought); off again, it crams; /ub autocram by hand still runs", CramOffWithAutoSort);
r.Add("chores: AutoCram runs with the macro off while the Item Tool's chest looter runs (#rynth-issues 2026-11-24)", CramDuringChestLooter);
}
private static CombatManager.ScannedTarget At(double yards) =>
@ -91,6 +92,40 @@ internal static class ChoresInFightTests
// Owner, 2026-11-03: "Auto sort and auto cram are fighting each other. When auto sort is on, auto
// cram should be disabled". RynthAi reads RynthSort's auto-sort (LegacyUiSettings.AutoSortOn).
// #rynth-issues 2026-11-24, "Inventory Autocram does not actively run while looting chests with
// ItemTool": the chest looter runs with the macro off as well, and Auto Cram needed the macro.
private static void CramDuringChestLooter()
{
try
{
var bot = new TickIsolationTests.Bot(heal: false, arrange: () =>
{
FakeHost.Names[Gem] = "Black Opal";
FakeHost.ItemTypes[Gem] = ItemTypeGem;
FakeHost.Containers[Gem] = Player;
FakeHost.Names[SidePack] = "Backpack";
FakeHost.ItemTypes[SidePack] = ItemTypeContainer;
FakeHost.Ints[(SidePack, ItemsCapacityKey)] = 24;
FakeHost.Containers[SidePack] = Player;
});
_ = bot.Cache[unchecked((int)Gem)];
_ = bot.Cache[unchecked((int)SidePack)];
bot.S.EnableAutocram = true;
bot.S.IsMacroRunning = false;
bool looterRunning = false;
var inv = new InventoryManager(bot.Host, bot.S, bot.Cache) { KeepsPacksWithoutMacro = () => looterRunning };
bot.Set("_inventoryManager", inv);
for (int i = 0; i < 5; i++) bot.Call("TickCramStack", bot.S);
Check.Eq(FakeHost.Moves.Count, 0, "macro off, no chest looter: Auto Cram waits, as before");
looterRunning = true;
bot.Call("TickCramStack", bot.S);
Check.True(FakeHost.Moves.Any(m => m.Id == Gem && m.Pack == SidePack),
"the chest looter running, macro off: the gem is crammed into the side pack (moves: " + string.Join(",", FakeHost.Moves.Select(m => $"{m.Id:X8}->{m.Pack:X8}")) + ")");
}
finally { TickIsolationTests.Done(); }
}
private static void CramOffWithAutoSort()
{
try

View file

@ -0,0 +1,430 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.CommandButtons;
using RynthCore.Plugin.RynthAi.Huds;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Command Buttons (2026-11-26, a player's ask): a window of buttons that each send one chat line, from
// three lists (this character, this server, all characters) kept beside the settings profiles. The file
// format and its layout, the folders, the chat line rules, colours, the grid's columns, moving, copying
// from another character, /ra buttons, a press going to RynthCore's chat parser, and the window in the
// sections manifest (no bar button).
internal static class CommandButtonsTests
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("command buttons: the file round-trips (label, command, colour, ask, layout); bad values are cleaned or clamped", FileRoundTrip);
r.Add("command buttons: the three lists load from the character's, the server's and the base folder; only what changed is saved; layout only in the character's", Folders);
r.Add("command buttons: chat line rules (one line, 200 characters, never a button that presses buttons) and what each line is", CommandLineRules);
r.Add("command buttons: colours as #RRGGBB, and text that reads on them", Colours);
r.Add("command buttons: columns (Auto fits the width), add up to the list's limit, move up and down", LayoutAddMove);
r.Add("command buttons: copy from another character on the server appends its buttons", CopyFrom);
r.Add("command buttons: /ra buttons add, list, press and remove (each replies); a press goes to RynthCore's chat parser on the tick", ChatCommand);
r.Add("command buttons: the window is in the sections manifest without a bar button; the options menu and /ra buttons show|hide open and close it", WindowAndManifest);
}
private static string TempRoot() => Path.Combine(Path.GetTempPath(), "rynth-buttons-" + Guid.NewGuid().ToString("N"));
private static CommandButton B(string label, string command, uint color = 0, bool confirm = false) =>
new() { Label = label, Command = command, Color = color, Confirm = confirm };
private static void FileRoundTrip()
{
var layout = new ButtonLayout { Columns = 4, Width = 90, Height = 30 };
var list = new[] { B("Start", "/ra start", 0xFF336699, false), B("", "*snow angel*", 0, true), B("Home", "@home") };
string json = CommandButtonSet.Serialize(list, layout);
List<CommandButton> back = CommandButtonSet.Parse(json, out ButtonLayout? l2);
Check.Eq(back.Count, 3, "three buttons back");
Check.True(back[0].Label == "Start" && back[0].Command == "/ra start" && back[0].Color == 0xFF336699 && !back[0].Confirm, "the first, with its colour");
Check.True(back[1].Label == "" && back[1].Command == "*snow angel*" && back[1].Color == 0 && back[1].Confirm, "no label, theme colour, asks first");
Check.Eq(back[2].Shown, "Home", "the label is what it shows");
Check.Eq(back[1].Shown, "*snow angel*", "no label: it shows its command");
Check.True(l2 != null && l2.Columns == 4 && l2.Width == 90 && l2.Height == 30, "the layout");
Check.False(json.Contains("\"color\": \"\""), "the theme's colour isn't written");
CommandButtonSet.Parse(CommandButtonSet.Serialize(list, null), out ButtonLayout? none);
Check.True(none == null, "no layout written: none read");
string messy = "{ \"version\": 1, \"layout\": { \"columns\": 99, \"width\": 5, \"height\": 5000 }, \"buttons\": [ "
+ "{ \"label\": \"" + new string('L', 50) + "\", \"command\": \"/ra start\\n/ra stop\", \"color\": \"blue\", \"confirm\": \"yes\" }, "
+ "{ \"command\": \"" + new string('x', 300) + "\" }, 7, { } ] }";
List<CommandButton> m = CommandButtonSet.Parse(messy, out ButtonLayout? ml);
Check.True(ml != null && ml.Columns == ButtonLayout.ColumnsMax && ml.Width == ButtonLayout.WidthMin && ml.Height == ButtonLayout.HeightMax, "the layout is clamped");
Check.Eq(m.Count, 3, "a non-object entry is skipped; an empty one is an empty button");
Check.Eq(m[0].Label.Length, CommandButton.MaxLabel, "a long label is cut to 32");
Check.Eq(m[0].Command, "/ra start /ra stop", "a command is one line");
Check.True(m[0].Color == 0 && !m[0].Confirm, "a bad colour is the theme's; confirm must be true to ask");
Check.Eq(m[1].Command.Length, CommandLine.MaxLength, "a long command is cut to 200");
Check.True(m[2].Label == "" && m[2].Command == "" && m[2].Shown == "(empty)", "an empty button");
var many = Enumerable.Range(1, CommandButtonSet.MaxPerList + 5).Select(i => B("b" + i, "/b" + i)).ToList();
Check.Eq(CommandButtonSet.Parse(CommandButtonSet.Serialize(many, null), out _).Count, CommandButtonSet.MaxPerList, "at most 60 a list");
}
private static void Folders()
{
string root = TempRoot();
string baseDir = Path.Combine(root, "SettingsProfiles"), server = Path.Combine(baseDir, "Server One"), hero = Path.Combine(server, "Hero");
Directory.CreateDirectory(hero);
try
{
File.WriteAllText(Path.Combine(hero, CommandButtonSet.FileName), CommandButtonSet.Serialize(new[] { B("Me", "/me") }, new ButtonLayout { Columns = 2, Width = 70, Height = 24 }));
File.WriteAllText(Path.Combine(server, CommandButtonSet.FileName), CommandButtonSet.Serialize(new[] { B("S1", "/s1"), B("S2", "/s2") }, new ButtonLayout { Columns = 9 }));
File.WriteAllText(Path.Combine(baseDir, CommandButtonSet.FileName), CommandButtonSet.Serialize(new[] { B("All", "/all") }, null));
var set = new CommandButtonSet();
var problems = new List<string>();
set.Load(hero, problems);
Check.Eq(problems.Count, 0, "no problems");
Check.True(set.Loaded && set.Character == "Hero" && set.Server == "Server One", "the character and server from the folders");
lock (set.Sync)
{
Check.Eq(set.List(ButtonScope.Character).Single().Command, "/me", "this character's list");
Check.Eq(string.Join(",", set.List(ButtonScope.Server).Select(b => b.Command)), "/s1,/s2", "the server's list");
Check.Eq(set.List(ButtonScope.All).Single().Command, "/all", "every character's list");
Check.True(set.Layout.Columns == 2 && set.Layout.Width == 70, "the layout is the character's (not the server file's)");
set.List(ButtonScope.Server).RemoveAt(0);
set.MarkChanged(ButtonScope.Server, 1);
}
DateTime heroTime = File.GetLastWriteTimeUtc(Path.Combine(hero, CommandButtonSet.FileName));
set.SaveDirty();
Check.False(set.AnyDirty, "saved");
string serverJson = File.ReadAllText(Path.Combine(server, CommandButtonSet.FileName));
Check.Eq(CommandButtonSet.Parse(serverJson, out ButtonLayout? sl).Single().Command, "/s2", "the server file has the edit");
Check.True(sl == null, "and no layout (only a character's file has one)");
Check.Eq(File.GetLastWriteTimeUtc(Path.Combine(hero, CommandButtonSet.FileName)), heroTime, "the character's file is untouched");
// The layout is saved with this character's list.
lock (set.Sync) { set.Layout.Columns = 5; set.MarkChanged(ButtonScope.Character, 2); }
set.SaveDirty();
var again = new CommandButtonSet();
again.Load(hero);
lock (again.Sync) Check.Eq(again.Layout.Columns, 5, "the layout survives a reload");
var other = new CommandButtonSet();
other.Load(Path.Combine(server, "Sidekick"));
lock (other.Sync)
{
Check.Eq(other.List(ButtonScope.Character).Count, 0, "another character: its own (empty) list");
Check.Eq(other.List(ButtonScope.Server).Single().Command, "/s2", "the same server list");
Check.Eq(other.List(ButtonScope.All).Single().Command, "/all", "the same all-characters list");
Check.True(other.Layout.Columns == 0 && other.Layout.Width == ButtonLayout.DefaultWidth, "and the default layout");
}
File.WriteAllText(Path.Combine(baseDir, CommandButtonSet.FileName), "{ not json");
var broken = new CommandButtonSet();
problems.Clear();
broken.Load(hero, problems);
Check.True(problems.Count == 1 && problems[0].Contains("all characters"), "a broken file is reported: " + string.Join(" | ", problems));
lock (broken.Sync) Check.Eq(broken.List(ButtonScope.Character).Count, 1, "and the others still load");
broken.SaveDirty();
Check.Eq(File.ReadAllText(Path.Combine(baseDir, CommandButtonSet.FileName)), "{ not json", "and it isn't saved over unless edited");
broken.Unload();
Check.False(broken.Loaded, "logout forgets them");
lock (broken.Sync) Check.Eq(broken.List(ButtonScope.Character).Count, 0, "(empty)");
}
finally { try { Directory.Delete(root, true); } catch { } }
}
private static void CommandLineRules()
{
Check.Eq(CommandLine.KindOf("/ra start"), CommandKind.Slash, "/ra start: a command");
Check.Eq(CommandLine.KindOf("/lua start threads"), CommandKind.Slash, "/lua: a command");
Check.Eq(CommandLine.KindOf("*snow angel*"), CommandKind.Emote, "*snow angel*: an emote");
Check.Eq(CommandLine.KindOf("*"), CommandKind.Say, "a lone * is speech");
Check.Eq(CommandLine.KindOf("* *"), CommandKind.Say, "* * is speech");
Check.Eq(CommandLine.KindOf("*wave"), CommandKind.Say, "*wave without the closing * is speech");
Check.Eq(CommandLine.KindOf("@home"), CommandKind.Server, "@home: a server command");
Check.Eq(CommandLine.KindOf("@e waves"), CommandKind.Emote, "@e waves: an emote");
Check.Eq(CommandLine.KindOf("@emote"), CommandKind.Emote, "@emote alone: an emote");
Check.Eq(CommandLine.KindOf("@echo hi"), CommandKind.Server, "@echo is not @e");
Check.Eq(CommandLine.KindOf("; grins"), CommandKind.Emote, "; grins: an emote");
Check.Eq(CommandLine.KindOf(":"), CommandKind.Say, "a lone : is speech");
Check.Eq(CommandLine.KindOf("hello all"), CommandKind.Say, "plain text is said aloud");
Check.Eq(CommandLine.KindOf(""), CommandKind.Empty, "nothing");
CommandCheck ok = CommandLine.Check(" /ra start ");
Check.True(ok.CanSend && ok.Line == "/ra start" && ok.Kind == CommandKind.Slash, "trimmed and sendable");
CommandCheck empty = CommandLine.Check(" ");
Check.True(empty.Problem == null && !empty.CanSend && empty.Kind == CommandKind.Empty, "empty is no problem, but sends nothing");
CommandCheck two = CommandLine.Check("/ra start\n/ra stop");
Check.True(!two.CanSend && two.Problem!.Contains("One line"), "two lines are refused: " + two.Problem);
CommandCheck tab = CommandLine.Check("/ra\tstart");
Check.True(tab.CanSend && tab.Line == "/ra start", "a tab is a space");
CommandCheck control = CommandLine.Check("/ra st\u0007art");
Check.True(control.CanSend && control.Line == "/ra start", "control characters go");
CommandCheck tooLong = CommandLine.Check("/" + new string('x', 200));
Check.True(!tooLong.CanSend && tooLong.Problem!.Contains("200"), "over 200 characters is refused: " + tooLong.Problem);
Check.True(CommandLine.Check("/" + new string('x', 199)).CanSend, "200 is fine");
Check.Eq(CommandLine.Clean("/" + new string('x', 300)).Length, CommandLine.MaxLength, "Clean cuts to 200");
foreach (string loop in new[] { "/ra buttons press 1", "/RA Buttons PRESS Start", "/ra button run 2", "/ra buttons server press 1", "/ra buttons all run x" })
{
CommandCheck c = CommandLine.Check(loop);
Check.True(!c.CanSend && c.Problem!.Contains("can't press buttons"), "a button can't press buttons: " + loop);
}
foreach (string fine in new[] { "/ra buttons", "/ra buttons show", "/ra buttons list", "/ra start", "/rab press 1", "/ra buttonsx press 1" })
Check.True(CommandLine.Check(fine).CanSend, "allowed: " + fine);
foreach (CommandKind k in Enum.GetValues<CommandKind>())
Check.True(CommandLine.Describe(k).Length > 0, "each kind is described: " + k);
Check.True(CommandLine.Describe(CommandKind.Say).Contains("aloud"), "plain text says it is said aloud");
Check.Eq(CommandButton.CleanLabel(" Jump\nhigh "), "Jump high", "a label is one line, trimmed");
Check.Eq(CommandButton.CleanLabel(new string('a', 40)).Length, CommandButton.MaxLabel, "a label is at most 32");
}
private static void Colours()
{
Check.True(CommandButton.TryParseColor("#FF8000", out uint orange), "#FF8000 reads");
Check.Eq(orange, 0xFF0080FFu, "as ImGui's ABGR, opaque");
Check.Eq(CommandButton.ColorText(orange), "#FF8000", "and writes back");
Check.True(CommandButton.TryParseColor("336699", out uint noHash) && CommandButton.ColorText(noHash) == "#336699", "without #");
Check.True(CommandButton.TryParseColor(" #abcdef ", out uint lower) && CommandButton.ColorText(lower) == "#ABCDEF", "lower case, spaces");
foreach (string bad in new[] { "", "#12345", "#1234567", "#GGHHII", "blue", null! })
Check.False(CommandButton.TryParseColor(bad, out uint z) || z != 0, "refused: " + (bad ?? "null"));
Check.Eq(CommandButton.ColorText(0), "", "0 is the theme's colour");
Check.True(CommandButton.TryParseColor("#000000", out uint black) && black != 0, "black is a colour, not the theme's");
Check.Eq(CommandButton.TextOn(0xFFFFFFFF), 0xFF141414u, "dark text on white");
Check.Eq(CommandButton.TextOn(0xFF202020), 0xFFF2F2F2u, "light text on dark grey");
CommandButton.TryParseColor("#FFEB3B", out uint yellow);
Check.Eq(CommandButton.TextOn(yellow), 0xFF141414u, "dark text on yellow");
CommandButton.TryParseColor("#1565C0", out uint blue);
Check.Eq(CommandButton.TextOn(blue), 0xFFF2F2F2u, "light text on blue");
}
private static void LayoutAddMove()
{
Check.Eq(ButtonLayout.ColumnsFor(3, 1000, 100, 4), 3, "set columns are kept");
Check.Eq(ButtonLayout.ColumnsFor(0, 308, 100, 4), 3, "Auto: three 100-wide buttons fit 308 (with two gaps of 4)");
Check.Eq(ButtonLayout.ColumnsFor(0, 307, 100, 4), 2, "but not 307");
Check.Eq(ButtonLayout.ColumnsFor(0, 30, 100, 4), 1, "always at least one");
Check.Eq(ButtonLayout.ColumnsFor(0, 100000, 40, 4), ButtonLayout.ColumnsMax, "at most 12");
Check.Eq(ButtonLayout.ColumnsFor(0, float.NaN, 100, 4), 1, "a NaN width is one column");
Check.Eq(ButtonLayout.ColumnsText(0), "Auto", "0 is Auto");
Check.Eq(ButtonLayout.ColumnsText(4), "4", "else the number");
var l = new ButtonLayout { Columns = -3, Width = 9999, Height = 0 };
l.Clamp();
Check.True(l.Columns == 0 && l.Width == ButtonLayout.WidthMax && l.Height == ButtonLayout.HeightMin, "clamped");
string root = TempRoot();
try
{
var set = new CommandButtonSet();
set.Load(Path.Combine(root, "SettingsProfiles", "S", "Hero"));
lock (set.Sync)
{
CommandButton? a = set.Add(ButtonScope.Character, " Jump\n", " /mt jump ", 5);
Check.True(a != null && a.Label == "Jump" && a.Command == "/mt jump", "add cleans the label and command");
Check.True(set.AnyDirty && set.ChangedAtMs == 5, "and marks the list changed");
set.Add(ButtonScope.Character, "B", "/b", 6);
set.Add(ButtonScope.Character, "C", "/c", 7);
Check.True(set.Move(ButtonScope.Character, 2, -1, 8), "C up");
Check.Eq(string.Join(",", set.List(ButtonScope.Character).Select(b => b.Label)), "Jump,C,B", "moved");
Check.False(set.Move(ButtonScope.Character, 0, -1, 9), "the first can't go up");
Check.False(set.Move(ButtonScope.Character, 2, 1, 9), "the last can't go down");
Check.False(set.Move(ButtonScope.Character, 7, 1, 9), "no such button");
Check.True(set.Move(ButtonScope.Character, 0, 1, 9), "Jump down");
Check.Eq(string.Join(",", set.List(ButtonScope.Character).Select(b => b.Label)), "C,Jump,B", "moved again");
while (set.List(ButtonScope.Server).Count < CommandButtonSet.MaxPerList) set.Add(ButtonScope.Server, "x", "/x", 10);
Check.True(set.Add(ButtonScope.Server, "y", "/y", 11) == null, "a full list takes no more");
}
}
finally { try { Directory.Delete(root, true); } catch { } }
}
private static void CopyFrom()
{
string root = TempRoot();
string server = Path.Combine(root, "SettingsProfiles", "Server One");
try
{
Directory.CreateDirectory(Path.Combine(server, "Hero"));
Directory.CreateDirectory(Path.Combine(server, "Alt"));
Directory.CreateDirectory(Path.Combine(server, "Empty")); // no buttons file: not offered
Directory.CreateDirectory(Path.Combine(server, "Bee"));
File.WriteAllText(Path.Combine(server, "Alt", CommandButtonSet.FileName),
CommandButtonSet.Serialize(new[] { B("Buff", "/ra buff", 0xFF00FF00), B("Quit", "/rc quit", 0, true) }, new ButtonLayout { Columns = 7 }));
File.WriteAllText(Path.Combine(server, "Bee", CommandButtonSet.FileName), CommandButtonSet.Serialize(new[] { B("x", "/x") }, null));
File.WriteAllText(Path.Combine(server, "Hero", CommandButtonSet.FileName), CommandButtonSet.Serialize(new[] { B("Mine", "/mine") }, null));
var set = new CommandButtonSet();
Check.Eq(set.OtherCharacters().Count, 0, "before a load: nobody");
set.Load(Path.Combine(server, "Hero"));
Check.Eq(string.Join(",", set.OtherCharacters()), "Alt,Bee", "the others with buttons, sorted, not this character");
int added = set.CopyFrom("Alt", 20, out string problem);
Check.Eq(added, 2, "two copied (" + problem + ")");
lock (set.Sync)
{
List<CommandButton> mine = set.List(ButtonScope.Character);
Check.Eq(string.Join(",", mine.Select(b => b.Label)), "Mine,Buff,Quit", "after this character's own");
Check.True(mine[1].Color == 0xFF00FF00 && mine[2].Confirm, "with their colour and ask");
Check.Eq(set.Layout.Columns, 0, "the layout stays this character's");
}
Check.True(set.AnyDirty, "and it will be saved");
Check.Eq(set.CopyFrom("Empty", 21, out problem), -1, "a character with no buttons: -1");
Check.True(problem.Contains("no buttons"), "and says so: " + problem);
Check.Eq(set.CopyFrom("..", 21, out _), -1, "no climbing out of the server's folder");
Check.Eq(set.CopyFrom("a\\b", 21, out _), -1, "no paths");
}
finally { try { Directory.Delete(root, true); } catch { } }
}
private static void RunDashActions(RynthAiPlugin p)
{
var q = (ConcurrentQueue<Action>)typeof(RynthAiPlugin).GetField("_dashActions", Any)!.GetValue(p)!;
while (q.TryDequeue(out Action? a)) a();
}
private static void ChatCommand()
{
string root = TempRoot();
try
{
FakeHost.Reset();
FakeHost.Create(0x50000F77);
var p = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
var set = (CommandButtonSet)typeof(RynthAiPlugin).GetField("_buttons", Any)!.GetValue(p)!;
MethodInfo handle = typeof(RynthAiPlugin).GetMethod("HandleButtonsCommand", Any)!;
string Say(string line)
{
int before = FakeHost.Chat.Count;
handle.Invoke(p, new object[] { line.Split(' ', StringSplitOptions.RemoveEmptyEntries) });
return string.Join(" | ", FakeHost.Chat.Skip(before));
}
Check.True(Say("/ra buttons list").Contains("load once you are in the world"), "before the lists load: it says why");
string hero = Path.Combine(root, "SettingsProfiles", "Server One", "Hero");
set.Load(hero);
Check.True(Say("/ra buttons list").Contains("No command buttons for this character"), "an empty list says so");
string add = Say("/ra buttons add Angel = *snow angel*");
Check.True(add.Contains("Command button 1 for this character: Angel sends *snow angel*"), "add with a label replies (" + add + ")");
Check.True(File.Exists(Path.Combine(hero, CommandButtonSet.FileName)), "and saves the character's file");
Check.True(Say("/ra buttons add /ra start").Contains("Command button 2 for this character: /ra start sends /ra start"), "add without a label");
Check.True(Say("/ra buttons server add Home = @home").Contains("for this server: Home sends @home"), "server add");
Check.True(File.Exists(Path.Combine(root, "SettingsProfiles", "Server One", CommandButtonSet.FileName)), "saved in the server's folder");
Check.True(Say("/ra buttons all add Loc = /loc").Contains("for all characters: Loc sends /loc"), "all add");
Check.True(Say("/ra buttons add Loop = /ra buttons press 1").Contains("can't press buttons"), "a button that presses buttons is refused");
Check.True(Say("/ra buttons add").Contains("Usage: /ra buttons add <label> = <command>"), "add with nothing gives the usage");
Check.True(Say("/ra buttons add Empty =").Contains("Usage"), "a label with no command gives the usage");
lock (set.Sync) Check.Eq(set.List(ButtonScope.Character).Count, 2, "none of those added anything");
string list = Say("/ra buttons list");
Check.True(list.Contains("Command buttons for this character (2)") && list.Contains("1. Angel: *snow angel*") && list.Contains("2. (no label): /ra start"),
"list shows them (" + list + ")");
// A press: queued for the tick, then RynthCore's chat parser gets the line as typed.
FakeHost.ChatCommands.Clear();
string press = Say("/ra buttons press Angel");
Check.True(press.Contains("Pressing command button 1 for this character: Angel"), "press by label replies (" + press + ")");
Check.Eq(FakeHost.ChatCommands.Count, 0, "nothing sent inside the chat command itself");
RunDashActions(p);
Check.Eq(string.Join(" | ", FakeHost.ChatCommands), "*snow angel*", "the tick sends the line to the chat parser");
Say("/ra buttons server press 1");
RunDashActions(p);
Check.Eq(FakeHost.ChatCommands.LastOrDefault(), "@home", "press by number, on the server's list");
Check.True(Say("/ra buttons press 9").Contains("There is no command button '9'"), "a number past the list says so");
Check.True(Say("/ra buttons press").Contains("Usage: /ra buttons press <n or label>"), "press with nothing gives the usage");
// A button with no command: not sent, and it says why.
lock (set.Sync) set.Add(ButtonScope.Character, "Blank", "", 1);
int sent = FakeHost.ChatCommands.Count;
Say("/ra buttons press Blank");
int chatBefore = FakeHost.Chat.Count;
RunDashActions(p);
Check.Eq(FakeHost.ChatCommands.Count, sent, "an empty button sends nothing");
Check.True(string.Join(" | ", FakeHost.Chat.Skip(chatBefore)).Contains("wasn't sent: it has no command yet"), "and says why");
Check.True(Say("/ra buttons remove 1").Contains("Removed command button 1 for this character: Angel"), "remove replies");
lock (set.Sync) Check.Eq(set.List(ButtonScope.Character)[0].Command, "/ra start", "and it is gone");
Check.True(CommandButtonSet.Parse(File.ReadAllText(Path.Combine(hero, CommandButtonSet.FileName)), out _).All(b => b.Label != "Angel"), "from the file too");
Check.True(Say("/ra buttons frobnicate").Contains("Usage: /ra buttons"), "an unknown verb gives the usage");
}
finally { try { Directory.Delete(root, true); } catch { } }
}
private static readonly List<(string Key, int Mode)> PanelCalls = new();
[System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })]
private static unsafe int FakeSetPanelOpen(byte* key, int mode)
{
PanelCalls.Add((System.Runtime.InteropServices.Marshal.PtrToStringUTF8((IntPtr)key) ?? "", mode));
return mode == 0 ? 0 : 1;
}
private static unsafe void PanelApi(ref RynthCoreApiNative api)
{
api.Version = Math.Max(api.Version, 89u);
api.SetPanelOpenFn = (IntPtr)(delegate* unmanaged[Cdecl]<byte*, int, int>)&FakeSetPanelOpen;
}
private static void WindowAndManifest()
{
string without = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections);
Check.False(without.Contains("commandbuttons"), "not asked for: not there");
string with = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, commandButtons: true);
using (var doc = System.Text.Json.JsonDocument.Parse(with))
{
var win = doc.RootElement.GetProperty("windows").EnumerateArray().Single();
Check.Eq(win.GetProperty("id").GetString(), "commandbuttons", "the window's id");
Check.Eq(win.GetProperty("title").GetString(), RynthAiPlugin.CommandButtonsTitle, "its title");
Check.Eq(win.GetProperty("surface").GetString(), RynthAiPlugin.CommandButtonsSurface, "its surface");
Check.False(win.GetProperty("bar").GetBoolean(), "no bar button (the options menu, /ra buttons and Find a Feature open it)");
Check.True(win.GetProperty("icon").GetString()!.Length > 0, "an icon for its header");
}
string all = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections,
dashboard: true, monsterStats: true, timedCommands: true, activeGear: true, featureSearch: true, commandButtons: true);
using (var doc = System.Text.Json.JsonDocument.Parse(all))
Check.True(doc.RootElement.GetProperty("windows").GetArrayLength() <= 8, "every RynthAi window fits the engine's 8");
try
{
FakeHost.Reset();
PanelCalls.Clear();
FakeHost.ConfigureApi = PanelApi;
FakeHost.Create(0x50000F77);
var p = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
// What the dashboard's ⋯ > Command buttons runs (queued to the tick by RynthAiPlugin.Dashboard.cs).
typeof(RynthAiPlugin).GetMethod("ToggleCommandButtonsWindow", Any)!.Invoke(p, null);
Check.Eq(PanelCalls.Count, 1, "one call to the engine");
Check.True(PanelCalls[0].Key == RynthAiPlugin.CommandButtonsTitle && PanelCalls[0].Mode == (int)RynthPanelOpen.Toggle,
"toggles the Command Buttons window (" + PanelCalls[0] + ")");
MethodInfo handle = typeof(RynthAiPlugin).GetMethod("HandleButtonsCommand", Any)!;
string Say(string line)
{
int before = FakeHost.Chat.Count;
handle.Invoke(p, new object[] { line.Split(' ', StringSplitOptions.RemoveEmptyEntries) });
return string.Join(" | ", FakeHost.Chat.Skip(before));
}
Check.True(Say("/ra buttons").Contains("Command Buttons window open"), "/ra buttons alone opens it");
Check.Eq(PanelCalls.Last().Mode, (int)RynthPanelOpen.Open, "(open, not toggle: Find a Feature's Open button runs it)");
Check.True(Say("/ra buttons show").Contains("Command Buttons window open"), "/ra buttons show opens it");
Check.True(Say("/ra buttons hide").Contains("Command Buttons window closed"), "/ra buttons hide closes it");
Check.Eq(PanelCalls.Last().Mode, (int)RynthPanelOpen.Close, "(close)");
Check.True(Say("/ra buttons edit").Contains("editing the buttons for this character"), "/ra buttons edit opens it to edit");
Check.True(Say("/ra buttons server edit").Contains("editing the buttons for this server"), "on the server's list");
}
finally
{
FakeHost.ConfigureApi = null;
}
}
}

View file

@ -96,6 +96,7 @@ internal static class CommandReplyTests
new("/ra cast 1234", "/ra cast banana", K.Act),
new("/ra targetlock off", null, K.Act),
new("/ra fightselected off", "/ra fightselected banana", K.Act),
new("/ra losline off", "/ra losline banana", K.Act),
new("/ra dfheight on", "/ra dfheight banana", K.Act),
new("/ra dfheight off", null, K.Act),
new("/ra dfheight window", null, K.Act),
@ -178,6 +179,12 @@ internal static class CommandReplyTests
new("/ra kits auto on", null, K.Act),
new("/ra kits auto below 3", "/ra kits auto below 0", K.Act),
new("/ra kits auto upto 4", "/ra kits auto upto 500", K.Act),
new(null, "/ra ammo banana", K.Act), // unknown option: the usage
new(null, "/ra ammo make", K.Act), // no crafting in this rig: why not
new("/ra ammo auto off", "/ra ammo auto banana", K.Act),
new("/ra ammo auto on", null, K.Act),
new("/ra ammo auto below 150", "/ra ammo auto below 0", K.Act),
new("/ra ammo auto upto 800", "/ra ammo auto upto 99999", K.Act),
new("/ra petelement cold", "/ra petelement banana", K.Act),
new("/ra petelement any", null, K.Act),
new(null, "/ra nosuchverb", K.Act),
@ -191,6 +198,10 @@ internal static class CommandReplyTests
new("/ra kits status", null, K.Query),
new("/ra kits auto", null, K.Query),
new("/ra kits auto status", null, K.Query),
new("/ra ammo", null, K.Query),
new("/ra ammo status", null, K.Query),
new("/ra ammo auto", null, K.Query),
new("/ra ammo auto status", null, K.Query),
new("/ra petelement", null, K.Query),
new("/ra petelement status", null, K.Query),
new("/ra", null, K.Query),

View file

@ -16,6 +16,7 @@ internal static class CorpseKillerTests
r.Add("corpse killer: CRLF and multi-word names", CrLfMultiWord);
r.Add("corpse killer: no 'Killed by' line reads as unknown", Missing);
r.Add("corpse killer: radar column reads the same name", RadarMatches);
r.Add("fellowship kills: a known killer outside the read member list is not looted; unknown killer, a fellow or no list yet still are", FellowModeLoots);
}
private static void Plain()
@ -46,7 +47,17 @@ internal static class CorpseKillerTests
Check.Null(RynthAiPlugin.ExtractCorpseKillerName("Killed by .\nCorpse will decay in 56s"), "empty killer");
}
private static void RadarMatches()
// #rynth-issues 2026-11-25: "Rynth treats all corpses as fellowship kills, both player corpses and monster corpses".
private static void FellowModeLoots()
{
Check.False(RynthAiPlugin.FellowModeLoots("Someone Else", killerIsFellow: false, membersKnown: 4), "someone else's kill, the list read: left");
Check.False(RynthAiPlugin.FellowModeLoots("Mite Defiler", killerIsFellow: false, membersKnown: 4), "a player's death corpse (a monster killed them): left");
Check.True(RynthAiPlugin.FellowModeLoots("A Fellow", killerIsFellow: true, membersKnown: 4), "a fellow's kill: looted");
Check.True(RynthAiPlugin.FellowModeLoots("", killerIsFellow: false, membersKnown: 4), "killer not known yet: looted pending the ID");
Check.True(RynthAiPlugin.FellowModeLoots("Someone Else", killerIsFellow: false, membersKnown: 0), "member list not read yet: the server decides, as before");
}
private static void RadarMatches()
{
Check.Eq(RynthRadarUi.ExtractKiller("Killed by Silentkelpie.\nCorpse will decay in 56s"), "Silentkelpie", "radar decay line");
Check.Eq(RynthRadarUi.ExtractKiller(null), "", "radar unknown is empty");

View file

@ -66,6 +66,7 @@ internal static class ExpressionTests
r.Add("expr doc: unquoted text keeps its spaces, backslash escapes a character", DocStrings);
r.Add("expr doc: true and false are 1 and 0", DocTrueFalse);
r.Add("expr doc: @name and &name read pvars and gvars, $ takes an expression", DocVarShorthand);
r.Add("expr: pvars read before the character's name is known join the character's file once it is (R-20261125-190541-5671)", PvarsBeforeName);
r.Add("expr doc: {index}, {key} and slices on lists, dicts and text", DocIndexAndSlice);
r.Add("expr: $x = value assigns (UB syntax real metas use)", AssignmentSyntax);
r.Add("expr doc: listadd, listpop and friends change the list in its variable", DocListsChangeInPlace);
@ -283,6 +284,35 @@ internal static class ExpressionTests
Is(e, "$host_set", "7");
}
// Coldeve, "Doesn't seem like getpvar/setpvar works in the meta?": a read before the name loaded "unknown.txt"
// for the whole session, and the next save wrote over the character's own file.
private static void PvarsBeforeName()
{
string pvarDir = ExpressionEngine.PvarsDir;
Directory.CreateDirectory(pvarDir);
string pfile = Path.Combine(pvarDir, "Late Name.txt");
File.Delete(Path.Combine(pvarDir, "unknown.txt")); // another test writes it
const string Saved = "saved\t7\nlist\t[a,b]\n";
File.WriteAllText(pfile, Saved);
FakeHost.Reset();
var host = FakeHost.Create();
var e = Engine(host, playerId: Player); // the client has no name for the player yet
Is(e, "getpvar[saved]", "0");
Is(e, "setpvar[fresh, 3]", "3");
e.FlushVars(force: true);
Check.Eq(File.ReadAllText(pfile), Saved, "nothing saved before the name is known (the file is kept)");
Check.False(File.Exists(Path.Combine(pvarDir, "unknown.txt")), "no unknown.txt");
FakeHost.Names[Player] = "Late Name"; // the name arrives
Is(e, "getpvar[saved]", "7");
Is(e, "listcontains[getpvar[list], b]", "1");
Is(e, "getpvar[fresh]", "3");
e.FlushVars(force: true);
string text = File.ReadAllText(pfile);
Check.True(text.Contains("saved\t7") && text.Contains("fresh\t3") && text.Contains("list\t[a,b]"), "saved together: " + text);
File.Delete(pfile);
}
private static void PersistentVars()
{
string pvarDir = ExpressionEngine.PvarsDir;

View file

@ -51,6 +51,31 @@ internal static class FeatureCatalogTests
r.Add("find a feature: the window is in the manifest with no bar button", Manifest);
r.Add("find a feature: /ra find opens the window with the words and says the count", FindCommand);
r.Add("find a feature: /ra find without plugin windows prints the best matches", FindCommandNoWindows);
r.Add("find a feature: streaks and Sense's exact match are found by the words players use", PlayerWords);
}
// 2026-11-26 (#rynthsuite): a new player couldn't find how to cast streaks, and Sense gained Exact.
// The words they'd type must bring the entry up near the top of the real catalog.
private static void PlayerWords()
{
List<FeatureEntry> all = Catalog().Entries.ToList();
void Finds(string query, string id, int within)
{
List<string> ids = FeatureSearch.Search(all, query).Select(h => h.Entry.Id).ToList();
int at = ids.IndexOf(id);
Check.True(at >= 0 && at < within, $"'{query}' finds {id} in the first {within} (at {at}: {string.Join(", ", ids.Take(5))})");
}
Finds("streak", "ai.use-streaks", 3);
Finds("streaks instead of bolts", "ai.use-streaks", 1);
Finds("bolt", "ai.use-streaks", 3);
Finds("arc", "ai.use-streaks", 5);
Finds("war spell type", "ai.use-streaks", 3);
Finds("exact match", "core.sense-exact", 1);
Finds("sense exact", "core.sense-exact", 1);
Finds("whole name", "core.sense-exact", 3);
FeatureEntry streaks = all.Single(e => e.Id == "ai.use-streaks");
Check.True(streaks.Where.Any(w => w == "Settings > Spell Combat > Use streaks instead of bolts"), "it says where: Settings > Spell Combat");
Check.Eq(streaks.Open, "/rc settings Spell Combat", "and opens that tab");
}
// ── Where things are ─────────────────────────────────────────────────
@ -364,7 +389,7 @@ internal static class FeatureCatalogTests
internal static List<string> ManifestSurfaces()
{
string json = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections,
dashboard: true, monsterStats: true, timedCommands: true, activeGear: true, featureSearch: true);
dashboard: true, monsterStats: true, timedCommands: true, activeGear: true, featureSearch: true, acMaps: true, commandButtons: true, tradeShop: true);
SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error);
Check.Eq(error, string.Empty, "the manifest parses");
var names = new List<string>();

View file

@ -26,6 +26,35 @@ internal static class HandSwapTests
private const int Melee = HandSwapSequence.MeleeSlot, Off = HandSwapSequence.ShieldSlot, Missile = HandSwapSequence.MissileSlot,
Ammo = HandSwapSequence.AmmoSlot, Held = HandSwapSequence.HeldSlot, Two = HandSwapSequence.TwoHandedSlot;
// 2026.11.23.3: a wand wielded since login has no home pack; the swap put it into a side pack, the game
// itself puts what it unwields into the main pack.
private static void UnknownHomeMainPack()
{
const uint PackA = 0x80000801, Filler = 0x80000810;
FakeHost.Reset();
FakeHost.ContentsCalls = true;
var ids = new List<uint>();
FakeHost.Names[PackA] = "Pack A"; FakeHost.ItemTypes[PackA] = 0x200; FakeHost.Ints[(PackA, 6)] = 24;
FakeHost.Containers[PackA] = Player; ids.Add(PackA);
FakeHost.Names[Sceptre] = "Sceptre"; FakeHost.ItemTypes[Sceptre] = 0x8000;
FakeHost.Wielders[Sceptre] = Player; ids.Add(Sceptre); // wielded since login: never in a pack
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, ids);
var clock = new DateTime(2026, 11, 25, 4, 0, 0);
cache.WalkClock = () => clock;
cache.GetDirectInventory(forceRefresh: true);
Check.Eq(cache.HomePackOf(I(Sceptre)), 0, "no home known");
Check.Eq(WorldObjectCache.FindPackFor(host, cache, includeMainPack: true, requireFree: 1, new[] { I(Sceptre) }), I(Player),
"put away: the main pack, as the game unwields (it was the side pack)");
Check.Eq(WorldObjectCache.FindPackFor(host, cache, includeMainPack: true, requireFree: 1), I(PackA), "without the item list: the usual choice");
// The main pack down to 4 free slots: the side pack (loot keeps its room).
for (uint i = 0; i < 98; i++) { FakeHost.Names[Filler + i] = $"Gem {i}"; FakeHost.ItemTypes[Filler + i] = 0x800; FakeHost.Containers[Filler + i] = Player; _ = cache[I(Filler + i)]; }
clock = clock.AddSeconds(2);
Check.Eq(WorldObjectCache.FindPackFor(host, cache, includeMainPack: true, requireFree: 1, new[] { I(Sceptre) }), I(PackA),
"main pack with 4 free: the side pack instead");
}
// 2026.11.19.1: "When the macro swaps out wands it randomly throws them into pack 1, 2 or 4": every put-away
// took the side pack with the most free slots at that moment.
private static void HomePackFirst()
@ -72,6 +101,7 @@ internal static class HandSwapTests
{
r.Add("hand swap: dual wield -> wand: the off hand, then the main hand, then the wand, each once the last landed", DualWieldOrder);
r.Add("weapon put away (R-20261121-040524-f6ed): back to the pack it came from while that has room, not the emptiest pack", HomePackFirst);
r.Add("weapon put away (R-20261125-040855-4588): never seen in a pack (wielded since login): the main pack, as the game unwields, while it keeps 4 slots for loot", UnknownHomeMainPack);
r.Add("hand swap: sword + shield, two-hander, bow (arrows stay on), empty hands, a wand already in hand", Loadouts);
r.Add("hand swap: peace first from a combat mode, then the hands (answered at once in peace), then the wand", PeaceFirst);
r.Add("hand swap: an unanswered step is sent again once, then the swap fails (bounded)", Bounded);

View file

@ -28,6 +28,7 @@ internal static class HealUpSpeedTests
r.Add("heal up: Combat off, Heal At 0, a monster hitting, the animation busy between hits: a kit goes within 1.1 s", CombatOffHitAnimatingHealsFast);
r.Add("heal up: Combat off, a monster in range: Top Off HP is the health line (not Heal At)", CombatOffUsesTopOffLine);
r.Add("heal up: Combat on keeps Heal At in a fight; Heal At 0 with no emergency line heals nothing and says so", CombatOnFightLineUnchanged);
r.Add("heal up (11-23): while Boost Loot's looting has the tick, Top Off HP is the health line and a kit goes; Heal At again once it hasn't", BoostLootLootingUsesTopOffLine);
r.Add("heal up: the animation cap counts only animation holds, and resets once the vitals step is reached", AnimationCapCountsOnlyAnimation);
r.Add("heal up: peace with the weapon in hand gets the weapon-out kit bar (30%); the wand in hand or Magic keep Kit Min Success", PeaceWeaponOutKitBar);
r.Add("heal up: [HealLatency] ends an episode at a macro stop; the heal after the restart counts from the restart", HealLatencyMacroOff);
@ -198,6 +199,33 @@ internal static class HealUpSpeedTests
finally { Done(); }
}
private static void BoostLootLootingUsesTopOffLine()
{
try
{
var (b, s, v, h) = Rig(enableCombat: true, healAt: 30);
b.InCombatOverride = () => true; // a monster within Monster Range
bool looting = true;
b.BoostLootHealsToTopOff = () => looting;
v.CurrentHealth = 300; // 60%: over Heal At 30, under Top Off HP 80
Check.True(b.WantsHealNow(), "Boost Loot looting: Top Off HP 80% is the line");
Check.True(b.CheckVitals(), "the vitals act");
Check.True(KitSent, "a kit went out: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("Vitals")).Take(6)));
var (b2, s2, v2, h2) = Rig(enableCombat: true, healAt: 30);
b2.InCombatOverride = () => true;
b2.BoostLootHealsToTopOff = () => false; // the looting doesn't have the tick (no loot work, or Boost Loot off)
v2.CurrentHealth = 300;
Check.False(b2.WantsHealNow(), "not looting: Heal At 30% is the fight's line, as before");
b2.CheckVitals();
Check.False(KitSent, "no kit");
b2.BoostLootHealsToTopOff = () => throw new InvalidOperationException("hook threw");
Check.False(b2.WantsHealNow(), "a hook that throws counts as not looting");
}
finally { Done(); }
}
private static void CombatOnFightLineUnchanged()
{
try

View file

@ -32,6 +32,7 @@ internal static class ItemToolTests
// 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: the main pack full -> no key spent; room again in time -> it goes on; full 30 s -> stops with the reason (#rynth-issues 2026-11-24)", ChestStopsWhenPackFull);
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);
@ -43,6 +44,7 @@ internal static class ItemToolTests
r.Add("chest looter: after a short re-lock wait the asks follow it (never under 5 s apart), bounded; a long wait still ends when the chest reads locked", ChestRelockProbes);
// 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: an NPC that takes one per give: each stack is given again until it is gone (R-20261125-205340-1218)", GiveOnePerStack);
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);
@ -98,6 +100,8 @@ internal static class ItemToolTests
return 0;
}
public string? HoldReason() => Hold;
public string? NoRoom;
public string? NoRoomReason() => NoRoom;
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)
@ -220,6 +224,33 @@ internal static class ItemToolTests
Check.Eq(ck.Looted, 2, "two chests looted");
}
// #rynth-issues 2026-11-24: "when the pack is full it keeps unlocking chests and using keys but fails to loot them".
private static void ChestStopsWhenPackFull()
{
var env = NewChest(out var ck);
env.Keys.Clear(); env.Keys.Add(11); env.Keys.Add(12);
Serve(env, ck);
env.AutoLootMs = 1000;
env.NoRoom = "the main pack is full";
ck.Start(out _);
env.Run(10_000);
Check.Eq(env.Sent.Count, 0, "the main pack full: no key used");
Check.True(ck.Running, "10 s: still waiting for room");
Check.True(env.Logs.Any(l => l.Contains("waits before the next key - the main pack is full")), "the wait is logged");
env.NoRoom = null; // Auto Cram made room
env.Run(5000, () => env.Sent.Count > 0);
Check.Eq(env.Sent.FirstOrDefault(), "key 11", "room again: the key goes on the chest");
env.Run(5000, () => ck.State == ChestKeyLooter.Phase.Waiting);
env.NoRoom = "the main pack is full";
int sent = env.Sent.Count;
env.Run(ChestKeyLooter.RegenWaitMs + ChestKeyLooter.NoRoomMaxMs + 5000, () => !ck.Running);
Check.False(ck.Running, "full for 30 s before the next key: the run stops");
Check.Eq(env.Sent.Count, sent, "no second key spent");
Check.True(Said(env).Contains("stopped before the next key: the main pack is full"), "says why: " + Said(env));
}
private static void ChestAlreadyUnlockedProbes()
{
var env = NewChest(out var ck);
@ -545,7 +576,12 @@ internal static class ItemToolTests
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 TakesOneAtATime; // the NPC takes one unit of a stack per give
public bool Landed(int itemId, int count, out int left)
{
left = Items.Contains(itemId) ? (Counts.TryGetValue(itemId, out int c) ? c : 1) : 0;
return !Items.Contains(itemId) || left < count;
}
public bool Send(int itemId, int targetId)
{
Sent.Add((T, itemId));
@ -564,7 +600,12 @@ internal static class ItemToolTests
while (T < end && (until == null || !until()))
{
T += 50;
if (PendingLand != 0 && T >= LandAt) { Items.Remove(PendingLand); PendingLand = 0; }
if (PendingLand != 0 && T >= LandAt)
{
if (TakesOneAtATime && Counts.TryGetValue(PendingLand, out int c) && c > 1) Counts[PendingLand] = c - 1;
else Items.Remove(PendingLand);
PendingLand = 0;
}
Gv.Tick();
}
}
@ -595,6 +636,21 @@ internal static class ItemToolTests
Check.True(qg.Status.Contains("3 item(s)"), "the status keeps the result: " + qg.Status);
}
// DreamWeave: a Collector took one Kirit Zefir Wing per give; the run gave one from each of 6 stacks and stopped.
private static void GiveOnePerStack()
{
var env = NewGive(out var qg);
env.Items.Clear(); env.Items.Add(1); env.Items.Add(2);
env.Counts[1] = 3; env.Counts[2] = 2;
env.TakesOneAtATime = true;
qg.Start(out _);
env.Run(60_000, () => !qg.Running);
Check.Eq(string.Join(",", env.Sent.Select(s => s.Item)), "1,1,1,2,2", "each stack given again until it is gone");
Check.Eq(qg.Given, 5, "five gives");
Check.Eq(qg.Units, 5, "five units (not the stacks' sizes added up)");
Check.True(env.Said.Last().Contains("done"), "done when none is left: " + env.Said.Last());
}
private static void GiveRefusals()
{
// One refused item is skipped; the others go.

View file

@ -53,6 +53,8 @@ internal static class LootCorpseTests
r.Add("boost loot: our kill holds the next target until its corpse is looted (one kill, one loot)", BoostLootOneKillOneLoot);
r.Add("boost loot: the wait ends after BoostLootKillWaitMs, and with Boost Loot off; a close monster waits for the corpse unless health is under Heal At", BoostLootHoldLimits);
r.Add("boost loot: looting the kill's corpse ends the wait; an older corpse does not", BoostLootWaitEndsOnKillCorpse);
r.Add("boost loot (11-23): under Top Off HP mid-loot with a monster close, the heal wins the tick; the claim is kept and looting resumes once healed", BoostLootHealsBeforeLooting);
r.Add("boost loot (11-23): Top Off HP only while Boost Loot's looting has the tick: not with Boost Loot off, no loot work, or under Heal At", BoostLootHealLimits);
r.Add("boost loot / starved loot (11-22): a monster in range hitting us from beyond 5 yd is fought; the corpse waits", HitFromAfarIsAFight);
r.Add("death wait (11-08, R-20261115-165857-1de7): the learned death + 1 s keeps nav off; a monster in range is locked at once", DeathWaitUsesLearnedTime);
r.Add("death wait (11-08): not learned yet: 2.5 s + 1 s; the corpse's coming is timed and learned", DeathWaitDefaultAndLearns);
@ -72,6 +74,7 @@ internal static class LootCorpseTests
r.Add("corpse close: not while the last item is between the corpse and the pack - it closes once the item is in the inventory", CloseWaitsForInventory);
r.Add("loot pacing: an item merged into a stack in the pack is confirmed without the 4 s arrival wait", MergedPickupConfirmedQuickly);
r.Add("loot pacing: each item taken restarts the corpse timeout, so a corpse with many keeps is looted to the end", ManyKeepsBeatTheTimeout);
r.Add("jump loot (2026-11-22): a corpse that closes during a jump pickup is reopened with jump-loot off; 3 closes during one item's pickups leave it (no reopen loop)", JumpLootCloseLoopEnds);
}
// ── World set-up ──────────────────────────────────────────────────────────
@ -555,12 +558,15 @@ internal static class LootCorpseTests
/// HoldNewTarget wired to the plugin. The corpse is created only with <paramref name="withCorpse"/>.
/// </summary>
private static Bot BoostWorld(float monsterMeters, bool withCorpse, out CombatManager combat, bool boost = true)
=> BoostWorld(monsterMeters, withCorpse, out combat, out _, boost);
private static Bot BoostWorld(float monsterMeters, bool withCorpse, out CombatManager combat, out RynthCoreHost host, bool boost = true)
{
BaseWorld(corpsePositioned: true);
FakeHost.Names[Monster] = "Ancient Water Elemental";
FakeHost.ItemTypes[Monster] = ItemTypeCreature;
FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + monsterMeters, Me0.Y + 0.5f, Me0.Z);
var host = FakeHost.Create(Player);
host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.EnableCombat = true;
bot.S.MonsterRange = 50;
@ -718,6 +724,144 @@ internal static class LootCorpseTests
Check.False((bool)bot.Call("BoostLootHoldsNewTarget")!, "so combat goes on at once");
}
// ── Boost Loot heals first (2026-11-23, the owner: "for loot boost below health max it keeps
// looting. I think it should interrupt looting and heal") ──
/// <summary>
/// The vitals step on the plugin's settings and vitals, wired as RynthAiPlugin wires it, with a
/// monster within Monster Range (InCombatOverride) so the fight's heal line would apply.
/// </summary>
private static BuffManager BoostVitals(Bot bot, RynthCoreHost host, PlayerVitalsCache v, bool wired = true)
{
bot.Set("_vitals", v);
var sm = new SpellManager(host, bot.S);
var b = new BuffManager(host, bot.S, sm, v);
b.InCombatOverride = () => true;
if (wired) b.BoostLootHealsToTopOff = () => (bool)bot.Call("BoostLootHealsToTopOff")!;
return b;
}
private static PlayerVitalsCache Vitals(uint health)
=> new() { MaxHealth = 500, CurrentHealth = health, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
/// <summary>One arbiter tick as RynthAiPlugin.OnTick builds it (the Boost Loot corpses-first part).</summary>
private static BotActivity Decide(Bot bot, CombatManager combat, BuffManager b)
{
bool wantBuff = b.PendingSpellId != 0 || b.WantsVitalRecharge;
bool wantLoot = bot.HasLootWork();
bot.Set("_lastWantLoot", wantLoot);
bool engaged = combat.IsUnderCloseAttack;
if (engaged && wantLoot && (bool)bot.Call("BoostLootFirst", bot.S)!) engaged = false;
var inputs = new ArbiterInputs(true, wantBuff, combat.HasEngageableTarget, wantLoot, false, false,
combatEngaged: engaged, boostLoot: bot.S.BoostLootPriority);
var act = ActivityArbiter.Decide(in inputs);
bot.S.BotAction = ActivityArbiter.ToBotAction(act);
return act;
}
private static void BoostLootHealsBeforeLooting()
{
var bot = BoostWorld(2f, withCorpse: true, out var combat, out var host);
bot.S.HealAt = 60;
bot.S.TopOffHP = 95;
bot.S.EmergencyHealAt = 0;
bot.S.StaminaToHealthAt = 0;
var v = Vitals(500);
var b = BoostVitals(bot, host, v);
// Full health: the corpse is claimed and opened with a monster 2 m away (corpses first).
Check.Eq(Decide(bot, combat, b), BotActivity.Looting, "full health, a monster close: Boost Loot loots first");
bot.Tick(BotActivity.Looting);
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)Corpse), "the corpse is claimed");
Check.True(FakeHost.Uses.Contains(Corpse), "and opened");
// Hit to 70%: over Heal At 60, under Top Off HP 95. It used to loot on (the fight's line, Heal At).
v.CurrentHealth = 350;
var old = BoostVitals(bot, host, v, wired: false);
Check.False(old.WantsHealNow(), "the old rule: in a fight the line is Heal At 60, 70% is over it (looting went on)");
Check.True((bool)bot.Call("BoostLootHealsToTopOff")!, "Boost Loot's looting has the tick: Top Off HP applies");
Check.True(b.WantsHealNow(), "70% < Top Off HP 95: a heal is wanted");
Check.Eq(Decide(bot, combat, b), BotActivity.Buffing, "the heal wins the tick over looting");
// The server opens the corpse while the heal has the tick: nothing is picked up, the claim stays.
bot.Cache.OnCreateObject(Gem);
bot.Cache.Tick();
bot.P.OnViewObjectContents(Corpse);
for (int i = 0; i < 20; i++)
{
bot.Tick(BotActivity.Buffing);
Thread.Sleep(10);
}
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "no pickup while healing");
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)Corpse), "the claim is kept through the heal");
// Healed over Top Off HP: looting resumes on the same corpse.
v.CurrentHealth = 480; // 96%
Check.False(b.WantsHealNow(), "96%: over Top Off HP, no heal wanted");
Check.Eq(Decide(bot, combat, b), BotActivity.Looting, "looting has the tick again");
for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++)
{
bot.Tick(BotActivity.Looting);
Thread.Sleep(10);
}
Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "the gem is looted after the heal");
// Heal At 0: the fight's line healed nothing; Top Off HP heals while looting.
var dw = BoostWorld(2f, withCorpse: true, out var combatDw, out var hostDw);
dw.S.HealAt = 0;
dw.S.TopOffHP = 80;
dw.S.EmergencyHealAt = 0;
dw.S.StaminaToHealthAt = 0;
var vDw = Vitals(500);
var bDw = BoostVitals(dw, hostDw, vDw);
Check.Eq(Decide(dw, combatDw, bDw), BotActivity.Looting, "Heal At 0, full health: looting (the tick that records loot work)");
vDw.CurrentHealth = 350; // 70%
Check.False(BoostVitals(dw, hostDw, vDw, wired: false).WantsHealNow(), "Heal At 0, the old rule: no heal at 70% in a fight");
Check.Eq(Decide(dw, combatDw, bDw), BotActivity.Buffing, "Heal At 0: 70% < Top Off HP 80 while looting: the heal wins");
vDw.CurrentHealth = 410; // 82%
Check.Eq(Decide(dw, combatDw, bDw), BotActivity.Looting, "over Top Off HP: looting");
}
private static void BoostLootHealLimits()
{
// Boost Loot off: the fight's line (Heal At) as before; nothing changes.
var off = BoostWorld(2f, withCorpse: true, out _, out var hostOff, boost: false);
off.S.HealAt = 60;
off.S.TopOffHP = 95;
var vOff = Vitals(350);
var bOff = BoostVitals(off, hostOff, vOff);
off.Set("_lastWantLoot", true);
Check.False((bool)off.Call("BoostLootHealsToTopOff")!, "Boost Loot off: no Top Off line");
Check.False(bOff.WantsHealNow(), "Boost Loot off, 70%, Heal At 60 in a fight: no heal (unchanged)");
// Boost Loot on, no loot work: a fight like any other.
var idle = BoostWorld(2f, withCorpse: false, out _, out var hostIdle);
idle.S.HealAt = 60;
idle.S.TopOffHP = 95;
var vIdle = Vitals(350);
var bIdle = BoostVitals(idle, hostIdle, vIdle);
idle.Set("_lastWantLoot", false);
Check.False((bool)idle.Call("BoostLootHealsToTopOff")!, "no loot work: no Top Off line");
Check.False(bIdle.WantsHealNow(), "no loot work, 70%: Heal At 60 is the line (unchanged)");
// Under Heal At: a monster on you is fought first, as before (11-22), and the fight's line heals.
var low = BoostWorld(2f, withCorpse: true, out var combatLow, out var hostLow);
low.S.HealAt = 60;
low.S.TopOffHP = 95;
low.S.EmergencyHealAt = 0;
low.S.StaminaToHealthAt = 0;
var vLow = Vitals(250); // 50%
var bLow = BoostVitals(low, hostLow, vLow);
low.Set("_lastWantLoot", true);
Check.False((bool)low.Call("BoostLootHealsToTopOff")!, "under Heal At: corpses first is off, so no Top Off line");
Check.True(bLow.WantsHealNow(), "50% < Heal At 60: the fight's heal");
Check.Eq(Decide(low, combatLow, bLow), BotActivity.Buffing, "the heal has the tick");
var noHeal = new ArbiterInputs(true, false, combatLow.HasEngageableTarget, true, false, false,
combatEngaged: combatLow.IsUnderCloseAttack, boostLoot: true);
Check.True(combatLow.IsUnderCloseAttack, "the rig: a monster 2 m away is on us");
Check.Eq(ActivityArbiter.Decide(in noHeal), BotActivity.Combat, "between heals, a monster on you is fought (not looted past)");
}
// ── The death wait (2026-11-08, Tom: the bot ran off from its kill, then turned round and ran back
// when the corpse came after the death animation) ──
@ -1321,6 +1465,76 @@ internal static class LootCorpseTests
Check.False(FakeHost.Logs.Any(l => l.Contains("abandoning corpse")), "the corpse is not abandoned on the timeout");
}
// 2026-11-22: jump-loot from a corpse about 4 m away. The client closed the corpse 1.5-2 s after
// each jump pickup (outside its use radius at the once-a-second check); the reopen started the
// item's tries over and the next pickup jumped again, so one corpse was opened and closed for
// 1-5 minutes. Now the close turns jump-loot off for the corpse, and each close during one item's
// pickups is one of its tries on that corpse: three, and the item is left.
private static void JumpLootCloseLoopEnds()
{
var oldClock = RynthAiPlugin.CorpseClock;
var oldPace = ActionPacer.NowMs;
long t = 60_000_000;
RynthAiPlugin.CorpseClock = () => t;
ActionPacer.NowMs = () => t;
ActionPacer.ForgetLootJump();
try
{
BaseWorld(corpsePositioned: true);
FakeHost.CloseContainerCalls = true;
FakeHost.TapJumpCalls = true;
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootJumpEnabled = true;
bot.S.LootCorpseTimeoutMs = 120_000;
bot.Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
bot.Cache.OnCreateObject(Corpse);
bot.Cache.OnCreateObject(Gem);
for (int i = 0; i < 50; i++) bot.Cache.Tick();
void TickUntil(Func<bool> done, long maxMs)
{
long end = t + maxMs;
while (t < end && !done()) { t += 20; bot.Tick(BotActivity.Looting); }
}
int Opens() => FakeHost.Uses.Count(u => u == Corpse);
int Moves() => FakeHost.ExternalMoves.Count(m => m.Id == Gem);
int closes = 0;
for (int round = 0; round < 8 && !Completed(bot); round++)
{
int opens = Opens();
TickUntil(() => Opens() > opens || Completed(bot), 10_000);
if (Opens() == opens) break;
FakeHost.GroundContainer = Corpse;
bot.P.OnViewObjectContents(Corpse);
int moves = Moves();
TickUntil(() => Moves() > moves || Completed(bot), 5_000);
if (Moves() == moves) break;
// The hop: about 1.5 s later the client closes the corpse, the gem still on it.
TickUntil(() => false, 1_500);
FakeHost.GroundContainer = 0;
bot.P.OnStopViewingObjectContents(Corpse);
closes++;
}
TickUntil(() => false, 10_000);
Check.Eq(FakeHost.TapJumps, 1, "only the first pickup jumps; after the corpse closed on it the pickups bend down");
Check.True(FakeHost.Logs.Any(l => l.Contains("jump-loot is off for this corpse")), "the switch is logged");
Check.Eq(Moves(), RynthAiPlugin.MaxClosesPerLootItem, $"the gem gets {RynthAiPlugin.MaxClosesPerLootItem} pickups across the reopens, not a fresh 3 tries on every open");
Check.Eq(closes, RynthAiPlugin.MaxClosesPerLootItem, "and the corpse closed on each of them");
Check.True(FakeHost.Logs.Any(l => l.Contains($"closed during its pickup {RynthAiPlugin.MaxClosesPerLootItem} times")), "leaving the gem is logged");
Check.True(Opens() <= RynthAiPlugin.MaxClosesPerLootItem + 1, $"no reopen loop: {Opens()} opens");
Check.True(Completed(bot), "the corpse is finished once the gem is left");
}
finally
{
RynthAiPlugin.CorpseClock = oldClock;
ActionPacer.NowMs = oldPace;
ActionPacer.ForgetLootJump();
}
}
private static void TickFor(Bot bot, int ms)
{
long end = Environment.TickCount64 + ms;

View file

@ -0,0 +1,381 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// 2026-11-26: Show Line of Sight (ShowLosLine, off by default; /ra losline [on|off]; Settings > Combat >
// Line Of Sight). A line in the world from the character to the combat target in the colour of the
// verdict the target scan's raycast gave it (no second raycast): green clear, red blocked with a
// yellow marker where it hit, dashed green when clear without a geometry test. Why: a melee character
// at 0xB470 swung at monsters 4.3-4.7 m off behind a wall that the scan's raycast called clear.
internal static class LosLineTests
{
private const uint Player = 0x50000E51;
private const uint Lb = 0xB4700000;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("los line: the setting is off by default, saved, copied, sent and set like the others", Setting);
r.Add("los line: /ra losline [on|off] always answers with the state or the usage", Command);
r.Add("los line: the scan keeps each monster's verdict while the setting is on, none while off", ScanCache);
r.Add("los line: the raycast's straight line and arc give the nearest point they hit", HitPoints);
r.Add("los line: the overlay draws the scan's verdict: green clear, red blocked with a marker, dashed untested", Overlay);
r.Add("los line: stale verdicts, the setting off or portal space draw nothing", OverlayQuiet);
}
// ── The setting ─────────────────────────────────────────────────────────
private static void Setting()
{
Check.False(new LegacyUiSettings().ShowLosLine, "off by default");
var old = System.Text.Json.JsonSerializer.Deserialize("{\"MonsterRange\":7}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(old != null && !old.ShowLosLine, "a profile saved before the setting loads it off");
var saved = System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { ShowLosLine = true }, RynthAiJsonContext.Default.LegacyUiSettings);
var back = System.Text.Json.JsonSerializer.Deserialize(saved, RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(saved.Contains("ShowLosLine") && back != null && back.ShowLosLine, "saved and loaded with the profile");
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { new LegacyUiSettings { ShowLosLine = true }, dst });
Check.True(dst.ShowLosLine, "a profile's on is copied");
var dst2 = new LegacyUiSettings { ShowLosLine = true };
copy.Invoke(null, new object[] { new LegacyUiSettings(), dst2 });
Check.False(dst2.ShowLosLine, "a profile's off is copied");
var s = new LegacyUiSettings { ShowLosLine = true };
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = System.Text.Json.JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(sent != null && sent.ShowLosLine == true, "sent to the engine's Settings window");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.True(s.ShowLosLine, "an engine without the row leaves it alone");
dash.ApplySettingsJson("{\"ShowLosLine\":false}");
Check.False(s.ShowLosLine, "the row's untick sets it off");
dash.ApplySettingsJson("{\"ShowLosLine\":true}");
Check.True(s.ShowLosLine, "the row's tick sets it on");
var live = new LegacyUiSettings();
var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic();
Check.True(map.TryGetValue("ShowLosLine", out var entry), "ShowLosLine is in the settings map");
Check.Eq(entry.Get(), "0", "reads off");
entry.Set("1");
Check.True(live.ShowLosLine, "and sets on");
}
// ── /ra losline ─────────────────────────────────────────────────────────
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new();
public Bot()
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(P, dash);
}
public void Ra(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(P, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
}
public string LastChat => FakeHost.Chat.Count > 0 ? FakeHost.Chat[^1] : "";
}
private static void Command()
{
FakeHost.Reset();
FakeHost.Create(Player);
var bot = new Bot();
bot.Ra("/ra losline");
Check.True(bot.S.ShowLosLine, "no argument toggles: on");
Check.True(bot.LastChat.Contains("Show Line of Sight: on"), bot.LastChat);
int before = FakeHost.Chat.Count;
bot.Ra("/ra losline");
Check.False(bot.S.ShowLosLine, "again: off");
Check.True(FakeHost.Chat.Count > before && bot.LastChat.Contains("Show Line of Sight: off"), bot.LastChat);
bot.Ra("/ra losline on");
Check.True(bot.S.ShowLosLine, "on");
Check.True(bot.LastChat.Contains("Show Line of Sight: on") && bot.LastChat.Contains("green"), "on says what the colours mean: " + bot.LastChat);
bot.Ra("/ra losline on");
Check.True(bot.S.ShowLosLine && bot.LastChat.Contains("Show Line of Sight: on"), "on again answers too: " + bot.LastChat);
bot.Ra("/ra losline off");
Check.False(bot.S.ShowLosLine, "off");
Check.True(bot.LastChat.Contains("Show Line of Sight: off"), bot.LastChat);
bot.Ra("/ra losline banana");
Check.False(bot.S.ShowLosLine, "an unknown argument changes nothing");
Check.True(bot.LastChat.Contains("Usage: /ra losline [on|off]") && bot.LastChat.Contains("now off"), "the usage and the state: " + bot.LastChat);
bot.S.EnableRaycasting = false;
bot.Ra("/ra losline on");
Check.True(bot.LastChat.Contains("Enable Raycasting is off"), "with raycasting off it says every line is dashed: " + bot.LastChat);
FakeHost.Chat.Clear();
typeof(RynthAiPlugin).GetMethod("HandleHelpCommand", Any)!.Invoke(bot.P, null);
Check.True(FakeHost.Chat.Any(c => c.Contains("/ra losline [on|off]")), "a help line");
}
// ── The scan's verdict cache ─────────────────────────────────────────────
private sealed class Rig
{
public readonly LegacyUiSettings S = new() { MonsterRange = 20, ShowLosLine = true };
public CombatManager C = null!;
public RynthCoreHost Host;
private readonly List<uint> _ids = new();
private uint _next = 0x80000701;
public Rig(bool nav3D = true, float playerX = 100f)
{
FakeHost.Reset();
FakeHost.Nav3DCalls = nav3D;
Place(Player, "Tester", Lb | 0x29, playerX, 100, 50, creature: false);
FakeHost.PlayerPose = (Lb | 0x29, playerX, 100f, 50f);
}
private static void Place(uint id, string name, uint cell, float x, float y, float z, bool creature = true)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (cell, x, y, z);
if (creature) FakeHost.ItemTypes[id] = 0x10;
}
public uint Mob(string name, float north, float east, float up = 0, uint cell = Lb | 0x29)
{
uint id = _next++;
Place(id, name, cell, 100 + east, 100 + north, 50 + up);
_ids.Add(id);
return id;
}
public uint MobAt(string name, uint cell, float x, float y, float z)
{
uint id = _next++;
Place(id, name, cell, x, y, z);
_ids.Add(id);
return id;
}
public void Scan(Func<int, bool>? blocked, int target = 0)
{
Host = FakeHost.Create();
var cache = FakeHost.MakeCache(Host, Player, _ids, _ids.ToDictionary(i => i, _ => 1f));
C = new CombatManager(Host, S, cache);
C.SetPlayerId(Player);
if (blocked != null) C.LosBlockedOverride = blocked;
if (target != 0) C.activeTargetId = target;
C.ScanNearbyTargets();
}
}
private static void ScanCache()
{
var rig = new Rig();
uint a = rig.Mob("Clear Drudge", 4.5f, 0);
uint b = rig.Mob("Walled Drudge", 4.3f, 1);
rig.Scan(id => id == unchecked((int)b), target: unchecked((int)a));
var c = rig.C;
Check.True(c.TryGetLosVerdict(unchecked((int)a), out var va), "the clear one has a verdict");
Check.False(va.Blocked, "clear");
Check.True(va.Tested, "tested (the scan gave a verdict)");
Check.Near(va.Distance, 4.5, 1e-3, "its distance");
Check.True(c.TryGetLosVerdict(unchecked((int)b), out var vb) && vb.Blocked, "the walled one: blocked");
Check.False(c.ScannedTargets.Any(t => t.Id == unchecked((int)b)), "and left out of the targets, as before");
Check.True(c.ScannedTargets.Any(t => t.Id == unchecked((int)a)), "the clear one is a target, as before");
Check.Eq(c.LosLineTargetId, unchecked((int)a), "the line goes to the combat target");
// Off: nothing kept (the scan pays nothing for the overlay).
var off = new Rig();
off.S.ShowLosLine = false;
uint a2 = off.Mob("Clear Drudge", 4.5f, 0);
off.Scan(_ => false, target: unchecked((int)a2));
Check.Eq(off.C.LosVerdicts.Count, 0, "setting off: no verdicts");
Check.Eq(off.C.ScannedTargets.Count, 1, "the scan itself unchanged");
// Each scan holds only its own verdicts: one that died since is gone.
rig.S.MonsterRange = 20;
FakeHost.Positions.Remove(b);
FakeHost.Names.Remove(b);
typeof(CombatManager).GetField("_lastScanTime", Any)!.SetValue(c, DateTime.MinValue);
c.ScanNearbyTargets();
Check.False(c.TryGetLosVerdict(unchecked((int)b), out _), "the next scan's cache doesn't keep a monster it didn't test");
// Melee within 4 m fights through a blocked line: the verdict stays blocked, marked as fought anyway.
var melee = new Rig();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = 2; // melee
uint m = melee.Mob("Close Drudge", 3f, 0);
melee.Scan(_ => true, target: unchecked((int)m));
Check.True(melee.C.TryGetLosVerdict(unchecked((int)m), out var vm) && vm.Blocked && vm.MeleeThrough,
"blocked, and melee fights it anyway (" + (vm.Blocked ? "blocked" : "clear") + (vm.MeleeThrough ? ", through" : "") + ")");
Check.True(melee.C.ScannedTargets.Any(t => t.Id == unchecked((int)m)), "still a target, as before");
// No raycast (not loaded, or Enable Raycasting off): clear without a test.
var none = new Rig();
uint n = none.Mob("Untested Drudge", 6f, 0);
none.Scan(null, target: unchecked((int)n));
Check.True(none.C.TryGetLosVerdict(unchecked((int)n), out var vn) && !vn.Blocked && !vn.Tested, "no raycast: clear, untested");
}
// ── Hit points from the raycast ──────────────────────────────────────────
private static BoundingVolume Box(float x0, float y0, float z0, float x1, float y1, float z1)
=> new() { Type = BoundingVolume.VolumeType.AxisAlignedBox, Min = new Vector3(x0, y0, z0), Max = new Vector3(x1, y1, z1),
Center = new Vector3((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2), Dimensions = new Vector3(x1 - x0, y1 - y0, z1 - z0) };
private static void HitPoints()
{
// Two walls across the line, the far one listed first: the nearer is reported.
var walls = new List<BoundingVolume> { Box(7f, -5f, 0f, 7.2f, 5f, 4f), Box(4f, -5f, 0f, 4.2f, 5f, 4f) };
var from = new Vector3(0f, 0f, 1f);
var to = new Vector3(10f, 0f, 1f);
Check.True(RaycastEngine.IsLinearPathBlocked(from, to, walls, false), "blocked (the verdict alone)");
Check.True(RaycastEngine.IsLinearPathBlocked(from, to, walls, false, out Vector3 hit), "blocked (with the point)");
Check.Near(hit.X, 4f, 1e-3, "the nearer wall's face");
Check.Near(hit.Y, 0f, 1e-3, "on the line");
Check.Near(hit.Z, 1f, 1e-3, "at chest height");
Check.True(RaycastEngine.IsLinearPathBlocked(from, to, walls, true, out Vector3 multi), "multi-ray: blocked");
Check.Near(multi.X, 4f, 1e-3, "multi-ray: the centre ray's hit");
var open = new List<BoundingVolume> { Box(4f, 3f, 0f, 4.2f, 5f, 4f) };
Check.False(RaycastEngine.IsLinearPathBlocked(from, to, open, false, out Vector3 none), "a wall beside the line: clear");
Check.True(none == Vector3.Zero, "and no point");
// An arc into a ceiling reports where it hits.
var ceiling = new List<BoundingVolume> { Box(-1f, -5f, 2.0f, 30f, 5f, 2.2f) };
var aim = new Vector3(25f, 0f, 1f);
bool arcBlocked = RaycastEngine.IsBallisticArcBlocked(from, aim, 18f, 0.5f, ceiling, out var arc);
Check.True(arcBlocked && arc.Blocked && !arc.OutOfReach, "the arc rises into the ceiling");
Check.Near(arc.HitPoint.Z, 2.0f, 0.05, "the hit is on the ceiling's underside");
Check.True(arc.HitPoint.X > 0.5f && arc.HitPoint.X < 25f, "between the two (x " + arc.HitPoint.X.ToString("0.00") + ")");
Check.Near(arc.HitAlong, arc.HitPoint.X, 1e-3, "the same place HitAlong names");
}
// ── The overlay ──────────────────────────────────────────────────────────
private static (float X, float Y, float Z) Chest(float x, float y, float z) => (x, z + 1f, y);
private static void Overlay()
{
var rig = new Rig();
uint a = rig.Mob("Target", 4.5f, 0);
uint b = rig.Mob("Other Blocked", 0, 6f);
uint c = rig.Mob("Other Clear", -8f, 0);
rig.Scan(id => id == unchecked((int)b), target: unchecked((int)a));
var ov = new LosLineOverlay(rig.Host, () => rig.S, () => rig.C);
ov.Submit();
var main = FakeHost.Nav3DLines.Where(l => l.Color == LosLineOverlay.ColorClear).ToList();
Check.Eq(main.Count, 1, "one solid green line to the target (the scan tested it clear)");
var me = Chest(100, 100, 50);
var tgt = Chest(100, 104.5f, 50);
Check.True(main.Count == 1 && Math.Abs(main[0].X1 - me.X) < 1e-3 && Math.Abs(main[0].Y1 - me.Y) < 1e-3 && Math.Abs(main[0].Z1 - me.Z) < 1e-3,
"from the character's chest (x east, y height, z north)");
Check.True(main.Count == 1 && Math.Abs(main[0].X2 - tgt.X) < 1e-3 && Math.Abs(main[0].Y2 - tgt.Y) < 1e-3 && Math.Abs(main[0].Z2 - tgt.Z) < 1e-3,
"to the target's chest");
Check.True(main.Count == 1 && main[0].Thick == LosLineOverlay.MainThick, "the main line's width");
Check.Eq(FakeHost.Nav3DLines.Count(l => l.Color == LosLineOverlay.ColorOtherBlocked), 1, "a thin dim red line to the blocked monster");
Check.Eq(FakeHost.Nav3DLines.Count(l => l.Color == LosLineOverlay.ColorOtherClear), 1, "a thin dim green line to the other clear one");
Check.Eq(FakeHost.Nav3DLines.Count, 3, "nothing else");
Check.Eq(FakeHost.Nav3DRings.Count, 0, "no marker when clear");
Check.Eq(ov.LastLines, 3, "three lines counted");
// The target blocked, with a hit point (global metres): red, and the yellow marker there.
FakeHost.Nav3DLines.Clear(); FakeHost.Nav3DRings.Clear(); FakeHost.Nav3DTriangles.Clear();
float gx = 0xB4 * 192f, gy = 0x70 * 192f;
rig.C.SetLosVerdictForTests(unchecked((int)a), new CombatManager.LosVerdict
{
Blocked = true, Tested = true, HasHit = true, HitX = gx + 100f, HitY = gy + 102f, HitZ = 51f, Distance = 4.5, At = RynthClock.Now,
});
ov.Submit();
Check.Eq(FakeHost.Nav3DLines.Count(l => l.Color == LosLineOverlay.ColorBlocked), 1, "one solid red line");
Check.Eq(FakeHost.Nav3DLines.Count(l => l.Color == LosLineOverlay.ColorClear), 0, "no green one");
Check.Eq(FakeHost.Nav3DRings.Count, 1, "a marker ring");
var ring = FakeHost.Nav3DRings.FirstOrDefault();
Check.True(Math.Abs(ring.X - 100f) < 1e-3 && Math.Abs(ring.Z - 102f) < 1e-3 && ring.Color == LosLineOverlay.ColorHit,
$"at the hit point in the player's frame (ring {ring.X:0.00},{ring.Y:0.00},{ring.Z:0.00})");
Check.True(ring.Y < 51f && ring.Y > 50f, "the ring's post spans the hit's height");
Check.Eq(FakeHost.Nav3DTriangles.Count, 8, "and a small yellow diamond (8 faces)");
Check.True(FakeHost.Nav3DTriangles.All(t => t.Color == LosLineOverlay.ColorHit), "yellow");
// Blocked but no hit point (an arc out of reach): red, no marker.
FakeHost.Nav3DLines.Clear(); FakeHost.Nav3DRings.Clear(); FakeHost.Nav3DTriangles.Clear();
rig.C.SetLosVerdictForTests(unchecked((int)a), new CombatManager.LosVerdict { Blocked = true, Tested = true, Distance = 4.5, At = RynthClock.Now });
ov.Submit();
Check.Eq(FakeHost.Nav3DLines.Count(l => l.Color == LosLineOverlay.ColorBlocked), 1, "red");
Check.Eq(FakeHost.Nav3DRings.Count + FakeHost.Nav3DTriangles.Count, 0, "no marker without a point");
// Clear without a geometry test: dashed green.
FakeHost.Nav3DLines.Clear();
rig.C.SetLosVerdictForTests(unchecked((int)a), new CombatManager.LosVerdict { Blocked = false, Tested = false, Distance = 4.5, At = RynthClock.Now });
ov.Submit();
var dashes = FakeHost.Nav3DLines.Where(l => l.Color == LosLineOverlay.ColorClear).ToList();
Check.True(dashes.Count >= 2, "dashed: several short green pieces (" + dashes.Count + ")");
float covered = dashes.Sum(d => MathF.Sqrt((d.X2 - d.X1) * (d.X2 - d.X1) + (d.Y2 - d.Y1) * (d.Y2 - d.Y1) + (d.Z2 - d.Z1) * (d.Z2 - d.Z1)));
Check.True(covered < 4.5f * 0.7f && covered > 4.5f * 0.4f, "with gaps between them (" + covered.ToString("0.00") + " of 4.5 m drawn)");
// A target in the next landblock east: drawn in this landblock's frame.
var edge = new Rig(playerX: 190f);
uint e = edge.MobAt("Next Block", ((Lb + 0x01000000) & 0xFFFF0000) | 0x01, 2f, 100f, 50f);
edge.Scan(_ => false, target: unchecked((int)e));
var ov2 = new LosLineOverlay(edge.Host, () => edge.S, () => edge.C);
ov2.Submit();
var l2 = FakeHost.Nav3DLines.FirstOrDefault(l => l.Color == LosLineOverlay.ColorClear);
Check.Near(l2.X1, 190f, 1e-3, "from the character, 190 m east in this landblock");
Check.Near(l2.X2, 194f, 1e-3, "to 192 m + 2 m east of this landblock's origin");
Check.Near(l2.Z2, 100f, 1e-3, "same north");
}
private static void OverlayQuiet()
{
var rig = new Rig();
uint a = rig.Mob("Target", 4.5f, 0);
rig.Scan(_ => false, target: unchecked((int)a));
var ov = new LosLineOverlay(rig.Host, () => rig.S, () => rig.C);
ov.Clock = () => RynthClock.Now.AddSeconds(5);
ov.Submit();
Check.Eq(FakeHost.Nav3DLines.Count, 0, "verdicts from a scan 5 s ago aren't drawn (no scan lately)");
ov.Clock = () => RynthClock.Now;
rig.S.ShowLosLine = false;
ov.Submit();
Check.Eq(FakeHost.Nav3DLines.Count, 0, "setting off: nothing");
rig.S.ShowLosLine = true;
FakeHost.PlayerPose = (0x00000000, 0f, 0f, 0f);
ov.Submit();
Check.Eq(FakeHost.Nav3DLines.Count, 0, "portal space: nothing");
FakeHost.PlayerPose = (Lb | 0x29, 100f, 100f, 50f);
ov.Submit();
Check.Eq(FakeHost.Nav3DLines.Count, 1, "back in the world: the line");
// No Nav3D in the engine: nothing, and no error.
var plain = new Rig(nav3D: false);
uint p = plain.Mob("Target", 4.5f, 0);
plain.Scan(_ => false, target: unchecked((int)p));
new LosLineOverlay(plain.Host, () => plain.S, () => plain.C).Submit();
Check.Eq(FakeHost.Nav3DLines.Count, 0, "an engine without Nav3D: nothing drawn");
}
}

View file

@ -82,6 +82,9 @@ internal static class NavEngineTests
r.Add("nav engine: a chat point that loads another route hands over to it", ChatLoadsRoute); // was a known failure; fixed by a8e5de0
r.Add("nav engine: a recall that never fires, next waypoint far: stops instead of walking off", RecallTimeoutFar); // was a known failure; fixed by 5cfbcea
r.Add("nav engine: a portal/NPC use the engine did not send is not logged as sent and is asked again", PortalNpcUseNotSent);
r.Add("nav engine: an NPC point (VTank type 7) uses its NPC on arrival, once, waits for the answer, then goes on", NpcPointUsesTheNpc);
r.Add("nav engine: an NPC point waits while the client is busy with the use, 20 s at most", NpcPointWaitsWhileBusy);
r.Add("nav engine: an NPC point whose NPC can't be found says so once and goes on after 15 s", NpcPointNotFound);
}
// ── Rig ───────────────────────────────────────────────────────────────────
@ -407,15 +410,95 @@ internal static class NavEngineTests
var point = new NavPoint { Type = T.PortalNPC, TargetName = "Gateway" };
FakeHost.UseObjectAccepts = false;
Check.False((bool)fire.Invoke(nav.E, new object[] { point })!, "the engine did not send the use: not fired, the caller asks again");
Check.False((bool)fire.Invoke(nav.E, new object[] { point, "portal" })!, "the engine did not send the use: not fired, the caller asks again");
Check.Eq(LogCount("UseObject portal 'Gateway' (dist="), 0, "and no 'used' line is logged");
Check.Eq(LogCount("was not sent - will retry"), 1, "the refusal is logged");
FakeHost.UseObjectAccepts = true;
Check.True((bool)fire.Invoke(nav.E, new object[] { point })!, "once the engine sends it the portal counts as fired");
Check.True((bool)fire.Invoke(nav.E, new object[] { point, "portal" })!, "once the engine sends it the portal counts as fired");
Check.Eq(LogCount("UseObject portal 'Gateway' (dist="), 1, "and the 'used' line is logged");
}
// ── NPC points (VTank type 7, #rynth-meta-and-expression-issues 11-23: "NPC 'talk' nav nodes do nothing") ──
private const uint NpcId = 0x7A000002, NpcMe = 0x50000F01;
private static Nav NpcRoute(bool npcThere, bool busyCalls = false)
{
FakeHost.Reset(); At(0, 0);
FakeHost.WeaponCalls = true; // UseObject
FakeHost.BusyCalls = busyCalls;
var pose = FakeHost.PlayerPose;
FakeHost.Names[NpcMe] = "Tester";
FakeHost.Positions[NpcMe] = pose;
if (npcThere)
{
FakeHost.Names[NpcId] = "Royal Guard";
FakeHost.Positions[NpcId] = (pose.Cell, pose.X + 2f, pose.Y, pose.Z);
}
var host = FakeHost.Create(NpcMe);
var cache = FakeHost.MakeCache(host, NpcMe, npcThere ? new[] { NpcId } : Array.Empty<uint>());
var npc = Pt(0, 0, T.Npc); npc.TargetName = "Royal Guard";
var nav = new Nav(Route(RT.Once, npc, Pt(20, 0), Pt(40, 0)));
nav.E.SetWorldObjectCache(cache);
nav.E.SetPlayerId(NpcMe);
return nav;
}
private static void NpcPointUsesTheNpc()
{
var nav = NpcRoute(npcThere: true);
nav.Tick();
Check.Eq(nav.Idx, 0, "arrived at the NPC point: it doesn't go on yet (it used to advance at once)");
Check.False(FakeHost.AutoRun, "it stops there");
nav.Run(1.0);
Check.Eq(FakeHost.Uses.Count(u => u == NpcId), 1, $"the NPC is used, once (uses: {string.Join(",", FakeHost.Uses.Select(u => u.ToString("X8")))})");
Check.Eq(LogCount("UseObject NPC 'Royal Guard'"), 1, "logged as an NPC use");
nav.Run(2.0);
Check.Eq(nav.Idx, 0, "under 3 s after the use: still waiting for the NPC's answer");
nav.Run(1.5);
Check.Eq(nav.Idx, 1, "then on to [1]");
Check.Eq(FakeHost.Uses.Count(u => u == NpcId), 1, "never used twice");
At(19.5, 0); nav.Tick();
Check.Eq(nav.Idx, 2, "the next plain waypoint is walked as before");
}
private static void NpcPointWaitsWhileBusy()
{
var nav = NpcRoute(npcThere: true, busyCalls: true);
nav.Tick();
nav.Run(1.0);
Check.Eq(FakeHost.Uses.Count(u => u == NpcId), 1, "used");
FakeHost.BusyStateValue = 1; // the walk over and the use still running
nav.Run(8.0);
Check.Eq(nav.Idx, 0, "busy 8 s after the use: still waiting");
FakeHost.BusyStateValue = 0;
nav.Run(0.3);
Check.Eq(nav.Idx, 1, "the use done: on to [1]");
var stuck = NpcRoute(npcThere: true, busyCalls: true);
stuck.Tick();
stuck.Run(1.0);
FakeHost.BusyStateValue = 1;
stuck.Run(18.0);
Check.Eq(stuck.Idx, 0, "busy 18 s: still waiting");
stuck.Run(2.5);
Check.Eq(stuck.Idx, 1, "busy past 20 s: goes on anyway");
}
private static void NpcPointNotFound()
{
var nav = NpcRoute(npcThere: false);
nav.Tick();
nav.Run(14.0);
Check.Eq(nav.Idx, 0, "14 s looking for the NPC: still there");
Check.Eq(FakeHost.Uses.Count, 0, "nothing used");
nav.Run(1.5);
Check.Eq(nav.Idx, 1, "15 s: goes on without it");
Check.Eq(FakeHost.Chat.Count(l => l.Contains("NPC 'Royal Guard'") && l.Contains("wasn't found")), 1, "one chat line says so");
Check.True(nav.S.EnableNavigation, "nav stays on");
}
private static void RecallTimeoutNear()
{
var nav = RecallRoute(30);

View file

@ -32,6 +32,7 @@ internal static class RebuffWhenIdleTests
r.Add("rebuff when idle: idle, a buff inside Rebuff With + the margin is rebuffed early", IdleInsideMarginRebuffed);
r.Add("rebuff when idle: in a fight, a buff inside the margin but over Rebuff With is not rebuffed", FightInsideMarginWaits);
r.Add("rebuff when idle: in a fight, a buff at or under Rebuff With (or dispelled) waits for the fight's end, then is rebuffed (2026-11-20)", FightRegularRebuff);
r.Add("rebuff: a fight that never ends (constant respawn): after 2 min of waiting a full pass goes in it, never under Heal At (R-20261125-130039-e3bc)", FightThatNeverEnds);
r.Add("rebuff when idle: a rebuff run under way when a monster comes: the cast sent resolves, the rest waits for the fight's end", RunPausesForFight);
r.Add("rabuffsdue[seconds]: how many buffs a rebuff with that line would cast (a dispelled one too); -1 with buffing off or no buff manager; asking casts nothing", BuffsDueCount);
r.Add("rebuff when idle: margin 0, or the option off, adds nothing", MarginZeroAddsNothing);
@ -136,6 +137,7 @@ internal static class RebuffWhenIdleTests
}
public bool Running => B.GetStateSnapshot().IsForceRebuffing;
public DateTime Now => _now;
public int Logged(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
}
@ -223,6 +225,38 @@ internal static class RebuffWhenIdleTests
Check.Eq(up.Logged("[Buff] buffs wait"), 0, "no wait logged with nothing due");
}
// Conquest, constant respawn, Monster Range 10: buffs waited almost 7 hours, ran out, and the character died.
private static void FightThatNeverEnds()
{
var rig = new Rig(rebuffWhenIdle: false) { Idle = false };
RynthClock.TestNow = () => rig.Now;
try
{
rig.Live((Strength, 2900), (Willpower, 3000));
rig.Beats(2);
rig.Live((Strength, 290), (Willpower, 3000));
Check.Eq(Show(rig.Beats(110)), "(none)", "110 s of an unbroken fight: Strength (290 s left) still waits");
Check.Eq(rig.Logged("[Buff] buffs wait: a fight"), 1, "the wait is logged once");
Check.Eq(rig.Arbiter(), BotActivity.Combat, "combat keeps the tick meanwhile");
Check.Eq(Show(rig.Beats(20)), Strength, "past 2 min: the pass goes in the fight and Strength is rebuffed");
Check.Eq(rig.Logged("for a fight that doesn't end"), 1, "the pass is logged");
Check.Eq(Show(rig.Beats(10)), "(none)", "nothing more to cast");
Check.Eq(rig.Logged("the rebuff pass in the fight is done (nothing left to cast)"), 1, "its end is logged");
// Under Heal At the pass never starts.
var hurt = new Rig(rebuffWhenIdle: false) { Idle = false };
RynthClock.TestNow = () => hurt.Now;
hurt.S.HealAt = 50;
hurt.Live((Strength, 2900), (Willpower, 3000));
hurt.Beats(2);
hurt.Live((Strength, 290), (Willpower, 3000));
var v = (PlayerVitalsCache)typeof(BuffManager).GetField("_vitals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(hurt.B)!;
v.CurrentHealth = 30;
Check.Eq(Show(hurt.Beats(150)), "(none)", "health 30% under Heal At 50%: no buff cast however long the fight");
}
finally { RynthClock.TestNow = null; }
}
// A script asks before a Thread (2026-11-20): Lua sees only the character's enchantments, not the item spells.
private static void BuffsDueCount()
{

View file

@ -0,0 +1,117 @@
using System.Linq;
using System.Reflection;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// No recharge for now (2026-11-24, R-20261124-121710-7876: Threads on DreamWeave, "you generally don't
// want your character to pull out a wand to recharge vitals while fighting", and a one-click way
// to put the settings back). LegacyUi/RechargeHold.cs, RynthAiPlugin.RechargeHold.cs.
internal static class RechargeHoldTests
{
public static void Register(Runner r)
{
r.Add("no recharge: a hold sets the vital's lines to 0 and releasing puts the real values back (Emergency Heal At stays)", HoldAndRelease);
r.Add("no recharge: a save writes the real values, never the held 0s", SaveWritesRealValues);
r.Add("no recharge: a line the player set while held keeps their value on release", PlayerValueWins);
r.Add("no recharge: a profile loaded while held stays held, over the new profile's lines", ProfileLoadKeepsHold);
r.Add("no recharge: /ra norecharge holds all, again releases; hp|stam|mana [on|off] one vital", Command);
}
private static LegacyUiSettings Settings() => new()
{
HealAt = 60, TopOffHP = 90, StaminaToHealthAt = 30, EmergencyHealAt = 25,
RestamAt = 30, RestamTo = 70, TopOffStam = 85, GetManaAt = 40, TopOffMana = 80,
};
private static void HoldAndRelease()
{
var s = Settings();
var h = s.RechargeHold;
h.Set(s, RechargeVital.All, true);
Check.Eq(h.Held, RechargeVital.All, "all held");
Check.Eq($"{s.HealAt}/{s.TopOffHP}/{s.StaminaToHealthAt}/{s.RestamAt}/{s.RestamTo}/{s.TopOffStam}/{s.GetManaAt}/{s.TopOffMana}", "0/0/0/0/0/0/0/0",
"every recharge line at 0 (the settings' own off)");
Check.Eq(s.EmergencyHealAt, 25, "Emergency Heal At is the safety floor: not held");
Check.Eq(h.RealValue("Heal At"), 60, "the real Heal At kept");
h.Set(s, RechargeVital.Stamina, false);
Check.Eq($"{s.RestamAt}/{s.RestamTo}/{s.TopOffStam}", "30/70/85", "stamina released: its lines back");
Check.Eq(s.HealAt, 0, "health still held");
Check.Eq(h.Held, RechargeVital.Health | RechargeVital.Mana, "health and mana held");
h.Set(s, RechargeVital.All, false);
Check.Eq($"{s.HealAt}/{s.TopOffHP}/{s.StaminaToHealthAt}/{s.GetManaAt}/{s.TopOffMana}", "60/90/30/40/80", "all released: as they were");
Check.Eq(h.Held, RechargeVital.None, "nothing held");
Check.Eq(RechargeHold.Describe(RechargeVital.All), "health, stamina and mana", "described");
}
private static void SaveWritesRealValues()
{
var s = Settings();
s.RechargeHold.Set(s, RechargeVital.All, true);
string json = s.RechargeHold.WithRealValues(s, () => JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings));
var saved = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.Eq($"{saved.HealAt}/{saved.RestamAt}/{saved.GetManaAt}/{saved.TopOffMana}", "60/30/40/80", "the saved profile has the real values");
Check.Eq($"{s.HealAt}/{s.RestamAt}/{s.GetManaAt}", "0/0/0", "and the live settings are held again after the save");
Check.False(json.Contains("RechargeHold"), "the hold itself is never saved");
}
private static void PlayerValueWins()
{
var s = Settings();
s.RechargeHold.Set(s, RechargeVital.Health, true);
s.HealAt = 45; // set in Settings while held
string json = s.RechargeHold.WithRealValues(s, () => JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings));
Check.Eq(JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!.HealAt, 45, "a save writes the player's new value");
s.RechargeHold.Set(s, RechargeVital.Health, false);
Check.Eq(s.HealAt, 45, "release keeps it (theirs wins)");
Check.Eq(s.TopOffHP, 90, "the untouched line comes back");
}
private static void ProfileLoadKeepsHold()
{
var live = Settings();
live.RechargeHold.Set(live, RechargeVital.Mana, true);
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var other = Settings(); other.GetManaAt = 55; other.TopOffMana = 95;
copy.Invoke(null, new object[] { other, live });
Check.Eq($"{live.GetManaAt}/{live.TopOffMana}", "0/0", "the loaded profile's mana lines are held");
Check.Eq(live.RechargeHold.Held, RechargeVital.Mana, "still held");
live.RechargeHold.Set(live, RechargeVital.Mana, false);
Check.Eq($"{live.GetManaAt}/{live.TopOffMana}", "55/95", "released: the loaded profile's values, not the old ones");
}
private static void Run(TickIsolationTests.Bot bot, string line) =>
typeof(RynthAiPlugin).GetMethod("HandleNoRechargeCommand", BindingFlags.Instance | BindingFlags.NonPublic)!
.Invoke(bot.P, new object[] { line.Split(' ') });
private static void Command()
{
var bot = new TickIsolationTests.Bot();
bot.S.HealAt = 60; bot.S.GetManaAt = 40; bot.S.RestamAt = 30;
Run(bot, "/ra norecharge");
Check.Eq(bot.S.RechargeHold.Held, RechargeVital.All, "no argument: all three held");
Check.Eq($"{bot.S.HealAt}/{bot.S.GetManaAt}/{bot.S.RestamAt}", "0/0/0", "their lines at 0");
Check.True(FakeHost.Chat.Any(l => l.Contains("No recharge for now: health, stamina and mana")), "said in chat: " + string.Join(" | ", FakeHost.Chat));
Check.Eq(bot.P.RechargeHeld, RechargeVital.All, "the dashboard reads it");
Run(bot, "/ra norecharge");
Check.Eq(bot.S.RechargeHold.Held, RechargeVital.None, "again: all released");
Check.Eq($"{bot.S.HealAt}/{bot.S.GetManaAt}/{bot.S.RestamAt}", "60/40/30", "as they were");
Check.True(FakeHost.Chat.Any(l => l.Contains("Recharge back on for health, stamina and mana")), "said in chat");
Run(bot, "/ra norecharge mana on");
Check.Eq(bot.S.RechargeHold.Held, RechargeVital.Mana, "one vital");
Run(bot, "/ra norecharge hp");
Check.Eq(bot.S.RechargeHold.Held, RechargeVital.Mana | RechargeVital.Health, "hp toggled on beside it");
Run(bot, "/ra norecharge off");
Check.Eq(bot.S.RechargeHold.Held, RechargeVital.None, "off: all released");
int fails = FakeHost.Chat.Count;
Run(bot, "/ra norecharge legs");
Check.True(FakeHost.Chat.Skip(fails).Any(l => l.Contains("unknown 'legs'")), "a wrong vital says the usage");
}
}

View file

@ -29,6 +29,7 @@ internal static class TickIsolationTests
{
r.Add("tick isolation: a step before healing that throws every tick (quest tracker) doesn't stop the heal", HealDespiteEarlierFault);
r.Add("tick guard: a member missing from a shared RynthCore library says to install the core update (R-20261123-203520-9756)", GuardSaysNeedsNewerCore);
r.Add("loot editor: a call that fails on an older core's loot library says to install the core update, once in 5 min; other failures are logged (R-20261124-085015-5215)", LootEditorSaysNeedsNewerCore);
r.Add("tick isolation: chores that throw every tick (mana stones, AutoCram) don't stop combat's heartbeat", CombatDespiteChoreFault);
r.Add("tick isolation: a chore failing every tick is switched off with one chat line, retried every 60 s, back on when it works", ChoreTripsAndRecovers);
r.Add("tick isolation: healing failing every tick is never switched off; one chat line, and combat still runs", HealingNeverTrips);
@ -268,6 +269,23 @@ internal static class TickIsolationTests
return (g, log, chat, () => now += stepMs);
}
private static void LootEditorSaysNeedsNewerCore()
{
var bot = new Bot();
var missing = new MissingFieldException("Field not found: 'RynthCore.Loot.Editing.LootEditRule.PerDayStatus'.");
bot.P.NoteLootEditorFailure(missing);
bot.P.NoteLootEditorFailure(missing);
int said = FakeHost.Chat.Count(l => l.Contains("The Loot Editor can't load: this RynthAi needs a newer RynthCore core: install the core update in the launcher"));
Check.Eq(said, 1, "said once in chat, not once per call: " + string.Join(" | ", FakeHost.Chat));
Check.True(FakeHost.Logs.Any(l => l.Contains("The Loot Editor can't load") && l.Contains("PerDayStatus")), "and logged with the missing member");
int chatBefore = FakeHost.Chat.Count;
bot.P.NoteLootEditorFailure(new InvalidOperationException("a broken profile"));
Check.Eq(FakeHost.Chat.Count, chatBefore, "another failure says nothing in chat");
Check.True(FakeHost.Logs.Any(l => l.Contains("A Loot Editor call failed: InvalidOperationException: a broken profile")), "but is logged (it used to vanish)");
Check.Null(RynthAiPlugin.LootEditorNeedsCoreLine(new InvalidOperationException("x")), "no core line for an ordinary failure");
}
private static void GuardSaysNeedsNewerCore()
{
var (g, _, chat, advance) = Guard();

View file

@ -0,0 +1,191 @@
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Engine.UI.Sections;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.Huds;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Trade;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The Trade Shop in RynthAi (RynthAiPlugin.TradeShop.cs): its window in the manifest without a bar
// button, its settings in the profile (the on/off never saved), when it pauses, and /ra tradeshop
// (every form replies). The sale flow itself is tested offline in RynthCore.RynthAiTests (TradeShopTests).
internal static class TradeShopPluginTests
{
private const uint Player = 0x50000F51;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("trade shop: the window is in the manifest with no bar button", Manifest);
r.Add("trade shop: settings save with the profile, the on/off never does; a reload keeps it", Settings);
r.Add("trade shop: pauses while the macro runs, while AutoTrade is on, and in combat mode", Pauses);
r.Add("trade shop: /ra tradeshop - every form replies, and the edits land", Commands);
}
private static void Manifest()
{
string json = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, tradeShop: true);
SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error);
Check.Eq(error, string.Empty, "no parse error");
Check.Eq(m.Windows.Length, 1, "the one window");
SectionWindowDecl w = m.Windows.Single();
Check.Eq(w.Id, "tradeshop", "id");
Check.Eq(w.Title, "Trade Shop", "title");
Check.Eq(w.Surface, RynthAiPlugin.TradeShopSurface, "the surface PluginExports.RenderEmbed draws");
Check.False(w.Bar, "no bar button (the bar is full)");
Check.True(w.Width >= w.MinWidth && w.Height >= w.MinHeight, "sizes");
string none = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, dashboard: true);
Check.False(none.Contains("tradeshop"), "off unless asked");
}
private static void Settings()
{
var fresh = new LegacyUiSettings();
Check.True(fresh.TradeShop != null && !fresh.TradeShop.Enabled && fresh.TradeShop.ConfirmEachSale && !fresh.TradeShop.AdvertiseEnabled,
"a new profile: off, confirm each sale on, no advertising");
var s = new LegacyUiSettings();
s.TradeShop.Enabled = true;
s.TradeShop.ConfirmEachSale = false;
s.TradeShop.Mode = TradeShopMode.Mode2Text;
s.TradeShop.Rates.PyrealsPerLegendaryKey = 400_000;
s.TradeShop.Listings.Add(new TradeShopListing { Name = "Hat", PricePyreals = 5000, Wcid = 123, ObjectId = 0x80001234, Stack = 0 });
string text = JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings);
LegacyUiSettings back = JsonSerializer.Deserialize(text, RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.False(back.TradeShop.Enabled, "the on/off is never saved (off at every login)");
Check.False(back.TradeShop.ConfirmEachSale, "confirm each sale saves");
Check.Eq(back.TradeShop.Mode, TradeShopMode.Mode2Text, "mode saves");
Check.Eq(back.TradeShop.Rates.PyrealsPerLegendaryKey, 400_000L, "the key rate saves");
Check.True(back.TradeShop.Listings.Count == 1 && back.TradeShop.Listings[0].Name == "Hat" && back.TradeShop.Listings[0].Wcid == 123,
"the catalog saves");
Check.False(text.Contains("\"Sync\""), "the lock isn't saved");
LegacyUiSettings old = JsonSerializer.Deserialize("{\"EnableAutostack\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!;
Check.True(old.TradeShop != null && old.TradeShop.ConfirmEachSale, "a profile from before the shop: the defaults");
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
dst.TradeShop.Enabled = true;
copy.Invoke(null, new object[] { back, dst });
Check.True(dst.TradeShop.Enabled, "a reload keeps the shop on");
Check.True(dst.TradeShop.Listings.Count == 1, "and copies the catalog");
}
private static (RynthAiPlugin P, LegacyUiSettings S) Plugin()
{
FakeHost.Reset();
FakeHost.Names[Player] = "Tester";
RynthCoreHost host = FakeHost.Create(playerId: Player);
var p = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
var s = new LegacyUiSettings();
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash);
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
typeof(RynthAiPlugin).GetField("_objectCache", Any)!.SetValue(p, cache);
typeof(RynthAiPlugin).GetField("_playerId", Any)!.SetValue(p, Player);
typeof(RynthAiPlugin).GetMethod("CreateTradeShop", Any)!.Invoke(p, null);
return (p, s);
}
private static string Say(RynthAiPlugin p, string line, bool tick = false)
{
FakeHost.Chat.Clear();
typeof(RynthAiPlugin).GetMethod("HandleTradeShopRaCommand", Any)!.Invoke(p, new object[] { line.Split(' ') });
if (tick) Shop(p).Tick();
return string.Join(" | ", FakeHost.Chat);
}
private static TradeShopManager Shop(RynthAiPlugin p) => (TradeShopManager)typeof(RynthAiPlugin).GetField("_tradeShop", Any)!.GetValue(p)!;
private static string Pause(RynthAiPlugin p) => (string)typeof(RynthAiPlugin).GetMethod("TradeShopPauseReason", Any)!.Invoke(p, null)!;
private static void Pauses()
{
var (p, s) = Plugin();
Check.Eq(Pause(p), "", "idle, macro off: free");
s.IsMacroRunning = true;
Check.Eq(Pause(p), "the macro is running", "the macro");
s.IsMacroRunning = false;
s.AutoTradeEnabled = true;
Check.True(Pause(p).StartsWith("AutoTrade is on"), "AutoTrade");
s.AutoTradeEnabled = false;
Check.Eq(Pause(p), "", "free again");
}
private static void Commands()
{
var (p, s) = Plugin();
TradeShopSettings c = s.TradeShop;
string r = Say(p, "/ra tradeshop status");
Check.True(r.Contains("Trade Shop: OFF") && r.Contains("confirm each sale ON"), "status: " + r);
r = Say(p, "/ra tradeshop");
Check.True(r.Contains("Trade Shop:") && r.Contains("window"), "bare: the status and the window: " + r);
r = Say(p, "/ra tradeshop bogus");
Check.True(r.Contains("unknown option") && r.Contains("Usage"), "a wrong option says the usage: " + r);
r = Say(p, "/ra tradeshop on", tick: true);
Check.True(c.Enabled && r.Contains("Trade Shop ON") && r.Contains("Confirm each sale is ON"), "on says what it does: " + r);
r = Say(p, "/ra tradeshop off", tick: true);
Check.True(!c.Enabled && r.Contains("Trade Shop OFF"), "off: " + r);
r = Say(p, "/ra tradeshop confirm");
Check.True(r.Contains("Usage: /ra tradeshop confirm on|off"), "confirm without on/off: " + r);
r = Say(p, "/ra tradeshop confirm off", tick: true);
Check.True(!c.ConfirmEachSale && r.Contains("Warning"), "confirm off warns: " + r);
r = Say(p, "/ra tradeshop confirm on", tick: true);
Check.True(c.ConfirmEachSale && r.Contains("Confirm each sale ON"), "confirm on: " + r);
r = Say(p, "/ra tradeshop mode2");
Check.True(c.Mode == TradeShopMode.Mode2Text && r.Contains("Mode 2"), "mode2: " + r);
r = Say(p, "/ra tradeshop mode1");
Check.True(c.Mode == TradeShopMode.Mode1Stock && r.Contains("Mode 1"), "mode1: " + r);
r = Say(p, "/ra tradeshop add 1,500 Fancy Hat");
Check.True(c.Listings.Count == 1 && c.Listings[0].Name == "Fancy Hat" && c.Listings[0].PricePyreals == 1500 && r.Contains("listed Fancy Hat"),
"add a typed listing: " + r);
r = Say(p, "/ra tradeshop add");
Check.True(r.Contains("Usage: /ra tradeshop add"), "add without a price: " + r);
r = Say(p, "/ra tradeshop price 1 2500");
Check.True(c.Listings[0].PricePyreals == 2500 && r.Contains("now"), "price: " + r);
r = Say(p, "/ra tradeshop price 9 2500");
Check.True(r.Contains("there is no #9"), "price of a missing row: " + r);
r = Say(p, "/ra tradeshop list");
Check.True(r.Contains("#1 Fancy Hat"), "list: " + r);
r = Say(p, "/ra tradeshop keys 300000");
Check.True(c.Rates.PyrealsPerLegendaryKey == 300_000 && r.Contains("1 LK = 300,000 py"), "keys: " + r);
r = Say(p, "/ra tradeshop remove 1");
Check.True(c.Listings.Count == 0 && r.Contains("removed #1 Fancy Hat"), "remove: " + r);
r = Say(p, "/ra tradeshop accept");
Check.True(r.Contains("no sale is waiting"), "accept with nothing waiting: " + r);
r = Say(p, "/ra tradeshop decline", tick: true);
Check.True(r.Contains("no sale to decline"), "decline with nothing: " + r);
r = Say(p, "/ra tradeshop advertise");
Check.True(r.Contains("advertising OFF"), "advertising off by default: " + r);
r = Say(p, "/ra tradeshop advertise every 1");
Check.True(c.AdvertiseIntervalSec == TradeShopSettings.MinAdvertiseSec && r.Contains("every 5 min"), "a 1-minute interval clamps to 5: " + r);
r = Say(p, "/ra tradeshop advertise channel general");
Check.True(c.AdvertiseChannel == TradeShopAdvertiseChannel.General && r.Contains("General"), "channel: " + r);
r = Say(p, "/ra tradeshop advertise channel allegiance");
Check.True(r.Contains("Channels:"), "a channel the shop doesn't use: " + r);
r = Say(p, "/ra tradeshop advertise now", tick: true);
Check.True(r.Contains("turn the shop on first"), "advertise now while off: " + r);
r = Say(p, "/ra tradeshop help");
Check.True(r.Contains("/ra tradeshop") && r.Contains("Usage"), "help: " + r);
}
}

View file

@ -44,7 +44,8 @@ internal static class UseRefusalTests
r.Add("use check (looting): Drakkon's stall - stop once, retry, say it once in chat, stop opening corpses, probe, recover", LootingStall);
r.Add("use check (looting): normal opens never trip it", LootingNormalOpens);
r.Add("loot only rare corpses: only a corpse whose description says it generated a rare is opened; off, both are", RareCorpsesOnly);
r.Add("corpse behind a wall (R-20261121-190950-ee4e): set aside after its first open, no clean stop or abandon; looted once the line is clear", CorpseBehindWallSetAside);
r.Add("corpse behind a wall (R-20261121-190950-ee4e, R-20261124-001522-b582): set aside before any open, no clean stop or abandon; looted once the line is clear", CorpseBehindWallSetAside);
r.Add("corpse behind a wall: still there after 20 s, one open anyway (the ray may be wrong); a failed one sets it aside the old way", CorpseBehindWallTryAnyway);
r.Add("use check (looting): opens with monsters about never trip it (a fight cancels them)", OpensInAFightDontCount);
r.Add("flight recorder: the use check asks the engine for a dump (clean stop, stuck); normal opens never do", FlightDumpRequests);
r.Add("corpse open: a corpse claimed while Combat owns the tick is opened only on the Looting tick", OpenWaitsForLootingTick);
@ -399,8 +400,8 @@ internal static class UseRefusalTests
if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; if (FakeHost.Uses.Last() == CorpseB) bot.P.OnViewObjectContents(CorpseB); }
}
for (int i = 0; i < 80; i++) Step(); // 8 s: the old way had four opens and the clean stop by now
Check.Eq(FakeHost.Uses.Count(u => u == CorpseA), 1, "one open of the corpse behind the wall, then it is set aside");
Check.True(FakeHost.Logs.Any(l => l.Contains("a wall stands between: set aside")), "logged");
Check.Eq(FakeHost.Uses.Count(u => u == CorpseA), 0, "no open of the corpse behind the wall (it used to get one, and a walk into the wall)");
Check.True(FakeHost.Logs.Any(l => l.Contains("has a wall between: set aside before any open")), "logged");
Check.False(FakeHost.Logs.Any(l => l.Contains("one clean stop")), "no clean stop or jump at the wall");
Check.False(FakeHost.Logs.Any(l => l.Contains("abandon #")), "not an abandon");
Check.True(FakeHost.Uses.Contains(CorpseB), "the corpse in the open is tried meanwhile");
@ -416,6 +417,35 @@ internal static class UseRefusalTests
});
}
private static void CorpseBehindWallTryAnyway()
{
World();
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.P.CorpseWallOverride = id => id == unchecked((int)CorpseA); // the ray always says wall
WithClock((now, advance) =>
{
long answerAt = 0;
void Step()
{
int uses = FakeHost.Uses.Count;
bot.Tick(BotActivity.Looting);
if (FakeHost.Uses.Count > uses) answerAt = now() + 60;
advance(100);
if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; if (FakeHost.Uses.Last() == CorpseB) bot.P.OnViewObjectContents(CorpseB); }
}
for (int i = 0; i < 180; i++) Step(); // 18 s
Check.Eq(FakeHost.Uses.Count(u => u == CorpseA), 0, "18 s behind the wall: never opened");
for (int i = 0; i < 60; i++) Step(); // past 20 s
Check.True(FakeHost.Logs.Any(l => l.Contains("one open anyway")), "after 20 s: one open anyway, said");
Check.Eq(FakeHost.Uses.Count(u => u == CorpseA), 1, "one open");
Check.True(FakeHost.Logs.Any(l => l.Contains("a wall stands between: set aside")), "it didn't open: set aside the old way");
for (int i = 0; i < 300; i++) Step(); // 30 s more
Check.Eq(FakeHost.Uses.Count(u => u == CorpseA), 1, "and no more opens while the wall stays");
Check.False(FakeHost.Logs.Any(l => l.Contains("abandon #")), "never an abandon");
});
}
private static void LootingNormalOpens()
{
World();

View file

@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.Trade;
namespace RynthCore.RynthAiTests.Fakes;
/// <summary>
/// A trade window that behaves like ACE's (ACE.Server/WorldObjects/Player_Trade.cs): an add clears
/// both accepts, a reset clears both sides and both accepts, a decline clears only ours, and the
/// second accept completes the trade with what is in the window then.
/// </summary>
internal sealed class FakeShopGame : ITradeShopGame
{
public long Now = 10_000_000;
public bool Trade = true;
public string Pause = "";
public bool Open, YouAccepted, PartnerAccepted;
public uint Generation = 1, Sequence = 1, PartnerId, Completed;
public readonly List<uint> Mine = new(), Theirs = new();
public readonly Dictionary<uint, TradeShopItem> Items = new();
public readonly List<TradeShopItem> Pack = new();
public readonly Dictionary<string, uint> Players = new(StringComparer.OrdinalIgnoreCase);
public readonly Dictionary<uint, string> Names = new();
public readonly List<string> Actions = new();
public readonly List<(string To, string Text)> Tells = new();
public readonly List<string> Said = new(), Chats = new(), Logs = new(), Sales = new();
public readonly List<uint> Received = new(), Given = new();
/// <summary>Runs on the Nth read of the buyer's side (1-based), once: a trade event landing mid-check.</summary>
public int HookOnPartnerRead;
public Action? Hook;
private int _partnerReads;
public int PartnerReads => _partnerReads;
public long NowMs => Now;
public bool HasTrade => Trade;
public bool TryGetTrade(out TradeShopTrade trade)
{
trade = new TradeShopTrade(Open, YouAccepted, PartnerAccepted, Generation, Sequence, Open ? PartnerId : 0, Completed);
return true;
}
public uint[] TradeItems(bool partnerSide)
{
if (partnerSide)
{
_partnerReads++;
uint[] now = Theirs.ToArray();
if (Hook != null && _partnerReads == HookOnPartnerRead) { var h = Hook; Hook = null; h(); }
return now;
}
return Mine.ToArray();
}
public bool TradeAdd(uint itemId)
{
Actions.Add("add:" + itemId.ToString("X8"));
if (!Open) return false;
Mine.Add(itemId);
YouAccepted = PartnerAccepted = false;
Sequence++;
return true;
}
public bool TradeAccept()
{
Actions.Add("accept");
if (!Open) return false;
YouAccepted = true;
Sequence++;
if (PartnerAccepted) Complete();
return true;
}
public bool TradeDecline()
{
Actions.Add("decline");
YouAccepted = false;
Sequence++;
return true;
}
public bool TradeReset()
{
Actions.Add("reset");
Mine.Clear();
Theirs.Clear();
YouAccepted = PartnerAccepted = false;
Sequence++;
return true;
}
public bool TradeClose()
{
Actions.Add("close");
Open = false;
Mine.Clear();
Theirs.Clear();
YouAccepted = PartnerAccepted = false;
Sequence++;
return true;
}
public TradeShopItem? ReadItem(uint id) => Items.TryGetValue(id, out TradeShopItem it) ? it : null;
public IEnumerable<TradeShopItem> PackItems() => Pack;
public uint FindPlayer(string exactName) => Players.TryGetValue(exactName, out uint id) ? id : 0;
public string NameOf(uint id) => Names.TryGetValue(id, out string? n) ? n : "";
public void Tell(string to, string message) => Tells.Add((to, message));
public void Say(string prefix, string message) => Said.Add(prefix + message);
public void Chat(string line) => Chats.Add(line);
public void Log(string line) => Logs.Add(line);
public void RecordSale(string line) => Sales.Add(line);
public string PauseReason() => Pause;
public string TimeOfDay() => "12:00";
// ── The other player's side ─────────────────────────────────────────
/// <summary>The buyer opens a trade with us.</summary>
public void OpenTradeWith(uint partner)
{
Open = true;
Generation++;
Sequence++;
PartnerId = partner;
Mine.Clear();
Theirs.Clear();
YouAccepted = PartnerAccepted = false;
}
/// <summary>The buyer puts an item in (ACE: both accepts cleared).</summary>
public void BuyerAdds(uint id, uint wcid, int stack, string name, bool known = true)
{
Items[id] = new TradeShopItem(id, known ? wcid : 0, name, stack, known);
Theirs.Add(id);
YouAccepted = PartnerAccepted = false;
Sequence++;
}
/// <summary>The buyer accepts; if we had accepted, the trade completes.</summary>
public void BuyerAccepts()
{
PartnerAccepted = true;
Sequence++;
if (YouAccepted) Complete();
}
private void Complete()
{
Received.AddRange(Theirs);
Given.AddRange(Mine);
Completed++;
Mine.Clear();
Theirs.Clear();
YouAccepted = PartnerAccepted = false;
Sequence++;
}
public int Count(string action) => Actions.Count(a => a == action);
}

View file

@ -28,6 +28,7 @@ internal static class Program
ItemInfoPartColorsTests.Register(runner);
KitPlannerTests.Register(runner);
KitAutoTests.Register(runner);
TradeShopTests.Register(runner);
return runner.Run("RynthAi tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -51,6 +51,18 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\MiniRemote\Crafting\KitPlanner.cs" Link="Linked\KitPlanner.cs" />
<!-- Make kits when low: when a run may start, what stops one, the waits (System only). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\MiniRemote\Crafting\KitAuto.cs" Link="Linked\KitAuto.cs" />
<!-- Trade Shop: payment by WCID, prices, tells and their limits, and the whole sale flow behind
ITradeShopGame (System only; the tests drive it with Fakes\FakeShopGame.cs). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\TradeShopCurrencyTable.cs" Link="Linked\TradeShopCurrencyTable.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\TradeShopRates.cs" Link="Linked\TradeShopRates.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\TradeShopPayment.cs" Link="Linked\TradeShopPayment.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\TradeShopSettings.cs" Link="Linked\TradeShopSettings.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\TradeShopAdvertise.cs" Link="Linked\TradeShopAdvertise.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\TradeShopTellParse.cs" Link="Linked\TradeShopTellParse.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\TradeShopMessages.cs" Link="Linked\TradeShopMessages.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\TradeShopTellLimiter.cs" Link="Linked\TradeShopTellLimiter.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\ITradeShopGame.cs" Link="Linked\ITradeShopGame.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Trade\TradeShopManager.cs" Link="Linked\TradeShopManager.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -0,0 +1,658 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using RynthCore.Plugin.RynthAi.Trade;
using RynthCore.RynthAiTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiTests.Tests;
// The Trade Shop (Plugins/RynthCore.Plugin.RynthAi/Trade). Ported from SilentKelpie's Trade Shop
// tests (RynthSuite PR #12: tell parsing, selectors, the price sheet, advertise prefixes), plus the
// safety rules: payment by WCID only, the accept-time re-check, no accept without !buy, Confirm each
// sale both ways, Mode 2 never accepted by the shop, the tell limits and the defaults.
internal static class TradeShopTests
{
public static void Register(Runner r)
{
// Ported (adapted).
r.Add("tradeshop tell: plain Name tells you", PlainTell);
r.Add("tradeshop tell: IIDString link, and a quoted 'X tells you' can't change the sender", LinkedTell);
r.Add("tradeshop tell: shop verbs need a '!' (a lone greeting doesn't)", Verbs);
r.Add("tradeshop selector: slot, value and name forms", Selectors);
r.Add("tradeshop messages: resolve by slot, name and value", Resolve);
r.Add("tradeshop messages: the sheet has the rates and every row", SheetRows);
r.Add("tradeshop advertise: channel prefixes and names", AdvertisePrefixes);
// New: payment by WCID.
r.Add("tradeshop payment: the WCID table (pyreals 273, 14 trade notes at face value, single-use LK)", WcidTable);
r.Add("tradeshop payment: junk with a high Value or a currency's name is worth 0", JunkWorthZero);
r.Add("tradeshop payment: an item not read yet is never paid", UnknownNotPaid);
r.Add("tradeshop payment: rates, refused currencies and price alternatives", Rates);
// New: the sale flow.
r.Add("tradeshop sale: confirm ON - ready, prompt, Accept sale re-checks then accepts, sale logged", ConfirmOnSale);
r.Add("tradeshop sale: confirm ON - a change while the prompt is up clears it and checks again", PromptClearsOnChange);
r.Add("tradeshop sale: confirm ON - Decline closes the trade and tells the buyer", DeclineCloses);
r.Add("tradeshop sale: confirm OFF - accepts a checked sale itself, and the warning when turned off", ConfirmOffSale);
r.Add("tradeshop sale: the accept-time re-check refuses when the trade changes between the reads", AcceptTimeRecheck);
r.Add("tradeshop sale: a change after the accept that fails the check withdraws the accept", ChangeAfterAccept);
r.Add("tradeshop sale: our side must be exactly the listed item", OurSideExact);
r.Add("tradeshop sale: no accept without !buy (greeted only), in either mode", NoAcceptWithoutBuy);
r.Add("tradeshop sale: Mode 2 is never accepted by the shop, only by the player's Accept sale", Mode2HandAccept);
r.Add("tradeshop sale: paused in combat / macro / hunt: tells dropped, a sale called off", Paused);
r.Add("tradeshop sale: turning it on says what it does; off means no answers", OnOff);
// New: limits and defaults.
r.Add("tradeshop limits: one command per 2 s, 20 lines a minute, ignore after spam", InboundLimits);
r.Add("tradeshop limits: 12 lines a minute per buyer, 30 in all, queues capped", OutboundLimits);
r.Add("tradeshop limits: the price sheet is chunked and capped", SheetCapped);
r.Add("tradeshop defaults: off, confirm on, no advertising, Trade, 5 min minimum, on/off not saved", Defaults);
r.Add("tradeshop advertise: off by default, never before a full interval, no leading slash", Advertising);
}
// ── Ported ──────────────────────────────────────────────────────────
private static void PlainTell()
{
Check.True(TradeShopTellParse.TryParseTell("Bob tells you, \"!list\"", out string who, out string msg), "parse");
Check.Eq(who, "Bob", "sender");
Check.Eq(msg, "!list", "body");
Check.False(TradeShopTellParse.TryParseTell("Bob says, \"!list\"", out _, out _), "local chat isn't a tell");
}
private static void LinkedTell()
{
Check.True(TradeShopTellParse.TryParseTell("<Tell:IIDString:1342177281:Alice>Alice<\\Tell> tells you, \"!buy 2\"",
out string who, out string msg), "parse link");
Check.Eq(who, "Alice", "link name");
Check.Eq(msg, "!buy 2", "body");
Check.True(TradeShopTellParse.TryParseTell("Bob tells you, \"Eve tells you, \"!buy 1\"\"", out who, out _), "nested");
Check.Eq(who, "Bob", "the first speaker is the sender");
Check.False(TradeShopTellParse.IsSafeName("Bob, /quit"), "a name with a comma or slash isn't sent a tell");
}
private static void Verbs()
{
Check.Eq(TradeShopTellParse.SplitCommand("!buy #2"), ("buy", "#2"), "buy");
Check.Eq(TradeShopTellParse.SplitCommand("!sheet").verb, "list", "sheet = list");
Check.Eq(TradeShopTellParse.SplitCommand("!rate").verb, "rates", "rate = rates");
Check.Eq(TradeShopTellParse.SplitCommand("hi").verb, "help", "a lone greeting");
Check.Eq(TradeShopTellParse.SplitCommand("hi there, how are you").verb, "", "chat isn't a command");
Check.Eq(TradeShopTellParse.SplitCommand("buy 2").verb, "", "no ! no buy");
Check.Eq(TradeShopTellParse.SplitCommand("!dance").verb, "", "unknown verb");
}
private static void Selectors()
{
Check.Eq(TradeShopTellParse.ParseSelector("#3").slot, 3, "#3");
Check.Eq(TradeShopTellParse.ParseSelector("slot:4").slot, 4, "slot:");
Check.Eq(TradeShopTellParse.ParseSelector("id:5").slot, 5, "id:");
Check.Eq(TradeShopTellParse.ParseSelector("2").slot, 2, "bare small = slot");
Check.Eq(TradeShopTellParse.ParseSelector("250,000").valuePy, 250000L, "bare large = value");
Check.Eq(TradeShopTellParse.ParseSelector("value:1000").valuePy, 1000L, "value:");
var q = TradeShopTellParse.ParseSelector("\"Sword of Lost Light\"");
Check.Null(q.slot, "quoted is a name");
Check.Eq(q.text, "Sword of Lost Light", "quoted text");
}
private static List<TradeShopListing> Three() => new()
{
new() { Name = "Alpha", PricePyreals = 100 },
new() { Name = "Sword of Lost Light", PricePyreals = 250_000 },
new() { Name = "Beta Key", PricePyreals = 500_000 },
};
private static void Resolve()
{
var list = Three();
Check.Eq(TradeShopMessages.ResolveListing(list, "#2")!.Name, "Sword of Lost Light", "slot");
Check.Eq(TradeShopMessages.ResolveListing(list, "lost light")!.Name, "Sword of Lost Light", "partial name");
Check.Eq(TradeShopMessages.ResolveListing(list, "250000")!.Name, "Sword of Lost Light", "value exact");
Check.Eq(TradeShopMessages.ResolveListing(list, "value:400000")!.Name, "Beta Key", "value at or above");
Check.Null(TradeShopMessages.ResolveListing(list, "#9"), "no slot 9");
}
private static void SheetRows()
{
var chunks = TradeShopMessages.PriceSheet(Three(), new TradeShopRates(), includeRates: true);
Check.True(chunks.Count >= 1, "a chunk");
Check.True(chunks[0].StartsWith("Rates:", StringComparison.Ordinal), "rates first");
string all = string.Join(" ", chunks);
Check.True(all.Contains("#1 Alpha") && all.Contains("#2 Sword of Lost Light") && all.Contains("#3 Beta Key"), "every row: " + all);
Check.True(chunks.All(c => c.Length <= TradeShopMessages.MaxLineChars), "tell-sized");
}
private static void AdvertisePrefixes()
{
Check.Eq(TradeShopAdvertise.SendPrefix(TradeShopAdvertiseChannel.Trade), "/ct ", "trade");
Check.Eq(TradeShopAdvertise.SendPrefix(TradeShopAdvertiseChannel.General), "/cg ", "general");
Check.Eq(TradeShopAdvertise.SendPrefix(TradeShopAdvertiseChannel.Local), "", "local");
Check.True(TradeShopAdvertise.TryParseChannel("ct", out var ch) && ch == TradeShopAdvertiseChannel.Trade, "ct = Trade");
Check.False(TradeShopAdvertise.TryParseChannel("allegiance", out _), "not a shop channel");
}
// ── Payment ─────────────────────────────────────────────────────────
private static TradeShopItem? Lookup(Dictionary<uint, TradeShopItem> d, uint id) => d.TryGetValue(id, out var it) ? it : null;
private static void WcidTable()
{
Check.Eq(TradeShopCurrencyTable.Classify(273), TradeShopCurrency.Pyreals, "273 pyreals");
var faces = new Dictionary<uint, long>
{
[2621] = 100, [2622] = 500, [2623] = 1000, [2624] = 5000, [2625] = 10000, [7374] = 15000, [7375] = 20000,
[7376] = 25000, [2626] = 50000, [7377] = 75000, [2627] = 100000, [20628] = 150000, [20629] = 200000, [20630] = 250000,
};
foreach (var kv in faces)
{
Check.Eq(TradeShopCurrencyTable.Classify(kv.Key), TradeShopCurrency.TradeNote, $"{kv.Key} is a note");
Check.Eq(TradeShopCurrencyTable.NoteFaceValue(kv.Key), kv.Value, $"{kv.Key} face");
}
foreach (uint lk in new uint[] { 48747, 48914, 51558, 72048, 72600 })
Check.Eq(TradeShopCurrencyTable.Classify(lk), TradeShopCurrency.LegendaryKey, $"{lk} single-use LK");
foreach (uint not in new uint[] { 48746, 48748, 51954, 72474, 46414, 0, 1, 999999 })
Check.Eq(TradeShopCurrencyTable.Classify(not), TradeShopCurrency.None, $"{not} isn't payment");
Check.Eq(TradeShopCurrencyTable.AllWcids().Count(), 20, "20 WCIDs in all");
var d = new Dictionary<uint, TradeShopItem>
{
[1] = new(1, 273, "Pyreal", 25_000, true),
[2] = new(2, 20630, "Trade Note (250,000)", 3, true),
[3] = new(3, 2623, "Trade Note (1,000)", 5, true),
[4] = new(4, 48747, "Legendary Key", 0, true),
};
TradeShopTally t = TradeShopPayment.Tally(new uint[] { 1, 2, 3, 4 }, id => Lookup(d, id));
Check.Eq(t.Pyreals, 25_000L, "pyreals by stack");
Check.Eq(t.NotePyreals, 755_000L, "notes at face x stack");
Check.Eq(t.LegendaryKeys, 1L, "one key");
Check.Eq(t.Unknown, 0, "all read");
Check.Eq(new TradeShopRates().AcceptedPyreals(t), 25_000L + 755_000L + TradeShopRates.DefaultPyrealsPerLegendaryKey, "worth");
}
private static void JunkWorthZero()
{
var d = new Dictionary<uint, TradeShopItem>
{
// A junk item with a huge Value: Value is never read; its WCID isn't in the table.
[10] = new(10, 30_000, "Gold Chunk", 0, true),
// Items named like currency, with the wrong WCID.
[11] = new(11, 12_345, "Pyreal", 1_000_000, true),
[12] = new(12, 54_321, "Trade Note (250,000)", 100, true),
[13] = new(13, 48748, "Legendary Key", 0, true), // a multi-use key: not one LK
};
TradeShopTally t = TradeShopPayment.Tally(new uint[] { 10, 11, 12, 13 }, id => Lookup(d, id));
Check.Eq(new TradeShopRates().AcceptedPyreals(t), 0L, "worth 0");
Check.Eq(t.OtherItems, 4, "four non-payment items");
Check.False(new TradeShopRates().Covers(1, t), "doesn't pay even 1 py");
}
private static void UnknownNotPaid()
{
var d = new Dictionary<uint, TradeShopItem>
{
[1] = new(1, 20630, "Trade Note (250,000)", 100, true),
[2] = new(2, 0, "", -1, false), // the client has no WCID for it yet
[3] = new(3, 273, "Pyreal", 0, true), // pyreals with no stack size read
};
TradeShopTally t = TradeShopPayment.Tally(new uint[] { 1, 2, 3, 4 }, id => Lookup(d, id)); // 4: not in the cache at all
Check.Eq(t.Unknown, 3, "three unknown");
Check.False(new TradeShopRates().Covers(1_000, t), "unknown items block the payment, however much else is there");
}
private static void Rates()
{
var r = new TradeShopRates();
Check.Eq(r.KeysFor(1_000_000), 2L, "2 LK at 500k");
Check.Eq(r.KeysFor(1_000_001), 3L, "rounded up");
Check.Eq(r.MmdFor(1_000_000), 4L, "4 MMD");
string alt = r.FormatAlternatives(1_000_000);
Check.True(alt.Contains("1,000,000 py") && alt.Contains("4 MMD") && alt.Contains("2 LK"), alt);
var t = new TradeShopTally { Pyreals = 600_000, NotePyreals = 500_000, LegendaryKeys = 1 };
Check.True(r.Covers(1_000_000, t), "mixed payment covers");
r.AcceptPyreals = false;
Check.Eq(r.AcceptedPyreals(t), 1_000_000L, "pyreals refused: notes + key");
r.AcceptLegendaryKeys = false;
Check.False(r.Covers(1_000_000, t), "keys refused too: short");
Check.Eq(r.KeysFor(1_000_000), 0L, "no key price when refused");
Check.False(new TradeShopRates().Covers(0, t), "no price, no sale");
}
// ── The sale flow ───────────────────────────────────────────────────
private const uint Bob = 0x50000BB0, Eve = 0x50000EE0, Sword = 0x7000_0001, SwordWcid = 5000;
private const long Price = 1_000_000;
private sealed class Shop
{
public readonly FakeShopGame G = new();
public readonly TradeShopSettings Cfg = new() { Enabled = true };
public readonly TradeShopManager M;
private uint _nextItem = 0x6000_0000;
public Shop(bool confirm = true, TradeShopMode mode = TradeShopMode.Mode1Stock)
{
Cfg.ConfirmEachSale = confirm;
Cfg.Mode = mode;
Cfg.Listings.Add(new TradeShopListing { Name = "Sword", PricePyreals = Price, ObjectId = Sword, Wcid = SwordWcid, Enabled = true });
G.Items[Sword] = new TradeShopItem(Sword, SwordWcid, "Sword", 0, true);
G.Pack.Add(G.Items[Sword]);
G.Players["Bob"] = Bob; G.Names[Bob] = "Bob";
G.Players["Eve"] = Eve; G.Names[Eve] = "Eve";
M = new TradeShopManager(G, () => Cfg);
Tick(); // baseline
}
public void Tick(int n = 1)
{
for (int i = 0; i < n; i++) { M.Tick(); G.Now += 1_300; }
}
public void TellFrom(string who, string body)
{
G.Now += TradeShopTellLimiter.MinCommandGapMs + 100;
M.OnTell($"{who} tells you, \"{body}\"", isIncomingTell: true);
Tick();
}
public uint Pay(uint wcid, int stack, string name = "x", bool known = true)
{
uint id = _nextItem++;
G.BuyerAdds(id, wcid, stack, name, known);
return id;
}
/// <summary>!buy, Bob opens the trade, the sword goes in the window.</summary>
public void ReadyForPayment(string who = "Bob", uint whoId = Bob)
{
TellFrom(who, "!buy #1");
G.OpenTradeWith(whoId);
Tick();
}
public bool TellTo(string who, string part) => G.Tells.Any(t => t.To == who && t.Text.Contains(part, StringComparison.OrdinalIgnoreCase));
public bool Chatted(string part) => G.Chats.Any(c => c.Contains(part, StringComparison.OrdinalIgnoreCase));
}
private static void ConfirmOnSale()
{
var s = new Shop(confirm: true);
s.ReadyForPayment();
Check.True(s.G.Actions.Contains("reset") && s.G.Actions.Contains("add:" + Sword.ToString("X8")), "window cleared, sword added: " + string.Join(",", s.G.Actions));
Check.True(s.G.Mine.SequenceEqual(new[] { Sword }), "our side is the sword");
s.Pay(TradeShopCurrencyTable.MmdWcid, 4, "Trade Note (250,000)");
s.Tick();
Check.Eq(s.G.Count("accept"), 0, "confirm on: no accept by itself");
TradeShopPrompt? p = s.M.Prompt;
Check.NotNull(p, "the prompt is up");
Check.True(p != null && p.Buyer == "Bob" && p.Item == "Sword" && p.PricePyreals == Price && p.Paid.Contains("4x Trade Note (250,000)"), "prompt: buyer, item, price, paid");
Check.True(s.Chatted("sale ready") && s.Chatted("Bob") && s.Chatted("1,000,000"), "a chat line with the sale");
s.Tick(5);
Check.Eq(s.G.Count("accept"), 0, "still waiting for the player");
s.M.RequestAccept();
s.Tick();
Check.Eq(s.G.Count("accept"), 1, "Accept sale accepts");
Check.Null(s.M.Prompt, "prompt gone");
s.G.BuyerAccepts();
s.Tick();
Check.Eq(s.G.Completed, 1u, "trade completed");
Check.True(s.G.Given.SequenceEqual(new[] { Sword }), "we gave the sword");
Check.Eq(s.G.Sales.Count, 1, "one sale in the sales log");
Check.True(s.G.Sales[0].Contains("Sword") && s.G.Sales[0].Contains("Bob") && s.G.Sales[0].Contains("1,000,000") && s.G.Sales[0].Contains("Trade Note"),
"sale line: item, buyer, price, paid: " + s.G.Sales[0]);
Check.True(s.Chatted("Sold Sword to Bob"), "the sale in chat");
Check.True(s.G.Logs.Any(l => l.Contains("Sold Sword to Bob")), "the sale in the log");
Check.True(s.M.RecentSales().Count == 1, "in the window's last sales");
Check.True(s.G.Actions.Last() == "close", "trade window closed for the next buyer");
}
private static void PromptClearsOnChange()
{
var s = new Shop(confirm: true);
s.ReadyForPayment();
s.Pay(TradeShopCurrencyTable.MmdWcid, 4);
s.Tick();
Check.NotNull(s.M.Prompt, "prompt up");
s.Pay(0, -1, "?", known: false); // the buyer adds something the client can't read yet
s.Tick();
Check.Null(s.M.Prompt, "the change cleared the prompt");
Check.True(s.Chatted("changed; checking it again"), "said so");
s.Tick(3);
Check.Null(s.M.Prompt, "an unknown item keeps it from coming back");
s.M.RequestAccept();
s.Tick();
Check.Eq(s.G.Count("accept"), 0, "no accept while an item is unknown");
Check.True(s.Chatted("no sale is waiting"), "Accept sale says why");
}
private static void DeclineCloses()
{
var s = new Shop(confirm: true);
s.ReadyForPayment();
s.Pay(TradeShopCurrencyTable.MmdWcid, 4);
s.Tick();
s.M.RequestDecline();
s.Tick(3);
Check.Eq(s.G.Count("accept"), 0, "not accepted");
Check.True(s.G.Actions.Contains("close") && !s.G.Open, "trade closed");
Check.Null(s.M.Prompt, "prompt gone");
Check.True(s.TellTo("Bob", "declined"), "the buyer is told");
Check.Eq(s.G.Sales.Count, 0, "no sale");
}
private static void ConfirmOffSale()
{
var s = new Shop(confirm: true);
s.M.SetConfirmEachSale(false);
s.Tick();
Check.True(s.Chatted("Confirm each sale OFF. Warning"), "one-line warning when turned off");
Check.False(s.Cfg.ConfirmEachSale, "off");
s.ReadyForPayment();
s.Pay(273, 999_999, "Pyreal");
s.Tick(2);
Check.Eq(s.G.Count("accept"), 0, "short by 1: no accept");
s.Pay(273, 1, "Pyreal");
s.Tick();
Check.Eq(s.G.Count("accept"), 1, "covered: accepted without a prompt");
Check.Null(s.M.Prompt, "no prompt");
s.G.BuyerAccepts();
s.Tick();
Check.Eq(s.G.Sales.Count, 1, "sale logged");
}
private static void AcceptTimeRecheck()
{
// A trade event lands between the accept-time reads (only the state's sequence moves): the shop
// doesn't accept on that read, and accepts on the next tick when nothing changed.
var s = new Shop(confirm: false);
s.ReadyForPayment();
s.Pay(TradeShopCurrencyTable.MmdWcid, 4);
// The next tick reads the buyer's side twice: the wait check, then the accept-time check.
s.G.HookOnPartnerRead = s.G.PartnerReads + 2;
s.G.Hook = () => s.G.Sequence++;
s.Tick();
Check.Eq(s.G.Count("accept"), 0, "the state moved between the reads: not accepted");
s.Tick();
Check.Eq(s.G.Count("accept"), 1, "re-read, unchanged: accepted");
// The payment shrinks during the accept-time check: never accepted.
var t = new Shop(confirm: false);
t.ReadyForPayment();
uint note = t.Pay(TradeShopCurrencyTable.MmdWcid, 4);
t.G.HookOnPartnerRead = t.G.PartnerReads + 2;
t.G.Hook = () =>
{
t.G.Items[note] = new TradeShopItem(note, TradeShopCurrencyTable.MmdWcid, "Trade Note (250,000)", 1, true);
t.G.Sequence++;
};
t.Tick(4);
Check.Eq(t.G.Count("accept"), 0, "short at the accept-time check: not accepted");
Check.True(t.M.Status.Contains("paid 250,000 of 1,000,000"), "status says it's short: " + t.M.Status);
}
private static void ChangeAfterAccept()
{
var s = new Shop(confirm: false);
s.ReadyForPayment();
uint note = s.Pay(TradeShopCurrencyTable.MmdWcid, 4);
s.Tick();
Check.Eq(s.G.Count("accept"), 1, "accepted");
// A stale or out-of-order update: the window now shows less, and our accept still stands.
s.G.Items[note] = new TradeShopItem(note, TradeShopCurrencyTable.MmdWcid, "Trade Note (250,000)", 1, true);
s.G.YouAccepted = true;
s.G.Sequence++;
s.Tick();
Check.Eq(s.G.Count("decline"), 1, "the accept is withdrawn");
Check.True(s.Chatted("accept withdrawn"), "said so");
s.G.BuyerAccepts();
s.Tick();
Check.Eq(s.G.Completed, 0u, "no trade");
Check.Eq(s.G.Sales.Count, 0, "no sale");
// The buyer adding more (ACE clears both accepts) is accepted again when it still passes.
var t = new Shop(confirm: false);
t.ReadyForPayment();
t.Pay(TradeShopCurrencyTable.MmdWcid, 4);
t.Tick();
t.G.Now += TradeShopManager.AcceptEchoWaitMs;
t.Pay(273, 10, "Pyreal");
t.Tick();
Check.Eq(t.G.Count("accept"), 2, "accepted again after the buyer added more");
}
private static void OurSideExact()
{
var s = new Shop(confirm: false);
s.ReadyForPayment();
s.G.Items[0x7000_0002] = new TradeShopItem(0x7000_0002, 6000, "Shield", 0, true);
s.G.Mine.Add(0x7000_0002); // something else on our side too
s.G.Sequence++;
s.Pay(TradeShopCurrencyTable.MmdWcid, 4);
s.Tick(3);
Check.Eq(s.G.Count("accept"), 0, "our side isn't exactly the sword: no accept");
Check.True(s.M.Status.Contains("isn't exactly Sword"), s.M.Status);
// The item in the window turned into something else (its WCID no longer the listing's).
var t = new Shop(confirm: false);
t.ReadyForPayment();
t.G.Items[Sword] = new TradeShopItem(Sword, 9999, "Sword", 0, true);
t.Pay(TradeShopCurrencyTable.MmdWcid, 4);
t.Tick(3);
Check.Eq(t.G.Count("accept"), 0, "not the listed item: no accept");
}
private static void NoAcceptWithoutBuy()
{
foreach (TradeShopMode mode in new[] { TradeShopMode.Mode1Stock, TradeShopMode.Mode2Text })
{
var s = new Shop(confirm: false, mode: mode);
s.G.OpenTradeWith(Eve);
s.Tick();
s.Pay(TradeShopCurrencyTable.MmdWcid, 100);
s.G.BuyerAccepts();
s.Tick(10);
Check.Eq(s.G.Count("accept"), 0, $"{mode}: never accepted");
Check.Null(s.M.Prompt, $"{mode}: no prompt");
Check.False(s.G.Actions.Any(a => a.StartsWith("add:", StringComparison.Ordinal)), $"{mode}: nothing put in the window");
Check.True(s.TellTo("Eve", "only accept a trade after !buy"), $"{mode}: greeted");
Check.Eq(s.G.Tells.Count(t => t.To == "Eve"), 1, $"{mode}: greeted once");
}
// Bob says !buy, but Eve opens the trade: Eve is not the buyer.
var b = new Shop(confirm: false);
b.TellFrom("Bob", "!buy #1");
b.G.OpenTradeWith(Eve);
b.Tick();
b.Pay(TradeShopCurrencyTable.MmdWcid, 4);
b.Tick(5);
Check.Eq(b.G.Count("accept"), 0, "someone else's trade isn't the sale");
Check.False(b.G.Actions.Any(a => a.StartsWith("add:", StringComparison.Ordinal)), "the sword stays in the pack");
}
private static void Mode2HandAccept()
{
var s = new Shop(confirm: false, mode: TradeShopMode.Mode2Text);
s.TellFrom("Bob", "!buy #1");
s.G.OpenTradeWith(Bob);
s.Tick();
Check.False(s.G.Actions.Any(a => a.StartsWith("add:", StringComparison.Ordinal) || a == "reset"), "Mode 2 puts nothing in the window");
s.Pay(TradeShopCurrencyTable.MmdWcid, 4);
s.Tick(5);
Check.Eq(s.G.Count("accept"), 0, "Mode 2: never accepted by the shop, even with confirm off");
Check.NotNull(s.M.Prompt, "the prompt is up");
Check.True(s.M.Prompt!.Mode == TradeShopMode.Mode2Text, "a Mode 2 prompt");
s.M.RequestAccept();
s.Tick();
Check.Eq(s.G.Count("accept"), 1, "the player's Accept sale accepts");
s.G.BuyerAccepts();
s.Tick();
Check.True(s.G.Sales.Count == 1 && s.G.Sales[0].Contains("hand it over"), "sale logged, with the hand-over note");
}
private static void Paused()
{
var s = new Shop(confirm: true);
s.G.Pause = "the macro is running";
s.TellFrom("Bob", "!list");
s.Tick(3);
Check.Eq(s.G.Tells.Count, 0, "no answers while paused");
Check.True(s.M.Status.StartsWith("Paused: the macro is running"), s.M.Status);
var t = new Shop(confirm: true);
t.ReadyForPayment();
t.Pay(TradeShopCurrencyTable.MmdWcid, 4);
t.Tick();
Check.NotNull(t.M.Prompt, "prompt up");
t.G.Pause = "in combat mode";
t.Tick(3);
Check.Null(t.M.Prompt, "sale called off");
Check.True(t.G.Actions.Contains("close"), "trade closed");
Check.True(t.TellTo("Bob", "called off"), "the buyer is told");
t.M.RequestAccept();
t.Tick();
Check.Eq(t.G.Count("accept"), 0, "nothing to accept");
}
private static void OnOff()
{
var s = new Shop();
s.Cfg.Enabled = false;
s.TellFrom("Bob", "!list");
s.Tick(3);
Check.Eq(s.G.Tells.Count, 0, "off: no answers");
s.M.SetEnabled(true);
s.Tick();
Check.True(s.Cfg.Enabled, "on");
Check.True(s.Chatted("Trade Shop ON") && s.Chatted("checks their payment by item type") && s.Chatted("Confirm each sale is ON"),
"turning it on says what it does");
s.TellFrom("Bob", "!list");
s.Tick(3);
Check.True(s.TellTo("Bob", "Price sheet"), "on: the price sheet");
}
// ── Limits ──────────────────────────────────────────────────────────
private static void InboundLimits()
{
var l = new TradeShopTellLimiter();
long t = 1_000_000;
Check.Eq(l.OnIncoming("Bob", t), TradeShopTellLimiter.Verdict.Accept, "first");
Check.Eq(l.OnIncoming("Bob", t + 1_000), TradeShopTellLimiter.Verdict.TooFast, "1 s later: too fast");
Check.Eq(l.OnIncoming("Bob", t + 2_100), TradeShopTellLimiter.Verdict.Accept, "2 s after the last accepted one");
Check.Eq(l.OnIncoming("Eve", t + 2_200), TradeShopTellLimiter.Verdict.Accept, "another buyer has their own gap");
// 20 lines a minute: the 21st starts a 2-minute ignore.
var m = new TradeShopTellLimiter();
TradeShopTellLimiter.Verdict v = default;
for (int i = 0; i < 21; i++) v = m.OnIncoming("Bob", t + i * 2_500);
Check.Eq(v, TradeShopTellLimiter.Verdict.NowIgnored, "21 lines in a minute: ignored");
Check.True(m.IsIgnored("Bob", t + 60_000), "still ignored");
Check.Eq(m.OnIncoming("Bob", t + 60_000), TradeShopTellLimiter.Verdict.Ignored, "dropped");
Check.Eq(m.OnIncoming("Bob", t + 21 * 2_500 + TradeShopTellLimiter.SpamIgnoreMs), TradeShopTellLimiter.Verdict.Accept, "after the ignore");
// Five too-fast lines in a minute: ignored.
var n = new TradeShopTellLimiter();
n.OnIncoming("Bob", t);
for (int i = 1; i <= 5; i++) v = n.OnIncoming("Bob", t + i * 100);
Check.Eq(v, TradeShopTellLimiter.Verdict.NowIgnored, "spam: ignored");
// Through the shop: a flood gets one price sheet and one notice, not one per line.
var s = new Shop();
for (int i = 0; i < 30; i++) s.M.OnTell("Bob tells you, \"!list\"", isIncomingTell: true);
s.Tick(40);
int sheets = s.G.Tells.Count(x => x.To == "Bob" && x.Text.StartsWith("Rates:", StringComparison.Ordinal));
Check.Eq(sheets, 1, "one sheet for a flood");
Check.True(s.G.Tells.Count(x => x.To == "Bob") <= TradeShopTellLimiter.MaxOutPerBuyerPerMinute + 1, "per-buyer cap");
Check.True(s.TellTo("Bob", "ignore you"), "told once that they're ignored");
Check.Eq(s.G.Tells.Count(x => x.Text.Contains("ignore you")), 1, "once");
}
private static void OutboundLimits()
{
var l = new TradeShopTellLimiter();
long t = 5_000_000;
int bob = 0;
for (int i = 0; i < 20; i++) if (l.TryTakeOut("Bob", t + i)) bob++;
Check.Eq(bob, TradeShopTellLimiter.MaxOutPerBuyerPerMinute, "12 a minute to one buyer");
Check.True(l.TryTakeOut("Bob", t + 30, overBuyerCap: true), "a sale line still goes");
int all = bob + 1;
for (int i = 0; i < 100; i++) if (l.TryTakeOut("P" + (char)('a' + i % 26) + (char)('a' + i / 26), t + 40 + i)) all++;
Check.Eq(all, TradeShopTellLimiter.MaxOutPerMinute, "30 a minute in all");
Check.True(l.TryTakeOut("Zed", t + 60_100), "a minute later there's room again");
// Through the shop: lines go 1.2 s apart, and never more than 30 in a minute.
var s = new Shop();
for (int b = 0; b < 15; b++)
{
string who = "Buyer" + (char)('a' + b);
s.M.OnTell($"{who} tells you, \"!list\"", isIncomingTell: true);
}
Check.True(CountQueuedIn(s) <= TradeShopTellLimiter.MaxInQueue, "inbound queue capped");
long start = s.G.Now;
s.Tick(60); // 60 ticks of 1.3 s = 78 s
int firstMinute = s.G.Tells.Count;
Check.True(firstMinute <= TradeShopTellLimiter.MaxOutPerMinute * 2, "at most 30 a minute: " + firstMinute);
var q = new Shop();
for (int i = 0; i < 100; i++) q.M.OnTell("Bob tells you, \"!list\"", isIncomingTell: true);
Check.True(CountQueuedIn(q) == TradeShopTellLimiter.MaxInQueue, "20 queued, the rest dropped");
_ = start;
}
private static int CountQueuedIn(Shop s)
{
var f = typeof(TradeShopManager).GetField("_inCount", BindingFlags.NonPublic | BindingFlags.Instance);
return (int)f!.GetValue(s.M)!;
}
private static void SheetCapped()
{
var list = new List<TradeShopListing>();
for (int i = 0; i < 60; i++) list.Add(new TradeShopListing { Name = "Item number " + i + " with a long name", PricePyreals = 1000 + i });
var chunks = TradeShopMessages.PriceSheet(list, new TradeShopRates(), includeRates: true);
Check.Eq(chunks.Count, TradeShopMessages.MaxSheetChunks, "capped at 4");
Check.True(chunks.All(c => c.Length <= TradeShopMessages.MaxLineChars), "each tell-sized");
Check.True(chunks[^1].Contains("more") && chunks[^1].Contains("!price"), "the last line says how many more: " + chunks[^1]);
Check.Eq(TradeShopMessages.Clip(new string('x', 500)).Length, TradeShopMessages.MaxLineChars, "a long line is clipped");
Check.False(TradeShopMessages.Clip("a\nb").Contains('\n'), "no line breaks");
}
private static void Defaults()
{
var c = new TradeShopSettings();
Check.False(c.Enabled, "off");
Check.True(c.ConfirmEachSale, "confirm each sale on");
Check.False(c.AdvertiseEnabled, "no advertising");
Check.Eq(c.AdvertiseChannel, TradeShopAdvertiseChannel.Trade, "Trade channel");
Check.True(c.AdvertiseIntervalSec >= 300, "interval at least 5 min");
Check.Eq(TradeShopSettings.ClampAdvertiseSec(30), 300, "30 s clamps to 300");
Check.Eq(c.Mode, TradeShopMode.Mode1Stock, "Mode 1");
Check.True(typeof(TradeShopSettings).GetField(nameof(TradeShopSettings.Enabled))!.GetCustomAttribute<JsonIgnoreAttribute>() != null,
"on/off is never saved");
var m = new TradeShopManager(new FakeShopGame(), () => c);
m.Tick();
Check.Eq(m.Status, "Off", "a new shop is off");
}
private static void Advertising()
{
var s = new Shop();
s.Tick(500); // ~11 minutes
Check.Eq(s.G.Said.Count, 0, "off by default: never advertises");
s.Cfg.AdvertiseEnabled = true;
s.Cfg.AdvertiseIntervalSec = 30; // clamped to 300
s.Tick(200); // ~4.3 minutes
Check.Eq(s.G.Said.Count, 0, "nothing before a full (5 min) interval");
s.Tick(40);
Check.Eq(s.G.Said.Count, 1, "one advert after 5 minutes");
Check.True(s.G.Said[0].StartsWith("/ct [Trade Shop] Selling: Sword"), s.G.Said[0]);
s.Cfg.AdvertisePrefix = "/quit WTS";
string line = TradeShopManager.AdvertiseLine(s.Cfg, s.Cfg.ForSale());
Check.True(line.StartsWith("quit WTS"), "a leading slash is dropped: " + line);
s.M.RequestAdvertise();
s.Tick();
s.M.RequestAdvertise();
s.Tick();
Check.Eq(s.G.Said.Count, 2, "Advertise now, then not again within a minute");
}
}

View file

@ -104,8 +104,12 @@ internal static partial class Program
Eq((int)((byte*)&t.VaultedDungeonsEnabled - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.VaultedDungeonsEnabledOffset, "VaultedDungeonsEnabled next");
Eq((int)((byte*)&t.BackAwayFrom - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.BackAwayFromOffset, "BackAwayFrom next");
Eq((int)((byte*)&t.SetPlayerCounter - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.SetPlayerCounterOffset, "SetPlayerCounter next");
Eq((uint)sizeof(RynthCore.Plugin.Shared.RynthAiHubApiV1), (uint)(RynthCore.Plugin.Shared.RynthAiHubApiV1.SetPlayerCounterOffset + sizeof(nint)),
"SetPlayerCounter is the last field (a new one appends here, with its own offset check)");
// LootActions, VendorSells and TradeGives (2026-11-26, RynthSort's pack jobs) came after SetPlayerCounter.
Eq((int)((byte*)&t.LootActions - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.LootActionsOffset, "LootActions next");
Eq((int)((byte*)&t.VendorSells - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.VendorSellsOffset, "VendorSells next");
Eq((int)((byte*)&t.TradeGives - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.TradeGivesOffset, "TradeGives next");
Eq((uint)sizeof(RynthCore.Plugin.Shared.RynthAiHubApiV1), (uint)(RynthCore.Plugin.Shared.RynthAiHubApiV1.TradeGivesOffset + sizeof(nint)),
"TradeGives is the last field (a new one appends here, with its own offset check)");
}
}

View file

@ -38,6 +38,7 @@ internal static partial class Program
Run(nameof(RecallListFromSpellbookAndMemory), RecallListFromSpellbookAndMemory);
Run(nameof(RecallListColdSpellbook), RecallListColdSpellbook);
Run(nameof(RecallMemoryRoundTrip), RecallMemoryRoundTrip);
Run(nameof(PortalRecallNoRecall), PortalRecallNoRecall);
Run(nameof(RecallMessages), RecallMessages);
Run(nameof(HandCastOnALifestone), HandCastOnALifestone);
Run(nameof(HandCastPortalTie), HandCastPortalTie);
@ -67,6 +68,7 @@ internal static partial class Program
RunArrival();
RunRealWalks();
RunTripTimes();
RunTargetSwitch();
Console.WriteLine();
Console.WriteLine(_fails == 0 && _asserts > 0
@ -228,6 +230,31 @@ internal static partial class Program
Check(notes.Exists(n => n.Contains("Spellbook not read")), "says why");
}
// R-20261126-024033-5d60 (Conquest): from the Dark Isle, which can't be recalled to, a goto cast Portal Recall and
// landed in a dungeon visited earlier. ACE keeps a portal as the last portal only if it isn't NoRecall.
private static void PortalRecallNoRecall()
{
Check(RecallPlanner.ForPortal(1) == RecallPlanner.LastPortalUpdate.Set, "an ordinary portal: Portal Recall goes there");
Check(RecallPlanner.ForPortal(0x20) == RecallPlanner.LastPortalUpdate.Keep, "a no-recall portal: the last portal stays the one before");
Check(RecallPlanner.ForPortal(0x20 | 0x2) == RecallPlanner.LastPortalUpdate.Keep, "no-recall among other rules");
Check(RecallPlanner.ForPortal(null) == RecallPlanner.LastPortalUpdate.SetUnconfirmed, "a portal not in the list: unconfirmed");
Atlas atlas = Atlas.Parse(AtlasJson);
var known = new HashSet<int> { RecallPlanner.PortalRecall };
var mem = new RecallMemory();
mem.Set("c", RecallSlot.LastPortal, new RecallSpot { OnMap = true, Ns = 10, Ew = 20, Label = "Somewhere", Unconfirmed = true });
var notes = new List<string>();
var list = RecallPlanner.Build(atlas, known, mem, "c", notes);
Check(!list.Exists(o => o.Name == "Portal Recall"), "an unconfirmed landing isn't used for routes");
Check(notes.Exists(n => n.StartsWith("Portal Recall") && n.Contains("cast Portal Recall once")), "...and says so");
var back = RecallMemory.Parse(mem.Serialize());
Check(back.Get("c", RecallSlot.LastPortal)?.Unconfirmed == true, "unconfirmed survives a save");
mem.Set("c", RecallSlot.LastPortal, new RecallSpot { OnMap = true, Ns = 10, Ew = 20, Label = "Somewhere" });
Check(RecallPlanner.Build(atlas, known, mem, "c", null).Exists(o => o.Name == "Portal Recall"), "confirmed: used again");
Check(RecallMemory.Parse(mem.Serialize()).Get("c", RecallSlot.LastPortal)?.Unconfirmed == false, "a confirmed spot reads back confirmed");
}
private static void RecallMemoryRoundTrip()
{
var mem = new RecallMemory();

View file

@ -22,6 +22,8 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AtlasStore.cs" Link="Linked\AtlasStore.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavReplies.cs" Link="Linked\NavReplies.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\ArrowGuide.cs" Link="Linked\ArrowGuide.cs" />
<!-- One target at a time (TargetSwitchTests). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TargetSwitch.cs" Link="Linked\TargetSwitch.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RecallMemory.cs" Link="Linked\RecallMemory.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RecallPlanner.cs" Link="Linked\RecallPlanner.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavDataConfig.cs" Link="Linked\NavDataConfig.cs" />

View file

@ -0,0 +1,90 @@
using System;
using RynthCore.Plugin.RynthNav;
namespace RynthNav.RouteTests;
// 11-24, a player, on clicking coordinates in chat: "It puts it into the top part of this arrow
// window. The bottom part follows the rynthnav thing though." One target at a time, the newest wins
// (TargetSwitch): what a new arrow, plan or clear does to the route shown and the trip walked.
internal static partial class Program
{
private static void RunTargetSwitch()
{
Run(nameof(TargetSamePlace), TargetSamePlace);
Run(nameof(TargetArrowOverAPlan), TargetArrowOverAPlan);
Run(nameof(TargetArrowWhileWalking), TargetArrowWhileWalking);
Run(nameof(TargetPlanWhileWalking), TargetPlanWhileWalking);
Run(nameof(TargetClear), TargetClear);
}
// Holtburg's lifestone-ish spot, and a place far from it.
private const double HoltNs = 42.08, HoltEw = 33.60, FarNs = -12.3, FarEw = 45.6;
private static HeldTarget Nothing => new(false, "", double.NaN, double.NaN, false, "", double.NaN, double.NaN);
private static HeldTarget PlanTo(double ns, double ew) => new(true, "Holtburg", ns, ew, false, "", double.NaN, double.NaN);
private static HeldTarget WalkingTo(double ns, double ew) => new(true, "Holtburg", ns, ew, true, "Holtburg", ns, ew);
private static void TargetSamePlace()
{
Check(TargetSwitch.SamePlace(HoltNs, HoltEw, HoltNs, HoltEw), "a place is itself");
// Chat coordinates have one decimal: 42.1N, 33.6E is Holtburg's 42.08N, 33.60E.
Check(TargetSwitch.SamePlace(42.1, 33.6, HoltNs, HoltEw), "rounded chat coords are the same place");
Check(!TargetSwitch.SamePlace(42.3, 33.6, HoltNs, HoltEw), "0.2 degrees away is another place (53 u)");
Check(!TargetSwitch.SamePlace(FarNs, FarEw, HoltNs, HoltEw), "far away is another place");
Check(!TargetSwitch.SamePlace(double.NaN, double.NaN, HoltNs, HoltEw), "an unknown spot is never the same place");
Check(!TargetSwitch.SamePlace(HoltNs, HoltEw, double.NaN, 33.6), "nor is a route with no goal known");
}
private static void TargetArrowOverAPlan()
{
// The report: a route was planned to one place, then chat coords elsewhere were clicked.
TargetChange c = TargetSwitch.For(NewTarget.Arrow, PlanTo(HoltNs, HoltEw), FarNs, FarEw);
Check(c.DropPlan, "an arrow elsewhere drops the old plan (no second target under it)");
Check(!c.StopTrip && !c.KeepArrow, "nothing walking: nothing to stop, the arrow moves");
c = TargetSwitch.For(NewTarget.Arrow, PlanTo(HoltNs, HoltEw), 42.1, 33.6);
Check(c == TargetChange.None, "an arrow at the planned place keeps the plan (it is the same target)");
c = TargetSwitch.For(NewTarget.Arrow, Nothing, FarNs, FarEw);
Check(c == TargetChange.None, "an arrow with nothing before it changes nothing else");
// A plan whose goal isn't known (an older plan): another target can't be shown to match it.
c = TargetSwitch.For(NewTarget.Arrow, PlanTo(double.NaN, double.NaN), HoltNs, HoltEw);
Check(c.DropPlan, "a plan with no known goal goes when the arrow is set");
// A plan replaces the shown route by itself: nothing to drop first.
c = TargetSwitch.For(NewTarget.Plan, PlanTo(HoltNs, HoltEw), FarNs, FarEw);
Check(c == TargetChange.None, "a new plan over an old plan: the plan replaces it");
}
private static void TargetArrowWhileWalking()
{
TargetChange c = TargetSwitch.For(NewTarget.Arrow, WalkingTo(HoltNs, HoltEw), FarNs, FarEw);
Check(c.StopTrip, "an arrow elsewhere ends the walk (the newest target wins)");
Check(c.DropPlan, "...and the walk's route goes with it");
Check(!c.KeepArrow, "...and the arrow moves to the new place");
c = TargetSwitch.For(NewTarget.Arrow, WalkingTo(HoltNs, HoltEw), 42.1, 33.6);
Check(!c.StopTrip && !c.DropPlan, "the arrow at the place being walked to keeps the walk");
Check(c.KeepArrow, "...and keeps the trip's own arrow (along its portals)");
}
private static void TargetPlanWhileWalking()
{
TargetChange c = TargetSwitch.For(NewTarget.Plan, WalkingTo(HoltNs, HoltEw), FarNs, FarEw);
Check(c.StopTrip && !c.KeepArrow, "planning elsewhere ends the walk; the arrow follows the plan");
Check(!c.DropPlan, "the plan replaces the walk's route itself");
c = TargetSwitch.For(NewTarget.Plan, WalkingTo(HoltNs, HoltEw), HoltNs, HoltEw);
Check(!c.StopTrip && c.KeepArrow, "planning the place being walked to: the walk and its arrow go on");
}
private static void TargetClear()
{
TargetChange c = TargetSwitch.For(NewTarget.Clear, WalkingTo(HoltNs, HoltEw));
Check(c.StopTrip && c.DropPlan && !c.KeepArrow, "clear while walking: stop, drop the route, arrow off");
c = TargetSwitch.For(NewTarget.Clear, PlanTo(HoltNs, HoltEw));
Check(!c.StopTrip && c.DropPlan, "clear with a plan: the plan goes");
Check(TargetSwitch.For(NewTarget.Clear, Nothing) == TargetChange.None, "clear with nothing: nothing to do");
}
}

View file

@ -31,6 +31,7 @@ internal static partial class Program
Run(nameof(MarkersEmitNearTheCharacter), MarkersEmitNearTheCharacter);
Run(nameof(MarkersNextWaypointAdvances), MarkersNextWaypointAdvances);
Run(nameof(MarkersClearOffTheTrip), MarkersClearOffTheTrip);
Run(nameof(PlanMarkersGoAtTheGoal), PlanMarkersGoAtTheGoal);
}
// ── Helpers ──────────────────────────────────────────────────────────
@ -386,4 +387,27 @@ internal static partial class Program
Check(hubTrip.Covers(0x0007, null, net.Contains), "inside the Town Network on a trip that takes it");
Check(!trip.Covers(0x0007, path, net.Contains), "...but not on one that doesn't");
}
// 2026-11-26 (a player's report): a plan's markers (Route, an Oracle quest pick) stayed on the
// ground after the character walked there; now they go at the goal, as a walked trip's do.
private static void PlanMarkersGoAtTheGoal()
{
var (plan, _) = MarkerTrip();
double arrive = ArrowGuide.DefaultArriveUnits;
Check(PathMarkers.PlanReached(plan, true, 50.4, 50.3, arrive), "standing on a plan's goal: done");
Check(PathMarkers.PlanReached(plan, true, 50.4 + 5 / 240.0, 50.3, arrive), "a few yards off it: done");
Check(!PathMarkers.PlanReached(plan, true, 50.4 + 40 / 240.0, 50.3, arrive), "40 yd off: still shown");
Check(!PathMarkers.PlanReached(plan, true, 10, 10, arrive), "where it starts: still shown");
Check(!PathMarkers.PlanReached(plan, false, 50.4, 50.3, arrive), "no map position (a dungeon, portal space): still shown");
var steps = plan.Steps.ToList();
WorldPt start = WorldPt.FromMap(10, 10, 5.0);
var walked = new PlannedTrip(2, steps, "Far Goal", 50.4, 50.3, true, start, (start.Landblock << 16) | 1, null, live: true);
Check(!PathMarkers.PlanReached(walked, true, 50.4, 50.3, arrive), "a walked trip reports its own arrival (FinishGoto)");
var entrance = new List<RouteStep> { new(50.4, 50.3, true, false, "Dungeon Portal", -1, 0, 0) };
var intoDungeon = Trip(entrance, 10, 10, "A Dungeon", 50.4, 50.3, enterPortal: "Dungeon Portal", enterName: "A Dungeon");
Check(intoDungeon.EndsInEntrance, "the test's plan ends in a dungeon's entrance");
Check(!PathMarkers.PlanReached(intoDungeon, true, 50.4, 50.3, arrive), "a plan into a dungeon goes through its entrance (the landblock check), not at it");
}
}

View file

@ -44,6 +44,7 @@ namespace RynthOracle.Tests
Lists();
QuestLines();
Catalog();
SharedNames();
Servers();
EngineServers();
QuestPackHook();
@ -201,6 +202,34 @@ namespace RynthOracle.Tests
Check(s3.ThrottleSecondsLeft(t6 + 61_000) == 0 && s3.Request(_ => true, t6 + 61_000), "refresh allowed again after the minute");
}
// R-20261124-141130-ca54: the weekly Gladiator Diemos token timer (pickedupmarkerboss10x) read
// "Colosseum Bosses" like 10 other rows, and a search for "Diemos" never found it.
private static void SharedNames()
{
Check(Quest.DetailOf("Pickup timer for Gladiator Diemos Token. In Yanshi.") == "Gladiator Diemos Token", "detail: the prefix and the place come off");
Check(Quest.DetailOf("Timer for how often a player can collect a society stipend. See Master Mhoire.") == "How often a player can collect a society stipend", "detail: 'Timer for' off, capitalised");
Check(Quest.DetailOf("") == "", "no info: no detail");
var cat = new QuestCatalog();
cat.Load(null, null);
if (!cat.UsingBundled) return;
Check(cat.TryGet("pickedupmarkerboss10x", out Quest d) && d.NameShared, "the Diemos timer's name is shared");
Check(d.Label == "Colosseum Bosses: Gladiator Diemos Token", "its row says which: " + d.Label);
Check(d.ShortLabel == "Gladiator Diemos Token", "the Quest Timers window shows the token: " + d.ShortLabel);
Check(d.DisplayName == "Colosseum Bosses", "the display name (chat, details) is unchanged");
Quest? unique = cat.Quests.FirstOrDefault(q => !q.NameShared && q.Name.Length > 0 && !q.IsNew);
Check(unique != null && unique.Label == unique.DisplayName && unique.ShortLabel == unique.DisplayName, "a quest with its own name keeps it: " + unique?.Label);
Check(QuestsTabFinds(cat, "diemos").Contains("pickedupmarkerboss10x"), "the Quests tab's search finds the Diemos timer by its info");
}
/// <summary>The flags the Quests tab's search keeps for <paramref name="search"/> (its rule: every term in flag, label, info or hint).</summary>
private static List<string> QuestsTabFinds(QuestCatalog cat, string search)
{
string[] terms = search.Split(' ', StringSplitOptions.RemoveEmptyEntries);
return cat.Quests.Where(q => terms.All(t => (q.Flag + " " + q.Label + " " + q.Info + " " + q.Hint).Contains(t, StringComparison.OrdinalIgnoreCase)))
.Select(q => q.Flag).ToList();
}
private static void Catalog()
{
var retail = new QuestCatalog();

View file

@ -0,0 +1,249 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Views;
namespace RynthSort.Tests
{
// "Add selected": the selected item's name goes into a pack's rules (rule text, no duplicates,
// which pack already takes the item, nothing selected / not an item), and the window's button.
internal static partial class Program
{
private static SelectedItem ItemSel(SortItem it) => new() { Kind = SelectionKind.Item, Id = it.Id, Name = it.Name, Item = it };
private static void AddSelectedText()
{
Eq(AddSelectedRules.EntryFor("Black Opal"), "Black Opal", "a plain name stays");
Eq(AddSelectedRules.EntryFor("Salvaged Iron (100)"), "Salvaged Iron", "a bag's count is left out");
Eq(AddSelectedRules.EntryFor(" Salvaged Steel (3) "), "Salvaged Steel", "whatever the count, spaces too");
Eq(AddSelectedRules.EntryFor("Sword (Flaming)"), "Sword (Flaming)", "a bracket that isn't a count stays");
Eq(AddSelectedRules.EntryFor("(5)"), "(5)", "a name that is only a count stays");
Eq(AddSelectedRules.EntryFor(new string('x', 100)).Length, SortRule.MaxNameLength, "a long name is cut like a typed one");
Eq(AddSelectedRules.EntryFor(null), "", "no name, no entry");
// The entry matches the item it came from, and the same item at another stack size.
var iron100 = It(1, "Salvaged Iron (100)", ObjectClasses.Salvage);
var iron37 = It(2, "Salvaged Iron (37)", ObjectClasses.Salvage);
SortRule r = SortRule.ForName(AddSelectedRules.EntryFor(iron100.Name), 4);
Check(SortRules.Matches(r, iron100) && SortRules.Matches(r, iron37), "the entry takes the bag and other bags of it");
Eq(SortRules.Describe(r), "name has \"Salvaged Iron\"", "the rule's text");
}
private static void AddSelectedLookup()
{
var inv = Inv(2);
inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
inv.Packs[1].Items.Add(It(20, "Lead Scarab", ObjectClasses.SpellComponent));
inv.Slots.Add(new SortSlot(inv.Packs[0].Id, 24));
inv.Slots.Add(new SortSlot(0x40000F01, 0));
Eq(SelectionLookup.Find(inv, 0, "").Kind, SelectionKind.Nothing, "id 0: nothing selected");
SelectedItem a = SelectionLookup.Find(inv, 10, "x");
Check(a.Kind == SelectionKind.Item && a.Item!.Name == "Black Opal" && a.Name == "Black Opal", "an item in the main pack");
Eq(SelectionLookup.Find(inv, 20, "").Kind, SelectionKind.Item, "an item in a side pack");
SelectedItem pack = SelectionLookup.Find(inv, inv.Packs[0].Id, "Sack");
Check(pack.Kind == SelectionKind.Pack && pack.Name == "Sack", "a pack is not an item");
Eq(SelectionLookup.Find(inv, 0x40000F01, "Foci").Kind, SelectionKind.Pack, "a focus is not an item");
SelectedItem far = SelectionLookup.Find(inv, 0x70000001, "Drudge");
Check(far.Kind == SelectionKind.NotInPacks && far.Name == "Drudge", "an object that isn't in the packs");
}
private static void AddSelectedRefusals()
{
var inv = Inv(3);
var c = Sorter();
c.Planner.Plan(inv, c.Data.Rules, SortScope.Main, true, 0, 0);
List<SortRule> rules = c.Data.Rules;
string before = string.Join("|", rules.Select(SortRules.Describe));
SortView v = c.Planner.View;
foreach (SelectionKind kind in new[] { SelectionKind.Unavailable, SelectionKind.NoInventory, SelectionKind.Nothing, SelectionKind.Pack, SelectionKind.NotInPacks })
{
AddOutcome o = AddSelectedRules.Apply(rules, v, 1, SelectedItem.Of(kind, 7, "Thing"));
Check(o.Status == AddStatus.Refused && o.Rule == null && o.Message.Contains("Nothing was added"), $"{kind}: refused, says nothing was added ({o.Message})");
}
Check(AddSelectedRules.Apply(rules, v, 1, SelectedItem.Of(SelectionKind.Nothing)).Message.Contains("Nothing is selected"), "nothing selected says so");
Check(AddSelectedRules.Apply(rules, v, 1, SelectedItem.Of(SelectionKind.Pack, 7, "Sack")).Message.Contains("is a pack"), "a pack says so");
Check(AddSelectedRules.Apply(rules, v, 1, SelectedItem.Of(SelectionKind.NotInPacks, 7, "Drudge")).Message.Contains("isn't an item in your packs"), "not in the packs says so");
var opal = It(10, "Black Opal", ObjectClasses.Gem);
Eq(AddSelectedRules.Apply(rules, v, 4, ItemSel(opal)).Status, AddStatus.Refused, "a pack you don't carry");
Eq(AddSelectedRules.Apply(rules, v, 0, ItemSel(opal)).Status, AddStatus.Refused, "pack 0");
Eq(AddSelectedRules.Apply(rules, v, 1, ItemSel(It(11, "", ObjectClasses.Gem))).Status, AddStatus.Refused, "an item with no name yet");
Eq(AddSelectedRules.Apply(rules, v, 1, new SelectedItem { Kind = SelectionKind.Item, Id = 5 }).Status, AddStatus.Refused, "an item selection without its item");
Eq(string.Join("|", rules.Select(SortRules.Describe)), before, "no refusal changed a rule");
}
private static void AddSelectedAdds()
{
var inv = Inv(4);
var c = Sorter();
c.Planner.Plan(inv, c.Data.Rules, SortScope.Main, true, 0, 0);
List<SortRule> rules = c.Data.Rules;
SortView v = c.Planner.View;
int count = rules.Count;
// A new rule (pack 4 has none): one name, the pack's id kept.
var tapers = It(30, "Prismatic Taper", ObjectClasses.SpellComponent, stack: 80, max: 100);
AddOutcome o = AddSelectedRules.Apply(rules, v, 4, ItemSel(tapers));
Check(o.Status == AddStatus.Added && o.Rule != null && rules.Contains(o.Rule!), "added as a new rule");
Eq(rules.Count, count + 1, "one rule more");
Check(o.Rule!.Pack == 4 && o.Rule.PackId == inv.Packs[3].Id, "the rule is pack 4's, by id");
Check(o.Rule.Names.Count == 1 && o.Rule.HasName("Prismatic Taper") && o.Rule.Classes.Count == 0, "one name, no class");
Check(o.Message.Contains("Added \"Prismatic Taper\" to pack 4 (Pack 4) as a new rule"), $"says what it added ({o.Message})");
Check(o.Message.Contains("It was going to pack 1") && o.Message.Contains("Now it goes here"), $"says the class rule had it, and that it goes here now ({o.Message})");
Eq(SortRules.RuleFor(rules, tapers)?.Pack, 4, "the name beats the class: it goes to pack 4 now");
// A second item goes into the same rule (it already lists names), not a rule each.
var opal = It(31, "Black Opal", ObjectClasses.Gem);
AddOutcome o2 = AddSelectedRules.Apply(rules, v, 4, ItemSel(opal));
Check(o2.Status == AddStatus.Added && ReferenceEquals(o2.Rule, o.Rule), "the next name joins that rule");
Eq(rules.Count, count + 1, "no rule more");
Check(o.Rule.HasName("Black Opal") && o.Rule.Names.Count == 2, "both names are in it");
Check(!o2.Message.Contains("as a new rule") && o2.Message.Contains("name has \"Black Opal\", name has \"Prismatic Taper\""), $"shows the rule ({o2.Message})");
// A bag of salvage (no rule wants it): its name without the count, no "was going to".
var iron = It(32, "Salvaged Iron (100)", ObjectClasses.Misc);
AddOutcome o3 = AddSelectedRules.Apply(rules, v, 4, ItemSel(iron));
Check(o3.Status == AddStatus.Added && o3.Rule!.HasName("Salvaged Iron") && !o3.Rule.HasName("Salvaged Iron (100)"), "a bag is added without its count");
Check(!o3.Message.Contains("was going to"), "no rule had it before");
Eq(SortRules.RuleFor(rules, It(33, "Salvaged Iron (12)", ObjectClasses.Misc))?.Pack, 4, "another bag of it goes there too");
// A rule that is off isn't joined.
o.Rule.On = false;
AddOutcome o4 = AddSelectedRules.Apply(rules, v, 4, ItemSel(It(34, "Buckler", ObjectClasses.Armor)));
Check(o4.Status == AddStatus.Added && !ReferenceEquals(o4.Rule, o.Rule) && o4.Message.Contains("as a new rule"), "an off rule is left as it is");
o.Rule.On = true;
// Full rules (16 names) aren't joined: a new rule.
foreach (SortRule r in rules.Where(r => r.Pack == 4))
for (int i = 0; r.Names.Count < SortRule.MaxNames; i++) r.AddName("filler " + r.Uid + " " + i);
AddOutcome o5 = AddSelectedRules.Apply(rules, v, 4, ItemSel(It(35, "Ruby", ObjectClasses.Gem)));
Check(o5.Status == AddStatus.Added && o5.Rule != null && o5.Rule.Names.Count == 1 && o5.Message.Contains("as a new rule"), "full rules: a new one");
// At the rule limit the name goes into a rule of the pack that has room; none: refused.
var many = new List<SortRule>();
for (int i = 0; i < SortStore.MaxRules - 1; i++) many.Add(SortRule.ForClass(ObjectClasses.Armor, 1));
var roomy = SortRule.ForClass(ObjectClasses.Food, 2);
many.Add(roomy);
AddOutcome o6 = AddSelectedRules.Apply(many, v, 2, ItemSel(It(36, "Apple", ObjectClasses.Misc)));
Check(o6.Status == AddStatus.Added && ReferenceEquals(o6.Rule, roomy) && roomy.HasName("Apple") && many.Count == SortStore.MaxRules, "at the limit: into the pack's rule with room");
AddOutcome o7 = AddSelectedRules.Apply(many, v, 3, ItemSel(It(37, "Pear", ObjectClasses.Misc)));
Check(o7.Status == AddStatus.Refused && many.Count == SortStore.MaxRules && o7.Message.Contains("no room"), $"at the limit, pack without a rule: refused ({o7.Message})");
}
private static void AddSelectedDuplicates()
{
var inv = Inv(4);
var c = Sorter();
c.Planner.Plan(inv, c.Data.Rules, SortScope.Main, true, 0, 0);
List<SortRule> rules = c.Data.Rules; // components 1, salvage 2, gems/stones/keys 3
SortView v = c.Planner.View;
rules.Add(SortRule.For(4, Array.Empty<int>(), "Opal"));
SortRule four = rules[^1];
string Dump() => string.Join("|", rules.Select(r => SortRules.Describe(r) + ">" + r.Pack + (r.On ? "" : "off")));
string before = Dump();
var blackOpal = It(40, "Black Opal", ObjectClasses.Gem);
AddOutcome same = AddSelectedRules.Apply(rules, v, 4, ItemSel(It(41, "Opal", ObjectClasses.Gem)));
Check(same.Status == AddStatus.AlreadyThere && same.Message.Contains("already in pack 4"), $"the same name: already there ({same.Message})");
AddOutcome inside = AddSelectedRules.Apply(rules, v, 4, ItemSel(blackOpal));
Check(inside.Status == AddStatus.AlreadyThere && inside.Message.Contains("name has \"Opal\""), $"a shorter name in the pack covers it ({inside.Message})");
AddOutcome anyCase = AddSelectedRules.Apply(rules, v, 4, ItemSel(It(42, "OPAL", ObjectClasses.Gem)));
Eq(anyCase.Status, AddStatus.AlreadyThere, "any case");
Eq(Dump(), before, "duplicates change nothing");
// Taken by a class rule of this pack (and no name elsewhere): already goes here.
AddOutcome byClass = AddSelectedRules.Apply(rules, v, 3, ItemSel(It(43, "Ruby", ObjectClasses.Gem)));
Check(byClass.Status == AddStatus.AlreadyThere && byClass.Message.Contains("already goes to pack 3") && byClass.Message.Contains("Gem"), $"a class rule of the pack: already goes there ({byClass.Message})");
Eq(Dump(), before, "and nothing changes");
// A rule that is off doesn't take it, but a second copy isn't added either.
four.On = false;
string beforeOff = Dump();
AddOutcome off = AddSelectedRules.Apply(rules, v, 4, ItemSel(blackOpal));
Check(off.Status == AddStatus.AlreadyThere && off.Message.Contains("turned off"), $"an off rule: say so ({off.Message})");
Eq(Dump(), beforeOff, "nothing changes");
four.On = true;
// Another pack's name rule wins over this pack's covering rule: said, nothing added.
var wins = SortRule.For(1, Array.Empty<int>(), "Black");
rules.Insert(0, wins);
AddOutcome loses = AddSelectedRules.Apply(rules, v, 4, ItemSel(blackOpal));
Check(loses.Status == AddStatus.AlreadyThere && loses.Message.Contains("rule for pack 1") && loses.Message.Contains("wins"), $"already there but another pack's rule wins ({loses.Message})");
rules.Remove(wins);
}
private static void AddSelectedOtherPack()
{
var inv = Inv(4);
var c = Sorter();
c.Planner.Plan(inv, c.Data.Rules, SortScope.Main, true, 0, 0);
List<SortRule> rules = c.Data.Rules;
SortView v = c.Planner.View;
var opal = It(50, "Black Opal", ObjectClasses.Gem); // gems go to pack 3
// Claimed by pack 3's class rule: pressing Add for pack 4 adds there and says pack 3 had it.
AddOutcome o = AddSelectedRules.Apply(rules, v, 4, ItemSel(opal));
Check(o.Status == AddStatus.Added && o.Message.Contains("It was going to pack 3") && o.Message.Contains("Gem"), $"says which pack had it ({o.Message})");
Check(o.Message.Contains("Now it goes here") && SortRules.RuleFor(rules, opal)?.Pack == 4, "and that the new name wins");
Check(rules.Count(r => r.Pack == 3) == 1 && rules.Single(r => r.Pack == 3).HasClass(ObjectClasses.Gem), "pack 3's rule is untouched (nothing moved)");
// Claimed by another pack's NAME rule that comes first: still added, and it says that rule still wins.
var rules2 = new List<SortRule> { SortRule.For(2, Array.Empty<int>(), "Opal") };
AddOutcome o2 = AddSelectedRules.Apply(rules2, v, 4, ItemSel(opal));
Check(o2.Status == AddStatus.Added && o2.Message.Contains("It was going to pack 2") && o2.Message.Contains("still wins"), $"a name rule that wins is said ({o2.Message})");
Eq(SortRules.RuleFor(rules2, opal)?.Pack, 2, "it really does still win");
Check(rules2.Count == 2 && rules2[0].Names.Count == 1 && rules2[1].HasName("Black Opal"), "the other pack's rule is untouched");
// A rule for a pack the character doesn't carry isn't a claim: this pack gets the item.
var rules3 = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 9) };
AddOutcome o3 = AddSelectedRules.Apply(rules3, v, 1, ItemSel(opal));
Check(o3.Status == AddStatus.Added && SortRules.RuleFor(rules3, opal)?.Pack == 1, "a rule for a pack you don't have: this pack gets it");
}
private static void AddSelectedWindow()
{
var (c, panel, host, w) = Window();
var opal = It(10, "Black Opal", ObjectClasses.Gem);
SelectedItem current = SelectedItem.Of(SelectionKind.Nothing);
panel.ReadSelected = () => current;
Draw(w, panel);
Check(BodyText(w).Contains("+ Add selected"), "every pack has an Add selected button");
uint seq = 0;
void Press(string id)
{
Apply(host, Event(1, ++seq, w.Hash, w.KeyOf(id), Click));
Draw(w, panel);
}
int rules = c.Data.Rules.Count;
Press("addsel.40000004");
Eq(c.Data.Rules.Count, rules, "nothing selected: no rule");
Check(BodyText(w).Contains("Nothing is selected"), "and the window says so");
current = ItemSel(opal);
Press("addsel.40000004");
Eq(c.Data.Rules.Count, rules + 1, "an item: a rule");
SortRule added = c.Data.Rules[^1];
Check(added.HasName("Black Opal") && added.PackId == 0x40000004 && ReferenceEquals(panel.Selected, added), "its name, pack 4, editor open");
string body = BodyText(w);
Check(body.Contains("Added \"Black Opal\" to pack 4") && body.Contains("name has \"Black Opal\""), "the window says what was added and shows the rule");
Check(body.IndexOf("Added \"Black Opal\"", StringComparison.Ordinal) > body.IndexOf("Pack 4: ", StringComparison.Ordinal), "the note sits in pack 4's section");
Press("addsel.40000004");
Eq(c.Data.Rules.Count, rules + 1, "again: no duplicate");
Check(BodyText(w).Contains("already in pack 4"), "the window says it is there already");
AddOutcome viaCommand = panel.AddSelected(2);
Check(viaCommand.Status == AddStatus.Added && c.Data.Rules.Any(r => r.Pack == 2 && r.HasName("Black Opal")), "the command's path adds to the pack it names");
Check(viaCommand.Message.Contains("pack 4"), $"and says pack 4 had it ({viaCommand.Message})");
Eq(panel.AddSelected(9).Status, AddStatus.Refused, "a pack that doesn't exist");
// The display list still goes through the engine's parser.
ParseAll(host, "add selected", out _);
}
}
}

View file

@ -0,0 +1,69 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Window;
namespace RynthSort.Tests
{
// RynthSort 0.6.0: an item dragged out of RynthCore's Inventory window (its ImGui payload
// "RYNTH_INV_ITEM") and let go on a pack card gets the same three choices as one dragged inside
// the window. The engine also offers that drop through its drop target, so the window takes the
// first of the two and ignores the echo.
internal static partial class Program
{
private static void DropFromInventory()
{
// One drop, one set of choices.
var once = new DropOnce();
Check(once.Take(42, 10.0), "the first arrival opens the choices");
Check(!once.Take(42, 10.2), "the same item a moment later (the other path) is the same drop");
Check(once.Take(43, 10.3), "another item is another drop");
Check(once.Take(42, 10.4), "back to the first item: a new drop (another item came between)");
Check(!once.Take(42, 11.0) && once.Take(42, 11.5), "the same item again after a second: a new drop");
Check(!once.Take(0, 20.0), "no item, no drop");
once.Reset();
Check(once.Take(42, 11.6), "after a reset anything is new");
// The payload type is the engine's, and RynthAi's Mini Remote takes the same one.
Eq(SortWindow.InvPayloadType, "RYNTH_INV_ITEM", "the payload type");
string root = RepoRoot();
string engine = Path.Combine(root, "..", "RynthCore", "src", "RynthCore.Engine", "ImGui");
string bridge = Path.Combine(engine, "ItemDragBridge.cs"), face = Path.Combine(engine, "Panels", "InventoryFace.cs");
if (File.Exists(bridge) && File.Exists(face))
{
Check(File.ReadAllText(bridge).Contains("PayloadType = \"" + SortWindow.InvPayloadType + "\""), "the engine's drag bridge publishes it");
Check(File.ReadAllText(face).Contains("ItemPayloadType = \"" + SortWindow.InvPayloadType + "\""), "the engine's Inventory publishes it");
}
else Console.WriteLine(" (no RynthCore checkout beside the repo: the engine's payload names weren't compared)");
string remote = Path.Combine(root, "Plugins", "RynthCore.Plugin.RynthAi", "Huds", "MiniRemoteHud.cs");
if (File.Exists(remote)) Check(File.ReadAllText(remote).Contains("ItemPayloadType = \"" + SortWindow.InvPayloadType + "\""), "RynthAi's Mini Remote takes the same payload");
// Dragging the item held it (the player's hands on it). Picking "All gems" on the drop
// lets it go again, so the sort the player asked for moves it.
var w = new FakeWorld();
w.Inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
SortController c = Controller(auto: true);
c.Data.Rules.Clear();
Ticks(c, w, 0, 500);
c.Touch.NoteDrag(10, c.Clock);
Check(c.IsHeld(10), "dragged: left alone");
EditResult r = RuleEdits.SendKind(c.Data.Rules, c.Planner.View, 2, ObjectClasses.Gem);
Check(r.Changed, "All gems to pack 2");
Ticks(c, w, 500, 2000);
Check(w.Inv.Main.Items.Any(i => i.Id == 10), "still held: it waits where it is");
c.Touch.Release(10); // the drop's choice (ISortWindowActions.Unhold)
Ticks(c, w, 2000, 4000);
Check(w.Inv.Packs[1].Items.Any(i => i.Id == 10), "let go: it goes to the pack it was dropped on");
}
/// <summary>The RynthSuite checkout these tests run from (the folder with RynthSuite.slnx).</summary>
private static string RepoRoot()
{
string? d = AppContext.BaseDirectory;
while (d != null && !File.Exists(Path.Combine(d, "RynthSuite.slnx"))) d = Path.GetDirectoryName(d);
return d ?? Directory.GetCurrentDirectory();
}
}
}

View file

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// RynthSort 0.6.0: the activity feed names packs ("Mana Potion -> Satchel"), with the pack's
// number when two carried packs share a name ("-> Satchel (3)"), as the cards' badges show it.
internal static partial class Program
{
private static void FeedPackNames()
{
// The names themselves.
string[] names = { "Sack", "Satchel", "Satchel", "" };
Eq(PackNames.Label(names, 0), "main pack", "0 is the main pack");
Eq(PackNames.Label(names, 1), "Sack", "a name no other pack has");
Eq(PackNames.Label(names, 2), "Satchel (2)", "two packs called Satchel: the number too");
Eq(PackNames.Label(names, 3), "Satchel (3)", "the other one");
Eq(PackNames.Label(names, 4), "pack 4", "a pack the client hasn't named yet");
Eq(PackNames.Label(names, 9), "pack 9", "past the packs carried");
Eq(PackNames.Label(new[] { "Satchel", "satchel " }, 1), "Satchel (1)", "any case, spaces trimmed");
Eq(PackNames.Label((SortInventory?)null, 2), "pack 2", "no packs read yet");
// In the loop: the feed says the pack's name, the log (/rsort status) keeps the number.
var w = new FakeWorld();
SortInventory inv = Inv(3);
inv.Packs[0].Name = "Sack";
inv.Packs[1].Name = "Satchel";
inv.Packs[2].Name = "Satchel";
w.Inv = inv;
inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
inv.Main.Items.Add(It(11, "Prismatic Taper", ObjectClasses.SpellComponent));
SortController c = Controller(auto: true);
c.Data.Rules = SortRules.Defaults(); // components 1, salvage 2, gems 3
Ticks(c, w, 0, 4000);
Check(inv.Packs[2].Items.Any(i => i.Id == 10) && inv.Packs[0].Items.Any(i => i.Id == 11), "both moved");
FeedLine opal = c.Feed.First(f => f.ItemId == 10), taper = c.Feed.First(f => f.ItemId == 11);
Eq(opal.Text, "Black Opal -> Satchel (3)", "two Satchels: the feed adds the number");
Eq(taper.Text, "Prismatic Taper -> Sack", "a unique name: just the name");
Check(c.Log.Contains("Black Opal -> pack 3") && c.Log.Contains("Prismatic Taper -> pack 1"), "the log keeps the numbers");
// Sent from the window, to the main pack.
c.StartSend(10, Me);
Ticks(c, w, 4000, 6000);
Eq(c.Feed[0].Text, "Black Opal -> main pack (you sent it)", "a send names the main pack");
// Put in order inside a pack: one line that counts up, by name.
var ow = new FakeWorld { Can = SortAbilities.All };
SortInventory oi = Inv(1);
oi.Packs[0].Name = "Hide Sack";
oi.Packs[0].OrderKnown = true;
oi.Packs[0].Items.Add(It(1, "Zircon", ObjectClasses.Gem));
oi.Packs[0].Items.Add(It(2, "Amber", ObjectClasses.Gem));
oi.Packs[0].Items.Add(It(3, "Jet", ObjectClasses.Gem));
ow.Inv = oi;
SortController co = Controller(auto: true);
co.Data.Rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) };
Ticks(co, ow, 0, 6000);
Check(co.Feed.Count > 0 && co.Feed[0].Text.EndsWith("put in order in Hide Sack", StringComparison.Ordinal), $"reorders by name ({co.Feed[0].Text})");
Check(co.Log[0].EndsWith("put in order in pack 1", StringComparison.Ordinal), "the log by number");
// The window's sentences use the same names.
SortController cs = ScreenController(inv);
cs.Data.Rules = SortRules.Defaults();
ScreenModel m = Screen(cs);
Check(m.PackName(2) == "Satchel (2)" && m.PackName(3) == "Satchel (3)" && m.PackName(1) == "Sack" && m.PackName(0) == "main pack", "PackName for toasts and rows");
Check(m.Packs[1].Name == "Satchel" && m.Packs[1].Label == "Satchel (2)", "the card keeps its name; its badge shows the number");
SortView view = cs.Planner.View;
EditResult r = RuleEdits.SendKind(cs.Data.Rules, view, 2, ObjectClasses.Plant);
Check(r.Text.Contains("go to Satchel (2)"), $"a toast names the right Satchel ({r.Text})");
}
}
}

View file

@ -0,0 +1,80 @@
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// RynthSort 0.6.1: pack cards fold down to their header and rules (by the pack's object id, saved
// with the character), and "+ Add a rule" takes a typed name (no item needed).
internal static partial class Program
{
private static void FoldedPacks()
{
var s = new SortSettings();
Check(s.CollapsedPacks.Count == 0 && !s.MainCollapsed, "nothing folded for a new character");
Check(s.SetCollapsed(0x500, true) && !s.SetCollapsed(0x500, true) && s.CollapsedPacks.SequenceEqual(new uint[] { 0x500 }), "folded once");
Check(!s.SetCollapsed(0, true), "no pack id: nothing");
Check(s.SetCollapsed(0x500, false) && s.CollapsedPacks.Count == 0 && !s.SetCollapsed(0x500, false), "opened");
for (uint i = 1; i <= SortSettings.MaxCollapsed + 5; i++) s.SetCollapsed(i, true);
Check(s.CollapsedPacks.Count == SortSettings.MaxCollapsed && s.CollapsedPacks[0] == 6 && s.CollapsedPacks[^1] == SortSettings.MaxCollapsed + 5,
"at most 64, the oldest dropped");
// The file: saved and read back; an older file has none; odd values are skipped.
var d = new CharacterSortData();
d.Settings.MainCollapsed = true;
d.Settings.SetCollapsed(0x80001234, true);
d.Settings.SetCollapsed(7, true);
using var doc1 = System.Text.Json.JsonDocument.Parse(SortStore.ToJson(d));
CharacterSortData back = SortStore.Parse(doc1.RootElement);
Check(back.Settings.MainCollapsed && back.Settings.CollapsedPacks.SequenceEqual(new uint[] { 0x80001234, 7 }), "saved and read back");
using var doc0 = System.Text.Json.JsonDocument.Parse("{\"rules\":[],\"settings\":{\"auto\":true}}");
CharacterSortData old = SortStore.Parse(doc0.RootElement);
Check(!old.Settings.MainCollapsed && old.Settings.CollapsedPacks.Count == 0, "an older file: nothing folded");
using var doc2 = System.Text.Json.JsonDocument.Parse("{\"settings\":{\"mainCollapsed\":\"yes\",\"collapsed\":[5,5,-1,\"x\",1.5,9]}}");
CharacterSortData odd = SortStore.Parse(doc2.RootElement);
Check(!odd.Settings.MainCollapsed && odd.Settings.CollapsedPacks.SequenceEqual(new uint[] { 5, 9 }), "odd values skipped");
// The window's model: the folded pack by its id, wherever it sits in the column.
SortInventory inv = Inv(3);
SortController c = ScreenController(inv);
c.Data.Settings.SetCollapsed(inv.Packs[1].Id, true);
ScreenModel m = Screen(c);
Check(!m.Packs[0].Collapsed && m.Packs[1].Collapsed && !m.Packs[2].Collapsed && !m.Main.Collapsed, "pack 2 folded, the rest open");
c.Data.Settings.MainCollapsed = true;
Check(Screen(c).Main.Collapsed, "the main pack folded");
}
private static void TypedNameRule()
{
SortInventory inv = Inv(3);
inv.Main.Items.Add(It(1, "Pyreal Scarab", ObjectClasses.Misc));
inv.Main.Items.Add(It(2, "Copper Scarab", ObjectClasses.Misc));
var rules = new List<SortRule>();
SortView view = SortPreview.Build(inv, rules, default, null).View;
EditResult r = RuleEdits.SendNameText(rules, view, 2, " Scarab ");
Check(r.Changed && rules.Count == 1 && rules[0].HasName("Scarab") && rules[0].PackId == inv.Packs[1].Id, $"a new name rule tied to the pack: {r.Text}");
Check(inv.Main.Items.All(i => SortRules.RuleFor(rules, i) == rules[0]), "both scarabs follow it");
Check(!RuleEdits.SendNameText(rules, view, 2, "scarab").Changed, "again (any case): nothing changes");
Check(!RuleEdits.SendNameText(rules, view, 2, " ").Changed && !RuleEdits.SendNameText(rules, view, 9, "Gem").Changed, "blank, or a pack not carried");
// The same name typed on another pack moves it there; the emptied rule goes.
r = RuleEdits.SendNameText(rules, view, 3, "Scarab");
Check(r.Changed && rules.Count == 1 && Views.SortPanelProxy.Shown(view, rules[0]) == 3, $"moved to pack 3: {r.Text}");
// A second name joins the pack's name rule; too long a name is cut to the limit.
RuleEdits.SendNameText(rules, view, 3, "Pea");
Check(rules.Count == 1 && rules[0].Names.Count == 2, "joins the same rule");
RuleEdits.SendNameText(rules, view, 1, new string('a', SortRule.MaxNameLength + 10));
Check(rules.Any(x => x.Names.Any(n => n.Length == SortRule.MaxNameLength)), "cut to the name limit");
// A name in a rule of this pack that is off: says so, changes nothing.
SortRule here = rules.First(x => x.HasName("Pea"));
here.On = false;
r = RuleEdits.SendNameText(rules, view, 3, "Pea");
Check(!r.Changed && r.Text.Contains("turned off"), $"off: {r.Text}");
}
}
}

View file

@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// RynthSort 0.6.0: a full pack. Items spill into the next pack with the same rule (an overflow
// pack); when there is none, the window's red banner and one chat line per sort say what didn't
// fit and where, and the pack's fill bar turns red. Each pack's own capacity counts.
internal static partial class Program
{
private static void FullPackSpill()
{
// Gems: the Satchel (pack 1, 2 slots) first, the Backpack (pack 2) when it is full.
SortInventory inv = Inv(3);
inv.Packs[0].Name = "Satchel";
inv.Packs[0].Capacity = 2;
inv.Packs[1].Name = "Backpack";
inv.Packs[2].Name = "Sack";
inv.Packs[0].Items.Add(It(1, "Fire Opal", ObjectClasses.Gem));
for (uint i = 10; i < 14; i++) inv.Main.Items.Add(It(i, "Gem " + i, ObjectClasses.Gem));
var rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1), SortRule.ForClass(ObjectClasses.Gem, 2) };
Check(SortRules.RulesFor(rules, inv.Main.Items[0]).Count == 2 && SortRules.RulesFor(rules, inv.Main.Items[0])[0] == rules[0], "both rules match; the first is the gem's own");
var planner = new SortPlanner();
List<SortMove> moves = planner.Plan(inv, rules, SortScope.All, force: true, 0, 0);
Check(moves.Count == 4 && moves[0].DestIndex == 1 && moves.Skip(1).All(m => m.DestIndex == 2), "one gem fills the Satchel, the rest spill into the Backpack");
Check(planner.View.Full.Contains(1) && planner.View.NoFit.Count == 0, "the Satchel is full, nothing left over");
// An item already in the overflow pack stays there while its own pack is full...
foreach (SortMove m in moves) ServerApply(inv, m);
Eq(planner.Plan(inv, rules, SortScope.All, force: true, 0, 0).Count, 0, "spilled items stay put");
// ... and goes to its own pack when that has room again.
inv.Packs[0].Items.RemoveAt(0);
moves = planner.Plan(inv, rules, SortScope.All, force: true, 0, 0);
Check(moves.Count == 1 && moves[0].DestIndex == 1 && moves[0].FromIndex == 2, "a slot free in the Satchel: one gem goes back to it");
Check(planner.Plan(inv, rules, SortScope.Clean, force: true, 0, 0).All(m => m.FromIndex != 2 || m.DestIndex == 1), "Clean doesn't pull overflow gems out to the main pack");
// No overflow with room: the items stay where they are, and the view names them.
SortInventory tight = Inv(2, cap: 1);
tight.Packs[0].Name = "Satchel";
tight.Packs[0].Items.Add(It(1, "Fire Opal", ObjectClasses.Gem));
tight.Packs[1].Items.Add(It(2, "Junk", ObjectClasses.Misc));
tight.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
tight.Main.Items.Add(It(11, "Amethyst", ObjectClasses.Gem));
moves = planner.Plan(tight, rules, SortScope.All, force: true, 0, 0);
Eq(moves.Count, 0, "both packs full: nothing moves");
Check(planner.View.NoFit.Count == 2 && planner.View.NoFit.All(l => l.Pack == 1 && l.From == 0), "two gems didn't fit the Satchel; they stay in the main pack");
Check(planner.View.WaitFull == 2, "counted as waiting on a full pack");
Eq(SortController.NoFitText(planner.View.NoFit, tight), "Satchel is full: Black Opal and Amethyst stay where they are.", "the words");
var one = new List<NoFitLine> { planner.View.NoFit[0] };
Eq(SortController.NoFitText(one, tight), "Satchel is full: Black Opal stays where it is.", "one item");
var many = Enumerable.Range(0, 6).Select(i => new NoFitLine(It((uint)(50 + i), "Gem" + i, ObjectClasses.Gem), 1, 0)).ToList();
Eq(SortController.NoFitText(many, tight), "Satchel is full: Gem0, Gem1, Gem2 and 3 more stay where they are.", "at most three names");
// A stack it can join still takes it in a full pack (as before).
SortInventory stack = Inv(1, cap: 1);
stack.Packs[0].Items.Add(It(1, "Lead Scarab", ObjectClasses.SpellComponent, wcid: 7, stack: 5, max: 100));
stack.Main.Items.Add(It(2, "Lead Scarab", ObjectClasses.SpellComponent, wcid: 7, stack: 3, max: 100));
moves = planner.Plan(stack, SortRules.Defaults(), SortScope.All, force: true, 0, 0);
Check(moves.Count == 1 && moves[0].MergeInto == 1 && planner.View.NoFit.Count == 0, "joins the stack there: not a no-fit");
// Each pack's real capacity: a 30-slot pack with 24 items still takes more.
SortInventory big = Inv(1, cap: 30);
Fill(big.Packs[0], 24, 100);
big.Main.Items.Add(It(5, "Black Opal", ObjectClasses.Gem));
moves = planner.Plan(big, new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) }, SortScope.All, force: true, 0, 0);
Check(moves.Count == 1 && planner.View.NoFit.Count == 0, "24 of 30: room");
}
private static void FullPackWarnings()
{
// In the loop: one chat line when items stop fitting, not one per tick.
var w = new FakeWorld { Inv = Inv(1, cap: 1) };
w.Inv.Packs[0].Name = "Satchel";
w.Inv.Packs[0].Items.Add(It(1, "Fire Opal", ObjectClasses.Gem));
w.Inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
SortController c = Controller(auto: true);
c.Data.Rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) };
var said = new List<string>();
c.Warn = said.Add;
Ticks(c, w, 0, 5000);
Check(said.Count == 1 && said[0] == "Satchel is full: Black Opal stays where it is.", $"one line ({string.Join(" | ", said)})");
Check(c.Feed.Any(f => f.Text == said[0]), "and in the feed");
Ticks(c, w, 5000, 15_000);
Eq(said.Count, 1, "ten seconds later: still one line");
w.Inv.Main.Items.Add(It(11, "Amethyst", ObjectClasses.Gem));
Ticks(c, w, 15_000, 18_000);
Check(said.Count == 2 && said[1] == "Satchel is full: Black Opal and Amethyst stay where they are.", "a new item that doesn't fit: a new line naming them all");
// Sort now says it once, at its end.
c.StartJob(SortScope.All);
Ticks(c, w, 18_000, 20_000);
Eq(said.Count, 3, "Sort now: one line when it ends");
// Room again: forgotten, so it is said again if it stops fitting.
w.Inv.Packs[0].Capacity = 3;
Ticks(c, w, 20_000, 24_000);
Check(w.Inv.Packs[0].Items.Count == 3, "room: both gems went");
w.Inv.Main.Items.Add(It(12, "Jet", ObjectClasses.Gem));
Ticks(c, w, 24_000, 27_000);
Check(said.Count == 4 && said[3].Contains("Jet"), "full again: a new line");
// Auto-sort off: nothing sorts, nothing said.
c.SetAuto(false);
w.Inv.Main.Items.Add(It(13, "Agate", ObjectClasses.Gem));
Ticks(c, w, 27_000, 32_000);
Eq(said.Count, 4, "off: no chat");
// The window: the red banner, the card's line and its red bar, the main pack's bar.
SortInventory inv = Inv(2, cap: 2);
inv.Packs[0].Name = "Satchel";
inv.Packs[1].Name = "Backpack";
inv.Packs[0].Items.Add(It(1, "Fire Opal", ObjectClasses.Gem));
inv.Packs[0].Items.Add(It(2, "Jet", ObjectClasses.Gem));
inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
SortController cs = ScreenController(inv);
cs.Data.Rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) };
ScreenModel m = Screen(cs);
Check(m.NoFit.Length == 1 && m.NoFit[0] == "Satchel is full: Black Opal stays where it is.", $"the banner ({string.Join(" | ", m.NoFit)})");
Check(m.Packs[0].Full && !m.Packs[1].Full && m.Packs[0].Warnings.Contains("Full: 1 item for it waits where it is."), "the Satchel's bar is red and its card says so");
Check(!m.Main.Full, "the main pack isn't full");
// An overflow pack: the banner goes, the card says the rest go on, the chip says overflow.
EditResult r = RuleEdits.AddOverflow(cs.Data.Rules, cs.Planner.View, 2, ObjectClasses.Gem);
Check(r.Changed && r.Text == "Gems go to Satchel, and to Backpack when it is full. Nothing has moved yet.", $"overflow ({r.Text})");
Check(cs.Data.Rules.Count == 2 && cs.Data.Rules[1].HasClass(ObjectClasses.Gem), "a new rule after the first");
Check(!RuleEdits.AddOverflow(cs.Data.Rules, cs.Planner.View, 2, ObjectClasses.Gem).Changed, "again: nothing");
Check(!RuleEdits.AddOverflow(cs.Data.Rules, cs.Planner.View, 1, ObjectClasses.Gem).Changed, "the pack that has it can't be its own overflow");
Check(!RuleEdits.AddOverflow(cs.Data.Rules, cs.Planner.View, 2, ObjectClasses.Scroll).Changed, "a kind no pack has: add it first");
m = Screen(cs);
Check(m.NoFit.Length == 0 && m.Packs[0].Warnings.Contains("Full: the next pack with the same rule takes the rest."), "spilling: no banner");
ChipModel chip = m.Packs[1].Chips.Single();
Check(chip.Overflow && chip.Label == "Gems (overflow)" && chip.Tip.StartsWith("Gems come here when Satchel is full", StringComparison.Ordinal), "the overflow chip");
Check(!m.Packs[0].Chips.Single().Overflow, "the Satchel's chip is the kind's own");
Check(m.Moves.Length == 1 && m.Moves[0].Right == "Backpack", "Next moves: to the Backpack");
Eq(m.KindChoices.Single(k => k.Cls == ObjectClasses.Gem).InPack, 1, "the picker still names the Satchel as the kind's pack");
// A full main pack: red too.
SortInventory fullMain = Inv(1, mainCap: 2);
fullMain.Main.Items.Add(It(1, "A", ObjectClasses.Misc));
fullMain.Main.Items.Add(It(2, "B", ObjectClasses.Misc));
Check(Screen(ScreenController(fullMain)).Main.Full, "a full main pack's bar is red");
}
}
}

View file

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// RynthSort 0.6.0: "Keep handy items at the front of the main pack". Healing kits, mana stones,
// food, potions and elixirs (the player's list) sit in the main pack's first slots. A move to a
// slot is the engine's PutItemInContainer (plugin API v80), the same move that puts items in
// order inside packs; without it the option does nothing. Items left alone are never moved for it.
internal static partial class Program
{
private static SortInventory HandyPack(params (string Name, int Cls)[] items)
{
SortInventory inv = Inv(2);
inv.Main.OrderKnown = true;
uint id = 1;
foreach (var (n, cls) in items) inv.Main.Items.Add(It(id++, n, cls));
return inv;
}
private static string Names(SortPack p) => string.Join(",", p.Items.Select(i => i.Name));
private static Func<SortItem, bool> DefaultHandy() =>
it => HandyItems.Matches(HandyItems.DefaultClasses, HandyItems.DefaultNames, it);
/// <summary>Plans and applies moves as the server would until none is left; returns how many.</summary>
private static int RunOut(SortInventory inv, List<SortRule> rules, PlanOptions opt, Func<uint, bool>? held = null, int max = 200)
{
var planner = new SortPlanner { Held = held };
int n = 0;
for (; n < max; n++)
{
List<SortMove> moves = planner.Plan(inv, rules, SortScope.All, force: true, 0, 0, opt);
if (moves.Count == 0) return n;
ServerApply(inv, moves[0]);
}
return n;
}
private static void HandyFront()
{
Func<SortItem, bool> handy = DefaultHandy();
Check(handy(It(1, "Treated Healing Kit", ObjectClasses.HealingKit)) && handy(It(2, "Mana Stone", ObjectClasses.ManaStone))
&& handy(It(3, "Peppermint Stick", ObjectClasses.Food)), "kits, mana stones and food by kind");
Check(handy(It(4, "Mana Potion", ObjectClasses.Misc)) && handy(It(5, "health elixir", ObjectClasses.Unknown)), "potions and elixirs by name, any case");
Check(!handy(It(6, "Black Opal", ObjectClasses.Gem)) && !handy(It(7, "", ObjectClasses.Misc)), "gems aren't handy; a nameless misc item isn't either");
Eq(HandyItems.Describe(HandyItems.DefaultClasses, HandyItems.DefaultNames), "healing kits, mana stones, food, potions and elixirs", "the list in words");
// The front run, and one move per handy item behind it (ordering off: the rest keep their order).
SortInventory inv = HandyPack(("Black Opal", ObjectClasses.Gem), ("Amuli Coat", ObjectClasses.Armor), ("Healing Kit", ObjectClasses.HealingKit),
("Zircon", ObjectClasses.Gem), ("Mana Potion", ObjectClasses.Misc), ("Celdon Girth", ObjectClasses.Armor));
Func<SortItem, bool> any = _ => true;
Eq(PackOrder.FrontRun(inv.Main.Items, handy, any), 0, "nothing handy in front yet");
Eq(PackOrder.HandyBehind(inv.Main.Items, handy, any), 2, "two handy items behind");
Check(PackOrder.FrontMove(inv.Main.Items, handy, any, out SortItem first, out int at) && first.Name == "Healing Kit" && at == 0, "the first handy item goes to slot 0");
var opt = new PlanOptions { Place = true, Merge = true, Handy = handy };
int moves = RunOut(inv, new List<SortRule>(), opt);
Eq(Names(inv.Main), "Healing Kit,Mana Potion,Black Opal,Amuli Coat,Zircon,Celdon Girth", "handy in front, the rest as they were");
Eq(moves, 2, "one move per handy item");
// Ordering on: the whole main pack in order, handy items first.
SortInventory ord = HandyPack(("Zircon", ObjectClasses.Gem), ("Mana Potion", ObjectClasses.Misc), ("Amber", ObjectClasses.Gem),
("Healing Kit", ObjectClasses.HealingKit), ("Apple", ObjectClasses.Food));
RunOut(ord, new List<SortRule>(), new PlanOptions { Order = true, Place = true, Merge = true, Handy = handy });
Eq(Names(ord.Main), "Apple,Healing Kit,Mana Potion,Amber,Zircon", "handy first (A-Z), then the rest A-Z");
Eq(RunOut(ord, new List<SortRule>(), new PlanOptions { Order = true, Place = true, Merge = true, Handy = handy }), 0, "then it stays still");
// Left alone: a held item is never moved for it, and handy items go after a held one in front.
SortInventory hold = HandyPack(("Black Opal", ObjectClasses.Gem), ("Zircon", ObjectClasses.Gem), ("Healing Kit", ObjectClasses.HealingKit),
("Mana Stone", ObjectClasses.ManaStone));
uint opalId = hold.Main.Items[0].Id, stoneId = hold.Main.Items[3].Id;
RunOut(hold, new List<SortRule>(), opt, held: id => id == opalId || id == stoneId);
Eq(Names(hold.Main), "Black Opal,Healing Kit,Zircon,Mana Stone", "the opal (held) keeps slot 0; the kit goes after it; the held stone stays");
// No moves to a slot (an engine before API v80): nothing happens for it.
SortInventory old = HandyPack(("Black Opal", ObjectClasses.Gem), ("Healing Kit", ObjectClasses.HealingKit));
Eq(RunOut(old, new List<SortRule>(), new PlanOptions { Merge = true, Handy = handy }), 0, "no slot moves: nothing moves");
SortInventory unknown = HandyPack(("Black Opal", ObjectClasses.Gem), ("Healing Kit", ObjectClasses.HealingKit));
unknown.Main.OrderKnown = false;
Eq(RunOut(unknown, new List<SortRule>(), opt), 0, "the main pack's order not known: nothing moves");
// A kind a side pack's rule names goes to that pack instead.
SortInventory ruled = HandyPack(("Black Opal", ObjectClasses.Gem), ("Healing Kit", ObjectClasses.HealingKit), ("Mana Stone", ObjectClasses.ManaStone));
RunOut(ruled, new List<SortRule> { SortRule.ForClass(ObjectClasses.HealingKit, 2) }, opt);
Check(ruled.Packs[1].Items.Any(i => i.Name == "Healing Kit") && Names(ruled.Main) == "Mana Stone,Black Opal", $"the kit to its pack, the stone to the front ({Names(ruled.Main)})");
// An item coming back to the main pack (Clean) lands in the handy run when it is handy.
SortInventory back = HandyPack(("Healing Kit", ObjectClasses.HealingKit), ("Black Opal", ObjectClasses.Gem));
back.Packs[0].Items.Add(It(50, "Mana Potion", ObjectClasses.Misc));
var cp = new SortPlanner();
List<SortMove> clean = cp.Plan(back, new List<SortRule>(), SortScope.Clean, force: true, 0, 0, opt);
Check(clean.Count == 1 && clean[0].Item.Id == 50 && clean[0].DestIndex == 0 && clean[0].Placement == 1, "a potion cleaned out of a pack goes right after the kit");
// New loot settling: the main pack waits (as for ordering).
SortInventory fresh = HandyPack(("Black Opal", ObjectClasses.Gem), ("Healing Kit", ObjectClasses.HealingKit));
var fp = new SortPlanner();
Eq(fp.Plan(fresh, new List<SortRule>(), SortScope.All, force: false, 0, 5000, opt).Count, 0, "items still settling: the main pack isn't touched");
Eq(fp.Plan(fresh, new List<SortRule>(), SortScope.All, force: false, 6000, 5000, opt).Count, 1, "settled: the kit moves");
Check(fp.View.Handy && fp.View.HandyBehind == 1, "the view counts what is left");
}
private static void HandyLoopAndStore()
{
// In the loop: auto-sort brings them to the front, then stays still; off by default.
var w = new FakeWorld { Can = SortAbilities.All };
w.Inv.Main.OrderKnown = true;
w.Inv.Main.Items.Add(It(1, "Black Opal Ring", ObjectClasses.Jewelry));
w.Inv.Main.Items.Add(It(2, "Celdon Girth", ObjectClasses.Armor));
w.Inv.Main.Items.Add(It(3, "Treated Healing Kit", ObjectClasses.HealingKit));
w.Inv.Main.Items.Add(It(4, "Mana Potion", ObjectClasses.Misc));
SortController c = Controller(auto: true);
c.Data.Rules.Clear();
c.Data.Settings.OrderInPacks = false;
Check(!c.Data.Settings.HandyFront, "off for a new character");
Ticks(c, w, 0, 4000);
Eq(w.Sent.Count, 0, "off: nothing moves");
c.Data.Settings.HandyFront = true;
Ticks(c, w, 4000, 12_000);
Eq(Names(w.Inv.Main), "Treated Healing Kit,Mana Potion,Black Opal Ring,Celdon Girth", "on: the kit and the potion in front");
int sent = w.Sent.Count;
Ticks(c, w, 12_000, 20_000);
Eq(w.Sent.Count, sent, "then nothing more moves");
Check(w.Sent.All(m => m.Kind == MoveKind.Reorder && m.Dest.Id == Me), "only moves inside the main pack");
// The player picks up the potion (selects it): it stays where they put it.
SortItem potion = w.Inv.Main.Items.First(i => i.Id == 4);
PackOrder.Apply(w.Inv.Main.Items, potion, 3);
c.Touch.NoteSelected(4, c.Clock);
Ticks(c, w, 20_000, 26_000);
Eq(w.Inv.Main.Items.FindIndex(i => i.Id == 4), 3, "held: not moved back to the front");
// The window: the switch, the list as chips, the picker, the note under the main pack.
SortController cs = ScreenController(w.Inv);
cs.Tick(new FakeWorld { Inv = w.Inv, Can = SortAbilities.All }, 100);
cs.Data.Settings.HandyFront = true;
ScreenModel m = Screen(cs);
Check(m.Settings.HandyOn && m.Settings.HandyChips.Length == 5, "five chips: three kinds, two names");
Check(m.Settings.HandyChips[0].Label == "Healing kits" && m.Settings.HandyChips[3].IsName && m.Settings.HandyChips[3].Label == "named \"Potion\"", "kinds, then names");
Check(!m.Settings.HandyChoices.Any(k => k.Cls == ObjectClasses.ManaStone) && m.Settings.HandyChoices.Any(k => k.Cls == ObjectClasses.Gem), "the picker offers what isn't on the list");
Eq(m.Main.Handy, "Handy at the front: healing kits, mana stones, food, potions and elixirs.", "the main pack says so");
cs.Data.Settings.HandyFront = false;
Eq(Screen(cs).Main.Handy, "", "off: nothing said");
// Editing the list.
var s = new SortSettings();
Check(HandyItems.AddClass(s, ObjectClasses.Scroll) && !HandyItems.AddClass(s, ObjectClasses.Scroll) && !HandyItems.AddClass(s, ObjectClasses.Monster),
"a kind once; only kinds the picker offers");
Check(HandyItems.AddName(s, " Draught ") && s.HandyNames.Contains("Draught") && !HandyItems.AddName(s, "draught") && !HandyItems.AddName(s, " "),
"a name trimmed, once (any case), never blank");
Check(HandyItems.RemoveName(s, "DRAUGHT") && !s.HandyNames.Contains("Draught"), "taken off, any case");
s.HandyClasses.Clear();
s.HandyNames.Clear();
s.HandyFront = true;
Check(HandyItems.For(s) == null, "an empty list: off");
// The file: off and the default list for files from before it; kept as set.
using var doc0 = System.Text.Json.JsonDocument.Parse("{\"rules\":[],\"settings\":{\"auto\":true,\"holdMin\":3}}");
CharacterSortData old = SortStore.Parse(doc0.RootElement);
Check(!old.Settings.HandyFront && old.Settings.HandyClasses.SequenceEqual(HandyItems.DefaultClasses) && old.Settings.HandyNames.SequenceEqual(HandyItems.DefaultNames),
"an older file: off, with the default list");
var d = new CharacterSortData();
d.Settings.HandyFront = true;
d.Settings.HandyClasses = new List<int> { ObjectClasses.HealingKit, ObjectClasses.Scroll };
d.Settings.HandyNames = new List<string> { "Elixir" };
using var doc1 = System.Text.Json.JsonDocument.Parse(SortStore.ToJson(d));
CharacterSortData back = SortStore.Parse(doc1.RootElement);
Check(back.Settings.HandyFront && back.Settings.HandyClasses.SequenceEqual(new[] { ObjectClasses.HealingKit, ObjectClasses.Scroll })
&& back.Settings.HandyNames.SequenceEqual(new[] { "Elixir" }), "saved and read back");
using var doc2 = System.Text.Json.JsonDocument.Parse("{\"settings\":{\"handyFront\":\"yes\",\"handyClasses\":[29,29,-4,\"x\",5],\"handyNames\":[\"\",7,\"Tonic\"]}}");
CharacterSortData odd = SortStore.Parse(doc2.RootElement);
Check(!odd.Settings.HandyFront && odd.Settings.HandyClasses.SequenceEqual(new[] { ObjectClasses.HealingKit }) && odd.Settings.HandyNames.SequenceEqual(new[] { "Tonic" }),
"odd values: off, each kind once, only real kinds and names");
}
}
}

View file

@ -0,0 +1,259 @@
using System;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// "Leave my items alone" (#rynth-issues "The bag sort feature is lacking in UX": it moves the items
// you're working with): what counts as the player touching an item, that sorting leaves those
// items where they are for the hold time, and the setting in the file.
internal static partial class Program
{
private const long Min = 60_000;
private static void HoldWatch()
{
SortInventory inv = Inv(2);
SortItem taper = It(10, "Prismatic Taper", ObjectClasses.SpellComponent);
SortItem opal = It(11, "Black Opal", ObjectClasses.Gem);
inv.Main.Items.Add(taper);
inv.Packs[0].Items.Add(opal);
inv.Worn.Add(20);
var t = new TouchWatch();
t.Observe(inv, 0);
Check(!t.IsHeld(10, 0, 3 * Min) && !t.IsHeld(11, 0, 3 * Min), "the first read only learns where things are");
// The player moves the opal to pack 2: held, as moved, for the hold time.
inv.Packs[0].Items.Remove(opal);
inv.Packs[1].Items.Add(opal);
t.Observe(inv, 1000);
Check(t.TryGetHeld(11, 1000, 3 * Min, out long at, out TouchKind kind) && at == 1000 && kind == TouchKind.Moved, "a pack change RynthSort didn't make: held, as moved");
Check(t.IsHeld(11, 1000 + 3 * Min - 1, 3 * Min) && !t.IsHeld(11, 1000 + 3 * Min, 3 * Min), "until the hold time is up");
Check(!t.IsHeld(11, 2000, 0), "a hold of 0 holds nothing");
// RynthSort's own move isn't the player's.
t.NoteOwnMove(10, inv.Packs[0].Id, 2000);
inv.Main.Items.Remove(taper);
inv.Packs[0].Items.Add(taper);
t.Observe(inv, 2500);
Check(!t.IsHeld(10, 2500, 3 * Min), "RynthSort's own move: not held");
// ... but the same item moved again by the player is.
inv.Packs[0].Items.Remove(taper);
inv.Main.Items.Add(taper);
t.Observe(inv, 3000);
Check(t.IsHeld(10, 3000, 3 * Min), "moved back by the player: held");
// An own move to somewhere else doesn't cover a move the player made.
t.ReleaseAll();
Check(!t.IsHeld(10, 3000, 3 * Min) && !t.IsHeld(11, 3000, 3 * Min), "Sort them too: every hold dropped");
t.NoteOwnMove(10, inv.Packs[1].Id, 3100);
inv.Main.Items.Remove(taper);
inv.Packs[0].Items.Add(taper);
t.Observe(inv, 3200);
Check(t.IsHeld(10, 3200, 3 * Min), "RynthSort sent it to pack 2 but it is in pack 1: the player's");
// Taken off: worn at the last read, in a pack now.
inv.Worn.Remove(20);
SortItem shield = It(20, "Shield", ObjectClasses.Armor);
inv.Main.Items.Add(shield);
t.Observe(inv, 4000);
Check(t.TryGetHeld(20, 4000, 3 * Min, out _, out kind) && kind == TouchKind.TakenOff, "taken off: held");
// New items: only just after a drop (picked up, a stack split off).
inv.Main.Items.Add(It(30, "Pyreal Mote", ObjectClasses.Misc));
t.Observe(inv, 5000);
Check(!t.IsHeld(30, 5000, 3 * Min), "new loot is not the player's");
t.NoteDrop(10, 6000);
Check(t.TryGetHeld(10, 6000, 3 * Min, out _, out kind) && kind == TouchKind.Dragged, "the dropped item itself: held");
inv.Main.Items.Add(It(31, "Prismatic Taper", ObjectClasses.SpellComponent, stack: 5, max: 100));
t.Observe(inv, 6500);
Check(t.TryGetHeld(31, 6500, 3 * Min, out _, out kind) && kind == TouchKind.PickedUp, "new just after a drop (a split stack): held");
inv.Main.Items.Add(It(32, "Prismatic Taper", ObjectClasses.SpellComponent));
t.Observe(inv, 6000 + TouchWatch.DropWindowMs + 1);
Check(!t.IsHeld(32, 6000 + TouchWatch.DropWindowMs + 1, 3 * Min), "new well after the drop: not held");
// Drags and selections.
t.NoteDrag(11, 7000);
Check(t.TryGetHeld(11, 7000, 3 * Min, out _, out kind) && kind == TouchKind.Dragged, "dragged: held");
t.NoteSelected(30, 8000);
Check(t.TryGetHeld(30, 8000, 3 * Min, out at, out kind) && kind == TouchKind.Selected && at == 8000, "selected: held");
t.NoteSelected(30, 9000);
Check(t.TryGetHeld(30, 9000, 3 * Min, out at, out _) && at == 9000, "still selected: the hold counts from the latest tick");
t.NoteSelected(0x7000_0001, 9000);
t.NoteSelected(20 + 1000, 9000);
Eq(t.HeldCount(9000, 3 * Min), 5, "a selected monster or unknown object isn't counted");
t.NoteSelected(inv.Packs[0].Id, 9000);
Check(!t.IsHeld(inv.Packs[0].Id, 9000, 3 * Min), "a selected pack isn't an item");
// A pack missing from a read for a moment: its items are remembered.
SortItem salvage = It(40, "Salvaged Iron", ObjectClasses.Salvage);
inv.Packs[1].Items.Add(salvage);
t.Observe(inv, 10_000);
inv.Packs[1].Items.Remove(salvage);
t.Observe(inv, 11_000);
inv.Main.Items.Add(salvage);
t.Observe(inv, 12_000);
Check(t.TryGetHeld(40, 12_000, 3 * Min, out _, out kind) && kind == TouchKind.Moved, "missing from one read, then in another pack: moved");
// After a reset the next read only learns again.
t.Reset();
inv.Main.Items.Remove(salvage);
inv.Packs[1].Items.Add(salvage);
t.Observe(inv, 13_000);
Check(!t.IsHeld(40, 13_000, 3 * Min), "after a reset: learning again");
Eq(TouchWatch.Words(TouchKind.TakenOff), "you took it off", "plain words");
}
private static void HoldPlan()
{
SortInventory inv = Inv(3);
inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
inv.Main.Items.Add(It(11, "Lead Scarab", ObjectClasses.SpellComponent));
inv.Packs[1].Items.Add(It(12, "Black Opal", ObjectClasses.Gem)); // gems go to pack 3
inv.Packs[2].Items.Add(It(13, "Junk", ObjectClasses.Misc)); // no rule: Clean evicts it
var held = new System.Collections.Generic.HashSet<uint> { 10, 12, 13 };
var p = new SortPlanner { Held = id => held.Contains(id) };
var moves = p.Plan(inv, Defaults, SortScope.All, force: true, 0, 0);
Check(moves.Count == 1 && moves[0].Item.Id == 11, "only the scarab moves: the taper and the opal are held");
Eq(moves[0].FromIndex, 0, "a move says where it came from (main pack)");
Eq(moves[0].FromId, Me, "and its pack's object");
Check(p.View.Held.Count == 2 && p.View.Held.Any(h => h.Item.Id == 10 && h.From == 0 && h.To == 1)
&& p.View.Held.Any(h => h.Item.Id == 12 && h.From == 2 && h.To == 3), "held items listed with where they'd go");
moves = p.Plan(inv, Defaults, SortScope.Clean, force: true, 0, 0);
Check(moves.All(m => m.Item.Id != 13) && p.View.Held.Any(h => h.Item.Id == 13 && h.To == 0), "Clean leaves a held stray where it is too");
// Not held any more: they move.
held.Clear();
moves = p.Plan(inv, Defaults, SortScope.All, force: true, 0, 0);
Eq(moves.Count, 3, "nothing held: all three move");
Eq(p.View.Held.Count, 0, "and none are listed");
// Stacks: a held stack is never joined into (or joined from), another one still is.
SortInventory st = Inv(1);
st.Packs[0].Items.Add(It(20, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 7, stack: 50, max: 100));
st.Packs[0].Items.Add(It(21, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 7, stack: 5, max: 100));
st.Packs[0].Items.Add(It(22, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 7, stack: 3, max: 100));
held.Add(20);
moves = p.Plan(st, Defaults, SortScope.All, force: true, 0, 0, PlanOptions.Full);
Check(moves.Count == 1 && moves[0].Kind == MoveKind.Stack && moves[0].Item.Id == 22 && moves[0].MergeInto == 21,
"the held big stack is left alone: the two others join");
held.Add(21);
moves = p.Plan(st, Defaults, SortScope.All, force: true, 0, 0, PlanOptions.Full);
Check(moves.All(m => m.Kind != MoveKind.Stack), "two of three held: nothing to join");
// A new item isn't joined into a held stack in its pack either.
Eq(SortPlanner.StackTarget(It(23, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 7, stack: 1, max: 100), st.Packs[0], id => held.Contains(id)), 22u,
"a route joins a stack the player isn't holding");
// Order: a held item isn't put in order (the others are, around it).
SortInventory ord = Inv(1);
ord.Packs[0].Items.Add(It(30, "Zircon", ObjectClasses.Gem));
ord.Packs[0].Items.Add(It(31, "Amber", ObjectClasses.Gem));
ord.Packs[0].OrderKnown = true;
held.Clear();
held.Add(30);
var rules = new System.Collections.Generic.List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) };
moves = p.Plan(ord, rules, SortScope.All, force: true, 0, 0, PlanOptions.Full);
Check(moves.Count == 1 && moves[0].Kind == MoveKind.Reorder && moves[0].Item.Id == 31 && moves[0].Placement == 0, "Amber goes before the held Zircon, Zircon stays");
held.Clear();
held.Add(31);
moves = p.Plan(ord, rules, SortScope.All, force: true, 0, 0, PlanOptions.Full);
Eq(moves.Count, 0, "the item out of place is held: that pack waits for the hold to end");
// Unpack ignores holds (the player asked for everything).
held.Add(12);
Check(p.PlanUnpack(inv, null, 0).Any(m => m.Item.Id == 12), "Unpack moves a held item too");
}
private static void HoldLoop()
{
// Components go to pack 1; the player takes a taper out to the main pack to use it.
var w = new FakeWorld();
SortItem taper = It(10, "Prismatic Taper", ObjectClasses.SpellComponent);
w.Inv.Packs[0].Items.Add(taper);
SortController c = Controller(settleSec: 5);
c.Data.Rules = SortRules.Defaults();
Ticks(c, w, 0, 2000);
Eq(w.Sent.Count, 0, "in its pack: nothing to do");
w.Inv.Packs[0].Items.Remove(taper);
w.Inv.Main.Items.Add(taper);
Ticks(c, w, 2000, 60_000);
Eq(w.Sent.Count, 0, "taken out by the player: left in the main pack");
Check(c.Planner.View.Held.Any(h => h.Item.Id == 10 && h.To == 1), "the window can say it is left alone and where it would go");
Check(c.IsHeld(10), "the controller says it is held");
c.StartJob(SortScope.All);
Ticks(c, w, 60_000, 70_000);
Eq(w.Sent.Count, 0, "Sort now leaves it alone too");
Check(c.Job == null, "and finishes");
// After the hold (3 minutes by default) auto-sort takes it back.
Ticks(c, w, 70_000, 2000 + 3 * Min + 8000);
Check(w.Sent.Count == 1 && w.Sent[0].Item.Id == 10 && w.Sent[0].DestIndex == 1, "after the hold it goes back to its pack");
Check(!c.IsHeld(10), "no longer held");
// RynthSort's own move back didn't make it held.
long t0 = 2000 + 3 * Min + 8000;
Ticks(c, w, t0, t0 + 5000);
Check(!c.IsHeld(10), "RynthSort's own move doesn't count as the player's");
// A selected item in the main pack (just looted) stays while selected.
SortItem scarab = It(11, "Lead Scarab", ObjectClasses.SpellComponent);
w.Inv.Main.Items.Add(scarab);
long t1 = t0 + 5000;
for (long t = t1; t <= t1 + 30_000; t += 16)
{
c.Touch.NoteSelected(11, t);
c.Tick(w, t);
}
Eq(w.Sent.Count(m => m.Item.Id == 11), 0, "selected: not moved");
// "Sort them too".
c.Touch.ReleaseAll();
Ticks(c, w, t1 + 30_016, t1 + 40_000);
Eq(w.Sent.Count(m => m.Item.Id == 11), 1, "released: it moves");
// Hold 0 = off: a moved item goes back at once.
c.Data.Settings.HoldMin = 0;
SortItem moved = w.Inv.Packs[0].Items.First(i => i.Id == 11);
w.Inv.Packs[0].Items.Remove(moved);
w.Inv.Main.Items.Add(moved);
int before = w.Sent.Count;
Ticks(c, w, t1 + 40_000, t1 + 50_000);
Check(w.Sent.Count == before + 1 && w.Sent[^1].Item.Id == 11, "hold off: moved straight back");
}
private static void HoldStore()
{
SortStore st = TempStore("hold");
CharacterSortData d = st.Load("S", "A", out _);
Eq(d.Settings.HoldMin, SortSettings.HoldMinDefault, "a new character: the default hold");
Eq(SortSettings.HoldMinDefault, 3, "three minutes");
d.Settings.HoldMin = 7;
st.Save("S", "A", d);
Check(File.ReadAllText(st.PathFor("S", "A")).Contains("\"holdMin\": 7"), "written");
Eq(st.Load("S", "A", out _).Settings.HoldMin, 7, "read back");
// A file from before the setting: the default. Out of range: clamped. A Lua double: rounded.
File.WriteAllText(st.PathFor("S", "A"), "{\"version\":3,\"rules\":[],\"settings\":{\"auto\":true,\"settleSec\":5}}");
CharacterSortData old = st.Load("S", "A", out string? problem);
Check(problem == null && old.Settings.HoldMin == SortSettings.HoldMinDefault && old.Settings.Auto, "an older file: the default hold, its own settings kept");
File.WriteAllText(st.PathFor("S", "A"), "{\"settings\":{\"holdMin\":99}}");
Eq(st.Load("S", "A", out _).Settings.HoldMin, SortSettings.HoldMinMax, "clamped to the most");
File.WriteAllText(st.PathFor("S", "A"), "{\"settings\":{\"holdMin\":-2}}");
Eq(st.Load("S", "A", out _).Settings.HoldMin, 0, "clamped to off");
File.WriteAllText(st.PathFor("S", "A"), "{\"settings\":{\"holdMin\":2.0}}");
Eq(st.Load("S", "A", out _).Settings.HoldMin, 2, "2.0 = 2");
// The Lua script's file has no hold: the default.
SortStore imp = TempStore("hold-import");
string lua = imp.LuaPathFor("DreamWeave", "Tester");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
Eq(imp.Load("DreamWeave", "Tester", out _).Settings.HoldMin, SortSettings.HoldMinDefault, "a Lua import: the default hold");
}
}
}

View file

@ -0,0 +1,176 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// RynthSort 0.6.0: pack jobs. A side pack can hold what RynthAi picks: Salvage (its loot
// profile's first matching rule says Salvage), Sell (its AutoVendor would sell it), Mule (its
// AutoTrade would give it to the mule). RynthAi answers through RynthAi.Hub (read only); when it
// can't (not loaded, too old, no profile), that pack changes nothing and the window says why.
internal static partial class Program
{
private static JobAnswers Answers(JobKind kind, params uint[] marked)
{
var a = new JobAnswers();
var ja = new JobAnswer { Known = true, Text = "Hunting.utl" };
foreach (uint id in marked) ja.Marked.Add(id);
a.ByKind[kind] = ja;
return a;
}
private static PlanOptions JobOpt(SortInventory inv, List<PackJob> jobs, JobAnswers? answers) =>
new() { Jobs = JobPlan.For(jobs, inv, answers) };
private static void JobsPlan()
{
// Pack 3 salvages; armor goes to pack 2 by kind.
SortInventory inv = Inv(3);
inv.Packs[2].Name = "Salvage Sack";
inv.Main.Items.Add(It(10, "Celdon Girth", ObjectClasses.Armor)); // the loot profile says Salvage
inv.Main.Items.Add(It(11, "Amuli Coat", ObjectClasses.Armor)); // it says Keep
inv.Main.Items.Add(It(12, "Black Opal", ObjectClasses.Gem)); // Salvage, but a name rule sends it to pack 1
var rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Armor, 2), SortRule.ForName("Black Opal", 1) };
var jobs = new List<PackJob>();
Check(PackJobs.Set(jobs, inv, 3, JobKind.Salvage, null) && !PackJobs.Set(jobs, inv, 3, JobKind.Salvage, null), "a job set once");
Check(jobs.Single().PackId == inv.Packs[2].Id && PackJobs.On(jobs, inv, 3)?.Kind == JobKind.Salvage, "kept by the pack's id");
Check(!PackJobs.Set(jobs, inv, 7, JobKind.Sell, null), "a pack not carried");
var planner = new SortPlanner();
List<SortMove> moves = planner.Plan(inv, rules, SortScope.All, force: true, 0, 0, JobOpt(inv, jobs, Answers(JobKind.Salvage, 10, 12)));
SortMove Of(uint id) => moves.Single(m => m.Item.Id == id);
Eq(Of(10).DestIndex, 3, "marked Salvage: to the Salvage pack, before its kind's pack");
Eq(Of(11).DestIndex, 2, "not marked: its kind's pack");
Eq(Of(12).DestIndex, 1, "a name rule beats the job");
// RynthAi can't answer: nothing new goes in, and what is in the pack stays (Clean too).
inv.Packs[2].Items.Add(It(20, "Celdon Sleeves", ObjectClasses.Armor));
foreach (JobAnswers? none in new[] { null, new JobAnswers { ByKind = { [JobKind.Salvage] = JobAnswer.Unknown("RynthAi isn't loaded") } } })
{
moves = planner.Plan(inv, rules, SortScope.Clean, force: true, 0, 0, JobOpt(inv, jobs, none));
Check(!moves.Any(m => m.Item.Id == 20) && !moves.Any(m => m.DestIndex == 3), "unknown: the Salvage pack's items stay, nothing goes in");
Eq(moves.Single(m => m.Item.Id == 10).DestIndex, 2, "the marked coat goes by its kind meanwhile");
}
// Known, and an item in the pack is no longer marked: it follows its rules again.
moves = planner.Plan(inv, rules, SortScope.All, force: true, 0, 0, JobOpt(inv, jobs, Answers(JobKind.Salvage, 10)));
Eq(moves.Single(m => m.Item.Id == 20).DestIndex, 2, "not salvage any more: to its kind's pack");
inv.Packs[2].Items.Add(It(21, "Odd Thing", ObjectClasses.Misc));
moves = planner.Plan(inv, rules, SortScope.Clean, force: true, 0, 0, JobOpt(inv, jobs, Answers(JobKind.Salvage, 10)));
Eq(moves.Single(m => m.Item.Id == 21).DestIndex, 0, "Clean: an unmarked item no rule wants goes back to the main pack");
moves = planner.Plan(inv, rules, SortScope.All, force: true, 0, 0, JobOpt(inv, jobs, Answers(JobKind.Salvage, 10, 21)));
Check(!moves.Any(m => m.Item.Id == 21), "marked and in its job pack: it stays");
// Held items aren't moved for a job; a full job pack says what didn't fit.
var held = new SortPlanner { Held = id => id == 10 };
moves = held.Plan(inv, rules, SortScope.All, force: true, 0, 0, JobOpt(inv, jobs, Answers(JobKind.Salvage, 10)));
Check(!moves.Any(m => m.Item.Id == 10) && held.View.Held.Any(h => h.Item.Id == 10 && h.To == 3), "held: left alone, would go to the Salvage pack");
SortInventory full = Inv(1, cap: 1);
full.Packs[0].Name = "Salvage Sack";
full.Packs[0].Items.Add(It(1, "Celdon Girth", ObjectClasses.Armor));
full.Main.Items.Add(It(2, "Amuli Coat", ObjectClasses.Armor));
var fj = new List<PackJob>();
PackJobs.Set(fj, full, 1, JobKind.Salvage, null);
moves = planner.Plan(full, new List<SortRule>(), SortScope.All, force: true, 0, 0, JobOpt(full, fj, Answers(JobKind.Salvage, 1, 2)));
Check(moves.Count == 0 && planner.View.NoFit.Single().Pack == 1, "a full Salvage pack: it waits, and the banner names it");
// Two packs with the same job: the second takes what the first can't.
SortInventory two = Inv(2, cap: 1);
two.Main.Items.Add(It(1, "A", ObjectClasses.Armor));
two.Main.Items.Add(It(2, "B", ObjectClasses.Armor));
var tj = new List<PackJob>();
PackJobs.Set(tj, two, 1, JobKind.Sell, null);
PackJobs.Set(tj, two, 2, JobKind.Sell, null);
moves = planner.Plan(two, new List<SortRule>(), SortScope.All, force: true, 0, 0, JobOpt(two, tj, Answers(JobKind.Sell, 1, 2)));
Check(moves.Count == 2 && moves[0].DestIndex == 1 && moves[1].DestIndex == 2, "Sell: the first pack, then the next with the same job");
// What to ask RynthAi, and the mule.
var mj = new List<PackJob>();
PackJobs.Set(mj, two, 1, JobKind.Mule, " Packmule ");
PackJobs.Set(mj, two, 2, JobKind.Salvage, null);
List<JobKind> wanted = PackJobs.Wanted(mj, two, out string mule);
Check(wanted.SequenceEqual(new[] { JobKind.Mule, JobKind.Salvage }) && mule == "Packmule", "the jobs carried, and the mule's name trimmed");
Check(PackJobs.Set(mj, two, 1, JobKind.Mule, "Other") && PackJobs.On(mj, two, 1)!.Mule == "Other", "another mule: changed");
Check(PackJobs.Set(mj, two, 1, JobKind.None, null) && PackJobs.On(mj, two, 1) == null && !PackJobs.Set(mj, two, 1, JobKind.None, null), "taken off once");
SortInventory moved = Inv(2);
moved.Packs.RemoveAt(1);
Eq(PackJobs.Wanted(mj, moved, out _).Count, 0, "a job's pack not carried: nothing to ask");
}
/// <summary>The fake world with RynthAi's answers (FakeWorld answers nothing, as with RynthAi not loaded).</summary>
private sealed class JobWorld : ISortWorld
{
public readonly FakeWorld W = new();
public JobAnswers? Answers;
public int Asked;
public SortInventory? ReadInventory() => W.ReadInventory();
public GateInputs ReadGate(bool sortInCombat, long nowMs) => W.ReadGate(sortInCombat, nowMs);
public bool SendMove(in SortMove move) => W.SendMove(in move);
public MoveObservation Observe(in SortMove move) => W.Observe(in move);
public int ErrorSeqNow() => W.ErrorSeqNow();
public SortAbilities Abilities => W.Abilities;
public JobAnswers? AskJobs(SortInventory inv, IReadOnlyList<JobKind> wanted, string mule, long nowMs) { Asked++; return Answers; }
}
private static void JobsLoopWindowStore()
{
var w = new JobWorld();
w.W.Inv.Packs[2].Name = "Junk Bag";
w.W.Inv.Main.Items.Add(It(10, "Plain Ring", ObjectClasses.Jewelry));
SortController c = Controller(auto: true);
c.Data.Rules.Clear();
for (long t = 0; t <= 2000; t += 16) c.Tick(w, t);
Eq(w.Asked, 0, "no job: RynthAi isn't asked");
PackJobs.Set(c.Data.Jobs, w.W.Inv, 3, JobKind.Sell, null);
for (long t = 2000; t <= 5000; t += 16) c.Tick(w, t);
Check(w.Asked > 0 && w.W.Inv.Main.Items.Any(i => i.Id == 10), "asked; no answer (RynthAi not loaded): the ring stays");
ScreenModel m = Screen(c);
Check(m.Packs[2].JobLabel == "Sell" && m.Packs[2].JobLine == "Asking RynthAi which items belong here...", $"the card ({m.Packs[2].JobLine})");
w.Answers = new JobAnswers { ByKind = { [JobKind.Sell] = JobAnswer.Unknown("RynthAi isn't loaded") } };
for (long t = 5000; t <= 7000; t += 16) c.Tick(w, t);
m = Screen(c);
Check(m.Packs[2].JobProblem && m.Packs[2].JobLine == "Sell can't work now: RynthAi isn't loaded. What is in this pack stays put until it can.", $"says why ({m.Packs[2].JobLine})");
w.Answers = Answers(JobKind.Sell, 10);
w.Answers.ByKind[JobKind.Sell].Text = "default.utl";
for (long t = 7000; t <= 10_000; t += 16) c.Tick(w, t);
Check(w.W.Inv.Packs[2].Items.Any(i => i.Id == 10), "RynthAi says sell: the ring went to the Junk Bag");
Check(c.Feed.Any(f => f.Text == "Plain Ring -> Junk Bag"), "the feed names it");
m = Screen(c);
Check(!m.Packs[2].JobProblem && m.Packs[2].JobLine == "Takes what RynthAi's AutoVendor would sell (default.utl).", m.Packs[2].JobLine);
TileModel ring = m.TilesById[10];
Check(ring.Rule == TileRule.Job && ring.RuleText == "Sell", "the tile knows its job");
Eq(string.Concat(ScreenText.Why(ring, m).Select(r => r.Text)), "In its pack: Junk Bag, by its job Sell.", "why");
// A move row for a job.
w.W.Inv.Main.Items.Add(It(11, "Gold Ring", ObjectClasses.Jewelry));
w.Answers.ByKind[JobKind.Sell].Marked.Add(11);
c.SetAuto(false);
for (long t = 10_000; t <= 12_000; t += 16) c.Tick(w, t);
m = Screen(c);
Check(m.Moves.Any(r => r.ItemId == 11 && r.Sub == "Job: Sell" && r.Right == "Junk Bag"), "Next moves: Job: Sell");
Check(m.Packs[2].Ghosts.Any(g => g.ItemId == 11), "a ghost on the job pack");
// Mule label.
PackJobs.Set(c.Data.Jobs, w.W.Inv, 1, JobKind.Mule, "Packmule");
Eq(Screen(c).Packs[0].JobLabel, "Mule: Packmule", "a mule's pill");
// The file: kept by pack id; files from before have none; odd entries are dropped.
var d = new CharacterSortData();
d.Jobs.Add(new PackJob { PackId = 0x40000003, Pack = 3, Kind = JobKind.Salvage });
d.Jobs.Add(new PackJob { PackId = 0x40000001, Pack = 1, Kind = JobKind.Mule, Mule = "Packmule" });
using var doc = System.Text.Json.JsonDocument.Parse(SortStore.ToJson(d));
CharacterSortData back = SortStore.Parse(doc.RootElement);
Check(back.Jobs.Count == 2 && back.Jobs[0].Kind == JobKind.Salvage && back.Jobs[0].PackId == 0x40000003
&& back.Jobs[1].Kind == JobKind.Mule && back.Jobs[1].Mule == "Packmule", "saved and read back");
using var old = System.Text.Json.JsonDocument.Parse("{\"rules\":[]}");
Eq(SortStore.Parse(old.RootElement).Jobs.Count, 0, "an older file: no jobs");
using var odd = System.Text.Json.JsonDocument.Parse("{\"jobs\":[{\"job\":\"juggle\",\"pack\":1},7,{\"job\":\"SELL\",\"pack\":99,\"mule\":\"x\"}]}");
CharacterSortData o = SortStore.Parse(odd.RootElement);
Check(o.Jobs.Count == 1 && o.Jobs[0].Kind == JobKind.Sell && o.Jobs[0].Pack == SortStore.MaxPack && o.Jobs[0].Mule == "", "odd entries: unknown jobs dropped, numbers clamped, a mule only for Mule");
using var none = System.Text.Json.JsonDocument.Parse(SortStore.ToJson(new CharacterSortData()));
Check(!none.RootElement.TryGetProperty("jobs", out _), "no jobs: nothing written");
}
}
}

View file

@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// Starter layouts (#rynth-issues "The bag sort feature is lacking in UX": complex rules, no
// common-sense default) fitted to the packs a character carries, and the preview of what a
// sort would move.
internal static partial class Program
{
private static void LayoutCatalog()
{
Check(StarterLayouts.All.Length >= 3, "a few layouts to pick from");
Eq(StarterLayouts.All[0].Key, "everyday", "the one to suggest first");
Check(StarterLayouts.All.Select(l => l.Key).Distinct().Count() == StarterLayouts.All.Length
&& StarterLayouts.All.Select(l => l.Name).Distinct().Count() == StarterLayouts.All.Length, "keys and names are unique");
foreach (StarterLayout l in StarterLayouts.All)
{
Check(l.Groups.Length >= 3 && l.Blurb.Length > 0 && l.Blurb.Length <= 120, $"{l.Name}: kinds and a short line ({l.Blurb.Length})");
var seen = new HashSet<int>();
foreach (StarterGroup g in l.Groups)
foreach (int c in g.Classes)
{
Check(seen.Add(c), $"{l.Name}: {ObjectClasses.Label(c)} is in one kind only");
Check(ObjectClasses.ChoiceIndex(c) >= 0, $"{l.Name}: {ObjectClasses.Label(c)} is a class the rule editor offers");
}
}
Check(StarterLayouts.Find("HUNTING") == StarterLayouts.Hunting && StarterLayouts.Find("nope") == null && StarterLayouts.Find(null) == null, "found by key");
}
private static void LayoutFit()
{
// No side packs: every kind stays in the main pack.
LayoutPlan none = StarterLayouts.Fit(StarterLayouts.Everyday, Inv(0));
Check(none.Placed.Count == 0 && none.Rules.Count == 0 && none.Left.Count == StarterLayouts.Everyday.Groups.Length, "no packs: nothing placed");
// Three empty packs: the first three kinds, top pack first.
SortInventory three = Inv(3);
LayoutPlan p3 = StarterLayouts.Fit(StarterLayouts.Everyday, three);
Eq(string.Join(",", p3.Placed.Select(x => x.Group.Key + x.Pack)), "components1,gems2,salvage3", "most wanted kinds on the top packs");
Eq(string.Join(",", p3.Left.Select(g => g.Key)), "notes,supplies,scrolls", "the rest stay in the main pack");
Check(p3.Spare.Count == 0 && p3.AlreadyThere == 0, "no spare pack, nothing in place yet");
Check(p3.Rules.Count == 3 && p3.Rules[0].PackId == 0x40000001 && p3.Rules[0].Pack == 1 && p3.Rules[0].HasClass(ObjectClasses.SpellComponent)
&& p3.Rules[1].HasClass(ObjectClasses.Gem) && p3.Rules[1].HasClass(ObjectClasses.ManaStone) && p3.Rules[1].HasClass(ObjectClasses.Key),
"one rule per kind, tied to its pack's id");
Check(p3.Rules[0].PackNote == "Pack 1 - empty", "and noted as the pack was");
// Packs that already hold a kind keep it (the fewest moves); the rest go to the roomiest packs.
SortInventory four = Inv(4);
Fill(four.Packs[0], 20, 1000); // pack 1: 20 other things
for (uint i = 0; i < 5; i++) four.Packs[2].Items.Add(It(2000 + i, "Salvaged Iron", ObjectClasses.Salvage));
for (uint i = 0; i < 8; i++) four.Packs[3].Items.Add(It(3000 + i, "Prismatic Taper", ObjectClasses.SpellComponent));
LayoutPlan p4 = StarterLayouts.Fit(StarterLayouts.Basics, four);
Eq(string.Join(",", p4.Placed.Select(x => x.Group.Key + x.Pack)), "gems2,salvage3,components4", "components stay in 4, salvage in 3, gems to the empty pack 2");
Eq(p4.AlreadyThere, 13, "13 items already where their kind goes");
Eq(string.Join(",", p4.Spare), "1", "pack 1 (full of other things) is left free");
// More packs than kinds: spares, top first.
LayoutPlan p7 = StarterLayouts.Fit(StarterLayouts.Basics, Inv(5));
Check(p7.Placed.Count == 3 && p7.Left.Count == 0 && string.Join(",", p7.Spare) == "4,5", "five packs, three kinds: packs 4 and 5 spare");
LayoutPlan all = StarterLayouts.Fit(StarterLayouts.Everyday, Inv(7));
Check(all.Placed.Count == 6 && all.Left.Count == 0 && all.Spare.Count == 1, "seven packs: every kind placed, one spare");
// The rules mean what the plan says.
SortInventory inv = Inv(3);
inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
inv.Main.Items.Add(It(11, "Black Opal", ObjectClasses.Gem));
inv.Main.Items.Add(It(12, "Trade Note (250,000)", ObjectClasses.TradeNote));
LayoutPlan fit = StarterLayouts.Fit(StarterLayouts.Everyday, inv);
Eq(SortRules.Resolve(SortRules.RuleFor(fit.Rules, inv.Main.Items[0])!, inv, out _), 1, "the taper goes to pack 1");
Eq(SortRules.Resolve(SortRules.RuleFor(fit.Rules, inv.Main.Items[1])!, inv, out _), 2, "the opal to pack 2");
Check(SortRules.RuleFor(fit.Rules, inv.Main.Items[2]) == null, "the trade note's kind had no pack: it stays");
}
private static void PreviewMoves()
{
SortInventory inv = Inv(3);
inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
inv.Main.Items.Add(It(11, "Lead Scarab", ObjectClasses.SpellComponent));
inv.Packs[1].Items.Add(It(12, "Black Opal", ObjectClasses.Gem));
inv.Packs[2].Items.Add(It(13, "Junk", ObjectClasses.Misc));
int before = inv.Main.Items.Count + inv.Packs.Sum(p => p.Items.Count);
SortPreview p = SortPreview.Build(inv, Defaults, PlanOptions.Full, null);
Eq(p.Moves.Count, 3, "three items would move");
Check(p.Into[1] == 2 && p.Into[3] == 1 && p.OutOf[0] == 2 && p.OutOf[2] == 1, "counted by pack in and out");
Check(p.Moves.All(m => m.Kind == MoveKind.Route) && !p.Empty, "only moves to other packs");
Eq(inv.Main.Items.Count + inv.Packs.Sum(x => x.Items.Count), before, "the preview moves nothing");
Check(inv.Main.Items.Any(i => i.Id == 10), "the inventory is as it was");
SortPreview clean = SortPreview.Build(inv, Defaults, PlanOptions.Full, null, clean: true);
Check(clean.Moves.Count == 4 && clean.Into[0] == 1, "Clean also sends the stray home");
SortPreview held = SortPreview.Build(inv, Defaults, PlanOptions.Full, id => id == 10);
Check(held.Moves.Count == 2 && held.View.Held.Count == 1 && held.View.Held[0].Item.Id == 10, "a held item is shown apart, not as a move");
// Settle times and blocks of the real planner don't matter to the preview, and it doesn't touch them.
var real = new SortPlanner();
real.Plan(inv, Defaults, SortScope.All, force: false, 0, 60_000);
Eq(real.View.WaitSettle, 2, "the real planner: both new items settling");
SortPreview again = SortPreview.Build(inv, Defaults, PlanOptions.Full, null);
Check(again.Moves.Count == 3 && real.View.WaitSettle == 2, "the preview moves them now; the real view is unchanged");
// Nothing to move: empty, and how much tidying inside the packs follows.
SortInventory tidy = Inv(1);
tidy.Packs[0].Items.Add(It(20, "Zircon", ObjectClasses.Gem));
tidy.Packs[0].Items.Add(It(21, "Amber", ObjectClasses.Gem));
tidy.Packs[0].OrderKnown = true;
SortPreview t = SortPreview.Build(tidy, new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) }, PlanOptions.Full, null);
Check(t.Empty && t.ToOrder == 1, "nothing to move; one item to put in order");
Eq(SortPreview.Build(tidy, Defaults, default, null).ToOrder, 0, "ordering off: nothing to order");
// A layout's preview: its rules on the packs as they are.
LayoutPlan fit = StarterLayouts.Fit(StarterLayouts.Everyday, inv);
SortPreview lp = SortPreview.Build(inv, fit.Rules, PlanOptions.Full, null);
Check(lp.Into[1] == 2 && lp.Moves.Count == 2, $"Everyday on these packs: two components to pack 1, the opal stays in pack 2, which gets the gems ({string.Join(",", lp.Into)})");
}
}
}

View file

@ -103,7 +103,7 @@ namespace RynthSort.Tests
private static void PackColumnWindow()
{
var c = new SortController();
var c = Sorter();
var selected = new List<uint>();
var panel = new SortPanel(c, () => { })
{

View file

@ -301,7 +301,8 @@ namespace RynthSort.Tests
{
SortStore st = TempStore("packids");
CharacterSortData d = st.Load("S", "A", out _);
Check(!d.PacksFixed, "new character: the defaults get tied to packs on the first read");
Check(!d.PacksFixed, "new character: rules made by number get tied to packs on the first read");
d.Rules = SortRules.Defaults();
d.Rules[0].PackId = 0x8000ABCD;
d.Rules[0].PackNote = "Sack - Components";
d.PacksFixed = true;

View file

@ -0,0 +1,319 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Ui;
using RynthCore.Plugin.RynthSort.Views;
using RynthCore.Plugin.Shared;
namespace RynthSort.Tests
{
// The redesigned window (#rynth-issues "The bag sort feature is lacking in UX"): what the status
// line says, the four pages, starter layouts through the window, the moves preview, items left
// alone, the kind picker, Undo and Put back, all driven by widget key as the engine sends them;
// and op level 3 (tables, a bold status) only when the engine has it.
internal static partial class Program
{
/// <summary>A window on a pretend game: the controller has read the packs once (auto-sort off).</summary>
private static (SortController C, SortPanel Panel, UiHost Host, UiWindow W, FakeWorld World) Live(bool rules = true)
{
var world = new FakeWorld();
world.Inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
world.Inv.Main.Items.Add(It(11, "Prismatic Taper", ObjectClasses.SpellComponent));
world.Inv.Packs[1].Items.Add(It(12, "Salvaged Iron", ObjectClasses.Salvage));
SortController c = Controller(auto: false);
if (!rules) c.Data.Rules.Clear();
Ticks(c, world, 0, 1000);
var panel = new SortPanel(c, () => { }) { Character = () => "Tester", Now = () => c.Clock };
var host = new UiHost();
UiWindow w = host.Add(new UiWindow("RynthSort/Main", "RynthSort") { Visible = true });
return (c, panel, host, w, world);
}
private static Action<ushort, string, byte[]> Sender(UiHost host, UiWindow w, SortPanel panel)
{
uint seq = 100;
return (type, id, payload) =>
{
Apply(host, Event(type, ++seq, w.Hash, w.KeyOf(id), payload));
Draw(w, panel);
};
}
private static void PanelStatusWords()
{
SortController c = Sorter();
var v = new SortView();
Eq(SortPanel.Headline(c, v, false).Text, "Off: nothing moves by itself", "off");
Eq(SortPanel.Headline(c, v, false).Color, UiColors.Grey, "off is grey");
c.Data.Settings.Auto = true;
var w = new FakeWorld();
c.Tick(w, 0);
Eq(SortPanel.Headline(c, c.Planner.View, false).Text, "On: all tidy", "on, nothing to do");
Eq(SortPanel.Headline(c, c.Planner.View, false).Color, UiColors.Green, "green");
Eq(SortPanel.Headline(c, c.Planner.View, true).Text, "On: no rules yet", "on without rules says so");
v.WaitSettle = 2;
v.NextSettleMs = 2100;
Eq(SortPanel.Headline(c, v, false).Text, "On: 2 new items move in 3 s", "settling, with the time");
v.WaitSettle = 1;
Eq(SortPanel.Headline(c, v, false).Text, "On: 1 new item moves in 3 s", "one settling");
v.WaitFull = 3;
var (stuck, color) = SortPanel.Headline(c, v, false);
Check(stuck == "On: 3 items can't move" && color == UiColors.Amber, "stuck items: amber");
c.StartJob(SortScope.Clean);
Eq(SortPanel.Headline(c, v, false).Text, "Cleaning packs", "a job says which");
Eq(SortPanel.Headline(c, v, false).Color, UiColors.Blue, "blue while working");
var paused = new FakeWorld { Gate = new GateInputs { Looting = true } };
SortController p = Controller();
p.Tick(paused, 0);
Eq(SortPanel.Headline(p, p.Planner.View, false).Text, "Paused: a corpse or chest is open", "paused, in plain words");
Eq(SortPanel.PausedWords("RynthAi is buffing"), "RynthAi is buffing", "RynthAi's reasons as they are");
Eq(SortPanel.PausedWords("busy"), "you are casting or using something", "busy");
var d = new SortView { WaitFull = 1, WaitNoPack = 2 };
List<string> lines = SortPanel.Details(c, d, null, true);
Check(lines[0].StartsWith("No rules yet", StringComparison.Ordinal), "no rules: said first");
Check(lines.Contains("1 item waits for a full pack; 2 items for a pack you don't carry."), $"what waits, in one line ({string.Join(" | ", lines)})");
Eq(SortPanel.Count(1, "item"), "1 item", "one");
Eq(SortPanel.Ago(30_000) + "," + SortPanel.Ago(150_000), "just now,2 min ago", "how long ago");
}
private static void PanelLayouts()
{
var (c, panel, host, w, _) = Live(rules: false);
var send = Sender(host, w, panel);
Draw(w, panel);
ParseAll(host, "no rules", out _);
string body = BodyText(w);
Eq(panel.Tab, PanelTab.Layouts, "no rules: the window opens on the layouts");
Check(body.Contains("Everyday (a good start)") && body.Contains("Hunting") && body.Contains("Crafting") && body.Contains("Just the basics"), "the layouts listed");
Check(body.Contains("No rules yet"), "and says there are no rules");
Check(!body.Contains("###layout.use"), "nothing to use until one is picked");
w.MarkSubmitted(true);
send(1, "layout.everyday", Click);
ParseAll(host, "a layout's preview", out _);
body = BodyText(w);
Check(panel.PickedLayout == "everyday", "picked");
Check(body.Contains("Everyday on your 3 packs") && body.Contains("Spell components") && body.Contains("Gems, mana stones and keys"), "where each kind goes");
Check(body.Contains("No pack left for trade notes and coins; healing kits, lockpicks and food; scrolls and books: they stay in the main pack."), "what has no pack");
Check(body.Contains("Pack 2") && body.Contains("Salvage") , "salvage stays in pack 2, which holds it");
Check(body.Contains("2 items would move; 1 already in place."), "how much would move");
Check(body.Contains("Use this layout###layout.use") && body.Contains("Cancel###layout.cancel"), "use or cancel");
Check(!body.Contains("This replaces"), "no rules to replace");
Eq(c.Data.Rules.Count, 0, "looking changes nothing");
send(1, "layout.cancel", Click);
Check(panel.PickedLayout == null && !BodyText(w).Contains("###layout.use"), "Cancel closes it");
send(1, "layout.everyday", Click);
send(1, "layout.use", Click);
Eq(c.Data.Rules.Count, 3, "Use this layout: one rule per pack");
Check(c.Data.Rules.Any(r => r.PackId == 0x40000002 && r.HasClass(ObjectClasses.Salvage)), "salvage tied to the pack that holds it");
Check(!c.Data.Settings.Auto && c.Job == null, "nothing moves: auto-sort stays off, no job");
Eq(panel.Tab, PanelTab.Packs, "back to the packs, to see the rules");
body = BodyText(w);
Check(body.Contains("Rules set from Everyday") && body.Contains("Nothing has moved yet"), "it says what happened");
Check(body.Contains("Undo: the Everyday layout###undo"), "and offers Undo");
Check(body.Contains("Spell Component (1 to move in)") || body.Contains("Spell Component (1"), "a rule says what it would bring in");
send(1, "undo", Click);
Eq(c.Data.Rules.Count, 0, "Undo: the rules as they were (none)");
Check(!BodyText(w).Contains("Undo:"), "Undo is used up");
// With rules already: picking says they are replaced.
c.Data.Rules.AddRange(SortRules.Defaults());
send(1, "tab.layouts", Click);
send(1, "layout.basics", Click);
Check(BodyText(w).Contains("This replaces your 3 rules (Undo brings them back)."), "replacing rules is said first");
// From the packs page with no rules: a button to the layouts.
c.Data.Rules.Clear();
send(1, "tab.packs", Click);
Check(BodyText(w).Contains("Pick a starter layout###go.layouts"), "no rules: a way to the layouts on the packs page");
send(1, "go.layouts", Click);
Eq(panel.Tab, PanelTab.Layouts, "and it goes there");
// No side packs: nowhere to put things.
var bare = new FakeWorld { Inv = Inv(0) };
bare.Inv.Main.Items.Add(It(1, "Black Opal", ObjectClasses.Gem));
SortController c0 = Controller(auto: false);
c0.Data.Rules.Clear();
Ticks(c0, bare, 0, 1000);
var p0 = new SortPanel(c0, () => { }) { Character = () => "Someone" };
var h0 = new UiHost();
UiWindow w0 = h0.Add(new UiWindow("RynthSort/Main", "RynthSort") { Visible = true });
Draw(w0, p0);
ParseAll(h0, "no packs", out _);
Check(BodyText(w0).Contains("You carry no side packs"), "no packs: says so");
}
private static void PanelMoves()
{
var (c, panel, host, w, world) = Live();
var send = Sender(host, w, panel);
Draw(w, panel);
Eq(panel.Tab, PanelTab.Packs, "with rules: the packs page first");
string body = BodyText(w);
Check(body.Contains("Moves (2)###tab.moves"), "the page button counts the moves");
Check(body.Contains("2 items would move when you sort (see Moves)."), "the status says what a sort would do");
send(1, "tab.moves", Click);
ParseAll(host, "moves page", out _);
body = BodyText(w);
Check(body.Contains("A sort would move 2 items:"), "how many");
Check(body.Contains("Black Opal") && body.Contains("main pack -> pack 3"), "the opal: from and to");
Check(body.Contains("Prismatic Taper") && body.Contains("main pack -> pack 1") && !body.Contains("Salvaged Iron"), "the taper to pack 1; the salvage is in its pack already");
Check(body.Contains("Nothing moves until you press Sort now or turn on Auto-sort."), "and that nothing moves yet");
Check(body.Contains("Its rule: Gem, Key, Mana Stone."), "a move's tooltip says which rule");
Check(!ContainsOp(w.Body, UiFormat.OpTable) && !ContainsOp(w.Body, UiFormat.OpPushFont), "op level 2: no tables, no fonts");
// The player selects the opal: it is left alone, and the page says so.
c.Touch.NoteSelected(10, 1100);
Ticks(c, world, 1100, 2200);
Draw(w, panel);
ParseAll(host, "left alone", out _);
body = BodyText(w);
Check(body.Contains("Left alone") && body.Contains("you selected it just now; would go to pack 3"), "left alone, how and where it would go");
Check(body.Contains("A sort would move 1 item:"), "and it isn't counted as a move");
Check(body.Contains("for 3 minutes (Settings)"), "for how long");
Check(body.Contains("1 item left alone because you used it lately (see Moves)."), "the status says so too");
send(1, "hold.release", Click);
Check(!c.IsHeld(10) && !BodyText(w).Contains("Left alone"), "Sort them too: no longer held");
// A sort, then the log and Put back.
send(1, "job.all", Click);
Ticks(c, world, 2200, 6000);
Draw(w, panel);
body = BodyText(w);
Check(body.Contains("Nothing to move: every item is in its pack."), "sorted: nothing left to move");
Check(body.Contains("Black Opal -> pack 3") && body.Contains("Packs sorted"), "the moves in Done lately");
Check(body.Contains("Put back###job.back") && body.Contains("Put back 2 items###moves.back"), "Put back beside Sort now and on this page");
send(1, "moves.back", Click);
Check(c.Job == SortScope.PutBack && !c.Data.Settings.Auto, "Put back starts (auto-sort off)");
Ticks(c, world, 6000, 10_000);
Check(world.Inv.Main.Items.Any(i => i.Id == 10) && world.Inv.Main.Items.Any(i => i.Id == 11), "the two items are back in the main pack");
Draw(w, panel);
Check(!BodyText(w).Contains("Put back###job.back"), "nothing left to put back: no button");
// Op level 3: the list is a table and the status bold; still accepted by the engine.
panel.OpLevel = () => 3;
Draw(w, panel);
ParseAll(host, "op level 3", out _);
Check(ContainsOp(w.Body, UiFormat.OpTable) && ContainsOp(w.Body, UiFormat.OpTableNextRow) && ContainsOp(w.Body, UiFormat.OpPushFont), "op level 3: a table and the bold status");
body = BodyText(w);
Check(body.Contains("Item") && body.Contains("From") && body.Contains("To"), "the table's columns");
int engineLevel = DisplayListParser.OpLevel; // 2 with the sibling checkout, 3 with -p:EngineParser=<an op level 3 engine>
if (engineLevel >= 3)
{
List<ParsedWindow> parsed = ParseWindows(host);
var ops = parsed[0].List!.Ops.Take(parsed[0].List!.OpCount).Select(o => (byte)o.Code).ToList();
Check(ops.Contains(UiFormat.OpTable) && ops.Count(o => o == UiFormat.OpTableNextRow) == 2 && ops.Contains(UiFormat.OpPushFont),
"an op level 3 engine keeps the table, its two rows and the font");
}
}
private static void PanelPacks()
{
var (c, panel, host, w, world) = Live();
panel.Icons = () => true;
var send = Sender(host, w, panel);
Draw(w, panel);
ParseAll(host, "packs page", out _);
string body = BodyText(w);
Check(body.Contains("Goes here:"), "what goes in each pack");
Check(body.Contains("Salvage (1 here)"), "a rule says how many items it keeps there");
Check(body.Contains("Gem, Key, Mana Stone (1 to move in)"), "and how many would move in");
Check(body.Contains("###kind.40000001") && body.Contains("Add a kind of item..."), "a kind picker per pack");
Check(body.Contains("Salvaged Iron"), "the pack's contents strip names its items");
// Gems to pack 1 with the kind picker: taken from pack 3's rule.
SortRule gems = c.Data.Rules.First(r => r.HasClass(ObjectClasses.Gem));
int pick = ObjectClasses.Choices.Where(x => x != ObjectClasses.SpellComponent).ToList().IndexOf(ObjectClasses.Gem) + 1;
send(3, "kind.40000001", BitConverter.GetBytes(pick));
Check(!gems.HasClass(ObjectClasses.Gem) && gems.HasClass(ObjectClasses.Key), "pack 3's rule gave up Gem");
Check(c.Data.Rules.Any(r => r.HasClass(ObjectClasses.Gem) && r.HasClass(ObjectClasses.SpellComponent) && SortPanel.ShownPack(c.Planner.View, r) == 1),
"and pack 1's rule took it");
Check(BodyText(w).Contains("Gems now go here (taken from pack 3). Nothing has moved yet."), "it says so under the pack");
Check(BodyText(w).Contains("Undo: Gems to pack 1###undo"), "with Undo");
send(1, "undo", Click);
Check(c.Data.Rules.Count == 3 && c.Data.Rules.Single(r => r.HasClass(ObjectClasses.Gem)).HasClass(ObjectClasses.Key), "Undo: back as it was");
send(3, "kind.40000001", BitConverter.GetBytes(0));
Eq(c.Data.Rules.Count(r => r.HasClass(ObjectClasses.Gem)), 1, "the picker's first line does nothing");
// A kind no pack had goes into the pack's rule; a pack with no rule gets a new one.
send(3, "kind.40000003", BitConverter.GetBytes(ObjectClasses.Choices.Where(x => x != ObjectClasses.Gem && x != ObjectClasses.ManaStone && x != ObjectClasses.Key).ToList().IndexOf(ObjectClasses.Lockpick) + 1));
Check(c.Data.Rules.Single(r => r.HasClass(ObjectClasses.Gem)).HasClass(ObjectClasses.Lockpick), "lockpicks join pack 3's rule");
world.Inv.Packs.Add(new SortPack { Id = 0x40000004, Name = "Pack 4", Capacity = 24 });
Ticks(c, world, 1000, 2500);
Draw(w, panel);
Check(BodyText(w).Contains("Nothing goes here yet."), "a new pack: nothing goes there yet");
int before = c.Data.Rules.Count;
send(3, "kind.40000004", BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.Food) + 1));
Check(c.Data.Rules.Count == before + 1 && c.Data.Rules[^1].HasClass(ObjectClasses.Food) && c.Data.Rules[^1].PackId == 0x40000004, "a pack with no rule gets one");
// Removing a rule can be undone.
SortRule food = c.Data.Rules[^1];
send(1, $"r{food.Uid}.row", Click);
send(1, $"r{food.Uid}.remove", Click);
Check(!c.Data.Rules.Contains(food) && BodyText(w).Contains("Undo: rule removed"), "removed, with Undo");
send(1, "undo", Click);
Check(c.Data.Rules.Any(r => r.HasClass(ObjectClasses.Food) && r.PackId == 0x40000004), "and back");
// The setting for leaving items alone.
send(1, "tab.settings", Click);
send(3, "hold", BitConverter.GetBytes(12));
Eq(c.Data.Settings.HoldMin, 12, "Leave alone (min)");
send(3, "hold", BitConverter.GetBytes(500));
Eq(c.Data.Settings.HoldMin, SortSettings.HoldMinMax, "clamped");
Check(BodyText(w).Contains("stays put for 30 minutes"), "the line under it says what it does");
send(3, "hold", BitConverter.GetBytes(0));
Check(BodyText(w).Contains("Off: an item you take out of its pack goes back at the next sort."), "and when it is off");
// Another character: the window starts fresh.
panel.Character = () => "Someone";
c.Data.Rules.Clear();
Draw(w, panel);
Eq(panel.Tab, PanelTab.Layouts, "another character with no rules: the layouts");
Check(panel.UndoWhat.Length == 0, "and no Undo from the last one");
}
private static void PanelBudget()
{
// A full character: eight packs of 24, a full main pack, 64 rules, icons, every page.
var world = new FakeWorld { Inv = Inv(8, cap: 40) };
uint id = 1;
for (int p = 0; p < 8; p++)
for (int i = 0; i < 24; i++) world.Inv.Packs[p].Items.Add(It(id++, $"Thing {p}-{i}", ObjectClasses.Choices[(p + i) % ObjectClasses.Choices.Length]));
for (int i = 0; i < 102; i++) world.Inv.Main.Items.Add(It(id++, $"Loot {i}", ObjectClasses.Choices[i % ObjectClasses.Choices.Length]));
SortController c = Controller(auto: false);
c.Data.Rules.Clear();
for (int i = 0; i < SortStore.MaxRules; i++)
c.Data.Rules.Add(SortRule.For(1 + i % 8, new[] { ObjectClasses.Choices[i % ObjectClasses.Choices.Length] }, "x" + i));
Ticks(c, world, 0, 1000);
var panel = new SortPanel(c, () => { }) { Character = () => "Tester", Icons = () => true, CanSelect = () => true };
var host = new UiHost();
UiWindow w = host.Add(new UiWindow("RynthSort/Main", "RynthSort") { Visible = true });
foreach (int level in new[] { 2, 3 })
{
panel.OpLevel = () => level;
foreach (PanelTab tab in Enum.GetValues<PanelTab>())
{
panel.ShowTab(tab);
Draw(w, panel);
ParseAll(host, $"level {level}, {tab}", out int ops);
Check(ops < 1500 && !BodyText(w).Contains("more than fits in one window"), $"level {level}, {tab}: fits ({ops} ops)");
Console.WriteLine($" level {level}, {tab}: {ops} ops, {w.Body.Length} bytes");
w.MarkSubmitted(true);
}
panel.ShowTab(PanelTab.Layouts);
Apply(host, Event(1, 1, w.Hash, w.KeyOf("layout.everyday"), Click));
Draw(w, panel);
ParseAll(host, $"level {level}, a layout preview", out int lops);
Check(lops < 1500, $"level {level}: a layout preview fits ({lops} ops)");
Apply(host, Event(1, 2, w.Hash, w.KeyOf("layout.cancel"), Click));
}
}
}
}

View file

@ -92,6 +92,46 @@ namespace RynthSort.Tests
Run("plan: a fixed inventory runs out of moves", Converges);
Run("loop: auto-sort tidies every pack, then stays still", ConvergesInTheLoop);
Run("remote: another plugin's \"rsort\" command reaches /rsort, anything else is not ours", RemoteCommand);
Run("add selected: the rule text from an item's name", AddSelectedText);
Run("add selected: finding the selected object in the packs", AddSelectedLookup);
Run("add selected: nothing selected, not an item, no pack", AddSelectedRefusals);
Run("add selected: where the name goes", AddSelectedAdds);
Run("add selected: duplicates", AddSelectedDuplicates);
Run("add selected: an item another pack's rule takes", AddSelectedOtherPack);
Run("add selected: the window button and the command", AddSelectedWindow);
Run("hold: what counts as the player touching an item", HoldWatch);
Run("hold: touched items are left where they are (moves, stacks, order)", HoldPlan);
Run("hold: in the loop (taken out, selected, released, off)", HoldLoop);
Run("hold: the setting in the file (old files, clamps, Lua import)", HoldStore);
Run("put back: the last sort undone, in the loop", PutBackLoop);
Run("put back: what can go back (room, packs, gone)", PutBackPlan);
Run("layouts: the starter layouts", LayoutCatalog);
Run("layouts: fitted to the packs carried (contents first, then room)", LayoutFit);
Run("preview: what a sort would move, before anything moves", PreviewMoves);
Run("window: what the status line says (off, on, settling, stuck, paused, jobs)", PanelStatusWords);
Run("window: starter layouts picked, previewed, used and undone", PanelLayouts);
Run("window: the moves page (preview, left alone, Sort them too, Put back, op level 3)", PanelMoves);
Run("window: the packs page (counts, kind picker, Undo) and the hold setting", PanelPacks);
Run("window: a full character fits on every page at op levels 2 and 3", PanelBudget);
Run("layouts: a pack keeps the kind it already holds, before kinds no pack holds", LayoutHeldKindsFirst);
Run("hold: one item left alone, or let go", HoldOneItem);
Run("send: an item sent to a pack from the window (Just move it, Send to)", SendFromWindow);
Run("screen: the activity feed with times, and settling items", ScreenFeedAndSettling);
Run("screen: the view-model's packs, tiles, chips, moves, left alone and status", ScreenModelPacks);
Run("screen: rules for packs not carried, and the layouts popup", ScreenModelOrphansAndLayouts);
Run("screen: rule changes (All a kind, Only a name, the x), toasts and Undo", ScreenRuleEdits);
Run("window: the sections manifest (frameless, drawn at its own size)", WindowManifest);
Run("window: tiles that just arrived pop in", WindowArrivals);
Run("feed: packs by name, with the number when two share it", FeedPackNames);
Run("drop: an item from RynthCore's Inventory on a pack card (one drop, the engine's payload)", DropFromInventory);
Run("handy: kits, stones, food, potions and elixirs at the front of the main pack", HandyFront);
Run("handy: in the loop, held items, the window and the file", HandyLoopAndStore);
Run("fold: packs fold to their header and rules, saved by pack id", FoldedPacks);
Run("rules: a typed name on \"+ Add a rule\" (no item needed)", TypedNameRule);
Run("full pack: overflow into the next pack with the same rule, else it waits", FullPackSpill);
Run("full pack: one chat line per sort, the banner, the red bar, overflow chips", FullPackWarnings);
Run("jobs: Salvage, Sell and Mule packs in the planner (name, job, kind; RynthAi can't answer)", JobsPlan);
Run("jobs: in the loop, the window and the file", JobsLoopWindowStore);
}
finally
{
@ -596,9 +636,17 @@ namespace RynthSort.Tests
return false;
}
private static SortController Controller(bool auto = true, int gapMs = 300, int settleSec = 0)
/// <summary>A controller with the old script's three rules (components 1, salvage 2, gems/stones/keys 3): a new character has none now.</summary>
private static SortController Sorter()
{
var c = new SortController();
c.Data.Rules = SortRules.Defaults();
return c;
}
private static SortController Controller(bool auto = true, int gapMs = 300, int settleSec = 0)
{
var c = Sorter();
c.Data.Settings.Auto = auto;
c.Data.Settings.GapMs = gapMs;
c.Data.Settings.SettleSec = settleSec;
@ -833,11 +881,13 @@ namespace RynthSort.Tests
{
SortStore st = TempStore("roundtrip");
CharacterSortData d = st.Load("DreamWeave", "Drakkon", out string? problem);
Check(problem == null && d.Rules.Count == 3 && d.ImportedFrom.Length == 0, "no file: the defaults");
Check(problem == null && d.Rules.Count == 0 && d.ImportedFrom.Length == 0, "no file: no rules (the window offers starter layouts)");
Check(!d.Settings.WindowOpen, "no file: the window starts closed (the bar button opens it)");
Check(!d.Settings.Auto, "no file: auto-sort starts off until it is turned on");
d.Rules = SortRules.Defaults();
d.Rules.Add(SortRule.ForName("Pyreal \"Mote\"", 6));
d.Rules[0].On = false;
d.Settings.Auto = false;
d.Settings.Auto = true;
d.Settings.SettleSec = 12;
d.Settings.GapMs = 900;
d.Settings.SortInCombat = true;
@ -849,7 +899,7 @@ namespace RynthSort.Tests
Eq(back.Rules.Count, 4, "rules");
Check(!back.Rules[0].On && back.Rules[3].Classes.Count == 0 && back.Rules[3].Names.Count == 1 && back.Rules[3].Names[0] == "Pyreal \"Mote\"" && back.Rules[3].Pack == 6, "rule fields");
Check(back.Rules[2].SameAs(SortRules.Defaults()[2]), "a rule with three classes comes back whole");
Check(!back.Settings.Auto && back.Settings.SettleSec == 12 && back.Settings.GapMs == 900 && back.Settings.SortInCombat && back.Settings.WindowOpen, "settings");
Check(back.Settings.Auto && back.Settings.SettleSec == 12 && back.Settings.GapMs == 900 && back.Settings.SortInCombat && back.Settings.WindowOpen, "settings");
Eq(SortStore.FileStem("Dream:Weave", "Con"), "Dream_Weave_Con", "unsafe characters replaced like RynthLua");
Eq(SortStore.SafeFileName("CON"), "_CON", "reserved names guarded");
}
@ -890,7 +940,7 @@ namespace RynthSort.Tests
Directory.CreateDirectory(Path.GetDirectoryName(own)!);
File.WriteAllText(own, "{ not json");
CharacterSortData d = st.Load("S", "A", out string? problem);
Check(problem != null && d.Rules.Count == 3, "broken file: defaults, problem reported");
Check(problem != null && d.Rules.Count == 0, "broken file: no rules, problem reported");
// The Lua script saved an empty rule list as {}; numbers as doubles; out-of-range values clamped.
File.WriteAllText(own, "{\"rules\":{},\"settings\":{\"auto\":true,\"settleSec\":99.0,\"gapMs\":5,\"x\":1}}");
@ -923,7 +973,7 @@ namespace RynthSort.Tests
private static (SortController, SortPanel, UiHost, UiWindow) Window()
{
var c = new SortController();
var c = Sorter();
var panel = new SortPanel(c, () => { }) { Character = () => "Drakkon" };
var host = new UiHost();
UiWindow w = host.Add(new UiWindow("RynthSort/Main", "RynthSort") { Visible = true });
@ -1002,11 +1052,13 @@ namespace RynthSort.Tests
ParseAll(host, "default rules", out int ops);
Check(ops > 10 && ops < 1500, $"ops in range ({ops})");
string body = BodyText(w);
Check(body.Contains("Auto-sort") && body.Contains("Sort now") && body.Contains("Clean packs") && body.Contains("Empty side packs"), "buttons and toggle");
Check(body.Contains("Auto-sort") && body.Contains("Sort now") && body.Contains("Clean packs") && body.Contains("Off: nothing moves by itself"), "buttons, toggle and what it is doing");
Check(body.Contains("Packs###tab.packs") && body.Contains("Moves###tab.moves") && body.Contains("Layouts###tab.layouts") && body.Contains("Settings###tab.settings"), "the four pages");
Check(!body.Contains("Empty side packs"), "Empty side packs is on the Settings page, not beside Sort now");
Check(body.Contains("Main pack (1/102)"), "the main pack's line");
Check(body.Contains("Pack 1: Pack 1 (24/24) - Junk 0, Junk 1, Junk 2"), "a section per pack, named with its room and contents");
Check(body.Contains("Pack 3: Pack 3 (0/24) - empty") && body.Contains("Gem, Key, Mana Stone"), "a rule with three classes as one row under its pack");
Check(body.Contains("Pack 4: Pack 4 (0/24) - empty") && body.Contains("No rules send items here."), "a pack without rules says so");
Check(body.Contains("Pack 4: Pack 4 (0/24) - empty") && body.Contains("Nothing goes here yet."), "a pack without rules says so");
Check(body.IndexOf("Pack 1: ", StringComparison.Ordinal) < body.IndexOf("Spell Component", StringComparison.Ordinal)
&& body.IndexOf("Spell Component", StringComparison.Ordinal) < body.IndexOf("Pack 2: ", StringComparison.Ordinal), "a rule sits under its pack");
Check(!body.Contains("Classes:"), "no editor until a rule is picked");
@ -1015,7 +1067,6 @@ namespace RynthSort.Tests
// The gem rule's editor, the settings open, warnings and a log.
SortRule gemRule = c.Data.Rules[2];
Apply(host, Event(1, 1, w.Hash, w.KeyOf($"r{gemRule.Uid}.row"), Click));
Apply(host, Event(6, 2, w.Hash, w.KeyOf("settings"), new byte[] { 1 }));
c.Note("Prismatic Taper -> pack 1");
panel.Warnings = () => new[] { "The RynthSort Lua script is set to start too" };
Draw(w, panel);
@ -1024,12 +1075,21 @@ namespace RynthSort.Tests
Check(body.Contains("Classes:") && body.Contains("Gem x") && body.Contains("Key x") && body.Contains("Mana Stone x"), "the rule's classes as chips");
Check(body.Contains("Add a class...") && body.Contains("Name has") && body.Contains("Remove rule"), "add a class, add a name, remove");
Check(body.Contains("Pack 3: Pack 3 (0/24) - empty") && body.Contains("Pack 7 (none)"), "the pack picker");
Check(body.Contains("Settle (s)") && body.Contains("Gap (ms)") && body.Contains("Sort during fights")
&& body.Contains("Put items in order inside packs") && body.Contains("Group by kind first"), "settings shown");
Check(body.Contains("plugin API 80"), "an engine that can't read orders: said in the settings");
Check(body.Contains("Lua script is set to start"), "warning shown");
Check(body.Contains("Last: Prismatic Taper -> pack 1"), "the last move under the status");
w.MarkSubmitted(true);
Apply(host, Event(1, 2, w.Hash, w.KeyOf("tab.settings"), Click));
Draw(w, panel);
ParseAll(host, "settings page", out _);
body = BodyText(w);
Check(body.Contains("Settle (s)") && body.Contains("Gap (ms)") && body.Contains("Sort during fights") && body.Contains("Leave alone (min)")
&& body.Contains("Put items in order inside packs") && body.Contains("Group by kind first") && body.Contains("Empty side packs"), "settings shown");
Check(body.Contains("plugin API 80"), "an engine that can't read orders: said in the settings");
Check(!body.Contains("Classes:"), "the packs aren't drawn on the settings page");
w.MarkSubmitted(true);
Apply(host, Event(1, 3, w.Hash, w.KeyOf("tab.packs"), Click));
gemRule.AddName("Opal");
gemRule.AddName("a##b");
Draw(w, panel);
@ -1160,7 +1220,7 @@ namespace RynthSort.Tests
Check(!c.Data.Rules.Contains(r) && panel.Selected == null, "Remove");
// Settings and buttons.
Send(6, "settings", new byte[] { 1 });
Send(1, "tab.settings", Click);
Send(3, "settle", BitConverter.GetBytes(12));
Send(3, "gap", BitConverter.GetBytes(50_000));
Send(2, "combat", new byte[] { 1 });
@ -1168,8 +1228,10 @@ namespace RynthSort.Tests
Send(2, "order", new byte[] { 0 });
Send(2, "orderkind", new byte[] { 1 });
Check(!c.Data.Settings.OrderInPacks && c.Data.Settings.OrderKindFirst, "the order boxes");
Send(2, "auto", new byte[] { 1 });
Check(c.Data.Settings.Auto, "auto-sort box on");
Send(2, "auto", new byte[] { 0 });
Check(!c.Data.Settings.Auto, "auto-sort box");
Check(!c.Data.Settings.Auto, "auto-sort box off");
Send(1, "job.all", Click);
Eq(c.Job, SortScope.All, "Sort now button");
Send(1, "job.unpack", Click);

View file

@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// "Put back": the last sort's moves undone (items back to the packs they came from), with
// auto-sort off first so nothing moves straight back again.
internal static partial class Program
{
private static void PutBackLoop()
{
var w = new FakeWorld();
w.Inv.Main.Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
w.Inv.Main.Items.Add(It(11, "Salvaged Iron", ObjectClasses.Salvage));
w.Inv.Packs[0].Items.Add(It(12, "Black Opal", ObjectClasses.Gem));
SortController c = Controller();
c.Data.Rules = SortRules.Defaults();
Ticks(c, w, 0, 5000);
Eq(w.Sent.Count, 3, "the sort moved three items");
Eq(c.PutBackCount, 3, "all three can be put back");
Check(c.History.Any(h => h.ItemId == 12 && h.FromId == 0x40000001 && h.ToId == 0x40000003), "each with where it came from");
Check(c.StartPutBack(), "Put back starts");
Check(!c.Data.Settings.Auto && c.Job == SortScope.PutBack, "auto-sort off first, the job asked for");
Ticks(c, w, 5000, 10_000);
Check(w.Inv.Main.Items.Any(i => i.Id == 10) && w.Inv.Main.Items.Any(i => i.Id == 11) && w.Inv.Packs[0].Items.Any(i => i.Id == 12),
"every item is back where it was");
Eq(w.Sent.Count, 6, "three moves back");
Check(c.Job == null && c.PutBackCount == 0, "done, nothing left to put back");
Eq(c.Log[0], "Put back 3 items", "the log says so");
Check(!c.StartPutBack(), "nothing to put back: it doesn't start");
Ticks(c, w, 10_000, 15_000);
Eq(w.Sent.Count, 6, "and nothing moves again (auto-sort is off)");
// Moved since by the player: that one stays where the player put it.
c.SetAuto(true);
Ticks(c, w, 15_000, 20_000);
Eq(c.PutBackCount, 3, "sorted again");
SortItem opal = w.Inv.Packs[2].Items.First(i => i.Id == 12);
w.Inv.Packs[2].Items.Remove(opal);
w.Inv.Packs[1].Items.Add(opal);
c.StartPutBack();
Ticks(c, w, 20_000, 26_000);
Check(w.Inv.Packs[1].Items.Any(i => i.Id == 12), "the opal the player moved stays");
Check(w.Inv.Main.Items.Any(i => i.Id == 10) && w.Inv.Main.Items.Any(i => i.Id == 11), "the other two went back");
Check(c.Log[0].StartsWith("Put back 2 items (1 gone", StringComparison.Ordinal), $"the log counts the one left ({c.Log[0]})");
// A new sort after a pause starts a new list; an item moved twice goes back to its first pack.
var w2 = new FakeWorld();
w2.Inv.Main.Items.Add(It(20, "Prismatic Taper", ObjectClasses.SpellComponent));
SortController c2 = Controller();
c2.Data.Rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.SpellComponent, 1) };
Ticks(c2, w2, 0, 3000);
Check(c2.History.Count == 1 && c2.History[0].FromId == Me, "to pack 1 from the main pack");
c2.Data.Rules[0].Pack = 2;
c2.Data.Rules[0].PackId = 0x40000002;
Ticks(c2, w2, 3000, 6000);
Check(c2.History.Count == 1 && c2.History[0].FromId == Me && c2.History[0].ToId == 0x40000002, "moved again: still goes back to the main pack");
w2.Inv.Main.Items.Add(It(21, "Lead Scarab", ObjectClasses.SpellComponent));
Ticks(c2, w2, 6000 + SortController.RunGapMs + 1000, 6000 + SortController.RunGapMs + 5000);
Check(c2.History.Count == 1 && c2.History[0].ItemId == 21, "a sort after a pause: only its moves");
// Stack joins aren't kept (the item is gone), and old moves fall off.
var w3 = new FakeWorld { Can = SortAbilities.All };
w3.Inv.Packs[0].Items.Add(It(30, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 7, stack: 10, max: 100));
w3.Inv.Main.Items.Add(It(31, "Prismatic Taper", ObjectClasses.SpellComponent, wcid: 7, stack: 2, max: 100));
SortController c3 = Controller();
c3.Data.Rules = SortRules.Defaults();
Ticks(c3, w3, 0, 3000);
Check(w3.Sent.Count >= 1 && w3.Sent[0].MergeInto == 30, "joined the stack in pack 1");
Eq(c3.PutBackCount, 0, "a join can't be put back");
w3.Inv.Main.Items.Add(It(32, "Salvaged Iron", ObjectClasses.Salvage));
Ticks(c3, w3, 3000, 6000);
Eq(c3.PutBackCount, 1, "a plain move can");
Ticks(c3, w3, 6000, 6000 + SortController.HistoryKeepMs + 2000);
Eq(c3.PutBackCount, 0, "after half an hour it falls off");
}
private static void PutBackPlan()
{
SortInventory inv = Inv(2, cap: 1, mainCap: 1);
inv.Main.Items.Add(It(1, "Filler", ObjectClasses.Misc));
inv.Packs[0].Items.Add(It(10, "Prismatic Taper", ObjectClasses.SpellComponent));
inv.Packs[1].Items.Add(It(11, "Black Opal", ObjectClasses.Gem));
var made = new List<MadeMove>
{
new(10, "Prismatic Taper", Me, 0x40000001, 0),
new(11, "Black Opal", 0x4000AAAA, 0x40000002, 1),
new(99, "Gone", Me, 0x40000001, 2),
};
var p = new SortPlanner();
List<SortMove> moves = p.PlanPutBack(inv, made, 0);
Eq(moves.Count, 0, "main pack full, the other's pack not carried, the third gone: nothing moves");
Check(p.View.MainFull && p.View.WaitMainFull == 1 && p.View.WaitNoPack == 1, "and the view says why");
inv.Main.Capacity = 5;
moves = p.PlanPutBack(inv, made, 0);
Check(moves.Count == 1 && moves[0].Item.Id == 10 && moves[0].DestIndex == 0 && moves[0].MergeInto == 0 && moves[0].FromIndex == 1,
"room now: the taper goes back as a stack of its own");
Check(p.PlanUnpack(inv, null, 0).All(m => m.FromIndex > 0), "unpack moves say which pack they came from");
}
}
}

View file

@ -16,7 +16,8 @@ namespace RynthSort.Tests
("on quiet", SortVerb.On, true, null), ("OFF Quiet", SortVerb.Off, true, null),
("now", SortVerb.Now, false, null), ("tidy", SortVerb.Now, false, null), ("clean", SortVerb.Clean, false, null),
("unpack", SortVerb.Unpack, false, null), ("unpack 2", SortVerb.Unpack, false, 2), ("unpack x", SortVerb.Unpack, false, null),
("unpack 0", SortVerb.Unpack, false, null), ("status", SortVerb.Status, false, null), ("help", SortVerb.Help, false, null),
("unpack 0", SortVerb.Unpack, false, null), ("back", SortVerb.Back, false, null), ("undo", SortVerb.Back, false, null), ("add 3", SortVerb.Add, false, 3), ("add", SortVerb.Add, false, null), ("add x", SortVerb.Add, false, null),
("status", SortVerb.Status, false, null), ("help", SortVerb.Help, false, null),
("?", SortVerb.Help, false, null), ("sortt", SortVerb.Unknown, false, null),
};
var seen = new HashSet<SortVerb>();
@ -35,6 +36,8 @@ namespace RynthSort.Tests
Check(SortCommand.Started(SortVerb.Clean).StartsWith("Cleaning", StringComparison.Ordinal), "clean");
Check(SortCommand.Unpacking(3).StartsWith("Emptying pack 3", StringComparison.Ordinal), "unpack 3");
Check(SortCommand.Unpacking(null).StartsWith("Emptying your side packs", StringComparison.Ordinal), "unpack");
Check(SortCommand.PuttingBack(3).StartsWith("Putting back the 3 items", StringComparison.Ordinal) && SortCommand.PuttingBack(1).Contains("1 item the"), "back");
Check(SortCommand.PuttingBack(0).StartsWith("Nothing to put back", StringComparison.Ordinal), "back with nothing to do");
string unknown = SortCommand.Unknown("sortt");
Check(unknown.StartsWith("Unknown '/rsort sortt'.", StringComparison.Ordinal) && unknown.Contains(SortCommand.Usage), "an unknown word: named, with the usage");
}

View file

@ -37,9 +37,26 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthSort\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthSort\obj\**;..\..\Plugins\RynthCore.Plugin.RynthSort\bin\**" Link="RynthSort\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
<!-- The window drawn with ImGui (Window/*.cs) compiles here too; nothing native is called. -->
<Compile Include="..\..\Plugins\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<Compile Include="..\..\Plugins\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
<Compile Include="$(EngineParser)" Link="Engine\DisplayListParser.cs" />
</ItemGroup>
<!--
The engine parser the window's lists are checked against: the sibling RynthCore checkout's (op
level 2, the released engine). To check the op level 3 lists (tables, fonts) against an engine
that has them, point it at that engine's parser:
dotnet run -c Release -p:EngineParser=<path>\DisplayListParser.cs
(in that engine's src\RynthCore.Engine\UI\ScriptWindows\).
-->
<PropertyGroup>
<EngineParser Condition="'$(EngineParser)' == ''">..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs</EngineParser>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,227 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// The window drawn with ImGui (2026-11-26, the approved design for #rynth-issues "The bag sort
// feature is lacking in UX"): its view-model (Screen/ScreenBuilder.cs), the rule changes it
// makes (Screen/RuleEdits.cs), and what the controller does for it (an item sent to a pack,
// the activity feed with times, settling items, items left alone and let go one at a time).
internal static partial class Program
{
private static SortController ScreenController(SortInventory inv, bool auto = false)
{
var w = new FakeWorld { Inv = inv };
SortController c = Controller(auto);
c.WallClock = () => new DateTime(2026, 11, 26, 14, 5, 0);
c.Tick(w, 0); // one read: the controller's last inventory and the planner's view
return c;
}
private static ScreenModel Screen(SortController c, bool layouts = false, ScreenSession? session = null) =>
ScreenBuilder.Build(c, new ScreenInputs { Character = "Someone", Server = "Testworld", WantLayouts = layouts, Session = session, CanAddSelected = true });
private static void ScreenFeedAndSettling()
{
var w = new FakeWorld();
SortController c = Controller(auto: false, settleSec: 30);
int minute = 0;
c.WallClock = () => new DateTime(2026, 11, 26, 23, minute, 0);
c.Data.Rules = SortRules.Defaults();
c.SetAuto(true);
Check(c.Feed.Count == 1 && c.Feed[0].Text == "Auto-sort on" && c.Feed[0].Time == "23:00", "auto-sort on is in the feed, with the time");
Eq(c.Log.Count, 0, "but not in the log /rsort status reads");
c.SetAuto(true);
Eq(c.Feed.Count, 1, "turning it on again adds nothing");
minute = 7;
w.Inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
Ticks(c, w, 0, 2000);
Check(c.Planner.View.Settling.Contains(10) && c.Planner.View.WaitSettle == 1, "a new item settling is named in the view");
ScreenModel m = Screen(c);
Check(m.TilesById[10].Settling, "and its tile shows the ring");
Check(m.Status.Tone == PillTone.Waiting && m.Status.Line.StartsWith("1 new item settling", StringComparison.Ordinal), $"the status says so ({m.Status.Line})");
Ticks(c, w, 2000, 33_000);
Check(w.Inv.Packs[2].Items.Any(i => i.Id == 10) && !c.Planner.View.Settling.Contains(10), "settled and moved");
Check(c.Feed[0].ItemId == 10 && c.Feed[0].Time == "23:07", "the move is in the feed with its item and time");
for (int i = 0; i < SortController.FeedMax + 5; i++) c.NoteFeed("line " + i);
Eq(c.Feed.Count, SortController.FeedMax, "the feed keeps the last few");
Eq(c.Feed[0].Text, "line " + (SortController.FeedMax + 4), "newest first");
}
private static void ScreenModelPacks()
{
SortInventory inv = DesignPacks();
SortController c = ScreenController(inv);
c.Data.Rules = StarterLayouts.Fit(StarterLayouts.Everyday, inv).Rules;
c.Data.Rules.Add(new SortRule { Pack = 3, PackId = inv.Packs[2].Id });
c.Data.Rules[^1].AddName("Black Opal");
c.Touch.Hold(inv.Main.Items[0].Id, c.Clock, TouchKind.Selected); // the Black Opal, selected in the game
ScreenModel m = Screen(c);
Check(m.Ready && m.Who == "Someone · Testworld", "ready, and whose packs");
Eq(m.Main.Count, "9 / 102", "main pack count");
Check(m.Main.Wells == 9 && !m.Main.NearlyFull, "three rows of wells in all");
Eq(m.Packs.Length, 4, "four side packs");
PackModel sack = m.Packs[0], hide = m.Packs[3], satchel = m.Packs[2];
Check(sack.Name == "Sack" && sack.Badge == "1" && sack.Where == "Top of your pack column", "the top pack");
Check(m.Packs[1].Where == "Pack 2 from the top" && hide.Where == "Bottom of your pack column", "where the others sit");
Eq(sack.Count, "3/24", "a pack's count");
Check(sack.Ghosts.Length == 1 && sack.Incoming == "+1 coming", "the taper is coming to the Sack");
Check(satchel.Ghosts.Length == 2 && satchel.Incoming == "+2 coming", "the mana stone and the key to the Satchel (the opal is left alone)");
Check(hide.Incoming == "+1 coming" && hide.Chips.Select(x => x.Label).SequenceEqual(new[] { "Food", "Healing kits", "Lockpicks" }), "the Hide Sack's kinds, A-Z, and the kit coming");
ChipModel name = satchel.Chips.Single(x => x.IsName);
Check(name.Label == "named \"Black Opal\"" && name.Name == "Black Opal" && name.Pack == 3, "a name rule is its own chip");
Check(satchel.Chips.Where(x => !x.IsName).Select(x => x.Label).SequenceEqual(new[] { "Gems", "Keys", "Mana stones" }), "the Satchel's kinds");
TileModel opal = m.TilesById[inv.Main.Items[0].Id];
Check(opal.Held && opal.HeldWhy == "You selected it just now" && !opal.Outgoing, "the opal is left alone, so not in the moves");
Check(opal.Rule == TileRule.Pack && opal.RulePack == 3 && opal.ByName && opal.RuleText == "named \"Black Opal\"", "and it goes by its name rule");
TileModel taper = m.TilesById[inv.Main.Items[1].Id];
Check(taper.Qty == "320" && taper.Outgoing && !taper.Moving && taper.KindLabel == "Spell components", "a stack's count; outgoing but nothing runs, so no lift");
Eq(m.TilesById[inv.Main.Items[8].Id].Qty, "2.4k", "thousands");
TileModel coat = m.TilesById[inv.Main.Items[6].Id];
Check(coat.Rule == TileRule.None && !coat.Outgoing, "the coat has no rule: it stays");
Eq(m.MovesCount, 5, "taper, stone, steel, kit and key would move");
RowModel first = m.Moves[0];
Check(first.Name == "Prismatic Taper" && first.Sub == "Rule: Spell components" && first.Right == "Sack", $"a move row ({first.Name}, {first.Sub}, {first.Right})");
Check(m.MovesHint.StartsWith("Nothing moves until", StringComparison.Ordinal), "auto-sort off: the hint");
Check(m.Held.Length == 1 && m.Held[0].Sub == "You selected it just now · would go to Satchel", $"left alone, and where it would go ({m.Held[0].Sub})");
Check(m.Status.Tone == PillTone.Off && m.Status.Pill == "Off" && m.Status.Line == "Nothing moves by itself. A sort would move 5 items. 1 left alone.", $"status ({m.Status.Line})");
Check(m.HoldNote == "3 min" && m.Feed.Length == 0 && m.Orphans.Length == 0 && !m.NoRules, "the rest");
Check(m.KindChoices.Single(k => k.Cls == ObjectClasses.Gem).InPack == 3 && m.KindChoices.Single(k => k.Cls == ObjectClasses.Scroll).InPack == 0,
"the picker knows which pack has a kind");
// Why it is where it is.
string Why(TileModel t) => string.Concat(ScreenText.Why(t, m).Select(r => r.Text));
Eq(Why(opal), "Goes to Satchel by the rule named \"Black Opal\", once it's no longer left alone.", "why: held, would go");
Eq(Why(coat), "No rule names it, so it stays in the main pack.", "why: no rule");
TileModel garnet = m.Packs[2].Tiles.Single(t => t.Name == "Black Garnet");
Eq(Why(garnet), "In its pack: Satchel, by the rule Gems.", "why: in its pack");
Check(ScreenText.Why(garnet, m).Count(r => r.Bold) == 2, "the pack and the rule in bold");
Eq(ScreenText.KindAndPlace(garnet, m), "Gems · in Satchel", "kind and place");
Check(ScreenText.Matches(garnet, "garn") && !ScreenText.Matches(garnet, "opal") && !ScreenText.Matches(garnet, ""), "find an item: any case; empty finds nothing");
// Busy: the moves lift; tidy: the success pill; a pack nearly full turns amber.
c.SetAuto(true);
c.StartJob(SortScope.All);
m = Screen(c);
Check(m.Busy && m.Status.Tone == PillTone.Moving && m.TilesById[taper.Id].Moving, "a sort running: the taper lifts");
var tidy = Inv(1);
tidy.PackOrderKnown = true;
tidy.Packs[0].Items.Add(It(1, "Fire Opal", ObjectClasses.Gem));
for (uint i = 0; i < 21; i++) tidy.Packs[0].Items.Add(It(10 + i, "Black Garnet", ObjectClasses.Gem));
SortController ct = ScreenController(tidy, auto: true);
ct.Data.Rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) };
ct.Tick(new FakeWorld { Inv = tidy }, 2000);
ScreenModel mt = Screen(ct);
Check(mt.Status.Tone == PillTone.Tidy && mt.Status.Pill == "All tidy" && mt.MovesCount == 0, $"all tidy ({mt.Status.Line})");
Check(mt.Packs[0].NearlyFull && mt.Packs[0].Where == "Your only side pack", "22 of 24: amber");
}
private static void ScreenModelOrphansAndLayouts()
{
SortInventory inv = DesignPacks();
SortController c = ScreenController(inv);
c.Data.Rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Scroll, 7) };
ScreenModel m = Screen(c);
Check(m.Orphans.Length == 1 && m.Orphans[0].Label == "Scrolls" && m.Orphans[0].Pack == 0, "a rule for a pack not carried");
Check(m.KindChoices.Single(k => k.Cls == ObjectClasses.Scroll).InPack == -1, "the picker says its pack isn't carried");
Eq(m.Layouts.Length, 0, "no layouts unless the popup is open");
m = Screen(c, layouts: true);
Eq(m.Layouts.Length, StarterLayouts.All.Length, "every layout");
LayoutCard every = m.Layouts[0];
Check(every.Key == "everyday" && every.Bars.Length == 4 && every.Bars[3].Length == 3 && every.Bars[3][0] == Kinds.Kits, "the Hide Sack's bar: kits, lockpicks, food");
Eq(every.Meta, "6 would move", "what Everyday would move (the opal too: nothing is held here)");
Check(every.Rows[3].PackName == "Hide Sack" && every.Rows[3].Chips.Length == 3, "the preview rows");
Check(every.Left.StartsWith("Stay in the main pack: ", StringComparison.Ordinal) && every.Left.Contains("trade notes") && every.Left.Contains("armor"),
$"what stays in the main pack ({every.Left})");
Check(every.Replaces.Length > 0, "it replaces the rules there are");
LayoutCard basics = m.Layouts.Single(l => l.Key == "basics");
Check(basics.Bars[3].Length == 0 && basics.Rows[3].Chips.Length == 0, "Just the basics leaves the Hide Sack free");
var none = ScreenBuilder.Build(c, new ScreenInputs());
Check(!none.Ready && none.NotReady.StartsWith("Log in", StringComparison.Ordinal), "nobody logged in");
Eq(ScreenBuilder.MainWells(0, 102), 18, "an empty main pack: three rows");
Eq(ScreenBuilder.MainWells(20, 102), 4, "a row past the last item");
Eq(ScreenBuilder.MainWells(101, 102), 1, "never past the capacity");
Check(Kinds.Label(ObjectClasses.ManaStone) == "Mana stones" && Kinds.Label(ObjectClasses.MeleeWeapon) == "Melee weapons", "sentence-case kinds");
Check(Kinds.Initials("Amuli Shadow Coat") == "AC" && Kinds.Qty(1) == "" && Kinds.Qty(12000) == "12k", "initials and counts");
}
private static void ScreenRuleEdits()
{
SortInventory inv = DesignPacks();
SortController c = ScreenController(inv);
List<SortRule> rules = c.Data.Rules;
rules.Clear();
rules.AddRange(StarterLayouts.Fit(StarterLayouts.Everyday, inv).Rules);
SortView view = SortPreview.Build(inv, rules, default, null).View;
// "All gems" dropped on the Hide Sack: gems leave the Satchel.
EditResult r = RuleEdits.SendKind(rules, view, 4, ObjectClasses.Gem);
Check(r.Changed && r.Text == "All gems now go to Hide Sack (taken from Satchel). Nothing has moved yet.", $"kind: {r.Text}");
Check(rules.Count(x => x.HasClass(ObjectClasses.Gem)) == 1 && Views.SortPanelProxy.Shown(view, rules.First(x => x.HasClass(ObjectClasses.Gem))) == 4, "one pack has gems now");
Check(RuleEdits.SendKind(rules, view, 4, ObjectClasses.Gem).Text == "Gems already go to Hide Sack.", "again: nothing changes");
Check(!RuleEdits.SendKind(rules, view, 9, ObjectClasses.Gem).Changed, "a pack not carried");
// A kind sent to a pack with no rules: a new rule there.
var empty = new List<SortRule>();
RuleEdits.SendKind(empty, view, 2, ObjectClasses.Salvage);
Check(empty.Count == 1 && empty[0].PackId == inv.Packs[1].Id && empty[0].HasClass(ObjectClasses.Salvage), "a new rule tied to the pack");
// "Only "Black Opal"" on the Backpack: a name rule; it leaves the Satchel's rules and beats the gems kind.
rules.Add(new SortRule { Pack = 3, PackId = inv.Packs[2].Id });
rules[^1].AddName("Black Opal");
SortItem opal = inv.Main.Items[0];
r = RuleEdits.SendName(rules, view, 2, opal);
Check(r.Changed && r.Text == "\"Black Opal\" now goes to Backpack. Nothing has moved yet.", $"name: {r.Text}");
Check(rules.Count(x => x.HasName("Black Opal")) == 1, "the name is in one pack's rules only (the Satchel's emptied rule went)");
Eq(Views.SortPanelProxy.Shown(view, SortRules.RuleFor(rules, opal)!), 2, "the name beats the kind: the opal goes to the Backpack");
Check(!RuleEdits.SendName(rules, view, 2, opal).Changed, "again: nothing changes");
// A chip's x.
SortRule gemRule = rules.First(x => x.HasClass(ObjectClasses.Gem));
bool alone = gemRule.Classes.Count == 1 && gemRule.Names.Count == 0;
r = RuleEdits.RemoveEntry(rules, view, gemRule.Uid, false, ObjectClasses.Gem, "");
Check(r.Changed && r.Text == "Gems no longer go to Hide Sack.", $"x: {r.Text}");
Check(!rules.Any(x => x.HasClass(ObjectClasses.Gem)) && (!alone || !rules.Contains(gemRule)), "gone, and an emptied rule with it");
Check(!RuleEdits.RemoveEntry(rules, view, 123456, false, 1, "").Changed, "a rule that's gone");
SortRule off = SortRule.ForClass(ObjectClasses.Scroll, 1);
off.On = false;
rules.Add(off);
Check(RuleEdits.TurnOn(rules, off.Uid).Changed && off.On && !RuleEdits.TurnOn(rules, off.Uid).Changed, "a faded chip turns its rule on");
// Toasts and the one Undo.
var session = new ScreenSession();
int before = rules.Count;
string snapshot = string.Join("|", rules.Select(SortRules.Describe));
Check(session.Edit(rules, l => RuleEdits.SendKind(l, view, 1, ObjectClasses.Plant), 1000), "a change");
Check(session.Toast != null && session.Toast.CanUndo && session.Toast.UntilMs == 1000 + ScreenSession.ToastMs, "a toast with Undo");
int seq = session.Toast!.Seq;
Check(!session.Edit(rules, l => RuleEdits.SendKind(l, view, 1, ObjectClasses.Plant), 2000), "no change");
Check(session.Toast != null && !session.Toast.CanUndo && session.Toast.Seq > seq && session.CanUndo, "says why, no Undo button, the Undo kept");
Check(session.Undo(rules, 3000) && rules.Count == before && string.Join("|", rules.Select(SortRules.Describe)) == snapshot, "Undo puts the rules back");
Check(!session.Undo(rules, 3000) && session.Toast!.Text == "Rules put back as they were.", "once");
session.Expire(3000 + ScreenSession.ToastMs);
Check(session.Toast == null, "the toast goes after its time");
r = RuleEdits.UseLayout(rules, inv, StarterLayouts.Basics);
Check(r.Changed && rules.Count == 3 && r.Text.StartsWith("Rules set from Just the basics", StringComparison.Ordinal), "a layout replaces the rules");
Check(!RuleEdits.UseLayout(rules, null, StarterLayouts.Basics).Changed && !RuleEdits.UseLayout(rules, Inv(0), StarterLayouts.Basics).Changed, "no packs read, or none carried");
}
}
}
namespace RynthSort.Tests.Views
{
internal static class SortPanelProxy
{
public static int Shown(RynthCore.Plugin.RynthSort.Sorting.SortView v, RynthCore.Plugin.RynthSort.Sorting.SortRule r) =>
RynthCore.Plugin.RynthSort.Views.SortPanel.ShownPack(v, r);
}
}

View file

@ -0,0 +1,132 @@
using System;
using System.Linq;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// What the controller does for the window drawn with ImGui (2026-11-26, the approved design for
// #rynth-issues "The bag sort feature is lacking in UX"): a layout gives a pack the kind it
// already holds before kinds no pack holds; one item left alone or let go; an item sent to a
// pack from the window without a rule ("Just move it", "Send to"), then left alone.
internal static partial class Program
{
/// <summary>The design's sample character: four packs, the main pack full of loot.</summary>
private static SortInventory DesignPacks()
{
SortInventory inv = Inv(4);
string[] names = { "Sack", "Backpack", "Satchel", "Hide Sack" };
for (int i = 0; i < 4; i++) inv.Packs[i].Name = names[i];
inv.PackOrderKnown = true;
inv.OrderSource = PackOrderSource.Known;
uint id = 100;
void Main(string n, int cls, int stack = 1) => inv.Main.Items.Add(It(id++, n, cls, stack: stack, max: stack > 1 ? 5000 : 1));
void In(int pack, string n, int cls, int stack = 1) => inv.Packs[pack].Items.Add(It(id++, n, cls, stack: stack, max: stack > 1 ? 5000 : 1));
Main("Black Opal", ObjectClasses.Gem);
Main("Prismatic Taper", ObjectClasses.SpellComponent, 320);
Main("Mana Stone", ObjectClasses.ManaStone);
Main("Salvaged Steel", ObjectClasses.Salvage);
Main("Treated Healing Kit", ObjectClasses.HealingKit);
Main("Trade Note (250,000)", ObjectClasses.TradeNote, 4);
Main("Amuli Shadow Coat", ObjectClasses.Armor);
Main("Legendary Key", ObjectClasses.Key);
Main("Pyreal", ObjectClasses.Money, 2400);
In(0, "Lead Scarab", ObjectClasses.SpellComponent, 40);
In(0, "Hyssop", ObjectClasses.SpellComponent, 75);
In(0, "Powdered Agate", ObjectClasses.SpellComponent, 60);
In(1, "Salvaged Iron", ObjectClasses.Salvage);
In(1, "Salvaged Granite", ObjectClasses.Salvage);
In(2, "Fire Opal", ObjectClasses.Gem);
In(2, "Black Garnet", ObjectClasses.Gem);
In(3, "Health Elixir", ObjectClasses.Food, 6);
In(3, "Peppermint Stick", ObjectClasses.Food, 20);
In(3, "Intricate Lockpick", ObjectClasses.Lockpick);
return inv;
}
private static void LayoutHeldKindsFirst()
{
// The design's Everyday: the Hide Sack already holds kits, lockpicks and food, so it keeps them.
SortInventory inv = DesignPacks();
LayoutPlan plan = StarterLayouts.Fit(StarterLayouts.Everyday, inv);
Eq(string.Join(",", plan.Placed.Select(x => x.Group.Key + x.Pack)), "components1,salvage2,gems3,supplies4",
"each pack keeps the kind it holds; the Hide Sack gets kits, lockpicks and food");
Eq(string.Join(",", plan.Left.Select(g => g.Key)), "notes,scrolls", "trade notes and scrolls (held by no pack) stay in the main pack");
Eq(plan.AlreadyThere, 10, "the ten items in the side packs are already where their kind goes");
// A kind no pack holds still gets the roomiest pack left, most wanted first.
SortInventory two = Inv(3);
two.Packs[2].Items.Add(It(1, "Health Elixir", ObjectClasses.Food));
LayoutPlan p2 = StarterLayouts.Fit(StarterLayouts.Everyday, two);
Eq(string.Join(",", p2.Placed.Select(x => x.Group.Key + x.Pack)), "components1,gems2,supplies3",
"the held kind (supplies, fifth in the list) wins its pack before salvage (third, held by none)");
Eq(string.Join(",", p2.Left.Select(g => g.Key)), "salvage,notes,scrolls", "salvage waits for a pack");
Check(StarterLayouts.Everyday.Blurb.Length <= 120, "the Everyday line still fits");
}
private static void HoldOneItem()
{
var t = new TouchWatch();
t.Hold(7, 1000, TouchKind.Chosen);
Check(t.IsHeld(7, 2000, 60_000), "asked to leave it: held");
Check(t.TryGetHeld(7, 2000, 60_000, out _, out TouchKind k) && k == TouchKind.Chosen && TouchWatch.Words(k) == "you asked to leave it", "and says why");
Check(!t.IsHeld(7, 2000, 0), "the hold setting at 0 holds nothing");
Check(t.Release(7) && !t.IsHeld(7, 2000, 60_000), "Let RynthSort move it: no longer held");
Check(!t.Release(7), "releasing again does nothing");
t.Hold(0, 1000, TouchKind.Sent);
Eq(t.HeldCount(1000, 60_000), 0, "no item, no hold");
}
private static void SendFromWindow()
{
var w = new FakeWorld();
w.Inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
SortController c = Controller(auto: true);
c.Data.Rules = SortRules.Defaults(); // gems go to pack 3
c.WallClock = () => new DateTime(2026, 11, 26, 9, 30, 0);
Check(c.StartSend(10, 0x40000001), "Just move it: to pack 1, no rule");
Check(c.Send != null && c.IsHeld(10), "left alone from now, so auto-sort doesn't take it meanwhile");
Ticks(c, w, 16, 3000);
Check(w.Inv.Packs[0].Items.Any(i => i.Id == 10), "it went to pack 1");
Check(w.Sent.Count == 1 && w.Sent[0].MergeInto == 0, "one plain move, and auto-sort didn't move it on to pack 3");
Check(c.IsHeld(10) && c.Touch.TryGetHeld(10, c.Clock, c.HoldMs, out _, out TouchKind k) && k == TouchKind.Sent, "held as sent there");
Eq(c.PutBackCount, 0, "not a sort: Put back leaves it");
Check(c.Feed.Count > 0 && c.Feed[0].ItemId == 10 && c.Feed[0].Time == "09:30" && c.Feed[0].Text.Contains("you sent it"), $"the feed says so, with the time ({c.Feed[0].Text})");
Check(c.Send == null && !c.HasMoveOut, "done");
// Waits while the way isn't clear, and is dropped after the wait.
w.Gate = new GateInputs { Looting = true };
c.StartSend(10, Me);
Ticks(c, w, 3000, 5000);
Check(w.Inv.Packs[0].Items.Any(i => i.Id == 10) && c.Paused && c.Send != null, "looting: it waits");
w.Gate = default;
Ticks(c, w, 5000, 8000);
Check(w.Inv.Main.Items.Any(i => i.Id == 10), "the way clear: back to the main pack");
c.StartSend(10, 0x40000002);
w.Gate = new GateInputs { Looting = true };
Ticks(c, w, 8000, 8000 + SortController.SendWaitMs + 1000);
Check(c.Send == null && w.Inv.Main.Items.Any(i => i.Id == 10), "too long: dropped, the item stays");
Check(c.Log[0].StartsWith("A move you asked for was dropped", StringComparison.Ordinal), "and the log says so");
// An item that isn't in the packs, a pack that isn't carried, a full pack.
w.Gate = default;
long t0 = 8000 + SortController.SendWaitMs + 2000;
c.StartSend(999, 0x40000001);
Ticks(c, w, t0, t0 + 2000);
Check(c.Log[0].Contains("isn't in your packs"), "an item gone: dropped");
c.StartSend(10, 0x4000FFFF);
Ticks(c, w, t0 + 2000, t0 + 4000);
Check(c.Log[0].Contains("that pack isn't carried"), "a pack not carried: not moved");
Check(!c.StartSend(0, 0x40000001) && !c.StartSend(10, 0), "no item or no pack: nothing starts");
var full = new FakeWorld { Inv = Inv(1, cap: 1) };
full.Inv.Packs[0].Items.Add(It(1, "Filler", ObjectClasses.Misc));
full.Inv.Main.Items.Add(It(2, "Black Opal", ObjectClasses.Gem));
SortController cf = Controller(auto: false);
cf.Tick(full, 0);
cf.StartSend(2, 0x40000001);
Ticks(cf, full, 16, 1000);
Check(full.Sent.Count == 0 && cf.Log[0].Contains("is full"), "a full pack: not moved, and why");
}
}
}

View file

@ -0,0 +1,62 @@
using System.Linq;
using System.Text.Json;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Screen;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// The window drawn with ImGui (2026-11-26): what the engine is told about it (the sections
// manifest), and the pop-in of tiles that just arrived in another pack. Nothing native runs here.
internal static partial class Program
{
private static void WindowManifest()
{
using JsonDocument doc = JsonDocument.Parse(RynthSortPlugin.Manifest);
JsonElement root = doc.RootElement;
Eq(root.GetProperty("version").GetInt32(), 1, "manifest version");
JsonElement[] windows = root.GetProperty("windows").EnumerateArray().ToArray();
Eq(windows.Length, 1, "one window");
JsonElement w = windows[0];
Check(w.GetProperty("title").GetString() == "RynthSort" && w.GetProperty("surface").GetString() == RynthSortPlugin.WindowSurface,
"the RynthSort title (the old script window's, which it replaces) and its surface");
Check(w.GetProperty("chrome").GetString() == "none" && w.GetProperty("scale").GetString() == "draw" && w.GetProperty("edgeToEdge").GetBoolean(),
"frameless, drawn at its own size (Ctrl+wheel), edge to edge");
Check(!w.TryGetProperty("fitHeight", out _), "players size it: not fitted to its content");
Check(!w.GetProperty("bar").GetBoolean(), "no bar button (the Inventory's Sort button and /rsort open it, as before)");
Check(w.GetProperty("minWidth").GetInt32() <= 360 && w.GetProperty("width").GetInt32() >= 1000, "it can be narrow (one column) and starts wide (three)");
Check(w.GetProperty("icon").GetString()!.Length == 1, "one glyph for an icon");
Eq(new RynthSortPlugin().SectionsJson(), "{\"version\":1}", "an engine without frameless windows is told of none (the script window stays)");
}
private static void WindowArrivals()
{
SortInventory inv = DesignPacks();
SortController c = ScreenController(inv);
var a = new Arrivals();
ScreenModel m1 = Screen(c);
a.Update(m1, 10.0);
uint taper = inv.Main.Items[1].Id;
Eq(a.Progress(taper, 10.0), 1f, "the first view pops nothing in");
// The taper moves to the Sack: in the next view it has just arrived.
SortItem item = inv.Main.Items[1];
inv.Main.Items.Remove(item);
inv.Packs[0].Items.Add(item);
ScreenModel m2 = Screen(c);
a.Update(m2, 20.0);
Eq(a.Progress(taper, 20.0), 0f, "it arrived just now");
Check(a.Progress(taper, 20.3) > 0.4f && a.Progress(taper, 20.3) < 0.6f, "half way through the pop-in");
Eq(a.Progress(taper, 21.0), 1f, "and done after it");
Eq(a.Progress(inv.Main.Items[0].Id, 20.0), 1f, "an item that stayed doesn't pop");
a.Update(m2, 30.0);
Eq(a.Progress(taper, 30.0), 1f, "the same view again changes nothing");
// Another character's view starts fresh.
var other = new ScreenModel { Ready = true, Who = "Someone else", Version = m2.Version + 1000 };
other.TilesById[taper] = new TileModel { Id = taper, Where = 3 };
a.Update(other, 40.0);
Eq(a.Progress(taper, 40.0), 1f, "another character: nothing pops");
}
}
}