feat(inventory): multi-select items to drop, give or move several at once

See Changelog/2026-10-11-inventory-multi-select.md.
This commit is contained in:
BlankenshipG 2026-10-12 00:31:39 -04:00
commit 1c034132a9
9 changed files with 1141 additions and 41 deletions

View file

@ -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;
/// <summary>A running or finished batch, for the status row. Immutable.</summary>
internal sealed class InventoryBatchStatus
{
public InventoryActionKind Kind;
public int Total, Done, Failed;
public string TargetName = string.Empty;
public bool Running;
/// <summary>Stop was pressed: it ends after the item in flight.</summary>
public bool Stopping;
/// <summary>"Giving 3 of 12 to Bob" while running, else the summary.</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;
/// <summary>The most items one batch takes (a full main pack and its side packs).</summary>
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;
/// <summary>
/// Starts acting on <paramref name="items"/> one after another (all of one kind; Drop, Give
/// or Move). Refused while another action or batch is waiting. Any thread.
/// </summary>
public static bool RequestBatch(IReadOnlyList<InventoryRequest> 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;
}
/// <summary>Stop: no more items are sent; the one in flight still ends normally. Any thread.</summary>
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<InventoryRequest> _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;
/// <summary>Starts a requested batch, counts the item that ended, sends the next one. Main thread.</summary>
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);
}
/// <summary>An item action requested, held or in flight (ours or not). Main thread.</summary>
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;
}
/// <summary>Ends the batch: the summary goes to the status row (LastResult) and the log. Main thread.</summary>
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;
}
/// <summary>"Giving 3 of 12 to Bob", "Dropping 3 of 12", "Moving 3 of 12 to Pack".</summary>
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}",
};
/// <summary>"Gave 10 of 12 items to Bob; 2 failed (first: ...)", "Dropped 12 items.", "Stopped: moved 3 of 12...".</summary>
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 + ".";
}
}

View file

@ -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
/// </summary>
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;

View file

@ -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);
}
/// <summary>Hover, click (select, and a press that may become a drag), double-click (use), right-click (menu).</summary>
@ -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);
}
/// <summary>

View file

@ -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<InventoryItem, uint> 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<InventoryRequest>();
private string _confirmTitle = string.Empty, _confirmOk = string.Empty, _confirmNote = string.Empty;
private string[] _confirmNames = Array.Empty<string>();
// 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;
/// <summary>A left click on an item: one item, or Ctrl / Shift to pick several.</summary>
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);
}
/// <summary>A right click: on a picked item the menu acts on the group, else on that one item.</summary>
private void RightClickItem(InventoryItem it)
{
if (!_multi.Contains(it.Id)) _multi.Single(it.Id);
_selected = it.Id;
_ctxItem = it;
_openCtx = true;
}
/// <summary>True when <paramref name="it"/> is drawn as selected (the one clicked, or part of the group).</summary>
private bool IsPicked(InventoryItem it) => it.Id == _selected || _multi.Contains(it.Id);
/// <summary>True when an action on <paramref name="it"/> means the whole group.</summary>
private bool IsGroup(InventoryItem? it) => _multi.IsMulti && (it == null || _multi.Contains(it.Id));
/// <summary>
/// A zone click or a drop: on the group (Drop, Give, or a pack) when several are picked
/// and <paramref name="item"/> is one of them; otherwise the single-item action.
/// <paramref name="slot"/> is the pack cell a single item was dropped on (-1: none);
/// a group goes to the end of the pack.
/// </summary>
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);
}
/// <summary>Builds the group's requests; Drop and Give ask first, Move starts at once.</summary>
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<InventoryRequest>(_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);
}
/// <summary>"2 worn, 1 gone" for the items a group action leaves out ("" when none).</summary>
private static string LeftOutText(int worn, int gone, int cant)
{
var parts = new List<string>(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<InventoryRequest> list)
{
if (!InventoryModel.RequestBatch(list, out string why)) Refuse(why);
else _refusal = string.Empty;
}
// ── Confirmation ────────────────────────────────────────────────────
private void OpenConfirm(InventoryActionKind action, List<InventoryRequest> 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;
}
/// <summary>The items by name ("Pyreal x3"), in picked order, at most ConfirmNameLines lines.</summary>
private static string[] ConfirmNames(List<InventoryRequest> list)
{
var order = new List<string>();
var counts = new Dictionary<string, int>(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<string>(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<InventoryRequest>();
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<InventoryRequest>();
ImGuiNET.ImGui.CloseCurrentPopup();
}
ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28));
ImGuiNET.ImGui.Dummy(new Vector2(200, 0));
}
finally
{
ImGuiNET.ImGui.EndPopup();
PopMenuStyle();
}
}
// ── Labels ──────────────────────────────────────────────────────────
/// <summary>Zone labels, menu entries and hints that show the group's size. Rebuilt only on change.</summary>
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 ──────────────────────────────────────────────────────
/// <summary>The right-click menu when the clicked item is part of a group.</summary>
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)");
}
/// <summary>Select all shown / select only this one (both menus).</summary>
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 ───────────────────────────────────────────────
/// <summary>
/// A running batch in the status row: progress and a Stop button at the row's right end.
/// False when no batch is running.
/// </summary>
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;
}
/// <summary>The group's size on the drag ghost.</summary>
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);
}
/// <summary>Forgets picked items that left the inventory (given, dropped, merged). On a new view only.</summary>
private void PruneSelection(InventoryView view)
{
if (_multi.Count == 0) return;
_multi.Prune(id => FindAny(view, id) != null);
}
/// <summary>An item in the packs or worn, by id.</summary>
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;
}
}

View file

@ -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-<selected creature>: 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 <pack>".
_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)");
}

View file

@ -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<uint> _set = new();
// Picked order: a batch acts on the items in the order the player picked them.
private readonly List<uint> _order = new();
/// <summary>Where a Shift+click run starts: the last item clicked or Ctrl+clicked (0 = none).</summary>
public uint Anchor { get; private set; }
public int Count => _order.Count;
/// <summary>The picked ids, in picked order.</summary>
public IReadOnlyList<uint> Ids => _order;
/// <summary>More than one item picked: the zones and the menu act on all of them.</summary>
public bool IsMulti => _order.Count > 1;
public bool Contains(uint id) => _set.Contains(id);
public void Clear()
{
_set.Clear();
_order.Clear();
Anchor = 0;
}
/// <summary>A plain click: just <paramref name="id"/>.</summary>
public void Single(uint id)
{
Clear();
if (id == 0) return;
Add(id);
Anchor = id;
}
/// <summary>Ctrl+click: adds <paramref name="id"/>, or removes it if picked. Returns true when it is now picked.</summary>
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;
}
/// <summary>
/// Shift+click: the items from the anchor to <paramref name="id"/>, both included, in the
/// order of <paramref name="shown"/>. <paramref name="additive"/> (Ctrl+Shift) keeps what is
/// already picked. With no anchor on show (another pack, a new search) it picks just
/// <paramref name="id"/>. The anchor stays where it was, so the run can be changed.
/// </summary>
public void Range<T>(IReadOnlyList<T> shown, Func<T, uint> 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;
}
/// <summary>Everything in <paramref name="shown"/> (the grid's current list), in its order.</summary>
public void SelectAll<T>(IReadOnlyList<T> shown, Func<T, uint> idOf)
{
Clear();
for (int i = 0; i < shown.Count; i++) Add(idOf(shown[i]));
if (_order.Count > 0) Anchor = _order[0];
}
/// <summary>Drops ids that <paramref name="exists"/> no longer finds (given, dropped, merged). True if any went.</summary>
public bool Prune(Func<uint, bool> 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<T>(IReadOnlyList<T> shown, Func<T, uint> idOf, uint id)
{
for (int i = 0; i < shown.Count; i++)
if (idOf(shown[i]) == id) return i;
return -1;
}
}