Snapshot for release 2026.10.11.1 (internal d20160b)
This commit is contained in:
parent
e6fffb0f42
commit
504a6f080a
66 changed files with 7865 additions and 310 deletions
155
Plugins/RynthCore.Plugin.RynthSort/HostSortWorld.cs
Normal file
155
Plugins/RynthCore.Plugin.RynthSort/HostSortWorld.cs
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort;
|
||||
|
||||
/// <summary>
|
||||
/// The controller's view of the game through the engine host. Plugin pump thread only (the
|
||||
/// plugin's tick), which is also where RynthAi's interfaces may be called.
|
||||
/// </summary>
|
||||
internal sealed unsafe class HostSortWorld : ISortWorld
|
||||
{
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly InventoryReader _reader;
|
||||
private readonly LootWatch _loot;
|
||||
private readonly Func<bool> _vendorOpenByEvent;
|
||||
private uint[] _groundBuf = new uint[256];
|
||||
|
||||
public HostSortWorld(RynthCoreHost host, InventoryReader reader, LootWatch loot, Func<bool> vendorOpenByEvent)
|
||||
{
|
||||
_host = host;
|
||||
_reader = reader;
|
||||
_loot = loot;
|
||||
_vendorOpenByEvent = vendorOpenByEvent;
|
||||
}
|
||||
|
||||
public SortInventory? ReadInventory() => _reader.Read(_host);
|
||||
|
||||
public GateInputs ReadGate(bool sortInCombat, long nowMs)
|
||||
{
|
||||
var g = new GateInputs { SortInCombat = sortInCombat };
|
||||
g.InPortalSpace = _host.HasIsPortaling && _host.IsPortaling();
|
||||
|
||||
uint ground = _host.HasGetGroundContainerId ? _host.GetGroundContainerId() : 0;
|
||||
int count = 0;
|
||||
if (ground != 0)
|
||||
{
|
||||
count = _host.HasGetNumContainedItems ? _host.GetNumContainedItems(ground) : -1;
|
||||
if (count < 0) count = _host.GetContainerContents(ground, _groundBuf);
|
||||
}
|
||||
g.Looting = _loot.Update(ground, count, nowMs);
|
||||
|
||||
g.VendorOpen = _host.HasVendorTrade ? _host.TryGetVendorInfo(out _) : _vendorOpenByEvent();
|
||||
g.TradeOpen = _host.HasTrade && _host.TryGetTradeState(out TradeState trade) && trade.IsOpen;
|
||||
g.ClientBusy = _host.HasGetBusyState && _host.GetBusyState() != 0;
|
||||
g.Animating = _host.HasGetCastBusyState && _host.GetCastBusyState() != 0;
|
||||
g.Bot = ReadRynthAi(_host);
|
||||
return g;
|
||||
}
|
||||
|
||||
public bool SendMove(in SortMove move)
|
||||
{
|
||||
uint id = move.Item.Id;
|
||||
if (move.MergeInto != 0 && _host.HasMergeStackInternal)
|
||||
return _host.MergeStackInternal(id, move.MergeInto);
|
||||
return _host.HasMoveItemInternal && _host.MoveItemInternal(id, move.Dest.Id, 0, Math.Max(1, move.Item.Stack));
|
||||
}
|
||||
|
||||
public MoveObservation Observe(uint itemId)
|
||||
{
|
||||
var o = new MoveObservation();
|
||||
if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(itemId, out uint container, out uint wielder, out _))
|
||||
{
|
||||
o.Exists = true;
|
||||
o.Container = container;
|
||||
o.Wielder = wielder;
|
||||
}
|
||||
else
|
||||
{
|
||||
// No ownership info: the object is gone (merged into a stack) when it has no name either.
|
||||
o.Exists = _host.TryGetObjectName(itemId, out string n) && n.Length > 0;
|
||||
o.Container = 0xFFFFFFFF;
|
||||
}
|
||||
o.Stack = _host.TryGetObjectIntProperty(itemId, 12, out int s) && s > 0 ? s : 1;
|
||||
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out uint error, out uint type, out uint obj))
|
||||
{
|
||||
o.ErrorSeq = seq;
|
||||
o.Error = error;
|
||||
o.ErrorEventType = type;
|
||||
o.ErrorObject = obj;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
public int ErrorSeqNow() =>
|
||||
_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
|
||||
|
||||
// ── RynthAi ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// RynthAi's activity bits: its "RynthAi.Activity" interface; on an older RynthAi without it,
|
||||
/// the bot state from "RynthAi.Status" (macro and action); null when RynthAi isn't loaded or not
|
||||
/// ready. Resolved again every call: a RynthAi reload frees the tables.
|
||||
/// </summary>
|
||||
internal static RynthAiActivity? ReadRynthAi(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasGetPluginInterface) return null;
|
||||
try
|
||||
{
|
||||
var act = (RynthAiActivityApiV1*)host.GetPluginInterface("RynthAi", RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion);
|
||||
if (act != null && act->Version >= 1 && act->StructSize >= (uint)sizeof(RynthAiActivityApiV1) && act->GetActivityFlags != null)
|
||||
{
|
||||
uint flags = 0;
|
||||
return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null;
|
||||
}
|
||||
var status = (RynthAiStatusApiV1*)host.GetPluginInterface("RynthAi", RynthAiStatusApiV1.InterfaceName, RynthAiStatusApiV1.InterfaceVersion);
|
||||
if (status != null && status->Version >= 1 && status->StructSize >= (uint)sizeof(RynthAiStatusApiV1) && status->GetStatusJson != null)
|
||||
{
|
||||
byte* r = null;
|
||||
if (status->GetStatusJson(&r) != 0 && r != null)
|
||||
return FromStatusJson(Marshal.PtrToStringUTF8((IntPtr)r));
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A RynthAi mid-reload: treat as not there this tick.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The bits an older RynthAi's status JSON ({macro, action, ...}) gives (no server-wait bit).</summary>
|
||||
internal static RynthAiActivity? FromStatusJson(string? json)
|
||||
{
|
||||
if (string.IsNullOrEmpty(json) || json[0] != '{') return null;
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
RynthAiActivity f = RynthAiActivity.None;
|
||||
if (root.TryGetProperty("macro", out JsonElement m) && m.ValueKind == JsonValueKind.True) f |= RynthAiActivity.MacroRunning;
|
||||
string action = root.TryGetProperty("action", out JsonElement a) && a.ValueKind == JsonValueKind.String ? a.GetString() ?? "" : "";
|
||||
if ((f & RynthAiActivity.MacroRunning) != 0)
|
||||
{
|
||||
// The display label: Buffing shows as Healing / Restoring mana / Restoring stamina too.
|
||||
f |= action switch
|
||||
{
|
||||
"" or "Default" => RynthAiActivity.None,
|
||||
"Combat" => RynthAiActivity.Combat,
|
||||
"Looting" => RynthAiActivity.Looting,
|
||||
"Salvaging" => RynthAiActivity.Salvaging,
|
||||
"Navigating" or "Following" => RynthAiActivity.Navigating,
|
||||
_ => RynthAiActivity.Buffing,
|
||||
};
|
||||
}
|
||||
return f;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
56
Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs
Normal file
56
Plugins/RynthCore.Plugin.RynthSort/PluginExports.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort;
|
||||
|
||||
/// <summary>
|
||||
/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take
|
||||
/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs.
|
||||
/// RynthSort draws through the engine's script windows (host calls from its own tick), so it
|
||||
/// exports no render callback and keeps no buffer the engine reads later.
|
||||
/// </summary>
|
||||
public static unsafe class PluginExports
|
||||
{
|
||||
private static readonly RynthPluginRuntime<RynthSortPlugin> Runtime = new();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Shutdown() => Runtime.Shutdown();
|
||||
|
||||
// UTF-8 literals live in the module's read-only data: nothing to allocate or free.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetName() => LiteralPointer("RynthSort"u8);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
|
||||
|
||||
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
|
||||
{
|
||||
fixed (byte* p = literal)
|
||||
return (IntPtr)p;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Tick() => Runtime.OnTick();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnLoginComplete() => Runtime.OnLoginComplete();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnLogout() => Runtime.OnLogout();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
|
||||
|
||||
// A vendor window (for engines without vendor info, API v67, these are the only signal).
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorOpen", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnVendorOpen(uint vendorId) => Runtime.OnVendorOpen(vendorId);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorClose", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnVendorClose(uint vendorId) => Runtime.OnVendorClose(vendorId);
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
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
|
||||
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.
|
||||
-->
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<OutputType>Library</OutputType>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<PublishAot>true</PublishAot>
|
||||
<NativeLib>Shared</NativeLib>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
|
||||
<StripSymbols>false</StripSymbols>
|
||||
<RootNamespace>RynthCore.Plugin.RynthSort</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthSort</AssemblyName>
|
||||
<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). -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Keeps your packs sorted: new loot goes to the pack its rule names.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- What RynthAi is doing (read only), so pack moves stay out of its way. -->
|
||||
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
|
||||
<!-- An older RynthAi without RynthAi.Activity: its RynthAi.Status bot state instead. -->
|
||||
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
318
Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs
Normal file
318
Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
using RynthCore.Plugin.RynthSort.Ui;
|
||||
using RynthCore.Plugin.RynthSort.Views;
|
||||
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.
|
||||
///
|
||||
/// 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,
|
||||
/// or while RynthAi is looting, salvaging, buffing, making ammo, waiting on the server or (unless
|
||||
/// "Sort during fights" is on) fighting. One move at a time, each waited on, then a gap.
|
||||
///
|
||||
/// Everything runs on the plugin pump (OnTick and the events the engine drains into it) except
|
||||
/// OnChatBarEnter, which the engine may call on AC's thread: it only queues the command.
|
||||
/// </summary>
|
||||
public sealed class RynthSortPlugin : RynthPluginBase
|
||||
{
|
||||
public const string Version = "0.1.0";
|
||||
private const long IdentityRetryMs = 1000;
|
||||
private const long SaveDelayMs = 750;
|
||||
private const long PassIntervalMs = 500;
|
||||
|
||||
private readonly SortStore _store = new();
|
||||
private readonly InventoryReader _reader = new();
|
||||
private readonly LootWatch _loot = new();
|
||||
private readonly SortController _sort = new();
|
||||
private readonly UiHost _ui = new();
|
||||
private readonly ConcurrentQueue<string> _commands = new();
|
||||
private HostSortWorld? _world;
|
||||
private UiWindow? _window;
|
||||
private SortPanel? _panel;
|
||||
|
||||
private bool _inWorld;
|
||||
private bool _identityKnown;
|
||||
private long _nextIdentityTryMs;
|
||||
private string _server = string.Empty;
|
||||
private string _character = string.Empty;
|
||||
private long _saveDueMs;
|
||||
private bool _vendorOpen;
|
||||
private bool _noUiLogged;
|
||||
private readonly List<string> _warnings = new();
|
||||
|
||||
public override int Initialize()
|
||||
{
|
||||
_ui.Log = msg => Host.Log(msg);
|
||||
_world = new HostSortWorld(Host, _reader, _loot, () => _vendorOpen);
|
||||
_sort.SettingsChanged = RequestSave;
|
||||
_panel = new SortPanel(_sort, RequestSave)
|
||||
{
|
||||
Warnings = () => _warnings,
|
||||
Character = () => _identityKnown ? _character : string.Empty,
|
||||
};
|
||||
_window = _ui.Add(new UiWindow("RynthSort/Main", "RynthSort")
|
||||
{
|
||||
DefaultWidth = 360f, DefaultHeight = 420f, MinWidth = 300f, MinHeight = 200f,
|
||||
});
|
||||
Host.Log($"[RynthSort] {Version} initialized. /rsort shows or hides the window; /rsort on|off|now|tidy|clean|unpack. Files: {_store.Root}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The engine calls this on a real login and on a freshly (re)loaded plugin already in game.
|
||||
public override void OnLoginComplete()
|
||||
{
|
||||
_inWorld = true;
|
||||
_identityKnown = false;
|
||||
_nextIdentityTryMs = Environment.TickCount64;
|
||||
_sort.Reset();
|
||||
_reader.Reset();
|
||||
_loot.Reset();
|
||||
_warnings.Clear();
|
||||
}
|
||||
|
||||
public override void OnLogout()
|
||||
{
|
||||
SaveNow();
|
||||
_inWorld = false;
|
||||
_identityKnown = false;
|
||||
_sort.Reset();
|
||||
_reader.Reset();
|
||||
_loot.Reset();
|
||||
_vendorOpen = false;
|
||||
if (_window != null) { _window.Visible = false; _window.NeedsPass = true; }
|
||||
_ui.SubmitEmpty(Host);
|
||||
}
|
||||
|
||||
public override void Shutdown()
|
||||
{
|
||||
SaveNow();
|
||||
_ui.SubmitEmpty(Host);
|
||||
}
|
||||
|
||||
public override void OnVendorOpen(uint vendorId) => _vendorOpen = true;
|
||||
public override void OnVendorClose(uint vendorId) => _vendorOpen = false;
|
||||
|
||||
// ── Chat ────────────────────────────────────────────────────────────────
|
||||
|
||||
// May run on AC's thread: classify and queue only.
|
||||
public override void OnChatBarEnter(string? text, ref int eat)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return;
|
||||
string t = text.Trim();
|
||||
if (!t.StartsWith("/rsort", StringComparison.OrdinalIgnoreCase) || (t.Length > 6 && !char.IsWhiteSpace(t[6])))
|
||||
return;
|
||||
eat = 1;
|
||||
_commands.Enqueue(t.Length > 6 ? t.Substring(6).Trim() : string.Empty);
|
||||
}
|
||||
|
||||
private void RunCommand(string arg)
|
||||
{
|
||||
string[] words = arg.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
string word = words.Length > 0 ? words[0].ToLowerInvariant() : string.Empty;
|
||||
if (word.Length > 0 && !_identityKnown && word is not ("help" or "?"))
|
||||
{
|
||||
Print("Log in first.");
|
||||
return;
|
||||
}
|
||||
switch (word)
|
||||
{
|
||||
case "":
|
||||
if (_window != null) { _window.Visible = !_window.Visible; _window.NeedsPass = true; }
|
||||
if (_window != null && _window.Visible && !Host.HasUi && !_noUiLogged)
|
||||
{
|
||||
_noUiLogged = true;
|
||||
Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Sorting still runs: /rsort on|off|now|tidy|clean|unpack.");
|
||||
}
|
||||
break;
|
||||
case "on":
|
||||
case "off":
|
||||
_sort.SetAuto(word == "on");
|
||||
Print("Auto-sort " + word);
|
||||
break;
|
||||
case "now":
|
||||
_sort.StartJob(SortScope.Main);
|
||||
break;
|
||||
case "tidy":
|
||||
_sort.StartJob(SortScope.All);
|
||||
break;
|
||||
case "clean":
|
||||
_sort.StartJob(SortScope.Clean);
|
||||
break;
|
||||
case "unpack":
|
||||
{
|
||||
int? n = words.Length > 1 && int.TryParse(words[1], out int p) && p > 0 ? p : null;
|
||||
_sort.StartUnpack(n);
|
||||
Print((n != null ? $"Emptying pack {n}" : "Emptying your side packs") + " into the main pack; auto-sort is off (/rsort on when done).");
|
||||
break;
|
||||
}
|
||||
case "status":
|
||||
PrintStatus();
|
||||
break;
|
||||
default:
|
||||
Print("/rsort [on | off | now | tidy | clean | unpack [pack] | status]");
|
||||
break;
|
||||
}
|
||||
if (_window != null) _window.NeedsPass = true;
|
||||
}
|
||||
|
||||
private void PrintStatus()
|
||||
{
|
||||
SortView v = _sort.Planner.View;
|
||||
Print($"{_character}: auto-sort {(_sort.Data.Settings.Auto ? "on" : "off")}, {_sort.Status}; {_sort.Data.Rules.Count} rules, "
|
||||
+ $"{v.Packs.Count} side packs, main pack {v.MainUsed}/{v.MainCapacity}; moved {_sort.Moved}, failed {_sort.Failed} this session.");
|
||||
}
|
||||
|
||||
private void Print(string text)
|
||||
{
|
||||
if (!Host.WriteToChat("[RynthSort] " + text, 1))
|
||||
Host.Log("[RynthSort] " + text);
|
||||
}
|
||||
|
||||
// ── Tick ────────────────────────────────────────────────────────────────
|
||||
|
||||
public override void OnTick()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd);
|
||||
_ui.Poll(Host);
|
||||
|
||||
if (_inWorld)
|
||||
{
|
||||
if (!_identityKnown && now >= _nextIdentityTryMs) TryStartCharacter(now);
|
||||
if (_identityKnown && _world != null)
|
||||
{
|
||||
try { _sort.Tick(_world, now); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[RynthSort] sorting step failed: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
|
||||
|
||||
if (!Host.HasUi || _window == null || _panel == null) return;
|
||||
Record(_window, now);
|
||||
_ui.Submit(Host, now);
|
||||
|
||||
if (_identityKnown && _window.Visible != _sort.Data.Settings.WindowOpen)
|
||||
{
|
||||
_sort.Data.Settings.WindowOpen = _window.Visible;
|
||||
RequestSave();
|
||||
}
|
||||
}
|
||||
|
||||
private void TryStartCharacter(long now)
|
||||
{
|
||||
_nextIdentityTryMs = now + IdentityRetryMs;
|
||||
uint player = Host.GetPlayerId();
|
||||
if (player == 0 || !Host.TryGetObjectName(player, out string name) || string.IsNullOrWhiteSpace(name)) return;
|
||||
string server = Host.TryGetWorldName(out string w) ? w : string.Empty;
|
||||
|
||||
_server = server;
|
||||
_character = name;
|
||||
CharacterSortData data = _store.Load(server, name, out string? problem);
|
||||
if (problem != null) Host.Log($"[RynthSort] couldn't read the saved rules ({problem}); using defaults.");
|
||||
_sort.Data = data;
|
||||
_identityKnown = true;
|
||||
|
||||
string own = _store.PathFor(server, name);
|
||||
if (data.ImportedFrom.Length > 0 && !File.Exists(own))
|
||||
{
|
||||
string? error = _store.Save(server, name, data);
|
||||
Print(error == null
|
||||
? $"Took over the RynthSort script's rules for {name} ({data.Rules.Count} rules, auto-sort {(data.Settings.Auto ? "on" : "off")})."
|
||||
: $"Took over the RynthSort script's rules for {name}, but couldn't save them: {error}");
|
||||
Host.Log($"[RynthSort] imported {data.ImportedFrom} -> {own}");
|
||||
}
|
||||
CheckLuaScriptAutostart(server, name);
|
||||
if (_window != null) { _window.Visible = data.Settings.WindowOpen; _window.NeedsPass = true; }
|
||||
Host.Log($"[RynthSort] sorting for {name} on {server}: {data.Rules.Count} rules, auto-sort {(data.Settings.Auto ? "on" : "off")}; file {own}");
|
||||
}
|
||||
|
||||
/// <summary>The RynthSort Lua script set to start too would sort beside the plugin: say so.</summary>
|
||||
private void CheckLuaScriptAutostart(string server, string character)
|
||||
{
|
||||
_warnings.Clear();
|
||||
try
|
||||
{
|
||||
string path = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthLua", "settings.json");
|
||||
if (!File.Exists(path)) return;
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
if (!LuaScriptStarts(doc.RootElement, server + "|" + character)) return;
|
||||
const string line = "The RynthSort Lua script is set to start too; stop it in RynthLua so only one sorts";
|
||||
_warnings.Add(line);
|
||||
Print(line + ".");
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Only a warning.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when RynthLua's settings start the "RynthSort" script for everyone or for this character.</summary>
|
||||
internal static bool LuaScriptStarts(JsonElement root, string characterKey)
|
||||
{
|
||||
if (root.ValueKind != JsonValueKind.Object) return false;
|
||||
static bool Has(JsonElement list)
|
||||
{
|
||||
if (list.ValueKind != JsonValueKind.Array) return false;
|
||||
foreach (JsonElement e in list.EnumerateArray())
|
||||
if (e.ValueKind == JsonValueKind.String && string.Equals(e.GetString(), "RynthSort", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
if (root.TryGetProperty("GlobalScripts", out JsonElement g) && Has(g)) return true;
|
||||
if (root.TryGetProperty("CharacterScripts", out JsonElement c) && c.ValueKind == JsonValueKind.Object)
|
||||
foreach (JsonProperty p in c.EnumerateObject())
|
||||
if (string.Equals(p.Name, characterKey, StringComparison.OrdinalIgnoreCase) && Has(p.Value)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void RequestSave()
|
||||
{
|
||||
if (_window != null) _window.NeedsPass = true;
|
||||
if (_saveDueMs == 0) _saveDueMs = Environment.TickCount64 + SaveDelayMs;
|
||||
}
|
||||
|
||||
private void SaveNow()
|
||||
{
|
||||
_saveDueMs = 0;
|
||||
if (!_identityKnown) return;
|
||||
_sort.Data.Settings.Clamp();
|
||||
string? error = _store.Save(_server, _character, _sort.Data);
|
||||
if (error != null) Host.Log("[RynthSort] save failed: " + error);
|
||||
}
|
||||
|
||||
/// <summary>A pass when one is wanted, or on the refresh interval while visible (the status ticks on).</summary>
|
||||
private void Record(UiWindow w, long now)
|
||||
{
|
||||
bool due = w.NeedsPass || (w.Visible && now >= w.NextPassMs);
|
||||
if (!due) return;
|
||||
w.NeedsPass = false;
|
||||
w.NextPassMs = now + PassIntervalMs;
|
||||
w.Begin();
|
||||
try
|
||||
{
|
||||
_panel!.Draw(w);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
w.TextWrapped($"Something went wrong drawing this window: {ex.GetType().Name}: {ex.Message}");
|
||||
Host.Log($"[RynthSort] {w.Key} pass failed: {ex}");
|
||||
}
|
||||
w.End();
|
||||
}
|
||||
}
|
||||
260
Plugins/RynthCore.Plugin.RynthSort/SortStore.cs
Normal file
260
Plugins/RynthCore.Plugin.RynthSort/SortStore.cs
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort;
|
||||
|
||||
/// <summary>RynthSort's settings for one character (the Lua script's DEFAULTS, plus what the plugin adds).</summary>
|
||||
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>
|
||||
public bool Auto = true;
|
||||
/// <summary>How long a new item sits in the main pack before it moves (seconds).</summary>
|
||||
public int SettleSec = 5;
|
||||
/// <summary>Auto-sort's pause between two moves (ms), to leave the bot room.</summary>
|
||||
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;
|
||||
|
||||
public void Clamp()
|
||||
{
|
||||
SettleSec = Math.Clamp(SettleSec, SettleMin, SettleMax);
|
||||
GapMs = Math.Clamp(GapMs, GapMin, GapMax);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One character's rules and settings.</summary>
|
||||
internal sealed class CharacterSortData
|
||||
{
|
||||
public List<SortRule> Rules = SortRules.Defaults();
|
||||
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>
|
||||
/// Per-character files: <SuiteDir>\RynthSort\characters\<server_character>.json, written by
|
||||
/// hand and read with JsonDocument (plugin types never go through System.Text.Json's serializer,
|
||||
/// which roots them across hot reloads). The same shape as the Lua script's saved data
|
||||
/// ({"rules":[...],"settings":{...}}), so its file (<SuiteDir>\RynthLua\Data\RynthSort\characters\...)
|
||||
/// is read the same way when a character has no RynthSort file yet.
|
||||
/// </summary>
|
||||
internal sealed class SortStore
|
||||
{
|
||||
public const int MaxRules = 64;
|
||||
public const int MaxPack = 32;
|
||||
|
||||
/// <summary>RynthSort's folder (tests point it at a temp folder).</summary>
|
||||
public string Root;
|
||||
/// <summary>The Lua script's data folder for RynthSort (tests point it at a temp folder).</summary>
|
||||
public string LuaDataRoot;
|
||||
|
||||
public SortStore()
|
||||
{
|
||||
string suite = RynthCore.Install.RynthInstallPaths.SuiteDir;
|
||||
Root = Path.Combine(suite, "RynthSort");
|
||||
LuaDataRoot = Path.Combine(suite, "RynthLua", "Data", "RynthSort");
|
||||
}
|
||||
|
||||
public SortStore(string root, string luaDataRoot)
|
||||
{
|
||||
Root = root;
|
||||
LuaDataRoot = luaDataRoot;
|
||||
}
|
||||
|
||||
/// <summary>"server_character" made safe as a file name, as the Lua script's storage names it.</summary>
|
||||
public static string FileStem(string server, string character) => SafeFileName($"{server}_{character}");
|
||||
|
||||
public string PathFor(string server, string character) => Path.Combine(Root, "characters", FileStem(server, character) + ".json");
|
||||
public string LuaPathFor(string server, string character) => Path.Combine(LuaDataRoot, "characters", FileStem(server, character) + ".json");
|
||||
|
||||
/// <summary>
|
||||
/// The character's rules and settings: RynthSort's own file; else the Lua script's (imported:
|
||||
/// <see cref="CharacterSortData.ImportedFrom"/> says so, and the caller saves it as RynthSort's);
|
||||
/// else the defaults. A broken file reads as the defaults (the next save rewrites it).
|
||||
/// </summary>
|
||||
public CharacterSortData Load(string server, string character, out string? problem)
|
||||
{
|
||||
problem = null;
|
||||
string own = PathFor(server, character);
|
||||
if (File.Exists(own))
|
||||
{
|
||||
if (TryRead(own, out CharacterSortData? d, out problem)) return d!;
|
||||
return new CharacterSortData();
|
||||
}
|
||||
string lua = LuaPathFor(server, character);
|
||||
if (File.Exists(lua) && TryRead(lua, out CharacterSortData? imported, out problem))
|
||||
{
|
||||
imported!.ImportedFrom = lua;
|
||||
return imported;
|
||||
}
|
||||
return new CharacterSortData();
|
||||
}
|
||||
|
||||
public static bool TryRead(string path, out CharacterSortData? data, out string? problem)
|
||||
{
|
||||
data = null;
|
||||
problem = null;
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path),
|
||||
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
data = Parse(doc.RootElement);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException)
|
||||
{
|
||||
problem = $"{Path.GetFileName(path)}: {ex.Message}";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Rules and settings from the file's root object; anything missing or odd keeps its default.</summary>
|
||||
internal static CharacterSortData Parse(JsonElement root)
|
||||
{
|
||||
var d = new CharacterSortData();
|
||||
if (root.ValueKind != JsonValueKind.Object) throw new JsonException("the file isn't a JSON object");
|
||||
|
||||
if (root.TryGetProperty("rules", out JsonElement rules))
|
||||
{
|
||||
// The Lua script saved an empty rule list as {} (an empty Lua table): no rules either.
|
||||
if (rules.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
d.Rules = new List<SortRule>();
|
||||
foreach (JsonElement e in rules.EnumerateArray())
|
||||
{
|
||||
if (d.Rules.Count >= MaxRules) break;
|
||||
SortRule? r = ParseRule(e);
|
||||
if (r != null) d.Rules.Add(r);
|
||||
}
|
||||
}
|
||||
else if (rules.ValueKind == JsonValueKind.Object && !rules.EnumerateObject().MoveNext())
|
||||
{
|
||||
d.Rules = new List<SortRule>();
|
||||
}
|
||||
}
|
||||
|
||||
if (root.TryGetProperty("settings", out JsonElement s) && s.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
SortSettings st = d.Settings;
|
||||
st.Auto = Bool(s, "auto", st.Auto);
|
||||
st.SettleSec = Int(s, "settleSec", st.SettleSec);
|
||||
st.GapMs = Int(s, "gapMs", st.GapMs);
|
||||
st.SortInCombat = Bool(s, "sortInCombat", st.SortInCombat);
|
||||
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;
|
||||
return d;
|
||||
}
|
||||
|
||||
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),
|
||||
};
|
||||
if (r.Text.Length > 64) r.Text = r.Text[..64];
|
||||
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)
|
||||
{
|
||||
string path = PathFor(server, character);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
|
||||
File.WriteAllText(tmp, ToJson(d), new UTF8Encoding(false));
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
internal static string ToJson(CharacterSortData d)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("version", 1);
|
||||
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.WriteNumber("pack", r.Pack);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
w.WriteStartObject("settings");
|
||||
w.WriteBoolean("auto", d.Settings.Auto);
|
||||
w.WriteNumber("settleSec", d.Settings.SettleSec);
|
||||
w.WriteNumber("gapMs", d.Settings.GapMs);
|
||||
w.WriteBoolean("sortInCombat", d.Settings.SortInCombat);
|
||||
w.WriteBoolean("windowOpen", d.Settings.WindowOpen);
|
||||
w.WriteEndObject();
|
||||
if (d.ImportedFrom.Length > 0) w.WriteString("importedFrom", d.ImportedFrom);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(ms.ToArray()) + "\n";
|
||||
}
|
||||
|
||||
private static bool Bool(JsonElement o, string name, bool fallback) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && (v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
|
||||
? v.GetBoolean()
|
||||
: fallback;
|
||||
|
||||
private static int Int(JsonElement o, string name, int fallback)
|
||||
{
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;
|
||||
if (v.TryGetInt32(out int i)) return i;
|
||||
// Lua numbers are doubles: 5.0 is 5.
|
||||
return v.TryGetDouble(out double dbl) && dbl >= int.MinValue && dbl <= int.MaxValue ? (int)Math.Round(dbl) : fallback;
|
||||
}
|
||||
|
||||
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
|
||||
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
|
||||
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
|
||||
};
|
||||
|
||||
/// <summary>RynthLua's LibraryStorage.SafeFileName, so both name a character's file the same way.</summary>
|
||||
public static string SafeFileName(string? name)
|
||||
{
|
||||
var invalid = Path.GetInvalidFileNameChars();
|
||||
var chars = (name ?? string.Empty).Trim().ToCharArray();
|
||||
for (int i = 0; i < chars.Length; i++)
|
||||
if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] < 32) chars[i] = '_';
|
||||
string n = new string(chars).TrimEnd('.', ' ');
|
||||
if (n.Length > 80) n = n[..80].TrimEnd('.', ' ');
|
||||
if (n.Length == 0 || n.Trim('.').Length == 0) n = "_" + n;
|
||||
string stem = n.Split('.')[0];
|
||||
if (ReservedNames.Contains(stem)) n = "_" + n;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
191
Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs
Normal file
191
Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the character's packs from the client into a <see cref="SortInventory"/>. Plugin pump
|
||||
/// thread only. GetContainerContents(player) gives the main pack's items, the side packs and the
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class InventoryReader
|
||||
{
|
||||
private const uint IntItemsCapacity = 6, IntMaxStackSize = 11, IntStackSize = 12;
|
||||
|
||||
private const uint ItemTypeMeleeWeapon = 0x00000001, ItemTypeArmor = 0x00000002, ItemTypeClothing = 0x00000004,
|
||||
ItemTypeJewelry = 0x00000008, ItemTypeCreature = 0x00000010, ItemTypeFood = 0x00000020, ItemTypeMoney = 0x00000040,
|
||||
ItemTypeMisc = 0x00000080, ItemTypeMissileWeapon = 0x00000100, ItemTypeContainer = 0x00000200,
|
||||
ItemTypeGem = 0x00000800, ItemTypeSpellComponents = 0x00001000, ItemTypeWritable = 0x00002000,
|
||||
ItemTypeKey = 0x00004000, ItemTypeCaster = 0x00008000, ItemTypePortal = 0x00010000,
|
||||
ItemTypePromissoryNote = 0x00040000, ItemTypeManaStone = 0x00080000, ItemTypeService = 0x00100000,
|
||||
ItemTypeCraftCookingBase = 0x00400000, ItemTypeCraftAlchemyBase = 0x00800000,
|
||||
ItemTypeCraftFletchingBase = 0x02000000, ItemTypeCraftAlchemyIntermediate = 0x04000000,
|
||||
ItemTypeCraftFletchingIntermediate = 0x08000000, ItemTypeLifeStone = 0x10000000,
|
||||
ItemTypeTinkeringTool = 0x20000000, ItemTypeTinkeringMaterial = 0x40000000;
|
||||
|
||||
// PublicWeenieDesc bitfield bits RynthLua's classifier reads for items.
|
||||
private const uint BfFood = 0x8000, BfHealer = 0x10000, BfLockpick = 0x20000;
|
||||
|
||||
private sealed class Known
|
||||
{
|
||||
public string Name = string.Empty;
|
||||
public int Class;
|
||||
public uint Wcid;
|
||||
public int MaxStack = 1;
|
||||
}
|
||||
|
||||
private readonly Dictionary<uint, Known> _known = new();
|
||||
private uint[] _buf = new uint[512];
|
||||
|
||||
public void Reset() => _known.Clear();
|
||||
|
||||
/// <summary>The packs now, or null when the character or its inventory isn't readable yet.</summary>
|
||||
public SortInventory? Read(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasGetPlayerId || !host.HasGetContainerContents) return null;
|
||||
uint player = host.GetPlayerId();
|
||||
if (player == 0) return null;
|
||||
|
||||
var inv = new SortInventory();
|
||||
inv.Main.Id = player;
|
||||
inv.Main.Name = "Main pack";
|
||||
inv.Main.Capacity = host.TryGetObjectIntProperty(player, IntItemsCapacity, out int mainCap) && mainCap > 0 ? mainCap : 0;
|
||||
|
||||
uint[] top = Contents(host, player);
|
||||
if (top.Length == 0) return null; // not loaded yet: never plan from an empty read
|
||||
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)
|
||||
{
|
||||
// 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)
|
||||
{
|
||||
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))
|
||||
{
|
||||
if (inner == 0) continue;
|
||||
uint it = host.TryGetItemType(inner, out uint itt) ? itt : 0;
|
||||
if ((it & ItemTypeContainer) != 0) continue;
|
||||
pack.Items.Add(Item(host, inner, it));
|
||||
}
|
||||
inv.Packs.Add(pack);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
inv.Main.Items.Add(Item(host, id, type));
|
||||
}
|
||||
return inv;
|
||||
}
|
||||
|
||||
private uint[] Contents(RynthCoreHost host, uint container)
|
||||
{
|
||||
int n = host.GetContainerContents(container, _buf);
|
||||
if (n >= _buf.Length)
|
||||
{
|
||||
_buf = new uint[_buf.Length * 2];
|
||||
n = host.GetContainerContents(container, _buf);
|
||||
}
|
||||
if (n <= 0) return Array.Empty<uint>();
|
||||
var ids = new uint[n];
|
||||
Array.Copy(_buf, ids, n);
|
||||
return ids;
|
||||
}
|
||||
|
||||
private static bool Wielded(RynthCoreHost host, uint id)
|
||||
{
|
||||
if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out _, out uint wielder, out _))
|
||||
return wielder != 0;
|
||||
return host.HasGetObjectWielderInfo && host.TryGetObjectWielderInfo(id, out uint w, out _) && w != 0;
|
||||
}
|
||||
|
||||
private SortItem Item(RynthCoreHost host, uint id, uint type)
|
||||
{
|
||||
if (!_known.TryGetValue(id, out Known? k))
|
||||
{
|
||||
k = new Known();
|
||||
k.Name = host.TryGetObjectName(id, out string name) ? name : string.Empty;
|
||||
k.Wcid = host.HasGetObjectWcid && host.TryGetObjectWcid(id, out uint wcid) ? wcid : 0;
|
||||
k.MaxStack = host.TryGetObjectIntProperty(id, IntMaxStackSize, out int max) && max > 0 ? max : 1;
|
||||
k.Class = Classify(host, id, type, k.Name, out bool certain);
|
||||
// Kept once the client had the data (a fresh object can lack its name or type for a tick).
|
||||
if (certain && k.Name.Length > 0) _known[id] = k;
|
||||
}
|
||||
int stack = host.TryGetObjectIntProperty(id, IntStackSize, out int s) && s > 0 ? s : 1;
|
||||
return new SortItem { Id = id, Name = k.Name, ObjectClass = k.Class, Wcid = k.Wcid, Stack = stack, MaxStack = k.MaxStack };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The item's ObjectClass the way RynthLua's game.World classifies items (GameWorldObject.cs:
|
||||
/// the healer / lockpick / food bits, then the ItemType flags most specific first, scrolls and
|
||||
/// foci by name), so a rule means the same in both.
|
||||
/// </summary>
|
||||
internal static int Classify(RynthCoreHost host, uint id, uint type, string name, out bool certain)
|
||||
{
|
||||
certain = false;
|
||||
uint bf = 0;
|
||||
bool gotBf = host.HasGetObjectBitfield && host.TryGetObjectBitfield(id, out bf) && bf != 0;
|
||||
if (!gotBf) bf = 0;
|
||||
return ClassifyFrom(type, bf, name, out certain);
|
||||
}
|
||||
|
||||
/// <summary>The classification from the raw data (pure).</summary>
|
||||
internal static int ClassifyFrom(uint type, uint bitfield, string name, out bool certain)
|
||||
{
|
||||
certain = false;
|
||||
name ??= string.Empty;
|
||||
if (type != 0 && (type & ItemTypeCreature) != 0) { certain = true; return ObjectClasses.Monster; }
|
||||
if (bitfield != 0)
|
||||
{
|
||||
if ((bitfield & BfHealer) != 0) { certain = true; return ObjectClasses.HealingKit; }
|
||||
if ((bitfield & BfLockpick) != 0) { certain = true; return ObjectClasses.Lockpick; }
|
||||
}
|
||||
if (type != 0)
|
||||
{
|
||||
certain = true;
|
||||
int cls = ClassifyByItemType(type);
|
||||
if (cls == ObjectClasses.Book && name.Contains("Scroll", StringComparison.OrdinalIgnoreCase)) return ObjectClasses.Scroll;
|
||||
if (name.StartsWith("Foci of", StringComparison.OrdinalIgnoreCase)) return ObjectClasses.Foci;
|
||||
if (cls == ObjectClasses.Misc && (bitfield & BfFood) != 0) return ObjectClasses.Food;
|
||||
return cls;
|
||||
}
|
||||
if ((bitfield & BfFood) != 0) { certain = true; return ObjectClasses.Food; }
|
||||
return ObjectClasses.Unknown;
|
||||
}
|
||||
|
||||
private static int ClassifyByItemType(uint t)
|
||||
{
|
||||
if ((t & ItemTypePromissoryNote) != 0) return ObjectClasses.TradeNote;
|
||||
if ((t & ItemTypeManaStone) != 0) return ObjectClasses.ManaStone;
|
||||
if ((t & ItemTypeSpellComponents) != 0) return ObjectClasses.SpellComponent;
|
||||
if ((t & ItemTypeGem) != 0) return ObjectClasses.Gem;
|
||||
if ((t & ItemTypeKey) != 0) return ObjectClasses.Key;
|
||||
if ((t & ItemTypeLifeStone) != 0) return ObjectClasses.Lifestone;
|
||||
if ((t & ItemTypeTinkeringMaterial) != 0) return ObjectClasses.Salvage;
|
||||
if ((t & ItemTypeTinkeringTool) != 0) return ObjectClasses.Ust;
|
||||
if ((t & ItemTypeCraftCookingBase) != 0) return ObjectClasses.BaseCooking;
|
||||
if ((t & ItemTypeCraftAlchemyBase) != 0) return ObjectClasses.BaseAlchemy;
|
||||
if ((t & ItemTypeCraftFletchingBase) != 0) return ObjectClasses.BaseFletching;
|
||||
if ((t & ItemTypeCraftAlchemyIntermediate) != 0) return ObjectClasses.CraftedAlchemy;
|
||||
if ((t & ItemTypeCraftFletchingIntermediate) != 0) return ObjectClasses.CraftedFletching;
|
||||
if ((t & ItemTypeService) != 0) return ObjectClasses.Services;
|
||||
if ((t & ItemTypePortal) != 0) return ObjectClasses.Portal;
|
||||
if ((t & ItemTypeWritable) != 0) return ObjectClasses.Book;
|
||||
if ((t & ItemTypeContainer) != 0) return ObjectClasses.Container;
|
||||
if ((t & ItemTypeCaster) != 0) return ObjectClasses.WandStaffOrb;
|
||||
if ((t & ItemTypeMissileWeapon) != 0) return ObjectClasses.MissileWeapon;
|
||||
if ((t & ItemTypeArmor) != 0) return ObjectClasses.Armor;
|
||||
if ((t & ItemTypeMeleeWeapon) != 0) return ObjectClasses.MeleeWeapon;
|
||||
if ((t & ItemTypeClothing) != 0) return ObjectClasses.Clothing;
|
||||
if ((t & ItemTypeJewelry) != 0) return ObjectClasses.Jewelry;
|
||||
if ((t & ItemTypeFood) != 0) return ObjectClasses.Food;
|
||||
if ((t & ItemTypeMoney) != 0) return ObjectClasses.Money;
|
||||
if ((t & ItemTypeMisc) != 0) return ObjectClasses.Misc;
|
||||
return ObjectClasses.Unknown;
|
||||
}
|
||||
}
|
||||
84
Plugins/RynthCore.Plugin.RynthSort/Sorting/MoveTracker.cs
Normal file
84
Plugins/RynthCore.Plugin.RynthSort/Sorting/MoveTracker.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>How a move in flight ended (or that it hasn't yet).</summary>
|
||||
internal enum MoveOutcome
|
||||
{
|
||||
Pending,
|
||||
/// <summary>The item is in the destination, or merged into a stack there.</summary>
|
||||
Done,
|
||||
/// <summary>The server refused it (InventoryServerSaveFailed, or a refusal naming the item).</summary>
|
||||
Refused,
|
||||
/// <summary>The server said "You're too busy" (or too many actions): try again later.</summary>
|
||||
TooBusy,
|
||||
/// <summary>No answer in <see cref="MoveTracker.TimeoutMs"/>.</summary>
|
||||
TimedOut,
|
||||
}
|
||||
|
||||
/// <summary>What the client says about the moved item and the server's last refusal, read each tick.</summary>
|
||||
internal struct MoveObservation
|
||||
{
|
||||
public bool Exists;
|
||||
public uint Container;
|
||||
public uint Wielder;
|
||||
public int Stack;
|
||||
/// <summary>The engine's refusal counter (TryGetLastWeenieError seq; 0 when unknown).</summary>
|
||||
public int ErrorSeq;
|
||||
public uint Error;
|
||||
public uint ErrorEventType;
|
||||
public uint ErrorObject;
|
||||
}
|
||||
|
||||
/// <summary>The one move RynthSort has out.</summary>
|
||||
internal sealed class MoveInFlight
|
||||
{
|
||||
public SortMove Move;
|
||||
public long SentMs;
|
||||
public int ErrorSeqAtSend;
|
||||
public int StackAtSend;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One move at a time: what counts as its answer, and how long to hold off after a refusal.
|
||||
/// Pure (no host calls), so the tests drive it with observations.
|
||||
/// </summary>
|
||||
internal static class MoveTracker
|
||||
{
|
||||
/// <summary>A move with no answer by then has failed (the Lua script's ObjectMove time limit).</summary>
|
||||
public const long TimeoutMs = 5000;
|
||||
/// <summary>An item that couldn't be moved is left alone this long.</summary>
|
||||
public const long BlockMs = 60_000;
|
||||
/// <summary>The longest hold after refusals in a row.</summary>
|
||||
public const long MaxBackoffMs = 30_000;
|
||||
|
||||
public const uint EventInventoryServerSaveFailed = 0x00A0;
|
||||
public const uint ErrorYoureTooBusy = 0x001D;
|
||||
public const uint ErrorTooManyActions = 0x0045;
|
||||
|
||||
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
|
||||
if (o.ErrorSeq != 0 && o.ErrorSeq != m.ErrorSeqAtSend)
|
||||
{
|
||||
if (o.Error == ErrorYoureTooBusy || o.Error == ErrorTooManyActions) return MoveOutcome.TooBusy;
|
||||
if (o.ErrorObject == mv.Item.Id || o.ErrorEventType == EventInventoryServerSaveFailed) return MoveOutcome.Refused;
|
||||
// Someone else's refusal (a fizzle, RynthAi's use): not ours; keep waiting.
|
||||
}
|
||||
return nowMs - m.SentMs >= TimeoutMs ? MoveOutcome.TimedOut : MoveOutcome.Pending;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The hold before the next move after <paramref name="failuresInARow"/> failures: 2 s, 4 s,
|
||||
/// 8 s ... up to <see cref="MaxBackoffMs"/>; 0 after a success.
|
||||
/// </summary>
|
||||
public static long BackoffMs(int failuresInARow)
|
||||
{
|
||||
if (failuresInARow <= 0) return 0;
|
||||
int shift = Math.Min(failuresInARow - 1, 10);
|
||||
return Math.Min(2000L << shift, MaxBackoffMs);
|
||||
}
|
||||
}
|
||||
236
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortController.cs
Normal file
236
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortController.cs
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>What the controller needs from the game (the plugin's HostSortWorld; the tests' fake).</summary>
|
||||
internal interface ISortWorld
|
||||
{
|
||||
/// <summary>The packs now, or null when they can't be read yet.</summary>
|
||||
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>
|
||||
bool SendMove(in SortMove move);
|
||||
/// <summary>The moved item and the server's last refusal.</summary>
|
||||
MoveObservation Observe(uint itemId);
|
||||
/// <summary>The engine's refusal counter now (0 when the engine can't say).</summary>
|
||||
int ErrorSeqNow();
|
||||
}
|
||||
|
||||
/// <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
|
||||
/// 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>
|
||||
internal sealed class SortController
|
||||
{
|
||||
/// <summary>Between two moves of a job asked for (the server's answer came already).</summary>
|
||||
public const long JobGapMs = 100;
|
||||
/// <summary>How often the gate is checked while paused (and auto-sort off is looked at).</summary>
|
||||
public const long PollMs = 250;
|
||||
/// <summary>How often the packs are read while nothing moves (and for the window while paused).</summary>
|
||||
public const long ViewMs = 1000;
|
||||
public const int LogLines = 6;
|
||||
|
||||
public CharacterSortData Data = new();
|
||||
public readonly SortPlanner Planner = new();
|
||||
public readonly SortGate Gate = new();
|
||||
|
||||
/// <summary>"watching", "off", "sorting", "unpacking", "paused: ..."; shown beside the auto-sort box.</summary>
|
||||
public string Status { get; private set; } = "starting";
|
||||
public bool Paused => Status.StartsWith("paused", StringComparison.Ordinal);
|
||||
/// <summary>A one-off job asked for, or null.</summary>
|
||||
public SortScope? Job { get; private set; }
|
||||
/// <summary>The side pack Unpack empties (null = all).</summary>
|
||||
public int? UnpackWhich { get; private set; }
|
||||
/// <summary>RynthAi's bits from the last gate read (null = RynthAi not there or not ready).</summary>
|
||||
public RynthAiActivity? LastBot { get; private set; }
|
||||
/// <summary>The last few moves and job results, newest first.</summary>
|
||||
public readonly List<string> Log = new();
|
||||
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;
|
||||
|
||||
private MoveInFlight? _inFlight;
|
||||
private long _nextStepMs;
|
||||
private long _nextViewMs;
|
||||
private int _failuresInARow;
|
||||
|
||||
public bool HasMoveOut => _inFlight != null;
|
||||
|
||||
/// <summary>Forget the character (logout, another character's data).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
Planner.Reset();
|
||||
Gate.Reset();
|
||||
_inFlight = null;
|
||||
_nextStepMs = _nextViewMs = 0;
|
||||
_failuresInARow = 0;
|
||||
Job = null;
|
||||
UnpackWhich = null;
|
||||
LastBot = null;
|
||||
Status = "starting";
|
||||
Log.Clear();
|
||||
Moved = Failed = 0;
|
||||
}
|
||||
|
||||
// ── Asking ──────────────────────────────────────────────────────────────
|
||||
|
||||
public void SetAuto(bool on)
|
||||
{
|
||||
Data.Settings.Auto = on;
|
||||
SettingsChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>Sort now (Main), Tidy (All) or Clean, as soon as the way is clear.</summary>
|
||||
public void StartJob(SortScope scope)
|
||||
{
|
||||
if (scope == SortScope.Unpack) { StartUnpack(null); return; }
|
||||
Job = scope;
|
||||
_nextStepMs = 0;
|
||||
}
|
||||
|
||||
/// <summary>Empty every side pack (or pack <paramref name="which"/>) into the main pack; auto-sort goes off first so nothing moves straight back.</summary>
|
||||
public void StartUnpack(int? which)
|
||||
{
|
||||
Data.Settings.Auto = false;
|
||||
Job = SortScope.Unpack;
|
||||
UnpackWhich = which;
|
||||
_nextStepMs = 0;
|
||||
SettingsChanged?.Invoke();
|
||||
}
|
||||
|
||||
public void Note(string line)
|
||||
{
|
||||
Log.Insert(0, line);
|
||||
while (Log.Count > LogLines) Log.RemoveAt(Log.Count - 1);
|
||||
}
|
||||
|
||||
// ── The loop ────────────────────────────────────────────────────────────
|
||||
|
||||
public void Tick(ISortWorld world, long nowMs)
|
||||
{
|
||||
if (_inFlight != null)
|
||||
{
|
||||
MoveObservation o = world.Observe(_inFlight.Move.Item.Id);
|
||||
MoveOutcome outcome = MoveTracker.Observe(_inFlight, in o, nowMs);
|
||||
if (outcome == MoveOutcome.Pending) return;
|
||||
Finish(_inFlight.Move, outcome, nowMs);
|
||||
_inFlight = null;
|
||||
return;
|
||||
}
|
||||
if (nowMs < _nextStepMs) return;
|
||||
|
||||
SortScope? scope = Job ?? (Data.Settings.Auto ? SortScope.Main : null);
|
||||
if (scope == null)
|
||||
{
|
||||
Status = "off";
|
||||
LastBot = null;
|
||||
RefreshView(world, SortScope.Main, nowMs);
|
||||
_nextStepMs = nowMs + PollMs;
|
||||
return;
|
||||
}
|
||||
|
||||
GateInputs g = world.ReadGate(Data.Settings.SortInCombat, nowMs);
|
||||
LastBot = g.Bot;
|
||||
string? why = Gate.Evaluate(in g, nowMs);
|
||||
if (why != null)
|
||||
{
|
||||
Status = "paused: " + why;
|
||||
RefreshView(world, scope == SortScope.Unpack ? SortScope.Main : scope.Value, nowMs);
|
||||
_nextStepMs = nowMs + PollMs;
|
||||
return;
|
||||
}
|
||||
|
||||
SortInventory? inv = world.ReadInventory();
|
||||
if (inv == null)
|
||||
{
|
||||
Status = "waiting for the inventory";
|
||||
_nextStepMs = nowMs + ViewMs;
|
||||
return;
|
||||
}
|
||||
_nextViewMs = nowMs + ViewMs;
|
||||
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);
|
||||
|
||||
if (moves.Count == 0)
|
||||
{
|
||||
if (Job != null) NoteJobDone(Job.Value);
|
||||
Job = null;
|
||||
UnpackWhich = null;
|
||||
Status = Data.Settings.Auto ? "watching" : "off";
|
||||
_nextStepMs = nowMs + ViewMs; // nothing to do: look again in a second (the Lua script's pace)
|
||||
return;
|
||||
}
|
||||
|
||||
Status = scope == SortScope.Unpack ? "unpacking" : "sorting";
|
||||
SortMove m = moves[0];
|
||||
int seq = world.ErrorSeqNow();
|
||||
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 };
|
||||
}
|
||||
|
||||
private void NoteJobDone(SortScope job)
|
||||
{
|
||||
SortView v = Planner.View;
|
||||
switch (job)
|
||||
{
|
||||
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;
|
||||
default: Note(v.Waiting > 0 ? $"Main pack sorted ({v.Waiting} can't move yet)" : "Main pack sorted"); break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Finish(SortMove m, MoveOutcome outcome, long nowMs, string? why = null)
|
||||
{
|
||||
string name = m.Item.Name.Length > 0 ? m.Item.Name : $"0x{m.Item.Id:X8}";
|
||||
long gap = Job != null ? JobGapMs : Data.Settings.GapMs;
|
||||
switch (outcome)
|
||||
{
|
||||
case MoveOutcome.Done:
|
||||
Moved++;
|
||||
_failuresInARow = 0;
|
||||
Note($"{name} -> {m.DestLabel}");
|
||||
_nextStepMs = nowMs + gap;
|
||||
return;
|
||||
case MoveOutcome.TooBusy:
|
||||
// Not the item's fault: no block, just a longer hold.
|
||||
_failuresInARow++;
|
||||
Note($"{name}: the server is busy, trying again");
|
||||
_nextStepMs = nowMs + Math.Max(gap, MoveTracker.BackoffMs(_failuresInARow));
|
||||
return;
|
||||
default:
|
||||
Failed++;
|
||||
_failuresInARow++;
|
||||
Planner.Block(m.Item.Id, nowMs + MoveTracker.BlockMs);
|
||||
why ??= outcome == MoveOutcome.TimedOut ? "no answer from the server" : "the server refused it";
|
||||
Note($"{name}: not moved ({why})");
|
||||
_nextStepMs = nowMs + Math.Max(gap, MoveTracker.BackoffMs(_failuresInARow));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the packs for the window now and then while nothing moves.</summary>
|
||||
private void RefreshView(ISortWorld world, SortScope scope, long nowMs)
|
||||
{
|
||||
if (nowMs < _nextViewMs) return;
|
||||
_nextViewMs = nowMs + ViewMs;
|
||||
SortInventory? inv = world.ReadInventory();
|
||||
if (inv == null) return;
|
||||
if (scope == SortScope.Unpack) Planner.PlanUnpack(inv, UnpackWhich, nowMs);
|
||||
else Planner.Plan(inv, Data.Rules, scope, force: false, nowMs, Data.Settings.SettleSec * 1000);
|
||||
}
|
||||
}
|
||||
124
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortGate.cs
Normal file
124
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortGate.cs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>Everything the "stay out of the way" check looks at, read once per pass.</summary>
|
||||
internal struct GateInputs
|
||||
{
|
||||
public bool InPortalSpace;
|
||||
/// <summary>A corpse or chest is being looted (<see cref="LootWatch"/>).</summary>
|
||||
public bool Looting;
|
||||
public bool VendorOpen;
|
||||
public bool TradeOpen;
|
||||
/// <summary>The client's busy count is above zero (a use, a cast, or anyone's item move in flight).</summary>
|
||||
public bool ClientBusy;
|
||||
/// <summary>The character's motion queue isn't empty (a gesture, a cast animation, a stance change).</summary>
|
||||
public bool Animating;
|
||||
/// <summary>RynthAi's activity bits (RynthAi.Activity), or null when RynthAi isn't loaded or not ready.</summary>
|
||||
public RynthAiActivity? Bot;
|
||||
/// <summary>The "Sort during fights" setting: moves may go while RynthAi fights (still never mid-action).</summary>
|
||||
public bool SortInCombat;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why no item may move right now, or null when it's fine. Never while a corpse or chest is
|
||||
/// being looted, a vendor or trade window is open, the character is busy with a use or cast or
|
||||
/// still animating, or in portal space; and never while RynthAi is looting, salvaging, buffing,
|
||||
/// healing, making ammo or waiting on the server for something it sent. While RynthAi fights,
|
||||
/// nothing moves either unless "Sort during fights" is on. After any pause, moves wait
|
||||
/// <see cref="QuietMs"/> more (the next corpse, cast or buff is often a moment away).
|
||||
/// </summary>
|
||||
internal sealed class SortGate
|
||||
{
|
||||
/// <summary>How long the way must have been clear before the next move.</summary>
|
||||
public const long QuietMs = 1500;
|
||||
|
||||
private long _pausedAt = long.MinValue / 2;
|
||||
private string _lastReason = string.Empty;
|
||||
|
||||
/// <summary>The reason without the quiet time: pure, for the tests and the window.</summary>
|
||||
public static string? Reason(in GateInputs g)
|
||||
{
|
||||
if (g.InPortalSpace) return "portal space";
|
||||
if (g.Looting) return "looting";
|
||||
if (g.VendorOpen) return "vendor open";
|
||||
if (g.TradeOpen) return "trading";
|
||||
if (g.ClientBusy || g.Animating) return "busy";
|
||||
if (g.Bot is RynthAiActivity a)
|
||||
{
|
||||
if ((a & RynthAiActivity.Looting) != 0) return "RynthAi is looting";
|
||||
if ((a & RynthAiActivity.Salvaging) != 0) return "RynthAi is salvaging";
|
||||
if ((a & RynthAiActivity.Buffing) != 0) return "RynthAi is buffing";
|
||||
if ((a & RynthAiActivity.Crafting) != 0) return "RynthAi is making ammo";
|
||||
if ((a & RynthAiActivity.ServerAction) != 0) return "RynthAi is waiting on the server";
|
||||
if ((a & RynthAiActivity.Combat) != 0 && !g.SortInCombat) return "RynthAi is fighting";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The reason, held for <see cref="QuietMs"/> after it clears.</summary>
|
||||
public string? Evaluate(in GateInputs g, long nowMs)
|
||||
{
|
||||
string? why = Reason(in g);
|
||||
if (why != null)
|
||||
{
|
||||
_pausedAt = nowMs;
|
||||
_lastReason = why;
|
||||
return why;
|
||||
}
|
||||
return nowMs - _pausedAt < QuietMs ? _lastReason : null;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_pausedAt = long.MinValue / 2;
|
||||
_lastReason = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the open corpse or chest is being looted. The client keeps reporting the last corpse
|
||||
/// as open after it has been looted (until another opens or you walk away), so an open container
|
||||
/// only counts while something is happening to it: it just opened, or its contents changed,
|
||||
/// within <see cref="ActiveMs"/>; and for <see cref="AfterMs"/> after that (the next corpse is
|
||||
/// often a moment away). The Lua script's rule, unchanged.
|
||||
/// </summary>
|
||||
internal sealed class LootWatch
|
||||
{
|
||||
public const long ActiveMs = 4000;
|
||||
public const long AfterMs = 1500;
|
||||
|
||||
private uint _id;
|
||||
private int _count = -1;
|
||||
private long _changedAt = long.MinValue / 2;
|
||||
private long _lastLootingAt = long.MinValue / 2;
|
||||
|
||||
/// <param name="containerId">The open ground container (0 = none).</param>
|
||||
/// <param name="itemCount">How many items it holds now.</param>
|
||||
public bool Update(uint containerId, int itemCount, long nowMs)
|
||||
{
|
||||
if (containerId != 0)
|
||||
{
|
||||
if (containerId != _id || itemCount != _count)
|
||||
{
|
||||
_id = containerId;
|
||||
_count = itemCount;
|
||||
_changedAt = nowMs;
|
||||
}
|
||||
if (nowMs - _changedAt < ActiveMs)
|
||||
{
|
||||
_lastLootingAt = nowMs;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return nowMs - _lastLootingAt < AfterMs;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_id = 0;
|
||||
_count = -1;
|
||||
_changedAt = long.MinValue / 2;
|
||||
_lastLootingAt = long.MinValue / 2;
|
||||
}
|
||||
}
|
||||
34
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs
Normal file
34
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>One loose item in a pack, as read this pass (InventoryReader).</summary>
|
||||
internal sealed class SortItem
|
||||
{
|
||||
public uint Id;
|
||||
public string Name = string.Empty;
|
||||
/// <summary>ObjectClass number (<see cref="ObjectClasses"/>).</summary>
|
||||
public int ObjectClass;
|
||||
public uint Wcid;
|
||||
public int Stack = 1;
|
||||
public int MaxStack = 1;
|
||||
/// <summary>Worn or wielded (the reader leaves these out; kept so the planner can refuse them too).</summary>
|
||||
public bool Wielded { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The main pack or one side pack and its loose items (packs and foci are never items).</summary>
|
||||
internal sealed class SortPack
|
||||
{
|
||||
public uint Id;
|
||||
public string Name = string.Empty;
|
||||
/// <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>The character's packs: the main pack and the side packs in order, top to bottom (pack 1 first).</summary>
|
||||
internal sealed class SortInventory
|
||||
{
|
||||
public SortPack Main = new();
|
||||
public readonly List<SortPack> Packs = new();
|
||||
}
|
||||
252
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs
Normal file
252
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
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>
|
||||
Main,
|
||||
/// <summary>Every pack, no settling: items in the wrong side pack move to theirs too ("Tidy").</summary>
|
||||
All,
|
||||
/// <summary>As <see cref="All"/>, and side-pack items no rule wants go back to the main pack ("Clean").</summary>
|
||||
Clean,
|
||||
/// <summary>Every side pack (or one) emptied into the main pack ("Unpack").</summary>
|
||||
Unpack,
|
||||
}
|
||||
|
||||
/// <summary>One move: <see cref="Item"/> into <see cref="Dest"/> (pack <see cref="DestIndex"/>, 0 = main pack).</summary>
|
||||
internal readonly struct SortMove
|
||||
{
|
||||
public readonly SortItem Item;
|
||||
public readonly SortPack Dest;
|
||||
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;
|
||||
|
||||
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto)
|
||||
{
|
||||
Item = item;
|
||||
Dest = dest;
|
||||
DestIndex = destIndex;
|
||||
MergeInto = mergeInto;
|
||||
}
|
||||
|
||||
public string DestLabel => DestIndex == 0 ? "main pack" : "pack " + DestIndex;
|
||||
}
|
||||
|
||||
/// <summary>A side pack as the window lists it.</summary>
|
||||
internal sealed class PackLine
|
||||
{
|
||||
public string Name = string.Empty;
|
||||
public int Used;
|
||||
public int Capacity;
|
||||
}
|
||||
|
||||
/// <summary>What the window shows about the packs after a planning pass.</summary>
|
||||
internal sealed class SortView
|
||||
{
|
||||
public readonly List<PackLine> Packs = new();
|
||||
public int MainUsed;
|
||||
public int MainCapacity;
|
||||
/// <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>
|
||||
public readonly SortedSet<int> Missing = 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.
|
||||
/// 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;
|
||||
|
||||
private readonly Dictionary<uint, long> _firstSeen = new();
|
||||
private readonly Dictionary<uint, long> _blocked = new();
|
||||
|
||||
public SortView View { get; private set; } = new();
|
||||
|
||||
/// <summary>Forget everything (logout, another character).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_firstSeen.Clear();
|
||||
_blocked.Clear();
|
||||
View = new SortView();
|
||||
}
|
||||
|
||||
/// <summary>Leave <paramref name="itemId"/> alone until <paramref name="untilMs"/> (a move failed).</summary>
|
||||
public void Block(uint itemId, long untilMs) => _blocked[itemId] = untilMs;
|
||||
|
||||
public bool IsBlocked(uint itemId, long nowMs) => _blocked.TryGetValue(itemId, out long until) && until > nowMs;
|
||||
|
||||
public int BlockedCount(long nowMs)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (long until in _blocked.Values) if (until > nowMs) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <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;
|
||||
|
||||
public static int CapacityOf(SortPack p, int fallback) => p.Capacity > 0 ? p.Capacity : fallback;
|
||||
|
||||
/// <summary>
|
||||
/// A stack in <paramref name="pack"/> that <paramref name="it"/> can join (the same kind, with room
|
||||
/// left), or 0. That is what lets a full pack still take the item.
|
||||
/// </summary>
|
||||
public static uint StackTarget(SortItem it, SortPack pack)
|
||||
{
|
||||
if (it.MaxStack <= 1) return 0;
|
||||
foreach (SortItem other in pack.Items)
|
||||
{
|
||||
if (other.Id == it.Id || !SameKind(it, other)) continue;
|
||||
int max = other.MaxStack > 1 ? other.MaxStack : it.MaxStack;
|
||||
if (other.Stack < max) return other.Id;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private 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;
|
||||
|
||||
/// <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).
|
||||
/// </summary>
|
||||
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs)
|
||||
{
|
||||
bool everyPack = scope != SortScope.Main;
|
||||
bool evict = scope == 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);
|
||||
|
||||
void Consider(SortItem wo, int from, bool settled)
|
||||
{
|
||||
if (!Sortable(wo) || IsBlocked(wo.Id, nowMs)) return;
|
||||
SortRule? r = SortRules.RuleFor(rules, wo);
|
||||
if (r == null && evict && from > 0)
|
||||
{
|
||||
// In a side pack and no rule wants it: back to the main pack, while there is room.
|
||||
uint joins = StackTarget(wo, inv.Main);
|
||||
if (mainUsed < mainCap || joins != 0)
|
||||
{
|
||||
moves.Add(new SortMove(wo, inv.Main, 0, joins));
|
||||
if (joins == 0) mainUsed++;
|
||||
}
|
||||
else
|
||||
{
|
||||
view.MainFull = true;
|
||||
view.Waiting++;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (r == null || r.Pack == from) return;
|
||||
if (r.Pack < 1 || r.Pack > inv.Packs.Count)
|
||||
{
|
||||
view.Missing.Add(r.Pack);
|
||||
view.Waiting++;
|
||||
return;
|
||||
}
|
||||
SortPack dest = inv.Packs[r.Pack - 1];
|
||||
uint into = StackTarget(wo, dest);
|
||||
if (used[r.Pack] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
|
||||
{
|
||||
view.Full.Add(r.Pack);
|
||||
view.Waiting++;
|
||||
return;
|
||||
}
|
||||
if (!settled)
|
||||
{
|
||||
view.Waiting++;
|
||||
return;
|
||||
}
|
||||
moves.Add(new SortMove(wo, dest, r.Pack, into));
|
||||
if (into == 0) used[r.Pack]++;
|
||||
}
|
||||
|
||||
var inMain = new HashSet<uint>();
|
||||
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);
|
||||
}
|
||||
if (_firstSeen.Count > inMain.Count)
|
||||
{
|
||||
var gone = new List<uint>();
|
||||
foreach (uint id in _firstSeen.Keys) if (!inMain.Contains(id)) gone.Add(id);
|
||||
foreach (uint id in gone) _firstSeen.Remove(id);
|
||||
}
|
||||
if (everyPack)
|
||||
{
|
||||
for (int i = 0; i < inv.Packs.Count; i++)
|
||||
foreach (SortItem wo in inv.Packs[i].Items) Consider(wo, i + 1, true);
|
||||
}
|
||||
|
||||
FillPacks(view, inv);
|
||||
View = view;
|
||||
return moves;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emptying side packs into the main pack: every sortable item in side pack <paramref name="which"/>
|
||||
/// (1-based; null = all of them), while the main pack has room or the item joins a stack there.
|
||||
/// </summary>
|
||||
public List<SortMove> PlanUnpack(SortInventory inv, int? which, long nowMs)
|
||||
{
|
||||
var moves = new List<SortMove>();
|
||||
int used = inv.Main.Items.Count;
|
||||
int cap = CapacityOf(inv.Main, MainCapacityFallback);
|
||||
int waiting = 0;
|
||||
for (int i = 0; i < inv.Packs.Count; i++)
|
||||
{
|
||||
if (which != null && which.Value != i + 1) continue;
|
||||
foreach (SortItem wo in inv.Packs[i].Items)
|
||||
{
|
||||
if (!Sortable(wo) || IsBlocked(wo.Id, nowMs)) continue;
|
||||
uint joins = StackTarget(wo, inv.Main);
|
||||
if (used < cap || joins != 0)
|
||||
{
|
||||
moves.Add(new SortMove(wo, inv.Main, 0, joins));
|
||||
if (joins == 0) used++;
|
||||
}
|
||||
else waiting++;
|
||||
}
|
||||
}
|
||||
var view = new SortView { Waiting = waiting, MainFull = waiting > 0 };
|
||||
FillPacks(view, inv);
|
||||
View = view;
|
||||
return moves;
|
||||
}
|
||||
|
||||
private static void FillPacks(SortView view, SortInventory inv)
|
||||
{
|
||||
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),
|
||||
});
|
||||
}
|
||||
}
|
||||
128
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortRules.cs
Normal file
128
Plugins/RynthCore.Plugin.RynthSort/Sorting/SortRules.cs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
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 }.
|
||||
/// </summary>
|
||||
internal sealed class SortRule
|
||||
{
|
||||
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;
|
||||
public int Pack = 1;
|
||||
|
||||
public SortRule Clone() => new() { On = On, Kind = Kind, Class = Class, Text = Text, Pack = Pack };
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The ObjectClass numbers, as RynthLua's ObjectClass enum (LuaEnums.ObjectClass: Decal/UtilityBelt
|
||||
/// order), so rules saved by the Lua script mean the same thing here.
|
||||
/// </summary>
|
||||
internal static class ObjectClasses
|
||||
{
|
||||
public static readonly string[] Names =
|
||||
{
|
||||
"Unknown", "MeleeWeapon", "Armor", "Clothing", "Jewelry", "Monster", "Food", "Money", "Misc",
|
||||
"MissileWeapon", "Container", "Gem", "SpellComponent", "Key", "Portal", "TradeNote", "ManaStone",
|
||||
"Plant", "BaseCooking", "BaseAlchemy", "BaseFletching", "CraftedCooking", "CraftedAlchemy",
|
||||
"CraftedFletching", "Player", "Vendor", "Door", "Corpse", "Lifestone", "HealingKit", "Lockpick",
|
||||
"WandStaffOrb", "Bundle", "Book", "Journal", "Sign", "Housing", "Npc", "Foci", "Salvage", "Ust",
|
||||
"Services", "Scroll",
|
||||
};
|
||||
|
||||
public const int Unknown = 0, MeleeWeapon = 1, Armor = 2, Clothing = 3, Jewelry = 4, Monster = 5, Food = 6,
|
||||
Money = 7, Misc = 8, MissileWeapon = 9, Container = 10, Gem = 11, SpellComponent = 12, Key = 13, Portal = 14,
|
||||
TradeNote = 15, ManaStone = 16, Plant = 17, BaseCooking = 18, BaseAlchemy = 19, BaseFletching = 20,
|
||||
CraftedCooking = 21, CraftedAlchemy = 22, CraftedFletching = 23, Player = 24, Vendor = 25, Door = 26,
|
||||
Corpse = 27, Lifestone = 28, HealingKit = 29, Lockpick = 30, WandStaffOrb = 31, Bundle = 32, Book = 33,
|
||||
Journal = 34, Sign = 35, Housing = 36, Npc = 37, Foci = 38, Salvage = 39, Ust = 40, Services = 41, Scroll = 42;
|
||||
|
||||
/// <summary>The classes the rule editor offers, in the Lua script's order.</summary>
|
||||
public static readonly int[] Choices =
|
||||
{
|
||||
SpellComponent, Salvage, Gem, ManaStone, Key, HealingKit, Lockpick, Food, Scroll, TradeNote, Money, Plant,
|
||||
BaseAlchemy, BaseCooking, BaseFletching, CraftedAlchemy, CraftedCooking, CraftedFletching, Jewelry, Armor,
|
||||
Clothing, MeleeWeapon, MissileWeapon, WandStaffOrb, Bundle, Book, Journal, Ust, Misc,
|
||||
};
|
||||
|
||||
/// <summary>"Spell Component" for SpellComponent, as the Lua script showed them.</summary>
|
||||
public static readonly string[] ChoiceLabels = BuildLabels();
|
||||
|
||||
private static string[] BuildLabels()
|
||||
{
|
||||
var labels = new string[Choices.Length];
|
||||
for (int i = 0; i < Choices.Length; i++) labels[i] = Spaced(Names[Choices[i]]);
|
||||
return labels;
|
||||
}
|
||||
|
||||
/// <summary>A space before each capital that follows a small letter ("ManaStone" -> "Mana Stone").</summary>
|
||||
public static string Spaced(string name)
|
||||
{
|
||||
var sb = new StringBuilder(name.Length + 4);
|
||||
for (int i = 0; i < name.Length; i++)
|
||||
{
|
||||
if (i > 0 && char.IsUpper(name[i]) && char.IsLower(name[i - 1])) sb.Append(' ');
|
||||
sb.Append(name[i]);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The index of <paramref name="cls"/> in <see cref="Choices"/>, or -1.</summary>
|
||||
public static int ChoiceIndex(int cls) => Array.IndexOf(Choices, cls);
|
||||
|
||||
public static string Label(int cls) =>
|
||||
cls >= 0 && cls < Names.Length ? Spaced(Names[cls]) : "class " + cls;
|
||||
}
|
||||
|
||||
internal static class SortRules
|
||||
{
|
||||
/// <summary>The Lua script's defaults: components, salvage, then gems, stones and keys together.</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),
|
||||
};
|
||||
|
||||
public static bool Matches(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;
|
||||
}
|
||||
|
||||
/// <summary>The first rule that matches (rules are tried in order), or null.</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];
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string Describe(SortRule r) =>
|
||||
r.Kind == RuleKind.Name ? $"name has \"{r.Text}\"" : ObjectClasses.Label(r.Class);
|
||||
}
|
||||
123
Plugins/RynthCore.Plugin.RynthSort/Ui/UiFormat.cs
Normal file
123
Plugins/RynthCore.Plugin.RynthSort/Ui/UiFormat.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Ui;
|
||||
|
||||
/// <summary>
|
||||
/// Display-list format 1 for the engine's script windows (RynthSuite
|
||||
/// Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2-4.3; the engine's DisplayListParser.cs is the source of
|
||||
/// truth). Little-endian. Only the ops RynthSort draws are listed.
|
||||
/// </summary>
|
||||
internal static class UiFormat
|
||||
{
|
||||
public const uint Magic = 0x31575352; // 'RSW1'
|
||||
public const ushort FormatVersion = 1;
|
||||
public const uint BodyUnchanged = 0xFFFFFFFF;
|
||||
public const int MaxString = 4096;
|
||||
public const int MaxStr8 = 128;
|
||||
public const int MaxOps = 1500; // engine limit per window
|
||||
public const int MaxBodyBytes = 64 * 1024; // engine limit per window
|
||||
public const byte OpHasBlock = 1;
|
||||
|
||||
// Ops
|
||||
public const byte OpEnd = 0x00;
|
||||
public const byte OpText = 0x01;
|
||||
public const byte OpTextColored = 0x02;
|
||||
public const byte OpTextWrapped = 0x03;
|
||||
public const byte OpTextDisabled = 0x04;
|
||||
public const byte OpBulletText = 0x05;
|
||||
public const byte OpSeparatorText = 0x06;
|
||||
public const byte OpSeparator = 0x10;
|
||||
public const byte OpSameLine = 0x11;
|
||||
public const byte OpSpacing = 0x13;
|
||||
public const byte OpDummy = 0x14;
|
||||
public const byte OpButton = 0x20;
|
||||
public const byte OpCheckbox = 0x21;
|
||||
public const byte OpSliderInt = 0x22;
|
||||
public const byte OpInputText = 0x24;
|
||||
public const byte OpCombo = 0x25;
|
||||
public const byte OpSelectable = 0x26;
|
||||
public const byte OpProgressBar = 0x27;
|
||||
public const byte OpImage = 0x28; // op level 2 (engines from 2026-09-30)
|
||||
public const byte OpPushID = 0x30;
|
||||
public const byte OpPopID = 0x31;
|
||||
public const byte OpPushStyleColor = 0x32;
|
||||
public const byte OpPopStyleColor = 0x33;
|
||||
public const byte OpSetItemTooltip = 0x38;
|
||||
public const byte OpChild = 0x40;
|
||||
public const byte OpCollapsingHeader = 0x41;
|
||||
|
||||
// Window flags
|
||||
public const uint FlagVisible = 1u << 0;
|
||||
public const uint FlagShowInBar = 1u << 1;
|
||||
public const uint FlagNoScrollbar = 1u << 5;
|
||||
|
||||
// Image icon kinds (op level 2)
|
||||
public const byte IconKindIcon = 0; // a 0x06 texture id
|
||||
public const byte IconKindObject = 1; // a live object's icon with underlay and overlay
|
||||
|
||||
// Selectable flags
|
||||
public const uint SelectableAllowDoubleClick = 4;
|
||||
|
||||
// Event types
|
||||
public const ushort EvClicked = 1;
|
||||
public const ushort EvBool = 2;
|
||||
public const ushort EvInt = 3;
|
||||
public const ushort EvText = 5;
|
||||
public const ushort EvOpen = 6;
|
||||
public const ushort EvVisibility = 8;
|
||||
public const ushort EvError = 10;
|
||||
|
||||
// ImGuiCol ids the engine accepts in PushStyleColor (ImGui.NET 1.91.6.1)
|
||||
public const int ColText = 0;
|
||||
public const int ColButton = 21;
|
||||
public const int ColButtonHovered = 22;
|
||||
public const int ColHeader = 24;
|
||||
|
||||
// InputText flags
|
||||
public const uint InputAutoSelectAll = 4096;
|
||||
|
||||
// CollapsingHeader flags
|
||||
public const uint TreeDefaultOpen = 32;
|
||||
|
||||
public static uint Fnv1a(ReadOnlySpan<byte> bytes, uint hash = 2166136261)
|
||||
{
|
||||
foreach (byte b in bytes)
|
||||
{
|
||||
hash ^= b;
|
||||
hash *= 16777619;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/// <summary>The length of <paramref name="s"/> cut to at most <paramref name="max"/> bytes without splitting a character.</summary>
|
||||
public static int CutUtf8(ReadOnlySpan<byte> s, int max)
|
||||
{
|
||||
if (s.Length <= max) return s.Length;
|
||||
int n = Math.Max(0, max);
|
||||
while (n > 0 && (s[n] & 0xC0) == 0x80) n--;
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>An ImGui U32 colour (0xAABBGGRR) from RGB bytes.</summary>
|
||||
public static uint Rgb(byte r, byte g, byte b, byte a = 255) =>
|
||||
((uint)a << 24) | ((uint)b << 16) | ((uint)g << 8) | r;
|
||||
}
|
||||
|
||||
/// <summary>Colours RynthSort uses (0xAABBGGRR).</summary>
|
||||
internal static class UiColors
|
||||
{
|
||||
public static readonly uint Green = UiFormat.Rgb(110, 210, 110);
|
||||
public static readonly uint Red = UiFormat.Rgb(225, 95, 95);
|
||||
public static readonly uint Yellow = UiFormat.Rgb(235, 205, 90);
|
||||
public static readonly uint Grey = UiFormat.Rgb(150, 150, 150);
|
||||
public static readonly uint Gold = UiFormat.Rgb(230, 180, 60);
|
||||
/// <summary>Upstream's "destruction" highlight: deep pink brightened by half (255, 30, 220).</summary>
|
||||
public static readonly uint Destruction = UiFormat.Rgb(255, 30, 220);
|
||||
public static readonly uint TabActive = UiFormat.Rgb(60, 110, 170);
|
||||
public static readonly uint TabActiveHover = UiFormat.Rgb(75, 130, 195);
|
||||
public static readonly uint OtherServer = UiFormat.Rgb(150, 185, 235);
|
||||
public static readonly uint Stale = UiFormat.Rgb(225, 150, 80);
|
||||
public static readonly uint White = UiFormat.Rgb(255, 255, 255);
|
||||
/// <summary>The Lua script's amber (paused, full packs): 1.0, 0.75, 0.25.</summary>
|
||||
public static readonly uint Amber = UiFormat.Rgb(255, 191, 64);
|
||||
}
|
||||
202
Plugins/RynthCore.Plugin.RynthSort/Ui/UiHost.cs
Normal file
202
Plugins/RynthCore.Plugin.RynthSort/Ui/UiHost.cs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Ui;
|
||||
|
||||
/// <summary>
|
||||
/// The plugin's side of the engine's script windows (API v71): polls the engine's events into
|
||||
/// the windows' handlers and submits the window set when something changed. Plugin pump thread
|
||||
/// only (inside the plugin's own tick), as the engine requires.
|
||||
/// </summary>
|
||||
internal sealed class UiHost
|
||||
{
|
||||
private readonly List<UiWindow> _windows = new();
|
||||
private readonly Dictionary<uint, UiWindow> _byHash = new();
|
||||
private byte[] _events = new byte[8192];
|
||||
private byte[] _submit = new byte[64 * 1024];
|
||||
private uint _lastSeq;
|
||||
private bool _submittedSomething;
|
||||
private long _retryAtMs;
|
||||
private long _lastErrorLogMs;
|
||||
|
||||
public Action<string>? Log;
|
||||
|
||||
public IReadOnlyList<UiWindow> Windows => _windows;
|
||||
|
||||
public UiWindow Add(UiWindow w)
|
||||
{
|
||||
_windows.Add(w);
|
||||
_byHash[w.Hash] = w;
|
||||
return w;
|
||||
}
|
||||
|
||||
/// <summary>Drains the engine's queued events into the windows' handlers.</summary>
|
||||
public void Poll(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasUi || !_submittedSomething) return;
|
||||
for (int round = 0; round < 8; round++)
|
||||
{
|
||||
int n = host.UiPollEvents(_events, out int remaining);
|
||||
if (n > 0) Apply(_events.AsSpan(0, n));
|
||||
if (remaining == 0) break;
|
||||
if (n == 0) Array.Resize(ref _events, _events.Length * 2); // one event didn't fit
|
||||
}
|
||||
}
|
||||
|
||||
private void Apply(ReadOnlySpan<byte> data)
|
||||
{
|
||||
int pos = 0;
|
||||
while (data.Length - pos >= 16)
|
||||
{
|
||||
ushort type = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]);
|
||||
int size = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]);
|
||||
if (size < 16 || size > data.Length - pos) break;
|
||||
uint seq = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 4)..]);
|
||||
uint window = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 8)..]);
|
||||
uint key = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 12)..]);
|
||||
ReadOnlySpan<byte> p = data.Slice(pos + 16, size - 16);
|
||||
pos += size;
|
||||
if (seq > _lastSeq) _lastSeq = seq;
|
||||
|
||||
_byHash.TryGetValue(window, out UiWindow? w);
|
||||
switch (type)
|
||||
{
|
||||
case UiFormat.EvClicked when w != null && p.Length >= 2:
|
||||
int count = BinaryPrimitives.ReadUInt16LittleEndian(p);
|
||||
for (int i = 0; i < Math.Min(count, 4); i++) w.Dispatch(key, new UiEvent(type));
|
||||
break;
|
||||
case UiFormat.EvBool when w != null && p.Length >= 1:
|
||||
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
|
||||
break;
|
||||
case UiFormat.EvInt when w != null && p.Length >= 4:
|
||||
w.Dispatch(key, new UiEvent(type, i: BinaryPrimitives.ReadInt32LittleEndian(p)));
|
||||
break;
|
||||
case UiFormat.EvText when w != null && p.Length >= 3:
|
||||
{
|
||||
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p[1..]), p.Length - 3);
|
||||
w.Dispatch(key, new UiEvent(type, text: Encoding.UTF8.GetString(p.Slice(3, n)), submitted: p[0] != 0));
|
||||
break;
|
||||
}
|
||||
case UiFormat.EvOpen when w != null && p.Length >= 1:
|
||||
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
|
||||
break;
|
||||
case UiFormat.EvVisibility when w != null && p.Length >= 1:
|
||||
// The player closed it (X) or opened it (bar menu / command): theirs wins.
|
||||
w.Visible = p[0] != 0;
|
||||
w.NeedsPass = true;
|
||||
break;
|
||||
case UiFormat.EvError when p.Length >= 2:
|
||||
{
|
||||
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p), p.Length - 2);
|
||||
Log?.Invoke("[RynthSort] window error: " + Encoding.UTF8.GetString(p.Slice(2, n)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sends the window set when any window's list or header changed.</summary>
|
||||
public void Submit(RynthCoreHost host, long nowMs)
|
||||
{
|
||||
if (!host.HasUi || nowMs < _retryAtMs) return;
|
||||
bool changed = !_submittedSomething && _windows.Count > 0;
|
||||
foreach (UiWindow w in _windows)
|
||||
if (w.BodyDirty || w.HeaderDirty) { changed = true; break; }
|
||||
if (!changed) return;
|
||||
|
||||
int pos = Write();
|
||||
int rc = host.UiSubmit(_submit.AsSpan(0, pos));
|
||||
if (rc == 0)
|
||||
{
|
||||
foreach (UiWindow w in _windows) w.MarkSubmitted(w.BodyDirty);
|
||||
_submittedSomething = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Nothing was applied; the engine keeps the previous lists. Try again in a second.
|
||||
_retryAtMs = nowMs + 1000;
|
||||
if (nowMs - _lastErrorLogMs > 10_000)
|
||||
{
|
||||
_lastErrorLogMs = nowMs;
|
||||
Log?.Invoke($"[RynthSort] the engine refused the window list ({rc}).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes every window from the engine (logout, shutdown). Their placement is kept by the engine.</summary>
|
||||
public void SubmitEmpty(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasUi || !_submittedSomething) return;
|
||||
Span<byte> b = stackalloc byte[16];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], 16);
|
||||
if (host.UiSubmit(b) == 0)
|
||||
{
|
||||
_submittedSomething = false;
|
||||
foreach (UiWindow w in _windows) w.ForgetSubmitted();
|
||||
}
|
||||
}
|
||||
|
||||
private int Write()
|
||||
{
|
||||
int size = 16;
|
||||
foreach (UiWindow w in _windows) size += 2 * (1 + UiFormat.MaxStr8) + 4 + 32 + 8 + (w.BodyDirty ? w.Body.Length : 0);
|
||||
if (_submit.Length < size) _submit = new byte[Math.Max(size, _submit.Length * 2)];
|
||||
Span<byte> b = _submit;
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], (ushort)_windows.Count);
|
||||
// Every event polled so far has been applied (handlers run as they arrive).
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
|
||||
int pos = 16;
|
||||
foreach (UiWindow w in _windows)
|
||||
{
|
||||
pos = Str8(b, pos, w.KeyUtf8);
|
||||
pos = Str8(b, pos, Encoding.UTF8.GetBytes(w.Title ?? string.Empty));
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.Flags); pos += 4;
|
||||
pos = F32(b, pos, w.DefaultWidth);
|
||||
pos = F32(b, pos, w.DefaultHeight);
|
||||
pos = F32(b, pos, w.MinWidth);
|
||||
pos = F32(b, pos, w.MinHeight);
|
||||
pos = F32(b, pos, float.NaN); // RequestSize: none
|
||||
pos = F32(b, pos, float.NaN);
|
||||
pos = F32(b, pos, float.NaN); // RequestPos: none
|
||||
pos = F32(b, pos, float.NaN);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.ListSeq); pos += 4;
|
||||
if (w.BodyDirty)
|
||||
{
|
||||
ReadOnlySpan<byte> body = w.Body;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], (uint)body.Length); pos += 4;
|
||||
body.CopyTo(b[pos..]);
|
||||
pos += body.Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], UiFormat.BodyUnchanged); pos += 4;
|
||||
}
|
||||
}
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], (uint)pos);
|
||||
return pos;
|
||||
}
|
||||
|
||||
private static int Str8(Span<byte> b, int pos, ReadOnlySpan<byte> s)
|
||||
{
|
||||
int n = UiFormat.CutUtf8(s, UiFormat.MaxStr8);
|
||||
b[pos] = (byte)n;
|
||||
s[..n].CopyTo(b[(pos + 1)..]);
|
||||
return pos + 1 + n;
|
||||
}
|
||||
|
||||
private static int F32(Span<byte> b, int pos, float v)
|
||||
{
|
||||
BinaryPrimitives.WriteSingleLittleEndian(b[pos..], v);
|
||||
return pos + 4;
|
||||
}
|
||||
}
|
||||
490
Plugins/RynthCore.Plugin.RynthSort/Ui/UiWindow.cs
Normal file
490
Plugins/RynthCore.Plugin.RynthSort/Ui/UiWindow.cs
Normal file
|
|
@ -0,0 +1,490 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Ui;
|
||||
|
||||
/// <summary>One input from the engine for a widget (a click, a new value, an open state).</summary>
|
||||
internal readonly struct UiEvent
|
||||
{
|
||||
public readonly ushort Type;
|
||||
public readonly bool Bool;
|
||||
public readonly int Int;
|
||||
public readonly string Text;
|
||||
public readonly bool Submitted;
|
||||
|
||||
public UiEvent(ushort type, bool b = false, int i = 0, string? text = null, bool submitted = false)
|
||||
{
|
||||
Type = type;
|
||||
Bool = b;
|
||||
Int = i;
|
||||
Text = text ?? string.Empty;
|
||||
Submitted = submitted;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One script window (engine API v71) and its recorder. A render pass records ImGui-style calls
|
||||
/// into a display list; every widget's handler (click, value change) is kept by its widget key
|
||||
/// until the next pass, so an event from the engine runs the code that drew that widget.
|
||||
///
|
||||
/// Widget keys are FNV-1a(id, window hash): RynthSort names every widget itself, so it needs
|
||||
/// no ID stack. ImGui sees "label###id": its ID comes from the id alone, so labels can change.
|
||||
/// The engine echoes the key in events and keys its per-widget local values by it.
|
||||
/// </summary>
|
||||
internal sealed class UiWindow
|
||||
{
|
||||
public readonly string Key;
|
||||
public readonly byte[] KeyUtf8;
|
||||
public readonly uint Hash;
|
||||
|
||||
public string Title;
|
||||
public bool Visible;
|
||||
public bool ShowInBar = 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>
|
||||
public bool NeedsPass = true;
|
||||
public long NextPassMs;
|
||||
|
||||
// The list as recorded by the last pass, and what the engine last accepted.
|
||||
private byte[] _body = new byte[16 * 1024];
|
||||
private int _len;
|
||||
private int _ops;
|
||||
private bool _cut;
|
||||
private byte[] _sentBody = Array.Empty<byte>();
|
||||
private int _sentLen = -1;
|
||||
public uint ListSeq { get; private set; }
|
||||
internal bool BodyDirty;
|
||||
|
||||
// Header as last accepted by the engine.
|
||||
private string? _sentTitle;
|
||||
private uint _sentFlags;
|
||||
private float _sentDw = float.NaN, _sentDh, _sentMw, _sentMh;
|
||||
|
||||
private Dictionary<uint, Action<UiEvent>> _handlers = new();
|
||||
private Dictionary<uint, Action<UiEvent>> _next = new();
|
||||
private readonly Dictionary<uint, bool> _openStates = new();
|
||||
|
||||
// Child blocks: where each open block's u32 length sits, or -1 when the block was dropped.
|
||||
private readonly int[] _blocks = new int[16];
|
||||
private int _blockDepth;
|
||||
private byte[] _tmp = new byte[512];
|
||||
|
||||
public UiWindow(string key, string title)
|
||||
{
|
||||
Key = key;
|
||||
KeyUtf8 = Encoding.UTF8.GetBytes(key);
|
||||
Hash = UiFormat.Fnv1a(KeyUtf8);
|
||||
Title = title;
|
||||
}
|
||||
|
||||
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0);
|
||||
|
||||
public bool HeaderDirty =>
|
||||
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight
|
||||
|| _sentMw != MinWidth || _sentMh != MinHeight;
|
||||
|
||||
public ReadOnlySpan<byte> Body => _body.AsSpan(0, _len);
|
||||
|
||||
// ── Pass ────────────────────────────────────────────────────────────────
|
||||
|
||||
public void Begin()
|
||||
{
|
||||
_len = 0;
|
||||
_ops = 0;
|
||||
_cut = false;
|
||||
_blockDepth = 0;
|
||||
_next.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Ends the pass: closes open blocks, writes End, and notes whether the list changed.</summary>
|
||||
public void End()
|
||||
{
|
||||
while (_blockDepth > 0) EndChild();
|
||||
if (_cut)
|
||||
{
|
||||
// Room was kept for this line (see Room).
|
||||
int p = BeginOp(UiFormat.OpTextDisabled);
|
||||
Str("(more than fits in one window; narrow the list)");
|
||||
EndOp(p);
|
||||
}
|
||||
Ensure(4);
|
||||
_body[_len++] = UiFormat.OpEnd;
|
||||
_body[_len++] = 0;
|
||||
_body[_len++] = 0;
|
||||
_body[_len++] = 0;
|
||||
|
||||
(_handlers, _next) = (_next, _handlers);
|
||||
bool differs = _sentLen != _len || !_body.AsSpan(0, _len).SequenceEqual(_sentBody.AsSpan(0, _sentLen));
|
||||
if (differs && !BodyDirty) ListSeq++;
|
||||
BodyDirty = differs;
|
||||
}
|
||||
|
||||
/// <summary>The engine accepted the last submit: remember what it now has.</summary>
|
||||
internal void MarkSubmitted(bool bodySent)
|
||||
{
|
||||
if (bodySent)
|
||||
{
|
||||
if (_sentBody.Length < _len) _sentBody = new byte[_body.Length];
|
||||
_body.AsSpan(0, _len).CopyTo(_sentBody);
|
||||
_sentLen = _len;
|
||||
BodyDirty = false;
|
||||
}
|
||||
_sentTitle = Title;
|
||||
_sentFlags = Flags;
|
||||
_sentDw = DefaultWidth; _sentDh = DefaultHeight; _sentMw = MinWidth; _sentMh = MinHeight;
|
||||
}
|
||||
|
||||
/// <summary>The engine dropped every window (logout, empty submit): send everything again next time.</summary>
|
||||
internal void ForgetSubmitted()
|
||||
{
|
||||
_sentLen = -1;
|
||||
_sentTitle = null;
|
||||
BodyDirty = _len > 0;
|
||||
}
|
||||
|
||||
internal void Dispatch(uint widgetKey, in UiEvent e)
|
||||
{
|
||||
if (_handlers.TryGetValue(widgetKey, out Action<UiEvent>? h))
|
||||
h(e);
|
||||
NeedsPass = true;
|
||||
}
|
||||
|
||||
// ── Widgets ─────────────────────────────────────────────────────────────
|
||||
|
||||
public uint KeyOf(string id)
|
||||
{
|
||||
int max = Encoding.UTF8.GetMaxByteCount(id.Length);
|
||||
if (_tmp.Length < max) _tmp = new byte[Math.Max(max, _tmp.Length * 2)];
|
||||
int n = Encoding.UTF8.GetBytes(id, _tmp);
|
||||
return UiFormat.Fnv1a(_tmp.AsSpan(0, n), Hash);
|
||||
}
|
||||
|
||||
public void Text(string text) => WriteText(UiFormat.OpText, text);
|
||||
public void TextDisabled(string text) => WriteText(UiFormat.OpTextDisabled, text);
|
||||
public void TextWrapped(string text) => WriteText(UiFormat.OpTextWrapped, text);
|
||||
public void BulletText(string text) => WriteText(UiFormat.OpBulletText, text);
|
||||
public void SeparatorText(string text) => WriteText(UiFormat.OpSeparatorText, text);
|
||||
|
||||
public void TextColored(uint abgr, string text)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpTextColored);
|
||||
U32(abgr);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Separator()
|
||||
{
|
||||
if (!Room()) return;
|
||||
EndOp(BeginOp(UiFormat.OpSeparator));
|
||||
}
|
||||
|
||||
public void Spacing()
|
||||
{
|
||||
if (!Room()) return;
|
||||
EndOp(BeginOp(UiFormat.OpSpacing));
|
||||
}
|
||||
|
||||
/// <summary>Next item on the same line, <paramref name="x"/> logical units from the content start (0 = right after).</summary>
|
||||
public void SameLine(float x = 0f, float spacing = -1f)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpSameLine);
|
||||
F32(x);
|
||||
F32(spacing);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Dummy(float w, float h)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpDummy);
|
||||
F32(w);
|
||||
F32(h);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpButton);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
U8(small ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
|
||||
}
|
||||
|
||||
public void SmallButton(string label, string id, Action onClick) => Button(label, id, onClick, small: true);
|
||||
|
||||
/// <summary>A button drawn highlighted when <paramref name="active"/> (tabs, toggles).</summary>
|
||||
public void ToggleButton(string label, string id, bool active, Action onClick, bool small = false)
|
||||
{
|
||||
if (active)
|
||||
{
|
||||
PushStyleColor(UiFormat.ColButton, UiColors.TabActive);
|
||||
PushStyleColor(UiFormat.ColButtonHovered, UiColors.TabActiveHover);
|
||||
}
|
||||
Button(label, id, onClick, small: small);
|
||||
if (active) PopStyleColor(2);
|
||||
}
|
||||
|
||||
public void Checkbox(string label, string id, bool value, Action<bool> set)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpCheckbox);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U8(value ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvBool) set(e.Bool); };
|
||||
}
|
||||
|
||||
/// <summary>An integer slider from <paramref name="min"/> to <paramref name="max"/> (clamped by the engine).</summary>
|
||||
public void SliderInt(string label, string id, int value, int min, int max, Action<int> set, string format = "%d")
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpSliderInt);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
I32(value);
|
||||
I32(min);
|
||||
I32(max);
|
||||
Str(format);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(Math.Clamp(e.Int, min, max)); };
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
if (!Room()) return;
|
||||
maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString);
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpInputText);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
Str(value ?? string.Empty, maxLen);
|
||||
U16((ushort)maxLen);
|
||||
U32(flags);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text); };
|
||||
}
|
||||
|
||||
public void Combo(string label, string id, int index, IReadOnlyList<string> items, Action<int> set)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int count = Math.Min(items.Count, 512);
|
||||
int p = BeginOp(UiFormat.OpCombo);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
I32(index);
|
||||
U16((ushort)count);
|
||||
for (int i = 0; i < count; i++) Str(items[i]);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(e.Int); };
|
||||
}
|
||||
|
||||
public void Selectable(string label, string id, bool selected, Action onClick, float w = 0f, float h = 0f)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpSelectable);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U8(selected ? (byte)1 : (byte)0);
|
||||
U32(0);
|
||||
F32(w);
|
||||
F32(h);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
|
||||
}
|
||||
|
||||
public void ProgressBar(float fraction, float w, float h, string overlay)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpProgressBar);
|
||||
F32(float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f);
|
||||
F32(w);
|
||||
F32(h);
|
||||
Str(overlay ?? string.Empty);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An icon (op level 2): <paramref name="kind"/> <see cref="UiFormat.IconKindIcon"/> = a 0x06
|
||||
/// texture id, <see cref="UiFormat.IconKindObject"/> = a live object. Engines without op level
|
||||
/// 2 skip it (the caller checks first so the layout doesn't shift).
|
||||
/// </summary>
|
||||
public void Image(byte kind, uint id, float w, float h)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpImage);
|
||||
U8(kind);
|
||||
U32(id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
F32(0f); F32(0f); // uv0
|
||||
F32(1f); F32(1f); // uv1
|
||||
U32(0xFFFFFFFFu); // tint: as is
|
||||
U32(0u); // border: none
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Tooltip for the item just drawn.</summary>
|
||||
public void Tooltip(string text)
|
||||
{
|
||||
if (!Room() || string.IsNullOrEmpty(text)) return;
|
||||
int p = BeginOp(UiFormat.OpSetItemTooltip);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void PushStyleColor(int colId, uint abgr)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpPushStyleColor);
|
||||
U16((ushort)colId);
|
||||
U32(abgr);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Pops are dropped when the list is cut short; the engine pops leftovers at the scope's end.</summary>
|
||||
public void PopStyleColor(int count = 1)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpPopStyleColor);
|
||||
U8((byte)Math.Clamp(count, 1, 255));
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A collapsing header; returns whether to record its contents. The open state is the
|
||||
/// player's (kept from the engine's Open events), so a header stays as they left it.
|
||||
/// </summary>
|
||||
public bool CollapsingHeader(string label, string id, bool defaultOpen = false)
|
||||
{
|
||||
uint key = KeyOf(id);
|
||||
bool open = _openStates.TryGetValue(key, out bool o) ? o : defaultOpen;
|
||||
if (!Room()) return false;
|
||||
int p = BeginOp(UiFormat.OpCollapsingHeader);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U32(defaultOpen ? UiFormat.TreeDefaultOpen : 0);
|
||||
U8(open ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvOpen) _openStates[key] = e.Bool; };
|
||||
return open;
|
||||
}
|
||||
|
||||
/// <summary>A scrolling region; h 0 = fill the rest of the window. Must be closed with <see cref="EndChild"/>.</summary>
|
||||
public void BeginChild(string id, float w = 0f, float h = 0f, bool border = true)
|
||||
{
|
||||
if (_blockDepth >= _blocks.Length) throw new InvalidOperationException("child regions nested too deep");
|
||||
if (!Room())
|
||||
{
|
||||
_blocks[_blockDepth++] = -1;
|
||||
return;
|
||||
}
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpChild, UiFormat.OpHasBlock);
|
||||
U32(key);
|
||||
Str(id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
U8(border ? (byte)1 : (byte)0);
|
||||
U32(0);
|
||||
EndOp(p);
|
||||
_blocks[_blockDepth++] = _len;
|
||||
U32(0); // BlockLength, patched by EndChild
|
||||
}
|
||||
|
||||
public void EndChild()
|
||||
{
|
||||
if (_blockDepth == 0) return;
|
||||
int at = _blocks[--_blockDepth];
|
||||
if (at < 0) return;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(at), (uint)(_len - (at + 4)));
|
||||
}
|
||||
|
||||
// ── Writing ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Whether another op fits. Room is kept for the closing "list cut short" line and the End
|
||||
/// op, so the list never goes over the engine's limits (it refuses an over-limit list whole).
|
||||
/// </summary>
|
||||
private bool Room()
|
||||
{
|
||||
if (_cut) return false;
|
||||
if (_ops < UiFormat.MaxOps - 8 && _len < UiFormat.MaxBodyBytes - 4096) return true;
|
||||
_cut = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void WriteText(byte code, string text)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(code);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
private int BeginOp(byte code, byte opFlags = 0)
|
||||
{
|
||||
_ops++;
|
||||
Ensure(4);
|
||||
_body[_len++] = code;
|
||||
_body[_len++] = opFlags;
|
||||
_len += 2; // PayloadLength, patched by EndOp
|
||||
return _len;
|
||||
}
|
||||
|
||||
private void EndOp(int payloadStart)
|
||||
{
|
||||
int length = _len - payloadStart;
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(payloadStart - 2), (ushort)Math.Min(length, ushort.MaxValue));
|
||||
}
|
||||
|
||||
private void Ensure(int extra)
|
||||
{
|
||||
if (_len + extra <= _body.Length) return;
|
||||
int size = _body.Length;
|
||||
while (size < _len + extra) size *= 2;
|
||||
Array.Resize(ref _body, size);
|
||||
}
|
||||
|
||||
private void U8(byte v) { Ensure(1); _body[_len++] = v; }
|
||||
private void U16(ushort v) { Ensure(2); BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), v); _len += 2; }
|
||||
private void U32(uint v) { Ensure(4); BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
|
||||
private void I32(int v) { Ensure(4); BinaryPrimitives.WriteInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
|
||||
|
||||
private void F32(float v)
|
||||
{
|
||||
Ensure(4);
|
||||
BinaryPrimitives.WriteSingleLittleEndian(_body.AsSpan(_len), float.IsFinite(v) ? v : 0f);
|
||||
_len += 4;
|
||||
}
|
||||
|
||||
/// <summary>str: u16 length + UTF-8, cut to <paramref name="maxBytes"/> on a character boundary.</summary>
|
||||
private void Str(string s, int maxBytes = UiFormat.MaxString)
|
||||
{
|
||||
s ??= string.Empty;
|
||||
ReadOnlySpan<char> src = s.Length > maxBytes ? s.AsSpan(0, maxBytes) : s.AsSpan();
|
||||
Ensure(2 + Encoding.UTF8.GetMaxByteCount(src.Length));
|
||||
int at = _len + 2;
|
||||
Span<byte> dst = _body.AsSpan(at);
|
||||
int n = UiFormat.CutUtf8(dst[..Encoding.UTF8.GetBytes(src, dst)], maxBytes);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), (ushort)n);
|
||||
_len = at + n;
|
||||
}
|
||||
}
|
||||
197
Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs
Normal file
197
Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
using RynthCore.Plugin.RynthSort.Ui;
|
||||
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.
|
||||
/// </summary>
|
||||
internal sealed class SortPanel
|
||||
{
|
||||
private static readonly string[] Kinds = { "Class", "Name has" };
|
||||
|
||||
private readonly SortController _c;
|
||||
private readonly Action _save;
|
||||
private int _selected = -1;
|
||||
|
||||
/// <summary>Extra warnings the plugin knows about (the Lua script set to start too).</summary>
|
||||
public Func<IReadOnlyList<string>> Warnings = () => Array.Empty<string>();
|
||||
/// <summary>The character (blank before login).</summary>
|
||||
public Func<string> Character = () => string.Empty;
|
||||
|
||||
public SortPanel(SortController c, Action save)
|
||||
{
|
||||
_c = c;
|
||||
_save = save;
|
||||
}
|
||||
|
||||
public int Selected => _selected;
|
||||
|
||||
public void Draw(UiWindow w)
|
||||
{
|
||||
if (Character().Length == 0)
|
||||
{
|
||||
w.TextDisabled("Log in to sort your packs.");
|
||||
return;
|
||||
}
|
||||
SortSettings s = _c.Data.Settings;
|
||||
List<SortRule> rules = _c.Data.Rules;
|
||||
|
||||
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.SameLine();
|
||||
w.TextColored(_c.Paused ? UiColors.Amber : UiColors.Grey, _c.Status);
|
||||
if (_c.Planner.View.Waiting > 0)
|
||||
{
|
||||
w.SameLine();
|
||||
w.TextDisabled($"({_c.Planner.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.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.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;
|
||||
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);
|
||||
|
||||
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.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)");
|
||||
}
|
||||
|
||||
if (_c.Log.Count > 0)
|
||||
{
|
||||
w.Separator();
|
||||
foreach (string line in _c.Log) w.TextDisabled(line);
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawRules(UiWindow w, List<SortRule> rules, SortView view)
|
||||
{
|
||||
if (_selected >= rules.Count) _selected = rules.Count - 1;
|
||||
for (int i = 0; i < rules.Count; i++)
|
||||
{
|
||||
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);
|
||||
}
|
||||
if (rules.Count == 0) w.TextDisabled("No rules: nothing moves.");
|
||||
|
||||
w.Button("Add rule", "rule.add", () =>
|
||||
{
|
||||
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;
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
SortRule rule = rules[sel];
|
||||
w.SeparatorText($"Rule {sel + 1}");
|
||||
w.Combo("Match", "rule.kind", rule.Kind == RuleKind.Name ? 1 : 0, Kinds, v =>
|
||||
{
|
||||
rule.Kind = v == 1 ? RuleKind.Name : RuleKind.Class;
|
||||
_save();
|
||||
});
|
||||
if (rule.Kind == RuleKind.Name)
|
||||
{
|
||||
w.InputText("Name has", "rule.text", rule.Text, 64, v => { rule.Text = v; _save(); });
|
||||
w.Tooltip("Part of the item's name, any case");
|
||||
}
|
||||
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();
|
||||
});
|
||||
}
|
||||
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>
|
||||
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})");
|
||||
}
|
||||
else list.Add($"Pack {i} (none)");
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue