Snapshot for release 2026.10.12.1 (internal 8d252bd)
This commit is contained in:
parent
504a6f080a
commit
3c4f093e3d
60 changed files with 5748 additions and 602 deletions
|
|
@ -29,6 +29,32 @@ internal sealed unsafe class HostSortWorld : ISortWorld
|
|||
|
||||
public SortInventory? ReadInventory() => _reader.Read(_host);
|
||||
|
||||
// PutItemInContainer answered "not bound" once: plain moves from then on.
|
||||
private bool _putUnbound;
|
||||
|
||||
public SortAbilities Abilities => new()
|
||||
{
|
||||
ReadOrder = _host.HasContainerOrder,
|
||||
PlaceMoves = _host.HasPutItemInContainer && !_putUnbound,
|
||||
Merge = _host.HasMergeStackInternal,
|
||||
};
|
||||
|
||||
// Diagnostics: a "looting" pause that lasts says what the open container looked like.
|
||||
private long _lootPauseSince = -1;
|
||||
private bool _lootPauseLogged;
|
||||
private int _lootPauseChanges, _lootPauseLastCount = int.MinValue;
|
||||
private void NoteLongLootPause(bool looting, uint ground, int count, long nowMs)
|
||||
{
|
||||
if (!looting) { _lootPauseSince = -1; _lootPauseLogged = false; _lootPauseChanges = 0; _lootPauseLastCount = int.MinValue; return; }
|
||||
if (_lootPauseSince < 0) _lootPauseSince = nowMs;
|
||||
if (count != _lootPauseLastCount) { _lootPauseChanges++; _lootPauseLastCount = count; }
|
||||
if (!_lootPauseLogged && nowMs - _lootPauseSince > 20_000)
|
||||
{
|
||||
_lootPauseLogged = true;
|
||||
try { _host.Log($"[RynthSort] paused for looting over 20 s: open container 0x{ground:X8}, item count now {count}, {_lootPauseChanges} count change(s) in that time"); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
public GateInputs ReadGate(bool sortInCombat, long nowMs)
|
||||
{
|
||||
var g = new GateInputs { SortInCombat = sortInCombat };
|
||||
|
|
@ -38,10 +64,13 @@ internal sealed unsafe class HostSortWorld : ISortWorld
|
|||
int count = 0;
|
||||
if (ground != 0)
|
||||
{
|
||||
count = _host.HasGetNumContainedItems ? _host.GetNumContainedItems(ground) : -1;
|
||||
if (count < 0) count = _host.GetContainerContents(ground, _groundBuf);
|
||||
// One way of counting only: mixing the two (the item count when it reads, else the
|
||||
// contents list) could flip between two different numbers and look like looting.
|
||||
count = _host.HasGetNumContainedItems ? _host.GetNumContainedItems(ground)
|
||||
: _host.GetContainerContents(ground, _groundBuf);
|
||||
}
|
||||
g.Looting = _loot.Update(ground, count, nowMs);
|
||||
NoteLongLootPause(g.Looting, ground, count, nowMs);
|
||||
|
||||
g.VendorOpen = _host.HasVendorTrade ? _host.TryGetVendorInfo(out _) : _vendorOpenByEvent();
|
||||
g.TradeOpen = _host.HasTrade && _host.TryGetTradeState(out TradeState trade) && trade.IsOpen;
|
||||
|
|
@ -56,12 +85,22 @@ internal sealed unsafe class HostSortWorld : ISortWorld
|
|||
uint id = move.Item.Id;
|
||||
if (move.MergeInto != 0 && _host.HasMergeStackInternal)
|
||||
return _host.MergeStackInternal(id, move.MergeInto);
|
||||
if (move.Kind == MoveKind.Stack) return false; // a join in place needs the merge
|
||||
if (move.Placement >= 0 && _host.HasPutItemInContainer && !_putUnbound)
|
||||
{
|
||||
int rc = _host.PutItemInContainer(id, move.Dest.Id, move.Placement);
|
||||
if (rc != -1) return rc == 1;
|
||||
_putUnbound = true;
|
||||
try { _host.Log("[RynthSort] this client can't send a move to a slot; items are moved to their packs but not put in order"); } catch { }
|
||||
}
|
||||
if (move.Kind == MoveKind.Reorder) return false; // a slot change in place needs PutItemInContainer
|
||||
return _host.HasMoveItemInternal && _host.MoveItemInternal(id, move.Dest.Id, 0, Math.Max(1, move.Item.Stack));
|
||||
}
|
||||
|
||||
public MoveObservation Observe(uint itemId)
|
||||
public MoveObservation Observe(in SortMove move)
|
||||
{
|
||||
var o = new MoveObservation();
|
||||
uint itemId = move.Item.Id;
|
||||
var o = new MoveObservation { Slot = -1 };
|
||||
if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(itemId, out uint container, out uint wielder, out _))
|
||||
{
|
||||
o.Exists = true;
|
||||
|
|
@ -75,6 +114,8 @@ internal sealed unsafe class HostSortWorld : ISortWorld
|
|||
o.Container = 0xFFFFFFFF;
|
||||
}
|
||||
o.Stack = _host.TryGetObjectIntProperty(itemId, 12, out int s) && s > 0 ? s : 1;
|
||||
if (move.Kind == MoveKind.Reorder && o.Exists && o.Container == move.Dest.Id)
|
||||
o.Slot = _reader.SlotOf(_host, move.Dest.Id, itemId);
|
||||
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out uint error, out uint type, out uint obj))
|
||||
{
|
||||
o.ErrorSeq = seq;
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ public static unsafe class PluginExports
|
|||
public static IntPtr GetName() => LiteralPointer("RynthSort"u8);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
|
||||
public static IntPtr GetVersion() => LiteralPointer("0.3.0"u8);
|
||||
|
||||
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
<!--
|
||||
RynthSort: keeps a character's packs sorted while they play or while RynthAi hunts. New
|
||||
items that land in the main pack move to the side pack their rule names, after a settle
|
||||
time; Tidy, Clean and Unpack on demand; /rsort. Replaces the RynthSort Lua script (its saved
|
||||
time; misplaced items move to theirs, stacks are joined and items are put in order inside
|
||||
each pack (slot orders, API v80); Sort now, Clean and Unpack on demand; /rsort. Replaces the RynthSort Lua script (its saved
|
||||
rules are imported on first run). Pack moves wait for RynthAi through its read-only
|
||||
"RynthAi.Activity" interface (Shared/RynthAiActivityApi.cs). UI: the engine's script
|
||||
windows (ImGui), no Avalonia.
|
||||
|
|
@ -26,8 +27,8 @@
|
|||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw the
|
||||
window; vendor info (v67), plugin interfaces (v68), refusals (v70) and trade (v72) are
|
||||
each checked first. Below v71 it still sorts (/rsort on|off|now|tidy|clean|unpack). -->
|
||||
window; vendor info (v67), plugin interfaces (v68), refusals (v70), trade (v72) and slot
|
||||
orders / moves to a slot (v80: in-pack order, top-to-bottom pack numbers) are each checked first. Below v71 it still sorts (/rsort on|off|now|tidy|clean|unpack). -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Keeps your packs sorted: new loot goes to the pack its rule names.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
|
|
|||
|
|
@ -11,12 +11,14 @@ using RynthCore.PluginCore;
|
|||
namespace RynthCore.Plugin.RynthSort;
|
||||
|
||||
/// <summary>
|
||||
/// RynthSort: keeps your packs sorted while you play or RynthAi hunts. New items that land in the
|
||||
/// main pack move to the side pack their rule names once they have sat there for the settle time;
|
||||
/// Tidy also moves misplaced items between side packs, Clean sends items no rule wants back to the
|
||||
/// main pack, Unpack empties the side packs. Rules are tried in order and the first that matches
|
||||
/// wins: by item class or by part of the name. Rules and settings are kept per character; the
|
||||
/// RynthSort Lua script's saved rules are taken over on a character's first run.
|
||||
/// RynthSort: keeps your packs sorted while you play or RynthAi hunts. Auto-sort keeps every pack
|
||||
/// tidy: new items that land in the main pack move to the side pack their rule names once they have
|
||||
/// sat there for the settle time, items in the wrong side pack move to theirs, stacks of one kind
|
||||
/// are joined and (with the engine's slot orders, API v80) items are put in order, A-Z, inside
|
||||
/// each pack. Clean also sends items no rule wants back to the main pack; Unpack empties the side
|
||||
/// packs. A rule lists classes and parts of names and the pack they go to; a name match beats a
|
||||
/// class match. Rules and settings are kept per character; the RynthSort Lua script's saved rules
|
||||
/// are taken over on a character's first run.
|
||||
///
|
||||
/// It stays out of the way (Sorting/SortGate.cs): nothing moves while a corpse or chest is being
|
||||
/// looted, a vendor or trade window is open, the character is busy or animating, in portal space,
|
||||
|
|
@ -28,7 +30,7 @@ namespace RynthCore.Plugin.RynthSort;
|
|||
/// </summary>
|
||||
public sealed class RynthSortPlugin : RynthPluginBase
|
||||
{
|
||||
public const string Version = "0.1.0";
|
||||
public const string Version = "0.3.0";
|
||||
private const long IdentityRetryMs = 1000;
|
||||
private const long SaveDelayMs = 750;
|
||||
private const long PassIntervalMs = 500;
|
||||
|
|
@ -51,6 +53,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
private long _saveDueMs;
|
||||
private bool _vendorOpen;
|
||||
private bool _noUiLogged;
|
||||
private bool _backupOnSave;
|
||||
private readonly List<string> _warnings = new();
|
||||
|
||||
public override int Initialize()
|
||||
|
|
@ -58,6 +61,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
_ui.Log = msg => Host.Log(msg);
|
||||
_world = new HostSortWorld(Host, _reader, _loot, () => _vendorOpen);
|
||||
_sort.SettingsChanged = RequestSave;
|
||||
_sort.PacksFixed = OnPacksFixed;
|
||||
_panel = new SortPanel(_sort, RequestSave)
|
||||
{
|
||||
Warnings = () => _warnings,
|
||||
|
|
@ -143,8 +147,6 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
Print("Auto-sort " + word);
|
||||
break;
|
||||
case "now":
|
||||
_sort.StartJob(SortScope.Main);
|
||||
break;
|
||||
case "tidy":
|
||||
_sort.StartJob(SortScope.All);
|
||||
break;
|
||||
|
|
@ -227,6 +229,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
if (problem != null) Host.Log($"[RynthSort] couldn't read the saved rules ({problem}); using defaults.");
|
||||
_sort.Data = data;
|
||||
_identityKnown = true;
|
||||
_backupOnSave = false;
|
||||
|
||||
string own = _store.PathFor(server, name);
|
||||
if (data.ImportedFrom.Length > 0 && !File.Exists(own))
|
||||
|
|
@ -281,6 +284,25 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The one-time pack fix ran: one log line per rule, a chat line, and a save (keeping a .bak of an imported file).</summary>
|
||||
private void OnPacksFixed(List<string> lines, int changed)
|
||||
{
|
||||
bool imported = _sort.Data.ImportedFrom.Length > 0;
|
||||
foreach (string line in lines) Host.Log("[RynthSort] pack fix: " + line);
|
||||
if (imported)
|
||||
{
|
||||
int left = lines.Count - changed;
|
||||
Print($"The rules taken over from the RynthSort script counted foci as packs: {changed} now point at the right pack"
|
||||
+ (left > 0 ? $", {left} left as they were (see the log)." : "."));
|
||||
_backupOnSave = true;
|
||||
}
|
||||
else if (changed > 0)
|
||||
{
|
||||
Host.Log($"[RynthSort] pack fix: {changed} rule(s) now remember their pack by id");
|
||||
}
|
||||
RequestSave();
|
||||
}
|
||||
|
||||
private void RequestSave()
|
||||
{
|
||||
if (_window != null) _window.NeedsPass = true;
|
||||
|
|
@ -292,8 +314,9 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
_saveDueMs = 0;
|
||||
if (!_identityKnown) return;
|
||||
_sort.Data.Settings.Clamp();
|
||||
string? error = _store.Save(_server, _character, _sort.Data);
|
||||
string? error = _store.Save(_server, _character, _sort.Data, _backupOnSave);
|
||||
if (error != null) Host.Log("[RynthSort] save failed: " + error);
|
||||
else _backupOnSave = false;
|
||||
}
|
||||
|
||||
/// <summary>A pass when one is wanted, or on the refresh interval while visible (the status ticks on).</summary>
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ internal sealed class SortSettings
|
|||
{
|
||||
public const int SettleMin = 0, SettleMax = 30, GapMin = 100, GapMax = 3000;
|
||||
|
||||
/// <summary>Auto-sort: new items in the main pack go to their pack after the settle time.</summary>
|
||||
/// <summary>Auto-sort: keeps every pack tidy (new items from the main pack after the settle time, misplaced items, stacks, order).</summary>
|
||||
public bool Auto = true;
|
||||
/// <summary>How long a new item sits in the main pack before it moves (seconds).</summary>
|
||||
public int SettleSec = 5;
|
||||
|
|
@ -21,8 +21,17 @@ internal sealed class SortSettings
|
|||
public int GapMs = 300;
|
||||
/// <summary>Moves may go while RynthAi fights (never while it waits on the server or animates).</summary>
|
||||
public bool SortInCombat;
|
||||
/// <summary>The window was open when last seen.</summary>
|
||||
public bool WindowOpen = true;
|
||||
/// <summary>Items are put in order inside each pack (A-Z by name), when the engine can read slot orders (API v80).</summary>
|
||||
public bool OrderInPacks = true;
|
||||
/// <summary>The order inside a pack groups by kind (class) first, then name.</summary>
|
||||
public bool OrderKindFirst;
|
||||
/// <summary>
|
||||
/// The window was open when last seen. Closed for a character RynthSort hasn't seen (it
|
||||
/// has a button on the RynthCore bar and /rsort), so a new character or alt doesn't get it
|
||||
/// popping up at every login until closed once; open once after taking over the Lua
|
||||
/// script's rules, to show them.
|
||||
/// </summary>
|
||||
public bool WindowOpen;
|
||||
|
||||
public void Clamp()
|
||||
{
|
||||
|
|
@ -38,6 +47,17 @@ internal sealed class CharacterSortData
|
|||
public SortSettings Settings = new();
|
||||
/// <summary>Where these came from on first run ("" = defaults, else the Lua script's file).</summary>
|
||||
public string ImportedFrom = string.Empty;
|
||||
/// <summary>
|
||||
/// The rules are tied to pack ids (<see cref="PackFix"/> ran once). False for files saved
|
||||
/// before pack ids, a new character's defaults and a fresh import from the Lua script.
|
||||
/// </summary>
|
||||
public bool PacksFixed;
|
||||
/// <summary>
|
||||
/// The Lua script's rules as its file has them, while <see cref="PacksFixed"/> is false and the
|
||||
/// rules came from it: tells untouched imported rules (Lua numbers) from ones picked in
|
||||
/// RynthSort's window since. Null when unknown. Not saved.
|
||||
/// </summary>
|
||||
public List<SortRule>? LuaRules;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -87,13 +107,20 @@ internal sealed class SortStore
|
|||
string own = PathFor(server, character);
|
||||
if (File.Exists(own))
|
||||
{
|
||||
if (TryRead(own, out CharacterSortData? d, out problem)) return d!;
|
||||
return new CharacterSortData();
|
||||
if (!TryRead(own, out CharacterSortData? d, out problem)) return new CharacterSortData();
|
||||
// Imported before pack ids: the Lua script's file says which rules are still its own.
|
||||
if (!d!.PacksFixed && d.ImportedFrom.Length > 0 && File.Exists(d.ImportedFrom)
|
||||
&& TryRead(d.ImportedFrom, out CharacterSortData? luaNow, out _))
|
||||
d.LuaRules = luaNow!.Rules;
|
||||
return d;
|
||||
}
|
||||
string lua = LuaPathFor(server, character);
|
||||
if (File.Exists(lua) && TryRead(lua, out CharacterSortData? imported, out problem))
|
||||
{
|
||||
imported!.ImportedFrom = lua;
|
||||
imported.PacksFixed = false; // Lua pack numbers: fixed on the first settled read
|
||||
imported.LuaRules = imported.Rules.ConvertAll(r => r.Clone());
|
||||
imported.Settings.WindowOpen = true; // show the rules just taken over (the Lua file has no windowOpen)
|
||||
return imported;
|
||||
}
|
||||
return new CharacterSortData();
|
||||
|
|
@ -149,37 +176,67 @@ internal sealed class SortStore
|
|||
st.SettleSec = Int(s, "settleSec", st.SettleSec);
|
||||
st.GapMs = Int(s, "gapMs", st.GapMs);
|
||||
st.SortInCombat = Bool(s, "sortInCombat", st.SortInCombat);
|
||||
st.OrderInPacks = Bool(s, "orderInPacks", st.OrderInPacks);
|
||||
st.OrderKindFirst = Bool(s, "orderKindFirst", st.OrderKindFirst);
|
||||
st.WindowOpen = Bool(s, "windowOpen", st.WindowOpen);
|
||||
st.Clamp();
|
||||
}
|
||||
if (root.TryGetProperty("importedFrom", out JsonElement f) && f.ValueKind == JsonValueKind.String)
|
||||
d.ImportedFrom = f.GetString() ?? string.Empty;
|
||||
// Missing (a version 1 file, the Lua script's file): rules by number only, not fixed yet.
|
||||
d.PacksFixed = Bool(root, "packsFixed", false);
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One rule. Version 3 has "classes" and "names" lists; anything older (versions 1 and 2, and the
|
||||
/// Lua script's file) has one test, { kind = "class" | "name", class, text }, which becomes a
|
||||
/// rule with that one class or name. Version 3 writes those old fields too (its first entry),
|
||||
/// so an older RynthSort reading a newer file still gets a sensible rule.
|
||||
/// </summary>
|
||||
private static SortRule? ParseRule(JsonElement e)
|
||||
{
|
||||
if (e.ValueKind != JsonValueKind.Object) return null;
|
||||
var r = new SortRule
|
||||
{
|
||||
On = Bool(e, "on", true),
|
||||
Kind = e.TryGetProperty("kind", out JsonElement k) && k.ValueKind == JsonValueKind.String
|
||||
&& string.Equals(k.GetString(), "name", StringComparison.OrdinalIgnoreCase) ? RuleKind.Name : RuleKind.Class,
|
||||
Class = Int(e, "class", ObjectClasses.SpellComponent),
|
||||
Text = e.TryGetProperty("text", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() ?? string.Empty : string.Empty,
|
||||
Pack = Math.Clamp(Int(e, "pack", 1), 1, MaxPack),
|
||||
PackId = UInt(e, "packId"),
|
||||
PackNote = e.TryGetProperty("packNote", out JsonElement pn) && pn.ValueKind == JsonValueKind.String ? pn.GetString() ?? string.Empty : string.Empty,
|
||||
};
|
||||
if (r.Text.Length > 64) r.Text = r.Text[..64];
|
||||
bool hasClasses = e.TryGetProperty("classes", out JsonElement cl) && cl.ValueKind == JsonValueKind.Array;
|
||||
bool hasNames = e.TryGetProperty("names", out JsonElement nm) && nm.ValueKind == JsonValueKind.Array;
|
||||
if (hasClasses || hasNames)
|
||||
{
|
||||
if (hasClasses)
|
||||
foreach (JsonElement c in cl.EnumerateArray())
|
||||
if (c.ValueKind == JsonValueKind.Number && c.TryGetDouble(out double v) && v >= 0 && v <= 1000) r.AddClass((int)Math.Round(v));
|
||||
if (hasNames)
|
||||
foreach (JsonElement n in nm.EnumerateArray())
|
||||
if (n.ValueKind == JsonValueKind.String) r.AddName(n.GetString());
|
||||
}
|
||||
else
|
||||
{
|
||||
bool byName = e.TryGetProperty("kind", out JsonElement k) && k.ValueKind == JsonValueKind.String
|
||||
&& string.Equals(k.GetString(), "name", StringComparison.OrdinalIgnoreCase);
|
||||
if (byName) r.AddName(e.TryGetProperty("text", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null);
|
||||
else r.AddClass(Int(e, "class", ObjectClasses.SpellComponent));
|
||||
}
|
||||
if (r.PackNote.Length > 96) r.PackNote = r.PackNote[..96];
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>Writes the character's file (temp file, then moved over the old one). Returns an error or null.</summary>
|
||||
public string? Save(string server, string character, CharacterSortData d)
|
||||
/// <summary>
|
||||
/// Writes the character's file (temp file, then moved over the old one). <paramref name="backup"/>:
|
||||
/// copy the old file to "<file>.bak" first (the one-time pack fix keeps one). Returns an error or null.
|
||||
/// </summary>
|
||||
public string? Save(string server, string character, CharacterSortData d, bool backup = false)
|
||||
{
|
||||
string path = PathFor(server, character);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
if (backup && File.Exists(path)) File.Copy(path, path + ".bak", overwrite: true);
|
||||
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
|
||||
File.WriteAllText(tmp, ToJson(d), new UTF8Encoding(false));
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
|
|
@ -197,16 +254,29 @@ internal sealed class SortStore
|
|||
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("version", 1);
|
||||
// 3: a rule holds several classes and names. 2: rules carry packId / packNote, and
|
||||
// packsFixed. Versions 1 and 2 still load (one class or name per rule).
|
||||
w.WriteNumber("version", 3);
|
||||
w.WriteStartArray("rules");
|
||||
foreach (SortRule r in d.Rules)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteBoolean("on", r.On);
|
||||
w.WriteString("kind", r.Kind == RuleKind.Name ? "name" : "class");
|
||||
w.WriteNumber("class", r.Class);
|
||||
w.WriteString("text", r.Text ?? string.Empty);
|
||||
w.WriteStartArray("classes");
|
||||
foreach (int c in r.Classes) w.WriteNumberValue(c);
|
||||
w.WriteEndArray();
|
||||
w.WriteStartArray("names");
|
||||
foreach (string n in r.Names) w.WriteStringValue(n);
|
||||
w.WriteEndArray();
|
||||
// The first entry the old way, for an older RynthSort reading this file (an empty
|
||||
// rule as a blank name rule, which matches nothing there too).
|
||||
bool firstIsName = r.Classes.Count == 0;
|
||||
w.WriteString("kind", firstIsName ? "name" : "class");
|
||||
w.WriteNumber("class", r.Classes.Count > 0 ? r.Classes[0] : ObjectClasses.SpellComponent);
|
||||
w.WriteString("text", firstIsName && r.Names.Count > 0 ? r.Names[0] : string.Empty);
|
||||
w.WriteNumber("pack", r.Pack);
|
||||
if (r.PackId != 0) w.WriteNumber("packId", r.PackId);
|
||||
if (r.PackNote.Length > 0) w.WriteString("packNote", r.PackNote);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
|
|
@ -215,9 +285,12 @@ internal sealed class SortStore
|
|||
w.WriteNumber("settleSec", d.Settings.SettleSec);
|
||||
w.WriteNumber("gapMs", d.Settings.GapMs);
|
||||
w.WriteBoolean("sortInCombat", d.Settings.SortInCombat);
|
||||
w.WriteBoolean("orderInPacks", d.Settings.OrderInPacks);
|
||||
w.WriteBoolean("orderKindFirst", d.Settings.OrderKindFirst);
|
||||
w.WriteBoolean("windowOpen", d.Settings.WindowOpen);
|
||||
w.WriteEndObject();
|
||||
if (d.ImportedFrom.Length > 0) w.WriteString("importedFrom", d.ImportedFrom);
|
||||
w.WriteBoolean("packsFixed", d.PacksFixed);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(ms.ToArray()) + "\n";
|
||||
|
|
@ -228,6 +301,14 @@ internal sealed class SortStore
|
|||
? v.GetBoolean()
|
||||
: fallback;
|
||||
|
||||
/// <summary>An object id (0 when missing, negative or odd).</summary>
|
||||
private static uint UInt(JsonElement o, string name)
|
||||
{
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return 0;
|
||||
if (v.TryGetUInt32(out uint u)) return u;
|
||||
return v.TryGetDouble(out double dbl) && dbl >= 0 && dbl <= uint.MaxValue && dbl == Math.Floor(dbl) ? (uint)dbl : 0;
|
||||
}
|
||||
|
||||
private static int Int(JsonElement o, string name, int fallback)
|
||||
{
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;
|
||||
|
|
|
|||
|
|
@ -10,6 +10,12 @@ namespace RynthCore.Plugin.RynthSort.Sorting;
|
|||
/// worn and wielded items; each side pack's items come from GetContainerContents(pack). A side
|
||||
/// pack is a container that holds items (ItemsCapacity above 0); foci hold none and are skipped,
|
||||
/// as are worn and wielded items. Names, classes and stack limits are kept per item id once read.
|
||||
/// GetContainerContents sorts by object id; with the engine's slot orders (API v80
|
||||
/// GetContainerOrder: what the server sent at login and with every move) each pack's items are put
|
||||
/// in their real slot order and the side packs in the pack column's order, top first, whenever
|
||||
/// that order names exactly what was read (<see cref="SortPack.ApplyOrder"/>,
|
||||
/// <see cref="SortInventory.ApplyPackOrder"/>). Without it the id order stays and nothing is
|
||||
/// reordered inside packs.
|
||||
/// </summary>
|
||||
internal sealed class InventoryReader
|
||||
{
|
||||
|
|
@ -39,6 +45,7 @@ internal sealed class InventoryReader
|
|||
|
||||
private readonly Dictionary<uint, Known> _known = new();
|
||||
private uint[] _buf = new uint[512];
|
||||
private uint[] _order = new uint[128];
|
||||
|
||||
public void Reset() => _known.Clear();
|
||||
|
||||
|
|
@ -59,12 +66,17 @@ internal sealed class InventoryReader
|
|||
foreach (uint id in top)
|
||||
{
|
||||
if (id == 0) continue;
|
||||
if (Wielded(host, id)) continue;
|
||||
uint type = host.TryGetItemType(id, out uint t) ? t : 0;
|
||||
if ((type & ItemTypeContainer) != 0)
|
||||
bool isContainer = (type & ItemTypeContainer) != 0;
|
||||
int cap = 0;
|
||||
bool capRead = isContainer && host.TryGetObjectIntProperty(id, IntItemsCapacity, out cap);
|
||||
// Every container entry, foci too and before the wielded check: the Lua script's count.
|
||||
if (isContainer) inv.Slots.Add(new SortSlot(id, capRead ? Math.Max(cap, 0) : -1));
|
||||
if (Wielded(host, id)) continue;
|
||||
if (isContainer)
|
||||
{
|
||||
// A side pack holds items; foci (containers that hold none) aren't packs or items.
|
||||
if (host.TryGetObjectIntProperty(id, IntItemsCapacity, out int cap) && cap > 0)
|
||||
if (capRead && cap > 0)
|
||||
{
|
||||
var pack = new SortPack { Id = id, Capacity = cap, Name = host.TryGetObjectName(id, out string pn) ? pn : string.Empty };
|
||||
foreach (uint inner in Contents(host, id))
|
||||
|
|
@ -80,9 +92,23 @@ internal sealed class InventoryReader
|
|||
}
|
||||
inv.Main.Items.Add(Item(host, id, type));
|
||||
}
|
||||
if (host.HasContainerOrder)
|
||||
{
|
||||
if (host.TryGetContainerOrder(player, false, ref _order, out int n)) inv.Main.ApplyOrder(_order, n);
|
||||
foreach (SortPack p in inv.Packs)
|
||||
if (host.TryGetContainerOrder(p.Id, false, ref _order, out n)) p.ApplyOrder(_order, n);
|
||||
if (host.TryGetContainerOrder(player, true, ref _order, out n)) inv.ApplyPackOrder(_order, n);
|
||||
}
|
||||
return inv;
|
||||
}
|
||||
|
||||
/// <summary>The slot <paramref name="itemId"/> holds in <paramref name="container"/> (the engine's slot order), or -1.</summary>
|
||||
public int SlotOf(RynthCoreHost host, uint container, uint itemId)
|
||||
{
|
||||
if (!host.HasContainerOrder || !host.TryGetContainerOrder(container, false, ref _order, out int n)) return -1;
|
||||
return Array.IndexOf(_order, itemId, 0, n);
|
||||
}
|
||||
|
||||
private uint[] Contents(RynthCoreHost host, uint container)
|
||||
{
|
||||
int n = host.GetContainerContents(container, _buf);
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ internal struct MoveObservation
|
|||
public uint Container;
|
||||
public uint Wielder;
|
||||
public int Stack;
|
||||
/// <summary>Its slot in its container (the engine's slot order), or -1 when unknown. Read for reorders only.</summary>
|
||||
public int Slot;
|
||||
/// <summary>The engine's refusal counter (TryGetLastWeenieError seq; 0 when unknown).</summary>
|
||||
public int ErrorSeq;
|
||||
public uint Error;
|
||||
|
|
@ -52,16 +54,35 @@ internal static class MoveTracker
|
|||
/// <summary>The longest hold after refusals in a row.</summary>
|
||||
public const long MaxBackoffMs = 30_000;
|
||||
|
||||
/// <summary>The container reads as this when the engine can't say (no ownership info).</summary>
|
||||
public const uint UnknownContainer = 0xFFFFFFFF;
|
||||
public const uint EventInventoryServerSaveFailed = 0x00A0;
|
||||
public const uint ErrorYoureTooBusy = 0x001D;
|
||||
public const uint ErrorTooManyActions = 0x0045;
|
||||
|
||||
/// <summary>
|
||||
/// What the client says about the move so far. A move within one pack (a stack joined, a slot
|
||||
/// changed) can't be judged by the item's container, which it never left: a join is answered
|
||||
/// when the item is gone or smaller, a reorder when the item sits at its slot (or left the pack).
|
||||
/// </summary>
|
||||
public static MoveOutcome Observe(MoveInFlight m, in MoveObservation o, long nowMs)
|
||||
{
|
||||
SortMove mv = m.Move;
|
||||
if (!o.Exists) return MoveOutcome.Done; // merged on arrival
|
||||
if (o.Container == mv.Dest.Id && o.Wielder == 0) return MoveOutcome.Done;
|
||||
if (mv.MergeInto != 0 && o.Stack < m.StackAtSend) return MoveOutcome.Done; // part of it joined the stack
|
||||
switch (mv.Kind)
|
||||
{
|
||||
case MoveKind.Stack:
|
||||
if (o.Stack < m.StackAtSend) return MoveOutcome.Done;
|
||||
break;
|
||||
case MoveKind.Reorder:
|
||||
if (o.Container == mv.Dest.Id && o.Slot == mv.Placement) return MoveOutcome.Done;
|
||||
if (o.Container != mv.Dest.Id && o.Container != UnknownContainer) return MoveOutcome.Done; // someone moved it away
|
||||
break;
|
||||
default:
|
||||
if (o.Container == mv.Dest.Id && o.Wielder == 0) return MoveOutcome.Done;
|
||||
if (mv.MergeInto != 0 && o.Stack < m.StackAtSend) return MoveOutcome.Done; // part of it joined the stack
|
||||
break;
|
||||
}
|
||||
if (o.ErrorSeq != 0 && o.ErrorSeq != m.ErrorSeqAtSend)
|
||||
{
|
||||
if (o.Error == ErrorYoureTooBusy || o.Error == ErrorTooManyActions) return MoveOutcome.TooBusy;
|
||||
|
|
|
|||
131
Plugins/RynthCore.Plugin.RynthSort/Sorting/PackFix.cs
Normal file
131
Plugins/RynthCore.Plugin.RynthSort/Sorting/PackFix.cs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>
|
||||
/// Ties rules to their packs' ids. Rules saved before RynthSort kept pack ids only had a number,
|
||||
/// and the Lua script's numbers counted foci as packs (game.Character.Containers: every container
|
||||
/// in the main pack, in the same order), so after a focus every imported number pointed one pack
|
||||
/// too far. Once per character, on a settled read of the packs (<see cref="Apply"/>):
|
||||
/// <list type="bullet">
|
||||
/// <item>a rule still as the Lua script had it: Lua number n is the n-th container, foci counted.
|
||||
/// A pack: the rule takes its id and its number among the real packs. A focus, or nothing there:
|
||||
/// left as it was, and said so.</item>
|
||||
/// <item>any other rule (picked in RynthSort's window, or the defaults): its number already counts
|
||||
/// real packs only, so it takes that pack's id.</item>
|
||||
/// </list>
|
||||
/// Pure: the tests drive it with hand-made inventories.
|
||||
/// </summary>
|
||||
internal static class PackFix
|
||||
{
|
||||
/// <summary>Every side-slot entry's capacity was readable (a focus and a pack can be told apart).</summary>
|
||||
public static bool Ready(SortInventory inv)
|
||||
{
|
||||
foreach (SortSlot s in inv.Slots)
|
||||
if (s.Capacity < 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The side-slot layout (ids and capacities): two reads alike mean the packs have settled.</summary>
|
||||
public static string Layout(SortInventory inv)
|
||||
{
|
||||
var sb = new StringBuilder(inv.Slots.Count * 12);
|
||||
foreach (SortSlot s in inv.Slots) sb.Append(s.Id.ToString("X8")).Append(':').Append(s.Capacity).Append(';');
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>"Sack - Salvage, Gems".</summary>
|
||||
public static string NoteOf(SortPack p) => $"{(p.Name.Length > 0 ? p.Name : "Pack")} - {p.Summary()}";
|
||||
|
||||
/// <summary>
|
||||
/// The one-time fix over <paramref name="rules"/> (only rules without a pack id are looked at).
|
||||
/// <paramref name="imported"/>: the rules came from the Lua script. <paramref name="luaRules"/>:
|
||||
/// the Lua script's rules as they are in its file (null when it can't be read: every rule is
|
||||
/// taken as imported). Returns one line per rule it looked at, saying what it did; changed
|
||||
/// counts the rules it changed.
|
||||
/// </summary>
|
||||
public static List<string> Apply(IReadOnlyList<SortRule> rules, SortInventory inv, bool imported, IReadOnlyList<SortRule>? luaRules, out int changed)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
changed = 0;
|
||||
for (int i = 0; i < rules.Count; i++)
|
||||
{
|
||||
SortRule r = rules[i];
|
||||
if (r.PackId != 0) continue;
|
||||
string who = $"rule {i + 1} ({SortRules.Describe(r)})";
|
||||
if (imported && (luaRules == null || Contains(luaRules, r)))
|
||||
{
|
||||
int n = r.Pack;
|
||||
if (n < 1 || n > inv.Slots.Count)
|
||||
{
|
||||
lines.Add($"{who}: the Lua script's pack {n} doesn't exist ({Count(inv)}); left as pack {n}");
|
||||
continue;
|
||||
}
|
||||
SortSlot slot = inv.Slots[n - 1];
|
||||
int idx = inv.IndexOf(slot.Id);
|
||||
if (!slot.IsPack || idx == 0)
|
||||
{
|
||||
lines.Add($"{who}: the Lua script's pack {n} is {(slot.IsPack ? "not a side pack" : "a focus")} (0x{slot.Id:X8}); left as pack {n}");
|
||||
continue;
|
||||
}
|
||||
SortPack p = inv.Packs[idx - 1];
|
||||
r.PackId = p.Id;
|
||||
r.Pack = idx;
|
||||
r.PackNote = NoteOf(p);
|
||||
changed++;
|
||||
lines.Add($"{who}: the Lua script's pack {n} -> pack {idx}, {r.PackNote} (0x{p.Id:X8})");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (r.Pack < 1 || r.Pack > inv.Packs.Count)
|
||||
{
|
||||
lines.Add($"{who}: pack {r.Pack}, which you don't have; left as it is");
|
||||
continue;
|
||||
}
|
||||
SortPack p = inv.Packs[r.Pack - 1];
|
||||
r.PackId = p.Id;
|
||||
r.PackNote = NoteOf(p);
|
||||
changed++;
|
||||
lines.Add($"{who}: pack {r.Pack} kept, now tied to {r.PackNote} (0x{p.Id:X8})");
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps each rule's number (and note) on its pack when that pack is carried, so the number
|
||||
/// the window shows and the fallback stay right as packs come and go. True when one changed.
|
||||
/// </summary>
|
||||
public static bool Sync(IReadOnlyList<SortRule> rules, SortInventory inv)
|
||||
{
|
||||
bool any = false;
|
||||
foreach (SortRule r in rules)
|
||||
{
|
||||
int idx = inv.IndexOf(r.PackId);
|
||||
if (idx == 0) continue;
|
||||
if (r.Pack != idx || r.PackNote.Length == 0)
|
||||
{
|
||||
r.Pack = idx;
|
||||
r.PackNote = NoteOf(inv.Packs[idx - 1]);
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
return any;
|
||||
}
|
||||
|
||||
private static bool Contains(IReadOnlyList<SortRule> list, SortRule r)
|
||||
{
|
||||
foreach (SortRule o in list)
|
||||
if (o.SameAs(r)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string Count(SortInventory inv)
|
||||
{
|
||||
int foci = 0;
|
||||
foreach (SortSlot s in inv.Slots) if (!s.IsPack) foci++;
|
||||
return $"{inv.Packs.Count} pack{(inv.Packs.Count == 1 ? "" : "s")} and {foci} foc{(foci == 1 ? "us" : "i")}";
|
||||
}
|
||||
}
|
||||
146
Plugins/RynthCore.Plugin.RynthSort/Sorting/PackOrder.cs
Normal file
146
Plugins/RynthCore.Plugin.RynthSort/Sorting/PackOrder.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>
|
||||
/// The order items keep inside a pack, and the moves that get a pack there. Pure: the tests drive it.
|
||||
///
|
||||
/// The order: by name A-Z (any case, then exact), so like items sit together; the same name with
|
||||
/// another kind of stack (class id) next; then by object id, which never changes. Optionally by
|
||||
/// kind first (the class's label: "Armor", "Gem", ...), then the same. It is a total order on the
|
||||
/// items, so a pack has exactly one target order however its items got there.
|
||||
///
|
||||
/// The moves: one item at a time to a slot (the engine's PutItemInContainer, API v80: placement =
|
||||
/// the index it should end at, counted without it, which is how ACE inserts). The items already in
|
||||
/// order relative to each other (a longest increasing run of target ranks) stay; one of the others
|
||||
/// is put right after the last of those that comes before it. That run grows by at least one with
|
||||
/// every move, so a pack of n items is in order after at most n - (longest run) moves, and an
|
||||
/// item that arrived in the right place costs none.
|
||||
/// </summary>
|
||||
internal static class PackOrder
|
||||
{
|
||||
/// <summary>The target order (see the class summary). <paramref name="kindFirst"/>: by class label first.</summary>
|
||||
public static int Compare(SortItem a, SortItem b, bool kindFirst)
|
||||
{
|
||||
if (ReferenceEquals(a, b)) return 0;
|
||||
if (kindFirst && a.ObjectClass != b.ObjectClass)
|
||||
{
|
||||
int k = string.Compare(ObjectClasses.Label(a.ObjectClass), ObjectClasses.Label(b.ObjectClass), StringComparison.OrdinalIgnoreCase);
|
||||
if (k != 0) return k;
|
||||
k = a.ObjectClass.CompareTo(b.ObjectClass);
|
||||
if (k != 0) return k;
|
||||
}
|
||||
string an = a.Name ?? string.Empty, bn = b.Name ?? string.Empty;
|
||||
int c = string.Compare(an, bn, StringComparison.OrdinalIgnoreCase);
|
||||
if (c != 0) return c;
|
||||
c = string.CompareOrdinal(an, bn);
|
||||
if (c != 0) return c;
|
||||
c = a.Wcid.CompareTo(b.Wcid);
|
||||
return c != 0 ? c : a.Id.CompareTo(b.Id);
|
||||
}
|
||||
|
||||
/// <summary>Every item has a name: an item the client hasn't described yet would sort as "" and move again once named.</summary>
|
||||
public static bool AllNamed(IReadOnlyList<SortItem> items)
|
||||
{
|
||||
foreach (SortItem it in items)
|
||||
if (string.IsNullOrEmpty(it.Name)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Each item's place in the target order (0 = first), in the items' current order.</summary>
|
||||
public static int[] Ranks(IReadOnlyList<SortItem> items, bool kindFirst)
|
||||
{
|
||||
int n = items.Count;
|
||||
var idx = new int[n];
|
||||
for (int i = 0; i < n; i++) idx[i] = i;
|
||||
Array.Sort(idx, (x, y) => Compare(items[x], items[y], kindFirst));
|
||||
var rank = new int[n];
|
||||
for (int r = 0; r < n; r++) rank[idx[r]] = r;
|
||||
return rank;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which positions are in a longest increasing run of <paramref name="rank"/> (they stay put).
|
||||
/// O(n^2) over a pack (at most ~100 items); the earliest-ending run is kept, so the answer is
|
||||
/// the same for the same list.
|
||||
/// </summary>
|
||||
public static bool[] Kept(int[] rank)
|
||||
{
|
||||
int n = rank.Length;
|
||||
var len = new int[n];
|
||||
var prev = new int[n];
|
||||
int best = -1;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
len[i] = 1;
|
||||
prev[i] = -1;
|
||||
for (int j = 0; j < i; j++)
|
||||
if (rank[j] < rank[i] && len[j] + 1 > len[i]) { len[i] = len[j] + 1; prev[i] = j; }
|
||||
if (best < 0 || len[i] > len[best]) best = i;
|
||||
}
|
||||
var kept = new bool[n];
|
||||
for (int i = best; i >= 0; i = prev[i]) kept[i] = true;
|
||||
return kept;
|
||||
}
|
||||
|
||||
/// <summary>How many items are out of place (would move): 0 = in order.</summary>
|
||||
public static int OutOfPlace(IReadOnlyList<SortItem> items, bool kindFirst)
|
||||
{
|
||||
if (items.Count < 2) return 0;
|
||||
bool[] kept = Kept(Ranks(items, kindFirst));
|
||||
int n = 0;
|
||||
foreach (bool k in kept) if (!k) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The next move that puts the pack in order: the out-of-place item with the lowest target rank
|
||||
/// that <paramref name="movable"/> allows, and the slot it goes to (counted without it). False
|
||||
/// when the pack is in order, or only items that can't move now are out of place.
|
||||
/// </summary>
|
||||
public static bool NextMove(IReadOnlyList<SortItem> items, bool kindFirst, Func<SortItem, bool> movable, out SortItem item, out int placement)
|
||||
{
|
||||
item = null!;
|
||||
placement = -1;
|
||||
int n = items.Count;
|
||||
if (n < 2) return false;
|
||||
int[] rank = Ranks(items, kindFirst);
|
||||
bool[] kept = Kept(rank);
|
||||
int pick = -1;
|
||||
for (int i = 0; i < n; i++)
|
||||
if (!kept[i] && movable(items[i]) && (pick < 0 || rank[i] < rank[pick])) pick = i;
|
||||
if (pick < 0) return false;
|
||||
|
||||
// Right after the last kept item that comes before it in the target order.
|
||||
int after = -1;
|
||||
for (int i = 0; i < n; i++)
|
||||
if (kept[i] && rank[i] < rank[pick]) after = i; // kept items rise with i: the last one wins
|
||||
item = items[pick];
|
||||
placement = after < 0 ? 0 : (after > pick ? after : after + 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The slot an item arriving in a pack should take so it lands where the order wants it: after
|
||||
/// every item there that comes before it. In a pack already in order that is its final place.
|
||||
/// </summary>
|
||||
public static int InsertAt(IReadOnlyList<SortItem> items, SortItem arriving, bool kindFirst)
|
||||
{
|
||||
int at = 0;
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
if (Compare(items[i], arriving, kindFirst) < 0) at = i + 1;
|
||||
return at;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The list after moving <paramref name="item"/> to <paramref name="placement"/> as ACE does it
|
||||
/// (taken out, the others close up, put in at that index, clamped to the end). For the tests'
|
||||
/// pretend server and the planner's checks.
|
||||
/// </summary>
|
||||
public static void Apply(List<SortItem> items, SortItem item, int placement)
|
||||
{
|
||||
items.Remove(item);
|
||||
items.Insert(Math.Clamp(placement, 0, items.Count), item);
|
||||
}
|
||||
}
|
||||
|
|
@ -11,19 +11,36 @@ internal interface ISortWorld
|
|||
SortInventory? ReadInventory();
|
||||
/// <summary>The "stay out of the way" inputs now.</summary>
|
||||
GateInputs ReadGate(bool sortInCombat, long nowMs);
|
||||
/// <summary>Sends the move to the client (merge or plain move). False = the engine refused it.</summary>
|
||||
/// <summary>Sends the move to the client (merge, move to a slot, or plain move). False = the engine refused it.</summary>
|
||||
bool SendMove(in SortMove move);
|
||||
/// <summary>The moved item and the server's last refusal.</summary>
|
||||
MoveObservation Observe(uint itemId);
|
||||
/// <summary>The moved item (its slot too, for a reorder) and the server's last refusal.</summary>
|
||||
MoveObservation Observe(in SortMove move);
|
||||
/// <summary>The engine's refusal counter now (0 when the engine can't say).</summary>
|
||||
int ErrorSeqNow();
|
||||
/// <summary>What this engine lets the planner do beyond moving items to their packs.</summary>
|
||||
SortAbilities Abilities { get; }
|
||||
}
|
||||
|
||||
/// <summary>What the engine can do for RynthSort (the plugin asks the host; the tests say).</summary>
|
||||
internal struct SortAbilities
|
||||
{
|
||||
/// <summary>Slot orders are readable (API v80 GetContainerOrder).</summary>
|
||||
public bool ReadOrder;
|
||||
/// <summary>A move can name its slot (API v80 PutItemInContainer, bound on this client).</summary>
|
||||
public bool PlaceMoves;
|
||||
/// <summary>Stacks can be merged (MergeStackInternal).</summary>
|
||||
public bool Merge;
|
||||
|
||||
public static SortAbilities All => new() { ReadOrder = true, PlaceMoves = true, Merge = true };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sorting loop, one step per plugin tick: one move at a time, each waited on until the
|
||||
/// server answers it (the item lands, or it is refused, or the time limit passes), then a gap.
|
||||
/// Auto-sort moves new main-pack items after the settle time, one per gap; a job asked for
|
||||
/// (Sort now, Tidy, Clean, Unpack) goes as fast as the server answers. Nothing is sent while the
|
||||
/// Auto-sort keeps every pack tidy (<see cref="SortScope.All"/>): new main-pack items go to their
|
||||
/// packs after the settle time, misplaced side-pack items to theirs, then stacks are joined and
|
||||
/// items put in order inside each pack, one move per gap; a job asked for (Sort now, Clean,
|
||||
/// Unpack) goes as fast as the server answers. Nothing is sent while the
|
||||
/// gate says why not (<see cref="SortGate"/>). An item that fails is left alone for a minute, and
|
||||
/// failures in a row hold every move off longer and longer (<see cref="MoveTracker.BackoffMs"/>).
|
||||
/// </summary>
|
||||
|
|
@ -52,16 +69,25 @@ internal sealed class SortController
|
|||
public RynthAiActivity? LastBot { get; private set; }
|
||||
/// <summary>The last few moves and job results, newest first.</summary>
|
||||
public readonly List<string> Log = new();
|
||||
/// <summary>What the engine allowed at the last tick (the window says when ordering isn't possible).</summary>
|
||||
public SortAbilities Abilities { get; private set; }
|
||||
public int Moved { get; private set; }
|
||||
public int Failed { get; private set; }
|
||||
|
||||
/// <summary>Settings changed by a command (auto-sort off for Unpack): the plugin saves.</summary>
|
||||
public Action? SettingsChanged;
|
||||
/// <summary>The one-time pack fix ran (<see cref="PackFix"/>): its lines and how many rules it changed. The plugin logs and saves.</summary>
|
||||
public Action<List<string>, int>? PacksFixed;
|
||||
|
||||
/// <summary>How long the side-slot layout must read the same before the one-time pack fix runs.</summary>
|
||||
public const long FixSettleMs = 3000;
|
||||
|
||||
private MoveInFlight? _inFlight;
|
||||
private long _nextStepMs;
|
||||
private long _nextViewMs;
|
||||
private int _failuresInARow;
|
||||
private string? _fixLayout;
|
||||
private long _fixLayoutSince;
|
||||
|
||||
public bool HasMoveOut => _inFlight != null;
|
||||
|
||||
|
|
@ -73,6 +99,7 @@ internal sealed class SortController
|
|||
_inFlight = null;
|
||||
_nextStepMs = _nextViewMs = 0;
|
||||
_failuresInARow = 0;
|
||||
_fixLayout = null;
|
||||
Job = null;
|
||||
UnpackWhich = null;
|
||||
LastBot = null;
|
||||
|
|
@ -107,6 +134,25 @@ internal sealed class SortController
|
|||
SettingsChanged?.Invoke();
|
||||
}
|
||||
|
||||
// Items put in order in one pack go in the log as one line that counts up.
|
||||
private string? _reorderRunLine;
|
||||
private int _reorderRunPack = -1, _reorderRunCount;
|
||||
|
||||
private void NoteReorderRun(in SortMove m)
|
||||
{
|
||||
if (_reorderRunLine != null && _reorderRunPack == m.DestIndex && Log.Count > 0 && ReferenceEquals(Log[0], _reorderRunLine))
|
||||
{
|
||||
_reorderRunCount++;
|
||||
Log[0] = _reorderRunLine = $"{_reorderRunCount} items put in order in {m.DestLabel}";
|
||||
return;
|
||||
}
|
||||
_reorderRunPack = m.DestIndex;
|
||||
_reorderRunCount = 1;
|
||||
string name = m.Item.Name.Length > 0 ? m.Item.Name : $"0x{m.Item.Id:X8}";
|
||||
Note($"{name} {m.Done}");
|
||||
_reorderRunLine = Log[0];
|
||||
}
|
||||
|
||||
public void Note(string line)
|
||||
{
|
||||
Log.Insert(0, line);
|
||||
|
|
@ -117,9 +163,10 @@ internal sealed class SortController
|
|||
|
||||
public void Tick(ISortWorld world, long nowMs)
|
||||
{
|
||||
Abilities = world.Abilities;
|
||||
if (_inFlight != null)
|
||||
{
|
||||
MoveObservation o = world.Observe(_inFlight.Move.Item.Id);
|
||||
MoveObservation o = world.Observe(in _inFlight.Move);
|
||||
MoveOutcome outcome = MoveTracker.Observe(_inFlight, in o, nowMs);
|
||||
if (outcome == MoveOutcome.Pending) return;
|
||||
Finish(_inFlight.Move, outcome, nowMs);
|
||||
|
|
@ -128,12 +175,12 @@ internal sealed class SortController
|
|||
}
|
||||
if (nowMs < _nextStepMs) return;
|
||||
|
||||
SortScope? scope = Job ?? (Data.Settings.Auto ? SortScope.Main : null);
|
||||
SortScope? scope = Job ?? (Data.Settings.Auto ? SortScope.All : null);
|
||||
if (scope == null)
|
||||
{
|
||||
Status = "off";
|
||||
LastBot = null;
|
||||
RefreshView(world, SortScope.Main, nowMs);
|
||||
RefreshView(world, SortScope.All, nowMs);
|
||||
_nextStepMs = nowMs + PollMs;
|
||||
return;
|
||||
}
|
||||
|
|
@ -157,9 +204,17 @@ internal sealed class SortController
|
|||
return;
|
||||
}
|
||||
_nextViewMs = nowMs + ViewMs;
|
||||
if (!AfterRead(inv, nowMs))
|
||||
{
|
||||
// Rules not tied to their packs yet: nothing moves by a number that may be wrong.
|
||||
Status = "reading your packs";
|
||||
Planner.Plan(inv, Data.Rules, SortScope.Main, force: false, nowMs, Data.Settings.SettleSec * 1000, Options(world));
|
||||
_nextStepMs = nowMs + PollMs;
|
||||
return;
|
||||
}
|
||||
List<SortMove> moves = scope == SortScope.Unpack
|
||||
? Planner.PlanUnpack(inv, UnpackWhich, nowMs)
|
||||
: Planner.Plan(inv, Data.Rules, scope.Value, force: Job != null, nowMs, Data.Settings.SettleSec * 1000);
|
||||
: Planner.Plan(inv, Data.Rules, scope.Value, force: Job != null, nowMs, Data.Settings.SettleSec * 1000, Options(world));
|
||||
|
||||
if (moves.Count == 0)
|
||||
{
|
||||
|
|
@ -174,12 +229,26 @@ internal sealed class SortController
|
|||
Status = scope == SortScope.Unpack ? "unpacking" : "sorting";
|
||||
SortMove m = moves[0];
|
||||
int seq = world.ErrorSeqNow();
|
||||
int stack = m.Item.Stack; // as read before the send (a merge's answer is a smaller stack)
|
||||
if (!world.SendMove(in m))
|
||||
{
|
||||
Finish(m, MoveOutcome.Refused, nowMs, "the engine refused the move");
|
||||
return;
|
||||
}
|
||||
_inFlight = new MoveInFlight { Move = m, SentMs = nowMs, ErrorSeqAtSend = seq, StackAtSend = m.Item.Stack };
|
||||
_inFlight = new MoveInFlight { Move = m, SentMs = nowMs, ErrorSeqAtSend = seq, StackAtSend = stack };
|
||||
}
|
||||
|
||||
/// <summary>What the planner may do: the engine's abilities and the settings.</summary>
|
||||
internal PlanOptions Options(ISortWorld world)
|
||||
{
|
||||
SortAbilities a = world.Abilities;
|
||||
return new PlanOptions
|
||||
{
|
||||
Order = a.ReadOrder && a.PlaceMoves && Data.Settings.OrderInPacks,
|
||||
KindFirst = Data.Settings.OrderKindFirst,
|
||||
Place = a.ReadOrder && a.PlaceMoves,
|
||||
Merge = a.Merge,
|
||||
};
|
||||
}
|
||||
|
||||
private void NoteJobDone(SortScope job)
|
||||
|
|
@ -189,7 +258,7 @@ internal sealed class SortController
|
|||
{
|
||||
case SortScope.Unpack: Note(v.MainFull ? "Main pack is full: unpacking stopped" : "Side packs emptied"); break;
|
||||
case SortScope.Clean: Note(v.MainFull ? "Main pack is full: some strays left" : "Packs cleaned"); break;
|
||||
case SortScope.All: Note(v.Waiting > 0 ? $"Packs tidied ({v.Waiting} can't move yet)" : "Packs tidied"); break;
|
||||
case SortScope.All: Note(v.Waiting > 0 ? $"Packs sorted ({v.Waiting} can't move yet)" : "Packs sorted"); break;
|
||||
default: Note(v.Waiting > 0 ? $"Main pack sorted ({v.Waiting} can't move yet)" : "Main pack sorted"); break;
|
||||
}
|
||||
}
|
||||
|
|
@ -203,7 +272,16 @@ internal sealed class SortController
|
|||
case MoveOutcome.Done:
|
||||
Moved++;
|
||||
_failuresInARow = 0;
|
||||
Note($"{name} -> {m.DestLabel}");
|
||||
if (m.Kind == MoveKind.Reorder)
|
||||
{
|
||||
Planner.NoteReorder(m.Item.Id, nowMs);
|
||||
NoteReorderRun(m);
|
||||
}
|
||||
else
|
||||
{
|
||||
_reorderRunLine = null;
|
||||
Note($"{name} {m.Done}");
|
||||
}
|
||||
_nextStepMs = nowMs + gap;
|
||||
return;
|
||||
case MoveOutcome.TooBusy:
|
||||
|
|
@ -223,6 +301,32 @@ internal sealed class SortController
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After each read: the one-time pack fix once the side slots have read the same for
|
||||
/// <see cref="FixSettleMs"/> (a pack whose capacity isn't readable yet could pass for a focus),
|
||||
/// then each rule's number kept on its pack. False while imported rules still wait for the fix
|
||||
/// (their numbers may name the wrong pack); rules saved by RynthSort meant what they say and
|
||||
/// sort on meanwhile.
|
||||
/// </summary>
|
||||
private bool AfterRead(SortInventory inv, long nowMs)
|
||||
{
|
||||
if (!Data.PacksFixed)
|
||||
{
|
||||
bool hold = Data.ImportedFrom.Length > 0;
|
||||
if (!PackFix.Ready(inv)) { _fixLayout = null; return !hold; }
|
||||
string layout = PackFix.Layout(inv);
|
||||
if (layout != _fixLayout) { _fixLayout = layout; _fixLayoutSince = nowMs; return !hold; }
|
||||
if (nowMs - _fixLayoutSince < FixSettleMs) return !hold;
|
||||
List<string> lines = PackFix.Apply(Data.Rules, inv, hold, Data.LuaRules, out int changed);
|
||||
Data.PacksFixed = true;
|
||||
Data.LuaRules = null;
|
||||
if (hold) Note($"Imported pack numbers fixed: {changed} of {lines.Count} rules");
|
||||
PacksFixed?.Invoke(lines, changed);
|
||||
}
|
||||
if (PackFix.Sync(Data.Rules, inv)) SettingsChanged?.Invoke();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the packs for the window now and then while nothing moves.</summary>
|
||||
private void RefreshView(ISortWorld world, SortScope scope, long nowMs)
|
||||
{
|
||||
|
|
@ -230,7 +334,8 @@ internal sealed class SortController
|
|||
_nextViewMs = nowMs + ViewMs;
|
||||
SortInventory? inv = world.ReadInventory();
|
||||
if (inv == null) return;
|
||||
AfterRead(inv, nowMs);
|
||||
if (scope == SortScope.Unpack) Planner.PlanUnpack(inv, UnpackWhich, nowMs);
|
||||
else Planner.Plan(inv, Data.Rules, scope, force: false, nowMs, Data.Settings.SettleSec * 1000);
|
||||
else Planner.Plan(inv, Data.Rules, scope, force: false, nowMs, Data.Settings.SettleSec * 1000, Options(world));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -99,7 +99,10 @@ internal sealed class LootWatch
|
|||
{
|
||||
if (containerId != 0)
|
||||
{
|
||||
if (containerId != _id || itemCount != _count)
|
||||
// An unreadable count (-1) is not a change: a count read that flickered between -1 and
|
||||
// the real number made a corpse left open look like it was being looted for ever
|
||||
// ("paused: looting" while standing still, 2026-10-11).
|
||||
if (containerId != _id || (itemCount >= 0 && itemCount != _count))
|
||||
{
|
||||
_id = containerId;
|
||||
_count = itemCount;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
|
|
@ -24,11 +26,140 @@ internal sealed class SortPack
|
|||
/// <summary>How many items it holds (ItemsCapacity; 102 for the main pack and 24 for a side pack when unknown).</summary>
|
||||
public int Capacity;
|
||||
public readonly List<SortItem> Items = new();
|
||||
/// <summary>
|
||||
/// <see cref="Items"/> are in the pack's real slot order (slot 0 first: the engine's
|
||||
/// GetContainerOrder, API v80, agreed with the contents read). False: object-id order, and
|
||||
/// nothing is reordered in this pack.
|
||||
/// </summary>
|
||||
public bool OrderKnown;
|
||||
|
||||
/// <summary>
|
||||
/// Puts <see cref="Items"/> in <paramref name="order"/> (the pack's slot order) when that names
|
||||
/// exactly the items read, each once; else leaves them and <see cref="OrderKnown"/> false (a
|
||||
/// list a move behind the contents, or a pack the server hasn't listed: never guessed).
|
||||
/// </summary>
|
||||
public bool ApplyOrder(IReadOnlyList<uint> order, int count)
|
||||
{
|
||||
OrderKnown = false;
|
||||
if (count != Items.Count) return false;
|
||||
var byId = new Dictionary<uint, SortItem>(Items.Count);
|
||||
foreach (SortItem it in Items)
|
||||
if (!byId.TryAdd(it.Id, it)) return false;
|
||||
var sorted = new List<SortItem>(count);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (!byId.Remove(order[i], out SortItem? it)) return false; // unknown here, or listed twice
|
||||
sorted.Add(it);
|
||||
}
|
||||
Items.Clear();
|
||||
Items.AddRange(sorted);
|
||||
OrderKnown = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What is in it, in a few words: the 2-3 commonest kinds of item ("Salvage, Gems"), by
|
||||
/// class, or by name for the classes that say little (Misc, Unknown); "empty" when empty.
|
||||
/// </summary>
|
||||
public string Summary(int most = 3)
|
||||
{
|
||||
if (Items.Count == 0) return "empty";
|
||||
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
var order = new List<string>();
|
||||
foreach (SortItem it in Items)
|
||||
{
|
||||
string key = KindOf(it);
|
||||
if (key.Length == 0) continue;
|
||||
if (counts.TryGetValue(key, out int n)) counts[key] = n + 1;
|
||||
else { counts[key] = 1; order.Add(key); }
|
||||
}
|
||||
if (order.Count == 0) return "unknown items";
|
||||
// Commonest first; a tie keeps the order the kinds were met in.
|
||||
var ranked = new List<string>(order);
|
||||
ranked.Sort((a, b) => counts[a] != counts[b] ? counts[b].CompareTo(counts[a]) : order.IndexOf(a).CompareTo(order.IndexOf(b)));
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 0; i < ranked.Count && i < most; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(", ");
|
||||
sb.Append(ranked[i]);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The kind an item counts as in <see cref="Summary"/>.</summary>
|
||||
internal static string KindOf(SortItem it)
|
||||
{
|
||||
int c = it.ObjectClass;
|
||||
if (c == ObjectClasses.Misc || c == ObjectClasses.Unknown || c == ObjectClasses.Bundle)
|
||||
return Shorten(it.Name);
|
||||
return ObjectClasses.Plural(c);
|
||||
}
|
||||
|
||||
private static string Shorten(string? name)
|
||||
{
|
||||
string n = (name ?? string.Empty).Trim();
|
||||
return n.Length <= 24 ? n : n[..23] + "~";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The character's packs: the main pack and the side packs in order, top to bottom (pack 1 first).</summary>
|
||||
/// <summary>A side-slot thing in the main pack (a side pack or a focus), in the client's list order.</summary>
|
||||
internal readonly struct SortSlot
|
||||
{
|
||||
public readonly uint Id;
|
||||
/// <summary>ItemsCapacity: above 0 for a side pack, 0 for a focus, -1 when it couldn't be read.</summary>
|
||||
public readonly int Capacity;
|
||||
|
||||
public SortSlot(uint id, int capacity)
|
||||
{
|
||||
Id = id;
|
||||
Capacity = capacity;
|
||||
}
|
||||
|
||||
public bool IsPack => Capacity > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The character's packs: the main pack and the side packs, pack 1 first. With the engine's slot
|
||||
/// order (API v80) that is the pack column on screen, top first (<see cref="PackOrderKnown"/>);
|
||||
/// else GetContainerContents' order, by object id. Rules keep the pack's id either way, so a
|
||||
/// pack keeps its rules whatever its number.
|
||||
/// </summary>
|
||||
internal sealed class SortInventory
|
||||
{
|
||||
public SortPack Main = new();
|
||||
public readonly List<SortPack> Packs = new();
|
||||
/// <summary>
|
||||
/// Every container entry in the main pack, foci included, in object-id order (what the Lua
|
||||
/// script numbered its packs by: game.Character.Containers). Never reordered: the one-time
|
||||
/// fix of imported Lua pack numbers (<see cref="PackFix"/>) reads the Lua numbers through it.
|
||||
/// </summary>
|
||||
public readonly List<SortSlot> Slots = new();
|
||||
/// <summary><see cref="Packs"/> are in the pack column's order, top first.</summary>
|
||||
public bool PackOrderKnown;
|
||||
|
||||
/// <summary>
|
||||
/// Puts <see cref="Packs"/> in the pack column's order: <paramref name="order"/> is the main
|
||||
/// pack's side-slot list (packs and foci, top first). Only when it names every pack read; else
|
||||
/// the packs keep their order and <see cref="PackOrderKnown"/> is false.
|
||||
/// </summary>
|
||||
public bool ApplyPackOrder(IReadOnlyList<uint> order, int count)
|
||||
{
|
||||
PackOrderKnown = false;
|
||||
var rank = new Dictionary<uint, int>(count);
|
||||
for (int i = 0; i < count; i++) rank.TryAdd(order[i], i);
|
||||
foreach (SortPack p in Packs)
|
||||
if (!rank.ContainsKey(p.Id)) return false;
|
||||
Packs.Sort((a, b) => rank[a.Id].CompareTo(rank[b.Id]));
|
||||
PackOrderKnown = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The 1-based number of side pack <paramref name="id"/>, or 0 when it isn't carried.</summary>
|
||||
public int IndexOf(uint id)
|
||||
{
|
||||
if (id == 0) return 0;
|
||||
for (int i = 0; i < Packs.Count; i++)
|
||||
if (Packs[i].Id == id) return i + 1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,9 +6,13 @@ namespace RynthCore.Plugin.RynthSort.Sorting;
|
|||
/// <summary>What a planning pass looks at.</summary>
|
||||
internal enum SortScope
|
||||
{
|
||||
/// <summary>Only the main pack; an item moves once it has sat there for the settle time (unless forced).</summary>
|
||||
/// <summary>Only the main pack's items to their packs; an item moves once it has sat there for the settle time (unless forced).</summary>
|
||||
Main,
|
||||
/// <summary>Every pack, no settling: items in the wrong side pack move to theirs too ("Tidy").</summary>
|
||||
/// <summary>
|
||||
/// Every pack: main-pack items to their packs (after the settle time unless forced), items in the
|
||||
/// wrong side pack to theirs, then (with <see cref="PlanOptions"/>) stacks joined and items put
|
||||
/// in order inside each pack. Auto-sort ("keep every pack tidy"), and Sort now (forced).
|
||||
/// </summary>
|
||||
All,
|
||||
/// <summary>As <see cref="All"/>, and side-pack items no rule wants go back to the main pack ("Clean").</summary>
|
||||
Clean,
|
||||
|
|
@ -16,6 +20,17 @@ internal enum SortScope
|
|||
Unpack,
|
||||
}
|
||||
|
||||
/// <summary>What a move does.</summary>
|
||||
internal enum MoveKind : byte
|
||||
{
|
||||
/// <summary>To another pack (maybe joining a stack there, maybe at a slot).</summary>
|
||||
Route,
|
||||
/// <summary>Joins another stack of the same kind in its own pack (<see cref="SortMove.MergeInto"/>).</summary>
|
||||
Stack,
|
||||
/// <summary>To another slot in its own pack (<see cref="SortMove.Placement"/>).</summary>
|
||||
Reorder,
|
||||
}
|
||||
|
||||
/// <summary>One move: <see cref="Item"/> into <see cref="Dest"/> (pack <see cref="DestIndex"/>, 0 = main pack).</summary>
|
||||
internal readonly struct SortMove
|
||||
{
|
||||
|
|
@ -24,24 +39,78 @@ internal readonly struct SortMove
|
|||
public readonly int DestIndex;
|
||||
/// <summary>A stack in <see cref="Dest"/> the item joins (a merge), or 0 for a plain move.</summary>
|
||||
public readonly uint MergeInto;
|
||||
/// <summary>The slot in <see cref="Dest"/> it should end at (counted without it), or -1: the first empty slot.</summary>
|
||||
public readonly int Placement;
|
||||
public readonly MoveKind Kind;
|
||||
|
||||
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto)
|
||||
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto, int placement = -1, MoveKind kind = MoveKind.Route)
|
||||
{
|
||||
Item = item;
|
||||
Dest = dest;
|
||||
DestIndex = destIndex;
|
||||
MergeInto = mergeInto;
|
||||
Placement = placement;
|
||||
Kind = kind;
|
||||
}
|
||||
|
||||
/// <summary>The item is already in <see cref="Dest"/> (a stack joined or a slot changed there).</summary>
|
||||
public bool InPlace => Kind != MoveKind.Route;
|
||||
|
||||
public string DestLabel => DestIndex == 0 ? "main pack" : "pack " + DestIndex;
|
||||
|
||||
/// <summary>What the log says it did: "-> pack 2", "stacked in pack 2", "put in order in pack 2".</summary>
|
||||
public string Done => Kind switch
|
||||
{
|
||||
MoveKind.Stack => "stacked in " + DestLabel,
|
||||
MoveKind.Reorder => "put in order in " + DestLabel,
|
||||
_ => "-> " + DestLabel,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>What a planning pass may do beyond moving items to their packs (what the engine and the settings allow).</summary>
|
||||
internal struct PlanOptions
|
||||
{
|
||||
/// <summary>Put items in order inside each pack whose slot order is known (API v80 and the "order" setting).</summary>
|
||||
public bool Order;
|
||||
/// <summary>The order groups by kind (class) first, then name.</summary>
|
||||
public bool KindFirst;
|
||||
/// <summary>Moves can name a slot (API v80): an item going to a pack whose order is known lands in its place.</summary>
|
||||
public bool Place;
|
||||
/// <summary>Stacks of the same kind in one pack are joined (the engine can merge stacks).</summary>
|
||||
public bool Merge;
|
||||
|
||||
/// <summary>Everything on: an engine with API v80 and the default settings.</summary>
|
||||
public static PlanOptions Full => new() { Order = true, Place = true, Merge = true };
|
||||
}
|
||||
|
||||
/// <summary>A side pack as the window lists it.</summary>
|
||||
internal sealed class PackLine
|
||||
{
|
||||
public uint Id;
|
||||
public string Name = string.Empty;
|
||||
public int Used;
|
||||
public int Capacity;
|
||||
/// <summary>What is in it, in a few words (<see cref="SortPack.Summary"/>).</summary>
|
||||
public string Summary = string.Empty;
|
||||
/// <summary>Its slot order is known (it can be put in order).</summary>
|
||||
public bool OrderKnown;
|
||||
/// <summary>Items out of place in it (0 = in order; only counted when the order is known and ordering is on).</summary>
|
||||
public int OutOfPlace;
|
||||
|
||||
/// <summary>"Sack (12/24) - Salvage, Gems".</summary>
|
||||
public string Label => $"{Name} ({Used}/{Capacity}) - {Summary}";
|
||||
/// <summary>"Sack - Salvage, Gems": what a rule remembers of its pack.</summary>
|
||||
public string Note => $"{Name} - {Summary}";
|
||||
}
|
||||
|
||||
/// <summary>A rule whose pack isn't carried: it goes nowhere (<see cref="UsedPack"/> 0) or to the pack its number names.</summary>
|
||||
internal sealed class RulePackIssue
|
||||
{
|
||||
public SortRule Rule = null!;
|
||||
/// <summary>1-based place in the rule list.</summary>
|
||||
public int RuleNumber;
|
||||
/// <summary>The side pack used instead (its number), or 0 when the rule has none.</summary>
|
||||
public int UsedPack;
|
||||
}
|
||||
|
||||
/// <summary>What the window shows about the packs after a planning pass.</summary>
|
||||
|
|
@ -50,30 +119,54 @@ internal sealed class SortView
|
|||
public readonly List<PackLine> Packs = new();
|
||||
public int MainUsed;
|
||||
public int MainCapacity;
|
||||
/// <summary>The main pack as a line (its order state; Id is the player).</summary>
|
||||
public PackLine Main = new();
|
||||
/// <summary>The packs are numbered top to bottom as the pack column shows them (else by object id).</summary>
|
||||
public bool PackOrderKnown;
|
||||
/// <summary>The pass could put items in order (the engine reads slot orders and ordering is on).</summary>
|
||||
public bool Ordering;
|
||||
/// <summary>Items a rule wants moved that can't go yet (settling, pack full, pack missing, main full).</summary>
|
||||
public int Waiting;
|
||||
/// <summary>Side packs (1-based) a rule wants to fill that are full.</summary>
|
||||
public readonly SortedSet<int> Full = new();
|
||||
/// <summary>Pack numbers rules use that the character doesn't have.</summary>
|
||||
/// <summary>Pack numbers rules (that are on) use and the character doesn't have.</summary>
|
||||
public readonly SortedSet<int> Missing = new();
|
||||
/// <summary>Rules (that are on) whose pack isn't carried, in rule order.</summary>
|
||||
public readonly List<RulePackIssue> Issues = new();
|
||||
/// <summary>Clean or Unpack found the main pack full.</summary>
|
||||
public bool MainFull;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sorting rules applied to the packs: which items move where, one planning pass at a time.
|
||||
/// A port of the Lua script's plan/planUnpack: rules are tried in order and the first match wins;
|
||||
/// worn and wielded items, packs and foci never move; a full pack is only used when the item
|
||||
/// joins a stack there; an item that failed to move is left alone until its block runs out.
|
||||
/// Each item has one place: the pack of the rule it follows (<see cref="SortRules.RuleFor"/>; the
|
||||
/// pack its id names, else its number: <see cref="SortRules.Resolve"/>), or where it is when no
|
||||
/// rule wants it (Clean: back to the main pack). Worn and wielded items, packs and foci never
|
||||
/// move; a full pack is only used when the item joins a stack there; an item that failed to move
|
||||
/// is left alone until its block runs out.
|
||||
///
|
||||
/// With <see cref="PlanOptions"/>, once nothing needs to change packs, every pack is tidied in
|
||||
/// place: two stacks of one kind are joined, then items are put in order (<see cref="PackOrder"/>).
|
||||
/// The main pack only once every item in it has settled.
|
||||
///
|
||||
/// It converges: a route takes an item to its one place and nothing sends it back (its place
|
||||
/// depends on the rules and the packs carried, not on where it is); a join leaves one stack fewer
|
||||
/// that isn't full; a reorder grows the run of items already in order. Each kind of move is
|
||||
/// finite, so a fixed inventory runs out of moves. As a backstop, an item put in order
|
||||
/// <see cref="MaxReorders"/> times within <see cref="ReorderWindowMs"/> isn't reordered again
|
||||
/// until that window passes (an order the engine and the server see differently can't loop).
|
||||
/// Pure (no host calls): the tests drive it with hand-made inventories.
|
||||
/// </summary>
|
||||
internal sealed class SortPlanner
|
||||
{
|
||||
public const int SideCapacityFallback = 24;
|
||||
public const int MainCapacityFallback = 102;
|
||||
public const int MaxReorders = 6;
|
||||
public const long ReorderWindowMs = 10 * 60_000;
|
||||
|
||||
private readonly Dictionary<uint, long> _firstSeen = new();
|
||||
private readonly Dictionary<uint, long> _blocked = new();
|
||||
private readonly Dictionary<uint, (int Count, long Since)> _reorders = new();
|
||||
|
||||
public SortView View { get; private set; } = new();
|
||||
|
||||
|
|
@ -82,6 +175,7 @@ internal sealed class SortPlanner
|
|||
{
|
||||
_firstSeen.Clear();
|
||||
_blocked.Clear();
|
||||
_reorders.Clear();
|
||||
View = new SortView();
|
||||
}
|
||||
|
||||
|
|
@ -97,6 +191,17 @@ internal sealed class SortPlanner
|
|||
return n;
|
||||
}
|
||||
|
||||
/// <summary>An item was put in order (a reorder move landed).</summary>
|
||||
public void NoteReorder(uint itemId, long nowMs)
|
||||
{
|
||||
if (_reorders.TryGetValue(itemId, out var r) && nowMs - r.Since < ReorderWindowMs) _reorders[itemId] = (r.Count + 1, r.Since);
|
||||
else _reorders[itemId] = (1, nowMs);
|
||||
}
|
||||
|
||||
/// <summary>The item has been put in order <see cref="MaxReorders"/> times lately: not again for now.</summary>
|
||||
public bool ReorderLimited(uint itemId, long nowMs) =>
|
||||
_reorders.TryGetValue(itemId, out var r) && nowMs - r.Since < ReorderWindowMs && r.Count >= MaxReorders;
|
||||
|
||||
/// <summary>Worn and wielded items, packs and foci never move.</summary>
|
||||
public static bool Sortable(SortItem it) =>
|
||||
!it.Wielded && it.ObjectClass != ObjectClasses.Container && it.ObjectClass != ObjectClasses.Foci;
|
||||
|
|
@ -119,24 +224,69 @@ internal sealed class SortPlanner
|
|||
return 0;
|
||||
}
|
||||
|
||||
private static bool SameKind(SortItem a, SortItem b) =>
|
||||
internal static bool SameKind(SortItem a, SortItem b) =>
|
||||
a.Wcid != 0 && b.Wcid != 0 ? a.Wcid == b.Wcid : string.Equals(a.Name, b.Name, StringComparison.Ordinal) && a.Name.Length > 0;
|
||||
|
||||
private static bool HasRoom(SortItem it) => it.MaxStack > 1 && it.Stack < it.MaxStack;
|
||||
|
||||
/// <summary>
|
||||
/// Two stacks of one kind in <paramref name="pack"/> that both have room: the smaller one
|
||||
/// (<paramref name="from"/>) joins the larger (<paramref name="into"/>). The first such kind in
|
||||
/// the pack's order; the same answer for the same pack. False when every kind has at most one
|
||||
/// stack with room.
|
||||
/// </summary>
|
||||
public static bool StackJoin(SortPack pack, Func<SortItem, bool> movable, out SortItem from, out SortItem into)
|
||||
{
|
||||
from = into = null!;
|
||||
List<SortItem> items = pack.Items;
|
||||
var seen = new bool[items.Count];
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
if (seen[i] || !HasRoom(items[i]) || !Sortable(items[i])) continue;
|
||||
SortItem? small = null, big = null;
|
||||
for (int j = i; j < items.Count; j++)
|
||||
{
|
||||
SortItem it = items[j];
|
||||
if (j > i && (seen[j] || !HasRoom(it) || !Sortable(it) || !SameKind(items[i], it))) continue;
|
||||
seen[j] = true;
|
||||
if (big == null || it.Stack > big.Stack || (it.Stack == big.Stack && it.Id < big.Id)) big = it;
|
||||
}
|
||||
foreach (SortItem it in items)
|
||||
{
|
||||
if (ReferenceEquals(it, big) || !HasRoom(it) || !Sortable(it) || !SameKind(items[i], it) || !movable(it)) continue;
|
||||
if (small == null || it.Stack < small.Stack || (it.Stack == small.Stack && it.Id > small.Id)) small = it;
|
||||
}
|
||||
if (small != null && big != null) { from = small; into = big; return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The moves to make now (routes only, as before ordering existed). See the overload.</summary>
|
||||
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs) =>
|
||||
Plan(inv, rules, scope, force, nowMs, settleMs, default);
|
||||
|
||||
/// <summary>
|
||||
/// The moves to make now for <paramref name="scope"/> (not <see cref="SortScope.Unpack"/>: see
|
||||
/// <see cref="PlanUnpack"/>), first one first. Also refreshes <see cref="View"/> and the main
|
||||
/// pack's settle clock (an item's time starts when a pass first sees it in the main pack).
|
||||
/// <see cref="PlanUnpack"/>), first one first: items to their packs, then (All and Clean, with
|
||||
/// <paramref name="opt"/>, when no item needs another pack) stacks joined, then items put in
|
||||
/// order, a pack at a time. Also refreshes <see cref="View"/> and the main pack's settle clock
|
||||
/// (an item's time starts when a pass first sees it in the main pack).
|
||||
/// </summary>
|
||||
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs)
|
||||
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs, PlanOptions opt)
|
||||
{
|
||||
bool everyPack = scope != SortScope.Main;
|
||||
bool evict = scope == SortScope.Clean;
|
||||
bool inPack = scope is SortScope.All or SortScope.Clean;
|
||||
var moves = new List<SortMove>();
|
||||
var view = new SortView();
|
||||
var used = new int[inv.Packs.Count + 1];
|
||||
for (int i = 0; i < inv.Packs.Count; i++) used[i + 1] = inv.Packs[i].Items.Count;
|
||||
int mainUsed = inv.Main.Items.Count;
|
||||
int mainCap = CapacityOf(inv.Main, MainCapacityFallback);
|
||||
bool kindFirst = opt.KindFirst;
|
||||
|
||||
int PlaceIn(SortPack dest, SortItem wo, uint joins) =>
|
||||
opt.Place && joins == 0 && dest.OrderKnown ? PackOrder.InsertAt(dest.Items, wo, kindFirst) : -1;
|
||||
|
||||
void Consider(SortItem wo, int from, bool settled)
|
||||
{
|
||||
|
|
@ -148,7 +298,7 @@ internal sealed class SortPlanner
|
|||
uint joins = StackTarget(wo, inv.Main);
|
||||
if (mainUsed < mainCap || joins != 0)
|
||||
{
|
||||
moves.Add(new SortMove(wo, inv.Main, 0, joins));
|
||||
moves.Add(new SortMove(wo, inv.Main, 0, joins, PlaceIn(inv.Main, wo, joins)));
|
||||
if (joins == 0) mainUsed++;
|
||||
}
|
||||
else
|
||||
|
|
@ -158,18 +308,19 @@ internal sealed class SortPlanner
|
|||
}
|
||||
return;
|
||||
}
|
||||
if (r == null || r.Pack == from) return;
|
||||
if (r.Pack < 1 || r.Pack > inv.Packs.Count)
|
||||
if (r == null) return;
|
||||
int to = SortRules.Resolve(r, inv, out _);
|
||||
if (to == 0)
|
||||
{
|
||||
view.Missing.Add(r.Pack);
|
||||
view.Waiting++;
|
||||
view.Waiting++; // reported once per rule below (Issues / Missing)
|
||||
return;
|
||||
}
|
||||
SortPack dest = inv.Packs[r.Pack - 1];
|
||||
if (to == from) return;
|
||||
SortPack dest = inv.Packs[to - 1];
|
||||
uint into = StackTarget(wo, dest);
|
||||
if (used[r.Pack] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
|
||||
if (used[to] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
|
||||
{
|
||||
view.Full.Add(r.Pack);
|
||||
view.Full.Add(to);
|
||||
view.Waiting++;
|
||||
return;
|
||||
}
|
||||
|
|
@ -178,16 +329,19 @@ internal sealed class SortPlanner
|
|||
view.Waiting++;
|
||||
return;
|
||||
}
|
||||
moves.Add(new SortMove(wo, dest, r.Pack, into));
|
||||
if (into == 0) used[r.Pack]++;
|
||||
moves.Add(new SortMove(wo, dest, to, into, PlaceIn(dest, wo, into)));
|
||||
if (into == 0) used[to]++;
|
||||
}
|
||||
|
||||
var inMain = new HashSet<uint>();
|
||||
bool mainSettled = true;
|
||||
foreach (SortItem wo in inv.Main.Items)
|
||||
{
|
||||
inMain.Add(wo.Id);
|
||||
if (!_firstSeen.TryGetValue(wo.Id, out long seen)) _firstSeen[wo.Id] = seen = nowMs;
|
||||
Consider(wo, 0, force || everyPack || nowMs - seen >= settleMs);
|
||||
bool settled = force || nowMs - seen >= settleMs;
|
||||
if (!settled) mainSettled = false;
|
||||
Consider(wo, 0, settled);
|
||||
}
|
||||
if (_firstSeen.Count > inMain.Count)
|
||||
{
|
||||
|
|
@ -201,7 +355,35 @@ internal sealed class SortPlanner
|
|||
foreach (SortItem wo in inv.Packs[i].Items) Consider(wo, i + 1, true);
|
||||
}
|
||||
|
||||
FillPacks(view, inv);
|
||||
bool ordering = inPack && opt.Order;
|
||||
if (inPack && moves.Count == 0)
|
||||
{
|
||||
// Nothing changes packs: tidy each pack in place. Side packs first, then the main pack
|
||||
// once nothing in it is new (loot still settling there would be ordered twice).
|
||||
bool Movable(SortItem it) => Sortable(it) && !IsBlocked(it.Id, nowMs);
|
||||
var stacks = new List<SortMove>();
|
||||
var reorders = new List<SortMove>();
|
||||
for (int i = 0; i <= inv.Packs.Count; i++)
|
||||
{
|
||||
bool main = i == inv.Packs.Count;
|
||||
if (main && !mainSettled) break;
|
||||
SortPack pack = main ? inv.Main : inv.Packs[i];
|
||||
int index = main ? 0 : i + 1;
|
||||
if (opt.Merge && StackJoin(pack, Movable, out SortItem from, out SortItem into))
|
||||
{
|
||||
stacks.Add(new SortMove(from, pack, index, into.Id, -1, MoveKind.Stack));
|
||||
continue;
|
||||
}
|
||||
if (ordering && pack.OrderKnown && PackOrder.AllNamed(pack.Items)
|
||||
&& PackOrder.NextMove(pack.Items, kindFirst, it => Movable(it) && !ReorderLimited(it.Id, nowMs), out SortItem item, out int at))
|
||||
reorders.Add(new SortMove(item, pack, index, 0, at, MoveKind.Reorder));
|
||||
}
|
||||
moves.AddRange(stacks);
|
||||
moves.AddRange(reorders);
|
||||
}
|
||||
|
||||
FillPacks(view, inv, ordering, kindFirst);
|
||||
FillIssues(view, inv, rules);
|
||||
View = view;
|
||||
return moves;
|
||||
}
|
||||
|
|
@ -232,21 +414,44 @@ internal sealed class SortPlanner
|
|||
}
|
||||
}
|
||||
var view = new SortView { Waiting = waiting, MainFull = waiting > 0 };
|
||||
FillPacks(view, inv);
|
||||
FillPacks(view, inv, false, false);
|
||||
View = view;
|
||||
return moves;
|
||||
}
|
||||
|
||||
private static void FillPacks(SortView view, SortInventory inv)
|
||||
private static PackLine LineOf(SortPack p, int capacityFallback, bool ordering, bool kindFirst) => new()
|
||||
{
|
||||
Id = p.Id,
|
||||
Name = p.Name.Length > 0 ? p.Name : "Pack",
|
||||
Used = p.Items.Count,
|
||||
Capacity = CapacityOf(p, capacityFallback),
|
||||
Summary = p.Summary(),
|
||||
OrderKnown = p.OrderKnown,
|
||||
OutOfPlace = ordering && p.OrderKnown ? PackOrder.OutOfPlace(p.Items, kindFirst) : 0,
|
||||
};
|
||||
|
||||
private static void FillPacks(SortView view, SortInventory inv, bool ordering, bool kindFirst)
|
||||
{
|
||||
view.MainUsed = inv.Main.Items.Count;
|
||||
view.MainCapacity = CapacityOf(inv.Main, MainCapacityFallback);
|
||||
foreach (SortPack p in inv.Packs)
|
||||
view.Packs.Add(new PackLine
|
||||
{
|
||||
Name = p.Name.Length > 0 ? p.Name : "Pack",
|
||||
Used = p.Items.Count,
|
||||
Capacity = CapacityOf(p, SideCapacityFallback),
|
||||
});
|
||||
view.Main = LineOf(inv.Main, MainCapacityFallback, ordering, kindFirst);
|
||||
view.Main.Name = "Main pack";
|
||||
view.PackOrderKnown = inv.PackOrderKnown;
|
||||
view.Ordering = ordering;
|
||||
foreach (SortPack p in inv.Packs) view.Packs.Add(LineOf(p, SideCapacityFallback, ordering, kindFirst));
|
||||
}
|
||||
|
||||
/// <summary>Every rule that is on and whose pack isn't carried (whether or not an item wants it now).</summary>
|
||||
private static void FillIssues(SortView view, SortInventory inv, IReadOnlyList<SortRule> rules)
|
||||
{
|
||||
for (int i = 0; i < rules.Count; i++)
|
||||
{
|
||||
SortRule r = rules[i];
|
||||
if (!r.On) continue;
|
||||
int to = SortRules.Resolve(r, inv, out bool fellBack);
|
||||
if (to != 0 && !fellBack) continue;
|
||||
if (to == 0) view.Missing.Add(r.Pack);
|
||||
view.Issues.Add(new RulePackIssue { Rule = r, RuleNumber = i + 1, UsedPack = to });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,35 +1,132 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>Which test a rule makes.</summary>
|
||||
internal enum RuleKind
|
||||
{
|
||||
/// <summary>The item's ObjectClass equals <see cref="SortRule.Class"/>.</summary>
|
||||
Class = 0,
|
||||
/// <summary>The item's name contains <see cref="SortRule.Text"/> (any case).</summary>
|
||||
Name = 1,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One rule: items it matches go to side pack <see cref="Pack"/> (1 = the first side pack, top to
|
||||
/// bottom). The same fields as the Lua script's rules: { on, kind = "class" | "name", class, text, pack }.
|
||||
/// One rule: items whose class is one of <see cref="Classes"/>, or whose name contains one of
|
||||
/// <see cref="Names"/> (any case), go to the side pack <see cref="PackId"/> names while it is
|
||||
/// carried, else to side pack number <see cref="Pack"/> (1 = the top side pack when the pack
|
||||
/// order is known). "Armor, Clothing, name has Shield -> pack 4" is one rule.
|
||||
/// A rule saved before rules held several entries (the Lua script's { kind, class | text }, and
|
||||
/// RynthSort's file versions 1 and 2) loads as a rule with one entry.
|
||||
/// </summary>
|
||||
internal sealed class SortRule
|
||||
{
|
||||
public const int MaxClasses = 32, MaxNames = 16, MaxNameLength = 64;
|
||||
|
||||
private static int _nextUid;
|
||||
|
||||
/// <summary>Stable for the session (never saved): the window's widget ids, so a rule keeps its row while the list resorts.</summary>
|
||||
public readonly int Uid = Interlocked.Increment(ref _nextUid);
|
||||
|
||||
public bool On = true;
|
||||
public RuleKind Kind = RuleKind.Class;
|
||||
/// <summary>An ObjectClass number (<see cref="ObjectClasses"/>).</summary>
|
||||
public int Class = ObjectClasses.SpellComponent;
|
||||
public string Text = string.Empty;
|
||||
/// <summary>ObjectClass numbers (<see cref="ObjectClasses"/>), each once.</summary>
|
||||
public readonly List<int> Classes = new();
|
||||
/// <summary>Parts of item names (any case), each once.</summary>
|
||||
public readonly List<string> Names = new();
|
||||
/// <summary>The pack's number: the fallback when <see cref="PackId"/> isn't carried (or is 0), and what the window shows.</summary>
|
||||
public int Pack = 1;
|
||||
/// <summary>The side pack's object id (0 = none yet: the number decides). Pack order and foci can't shift it.</summary>
|
||||
public uint PackId;
|
||||
/// <summary>What the pack was when it was picked ("Sack - Salvage, Gems"), for the warning when it's gone.</summary>
|
||||
public string PackNote = string.Empty;
|
||||
|
||||
public SortRule Clone() => new() { On = On, Kind = Kind, Class = Class, Text = Text, Pack = Pack };
|
||||
/// <summary>No class and no name: it matches nothing (a rule just added, before anything is put in it).</summary>
|
||||
public bool IsEmpty => Classes.Count == 0 && Names.Count == 0;
|
||||
|
||||
public static SortRule ForClass(int cls, int pack) => new() { Kind = RuleKind.Class, Class = cls, Pack = pack };
|
||||
public static SortRule ForName(string text, int pack) => new() { Kind = RuleKind.Name, Text = text, Pack = pack };
|
||||
public bool HasClass(int cls) => Classes.Contains(cls);
|
||||
|
||||
public bool HasName(string text) => IndexOfName(text) >= 0;
|
||||
|
||||
private int IndexOfName(string text)
|
||||
{
|
||||
for (int i = 0; i < Names.Count; i++)
|
||||
if (string.Equals(Names[i], text, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>Adds a class (false when it's there already or the rule is full).</summary>
|
||||
public bool AddClass(int cls)
|
||||
{
|
||||
if (cls < 0 || Classes.Contains(cls) || Classes.Count >= MaxClasses) return false;
|
||||
Classes.Add(cls);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool RemoveClass(int cls) => Classes.Remove(cls);
|
||||
|
||||
/// <summary>Adds a name part, trimmed and cut to <see cref="MaxNameLength"/> (false when blank, there already, or the rule is full).</summary>
|
||||
public bool AddName(string? text)
|
||||
{
|
||||
string t = Clean(text);
|
||||
if (t.Length == 0 || IndexOfName(t) >= 0 || Names.Count >= MaxNames) return false;
|
||||
Names.Add(t);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool RemoveName(string text)
|
||||
{
|
||||
int i = IndexOfName(text);
|
||||
if (i < 0) return false;
|
||||
Names.RemoveAt(i);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static string Clean(string? text)
|
||||
{
|
||||
string t = (text ?? string.Empty).Trim();
|
||||
return t.Length > MaxNameLength ? t[..MaxNameLength].TrimEnd() : t;
|
||||
}
|
||||
|
||||
/// <summary>Everything of <paramref name="other"/>'s classes and names this rule doesn't have yet.</summary>
|
||||
public void TakeEntriesOf(SortRule other)
|
||||
{
|
||||
foreach (int c in other.Classes) AddClass(c);
|
||||
foreach (string n in other.Names) AddName(n);
|
||||
}
|
||||
|
||||
public SortRule Clone()
|
||||
{
|
||||
var r = new SortRule { On = On, Pack = Pack, PackId = PackId, PackNote = PackNote };
|
||||
r.Classes.AddRange(Classes);
|
||||
r.Names.AddRange(Names);
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>The same classes and names (in any order, names any case) and the same pack number: what an untouched imported rule looks like.</summary>
|
||||
public bool SameAs(SortRule o)
|
||||
{
|
||||
if (Pack != o.Pack || Classes.Count != o.Classes.Count || Names.Count != o.Names.Count) return false;
|
||||
foreach (int c in Classes) if (!o.Classes.Contains(c)) return false;
|
||||
foreach (string n in Names) if (!o.HasName(n)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static SortRule ForClass(int cls, int pack)
|
||||
{
|
||||
var r = new SortRule { Pack = pack };
|
||||
r.AddClass(cls);
|
||||
return r;
|
||||
}
|
||||
|
||||
public static SortRule ForName(string text, int pack)
|
||||
{
|
||||
var r = new SortRule { Pack = pack };
|
||||
r.AddName(text);
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>A rule with several classes (and names): "Gem, Mana Stone, Key -> pack 3".</summary>
|
||||
public static SortRule For(int pack, int[] classes, params string[] names)
|
||||
{
|
||||
var r = new SortRule { Pack = pack };
|
||||
foreach (int c in classes) r.AddClass(c);
|
||||
foreach (string n in names) r.AddName(n);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -90,39 +187,130 @@ internal static class ObjectClasses
|
|||
|
||||
public static string Label(int cls) =>
|
||||
cls >= 0 && cls < Names.Length ? Spaced(Names[cls]) : "class " + cls;
|
||||
|
||||
/// <summary>A class as a pack's contents read: "Components", "Gems", "Salvage".</summary>
|
||||
public static string Plural(int cls) => cls switch
|
||||
{
|
||||
SpellComponent => "Components",
|
||||
Salvage => "Salvage",
|
||||
Gem => "Gems",
|
||||
ManaStone => "Mana Stones",
|
||||
Key => "Keys",
|
||||
HealingKit => "Healing Kits",
|
||||
Lockpick => "Lockpicks",
|
||||
Food => "Food",
|
||||
Scroll => "Scrolls",
|
||||
TradeNote => "Trade Notes",
|
||||
Money => "Money",
|
||||
Plant => "Plants",
|
||||
Jewelry => "Jewelry",
|
||||
Armor => "Armor",
|
||||
Clothing => "Clothing",
|
||||
MeleeWeapon => "Melee Weapons",
|
||||
MissileWeapon => "Missile Weapons",
|
||||
WandStaffOrb => "Casters",
|
||||
Book => "Books",
|
||||
Journal => "Journals",
|
||||
Ust => "Ust",
|
||||
_ => Label(cls),
|
||||
};
|
||||
}
|
||||
|
||||
internal static class SortRules
|
||||
{
|
||||
/// <summary>The Lua script's defaults: components, salvage, then gems, stones and keys together.</summary>
|
||||
/// <summary>The Lua script's defaults: components, salvage, then gems, stones and keys together (one rule).</summary>
|
||||
public static List<SortRule> Defaults() => new()
|
||||
{
|
||||
SortRule.ForClass(ObjectClasses.SpellComponent, 1),
|
||||
SortRule.ForClass(ObjectClasses.Salvage, 2),
|
||||
SortRule.ForClass(ObjectClasses.Gem, 3),
|
||||
SortRule.ForClass(ObjectClasses.ManaStone, 3),
|
||||
SortRule.ForClass(ObjectClasses.Key, 3),
|
||||
SortRule.For(3, new[] { ObjectClasses.Gem, ObjectClasses.ManaStone, ObjectClasses.Key }),
|
||||
};
|
||||
|
||||
public static bool Matches(SortRule r, SortItem item)
|
||||
/// <summary>The item's name contains one of the rule's names (any case).</summary>
|
||||
public static bool MatchesName(SortRule r, SortItem item)
|
||||
{
|
||||
if (!r.On) return false;
|
||||
if (r.Kind == RuleKind.Name)
|
||||
{
|
||||
string t = r.Text ?? string.Empty;
|
||||
return t.Length > 0 && (item.Name ?? string.Empty).Contains(t, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
return item.ObjectClass == r.Class;
|
||||
string name = item.Name ?? string.Empty;
|
||||
if (name.Length == 0) return false;
|
||||
foreach (string t in r.Names)
|
||||
if (t.Length > 0 && name.Contains(t, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The first rule that matches (rules are tried in order), or null.</summary>
|
||||
public static bool MatchesClass(SortRule r, SortItem item) => r.Classes.Contains(item.ObjectClass);
|
||||
|
||||
public static bool Matches(SortRule r, SortItem item) => r.On && (MatchesName(r, item) || MatchesClass(r, item));
|
||||
|
||||
/// <summary>
|
||||
/// The rule an item follows, or null. A name match beats a class match (it is the more
|
||||
/// specific: "Armor -> 4" and "name has Shield -> 5" send shields to 5, whatever the order);
|
||||
/// between two rules that match the same way, the one saved first wins (the window warns
|
||||
/// when two rules name the same class or name).
|
||||
/// </summary>
|
||||
public static SortRule? RuleFor(IReadOnlyList<SortRule> rules, SortItem item)
|
||||
{
|
||||
for (int i = 0; i < rules.Count; i++)
|
||||
if (Matches(rules[i], item)) return rules[i];
|
||||
if (rules[i].On && MatchesName(rules[i], item)) return rules[i];
|
||||
for (int i = 0; i < rules.Count; i++)
|
||||
if (rules[i].On && MatchesClass(rules[i], item)) return rules[i];
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string Describe(SortRule r) =>
|
||||
r.Kind == RuleKind.Name ? $"name has \"{r.Text}\"" : ObjectClasses.Label(r.Class);
|
||||
/// <summary>"Gem, Key, Mana Stone, name has "Opal"": the classes (A-Z), then the names (A-Z).</summary>
|
||||
public static string Describe(SortRule r)
|
||||
{
|
||||
if (r.IsEmpty) return "(empty: add a class or a name)";
|
||||
var parts = new List<string>(r.Classes.Count + r.Names.Count);
|
||||
foreach (string l in ClassLabels(r)) parts.Add(l);
|
||||
foreach (string n in SortedNames(r)) parts.Add($"name has \"{n}\"");
|
||||
return string.Join(", ", parts);
|
||||
}
|
||||
|
||||
/// <summary>The rule's classes as labels, A-Z.</summary>
|
||||
public static List<string> ClassLabels(SortRule r)
|
||||
{
|
||||
var labels = r.Classes.ConvertAll(ObjectClasses.Label);
|
||||
labels.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
return labels;
|
||||
}
|
||||
|
||||
/// <summary>The rule's classes ordered by label, A-Z.</summary>
|
||||
public static List<int> SortedClasses(SortRule r)
|
||||
{
|
||||
var list = new List<int>(r.Classes);
|
||||
list.Sort((a, b) => string.Compare(ObjectClasses.Label(a), ObjectClasses.Label(b), StringComparison.OrdinalIgnoreCase));
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<string> SortedNames(SortRule r)
|
||||
{
|
||||
var list = new List<string>(r.Names);
|
||||
list.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>The order rules are listed in under their pack: by <see cref="Describe"/>, A-Z (empty rules last).</summary>
|
||||
public static int CompareForList(SortRule a, SortRule b)
|
||||
{
|
||||
if (a.IsEmpty != b.IsEmpty) return a.IsEmpty ? 1 : -1;
|
||||
int c = string.Compare(Describe(a), Describe(b), StringComparison.OrdinalIgnoreCase);
|
||||
return c != 0 ? c : a.Uid.CompareTo(b.Uid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The side pack the rule sends items to: 1-based index into <paramref name="inv"/>'s packs, or 0
|
||||
/// when it has none. The pack <see cref="SortRule.PackId"/> names when that is carried; else
|
||||
/// pack number <see cref="SortRule.Pack"/> when there is one (<paramref name="fellBack"/>: its id was set but isn't carried).
|
||||
/// </summary>
|
||||
public static int Resolve(SortRule r, SortInventory inv, out bool fellBack)
|
||||
{
|
||||
fellBack = false;
|
||||
int byId = inv.IndexOf(r.PackId);
|
||||
if (byId > 0) return byId;
|
||||
if (r.Pack >= 1 && r.Pack <= inv.Packs.Count)
|
||||
{
|
||||
fellBack = r.PackId != 0;
|
||||
return r.Pack;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,6 +30,8 @@ internal static class UiFormat
|
|||
public const byte OpSameLine = 0x11;
|
||||
public const byte OpSpacing = 0x13;
|
||||
public const byte OpDummy = 0x14;
|
||||
public const byte OpIndent = 0x15;
|
||||
public const byte OpUnindent = 0x16;
|
||||
public const byte OpButton = 0x20;
|
||||
public const byte OpCheckbox = 0x21;
|
||||
public const byte OpSliderInt = 0x22;
|
||||
|
|
@ -49,6 +51,9 @@ internal static class UiFormat
|
|||
// Window flags
|
||||
public const uint FlagVisible = 1u << 0;
|
||||
public const uint FlagShowInBar = 1u << 1;
|
||||
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
|
||||
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
|
||||
public const uint FlagBarButton = 1u << 11;
|
||||
public const uint FlagNoScrollbar = 1u << 5;
|
||||
|
||||
// Image icon kinds (op level 2)
|
||||
|
|
@ -75,6 +80,8 @@ internal static class UiFormat
|
|||
|
||||
// InputText flags
|
||||
public const uint InputAutoSelectAll = 4096;
|
||||
/// <summary>The text box reports Enter (its event carries submitted = true).</summary>
|
||||
public const uint InputEnterReturnsTrue = 32;
|
||||
|
||||
// CollapsingHeader flags
|
||||
public const uint TreeDefaultOpen = 32;
|
||||
|
|
|
|||
|
|
@ -42,6 +42,9 @@ internal sealed class UiWindow
|
|||
public string Title;
|
||||
public bool Visible;
|
||||
public bool ShowInBar = true;
|
||||
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
|
||||
/// tooltip) rather than a line in the Scripts menu.</summary>
|
||||
public bool BarButton = true;
|
||||
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
|
||||
|
||||
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
|
||||
|
|
@ -80,7 +83,8 @@ internal sealed class UiWindow
|
|||
Title = title;
|
||||
}
|
||||
|
||||
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0);
|
||||
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
|
||||
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
|
||||
|
||||
public bool HeaderDirty =>
|
||||
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight
|
||||
|
|
@ -208,6 +212,23 @@ internal sealed class UiWindow
|
|||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Moves the following items right by <paramref name="w"/> logical units, until <see cref="Unindent"/>.</summary>
|
||||
public void Indent(float w)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpIndent);
|
||||
F32(w);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Unindent(float w)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpUnindent);
|
||||
F32(w);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false)
|
||||
{
|
||||
if (!Room()) return;
|
||||
|
|
@ -265,7 +286,11 @@ internal sealed class UiWindow
|
|||
}
|
||||
|
||||
/// <summary>A text box; <paramref name="set"/> gets every edit (submitted = Enter was pressed).</summary>
|
||||
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0)
|
||||
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0) =>
|
||||
InputText(label, id, value, maxLen, (text, _) => set(text), flags);
|
||||
|
||||
/// <summary>A text box; <paramref name="set"/> gets every edit and whether Enter was pressed.</summary>
|
||||
public void InputText(string label, string id, string value, int maxLen, Action<string, bool> set, uint flags = 0)
|
||||
{
|
||||
if (!Room()) return;
|
||||
maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString);
|
||||
|
|
@ -277,7 +302,7 @@ internal sealed class UiWindow
|
|||
U16((ushort)maxLen);
|
||||
U32(flags);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text); };
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text, e.Submitted); };
|
||||
}
|
||||
|
||||
public void Combo(string label, string id, int index, IReadOnlyList<string> items, Action<int> set)
|
||||
|
|
|
|||
|
|
@ -7,17 +7,23 @@ using RynthCore.Plugin.Shared;
|
|||
namespace RynthCore.Plugin.RynthSort.Views;
|
||||
|
||||
/// <summary>
|
||||
/// The RynthSort window: the auto-sort box and status, the job buttons, warnings, the rule list
|
||||
/// (first match wins: enable, select to edit, add, move up or down, remove) and the settings.
|
||||
/// Recorded on the pump thread, replayed by the engine.
|
||||
/// The RynthSort window: the auto-sort box and status, the job buttons, then one collapsing
|
||||
/// section per side pack ("Pack 1: Sack (12/24) - Components", top pack first) holding that
|
||||
/// pack's warnings and its rules (A-Z), a section for rules whose pack isn't carried, and the
|
||||
/// settings. A rule is one row (on/off box, its classes and names); selecting it opens its
|
||||
/// editor beneath: the classes and names as chips (click one to take it out), a class picker and
|
||||
/// a name box to add, the pack it sends to, and Remove. Recorded on the pump thread, replayed by
|
||||
/// the engine.
|
||||
/// </summary>
|
||||
internal sealed class SortPanel
|
||||
{
|
||||
private static readonly string[] Kinds = { "Class", "Name has" };
|
||||
private const float RowIndent = 6f, EditorIndent = 22f;
|
||||
private const int ChipsPerLine = 3;
|
||||
|
||||
private readonly SortController _c;
|
||||
private readonly Action _save;
|
||||
private int _selected = -1;
|
||||
private SortRule? _selected;
|
||||
private string _nameDraft = string.Empty;
|
||||
|
||||
/// <summary>Extra warnings the plugin knows about (the Lua script set to start too).</summary>
|
||||
public Func<IReadOnlyList<string>> Warnings = () => Array.Empty<string>();
|
||||
|
|
@ -30,7 +36,8 @@ internal sealed class SortPanel
|
|||
_save = save;
|
||||
}
|
||||
|
||||
public int Selected => _selected;
|
||||
/// <summary>The rule whose editor is open, or null.</summary>
|
||||
public SortRule? Selected => _selected;
|
||||
|
||||
public void Draw(UiWindow w)
|
||||
{
|
||||
|
|
@ -41,47 +48,58 @@ internal sealed class SortPanel
|
|||
}
|
||||
SortSettings s = _c.Data.Settings;
|
||||
List<SortRule> rules = _c.Data.Rules;
|
||||
if (_selected != null && !rules.Contains(_selected)) _selected = null;
|
||||
SortView view = _c.Planner.View;
|
||||
|
||||
w.Checkbox("Auto-sort", "auto", s.Auto, v => _c.SetAuto(v));
|
||||
w.Tooltip("New items in the main pack go to their pack after the settle time");
|
||||
w.Tooltip("Keeps every pack tidy: new items go to their pack after the settle time, items in the wrong pack move to theirs, "
|
||||
+ "stacks of one kind are joined and items are put in order (A-Z) inside each pack");
|
||||
w.SameLine();
|
||||
w.TextColored(_c.Paused ? UiColors.Amber : UiColors.Grey, _c.Status);
|
||||
if (_c.Planner.View.Waiting > 0)
|
||||
if (view.Waiting > 0)
|
||||
{
|
||||
w.SameLine();
|
||||
w.TextDisabled($"({_c.Planner.View.Waiting} waiting)");
|
||||
w.TextDisabled($"({view.Waiting} waiting)");
|
||||
}
|
||||
|
||||
w.Button("Sort main pack", "job.main", () => _c.StartJob(SortScope.Main));
|
||||
w.Tooltip("Sort the main pack now, without waiting for items to settle");
|
||||
w.Button("Sort now", "job.all", () => _c.StartJob(SortScope.All));
|
||||
w.Tooltip("Sort every pack now, without waiting for new items to settle");
|
||||
w.SameLine();
|
||||
w.Button("Tidy all packs", "job.all", () => _c.StartJob(SortScope.All));
|
||||
w.Tooltip("Also move items that are in the wrong side pack");
|
||||
w.Button("Clean packs", "job.clean", () => _c.StartJob(SortScope.Clean));
|
||||
w.Tooltip("Sort now, and side-pack items no rule wants go back to the main pack");
|
||||
w.SameLine();
|
||||
w.Button("Empty side packs", "job.unpack", () => _c.StartUnpack(null));
|
||||
w.Tooltip("Move everything from your side packs into the main pack. Turns auto-sort off first, so nothing moves back.");
|
||||
w.Button("Clean packs", "job.clean", () => _c.StartJob(SortScope.Clean));
|
||||
w.Tooltip("Side-pack items no rule wants go to the main pack; items in the wrong side pack go to theirs");
|
||||
|
||||
SortView view = _c.Planner.View;
|
||||
w.TextDisabled($"Main pack ({view.Main.Used}/{view.Main.Capacity}){OrderNote(view, view.Main, " - ")}");
|
||||
w.Tooltip("Items no rule names stay in the main pack");
|
||||
if (view.MainFull) w.TextColored(UiColors.Amber, "The main pack is full");
|
||||
foreach (int p in view.Full) w.TextColored(UiColors.Amber, $"Pack {p} is full");
|
||||
foreach (int p in view.Missing) w.TextColored(UiColors.Amber, $"A rule uses pack {p}, which you don't have");
|
||||
if (s.Auto && _c.LastBot is RynthAiActivity bot && (bot & RynthAiActivity.AutoCram) != 0 && (bot & RynthAiActivity.MacroRunning) != 0)
|
||||
w.TextColored(UiColors.Amber, "RynthAi's AutoCram also moves loot out of the main pack; turn one of them off");
|
||||
foreach (string warning in Warnings()) w.TextColored(UiColors.Amber, warning);
|
||||
|
||||
if (w.CollapsingHeader("Rules (first match wins)", "rules", defaultOpen: true))
|
||||
DrawRules(w, rules, view);
|
||||
Dictionary<int, List<SortRule>> byPack = Group(rules, view);
|
||||
Dictionary<int, List<string>> conflicts = Conflicts(rules, view);
|
||||
for (int i = 1; i <= view.Packs.Count; i++)
|
||||
DrawPack(w, view, rules, i, byPack.TryGetValue(i, out List<SortRule>? list) ? list : new List<SortRule>(),
|
||||
conflicts.TryGetValue(i, out List<string>? c) ? c : null);
|
||||
if (byPack.TryGetValue(0, out List<SortRule>? missing)) DrawMissing(w, view, rules, missing);
|
||||
if (view.Packs.Count == 0) w.TextDisabled("No side packs: items stay in the main pack.");
|
||||
|
||||
if (w.CollapsingHeader("Settings", "settings"))
|
||||
{
|
||||
w.SliderInt("Settle (s)", "settle", s.SettleSec, SortSettings.SettleMin, SortSettings.SettleMax, v => { s.SettleSec = v; _save(); });
|
||||
w.Tooltip("How long a new item sits in the main pack before it is moved");
|
||||
w.SliderInt("Gap (ms)", "gap", s.GapMs, SortSettings.GapMin, SortSettings.GapMax, v => { s.GapMs = v; _save(); });
|
||||
w.Tooltip("Auto-sort's pause between two moves, to leave the bot room. Sort, Tidy, Clean and Unpack don't wait.");
|
||||
w.Tooltip("Auto-sort's pause between two moves, to leave the bot room. Sort now, Clean and Empty don't wait.");
|
||||
w.Checkbox("Sort during fights", "combat", s.SortInCombat, v => { s.SortInCombat = v; _save(); });
|
||||
w.Tooltip("Off: nothing moves while RynthAi fights. On: moves go between its attacks and casts (never while one is unanswered)");
|
||||
w.Checkbox("Put items in order inside packs", "order", s.OrderInPacks, v => { s.OrderInPacks = v; _save(); });
|
||||
w.Tooltip("Like items side by side, A-Z by name, in every pack. Off: items only go to their packs (and stacks are still joined).");
|
||||
w.Checkbox("Group by kind first", "orderkind", s.OrderKindFirst, v => { s.OrderKindFirst = v; _save(); });
|
||||
w.Tooltip("Order by kind (Armor, Gem, Spell Component ...) and then A-Z by name, instead of A-Z by name only");
|
||||
if (!(_c.Abilities.ReadOrder && _c.Abilities.PlaceMoves))
|
||||
w.TextWrapped("This RynthCore can't read the order inside packs (it needs plugin API 80): items go to their packs but aren't put in order.");
|
||||
}
|
||||
|
||||
if (_c.Log.Count > 0)
|
||||
|
|
@ -91,105 +109,319 @@ internal sealed class SortPanel
|
|||
}
|
||||
}
|
||||
|
||||
private void DrawRules(UiWindow w, List<SortRule> rules, SortView view)
|
||||
// ── Pack sections ───────────────────────────────────────────────────────
|
||||
|
||||
private void DrawPack(UiWindow w, SortView view, List<SortRule> rules, int number, List<SortRule> packRules, List<string>? conflicts)
|
||||
{
|
||||
if (_selected >= rules.Count) _selected = rules.Count - 1;
|
||||
for (int i = 0; i < rules.Count; i++)
|
||||
PackLine p = view.Packs[number - 1];
|
||||
bool full = view.Full.Contains(number);
|
||||
List<string> warnings = FallbackWarnings(view, number);
|
||||
if (conflicts != null) warnings.AddRange(conflicts);
|
||||
bool attention = full || warnings.Count > 0;
|
||||
if (attention) w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
|
||||
bool open = w.CollapsingHeader($"Pack {number}: {p.Label}", $"pack.{p.Id:X8}", defaultOpen: true);
|
||||
if (attention) w.PopStyleColor();
|
||||
w.Tooltip(PackTooltip(view));
|
||||
if (!open) return;
|
||||
|
||||
w.Indent(RowIndent);
|
||||
if (full) w.TextColored(UiColors.Amber, "This pack is full: items for it wait where they are");
|
||||
foreach (string line in warnings) w.TextColored(UiColors.Amber, line);
|
||||
packRules.Sort(SortRules.CompareForList);
|
||||
foreach (SortRule r in packRules) DrawRule(w, view, rules, r);
|
||||
if (packRules.Count == 0) w.TextDisabled("No rules send items here.");
|
||||
|
||||
uint id = p.Id;
|
||||
w.SmallButton("+ Add rule", $"add.{id:X8}", () => AddRule(rules, view, number));
|
||||
w.Tooltip("A rule sends items to this pack: items of any of its classes, or with any of its names in their name. A name beats a class.");
|
||||
int on = 0;
|
||||
foreach (SortRule r in packRules) if (r.On && !r.IsEmpty) on++;
|
||||
if (on >= 2)
|
||||
{
|
||||
SortRule r = rules[i];
|
||||
int index = i;
|
||||
w.Checkbox("", "on." + i, r.On, v => { r.On = v; _save(); });
|
||||
w.Tooltip("Rule on or off");
|
||||
w.SameLine();
|
||||
string pack = r.Pack >= 1 && r.Pack <= view.Packs.Count ? $"pack {r.Pack} ({view.Packs[r.Pack - 1].Name})" : $"pack {r.Pack}";
|
||||
w.Selectable($"{i + 1}. {SortRules.Describe(r)} -> {pack}", "row." + i, _selected == i,
|
||||
() => _selected = _selected == index ? -1 : index);
|
||||
w.SmallButton("Merge rules", $"merge.{id:X8}", () => MergeRules(rules, packRules));
|
||||
w.Tooltip("Make this pack's rules (the ones that are on) one rule with all their classes and names");
|
||||
}
|
||||
if (rules.Count == 0) w.TextDisabled("No rules: nothing moves.");
|
||||
string order = OrderNote(view, p, "");
|
||||
if (order.Length > 0) w.TextDisabled(order);
|
||||
w.Unindent(RowIndent);
|
||||
}
|
||||
|
||||
w.Button("Add rule", "rule.add", () =>
|
||||
private void DrawMissing(UiWindow w, SortView view, List<SortRule> rules, List<SortRule> missing)
|
||||
{
|
||||
w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
|
||||
bool open = w.CollapsingHeader($"Rules for packs you don't have ({missing.Count})", "missing", defaultOpen: true);
|
||||
w.PopStyleColor();
|
||||
if (!open) return;
|
||||
w.Indent(RowIndent);
|
||||
w.TextWrapped("Their items stay where they are. Pick one of your packs in a rule's editor, or remove the rule.");
|
||||
var groups = new List<List<SortRule>>();
|
||||
foreach (SortRule r in missing)
|
||||
{
|
||||
if (rules.Count >= SortStore.MaxRules) return;
|
||||
rules.Add(SortRule.ForClass(ObjectClasses.SpellComponent, 1));
|
||||
_selected = rules.Count - 1;
|
||||
_save();
|
||||
});
|
||||
if (_selected < 0 || _selected >= rules.Count) return;
|
||||
List<SortRule>? g = groups.Find(x => SamePackOf(x[0], r));
|
||||
if (g == null) groups.Add(g = new List<SortRule>());
|
||||
g.Add(r);
|
||||
}
|
||||
foreach (List<SortRule> g in groups)
|
||||
{
|
||||
SortRule first = g[0];
|
||||
w.TextColored(UiColors.Amber, first.PackNote.Length > 0 ? $"A pack you don't have (it was {first.PackNote}):" : $"Pack {first.Pack}, which you don't have:");
|
||||
g.Sort(SortRules.CompareForList);
|
||||
foreach (SortRule r in g) DrawRule(w, view, rules, r);
|
||||
}
|
||||
w.Unindent(RowIndent);
|
||||
}
|
||||
|
||||
int sel = _selected;
|
||||
w.SameLine();
|
||||
w.Button("Up", "rule.up", () =>
|
||||
{
|
||||
if (sel <= 0) return;
|
||||
(rules[sel - 1], rules[sel]) = (rules[sel], rules[sel - 1]);
|
||||
_selected = sel - 1;
|
||||
_save();
|
||||
});
|
||||
w.SameLine();
|
||||
w.Button("Down", "rule.down", () =>
|
||||
{
|
||||
if (sel >= rules.Count - 1) return;
|
||||
(rules[sel + 1], rules[sel]) = (rules[sel], rules[sel + 1]);
|
||||
_selected = sel + 1;
|
||||
_save();
|
||||
});
|
||||
w.SameLine();
|
||||
w.Button("Remove", "rule.remove", () =>
|
||||
{
|
||||
rules.RemoveAt(sel);
|
||||
_selected = Math.Min(sel, rules.Count - 1);
|
||||
_save();
|
||||
});
|
||||
private static bool SamePackOf(SortRule a, SortRule b) =>
|
||||
a.PackId != 0 || b.PackId != 0 ? a.PackId == b.PackId : a.Pack == b.Pack;
|
||||
|
||||
SortRule rule = rules[sel];
|
||||
w.SeparatorText($"Rule {sel + 1}");
|
||||
w.Combo("Match", "rule.kind", rule.Kind == RuleKind.Name ? 1 : 0, Kinds, v =>
|
||||
// ── Rules ───────────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawRule(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
|
||||
{
|
||||
string k = "r" + r.Uid;
|
||||
w.Checkbox("", k + ".on", r.On, v => { r.On = v; _save(); });
|
||||
w.Tooltip(r.On ? "Rule on: click to turn it off" : "Rule off: click to turn it on");
|
||||
w.SameLine();
|
||||
bool selected = ReferenceEquals(_selected, r);
|
||||
w.Selectable(Shown(SortRules.Describe(r)), k + ".row", selected, () =>
|
||||
{
|
||||
rule.Kind = v == 1 ? RuleKind.Name : RuleKind.Class;
|
||||
_selected = ReferenceEquals(_selected, r) ? null : r;
|
||||
_nameDraft = string.Empty;
|
||||
});
|
||||
w.Tooltip(selected ? "Click to close the editor" : "Click to change this rule");
|
||||
if (selected) DrawEditor(w, view, rules, r);
|
||||
}
|
||||
|
||||
private void DrawEditor(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
|
||||
{
|
||||
string k = "r" + r.Uid;
|
||||
w.Indent(EditorIndent);
|
||||
|
||||
List<int> classes = SortRules.SortedClasses(r);
|
||||
if (classes.Count > 0)
|
||||
{
|
||||
w.TextDisabled("Classes:");
|
||||
for (int i = 0; i < classes.Count; i++)
|
||||
{
|
||||
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
|
||||
int cls = classes[i];
|
||||
string label = ObjectClasses.Label(cls);
|
||||
w.SmallButton(label + " x", $"{k}.c{cls}", () => { r.RemoveClass(cls); _save(); });
|
||||
w.Tooltip($"Take {label} out of this rule");
|
||||
}
|
||||
}
|
||||
var offered = new List<int>();
|
||||
var labels = new List<string> { "Add a class..." };
|
||||
foreach (int cls in ObjectClasses.Choices)
|
||||
{
|
||||
if (r.HasClass(cls)) continue;
|
||||
offered.Add(cls);
|
||||
labels.Add(ObjectClasses.Label(cls));
|
||||
}
|
||||
if (offered.Count > 0 && r.Classes.Count < SortRule.MaxClasses)
|
||||
w.Combo("Class", k + ".addclass", 0, labels, v =>
|
||||
{
|
||||
if (v >= 1 && v <= offered.Count && r.AddClass(offered[v - 1])) _save();
|
||||
});
|
||||
|
||||
List<string> names = SortRules.SortedNames(r);
|
||||
if (names.Count > 0)
|
||||
{
|
||||
w.TextDisabled("Names:");
|
||||
for (int i = 0; i < names.Count; i++)
|
||||
{
|
||||
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
|
||||
string name = names[i];
|
||||
w.SmallButton($"\"{Shown(name)}\" x", $"{k}.n{i}", () => { r.RemoveName(name); _save(); });
|
||||
w.Tooltip($"Take \"{name}\" out of this rule");
|
||||
}
|
||||
}
|
||||
if (r.Names.Count < SortRule.MaxNames)
|
||||
{
|
||||
w.InputText("Name has", k + ".draft", _nameDraft, SortRule.MaxNameLength, (text, enter) =>
|
||||
{
|
||||
_nameDraft = text;
|
||||
if (enter) AddDraft(r);
|
||||
}, UiFormat.InputEnterReturnsTrue);
|
||||
w.Tooltip("Part of an item's name, any case: \"Opal\" takes every item with Opal in its name. Enter or Add puts it in the rule.");
|
||||
w.SameLine();
|
||||
w.SmallButton("Add", k + ".addname", () => AddDraft(r));
|
||||
}
|
||||
|
||||
int shown = ShownPack(view, r);
|
||||
w.Combo("Pack", k + ".pack", Math.Max((shown > 0 ? shown : r.Pack) - 1, 0), PackChoices(view, r.Pack), v =>
|
||||
{
|
||||
SetPack(r, view, v + 1);
|
||||
_save();
|
||||
});
|
||||
if (rule.Kind == RuleKind.Name)
|
||||
w.Tooltip("Where this rule sends items. " + PackTooltip(view));
|
||||
w.SmallButton("Remove rule", k + ".remove", () =>
|
||||
{
|
||||
w.InputText("Name has", "rule.text", rule.Text, 64, v => { rule.Text = v; _save(); });
|
||||
w.Tooltip("Part of the item's name, any case");
|
||||
rules.Remove(r);
|
||||
if (ReferenceEquals(_selected, r)) _selected = null;
|
||||
_save();
|
||||
});
|
||||
w.Unindent(EditorIndent);
|
||||
}
|
||||
|
||||
private void AddDraft(SortRule r)
|
||||
{
|
||||
if (r.AddName(_nameDraft)) _save();
|
||||
_nameDraft = string.Empty;
|
||||
}
|
||||
|
||||
private void AddRule(List<SortRule> rules, SortView view, int number)
|
||||
{
|
||||
if (rules.Count >= SortStore.MaxRules) return;
|
||||
var added = new SortRule();
|
||||
SetPack(added, view, number);
|
||||
rules.Add(added);
|
||||
_selected = added;
|
||||
_nameDraft = string.Empty;
|
||||
_save();
|
||||
}
|
||||
|
||||
/// <summary>The pack's rules that are on become one (the first A-Z keeps its place in the list, so a tie still goes its way).</summary>
|
||||
private void MergeRules(List<SortRule> rules, List<SortRule> packRules)
|
||||
{
|
||||
SortRule? keep = null;
|
||||
foreach (SortRule r in rules)
|
||||
{
|
||||
if (!packRules.Contains(r) || !r.On || r.IsEmpty) continue;
|
||||
if (keep == null) { keep = r; continue; }
|
||||
keep.TakeEntriesOf(r);
|
||||
}
|
||||
if (keep == null) return;
|
||||
rules.RemoveAll(r => !ReferenceEquals(r, keep) && packRules.Contains(r) && r.On && !r.IsEmpty);
|
||||
_selected = keep;
|
||||
_save();
|
||||
}
|
||||
|
||||
/// <summary>Text as a label shows it: "##" would start ImGui's id part.</summary>
|
||||
private static string Shown(string text) => text.Replace("##", "# #");
|
||||
|
||||
// ── Helpers (pure, for the tests) ───────────────────────────────────────
|
||||
|
||||
/// <summary>The pack tooltip: how packs are numbered and that a rule keeps its pack.</summary>
|
||||
internal static string PackTooltip(SortView view) => view.PackOrderKnown ? PackTooltipTopDown : PackTooltipListOrder;
|
||||
|
||||
internal const string PackTooltipTopDown =
|
||||
"Packs are numbered from the top of the pack column (foci don't count). "
|
||||
+ "A rule remembers the pack you pick, so adding, moving or emptying packs doesn't change where items go.";
|
||||
|
||||
internal const string PackTooltipListOrder =
|
||||
"A rule remembers the pack you pick, so adding, moving or emptying packs doesn't change where items go. "
|
||||
+ "Pack numbers count your side packs (not foci) in the client's list order, oldest pack first, "
|
||||
+ "which can differ from the pack column on screen: go by the name and what's in it.";
|
||||
|
||||
/// <summary>" - in order", " - 3 to put in order", " - order not known": a pack's order as the window says it (empty when ordering is off).</summary>
|
||||
internal static string OrderNote(SortView view, PackLine p, string lead)
|
||||
{
|
||||
if (!view.Ordering) return string.Empty;
|
||||
if (!p.OrderKnown) return lead + "order not known yet: not put in order";
|
||||
if (p.OutOfPlace == 0) return lead + "in order";
|
||||
return lead + (p.OutOfPlace == 1 ? "1 item to put in order" : $"{p.OutOfPlace} items to put in order");
|
||||
}
|
||||
|
||||
/// <summary>Rules by the side pack they send to now (1-based; 0 = a pack that isn't carried).</summary>
|
||||
internal static Dictionary<int, List<SortRule>> Group(IReadOnlyList<SortRule> rules, SortView view)
|
||||
{
|
||||
var map = new Dictionary<int, List<SortRule>>();
|
||||
foreach (SortRule r in rules)
|
||||
{
|
||||
int n = ShownPack(view, r);
|
||||
if (!map.TryGetValue(n, out List<SortRule>? list)) map[n] = list = new List<SortRule>();
|
||||
list.Add(r);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Classes and names that two rules (that are on) send to different packs, by the pack whose
|
||||
/// rule loses: "Armor: also in a rule for pack 2, which wins". A name beats a class, so only
|
||||
/// rules that match the same way compete; between those the rule saved first wins.
|
||||
/// </summary>
|
||||
internal static Dictionary<int, List<string>> Conflicts(IReadOnlyList<SortRule> rules, SortView view)
|
||||
{
|
||||
var map = new Dictionary<int, List<string>>();
|
||||
void Add(int pack, string line)
|
||||
{
|
||||
if (!map.TryGetValue(pack, out List<string>? l)) map[pack] = l = new List<string>();
|
||||
if (!l.Contains(line)) l.Add(line);
|
||||
}
|
||||
string Where(int pack) => pack > 0 ? "pack " + pack : "a pack you don't have";
|
||||
|
||||
var classWinner = new Dictionary<int, int>();
|
||||
var nameWinner = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (SortRule r in rules)
|
||||
{
|
||||
if (!r.On) continue;
|
||||
int pack = ShownPack(view, r);
|
||||
foreach (int cls in r.Classes)
|
||||
{
|
||||
if (!classWinner.TryGetValue(cls, out int won)) classWinner[cls] = pack;
|
||||
else if (won != pack) Add(pack, $"{ObjectClasses.Label(cls)}: also in a rule for {Where(won)}, which wins");
|
||||
}
|
||||
foreach (string n in r.Names)
|
||||
{
|
||||
if (!nameWinner.TryGetValue(n, out int won)) nameWinner[n] = pack;
|
||||
else if (won != pack) Add(pack, $"\"{n}\": also in a rule for {Where(won)}, which wins");
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// For side pack <paramref name="number"/>: rules that use it only because their own pack isn't
|
||||
/// carried (their number names it): "Gem, Key: its pack (Sack - Gems) isn't carried, so this one is used".
|
||||
/// </summary>
|
||||
internal static List<string> FallbackWarnings(SortView view, int number)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
foreach (RulePackIssue issue in view.Issues)
|
||||
{
|
||||
if (issue.UsedPack != number) continue;
|
||||
string note = issue.Rule.PackNote;
|
||||
lines.Add($"{SortRules.Describe(issue.Rule)}: {(note.Length > 0 ? "its pack (" + note + ")" : "its pack")} isn't carried, so this one is used");
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>Points <paramref name="rule"/> at side pack <paramref name="number"/> (1-based): that pack's id when it is carried.</summary>
|
||||
internal static void SetPack(SortRule rule, SortView view, int number)
|
||||
{
|
||||
rule.Pack = Math.Clamp(number, 1, SortStore.MaxPack);
|
||||
if (rule.Pack <= view.Packs.Count)
|
||||
{
|
||||
PackLine p = view.Packs[rule.Pack - 1];
|
||||
rule.PackId = p.Id;
|
||||
rule.PackNote = p.Note;
|
||||
}
|
||||
else
|
||||
{
|
||||
int ci = ObjectClasses.ChoiceIndex(rule.Class);
|
||||
var labels = new List<string>(ObjectClasses.ChoiceLabels);
|
||||
if (ci < 0)
|
||||
{
|
||||
// A class the editor doesn't offer (set by hand or by the Lua script): keep it selectable.
|
||||
labels.Add(ObjectClasses.Label(rule.Class));
|
||||
ci = labels.Count - 1;
|
||||
}
|
||||
int keep = rule.Class;
|
||||
w.Combo("Class", "rule.class", ci, labels, v =>
|
||||
{
|
||||
rule.Class = v < ObjectClasses.Choices.Length ? ObjectClasses.Choices[v] : keep;
|
||||
_save();
|
||||
});
|
||||
rule.PackId = 0;
|
||||
rule.PackNote = string.Empty;
|
||||
}
|
||||
w.Combo("Pack", "rule.pack", Math.Max(rule.Pack - 1, 0), PackChoices(view, rule.Pack), v =>
|
||||
{
|
||||
rule.Pack = Math.Clamp(v + 1, 1, SortStore.MaxPack);
|
||||
_save();
|
||||
});
|
||||
w.Tooltip("Pack numbers are your side packs in order, top to bottom");
|
||||
}
|
||||
|
||||
/// <summary>"Pack 1: Name (used/cap)" for each side pack, then "(none)" up to at least 7.</summary>
|
||||
/// <summary>The side pack the rule uses now (1-based), as the planner resolves it, or 0.</summary>
|
||||
internal static int ShownPack(SortView view, SortRule r)
|
||||
{
|
||||
if (r.PackId != 0)
|
||||
for (int i = 0; i < view.Packs.Count; i++)
|
||||
if (view.Packs[i].Id == r.PackId) return i + 1;
|
||||
return r.Pack >= 1 && r.Pack <= view.Packs.Count ? r.Pack : 0;
|
||||
}
|
||||
|
||||
/// <summary>"Pack 1: Sack (12/24) - Salvage, Gems" for each side pack, then "(none)" up to at least 7.</summary>
|
||||
internal static List<string> PackChoices(SortView view, int atLeast)
|
||||
{
|
||||
int n = Math.Min(Math.Max(Math.Max(view.Packs.Count, 7), atLeast), SortStore.MaxPack);
|
||||
var list = new List<string>(n);
|
||||
for (int i = 1; i <= n; i++)
|
||||
{
|
||||
if (i <= view.Packs.Count)
|
||||
{
|
||||
PackLine p = view.Packs[i - 1];
|
||||
list.Add($"Pack {i}: {p.Name} ({p.Used}/{p.Capacity})");
|
||||
}
|
||||
if (i <= view.Packs.Count) list.Add($"Pack {i}: {view.Packs[i - 1].Label}");
|
||||
else list.Add($"Pack {i} (none)");
|
||||
}
|
||||
return list;
|
||||
|
|
|
|||
Loading…
Reference in a new issue