RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9b5e2765b7
commit
a24ed6df7c
322 changed files with 83009 additions and 7504 deletions
951
src/RynthCore.Engine/ImGui/Panels/ChatFace.cs
Normal file
951
src/RynthCore.Engine/ImGui/Panels/ChatFace.cs
Normal file
|
|
@ -0,0 +1,951 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/ChatFace.cs
|
||||
// ImGui face of RynthChat (docked or popped out; the old Avalonia face is
|
||||
// UI/Panels/RynthChatPanel.cs): channel and custom tabs with unread counts
|
||||
// (right-click a tab: mark read, rename, delete), Filters (the ChatFilters
|
||||
// rule editor), the settings gear, search, the coloured scrollback, and the
|
||||
// input line with Tell and the panel's resize grip beside it.
|
||||
//
|
||||
// Scrollback: wrapped lines, heights cached per wrap width and font; only
|
||||
// the lines in view are drawn. The timestamp is dimmed and the text wraps
|
||||
// under itself. Lines keep the colour and highlights the rules gave them
|
||||
// (ChatLine.Route, worked out on the pump - no regex runs here); a line with
|
||||
// highlights is laid out by hand (LayoutSpans) so each run can take its own
|
||||
// colour. Drag across lines to copy them (the keyboard stays with the game,
|
||||
// so copy is mouse-driven). Right-click a line to copy it or to make a rule
|
||||
// from it: move / copy lines like it to a tab, hide them, colour them. A line
|
||||
// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go
|
||||
// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them).
|
||||
// Follows the newest line until you scroll up.
|
||||
//
|
||||
// The input line belongs to ChatModel (UI/Data/ChatData.cs): Win32Backend
|
||||
// turns the chat keys into ChatModel edits on AC's thread, which is also
|
||||
// this face's thread. Clicking the box starts typing, like Enter.
|
||||
//
|
||||
// The panel has no strip under the body for the resize grip (PanelSpec.
|
||||
// GripInBody): the input row stops short of the bottom-right corner by
|
||||
// ImGuiPanelHost.BodyGripReserve and the host draws the grip there.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class ChatFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Chat";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(460, 300), new Vector2(260, 140), Background: 0, EdgeToEdge: true, GripInBody: true),
|
||||
() => new ChatFace());
|
||||
|
||||
private static readonly uint TabActive = RynthTheme.Argb(0xFF264C59), TabAdd = RynthTheme.Argb(0xFF7AE09A),
|
||||
InputBg = RynthTheme.Argb(0xFF0A121A), InputBorder = RynthTheme.Argb(0xFF264C59), InputActive = RynthTheme.Argb(0xFFFFD700),
|
||||
SelBg = RynthTheme.Argb(0x663A6EA5), FlashBg = RynthTheme.Argb(0xE0264C59), TellBg = RynthTheme.Argb(0xFF0E2E3A),
|
||||
TsColor = RynthTheme.Argb(0xFF6F8397), MentionBg = RynthTheme.Argb(0x33FFC857),
|
||||
BadgeBg = RynthTheme.Argb(0xFF1F6F7A), BadgeMention = RynthTheme.Argb(0xFFB8860B);
|
||||
private const float StickThreshold = 24f;
|
||||
|
||||
// Visible lines for the current tab + search, with wrapped heights; _lay
|
||||
// holds the hand layout of lines with highlights (null for plain lines).
|
||||
private readonly List<ChatLine> _vis = new(512);
|
||||
private readonly List<float> _h = new(512);
|
||||
private readonly List<SpanLayout?> _lay = new(512);
|
||||
private float[] _tops = new float[1];
|
||||
private int _heightsFrom; // first line whose height needs measuring
|
||||
private bool _topsDirty = true;
|
||||
private long _seenLinesVersion = -1, _seenRoutes = -1, _lastId;
|
||||
private string _seenTab = "", _seenSearch = "";
|
||||
private float _seenWrap = -1, _seenFont = -1;
|
||||
private bool _seenTs;
|
||||
|
||||
private readonly byte[] _search = new byte[128], _newTab = new byte[64], _mentionWords = new byte[256];
|
||||
private bool _stick = true;
|
||||
private float _lastScrollY;
|
||||
// Height of lines dropped off the top (the buffer is full) while not following the
|
||||
// tail: the view is moved up by as much, so the lines being read stay put instead of
|
||||
// sliding away.
|
||||
private float _droppedAbove;
|
||||
private float _inputScroll;
|
||||
|
||||
// Selection: indices into _vis.
|
||||
private int _selAnchor = -1, _selEnd = -1;
|
||||
private bool _selDragging, _selMoved;
|
||||
private Vector2 _selDown;
|
||||
private string? _flash;
|
||||
private double _flashUntil;
|
||||
|
||||
// Unread lines per tab since it was last on screen (Id of the newest line seen there).
|
||||
private readonly Dictionary<string, long> _seenId = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, (int Count, bool Mention)> _unread = new(StringComparer.OrdinalIgnoreCase);
|
||||
private long _unreadLines = -1, _unreadRoutes = -1, _unreadTabsVersion = -1;
|
||||
private string _unreadTab = "";
|
||||
|
||||
private bool _openSettings, _openNewTab, _focusNewTab, _openTabMenu, _openLineMenu, _openRename;
|
||||
private string? _ctxTab, _renameFrom;
|
||||
private ChatLine? _ctxLine;
|
||||
private string _ctxPattern = "";
|
||||
// Map coordinates in the right-clicked line (ChatCoords, found when the menu opens):
|
||||
// its menu offers "Arrow to" / "Go to" them, through RynthNav.
|
||||
private List<ChatCoord> _ctxCoords = new();
|
||||
/// <summary>A Move/Copy rule waiting for the New tab popup to name its tab.</summary>
|
||||
private ChatFilterRule? _pendingRule;
|
||||
|
||||
public bool ClickThrough => ChatModel.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl;
|
||||
|
||||
/// <summary>New lines arrive a few times a second at most; popped out and idle, 5 Hz is plenty.</summary>
|
||||
public int PopOutIdleHz => 5;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
ChatModel.EnsureSettingsLoaded();
|
||||
UiSources.Chat.Subscribe();
|
||||
UiSources.Chat.RequestRefresh();
|
||||
ChatModel.SetShown(true);
|
||||
_stick = true;
|
||||
_seenRoutes = -1; // full rebuild on the first frame
|
||||
_seenId.Clear(); // every tab starts read
|
||||
_unreadLines = -1;
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
ChatModel.SetShown(false);
|
||||
UiSources.Chat.Unsubscribe();
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
uint bg = RynthTheme.Argb(((uint)Math.Clamp(ChatModel.BackgroundAlpha, 0, 255) << 24) | 0x0A121A);
|
||||
dl.AddRectFilled(origin, origin + size, bg, 4);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
|
||||
float x0 = origin.X + 4, w = size.X - 8;
|
||||
|
||||
var snap = UiSources.Chat.Current;
|
||||
ChatLine[] lines = snap?.Value ?? Array.Empty<ChatLine>();
|
||||
string tab = ChatModel.CurrentTab();
|
||||
UpdateUnread(lines, snap?.Version ?? -1, tab);
|
||||
|
||||
float y = DrawTabStrip(new Vector2(x0, origin.Y + 4), w);
|
||||
|
||||
DrawSearch(new Vector2(x0, y), w);
|
||||
y += 26;
|
||||
|
||||
SyncLines(snap, lines, tab);
|
||||
|
||||
// Scrollback, then the input row along the bottom; the grip takes its
|
||||
// bottom-right corner (ImGuiPanelHost.BodyGripReserve).
|
||||
const float inputH = 22, bottomPad = 2;
|
||||
float reserve = ImGuiPanelHost.BodyGripReserve;
|
||||
float inputY = origin.Y + size.Y - bottomPad - inputH;
|
||||
float listH = Math.Max(20, inputY - 4 - y);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y));
|
||||
DrawLines(new Vector2(w, listH));
|
||||
float inputRight = reserve > 0 ? origin.X + size.X - reserve - 3 : x0 + w;
|
||||
DrawInput(new Vector2(x0, inputY), inputRight - x0, inputH);
|
||||
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
DrawPopups();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
// ── Tabs ─────────────────────────────────────────────────────────────
|
||||
|
||||
private const string SearchHint = PhosphorIcons.MagnifyingGlass + " Search…";
|
||||
private const string FiltersLabel = PhosphorIcons.Funnel + " Filters";
|
||||
|
||||
/// <summary>Tabs wrap left of Filters and the settings gear. Returns the y below the strip.</summary>
|
||||
private float DrawTabStrip(Vector2 start, float w)
|
||||
{
|
||||
const float h = 20;
|
||||
float gearW = 22, filtW = ButtonWidth(FiltersLabel) - 4;
|
||||
float right = start.X + w;
|
||||
if (IconButton("##chat_gear", PhosphorIcons.Gear, new Vector2(right - gearW, start.Y), new Vector2(gearW, h), Text, BtnFill))
|
||||
_openSettings = true;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Chat settings");
|
||||
if (Button("##chat_filters", FiltersLabel, new Vector2(right - gearW - 3 - filtW, start.Y), new Vector2(filtW, h), Text, BtnFill))
|
||||
PanelRouter.Toggle("ChatFilters");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Rules: move, copy or hide lines by regex, and colour them");
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float stripRight = right - gearW - filtW - 8;
|
||||
float x = start.X, y = start.Y;
|
||||
string current = ChatModel.CurrentTab();
|
||||
foreach (string tab in ChatModel.AllTabs())
|
||||
{
|
||||
bool custom = !ChatModel.IsBaseTab(tab);
|
||||
bool active = string.Equals(tab, current, StringComparison.OrdinalIgnoreCase);
|
||||
_unread.TryGetValue(tab, out var unread);
|
||||
string? badge = !active && unread.Count > 0 ? (unread.Count > 99 ? "99+" : unread.Count.ToString()) : null;
|
||||
float badgeW = 0;
|
||||
if (badge != null)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
badgeW = ImGuiNET.ImGui.CalcTextSize(badge).X + 8;
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
float textW = ImGuiNET.ImGui.CalcTextSize(tab).X;
|
||||
// No inline delete button on custom tabs: right-click → Delete tab does it and
|
||||
// the red X cost a tab's worth of strip width (2026-09-30).
|
||||
float bw = textW + 12 + (badge != null ? badgeW + 3 : 0), extra = 0;
|
||||
if (x > start.X && x + bw + extra > stripRight) { x = start.X; y += h + 2; }
|
||||
ImGuiNET.ImGui.PushID(tab);
|
||||
var p = new Vector2(x, y);
|
||||
if (Button("##tab", "", p, new Vector2(bw, h), Text, active ? TabActive : BtnFill))
|
||||
ChatModel.SelectTab(tab);
|
||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _ctxTab = tab; _openTabMenu = true; }
|
||||
if (unread.Mention && !active) ImGuiNET.ImGui.SetItemTooltip("Someone mentioned you here");
|
||||
else if (custom) ImGuiNET.ImGui.SetItemTooltip("Right-click to rename or delete this tab");
|
||||
float ty = y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
dl.AddText(new Vector2(x + 6, ty), Text, tab);
|
||||
if (badge != null)
|
||||
{
|
||||
var b0 = new Vector2(x + 6 + textW + 3, y + 4);
|
||||
dl.AddRectFilled(b0, b0 + new Vector2(badgeW, h - 8), unread.Mention ? BadgeMention : BadgeBg, (h - 8) * 0.5f);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
dl.AddText(b0 + new Vector2(4, (h - 8 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, badge);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
ImGuiNET.ImGui.PopID();
|
||||
x += bw + extra + 2;
|
||||
}
|
||||
if (x > start.X && x + 18 > stripRight) { x = start.X; y += h + 2; }
|
||||
if (IconButton("##chat_addtab", PhosphorIcons.Plus, new Vector2(x, y), new Vector2(18, h), TabAdd, BtnFill, font: UiFont.Ui11))
|
||||
{
|
||||
_pendingRule = null;
|
||||
WriteUtf8(_newTab, "");
|
||||
_openNewTab = _focusNewTab = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("New tab (fill it with a rule: right-click a line, or Filters)");
|
||||
return y + h + 4;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unread counts per tab: lines shown there that arrived after it was last on
|
||||
/// screen. Recounted only when the lines, the routes or the tabs change.
|
||||
/// </summary>
|
||||
private void UpdateUnread(ChatLine[] lines, long linesVersion, string current)
|
||||
{
|
||||
long newest = lines.Length > 0 ? lines[^1].Id : 0;
|
||||
_seenId[current] = newest;
|
||||
long routes = ChatModel.RoutesVersion, tabsVersion = ChatModel.FiltersVersion;
|
||||
if (linesVersion == _unreadLines && routes == _unreadRoutes && tabsVersion == _unreadTabsVersion
|
||||
&& string.Equals(current, _unreadTab, StringComparison.Ordinal)) return;
|
||||
_unreadLines = linesVersion;
|
||||
_unreadRoutes = routes;
|
||||
_unreadTabsVersion = tabsVersion;
|
||||
_unreadTab = current;
|
||||
_unread.Clear();
|
||||
foreach (string tab in ChatModel.AllTabs())
|
||||
{
|
||||
if (!_seenId.TryGetValue(tab, out long seen)) { _seenId[tab] = newest; continue; } // a new tab starts read
|
||||
int count = 0;
|
||||
bool mention = false;
|
||||
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > seen; i--)
|
||||
if (ChatModel.LineInTab(lines[i], tab)) { count++; mention |= lines[i].Route.Mention; }
|
||||
if (count > 0) _unread[tab] = (count, mention);
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawSearch(Vector2 p, float w)
|
||||
{
|
||||
bool hasText = _search[0] != 0;
|
||||
TextBox("##chat_search", _search, p, hasText ? w - 24 : w, SearchHint, out _);
|
||||
if (hasText)
|
||||
{
|
||||
if (IconButton("##chat_search_x", PhosphorIcons.X, new Vector2(p.X + w - 22, p.Y), new Vector2(22, 22), Mute, BtnFill, font: UiFont.Ui10))
|
||||
WriteUtf8(_search, "");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Clear the search");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Lines ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Brings _vis up to date with the snapshot, tab, search and routes.</summary>
|
||||
private void SyncLines(UiSnapshot<ChatLine[]>? snap, ChatLine[] lines, string tab)
|
||||
{
|
||||
string search = Utf8(_search);
|
||||
long routes = ChatModel.RoutesVersion;
|
||||
|
||||
if (routes != _seenRoutes || tab != _seenTab || search != _seenSearch)
|
||||
{
|
||||
_seenRoutes = routes;
|
||||
_seenTab = tab;
|
||||
_seenSearch = search;
|
||||
_seenLinesVersion = snap?.Version ?? -1;
|
||||
_vis.Clear();
|
||||
_h.Clear();
|
||||
_lay.Clear();
|
||||
foreach (ChatLine line in lines)
|
||||
if (ChatModel.LineVisible(line, tab, search)) { _vis.Add(line); _h.Add(0); _lay.Add(null); }
|
||||
_lastId = lines.Length > 0 ? lines[^1].Id : _lastId;
|
||||
_heightsFrom = 0;
|
||||
_topsDirty = true;
|
||||
ClearSelection();
|
||||
_stick = true; // a rebuild re-pins to the newest line
|
||||
_droppedAbove = 0f;
|
||||
return;
|
||||
}
|
||||
if (snap == null || snap.Version == _seenLinesVersion) return;
|
||||
_seenLinesVersion = snap.Version;
|
||||
|
||||
// Drop lines the source no longer keeps, then add the new ones.
|
||||
long oldest = lines.Length > 0 ? lines[0].Id : long.MaxValue;
|
||||
int drop = 0;
|
||||
while (drop < _vis.Count && _vis[drop].Id < oldest) drop++;
|
||||
if (drop > 0 && !_selDragging)
|
||||
{
|
||||
if (!Following)
|
||||
for (int i = 0; i < drop; i++) _droppedAbove += _h[i];
|
||||
_vis.RemoveRange(0, drop);
|
||||
_h.RemoveRange(0, drop);
|
||||
_lay.RemoveRange(0, drop);
|
||||
_heightsFrom = Math.Max(0, _heightsFrom - drop);
|
||||
if (_selAnchor >= 0) { _selAnchor -= drop; _selEnd -= drop; if (_selAnchor < 0 || _selEnd < 0) ClearSelection(); }
|
||||
_topsDirty = true;
|
||||
}
|
||||
foreach (ChatLine line in lines)
|
||||
{
|
||||
if (line.Id <= _lastId) continue;
|
||||
_lastId = line.Id;
|
||||
if (!ChatModel.LineVisible(line, tab, search)) continue;
|
||||
if (_heightsFrom > _vis.Count) _heightsFrom = _vis.Count;
|
||||
_vis.Add(line);
|
||||
_h.Add(0);
|
||||
_lay.Add(null);
|
||||
_topsDirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The view follows the newest line (auto-scroll on and not scrolled away).</summary>
|
||||
private bool Following => ChatModel.AutoScroll && _stick;
|
||||
|
||||
private void DrawLines(Vector2 size)
|
||||
{
|
||||
// Lines left the top of a full buffer while not following: scroll up by as much
|
||||
// in THIS frame's BeginChild. (SetScrollY only lands in the next frame's Begin,
|
||||
// after this frame has drawn the shortened list at the old scroll - the text
|
||||
// jumped up for a frame and a strip at the bottom went blank, several times a
|
||||
// second in busy chat.) A frame with wheel input waits a frame: this would
|
||||
// override the wheel's own scroll.
|
||||
bool compensated = false;
|
||||
if (_droppedAbove > 0f)
|
||||
{
|
||||
if (Following) _droppedAbove = 0f;
|
||||
else if (ImGuiNET.ImGui.GetIO().MouseWheel == 0f)
|
||||
{
|
||||
ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, Math.Max(0f, _lastScrollY - _droppedAbove)));
|
||||
_droppedAbove = 0f;
|
||||
compensated = true;
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, 10f);
|
||||
bool open = ImGuiNET.ImGui.BeginChild("##chat_lines", size, ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar);
|
||||
ImGuiNET.ImGui.PopStyleVar(2);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (!open) { ImGuiNET.ImGui.EndChild(); return; }
|
||||
|
||||
float fontSize = ChatModel.FontSize;
|
||||
ImFontPtr font = ImGuiFonts.Chat(fontSize);
|
||||
ImGuiNET.ImGui.PushFont(font);
|
||||
bool showTs = ChatModel.ShowTimestamps;
|
||||
float wrapW = Math.Max(20, ImGuiNET.ImGui.GetContentRegionAvail().X - 6);
|
||||
// The text starts after the timestamp and wraps under itself.
|
||||
float tsW = showTs ? ImGuiNET.ImGui.CalcTextSize("00:00:00 ").X : 0;
|
||||
float textW = Math.Max(20, wrapW - tsW);
|
||||
if (wrapW != _seenWrap || fontSize != _seenFont || showTs != _seenTs)
|
||||
{
|
||||
_seenWrap = wrapW;
|
||||
_seenFont = fontSize;
|
||||
_seenTs = showTs;
|
||||
_heightsFrom = 0;
|
||||
}
|
||||
if (_heightsFrom < _vis.Count)
|
||||
{
|
||||
for (int i = _heightsFrom; i < _vis.Count; i++)
|
||||
{
|
||||
ChatLine line = _vis[i];
|
||||
ChatSpan[]? spans = line.Route.Spans;
|
||||
if (spans != null)
|
||||
{
|
||||
SpanLayout lay = LayoutSpans(font, line.Text, spans, textW);
|
||||
_lay[i] = lay;
|
||||
_h[i] = lay.Height;
|
||||
}
|
||||
else
|
||||
{
|
||||
_lay[i] = null;
|
||||
_h[i] = ImGuiNET.ImGui.CalcTextSize(line.Text, false, textW).Y;
|
||||
}
|
||||
}
|
||||
_heightsFrom = _vis.Count;
|
||||
_topsDirty = true;
|
||||
}
|
||||
if (_topsDirty)
|
||||
{
|
||||
if (_tops.Length < _vis.Count + 1) _tops = new float[Math.Max(_vis.Count + 1, _tops.Length * 2)];
|
||||
_tops[0] = 0;
|
||||
for (int i = 0; i < _vis.Count; i++) _tops[i + 1] = _tops[i] + _h[i];
|
||||
_topsDirty = false;
|
||||
}
|
||||
int n = _vis.Count;
|
||||
float total = _tops[n];
|
||||
|
||||
// Following the tail until the user scrolls away from it.
|
||||
float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY();
|
||||
if (compensated) _lastScrollY = scrollY; // our move, not the user's
|
||||
// Wheel up over the chat stops following at once; reaching the bottom again resumes it.
|
||||
// Not while it has nothing to scroll: no scroll change would ever turn following back on.
|
||||
if (maxY > 0f && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.GetIO().MouseWheel > 0f)
|
||||
_stick = false;
|
||||
else if (Math.Abs(scrollY - _lastScrollY) > 0.5f)
|
||||
_stick = scrollY >= maxY - StickThreshold;
|
||||
|
||||
Vector2 basePos = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float viewH = ImGuiNET.ImGui.GetWindowHeight();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
int first = FirstAtOrBelow(scrollY, n);
|
||||
int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd);
|
||||
for (int i = first; i < n && _tops[i] < scrollY + viewH; i++)
|
||||
{
|
||||
Vector2 p = basePos + new Vector2(0, _tops[i]);
|
||||
ChatLine line = _vis[i];
|
||||
ChatRoute route = line.Route;
|
||||
if (route.Mention)
|
||||
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), MentionBg);
|
||||
if (lo >= 0 && i >= lo && i <= hi)
|
||||
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), SelBg);
|
||||
uint col = RynthTheme.Argb(ChatModel.LineArgb(line));
|
||||
if (showTs) dl.AddText(font, font.FontSize, p + new Vector2(3, 0), TsColor, line.Timestamp);
|
||||
Vector2 tp = p + new Vector2(3 + tsW, 0);
|
||||
SpanLayout? lay = _lay[i];
|
||||
if (lay == null)
|
||||
dl.AddText(font, font.FontSize, tp, col, line.Text, textW);
|
||||
else
|
||||
foreach (Seg seg in lay.Segs)
|
||||
dl.AddText(font, font.FontSize, tp + seg.Offset, seg.Argb == 0 ? col : RynthTheme.Argb(seg.Argb), seg.Text);
|
||||
}
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(wrapW, Math.Max(1, total)));
|
||||
HandleSelection(basePos, wrapW, scrollY, viewH, n);
|
||||
HandleLineMenu(basePos, wrapW, n);
|
||||
|
||||
_lastScrollY = scrollY;
|
||||
if (ChatModel.AutoScroll && _stick && !_selDragging && total > viewH)
|
||||
ImGuiNET.ImGui.SetScrollHereY(1f);
|
||||
|
||||
// "Copied N lines" / "Rule added", top-right, for a moment.
|
||||
if (_flash != null)
|
||||
{
|
||||
if (ImGuiNET.ImGui.GetTime() > _flashUntil) _flash = null;
|
||||
else
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_flash);
|
||||
Vector2 wp = ImGuiNET.ImGui.GetWindowPos();
|
||||
Vector2 fp = new(Math.Max(wp.X + 2, wp.X + wrapW - ts.X - 12), wp.Y + 4);
|
||||
dl.AddRectFilled(fp, fp + ts + new Vector2(12, 4), FlashBg, 3);
|
||||
dl.AddText(fp + new Vector2(6, 2), Text, _flash);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
}
|
||||
|
||||
private void Flash(string message, double seconds = 2.0)
|
||||
{
|
||||
_flash = message;
|
||||
_flashUntil = ImGuiNET.ImGui.GetTime() + seconds;
|
||||
}
|
||||
|
||||
// ── Highlighted lines: hand layout ───────────────────────────────────
|
||||
|
||||
private readonly record struct Seg(string Text, Vector2 Offset, uint Argb); // Argb 0 = the line's colour
|
||||
|
||||
private sealed class SpanLayout
|
||||
{
|
||||
public required float Height;
|
||||
public required Seg[] Segs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Word-wraps <paramref name="text"/> to <paramref name="wrapW"/> and cuts each
|
||||
/// row where a highlight starts or ends, so every run is drawn in its own
|
||||
/// colour. Called when a line is measured, never per frame.
|
||||
/// </summary>
|
||||
private static SpanLayout LayoutSpans(ImFontPtr font, string text, ChatSpan[] spans, float wrapW)
|
||||
{
|
||||
float size = font.FontSize;
|
||||
float Width(int start, int end) => end <= start ? 0 : font.CalcTextSizeA(size, float.MaxValue, 0f, text[start..end]).X;
|
||||
|
||||
// Rows as [start, end) character ranges.
|
||||
var rows = new List<(int Start, int End)>();
|
||||
int rowStart = 0;
|
||||
float x = 0;
|
||||
int i = 0;
|
||||
while (i < text.Length)
|
||||
{
|
||||
if (text[i] == '\n') { rows.Add((rowStart, i)); rowStart = i + 1; x = 0; i++; continue; }
|
||||
// A word and the spaces after it.
|
||||
int j = i;
|
||||
while (j < text.Length && text[j] != ' ' && text[j] != '\n') j++;
|
||||
while (j < text.Length && text[j] == ' ') j++;
|
||||
float ww = Width(i, j);
|
||||
int wordEnd = j;
|
||||
while (wordEnd > i && text[wordEnd - 1] == ' ') wordEnd--;
|
||||
float inkW = Width(i, wordEnd);
|
||||
if (x > 0 && x + inkW > wrapW)
|
||||
{
|
||||
rows.Add((rowStart, i));
|
||||
rowStart = i;
|
||||
x = 0;
|
||||
}
|
||||
if (x == 0 && inkW > wrapW)
|
||||
{
|
||||
// A word wider than the row: break it by characters.
|
||||
int k = i;
|
||||
while (k < wordEnd)
|
||||
{
|
||||
int m = k + 1;
|
||||
while (m < wordEnd && Width(k, m + 1) <= wrapW) m++;
|
||||
if (m < wordEnd) { rows.Add((rowStart, m)); rowStart = m; }
|
||||
else x = Width(k, j);
|
||||
k = m;
|
||||
}
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
x += ww;
|
||||
i = j;
|
||||
}
|
||||
rows.Add((rowStart, text.Length));
|
||||
|
||||
var segs = new List<Seg>();
|
||||
for (int r = 0; r < rows.Count; r++)
|
||||
{
|
||||
(int a, int b) = rows[r];
|
||||
float y = r * size, sx = 0;
|
||||
int c = a;
|
||||
foreach (ChatSpan span in spans)
|
||||
{
|
||||
int s0 = Math.Max(span.Start, a), s1 = Math.Min(span.Start + span.Length, b);
|
||||
if (s1 <= s0) continue;
|
||||
if (s0 > c) { segs.Add(new Seg(text[c..s0], new Vector2(sx, y), 0)); sx += Width(c, s0); }
|
||||
segs.Add(new Seg(text[s0..s1], new Vector2(sx, y), span.Argb));
|
||||
sx += Width(s0, s1);
|
||||
c = s1;
|
||||
}
|
||||
if (c < b) segs.Add(new Seg(text[c..b], new Vector2(sx, y), 0));
|
||||
}
|
||||
return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray() };
|
||||
}
|
||||
|
||||
/// <summary>Index of the line containing content y (clamped to the list).</summary>
|
||||
private int FirstAtOrBelow(float y, int n)
|
||||
{
|
||||
int lo = 0, hi = n; // first i with _tops[i + 1] > y
|
||||
while (lo < hi)
|
||||
{
|
||||
int mid = (lo + hi) >> 1;
|
||||
if (_tops[mid + 1] > y) hi = mid; else lo = mid + 1;
|
||||
}
|
||||
return Math.Min(lo, Math.Max(0, n - 1));
|
||||
}
|
||||
|
||||
private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n)
|
||||
{
|
||||
if (n == 0) { ClearSelection(); return; }
|
||||
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
|
||||
float contentY = mouse.Y - basePos.Y;
|
||||
if (!_selDragging)
|
||||
{
|
||||
if (!ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)
|
||||
|| !ImGuiNET.ImGui.IsWindowHovered()
|
||||
|| mouse.X > basePos.X + wrapW + 6) // the scrollbar
|
||||
return;
|
||||
ClearSelection();
|
||||
if (contentY < 0 || contentY >= _tops[n]) return;
|
||||
_selAnchor = _selEnd = FirstAtOrBelow(contentY, n);
|
||||
_selDragging = true;
|
||||
_selMoved = false;
|
||||
_selDown = mouse;
|
||||
return;
|
||||
}
|
||||
|
||||
if (Math.Abs(mouse.X - _selDown.X) > 3 || Math.Abs(mouse.Y - _selDown.Y) > 3) _selMoved = true;
|
||||
_selEnd = FirstAtOrBelow(Math.Clamp(contentY, 0, _tops[n] - 1), n);
|
||||
|
||||
// Dragging past the edges scrolls.
|
||||
Vector2 wp = ImGuiNET.ImGui.GetWindowPos();
|
||||
if (mouse.Y < wp.Y) ImGuiNET.ImGui.SetScrollY(Math.Max(0, scrollY - 12));
|
||||
else if (mouse.Y > wp.Y + viewH) ImGuiNET.ImGui.SetScrollY(scrollY + 12);
|
||||
|
||||
if (ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return;
|
||||
_selDragging = false;
|
||||
// A drag (even within one line) copies; a plain click just clears.
|
||||
if (!_selMoved && _selEnd == _selAnchor) { ClearSelection(); return; }
|
||||
int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd);
|
||||
var parts = new List<string>(hi - lo + 1);
|
||||
for (int i = lo; i <= hi && i < _vis.Count; i++) parts.Add(CopyText(_vis[i]));
|
||||
Flash(ChatModel.CopyLines(parts), 1.5);
|
||||
}
|
||||
|
||||
private static string CopyText(ChatLine line) => ChatModel.ShowTimestamps ? line.FormattedText : line.Text;
|
||||
|
||||
/// <summary>Right-click on a line: its menu (drawn in DrawPopups).</summary>
|
||||
private void HandleLineMenu(Vector2 basePos, float wrapW, int n)
|
||||
{
|
||||
if (n == 0 || _selDragging || !ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right) || !ImGuiNET.ImGui.IsWindowHovered())
|
||||
return;
|
||||
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
|
||||
float contentY = mouse.Y - basePos.Y;
|
||||
if (mouse.X > basePos.X + wrapW + 6 || contentY < 0 || contentY >= _tops[n]) return;
|
||||
_ctxLine = _vis[FirstAtOrBelow(contentY, n)];
|
||||
_ctxPattern = ChatModel.PatternFor(_ctxLine);
|
||||
_ctxCoords = ImGuiPanelHost.HasFace(RynthNavFace.Title) ? ChatCoords.Find(_ctxLine.Text) : new List<ChatCoord>();
|
||||
_openLineMenu = true;
|
||||
}
|
||||
|
||||
private void ClearSelection()
|
||||
{
|
||||
_selAnchor = _selEnd = -1;
|
||||
_selDragging = _selMoved = false;
|
||||
}
|
||||
|
||||
// ── Input ────────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawInput(Vector2 p, float w, float h)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float tellW = ButtonWidth("Tell");
|
||||
float boxW = Math.Max(20, w - tellW - 4);
|
||||
bool typing = Win32Backend.ChatCaptureActive;
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##chat_input", new Vector2(boxW, h)))
|
||||
ChatModel.BeginTyping();
|
||||
if (!typing && ChatHooks.RynthChatOwnsChat) ImGuiNET.ImGui.SetItemTooltip("Click or press Enter to chat");
|
||||
dl.AddRectFilled(p, p + new Vector2(boxW, h), InputBg, 3);
|
||||
dl.AddRect(p, p + new Vector2(boxW, h), typing ? InputActive : InputBorder, 3);
|
||||
|
||||
string text = ChatModel.InputText;
|
||||
float fh = ImGuiNET.ImGui.GetFontSize();
|
||||
float ty = p.Y + (h - fh) * 0.5f;
|
||||
dl.PushClipRect(p + new Vector2(2, 1), p + new Vector2(boxW - 2, h - 1), true);
|
||||
if (text.Length == 0 && !typing)
|
||||
{
|
||||
_inputScroll = 0;
|
||||
dl.AddText(new Vector2(p.X + 5, ty), Faded(Mute), ChatModel.InputHint ?? "Press Enter to chat…");
|
||||
}
|
||||
else
|
||||
{
|
||||
int cursor = Math.Clamp(ChatModel.InputCursor, 0, text.Length);
|
||||
float caretX = cursor == 0 ? 0 : ImGuiNET.ImGui.CalcTextSize(text[..cursor]).X;
|
||||
float room = boxW - 12;
|
||||
if (caretX - _inputScroll > room) _inputScroll = caretX - room;
|
||||
if (caretX < _inputScroll) _inputScroll = caretX;
|
||||
float tx = p.X + 5 - _inputScroll;
|
||||
dl.AddText(new Vector2(tx, ty), Text, text);
|
||||
if (typing && ImGuiNET.ImGui.GetTime() % 1.0 < 0.6)
|
||||
dl.AddLine(new Vector2(tx + caretX, ty), new Vector2(tx + caretX, ty + fh), Text);
|
||||
}
|
||||
dl.PopClipRect();
|
||||
|
||||
if (Button("##chat_tell", "Tell", new Vector2(p.X + boxW + 4, p.Y), new Vector2(tellW, h), Text, TellBg))
|
||||
Win32Backend.RequestTellSelected();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Select an NPC or player in the game, then click to start /tell <name>, — or type /tell and press Enter.");
|
||||
}
|
||||
|
||||
// ── Rules from a line ────────────────────────────────────────────────
|
||||
|
||||
private void RuleFromLine(ChatRuleAction action, string? tab)
|
||||
{
|
||||
var rule = new ChatFilterRule { Pattern = _ctxPattern, Action = action, Tab = tab ?? "" };
|
||||
if (action == ChatRuleAction.Color)
|
||||
{
|
||||
rule.ColorMode = ChatColorMode.Line;
|
||||
ChatModel.AddRule(rule);
|
||||
if (!ImGuiPanelHost.IsOpen("ChatFilters")) PanelRouter.Toggle("ChatFilters");
|
||||
Flash("Rule added - pick its colour in Filters");
|
||||
return;
|
||||
}
|
||||
ChatModel.AddRule(rule);
|
||||
Flash(action switch
|
||||
{
|
||||
ChatRuleAction.Move => $"Rule added: lines like this move to {tab}",
|
||||
ChatRuleAction.Copy => $"Rule added: lines like this also show in {tab}",
|
||||
_ => "Rule added: lines like this are hidden (undo in Filters)",
|
||||
}, 3);
|
||||
}
|
||||
|
||||
private void TabMenu(string id, ChatRuleAction action)
|
||||
{
|
||||
if (!ImGuiNET.ImGui.BeginMenu(id)) return;
|
||||
foreach (string t in ChatModel.TargetTabs())
|
||||
if (ImGuiNET.ImGui.MenuItem(t)) RuleFromLine(action, t);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("New tab…"))
|
||||
{
|
||||
_pendingRule = new ChatFilterRule { Pattern = _ctxPattern, Action = action };
|
||||
WriteUtf8(_newTab, "");
|
||||
_openNewTab = _focusNewTab = true;
|
||||
}
|
||||
ImGuiNET.ImGui.EndMenu();
|
||||
}
|
||||
|
||||
// ── Popups ───────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawPopups()
|
||||
{
|
||||
if (_openSettings)
|
||||
{
|
||||
_openSettings = false;
|
||||
WriteUtf8(_mentionWords, ChatModel.MentionWords);
|
||||
ImGuiNET.ImGui.OpenPopup("##chat_settings");
|
||||
}
|
||||
if (_openNewTab) { _openNewTab = false; ImGuiNET.ImGui.OpenPopup("##chat_newtab"); }
|
||||
if (_openTabMenu) { _openTabMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_tabmenu"); }
|
||||
if (_openLineMenu) { _openLineMenu = false; ImGuiNET.ImGui.OpenPopup("##chat_linemenu"); }
|
||||
if (_openRename) { _openRename = false; ImGuiNET.ImGui.OpenPopup("##chat_rename"); }
|
||||
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, RynthTheme.Argb(0xF2060C14));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, TabActive);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, Amber);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, TabActive);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
|
||||
|
||||
DrawSettingsPopup();
|
||||
DrawNewTabPopup();
|
||||
DrawTabMenu();
|
||||
DrawRenamePopup();
|
||||
DrawLineMenu();
|
||||
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(8);
|
||||
}
|
||||
|
||||
private void DrawSettingsPopup()
|
||||
{
|
||||
if (!ImGuiNET.ImGui.BeginPopup("##chat_settings")) return;
|
||||
ImGuiNET.ImGui.PushItemWidth(150);
|
||||
int font = (int)MathF.Round(ChatModel.FontSize);
|
||||
if (ImGuiNET.ImGui.SliderInt("Font size", ref font, 8, 18)) ChatModel.FontSize = font;
|
||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatModel.SaveSettings();
|
||||
int pct = (int)MathF.Round(ChatModel.BackgroundAlpha / 2.55f);
|
||||
if (ImGuiNET.ImGui.SliderInt("Background", ref pct, 0, 100, "%d%%"))
|
||||
ChatModel.BackgroundAlpha = (int)MathF.Round(pct * 2.55f);
|
||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatModel.SaveSettings();
|
||||
ImGuiNET.ImGui.PopItemWidth();
|
||||
|
||||
bool ts = ChatModel.ShowTimestamps;
|
||||
if (ImGuiNET.ImGui.Checkbox("Timestamps", ref ts))
|
||||
{
|
||||
ChatModel.ShowTimestamps = ts;
|
||||
ChatModel.SaveSettings();
|
||||
}
|
||||
bool auto = ChatModel.AutoScroll;
|
||||
if (ImGuiNET.ImGui.Checkbox("Auto-scroll", ref auto))
|
||||
{
|
||||
ChatModel.AutoScroll = auto;
|
||||
if (auto) _stick = true;
|
||||
ChatModel.SaveSettings();
|
||||
}
|
||||
bool hide = ChatHooks.SuppressOriginalChat;
|
||||
if (ImGuiNET.ImGui.Checkbox("Hide retail chat (Enter types here)", ref hide))
|
||||
{
|
||||
ChatHooks.SuppressOriginalChat = hide;
|
||||
ChatModel.SaveSettings();
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("On: the retail chatbox is hidden and Enter types in RynthChat.\n" +
|
||||
"Off: the retail chatbox is shown and Enter types there; RynthChat keeps showing lines and its Tell button still works.");
|
||||
bool log = ChatModel.LogEnabled;
|
||||
if (ImGuiNET.ImGui.Checkbox("Log to file", ref log))
|
||||
{
|
||||
ChatModel.LogEnabled = log;
|
||||
ChatModel.SaveSettings();
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("%AppData%\\RynthCore\\ChatLogs\\<character>.log");
|
||||
bool through = ChatModel.CtrlGatedClickThrough;
|
||||
if (ImGuiNET.ImGui.Checkbox("Click-through (hold Ctrl to interact)", ref through))
|
||||
ChatModel.SetCtrlGatedClickThrough(through);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Docked chat only; popped out it's always interactive.\n" +
|
||||
"On: clicks pass through to the game; hold Ctrl to use the chat.");
|
||||
|
||||
ImGuiNET.ImGui.Separator();
|
||||
bool mention = ChatModel.MentionHighlight;
|
||||
if (ImGuiNET.ImGui.Checkbox("Highlight my name", ref mention))
|
||||
{
|
||||
ChatModel.MentionHighlight = mention;
|
||||
ChatModel.FiltersChanged(); // re-highlights the kept lines
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("When another player's chat or channel line says your character's name\n" +
|
||||
"(or a word below), the name is highlighted, the line tinted and the tab's count turns gold.");
|
||||
if (mention)
|
||||
{
|
||||
Label("Also highlight (comma-separated):", Mute);
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
TextBox("##mention_words", _mentionWords, p, 230, "e.g. Drak, buffs", out _);
|
||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
ChatModel.MentionWords = Utf8(_mentionWords).Trim();
|
||||
ChatModel.FiltersChanged();
|
||||
}
|
||||
NextLine(p, 26);
|
||||
bool sound = ChatModel.MentionSound;
|
||||
if (ImGuiNET.ImGui.Checkbox("Beep when mentioned", ref sound))
|
||||
{
|
||||
ChatModel.MentionSound = sound;
|
||||
ChatModel.SaveSettings();
|
||||
}
|
||||
}
|
||||
if (!ChatModel.PluginBound) Label("Plugin not bound", Mute);
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
|
||||
private void DrawNewTabPopup()
|
||||
{
|
||||
if (!ImGuiNET.ImGui.BeginPopup("##chat_newtab"))
|
||||
{
|
||||
_pendingRule = null;
|
||||
return;
|
||||
}
|
||||
if (_pendingRule != null)
|
||||
Label(_pendingRule.Action == ChatRuleAction.Copy ? "New tab for a copy of lines like this:" : "New tab for lines like this:", Mute);
|
||||
if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; }
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
bool enter = TextBox("##newtab_name", _newTab, p, 120, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20);
|
||||
bool add = Button("##newtab_add", "Add", new Vector2(p.X + 124, p.Y), new Vector2(ButtonWidth("Add"), 20), Text, TabActive);
|
||||
bool cancel = Button("##newtab_cancel", "Cancel", new Vector2(p.X + 128 + ButtonWidth("Add"), p.Y), new Vector2(ButtonWidth("Cancel"), 20), Text, BtnFill);
|
||||
NextLine(p, 20);
|
||||
if (enter || add)
|
||||
{
|
||||
ChatFilterRule? pending = _pendingRule;
|
||||
string? name = ChatModel.AddCustomTab(Utf8(_newTab), select: pending == null);
|
||||
if (name != null && pending != null)
|
||||
{
|
||||
pending.Tab = name;
|
||||
ChatModel.AddRule(pending);
|
||||
Flash(pending.Action == ChatRuleAction.Copy
|
||||
? $"Rule added: lines like this also show in {name}"
|
||||
: $"Rule added: lines like this move to {name}", 3);
|
||||
}
|
||||
_pendingRule = null;
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
else if (cancel || ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape))
|
||||
{
|
||||
_pendingRule = null;
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
|
||||
private void DrawTabMenu()
|
||||
{
|
||||
if (!ImGuiNET.ImGui.BeginPopup("##chat_tabmenu")) return;
|
||||
string tab = _ctxTab ?? "";
|
||||
Label(tab, Teal);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Mark as read"))
|
||||
{
|
||||
var lines = UiSources.Chat.Current?.Value;
|
||||
_seenId[tab] = lines is { Length: > 0 } ? lines[^1].Id : 0;
|
||||
_unread.Remove(tab);
|
||||
}
|
||||
if (ImGuiNET.ImGui.MenuItem("Mark all tabs read"))
|
||||
{
|
||||
var lines = UiSources.Chat.Current?.Value;
|
||||
long newest = lines is { Length: > 0 } ? lines[^1].Id : 0;
|
||||
foreach (string t in ChatModel.AllTabs()) _seenId[t] = newest;
|
||||
_unread.Clear();
|
||||
}
|
||||
if (!ChatModel.IsBaseTab(tab))
|
||||
{
|
||||
if (ImGuiNET.ImGui.MenuItem("Rename…"))
|
||||
{
|
||||
_renameFrom = tab;
|
||||
WriteUtf8(_newTab, tab);
|
||||
_openRename = _focusNewTab = true;
|
||||
}
|
||||
if (ImGuiNET.ImGui.MenuItem("Delete tab")) ChatModel.DeleteCustomTab(tab);
|
||||
}
|
||||
if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters"))
|
||||
PanelRouter.Toggle("ChatFilters");
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
|
||||
private void DrawRenamePopup()
|
||||
{
|
||||
if (!ImGuiNET.ImGui.BeginPopup("##chat_rename")) return;
|
||||
Label($"Rename \"{_renameFrom}\" (its rules follow):", Mute);
|
||||
if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; }
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
bool enter = TextBox("##rename_name", _newTab, p, 140, "tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20);
|
||||
bool ok = Button("##rename_ok", "Rename", new Vector2(p.X + 144, p.Y), new Vector2(ButtonWidth("Rename"), 20), Text, TabActive);
|
||||
NextLine(p, 20);
|
||||
if (enter || ok)
|
||||
{
|
||||
if (_renameFrom != null && !ChatModel.RenameCustomTab(_renameFrom, Utf8(_newTab)))
|
||||
Flash("That name is taken (or blank)");
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
else if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape))
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
|
||||
private void DrawLineMenu()
|
||||
{
|
||||
ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(200, 0), new Vector2(420, float.MaxValue));
|
||||
if (!ImGuiNET.ImGui.BeginPopup("##chat_linemenu")) return;
|
||||
ChatLine? line = _ctxLine;
|
||||
if (line == null) { ImGuiNET.ImGui.EndPopup(); return; }
|
||||
// Coordinates in the line: point RynthNav's arrow there, or walk there (left-click
|
||||
// selects lines, so this lives in the right-click menu).
|
||||
for (int i = 0; i < _ctxCoords.Count && i < 3; i++)
|
||||
{
|
||||
ChatCoord c = _ctxCoords[i];
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.NavigationArrow + " Arrow to " + c.Text))
|
||||
RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew);
|
||||
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Play + " Go to " + c.Text))
|
||||
RynthNavCommands.Go(c.Text, c.Ns, c.Ew);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
if (_ctxCoords.Count > 0) ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Copy line")) Flash(ChatModel.CopyLines(new[] { CopyText(line) }), 1.5);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 400);
|
||||
ImGuiNET.ImGui.TextUnformatted("Lines like this: " + _ctxPattern);
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
TabMenu("Move them to", ChatRuleAction.Move);
|
||||
TabMenu("Also show them in", ChatRuleAction.Copy);
|
||||
if (ImGuiNET.ImGui.MenuItem("Hide them")) RuleFromLine(ChatRuleAction.Hide, null);
|
||||
if (ImGuiNET.ImGui.MenuItem("Colour them…")) RuleFromLine(ChatRuleAction.Color, null);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters"))
|
||||
PanelRouter.Toggle("ChatFilters");
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
527
src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs
Normal file
527
src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs
Normal file
|
|
@ -0,0 +1,527 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/ChatFiltersFace.cs
|
||||
// ImGui face of the RynthChat rule editor (the old Avalonia face is
|
||||
// UI/Panels/RynthChatFiltersPanel.cs). One card per rule:
|
||||
//
|
||||
// [#] [on] [regex ..........................] [up] [down] [delete]
|
||||
// When [Any line v] [Move to v] [Junk v] [Colour line v] [swatch]
|
||||
// (a regex error, a timed-out rule, a missing tab, or its hit count)
|
||||
//
|
||||
// The order and what each action does are spelled out in the header lines
|
||||
// (and in UI/Data/ChatData.cs). Below the rules: Add, Import / Export (the
|
||||
// clipboard, JSON), and a test box - paste a line, pick where it came from,
|
||||
// and see which rules match and where it ends up. The test runs on an edit,
|
||||
// never per frame; the chat itself is routed on the pump.
|
||||
//
|
||||
// The rules live in ChatModel. Each edit applies (the pump re-routes the
|
||||
// kept lines within 100 ms) and saves at once.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class ChatFiltersFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "ChatFilters";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(600, 460), new Vector2(440, 260), EdgeToEdge: true, GripInBody: true),
|
||||
() => new ChatFiltersFace());
|
||||
|
||||
private static readonly uint AddBg = RynthTheme.Argb(0xFF264C59), CardBg = RynthTheme.Argb(0xFF0E1822),
|
||||
FocusBorder = RynthTheme.Argb(0xFFFFD700);
|
||||
|
||||
private sealed class Buffers
|
||||
{
|
||||
public readonly byte[] Pattern = new byte[1024];
|
||||
public bool Active;
|
||||
}
|
||||
|
||||
private readonly Dictionary<ChatFilterRule, Buffers> _bufs = new();
|
||||
private long _seenVersion = -1;
|
||||
private readonly Picker _picker = new("##chatrule_pick");
|
||||
private string? _flash;
|
||||
private double _flashUntil;
|
||||
private ChatFilterRule? _focus;
|
||||
private double _focusUntil;
|
||||
private bool _scrollToFocus;
|
||||
private ChatFilterRule? _newTabFor;
|
||||
private bool _openNewTab, _focusNewTab;
|
||||
private readonly byte[] _newTab = new byte[64];
|
||||
|
||||
// Test box: re-evaluated when the text, its source or the rules change.
|
||||
private readonly byte[] _test = new byte[512];
|
||||
private int _testSource = 1; // index into ChatModel.Conditions (not 0, "any")
|
||||
private string _testSeen = "";
|
||||
private int _testSourceSeen = -1;
|
||||
private long _testVersion = -1;
|
||||
private readonly List<(string Text, uint Color)> _testResult = new();
|
||||
|
||||
public void OnShown() => ChatModel.EnsureSettingsLoaded();
|
||||
|
||||
private const string AddLabel = PhosphorIcons.Plus + " Add rule";
|
||||
private const string ImportLabel = PhosphorIcons.ClipboardText + " Import";
|
||||
private const string ExportLabel = PhosphorIcons.Copy + " Export";
|
||||
private const string Caret = " " + PhosphorIcons.CaretDown;
|
||||
|
||||
private static readonly string[] ActionLabels = { "Move to", "Copy to", "Hide", "Colour only" };
|
||||
private static readonly string[] ActionHelp =
|
||||
{
|
||||
"Move: the line shows ONLY in the chosen tab (it leaves All and its channel tab).",
|
||||
"Copy: the line also shows in the chosen tab (it stays where it was).",
|
||||
"Hide: the line is not shown anywhere (the chat log still has it).",
|
||||
"Colour only: no routing; the rule just colours.",
|
||||
};
|
||||
private static readonly string[] ColorLabels = { "No colour", "Colour line", "Colour match" };
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
ChatFilterRule[] rules = ChatModel.Filters;
|
||||
SyncBuffers(rules);
|
||||
if (ChatModel.FocusRule is { } focus)
|
||||
{
|
||||
ChatModel.FocusRule = null;
|
||||
_focus = focus;
|
||||
_focusUntil = ImGuiNET.ImGui.GetTime() + 2.5;
|
||||
_scrollToFocus = true;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text, as a case-insensitive regex.", Mute);
|
||||
Label("Where it shows: Copy rules add a tab and go on; the first Move or Hide that matches decides.", Mute);
|
||||
Label("Colour: the first \"Colour line\" wins; \"Colour match\" colours every match (a higher rule wins an overlap).", Mute);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
|
||||
|
||||
float testH = TestAreaHeight();
|
||||
Action? edit = null;
|
||||
float listH = Math.Max(60, Remaining(origin, size) - 30 - testH);
|
||||
ImGuiNET.ImGui.BeginChild("##filter_rows", new Vector2(w, listH));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
|
||||
float rowW = ImGuiNET.ImGui.GetContentRegionAvail().X - 2;
|
||||
for (int i = 0; i < rules.Length; i++)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
DrawRule(rules, i, rowW, ref edit);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
if (rules.Length == 0)
|
||||
{
|
||||
Label("No rules yet. Click \"Add rule\", or right-click a line in the chat", Mute);
|
||||
Label("and pick \"Move them to\", \"Hide them\" or \"Colour them\".", Mute);
|
||||
}
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
|
||||
// Add / Import / Export
|
||||
Vector2 ap = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float bx = ap.X;
|
||||
if (Button("##add", AddLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(AddLabel) + 4, 24), Text, AddBg))
|
||||
{
|
||||
// An empty pattern matches nothing until typed; saved now so the row survives a relaunch mid-edit.
|
||||
var rule = new ChatFilterRule();
|
||||
edit = () => ChatModel.AddRule(rule);
|
||||
}
|
||||
bx += ButtonWidth(AddLabel) + 8;
|
||||
if (Button("##import", ImportLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(ImportLabel), 24), Text, BtnFill))
|
||||
Flash(ChatModel.ImportRules(ChatModel.GetClipboardText()));
|
||||
ImGuiNET.ImGui.SetItemTooltip("Add the rules on the clipboard (an Export, or a rynthchat_settings.json) after these.");
|
||||
bx += ButtonWidth(ImportLabel) + 4;
|
||||
if (Button("##export", ExportLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(ExportLabel), 24), Text, BtnFill, rules.Length > 0))
|
||||
Flash(ChatModel.SetClipboardText(ChatModel.ExportRules())
|
||||
? $"Copied {rules.Length} rule{(rules.Length == 1 ? "" : "s")} to the clipboard"
|
||||
: "Clipboard busy - try again");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Copy every rule and your tabs to the clipboard as JSON, to share or keep.");
|
||||
bx += ButtonWidth(ExportLabel) + 8;
|
||||
if (_flash != null)
|
||||
{
|
||||
if (ImGuiNET.ImGui.GetTime() > _flashUntil) _flash = null;
|
||||
else ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(bx, ap.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, _flash);
|
||||
}
|
||||
NextLine(ap, 28);
|
||||
|
||||
DrawTest(w);
|
||||
|
||||
End(origin, size);
|
||||
_picker.Draw();
|
||||
DrawNewTabPopup();
|
||||
edit?.Invoke(); // after drawing: the rows above drew from the old list
|
||||
}
|
||||
|
||||
private void Flash(string message)
|
||||
{
|
||||
_flash = message;
|
||||
_flashUntil = ImGuiNET.ImGui.GetTime() + 3;
|
||||
}
|
||||
|
||||
// ── One rule ─────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawRule(ChatFilterRule[] rules, int i, float rowW, ref Action? edit)
|
||||
{
|
||||
ChatFilterRule r = rules[i];
|
||||
Buffers b = _bufs[r];
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 card = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
dl.ChannelsSplit(2);
|
||||
dl.ChannelsSetCurrent(1);
|
||||
const float rowH = 22;
|
||||
|
||||
// Row 1: number, on, pattern, up, down, delete.
|
||||
Vector2 p = card + new Vector2(4, 4);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
dl.AddText(new Vector2(p.X, p.Y + 5), Faded(Mute), (i + 1).ToString());
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 16, p.Y + 1));
|
||||
bool on = r.Enabled;
|
||||
if (ImGuiNET.ImGui.Checkbox("##on", ref on)) { r.Enabled = on; ChatModel.FiltersChanged(); }
|
||||
ImGuiNET.ImGui.SetItemTooltip(on ? "Rule on (click to turn off)" : "Rule off (click to turn on)");
|
||||
|
||||
const float btn = 22;
|
||||
float x = p.X + 42;
|
||||
float patW = Math.Max(80, card.X + rowW - 4 - 3 * (btn + 2) - 4 - x);
|
||||
if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, "regex, e.g. ^You have been healed", out bool patActive))
|
||||
{
|
||||
r.Pattern = Utf8(b.Pattern);
|
||||
r.Recompile();
|
||||
ChatModel.FiltersChanged();
|
||||
}
|
||||
b.Active = patActive;
|
||||
if (r.Invalid && r.Pattern.Length > 0)
|
||||
dl.AddRect(new Vector2(x, p.Y), new Vector2(x + patW, p.Y + rowH), Red, 3);
|
||||
else if (r.Slow)
|
||||
dl.AddRect(new Vector2(x, p.Y), new Vector2(x + patW, p.Y + rowH), Amber, 3);
|
||||
x += patW + 4;
|
||||
ChatFilterRule rule = r;
|
||||
if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i > 0))
|
||||
edit = () => ChatModel.MoveFilter(rule, -1);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Move up (runs earlier)");
|
||||
x += btn + 2;
|
||||
if (IconButton("##down", PhosphorIcons.ArrowDown, new Vector2(x, p.Y), new Vector2(btn, rowH), Text, BtnFill, i < rules.Length - 1))
|
||||
edit = () => ChatModel.MoveFilter(rule, +1);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Move down (runs later)");
|
||||
x += btn + 2;
|
||||
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x, p.Y), new Vector2(btn, rowH), Red, BtnFill))
|
||||
edit = () => ChatModel.EditFilters(list => list.Remove(rule));
|
||||
ImGuiNET.ImGui.SetItemTooltip("Delete this rule");
|
||||
|
||||
// Row 2 (wraps when narrow): When, action, tab, colour mode, swatch.
|
||||
float left = p.X + 42, right = card.X + rowW - 4;
|
||||
var flow = new Flow(left, p.Y + rowH + 4, right, rowH);
|
||||
|
||||
string whenText = "When: " + ChatModel.ConditionLabel(r.When) + Caret;
|
||||
Vector2 wp = flow.Place(Math.Min(ButtonWidth(whenText), 240));
|
||||
if (Button("##when", whenText, wp, new Vector2(Math.Min(ButtonWidth(whenText), 240), rowH), Text, BtnFill, leftAlign: true))
|
||||
OpenWhenPicker(rule, wp);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Only lines from this channel or chat type (Any line: every line)");
|
||||
|
||||
int action = (int)r.Action;
|
||||
string actText = ActionLabels[action] + Caret;
|
||||
Vector2 aPos = flow.Place(ButtonWidth(actText));
|
||||
if (Button("##act", actText, aPos, new Vector2(ButtonWidth(actText), rowH), Text, BtnFill))
|
||||
_picker.Open(aPos + new Vector2(0, rowH + 2), ActionLabels, action, k =>
|
||||
{
|
||||
rule.Action = (ChatRuleAction)k;
|
||||
if (rule.Action == ChatRuleAction.Color && rule.ColorMode == ChatColorMode.None) rule.ColorMode = ChatColorMode.Line;
|
||||
ChatModel.FiltersChanged();
|
||||
}, 140);
|
||||
ImGuiNET.ImGui.SetItemTooltip(ActionHelp[action]);
|
||||
|
||||
if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy)
|
||||
{
|
||||
bool noTab = r.Tab.Length == 0;
|
||||
string tabText = (noTab ? "pick a tab" : r.Tab) + Caret;
|
||||
Vector2 tPos = flow.Place(ButtonWidth(tabText));
|
||||
if (Button("##tab", tabText, tPos, new Vector2(ButtonWidth(tabText), rowH), noTab ? Amber : Teal, BtnFill))
|
||||
OpenTabPicker(rule, tPos);
|
||||
ImGuiNET.ImGui.SetItemTooltip("The tab it goes to (pick \"New tab…\" to make one)");
|
||||
}
|
||||
|
||||
if (r.Action != ChatRuleAction.Hide)
|
||||
{
|
||||
int mode = (int)r.ColorMode;
|
||||
string colText = ColorLabels[mode] + Caret;
|
||||
Vector2 cPos = flow.Place(ButtonWidth(colText));
|
||||
if (Button("##colmode", colText, cPos, new Vector2(ButtonWidth(colText), rowH), Text, BtnFill))
|
||||
_picker.Open(cPos + new Vector2(0, rowH + 2), ColorLabels, mode, k =>
|
||||
{
|
||||
rule.ColorMode = (ChatColorMode)k;
|
||||
ChatModel.FiltersChanged();
|
||||
}, 130);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the regex matched.");
|
||||
if (r.ColorMode != ChatColorMode.None)
|
||||
{
|
||||
Vector2 sPos = flow.Place(rowH);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(sPos + new Vector2(2, 2));
|
||||
Vector4 v = RynthTheme.Vec(r.ColorArgb);
|
||||
var rgb = new Vector3(v.X, v.Y, v.Z);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 3));
|
||||
if (ImGuiNET.ImGui.ColorEdit3("##col", ref rgb, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
{
|
||||
r.ColorArgb = 0xFF000000
|
||||
| ((uint)Math.Clamp((int)MathF.Round(rgb.X * 255), 0, 255) << 16)
|
||||
| ((uint)Math.Clamp((int)MathF.Round(rgb.Y * 255), 0, 255) << 8)
|
||||
| (uint)Math.Clamp((int)MathF.Round(rgb.Z * 255), 0, 255);
|
||||
ChatModel.FiltersChanged();
|
||||
}
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
}
|
||||
}
|
||||
|
||||
// Row 3: what's wrong, or what it's doing.
|
||||
float y = flow.Bottom + 3;
|
||||
(string? note, uint noteColor) = RuleNote(r);
|
||||
if (note != null)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
ImGuiNET.ImGui.PushClipRect(new Vector2(left, y), new Vector2(right, y + 40), true);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(left, y));
|
||||
ImGuiNET.ImGui.PushTextWrapPos(right - ImGuiNET.ImGui.GetWindowPos().X + ImGuiNET.ImGui.GetScrollX());
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, noteColor);
|
||||
ImGuiNET.ImGui.TextUnformatted(note);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
ImGuiNET.ImGui.PopClipRect();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
float bottom = Math.Max(y, flow.Bottom + 2) + 4;
|
||||
|
||||
// Card background under everything (channel 0), dimmed while off.
|
||||
dl.ChannelsSetCurrent(0);
|
||||
bool focused = ReferenceEquals(r, _focus) && ImGuiNET.ImGui.GetTime() < _focusUntil;
|
||||
dl.AddRectFilled(card, new Vector2(card.X + rowW, bottom), r.Enabled ? CardBg : RowAlt, 4);
|
||||
dl.AddRect(card, new Vector2(card.X + rowW, bottom), focused ? FocusBorder : BtnBord, 4);
|
||||
dl.ChannelsMerge();
|
||||
if (!r.Enabled)
|
||||
dl.AddRectFilled(card, new Vector2(card.X + rowW, bottom), RynthTheme.Argb(0x55000000), 4);
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(card.X, bottom));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(rowW, 4));
|
||||
if (_scrollToFocus && ReferenceEquals(r, _focus))
|
||||
{
|
||||
_scrollToFocus = false;
|
||||
ImGuiNET.ImGui.SetScrollHereY(1f); // bring the new rule into view
|
||||
}
|
||||
}
|
||||
|
||||
private static (string? Note, uint Color) RuleNote(ChatFilterRule r)
|
||||
{
|
||||
if (r.Pattern.Length == 0) return ("Type a pattern: the rule matches nothing until then.", Faded(Mute));
|
||||
if (r.Invalid) return ("Regex error: " + (r.Error ?? "doesn't compile"), Red);
|
||||
if (r.Slow) return ("Too slow: matching it took too long (see the RynthCore log), so the rule is skipped. Edit the pattern to try again.", Amber);
|
||||
if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy && r.Tab.Length == 0)
|
||||
return ("Pick a tab: until then it only colours.", Amber);
|
||||
if (!r.Enabled) return ("Off.", Faded(Mute));
|
||||
int hits = System.Threading.Volatile.Read(ref r.Hits);
|
||||
return (hits == 0 ? "No recent line matches." : $"Matches {hits} recent line{(hits == 1 ? "" : "s")}.", Faded(Mute));
|
||||
}
|
||||
|
||||
/// <summary>Left-to-right placement that wraps to a new row when the next item doesn't fit.</summary>
|
||||
private struct Flow
|
||||
{
|
||||
private readonly float _left, _right, _h;
|
||||
private float _x, _y;
|
||||
public Flow(float left, float top, float right, float h) { _left = _x = left; _right = right; _y = top; _h = h; }
|
||||
public float Bottom => _y + _h;
|
||||
|
||||
public Vector2 Place(float w)
|
||||
{
|
||||
if (_x > _left && _x + w > _right) { _x = _left; _y += _h + 3; }
|
||||
var at = new Vector2(_x, _y);
|
||||
_x += w + 4;
|
||||
return at;
|
||||
}
|
||||
}
|
||||
|
||||
private void OpenWhenPicker(ChatFilterRule rule, Vector2 at)
|
||||
{
|
||||
var labels = new string[ChatModel.Conditions.Length];
|
||||
int sel = 0;
|
||||
for (int k = 0; k < labels.Length; k++)
|
||||
{
|
||||
labels[k] = ChatModel.Conditions[k].Label;
|
||||
if (string.Equals(ChatModel.Conditions[k].Value, rule.When, StringComparison.OrdinalIgnoreCase)) sel = k;
|
||||
}
|
||||
_picker.Open(at + new Vector2(0, 24), labels, sel, k =>
|
||||
{
|
||||
rule.When = ChatModel.Conditions[k].Value;
|
||||
ChatModel.FiltersChanged();
|
||||
}, 260);
|
||||
}
|
||||
|
||||
private void OpenTabPicker(ChatFilterRule rule, Vector2 at)
|
||||
{
|
||||
string[] tabs = ChatModel.TargetTabs();
|
||||
var items = new string[tabs.Length + 1];
|
||||
Array.Copy(tabs, items, tabs.Length);
|
||||
items[^1] = PhosphorIcons.Plus + " New tab…";
|
||||
int sel = Array.FindIndex(tabs, t => string.Equals(t, rule.Tab, StringComparison.OrdinalIgnoreCase));
|
||||
_picker.Open(at + new Vector2(0, 24), items, sel, k =>
|
||||
{
|
||||
if (k == tabs.Length)
|
||||
{
|
||||
_newTabFor = rule;
|
||||
WriteUtf8(_newTab, "");
|
||||
_openNewTab = _focusNewTab = true;
|
||||
return;
|
||||
}
|
||||
rule.Tab = tabs[k];
|
||||
ChatModel.FiltersChanged();
|
||||
}, 180);
|
||||
}
|
||||
|
||||
private void DrawNewTabPopup()
|
||||
{
|
||||
if (_openNewTab) { _openNewTab = false; ImGuiNET.ImGui.OpenPopup("##chatrule_newtab"); }
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 6));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##chatrule_newtab");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (!open) return;
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
|
||||
if (_focusNewTab) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _focusNewTab = false; }
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
bool enter = TextBox("##ruletab_name", _newTab, p, 140, "new tab name", out _, ImGuiInputTextFlags.EnterReturnsTrue, 20);
|
||||
bool add = Button("##ruletab_add", "Add", new Vector2(p.X + 144, p.Y), new Vector2(ButtonWidth("Add"), 20), Text, AddBg);
|
||||
NextLine(p, 20);
|
||||
if (enter || add)
|
||||
{
|
||||
string? name = ChatModel.AddCustomTab(Utf8(_newTab), select: false);
|
||||
if (name != null && _newTabFor != null)
|
||||
{
|
||||
_newTabFor.Tab = name;
|
||||
ChatModel.FiltersChanged();
|
||||
}
|
||||
_newTabFor = null;
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
else if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape))
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
|
||||
// ── Test box ─────────────────────────────────────────────────────────
|
||||
|
||||
private float TestAreaHeight()
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
float lh = ImGuiNET.ImGui.GetTextLineHeightWithSpacing();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
return 16 + 26 + Math.Max(1, _testResult.Count) * lh + 4;
|
||||
}
|
||||
|
||||
private void DrawTest(float w)
|
||||
{
|
||||
Label("Test a line - paste one from the chat (right-click it, Copy line):", Mute);
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
string srcLabel = "from: " + ChatModel.Conditions[_testSource].Label + Caret;
|
||||
float srcW = Math.Min(ButtonWidth(srcLabel), 230);
|
||||
TextBox("##test", _test, p, Math.Max(80, w - srcW - 4), "e.g. Bob tells you, \"hi\"", out _);
|
||||
var sp = new Vector2(p.X + w - srcW, p.Y);
|
||||
if (Button("##testsrc", srcLabel, sp, new Vector2(srcW, 22), Text, BtnFill, leftAlign: true))
|
||||
{
|
||||
var labels = new string[ChatModel.Conditions.Length - 1];
|
||||
for (int k = 1; k < ChatModel.Conditions.Length; k++) labels[k - 1] = ChatModel.Conditions[k].Label;
|
||||
_picker.Open(sp + new Vector2(0, 24), labels, _testSource - 1, k => _testSource = k + 1, 260);
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Where the test line came from (for rules with a When)");
|
||||
NextLine(p, 26);
|
||||
|
||||
string text = Utf8(_test);
|
||||
long version = ChatModel.FiltersVersion;
|
||||
if (text != _testSeen || _testSource != _testSourceSeen || version != _testVersion)
|
||||
{
|
||||
_testSeen = text;
|
||||
_testSourceSeen = _testSource;
|
||||
_testVersion = version;
|
||||
RunTest(text);
|
||||
}
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
// The result lines reach the body's bottom edge: a long one is cut short of
|
||||
// the resize grip (GripInBody) instead of running under it.
|
||||
float grip = ImGuiPanelHost.BodyGripReserve;
|
||||
if (grip > 0)
|
||||
{
|
||||
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImGuiNET.ImGui.PushClipRect(at, new Vector2(at.X + w - grip, at.Y + 4096), true);
|
||||
}
|
||||
foreach ((string line, uint color) in _testResult) Label(line, color);
|
||||
if (grip > 0) ImGuiNET.ImGui.PopClipRect();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
/// <summary>Runs the rules over the test line. On an edit only (UI thread; each regex has its timeout).</summary>
|
||||
private void RunTest(string text)
|
||||
{
|
||||
_testResult.Clear();
|
||||
text = text.Trim();
|
||||
// A line copied from the chat starts with its timestamp; the rules never see that.
|
||||
if (text.Length > 9 && text[2] == ':' && text[5] == ':' && text[8] == ' ' && char.IsDigit(text[0])) text = text[9..];
|
||||
if (text.Length == 0) { _testResult.Add(("Paste a line to see which rules match and where it goes.", Faded(Mute))); return; }
|
||||
|
||||
string when = ChatModel.Conditions[_testSource].Value;
|
||||
string channel = "Chat";
|
||||
int type = -1;
|
||||
if (when.StartsWith("chan:", StringComparison.Ordinal)) channel = when[5..];
|
||||
else if (when.StartsWith("type:", StringComparison.Ordinal) && int.TryParse(when[5..], out int t))
|
||||
{
|
||||
type = t;
|
||||
channel = ChatModel.ChannelForType(t);
|
||||
}
|
||||
if (text.StartsWith("[Rynth", StringComparison.OrdinalIgnoreCase)) channel = "Rynth";
|
||||
|
||||
var trace = new List<ChatRouter.Step>();
|
||||
ChatRoute route = ChatModel.TestRouter().Evaluate(text, channel, type, trace);
|
||||
foreach (ChatRouter.Step step in trace)
|
||||
_testResult.Add(((step.Rule < 0 ? "Your name" : $"Rule {step.Rule + 1}") + ": " + step.What, Text));
|
||||
if (trace.Count == 0) _testResult.Add(("No rule matches.", Faded(Mute)));
|
||||
|
||||
string where;
|
||||
if (route.Hidden) where = "Hidden: shown nowhere.";
|
||||
else
|
||||
{
|
||||
var tabs = new List<string>();
|
||||
if (route.InHome) { tabs.Add("All"); tabs.Add(channel); }
|
||||
if (route.Tabs != null) tabs.AddRange(route.Tabs);
|
||||
where = tabs.Count == 0 ? "Shown nowhere." : "Shows in: " + string.Join(", ", tabs) + ".";
|
||||
}
|
||||
uint color = RynthTheme.Argb(route.LineArgb ?? ChatModel.ChannelArgb(channel));
|
||||
_testResult.Add((where + (route.LineArgb != null ? " (this is its colour)" : ""), route.Hidden ? Faded(Mute) : color));
|
||||
}
|
||||
|
||||
/// <summary>Buffers for each rule; refilled from the rules when another face changed them,
|
||||
/// except the row being typed in.</summary>
|
||||
private void SyncBuffers(ChatFilterRule[] rules)
|
||||
{
|
||||
long version = ChatModel.FiltersVersion;
|
||||
bool changed = version != _seenVersion;
|
||||
_seenVersion = version;
|
||||
foreach (ChatFilterRule r in rules)
|
||||
{
|
||||
if (!_bufs.TryGetValue(r, out Buffers? b))
|
||||
{
|
||||
_bufs[r] = b = new Buffers();
|
||||
WriteUtf8(b.Pattern, r.Pattern);
|
||||
}
|
||||
else if (changed && !b.Active)
|
||||
WriteUtf8(b.Pattern, r.Pattern);
|
||||
}
|
||||
if (_bufs.Count > rules.Length)
|
||||
{
|
||||
var live = new HashSet<ChatFilterRule>(rules);
|
||||
foreach (ChatFilterRule gone in new List<ChatFilterRule>(_bufs.Keys))
|
||||
if (!live.Contains(gone)) _bufs.Remove(gone);
|
||||
}
|
||||
}
|
||||
}
|
||||
563
src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs
Normal file
563
src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs
Normal file
|
|
@ -0,0 +1,563 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/DamageDetailFace.cs
|
||||
// "Monster Detail": everything the Damage panel knows about one monster,
|
||||
// opened by clicking its name there. The Damage panel keeps only what you
|
||||
// set and sort by; the numbers behind it live here:
|
||||
// header HP (and where it came from), seconds per kill, hit rate
|
||||
// Weak to all eight elements as damage taken (1.0 = full) + source
|
||||
// Accuracy per weapon: hits, misses, hit %, seconds per kill
|
||||
// Damage per weapon / element / spell tier: avg, crit, non-crit,
|
||||
// crit rate, casts per kill, kills
|
||||
// Summons kills and seconds per kill per summon element (and none)
|
||||
// Damage taken per element: hits, average, biggest
|
||||
// Rule priority, damage type, extra vuln, match expression, spell
|
||||
// shapes (debuffs: the Damage panel's caret)
|
||||
// "Default" shows only Rule: the settings every monster on Default uses.
|
||||
// A name rule (wcid 0 + a rule name, from the Damage panel's Name rules,
|
||||
// e.g. "Olthoi") shows only Rule, plus its debuffs, off hand, pet, rename
|
||||
// and delete: it has no row in the Damage panel to hold them.
|
||||
//
|
||||
// Data: UiSources.MonsterDetail (the selected wcid) and MonsterRules; edits
|
||||
// go through DamageCommands on the pump thread. No Avalonia twin; pops out as ImGui.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using Rule = RynthCore.Engine.UI.Panels.MonstersPanel.Rule;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class DamageDetailFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Monster Detail";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(560, 620), new Vector2(360, 240)),
|
||||
() => new DamageDetailFace());
|
||||
|
||||
private static string _selectedName = "";
|
||||
|
||||
/// <summary>
|
||||
/// Shows <paramref name="wcid"/> in the Monster Detail panel, opening it. wcid 0 shows a
|
||||
/// rule only: <paramref name="name"/>'s (a name rule, or a monster not met yet), or the
|
||||
/// Default settings when the name is empty or "Default".
|
||||
/// </summary>
|
||||
public static void Show(uint wcid, string name)
|
||||
{
|
||||
_selectedName = wcid == 0 && (string.IsNullOrWhiteSpace(name) || IsDefaultName(name)) ? "Default" : name;
|
||||
MonsterDetailSource.SelectedWcid = wcid;
|
||||
_showCount++;
|
||||
UiSources.MonsterDetail.RequestRefresh();
|
||||
ImGuiPanelHost.Open(Title);
|
||||
}
|
||||
|
||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||
private static readonly uint Teal = C(0xFF26D9E6), Gold = C(0xFFFFD16A), Dim = C(0xFFC8D4E0), White = C(0xFFF2F7FC),
|
||||
EntryBg = C(0xFF16283A), EntryBorder = C(0xFF34587A), ToggleOn = C(0xFF33CC66), ToggleOff = C(0xFF4D4D4D),
|
||||
BarBg = C(0xFF16222E), Good = C(0xFF33CC66), Mid = C(0xFFE8B333), Bad = C(0xFFE05A5A), DeleteBg = C(0xFF6E1E1E),
|
||||
DeleteBorder = C(0xFFFF8A8A);
|
||||
|
||||
private MonsterDetail? _detail;
|
||||
private long _seenVersion = -1, _seenRulesVersion = -1;
|
||||
private MonsterRulesSnapshot? _rules;
|
||||
private bool _confirmRemove;
|
||||
private static int _showCount;
|
||||
private int _seenShow = -1;
|
||||
|
||||
// The Rule section's edit boxes: whose rule they hold, the saved values they were
|
||||
// last loaded from, and whether one is being typed in.
|
||||
private string _bufFor = "";
|
||||
private int _prioSeen = int.MinValue;
|
||||
private string? _exprSeen;
|
||||
private bool _prioActive, _exprActive;
|
||||
private readonly byte[] _prioBuf = new byte[12], _exprBuf = new byte[512], _renameBuf = new byte[128];
|
||||
private string? _renaming; // a rename just sent: "Loading…" until the rule comes back under it
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.MonsterDetail.Subscribe();
|
||||
UiSources.MonsterRules.Subscribe();
|
||||
UiSources.MonsterDetail.RequestRefresh();
|
||||
UiSources.MonsterRules.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
UiSources.MonsterDetail.Unsubscribe();
|
||||
UiSources.MonsterRules.Unsubscribe();
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
var snap = UiSources.MonsterDetail.Current;
|
||||
if (snap != null && snap.Version != _seenVersion) { _seenVersion = snap.Version; _detail = snap.Value; }
|
||||
var rules = UiSources.MonsterRules.Current;
|
||||
if (rules != null && rules.Version != _seenRulesVersion) { _seenRulesVersion = rules.Version; _rules = rules.Value; }
|
||||
|
||||
if (_seenShow != _showCount) { _seenShow = _showCount; _confirmRemove = false; } // another monster: no stale confirm
|
||||
uint wcid = MonsterDetailSource.SelectedWcid;
|
||||
bool isDefault = wcid == 0 && IsDefaultName(_selectedName);
|
||||
bool nameRule = wcid == 0 && !isDefault;
|
||||
MonsterDetail? d = _detail != null && _detail.Wcid == wcid && wcid != 0 ? _detail : null;
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4));
|
||||
|
||||
// ── Header ───────────────────────────────────────────────────────
|
||||
string name = d != null && d.Name.Length > 0 ? d.Name : _selectedName;
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
ImGuiNET.ImGui.TextColored(Vec(Teal), isDefault ? "DEFAULT" : name);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
if (isDefault)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "The spell settings every monster set to Default uses.");
|
||||
}
|
||||
else if (nameRule)
|
||||
{
|
||||
NameRuleHeader(name);
|
||||
}
|
||||
else if (d == null)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), _detail != null && !_detail.Bound ? "Waiting for RynthAi…" : "Loading…");
|
||||
}
|
||||
else
|
||||
{
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "wcid " + wcid.ToString(CultureInfo.InvariantCulture));
|
||||
// Aelrynth only: which difficulty tier these numbers are (the Damage panel's chip picks it).
|
||||
if (UiSources.Damage.Current?.Value.Tier is { Show: true } tier)
|
||||
{
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.TextColored(Vec(tier.View == tier.Current ? Teal : Gold),
|
||||
tier.View <= 0 ? "· Tier 0 (real Dereth)" : "· Tier " + tier.View.ToString(CultureInfo.InvariantCulture));
|
||||
ImGuiNET.ImGui.SetItemTooltip("HP, casts to kill, seconds per kill, hits and damage taken are this difficulty tier's.\n" +
|
||||
"Damage per cast and weaknesses are the same at every tier. Change it on the Damage panel.");
|
||||
}
|
||||
string hp = d.Hp > 0 ? $"HP {d.Hp:N0} ({d.HpSrc})" : "HP unknown";
|
||||
string sec = d.SecKill > 0 ? $"{d.SecKill:0.0} s per kill" : "no timed kills yet";
|
||||
string hit = d.HitRate >= 0 ? $"{d.HitRate * 100:0}% hits" : "no hits yet";
|
||||
ImGuiNET.ImGui.TextColored(Vec(White), $"{hp} · {sec} · {hit}");
|
||||
|
||||
float bw = ImGuiNET.ImGui.CalcTextSize(RemoveLabel).X + 16;
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
float room = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
if (room > bw) ImGuiNET.ImGui.SetCursorPosX(ImGuiNET.ImGui.GetCursorPosX() + room - bw);
|
||||
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (FaceKit.Button("##remove", RemoveLabel, bp, new Vector2(bw, ImGuiNET.ImGui.GetFrameHeight()), White, DeleteBg, border: DeleteBorder))
|
||||
_confirmRemove = true;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Take this monster off the Damage panel: its learned numbers and your settings for it. It comes back if you meet it again.");
|
||||
if (_confirmRemove)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(Vec(Gold), "Remove " + name + " and everything learned about it?");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.SmallButton("Remove##yes"))
|
||||
{
|
||||
DamageCommands.RemoveMonster(wcid);
|
||||
_confirmRemove = false;
|
||||
ImGuiPanelHost.Close(Title);
|
||||
}
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.SmallButton("Cancel##no")) _confirmRemove = false;
|
||||
}
|
||||
|
||||
WeakSection(d);
|
||||
AccuracySection(d);
|
||||
DamageSection(d);
|
||||
SummonSection(d);
|
||||
TakenSection(d);
|
||||
}
|
||||
|
||||
RuleSection(isDefault ? "Default" : name, nameRule);
|
||||
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
private static bool IsDefaultName(string name) => name.Equals("Default", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// A name rule's header: what it matches, and Delete rule (confirmed).
|
||||
private void NameRuleHeader(string name)
|
||||
{
|
||||
Rule? rule = _rules?.FindRule(name);
|
||||
if (rule != null) _renaming = null;
|
||||
ImGuiNET.ImGui.PushTextWrapPos(0);
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), rule == null
|
||||
? (_rules == null || _renaming == name ? "Loading…" : "There is no rule with this name (deleted?).")
|
||||
: "A name rule: used for every monster whose name contains \"" + name + "\""
|
||||
+ (string.IsNullOrWhiteSpace(rule.MatchExpression) ? "" : " and its match expression is true")
|
||||
+ ", unless a rule higher in the Name rules list matches it first.");
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
if (rule == null) return;
|
||||
|
||||
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float bw = ImGuiNET.ImGui.CalcTextSize(DeleteRuleLabel).X + 16;
|
||||
if (FaceKit.Button("##delrule", DeleteRuleLabel, bp, new Vector2(bw, ImGuiNET.ImGui.GetFrameHeight()), White, DeleteBg, border: DeleteBorder))
|
||||
_confirmRemove = true;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Delete this rule. Monsters it covered go back to Default (or another rule that matches).");
|
||||
if (!_confirmRemove) return;
|
||||
ImGuiNET.ImGui.TextColored(Vec(Gold), "Delete the rule " + name + "?");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.SmallButton("Delete##yes"))
|
||||
{
|
||||
DamageCommands.ResetRule(name);
|
||||
_confirmRemove = false;
|
||||
ImGuiPanelHost.Close(Title);
|
||||
}
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.SmallButton("Cancel##no")) _confirmRemove = false;
|
||||
}
|
||||
|
||||
// ── Sections ─────────────────────────────────────────────────────────
|
||||
|
||||
private static bool Section(string title)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Header, EntryBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, FaceKit.Lighten(EntryBg));
|
||||
bool open = ImGuiNET.ImGui.CollapsingHeader(title, ImGuiTreeNodeFlags.DefaultOpen);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
return open;
|
||||
}
|
||||
|
||||
private static void WeakSection(MonsterDetail d)
|
||||
{
|
||||
if (!Section("Weak to")) return;
|
||||
if (d.Weak.Count == 0)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "Nothing known yet: not in the server data, no creature type, nothing learned.");
|
||||
return;
|
||||
}
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "Damage it takes from each element (1.0 = full, 0.5 = half), from " + d.WeakSrc + ".");
|
||||
float labelW = ImGuiNET.ImGui.CalcTextSize("Lightning ").X;
|
||||
float barW = Math.Max(80, ImGuiNET.ImGui.GetContentRegionAvail().X - labelW - ImGuiNET.ImGui.CalcTextSize(" 0.00x").X - 8);
|
||||
double top = 1.0;
|
||||
foreach (var (_, m) in d.Weak) if (m > top) top = m;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float h = ImGuiNET.ImGui.GetTextLineHeight();
|
||||
foreach (var (e, m) in d.Weak)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
dl.AddText(p, White, e);
|
||||
Vector2 b0 = p + new Vector2(labelW, 2), b1 = b0 + new Vector2(barW, h - 4);
|
||||
dl.AddRectFilled(b0, b1, BarBg, 2);
|
||||
if (m >= 0)
|
||||
{
|
||||
float f = (float)Math.Clamp(m / top, 0, 1);
|
||||
uint col = m >= 1.0 ? Good : m >= 0.6 ? Mid : Bad;
|
||||
dl.AddRectFilled(b0, b0 + new Vector2(barW * f, h - 4), col, 2);
|
||||
dl.AddText(new Vector2(b1.X + 6, p.Y), White, m.ToString("0.00", CultureInfo.InvariantCulture) + "x");
|
||||
}
|
||||
else
|
||||
dl.AddText(new Vector2(b1.X + 6, p.Y), Dim, "learned");
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(labelW + barW + 60, h));
|
||||
}
|
||||
}
|
||||
|
||||
private static void AccuracySection(MonsterDetail d)
|
||||
{
|
||||
if (!Section("Accuracy and speed")) return;
|
||||
if (d.Weapons.Count == 0) { ImGuiNET.ImGui.TextColored(Vec(Dim), "No attacks recorded yet."); return; }
|
||||
if (!BeginTable("##acc", "Weapon", "Hit %", "Hits", "Misses", "Sec/Kill", "Timed kills")) return;
|
||||
foreach (var (w, hits, misses, sec, secN) in d.Weapons)
|
||||
{
|
||||
ImGuiNET.ImGui.TableNextRow();
|
||||
Cell(w);
|
||||
Cell(hits + misses > 0 ? $"{100.0 * hits / (hits + misses):0}%" : "—");
|
||||
Cell(hits.ToString(CultureInfo.InvariantCulture));
|
||||
Cell(misses.ToString(CultureInfo.InvariantCulture));
|
||||
Cell(sec > 0 ? sec.ToString("0.0", CultureInfo.InvariantCulture) : "—");
|
||||
Cell(secN.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
ImGuiNET.ImGui.EndTable();
|
||||
}
|
||||
|
||||
private static void DamageSection(MonsterDetail d)
|
||||
{
|
||||
if (!Section("Damage")) return;
|
||||
if (d.Casts.Count == 0) { ImGuiNET.ImGui.TextColored(Vec(Dim), "No damage recorded yet."); return; }
|
||||
if (!BeginTable("##dmg", "Weapon", "Element", "Tier", "Avg", "Crit", "Non-crit", "Crit %", "Casts/Kill", "Kills")) return;
|
||||
foreach (DetailCast c in d.Casts)
|
||||
{
|
||||
ImGuiNET.ImGui.TableNextRow();
|
||||
Cell(c.Weapon);
|
||||
Cell(c.Elem);
|
||||
Cell(DamageSource.FormatTier(c.Tier));
|
||||
Cell(c.Hits > 0 ? c.Avg.ToString("0", CultureInfo.InvariantCulture) : "—");
|
||||
Cell(c.CritN > 0 ? c.Crit.ToString("0", CultureInfo.InvariantCulture) : "—");
|
||||
Cell(c.NonCritN > 0 ? c.NonCrit.ToString("0", CultureInfo.InvariantCulture) : "—");
|
||||
Cell(c.CritN + c.NonCritN > 0 ? $"{100.0 * c.CritN / (c.CritN + c.NonCritN):0}%" : "—");
|
||||
Cell(c.Kills > 0 ? c.Casts.ToString("0.00", CultureInfo.InvariantCulture) : "—");
|
||||
Cell(c.Kills.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
ImGuiNET.ImGui.EndTable();
|
||||
}
|
||||
|
||||
private static void SummonSection(MonsterDetail d)
|
||||
{
|
||||
if (!Section("Summons")) return;
|
||||
if (d.Summons.Count == 0)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "No timed kills yet. (The game doesn't report a summon's own damage, so this compares kill times.)");
|
||||
return;
|
||||
}
|
||||
if (!BeginTable("##pets", "Summon", "Kills", "Sec/Kill")) return;
|
||||
foreach (var (e, kills, sec) in d.Summons)
|
||||
{
|
||||
ImGuiNET.ImGui.TableNextRow();
|
||||
Cell(e);
|
||||
Cell(kills.ToString(CultureInfo.InvariantCulture));
|
||||
Cell(sec > 0 ? sec.ToString("0.0", CultureInfo.InvariantCulture) : "—");
|
||||
}
|
||||
ImGuiNET.ImGui.EndTable();
|
||||
}
|
||||
|
||||
private static void TakenSection(MonsterDetail d)
|
||||
{
|
||||
if (!Section("Damage taken")) return;
|
||||
if (d.Taken.Count == 0) { ImGuiNET.ImGui.TextColored(Vec(Dim), "It hasn't hit you yet."); return; }
|
||||
if (!BeginTable("##taken", "Element", "Hits", "Average", "Biggest")) return;
|
||||
foreach (var (e, hits, avg, max) in d.Taken)
|
||||
{
|
||||
ImGuiNET.ImGui.TableNextRow();
|
||||
Cell(e);
|
||||
Cell(hits.ToString(CultureInfo.InvariantCulture));
|
||||
Cell(avg.ToString("0", CultureInfo.InvariantCulture));
|
||||
Cell(max.ToString("0", CultureInfo.InvariantCulture));
|
||||
}
|
||||
ImGuiNET.ImGui.EndTable();
|
||||
}
|
||||
|
||||
// The rule a monster (or Default, or a name rule) uses: priority, damage type, extra vuln,
|
||||
// match expression, spell shapes; a name rule also debuffs, off hand, pet and its name.
|
||||
// A monster following Default gets its own rule (a copy of Default) on the first change.
|
||||
private void RuleSection(string name, bool nameRule)
|
||||
{
|
||||
if (!Section("Rule")) return;
|
||||
if (_rules == null || _rules.Parsed.Rules.Count == 0)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "Monster rules not loaded yet.");
|
||||
return;
|
||||
}
|
||||
bool isDefault = IsDefaultName(name);
|
||||
Rule? exact = isDefault ? null : _rules.FindRule(name);
|
||||
if (nameRule && exact == null) return; // deleted: editing would make it again
|
||||
bool custom = exact != null;
|
||||
Rule view = isDefault ? _rules.DefaultRule() : exact ?? _rules.DefaultRule();
|
||||
|
||||
if (!nameRule)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(Vec(custom || isDefault ? Gold : Dim),
|
||||
isDefault ? "Applies to every monster set to Default." : custom ? "Custom settings for this monster." : "Following Default (a change here gives it its own settings).");
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), DebuffsHint);
|
||||
if (custom)
|
||||
{
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.SmallButton("Back to Default")) DamageCommands.ResetRule(name);
|
||||
}
|
||||
}
|
||||
|
||||
// The edit boxes reload from the rule when its saved value changes (not every frame,
|
||||
// so a value just entered stays while the plugin saves it).
|
||||
if (_bufFor != name)
|
||||
{
|
||||
_bufFor = name;
|
||||
_prioSeen = int.MinValue;
|
||||
_exprSeen = null;
|
||||
WriteUtf8(_renameBuf, name);
|
||||
}
|
||||
|
||||
// Priority
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "Priority");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (!_prioActive && _prioSeen != view.Priority)
|
||||
{
|
||||
WriteUtf8(_prioBuf, view.Priority.ToString(CultureInfo.InvariantCulture));
|
||||
_prioSeen = view.Priority;
|
||||
}
|
||||
ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("0000").X + 12);
|
||||
bool enter = ImGuiNET.ImGui.InputText("##prio", _prioBuf, (uint)_prioBuf.Length,
|
||||
ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
_prioActive = ImGuiNET.ImGui.IsItemActive();
|
||||
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
if (int.TryParse(Utf8(_prioBuf).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int prio))
|
||||
{
|
||||
if (prio != view.Priority) DamageCommands.EditRule(name, r => r.Priority = prio);
|
||||
}
|
||||
else _prioSeen = int.MinValue; // not a number: show the saved value again
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Target priority: while a higher-priority monster is in range it is attacked first, always (1 = normal). Enter to save.");
|
||||
|
||||
// Damage type and Extra vuln
|
||||
ImGuiNET.ImGui.SameLine(0, 14);
|
||||
Combo("Damage", "##dtype", DamageCommands.DamageTypes, string.IsNullOrEmpty(view.DamageType) ? "Auto" : view.DamageType,
|
||||
pick => DamageCommands.EditRule(name, r => r.DamageType = pick),
|
||||
"Element for spells and weapons against it. Auto = the one it's weakest to.");
|
||||
ImGuiNET.ImGui.SameLine(0, 14);
|
||||
Combo("Extra vuln", "##exvuln", DamageCommands.ExVulnTypes, string.IsNullOrEmpty(view.ExVuln) ? "None" : view.ExVuln,
|
||||
pick => DamageCommands.EditRule(name, r => r.ExVuln = pick),
|
||||
"A vulnerability of another element, on top of Vuln (which follows the attack's element).");
|
||||
|
||||
// Match expression (Default never matches by name, so it has none)
|
||||
if (!isDefault)
|
||||
{
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "Match");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
string expr = view.MatchExpression ?? "";
|
||||
if (!_exprActive && _exprSeen != expr)
|
||||
{
|
||||
WriteUtf8(_exprBuf, expr);
|
||||
_exprSeen = expr;
|
||||
}
|
||||
ImGuiNET.ImGui.SetNextItemWidth(-1);
|
||||
bool exprEnter = ImGuiNET.ImGui.InputText("##expr", _exprBuf, (uint)_exprBuf.Length, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
_exprActive = ImGuiNET.ImGui.IsItemActive();
|
||||
if (exprEnter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
string typed = Utf8(_exprBuf).Trim();
|
||||
if (typed != expr) DamageCommands.EditRule(name, r => r.MatchExpression = typed);
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Only when this is true as well (empty = by name only). Enter to save.\n" +
|
||||
"Variables: name, range, typeid, maxhp, metastate, true, false\nExamples: range>5, maxhp>1000");
|
||||
}
|
||||
|
||||
ToggleRow("Shapes", DamageCommands.ShapeDefs, view, name);
|
||||
string casts = DamageCommands.BaseShapeName(view);
|
||||
if (casts.Length > 0)
|
||||
{
|
||||
ImGuiNET.ImGui.SameLine(0, 10);
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "casts " + casts + (view.UseRing ? ", Ring when enough are near" : ""));
|
||||
ImGuiNET.ImGui.SetItemTooltip("With several shapes on, the first of Arc, Streak, Blast, Bolt is cast.\n" +
|
||||
"Ring replaces it when at least Min Ring Targets monsters are within Ring Range (Settings).");
|
||||
}
|
||||
if (!nameRule) return;
|
||||
|
||||
// A name rule has no Damage panel row: its debuffs, off hand and pet are set here.
|
||||
ToggleRow("Debuffs", DamageCommands.DebuffDefs, view, name);
|
||||
int off = view.OffhandId;
|
||||
string offText = off >= 0 && off < DamageCommands.OffhandModeNames.Length ? DamageCommands.OffhandModeNames[off] : "Item " + unchecked((uint)off);
|
||||
Combo("Off hand", "##offhand", DamageCommands.OffhandModeNames, offText,
|
||||
pick => DamageCommands.EditRule(name, r => r.OffhandId = Array.IndexOf(DamageCommands.OffhandModeNames, pick)),
|
||||
"Off hand against the monsters it covers. Default = the DEFAULT line's.\n" +
|
||||
"Auto = a listed shield; Shield; Dual wield (needs the skill); None = leave the off hand alone.");
|
||||
ImGuiNET.ImGui.SameLine(0, 14);
|
||||
string pet = string.IsNullOrEmpty(view.PetDamage) || view.PetDamage.Equals("PAuto", StringComparison.OrdinalIgnoreCase) ? "Auto" : view.PetDamage;
|
||||
Combo("Pet", "##pet", PetLabels, pet,
|
||||
pick => DamageCommands.EditRule(name, r => r.PetDamage = pick == "Auto" ? "PAuto" : pick),
|
||||
"Summon element against the monsters it covers. Auto = its Damage type, else the DEFAULT line's.");
|
||||
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), "Name");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.SetNextItemWidth(Math.Min(260, ImGuiNET.ImGui.GetContentRegionAvail().X));
|
||||
bool renamed = ImGuiNET.ImGui.InputText("##rename", _renameBuf, (uint)_renameBuf.Length, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
if (renamed || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
string to = Utf8(_renameBuf).Trim();
|
||||
if (to.Length > 0 && to != name && !IsDefaultName(to) && (_rules.FindRule(to) == null || to.Equals(name, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
DamageCommands.EditRule(name, r => r.Name = to);
|
||||
_selectedName = to;
|
||||
_bufFor = to;
|
||||
_renaming = to;
|
||||
}
|
||||
else WriteUtf8(_renameBuf, name);
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("The part of a monster's name this rule looks for. Enter to rename.");
|
||||
}
|
||||
|
||||
private static readonly string[] PetLabels =
|
||||
{ "Auto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
|
||||
|
||||
/// <summary>A label and a combo of <paramref name="items"/>; <paramref name="onPick"/> runs when another one is chosen.</summary>
|
||||
private static void Combo(string label, string id, string[] items, string current, Action<string> onPick, string tip)
|
||||
{
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), label);
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("Dual wield").X + 34);
|
||||
if (ImGuiNET.ImGui.BeginCombo(id, current))
|
||||
{
|
||||
foreach (string v in items)
|
||||
if (ImGuiNET.ImGui.Selectable(v, v.Equals(current, StringComparison.OrdinalIgnoreCase))
|
||||
&& !v.Equals(current, StringComparison.OrdinalIgnoreCase))
|
||||
onPick(v);
|
||||
ImGuiNET.ImGui.EndCombo();
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(tip);
|
||||
}
|
||||
|
||||
private const string RemoveLabel = PhosphorIcons.Trash + " Remove monster";
|
||||
private const string DeleteRuleLabel = PhosphorIcons.Trash + " Delete rule";
|
||||
private const string DebuffsHint = "Debuffs are set with the " + PhosphorIcons.CaretDown + " in the Damage panel's Debuffs column.";
|
||||
|
||||
private static void ToggleRow(string label, (string Field, string Label, string Tip)[] defs, Rule view, string name)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(Vec(Dim), label);
|
||||
float h = ImGuiNET.ImGui.GetFrameHeight();
|
||||
foreach (var (field, text, tip) in defs)
|
||||
{
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
bool on = view.GetToggle(field);
|
||||
float tw = ImGuiNET.ImGui.CalcTextSize(text).X;
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var size = new Vector2(tw + h + 8, h);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##t_" + field, size))
|
||||
DamageCommands.EditRule(name, rule => DamageCommands.FlipToggle(rule, field));
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.SetItemTooltip(tip);
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(p, p + size, hot ? FaceKit.Lighten(EntryBg) : EntryBg, 2);
|
||||
dl.AddRect(p, p + size, EntryBorder, 2);
|
||||
float box = h - 8;
|
||||
dl.AddRectFilled(p + new Vector2(4, 4), p + new Vector2(4 + box, 4 + box), on ? ToggleOn : ToggleOff, 2);
|
||||
dl.AddText(p + new Vector2(box + 8, (h - ImGuiNET.ImGui.GetTextLineHeight()) * 0.5f), White, text);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
private static bool BeginTable(string id, params string[] headers)
|
||||
{
|
||||
if (!ImGuiNET.ImGui.BeginTable(id, headers.Length,
|
||||
ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.PadOuterX))
|
||||
return false;
|
||||
foreach (string h in headers) ImGuiNET.ImGui.TableSetupColumn(h);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal);
|
||||
ImGuiNET.ImGui.TableHeadersRow();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void Cell(string text)
|
||||
{
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
ImGuiNET.ImGui.TextColored(Vec(White), text);
|
||||
}
|
||||
|
||||
private static Vector4 Vec(uint abgr) => ImGuiNET.ImGui.ColorConvertU32ToFloat4(abgr);
|
||||
|
||||
private static string Utf8(byte[] buffer)
|
||||
{
|
||||
int len = Array.IndexOf(buffer, (byte)0);
|
||||
return Encoding.UTF8.GetString(buffer, 0, len < 0 ? buffer.Length : len);
|
||||
}
|
||||
|
||||
/// <summary>Writes <paramref name="text"/> NUL-terminated, cut at a character boundary if it doesn't fit.</summary>
|
||||
private static void WriteUtf8(byte[] buffer, string text)
|
||||
{
|
||||
byte[] all = Encoding.UTF8.GetBytes(text);
|
||||
int n = Math.Min(all.Length, buffer.Length - 1);
|
||||
while (n > 0 && n < all.Length && (all[n] & 0xC0) == 0x80) n--; // don't split a sequence
|
||||
Array.Copy(all, buffer, n);
|
||||
buffer[n] = 0;
|
||||
}
|
||||
}
|
||||
1448
src/RynthCore.Engine/ImGui/Panels/DamageFace.cs
Normal file
1448
src/RynthCore.Engine/ImGui/Panels/DamageFace.cs
Normal file
File diff suppressed because it is too large
Load diff
659
src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs
Normal file
659
src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs
Normal file
|
|
@ -0,0 +1,659 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/DungeonMapFace.cs
|
||||
// The Dungeon Map: a large, pannable map of the current dungeon. It replaces
|
||||
// RynthAi's plugin-drawn DungeonMapUi window (plugin ImGui rendering is no
|
||||
// longer called; RYNTHCORE_FORCE_IMGUI only) and is opened from the RynthAi
|
||||
// dashboard's Map launcher.
|
||||
//
|
||||
// Data: UiSources.Radar, the same snapshot the Radar face draws
|
||||
// (RynthPluginGetRadarSnapshot): every floor's walls and fill strips, the
|
||||
// visited cells, portal / door / creature markers with labels, the player pose.
|
||||
// The plugin's D3D9 floor textures are not used; floors are strips and walls
|
||||
// are lines, drawn without anti-aliasing and culled to the canvas.
|
||||
//
|
||||
// Like the plugin window it replaces:
|
||||
// - toolbar: 1U1D (current floor +-1), F1..Fn floor toggles, All, Here, zoom,
|
||||
// Follow, Rotate, Reset, Doors, Creatures, opacity; it can be hidden;
|
||||
// - markers: the radar's kinds (RadarKind); the kinds added 2026-10-04 use the
|
||||
// radar's shapes and colours (RadarMarkerStyle) and its per-kind show boxes;
|
||||
// - drag pans (and turns Follow off), the wheel zooms;
|
||||
// - portals always shown with their destination; doors and creatures optional;
|
||||
// - hidden while you're outdoors or in portal space, back in the next dungeon
|
||||
// (the panel stays open; ImGuiPanelHost skips drawing it docked).
|
||||
// Settings are the engine's (dungeon_map_settings.txt beside radar_settings.txt),
|
||||
// not RynthAi's per-character Map* fields. Zoom, pan and floor picks last for the
|
||||
// session, as they did.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class DungeonMapFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Dungeon Map";
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
DungeonMapSettingsStore.Load(); // engine init thread: the file read stays off AC's thread
|
||||
ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true),
|
||||
() => new DungeonMapFace());
|
||||
}
|
||||
|
||||
// ── Palette (the plugin map's colours, ARGB) ──────────────────────────
|
||||
private const uint CanvasBgArgb = 0xFF0A121F, ToolbarBgArgb = 0xE00A121A;
|
||||
private static readonly uint CanvasBorder = C(0xFF334D66), Wall = C(0xFF8CCCFF),
|
||||
PlayerCol = C(0xFF33FF66), Portal = C(0xFFE673FF), PortalRing = C(0xB3FFBFFF), PortalLabel = C(0xFFFFE0FF),
|
||||
Door = C(0xFFBF8C40), DoorRing = C(0xB3E6BF80), DoorLabel = C(0xFFF2D9A6),
|
||||
Monster = C(0xFFFF4033), MonsterRing = C(0xB3FF8C80), Npc = C(0xFFFFD933), NpcRing = C(0xB3FFF28C),
|
||||
CreatureLabel = C(0xFFFFE6E6), Hint = C(0xFF8FA3B8), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A),
|
||||
FloorOn = C(0xFF2673B3), FloorHere = C(0xFF1AA64D);
|
||||
private const uint FillFlat = 0x662E8C38, FillUp = 0x668C1F14, FillDown = 0x661A8026, FillVisited = 0xB84D6B94;
|
||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||
|
||||
/// <summary>ARGB colour with its alpha scaled, as an ImGui colour.</summary>
|
||||
private static uint MulAlpha(uint argb, float k) =>
|
||||
RynthTheme.Argb((argb & 0x00FFFFFF) | ((uint)Math.Clamp((int)MathF.Round((argb >> 24) * k), 0, 255) << 24));
|
||||
|
||||
private const float DimOtherFloors = 0.25f; // the plugin map's DimCol
|
||||
private const float DefaultZoom = 5f, MinZoom = 1f, MaxZoom = 20f;
|
||||
|
||||
// ── Session state (per open) ─────────────────────────────────────────
|
||||
private float _zoom = DefaultZoom;
|
||||
private Vector2 _pan;
|
||||
private bool _follow = true;
|
||||
private bool _oneUpOneDown = true;
|
||||
private readonly HashSet<int> _visible = new();
|
||||
private int _autoLayer = -1;
|
||||
private uint _landblock;
|
||||
private int[] _drawOrder = Array.Empty<int>();
|
||||
|
||||
public int PopOutIdleHz => 20; // markers move
|
||||
|
||||
public bool HiddenWhileDocked
|
||||
{
|
||||
get
|
||||
{
|
||||
RadarView? view = UiSources.Radar.Current?.Value;
|
||||
return view != null && !view.Live.IsIndoor;
|
||||
}
|
||||
}
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
DungeonMapSettingsStore.Load();
|
||||
UiSources.Radar.Subscribe();
|
||||
UiSources.Radar.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Radar.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
|
||||
if (size.X < 16 || size.Y < 16) return;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
RadarView? view = UiSources.Radar.Current?.Value;
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
try
|
||||
{
|
||||
if (view == null) { Message(dl, origin, size, "Waiting for map data from RynthAi..."); return; }
|
||||
RadarSnapshot live = view.Live;
|
||||
if (!live.IsIndoor) { Message(dl, origin, size, "Outdoors: the map shows while you're in a dungeon."); return; }
|
||||
|
||||
int layers = live.LayerZs.Count;
|
||||
TrackLayers(view, live.Player.Landblock, layers);
|
||||
|
||||
// ── Toolbar ──
|
||||
float top = origin.Y;
|
||||
if (DungeonMapSettingsStore.ShowToolbar)
|
||||
{
|
||||
float barH = Toolbar(dl, origin, size.X, view, layers);
|
||||
top += barH;
|
||||
}
|
||||
|
||||
// ── Canvas ──
|
||||
var canvasMin = new Vector2(origin.X, top);
|
||||
var canvasMax = origin + size;
|
||||
if (canvasMax.Y - canvasMin.Y < 24) return;
|
||||
dl.AddRectFilled(canvasMin, canvasMax, MulAlpha(CanvasBgArgb, Math.Clamp(DungeonMapSettingsStore.BgOpacity, 0f, 1f)));
|
||||
dl.AddRect(canvasMin, canvasMax, CanvasBorder);
|
||||
|
||||
if (_follow) _pan = Vector2.Zero;
|
||||
Vector2 centre = (canvasMin + canvasMax) * 0.5f + _pan;
|
||||
|
||||
if (layers == 0)
|
||||
DrawCentredText(dl, (canvasMin + canvasMax) * 0.5f, Hint,
|
||||
$"Loading dungeon geometry for {live.Player.Landblock:X4}...");
|
||||
else
|
||||
{
|
||||
ImDrawListFlags saved = dl.Flags;
|
||||
dl.Flags = saved & ~(ImDrawListFlags.AntiAliasedLines | ImDrawListFlags.AntiAliasedLinesUseTex | ImDrawListFlags.AntiAliasedFill);
|
||||
dl.PushClipRect(canvasMin, canvasMax, true);
|
||||
var proj = new Projection(centre, live.Player, DungeonMapSettingsStore.RotateWithPlayer, _zoom);
|
||||
DrawFloors(dl, view, proj, canvasMin, canvasMax);
|
||||
dl.Flags = saved;
|
||||
DrawMarkers(dl, live, proj, canvasMin, canvasMax);
|
||||
DrawPlayer(dl, centre, proj);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
|
||||
// Show-toolbar button over the canvas corner (submitted before the surface so it wins the hover).
|
||||
if (!DungeonMapSettingsStore.ShowToolbar)
|
||||
{
|
||||
if (IconButton("##dmap_showbar", canvasMin + new Vector2(4, 4), PhosphorIcons.CaretDown))
|
||||
{
|
||||
DungeonMapSettingsStore.ShowToolbar = true;
|
||||
DungeonMapSettingsStore.Save();
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Show the map settings");
|
||||
}
|
||||
|
||||
CanvasInput(canvasMin, canvasMax);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Floors ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Follows the player's floor: 1U1D keeps current +-1, Follow alone keeps just the current one.</summary>
|
||||
private void TrackLayers(RadarView view, uint landblock, int layers)
|
||||
{
|
||||
if (landblock != _landblock)
|
||||
{
|
||||
_landblock = landblock;
|
||||
_pan = Vector2.Zero;
|
||||
_autoLayer = -1;
|
||||
_visible.Clear();
|
||||
}
|
||||
int best = view.CurrentLayer;
|
||||
if (best < 0 || best == _autoLayer) return;
|
||||
_autoLayer = best;
|
||||
if (_oneUpOneDown) SetOneUpOneDown(layers);
|
||||
else if (_follow || _visible.Count == 0) { _visible.Clear(); _visible.Add(best); }
|
||||
}
|
||||
|
||||
private void SetOneUpOneDown(int layers)
|
||||
{
|
||||
_visible.Clear();
|
||||
if (_autoLayer < 0) return;
|
||||
if (_autoLayer > 0) _visible.Add(_autoLayer - 1);
|
||||
_visible.Add(_autoLayer);
|
||||
if (_autoLayer < layers - 1) _visible.Add(_autoLayer + 1);
|
||||
}
|
||||
|
||||
private void DrawFloors(ImDrawListPtr dl, RadarView view, in Projection proj, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
int layers = view.Live.LayerZs.Count;
|
||||
int cur = view.CurrentLayer;
|
||||
// Other floors first, the player's floor on top.
|
||||
if (_drawOrder.Length < layers) _drawOrder = new int[layers];
|
||||
int n = 0;
|
||||
foreach (int i in _visible) if (i >= 0 && i < layers && i != cur) _drawOrder[n++] = i;
|
||||
bool curVisible = cur >= 0 && _visible.Contains(cur);
|
||||
if (curVisible) _drawOrder[n++] = cur;
|
||||
|
||||
// Fill strips: 5 floats (x0, y0, x1, y1, type).
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
int layer = _drawOrder[k];
|
||||
if (view.FillsByLayer[layer] is not float[] strips) continue;
|
||||
float a = layer == cur ? 1f : DimOtherFloors;
|
||||
uint flat = MulAlpha(FillFlat, a), up = MulAlpha(FillUp, a), down = MulAlpha(FillDown, a);
|
||||
for (int i = 0; i + 4 < strips.Length; i += 5)
|
||||
{
|
||||
int type = (int)strips[i + 4];
|
||||
FillRect(dl, proj, strips[i], strips[i + 1], strips[i + 2], strips[i + 3],
|
||||
type == 1 ? up : type == 2 ? down : flat, clipMin, clipMax);
|
||||
}
|
||||
}
|
||||
|
||||
// Visited cells, the player's floor only: 4 floats per strip.
|
||||
if (curVisible && view.VisitedByLayer[cur] is float[] visited)
|
||||
{
|
||||
uint fill = RynthTheme.Argb(FillVisited);
|
||||
for (int i = 0; i + 3 < visited.Length; i += 4)
|
||||
FillRect(dl, proj, visited[i], visited[i + 1], visited[i + 2], visited[i + 3], fill, clipMin, clipMax);
|
||||
}
|
||||
|
||||
// Walls: 6 floats (ax, ay, bx, by, cell x, cell y).
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
int layer = _drawOrder[k];
|
||||
if (view.WallsByLayer[layer] is not float[] segs) continue;
|
||||
bool current = layer == cur;
|
||||
uint col = current ? Wall : MulAlpha(0xFF8CCCFF, DimOtherFloors);
|
||||
float thick = current ? 1.5f : 1f;
|
||||
for (int i = 0; i + 5 < segs.Length; i += 6)
|
||||
{
|
||||
Vector2 pa = proj.P(segs[i], segs[i + 1]);
|
||||
Vector2 pb = proj.P(segs[i + 2], segs[i + 3]);
|
||||
if (MathF.Max(pa.X, pb.X) < clipMin.X || MathF.Min(pa.X, pb.X) > clipMax.X ||
|
||||
MathF.Max(pa.Y, pb.Y) < clipMin.Y || MathF.Min(pa.Y, pb.Y) > clipMax.Y) continue;
|
||||
dl.AddLine(pa, pb, col, thick);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void FillRect(ImDrawListPtr dl, in Projection proj, float x0, float y0, float x1, float y1,
|
||||
uint col, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
Vector2 p00 = proj.P(x0, y0), p11 = proj.P(x1, y1);
|
||||
if (proj.Rotated)
|
||||
{
|
||||
Vector2 p10 = proj.P(x1, y0), p01 = proj.P(x0, y1);
|
||||
float minX = MathF.Min(MathF.Min(p00.X, p11.X), MathF.Min(p10.X, p01.X));
|
||||
float maxX = MathF.Max(MathF.Max(p00.X, p11.X), MathF.Max(p10.X, p01.X));
|
||||
float minY = MathF.Min(MathF.Min(p00.Y, p11.Y), MathF.Min(p10.Y, p01.Y));
|
||||
float maxY = MathF.Max(MathF.Max(p00.Y, p11.Y), MathF.Max(p10.Y, p01.Y));
|
||||
if (maxX < clipMin.X || minX > clipMax.X || maxY < clipMin.Y || minY > clipMax.Y) return;
|
||||
dl.AddQuadFilled(p00, p10, p11, p01, col);
|
||||
}
|
||||
else
|
||||
{
|
||||
var a = Vector2.Min(p00, p11);
|
||||
var b = Vector2.Max(p00, p11);
|
||||
if (b.X < clipMin.X || a.X > clipMax.X || b.Y < clipMin.Y || a.Y > clipMax.Y) return;
|
||||
dl.AddRectFilled(a, b, col);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Markers and player ────────────────────────────────────────────────
|
||||
|
||||
private static void DrawMarkers(ImDrawListPtr dl, RadarSnapshot live, in Projection proj, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
const float Margin = 20f;
|
||||
bool doors = DungeonMapSettingsStore.ShowDoors, creatures = DungeonMapSettingsStore.ShowCreatures;
|
||||
RadarMarkerStyle.FillColors(KindCols);
|
||||
foreach (RadarMarker m in live.Markers)
|
||||
{
|
||||
if (!ShowOnMap(m.Kind, doors, creatures)) continue;
|
||||
Vector2 p = proj.P(m.X, m.Y);
|
||||
if (p.X < clipMin.X - Margin || p.X > clipMax.X + Margin || p.Y < clipMin.Y - Margin || p.Y > clipMax.Y + Margin) continue;
|
||||
switch (m.Kind)
|
||||
{
|
||||
case 0:
|
||||
dl.AddCircleFilled(p, 4f, Monster, 10);
|
||||
dl.AddCircle(p, 6f, MonsterRing, 10, 1f);
|
||||
Label(dl, p + new Vector2(7, -7), CreatureLabel, m.Label, 20);
|
||||
break;
|
||||
case 1:
|
||||
dl.AddCircleFilled(p, 4f, Npc, 10);
|
||||
dl.AddCircle(p, 6f, NpcRing, 10, 1.2f);
|
||||
Label(dl, p + new Vector2(7, -7), CreatureLabel, m.Label, 20);
|
||||
break;
|
||||
case 2:
|
||||
dl.AddCircleFilled(p, 5f, Portal, 12);
|
||||
dl.AddCircle(p, 7f, PortalRing, 12, 1.5f);
|
||||
Label(dl, p + new Vector2(9, -7), PortalLabel, m.Label, 22);
|
||||
break;
|
||||
case 3:
|
||||
const float r = 5f, o = r + 1.5f;
|
||||
dl.AddQuadFilled(p + new Vector2(0, -r), p + new Vector2(r, 0), p + new Vector2(0, r), p + new Vector2(-r, 0), Door);
|
||||
dl.AddQuad(p + new Vector2(0, -o), p + new Vector2(o, 0), p + new Vector2(0, o), p + new Vector2(-o, 0), DoorRing, 1.2f);
|
||||
Label(dl, p + new Vector2(8, -7), DoorLabel, m.Label, 20);
|
||||
break;
|
||||
default:
|
||||
// The kinds added 2026-10-04: the radar's shape and (user-pickable) colour, a size up.
|
||||
RadarMarkerStyle.Draw(dl, m.Kind, p, KindCols[m.Kind], 1.35f);
|
||||
if (m.Kind is not RadarKind.GroundItem)
|
||||
Label(dl, p + new Vector2(8, -7), CreatureLabel, m.Label, 20);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly uint[] KindCols = new uint[RadarKind.Count];
|
||||
|
||||
/// <summary>
|
||||
/// Portals always; doors with the map's Doors box; monsters and NPCs with its Creatures box.
|
||||
/// The kinds added 2026-10-04 also follow the radar's show box for that kind (so items on the
|
||||
/// ground stay off unless turned on there): players, fellows, pets and vendors with Creatures,
|
||||
/// corpses, lifestones and ground items on the radar's box alone. Unknown kinds: hidden.
|
||||
/// </summary>
|
||||
private static bool ShowOnMap(byte kind, bool doors, bool creatures) => kind switch
|
||||
{
|
||||
RadarKind.Portal => true,
|
||||
RadarKind.Door => doors,
|
||||
RadarKind.Monster or RadarKind.Npc => creatures,
|
||||
RadarKind.Player or RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor =>
|
||||
creatures && UI.Panels.RadarSettingsStore.ShowKind(kind),
|
||||
_ => UI.Panels.RadarSettingsStore.ShowKind(kind),
|
||||
};
|
||||
|
||||
private static void Label(ImDrawListPtr dl, Vector2 pos, uint col, string? text, int max)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return;
|
||||
if (text.Length > max) text = text[..max] + "…";
|
||||
dl.AddText(pos, col, text);
|
||||
}
|
||||
|
||||
private static void DrawPlayer(ImDrawListPtr dl, Vector2 at, in Projection proj)
|
||||
{
|
||||
dl.AddCircleFilled(at, 4f, PlayerCol, 10);
|
||||
// Rotating: facing is always up. North-up: AC heading 0 = east, 90 = north.
|
||||
Vector2 tip = proj.Rotated ? at + new Vector2(0, -10) : at + new Vector2(proj.Cos * 10, -proj.Sin * 10);
|
||||
dl.AddLine(at, tip, PlayerCol, 1.5f);
|
||||
}
|
||||
|
||||
/// <summary>World (AC x east, y north) to screen around the player, north-up or rotated so facing is up.</summary>
|
||||
private readonly struct Projection
|
||||
{
|
||||
private readonly float _cx, _cy, _pwx, _pwy, _sin, _cos, _zoom;
|
||||
public readonly bool Rotated;
|
||||
|
||||
public Projection(Vector2 playerAt, RadarPlayer p, bool rotate, float zoom)
|
||||
{
|
||||
_cx = playerAt.X; _cy = playerAt.Y; _pwx = p.WorldX; _pwy = p.WorldY;
|
||||
float h = p.Heading * MathF.PI / 180f;
|
||||
_sin = MathF.Sin(h); _cos = MathF.Cos(h);
|
||||
Rotated = rotate; _zoom = zoom;
|
||||
}
|
||||
|
||||
public float Sin => _sin;
|
||||
public float Cos => _cos;
|
||||
|
||||
public Vector2 P(float wx, float wy)
|
||||
{
|
||||
float dx = wx - _pwx, dy = wy - _pwy;
|
||||
if (Rotated)
|
||||
{
|
||||
float right = _sin * dx - _cos * dy;
|
||||
float forward = _cos * dx + _sin * dy;
|
||||
return new Vector2(_cx + right * _zoom, _cy - forward * _zoom);
|
||||
}
|
||||
return new Vector2(_cx + dx * _zoom, _cy - dy * _zoom);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Canvas input ──────────────────────────────────────────────────────
|
||||
|
||||
private void CanvasInput(Vector2 canvasMin, Vector2 canvasMax)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(canvasMin);
|
||||
ImGuiNET.ImGui.InvisibleButton("##dmap_canvas", Vector2.Max(canvasMax - canvasMin, new Vector2(1, 1)));
|
||||
if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left))
|
||||
{
|
||||
Vector2 delta = ImGuiNET.ImGui.GetIO().MouseDelta;
|
||||
if (float.IsFinite(delta.X) && float.IsFinite(delta.Y) && delta != Vector2.Zero)
|
||||
{
|
||||
_follow = false;
|
||||
_pan += delta;
|
||||
}
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
{
|
||||
float wheel = ImGuiNET.ImGui.GetIO().MouseWheel;
|
||||
if (float.IsFinite(wheel) && wheel != 0f)
|
||||
_zoom = Math.Clamp(_zoom + wheel * 0.5f, MinZoom, MaxZoom);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Toolbar ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Draws the settings rows (they wrap to the width). Returns their height.</summary>
|
||||
private float Toolbar(ImDrawListPtr dl, Vector2 origin, float width, RadarView view, int layers)
|
||||
{
|
||||
const float pad = 4;
|
||||
// Background first, sized once the rows are laid out: a channel split keeps it underneath.
|
||||
dl.ChannelsSplit(2);
|
||||
dl.ChannelsSetCurrent(1);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(pad, pad));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 1));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4));
|
||||
float limit = origin.X + width - pad;
|
||||
bool changed = false;
|
||||
|
||||
if (IconButton("##dmap_hidebar", ImGuiNET.ImGui.GetCursorScreenPos(), PhosphorIcons.CaretUp))
|
||||
{
|
||||
DungeonMapSettingsStore.ShowToolbar = false;
|
||||
changed = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Hide the map settings");
|
||||
|
||||
// 1U1D and the floors.
|
||||
SameLineIfFits(40, limit);
|
||||
if (ToggleButton("1U1D##dmap_1u1d", _oneUpOneDown, FloorOn))
|
||||
{
|
||||
_oneUpOneDown = !_oneUpOneDown;
|
||||
if (_oneUpOneDown) SetOneUpOneDown(layers);
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Show your floor and the ones just above and below it");
|
||||
if (layers > 1)
|
||||
{
|
||||
SameLineIfFits(ImGuiNET.ImGui.CalcTextSize("Floors:").X, limit);
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextUnformatted("Floors:");
|
||||
for (int i = 0; i < layers; i++)
|
||||
{
|
||||
string label = FloorLabel(i);
|
||||
SameLineIfFits(ImGuiNET.ImGui.CalcTextSize(label).X + 8, limit, 2);
|
||||
bool on = _visible.Contains(i);
|
||||
if (ToggleButton(label, on, i == view.CurrentLayer ? FloorHere : FloorOn))
|
||||
{
|
||||
_oneUpOneDown = false;
|
||||
if (on) _visible.Remove(i); else _visible.Add(i);
|
||||
}
|
||||
}
|
||||
SameLineIfFits(24, limit);
|
||||
if (ImGuiNET.ImGui.SmallButton("All##dmap_all"))
|
||||
{
|
||||
_oneUpOneDown = false;
|
||||
_visible.Clear();
|
||||
for (int i = 0; i < layers; i++) _visible.Add(i);
|
||||
}
|
||||
SameLineIfFits(34, limit, 2);
|
||||
if (ImGuiNET.ImGui.SmallButton("Here##dmap_here"))
|
||||
{
|
||||
_oneUpOneDown = false;
|
||||
_visible.Clear();
|
||||
if (view.CurrentLayer >= 0) _visible.Add(view.CurrentLayer);
|
||||
}
|
||||
}
|
||||
|
||||
// Zoom.
|
||||
SameLineIfFits(130, limit, 12);
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextUnformatted("Zoom:");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.SetNextItemWidth(80);
|
||||
ImGuiNET.ImGui.SliderFloat("##dmap_zoom", ref _zoom, MinZoom, MaxZoom, "%.1fx");
|
||||
if (!float.IsFinite(_zoom)) _zoom = DefaultZoom;
|
||||
|
||||
// Follow / Rotate / Reset.
|
||||
SameLineIfFits(190, limit, 12);
|
||||
ImGuiNET.ImGui.Checkbox("Follow##dmap_follow", ref _follow);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Keep the map centred on you (dragging the map turns this off)");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
changed |= ImGuiNET.ImGui.Checkbox("Rotate##dmap_rotate", ref DungeonMapSettingsStore.RotateWithPlayer);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Turn the map so the way you face is up");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.SmallButton("Reset##dmap_reset"))
|
||||
{
|
||||
_pan = Vector2.Zero;
|
||||
_zoom = DefaultZoom;
|
||||
_follow = true;
|
||||
_oneUpOneDown = true;
|
||||
SetOneUpOneDown(layers);
|
||||
}
|
||||
|
||||
// Doors / Creatures.
|
||||
SameLineIfFits(160, limit, 12);
|
||||
changed |= ImGuiNET.ImGui.Checkbox("Doors##dmap_doors", ref DungeonMapSettingsStore.ShowDoors);
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
changed |= ImGuiNET.ImGui.Checkbox("Creatures##dmap_creatures", ref DungeonMapSettingsStore.ShowCreatures);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Monsters, NPCs, players, fellows, your pet and vendors. Players, fellows, pets, vendors, corpses, lifestones and ground items also follow their box in the Radar's settings.");
|
||||
|
||||
// Opacity (of the map's background).
|
||||
SameLineIfFits(130, limit, 12);
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextUnformatted("Opacity:");
|
||||
ImGuiNET.ImGui.SameLine(0, 4);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(70);
|
||||
if (ImGuiNET.ImGui.SliderFloat("##dmap_opacity", ref DungeonMapSettingsStore.BgOpacity, 0f, 1f, "%.2f"))
|
||||
DungeonMapSettingsStore.BgOpacity = Math.Clamp(DungeonMapSettingsStore.BgOpacity, 0f, 1f);
|
||||
// Save once the drag ends, not on every step.
|
||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) changed = true;
|
||||
|
||||
ImGuiNET.ImGui.PopStyleVar(2);
|
||||
float bottom = ImGuiNET.ImGui.GetItemRectMax().Y + pad;
|
||||
dl.ChannelsSetCurrent(0);
|
||||
dl.AddRectFilled(origin, new Vector2(origin.X + width, bottom), C(ToolbarBgArgb));
|
||||
dl.ChannelsMerge();
|
||||
|
||||
if (changed) DungeonMapSettingsStore.Save();
|
||||
return bottom - origin.Y;
|
||||
}
|
||||
|
||||
private static readonly List<string> FloorLabels = new();
|
||||
|
||||
private static string FloorLabel(int i)
|
||||
{
|
||||
while (FloorLabels.Count <= i) FloorLabels.Add("F" + (FloorLabels.Count + 1) + "##dmap_floor" + FloorLabels.Count);
|
||||
return FloorLabels[i];
|
||||
}
|
||||
|
||||
/// <summary>Keeps the next item on this row when it fits before <paramref name="limit"/>, else starts a new row.</summary>
|
||||
private static void SameLineIfFits(float nextWidth, float limit, float gap = 8)
|
||||
{
|
||||
if (ImGuiNET.ImGui.GetItemRectMax().X + gap + nextWidth <= limit)
|
||||
ImGuiNET.ImGui.SameLine(0, gap);
|
||||
}
|
||||
|
||||
private static bool ToggleButton(string label, bool on, uint onColour)
|
||||
{
|
||||
if (on)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, onColour);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, onColour);
|
||||
}
|
||||
bool clicked = ImGuiNET.ImGui.SmallButton(label);
|
||||
if (on) ImGuiNET.ImGui.PopStyleColor(2);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
private static bool IconButton(string id, Vector2 pos, string glyph)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
var size = new Vector2(18, 18);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
|
||||
uint bg = ImGuiNET.ImGui.IsItemActive() ? C(0xE0101820) : ImGuiNET.ImGui.IsItemHovered() ? C(0xE0243444) : ButtonBg;
|
||||
dl.AddRectFilled(pos, pos + size, bg, 3);
|
||||
dl.AddRect(pos, pos + size, ButtonBorder, 3);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, size, C(0xFFF2F8FF));
|
||||
return clicked;
|
||||
}
|
||||
|
||||
private static void Message(ImDrawListPtr dl, Vector2 origin, Vector2 size, string text)
|
||||
{
|
||||
dl.AddRectFilled(origin, origin + size, MulAlpha(CanvasBgArgb, Math.Clamp(DungeonMapSettingsStore.BgOpacity, 0.6f, 1f)));
|
||||
DrawCentredText(dl, origin + size * 0.5f, Hint, text);
|
||||
}
|
||||
|
||||
private static void DrawCentredText(ImDrawListPtr dl, Vector2 centre, uint col, string text)
|
||||
{
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text);
|
||||
dl.AddText(centre - ts * 0.5f, col, text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Dungeon Map's settings (the plugin map's MapShowDoors / MapShowCreatures /
|
||||
/// MapShowToolbar / MapBgOpacity / MapRotateWithPlayer, same defaults). Engine-wide,
|
||||
/// in %LOCALAPPDATA%\RynthCore\dungeon_map_settings.txt, like radar_settings.txt.
|
||||
/// </summary>
|
||||
internal static class DungeonMapSettingsStore
|
||||
{
|
||||
private static readonly object _sync = new();
|
||||
private static bool _loaded;
|
||||
|
||||
public static bool ShowDoors = true;
|
||||
public static bool ShowCreatures = true;
|
||||
public static bool ShowToolbar = true;
|
||||
public static float BgOpacity = 1.0f;
|
||||
public static bool RotateWithPlayer;
|
||||
|
||||
private static string FilePath
|
||||
{
|
||||
get
|
||||
{
|
||||
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
return Path.Combine(root, "RynthCore", "dungeon_map_settings.txt");
|
||||
}
|
||||
}
|
||||
|
||||
public static void Load()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
if (!File.Exists(path)) return;
|
||||
foreach (string raw in File.ReadAllLines(path))
|
||||
{
|
||||
string line = raw.Trim();
|
||||
if (line.Length == 0 || line.StartsWith('#')) continue;
|
||||
int eq = line.IndexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
string key = line[..eq].Trim();
|
||||
string val = line[(eq + 1)..].Trim();
|
||||
switch (key)
|
||||
{
|
||||
case "showDoors": ShowDoors = val == "1"; break;
|
||||
case "showCreatures": ShowCreatures = val == "1"; break;
|
||||
case "showToolbar": ShowToolbar = val == "1"; break;
|
||||
case "rotate": RotateWithPlayer = val == "1"; break;
|
||||
case "opacity":
|
||||
if (float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float o))
|
||||
BgOpacity = Math.Clamp(o, 0f, 1f);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* best-effort: defaults already in place */ }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes the settings in the background (the caller is AC's render thread).</summary>
|
||||
public static void Save()
|
||||
{
|
||||
// Snapshot on the caller's thread: the writer runs later.
|
||||
string text = "# RynthCore dungeon map settings - auto-generated, hand-edits OK.\n"
|
||||
+ $"showDoors={(ShowDoors ? "1" : "0")}\n"
|
||||
+ $"showCreatures={(ShowCreatures ? "1" : "0")}\n"
|
||||
+ $"showToolbar={(ShowToolbar ? "1" : "0")}\n"
|
||||
+ $"rotate={(RotateWithPlayer ? "1" : "0")}\n"
|
||||
+ FormattableString.Invariant($"opacity={BgOpacity:0.##}\n");
|
||||
UiBackgroundWriter.Enqueue("dungeon map settings", () =>
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(path, text);
|
||||
}
|
||||
catch { /* non-fatal */ }
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
315
src/RynthCore.Engine/ImGui/Panels/FaceKit.cs
Normal file
315
src/RynthCore.Engine/ImGui/Panels/FaceKit.cs
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/FaceKit.cs
|
||||
// Widgets the RynthAi-style ImGui faces share: the flat bordered button (and
|
||||
// its icon-only form), a text box with a grey hint, a picker (button + popup
|
||||
// list), wrapped button rows, and UTF-8 text buffers. Colours are the panels' palette (ABGR),
|
||||
// with text brighter than the Avalonia faces (Tom, 2026-09-28).
|
||||
//
|
||||
// Everything runs on AC's render thread inside a face's Draw. No per-frame
|
||||
// allocation except what callers pass in.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
using ImGuiNET;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal static class FaceKit
|
||||
{
|
||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||
|
||||
public static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Green = C(0xFF33CC66),
|
||||
Red = C(0xFFE05A5A), Mute = C(0xFFC8D6E4), Text = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14),
|
||||
PanelBg = C(0xFF141F29), RowAlt = C(0xFF101822), BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A),
|
||||
Selected = C(0xFF1A2E42), StartBg = C(0xFF196119), StopBg = C(0xFF801919), DeleteBg = C(0xFF801A1A);
|
||||
|
||||
// ── Frame ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Starts an edge-to-edge face body: shell background, Ui10 font, a 6 px
|
||||
/// inset kept on every line (Indent). Returns the content width. Pair with End.
|
||||
/// </summary>
|
||||
public static float Begin(out Vector2 origin, out Vector2 size)
|
||||
{
|
||||
origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
size = ImGuiNET.ImGui.GetContentRegionAvail();
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(origin, origin + size, ShellBg, 4);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(6, 6));
|
||||
ImGuiNET.ImGui.Indent(6);
|
||||
return size.X - 12;
|
||||
}
|
||||
|
||||
public static void End(Vector2 origin, Vector2 size)
|
||||
{
|
||||
ImGuiNET.ImGui.Unindent(6);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddRect(origin, origin + size, BtnBord, 4);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A GripInBody face: how far the resize grip reaches above the 6 px bottom
|
||||
/// margin (0 for other faces). A scrolling child that runs to the margin ends
|
||||
/// this much higher so its scrollbar stays clear of the grip.
|
||||
/// </summary>
|
||||
public static float GripOverlap() => Math.Max(0f, ImGuiPanelHost.BodyGripReserve - 6f);
|
||||
|
||||
/// <summary>Space left below the cursor down to the body's bottom (6 px margin).</summary>
|
||||
public static float Remaining(Vector2 origin, Vector2 size) =>
|
||||
origin.Y + size.Y - 6 - ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
|
||||
/// <summary>Moves the layout cursor to the start of the line below a row drawn at <paramref name="rowStart"/>.</summary>
|
||||
public static void NextLine(Vector2 rowStart, float rowHeight)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(rowStart.X, rowStart.Y + rowHeight));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
}
|
||||
|
||||
public static void Separator(float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddLine(p + new Vector2(0, 1), p + new Vector2(w, 1), BtnBord);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, 2));
|
||||
}
|
||||
|
||||
public static void Label(string text, uint color)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
|
||||
ImGuiNET.ImGui.TextUnformatted(text);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
|
||||
// ── Buttons ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A flat bordered button at <paramref name="pos"/>.</summary>
|
||||
public static bool Button(string id, string label, Vector2 pos, Vector2 size, uint fg, uint bg,
|
||||
bool enabled = true, bool leftAlign = false, uint border = 0)
|
||||
{
|
||||
bool clicked = ButtonFrame(id, pos, size, bg, enabled, border);
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(label);
|
||||
float tx = leftAlign ? pos.X + 6 : pos.X + (size.X - ts.X) * 0.5f;
|
||||
dl.PushClipRect(pos, pos + size, true);
|
||||
dl.AddText(new Vector2(tx, pos.Y + (size.Y - ts.Y) * 0.5f), enabled ? fg : Faded(fg), label);
|
||||
dl.PopClipRect();
|
||||
return clicked;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Button's look with a Phosphor icon centred on it. <paramref name="font"/>
|
||||
/// sets the icon's size: Ui14 (about 13 px) for 20+ px buttons, Ui11 for smaller.
|
||||
/// </summary>
|
||||
public static bool IconButton(string id, string icon, Vector2 pos, Vector2 size, uint fg, uint bg,
|
||||
bool enabled = true, uint border = 0, UiFont font = UiFont.Ui14)
|
||||
{
|
||||
bool clicked = ButtonFrame(id, pos, size, bg, enabled, border);
|
||||
PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(font), icon, pos, size, enabled ? fg : Faded(fg));
|
||||
return clicked;
|
||||
}
|
||||
|
||||
private static bool ButtonFrame(string id, Vector2 pos, Vector2 size, uint bg, bool enabled, uint border)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size) && enabled;
|
||||
bool hot = enabled && ImGuiNET.ImGui.IsItemHovered();
|
||||
uint fill = enabled && ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : hot ? Lighten(bg) : bg;
|
||||
dl.AddRectFilled(pos, pos + size, fill, 3);
|
||||
dl.AddRect(pos, pos + size, border != 0 ? border : BtnBord, 3);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
/// <summary>Width a button needs for <paramref name="label"/> at the current font.</summary>
|
||||
public static float ButtonWidth(string label) => ImGuiNET.ImGui.CalcTextSize(label).X + 16;
|
||||
|
||||
/// <summary>
|
||||
/// A draggable column edge at screen x (a 6 px handle, resize cursor on hover).
|
||||
/// Dragging changes <paramref name="width"/> (never below <paramref name="min"/>);
|
||||
/// <paramref name="onCommit"/> runs when the drag ends, to save it. Leaves the
|
||||
/// cursor where it was. Returns true while the width is changing.
|
||||
/// </summary>
|
||||
public static bool ColumnDivider(string id, float x, float top, float height, ref float width, float min,
|
||||
Action<float>? onCommit)
|
||||
{
|
||||
Vector2 saved = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x - 3, top));
|
||||
ImGuiNET.ImGui.SetNextItemAllowOverlap();
|
||||
ImGuiNET.ImGui.InvisibleButton(id, new Vector2(6, height));
|
||||
bool active = ImGuiNET.ImGui.IsItemActive();
|
||||
bool hot = active || ImGuiNET.ImGui.IsItemHovered();
|
||||
if (hot) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeEW);
|
||||
bool changed = false;
|
||||
if (active)
|
||||
{
|
||||
float dx = ImGuiNET.ImGui.GetIO().MouseDelta.X;
|
||||
if (dx != 0)
|
||||
{
|
||||
width = Math.Max(min, width + dx);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsItemDeactivated()) onCommit?.Invoke(width);
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddLine(new Vector2(x, top + 3), new Vector2(x, top + height - 3),
|
||||
hot ? Teal : BtnBord, hot ? 2f : 1f);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(saved);
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A row of buttons that wraps to the width; returns the index clicked or -1.
|
||||
/// <paramref name="enabled"/> may be null (all enabled).
|
||||
/// </summary>
|
||||
public static int WrapButtons(string idPrefix, string[] labels, float w, float height = 24, bool[]? enabled = null)
|
||||
{
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x = start.X, y = start.Y;
|
||||
int clicked = -1;
|
||||
for (int i = 0; i < labels.Length; i++)
|
||||
{
|
||||
float bw = ButtonWidth(labels[i]);
|
||||
if (x > start.X && x + bw > start.X + w) { x = start.X; y += height + 4; }
|
||||
ImGuiNET.ImGui.PushID(idPrefix + i);
|
||||
if (Button("##b", labels[i], new Vector2(x, y), new Vector2(bw, height), Text, BtnFill, enabled == null || enabled[i]))
|
||||
clicked = i;
|
||||
ImGuiNET.ImGui.PopID();
|
||||
x += bw + 4;
|
||||
}
|
||||
NextLine(start, y - start.Y + height);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
// ── Text input ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// A bordered text box with a grey <paramref name="hint"/> while empty.
|
||||
/// Returns true when Enter was pressed (with EnterReturnsTrue) or the text changed.
|
||||
/// </summary>
|
||||
public static bool TextBox(string id, byte[] buffer, Vector2 pos, float width, string hint, out bool active,
|
||||
ImGuiInputTextFlags flags = ImGuiInputTextFlags.None, float height = 22)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(width);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3f);
|
||||
bool result = ImGuiNET.ImGui.InputText(id, buffer, (uint)buffer.Length, flags);
|
||||
active = ImGuiNET.ImGui.IsItemActive();
|
||||
ImGuiNET.ImGui.PopStyleVar(3);
|
||||
ImGuiNET.ImGui.PopStyleColor(3);
|
||||
if (buffer[0] == 0 && !active && hint.Length > 0)
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(pos + new Vector2(5, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), hint);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Picker ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// One popup list per face, opened from any button: call Open from the
|
||||
/// button's click and Draw once per frame at the end of the face's Draw
|
||||
/// (outside any child window, so the popup id always matches).
|
||||
/// </summary>
|
||||
internal sealed class Picker
|
||||
{
|
||||
private readonly string _popupId;
|
||||
private string[] _items = Array.Empty<string>();
|
||||
private int _selected = -1;
|
||||
private Action<int>? _onPick;
|
||||
private Vector2 _pos;
|
||||
private float _width = 220;
|
||||
private bool _openRequested;
|
||||
|
||||
public Picker(string popupId) => _popupId = popupId;
|
||||
|
||||
public void Open(Vector2 below, string[] items, int selected, Action<int> onPick, float width = 220)
|
||||
{
|
||||
_items = items;
|
||||
_selected = selected;
|
||||
_onPick = onPick;
|
||||
_pos = below;
|
||||
_width = width;
|
||||
_openRequested = items.Length > 0;
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
if (_openRequested)
|
||||
{
|
||||
_openRequested = false;
|
||||
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
|
||||
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(_pos.X, 0, Math.Max(0, display.X - _width)), _pos.Y));
|
||||
ImGuiNET.ImGui.OpenPopup(_popupId);
|
||||
}
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
|
||||
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(_width, Math.Min(_items.Length * 21 + 4, 340)));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup(_popupId);
|
||||
ImGuiNET.ImGui.PopStyleVar(3);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (!open) return;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float iw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
for (int i = 0; i < _items.Length; i++)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
bool click = ImGuiNET.ImGui.InvisibleButton("##it", new Vector2(iw, 20));
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
bool sel = i == _selected;
|
||||
dl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? Selected : hot ? Lighten(BtnFill) : BtnFill);
|
||||
dl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord);
|
||||
dl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : Text, _items[i]);
|
||||
if (click)
|
||||
{
|
||||
Action<int>? act = _onPick;
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
act?.Invoke(i);
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Text buffers ─────────────────────────────────────────────────────
|
||||
|
||||
public static string Utf8(byte[] buffer)
|
||||
{
|
||||
int len = Array.IndexOf(buffer, (byte)0);
|
||||
return Encoding.UTF8.GetString(buffer, 0, len < 0 ? buffer.Length : len);
|
||||
}
|
||||
|
||||
/// <summary>Writes <paramref name="text"/> NUL-terminated, cut at a character boundary if it doesn't fit.</summary>
|
||||
public static void WriteUtf8(byte[] buffer, string text)
|
||||
{
|
||||
byte[] all = Encoding.UTF8.GetBytes(text ?? string.Empty);
|
||||
int n = Math.Min(all.Length, buffer.Length - 1);
|
||||
while (n > 0 && n < all.Length && (all[n] & 0xC0) == 0x80) n--;
|
||||
Array.Copy(all, buffer, n);
|
||||
buffer[n] = 0;
|
||||
}
|
||||
|
||||
// ── Colour helpers ───────────────────────────────────────────────────
|
||||
|
||||
public static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12);
|
||||
public static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0);
|
||||
public static uint Faded(uint abgr) => (abgr & 0x00FFFFFF) | ((abgr >> 25) << 24);
|
||||
|
||||
private static uint Scale(uint abgr, float k, int add)
|
||||
{
|
||||
uint a = abgr & 0xFF000000;
|
||||
uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add);
|
||||
uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add);
|
||||
uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add);
|
||||
return a | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
}
|
||||
847
src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs
Normal file
847
src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs
Normal file
|
|
@ -0,0 +1,847 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/InventoryFace.Classic.cs
|
||||
// The Inventory panel's Classic look (docs/IMGUI_INVENTORY.md, Phase 2): the
|
||||
// retail inventory window, drawn with the client's own pictures from
|
||||
// client_portal.dat (RetailSprites) at the retail layout's positions.
|
||||
//
|
||||
// Where the numbers come from: the retail window is LayoutDesc 0x21000023 in
|
||||
// the client's dats. Tom's OpenAC client rebuilds it from the dat
|
||||
// (src/AcDream.App/UI/Layout: InventoryController, PaperdollController,
|
||||
// PaperdollSlotBackgrounds, ItemListCellTemplate, UiItemSlot, RetailChromeSprites)
|
||||
// and pins the resolved layout in tests/AcDream.App.Tests/UI/Layout/fixtures/
|
||||
// inventory_21000023.json. The element positions, sizes and picture ids below
|
||||
// are read from that layout (and the empty-cell pictures re-resolved from the
|
||||
// installed dats the way OpenAC's ItemListCellTemplate does); the resize rules
|
||||
// (the grid and pack column grow with the window's height, the background's
|
||||
// 25 px title band isn't stretched) follow AcClientReborn's InventoryGeometry.
|
||||
// Credit: OpenAC (Tom's project) for the layout and sprite research.
|
||||
//
|
||||
// title retail title bar "Inventory of <name>", tool toggles, close
|
||||
// tools search, sort, category chips (toggle, the funnel in the title)
|
||||
// paperdoll the 24 equip slots at their retail places (the 3D figure isn't
|
||||
// drawn, so the retail "Slots" view is always on)
|
||||
// column burden meter, main pack, then the main pack's pack slots: side
|
||||
// packs, then the items that take a pack slot (foci), as retail
|
||||
// lists them; its scrollbar
|
||||
// contents "Contents of <pack>": the open pack's slots, retail scrollbar;
|
||||
// with a search or filter on, the matches from every pack
|
||||
// status the action waiting / last outcome (or the pyreals), Drop, Give
|
||||
//
|
||||
// Same behaviours as the Modern look: one action at a time, drag to a pack /
|
||||
// slot / Drop / Give, double-click to use, right-click menu, split dialog.
|
||||
// Geometry is in retail pixels times the UI scale (DPI x the panel's text size),
|
||||
// shrunk only to fit a window narrower than 300.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed partial class InventoryFace
|
||||
{
|
||||
// ── Retail art (0x06 textures in client_portal.dat) ─────────────────
|
||||
private static class Art
|
||||
{
|
||||
public const uint Backdrop = 0x06004D0Au; // 300x362 stone background (element 0x100001D0)
|
||||
public const uint TitleBar = 0x06004CFAu; // 276x25 title bar (0x100001D3)
|
||||
public const uint Close = 0x06004D0Cu; // 24x25 close button (0x100001D2); +1 = pressed
|
||||
public const uint GridEmpty = 0x06004D20u; // empty contents cell (prototype 0x1000033A, ItemSlot_Empty)
|
||||
public const uint PackEmpty = 0x06000F6Eu; // empty side-pack cell (prototype 0x1000033F > 0x1000033E)
|
||||
public const uint OpenPack = 0x06005D9Cu; // 36x36 gold arrow on the open pack
|
||||
public const uint MainPackIcon = 0x0600127Eu; // the main pack's backpack
|
||||
public const uint Selected = 0x06004D21u; // yellow square on the selected item
|
||||
public const uint Waiting = 0x0600109Au; // hatch on an item waiting for the server
|
||||
public const uint AcceptGrid = 0x060011F9u, AcceptPack = 0x060011F7u, Reject = 0x060011F8u;
|
||||
public const uint BurdenBack = 0x0600121Du, BurdenFill = 0x0600121Cu; // meter 0x100001D9 and its fill
|
||||
public const uint CapacityBack = 0x06004D22u, CapacityFill = 0x06004D23u; // 5x30 pack fill meter
|
||||
public const uint Track = 0x06004C5Fu; // 16x32 scrollbar chain, tiled (LayoutDesc 0x2100003E)
|
||||
public const uint ThumbTop = 0x06004C60u, ThumbMid = 0x06004C63u, ThumbBottom = 0x06004C66u;
|
||||
public const uint Down = 0x06004C69u, Up = 0x06004C6Cu; // +1 rollover, +2 pressed
|
||||
}
|
||||
|
||||
// Retail geometry (px at scale 1), LayoutDesc 0x21000023.
|
||||
private const float RetailW = 300, TitleH = 25, FieldY = 23, ContentsY = 237, SideW = 61, CellPx = 32, PackPx = 36;
|
||||
private const int SideBagSlots = 7;
|
||||
|
||||
private static uint Rgb(uint argb) => RynthTheme.Argb(argb);
|
||||
private static readonly uint StoneFallback = Rgb(0xFF16140F), CellFallback = Rgb(0xFF1C1B18), CellEdge = Rgb(0xFF4A4436),
|
||||
Gold = Rgb(0xFFCAB06D), White = Rgb(0xFFFFFFFF), Black = Rgb(0xFF000000), SelYellow = Rgb(0xFFF0E040),
|
||||
AcceptGreen = Rgb(0xFF30D040), RejectRed = Rgb(0xFFE03030);
|
||||
|
||||
/// <summary>One paperdoll slot: its equip mask, retail place in the paperdoll field, empty picture.</summary>
|
||||
private readonly struct DollSlot
|
||||
{
|
||||
public readonly uint Mask;
|
||||
public readonly float X, Y;
|
||||
public readonly uint Empty;
|
||||
public readonly string Name;
|
||||
/// <summary>Aetheria slots: the unlock bit (PropertyInt 322); 0 = always shown.</summary>
|
||||
public readonly uint Sigil;
|
||||
|
||||
public DollSlot(uint mask, float x, float y, uint empty, string name, uint sigil = 0)
|
||||
{
|
||||
Mask = mask;
|
||||
X = x;
|
||||
Y = y;
|
||||
Empty = empty;
|
||||
Name = name;
|
||||
Sigil = sigil;
|
||||
}
|
||||
}
|
||||
|
||||
// Element ids, masks and empty pictures: OpenAC's PaperdollSlotBackgrounds (pinned from the
|
||||
// live dat there, re-checked against the installed dats); places: the layout's elements.
|
||||
private static readonly DollSlot[] Doll =
|
||||
{
|
||||
new(0x00000001u, 84, 28, 0x06006D7Fu, "Head"), // 0x100005AB
|
||||
new(0x00000200u, 84, 64, 0x06006D7Bu, "Chest"), // 0x100005AC
|
||||
new(0x00000400u, 84, 100, 0x06006D79u, "Abdomen"), // 0x100005AD
|
||||
new(0x00000800u, 48, 64, 0x06006D87u, "Upper arms"), // 0x100005AE
|
||||
new(0x00001000u, 48, 100, 0x06006D81u, "Lower arms"), // 0x100005AF
|
||||
new(0x00000020u, 48, 136, 0x06006D7Du, "Hands"), // 0x100005B0
|
||||
new(0x00002000u, 120, 100, 0x06006D89u, "Upper legs"), // 0x100005B1
|
||||
new(0x00004000u, 120, 136, 0x06006D83u, "Lower legs"), // 0x100005B2
|
||||
new(0x00000100u, 120, 172, 0x06006D85u, "Feet"), // 0x100005B3
|
||||
new(0x00000002u, 192, 80, 0x060032C5u, "Shirt"), // 0x100001E2
|
||||
new(0x00000040u, 192, 116, 0x060032C4u, "Pants"), // 0x100001E3
|
||||
new(0x00008000u, 8, 8, 0x06000F68u, "Neck"), // 0x100001DA
|
||||
new(0x04000000u, 8, 44, 0x06006A6Cu, "Trinket"), // 0x1000058E
|
||||
new(0x00020000u, 8, 80, 0x06000F6Au, "Right wrist"), // 0x100001DD
|
||||
new(0x00080000u, 8, 116, 0x06000F6Bu, "Right ring"), // 0x100001DE
|
||||
new(0x00200000u, 8, 172, 0x06000F6Cu, "Shield"), // 0x100001E1
|
||||
new(0x00010000u, 156, 80, 0x06000F5Du, "Left wrist"), // 0x100001DB
|
||||
new(0x00040000u, 156, 116, 0x06000F5Au, "Left ring"), // 0x100001DC
|
||||
new(0x03500000u, 156, 172, 0x06000F66u, "Weapon"), // 0x100001DF: melee, missile, held, two-handed
|
||||
new(0x00800000u, 190, 172, 0x06000F5Eu, "Ammunition"), // 0x100001E0
|
||||
new(0x08000000u, 192, 44, 0x0600708Fu, "Cloak"), // 0x100005E9
|
||||
new(0x10000000u, 126, 8, 0x06006BEFu, "Blue Aetheria", 1), // 0x10000595
|
||||
new(0x20000000u, 158, 8, 0x06006BF0u, "Yellow Aetheria", 2), // 0x10000596
|
||||
new(0x40000000u, 190, 8, 0x06006BF1u, "Red Aetheria", 4), // 0x10000597
|
||||
};
|
||||
|
||||
// ── Classic state ───────────────────────────────────────────────────
|
||||
private int _gridFirstRow, _packFirstRow;
|
||||
private float _thumbGrab;
|
||||
private string _captionText = string.Empty;
|
||||
private string? _hoverLabel, _hoverLabel2;
|
||||
private string _titleText = "Inventory";
|
||||
private string? _titleFor;
|
||||
|
||||
// =====================================================================
|
||||
// Body
|
||||
// =====================================================================
|
||||
|
||||
private void ClassicBody(InventoryView view, Vector2 origin, Vector2 size)
|
||||
{
|
||||
// Scale: the UI scale (DPI x this panel's text size), shrunk only to fit a narrow window.
|
||||
float ui = EngineFrameController.FontScale * PanelTextScale.Factor(ImGuiFonts.CurrentStep);
|
||||
if (!(ui > 0f) || !float.IsFinite(ui)) ui = 1f;
|
||||
ui *= InventorySettingsStore.SizeFactor; // the panel's own size (the - / + in the title bar)
|
||||
float s = Math.Max(0.4f, Math.Min(ui, size.X / RetailW));
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float w = size.X;
|
||||
Vector2 o = origin;
|
||||
float statusH = MathF.Round(20 * s);
|
||||
float bottom = o.Y + size.Y - statusH;
|
||||
|
||||
// The open pack: a real pack (Classic has no "All" or "Worn" entry; the paperdoll is Worn).
|
||||
if (_pack == AllPacks || _pack == WornPacks || view.PackOf(_pack) == null)
|
||||
_pack = view.Packs.Length > 0 ? view.Packs[0].Id : AllPacks;
|
||||
bool filtered = _category != 0 || _searchText.Length > 0;
|
||||
RebuildIfNeeded(view, filtered ? AllPacks : _pack);
|
||||
|
||||
Backdrop(dl, o, w, bottom - o.Y, s);
|
||||
TitleBar(view, dl, o, w, s);
|
||||
|
||||
// Tools (search, sort, categories): between the title bar and the retail body.
|
||||
float toolsBottom = o.Y + TitleH * s;
|
||||
if (InventorySettingsStore.ShowTools)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(o.X + 6, toolsBottom + 4));
|
||||
Tools(w - 12);
|
||||
Chips(w - 12);
|
||||
toolsBottom = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
}
|
||||
float ry = toolsBottom - TitleH * s; // where retail y = 0 lands
|
||||
float r = Math.Max(ContentsY + 60, (bottom - ry) / s); // the retail window's height (px at scale 1)
|
||||
|
||||
float sx = o.X + w - SideW * s; // the side column follows the right edge
|
||||
Paperdoll(view, dl, new Vector2(o.X, ry + FieldY * s), s);
|
||||
SideColumn(view, dl, new Vector2(sx, ry + FieldY * s), r, s, filtered);
|
||||
Contents(view, dl, new Vector2(o.X, ry + ContentsY * s), sx, r, s, filtered);
|
||||
StatusStrip(view, dl, new Vector2(o.X, bottom), w, statusH, s);
|
||||
|
||||
// A press on an item that moves far enough starts a drag.
|
||||
if (_pressItem != null && _dragItem == null && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)
|
||||
&& Vector2.DistanceSquared(ImGuiNET.ImGui.GetMousePos(), _pressAt) > 25)
|
||||
_dragItem = _pressItem;
|
||||
}
|
||||
|
||||
// ── Background and title bar ────────────────────────────────────────
|
||||
|
||||
/// <summary>The stone background: its 25 px title band at scale, the rest stretched (AcClientReborn's rule).</summary>
|
||||
private static void Backdrop(ImDrawListPtr dl, Vector2 o, float w, float h, float s)
|
||||
{
|
||||
if (!RetailSprites.TryGet(Art.Backdrop, out IntPtr tex))
|
||||
{
|
||||
dl.AddRectFilled(o, o + new Vector2(w, h), StoneFallback);
|
||||
return;
|
||||
}
|
||||
const float ArtH = 362f;
|
||||
float band = Math.Min(h, TitleH * s);
|
||||
dl.AddImage(tex, o, o + new Vector2(w, band), Vector2.Zero, new Vector2(1, TitleH / ArtH));
|
||||
if (h > band)
|
||||
dl.AddImage(tex, o + new Vector2(0, band), o + new Vector2(w, h), new Vector2(0, TitleH / ArtH), Vector2.One);
|
||||
}
|
||||
|
||||
private void TitleBar(InventoryView view, ImDrawListPtr dl, Vector2 o, float w, float s)
|
||||
{
|
||||
float h = TitleH * s, closeW = 24 * s;
|
||||
float barW = w - closeW;
|
||||
|
||||
// The bar: three slices so its bevelled ends keep their shape at any width.
|
||||
if (RetailSprites.TryGet(Art.TitleBar, out IntPtr tex))
|
||||
{
|
||||
const float Src = 276f, Cap = 14f;
|
||||
float cap = Math.Min(Cap * s, barW * 0.5f);
|
||||
float u = Cap / Src;
|
||||
dl.AddImage(tex, o, o + new Vector2(cap, h), Vector2.Zero, new Vector2(u, 1));
|
||||
dl.AddImage(tex, o + new Vector2(cap, 0), o + new Vector2(barW - cap, h), new Vector2(u, 0), new Vector2(1 - u, 1));
|
||||
dl.AddImage(tex, o + new Vector2(barW - cap, 0), o + new Vector2(barW, h), new Vector2(1 - u, 0), Vector2.One);
|
||||
}
|
||||
else
|
||||
{
|
||||
dl.AddRectFilled(o, o + new Vector2(barW, h - 1), Black, 4);
|
||||
dl.AddRect(o, o + new Vector2(barW, h - 1), Gold, 4);
|
||||
}
|
||||
|
||||
// Two toggles at the bar's right end: the tools row and the Modern look.
|
||||
float btn = MathF.Round(18 * s);
|
||||
var b2 = new Vector2(o.X + barW - 8 * s - btn, o.Y + (h - btn) * 0.5f);
|
||||
var b1 = new Vector2(b2.X - btn - 2 * s, b2.Y);
|
||||
var bPlus = new Vector2(b1.X - btn - 6 * s, b2.Y);
|
||||
var bMinus = new Vector2(bPlus.X - btn - 2 * s, b2.Y);
|
||||
if (TitleToggle("##inv_smaller", PhosphorIcons.Minus, bMinus, btn, false))
|
||||
InventorySettingsStore.StepSize(-1);
|
||||
ImGuiNET.ImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)");
|
||||
if (TitleToggle("##inv_bigger", PhosphorIcons.Plus, bPlus, btn, false))
|
||||
InventorySettingsStore.StepSize(+1);
|
||||
ImGuiNET.ImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)");
|
||||
if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, b1, btn, InventorySettingsStore.ShowTools))
|
||||
InventorySettingsStore.SetShowTools(!InventorySettingsStore.ShowTools);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Search, sort and filter");
|
||||
if (TitleToggle("##inv_modern", PhosphorIcons.SquaresFour, b2, btn, false))
|
||||
InventorySettingsStore.SetClassic(false);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Modern look");
|
||||
|
||||
// Drag surface: the bar left of the toggles (moves the panel, like the header).
|
||||
float dragW = Math.Max(1, bMinus.X - o.X - 2);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(o);
|
||||
ImGuiNET.ImGui.InvisibleButton("##inv_titledrag", new Vector2(dragW, h));
|
||||
ImGuiPanelHost.DragWindowWithLastItem();
|
||||
|
||||
// "Inventory of <name>", centred on the bar (left of the toggles when it's narrow).
|
||||
if (!ReferenceEquals(_titleFor, view.PlayerName))
|
||||
{
|
||||
_titleFor = view.PlayerName;
|
||||
_titleText = view.PlayerName.Length > 0 ? "Inventory of " + view.PlayerName : "Inventory";
|
||||
}
|
||||
ImFontPtr f = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
ImGuiNET.ImGui.PushFont(f);
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_titleText);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
float tx = o.X + (barW - ts.X) * 0.5f;
|
||||
if (tx + ts.X > bMinus.X - 4) tx = Math.Max(o.X + 10 * s, bMinus.X - 4 - ts.X);
|
||||
dl.PushClipRect(o + new Vector2(6 * s, 0), new Vector2(bMinus.X - 2, o.Y + h), true);
|
||||
dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, new Vector2(tx, o.Y + (h - ts.Y) * 0.5f), White, _titleText);
|
||||
dl.PopClipRect();
|
||||
|
||||
// The retail close button.
|
||||
var cp = new Vector2(o.X + barW, o.Y);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(cp);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##inv_close", new Vector2(closeW, h)))
|
||||
ImGuiPanelHost.Close(Title);
|
||||
bool down = ImGuiNET.ImGui.IsItemActive();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Close");
|
||||
if (!Sprite(dl, down ? Art.Close + 1 : Art.Close, cp, new Vector2(closeW, h)))
|
||||
{
|
||||
dl.AddRect(cp + new Vector2(3 * s, 3 * s), cp + new Vector2(closeW - 3 * s, h - 3 * s), Gold, 2);
|
||||
dl.AddLine(cp + new Vector2(7 * s, h * 0.5f), cp + new Vector2(closeW - 7 * s, h * 0.5f), Gold, 2);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TitleToggle(string id, string glyph, Vector2 pos, float size, bool on)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(size, size));
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
if (on || hot) dl.AddRect(pos, pos + new Vector2(size, size), on ? Gold : Faded(Gold), 3);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(size, size), on || hot ? Gold : Faded(Gold));
|
||||
return clicked;
|
||||
}
|
||||
|
||||
// ── Paperdoll ───────────────────────────────────────────────────────
|
||||
|
||||
private void Paperdoll(InventoryView view, ImDrawListPtr dl, Vector2 field, float s)
|
||||
{
|
||||
float cell = CellPx * s;
|
||||
uint pendingId = InventoryModel.Pending?.ItemId ?? 0;
|
||||
for (int i = 0; i < Doll.Length; i++)
|
||||
{
|
||||
DollSlot slot = Doll[i];
|
||||
InventoryItem? worn = null;
|
||||
foreach (InventoryItem it in view.Worn)
|
||||
if ((it.Location & slot.Mask) != 0) { worn = it; break; }
|
||||
if (slot.Sigil != 0 && worn == null && (view.AetheriaMask & slot.Sigil) == 0) continue; // locked sigil slot
|
||||
|
||||
var min = new Vector2(field.X + slot.X * s, field.Y + slot.Y * s);
|
||||
var max = min + new Vector2(cell, cell);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(min);
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
ImGuiNET.ImGui.InvisibleButton("##doll", new Vector2(cell, cell), ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
|
||||
bool hovered = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
|
||||
if (worn != null)
|
||||
{
|
||||
DrawItemIcon(dl, worn.Id, min, cell, ReferenceEquals(worn, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu);
|
||||
ItemPointer(worn, hovered);
|
||||
}
|
||||
else
|
||||
{
|
||||
CellPicture(dl, slot.Empty, min, cell);
|
||||
if (hovered)
|
||||
{
|
||||
_hoverLabel = slot.Name;
|
||||
_hoverLabel2 = "Empty. Drag an item here to wear it.";
|
||||
}
|
||||
}
|
||||
|
||||
bool over = MouseIn(min, max);
|
||||
if (_dragItem != null && over)
|
||||
{
|
||||
bool fits = _dragItem.Wielder == 0 && (_dragItem.ValidLocations & slot.Mask) != 0;
|
||||
Overlay(dl, fits ? Art.AcceptGrid : Art.Reject, min, cell, fits ? AcceptGreen : RejectRed);
|
||||
}
|
||||
if (worn != null)
|
||||
{
|
||||
if (worn.Id == pendingId) Overlay(dl, Art.Waiting, min, cell, Amber);
|
||||
if (worn.Id == _selected) Overlay(dl, Art.Selected, min, cell, SelYellow);
|
||||
}
|
||||
_targets.Add(new Target { Min = min, Max = max, Kind = DropKind.Slot, Id = slot.Mask, Name = slot.Name });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Side column: burden, main pack, side packs ──────────────────────
|
||||
|
||||
private void SideColumn(InventoryView view, ImDrawListPtr dl, Vector2 field, float r, float s, bool filtered)
|
||||
{
|
||||
// Burden: caption and percent (36x15 each at y 7 and 18), meter 11x58 at (44, 8).
|
||||
ImFontPtr f = ImGuiFonts.Get(UiFont.Ui9);
|
||||
CenterText(dl, f, "Burden", new Vector2(field.X, field.Y + 7 * s), new Vector2(36 * s, 15 * s), White);
|
||||
CenterText(dl, f, view.BurdenText, new Vector2(field.X, field.Y + 18 * s), new Vector2(36 * s, 15 * s), White);
|
||||
var mMin = new Vector2(field.X + 44 * s, field.Y + 8 * s);
|
||||
var mSize = new Vector2(11 * s, 58 * s);
|
||||
// Retail's meter holds 0-300% of capacity (OpenAC's BurdenMath.LoadToFill: load / 3).
|
||||
float load = view.BurdenCapacity > 0 && view.Burden >= 0 ? view.Burden / (float)view.BurdenCapacity : 0f;
|
||||
float fill = Math.Clamp(load / 3f, 0f, 1f);
|
||||
if (!Sprite(dl, Art.BurdenBack, mMin, mSize)) dl.AddRectFilled(mMin, mMin + mSize, CellFallback);
|
||||
if (fill > 0f)
|
||||
{
|
||||
var fMin = new Vector2(mMin.X, mMin.Y + mSize.Y * (1 - fill));
|
||||
if (RetailSprites.TryGet(Art.BurdenFill, out IntPtr ft))
|
||||
dl.AddImage(ft, fMin, mMin + mSize, new Vector2(0, 1 - fill), Vector2.One);
|
||||
else
|
||||
dl.AddRectFilled(fMin, mMin + mSize, load > 2f ? Red : load > 1f ? Amber : Green);
|
||||
}
|
||||
if (MouseIn(field + new Vector2(0, 7 * s), mMin + mSize) && ImGuiNET.ImGui.IsWindowHovered())
|
||||
{
|
||||
_hoverLabel = "Burden";
|
||||
_hoverLabel2 = view.BurdenTip;
|
||||
}
|
||||
|
||||
// Main pack (36x36 at (6, 32)).
|
||||
InventoryPack? main = view.Packs.Length > 0 ? view.Packs[0] : null;
|
||||
PackCell(view, dl, main, new Vector2(field.X + 6 * s, field.Y + 32 * s), s, -1, filtered);
|
||||
|
||||
// The main pack's pack slots (36 px pitch at (6, 73)): the side packs, then the items
|
||||
// that take a pack slot (foci), as retail lists them; retail's seven slots (eight with
|
||||
// the augmentation) or more. Scrollbar at (41, 73); they scroll together.
|
||||
float listY = field.Y + 73 * s;
|
||||
float listH = Math.Max(PackPx * s, (r - FieldY - 87) * s);
|
||||
int rows = Math.Max(1, (int)(listH / (PackPx * s)));
|
||||
int sidePacks = Math.Max(0, view.Packs.Length - 1);
|
||||
int used = sidePacks + view.SlotItems.Length;
|
||||
int slots = Math.Max(view.ContainerSlots > 0 ? view.ContainerSlots : SideBagSlots, used);
|
||||
_packFirstRow = Math.Clamp(_packFirstRow, 0, Math.Max(0, slots - rows));
|
||||
uint pendingId = InventoryModel.Pending?.ItemId ?? 0;
|
||||
for (int row = 0; row < rows; row++)
|
||||
{
|
||||
int i = _packFirstRow + row;
|
||||
if (i >= slots) break;
|
||||
var min = new Vector2(field.X + 6 * s, listY + row * PackPx * s);
|
||||
if (i < sidePacks) PackCell(view, dl, view.Packs[i + 1], min, s, i, filtered);
|
||||
else if (i < used) SlotItemCell(view, dl, view.SlotItems[i - sidePacks], min, s, i, pendingId);
|
||||
else
|
||||
{
|
||||
PackCell(view, dl, null, min, s, i, filtered);
|
||||
SlotDropHint(view, dl, min + new Vector2(2 * s, 2 * s), CellPx * s);
|
||||
}
|
||||
}
|
||||
// The column itself (after the pack cells, which win): a pack-slot item dropped here
|
||||
// moves to the main pack, where it lives. Nothing goes *inside* a pack-slot item.
|
||||
var colMin = new Vector2(field.X, listY);
|
||||
var colMax = new Vector2(field.X + 41 * s, listY + Math.Min(listH, rows * PackPx * s));
|
||||
if (view.PlayerId != 0)
|
||||
_targets.Add(new Target { Min = colMin, Max = colMax, Kind = DropKind.PackSlots, Id = view.PlayerId, Name = "Main pack" });
|
||||
if (MouseIn(new Vector2(field.X, listY), new Vector2(field.X + SideW * s, listY + listH))
|
||||
&& ImGuiNET.ImGui.IsWindowHovered())
|
||||
Wheel(ref _packFirstRow, slots - rows);
|
||||
Scrollbar("##inv_packsb", new Vector2(field.X + 41 * s, listY), listH, s, ref _packFirstRow, slots, rows);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A pack-slot item (a focus) in the side column: a 36x36 cell with the item at (2, 2),
|
||||
/// drawn and handled like a grid item (select, double-click use, drag, tooltip, menu).
|
||||
/// </summary>
|
||||
private void SlotItemCell(InventoryView view, ImDrawListPtr dl, InventoryItem it, Vector2 min, float s, int index, uint pendingId)
|
||||
{
|
||||
float box = PackPx * s, cell = CellPx * s;
|
||||
var inner = min + new Vector2(2 * s, 2 * s);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(min);
|
||||
ImGuiNET.ImGui.PushID(index + 2);
|
||||
ImGuiNET.ImGui.InvisibleButton("##slotitem", new Vector2(box, box), ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
|
||||
bool hovered = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
ItemPointer(it, hovered);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts
|
||||
ItemCell(dl, it, inner, cell, pendingId);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
SlotDropHint(view, dl, inner, cell);
|
||||
}
|
||||
|
||||
/// <summary>While a drag is over a pack-slot cell: accept a pack-slot item headed for the main pack, else refuse.</summary>
|
||||
private void SlotDropHint(InventoryView view, ImDrawListPtr dl, Vector2 inner, float cell)
|
||||
{
|
||||
if (_dragItem == null || !MouseIn(inner, inner + new Vector2(cell, cell))) return;
|
||||
InventoryPack? main = view.Packs.Length > 0 ? view.Packs[0] : null;
|
||||
if (_dragItem.RequiresPackSlot && _dragItem.Container == view.PlayerId && _dragItem.Wielder == 0) return; // already here
|
||||
bool ok = main != null && _dragItem.RequiresPackSlot && !PackRefuses(view, main, _dragItem);
|
||||
Overlay(dl, ok ? Art.AcceptPack : Art.Reject, inner, cell, ok ? AcceptGreen : RejectRed);
|
||||
}
|
||||
|
||||
/// <summary>One pack cell (36x36, the picture at (2, 2)): click opens it; drop an item on it to move it in.</summary>
|
||||
private void PackCell(InventoryView view, ImDrawListPtr dl, InventoryPack? pack, Vector2 min, float s, int index, bool filtered)
|
||||
{
|
||||
float box = PackPx * s, cell = CellPx * s;
|
||||
var inner = min + new Vector2(2 * s, 2 * s);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(min);
|
||||
ImGuiNET.ImGui.PushID(index + 2);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton("##pack", new Vector2(box, box));
|
||||
bool hovered = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
|
||||
if (pack == null)
|
||||
{
|
||||
CellPicture(dl, Art.PackEmpty, inner, cell);
|
||||
return;
|
||||
}
|
||||
if (clicked && _dragItem == null) _pack = pack.Id;
|
||||
if (pack.IsMain)
|
||||
{
|
||||
if (!Sprite(dl, Art.MainPackIcon, inner, new Vector2(cell, cell)))
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Backpack, inner, new Vector2(cell, cell), Amber);
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawItemIcon(dl, pack.Id, inner, cell);
|
||||
}
|
||||
|
||||
// Fill meter (5x30 at the cell's right edge), hidden while the pack is empty (retail's
|
||||
// rule). Pack-slot items (foci) don't count against the main pack's 102.
|
||||
if (pack.Used > 0 && pack.Capacity > 0)
|
||||
{
|
||||
float f = Math.Clamp(pack.Used / (float)pack.Capacity, 0f, 1f);
|
||||
var bMin = inner + new Vector2(cell - 5 * s, 1 * s);
|
||||
var bSize = new Vector2(5 * s, 30 * s);
|
||||
if (!Sprite(dl, Art.CapacityBack, bMin, bSize)) dl.AddRectFilled(bMin, bMin + bSize, Black);
|
||||
var fMin = new Vector2(bMin.X, bMin.Y + bSize.Y * (1 - f));
|
||||
if (RetailSprites.TryGet(Art.CapacityFill, out IntPtr ft))
|
||||
dl.AddImage(ft, fMin, bMin + bSize, new Vector2(0, 1 - f), Vector2.One);
|
||||
else
|
||||
dl.AddRectFilled(fMin, bMin + bSize, Gold);
|
||||
}
|
||||
|
||||
if (pack.Id == _pack && !filtered)
|
||||
{
|
||||
if (!Sprite(dl, Art.OpenPack, min, new Vector2(box, box)))
|
||||
dl.AddTriangleFilled(new Vector2(min.X, min.Y + box * 0.35f), new Vector2(min.X + 5 * s, min.Y + box * 0.5f),
|
||||
new Vector2(min.X, min.Y + box * 0.65f), Gold);
|
||||
}
|
||||
if (_dragItem != null && MouseIn(min, min + new Vector2(box, box)))
|
||||
{
|
||||
bool here = _dragItem.Container == pack.Id && _dragItem.Wielder == 0;
|
||||
bool full = !here && PackRefuses(view, pack, _dragItem);
|
||||
if (!here) Overlay(dl, full ? Art.Reject : Art.AcceptPack, inner, cell, full ? RejectRed : AcceptGreen);
|
||||
}
|
||||
if (hovered)
|
||||
{
|
||||
_hoverLabel = pack.Name;
|
||||
_hoverLabel2 = pack.FillText;
|
||||
}
|
||||
_targets.Add(new Target { Min = min, Max = min + new Vector2(box, box), Kind = DropKind.Pack, Id = pack.Id, Name = pack.Name });
|
||||
}
|
||||
|
||||
// ── Contents: the open pack's slots ─────────────────────────────────
|
||||
|
||||
private void Contents(InventoryView view, ImDrawListPtr dl, Vector2 field, float sideX, float r, float s, bool filtered)
|
||||
{
|
||||
float cell = CellPx * s;
|
||||
var gridPos = new Vector2(field.X + 15 * s, field.Y + 20 * s);
|
||||
float availW = sideX - 32 * s - gridPos.X; // retail: grid 15..207, scrollbar 207..223, column at 239
|
||||
int cols = Math.Max(1, (int)(availW / cell));
|
||||
float gridW = cols * cell;
|
||||
float gridH = Math.Max(cell, (r - ContentsY - 5 - 24) * s);
|
||||
int rows = Math.Max(1, (int)(gridH / cell + 0.01f));
|
||||
|
||||
// "Contents of <pack>" over the grid.
|
||||
CenterText(dl, ImGuiFonts.Get(UiFont.Ui10), _captionText, new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White);
|
||||
|
||||
InventoryPack? open = filtered ? null : view.PackOf(_pack);
|
||||
int cells = open != null ? Math.Max(open.Capacity, _shown.Count) : _shown.Count;
|
||||
int totalRows = (cells + cols - 1) / cols;
|
||||
_gridFirstRow = Math.Clamp(_gridFirstRow, 0, Math.Max(0, totalRows - rows));
|
||||
|
||||
var area = new Vector2(gridW, rows * cell);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(gridPos);
|
||||
ImGuiNET.ImGui.InvisibleButton("##inv_cells", area, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
|
||||
bool hovered = ImGuiNET.ImGui.IsItemHovered();
|
||||
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
|
||||
int hoverCell = -1;
|
||||
if (MouseIn(gridPos, gridPos + area))
|
||||
{
|
||||
int c = (int)((mouse.X - gridPos.X) / cell), rr = (int)((mouse.Y - gridPos.Y) / cell);
|
||||
if (c >= 0 && c < cols && rr >= 0 && rr < rows) hoverCell = (_gridFirstRow + rr) * cols + c;
|
||||
if (ImGuiNET.ImGui.IsWindowHovered()) Wheel(ref _gridFirstRow, totalRows - rows);
|
||||
}
|
||||
if (hovered && hoverCell >= 0 && hoverCell < _shown.Count) ItemPointer(_shown[hoverCell], true);
|
||||
|
||||
// Only the rows on show; retail draws an item's icon in place of the empty cell.
|
||||
uint pendingId = InventoryModel.Pending?.ItemId ?? 0;
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts
|
||||
for (int rr = 0; rr < rows; rr++)
|
||||
{
|
||||
for (int c = 0; c < cols; c++)
|
||||
{
|
||||
int i = (_gridFirstRow + rr) * cols + c;
|
||||
if (i >= cells) break;
|
||||
var min = new Vector2(gridPos.X + c * cell, gridPos.Y + rr * cell);
|
||||
if (i >= _shown.Count)
|
||||
{
|
||||
CellPicture(dl, Art.GridEmpty, min, cell);
|
||||
continue;
|
||||
}
|
||||
ItemCell(dl, _shown[i], min, cell, pendingId);
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
||||
if (open != null)
|
||||
{
|
||||
// Dropping on the grid moves the item into the open pack.
|
||||
if (_dragItem != null && hoverCell >= 0 && hoverCell < cells && !(_dragItem.Container == open.Id && _dragItem.Wielder == 0))
|
||||
{
|
||||
int c = hoverCell % cols, rr = hoverCell / cols - _gridFirstRow;
|
||||
var min = new Vector2(gridPos.X + c * cell, gridPos.Y + rr * cell);
|
||||
bool full = PackRefuses(view, open, _dragItem);
|
||||
Overlay(dl, full ? Art.Reject : Art.AcceptGrid, min, cell, full ? RejectRed : AcceptGreen);
|
||||
}
|
||||
_targets.Add(new Target { Min = gridPos, Max = gridPos + area, Kind = DropKind.Pack, Id = open.Id, Name = open.Name });
|
||||
}
|
||||
else if (_shown.Count == 0)
|
||||
{
|
||||
dl.AddText(gridPos + new Vector2(4, 4), Mute, "Nothing matches.");
|
||||
}
|
||||
|
||||
Scrollbar("##inv_gridsb", new Vector2(gridPos.X + gridW, gridPos.Y), rows * cell, s, ref _gridFirstRow, totalRows, rows);
|
||||
}
|
||||
|
||||
// ── Status strip: the action / outcome (or pyreals), Drop, Give ─────
|
||||
|
||||
private void StatusStrip(InventoryView view, ImDrawListPtr dl, Vector2 p, float w, float h, float s)
|
||||
{
|
||||
dl.AddRectFilled(p, p + new Vector2(w, h), Black);
|
||||
dl.AddLine(p, p + new Vector2(w, 0), Faded(Gold));
|
||||
InventoryTarget? target = InventoryModel.Target;
|
||||
InventoryItem? sel = SelectedItem(view);
|
||||
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),
|
||||
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);
|
||||
}
|
||||
|
||||
// ── Pieces ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// One item's cell picture (the contents grid and the side column's pack-slot items):
|
||||
/// its icon (faded while dragged), stack count (in the caller's font), and the waiting
|
||||
/// and selected overlays.
|
||||
/// </summary>
|
||||
private void ItemCell(ImDrawListPtr dl, InventoryItem it, Vector2 min, float cell, uint pendingId)
|
||||
{
|
||||
DrawItemIcon(dl, it.Id, min, cell, ReferenceEquals(it, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu);
|
||||
if (it.StackText.Length > 0)
|
||||
{
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(it.StackText);
|
||||
var tp = new Vector2(min.X + cell - ts.X - 1, min.Y + cell - ts.Y);
|
||||
dl.AddText(tp + Vector2.One, StackShadow, it.StackText);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Hover, click (select, and a press that may become a drag), double-click (use), right-click (menu).</summary>
|
||||
private void ItemPointer(InventoryItem it, bool hovered)
|
||||
{
|
||||
if (!hovered) return;
|
||||
_hover = it;
|
||||
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
|
||||
{
|
||||
_selected = it.Id;
|
||||
_pressItem = it;
|
||||
_pressAt = ImGuiNET.ImGui.GetMousePos();
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
|
||||
{
|
||||
_pressItem = null;
|
||||
Act(InventoryActionKind.Use, it, 0, "", 0);
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
|
||||
{
|
||||
_selected = it.Id;
|
||||
_ctxItem = it;
|
||||
_openCtx = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The retail scrollbar (LayoutDesc 0x2100003E's 16 px variant): tiled chain, up and down
|
||||
/// gems, three-piece thumb. Clicking a gem moves a row; dragging the thumb, or clicking the
|
||||
/// chain, moves to that point.
|
||||
/// </summary>
|
||||
private void Scrollbar(string id, Vector2 pos, float h, float s, ref int first, int total, int visible)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float w = 16 * s, btn = Math.Min(16 * s, h * 0.5f);
|
||||
int max = Math.Max(0, total - visible);
|
||||
first = Math.Clamp(first, 0, max);
|
||||
if (h < 2 || w < 2) return;
|
||||
|
||||
// Chain, tiled down the shaft (stretching smears the beads).
|
||||
if (RetailSprites.TryGet(Art.Track, out IntPtr track))
|
||||
{
|
||||
float tile = 32 * s;
|
||||
for (float y = 0; y < h; y += tile)
|
||||
{
|
||||
float th = Math.Min(tile, h - y);
|
||||
dl.AddImage(track, new Vector2(pos.X, pos.Y + y), new Vector2(pos.X + w, pos.Y + y + th), Vector2.Zero,
|
||||
new Vector2(1, th / tile));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
dl.AddRectFilled(pos + new Vector2(w * 0.3f, 0), pos + new Vector2(w * 0.7f, h), Faded(Gold));
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.PushID(id);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##up", new Vector2(w, btn)) && first > 0) first--;
|
||||
uint upState = ImGuiNET.ImGui.IsItemActive() ? 2u : ImGuiNET.ImGui.IsItemHovered() ? 1u : 0u;
|
||||
var downPos = new Vector2(pos.X, pos.Y + h - btn);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(downPos);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##down", new Vector2(w, btn)) && first < max) first++;
|
||||
uint downState = ImGuiNET.ImGui.IsItemActive() ? 2u : ImGuiNET.ImGui.IsItemHovered() ? 1u : 0u;
|
||||
|
||||
float t0 = pos.Y + btn, span = h - 2 * btn;
|
||||
if (max > 0 && span > 4)
|
||||
{
|
||||
float th = Math.Clamp(span * visible / Math.Max(1, total), Math.Min(16 * s, span), span);
|
||||
float t = t0 + (span - th) * first / max;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, t0));
|
||||
ImGuiNET.ImGui.InvisibleButton("##track", new Vector2(w, span));
|
||||
if (ImGuiNET.ImGui.IsItemActive())
|
||||
{
|
||||
float my = ImGuiNET.ImGui.GetMousePos().Y;
|
||||
if (ImGuiNET.ImGui.IsItemActivated()) _thumbGrab = my >= t && my < t + th ? my - t : th * 0.5f;
|
||||
float rel = (my - _thumbGrab - t0) / Math.Max(1f, span - th);
|
||||
first = Math.Clamp((int)MathF.Round(rel * max), 0, max);
|
||||
t = t0 + (span - th) * first / max;
|
||||
}
|
||||
// Thumb: 3 px caps, the middle stretched.
|
||||
float cap = Math.Min(3 * s, th * 0.5f);
|
||||
var a = new Vector2(pos.X, t);
|
||||
if (!Sprite(dl, Art.ThumbTop, a, new Vector2(w, cap))
|
||||
| !Sprite(dl, Art.ThumbMid, a + new Vector2(0, cap), new Vector2(w, th - 2 * cap))
|
||||
| !Sprite(dl, Art.ThumbBottom, a + new Vector2(0, th - cap), new Vector2(w, cap)))
|
||||
dl.AddRectFilled(a, a + new Vector2(w, th), Rgb(0xFF203C78), 2);
|
||||
}
|
||||
ImGuiNET.ImGui.PopID();
|
||||
|
||||
if (!Sprite(dl, Art.Up + upState, pos, new Vector2(w, btn)))
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretUp, pos, new Vector2(w, btn), Gold);
|
||||
if (!Sprite(dl, Art.Down + downState, downPos, new Vector2(w, btn)))
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown, downPos, new Vector2(w, btn), Gold);
|
||||
}
|
||||
|
||||
private static void Wheel(ref int first, int max)
|
||||
{
|
||||
float wheel = ImGuiNET.ImGui.GetIO().MouseWheel;
|
||||
if (wheel == 0) return;
|
||||
first = Math.Clamp(first - Math.Sign(wheel), 0, Math.Max(0, max));
|
||||
}
|
||||
|
||||
/// <summary>A retail picture at min..min+size; false (nothing drawn) until it has loaded.</summary>
|
||||
private static bool Sprite(ImDrawListPtr dl, uint id, Vector2 min, Vector2 size)
|
||||
{
|
||||
if (!RetailSprites.TryGet(id, out IntPtr tex)) return false;
|
||||
dl.AddImage(tex, min, min + size);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>An empty cell's picture, or a plain dark cell until it has loaded.</summary>
|
||||
private static void CellPicture(ImDrawListPtr dl, uint id, Vector2 min, float size)
|
||||
{
|
||||
if (Sprite(dl, id, min, new Vector2(size, size))) return;
|
||||
dl.AddRectFilled(min, min + new Vector2(size, size), CellFallback);
|
||||
dl.AddRect(min, min + new Vector2(size, size), CellEdge);
|
||||
}
|
||||
|
||||
/// <summary>A retail overlay (selected, waiting, drop accepted / refused), or an outline in <paramref name="fallback"/>.</summary>
|
||||
private static void Overlay(ImDrawListPtr dl, uint id, Vector2 min, float size, uint fallback)
|
||||
{
|
||||
if (Sprite(dl, id, min, new Vector2(size, size))) return;
|
||||
dl.AddRect(min, min + new Vector2(size, size), fallback, 2, ImDrawFlags.None, 1.5f);
|
||||
}
|
||||
|
||||
private static void CenterText(ImDrawListPtr dl, ImFontPtr f, string text, Vector2 pos, Vector2 size, uint color)
|
||||
{
|
||||
if (text.Length == 0) return;
|
||||
ImGuiNET.ImGui.PushFont(f);
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
dl.PushClipRect(pos, pos + size, true);
|
||||
dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, new Vector2(pos.X + (size.X - ts.X) * 0.5f, pos.Y + (size.Y - ts.Y) * 0.5f), color, text);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
|
||||
private static bool MouseIn(Vector2 min, Vector2 max)
|
||||
{
|
||||
Vector2 m = ImGuiNET.ImGui.GetMousePos();
|
||||
return m.X >= min.X && m.Y >= min.Y && m.X < max.X && m.Y < max.Y;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Inventory panel's remembered choices: Classic or Modern look, and whether the
|
||||
/// Classic view shows its tools row. %LOCALAPPDATA%\RynthCore\inventory_settings.txt,
|
||||
/// read once when the panel opens, written in the background when a choice changes.
|
||||
/// </summary>
|
||||
internal static class InventorySettingsStore
|
||||
{
|
||||
private static readonly object Sync = new();
|
||||
private static bool _loaded;
|
||||
|
||||
/// <summary>The retail look (default) or the Phase 1 modern layout.</summary>
|
||||
public static bool Classic { get; private set; } = true;
|
||||
/// <summary>Classic view: the search / sort / category row under the title bar.</summary>
|
||||
public static bool ShowTools { get; private set; }
|
||||
/// <summary>The panel's size in percent of the UI scale (50-150, steps of 10); text follows it.</summary>
|
||||
public static int SizePct { get; private set; } = 80;
|
||||
public static float SizeFactor => SizePct / 100f;
|
||||
|
||||
private static string FilePath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "inventory_settings.txt");
|
||||
|
||||
public static void Load()
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
if (!File.Exists(path)) return;
|
||||
foreach (string raw in File.ReadAllLines(path))
|
||||
{
|
||||
string line = raw.Trim();
|
||||
int eq = line.IndexOf('=');
|
||||
if (line.StartsWith('#') || eq <= 0) continue;
|
||||
string key = line[..eq].Trim(), val = line[(eq + 1)..].Trim();
|
||||
if (key == "classic") Classic = val == "1";
|
||||
else if (key == "tools") ShowTools = val == "1";
|
||||
else if (key == "size" && int.TryParse(val, out int pct)) SizePct = Math.Clamp(pct, 50, 150);
|
||||
}
|
||||
}
|
||||
catch { /* defaults stay */ }
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetClassic(bool on)
|
||||
{
|
||||
if (Classic == on) return;
|
||||
Classic = on;
|
||||
Save();
|
||||
}
|
||||
|
||||
public static void StepSize(int dir)
|
||||
{
|
||||
int next = Math.Clamp(SizePct + 10 * Math.Sign(dir), 50, 150);
|
||||
if (next == SizePct) return;
|
||||
SizePct = next;
|
||||
Save();
|
||||
}
|
||||
|
||||
public static void SetShowTools(bool on)
|
||||
{
|
||||
if (ShowTools == on) return;
|
||||
ShowTools = on;
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>Writes the settings in the background (the caller is AC's render thread).</summary>
|
||||
private static void Save()
|
||||
{
|
||||
string text = "# RynthCore inventory panel settings - auto-generated, hand-edits OK.\n"
|
||||
+ "classic=" + (Classic ? "1" : "0") + "\n"
|
||||
+ "tools=" + (ShowTools ? "1" : "0") + "\n"
|
||||
+ "size=" + SizePct + "\n";
|
||||
UiBackgroundWriter.Enqueue("inventory settings", () =>
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(path, text);
|
||||
}
|
||||
catch { /* non-fatal */ }
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
990
src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs
Normal file
990
src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs
Normal file
|
|
@ -0,0 +1,990 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/InventoryFace.cs
|
||||
// The in-game Inventory panel (docs/IMGUI_INVENTORY.md). Engine only.
|
||||
// Two looks, one set of behaviours (a toggle switches them, remembered):
|
||||
// Classic the retail inventory window, drawn from the client's own
|
||||
// pictures (InventoryFace.Classic.cs; Phase 2)
|
||||
// Modern the Phase 1 layout, below
|
||||
//
|
||||
// header burden (percent of capacity) and pyreals; item count
|
||||
// tools search box, sort picker; category chips
|
||||
// packs All, Main pack, each side pack (its icon and fill), Worn
|
||||
// grid the chosen pack's items as icons with stack counts; hover for a
|
||||
// tooltip (asks the server to identify an unknown item, throttled);
|
||||
// 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
|
||||
// status the one action waiting for the server (with a timer), or how the
|
||||
// last one ended
|
||||
//
|
||||
// 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).
|
||||
// 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.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed partial class InventoryFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Inventory";
|
||||
|
||||
// Default: the Classic view at its retail size (300 x 362 body, plus the status strip).
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(302, 426), new Vector2(240, 300), EdgeToEdge: true),
|
||||
() => new InventoryFace());
|
||||
|
||||
// ── Layout (px, like the other faces) ───────────────────────────────
|
||||
private const float Cell = 38, Icon = 32, RowH = 24, PackRowH = 38, ZoneH = 30, StatusH = 20;
|
||||
private const uint AllPacks = 0, WornPacks = 1; // pseudo pack ids (real ids are never 0 or 1)
|
||||
|
||||
private static readonly uint CellBg = RynthTheme.Argb(0xFF101822), CellHot = RynthTheme.Argb(0xFF1C3148),
|
||||
CellSel = RynthTheme.Argb(0xFF26D9E6), StackCol = RynthTheme.Argb(0xFFFFFFFF), StackShadow = RynthTheme.Argb(0xE0000000),
|
||||
DropHot = RynthTheme.Argb(0xFF1F5A3A), Placeholder = RynthTheme.Argb(0xFF1A2633);
|
||||
|
||||
private static readonly string[] SortNames = { "Pack order", "Name", "Value", "Burden", "Type", "Stack" };
|
||||
private static readonly string[] SortLabels = Array.ConvertAll(SortNames, n => PhosphorIcons.SortAscending + " " + n);
|
||||
private static readonly string[] CategoryNames = { "All", "Weapons", "Armor", "Jewelry", "Usable", "Comps", "Salvage", "Misc" };
|
||||
private static readonly InventoryCategory[] CategoryOf =
|
||||
{
|
||||
default, InventoryCategory.Weapons, InventoryCategory.Armor, InventoryCategory.Jewelry, InventoryCategory.Usable,
|
||||
InventoryCategory.Components, InventoryCategory.Salvage, InventoryCategory.Misc,
|
||||
};
|
||||
|
||||
// ── State ───────────────────────────────────────────────────────────
|
||||
private uint _pack = AllPacks;
|
||||
private int _sort, _category;
|
||||
private readonly byte[] _search = new byte[64];
|
||||
private string _searchText = string.Empty;
|
||||
private uint _selected;
|
||||
private readonly Picker _picker = new("##inv_sort");
|
||||
|
||||
// Filtered, sorted list (rebuilt only when an input changes).
|
||||
private readonly List<InventoryItem> _shown = new(256);
|
||||
private InventoryView? _builtFor;
|
||||
private uint _builtPack = uint.MaxValue;
|
||||
private int _builtSort = -1, _builtCategory = -1;
|
||||
private string _builtSearch = "\0";
|
||||
private bool _builtClassic;
|
||||
// Leave pack-slot items (foci) out of this list: the Classic main pack grid (they're in the side column).
|
||||
private bool _skipSlotItems;
|
||||
private string _countText = string.Empty;
|
||||
|
||||
// Hover and tooltip cache.
|
||||
private InventoryItem? _hover, _tipItem;
|
||||
private string[] _tipBase = Array.Empty<string>();
|
||||
|
||||
// Drag.
|
||||
private InventoryItem? _pressItem, _dragItem;
|
||||
private Vector2 _pressAt;
|
||||
// Slot: one paperdoll slot (Id = its equip mask, Name = the slot's name).
|
||||
// PackSlots: the Classic side column's pack slots (Id = the main pack): only a
|
||||
// pack-slot item (a focus) goes there, which moves it to the main pack.
|
||||
private enum DropKind : byte { None, Pack, Equip, Drop, Give, Slot, PackSlots }
|
||||
private struct Target { public Vector2 Min, Max; public DropKind Kind; public uint Id; public string Name; }
|
||||
private readonly List<Target> _targets = new(16);
|
||||
|
||||
// Context menu and split dialog (opened at the end of Draw, outside any child).
|
||||
private InventoryItem? _ctxItem;
|
||||
private bool _openCtx, _openSplit;
|
||||
private InventoryItem? _splitItem;
|
||||
private int _splitAmount = 1;
|
||||
private uint _splitTarget;
|
||||
|
||||
// Status line cache.
|
||||
private string _statusText = string.Empty;
|
||||
private int _statusKey = int.MinValue;
|
||||
private string _refusal = string.Empty;
|
||||
private long _refusalAt;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
InventorySettingsStore.Load();
|
||||
InventoryModel.Subscribe();
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
InventoryModel.Hover(0);
|
||||
InventoryModel.Unsubscribe();
|
||||
_dragItem = _pressItem = null;
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Frame
|
||||
// =====================================================================
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
InventoryView view = InventoryModel.Current;
|
||||
_targets.Clear();
|
||||
_hover = null;
|
||||
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
if (view.PlayerId == 0)
|
||||
{
|
||||
Label("Waiting for your character's inventory...", Mute);
|
||||
End(origin, size);
|
||||
InventoryModel.Hover(0);
|
||||
return;
|
||||
}
|
||||
|
||||
_hoverLabel = _hoverLabel2 = null;
|
||||
// Text follows the panel's size setting (the - / + in the Classic title bar).
|
||||
ImGuiNET.ImGui.SetWindowFontScale(InventorySettingsStore.SizeFactor);
|
||||
if (InventorySettingsStore.Classic) ClassicBody(view, origin, size);
|
||||
else ModernBody(view, origin, size, w);
|
||||
|
||||
InventoryModel.Hover(_dragItem == null ? _hover?.Id ?? 0 : 0);
|
||||
FinishDrag();
|
||||
End(origin, size);
|
||||
|
||||
Tooltip();
|
||||
DrawDragGhost();
|
||||
ContextMenu(view);
|
||||
SplitDialog(view);
|
||||
_picker.Draw();
|
||||
}
|
||||
|
||||
/// <summary>The Phase 1 layout: header, tools, chips, pack column | grid, zones, status.</summary>
|
||||
private void ModernBody(InventoryView view, Vector2 origin, Vector2 size, float w)
|
||||
{
|
||||
if (_pack != AllPacks && _pack != WornPacks && view.PackOf(_pack) == null) _pack = AllPacks;
|
||||
RebuildIfNeeded(view, _pack); // the header shows the count
|
||||
Header(view, w);
|
||||
Tools(w);
|
||||
Chips(w);
|
||||
RebuildIfNeeded(view, _pack);
|
||||
|
||||
// Body: pack column | grid, then zones and the status row at the bottom.
|
||||
float bottomH = ZoneH + StatusH + 8;
|
||||
Vector2 bodyPos = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float bodyH = Math.Max(60, origin.Y + size.Y - 6 - bottomH - bodyPos.Y);
|
||||
float colW = w >= 380 ? 128 : 46;
|
||||
PackColumn(view, bodyPos, colW, bodyH);
|
||||
Grid(new Vector2(bodyPos.X + colW + 4, bodyPos.Y), new Vector2(w - colW - 4, bodyH));
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bodyPos.X, bodyPos.Y + bodyH + 4));
|
||||
Zones(view, w);
|
||||
StatusRow(w);
|
||||
}
|
||||
|
||||
// ── Header: burden, pyreals, count ──────────────────────────────────
|
||||
|
||||
private void Header(InventoryView view, float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImFontPtr icons = ImGuiFonts.Get(UiFont.Ui14);
|
||||
float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
|
||||
PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Scales, p, new Vector2(18, RowH), Amber);
|
||||
float x = p.X + 20;
|
||||
dl.AddText(new Vector2(x, ty), BurdenColour(view), view.BurdenText);
|
||||
float bw = ImGuiNET.ImGui.CalcTextSize(view.BurdenText).X;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.InvisibleButton("##burden", new Vector2(x + bw - p.X, RowH));
|
||||
ImGuiNET.ImGui.SetItemTooltip(view.BurdenTip);
|
||||
|
||||
x += bw + 16;
|
||||
PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Coins, new Vector2(x, p.Y), new Vector2(18, RowH), Amber);
|
||||
dl.AddText(new Vector2(x + 20, ty), Text, view.PyrealText);
|
||||
|
||||
// Switch to the Classic (retail) look.
|
||||
var tb = new Vector2(p.X + w - 22, p.Y + 1);
|
||||
if (IconButton("##inv_classic", PhosphorIcons.AppWindow, tb, new Vector2(22, 22), Amber, BtnFill, font: UiFont.Ui11))
|
||||
InventorySettingsStore.SetClassic(true);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Classic look (the retail inventory window)");
|
||||
|
||||
float cw = ImGuiNET.ImGui.CalcTextSize(_countText).X;
|
||||
dl.AddText(new Vector2(tb.X - cw - 6, ty), Mute, _countText);
|
||||
NextLine(p, RowH + 2);
|
||||
}
|
||||
|
||||
private static uint BurdenColour(InventoryView view)
|
||||
{
|
||||
if (view.BurdenCapacity <= 0 || view.Burden < 0) return Text;
|
||||
return view.Burden > view.BurdenCapacity ? Red : view.Burden * 10 > view.BurdenCapacity * 9 ? Amber : Green;
|
||||
}
|
||||
|
||||
// ── Search, sort, categories ────────────────────────────────────────
|
||||
|
||||
private void Tools(float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float sortW = 118;
|
||||
float boxW = Math.Max(80, w - sortW - 26 - 8);
|
||||
if (TextBox("##inv_search", _search, p, boxW, PhosphorIcons.MagnifyingGlass + " Search names", out _))
|
||||
_searchText = Utf8(_search).Trim().ToLowerInvariant();
|
||||
if (IconButton("##inv_clear", PhosphorIcons.X, new Vector2(p.X + boxW + 2, p.Y), new Vector2(22, 22), Mute, BtnFill,
|
||||
enabled: _search[0] != 0, font: UiFont.Ui11))
|
||||
{
|
||||
Array.Clear(_search);
|
||||
_searchText = string.Empty;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Clear the search");
|
||||
Vector2 sp = new(p.X + w - sortW, p.Y);
|
||||
if (Button("##inv_sortbtn", SortLabels[_sort], sp, new Vector2(sortW, 22), Text, BtnFill,
|
||||
leftAlign: true))
|
||||
_picker.Open(new Vector2(sp.X, sp.Y + 24), SortNames, _sort, i => _sort = i, sortW);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Sort the items");
|
||||
NextLine(p, 26);
|
||||
}
|
||||
|
||||
private void Chips(float w)
|
||||
{
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x = start.X, y = start.Y;
|
||||
ImFontPtr f = ImGuiFonts.Get(UiFont.Ui9);
|
||||
const float h = 18;
|
||||
for (int i = 0; i < CategoryNames.Length; i++)
|
||||
{
|
||||
string label = CategoryNames[i];
|
||||
float cw = CalcWidth(f, label) + 12;
|
||||
if (x > start.X && x + cw > start.X + w) { x = start.X; y += h + 3; }
|
||||
var pos = new Vector2(x, y);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##chip", new Vector2(cw, h))) _category = i;
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
bool on = _category == i;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(pos, pos + new Vector2(cw, h), on ? Selected : hot ? Lighten(BtnFill) : BtnFill, 9);
|
||||
dl.AddRect(pos, pos + new Vector2(cw, h), on ? Teal : BtnBord, 9);
|
||||
dl.AddText(f, f.FontSize * InventorySettingsStore.SizeFactor, pos + new Vector2(6, (h - f.FontSize) * 0.5f), on ? Teal : Text, label);
|
||||
x += cw + 4;
|
||||
}
|
||||
NextLine(start, y - start.Y + h + 4);
|
||||
}
|
||||
|
||||
private static float CalcWidth(ImFontPtr font, string text)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(font);
|
||||
float w = ImGuiNET.ImGui.CalcTextSize(text).X;
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
return w;
|
||||
}
|
||||
|
||||
// ── Filtered list ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The filtered, sorted list for <paramref name="pack"/> (a real pack id, AllPacks or
|
||||
/// WornPacks; the caller makes sure a real id is in the view). Rebuilt only on change.
|
||||
/// </summary>
|
||||
private void RebuildIfNeeded(InventoryView view, uint pack)
|
||||
{
|
||||
bool classic = InventorySettingsStore.Classic;
|
||||
if (ReferenceEquals(view, _builtFor) && _builtPack == pack && _builtSort == _sort
|
||||
&& _builtCategory == _category && ReferenceEquals(_builtSearch, _searchText) && _builtClassic == classic)
|
||||
return;
|
||||
if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category)
|
||||
_gridFirstRow = 0; // another pack or filter: back to the top (Classic grid)
|
||||
_builtFor = view;
|
||||
_builtPack = pack;
|
||||
_builtSort = _sort;
|
||||
_builtCategory = _category;
|
||||
_builtSearch = _searchText;
|
||||
_builtClassic = classic;
|
||||
|
||||
_shown.Clear();
|
||||
InventoryPack? one = pack == WornPacks || pack == AllPacks ? null : view.PackOf(pack);
|
||||
// Classic, the main pack open: its pack-slot items (foci) are in the side column, not
|
||||
// the grid (retail). A search or filter (all packs) and the Modern look list them.
|
||||
_skipSlotItems = classic && one != null && one.IsMain;
|
||||
if (pack == WornPacks) AddFiltered(view.Worn);
|
||||
else if (one == null) foreach (InventoryPack p in view.Packs) AddFiltered(p.Items);
|
||||
else AddFiltered(one.Items);
|
||||
|
||||
Comparison<InventoryItem>? cmp = _sort switch
|
||||
{
|
||||
1 => ByName,
|
||||
2 => static (a, b) => b.Value != a.Value ? b.Value.CompareTo(a.Value) : ByName(a, b),
|
||||
3 => static (a, b) => b.Burden != a.Burden ? b.Burden.CompareTo(a.Burden) : ByName(a, b),
|
||||
4 => static (a, b) => a.Category != b.Category ? a.Category.CompareTo(b.Category) : ByName(a, b),
|
||||
5 => static (a, b) => b.Stack != a.Stack ? b.Stack.CompareTo(a.Stack) : ByName(a, b),
|
||||
_ => null, // pack order: as captured (packs in order, ascending id inside each)
|
||||
};
|
||||
if (cmp != null) _shown.Sort(cmp);
|
||||
|
||||
int total = pack == WornPacks ? view.Worn.Length : one == null ? view.ItemCount
|
||||
: _skipSlotItems ? one.Used : one.Items.Length;
|
||||
_countText = _shown.Count == total
|
||||
? total.ToString(CultureInfo.InvariantCulture) + " items"
|
||||
: _shown.Count.ToString(CultureInfo.InvariantCulture) + " of " + total.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)
|
||||
: one.IsMain ? "Contents of Backpack"
|
||||
: "Contents of " + one.Name;
|
||||
}
|
||||
|
||||
private static int ByName(InventoryItem a, InventoryItem b)
|
||||
{
|
||||
int c = string.CompareOrdinal(a.SearchName, b.SearchName);
|
||||
return c != 0 ? c : a.Id.CompareTo(b.Id);
|
||||
}
|
||||
|
||||
private void AddFiltered(InventoryItem[] items)
|
||||
{
|
||||
InventoryCategory cat = CategoryOf[_category];
|
||||
foreach (InventoryItem it in items)
|
||||
{
|
||||
if (_skipSlotItems && it.RequiresPackSlot) continue;
|
||||
if (_category != 0 && it.Category != cat) continue;
|
||||
if (_searchText.Length > 0 && !it.SearchName.Contains(_searchText, StringComparison.Ordinal)) continue;
|
||||
_shown.Add(it);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Pack column ─────────────────────────────────────────────────────
|
||||
|
||||
private void PackColumn(InventoryView view, Vector2 pos, float colW, float h)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 2));
|
||||
ImGuiNET.ImGui.BeginChild("##inv_packs", new Vector2(colW, h), ImGuiChildFlags.AlwaysUseWindowPadding);
|
||||
ImGuiNET.ImGui.PopStyleVar(2);
|
||||
float iw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
bool wide = colW > 60;
|
||||
|
||||
PackRow("##p_all", AllPacks, PhosphorIcons.SquaresFour, 0, "All packs", view.ItemCountText, iw, wide, DropKind.None, "");
|
||||
for (int i = 0; i < view.Packs.Length; i++)
|
||||
{
|
||||
InventoryPack p = view.Packs[i];
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
PackRow("##p", p.Id, p.IsMain ? PhosphorIcons.Backpack : string.Empty, p.IsMain ? 0 : p.Id, p.Name, p.FillText,
|
||||
iw, wide, DropKind.Pack, p.Name);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
PackRow("##p_worn", WornPacks, PhosphorIcons.Shield, 0, "Worn", view.WornCountText, iw, wide, DropKind.Equip, "Worn");
|
||||
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
|
||||
/// <summary>One pack entry: click shows it; it is a drop target (move into it, or equip for Worn).</summary>
|
||||
private void PackRow(string id, uint packId, string glyph, uint iconObject, string name, string fill, float w, bool wide,
|
||||
DropKind drop, string dropName)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var sz = new Vector2(w, PackRowH);
|
||||
if (ImGuiNET.ImGui.InvisibleButton(id, sz)) _pack = packId;
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
|
||||
if (!wide && hot && _dragItem == null && ImGuiNET.ImGui.BeginTooltip())
|
||||
{
|
||||
ImGuiNET.ImGui.TextUnformatted(name);
|
||||
ImGuiNET.ImGui.TextUnformatted(fill);
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
bool on = _pack == packId;
|
||||
bool dropHot = _dragItem != null && drop != DropKind.None && hot;
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(p, p + sz, dropHot ? DropHot : on ? Selected : hot ? CellHot : BtnFill, 3);
|
||||
dl.AddRect(p, p + sz, on || dropHot ? Teal : BtnBord, 3);
|
||||
var iconMin = new Vector2(p.X + 3, p.Y + (PackRowH - Icon) * 0.5f);
|
||||
if (iconObject != 0) DrawItemIcon(dl, iconObject, iconMin, Icon);
|
||||
else PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), glyph, iconMin, new Vector2(Icon, Icon), on ? Teal : Mute);
|
||||
if (wide)
|
||||
{
|
||||
float tx = p.X + Icon + 8;
|
||||
dl.PushClipRect(new Vector2(tx, p.Y), p + sz, true);
|
||||
dl.AddText(new Vector2(tx, p.Y + 3), on ? Teal : Text, name);
|
||||
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
|
||||
dl.AddText(f9, f9.FontSize * InventorySettingsStore.SizeFactor, new Vector2(tx, p.Y + PackRowH - f9.FontSize - 4), Mute, fill);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
if (drop != DropKind.None)
|
||||
{
|
||||
// Only the part inside the (scrolling) pack column counts: a row scrolled out of
|
||||
// view must not catch a drop over the search box or the zones.
|
||||
Vector2 wmin = ImGuiNET.ImGui.GetWindowPos(), wmax = wmin + ImGuiNET.ImGui.GetWindowSize();
|
||||
Vector2 min = Vector2.Max(p, wmin), max = Vector2.Min(p + sz, wmax);
|
||||
if (max.X > min.X && max.Y > min.Y)
|
||||
_targets.Add(new Target { Min = min, Max = max, Kind = drop, Id = packId, Name = dropName });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Grid ────────────────────────────────────────────────────────────
|
||||
|
||||
private void Grid(Vector2 pos, Vector2 size)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(3, 3));
|
||||
ImGuiNET.ImGui.BeginChild("##inv_grid", size, ImGuiChildFlags.AlwaysUseWindowPadding);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
|
||||
// Showing one pack: dropping on the grid moves the item into that pack.
|
||||
if (_pack != AllPacks && _pack != WornPacks && _builtFor?.PackOf(_pack) is InventoryPack shownPack)
|
||||
{
|
||||
Vector2 wmin = ImGuiNET.ImGui.GetWindowPos();
|
||||
_targets.Add(new Target { Min = wmin, Max = wmin + ImGuiNET.ImGui.GetWindowSize(), Kind = DropKind.Pack,
|
||||
Id = shownPack.Id, Name = shownPack.Name });
|
||||
}
|
||||
|
||||
float avail = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
int cols = Math.Max(1, (int)(avail / Cell));
|
||||
int rows = (_shown.Count + cols - 1) / cols;
|
||||
Vector2 o = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var content = new Vector2(cols * Cell, Math.Max(rows * Cell, 1));
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
|
||||
if (_shown.Count == 0)
|
||||
{
|
||||
dl.AddText(o + new Vector2(4, 4), Mute, _searchText.Length > 0 || _category != 0 ? "Nothing matches." : "Empty.");
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(avail, 20));
|
||||
}
|
||||
else
|
||||
{
|
||||
// One button over the whole grid: hover, click, double-click, right-click and
|
||||
// drag are worked out from the mouse position (no item per cell).
|
||||
ImGuiNET.ImGui.InvisibleButton("##cells", content, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
|
||||
bool hovered = ImGuiNET.ImGui.IsItemHovered();
|
||||
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
|
||||
int hoverIdx = -1;
|
||||
if (hovered)
|
||||
{
|
||||
int c = (int)((mouse.X - o.X) / Cell), r = (int)((mouse.Y - o.Y) / Cell);
|
||||
if (c >= 0 && c < cols && r >= 0 && r < rows)
|
||||
{
|
||||
int i = r * cols + c;
|
||||
if (i < _shown.Count) hoverIdx = i;
|
||||
}
|
||||
}
|
||||
InventoryItem? hot = hoverIdx >= 0 ? _shown[hoverIdx] : null;
|
||||
_hover = hot;
|
||||
|
||||
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
|
||||
{
|
||||
_selected = hot.Id;
|
||||
_pressItem = hot;
|
||||
_pressAt = mouse;
|
||||
}
|
||||
if (hot != null && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
|
||||
{
|
||||
_pressItem = null;
|
||||
Act(InventoryActionKind.Use, hot, 0, "", 0);
|
||||
}
|
||||
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
|
||||
{
|
||||
_selected = hot.Id;
|
||||
_ctxItem = hot;
|
||||
_openCtx = true;
|
||||
}
|
||||
if (_pressItem != null && _dragItem == null && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)
|
||||
&& Vector2.DistanceSquared(mouse, _pressAt) > 25)
|
||||
_dragItem = _pressItem;
|
||||
|
||||
// Visible rows only.
|
||||
Vector2 clipMin = ImGuiNET.ImGui.GetWindowPos(), clipMax = clipMin + ImGuiNET.ImGui.GetWindowSize();
|
||||
int firstRow = Math.Max(0, (int)((clipMin.Y - o.Y) / Cell));
|
||||
int lastRow = Math.Min(rows - 1, (int)((clipMax.Y - o.Y) / Cell));
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts
|
||||
for (int r = firstRow; r <= lastRow; r++)
|
||||
{
|
||||
for (int c = 0; c < cols; c++)
|
||||
{
|
||||
int i = r * cols + c;
|
||||
if (i >= _shown.Count) break;
|
||||
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;
|
||||
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)
|
||||
{
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(it.StackText);
|
||||
var tp = new Vector2(cmax.X - ts.X - 2, cmax.Y - ts.Y - 1);
|
||||
dl.AddText(tp + Vector2.One, StackShadow, it.StackText);
|
||||
dl.AddText(tp, StackCol, it.StackText);
|
||||
}
|
||||
if (sel) dl.AddRect(cmin, cmax, CellSel, 3, ImDrawFlags.None, 1.5f);
|
||||
else if (it.Wielder != 0) dl.AddRect(cmin, cmax, Amber, 3);
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
|
||||
/// <summary>An item's icon (with underlay and overlay) from the shared icon cache, or a placeholder.</summary>
|
||||
private static void DrawItemIcon(ImDrawListPtr dl, uint objectId, Vector2 min, float size, uint tint = 0xFFFFFFFF)
|
||||
{
|
||||
if (ScriptIcons.TryGet(ScriptIconKind.Object, objectId, out IntPtr tex))
|
||||
dl.AddImage(tex, min, min + new Vector2(size, size), Vector2.Zero, Vector2.One, tint);
|
||||
else
|
||||
dl.AddRectFilled(min, min + new Vector2(size, size), Placeholder, 2);
|
||||
}
|
||||
|
||||
// ── Zones: equip, drop, give ────────────────────────────────────────
|
||||
|
||||
private void Zones(InventoryView view, float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
InventoryTarget? target = InventoryModel.Target;
|
||||
InventoryItem? sel = SelectedItem(view);
|
||||
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,
|
||||
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 void Zone(string id, DropKind kind, string glyph, string label, Vector2 pos, Vector2 size, uint targetId,
|
||||
string targetName, bool enabled, InventoryItem? selected, string tip)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
|
||||
ImGuiNET.ImGui.SetItemTooltip(tip);
|
||||
bool dropHot = enabled && _dragItem != null && hot;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
uint fill = dropHot ? DropHot : _dragItem != null && enabled ? Selected : hot && enabled ? Lighten(BtnFill) : BtnFill;
|
||||
dl.AddRectFilled(pos, pos + size, fill, 3);
|
||||
dl.AddRect(pos, pos + size, dropHot || (_dragItem != null && enabled) ? Teal : BtnBord, 3);
|
||||
uint fg = enabled ? Text : Faded(Mute);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), glyph, pos + new Vector2(4, 0), new Vector2(18, size.Y), fg);
|
||||
dl.PushClipRect(pos, pos + size, true);
|
||||
dl.AddText(new Vector2(pos.X + 26, pos.Y + (size.Y - ImGuiNET.ImGui.GetFontSize()) * 0.5f), fg, label);
|
||||
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
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// ── Status row ──────────────────────────────────────────────────────
|
||||
|
||||
private void StatusRow(float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
StatusLine(p, w, StatusH, null);
|
||||
NextLine(p, StatusH);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The one action waiting for the server, a refusal, or how the last action ended; when
|
||||
/// there is nothing to say, the pyreals (<paramref name="idleView"/>, Classic) or a hint.
|
||||
/// </summary>
|
||||
private void StatusLine(Vector2 p, float w, float statusH, InventoryView? idleView)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
InventoryPending? pending = InventoryModel.Pending;
|
||||
InventoryResult? result = InventoryModel.LastResult;
|
||||
float ty = p.Y + (statusH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
dl.PushClipRect(p, p + new Vector2(w, statusH), true);
|
||||
if (pending != null)
|
||||
{
|
||||
int tenths = (int)((now - pending.StartedTicks) * 10 / Stopwatch.Frequency);
|
||||
int key = (int)(pending.ItemId * 31) ^ tenths ^ ((int)pending.Kind << 24)
|
||||
^ (pending.WaitingForGame ? (0x40000000 ^ pending.BusyWith.GetHashCode()) : 0);
|
||||
if (key != _statusKey)
|
||||
{
|
||||
_statusKey = key;
|
||||
string secs = " " + (tenths / 10.0).ToString("0.0", CultureInfo.InvariantCulture) + "s";
|
||||
// Held until the client's own item gate opens (the bot or another action has it).
|
||||
_statusText = pending.WaitingForGame
|
||||
? "Waiting for the game: " + pending.Label + " (busy with " + pending.BusyWith + ")" + secs
|
||||
: "Waiting for the server: " + pending.Label + secs;
|
||||
}
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.HourglassMedium, p, new Vector2(16, statusH), Amber);
|
||||
dl.AddText(new Vector2(p.X + 18, ty), Amber, _statusText);
|
||||
}
|
||||
else if (_refusal.Length > 0 && (now - _refusalAt) < Stopwatch.Frequency * 4)
|
||||
{
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Warning, p, new Vector2(16, statusH), Amber);
|
||||
dl.AddText(new Vector2(p.X + 18, ty), Amber, _refusal);
|
||||
}
|
||||
else if (result != null && (now - result.AtTicks) < Stopwatch.Frequency * 8)
|
||||
{
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), result.Ok ? PhosphorIcons.Check : PhosphorIcons.Warning,
|
||||
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 (idleView != null)
|
||||
{
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Coins, p, new Vector2(16, statusH), Amber);
|
||||
dl.AddText(new Vector2(p.X + 18, ty), Text, idleView.PyrealText);
|
||||
float pw = ImGuiNET.ImGui.CalcTextSize(idleView.PyrealText).X;
|
||||
dl.AddText(new Vector2(p.X + 22 + pw, ty), Mute, "pyreals");
|
||||
}
|
||||
else
|
||||
{
|
||||
dl.AddText(new Vector2(p.X + 2, ty), Faded(Mute), "Double-click to use. Drag to a pack, Equip, Drop or Give. Right-click for more.");
|
||||
}
|
||||
dl.PopClipRect();
|
||||
}
|
||||
|
||||
// ── Actions ─────────────────────────────────────────────────────────
|
||||
|
||||
private void Act(InventoryActionKind kind, InventoryItem item, uint target, string targetName, int amount)
|
||||
{
|
||||
var req = new InventoryRequest
|
||||
{
|
||||
Kind = kind, ItemId = item.Id, TargetId = target, TargetName = targetName, Amount = amount, ItemName = item.Name,
|
||||
};
|
||||
if (!InventoryModel.Request(req, out string why))
|
||||
{
|
||||
_refusal = why;
|
||||
_refusalAt = Stopwatch.GetTimestamp();
|
||||
}
|
||||
else
|
||||
{
|
||||
_refusal = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
private void DropOn(DropKind kind, uint targetId, string targetName, InventoryItem item)
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case DropKind.Pack:
|
||||
if (item.Container == targetId && item.Wielder == 0) return; // same pack: nothing to do
|
||||
if (item.RequiresPackSlot && targetId != InventoryModel.Current.PlayerId)
|
||||
{
|
||||
// A side pack has no pack slots (ACE: ContainerCapacity 0); the server would refuse.
|
||||
Refuse(item.Name + " uses a pack slot: it can only go in the main pack.");
|
||||
return;
|
||||
}
|
||||
Act(InventoryActionKind.Move, item, targetId, targetName, 0);
|
||||
break;
|
||||
case DropKind.PackSlots:
|
||||
if (!item.RequiresPackSlot)
|
||||
{
|
||||
Refuse("Only items that use a pack slot (foci) go there. Drop it on a pack to move it.");
|
||||
return;
|
||||
}
|
||||
if (item.Container == targetId && item.Wielder == 0) return; // already in the main pack
|
||||
Act(InventoryActionKind.Move, item, targetId, targetName, 0);
|
||||
break;
|
||||
case DropKind.Equip:
|
||||
if (item.Wielder != 0) return;
|
||||
Act(InventoryActionKind.Wield, item, 0, "", 0);
|
||||
break;
|
||||
case DropKind.Slot:
|
||||
if (item.Wielder != 0) return; // already worn (moving between slots isn't supported)
|
||||
if ((item.ValidLocations & targetId) == 0)
|
||||
{
|
||||
Refuse(item.Name + " doesn't go in the " + targetName + " slot.");
|
||||
return;
|
||||
}
|
||||
Act(InventoryActionKind.Wield, item, targetId, targetName, 0);
|
||||
break;
|
||||
case DropKind.Drop:
|
||||
Act(InventoryActionKind.Drop, item, 0, "", 0);
|
||||
break;
|
||||
case DropKind.Give:
|
||||
if (targetId != 0) Act(InventoryActionKind.Give, item, targetId, targetName, 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Refuse(string why)
|
||||
{
|
||||
_refusal = why;
|
||||
_refusalAt = Stopwatch.GetTimestamp();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Would <paramref name="pack"/> refuse <paramref name="item"/> (full, or no place for it)?
|
||||
/// ACE's rules (Container.TryAddToInventory): a pack-slot item takes one of the main pack's
|
||||
/// pack slots (a side pack has none); anything else takes an item slot.
|
||||
/// </summary>
|
||||
private static bool PackRefuses(InventoryView view, InventoryPack pack, InventoryItem item)
|
||||
{
|
||||
if (item.Container == pack.Id && item.Wielder == 0) return false; // already there
|
||||
if (item.RequiresPackSlot)
|
||||
return !pack.IsMain || Math.Max(0, view.Packs.Length - 1) + view.SlotItems.Length >= view.ContainerSlots;
|
||||
return pack.Used >= pack.Capacity;
|
||||
}
|
||||
|
||||
/// <summary>Mouse released during a drag: act on the target under it (collected this frame).</summary>
|
||||
private void FinishDrag()
|
||||
{
|
||||
if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left))
|
||||
{
|
||||
InventoryItem? item = _dragItem;
|
||||
_dragItem = null;
|
||||
_pressItem = null;
|
||||
if (item == null) return;
|
||||
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);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawDragGhost()
|
||||
{
|
||||
if (_dragItem == null) return;
|
||||
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);
|
||||
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
||||
}
|
||||
|
||||
// ── Tooltip ─────────────────────────────────────────────────────────
|
||||
|
||||
private void Tooltip()
|
||||
{
|
||||
InventoryItem? it = _hover;
|
||||
if (_dragItem != null || ImGuiNET.ImGui.IsPopupOpen("", ImGuiPopupFlags.AnyPopupId)) return;
|
||||
if (it == null)
|
||||
{
|
||||
// A pack cell, an empty paperdoll slot, the burden meter (Classic view).
|
||||
if (_hoverLabel == null) return;
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
if (ImGuiNET.ImGui.BeginTooltip())
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.TextUnformatted(_hoverLabel);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
if (_hoverLabel2 != null)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGuiNET.ImGui.TextUnformatted(_hoverLabel2);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
return;
|
||||
}
|
||||
if (!ReferenceEquals(it, _tipItem))
|
||||
{
|
||||
_tipItem = it;
|
||||
_tipBase = BaseLines(it);
|
||||
}
|
||||
InventoryTooltip? extra = InventoryModel.Tooltip;
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
if (ImGuiNET.ImGui.BeginTooltip())
|
||||
{
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetFontSize() * 24);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.TextUnformatted(it.Name);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
foreach (string line in _tipBase) ImGuiNET.ImGui.TextUnformatted(line);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
if (extra != null && extra.Id == it.Id)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
|
||||
foreach (string line in extra.Lines) ImGuiNET.ImGui.TextUnformatted(line);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
}
|
||||
|
||||
private static string[] BaseLines(InventoryItem it)
|
||||
{
|
||||
var lines = new List<string>(6);
|
||||
if (it.Stack > 1)
|
||||
lines.Add(it.MaxStack > 1 ? $"Stack {it.Stack:N0} of {it.MaxStack:N0}" : $"Stack {it.Stack:N0}");
|
||||
lines.Add($"Value {it.Value:N0} Burden {it.Burden:N0}");
|
||||
if (it.Workmanship > 0)
|
||||
lines.Add("Workmanship " + it.Workmanship.ToString("0.##", CultureInfo.InvariantCulture));
|
||||
if (it.Wielder != 0) lines.Add("Equipped");
|
||||
if (it.IsPack) lines.Add($"Pack: {it.ItemsCapacity} slots");
|
||||
if (it.RequiresPackSlot) lines.Add("Uses a pack slot (main pack only)");
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
// ── Context menu ────────────────────────────────────────────────────
|
||||
|
||||
private void ContextMenu(InventoryView view)
|
||||
{
|
||||
if (_openCtx)
|
||||
{
|
||||
_openCtx = false;
|
||||
ImGuiNET.ImGui.OpenPopup("##inv_ctx");
|
||||
}
|
||||
PushMenuStyle();
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##inv_ctx");
|
||||
if (!open) { PopMenuStyle(); return; }
|
||||
try
|
||||
{
|
||||
InventoryItem? it = _ctxItem;
|
||||
if (it == null) { ImGuiNET.ImGui.CloseCurrentPopup(); return; }
|
||||
bool idle = InventoryModel.Pending == null;
|
||||
ImGuiNET.ImGui.TextDisabled(it.Name);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Use", "double-click", false, idle))
|
||||
Act(InventoryActionKind.Use, it, 0, "", 0);
|
||||
if (it.Wielder == 0 && it.ValidLocations != 0
|
||||
&& ImGuiNET.ImGui.MenuItem("Equip", "", false, idle && InventoryModel.WieldAvailable))
|
||||
Act(InventoryActionKind.Wield, it, 0, "", 0);
|
||||
if (it.Stack > 1 && it.Wielder == 0 && ImGuiNET.ImGui.MenuItem("Split...", "", false, idle))
|
||||
{
|
||||
_splitItem = it;
|
||||
_splitAmount = Math.Max(1, it.Stack / 2);
|
||||
_splitTarget = it.Container;
|
||||
_openSplit = true;
|
||||
}
|
||||
if (ImGuiNET.ImGui.BeginMenu("Move to", idle))
|
||||
{
|
||||
foreach (InventoryPack p in view.Packs)
|
||||
{
|
||||
bool here = p.Id == it.Container && it.Wielder == 0;
|
||||
bool fits = !it.RequiresPackSlot || p.IsMain; // a focus goes in the main pack only
|
||||
if (ImGuiNET.ImGui.MenuItem(p.Name, p.FillText, here, !here && fits))
|
||||
Act(InventoryActionKind.Move, it, p.Id, p.Name, 0);
|
||||
}
|
||||
ImGuiNET.ImGui.EndMenu();
|
||||
}
|
||||
if (it.Wielder == 0 && ImGuiNET.ImGui.MenuItem("Drop", "", false, idle && InventoryModel.DropAvailable))
|
||||
Act(InventoryActionKind.Drop, it, 0, "", 0);
|
||||
InventoryTarget? target = InventoryModel.Target;
|
||||
if (target != null && it.Wielder == 0
|
||||
&& ImGuiNET.ImGui.MenuItem(target.MenuLabel, "", false, idle && InventoryModel.GiveAvailable))
|
||||
Act(InventoryActionKind.Give, it, target.Id, target.Name, 0);
|
||||
if (!idle)
|
||||
ImGuiNET.ImGui.TextDisabled("(an item action is waiting)");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
PopMenuStyle();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Split dialog ────────────────────────────────────────────────────
|
||||
|
||||
private void SplitDialog(InventoryView view)
|
||||
{
|
||||
if (_openSplit)
|
||||
{
|
||||
_openSplit = false;
|
||||
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always);
|
||||
ImGuiNET.ImGui.OpenPopup("##inv_split");
|
||||
}
|
||||
PushMenuStyle();
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##inv_split");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
if (!open) { PopMenuStyle(); return; }
|
||||
try
|
||||
{
|
||||
InventoryItem? it = _splitItem;
|
||||
// The stack may have changed or gone since the dialog opened: use the live copy.
|
||||
InventoryItem? live = it == null ? null : FindById(view, it.Id);
|
||||
if (live == null || live.Stack < 2)
|
||||
{
|
||||
ImGuiNET.ImGui.TextUnformatted("That stack is gone.");
|
||||
if (Button("##sp_close", "Close", ImGuiNET.ImGui.GetCursorScreenPos(), new Vector2(80, 22), Text, BtnFill))
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(80, 24));
|
||||
return;
|
||||
}
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.TextUnformatted(live.Name);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.TextUnformatted("Stack of " + live.StackText + ". Split off:");
|
||||
int max = live.Stack - 1;
|
||||
_splitAmount = Math.Clamp(_splitAmount, 1, max);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(200);
|
||||
ImGuiNET.ImGui.SliderInt("##sp_slider", ref _splitAmount, 1, max);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(200);
|
||||
ImGuiNET.ImGui.InputInt("##sp_input", ref _splitAmount, 1, 10);
|
||||
_splitAmount = Math.Clamp(_splitAmount, 1, max);
|
||||
|
||||
ImGuiNET.ImGui.TextUnformatted("Into:");
|
||||
InventoryPack? into = view.PackOf(_splitTarget);
|
||||
if (into == null) { _splitTarget = live.Container; into = view.PackOf(_splitTarget); }
|
||||
foreach (InventoryPack p in view.Packs)
|
||||
{
|
||||
if (ImGuiNET.ImGui.Selectable(p.Name + " (" + p.FillText + ")##sp" + p.Id.ToString(CultureInfo.InvariantCulture),
|
||||
p.Id == _splitTarget))
|
||||
_splitTarget = p.Id;
|
||||
}
|
||||
|
||||
bool idle = InventoryModel.Pending == null;
|
||||
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
|
||||
if (Button("##sp_ok", PhosphorIcons.Scissors + " Split", bp, new Vector2(96, 24), Teal, BtnFill, enabled: idle && into != null))
|
||||
{
|
||||
Act(InventoryActionKind.Split, live, _splitTarget, into?.Name ?? "", _splitAmount);
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
if (Button("##sp_cancel", "Cancel", bp + new Vector2(102, 0), new Vector2(80, 24), Text, BtnFill))
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(200, 0));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
PopMenuStyle();
|
||||
}
|
||||
}
|
||||
|
||||
private static InventoryItem? FindById(InventoryView view, uint id)
|
||||
{
|
||||
foreach (InventoryPack p in view.Packs)
|
||||
foreach (InventoryItem it in p.Items)
|
||||
if (it.Id == id) return it;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void PushMenuStyle()
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Header, Selected);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, Lighten(BtnFill));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
|
||||
}
|
||||
|
||||
private static void PopMenuStyle()
|
||||
{
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(7);
|
||||
}
|
||||
}
|
||||
250
src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs
Normal file
250
src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/ItemsFace.cs
|
||||
// ImGui face of the Items panel (UI/Panels/ItemsPanel.cs): weapons (name,
|
||||
// element, Del), consumables (name, type, Del), each with "Add Selected",
|
||||
// and mana stone tapping (on/off, keep count, min max-mana to tap).
|
||||
//
|
||||
// Edits change a private copy and save the whole payload (ItemsCommands,
|
||||
// pump thread). A newer snapshot replaces the copy; snapshots from before
|
||||
// the last save are ignored so an edit never flickers back.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using RynthCore.Engine.UI.Panels;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class ItemsFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Items";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(420, 520), new Vector2(340, 260), EdgeToEdge: true),
|
||||
() => new ItemsFace());
|
||||
|
||||
private static readonly uint OnBg = RynthTheme.Argb(0xFF104010), OnText = RynthTheme.Argb(0xFF33FF33);
|
||||
|
||||
private ItemsPanel.Payload _data = new();
|
||||
private long _seenVersion = -1, _savedAtVersion = -1;
|
||||
private readonly Picker _picker = new("##items_pick");
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.Items.Subscribe();
|
||||
UiSources.Items.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Items.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
TakeSnapshot();
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
|
||||
ImGuiNET.ImGui.BeginChild("##items_body", new Vector2(w, Math.Max(60, Remaining(origin, size))));
|
||||
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
|
||||
// Weapons
|
||||
Section("Weapons", bw);
|
||||
if (_data.Weapons.Count == 0) Empty("No weapons configured", bw);
|
||||
else
|
||||
{
|
||||
TableHeader("Element", bw);
|
||||
for (int i = 0; i < _data.Weapons.Count; i++)
|
||||
{
|
||||
ItemsPanel.WeaponEntry wpn = _data.Weapons[i];
|
||||
ImGuiNET.ImGui.PushID("w" + i);
|
||||
int r = Row(wpn.Name, wpn.Element, i, bw);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
if (r == 1)
|
||||
{
|
||||
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
|
||||
_picker.Open(at, ItemsCommands.Elements, Array.IndexOf(ItemsCommands.Elements, wpn.Element), e =>
|
||||
{
|
||||
wpn.Element = ItemsCommands.Elements[e];
|
||||
Save();
|
||||
}, 160);
|
||||
}
|
||||
else if (r == 2)
|
||||
{
|
||||
_data.Weapons.RemoveAt(i);
|
||||
Save();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
AddSelected("##add_weapon", PhosphorIcons.Plus + " Add Selected Weapon", "(select a weapon in inventory first)", ItemsCommands.AddSelectedWeapon);
|
||||
Divider(bw);
|
||||
|
||||
// Consumables
|
||||
Section("Consumable Items", bw);
|
||||
if (_data.Consumables.Count == 0) Empty("No consumables configured", bw);
|
||||
else
|
||||
{
|
||||
TableHeader("Type", bw);
|
||||
for (int i = 0; i < _data.Consumables.Count; i++)
|
||||
{
|
||||
ItemsPanel.ConsumableEntry c = _data.Consumables[i];
|
||||
ImGuiNET.ImGui.PushID("c" + i);
|
||||
int r = Row(c.Name, c.Type, i, bw);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
if (r == 1)
|
||||
{
|
||||
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
|
||||
_picker.Open(at, ItemsCommands.ConsumableTypes, Array.IndexOf(ItemsCommands.ConsumableTypes, c.Type), t =>
|
||||
{
|
||||
c.Type = ItemsCommands.ConsumableTypes[t];
|
||||
Save();
|
||||
}, 160);
|
||||
}
|
||||
else if (r == 2)
|
||||
{
|
||||
_data.Consumables.RemoveAt(i);
|
||||
Save();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
AddSelected("##add_consumable", PhosphorIcons.Plus + " Add Selected Consumable", "(select an item in inventory first)", ItemsCommands.AddSelectedConsumable);
|
||||
Divider(bw);
|
||||
|
||||
// Mana stone tapping
|
||||
Section("Mana Stone Tapping", bw);
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4);
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float ty = p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
dl.AddText(new Vector2(p.X, ty), Text, "Enable Tapping");
|
||||
float x = p.X + ImGuiNET.ImGui.CalcTextSize("Enable Tapping").X + 6;
|
||||
bool on = _data.EnableManaTapping;
|
||||
if (Button("##tap", on ? "ON" : "OFF", new Vector2(x, p.Y), new Vector2(50, 22), on ? OnText : Mute, on ? OnBg : BtnFill))
|
||||
{
|
||||
_data.EnableManaTapping = !on;
|
||||
Save();
|
||||
}
|
||||
x += 66;
|
||||
dl.AddText(new Vector2(x, ty), Text, "Keep count:");
|
||||
x += ImGuiNET.ImGui.CalcTextSize("Keep count:").X + 6;
|
||||
int keep = Spinner("##keep", _data.ManaStoneKeepCount, 1, 999, new Vector2(x, p.Y));
|
||||
if (keep != _data.ManaStoneKeepCount) { _data.ManaStoneKeepCount = keep; Save(); }
|
||||
NextLine(new Vector2(p.X - 4, p.Y - 4), 30);
|
||||
if (_data.EnableManaTapping)
|
||||
{
|
||||
p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 0);
|
||||
dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, "Min MaxMana to tap:");
|
||||
float sx = p.X + ImGuiNET.ImGui.CalcTextSize("Min MaxMana to tap:").X + 6;
|
||||
int min = Spinner("##minmana", _data.ManaTapMinMana, 100, 99999, new Vector2(sx, p.Y));
|
||||
if (min != _data.ManaTapMinMana) { _data.ManaTapMinMana = min; Save(); }
|
||||
NextLine(new Vector2(p.X - 4, p.Y), 28);
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
End(origin, size);
|
||||
_picker.Draw();
|
||||
}
|
||||
|
||||
private void TakeSnapshot()
|
||||
{
|
||||
var snap = UiSources.Items.Current;
|
||||
if (snap == null || snap.Version == _seenVersion || snap.Version <= _savedAtVersion) return;
|
||||
_seenVersion = snap.Version;
|
||||
_data = snap.Value.ParseCopy();
|
||||
}
|
||||
|
||||
private void Save()
|
||||
{
|
||||
_savedAtVersion = UiSources.Items.Current?.Version ?? _savedAtVersion;
|
||||
ItemsCommands.SetJson(ItemsCommands.Serialize(_data));
|
||||
}
|
||||
|
||||
// ── Pieces ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void Section(string title, float w)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
float h = bold.FontSize + 8;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(p, p + new Vector2(w, h), Selected);
|
||||
dl.AddText(bold, bold.FontSize, p + new Vector2(8, 4), Amber, title);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, h));
|
||||
}
|
||||
|
||||
private static void TableHeader(string column, float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(p, p + new Vector2(w, 22), Selected);
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
float ty = p.Y + (22 - bold.FontSize) * 0.5f;
|
||||
dl.AddText(bold, bold.FontSize, new Vector2(p.X + 6, ty), Text, "Item Name");
|
||||
dl.AddText(bold, bold.FontSize, new Vector2(p.X + w - 146 + 6, ty), Text, column);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
|
||||
}
|
||||
|
||||
private static void Empty(string message, float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(p, p + new Vector2(w, 22), RowAlt);
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(8, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, message);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
|
||||
}
|
||||
|
||||
/// <summary>Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0.</summary>
|
||||
private static int Row(string name, string value, int index, float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(p, p + new Vector2(w, 24), index % 2 == 0 ? RowAlt : PanelBg);
|
||||
float nameW = w - 146;
|
||||
dl.PushClipRect(p, p + new Vector2(nameW, 24), true);
|
||||
dl.AddText(new Vector2(p.X + 6, p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, name);
|
||||
dl.PopClipRect();
|
||||
int result = 0;
|
||||
if (Button("##pick", value, new Vector2(p.X + nameW + 2, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1;
|
||||
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(p.X + nameW + 102, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Remove");
|
||||
NextLine(p, 24);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void AddSelected(string id, string label, string hint, Action onClick)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4);
|
||||
float bw = ButtonWidth(label) + 4;
|
||||
if (Button(id, label, p, new Vector2(bw, 24), Teal, BtnFill)) onClick();
|
||||
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(f9, f9.FontSize, new Vector2(p.X + bw + 8, p.Y + (24 - f9.FontSize) * 0.5f), Mute, hint);
|
||||
NextLine(new Vector2(p.X - 4, p.Y - 4), 32);
|
||||
}
|
||||
|
||||
private static void Divider(float w)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
|
||||
Separator(w);
|
||||
}
|
||||
|
||||
/// <summary>[-] value [+]; returns the new value (same when nothing was clicked).</summary>
|
||||
private static int Spinner(string id, int value, int min, int max, Vector2 pos)
|
||||
{
|
||||
int v = value;
|
||||
ImGuiNET.ImGui.PushID(id);
|
||||
if (IconButton("##dec", PhosphorIcons.Minus, pos, new Vector2(22, 22), Teal, BtnFill)) v = Math.Max(min, v - 1);
|
||||
string text = v.ToString(CultureInfo.InvariantCulture);
|
||||
float tw = ImGuiNET.ImGui.CalcTextSize(text).X;
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(pos.X + 24 + (60 - tw) * 0.5f, pos.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, text);
|
||||
if (IconButton("##inc", PhosphorIcons.Plus, new Vector2(pos.X + 86, pos.Y), new Vector2(22, 22), Teal, BtnFill)) v = Math.Min(max, v + 1);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
return v;
|
||||
}
|
||||
}
|
||||
1192
src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs
Normal file
1192
src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs
Normal file
File diff suppressed because it is too large
Load diff
577
src/RynthCore.Engine/ImGui/Panels/LuaFace.cs
Normal file
577
src/RynthCore.Engine/ImGui/Panels/LuaFace.cs
Normal file
|
|
@ -0,0 +1,577 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/LuaFace.cs
|
||||
// ImGui face of the Lua panel. Two layouts, picked by the payload:
|
||||
//
|
||||
// RynthLua v2 (ScriptInfos present), tabs "Scripts" | "Editor", and on the
|
||||
// right "N running · RynthAi: loaded / not loaded":
|
||||
// Scripts one row per script: running dot, name, description, autostart
|
||||
// (Off / global / this character), Run|Stop, Restart. Click a row
|
||||
// to select it; below, the selected script's state, "Open in
|
||||
// editor", its console (Copy, Clear) and a line that runs Lua
|
||||
// inside it (execin).
|
||||
// Editor status + Run/Stop for the editor's script (the name box, else
|
||||
// "editor"), name + Save/New/Delete, the coloured editor
|
||||
// (CodeEditor, Lua) and the selected script's console.
|
||||
// Old single-script payload (RynthAi's exports) or no plugin: the v1 face,
|
||||
// status + Run/Stop, script buttons (click to open), name row, editor,
|
||||
// console; "Lua: RynthLua not connected" until a plugin answers.
|
||||
//
|
||||
// Data: UiSources.Lua (hub) and LuaCommands. The editor takes a script when
|
||||
// the plugin reports a new load (LoadSeq); on first open it restores the
|
||||
// plugin's last script only if the editor is empty. Text leaves the editor
|
||||
// only on Run/Save. The payload's Console is the selected script's.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class LuaFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Lua";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(420, 560), new Vector2(380, 360), EdgeToEdge: true, GripInBody: true),
|
||||
() => new LuaFace());
|
||||
|
||||
private static readonly uint ConsoleBg = RynthTheme.Argb(0xFF05090D), DotOff = RynthTheme.Argb(0xFF4D5A66);
|
||||
|
||||
private const string NotConnected = "Lua: RynthLua not connected";
|
||||
/// <summary>RynthLua's description for a running script that has no file (the editor, /lua exec).</summary>
|
||||
private const string NotSaved = "(not saved)";
|
||||
private const float RowH = 26;
|
||||
|
||||
private static readonly string[] AutoCodes = { "none", "global", "character" };
|
||||
private static readonly string[] AutoItems = { "Off", "Every character (global)", "This character" };
|
||||
|
||||
private LuaPayload? _data;
|
||||
private long _seenVersion = -1;
|
||||
private int _lastLoadSeq = -1, _lastConsoleSeq = -1;
|
||||
private string _lastSelected = string.Empty;
|
||||
private bool _firstFetch = true, _scrollConsole;
|
||||
private string _status = NotConnected;
|
||||
private bool _running;
|
||||
private string _note = string.Empty; // local hint ("Type a script name first.")
|
||||
private bool _editorTab;
|
||||
private string _editorSelectSent = string.Empty; // Editor tab: last "select" sent for its script
|
||||
private bool _focusExec;
|
||||
|
||||
private readonly byte[] _name = new byte[128];
|
||||
private readonly byte[] _exec = new byte[1024];
|
||||
private readonly Picker _picker = new("##lua_pick");
|
||||
private CodeEditor? _editor;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.Lua.Subscribe();
|
||||
UiSources.Lua.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
UiSources.Lua.Unsubscribe();
|
||||
_editor?.Dispose();
|
||||
_editor = null;
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
_editor ??= new CodeEditor("##lua_source", CodeLanguage.Lua, CodeEditor.RynthPalette());
|
||||
TakeSnapshot();
|
||||
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
LuaPayload? d = _data;
|
||||
if (d?.ScriptInfos is { } infos)
|
||||
{
|
||||
Header(w, d);
|
||||
if (_editorTab) EditorView(w, origin, size, d, infos);
|
||||
else ScriptsView(w, origin, size, d, infos);
|
||||
}
|
||||
else
|
||||
LegacyView(w, origin, size);
|
||||
End(origin, size);
|
||||
_picker.Draw();
|
||||
}
|
||||
|
||||
private void TakeSnapshot()
|
||||
{
|
||||
var snap = UiSources.Lua.Current;
|
||||
if (snap == null)
|
||||
{
|
||||
// Plugins unloaded (RL): back to "not connected" until one answers again.
|
||||
if (_data != null)
|
||||
{
|
||||
_data = null;
|
||||
_seenVersion = -1;
|
||||
_running = false;
|
||||
_status = NotConnected;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (snap.Version == _seenVersion) return;
|
||||
_seenVersion = snap.Version;
|
||||
LuaPayload d = _data = snap.Value;
|
||||
|
||||
_running = d.Running;
|
||||
_status = d.Running
|
||||
? $"Running: {(d.ScriptName.Length > 0 ? d.ScriptName : "(editor)")}"
|
||||
: d.Status.Length > 0 ? d.Status : "Lua: idle";
|
||||
|
||||
// A newly loaded script goes into the editor; on first open only if it's empty.
|
||||
if (d.LoadSeq != _lastLoadSeq)
|
||||
{
|
||||
bool take = !_firstFetch || _editor!.GetText().Length == 0;
|
||||
_lastLoadSeq = d.LoadSeq;
|
||||
if (take)
|
||||
{
|
||||
_editor!.SetText(d.LoadedText);
|
||||
WriteUtf8(_name, d.LoadedName);
|
||||
}
|
||||
}
|
||||
string selected = d.Selected ?? string.Empty;
|
||||
if (d.ConsoleSeq != _lastConsoleSeq || selected != _lastSelected)
|
||||
{
|
||||
_lastConsoleSeq = d.ConsoleSeq;
|
||||
_lastSelected = selected;
|
||||
_scrollConsole = true;
|
||||
_note = string.Empty;
|
||||
}
|
||||
_firstFetch = false;
|
||||
}
|
||||
|
||||
private const string ScriptsTab = PhosphorIcons.Files + " Scripts", EditorTab = PhosphorIcons.PencilSimple + " Editor";
|
||||
private const string RunLabel = PhosphorIcons.Play + " Run", StopLabel = PhosphorIcons.Stop + " Stop",
|
||||
RestartLabel = PhosphorIcons.ArrowCounterClockwise + " Restart";
|
||||
|
||||
// ── v2: header ───────────────────────────────────────────────────────
|
||||
|
||||
// [Scripts][Editor] N running · RynthAi: loaded
|
||||
private void Header(float w, LuaPayload d)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float h = 24;
|
||||
float sw = ButtonWidth(ScriptsTab) + 4, ew = ButtonWidth(EditorTab) + 4;
|
||||
if (Button("##tab_scripts", ScriptsTab, p, new Vector2(sw, h), _editorTab ? Text : Teal, _editorTab ? BtnFill : Selected))
|
||||
_editorTab = false;
|
||||
if (Button("##tab_editor", EditorTab, new Vector2(p.X + sw + 2, p.Y), new Vector2(ew, h), _editorTab ? Teal : Text, _editorTab ? Selected : BtnFill))
|
||||
_editorTab = true;
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
bool ai = d.RynthAi == true;
|
||||
string run = d.RunningCount == 1 ? "1 running" : $"{d.RunningCount} running";
|
||||
const string sep = " · ";
|
||||
string aiText = ai ? "RynthAi: loaded" : "RynthAi: not loaded";
|
||||
float runW = ImGuiNET.ImGui.CalcTextSize(run).X, sepW = ImGuiNET.ImGui.CalcTextSize(sep).X, aiW = ImGuiNET.ImGui.CalcTextSize(aiText).X;
|
||||
float left = p.X + sw + ew + 10, right = p.X + w;
|
||||
float x = Math.Max(left, right - runW - sepW - aiW);
|
||||
float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
dl.PushClipRect(new Vector2(left, p.Y), new Vector2(right, p.Y + h), true);
|
||||
dl.AddText(new Vector2(x, ty), d.RunningCount > 0 ? Green : Mute, run);
|
||||
dl.AddText(new Vector2(x + runW, ty), Mute, sep);
|
||||
dl.AddText(new Vector2(x + runW + sepW, ty), ai ? Green : Amber, aiText);
|
||||
dl.PopClipRect();
|
||||
if (ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x + runW + sepW, p.Y), new Vector2(right, p.Y + h)))
|
||||
ImGuiNET.ImGui.SetTooltip(ai
|
||||
? "RynthAi's script interface is there: scripts can use its macro, nav and meta features."
|
||||
: "RynthAi isn't loaded (or is too old): scripts' RynthAi calls won't work.");
|
||||
NextLine(p, h + 2);
|
||||
}
|
||||
|
||||
// ── v2: Scripts tab ──────────────────────────────────────────────────
|
||||
|
||||
private void ScriptsView(float w, Vector2 origin, Vector2 size, LuaPayload d, List<LuaScriptInfo> infos)
|
||||
{
|
||||
string sel = d.Selected ?? string.Empty;
|
||||
ScriptList(w, Remaining(origin, size), infos, sel);
|
||||
LuaScriptInfo? si = Find(infos, sel);
|
||||
SelectedRow(w, d, sel, si);
|
||||
|
||||
// Console, then the exec line: Dummy+header (30) + child + spacing (4) + line (22).
|
||||
float consoleH = Math.Max(40, Remaining(origin, size) - 56);
|
||||
Console(w, consoleH, sel.Length > 0 ? "Console · " + sel : "Console");
|
||||
ExecRow(w, sel, si?.Running == true);
|
||||
}
|
||||
|
||||
private void ScriptList(float w, float avail, List<LuaScriptInfo> infos, string selected)
|
||||
{
|
||||
int n = infos.Count;
|
||||
float listMax = Math.Max(RowH * 2 + 4, avail * 0.42f);
|
||||
float listH = Math.Clamp(Math.Max(1, n) * RowH + 4, RowH + 4, listMax);
|
||||
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
|
||||
ImGuiNET.ImGui.BeginChild("##lua_list", new Vector2(w, listH), ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
float rw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
if (n == 0)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(8, (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute,
|
||||
"No scripts yet: write one in the Editor tab and Save.");
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(rw, RowH));
|
||||
}
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
ScriptRow(infos[i], i, rw, selected);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
}
|
||||
|
||||
// (dot) Name description ........ [Auto: off] [Run] [Restart]
|
||||
private void ScriptRow(LuaScriptInfo info, int index, float w, string selected)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
bool isSel = info.Name.Equals(selected, StringComparison.OrdinalIgnoreCase);
|
||||
bool notSaved = IsNotSaved(info);
|
||||
const float autoW = 74, runW = 50, restartW = 64, gap = 3;
|
||||
float nameW = Math.Max(40, w - (autoW + runW + restartW + gap * 3 + 2));
|
||||
|
||||
dl.AddRectFilled(p, p + new Vector2(w, RowH), isSel ? Selected : index % 2 == 0 ? RowAlt : PanelBg);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(nameW, RowH)) && !isSel)
|
||||
LuaCommands.Send("select", info.Name);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
{
|
||||
if (!isSel) dl.AddRectFilled(p, p + new Vector2(nameW, RowH), BtnFill);
|
||||
ImGuiNET.ImGui.SetTooltip(RowTooltip(info, notSaved));
|
||||
}
|
||||
if (isSel) dl.AddRectFilled(p, p + new Vector2(2, RowH), Teal);
|
||||
|
||||
float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
dl.AddCircleFilled(new Vector2(p.X + 11, p.Y + RowH * 0.5f), 4, info.Running ? Green : DotOff);
|
||||
dl.PushClipRect(p, p + new Vector2(nameW - 4, RowH), true);
|
||||
dl.AddText(new Vector2(p.X + 21, ty), isSel ? Teal : Text, info.Name);
|
||||
if (info.Description.Length > 0)
|
||||
dl.AddText(new Vector2(p.X + 21 + ImGuiNET.ImGui.CalcTextSize(info.Name).X + 8, ty), Faded(Mute), info.Description);
|
||||
dl.PopClipRect();
|
||||
|
||||
float x = p.X + nameW, by = p.Y + 3, bh = RowH - 6;
|
||||
bool auto = info.Autostart is "global" or "character";
|
||||
if (Button("##auto", AutoLabel(info.Autostart), new Vector2(x, by), new Vector2(autoW, bh), auto ? Teal : Mute, BtnFill, enabled: !notSaved))
|
||||
{
|
||||
string name = info.Name;
|
||||
// Before login there's no character to autostart for: only off / global.
|
||||
string[] items = _data?.LoggedIn == false ? AutoItems[..2] : AutoItems;
|
||||
_picker.Open(new Vector2(x, by + bh + 2), items, Array.IndexOf(AutoCodes, info.Autostart),
|
||||
k => LuaCommands.Send("autostart", name, AutoCodes[k]), 190);
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(notSaved
|
||||
? "Save it to a file to autostart it."
|
||||
: "Start at login: off, on every character (global), or on this character only.");
|
||||
x += autoW + gap;
|
||||
if (info.Running)
|
||||
{
|
||||
if (Button("##run", StopLabel, new Vector2(x, by), new Vector2(runW, bh), Text, StopBg))
|
||||
LuaCommands.Send("stopScript", info.Name);
|
||||
}
|
||||
else if (Button("##run", RunLabel, new Vector2(x, by), new Vector2(runW, bh), Text, StartBg, enabled: !notSaved))
|
||||
LuaCommands.Send("start", info.Name);
|
||||
x += runW + gap;
|
||||
if (Button("##restart", RestartLabel, new Vector2(x, by), new Vector2(restartW, bh), Text, BtnFill, enabled: info.Running && !notSaved))
|
||||
LuaCommands.Send("restart", info.Name);
|
||||
ImGuiNET.ImGui.SetItemTooltip(notSaved ? "Not saved: run it again from the Editor." : "Stop it and start it again from its file.");
|
||||
NextLine(p, RowH);
|
||||
}
|
||||
|
||||
private static bool IsNotSaved(LuaScriptInfo info) => info.Transient || info.Description == NotSaved;
|
||||
|
||||
private static string RowTooltip(LuaScriptInfo info, bool notSaved)
|
||||
{
|
||||
string kind = notSaved ? "Not saved (the editor or /lua exec)"
|
||||
: info.IsFolder ? $"Folder script ({info.Name}\\index.lua)" : $"Single file ({info.Name}.lua)";
|
||||
string desc = notSaved || info.Description.Length == 0 ? string.Empty : info.Description + "\n";
|
||||
return $"{info.Name}\n{desc}{kind}\nClick to show its console.";
|
||||
}
|
||||
|
||||
private static string AutoLabel(string autostart) => autostart switch
|
||||
{
|
||||
"global" => "Auto: all",
|
||||
"character" => "Auto: char",
|
||||
_ => "Auto: off",
|
||||
};
|
||||
|
||||
// name running | stopped (status) [Open in editor]
|
||||
private void SelectedRow(float w, LuaPayload d, string sel, LuaScriptInfo? si)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float h = 22;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
if (sel.Length == 0)
|
||||
{
|
||||
dl.AddText(p + new Vector2(0, (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Click a script to see its console.");
|
||||
NextLine(p, h);
|
||||
return;
|
||||
}
|
||||
const string open = PhosphorIcons.PencilSimple + " Open in editor";
|
||||
float bw = ButtonWidth(open);
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
ImGuiNET.ImGui.PushFont(bold);
|
||||
float nameW = ImGuiNET.ImGui.CalcTextSize(sel).X;
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
bool running = si?.Running == true;
|
||||
string state = running ? "running"
|
||||
: d.ScriptName.Equals(sel, StringComparison.OrdinalIgnoreCase) && d.Status.Length > 0 ? d.Status : "stopped";
|
||||
dl.PushClipRect(p, p + new Vector2(w - bw - 6, h), true);
|
||||
dl.AddText(bold, bold.FontSize, p + new Vector2(0, (h - bold.FontSize) * 0.5f), Teal, sel);
|
||||
dl.AddText(p + new Vector2(nameW + 10, (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), running ? Green : Amber, state);
|
||||
dl.PopClipRect();
|
||||
bool canOpen = si != null && !IsNotSaved(si);
|
||||
if (Button("##open", open, new Vector2(p.X + w - bw, p.Y), new Vector2(bw, h), Text, BtnFill, enabled: canOpen))
|
||||
{
|
||||
LuaCommands.Send("load", sel);
|
||||
_editorTab = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(canOpen
|
||||
? (si!.IsFolder ? "Edit its index.lua in the Editor tab." : "Edit it in the Editor tab.")
|
||||
: "It has no file to open.");
|
||||
NextLine(p, h);
|
||||
}
|
||||
|
||||
// [Lua to run inside <script>...] [Exec]
|
||||
private void ExecRow(float w, string sel, bool canExec)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float bw = 50;
|
||||
string hint = sel.Length == 0 ? "Select a script to run code in it"
|
||||
: canExec ? $"Lua to run inside {sel} (Enter)" : $"Start {sel} to run code in it";
|
||||
if (_focusExec)
|
||||
{
|
||||
ImGuiNET.ImGui.SetKeyboardFocusHere();
|
||||
_focusExec = false;
|
||||
}
|
||||
// The row sits on the body's bottom edge: it stops short of the resize grip (GripInBody).
|
||||
float grip = ImGuiPanelHost.BodyGripReserve;
|
||||
bool enter = TextBox("##lua_exec", _exec, p, w - bw - 4 - grip, hint, out _, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool click = Button("##exec", "Exec", new Vector2(p.X + w - bw - grip, p.Y), new Vector2(bw, 22), Text, BtnFill, enabled: canExec);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Runs the line inside the selected script: its globals, its state.");
|
||||
if ((enter || click) && canExec)
|
||||
{
|
||||
string code = Utf8(_exec).Trim();
|
||||
if (code.Length > 0)
|
||||
{
|
||||
LuaCommands.Send("execin", sel, code);
|
||||
_exec[0] = 0;
|
||||
}
|
||||
_focusExec = enter; // Enter leaves the box; keep typing in it
|
||||
}
|
||||
NextLine(p, 22);
|
||||
}
|
||||
|
||||
// ── v2: Editor tab ───────────────────────────────────────────────────
|
||||
|
||||
private void EditorView(float w, Vector2 origin, Vector2 size, LuaPayload d, List<LuaScriptInfo> infos)
|
||||
{
|
||||
// RynthLua runs the editor text as a script named by the name box, else "editor".
|
||||
string edName = Utf8(_name).Trim();
|
||||
string runName = edName.Length > 0 ? edName : "editor";
|
||||
LuaScriptInfo? ei = Find(infos, runName);
|
||||
bool running = ei?.Running == true;
|
||||
// Always say which script the editor holds: the Scripts tab's selection doesn't change it
|
||||
// (only "Open in editor" does), so the name here is the one Run/Save act on.
|
||||
string editing = "Editing: " + runName + (_editor?.IsDirty == true ? " (unsaved)" : "");
|
||||
string status = running ? editing + " · running"
|
||||
: d.ScriptName.Equals(runName, StringComparison.OrdinalIgnoreCase) && d.Status.Length > 0 ? editing + " · " + d.Status
|
||||
: editing;
|
||||
|
||||
// The console below follows the editor's script, not whatever was last clicked on the
|
||||
// Scripts tab. Select it once per change of name (selecting also moves the Scripts tab).
|
||||
if (ei != null && !runName.Equals(d.Selected ?? string.Empty, StringComparison.OrdinalIgnoreCase)
|
||||
&& !runName.Equals(_editorSelectSent, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
LuaCommands.Send("select", ei.Name);
|
||||
_editorSelectSent = runName;
|
||||
}
|
||||
else if (runName.Equals(d.Selected ?? string.Empty, StringComparison.OrdinalIgnoreCase))
|
||||
_editorSelectSent = string.Empty;
|
||||
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
const float bw = 64;
|
||||
float statusW = w - 2 * (bw + 4);
|
||||
dl.PushClipRect(p, p + new Vector2(statusW, 24), true);
|
||||
dl.AddText(bold, bold.FontSize, p + new Vector2(0, (24 - bold.FontSize) * 0.5f), running ? Green : Amber, status);
|
||||
dl.PopClipRect();
|
||||
if (Button("##run", RunLabel, new Vector2(p.X + statusW + 4, p.Y), new Vector2(bw, 24), Text, StartBg))
|
||||
LuaCommands.Send("run", edName, _editor?.GetText() ?? string.Empty);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Run the editor's text as " + runName + " (replaces a running copy).");
|
||||
if (Button("##stop", StopLabel, new Vector2(p.X + statusW + bw + 8, p.Y), new Vector2(bw, 24), Text, StopBg, enabled: running))
|
||||
LuaCommands.Send("stopScript", runName);
|
||||
NextLine(p, 24);
|
||||
|
||||
bool folder = ei?.IsFolder == true;
|
||||
NameRow(w, canDelete: !folder, saveTip: folder ? "Saves its index.lua." : null,
|
||||
deleteTip: folder ? "Folder scripts are deleted in Explorer." : "Renames it to .lua.bak.");
|
||||
EditorAndConsole(w, origin, size, 120, ei != null ? "Console · " + ei.Name
|
||||
: d.Selected is { Length: > 0 } s ? "Console · " + s : "Console");
|
||||
}
|
||||
|
||||
// ── v1: old single-script payload / not connected ────────────────────
|
||||
|
||||
private void LegacyView(float w, Vector2 origin, Vector2 size)
|
||||
{
|
||||
TopRow(w);
|
||||
Scripts(w);
|
||||
NameRow(w, canDelete: true, saveTip: null, deleteTip: null);
|
||||
EditorAndConsole(w, origin, size, 150, "Console");
|
||||
}
|
||||
|
||||
// Status | Run Stop
|
||||
private void TopRow(float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
const float bw = 64;
|
||||
float statusW = w - 2 * (bw + 4);
|
||||
dl.PushClipRect(p, p + new Vector2(statusW, 24), true);
|
||||
dl.AddText(bold, bold.FontSize, p + new Vector2(0, (24 - bold.FontSize) * 0.5f), _running ? Green : Amber, _status);
|
||||
dl.PopClipRect();
|
||||
if (Button("##run", RunLabel, new Vector2(p.X + statusW + 4, p.Y), new Vector2(bw, 24), Text, StartBg))
|
||||
LuaCommands.Send("run", Utf8(_name).Trim(), _editor?.GetText() ?? string.Empty);
|
||||
if (Button("##stop", StopLabel, new Vector2(p.X + statusW + bw + 8, p.Y), new Vector2(bw, 24), Text, StopBg))
|
||||
LuaCommands.Send("stop");
|
||||
NextLine(p, 24);
|
||||
}
|
||||
|
||||
// "Scripts (click to open):" then one button per script, wrapping.
|
||||
private void Scripts(float w)
|
||||
{
|
||||
Label("Scripts (click to open):", Mute);
|
||||
var scripts = _data?.Scripts;
|
||||
if (scripts == null || scripts.Count == 0)
|
||||
{
|
||||
Label("(none yet: write one and Save)", Mute);
|
||||
return;
|
||||
}
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x = start.X, y = start.Y;
|
||||
for (int i = 0; i < scripts.Count; i++)
|
||||
{
|
||||
string s = scripts[i];
|
||||
float bw = ButtonWidth(s);
|
||||
if (x > start.X && x + bw > start.X + w) { x = start.X; y += 26; }
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
if (Button("##s", s, new Vector2(x, y), new Vector2(bw, 22), Text, BtnFill))
|
||||
LuaCommands.Send("load", s);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
x += bw + 4;
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(start.X, y + 22));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
// ── Shared pieces ────────────────────────────────────────────────────
|
||||
|
||||
// [name] Save New Delete
|
||||
private void NameRow(float w, bool canDelete, string? saveTip, string? deleteTip)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float bw = 58;
|
||||
float boxW = w - 3 * (bw + 4);
|
||||
TextBox("##lua_name", _name, p, boxW, "Script name...", out _);
|
||||
|
||||
float x = p.X + boxW + 4;
|
||||
if (Button("##save", PhosphorIcons.FloppyDisk + " Save", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill))
|
||||
{
|
||||
string name = Utf8(_name).Trim();
|
||||
if (name.Length == 0) _note = "Type a script name first.";
|
||||
else
|
||||
{
|
||||
LuaCommands.Send("save", name, _editor?.GetText() ?? string.Empty);
|
||||
_editor?.MarkClean();
|
||||
}
|
||||
}
|
||||
if (saveTip != null) ImGuiNET.ImGui.SetItemTooltip(saveTip);
|
||||
x += bw + 4;
|
||||
if (Button("##new", PhosphorIcons.FilePlus + " New", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill))
|
||||
{
|
||||
_editor?.SetText(string.Empty);
|
||||
Array.Clear(_name);
|
||||
}
|
||||
x += bw + 4;
|
||||
if (Button("##delete", PhosphorIcons.Trash + " Delete", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill, enabled: canDelete))
|
||||
{
|
||||
string name = Utf8(_name).Trim();
|
||||
if (name.Length > 0) LuaCommands.Send("delete", name);
|
||||
}
|
||||
if (deleteTip != null) ImGuiNET.ImGui.SetItemTooltip(deleteTip);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
// The editor takes what the console leaves.
|
||||
private void EditorAndConsole(float w, Vector2 origin, Vector2 size, float consoleH, string consoleTitle)
|
||||
{
|
||||
// The console below scrolls: the pair ends above the resize grip (GripInBody).
|
||||
float editorH = Math.Max(80, Remaining(origin, size) - consoleH - 34 - GripOverlap());
|
||||
if (!CodeEditor.Available)
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE04848), "The script editor needs the new cimgui.dll (a full RynthCore deploy).");
|
||||
else
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Code12));
|
||||
_editor!.Render(new Vector2(w, editorH));
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
Console(w, consoleH, consoleTitle);
|
||||
}
|
||||
|
||||
// Console [Copy] [Clear], then the output (green, wrapped, follows new lines).
|
||||
private void Console(float w, float height, string title)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.PushClipRect(p, p + new Vector2(w - 122, 22), true);
|
||||
dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, title);
|
||||
dl.PopClipRect();
|
||||
if (Button("##copy", PhosphorIcons.Copy + " Copy", new Vector2(p.X + w - 116, p.Y), new Vector2(56, 22), Text, BtnFill))
|
||||
ImGuiNET.ImGui.SetClipboardText(_data?.Console ?? string.Empty);
|
||||
if (Button("##clear", PhosphorIcons.Eraser + " Clear", new Vector2(p.X + w - 56, p.Y), new Vector2(56, 22), Text, BtnFill))
|
||||
LuaCommands.Send("clearConsole");
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24));
|
||||
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, ConsoleBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
|
||||
ImGuiNET.ImGui.BeginChild("##lua_console", new Vector2(w, height), ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono10));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Green);
|
||||
ImGuiNET.ImGui.PushTextWrapPos(0);
|
||||
string text = _data?.Console ?? string.Empty;
|
||||
if (text.Length > 0) ImGuiNET.ImGui.TextUnformatted(text);
|
||||
if (_note.Length > 0) ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "[panel] " + _note);
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
if (_scrollConsole)
|
||||
{
|
||||
ImGuiNET.ImGui.SetScrollHereY(1f);
|
||||
_scrollConsole = false;
|
||||
}
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
}
|
||||
|
||||
private static LuaScriptInfo? Find(List<LuaScriptInfo> infos, string name)
|
||||
{
|
||||
if (name.Length == 0) return null;
|
||||
foreach (LuaScriptInfo i in infos)
|
||||
if (i.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
457
src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs
Normal file
457
src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs
Normal file
|
|
@ -0,0 +1,457 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/MetaFace.Schedule.cs
|
||||
// The Meta panel's Schedule view: RynthAi's Meta Manager, which loads a meta
|
||||
// when a timer runs out (RynthSuite Docs/META_MANAGER.md).
|
||||
//
|
||||
// [x Manager] Poll [5] min [poll now] Wait [60] s Gap [30] s [x While stopped]
|
||||
// 34 quests, polled 2m ago . last: farm.af (quest x ready)
|
||||
// # [on] [up][dn] [edit][del] when quest x ready -> farm.af ready | 12m 30s
|
||||
// ...
|
||||
// [+ New Rule] first match: amber edge
|
||||
//
|
||||
// Data: the "schedule" object of the Meta snapshot (UiSources.Meta). Every
|
||||
// change is an mm_* MetaCommand, applied by RynthAi on its tick; nothing here
|
||||
// loads a meta or sends chat. Times are absolute (unix ms) in the snapshot,
|
||||
// so the countdowns tick here between snapshots.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed partial class MetaFace
|
||||
{
|
||||
private const string ScheduleLabel = PhosphorIcons.HourglassMedium + " Schedule##mode_sch";
|
||||
|
||||
private static readonly string[] TriggerNames =
|
||||
{
|
||||
"Quest ready (/myquests timer)", "After N minutes on the meta", "Every N minutes", "Countdown (you start it)",
|
||||
};
|
||||
|
||||
// Rule editor: -2 closed, -1 new rule, else the rule's index.
|
||||
private int _schedEdit = -2;
|
||||
private ScheduleRuleDto _schedRule = new();
|
||||
private readonly byte[] _schedQuest = new byte[128];
|
||||
private readonly byte[] _schedMinutes = new byte[16];
|
||||
private readonly byte[] _schedPoll = new byte[8], _schedWait = new byte[8], _schedGap = new byte[8];
|
||||
private long _schedFieldsVersion = -1; // snapshot the number boxes were last filled from
|
||||
private string[] _schedMetaPicks = Array.Empty<string>(), _schedOnlyPicks = Array.Empty<string>();
|
||||
|
||||
private void ShowSchedule()
|
||||
{
|
||||
_view = View.Schedule;
|
||||
_schedEdit = -2;
|
||||
}
|
||||
|
||||
private void ScheduleView(Vector2 origin, Vector2 size)
|
||||
{
|
||||
float w = size.X;
|
||||
SchedulePayload? sc = _data.Schedule;
|
||||
ModeRow(w, source: false, schedule: true);
|
||||
Separator(w);
|
||||
if (sc == null)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " This RynthAi has no Meta Manager (update RynthAi).");
|
||||
return;
|
||||
}
|
||||
|
||||
RefreshScheduleFields(sc);
|
||||
if (_schedEdit != -2)
|
||||
{
|
||||
ScheduleEditor(sc, size.Y - (ImGuiNET.ImGui.GetCursorScreenPos().Y - origin.Y) - FaceKit.GripOverlap());
|
||||
return;
|
||||
}
|
||||
|
||||
ScheduleSettings(sc, w);
|
||||
ScheduleStatusLine(sc, w);
|
||||
Separator(w);
|
||||
|
||||
const float bottomH = 24;
|
||||
float listH = Math.Max(40, origin.Y + size.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - bottomH - 9);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
|
||||
ImGuiNET.ImGui.BeginChild("##sched_rules", new Vector2(w, listH));
|
||||
ScheduleRules(sc, ImGuiNET.ImGui.GetContentRegionAvail().X);
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
|
||||
Separator(w);
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float newW = 80;
|
||||
if (Button(PhosphorIcons.Plus + " New Rule##sched_new", new Vector2(p.X, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green))
|
||||
OpenScheduleEditor(-1, new ScheduleRuleDto { Meta = FirstMetaFile() });
|
||||
if (sc.Rules.Count > 0)
|
||||
{
|
||||
if (Button(PhosphorIcons.ArrowCounterClockwise + " Re-arm all##sched_reset", new Vector2(p.X + newW + 4, p.Y), new Vector2(86, 24),
|
||||
Mute, BtnFill, BtnBord))
|
||||
MetaCommands.Simple("mm_reset", -1);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Clear every rule's fired / error / holding state");
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
}
|
||||
|
||||
/// <summary>Refill the number boxes from a new snapshot (not while one is being typed in).</summary>
|
||||
private void RefreshScheduleFields(SchedulePayload sc)
|
||||
{
|
||||
long v = UiSources.Meta.Current?.Version ?? 0;
|
||||
if (v == _schedFieldsVersion || ImGuiNET.ImGui.IsAnyItemActive()) return;
|
||||
_schedFieldsVersion = v;
|
||||
WriteUtf8(_schedPoll, sc.PollMinutes.ToString(CultureInfo.InvariantCulture));
|
||||
WriteUtf8(_schedWait, sc.MaxWaitSeconds.ToString(CultureInfo.InvariantCulture));
|
||||
WriteUtf8(_schedGap, sc.MinGapSeconds.ToString(CultureInfo.InvariantCulture));
|
||||
var metas = new List<string>();
|
||||
foreach (MetaFile f in _data.Files)
|
||||
if (!string.IsNullOrEmpty(f.Path)) metas.Add(System.IO.Path.GetFileName(f.Path));
|
||||
_schedMetaPicks = metas.ToArray();
|
||||
var only = new List<string> { "(any meta)" };
|
||||
only.AddRange(metas);
|
||||
_schedOnlyPicks = only.ToArray();
|
||||
}
|
||||
|
||||
private string FirstMetaFile() => _schedMetaPicks.Length > 0 ? _schedMetaPicks[0] : string.Empty;
|
||||
|
||||
// [x Manager] Poll [5] min [poll now] | Wait [60] s Gap [30] s [x While stopped]
|
||||
private void ScheduleSettings(SchedulePayload sc, float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x = p.X;
|
||||
if (Toggle((sc.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " Manager##sched_on", ref x, p.Y, sc.Enabled))
|
||||
{
|
||||
sc.Enabled = !sc.Enabled; // shows at once; the next snapshot confirms
|
||||
MetaCommands.Simple("mm_enabled", value: sc.Enabled ? "true" : "false");
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Off by default. While on, it loads the first due rule's meta (also /ra metamgr on|off).");
|
||||
x += 4;
|
||||
NumberField("Poll", "##sched_poll", _schedPoll, "min", ref x, p.Y, 30, "How often it sends /myquests (minimum 1). Only while on and with a quest rule.",
|
||||
n => { if (n >= 1) MetaCommands.Simple("mm_poll_minutes", value: n.ToString(CultureInfo.InvariantCulture)); });
|
||||
if (IconButton("##sched_pollnow", PhosphorIcons.ArrowsClockwise, new Vector2(x, p.Y), new Vector2(24, 22), TextDim, BtnFill, BtnBord,
|
||||
enabled: sc.Enabled))
|
||||
MetaCommands.Simple("mm_poll_now");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Check /myquests now");
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
|
||||
Vector2 q = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
x = q.X;
|
||||
NumberField("Wait up to", "##sched_wait", _schedWait, "s", ref x, q.Y, 34,
|
||||
"A switch waits until the bot is not fighting, looting, buffing or in a portal - at most this long, then it switches anyway.",
|
||||
n => MetaCommands.Simple("mm_max_wait", value: Math.Max(0, n).ToString(CultureInfo.InvariantCulture)));
|
||||
NumberField("Gap", "##sched_gap", _schedGap, "s", ref x, q.Y, 34, "At least this long between two switches.",
|
||||
n => MetaCommands.Simple("mm_min_gap", value: Math.Max(0, n).ToString(CultureInfo.InvariantCulture)));
|
||||
if (Toggle((sc.AllowWhileStopped ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " While stopped##sched_stopped", ref x, q.Y,
|
||||
sc.AllowWhileStopped))
|
||||
{
|
||||
sc.AllowWhileStopped = !sc.AllowWhileStopped;
|
||||
MetaCommands.Simple("mm_allow_stopped", value: sc.AllowWhileStopped ? "true" : "false");
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Also switch metas while the macro is stopped (off: it waits for the macro to run).");
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(q.X, q.Y + 24));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
}
|
||||
|
||||
/// <summary>"Label [box] unit" at (x, y); commits a whole number when the box loses focus after an edit.</summary>
|
||||
private static void NumberField(string label, string id, byte[] buf, string unit, ref float x, float y, float boxW, string tip, Action<int> commit)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float fy = y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
dl.AddText(new Vector2(x, fy), Mute, label);
|
||||
x += ImGuiNET.ImGui.CalcTextSize(label).X + 4;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y));
|
||||
TextBox(id, buf, boxW, "", ImGuiInputTextFlags.CharsDecimal, out _);
|
||||
bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
|
||||
ImGuiNET.ImGui.SetItemTooltip(tip);
|
||||
if (done && int.TryParse(Utf8(buf).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
|
||||
commit(n);
|
||||
x += boxW + 3;
|
||||
dl.AddText(new Vector2(x, fy), Mute, unit);
|
||||
x += ImGuiNET.ImGui.CalcTextSize(unit).X + 8;
|
||||
}
|
||||
|
||||
private void ScheduleStatusLine(SchedulePayload sc, float w)
|
||||
{
|
||||
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
string poll = !sc.Enabled ? "Off - nothing is loaded or polled."
|
||||
: sc.ServerDisabled ? "The server has /myquests turned off: quest rules can't fire."
|
||||
: !sc.Polling ? "No quest rules: /myquests is not polled."
|
||||
: sc.LastPollMs == 0 ? "Waiting for the first /myquests."
|
||||
: $"{sc.QuestCount} quest timer(s), /myquests {Span(now - sc.LastPollMs)} ago.";
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(sc.ServerDisabled ? 0xFFE8B333 : 0xFFC8D6E4), Fit(poll, w));
|
||||
if (sc.LastSwitch.Length > 0)
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6),
|
||||
Fit($"Last: {sc.LastSwitch}{(sc.LastSwitchMs > 0 ? $", {Span(now - sc.LastSwitchMs)} ago" : "")}", w));
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
private void ScheduleRules(SchedulePayload sc, float w)
|
||||
{
|
||||
if (sc.Rules.Count == 0)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " No rules. New Rule: when a timer runs out, load a meta.");
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " The first due rule (top to bottom) wins.");
|
||||
return;
|
||||
}
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
const float h = 20;
|
||||
for (int i = 0; i < sc.Rules.Count; i++)
|
||||
{
|
||||
ScheduleRuleDto r = sc.Rules[i];
|
||||
bool first = i == sc.FirstMatch && sc.Enabled;
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
dl.AddRectFilled(p, p + new Vector2(w, h), i % 2 == 0 ? PanelBg : RowAlt);
|
||||
ImGuiNET.ImGui.PushID(1000 + i);
|
||||
bool changed = false;
|
||||
float x = p.X + 1;
|
||||
|
||||
dl.AddText(new Vector2(x + 2, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, (i + 1).ToString(CultureInfo.InvariantCulture));
|
||||
x += 16;
|
||||
if (IconButton("##en", r.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, new Vector2(x, p.Y + 2), new Vector2(14, 16),
|
||||
r.Enabled ? Green : Mute, BtnFill, BtnBord))
|
||||
{
|
||||
r.Enabled = !r.Enabled;
|
||||
MetaCommands.Simple("mm_rule_enabled", i, r.Enabled ? "true" : "false");
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(r.Enabled ? "On - click to turn this rule off" : "Off - click to turn it on");
|
||||
x += 16;
|
||||
if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, enabled: i > 0))
|
||||
{
|
||||
MetaCommands.Simple("mm_move", i, "-1");
|
||||
(sc.Rules[i], sc.Rules[i - 1]) = (sc.Rules[i - 1], sc.Rules[i]);
|
||||
changed = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Higher priority");
|
||||
x += 18;
|
||||
if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord,
|
||||
enabled: i < sc.Rules.Count - 1))
|
||||
{
|
||||
MetaCommands.Simple("mm_move", i, "1");
|
||||
(sc.Rules[i], sc.Rules[i + 1]) = (sc.Rules[i + 1], sc.Rules[i]);
|
||||
changed = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Lower priority");
|
||||
x += 18;
|
||||
if (r.Trigger == 3) // countdown: start / stop
|
||||
{
|
||||
bool running = r.DueAtMs > 0;
|
||||
if (IconButton("##cd", running ? PhosphorIcons.Stop : PhosphorIcons.Play, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16),
|
||||
running ? Amber : Green, BtnFill, BtnBord))
|
||||
MetaCommands.Simple(running ? "mm_countdown_stop" : "mm_countdown_start", i);
|
||||
ImGuiNET.ImGui.SetItemTooltip(running ? "Stop the countdown" : $"Start the countdown ({Num(r.Minutes)} min)");
|
||||
}
|
||||
else if (r.Fired || (r.State ?? "").StartsWith("error", StringComparison.Ordinal) || (r.State ?? "").Contains("holding"))
|
||||
{
|
||||
if (IconButton("##rearm", PhosphorIcons.ArrowCounterClockwise, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Teal, BtnFill, BtnBord))
|
||||
MetaCommands.Simple("mm_reset", i);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Re-arm this rule");
|
||||
}
|
||||
x += 18;
|
||||
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x + 1, p.Y + 2), new Vector2(18, 16), TextDim, DelFill, BtnBord))
|
||||
{
|
||||
MetaCommands.Simple("mm_delete", i);
|
||||
sc.Rules.RemoveAt(i);
|
||||
changed = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Delete rule");
|
||||
x += 22;
|
||||
|
||||
// Text: "when TRIGGER, load META" | time left / state; click to edit.
|
||||
float textW = p.X + w - x;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y));
|
||||
bool open = ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(Math.Max(1, textW), h));
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
{
|
||||
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
||||
ImGuiNET.ImGui.SetTooltip(RuleTooltip(r, i, first));
|
||||
}
|
||||
ImGuiNET.ImGui.PopID();
|
||||
if (changed) return; // the list changed: draw it again next frame
|
||||
if (open)
|
||||
{
|
||||
OpenScheduleEditor(i, r);
|
||||
return;
|
||||
}
|
||||
|
||||
(string when, uint whenCol) = WhenText(r, now);
|
||||
float whenW = ImGuiNET.ImGui.CalcTextSize(when).X;
|
||||
float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
uint col = r.Enabled ? TextDim : Faded(TextDim);
|
||||
dl.AddText(new Vector2(x + 3, ty), col, Fit(RuleText(r), Math.Max(10, textW - whenW - 14)));
|
||||
dl.AddText(new Vector2(p.X + w - whenW - 4, ty), r.Enabled ? whenCol : Faded(whenCol), when);
|
||||
if (first) dl.AddRect(p, p + new Vector2(w, h), Amber, 2);
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
}
|
||||
}
|
||||
|
||||
private static string RuleText(ScheduleRuleDto r)
|
||||
{
|
||||
string trig = r.Trigger switch
|
||||
{
|
||||
0 => $"quest {(r.Quest.Length > 0 ? r.Quest : "?")} ready",
|
||||
1 => $"{Num(r.Minutes)} min on the meta",
|
||||
2 => $"every {Num(r.Minutes)} min",
|
||||
_ => $"{Num(r.Minutes)} min countdown",
|
||||
};
|
||||
string on = r.OnlyOnMeta.Length > 0 ? $" (on {r.OnlyOnMeta})" : "";
|
||||
return $"{trig}{on} {Arrow} {(r.Meta.Length > 0 ? r.Meta : "?")}{(r.Repeat ? "" : " [once]")}";
|
||||
}
|
||||
|
||||
private const string Arrow = "->";
|
||||
|
||||
/// <summary>The right-hand column: the state words, else the time left, "ready" or "never".</summary>
|
||||
private static (string Text, uint Color) WhenText(ScheduleRuleDto r, long nowMs)
|
||||
{
|
||||
string state = r.State ?? string.Empty;
|
||||
if (state.StartsWith("error", StringComparison.Ordinal)) return ("error", Red);
|
||||
if (state.StartsWith("waiting", StringComparison.Ordinal)) return (state, Amber);
|
||||
if (state == "switching") return (state, Amber);
|
||||
if (r.Fired) return ("fired", Mute);
|
||||
if (state.Contains("holding")) return ("holding", Teal);
|
||||
if (state.Length > 0 && r.DueAtMs == 0) return (Short(state), Mute);
|
||||
if (r.DueAtMs == -1) return ("never", Mute);
|
||||
if (r.DueAtMs == 0) return ("-", Mute);
|
||||
long left = r.DueAtMs - nowMs;
|
||||
return left <= 0 ? ("ready", Green) : (Span(left), TextDim);
|
||||
}
|
||||
|
||||
private static string Short(string state) => state switch
|
||||
{
|
||||
"no /myquests yet" => "no data yet",
|
||||
"/myquests is off on this server" => "no /myquests",
|
||||
"not started" => "not started",
|
||||
_ => state.Length > 18 ? state.Substring(0, 18) + "…" : state,
|
||||
};
|
||||
|
||||
private static string RuleTooltip(ScheduleRuleDto r, int i, bool first)
|
||||
{
|
||||
var sb = new System.Text.StringBuilder();
|
||||
sb.Append("Rule ").Append(i + 1).Append(": ").Append(TriggerNames[Math.Clamp(r.Trigger, 0, 3)]).Append('\n');
|
||||
if (r.Trigger == 0) sb.Append("Quest: ").Append(r.Quest.Length > 0 ? r.Quest : "(none)").Append('\n');
|
||||
else sb.Append("Minutes: ").Append(Num(r.Minutes)).Append('\n');
|
||||
sb.Append("Loads: ").Append(r.Meta.Length > 0 ? r.Meta : "(none)").Append('\n');
|
||||
if (r.OnlyOnMeta.Length > 0) sb.Append("Only while on: ").Append(r.OnlyOnMeta).Append('\n');
|
||||
sb.Append(r.Repeat ? "Repeats" : "Once (one-shot)");
|
||||
if (r.FireCount > 0) sb.Append(", fired ").Append(r.FireCount).Append("x this session");
|
||||
if (!string.IsNullOrEmpty(r.State)) sb.Append('\n').Append(r.State);
|
||||
if (first) sb.Append("\nFirst match: this rule fires next.");
|
||||
sb.Append("\nClick to edit.");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
// ── Rule editor ─────────────────────────────────────────────────────
|
||||
|
||||
private void OpenScheduleEditor(int index, ScheduleRuleDto r)
|
||||
{
|
||||
_schedEdit = index;
|
||||
_schedRule = r.CloneSettings();
|
||||
WriteUtf8(_schedQuest, _schedRule.Quest);
|
||||
WriteUtf8(_schedMinutes, Num(_schedRule.Minutes));
|
||||
}
|
||||
|
||||
private void ScheduleEditor(SchedulePayload sc, float height)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
|
||||
ImGuiNET.ImGui.BeginChild("##sched_editor", new Vector2(0, Math.Max(60, height)));
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
ScheduleRuleDto r = _schedRule;
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}");
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
||||
FieldLabel("When:");
|
||||
int picked = FlowPicker("##sched_trig", TriggerNames[Math.Clamp(r.Trigger, 0, 3)], TriggerNames, r.Trigger, w);
|
||||
if (picked >= 0) r.Trigger = picked;
|
||||
|
||||
if (r.Trigger == 0)
|
||||
{
|
||||
FieldLabel("Quest (as /myquests shows it; case doesn't matter):");
|
||||
if (TextBox("##sched_quest", _schedQuest, w, "e.g. blightlordlairwait1008", ImGuiInputTextFlags.None, out _))
|
||||
r.Quest = Utf8(_schedQuest).Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
FieldLabel(r.Trigger switch
|
||||
{
|
||||
1 => "Minutes on the current meta:",
|
||||
2 => "Every how many minutes:",
|
||||
_ => "Countdown minutes (start it with the play button or /ra metamgr start):",
|
||||
});
|
||||
if (TextBox("##sched_min", _schedMinutes, 80, "30", ImGuiInputTextFlags.CharsDecimal, out _)
|
||||
&& double.TryParse(Utf8(_schedMinutes).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double m) && m >= 0)
|
||||
r.Minutes = m;
|
||||
}
|
||||
|
||||
FieldLabel("Load meta:");
|
||||
picked = FlowPicker("##sched_meta", r.Meta.Length > 0 ? r.Meta : "Select a meta...", _schedMetaPicks,
|
||||
Array.FindIndex(_schedMetaPicks, s => string.Equals(s, r.Meta, StringComparison.OrdinalIgnoreCase)), w);
|
||||
if (picked >= 0) r.Meta = _schedMetaPicks[picked];
|
||||
|
||||
FieldLabel("Only while this meta is loaded:");
|
||||
int onlyIdx = r.OnlyOnMeta.Length == 0 ? 0
|
||||
: Array.FindIndex(_schedOnlyPicks, s => string.Equals(s, r.OnlyOnMeta, StringComparison.OrdinalIgnoreCase));
|
||||
picked = FlowPicker("##sched_only", r.OnlyOnMeta.Length > 0 ? r.OnlyOnMeta : _schedOnlyPicks.Length > 0 ? _schedOnlyPicks[0] : "(any meta)",
|
||||
_schedOnlyPicks, onlyIdx, w);
|
||||
if (picked >= 0) r.OnlyOnMeta = picked == 0 ? string.Empty : _schedOnlyPicks[picked];
|
||||
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x = p.X;
|
||||
if (Toggle("Repeat##sched_rep", ref x, p.Y, r.Repeat)) r.Repeat = true;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Fires every time its timer runs out");
|
||||
if (Toggle("Once##sched_once", ref x, p.Y, !r.Repeat)) r.Repeat = false;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Fires once, then waits until you re-arm it");
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Separator(w);
|
||||
bool valid = r.Meta.Length > 0 && (r.Trigger != 0 || r.Quest.Length > 0);
|
||||
Vector2 b = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
string saveLabel = (_schedEdit == -1 ? "Add Rule" : "Save Rule") + "##sched_save";
|
||||
float sw = ImGuiNET.ImGui.CalcTextSize(saveLabel.Substring(0, saveLabel.IndexOf("##", StringComparison.Ordinal))).X + 20;
|
||||
if (Button(saveLabel, b, new Vector2(sw, 22), TextDim, NewFill, Green, enabled: valid))
|
||||
{
|
||||
var send = r.CloneSettings();
|
||||
if (_schedEdit == -1) MetaCommands.Send(new MetaCmd { Op = "mm_add", ScheduleRule = send });
|
||||
else MetaCommands.Send(new MetaCmd { Op = "mm_update", Index = _schedEdit, ScheduleRule = send });
|
||||
_schedEdit = -2;
|
||||
}
|
||||
if (!valid) ImGuiNET.ImGui.SetItemTooltip(r.Meta.Length == 0 ? "Pick a meta to load" : "Name the quest");
|
||||
if (Button("Cancel##sched_cancel", new Vector2(b.X + sw + 6, b.Y), new Vector2(60, 22), Mute, BtnFill, BtnBord))
|
||||
_schedEdit = -2;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(b.X, b.Y + 22));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||
if (_schedEdit >= 0)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), "Saving re-arms the rule (clears fired / error).");
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
}
|
||||
|
||||
private static string Num(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>12s, 4m 05s, 3h 20m, 2d 4h.</summary>
|
||||
private static string Span(long ms)
|
||||
{
|
||||
if (ms < 0) ms = 0;
|
||||
var t = TimeSpan.FromMilliseconds(ms);
|
||||
if (t.TotalHours >= 24) return $"{(int)t.TotalDays}d {t.Hours}h";
|
||||
if (t.TotalMinutes >= 60) return $"{(int)t.TotalHours}h {t.Minutes:00}m";
|
||||
if (t.TotalSeconds >= 60) return $"{(int)t.TotalMinutes}m {t.Seconds:00}s";
|
||||
return $"{(int)t.TotalSeconds}s";
|
||||
}
|
||||
}
|
||||
1301
src/RynthCore.Engine/ImGui/Panels/MetaFace.cs
Normal file
1301
src/RynthCore.Engine/ImGui/Panels/MetaFace.cs
Normal file
File diff suppressed because it is too large
Load diff
25
src/RynthCore.Engine/ImGui/Panels/MonstersFace.cs
Normal file
25
src/RynthCore.Engine/ImGui/Panels/MonstersFace.cs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/MonstersFace.cs
|
||||
// The basic Monsters panel's ImGui face, retired 2026-10-01 (Tom). What only
|
||||
// it could do moved to the Damage panel (DamageFace: Name rules, the
|
||||
// Offhand modes per monster) and Monster Detail (DamageDetailFace: priority,
|
||||
// damage type, extra vuln, match expression; a name rule's debuffs, off
|
||||
// hand, pet and name). Categories were dropped from the UI; Rule.Category
|
||||
// stays in the model so existing rule files keep it.
|
||||
//
|
||||
// Only Register is left, because EntryPoint calls it: it registers no face
|
||||
// (so "Monsters" never shows) and moves a Monsters panel saved open onto
|
||||
// Damage. PanelRouter sends every other "Monsters" request to Damage.
|
||||
// ============================================================================
|
||||
|
||||
using RynthCore.Engine.UI;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal static class MonstersFace
|
||||
{
|
||||
public const string Title = "Monsters";
|
||||
|
||||
/// <summary>Engine init (EntryPoint). Registers nothing: see the file header.</summary>
|
||||
public static void Register() => PanelRouter.MoveRetiredMonstersPanel();
|
||||
}
|
||||
360
src/RynthCore.Engine/ImGui/Panels/NavFace.cs
Normal file
360
src/RynthCore.Engine/ImGui/Panels/NavFace.cs
Normal file
|
|
@ -0,0 +1,360 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/NavFace.cs
|
||||
// ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status,
|
||||
// Start/Stop, route type and insert mode, Add Waypoint / Portal (not yet) /
|
||||
// Recall / Clear / Save / Dungeon Patrol, a chat waypoint, Save As, the nav
|
||||
// file picker, the nav point reach (RynthAi's FollowNavMin, the same row as
|
||||
// Settings > Navigation), and the waypoint list (click selects the insert
|
||||
// point, X deletes, => marks the active one).
|
||||
//
|
||||
// Data: UiSources.Nav (hub) and NavCommands. Button actions change a private
|
||||
// copy at once; the plugin applies commands immediately, so the next
|
||||
// snapshot (requested right after) replaces the copy. The reach row reads
|
||||
// UiSources.Settings and saves through SettingsCommands, like the Settings face.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class NavFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Nav";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(400, 560), new Vector2(360, 380), EdgeToEdge: true),
|
||||
() => new NavFace());
|
||||
|
||||
private static readonly string[] Actions =
|
||||
{
|
||||
PhosphorIcons.MapPinPlus + " Add Waypoint", PhosphorIcons.Spiral + " Add Portal", PhosphorIcons.MagicWand + " Add Recall",
|
||||
PhosphorIcons.Trash + " Clear Route", PhosphorIcons.FloppyDisk + " Save Route", PhosphorIcons.Footprints + " Dungeon Patrol",
|
||||
};
|
||||
private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation";
|
||||
private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As";
|
||||
private static readonly bool[] ActionsEnabled = { true, false, true, true, true, true };
|
||||
|
||||
private NavPayload _data = new();
|
||||
private long _seenVersion = -1;
|
||||
private readonly List<string> _pointText = new();
|
||||
private int _selected = -1, _addMode;
|
||||
private bool _typing;
|
||||
private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)";
|
||||
private string _fileLabel = "Select nav file...";
|
||||
private string[] _navFiles = Array.Empty<string>();
|
||||
private readonly byte[] _chat = new byte[256];
|
||||
private int _chatLoadedFor = -1; // waypoint whose command is in _chat (-1: none)
|
||||
|
||||
private static void SetUtf8(byte[] buffer, string text)
|
||||
{
|
||||
Array.Clear(buffer);
|
||||
byte[] b = System.Text.Encoding.UTF8.GetBytes(text ?? string.Empty);
|
||||
Array.Copy(b, buffer, Math.Min(b.Length, buffer.Length - 1));
|
||||
}
|
||||
private readonly byte[] _saveName = new byte[128];
|
||||
private readonly byte[] _reach = new byte[16];
|
||||
private RynthAiSettings? _settings; // last Settings snapshot (null until fetched)
|
||||
private long _settingsVersion = -1;
|
||||
private bool _reachTyping;
|
||||
private readonly Picker _picker = new("##nav_pick");
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.Nav.Subscribe();
|
||||
UiSources.Nav.RequestRefresh();
|
||||
UiSources.Settings.Subscribe();
|
||||
UiSources.Settings.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
UiSources.Nav.Unsubscribe();
|
||||
UiSources.Settings.Unsubscribe();
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
TakeSnapshot();
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
bool typing = false;
|
||||
NavPayload d = _data;
|
||||
bool navActive = d.MacroRunning && d.NavigationEnabled;
|
||||
|
||||
// Active nav + status
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
Label(_activeLabel, Amber);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
if (d.NavStatusLine.Length > 0) Label(d.NavStatusLine, d.NavIsStuck ? Amber : Green);
|
||||
|
||||
// Start / Stop
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (Button("##startstop", navActive ? StopNav : StartNav, p, new Vector2(w, 28), Text, navActive ? StopBg : StartBg))
|
||||
{
|
||||
if (navActive)
|
||||
{
|
||||
NavCommands.Send(new NavCmd { Cmd = "stopNav" });
|
||||
_data.NavigationEnabled = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
NavCommands.Send(new NavCmd { Cmd = "startNav" });
|
||||
_data.MacroRunning = true;
|
||||
_data.NavigationEnabled = true;
|
||||
}
|
||||
}
|
||||
NextLine(p, 32);
|
||||
Separator(w);
|
||||
|
||||
// Route type | Insert mode
|
||||
p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float half = (w - 4) / 2;
|
||||
if (Button("##route", _routeLabel, p, new Vector2(half, 22), Text, BtnFill, leftAlign: true))
|
||||
_picker.Open(new Vector2(p.X, p.Y + 22), NavCommands.RouteTypes, NavCommands.RouteIndex(_data.RouteType), i =>
|
||||
{
|
||||
int routeType = NavCommands.RouteTypeFor(i);
|
||||
NavCommands.Send(new NavCmd { Cmd = "setRouteType", RouteType = routeType });
|
||||
_data.RouteType = routeType;
|
||||
UpdateLabels();
|
||||
});
|
||||
if (Button("##insert", _insertLabel, new Vector2(p.X + half + 4, p.Y), new Vector2(half, 22), Text, BtnFill, leftAlign: true))
|
||||
_picker.Open(new Vector2(p.X + half + 4, p.Y + 22), NavCommands.AddModes, _addMode, i =>
|
||||
{
|
||||
_addMode = i;
|
||||
UpdateLabels();
|
||||
});
|
||||
NextLine(p, 26);
|
||||
|
||||
typing |= ReachRow(w);
|
||||
|
||||
// Actions
|
||||
int action = WrapButtons("nav_act", Actions, w, 24, ActionsEnabled);
|
||||
switch (action)
|
||||
{
|
||||
case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break;
|
||||
case 2:
|
||||
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i =>
|
||||
NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected }));
|
||||
break;
|
||||
case 3:
|
||||
NavCommands.Send(new NavCmd { Cmd = "clearRoute" });
|
||||
_data.Points.Clear();
|
||||
_selected = -1;
|
||||
RebuildPointText();
|
||||
break;
|
||||
case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break;
|
||||
case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break;
|
||||
}
|
||||
|
||||
// Chat waypoint: sent as if typed when the route reaches it. Selecting an
|
||||
// existing chat waypoint loads its command here; Update saves the edit.
|
||||
bool chatSelected = _selected >= 0 && _selected < _data.Points.Count
|
||||
&& _data.Points[_selected].Type == "Chat";
|
||||
if (_selected != _chatLoadedFor)
|
||||
{
|
||||
if (chatSelected) SetUtf8(_chat, _data.Points[_selected].Text);
|
||||
else if (_chatLoadedFor >= 0) Array.Clear(_chat); // leaving a chat point: don't keep its text
|
||||
_chatLoadedFor = chatSelected ? _selected : -1;
|
||||
}
|
||||
p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float addW = ButtonWidth(AddChat);
|
||||
float updW = chatSelected ? ButtonWidth("Update") + 4 : 0;
|
||||
bool chatEnter = TextBox("##nav_chat", _chat, p, w - addW - updW - 4, "Chat command, e.g. /ub usei Healing Kit",
|
||||
out bool chatActive, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
typing |= chatActive;
|
||||
bool update = chatSelected
|
||||
&& Button("##updchat", "Update", new Vector2(p.X + w - addW - updW, p.Y), new Vector2(updW - 4, 22), Text, BtnFill);
|
||||
bool addChat = Button("##addchat", AddChat, new Vector2(p.X + w - addW, p.Y), new Vector2(addW, 22), Text, BtnFill);
|
||||
if (update || (chatEnter && chatSelected))
|
||||
{
|
||||
string text = Utf8(_chat).Trim();
|
||||
if (text.Length > 0)
|
||||
{
|
||||
NavCommands.Send(new NavCmd { Cmd = "editChat", Index = _selected, Text = text });
|
||||
_data.Points[_selected].Text = text;
|
||||
_data.Points[_selected].Desc = "[Chat] " + text;
|
||||
RebuildPointText();
|
||||
}
|
||||
}
|
||||
else if (chatEnter || addChat)
|
||||
{
|
||||
string text = Utf8(_chat).Trim();
|
||||
if (text.Length > 0)
|
||||
{
|
||||
NavCommands.Send(new NavCmd { Cmd = "addChat", Text = text, AddMode = _addMode, InsertAt = _selected });
|
||||
Array.Clear(_chat);
|
||||
_chatLoadedFor = -1;
|
||||
}
|
||||
}
|
||||
NextLine(p, 26);
|
||||
|
||||
// Save as a named nav
|
||||
p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float saveW = ButtonWidth(SaveAs);
|
||||
bool saveEnter = TextBox("##nav_saveas", _saveName, p, w - saveW - 4, "Nav name...", out bool saveActive, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
typing |= saveActive;
|
||||
bool saveAs = Button("##saveas", SaveAs, new Vector2(p.X + w - saveW, p.Y), new Vector2(saveW, 22), Text, BtnFill);
|
||||
if (saveEnter || saveAs)
|
||||
{
|
||||
string name = Utf8(_saveName).Trim();
|
||||
if (name.Length > 0)
|
||||
{
|
||||
NavCommands.Send(new NavCmd { Cmd = "saveRoute", NavName = name });
|
||||
Array.Clear(_saveName);
|
||||
}
|
||||
}
|
||||
NextLine(p, 26);
|
||||
|
||||
// Nav file picker
|
||||
if (_navFiles.Length > 0)
|
||||
{
|
||||
p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float lw = ImGuiNET.ImGui.CalcTextSize("Nav:").X + 6;
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Nav:");
|
||||
if (Button("##navfile", _fileLabel, new Vector2(p.X + lw, p.Y), new Vector2(w - lw, 22), Text, BtnFill, leftAlign: true))
|
||||
_picker.Open(new Vector2(p.X + lw, p.Y + 22), _navFiles, Array.IndexOf(_navFiles, _data.ActiveNavName), i =>
|
||||
NavCommands.Send(new NavCmd { Cmd = "loadNav", NavName = _navFiles[i] }));
|
||||
NextLine(p, 26);
|
||||
}
|
||||
|
||||
// Waypoints
|
||||
Separator(w);
|
||||
Label($"Waypoints ({_data.Points.Count})", Mute);
|
||||
float listH = Math.Max(60, Remaining(origin, size));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
|
||||
ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH));
|
||||
Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X);
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
|
||||
_typing = typing;
|
||||
End(origin, size);
|
||||
_picker.Draw();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Nav point reach (yd): how close nav gets to each nav point before moving on. Label,
|
||||
/// [-] value [+]; the typed value commits on Enter or when the box loses focus. Saves the
|
||||
/// whole settings payload (a copy of the latest snapshot), as the Settings face does.
|
||||
/// Hidden until RynthAi's settings have been fetched. Returns true while typing.
|
||||
/// </summary>
|
||||
private bool ReachRow(float w)
|
||||
{
|
||||
var snap = UiSources.Settings.Current;
|
||||
if (snap != null && snap.Version != _settingsVersion && !_reachTyping)
|
||||
{
|
||||
_settingsVersion = snap.Version;
|
||||
_settings = snap.Value.Clone();
|
||||
WriteUtf8(_reach, _settings.FollowNavMin.ToString("0.0#", CultureInfo.InvariantCulture));
|
||||
}
|
||||
if (_settings == null) return false;
|
||||
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
string label = SettingsSchema.NavPointReachLabel;
|
||||
float labelW = ImGuiNET.ImGui.CalcTextSize(label).X;
|
||||
dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, label);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.InvisibleButton("##reach_label", new Vector2(Math.Max(1, labelW), 22));
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(SettingsSchema.NavPointReachTip);
|
||||
|
||||
const float stepW = 22, boxW = 52;
|
||||
float right = p.X + w;
|
||||
float value = _settings.FollowNavMin;
|
||||
if (Button("##reach_minus", "-", new Vector2(right - stepW * 2 - boxW - 8, p.Y), new Vector2(stepW, 22), Text, BtnFill))
|
||||
SaveReach(value - 0.1f);
|
||||
bool enter = TextBox("##reach", _reach, new Vector2(right - stepW - boxW - 4, p.Y), boxW, "",
|
||||
out bool active, ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool commit = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
|
||||
if (Button("##reach_plus", "+", new Vector2(right - stepW, p.Y), new Vector2(stepW, 22), Text, BtnFill))
|
||||
SaveReach(value + 0.1f);
|
||||
if (commit)
|
||||
{
|
||||
if (float.TryParse(Utf8(_reach), NumberStyles.Float, CultureInfo.InvariantCulture, out float typed)) SaveReach(typed);
|
||||
else WriteUtf8(_reach, value.ToString("0.0#", CultureInfo.InvariantCulture)); // bad input reverts
|
||||
}
|
||||
_reachTyping = active;
|
||||
NextLine(p, 26);
|
||||
return active;
|
||||
}
|
||||
|
||||
private void SaveReach(float yards)
|
||||
{
|
||||
if (_settings == null || float.IsNaN(yards)) return;
|
||||
yards = MathF.Round(Math.Clamp(yards, 0.5f, 20f) * 10f) / 10f;
|
||||
_settings.FollowNavMin = yards;
|
||||
WriteUtf8(_reach, yards.ToString("0.0#", CultureInfo.InvariantCulture));
|
||||
SettingsCommands.Save(_settings.Clone());
|
||||
}
|
||||
|
||||
private void Waypoints(float w)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 clipMin = ImGuiNET.ImGui.GetWindowPos(), clipMax = clipMin + ImGuiNET.ImGui.GetWindowSize();
|
||||
for (int i = 0; i < _data.Points.Count; i++)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float h = 22;
|
||||
if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; }
|
||||
bool active = i == _data.ActiveNavIndex, selected = i == _selected;
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
// Row click selects (drawn first so the X button on top wins).
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) _selected = i;
|
||||
dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt);
|
||||
if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11))
|
||||
{
|
||||
NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i });
|
||||
if (_selected == i) _selected = -1;
|
||||
else if (_selected > i) _selected--;
|
||||
_data.Points.RemoveAt(i);
|
||||
RebuildPointText();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
return;
|
||||
}
|
||||
float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
if (active) dl.AddText(new Vector2(p.X + 24, ty), Teal, "=>");
|
||||
dl.PushClipRect(p, p + new Vector2(w - 2, h), true);
|
||||
dl.AddText(new Vector2(p.X + 44, ty), active ? Teal : Text, i < _pointText.Count ? _pointText[i] : "");
|
||||
dl.PopClipRect();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, 0));
|
||||
}
|
||||
}
|
||||
|
||||
private void TakeSnapshot()
|
||||
{
|
||||
var snap = UiSources.Nav.Current;
|
||||
if (snap == null || snap.Version == _seenVersion || _typing) return;
|
||||
_seenVersion = snap.Version;
|
||||
_data = snap.Value.Clone();
|
||||
_navFiles = _data.NavFiles.ToArray();
|
||||
if (_selected >= _data.Points.Count) _selected = -1;
|
||||
RebuildPointText();
|
||||
UpdateLabels();
|
||||
}
|
||||
|
||||
private void RebuildPointText()
|
||||
{
|
||||
_pointText.Clear();
|
||||
for (int i = 0; i < _data.Points.Count; i++) _pointText.Add(NavCommands.PointText(_data.Points[i], i));
|
||||
}
|
||||
|
||||
private void UpdateLabels()
|
||||
{
|
||||
_activeLabel = "Active Nav: " + (string.IsNullOrEmpty(_data.ActiveNavName) ? "None (Unsaved)" : _data.ActiveNavName);
|
||||
_routeLabel = "Route: " + NavCommands.RouteTypes[NavCommands.RouteIndex(_data.RouteType)];
|
||||
_insertLabel = "Insert: " + NavCommands.AddModes[_addMode];
|
||||
int fileIdx = string.IsNullOrEmpty(_data.ActiveNavName) ? -1 : _data.NavFiles.IndexOf(_data.ActiveNavName);
|
||||
_fileLabel = fileIdx >= 0 ? _data.NavFiles[fileIdx] : "Select nav file...";
|
||||
}
|
||||
}
|
||||
286
src/RynthCore.Engine/ImGui/Panels/P1Faces.cs
Normal file
286
src/RynthCore.Engine/ImGui/Panels/P1Faces.cs
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/P1Faces.cs
|
||||
// ImGui faces of the Status, Log and Tracker panels
|
||||
// (docs/IMGUI_PARITY_PLAN.md §2.11, §2.12). Each mirrors its Avalonia face in
|
||||
// UI/Panels and reads the same UiDataHub snapshot. AC thread only; strings
|
||||
// are built when a snapshot changes, not per frame.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal static class P1Faces
|
||||
{
|
||||
/// <summary>Registers the P1 faces next to their Avalonia faces (EntryPoint).</summary>
|
||||
public static void Register(bool trackerPresent)
|
||||
{
|
||||
// Status and Log end in a footer of left-aligned buttons: the resize grip
|
||||
// sits beside it, over the body (GripInBody), instead of in a strip below.
|
||||
var standard = new PanelSpec(new Vector2(400, 500), new Vector2(320, 240), GripInBody: true);
|
||||
ImGuiPanelHost.Register("Status", standard, () => new StatusFace());
|
||||
ImGuiPanelHost.Register("Log", standard, () => new LogFace());
|
||||
if (trackerPresent)
|
||||
ImGuiPanelHost.Register("Tracker",
|
||||
new PanelSpec(new Vector2(165, 190), new Vector2(60, 20), Background: 0, GripInBody: true),
|
||||
() => new TrackerFace());
|
||||
// The Skills panel: an engine panel with only an ImGui face, needing no plugin.
|
||||
// Registered here so engine init needs no new line in EntryPoint; ImGuiBar gives
|
||||
// it a bar button (ImGuiOnlyPanels).
|
||||
SkillsFace.Register();
|
||||
// Sense (watch list of names, anywhere the client knows): ImGui only, like Skills.
|
||||
SenseFace.Register();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Status: engine facts, plugin rows, and each panel's face.</summary>
|
||||
internal sealed class StatusFace : IImGuiPanel
|
||||
{
|
||||
private static readonly Vector4 HeaderColor = RynthTheme.Vec(0xC88CC8FF);
|
||||
private static readonly Vector4 RowColor = RynthTheme.Vec(0xC8D2D2D2);
|
||||
private static readonly Vector4 ErrorColor = RynthTheme.Vec(0xDCFF6464);
|
||||
|
||||
private string[] _engineRows = Array.Empty<string>();
|
||||
private long _pluginVersion = -1;
|
||||
private string _pluginHeader = "Plugins";
|
||||
private readonly List<(string Text, bool Error)> _pluginRows = new();
|
||||
private List<string> _faceRows = new();
|
||||
private long _faceRowsTick;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.PluginStatus.Subscribe();
|
||||
UiSources.PluginStatus.RequestRefresh();
|
||||
BuildEngineRows();
|
||||
}
|
||||
|
||||
private void BuildEngineRows()
|
||||
{
|
||||
_engineRows = new[]
|
||||
{
|
||||
$"Version: {EntryPoint.BuildStamp}",
|
||||
$"Game HWND: 0x{EntryPoint.GameHwnd:X8}",
|
||||
$"Plugin dir: {PluginManager.PluginDirectory}",
|
||||
};
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.PluginStatus.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
RefreshCaches();
|
||||
float footer = ImGuiNET.ImGui.GetFrameHeightWithSpacing();
|
||||
ImGuiNET.ImGui.BeginChild("##status", new Vector2(0, -footer));
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
|
||||
Header("Engine");
|
||||
foreach (string row in _engineRows) Row(row, false);
|
||||
Separator();
|
||||
Header(_pluginHeader);
|
||||
if (_pluginRows.Count == 0) Row("None loaded", false);
|
||||
foreach (var (text, error) in _pluginRows) Row(text, error);
|
||||
Separator();
|
||||
Header("UI faces");
|
||||
foreach (string row in _faceRows) Row(row, false);
|
||||
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowsClockwise + " Refresh"))
|
||||
{
|
||||
UiSources.PluginStatus.RequestRefresh();
|
||||
_faceRowsTick = 0;
|
||||
BuildEngineRows();
|
||||
}
|
||||
}
|
||||
|
||||
private void RefreshCaches()
|
||||
{
|
||||
var snap = UiSources.PluginStatus.Current;
|
||||
if (snap != null && snap.Version != _pluginVersion)
|
||||
{
|
||||
_pluginVersion = snap.Version;
|
||||
_pluginHeader = $"Plugins ({snap.Value.Length})";
|
||||
_pluginRows.Clear();
|
||||
foreach (PluginStatusRow r in snap.Value)
|
||||
_pluginRows.Add(($"{r.Label}: {r.State}", r.IsError));
|
||||
}
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
if (now - _faceRowsTick > 2000)
|
||||
{
|
||||
_faceRowsTick = now;
|
||||
_faceRows = PanelRouter.Describe();
|
||||
}
|
||||
}
|
||||
|
||||
private static void Header(string text)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
ImGuiNET.ImGui.TextColored(HeaderColor, text);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
private static void Row(string text, bool error)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, error ? ErrorColor : RowColor);
|
||||
ImGuiNET.ImGui.TextWrapped(text);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
|
||||
private static void Separator()
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddLine(p, p + new Vector2(w, 0), RynthTheme.Argb(0x3CFFFFFF));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Log: the engine's recent-log ring, monospace, with Auto-scroll and Clear.</summary>
|
||||
internal sealed unsafe class LogFace : IImGuiPanel
|
||||
{
|
||||
private ImGuiListClipper* _clipper;
|
||||
private bool _autoScroll = true;
|
||||
private long _clearedSeq;
|
||||
private long _seenVersion = -1;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.Log.Subscribe();
|
||||
UiSources.Log.RequestRefresh();
|
||||
_clipper = ImGuiNative.ImGuiListClipper_ImGuiListClipper();
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
UiSources.Log.Unsubscribe();
|
||||
if (_clipper != null) ImGuiNative.ImGuiListClipper_destroy(_clipper);
|
||||
_clipper = null;
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
var snap = UiSources.Log.Current;
|
||||
bool changed = snap != null && snap.Version != _seenVersion;
|
||||
if (snap != null) _seenVersion = snap.Version;
|
||||
|
||||
float footer = ImGuiNET.ImGui.GetFrameHeightWithSpacing();
|
||||
ImGuiNET.ImGui.BeginChild("##lines", new Vector2(0, -footer));
|
||||
if (snap != null && _clipper != null)
|
||||
{
|
||||
LogSnapshot log = snap.Value;
|
||||
// Clear hides everything up to the sequence number it saw, so it keeps
|
||||
// working after the 256-line ring wraps (Avalonia bug A6).
|
||||
int start = (int)Math.Clamp(_clearedSeq - log.FirstSeq + 1, 0, log.Lines.Length);
|
||||
int count = log.Lines.Length - start;
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono10));
|
||||
var clipper = new ImGuiListClipperPtr(_clipper);
|
||||
clipper.Begin(count);
|
||||
while (clipper.Step())
|
||||
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
|
||||
ImGuiNET.ImGui.TextUnformatted(log.Lines[start + i]);
|
||||
clipper.End();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
||||
if (changed && _autoScroll)
|
||||
ImGuiNET.ImGui.SetScrollHereY(1f);
|
||||
}
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
|
||||
ImGuiNET.ImGui.Checkbox("Auto-scroll", ref _autoScroll);
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.Eraser + " Clear"))
|
||||
_clearedSeq = snap?.Value.LastSeq ?? EntryPoint.RecentLogSeq;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tracker: nine session-stat rows over an adjustable-opacity background.</summary>
|
||||
internal sealed class TrackerFace : IImGuiPanel
|
||||
{
|
||||
private static readonly Vector4 TitleColor = RynthTheme.Vec(0xFFE6B450);
|
||||
private static readonly Vector4 LabelColor = RynthTheme.Vec(0xFF999999);
|
||||
private static readonly uint ResetBg = RynthTheme.Argb(0xFF1A2E40);
|
||||
private static readonly uint ResetBorder = RynthTheme.Argb(0xFF264C59);
|
||||
private int _opacity;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.Tracker.Subscribe();
|
||||
UiSources.Tracker.RequestRefresh();
|
||||
_opacity = (int)Math.Round(TrackerSettings.BgAlpha / 2.55);
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Tracker.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
// Background behind the content only (like the Avalonia StackPanel), so
|
||||
// content goes on channel 1 and the rect, sized afterwards, on channel 0.
|
||||
dl.ChannelsSplit(2);
|
||||
dl.ChannelsSetCurrent(1);
|
||||
Vector2 top = ImGuiNET.ImGui.GetCursorScreenPos() - ImGuiNET.ImGui.GetStyle().WindowPadding;
|
||||
float width = ImGuiNET.ImGui.GetWindowWidth();
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
|
||||
// Title row: [Tracker] [===slider===] [reset]
|
||||
ImGuiNET.ImGui.TextColored(TitleColor, "Tracker");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
float resetW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.ArrowCounterClockwise).X + 8;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(10, ImGuiNET.ImGui.GetContentRegionAvail().X - resetW - 4));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(2, 0));
|
||||
if (ImGuiNET.ImGui.SliderInt("##opacity", ref _opacity, 0, 100, ""))
|
||||
TrackerSettings.SetBgAlpha((byte)Math.Round(_opacity * 2.55), save: false);
|
||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
TrackerSettings.SetBgAlpha((byte)Math.Round(_opacity * 2.55), save: true);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, ResetBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ResetBorder);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 1));
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + "##reset"))
|
||||
UiSources.Tracker.RequestReset();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Reset the session stats");
|
||||
ImGuiNET.ImGui.PopStyleVar(2);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
|
||||
TrackerSnapshot? snap = UiSources.Tracker.Current?.Value;
|
||||
string[]? values = snap?.Values;
|
||||
string[] labels = snap?.Labels ?? TrackerSnapshot.DefaultLabels;
|
||||
// The resize grip sits over the body's bottom-right corner (GripInBody): a
|
||||
// row that reaches down into it right-aligns its value short of it.
|
||||
float grip = ImGuiPanelHost.BodyGripReserve;
|
||||
float gripTop = grip > 0 ? ImGuiNET.ImGui.GetWindowPos().Y + ImGuiNET.ImGui.GetWindowHeight() - grip : float.MaxValue;
|
||||
float rowH = ImGuiNET.ImGui.GetTextLineHeight();
|
||||
for (int i = 0; i < labels.Length; i++)
|
||||
{
|
||||
float rowRight = ImGuiNET.ImGui.GetCursorPosX() + ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
if (ImGuiNET.ImGui.GetCursorScreenPos().Y + rowH > gripTop) rowRight -= grip;
|
||||
ImGuiNET.ImGui.TextColored(LabelColor, labels[i]);
|
||||
string value = values != null && i < values.Length ? values[i] : "—";
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono9));
|
||||
float w = ImGuiNET.ImGui.CalcTextSize(value).X;
|
||||
ImGuiNET.ImGui.SameLine(Math.Max(0, rowRight - w));
|
||||
ImGuiNET.ImGui.TextUnformatted(value);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
||||
float bottom = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
dl.ChannelsSetCurrent(0);
|
||||
uint bg = RynthTheme.Argb(((uint)TrackerSettings.BgAlpha << 24) | 0x0A121A);
|
||||
dl.AddRectFilled(top, new Vector2(top.X + width, bottom), bg);
|
||||
dl.ChannelsMerge();
|
||||
}
|
||||
}
|
||||
682
src/RynthCore.Engine/ImGui/Panels/RadarFace.cs
Normal file
682
src/RynthCore.Engine/ImGui/Panels/RadarFace.cs
Normal file
|
|
@ -0,0 +1,682 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/RadarFace.cs
|
||||
// ImGui face of the Radar (docs/IMGUI_PARITY_PLAN.md §2.2), drawn the way
|
||||
// the Avalonia face's RadarSurface.Render does: gold rim, canvas, crosshair,
|
||||
// floors (current layer full, the one above and below at 30%) with slope
|
||||
// tints, walls (blue when visited), visited overlay, markers, player arrow,
|
||||
// outlined compass on the playfield perimeter, coordinate strip. Top-right
|
||||
// pop-out and settings (gear) buttons, wheel zoom, left-drag moves, left-click on a dot
|
||||
// selects it in game by object id (hover: name, distance, health), right-click menu, settings
|
||||
// popup. Settings are shared with the Avalonia face (RadarSettingsStore).
|
||||
// Marker kinds (RadarKind) each have a shape (RadarMarkerStyle), a show box
|
||||
// and a colour the user can pick; the settings popup doubles as the legend.
|
||||
//
|
||||
// Data: UiSources.Radar (RadarView, lookups precomputed). World geometry is
|
||||
// drawn without anti-aliasing (crisp tiling like the Avalonia face's aliased
|
||||
// mode, and far fewer vertices for big dungeons); no per-frame allocation.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using RynthCore.Engine.UI.Panels;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class RadarFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Radar";
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(320, 320), new Vector2(120, 120), PanelChrome.None,
|
||||
Background: 0, Rounding: 0, EdgeToEdge: true, GoldGrip: true),
|
||||
() => new RadarFace());
|
||||
// The Inventory panel (engine data only, like the radar): registered here so
|
||||
// engine init needs no new line in EntryPoint (as LootEditor / DungeonMap
|
||||
// register from RynthAiFace). Opened from the bar and /rc inv.
|
||||
InventoryFace.Register();
|
||||
}
|
||||
|
||||
// ── Palette (RadarPanel's, ARGB) ────────────────────────────────────
|
||||
private const uint FrameOuterArgb = 0xFF0A0D14, CanvasBgArgb = 0xFF0A121A;
|
||||
private static readonly uint FrameInner = C(0xFF9E853D), FrameAccent = C(0xFFE6C766),
|
||||
Crosshair = C(0x994D6680), Cardinal = C(0xFFFFFFFF), CoordText = C(0xFFF2F8FF), Outline = C(0xF2000000),
|
||||
PlayerCol = C(0xFF33FF66), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A);
|
||||
// Marker colours per kind (RadarSettingsStore.KindColors, user-pickable), refreshed each frame.
|
||||
private static readonly uint[] KindCols = new uint[RadarKind.Count];
|
||||
private const uint WallUnseen = 0xFFFFFFFF, WallVisited = 0xFF4099FF, FloorFlat = 0x8C2E8C38,
|
||||
FloorUp = 0x668C1F14, FloorDown = 0x661A8026, FloorVisited = 0xA64D6B94;
|
||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||
|
||||
/// <summary>ARGB colour with its alpha scaled, as an ImGui colour.</summary>
|
||||
private static uint MulAlpha(uint argb, float k) =>
|
||||
RynthTheme.Argb((argb & 0x00FFFFFF) | ((uint)Math.Clamp((int)MathF.Round((argb >> 24) * k), 0, 255) << 24));
|
||||
|
||||
private static readonly (string Label, float WorldX, float WorldY)[] Compass =
|
||||
{ ("N", 0, 1), ("E", 1, 0), ("S", 0, -1), ("W", -1, 0) };
|
||||
|
||||
private bool _settingsOpen;
|
||||
|
||||
/// <summary>Markers move: popped out, redraw smoothly even when idle.</summary>
|
||||
public int PopOutIdleHz => 20;
|
||||
|
||||
public bool ClickThrough =>
|
||||
RadarSettingsStore.CtrlGatedClickThrough && !ImGuiNET.ImGui.GetIO().KeyCtrl;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
RadarSettingsStore.Load();
|
||||
UiSources.Radar.Subscribe();
|
||||
UiSources.Radar.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Radar.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
|
||||
if (size.X < 16 || size.Y < 16) return;
|
||||
RadarView? view = UiSources.Radar.Current?.Value;
|
||||
|
||||
bool rim = RadarSettingsStore.ShowGoldRim;
|
||||
float canvasInset = rim ? 5 : 0;
|
||||
const float coordStrip = 14;
|
||||
float opacity = Math.Clamp(RadarSettingsStore.Opacity, 0f, 1f);
|
||||
Vector2 frameMax = origin + size;
|
||||
|
||||
// ── Frame: outer black (fades) + gold inner border + accent ──
|
||||
if (rim)
|
||||
{
|
||||
dl.AddRectFilled(origin, frameMax, MulAlpha(FrameOuterArgb, opacity));
|
||||
dl.AddRect(origin + new Vector2(1, 1), frameMax - new Vector2(1, 1), FrameInner, 0, ImDrawFlags.None, 2);
|
||||
dl.AddRect(origin + new Vector2(3, 3), frameMax - new Vector2(3, 3), FrameAccent, 0, ImDrawFlags.None, 1);
|
||||
}
|
||||
|
||||
// ── Canvas and world playfield (canvas minus the coord strip) ──
|
||||
Vector2 canvasMin = origin + new Vector2(canvasInset, canvasInset);
|
||||
Vector2 canvasMax = frameMax - new Vector2(canvasInset, canvasInset);
|
||||
dl.AddRectFilled(canvasMin, canvasMax, MulAlpha(CanvasBgArgb, opacity));
|
||||
var worldMin = canvasMin;
|
||||
var worldMax = new Vector2(canvasMax.X, canvasMax.Y - coordStrip);
|
||||
Vector2 centre = (worldMin + worldMax) * 0.5f;
|
||||
dl.AddLine(new Vector2(centre.X, worldMin.Y), new Vector2(centre.X, worldMax.Y), Crosshair);
|
||||
dl.AddLine(new Vector2(worldMin.X, centre.Y), new Vector2(worldMax.X, centre.Y), Crosshair);
|
||||
|
||||
if (view != null)
|
||||
{
|
||||
ImDrawListFlags saved = dl.Flags;
|
||||
dl.Flags = saved & ~(ImDrawListFlags.AntiAliasedLines | ImDrawListFlags.AntiAliasedLinesUseTex | ImDrawListFlags.AntiAliasedFill);
|
||||
dl.PushClipRect(worldMin, worldMax, true);
|
||||
DrawWorld(dl, view, centre, worldMin, worldMax);
|
||||
dl.PopClipRect();
|
||||
dl.Flags = saved;
|
||||
|
||||
DrawOutlinedText(dl, ImGuiFonts.Get(UiFont.UiBold11), view.CoordText,
|
||||
new Vector2((canvasMin.X + canvasMax.X) * 0.5f, canvasMax.Y), CoordText, alignBottom: true);
|
||||
DrawCardinals(dl, view, centre, (worldMax.X - worldMin.X) * 0.5f, (worldMax.Y - worldMin.Y) * 0.5f);
|
||||
}
|
||||
|
||||
// ── Buttons (submitted before the surface so they win the hover) ──
|
||||
const float btn = 22, gap = 4, inset = 6;
|
||||
var gearPos = new Vector2(frameMax.X - inset - btn, origin.Y + inset);
|
||||
var popPos = gearPos - new Vector2(btn + gap, 0);
|
||||
if (PanelRouter.CanPopOut)
|
||||
{
|
||||
if (IconButton("##radar_pop", popPos, ImGuiPanelHost.PopOutGlyph))
|
||||
ImGuiPanelHost.TogglePopOut(Title);
|
||||
ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip);
|
||||
}
|
||||
bool gear = IconButton("##radar_gear", gearPos, PhosphorIcons.Gear);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Radar settings");
|
||||
if (gear)
|
||||
{
|
||||
if (_settingsOpen) _settingsOpen = false;
|
||||
else
|
||||
{
|
||||
_settingsOpen = true;
|
||||
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(gearPos.X + btn, gearPos.Y + btn + 4), ImGuiCond.Always, new Vector2(1, 0));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Surface: drag moves the panel, a click on a dot selects, wheel zooms, right-click menu ──
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(origin);
|
||||
bool surfaceClicked = ImGuiNET.ImGui.InvisibleButton("##radar_surface", size);
|
||||
ImGuiPanelHost.DragWindowWithLastItem();
|
||||
if (view != null && RadarSettingsStore.ClickToSelect)
|
||||
MarkerInput(dl, view, centre, worldMin, worldMax, surfaceClicked);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
{
|
||||
float wheel = ImGuiNET.ImGui.GetIO().MouseWheel;
|
||||
if (wheel != 0)
|
||||
{
|
||||
float next = Math.Clamp(RadarSettingsStore.Zoom + wheel * 0.15f, 0.5f, 6.0f);
|
||||
if (next != RadarSettingsStore.Zoom) { RadarSettingsStore.Zoom = next; RadarSettingsStore.Save(); }
|
||||
}
|
||||
}
|
||||
if (ImGuiNET.ImGui.BeginPopupContextItem("##radar_menu"))
|
||||
{
|
||||
if (PanelRouter.CanPopOut && ImGuiNET.ImGui.MenuItem(ImGuiPopOuts.InPopOutFrame ? "Dock back" : "Pop out"))
|
||||
ImGuiPanelHost.TogglePopOut(Title);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Rotate with player", "", RadarSettingsStore.RotateWithPlayer))
|
||||
{
|
||||
RadarSettingsStore.RotateWithPlayer = !RadarSettingsStore.RotateWithPlayer;
|
||||
RadarSettingsStore.Save();
|
||||
}
|
||||
ImGuiPanelHost.TextSizeMenu(Title);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Close"))
|
||||
ImGuiPanelHost.Close(Title);
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
|
||||
SettingsWindow();
|
||||
}
|
||||
|
||||
// ── World ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>World (AC x east, y north) → screen, north-up or rotated so facing is up.</summary>
|
||||
private readonly struct Projection
|
||||
{
|
||||
private readonly float _cx, _cy, _pwx, _pwy, _sin, _cos, _zoom;
|
||||
private readonly bool _rotate;
|
||||
|
||||
public Projection(Vector2 centre, RadarPlayer p, bool rotate, float zoom)
|
||||
{
|
||||
_cx = centre.X; _cy = centre.Y; _pwx = p.WorldX; _pwy = p.WorldY;
|
||||
float h = p.Heading * MathF.PI / 180f; // AC: 0 = east, 90 = north
|
||||
_sin = MathF.Sin(h); _cos = MathF.Cos(h);
|
||||
_rotate = rotate; _zoom = zoom;
|
||||
}
|
||||
|
||||
public float Sin => _sin;
|
||||
public float Cos => _cos;
|
||||
|
||||
public Vector2 P(float wx, float wy)
|
||||
{
|
||||
float dx = wx - _pwx, dy = wy - _pwy;
|
||||
if (_rotate)
|
||||
{
|
||||
float right = _sin * dx - _cos * dy;
|
||||
float forward = _cos * dx + _sin * dy;
|
||||
return new Vector2(_cx + right * _zoom, _cy - forward * _zoom);
|
||||
}
|
||||
return new Vector2(_cx + dx * _zoom, _cy - dy * _zoom);
|
||||
}
|
||||
}
|
||||
|
||||
private static void DrawWorld(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
RadarSnapshot live = view.Live;
|
||||
bool rotate = RadarSettingsStore.RotateWithPlayer;
|
||||
var proj = new Projection(centre, live.Player, rotate, MathF.Max(0.5f, RadarSettingsStore.Zoom));
|
||||
|
||||
int cur = view.CurrentLayer, count = live.LayerZs.Count;
|
||||
// Same order as the Avalonia/ImGui-era radar: below, above (dimmed), current.
|
||||
if (cur - 1 >= 0) DrawLayer(dl, view, cur - 1, 0.30f, false, proj, rotate, clipMin, clipMax);
|
||||
if (cur + 1 < count && cur >= 0) DrawLayer(dl, view, cur + 1, 0.30f, false, proj, rotate, clipMin, clipMax);
|
||||
if (cur >= 0) DrawLayer(dl, view, cur, 1.00f, true, proj, rotate, clipMin, clipMax);
|
||||
|
||||
// Markers (shapes: RadarMarkerStyle). Corpses and items first, creatures on top.
|
||||
RadarMarkerStyle.FillColors(KindCols);
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
foreach (RadarMarker m in live.Markers)
|
||||
{
|
||||
if (!RadarSettingsStore.ShowKind(m.Kind)) continue;
|
||||
if ((pass == 1) != (RadarKind.IsCreature(m.Kind) || m.Kind is RadarKind.Portal or RadarKind.Door)) continue;
|
||||
Vector2 pp = proj.P(m.X, m.Y);
|
||||
if (pp.X < clipMin.X || pp.X > clipMax.X || pp.Y < clipMin.Y || pp.Y > clipMax.Y) continue;
|
||||
RadarMarkerStyle.Draw(dl, m.Kind, pp, KindCols[m.Kind]);
|
||||
}
|
||||
}
|
||||
|
||||
// Player dot + 10 px heading arrow (always up when rotating).
|
||||
dl.AddCircleFilled(centre, 3.5f, PlayerCol, 10);
|
||||
Vector2 tip = rotate ? centre + new Vector2(0, -10) : centre + new Vector2(proj.Cos * 10, -proj.Sin * 10);
|
||||
dl.AddLine(centre, tip, PlayerCol, 2);
|
||||
}
|
||||
|
||||
private static void DrawLayer(ImDrawListPtr dl, RadarView view, int layer, float a, bool current,
|
||||
in Projection proj, bool rotate, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
// Floor strips: 5 floats (x0, y0, x1, y1, type).
|
||||
if (view.FillsByLayer[layer] is float[] strips)
|
||||
{
|
||||
uint flat = MulAlpha(FloorFlat, a), up = MulAlpha(FloorUp, a), down = MulAlpha(FloorDown, a);
|
||||
for (int i = 0; i + 4 < strips.Length; i += 5)
|
||||
{
|
||||
int type = (int)strips[i + 4];
|
||||
uint col = type == 1 ? up : type == 2 ? down : flat;
|
||||
FillRect(dl, proj, rotate, strips[i], strips[i + 1], strips[i + 2], strips[i + 3], col, clipMin, clipMax);
|
||||
}
|
||||
}
|
||||
|
||||
// Walls: 6 floats (ax, ay, bx, by, cell x, cell y); visited tint on the current layer.
|
||||
if (view.WallsByLayer[layer] is float[] segs)
|
||||
{
|
||||
uint unseen = MulAlpha(WallUnseen, a), visited = MulAlpha(WallVisited, a);
|
||||
float thick = current ? 1.5f : 1.0f;
|
||||
bool[]? flags = current ? view.CurrentWallVisited : null;
|
||||
for (int i = 0, w = 0; i + 5 < segs.Length; i += 6, w++)
|
||||
{
|
||||
Vector2 pa = proj.P(segs[i], segs[i + 1]);
|
||||
Vector2 pb = proj.P(segs[i + 2], segs[i + 3]);
|
||||
if (MathF.Max(pa.X, pb.X) < clipMin.X || MathF.Min(pa.X, pb.X) > clipMax.X ||
|
||||
MathF.Max(pa.Y, pb.Y) < clipMin.Y || MathF.Min(pa.Y, pb.Y) > clipMax.Y) continue;
|
||||
bool v = flags != null && w < flags.Length && flags[w];
|
||||
dl.AddLine(pa, pb, v ? visited : unseen, thick);
|
||||
}
|
||||
}
|
||||
|
||||
// Visited overlay (current layer only): 4 floats per strip.
|
||||
if (current && view.VisitedByLayer[layer] is float[] vStrips)
|
||||
{
|
||||
uint fill = MulAlpha(FloorVisited, a);
|
||||
for (int i = 0; i + 3 < vStrips.Length; i += 4)
|
||||
FillRect(dl, proj, rotate, vStrips[i], vStrips[i + 1], vStrips[i + 2], vStrips[i + 3], fill, clipMin, clipMax);
|
||||
}
|
||||
}
|
||||
|
||||
private static void FillRect(ImDrawListPtr dl, in Projection proj, bool rotate, float x0, float y0, float x1, float y1,
|
||||
uint col, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
Vector2 p00 = proj.P(x0, y0), p11 = proj.P(x1, y1);
|
||||
if (rotate)
|
||||
{
|
||||
Vector2 p10 = proj.P(x1, y0), p01 = proj.P(x0, y1);
|
||||
float minX = MathF.Min(MathF.Min(p00.X, p11.X), MathF.Min(p10.X, p01.X));
|
||||
float maxX = MathF.Max(MathF.Max(p00.X, p11.X), MathF.Max(p10.X, p01.X));
|
||||
float minY = MathF.Min(MathF.Min(p00.Y, p11.Y), MathF.Min(p10.Y, p01.Y));
|
||||
float maxY = MathF.Max(MathF.Max(p00.Y, p11.Y), MathF.Max(p10.Y, p01.Y));
|
||||
if (maxX < clipMin.X || minX > clipMax.X || maxY < clipMin.Y || minY > clipMax.Y) return;
|
||||
dl.AddQuadFilled(p00, p10, p11, p01, col);
|
||||
}
|
||||
else
|
||||
{
|
||||
var a = Vector2.Min(p00, p11);
|
||||
var b = Vector2.Max(p00, p11);
|
||||
if (b.X < clipMin.X || a.X > clipMax.X || b.Y < clipMin.Y || a.Y > clipMax.Y) return;
|
||||
dl.AddRectFilled(a, b, col);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Click-to-select ─────────────────────────────────────────────────────
|
||||
// Left-click a dot: that object is selected in game, as a click on it in the
|
||||
// 3D world would. A press that moves more than a few pixels is a drag (the
|
||||
// panel moves) and selects nothing. Hover shows the object's name and
|
||||
// distance (and its last known health, when the engine has seen one).
|
||||
// RynthAi 2026-10-01 and later send each marker's object id, and the click
|
||||
// selects exactly that id. Older RynthAi builds send no id (Id = 0): then
|
||||
// the clicked marker is matched to the client's object list by position
|
||||
// (the engine's ~0.1 s position snapshot, same landblock, name preferred),
|
||||
// which can pick the wrong one of two same-name monsters close together.
|
||||
// The select itself is queued for AC's main thread
|
||||
// (AcMainThreadQueue.EnqueueOverlaySelect), which re-checks the object
|
||||
// still exists before selecting.
|
||||
|
||||
private const float ClickSlop = 4f; // px a press may move and still be a click
|
||||
private const float MatchTolerance = 5f; // metres between a marker and its object (snapshot lag)
|
||||
private const uint TypeCreature = 0x10, TypePortal = 0x10000;
|
||||
|
||||
private Vector2 _pressPos;
|
||||
private float _pressTravel;
|
||||
private byte _tipKind = byte.MaxValue;
|
||||
private string? _tipLabel;
|
||||
private int _tipDistance = int.MinValue;
|
||||
private int _tipPct = -1;
|
||||
private string _tipText = "";
|
||||
|
||||
private void MarkerInput(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax, bool clicked)
|
||||
{
|
||||
Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos;
|
||||
if (ImGuiNET.ImGui.IsItemActivated())
|
||||
{
|
||||
_pressPos = mouse;
|
||||
_pressTravel = 0f;
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsItemActive())
|
||||
{
|
||||
_pressTravel = MathF.Max(_pressTravel, Vector2.Distance(mouse, _pressPos));
|
||||
// Popped out, a 2 px drag hands the move to the OS window (DragWindowWithLastItem),
|
||||
// which then follows the cursor: the context's mouse barely moves, so mark it a drag.
|
||||
if (ImGuiPopOuts.InPopOutFrame && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 2f))
|
||||
_pressTravel = float.MaxValue;
|
||||
}
|
||||
|
||||
bool hovered = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (!hovered && !clicked) return;
|
||||
if (mouse.X < clipMin.X || mouse.X > clipMax.X || mouse.Y < clipMin.Y || mouse.Y > clipMax.Y) return;
|
||||
|
||||
float zoom = MathF.Max(0.5f, RadarSettingsStore.Zoom);
|
||||
var proj = new Projection(centre, view.Live.Player, RadarSettingsStore.RotateWithPlayer, zoom);
|
||||
// Hit radius: a little more than the dot, growing with zoom, in UI-scaled pixels.
|
||||
float radius = Math.Clamp(5f + 1.5f * zoom, 6f, 14f) * MathF.Max(1f, EngineFrameController.FontScale);
|
||||
RadarMarker? hit = MarkerAt(view, proj, mouse, radius, clipMin, clipMax, out Vector2 hitPos);
|
||||
if (hit == null) return;
|
||||
|
||||
if (clicked && _pressTravel <= ClickSlop)
|
||||
{
|
||||
uint id = hit.Id != 0 ? hit.Id : ResolveMarker(view, hit);
|
||||
if (id != 0)
|
||||
Compatibility.AcMainThreadQueue.EnqueueOverlaySelect(id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hovered || ImGuiNET.ImGui.IsItemActive()) return;
|
||||
dl.PushClipRect(clipMin, clipMax, true);
|
||||
dl.AddCircle(hitPos, 6.5f, CoordText, 16, 1.5f);
|
||||
dl.PopClipRect();
|
||||
ImGuiNET.ImGui.BeginTooltip();
|
||||
ImGuiNET.ImGui.TextUnformatted(TipText(view, hit));
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
|
||||
/// <summary>The shown marker nearest <paramref name="mouse"/> within <paramref name="radius"/> px, or null.</summary>
|
||||
private static RadarMarker? MarkerAt(RadarView view, in Projection proj, Vector2 mouse, float radius,
|
||||
Vector2 clipMin, Vector2 clipMax, out Vector2 at)
|
||||
{
|
||||
RadarMarker? best = null;
|
||||
float bestD2 = radius * radius;
|
||||
at = default;
|
||||
foreach (RadarMarker m in view.Live.Markers)
|
||||
{
|
||||
if (!RadarSettingsStore.ShowKind(m.Kind)) continue;
|
||||
Vector2 pp = proj.P(m.X, m.Y);
|
||||
if (pp.X < clipMin.X || pp.X > clipMax.X || pp.Y < clipMin.Y || pp.Y > clipMax.Y) continue;
|
||||
float d2 = Vector2.DistanceSquared(pp, mouse);
|
||||
if (d2 > bestD2) continue;
|
||||
bestD2 = d2;
|
||||
best = m;
|
||||
at = pp;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The object a marker stands for: the nearest object in the player's landblock
|
||||
/// (world = landblock-local + 192 m per landblock step, as the radar's markers)
|
||||
/// of the marker's kind, within <see cref="MatchTolerance"/>; a name match wins
|
||||
/// over a slightly nearer stranger. 0 when nothing matches. Only for markers
|
||||
/// without an id (older RynthAi builds).
|
||||
/// </summary>
|
||||
private static uint ResolveMarker(RadarView view, RadarMarker m)
|
||||
{
|
||||
uint landblock = view.Live.Player.Landblock;
|
||||
if (landblock == 0) return 0;
|
||||
uint playerId = Compatibility.ClientHelperHooks.GetPlayerId();
|
||||
string? label = string.IsNullOrEmpty(m.Label) ? null : m.Label;
|
||||
const float tol2 = MatchTolerance * MatchTolerance;
|
||||
uint best = 0;
|
||||
float bestScore = float.MaxValue;
|
||||
foreach (uint id in Compatibility.ClientObjectHooks.LiveObjectIds)
|
||||
{
|
||||
if (id == 0 || id == playerId) continue;
|
||||
if (!Compatibility.ClientObjectHooks.TryGetSnapshotPosition(id, out uint cell, out float x, out float y, out float z)) continue;
|
||||
if ((cell >> 16) != landblock) continue;
|
||||
float dx = x + ((cell >> 24) & 0xFF) * 192f - m.X;
|
||||
float dy = y + ((cell >> 16) & 0xFF) * 192f - m.Y;
|
||||
float dz = z - m.Z;
|
||||
float d2 = dx * dx + dy * dy + dz * dz;
|
||||
if (d2 > tol2) continue;
|
||||
if (m.Kind <= 2)
|
||||
{
|
||||
if (!Compatibility.ClientObjectHooks.TryGetSnapshotItemType(id, out uint type)) continue;
|
||||
uint need = m.Kind == 2 ? TypePortal : TypeCreature;
|
||||
if ((type & need) == 0) continue;
|
||||
}
|
||||
bool named = label != null && Compatibility.ClientObjectHooks.TryGetSnapshotName(id, out string name)
|
||||
&& name.Equals(label, StringComparison.Ordinal);
|
||||
float score = named ? d2 : d2 + tol2;
|
||||
if (score < bestScore) { bestScore = score; best = id; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Name\n12 yd" for the hovered marker, plus " 75%" when the marker has an id and
|
||||
/// the engine has a health reading for it (MonsterHudData: one locked lookup, hover
|
||||
/// only). Rebuilt only when the marker, whole yards or whole percent change.
|
||||
/// </summary>
|
||||
private string TipText(RadarView view, RadarMarker m)
|
||||
{
|
||||
RadarPlayer p = view.Live.Player;
|
||||
float dx = m.X - p.WorldX, dy = m.Y - p.WorldY, dz = m.Z - p.Z;
|
||||
int d = (int)MathF.Round(MathF.Sqrt(dx * dx + dy * dy + dz * dz));
|
||||
int pct = -1;
|
||||
if (m.Id != 0 && RadarKind.IsCreature(m.Kind) && Hud.MonsterHudData.TryGetHealth(m.Id, out Hud.HealthObservation h))
|
||||
pct = (int)MathF.Round(h.Ratio * 100f);
|
||||
// Markers are rebuilt on every radar poll: key on what the text shows, not the instance.
|
||||
if (m.Kind == _tipKind && d == _tipDistance && pct == _tipPct
|
||||
&& string.Equals(m.Label, _tipLabel, StringComparison.Ordinal))
|
||||
return _tipText;
|
||||
_tipKind = m.Kind;
|
||||
_tipLabel = m.Label;
|
||||
_tipDistance = d;
|
||||
_tipPct = pct;
|
||||
// A label is the object's name; the kinds a name alone doesn't tell apart say what they are.
|
||||
string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind)
|
||||
: m.Kind is RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor or RadarKind.OwnCorpse or RadarKind.Player
|
||||
? m.Label + " (" + RadarKind.Name(m.Kind) + ")"
|
||||
: m.Label!;
|
||||
var inv = System.Globalization.CultureInfo.InvariantCulture;
|
||||
_tipText = name + "\n" + d.ToString(inv) + " yd"
|
||||
+ (pct >= 0 ? " " + pct.ToString(inv) + "%" : "");
|
||||
return _tipText;
|
||||
}
|
||||
|
||||
// ── Compass and text ───────────────────────────────────────────────────
|
||||
|
||||
private static void DrawCardinals(ImDrawListPtr dl, RadarView view, Vector2 centre, float halfW, float halfH)
|
||||
{
|
||||
const float sz = 14;
|
||||
bool rotate = RadarSettingsStore.RotateWithPlayer;
|
||||
float h = view.Live.Player.Heading * MathF.PI / 180f;
|
||||
float sinH = MathF.Sin(h), cosH = MathF.Cos(h);
|
||||
float effW = MathF.Max(1, halfW - sz), effH = MathF.Max(1, halfH - sz);
|
||||
ImFontPtr font = ImGuiFonts.Get(UiFont.UiBold14);
|
||||
|
||||
foreach (var c in Compass)
|
||||
{
|
||||
float dirX, dirY;
|
||||
if (rotate)
|
||||
{
|
||||
dirX = sinH * c.WorldX - cosH * c.WorldY;
|
||||
dirY = -(cosH * c.WorldX + sinH * c.WorldY);
|
||||
}
|
||||
else
|
||||
{
|
||||
dirX = c.WorldX;
|
||||
dirY = -c.WorldY;
|
||||
}
|
||||
// Onto the rectangular perimeter: max(|dx t|/effW, |dy t|/effH) = 1.
|
||||
float m = MathF.Max(MathF.Abs(dirX) / effW, MathF.Abs(dirY) / effH);
|
||||
if (m < 1e-4f) continue;
|
||||
float t = 1 / m;
|
||||
DrawOutlinedText(dl, font, c.Label, new Vector2(centre.X + dirX * t, centre.Y + dirY * t), Cardinal, alignBottom: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Text with a 1 px 4-way black outline, centred on x; centred or bottom-aligned on y.</summary>
|
||||
private static void DrawOutlinedText(ImDrawListPtr dl, ImFontPtr font, string text, Vector2 anchor, uint col, bool alignBottom)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(font);
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
var pos = new Vector2(anchor.X - ts.X * 0.5f, alignBottom ? anchor.Y - ts.Y - 1 : anchor.Y - ts.Y * 0.5f);
|
||||
float fs = font.FontSize;
|
||||
dl.AddText(font, fs, pos + new Vector2(-1, 0), Outline, text);
|
||||
dl.AddText(font, fs, pos + new Vector2(1, 0), Outline, text);
|
||||
dl.AddText(font, fs, pos + new Vector2(0, -1), Outline, text);
|
||||
dl.AddText(font, fs, pos + new Vector2(0, 1), Outline, text);
|
||||
dl.AddText(font, fs, pos, col, text);
|
||||
}
|
||||
|
||||
private static bool IconButton(string id, Vector2 pos, string glyph)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
var size = new Vector2(22, 22);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
|
||||
uint bg = ImGuiNET.ImGui.IsItemActive() ? C(0xE0101820) : ImGuiNET.ImGui.IsItemHovered() ? C(0xE0243444) : ButtonBg;
|
||||
dl.AddRectFilled(pos, pos + size, bg, 3);
|
||||
dl.AddRect(pos, pos + size, ButtonBorder, 3);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), glyph, pos, size, CoordText);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
// ── Settings (gear) ─────────────────────────────────────────────────────
|
||||
|
||||
private void SettingsWindow()
|
||||
{
|
||||
if (!_settingsOpen) return;
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, C(0xFF0A121A));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ButtonBorder);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 4f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 10));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 6));
|
||||
const ImGuiWindowFlags flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize
|
||||
| ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoCollapse;
|
||||
bool visible = ImGuiNET.ImGui.Begin("##radar_settings", ref _settingsOpen, flags);
|
||||
ImGuiNET.ImGui.PopStyleVar(3);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (visible)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
ImGuiNET.ImGui.TextUnformatted("Radar Settings");
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.Separator();
|
||||
|
||||
bool changed = false;
|
||||
changed |= Check("Rotate with player", ref RadarSettingsStore.RotateWithPlayer);
|
||||
changed |= Check("Show gold rim", ref RadarSettingsStore.ShowGoldRim);
|
||||
changed |= Check("Docked click-through (hold Ctrl to interact)", ref RadarSettingsStore.CtrlGatedClickThrough);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
ImGuiNET.ImGui.SetTooltip("On: docked clicks pass through to the game; hold Ctrl to drag, open the gear, or resize.");
|
||||
changed |= Check("Click a dot to select it", ref RadarSettingsStore.ClickToSelect);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
ImGuiNET.ImGui.SetTooltip("Left-click a dot to select that object in game. Hover a dot for its name and distance.");
|
||||
changed |= Slider("Opacity", ref RadarSettingsStore.Opacity, 0.05f, 1.0f, "%.2f");
|
||||
changed |= Slider("Zoom", ref RadarSettingsStore.Zoom, 0.5f, 6.0f, "%.1f");
|
||||
ImGuiNET.ImGui.Separator();
|
||||
changed |= KindRows();
|
||||
if (changed)
|
||||
{
|
||||
AvaloniaOverlay.RadarCtrlGatedClickThrough = RadarSettingsStore.CtrlGatedClickThrough;
|
||||
RadarSettingsStore.Save();
|
||||
}
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
ImGuiNET.ImGui.End();
|
||||
}
|
||||
|
||||
private static bool Check(string label, ref bool value) => ImGuiNET.ImGui.Checkbox(label, ref value);
|
||||
|
||||
// Legend order: creatures, then corpses, then places, then items.
|
||||
private static readonly (byte Kind, string Label)[] KindRowsOrder =
|
||||
{
|
||||
(RadarKind.Monster, "Monsters"), (RadarKind.Player, "Players"), (RadarKind.Fellow, "Fellows"),
|
||||
(RadarKind.Npc, "NPCs"), (RadarKind.Vendor, "Vendors"), (RadarKind.Pet, "Your pets"),
|
||||
(RadarKind.Corpse, "Corpses"), (RadarKind.OwnCorpse, "Your corpses"), (RadarKind.Lifestone, "Lifestones"),
|
||||
(RadarKind.Portal, "Portals"), (RadarKind.Door, "Doors"), (RadarKind.GroundItem, "Items on the ground"),
|
||||
};
|
||||
|
||||
private static readonly string[] KindTips =
|
||||
{
|
||||
"Creatures you can attack.",
|
||||
"Creatures you can't attack (townsfolk, quest givers).",
|
||||
"Portals, with their destination.",
|
||||
"Doors, gates and hatches.",
|
||||
"Other players.",
|
||||
"Players in your fellowship.",
|
||||
"Your own combat pet.",
|
||||
"Shopkeepers.",
|
||||
"Corpses you can't loot (or not identified yet: selecting one tells).",
|
||||
"Corpses you may loot: your kills, your fellows' kills and your own corpse. Known once the corpse has been identified (looting or selecting it does that).",
|
||||
"Lifestones.",
|
||||
"Items lying on the ground. Off by default: there can be a lot of them.",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The legend and per-kind settings: show box, the marker as drawn, its name and a colour
|
||||
/// swatch (click to pick). One row per kind, then "Reset colours". True when something changed.
|
||||
/// </summary>
|
||||
private static bool KindRows()
|
||||
{
|
||||
bool changed = false;
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
ImGuiNET.ImGui.TextUnformatted("Show (click a swatch to change its colour):");
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
RadarMarkerStyle.FillColors(KindCols);
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float scale = MathF.Max(1f, EngineFrameController.FontScale);
|
||||
const ImGuiColorEditFlags pickFlags = ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel
|
||||
| ImGuiColorEditFlags.AlphaBar | ImGuiColorEditFlags.AlphaPreviewHalf;
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 3));
|
||||
foreach (var (kind, label) in KindRowsOrder)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(kind);
|
||||
changed |= ImGuiNET.ImGui.Checkbox("##show", ref RadarSettingsStore.ShowFlag(kind));
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]);
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
// The marker exactly as the radar draws it.
|
||||
float box = ImGuiNET.ImGui.GetFrameHeight();
|
||||
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(box, box));
|
||||
RadarMarkerStyle.Draw(dl, kind, at + new Vector2(box, box) * 0.5f, KindCols[kind], 1.3f * scale);
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextUnformatted(label);
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]);
|
||||
ImGuiNET.ImGui.SameLine(190 * scale);
|
||||
Vector4 v = RynthTheme.Vec(RadarSettingsStore.KindColors[kind]);
|
||||
if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, pickFlags))
|
||||
{
|
||||
RadarSettingsStore.KindColors[kind] = ToArgb(v);
|
||||
_colorDirty = true;
|
||||
}
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
// The picker reports every drag step: save once no colour edit is in progress.
|
||||
if (_colorDirty && !ImGuiNET.ImGui.IsAnyItemActive())
|
||||
{
|
||||
_colorDirty = false;
|
||||
changed = true;
|
||||
}
|
||||
if (ImGuiNET.ImGui.SmallButton("Reset colours"))
|
||||
{
|
||||
RadarSettingsStore.ResetKindColors();
|
||||
changed = true;
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Every kind back to its default colour (show boxes stay as they are).");
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static bool _colorDirty;
|
||||
|
||||
private static uint ToArgb(Vector4 v)
|
||||
{
|
||||
static uint B(float f) => (uint)Math.Clamp((int)MathF.Round(f * 255f), 0, 255);
|
||||
return (B(v.W) << 24) | (B(v.X) << 16) | (B(v.Y) << 8) | B(v.Z);
|
||||
}
|
||||
|
||||
private static bool Slider(string label, ref float value, float min, float max, string fmt)
|
||||
{
|
||||
ImGuiNET.ImGui.TextUnformatted(label);
|
||||
ImGuiNET.ImGui.SameLine(60);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(170);
|
||||
ImGuiNET.ImGui.PushID(label);
|
||||
bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, fmt);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
// Save once the drag ends, not on every step.
|
||||
return changed && !ImGuiNET.ImGui.IsItemActive() || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
|
||||
}
|
||||
}
|
||||
117
src/RynthCore.Engine/ImGui/Panels/RadarMarkerStyle.cs
Normal file
117
src/RynthCore.Engine/ImGui/Panels/RadarMarkerStyle.cs
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/RadarMarkerStyle.cs
|
||||
// One shape per radar marker kind (RadarKind), shared by the Radar face, its
|
||||
// settings legend and the Dungeon Map. Shapes differ as well as colours, so
|
||||
// the kinds stay apart for colour-blind players and when a user picks two
|
||||
// similar colours:
|
||||
// monster filled dot player dot with a white ring
|
||||
// NPC filled dot fellow triangle with a white edge
|
||||
// vendor coin (dot, dark rim) pet small dot, dark edge
|
||||
// corpse X your corpse bold X with a dark outline
|
||||
// lifestone ring with a centre item small square
|
||||
// portal diamond door square with a dark edge
|
||||
// Colours come in as ImGui colours (RynthTheme.Argb of the ARGB setting).
|
||||
// ============================================================================
|
||||
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using RynthCore.Engine.UI.Panels;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal static class RadarMarkerStyle
|
||||
{
|
||||
private static readonly uint White = RynthTheme.Argb(0xF0FFFFFF);
|
||||
private static readonly uint Black = RynthTheme.Argb(0xE6000000);
|
||||
|
||||
/// <summary>
|
||||
/// Draws a marker of <paramref name="kind"/> centred on <paramref name="p"/>. <paramref name="s"/>
|
||||
/// scales it (1 = the radar's size; the Dungeon Map draws a little bigger).
|
||||
/// </summary>
|
||||
public static void Draw(ImDrawListPtr dl, byte kind, Vector2 p, uint col, float s = 1f)
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case RadarKind.Monster:
|
||||
case RadarKind.Npc:
|
||||
dl.AddCircleFilled(p, 3f * s, col, 8);
|
||||
break;
|
||||
case RadarKind.Portal:
|
||||
{
|
||||
float r = 4f * s;
|
||||
dl.AddQuadFilled(p + new Vector2(0, -r), p + new Vector2(r, 0), p + new Vector2(0, r), p + new Vector2(-r, 0), col);
|
||||
break;
|
||||
}
|
||||
case RadarKind.Door:
|
||||
{
|
||||
var h = new Vector2(3.5f * s, 3.5f * s);
|
||||
dl.AddRectFilled(p - h, p + h, col);
|
||||
dl.AddRect(p - h, p + h, Darken(col, 0.4f));
|
||||
break;
|
||||
}
|
||||
case RadarKind.Player:
|
||||
dl.AddCircleFilled(p, 3.5f * s, col, 10);
|
||||
dl.AddCircle(p, 4.5f * s, White, 12, 1.5f);
|
||||
break;
|
||||
case RadarKind.Fellow:
|
||||
{
|
||||
float r = 4.8f * s;
|
||||
Vector2 a = p + new Vector2(0, -r), b = p + new Vector2(r * 0.9f, r * 0.65f), c = p + new Vector2(-r * 0.9f, r * 0.65f);
|
||||
dl.AddTriangleFilled(a, b, c, col);
|
||||
dl.AddTriangle(a, b, c, White, 1.3f);
|
||||
break;
|
||||
}
|
||||
case RadarKind.Pet:
|
||||
dl.AddCircleFilled(p, 2.3f * s, col, 8);
|
||||
dl.AddCircle(p, 2.8f * s, Black, 8, 1f);
|
||||
break;
|
||||
case RadarKind.Vendor:
|
||||
dl.AddCircleFilled(p, 4f * s, col, 12);
|
||||
dl.AddCircle(p, 4f * s, Darken(col, 0.45f), 12, 1.2f);
|
||||
dl.AddCircle(p, 2f * s, Darken(col, 0.55f), 8, 1f);
|
||||
break;
|
||||
case RadarKind.Corpse:
|
||||
{
|
||||
float r = 3f * s;
|
||||
dl.AddLine(p + new Vector2(-r, -r), p + new Vector2(r, r), col, 1.5f);
|
||||
dl.AddLine(p + new Vector2(-r, r), p + new Vector2(r, -r), col, 1.5f);
|
||||
break;
|
||||
}
|
||||
case RadarKind.OwnCorpse:
|
||||
{
|
||||
float r = 3.6f * s;
|
||||
dl.AddLine(p + new Vector2(-r, -r), p + new Vector2(r, r), Black, 4f);
|
||||
dl.AddLine(p + new Vector2(-r, r), p + new Vector2(r, -r), Black, 4f);
|
||||
dl.AddLine(p + new Vector2(-r, -r), p + new Vector2(r, r), col, 2.2f);
|
||||
dl.AddLine(p + new Vector2(-r, r), p + new Vector2(r, -r), col, 2.2f);
|
||||
break;
|
||||
}
|
||||
case RadarKind.Lifestone:
|
||||
dl.AddCircle(p, 3.8f * s, col, 12, 2f);
|
||||
dl.AddCircleFilled(p, 1.2f * s, col, 6);
|
||||
break;
|
||||
case RadarKind.GroundItem:
|
||||
{
|
||||
var h = new Vector2(2f * s, 2f * s);
|
||||
dl.AddRectFilled(p - h, p + h, col);
|
||||
dl.AddRect(p - h - Vector2.One, p + h + Vector2.One, Black);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An ImGui colour (ABGR) with its RGB scaled by <paramref name="k"/>, alpha kept.</summary>
|
||||
public static uint Darken(uint col, float k)
|
||||
{
|
||||
uint r = (uint)((col & 0xFF) * k), g = (uint)(((col >> 8) & 0xFF) * k), b = (uint)(((col >> 16) & 0xFF) * k);
|
||||
return (col & 0xFF000000) | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
|
||||
/// <summary>Each kind's ImGui colour from the radar settings, refreshed into <paramref name="into"/> (length RadarKind.Count).</summary>
|
||||
public static void FillColors(uint[] into)
|
||||
{
|
||||
for (int k = 0; k < into.Length; k++)
|
||||
into[k] = RynthTheme.Argb(RadarSettingsStore.KindColor((byte)k));
|
||||
}
|
||||
}
|
||||
866
src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs
Normal file
866
src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs
Normal file
|
|
@ -0,0 +1,866 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/RynthAiFace.cs
|
||||
// ImGui face of the RynthAi dashboard (docs/IMGUI_PARITY_PLAN.md §2.1),
|
||||
// first laid out from the Avalonia face (UI/Panels/RynthAiPanel.cs), then
|
||||
// made compact with Phosphor icons, after DrakBot's dashboard. Top to bottom:
|
||||
// title row RYNTHAI DASHBOARD | target, vitals, lock, opacity -/+,
|
||||
// minimize, pop out
|
||||
// header grid macro RUNNING/STOPPED, meta state, bot activity | pickers
|
||||
// control row (ON/OFF when minimized) combat, buffing, nav, looting and
|
||||
// meta toggles ... force rebuff
|
||||
// launchers one row of icon buttons (names in tooltips; labels too
|
||||
// when the panel is wide enough)
|
||||
// footer FPS | version | uptime
|
||||
// bars player vitals, then the target (name + health), each
|
||||
// toggled from the title row. Last on purpose, like DrakBot's
|
||||
// target row: what comes and goes with a fight never moves
|
||||
// the buttons above it.
|
||||
// Minimized keeps the title row, the control row and the bars. The window's
|
||||
// minimum height is the content's, and toggling the bars or minimize fits the
|
||||
// window to the content. Data: UiSources.RynthAi (a RynthAiView with every
|
||||
// string preformatted); clicks: RynthAiCommands.
|
||||
//
|
||||
// Chromeless (like the Avalonia face): the title row is the drag surface.
|
||||
// AC thread only; no per-frame string building except the FPS/uptime footer,
|
||||
// which is cached until its value changes.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class RynthAiFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "RynthAi";
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(296, 200), new Vector2(MinWidth, 54), PanelChrome.None,
|
||||
Background: RynthTheme.RynthAiBackground, BorderColor: RynthTheme.RynthAiBorder,
|
||||
Rounding: RynthTheme.RynthAiRounding),
|
||||
() => new RynthAiFace());
|
||||
// The Loot Editor edits RynthAi's loot profiles and opens from this dashboard.
|
||||
LootEditorFace.Register();
|
||||
// The Map launcher's panel. Registered here (only with RynthAi present, which
|
||||
// feeds its data) so engine init needs no new line in EntryPoint.
|
||||
DungeonMapFace.Register();
|
||||
}
|
||||
|
||||
private const float MinWidth = 280;
|
||||
|
||||
// ── Palette (RynthAiPanel's, ARGB) ─────────────────────────────────
|
||||
private static readonly uint Teal = C(0xFF26D9E6), TealSoft = C(0xFF264C59), Amber = C(0xFFE8B333),
|
||||
Green = C(0xFF40D973), Mute = C(0xFFB8C8D8), TextDim = C(0xFFF2F7FC), White = C(0xFFFFFFFF),
|
||||
Hp = C(0xFFD93333), Mana = C(0xFF268CF2), ShellBg = C(0xFF0A0F14), BarBg = C(0xFF141F29),
|
||||
BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A), MacroRun = C(0xFF1A5926), MacroStop = C(0xFF401F1F),
|
||||
FrFill = C(0xFF47330A), SelectorBg = C(0xFF2D3847);
|
||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||
|
||||
private static readonly uint[] SegmentColors = BuildSegmentColors();
|
||||
|
||||
private string _fpsText = "FPS —", _upText = "Up —";
|
||||
private int _fpsShown = -1;
|
||||
private long _upShown = -1;
|
||||
private bool _patrolOpen;
|
||||
// Picker toggle: ImGui closes a popup on the press outside it, so remember
|
||||
// whether it was showing when the selector press began (a second click closes).
|
||||
private readonly int[] _pickerShownFrame = { -10, -10, -10, -10 };
|
||||
private readonly bool[] _pressedWhileOpen = new bool[4];
|
||||
// The content's height (logical units, body padding included), measured each
|
||||
// frame: the window's minimum height. _fit: resize the window to it once.
|
||||
private float _contentHeight;
|
||||
private bool _fit;
|
||||
// Files folded/open flipped: size the window to that mode's own remembered size.
|
||||
private bool _modeFlip, _modeFlipApply;
|
||||
private Vector2 _winLogical; // the window's size in logical units, last frame (docked only)
|
||||
private const float GripRoom = 12;
|
||||
|
||||
public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight
|
||||
: RynthAiDashboardState.Minimized ? 54 : 180);
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.RynthAi.Subscribe();
|
||||
UiSources.RynthAi.RequestRefresh();
|
||||
_fit = true; // drop the empty space a taller saved size leaves under the content
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
UiSources.RynthAi.Unsubscribe();
|
||||
if (_patrolOpen) { UiSources.Patrol.Unsubscribe(); _patrolOpen = false; }
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
RynthAiView? view = UiSources.RynthAi.Current?.Value;
|
||||
RynthAiSnapshot raw = view?.Raw ?? Empty;
|
||||
bool minimized = RynthAiDashboardState.Minimized;
|
||||
uint boxBg = (C(0xFF0A121A) & 0x00FFFFFF) | ((uint)(view?.PanelAlpha ?? 242) << 24);
|
||||
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x0 = start.X;
|
||||
float width = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
|
||||
TitleRow(raw, x0, width, minimized);
|
||||
Gap(4);
|
||||
// The Profile/Nav/Loot/Meta pickers only while expanded (the caret on the control row).
|
||||
if (!minimized && RynthAiDashboardState.ShowFiles)
|
||||
{
|
||||
HeaderGrid(view, raw, x0, width);
|
||||
Gap(4);
|
||||
}
|
||||
ControlRow(view, raw, x0, width, minimized, boxBg);
|
||||
if (!minimized)
|
||||
{
|
||||
Gap(4);
|
||||
Launchers(x0, width);
|
||||
Gap(6);
|
||||
Footer(view, x0, width);
|
||||
}
|
||||
Bars(view, raw, x0, width, boxBg);
|
||||
PatrolPopup();
|
||||
MeasureAndFit(start.Y);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the content height as the window's minimum (so the bars at the
|
||||
/// bottom are never cut off) and, after a toggle, fits the window to it.
|
||||
/// </summary>
|
||||
private void MeasureAndFit(float startY)
|
||||
{
|
||||
float pad = ImGuiNET.ImGui.GetCursorStartPos().Y; // the body's top padding (the bottom's is the same)
|
||||
float px = ImGuiNET.ImGui.GetCursorScreenPos().Y - startY + 2 * pad;
|
||||
float place = ImGuiPanelHost.PlacementScale();
|
||||
// + room for the host's resize grip, which is painted over the body's bottom-right corner.
|
||||
_contentHeight = MathF.Ceiling(px / place) + GripRoom;
|
||||
if (!ImGuiPopOuts.InPopOutFrame)
|
||||
{
|
||||
if (_modeFlip)
|
||||
{
|
||||
// The flip happened mid-frame, so this frame measured the old layout: size next frame.
|
||||
_modeFlip = false;
|
||||
_modeFlipApply = true;
|
||||
}
|
||||
else if (_modeFlipApply)
|
||||
{
|
||||
_modeFlipApply = false;
|
||||
_fit = false;
|
||||
bool open = RynthAiDashboardState.ShowFiles;
|
||||
bool known = RynthAiDashboardState.TryGetFilesModeSize(open, out float mw, out float mh);
|
||||
float w = known ? mw : ImGuiNET.ImGui.GetWindowWidth() / place;
|
||||
// Folded always shrinks to its one line; open comes back at the size it last had.
|
||||
float h = open && known ? MathF.Max(mh, _contentHeight) : _contentHeight;
|
||||
ImGuiPanelHost.RequestSize(Title, new Vector2(w, h));
|
||||
return;
|
||||
}
|
||||
_winLogical = new Vector2(ImGuiNET.ImGui.GetWindowWidth() / place, ImGuiNET.ImGui.GetWindowHeight() / place);
|
||||
}
|
||||
if (_fit && !ImGuiPopOuts.InPopOutFrame)
|
||||
{
|
||||
_fit = false;
|
||||
ImGuiPanelHost.RequestSize(Title, new Vector2(ImGuiNET.ImGui.GetWindowWidth() / place, _contentHeight));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Title row: "R" + "YNTHAI DASHBOARD" | chips (drag surface) ──────
|
||||
|
||||
private void TitleRow(RynthAiSnapshot raw, float x0, float width, bool minimized)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
const int chips = 7;
|
||||
const float chipW = 18, chipH = 16, chipGap = 2;
|
||||
float chipsW = chips * chipW + (chips - 1) * chipGap;
|
||||
float rowH = 20;
|
||||
|
||||
// Drag surface: everything left of the chips.
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y));
|
||||
ImGuiNET.ImGui.InvisibleButton("##dash_drag", new Vector2(Math.Max(1, width - chipsW), rowH));
|
||||
ImGuiPanelHost.DragWindowWithLastItem();
|
||||
|
||||
ImFontPtr title = ImGuiFonts.Get(UiFont.Dash14);
|
||||
float ty = y + (rowH - title.FontSize) * 0.5f;
|
||||
dl.PushClipRect(new Vector2(x0, y), new Vector2(x0 + Math.Max(1, width - chipsW - 4), y + rowH), true);
|
||||
dl.AddText(title, title.FontSize, new Vector2(x0, ty), Teal, "R");
|
||||
float rw = CalcWidth(title, "R");
|
||||
dl.AddText(title, title.FontSize, new Vector2(x0 + rw, ty), White, "YNTHAI DASHBOARD");
|
||||
dl.PopClipRect();
|
||||
|
||||
float cx = x0 + width - chipsW;
|
||||
float cy = y + (rowH - chipH) * 0.5f;
|
||||
var chip = new Vector2(chipW, chipH);
|
||||
const UiFont chipFont = UiFont.Dash11;
|
||||
|
||||
bool target = RynthAiDashboardState.ShowTargetBar;
|
||||
if (IconButton("##chip_target", new Vector2(cx, cy), chip, PhosphorIcons.Crosshair, chipFont, BtnFill, target ? Teal : Mute, BtnBord, 2))
|
||||
{
|
||||
RynthAiDashboardState.SetShowTargetBar(!target);
|
||||
_fit = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(target
|
||||
? "Target bar on: the target's name and health at the bottom. Click to hide it."
|
||||
: "Target bar off. Click to show the target's name and health at the bottom.");
|
||||
cx += chipW + chipGap;
|
||||
bool vitals = RynthAiDashboardState.ShowVitals;
|
||||
if (IconButton("##chip_vitals", new Vector2(cx, cy), chip, PhosphorIcons.Heartbeat, chipFont, BtnFill, vitals ? Teal : Mute, BtnBord, 2))
|
||||
{
|
||||
RynthAiDashboardState.SetShowVitals(!vitals);
|
||||
_fit = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(vitals
|
||||
? "Player vitals on: your health, stamina and mana at the bottom. Click to hide them."
|
||||
: "Player vitals off. Click to show your health, stamina and mana at the bottom.");
|
||||
cx += chipW + chipGap;
|
||||
if (IconButton("##chip_lock", new Vector2(cx, cy), chip, raw.IsLocked ? PhosphorIcons.Lock : PhosphorIcons.LockOpen,
|
||||
chipFont, BtnFill, raw.IsLocked ? Amber : Mute, BtnBord, 2))
|
||||
RynthAiCommands.TogglePanelLock();
|
||||
ImGuiNET.ImGui.SetItemTooltip(raw.IsLocked ? "Locked. Click to unlock the dashboard." : "Click to lock the dashboard in place.");
|
||||
cx += chipW + chipGap;
|
||||
if (IconButton("##chip_minus", new Vector2(cx, cy), chip, PhosphorIcons.Minus, chipFont, BtnFill, Mute, BtnBord, 2))
|
||||
RynthAiCommands.AdjustOpacity(-0.1f);
|
||||
ImGuiNET.ImGui.SetItemTooltip("More transparent");
|
||||
cx += chipW + chipGap;
|
||||
if (IconButton("##chip_plus", new Vector2(cx, cy), chip, PhosphorIcons.Plus, chipFont, BtnFill, Mute, BtnBord, 2))
|
||||
RynthAiCommands.AdjustOpacity(0.1f);
|
||||
ImGuiNET.ImGui.SetItemTooltip("More opaque");
|
||||
cx += chipW + chipGap;
|
||||
if (IconButton("##chip_min", new Vector2(cx, cy), chip,
|
||||
minimized ? PhosphorIcons.ArrowsOutLineVertical : PhosphorIcons.ArrowsInLineVertical, chipFont, BtnFill, Mute, BtnBord, 2))
|
||||
{
|
||||
RynthAiDashboardState.SetMinimized(!minimized);
|
||||
_fit = true; // the window fits the other mode's content next frame
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(minimized ? "Expand" : "Minimize");
|
||||
cx += chipW + chipGap;
|
||||
if (PanelRouter.CanPopOut)
|
||||
{
|
||||
if (IconButton("##chip_dock", new Vector2(cx, cy), chip, ImGuiPanelHost.PopOutGlyph, chipFont, BtnFill, Mute, BtnBord, 2))
|
||||
ImGuiPanelHost.TogglePopOut(Title);
|
||||
ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip);
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + rowH));
|
||||
}
|
||||
|
||||
// ── Header: macro + state (40%) | Profile/Nav/Loot/Meta pickers (60%) ──
|
||||
|
||||
private void HeaderGrid(RynthAiView? view, RynthAiSnapshot raw, float x0, float width)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float y0 = ImGuiNET.ImGui.GetCursorScreenPos().Y + 2;
|
||||
float leftW = width * 0.4f;
|
||||
|
||||
// Left: Meta State / Bot Activity (the macro start/stop is the control row's first square).
|
||||
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10);
|
||||
float ly = y0;
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Meta State:");
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.MetaStateText ?? "Default");
|
||||
ly += 2 * (f10.FontSize + 1) + 4;
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Bot Activity:");
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.BotActivityText ?? "Idle");
|
||||
float leftBottom = ly + 2 * (f10.FontSize + 1);
|
||||
|
||||
// Right: four selector rows (label 36 px, picker fills, spacing 3).
|
||||
float rx = x0 + leftW, rw = width - leftW, ry = y0;
|
||||
// The fold arrow sits at the end of the Profile row, where it always fits.
|
||||
const float foldW = 18f;
|
||||
Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, rx, ry, rw - foldW - 2, null);
|
||||
if (IconButton("##files_fold", new Vector2(rx + rw - foldW, ry), new Vector2(foldW, 16), PhosphorIcons.CaretUp, UiFont.Dash11, BtnFill, Mute, BtnBord, 2))
|
||||
{
|
||||
RynthAiDashboardState.SetFilesModeSize(true, _winLogical.X, _winLogical.Y);
|
||||
RynthAiDashboardState.SetShowFiles(false);
|
||||
_modeFlip = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Fold the loaded files into one line");
|
||||
ry += 16 + 3;
|
||||
Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, rx, ry, rw, null);
|
||||
ry += 16 + 3;
|
||||
Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, rx, ry, rw, raw);
|
||||
ry += 16 + 3;
|
||||
Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, rx, ry, rw, null);
|
||||
ry += 16;
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + 4));
|
||||
}
|
||||
|
||||
private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta" };
|
||||
private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta" };
|
||||
private static readonly string[] NoneItems = { "None" };
|
||||
|
||||
private void Selector(int slot, string label, string text, string[] items, int selected, int kind,
|
||||
float x, float y, float w, RynthAiSnapshot? lootEdit)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10), f9 = ImGuiFonts.Get(UiFont.Dash9);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x, y + (16 - f10.FontSize) * 0.5f), Mute, label);
|
||||
|
||||
float editW = 0;
|
||||
if (lootEdit != null)
|
||||
{
|
||||
editW = 18;
|
||||
var ep = new Vector2(x + w - editW, y);
|
||||
if (IconButton("##loot_edit", ep, new Vector2(editW, 16), PhosphorIcons.TreasureChest, UiFont.Dash11, SelectorBg, Mute, 0, 2))
|
||||
{
|
||||
string path = !string.IsNullOrEmpty(lootEdit.VendorProfilePath) ? lootEdit.VendorProfilePath : lootEdit.CurrentLootPath;
|
||||
// The in-game Loot Editor panel. The external editor is one click away on the
|
||||
// panel's toolbar (LootEditorFace.LaunchExternal, an STA thread of its own).
|
||||
LootEditorFace.ToggleFor(path);
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Loot Editor: the loot profile in use, or the open vendor's AutoVendor profile.");
|
||||
editW += 3;
|
||||
}
|
||||
|
||||
var pos = new Vector2(x + 36, y);
|
||||
var size = new Vector2(Math.Max(20, w - 36 - editW), 16);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(SelectorIds[slot], size);
|
||||
bool hovered = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (ImGuiNET.ImGui.IsItemActivated())
|
||||
_pressedWhileOpen[slot] = ImGuiNET.ImGui.GetFrameCount() - _pickerShownFrame[slot] <= 1;
|
||||
bool open = ImGuiNET.ImGui.IsPopupOpen(PickerIds[slot]);
|
||||
dl.AddRectFilled(pos, pos + size, hovered ? Lighten(SelectorBg) : SelectorBg, 2);
|
||||
dl.AddRect(pos, pos + size, BtnBord, 2);
|
||||
const float arrowW = 12;
|
||||
dl.PushClipRect(pos, pos + size - new Vector2(arrowW + 4, 0), true);
|
||||
dl.AddText(f9, f9.FontSize, pos + new Vector2(5, (16 - f9.FontSize) * 0.5f), White, text);
|
||||
dl.PopClipRect();
|
||||
PhosphorIcons.DrawCentered(dl, f10, open ? PhosphorIcons.CaretUp : PhosphorIcons.CaretDown,
|
||||
new Vector2(pos.X + size.X - arrowW - 3, y), new Vector2(arrowW, 16), Mute);
|
||||
|
||||
if (clicked && !_pressedWhileOpen[slot] && !open)
|
||||
{
|
||||
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(pos.X, pos.Y + size.Y + 2));
|
||||
ImGuiNET.ImGui.OpenPopup(PickerIds[slot]);
|
||||
}
|
||||
Picker(slot, items.Length == 0 ? NoneItems : items, Math.Clamp(selected, 0, Math.Max(0, items.Length - 1)), kind, items.Length > 0);
|
||||
}
|
||||
|
||||
private void Picker(int slot, string[] items, int selected, int kind, bool real)
|
||||
{
|
||||
// Same look as the Avalonia picker: 200 wide, teal border, radius 6.
|
||||
float maxH = Math.Min(items.Length * 26 + 12, Math.Max(60,
|
||||
ImGuiNET.ImGui.GetIO().DisplaySize.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - 20));
|
||||
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(200, maxH));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 6f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupBorderSize, 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(2, 2));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup(PickerIds[slot]);
|
||||
ImGuiNET.ImGui.PopStyleVar(4);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (!open) return;
|
||||
_pickerShownFrame[slot] = ImGuiNET.ImGui.GetFrameCount();
|
||||
|
||||
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
for (int i = 0; i < items.Length; i++)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
bool isSel = i == selected;
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (ItemButton("##item", p, new Vector2(w, 24), items[i], isSel ? TealSoft : BtnFill, isSel ? Teal : White))
|
||||
{
|
||||
if (real) RynthAiCommands.SelectProfile(kind, i);
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
|
||||
private static bool ItemButton(string id, Vector2 pos, Vector2 size, string text, uint bg, uint fg)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
|
||||
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(bg) : bg;
|
||||
dl.AddRectFilled(pos, pos + size, fill, 3);
|
||||
dl.AddRect(pos, pos + size, BtnBord, 3);
|
||||
ImFontPtr f = ImGuiFonts.Get(UiFont.Dash11);
|
||||
dl.PushClipRect(pos, pos + size, true);
|
||||
dl.AddText(f, f.FontSize, pos + new Vector2(8, (size.Y - f.FontSize) * 0.5f), fg, text);
|
||||
dl.PopClipRect();
|
||||
return clicked;
|
||||
}
|
||||
|
||||
// ── Control row: (ON/OFF) combat, buffing, nav, looting, meta ... force rebuff ──
|
||||
|
||||
private const float Square = 24, SquareStep = 27, RowPad = 3;
|
||||
|
||||
private void ControlRow(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, bool minimized, uint boxBg)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float top = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
float bottom = top + Square + 2 * RowPad;
|
||||
dl.AddRectFilled(new Vector2(x0, top), new Vector2(x0 + width, bottom), boxBg, 3);
|
||||
dl.AddRect(new Vector2(x0, top), new Vector2(x0 + width, bottom), BtnBord, 3);
|
||||
|
||||
float x = x0 + 5, y = top + RowPad;
|
||||
// Macro start/stop: a square like the toggles, green with a Stop glyph while running.
|
||||
{
|
||||
bool on = raw.MacroRunning;
|
||||
if (IconButton("##macro", new Vector2(x, y), new Vector2(Square, Square), on ? PhosphorIcons.Stop : PhosphorIcons.Play,
|
||||
UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, 3))
|
||||
RynthAiCommands.ToggleMacro();
|
||||
ImGuiNET.ImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it.");
|
||||
x += SquareStep + 6;
|
||||
}
|
||||
Toggle("##t_combat", PhosphorIcons.Sword, raw.CombatEnabled, 0, new Vector2(x, y), "Combat");
|
||||
x += SquareStep;
|
||||
Toggle("##t_buff", PhosphorIcons.Sparkle, raw.BuffingEnabled, 1, new Vector2(x, y), "Buffing");
|
||||
x += SquareStep;
|
||||
Toggle("##t_nav", PhosphorIcons.SneakerMove, raw.NavigationEnabled, 2, new Vector2(x, y), "Navigation");
|
||||
x += SquareStep;
|
||||
Toggle("##t_loot", PhosphorIcons.Bag, raw.LootingEnabled, 3, new Vector2(x, y), "Looting");
|
||||
x += SquareStep;
|
||||
Toggle("##t_meta", PhosphorIcons.Code, raw.MetaEnabled, 4, new Vector2(x, y), "Meta (the macro rules)");
|
||||
x += SquareStep;
|
||||
|
||||
// The pickers fold out from a caret left of FR (expanded mode, while folded away).
|
||||
const float caretW = 16f;
|
||||
bool caret = !minimized && !RynthAiDashboardState.ShowFiles;
|
||||
float frX = x0 + width - 5 - Square;
|
||||
if (caret)
|
||||
{
|
||||
if (IconButton("##files_open", new Vector2(frX - 4 - caretW, y), new Vector2(caretW, Square), PhosphorIcons.CaretDown,
|
||||
UiFont.Dash11, BtnFill, Teal, BtnBord, 2))
|
||||
{
|
||||
RynthAiDashboardState.SetFilesModeSize(false, _winLogical.X, _winLogical.Y);
|
||||
RynthAiDashboardState.SetShowFiles(true);
|
||||
_modeFlip = true;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") +
|
||||
"\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") +
|
||||
"\n\nClick to show the Profile, Nav, Loot and Meta pickers.");
|
||||
}
|
||||
|
||||
// What the bot is doing, always in view (every mode, minimized too): between the toggles and FR.
|
||||
{
|
||||
ImFontPtr af = ImGuiFonts.Get(UiFont.Dash10);
|
||||
float ax = x + 2, aRight = (caret ? frX - 4 - caretW : frX) - 6;
|
||||
if (aRight - ax > 20)
|
||||
{
|
||||
string activity = view?.BotActivityText ?? "Idle";
|
||||
float ay = y + (Square - af.FontSize) * 0.5f;
|
||||
dl.PushClipRect(new Vector2(ax, y), new Vector2(aRight, y + Square), true);
|
||||
dl.AddText(af, af.FontSize, new Vector2(ax, ay), Amber, activity);
|
||||
dl.PopClipRect();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ax, y));
|
||||
ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, Square));
|
||||
ImGuiNET.ImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + (view?.MetaStateText ?? "Default"));
|
||||
}
|
||||
}
|
||||
|
||||
// Force rebuff, set apart at the right (DrakBot's place for it).
|
||||
if (IconButton("##fr", new Vector2(x0 + width - 5 - Square, y), new Vector2(Square, Square), PhosphorIcons.ArrowsClockwise,
|
||||
UiFont.Dash14, FrFill, Amber, BtnBord, 3))
|
||||
RynthAiCommands.ForceRebuff();
|
||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
|
||||
RynthAiCommands.CancelForceRebuff();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Force rebuff (FR): recast all buffs. Right-click: cancel.");
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, bottom));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(width, 0));
|
||||
}
|
||||
|
||||
private void Toggle(string id, string icon, bool on, int subsystem, Vector2 pos, string name)
|
||||
{
|
||||
if (IconButton(id, pos, new Vector2(Square, Square), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, 3))
|
||||
RynthAiCommands.SetSubsystemEnabled(subsystem, !on);
|
||||
ImGuiNET.ImGui.SetItemTooltip(on ? name + " on. Click to turn it off." : name + " off. Click to turn it on.");
|
||||
}
|
||||
|
||||
// ── Launchers: one row of icon buttons ──────────────────────────────
|
||||
|
||||
private const float LauncherH = 22, LauncherGap = 2;
|
||||
|
||||
private void Launchers(float x0, float width)
|
||||
{
|
||||
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
const int buttons = 8;
|
||||
float bw = MathF.Floor((width - buttons * LauncherGap) / buttons);
|
||||
// Short labels only when every button has room for its icon and label.
|
||||
bool labels = bw >= 68;
|
||||
float x = x0;
|
||||
|
||||
Launcher("##l_meta", PhosphorIcons.ListChecks, "Meta", "Meta: the macro rules", x, y, bw, labels, () => PanelRouter.Toggle("Meta"));
|
||||
x += bw + LauncherGap;
|
||||
Launcher("##l_lua", PhosphorIcons.FileCode, "Lua", "Lua scripts", x, y, bw, labels, () => PanelRouter.Toggle("Lua"));
|
||||
x += bw + LauncherGap;
|
||||
// Monsters opens the Damage panel (the basic Monsters panel and its
|
||||
// Simple/Advanced chip were retired 2026-10-01).
|
||||
Launcher("##l_mon", PhosphorIcons.Skull, "Monsters", "Monsters: weapons, spells and rules per monster (the Damage panel)",
|
||||
x, y, bw, labels, PanelRouter.ToggleMonsters);
|
||||
x += bw + LauncherGap;
|
||||
Launcher("##l_set", PhosphorIcons.Gear, "Settings", "Settings", x, y, bw, labels, () => PanelRouter.Toggle("Settings"));
|
||||
x += bw + LauncherGap;
|
||||
Launcher("##l_nav", PhosphorIcons.MapTrifold, "Nav", "Nav: routes", x, y, bw, labels, () => PanelRouter.Toggle("Nav"));
|
||||
x += bw + LauncherGap;
|
||||
Launcher("##l_map", PhosphorIcons.MapPin, "Map", "Dungeon Map (shows while you're in a dungeon)", x, y, bw, labels,
|
||||
() => PanelRouter.Toggle(DungeonMapFace.Title));
|
||||
x += bw + LauncherGap;
|
||||
Launcher("##l_items", PhosphorIcons.Backpack, "Items", "Items", x, y, bw, labels, () => PanelRouter.Toggle("Items"));
|
||||
x += bw + LauncherGap;
|
||||
Launcher("##l_patrol", PhosphorIcons.Footprints, "Patrol",
|
||||
"Patrol. Left-click: start dungeon patrol. Right-click: routes & recorded hazards.", x, y, bw, labels,
|
||||
() => RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}"));
|
||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
|
||||
{
|
||||
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1));
|
||||
ImGuiNET.ImGui.OpenPopup("##patrol");
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH));
|
||||
}
|
||||
|
||||
private void Launcher(string id, string icon, string label, string tooltip, float x, float y, float w, bool showLabel, Action? onClick)
|
||||
{
|
||||
var pos = new Vector2(x, y);
|
||||
var size = new Vector2(Math.Max(10, w), LauncherH);
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
|
||||
ImGuiNET.ImGui.SetItemTooltip(tooltip);
|
||||
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill;
|
||||
dl.AddRectFilled(pos, pos + size, fill, 3);
|
||||
dl.AddRect(pos, pos + size, BtnBord, 3);
|
||||
|
||||
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Dash14);
|
||||
if (showLabel)
|
||||
{
|
||||
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Dash9);
|
||||
const float iconBox = 16;
|
||||
PhosphorIcons.DrawCentered(dl, iconFont, icon, pos + new Vector2(4, 0), new Vector2(iconBox, LauncherH), Mute);
|
||||
dl.PushClipRect(pos, pos + size, true);
|
||||
dl.AddText(f9, f9.FontSize, new Vector2(pos.X + 4 + iconBox + 4, pos.Y + (LauncherH - f9.FontSize) * 0.5f), Mute, label);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
else
|
||||
{
|
||||
PhosphorIcons.DrawCentered(dl, iconFont, icon, pos, size, Mute);
|
||||
}
|
||||
if (clicked && onClick != null)
|
||||
{
|
||||
onClick();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Footer: FPS | version | uptime ─────────────────────────────────────
|
||||
|
||||
private void Footer(RynthAiView? view, float x0, float width)
|
||||
{
|
||||
int fps = (int)MathF.Round(D3D9.EndSceneHook.MeasuredFps);
|
||||
if (fps != _fpsShown) { _fpsShown = fps; _fpsText = fps > 0 ? $"FPS {fps}" : "FPS —"; }
|
||||
DateTime started = EntryPoint.InitStartedUtc;
|
||||
if (started != DateTime.MinValue)
|
||||
{
|
||||
TimeSpan up = DateTime.UtcNow - started;
|
||||
long secs = (long)up.TotalSeconds;
|
||||
if (secs != _upShown)
|
||||
{
|
||||
_upShown = secs;
|
||||
_upText = up.TotalHours >= 1 ? $"Up {(int)up.TotalHours}:{up.Minutes:D2}:{up.Seconds:D2}" : $"Up {up.Minutes}:{up.Seconds:D2}";
|
||||
}
|
||||
}
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10);
|
||||
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
float fpsW = CalcWidth(f10, _fpsText), upW = CalcWidth(f10, _upText);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, y), Mute, _fpsText);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0 + width - upW, y), Mute, _upText);
|
||||
|
||||
// The version between them: centred when there's room, else after FPS, clipped short of the uptime.
|
||||
string version = view?.Version ?? string.Empty;
|
||||
if (version.Length > 0)
|
||||
{
|
||||
float left = x0 + fpsW + 8, right = x0 + width - upW - 8;
|
||||
if (right > left)
|
||||
{
|
||||
float vw = CalcWidth(f10, version);
|
||||
float vx = x0 + (width - vw) * 0.5f;
|
||||
if (vx < left || vx + vw > right) vx = left;
|
||||
dl.PushClipRect(new Vector2(left, y), new Vector2(right, y + f10.FontSize + 2), true);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(vx, y), Mute, version);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + f10.FontSize + 2));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(width, 0));
|
||||
}
|
||||
|
||||
// ── Bars (bottom): player vitals, then the target ──────────────────────
|
||||
|
||||
private const float VitalsH = 14 + 3 + 14 + 3 + 14;
|
||||
|
||||
private void Bars(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, uint boxBg)
|
||||
{
|
||||
bool vitals = RynthAiDashboardState.ShowVitals, target = RynthAiDashboardState.ShowTargetBar;
|
||||
if (!vitals && !target) return;
|
||||
Gap(4);
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImFontPtr f11 = ImGuiFonts.Get(UiFont.Dash11), f10 = ImGuiFonts.Get(UiFont.Dash10);
|
||||
// The target's stamina/mana rows are held while that option is on, so they
|
||||
// don't grow the box (and the window) as targets come and go.
|
||||
bool subRows = raw.ShowTargetStaminaMana;
|
||||
float targetH = f11.FontSize + 2 + 3 + 12 + (subRows ? 2 * (13 + 3) - 3 : 0);
|
||||
float top = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
float height = 5 + (vitals ? VitalsH : 0) + (vitals && target ? 6 : 0) + (target ? targetH : 0) + 4;
|
||||
var tl = new Vector2(x0, top);
|
||||
var br = new Vector2(x0 + width, top + height);
|
||||
dl.AddRectFilled(tl, br, boxBg, 3);
|
||||
dl.AddRect(tl, br, BtnBord, 3);
|
||||
|
||||
float rx = x0 + 5, rw = width - 10, ry = top + 5;
|
||||
if (vitals)
|
||||
{
|
||||
VitalRow(dl, rx, ry, rw, PhosphorIcons.Heart, view?.Health ?? default, Hp, f10); ry += 14 + 3;
|
||||
VitalRow(dl, rx, ry, rw, PhosphorIcons.Lightning, view?.Stamina ?? default, Green, f10); ry += 14 + 3;
|
||||
VitalRow(dl, rx, ry, rw, PhosphorIcons.Drop, view?.Mana ?? default, Mana, f10); ry += 14;
|
||||
if (target) ry += 6;
|
||||
}
|
||||
if (target)
|
||||
{
|
||||
// Crosshair + name | health, then the 15-segment bar.
|
||||
string hpText = raw.TargetHealthDisplay;
|
||||
float hpW = CalcWidth(f11, hpText);
|
||||
float iconW = CalcWidth(f11, PhosphorIcons.Crosshair);
|
||||
dl.AddText(f11, f11.FontSize, new Vector2(rx, ry), Mute, PhosphorIcons.Crosshair);
|
||||
dl.PushClipRect(new Vector2(rx, ry), new Vector2(rx + rw - hpW - 4, ry + f11.FontSize + 2), true);
|
||||
dl.AddText(f11, f11.FontSize, new Vector2(rx + iconW + 3, ry), TextDim, view?.TargetHeadline ?? "NO TARGET");
|
||||
dl.PopClipRect();
|
||||
dl.AddText(f11, f11.FontSize, new Vector2(rx + rw - hpW, ry), White, hpText);
|
||||
ry += f11.FontSize + 2 + 3;
|
||||
|
||||
// 15-segment gradient bar, 10 high, 2 px between segments.
|
||||
int lit = view?.TargetSegmentsLit ?? 0;
|
||||
float segW = (rw - 2 * (RynthAiView.Segments - 1)) / RynthAiView.Segments;
|
||||
for (int i = 0; i < RynthAiView.Segments; i++)
|
||||
{
|
||||
float sx = rx + i * (segW + 2);
|
||||
dl.AddRectFilled(new Vector2(sx, ry + 1), new Vector2(sx + segW, ry + 11), i < lit ? SegmentColors[i] : BarBg, 1);
|
||||
}
|
||||
ry += 12;
|
||||
|
||||
if (subRows)
|
||||
{
|
||||
bool shown = view != null && view.ShowTargetSubBars;
|
||||
ry += 3;
|
||||
CompactBar(dl, rx, ry, rw, shown ? view!.TargetStamina : default, Green, f10); ry += 13 + 3;
|
||||
CompactBar(dl, rx, ry, rw, shown ? view!.TargetMana : default, Mana, f10);
|
||||
}
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, top + height));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(width, 0));
|
||||
}
|
||||
|
||||
private static void CompactBar(ImDrawListPtr dl, float x, float y, float w, VitalView bar, uint color, ImFontPtr font)
|
||||
{
|
||||
var a = new Vector2(x, y + 1);
|
||||
var b = new Vector2(x + w, y + 12);
|
||||
dl.AddRectFilled(a, b, BarBg, 2);
|
||||
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 2);
|
||||
dl.AddText(font, font.FontSize, new Vector2(x + 4, y + 1 + (11 - font.FontSize) * 0.5f), White, bar.Text ?? "");
|
||||
}
|
||||
|
||||
private static void VitalRow(ImDrawListPtr dl, float x, float y, float w, string icon, VitalView bar, uint color, ImFontPtr font)
|
||||
{
|
||||
var a = new Vector2(x, y + 1);
|
||||
var b = new Vector2(x + w, y + 14);
|
||||
dl.AddRectFilled(a, b, BarBg, 6);
|
||||
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 6);
|
||||
float ty = y + 1 + (13 - font.FontSize) * 0.5f;
|
||||
dl.AddText(font, font.FontSize, new Vector2(x + 4, ty), Mute, icon);
|
||||
dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? "");
|
||||
}
|
||||
|
||||
// ── Patrol flyout (right-click Patrol) ────────────────────────────────
|
||||
|
||||
private void PatrolPopup()
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
|
||||
ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(260, 0), new Vector2(260, 376));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##patrol");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
|
||||
if (open != _patrolOpen)
|
||||
{
|
||||
_patrolOpen = open;
|
||||
if (open) { UiSources.Patrol.Subscribe(); UiSources.Patrol.RequestRefresh(); }
|
||||
else UiSources.Patrol.Unsubscribe();
|
||||
}
|
||||
if (!open) return;
|
||||
|
||||
var snap = UiSources.Patrol.Current;
|
||||
PatrolInfo info = snap?.Value ?? new PatrolInfo();
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash10));
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash11));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), PhosphorIcons.Footprints + " PATROL & ROUTES");
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
||||
Section("THIS DUNGEON");
|
||||
if (info.InDungeon)
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{info.CurrentLandblock} · {info.CurrentHazards} hazard cell(s)");
|
||||
if (info.CurrentHazards > 0)
|
||||
{
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (Mini("Clear##cur"))
|
||||
RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{info.CurrentLandblock}\"}}", refreshPatrol: true);
|
||||
}
|
||||
if (Mini(MarkHazardLabel))
|
||||
RynthAiCommands.SendNavCommand("{\"Cmd\":\"markHazardHere\"}", refreshPatrol: true);
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (Mini("Unmark"))
|
||||
RynthAiCommands.SendNavCommand("{\"Cmd\":\"unmarkHazardHere\"}", refreshPatrol: true);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, RynthTheme.Vec(0xFFB8C8D8));
|
||||
ImGuiNET.ImGui.TextWrapped("Stand on the lava/acid, click Mark, then re-run Patrol.");
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
else
|
||||
{
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "Not in a dungeon.");
|
||||
}
|
||||
|
||||
Section($"RECORDED HAZARDS ({info.Dungeons.Length})");
|
||||
if (info.Dungeons.Length == 0)
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "None recorded yet.");
|
||||
for (int i = 0; i < info.Dungeons.Length; i++)
|
||||
{
|
||||
DungeonHazards d = info.Dungeons[i];
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{d.Landblock} · {d.Cells} cell(s)");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (Mini("Clear"))
|
||||
RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}", refreshPatrol: true);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
if (info.Dungeons.Length > 0 && Mini("Clear all recorded hazards"))
|
||||
RynthAiCommands.SendNavCommand("{\"Cmd\":\"clearHazardsAll\"}", refreshPatrol: true);
|
||||
|
||||
Section($"SAVED ROUTES ({info.Routes.Length})");
|
||||
if (info.Routes.Length == 0)
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "No .nav routes saved.");
|
||||
foreach (string name in info.Routes)
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "• " + name);
|
||||
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
|
||||
private const string MarkHazardLabel = PhosphorIcons.Warning + " Mark cell as hazard";
|
||||
|
||||
private static void Section(string text)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), text);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
private static bool Mini(string label)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, BtnFill);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, Lighten(BtnFill));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonActive, Darken(BtnFill));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 2f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 1));
|
||||
bool clicked = ImGuiNET.ImGui.Button(label);
|
||||
ImGuiNET.ImGui.PopStyleVar(3);
|
||||
ImGuiNET.ImGui.PopStyleColor(5);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
return clicked;
|
||||
}
|
||||
|
||||
// ── Shared helpers ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Draws the Avalonia face's flat button frame; returns true on left click.</summary>
|
||||
private static bool ButtonFrame(string id, Vector2 pos, Vector2 size, uint bg, uint border, float rounding)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight)
|
||||
&& ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Left);
|
||||
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(bg) : bg;
|
||||
dl.AddRectFilled(pos, pos + size, fill, rounding);
|
||||
if (border != 0) dl.AddRect(pos, pos + size, border, rounding);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
/// <summary>A flat button with centred text; returns true on left click.</summary>
|
||||
private static bool Button(string id, Vector2 pos, Vector2 size, string text, UiFont font,
|
||||
uint bg, uint fg, uint border, float rounding)
|
||||
{
|
||||
bool clicked = ButtonFrame(id, pos, size, bg, border, rounding);
|
||||
ImFontPtr f = ImGuiFonts.Get(font);
|
||||
float tw = CalcWidth(f, text);
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(f, f.FontSize, pos + new Vector2((size.X - tw) * 0.5f, (size.Y - f.FontSize) * 0.5f), fg, text);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
/// <summary>A flat button with a Phosphor icon centred on it; returns true on left click.</summary>
|
||||
private static bool IconButton(string id, Vector2 pos, Vector2 size, string icon, UiFont font,
|
||||
uint bg, uint fg, uint border, float rounding)
|
||||
{
|
||||
bool clicked = ButtonFrame(id, pos, size, bg, border, rounding);
|
||||
PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(font), icon, pos, size, fg);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
private static float CalcWidth(ImFontPtr font, string text)
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(font);
|
||||
float w = ImGuiNET.ImGui.CalcTextSize(text).X;
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
return w;
|
||||
}
|
||||
|
||||
private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12);
|
||||
private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0);
|
||||
|
||||
private static uint Scale(uint abgr, float k, int add)
|
||||
{
|
||||
uint a = abgr & 0xFF000000;
|
||||
uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add);
|
||||
uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add);
|
||||
uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add);
|
||||
return a | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
|
||||
private static void Gap(float h) => ImGuiNET.ImGui.Dummy(new Vector2(0, h));
|
||||
|
||||
private static uint[] BuildSegmentColors()
|
||||
{
|
||||
var colors = new uint[RynthAiView.Segments];
|
||||
for (int i = 0; i < colors.Length; i++)
|
||||
{
|
||||
float t = (float)i / (colors.Length - 1);
|
||||
uint r, g, b;
|
||||
if (t < 0.33f) { float f = t / 0.33f; r = 255; g = (uint)(f * 255); b = 0; }
|
||||
else if (t < 0.66f) { float f = (t - 0.33f) / 0.33f; r = (uint)((1f - f) * 255); g = 255; b = 0; }
|
||||
else { float f = (t - 0.66f) / 0.34f; r = 0; g = 255; b = (uint)(f * 255); }
|
||||
colors[i] = C(0xFF000000 | (r << 16) | (g << 8) | b);
|
||||
}
|
||||
return colors;
|
||||
}
|
||||
|
||||
private static readonly RynthAiSnapshot Empty = new();
|
||||
}
|
||||
226
src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs
Normal file
226
src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/RynthNavArrowFace.cs
|
||||
// RynthNav's arrow: a small draggable overlay that points at RynthNav's arrow
|
||||
// target relative to the way you face, with the distance, the compass point
|
||||
// and the target's name (our take on GoArrow's arrow; Digero 2006, Virindi
|
||||
// 2011, MIT). Shown and hidden from the RynthNav panel's Arrow tab; opens by
|
||||
// itself when a command sets the arrow (RynthNavArrowWatch). Works popped out.
|
||||
//
|
||||
// arrow turns with you every frame (the pose snapshot's heading); green
|
||||
// within 30 yd, amber while it points at a portal on a route; a
|
||||
// wand instead of the arrow when the next step is a recall.
|
||||
// text name, distance and compass point, the route step.
|
||||
// buttons pop out, hide; Go (RynthNav walks there) and Stop.
|
||||
//
|
||||
// The target comes from RynthNav's status (UiSources.RynthNav); RynthNav owns
|
||||
// it and decides arrival. AC's render thread: snapshots only, no AC calls, and
|
||||
// strings are rebuilt only when what they show changes.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class RynthNavArrowFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "RynthNav Arrow";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(236, 84), new Vector2(236, 84), PanelChrome.None, Background: 0, Rounding: 6, EdgeToEdge: true),
|
||||
() => new RynthNavArrowFace());
|
||||
|
||||
/// <summary>Shows the overlay (any thread). Only where ImGui faces are drawn.</summary>
|
||||
public static void Show()
|
||||
{
|
||||
if (!ImGuiPanelHost.IsOpen(Title) && PanelRouter.ResolveDockedFace(Title) == PanelFace.ImGui)
|
||||
ImGuiPanelHost.Open(Title);
|
||||
}
|
||||
|
||||
/// <summary>The arrow turns with you: redraw popped out often enough to look smooth.</summary>
|
||||
public int PopOutIdleHz => 20;
|
||||
|
||||
private static readonly uint Glass = RynthTheme.Argb(0xDC0A0F14), Ring = RynthTheme.Argb(0xFF1A2A39);
|
||||
|
||||
private readonly ArrowReadout _read = new();
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.RynthNav.Subscribe();
|
||||
UiSources.RynthNav.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.RynthNav.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
|
||||
if (size.X < 40 || size.Y < 40) return;
|
||||
RynthNavStatus? st = UiSources.RynthNav.Current?.Value;
|
||||
_read.Update(st);
|
||||
|
||||
dl.AddRectFilled(origin, origin + size, Glass, 6);
|
||||
dl.AddRect(origin, origin + size, BtnBord, 6);
|
||||
|
||||
// The arrow, in a ring on the left.
|
||||
float d = size.Y - 12;
|
||||
Vector2 c = origin + new Vector2(6 + d * 0.5f, size.Y * 0.5f);
|
||||
dl.AddCircleFilled(c, d * 0.5f, ShellBg, 32);
|
||||
dl.AddCircle(c, d * 0.5f, Ring, 32, 1.5f);
|
||||
_read.DrawPointer(dl, c, d * 0.5f - 6);
|
||||
|
||||
// Text.
|
||||
float tx = origin.X + d + 14, right = origin.X + size.X - 6;
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f10 = ImGuiFonts.Get(UiFont.Ui10), f9 = ImGuiFonts.Get(UiFont.Ui9);
|
||||
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 46, origin.Y + size.Y), true);
|
||||
dl.AddText(bold, bold.FontSize, new Vector2(tx, origin.Y + 6), Teal, _read.Line1);
|
||||
dl.PopClipRect();
|
||||
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right, origin.Y + size.Y), true);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(tx, origin.Y + 26), Text, _read.Line2);
|
||||
dl.PopClipRect();
|
||||
dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 48, origin.Y + size.Y), true);
|
||||
dl.AddText(f9, f9.FontSize, new Vector2(tx, origin.Y + size.Y - 6 - f9.FontSize - 2), Mute, _read.Line3);
|
||||
dl.PopClipRect();
|
||||
|
||||
// Buttons (before the surface, so they win the hover).
|
||||
const float b = 20, gap = 3;
|
||||
var closePos = new Vector2(right - b, origin.Y + 5);
|
||||
var popPos = closePos - new Vector2(b + gap, 0);
|
||||
if (PanelRouter.CanPopOut)
|
||||
{
|
||||
if (IconButton("##rna_pop", ImGuiPanelHost.PopOutGlyph, popPos, new Vector2(b, b), Mute, BtnFill, font: UiFont.Ui11))
|
||||
ImGuiPanelHost.TogglePopOut(Title);
|
||||
ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip);
|
||||
}
|
||||
if (IconButton("##rna_close", PhosphorIcons.X, closePos, new Vector2(b, b), Mute, BtnFill, font: UiFont.Ui11))
|
||||
ImGuiPanelHost.Close(Title);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Hide the arrow (the RynthNav panel's Arrow tab shows it again)");
|
||||
var stopPos = new Vector2(right - b, origin.Y + size.Y - b - 5);
|
||||
var goPos = stopPos - new Vector2(b + gap, 0);
|
||||
bool canGo = _read.CanGo;
|
||||
if (IconButton("##rna_go", PhosphorIcons.Play, goPos, new Vector2(b, b), Green, BtnFill, enabled: canGo, font: UiFont.Ui11)
|
||||
&& st?.Arrow is RynthNavArrow ar)
|
||||
RynthNavCommands.Go(ar.Final, ar.FinalNs, ar.FinalEw);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Go: RynthNav walks there (with portals and recalls when its routing is on)");
|
||||
if (IconButton("##rna_stop", PhosphorIcons.Stop, stopPos, new Vector2(b, b), Red, BtnFill, font: UiFont.Ui11))
|
||||
RynthNavCommands.Move(5);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Stop walking");
|
||||
|
||||
// Surface: drag moves the overlay (the OS window when popped out).
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(origin);
|
||||
ImGuiNET.ImGui.InvisibleButton("##rna_surface", size);
|
||||
ImGuiPanelHost.DragWindowWithLastItem();
|
||||
if (ImGuiNET.ImGui.IsItemHovered() && _read.Tooltip.Length > 0) ImGuiNET.ImGui.SetItemTooltip(_read.Tooltip);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the arrow shows this frame: the target from RynthNav's status, your position and
|
||||
/// heading from the pose snapshot. Shared by the overlay and the panel's Arrow tab. AC's
|
||||
/// render thread; the text is rebuilt only when what it shows changes.
|
||||
/// </summary>
|
||||
internal sealed class ArrowReadout
|
||||
{
|
||||
public string Line1 = "No arrow", Line2 = "", Line3 = "", Tooltip = "";
|
||||
public bool HasTarget, CanGo, Pointing;
|
||||
public float Relative; // degrees clockwise from straight ahead
|
||||
public double Distance = double.NaN;
|
||||
public string Kind = "";
|
||||
|
||||
private RynthNavArrow? _arrow;
|
||||
private int _distKey = int.MinValue, _compassKey = -1;
|
||||
private bool _wasInDungeon, _wasAvailable = true;
|
||||
private string _compass = "";
|
||||
|
||||
private static readonly uint NearCol = RynthTheme.Argb(0xFF40D973);
|
||||
|
||||
public void Update(RynthNavStatus? st)
|
||||
{
|
||||
RynthNavArrow? a = st?.Arrow;
|
||||
bool available = st == null || st.Travel;
|
||||
if (!ReferenceEquals(a, _arrow) || available != _wasAvailable)
|
||||
{
|
||||
_arrow = a;
|
||||
_wasAvailable = available;
|
||||
_distKey = int.MinValue;
|
||||
_compassKey = -1;
|
||||
HasTarget = a != null;
|
||||
Kind = a?.Kind ?? "";
|
||||
CanGo = a != null && (a.FinalNs != 0 || a.FinalEw != 0);
|
||||
Line1 = a == null ? (available ? "No arrow" : "RynthNav is too old for the arrow") : a.Name;
|
||||
Line3 = a == null ? (available ? "Atlas, chat coords or /rnav arrow" : "")
|
||||
: a.Kind == "recall" ? (a.StepText.Length > 0 ? a.StepText : "cast the recall")
|
||||
: a.Kind == "portal" ? "walk into the portal" + (a.Steps > 1 ? $" · step {a.Step}/{a.Steps}" : "")
|
||||
: a.Steps > 1 ? $"step {a.Step}/{a.Steps}" : a.Type;
|
||||
Tooltip = a == null ? "" : (a.Kind == "recall" ? "Cast " + a.Name : a.Name + " " + a.CoordText)
|
||||
+ (a.Steps > 1 ? "\nOn the way to " + a.Final : "");
|
||||
Line2 = a == null ? "" : a.Kind == "recall" ? "Cast " + a.Name : a.CoordText;
|
||||
}
|
||||
Pointing = false;
|
||||
if (a == null || a.Kind == "recall" || !a.OnMap) return;
|
||||
if (!RynthNavAtlas.TryPlayerPos(out double ns, out double ew, out bool onMap, out _)) return;
|
||||
if (!onMap)
|
||||
{
|
||||
if (!_wasInDungeon) { Line2 = "in a dungeon: no direction"; _wasInDungeon = true; _distKey = int.MinValue; }
|
||||
return;
|
||||
}
|
||||
_wasInDungeon = false;
|
||||
Distance = RynthNavAtlas.Distance(ns, ew, a.Ns, a.Ew);
|
||||
double bearing = RynthNavAtlas.Bearing(ns, ew, a.Ns, a.Ew);
|
||||
int compassKey = (int)Math.Round(((bearing % 360.0) + 360.0) % 360.0 / 22.5) & 15;
|
||||
if (compassKey != _compassKey) { _compassKey = compassKey; _compass = RynthNavAtlas.CompassPoint(bearing); _distKey = int.MinValue; }
|
||||
int key = Distance < 1000 ? (int)Math.Round(Distance) : 100000 + (int)Math.Round(Distance / 100);
|
||||
if (key != _distKey)
|
||||
{
|
||||
_distKey = key;
|
||||
Line2 = RynthNavStatus.Yards(Distance) + " " + _compass;
|
||||
}
|
||||
if (TryHeading(out float heading))
|
||||
{
|
||||
Relative = (float)bearing - heading;
|
||||
Pointing = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The pointer at <paramref name="c"/>: an arrow, a wand for a recall, a dot when there's nothing.</summary>
|
||||
public void DrawPointer(ImDrawListPtr dl, Vector2 c, float r)
|
||||
{
|
||||
if (!HasTarget) { dl.AddCircleFilled(c, 3, FaceKit.Mute); return; }
|
||||
if (Kind == "recall")
|
||||
{
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.MagicWand, c - new Vector2(r, r), new Vector2(2 * r, 2 * r), FaceKit.Amber);
|
||||
return;
|
||||
}
|
||||
if (!Pointing) { PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Compass, c - new Vector2(r, r), new Vector2(2 * r, 2 * r), FaceKit.Mute); return; }
|
||||
uint col = Kind == "portal" ? FaceKit.Amber : Distance <= 30 ? NearCol : FaceKit.Teal;
|
||||
float rad = Relative * (MathF.PI / 180f);
|
||||
float s = MathF.Sin(rad), co = MathF.Cos(rad);
|
||||
Vector2 tip = Rot(c, 0, -r, s, co), left = Rot(c, -0.62f * r, 0.78f * r, s, co),
|
||||
notch = Rot(c, 0, 0.36f * r, s, co), right = Rot(c, 0.62f * r, 0.78f * r, s, co);
|
||||
dl.AddTriangleFilled(tip, left, notch, col);
|
||||
dl.AddTriangleFilled(tip, notch, right, col);
|
||||
}
|
||||
|
||||
private static Vector2 Rot(Vector2 c, float x, float y, float s, float co) =>
|
||||
new(c.X + x * co - y * s, c.Y + x * s + y * co);
|
||||
|
||||
/// <summary>Your heading this frame (compass degrees) from the pose snapshot; no AC call (SenseFace's way).</summary>
|
||||
private static bool TryHeading(out float heading)
|
||||
{
|
||||
heading = 0;
|
||||
if (!PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out _, out _, out _, out _, out float qw, out float qz, out bool valid, out float h))
|
||||
return false;
|
||||
if (valid) { heading = h; return true; }
|
||||
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
|
||||
heading = (float)((-yaw % 360.0 + 720.0) % 360.0);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
1028
src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs
Normal file
1028
src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs
Normal file
File diff suppressed because it is too large
Load diff
103
src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs
Normal file
103
src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/ScriptWindowFace.cs
|
||||
// Script windows (API v71): the panel face of one window a plugin submitted
|
||||
// (UI/ScriptWindows). Hosted by ImGuiPanelHost like any panel (frame, saved
|
||||
// placement, error isolation, input capture); Draw is the replay.
|
||||
// Design: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §3, §2.5 (Geometry).
|
||||
//
|
||||
// Before the replay, inside the host's body child, the face reports the
|
||||
// window's geometry (position, size, content region, cursor start, focused,
|
||||
// hovered) in logical units at UI scale 1, as a Geometry event when a value
|
||||
// moved by more than half a unit or a flag changed.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed unsafe class ScriptWindowFace : IImGuiPanel
|
||||
{
|
||||
private const float GeometryEpsilon = 0.5f;
|
||||
|
||||
private readonly ScriptWindow _window;
|
||||
|
||||
public ScriptWindowFace(ScriptWindow window) => _window = window;
|
||||
|
||||
public bool ClickThrough => (_window.Flags & WindowFlags.ClickThrough) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Opened. Unless the owner asked for it (ScriptWindow.ExpectOpen), the player
|
||||
/// opened it (bar, /rc ui open): the owner hears it once so its own visible flag
|
||||
/// follows, and its flag stays stale until it has seen this event (§3.3). AC thread.
|
||||
/// </summary>
|
||||
public void OnShown() => NoteVisibility(visible: true);
|
||||
|
||||
/// <summary>Closed: as OnShown; a close the owner didn't ask for is the player's X unless the bar said otherwise.</summary>
|
||||
public void OnHidden() => NoteVisibility(visible: false);
|
||||
|
||||
private void NoteVisibility(bool visible)
|
||||
{
|
||||
ScriptWindow w = _window;
|
||||
bool expected;
|
||||
if (visible) { expected = w.ExpectOpen; w.ExpectOpen = false; }
|
||||
else { expected = w.ExpectClose; w.ExpectClose = false; }
|
||||
int reason = w.PendingReason;
|
||||
w.PendingReason = 0;
|
||||
if (w.Removed || expected) return;
|
||||
byte why = reason != 0 ? (byte)reason
|
||||
: visible ? VisibilityReason.BarOrCommand : VisibilityReason.PlayerClose;
|
||||
w.PlayerVisibilitySeq = w.Owner.Events.Visibility(w.Hash, visible, why);
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
try
|
||||
{
|
||||
ScriptWindowMetrics.Refresh();
|
||||
ReportGeometry();
|
||||
ScriptWindowReplay.Draw(_window);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Queues a Geometry event when the body's geometry or focus/hover changed. AC thread.</summary>
|
||||
private void ReportGeometry()
|
||||
{
|
||||
float s = EngineFrameController.FontScale;
|
||||
if (!(s > 0f) || !float.IsFinite(s)) s = 1f;
|
||||
Vector2 pos, size, avail, cursor;
|
||||
ImGuiNative.igGetWindowPos(&pos);
|
||||
ImGuiNative.igGetWindowSize(&size);
|
||||
ImGuiNative.igGetContentRegionAvail(&avail);
|
||||
ImGuiNative.igGetCursorPos(&cursor);
|
||||
uint flags = 0;
|
||||
if (ImGuiNative.igIsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows) != 0) flags |= ScriptGeometry.Focused;
|
||||
if (ImGuiNative.igIsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows) != 0) flags |= ScriptGeometry.Hovered;
|
||||
var g = new ScriptGeometry
|
||||
{
|
||||
Pos = pos / s,
|
||||
Size = size / s,
|
||||
Avail = avail / s,
|
||||
Cursor = cursor / s,
|
||||
Flags = flags,
|
||||
};
|
||||
ScriptWindow w = _window;
|
||||
if (w.GeometrySent && g.Flags == w.LastGeometry.Flags
|
||||
&& !Moved(g.Pos, w.LastGeometry.Pos) && !Moved(g.Size, w.LastGeometry.Size)
|
||||
&& !Moved(g.Avail, w.LastGeometry.Avail) && !Moved(g.Cursor, w.LastGeometry.Cursor))
|
||||
return;
|
||||
w.LastGeometry = g;
|
||||
w.GeometrySent = true;
|
||||
w.Owner.Events.Geometry(w.Hash, g);
|
||||
}
|
||||
|
||||
private static bool Moved(Vector2 a, Vector2 b) =>
|
||||
MathF.Abs(a.X - b.X) > GeometryEpsilon || MathF.Abs(a.Y - b.Y) > GeometryEpsilon;
|
||||
}
|
||||
430
src/RynthCore.Engine/ImGui/Panels/SenseFace.cs
Normal file
430
src/RynthCore.Engine/ImGui/Panels/SenseFace.cs
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/SenseFace.cs
|
||||
// The Sense panel, our take on Virindi Sense: type a name, and every object
|
||||
// the client knows about anywhere (not just in radar range) whose name
|
||||
// matches shows up here. Engine only, ImGui only.
|
||||
//
|
||||
// add row a text box (Enter adds), Add, the settings gear, the help mark
|
||||
// terms one chip per term: click it to switch it on/off, X removes it
|
||||
// status how many matches among how many known objects (or why none)
|
||||
// rows direction arrow (relative to where you face), name, kind,
|
||||
// distance, compass point, map coordinates; nearest first; a new
|
||||
// match flashes. Click selects it in game, hover for details.
|
||||
// gear a chat line and/or the system beep when a new match appears
|
||||
// (both off by default; they work with the panel closed).
|
||||
//
|
||||
// Data: SenseStore (the list, sense.txt) and UiSources.Sense (the 2 Hz scan on
|
||||
// the pump thread, snapshots only; UI/Data/SenseData.cs). This face only reads
|
||||
// the published view and the player pose snapshot (for the arrows, per frame)
|
||||
// and parks a click's select with AcMainThreadQueue.EnqueueOverlaySelect, the
|
||||
// path the Radar and the nameplates use. AC's render thread; no AC calls, no
|
||||
// file I/O, no per-frame allocation except a hovered row's tooltip.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class SenseFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Sense";
|
||||
|
||||
/// <summary>Registers the face (engine init) and queues the list's load so alerts work before it opens.</summary>
|
||||
public static void Register()
|
||||
{
|
||||
ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(470, 360), new Vector2(300, 220), EdgeToEdge: true, GripInBody: true),
|
||||
() => new SenseFace());
|
||||
SenseStore.EnsureLoadQueued();
|
||||
}
|
||||
|
||||
/// <summary>Arrows turn with you: 10 Hz idle popped out, 30 Hz while a new match flashes.</summary>
|
||||
public int PopOutIdleHz => _flashing ? 30 : 10;
|
||||
|
||||
// ── Layout (px) and palette ──────────────────────────────────────────
|
||||
private const float RowH = 20f, ArrowW = 20f, KindW = 58f, DistW = 64f, DirW = 34f, LocW = 116f, ChipH = 20f;
|
||||
private const long FlashMs = 2500;
|
||||
|
||||
private static readonly uint Purple = RynthTheme.Argb(0xFFBF4DFF), ChipOff = RynthTheme.Argb(0xFF0E161E);
|
||||
|
||||
private const string HelpText =
|
||||
"Sense lists every object the client knows about whose name matches a term on your list, however far away it is.\n\n" +
|
||||
"How far: the client only knows what the server has sent it. That is everything in the landblocks it has loaded " +
|
||||
"around you (outdoors: your landblock and the ones around it, a few hundred yards, far past the radar), or the whole " +
|
||||
"dungeon you are in. Nothing beyond that reaches the client, so no plugin can see it.\n\n" +
|
||||
"Terms ignore case. Without * or ? a name only has to contain the term (drake finds Dragon's Isle Drake). " +
|
||||
"With them the whole name must match: Drake* starts with Drake, ? is any one letter.\n\n" +
|
||||
"The distance shows when you and the object are both outdoors (or in surface buildings), or in the same dungeon. " +
|
||||
"Otherwise the row says elsewhere and gives the landblock.\n\n" +
|
||||
"Click a row to select it in game. Gear: a chat line or a beep when a new match appears.\n" +
|
||||
"/rc sense opens and closes this panel.";
|
||||
|
||||
// ── State ───────────────────────────────────────────────────────────
|
||||
private readonly byte[] _input = new byte[SenseStore.MaxTermLength + 1];
|
||||
private string _message = "";
|
||||
private uint _messageColor;
|
||||
private long _messageUntilMs;
|
||||
private bool _openSettings;
|
||||
private bool _flashing;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
SenseStore.EnsureLoadQueued();
|
||||
UiSources.Sense.Subscribe();
|
||||
UiSources.Sense.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Sense.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
DrawAddRow(w);
|
||||
DrawTerms(w);
|
||||
|
||||
SenseView view = UiSources.Sense.Current?.Value ?? SenseView.Empty;
|
||||
DrawStatus(view);
|
||||
bool showLoc = w - (ArrowW + KindW + DistW + DirW + LocW) >= 110;
|
||||
DrawColumnHeader(w, showLoc);
|
||||
|
||||
float bodyH = Math.Max(40, Remaining(origin, size) - GripOverlap());
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
|
||||
ImGuiNET.ImGui.BeginChild("##sense_rows", new Vector2(w, bodyH));
|
||||
DrawRows(view, showLoc);
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
End(origin, size);
|
||||
|
||||
DrawSettingsPopup();
|
||||
}
|
||||
|
||||
// ── Add row ─────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawAddRow(float w)
|
||||
{
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float h = 22, iconW = 22;
|
||||
string addLabel = PhosphorIcons.Plus + " Add";
|
||||
float addW = ButtonWidth(addLabel);
|
||||
float boxW = Math.Max(60, w - addW - iconW * 2 - 12);
|
||||
|
||||
bool enter = TextBox("##sense_input", _input, start, boxW,
|
||||
PhosphorIcons.MagnifyingGlass + " Name to watch for (* and ? wildcards)", out _,
|
||||
ImGuiInputTextFlags.EnterReturnsTrue, h);
|
||||
bool add = Button("##sense_add", addLabel, new Vector2(start.X + boxW + 4, start.Y), new Vector2(addW, h), Text, BtnFill,
|
||||
enabled: SenseStore.Loaded);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Add the name to the watch list (Enter in the box does the same)");
|
||||
if (enter || add) AddTerm();
|
||||
|
||||
float gx = start.X + boxW + 4 + addW + 4;
|
||||
if (IconButton("##sense_gear", PhosphorIcons.Gear, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill))
|
||||
_openSettings = true;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Alerts");
|
||||
IconButton("##sense_help", PhosphorIcons.Info, new Vector2(gx + iconW + 4, start.Y), new Vector2(iconW, h), Mute, BtnFill);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
{
|
||||
ImGuiNET.ImGui.BeginTooltip();
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetFontSize() * 30);
|
||||
ImGuiNET.ImGui.TextUnformatted(HelpText);
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
NextLine(start, h + 4);
|
||||
}
|
||||
|
||||
private void AddTerm()
|
||||
{
|
||||
string text = Utf8(_input);
|
||||
bool ok = SenseStore.Add(text, out string message);
|
||||
if (ok) WriteUtf8(_input, "");
|
||||
ShowMessage(message, ok ? Mute : Amber);
|
||||
}
|
||||
|
||||
private void ShowMessage(string text, uint color)
|
||||
{
|
||||
_message = text;
|
||||
_messageColor = color;
|
||||
_messageUntilMs = Environment.TickCount64 + 3000;
|
||||
}
|
||||
|
||||
// ── Terms ───────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawTerms(float w)
|
||||
{
|
||||
if (!SenseStore.Loaded)
|
||||
{
|
||||
Label("Loading the watch list...", Mute);
|
||||
return;
|
||||
}
|
||||
SensePattern[] terms = SenseStore.Terms;
|
||||
if (terms.Length == 0)
|
||||
{
|
||||
Label("No names yet: type one above and press Enter.", Mute);
|
||||
return;
|
||||
}
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui11);
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x = start.X, y = start.Y;
|
||||
const float iconW = 18, xW = 16;
|
||||
int toggle = -1, remove = -1;
|
||||
for (int i = 0; i < terms.Length; i++)
|
||||
{
|
||||
SensePattern t = terms[i];
|
||||
float textW = ImGuiNET.ImGui.CalcTextSize(t.Text).X;
|
||||
float chipW = Math.Min(w, iconW + textW + 6 + xW);
|
||||
if (x > start.X && x + chipW > start.X + w) { x = start.X; y += ChipH + 4; }
|
||||
var p = new Vector2(x, y);
|
||||
uint fg = t.Enabled ? Text : Faded(Mute);
|
||||
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##t", new Vector2(chipW - xW, ChipH))) toggle = i;
|
||||
bool hotT = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (hotT)
|
||||
ImGuiNET.ImGui.SetItemTooltip(t.Enabled
|
||||
? (t.IsGlob ? "On: the whole name must match (wildcards). Click to switch off." : "On: names containing this match. Click to switch off.")
|
||||
: "Off. Click to switch on.");
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x + chipW - xW, y));
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##x", new Vector2(xW, ChipH))) remove = i;
|
||||
bool hotX = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (hotX) ImGuiNET.ImGui.SetItemTooltip("Remove");
|
||||
ImGuiNET.ImGui.PopID();
|
||||
|
||||
uint bg = t.Enabled ? BtnFill : ChipOff;
|
||||
if (hotT) bg = Lighten(bg);
|
||||
dl.AddRectFilled(p, p + new Vector2(chipW, ChipH), bg, 3);
|
||||
dl.AddRect(p, p + new Vector2(chipW, ChipH), t.Enabled ? Teal : BtnBord, 3);
|
||||
PhosphorIcons.DrawCentered(dl, iconFont, t.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square,
|
||||
p, new Vector2(iconW, ChipH), t.Enabled ? Teal : fg);
|
||||
dl.PushClipRect(p, p + new Vector2(chipW - xW, ChipH), true);
|
||||
dl.AddText(new Vector2(x + iconW, y + (ChipH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), fg, t.Text);
|
||||
dl.PopClipRect();
|
||||
PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.X, new Vector2(x + chipW - xW, y), new Vector2(xW, ChipH),
|
||||
hotX ? Red : Faded(Mute));
|
||||
x += chipW + 4;
|
||||
}
|
||||
NextLine(start, y - start.Y + ChipH + 4);
|
||||
|
||||
if (toggle >= 0) SenseStore.SetEnabled(toggle, !terms[toggle].Enabled);
|
||||
if (remove >= 0)
|
||||
{
|
||||
ShowMessage($"Stopped watching for \"{terms[remove].Text}\".", Mute);
|
||||
SenseStore.Remove(remove);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Status and header ───────────────────────────────────────────────
|
||||
|
||||
private void DrawStatus(SenseView view)
|
||||
{
|
||||
bool msg = _message.Length > 0 && Environment.TickCount64 < _messageUntilMs;
|
||||
Label(msg ? _message : view.Status.Length > 0 ? view.Status : "Scanning...", msg ? _messageColor : Mute);
|
||||
}
|
||||
|
||||
private static void DrawColumnHeader(float w, bool showLoc)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float ty = p.Y + 1;
|
||||
float nameW = NameWidth(w, showLoc);
|
||||
float x = p.X + ArrowW;
|
||||
dl.AddText(new Vector2(x, ty), Mute, "Name");
|
||||
x += nameW;
|
||||
dl.AddText(new Vector2(x, ty), Mute, "Kind");
|
||||
x += KindW;
|
||||
dl.AddText(new Vector2(x, ty), Mute, "Dist");
|
||||
x += DistW;
|
||||
dl.AddText(new Vector2(x, ty), Mute, "Dir");
|
||||
x += DirW;
|
||||
if (showLoc) dl.AddText(new Vector2(x, ty), Mute, "Location");
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, ImGuiNET.ImGui.GetFontSize() + 2));
|
||||
Separator(w);
|
||||
}
|
||||
|
||||
private static float NameWidth(float w, bool showLoc) =>
|
||||
Math.Max(40, w - ArrowW - KindW - DistW - DirW - (showLoc ? LocW : 0));
|
||||
|
||||
// ── Rows ────────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawRows(SenseView view, bool showLoc)
|
||||
{
|
||||
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
SenseRow[] rows = view.Rows;
|
||||
_flashing = false;
|
||||
if (rows.Length == 0)
|
||||
{
|
||||
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(6, 6);
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(at, Faded(Mute),
|
||||
SenseStore.AnyEnabled ? "Nothing matching is in the client's range right now." : "Switch a term on to start watching.");
|
||||
return;
|
||||
}
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
long now = Environment.TickCount64;
|
||||
uint selected = ClientHelperHooks.GetSelectedItemId();
|
||||
float heading = PlayerHeading(out bool haveHeading);
|
||||
float nameW = NameWidth(bw, showLoc);
|
||||
float fontH = ImGuiNET.ImGui.GetFontSize();
|
||||
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float scroll = ImGuiNET.ImGui.GetScrollY();
|
||||
float visible = ImGuiNET.ImGui.GetWindowHeight();
|
||||
int first = Math.Max(0, (int)(scroll / RowH) - 1);
|
||||
int last = Math.Min(rows.Length, (int)((scroll + visible) / RowH) + 2);
|
||||
int clicked = -1, hovered = -1;
|
||||
|
||||
for (int i = first; i < last; i++)
|
||||
{
|
||||
SenseRow r = rows[i];
|
||||
var p = new Vector2(start.X, start.Y + i * RowH);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(bw, RowH))) clicked = i;
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
if (hot) hovered = i;
|
||||
|
||||
bool isSel = r.Id == selected;
|
||||
uint bg = isSel ? Selected : hot ? Lighten(PanelBg) : (i & 1) == 1 ? RowAlt : 0;
|
||||
if (bg != 0) dl.AddRectFilled(p, p + new Vector2(bw, RowH), bg);
|
||||
if (r.FirstSeenMs != 0)
|
||||
{
|
||||
long age = now - r.FirstSeenMs;
|
||||
if (age >= 0 && age < FlashMs)
|
||||
{
|
||||
_flashing = true;
|
||||
float pulse = 0.5f + 0.5f * MathF.Cos(age * 0.0126f);
|
||||
float a = (1f - age / (float)FlashMs) * (0.2f + 0.35f * pulse);
|
||||
dl.AddRectFilled(p, p + new Vector2(bw, RowH), WithAlpha(Amber, a));
|
||||
}
|
||||
}
|
||||
if (isSel) dl.AddRect(p, p + new Vector2(bw, RowH), Teal);
|
||||
|
||||
Vector2 mid = p + new Vector2(ArrowW * 0.5f, RowH * 0.5f);
|
||||
if (r.Measured && haveHeading && !float.IsNaN(r.Bearing))
|
||||
DrawArrow(dl, mid, r.Bearing - heading, KindColor(r.Kind));
|
||||
else if (r.Measured)
|
||||
dl.AddCircleFilled(mid, 2.5f, KindColor(r.Kind));
|
||||
else
|
||||
dl.AddCircle(mid, 3.5f, Faded(Mute), 12, 1.2f);
|
||||
|
||||
float ty = p.Y + (RowH - fontH) * 0.5f;
|
||||
uint nameCol = r.Measured ? Text : Mute;
|
||||
float x = p.X + ArrowW;
|
||||
Cell(dl, r.Name, x, ty, nameW - 4, nameCol);
|
||||
x += nameW;
|
||||
Cell(dl, SenseSource.KindName(r.Kind), x, ty, KindW - 4, KindColor(r.Kind));
|
||||
x += KindW;
|
||||
Cell(dl, r.DistanceText, x, ty, DistW - 4, r.Measured ? Text : Faded(Mute));
|
||||
x += DistW;
|
||||
Cell(dl, r.CompassText, x, ty, DirW - 4, Mute);
|
||||
x += DirW;
|
||||
if (showLoc) Cell(dl, r.LocationText, x, ty, bw - (x - p.X) - 4, Mute);
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(start);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(bw, rows.Length * RowH));
|
||||
|
||||
if (clicked >= 0)
|
||||
AcMainThreadQueue.EnqueueOverlaySelect(rows[clicked].Id);
|
||||
if (hovered >= 0)
|
||||
{
|
||||
ImGuiNET.ImGui.BeginTooltip();
|
||||
ImGuiNET.ImGui.TextUnformatted(rows[hovered].Tooltip);
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
}
|
||||
|
||||
private static void Cell(ImDrawListPtr dl, string text, float x, float y, float width, uint color)
|
||||
{
|
||||
if (text.Length == 0 || width <= 0) return;
|
||||
dl.PushClipRect(new Vector2(x, y - 2), new Vector2(x + width, y + 40), true);
|
||||
dl.AddText(new Vector2(x, y), color, text);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An arrow pointing <paramref name="degrees"/> clockwise from straight up
|
||||
/// (up = the way you face).
|
||||
/// </summary>
|
||||
private static void DrawArrow(ImDrawListPtr dl, Vector2 c, float degrees, uint color)
|
||||
{
|
||||
float rad = degrees * (MathF.PI / 180f);
|
||||
float s = MathF.Sin(rad), co = MathF.Cos(rad);
|
||||
Vector2 tip = Rot(c, 0, -6.5f, s, co), left = Rot(c, -4.5f, 5f, s, co),
|
||||
notch = Rot(c, 0, 2.5f, s, co), right = Rot(c, 4.5f, 5f, s, co);
|
||||
dl.AddTriangleFilled(tip, left, notch, color);
|
||||
dl.AddTriangleFilled(tip, notch, right, color);
|
||||
}
|
||||
|
||||
private static Vector2 Rot(Vector2 c, float x, float y, float s, float co) =>
|
||||
new(c.X + x * co - y * s, c.Y + x * s + y * co);
|
||||
|
||||
/// <summary>Your heading this frame (compass degrees) from the pose snapshot; no AC call.</summary>
|
||||
private static float PlayerHeading(out bool ok)
|
||||
{
|
||||
ok = PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out _, out _, out _, out _, out float qw, out float qz,
|
||||
out bool headingValid, out float heading);
|
||||
if (!ok) return 0;
|
||||
if (headingValid) return heading;
|
||||
// AC's get_heading not bound yet: the yaw quaternion (ClientObjectHooks' formula).
|
||||
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
|
||||
return (float)((-yaw % 360.0 + 720.0) % 360.0);
|
||||
}
|
||||
|
||||
private static uint KindColor(SenseKind kind) => kind switch
|
||||
{
|
||||
SenseKind.Monster => Red,
|
||||
SenseKind.Npc => Amber,
|
||||
SenseKind.Player => Green,
|
||||
SenseKind.Portal => Purple,
|
||||
SenseKind.Corpse => Mute,
|
||||
_ => Teal,
|
||||
};
|
||||
|
||||
private static uint WithAlpha(uint abgr, float a) =>
|
||||
(abgr & 0x00FFFFFF) | ((uint)Math.Clamp((int)(a * 255f), 0, 255) << 24);
|
||||
|
||||
// ── Settings (gear) ─────────────────────────────────────────────────
|
||||
|
||||
private void DrawSettingsPopup()
|
||||
{
|
||||
if (_openSettings)
|
||||
{
|
||||
_openSettings = false;
|
||||
ImGuiNET.ImGui.OpenPopup("##sense_settings");
|
||||
}
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##sense_settings");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(5);
|
||||
if (!open) return;
|
||||
|
||||
Label("When a new match appears:", Mute);
|
||||
bool chat = SenseStore.AlertChat, beep = SenseStore.AlertBeep;
|
||||
if (ImGuiNET.ImGui.Checkbox("Chat line", ref chat))
|
||||
SenseStore.SetAlerts(chat, beep);
|
||||
ImGuiNET.ImGui.SetItemTooltip("A line in chat such as: Sense: Dragon's Isle Drake 140 yd NE\n" +
|
||||
"(at most three at once; the same object again only after two minutes).");
|
||||
if (ImGuiNET.ImGui.Checkbox("System beep", ref beep))
|
||||
SenseStore.SetAlerts(chat, beep);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Windows' default sound, at most every 3 seconds.");
|
||||
Label("Alerts keep working with the panel closed.", Faded(Mute));
|
||||
Label("Saved in %LocalAppData%\\RynthCore\\sense.txt", Faded(Mute));
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
448
src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs
Normal file
448
src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/SettingsFace.cs
|
||||
// ImGui face of RynthAi's Advanced Settings (docs/IMGUI_PARITY_PLAN.md §2.4).
|
||||
//
|
||||
// Draws SettingsSchema (UI/Data/SettingsData.cs), the same list the Avalonia
|
||||
// face builds from, with that face's look: 150 px tab sidebar, "Advanced
|
||||
// Settings > Tab" header, square toggle dots, - [value] + steppers (typed
|
||||
// values commit on Enter or when the field loses focus, then clamp; bad
|
||||
// input reverts), combo pickers, amber section headers, tooltips.
|
||||
//
|
||||
// Edits a private copy of the hub's settings and saves the whole copy
|
||||
// (SettingsCommands.Save) on each change; a newer fetch replaces the copy
|
||||
// only while no field here is being typed in. Rows that show or hide other
|
||||
// rows need nothing special: visibility is re-evaluated every frame.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class SettingsFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Settings";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(400, 500), new Vector2(320, 240), EdgeToEdge: true),
|
||||
() => new SettingsFace());
|
||||
|
||||
// ── Palette (SettingsPanel's, ARGB) ─────────────────────────────────
|
||||
private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Mute = C(0xFFB8C8D8),
|
||||
TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), PanelBg = C(0xFF141F29), BtnFill = C(0xFF16283A),
|
||||
BtnBord = C(0xFF34587A), ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), TabActive = C(0xFF1A2E42);
|
||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||
|
||||
private static readonly string[] Headers = BuildHeaders();
|
||||
|
||||
private RynthAiSettings _data = new();
|
||||
private long _seenVersion = -1;
|
||||
private int _tab;
|
||||
private bool _editing;
|
||||
|
||||
// Typed-value buffers, one per numeric row (UTF-8, NUL-terminated).
|
||||
private sealed class NumberEdit
|
||||
{
|
||||
public readonly byte[] Buffer = new byte[24];
|
||||
public double Shown = double.NaN;
|
||||
public bool Active; // the box had keyboard focus last frame
|
||||
}
|
||||
private readonly Dictionary<SettingRow, NumberEdit> _edits = new();
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.Settings.Subscribe();
|
||||
UiSources.Settings.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Settings.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
// Take a newer fetch unless a value is being typed in.
|
||||
var snap = UiSources.Settings.Current;
|
||||
if (snap != null && snap.Version != _seenVersion && !_editing)
|
||||
{
|
||||
_seenVersion = snap.Version;
|
||||
_data = snap.Value.Clone();
|
||||
}
|
||||
_editing = false;
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
|
||||
dl.AddRectFilled(origin, origin + size, ShellBg, 4);
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
Sidebar(size.Y);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(150, 0));
|
||||
Content(new Vector2(size.X - 150, size.Y));
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
||||
dl.AddRect(origin, origin + size, BtnBord, 4);
|
||||
}
|
||||
|
||||
// ── Sidebar: one button per tab ────────────────────────────────────────
|
||||
|
||||
private void Sidebar(float height)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
|
||||
ImGuiNET.ImGui.BeginChild("##settings_tabs", new Vector2(150, height), ImGuiChildFlags.AlwaysUseWindowPadding);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
SettingsTab[] tabs = SettingsSchema.Tabs;
|
||||
for (int i = 0; i < tabs.Length; i++)
|
||||
{
|
||||
string tabName = tabs[i].Name;
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##tab", new Vector2(w, 26))) _tab = i;
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
bool sel = i == _tab;
|
||||
dl.AddRectFilled(p, p + new Vector2(w, 26), sel ? TabActive : hot ? Lighten(BtnFill) : BtnFill);
|
||||
dl.AddRect(p, p + new Vector2(w, 26), BtnBord);
|
||||
float ty = p.Y + (26 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
dl.AddText(new Vector2(p.X + 8, ty), sel ? Teal : Mute, TabLabel(tabName));
|
||||
}
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
}
|
||||
|
||||
// ── Content: header + the tab's rows ───────────────────────────────────
|
||||
|
||||
private void Content(Vector2 size)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 6));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 0));
|
||||
ImGuiNET.ImGui.BeginChild("##settings_content", size, ImGuiChildFlags.AlwaysUseWindowPadding);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
if (_tab >= SettingsSchema.Tabs.Length) _tab = 0;
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Headers[_tab]);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
dl.AddLine(lp, lp + new Vector2(w, 0), BtnBord);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
|
||||
|
||||
SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows;
|
||||
for (int i = 0; i < rows.Length; i++)
|
||||
{
|
||||
SettingRow row = rows[i];
|
||||
if (!row.IsVisible(_data)) continue;
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
DrawRow(row, w);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
}
|
||||
|
||||
private void DrawRow(SettingRow row, float w)
|
||||
{
|
||||
switch (row.Kind)
|
||||
{
|
||||
case SettingKind.Bool: BoolRow(row, w); break;
|
||||
case SettingKind.Int:
|
||||
case SettingKind.Float:
|
||||
case SettingKind.Double: NumberRow(row, w); break;
|
||||
case SettingKind.Combo: ComboRow(row, w); break;
|
||||
case SettingKind.Section: Section(row.Label, w); break;
|
||||
case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break;
|
||||
case SettingKind.Note: Note(row.Label, w); break;
|
||||
case SettingKind.CraftingStatus: CraftingStatus(row); break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Changed(SettingRow row, double value)
|
||||
{
|
||||
row.Set!(_data, value);
|
||||
SettingsCommands.Save(_data.Clone());
|
||||
}
|
||||
|
||||
// Square dot + label; the whole row toggles.
|
||||
private void BoolRow(SettingRow row, float w)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
bool on = row.Get!(_data) != 0;
|
||||
float labelW = ImGuiNET.ImGui.CalcTextSize(row.Label).X;
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##b", new Vector2(Math.Min(w, 18 + labelW), 16)))
|
||||
Changed(row, on ? 0 : 1);
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
||||
Tooltip(row);
|
||||
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2);
|
||||
dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
// Label | [-] [value] [+]; the value commits on Enter or focus loss.
|
||||
private void NumberRow(SettingRow row, float w)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
bool isInt = row.Kind == SettingKind.Int;
|
||||
float boxW = isInt ? 52 : 64, boxCol = isInt ? 56 : 68;
|
||||
double value = Math.Clamp(row.Get!(_data), row.Min, row.Max);
|
||||
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float right = p.X + w;
|
||||
dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label);
|
||||
ImGuiNET.ImGui.InvisibleButton("##label", new Vector2(Math.Max(1, w - 40 - boxCol), 22));
|
||||
Tooltip(row);
|
||||
|
||||
float plusX = right - 20, boxX = plusX - boxCol + (boxCol - boxW) * 0.5f, minusX = right - 20 - boxCol - 20;
|
||||
if (StepButton("##minus", new Vector2(minusX + 1, p.Y + 1), PhosphorIcons.Minus))
|
||||
Changed(row, Math.Clamp(value - row.Step, row.Min, row.Max));
|
||||
|
||||
// Typed value (amber on the panel colour).
|
||||
NumberEdit edit = EditFor(row);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(boxX, p.Y + 1));
|
||||
ImGuiNET.ImGui.SetNextItemWidth(boxW);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f);
|
||||
if (!edit.Active && edit.Shown != value)
|
||||
WriteValue(edit, value, isInt);
|
||||
ImGuiNET.ImGui.InputText("##v", edit.Buffer, (uint)edit.Buffer.Length,
|
||||
ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll);
|
||||
bool active = ImGuiNET.ImGui.IsItemActive();
|
||||
edit.Active = active;
|
||||
_editing |= active;
|
||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
if (TryParse(edit.Buffer, out double typed))
|
||||
{
|
||||
double clamped = Math.Clamp(isInt ? Math.Round(typed) : typed, row.Min, row.Max);
|
||||
Changed(row, clamped);
|
||||
WriteValue(edit, clamped, isInt);
|
||||
}
|
||||
else WriteValue(edit, value, isInt); // bad input reverts
|
||||
}
|
||||
ImGuiNET.ImGui.PopStyleVar(3);
|
||||
ImGuiNET.ImGui.PopStyleColor(3);
|
||||
|
||||
if (StepButton("##plus", new Vector2(plusX + 1, p.Y + 1), PhosphorIcons.Plus))
|
||||
Changed(row, Math.Clamp(value + row.Step, row.Min, row.Max));
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
private NumberEdit EditFor(SettingRow row)
|
||||
{
|
||||
if (!_edits.TryGetValue(row, out NumberEdit? e))
|
||||
_edits[row] = e = new NumberEdit();
|
||||
return e;
|
||||
}
|
||||
|
||||
private static void WriteValue(NumberEdit edit, double value, bool isInt)
|
||||
{
|
||||
string text = isInt ? ((long)Math.Round(value)).ToString(CultureInfo.InvariantCulture)
|
||||
: value.ToString("G4", CultureInfo.InvariantCulture);
|
||||
int n = Encoding.UTF8.GetBytes(text, 0, text.Length, edit.Buffer, 0);
|
||||
edit.Buffer[Math.Min(n, edit.Buffer.Length - 1)] = 0;
|
||||
edit.Shown = value;
|
||||
}
|
||||
|
||||
private static bool TryParse(byte[] buffer, out double value)
|
||||
{
|
||||
int len = Array.IndexOf(buffer, (byte)0);
|
||||
if (len < 0) len = buffer.Length;
|
||||
return double.TryParse(Encoding.UTF8.GetString(buffer, 0, len), NumberStyles.Float, CultureInfo.InvariantCulture, out value);
|
||||
}
|
||||
|
||||
// Label | [current item]; click opens a 220 px list with the current item highlighted.
|
||||
private void ComboRow(SettingRow row, float w)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
string[] items = row.Items!;
|
||||
int current = Math.Clamp((int)row.Get!(_data), 0, items.Length - 1);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label);
|
||||
|
||||
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Ui10);
|
||||
const float btnW = 160;
|
||||
var bp = new Vector2(p.X + w - btnW, p.Y + 1);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(bp);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##combo", new Vector2(btnW, 20)))
|
||||
{
|
||||
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Max(bp.X + btnW - 220, 0), bp.Y + 20));
|
||||
ImGuiNET.ImGui.OpenPopup("##combo_list");
|
||||
}
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
Tooltip(row);
|
||||
dl.AddRectFilled(bp, bp + new Vector2(btnW, 20), hot ? Lighten(BtnFill) : BtnFill);
|
||||
dl.AddRect(bp, bp + new Vector2(btnW, 20), BtnBord);
|
||||
dl.PushClipRect(bp, bp + new Vector2(btnW - 16, 20), true);
|
||||
dl.AddText(f10, f10.FontSize, bp + new Vector2(4, (20 - f10.FontSize) * 0.5f), TextDim, items[current]);
|
||||
dl.PopClipRect();
|
||||
PhosphorIcons.DrawCentered(dl, f10, PhosphorIcons.CaretDown, bp + new Vector2(btnW - 16, 0), new Vector2(14, 20), Mute);
|
||||
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
|
||||
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(220, items.Length * 21 + 4));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##combo_list");
|
||||
ImGuiNET.ImGui.PopStyleVar(2);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (open)
|
||||
{
|
||||
var pdl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float iw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
for (int i = 0; i < items.Length; i++)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
bool picked = ImGuiNET.ImGui.InvisibleButton("##item", new Vector2(iw, 20));
|
||||
bool ih = ImGuiNET.ImGui.IsItemHovered();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
bool sel = i == current;
|
||||
pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? TabActive : ih ? Lighten(BtnFill) : BtnFill);
|
||||
pdl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord);
|
||||
pdl.AddText(f10, f10.FontSize, ip + new Vector2(6, (20 - f10.FontSize) * 0.5f), sel ? Teal : TextDim, items[i]);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
|
||||
if (picked)
|
||||
{
|
||||
Changed(row, i);
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
private static void Section(string text, float w)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
float h = bold.FontSize + 4;
|
||||
dl.AddRectFilled(p, p + new Vector2(w, h), TabActive);
|
||||
dl.AddText(bold, bold.FontSize, p + new Vector2(4, 2), Amber, text);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, h));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
private static void Note(string text, float w)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
bool small = !text.StartsWith('(');
|
||||
if (small) ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
|
||||
ImGuiNET.ImGui.TextUnformatted(text);
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
if (small) ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
private void CraftingStatus(SettingRow row)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), row.Label);
|
||||
ImGuiNET.ImGui.SameLine(0, 6);
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(_data.MissileCraftingActive ? 0xFFE8B333 : 0xFFB8C8D8), _data.MissileCraftingState);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
if (!string.IsNullOrEmpty(_data.MissileCraftingStatus))
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
|
||||
ImGuiNET.ImGui.TextWrapped(_data.MissileCraftingStatus);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
}
|
||||
|
||||
private static bool StepButton(string id, Vector2 pos, string glyph)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(18, 20));
|
||||
uint bg = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill;
|
||||
dl.AddRectFilled(pos, pos + new Vector2(18, 20), bg);
|
||||
dl.AddRect(pos, pos + new Vector2(18, 20), BtnBord);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(18, 20), TextDim);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
// Tab icons by tab name (SettingsSchema); a tab not listed shows its name alone.
|
||||
private static readonly System.Collections.Generic.Dictionary<string, string> TabIcons = new()
|
||||
{
|
||||
["Display"] = PhosphorIcons.Monitor,
|
||||
["UI"] = PhosphorIcons.AppWindow,
|
||||
["Misc"] = PhosphorIcons.DotsThree,
|
||||
["Recharge"] = PhosphorIcons.BatteryCharging,
|
||||
["Melee Combat"] = PhosphorIcons.Sword,
|
||||
["Spell Combat"] = PhosphorIcons.MagicWand,
|
||||
["Ranges"] = PhosphorIcons.Ruler,
|
||||
["Navigation"] = PhosphorIcons.SneakerMove,
|
||||
["Buffing"] = PhosphorIcons.Sparkle,
|
||||
["Crafting"] = PhosphorIcons.Hammer,
|
||||
["Looting"] = PhosphorIcons.Bag,
|
||||
["Vendoring"] = PhosphorIcons.Storefront,
|
||||
};
|
||||
private static readonly System.Collections.Generic.Dictionary<string, string> TabLabels = new();
|
||||
|
||||
/// <summary>"icon Name", built once per tab.</summary>
|
||||
private static string TabLabel(string name)
|
||||
{
|
||||
if (TabLabels.TryGetValue(name, out string? label)) return label;
|
||||
label = TabIcons.TryGetValue(name, out string? icon) ? icon + " " + name : name;
|
||||
TabLabels[name] = label;
|
||||
return label;
|
||||
}
|
||||
|
||||
private static void Tooltip(SettingRow row)
|
||||
{
|
||||
if (row.Tooltip != null) ImGuiNET.ImGui.SetItemTooltip(row.Tooltip);
|
||||
}
|
||||
|
||||
private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12);
|
||||
private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0);
|
||||
|
||||
private static uint Scale(uint abgr, float k, int add)
|
||||
{
|
||||
uint a = abgr & 0xFF000000;
|
||||
uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add);
|
||||
uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add);
|
||||
uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add);
|
||||
return a | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
|
||||
private static string[] BuildHeaders()
|
||||
{
|
||||
var headers = new string[SettingsSchema.Tabs.Length];
|
||||
for (int i = 0; i < headers.Length; i++)
|
||||
headers[i] = "Advanced Settings > " + SettingsSchema.Tabs[i].Name;
|
||||
return headers;
|
||||
}
|
||||
}
|
||||
226
src/RynthCore.Engine/ImGui/Panels/SkillsData.cs
Normal file
226
src/RynthCore.Engine/ImGui/Panels/SkillsData.cs
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/SkillsData.cs
|
||||
// The Skills panel's static data from client_portal.dat, read once in the
|
||||
// background (UiBackgroundWriter, never AC's thread):
|
||||
//
|
||||
// SkillTable 0x0E000004 id u32, PackedHashTable (u16 count, u16 buckets) of
|
||||
// u32 skill id + SkillBase: description, name (u16 length + bytes, each
|
||||
// padded to 4 from the file start), icon u32, trained cost i32,
|
||||
// specialized cost i32 (total), category u32, chargen use u32,
|
||||
// min level u32 (1 usable untrained, 2 needs training), formula
|
||||
// (W, X, Y, Z, attr1, attr2 u32), upper, lower, learn mod f64.
|
||||
// XpTable 0x0E000018 id u32, counts (attribute, vital, trained,
|
||||
// specialized i32, level u32), then count+1 u32 each for attributes,
|
||||
// vitals, trained and specialized skills, count+1 u64 levels, count+1 u32
|
||||
// skill credits per level.
|
||||
//
|
||||
// Layouts: ACE.DatLoader SkillTable / SkillBase / SkillFormula / XpTable (the
|
||||
// server raises against the same XpTable). Readers take the published
|
||||
// immutable tables; any thread.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
/// <summary>One skill from the portal SkillTable.</summary>
|
||||
internal sealed class SkillDatEntry
|
||||
{
|
||||
public uint Id;
|
||||
public string Name = "";
|
||||
public string Description = "";
|
||||
public uint Icon;
|
||||
public int TrainedCost;
|
||||
public int SpecializedCost;
|
||||
public uint Category; // 1 combat, 2 other, 3 magic
|
||||
public uint MinLevel; // 1 usable untrained, 2 trained or better
|
||||
public uint Attr1, Attr2, Divisor;
|
||||
public bool UsableUntrained => MinLevel <= 1;
|
||||
}
|
||||
|
||||
internal sealed class SkillDatTables
|
||||
{
|
||||
public readonly Dictionary<uint, SkillDatEntry> Skills = new();
|
||||
public uint[] AttributeXp = Array.Empty<uint>();
|
||||
public uint[] VitalXp = Array.Empty<uint>();
|
||||
public uint[] TrainedXp = Array.Empty<uint>();
|
||||
public uint[] SpecializedXp = Array.Empty<uint>();
|
||||
public ulong[] LevelXp = Array.Empty<ulong>();
|
||||
}
|
||||
|
||||
internal static class SkillDat
|
||||
{
|
||||
private const uint SkillTableFileId = 0x0E000004;
|
||||
private const uint XpTableFileId = 0x0E000018;
|
||||
private const int MaxFile = 1024 * 1024;
|
||||
|
||||
private static volatile SkillDatTables? _tables;
|
||||
private static int _queued;
|
||||
private static volatile string _status = "not loaded";
|
||||
|
||||
public static SkillDatTables? Tables => _tables;
|
||||
|
||||
/// <summary>"38 skills, 190 attribute ranks" or why not. Any thread.</summary>
|
||||
public static string Status => _status;
|
||||
|
||||
/// <summary>Queues the one-time read (again after a failure). Cheap once loaded.</summary>
|
||||
public static void EnsureLoadQueued()
|
||||
{
|
||||
if (_tables != null || Interlocked.Exchange(ref _queued, 1) == 1) return;
|
||||
_status = "loading";
|
||||
UiBackgroundWriter.Enqueue("skills dat", Load);
|
||||
}
|
||||
|
||||
private static void Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
string? path = AcDatFile.FindPortalDat();
|
||||
if (path == null) { Fail("client_portal.dat not found next to acclient.exe"); return; }
|
||||
using AcDatFile? dat = AcDatFile.Open(path, out string why);
|
||||
if (dat == null) { Fail($"{Path.GetFileName(path)}: {why}"); return; }
|
||||
byte[]? skills = dat.Read(SkillTableFileId, MaxFile);
|
||||
byte[]? xp = dat.Read(XpTableFileId, MaxFile);
|
||||
if (skills == null || xp == null) { Fail($"{Path.GetFileName(path)}: skill or XP table missing"); return; }
|
||||
var t = new SkillDatTables();
|
||||
if (!ParseSkills(skills, t) || !ParseXp(xp, t)) { Fail($"{Path.GetFileName(path)}: skill or XP table unreadable"); return; }
|
||||
_tables = t;
|
||||
_status = string.Format(CultureInfo.InvariantCulture, "{0} skills, {1} attribute and {2} skill ranks from {3}",
|
||||
t.Skills.Count, t.AttributeXp.Length - 1, t.TrainedXp.Length - 1, Path.GetFileName(path));
|
||||
RynthLog.UI($"Skills: {_status}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Fail($"read failed: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Fail(string why)
|
||||
{
|
||||
_status = why;
|
||||
RynthLog.UI($"Skills: {why}");
|
||||
Volatile.Write(ref _queued, 0); // the panel's next open tries again
|
||||
}
|
||||
|
||||
private static bool ParseSkills(byte[] raw, SkillDatTables t)
|
||||
{
|
||||
var r = new Reader(raw);
|
||||
r.U32(); // file id
|
||||
int count = r.U16();
|
||||
r.U16(); // buckets
|
||||
for (int i = 0; i < count && r.Ok; i++)
|
||||
{
|
||||
var s = new SkillDatEntry { Id = r.U32() };
|
||||
s.Description = r.PString();
|
||||
s.Name = r.PString();
|
||||
s.Icon = r.U32();
|
||||
s.TrainedCost = (int)r.U32();
|
||||
s.SpecializedCost = (int)r.U32();
|
||||
s.Category = r.U32();
|
||||
r.U32(); // chargen use
|
||||
s.MinLevel = r.U32();
|
||||
r.U32(); r.U32(); r.U32(); // formula W, X, Y
|
||||
s.Divisor = r.U32(); // Z
|
||||
s.Attr1 = r.U32();
|
||||
s.Attr2 = r.U32();
|
||||
r.Skip(24); // upper, lower bound, learn mod
|
||||
if (!r.Ok) break;
|
||||
if (s.Name.Length > 0) t.Skills[s.Id] = s;
|
||||
}
|
||||
return r.Ok && t.Skills.Count > 0;
|
||||
}
|
||||
|
||||
private static bool ParseXp(byte[] raw, SkillDatTables t)
|
||||
{
|
||||
var r = new Reader(raw);
|
||||
r.U32(); // file id
|
||||
int attrs = (int)r.U32(), vitals = (int)r.U32(), trained = (int)r.U32(), spec = (int)r.U32();
|
||||
int levels = (int)r.U32();
|
||||
if (!r.Ok || attrs < 0 || vitals < 0 || trained < 0 || spec < 0 || levels < 0
|
||||
|| attrs > 10000 || vitals > 10000 || trained > 10000 || spec > 10000 || levels > 10000)
|
||||
return false;
|
||||
t.AttributeXp = r.U32s(attrs + 1);
|
||||
t.VitalXp = r.U32s(vitals + 1);
|
||||
t.TrainedXp = r.U32s(trained + 1);
|
||||
t.SpecializedXp = r.U32s(spec + 1);
|
||||
var lv = new ulong[levels + 1];
|
||||
for (int i = 0; i <= levels; i++) lv[i] = r.U64();
|
||||
t.LevelXp = lv;
|
||||
return r.Ok;
|
||||
}
|
||||
|
||||
// ── XP arithmetic (the server's: Player.SpendAttributeXp / SpendSkillXp) ──
|
||||
|
||||
/// <summary>True when <paramref name="ranks"/> is the table's top rank (nothing left to buy).</summary>
|
||||
public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1 >= (uint)table.Length;
|
||||
|
||||
/// <summary>XP to buy <paramref name="n"/> more ranks from <paramref name="ranks"/> with <paramref name="spent"/> already spent; -1 past the top.</summary>
|
||||
public static long CostOf(uint[] table, uint ranks, uint spent, int n)
|
||||
{
|
||||
if (n < 1) return 0;
|
||||
long target = (long)ranks + n;
|
||||
if (target >= table.Length) return -1;
|
||||
return Math.Max(0L, (long)table[target] - spent);
|
||||
}
|
||||
|
||||
/// <summary>How many ranks in a row <paramref name="available"/> XP buys (0 when not even one), up to the top rank.</summary>
|
||||
public static int Affordable(uint[] table, uint ranks, uint spent, long available)
|
||||
{
|
||||
int lo = 0, hi = Math.Max(0, table.Length - 1 - (int)Math.Min(ranks, (uint)int.MaxValue));
|
||||
while (lo < hi)
|
||||
{
|
||||
int mid = (lo + hi + 1) / 2;
|
||||
long c = CostOf(table, ranks, spent, mid);
|
||||
if (c >= 0 && c <= available) lo = mid; else hi = mid - 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary>
|
||||
private ref struct Reader
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _b;
|
||||
private int _p;
|
||||
public bool Ok;
|
||||
|
||||
public Reader(byte[] b) { _b = b; _p = 0; Ok = true; }
|
||||
|
||||
private bool Has(int n)
|
||||
{
|
||||
if (Ok && n >= 0 && _p + n <= _b.Length) return true;
|
||||
Ok = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
public uint U32() { if (!Has(4)) return 0; uint v = BitConverter.ToUInt32(_b.Slice(_p, 4)); _p += 4; return v; }
|
||||
public ushort U16() { if (!Has(2)) return 0; ushort v = BitConverter.ToUInt16(_b.Slice(_p, 2)); _p += 2; return v; }
|
||||
public ulong U64() { if (!Has(8)) return 0; ulong v = BitConverter.ToUInt64(_b.Slice(_p, 8)); _p += 8; return v; }
|
||||
public void Skip(int n) { if (Has(n)) _p += n; }
|
||||
|
||||
public uint[] U32s(int n)
|
||||
{
|
||||
if (!Has(n * 4)) return Array.Empty<uint>();
|
||||
var a = new uint[n];
|
||||
for (int i = 0; i < n; i++) a[i] = U32();
|
||||
return a;
|
||||
}
|
||||
|
||||
/// <summary>u16 length + Latin-1 bytes, then aligned to 4 from the file start (ACE AlignBoundary).</summary>
|
||||
public string PString()
|
||||
{
|
||||
int n = U16();
|
||||
if (!Has(n)) return "";
|
||||
string s = Encoding.Latin1.GetString(_b.Slice(_p, n));
|
||||
_p += n;
|
||||
_p = (_p + 3) & ~3;
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
1459
src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs
Normal file
1459
src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs
Normal file
File diff suppressed because it is too large
Load diff
250
src/RynthCore.Engine/ImGui/Panels/VisionFace.cs
Normal file
250
src/RynthCore.Engine/ImGui/Panels/VisionFace.cs
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/VisionFace.cs
|
||||
// ImGui face of the RynthVision settings (UI/Panels/RynthVisionPanel.cs),
|
||||
// in three tabs:
|
||||
// Terrain the plugin's overlays (radar ring, unclimbable slopes,
|
||||
// impassable water), colours (AARRGGBB hex + swatch), tuning
|
||||
// sliders (Ctrl+click to type a value), water terrain types,
|
||||
// and "Log terrain types here";
|
||||
// Nameplates the RynthVision nameplates (monster plates, debuff icons,
|
||||
// your own plate), engine-side (Hud/MonsterHudSettingsUi);
|
||||
// Combat text floating damage / heal numbers, kill burst and gains.
|
||||
//
|
||||
// Terrain edits a private copy and saves just the changed field
|
||||
// (VisionCommands) when a control finishes changing (a slider on release).
|
||||
// A newer snapshot replaces the copy unless a control is in use. The other
|
||||
// two tabs edit MonsterHudSettings directly (saved in the background).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class VisionFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Vision";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(320, 560), new Vector2(280, 240), EdgeToEdge: true),
|
||||
() => new VisionFace());
|
||||
|
||||
private static readonly Vector4 HeaderColor = RynthTheme.Vec(0xFF7AB8F5);
|
||||
|
||||
private VisionSettings? _s;
|
||||
private long _seenVersion = -1;
|
||||
private bool _busy;
|
||||
private readonly byte[] _slopeHex = new byte[12], _waterHex = new byte[12], _radarHex = new byte[12];
|
||||
private readonly byte[] _waterTypes = new byte[128];
|
||||
private int _tab;
|
||||
private static readonly string[] TabNames = { "Terrain", "Nameplates", "Combat text" };
|
||||
private static readonly string[] TabIds = { "##vtab0", "##vtab1", "##vtab2" };
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.Vision.Subscribe();
|
||||
UiSources.Vision.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Vision.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
TakeSnapshot();
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
TabStrip(w);
|
||||
|
||||
if (_tab == 0)
|
||||
{
|
||||
_busy = DrawTerrain(w, origin, size);
|
||||
}
|
||||
else
|
||||
{
|
||||
_busy = false;
|
||||
ImGuiNET.ImGui.BeginChild("##vision_overlays", new Vector2(w, Math.Max(60, Remaining(origin, size))));
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
float cw = ImGuiNET.ImGui.GetContentRegionAvail().X - 4;
|
||||
if (_tab == 1) Hud.MonsterHudSettingsUi.DrawNameplates(cw);
|
||||
else Hud.MonsterHudSettingsUi.DrawCombatText(cw);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
}
|
||||
End(origin, size);
|
||||
}
|
||||
|
||||
/// <summary>Terrain | Nameplates | Combat text, as a row of flat buttons.</summary>
|
||||
private void TabStrip(float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x = p.X;
|
||||
float bw = MathF.Floor((w - 8) / TabNames.Length);
|
||||
for (int i = 0; i < TabNames.Length; i++)
|
||||
{
|
||||
bool sel = i == _tab;
|
||||
if (Button(TabIds[i], TabNames[i], new Vector2(x, p.Y), new Vector2(bw, 24), sel ? Teal : Mute,
|
||||
sel ? Selected : BtnFill, border: sel ? Teal : 0))
|
||||
_tab = i;
|
||||
x += bw + 4;
|
||||
}
|
||||
NextLine(p, 30);
|
||||
}
|
||||
|
||||
/// <summary>The plugin's own settings. True while a control is in use.</summary>
|
||||
private bool DrawTerrain(float w, Vector2 origin, Vector2 size)
|
||||
{
|
||||
bool busy = false;
|
||||
if (_s == null)
|
||||
{
|
||||
Label("Waiting for the RynthVision plugin…", Mute);
|
||||
return false;
|
||||
}
|
||||
VisionSettings s = _s;
|
||||
|
||||
ImGuiNET.ImGui.BeginChild("##vision_body", new Vector2(w, Math.Max(60, Remaining(origin, size))));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrab, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, Amber);
|
||||
|
||||
Header("Overlays");
|
||||
if (ImGuiNET.ImGui.Checkbox("Radar range ring", ref s.Radar)) Save(VisionKeys.Radar);
|
||||
if (ImGuiNET.ImGui.Checkbox("Unclimbable slopes", ref s.Slopes)) Save(VisionKeys.Slopes);
|
||||
if (ImGuiNET.ImGui.Checkbox("Impassable water", ref s.Water)) Save(VisionKeys.Water);
|
||||
|
||||
Header("Colors (hex AARRGGBB)");
|
||||
busy |= ColorRow(SlopeColorF, _slopeHex, ref s.SlopeColor);
|
||||
busy |= ColorRow(WaterColorF, _waterHex, ref s.WaterColor);
|
||||
busy |= ColorRow(RadarColorF, _radarHex, ref s.RadarColor);
|
||||
|
||||
Header("Tuning");
|
||||
ImGuiNET.ImGui.PushItemWidth(Math.Max(120, ImGuiNET.ImGui.GetContentRegionAvail().X - 8));
|
||||
busy |= Slider(RadarRangeF, ref s.RadarRange, 24, 300, "%.0f");
|
||||
busy |= Slider(RingThickF, ref s.RingThick, 0.5, 6, "%.1f");
|
||||
busy |= Slider(RingHeightF, ref s.RingHeight, 0.5, 30, "%.1f");
|
||||
busy |= IntSlider(SlopeRadiusF, ref s.SlopeRadius, 1, 24);
|
||||
busy |= Slider(SlopeFloorZF, ref s.SlopeFloorZ, 0.30, 0.95, "%.3f");
|
||||
busy |= Slider(SlopeBiasF, ref s.SlopeBias, 0.00, 1.00, "%.2f");
|
||||
busy |= IntSlider(WaterRadiusF, ref s.WaterRadius, 1, 24);
|
||||
ImGuiNET.ImGui.PopItemWidth();
|
||||
|
||||
Header("Water terrain types");
|
||||
if (ImGuiNET.ImGui.Checkbox("Highlight cell if ANY corner is water (else all four)", ref s.WaterAnyCorner)) Save(VisionKeys.WaterAnyCorner);
|
||||
if (ImGuiNET.ImGui.Checkbox("Only paint water cells with an unwalkable triangle (real impassable)", ref s.WaterImpassableOnly)) Save(VisionKeys.WaterImpassableOnly);
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
bool enter = TextBox("##water_types", _waterTypes, p, 160, "18,19,20", out bool typing, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
|
||||
busy |= typing;
|
||||
bool apply = Button("##water_apply", "Apply", new Vector2(p.X + 164, p.Y), new Vector2(56, 22), Text, BtnFill);
|
||||
if (enter || done || apply)
|
||||
{
|
||||
// An empty list resets to the defaults in the plugin; the republish
|
||||
// after the save brings them back here.
|
||||
s.WaterTypes = VisionSettings.ParseCsv(Utf8(_waterTypes));
|
||||
WriteUtf8(_waterTypes, string.Join(",", s.WaterTypes));
|
||||
Save(VisionKeys.WaterTypes);
|
||||
}
|
||||
NextLine(p, 26);
|
||||
|
||||
p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (Button("##inspect", "Log terrain types here", p, new Vector2(ButtonWidth("Log terrain types here") + 8, 24), Text, BtnFill))
|
||||
VisionCommands.Inspect();
|
||||
NextLine(p, 28);
|
||||
|
||||
ImGuiNET.ImGui.PopStyleColor(5);
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
return busy;
|
||||
}
|
||||
|
||||
private void TakeSnapshot()
|
||||
{
|
||||
var snap = UiSources.Vision.Current;
|
||||
if (snap == null || snap.Version == _seenVersion || _busy) return;
|
||||
_seenVersion = snap.Version;
|
||||
_s = snap.Value.Settings.Clone();
|
||||
WriteUtf8(_slopeHex, _s.SlopeColor.ToString("X8"));
|
||||
WriteUtf8(_waterHex, _s.WaterColor.ToString("X8"));
|
||||
WriteUtf8(_radarHex, _s.RadarColor.ToString("X8"));
|
||||
WriteUtf8(_waterTypes, string.Join(",", _s.WaterTypes));
|
||||
}
|
||||
|
||||
private void Save(string key)
|
||||
{
|
||||
if (_s != null) VisionCommands.SaveField(_s, key);
|
||||
}
|
||||
|
||||
/// <summary>A control's label, ImGui id and settings key, built once (no per-frame strings).</summary>
|
||||
private sealed class Field
|
||||
{
|
||||
public readonly string Label, Id, Key;
|
||||
public Field(string label, string id, string key) { Label = label; Id = id; Key = key; }
|
||||
public static Field Slider(string name, string key) => new(name + ":", "##" + name, key);
|
||||
public static Field Color(string name, string key) => new(name, "##hex_" + name, key);
|
||||
}
|
||||
|
||||
private static readonly Field SlopeColorF = Field.Color("Slope", VisionKeys.SlopeColor);
|
||||
private static readonly Field WaterColorF = Field.Color("Water", VisionKeys.WaterColor);
|
||||
private static readonly Field RadarColorF = Field.Color("Radar", VisionKeys.RadarColor);
|
||||
private static readonly Field RadarRangeF = Field.Slider("Radar range", VisionKeys.RadarRange);
|
||||
private static readonly Field RingThickF = Field.Slider("Ring thickness", VisionKeys.RingThick);
|
||||
private static readonly Field RingHeightF = Field.Slider("Ring height (m)", VisionKeys.RingHeight);
|
||||
private static readonly Field SlopeRadiusF = Field.Slider("Slope radius (cells)", VisionKeys.SlopeRadius);
|
||||
private static readonly Field SlopeFloorZF = Field.Slider("Slope floor Z", VisionKeys.SlopeFloorZ);
|
||||
private static readonly Field SlopeBiasF = Field.Slider("Slope height bias (m)", VisionKeys.SlopeBias);
|
||||
private static readonly Field WaterRadiusF = Field.Slider("Water radius (cells)", VisionKeys.WaterRadius);
|
||||
|
||||
private static void Header(string text)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
ImGuiNET.ImGui.TextColored(HeaderColor, text);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
/// <summary>Name | hex box | swatch. Commits on Enter or focus loss; bad input reverts. True while typing.</summary>
|
||||
private bool ColorRow(Field f, byte[] hex, ref uint argb)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, f.Label);
|
||||
bool enter = TextBox(f.Id, hex, new Vector2(p.X + 48, p.Y), 92, "", out bool typing,
|
||||
ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.CharsHexadecimal | ImGuiInputTextFlags.CharsUppercase);
|
||||
bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
|
||||
if (enter || done)
|
||||
{
|
||||
if (VisionSettings.TryParseHex(Utf8(hex), out uint c)) { argb = c; Save(f.Key); }
|
||||
WriteUtf8(hex, argb.ToString("X8"));
|
||||
}
|
||||
// Swatch: AARRGGBB -> ImGui ABGR.
|
||||
uint abgr = (argb & 0xFF00FF00) | ((argb >> 16) & 0xFF) | ((argb & 0xFF) << 16);
|
||||
Vector2 sw = new(p.X + 146, p.Y + 3);
|
||||
dl.AddRectFilled(sw, sw + new Vector2(22, 16), abgr);
|
||||
dl.AddRect(sw, sw + new Vector2(22, 16), Mute);
|
||||
NextLine(p, 26);
|
||||
return typing;
|
||||
}
|
||||
|
||||
/// <summary>Label, then the slider; saves on release (or after Ctrl+click typing). True while in use.</summary>
|
||||
private bool Slider(Field f, ref double value, double min, double max, string format)
|
||||
{
|
||||
ImGuiNET.ImGui.TextUnformatted(f.Label);
|
||||
float v = (float)value;
|
||||
ImGuiNET.ImGui.SliderFloat(f.Id, ref v, (float)min, (float)max, format, ImGuiSliderFlags.AlwaysClamp);
|
||||
value = v;
|
||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Ctrl+click to type a value");
|
||||
return ImGuiNET.ImGui.IsItemActive();
|
||||
}
|
||||
|
||||
private bool IntSlider(Field f, ref int value, int min, int max)
|
||||
{
|
||||
ImGuiNET.ImGui.TextUnformatted(f.Label);
|
||||
ImGuiNET.ImGui.SliderInt(f.Id, ref value, min, max, "%d", ImGuiSliderFlags.AlwaysClamp);
|
||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Ctrl+click to type a value");
|
||||
return ImGuiNET.ImGui.IsItemActive();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue