diff --git a/Changelog/2026-10-11-inventory-multi-select.md b/Changelog/2026-10-11-inventory-multi-select.md new file mode 100644 index 0000000..46ef8d6 --- /dev/null +++ b/Changelog/2026-10-11-inventory-multi-select.md @@ -0,0 +1,84 @@ +# Inventory: pick several items, then Drop, Give or Move them + +**Date:** 2026-10-11 +**Area:** Engine (`RynthCore.Engine`), Inventory panel (both looks: Modern and Classic) and +`InventoryModel`. + +## What's new + +The Inventory window can select several items and act on all of them at once. + +- **Picking items** (in both looks): + - **Click:** selects one item, as before. + - **Ctrl+click:** adds an item to the selection, or removes it if it is already selected. + - **Shift+click:** selects every item from the last clicked item to this one, in the order the + grid shows them. **Ctrl+Shift+click** adds that run to the current selection. + - **Right-click > Select all shown:** selects every item the grid shows, meaning the open pack or + the search's matches. The menu item shows the count. + - **Right-click > Select only this item** returns to a single item. +- **Acting on the selection** when more than one item is selected: + - The zones read **Drop N** and **Give N: **. Clicking a zone, or dragging any selected + item onto it, acts on the whole selection. + - Dragging a selected item onto a pack (the pack column, or a pack in the grid) moves the whole + selection there. The drag ghost shows the count. + - The right-click menu on a selected item shows *N items selected*, then **Drop N items**, + **Give N items to ** and **Move N items to >** (with a list of your packs). + - The status row shows the size of the selection and how to use it. +- **Confirmation:** Drop and Give of several items open a confirmation that lists the items by name + (for example "Pyreal x3", up to 10 lines). Give adds "Given items can't be taken back." Move + starts straight away. +- **Progress and Stop:** while the items are sent, the status row shows progress such as + *Giving 3 of 12 to Bob*, with a **Stop** button. When the run ends, the status row and the log + show a summary such as *Gave 10 of 12 items to Bob; 2 failed (first: …).* or *Stopped: dropped + 3 of 12 items; 9 not sent.* + +## Behaviour + +- AC still gets one item action at a time. The batch passes each item to the same request path a + single click uses, so every item is checked, sent and watched exactly as before, including the + wait for AC's action gate. The next item goes only after the previous one has ended (done, + refused, gone or timed out), with a short gap of 0.25 s. +- The batch keeps running with the Inventory window closed and ends by itself. +- Some items are left out of a run, and the confirmation or the status row says how many and why: + - Worn and wielded items. + - Packs and foci sent to a side pack (they only fit in the main pack). + - Items that have already left the inventory. +- Items already in the target pack are skipped quietly, as a single item's drop on its own pack + is. A group dropped back onto its own pack does nothing. +- A Give stops early, and counts the remaining items as failed, if the target disappears or you + leave the world. +- At most 400 items per run. +- While a run is going, single item actions (Use, Split, Equip and so on) are refused with + "Several items are being sent; wait, or press Stop." A run can't start while a single action is + still waiting. +- Items that leave the inventory (given, dropped or merged) drop out of the selection + automatically. +- A plain click on one item of a selection keeps the selection if you drag, and narrows it to that + item if you release without dragging, as in Windows Explorer. +- No keyboard shortcuts were added (such as Ctrl+A or Delete). Keys may belong to AC, so selection + uses mouse modifiers only. + +## Files + +- `src/RynthCore.Engine/ImGui/Panels/InventorySelection.cs` (new): the selection itself (ids, picked + order, anchor, ranges, select all, prune). It has no engine state, so it is unit-tested. +- `src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs` (new): clicks, group actions, + the confirmation, labels, the group menu, the status row's progress and Stop button, and the + drag badge. +- `src/RynthCore.Engine/Compatibility/InventoryModel.Batch.cs` (new): `RequestBatch`, + `CancelBatch`, `Batch` and `BatchRunning`, plus the main-thread runner that feeds items one at a + time. +- `src/RynthCore.Engine/Compatibility/InventoryModel.cs`: the model is now a partial class. Single + requests are refused during a run, and the tick drives the runner even with the panel closed. +- `src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs` and `InventoryFace.Classic.cs`: grid clicks, + selection highlight, zone labels, drag release, context menu and status row now use the + selection. +- `tools/InventorySelectionTests` (new): 42 checks covering click, Ctrl+click, Shift and Ctrl+Shift + runs in both directions, a missing anchor, select all, prune and id 0. + Run with `dotnet run -c Release`. + +## Verification + +- `dotnet build -c Release` for the engine: no errors and no new warnings. +- `tools/InventorySelectionTests`: 42/42 checks passed. +- Not yet tested in game. diff --git a/src/RynthCore.Engine/Compatibility/InventoryModel.Batch.cs b/src/RynthCore.Engine/Compatibility/InventoryModel.Batch.cs new file mode 100644 index 0000000..02f7dc5 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/InventoryModel.Batch.cs @@ -0,0 +1,259 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/InventoryModel.Batch.cs +// Several items in one go (the Inventory panel's multi-selection): Drop, +// Give to the selected creature, or Move into a pack. +// +// Still one item action at a time (AC refuses a second while one waits): the +// batch hands the next item to the normal request path only after the one +// before it has ended (done, refused, gone or timed out), with a short gap, +// so each item is checked and watched exactly like a single click. +// +// Threads: RequestBatch / CancelBatch / Batch / BatchRunning any thread; +// everything else on AC's main thread (BatchTick, from MainThreadTick). The +// batch keeps running with the panel closed and ends by itself. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +/// A running or finished batch, for the status row. Immutable. +internal sealed class InventoryBatchStatus +{ + public InventoryActionKind Kind; + public int Total, Done, Failed; + public string TargetName = string.Empty; + public bool Running; + /// Stop was pressed: it ends after the item in flight. + public bool Stopping; + /// "Giving 3 of 12 to Bob" while running, else the summary. + public string Text = string.Empty; +} + +internal static partial class InventoryModel +{ + // Between items: lets the server's answer to one settle before the next is sent. + private static readonly long BatchGapTicks = Freq / 4; + /// The most items one batch takes (a full main pack and its side packs). + public const int MaxBatch = 400; + + // ── Published / inputs (any thread) ───────────────────────────────── + private static InventoryBatchStatus? _batchStatus; + private static InventoryRequest[]? _batchRequested; + private static int _batchActive, _batchCancel; + + public static InventoryBatchStatus? Batch => Volatile.Read(ref _batchStatus); + public static bool BatchRunning => Volatile.Read(ref _batchActive) != 0; + + /// + /// Starts acting on one after another (all of one kind; Drop, Give + /// or Move). Refused while another action or batch is waiting. Any thread. + /// + public static bool RequestBatch(IReadOnlyList items, out string why) + { + if (items.Count == 0) { why = "Nothing to do."; return false; } + if (items.Count > MaxBatch) { why = $"At most {MaxBatch} items at once."; return false; } + InventoryActionKind kind = items[0].Kind; + if (kind is not (InventoryActionKind.Drop or InventoryActionKind.Give or InventoryActionKind.Move)) + { + why = "Only Drop, Give and Move work on several items."; + return false; + } + for (int i = 1; i < items.Count; i++) + { + if (items[i].Kind != kind) { why = "A batch is one kind of action."; return false; } + } + InventoryPending? busy = Pending; + if (busy != null) + { + why = (busy.WaitingForGame ? "Still waiting for the game: " : "Still waiting for the server: ") + busy.Label; + return false; + } + if (Volatile.Read(ref _requested) != null) { why = "Another item action is about to be sent."; return false; } + if (Interlocked.CompareExchange(ref _batchActive, 1, 0) != 0) { why = "Several items are already being sent."; return false; } + + var copy = new InventoryRequest[items.Count]; + for (int i = 0; i < copy.Length; i++) copy[i] = items[i]; + Volatile.Write(ref _batchCancel, 0); + Volatile.Write(ref _batchRequested, copy); + why = string.Empty; + return true; + } + + /// Stop: no more items are sent; the one in flight still ends normally. Any thread. + public static void CancelBatch() + { + if (!BatchRunning) return; + Volatile.Write(ref _batchCancel, 1); + InventoryBatchStatus? s = Batch; + if (s is { Running: true, Stopping: false }) + Volatile.Write(ref _batchStatus, new InventoryBatchStatus + { + Kind = s.Kind, Total = s.Total, Done = s.Done, Failed = s.Failed, TargetName = s.TargetName, + Running = true, Stopping = true, Text = s.Text + " (stopping)", + }); + } + + // ── Main thread ───────────────────────────────────────────────────── + private static readonly Queue _batchQueue = new(); + private static InventoryActionKind _batchKind; + private static int _batchTotal, _batchDone, _batchFailed; + private static string _batchTarget = string.Empty, _batchFirstError = string.Empty; + // The item handed to the request path, until it has ended. + private static InventoryRequest? _batchWaiting; + private static InventoryResult? _batchResultBefore; + private static long _batchNextAt; + + /// Starts a requested batch, counts the item that ended, sends the next one. Main thread. + private static void BatchTick(long now) + { + InventoryRequest[]? incoming = Interlocked.Exchange(ref _batchRequested, null); + if (incoming != null) StartBatch(incoming, now); + // RequestBatch sets the flag a moment before it hands over the items: they come next tick. + if (_batchTotal == 0) return; + + // The item handed over last tick: wait until it has ended, then count it. + if (_batchWaiting != null) + { + if (Busy()) return; + InventoryResult? r = LastResult; + bool ended = r != null && !ReferenceEquals(r, _batchResultBefore); + if (ended && r!.Ok) _batchDone++; + else + { + _batchFailed++; + if (_batchFirstError.Length == 0) _batchFirstError = ended ? r!.Text : "no answer"; + } + _batchWaiting = null; + _batchNextAt = now + BatchGapTicks; + PublishBatch(running: true); + } + + if (Volatile.Read(ref _batchCancel) != 0) { EndBatch(now, "stopped"); return; } + if (_batchQueue.Count == 0) { EndBatch(now, string.Empty); return; } + if (now < _batchNextAt || Busy()) return; + + uint player = ClientHelperHooks.GetPlayerId(); + if (player == 0) { FailRest("not in the world"); EndBatch(now, string.Empty); return; } + + InventoryRequest next = _batchQueue.Peek(); + if (next.Kind == InventoryActionKind.Give + && (next.TargetId == 0 || next.TargetId == player || !ClientObjectHooks.TryGetItemType(next.TargetId, out _))) + { + FailRest(next.TargetName + " is gone"); + EndBatch(now, string.Empty); + return; + } + + _batchQueue.Dequeue(); + _batchResultBefore = LastResult; + if (Interlocked.CompareExchange(ref _requested, next, null) != null) + { + // Something else got in first (shouldn't happen: Request refuses during a batch). + _batchFailed++; + if (_batchFirstError.Length == 0) _batchFirstError = "another action was in the way"; + _batchNextAt = now + BatchGapTicks; + PublishBatch(running: true); + return; + } + _batchWaiting = next; + PublishBatch(running: true); + } + + /// An item action requested, held or in flight (ours or not). Main thread. + private static bool Busy() => _inFlight != null || _held != null || Volatile.Read(ref _requested) != null; + + private static void StartBatch(InventoryRequest[] items, long now) + { + _batchQueue.Clear(); + foreach (InventoryRequest r in items) _batchQueue.Enqueue(r); + _batchKind = items[0].Kind; + _batchTotal = items.Length; + _batchDone = _batchFailed = 0; + _batchTarget = items[0].TargetName; + _batchFirstError = string.Empty; + _batchWaiting = null; + _batchResultBefore = null; + _batchNextAt = now; + PublishBatch(running: true); + RynthLog.Compat($"InventoryModel: batch {_batchKind} of {_batchTotal} item(s){(_batchTarget.Length > 0 ? " to " + _batchTarget : "")}."); + } + + private static void FailRest(string why) + { + _batchFailed += _batchQueue.Count; + _batchQueue.Clear(); + if (_batchFirstError.Length == 0) _batchFirstError = why; + } + + /// Ends the batch: the summary goes to the status row (LastResult) and the log. Main thread. + private static void EndBatch(long now, string how) + { + bool started = _batchTotal > 0; + int skipped = _batchQueue.Count; + _batchQueue.Clear(); + _batchWaiting = null; + if (started) + { + InventoryBatchStatus s = PublishBatch(running: false, how, skipped); + Finish(s.Text, _batchFailed == 0 && skipped == 0, now); + RynthLog.Compat("InventoryModel: " + s.Text); + } + _batchTotal = 0; + Volatile.Write(ref _batchCancel, 0); + Volatile.Write(ref _batchActive, 0); + } + + private static InventoryBatchStatus PublishBatch(bool running, string how = "", int skipped = 0) + { + var s = new InventoryBatchStatus + { + Kind = _batchKind, Total = _batchTotal, Done = _batchDone, Failed = _batchFailed, + TargetName = _batchTarget, Running = running, + Stopping = running && Volatile.Read(ref _batchCancel) != 0, + }; + s.Text = running + ? BatchProgressText(_batchKind, Math.Min(_batchTotal, _batchDone + _batchFailed + 1), _batchTotal, _batchTarget) + + (s.Stopping ? " (stopping)" : string.Empty) + : BatchSummaryText(_batchKind, _batchDone, _batchFailed, skipped, _batchTotal, _batchTarget, how, _batchFirstError); + Volatile.Write(ref _batchStatus, s); + return s; + } + + /// "Giving 3 of 12 to Bob", "Dropping 3 of 12", "Moving 3 of 12 to Pack". + internal static string BatchProgressText(InventoryActionKind kind, int n, int total, string target) => kind switch + { + InventoryActionKind.Give => $"Giving {n} of {total} to {target}", + InventoryActionKind.Move => $"Moving {n} of {total} to {target}", + _ => $"Dropping {n} of {total}", + }; + + /// "Gave 10 of 12 items to Bob; 2 failed (first: ...)", "Dropped 12 items.", "Stopped: moved 3 of 12...". + internal static string BatchSummaryText(InventoryActionKind kind, int done, int failed, int skipped, int total, + string target, string how, string firstError) + { + string verb = kind switch + { + InventoryActionKind.Give => "gave", + InventoryActionKind.Move => "moved", + _ => "dropped", + }; + string where = kind switch + { + InventoryActionKind.Give => " to " + target, + InventoryActionKind.Move => " to " + target, + _ => string.Empty, + }; + string count = done == total ? $"{total} item{(total == 1 ? "" : "s")}" : $"{done} of {total} items"; + string text = how.Length > 0 + ? $"{char.ToUpperInvariant(how[0])}{how[1..]}: {verb} {count}{where}" + : $"{char.ToUpperInvariant(verb[0])}{verb[1..]} {count}{where}"; + if (failed > 0) text += $"; {failed} failed"; + if (skipped > 0) text += $"; {skipped} not sent"; + if (failed > 0 && firstError.Length > 0) text += $" (first: {firstError.TrimEnd('.')})"; + return text + "."; + } +} diff --git a/src/RynthCore.Engine/Compatibility/InventoryModel.cs b/src/RynthCore.Engine/Compatibility/InventoryModel.cs index 0fcf53a..bd4cc00 100644 --- a/src/RynthCore.Engine/Compatibility/InventoryModel.cs +++ b/src/RynthCore.Engine/Compatibility/InventoryModel.cs @@ -17,6 +17,9 @@ // One item action at a time: AC keeps one pending inventory request and refuses // a second ("You can only move or use one item at a time"; ClientActionGates). // Request() refuses while an action is waiting; nothing is ever queued behind it. +// Several items (the panel's multi-selection) go through RequestBatch +// (InventoryModel.Batch.cs), which feeds them to this same path one at a time, +// each only after the one before it has ended. // // The client's own gate (ClientActionGates, read on the main thread here): // Before the send while AC's pending-request slot holds anyone's request (the @@ -212,7 +215,7 @@ internal sealed class InventoryResult public long AtTicks; } -internal static class InventoryModel +internal static partial class InventoryModel { // ── Cadence ───────────────────────────────────────────────────────── private static readonly long Freq = Stopwatch.Frequency; @@ -295,6 +298,11 @@ internal static class InventoryModel /// public static bool Request(InventoryRequest request, out string why) { + if (BatchRunning) + { + why = "Several items are being sent; wait, or press Stop."; + return false; + } InventoryPending? busy = Pending; if (busy != null) { @@ -357,7 +365,8 @@ internal static class InventoryModel public static void MainThreadTick() { bool open = Volatile.Read(ref _subscribers) > 0; - if (!open && _inFlight == null && _held == null && Volatile.Read(ref _requested) == null) + if (!open && _inFlight == null && _held == null && Volatile.Read(ref _requested) == null + && Volatile.Read(ref _batchActive) == 0) return; if (!MainThreadGuard.IsOnMainThread()) return; @@ -375,6 +384,8 @@ internal static class InventoryModel _lastWatch = now; Watch(now); } + // After the watch, so an item that just ended is counted before the next is sent. + if (Volatile.Read(ref _batchActive) != 0) BatchTick(now); if (!open) return; bool dirty = Volatile.Read(ref _dirty) != 0; diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs index c9121db..e149403 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs @@ -774,12 +774,13 @@ internal sealed partial class InventoryFace dl.AddLine(p, p + new Vector2(w, 0), Faded(Gold)); InventoryTarget? target = InventoryModel.Target; InventoryItem? sel = SelectedItem(view); + RefreshSelectionLabels(target); float zh = h - 4, giveW = Math.Min(128 * s, w * 0.42f), dropW = 62 * s; var give = new Vector2(p.X + w - giveW - 2, p.Y + 2); var drop = new Vector2(give.X - dropW - 3, p.Y + 2); - Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", drop, new Vector2(dropW, zh), 0, "", - InventoryModel.DropAvailable, sel, "Drop on the ground: drag an item here, or click to drop the selected item."); - Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", give, new Vector2(giveW, zh), + Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, _dropLabel, drop, new Vector2(dropW, zh), 0, "", + InventoryModel.DropAvailable, sel, DropTip); + Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, _giveLabel, give, new Vector2(giveW, zh), target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel, target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to."); StatusLine(new Vector2(p.X + 3, p.Y), Math.Max(10, drop.X - p.X - 6), h, view); @@ -803,7 +804,7 @@ internal sealed partial class InventoryFace dl.AddText(tp, StackCol, it.StackText); } if (it.Id == pendingId) Overlay(dl, Art.Waiting, min, cell, Amber); - if (it.Id == _selected) Overlay(dl, Art.Selected, min, cell, SelYellow); + if (IsPicked(it)) Overlay(dl, Art.Selected, min, cell, SelYellow); } /// Hover, click (select, and a press that may become a drag), double-click (use), right-click (menu). @@ -813,7 +814,7 @@ internal sealed partial class InventoryFace _hover = it; if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) { - SelectItem(it); + ClickItem(it); _pressItem = it; _pressAt = ImGuiNET.ImGui.GetMousePos(); } @@ -823,11 +824,7 @@ internal sealed partial class InventoryFace Act(InventoryActionKind.Use, it, 0, "", 0); } if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) - { - _selected = it.Id; - _ctxItem = it; - _openCtx = true; - } + RightClickItem(it); } /// diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs new file mode 100644 index 0000000..05431fe --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs @@ -0,0 +1,373 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/InventoryFace.MultiSelect.cs +// Several items at once, in both looks: +// pick click = one item; Ctrl+click adds / removes one; Shift+click +// the run from the last clicked item (Ctrl+Shift adds the run); +// right-click menu: Select all shown +// act with more than one picked, Drop, Give and a drop on a pack act +// on all of them (drag any picked item, or click the zone); the +// right-click menu has Drop / Give / Move to for the group +// confirm Drop and Give of several ask first (given items don't come +// back); Move doesn't +// run InventoryModel.RequestBatch sends them one at a time; the status +// row shows "Giving 3 of 12 to Bob" with a Stop button +// Worn items, and items that can't go where they're sent, are left out (and +// counted in the confirm / refusal text). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class InventoryFace +{ + private const int ConfirmNameLines = 10; + private static readonly Func IdOfItem = static it => it.Id; + + private readonly InventorySelection _multi = new(); + // A plain press on an item that is part of the group: the group stays for a drag; + // released without dragging, the selection narrows to that item (Explorer's rule). + private bool _pressNarrow; + + // Drop / Give confirmation (opened at the end of Draw, like the split dialog). + private bool _openConfirm; + private InventoryRequest[] _confirmItems = Array.Empty(); + private string _confirmTitle = string.Empty, _confirmOk = string.Empty, _confirmNote = string.Empty; + private string[] _confirmNames = Array.Empty(); + + // Labels that carry the selection's size, rebuilt only when it or the give target changes. + private int _labelsFor = -1; + private InventoryTarget? _labelsTarget; + private string _dropLabel = "Drop", _giveLabel = "Give", _countBadge = string.Empty, _selHint = string.Empty; + private string _menuCount = string.Empty, _menuDrop = string.Empty, _menuGive = string.Empty, _menuMove = string.Empty; + private string _selectAllLabel = "Select all shown"; + + // Status row cache for a running batch. + private InventoryBatchStatus? _batchShown; + + /// A left click on an item: one item, or Ctrl / Shift to pick several. + private void ClickItem(InventoryItem it) + { + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + _pressNarrow = false; + if (io.KeyShift) + { + _multi.Range(_shown, IdOfItem, it.Id, additive: io.KeyCtrl); + SelectItem(it); + return; + } + if (io.KeyCtrl) + { + // Ctrl+click right after a right-click selection keeps that item too. + if (_multi.Count == 0 && _selected != 0 && _selected != it.Id) _multi.Single(_selected); + if (_multi.Toggle(it.Id)) SelectItem(it); + else _selected = _multi.Count > 0 ? _multi.Ids[_multi.Count - 1] : 0; + return; + } + if (_multi.IsMulti && _multi.Contains(it.Id)) _pressNarrow = true; + else _multi.Single(it.Id); + SelectItem(it); + } + + /// A right click: on a picked item the menu acts on the group, else on that one item. + private void RightClickItem(InventoryItem it) + { + if (!_multi.Contains(it.Id)) _multi.Single(it.Id); + _selected = it.Id; + _ctxItem = it; + _openCtx = true; + } + + /// True when is drawn as selected (the one clicked, or part of the group). + private bool IsPicked(InventoryItem it) => it.Id == _selected || _multi.Contains(it.Id); + + /// True when an action on means the whole group. + private bool IsGroup(InventoryItem? it) => _multi.IsMulti && (it == null || _multi.Contains(it.Id)); + + /// + /// A zone click or a drop: on the group (Drop, Give, or a pack) when several are picked + /// and is one of them; otherwise the single-item action. + /// is the pack cell a single item was dropped on (-1: none); + /// a group goes to the end of the pack. + /// + private void DropOnSelection(DropKind kind, uint targetId, string targetName, InventoryItem? item, int slot = -1) + { + if (IsGroup(item) && kind is DropKind.Drop or DropKind.Give or DropKind.Pack) + { + GroupAction(kind, targetId, targetName); + return; + } + if (item != null) DropOn(kind, targetId, targetName, item, slot); + } + + /// Builds the group's requests; Drop and Give ask first, Move starts at once. + private void GroupAction(DropKind kind, uint targetId, string targetName) + { + InventoryView view = InventoryModel.Current; + InventoryActionKind action = kind switch + { + DropKind.Drop => InventoryActionKind.Drop, + DropKind.Give => InventoryActionKind.Give, + _ => InventoryActionKind.Move, + }; + if (action == InventoryActionKind.Give && targetId == 0) { Refuse("Select someone in the game to give to."); return; } + + var list = new List(_multi.Count); + int worn = 0, gone = 0, cant = 0; + foreach (uint id in _multi.Ids) + { + InventoryItem? it = FindAny(view, id); + if (it == null) { gone++; continue; } + if (it.Wielder != 0) { worn++; continue; } + if (action == InventoryActionKind.Move) + { + // Already there (or the pack itself): skipped quietly, like a single item's drop. + if (it.Id == targetId || it.Container == targetId) continue; + // Foci and packs go only in the main pack (a side pack has no pack slots). + if ((it.RequiresPackSlot || it.IsPack) && targetId != view.PlayerId) { cant++; continue; } + } + list.Add(new InventoryRequest + { + Kind = action, ItemId = it.Id, TargetId = action == InventoryActionKind.Drop ? 0 : targetId, + TargetName = action == InventoryActionKind.Drop ? string.Empty : targetName, ItemName = it.Name, + }); + } + if (list.Count > InventoryModel.MaxBatch) + { + Refuse($"{list.Count} items: at most {InventoryModel.MaxBatch} at once."); + return; + } + + string note = LeftOutText(worn, gone, cant); + if (list.Count == 0) + { + // All already in that pack: nothing to do, nothing to say. + if (action == InventoryActionKind.Move && note.Length == 0) return; + Refuse(note.Length > 0 ? "Nothing to send: " + note : "Nothing to send."); + return; + } + if (action == InventoryActionKind.Move) + { + StartBatch(list); + if (note.Length > 0 && _refusal.Length == 0) Refuse("Left out: " + note); + return; + } + OpenConfirm(action, list, targetName, note); + } + + /// "2 worn, 1 gone" for the items a group action leaves out ("" when none). + private static string LeftOutText(int worn, int gone, int cant) + { + var parts = new List(3); + if (worn > 0) parts.Add($"{worn} worn"); + if (cant > 0) parts.Add($"{cant} can only go in the main pack"); + if (gone > 0) parts.Add($"{gone} gone"); + return string.Join(", ", parts); + } + + private void StartBatch(IReadOnlyList list) + { + if (!InventoryModel.RequestBatch(list, out string why)) Refuse(why); + else _refusal = string.Empty; + } + + // ── Confirmation ──────────────────────────────────────────────────── + + private void OpenConfirm(InventoryActionKind action, List list, string targetName, string note) + { + string n = list.Count.ToString(CultureInfo.InvariantCulture); + _confirmItems = list.ToArray(); + _confirmTitle = action == InventoryActionKind.Give + ? $"Give {n} item{(list.Count == 1 ? "" : "s")} to {targetName}?" + : $"Drop {n} item{(list.Count == 1 ? "" : "s")} on the ground?"; + _confirmOk = (action == InventoryActionKind.Give ? PhosphorIcons.Gift + " Give " : PhosphorIcons.ArrowFatDown + " Drop ") + n; + _confirmNote = note.Length > 0 ? "Left out: " + note + "." : string.Empty; + _confirmNames = ConfirmNames(list); + _openConfirm = true; + } + + /// The items by name ("Pyreal x3"), in picked order, at most ConfirmNameLines lines. + private static string[] ConfirmNames(List list) + { + var order = new List(); + var counts = new Dictionary(StringComparer.Ordinal); + foreach (InventoryRequest r in list) + { + if (counts.TryGetValue(r.ItemName, out int c)) counts[r.ItemName] = c + 1; + else { counts[r.ItemName] = 1; order.Add(r.ItemName); } + } + var lines = new List(Math.Min(order.Count, ConfirmNameLines) + 1); + for (int i = 0; i < order.Count && i < ConfirmNameLines; i++) + lines.Add(counts[order[i]] > 1 ? $"{order[i]} x{counts[order[i]]}" : order[i]); + if (order.Count > ConfirmNameLines) + lines.Add($"...and {order.Count - ConfirmNameLines} more kind{(order.Count - ConfirmNameLines == 1 ? "" : "s")}"); + return lines.ToArray(); + } + + private void ConfirmDialog() + { + if (_openConfirm) + { + _openConfirm = false; + ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always); + ImGuiNET.ImGui.OpenPopup("##inv_batch_confirm"); + } + PushMenuStyle(); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8)); + bool open = ImGuiNET.ImGui.BeginPopup("##inv_batch_confirm"); + ImGuiNET.ImGui.PopStyleVar(); + if (!open) { PopMenuStyle(); return; } + try + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.TextUnformatted(_confirmTitle); + ImGuiNET.ImGui.PopStyleColor(); + foreach (string line in _confirmNames) ImGuiNET.ImGui.BulletText(line); + if (_confirmNote.Length > 0) ImGuiNET.ImGui.TextDisabled(_confirmNote); + if (_confirmItems.Length > 0 && _confirmItems[0].Kind == InventoryActionKind.Give) + ImGuiNET.ImGui.TextDisabled("Given items can't be taken back."); + + bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning; + Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + if (Button("##bc_ok", _confirmOk, bp, new Vector2(110, 24), Teal, BtnFill, enabled: idle && _confirmItems.Length > 0)) + { + StartBatch(_confirmItems); + _confirmItems = Array.Empty(); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + if (!idle) ImGuiNET.ImGui.SetItemTooltip("An item action is still waiting."); + if (Button("##bc_cancel", "Cancel", bp + new Vector2(116, 0), new Vector2(80, 24), Text, BtnFill)) + { + _confirmItems = Array.Empty(); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28)); + ImGuiNET.ImGui.Dummy(new Vector2(200, 0)); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + PopMenuStyle(); + } + } + + // ── Labels ────────────────────────────────────────────────────────── + + /// Zone labels, menu entries and hints that show the group's size. Rebuilt only on change. + private void RefreshSelectionLabels(InventoryTarget? target) + { + int n = _multi.IsMulti ? _multi.Count : 0; + if (n == _labelsFor && ReferenceEquals(target, _labelsTarget)) return; + _labelsFor = n; + _labelsTarget = target; + string count = n.ToString(CultureInfo.InvariantCulture); + _dropLabel = n > 0 ? "Drop " + count : "Drop"; + _giveLabel = target == null ? "Give" : n > 0 ? "Give " + count + ": " + target.Name : target.ZoneLabel; + _countBadge = n > 0 ? count : string.Empty; + _selHint = n > 0 + ? count + " selected: Drop, Give, drag to a pack, or right-click. Ctrl+click adds or removes; Shift+click picks a run." + : string.Empty; + _menuCount = count + " items selected"; + _menuDrop = "Drop " + count + " items"; + _menuGive = target == null ? string.Empty : "Give " + count + " items to " + target.Name; + _menuMove = "Move " + count + " items to"; + } + + // ── Group menu ────────────────────────────────────────────────────── + + /// The right-click menu when the clicked item is part of a group. + private void GroupMenu(InventoryView view, InventoryItem clicked) + { + bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning; + InventoryTarget? target = InventoryModel.Target; + RefreshSelectionLabels(target); + ImGuiNET.ImGui.TextDisabled(_menuCount); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem(_menuDrop, "", false, idle && InventoryModel.DropAvailable)) + GroupAction(DropKind.Drop, 0, string.Empty); + if (target != null && ImGuiNET.ImGui.MenuItem(_menuGive, "", false, idle && InventoryModel.GiveAvailable)) + GroupAction(DropKind.Give, target.Id, target.Name); + if (ImGuiNET.ImGui.BeginMenu(_menuMove, idle)) + { + foreach (InventoryPack p in view.Packs) + if (ImGuiNET.ImGui.MenuItem(p.Name, p.FillText, false, true)) + GroupAction(DropKind.Pack, p.Id, p.Name); + ImGuiNET.ImGui.EndMenu(); + } + ImGuiNET.ImGui.Separator(); + SelectionMenuItems(clicked); + if (!idle) ImGuiNET.ImGui.TextDisabled("(an item action is waiting)"); + } + + /// Select all shown / select only this one (both menus). + private void SelectionMenuItems(InventoryItem clicked) + { + if (ImGuiNET.ImGui.MenuItem(_selectAllLabel, "", false, _shown.Count > 1)) + _multi.SelectAll(_shown, IdOfItem); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Pick every item the grid shows (this pack, or the search's matches). Ctrl+click and Shift+click also pick several."); + if (_multi.IsMulti && ImGuiNET.ImGui.MenuItem("Select only this item")) + { + _multi.Single(clicked.Id); + _selected = clicked.Id; + } + } + + // ── Status and pieces ─────────────────────────────────────────────── + + /// + /// A running batch in the status row: progress and a Stop button at the row's right end. + /// False when no batch is running. + /// + private bool BatchStatus(ImDrawListPtr dl, Vector2 p, float w, float statusH, float ty) + { + InventoryBatchStatus? batch = InventoryModel.Batch; + if (batch == null || !batch.Running) { _batchShown = null; return false; } + _batchShown = batch; + float stop = Math.Min(statusH - 2, 20); + var stopPos = new Vector2(p.X + w - stop - 1, p.Y + (statusH - stop) * 0.5f); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.HourglassMedium, p, new Vector2(16, statusH), Amber); + dl.PushClipRect(p, new Vector2(stopPos.X - 2, p.Y + statusH), true); + dl.AddText(new Vector2(p.X + 18, ty), Amber, batch.Text); + dl.PopClipRect(); + if (IconButton("##inv_batch_stop", PhosphorIcons.Stop, stopPos, new Vector2(stop, stop), Red, BtnFill, + enabled: !batch.Stopping, font: UiFont.Ui11)) + InventoryModel.CancelBatch(); + ImGuiNET.ImGui.SetItemTooltip("Stop: no more items are sent (the one in flight still finishes)."); + return true; + } + + /// The group's size on the drag ghost. + private void DragBadge(ImDrawListPtr fg, Vector2 ghostMin) + { + if (!IsGroup(_dragItem) || _countBadge.Length == 0) return; + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_countBadge); + var tp = ghostMin + new Vector2(Icon - ts.X + 4, Icon - ts.Y + 4); + fg.AddRectFilled(tp - new Vector2(3, 1), tp + ts + new Vector2(3, 1), Faded(Black), 4); + fg.AddText(tp, Amber, _countBadge); + } + + /// Forgets picked items that left the inventory (given, dropped, merged). On a new view only. + private void PruneSelection(InventoryView view) + { + if (_multi.Count == 0) return; + _multi.Prune(id => FindAny(view, id) != null); + } + + /// An item in the packs or worn, by id. + private static InventoryItem? FindAny(InventoryView view, uint id) + { + foreach (InventoryPack p in view.Packs) + foreach (InventoryItem it in p.Items) + if (it.Id == id) return it; + foreach (InventoryItem it in view.Worn) + if (it.Id == id) return it; + return null; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index 63a0620..8ab7195 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -14,13 +14,16 @@ // double-click uses; right-click for Use / Equip / Split / Move to / // Drop / Give; drag onto a pack to move, onto Equip / Drop / Give // zones Equip, Drop, Give-to-: drop targets for a drag, -// or buttons for the selected item +// or buttons for the selected item(s) // status the one action waiting for the server (with a timer), or how the -// last one ended +// last one ended; a several-item run's progress and Stop +// several Ctrl+click / Shift+click / Select all pick several items for Drop, +// Give or Move (InventoryFace.MultiSelect.cs) // // Data: InventoryModel (Compatibility), captured and acted on on AC's main // thread. This face only reads its published objects and posts requests; one // item action at a time (a click while one waits is refused, never queued). +// Several items go as a batch the model sends one after another. // Per frame: no allocation except the tooltip of a newly hovered item and the // filtered list when the view, pack, filter, search or sort change. // ============================================================================ @@ -130,6 +133,7 @@ internal sealed partial class InventoryFace : IImGuiPanel InventoryModel.Hover(0); InventoryModel.Unsubscribe(); _dragItem = _pressItem = null; + _pressNarrow = false; ItemDragBridge.EndPopOutDrag(); UiDropTargets.EngineDragObject = 0; _lootAdd.Cancel(); @@ -169,6 +173,7 @@ internal sealed partial class InventoryFace : IImGuiPanel DrawDragGhost(); ContextMenu(view); SplitDialog(view); + ConfirmDialog(); _lootAdd.Draw(); _picker.Draw(); } @@ -323,6 +328,7 @@ internal sealed partial class InventoryFace : IImGuiPanel return; if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category) _gridFirstRow = 0; // another pack or filter: back to the top (Classic grid) + if (!ReferenceEquals(view, _builtFor)) PruneSelection(view); _builtFor = view; _builtPack = pack; _builtSort = _sort; @@ -357,6 +363,7 @@ internal sealed partial class InventoryFace : IImGuiPanel _countText = _shown.Count == total ? total.ToString(CultureInfo.InvariantCulture) + " items" : _shown.Count.ToString(CultureInfo.InvariantCulture) + " of " + total.ToString(CultureInfo.InvariantCulture); + _selectAllLabel = "Select all shown (" + _shown.Count.ToString(CultureInfo.InvariantCulture) + ")"; // The Classic grid's caption, retail's "Contents of ". _captionText = pack == WornPacks ? "Worn" : one == null ? (_shown.Count == total ? "All packs" : "Matches in all packs: " + _countText) @@ -539,7 +546,7 @@ internal sealed partial class InventoryFace : IImGuiPanel if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) { - SelectItem(hot); + ClickItem(hot); _pressItem = hot; _pressAt = mouse; } @@ -549,11 +556,7 @@ internal sealed partial class InventoryFace : IImGuiPanel Act(InventoryActionKind.Use, hot, 0, "", 0); } if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) - { - _selected = hot.Id; - _ctxItem = hot; - _openCtx = true; - } + RightClickItem(hot); if (_pressItem != null && _dragItem == null && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && Vector2.DistanceSquared(mouse, _pressAt) > 25) _dragItem = _pressItem; @@ -572,7 +575,7 @@ internal sealed partial class InventoryFace : IImGuiPanel InventoryItem it = _shown[i]; var cmin = new Vector2(o.X + c * Cell, o.Y + r * Cell); var cmax = cmin + new Vector2(Cell - 2, Cell - 2); - bool sel = it.Id == _selected; + bool sel = IsPicked(it); dl.AddRectFilled(cmin, cmax, i == hoverIdx ? CellHot : CellBg, 3); DrawItemIcon(dl, it.Id, cmin + new Vector2(2, 2), Icon, ReferenceEquals(it, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu); if (it.StackText.Length > 0) @@ -613,21 +616,24 @@ internal sealed partial class InventoryFace : IImGuiPanel Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); InventoryTarget? target = InventoryModel.Target; InventoryItem? sel = SelectedItem(view); + RefreshSelectionLabels(target); float zw = (w - 8) / 3f; var sz = new Vector2(zw, ZoneH); Zone("##z_equip", DropKind.Equip, PhosphorIcons.Shield, "Equip", new Vector2(p.X, p.Y), sz, 0, "", InventoryModel.WieldAvailable, sel, "Equip: drag an item here, or click to equip the selected item."); - Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", new Vector2(p.X + zw + 4, p.Y), sz, 0, "", - InventoryModel.DropAvailable, sel, - "Drop on the ground: drag an item here, or click to drop the selected item."); - Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", new Vector2(p.X + 2 * (zw + 4), p.Y), sz, + Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, _dropLabel, new Vector2(p.X + zw + 4, p.Y), sz, 0, "", + InventoryModel.DropAvailable, sel, DropTip); + Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, _giveLabel, new Vector2(p.X + 2 * (zw + 4), p.Y), sz, target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel, target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to."); NextLine(p, ZoneH + 4); } + private const string DropTip = "Drop on the ground: drag an item here, or click to drop the selected item(s).\n" + + "Ctrl+click or Shift+click items to drop several."; + private void Zone(string id, DropKind kind, string glyph, string label, Vector2 pos, Vector2 size, uint targetId, string targetName, bool enabled, InventoryItem? selected, string tip) { @@ -647,20 +653,14 @@ internal sealed partial class InventoryFace : IImGuiPanel dl.PopClipRect(); if (enabled) _targets.Add(new Target { Min = pos, Max = pos + size, Kind = kind, Id = targetId, Name = targetName }); - if (clicked && enabled && selected != null) - DropOn(kind, targetId, targetName, selected); // refused with a message while one waits + // Refused with a message while one waits. Equip is always the one selected item. + if (clicked && enabled && kind != DropKind.Equip && _multi.IsMulti) + DropOnSelection(kind, targetId, targetName, null); + else if (clicked && enabled && selected != null) + DropOn(kind, targetId, targetName, selected); } - private InventoryItem? SelectedItem(InventoryView view) - { - if (_selected == 0) return null; - foreach (InventoryPack p in view.Packs) - foreach (InventoryItem it in p.Items) - if (it.Id == _selected) return it; - foreach (InventoryItem it in view.Worn) - if (it.Id == _selected) return it; - return null; - } + private InventoryItem? SelectedItem(InventoryView view) => _selected == 0 ? null : FindAny(view, _selected); // ── Status row ────────────────────────────────────────────────────── @@ -682,6 +682,8 @@ internal sealed partial class InventoryFace : IImGuiPanel InventoryPending? pending = InventoryModel.Pending; InventoryResult? result = InventoryModel.LastResult; float ty = p.Y + (statusH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + // A several-item run: its progress and Stop (a button, so outside the clip below). + if (BatchStatus(dl, p, w, statusH, ty)) return; dl.PushClipRect(p, p + new Vector2(w, statusH), true); if (pending != null) { @@ -711,6 +713,11 @@ internal sealed partial class InventoryFace : IImGuiPanel p, new Vector2(16, statusH), result.Ok ? Green : Red); dl.AddText(new Vector2(p.X + 18, ty), result.Ok ? Green : Red, result.Text); } + else if (_selHint.Length > 0) + { + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CheckSquare, p, new Vector2(16, statusH), Teal); + dl.AddText(new Vector2(p.X + 18, ty), Text, _selHint); + } else if (idleView != null) { PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Coins, p, new Vector2(16, statusH), Amber); @@ -835,16 +842,23 @@ internal sealed partial class InventoryFace : IImGuiPanel { if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) { - InventoryItem? item = _dragItem; + InventoryItem? item = _dragItem, pressed = _pressItem; + bool narrow = _pressNarrow; _dragItem = null; _pressItem = null; - if (item == null) return; + _pressNarrow = false; + if (item == null) + { + // A plain click on one of a group, not dragged: just that item now. + if (narrow && pressed != null) _multi.Single(pressed.Id); + return; + } ItemDragBridge.EndPopOutDrag(); Vector2 m = ImGuiNET.ImGui.GetMousePos(); 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, t.Slot); + DropOnSelection(t.Kind, t.Id, t.Name, item, t.Slot); return; } // Let go outside this panel: another engine panel that takes items (Item Count, @@ -880,6 +894,7 @@ internal sealed partial class InventoryFace : IImGuiPanel var fg = ImGuiNET.ImGui.GetForegroundDrawList(); Vector2 m = ImGuiNET.ImGui.GetMousePos() - new Vector2(Icon * 0.5f, Icon * 0.5f); DrawItemIcon(fg, _dragItem.Id, m, Icon, 0xD0FFFFFF); + DragBadge(fg, m); ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); // A popped-out Inventory draws in its own ImGui context: the client's drop targets @@ -987,7 +1002,8 @@ internal sealed partial class InventoryFace : IImGuiPanel { InventoryItem? it = _ctxItem; if (it == null) { ImGuiNET.ImGui.CloseCurrentPopup(); return; } - bool idle = InventoryModel.Pending == null; + if (IsGroup(it)) { GroupMenu(view, it); return; } + bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning; ImGuiNET.ImGui.TextDisabled(it.Name); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Use", "double-click", false, idle)) @@ -1029,6 +1045,8 @@ internal sealed partial class InventoryFace : IImGuiPanel if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Track how many of these you carry on RynthAi's floating item count HUD (/ra itemhud add)"); if (!it.IsPack) MiniRemoteMenu(it); + ImGuiNET.ImGui.Separator(); + SelectionMenuItems(it); if (!idle) ImGuiNET.ImGui.TextDisabled("(an item action is waiting)"); } diff --git a/src/RynthCore.Engine/ImGui/Panels/InventorySelection.cs b/src/RynthCore.Engine/ImGui/Panels/InventorySelection.cs new file mode 100644 index 0000000..ced8fad --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/InventorySelection.cs @@ -0,0 +1,129 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/InventorySelection.cs +// The Inventory panel's multi-selection: which items are picked for a +// Drop / Give / Move of several at once. Windows-style: click picks one, +// Ctrl+click adds or removes one, Shift+click picks the run from the last +// clicked item (the anchor) in the order the grid shows them, Ctrl+Shift+click +// adds that run. +// +// Ids only (object ids), no engine state, so tools/InventorySelectionTests can +// run it. AC's render thread only (the panel's Draw); not thread-safe. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class InventorySelection +{ + private readonly HashSet _set = new(); + // Picked order: a batch acts on the items in the order the player picked them. + private readonly List _order = new(); + + /// Where a Shift+click run starts: the last item clicked or Ctrl+clicked (0 = none). + public uint Anchor { get; private set; } + + public int Count => _order.Count; + + /// The picked ids, in picked order. + public IReadOnlyList Ids => _order; + + /// More than one item picked: the zones and the menu act on all of them. + public bool IsMulti => _order.Count > 1; + + public bool Contains(uint id) => _set.Contains(id); + + public void Clear() + { + _set.Clear(); + _order.Clear(); + Anchor = 0; + } + + /// A plain click: just . + public void Single(uint id) + { + Clear(); + if (id == 0) return; + Add(id); + Anchor = id; + } + + /// Ctrl+click: adds , or removes it if picked. Returns true when it is now picked. + public bool Toggle(uint id) + { + if (id == 0) return false; + Anchor = id; + if (_set.Remove(id)) + { + _order.Remove(id); + return false; + } + Add(id); + return true; + } + + /// + /// Shift+click: the items from the anchor to , both included, in the + /// order of . (Ctrl+Shift) keeps what is + /// already picked. With no anchor on show (another pack, a new search) it picks just + /// . The anchor stays where it was, so the run can be changed. + /// + public void Range(IReadOnlyList shown, Func idOf, uint id, bool additive) + { + int to = IndexOf(shown, idOf, id); + int from = Anchor == 0 ? -1 : IndexOf(shown, idOf, Anchor); + if (to < 0 || from < 0) + { + if (additive) { Add(id); Anchor = id; } + else Single(id); + return; + } + uint anchor = Anchor; + if (!additive) + { + _set.Clear(); + _order.Clear(); + } + int step = to >= from ? 1 : -1; + for (int i = from; ; i += step) + { + Add(idOf(shown[i])); + if (i == to) break; + } + Anchor = anchor; + } + + /// Everything in (the grid's current list), in its order. + public void SelectAll(IReadOnlyList shown, Func idOf) + { + Clear(); + for (int i = 0; i < shown.Count; i++) Add(idOf(shown[i])); + if (_order.Count > 0) Anchor = _order[0]; + } + + /// Drops ids that no longer finds (given, dropped, merged). True if any went. + public bool Prune(Func exists) + { + int before = _order.Count; + _order.RemoveAll(id => !exists(id)); + if (_order.Count == before) return false; + _set.Clear(); + foreach (uint id in _order) _set.Add(id); + if (Anchor != 0 && !_set.Contains(Anchor)) Anchor = 0; + return true; + } + + private void Add(uint id) + { + if (id != 0 && _set.Add(id)) _order.Add(id); + } + + private static int IndexOf(IReadOnlyList shown, Func idOf, uint id) + { + for (int i = 0; i < shown.Count; i++) + if (idOf(shown[i]) == id) return i; + return -1; + } +} diff --git a/tools/InventorySelectionTests/InventorySelectionTests.csproj b/tools/InventorySelectionTests/InventorySelectionTests.csproj new file mode 100644 index 0000000..d663688 --- /dev/null +++ b/tools/InventorySelectionTests/InventorySelectionTests.csproj @@ -0,0 +1,23 @@ + + + + + Exe + net10.0 + enable + enable + true + InventorySelectionTests + + + + + + + diff --git a/tools/InventorySelectionTests/Program.cs b/tools/InventorySelectionTests/Program.cs new file mode 100644 index 0000000..fa7e75a --- /dev/null +++ b/tools/InventorySelectionTests/Program.cs @@ -0,0 +1,206 @@ +using RynthCore.Engine.ImGuiBackend.Panels; + +namespace InventorySelectionTests; + +/// +/// The Inventory panel's multi-selection (InventorySelection.cs) without AC or ImGui: the +/// grid is a list of ids in the order it shows them, like the panel's filtered list. +/// +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + // The grid as shown: ids in display order (deliberately not sorted). + private static readonly uint[] Shown = { 50, 10, 40, 20, 30, 60 }; + private static readonly Func Id = static id => id; + + private static int Main() + { + SingleClick(); + CtrlToggle(); + ShiftRunForward(); + ShiftRunBackward(); + ShiftRunMovesWithAnchorKept(); + CtrlShiftAddsRun(); + ShiftWithoutAnchor(); + ShiftAnchorNotShown(); + SelectAllShown(); + PruneGone(); + ZeroIdsIgnored(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL INVENTORY SELECTION TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + private static void SingleClick() + { + Case("click: just that item"); + var s = new InventorySelection(); + s.Single(40); + Check(s.Count == 1 && s.Contains(40), "one picked"); + Check(!s.IsMulti, "one is not a group"); + Check(s.Anchor == 40, "anchor is the clicked item"); + s.Toggle(20); + s.Single(10); + Same(s.Ids, new uint[] { 10 }, "a plain click replaces the group"); + s.Clear(); + Check(s.Count == 0 && s.Anchor == 0, "clear empties and forgets the anchor"); + } + + private static void CtrlToggle() + { + Case("ctrl+click: add or remove one, picked order kept"); + var s = new InventorySelection(); + s.Single(40); + Check(s.Toggle(20), "ctrl+click adds"); + Check(s.Toggle(60), "ctrl+click adds another"); + Check(s.IsMulti, "three is a group"); + Same(s.Ids, new uint[] { 40, 20, 60 }, "picked order, not grid order"); + Check(!s.Toggle(20), "ctrl+click on a picked item removes it"); + Same(s.Ids, new uint[] { 40, 60 }, "the others stay in order"); + Check(s.Anchor == 20, "anchor follows the last ctrl+click, even a removal"); + Check(!s.Contains(20), "removed item no longer picked"); + } + + private static void ShiftRunForward() + { + Case("shift+click: run forward in grid order"); + var s = new InventorySelection(); + s.Single(10); // index 1 + s.Range(Shown, Id, 30, additive: false); // index 4 + Same(s.Ids, new uint[] { 10, 40, 20, 30 }, "anchor..clicked, both included, grid order"); + Check(s.Anchor == 10, "anchor stays"); + } + + private static void ShiftRunBackward() + { + Case("shift+click: run backward"); + var s = new InventorySelection(); + s.Single(30); // index 4 + s.Range(Shown, Id, 10, additive: false); // index 1 + Same(s.Ids, new uint[] { 30, 20, 40, 10 }, "anchor first, walking back to the clicked item"); + s.Range(Shown, Id, 30, additive: false); + Same(s.Ids, new uint[] { 30 }, "shift+click on the anchor itself picks just it"); + } + + private static void ShiftRunMovesWithAnchorKept() + { + Case("shift+click again: the run is redrawn from the same anchor"); + var s = new InventorySelection(); + s.Single(40); // index 2 + s.Range(Shown, Id, 60, additive: false); // 40,20,30,60 + s.Range(Shown, Id, 50, additive: false); // back past the anchor: 40,10,50 + Same(s.Ids, new uint[] { 40, 10, 50 }, "the old run is replaced, not extended"); + Check(s.Anchor == 40, "anchor unchanged"); + } + + private static void CtrlShiftAddsRun() + { + Case("ctrl+shift+click: adds the run to what is picked"); + var s = new InventorySelection(); + s.Single(60); + s.Toggle(10); // anchor = 10 (index 1) + s.Range(Shown, Id, 20, additive: true); // 10,40,20 + Same(s.Ids, new uint[] { 60, 10, 40, 20 }, "earlier picks kept, no duplicates"); + Check(s.Count == 4, "count matches"); + } + + private static void ShiftWithoutAnchor() + { + Case("shift+click with nothing picked"); + var s = new InventorySelection(); + s.Range(Shown, Id, 20, additive: false); + Same(s.Ids, new uint[] { 20 }, "picks just the clicked item"); + Check(s.Anchor == 20, "and it becomes the anchor"); + var t = new InventorySelection(); + t.Range(Shown, Id, 20, additive: true); + Same(t.Ids, new uint[] { 20 }, "ctrl+shift with nothing picked adds just it"); + } + + private static void ShiftAnchorNotShown() + { + Case("shift+click when the anchor is not on show (other pack, new search)"); + var s = new InventorySelection(); + s.Single(999); // picked in another pack + s.Range(Shown, Id, 30, additive: false); + Same(s.Ids, new uint[] { 30 }, "plain shift: just the clicked item"); + var t = new InventorySelection(); + t.Single(999); + t.Range(Shown, Id, 30, additive: true); + Same(t.Ids, new uint[] { 999, 30 }, "ctrl+shift: the other pack's pick is kept"); + Check(t.Anchor == 30, "the clicked item is the new anchor"); + var u = new InventorySelection(); + u.Single(10); + u.Range(Shown, Id, 777, additive: false); // clicked id not in the list (raced a rebuild) + Same(u.Ids, new uint[] { 777 }, "clicked item not in the list: just it"); + } + + private static void SelectAllShown() + { + Case("select all shown"); + var s = new InventorySelection(); + s.Single(999); + s.SelectAll(Shown, Id); + Same(s.Ids, Shown, "every shown item, in grid order, nothing else"); + Check(s.Anchor == 50, "anchor is the first shown"); + s.SelectAll(Array.Empty(), Id); + Check(s.Count == 0 && s.Anchor == 0, "nothing shown: nothing picked"); + } + + private static void PruneGone() + { + Case("prune: items that left the inventory are forgotten"); + var s = new InventorySelection(); + s.SelectAll(Shown, Id); // anchor 50 + var still = new HashSet { 10, 20, 60 }; + Check(s.Prune(still.Contains), "reports a change"); + Same(s.Ids, new uint[] { 10, 20, 60 }, "the rest stay, in order"); + Check(!s.Contains(50) && !s.Contains(40), "gone ones no longer picked"); + Check(s.Anchor == 0, "a gone anchor is forgotten"); + Check(!s.Prune(still.Contains), "nothing gone: no change"); + s.Single(10); + s.Toggle(20); // anchor 20 + Check(!s.Prune(still.Contains) && s.Anchor == 20, "a kept anchor stays"); + s.Toggle(60); // anchor 60 + still.Remove(10); + Check(s.Prune(still.Contains) && s.Anchor == 60, "an anchor still there survives others going"); + Same(s.Ids, new uint[] { 20, 60 }, "only the gone one left"); + } + + private static void ZeroIdsIgnored() + { + Case("id 0 (no object) is never picked"); + var s = new InventorySelection(); + s.Single(0); + Check(s.Count == 0 && s.Anchor == 0, "single(0) picks nothing"); + Check(!s.Toggle(0), "toggle(0) refused"); + s.SelectAll(new uint[] { 0, 10, 0 }, Id); + Same(s.Ids, new uint[] { 10 }, "select all skips 0"); + } + + // ── harness ───────────────────────────────────────────────────────── + + private static void Case(string name) + { + _case = name; + Console.WriteLine("- " + name); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } + + private static void Same(IReadOnlyList got, IReadOnlyList want, string what) + { + bool ok = got.Count == want.Count; + for (int i = 0; ok && i < got.Count; i++) ok = got[i] == want[i]; + Check(ok, what + $" (got [{string.Join(",", got)}], want [{string.Join(",", want)}])"); + } +}