diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 06d1fa8..8aba138 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -59,6 +59,7 @@ internal static class AcMainThreadQueue SplitStackInternal, MergeStackInternal, GiveObjectTo, + PutItemInContainer, // CommandInterpreter movement marshalled 2026-06-12: SetAutoRun / // TurnToHeading / StopCompletely were the last direct off-thread AC // mutators (dump-proven: a SetAutoRun executed 15s after a main thread @@ -421,6 +422,9 @@ internal static class AcMainThreadQueue public static bool EnqueueGiveObjectTo(uint objectId, uint targetId, int amount) => Enqueue(ActionKind.GiveObjectTo, objectId, targetId, unchecked((uint)amount)); + public static bool EnqueuePutItemInContainer(uint objectId, uint containerId, int slot) => + Enqueue(ActionKind.PutItemInContainer, objectId, containerId, unchecked((uint)slot)); + public static bool EnqueueWieldItem(uint objectId, uint equipMask) => Enqueue(ActionKind.WieldItem, objectId, equipMask, 0); @@ -642,6 +646,9 @@ internal static class AcMainThreadQueue case ActionKind.GiveObjectTo: ClientHelperHooks.GiveObjectTo(e.A, e.B, unchecked((int)e.C)); break; + case ActionKind.PutItemInContainer: + ClientHelperHooks.PutItemInContainerAt(e.A, e.B, unchecked((int)e.C)); + break; case ActionKind.WieldItem: ClientHelperHooks.WieldItem(e.A, e.B); break; diff --git a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs index 1ecbbb3..ddea408 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs @@ -351,7 +351,7 @@ internal static class ChatCallbackHooks [MethodImpl(MethodImplOptions.NoInlining)] private static bool EatOwnReply(string line) { - try { return MasteryFeed.OnIncomingLine(line); } + try { return MasteryFeed.OnIncomingLine(line) || VaultFeed.OnIncomingLine(line); } catch { return false; } } diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index e034e41..a0fa357 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -75,6 +75,16 @@ internal static class ClientHelperHooks [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate byte EventGiveObjectRequestDelegate(uint targetId, uint objectId, int amount); + // CM_Inventory::Event_PutItemInContainer(item, container, placement) @0x006ACC80 - the 0x19 + // PutItemInContainer game action, the packet only: item, container, then the SLOT in that + // container (what a drop on a cell of the pack grid asks for; retail and OpenAC both send it). + // MoveItemInternal (the native move) always lands an item in the first empty slot. Same + // template as Event_GiveObjectRequest (0x10 after the first inner call, arguments written in + // wire order) ending in the 0x19 opcode. Unique (1 match @0x006ACC80) in both acclient copies, + // checked 2026-10-09 by deriving the pattern from the give pattern. + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate byte EventPutItemInContainerDelegate(uint itemId, uint containerId, int placement); + // CM_Inventory::Event_GetAndWieldItem(ulong itemId, ulong equipMask) — the 0x001A // GetAndWieldItem game action ("wield this item at these locations"). Same generated // shape as its two siblings above (cdecl, returns bool), opcode immediate 0x1A. @@ -142,6 +152,7 @@ internal static class ClientHelperHooks private const int EventStackableMergeVa = 0x006ACDD0; // CM_Inventory::Event_GiveObjectRequest — public give-to-NPC API (FALLBACK only; pattern-scanned). private const int EventGiveObjectRequestVa = 0x006ACA60; + private const int EventPutItemInContainerVa = 0x006ACC80; // CM_Inventory::Event_GetAndWieldItem — wield into a chosen slot (FALLBACK only; pattern-scanned). private const int EventGetAndWieldItemVa = 0x006AC950; // CM_Inventory::Event_DropItem — drop an item on the ground (FALLBACK only; pattern-scanned). @@ -169,6 +180,7 @@ internal static class ClientHelperHooks private static MoveItemInternalDelegate? _moveItemInternal; private static EventStackableMergeDelegate? _eventStackableMerge; private static EventGiveObjectRequestDelegate? _eventGiveObjectRequest; + private static EventPutItemInContainerDelegate? _eventPutItemInContainer; private static EventGetAndWieldItemDelegate? _eventGetAndWieldItem; private static EventDropItemDelegate? _eventDropItem; private static EventNoLongerViewingContentsDelegate? _eventNoLongerViewingContents; @@ -197,6 +209,7 @@ internal static class ClientHelperHooks public static bool HasSplitStackInternal => _moveItemInternal != null; public static bool HasMergeStackInternal => _eventStackableMerge != null; public static bool HasGiveObjectTo => _eventGiveObjectRequest != null; + public static bool HasPutItemInContainer => _eventPutItemInContainer != null; public static bool HasWieldItem => _eventGetAndWieldItem != null; public static bool HasDropItem => _eventDropItem != null; public static bool HasCloseContainer => _eventNoLongerViewingContents != null; @@ -227,6 +240,7 @@ internal static class ClientHelperHooks // so do NOT trim it. Generated + verified unique (1 match @0x006ACA60) via // pe_pattern.py GEN against both acclient copies. private static readonly byte?[] PatEventGiveObjectRequest = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xCD ]; + private static readonly byte?[] PatEventPutItemInContainer = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x19 ]; // CM_Inventory::Event_GetAndWieldItem @0x006AC950. Same template as the two above but with // one fewer argument (so +0x0C, not +0x10, after the first inner call) and the 0x1A opcode // as the last byte. Generated + verified unique (1 match @0x006AC950) via pe_pattern.py GEN @@ -302,6 +316,7 @@ internal static class ClientHelperHooks _moveItemInternal = Bind(text, "ClientHelper.MoveItemInternal", PatMoveItemInternal, MoveItemInternalVa); _eventStackableMerge = Bind(text, "ClientHelper.Event_StackableMerge", PatEventStackableMerge, EventStackableMergeVa); _eventGiveObjectRequest = Bind(text, "ClientHelper.Event_GiveObjectRequest", PatEventGiveObjectRequest, EventGiveObjectRequestVa); + _eventPutItemInContainer = Bind(text, "ClientHelper.Event_PutItemInContainer", PatEventPutItemInContainer, EventPutItemInContainerVa); _eventGetAndWieldItem = Bind(text, "ClientHelper.Event_GetAndWieldItem", PatEventGetAndWieldItem, EventGetAndWieldItemVa); _eventDropItem = Bind(text, "ClientHelper.Event_DropItem", PatEventDropItem, EventDropItemVa); _eventNoLongerViewingContents = Bind(text, "ClientHelper.Event_NoLongerViewingContents", PatEventNoLongerViewingContents, EventNoLongerViewingContentsVa); @@ -690,6 +705,36 @@ internal static class ClientHelperHooks } } + /// + /// Put an item into a container at a given slot (CM_Inventory::Event_PutItemInContainer, the + /// 0x19 game action): the drop on a cell of the pack grid, or a reorder inside one pack. The + /// server decides (full pack, wrong kind of item) and answers as for any move; this is the + /// packet only, so unlike it never walks the client's slot + /// table. is the index in the container (the server clamps it). + /// + public static bool PutItemInContainerAt(uint objectId, uint containerId, int slot) + { + if (!MainThreadGuard.IsOnMainThread()) + return AcMainThreadQueue.EnqueuePutItemInContainer(objectId, containerId, slot); + + if (_eventPutItemInContainer == null) return false; + if (!IsValidObjectId(objectId)) return false; + if (!IsValidContainerId(containerId)) return false; + if (slot < 0) return false; + + try + { + byte rv = _eventPutItemInContainer(objectId, containerId, slot); + RynthLog.Verbose($"Compat: Event_PutItemInContainer item=0x{objectId:X8} -> container=0x{containerId:X8} slot={slot} rv={rv}"); + return rv != 0; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: Event_PutItemInContainer threw - {ex.Message}"); + return false; + } + } + /// /// Give an item to an NPC (or another player) via the canonical public API /// CM_Inventory::Event_GiveObjectRequest (cdecl) at 0x006ACA60 — the F7B1 give @@ -1228,6 +1273,7 @@ internal static class ClientHelperHooks _moveItemInternal = null; _eventStackableMerge = null; _eventGiveObjectRequest = null; + _eventPutItemInContainer = null; _eventGetAndWieldItem = null; _eventDropItem = null; _eventNoLongerViewingContents = null; diff --git a/src/RynthCore.Engine/Compatibility/InventoryModel.cs b/src/RynthCore.Engine/Compatibility/InventoryModel.cs index 2b353cb..0fcf53a 100644 --- a/src/RynthCore.Engine/Compatibility/InventoryModel.cs +++ b/src/RynthCore.Engine/Compatibility/InventoryModel.cs @@ -185,6 +185,8 @@ internal sealed class InventoryRequest public uint TargetId; /// Split: how many to split off. Give: 0 = the whole stack. public int Amount; + /// Move: the slot in the target pack the item should end at (the server's order), or -1 for the first empty one. + public int Slot = -1; public string ItemName = string.Empty; public string TargetName = string.Empty; } @@ -574,7 +576,12 @@ internal static class InventoryModel if (burden < 0) { view.BurdenText = "?"; view.BurdenTip = "Burden not known yet."; } else if (capacity > 0) { - int pct = (int)Math.Round(100.0 * burden / capacity); + // Retail's own arithmetic (OpenAC BurdenMath.LoadToPercent, checked against the retail panel): the + // load ratio in single precision, the meter's fill (0-300%), and the percent shown is that rounded + // DOWN. Rounding to nearest showed 36 where retail showed 35. + float load = (float)burden / capacity; + float fill = Math.Clamp(load / 3f, 0f, 1f); + int pct = (int)MathF.Floor(fill * 300f); view.BurdenText = pct.ToString(CultureInfo.InvariantCulture) + "%"; view.BurdenTip = $"Burden {burden:N0} of {capacity:N0} ({pct}%). Over 100% you move slower; 300% is the limit."; } @@ -821,10 +828,14 @@ internal static class InventoryModel Finish("That pack is gone.", false, now); return; } - if (f.Container == r.TargetId && !worn) { Finish($"{r.ItemName} is already there.", true, now); return; } + if (f.Container == r.TargetId && !worn && r.Slot < 0) { Finish($"{r.ItemName} is already there.", true, now); return; } int amount = Math.Max(1, (int)f.StackSize); - // The helper refuses (false) a full pack of the player's own before sending. - ok = ClientHelperHooks.MoveItemInternal(r.ItemId, r.TargetId, 0, amount); + // A slot (a drop on a cell of the grid, or a reorder) goes out as the packet itself; the + // server answers a full pack or a wrong kind of item. Without one the helper picks the + // first empty slot, and refuses (false) a full pack of the player's own before sending. + ok = r.Slot >= 0 && ClientHelperHooks.HasPutItemInContainer + ? ClientHelperHooks.PutItemInContainerAt(r.ItemId, r.TargetId, r.Slot) + : ClientHelperHooks.MoveItemInternal(r.ItemId, r.TargetId, 0, amount); if (!ok) { Finish($"{r.TargetName} is full, or the move isn't possible.", false, now); return; } break; } diff --git a/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs index c994566..75464d9 100644 --- a/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs +++ b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs @@ -115,5 +115,7 @@ internal static class MainThreadSnapshots // Aelrynth skill mastery: the /mastery-data request after login, on panel open // and after a raise (only on Aelrynth; a few compares when nothing is wanted). try { MasteryFeed.MainThreadTick(playerLive); } catch { } + // Aelrynth account vault (the Inventory panel's Vault view): reads on request only. + try { VaultFeed.MainThreadTick(playerLive); } catch { } } } diff --git a/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs b/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs index 2bbec6a..b9500fb 100644 --- a/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs +++ b/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs @@ -45,6 +45,10 @@ internal static class RawPacketHooks public static void Initialize() { + // The engine's own readers of the server stream (the Inventory panel's item order) need the + // datagrams from here on, not from the first frame pump: see ServerMessageStream.EnableEarly. + Net.ServerMessageStream.EnableEarly(); + if (Plugins.EngineSettings.FlightRecorder) { try { InstallSendTo(); } diff --git a/src/RynthCore.Engine/Compatibility/VaultFeed.cs b/src/RynthCore.Engine/Compatibility/VaultFeed.cs new file mode 100644 index 0000000..0f3925f --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/VaultFeed.cs @@ -0,0 +1,293 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/VaultFeed.cs +// The Aelrynth account vault (the Aeshnidae.Mule mod) for the Inventory panel's Vault view. +// +// The vault is storage the retail client is never shown, so the contents exist only on the server: +// "/mule-data [page]" answers one "~ael1" chat line a page (Net/AelrynthVaultWire.cs parses it). +// This feed asks for the pages, reads them, hides them from chat, and publishes the whole vault. +// Built on the same plan as MasteryFeed (read that for the reasoning behind the hiding): +// +// - only ever on Aelrynth (ServerInfo.IsAelrynth): another server would answer "Unknown command"; +// if Aelrynth does anyway (the mod switched off) the feed stops asking until the next login; +// - asked when the Vault view opens (unless the last read is under 30 s old) and on request; +// - a reply to OUR request (sent in the last 15 s) is eaten before AC draws it; a line the player +// asked for by typing /mule-data is read but left in chat; +// - a vault the server says is still loading is asked again a few times, and is never shown empty; +// - a vault that changed between pages (a deposit mid-read) is read again, not shown half and half. +// +// The one action: Withdraw sends "@mule withdraw 0x" (the player chose the item), then reads again. +// +// Threads: MainThreadTick and OnIncomingLine run on AC's main thread (the only place a command is +// sent). The panel's calls set fields under a small lock; Snapshot is readable anywhere. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Engine.Net; + +namespace RynthCore.Engine.Compatibility; + +/// A whole vault as last read. Immutable. +internal sealed class VaultSnapshot +{ + public required VaultItem[] Items { get; init; } + public required int Max { get; init; } + public required long ReceivedMs { get; init; } +} + +internal static class VaultFeed +{ + private const int ReplyWindowMs = 15_000, StaleMs = 30_000, RetryLoadingMs = 3000, MaxRetries = 5; + private const int AfterWithdrawMs = 1500; + + private static readonly object Gate = new(); + + // Any thread, under Gate. + private static long _wantAtMs; // 0 = no read wanted + private static string? _command; // a player action to send (withdraw) + private static string _commandLabel = ""; + + // Main thread only. + private static uint _playerId; + private static long _lastSendMs; + private static int _expectPage = 1; + private static int _retries; + private static string? _nextCommand; // the next page, sent on the next tick + private static long _nextCommandAtMs; + private static readonly List Acc = new(); + + private static volatile VaultSnapshot? _snapshot; + private static long _awaitingUntilMs; + private static volatile bool _unsupported; + private static volatile string _status = "not asked yet"; + + /// The last whole read, or null (none this login). Any thread. + public static VaultSnapshot? Snapshot => _snapshot; + public static bool Unsupported => _unsupported; + public static string Status => _status; + public static bool Awaiting => Environment.TickCount64 < Volatile.Read(ref _awaitingUntilMs); + + /// + /// The Vault button belongs here: on Aelrynth, with our chat hook in (it hides the reply). It stays when the + /// server has no vault command yet (): the view says so, and Refresh asks again. + /// + public static bool Available => ServerInfo.IsAelrynth && ChatCallbackHooks.IncomingInstalled; + + /// The Vault view opened: read unless the last read is fresh. Any thread. + public static void ViewOpened() + { + if (!Available || _unsupported) return; + VaultSnapshot? s = _snapshot; + if (s == null || Environment.TickCount64 - s.ReceivedMs > StaleMs) + RequestAt(Environment.TickCount64); + } + + /// Read now (the main thread paces it). Any thread. + public static void RequestRefresh() + { + if (!Available) return; + _unsupported = false; // the player asked again: the vault mod may have gone live since + RequestAt(Environment.TickCount64); + } + + /// Takes one item out: "/mule withdraw 0x<id>", then reads the vault again. Any thread. + public static bool Withdraw(VaultItem item) + { + if (!Available || item.Id == 0) return false; + lock (Gate) + { + if (_command != null) return false; + _command = "@mule withdraw 0x" + item.Id.ToString("X8", System.Globalization.CultureInfo.InvariantCulture); + _commandLabel = item.Name; + } + return true; + } + + private static void RequestAt(long atMs) + { + lock (Gate) + { + if (_wantAtMs == 0 || atMs < _wantAtMs) + _wantAtMs = Math.Max(1, atMs); + } + } + + // ── AC's main thread ──────────────────────────────────────────────── + + internal static void MainThreadTick(bool playerLive) + { + if (!MainThreadGuard.IsOnMainThread()) + return; + long now = Environment.TickCount64; + uint me = LogoutLifecycleHooks.HasObservedLogout ? 0 : ClientHelperHooks.GetPlayerId(); + if (me != _playerId) + NewLogin(me); + if (me == 0 || !playerLive) + return; + + // The next page of a read under way goes out at once; a retry waits for its time. + if (_nextCommand != null && now >= _nextCommandAtMs) + { + string cmd = _nextCommand; + _nextCommand = null; + if (ChatCommandDispatcher.SendServerCommand(cmd)) + Volatile.Write(ref _awaitingUntilMs, now + ReplyWindowMs); + else + _status = "could not send the request"; + return; + } + + // Idle: two loads, no lock. + if (Volatile.Read(ref _wantAtMs) == 0 && Volatile.Read(ref _command) == null) + return; + string? action; + string label; + long wantAt; + lock (Gate) { action = _command; label = _commandLabel; wantAt = _wantAtMs; } + + if (!Available) + { + lock (Gate) { _wantAtMs = 0; _command = null; } + return; + } + + if (action != null) + { + lock (Gate) { _command = null; } + if (ChatCommandDispatcher.SendServerCommand(action)) + { + _status = $"asked the server to give back {label}"; + RynthLog.Compat($"VaultFeed: sent {action}"); + RequestAt(now + AfterWithdrawMs); + } + else + { + _status = "could not send the withdraw"; + } + return; + } + + if (wantAt != 0 && now >= wantAt && !Awaiting && now - _lastSendMs >= 1000) + { + lock (Gate) { _wantAtMs = 0; } + _lastSendMs = now; + Acc.Clear(); + _expectPage = 1; + _retries = 0; + if (ChatCommandDispatcher.SendServerCommand(AelrynthVaultWire.PageCommand(1))) + { + Volatile.Write(ref _awaitingUntilMs, now + ReplyWindowMs); + _status = "reading the vault..."; + } + else + { + _status = "could not send the request (the client's talk function isn't bound)"; + } + } + } + + private static void NewLogin(uint me) + { + _playerId = me; + _snapshot = null; + _unsupported = false; + _nextCommand = null; + Acc.Clear(); + _expectPage = 1; + _retries = 0; + Volatile.Write(ref _awaitingUntilMs, 0); + lock (Gate) { _wantAtMs = 0; _command = null; } + _status = me != 0 ? "not asked yet" : "logged out"; + } + + /// + /// Every incoming chat line, from the chat hook (AC's main thread), before AC draws it. + /// True = eat it (our own request's reply). Never throws. + /// + internal static bool OnIncomingLine(string line) + { + try + { + if (line.Length < 8 || !ServerInfo.IsAelrynth) + return false; + bool awaiting = Awaiting; + if (AelrynthVaultWire.IsMuleLine(line)) + { + // A reply nobody here asked for (the RynthInventory plugin's own read, or one the player typed) + // is left for them; the plugin eats its own. + if (!awaiting) + return false; + OnReply(line); + return true; + } + if (awaiting && AelrynthVaultWire.IsUnknownCommand(line)) + { + _unsupported = true; + Volatile.Write(ref _awaitingUntilMs, 0); + _status = "the vault is not open on this server yet"; + RynthLog.Compat("VaultFeed: the server answered Unknown command: mule-data - not asking again this login."); + return true; + } + return false; + } + catch + { + return false; + } + } + + private static void OnReply(string line) + { + long now = Environment.TickCount64; + Volatile.Write(ref _awaitingUntilMs, 0); + if (!AelrynthVaultWire.TryParse(line, out VaultPage p)) + { + _status = "the server's reply could not be read"; + return; + } + if (!p.Ready) + { + // Still loading on the server: ask again shortly, never show it as empty. + if (p.Why == "loading" && ++_retries <= MaxRetries) + { + _status = "the vault is still loading on the server"; + Restart(now + RetryLoadingMs); + } + else + { + _status = p.Why.Length > 0 ? $"the vault is not available ({p.Why})" : "the vault is not available"; + } + return; + } + if (p.Page != _expectPage) + return; // a page twice, or out of turn: wait for the one asked + + Acc.AddRange(p.Items); + if (p.Page < p.Pages) + { + _expectPage = p.Page + 1; + _nextCommand = AelrynthVaultWire.PageCommand(_expectPage); + _nextCommandAtMs = now; + return; + } + // The last page. A total that disagrees with what was read means the vault changed under the read. + if (p.Count != Acc.Count && ++_retries <= MaxRetries) + { + _status = "the vault changed while reading; reading again"; + Restart(now + 500); + return; + } + _snapshot = new VaultSnapshot { Items = Acc.ToArray(), Max = p.Max, ReceivedMs = now }; + Acc.Clear(); + _status = $"{_snapshot.Items.Length} item(s)"; + } + + private static void Restart(long atMs) + { + Acc.Clear(); + _expectPage = 1; + _nextCommand = AelrynthVaultWire.PageCommand(1); + _nextCommandAtMs = atMs; + } +} diff --git a/src/RynthCore.Engine/ImGui/DX9Backend.cs b/src/RynthCore.Engine/ImGui/DX9Backend.cs index 1fa9201..d4dbd5d 100644 --- a/src/RynthCore.Engine/ImGui/DX9Backend.cs +++ b/src/RynthCore.Engine/ImGui/DX9Backend.cs @@ -138,7 +138,10 @@ internal static unsafe class DX9Backend private const uint D3DRS_WRAP0 = 128; // D3DTEXTUREFILTERTYPE - private const uint D3DTEXF_LINEAR = 2; + private const uint D3DTEXF_LINEAR = 2, D3DTEXF_POINT = 1; + // Draw-list callbacks this renderer understands besides ResetRenderState (see IconSampling): the sampler + // for the draw commands that follow, until the next one or the end of the list. + // FVF: xyz (3 floats) + diffuse (uint) + 1 tex coord (2 floats) private const uint D3DFVF_XYZ = 0x002; @@ -661,8 +664,15 @@ internal static unsafe class DX9Backend if (cmd->UserCallback != IntPtr.Zero) { - if ((int)cmd->UserCallback == ResetRenderStateSentinel) + int cb = (int)cmd->UserCallback; + if (cb == ResetRenderStateSentinel) SetupRenderStateNative(pDevice, displayPos, displaySize); + else if (cb == IconSampling.PointSentinel || cb == IconSampling.LinearSentinel) + { + uint f = cb == IconSampling.PointSentinel ? D3DTEXF_POINT : D3DTEXF_LINEAR; + _setSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, f); + _setSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, f); + } // Other callbacks are not supported (no managed callbacks // from inside the render path); they carry no geometry. continue; diff --git a/src/RynthCore.Engine/ImGui/IconSampling.cs b/src/RynthCore.Engine/ImGui/IconSampling.cs new file mode 100644 index 0000000..85a3c6a --- /dev/null +++ b/src/RynthCore.Engine/ImGui/IconSampling.cs @@ -0,0 +1,24 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/IconSampling.cs +// Item icons are 32x32 pictures drawn bigger; retail draws them point-sampled (crisp, hard-edged +// pixels, so its black outline stays a black line) and ImGui's default is a linear filter that blurs +// them. A face wraps its icon draws in Begin / End: two draw-list "callbacks" that DX9Backend answers by +// switching sampler 0's filter for the commands after them (no managed code runs in the render path). +// Every list starts back on linear (SetupRenderState), so a missed End cannot leak past its list. +// ============================================================================ + +using System; +using ImGuiNET; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class IconSampling +{ + public const int PointSentinel = -101, LinearSentinel = -102; + + /// The draws after this are point-sampled. + public static void Begin(ImDrawListPtr dl) => dl.AddCallback(new IntPtr(PointSentinel), IntPtr.Zero); + + /// The draws after this are linear again. + public static void End(ImDrawListPtr dl) => dl.AddCallback(new IntPtr(LinearSentinel), IntPtr.Zero); +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs index 0dfd957..c26ba36 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs @@ -90,8 +90,7 @@ internal static class MonsterHud // Element colours, shared by the "weak to" pill and the vulnerability icons. private static readonly uint ElemSlash = C(0xFFC9D1DB), ElemPierce = C(0xFFD9C19A), ElemBludgeon = C(0xFFB59A7E), - ElemFire = C(0xFFFF7A3D), ElemCold = C(0xFF7FD3FF), ElemLightning = C(0xFFC89BFF), ElemAcid = C(0xFF8FE36A), - ElemNether = C(0xFFB06BE0); + ElemFire = C(0xFFFF7A3D), ElemCold = C(0xFF7FD3FF), ElemLightning = C(0xFFC89BFF), ElemAcid = C(0xFF8FE36A); // One glyph and tint per DebuffKind (index = kind). private static readonly string[] KindGlyph = @@ -174,7 +173,8 @@ internal static class MonsterHud public int OverflowKey = -1; } - private sealed record WeakTag(string Label, uint Color); + // Icon: a Phosphor glyph drawn before the letters, so the element reads at a glance. + private sealed record WeakTag(string Label, uint Color, string Icon); private const float DefaultHeadHeight = 2.0f; private static readonly Dictionary Plates = new(64); @@ -687,23 +687,34 @@ internal static class MonsterHud _weakByName = byName; } - /// "Bludgeon 1.0, Pierce 0.86" -> the first (most damage taken) element. + /// + /// "Bludgeon 1.0, Pierce 0.86" -> the first (most damage taken) element. Nether is + /// skipped: everything takes it, so the pill shows the next element instead. + /// private static WeakTag? ParseWeak(string weak) { - int comma = weak.IndexOf(','); - string first = (comma > 0 ? weak[..comma] : weak).Trim(); - int sp = first.IndexOf(' '); - string elem = sp > 0 ? first[..sp] : first; - return elem.ToLowerInvariant() switch + foreach (string part in weak.Split(',')) { - "slash" or "slashing" => new WeakTag("SL", ElemSlash), - "pierce" or "piercing" => new WeakTag("PI", ElemPierce), - "bludgeon" or "bludgeoning" => new WeakTag("BL", ElemBludgeon), - "fire" => new WeakTag("FI", ElemFire), - "cold" => new WeakTag("CO", ElemCold), - "lightning" or "electric" => new WeakTag("LI", ElemLightning), - "acid" => new WeakTag("AC", ElemAcid), - "nether" => new WeakTag("NE", ElemNether), + string first = part.Trim(); + int sp = first.IndexOf(' '); + string elem = (sp > 0 ? first[..sp] : first).ToLowerInvariant(); + if (elem.Length == 0 || elem == "nether") continue; + return ElementTag(elem); + } + return null; + } + + private static WeakTag? ElementTag(string elem) + { + return elem switch + { + "slash" or "slashing" => new WeakTag("SL", ElemSlash, PhosphorIcons.Sword), + "pierce" or "piercing" => new WeakTag("PI", ElemPierce, PhosphorIcons.Knife), + "bludgeon" or "bludgeoning" => new WeakTag("BL", ElemBludgeon, PhosphorIcons.Hammer), + "fire" => new WeakTag("FI", ElemFire, PhosphorIcons.Fire), + "cold" => new WeakTag("CO", ElemCold, PhosphorIcons.Snowflake), + "lightning" or "electric" => new WeakTag("LI", ElemLightning, PhosphorIcons.Lightning), + "acid" => new WeakTag("AC", ElemAcid, PhosphorIcons.Flask), _ => null, }; } @@ -1244,17 +1255,19 @@ internal static class MonsterHud } } - // Left of the bar: the "weak to" element pill. + // Left of the bar: the "weak to" element pill, its icon then its letters. if (p.Weak != null) { - float pw = TextWidth(p.SmallFont, p.SmallSize, p.Weak.Label) + 6f * k; + float iw = TextWidth(p.SmallFont, p.SmallSize, p.Weak.Icon) + 2f * k; + float pw = iw + TextWidth(p.SmallFont, p.SmallSize, p.Weak.Label) + 6f * k; float ph = MathF.Max(p.BarH + 2f, p.SmallSize + 2f); var q0 = new Vector2(MathF.Round(barL - 4f * k - pw), MathF.Round(barTop + (p.BarH - ph) * 0.5f)); var q1 = q0 + new Vector2(pw, ph); dl.AddRectFilled(q0, q1, Mul(BadgeBack, a), 3f * k); dl.AddRect(q0, q1, Mul(p.Weak.Color, a * 0.9f), 3f * k, ImDrawFlags.None, 1f); var tp = new Vector2(MathF.Round(q0.X + 3f * k), MathF.Round(q0.Y + (ph - p.SmallSize) * 0.5f)); - dl.AddText(p.SmallFont, p.SmallSize, tp, Mul(p.Weak.Color, a), p.Weak.Label); + dl.AddText(p.SmallFont, p.SmallSize, tp, Mul(p.Weak.Color, a), p.Weak.Icon); + dl.AddText(p.SmallFont, p.SmallSize, tp + new Vector2(MathF.Round(iw), 0), Mul(p.Weak.Color, a), p.Weak.Label); } // Distance, right of the bar. diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index f749181..24c81b3 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -45,6 +45,18 @@ internal sealed class ChatFace : IImGuiPanel { public const string Title = "Chat"; + // The channel tabs live in a drawer on the window's left edge (Tom 2026-10-09: the + // wrapped tab rows took too much room), the way the dashboard's ranges do. + private readonly ChannelsDrawer _channels; + private readonly DashboardDrawers _drawers; + private bool _openTabsPopup; + + public ChatFace() + { + _channels = new ChannelsDrawer(this); + _drawers = new DashboardDrawers("##chat_drawers", _channels); + } + public static void Register() => ImGuiPanelHost.Register(Title, new PanelSpec(new Vector2(460, 300), new Vector2(260, 140), Background: 0, EdgeToEdge: true, GripInBody: true), () => new ChatFace()); @@ -142,10 +154,7 @@ internal sealed class ChatFace : IImGuiPanel string tab = ChatModel.CurrentTab(); UpdateUnread(lines, snap?.Version ?? -1, tab); - float y = DrawTabStrip(new Vector2(x0, origin.Y + 4), w); - - DrawSearch(new Vector2(x0, y), w); - y += 26; + float y = DrawHeader(new Vector2(x0, origin.Y + 4), w); SyncLines(snap, lines, tab); @@ -163,77 +172,174 @@ internal sealed class ChatFace : IImGuiPanel ImGuiNET.ImGui.PopStyleVar(); DrawPopups(); ImGuiNET.ImGui.PopFont(); + _drawers.Draw(); // last: its own window, placed against this one } // ── Tabs ───────────────────────────────────────────────────────────── private const string SearchHint = PhosphorIcons.MagnifyingGlass + " Search…"; - private const string FiltersLabel = PhosphorIcons.Funnel + " Filters"; - /// Tabs wrap left of Filters and the settings gear. Returns the y below the strip. - private float DrawTabStrip(Vector2 start, float w) + /// + /// One row: the channel button (current tab, unread elsewhere; it opens the channels + /// drawer, or a list when popped out), search, Filters and the gear. Returns the y below it. + /// + private float DrawHeader(Vector2 start, float w) { - const float h = 20; - float gearW = 22, filtW = ButtonWidth(FiltersLabel) - 4; - float right = start.X + w; + const float h = 22; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float gearW = 22, filtW = 22, right = start.X + w; if (IconButton("##chat_gear", PhosphorIcons.Gear, new Vector2(right - gearW, start.Y), new Vector2(gearW, h), Text, BtnFill)) _openSettings = true; ImGuiNET.ImGui.SetItemTooltip("Chat settings"); - if (Button("##chat_filters", FiltersLabel, new Vector2(right - gearW - 3 - filtW, start.Y), new Vector2(filtW, h), Text, BtnFill)) + if (IconButton("##chat_filters", PhosphorIcons.Funnel, new Vector2(right - gearW - 3 - filtW, start.Y), new Vector2(filtW, h), Text, BtnFill)) PanelRouter.Toggle("ChatFilters"); - ImGuiNET.ImGui.SetItemTooltip("Rules: move, copy or hide lines by regex, and colour them"); + ImGuiNET.ImGui.SetItemTooltip("Filters: move, copy or hide lines by regex, and colour them"); - var dl = ImGuiNET.ImGui.GetWindowDrawList(); - float stripRight = right - gearW - filtW - 8; - float x = start.X, y = start.Y; + // The channel button: icon, current tab, and the unread count of every other tab. string current = ChatModel.CurrentTab(); + int others = 0; + bool mention = false; + foreach (var kv in _unread) + { + if (string.Equals(kv.Key, current, StringComparison.OrdinalIgnoreCase)) continue; + others += kv.Value.Count; + mention |= kv.Value.Mention && kv.Value.Count > 0; + } + string? badge = others > 0 ? (others > 99 ? "99+" : others.ToString()) : null; + float badgeW = badge != null ? BadgeWidth(badge) : 0; + string label = PhosphorIcons.ChatCircleText + " " + current; + float labelW = ImGuiNET.ImGui.CalcTextSize(label).X; + float caretW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.CaretDown).X; + float bw = MathF.Min(labelW + 16 + caretW + (badge != null ? badgeW + 4 : 0), w * 0.45f); + bool drawerOpen = _drawers.IsOpen(_channels); + if (Button("##chat_channel", "", start, new Vector2(bw, h), Text, drawerOpen ? TabActive : BtnFill)) + { + if (ImGuiPopOuts.InPopOutFrame) _openTabsPopup = true; // no drawer beside a popped-out window + else _drawers.Toggle(_channels); + } + if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip)) + ImGuiNET.ImGui.SetTooltip(mention ? "Channels (someone mentioned you)" : "Channels: pick a tab, see what's unread"); + float ty = start.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.PushClipRect(start, start + new Vector2(bw - caretW - 6 - (badge != null ? badgeW + 4 : 0), h), true); + dl.AddText(new Vector2(start.X + 6, ty), Text, label); + dl.PopClipRect(); + float bx = start.X + bw - caretW - 6; + if (badge != null) + { + bx -= badgeW + 4; + DrawBadge(dl, new Vector2(bx, start.Y + 4), badgeW, h - 8, badge, mention); + bx += badgeW + 4; + } + dl.AddText(new Vector2(start.X + bw - caretW - 5, ty), Mute, PhosphorIcons.CaretDown); + + // Search fills the rest. + float sx = start.X + bw + 4, sw = right - gearW - filtW - 7 - sx; + if (sw > 40) DrawSearch(new Vector2(sx, start.Y), sw); + return start.Y + h + 4; + } + + private static float BadgeWidth(string badge) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + float w = ImGuiNET.ImGui.CalcTextSize(badge).X + 8; + ImGuiNET.ImGui.PopFont(); + return w; + } + + private static void DrawBadge(ImDrawListPtr dl, Vector2 p, float w, float h, string badge, bool mention) + { + dl.AddRectFilled(p, p + new Vector2(w, h), mention ? BadgeMention : BadgeBg, h * 0.5f); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + dl.AddText(p + new Vector2(4, (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, badge); + ImGuiNET.ImGui.PopFont(); + } + + /// + /// The channel rows (the drawer's panel; the popped-out list draws its own): each tab with + /// its unread count, the current one highlighted; click picks it, right-click renames or + /// deletes a created tab; "+ New tab" at the end. + /// + private void DrawChannelRows(Vector2 start, float w, float rowH) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + string current = ChatModel.CurrentTab(); + float y = start.Y; foreach (string tab in ChatModel.AllTabs()) { - bool custom = !ChatModel.IsBaseTab(tab); bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase); _unread.TryGetValue(tab, out var unread); string? badge = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null; - float badgeW = 0; - if (badge != null) - { - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - badgeW = ImGuiNET.ImGui.CalcTextSize(badge).X + 8; - ImGuiNET.ImGui.PopFont(); - } - float textW = ImGuiNET.ImGui.CalcTextSize(tab).X; - // No inline delete button on custom tabs: right-click → Delete tab does it and - // the red X cost a tab's worth of strip width (2026-09-30). - float bw = textW + 12 + (badge != null ? badgeW + 3 : 0), extra = 0; - if (x > start.X && x + bw + extra > stripRight) { x = start.X; y += h + 2; } ImGuiNET.ImGui.PushID(tab); - var p = new Vector2(x, y); - if (Button("##tab", "", p, new Vector2(bw, h), Text, active ? TabActive : BtnFill)) + var p = new Vector2(start.X, y); + if (Button("##row", "", p, new Vector2(w, rowH), Text, active ? TabActive : BtnFill)) ChatModel.SelectTab(tab); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _ctxTab = tab; _openTabMenu = true; } if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here"); - else if (custom) ImGuiNET.ImGui.SetItemTooltip("Right-click to rename or delete this tab"); - float ty = y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; - dl.AddText(new Vector2(x + 6, ty), Text, tab); - if (badge != null) - { - var b0 = new Vector2(x + 6 + textW + 3, y + 4); - dl.AddRectFilled(b0, b0 + new Vector2(badgeW, h - 8), unread.Mention ? BadgeMention : BadgeBg, (h - 8) * 0.5f); - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - dl.AddText(b0 + new Vector2(4, (h - 8 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, badge); - ImGuiNET.ImGui.PopFont(); - } + else if (!ChatModel.IsBaseTab(tab)) ImGuiNET.ImGui.SetItemTooltip("Right-click to rename or delete this tab"); + float badgeW = badge != null ? BadgeWidth(badge) : 0; + float ty = y + (rowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.PushClipRect(p, p + new Vector2(w - (badge != null ? badgeW + 8 : 0), rowH), true); + dl.AddText(new Vector2(p.X + 6, ty), active ? Teal : Text, tab); + dl.PopClipRect(); + if (badge != null) DrawBadge(dl, new Vector2(p.X + w - badgeW - 4, y + 3), badgeW, rowH - 6, badge, unread.Mention); ImGuiNET.ImGui.PopID(); - x += bw + extra + 2; + y += rowH + 2; } - if (x > start.X && x + 18 > stripRight) { x = start.X; y += h + 2; } - if (IconButton("##chat_addtab", PhosphorIcons.Plus, new Vector2(x, y), new Vector2(18, h), TabAdd, BtnFill, font: UiFont.Ui11)) + if (Button("##chat_addtab", PhosphorIcons.Plus + " New tab", new Vector2(start.X, y), new Vector2(w, rowH), TabAdd, BtnFill)) { _pendingRule = null; WriteUtf8(_newTab, ""); _openNewTab = _focusNewTab = true; } ImGuiNET.ImGui.SetItemTooltip("New tab (fill it with a rule: right-click a line, or Filters)"); - return y + h + 4; + } + + /// Popped out (no drawer beside the window): the channels as a list under the button. + private void DrawTabsPopup() + { + if (!ImGuiNET.ImGui.BeginPopup("##chat_tabs")) return; + string current = ChatModel.CurrentTab(); + foreach (string tab in ChatModel.AllTabs()) + { + _unread.TryGetValue(tab, out var unread); + bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase); + string label = !active && unread.Count > 0 ? $"{tab} ({unread.Count})" : tab; + if (ImGuiNET.ImGui.Selectable(label + "##tabsel_" + tab, active)) ChatModel.SelectTab(tab); + } + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.Selectable(PhosphorIcons.Plus + " New tab")) + { + _pendingRule = null; + WriteUtf8(_newTab, ""); + _openNewTab = _focusNewTab = true; + } + ImGuiNET.ImGui.EndPopup(); + } + + /// The channels drawer on the chat window's left edge (DashboardDrawers' mechanics). + private sealed class ChannelsDrawer : DashboardDrawer + { + private const float RowH = 20; + private static bool s_open; // this session only + private readonly ChatFace _face; + + public ChannelsDrawer(ChatFace face) => _face = face; + + public override string Key => "chat_channels"; + public override string Icon => PhosphorIcons.ChatCircleText; + public override string Name => "channels"; + public override string TabTooltip(bool right) => "Channels: every tab, with what's unread"; + public override float Width(float k) => 150 * k; + public override float Height(float k) => + (2 * Pad + TitleH + 4) * k + (ChatModel.AllTabs().Length + 1) * (RowH + 2) * k; + public override bool SavedOpen => s_open; + public override void SaveOpen(bool open) => s_open = open; + + public override void DrawPanel(Vector2 origin, float width, float height, float k) + { + float y = PanelFrame(origin, width, height, k, Icon, "CHANNELS", null, "Hide the channels"); + _face.DrawChannelRows(new Vector2(origin.X + Pad * k, y), width - 2 * Pad * k, RowH * k); + } } /// @@ -727,6 +833,7 @@ internal sealed class ChatFace : IImGuiPanel if (_openTabMenu) { _openTabMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_tabmenu"); } if (_openLineMenu) { _openLineMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_linemenu"); } if (_openRename) { _openRename = false; ImGuiNET.ImGui.OpenPopup("##chat_rename"); } + if (_openTabsPopup) { _openTabsPopup = false; ImGuiNET.ImGui.OpenPopup("##chat_tabs"); } ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, RynthTheme.Argb(0xF2060C14)); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, TabActive); @@ -739,6 +846,7 @@ internal sealed class ChatFace : IImGuiPanel ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); DrawSettingsPopup(); + DrawTabsPopup(); DrawNewTabPopup(); DrawTabMenu(); DrawRenamePopup(); diff --git a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs index 00af2e3..0670767 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs @@ -111,7 +111,7 @@ internal abstract class DashboardDrawer /// The tabs and the one open drawer beside the RynthAi dashboard. internal sealed class DashboardDrawers { - private const string WindowId = "##rynthai_drawers"; + private readonly string WindowId; // "##rynthai_drawers" for the dashboard; the chat has its own private const float SlideSeconds = 0.14f; private static readonly uint Teal = RynthTheme.Argb(0xFF26D9E6), Mute = RynthTheme.Argb(0xFFB8C8D8), @@ -123,8 +123,12 @@ internal sealed class DashboardDrawers private float _t; // slide position of _shown, 0 closed .. 1 open private bool _loaded; - public DashboardDrawers(params DashboardDrawer[] drawers) + public DashboardDrawers(params DashboardDrawer[] drawers) : this("##rynthai_drawers", drawers) { } + + /// A drawer set beside another panel (RynthChat's channels): its own window id. + public DashboardDrawers(string windowId, params DashboardDrawer[] drawers) { + WindowId = windowId; _drawers = drawers; foreach (DashboardDrawer d in drawers) d.Host = this; } diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs index 807801e..00cbf87 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs @@ -34,10 +34,12 @@ // ============================================================================ using System; +using System.Globalization; using System.IO; using System.Numerics; using ImGuiNET; using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Net; using RynthCore.Engine.UI; using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; @@ -143,9 +145,14 @@ internal sealed partial class InventoryFace float ui = EngineFrameController.FontScale * PanelTextScale.Factor(ImGuiFonts.CurrentStep); if (!(ui > 0f) || !float.IsFinite(ui)) ui = 1f; ui *= InventorySettingsStore.SizeFactor; // the panel's own size (the - / + in the title bar) - float s = Math.Max(0.4f, Math.Min(ui, size.X / RetailW)); + // Whole-pixel cells keep point-sampled icons even (32 px art drawn at 46.4 px is uneven). + float want = Math.Max(0.4f, MathF.Round(32f * ui) / 32f); + float s = Math.Max(0.4f, Math.Min(want, size.X / RetailW)); var dl = ImGuiNET.ImGui.GetWindowDrawList(); - float w = size.X; + // Retail's window is a fixed width at its size: the panel follows it (the - / + in the title bar + // resize it), so there is no spare strip beside the burden meter. + FitWidth(size, RetailW * want); + float w = Math.Min(size.X, RetailW * s); Vector2 o = origin; float statusH = MathF.Round(20 * s); float bottom = o.Y + size.Y - statusH; @@ -171,7 +178,9 @@ internal sealed partial class InventoryFace float ry = toolsBottom - TitleH * s; // where retail y = 0 lands float r = Math.Max(ContentsY + 60, (bottom - ry) / s); // the retail window's height (px at scale 1) - float sx = o.X + w - SideW * s; // the side column follows the right edge + // The side column sits against the grid, where retail has it: the retail window is a fixed width, + // so a wider panel leaves its spare room on the right instead of a gap in the middle. + float sx = o.X + Math.Min(w - SideW * s, (RetailW - SideW) * s); Paperdoll(view, dl, new Vector2(o.X, ry + FieldY * s), s); SideColumn(view, dl, new Vector2(sx, ry + FieldY * s), r, s, filtered); Contents(view, dl, new Vector2(o.X, ry + ContentsY * s), sx, r, s, filtered); @@ -234,14 +243,37 @@ internal sealed partial class InventoryFace InventorySettingsStore.StepSize(+1); ImGuiNET.ImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)"); if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, b1, btn, InventorySettingsStore.ShowTools)) + { + // Closing the search / filter row shows every item again. + if (InventorySettingsStore.ShowTools) ClearFilters(); InventorySettingsStore.SetShowTools(!InventorySettingsStore.ShowTools); + } ImGuiNET.ImGui.SetItemTooltip("Search, sort and filter"); if (TitleToggle("##inv_modern", PhosphorIcons.SquaresFour, b2, btn, false)) InventorySettingsStore.SetClassic(false); ImGuiNET.ImGui.SetItemTooltip("Modern look"); + // Vault (Aelrynth only): the contents area shows the account vault instead of the open pack. + float leftmost = bMinus.X; + if (VaultFeed.Available) + { + var vsz = new Vector2(MathF.Round(38 * s), btn); + var bV = new Vector2(bMinus.X - vsz.X - 8 * s, b2.Y); + if (TitleTextToggle("##inv_vault", "Vault", bV, vsz, _vaultOpen)) + { + _vaultOpen = !_vaultOpen; + if (_vaultOpen) VaultFeed.ViewOpened(); + } + ImGuiNET.ImGui.SetItemTooltip("Your Aelrynth account vault"); + leftmost = bV.X; + } + else + { + _vaultOpen = false; + } + // Drag surface: the bar left of the toggles (moves the panel, like the header). - float dragW = Math.Max(1, bMinus.X - o.X - 2); + float dragW = Math.Max(1, leftmost - o.X - 2); ImGuiNET.ImGui.SetCursorScreenPos(o); ImGuiNET.ImGui.InvisibleButton("##inv_titledrag", new Vector2(dragW, h)); ImGuiPanelHost.DragWindowWithLastItem(); @@ -256,10 +288,12 @@ internal sealed partial class InventoryFace ImGuiNET.ImGui.PushFont(f); Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_titleText); ImGuiNET.ImGui.PopFont(); + float titlePx = 12 * s; + ts *= titlePx / f.FontSize; float tx = o.X + (barW - ts.X) * 0.5f; - if (tx + ts.X > bMinus.X - 4) tx = Math.Max(o.X + 10 * s, bMinus.X - 4 - ts.X); - dl.PushClipRect(o + new Vector2(6 * s, 0), new Vector2(bMinus.X - 2, o.Y + h), true); - dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, new Vector2(tx, o.Y + (h - ts.Y) * 0.5f), White, _titleText); + if (tx + ts.X > leftmost - 4) tx = Math.Max(o.X + 10 * s, leftmost - 4 - ts.X); + dl.PushClipRect(o + new Vector2(6 * s, 0), new Vector2(leftmost - 2, o.Y + h), true); + dl.AddText(f, titlePx, new Vector2(tx, o.Y + (h - ts.Y) * 0.5f), White, _titleText); dl.PopClipRect(); // The retail close button. @@ -301,7 +335,7 @@ internal sealed partial class InventoryFace if ((it.Location & slot.Mask) != 0) { worn = it; break; } if (slot.Sigil != 0 && worn == null && (view.AetheriaMask & slot.Sigil) == 0) continue; // locked sigil slot - var min = new Vector2(field.X + slot.X * s, field.Y + slot.Y * s); + var min = new Vector2(MathF.Round(field.X + slot.X * s), MathF.Round(field.Y + slot.Y * s)); var max = min + new Vector2(cell, cell); ImGuiNET.ImGui.SetCursorScreenPos(min); ImGuiNET.ImGui.PushID(i); @@ -309,6 +343,9 @@ internal sealed partial class InventoryFace bool hovered = ImGuiNET.ImGui.IsItemHovered(); ImGuiNET.ImGui.PopID(); + // The slot's tile is drawn filled or not: it is part of the panel, and it is what says an + // item is worn (retail draws a worn item like any other, over its slot). + CellPicture(dl, slot.Empty, min, cell); if (worn != null) { DrawItemIcon(dl, worn.Id, min, cell, ReferenceEquals(worn, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu); @@ -316,7 +353,6 @@ internal sealed partial class InventoryFace } else { - CellPicture(dl, slot.Empty, min, cell); if (hovered) { _hoverLabel = slot.Name; @@ -344,9 +380,10 @@ internal sealed partial class InventoryFace private void SideColumn(InventoryView view, ImDrawListPtr dl, Vector2 field, float r, float s, bool filtered) { // Burden: caption and percent (36x15 each at y 7 and 18), meter 11x58 at (44, 8). - ImFontPtr f = ImGuiFonts.Get(UiFont.Ui9); - CenterText(dl, f, "Burden", new Vector2(field.X, field.Y + 7 * s), new Vector2(36 * s, 15 * s), White); - CenterText(dl, f, view.BurdenText, new Vector2(field.X, field.Y + 18 * s), new Vector2(36 * s, 15 * s), White); + // Retail's text here is about 13 px (a serif face); the smallest UI font was too small to read. + ImFontPtr f = ImGuiFonts.Get(UiFont.Ui14); + CenterText(dl, f, "Burden", new Vector2(field.X - 3 * s, field.Y + 5 * s), new Vector2(42 * s, 15 * s), White, 13 * s); + CenterText(dl, f, view.BurdenText, new Vector2(field.X - 3 * s, field.Y + 18 * s), new Vector2(42 * s, 15 * s), White, 13 * s); var mMin = new Vector2(field.X + 44 * s, field.Y + 8 * s); var mSize = new Vector2(11 * s, 58 * s); // Retail's meter holds 0-300% of capacity (OpenAC's BurdenMath.LoadToFill: load / 3). @@ -369,7 +406,7 @@ internal sealed partial class InventoryFace // Main pack (36x36 at (6, 32)). InventoryPack? main = view.Packs.Length > 0 ? view.Packs[0] : null; - PackCell(view, dl, main, new Vector2(field.X + 6 * s, field.Y + 32 * s), s, -1, filtered); + PackCell(view, dl, main, new Vector2(MathF.Round(field.X + 6 * s), MathF.Round(field.Y + 32 * s)), s, -1, filtered); // The main pack's pack slots (36 px pitch at (6, 73)): the side packs, then the items // that take a pack slot (foci), as retail lists them; retail's seven slots (eight with @@ -386,7 +423,7 @@ internal sealed partial class InventoryFace { int i = _packFirstRow + row; if (i >= slots) break; - var min = new Vector2(field.X + 6 * s, listY + row * PackPx * s); + var min = new Vector2(MathF.Round(field.X + 6 * s), MathF.Round(listY + row * PackPx * s)); if (i < sidePacks) PackCell(view, dl, view.Packs[i + 1], min, s, i, filtered); else if (i < used) SlotItemCell(view, dl, view.SlotItems[i - sidePacks], min, s, i, pendingId); else @@ -404,7 +441,9 @@ internal sealed partial class InventoryFace if (MouseIn(new Vector2(field.X, listY), new Vector2(field.X + SideW * s, listY + listH)) && ImGuiNET.ImGui.IsWindowHovered()) Wheel(ref _packFirstRow, slots - rows); - Scrollbar("##inv_packsb", new Vector2(field.X + 41 * s, listY), listH, s, ref _packFirstRow, slots, rows); + // Retail draws this scrollbar only when the slots do not all fit. + if (slots > rows) + Scrollbar("##inv_packsb", new Vector2(field.X + 41 * s, listY), listH, s, ref _packFirstRow, slots, rows); } /// @@ -422,6 +461,7 @@ internal sealed partial class InventoryFace ImGuiNET.ImGui.PopID(); ItemPointer(it, hovered); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts + CellPicture(dl, Art.PackEmpty, inner, cell); // the slot stays under what fills it ItemCell(dl, it, inner, cell, pendingId); ImGuiNET.ImGui.PopFont(); SlotDropHint(view, dl, inner, cell); @@ -454,6 +494,7 @@ internal sealed partial class InventoryFace return; } if (clicked && _dragItem == null) _pack = pack.Id; + CellPicture(dl, Art.PackEmpty, inner, cell); // the slot stays under what fills it if (pack.IsMain) { if (!Sprite(dl, Art.MainPackIcon, inner, new Vector2(cell, cell))) @@ -503,16 +544,21 @@ internal sealed partial class InventoryFace private void Contents(InventoryView view, ImDrawListPtr dl, Vector2 field, float sideX, float r, float s, bool filtered) { + if (_vaultOpen && VaultFeed.Available) + { + VaultContents(dl, field, sideX, r, s); + return; + } float cell = CellPx * s; - var gridPos = new Vector2(field.X + 15 * s, field.Y + 20 * s); + var gridPos = new Vector2(MathF.Round(field.X + 15 * s), MathF.Round(field.Y + 20 * s)); float availW = sideX - 32 * s - gridPos.X; // retail: grid 15..207, scrollbar 207..223, column at 239 - int cols = Math.Max(1, (int)(availW / cell)); + int cols = Math.Max(1, (int)(availW / cell + 0.01f)); // exact multiples must not round down (6 columns at retail size) float gridW = cols * cell; float gridH = Math.Max(cell, (r - ContentsY - 5 - 24) * s); int rows = Math.Max(1, (int)(gridH / cell + 0.01f)); // "Contents of " over the grid. - CenterText(dl, ImGuiFonts.Get(UiFont.Ui10), _captionText, new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White); + CenterText(dl, ImGuiFonts.Get(UiFont.Ui14), _captionText, new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White, 12 * s); InventoryPack? open = filtered ? null : view.PackOf(_pack); int cells = open != null ? Math.Max(open.Capacity, _shown.Count) : _shown.Count; @@ -533,7 +579,8 @@ internal sealed partial class InventoryFace } if (hovered && hoverCell >= 0 && hoverCell < _shown.Count) ItemPointer(_shown[hoverCell], true); - // Only the rows on show; retail draws an item's icon in place of the empty cell. + // Only the rows on show. Retail draws the empty-cell picture under EVERY cell and the item + // over it (AcClientReborn does the same), so the grid's lines show behind an item's icon. uint pendingId = InventoryModel.Pending?.ItemId ?? 0; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts for (int rr = 0; rr < rows; rr++) @@ -543,11 +590,8 @@ internal sealed partial class InventoryFace int i = (_gridFirstRow + rr) * cols + c; if (i >= cells) break; var min = new Vector2(gridPos.X + c * cell, gridPos.Y + rr * cell); - if (i >= _shown.Count) - { - CellPicture(dl, Art.GridEmpty, min, cell); - continue; - } + CellPicture(dl, Art.GridEmpty, min, cell); + if (i >= _shown.Count) continue; ItemCell(dl, _shown[i], min, cell, pendingId); } } @@ -555,15 +599,30 @@ internal sealed partial class InventoryFace if (open != null) { - // Dropping on the grid moves the item into the open pack. - if (_dragItem != null && hoverCell >= 0 && hoverCell < cells && !(_dragItem.Container == open.Id && _dragItem.Wielder == 0)) + // Dropping on the grid moves the item into the open pack - to the slot under the mouse when + // the cells are the server's slots (retail: a drop on a cell places it there, which is also + // how items are reordered inside a pack). + int dropSlot = -1; + if (_dragItem != null && hoverCell >= 0 && CellsAreSlots(_dragItem)) + { + int mine = _dragItem.Container == open.Id && _dragItem.Wielder == 0 ? SlotOf(_dragItem) : -1; + int others = _shown.Count - (mine >= 0 ? 1 : 0); + dropSlot = Math.Min(hoverCell, Math.Max(0, others)); + } + // A drop inside the item's own pack that cannot be a slot says why, instead of doing nothing. + if (dropSlot < 0 && _dragItem != null && hoverCell >= 0 && _dragItem.Container == open.Id && _dragItem.Wielder == 0 + && !_dragItem.RequiresPackSlot && !_dragItem.IsPack) + dropSlot = -2; + bool sameSpot = dropSlot >= 0 && _dragItem != null && _dragItem.Container == open.Id && _dragItem.Wielder == 0 && SlotOf(_dragItem) == dropSlot; + if (_dragItem != null && hoverCell >= 0 && hoverCell < cells + && (dropSlot >= 0 ? !sameSpot : !(_dragItem.Container == open.Id && _dragItem.Wielder == 0))) { int c = hoverCell % cols, rr = hoverCell / cols - _gridFirstRow; var min = new Vector2(gridPos.X + c * cell, gridPos.Y + rr * cell); bool full = PackRefuses(view, open, _dragItem); Overlay(dl, full ? Art.Reject : Art.AcceptGrid, min, cell, full ? RejectRed : AcceptGreen); } - _targets.Add(new Target { Min = gridPos, Max = gridPos + area, Kind = DropKind.Pack, Id = open.Id, Name = open.Name }); + _targets.Add(new Target { Min = gridPos, Max = gridPos + area, Kind = DropKind.Pack, Id = open.Id, Name = open.Name, Slot = dropSlot }); } else if (_shown.Count == 0) { @@ -573,6 +632,140 @@ internal sealed partial class InventoryFace Scrollbar("##inv_gridsb", new Vector2(gridPos.X + gridW, gridPos.Y), rows * cell, s, ref _gridFirstRow, totalRows, rows); } + + // ── The Aelrynth account vault (Inventory > Vault) ────────────────── + + private bool _vaultOpen; + private int _vaultFirstRow; + private VaultItem? _vaultCtx; + private bool _openVaultCtx; + + /// A small labelled button in the title bar. + private static bool TitleTextToggle(string id, string label, Vector2 pos, Vector2 size, bool on) + { + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + uint col = on || hot ? Gold : Faded(Gold); + dl.AddRect(pos, pos + size, col, 3); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(label); + dl.AddText(pos + new Vector2((size.X - ts.X) * 0.5f, (size.Y - ts.Y) * 0.5f), col, label); + return clicked; + } + + /// + /// The Vault view: the contents area shows the account vault (the grid's own frames for every slot, + /// items drawn as they are in a pack). Read-only apart from right-click > Withdraw. + /// + private void VaultContents(ImDrawListPtr dl, Vector2 field, float sideX, float r, float s) + { + float cell = CellPx * s; + var gridPos = new Vector2(MathF.Round(field.X + 15 * s), MathF.Round(field.Y + 20 * s)); + float availW = sideX - 32 * s - gridPos.X; + int cols = Math.Max(1, (int)(availW / cell + 0.01f)); // exact multiples must not round down (6 columns at retail size) + float gridW = cols * cell; + float gridH = Math.Max(cell, (r - ContentsY - 5 - 24) * s); + int rows = Math.Max(1, (int)(gridH / cell + 0.01f)); + + VaultSnapshot? snap = VaultFeed.Snapshot; + VaultItem[] items = snap?.Items ?? Array.Empty(); + int cells = snap == null ? 0 : Math.Max(snap.Max, items.Length); + string caption = snap == null ? VaultFeed.Status + : snap.Max > 0 ? $"Aelrynth Vault: {items.Length:N0} of {snap.Max:N0}" : $"Aelrynth Vault: {items.Length:N0}"; + CenterText(dl, ImGuiFonts.Get(UiFont.Ui14), caption, new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White, 12 * s); + + // Read again (the vault changes when anything is deposited or withdrawn). + var rb = new Vector2(gridPos.X + gridW - 44 * s, field.Y + 1 * s); + if (TitleTextToggle("##vault_refresh", "Refresh", rb, new Vector2(44 * s, 14 * s), VaultFeed.Awaiting)) + VaultFeed.RequestRefresh(); + + int totalRows = (cells + cols - 1) / cols; + _vaultFirstRow = Math.Clamp(_vaultFirstRow, 0, Math.Max(0, totalRows - rows)); + var area = new Vector2(gridW, rows * cell); + ImGuiNET.ImGui.SetCursorScreenPos(gridPos); + ImGuiNET.ImGui.InvisibleButton("##vault_cells", area, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight); + bool hovered = ImGuiNET.ImGui.IsItemHovered(); + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + int hoverCell = -1; + if (MouseIn(gridPos, gridPos + area)) + { + int c = (int)((mouse.X - gridPos.X) / cell), rr = (int)((mouse.Y - gridPos.Y) / cell); + if (c >= 0 && c < cols && rr >= 0 && rr < rows) hoverCell = (_vaultFirstRow + rr) * cols + c; + if (ImGuiNET.ImGui.IsWindowHovered()) Wheel(ref _vaultFirstRow, totalRows - rows); + } + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts + for (int rr = 0; rr < rows; rr++) + { + for (int c = 0; c < cols; c++) + { + int i = (_vaultFirstRow + rr) * cols + c; + if (i >= cells) break; + var min = new Vector2(gridPos.X + c * cell, gridPos.Y + rr * cell); + CellPicture(dl, Art.GridEmpty, min, cell); + if (i >= items.Length) continue; + VaultItem it = items[i]; + if (ScriptIcons.TryGetItem(it.Icon, it.Underlay, it.Overlay, it.Effects, it.ItemType, out IntPtr tex)) + { + IconSampling.Begin(dl); + dl.AddImage(tex, min, min + new Vector2(cell, cell)); + IconSampling.End(dl); + } + else + dl.AddRectFilled(min, min + new Vector2(cell, cell), Placeholder, 2); + if (it.Stack > 1) + { + string st = it.Stack.ToString(CultureInfo.InvariantCulture); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(st); + var tp = new Vector2(min.X + cell - ts.X - 1, min.Y + cell - ts.Y); + dl.AddText(tp + Vector2.One, StackShadow, st); + dl.AddText(tp, StackCol, st); + } + } + } + ImGuiNET.ImGui.PopFont(); + + if (hovered && hoverCell >= 0 && hoverCell < items.Length) + { + VaultItem hot = items[hoverCell]; + ImGuiNET.ImGui.SetTooltip(hot.Stack > 1 ? $"{hot.Name} ({hot.Stack:N0})" : hot.Name); + if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) + { + _vaultCtx = hot; + _openVaultCtx = true; + } + } + else if (snap == null && !VaultFeed.Awaiting) + { + dl.AddText(gridPos + new Vector2(4, 22 * s), Mute, VaultFeed.Unsupported ? "The vault is not open on this server yet." : "Click Refresh to read the vault."); + } + + if (_openVaultCtx) + { + _openVaultCtx = false; + ImGuiNET.ImGui.OpenPopup("##vault_ctx"); + } + PushMenuStyle(); + if (ImGuiNET.ImGui.BeginPopup("##vault_ctx")) + { + VaultItem? it = _vaultCtx; + if (it == null) ImGuiNET.ImGui.CloseCurrentPopup(); + else + { + ImGuiNET.ImGui.TextDisabled(it.Name); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Withdraw", "", false, VaultFeed.Available)) + VaultFeed.Withdraw(it); + } + ImGuiNET.ImGui.EndPopup(); + } + PopMenuStyle(); + + if (snap != null) // nothing to scroll before the vault has been read + Scrollbar("##inv_vaultsb", new Vector2(gridPos.X + gridW, gridPos.Y), rows * cell, s, ref _vaultFirstRow, totalRows, rows); + } + // ── Status strip: the action / outcome (or pyreals), Drop, Give ───── private void StatusStrip(InventoryView view, ImDrawListPtr dl, Vector2 p, float w, float h, float s) @@ -736,17 +929,36 @@ internal sealed partial class InventoryFace dl.AddRect(min, min + new Vector2(size, size), fallback, 2, ImDrawFlags.None, 1.5f); } - private static void CenterText(ImDrawListPtr dl, ImFontPtr f, string text, Vector2 pos, Vector2 size, uint color) + /// + /// Text centred in a box. is the drawn size in screen pixels (retail's text is a fixed + /// size per 32 px cell, so callers pass N * the layout scale); 0 = the font's own size times the panel size. + /// + private static void CenterText(ImDrawListPtr dl, ImFontPtr f, string text, Vector2 pos, Vector2 size, uint color, float px = 0f) { if (text.Length == 0) return; + float drawPx = px > 0f ? px : f.FontSize * InventorySettingsStore.SizeFactor; ImGuiNET.ImGui.PushFont(f); Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text); ImGuiNET.ImGui.PopFont(); + ts *= drawPx / f.FontSize; dl.PushClipRect(pos, pos + size, true); - dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, new Vector2(pos.X + (size.X - ts.X) * 0.5f, pos.Y + (size.Y - ts.Y) * 0.5f), color, text); + dl.AddText(f, drawPx, new Vector2(pos.X + (size.X - ts.X) * 0.5f, pos.Y + (size.Y - ts.Y) * 0.5f), color, text); dl.PopClipRect(); } + private long _fitAtMs; + + /// Asks the host to make the panel exactly wide (screen px) when it is not; at most twice a second. + private void FitWidth(Vector2 size, float wantPx) + { + if (ImGuiPopOuts.InPopOutFrame || Math.Abs(size.X - wantPx) <= 4f) return; + long now = Environment.TickCount64; + if (now - _fitAtMs < 500) return; + _fitAtMs = now; + float place = ImGuiPanelHost.PlacementScale(); + ImGuiPanelHost.RequestSize(Title, new Vector2(wantPx / place, size.Y / place)); + } + private static bool MouseIn(Vector2 min, Vector2 max) { Vector2 m = ImGuiNET.ImGui.GetMousePos(); @@ -768,7 +980,7 @@ internal static class InventorySettingsStore public static bool Classic { get; private set; } = true; /// Classic view: the search / sort / category row under the title bar. public static bool ShowTools { get; private set; } - /// The panel's size in percent of the UI scale (50-150, steps of 10); text follows it. + /// The panel's size in percent of the UI scale (50-150, steps of 5); text follows it. public static int SizePct { get; private set; } = 80; public static float SizeFactor => SizePct / 100f; @@ -809,7 +1021,7 @@ internal static class InventorySettingsStore public static void StepSize(int dir) { - int next = Math.Clamp(SizePct + 10 * Math.Sign(dir), 50, 150); + int next = Math.Clamp(SizePct + 5 * Math.Sign(dir), 50, 150); if (next == SizePct) return; SizePct = next; Save(); diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index 296dbe0..ddedcef 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -42,8 +42,12 @@ internal sealed partial class InventoryFace : IImGuiPanel public const string Title = "Inventory"; // Default: the Classic view at its retail size (300 x 362 body, plus the status strip). + // Chromeless: the Classic look has the retail title bar (drag, close) and the Modern look + // draws its own background, drag area and close button, so the engine's DRAG header would + // be a second title bar. public static void Register() => ImGuiPanelHost.Register(Title, - new PanelSpec(new Vector2(302, 426), new Vector2(240, 300), EdgeToEdge: true), + new PanelSpec(new Vector2(302, 426), new Vector2(140, 300), PanelChrome.None, + Background: 0, Rounding: 0, EdgeToEdge: true), () => new InventoryFace()); // ── Layout (px, like the other faces) ─────────────────────────────── @@ -78,6 +82,10 @@ internal sealed partial class InventoryFace : IImGuiPanel private int _builtSort = -1, _builtCategory = -1; private string _builtSearch = "\0"; private bool _builtClassic; + private int _builtOrderVersion = -1; + // The shown list follows the server's slot order for this pack (so a cell is a slot). + private bool _orderKnown; + private readonly Dictionary _rank = new(); // Leave pack-slot items (foci) out of this list: the Classic main pack grid (they're in the side column). private bool _skipSlotItems; private string _countText = string.Empty; @@ -93,7 +101,7 @@ internal sealed partial class InventoryFace : IImGuiPanel // PackSlots: the Classic side column's pack slots (Id = the main pack): only a // pack-slot item (a focus) goes there, which moves it to the main pack. private enum DropKind : byte { None, Pack, Equip, Drop, Give, Slot, PackSlots } - private struct Target { public Vector2 Min, Max; public DropKind Kind; public uint Id; public string Name; } + private struct Target { public Vector2 Min, Max; public DropKind Kind; public uint Id; public string Name; public int Slot; } private readonly List _targets = new(16); // Context menu and split dialog (opened at the end of Draw, outside any child). @@ -168,6 +176,8 @@ internal sealed partial class InventoryFace : IImGuiPanel private void ModernBody(InventoryView view, Vector2 origin, Vector2 size, float w) { if (_pack != AllPacks && _pack != WornPacks && view.PackOf(_pack) == null) _pack = AllPacks; + ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(origin, origin + size, RynthTheme.PanelGlass, 6); + ImGuiNET.ImGui.GetWindowDrawList().AddRect(origin, origin + size, RynthTheme.PanelBorder, 6); RebuildIfNeeded(view, _pack); // the header shows the count Header(view, w); Tools(w); @@ -207,14 +217,28 @@ internal sealed partial class InventoryFace : IImGuiPanel PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Coins, new Vector2(x, p.Y), new Vector2(18, RowH), Amber); dl.AddText(new Vector2(x + 20, ty), Text, view.PyrealText); + // Close (the engine's header is off for this panel). + if (IconButton("##inv_close", PhosphorIcons.X, new Vector2(p.X + w - 22, p.Y + 1), new Vector2(22, 22), Amber, BtnFill, font: UiFont.Ui11)) + ImGuiPanelHost.Close(Title); + ImGuiNET.ImGui.SetItemTooltip("Close"); + // Switch to the Classic (retail) look. - var tb = new Vector2(p.X + w - 22, p.Y + 1); + var tb = new Vector2(p.X + w - 46, p.Y + 1); if (IconButton("##inv_classic", PhosphorIcons.AppWindow, tb, new Vector2(22, 22), Amber, BtnFill, font: UiFont.Ui11)) InventorySettingsStore.SetClassic(true); ImGuiNET.ImGui.SetItemTooltip("Classic look (the retail inventory window)"); float cw = ImGuiNET.ImGui.CalcTextSize(_countText).X; dl.AddText(new Vector2(tb.X - cw - 6, ty), Mute, _countText); + + // Drag surface: the empty part of the header, between the pyreals and the count. + float dragFrom = x + 20 + ImGuiNET.ImGui.CalcTextSize(view.PyrealText).X + 6, dragTo = tb.X - cw - 10; + if (dragTo > dragFrom) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(dragFrom, p.Y)); + ImGuiNET.ImGui.InvisibleButton("##inv_drag", new Vector2(dragTo - dragFrom, RowH)); + ImGuiPanelHost.DragWindowWithLastItem(); + } NextLine(p, RowH + 2); } @@ -293,7 +317,8 @@ internal sealed partial class InventoryFace : IImGuiPanel { bool classic = InventorySettingsStore.Classic; if (ReferenceEquals(view, _builtFor) && _builtPack == pack && _builtSort == _sort - && _builtCategory == _category && ReferenceEquals(_builtSearch, _searchText) && _builtClassic == classic) + && _builtCategory == _category && ReferenceEquals(_builtSearch, _searchText) && _builtClassic == classic + && _builtOrderVersion == Net.InventoryOrder.Version) return; if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category) _gridFirstRow = 0; // another pack or filter: back to the top (Classic grid) @@ -303,6 +328,7 @@ internal sealed partial class InventoryFace : IImGuiPanel _builtCategory = _category; _builtSearch = _searchText; _builtClassic = classic; + _builtOrderVersion = Net.InventoryOrder.Version; _shown.Clear(); InventoryPack? one = pack == WornPacks || pack == AllPacks ? null : view.PackOf(pack); @@ -323,6 +349,7 @@ internal sealed partial class InventoryFace : IImGuiPanel _ => null, // pack order: as captured (packs in order, ascending id inside each) }; if (cmp != null) _shown.Sort(cmp); + else ApplyServerOrder(one); int total = pack == WornPacks ? view.Worn.Length : one == null ? view.ItemCount : _skipSlotItems ? one.Used : one.Items.Length; @@ -336,6 +363,40 @@ internal sealed partial class InventoryFace : IImGuiPanel : "Contents of " + one.Name; } + + /// + /// Pack order = the server's: the list ACE sent for this pack (Net/InventoryOrder), so cell k is + /// slot k. A pack whose list was never seen (a side pack not opened yet, or an engine that + /// reloaded after login) stays in id order and says so: drops there + /// take the first empty slot, as before. + /// + private void ApplyServerOrder(InventoryPack? pack) + { + _orderKnown = false; + if (pack == null || !Net.InventoryOrder.TryGetOrder(pack.Id, false, out uint[] items)) return; + Net.InventoryOrder.TryGetOrder(pack.Id, true, out uint[] slots); + _rank.Clear(); + for (int i = 0; i < items.Length; i++) _rank[items[i]] = i; + for (int i = 0; i < slots.Length; i++) _rank[slots[i]] = 1_000_000 + i; + _shown.Sort((a, b) => + { + int ra = _rank.TryGetValue(a.Id, out int x) ? x : int.MaxValue, rb = _rank.TryGetValue(b.Id, out int y) ? y : int.MaxValue; + return ra != rb ? ra.CompareTo(rb) : a.Id.CompareTo(b.Id); + }); + _orderKnown = true; + } + + /// A grid cell is a slot only while the list is the server's, whole and in pack order, and the item is an ordinary one. + private bool CellsAreSlots(InventoryItem item) => + _orderKnown && _sort == 0 && _category == 0 && _searchText.Length == 0 && !item.RequiresPackSlot && !item.IsPack; + + /// The slot an item holds now among its pack's ordinary items, or -1 when unknown. + private static int SlotOf(InventoryItem item) + { + if (!Net.InventoryOrder.TryGetOrder(item.Container, false, out uint[] ids)) return -1; + return Array.IndexOf(ids, item.Id); + } + private static int ByName(InventoryItem a, InventoryItem b) { int c = string.CompareOrdinal(a.SearchName, b.SearchName); @@ -535,7 +596,11 @@ internal sealed partial class InventoryFace : IImGuiPanel private static void DrawItemIcon(ImDrawListPtr dl, uint objectId, Vector2 min, float size, uint tint = 0xFFFFFFFF) { if (ScriptIcons.TryGet(ScriptIconKind.Object, objectId, out IntPtr tex)) + { + IconSampling.Begin(dl); // retail draws icons crisp dl.AddImage(tex, min, min + new Vector2(size, size), Vector2.Zero, Vector2.One, tint); + IconSampling.End(dl); + } else dl.AddRectFilled(min, min + new Vector2(size, size), Placeholder, 2); } @@ -661,11 +726,11 @@ internal sealed partial class InventoryFace : IImGuiPanel // ── Actions ───────────────────────────────────────────────────────── - private void Act(InventoryActionKind kind, InventoryItem item, uint target, string targetName, int amount) + private void Act(InventoryActionKind kind, InventoryItem item, uint target, string targetName, int amount, int slot = -1) { var req = new InventoryRequest { - Kind = kind, ItemId = item.Id, TargetId = target, TargetName = targetName, Amount = amount, ItemName = item.Name, + Kind = kind, ItemId = item.Id, TargetId = target, TargetName = targetName, Amount = amount, ItemName = item.Name, Slot = slot, }; if (!InventoryModel.Request(req, out string why)) { @@ -678,11 +743,25 @@ internal sealed partial class InventoryFace : IImGuiPanel } } - private void DropOn(DropKind kind, uint targetId, string targetName, InventoryItem item) + private void DropOn(DropKind kind, uint targetId, string targetName, InventoryItem item, int slot = -1) { switch (kind) { case DropKind.Pack: + if (slot == -2) + { + Refuse(_sort != 0 || _category != 0 || _searchText.Length > 0 + ? "To reorder, set Sort to Pack order and clear the search and filter." + : "The pack's order isn't known yet: log in again so the panel can learn it."); + return; + } + if (slot >= 0) + { + // Dropped on a cell of the grid: that slot in the pack, which is also a reorder inside it. + if (item.Container == targetId && item.Wielder == 0 && SlotOf(item) == slot) return; // already there + Act(InventoryActionKind.Move, item, targetId, targetName, 0, slot); + break; + } if (item.Container == targetId && item.Wielder == 0) return; // same pack: nothing to do if (item.RequiresPackSlot && targetId != InventoryModel.Current.PlayerId) { @@ -723,6 +802,14 @@ internal sealed partial class InventoryFace : IImGuiPanel } } + /// Back to everything: no search text, no category. + private void ClearFilters() + { + Array.Clear(_search); + _searchText = string.Empty; + _category = 0; + } + private void Refuse(string why) { _refusal = why; @@ -755,7 +842,7 @@ internal sealed partial class InventoryFace : IImGuiPanel foreach (Target t in _targets) { if (m.X < t.Min.X || m.Y < t.Min.Y || m.X >= t.Max.X || m.Y >= t.Max.Y) continue; - DropOn(t.Kind, t.Id, t.Name, item); + DropOn(t.Kind, t.Id, t.Name, item, t.Slot); return; } // Let go outside this panel: another engine panel that takes items (Item Count, diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index 50c90a6..3207e01 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -3,7 +3,7 @@ // ImGui face of the RynthAi dashboard (docs/IMGUI_PARITY_PLAN.md §2.1), // first laid out from the Avalonia face (UI/Panels/RynthAiPanel.cs), then // made compact with Phosphor icons, after DrakBot's dashboard. Top to bottom: -// title row RYNTHAI DASHBOARD | target, vitals, lock, opacity -/+, +// title row RYNTH | target, vitals, lock, opacity -/+, // minimize, pop out // header grid popped out only: meta state, bot activity | pickers (docked, // they are the Loaded files drawer) @@ -168,7 +168,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel } } - // ── Title row: "R" + "YNTHAI DASHBOARD" | chips (drag surface) ────── + // ── Title row: "R" + "YNTH" | chips (drag surface) ────── private void TitleRow(RynthAiSnapshot raw, float x0, float width, bool minimized) { @@ -189,7 +189,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel dl.PushClipRect(new Vector2(x0, y), new Vector2(x0 + Math.Max(1, width - chipsW - 4), y + rowH), true); dl.AddText(title, title.FontSize, new Vector2(x0, ty), Teal, "R"); float rw = CalcWidth(title, "R"); - dl.AddText(title, title.FontSize, new Vector2(x0 + rw, ty), White, "YNTHAI DASHBOARD"); + dl.AddText(title, title.FontSize, new Vector2(x0 + rw, ty), White, "YNTH"); dl.PopClipRect(); float cx = x0 + width - chipsW; diff --git a/src/RynthCore.Engine/ImGui/ScriptIcons.cs b/src/RynthCore.Engine/ImGui/ScriptIcons.cs index d2db463..f764315 100644 --- a/src/RynthCore.Engine/ImGui/ScriptIcons.cs +++ b/src/RynthCore.Engine/ImGui/ScriptIcons.cs @@ -55,10 +55,11 @@ internal static class ScriptIcons private static readonly long FailedRetryTicks = Stopwatch.Frequency * 30; // an icon that didn't decode private static readonly long BudgetRetryTicks = Stopwatch.Frequency * 2; // no room in the byte budget - private const uint StypeIcon = 8, StypeIconOverlay = 50, StypeIconUnderlay = 52; + private const uint StypeIcon = 8, StypeIconOverlay = 50, StypeIconUnderlay = 52, StypeUiEffects = 18, StypeItemType = 1; /// What one picture is made of: icon, underlay and overlay texture ids (0 = none). - private readonly record struct Layers(uint Icon, uint Underlay, uint Overlay); + // Effects / ItemType (Object icons only) pick the plate the icon is drawn on when the server sent no underlay. + private readonly record struct Layers(uint Icon, uint Underlay, uint Overlay, uint Effects = 0, uint ItemType = 0); /// One asked-for (kind, id): the layers it resolved to. private sealed class Slot @@ -198,6 +199,34 @@ internal static class ScriptIcons return false; } + /// + /// The texture for an item given as its layers rather than as a live object (the vault's items): the + /// icon on the plate its type / effects ask for, with underlay and overlay, as an object would be drawn. + /// False until it is ready (the work is queued). AC's render thread. + /// + public static bool TryGetItem(uint icon, uint underlay, uint overlay, uint effects, uint itemType, out IntPtr texture) + { + texture = IntPtr.Zero; + if (icon == 0) return false; + long now = Stopwatch.GetTimestamp(); + var layers = new Layers(AcIconDecoder.NormalizeIconId(icon), underlay, overlay, effects, itemType); + if (!Textures.TryGetValue(layers, out Texture? tex)) + { + tex = new Texture(); + Textures[layers] = tex; + } + tex.LastUsed = _frame; + if (tex.Ptr != IntPtr.Zero) + { + texture = tex.Ptr; + return true; + } + if (!tex.Pending && (tex.FailedAt == 0 || now - tex.FailedAt >= tex.RetryTicks) + && Enqueue(new Request(Work.Decode, ScriptIconKind.Object, icon, layers, _generation))) + tex.Pending = true; + return false; + } + /// /// Start of the ImGui frame, before anything draws: creates the textures decoded since /// the last frame (at most 8) and evicts the least recently drawn ones over the cap. @@ -419,7 +448,9 @@ internal static class ScriptIcons return new Result(Work.Resolve, key, default, false, null, r.Generation); ClientObjectHooks.TryGetObjectDataIdProperty(r.Id, StypeIconUnderlay, out uint under); ClientObjectHooks.TryGetObjectDataIdProperty(r.Id, StypeIconOverlay, out uint over); - return new Result(Work.Resolve, key, new Layers(icon, under, over), true, null, r.Generation); + ClientObjectHooks.TryGetObjectIntProperty(r.Id, StypeUiEffects, out int effects); + ClientObjectHooks.TryGetObjectIntProperty(r.Id, StypeItemType, out int itemType); + return new Result(Work.Resolve, key, new Layers(icon, under, over, unchecked((uint)effects), unchecked((uint)itemType)), true, null, r.Generation); } if (r.Kind == ScriptIconKind.Spell) { @@ -445,7 +476,9 @@ internal static class ScriptIcons RynthLog.UI($"ScriptIcons: no icons ({why}); script windows draw placeholders."); } } - AcIconImage? image = dat == null ? null : AcIconDecoder.Compose(dat, r.Layers.Icon, r.Layers.Underlay, r.Layers.Overlay); + // An object's icon sits on its plate (the server's underlay, else the one its effects / type ask for). + uint under = dat != null && r.Kind == ScriptIconKind.Object ? AcIconPlates.For(dat, r.Layers.Underlay, r.Layers.Effects, r.Layers.ItemType) : r.Layers.Underlay; + AcIconImage? image = dat == null ? null : AcIconDecoder.Compose(dat, r.Layers.Icon, under, r.Layers.Overlay, dat != null && r.Kind == ScriptIconKind.Object ? AcIconPlates.RimFor(dat, r.Layers.Effects) : 0u); return new Result(Work.Decode, key, r.Layers, image != null, image, r.Generation); } } diff --git a/src/RynthCore.Engine/Net/AelrynthVaultWire.cs b/src/RynthCore.Engine/Net/AelrynthVaultWire.cs new file mode 100644 index 0000000..dad5fe1 --- /dev/null +++ b/src/RynthCore.Engine/Net/AelrynthVaultWire.cs @@ -0,0 +1,118 @@ +// ============================================================================ +// RynthCore.Engine - Net/AelrynthVaultWire.cs +// The Aelrynth account vault's wire format (the Aeshnidae.Mule mod's /mule-data). +// +// The vault is storage the retail client is never shown, so the only way to see inside is to ask: +// "/mule-data [page]" answers ONE chat line a page, "~ael1 " + JSON: +// +// {"t":"mule","ready":true,"page":1,"pages":3,"count":57,"max":1000,"items":[ +// {"o":objectId,"w":wcid,"n":name,"i":icon,"u":underlay,"v":overlay,"s":stack,"m":maxStack,"y":itemType,"e":uiEffects}, ...]} +// {"t":"mule","ready":false,"why":"loading"} (still loading on the server: never an empty vault) +// +// A field the reader does not know is ignored, so the mod can add fields. Pure code (no engine state); +// compiled into tools/NetMessageTests. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text.Json; + +namespace RynthCore.Engine.Net; + +/// One item in the vault, with what an icon needs. Immutable once parsed. +internal sealed class VaultItem +{ + public uint Id, Wcid, Icon, Underlay, Overlay, ItemType, Effects; + public int Stack = 1, MaxStack; + public string Name = string.Empty; +} + +/// One page of the vault as the server sent it. +internal sealed class VaultPage +{ + public bool Ready; + /// Why a not-ready reply was not ready ("loading", "closed", "fault", "error"). + public string Why = string.Empty; + public int Page = 1, Pages = 1, Count, Max; + public List Items = new(); +} + +internal static class AelrynthVaultWire +{ + /// The command as the engine sends it: talk text starting with @, which ACE runs as the command (ChatCommandDispatcher.SendServerCommand). + public const string Command = "@mule-data"; + public const string CommandName = "mule-data"; + private const string Prefix = "~ael1 "; + private const int MaxItemsPerPage = 200, MaxPages = 80; + + /// The command for a page (1 = the bare command). + public static string PageCommand(int page) => page <= 1 ? Command : Command + " " + page.ToString(System.Globalization.CultureInfo.InvariantCulture); + + /// A "~ael1" data line whose kind is "mule" (another mod's data line is not ours). + public static bool IsMuleLine(string? line) + { + if (string.IsNullOrEmpty(line)) return false; + int at = line.IndexOf(Prefix, StringComparison.Ordinal); + return at >= 0 && line.IndexOf("\"t\":\"mule\"", at, StringComparison.Ordinal) >= 0; + } + + /// ACE's reply to a command it does not have ("Unknown command: mule-data"). + public static bool IsUnknownCommand(string? line) + { + if (string.IsNullOrEmpty(line)) return false; + return line.IndexOf("Unknown command", StringComparison.OrdinalIgnoreCase) >= 0 + && line.IndexOf(CommandName, StringComparison.OrdinalIgnoreCase) >= 0; + } + + /// The page in a mule line; false when it is not one or is too damaged to read. + public static bool TryParse(string? line, out VaultPage page) + { + page = new VaultPage(); + if (!IsMuleLine(line)) return false; + try + { + int at = line!.IndexOf(Prefix, StringComparison.Ordinal) + Prefix.Length; + using JsonDocument doc = JsonDocument.Parse(line.AsMemory(at)); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return false; + + page.Ready = root.TryGetProperty("ready", out JsonElement r) && r.ValueKind == JsonValueKind.True; + page.Why = Str(root, "why"); + if (!page.Ready) return true; + + page.Page = Math.Max(1, Int(root, "page", 1)); + page.Pages = Math.Min(Math.Max(1, Int(root, "pages", 1)), MaxPages); + page.Count = Math.Max(0, Int(root, "count", 0)); + page.Max = Math.Max(0, Int(root, "max", 0)); + if (root.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement e in items.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.Object) continue; + if (page.Items.Count >= MaxItemsPerPage) break; + page.Items.Add(new VaultItem + { + Id = UInt(e, "o"), Wcid = UInt(e, "w"), Name = Str(e, "n"), + Icon = UInt(e, "i"), Underlay = UInt(e, "u"), Overlay = UInt(e, "v"), + Stack = Math.Max(1, Int(e, "s", 1)), MaxStack = Int(e, "m", 0), + ItemType = UInt(e, "y"), Effects = UInt(e, "e"), + }); + } + } + return true; + } + catch (JsonException) + { + return false; + } + } + + private static int Int(JsonElement e, string name, int fallback) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback; + + private static uint UInt(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetUInt32(out uint u) ? u : 0u; + + private static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; +} diff --git a/src/RynthCore.Engine/Net/InventoryOrder.cs b/src/RynthCore.Engine/Net/InventoryOrder.cs new file mode 100644 index 0000000..79477fe --- /dev/null +++ b/src/RynthCore.Engine/Net/InventoryOrder.cs @@ -0,0 +1,320 @@ +// ============================================================================ +// RynthCore.Engine - Net/InventoryOrder.cs +// The order of the items in each of the player's containers, as the SERVER keeps it. +// +// Why: retail lets a drop name a slot in a pack (PutItemInContainer carries a placement), and +// the Inventory panel's grid is that order. The client's PWD snapshot only knows which +// container an item is in, so the panel had the items by id: a drop on cell k could not be +// turned into a placement. The server's order is sent in three places, and all three are +// read here from the reassembled message stream (ServerMessageStream), read-only: +// +// PlayerDescription (event 0x0013) the main pack, in PlacementPosition order: first the +// ordinary items, then the side packs and foci. At login. +// ViewContents (event 0x0196) a pack the player opened, same order. +// InventoryPutObjInContainer (0x0022) an item landed in a container at a placement. +// InventoryRemoveObject (0x0024) / DeleteObject (0xF747): the item left. +// +// ACE keeps the positions contiguous (0..n-1, renumbered at load, shifted down on a removal and +// up on an add), and orders items and "pack-slot" things (side packs, foci) separately, so a +// list here is one container's one kind and an add is "remove from wherever it was, insert at +// the placement". Sending placement = the index the item should end at (counted without it) +// therefore lands it exactly there. +// +// A container is only "known" once a full list for it was seen: a drop on a container this +// has not seen a list for falls back to the first-empty-slot move, never to a guess. +// +// Pure code (no engine state); compiled into tools/NetMessageTests. Any thread. +// ============================================================================ + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Threading; + +namespace RynthCore.Engine.Net; + +internal static class InventoryOrder +{ + public const uint GameEventOpcode = 0xF7B0, DeleteObjectOpcode = 0xF747, InventoryRemoveOpcode = 0x0024; + public const uint EventPlayerDescription = 0x0013, EventPutObjInContainer = 0x0022, EventViewContents = 0x0196; + + /// ContainerType on the wire: 0 ordinary item, 1 side pack, 2 foci. 1 and 2 are the "pack slot" kind. + private static bool SlotKind(uint containerType) => containerType != 0; + + /// Object ids are far above any count, type or mask; it keeps those from passing for ids. + private const uint MinId = 0x1000; + + private static readonly object Gate = new(); + // (container, slotKind) -> ids in server order. A key is present only for a list seen in full. + private static readonly Dictionary<(uint, bool), List> Lists = new(); + private static int _version; + // Containers other than the player's own (corpses, chests, packs once opened) are kept least-recently-seen out. + private const int MaxLists = 64; + private static uint _player; + private static long _clock; + private static readonly Dictionary Touched = new(); + + /// Changes whenever any list changed (a cheap "rebuild your view" check). + public static int Version => Volatile.Read(ref _version); + + public static void Reset() + { + lock (Gate) { Lists.Clear(); Touched.Clear(); _player = 0; _version++; } + } + + /// + /// The server's order of 's ordinary items (or, with + /// , its side packs and foci). False when no full list was seen. + /// + public static bool TryGetOrder(uint container, bool slotKind, out uint[] ids) + { + lock (Gate) + { + if (Lists.TryGetValue((container, slotKind), out List? l)) { ids = l.ToArray(); return true; } + } + ids = Array.Empty(); + return false; + } + + /// + /// One whole server message, starting at its opcode (the way ServerMessageStream delivers it). + /// Anything else is ignored; a malformed one is dropped. + /// + public static void Observe(ReadOnlySpan msg) + { + if (msg.Length < 8) return; + uint opcode = U32(msg, 0); + try + { + if (opcode == GameEventOpcode) + { + if (msg.Length < 16) return; + uint ev = U32(msg, 12); + if (ev == EventPlayerDescription) OnPlayerDescription(U32(msg, 4), msg.Slice(16)); + else if (ev == EventViewContents) OnViewContents(msg.Slice(16)); + else if (ev == EventPutObjInContainer) OnPut(msg.Slice(16)); + } + else if (opcode == InventoryRemoveOpcode || opcode == DeleteObjectOpcode) + OnGone(U32(msg, 4)); + } + catch (ArgumentOutOfRangeException) { } + } + + // ── Keeping it across an engine reload ────────────────────────────────── + // The login message is the only place the main pack's order arrives, and a hot reload of the engine + // (every deploy, and any crash recovery) would lose it until the next login. So the lists are + // saved as they change and read back when the engine starts. Layout: 'IORD', version u32, list count + // u32, then per list: container u32, slot-kind u8, count u32, ids u32 each. + + private const uint Magic = 0x44524F49; // "IORD" + + public static byte[] Serialize() + { + lock (Gate) + { + var ms = new System.IO.MemoryStream(); + var w = new System.IO.BinaryWriter(ms); + w.Write(Magic); w.Write(1u); w.Write((uint)Lists.Count); + foreach (KeyValuePair<(uint, bool), List> kv in Lists) + { + w.Write(kv.Key.Item1); w.Write(kv.Key.Item2 ? (byte)1 : (byte)0); w.Write((uint)kv.Value.Count); + foreach (uint id in kv.Value) w.Write(id); + } + w.Flush(); + return ms.ToArray(); + } + } + + /// Replaces the lists with a saved set. False (nothing changed) when the data is not one. + public static bool Restore(ReadOnlySpan data) + { + try + { + if (data.Length < 12 || U32(data, 0) != Magic || U32(data, 4) != 1) return false; + uint lists = U32(data, 8); + if (lists > 4096) return false; + int at = 12; + var loaded = new Dictionary<(uint, bool), List>(); + for (uint i = 0; i < lists; i++) + { + if (at + 9 > data.Length) return false; + uint container = U32(data, at); bool slot = data[at + 4] != 0; uint n = U32(data, at + 5); + at += 9; + if (n > 100000 || at + (long)n * 4 > data.Length) return false; + var l = new List((int)n); + for (uint k = 0; k < n; k++) { l.Add(U32(data, at)); at += 4; } + loaded[(container, slot)] = l; + } + lock (Gate) + { + Lists.Clear(); + Touched.Clear(); + foreach (KeyValuePair<(uint, bool), List> kv in loaded) { Lists[kv.Key] = kv.Value; Touched[kv.Key.Item1] = ++_clock; } + Evict(); + _version++; + } + return true; + } + catch (ArgumentOutOfRangeException) { return false; } + } + + // ── ViewContents: container, count, count x (id, type) ────────────────── + + private static void OnViewContents(ReadOnlySpan p) + { + if (p.Length < 8) return; + uint container = U32(p, 0); + uint count = U32(p, 4); + if (count > 4096 || p.Length < 8 + (long)count * 8) return; + var items = new List((int)count); + var slots = new List(); + for (int i = 0; i < count; i++) + { + uint id = U32(p, 8 + i * 8), type = U32(p, 12 + i * 8); + if (id == 0 || type > 2) return; + (SlotKind(type) ? slots : items).Add(id); + } + lock (Gate) + { + RemoveEverywhere(container, items, slots); + Lists[(container, false)] = items; + Lists[(container, true)] = slots; + Touched[container] = ++_clock; + Evict(); + _version++; + } + } + + // ── PlayerDescription: ... inventory count, n x (id, type), worn count, e x (id, loc, priority) ── + + private static void OnPlayerDescription(uint player, ReadOnlySpan p) + { + if (!TryFindContents(p, out int invAt, out int n)) return; + var items = new List(n); + var slots = new List(); + for (int i = 0; i < n; i++) + { + uint id = U32(p, invAt + 4 + i * 8), type = U32(p, invAt + 8 + i * 8); + (SlotKind(type) ? slots : items).Add(id); + } + lock (Gate) + { + Lists.Clear(); // a login: nothing seen before it counts + Touched.Clear(); + _player = player; + Lists[(player, false)] = items; + Lists[(player, true)] = slots; + Touched[player] = ++_clock; + _version++; + } + } + + /// + /// The inventory list sits at the END of PlayerDescription, before the worn list that closes it; + /// everything before it is a long run of options and tables that is not worth parsing for this. + /// So the tail is read backwards: a worn count e with e x 12 bytes after it, and before that an + /// inventory count n with n x 8 bytes, every id non-zero and every type 0..2. Both counts being + /// where they must be and every entry being sane is not something noise does by accident. + /// + internal static bool TryFindContents(ReadOnlySpan p, out int invAt, out int n) + { + invAt = 0; n = 0; + for (int e = 0; e <= 256; e++) + { + int wornAt = p.Length - 12 * e - 4; + if (wornAt < 4) break; + if (U32(p, wornAt) != (uint)e) continue; + if (!WornSane(p, wornAt, e)) continue; + int maxN = (wornAt - 4) / 8; + // Largest first: a shorter list can match too (a pack-type word of 1 reads as a count of 1). + for (int cand = Math.Min(maxN, 4096); cand >= 0; cand--) + { + int at = wornAt - 8 * cand - 4; + if (U32(p, at) != (uint)cand) continue; + if (!InventorySane(p, at, cand)) continue; + invAt = at; n = cand; + return true; + } + } + return false; + } + + private static bool WornSane(ReadOnlySpan p, int wornAt, int e) + { + for (int i = 0; i < e; i++) + if (U32(p, wornAt + 4 + i * 12) < MinId || U32(p, wornAt + 8 + i * 12) == 0) return false; + return true; + } + + private static bool InventorySane(ReadOnlySpan p, int at, int n) + { + for (int i = 0; i < n; i++) + { + if (U32(p, at + 4 + i * 8) < MinId || U32(p, at + 8 + i * 8) > 2) return false; + } + return true; + } + + // ── Moves ─────────────────────────────────────────────────────────────── + + private static void OnPut(ReadOnlySpan p) + { + if (p.Length < 16) return; + uint item = U32(p, 0), container = U32(p, 4), type = U32(p, 12); + int placement = unchecked((int)U32(p, 8)); + bool slot = SlotKind(type); + lock (Gate) + { + RemoveItem(item); + if (Lists.TryGetValue((container, slot), out List? l)) + l.Insert(Math.Clamp(placement, 0, l.Count), item); + _version++; + } + } + + private static void OnGone(uint id) + { + if (id == 0) return; + lock (Gate) { if (RemoveItem(id)) _version++; } + } + + /// Drops the least recently seen containers beyond ; never the player's own. + private static void Evict() + { + while (Touched.Count > MaxLists) + { + uint oldest = 0; long at = long.MaxValue; + foreach (KeyValuePair kv in Touched) + if (kv.Key != _player && kv.Value < at) { at = kv.Value; oldest = kv.Key; } + if (oldest == 0) return; + Touched.Remove(oldest); + Lists.Remove((oldest, false)); + Lists.Remove((oldest, true)); + } + } + + private static bool RemoveItem(uint id) + { + bool any = false; + foreach (List l in Lists.Values) + { + int i = l.IndexOf(id); + if (i < 0) continue; + l.RemoveAt(i); + any = true; + } + return any; + } + + // A full list for a container replaces the old one; its items must not also sit in another list. + private static void RemoveEverywhere(uint container, List items, List slots) + { + foreach (KeyValuePair<(uint, bool), List> kv in Lists) + { + if (kv.Key.Item1 == container) continue; + kv.Value.RemoveAll(id => items.Contains(id) || slots.Contains(id)); + } + } + + private static uint U32(ReadOnlySpan s, int at) => BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(at, 4)); +} diff --git a/src/RynthCore.Engine/Net/ServerMessageStream.cs b/src/RynthCore.Engine/Net/ServerMessageStream.cs index 588834a..5125a9e 100644 --- a/src/RynthCore.Engine/Net/ServerMessageStream.cs +++ b/src/RynthCore.Engine/Net/ServerMessageStream.cs @@ -27,7 +27,7 @@ namespace RynthCore.Engine.Net; internal static unsafe class ServerMessageStream { - private const int RingBytes = 512 * 1024; + private const int RingBytes = 2 * 1024 * 1024; private const int MaxPacketsPerPump = 8192; private const long MaxCaptureBytes = 32L * 1024 * 1024; private const int MaxLogLinesPerKind = 5; @@ -40,6 +40,12 @@ internal static unsafe class ServerMessageStream private static bool _sessionOff; private static bool _pluginsWant; + /// + /// The engine itself wants the stream (the Inventory panel's server-order tracker, Net/InventoryOrder), + /// whether or not a plugin does. engine.json / /rc netmsg off still turn the stream off. + /// + public static volatile bool EngineWants = true; + // Delivery counters (pump thread). private static long _delivered, _dispatchedToPlugins; private static long _pumpTicksTotal, _pumpTicksMax, _pumps; @@ -68,6 +74,23 @@ internal static unsafe class ServerMessageStream // ── receive hook side ─────────────────────────────────────────────────── + /// + /// Starts copying datagrams as soon as the receive hook is installed (RawPacketHooks.Initialize), when the + /// engine itself wants the stream. The pump only runs once the world is up, and the server sends the + /// player's inventory order (PlayerDescription) while entering it: the ring holds that until the first pump. + /// + public static void EnableEarly() + { + try + { + if (!EngineWants || _sessionOff || !EngineSettings.ServerMessageStream || _capturing) return; + _ring ??= new PacketRing(RingBytes); + _capturing = true; + RynthLog.Compat("ServerMessageStream: capture on from the receive hook (the engine's own readers)."); + } + catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: early capture failed - {ex.GetType().Name}: {ex.Message}"); } + } + /// Called by the RecvFrom detour after the real recvfrom, with the bytes it returned. public static void OnDatagram(byte* data, int length) { @@ -88,15 +111,50 @@ internal static unsafe class ServerMessageStream /// Once per ProcessPendingActions (the single TickAll driver). : /// some initialized plugin has a non-empty interest. /// + // The server's item order survives an engine reload (Net/InventoryOrder): saved per client process. + private static bool _orderRestored; + private static int _orderSavedVersion = -1; + private static long _orderSavedMs; + private static string OrderFile => Path.Combine(Path.GetTempPath(), $"RynthCore.invorder.{Environment.ProcessId}.bin"); + + private static void KeepInventoryOrder(long nowMs) + { + try + { + if (!_orderRestored) + { + _orderRestored = true; + string f = OrderFile; + // Only this client's own file, and not a stale one (a recycled process id). + if (File.Exists(f) && DateTime.UtcNow - File.GetLastWriteTimeUtc(f) < TimeSpan.FromHours(24) + && InventoryOrder.Restore(File.ReadAllBytes(f))) + RynthLog.Compat("ServerMessageStream: restored the server's item order saved before this engine loaded."); + _orderSavedVersion = InventoryOrder.Version; + return; + } + int v = InventoryOrder.Version; + if (v == _orderSavedVersion || nowMs - _orderSavedMs < 1500) return; + File.WriteAllBytes(OrderFile, InventoryOrder.Serialize()); + _orderSavedVersion = v; + _orderSavedMs = nowMs; + } + catch (Exception ex) + { + RynthLog.Compat($"ServerMessageStream: item order file failed - {ex.GetType().Name}: {ex.Message}"); + _orderSavedVersion = InventoryOrder.Version; // do not retry every pump + } + } + public static void Pump(bool pluginsWant) { + KeepInventoryOrder(Environment.TickCount64); _pluginsWant = pluginsWant; if (_captureStopRequested) { _captureStopRequested = false; StopCapture("stopped"); } - bool want = EngineSettings.ServerMessageStream && !_sessionOff && (pluginsWant || _logOn || _capture != null); + bool want = EngineSettings.ServerMessageStream && !_sessionOff && (pluginsWant || EngineWants || _logOn || _capture != null); if (want != _capturing) { if (want) @@ -156,6 +214,11 @@ internal static unsafe class ServerMessageStream try { LogTap(opcode, eventType, message, length); } catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: log tap failed - {ex.GetType().Name}: {ex.Message}"); } } + if (EngineWants) + { + try { InventoryOrder.Observe(new ReadOnlySpan(message, length)); } + catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: inventory order failed - {ex.GetType().Name}: {ex.Message}"); } + } if (_pluginsWant) _dispatchedToPlugins += PluginManager.DispatchServerMessage(opcode, eventType, message + 4, length - 4); } diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 0516ff5..d53a72a 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -651,7 +651,8 @@ internal sealed class ChatRouter internal static class ChatModel { /// Channel tabs; must match ChatClassifier in the plugin. - public static readonly string[] BaseTabs = { "All", "Chat", "Channels", "System", "Combat", "Rynth", "Other" }; + // Items (2026-10-09): RynthAi's item info, "[RynthAi Item] " (RynthChat's ChatClassifier.IsItemInfo). + public static readonly string[] BaseTabs = { "All", "Chat", "Channels", "System", "Combat", "Rynth", "Items", "Other" }; /// Channel tab colour as 0xAARRGGBB: the user's (Line colours in the chat /// settings), else the built-in one (ChatLineColors.BuiltInTabArgb). @@ -673,6 +674,7 @@ internal static class ChatModel ("chan:System", "System tab"), ("chan:Combat", "Combat tab (combat and magic)"), ("chan:Rynth", "Rynth tab (plugin output)"), + ("chan:Items", "Items tab (item info)"), ("chan:Other", "Other tab"), ("type:3", "Tells to you"), ("type:4", "Tells you send"), diff --git a/src/RynthCore.Engine/UI/Data/ChatLineColors.cs b/src/RynthCore.Engine/UI/Data/ChatLineColors.cs index 297ef35..1d14cea 100644 --- a/src/RynthCore.Engine/UI/Data/ChatLineColors.cs +++ b/src/RynthCore.Engine/UI/Data/ChatLineColors.cs @@ -39,7 +39,7 @@ internal static class ChatLineColors public const int MaxTagLength = 40; /// Channel tabs that have a colour (All has none); must match ChatModel.BaseTabs. - public static readonly string[] Tabs = { "Chat", "Channels", "System", "Combat", "Rynth", "Other" }; + public static readonly string[] Tabs = { "Chat", "Channels", "System", "Combat", "Rynth", "Items", "Other" }; /// The player-to-player kinds (ChatMessageType). public static readonly ChatColorKind[] ChatKinds = @@ -79,6 +79,7 @@ internal static class ChatLineColors "System" => 0xFF8CA6BF, "Combat" => 0xFFD93333, "Rynth" => 0xFFE6B450, // amber, distinct from the blue/grey channels + "Items" => 0xFF9FD8C8, // pale teal: RynthAi's item info (2026-10-09) _ => 0xFFAAAAAA, }; diff --git a/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs b/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs index 8096a6b..a3a03d9 100644 --- a/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs +++ b/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs @@ -217,10 +217,14 @@ internal static class AcIconDecoder /// the last (alpha blended) at the icon's size. 0 = no underlay / overlay. Null when the icon /// itself can't be decoded; an underlay or overlay that can't be is left out. /// - public static AcIconImage? Compose(AcDatFile dat, uint icon, uint underlay, uint overlay) + public static AcIconImage? Compose(AcDatFile dat, uint icon, uint underlay, uint overlay, uint rimTexture = 0) { AcIconImage? baseImage = Decode(dat, icon); if (baseImage == null) return null; + RepaintOutline(baseImage, BandDepth, rimTexture != 0 ? RimImage(dat, rimTexture) : null); + // The server gives some items (foci) an overlay that IS the icon. Drawn over the repainted icon it + // would bring the dat's white outline back, and it adds nothing the icon has not already drawn. + if (overlay == icon) overlay = 0; AcIconImage? under = underlay != 0 ? Decode(dat, underlay) : null; AcIconImage? over = overlay != 0 ? Decode(dat, overlay) : null; if (under == null && over == null) return baseImage; @@ -233,6 +237,97 @@ internal static class AcIconDecoder return new AcIconImage { Width = w, Height = h, Pixels = outPx }; } + /// The outline colour retail paints over an icon's authored white band (measured in AcClientReborn's IconOutline). + private const byte OutlineR = 0x30, OutlineG = 0x2D, OutlineB = 0x7B; + // The outline of an item with effects (magical, an element...) is not one colour: retail lets the dat's + // effect texture (AcIconPlates.RimFor: a vertical gradient, pale at the top to deep at the bottom) show + // through the icon's outline band, texel for texel. Read off a retail robe, whose outline runs from pale + // cyan at the head to deep blue at the hem, which is the blue effect texture 0x060011CA. + private static readonly Dictionary RimCache = new(); + + private static AcIconImage? RimImage(AcDatFile dat, uint id) + { + lock (RimCache) + { + if (!RimCache.TryGetValue(id, out AcIconImage? img)) + RimCache[id] = img = Decode(dat, id); + return img; + } + } + private const int BandDepth = 2; + + /// + /// The dat authors every icon's outline as near-white (pure white, or red on a gem) and retail + /// repaints it, so drawing the dat as-is leaves a white halo. The band is the near-white texels + /// within texels of the silhouette edge (a texel's distance is 1 when it + /// touches transparency, 2 when it touches one that does). It is a distance, not a chain from + /// the edge, because some art (the foci) has a one-texel dark shadow OUTSIDE its white band: the + /// white never touches transparency there, and an adjacency test left it white along that side. + /// The depth cap keeps a genuinely white item (a flame) from becoming a silhouette, and interior + /// highlights deeper than that survive. Measured over every 32x32 icon in 0x06000F00..0x06007000. + /// + internal static void RepaintOutline(AcIconImage img, int depth = BandDepth, AcIconImage? rim = null) + { + int w = img.Width, h = img.Height; + byte[] px = img.Pixels; + if (px.Length < w * h * 4) return; + bool Opaque(int x, int y) => x >= 0 && y >= 0 && x < w && y < h && px[(y * w + x) * 4 + 3] >= 128; + bool NearWhite(int x, int y) + { + int o = (y * w + x) * 4; + return px[o + 3] >= 128 && px[o] >= 226 && px[o + 1] >= 226 && px[o + 2] >= 226; + } + // Distance 1 = opaque and touching transparency (or the image edge); n = touching a distance n-1 texel. + var dist = new byte[w * h]; + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + if (Opaque(x, y) && !(Opaque(x - 1, y) && Opaque(x + 1, y) && Opaque(x, y - 1) && Opaque(x, y + 1))) + dist[y * w + x] = 1; + // One level past the band is taken only where it continues the band (a near-white texel + // touching a repainted one): art with a two-texel shadow outside its white leaves a straggler. + int reach = depth + 1; + for (int lvl = 2; lvl <= reach; lvl++) + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + { + if (dist[y * w + x] != 0 || !Opaque(x, y)) continue; + int prev = lvl - 1; + bool near = (x > 0 && dist[y * w + x - 1] == prev) || (x + 1 < w && dist[y * w + x + 1] == prev) + || (y > 0 && dist[(y - 1) * w + x] == prev) || (y + 1 < h && dist[(y + 1) * w + x] == prev); + if (near) dist[y * w + x] = (byte)lvl; + } + var band = new bool[w * h]; + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + if (dist[y * w + x] != 0 && dist[y * w + x] <= depth && NearWhite(x, y)) band[y * w + x] = true; + var extra = new List(); + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + { + if (dist[y * w + x] != reach || !NearWhite(x, y)) continue; + if ((x > 0 && band[y * w + x - 1]) || (x + 1 < w && band[y * w + x + 1]) + || (y > 0 && band[(y - 1) * w + x]) || (y + 1 < h && band[(y + 1) * w + x])) + extra.Add(y * w + x); + } + foreach (int i in extra) band[i] = true; + for (int i = 0; i < w * h; i++) + { + if (!band[i]) continue; + int o = i * 4; + if (rim != null && rim.Width > 0 && rim.Height > 0) + { + int x = i % w, y = i / w; + int ro = ((y * rim.Height / h) * rim.Width + x * rim.Width / w) * 4; + if (ro + 2 < rim.Pixels.Length) + { + px[o] = rim.Pixels[ro]; px[o + 1] = rim.Pixels[ro + 1]; px[o + 2] = rim.Pixels[ro + 2]; + continue; + } + } + px[o] = OutlineR; px[o + 1] = OutlineG; px[o + 2] = OutlineB; + } + } + /// Draws over (w x h), scaled nearest-neighbour when sizes differ. private static void Over(byte[] dst, int w, int h, AcIconImage src) { diff --git a/src/RynthCore.Engine/UI/ScriptWindows/AcIconPlates.cs b/src/RynthCore.Engine/UI/ScriptWindows/AcIconPlates.cs new file mode 100644 index 0000000..93af060 --- /dev/null +++ b/src/RynthCore.Engine/UI/ScriptWindows/AcIconPlates.cs @@ -0,0 +1,134 @@ +// ============================================================================ +// RynthCore.Engine - UI/ScriptWindows/AcIconPlates.cs +// What an item's icon is drawn ON. +// +// An AC item icon is a silhouette (24-83% of its texels are transparent), so retail composites it +// over an opaque 32x32 PLATE, and which plate is most of an item's colour on screen: armour blue, +// ammunition brown, pouches green, anything with spells blue. Nothing is hardcoded: two DID mappers +// in client_portal.dat answer it, 0x25000008 (ItemType -> plate) and 0x25000009 (UiEffects -> plate). +// Both key on the BIT INDEX plus one (MeleeWeapon 0x1 is key 1, Armor 0x2 is key 2 ...), and key 33 +// is the table's own "Default". +// +// The order they are asked in is the finding (AcClientReborn's IconPlates, measured against retail +// captures): the server's own IconUnderlay for the item wins outright; then the effect table +// (UiEffects is consulted BEFORE ItemType, which is why an enchanted item is blue and void gear is +// black); then the item-type table; then that table's Default. +// +// Mapper layout: file id u32, a numbering byte, a compressed count, count x (key u32, plate id u32), +// then names (not needed). Pure code over AcDatFile; the plate textures are ordinary 0x06 files. +// Thread: whatever thread owns the AcDatFile (the icon worker). +// ============================================================================ + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Numerics; + +namespace RynthCore.Engine.UI.ScriptWindows; + +internal static class AcIconPlates +{ + public const uint IconBackgrounds = 0x25000008u, EffectIcons = 0x25000009u; + private const uint DefaultKey = 33; + + private static Dictionary? _byType, _byEffect; + private static bool _loaded; + + /// The plate this item asks for; 0 when the dat has neither table (the icon is then drawn bare). + public static uint For(AcDatFile dat, uint underlay, uint uiEffects, uint itemType) + { + if (underlay != 0) return underlay; + Load(dat); + // The plate comes from the item type only: retail shows a magical item's armour on the same blue as + // a plain one. The effect table colours the OUTLINE instead (RimFor). + return PlateFor(underlay, 0, itemType, _byEffect, _byType); + } + + /// + /// The texture whose colours the icon's outline takes for these effects (0 = a plain item: the plain outline). + /// UiEffects keys the table by bit index + 1 (Magical is key 1 and the blue gradient); a bit the table has no + /// entry for takes its Default (black: why void gear has a black outline). + /// + public static uint RimFor(AcDatFile dat, uint uiEffects) + { + if (uiEffects == 0) return 0; + Load(dat); + if (_byEffect == null) return 0; + uint e = ForBit(_byEffect, uiEffects); + if (e != 0) return e; + return _byEffect.TryGetValue(DefaultKey, out uint d) ? d : 0; + } + + /// The lookup order, apart from the dat (testable). + internal static uint PlateFor(uint underlay, uint uiEffects, uint itemType, + Dictionary? effects, Dictionary? types) + { + if (underlay != 0) return underlay; + if (effects != null && uiEffects != 0) + { + uint e = ForBit(effects, uiEffects); + if (e != 0) return e; + // A UiEffects bit the table has no entry for takes the effect table's Default, not the + // item type's (this is why void gear is black). + if (effects.TryGetValue(DefaultKey, out uint ed) && ed != 0) return ed; + } + if (types != null) + { + uint t = ForBit(types, itemType); + if (t != 0) return t; + if (types.TryGetValue(DefaultKey, out uint td)) return td; + } + return 0; + } + + /// The lowest set bit decides (an item carries one ItemType in practice). + private static uint ForBit(Dictionary map, uint bits) + { + if (bits == 0) return 0; + uint key = (uint)BitOperations.TrailingZeroCount(bits) + 1; + return map.TryGetValue(key, out uint id) ? id : 0; + } + + private static void Load(AcDatFile dat) + { + if (_loaded) return; + _loaded = true; // one try per session: a dat without them draws bare icons + _byType = ReadMapper(dat.Read(IconBackgrounds, 64 * 1024)); + _byEffect = ReadMapper(dat.Read(EffectIcons, 64 * 1024)); + } + + /// A DID mapper file's key -> id pairs, or null when it does not parse. + internal static Dictionary? ReadMapper(byte[]? data) + { + if (data == null || data.Length < 9) return null; + try + { + int at = 5; // file id, numbering byte + uint n = Compressed(data, ref at); + if (n > 100000 || at + (long)n * 8 > data.Length) return null; + var map = new Dictionary((int)n); + for (uint i = 0; i < n; i++) + { + map[BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(at))] = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(at + 4)); + at += 8; + } + return map; + } + catch (ArgumentOutOfRangeException) + { + return null; + } + } + + /// AC's compressed uint: one byte when the top bit is clear, two when 0x80 is set, four when 0xC0 is. + private static uint Compressed(byte[] d, ref int at) + { + byte b0 = d[at++]; + if ((b0 & 0x80) == 0) return b0; + byte b1 = d[at++]; + if ((b0 & 0x40) == 0) return (uint)(((b0 & 0x7F) << 8) | b1); + int low = d[at] | (d[at + 1] << 8); // the low half is little-endian + at += 2; + return (uint)(((((b0 & 0x3F) << 8) | b1) << 16) | low); + } +} diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index b3bb012..2650fbf 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -318,10 +318,12 @@ internal static class Program private static uint OldChannelArgb(string chan) => chan switch { "Chat" => 0xFFE0E0E0, "Channels" => 0xFF7AB8F5, "System" => 0xFF8CA6BF, - "Combat" => 0xFFD93333, "Rynth" => 0xFFE6B450, _ => 0xFFAAAAAA, + "Combat" => 0xFFD93333, "Rynth" => 0xFFE6B450, + "Items" => 0xFF9FD8C8, // the Items tab, new 2026-10-09 (item info used to be in Rynth) + _ => 0xFFAAAAAA, }; - private static readonly string[] AllTabsAndOdd = { "Chat", "Channels", "System", "Combat", "Rynth", "Other", "Junk", "" }; + private static readonly string[] AllTabsAndOdd = { "Chat", "Channels", "System", "Combat", "Rynth", "Items", "Other", "Junk", "" }; private static void LineColorDefaultsUnchanged() { diff --git a/tools/NetMessageTests/InventoryOrderTests.cs b/tools/NetMessageTests/InventoryOrderTests.cs new file mode 100644 index 0000000..981b90d --- /dev/null +++ b/tools/NetMessageTests/InventoryOrderTests.cs @@ -0,0 +1,138 @@ +namespace NetMessageTests; +using System.Buffers.Binary; +using RynthCore.Engine.Net; + +// Net/InventoryOrder: the server's item order, read from PlayerDescription, ViewContents and +// InventoryPutObjInContainer. Messages are built the way ACE writes them +// (GameEventPlayerDescription / GameEventViewContents / GameEventItemServerSaysContainId). +internal static unsafe partial class Program +{ + private const uint Player = 0x50000001; + + private static byte[] GameEvent(uint ev, params uint[] payload) + { + var b = new byte[16 + payload.Length * 4]; + BinaryPrimitives.WriteUInt32LittleEndian(b, 0xF7B0); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4), Player); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8), 1); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(12), ev); + for (int i = 0; i < payload.Length; i++) BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(16 + i * 4), payload[i]); + return b; + } + + // junkWords of noise (options, tables, spells...), then the inventory list, then the worn list. + private static byte[] PlayerDescriptionMsg(int junkWords, uint[] inventory, uint[] types, int worn) + { + var w = new List(); + var rnd = new Random(junkWords + 1); + for (int i = 0; i < junkWords; i++) w.Add((uint)rnd.Next()); + w.Add((uint)inventory.Length); + for (int i = 0; i < inventory.Length; i++) { w.Add(inventory[i]); w.Add(types[i]); } + w.Add((uint)worn); + for (int i = 0; i < worn; i++) { w.Add(0x80001000u + (uint)i); w.Add(0x200u); w.Add(3); } + return GameEvent(0x0013, w.ToArray()); + } + + private static string Order(uint container, bool slots) => + InventoryOrder.TryGetOrder(container, slots, out uint[] ids) + ? string.Join(",", ids.Select(i => (i & 0xFFFF).ToString("X"))) + : "unknown"; + + private static byte[] MessageWithGuid(uint opcode, uint guid) + { + var b = new byte[8]; + BinaryPrimitives.WriteUInt32LittleEndian(b, opcode); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4), guid); + return b; + } + + private static void InventoryOrderTests() + { + Case("inventory order: PlayerDescription gives the main pack, items then pack-slot things"); + InventoryOrder.Reset(); + uint[] ids = { 0x80000001, 0x80000002, 0x80000003, 0x80000004, 0x80000005 }; + uint[] types = { 0, 0, 0, 1, 2 }; + InventoryOrder.Observe(PlayerDescriptionMsg(137, ids, types, 4)); + Eq(Order(Player, false), "1,2,3", "ordinary items in server order"); + Eq(Order(Player, true), "4,5", "side pack and focus, in their own list"); + + Case("inventory order: the tail is found whatever noise comes before it"); + for (int junk = 0; junk < 300; junk += 7) + { + InventoryOrder.Reset(); + InventoryOrder.Observe(PlayerDescriptionMsg(junk, ids, types, junk % 9)); + Eq(Order(Player, false), "1,2,3", $"junk {junk}"); + } + InventoryOrder.Reset(); + InventoryOrder.Observe(PlayerDescriptionMsg(20, Array.Empty(), Array.Empty(), 0)); + Eq(Order(Player, false), "", "an empty pack is a known, empty list"); + + Case("inventory order: a move puts the item at its placement, the others shift"); + InventoryOrder.Reset(); + InventoryOrder.Observe(PlayerDescriptionMsg(50, new uint[] { 0x80000001, 0x80000002, 0x80000003, 0x80000004 }, new uint[] { 0, 0, 0, 0 }, 2)); + InventoryOrder.Observe(GameEvent(0x0022, 0x80000001, Player, 2, 0)); + Eq(Order(Player, false), "2,3,1,4", "first item dropped on the third cell lands there"); + InventoryOrder.Observe(GameEvent(0x0022, 0x80000004, Player, 0, 0)); + Eq(Order(Player, false), "4,2,3,1", "last item to the front"); + InventoryOrder.Observe(GameEvent(0x0022, 0x80000002, Player, 99, 0)); + Eq(Order(Player, false), "4,3,1,2", "a placement past the end is the end"); + + Case("inventory order: between containers; an unseen container is not guessed"); + uint pack = 0x80000100; + InventoryOrder.Observe(GameEvent(0x0196, pack, 2, 0x80000200, 0, 0x80000201, 0)); + Eq(Order(pack, false), "200,201", "ViewContents gives the open pack"); + InventoryOrder.Observe(GameEvent(0x0022, 0x80000004, pack, 1, 0)); + Eq(Order(pack, false), "200,4,201", "moved into the pack at 1"); + Eq(Order(Player, false), "3,1,2", "and gone from the main pack"); + InventoryOrder.Observe(GameEvent(0x0022, 0x80000003, 0x80000999, 0, 0)); + Eq(Order(Player, false), "1,2", "moved to a container never seen: only the removal is applied"); + Eq(Order(0x80000999, false), "unknown", "and that container stays unknown"); + + Case("inventory order: removal and deletion"); + InventoryOrder.Observe(MessageWithGuid(0x0024, 0x80000001)); + Eq(Order(Player, false), "2", "InventoryRemoveObject"); + InventoryOrder.Observe(MessageWithGuid(0xF747, 0x80000002)); + Eq(Order(Player, false), "", "DeleteObject"); + + Case("inventory order: opened containers are bounded, the player's own is never dropped"); + InventoryOrder.Reset(); + InventoryOrder.Observe(PlayerDescriptionMsg(30, new uint[] { 0x80000001, 0x80000002 }, new uint[] { 0, 0 }, 0)); + for (uint c = 0; c < 200; c++) + InventoryOrder.Observe(GameEvent(0x0196, 0x90000000 + c, 1, 0xA0000000 + c, 0)); + Eq(Order(Player, false), "1,2", "the player's list survives 200 corpses"); + Eq(Order(0x90000000 + 199, false), "C7", "the newest container is kept"); + Eq(Order(0x90000000, false), "unknown", "the oldest was dropped"); + Check(InventoryOrder.Serialize().Length < 4000, "so the saved file stays small"); + + Case("inventory order: saved and restored (it survives an engine reload)"); + InventoryOrder.Reset(); + InventoryOrder.Observe(PlayerDescriptionMsg(60, new uint[] { 0x80000001, 0x80000002, 0x80000003, 0x80000004 }, new uint[] { 0, 0, 0, 1 }, 1)); + InventoryOrder.Observe(GameEvent(0x0022, 0x80000003, Player, 0, 0)); + byte[] saved = InventoryOrder.Serialize(); + string before = Order(Player, false) + "|" + Order(Player, true); + InventoryOrder.Reset(); + Eq(Order(Player, false), "unknown", "a fresh engine knows nothing"); + Check(InventoryOrder.Restore(saved), "the saved data is accepted"); + Eq(Order(Player, false) + "|" + Order(Player, true), before, "same lists back"); + Check(!InventoryOrder.Restore(new byte[] { 1, 2, 3 }), "garbage is refused"); + Check(!InventoryOrder.Restore(saved.AsSpan(0, saved.Length - 3)), "a truncated file is refused"); + Eq(Order(Player, false) + "|" + Order(Player, true), before, "and a refused file changes nothing"); + + Case("inventory order: junk never throws and never invents a list"); + InventoryOrder.Reset(); + var rng = new Random(5); + uint[] events = { 0x13, 0x22, 0x196 }; + for (int i = 0; i < 2000; i++) + { + var junk = new byte[rng.Next(0, 80)]; + rng.NextBytes(junk); + if (junk.Length >= 16 && i % 2 == 0) + { + BinaryPrimitives.WriteUInt32LittleEndian(junk, 0xF7B0); + BinaryPrimitives.WriteUInt32LittleEndian(junk.AsSpan(12), events[i % 3]); + } + InventoryOrder.Observe(junk); + } + Check(true, "2000 random messages survived"); + } +} diff --git a/tools/NetMessageTests/NetMessageTests.csproj b/tools/NetMessageTests/NetMessageTests.csproj index c4fd133..2f77613 100644 --- a/tools/NetMessageTests/NetMessageTests.csproj +++ b/tools/NetMessageTests/NetMessageTests.csproj @@ -34,6 +34,8 @@ + + diff --git a/tools/NetMessageTests/Program.cs b/tools/NetMessageTests/Program.cs index e955f05..6cc2b95 100644 --- a/tools/NetMessageTests/Program.cs +++ b/tools/NetMessageTests/Program.cs @@ -26,7 +26,7 @@ internal sealed unsafe class CountOnly : IServerMessageSink } } -internal static unsafe class Program +internal static unsafe partial class Program { private static int _checks, _failed; private static string _case = ""; @@ -68,6 +68,8 @@ internal static unsafe class Program SystemTextAndConfirmation(); TruncationNeverThrows(); EndToEndGameEvents(); + InventoryOrderTests(); + VaultWireTests(); // Captures given on the command line foreach (string path in args) diff --git a/tools/NetMessageTests/VaultWireTests.cs b/tools/NetMessageTests/VaultWireTests.cs new file mode 100644 index 0000000..6628bbf --- /dev/null +++ b/tools/NetMessageTests/VaultWireTests.cs @@ -0,0 +1,44 @@ +namespace NetMessageTests; + +using RynthCore.Engine.Net; + +// Net/AelrynthVaultWire: the vault's "~ael1" mule lines (Aeshnidae.Mule's /mule-data). +internal static unsafe partial class Program +{ + private static void VaultWireTests() + { + const string A = "{\"o\":2147483649,\"w\":100,\"n\":\"Acid Assagai\",\"i\":100667000,\"u\":100667001,\"v\":100667002,\"s\":3,\"m\":100,\"y\":1,\"e\":1}"; + const string B = "{\"o\":2147483650,\"w\":101,\"n\":\"Pyreal\",\"i\":100667003,\"y\":8192,\"future\":\"ignored\"}"; + string page = "~ael1 {\"t\":\"mule\",\"ready\":true,\"page\":2,\"pages\":3,\"count\":57,\"max\":1000,\"items\":[" + A + "," + B + "]}"; + + Case("vault wire: a page"); + Check(AelrynthVaultWire.IsMuleLine(page), "recognised as a mule line"); + Check(AelrynthVaultWire.TryParse(page, out VaultPage p), "parses"); + Check(p.Ready, "ready"); + Eq(p.Page, 2, "page"); Eq(p.Pages, 3, "pages"); Eq(p.Count, 57, "count"); Eq(p.Max, 1000, "max"); Eq(p.Items.Count, 2, "items"); + VaultItem a = p.Items[0]; + Eq(a.Id, 2147483649u, "id"); Eq(a.Name, "Acid Assagai", "name"); Eq(a.Icon, 100667000u, "icon"); Eq(a.Underlay, 100667001u, "underlay"); + Eq(a.Overlay, 100667002u, "overlay"); Eq(a.Stack, 3, "stack"); Eq(a.MaxStack, 100, "max stack"); Eq(a.ItemType, 1u, "item type"); Eq(a.Effects, 1u, "effects"); + Eq(p.Items[1].Stack, 1, "no stack field is a stack of one"); + Eq(p.Items[1].Underlay, 0u, "no underlay is none"); + + Case("vault wire: not ready is not empty"); + Check(AelrynthVaultWire.TryParse("~ael1 {\"t\":\"mule\",\"ready\":false,\"why\":\"loading\"}", out VaultPage n), "parses"); + Check(!n.Ready && n.Why == "loading" && n.Items.Count == 0, "not ready, and says why"); + + Case("vault wire: other lines"); + Check(!AelrynthVaultWire.IsMuleLine("~ael1 {\"t\":\"inspect\",\"ok\":true}"), "the Companion's line is not ours"); + Check(!AelrynthVaultWire.IsMuleLine("Welcome to Aelrynth"), "chat is not ours"); + Check(!AelrynthVaultWire.IsMuleLine(null), "null"); + Check(!AelrynthVaultWire.TryParse("~ael1 {\"t\":\"mule\",\"ready\":tru", out _), "damaged JSON is refused"); + Check(AelrynthVaultWire.IsUnknownCommand("Unknown command: mule-data"), "ACE's reply for a missing command"); + Check(!AelrynthVaultWire.IsUnknownCommand("Unknown command: mastery-data"), "another command's reply is not ours"); + Eq(AelrynthVaultWire.PageCommand(1), "@mule-data", "first page is the bare command"); + Eq(AelrynthVaultWire.PageCommand(3), "@mule-data 3", "later pages say which"); + + Case("vault wire: absurd sizes are bounded"); + string many = "~ael1 {\"t\":\"mule\",\"ready\":true,\"page\":1,\"pages\":99999,\"count\":1,\"max\":1,\"items\":[" + string.Join(",", System.Linq.Enumerable.Repeat(B, 500)) + "]}"; + Check(AelrynthVaultWire.TryParse(many, out VaultPage big), "parses"); + Check(big.Items.Count <= 200 && big.Pages <= 80, "items and pages are capped"); + } +}