Snapshot for release 2026.10.12.1 (internal 8d252bd)

This commit is contained in:
Tom Bohar 2026-10-12 00:33:13 -04:00
commit 3c4f093e3d
60 changed files with 5748 additions and 602 deletions

View file

@ -0,0 +1,500 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// RynthSort v3: rules with several classes and names (and their migration), the order inside
// packs, the side packs' top-to-bottom order, stacks joined in place, and that auto-sort runs out
// of moves on a fixed inventory instead of moving items back and forth.
internal static partial class Program
{
// ── Rules with several entries ──────────────────────────────────────
private static void MultiRules()
{
var armor = It(1, "Gold Breastplate", ObjectClasses.Armor);
var shirt = It(2, "Flared Shirt", ObjectClasses.Clothing);
var sword = It(3, "Tachi", ObjectClasses.MeleeWeapon);
var shield = It(4, "Kite Shield", ObjectClasses.Armor);
var opal = It(5, "Black Opal", ObjectClasses.Gem);
var gear = SortRule.For(4, new[] { ObjectClasses.Armor, ObjectClasses.Clothing, ObjectClasses.MeleeWeapon });
Check(SortRules.Matches(gear, armor) && SortRules.Matches(gear, shirt) && SortRules.Matches(gear, sword), "one rule, three classes: any of them matches");
Check(!SortRules.Matches(gear, opal), "not the others");
var mixed = SortRule.For(5, new[] { ObjectClasses.Gem }, "Shield", "Pyreal");
Check(SortRules.Matches(mixed, shield) && SortRules.Matches(mixed, opal), "classes and names in one rule: either matches");
var rules = new List<SortRule> { gear, mixed };
Eq(SortRules.RuleFor(rules, shield)?.Pack, 5, "the shield's name beats the armor class");
Eq(SortRules.RuleFor(rules, armor)?.Pack, 4, "other armor by class");
Check(!gear.AddClass(ObjectClasses.Armor) && gear.Classes.Count == 3, "a class is in a rule once");
Check(mixed.AddName(" Mote ") && mixed.HasName("mote") && !mixed.AddName("MOTE") && !mixed.AddName(" "), "names trimmed, once in any case, never blank");
Check(mixed.RemoveName("PYREAL") && !mixed.HasName("Pyreal"), "removed in any case");
Check(SortRule.Clean(new string('x', 80)).Length == SortRule.MaxNameLength, "names cut to 64");
Eq(SortRules.Describe(gear), "Armor, Clothing, Melee Weapon", "described A-Z");
Eq(SortRules.Describe(mixed), "Gem, name has \"Mote\", name has \"Shield\"", "classes first, then names, A-Z");
Eq(SortRules.Describe(new SortRule()), "(empty: add a class or a name)", "an empty rule");
Check(!SortRules.Matches(new SortRule(), opal), "an empty rule matches nothing");
Check(gear.SameAs(SortRule.For(4, new[] { ObjectClasses.MeleeWeapon, ObjectClasses.Armor, ObjectClasses.Clothing })), "same entries in another order: the same rule");
Check(!gear.SameAs(SortRule.For(5, new[] { ObjectClasses.MeleeWeapon, ObjectClasses.Armor, ObjectClasses.Clothing })), "another pack: not the same");
SortRule copy = mixed.Clone();
copy.AddClass(ObjectClasses.Key);
Check(!mixed.HasClass(ObjectClasses.Key) && copy.Uid != mixed.Uid, "a clone is its own rule");
var list = new List<SortRule> { SortRule.ForName("Zircon", 1), new SortRule { Pack = 1 }, SortRule.ForClass(ObjectClasses.Armor, 1), SortRule.ForClass(ObjectClasses.Gem, 1) };
list.Sort(SortRules.CompareForList);
Check(SortRules.Describe(list[0]) == "Armor" && SortRules.Describe(list[1]) == "Gem" && list[2].HasName("Zircon") && list[3].IsEmpty, "listed A-Z under a pack, empty last");
Eq(SortRules.Defaults().Count, 3, "defaults: components, salvage, and gems/stones/keys as one rule");
Check(SortRules.Defaults()[2].Classes.Count == 3, "the third default rule holds three classes");
}
private static void RuleMigration()
{
SortStore st = TempStore("migration");
string own = st.PathFor("S", "Old");
Directory.CreateDirectory(Path.GetDirectoryName(own)!);
// A version 2 file (2026-10-11): one class or name per rule, ids, the fix done.
File.WriteAllText(own, "{\"version\":2,\"rules\":["
+ "{\"on\":true,\"kind\":\"class\",\"class\":12,\"text\":\"\",\"pack\":1,\"packId\":1073741825,\"packNote\":\"Sack - Components\"},"
+ "{\"on\":false,\"kind\":\"name\",\"class\":12,\"text\":\"Ink of\",\"pack\":2,\"packId\":1073741826},"
+ "{\"on\":true,\"kind\":\"name\",\"class\":12,\"text\":\"\",\"pack\":3}],"
+ "\"settings\":{\"auto\":true},\"packsFixed\":true}");
CharacterSortData d = st.Load("S", "Old", out string? problem);
Check(problem == null && d.Rules.Count == 3 && d.PacksFixed, "version 2 loads");
Check(d.Rules[0].Classes.SequenceEqual(new[] { ObjectClasses.SpellComponent }) && d.Rules[0].Names.Count == 0
&& d.Rules[0].PackId == 0x40000001 && d.Rules[0].PackNote == "Sack - Components", "a class rule: one class, its pack kept");
Check(d.Rules[1].Names.SequenceEqual(new[] { "Ink of" }) && d.Rules[1].Classes.Count == 0 && !d.Rules[1].On && d.Rules[1].PackId == 0x40000002,
"a name rule: one name (not its unused class), off stays off");
Check(d.Rules[2].IsEmpty, "a blank name rule matched nothing and still doesn't");
Check(d.Settings.OrderInPacks && !d.Settings.OrderKindFirst, "the order settings at their defaults");
// Saved as version 3, with the old fields too (an older RynthSort reads the first entry).
d.Rules[0].AddClass(ObjectClasses.Salvage);
d.Rules[0].AddName("Taper");
Check(st.Save("S", "Old", d) == null, "saved");
string json = File.ReadAllText(own);
Check(json.Contains("\"version\": 3") && json.Contains("\"classes\"") && json.Contains("\"names\""), "version 3 with lists");
using (var doc = System.Text.Json.JsonDocument.Parse(json))
{
var r0 = doc.RootElement.GetProperty("rules")[0];
Check(r0.GetProperty("kind").GetString() == "class" && r0.GetProperty("class").GetInt32() == ObjectClasses.SpellComponent, "old fields: the first class");
var r2 = doc.RootElement.GetProperty("rules")[2];
Check(r2.GetProperty("kind").GetString() == "name" && r2.GetProperty("text").GetString() == "", "an empty rule reads as a blank name rule to an older RynthSort");
var r1 = doc.RootElement.GetProperty("rules")[1];
Check(r1.GetProperty("kind").GetString() == "name" && r1.GetProperty("text").GetString() == "Ink of", "a name-only rule: its name the old way");
}
CharacterSortData back = st.Load("S", "Old", out problem);
Check(problem == null && back.Rules[0].Classes.Count == 2 && back.Rules[0].HasClass(ObjectClasses.Salvage) && back.Rules[0].HasName("taper"), "version 3 reads back whole");
// Odd lists: non-numbers and bad strings skipped, duplicates once, the old fields ignored when lists are there.
File.WriteAllText(own, "{\"version\":3,\"rules\":[{\"classes\":[11,\"x\",11,-3,13.0],\"names\":[\"Opal\",5,\"opal\",\" \"],\"kind\":\"class\",\"class\":39,\"pack\":2}]}");
CharacterSortData odd = st.Load("S", "Old", out _);
Check(odd.Rules[0].Classes.SequenceEqual(new[] { ObjectClasses.Gem, ObjectClasses.Key }) && odd.Rules[0].Names.SequenceEqual(new[] { "Opal" }), "lists cleaned; old fields ignored");
// The Lua script's rules read the same way (one entry each) and still compare as its own.
SortStore imp = TempStore("migration-lua");
string lua = imp.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
CharacterSortData fresh = imp.Load("DreamWeave", "Drakkon", out _);
Check(fresh.Rules.All(x => x.Classes.Count == 1 && x.Names.Count == 0) && fresh.Rules[0].SameAs(fresh.LuaRules![0]), "Lua rules: one class each, SameAs their file");
}
// ── Order inside a pack ─────────────────────────────────────────────
private static List<SortItem> Items(params string[] names)
{
var list = new List<SortItem>();
for (int i = 0; i < names.Length; i++) list.Add(It(100 + (uint)i, names[i], ObjectClasses.Misc));
return list;
}
private static string Names(IEnumerable<SortItem> items) => string.Join(",", items.Select(i => i.Name));
/// <summary>Runs NextMove (every item movable) until it stops; the moves it took.</summary>
private static int SortByMoves(List<SortItem> items, bool kindFirst, Dictionary<uint, int>? perItem = null, int limit = 1000)
{
int moves = 0;
while (moves < limit && PackOrder.NextMove(items, kindFirst, _ => true, out SortItem it, out int at))
{
PackOrder.Apply(items, it, at);
moves++;
if (perItem != null) perItem[it.Id] = perItem.TryGetValue(it.Id, out int n) ? n + 1 : 1;
}
return moves;
}
private static bool InOrder(IReadOnlyList<SortItem> items, bool kindFirst)
{
for (int i = 1; i < items.Count; i++)
if (PackOrder.Compare(items[i - 1], items[i], kindFirst) > 0) return false;
return true;
}
private static void InPackOrder()
{
// The order: A-Z any case; like names together; then the stack kind; then the id.
var a = It(5, "black opal", ObjectClasses.Gem, wcid: 2);
var b = It(4, "Black Opal", ObjectClasses.Gem, wcid: 2);
var c2 = It(3, "Black Opal", ObjectClasses.Gem, wcid: 1);
var d = It(9, "Amber", ObjectClasses.Misc);
var list = new List<SortItem> { a, b, c2, d };
list.Sort((x, y) => PackOrder.Compare(x, y, false));
Eq(string.Join(",", list.Select(i => i.Id)), "9,3,4,5", "Amber; then the Black Opals: same name together, by kind, by id");
var armor = It(20, "Zircon Plate", ObjectClasses.Armor);
var gem = It(21, "Agate", ObjectClasses.Gem);
Check(PackOrder.Compare(armor, gem, false) > 0 && PackOrder.Compare(armor, gem, true) < 0, "kind first: Armor before Gem whatever the names");
// One item that arrived at the end: one move puts it in its place.
var items = Items("Amber", "Bone", "Coal", "Dust", "Agate");
Check(PackOrder.NextMove(items, false, _ => true, out SortItem it, out int at) && it.Name == "Agate" && at == 0, "Agate to slot 0");
PackOrder.Apply(items, it, at);
Check(InOrder(items, false) && !PackOrder.NextMove(items, false, _ => true, out _, out _), "then in order: no move");
// One item at the top that belongs at the bottom: one move, not four.
items = Items("Zinc", "Amber", "Bone", "Coal", "Dust");
Eq(SortByMoves(items, false), 1, "Zinc to the end in one move");
Eq(Names(items), "Amber,Bone,Coal,Dust,Zinc", "in order");
// Reversed: n - 1 moves.
items = Items("E", "D", "C", "B", "A");
Eq(SortByMoves(items, false), 4, "reversed five: four moves");
Check(InOrder(items, false), "in order");
// A move "counted without it": moving down past others.
items = Items("B", "A", "C");
Check(PackOrder.NextMove(items, false, _ => true, out it, out at), "a move");
PackOrder.Apply(items, it, at);
Eq(Names(items), "A,B,C", $"{it.Name} to {at}");
// Where an arriving item goes.
items = Items("Amber", "Coal", "Dust");
Eq(PackOrder.InsertAt(items, It(1, "Bone", ObjectClasses.Misc), false), 1, "Bone between Amber and Coal");
Eq(PackOrder.InsertAt(items, It(1, "Zinc", ObjectClasses.Misc), false), 3, "Zinc at the end");
Eq(PackOrder.InsertAt(items, It(1, "Aaa", ObjectClasses.Misc), false), 0, "Aaa first");
Eq(PackOrder.InsertAt(new List<SortItem>(), It(1, "X", ObjectClasses.Misc), false), 0, "an empty pack");
// An item that can't move now isn't picked; another is.
items = Items("C", "B", "A");
Check(PackOrder.NextMove(items, false, x => x.Name != "A", out it, out _) && it.Name != "A", "a blocked item is skipped");
Check(!PackOrder.NextMove(Items("B", "A"), false, x => false, out _, out _), "nothing movable: no move");
Eq(PackOrder.OutOfPlace(Items("Zinc", "Amber", "Bone"), false), 1, "one out of place");
Eq(PackOrder.OutOfPlace(Items("Amber", "Bone"), false), 0, "in order");
Check(!PackOrder.AllNamed(new List<SortItem> { It(1, "", ObjectClasses.Misc) }), "an unnamed item: wait for its name");
// Every order of up to 7 items: in order after at most n - (longest run) moves, each item moved at most twice.
int worstPerItem = 0;
for (int n = 1; n <= 7; n++)
{
foreach (int[] perm in Permutations(n))
{
var p = perm.Select(i => It(100 + (uint)i, ((char)('A' + i)).ToString(), ObjectClasses.Misc)).ToList();
bool[] kept = PackOrder.Kept(PackOrder.Ranks(p, false));
int bound = kept.Count(x => !x);
var per = new Dictionary<uint, int>();
int moves = SortByMoves(p, false, per);
if (!InOrder(p, false) || moves > bound) { Check(false, $"order {string.Join("", perm)}: {moves} moves (bound {bound}), in order {InOrder(p, false)}"); goto done; }
worstPerItem = Math.Max(worstPerItem, per.Values.DefaultIfEmpty(0).Max());
}
}
Check(true, "every order of 1-7 items sorts within n - (longest run) moves");
done:
Check(worstPerItem <= 2, $"no item moved more than twice ({worstPerItem})");
// Bigger packs, shuffled the same way every run.
var rnd = new Random(1234);
for (int round = 0; round < 40; round++)
{
int n = 10 + rnd.Next(93);
var p = Enumerable.Range(0, n).Select(i => It(1000 + (uint)i, "Item " + rnd.Next(60).ToString("D2"), ObjectClasses.Misc, wcid: (uint)rnd.Next(3))).OrderBy(_ => rnd.Next()).ToList();
int bound = PackOrder.OutOfPlace(p, round % 2 == 0);
var per = new Dictionary<uint, int>();
int moves = SortByMoves(p, round % 2 == 0, per);
if (!InOrder(p, round % 2 == 0) || moves > bound || per.Values.DefaultIfEmpty(0).Max() >= SortPlanner.MaxReorders)
{
Check(false, $"round {round}: {n} items, {moves} moves (bound {bound}), most per item {per.Values.DefaultIfEmpty(0).Max()}");
break;
}
}
Check(true, "40 shuffled packs of 10-102 items sort within the bound, under the per-item backstop");
}
private static IEnumerable<int[]> Permutations(int n)
{
var a = Enumerable.Range(0, n).ToArray();
yield return (int[])a.Clone();
while (true)
{
int i = n - 2;
while (i >= 0 && a[i] >= a[i + 1]) i--;
if (i < 0) yield break;
int j = n - 1;
while (a[j] <= a[i]) j--;
(a[i], a[j]) = (a[j], a[i]);
Array.Reverse(a, i + 1, n - i - 1);
yield return (int[])a.Clone();
}
}
private static void SlotOrders()
{
var pack = new SortPack { Id = 0x40000001 };
pack.Items.AddRange(Items("A", "B", "C")); // ids 100, 101, 102 (id order)
Check(pack.ApplyOrder(new uint[] { 102, 100, 101 }, 3) && pack.OrderKnown, "a list naming exactly the items read");
Eq(string.Join(",", pack.Items.Select(i => i.Id)), "102,100,101", "items in slot order");
Check(!pack.ApplyOrder(new uint[] { 102, 100 }, 2) && !pack.OrderKnown, "one short (a move behind): not known");
Check(!pack.ApplyOrder(new uint[] { 102, 100, 999 }, 3) && !pack.OrderKnown, "an id not read: not known");
Check(!pack.ApplyOrder(new uint[] { 102, 102, 100 }, 3) && !pack.OrderKnown, "an id twice: not known");
Eq(pack.Items.Count, 3, "a refused list leaves the items");
Check(pack.ApplyOrder(new uint[] { 100, 101, 102, 7 }, 3), "only the count given is read");
// The side packs, top first; foci in the list are fine.
SortInventory inv = Inv(3); // ids ...01, 02, 03 (id order)
Check(inv.ApplyPackOrder(new uint[] { 0x40000003, 0x40000F01, 0x40000001, 0x40000002 }, 4) && inv.PackOrderKnown, "pack column order");
Eq(string.Join(",", inv.Packs.Select(p => p.Id & 0xF)), "3,1,2", "pack 1 is the top pack");
SortInventory inv2 = Inv(3);
Check(!inv2.ApplyPackOrder(new uint[] { 0x40000003, 0x40000001 }, 2) && !inv2.PackOrderKnown, "a pack missing from the list: not known");
Eq(string.Join(",", inv2.Packs.Select(p => p.Id & 0xF)), "1,2,3", "id order kept");
// A rule's number follows its pack to its new place; the Lua fix still reads id order.
var rule = SortRule.ForClass(ObjectClasses.Gem, 1);
rule.PackId = 0x40000003;
Check(PackFix.Sync(new List<SortRule> { rule }, inv) && rule.Pack == 1, "the top pack is now pack 1");
}
// ── The planner keeping every pack tidy ─────────────────────────────
private static void PlanInPack()
{
var rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) };
// A route into a pack whose order is known names the item's slot there.
SortInventory inv = Inv(1);
inv.Packs[0].Items.AddRange(new[] { It(50, "Agate", ObjectClasses.Gem), It(51, "Opal", ObjectClasses.Gem) });
inv.Packs[0].OrderKnown = true;
inv.Main.Items.Add(It(10, "Jet", ObjectClasses.Gem));
List<SortMove> m = new SortPlanner().Plan(inv, rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Route && m[0].Placement == 1, "Jet goes between Agate and Opal");
inv.Packs[0].OrderKnown = false;
m = new SortPlanner().Plan(inv, rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Check(m.Count == 1 && m[0].Placement == -1, "order unknown: the first empty slot");
m = new SortPlanner().Plan(inv, rules, SortScope.All, true, 0, 0);
Check(m.Count == 1 && m[0].Placement == -1, "without the options: as before");
// Nothing to route: stacks first, then order.
inv = Inv(1);
inv.Packs[0].OrderKnown = true;
inv.Packs[0].Items.AddRange(new[]
{
It(60, "Opal", ObjectClasses.Gem, wcid: 7, stack: 3, max: 10),
It(61, "Agate", ObjectClasses.Gem),
It(62, "Opal", ObjectClasses.Gem, wcid: 7, stack: 5, max: 10),
});
var p = new SortPlanner();
m = p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full);
Check(m.Count >= 1 && m[0].Kind == MoveKind.Stack && m[0].Item.Id == 60 && m[0].MergeInto == 62 && m[0].Dest.Id == inv.Packs[0].Id,
"the smaller Opal stack joins the larger, in its pack");
Check(m.Count == 1, "one tidy move per pack per pass");
inv.Packs[0].Items.RemoveAt(0);
inv.Packs[0].Items[1].Stack = 8;
m = p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full);
Check(m.Count == 0, "Agate, Opal: in order, one stack: nothing");
inv.Packs[0].Items.Reverse();
m = p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Reorder && m[0].InPlace && m[0].Placement >= 0, "out of order: a reorder in place");
Eq(p.View.Packs[0].OutOfPlace, 1, "the view counts it");
Check(p.View.Ordering && p.View.Packs[0].OrderKnown, "the view knows ordering is on");
// Not without the options, not for Main or Unpack, not for an unknown order, not with an unnamed item.
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000).Count, 0, "no options: no tidying");
Eq(p.Plan(inv, rules, SortScope.Main, false, 0, 5000, PlanOptions.Full).Count, 0, "Main: routes only");
inv.Packs[0].OrderKnown = false;
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full).Count, 0, "order unknown: not reordered");
inv.Packs[0].OrderKnown = true;
inv.Packs[0].Items.Add(It(70, "", ObjectClasses.Gem));
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full).Count, 0, "an unnamed item: wait");
inv.Packs[0].Items.RemoveAt(2);
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, new PlanOptions { Order = false, Merge = true }).Count, 0, "ordering off: no reorder");
// A route waits for nothing in place: routes first.
inv.Main.Items.Add(It(11, "Zircon", ObjectClasses.Gem));
m = p.Plan(inv, rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Route, "a route goes before any tidying");
// The main pack is put in order only once nothing in it is new.
inv = Inv(0);
inv.Main.OrderKnown = true;
inv.Main.Items.AddRange(new[] { It(80, "Zinc", ObjectClasses.Misc), It(81, "Amber", ObjectClasses.Misc) });
p = new SortPlanner();
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full).Count, 0, "new items settling in the main pack: not yet");
m = p.Plan(inv, rules, SortScope.All, false, 5000, 5000, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Reorder && m[0].DestIndex == 0, "settled: the main pack is put in order");
Check(m[0].Done == "put in order in main pack", "logged as such");
// The backstop: an item put in order too often lately isn't again until the window passes.
for (int i = 0; i < SortPlanner.MaxReorders; i++) p.NoteReorder(80, 6000 + i);
Check(p.ReorderLimited(80, 7000), "limited after too many");
m = p.Plan(inv, rules, SortScope.All, false, 7000, 5000, PlanOptions.Full);
Check(m.All(x => x.Item.Id != 80), "not moved again");
Check(!p.ReorderLimited(80, 6000 + SortPlanner.ReorderWindowMs), "the window passes");
}
private static void MoveAnswersInPlace()
{
var item = It(10, "Opal", ObjectClasses.Gem, stack: 5);
var pack = new SortPack { Id = 0x40000001 };
var reorder = new MoveInFlight { Move = new SortMove(item, pack, 1, 0, 2, MoveKind.Reorder), SentMs = 1000, ErrorSeqAtSend = 7, StackAtSend = 5 };
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = 0, ErrorSeq = 7 }, 1500), MoveOutcome.Pending,
"in its pack but not at its slot yet: still waiting (its container says nothing)");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = 2, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "at its slot");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = Me, Slot = 0, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "moved away by someone: stop waiting");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = -1, ErrorSeq = 7 }, 1000 + MoveTracker.TimeoutMs), MoveOutcome.TimedOut, "no answer");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = 0, ErrorSeq = 8, ErrorEventType = 0xA0, ErrorObject = 10 }, 1500),
MoveOutcome.Refused, "refused");
var join = new MoveInFlight { Move = new SortMove(item, pack, 1, 50, -1, MoveKind.Stack), SentMs = 1000, ErrorSeqAtSend = 7, StackAtSend = 5 };
Eq(MoveTracker.Observe(join, new MoveObservation { Exists = true, Container = pack.Id, Stack = 5, ErrorSeq = 7 }, 1500), MoveOutcome.Pending, "a join: still whole");
Eq(MoveTracker.Observe(join, new MoveObservation { Exists = true, Container = pack.Id, Stack = 2, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "part of it joined");
Eq(MoveTracker.Observe(join, new MoveObservation { Exists = false }, 1500), MoveOutcome.Done, "all of it joined");
}
// ── Convergence ─────────────────────────────────────────────────────
/// <summary>A messy character: loot in the main pack, items in the wrong packs, packs out of order, split stacks.</summary>
private static SortInventory Messy()
{
SortInventory inv = Inv(3, cap: 24);
foreach (SortPack p in inv.Packs) p.OrderKnown = true;
inv.Main.OrderKnown = true;
uint id = 1000;
SortItem Add(SortPack p, string name, int cls, uint wcid = 0, int stack = 1, int max = 1)
{
var it = It(id++, name, cls, wcid, stack, max);
p.Items.Add(it);
return it;
}
// Main pack: loot of every kind, and things no rule wants.
Add(inv.Main, "Lead Scarab", ObjectClasses.SpellComponent, 691, 3, 100);
Add(inv.Main, "Salvaged Iron", ObjectClasses.Salvage);
Add(inv.Main, "Black Opal", ObjectClasses.Gem, 2401, 1, 1);
Add(inv.Main, "Zircon Plate", ObjectClasses.Armor);
Add(inv.Main, "Ashcoal", ObjectClasses.Misc);
Add(inv.Main, "Healing Kit", ObjectClasses.HealingKit, 628, 1, 1);
Add(inv.Main, "Prismatic Taper", ObjectClasses.SpellComponent, 20631, 40, 100);
Add(inv.Main, "Amber Ring", ObjectClasses.Jewelry);
// Pack 1 (components): out of order, split stacks, a gem that belongs in pack 3.
Add(inv.Packs[0], "Prismatic Taper", ObjectClasses.SpellComponent, 20631, 70, 100);
Add(inv.Packs[0], "Hyssop", ObjectClasses.SpellComponent, 650, 5, 100);
Add(inv.Packs[0], "Agate", ObjectClasses.Gem, 2394, 1, 1);
Add(inv.Packs[0], "Prismatic Taper", ObjectClasses.SpellComponent, 20631, 90, 100);
Add(inv.Packs[0], "Copper Scarab", ObjectClasses.SpellComponent, 690, 1, 100);
Add(inv.Packs[0], "Lead Scarab", ObjectClasses.SpellComponent, 691, 99, 100);
Add(inv.Packs[0], "Birch", ObjectClasses.SpellComponent, 660, 10, 100);
// Pack 2 (salvage): reversed.
foreach (string s in new[] { "Salvaged Steel", "Salvaged Granite", "Salvaged Gold", "Salvaged Ebony", "Salvaged Copper" })
Add(inv.Packs[1], s, ObjectClasses.Salvage);
// Pack 3 (gems, stones, keys): a component that belongs in pack 1, and stray misc.
Add(inv.Packs[2], "Mana Stone", ObjectClasses.ManaStone);
Add(inv.Packs[2], "Legendary Key", ObjectClasses.Key);
Add(inv.Packs[2], "Gold Scarab", ObjectClasses.SpellComponent, 693, 2, 100);
Add(inv.Packs[2], "Pyreal Mote", ObjectClasses.Misc);
Add(inv.Packs[2], "Diamond", ObjectClasses.Gem);
return inv;
}
private static void Converges()
{
foreach (bool kindFirst in new[] { false, true })
foreach (SortScope scope in new[] { SortScope.All, SortScope.Clean })
{
string what = $"{scope}{(kindFirst ? ", kind first" : "")}";
SortInventory inv = Messy();
List<SortRule> rules = SortRules.Defaults();
var opt = PlanOptions.Full;
opt.KindFirst = kindFirst;
var planner = new SortPlanner();
var seen = new HashSet<string>();
int passes = 0, moved = 0;
bool repeated = false;
// The planner on the same inventory, each pass's first move done as the server does it.
for (; passes < 500; passes++)
{
List<SortMove> moves = planner.Plan(inv, rules, scope, false, 10_000 + passes, 0, opt);
if (moves.Count == 0) break;
SortMove m = moves[0];
string state = Snapshot(inv) + "|" + m.Item.Id + ">" + m.Dest.Id + "@" + m.Placement + "+" + m.MergeInto;
if (!seen.Add(state)) repeated = true;
ServerApply(inv, m);
if (m.Kind == MoveKind.Reorder) planner.NoteReorder(m.Item.Id, 10_000 + passes);
moved++;
}
Console.WriteLine($" {what}: {moved} moves to tidy the messy inventory");
Check(passes < 500, $"{what}: runs out of moves ({moved} moves)");
Check(!repeated, $"{what}: never the same move from the same state twice");
Check(moved <= 60, $"{what}: in a sensible number of moves ({moved})");
for (int i = 0; i < 50; i++)
if (planner.Plan(inv, rules, scope, false, 20_000 + i * 1000, 0, opt).Count != 0) { Check(false, $"{what}: stays still afterwards"); break; }
Check(true, $"{what}: 50 more passes, no move");
// And it is tidy: every item in its pack, packs in order, one stack with room per kind.
foreach (SortItem it in inv.Main.Items.Concat(inv.Packs.SelectMany(p => p.Items)))
{
SortRule? r = SortRules.RuleFor(rules, it);
SortPack where = inv.Packs.Prepend(inv.Main).First(p => p.Items.Contains(it));
if (r != null) Check(where.Id == inv.Packs[r.Pack - 1].Id, $"{what}: {it.Name} in its rule's pack");
else if (scope == SortScope.Clean) Check(where == inv.Main, $"{what}: {it.Name} (no rule) back in the main pack");
}
foreach (SortPack pk in inv.Packs.Prepend(inv.Main))
{
Check(InOrder(pk.Items, kindFirst), $"{what}: {pk.Name} in order ({Names(pk.Items)})");
Check(!SortPlanner.StackJoin(pk, _ => true, out _, out _), $"{what}: {pk.Name} has no two stacks to join");
}
Eq(inv.Packs[0].Items.Count(i => i.Name == "Prismatic Taper"), 2, $"{what}: tapers 200 = 100 + 100");
}
}
private static string Snapshot(SortInventory inv) =>
string.Join(";", inv.Packs.Prepend(inv.Main).Select(p => string.Join(",", p.Items.Select(i => i.Id + "x" + i.Stack))));
private static void ConvergesInTheLoop()
{
// The controller with auto-sort on, against a pretend server that does what ACE does.
var w = new FakeWorld { Inv = Messy(), Can = SortAbilities.All };
SortController c = Controller(auto: true, gapMs: 300, settleSec: 1);
Ticks(c, w, 0, 120_000);
int sent = w.Sent.Count;
if (Environment.GetEnvironmentVariable("RSORT_DEBUG") == "1") foreach (SortMove dm in w.Sent) Console.WriteLine($" {dm.Kind} {dm.Item.Name} x{dm.Item.Stack} -> {dm.DestLabel} @{dm.Placement} +{dm.MergeInto}");
Console.WriteLine($" auto-sort: {sent} moves ({w.Sent.Count(m => m.Kind == MoveKind.Route)} to packs, {w.Sent.Count(m => m.Kind == MoveKind.Stack)} stacks joined, {w.Sent.Count(m => m.Kind == MoveKind.Reorder)} reorders)");
Check(sent > 20 && sent < 80, $"auto-sort tidied everything ({sent} moves)");
Eq(c.Status, "watching", "then watching");
Eq(c.Failed, 0, "no move failed or timed out on the way");
Check(c.Log.Any(l => l.Contains("put in order")), $"reorders logged ({string.Join(" / ", c.Log)})");
Ticks(c, w, 120_000, 600_000);
Eq(w.Sent.Count, sent, "eight minutes more: not one move (nothing moves back and forth)");
foreach (SortPack pk in w.Inv.Packs.Prepend(w.Inv.Main)) Check(InOrder(pk.Items, false), $"{pk.Name} in order");
// New loot: routed into its place after the settle time, nothing else stirs.
w.Inv.Main.Items.Add(It(5000, "Cobalt Scarab", ObjectClasses.SpellComponent, 6000, 1, 100));
Ticks(c, w, 600_000, 700_000);
Eq(w.Sent.Count, sent + 1, "one new item: one move");
SortMove last = w.Sent[^1];
Check(last.Kind == MoveKind.Route && last.Placement >= 0 && last.Dest.Id == w.Inv.Packs[0].Id, "into pack 1 at its slot");
Check(InOrder(w.Inv.Packs[0].Items, false), "pack 1 still in order (it landed in its place)");
// An engine before API v80: items still go to their packs; nothing is reordered.
var old = new FakeWorld { Inv = Messy(), Can = new SortAbilities { Merge = true } };
SortController c2 = Controller(auto: true, settleSec: 0);
Ticks(c2, old, 0, 120_000);
Check(old.Sent.All(m => m.Kind != MoveKind.Reorder && m.Placement == -1), "no slots, no reorders");
Check(old.Inv.Packs[2].Items.All(i => i.ObjectClass != ObjectClasses.SpellComponent), "but the misplaced component left pack 3");
int oldSent = old.Sent.Count;
Ticks(c2, old, 120_000, 300_000);
Eq(old.Sent.Count, oldSent, "and it stays still too");
}
}
}

View file

@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Views;
namespace RynthSort.Tests
{
// Rules tied to pack ids, the one-time fix of imported Lua pack numbers, the pack picker's labels
// and spell component classification.
internal static partial class Program
{
private const uint FocusA = 0x40000F01, FocusB = 0x40000F02;
/// <summary>
/// A main pack whose side slots are, in the client's list order: a focus, pack A, a focus,
/// pack B, pack C. The Lua script numbered those 1-5; RynthSort's packs are A, B, C (1-3).
/// </summary>
private static SortInventory WithFoci()
{
var inv = new SortInventory();
inv.Main.Id = Me;
inv.Main.Name = "Main pack";
inv.Main.Capacity = 102;
inv.Slots.Add(new SortSlot(FocusA, 0));
inv.Slots.Add(new SortSlot(0x40000001, 24));
inv.Slots.Add(new SortSlot(FocusB, 0));
inv.Slots.Add(new SortSlot(0x40000002, 24));
inv.Slots.Add(new SortSlot(0x40000003, 24));
foreach (SortSlot s in inv.Slots)
if (s.IsPack) inv.Packs.Add(new SortPack { Id = s.Id, Name = "Pack", Capacity = 24 });
inv.Packs[0].Items.Add(It(500, "Salvaged Iron", ObjectClasses.Salvage));
inv.Packs[1].Items.Add(It(501, "Black Opal", ObjectClasses.Gem));
inv.Packs[2].Items.Add(It(502, "Lead Scarab", ObjectClasses.SpellComponent));
return inv;
}
private static void ClassifyComponents()
{
// ItemType SpellComponents (0x1000) on ACE: the scarabs (Lead 691 .. Platinum 8897, Mana
// Scarab 37155) and Prismatic Taper (20631, weenie type SpellComponent) all have 4096.
foreach (string name in new[] { "Lead Scarab", "Platinum Scarab", "Mana Scarab", "Dark Scarab", "Prismatic Taper", "Red Taper", "Hyssop", "Ink of Formation" })
{
Eq(InventoryReader.ClassifyFrom(0x00001000, 0, name, out bool certain), ObjectClasses.SpellComponent, name);
Check(certain, name + ": certain");
// An item's ordinary bitfield bits (stuck, attackable) don't change it.
Eq(InventoryReader.ClassifyFrom(0x00001000, 0x00000014, name, out _), ObjectClasses.SpellComponent, name + " with bitfield bits");
}
var comps = SortRule.ForClass(ObjectClasses.SpellComponent, 1);
Check(SortRules.Matches(comps, It(1, "Platinum Scarab", InventoryReader.ClassifyFrom(0x1000, 0, "Platinum Scarab", out _))), "a component rule takes scarabs");
Check(SortRules.Matches(comps, It(2, "Prismatic Taper", InventoryReader.ClassifyFrom(0x1000, 0, "Prismatic Taper", out _))), "and tapers");
}
private static void ResolveById()
{
SortInventory inv = Inv(3);
var gem = SortRule.ForClass(ObjectClasses.Gem, 1);
gem.PackId = 0x40000003;
Eq(SortRules.Resolve(gem, inv, out bool fell), 3, "the pack its id names, not its number");
Check(!fell, "not a fallback");
inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
var p = new SortPlanner();
List<SortMove> m = p.Plan(inv, new List<SortRule> { gem }, SortScope.Main, true, 0, 0);
Check(m.Count == 1 && m[0].Dest.Id == 0x40000003 && m[0].DestIndex == 3, "moved to the pack with its id");
Eq(p.View.Issues.Count, 0, "no warning");
// A new pack shows up ahead of it in the list: the rule follows its pack.
inv.Packs.Insert(0, new SortPack { Id = 0x40000009, Name = "New", Capacity = 24 });
Eq(SortRules.Resolve(gem, inv, out _), 4, "its pack is now 4th: still the one used");
m = p.Plan(inv, new List<SortRule> { gem }, SortScope.Main, true, 0, 0);
Check(m.Count == 1 && m[0].Dest.Id == 0x40000003, "still moved to the same pack");
Check(PackFix.Sync(new List<SortRule> { gem }, inv) && gem.Pack == 4, "its number follows (for the window and the fallback)");
Check(!PackFix.Sync(new List<SortRule> { gem }, inv), "no change the second time");
// Already in its pack: Tidy leaves it there.
inv.Main.Items.Clear();
inv.Packs[3].Items.Add(It(11, "Black Opal", ObjectClasses.Gem));
Eq(p.Plan(inv, new List<SortRule> { gem }, SortScope.All, true, 0, 0).Count, 0, "in its pack: no move");
// Its pack isn't carried: the number decides, and the window says so.
SortInventory inv2 = Inv(3);
inv2.Main.Items.Add(It(12, "Black Opal", ObjectClasses.Gem));
var gone = SortRule.ForClass(ObjectClasses.Gem, 2);
gone.PackId = 0x4000FFFF;
gone.PackNote = "Sack - Gems";
Eq(SortRules.Resolve(gone, inv2, out fell), 2, "not carried: its number");
Check(fell, "a fallback");
m = p.Plan(inv2, new List<SortRule> { gone }, SortScope.Main, true, 0, 0);
Check(m.Count == 1 && m[0].DestIndex == 2, "moved by number");
Check(p.View.Issues.Count == 1 && p.View.Issues[0].UsedPack == 2 && p.View.Missing.Count == 0, "reported as a fallback, not missing");
// Not carried and no such number: nowhere.
gone.Pack = 5;
Eq(SortRules.Resolve(gone, inv2, out _), 0, "nowhere");
m = p.Plan(inv2, new List<SortRule> { gone }, SortScope.Main, true, 0, 0);
Check(m.Count == 0 && p.View.Missing.Contains(5) && p.View.Issues.Count == 1 && p.View.Issues[0].UsedPack == 0, "no move, reported missing");
Eq(p.View.Waiting, 1, "the item waits");
// A rule with no id is the number, as before; one that is off isn't reported.
Eq(SortRules.Resolve(SortRule.ForClass(ObjectClasses.Gem, 3), inv2, out fell), 3, "no id: the number");
Check(!fell, "no id: not a fallback");
gone.On = false;
p.Plan(inv2, new List<SortRule> { gone }, SortScope.Main, true, 0, 0);
Eq(p.View.Issues.Count, 0, "a rule that is off isn't reported");
}
private static List<SortRule> LuaRules() => new()
{
SortRule.ForClass(ObjectClasses.SpellComponent, 1), // a focus
SortRule.ForClass(ObjectClasses.Salvage, 2), // pack A
SortRule.ForClass(ObjectClasses.Gem, 3), // a focus
SortRule.ForClass(ObjectClasses.Key, 4), // pack B
SortRule.ForClass(ObjectClasses.HealingKit, 5), // pack C
SortRule.ForClass(ObjectClasses.TradeNote, 6), // nothing
};
private static void PackFixImported()
{
SortInventory inv = WithFoci();
List<SortRule> rules = LuaRules();
List<string> lines = PackFix.Apply(rules, inv, imported: true, LuaRules(), out int changed);
Eq(changed, 3, "three rules pointed at a pack");
Eq(lines.Count, 6, "a line for every rule");
Check(rules[0].PackId == 0 && rules[0].Pack == 1 && lines[0].Contains("a focus") && lines[0].Contains("left as pack 1"), "Lua pack 1 was a focus: left, and said so");
Check(rules[1].PackId == 0x40000001 && rules[1].Pack == 1, "Lua pack 2 = pack A = RynthSort's pack 1");
Check(lines[1].Contains("the Lua script's pack 2 -> pack 1") && lines[1].Contains("Pack - Salvage") && lines[1].Contains("0x40000001"), $"logged ({lines[1]})");
Check(rules[2].PackId == 0 && rules[2].Pack == 3 && lines[2].Contains("a focus"), "Lua pack 3 was a focus");
Check(rules[3].PackId == 0x40000002 && rules[3].Pack == 2, "Lua pack 4 = pack B = 2");
Check(rules[4].PackId == 0x40000003 && rules[4].Pack == 3 && rules[4].PackNote == "Pack - Components", "Lua pack 5 = pack C = 3, remembered with its contents");
Check(rules[5].PackId == 0 && rules[5].Pack == 6 && lines[5].Contains("doesn't exist") && lines[5].Contains("3 packs and 2 foci"), $"Lua pack 6 doesn't exist ({lines[5]})");
// Every rule with an id now: a second run changes nothing.
List<string> again = PackFix.Apply(rules, inv, true, LuaRules(), out int changed2);
Eq(changed2, 0, "rules with ids are skipped");
Eq(again.Count, 3, "only the three still without one are looked at");
// The Lua file unreadable (null): every rule is taken as the Lua script's.
List<SortRule> r2 = LuaRules();
PackFix.Apply(r2, inv, true, null, out int c3);
Check(c3 == 3 && r2[3].PackId == 0x40000002, "no Lua file to compare with: all as imported");
// No foci: Lua numbers and RynthSort's agree; the fix only adds the ids.
SortInventory plain = Inv(3);
foreach (SortPack pk in plain.Packs) plain.Slots.Add(new SortSlot(pk.Id, 24));
List<SortRule> r3 = SortRules.Defaults();
PackFix.Apply(r3, plain, true, SortRules.Defaults(), out int c4);
Check(c4 == 3 && r3[0].PackId == 0x40000001 && r3[0].Pack == 1 && r3[2].PackId == 0x40000003 && r3[2].Pack == 3, "no foci: same numbers, ids added");
// Rules RynthSort saved (not imported): each keeps its number and takes that pack's id.
List<SortRule> own = SortRules.Defaults();
List<string> ownLines = PackFix.Apply(own, inv, imported: false, null, out int c5);
Check(c5 == 3 && own[0].PackId == 0x40000001 && own[1].PackId == 0x40000002 && own[2].PackId == 0x40000003, "RynthSort's numbers count real packs: pinned as they are");
Check(ownLines[0].Contains("pack 1 kept"), $"logged ({ownLines[0]})");
Check(PackFix.Ready(inv), "every capacity read: ready");
inv.Slots[2] = new SortSlot(FocusB, -1);
Check(!PackFix.Ready(inv), "a capacity not readable yet: not ready (could be a pack)");
}
// Drakkon's rules as RynthSort's file had them on 2026-10-11 (imported, then edited in the
// window), against his Lua script's file (2026-10-07): only rules 5 and 6 are still the Lua
// script's (keys 3, kits 4); the rest were picked in RynthSort's window, in its numbers.
private static List<SortRule> DrakkonNow() => new()
{
SortRule.ForClass(ObjectClasses.SpellComponent, 4),
SortRule.ForClass(ObjectClasses.Salvage, 1),
SortRule.ForClass(ObjectClasses.Gem, 4),
SortRule.ForClass(ObjectClasses.ManaStone, 4),
SortRule.ForClass(ObjectClasses.Key, 3),
SortRule.ForClass(ObjectClasses.HealingKit, 4),
SortRule.ForClass(ObjectClasses.TradeNote, 4),
SortRule.ForName("Ink of", 2),
SortRule.ForName("Prismatic Taper", 4),
};
private static void PackFixDrakkon()
{
SortStore st = TempStore("drakkon");
string lua = st.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
var d = new CharacterSortData { Rules = DrakkonNow(), ImportedFrom = lua };
Check(st.Save("DreamWeave", "Drakkon", d) == null, "saved like the old file");
// The old file had no packsFixed and version 1.
string own = st.PathFor("DreamWeave", "Drakkon");
File.WriteAllText(own, File.ReadAllText(own).Replace("\"packsFixed\": false", "\"x\": 0").Replace("\"version\": 3", "\"version\": 1"));
CharacterSortData loaded = st.Load("DreamWeave", "Drakkon", out string? problem);
Check(problem == null && !loaded.PacksFixed && loaded.LuaRules != null && loaded.LuaRules.Count == 6, "imported, not fixed: the Lua file's rules read to compare with");
// A layout with one focus: slot 1 pack A, slot 2 a focus, slot 3 pack B, slot 4 pack C.
var inv = new SortInventory();
inv.Main.Id = Me;
inv.Slots.Add(new SortSlot(0x40000001, 24));
inv.Slots.Add(new SortSlot(FocusA, 0));
inv.Slots.Add(new SortSlot(0x40000002, 24));
inv.Slots.Add(new SortSlot(0x40000003, 24));
foreach (SortSlot s in inv.Slots)
if (s.IsPack) inv.Packs.Add(new SortPack { Id = s.Id, Name = "Pack", Capacity = 24 });
List<SortRule> r = loaded.Rules;
List<string> lines = PackFix.Apply(r, inv, true, loaded.LuaRules, out int changed);
Check(r[4].PackId == 0x40000002 && r[4].Pack == 2, "keys: the Lua script's pack 3 (after the focus) -> pack 2");
Check(r[5].PackId == 0x40000003 && r[5].Pack == 3, "kits: the Lua script's pack 4 -> pack 3");
Check(r[1].PackId == 0x40000001 && r[1].Pack == 1, "salvage (picked in RynthSort): pack 1 kept");
Check(r[7].PackId == 0x40000002 && r[7].Pack == 2, "Ink of (picked in RynthSort): pack 2 kept");
Check(r[0].PackId == 0 && r[0].Pack == 4 && lines[0].Contains("which you don't have"), "components to RynthSort's pack 4: there are only 3, left (and said)");
Check(r[8].PackId == 0 && r[8].Pack == 4, "Prismatic Taper to pack 4: the same");
Eq(changed, 4, "four rules tied to their packs");
Eq(lines.Count, 9, "a line per rule");
}
private static void PackFixLoop()
{
var w = new FakeWorld { Inv = WithFoci() };
w.Inv.Main.Items.Add(It(10, "Platinum Scarab", ObjectClasses.SpellComponent));
w.Inv.Main.Items.Add(It(11, "Healing Kit", ObjectClasses.HealingKit));
SortController c = Controller();
c.Data.Rules = LuaRules();
c.Data.ImportedFrom = "lua.json";
c.Data.LuaRules = LuaRules();
List<string>? fixLines = null;
int fixChanged = -1;
c.PacksFixed = (l, n) => { fixLines = l; fixChanged = n; };
Ticks(c, w, 0, SortController.FixSettleMs - 100);
Eq(w.Sent.Count, 0, "imported rules not fixed yet: nothing moves");
Eq(c.Status, "reading your packs", "status says why");
Check(!c.Data.PacksFixed && fixLines == null, "not before the packs have read the same for a while");
Ticks(c, w, SortController.FixSettleMs - 100 + 16, SortController.FixSettleMs + 1500);
Check(c.Data.PacksFixed && c.Data.LuaRules == null, "fixed once settled");
Check(fixLines != null && fixLines.Count == 6 && fixChanged == 3, "the plugin hears it (to log and save)");
Check(c.Log.Any(x => x.Contains("Imported pack numbers fixed: 3 of 6")), "noted in the window");
Check(w.Sent.Any(m => m.Item.Id == 11 && m.Dest.Id == 0x40000003), "kits (the Lua script's pack 5) go to pack C");
// Components named the Lua script's pack 1, a focus: left as it was, "pack 1", which is
// RynthSort's first real pack (the log line says so; Tom picks the right one).
Check(w.Sent.Any(m => m.Item.Id == 10 && m.Dest.Id == 0x40000001), "a rule left as it was keeps its number");
Check(c.Data.Rules[0].PackId == 0, "and has no id until one is picked");
}
private static void PackLabels()
{
var inv = new SortInventory();
inv.Main.Id = Me;
for (int i = 1; i <= 3; i++) inv.Packs.Add(new SortPack { Id = 0x40000000u + (uint)i, Name = "Pack", Capacity = 24 });
for (uint i = 0; i < 10; i++) inv.Packs[0].Items.Add(It(100 + i, "Salvaged Iron", ObjectClasses.Salvage));
for (uint i = 0; i < 5; i++) inv.Packs[0].Items.Add(It(200 + i, "Black Opal", ObjectClasses.Gem));
inv.Packs[0].Items.Add(It(300, "Legendary Key", ObjectClasses.Key));
inv.Packs[0].Items.Add(It(301, "Pyreal Mote", ObjectClasses.Misc));
inv.Packs[1].Items.Add(It(400, "Lead Scarab", ObjectClasses.SpellComponent));
inv.Packs[1].Items.Add(It(401, "Pyreal Mote", ObjectClasses.Misc));
inv.Packs[1].Items.Add(It(402, "Pyreal Mote", ObjectClasses.Misc));
Eq(inv.Packs[0].Summary(), "Salvage, Gems, Keys", "the three commonest kinds");
Eq(inv.Packs[1].Summary(), "Pyreal Mote, Components", "misc items by name");
Eq(inv.Packs[2].Summary(), "empty", "empty");
var p = new SortPlanner();
p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0);
List<string> choices = SortPanel.PackChoices(p.View, 1);
Eq(choices[0], "Pack 1: Pack (17/24) - Salvage, Gems, Keys", "picker label: number, name, room, contents");
Eq(choices[1], "Pack 2: Pack (3/24) - Pyreal Mote, Components", "bags with one name told apart by contents");
Eq(choices[2], "Pack 3: Pack (0/24) - empty", "an empty pack");
Eq(choices[3], "Pack 4 (none)", "then numbers you don't have");
// Picking stores the id; the row shows the pack it resolves to.
var rule = SortRule.ForClass(ObjectClasses.Gem, 1);
SortPanel.SetPack(rule, p.View, 2);
Check(rule.Pack == 2 && rule.PackId == 0x40000002 && rule.PackNote == "Pack - Pyreal Mote, Components", "picked: number, id and note");
Eq(SortPanel.ShownPack(p.View, rule), 2, "the rule is listed under pack 2");
SortPanel.SetPack(rule, p.View, 6);
Check(rule.Pack == 6 && rule.PackId == 0 && rule.PackNote == "", "a number you don't have: no id");
Check(!p.View.PackOrderKnown && SortPanel.PackTooltip(p.View).Contains("list order") && !SortPanel.PackTooltip(p.View).Contains("top of the pack column"),
"pack order unknown: the tooltip doesn't claim screen order");
inv.PackOrderKnown = true;
p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0);
Check(SortPanel.PackTooltip(p.View).Contains("top of the pack column"), "pack order known: numbered from the top");
// Warnings sit with their pack: a rule that fell back to a number is listed (and warned
// about) under the pack it uses; rules whose pack isn't carried are grouped by that pack.
var gems = SortRule.ForClass(ObjectClasses.Gem, 7);
gems.PackId = 0x4000AAAA; gems.PackNote = "Sack - Gems";
var keys = SortRule.ForClass(ObjectClasses.Key, 7);
keys.PackId = 0x4000AAAA; keys.PackNote = "Sack - Gems";
var salvage = SortRule.ForClass(ObjectClasses.Salvage, 1);
salvage.PackId = 0x4000BBBB; salvage.PackNote = "Bag - Salvage";
var rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.SpellComponent, 1), gems, keys, SortRule.ForClass(ObjectClasses.ManaStone, 6), salvage };
inv.PackOrderKnown = false;
p.Plan(inv, rules, SortScope.Main, true, 0, 0);
Eq(SortPanel.FallbackWarnings(p.View, 1).Count, 1, "one fallback warning, under pack 1");
Eq(SortPanel.FallbackWarnings(p.View, 1)[0], "Salvage: its pack (Bag - Salvage) isn't carried, so this one is used", "with what the pack was");
Eq(SortPanel.FallbackWarnings(p.View, 2).Count, 0, "none under pack 2");
Dictionary<int, List<SortRule>> groups = SortPanel.Group(rules, p.View);
Check(groups[1].Count == 2 && groups[1].Contains(salvage), "pack 1 lists its own rule and the fallback");
Check(groups[0].Count == 3 && groups[0].Contains(gems) && groups[0].Contains(keys), "rules for packs you don't have, together");
}
private static void StorePackIds()
{
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");
d.Rules[0].PackId = 0x8000ABCD;
d.Rules[0].PackNote = "Sack - Components";
d.PacksFixed = true;
st.Save("S", "A", d);
string json = File.ReadAllText(st.PathFor("S", "A"));
Check(json.Contains("\"version\": 3") && json.Contains("\"packId\": 2147527629") && json.Contains("\"packsFixed\": true"), "version 2 with pack ids");
Check(!json.Contains("\"packId\": 0"), "no packId written for rules without one");
CharacterSortData back = st.Load("S", "A", out string? problem);
Check(problem == null && back.PacksFixed && back.Rules[0].PackId == 0x8000ABCD && back.Rules[0].PackNote == "Sack - Components" && back.Rules[1].PackId == 0, "read back");
Check(back.LuaRules == null, "not imported: nothing to compare with");
// A version 1 file: rules by number, not fixed.
File.WriteAllText(st.PathFor("S", "A"), "{\"version\":1,\"rules\":[{\"kind\":\"class\",\"class\":11,\"pack\":3}]}");
CharacterSortData v1 = st.Load("S", "A", out problem);
Check(problem == null && !v1.PacksFixed && v1.Rules[0].PackId == 0 && v1.Rules[0].Pack == 3, "version 1 loads: number only, fix pending");
File.WriteAllText(st.PathFor("S", "A"), "{\"rules\":[{\"pack\":3,\"packId\":-5},{\"pack\":2,\"packId\":3.5},{\"pack\":1,\"packId\":1073741825.0}]}");
CharacterSortData odd = st.Load("S", "A", out _);
Check(odd.Rules[0].PackId == 0 && odd.Rules[1].PackId == 0 && odd.Rules[2].PackId == 0x40000001, "odd ids read as none; a whole double is fine");
// A fresh import: the Lua rules kept to compare with, not fixed.
SortStore imp = TempStore("packids-import");
string lua = imp.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
CharacterSortData fresh = imp.Load("DreamWeave", "Drakkon", out _);
Check(!fresh.PacksFixed && fresh.LuaRules != null && fresh.LuaRules.Count == 6 && !ReferenceEquals(fresh.LuaRules[0], fresh.Rules[0]), "fresh import: Lua rules copied, fix pending");
// Saved with a backup: the old file kept beside it.
imp.Save("DreamWeave", "Drakkon", fresh);
string before = File.ReadAllText(imp.PathFor("DreamWeave", "Drakkon"));
fresh.PacksFixed = true;
Check(imp.Save("DreamWeave", "Drakkon", fresh, backup: true) == null, "saved with a backup");
string bak = imp.PathFor("DreamWeave", "Drakkon") + ".bak";
Check(File.Exists(bak) && File.ReadAllText(bak) == before, ".bak holds the file as it was");
CharacterSortData fixedNow = imp.Load("DreamWeave", "Drakkon", out _);
Check(fixedNow.PacksFixed && fixedNow.LuaRules == null, "once fixed, the Lua file isn't read again");
}
}
}

View file

@ -47,6 +47,12 @@ namespace RynthSort.Tests
{
Run("rules: class and name matching, first match wins", RuleMatching);
Run("classify: item classes as RynthLua sees them", Classify);
Run("classify: scarabs, tapers and other spell components", ClassifyComponents);
Run("rules: a rule's pack by id, else its number", ResolveById);
Run("pack fix: imported Lua numbers (foci counted)", PackFixImported);
Run("pack fix: Drakkon's rules (edited after the import)", PackFixDrakkon);
Run("pack fix: in the loop (held until the packs settle)", PackFixLoop);
Run("window: pack labels and warnings", PackLabels);
Run("plan: settle time, force", PlanSettle);
Run("plan: pack choice (full pack, stacks, capacity)", PlanPackChoice);
Run("plan: worn, packs, foci and blocked items never move", PlanNeverMoves);
@ -67,9 +73,19 @@ namespace RynthSort.Tests
Run("store: save and load", StoreRoundTrip);
Run("store: Lua script import", StoreLuaImport);
Run("store: odd files", StoreOddFiles);
Run("store: pack ids, the fix flag and the backup", StorePackIds);
Run("lua autostart warning", LuaAutostart);
Run("window: display lists parse in the engine", WindowParses);
Run("window: a bar button of its own", WindowBarButton);
Run("window: rule editing through events", WindowEvents);
Run("rules: several classes and names in one rule", MultiRules);
Run("store: old rules migrate to version 3", RuleMigration);
Run("order: inside a pack (A-Z, fewest moves, every order of up to 7)", InPackOrder);
Run("order: slot orders and the pack column", SlotOrders);
Run("plan: stacks and order inside packs", PlanInPack);
Run("moves: answers for moves within a pack", MoveAnswersInPlace);
Run("plan: a fixed inventory runs out of moves", Converges);
Run("loop: auto-sort tidies every pack, then stays still", ConvergesInTheLoop);
}
finally
{
@ -140,9 +156,11 @@ namespace RynthSort.Tests
Check(!SortRules.Matches(off, gem), "a rule that is off matches nothing");
var rules = new List<SortRule> { SortRule.ForName("taper", 5), SortRule.ForClass(ObjectClasses.SpellComponent, 1) };
Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "first match wins (name rule above the class rule)");
Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "a name match beats a class match");
(rules[0], rules[1]) = (rules[1], rules[0]);
Eq(SortRules.RuleFor(rules, comp)?.Pack, 1, "reordered: the class rule wins");
Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "whatever the order");
var twoClass = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 2), SortRule.ForClass(ObjectClasses.Gem, 4) };
Eq(SortRules.RuleFor(twoClass, gem)?.Pack, 2, "two class matches: the rule saved first");
Check(SortRules.RuleFor(Defaults, misc) == null, "no rule wants misc");
Eq(SortRules.RuleFor(Defaults, salvage)?.Pack, 2, "default: salvage to pack 2");
Eq(SortRules.RuleFor(Defaults, gem)?.Pack, 3, "default: gems to pack 3");
@ -411,6 +429,13 @@ namespace RynthSort.Tests
Check(w.Update(0x7000_0002, 7, 20_000), "the next corpse");
Check(w.Update(0, 0, 20_500), "closed: 1.5 s more (the next corpse is a moment away)");
Check(!w.Update(0, 0, 21_600), "then clear");
// An unreadable count (-1) between real reads is not a change (2026-10-11: paused for ever).
var f = new LootWatch();
Check(f.Update(0x7000_0003, 6, 30_000), "a corpse opened");
for (long t = 30_500; t < 40_000; t += 500)
f.Update(0x7000_0003, t % 1000 == 0 ? 6 : -1, t);
Check(!f.Update(0x7000_0003, 6, 40_000), "a flickering unreadable count doesn't keep it 'looting'");
}
private static void StatusJsonFallback()
@ -466,14 +491,17 @@ namespace RynthSort.Tests
public GateInputs Gate;
public readonly List<SortMove> Sent = new();
public bool EngineAccepts = true;
/// <summary>What the pretend engine can do (none: as an engine before API v80 without merges).</summary>
public SortAbilities Can;
/// <summary>"land" moves the item at once; "refuse" answers with InventoryServerSaveFailed; "busy" with You're too busy; "silent" never answers.</summary>
public string Server = "land";
public int ErrorSeq = 3;
private readonly Dictionary<uint, uint> _where = new();
private readonly HashSet<uint> _gone = new();
public SortInventory? ReadInventory() => Inv;
public GateInputs ReadGate(bool sortInCombat, long nowMs) { GateInputs g = Gate; g.SortInCombat = sortInCombat; return g; }
public int ErrorSeqNow() => ErrorSeq;
public SortAbilities Abilities => Can;
public bool SendMove(in SortMove move)
{
@ -482,12 +510,7 @@ namespace RynthSort.Tests
switch (Server)
{
case "land":
uint id = move.Item.Id;
foreach (SortPack p in Inv.Packs.Prepend(Inv.Main)) p.Items.RemoveAll(i => i.Id == id);
uint destId = move.Dest.Id;
SortPack dest = destId == Inv.Main.Id ? Inv.Main : Inv.Packs.First(p => p.Id == destId);
dest.Items.Add(move.Item);
_where[id] = dest.Id;
if (ServerApply(Inv, move)) _gone.Add(move.Item.Id);
break;
case "refuse":
ErrorSeq++;
@ -504,15 +527,58 @@ namespace RynthSort.Tests
private uint _refused;
private bool _busy;
public MoveObservation Observe(uint itemId)
public MoveObservation Observe(in SortMove move)
{
var o = new MoveObservation { Exists = true, Container = _where.TryGetValue(itemId, out uint c) ? c : Me, ErrorSeq = ErrorSeq };
uint itemId = move.Item.Id;
var o = new MoveObservation { Exists = !_gone.Contains(itemId), Container = Me, ErrorSeq = ErrorSeq, Slot = -1, Stack = move.Item.Stack };
foreach (SortPack p in Inv.Packs.Prepend(Inv.Main))
{
int at = p.Items.FindIndex(i => i.Id == itemId);
if (at < 0) continue;
o.Container = p.Id;
o.Slot = at;
o.Stack = p.Items[at].Stack;
}
if (_refused == itemId) { o.ErrorEventType = 0xA0; o.ErrorObject = itemId; }
if (_busy) { o.Error = 0x1D; o.ErrorEventType = 0x28A; }
return o;
}
}
/// <summary>
/// What ACE does with a move: a merge adds what fits to the other stack (the rest stays; a
/// stack emptied is gone: true); a move takes the item out and puts it in at its placement
/// (clamped), or at the end when it names none. Items keep their objects (the planner's
/// copies of stack sizes see the change, as a fresh read would).
/// </summary>
private static bool ServerApply(SortInventory inv, SortMove move)
{
uint id = move.Item.Id;
uint destId = move.Dest.Id;
SortPack? from = inv.Packs.Prepend(inv.Main).FirstOrDefault(p => p.Items.Any(i => i.Id == id));
if (from == null) return false;
SortItem item = from.Items.First(i => i.Id == id);
SortPack dest = destId == inv.Main.Id ? inv.Main : inv.Packs.First(p => p.Id == destId);
uint mergeInto = move.MergeInto;
if (mergeInto != 0)
{
SortItem? into = dest.Items.FirstOrDefault(i => i.Id == mergeInto);
if (into == null) return false;
int max = into.MaxStack > 1 ? into.MaxStack : item.MaxStack;
int amount = Math.Min(item.Stack, max - into.Stack);
if (amount <= 0) return false;
into.Stack += amount;
item.Stack -= amount;
if (item.Stack > 0) return false;
from.Items.Remove(item);
return true;
}
from.Items.Remove(item);
int at = move.Placement >= 0 ? Math.Clamp(move.Placement, 0, dest.Items.Count) : dest.Items.Count;
dest.Items.Insert(at, item);
return false;
}
private static SortController Controller(bool auto = true, int gapMs = 300, int settleSec = 0)
{
var c = new SortController();
@ -695,7 +761,7 @@ namespace RynthSort.Tests
Ticks(c, w, 0, 600);
Eq(w.Sent.Count, 2, "tidy moved both quickly (job gap, not the 3 s auto gap)");
Eq(w.Inv.Packs[1].Items.Count, 2, "both in pack 2");
Check(c.Job == null && c.Log[0] == "Packs tidied", "job ends with a note");
Check(c.Job == null && c.Log[0] == "Packs sorted", "job ends with a note");
// Unpack turns auto-sort off (and asks for a save) so nothing moves back.
var w2 = new FakeWorld();
@ -750,21 +816,23 @@ namespace RynthSort.Tests
{
SortStore st = TempStore("roundtrip");
CharacterSortData d = st.Load("DreamWeave", "Drakkon", out string? problem);
Check(problem == null && d.Rules.Count == 5 && d.ImportedFrom.Length == 0, "no file: the defaults");
Check(problem == null && d.Rules.Count == 3 && d.ImportedFrom.Length == 0, "no file: the defaults");
Check(!d.Settings.WindowOpen, "no file: the window starts closed (the bar button opens it)");
d.Rules.Add(SortRule.ForName("Pyreal \"Mote\"", 6));
d.Rules[0].On = false;
d.Settings.Auto = false;
d.Settings.SettleSec = 12;
d.Settings.GapMs = 900;
d.Settings.SortInCombat = true;
d.Settings.WindowOpen = false;
d.Settings.WindowOpen = true;
Check(st.Save("DreamWeave", "Drakkon", d) == null, "saved");
Check(File.Exists(Path.Combine(st.Root, "characters", "DreamWeave_Drakkon.json")), "file named server_character");
CharacterSortData back = st.Load("DreamWeave", "Drakkon", out problem);
Check(problem == null, "read back");
Eq(back.Rules.Count, 6, "rules");
Check(!back.Rules[0].On && back.Rules[5].Kind == RuleKind.Name && back.Rules[5].Text == "Pyreal \"Mote\"" && back.Rules[5].Pack == 6, "rule fields");
Check(!back.Settings.Auto && back.Settings.SettleSec == 12 && back.Settings.GapMs == 900 && back.Settings.SortInCombat && !back.Settings.WindowOpen, "settings");
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");
Eq(SortStore.FileStem("Dream:Weave", "Con"), "Dream_Weave_Con", "unsafe characters replaced like RynthLua");
Eq(SortStore.SafeFileName("CON"), "_CON", "reserved names guarded");
}
@ -782,9 +850,10 @@ namespace RynthSort.Tests
Check(problem == null, "Lua file read");
Eq(d.ImportedFrom, lua, "marked as imported");
Eq(d.Rules.Count, 6, "six rules");
Check(d.Rules[5].Kind == RuleKind.Class && d.Rules[5].Class == ObjectClasses.HealingKit && d.Rules[5].Pack == 4, "healing kits to pack 4");
Check(d.Rules[5].Names.Count == 0 && d.Rules[5].Classes.Count == 1 && d.Rules[5].Classes[0] == ObjectClasses.HealingKit && d.Rules[5].Pack == 4, "healing kits to pack 4 (one class)");
Check(!d.Settings.Auto && d.Settings.SettleSec == 5 && d.Settings.GapMs == 600, "settings taken over");
Check(d.Settings.WindowOpen && !d.Settings.SortInCombat, "plugin-only settings at their defaults");
Check(!d.Settings.SortInCombat, "plugin-only settings at their defaults");
Check(d.Settings.WindowOpen, "taken over from the Lua script: the window opens once to show the rules");
// Once RynthSort has its own file, the Lua file is no longer read (and is left alone).
d.Rules.RemoveAt(0);
@ -804,7 +873,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 == 5, "broken file: defaults, problem reported");
Check(problem != null && d.Rules.Count == 3, "broken file: defaults, 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}}");
@ -815,9 +884,9 @@ namespace RynthSort.Tests
File.WriteAllText(own, "{\"rules\":[{\"kind\":\"name\",\"text\":\"Key\",\"pack\":2.0},{\"class\":11,\"pack\":-4},7,{\"on\":false}]}");
d = st.Load("S", "A", out _);
Eq(d.Rules.Count, 3, "a non-object entry is skipped");
Check(d.Rules[0].Kind == RuleKind.Name && d.Rules[0].Pack == 2 && d.Rules[0].On, "missing 'on' = on; 2.0 = 2");
Check(d.Rules[0].Names.Count == 1 && d.Rules[0].Names[0] == "Key" && d.Rules[0].Classes.Count == 0 && d.Rules[0].Pack == 2 && d.Rules[0].On, "missing 'on' = on; 2.0 = 2");
Eq(d.Rules[1].Pack, 1, "pack clamped to 1");
Check(!d.Rules[2].On && d.Rules[2].Class == ObjectClasses.SpellComponent, "defaults for missing fields");
Check(!d.Rules[2].On && d.Rules[2].Classes.Count == 1 && d.Rules[2].Classes[0] == ObjectClasses.SpellComponent, "defaults for missing fields");
}
private static void LuaAutostart()
@ -869,6 +938,32 @@ namespace RynthSort.Tests
maxOps = windows.Where(x => x.List != null).Select(x => x.List!.OpCount).DefaultIfEmpty(0).Max();
}
private static unsafe List<ParsedWindow> ParseWindows(UiHost host)
{
int n = Write(host);
byte[] buf = SubmitBuffer(host);
List<ParsedWindow> windows;
fixed (byte* p = buf) DisplayListParser.Parse(p, n, 4000f, out _, out windows, out _);
return windows;
}
private static void WindowBarButton()
{
Eq(UiFormat.FlagBarButton, WindowFlags.BarButton, "the plugin's bit is the engine's");
var (_, panel, host, w) = Window();
Draw(w, panel);
List<ParsedWindow> windows = ParseWindows(host);
Check(windows.Count == 1 && windows[0].Title == "RynthSort", "one window, titled RynthSort (the button's tooltip)");
uint f = windows.Count == 1 ? windows[0].Flags : 0;
Check((f & WindowFlags.ShowInBar) != 0 && (f & WindowFlags.BarButton) != 0, "ShowInBar + BarButton survive the engine's parse");
w.MarkSubmitted(true);
w.ShowInBar = false;
windows = ParseWindows(host);
f = windows.Count == 1 ? windows[0].Flags : ~0u;
Check((f & (WindowFlags.ShowInBar | WindowFlags.BarButton)) == 0, "not in the bar: no button either");
}
private static byte[] Event(ushort type, uint seq, uint window, uint key, byte[] payload)
{
var e = new byte[16 + payload.Length];
@ -890,37 +985,65 @@ 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 main pack") && body.Contains("Tidy all packs")
&& body.Contains("Empty side packs") && body.Contains("Clean packs"), "buttons and toggle");
Check(body.Contains("Rules (first match wins)") && body.Contains("1. Spell Component -> pack 1 (Pack 1)"), "rule list");
Check(body.Contains("Auto-sort") && body.Contains("Sort now") && body.Contains("Clean packs") && body.Contains("Empty side packs"), "buttons and toggle");
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.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");
w.MarkSubmitted(true);
// A selected rule's editor (class, then name), the settings open, warnings and a log.
Apply(host, Event(1, 1, w.Hash, w.KeyOf("row.0"), Click));
// 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);
ParseAll(host, "rule editor (class)", out _);
ParseAll(host, "rule editor", out _);
body = BodyText(w);
Check(body.Contains("Rule 1") && body.Contains("Mana Stone") && body.Contains("Pack 1: Pack 1 (24/24)") && body.Contains("Pack 7 (none)"), "editor with class and pack choices");
Check(body.Contains("Settle (s)") && body.Contains("Gap (ms)") && body.Contains("Sort during fights"), "settings shown");
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");
w.MarkSubmitted(true);
c.Data.Rules[0].Kind = RuleKind.Name;
c.Data.Rules[0].Text = "Taper";
c.Data.Rules[0].Class = 999;
gemRule.AddName("Opal");
gemRule.AddName("a##b");
Draw(w, panel);
ParseAll(host, "rule editor (name)", out _);
Check(BodyText(w).Contains("Name has"), "name editor");
c.Data.Rules[0].Kind = RuleKind.Class;
ParseAll(host, "rule editor with names", out _);
body = BodyText(w);
Check(body.Contains("Names:") && body.Contains("\"Opal\" x"), "names as chips");
Check(body.Contains("Gem, Key, Mana Stone, name has \"a# #b\", name has \"Opal\""), "the row: classes, then names, A-Z (## shown apart)");
// A rule whose pack isn't carried: its own section, grouped by what the pack was.
var gone = SortRule.ForClass(ObjectClasses.Lockpick, 9);
gone.PackId = 0x4000AAAA;
gone.PackNote = "Sack - Gems";
c.Data.Rules.Add(gone);
var inv = Inv(4);
Fill(inv.Packs[0], 24, 1000);
inv.Packs[0].OrderKnown = true;
c.Planner.Plan(inv, c.Data.Rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Draw(w, panel);
ParseAll(host, "rule editor (class the editor doesn't offer)", out _);
Check(BodyText(w).Contains("class 999"), "an unknown class stays shown");
ParseAll(host, "missing pack", out _);
body = BodyText(w);
Check(body.Contains("Rules for packs you don't have (1)") && body.Contains("A pack you don't have (it was Sack - Gems):") && body.Contains("Lockpick"), "missing-pack section");
Check(body.Contains("Pack 1: Pack 1 (24/24)") && body.Contains("in order"), "a pack in order says so");
// Two rules naming the same class for different packs: the losing pack says so.
c.Data.Rules.Add(SortRule.ForClass(ObjectClasses.Gem, 4));
Draw(w, panel);
ParseAll(host, "conflict", out _);
Check(BodyText(w).Contains("Gem: also in a rule for pack 3, which wins"), "conflict shown under the losing pack");
// Many rules still fit.
for (int i = 0; i < SortStore.MaxRules; i++) c.Data.Rules.Add(SortRule.ForName("x" + i, 1 + i % 8));
for (int i = 0; i < SortStore.MaxRules; i++) c.Data.Rules.Add(SortRule.For(1 + i % 8, new[] { ObjectClasses.Armor, ObjectClasses.Food }, "x" + i, "y" + i));
Draw(w, panel);
ParseAll(host, "64+ rules", out int many);
Check(many < 1500, $"many rules fit ({many} ops)");
@ -932,64 +1055,107 @@ namespace RynthSort.Tests
Check(BodyText(w).Contains("Log in"), "logged-out text");
}
private static byte[] TextEvent(string text, bool submitted)
{
byte[] t = Encoding.UTF8.GetBytes(text);
var payload = new byte[3 + t.Length];
payload[0] = submitted ? (byte)1 : (byte)0;
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(1), (ushort)t.Length);
t.CopyTo(payload, 3);
return payload;
}
private static void WindowEvents()
{
var (c, panel, host, w) = Window();
Draw(w, panel);
int rules = c.Data.Rules.Count;
uint seq = 0;
void Send(ushort type, string id, byte[] payload)
{
Apply(host, Event(type, ++seq, w.Hash, w.KeyOf(id), payload));
Draw(w, panel);
}
Apply(host, Event(1, 1, w.Hash, w.KeyOf("rule.add"), Click));
// "+ Add rule" in pack 4's section: a new, empty rule for pack 4, its editor open.
Send(1, "add.40000004", Click);
Eq(c.Data.Rules.Count, rules + 1, "Add rule");
Eq(panel.Selected, rules, "the new rule is selected");
Draw(w, panel);
SortRule r = panel.Selected!;
Check(r != null && r.IsEmpty && r.PackId == 0x40000004 && r.Pack == 4, "the new rule is selected, empty, for that pack");
Check(BodyText(w).Contains("(empty: add a class or a name)"), "an empty rule says what to do");
string k = "r" + r!.Uid;
Apply(host, Event(1, 2, w.Hash, w.KeyOf("rule.up"), Click));
Eq(panel.Selected, rules - 1, "Up moves the selection with the rule");
Draw(w, panel);
// Classes through the picker (its first line is "Add a class...").
Send(3, k + ".addclass", BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.Armor) + 1));
Check(r.Classes.Count == 1 && r.HasClass(ObjectClasses.Armor), "picker adds Armor");
int clothing = ObjectClasses.Choices.Where(x => x != ObjectClasses.Armor).ToList().IndexOf(ObjectClasses.Clothing) + 1;
Send(3, k + ".addclass", BitConverter.GetBytes(clothing));
Check(r.HasClass(ObjectClasses.Clothing) && r.Classes.Count == 2, "and Clothing (the picker leaves out what the rule has)");
Send(3, k + ".addclass", BitConverter.GetBytes(0));
Eq(r.Classes.Count, 2, "the picker's first line adds nothing");
// The new rule: make it a name rule for "opal" to pack 4.
Apply(host, Event(3, 3, w.Hash, w.KeyOf("rule.kind"), BitConverter.GetBytes(1)));
Draw(w, panel);
byte[] text = Encoding.UTF8.GetBytes("opal");
var payload = new byte[3 + text.Length];
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(1), (ushort)text.Length);
text.CopyTo(payload, 3);
Apply(host, Event(5, 4, w.Hash, w.KeyOf("rule.text"), payload));
Apply(host, Event(3, 5, w.Hash, w.KeyOf("rule.pack"), BitConverter.GetBytes(3)));
SortRule r = c.Data.Rules[rules - 1];
Check(r.Kind == RuleKind.Name && r.Text == "opal" && r.Pack == 4, "edited through the combo, text box and pack combo");
Draw(w, panel);
// Names: typed and Enter, or typed and Add.
Send(5, k + ".draft", TextEvent("Shield", true));
Check(r.Names.Count == 1 && r.HasName("Shield"), "Enter adds the name");
Send(5, k + ".draft", TextEvent("Buckler", false));
Eq(r.Names.Count, 1, "typing alone adds nothing");
Send(1, k + ".addname", Click);
Check(r.HasName("Buckler") && r.Names.Count == 2, "Add adds it");
Send(5, k + ".draft", TextEvent("shield", true));
Eq(r.Names.Count, 2, "the same name in another case isn't added twice");
Check(BodyText(w).Contains("Armor, Clothing, name has \"Buckler\", name has \"Shield\""), "the row lists them");
// Its checkbox turns it off.
Apply(host, Event(2, 6, w.Hash, w.KeyOf("on." + (rules - 1)), new byte[] { 0 }));
Check(!r.On, "checkbox turns the rule off");
Draw(w, panel);
// Chips take entries out.
Send(1, $"{k}.c{ObjectClasses.Clothing}", Click);
Check(!r.HasClass(ObjectClasses.Clothing) && r.HasClass(ObjectClasses.Armor), "a class chip removes its class");
Send(1, k + ".n0", Click);
Check(!r.HasName("Buckler") && r.HasName("Shield"), "a name chip removes its name (A-Z: Buckler first)");
Apply(host, Event(1, 7, w.Hash, w.KeyOf("rule.down"), Click));
Eq(c.Data.Rules.IndexOf(r), rules, "Down");
Draw(w, panel);
Apply(host, Event(1, 8, w.Hash, w.KeyOf("rule.remove"), Click));
Check(!c.Data.Rules.Contains(r) && c.Data.Rules.Count == rules, "Remove");
Draw(w, panel);
// Another pack through the picker.
Send(3, k + ".pack", BitConverter.GetBytes(1));
Check(r.Pack == 2 && r.PackId == 0x40000002 && r.PackNote.StartsWith("Pack 2 - "), $"moved to pack 2, kept by its id ({r.PackNote})");
string body = BodyText(w);
Check(body.IndexOf("Pack 2: ", StringComparison.Ordinal) < body.IndexOf("Armor, name has", StringComparison.Ordinal)
&& body.IndexOf("Armor, name has", StringComparison.Ordinal) < body.IndexOf("Pack 3: ", StringComparison.Ordinal), "now listed under pack 2");
// Class combo on rule 1.
Apply(host, Event(1, 9, w.Hash, w.KeyOf("row.0"), Click));
Draw(w, panel);
Apply(host, Event(3, 10, w.Hash, w.KeyOf("rule.class"), BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.HealingKit))));
Eq(c.Data.Rules[0].Class, ObjectClasses.HealingKit, "class combo");
// On and off.
Send(2, k + ".on", new byte[] { 0 });
Check(!r.On, "the box turns the rule off");
Send(2, k + ".on", new byte[] { 1 });
Check(r.On, "and on");
// Merge rules: a second rule for pack 3 joins the first.
Send(1, "add.40000003", Click);
SortRule second = panel.Selected!;
Send(3, "r" + second.Uid + ".addclass", BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.Lockpick) + 1));
Check(BodyText(w).Contains("Merge rules"), "two rules in a pack: Merge rules offered");
int before = c.Data.Rules.Count;
Send(1, "merge.40000003", Click);
Eq(c.Data.Rules.Count, before - 1, "two rules became one");
SortRule merged = c.Data.Rules.Single(x => x.PackId == 0x40000003 || x.Pack == 3);
Check(merged.HasClass(ObjectClasses.Gem) && merged.HasClass(ObjectClasses.Key) && merged.HasClass(ObjectClasses.ManaStone) && merged.HasClass(ObjectClasses.Lockpick),
"the merged rule has every class");
// Remove.
Send(1, k + ".row", Click);
Check(ReferenceEquals(panel.Selected, r), "picked again");
Send(1, k + ".remove", Click);
Check(!c.Data.Rules.Contains(r) && panel.Selected == null, "Remove");
// Settings and buttons.
Apply(host, Event(6, 11, w.Hash, w.KeyOf("settings"), new byte[] { 1 }));
Draw(w, panel);
Apply(host, Event(3, 12, w.Hash, w.KeyOf("settle"), BitConverter.GetBytes(12)));
Apply(host, Event(3, 13, w.Hash, w.KeyOf("gap"), BitConverter.GetBytes(50_000)));
Apply(host, Event(2, 14, w.Hash, w.KeyOf("combat"), new byte[] { 1 }));
Send(6, "settings", new byte[] { 1 });
Send(3, "settle", BitConverter.GetBytes(12));
Send(3, "gap", BitConverter.GetBytes(50_000));
Send(2, "combat", new byte[] { 1 });
Check(c.Data.Settings.SettleSec == 12 && c.Data.Settings.GapMs == SortSettings.GapMax && c.Data.Settings.SortInCombat, "sliders (clamped) and the fights box");
Apply(host, Event(2, 15, w.Hash, w.KeyOf("auto"), new byte[] { 0 }));
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[] { 0 });
Check(!c.Data.Settings.Auto, "auto-sort box");
Apply(host, Event(1, 16, w.Hash, w.KeyOf("job.all"), Click));
Eq(c.Job, SortScope.All, "Tidy button");
Apply(host, Event(1, 17, w.Hash, w.KeyOf("job.unpack"), Click));
Send(1, "job.all", Click);
Eq(c.Job, SortScope.All, "Sort now button");
Send(1, "job.unpack", Click);
Check(c.Job == SortScope.Unpack && c.UnpackWhich == null, "Empty side packs button");
}
}

View file

@ -4,7 +4,12 @@
Offline checks for RynthSort: rule matching, pack choice (a full pack only takes an item that
joins a stack there), Tidy / Clean / Unpack planning, the "stay out of the way" gates (looting,
vendor, trade, busy, portal space and RynthAi's activity bits), one move at a time with the
gap and the back-off after refusals, the per-character file and the Lua script import, and that
gap and the back-off after refusals, the per-character file and the Lua script import, rules
tied to pack ids (and the one-time fix of the Lua script's pack numbers, which counted foci),
rules with several classes and names (and old files migrating to them), the order inside
packs (every order of up to 7 items, shuffled packs to 102), slot orders and the pack column,
stacks joined in place, that a fixed inventory runs out of moves (planner and loop),
the pack picker's labels, spell component classification, and that
the window's display list is accepted by the engine's own parser (RynthCore
src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs, compiled in from the sibling
RynthCore checkout). Nothing native is loaded: no AC, no ImGui context. Files go to a temp