Snapshot for release 2026.10.31.4 (internal 34cea02)

This commit is contained in:
Tom Bohar 2026-11-01 18:47:28 -05:00
commit b1c182b05d
114 changed files with 8691 additions and 452 deletions

View file

@ -1006,12 +1006,16 @@ internal static class AcMainThreadQueue
// main-thread-only like 0xC8. Same shape as the RequestId slot: its own small
// queue, NOT the gesture-deferred action ring (a packet send doesn't perturb the
// motion graph and a health query must not wait out a swing). Callers ignore the
// result and only want the async 0x01C0 reply, so a target already waiting here is
// not queued twice. Pre-sized, so enqueue does not allocate.
// result and only want the async 0x01C0 reply, so a target that is already the LAST
// one waiting here is not queued twice. Only the last: the server streams health for
// the most recent query, so "pet, then the fight target again" must keep that order
// even when the fight target was already queued before the pet (deduping against any
// earlier entry left the stream on the pet). Pre-sized, so enqueue does not allocate.
private const int MaxQueryHealthQueue = 64;
private static readonly System.Collections.Generic.Queue<(uint Id, long At, int Epoch)> _queryHealthQueue = new(MaxQueryHealthQueue);
private static readonly object _queryHealthLock = new();
private static int _queryHealthPending; // lock-free "anything queued?" for the per-frame drain
private static uint _queryHealthLastId; // the newest entry's id (under _queryHealthLock)
// Pump-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueQueryHealth(uint targetId)
@ -1019,14 +1023,15 @@ internal static class AcMainThreadQueue
if (targetId == 0) return false;
lock (_queryHealthLock)
{
foreach (var q in _queryHealthQueue)
if (q.Id == targetId) return true; // already pending; one reply answers both
if (_queryHealthQueue.Count > 0 && _queryHealthLastId == targetId)
return true; // already the last pending; one reply answers both, the order holds
if (_queryHealthQueue.Count >= MaxQueryHealthQueue)
{
Interlocked.Increment(ref _dropped);
return false;
}
_queryHealthQueue.Enqueue((targetId, NowMs, Volatile.Read(ref _loginEpoch)));
_queryHealthLastId = targetId;
Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count);
return true;
}

View file

@ -122,7 +122,7 @@ internal static class ChatCommandReplies
"debuffs [on|off] | debuffs size <50-200%> | others [on|off] | numbers [dealt|taken|heals|kills] [on|off] | " +
"gains [xp|lum|radiance] [on|off] | npcs [on|off] | npcs dist <yd>|max <n> | players [on|off] | portals [on|off] | portals dist <yd> | " +
"all|engaged |dist <yd>|max <n>|scale <x>|opacity <x>|lift <m> | " +
"names|hp|level|weak|distance|fade|click [on|off] | reset | status | test";
"names|hp|level|weak|distance|fade|click [on|off] | refresh [on|off] | refresh <seconds> | reset | status | test";
public const string ServerUsage =
"Usage: /rc server [<server> auto|on|off] | pick <server>|auto | [aelrynth|other|auto] | names ilt [add|remove <pattern>]";
@ -189,15 +189,26 @@ internal static class ChatCommandReplies
V("hotkey", HotkeyUsage, null),
V("rl", "Usage: /rc rl (reloads RynthCore, as the bar's RL button)", NoArgs, "reload"),
V("inventory", "Usage: /rc inventory (opens or closes the Inventory panel)", NoArgs, "inv"),
V("sense", "Usage: /rc sense (opens or closes the Sense panel)", NoArgs),
V("sense", RynthCore.Engine.UI.Data.SenseLayout.Usage, RynthCore.Engine.UI.Data.SenseLayout.IsValidArgs),
V("characters", "Usage: /rc characters (opens or closes RynthNet's Characters window)", NoArgs, "chars"),
V("itemcount", "Usage: /rc itemcount (opens or closes the Item Count panel)", NoArgs, "itemhud"),
V("resetbar", "Usage: /rc resetbar (moves the RynthCore bar back to the top-left corner)", NoArgs, "barreset"),
V("actionstate", "Usage: /rc actionstate (the client's item-action gates)", NoArgs, "actions"),
V("unlockactions", "Usage: /rc unlockactions (opens the client's item-action gates now)", NoArgs, "unlock"),
V("vitals", "Usage: /rc vitals (the old vitals HUD is gone: /rv plates self)", NoArgs, "hud"),
V("layout", "Usage: /rc layout [status] | default | reset [confirm]", LayoutArgs),
V("uicost", UiCostUsage, null),
};
/// <summary>/rc uicost: the UI frame cost breakdown (ImGui/UiCost.cs).</summary>
public const string UiCostUsage =
"Usage: /rc uicost [on|off|<ms>|now|status] (alone: now; <ms> = the slow-frame threshold, 5-2000)";
/// <summary>"/rc layout": nothing or status, default, reset, reset confirm (any spacing).</summary>
private static bool LayoutArgs(string a) =>
string.Join(' ', a.Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant()
is "" or "status" or "default" or "reset" or "reset confirm";
/// <summary>The verb <paramref name="word"/> names (its name or another spelling), or null.</summary>
public static ChatVerb? Find(string word)
{

View file

@ -438,6 +438,8 @@ internal static class CombatActionHooks
if (AcMainThreadQueue.MustQueue(teardown: false))
return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId);
// The server streams health for the last id queried: the HUD's probes put it back here.
ImGuiBackend.Hud.HealthProbe.NoteQuery(targetId);
try
{
return _queryHealth(targetId);
@ -448,6 +450,30 @@ internal static class CombatActionHooks
}
}
/// <summary>
/// The nameplates' health probe (MonsterHud.ProbeHealth): a 0x1BF for <paramref name="probeId"/>, then
/// one for <paramref name="restoreId"/> (the stream's owner) so the selected / fight target keeps its
/// live 0x01C0 stream. Both go out back to back on AC's main thread, in order; false (nothing sent) off
/// it or in a death / portal window. No owner (0): no second query - the stream stays on the probed
/// monster and its updates stay the HUD's until someone else queries (HealthProbe.IsProbeReply).
/// </summary>
internal static bool SendHudHealthProbe(uint probeId, uint restoreId, long nowMs)
{
if (_queryHealth == null || probeId == 0 || probeId == restoreId || AcMainThreadQueue.MustQueue(teardown: false))
return false;
try
{
ImGuiBackend.Hud.HealthProbe.NoteProbe(probeId, nowMs, sticky: restoreId == 0);
_queryHealth(probeId);
if (restoreId != 0) _queryHealth(restoreId);
return true;
}
catch
{
return false;
}
}
public static bool RequestId(uint objectId)
{
if (_requestId == null || objectId == 0)
@ -1016,7 +1042,7 @@ internal static class CombatActionHooks
if (playerId != 0 && targetId == playerId && healthRatio > 0f && healthRatio <= 1f)
PlayerVitalsHooks.UpdateMaxFromHealthRatio(healthRatio);
PluginManager.QueueUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
PluginManager.QueueUpdateHealth(targetId, healthRatio, currentHealth, maxHealth, healthReply: true);
}
}
catch

View file

@ -155,7 +155,13 @@ internal static class HeartbeatLogger
try
{
if (Plugins.EngineSettings.EnableImGuiBackend)
uiField = $" ui={ImGuiBackend.UiFrameStats.P95Ms:0.0}/{ImGuiBackend.UiFrameStats.MaxMs:0.0}ms";
{
float uiP95 = ImGuiBackend.UiFrameStats.P95Ms;
uiField = $" ui={uiP95:0.0}/{ImGuiBackend.UiFrameStats.MaxMs:0.0}ms";
// uitop=part:avg/max,... = the UI frame's top 3 parts over the last seconds
// (ImGui/UiCost), only while the p95 is over the slow-frame threshold.
uiField += ImGuiBackend.UiCost.HeartbeatField(uiP95);
}
}
catch { }
// vafree = free address space (MB): reloads leak engine/plugin copies,

View file

@ -101,6 +101,13 @@ namespace RynthCore.Engine.Compatibility;
/// hotkeys (<see cref="Hotkeys.HotkeyService"/>; saved for the PC in hotkeys.txt).</item>
/// <item><c>/rc diagnostics</c> (or <c>/rc serverpick</c>) - opens Settings &gt; Diagnostics, the server
/// picker: the one place a server is forced for this character (plugins' "Force a server" links).</item>
/// <item><c>/rc layout [status] | default | reset [confirm]</c> - the panel layout this client uses
/// (<see cref="UI.PanelLayout"/>: its character's own, or the PC-wide default and why) and its files;
/// default makes this character's layout the one new characters start from; reset (then reset
/// confirm) puts this character back to the default. Also Settings &gt; Display.</item>
/// <item><c>/rc uicost [on|off|&lt;ms&gt;|now|status]</c> - the UI frame cost breakdown
/// (<see cref="ImGuiBackend.UiCost"/>): timing on or off, the slow-frame threshold, and (now, or
/// alone) which parts of the UI frame took the time over the last seconds. Also Settings &gt; Diagnostics.</item>
/// </list>
/// </summary>
internal static class RynthCoreChatCommands
@ -360,6 +367,13 @@ internal static class RynthCoreChatCommands
return;
}
// /rc uicost [on|off|<ms>|now|status] : the UI frame cost breakdown (ImGui/UiCost; alone: now)
if (IsVerb(sub, "uicost", out string uiCostArgs))
{
ReplyLines(ImGuiBackend.UiCost.HandleCommand(uiCostArgs));
return;
}
// /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream
if (IsVerb(sub, "netmsg", out string netArgs))
{
@ -602,6 +616,17 @@ internal static class RynthCoreChatCommands
SettingsCommand(settingsArgs);
return;
}
if (IsVerb(sub, "sense", out string senseArgs) && senseArgs.Length > 0)
{
SenseLayoutCommand(senseArgs); // alone, /rc sense opens or closes the panel (the switch below)
return;
}
// /rc layout [status] | default | reset [confirm]: this client's panel layout (UI/PanelLayout).
if (IsVerb(sub, "layout", out string layoutArgs))
{
HandleLayoutCommand(layoutArgs);
return;
}
if (IsVerb(sub, "hotkey", out hotkeyArgs) || IsVerb(sub, "hotkeys", out hotkeyArgs))
{
// The parser's own errors (an unknown verb, a bad key) are the failures; the rest is what changed.
@ -1156,6 +1181,39 @@ internal static class RynthCoreChatCommands
Reply(ChatCommandReplies.PanelReply(label, null, wasOpen));
}
/// <summary>
/// "/rc sense compact on|off | collapse on|off | view full|compact|collapsed": the Sense panel's
/// look (saved in sense.txt), and the look now; alone, compact / collapse / view say the look now.
/// </summary>
private static void SenseLayoutCommand(string args)
{
string title = ImGuiBackend.Panels.SenseFace.Title;
if (!ImGuiBackend.ImGuiPanelHost.HasFace(title))
{
Fail("The Sense panel isn't available (the ImGui layer is off?).");
return;
}
if (!UI.Data.SenseStore.Loaded)
{
UI.Data.SenseStore.EnsureLoadQueued();
Fail("Can't change the Sense view yet: its settings are still loading. Try again in a moment.");
return;
}
UI.Data.SenseLayoutAnswer a = UI.Data.SenseLayout.Apply(args, UI.Data.SenseStore.Layout,
ImGuiBackend.ImGuiPanelHost.IsOpen(title));
if (!a.Ok)
{
Fail(a.Reply);
return;
}
if (!UI.Data.SenseStore.SetLayout(a.Next))
{
Fail("Can't change the Sense view yet: its settings are still loading. Try again in a moment.");
return;
}
Reply(a.Reply);
}
/// <summary>Settings, opened on <paramref name="tab"/> (or switched to it when open).</summary>
private static void OpenSettingsTab(string tab)
{
@ -1403,6 +1461,22 @@ internal static class RynthCoreChatCommands
case "click":
case "clickselect":
S.ClickToSelect = Flag(value, S.ClickToSelect); break;
case "refresh":
case "health":
// "refresh [on|off]" or "refresh <seconds>" (between two health queries for other plates).
if (value != null && !IsOnOff(value))
{
if (!TryNum(value, out float rs))
{
Fail(FormattableString.Invariant(
$"Usage: /rv plates refresh [on|off] | refresh {ImGuiBackend.Hud.HealthProbe.MinIntervalSec:0.0}-{ImGuiBackend.Hud.HealthProbe.MaxIntervalSec:0.0} (seconds; now {S.HealthRefreshSec:0.0#})"));
return;
}
S.HealthRefreshSec = Math.Clamp(rs, ImGuiBackend.Hud.HealthProbe.MinIntervalSec, ImGuiBackend.Hud.HealthProbe.MaxIntervalSec);
S.RefreshOthersHealth = true;
}
else S.RefreshOthersHealth = Flag(value, S.RefreshOthersHealth);
break;
case "onscreen":
case "keeponscreen":
S.KeepOnScreen = Flag(value, S.KeepOnScreen); break;
@ -1601,8 +1675,56 @@ internal static class RynthCoreChatCommands
ReplyLines(UI.Data.Discord.ChatDiscord.HandleCommand(verb));
}
/// <summary>
/// /rc layout: which panel layout this client uses and its files (UI/PanelLayout: the character's own,
/// or the PC-wide default and why); default makes this character's the default for new characters;
/// reset asks, reset confirm copies the default over this character's. Those two answer when their
/// files are written (from the UI writer), or at once with why they can't run.
/// </summary>
private static void HandleLayoutCommand(string args)
{
UI.LayoutCommand cmd = UI.PanelLayoutPolicy.ParseCommand(args);
switch (cmd)
{
case UI.LayoutCommand.Status:
ReplyLines(UI.PanelLayout.DescribeLines());
return;
case UI.LayoutCommand.ResetAsk:
{
string? problem = UI.PanelLayout.Check(cmd, out string ask);
Answer(problem == null, ask, problem ?? "");
return;
}
case UI.LayoutCommand.MakeDefault:
case UI.LayoutCommand.ResetConfirm:
{
string? problem = UI.PanelLayout.Request(cmd, LaterReply());
if (problem != null) Fail(problem);
return;
}
default:
Fail(UI.PanelLayoutPolicy.Usage);
return;
}
}
// ── replies (ChatCommandReplies says where each goes and its colour) ─────
/// <summary>
/// The answer of a command whose result comes later from another thread (a file job on the UI
/// writer): (text, ok), sent as this line's origin would send it. Marks this line answered.
/// </summary>
private static Action<string, bool> LaterReply()
{
ChatCommandOrigin origin = _origin;
_answered = true;
return (text, ok) =>
{
ChatReplyKind kind = ok ? ChatReplyKind.Ok : ChatReplyKind.Fail;
Reply(text, kind, ChatCommandReplies.ToChat(kind, origin));
};
}
/// <summary>It worked, or the state now: in chat (green) for the player, the log only for a script.</summary>
private static void Reply(string text) => Reply(text, ChatReplyKind.Ok, ChatCommandReplies.ToChat(ChatReplyKind.Ok, _origin));

View file

@ -122,6 +122,27 @@ internal static class SehTrampoline
((delegate* unmanaged[Cdecl]<uint, void>)fn)(exitCode);
}
/// <summary>
/// The loaded RynthCore.SehTrampoline.dll's file when it exports RC_DumpProcessW (v9+): the
/// hang watchdog runs it in rundll32 to write a dump of this process from outside it
/// (CrashDump.WriteHangDumpOutOfProcess). Null when the DLL is older or not loaded.
/// </summary>
public static string? DumpHelperPath()
{
try
{
nint module = GetModuleHandleW("RynthCore.SehTrampoline.dll");
if (module == 0 || GetProcAddress(module, "RC_DumpProcessW") == 0) return null;
var buf = new char[1024];
int n = GetModuleFileNameW(module, buf, buf.Length);
return n > 0 && n < buf.Length ? new string(buf, 0, n) : null;
}
catch { return null; }
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleFileNameW")]
private static extern int GetModuleFileNameW(nint module, [Out] char[] path, int size);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleHandleW")]
private static extern nint GetModuleHandleW(string name);

View file

@ -19,6 +19,10 @@ internal static class SessionStateRegistry
internal static string LastCharacterName { get; private set; } = string.Empty;
internal static string LastServerName { get; private set; } = string.Empty;
/// <summary>True once a login's identity is recorded (the names above are final for it; empty when
/// the launch context had none). UI/PanelLayout waits for it before it picks the character's layout.</summary>
internal static bool LoginRecorded => System.Threading.Volatile.Read(ref _loginRecorded);
public static void Initialize()
{
if (_initialized)

View file

@ -335,7 +335,7 @@ internal static class SmartBoxHooks
_hpReadLogCount++;
RynthLog.Compat($"Creature HP id=0x{targetId:X8}: sehRead={(gotReal ? realMax.ToString() : "none")} used={maxHealth} ratio={ratio:0.00}");
}
PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth);
PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth, healthReply: true);
}
break;
@ -765,7 +765,7 @@ internal static class SmartBoxHooks
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(ratio, 0f, 1f));
}
PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth);
PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth, healthReply: true);
}
catch
{

View file

@ -0,0 +1,61 @@
// ============================================================================
// RynthCore.Engine - Compatibility/VendorRatePolicy.cs
// The pure part of VendorTrade's profile check: whether a buy/sell rate read
// from the client's vendor profile is a real rate or a misread. Compiled into
// tools\VendorRateTests.
//
// A rate of exactly 0 is a real rate. A custom server can run a free storage
// vendor (a "vault") whose BuyPrice and SellPrice are both 0; it pays nothing
// for what you hand it and charges nothing for what you take back. Refusing
// 0 turned trading off for such vendors. Negative, NaN, infinite and huge
// values still mean the profile was misread, and trading stays off for them.
//
// The price helpers live here too so the test can pin them: a 0 rate prices
// at 0 (the vault's own GetSellCost/GetBuyCost return 0), while any rate
// above 0 keeps ACE's 1-per-stack floor. The server stays the authority.
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static class VendorRatePolicy
{
/// <summary>Rates at or above this are taken as a misread profile.</summary>
public const float MaxRate = 1000f;
/// <summary>True when <paramref name="rate"/> is finite and in [0, MaxRate).</summary>
public static bool LooksSane(float rate) => float.IsFinite(rate) && rate >= 0f && rate < MaxRate;
/// <summary>True when both rates are exactly 0: a free vendor (it neither charges nor pays).</summary>
public static bool IsFreeVendor(float buyRate, float sellRate) => buyRate == 0f && sellRate == 0f;
public const uint ItemTypePromissoryNote = 0x00040000;
/// <summary>
/// What the player pays for one created stack worth <paramref name="stackValue"/> (ACE Vendor.GetSellCost):
/// max(1, ceil(rate * value - 0.1)), promissory notes at 1.15. A vendor rate of exactly 0 is a free
/// vendor and costs 0 (no 1-per-stack floor); every rate above 0 keeps the stock ACE floor.
/// </summary>
public static long PlayerPaysForStack(float sellRate, uint itemType, long stackValue)
{
if (sellRate == 0f)
return 0;
float rate = itemType == ItemTypePromissoryNote ? 1.15f : sellRate;
float product = rate * stackValue;
return Math.Max(1L, (long)Math.Ceiling(product - 0.1));
}
/// <summary>
/// What the vendor pays for one item worth <paramref name="value"/> (ACE Vendor.GetBuyCost):
/// max(1, floor(rate * value + 0.1)), promissory notes at 1.0. A vendor rate of exactly 0 pays 0.
/// </summary>
public static long VendorPaysForStack(float buyRate, uint itemType, long value)
{
if (buyRate == 0f)
return 0;
float rate = itemType == ItemTypePromissoryNote ? 1.0f : buyRate;
float product = rate * value;
return Math.Max(1L, (long)Math.Floor(product + 0.1));
}
}

View file

@ -168,7 +168,7 @@ internal static class VendorTrade
private const int PwdItemsCapacity = 48, PwdContainersCapacity = 52, PwdType = 56, PwdValue = 60;
private const int PwdStackSize = 96, PwdMaxStackSize = 100, PwdBitfield = 104, PwdBurden = 116;
private const uint ItemTypePromissoryNote = 0x00040000;
private const uint ItemTypePromissoryNote = VendorRatePolicy.ItemTypePromissoryNote;
private const int PyrealMaxStack = 25000; // coinstack MaxStackSize (payout slots)
private const int MaxVendorItems = 1024;
private const int MaxTradeEntries = 100;
@ -232,6 +232,8 @@ internal static class VendorTrade
// Chat echo for /rc vendor (drained on the main thread; written from the drain,
// never from inside the outgoing-chat detour).
private static readonly object _echoLock = new();
// Zero-rate (free) vendors already logged, so each vendor id is logged once per engine.
private static readonly HashSet<uint> _zeroRateLogged = new();
private static readonly Queue<string> _echo = new();
private static volatile int _echoCount;
private const int MaxEcho = 48;
@ -316,6 +318,13 @@ internal static class VendorTrade
snap.ProfileRead = RateLooksSane(snap.BuyRate) && RateLooksSane(snap.SellRate);
if (!snap.ProfileRead)
RynthLog.Warn($"VendorTrade: vendor 0x{vendorId:X8} profile rates look wrong (buy={snap.BuyRate} sell={snap.SellRate}); trading with it is off.");
else if (VendorRatePolicy.IsFreeVendor(snap.BuyRate, snap.SellRate))
{
bool first;
lock (_zeroRateLogged) first = _zeroRateLogged.Add(vendorId);
if (first)
RynthLog.Compat($"VendorTrade: vendor 0x{vendorId:X8} has buy=0 sell=0: a zero-rate (free) vendor; trades are priced at 0.");
}
}
if (list != IntPtr.Zero && Readable(list, ListSize))
@ -962,20 +971,14 @@ internal static class VendorTrade
// ════════════════════════════════════════════════════════════════════════════
/// <summary>What the player pays for one created stack worth <paramref name="stackValue"/> (ACE Vendor.GetSellCost).</summary>
internal static long PlayerPaysForStack(float sellRate, uint itemType, long stackValue)
{
float rate = itemType == ItemTypePromissoryNote ? 1.15f : sellRate;
float product = rate * stackValue;
return Math.Max(1L, (long)Math.Ceiling(product - 0.1));
}
// A 0 rate (free vendor) costs 0; see VendorRatePolicy.
internal static long PlayerPaysForStack(float sellRate, uint itemType, long stackValue) =>
VendorRatePolicy.PlayerPaysForStack(sellRate, itemType, stackValue);
/// <summary>What the vendor pays for one item worth <paramref name="value"/> (ACE Vendor.GetBuyCost).</summary>
internal static long VendorPaysForStack(float buyRate, uint itemType, long value)
{
float rate = itemType == ItemTypePromissoryNote ? 1.0f : buyRate;
float product = rate * value;
return Math.Max(1L, (long)Math.Floor(product + 0.1));
}
// A 0 rate (free vendor) pays 0; see VendorRatePolicy.
internal static long VendorPaysForStack(float buyRate, uint itemType, long value) =>
VendorRatePolicy.VendorPaysForStack(buyRate, itemType, value);
/// <summary>
/// Cost / slots / burden for buying <paramref name="amount"/> of <paramref name="item"/>,
@ -1425,7 +1428,8 @@ internal static class VendorTrade
return sb.ToString();
}
private static bool RateLooksSane(float rate) => float.IsFinite(rate) && rate > 0f && rate < 1000f;
// 0 is a real rate (a free storage vendor); see VendorRatePolicy.
private static bool RateLooksSane(float rate) => VendorRatePolicy.LooksSane(rate);
private static bool InModule(IntPtr p)
{

View file

@ -12,12 +12,18 @@
// (AutoRestartWedgedClients, kept as it is). The hang dump is a small type and
// holds no heap, which is what an out-of-memory needs.
//
// Safe to call from a background thread: MiniDumpWriteDump suspends all other
// threads internally while it snapshots them, which is exactly what we want for
// a hang. The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire).
// MiniDumpWriteDump on this process suspends all other threads and then allocates
// from the process heap: a suspended thread holding the heap lock deadlocks it for
// good. The hang watchdog's dump therefore goes out of process since 2026-11-01
// (WriteHangDumpOutOfProcess, rundll32 + SehTrampoline): a client hung on a reload (10-31
// 21:17) with AC's main thread suspended inside RtlAllocateHeap and the dumping
// thread waiting on that heap's lock. The crash-exit and OUT OF MEMORY dumps still
// run in process (the process is dying, or held in a modal box).
// The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire).
// ============================================================================
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
@ -95,6 +101,99 @@ internal static class CrashDump
}
}
// Longest the dump helper may take for the small hang dump before it is stopped.
private const int DumpToolTimeoutMs = 120_000;
/// <summary>
/// The hang dump: a minidump of this process (thread stacks, no heap) written to
/// Logs\dumps\hang_&lt;pid&gt;_&lt;time&gt;.dmp from another process: the 32-bit rundll32 running
/// RynthCore.SehTrampoline.dll's RC_DumpProcess (v9+; the runtime's createdump.exe takes no
/// pid any more). Nothing here waits on a lock a suspended thread holds (see the header).
/// While it runs this process is in HIGH priority class: the dumper suspends each thread
/// and reads its context, and on a busy machine that read waits seconds for every
/// low-priority thread (the loader's hook freezes had the same wait, native\Loader\Hooks.c
/// BoostForFreeze), with every thread it already suspended frozen meanwhile. No dump when
/// the helper is missing or older (never the in-process fallback). Never throws.
/// </summary>
internal static bool WriteHangDumpOutOfProcess(string reason, out string dumpPath, string prefix = "hang")
{
dumpPath = string.Empty;
try
{
string dir = Path.Combine(LogPaths.LogDirectory, "dumps");
Directory.CreateDirectory(dir);
long free = FreeBytes(dir);
if (!DumpBudget.SmallDumpAllowed(free))
{
RynthLog.Error($"CrashDump: not writing the {prefix} dump - {(free < 0 ? "free space unknown" : (free / (1024 * 1024)) + " MB free")} on the dump volume, reason={reason}");
return false;
}
string? helper = Compatibility.SehTrampoline.DumpHelperPath();
if (helper == null)
{
RynthLog.Error($"CrashDump: the loaded RynthCore.SehTrampoline.dll has no RC_DumpProcess (older than v9; a client restart loads the new one) - {prefix} dump skipped (a dump written from inside a live client can deadlock it), reason={reason}");
return false;
}
dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{DateTime.Now:yyyyMMdd_HHmmss}.dmp");
// SysWOW64's rundll32: a 32-bit process, like the DLL.
string rundll = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "rundll32.exe");
var psi = new ProcessStartInfo(rundll, HangDumpCommand.Arguments(helper, dumpPath, Environment.ProcessId))
{
UseShellExecute = false,
CreateNoWindow = true,
};
long t0 = Stopwatch.GetTimestamp();
bool boosted = false;
ProcessPriorityClass before = ProcessPriorityClass.Normal;
int exitCode;
bool exited;
lock (DumpLock)
{
using Process self = Process.GetCurrentProcess();
try
{
before = self.PriorityClass;
if (before != ProcessPriorityClass.High && before != ProcessPriorityClass.RealTime)
{
self.PriorityClass = ProcessPriorityClass.High;
boosted = true;
}
}
catch { /* no boost: the dump just takes longer */ }
try
{
using Process? dumper = Process.Start(psi);
if (dumper == null) { RynthLog.Error($"CrashDump: the dump helper did not start, reason={reason}"); return false; }
exited = dumper.WaitForExit(DumpToolTimeoutMs);
if (!exited) { try { dumper.Kill(); } catch { } }
exitCode = exited ? dumper.ExitCode : -1;
}
finally
{
if (boosted) { try { self.PriorityClass = before; } catch { } }
}
}
double ms = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency;
long size = 0;
try { size = File.Exists(dumpPath) ? new FileInfo(dumpPath).Length : 0; } catch { }
if (!exited || exitCode != 0 || size == 0)
{
RynthLog.Error($"CrashDump: dump helper {(exited ? $"exit {exitCode} ({HangDumpCommand.DescribeExit(exitCode)})" : $"still running after {DumpToolTimeoutMs / 1000}s, stopped")} after {ms:0} ms, no {prefix} dump, reason={reason}");
try { File.Delete(dumpPath); } catch { }
return false;
}
RynthLog.Error($"CrashDump: wrote {dumpPath} ({size / 1024}KB, out of process, {ms:0} ms) reason={reason}");
return true;
}
catch (Exception ex)
{
RynthLog.Error($"CrashDump: {prefix} dump failed {ex.GetType().Name}: {ex.Message}");
return false;
}
}
/// <summary>Free bytes available to this user on the volume holding <paramref name="dir"/>; -1 when unknown.</summary>
internal static long FreeBytes(string dir)
{

View file

@ -296,12 +296,21 @@ internal static class EndSceneHook
}
}
// AC's own EndScene (and whatever AC does until the next frame): the hang watchdog's
// step goes back to "outside the engine" first.
private static int CallOriginalEndScene(IntPtr pDevice)
{
MainThreadHangWatchdog.Step = null;
return _originalEndScene!(pDevice);
}
private static int EndSceneDetour(IntPtr pDevice)
{
// Liveness beacon for MainThreadHangWatchdog — this detour runs on AC's
// main/render thread every frame (even with the ImGui backend disabled),
// so a stalled beat means the main thread is wedged. Must never throw.
try { MainThreadHangWatchdog.MainThreadBeat(); } catch { }
MainThreadHangWatchdog.Step = "EndScene: engine frame";
try
{
if (!_offscreenFilterDisabled && !DX9Backend.IsRenderingToBackBuffer(pDevice))
@ -320,7 +329,7 @@ internal static class EndSceneHook
// fall back with Decal; without Decal nothing changes.
if (DecalD3D9.Enabled ||
(_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs))
return _originalEndScene!(pDevice);
return CallOriginalEndScene(pDevice);
_offscreenFilterDisabled = true;
RynthLog.D3D9($"EndSceneHook: Falling back to unfiltered EndScene after {_skipCount} skipped offscreen pass(es) over {offscreenElapsedMs}ms.");
@ -398,7 +407,7 @@ internal static class EndSceneHook
// New hook confirmed live — safe to free the old
// trampoline now.
MinHook.MH_RemoveHook(oldAddr);
return _originalEndScene!(pDevice);
return CallOriginalEndScene(pDevice);
}
RynthLog.D3D9("EndSceneHook: Rehook failed — restoring original hook.");
@ -421,7 +430,7 @@ internal static class EndSceneHook
}
if (_renderCount < WarmupFrames)
return _originalEndScene!(pDevice);
return CallOriginalEndScene(pDevice);
_uiActivated = true;
RynthLog.D3D9("EndSceneHook: Warmup complete - initializing ImGui.");
@ -450,6 +459,7 @@ internal static class EndSceneHook
// The UI hides between characters: nothing is drawn at character select or
// on the way out, and it's back the moment login completes (an engine
// reload synthesises login for a player already in the world).
MainThreadHangWatchdog.Step = "EndScene: overlay blit and ImGui submit";
try
{
if (Compatibility.LoginLifecycleHooks.HasObservedLoginComplete)
@ -542,6 +552,6 @@ internal static class EndSceneHook
catch { /* never let the cap take EndScene down */ }
_videoPatchTimer.Restart();
return _originalEndScene!(pDevice);
return CallOriginalEndScene(pDevice);
}
}

View file

@ -163,10 +163,14 @@ internal static class Nav3DRenderInjector
// Video patch: no 3D scene this frame, so no markers or plates over the black.
if (VideoPatch.SkipWorldThisFrame) return;
_inRender = true;
long cost = ImGuiBackend.UiCost.Start(); // UiCost: outside ui=, listed apart
try { ImGuiBackend.DX9Backend.RenderNav3D(dev); }
catch { }
ImGuiBackend.UiCost.Stop(ImGuiBackend.UiCost.Nav3D, cost);
cost = ImGuiBackend.UiCost.Start();
try { ImGuiBackend.UnderUiLayer.PresentFallback(dev); }
catch { }
ImGuiBackend.UiCost.Stop(ImGuiBackend.UiCost.WorldPresent, cost);
_inRender = false;
_atEndScene++;
}
@ -192,6 +196,7 @@ internal static class Nav3DRenderInjector
// This frame's camera, not the one EndScene captured last frame (see RefreshView).
try { GameMatrixCapture.RefreshView(); }
catch { }
long cost = ImGuiBackend.UiCost.Start(); // UiCost: outside ui=, listed apart
try
{
// At the UI pass AC has set a full-screen viewport; the markers project
@ -201,8 +206,10 @@ internal static class Nav3DRenderInjector
catch
{
}
ImGuiBackend.UiCost.Stop(ImGuiBackend.UiCost.Nav3D, cost);
// The world overlays (nameplates, combat text) go here too, over the
// markers and under AC's UI. UnderUiLayer presents a list at most once.
cost = ImGuiBackend.UiCost.Start();
try
{
if (sceneViewport) ImGuiBackend.UnderUiLayer.PresentAtUiPass(dev);
@ -211,6 +218,7 @@ internal static class Nav3DRenderInjector
catch
{
}
ImGuiBackend.UiCost.Stop(ImGuiBackend.UiCost.WorldPresent, cost);
_inRender = false;
return true;
}

View file

@ -983,6 +983,9 @@ public static class EntryPoint
RynthLog.Info("InitWorker: stand-down complete - this client runs as a Decal client; RynthCore stays idle.");
return;
}
// Panel layout per character (UI/PanelLayout): before the EndScene hook, so the first
// frame already asks for the right layout (after a hot reload, the character's).
UI.PanelLayout.Initialize();
if (Plugins.EngineSettings.EnablePlugins)
{
RynthLog.Info("InitWorker DIAG — calling PluginManager.LoadPlugins.");

View file

@ -0,0 +1,36 @@
// ============================================================================
// RynthCore.Engine - HangDumpCommand.cs
// The hang watchdog's dump, written from outside the client (CrashDump.
// WriteHangDumpOutOfProcess): the 32-bit rundll32 runs RynthCore.SehTrampoline.dll's
// RC_DumpProcess (native\SehTrampoline\SehTrampoline.c, DumpArgs.h). Its command line
// and what its exit code means. Pure: tools\EngineRobustnessTests checks both.
// ============================================================================
using System.Globalization;
namespace RynthCore.Engine;
internal static class HangDumpCommand
{
/// <summary>The rundll32 entry, by its plain name (rundll32 tries RC_DumpProcessW first).</summary>
public const string Entry = "RC_DumpProcess";
/// <summary>
/// rundll32's arguments: <c>"&lt;helper dll&gt;",RC_DumpProcess &lt;pid&gt; &lt;dump path&gt;</c>. The
/// path is the rest of the line, unquoted (RC_DumpProcess takes it as it is, spaces included).
/// </summary>
public static string Arguments(string helperDll, string dumpPath, int pid) =>
$"\"{helperDll}\",{Entry} {pid.ToString(CultureInfo.InvariantCulture)} {dumpPath}";
/// <summary>What RC_DumpProcess's exit code means.</summary>
public static string DescribeExit(int code) => code switch
{
0 => "written",
1 => "bad arguments",
2 => "could not open the client process",
3 => "could not create the dump file",
4 => "no dbghelp MiniDumpWriteDump",
5 => "MiniDumpWriteDump failed",
_ => "rundll32 could not run the helper",
};
}

View file

@ -39,6 +39,37 @@ internal static unsafe class DX9Backend
return _vtxScratch;
}
// Rebased-index scratch (DrawSubmitPlan): one command's indices less its smallest one, reused for
// every command (DrawIndexedPrimitiveUP copies them before it returns). Freed in Shutdown.
private static ushort* _idxScratch;
private static int _idxScratchCapacity;
private static ushort* EnsureIndexScratch(int needed)
{
if (needed > _idxScratchCapacity)
{
int cap = _idxScratchCapacity == 0 ? 16384 : _idxScratchCapacity;
while (cap < needed) cap *= 2;
if (_idxScratch != null) NativeMemory.Free(_idxScratch);
_idxScratch = (ushort*)NativeMemory.Alloc((nuint)cap, sizeof(ushort));
_idxScratchCapacity = cap;
}
return _idxScratch;
}
// ── UiCost counters ──
private static SubmitStats _lastSubmit;
/// <summary>The last RenderDrawData / RenderDrawList call's counters (read right after the call). Render thread.</summary>
public static SubmitStats LastSubmit => _lastSubmit;
private static int _fontUploads, _texUploads;
/// <summary>Textures made since the last call: the font atlas, and the others (icons, map tiles, pictures). Render thread.</summary>
public static void TakeUploads(out int font, out int tex)
{
font = _fontUploads; tex = _texUploads;
_fontUploads = _texUploads = 0;
}
// ── Diagnostics (/rc imgui diag): what the last RenderDrawData did ──
private static int _diagLists, _diagVtx, _diagCmds, _diagDraws, _diagSkipped, _diagFailed, _diagLastHr;
private static long _diagFrames;
@ -413,6 +444,12 @@ internal static unsafe class DX9Backend
_vtxScratch = null;
_vtxScratchCapacity = 0;
}
if (_idxScratch != null)
{
NativeMemory.Free(_idxScratch);
_idxScratch = null;
_idxScratchCapacity = 0;
}
_initialized = false;
_coreInitialized = false;
}
@ -524,6 +561,7 @@ internal static unsafe class DX9Backend
private static void RenderLists(ImDrawList** cmdLists, int cmdListsCount, int totalVtx, Vector2 displayPos, Vector2 displaySize,
IntPtr pDevice, bool midFrame)
{
_lastSubmit.Clear();
if (cmdListsCount == 0) return;
if (displaySize.X <= 0 || displaySize.Y <= 0) return;
if (cmdLists == null) return;
@ -629,6 +667,12 @@ internal static unsafe class DX9Backend
SetupRenderStateNative(pDevice, displayPos, displaySize);
const int ResetRenderStateSentinel = -8; // ImDrawCallback_ResetRenderState
// The texture and scissor rect last set here: an unchanged one isn't set again.
IntPtr boundTex = IntPtr.Zero;
bool texBound = false;
RECT boundScissor = default;
bool scissorBound = false;
ref SubmitStats st = ref _lastSubmit;
for (int n = 0; n < cmdListsCount; n++)
{
@ -638,6 +682,7 @@ internal static unsafe class DX9Backend
int vtxCount = list->VtxBuffer.Size;
int cmdCount = list->CmdBuffer.Size;
if (vtxCount == 0 || cmdCount == 0) continue;
st.Lists++;
ImDrawVert* srcVtx = (ImDrawVert*)list->VtxBuffer.Data;
ushort* idxBase = (ushort*)list->IdxBuffer.Data;
@ -696,20 +741,52 @@ internal static unsafe class DX9Backend
if (sr.Top < 0) sr.Top = 0;
if (sr.Right > (int)displaySize.X) sr.Right = (int)displaySize.X;
if (sr.Bottom > (int)displaySize.Y) sr.Bottom = (int)displaySize.Y;
if (sr.Right <= sr.Left || sr.Bottom <= sr.Top) { _diagSkipped++; continue; }
_setScissorRect!(pDevice, &sr);
_setTexture!(pDevice, 0, cmd->TextureId);
if (sr.Right <= sr.Left || sr.Bottom <= sr.Top) { _diagSkipped++; st.Skipped++; continue; }
// DrawIndexedPrimitiveUP has no base-vertex argument, so the
// command's VtxOffset is applied by offsetting the vertex pointer.
// DrawIndexedPrimitiveUP copies NumVertices vertices on every call, so a
// command gets only the vertices its indices reach (DrawSubmitPlan), not the
// whole list (that was V x C vertices a frame: the Loot Editor's 200-330 ms
// submit). It has no base-vertex argument: the command's VtxOffset and its
// smallest index move the vertex pointer, and the indices are rebased to it.
uint vtxOffset = cmd->VtxOffset;
if (vtxOffset >= (uint)vtxCount) { _diagSkipped++; continue; }
ushort* cmdIdx = idxBase + cmd->IdxOffset;
if (vtxOffset >= (uint)vtxCount
|| cmd->IdxOffset + elemCount > (uint)list->IdxBuffer.Size
|| !DrawSubmitPlan.Plan(cmdIdx, (int)elemCount, vtxCount, (int)vtxOffset, out int first, out int numVerts))
{
_diagSkipped++; st.Skipped++; continue;
}
ushort* drawIdx = cmdIdx;
if (first > 0)
{
drawIdx = EnsureIndexScratch((int)elemCount);
DrawSubmitPlan.Rebase(cmdIdx, drawIdx, (int)elemCount, first);
}
if (!scissorBound || sr.Left != boundScissor.Left || sr.Top != boundScissor.Top
|| sr.Right != boundScissor.Right || sr.Bottom != boundScissor.Bottom)
{
_setScissorRect!(pDevice, &sr);
boundScissor = sr;
scissorBound = true;
}
if (!texBound || cmd->TextureId != boundTex)
{
_setTexture!(pDevice, 0, cmd->TextureId);
if (texBound) st.TexSwitches++;
boundTex = cmd->TextureId;
texBound = true;
}
int hr = _drawIndexedPrimUP!(pDevice,
D3DPT_TRIANGLELIST, 0, (uint)vtxCount - vtxOffset,
D3DPT_TRIANGLELIST, 0, (uint)numVerts,
elemCount / 3,
(IntPtr)(idxBase + cmd->IdxOffset), D3DFMT_INDEX16,
(IntPtr)(vtxBuf + vtxOffset), (uint)sizeof(CustomVertex));
(IntPtr)drawIdx, D3DFMT_INDEX16,
(IntPtr)(vtxBuf + vtxOffset + first), (uint)sizeof(CustomVertex));
_diagDraws++;
st.Draws++;
st.VtxCopied += numVerts;
st.VtxWholeList += vtxCount - vtxOffset;
if (hr < 0) { _diagFailed++; _diagLastHr = hr; }
}
}
@ -927,27 +1004,42 @@ internal static unsafe class DX9Backend
return false;
}
// Copy with RGBA → BGRA swizzle (ImGui gives RGBA, D3D9 A8R8G8B8 is BGRA in memory)
byte* src = (byte*)pixels;
byte* dst = (byte*)locked.pBits;
for (int y = 0; y < height; y++)
if (ImGuiFonts.TakeBgraPixels(width, height, out IntPtr bgra))
{
byte* srcRow = src + y * width * 4;
byte* dstRow = dst + y * locked.Pitch;
for (int x = 0; x < width; x++)
// The bake worker made the BGRA rows (ImGuiFonts.BakeWorker): only a row copy here.
try
{
int si = x * 4;
int di = x * 4;
dstRow[di + 0] = srcRow[si + 2]; // B ← R
dstRow[di + 1] = srcRow[si + 1]; // G ← G
dstRow[di + 2] = srcRow[si + 0]; // R ← B
dstRow[di + 3] = srcRow[si + 3]; // A ← A
long row = (long)width * 4;
for (int y = 0; y < height; y++)
Buffer.MemoryCopy((byte*)bgra + y * row, dst + (long)y * locked.Pitch, row, row);
}
finally { ImGuiFonts.FreeBgraPixels(bgra); }
}
else
{
// Copy with RGBA → BGRA swizzle (ImGui gives RGBA, D3D9 A8R8G8B8 is BGRA in memory)
byte* src = (byte*)pixels;
for (int y = 0; y < height; y++)
{
byte* srcRow = src + y * width * 4;
byte* dstRow = dst + y * locked.Pitch;
for (int x = 0; x < width; x++)
{
int si = x * 4;
int di = x * 4;
dstRow[di + 0] = srcRow[si + 2]; // B ← R
dstRow[di + 1] = srcRow[si + 1]; // G ← G
dstRow[di + 2] = srcRow[si + 0]; // R ← B
dstRow[di + 3] = srcRow[si + 3]; // A ← A
}
}
}
unlockRect(_fontTexture, 0);
_fontUploads++; // UiCost: a font atlas upload this frame
// Store texture ID for ImGui
io.Fonts.SetTexID(_fontTexture);
@ -1001,6 +1093,7 @@ internal static unsafe class DX9Backend
}
}
unlockRect(tex, 0);
_texUploads++; // UiCost
return tex;
}
@ -1033,6 +1126,7 @@ internal static unsafe class DX9Backend
for (int y = 0; y < rows; y++) // the pitch of a compressed surface is the bytes of one row of blocks
blocks.Slice(y * rowBytes, rowBytes).CopyTo(new Span<byte>(dst + y * locked.Pitch, rowBytes));
unlockRect(tex, 0);
_texUploads++; // UiCost
return tex;
}

View file

@ -0,0 +1,70 @@
// ============================================================================
// RynthCore.Engine - ImGui/DrawSubmitPlan.cs
// How DX9Backend hands one ImDrawCmd to DrawIndexedPrimitiveUP. Pure logic,
// no engine or D3D types (tools/UiCostTests compiles it). The submit's
// counters (SubmitStats) live in UiCostModel.cs, which stays self-contained.
//
// DrawIndexedPrimitiveUP copies NumVertices vertices out of the caller's
// memory into the runtime's own vertex buffer on EVERY call. The renderer used
// to pass the whole draw list's vertex count for each command, so a window
// with V vertices and C draw commands copied V x C vertices a frame. Every
// PushClipRect starts a new command; the Loot Editor's rule list pushes two
// clip rects per row (name, conditions), so with the editor open the frame's
// vertices went from ~13k to ~30k in one child list split into a command or
// more per row, and the submit copied the list once per command: on the order
// of a million vertices (tens of MB) a frame through the runtime's ring
// buffer. Logged live: submit 200-330 ms for <1 ms of building (and the GPU/
// driver stalls slowed another client on the PC too).
//
// Now each command gets only the vertices its indices reach: the min..max of
// its indices. When min > 0 the indices are rebased into a scratch copy and
// the vertex pointer moved by min, so MinVertexIndex is always 0 (some D3D9
// implementations copy from vertex 0 up to MinVertexIndex + NumVertices,
// whatever MinVertexIndex says). A frame now copies about its vertex count.
// ============================================================================
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class DrawSubmitPlan
{
/// <summary>
/// The vertices one command uses: the smallest and largest of its <paramref name="count"/>
/// indices (count &gt; 0). Linear in count; over a frame that is the frame's index count.
/// </summary>
public static void IndexRange(ushort* idx, int count, out int min, out int max)
{
int lo = ushort.MaxValue, hi = 0;
for (int i = 0; i < count; i++)
{
int v = idx[i];
if (v < lo) lo = v;
if (v > hi) hi = v;
}
min = lo;
max = hi;
}
/// <summary>dst[i] = src[i] - by, for the <paramref name="count"/> indices of a command whose smallest index is <paramref name="by"/>.</summary>
public static void Rebase(ushort* src, ushort* dst, int count, int by)
{
for (int i = 0; i < count; i++)
dst[i] = (ushort)(src[i] - by);
}
/// <summary>
/// What to draw for one command: its first vertex (from the command's VtxOffset) and how many
/// vertices to hand over. False when an index reaches past the list (a broken list: skipped,
/// nothing read out of bounds). <paramref name="listVtx"/> is the list's vertex count.
/// </summary>
public static bool Plan(ushort* idx, int count, int listVtx, int vtxOffset, out int first, out int numVerts)
{
first = 0;
numVerts = 0;
if (count <= 0 || vtxOffset < 0 || vtxOffset >= listVtx) return false;
IndexRange(idx, count, out int min, out int max);
if (vtxOffset + max >= listVtx) return false;
first = min;
numVerts = max - min + 1;
return true;
}
}

View file

@ -121,107 +121,174 @@ internal static class EngineFrameController
return true;
}
public static bool Init(IntPtr pDevice)
// ImGui init runs in two parts since 2026-11-01: the first makes the context (handed to the
// plugins at once, as before) and starts the font atlas bake on a worker (ImGuiFonts.
// StartInitialBake); frames build nothing until the bake is done, and the frame that finds it
// done swaps it in, sets up the Win32 backend and uploads the texture. The bake used to run
// here, on AC's thread, for 2.5-5 s of every hot reload (the main-thread hangs of 10-31/11-01).
private enum InitStep { Done, Baking, Failed }
private static long _initStartedTicks;
private static InitStep Init(IntPtr pDevice)
{
if (_imguiInitialized)
return true;
return InitStep.Done;
bool begin = _context == IntPtr.Zero;
if (!EnsureCore(pDevice))
if (begin)
{
_initFailStep = "EnsureCore (game window not found)";
return false;
if (!EnsureCore(pDevice))
{
_initFailStep = "EnsureCore (game window not found)";
return InitStep.Failed;
}
// Before any context exists: the loaded cimgui.dll must be the exact
// build ImGui.NET wraps, or every struct read below is at wrong offsets.
MainThreadHangWatchdog.Step = "ImGui init: self-test";
_initStartedTicks = Stopwatch.GetTimestamp();
Compatibility.MemoryUse.Mark("ImGui init: before the self-test");
if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle))
return InitStep.Failed;
Compatibility.MemoryUse.Mark("ImGui self-test done");
}
// Before any context exists: the loaded cimgui.dll must be the exact
// build ImGui.NET wraps, or every struct read below is at wrong offsets.
Compatibility.MemoryUse.Mark("ImGui init: before the self-test");
if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle))
return false;
Compatibility.MemoryUse.Mark("ImGui self-test done");
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
if (previousContext != IntPtr.Zero)
RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context.");
_context = ImGuiNET.ImGui.CreateContext();
Compatibility.MemoryUse.Mark("ImGui context created");
bool initSucceeded = false;
if (begin)
{
if (previousContext != IntPtr.Zero)
RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context.");
MainThreadHangWatchdog.Step = "ImGui init: context";
_context = ImGuiNET.ImGui.CreateContext();
Compatibility.MemoryUse.Mark("ImGui context created");
}
InitStep result = InitStep.Failed;
try
{
ImGuiNET.ImGui.SetCurrentContext(_context);
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
// Pin imgui.ini to a stable absolute path so window positions/sizes
// persist across plugin reloads (RL) and AC restarts. The default
// ImGui behavior writes to the working directory which can differ
// between launches. Allocated once, kept alive for the process lifetime.
try
if (begin)
{
string iniPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini");
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
SetUpContext(io);
MainThreadHangWatchdog.Step = "ImGui init: starting the font bake";
if (ImGuiFonts.StartInitialBake(_uiScale))
{
RynthLog.UI("EngineFrameController: the font atlas bakes on a worker; ImGui frames start once it is done.");
result = InitStep.Baking;
return result;
}
// No worker to be had: the old way, on this thread.
MainThreadHangWatchdog.Step = "ImGui init: fonts on the render thread";
ImGuiFonts.Build(io, _uiScale);
}
catch (Exception ex)
else
{
RynthLog.Render($"EngineFrameController: failed to pin imgui.ini path - {ex.Message}");
MainThreadHangWatchdog.Step = "ImGui init: swapping in the baked atlas";
if (!ImGuiFonts.SwapFinished(io, _uiScale, out string baked))
{
result = InitStep.Baking; // still baking: no ImGui frame yet
return result;
}
double sinceMs = (Stopwatch.GetTimestamp() - _initStartedTicks) * 1000.0 / Stopwatch.Frequency;
RynthLog.UI($"ImGuiFonts: first atlas {baked} ({sinceMs:0} ms after ImGui init began).");
Compatibility.MemoryUse.Mark("ImGui fonts swapped in");
}
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
// Multi-viewport (ViewportsEnable) is deliberately never enabled: it
// runs many native->managed platform/renderer callbacks per frame on
// AC's thread and creates HWNDs from inside EndScene. Pop-out panels,
// if built, are driven explicitly by the engine instead
// (docs/IMGUI_PARITY_PLAN.md section 4.2).
// DPI scale for fonts and style metrics. Logged next to Avalonia's
// scale: docked positions are stored in Avalonia logical units, so
// the two must agree for a panel to land in the same place in
// either face (plan section 4.4).
_uiScale = UiScale.ForWindow(_gameHwnd);
RynthLog.UI($"EngineFrameController: ImGui scale {_uiScale:0.##} (Avalonia input scale {UI.AvaloniaOverlay.InputScale:0.##}).");
RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), _uiScale);
Compatibility.MemoryUse.Mark("ImGui theme applied");
ImGuiFonts.Build(io, _uiScale);
MainThreadHangWatchdog.Step = "ImGui init: Win32 backend";
if (!Win32Backend.Init(_gameHwnd))
{
_initFailStep = "Win32Backend.Init";
return false;
return result;
}
Compatibility.MemoryUse.Mark("Win32 backend ready");
MainThreadHangWatchdog.Step = "ImGui init: font texture upload";
if (!DX9Backend.InitImGui(pDevice))
{
_initFailStep = "DX9Backend.InitImGui";
return false;
return result;
}
Compatibility.MemoryUse.Mark("DX9 backend ready (font texture)");
_lastFrameTicks = Stopwatch.GetTimestamp();
_imguiInitialized = true;
initSucceeded = true;
result = InitStep.Done;
RynthLog.UI("EngineFrameController: ImGui initialized.");
return true;
return result;
}
finally
{
if (!initSucceeded && _context != IntPtr.Zero)
if (result == InitStep.Failed && _context != IntPtr.Zero)
{
// A bake may still be running: no context may be destroyed while it allocates.
ImGuiFonts.WaitForWorkers();
ImGuiNET.ImGui.DestroyContext(_context);
_context = IntPtr.Zero;
}
ImGuiNET.ImGui.SetCurrentContext(previousContext);
MainThreadHangWatchdog.Step = "EndScene: ImGui frame";
}
}
/// <summary>The new context's ini handling, flags, DPI scale and theme (Init's first part). Context current.</summary>
private static void SetUpContext(ImGuiIOPtr io)
{
// Panel layout per character (UI/PanelLayout): the engine loads and saves the
// imgui.ini of the layout in use itself (the character's, or the PC-wide
// default), so Dear ImGui gets no file name: it would load only the one it
// started with and write it from the render thread, not atomically. The
// context starts with the layout already applied, if there is one.
if (UI.PanelLayout.Initialized)
{
unsafe { io.NativePtr->IniFilename = null; }
UI.PanelLayout.OnContextCreated(LoadIniFn);
RynthLog.Info("EngineFrameController: imgui.ini is loaded and saved by the panel layout (UI/PanelLayout).");
}
// Without it (an engine that didn't get that far), as before: pin imgui.ini to
// a stable absolute path so window positions/sizes persist across plugin
// reloads (RL) and AC restarts. The default ImGui behavior writes to the
// working directory which can differ between launches. Allocated once,
// kept alive for the process lifetime.
else try
{
string iniPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini");
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
}
catch (Exception ex)
{
RynthLog.Render($"EngineFrameController: failed to pin imgui.ini path - {ex.Message}");
}
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
// Multi-viewport (ViewportsEnable) is deliberately never enabled: it
// runs many native->managed platform/renderer callbacks per frame on
// AC's thread and creates HWNDs from inside EndScene. Pop-out panels,
// if built, are driven explicitly by the engine instead
// (docs/IMGUI_PARITY_PLAN.md section 4.2).
// DPI scale for fonts and style metrics. Logged next to Avalonia's
// scale: docked positions are stored in Avalonia logical units, so
// the two must agree for a panel to land in the same place in
// either face (plan section 4.4).
_uiScale = UiScale.ForWindow(_gameHwnd);
RynthLog.UI($"EngineFrameController: ImGui scale {_uiScale:0.##} (Avalonia input scale {UI.AvaloniaOverlay.InputScale:0.##}).");
RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), _uiScale);
Compatibility.MemoryUse.Mark("ImGui theme applied");
}
public static void Shutdown()
{
if (!_imguiInitialized)
// A context whose first font atlas is still baking (Init's two parts) goes too.
if (!_imguiInitialized && _context == IntPtr.Zero)
return;
bool framesRan = _imguiInitialized;
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
IntPtr contextToDestroy = _context;
@ -250,6 +317,15 @@ internal static class EngineFrameController
// unhooks), so restoring AC's original WndProc this early sends
// those destroys to AC's proc, which ignores them, and the orphaned
// panel HWND outlives the engine load.
// The windows' places go to the layout's imgui.ini now (with no IniFilename
// DestroyContext doesn't save them; UI/PanelLayout).
try
{
// Not before the first frame (the atlas still baking): nothing moved, nothing to save.
if (UI.PanelLayout.Initialized && framesRan)
UI.PanelLayout.SaveIniOnShutdown(ImGuiNET.ImGui.SaveIniSettingsToMemory());
}
catch (Exception ex) { RynthLog.UI($"EngineFrameController: imgui.ini save at shutdown threw {ex.GetType().Name}: {ex.Message}"); }
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
ImGuiFonts.Free(); // the atlas referenced these buffers; the context is gone now
@ -276,6 +352,7 @@ internal static class EngineFrameController
{
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
// in ImGui-off mode so Avalonia owner-window binding works.
MainThreadHangWatchdog.Step = "EndScene: engine pipeline (layout, prefetches, queues)";
EnsureCore(pDevice);
// Settings > Display: borderless windowed + AC window placement. Throttled; reads only
@ -283,6 +360,12 @@ internal static class EngineFrameController
try { UI.AcWindowChrome.Tick(_gameHwnd); }
catch (Exception ex) { RynthLog.UI($"AcWindowChrome.Tick threw {ex.GetType().Name}: {ex.Message}"); }
// Panel layout per character: switches to the character's layout (or back to the
// PC-wide default) and applies a loaded one, before anything below draws a panel.
// A layout waits for the ImGui context while the ImGui layer is in use.
UI.PanelLayout.Tick(imguiInUse: Plugins.EngineSettings.EnableImGuiBackend && !_imguiInitFailed,
imguiReady: _imguiInitialized, SnapshotIniFn, LoadIniFn);
// Cache the D3D9 device function pointers used by Nav3DRenderInjector,
// RenderNav3D, and the always-on render path. This is a strict subset
// of what InitImGui needs and is safe to run without ImGui state.
@ -400,8 +483,12 @@ internal static class EngineFrameController
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
bool imguiBuilt = false;
long uiTicks = 0;
MainThreadHangWatchdog.Step = "EndScene: ImGui frame";
if (!imguiEnabled)
{
_imguiIdle = true; // switched off in game: input state resets when it comes back
UiCost.DiscardFrame(); // no UI frame: what the 3D pass timed isn't kept for one
}
else
{
long t0 = Stopwatch.GetTimestamp();
@ -421,7 +508,13 @@ internal static class EngineFrameController
long t0 = Stopwatch.GetTimestamp();
// Popped-out panels: their own contexts, windows and render targets.
if (_imguiInitialized)
{
MainThreadHangWatchdog.Step = "EndScene: pop-out panels";
// UiCost: what RenderAll spends outside the pop-out windows it times itself.
long c0 = UiCost.Start(), mark = UiCost.Mark;
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
UiCost.StopExclusive(UiCost.PopOuts, c0, mark);
}
long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0);
if (imguiBuilt)
{
@ -431,6 +524,7 @@ internal static class EngineFrameController
else
{
UiFrameStats.Record(ticks);
UiCost.EndFrame(ticks);
}
}
}
@ -599,11 +693,38 @@ internal static class EngineFrameController
/// Panel faces show only in the world, like the Avalonia overlay (hidden
/// between characters, not closed). Also off as soon as AC leaves the world screen
/// (UiFlowHooks, before the logout dispatch catches up) and for good once
/// Client::Cleanup starts.
/// Client::Cleanup starts. And after a login (or a hot reload) not before that
/// character's panel layout is in place (UI/PanelLayout), so nothing draws at the
/// default places first.
/// </summary>
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete
&& Compatibility.UiFlowHooks.InWorldOrUnknown
&& !Compatibility.UiFlowHooks.ClientCleanupStarted;
&& !Compatibility.UiFlowHooks.ClientCleanupStarted
&& UI.PanelLayout.ReadyToDraw;
// The ImGui windows' saved text, read from and loaded into the main context for UI/PanelLayout
// (render thread, between frames). Cached so the per-frame Tick allocates nothing.
private static readonly Func<string?> SnapshotIniFn = SnapshotIni;
private static readonly Action<string> LoadIniFn = LoadIni;
private static string? SnapshotIni()
{
if (!_imguiInitialized || _context == IntPtr.Zero) return null;
IntPtr previous = ImGuiNET.ImGui.GetCurrentContext();
ImGuiNET.ImGui.SetCurrentContext(_context);
try { return ImGuiNET.ImGui.SaveIniSettingsToMemory(); }
finally { ImGuiNET.ImGui.SetCurrentContext(previous); }
}
/// <summary>Loads ini text into the main context: Dear ImGui applies it to windows that already exist too.</summary>
private static void LoadIni(string text)
{
if (_context == IntPtr.Zero) return;
IntPtr previous = ImGuiNET.ImGui.GetCurrentContext();
ImGuiNET.ImGui.SetCurrentContext(_context);
try { ImGuiNET.ImGui.LoadIniSettingsFromMemory(text); }
finally { ImGuiNET.ImGui.SetCurrentContext(previous); }
}
/// <summary>DPI scale the fonts and style were built for (see Init).</summary>
private static float _uiScale = 1f;
@ -663,19 +784,24 @@ internal static class EngineFrameController
{
// Initialised as soon as the backend is enabled (not lazily on first
// content), so the cimgui self-test result is in the log at startup.
if (!Init(pDevice))
InitStep step = Init(pDevice);
if (step == InitStep.Failed)
{
_imguiInitFailed = true;
RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session.");
return false;
}
if (step == InitStep.Baking)
return false; // the first font atlas is still baking on its worker: no ImGui frame yet
}
Win32Backend.UpdateClientMetrics(out int clientW, out int clientH);
// Monster nameplates: pick the monsters (throttled) before deciding
// whether there is a frame to build, so plates alone can ask for one.
long cHud = UiCost.Start();
Hud.MonsterHud.Update(PanelsLive);
UiCost.Stop(UiCost.HudUpdate, cHud);
if (!HasImGuiContent())
{
@ -704,6 +830,8 @@ internal static class EngineFrameController
}
_frameCount++;
// UiCost (ImGui/UiCost.cs): each part of the frame below is timed, by name.
long cSetup = UiCost.Start();
// A panel's text size changed: re-bake the fonts (only the sizes in
// use) and replace the font texture, between frames.
// The new atlas is baked on a worker (ImGuiFonts.PumpRebuild), once per run of
@ -737,7 +865,10 @@ internal static class EngineFrameController
io.DeltaTime = dt > 0f ? dt : 1f / 60f;
RynthTheme.RefreshStyle(ref _themeApplied); // a theme change re-colours the base style
UiCost.Stop(UiCost.FrameSetup, cSetup);
long cNew = UiCost.Start();
ImGuiNET.ImGui.NewFrame();
UiCost.Stop(UiCost.ImGuiNewFrame, cNew);
frameStarted = true;
// Before any window: a drag from a popped-out Inventory or AC's inventory becomes
// a payload the client's drop targets (Mini Remote slots) see this frame.
@ -755,15 +886,17 @@ internal static class EngineFrameController
if (Plugins.EngineSettings.EnableImGuiShell)
{
branch = 1;
long cShell = UiCost.Start();
RynthCoreShell.Render(_frameCount);
PluginManager.RenderAll();
UiCost.Stop(UiCost.Shell, cShell);
PluginManager.RenderAll(); // times each plugin's Render (UiCost)
}
else if (PluginOverlayWindowsLive)
{
branch = 2;
// Only the opt-in extra windows (RynthPluginRenderOverlay), never the
// plugins' full ImGui UIs.
PluginManager.RenderOverlayAll();
PluginManager.RenderOverlayAll(); // times each plugin's RenderOverlay (UiCost)
}
else
{
@ -779,29 +912,53 @@ internal static class EngineFrameController
// World overlays: built into UnderUiLayer's list, drawn next frame at
// AC's 3D->UI transition (under AC's UI and every panel), no input.
// Video patch: with no 3D scene only the screen-fixed player plate draws.
// Timed from here, as one part (plates, the player plate, combat text): the HUD's own
// code isn't instrumented.
long cPlates = UiCost.Start();
Hud.MonsterHud.Draw(_uiScale, worldVisible: !D3D9.VideoPatch.SkipWorldThisFrame);
UiCost.Stop(UiCost.MonsterHud, cPlates, cPlates != 0 ? Hud.MonsterHud.PlateCount : -1);
// Video patch "all": the "rendering paused" banner (background list, under the panels).
long cPart = UiCost.Start();
VideoPatchBanner.Draw();
UiCost.Stop(UiCost.VideoBanner, cPart);
// Server verdicts, the plugins' section manifests and the servermenu push. Every
// frame, bar or not: with the bar hidden (the rail instead) nothing else ticks them,
// so Options > Diagnostics listed no servers and no server plugin was told it is active.
cPart = UiCost.Start();
RynthCore.Engine.UI.ServerMenus.Tick();
UiCost.Stop(UiCost.ServerMenus, cPart);
cPart = UiCost.Start();
if (ImGuiBar.Visible)
ImGuiBar.Draw(_uiScale);
ImGuiPanelHost.DrawAll(_uiScale);
UiCost.Stop(UiCost.Bar, cPart);
ImGuiPanelHost.DrawAll(_uiScale); // times each panel by title, and its own upkeep (UiCost)
// Settings drawer bodies RynthAi's window didn't draw this frame let their sources go.
cPart = UiCost.Start();
Panels.SettingsDrawerBodies.EndFrame();
UiCost.Stop(UiCost.DrawerBodies, cPart);
cPart = UiCost.Start();
ImGuiBar.SyncPopOut(_uiScale);
UiCost.Stop(UiCost.Bar, cPart);
}
if (ImGuiFontTest.Enabled)
ImGuiFontTest.Draw(_uiScale);
long cRender = UiCost.Start();
ImGuiNET.ImGui.EndFrame();
frameEnded = true;
ImGuiNET.ImGui.Render();
UiCost.Stop(UiCost.ImGuiRender, cRender);
long cFinish = UiCost.Start();
ImGuiAssertLog.Poll();
_framesBuilt++;
_lastDisplaySize = io.DisplaySize;
// Windows moved a while ago (Dear ImGui's dirty timer; no IniFilename, so it asks):
// saved to the panel layout's imgui.ini in the background (UI/PanelLayout).
if (io.WantSaveIniSettings)
{
io.WantSaveIniSettings = false;
UI.PanelLayout.QueueIniSave(ImGuiNET.ImGui.SaveIniSettingsToMemory(), explicitSave: false);
}
// io.WantCaptureMouse already applies ImGui's own button-ownership
// rule; io.WantTextInput is true only while a text field is edited.
@ -826,6 +983,7 @@ internal static class EngineFrameController
if (typing && !Win32Backend.UiCaptureEnabled)
_dropImGuiTextFocus = true;
ArbitrateTextFocus(io.WantTextInput);
UiCost.Stop(UiCost.FrameFinish, cFinish);
return true;
}
catch (Exception ex)
@ -884,7 +1042,9 @@ internal static class EngineFrameController
long t0 = Stopwatch.GetTimestamp();
SubmitImGuiFrame(device);
UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0));
long ticks = _deferredUiTicks + (Stopwatch.GetTimestamp() - t0);
UiFrameStats.Record(ticks);
UiCost.EndFrame(ticks);
}
/// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary>
@ -895,7 +1055,16 @@ internal static class EngineFrameController
try
{
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
long c0 = UiCost.Start();
DX9Backend.RenderDrawData(drawData, pDevice);
if (c0 != 0)
{
int vertices = 0;
// ImDrawData +12 TotalVtxCount (as LogHeartbeatIfDue).
unsafe { byte* p = (byte*)drawData.NativePtr; if (p != null) vertices = *(int*)(p + 12); }
UiCost.Stop(UiCost.Submit, c0, vertices);
UiCost.SetSubmit(DX9Backend.LastSubmit); // draws, texture switches, vertices copied
}
_drawSubmits++;
if (!_loggedFirstSubmit)
{

View file

@ -0,0 +1,24 @@
// ============================================================================
// RynthCore.Engine - ImGui/FontPixels.cs
// ImGui's font atlas pixels (RGBA32) as D3D9 A8R8G8B8 rows (BGRA in memory). The bake
// worker converts them (ImGuiFonts.BakeWorker), so AC's thread only copies rows into the
// texture (DX9Backend.CreateFontTexture). Pure: tools\EngineRobustnessTests checks it.
// ============================================================================
using System;
namespace RynthCore.Engine.ImGuiBackend;
internal static class FontPixels
{
/// <summary>R and B swap in each 32-bit pixel (little-endian RGBA: R in the low byte).</summary>
public static void RgbaToBgra(ReadOnlySpan<uint> rgba, Span<uint> bgra)
{
if (bgra.Length < rgba.Length) throw new ArgumentException("destination too small", nameof(bgra));
for (int i = 0; i < rgba.Length; i++)
{
uint p = rgba[i];
bgra[i] = (p & 0xFF00FF00u) | ((p & 0x000000FFu) << 16) | ((p >> 16) & 0x000000FFu);
}
}
}

View file

@ -241,6 +241,20 @@ internal static class ImGuiBar
/// <summary>True when the ImGui bar should draw (the ImGui layer on, not popped out).</summary>
public static bool Visible => ResolveFace() != PanelFace.Avalonia && !Floating;
/// <summary>
/// The panel store now holds another layout (UI/PanelLayout: another character's, the default, or a
/// reset): the bar's place, rows and popped-out state are read from it again; a popped-out bar's
/// window closes and SyncPopOut opens it at the new layout's spot. AC thread, between frames.
/// </summary>
public static void OnLayoutSwitched()
{
Volatile.Write(ref _rowSettings, null);
_floating = null;
_placed = false;
_userMoved = false;
if (ImGuiPopOuts.IsPopped(PopOutTitle)) ImGuiPopOuts.Close(PopOutTitle);
}
/// <summary>
/// Opens or closes the bar's own window to match <see cref="PoppedOut"/>. AC
/// thread, in the world, with the main context current (after the panels).

View file

@ -32,6 +32,13 @@
// Font files are read by Preload() on the engine's init worker, so AC's
// render thread only copies bytes into the atlas. The native TTF buffers and
// glyph ranges stay alive until Free() (after the context is destroyed).
//
// The first atlas is baked off AC's thread too (2026-11-01, StartInitialBake): on a
// hot reload with every client reloading at once, queueing the fonts, rasterizing
// the atlas, the RGBA->BGRA copy and freeing the ~150 MB of TTF copies took 2.5-5 s
// of AC's main thread in the first ImGui frame (the "[UiCost] frame 3611 ms" lines,
// the main-thread hangs of every reload). The worker now does all of it; AC's thread
// swaps the finished atlas in and copies ready BGRA rows into the texture.
// ============================================================================
using System;
@ -105,6 +112,8 @@ internal static unsafe class ImGuiFonts
// set per size in use. Get() returns the set for CurrentStep, which the panel
// host sets while it draws a panel, so every face's text grows without any
// face code changing. Baked (not stretched), so the big text stays sharp.
// The sizes self-drawn windows are drawn at (UI.PanelDrawScale) are baked too:
// a window at 160% draws its text from the 160% set (StepsToBake).
private static readonly Dictionary<int, ImFontPtr[]> ScaledFonts = new();
/// <summary>Text size step of the panel being drawn (0 = normal). Render thread.</summary>
@ -167,6 +176,15 @@ internal static unsafe class ImGuiFonts
_preloaded = true;
}
/// <summary>The text size steps any panel uses, and those the self-drawn windows' sizes need.</summary>
private static List<int> StepsToBake(float scale)
{
List<int> steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse();
foreach (int step in RynthCore.Engine.UI.PanelDrawScale.FontStepsInUse(scale))
if (!steps.Contains(step)) steps.Add(step);
return steps;
}
/// <summary>A baked font. Before Build (or if it failed) this is ImGui's default font.</summary>
public static ImFontPtr Get(UiFont font)
{
@ -219,7 +237,7 @@ internal static unsafe class ImGuiFonts
Compatibility.MemoryUse.Mark("font files read");
ScaledFonts.Clear();
AddAll(io.Fonts, scale, RynthCore.Engine.UI.PanelTextScale.StepsInUse(), Fonts, ScaledFonts);
AddAll(io.Fonts, scale, StepsToBake(scale), Fonts, ScaledFonts);
if (Fonts[(int)UiFont.Ui11].NativePtr != null)
io.NativePtr->FontDefault = Fonts[(int)UiFont.Ui11].NativePtr;
@ -403,8 +421,16 @@ internal static unsafe class ImGuiFonts
public int Steps;
public double Ms;
public string? Error;
// The atlas pixels as D3D9 A8R8G8B8 rows (BGRA in memory), made by the worker
// (NativeMemory); handed on by SwapIn. 0 when the bake failed.
public IntPtr Bgra;
public int Width, Height;
}
// The swapped-in atlas's BGRA copy, until DX9Backend uploads it (TakeBgraPixels). Render thread.
private static IntPtr _bgra;
private static int _bgraWidth, _bgraHeight;
private static System.Threading.Thread? _bakeThread;
private static Bake? _bakeDone; // set by the worker as it ends
private static readonly List<System.Threading.Thread> FreeThreads = new();
@ -418,32 +444,15 @@ internal static unsafe class ImGuiFonts
{
what = "";
if (_bakeThread != null)
{
Bake? done = System.Threading.Volatile.Read(ref _bakeDone);
if (done == null) return false; // still baking: frames go on with the old atlas
_bakeThread.Join();
_bakeThread = null;
_bakeDone = null;
if (done.Atlas == IntPtr.Zero)
{
// Failed off-thread: the old way, here.
io.Fonts.Clear();
Build(io, scale);
what = $"off-thread bake failed ({done.Error}); re-baked on the render thread";
return true;
}
SwapIn(io, done);
what = $"baked off-thread in {done.Ms:0.0} ms ({done.Steps} enlarged size(s) in use)";
return true;
}
return SwapFinished(io, scale, out what); // false while baking: frames go on with the old atlas
if (!TakeRebuildRequest()) return false;
PrepareNativeData();
List<int> steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse();
List<int> steps = StepsToBake(scale);
try
{
_bakeDone = null;
_bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps));
_bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps, prepare: false));
return false;
}
catch (Exception ex)
@ -456,27 +465,125 @@ internal static unsafe class ImGuiFonts
}
}
private static void BakeWorker(float scale, List<int> steps)
/// <summary>
/// The first atlas of a context, baked on a worker (see the header): reading the font files if
/// the init worker hasn't, making their native copies, queueing every font, rasterizing, the
/// BGRA copy and freeing the TTF copies all happen there. AC thread, once the scale is known.
/// False when no worker could be started (the caller then calls <see cref="Build"/>).
/// </summary>
public static bool StartInitialBake(float scale)
{
if (_bakeThread != null) return true;
List<int> steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse();
try
{
_bakeDone = null;
_bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps, prepare: true));
return true;
}
catch (Exception ex)
{
_bakeThread = null;
RynthLog.UI($"ImGuiFonts: no bake thread for the first atlas ({ex.GetType().Name}: {ex.Message}); baking it on the render thread.");
return false;
}
}
/// <summary>
/// Render thread, with <paramref name="io"/>'s context current: swaps a finished bake (the
/// first atlas, or a re-bake) into it. True when the atlas changed (the caller makes its
/// texture); false while none is running or it is still baking.
/// </summary>
public static bool SwapFinished(ImGuiIOPtr io, float scale, out string what)
{
what = "";
if (_bakeThread == null) return false;
Bake? done = System.Threading.Volatile.Read(ref _bakeDone);
if (done == null) return false;
_bakeThread.Join();
_bakeThread = null;
_bakeDone = null;
if (done.Atlas == IntPtr.Zero)
{
// Failed off-thread: the old way, here.
io.Fonts.Clear();
Build(io, scale);
what = $"off-thread bake failed ({done.Error}); baked on the render thread";
return true;
}
SwapIn(io, done);
what = $"baked off-thread in {done.Ms:0.0} ms: {CountBaked()} fonts at scale {scale:0.##}, {done.Steps} enlarged size(s) in use, "
+ $"icons {(_phosphor != null ? $"{IconCount()} merged" : "missing")}"
+ (_symbolMerges > 0 ? $", Segoe UI Symbol merged into {_symbolMerges}" : "");
return true;
}
/// <summary>
/// The swapped-in atlas's pixels as A8R8G8B8 rows, made by the bake worker, when they match
/// <paramref name="width"/> x <paramref name="height"/>: the caller copies them into the texture
/// and frees them with <see cref="FreeBgraPixels"/>. False (nothing to free) otherwise: the
/// caller converts ImGui's RGBA itself. Either way the copy is no longer held here. Render thread.
/// </summary>
public static bool TakeBgraPixels(int width, int height, out IntPtr bgra)
{
bgra = _bgra;
bool match = bgra != IntPtr.Zero && _bgraWidth == width && _bgraHeight == height;
if (bgra != IntPtr.Zero && !match) FreeBgraPixels(bgra);
_bgra = IntPtr.Zero;
_bgraWidth = _bgraHeight = 0;
if (!match) bgra = IntPtr.Zero;
return match;
}
public static void FreeBgraPixels(IntPtr bgra)
{
if (bgra != IntPtr.Zero) NativeMemory.Free((void*)bgra);
}
private static void BakeWorker(float scale, List<int> steps, bool prepare)
{
var bake = new Bake { Steps = steps.Count };
long t0 = Stopwatch.GetTimestamp();
ImFontAtlas* atlas = null;
try
{
// The first bake makes the native copies of the font files here; a re-bake finds
// them made (PumpRebuild prepares them first). One bake runs at a time, and nothing
// else touches them until it is joined (SwapFinished, WaitForWorkers).
if (prepare)
{
PrepareNativeData();
Compatibility.MemoryUse.Mark("font files read (bake worker)");
}
atlas = ImGuiNative.ImFontAtlas_ImFontAtlas();
var ptr = new ImFontAtlasPtr(atlas);
AddAll(ptr, scale, steps, bake.Base, bake.Scaled);
if (bake.Base[(int)UiFont.Ui11].NativePtr == null)
ptr.AddFontDefault(); // no Segoe UI: ImGui's built-in font keeps text readable
ptr.Build();
// The RGBA copy the texture is made from, here too: the swap then only uploads it.
ptr.GetTexDataAsRGBA32(out IntPtr _, out int _, out int _);
// The RGBA copy the texture is made from, and its BGRA rows for D3D9, here too:
// the swap then only copies rows into the texture.
ptr.GetTexDataAsRGBA32(out IntPtr rgba, out int w, out int h);
if (rgba != IntPtr.Zero && w > 0 && h > 0)
{
bake.Bgra = (IntPtr)NativeMemory.Alloc((nuint)w * (nuint)h, 4);
FontPixels.RgbaToBgra(new ReadOnlySpan<uint>((void*)rgba, w * h), new Span<uint>((void*)bake.Bgra, w * h));
bake.Width = w;
bake.Height = h;
}
// The glyphs are rasterized: the atlas's copies of the font files (~150 MB with
// every size) are never read again (DX9Backend's note), so they go here, not on
// AC's thread. The pixels and TexReady stay.
ptr.ClearInputData();
if (prepare) Compatibility.MemoryUse.Mark("font atlas baked (bake worker)");
bake.Atlas = (IntPtr)atlas;
atlas = null;
}
catch (Exception ex)
{
bake.Error = $"{ex.GetType().Name}: {ex.Message}";
FreeBgraPixels(bake.Bgra);
bake.Bgra = IntPtr.Zero;
}
finally
{
@ -496,6 +603,10 @@ internal static unsafe class ImGuiFonts
Array.Copy(bake.Base, Fonts, Fonts.Length);
ScaledFonts.Clear();
foreach (KeyValuePair<int, ImFontPtr[]> kv in bake.Scaled) ScaledFonts[kv.Key] = kv.Value;
FreeBgraPixels(_bgra); // a copy never uploaded (each swap is uploaded straight after)
_bgra = bake.Bgra;
_bgraWidth = bake.Width;
_bgraHeight = bake.Height;
ImGuiPopOuts.ReplaceFontAtlas((IntPtr)old, (IntPtr)fresh);
if (old == null || old == fresh) return;
IntPtr oldPtr = (IntPtr)old;
@ -538,7 +649,11 @@ internal static unsafe class ImGuiFonts
_bakeDone = null;
if (pending != null && pending.Atlas != IntPtr.Zero)
ImGuiNative.ImFontAtlas_destroy((ImFontAtlas*)pending.Atlas); // baked, never swapped in
if (pending != null) FreeBgraPixels(pending.Bgra);
}
FreeBgraPixels(_bgra);
_bgra = IntPtr.Zero;
_bgraWidth = _bgraHeight = 0;
foreach (IntPtr p in NativeBuffers)
NativeMemory.Free((void*)p);
NativeBuffers.Clear();

View file

@ -118,6 +118,15 @@ internal interface IImGuiPanel
/// </summary>
bool ClickThroughWantsWheel => false;
/// <summary>
/// True while the face shows a bare look (the Sense panel's compact view, 2026-10-31): docked,
/// the host draws no header, frame, border, background or resize grip, so only what the face
/// paints shows; with <see cref="ClickThrough"/> the rest passes clicks to the game. The window
/// keeps its place and size for when the face is framed again. Popped out (an OS window of its
/// own) and embedded copies are framed as usual. Answered by the face's last Draw; keep it cheap.
/// </summary>
bool Bare => false;
/// <summary>
/// Popped out and not hovered or in use: how often the face is redrawn (Hz).
/// Its pictures are only pushed when they change; this bounds the cost of
@ -594,10 +603,14 @@ internal static class ImGuiPanelHost
/// </summary>
public static void DrawAll(float uiScale)
{
// UiCost: each panel by its title; the rest of DrawAll as the host's upkeep.
long cHost = UiCost.Start(), costMark = UiCost.Mark;
int drawn = 0;
_frameScale = uiScale;
WheelWanted = false;
float placeScale = PlacementScale();
ApplyFaceChanges(placeScale); // plugin windows taking over (or giving back) engine panels
ApplyLayoutSwitch(placeScale); // another character's panel layout (UI/PanelLayout)
while (Requests.TryDequeue(out var req))
Apply(req.Title, req.Kind, placeScale);
RemoveUnregistered();
@ -614,9 +627,13 @@ internal static class ImGuiPanelHost
if (_resizeTitle == entry.Title) _resizeTitle = null; // hid mid-resize: free the grip
continue;
}
long cPanel = UiCost.Start();
DrawPanel(entry, uiScale, placeScale, null);
UiCost.StopPanel(entry.Title, cPanel);
drawn++;
}
DrawSizeNote();
UiCost.StopExclusive(UiCost.PanelHost, cHost, costMark, cHost != 0 ? drawn : -1);
}
// ── One way to resize every panel (Tom 2026-10-23) ───────────────────
@ -680,7 +697,9 @@ internal static class ImGuiPanelHost
lock (Sync) Entries.TryGetValue(title, out entry);
if (entry == null || !entry.Shown || !entry.Popped) return;
_frameScale = uiScale;
long cPanel = UiCost.Start();
DrawPanel(entry, uiScale, PlacementScale(), display);
UiCost.StopPopped(entry.Title, cPanel);
}
/// <summary>A pop-out window was moved or resized by the user: save it. Game thread.</summary>
@ -703,6 +722,12 @@ internal static class ImGuiPanelHost
_restored = true;
// Settings > Display "Remember Open Windows and Positions" (default on).
if (!Plugins.EngineSettings.RememberWindowLayout) return;
OpenSavedOpen();
}
/// <summary>Opens the engine panels the panel store has saved open (ImGui or Both docked face). AC thread.</summary>
private static void OpenSavedOpen()
{
List<string> titles = new();
// Script windows (dynamic) open when their owner says so, not from the saved state.
lock (Sync)
@ -719,6 +744,77 @@ internal static class ImGuiPanelHost
}
}
// ── Panel layout per character (UI/PanelLayout) ───────────────────────
private static volatile bool _layoutSwitched;
/// <summary>
/// The panel store now holds another layout (another character's, the default, or a reset): the
/// open panels take their places from it at the next DrawAll. Any thread.
/// </summary>
public static void OnLayoutSwitched() => _layoutSwitched = true;
/// <summary>
/// After a layout switch: each shown panel is placed from the new layout (docked spot and size, popped
/// out or not, and where); an engine panel the layout has saved closed closes, without saving over
/// it; engine panels it has saved open open. Plugin and script windows stay open (their owners
/// decide that) and move. Nothing shown (a hot reload, the first login): only the opening. AC thread.
/// </summary>
private static void ApplyLayoutSwitch(float placeScale)
{
if (!_layoutSwitched) return;
_layoutSwitched = false;
bool remember = Plugins.EngineSettings.RememberWindowLayout;
List<Entry> order;
lock (Sync) order = DrawOrder;
foreach (Entry e in order)
{
if (!e.Shown) continue;
bool has = PanelStateStore.TryGetPanel(e.Title, out PanelStateStore.PanelEntry saved);
if (!e.Dynamic && remember && has && !saved.Open)
{
CloseQuietly(e);
continue;
}
if (e.Popped)
{
ImGuiPopOuts.Close(e.Title);
e.Popped = false;
}
PlaceFromSavedState(e, placeScale);
if (PanelRouter.CanPopOut && !e.Spec.NoPopOut && has && saved.Floating)
StartPopOut(e, placeScale, fromSaved: true);
else if (!has)
Persist(e, open: true, placeScale); // new to this layout: saved here, so it reopens here
}
if (remember) OpenSavedOpen(); // queued; applied by this DrawAll (an open one is skipped)
RynthLog.UI("ImGuiPanelHost: the open panels took their places from the panel layout now in use.");
}
/// <summary>Closes a shown face without saving its placement (the layout it came from isn't in use any more). AC thread.</summary>
private static void CloseQuietly(Entry entry)
{
lock (Sync)
{
if (_open.Contains(entry.Title))
{
var next = new HashSet<string>(_open, StringComparer.OrdinalIgnoreCase);
next.Remove(entry.Title);
System.Threading.Volatile.Write(ref _open, next);
}
}
if (entry.Popped)
{
ImGuiPopOuts.Close(entry.Title);
entry.Popped = false;
}
try { entry.Instance?.OnHidden(); }
catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: {entry.Title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); }
entry.Instance = null;
entry.Shown = false;
System.Threading.Interlocked.Decrement(ref _shownCount);
}
/// <summary>Client pixels per logical unit (the unit PanelSpec sizes, MinSize and RequestSize use).</summary>
internal static float PlacementScale()
{
@ -1006,7 +1102,10 @@ internal static class ImGuiPanelHost
{
PanelSpec spec = entry.Spec;
bool popped = popDisplay.HasValue;
bool standard = spec.Chrome == PanelChrome.Standard;
// A bare face (IImGuiPanel.Bare): docked, no frame of any kind, only what it paints.
bool bare = false;
if (!popped) try { bare = entry.Instance?.Bare ?? false; } catch { }
bool standard = spec.Chrome == PanelChrome.Standard && !bare;
bool both = PanelRouter.ResolveDockedFace(entry.Title) == PanelFace.Both;
Vector2 minSize = (entry.Instance?.MinSize ?? spec.MinSize) * placeScale;
@ -1071,10 +1170,10 @@ internal static class ImGuiPanelHost
ImGuiNET.ImGui.SetNextWindowSizeConstraints(minSize, new Vector2(float.MaxValue, float.MaxValue));
}
uint background = spec.Background ?? RynthTheme.PanelGlass;
uint background = bare ? 0u : spec.Background ?? RynthTheme.PanelGlass;
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, spec.Rounding);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, spec.Chrome == PanelChrome.None ? 0f : 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, spec.Chrome == PanelChrome.None || bare ? 0f : 1f);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, background);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, spec.BorderColor ?? RynthTheme.PanelBorder);
@ -1113,7 +1212,7 @@ internal static class ImGuiPanelHost
// the same way, over the corner the face leaves free.
bool inlineGrip = standard && spec.GripInBody;
bool manualGrip = (!standard || inlineGrip) && !clickThrough && !popped // popped: the window resizes itself
&& !spec.NoResize;
&& !spec.NoResize && !bare; // bare: sized while framed
Vector2 outerPos = ImGuiNET.ImGui.GetWindowPos(), outerSize = ImGuiNET.ImGui.GetWindowSize();
float gSize = GripSize(entry, uiScale);
Vector2 gMin = GripMin(entry, uiScale, outerPos + outerSize);
@ -1271,6 +1370,9 @@ internal static class ImGuiPanelHost
/// <summary>True while an embedded copy draws: its window moves and size requests are ignored.</summary>
[ThreadStatic] private static bool _inEmbed;
/// <summary>True while an embedded copy of a face draws (inside another panel's section). AC thread.</summary>
internal static bool DrawingEmbedded => _inEmbed;
/// <summary>True when <paramref name="title"/> is registered and may be drawn inside another panel. Any thread.</summary>
public static bool CanEmbed(string title) => !NotEmbeddable.Contains(title) && HasFace(title);

View file

@ -432,7 +432,10 @@ internal static unsafe class ImGuiPopOuts
if (pop.Window == null || pop.Window.Hwnd == IntPtr.Zero) continue;
long interval = pop.HotFrames > 0 || pop.Hovered || pop.WantTextInput ? 0 : pop.IdleInterval;
if (pop.HotFrames <= 0 && now - pop.LastFrameTicks < Math.Max(interval, FrameInterval)) continue;
// UiCost: the window's own frame, render and present; its panel is timed by the host.
long cPop = UiCost.Start(), costMark = UiCost.Mark;
RenderOne(device, pop, uiScale, now);
UiCost.StopPopOutWindow(pop.Title, cPop, costMark);
}
}
finally

View file

@ -0,0 +1,194 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/HealthProbe.cs
// Fresh health for the monster plates that are NOT the selected / queried
// target (2026-10-31: "only the selected monster's plate keeps updating; the
// others show a number that stops changing while they take damage").
//
// Why they froze: ACE sends a creature's health (0x01C0 UpdateHealth) only
// to players whose current health-query target it is (Player.HandleAction-
// QueryHealth -> UpdateSelectedTarget; Creature.OnHealthUpdate walks that
// creature's selectedTargets). One target per player: every QueryHealth
// moves the stream. So a plate got one value when it was selected / queried /
// appraised and then nothing, and CleaveHealth estimates only cover the
// player's own weapon hits (no other players, pets, procs or DoTs).
//
// The fix: the HUD asks for them, slowly. At most one probe per interval
// (setting, default 1 s), and each probe is immediately followed by a query
// for the stream's owner (the last target a plugin or the selection asked
// for), so the selected / fight target keeps its live stream. Cost per probe:
// two 0x01BF game actions up, two 0x01C0 replies down (well under 100 bytes).
//
// Who is probed (Pick): plates on screen, not the stream owner, not dead.
// 1. "active" plates (hurt, hit by you, or hitting you) whose last server
// reading is ActiveRefreshSec old or more, the stalest first;
// 2. plates never read by the server, nearest first (one probe each);
// 3. quiet plates whose reading is IdleRefreshSec old or more.
// Nothing due: no traffic.
//
// A probe's reply is the HUD's: PluginManager records it for the plates but
// does not hand it to plugins (IsProbeReply), so a bot never reads another
// player's damage on a monster it isn't fighting as its own hit.
//
// Pick and the ledger are pure (time is passed in); compiled into
// tools/CleaveGhostTests. Engine-owned statics only.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.ImGuiBackend.Hud;
internal static class HealthProbe
{
/// <summary>A plate in the fight is re-read when its last server reading is this old (s).</summary>
public const double ActiveRefreshSec = 2.0;
/// <summary>A quiet plate (full health, nobody fighting it) is re-read this rarely (s).</summary>
public const double IdleRefreshSec = 12.0;
/// <summary>A 0x01C0 for a probed id this soon after the probe (ms) is the probe's reply.</summary>
public const long ReplyWindowMs = 2000;
/// <summary>The setting's range and default: seconds between two probes.</summary>
public const float DefaultIntervalSec = 1.0f, MinIntervalSec = 0.5f, MaxIntervalSec = 5.0f;
/// <summary>
/// One plate. <paramref name="Seen"/>: the server has sent its health at least once;
/// <paramref name="ServerAgeSec"/>: seconds since that last server reading (estimates don't count).
/// <paramref name="Active"/>: hurt, hit by the player or hitting the player recently.
/// <paramref name="Dead"/>: its last reading was 0.
/// </summary>
public readonly record struct Candidate(uint Id, float Distance, bool Seen, double ServerAgeSec, bool Active, bool Dead = false);
/// <summary>The plate to probe now, or 0 when none is due. <paramref name="owner"/> is never picked (it is streamed).</summary>
public static uint Pick(ReadOnlySpan<Candidate> candidates, uint owner)
{
uint best = 0;
int bestTier = -1;
double bestScore = double.NegativeInfinity;
float bestD = float.MaxValue;
foreach (Candidate c in candidates)
{
if (c.Id == 0 || c.Id == owner || c.Dead) continue;
int tier;
double score;
if (c.Active)
{
if (c.Seen && !(c.ServerAgeSec >= ActiveRefreshSec)) continue;
tier = 2;
score = c.Seen ? c.ServerAgeSec / ActiveRefreshSec : double.MaxValue;
}
else if (!c.Seen)
{
tier = 1;
score = 0; // all equal: the nearest wins
}
else
{
if (!(c.ServerAgeSec >= IdleRefreshSec)) continue;
tier = 0;
score = c.ServerAgeSec / IdleRefreshSec;
}
bool better = tier > bestTier ||
(tier == bestTier && (score > bestScore || (score == bestScore && c.Distance < bestD)));
if (!better) continue;
best = c.Id; bestTier = tier; bestScore = score; bestD = c.Distance;
}
return best;
}
// ── The server's health stream: whose it is, and which replies are the HUD's ──
private static readonly object Sync = new();
private static uint _owner;
private static bool _ownerKnown;
private const int MaxPending = 8;
private static readonly uint[] PendingId = new uint[MaxPending];
private static readonly long[] PendingAt = new long[MaxPending];
private static readonly bool[] PendingSticky = new bool[MaxPending];
private static int _pendingNext;
private static long _probes;
/// <summary>Probes sent since the engine started (status line).</summary>
public static long ProbeCount => Interlocked.Read(ref _probes);
/// <summary>
/// A health query that is not the HUD's went out for <paramref name="id"/> (a plugin's QueryHealth,
/// or the client's own on a selection change): the server streams that id now, and its replies
/// belong to whoever asked. Any thread.
/// </summary>
public static void NoteQuery(uint id)
{
lock (Sync)
{
_owner = id;
_ownerKnown = true;
// The stream moved: a sticky probe (sent with no owner to hand back to) no longer streams,
// and the newly queried id's replies are the asker's.
for (int i = 0; i < MaxPending; i++)
if (PendingId[i] == id || PendingSticky[i]) { PendingId[i] = 0; PendingSticky[i] = false; }
}
}
/// <summary>The id the server streams health for (see NoteQuery); false before anything was noted.</summary>
public static bool TryGetOwner(out uint owner)
{
lock (Sync)
{
owner = _owner;
return _ownerKnown;
}
}
/// <summary>
/// The HUD probed <paramref name="id"/> at <paramref name="nowMs"/>. <paramref name="sticky"/>: no owner was
/// queried after it, so the server keeps streaming this id to us: every reply for it is the HUD's until
/// the next NoteQuery (no ReplyWindowMs).
/// </summary>
public static void NoteProbe(uint id, long nowMs, bool sticky = false)
{
if (id == 0) return;
lock (Sync)
{
int slot = -1;
for (int i = 0; i < MaxPending; i++)
if (PendingId[i] == id) { slot = i; break; }
if (slot < 0) { slot = _pendingNext; _pendingNext = (_pendingNext + 1) % MaxPending; }
PendingId[slot] = id;
PendingAt[slot] = nowMs;
PendingSticky[slot] = sticky;
_probes++;
}
}
/// <summary>True when a health reply for <paramref name="id"/> answers a HUD probe (sent within ReplyWindowMs).</summary>
public static bool IsProbeReply(uint id, long nowMs)
{
if (id == 0) return false;
lock (Sync)
{
if (_ownerKnown && id == _owner) return false; // someone else asked for it too
for (int i = 0; i < MaxPending; i++)
if (PendingId[i] == id)
{
if (PendingSticky[i]) return true;
long age = nowMs - PendingAt[i];
if (age >= 0 && age <= ReplyWindowMs) return true;
PendingId[i] = 0; // expired
return false;
}
return false;
}
}
/// <summary>Logout / character switch: nothing carries over.</summary>
public static void Reset()
{
lock (Sync)
{
_owner = 0;
_ownerKnown = false;
Array.Clear(PendingId);
Array.Clear(PendingSticky);
_pendingNext = 0;
}
}
}

View file

@ -288,6 +288,7 @@ internal static class MonsterHud
if (track) Snapshot(now, trackMonsters);
}
if (monsters) ApplyDealtHits(now);
if (monsters && MonsterHudSettings.RefreshOthersHealth) ProbeHealth(now);
_hasContent = Plates.Count > 0 || MonsterHudSettings.SelfPlate || CombatText.HasContent;
}
@ -316,6 +317,8 @@ internal static class MonsterHud
{
ClearPlates();
MonsterHudData.Clear();
HealthProbe.Reset();
_nextProbeTicks = 0;
PlateDebuffs.Clear();
CombatText.Clear();
PlayerPlate.Reset();
@ -1590,6 +1593,45 @@ internal static class MonsterHud
}
}
// ── Health for the plates the server isn't streaming (HealthProbe) ──
private static readonly List<HealthProbe.Candidate> ProbeCandidates = new();
private static long _nextProbeTicks;
/// <summary>"Hit by you" keeps a plate in the fight this long (s) for the probe's refresh.</summary>
private const double ProbeHitMemorySec = 30;
/// <summary>
/// At most one health query per "Refresh others' health" interval for an on-screen plate the server
/// isn't streaming, then one for the stream's owner so the selected / fight target keeps its feed.
/// AC's main thread only (both sends go out back to back, in order); skipped otherwise and in a
/// death / portal / login window.
/// </summary>
private static void ProbeHealth(long now)
{
if (now < _nextProbeTicks || Plates.Count == 0) return;
float interval = Math.Clamp(MonsterHudSettings.HealthRefreshSec, HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec);
_nextProbeTicks = now + (long)(interval * Stopwatch.Frequency);
if (!CombatActionHooks.HasQueryHealth || AcMainThreadQueue.MustQueue(teardown: false)) return;
if (!HealthProbe.TryGetOwner(out uint owner)) owner = ClientHelperHooks.GetSelectedItemId();
double freq = Stopwatch.Frequency;
long hitWindow = (long)(ProbeHitMemorySec * freq);
ProbeCandidates.Clear();
foreach (Plate p in Plates.Values)
{
if (p.IsLabel || p.Gone || !p.OnScreen || p.Alpha < 0.01f || p.Id == _playerId) continue;
bool has = MonsterHudData.TryGetHealth(p.Id, out HealthObservation h);
bool seen = has && h.ServerTicks != 0;
long lastHit = CombatText.LastHitTicks(p.Id);
bool active = p.IsAttacker || (has && (h.Ratio < 0.999f || h.Estimated)) ||
(lastHit != long.MinValue && now - lastHit < hitWindow);
ProbeCandidates.Add(new HealthProbe.Candidate(p.Id, p.Distance, seen, seen ? (now - h.ServerTicks) / freq : 0,
active, Dead: seen && h.Ratio <= 0.001f));
}
uint id = HealthProbe.Pick(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(ProbeCandidates), owner);
if (id == 0) return;
CombatActionHooks.SendHudHealthProbe(id, owner, Environment.TickCount64);
}
internal static uint FindPlateByName(string name)
{
uint target = ClientHelperHooks.GetSelectedItemId();
@ -1696,7 +1738,9 @@ internal static class MonsterHud
$"name labels {labels} ({labelsOnScreen} on screen, {portals} portals), {Classes.Count} objects classified; " +
$"camera {(GameMatrixCapture.HasCapturedFrame ? "captured" : "not captured")} " +
$"(frame lb 0x{GameMatrixCapture.FrameLandblock:X4}, viewport {GameMatrixCapture.ViewportWidth}x{GameMatrixCapture.ViewportHeight}); " +
$"weakness data {(_weakByWcid.Count + _weakByName.Count > 0 ? "loaded" : "none")}.",
$"weakness data {(_weakByWcid.Count + _weakByName.Count > 0 ? "loaded" : "none")}; " +
$"others' health refresh {(MonsterHudSettings.RefreshOthersHealth ? $"on, every {MonsterHudSettings.HealthRefreshSec:0.0#} s" : "off")} " +
$"({HealthProbe.ProbeCount} quer{(HealthProbe.ProbeCount == 1 ? "y" : "ies")} sent).",
PlateDebuffs.Describe(),
PlayerPlate.Describe() + " " + CombatText.Describe(),
AcMouseOver.Describe(),

View file

@ -23,8 +23,10 @@ using System.Diagnostics;
namespace RynthCore.Engine.ImGuiBackend.Hud;
/// <summary>Last health observation for one object. <paramref name="Prev"/>: the ratio before it
/// (-1 = first). <paramref name="Estimated"/>: worked out from a hit (CleaveHealth), not sent by the server.</summary>
internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks, float Prev = -1f, bool Estimated = false);
/// (-1 = first). <paramref name="Estimated"/>: worked out from a hit (CleaveHealth), not sent by the server.
/// <paramref name="ServerTicks"/>: when the server last sent this object's health (0 = never; estimates keep it).</summary>
internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks, float Prev = -1f, bool Estimated = false,
long ServerTicks = 0);
internal static class MonsterHudData
{
@ -58,7 +60,8 @@ internal static class MonsterHudData
}
if (Health.Count >= MaxHealthEntries && !Health.ContainsKey(id))
Health.Clear();
Health[id] = new HealthObservation(ratio, current, max, now, before, estimated);
long serverTicks = estimated ? (had ? prev.ServerTicks : 0) : now;
Health[id] = new HealthObservation(ratio, current, max, now, before, estimated, serverTicks);
}
// An estimate never kills (CleaveHealth keeps it above 0) and the server correcting one
// isn't a heal: the combat text sees an estimate's successor as a first observation.

View file

@ -49,6 +49,14 @@ internal static class MonsterHudSettings
public static float HeightLift = 0.0f; // extra metres above the estimated head height
/// <summary>A left-click on a monster plate selects that monster in game.</summary>
public static bool ClickToSelect = true;
/// <summary>
/// "Refresh others' health" (2026-10-31): the server streams health only for the selected / queried
/// monster, so the HUD asks for the other plates' health itself, one monster per HealthRefreshSec
/// (HealthProbe). Off: only the selected / queried monster's plate is live.
/// </summary>
public static bool RefreshOthersHealth = true;
/// <summary>Seconds between two of those health queries (HealthProbe's range).</summary>
public static float HealthRefreshSec = HealthProbe.DefaultIntervalSec;
// Name-only labels over NPCs (vendors in gold) and, optionally, other players.
// Counted apart from MaxPlates so they never push a monster plate out.
@ -220,6 +228,10 @@ internal static class MonsterHudSettings
case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break;
case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break;
case "clickSelect": ClickToSelect = val == "1"; break;
case "refreshOthersHealth": RefreshOthersHealth = val == "1"; break;
case "healthRefreshSec":
if (TryF(val, out float hr)) HealthRefreshSec = Math.Clamp(hr, HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec);
break;
case "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break;
case "npcNames": NpcNames = val == "1"; break;
case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break;
@ -339,6 +351,8 @@ internal static class MonsterHudSettings
sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}"));
sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}"));
sw.WriteLine($"clickSelect={B(ClickToSelect)}");
sw.WriteLine($"refreshOthersHealth={B(RefreshOthersHealth)}");
sw.WriteLine(FormattableString.Invariant($"healthRefreshSec={HealthRefreshSec:0.##}"));
sw.WriteLine($"npcNames={B(NpcNames)}");
sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}"));
sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}"));
@ -397,6 +411,7 @@ internal static class MonsterHudSettings
Enabled = true; MaxDistance = 35f; MaxPlates = 20; Filter = PlateFilter.All;
ShowNames = true; ShowHpNumbers = true; ShowDistance = false; ShowLevel = true; ShowWeakness = true;
FadeWithDistance = true; Scale = 1.0f; Opacity = 0.9f; HeightLift = 0f; ClickToSelect = true;
RefreshOthersHealth = true; HealthRefreshSec = HealthProbe.DefaultIntervalSec;
ShowDebuffs = true; ShowOthersDebuff = true;
NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false; PlayerBars = false;
PortalNames = true; PortalMaxDistance = DefaultPortalDistance;
@ -462,7 +477,8 @@ internal static class MonsterHudSettings
$"RynthVision nameplates: monsters {(Enabled ? "ON" : "OFF")} ({(Filter == PlateFilter.Engaged ? "engaged only" : "all monsters")}, " +
$"{MaxDistance:0}yd, max {MaxPlates}, scale {Scale:0.##}, opacity {Opacity:0.##}, lift {HeightLift:0.#}m; " +
$"names {OnOff(ShowNames)}, hp {OnOff(ShowHpNumbers)}, level {OnOff(ShowLevel)}, weak {OnOff(ShowWeakness)}, " +
$"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " +
$"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}, " +
$"refresh others' health {(RefreshOthersHealth ? $"every {HealthRefreshSec:0.0#} s" : "off")}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " +
$"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)} (bars {OnOff(PlayerBars)}), " +
$"portal names {OnOff(PortalNames)} ({PortalMaxDistance:0}yd); " +
$"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " +

View file

@ -67,6 +67,14 @@ internal static class MonsterHudSettingsUi
MonsterHudSettings.MinDistance, MonsterHudSettings.MaxDistanceLimit, "%.0f", w);
changed |= SliderI("Max plates", ref MonsterHudSettings.MaxPlates,
MonsterHudSettings.MinPlates, MonsterHudSettings.MaxPlatesLimit, w);
changed |= Toggle("Refresh others' health", ref MonsterHudSettings.RefreshOthersHealth,
"The server only keeps the selected (or fought) monster's health up to date. On: the HUD also asks for " +
"the other plates' health, one monster at a time - first the ones in the fight, then any it hasn't seen - " +
"and hands the live feed straight back to your target. Two small queries per refresh. " +
"Off: only your target's plate is live. Chat: /rv plates refresh [on|off], /rv plates refresh <seconds>.");
if (MonsterHudSettings.RefreshOthersHealth)
changed |= SliderF("Refresh every (s)", ref MonsterHudSettings.HealthRefreshSec,
HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec, "%.1f s", w);
Section("On the plate", w);
changed |= Toggle("Name", ref MonsterHudSettings.ShowNames, null);

View file

@ -14,7 +14,8 @@
// 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
// from it: move / copy lines like it to a tab, hide them, colour or highlight
// them (a "Highlight line" rule: a band behind the whole line). 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). The
// coordinates are also drawn as underlined links: click points RynthNav's
@ -638,6 +639,10 @@ internal sealed class ChatFace : IImGuiPanel
Vector2 p = basePos + new Vector2(0, _tops[i]);
ChatLine line = _vis[i];
ChatRoute route = line.Route;
// A "Highlight line" rule: a band behind all of the line's rows, under the mention
// tint and the selection. One rect, no allocation; _h[i] already spans every row.
if (route.HighlightArgb is uint band)
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), RynthTheme.Argb(ChatColorModes.BandArgb(band)));
if (route.Mention)
dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), MentionBg);
if (lo >= 0 && i >= lo && i <= hi)
@ -1065,15 +1070,17 @@ internal sealed class ChatFace : IImGuiPanel
// ── Rules from a line ────────────────────────────────────────────────
private void RuleFromLine(ChatRuleAction action, string? tab)
private void RuleFromLine(ChatRuleAction action, string? tab, ChatColorMode colour = ChatColorMode.Line)
{
var rule = new ChatFilterRule { Pattern = _ctxPattern, Action = action, Tab = tab ?? "" };
if (action == ChatRuleAction.Color)
{
rule.ColorMode = ChatColorMode.Line;
rule.ColorMode = colour;
ChatModel.AddRule(rule);
if (!ImGuiPanelHost.IsOpen("ChatFilters")) PanelRouter.Toggle("ChatFilters");
Flash("Rule added - pick its colour in Filters");
Flash(colour == ChatColorMode.Highlight
? "Rule added: lines like this are highlighted - pick its colour in Filters"
: "Rule added - pick its colour in Filters");
return;
}
ChatModel.AddRule(rule);
@ -1486,6 +1493,7 @@ internal sealed class ChatFace : IImGuiPanel
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);
if (ImGuiNET.ImGui.MenuItem("Highlight them…")) RuleFromLine(ChatRuleAction.Color, null, ChatColorMode.Highlight);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters"))
PanelRouter.Toggle("ChatFilters");

View file

@ -5,6 +5,7 @@
//
// [#] [on] [Contains v] [pattern ...................] [up] [down] [delete]
// When [Any line v] [Move to v] [Junk v] [Colour line v] [swatch]
// (colour: No colour / Colour line / Colour match / Highlight line)
// (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
@ -84,7 +85,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel
"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" };
// Indexed by ChatColorMode.
private static readonly string[] ColorLabels = { "No colour", "Colour line", "Colour match", "Highlight line" };
private static readonly string[] ColorHelp =
{
"No colour: the rule doesn't colour the line.",
"Colour line: the whole line's text in this colour.",
"Colour match: just the text the rule matched, in this colour.",
"Highlight line: a band in this colour behind the whole line; the text keeps its colour.",
};
private static readonly string[] ModeHelp =
{
"Regex: a case-insensitive regular expression (^ start, $ end, \\d+ a number...).",
@ -116,7 +125,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text: plain text (any case) or a 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);
Label("Colour: the first \"Colour line\" wins, and the first \"Highlight line\"; \"Colour match\" colours every match (a higher rule wins an overlap).", Mute);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
@ -346,7 +355,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
if (r.Action != ChatRuleAction.Hide)
{
int mode = (int)r.ColorMode;
int mode = Math.Clamp((int)r.ColorMode, 0, ColorLabels.Length - 1);
string colText = ColorLabels[mode] + Caret;
Vector2 cPos = flow.Place(ButtonWidth(colText));
if (Button("##colmode", colText, cPos, new Vector2(ButtonWidth(colText), rowH), Text, BtnFill))
@ -354,8 +363,8 @@ internal sealed class ChatFiltersFace : IImGuiPanel
{
rule.ColorMode = (ChatColorMode)k;
ChatModel.FiltersChanged();
}, 130);
ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the rule matched.");
}, 140);
SafeImGui.SetItemTooltip(ColorHelp[mode]);
if (r.ColorMode != ChatColorMode.None)
{
Vector2 sPos = flow.Place(rowH);
@ -629,6 +638,9 @@ internal sealed class ChatFiltersFace : IImGuiPanel
}
uint color = RynthTheme.Argb(ChatLineColors.Resolve(route.LineArgb, ChatLineColors.KindOf(type, channel, text), channel, type));
_testResult.Add((where + (route.LineArgb != null ? " (this is its colour)" : ""), route.Hidden ? Faded(Mute) : color));
if (!route.Hidden && route.HighlightArgb is uint band)
_testResult.Add(($"Highlighted: a {ChatModel.FormatColor(band | 0xFF000000)} band behind the line (this colour).",
RynthTheme.Argb(band | 0xFF000000)));
// Not hidden: name a standard filter that would hide it (one not in the rules yet).
if (!route.Hidden)

View file

@ -7,7 +7,9 @@
// UiSources.LootEdit, shared with the Loot Editor): each rule
// with its on/off gem, its action (Keep, Keep #, Salvage,
// Sell, Read) and summary; move up / down, duplicate, delete,
// add; Save and Reload; RynthAi's last message.
// add; Why? (RynthAi's "Why this loot rule?" window for the
// item selected in the game); Save and Reload; RynthAi's last
// message.
// A rule's conditions are written in the Loot Editor (the Editor plate opens it
// on this file). Opening another file waits for unsaved changes to be saved or
// reloaded (the Loot Editor asks about discarding them; this tab doesn't).
@ -170,6 +172,11 @@ internal sealed class ClassicLootTab : IClassicTab
if (Plate("##cl_add", "Add", new Vector2(x, y)) && editable)
LootEditCommands.Simple("add", -1);
SafeImGui.SetItemTooltip("Add a new rule at the end (write it in the Loot Editor)");
x += Px(50);
// The selected item, not the selected rule: RynthAi's "Why this loot rule?" window.
if (x + Px(46) <= o.X + w && Plate("##cl_why", "Why?", new Vector2(x, y)))
LootEditorFace.AskLootWhy();
SafeImGui.SetItemTooltip(LootEditorFace.LootWhyLabel + "\n" + LootEditorFace.LootWhyTip);
y += Px(21);
}

View file

@ -16,6 +16,9 @@
// Monster Detail panel (weaknesses, accuracy, damage, summons, damage taken,
// its rule). x removes the monster (confirmed). Gold = set by you, dim =
// automatic.
// Under a monster's row, when the plugin sends them (the row's "mstats",
// UI/Data/DamageRowStats.cs, 2026-10-30): how often it evades and resists you
// and you it since login, the full numbers on hover.
// Where the server plugin reports difficulty tiers: a tier chip after Reset stats
// (DamageView.Tier) - which tier the numbers are for, and a picker; "~" marks an
// HP estimated from tier 0's. Hidden elsewhere.
@ -97,6 +100,8 @@ internal sealed class DamageFace : IImGuiPanel
public string NameShown = "", NameTip = "";
public string Weapon = "", Offhand = "", Pet = "", WeakTop = "", Sec = "", SecTip = "";
public string Prefer = "Auto";
/// <summary>The line under the row (the plugin's evades and resists since login) and its tooltip; "" for none.</summary>
public string Stats = "", StatsTip = "";
public bool CritSet, NonCritSet, WeaponGold, OffhandGold, PetGold, PreferGold;
public string[] TierLines = Array.Empty<string>();
/// <summary>Priority shown (int.MinValue = rules not loaded), whether it's the monster's own
@ -361,6 +366,11 @@ internal sealed class DamageFace : IImGuiPanel
t.Sec = r.SecKill > 0 ? r.SecKill.ToString("0.0", inv) : "—";
t.SecTip = (r.SecKill > 0 ? $"{r.SecKill:0.0} s from engaging to the kill (average of timed kills)." : "No timed kills yet.")
+ (r.HitRate >= 0 ? $"\nHits: {r.HitRate * 100:0}% of attacks and casts landed." : "");
if (r.Stats != null)
{
t.Stats = r.Stats.Line();
t.StatsTip = r.Stats.Tip();
}
t.TierLines = new string[r.Tiers.Count];
for (int i = 0; i < r.Tiers.Count; i++)
{
@ -756,29 +766,33 @@ internal sealed class DamageFace : IImGuiPanel
}
}
// The line under a monster's row: the plugin's evades and resists since login (DamageRowStats).
private const float StatsH = 16;
private void DrawRow(DamageRow r, Vector2 clipMin, Vector2 clipMax)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (p.Y + RowH < clipMin.Y || p.Y > clipMax.Y)
RowText t = _text[r];
float h = RowH + (t.Stats.Length > 0 ? StatsH : 0);
if (p.Y + h < clipMin.Y || p.Y > clipMax.Y)
{
ImGuiNET.ImGui.Dummy(new Vector2(TableW, RowH)); // off screen: keep the layout, skip the drawing
ImGuiNET.ImGui.Dummy(new Vector2(TableW, h)); // off screen: keep the layout, skip the drawing
return;
}
RowText t = _text[r];
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(TableW, RowH), r.IsDefault ? HeaderBg : RowBg);
dl.AddRectFilled(p, p + new Vector2(TableW, h), r.IsDefault ? HeaderBg : RowBg);
if (r.Targeted)
{
// The monster being fought (or selected): teal wash, a bar on the left, an outline.
dl.AddRectFilled(p, p + new Vector2(TableW, RowH), TargetBg);
dl.AddRectFilled(p, p + new Vector2(3, RowH), Teal);
dl.AddRect(p, p + new Vector2(TableW, RowH), Teal);
dl.AddRectFilled(p, p + new Vector2(TableW, h), TargetBg);
dl.AddRectFilled(p, p + new Vector2(3, h), Teal);
dl.AddRect(p, p + new Vector2(TableW, h), Teal);
}
else if (r.Nearby)
{
// On the player's landblock: a green wash and bar.
dl.AddRectFilled(p, p + new Vector2(TableW, RowH), NearbyBg);
dl.AddRectFilled(p, p + new Vector2(3, RowH), NearbyBar);
dl.AddRectFilled(p, p + new Vector2(TableW, h), NearbyBg);
dl.AddRectFilled(p, p + new Vector2(3, h), NearbyBar);
}
ImGuiNET.ImGui.PushID(r.IsDefault ? "default" : r.Key);
float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
@ -892,8 +906,21 @@ internal sealed class DamageFace : IImGuiPanel
}
SafeImGui.SetItemTooltip("Remove " + r.Name + " from this list (asks first).");
if (t.Stats.Length > 0)
{
// Under the monster: its evades and resists both ways since login, the full numbers on hover.
ImFontPtr small = ImGuiFonts.Get(UiFont.Ui10);
var at = new Vector2(p.X + ColX[ColMonster] + 22, p.Y + RowH + (StatsH - small.FontSize) * 0.5f - 2);
dl.PushClipRect(new Vector2(p.X, p.Y + RowH), new Vector2(p.X + TableW, p.Y + h), true);
dl.AddText(small, small.FontSize, at, Dim, t.Stats);
dl.PopClipRect();
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColMonster] + 22, p.Y + RowH));
ImGuiNET.ImGui.InvisibleButton("##stats", new Vector2(Math.Max(1, TableW - ColX[ColMonster] - 26), StatsH));
SafeImGui.SetItemTooltip(t.StatsTip);
}
ImGuiNET.ImGui.PopID();
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH));
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h));
ImGuiNET.ImGui.Dummy(new Vector2(TableW, 0));
}
@ -1442,7 +1469,7 @@ internal sealed class DamageFace : IImGuiPanel
ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Reset ALL learned damage statistics?");
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text),
"Monster names and your settings (manual HP, weapon/offhand picks, debuffs) are KEPT — only the learned damage, crit, casts-to-kill, kills and HP are cleared. This cannot be undone.");
"Monster names and your settings (manual HP, weapon/offhand picks, debuffs) are KEPT — only the learned damage, crit, casts-to-kill, kills and HP are cleared, and the evades and resists under each monster start over. This cannot be undone.");
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;

View file

@ -60,6 +60,10 @@ internal sealed class ItemsFace : IImGuiPanel
"An entry whose item is gone but with an unlisted item of the same name in your pack\n" +
"(a new stack of kits, a replacement weapon) is pointed at that item instead.\n" +
"Does nothing while your inventory is still loading. Also: /ra items clean.");
// The other way: everything in the pack that belongs here and isn't listed yet (answers in chat).
AddSelected("##fill_from_pack", PhosphorIcons.Plus + " Add From Pack", "(weapons, healing kits, lockpicks, pet essences not listed yet)",
() => RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra items fill"),
"Adds every weapon, healing kit, lockpick and pet essence in your pack that isn't listed yet.\nRynthAi says in chat what it added. Also: /ra items fill.");
// Weapons
Section("Weapons", bw);

View file

@ -158,6 +158,11 @@ internal sealed class LootEditorFace : IImGuiPanel
public readonly byte[] Bytes = new byte[512];
public string? Shown;
public bool Active;
// A text condition (TextPattern): the mode shown, the words in the box, and the pattern they were
// read from (re-read only when the pattern changes, so a mode the player picked stays).
public LootTextMode? Mode;
public string Words = "";
public string? ParsedFrom;
}
private readonly Dictionary<(int Cond, int Line), FieldBuffer> _fields = new();
private readonly FieldBuffer _nameField = new(), _keepField = new();
@ -758,10 +763,26 @@ internal sealed class LootEditorFace : IImGuiPanel
? "A rule for the item selected in the game (click it first): preview, then add it here"
: s.Dirty ? "Save or discard your edits first" : "This profile is read-only here");
addW += itemW + 6;
// RynthAi answers in its own "Why this loot rule?" window (an older RynthAi ignores it).
string whyLabel = PhosphorIcons.Info + " " + LootWhyLabel;
float whyW = ButtonWidth(whyLabel) + 6;
if (Button("##loot_why", whyLabel, new Vector2(p.X + addW + 6, p.Y), new Vector2(whyW, h), Text, BtnFill))
AskLootWhy();
SafeImGui.SetItemTooltip(LootWhyTip);
addW += whyW + 6;
MessageText(new Vector2(p.X + addW + 8, p.Y), p.X + w - grip - 4, h);
NextLine(p, h);
}
/// <summary>The "Why this loot rule?" buttons (here and the Classic Loot tab).</summary>
internal const string LootWhyLabel = "Why this loot rule?";
internal const string LootWhyTip =
"Which rule of the loot profile in use takes the item selected in the game, and why the rules above it\n" +
"didn't (the first condition each failed, and the value it read). RynthAi shows it in a small window.\nAlso: /ra loot why";
/// <summary>RynthAi's "lootwhy" remote command: /ra loot why window, for the selected item. Any thread.</summary>
internal static void AskLootWhy() => RynthAiCommands.ApplyRemoteCommand("lootwhy", "show");
private void MessageText(Vector2 at, float right, float h)
{
if (_msg.Length == 0 || (_msgOk && (DateTime.Now - _msgAt).TotalSeconds > 10)) return;
@ -1110,14 +1131,13 @@ internal sealed class LootEditorFace : IImGuiPanel
}
case "keypattern":
{
float kw = w * 0.34f;
float kw = w * 0.30f;
IdPicker("##key", c, 1, KeyTable(node.KeyTable), "key", p, kw - 2, h, ro);
if (Field("##pat", FieldFor(i, 0), c.Lines[0], new Vector2(p.X + kw + 2, p.Y), w - kw - 2, "pattern (regex)", ro, out string v, h))
c.Lines[0] = v;
TextPattern("##pat", c, i, new Vector2(p.X + kw + 2, p.Y), w - kw - 2, h, ro);
break;
}
case "text":
if (Field("##text", FieldFor(i, 0), c.Lines[0], p, w, "pattern (regex)", ro, out string t, h)) c.Lines[0] = t;
TextPattern("##text", c, i, p, w, h, ro);
break;
default: // "value"
if (Field("##value", FieldFor(i, 0), c.Lines[0], p, w, node.Labels.Count > 0 ? node.Labels[0].ToLowerInvariant() : "value", ro, out string n, h))
@ -1188,6 +1208,62 @@ internal sealed class LootEditorFace : IImGuiPanel
SafeImGui.SetItemTooltip(tip);
}
/// <summary>
/// A text condition's pattern as a mode and plain words (2026-11-01: "people hate regex"): [contains v]
/// [words]. The editor writes the regex (UI.LootPatternText) into the condition, so the profile stays a
/// plain VTank .utl; "regex" shows the pattern itself. A mode the player picks stays while the pattern
/// still reads back as it.
/// </summary>
private void TextPattern(string id, LootEditConditionDto c, int cond, Vector2 p, float w, float h, bool ro)
{
FieldBuffer buf = FieldFor(cond, 0);
string pattern = c.Lines[0];
if (!ReferenceEquals(buf.ParsedFrom, pattern))
{
var (mode, words) = LootPatternText.Parse(pattern);
LootTextMode keep = buf.Mode ?? mode;
if (keep == LootTextMode.Regex) { buf.Mode = LootTextMode.Regex; buf.Words = pattern; }
else if (pattern.Length == 0) { buf.Mode = keep; buf.Words = ""; }
else { buf.Mode = mode; buf.Words = mode == LootTextMode.Regex ? pattern : words; }
buf.ParsedFrom = pattern;
}
LootTextMode shown = buf.Mode ?? LootTextMode.Contains;
float mw = Math.Min(120, Math.Max(80, w * 0.36f));
if (PickerButton(id + "_mode", LootPatternText.Label(shown), p, mw - 2, h, ro))
{
FieldBuffer target = buf;
LootEditConditionDto dto = c;
_picker.Open(new Vector2(p.X, p.Y + h), LootPatternText.Labels, (int)shown, k =>
{
LootTextMode next = LootPatternText.Modes[k];
LootTextMode was = target.Mode ?? LootTextMode.Contains;
if (next == was || dto.Lines.Count == 0) return;
// Into regex: the pattern as it is. Out of regex: its words when it has a plain shape.
string words = next == LootTextMode.Regex ? dto.Lines[0]
: was == LootTextMode.Regex ? (LootPatternText.Parse(dto.Lines[0]) is var (m2, w2) && m2 != LootTextMode.Regex ? w2 : "")
: target.Words;
dto.Lines[0] = LootPatternText.Build(next, words);
target.Mode = next;
target.Words = words;
target.ParsedFrom = dto.Lines[0];
target.Shown = null; // the box shows the new words
}, Math.Max(150, mw));
}
SafeImGui.SetItemTooltip("How the text is matched (case doesn't matter). Pick \"regex\" to type a pattern yourself.");
if (Field(id, buf, buf.Words, new Vector2(p.X + mw, p.Y), w - mw, LootPatternText.Hint(shown), ro, out string typed, h))
{
buf.Words = typed;
c.Lines[0] = LootPatternText.Build(shown, typed);
buf.ParsedFrom = c.Lines[0];
}
if (shown != LootTextMode.Regex)
SafeImGui.SetItemTooltip(c.Lines[0].Length > 0
? "Written to the profile as: " + c.Lines[0] + (shown is LootTextMode.Contains or LootTextMode.NotContains ? "\nSeveral words: separate them with commas (either of them)." : "")
: (shown is LootTextMode.Contains or LootTextMode.NotContains ? "Type a word. Several: separate them with commas (either of them)." : "Type the text."));
}
/// <summary>A whole number: "45", "45.0" (a buffed-long value written as a double).</summary>
private static bool TryWhole(string? raw, out int value)
{

View file

@ -2,8 +2,9 @@
// 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":
// RynthLua v2 (ScriptInfos present), tabs "Scripts" | "Editor", "Live reload:
// on/off" (a RynthLua with live reload; /lua livereload), 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
@ -161,13 +162,37 @@ internal sealed class LuaFace : IImGuiPanel
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;
// RynthLua's live reload (a RynthLua that has it says so in the payload): /lua livereload on|off.
float lrW = 0;
if (LuaLiveReload.Label(d.LiveReload) is { } lrLabel)
{
bool on = d.LiveReload == true;
string caption = PhosphorIcons.ArrowsClockwise + " " + lrLabel;
lrW = ButtonWidth(caption) + 4;
if (Button("##lua_live", caption, new Vector2(p.X + sw + ew + 8, p.Y), new Vector2(lrW, h), on ? Teal : Mute, on ? Selected : BtnFill))
LuaCommands.Chat(LuaLiveReload.ClickArgs(on));
SafeImGui.SetItemTooltip(LuaLiveReload.Tip(on));
lrW += 6;
}
// Stop every running script (/lua stop all), while two or more run.
if (d.RunningCount > 1 && d.ScriptInfos is { } running)
{
const string StopAll = PhosphorIcons.Stop + " Stop all";
float saW = ButtonWidth(StopAll) + 4;
if (Button("##lua_stopall", StopAll, new Vector2(p.X + sw + ew + 8 + lrW, p.Y), new Vector2(saW, h), Text, StopBg))
foreach (LuaScriptInfo si in running)
if (si.Running) LuaCommands.Send("stopScript", si.Name);
SafeImGui.SetItemTooltip("Stop every running script. Also: /lua stop all");
lrW += saW + 6;
}
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 left = p.X + sw + ew + 10 + lrW, 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);

View file

@ -691,6 +691,20 @@ internal sealed partial class MetaFace
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
bool canRevert = _editOriginal != null && !MetaRuleEdit.SameContent(_editRule, _editOriginal);
string problem = SaveProblem();
float problemX = p.X;
if (canRevert) problemX += BtnW(PhosphorIcons.ArrowCounterClockwise + " Revert", 60) + 6;
if (problem.Length > 0 && !_editConfirmDelete)
{
// The editor's status line: why the last change isn't saved (the full text on hover).
string del = PhosphorIcons.Trash + (_editIndex < 0 ? " Discard" : " Delete rule");
float room = p.X + w - BtnW(del, 70) - 6 - problemX;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
dl.AddText(new Vector2(problemX, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Red, Fit(problem, Math.Max(20, room)));
ImGuiNET.ImGui.PopFont();
if (ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(problemX, p.Y), new Vector2(problemX + Math.Max(20, room), p.Y + h)))
ImGuiNET.ImGui.SetTooltip(problem);
}
if (canRevert)
{
string label = PhosphorIcons.ArrowCounterClockwise + " Revert";
@ -702,7 +716,7 @@ internal sealed partial class MetaFace
}
ImGuiNET.ImGui.SetItemTooltip("Undo every change since you opened this rule (and save that)");
}
else
else if (problem.Length == 0)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
dl.AddText(new Vector2(p.X, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute),

View file

@ -207,15 +207,18 @@ internal sealed partial class MetaFace
FilterRow(w);
// A note over the list: the editor closed under a meta switch, or the meta can't do anything.
string note = string.Empty;
if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000) note = _listNote;
// A change that wasn't saved comes first, in red, and stays until the next result (2026-11-01).
string note = SaveProblem();
bool unsaved = note.Length > 0;
if (unsaved) { }
else if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000) note = _listNote;
else if (_data.Rules.Count > 0 && !HasRulesIn(_data.CurrentState))
note = $"The current state, {_data.CurrentState}, has no rules: the meta does nothing until something changes the state.";
if (note.Length > 0)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, unsaved ? Red : Amber);
ImGuiNET.ImGui.TextUnformatted(note);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PopTextWrapPos();

View file

@ -102,8 +102,7 @@ internal sealed partial class MetaFace : IImGuiPanel
// ── Saving ───────────────────────────────────────────────────────────
private readonly MetaAutosave _autosave = new();
private readonly MetaBackupPlan _backup = new();
private long _saveSentAt = -1; // ms (TickCount64) of the last rule command, for "Saving..."
private long _saveSentVersion; // the snapshot version then
private readonly MetaSaveWatch _saveWatch = new(); // waits for RynthAi's answer to each change
private static long NowMs => Environment.TickCount64;
// ── Rule editor ──────────────────────────────────────────────────────
@ -145,6 +144,7 @@ internal sealed partial class MetaFace : IImGuiPanel
UiSources.Meta.RequestRefresh();
CodeEditor.SetMetaVocabulary(MetaVocabulary.StructKeywords, MetaVocabulary.ConditionKeywords, MetaVocabulary.ActionKeywords);
_backup.NewSession(); // a new editing session: the first save backs the file up again
_saveWatch.Reset();
}
public void OnHidden()
@ -271,8 +271,7 @@ internal sealed partial class MetaFace : IImGuiPanel
// Saving over another meta keeps that one's old copy as <file>.bak.
MetaCommands.Backup(target, MetaBackupPlan.BackupOf(target));
MetaCommands.Simple("save_file", path: target);
_saveSentAt = NowMs;
_saveSentVersion = _seenVersion;
_saveWatch.Sent(NowMs, SeenSaveSeq, MetaCommands.Undelivered);
}
_saveAs = false;
}
@ -324,6 +323,7 @@ internal sealed partial class MetaFace : IImGuiPanel
{
float m = Math.Max(ImGuiNET.ImGui.CalcTextSize(SavedText).X, ImGuiNET.ImGui.CalcTextSize(SavingText).X);
m = Math.Max(m, Math.Max(ImGuiNET.ImGui.CalcTextSize(EditingText).X, ImGuiNET.ImGui.CalcTextSize(NoFileText).X));
m = Math.Max(m, ImGuiNET.ImGui.CalcTextSize(UnconfirmedText).X);
if (editor) m = Math.Max(m, ImGuiNET.ImGui.CalcTextSize(DraftText).X);
return m + 6;
}
@ -339,10 +339,37 @@ internal sealed partial class MetaFace : IImGuiPanel
return _editTyping
? (EditingText, Amber, "Saves when you leave the box (Enter, Tab or click elsewhere).")
: (SavingText, Amber, "Saving in a moment...");
if (_saveSentAt >= 0 && _seenVersion == _saveSentVersion && NowMs - _saveSentAt < 2500)
return (SavingText, Amber, "Saving " + file + "...");
switch (_saveWatch.State(NowMs, _data.SaveResult, MetaCommands.Undelivered))
{
case MetaSaveState.Saving:
return (SavingText, Amber, "Saving " + file + "...");
case MetaSaveState.Failed:
case MetaSaveState.NotSent:
return (NoFileText, Red, SaveProblem());
case MetaSaveState.Unconfirmed:
return (UnconfirmedText, Amber, SaveProblem());
}
string bak = System.IO.Path.GetFileName(MetaBackupPlan.BackupOf(MetaBackupPlan.WrittenFile(_data.CurrentMetaPath!)));
return (SavedText, Green, $"Every change saves to {file} on its own. The first change after opening this panel keeps the file as it was in {bak}.");
string last = _data.SaveResult is { Seq: > 0, Text.Length: > 0 } r ? $"\nLast: {r.Text}" : "";
return (SavedText, Green, $"Every change saves to {file} on its own. The first change after opening this panel keeps the file as it was in {bak}.{last}");
}
private const string UnconfirmedText = PhosphorIcons.Warning + " Not confirmed";
/// <summary>The result seq the panel has seen (0: none, or a RynthAi without results).</summary>
private long SeenSaveSeq => _data.SaveResult?.Seq ?? 0;
/// <summary>Why the last change isn't saved, for the status line and the indicator's tooltip; empty when it is.</summary>
private string SaveProblem()
{
if (string.IsNullOrEmpty(_data.CurrentMetaPath)) return string.Empty; // "Not saved" + its own hint
return _saveWatch.State(NowMs, _data.SaveResult, MetaCommands.Undelivered) switch
{
MetaSaveState.Failed => _data.SaveResult!.Text,
MetaSaveState.NotSent => "Not saved: the change never reached RynthAi (it isn't loaded, or is too old for this panel). Reload RynthAi and make the change again.",
MetaSaveState.Unconfirmed => "RynthAi hasn't confirmed the last change. If this stays, it may not have been saved: check the rule after reopening the meta.",
_ => string.Empty,
};
}
/// <summary>The save status, right-aligned in (pos, width); hover for details.</summary>
@ -360,15 +387,14 @@ internal sealed partial class MetaFace : IImGuiPanel
/// <summary>
/// Every command that changes the meta's rules goes through here: before the first one of this
/// session the file is backed up, and the indicator shows "Saving..." until the next snapshot.
/// (RynthAi writes the file after each such command.)
/// session the file is backed up, and the indicator shows "Saving..." until RynthAi answers
/// (MetaSaveWatch; RynthAi writes the file after each such command and reports the result).
/// </summary>
private void SendEdit(MetaCmd cmd)
{
if (_backup.Before(_data.CurrentMetaPath) is { } b) MetaCommands.Backup(b.File, b.Backup);
MetaCommands.Send(cmd);
_saveSentAt = NowMs;
_saveSentVersion = _seenVersion;
_saveWatch.Sent(NowMs, SeenSaveSeq, MetaCommands.Undelivered);
}
private void BeginSaveAs()

View file

@ -6,7 +6,7 @@
// Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate /
// delete / set active / move here on the selection; nearest, reverse, snap to
// path, point at selection, pause, simplify; recording and trail -> route),
// a chat waypoint, Save As, the nav file picker, the nav point reach
// a chat waypoint, Save As, the nav file picker (at the top), the nav point reach
// (RynthAi's FollowNavMin, the same row as Settings > Navigation), and the
// waypoint list (click selects, Ctrl/Shift-click multi-selects, double-click
// sets active, right-click edits, X or Delete deletes, => marks the active one).
@ -56,6 +56,7 @@ internal sealed class NavFace : IImGuiPanel
{
PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path",
PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify",
PhosphorIcons.ArrowCounterClockwise + " Restart",
};
private static readonly string[] RowMenu =
{ "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" };
@ -110,6 +111,19 @@ internal sealed class NavFace : IImGuiPanel
bool typing = false;
NavPayload d = _data;
bool navActive = d.MacroRunning && d.NavigationEnabled;
Vector2 p;
// Nav file picker, first (2026-11-01, the owner: "move the nav file selection to the top")
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);
}
// Active nav + status
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
@ -118,7 +132,7 @@ internal sealed class NavFace : IImGuiPanel
if (d.NavStatusLine.Length > 0) Label(d.NavStatusLine, d.NavIsStuck ? Amber : Green);
// Start / Stop
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
p = ImGuiNET.ImGui.GetCursorScreenPos();
if (Button("##startstop", navActive ? StopNav : StartNav, p, new Vector2(w, 28), Text, navActive ? StopBg : StartBg))
{
if (navActive)
@ -258,18 +272,6 @@ internal sealed class NavFace : IImGuiPanel
}
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);
@ -441,6 +443,10 @@ internal sealed class NavFace : IImGuiPanel
_picker.Open(at, NavCommands.SimplifyLabels, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300);
break;
case 6:
// Run the route again from its first point (a finished Once route too); answers in chat.
RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra nav restart");
break;
}
// Record | Route from Trail...
@ -456,7 +462,11 @@ internal sealed class NavFace : IImGuiPanel
Vector2 tp = new(p.X + half + 4, p.Y);
if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2))
_picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300);
{
// The last choice wipes the trail (/ra navtrail clear); the others make a route of it.
if (i == NavCommands.TrailClearChoice) RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra navtrail clear");
else NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 });
}, width: 300);
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
SafeImGui.SetTooltip(_data.TrailPoints >= 2
? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed."

View file

@ -210,15 +210,31 @@ internal sealed unsafe class LogFace : IImGuiPanel
}
}
/// <summary>Tracker: the session-stat rows (TrackerSource) over an adjustable-opacity background.</summary>
/// <summary>
/// Tracker: the session-stat rows (TrackerSource) over an adjustable-opacity background, or text only
/// (TrackerSettings.TextOnly: bare, the rows shadowed, clicks pass through except over them).
/// </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 uint ResetBorder => RynthTheme.AccentFill;
// Text only: no background behind it, so brighter than the framed look, each with a shadow.
private static readonly uint BareLabel = RynthTheme.Argb(0xFFCFCFCF);
private static readonly uint BareValue = RynthTheme.Argb(0xFFFFFFFF);
private static readonly uint BareShadow = RynthTheme.Argb(0xD0000000);
private int _opacity;
// Text only: the mouse is over what the last frame drew, so the window takes input (to drag it, or
// for the frame button); elsewhere clicks reach the game. A press that began there keeps it.
private bool _hot, _pressHot;
/// <summary>Text only is bare: docked, no frame, title, background or grip (popped out it is framed as usual).</summary>
public bool Bare => TrackerSettings.TextOnly;
public bool ClickThrough => Bare && !_hot && !_pressHot;
public void OnShown()
{
UiSources.Tracker.Subscribe();
@ -229,6 +245,90 @@ internal sealed class TrackerFace : IImGuiPanel
public void OnHidden() => UiSources.Tracker.Unsubscribe();
public void Draw()
{
if (TrackerSettings.TextOnly && !ImGuiPanelHost.DrawingEmbedded && !ImGuiPopOuts.InPopOutFrame)
{
DrawTextOnly();
return;
}
_hot = _pressHot = false;
DrawFramed();
}
/// <summary>
/// Text only: each row's label and value with a 1 px shadow, nothing behind them. The rows are a
/// drag handle; the button at the end of the first row (faint until the mouse is on the rows)
/// brings the frame back.
/// </summary>
private void DrawTextOnly()
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
float width = Math.Max(60, ImGuiNET.ImGui.GetContentRegionAvail().X);
Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos;
bool wasHot = _hot;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
float rowH = ImGuiNET.ImGui.GetTextLineHeight() + 1;
float buttonW = rowH + 4;
TrackerSnapshot? snap = UiSources.Tracker.Current?.Value;
string[]? values = snap?.Values;
string[] labels = snap?.Labels ?? TrackerSnapshot.DefaultLabels;
ImFontPtr labelFont = ImGuiNET.ImGui.GetFont();
float labelSize = ImGuiNET.ImGui.GetFontSize();
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono9));
ImFontPtr valueFont = ImGuiNET.ImGui.GetFont();
float valueSize = ImGuiNET.ImGui.GetFontSize();
float y = origin.Y;
for (int i = 0; i < labels.Length; i++)
{
// The first row stops short of the frame button.
float right = origin.X + width - (i == 0 ? buttonW + 2 : 0);
Shadowed(dl, labelFont, labelSize, new Vector2(origin.X, y), BareLabel, labels[i]);
string value = values != null && i < values.Length ? values[i] : "—";
float w = ImGuiNET.ImGui.CalcTextSize(value).X;
Shadowed(dl, valueFont, valueSize, new Vector2(Math.Max(origin.X, right - w), y), BareValue, value);
y += rowH;
}
ImGuiNET.ImGui.PopFont();
float height = Math.Max(rowH, y - origin.Y);
// The rows: a drag handle (the window has no title bar to hold).
ImGuiNET.ImGui.SetCursorScreenPos(origin);
ImGuiNET.ImGui.InvisibleButton("##tracker_textonly_drag", new Vector2(Math.Max(1, width - buttonW - 2), height));
ImGuiPanelHost.DragWindowWithLastItem();
if (ImGuiNET.ImGui.IsItemHovered() && !ImGuiNET.ImGui.IsItemActive())
ImGuiNET.ImGui.SetTooltip("Drag to move the Tracker.");
// Frame button: faint until the mouse is on the rows.
Vector2 bp = new(origin.X + width - buttonW, origin.Y);
ImGuiNET.ImGui.SetCursorScreenPos(bp);
float alpha = wasHot ? 1f : 0.35f;
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.Alpha, alpha);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(1, 0));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, ResetBg);
if (ImGuiNET.ImGui.Button(PhosphorIcons.SquaresFour + "##tracker_frame", new Vector2(buttonW, rowH)))
TrackerSettings.SetTextOnly(false);
ImGuiNET.ImGui.SetItemTooltip("Show the Tracker's frame and background again.");
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopFont();
// Hot for the next frame: the mouse over the rows or the button.
bool over = mouse.X >= origin.X && mouse.X <= origin.X + width && mouse.Y >= origin.Y && mouse.Y <= origin.Y + height;
_hot = over;
bool down = ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left);
if (!down) _pressHot = false;
else if (over && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) _pressHot = true;
}
private static void Shadowed(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 p, uint color, string text)
{
dl.AddText(font, size, p + new Vector2(1, 1), BareShadow, text);
dl.AddText(font, size, p, color, text);
}
private void DrawFramed()
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
// Background behind the content only (like the Avalonia StackPanel), so
@ -240,11 +340,12 @@ internal sealed class TrackerFace : IImGuiPanel
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
// Title row: [Tracker] [===slider===] [reset]
// Title row: [Tracker] [===slider===] [text only] [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));
float textOnlyW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.TextAa).X + 8;
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(10, ImGuiNET.ImGui.GetContentRegionAvail().X - resetW - textOnlyW - 8));
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);
@ -256,6 +357,15 @@ internal sealed class TrackerFace : IImGuiPanel
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ResetBorder);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 1));
bool canBare = !ImGuiPanelHost.DrawingEmbedded && !ImGuiPopOuts.InPopOutFrame;
ImGuiNET.ImGui.BeginDisabled(!canBare);
if (ImGuiNET.ImGui.Button(PhosphorIcons.TextAa + "##textonly"))
TrackerSettings.SetTextOnly(true);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip(canBare
? "Text only: hide the frame and background, just the numbers (clicks pass through to the game).\nThe button at the end of its first row brings the frame back."
: "Text only works while the Tracker is docked (not popped out).");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + "##reset"))
UiSources.Tracker.RequestReset();
ImGuiNET.ImGui.SetItemTooltip("Reset the session stats");

View file

@ -15,6 +15,10 @@
// (wantHeight) as its minimum and is fitted to it whenever it changes and the
// mouse is up (a frameless window's empty rows would still catch clicks meant
// for the game); a text size change scales its width along with its fonts.
// A "scale": "draw" window set bigger than normal (PanelDrawScale) gets the
// fonts baked nearest above its size while the plugin draws (2026-11-01: from
// the normal bake, stretched, its text blurred); the font pushed for its menus
// and tooltips stays at the panel's text size.
// docs/PLUGIN_WINDOWS.md. AC's render thread.
// ============================================================================
@ -39,11 +43,12 @@ internal sealed class PluginWindowFace : IImGuiPanel
// "fitHeight" (v90): the content height the plugin asked for (logical units; 0 = not known
// yet), and the text size factor and width (logical) the window was last fitted at.
private readonly bool _fitHeight;
private readonly bool _fitHeight, _drawScale;
private readonly float _minWidth;
private float _contentHeight, _fitK, _fitWidth;
public PluginWindowFace(string plugin, string surface, string title, bool fitHeight = false, float minWidth = 0f)
public PluginWindowFace(string plugin, string surface, string title, bool fitHeight = false, float minWidth = 0f,
bool drawScale = false)
{
_plugin = plugin;
_title = title;
@ -51,6 +56,15 @@ internal sealed class PluginWindowFace : IImGuiPanel
_idScope = "##pw_" + surface;
_fitHeight = fitHeight;
_minWidth = minWidth;
_drawScale = drawScale;
}
/// <summary>The font step the plugin draws with: a draw-scale window's own size's (baked), else the text size's.</summary>
private int DrawFontStep(int textStep)
{
if (!_drawScale) return textStep;
int pct = PanelDrawScale.Get(_title);
return pct > 0 ? ImGuiFonts.BakedStepNear(PanelDrawScale.FontStep(pct, EngineFrameController.FontScale)) : textStep;
}
/// <summary>A fitHeight window's minimum: its minimum width at its text size, and the content's height.</summary>
@ -78,10 +92,13 @@ internal sealed class PluginWindowFace : IImGuiPanel
guarded = guarded && ImGuiStackGuard.AtWindowBase(bodyBase); // drawn anywhere else: as before
ImGuiNET.ImGui.PushID(_idScope);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
int textStep = ImGuiFonts.CurrentStep;
ImGuiFonts.CurrentStep = DrawFontStep(textStep);
ImGuiStackGuard.Mark given = guarded ? ImGuiStackGuard.Take() : default;
try { result = PluginManager.RenderEmbed(_plugin, _surface, avail, out want); }
finally
{
ImGuiFonts.CurrentStep = textStep;
ImGuiStackGuard.Mark after = default;
StackCheck check = guarded ? ImGuiStackGuard.Check(given, out after) : StackCheck.Balanced;
if (check == StackCheck.Balanced)

View file

@ -14,6 +14,9 @@
// legend. Your own arrow, the compass letters and the coordinates have sizes too.
// Outdoors the World Map's picture can be drawn behind it (RadarSettingsStore.ShowWorldMap; the
// tiles come from WorldMapTiles through WorldMapTileDrawer, the same code as the World Map).
// The object selected in game is highlighted (RadarSettingsStore.HighlightSelected, RadarSelection):
// a ring in its own colour round its marker and the hover label beside it, or an arrow on the
// edge when it is off the picture.
//
// Data: UiSources.Radar (RadarView, lookups precomputed). World geometry is
// drawn without anti-aliasing (crisp tiling like the Avalonia face's aliased
@ -72,6 +75,8 @@ internal sealed class RadarFace : IImGuiPanel
// The round radar (RadarSettingsStore.RoundRadar): this frame's circle, read by the drawing helpers.
private static bool _round;
private static RoundMask _mask;
// The selected object's marker this frame (RadarSelection.Highlighted), or null; drawn over everything.
private static RadarMarker? _sel;
/// <summary>Markers move: popped out, redraw smoothly even when idle.</summary>
public int PopOutIdleHz => 20;
@ -167,6 +172,11 @@ internal sealed class RadarFace : IImGuiPanel
dl.AddLine(new Vector2(worldMin.X, centre.Y), new Vector2(worldMax.X, centre.Y), Crosshair);
}
// The game's current selection (the global AC's SetSelectedObject writes; one read a frame).
uint selectedId = view != null && RadarSettingsStore.HighlightSelected && Compatibility.SelectedTargetHooks.IsInstalled
? Compatibility.SelectedTargetHooks.ReadCurrentSelectedId() : 0;
_sel = view != null ? RadarSelection.Highlighted(RadarSettingsStore.HighlightSelected, view.Live.Markers, selectedId) : null;
if (view != null)
{
ImDrawListFlags saved = dl.Flags;
@ -175,6 +185,7 @@ internal sealed class RadarFace : IImGuiPanel
DrawWorld(dl, view, centre, worldMin, worldMax);
dl.PopClipRect();
dl.Flags = saved;
DrawSelected(dl, view, centre, worldMin, worldMax, origin, panelMax);
DrawOutlinedText(dl, ImGuiFonts.Get(UiFont.UiBold11), view.CoordText,
new Vector2((origin.X + panelMax.X) * 0.5f, panelMax.Y), CoordText, alignBottom: true,
@ -306,7 +317,7 @@ internal sealed class RadarFace : IImGuiPanel
{
foreach (RadarMarker m in live.Markers)
{
if (!RadarSettingsStore.ShowKind(m.Kind)) continue;
if (m == _sel || !RadarSettingsStore.ShowKind(m.Kind)) continue; // the selected one: DrawSelected
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 (_round ? !_mask.Contains(pp) : (pp.X < clipMin.X || pp.X > clipMax.X || pp.Y < clipMin.Y || pp.Y > clipMax.Y)) continue;
@ -323,6 +334,7 @@ internal sealed class RadarFace : IImGuiPanel
foreach (RadarMarker m in live.Markers)
{
if (!markers.NameShown(m.Kind) || !RadarSettingsStore.ShowKind(m.Kind)) continue;
if (m == _sel && RadarSettingsStore.ShowSelectedLabel) continue; // its label has the name
Vector2 pp = proj.P(m.X, m.Y);
if (pp.X < clipMin.X - 8 || pp.X > clipMax.X || pp.Y < clipMin.Y - 8 || pp.Y > clipMax.Y + 8) continue;
if (_round && !_mask.Contains(pp)) continue;
@ -338,6 +350,57 @@ internal sealed class RadarFace : IImGuiPanel
dl.AddLine(centre, tip, PlayerCol, 2);
}
// ── The selected object ────────────────────────────────────────────────
// A ring in the selection colour round its marker (the marker drawn over everything, even when its
// kind's box is off), and the hover label beside it; off the picture, an arrow on the edge pointing
// to it with the label next to the arrow. Drawn anti-aliased, after the world.
private const float ArrowInset = 3f, ArrowLength = 9f, ArrowHalfWidth = 5f;
private readonly TipCache _selTip = new();
private void DrawSelected(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax,
Vector2 panelMin, Vector2 panelMax)
{
RadarMarker? sel = _sel;
if (sel == null) return;
var proj = new Projection(centre, view.Live.Player, RadarSettingsStore.RotateWithPlayer, MathF.Max(0.5f, RadarSettingsStore.Zoom));
Vector2 pp = proj.P(sel.X, sel.Y);
uint col = RynthTheme.Argb(RadarSettingsStore.SelectedColor);
Vector2 anchor;
float gap;
dl.PushClipRect(clipMin, clipMax, true);
if (RadarSelection.EdgeArrow(centre, pp, clipMin, clipMax, _round ? _mask : null, ArrowInset, out Vector2 tip, out Vector2 dir))
{
RadarSelection.ArrowCorners(tip, dir, ArrowLength, ArrowHalfWidth, out Vector2 a, out Vector2 b, out Vector2 c);
dl.AddTriangleFilled(a, b, c, col);
dl.AddTriangle(a, b, c, Outline, 1.5f);
anchor = tip - dir * (ArrowLength * 0.5f);
gap = ArrowLength;
}
else
{
float size = RadarSettingsStore.Markers.SizeOf(sel.Kind);
float r = MathF.Max(6.5f, RadarMarkerStyle.Radius(sel.Kind) * size + 3f);
dl.AddCircle(pp, r, Outline, 20, 3.5f);
RadarMarkerStyle.Draw(dl, sel.Kind, pp, KindCols[sel.Kind], size);
dl.AddCircle(pp, r, col, 20, 2f);
anchor = pp;
gap = r + 4f;
}
dl.PopClipRect();
if (!RadarSettingsStore.ShowSelectedLabel) return;
// The hover label, as a tooltip-styled box kept inside the panel.
string text = _selTip.Get(view, sel);
var style = ImGuiNET.ImGui.GetStyle();
Vector2 pad = new Vector2(6f, 4f);
Vector2 box = ImGuiNET.ImGui.CalcTextSize(text) + pad * 2f;
Vector2 at = RadarSelection.LabelPos(anchor, gap, box, panelMin, panelMax);
dl.AddRectFilled(at, at + box, ImGuiNET.ImGui.GetColorU32(ImGuiCol.PopupBg), style.PopupRounding);
dl.AddRect(at, at + box, col, style.PopupRounding, ImDrawFlags.None, 1f);
dl.AddText(at + pad, ImGuiNET.ImGui.GetColorU32(ImGuiCol.Text), text);
}
// ── World map backdrop ─────────────────────────────────────────────────
// The radar's world coordinates are yards from the world's south-west corner; the World Map's cells
// are 24 yards, so cell = yards / 24 on both axes, and the radar's zoom (px per yard) is 24x that
@ -475,11 +538,7 @@ internal sealed class RadarFace : IImGuiPanel
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 readonly TipCache _hoverTip = new();
private void MarkerInput(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax, bool clicked)
{
@ -517,8 +576,9 @@ internal sealed class RadarFace : IImGuiPanel
dl.PushClipRect(clipMin, clipMax, true);
dl.AddCircle(hitPos, 6.5f, CoordText, 16, 1.5f);
dl.PopClipRect();
if (hit == _sel && RadarSettingsStore.ShowSelectedLabel) return; // its label is already showing
ImGuiNET.ImGui.BeginTooltip();
ImGuiNET.ImGui.TextUnformatted(TipText(view, hit));
ImGuiNET.ImGui.TextUnformatted(_hoverTip.Get(view, hit));
ImGuiNET.ImGui.EndTooltip();
}
@ -621,34 +681,44 @@ internal sealed class RadarFace : IImGuiPanel
}
/// <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.
/// "Name\n12 yd" for the hovered (or selected) marker, plus " 75%" when the marker has an id and
/// the engine has a health reading for it (MonsterHudData: one locked lookup, hover and the
/// selected marker only). Rebuilt only when the marker, whole yards or whole percent change; one
/// cache for the hover tooltip, one for the selected object's label, so neither rebuilds the other's.
/// </summary>
private string TipText(RadarView view, RadarMarker m)
private sealed class TipCache
{
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))
private byte _tipKind = byte.MaxValue;
private string? _tipLabel;
private int _tipDistance = int.MinValue;
private int _tipPct = -1;
private string _tipText = "";
public string Get(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 kind always follows it, so a dot says which show box
// in the settings hides it (a fellow is not a "Player", your kill's corpse not a "Corpse").
string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind)
: m.Label + " (" + RadarKind.Name(m.Kind) + ")";
var inv = System.Globalization.CultureInfo.InvariantCulture;
_tipText = name + "\n" + d.ToString(inv) + " yd"
+ (pct >= 0 ? " " + pct.ToString(inv) + "%" : "");
return _tipText;
_tipKind = m.Kind;
_tipLabel = m.Label;
_tipDistance = d;
_tipPct = pct;
// A label is the object's name; the kind always follows it, so a dot says which show box
// in the settings hides it (a fellow is not a "Player", your kill's corpse not a "Corpse").
string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind)
: m.Label + " (" + RadarKind.Name(m.Kind) + ")";
var inv = System.Globalization.CultureInfo.InvariantCulture;
_tipText = name + "\n" + d.ToString(inv) + " yd"
+ (pct >= 0 ? " " + pct.ToString(inv) + "%" : "");
return _tipText;
}
}
// ── Compass and text ───────────────────────────────────────────────────
@ -763,6 +833,26 @@ internal sealed class RadarFace : IImGuiPanel
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 |= Check("Highlight the selected object", ref RadarSettingsStore.HighlightSelected);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Whatever you have selected in game (a monster, NPC, player, portal, door, corpse or item on the ground)\ngets a ring in this colour round its dot, even when its kind's box is off.\nOff the radar's picture, an arrow on the edge points the way to it.");
ImGuiNET.ImGui.SameLine();
Vector4 selCol = RynthTheme.Vec(RadarSettingsStore.SelectedColor);
if (ImGuiNET.ImGui.ColorEdit4("##selcol", ref selCol, PickFlags))
{
RadarSettingsStore.SelectedColor = ToArgb(selCol);
_colorDirty = true;
}
if (ImGuiNET.ImGui.IsItemHovered() && !ImGuiNET.ImGui.IsItemActive())
ImGuiNET.ImGui.SetTooltip("The selection ring's colour (click to change it).");
if (RadarSettingsStore.HighlightSelected)
{
ImGuiNET.ImGui.Indent();
changed |= Check("Show its label", ref RadarSettingsStore.ShowSelectedLabel);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("The hover label (name, distance, health) stays beside the selected object while it is selected.");
ImGuiNET.ImGui.Unindent();
}
changed |= Slider("Opacity", ref RadarSettingsStore.Opacity, 0.05f, 1.0f, "%.2f");
changed |= Slider("Zoom", ref RadarSettingsStore.Zoom, 0.5f, 6.0f, "%.1f");
changed |= Check("World map behind the radar (outdoors)", ref RadarSettingsStore.ShowWorldMap);
@ -865,8 +955,6 @@ internal sealed class RadarFace : IImGuiPanel
float xName = 232 * scale, xSize = 268 * scale, xText = 350 * scale;
MarkerStyleSettings markers = RadarSettingsStore.Markers;
MarkerStyleEditor.HeaderRow(xName, xSize, xText);
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)
{
@ -893,7 +981,7 @@ internal sealed class RadarFace : IImGuiPanel
if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(KindTips[kind]);
ImGuiNET.ImGui.SameLine(190 * scale);
Vector4 v = RynthTheme.Vec(RadarSettingsStore.KindColors[kind]);
if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, pickFlags))
if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, PickFlags))
{
RadarSettingsStore.KindColors[kind] = ToArgb(v);
_colorDirty = true;
@ -922,7 +1010,7 @@ internal sealed class RadarFace : IImGuiPanel
RadarSettingsStore.ResetKindColors();
changed = true;
}
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Every kind back to its default colour (show boxes stay as they are).");
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Every kind, and the selection ring, back to its default colour (show boxes stay as they are).");
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Reset sizes and names"))
{
@ -935,6 +1023,10 @@ internal sealed class RadarFace : IImGuiPanel
private static bool _colorDirty;
// The colour swatches: click to pick, alpha included.
private const ImGuiColorEditFlags PickFlags = ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel
| ImGuiColorEditFlags.AlphaBar | ImGuiColorEditFlags.AlphaPreviewHalf;
private static uint ToArgb(Vector4 v)
{
static uint B(float f) => (uint)Math.Clamp((int)MathF.Round(f * 255f), 0, 255);

View file

@ -0,0 +1,116 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/RadarSelection.cs
// The object selected in game, highlighted on the radar (2026-10-31, a player's
// request: "Can the hover icon stay over whichever mob/door/etc. you have
// selected?"). RadarFace reads AC's current selection each frame (the global the
// SetSelectedObject hook reads, SelectedTargetHooks.ReadCurrentSelectedId: no new
// hook) and draws a ring in its own colour round that object's marker, with the
// hover label (name, distance, health) beside it. Off the radar's picture, a small
// arrow on the edge points the way to it.
//
// The rules, pure (no ImGui, no AC), so tools\RadarSettingsTests links this file:
// - which marker is the selected one: the marker with the selected object's id;
// none when nothing is selected or the marker has no id (RynthAi builds before
// 2026-10-01 send none);
// - it clears when the selection clears, or the object is no longer one of the
// radar's markers (gone, out of the client's view, an item in a pack);
// - the selected object is shown even when its kind's show box is off (items on
// the ground start hidden, and the player picked this one);
// - where the edge arrow goes, and where the label sits.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using RynthCore.Engine.UI.Data;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal static class RadarSelection
{
/// <summary>
/// The marker of the selected object, or null: nothing selected (id 0), the object isn't one of
/// the markers, or the markers carry no ids. A kind this engine doesn't know (a newer RynthAi's) is
/// never highlighted: it has no shape or colour here. A List, not an interface, so the loop allocates nothing.
/// </summary>
public static RadarMarker? Find(List<RadarMarker>? markers, uint selectedId)
{
if (selectedId == 0 || markers == null) return null;
foreach (RadarMarker m in markers)
if (m.Id == selectedId)
return m.Kind < RadarKind.Count ? m : null;
return null;
}
/// <summary>Whether a marker is highlighted this frame: the setting is on and it is the selected object's.</summary>
public static RadarMarker? Highlighted(bool settingOn, List<RadarMarker>? markers, uint selectedId) =>
settingOn ? Find(markers, selectedId) : null;
/// <summary>
/// The edge arrow toward a marker that is off the radar's picture. <paramref name="target"/> is the
/// marker's screen point; the picture is the box <paramref name="min"/>..<paramref name="max"/>, or the
/// circle <paramref name="round"/> on the round radar. False when the marker is on the picture (it is
/// drawn where it is) or is at the centre. Otherwise <paramref name="tip"/> is the arrow's point,
/// <paramref name="inset"/> px inside the edge on the line from <paramref name="centre"/> to the marker,
/// and <paramref name="dir"/> the unit direction it points.
/// </summary>
public static bool EdgeArrow(Vector2 centre, Vector2 target, Vector2 min, Vector2 max, RoundMask? round, float inset,
out Vector2 tip, out Vector2 dir)
{
tip = default;
dir = default;
if (round is RoundMask circle)
{
if (circle.Contains(target)) return false;
}
else if (target.X >= min.X && target.X <= max.X && target.Y >= min.Y && target.Y <= max.Y) return false;
Vector2 d = target - centre;
float len = d.Length();
if (!(len > 1e-4f) || !float.IsFinite(len)) return false;
dir = d / len;
float t;
if (round is RoundMask c)
t = MathF.Max(0f, c.Radius - inset);
else
{
// Onto the box: the nearer of the two sides the ray meets.
float hx = MathF.Max(0f, MathF.Min(centre.X - min.X, max.X - centre.X) - inset);
float hy = MathF.Max(0f, MathF.Min(centre.Y - min.Y, max.Y - centre.Y) - inset);
float tx = MathF.Abs(dir.X) > 1e-6f ? hx / MathF.Abs(dir.X) : float.MaxValue;
float ty = MathF.Abs(dir.Y) > 1e-6f ? hy / MathF.Abs(dir.Y) : float.MaxValue;
t = MathF.Min(tx, ty);
}
tip = centre + dir * t;
return true;
}
/// <summary>
/// The edge arrow's three corners: the point at <paramref name="tip"/>, the base
/// <paramref name="length"/> px back toward the centre and <paramref name="halfWidth"/> px to each side.
/// </summary>
public static void ArrowCorners(Vector2 tip, Vector2 dir, float length, float halfWidth,
out Vector2 a, out Vector2 b, out Vector2 c)
{
var side = new Vector2(-dir.Y, dir.X);
Vector2 back = tip - dir * length;
a = tip;
b = back + side * halfWidth;
c = back - side * halfWidth;
}
/// <summary>
/// Where the label's box (<paramref name="size"/>) goes: to the right of a marker at
/// <paramref name="anchor"/>, <paramref name="gap"/> px clear of it, vertically centred; on the left when
/// it would run past <paramref name="boundsMax"/>; then kept inside the bounds as far as it fits.
/// </summary>
public static Vector2 LabelPos(Vector2 anchor, float gap, Vector2 size, Vector2 boundsMin, Vector2 boundsMax)
{
float x = anchor.X + gap;
if (x + size.X > boundsMax.X) x = anchor.X - gap - size.X;
float y = anchor.Y - size.Y * 0.5f;
x = MathF.Max(boundsMin.X, MathF.Min(x, boundsMax.X - size.X));
y = MathF.Max(boundsMin.Y, MathF.Min(y, boundsMax.Y - size.Y));
return new Vector2(x, y);
}
}

View file

@ -562,6 +562,15 @@ internal sealed class RynthNavFace : IImGuiPanel
SectionLabel("WHERE YOUR RECALLS LAND");
foreach (string line in st.MineLines) Wrapped(line, Text, iw);
}
// Lifestone Recall's landing, learned from the lifestone selected or stood at (/rnav tie lifestone).
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const string LsLabel = PhosphorIcons.MapPin + " My lifestone is the one selected";
if (Button("##rc_tiels", LsLabel, p, new Vector2(Math.Min(iw, ButtonWidth(LsLabel) + 8), 22), Text, BtnFill))
RynthNavCommands.Command("tie lifestone");
ImGuiNET.ImGui.SetItemTooltip("Select the lifestone you are tied to (or stand at it), then click: routes can use\nLifestone Recall from then on, without casting it once first. Also: /rnav tie lifestone");
NextLine(p, 26);
}
}
else Wrapped("Update RynthNav (0.6.1) to see your portal ties here and answer \"which tie was it?\" with a button.", Mute, iw);
@ -858,6 +867,19 @@ internal sealed class RynthNavFace : IImGuiPanel
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
Label(view.Summary.Length > 0 ? view.Summary : RynthNavAtlas.Status.Length > 0 ? RynthNavAtlas.Status : "Loading…", Mute);
ImGuiNET.ImGui.PopFont();
// Recent: forget them (/rnav recent clear).
if (_mode == AtlasMode.Recent && view.Rows.Length > 0)
{
Vector2 cp = ImGuiNET.ImGui.GetCursorScreenPos();
const string ClearLabel = PhosphorIcons.Eraser + " Forget recent places";
if (Button("##atl_recent_clear", ClearLabel, cp, new Vector2(ButtonWidth(ClearLabel) + 8, 22), Text, BtnFill))
{
RynthNavCommands.Command("recent clear");
PushQuery();
}
ImGuiNET.ImGui.SetItemTooltip("Empty the Recent list (favorites stay). Also: /rnav recent clear");
NextLine(cp, 26);
}
// List
float listH = Math.Max(60, origin.Y + size.Y - 6 - ImGuiNET.ImGui.GetCursorScreenPos().Y - DetailH - 4);

View file

@ -13,6 +13,21 @@
// gear a chat line and/or the system beep when a new match appears
// (both off by default; they work with the panel closed).
//
// Compact (2026-10-31, the owner: "we should make a small version of it"; in
// item-counter.lua's spirit): only the match rows, tighter, and docked no
// frame or background (IImGuiPanel.Bare); clicks go through to the game except
// over the rows (ClickThrough, worked out from the last frame's rows, as the
// radar's dots). Each row: arrow, name, distance; the coordinates, then the
// kind, when the window is wide enough (SenseLayout.Compact). After the first
// row, two small buttons are always there (faint until the mouse is on the
// panel; SenseLayout.OtherViews): collapse, and back to the full panel.
// Collapsed: one line, "Sense: N"; a click on it (or the caret beside it)
// opens it to compact. The full panel's add row has the compact and collapse
// buttons. The look is kept in sense.txt
// (view=...) and set by /rc sense compact on|off, collapse on|off. Moving and
// resizing are the full panel's (the window keeps its place and size). Popped
// out, or embedded in the Mini Remote, the frame stays; embedded is always full.
//
// 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)
@ -62,6 +77,7 @@ internal sealed class SenseFace : IImGuiPanel
"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" +
"The arrows-in button (or /rc sense compact on) shows just the matches, without the frame.\n" +
"/rc sense opens and closes this panel.";
// ── State ───────────────────────────────────────────────────────────
@ -72,6 +88,16 @@ internal sealed class SenseFace : IImGuiPanel
private bool _openSettings;
private bool _flashing;
// Compact / collapsed: the mouse is over what the last frame drew (rows, the line, the
// buttons), so the window takes input; elsewhere it lets clicks through. A press that began
// there keeps it until the button is released.
private bool _hot, _pressHot;
/// <summary>Compact and collapsed are bare: docked, no frame or background.</summary>
public bool Bare => SenseStore.Layout != SenseLayoutMode.Full;
public bool ClickThrough => Bare && !_hot && !_pressHot;
public void OnShown()
{
SenseStore.EnsureLoadQueued();
@ -82,6 +108,18 @@ internal sealed class SenseFace : IImGuiPanel
public void OnHidden() => UiSources.Sense.Unsubscribe();
public void Draw()
{
SenseLayoutMode layout = SenseStore.Layout;
if (layout != SenseLayoutMode.Full && !ImGuiPanelHost.DrawingEmbedded)
{
DrawSmall(layout);
return;
}
_hot = _pressHot = false;
DrawFull();
}
private void DrawFull()
{
float w = Begin(out Vector2 origin, out Vector2 size);
DrawAddRow(w);
@ -113,7 +151,7 @@ internal sealed class SenseFace : IImGuiPanel
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);
float boxW = Math.Max(60, w - addW - iconW * 4 - 20);
bool enter = TextBox("##sense_input", _input, start, boxW,
PhosphorIcons.MagnifyingGlass + " Name to watch for (* and ? wildcards)", out _,
@ -124,6 +162,17 @@ internal sealed class SenseFace : IImGuiPanel
if (enter || add) AddTerm();
float gx = start.X + boxW + 4 + addW + 4;
// The view switch: compact, then collapsed (one line).
if (IconButton("##sense_compact", PhosphorIcons.ArrowsInLineVertical, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill,
enabled: SenseStore.Loaded))
SenseStore.SetLayout(SenseLayoutMode.Compact);
SafeImGui.SetItemTooltip(SenseLayout.SwitchTip(SenseLayoutMode.Compact));
gx += iconW + 4;
if (IconButton("##sense_collapse", PhosphorIcons.CaretUp, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill,
enabled: SenseStore.Loaded))
SenseStore.SetLayout(SenseLayoutMode.Collapsed);
SafeImGui.SetItemTooltip(SenseLayout.SwitchTip(SenseLayoutMode.Collapsed));
gx += iconW + 4;
if (IconButton("##sense_gear", PhosphorIcons.Gear, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill))
_openSettings = true;
ImGuiNET.ImGui.SetItemTooltip("Alerts");
@ -344,6 +393,218 @@ internal sealed class SenseFace : IImGuiPanel
}
}
// ── Compact and collapsed (bare) ────────────────────────────────────
private static readonly uint Shadow = 0xB0000000;
/// <summary>
/// The bare looks: compact (the match rows only) or collapsed ("Sense: N"). Works out
/// <see cref="_hot"/> for the next frame's <see cref="ClickThrough"/> from what it draws.
/// </summary>
private void DrawSmall(SenseLayoutMode layout)
{
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
bool popped = ImGuiPopOuts.InPopOutFrame;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, Vector2.Zero);
try
{
SenseView view = UiSources.Sense.Current?.Value ?? SenseView.Empty;
Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos;
bool wasHot = _hot;
float k = MathF.Max(0.5f, ImGuiNET.ImGui.GetFontSize() / 10f);
_flashing = false;
Vector2 drawnMax = layout == SenseLayoutMode.Collapsed || view.Rows.Length == 0
? DrawCollapsedLine(origin, view, collapsed: layout == SenseLayoutMode.Collapsed, k)
: DrawCompactRows(origin, size, view, k);
// The view switch after the first line, always there (2026-10-31: a control you can
// see, not one that shows on hover): faint until the mouse is on the panel.
float bh = MathF.Round(SenseLayout.CompactRowHeight * k), bw = bh + 2;
Vector2 bp = new(drawnMax.X + 4, origin.Y);
Vector2 buttonsMax = bp + new Vector2(bw * 2 + 2, bh);
if (SenseStore.Loaded)
{
bool lit = wasHot || popped;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(bp - new Vector2(2, 0), buttonsMax + new Vector2(2, 0), WithAlpha(ShellBg, lit ? 0.85f : 0.45f), 3);
(SenseLayoutMode first, SenseLayoutMode second) = SenseLayout.OtherViews(layout);
ViewButton("##sense_v1", first, bp, new Vector2(bw, bh), lit);
ViewButton("##sense_v2", second, bp + new Vector2(bw + 2, 0), new Vector2(bw, bh), lit);
}
// Hot for the next frame: the mouse over what was drawn or the view switch, or (once hot)
// the strip out to the buttons.
bool over = SenseStore.Loaded
? SenseLayout.TakesMouse(mouse.X, mouse.Y, origin.X, origin.Y, drawnMax.X, drawnMax.Y, bp.X - 2, buttonsMax.X + 2, buttonsMax.Y, wasHot)
: SenseLayout.IsHot(mouse.X, mouse.Y, origin.X, origin.Y, drawnMax.X, drawnMax.Y, buttonsMax.X, buttonsMax.Y, wasHot);
_hot = over;
bool down = ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left);
if (!down) _pressHot = false;
else if (over && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) _pressHot = true;
}
finally
{
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopFont();
}
ImGuiNET.ImGui.SetCursorScreenPos(origin);
ImGuiNET.ImGui.Dummy(new Vector2(1, 1));
}
/// <summary>One button of the view switch: to <paramref name="to"/> (its own glyph). <paramref name="lit"/>: full strength.</summary>
private static void ViewButton(string id, SenseLayoutMode to, Vector2 pos, Vector2 size, bool lit)
{
string glyph = to switch
{
SenseLayoutMode.Compact => PhosphorIcons.CaretDown,
SenseLayoutMode.Collapsed => PhosphorIcons.CaretUp,
_ => PhosphorIcons.ArrowsOutLineVertical,
};
if (IconButton(id, glyph, pos, size, lit ? Text : Faded(Text), lit ? BtnFill : WithAlpha(BtnFill, 0.5f), font: UiFont.Ui11))
SenseStore.SetLayout(to);
SafeImGui.SetItemTooltip(SenseLayout.SwitchTip(to));
}
/// <summary>"Sense: N" (collapsed, or compact with nothing to show). Click opens a collapsed one. Returns its far corner.</summary>
private Vector2 DrawCollapsedLine(Vector2 origin, SenseView view, bool collapsed, float k)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float rowH = MathF.Round(SenseLayout.CompactRowHeight * k);
string text = SenseLayout.CollapsedText(view.Rows.Length);
float tw = ImGuiNET.ImGui.CalcTextSize(text).X;
float iconW = rowH;
Vector2 size = new(iconW + tw + 4, rowH);
ImGuiNET.ImGui.SetCursorScreenPos(origin);
bool clicked = ImGuiNET.ImGui.InvisibleButton("##sense_line", size);
bool hot = ImGuiNET.ImGui.IsItemHovered();
if (hot)
{
dl.AddRectFilled(origin, origin + size, WithAlpha(ShellBg, 0.7f), 3);
ImGuiNET.ImGui.BeginTooltip();
ImGuiNET.ImGui.TextUnformatted(view.Status.Length > 0 ? view.Status : "Scanning...");
ImGuiNET.ImGui.TextUnformatted(collapsed ? "Click to show the matches." : "Nothing matching to show.");
ImGuiNET.ImGui.EndTooltip();
}
if (clicked && collapsed) SenseStore.SetLayout(SenseLayoutMode.Compact);
uint col = view.Rows.Length > 0 ? Amber : Faded(Text);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Binoculars, origin + new Vector2(1, 1), new Vector2(iconW, rowH), Shadow);
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Binoculars, origin, new Vector2(iconW, rowH), col);
ShadowText(dl, new Vector2(origin.X + iconW + 2, origin.Y + (rowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), view.Rows.Length > 0 ? Text : Faded(Text), text);
return origin + size;
}
/// <summary>The compact rows: arrow, name, distance, then the coordinates and the kind when they fit. Returns the far corner.</summary>
private Vector2 DrawCompactRows(Vector2 origin, Vector2 size, SenseView view, float k)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
SenseRow[] rows = view.Rows;
float rowH = MathF.Max(MathF.Round(SenseLayout.CompactRowHeight * k), MathF.Ceiling(ImGuiNET.ImGui.GetFontSize() + 3));
(int shown, bool more) = SenseLayout.CompactFit(size.Y, rowH, rows.Length);
SenseCompactColumns cols = SenseLayout.Compact(size.X, k);
float arrowW = SenseLayout.CompactArrowWidth * k, distW = SenseLayout.CompactDistWidth * k,
locW = SenseLayout.CompactLocWidth * k, kindW = SenseLayout.CompactKindWidth * k;
// The name column is as wide as the longest name shown (up to what the layout allows),
// so the rows end where their text does: past that, clicks reach the game.
float nameW = 0;
for (int i = 0; i < shown; i++) nameW = MathF.Max(nameW, ImGuiNET.ImGui.CalcTextSize(rows[i].Name).X);
nameW = MathF.Min(nameW + 8, cols.NameWidth);
float used = arrowW + nameW + distW + (cols.Location ? locW : 0) + (cols.Kind ? kindW : 0);
long now = Environment.TickCount64;
uint selected = ClientHelperHooks.GetSelectedItemId();
float heading = PlayerHeading(out bool haveHeading);
float fontH = ImGuiNET.ImGui.GetFontSize();
int clicked = -1, hovered = -1;
for (int i = 0; i < shown; i++)
{
SenseRow r = rows[i];
var p = new Vector2(origin.X, origin.Y + i * rowH);
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.PushID(i);
if (ImGuiNET.ImGui.InvisibleButton("##crow", new Vector2(used, rowH))) clicked = i;
bool hot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
if (hot) hovered = i;
bool isSel = r.Id == selected;
if (hot) dl.AddRectFilled(p, p + new Vector2(used, rowH), WithAlpha(ShellBg, 0.7f), 2);
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(used, rowH), WithAlpha(Amber, a), 2);
}
}
if (isSel) dl.AddRect(p, p + new Vector2(used, rowH), Teal, 2);
Vector2 mid = p + new Vector2(arrowW * 0.5f, rowH * 0.5f);
uint kc = KindColor(r.Kind);
if (r.Measured && haveHeading && !float.IsNaN(r.Bearing))
{
DrawArrow(dl, mid + new Vector2(1, 1), r.Bearing - heading, Shadow);
DrawArrow(dl, mid, r.Bearing - heading, kc);
}
else if (r.Measured)
dl.AddCircleFilled(mid, 2.5f, kc);
else
dl.AddCircle(mid, 3.5f, Faded(Mute), 12, 1.2f);
float ty = p.Y + (rowH - fontH) * 0.5f;
float x = p.X + arrowW;
ShadowCell(dl, r.Name, x, ty, nameW - 4, r.Measured ? Text : Mute);
x += nameW;
ShadowCell(dl, r.DistanceText, x, ty, distW - 4, r.Measured ? Text : Faded(Text));
x += distW;
if (cols.Location) { ShadowCell(dl, r.LocationText, x, ty, locW - 4, Mute); x += locW; }
if (cols.Kind) ShadowCell(dl, SenseSource.KindName(r.Kind), x, ty, kindW - 4, kc);
}
int slots = shown;
if (more)
{
// Rows that don't fit (the window keeps the full panel's size): how many, in the last slot.
var p = new Vector2(origin.X, origin.Y + shown * rowH);
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.InvisibleButton("##cmore", new Vector2(used, rowH));
ImGuiNET.ImGui.SetItemTooltip("More matches than fit: make the panel taller in its full view (/rc sense compact off).");
ShadowText(dl, new Vector2(p.X + arrowW, p.Y + (rowH - fontH) * 0.5f), Mute, SenseLayout.MoreText(rows.Length - shown));
slots++;
}
if (clicked >= 0)
AcMainThreadQueue.EnqueueOverlaySelect(rows[clicked].Id);
if (hovered >= 0)
{
ImGuiNET.ImGui.BeginTooltip();
ImGuiNET.ImGui.TextUnformatted(rows[hovered].Tooltip);
ImGuiNET.ImGui.EndTooltip();
}
return origin + new Vector2(used, slots * rowH);
}
private static void ShadowText(ImDrawListPtr dl, Vector2 at, uint color, string text)
{
if (text.Length == 0) return;
dl.AddText(at + new Vector2(1, 1), Shadow, text);
dl.AddText(at, color, text);
}
private static void ShadowCell(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);
ShadowText(dl, new Vector2(x, y), color, text);
dl.PopClipRect();
}
private static void Cell(ImDrawListPtr dl, string text, float x, float y, float width, uint color)
{
if (text.Length == 0 || width <= 0) return;

View file

@ -251,7 +251,19 @@ internal sealed class SettingsRows
ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f));
if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label))
bool clicked = ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label);
Tooltip(row);
if (row.Confirm != null)
{
// Asks first: the question, then the button's own caption to go ahead, or Cancel.
if (clicked)
{
_confirmText = row.Confirm();
ImGuiNET.ImGui.OpenPopup("##confirm");
}
clicked = ConfirmPopup(row.ButtonText ?? row.Label);
}
if (clicked)
{
// A settings edit is applied to this copy and saved like a typed value (the number
// boxes re-sync from the copy next frame); Click, when also set, runs after.
@ -262,7 +274,33 @@ internal sealed class SettingsRows
}
row.Click?.Invoke();
}
Tooltip(row);
}
private string _confirmText = string.Empty;
/// <summary>The open confirmation (the row's ID scope): true when the player went ahead.</summary>
private bool ConfirmPopup(string caption)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(12, 10));
bool open = ImGuiNET.ImGui.BeginPopup("##confirm");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return false;
bool go = false;
try
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
ImGuiNET.ImGui.TextUnformatted(_confirmText);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
if (ImGuiNET.ImGui.Button(caption.TrimEnd('.') + "##confirm_go")) { go = true; ImGuiNET.ImGui.CloseCurrentPopup(); }
ImGuiNET.ImGui.SameLine(0, 8);
if (ImGuiNET.ImGui.Button("Cancel##confirm_no")) ImGuiNET.ImGui.CloseCurrentPopup();
}
finally { ImGuiNET.ImGui.EndPopup(); }
return go;
}
private void Changed(SettingRow row, double value)

View file

@ -0,0 +1,216 @@
// ============================================================================
// RynthCore.Engine - ImGui/UiCost.cs
// Which part of the UI frame is slow: the breakdown behind the heartbeat's
// ui= (UiFrameStats). The logic is in UiCostModel (tested offline); this is
// the engine side - the slots by name, the settings, the log line, the
// heartbeat field and /rc uicost.
//
// Timed (each one Start/Stop pair around a call, on AC's render thread):
// frame setup (fonts, icon textures, backends' NewFrame), the monster HUD
// update and draw (plates, combat text; from EngineFrameController, the
// HUD's own code is not touched), ImGui NewFrame and EndFrame+Render, the
// shell, each plugin's Render / RenderOverlay callback (by plugin), the bar,
// the server menus, the panel host's upkeep, each docked panel and plugin
// window (by title), each popped-out panel (by title) and its pop-out window
// (its own frame, render and present), the ImGui submit (with its vertex
// count), and outside ui= the Nav3D markers and the world overlays' present
// at AC's 3D->UI pass.
// Counted (no timing): the main submit's draw lists, draw calls, texture
// switches and vertices copied, against what copying each command's whole list
// would have been (DrawSubmitPlan), and the textures uploaded that frame (the
// font atlas, the others). The line ends "| submit: ...; uploads: ...", the
// heartbeat field adds " uisub=draws:N,texsw:N,vtx:copied/whole-list,up:font/tex".
//
// engine.json UiCostLog (default on) and UiCostThresholdMs (default 50):
// Settings > Diagnostics, /rc uicost [on|off|<ms>|now]. Off = no timing at
// all (each site is one flag check). On, a frame at or over the threshold
// writes ONE "[UiCost] frame ..." line, at most once every 5 s; the
// heartbeat gets " uitop=..." only while its ui p95 is over the threshold.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace RynthCore.Engine.ImGuiBackend;
internal static class UiCost
{
private static readonly UiCostModel Model = new(Stopwatch.Frequency);
private static readonly object Sync = new();
// Fixed parts of the frame.
internal static readonly int FrameSetup = Model.Register("Frame setup");
internal static readonly int HudUpdate = Model.Register("Monster HUD update");
internal static readonly int ImGuiNewFrame = Model.Register("ImGui NewFrame");
internal static readonly int Shell = Model.Register("Shell");
internal static readonly int MonsterHud = Model.Register("Monster HUD (plates, combat text)", unit: "plates");
internal static readonly int VideoBanner = Model.Register("Video patch banner");
internal static readonly int ServerMenus = Model.Register("Server menus");
internal static readonly int Bar = Model.Register("Bar");
internal static readonly int PanelHost = Model.Register("Panel host upkeep", unit: "panels");
internal static readonly int DrawerBodies = Model.Register("Settings drawer bodies");
internal static readonly int ImGuiRender = Model.Register("ImGui EndFrame+Render");
internal static readonly int FrameFinish = Model.Register("Frame finish (ini, input)");
internal static readonly int PopOuts = Model.Register("Pop-outs upkeep");
internal static readonly int Submit = Model.Register("ImGui submit", unit: "vtx");
internal static readonly int Nav3D = Model.Register("Nav3D markers", outside: true);
internal static readonly int WorldPresent = Model.Register("World overlays present", outside: true);
// Named parts, a slot each the first time the name is seen (render thread only).
private static readonly Dictionary<string, int> PanelSlots = new(StringComparer.Ordinal);
private static readonly Dictionary<string, int> Popped = new(StringComparer.Ordinal);
private static readonly Dictionary<string, int> PopOutWindows = new(StringComparer.Ordinal);
private static readonly Dictionary<string, int> PluginRender = new(StringComparer.Ordinal);
private static readonly Dictionary<string, int> PluginOverlay = new(StringComparer.Ordinal);
private static bool _settingsRead;
/// <summary>Timing on (engine.json UiCostLog). Read once per frame from the settings.</summary>
public static bool Enabled => Model.Enabled;
/// <summary>A timestamp for a Stop, or 0 while timing is off.</summary>
public static long Start()
{
if (!_settingsRead) RefreshSettings();
return Model.Start();
}
public static void Stop(int slot, long start, int count = -1) => Model.Stop(slot, start, count);
/// <summary>What the slots got this frame so far, for <see cref="StopExclusive"/>.</summary>
public static long Mark => Model.Mark;
public static void StopExclusive(int slot, long start, long mark, int count = -1) => Model.StopExclusive(slot, start, mark, count);
/// <summary>The main ImGui submit's counters (DX9Backend.LastSubmit right after it), for the line and the heartbeat.</summary>
public static void SetSubmit(in SubmitStats stats)
{
if (Model.Enabled) Model.SetSubmit(stats);
}
/// <summary>A docked panel or plugin window, by its title.</summary>
public static void StopPanel(string title, long start)
{
if (start == 0) return;
Model.Stop(SlotFor(PanelSlots, title, ""), start);
}
/// <summary>A popped-out panel's drawing, by its title.</summary>
public static void StopPopped(string title, long start)
{
if (start == 0) return;
Model.Stop(SlotFor(Popped, title, " (popped out)"), start);
}
/// <summary>A pop-out window's own frame, render and present (its panel's drawing not included).</summary>
public static void StopPopOutWindow(string title, long start, long mark)
{
if (start == 0) return;
Model.StopExclusive(SlotFor(PopOutWindows, title, " pop-out window"), start, mark);
}
/// <summary>A plugin's Render callback (the shell branch).</summary>
public static void StopPluginRender(string plugin, long start)
{
if (start == 0) return;
Model.Stop(SlotFor(PluginRender, plugin, " (plugin render)"), start);
}
/// <summary>A plugin's RenderOverlay callback (its overlay windows).</summary>
public static void StopPluginOverlay(string plugin, long start)
{
if (start == 0) return;
Model.Stop(SlotFor(PluginOverlay, plugin, " (plugin overlay)"), start);
}
private static int SlotFor(Dictionary<string, int> map, string name, string suffix)
{
if (map.TryGetValue(name, out int slot)) return slot;
slot = Model.Register(string.IsNullOrEmpty(name) ? "(no name)" + suffix : name + suffix);
map[name] = slot;
return slot;
}
/// <summary>
/// The end of a UI frame, where UiFrameStats records it (<paramref name="uiTicks"/> is the same
/// number). Writes the slow-frame line when one is due. Render thread.
/// </summary>
public static void EndFrame(long uiTicks)
{
RefreshSettings();
DX9Backend.TakeUploads(out int fontUploads, out int texUploads); // this frame's (also cleared while off)
if (!Model.Enabled && Model.Mark == 0) return; // off, and nothing left from a frame that was on
Model.AddUploads(fontUploads, texUploads);
string? line;
lock (Sync) line = Model.EndFrame(uiTicks, Stopwatch.GetTimestamp(), logSlow: Model.Enabled);
if (line != null) RynthLog.Info(line);
}
/// <summary>No UI frame this EndScene (the ImGui layer is off): what was timed is dropped. Render thread.</summary>
public static void DiscardFrame()
{
if (Model.Mark != 0) Model.DiscardFrame();
}
private static void RefreshSettings()
{
_settingsRead = true;
Model.Enabled = Plugins.EngineSettings.UiCostLog;
int ms = Plugins.EngineSettings.UiCostThresholdMs;
if (ms != Model.ThresholdMs) lock (Sync) Model.ThresholdMs = ms;
}
/// <summary>
/// The heartbeat's " uitop=a:avg/max,b:avg/max,c:avg/max" (the window's top 3 by average), only
/// while timing is on and <paramref name="uiP95Ms"/> is at or over the threshold; otherwise "".
/// Heartbeat thread.
/// </summary>
public static string HeartbeatField(float uiP95Ms)
{
if (!Model.Enabled || uiP95Ms < Model.ThresholdMs) return "";
lock (Sync) return Model.HeartbeatField(Stopwatch.GetTimestamp(), 3);
}
/// <summary>/rc uicost [on|off|&lt;ms&gt;|now|status]: the reply lines (every form answers).</summary>
public static List<string> HandleCommand(string args)
{
string a = (args ?? "").Trim().ToLowerInvariant();
var lines = new List<string>();
if (a is "on" or "off")
{
Plugins.EngineSettings.UiCostLog = a == "on";
RefreshSettings();
lines.Add(a == "on"
? $"UI cost timing on: a UI frame of {Model.ThresholdMs} ms or more writes one [UiCost] line to the log (at most every 5 s)."
: "UI cost timing off: nothing is timed or logged. /rc uicost on starts it again.");
return lines;
}
if (a.EndsWith("ms", StringComparison.Ordinal)) a = a.Substring(0, a.Length - 2).Trim();
if (int.TryParse(a, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int ms))
{
int v = UiCostModel.ClampThresholdMs(ms);
Plugins.EngineSettings.UiCostThresholdMs = v;
RefreshSettings();
string clamped = v != ms ? $" (kept to {UiCostModel.MinThresholdMs}-{UiCostModel.MaxThresholdMs})" : "";
lines.Add($"UI cost threshold {v} ms{clamped}; timing {(Model.Enabled ? "on" : "off - /rc uicost on to log")}.");
return lines;
}
if (a is "now" or "")
{
lock (Sync) lines.AddRange(Model.Describe(Stopwatch.GetTimestamp()));
if (!Model.Enabled) lines.Add("Timing is off, so this shows nothing new: /rc uicost on.");
return lines;
}
if (a == "status")
{
lines.Add($"UI cost timing {(Model.Enabled ? "on" : "off")}, threshold {Model.ThresholdMs} ms, {Model.SlotCount} parts named, " +
$"{Model.FramesSeen} frames timed, {Model.LinesWritten} slow-frame lines logged.");
return lines;
}
lines.Add(Usage);
return lines;
}
public const string Usage = Compatibility.ChatCommandReplies.UiCostUsage;
}

View file

@ -0,0 +1,649 @@
// ============================================================================
// RynthCore.Engine - ImGui/UiCostModel.cs
// The UI frame cost breakdown (ImGui/UiCost.cs): which part of the UI frame
// takes the time. Pure logic, no engine types (tools/UiCostTests compiles it).
//
// Each timed part of a frame is a slot (a docked panel by title, a plugin's
// render callback, the monster HUD, the ImGui submit, ...). Start/Stop add the
// ticks of one call to the slot for this frame; EndFrame folds the frame into
// a rolling window (Buckets x 1 s) and, when the frame's UI time is over the
// threshold and no line was written in the last LogIntervalSeconds, returns
// ONE line naming the frame's biggest parts. Nothing allocates per frame:
// the arrays are fixed, a slot's name is made once, and strings are built only
// for that line and for the summaries (/rc uicost now, the heartbeat field).
//
// "Outside" slots (the Nav3D markers and the world overlays' present at AC's
// 3D->UI pass) cost render time but are not part of the heartbeat's ui=; they
// are listed apart. Whatever the frame spent that no slot covers is "untimed"
// (Dear ImGui's own work between the timed calls, input, ini saves...).
//
// Threads: Register, Start, Stop and EndFrame on AC's render thread; the
// summaries from any thread, with the caller holding one lock around them and
// EndFrame (UiCost does).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Threading;
namespace RynthCore.Engine.ImGuiBackend;
internal sealed class UiCostModel
{
public const int DefaultThresholdMs = 50;
public const int MinThresholdMs = 5;
public const int MaxThresholdMs = 2000;
public const int MaxSlots = 160;
/// <summary>The rolling window: this many 1 s buckets (the summaries cover the last 4-5 s).</summary>
public const int Buckets = 5;
public const int LogIntervalSeconds = 5;
/// <summary>Parts named in a slow-frame line; the rest are summed as "+N more".</summary>
public const int LineTopItems = 8;
/// <summary>A threshold from a setting or a command, kept in range.</summary>
public static int ClampThresholdMs(int ms) => Math.Clamp(ms, MinThresholdMs, MaxThresholdMs);
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
private readonly long _freq;
private readonly long _bucketTicks;
private readonly long _logIntervalTicks;
// Slots.
private readonly string[] _names = new string[MaxSlots];
private readonly string?[] _units = new string?[MaxSlots];
private readonly bool[] _outside = new bool[MaxSlots];
private int _slotCount;
/// <summary>Slot 0: names past MaxSlots share it.</summary>
public const int OverflowSlot = 0;
// This frame.
private readonly long[] _fTicks = new long[MaxSlots];
private readonly int[] _fCount = new int[MaxSlots];
private readonly int[] _fCalls = new int[MaxSlots];
private readonly int[] _touched = new int[MaxSlots];
private int _touchedCount;
private long _fAll, _fOutside;
// This frame's ImGui submit counters (SubmitStats, end of this file) and texture uploads.
private SubmitStats _fSubmit;
private bool _fHasSubmit;
private int _fFontUploads, _fTexUploads;
// The window, one row per bucket.
private readonly long[] _bStart = new long[Buckets];
private readonly long[] _bFrames = new long[Buckets];
private readonly long[] _bUiSum = new long[Buckets];
private readonly long[] _bUiMax = new long[Buckets];
private readonly long[] _bSlow = new long[Buckets];
private readonly long[] _bUntimedSum = new long[Buckets];
private readonly long[] _bUntimedMax = new long[Buckets];
private readonly long[,] _bSum = new long[Buckets, MaxSlots];
private readonly long[,] _bMax = new long[Buckets, MaxSlots];
private readonly int[,] _bMaxCount = new int[Buckets, MaxSlots];
// The bucket's slowest frame, part by part.
private readonly long[,] _bWorst = new long[Buckets, MaxSlots];
private readonly int[,] _bWorstCount = new int[Buckets, MaxSlots];
private readonly long[] _bWorstUntimed = new long[Buckets];
// The bucket's submit counters (each one's largest frame) and uploads (summed).
private readonly SubmitStats[] _bSubmitMax = new SubmitStats[Buckets];
private readonly bool[] _bHasSubmit = new bool[Buckets];
private readonly long[] _bFontUploads = new long[Buckets];
private readonly long[] _bTexUploads = new long[Buckets];
private int _cur = -1;
private long _lastLogAt;
private bool _loggedOnce;
private int _thresholdMs = DefaultThresholdMs;
private long _thresholdTicks;
// Scratch for sorting (render thread for the frame line; under the caller's lock for summaries).
private readonly int[] _order = new int[MaxSlots + 1];
private readonly long[] _orderTicks = new long[MaxSlots + 1];
private readonly long[] _winSum = new long[MaxSlots];
private readonly long[] _winMax = new long[MaxSlots];
private readonly int[] _winMaxCount = new int[MaxSlots];
private SubmitStats _winSubmit;
private bool _winHasSubmit;
private long _winFontUploads, _winTexUploads;
/// <summary>Timing on: Start returns a timestamp; off: 0 and every Stop is a no-op.</summary>
public bool Enabled;
/// <summary>Frames folded into the window since the start (diagnostics, tests).</summary>
public long FramesSeen { get; private set; }
/// <summary>Slow-frame lines returned by EndFrame since the start.</summary>
public long LinesWritten { get; private set; }
public UiCostModel(long ticksPerSecond)
{
_freq = Math.Max(1, ticksPerSecond);
_bucketTicks = _freq;
_logIntervalTicks = _freq * LogIntervalSeconds;
ThresholdMs = DefaultThresholdMs;
Register("(more names)");
for (int i = 0; i < MaxSlots; i++) _fCount[i] = -1;
}
/// <summary>A frame at or over this many ms is slow (logged, counted).</summary>
public int ThresholdMs
{
get => _thresholdMs;
set
{
_thresholdMs = ClampThresholdMs(value);
_thresholdTicks = _thresholdMs * _freq / 1000;
}
}
public int SlotCount => Volatile.Read(ref _slotCount);
public string SlotName(int slot) => (uint)slot < (uint)SlotCount ? _names[slot] : "?";
/// <summary>
/// A new slot. <paramref name="unit"/> names the count passed to Stop ("plates", "vtx"), null for
/// none; <paramref name="outside"/>: not part of the frame's UI time (listed apart). Past
/// MaxSlots the overflow slot. Render thread (the summaries read only slots already published).
/// </summary>
public int Register(string name, string? unit = null, bool outside = false)
{
int n = _slotCount;
if (n >= MaxSlots) return OverflowSlot;
_names[n] = name;
_units[n] = unit;
_outside[n] = outside;
Volatile.Write(ref _slotCount, n + 1);
return n;
}
/// <summary>A timestamp to pass to Stop, or 0 while timing is off.</summary>
public long Start() => Enabled ? Stopwatch.GetTimestamp() : 0;
/// <summary>Adds the time since <paramref name="start"/> (from Start) to <paramref name="slot"/>; a no-op for 0.</summary>
public void Stop(int slot, long start, int count = -1)
{
if (start == 0) return;
Add(slot, Stopwatch.GetTimestamp() - start, count);
}
/// <summary>The ticks every slot got this frame so far: Mark before a part, StopExclusive after it.</summary>
public long Mark => _fAll;
/// <summary>
/// As Stop, less what the slots timed inside it got (since <paramref name="mark"/>): a part that
/// draws other timed parts (the panel host around its panels, a pop-out window around its panel)
/// keeps only its own time, so nothing is counted twice.
/// </summary>
public void StopExclusive(int slot, long start, long mark, int count = -1)
{
if (start == 0) return;
long ticks = Stopwatch.GetTimestamp() - start - (_fAll - mark);
Add(slot, ticks < 0 ? 0 : ticks, count);
}
/// <summary>Adds <paramref name="ticks"/> (and a count, when not negative) to a slot for this frame.</summary>
public void Add(int slot, long ticks, int count = -1)
{
if ((uint)slot >= (uint)_slotCount) return;
if (_fCalls[slot]++ == 0) _touched[_touchedCount++] = slot;
_fTicks[slot] += ticks;
if (count >= 0) _fCount[slot] = (_fCount[slot] < 0 ? 0 : _fCount[slot]) + count;
_fAll += ticks;
if (_outside[slot]) _fOutside += ticks;
}
/// <summary>This frame's ImGui submit counters (the main submit; a second call this frame replaces them).</summary>
public void SetSubmit(in SubmitStats stats)
{
_fSubmit = stats;
_fHasSubmit = true;
}
/// <summary>Textures made or re-uploaded this frame: the font atlas, and any other (icons, map tiles, pictures).</summary>
public void AddUploads(int font, int tex)
{
if (font > 0) _fFontUploads += font;
if (tex > 0) _fTexUploads += tex;
}
/// <summary>
/// Ends the frame: <paramref name="uiTicks"/> is its UI time (what the heartbeat's ui= records).
/// Folds it into the window and returns the slow-frame line when one is due (over the threshold,
/// none in the last LogIntervalSeconds, logging on), else null.
/// </summary>
public string? EndFrame(long uiTicks, long now, bool logSlow)
{
Rotate(now);
int b = _cur;
long inside = _fAll - _fOutside;
long untimed = uiTicks - inside;
if (untimed < 0) untimed = 0;
FramesSeen++;
_bFrames[b]++;
_bUiSum[b] += uiTicks;
bool worst = uiTicks > _bUiMax[b] || _bFrames[b] == 1;
if (uiTicks > _bUiMax[b]) _bUiMax[b] = uiTicks;
bool slow = uiTicks >= _thresholdTicks;
if (slow) _bSlow[b]++;
_bUntimedSum[b] += untimed;
if (untimed > _bUntimedMax[b]) _bUntimedMax[b] = untimed;
if (worst)
{
for (int s = 0; s < MaxSlots; s++) { _bWorst[b, s] = 0; _bWorstCount[b, s] = -1; }
_bWorstUntimed[b] = untimed;
}
for (int i = 0; i < _touchedCount; i++)
{
int s = _touched[i];
long t = _fTicks[s];
_bSum[b, s] += t;
if (t > _bMax[b, s]) _bMax[b, s] = t;
if (_fCount[s] > _bMaxCount[b, s]) _bMaxCount[b, s] = _fCount[s];
if (worst) { _bWorst[b, s] = t; _bWorstCount[b, s] = _fCount[s]; }
}
if (_fHasSubmit) { _bSubmitMax[b].MaxWith(_fSubmit); _bHasSubmit[b] = true; }
_bFontUploads[b] += _fFontUploads;
_bTexUploads[b] += _fTexUploads;
string? line = null;
if (logSlow && slow && (!_loggedOnce || now - _lastLogAt >= _logIntervalTicks))
{
_loggedOnce = true;
_lastLogAt = now;
LinesWritten++;
line = FormatFrameLine(uiTicks, untimed);
}
DiscardFrame(); // clears only what this frame touched
return line;
}
/// <summary>Drops what this frame timed without folding it in (no UI frame this EndScene).</summary>
public void DiscardFrame()
{
for (int i = 0; i < _touchedCount; i++)
{
int s = _touched[i];
_fTicks[s] = 0;
_fCalls[s] = 0;
_fCount[s] = -1;
}
_touchedCount = 0;
_fAll = 0;
_fOutside = 0;
_fSubmit = default;
_fHasSubmit = false;
_fFontUploads = _fTexUploads = 0;
}
private void Rotate(long now)
{
if (_cur < 0)
{
_cur = 0;
ClearBucket(0, now);
return;
}
long age = now - _bStart[_cur];
if (age < _bucketTicks) return;
long steps = age / _bucketTicks;
if (steps >= Buckets)
{
for (int i = 0; i < Buckets; i++) ClearBucket(i, 0);
_cur = 0;
_bStart[0] = now;
return;
}
long start = _bStart[_cur];
for (long i = 0; i < steps; i++)
{
start += _bucketTicks;
_cur = (_cur + 1) % Buckets;
ClearBucket(_cur, start);
}
}
private void ClearBucket(int b, long start)
{
_bStart[b] = start;
_bFrames[b] = _bUiSum[b] = _bUiMax[b] = _bSlow[b] = _bUntimedSum[b] = _bUntimedMax[b] = _bWorstUntimed[b] = 0;
_bSubmitMax[b] = default;
_bHasSubmit[b] = false;
_bFontUploads[b] = _bTexUploads[b] = 0;
for (int s = 0; s < MaxSlots; s++)
{
_bSum[b, s] = 0; _bMax[b, s] = 0; _bMaxCount[b, s] = -1;
_bWorst[b, s] = 0; _bWorstCount[b, s] = -1;
}
}
// ── Text ───────────────────────────────────────────────────────────────
private string Ms(long ticks) => (ticks * 1000.0 / _freq).ToString("0.0", Inv);
private string WithCount(int slot, int count) =>
count >= 0 && _units[slot] is { } unit ? $" ({count.ToString(Inv)} {unit})" : "";
/// <summary>
/// "[UiCost] frame 187.0 ms (over 50): Radar 120.3, Monster HUD 41.0 (38 plates), ..., untimed 3.2,
/// +4 more 0.9 | 3D pass, not in ui=: Nav3D markers 1.2". Parts under 0.05 ms are left out.
/// </summary>
private string FormatFrameLine(long uiTicks, long untimed)
{
var sb = new StringBuilder(256);
sb.Append("[UiCost] frame ").Append(Ms(uiTicks)).Append(" ms (over ").Append(_thresholdMs.ToString(Inv)).Append("): ");
int n = 0;
for (int i = 0; i < _touchedCount; i++)
{
int s = _touched[i];
if (_outside[s]) continue;
_order[n] = s; _orderTicks[n] = _fTicks[s]; n++;
}
_order[n] = -1; _orderTicks[n] = untimed; n++;
SortDesc(n);
AppendTop(sb, n, LineTopItems, s => _fCount[s]);
AppendSubmit(sb, _fHasSubmit, _fSubmit, _fFontUploads, _fTexUploads);
int o = 0;
for (int i = 0; i < _touchedCount; i++)
{
int s = _touched[i];
if (!_outside[s]) continue;
_order[o] = s; _orderTicks[o] = _fTicks[s]; o++;
}
if (o > 0)
{
SortDesc(o);
sb.Append(" | 3D pass, not in ui=: ");
AppendTop(sb, o, LineTopItems, s => _fCount[s]);
}
return sb.ToString();
}
/// <summary>
/// " | submit: 21 lists, 412 draws, 3 tex switches, 31k vtx copied (whole-list 4.2M); uploads: 1 font, 0 tex".
/// The submit part only when one was recorded, the uploads only when there were any.
/// </summary>
private static void AppendSubmit(StringBuilder sb, bool has, in SubmitStats s, long font, long tex)
{
if (has)
{
sb.Append(" | submit: ").Append(s.Lists.ToString(Inv)).Append(" lists, ")
.Append(s.Draws.ToString(Inv)).Append(" draws, ")
.Append(s.TexSwitches.ToString(Inv)).Append(" tex switches, ")
.Append(Compact(s.VtxCopied)).Append(" vtx copied (whole-list ").Append(Compact(s.VtxWholeList)).Append(')');
if (s.Skipped > 0) sb.Append(", ").Append(s.Skipped.ToString(Inv)).Append(" skipped");
}
if (font > 0 || tex > 0)
sb.Append(has ? "; uploads: " : " | uploads: ").Append(font.ToString(Inv)).Append(" font, ").Append(tex.ToString(Inv)).Append(" tex");
}
/// <summary>950, 31.2k, 4.2M.</summary>
public static string Compact(long n)
{
if (n < 1000) return n.ToString(Inv);
if (n < 1_000_000) return (n / 1000.0).ToString("0.#", Inv) + "k";
return (n / 1_000_000.0).ToString("0.#", Inv) + "M";
}
private void AppendTop(StringBuilder sb, int n, int top, Func<int, int> count)
{
long minTicks = _freq / 20000; // 0.05 ms
int shown = 0, more = 0;
long moreTicks = 0;
for (int i = 0; i < n; i++)
{
int s = _order[i];
long t = _orderTicks[i];
if (shown >= top || t < minTicks || t <= 0)
{
if (t > 0) { more++; moreTicks += t; }
continue;
}
if (shown > 0) sb.Append(", ");
if (s < 0) sb.Append("untimed ").Append(Ms(t));
else sb.Append(_names[s]).Append(' ').Append(Ms(t)).Append(WithCount(s, count(s)));
shown++;
}
if (shown == 0) sb.Append("nothing timed");
if (more > 0) sb.Append(", +").Append(more.ToString(Inv)).Append(" more ").Append(Ms(moreTicks));
}
// Insertion sort of _order/_orderTicks [0, n) by ticks, largest first (n is small).
private void SortDesc(int n)
{
for (int i = 1; i < n; i++)
{
int s = _order[i];
long t = _orderTicks[i];
int j = i - 1;
while (j >= 0 && _orderTicks[j] < t)
{
_order[j + 1] = _order[j];
_orderTicks[j + 1] = _orderTicks[j];
j--;
}
_order[j + 1] = s;
_orderTicks[j + 1] = t;
}
}
/// <summary>The live buckets at <paramref name="now"/> (the window), folded into the _win arrays.</summary>
private (long frames, long uiSum, long uiMax, long slow, long untimedSum, long untimedMax, long spanTicks, int worstBucket) FoldWindow(long now)
{
Array.Clear(_winSum);
Array.Clear(_winMax);
for (int s = 0; s < MaxSlots; s++) _winMaxCount[s] = -1;
_winSubmit = default;
_winHasSubmit = false;
_winFontUploads = _winTexUploads = 0;
long frames = 0, uiSum = 0, uiMax = 0, slow = 0, untimedSum = 0, untimedMax = 0, oldest = now;
int worstBucket = -1;
if (_cur < 0) return (0, 0, 0, 0, 0, 0, 0, -1);
long horizon = now - _bucketTicks * Buckets;
int slots = SlotCount;
for (int b = 0; b < Buckets; b++)
{
if (_bFrames[b] == 0 || _bStart[b] < horizon) continue;
if (_bStart[b] < oldest) oldest = _bStart[b];
frames += _bFrames[b];
uiSum += _bUiSum[b];
if (worstBucket < 0 || _bUiMax[b] > uiMax) { uiMax = _bUiMax[b]; worstBucket = b; }
slow += _bSlow[b];
untimedSum += _bUntimedSum[b];
if (_bUntimedMax[b] > untimedMax) untimedMax = _bUntimedMax[b];
if (_bHasSubmit[b]) { _winSubmit.MaxWith(_bSubmitMax[b]); _winHasSubmit = true; }
_winFontUploads += _bFontUploads[b];
_winTexUploads += _bTexUploads[b];
for (int s = 0; s < slots; s++)
{
_winSum[s] += _bSum[b, s];
if (_bMax[b, s] > _winMax[s]) _winMax[s] = _bMax[b, s];
if (_bMaxCount[b, s] > _winMaxCount[s]) _winMaxCount[s] = _bMaxCount[b, s];
}
}
return (frames, uiSum, uiMax, slow, untimedSum, untimedMax, now - oldest, worstBucket);
}
/// <summary>
/// The window's biggest parts by average per frame, for the heartbeat: " uitop=Radar:2.1/120.3,..."
/// (avg/max ms, spaces in names as '_'). Empty when the window has no frames.
/// </summary>
public string HeartbeatField(long now, int top = 3)
{
var w = FoldWindow(now);
if (w.frames == 0) return "";
int n = FillWindowOrder(w.untimedSum, includeOutside: false);
var sb = new StringBuilder(" uitop=");
int shown = 0;
for (int i = 0; i < n && shown < top; i++)
{
if (_orderTicks[i] <= 0) break;
int s = _order[i];
if (shown > 0) sb.Append(',');
string name = s < 0 ? "untimed" : _names[s];
sb.Append(name.Replace(' ', '_').Replace(',', ';').Replace('=', '-'));
sb.Append(':').Append(Ms(_orderTicks[i] / w.frames)).Append('/').Append(Ms(s < 0 ? w.untimedMax : _winMax[s]));
shown++;
}
if (shown == 0) return "";
// The window's largest submit: " uisub=draws:412,texsw:3,vtx:31k/4.2M,up:0/0"
// (vtx copied / what whole-list copies would have been; uploads font/other, summed).
if (_winHasSubmit || _winFontUploads > 0 || _winTexUploads > 0)
{
sb.Append(" uisub=draws:").Append(_winSubmit.Draws.ToString(Inv))
.Append(",texsw:").Append(_winSubmit.TexSwitches.ToString(Inv))
.Append(",vtx:").Append(Compact(_winSubmit.VtxCopied)).Append('/').Append(Compact(_winSubmit.VtxWholeList))
.Append(",up:").Append(_winFontUploads.ToString(Inv)).Append('/').Append(_winTexUploads.ToString(Inv));
}
return sb.ToString();
}
private int FillWindowOrder(long untimedSum, bool includeOutside)
{
int n = 0;
int slots = SlotCount;
for (int s = 0; s < slots; s++)
{
if (_winSum[s] <= 0 || _outside[s] != includeOutside) continue;
_order[n] = s; _orderTicks[n] = _winSum[s]; n++;
}
if (!includeOutside && untimedSum > 0) { _order[n] = -1; _orderTicks[n] = untimedSum; n++; }
SortDesc(n);
return n;
}
/// <summary>
/// The breakdown for /rc uicost now: the window's frames, the parts by average per frame (with
/// their worst), the slowest frame part by part, and the 3D pass parts.
/// </summary>
public List<string> Describe(long now, int top = 8)
{
var lines = new List<string>();
var w = FoldWindow(now);
string state = Enabled ? $"timing on, slow frames logged at {_thresholdMs.ToString(Inv)} ms+" : "timing off";
if (w.frames == 0)
{
lines.Add($"UI cost: no UI frames in the last {Buckets.ToString(Inv)} s ({state}).");
return lines;
}
double span = w.spanTicks / (double)_freq;
lines.Add($"UI cost, last {span.ToString("0.0", Inv)} s: {w.frames.ToString(Inv)} frames, avg {Ms(w.uiSum / w.frames)} ms, " +
$"max {Ms(w.uiMax)} ms, {w.slow.ToString(Inv)} at {_thresholdMs.ToString(Inv)} ms+ ({state}).");
int n = FillWindowOrder(w.untimedSum, includeOutside: false);
var sb = new StringBuilder("Per frame, avg (max): ");
AppendWindowItems(sb, n, top, w.frames, w.untimedMax);
lines.Add(sb.ToString());
if (w.worstBucket >= 0)
{
int b = w.worstBucket;
int m = 0;
int slots = SlotCount;
for (int s = 0; s < slots; s++)
{
if (_outside[s] || _bWorst[b, s] <= 0) continue;
_order[m] = s; _orderTicks[m] = _bWorst[b, s]; m++;
}
_order[m] = -1; _orderTicks[m] = _bWorstUntimed[b]; m++;
SortDesc(m);
var wsb = new StringBuilder("Slowest frame ").Append(Ms(w.uiMax)).Append(" ms: ");
AppendTop(wsb, m, top, s => _bWorstCount[b, s]);
lines.Add(wsb.ToString());
}
if (_winHasSubmit || _winFontUploads > 0 || _winTexUploads > 0)
{
var ssb = new StringBuilder("ImGui submit, largest per frame");
AppendSubmit(ssb, _winHasSubmit, _winSubmit, _winFontUploads, _winTexUploads);
// "... | submit: ..." reads as "ImGui submit, largest per frame: ..." here; uploads are the window's sum.
ssb.Replace(" | submit:", ":").Replace(" | uploads:", ": uploads (window total):").Replace("; uploads:", "; uploads (window total):");
lines.Add(ssb.ToString());
}
int o = FillWindowOrder(0, includeOutside: true);
if (o > 0)
{
var osb = new StringBuilder("3D pass, not in ui=, avg (max): ");
AppendWindowItems(osb, o, top, w.frames, 0);
lines.Add(osb.ToString());
}
return lines;
}
private void AppendWindowItems(StringBuilder sb, int n, int top, long frames, long untimedMax)
{
int shown = 0;
for (int i = 0; i < n && shown < top; i++)
{
int s = _order[i];
long avg = _orderTicks[i] / frames;
if (shown > 0) sb.Append(", ");
if (s < 0) sb.Append("untimed ").Append(Ms(avg)).Append(" (").Append(Ms(untimedMax)).Append(')');
else
{
sb.Append(_names[s]).Append(' ').Append(Ms(avg)).Append(" (").Append(Ms(_winMax[s]));
if (_winMaxCount[s] >= 0 && _units[s] is { } unit) sb.Append(", ").Append(_winMaxCount[s].ToString(Inv)).Append(' ').Append(unit);
sb.Append(')');
}
shown++;
}
if (shown == 0) sb.Append("nothing timed");
else if (n > shown) sb.Append(", +").Append((n - shown).ToString(Inv)).Append(" more");
}
/// <summary>The window's totals (tests): frames, average and max UI ms, slow frames.</summary>
public (long Frames, double AvgMs, double MaxMs, long Slow) WindowTotals(long now)
{
var w = FoldWindow(now);
if (w.frames == 0) return (0, 0, 0, 0);
return (w.frames, w.uiSum * 1000.0 / _freq / w.frames, w.uiMax * 1000.0 / _freq, w.slow);
}
/// <summary>One slot's window total, average per frame and max, in ms (tests).</summary>
public (double AvgMs, double MaxMs) SlotWindow(long now, int slot)
{
var w = FoldWindow(now);
if (w.frames == 0 || (uint)slot >= (uint)SlotCount) return (0, 0);
return (_winSum[slot] * 1000.0 / _freq / w.frames, _winMax[slot] * 1000.0 / _freq);
}
}
/// <summary>
/// One ImGui submit's counters (DX9Backend.RenderLists): what the [UiCost] line and the
/// heartbeat print about the submit, so a slow one names its shape.
/// </summary>
internal struct SubmitStats
{
/// <summary>Draw lists drawn.</summary>
public int Lists;
/// <summary>Draw calls made (commands with geometry, not clipped away).</summary>
public int Draws;
/// <summary>Commands skipped: clipped away or broken.</summary>
public int Skipped;
/// <summary>SetTexture calls that changed the texture.</summary>
public int TexSwitches;
/// <summary>Vertices handed to the draw calls (what the runtime copies).</summary>
public long VtxCopied;
/// <summary>What the same submit would have copied handing each command its whole list (the old renderer).</summary>
public long VtxWholeList;
public void Clear() => this = default;
/// <summary>Folds another submit in (the window keeps each counter's largest).</summary>
public void MaxWith(in SubmitStats o)
{
if (o.Lists > Lists) Lists = o.Lists;
if (o.Draws > Draws) Draws = o.Draws;
if (o.Skipped > Skipped) Skipped = o.Skipped;
if (o.TexSwitches > TexSwitches) TexSwitches = o.TexSwitches;
if (o.VtxCopied > VtxCopied) VtxCopied = o.VtxCopied;
if (o.VtxWholeList > VtxWholeList) VtxWholeList = o.VtxWholeList;
}
}

View file

@ -19,6 +19,20 @@
//
// This captures the exact wedge location for every client, on every freeze,
// with no external debugger and no per-PID coordination.
//
// 2026-11-01 (a client hung for good on a hot reload, 10-31 21:17):
// * The hang dump (after six samples, as before) is written out of process: rundll32
// runs RynthCore.SehTrampoline.dll's RC_DumpProcess (CrashDump.WriteHangDumpOutOfProcess). It was
// MiniDumpWriteDump on this process: dbghelp suspends every other thread and then
// allocates from the process heap, so a main thread suspended inside RtlAllocateHeap
// (the font atlas build) deadlocked the whole process; on the clients that
// recovered it froze every thread for 8-10 s on top of the reload stall.
// * SuspendThread / GetThreadContext / ResumeThread skip the GC transition: a GC
// starting while this thread held the main thread suspended would otherwise stop
// this thread at the P/Invoke return, and the GC would wait for ever for the main
// thread it can't run.
// * Step: what the engine is doing on AC's main thread (EndScene, ImGui init's
// parts), logged with the hang, so a stall inside the engine names its step.
// ============================================================================
using System;
@ -35,14 +49,16 @@ internal static class MainThreadHangWatchdog
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
// No GC transition between suspending the main thread and resuming it (see the header):
// these three are short kernel calls that never call back into managed code.
[DllImport("kernel32.dll"), SuppressGCTransition]
private static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
[DllImport("kernel32.dll"), SuppressGCTransition]
private static extern uint ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext);
[DllImport("kernel32.dll"), SuppressGCTransition]
private static extern int GetThreadContext(IntPtr hThread, IntPtr lpContext);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
@ -59,6 +75,13 @@ internal static class MainThreadHangWatchdog
// While a wedge lasts, the "still hung" line is repeated this often.
private const long StillHungRepeatMs = 20_000;
/// <summary>
/// What the engine is doing on AC's main thread, set at a few steps of the EndScene
/// detour and of ImGui init; null = outside the engine (AC's own code). Logged with a
/// hang. A constant string per step (no allocation on AC's thread).
/// </summary>
internal static volatile string? Step;
/// <summary>"unhandled ACCESS_VIOLATION at acclient.exe+0x18712F" when the current hang is a crash dialog.</summary>
internal static volatile string? CrashCause;
@ -181,6 +204,7 @@ internal static class MainThreadHangWatchdog
hangStartBeat = lastBeat;
RynthLog.Info("================================================================");
RynthLog.Error($"==== MAIN THREAD HANG DETECTED tid={tid} build={EntryPoint.BuildStamp} initCount={EntryPoint.InitCount} (stalled {stale}ms) ====");
RynthLog.Error($" main thread step: {Step ?? "outside the engine (AC's own code)"}");
// A modal dialog (AC's error MessageBox) holds the main thread: say which.
string? box = Compatibility.MessageBoxHooks.Describe();
if (box != null) RynthLog.Error($" hang cause: {box}");
@ -204,9 +228,8 @@ internal static class MainThreadHangWatchdog
sample++;
RynthLog.Info($" (still hung after {MaxSamplesPerHang} samples — suppressing further samples until recovery)");
lastStillHungLog = Environment.TickCount64;
// Confirmed permanent wedge (~10s+): write one targeted
// minidump for WinDbg post-mortem if the log stack walk
// isn't enough. Once per session.
// Confirmed long wedge (~10s+): one minidump for a post-mortem when
// the log stack walk isn't enough, written out of process. Once per session.
TryWriteHangDump(tid, stale);
}
else if (Environment.TickCount64 - lastStillHungLog >= StillHungRepeatMs)
@ -255,8 +278,9 @@ internal static class MainThreadHangWatchdog
RynthLog.Info($" (hang minidump skipped: the full-memory dump {full} already covers this hang)");
return;
}
CrashDump.WriteSelfDump(
$"main-thread hang tid={tid} stale={staleMs}ms build={EntryPoint.BuildStamp}", out _);
// Out of process (rundll32 + SehTrampoline), never MiniDumpWriteDump on this process: see the header.
CrashDump.WriteHangDumpOutOfProcess(
$"main-thread hang tid={tid} stale={staleMs}ms step={Step ?? "outside the engine"} build={EntryPoint.BuildStamp}", out _);
}
catch { /* a diagnostic must never destabilize the host */ }
}
@ -384,7 +408,7 @@ internal static class MainThreadHangWatchdog
suspendCount = SuspendThread(h);
if (suspendCount != 0xFFFFFFFF)
{
ctxOk = GetThreadContext(h, ctx);
ctxOk = GetThreadContext(h, ctx) != 0;
ResumeThread(h);
}
@ -395,7 +419,7 @@ internal static class MainThreadHangWatchdog
}
uint eip = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EIP);
RynthLog.Info($" sample#{sampleNum} (stale {staleMs}ms) eip=0x{eip:X8} {CrashLogger.ResolveCodeAddr((IntPtr)eip)}");
RynthLog.Info($" sample#{sampleNum} (stale {staleMs}ms) eip=0x{eip:X8} {CrashLogger.ResolveCodeAddr((IntPtr)eip)} step={Step ?? "outside the engine"}");
if (fullStack)
{

View file

@ -45,6 +45,8 @@ internal static class EngineSettings
private static bool _borderlessWindowed;
// Settings > Display: reopen Rynth panels where they were (default on: panels have always been remembered).
private static bool _rememberWindowLayout = true;
// Settings > Display: each character keeps its own panel layout (default on; off = the one shared layout).
private static bool _panelLayoutPerCharacter = true;
// Settings > Display: save and restore the AC window's own position and size (default off, opt-in).
private static bool _rememberAcWindowPosition;
// "LoadAllServerPlugins": hand-set only, written back only when true (PluginManifestGate).
@ -55,6 +57,9 @@ internal static class EngineSettings
// leaves the world, for at most _holdReloadInWorldMaxMinutes (ReloadInWorldGate).
private static bool _holdReloadInWorld;
private static int _holdReloadInWorldMaxMinutes = ReloadInWorldGate.DefaultMaxMinutes;
// Settings > Diagnostics: the UI frame cost breakdown (ImGui/UiCost.cs; default on, 50 ms).
private static bool _uiCostLog = true;
private static int _uiCostThresholdMs = ImGuiBackend.UiCostModel.DefaultThresholdMs;
// "IltServerNames" / "IltHosts": what counts as Infinite Leaftide (Compatibility/IltInfo.cs).
// null = not in the file: IltDetect's defaults.
private static List<string>? _iltServerNames;
@ -468,6 +473,27 @@ internal static class EngineSettings
}
}
/// <summary>"PanelLayoutPerCharacter" in engine.json (default true): in the world each character
/// uses its own panel layout (%LOCALAPPDATA%\RynthCore\layouts\&lt;server&gt;\&lt;character&gt;\
/// panel_state.txt and imgui.ini, UI/PanelLayout), so clients on one PC don't move each other's
/// panels. Off: every client uses the one PC-wide layout, as before. Set in game in Settings >
/// Display: the client it is set in switches at once, the others as they start.</summary>
public static bool PanelLayoutPerCharacter
{
get
{
EnsureLoaded();
return _panelLayoutPerCharacter;
}
set
{
EnsureLoaded();
if (_panelLayoutPerCharacter == value) return;
_panelLayoutPerCharacter = value;
Save("PanelLayoutPerCharacter");
}
}
/// <summary>"RememberAcWindowPosition" in engine.json (default false, opt-in): save the Asheron's
/// Call window's position and size per character and put it back at the next login.
/// Set in game in Settings > Display.</summary>
@ -545,6 +571,47 @@ internal static class EngineSettings
}
}
/// <summary>"UiCostLog" in engine.json (default true): time the parts of each UI frame (panels by
/// title, plugin callbacks, the monster HUD, pop-outs, the ImGui submit; ImGui/UiCost.cs) and log one
/// "[UiCost]" line for a frame at or over <see cref="UiCostThresholdMs"/>, at most every 5 s. Off: no
/// timing at all. Only a false is written to the file. Settings > Diagnostics, /rc uicost on|off.</summary>
public static bool UiCostLog
{
get
{
EnsureLoaded();
return _uiCostLog;
}
set
{
EnsureLoaded();
if (_uiCostLog == value) return;
_uiCostLog = value;
Save("UiCostLog");
}
}
/// <summary>"UiCostThresholdMs" in engine.json (default 50, valid 5-2000): a UI frame this slow is
/// logged with its breakdown (<see cref="UiCostLog"/>), and the heartbeat names the top parts while
/// its ui p95 is over it. Clamped; only a non-default value is written. Settings > Diagnostics,
/// /rc uicost &lt;ms&gt;.</summary>
public static int UiCostThresholdMs
{
get
{
EnsureLoaded();
return _uiCostThresholdMs;
}
set
{
EnsureLoaded();
int v = ImGuiBackend.UiCostModel.ClampThresholdMs(value);
if (_uiCostThresholdMs == v) return;
_uiCostThresholdMs = v;
Save("UiCostThresholdMs");
}
}
/// <summary>"ReportEndpoint" in engine.json: a test URL for "Report a problem" instead of the
/// built-in https://aelrynth.com/rynth/report (ProblemReportCore.ResolveEndpoint accepts https,
/// or http to this PC; anything else is ignored). Null when the file has none. Edited in the file.</summary>
@ -807,6 +874,10 @@ internal static class EngineSettings
(rwlEl.ValueKind == JsonValueKind.True || rwlEl.ValueKind == JsonValueKind.False))
_rememberWindowLayout = rwlEl.GetBoolean();
if (doc.RootElement.TryGetProperty("PanelLayoutPerCharacter", out var plpcEl) &&
(plpcEl.ValueKind == JsonValueKind.True || plpcEl.ValueKind == JsonValueKind.False))
_panelLayoutPerCharacter = plpcEl.GetBoolean();
if (doc.RootElement.TryGetProperty("RememberAcWindowPosition", out var rapEl) &&
(rapEl.ValueKind == JsonValueKind.True || rapEl.ValueKind == JsonValueKind.False))
_rememberAcWindowPosition = rapEl.GetBoolean();
@ -825,6 +896,15 @@ internal static class EngineSettings
hrimEl.TryGetInt32(out int hrim))
_holdReloadInWorldMaxMinutes = ReloadInWorldGate.ClampMaxMinutes(hrim);
if (doc.RootElement.TryGetProperty("UiCostLog", out var uclEl) &&
(uclEl.ValueKind == JsonValueKind.True || uclEl.ValueKind == JsonValueKind.False))
_uiCostLog = uclEl.GetBoolean();
if (doc.RootElement.TryGetProperty("UiCostThresholdMs", out var uctEl) &&
uctEl.ValueKind == JsonValueKind.Number &&
uctEl.TryGetInt32(out int uct))
_uiCostThresholdMs = ImGuiBackend.UiCostModel.ClampThresholdMs(uct);
if (doc.RootElement.TryGetProperty("ReportEndpoint", out var repEl) &&
repEl.ValueKind == JsonValueKind.String &&
repEl.GetString() is { Length: > 0 } rep)
@ -911,6 +991,8 @@ internal static class EngineSettings
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel",
"LoadAllServerPlugins", "TransitionGate",
"HoldReloadInWorld", "HoldReloadInWorldMaxMinutes",
"PanelLayoutPerCharacter",
"UiCostLog", "UiCostThresholdMs",
};
// The engine.json keys this client changed this session. Every client keeps the whole settings
@ -980,6 +1062,8 @@ internal static class EngineSettings
w.WriteBoolean("BorderlessWindowed", true);
if (!_rememberWindowLayout) // default true: leave the file as it was
w.WriteBoolean("RememberWindowLayout", false);
if (!_panelLayoutPerCharacter) // default true: leave the file as it was
w.WriteBoolean("PanelLayoutPerCharacter", false);
if (_rememberAcWindowPosition) // default false: leave the file as it was
w.WriteBoolean("RememberAcWindowPosition", true);
if (!_closeOnServerDisconnect) // default true: leave the file as it was
@ -994,6 +1078,10 @@ internal static class EngineSettings
w.WriteBoolean("HoldReloadInWorld", true);
if (_holdReloadInWorldMaxMinutes != ReloadInWorldGate.DefaultMaxMinutes) // only a non-default value is written
w.WriteNumber("HoldReloadInWorldMaxMinutes", _holdReloadInWorldMaxMinutes);
if (!_uiCostLog) // default true: only a false is written
w.WriteBoolean("UiCostLog", false);
if (_uiCostThresholdMs != ImGuiBackend.UiCostModel.DefaultThresholdMs) // only a non-default value is written
w.WriteNumber("UiCostThresholdMs", _uiCostThresholdMs);
if (_reportEndpoint != null) // only a hand-set value is written
w.WriteString("ReportEndpoint", _reportEndpoint);
WriteStringList(w, "IltServerNames", _iltServerNames); // null (not in the file): left out

View file

@ -811,7 +811,8 @@ internal struct RynthCoreAPI
/// which v77 callbacks can arrive. bit0 RynthPluginOnScreenChanged from the UseNewMode hook,
/// bit1 ... from the +0x8C mode poll instead (one tick late), bit2 RynthPluginOnClientCleanup,
/// bit3 RynthPluginOnTooltipShow, bit4 RynthPluginOnTooltipHide, bit5 RynthPluginOnDragStart,
/// bit6 RynthPluginOnItemDropped, bit7 Client::Cleanup has started. Any thread.
/// bit6 RynthPluginOnItemDropped, bit7 Client::Cleanup has started, bit8 (2026-10-30, not a hook)
/// the Damage panel draws a RynthPluginGetMonsterDamageJson row's "mstats". Any thread.
/// Requires API v77+.</summary>
public IntPtr GetUiHookFlagsFn;

View file

@ -277,6 +277,9 @@ internal static partial class PluginManager
if (UiElementHooks.DragStartLive) flags |= 1u << 5;
if (UiElementHooks.DropLive) flags |= 1u << 6;
if (UiFlowHooks.ClientCleanupStarted) flags |= 1u << 7;
// Not a hook: the Damage panel draws a row's "mstats" (UI/Data/DamageRowStats.cs, 2026-10-30), so
// RynthAi shows its monster stats there instead of its own window. No API version change.
flags |= 1u << 8;
return flags;
}
}

View file

@ -745,6 +745,8 @@ internal static partial class PluginManager
public static void QueueSelectedTargetChange(uint currentTargetId, uint previousTargetId)
{
ImGuiBackend.Hud.HudFeed.OnSelection(currentTargetId); // debuff target matching
// A selection makes the client query its health: the server's health stream follows it (HealthProbe).
ImGuiBackend.Hud.HealthProbe.NoteQuery(currentTargetId);
if (!_initialized || _plugins.Count == 0)
return;
@ -924,13 +926,21 @@ internal static partial class PluginManager
}
}
public static void QueueUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
/// <summary>
/// One health observation. <paramref name="healthReply"/>: it is a 0x01C0 UpdateHealth (a QueryHealth
/// reply or the server's stream); one that answers the nameplates' own probe (HealthProbe) is the
/// HUD's alone - plugins never asked for it, and a bot must not read someone else's hit on a monster
/// it isn't fighting as its own.
/// </summary>
public static void QueueUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth, bool healthReply = false)
{
// Monster nameplates keep the last ratio per object (engine-side, plugins or not).
ImGuiBackend.Hud.MonsterHudData.RecordHealth(targetId, healthRatio, currentHealth, maxHealth);
if (_plugins.Count == 0)
return;
if (healthReply && ImGuiBackend.Hud.HealthProbe.IsProbeReply(targetId, Environment.TickCount64))
return;
lock (PendingUpdateHealthLock)
{
@ -1212,6 +1222,7 @@ internal static partial class PluginManager
if (!plugin.Initialized || plugin.Failed || plugin.Render == null)
continue;
long cost = ImGuiBackend.UiCost.Start(); // UiCost: each plugin's Render, by name
try
{
plugin.Render();
@ -1221,6 +1232,7 @@ internal static partial class PluginManager
plugin.Failed = true;
RynthLog.Error($"PluginManager: {plugin.DisplayName} Render threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled.");
}
ImGuiBackend.UiCost.StopPluginRender(plugin.DisplayName, cost);
}
}
@ -1286,6 +1298,7 @@ internal static partial class PluginManager
RynthLog.Plugin($"PluginManager: first RenderOverlay call for {plugin.DisplayName}.");
}
long cost = ImGuiBackend.UiCost.Start(); // UiCost: each plugin's RenderOverlay, by name
try
{
overlay();
@ -1295,6 +1308,7 @@ internal static partial class PluginManager
plugin.RenderOverlay = null;
RynthLog.Error($"PluginManager: {plugin.DisplayName} RenderOverlay threw {ex.GetType().Name}: {ex.Message} - overlay windows off for this session (plugin keeps running).");
}
ImGuiBackend.UiCost.StopPluginOverlay(plugin.DisplayName, cost);
}
}

View file

@ -275,23 +275,16 @@ internal static class AcWindowChrome
try
{
// To the imgui.ini of the panel layout in use (this character's, or the PC-wide default).
if (ImGuiNET.ImGui.GetCurrentContext() != IntPtr.Zero)
{
string ini = ImGuiNET.ImGui.SaveIniSettingsToMemory();
string iniPath = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini");
UiBackgroundWriter.Enqueue("imgui.ini", () =>
{
Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
File.WriteAllText(iniPath, ini);
});
}
PanelLayout.QueueIniSave(ImGuiNET.ImGui.SaveIniSettingsToMemory(), explicitSave: true);
}
catch (Exception ex)
{
try { RynthLog.UI($"AcWindowChrome: imgui.ini save failed - {ex.Message}"); } catch { }
}
// Rewrites panel_state.txt from the in-memory state (even with Remember Open Windows off).
// Rewrites the layout's panel_state.txt from the in-memory state (even with Remember Open Windows off).
UiBackgroundWriter.Enqueue("panel state (save now)", PanelStateStore.Flush);
try

View file

@ -20,10 +20,12 @@
// Copy it to a tab as well (it stays where it was),
// Hide it everywhere, or
// Colour it only,
// and it can colour the whole line or just the matched text. Order: top to
// bottom. Copy rules add up; the first matching Move or Hide decides and
// stops the routing. The first matching line colour wins; matched-text
// colours add up, a higher rule winning where two overlap.
// and it can colour the whole line, just the matched text, or (2026-11-01)
// highlight the line with a band behind it. Order: top to bottom. Copy rules
// add up; the first matching Move or Hide decides and stops the routing. The
// first matching line colour wins, and so does the first matching highlight
// (on its own: a line can have both); matched-text colours add up, a higher
// rule winning where two overlap.
//
// Threads: rules are evaluated ONLY on the pump (ChatSource) - each new line
// once, and every kept line again when the rules change (in 8 ms slices, newest
@ -866,7 +868,8 @@ internal static class ChatModel
_ => "move",
},
When = f.When.Length > 0 ? f.When : null,
ColorMode = f.ColorMode switch { ChatColorMode.Line => "line", ChatColorMode.Match => "match", _ => null },
// "highlight" since 2026-11-01; an older RynthCore reads it as no colour (ChatColorModes.Parse).
ColorMode = ChatColorModes.ToJson(f.ColorMode),
// Kept while the rule is set to "No colour" too, so switching colour back on
// after a relaunch finds the colour that was picked.
Color = f.ColorMode != ChatColorMode.None || f.ColorArgb != ChatFilterRule.DefaultColor ? FormatColor(f.ColorArgb) : null,
@ -897,12 +900,7 @@ internal static class ChatModel
_ => tab.Length == 0 ? ChatRuleAction.Hide : ChatRuleAction.Move,
},
When = f.When ?? "",
ColorMode = (f.ColorMode ?? "").ToLowerInvariant() switch
{
"line" => ChatColorMode.Line,
"match" or "text" => ChatColorMode.Match,
_ => ChatColorMode.None,
},
ColorMode = ChatColorModes.Parse(f.ColorMode),
ColorArgb = ParseColor(f.Color) ?? ChatFilterRule.DefaultColor,
// Absent (every file before 2026-10-05): Regex, as those rules always were.
Mode = ChatRuleMatching.Parse(f.Mode),
@ -1330,6 +1328,8 @@ internal static class ChatModel
// rynthchat_settings.v1.bak, and the next save writes version 2.
// "lineColors" (2026-10-08, ChatLineColors) is written only once a colour
// is set, so it needs no version bump: a file without it loads as before.
// "colorMode": "highlight" (2026-11-01) needs none either: "colorMode" is a
// string, and a RynthCore without it reads an unknown value as no colour.
public const int SettingsVersion = 2;
private static readonly object SaveLock = new();

View file

@ -75,7 +75,7 @@ internal sealed class ChatRoute
{
public static readonly ChatRoute Default = new(false, true, null, null, null, false);
public ChatRoute(bool hidden, bool inHome, string[]? tabs, uint? lineArgb, ChatSpan[]? spans, bool mention)
public ChatRoute(bool hidden, bool inHome, string[]? tabs, uint? lineArgb, ChatSpan[]? spans, bool mention, uint? highlightArgb = null)
{
Hidden = hidden;
InHome = inHome;
@ -83,6 +83,7 @@ internal sealed class ChatRoute
LineArgb = lineArgb;
Spans = spans;
Mention = mention;
HighlightArgb = highlightArgb;
}
/// <summary>A Hide rule matched: shown nowhere.</summary>
@ -97,6 +98,10 @@ internal sealed class ChatRoute
public ChatSpan[]? Spans { get; }
/// <summary>Someone said your name (or a mention word).</summary>
public bool Mention { get; }
/// <summary>A "Highlight line" rule's colour (its swatch, 0xAARRGGBB): a band behind the
/// whole line, drawn at <see cref="ChatColorModes.BandArgb"/>; null = no band. The text
/// keeps its own colour (LineArgb or the channel's).</summary>
public uint? HighlightArgb { get; }
public bool ShowsIn(string tab, string channel)
{
@ -121,7 +126,52 @@ internal enum ChatRuleAction
Color,
}
internal enum ChatColorMode { None, Line, Match }
/// <summary>
/// What a rule's colour does. Line: the line's text colour. Match: only the matched text.
/// Highlight (2026-11-01): a band in the colour behind the whole line, text in its own colour.
/// New values go at the end: the editor's dropdown is indexed by the value.
/// </summary>
internal enum ChatColorMode { None, Line, Match, Highlight }
/// <summary>
/// "colorMode" in rynthchat_settings.json and Export / Import, and the highlight band's colour.
/// Kept apart from ChatModel so tools/ChatFilterTests can check them.
/// </summary>
internal static class ChatColorModes
{
/// <summary>The value written to JSON; null (no key) for None, as every file before.</summary>
public static string? ToJson(ChatColorMode mode) => mode switch
{
ChatColorMode.Line => "line",
ChatColorMode.Match => "match",
ChatColorMode.Highlight => "highlight",
_ => null,
};
/// <summary>
/// Any case; "text" is an old spelling of "match". Unknown or absent: None. (A RynthCore
/// from before 2026-11-01 reads "highlight" the same way, as None: the rule loads, routes
/// as before and keeps its colour, it just doesn't colour.)
/// </summary>
public static ChatColorMode Parse(string? json) => (json ?? "").Trim().ToLowerInvariant() switch
{
"line" => ChatColorMode.Line,
"match" or "text" => ChatColorMode.Match,
"highlight" or "band" => ChatColorMode.Highlight,
_ => ChatColorMode.None,
};
/// <summary>How opaque the band is for an opaque swatch (0x66 = 40%).</summary>
public const uint BandAlpha = 0x66;
/// <summary>
/// The band drawn for a highlight colour: its RGB at 40% of its own alpha. The editor's
/// swatch is RGB only (always opaque), and at full strength a band in a light colour would
/// drown the text, which keeps its normal (often light) colour; 40% reads on the dark chat
/// with any text colour. An imported translucent colour ("#80RRGGBB") comes out fainter still.
/// </summary>
public static uint BandArgb(uint argb) => ((argb >> 24) * BandAlpha / 0xFF) << 24 | (argb & 0x00FFFFFF);
}
/// <summary>
/// One rule. Its fields are edited in place by a rule editor (then
@ -305,7 +355,7 @@ internal sealed class ChatRouter
{
bool hidden = false, inHome = true, routed = false;
List<string>? tabs = null;
uint? lineArgb = null;
uint? lineArgb = null, highlightArgb = null;
List<(int Start, int Length, uint Argb)>? spans = null;
for (int i = 0; i < _rules.Length; i++)
@ -322,8 +372,11 @@ internal sealed class ChatRouter
bool wantsRoute = routes && !routed;
bool wantsLine = mode == ChatColorMode.Line && lineArgb == null;
bool wantsMatch = mode == ChatColorMode.Match;
// The band works like the line colour, on its own: the first Highlight rule that
// matches picks it, whatever Line / Match rules did (they colour the text on top).
bool wantsHighlight = mode == ChatColorMode.Highlight && highlightArgb == null;
// Nothing left for it to decide (the test box still shows that it matches).
if (!wantsRoute && !wantsLine && !wantsMatch && trace == null) continue;
if (!wantsRoute && !wantsLine && !wantsMatch && !wantsHighlight && trace == null) continue;
if (!rule.WhenMatches(channel, chatType)) continue;
Match m;
@ -369,6 +422,13 @@ internal sealed class ChatRouter
}
else if (mode == ChatColorMode.Line && trace != null)
what!.Append(what.Length > 0 ? ", " : "").Append("(line colour already set above)");
if (wantsHighlight)
{
highlightArgb = rule.ColorArgb;
what?.Append(what.Length > 0 ? ", " : "").Append("highlights the line");
}
else if (mode == ChatColorMode.Highlight && trace != null)
what!.Append(what.Length > 0 ? ", " : "").Append("(highlight already set above)");
if (wantsMatch)
{
int n = 0;
@ -427,9 +487,9 @@ internal sealed class ChatRouter
if (mention) trace?.Add(new Step(-1, "mentions you (highlighted)"));
}
if (!hidden && inHome && tabs == null && lineArgb == null && spans == null && !mention)
if (!hidden && inHome && tabs == null && lineArgb == null && highlightArgb == null && spans == null && !mention)
return ChatRoute.Default;
return new ChatRoute(hidden, inHome, tabs?.ToArray(), lineArgb, Resolve(spans, text.Length), mention);
return new ChatRoute(hidden, inHome, tabs?.ToArray(), lineArgb, Resolve(spans, text.Length), mention, highlightArgb);
}
private static void AddTab(ref List<string>? tabs, string tab)

View file

@ -61,6 +61,9 @@ internal sealed class DamageRow
public List<DamageTierStat> Tiers = new();
/// <summary>The synthetic top "Default" line (wcid 0).</summary>
public bool IsDefault;
/// <summary>Evades, resists, attacks and spells both ways since login (the row's optional "mstats",
/// DamageRowStats.cs); null when the plugin sends none.</summary>
public DamageRowStats? Stats;
}
internal sealed class DamageTierStat
@ -303,6 +306,7 @@ internal sealed unsafe class DamageSource : UiSource<DamageView>
if (e.TryGetProperty("hitRate", out var hr)) row.HitRate = hr.GetDouble();
if (e.TryGetProperty("targeted", out var tg)) row.Targeted = tg.GetBoolean();
if (e.TryGetProperty("nearby", out var nb)) row.Nearby = nb.GetBoolean();
row.Stats = DamageRowStats.Parse(e);
if (e.TryGetProperty("tiers", out var tarr) && tarr.ValueKind == JsonValueKind.Array)
foreach (JsonElement te in tarr.EnumerateArray())
row.Tiers.Add(new DamageTierStat

View file

@ -0,0 +1,92 @@
// ============================================================================
// RynthCore.Engine - UI/Data/DamageRowStats.cs
// A Damage panel row's combat numbers since login (or the plugin's reset), as
// the plugin sends them: the optional "mstats" object of a row of
// RynthPluginGetMonsterDamageJson (RynthAi 2026-10-30, a player's request:
// "combat statistics under individual monsters, evades/resists for both the
// player and the monster"). DamageFace draws Line() under the monster's row and
// Tip() over it. A plugin that sends no "mstats" gets no line (as before).
//
// "mstats": { "sw": swings, "ev": evaded, "sp": spells, "rs": resisted, "ne": no effect,
// "at": attacks, "yev": you evaded, "ysp": spells at you, "yrs": you resisted,
// "yne": no effect on you, "k": kills, "dd": damage dealt, "dt": damage taken }
//
// sw = your melee and missile attacks at it (hits + its evades), sp = your spells that
// reached it (landed + resisted + no effect); at / ysp the same from it to you. Missing
// numbers are 0. The engine only words them; the plugin counts.
//
// Pure (System.Text.Json only): tools/DamageRowStatsTests compiles this file as is.
// The plugin sees an engine that draws them through GetUiHookFlags bit 8.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Json;
namespace RynthCore.Engine.UI.Data;
internal sealed record DamageRowStats(
int Swings, int Evaded, int Spells, int Resisted, int NoEffect,
int Attacks, int YouEvaded, int SpellsAtYou, int YouResisted, int NoEffectOnYou,
int Kills, long Dealt, long Taken)
{
/// <summary>The row's "mstats", or null when it has none (or nothing counted in it).</summary>
public static DamageRowStats? Parse(JsonElement row)
{
if (row.ValueKind != JsonValueKind.Object || !row.TryGetProperty("mstats", out JsonElement m) || m.ValueKind != JsonValueKind.Object)
return null;
var s = new DamageRowStats(I(m, "sw"), I(m, "ev"), I(m, "sp"), I(m, "rs"), I(m, "ne"),
I(m, "at"), I(m, "yev"), I(m, "ysp"), I(m, "yrs"), I(m, "yne"), I(m, "k"), L(m, "dd"), L(m, "dt"));
return s.IsEmpty ? null : s;
}
public bool IsEmpty => Swings == 0 && Spells == 0 && Attacks == 0 && SpellsAtYou == 0 && Kills == 0;
/// <summary>"23%" (whole from 10% up), "4.5%" (one decimal below), "-" with nothing to divide by. RynthAi words it the same.</summary>
public static string Percent(int part, int whole)
{
if (whole <= 0) return "-";
double p = Math.Clamp((double)part / whole, 0, 1) * 100;
p = p >= 10 ? Math.Round(p, MidpointRounding.AwayFromZero) : Math.Round(p, 1, MidpointRounding.AwayFromZero);
return p.ToString("0.#", CultureInfo.InvariantCulture) + "%";
}
/// <summary>
/// The line under the row: "It evades 23% (14/61) · It resists 10% (3/30) · You evade 42% (50/120) ·
/// You resist 13% (1/8)", each part only when there is something to divide by; "" for none.
/// </summary>
public string Line()
{
var parts = new List<string>(4);
if (Swings > 0) parts.Add($"It evades {Percent(Evaded, Swings)} ({N(Evaded)}/{N(Swings)})");
if (Spells > 0) parts.Add($"It resists {Percent(Resisted, Spells)} ({N(Resisted)}/{N(Spells)})");
if (Attacks > 0) parts.Add($"You evade {Percent(YouEvaded, Attacks)} ({N(YouEvaded)}/{N(Attacks)})");
if (SpellsAtYou > 0) parts.Add($"You resist {Percent(YouResisted, SpellsAtYou)} ({N(YouResisted)}/{N(SpellsAtYou)})");
return string.Join(" · ", parts);
}
/// <summary>The tooltip: both ways in full.</summary>
public string Tip()
{
string noEffect = NoEffect > 0 ? $", {N(NoEffect)} no effect (immune)" : "";
string noEffectYou = NoEffectOnYou > 0 ? $", {N(NoEffectOnYou)} no effect (immune)" : "";
return "Since you logged in (or /ra mstats reset):\n"
+ $"You at it: {N(Swings)} melee/missile attacks, {N(Swings - Evaded)} hit, it evaded {N(Evaded)} ({Percent(Evaded, Swings)}); "
+ $"{N(Spells)} spells reached it, it resisted {N(Resisted)} ({Percent(Resisted, Spells)}){noEffect}; "
+ $"{N(Dealt)} damage, {N(Kills)} {(Kills == 1 ? "kill" : "kills")}.\n"
+ $"It at you: {N(Attacks)} melee/missile attacks, {N(Attacks - YouEvaded)} hit, you evaded {N(YouEvaded)} ({Percent(YouEvaded, Attacks)}); "
+ $"{N(SpellsAtYou)} spells reached you, you resisted {N(YouResisted)} ({Percent(YouResisted, SpellsAtYou)}){noEffectYou}; "
+ $"{N(Taken)} damage.\n"
+ "The killing blow counts as a hit (melee, missile) or a landed spell (magic).";
}
private static string N(long v) => v.ToString("N0", CultureInfo.InvariantCulture);
private static int I(JsonElement m, string key)
=> m.TryGetProperty(key, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long x)
? (int)Math.Clamp(x, 0, int.MaxValue) : 0;
private static long L(JsonElement m, string key)
=> m.TryGetProperty(key, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long x) ? Math.Max(0, x) : 0;
}

View file

@ -43,6 +43,8 @@ internal sealed class LuaPayload
public bool? RynthAi { get; set; }
/// <summary>A character is logged in (per-character autostart needs one). Null from older plugins.</summary>
public bool? LoggedIn { get; set; }
/// <summary>Live reload: a running script restarts when its file is saved (/lua livereload). Null from a RynthLua without it.</summary>
public bool? LiveReload { get; set; }
}
/// <summary>One script in the v2 list (RynthLua's LuaScriptInfo).</summary>
@ -140,4 +142,14 @@ internal static unsafe class LuaCommands
UiSources.Lua.RequestRefreshAfterPluginTick();
});
}
/// <summary>
/// /lua &lt;args&gt; as if typed (it answers in chat), through RynthLua's remote command ("lua", args),
/// for a setting the panel command doesn't carry (live reload). Pump thread, like Send.
/// </summary>
public static void Chat(string args) => UiDataHub.Post("Lua /lua " + args, () =>
{
if (PluginManager.SendPluginCommand("RynthLua", "lua", args))
UiSources.Lua.RequestRefreshAfterPluginTick();
});
}

View file

@ -0,0 +1,29 @@
// ============================================================================
// RynthCore.Engine - UI/Data/LuaLiveReload.cs
// The Lua panel's live reload toggle (2026-10-31: the owner asked for buttons,
// not only commands): RynthLua's /lua livereload on|off, shown when its panel
// payload says LiveReload (a RynthLua without live reload sends nothing, and
// the toggle isn't drawn). What it says and the /lua arguments a click sends
// (LuaCommands.Chat). Pure, so tools\ChatCommandReplyTests compiles it in.
// ============================================================================
namespace RynthCore.Engine.UI.Data;
internal static class LuaLiveReload
{
/// <summary>The toggle's caption, or null when this RynthLua has no live reload (the toggle isn't drawn).</summary>
public static string? Label(bool? on) => on switch
{
true => "Live reload: on",
false => "Live reload: off",
_ => null,
};
/// <summary>The /lua arguments a click sends: the other value.</summary>
public static string ClickArgs(bool on) => on ? "livereload off" : "livereload on";
public static string Tip(bool on) =>
(on ? "On: a running script restarts when you save its file (or one it requires). Click to turn it off."
: "Off: saving a script's file doesn't restart it. Click to turn live reload on.")
+ "\nAlso: /lua livereload on|off";
}

View file

@ -19,6 +19,7 @@ using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Data;
@ -113,6 +114,9 @@ internal sealed class MetaPayload
public string SourceText { get; set; } = string.Empty;
/// <summary>Null from a plugin that doesn't report apply results yet (it reports to chat).</summary>
public MetaApplyResult? ApplyResult { get; set; }
/// <summary>The last write of the meta file, or the edit that wasn't applied (RynthAi's MetaSaver,
/// 2026-11-01); null from a RynthAi without it. The "Saved" indicator follows this.</summary>
public MetaSaveResult? SaveResult { get; set; }
/// <summary>The Meta Manager; null from a RynthAi without it.</summary>
public SchedulePayload? Schedule { get; set; }
/// <summary>Seconds in state and the Watchdog; null from a RynthAi without it.</summary>
@ -179,28 +183,47 @@ internal sealed unsafe class MetaSource : UiSource<MetaPayload>
internal static unsafe class MetaCommands
{
private static delegate* unmanaged[Cdecl]<IntPtr, void> _sendMetaCommand;
private static int _undelivered;
static MetaCommands()
{
PluginManager.PluginsUnloaded += () => _sendMetaCommand = null;
}
/// <summary>Commands that never reached RynthAi (not loaded, no export, the hub refused the post).
/// The Meta panel compares it before and after an edit: it went up = "Not saved: not sent".</summary>
public static int Undelivered => Volatile.Read(ref _undelivered);
/// <summary><paramref name="cmd"/> (and its Rule) must not be changed after this call.</summary>
public static void Send(MetaCmd cmd)
{
UiDataHub.Post("Meta " + cmd.Op, () =>
bool posted = UiDataHub.Post("Meta " + cmd.Op, () =>
{
if (_sendMetaCommand == null)
_sendMetaCommand = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve("RynthAi", "RynthPluginSendMetaCommand");
if (_sendMetaCommand == null) return;
if (_sendMetaCommand == null)
{
// Used to return without a word: the panel showed "Saved" for an edit RynthAi never got.
int n = Interlocked.Increment(ref _undelivered);
if (n <= 5 || n % 50 == 0)
RynthLog.UI($"Meta: '{cmd.Op}' NOT sent: RynthAi isn't loaded or has no RynthPluginSendMetaCommand ({n} not sent so far).");
return;
}
string json = JsonSerializer.Serialize(cmd, MetaJsonContext.Default.MetaCmd);
IntPtr ansi = Marshal.StringToHGlobalAnsi(json);
try { _sendMetaCommand(ansi); }
finally { Marshal.FreeHGlobal(ansi); }
if (IsRuleEdit(cmd.Op))
RynthLog.UI($"Meta: sent {cmd.Op}{(cmd.Index >= 0 ? " " + (cmd.Index + 1) : "")}{(cmd.Path.Length > 0 ? " " + cmd.Path : "")} to RynthAi.");
UiSources.Meta.RequestRefreshAfterPluginTick();
});
if (!posted) Interlocked.Increment(ref _undelivered); // the hub logged why
}
/// <summary>The commands that change the meta's rules or file (RynthAi writes the file after each).</summary>
public static bool IsRuleEdit(string op) => op is "add_rule" or "update_rule" or "delete_rule" or "move_up" or "move_down"
or "duplicate_rule" or "set_rule_enabled" or "set_source" or "save_file";
public static void Simple(string op, int index = -1, string value = "", string path = "")
=> Send(new MetaCmd { Op = op, Index = index, Value = value, Path = path });

View file

@ -110,6 +110,77 @@ internal sealed class MetaBackupPlan
public static string BackupOf(string file) => file + ".bak";
}
/// <summary>RynthAi's last write of the meta file, or the edit it didn't apply (the snapshot's "saveResult").</summary>
internal sealed class MetaSaveResult
{
/// <summary>Counts results this plugin session (0 = none yet).</summary>
public long Seq { get; set; }
public bool Ok { get; set; } = true;
/// <summary>What happened, in a few words ("Saved farm.af (12 rules)", "NOT saved to farm.af: ...").</summary>
public string Text { get; set; } = string.Empty;
public string Path { get; set; } = string.Empty;
}
/// <summary>What the Meta panel's save indicator shows.</summary>
internal enum MetaSaveState
{
/// <summary>Every change so far was written (or nothing was changed).</summary>
Saved,
/// <summary>A change was sent; RynthAi hasn't answered yet.</summary>
Saving,
/// <summary>RynthAi answered: the write failed, or the edit wasn't applied (the result says why).</summary>
Failed,
/// <summary>The change never reached RynthAi (not loaded, no export).</summary>
NotSent,
/// <summary>Sent, but no answer after <see cref="MetaSaveWatch.ConfirmMs"/>.</summary>
Unconfirmed,
}
/// <summary>
/// The Meta panel's "Saved" indicator (2026-11-01). It used to show "Saving..." for 2.5 s after a
/// change and then "Saved", whatever happened: an edit RynthAi refused, one it couldn't write, one
/// that never reached it all looked saved, and the change was simply gone the next time the meta
/// loaded. Now it waits for RynthAi's answer: the snapshot's <see cref="MetaSaveResult"/> with a
/// newer <see cref="MetaSaveResult.Seq"/> than the one seen when the change was sent. A RynthAi
/// without results (null) keeps the old timer.
/// </summary>
internal sealed class MetaSaveWatch
{
/// <summary>How long a change waits for RynthAi's answer before the indicator says it's not confirmed.</summary>
public const long ConfirmMs = 4000;
/// <summary>The old timer, for a RynthAi that reports no results.</summary>
public const long LegacySavingMs = 2500;
private long _sentAt = -1;
private long _seqAtSend;
private int _undeliveredAtSend;
/// <summary>A change was sent now; <paramref name="seenSeq"/> is the result seq the panel shows,
/// <paramref name="undelivered"/> MetaCommands.Undelivered.</summary>
public void Sent(long nowMs, long seenSeq, int undelivered)
{
// A burst of changes waits for the answer to the newest one; a send while still waiting keeps
// the older count, so a command dropped earlier in the burst still shows.
if (_sentAt < 0) _undeliveredAtSend = undelivered;
_sentAt = nowMs;
_seqAtSend = seenSeq;
}
/// <summary>The panel opened or another meta loaded: nothing is pending.</summary>
public void Reset() => _sentAt = -1;
public MetaSaveState State(long nowMs, MetaSaveResult? result, int undelivered)
{
if (_sentAt >= 0 && undelivered > _undeliveredAtSend) return MetaSaveState.NotSent;
if (result == null)
return _sentAt >= 0 && nowMs - _sentAt < LegacySavingMs ? MetaSaveState.Saving : MetaSaveState.Saved;
if (_sentAt >= 0 && result.Seq <= _seqAtSend)
return nowMs - _sentAt < ConfirmMs ? MetaSaveState.Saving : MetaSaveState.Unconfirmed;
if (_sentAt >= 0) _sentAt = -1; // answered
return result.Seq > 0 && !result.Ok ? MetaSaveState.Failed : MetaSaveState.Saved;
}
}
/// <summary>Rule edits the editor makes.</summary>
internal static class MetaRuleEdit
{

View file

@ -139,8 +139,12 @@ internal static class NavCommands
{
"Replace route with the trail (walk it again)",
"Replace route with a backtrack (walk it back)",
"Clear the trail (start a new one from here)",
};
/// <summary>The <see cref="TrailChoices"/> entry that wipes the trail (/ra navtrail clear) instead of making a route.</summary>
public const int TrailClearChoice = 2;
/// <summary>Route picker index for the plugin's RouteType (1 Circular, 2 Linear, 3 Follow, else Once).</summary>
public static int RouteIndex(int routeType) => routeType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 };

View file

@ -3,12 +3,14 @@
// Sense, our take on Virindi Sense: a watch list of names, and every object
// the client knows about, anywhere, whose name matches one.
//
// SenseStore the watch list and the alert settings, in
// SenseStore the watch list, the alert settings and the panel's look
// (full, compact, collapsed), in
// %LocalAppData%\RynthCore\sense.txt (read and written on
// UiBackgroundWriter, never on AC's render thread).
// SensePattern one term, case-insensitive. Without wildcards the name only
// has to contain it ("drake" finds "Dragon's Isle Drake");
// with * or ? the whole name must match ("Drake*", "?ire Ant").
// UiBackgroundWriter, never on AC's render thread; the text
// format is SenseFile in SenseModel.cs).
// SensePattern (SenseModel.cs) one term, case-insensitive. Without wildcards
// the name only has to contain it ("drake" finds "Dragon's Isle
// Drake"); with * or ? the whole name must match ("Drake*").
// SenseSource the scan: on the plugin pump thread at 2 Hz, reading only the
// engine's main-thread snapshots (LiveObjectIds, the identity,
// position, PWD and attackable snapshots, the player pose),
@ -43,60 +45,15 @@ using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.UI.Data;
/// <summary>One watch-list term. Immutable.</summary>
internal sealed class SensePattern
{
public SensePattern(string text, bool enabled)
{
Text = (text ?? string.Empty).Trim();
Enabled = enabled;
IsGlob = Text.IndexOfAny(Wildcards) >= 0;
}
private static readonly char[] Wildcards = { '*', '?' };
public string Text { get; }
public bool Enabled { get; }
/// <summary>True when the term has * or ?: the whole name must match it.</summary>
public bool IsGlob { get; }
public bool Matches(string name)
{
if (Text.Length == 0 || string.IsNullOrEmpty(name)) return false;
return IsGlob ? Glob(name, Text) : name.Contains(Text, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Case-insensitive whole-string match of <paramref name="s"/> against
/// <paramref name="p"/> (* any run, ? one character). Iterative, backtracking
/// only to the last *; no allocation.
/// </summary>
internal static bool Glob(string s, string p)
{
int si = 0, pi = 0, star = -1, mark = 0;
while (si < s.Length)
{
if (pi < p.Length && p[pi] == '*') { star = pi++; mark = si; }
else if (pi < p.Length && (p[pi] == '?' || Same(p[pi], s[si]))) { si++; pi++; }
else if (star >= 0) { pi = star + 1; si = ++mark; }
else return false;
}
while (pi < p.Length && p[pi] == '*') pi++;
return pi == p.Length;
}
private static bool Same(char a, char b) => a == b || char.ToUpperInvariant(a) == char.ToUpperInvariant(b);
}
/// <summary>
/// The watch list and alert settings. Edited on AC's thread (the face, /rc sense),
/// read by the scan on the pump thread: the term list is an immutable array
/// The watch list, alert settings and the panel's look. Edited on AC's thread (the face,
/// /rc sense), read by the scan on the pump thread: the term list is an immutable array
/// swapped whole, with a version the scan compares. File I/O on UiBackgroundWriter.
/// </summary>
internal static class SenseStore
{
public const int MaxTerms = 40;
public const int MaxTermLength = 64;
public const int MaxTerms = SenseFile.MaxTerms;
public const int MaxTermLength = SenseFile.MaxTermLength;
private static readonly object Sync = new();
private static SensePattern[] _terms = Array.Empty<SensePattern>();
@ -105,6 +62,7 @@ internal static class SenseStore
private static bool _loadQueued;
private static volatile bool _alertChat;
private static volatile bool _alertBeep;
private static volatile int _layout; // SenseLayoutMode
private static bool _alertSubscribed;
/// <summary>The current terms (never null; do not modify). Any thread.</summary>
@ -121,6 +79,9 @@ internal static class SenseStore
/// <summary>The system beep when a new match appears (off by default).</summary>
public static bool AlertBeep => _alertBeep;
/// <summary>How the panel looks: full (the default), compact or collapsed. Any thread.</summary>
public static SenseLayoutMode Layout => (SenseLayoutMode)_layout;
public static bool AnyEnabled
{
get
@ -148,44 +109,11 @@ internal static class SenseStore
private static void LoadNow()
{
var list = new List<SensePattern>();
bool chat = false, beep = false;
SenseFileData data = new();
try
{
string path = FilePath;
if (File.Exists(path))
{
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)..];
switch (key)
{
case "alertChat": chat = val.Trim() == "1"; break;
case "alertBeep": beep = val.Trim() == "1"; break;
case "term":
{
// term=1|pattern (1 on, 0 off); a bare term=pattern is on.
bool on = true;
string text = val;
int bar = val.IndexOf('|');
if (bar is 1 && (val[0] == '0' || val[0] == '1'))
{
on = val[0] == '1';
text = val[2..];
}
text = Clean(text);
if (text.Length > 0 && list.Count < MaxTerms && IndexOf(list, text) < 0)
list.Add(new SensePattern(text, on));
break;
}
}
}
}
if (File.Exists(path)) data = SenseFile.Parse(File.ReadAllLines(path));
}
catch (Exception ex)
{
@ -194,41 +122,29 @@ internal static class SenseStore
lock (Sync)
{
Volatile.Write(ref _terms, list.ToArray());
_alertChat = chat;
_alertBeep = beep;
Volatile.Write(ref _terms, data.Terms.ToArray());
_alertChat = data.AlertChat;
_alertBeep = data.AlertBeep;
_layout = (int)data.Layout;
Interlocked.Increment(ref _version);
_loaded = true;
}
SyncAlertSubscription();
}
private static string Clean(string text)
{
text = (text ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim();
return text.Length > MaxTermLength ? text[..MaxTermLength] : text;
}
private static int IndexOf(IReadOnlyList<SensePattern> list, string text)
{
for (int i = 0; i < list.Count; i++)
if (string.Equals(list[i].Text, text, StringComparison.OrdinalIgnoreCase)) return i;
return -1;
}
/// <summary>
/// Adds a term (switched on). An existing term with the same text is switched
/// on instead. False when the text is empty, the list is full or not loaded yet.
/// </summary>
public static bool Add(string text, out string message)
{
text = Clean(text);
text = SenseFile.Clean(text);
if (!_loaded) { message = "The watch list is still loading."; return false; }
if (text.Length == 0) { message = "Type a name first."; return false; }
lock (Sync)
{
SensePattern[] cur = _terms;
int at = IndexOf(cur, text);
int at = SenseFile.IndexOf(cur, text);
if (at >= 0)
{
message = cur[at].Enabled ? $"\"{cur[at].Text}\" is already on the list." : $"\"{cur[at].Text}\" switched on.";
@ -277,6 +193,19 @@ internal static class SenseStore
Save();
}
/// <summary>
/// Sets the panel's look and saves it with the list. False (nothing changes) while the list is
/// still loading: the file would be written before it was read. Any thread.
/// </summary>
public static bool SetLayout(SenseLayoutMode mode)
{
if (!_loaded) return false;
if ((int)mode == _layout) return true;
_layout = (int)mode;
Save();
return true;
}
// Under Sync.
private static void Replace(int index, SensePattern pattern)
{
@ -322,18 +251,11 @@ internal static class SenseStore
{
try
{
SensePattern[] terms = Terms;
var sb = new StringBuilder();
sb.AppendLine("# RynthCore Sense watch list - auto-generated, hand-edits OK. /rc sense in game.");
sb.AppendLine("# term=1|name (1 on, 0 off). No * or ?: the name contains it. With * or ?: the whole name matches.");
sb.AppendLine(_alertChat ? "alertChat=1" : "alertChat=0");
sb.AppendLine(_alertBeep ? "alertBeep=1" : "alertBeep=0");
foreach (SensePattern t in terms)
sb.Append("term=").Append(t.Enabled ? '1' : '0').Append('|').AppendLine(t.Text);
string text = SenseFile.Format(Terms, _alertChat, _alertBeep, Layout);
string path = FilePath;
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(path, sb.ToString());
File.WriteAllText(path, text);
}
catch (Exception ex)
{

View file

@ -0,0 +1,411 @@
// ============================================================================
// RynthCore.Engine - UI/Data/SenseModel.cs
// The Sense panel's pure part (no AC, no ImGui, no files), so tools\SenseTests
// can compile it in:
//
// SensePattern one watch-list term (moved here from SenseData.cs).
// SenseLayoutMode how the panel looks: Full (the add row, term chips, status
// and the match rows), Compact (only the match rows, tighter,
// no frame or background, clicks pass through except on the
// rows; item-counter.lua's bare look) and Collapsed (one line,
// "Sense: N", that opens back to Compact on a click).
// SenseFile sense.txt read and written as text: the terms, the alerts
// and the look (view=full|compact|collapsed).
// SenseLayout the compact view's layout decisions (which columns fit,
// row height, which row the mouse is on) and /rc sense's
// look commands (compact on|off, collapse on|off, view ...)
// with their replies.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Engine.UI.Data;
/// <summary>One watch-list term. Immutable.</summary>
internal sealed class SensePattern
{
public SensePattern(string text, bool enabled)
{
Text = (text ?? string.Empty).Trim();
Enabled = enabled;
IsGlob = Text.IndexOfAny(Wildcards) >= 0;
}
private static readonly char[] Wildcards = { '*', '?' };
public string Text { get; }
public bool Enabled { get; }
/// <summary>True when the term has * or ?: the whole name must match it.</summary>
public bool IsGlob { get; }
public bool Matches(string name)
{
if (Text.Length == 0 || string.IsNullOrEmpty(name)) return false;
return IsGlob ? Glob(name, Text) : name.Contains(Text, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Case-insensitive whole-string match of <paramref name="s"/> against
/// <paramref name="p"/> (* any run, ? one character). Iterative, backtracking
/// only to the last *; no allocation.
/// </summary>
internal static bool Glob(string s, string p)
{
int si = 0, pi = 0, star = -1, mark = 0;
while (si < s.Length)
{
if (pi < p.Length && p[pi] == '*') { star = pi++; mark = si; }
else if (pi < p.Length && (p[pi] == '?' || Same(p[pi], s[si]))) { si++; pi++; }
else if (star >= 0) { pi = star + 1; si = ++mark; }
else return false;
}
while (pi < p.Length && p[pi] == '*') pi++;
return pi == p.Length;
}
private static bool Same(char a, char b) => a == b || char.ToUpperInvariant(a) == char.ToUpperInvariant(b);
}
/// <summary>How the Sense panel looks (sense.txt "view").</summary>
internal enum SenseLayoutMode : byte
{
/// <summary>The whole panel: add row, chips, status, column header, rows. The default.</summary>
Full,
/// <summary>Only the match rows, tighter; no frame or background; clicks pass through except on the rows.</summary>
Compact,
/// <summary>One line, "Sense: N"; a click opens it to Compact.</summary>
Collapsed,
}
/// <summary>What sense.txt holds.</summary>
internal sealed class SenseFileData
{
public List<SensePattern> Terms = new();
public bool AlertChat;
public bool AlertBeep;
public SenseLayoutMode Layout = SenseLayoutMode.Full;
}
/// <summary>sense.txt as text (the store does the file I/O). Pure.</summary>
internal static class SenseFile
{
public const int MaxTerms = 40;
public const int MaxTermLength = 64;
/// <summary>
/// Reads the lines of sense.txt: "alertChat=1", "alertBeep=0", "view=compact", "term=1|name"
/// (1 on, 0 off; a bare "term=name" is on). Comments (#), blank lines and unknown keys are
/// skipped; a duplicate term (any case), an empty one or one past <see cref="MaxTerms"/> is
/// dropped; an unknown view is Full.
/// </summary>
public static SenseFileData Parse(IEnumerable<string> lines)
{
var data = new SenseFileData();
foreach (string raw in lines)
{
string line = (raw ?? string.Empty).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)..];
switch (key)
{
case "alertChat": data.AlertChat = val.Trim() == "1"; break;
case "alertBeep": data.AlertBeep = val.Trim() == "1"; break;
case "view":
data.Layout = SenseLayout.TryParseLayout(val, out SenseLayoutMode mode) ? mode : SenseLayoutMode.Full;
break;
case "term":
{
bool on = true;
string text = val;
int bar = val.IndexOf('|');
if (bar is 1 && (val[0] == '0' || val[0] == '1'))
{
on = val[0] == '1';
text = val[2..];
}
text = Clean(text);
if (text.Length > 0 && data.Terms.Count < MaxTerms && IndexOf(data.Terms, text) < 0)
data.Terms.Add(new SensePattern(text, on));
break;
}
}
}
return data;
}
/// <summary>The file's text (what <see cref="Parse"/> reads back).</summary>
public static string Format(IReadOnlyList<SensePattern> terms, bool alertChat, bool alertBeep, SenseLayoutMode layout)
{
var sb = new StringBuilder();
sb.AppendLine("# RynthCore Sense watch list - auto-generated, hand-edits OK. /rc sense in game.");
sb.AppendLine("# term=1|name (1 on, 0 off). No * or ?: the name contains it. With * or ?: the whole name matches.");
sb.AppendLine("# view=full|compact|collapsed (/rc sense compact on|off, /rc sense collapse on|off).");
sb.AppendLine(alertChat ? "alertChat=1" : "alertChat=0");
sb.AppendLine(alertBeep ? "alertBeep=1" : "alertBeep=0");
sb.Append("view=").AppendLine(SenseLayout.LayoutName(layout));
foreach (SensePattern t in terms)
sb.Append("term=").Append(t.Enabled ? '1' : '0').Append('|').AppendLine(t.Text);
return sb.ToString();
}
/// <summary>One line, trimmed, at most <see cref="MaxTermLength"/> characters.</summary>
public static string Clean(string text)
{
text = (text ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim();
return text.Length > MaxTermLength ? text[..MaxTermLength] : text;
}
/// <summary>The index of the term with this text (any case), or -1.</summary>
public static int IndexOf(IReadOnlyList<SensePattern> list, string text)
{
for (int i = 0; i < list.Count; i++)
if (string.Equals(list[i].Text, text, StringComparison.OrdinalIgnoreCase)) return i;
return -1;
}
}
/// <summary>The compact view's columns at a width (px): arrow, name and distance always.</summary>
internal readonly record struct SenseCompactColumns(bool Location, bool Kind, float NameWidth);
/// <summary>What one /rc sense look command did.</summary>
internal readonly record struct SenseLayoutAnswer(bool Ok, SenseLayoutMode Next, string Reply);
/// <summary>The compact view's layout and the look commands. Pure.</summary>
internal static class SenseLayout
{
/// <summary>Row heights (px at 100%): the full view's rows and the compact view's.</summary>
public const float FullRowHeight = 20f, CompactRowHeight = 16f;
/// <summary>Compact column widths (px at 100%).</summary>
public const float CompactArrowWidth = 16f, CompactDistWidth = 52f, CompactLocWidth = 104f, CompactKindWidth = 50f;
/// <summary>The name keeps at least this much before the coordinates, then the kind, are shown.</summary>
public const float CompactNameRoom = 110f;
public const string Usage =
"Usage: /rc sense [compact on|off | collapse on|off | view full|compact|collapsed] (alone: opens or closes the Sense panel)";
/// <summary>
/// Which compact columns fit in <paramref name="width"/> px (<paramref name="scale"/>: the text
/// size factor the widths grow with): the coordinates when the name still keeps
/// <see cref="CompactNameRoom"/>, then the kind on the same rule. The name gets what is left.
/// </summary>
public static SenseCompactColumns Compact(float width, float scale = 1f)
{
float k = scale > 0 ? scale : 1f;
float fixedW = (CompactArrowWidth + CompactDistWidth) * k;
float room = CompactNameRoom * k;
bool loc = width - fixedW - CompactLocWidth * k >= room;
bool kind = loc && width - fixedW - (CompactLocWidth + CompactKindWidth) * k >= room;
float name = width - fixedW - (loc ? CompactLocWidth * k : 0) - (kind ? CompactKindWidth * k : 0);
return new SenseCompactColumns(loc, kind, Math.Max(24f * k, name));
}
/// <summary>The collapsed line: "Sense: 3", "Sense: 0".</summary>
public static string CollapsedText(int matches) =>
"Sense: " + Math.Max(0, matches).ToString(CultureInfo.InvariantCulture);
/// <summary>
/// The match row under the mouse at <paramref name="mouseY"/> (rows start at <paramref name="top"/>,
/// <paramref name="rowHeight"/> apart, <paramref name="rows"/> of them shown); -1 for none.
/// </summary>
public static int RowAt(float mouseY, float top, float rowHeight, int rows)
{
if (rows <= 0 || rowHeight <= 0 || mouseY < top) return -1;
int i = (int)((mouseY - top) / rowHeight);
return i < rows ? i : -1;
}
/// <summary>
/// Whether the bare panel takes the mouse (else clicks go to the game): over what it drew, from
/// (<paramref name="x0"/>, <paramref name="y0"/>) to (<paramref name="drawnX1"/>, <paramref name="drawnY1"/>),
/// or, while it was already hot, anywhere in the strip to the right of that out to the buttons'
/// far edge (<paramref name="buttonsX1"/>), so the buttons beside the first line can be reached from any row.
/// </summary>
public static bool IsHot(float mx, float my, float x0, float y0, float drawnX1, float drawnY1, float buttonsX1, float buttonsY1, bool wasHot)
{
if (mx < x0 || my < y0) return false;
if (mx < drawnX1 && my < drawnY1) return true;
return wasHot && mx < buttonsX1 && my < Math.Max(drawnY1, buttonsY1);
}
/// <summary>
/// The view switch every look shows (2026-10-31: always there, not only on hover): the two other
/// looks, in the order their buttons stand. Full: compact, collapsed. Compact: collapsed (the
/// caret up), full. Collapsed: compact (the caret down), full.
/// </summary>
public static (SenseLayoutMode First, SenseLayoutMode Second) OtherViews(SenseLayoutMode current) => current switch
{
SenseLayoutMode.Compact => (SenseLayoutMode.Collapsed, SenseLayoutMode.Full),
SenseLayoutMode.Collapsed => (SenseLayoutMode.Compact, SenseLayoutMode.Full),
_ => (SenseLayoutMode.Compact, SenseLayoutMode.Collapsed),
};
/// <summary>What the view switch's button to <paramref name="to"/> says (its tooltip) and the command it matches.</summary>
public static string SwitchTip(SenseLayoutMode to) => to switch
{
SenseLayoutMode.Compact => "Compact: just the matches, no frame; clicks pass through around them (/rc sense view compact)",
SenseLayoutMode.Collapsed => "Collapse to one line, \"Sense: N\"; click it to show the matches (/rc sense view collapsed)",
_ => "The full Sense panel: add names, alerts, move and resize (/rc sense view full)",
};
/// <summary>
/// Whether the bare panel takes the mouse: <see cref="IsHot"/>, or over the view switch beside the
/// first line (from <paramref name="buttonsX0"/>), which is always drawn and so always clickable.
/// </summary>
public static bool TakesMouse(float mx, float my, float x0, float y0, float drawnX1, float drawnY1,
float buttonsX0, float buttonsX1, float buttonsY1, bool wasHot)
{
if (IsHot(mx, my, x0, y0, drawnX1, drawnY1, buttonsX1, buttonsY1, wasHot)) return true;
return mx >= buttonsX0 && mx < buttonsX1 && my >= y0 && my < buttonsY1;
}
/// <summary>
/// Compact rows that fit in <paramref name="height"/> px: (rows drawn, whether the last slot says
/// "+N more" instead). At least one slot when there are rows.
/// </summary>
public static (int Drawn, bool More) CompactFit(float height, float rowHeight, int rows)
{
int slots = RowsThatFit(height, rowHeight, rows);
return slots < rows ? (slots - 1, true) : (slots, false);
}
/// <summary>"+3 more".</summary>
public static string MoreText(int hidden) => "+" + Math.Max(0, hidden).ToString(CultureInfo.InvariantCulture) + " more";
/// <summary>How many rows of <paramref name="rowHeight"/> fit in <paramref name="height"/> (at least one when any).</summary>
public static int RowsThatFit(float height, float rowHeight, int rows)
{
if (rows <= 0) return 0;
if (rowHeight <= 0) return rows;
return Math.Clamp((int)(height / rowHeight), 1, rows);
}
public static string LayoutName(SenseLayoutMode mode) => mode switch
{
SenseLayoutMode.Compact => "compact",
SenseLayoutMode.Collapsed => "collapsed",
_ => "full",
};
/// <summary>"full", "compact" (or "small", "mini"), "collapsed" (or "collapse"), any case.</summary>
public static bool TryParseLayout(string text, out SenseLayoutMode mode)
{
switch ((text ?? string.Empty).Trim().ToLowerInvariant())
{
case "full": case "normal": mode = SenseLayoutMode.Full; return true;
case "compact": case "small": case "mini": mode = SenseLayoutMode.Compact; return true;
case "collapsed": case "collapse": mode = SenseLayoutMode.Collapsed; return true;
default: mode = SenseLayoutMode.Full; return false;
}
}
/// <summary>True when <paramref name="args"/> (after "/rc sense ") is a look command.</summary>
public static bool IsLayoutCommand(string args)
{
string first = FirstWord(args, out _);
return first is "compact" or "collapse" or "collapsed" or "view";
}
/// <summary>
/// The check before /rc sense runs (ChatCommandReplies): nothing (open or close the panel), or a
/// look command <see cref="Apply"/> takes: compact|collapse [on|off], view [full|compact|collapsed].
/// </summary>
public static bool IsValidArgs(string args)
{
string a = (args ?? string.Empty).Trim();
if (a.Length == 0) return true;
string word = FirstWord(a, out string rest);
string value = rest.Trim().ToLowerInvariant();
if (value.Contains(' ')) return false;
return word switch
{
"compact" or "collapse" or "collapsed" => value is "" or "on" or "off",
"view" => value is "" or "full" or "compact" or "collapsed",
_ => false,
};
}
/// <summary>
/// /rc sense compact on|off, collapse on|off, view full|compact|collapsed, from the look now
/// (<paramref name="current"/>). Alone (compact, collapse, view) each says the look now.
/// compact off is Full; collapse on is Collapsed, collapse off opens it to Compact (Full stays
/// Full). <paramref name="panelOpen"/>: the reply says how to open a closed panel.
/// </summary>
public static SenseLayoutAnswer Apply(string args, SenseLayoutMode current, bool panelOpen)
{
string word = FirstWord(args, out string rest);
string value = rest.Trim().ToLowerInvariant();
SenseLayoutMode next = current;
bool changed;
switch (word)
{
case "compact":
if (value.Length == 0) return Now(current, panelOpen);
if (!TryOnOff(value, out bool compactOn)) return Bad();
next = compactOn ? (current == SenseLayoutMode.Collapsed ? SenseLayoutMode.Collapsed : SenseLayoutMode.Compact)
: SenseLayoutMode.Full;
break;
case "collapse":
case "collapsed":
if (value.Length == 0) return Now(current, panelOpen);
if (!TryOnOff(value, out bool collapseOn)) return Bad();
next = collapseOn ? SenseLayoutMode.Collapsed
: current == SenseLayoutMode.Collapsed ? SenseLayoutMode.Compact : current;
break;
case "view":
if (value.Length == 0) return Now(current, panelOpen);
if (value is not ("full" or "compact" or "collapsed") || !TryParseLayout(value, out next)) return Bad();
break;
default:
return Bad();
}
changed = next != current;
return new SenseLayoutAnswer(true, next, Describe(next, changed ? "Sense: now the " : "Sense is already in the ", panelOpen));
}
/// <summary>
/// "&lt;head&gt;compact view (just the matches, ...)." plus, when the panel is closed, how to open it.
/// Heads: "Sense: now the " (changed), "Sense is already in the " (no change), "Sense is in the " (asked).
/// </summary>
public static string Describe(SenseLayoutMode mode, string head, bool panelOpen)
{
string what = mode switch
{
SenseLayoutMode.Compact => "compact view (just the matches; clicks pass through around them). /rc sense compact off for the full panel",
SenseLayoutMode.Collapsed => "collapsed view (one line, Sense: N). Click it, or /rc sense collapse off, to show the matches",
_ => "full view. /rc sense compact on for the small one",
};
return head + what + (panelOpen ? "." : ". The panel is closed: /rc sense opens it.");
}
private static SenseLayoutAnswer Now(SenseLayoutMode current, bool panelOpen) =>
new(true, current, Describe(current, "Sense is in the ", panelOpen));
private static SenseLayoutAnswer Bad() => new(false, default, Usage);
private static bool TryOnOff(string value, out bool on)
{
switch (value)
{
case "on": on = true; return true;
case "off": on = false; return true;
default: on = false; return false;
}
}
private static string FirstWord(string s, out string rest)
{
s = (s ?? string.Empty).Trim();
int sp = s.IndexOf(' ');
if (sp < 0) { rest = string.Empty; return s.ToLowerInvariant(); }
rest = s[(sp + 1)..].Trim();
return s[..sp].ToLowerInvariant();
}
}

View file

@ -78,6 +78,8 @@ internal sealed class RynthAiSettings
// Ranges > Combat Targeting. Null until RynthAi sends them; an older RynthAi leaves them alone.
public int? TargetSelection { get; set; }
public bool? TargetLock { get; set; }
// Fight the monster I select (RynthAi 2026-11-01). Null: a RynthAi without it; it leaves it alone.
public bool? FightSelectedTarget { get; set; }
public int TargetNoProgressTimeoutSec { get; set; }
public int GiveQueueIntervalMs { get; set; } = 150;
// Recharge
@ -493,7 +495,10 @@ internal sealed record SettingRow(
Action<RynthAiSettings>? Edit = null,
// Combo rows whose list changes while the game runs (the Theme picker's saved schemes):
// asked each time the row draws, in place of Items.
Func<string[]>? ItemsNow = null)
Func<string[]>? ItemsNow = null,
// Button rows that can't be undone: the question a click asks first (asked when it opens);
// Click/Edit run only when the player confirms.
Func<string>? Confirm = null)
{
public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s);
@ -652,6 +657,15 @@ internal static class SettingsSchema
private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) =>
new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click);
// A button that runs a RynthAi chat command as if typed (it answers in chat), through RynthAi's
// "sendchat" remote command: a one-shot action that has no setting of its own.
private static SettingRow ChatButton(string label, string buttonText, string command, string? tip = null) =>
Button(label, buttonText, () => RynthAiCommands.ApplyRemoteCommand("sendchat", command), tip);
// A button that asks first (Settings > Display's layout reset): Click runs once the player confirms.
private static SettingRow ConfirmButton(string label, string buttonText, Func<string> confirm, Action click, string? tip = null) =>
new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click, Confirm: confirm);
// A button that edits the settings (the panel saves the result like a typed value).
private static SettingRow EditButton(string label, string buttonText, Action<RynthAiSettings> edit, string? tip = null) =>
new(SettingKind.Button, label, tip, ButtonText: buttonText, Edit: edit);
@ -751,6 +765,18 @@ internal static class SettingsSchema
Bool("Remember Open Windows and Positions", _ => Plugins.EngineSettings.RememberWindowLayout,
(_, v) => Plugins.EngineSettings.RememberWindowLayout = v,
"On (default): reopen Rynth panels where you left them.\nOff: do not overwrite the saved panel layout or reopen panels from the last session. Applies to all your clients."),
// Stored in engine.json for every client (EngineSettings); the layouts themselves by UI/PanelLayout.
Bool("Panel Layout Per Character", _ => Plugins.EngineSettings.PanelLayoutPerCharacter,
(_, v) => Plugins.EngineSettings.PanelLayoutPerCharacter = v,
"On (default): each character keeps its own panel places (docked, popped out, the bar, plugin windows),\nso clients on this PC no longer move each other's panels. A new character starts from the default layout.\nOff: every client shares one layout, as before. /rc layout shows the files in use.\nThis client switches at once; your other clients when they start."),
// Whose layout is in use and its folder (/rc layout's first line, short).
Status(_ => PanelLayout.SettingsLine()),
Button("Layout for New Characters", "Use this character's", () => PanelLayout.MakeDefaultFromSettings(),
"Make this character's panel layout the default that new characters start from (/rc layout default).\nCharacters that already have a layout keep their own; the button below puts one back to the default.")
with { VisibleWhen = _ => Plugins.EngineSettings.PanelLayoutPerCharacter },
ConfirmButton("Reset This Character's Layout", "Reset...", () => PanelLayout.ResetConfirmText(), () => PanelLayout.ResetFromSettings(),
"Put this character's panel layout back to the default for new characters: open panels move to the default's places.\nAsks first. Also: /rc layout reset confirm.")
with { VisibleWhen = _ => Plugins.EngineSettings.PanelLayoutPerCharacter && PanelLayout.CanResetFromSettings },
Bool("Remember Game Window Position", _ => Plugins.EngineSettings.RememberAcWindowPosition,
(_, v) =>
{
@ -1196,6 +1222,12 @@ internal static class SettingsSchema
Bool("Target Lock", s => s.TargetLock ?? true, (s, v) => s.TargetLock = v,
"On: keeps the target it picked until it dies, leaves range (Disengage Range), or a higher-priority monster shows up.\n" +
"Off: switches whenever another monster is clearly better by the Targeting rule."),
Bool("Fight the monster I select", s => s.FightSelectedTarget ?? false, (s, v) => s.FightSelectedTarget = v,
"On: in a fight, a monster YOU select (click it, or pick it on the radar or in a Selection window)\n" +
"is fought first, ahead of Targeting and Priority, until it dies, can't be reached, or you select\n" +
"another monster or deselect. The bot's own selections never count. Ignored (Priority 0) and\n" +
"never-attack monsters are not followed (/ra targetlock still forces them). Out to Disengage Range.\n" +
"/ra fightselected [on|off]"),
Spacer(),
Section("Corpse Acquisition (Yards)"),
Double("Corpse Max (yd)", s => s.CorpseApproachRangeMax, (s, v) => s.CorpseApproachRangeMax = v, 0.5, 50.0, 0.5, CorpseMaxTip),
@ -1327,6 +1359,8 @@ internal static class SettingsSchema
"When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast."),
Bool("Cast buffs even when an item gives them", s => s.CastBuffsOverItemBuffs, (s, v) => s.CastBuffsOverItemBuffs = v,
"Cast your own buff even when worn gear already gives that buff.\nFor servers with buff augments, where your own cast is stronger or lasts longer.\nOn by default: on retail it costs a few extra casts."),
ChatButton("Buffs Left Out", "List in chat", "/ra buff skipped",
"The buffs RynthAi leaves out because this character can't use them, listed in chat (/ra buff skipped)."),
Spacer(),
Section("Protections (untick to skip)"),
BuffToggles(ProtToggles),
@ -1371,6 +1405,12 @@ internal static class SettingsSchema
"When your own corpse (\"Corpse of <you>\") is within loot range, open it and take every\nitem on it, whatever the loot profile and Loot From say. Needs Enable Looting.\n/ra owncorpse says where your last corpse is."),
Bool("Travel Back To My Corpse", s => s.TravelToOwnCorpse, (s, v) => s.TravelToOwnCorpse = v,
"After a death, walk back to where you died with RynthNav (outdoor deaths only),\nfighting on the way as usual, recover the corpse, then carry on. Needs the macro\nrunning and RynthNav loaded. /ra owncorpse stop cancels."),
ChatButton("Where Is My Corpse", "Say in chat", "/ra owncorpse",
"Where your last corpse is, how far, and whether RynthAi is on its way to it (/ra owncorpse)."),
ChatButton("Go To My Corpse", "Go", "/ra owncorpse go",
"Walk back to your last corpse now with RynthNav and recover it (/ra owncorpse go)."),
ChatButton("Stop Going To My Corpse", "Stop", "/ra owncorpse stop",
"Stop the walk back to your corpse (/ra owncorpse stop)."),
Spacer(),
Section("Inventory Management"),
Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v),
@ -1380,6 +1420,8 @@ internal static class SettingsSchema
"After the salvage queue empties, move same-name bags together so the server merges them."),
Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v,
"When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."),
ChatButton("Tidy Packs Now", "Stack and cram", "/mt autopack",
"One pass now: stack what stacks and move items from the main pack into side packs (/mt autopack).\nAutostack and Autocram above do it on their own while they are on."),
Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"),
"Opens the floating pack item count HUD / Mini Remote setup (/ra huds).\nThe Item Count panel is separate (/rc itemcount; Inventory's Count button)."),
Bool("Salvage Without The Panel", s => s.SalvageWithoutPanel, (s, v) => s.SalvageWithoutPanel = v,
@ -1456,6 +1498,23 @@ internal static class SettingsSchema
Note("+log = the category is at Info: its trace lines also go to the normal log. The launcher's Logging page sets Off, Trace or Info."),
Note("Exceptions always go to exceptions_<date>.txt with full stack traces (throttled). Settings here are for this PC, not the profile."),
Spacer(),
// Stored in engine.json for every client (EngineSettings.UiCostLog, UiCostThresholdMs; ImGui/UiCost.cs).
Section("UI Frame Cost"),
Bool("Time the UI frame's parts", _ => Plugins.EngineSettings.UiCostLog,
(_, v) => Plugins.EngineSettings.UiCostLog = v,
"On (default): every panel, plugin window and overlay is timed as it draws, and a slow UI frame\n" +
"writes one [UiCost] line to the log naming its slowest parts (at most one every 5 s). The heartbeat\n" +
"adds uitop= with the top 3 while UI frames are slow. Costs a few microseconds a frame. Also: /rc uicost on|off."),
Int(" Slow frame (ms)", _ => Plugins.EngineSettings.UiCostThresholdMs,
(_, v) => Plugins.EngineSettings.UiCostThresholdMs = v,
ImGuiBackend.UiCostModel.MinThresholdMs, ImGuiBackend.UiCostModel.MaxThresholdMs, 5,
"A UI frame this long or longer is logged with its breakdown. Default 50. Also: /rc uicost <ms>.",
when: _ => Plugins.EngineSettings.UiCostLog),
Button(" Breakdown", "Print to chat",
() => Compatibility.RynthCoreChatCommands.TryHandle("/rc uicost now", Compatibility.ChatCommandOrigin.Player),
"Which parts of the UI frame took the time over the last few seconds, and the slowest frame part by part\n" +
"(/rc uicost now)."),
Spacer(),
Section("Server"),
new SettingRow(SettingKind.ServerPick, "Server",
"Which server this character counts as. Auto detects it (the connect host, the world name the server announces, RynthILT).\n"

View file

@ -0,0 +1,175 @@
// ============================================================================
// RynthCore.Engine - UI/LootPatternText.cs
// The Loot Editor's words for a text condition's pattern (2026-11-01, the
// owner: "People hate regex ... let's add a does not contain"). A VTank text
// condition (String Value Match, name matches) holds a regex; the editor
// shows a mode and plain words instead and writes the regex for them:
//
// contains Sanguine Sanguine
// doesn't contain Sanguine ^(?!.*Sanguine)
// starts with Sanguine ^Sanguine
// ends with Sanguine Sanguine$
// is exactly Sanguine Robe ^Sanguine Robe$
// regex (anything) as typed
//
// The words are escaped the way RynthCore.LootSdk's LootItemRules.EscapeText
// does (regex metacharacters, spaces left alone), so a profile stays a plain
// VTank .utl. Reading a pattern back (Parse) gives the mode whose shape it
// has, else Regex. Several words: "Sanguine, Tattered" means either word
// (contains / doesn't contain only). Matching is case-insensitive (RynthAi's
// evaluator), so the words are too. Pure: tools\LootPatternTextTests.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Engine.UI;
internal enum LootTextMode { Contains, NotContains, StartsWith, EndsWith, Exactly, Regex }
internal static class LootPatternText
{
public static readonly LootTextMode[] Modes =
{ LootTextMode.Contains, LootTextMode.NotContains, LootTextMode.StartsWith, LootTextMode.EndsWith, LootTextMode.Exactly, LootTextMode.Regex };
public static readonly string[] Labels = { "contains", "doesn't contain", "starts with", "ends with", "is exactly", "regex" };
public static string Label(LootTextMode mode) => Labels[(int)mode];
/// <summary>What the field's hint says in <paramref name="mode"/>.</summary>
public static string Hint(LootTextMode mode) => mode switch
{
LootTextMode.Contains or LootTextMode.NotContains => "word(s), commas for either",
LootTextMode.Regex => "pattern (regex)",
_ => "text",
};
/// <summary>The regex for <paramref name="words"/> in <paramref name="mode"/> (Regex: the text as typed).</summary>
public static string Build(LootTextMode mode, string words)
{
if (mode == LootTextMode.Regex) return words;
string w = words.Trim();
if (w.Length == 0) return ""; // no words yet: an empty pattern (the editor keeps the mode)
switch (mode)
{
case LootTextMode.Contains:
return Alternatives(w, wrap: false);
case LootTextMode.NotContains:
return w.Length == 0 ? "" : "^(?!.*" + Alternatives(w, wrap: true) + ")";
case LootTextMode.StartsWith:
return "^" + Escape(w);
case LootTextMode.EndsWith:
return Escape(w) + "$";
default: // Exactly
return "^" + Escape(w) + "$";
}
}
/// <summary>
/// The mode and words <paramref name="pattern"/> stands for: the first shape it has (doesn't contain,
/// is exactly, starts with, ends with, contains), with its words unescaped; else Regex and the pattern.
/// An empty pattern is Contains with no words.
/// </summary>
public static (LootTextMode Mode, string Words) Parse(string pattern)
{
pattern ??= "";
if (pattern.Length == 0) return (LootTextMode.Contains, "");
if (pattern.StartsWith("^(?!.*", StringComparison.Ordinal) && pattern.EndsWith(")", StringComparison.Ordinal))
{
string inner = pattern.Substring(6, pattern.Length - 7);
if (inner.StartsWith("(", StringComparison.Ordinal) && inner.EndsWith(")", StringComparison.Ordinal)
&& TryWords(inner.Substring(1, inner.Length - 2), out string several) && several.Contains(','))
return (LootTextMode.NotContains, several);
if (TryUnescape(inner, out string one)) return (LootTextMode.NotContains, one);
}
bool start = pattern.StartsWith("^", StringComparison.Ordinal);
bool end = pattern.EndsWith("$", StringComparison.Ordinal) && !pattern.EndsWith("\\$", StringComparison.Ordinal);
string mid = pattern.Substring(start ? 1 : 0, pattern.Length - (start ? 1 : 0) - (end ? 1 : 0));
if (start || end)
{
if (TryUnescape(mid, out string text) && text.Length > 0)
return (start && end ? LootTextMode.Exactly : start ? LootTextMode.StartsWith : LootTextMode.EndsWith, text);
return (LootTextMode.Regex, pattern);
}
if (TryWords(pattern, out string words)) return (LootTextMode.Contains, words);
return (LootTextMode.Regex, pattern);
}
// "a, b" -> "a|b" (each escaped); wrap: "(a|b)" when there are several.
private static string Alternatives(string words, bool wrap)
{
var parts = new List<string>();
foreach (string raw in words.Split(','))
{
string p = raw.Trim();
if (p.Length > 0) parts.Add(Escape(p));
}
if (parts.Count == 0) return "";
string joined = string.Join("|", parts);
return wrap && parts.Count > 1 ? "(" + joined + ")" : joined;
}
// "a|b" (each a plain escaped text) -> "a, b".
private static bool TryWords(string pattern, out string words)
{
words = "";
var parts = new List<string>();
foreach (string piece in SplitTopLevelBars(pattern))
{
if (!TryUnescape(piece, out string t) || t.Trim().Length == 0 || t.Contains(',')) return false;
parts.Add(t);
}
if (parts.Count == 0) return false;
words = string.Join(", ", parts);
return true;
}
// Splits on '|' that isn't escaped.
private static IEnumerable<string> SplitTopLevelBars(string s)
{
var sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char ch = s[i];
if (ch == '\\' && i + 1 < s.Length) { sb.Append(ch).Append(s[++i]); continue; }
if (ch == '|') { yield return sb.ToString(); sb.Clear(); continue; }
sb.Append(ch);
}
yield return sb.ToString();
}
private const string Meta = "\\*+?|{}[]()^$.#";
/// <summary>Text with the regex metacharacters escaped, spaces left alone (as LootSdk's EscapeText).</summary>
public static string Escape(string text)
{
var sb = new StringBuilder(text.Length + 8);
foreach (char ch in text)
{
if (Meta.IndexOf(ch) >= 0) sb.Append('\\');
sb.Append(ch);
}
return sb.ToString();
}
/// <summary>The plain text <paramref name="pattern"/> is, when it has no unescaped metacharacter.</summary>
private static bool TryUnescape(string pattern, out string text)
{
var sb = new StringBuilder(pattern.Length);
for (int i = 0; i < pattern.Length; i++)
{
char ch = pattern[i];
if (ch == '\\')
{
if (i + 1 >= pattern.Length || Meta.IndexOf(pattern[i + 1]) < 0) { text = ""; return false; }
sb.Append(pattern[++i]);
continue;
}
if (Meta.IndexOf(ch) >= 0) { text = ""; return false; }
sb.Append(ch);
}
text = sb.ToString();
return true;
}
}

View file

@ -8,6 +8,12 @@
// font (Tom 2026-10-22: "the shortcut size needs to go a lot smaller").
// Stored for the whole PC in %LOCALAPPDATA%\RynthCore\panel_draw_scale.txt as
// "Title=percent" lines; every client looks for a change at most every 2 s.
//
// Sharp when bigger (2026-11-01, Tom: enlarged windows "get blurry"): a window
// drawn over 100% took its text from the normal bake, stretched. Now its fonts
// come from the text size bake just above its size (FontStep; PluginWindowFace
// switches ImGuiFonts.CurrentStep while the plugin draws), shrunk a little at
// most, and ImGuiFonts bakes the sizes the saved ones need with the text sizes.
// ============================================================================
using System;
@ -38,6 +44,9 @@ internal static class PanelDrawScale
private static readonly Dictionary<string, int> Scales = new(StringComparer.OrdinalIgnoreCase);
private static DateTime _fileTime = DateTime.MinValue;
private static long _checkedMs = long.MinValue / 2;
// The font steps last handed to ImGuiFonts' bake ("3,6"; null before the first bake).
private static string? _bakedSteps;
private const int RebuildDelayMs = 250;
private static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_draw_scale.txt");
@ -61,6 +70,7 @@ internal static class PanelDrawScale
Refresh();
if ((Scales.TryGetValue(title, out int cur) ? cur : 0) == percent) return;
if (percent == 0) Scales.Remove(title); else Scales[title] = percent;
NoteSteps();
try
{
string path = FilePath;
@ -90,16 +100,65 @@ internal static class PanelDrawScale
if (t == _fileTime) return;
_fileTime = t;
Scales.Clear();
if (t == DateTime.MinValue) return;
foreach (string raw in File.ReadAllLines(path))
{
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#')) continue;
int eq = line.LastIndexOf('=');
if (eq <= 0 || !int.TryParse(line.AsSpan(eq + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p)) continue;
if (p >= Min && p <= Max) Scales[line[..eq].Trim()] = p;
}
if (t != DateTime.MinValue)
foreach (string raw in File.ReadAllLines(path))
{
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#')) continue;
int eq = line.LastIndexOf('=');
if (eq <= 0 || !int.TryParse(line.AsSpan(eq + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p)) continue;
if (p >= Min && p <= Max) Scales[line[..eq].Trim()] = p;
}
NoteSteps();
}
catch { /* the old values stay */ }
}
/// <summary>
/// The text size step a window drawn at <paramref name="percent"/> takes its fonts from: the smallest
/// bake at least that big (shrinking a bigger bake stays sharp, stretching a smaller one blurs);
/// 0 at or under normal. A percent is of 96-DPI pixels; the fonts are baked at <paramref name="fontScale"/>.
/// </summary>
public static int FontStep(int percent, float fontScale)
{
if (percent <= 0) return 0;
float want = percent / 100f / Math.Max(0.5f, fontScale);
int last = PanelTextScale.SizeNames.Length - 1;
for (int step = 0; step < last; step++)
if (PanelTextScale.Factor(step) >= want - 0.005f) return step;
return last;
}
/// <summary>The non-zero font steps the saved sizes need; ImGuiFonts bakes them with the text sizes. Any thread.</summary>
public static List<int> FontStepsInUse(float fontScale)
{
lock (Sync)
{
Refresh();
List<int> steps = Steps(fontScale);
_bakedSteps = string.Join(",", steps);
return steps;
}
}
// Caller holds Sync.
private static List<int> Steps(float fontScale)
{
var steps = new List<int>();
foreach (int p in Scales.Values)
{
int step = FontStep(p, fontScale);
if (step > 0 && !steps.Contains(step)) steps.Add(step);
}
steps.Sort();
return steps;
}
// Caller holds Sync. A size whose font step isn't in the bake: re-bake once the changes stop.
private static void NoteSteps()
{
if (_bakedSteps == null) return;
string now = string.Join(",", Steps(RynthCore.Engine.ImGuiBackend.EngineFrameController.FontScale));
if (now != _bakedSteps) RynthCore.Engine.ImGuiBackend.ImGuiFonts.RequestRebuild(RebuildDelayMs);
}
}

View file

@ -0,0 +1,452 @@
// ============================================================================
// RynthCore.Engine - UI/PanelLayout.cs
// Panel layout per character (PanelLayoutPolicy.cs has the rules and names):
// which layout's files this client uses, the switch between them, and the
// engine's own saving of imgui.ini.
//
// Switching. Tick (EndScene, AC's render thread, every frame) works out the
// layout the client should use: the PC-wide default until a character is in
// the world, then that character's (SessionStateRegistry's server and name,
// known straight after LoginComplete, which a hot reload marks at engine init).
// A switch then runs in three steps:
// 1. render thread: snapshot the ImGui windows of the layout being left;
// 2. UI writer (UiBackgroundWriter, in order with every other UI save): write
// out the layout being left when it is a character's, seed a new
// character's files from the default, PanelStateStore.SwitchTo the new
// panel_state.txt, read the new imgui.ini;
// 3. render thread, before any panel draws: LoadIniSettingsFromMemory (Dear
// ImGui 1.91.6 applies loaded settings to windows that already exist,
// WindowSettingsHandler_ApplyAll), and the bar and the open panels take
// their places from the new store (ImGuiBar / ImGuiPanelHost.OnLayoutSwitched).
// After a login, panels draw only once step 3 is done for that login
// (ReadyToDraw, EngineFrameController.PanelsLive): never first at the default
// places and then a jump.
//
// imgui.ini. The context's IniFilename stays null (EngineFrameController.Init):
// the engine loads the file of the layout in use (step 3) and saves it when
// Dear ImGui asks (io.WantSaveIniSettings), at a switch and at shutdown, off
// the render thread and atomically, always to the file of the layout the
// context holds.
//
// The default pair is written by clients that use it in the world as before
// (setting off, no character name) and by /rc layout default; not by a switch,
// not at character select with the setting on, and never with the windows of a
// character that logged out (PanelLayoutPolicy.MayAutoSaveIni).
// ============================================================================
using System;
using System.IO;
using System.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI;
internal static class PanelLayout
{
private static readonly PanelLayoutSession Session = new();
private static readonly LatestTextWrites IniWrites = new(PanelLayoutFiles.WriteText);
private static volatile bool _initialized;
/// <summary>A finished step 2, waiting for the render thread.</summary>
private sealed record Loaded(LayoutSwitch Switch, LayoutFiles Files, string? IniText, string? Error, Action<string?>? After);
private static Loaded? _loaded; // written by the UI writer, read by the render thread
// Render thread: the layout applied (step 3; one reference, so other threads read it whole)
// and the ImGui windows' text for it.
private static Loaded? _applied;
private static string? _activeIniText;
private static bool _contextHeldCharacter; // the ImGui context has had a character's windows in it
private static LayoutOwner? _placedFor; // the layout the open panels were last placed from
private static bool _placedForSet;
/// <summary>The character whose layout is applied; null = the default (or none yet).</summary>
private static LayoutOwner? Active => Volatile.Read(ref _applied)?.Switch.To;
// The identity Tick last read (SessionStateRegistry's strings), so it isn't rebuilt every frame.
private static string? _idServer, _idCharacter;
private static LayoutOwner? _idOwner;
/// <summary>An /rc layout default or reset waiting for the render thread (one at a time).</summary>
private sealed record PendingOp(LayoutCommand Kind, Action<string, bool> Reply);
private static PendingOp? _pendingOp;
private static Action<string, bool>? _resetReply; // render thread: the reset switch's answer
/// <summary>True once the engine runs layouts (Initialize). Until then imgui.ini is Dear ImGui's own, as before.</summary>
public static bool Initialized => _initialized;
private static string LocalRoot =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore");
/// <summary>The PC-wide default imgui.ini (the file every client used before).</summary>
internal static string DefaultIniPath => Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, PanelLayoutPolicy.ImGuiIniFileName);
private static LayoutFiles FilesFor(LayoutOwner? who) => PanelLayoutPolicy.FilesFor(LocalRoot, DefaultIniPath, who);
/// <summary>Engine init (InitWorker), before the EndScene hook goes in. From here the engine owns imgui.ini.</summary>
public static void Initialize()
{
if (_initialized) return;
_initialized = true;
RynthLog.UI($"PanelLayout: per character {(EngineSettings.PanelLayoutPerCharacter ? "on" : "off")}; layouts under {Path.Combine(LocalRoot, PanelLayoutPolicy.LayoutsFolder)}.");
}
private static bool InWorld => LoginLifecycleHooks.HasObservedLoginComplete;
private static LayoutOwner? Identity()
{
string server = SessionStateRegistry.LastServerName, character = SessionStateRegistry.LastCharacterName;
if (!ReferenceEquals(server, _idServer) || !ReferenceEquals(character, _idCharacter))
{
_idServer = server;
_idCharacter = character;
_idOwner = PanelLayoutPolicy.Owner(server, character);
}
return _idOwner;
}
/// <summary>
/// True when panels may draw (EngineFrameController.PanelsLive): after a login, only once that
/// login's layout is in place. Always true before Initialize. Render thread.
/// </summary>
public static bool ReadyToDraw =>
!_initialized || Session.ReadyToDraw(Environment.TickCount64, InWorld, LoginLifecycleHooks.LoginCompleteAtMs);
// ── the frame (render thread) ─────────────────────────────────────────
/// <summary>
/// Once a frame, from EndScene (render thread, outside the ImGui frame). <paramref name="imguiInUse"/>:
/// the ImGui layer is on and didn't fail, so a layout waits for its context; <paramref name="imguiReady"/>:
/// the context exists. <paramref name="snapshotIni"/> / <paramref name="loadIni"/> run on it.
/// </summary>
public static void Tick(bool imguiInUse, bool imguiReady, Func<string?> snapshotIni, Action<string> loadIni)
{
if (!_initialized) return;
try
{
ApplyLoaded(imguiInUse, imguiReady, loadIni);
if (!Session.InFlight && Volatile.Read(ref _pendingOp) != null && Interlocked.Exchange(ref _pendingOp, null) is { } op)
RunOp(op, imguiReady ? snapshotIni : null);
LayoutSwitch? sw = Session.Tick(Environment.TickCount64, EngineSettings.PanelLayoutPerCharacter, InWorld,
LoginLifecycleHooks.LoginCompleteAtMs, SessionStateRegistry.LoginRecorded, Identity());
if (sw is { } s)
StartSwitch(s, s.FlushFrom && imguiReady ? snapshotIni() : null);
if (_resetReply is { } unanswered)
{
// The reset asked for this frame didn't become a switch: the layout in use changed first.
_resetReply = null;
unanswered(PanelLayoutPolicy.FailedReply("reset the panel layout", "the layout in use changed first; try again"), false);
}
}
catch (Exception ex)
{
RynthLog.UI($"PanelLayout: tick threw {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>Step 1: the switch goes to the UI writer, with the windows of the layout being left.</summary>
private static void StartSwitch(LayoutSwitch sw, string? fromIni)
{
LayoutFiles from = FilesFor(sw.From), to = FilesFor(sw.To);
if (sw.FlushFrom && fromIni != null) IniWrites.Queue(from.ImGuiIni, fromIni);
Action<string?>? after = null;
if (sw.Reseed && _resetReply is { } reply && sw.To is { } who)
{
_resetReply = null;
after = error => reply(error == null ? PanelLayoutPolicy.ResetDoneReply(who)
: PanelLayoutPolicy.FailedReply("reset " + PanelLayoutPolicy.Describe(who) + "'s panel layout", error), error == null);
}
UiBackgroundWriter.Enqueue("panel layout switch", () => LoadOnWriter(sw, from, to, after));
}
/// <summary>Step 2 (UI writer): write out what is left, seed or reseed, switch the store, read the new imgui.ini.</summary>
private static void LoadOnWriter(LayoutSwitch sw, LayoutFiles from, LayoutFiles to, Action<string?>? after)
{
string? ini = null, error = null;
string seeded = string.Empty;
try
{
if (sw.FlushFrom) IniWrites.Flush(from.ImGuiIni);
}
catch (Exception ex)
{
RynthLog.UI($"PanelLayout: writing out {from.ImGuiIni} failed - {ex.Message}");
}
try
{
if (sw.To != null)
{
LayoutFiles defaults = FilesFor(null);
if (sw.Reseed)
{
PanelLayoutFiles.CopyOver(defaults, to);
seeded = " (reset from the default)";
}
else
{
var copied = PanelLayoutFiles.SeedMissing(defaults, to);
if (copied.PanelState || copied.Ini)
seeded = " (new: " + (copied.PanelState && copied.Ini ? "both files" : copied.PanelState ? "panel_state.txt" : "imgui.ini")
+ " copied from the default)";
}
}
}
catch (Exception ex)
{
// The switch still happens: the character's files are made by its first save.
error = ex.Message;
}
// Never throws (it logs a file it can't read and starts empty).
PanelStateStore.SwitchTo(to.PanelState, flushCurrent: sw.FlushFrom);
try { ini = PanelLayoutFiles.ReadText(to.ImGuiIni); }
catch (Exception ex) { error ??= ex.Message; }
string who = sw.To is { } owner ? PanelLayoutPolicy.Describe(owner) + "'s" : "the PC-wide default";
if (error == null) RynthLog.UI($"PanelLayout: switched to {who} layout{seeded}: {to.PanelState}, {to.ImGuiIni}.");
else RynthLog.Warn($"PanelLayout: switched to {who} layout ({to.PanelState}), but its files had a problem - {error}.");
Volatile.Write(ref _loaded, new Loaded(sw, to, ini, error, after));
try { after?.Invoke(error); } catch { }
}
/// <summary>Step 3 (render thread): the loaded layout goes into the ImGui context, the bar and the open panels.</summary>
private static void ApplyLoaded(bool imguiInUse, bool imguiReady, Action<string> loadIni)
{
Loaded? l = Volatile.Read(ref _loaded);
if (l == null || ReferenceEquals(l, _applied)) return;
if (imguiInUse && !imguiReady) return; // the context is made this frame: apply on the next
if (imguiReady && !string.IsNullOrEmpty(l.IniText))
{
try { loadIni(l.IniText); }
catch (Exception ex) { RynthLog.UI($"PanelLayout: loading {l.Files.ImGuiIni} threw {ex.GetType().Name}: {ex.Message}"); }
}
Volatile.Write(ref _applied, l);
_activeIniText = l.IniText;
if (l.Switch.To != null) _contextHeldCharacter = true;
Session.MarkApplied(l.Switch.Gen);
// A reset places the panels again even though the layout's owner is the same.
if (InWorld && (l.Switch.Reseed || !_placedForSet || !Equals(l.Switch.To, _placedFor)))
{
// At character select nothing draws: the panels are placed when a character comes in.
_placedFor = l.Switch.To;
_placedForSet = true;
ImGuiBackend.ImGuiBar.OnLayoutSwitched();
ImGuiBackend.ImGuiPanelHost.OnLayoutSwitched();
}
}
/// <summary>
/// The ImGui context was just made (EngineFrameController.Init, context current, before its first
/// frame): it starts with the windows of the layout in use, if one is applied already.
/// </summary>
public static void OnContextCreated(Action<string> loadIni)
{
if (!_initialized || _applied == null || string.IsNullOrEmpty(_activeIniText)) return;
try { loadIni(_activeIniText); }
catch (Exception ex) { RynthLog.UI($"PanelLayout: loading the layout into the new context threw {ex.GetType().Name}: {ex.Message}"); }
}
// ── saving imgui.ini ──────────────────────────────────────────────────
/// <summary>
/// The ImGui windows' text to save (render thread): Dear ImGui's dirty timer (io.WantSaveIniSettings),
/// or <paramref name="explicitSave"/> for Save Layout Now. Written in the background, atomically, to
/// the file of the layout the context holds.
/// </summary>
public static void QueueIniSave(string text, bool explicitSave)
{
if (!_initialized)
{
// Dear ImGui owns the file (IniFilename pinned): Save Layout Now writes the default, as before.
if (explicitSave) UiBackgroundWriter.Enqueue("imgui.ini", () => PanelLayoutFiles.WriteText(DefaultIniPath, text));
return;
}
if (!MaySave(explicitSave, out string path)) return;
_activeIniText = text;
IniWrites.Queue(path, text);
UiBackgroundWriter.Enqueue("imgui.ini", () =>
{
try { IniWrites.Flush(path); }
catch (Exception ex) { RynthLog.UI($"PanelLayout: saving {path} failed - {ex.Message}"); }
});
}
/// <summary>The ImGui context is about to go (engine shutdown, a hot reload): its windows are written now.</summary>
public static void SaveIniOnShutdown(string text)
{
if (!_initialized || !MaySave(explicitSave: false, out string path)) return;
try
{
IniWrites.Queue(path, text);
IniWrites.Flush(path);
}
catch (Exception ex)
{
RynthLog.UI($"PanelLayout: saving {path} at shutdown failed - {ex.Message}");
}
}
private static bool MaySave(bool explicitSave, out string path)
{
path = string.Empty;
// Nothing applied yet: the context holds no file's windows, and saving it would empty one.
if (Volatile.Read(ref _applied) is not { } applied) return false;
if (!explicitSave && !PanelLayoutPolicy.MayAutoSaveIni(applied.Switch.To != null, EngineSettings.PanelLayoutPerCharacter, InWorld, _contextHeldCharacter))
return false;
path = applied.Files.ImGuiIni;
return true;
}
// ── /rc layout and Settings ───────────────────────────────────────────
/// <summary>/rc layout: the layout in use, its files, and the default's. Any thread (racy reads).</summary>
public static string[] DescribeLines()
{
LayoutFiles defaults = FilesFor(null);
if (!_initialized)
return PanelLayoutPolicy.StatusLines(null, defaults, DefaultReason.NotRunning, defaults, false);
bool perCharacter = EngineSettings.PanelLayoutPerCharacter;
Loaded? applied = Volatile.Read(ref _applied);
LayoutOwner? active = applied?.Switch.To;
LayoutFiles files = applied?.Files ?? defaults;
DefaultReason why = DefaultReason.None;
if (active == null)
{
if (!perCharacter) why = DefaultReason.SettingOff;
else if (!InWorld) why = DefaultReason.NotInWorld;
else if (!Session.Decided) why = DefaultReason.WaitingForName;
else if (Session.Wanted == null) why = DefaultReason.NoCharacterName;
}
return PanelLayoutPolicy.StatusLines(active, files, why, defaults, perCharacter);
}
// Settings > Display's line, built again only when what it shows changed (it draws every frame).
private static Loaded? _lineFor;
private static int _lineFlags = -1;
private static string _line = string.Empty;
/// <summary>Settings > Display: whose layout this client uses and where its files are. Render thread.</summary>
public static string SettingsLine()
{
bool perCharacter = EngineSettings.PanelLayoutPerCharacter;
Loaded? applied = Volatile.Read(ref _applied);
int flags = (perCharacter ? 1 : 0) | (InWorld ? 2 : 0) | (Session.Decided ? 4 : 0) | (Session.Wanted != null ? 8 : 0) | (_initialized ? 16 : 0);
if (ReferenceEquals(applied, _lineFor) && flags == _lineFlags) return _line;
_lineFor = applied;
_lineFlags = flags;
LayoutFiles defaults = FilesFor(null);
LayoutOwner? active = applied?.Switch.To;
DefaultReason why = DefaultReason.None;
if (!_initialized) why = DefaultReason.NotRunning;
else if (active == null)
{
if (!perCharacter) why = DefaultReason.SettingOff;
else if (!InWorld) why = DefaultReason.NotInWorld;
else if (!Session.Decided) why = DefaultReason.WaitingForName;
else if (Session.Wanted == null) why = DefaultReason.NoCharacterName;
}
_line = PanelLayoutPolicy.SettingsLine(active, applied?.Files ?? defaults, why);
return _line;
}
/// <summary>Settings > Display's reset button: there is a character's own layout to reset.</summary>
public static bool CanResetFromSettings => _initialized && Active != null;
/// <summary>Settings > Display's reset confirmation text.</summary>
public static string ResetConfirmText() => PanelLayoutPolicy.ResetConfirmText(Active);
/// <summary>Settings > Display "Reset this character's layout" (confirmed): /rc layout reset confirm, answered in chat.</summary>
public static void ResetFromSettings()
{
static void Chat(string text, bool ok) =>
AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, ok ? 1 : 0x1A);
string? problem = Request(LayoutCommand.ResetConfirm, Chat);
if (problem != null) Chat(problem, false);
}
/// <summary>
/// /rc layout default or reset: null when it can run, else why not (with the usage). Reset without
/// confirm only answers what it would do (<paramref name="ask"/>). Any thread.
/// </summary>
public static string? Check(LayoutCommand kind, out string ask)
{
ask = string.Empty;
string verb = kind == LayoutCommand.MakeDefault ? "make a default from this client" : "reset the panel layout";
LayoutOwner? active = Active;
string? problem = PanelLayoutPolicy.CharacterLayoutProblem(verb, _initialized, EngineSettings.PanelLayoutPerCharacter,
InWorld, active, Session.InFlight);
if (problem == null && kind == LayoutCommand.ResetAsk && active != null)
ask = PanelLayoutPolicy.ResetAskReply(active, FilesFor(null));
return problem;
}
/// <summary>
/// /rc layout default or reset confirm: queued for the render thread; <paramref name="reply"/> gets the
/// result (text, ok) from the UI writer when it is done. Null when queued, else why not. Any thread.
/// </summary>
public static string? Request(LayoutCommand kind, Action<string, bool> reply)
{
string? problem = Check(kind, out _);
if (problem != null) return problem;
if (Interlocked.CompareExchange(ref _pendingOp, new PendingOp(kind, reply), null) != null)
return PanelLayoutPolicy.BusyReply;
return null;
}
/// <summary>Settings > Display "Layout for New Characters": /rc layout default, answered in chat.</summary>
public static void MakeDefaultFromSettings()
{
static void Chat(string text, bool ok) =>
AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, ok ? 1 : 0x1A);
string? problem = Request(LayoutCommand.MakeDefault, Chat);
if (problem != null) Chat(problem, false);
}
/// <summary>Runs a queued /rc layout op (render thread, no switch in flight).</summary>
private static void RunOp(PendingOp op, Func<string?>? snapshotIni)
{
Loaded? applied = Volatile.Read(ref _applied);
if (applied?.Switch.To is not { } who)
{
// The layout changed between the command and this frame (a logout, the setting).
op.Reply(PanelLayoutPolicy.CharacterLayoutProblem("change the panel layout", true, EngineSettings.PanelLayoutPerCharacter,
InWorld, null, false) ?? PanelLayoutPolicy.FailedReply("change the panel layout", "no character layout is in use"), false);
return;
}
LayoutFiles files = applied.Files;
if (op.Kind == LayoutCommand.ResetConfirm)
{
// The next switch (this frame) copies the default over this character's files and
// places the panels from it; it answers when its files are done.
_resetReply = op.Reply;
Session.WantReseed();
return;
}
// Make default: this character's windows as they are now (saved to its own file too), then
// the panel store's text, both written as the default, in order after every save queued so far.
string? ini = snapshotIni?.Invoke();
if (ini != null)
{
_activeIniText = ini;
IniWrites.Queue(files.ImGuiIni, ini);
}
LayoutFiles defaults = FilesFor(null);
UiBackgroundWriter.Enqueue("panel layout default", () =>
{
try
{
IniWrites.Flush(files.ImGuiIni);
PanelLayoutFiles.MakeDefault(files, defaults, PanelStateStore.Snapshot(), ini);
RynthLog.UI($"PanelLayout: {PanelLayoutPolicy.Describe(who)}'s layout is now the default ({defaults.PanelState}, {defaults.ImGuiIni}).");
op.Reply(PanelLayoutPolicy.MakeDefaultDoneReply(who, defaults), true);
}
catch (Exception ex)
{
op.Reply(PanelLayoutPolicy.FailedReply("make the default", ex.Message), false);
}
});
}
}

View file

@ -0,0 +1,123 @@
// ============================================================================
// RynthCore.Engine - UI/PanelLayoutFiles.cs
// Panel layout per character: the file operations (PanelLayoutPolicy has the
// names and decisions). No engine state and no logging, so
// tools\PanelLayoutTests runs them against a temp folder.
//
// Every write is atomic (a temp file beside the target, then a replace:
// EngineSettingsFile.WriteAtomic), so a client that dies mid-save leaves the
// old file, never half a file. Each client writes only its own character's
// files; the default pair is written only by an explicit "make this the
// default" and, as before, by clients that use it.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI;
internal static class PanelLayoutFiles
{
private static readonly UTF8Encoding Utf8NoBom = new(false);
/// <summary>The file's text, or null when there is none.</summary>
public static string? ReadText(string path) => File.Exists(path) ? File.ReadAllText(path) : null;
/// <summary>Writes <paramref name="text"/> to <paramref name="path"/> atomically (creating its folder).</summary>
public static void WriteText(string path, string text)
{
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
EngineSettingsFile.WriteAtomic(path, Utf8NoBom.GetBytes(text));
}
/// <summary>
/// A character without a layout yet starts from the default: each of its files that is missing is
/// copied from the default's (PanelLayoutPolicy.SeedPlan). Files it already has are left alone.
/// Returns which were copied.
/// </summary>
public static (bool PanelState, bool Ini) SeedMissing(LayoutFiles defaults, LayoutFiles character)
{
var plan = PanelLayoutPolicy.SeedPlan(File.Exists(character.PanelState), File.Exists(character.ImGuiIni),
File.Exists(defaults.PanelState), File.Exists(defaults.ImGuiIni));
if (plan.PanelState) CopyAtomic(defaults.PanelState, character.PanelState);
if (plan.Ini) CopyAtomic(defaults.ImGuiIni, character.ImGuiIni);
return plan;
}
/// <summary>
/// /rc layout reset: the character's files become copies of the default's. A file the default
/// doesn't have makes the character's empty (as a new character with no default would start), so
/// nothing of the old layout is left. Nothing is deleted.
/// </summary>
public static void CopyOver(LayoutFiles defaults, LayoutFiles character)
{
if (File.Exists(defaults.PanelState)) CopyAtomic(defaults.PanelState, character.PanelState);
else WriteText(character.PanelState, string.Empty);
if (File.Exists(defaults.ImGuiIni)) CopyAtomic(defaults.ImGuiIni, character.ImGuiIni);
else WriteText(character.ImGuiIni, string.Empty);
}
/// <summary>
/// /rc layout default: the character's layout becomes the default for new characters.
/// <paramref name="panelState"/> is the panel store's text now; <paramref name="ini"/> the ImGui
/// windows' (null: the character's imgui.ini as saved, and nothing when it has none).
/// </summary>
public static void MakeDefault(LayoutFiles character, LayoutFiles defaults, string panelState, string? ini)
{
WriteText(defaults.PanelState, panelState);
string? text = ini ?? ReadText(character.ImGuiIni);
if (text != null) WriteText(defaults.ImGuiIni, text);
}
private static void CopyAtomic(string from, string to)
{
string? dir = Path.GetDirectoryName(to);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
EngineSettingsFile.WriteAtomic(to, File.ReadAllBytes(from));
}
}
/// <summary>
/// The latest text queued for each file, written by whoever flushes it first (the UI writer, a layout
/// switch, shutdown): an older save can never land after a newer one. Writes run one at a time.
/// </summary>
internal sealed class LatestTextWrites
{
private readonly object _slots = new();
private readonly object _writing = new();
private readonly Dictionary<string, string> _pending = new(StringComparer.OrdinalIgnoreCase);
private readonly Action<string, string> _write;
public LatestTextWrites(Action<string, string> write) => _write = write;
/// <summary>Keeps <paramref name="text"/> as what <paramref name="path"/> gets next (replacing an unwritten one). Any thread; never blocks on a write.</summary>
public void Queue(string path, string text)
{
lock (_slots) _pending[path] = text;
}
/// <summary>Writes <paramref name="path"/>'s queued text, if any. False when there was nothing to write. Throws what the write throws.</summary>
public bool Flush(string path)
{
lock (_writing)
{
string? text;
lock (_slots)
{
if (!_pending.Remove(path, out text)) return false;
}
_write(path, text);
return true;
}
}
/// <summary>True while <paramref name="path"/> has text waiting.</summary>
public bool HasPending(string path)
{
lock (_slots) return _pending.ContainsKey(path);
}
}

View file

@ -0,0 +1,354 @@
// ============================================================================
// RynthCore.Engine - UI/PanelLayoutPolicy.cs
// Panel layout per character: the pure part (no AC, no ImGui, no engine
// state), so tools\PanelLayoutTests can compile it in. PanelLayout.cs does the
// threads and the engine's stores; PanelLayoutFiles.cs the file operations.
//
// A layout is the pair of files the engine keeps window places in:
// panel_state.txt docked panels, pop-outs, the bar (place, rows, popped
// out), plugin windows (v89) and script windows (v71);
// imgui.ini the windows plugins draw with ImGui themselves.
// Every client on a PC used to share one pair, so whichever client saved last
// won and the others came back from a reload or a restart with its places.
// Now a client in the world uses its character's own pair:
// %LOCALAPPDATA%\RynthCore\layouts\<server>\<character>\panel_state.txt, imgui.ini
// At character select, while no character name is known, and with the setting
// off (engine.json "PanelLayoutPerCharacter": false) it uses the PC-wide
// default pair, the files every client used before: panel_state.txt beside
// that folder and C:\Games\RynthSuite\RynthAi\imgui.ini. A character without
// a layout yet starts from a copy of the default, so nothing moves the first
// time. The key is the one the engine's other per-character files use: the
// server and character of the launch context (SessionStateRegistry).
//
// Here: who owns a layout and its file names, which layout a client uses,
// what a new character's layout is seeded from, the session bookkeeping that
// decides when to switch and when panels may draw (PanelLayoutSession), and
// /rc layout's parsing and reply texts.
// ============================================================================
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace RynthCore.Engine.UI;
/// <summary>Whose layout: a character on a server (names as the launch context gives them).</summary>
internal sealed record LayoutOwner(string Server, string Character)
{
// AC names are unique per server ignoring case, and the folders are case-insensitive too.
public bool Equals(LayoutOwner? other) =>
other is not null
&& string.Equals(Server, other.Server, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Character, other.Character, StringComparison.OrdinalIgnoreCase);
public override int GetHashCode() =>
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(Server), StringComparer.OrdinalIgnoreCase.GetHashCode(Character));
}
/// <summary>The two files of one layout.</summary>
internal readonly record struct LayoutFiles(string PanelState, string ImGuiIni)
{
public string Folder => Path.GetDirectoryName(PanelState) ?? string.Empty;
}
/// <summary>What /rc layout asks for.</summary>
internal enum LayoutCommand { Invalid, Status, MakeDefault, ResetAsk, ResetConfirm }
/// <summary>Why a client in the world uses the PC-wide default (the status line says it).</summary>
internal enum DefaultReason { None, SettingOff, NotInWorld, NoCharacterName, WaitingForName, NotRunning }
internal static class PanelLayoutPolicy
{
public const string PanelStateFileName = "panel_state.txt";
public const string ImGuiIniFileName = "imgui.ini";
public const string LayoutsFolder = "layouts";
/// <summary>After login, how long a client waits for the character's name before it uses what it has.</summary>
public const long IdentityWaitMs = 3000;
/// <summary>A switch that hasn't finished this long after it was asked for no longer keeps panels from drawing.</summary>
public const long ApplyGiveUpMs = 5000;
// ── who, and the file names ────────────────────────────────────────
/// <summary>The layout's owner, or null while no character name is known.</summary>
public static LayoutOwner? Owner(string? server, string? character)
{
string c = (character ?? string.Empty).Trim();
if (c.Length == 0) return null;
return new LayoutOwner((server ?? string.Empty).Trim(), c);
}
/// <summary>"Name on Server" (just the name when the server isn't known), for replies and the log.</summary>
public static string Describe(LayoutOwner who) =>
who.Server.Length > 0 ? who.Character + " on " + who.Server : who.Character;
/// <summary>The PC-wide default pair: today's files.</summary>
public static LayoutFiles DefaultFiles(string localRoot, string defaultIniPath) =>
new(Path.Combine(localRoot, PanelStateFileName), defaultIniPath);
/// <summary>A character's pair: &lt;localRoot&gt;\layouts\&lt;server&gt;\&lt;character&gt;\.</summary>
public static LayoutFiles CharacterFiles(string localRoot, LayoutOwner who)
{
string dir = Path.Combine(localRoot, LayoutsFolder, SafeSegment(who.Server), SafeSegment(who.Character));
return new LayoutFiles(Path.Combine(dir, PanelStateFileName), Path.Combine(dir, ImGuiIniFileName));
}
/// <summary>The files for <paramref name="who"/>; null = the PC-wide default.</summary>
public static LayoutFiles FilesFor(string localRoot, string defaultIniPath, LayoutOwner? who) =>
who is null ? DefaultFiles(localRoot, defaultIniPath) : CharacterFiles(localRoot, who);
private const int MaxSegment = 64;
private static readonly string[] ReservedNames =
{
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
};
/// <summary>
/// <paramref name="name"/> as one folder name: characters Windows doesn't allow become '_', no
/// trailing dot or space, not a device name, at most 64 characters; "_" for an empty name. A name
/// that had to change gets "-" and a hash of the original, so two names that clean up alike
/// (a server "A:B" and one "A?B") keep apart. Names that are already safe stay as they are.
/// </summary>
public static string SafeSegment(string? name)
{
string original = (name ?? string.Empty).Trim();
if (original.Length == 0) return "_";
char[] invalid = Path.GetInvalidFileNameChars();
var sb = new StringBuilder(original.Length);
foreach (char ch in original)
sb.Append(ch < 32 || Array.IndexOf(invalid, ch) >= 0 ? '_' : ch);
string s = sb.ToString().TrimEnd('.', ' ');
if (s.Length > MaxSegment) s = s.Substring(0, MaxSegment).TrimEnd('.', ' ');
string stem = s.Split('.')[0];
if (s.Length == 0 || Array.Exists(ReservedNames, r => r.Equals(stem, StringComparison.OrdinalIgnoreCase)))
s = "_" + s;
if (s == original) return s;
uint h = 2166136261; // FNV-1a over the lower-cased original
foreach (char ch in original.ToLowerInvariant())
h = (h ^ ch) * 16777619;
return s + "-" + h.ToString("x8", CultureInfo.InvariantCulture);
}
// ── which layout ─────────────────────────────────────────────────────
/// <summary>The layout a client uses: its character's while in the world with the setting on and a
/// name known; otherwise (null) the PC-wide default.</summary>
public static LayoutOwner? Choose(bool perCharacter, bool inWorld, LayoutOwner? identity) =>
perCharacter && inWorld ? identity : null;
/// <summary>Which of a new character's files are copied from the default: each one the character
/// doesn't have yet and the default has (a missing default file leaves the character's missing too).</summary>
public static (bool PanelState, bool Ini) SeedPlan(bool characterPanelState, bool characterIni, bool defaultPanelState, bool defaultIni) =>
(!characterPanelState && defaultPanelState, !characterIni && defaultIni);
/// <summary>
/// Whether an automatic save of the ImGui windows (the dirty timer, shutdown) may write the file in
/// use. Always for a character's layout. The default: with the setting off (the shared file, as
/// before), or in the world by a client whose context never held a character's windows (one with
/// no character name, which uses the default as before). Not at character select: the default
/// there is this client's copy from when it loaded it, and writing it back could undo another
/// client's /rc layout default; nor with the windows of a character that just logged out. An
/// explicit save (Save Layout Now) writes whatever is in use.
/// </summary>
public static bool MayAutoSaveIni(bool characterLayout, bool perCharacter, bool inWorld, bool contextHeldCharacter) =>
characterLayout || !perCharacter || (inWorld && !contextHeldCharacter);
// ── /rc layout ───────────────────────────────────────────────────────
public const string Usage = "Usage: /rc layout [status] | default | reset [confirm]";
/// <summary>"/rc layout" and its arguments (any case, any spacing).</summary>
public static LayoutCommand ParseCommand(string? args)
{
string a = string.Join(' ', (args ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
return a switch
{
"" or "status" => LayoutCommand.Status,
"default" => LayoutCommand.MakeDefault,
"reset" => LayoutCommand.ResetAsk,
"reset confirm" => LayoutCommand.ResetConfirm,
_ => LayoutCommand.Invalid,
};
}
public static string ReasonText(DefaultReason why) => why switch
{
DefaultReason.SettingOff => "Panel layout per character is off (Settings > Display)",
DefaultReason.NotInWorld => "no character is in the world",
DefaultReason.NoCharacterName => "no character name is known for this client (it wasn't started by the RynthCore launcher)",
DefaultReason.WaitingForName => "still waiting for the character's name",
DefaultReason.NotRunning => "panel layouts aren't running in this client",
_ => "the layout is still switching",
};
/// <summary>/rc layout: the layout in use and its files, and the default's.</summary>
public static string[] StatusLines(LayoutOwner? inUse, LayoutFiles files, DefaultReason why, LayoutFiles defaults, bool perCharacter)
{
if (inUse is not null)
return new[]
{
$"Panel layout: {Describe(inUse)}'s own: {files.PanelState} and {files.ImGuiIni}.",
$"New characters start from the default ({defaults.PanelState} and {defaults.ImGuiIni}): /rc layout default makes this layout that default, /rc layout reset puts this character back to it.",
};
if (why == DefaultReason.NotRunning)
return new[] { $"Can't show the panel layout: {ReasonText(why)} (the engine's panels aren't up)." };
string line = $"Panel layout: the PC-wide default ({ReasonText(why)}): {files.PanelState} and {files.ImGuiIni}.";
return perCharacter
? new[] { line, "Each character gets its own layout, a copy of this default, when it logs in." }
: new[] { line };
}
/// <summary>
/// Settings > Display's line under "Panel Layout Per Character": whose layout is in use and the
/// folder its files are in (a character's), or the PC-wide default and why.
/// </summary>
public static string SettingsLine(LayoutOwner? inUse, LayoutFiles files, DefaultReason why)
{
if (inUse is not null)
return $"In use: {Describe(inUse)}'s own layout ({files.Folder}).";
if (why == DefaultReason.NotRunning)
return "In use: none (" + ReasonText(why) + ").";
return $"In use: the PC-wide default ({ReasonText(why)}): {files.PanelState}.";
}
/// <summary>Settings > Display's reset confirmation: what "Reset this character's layout" will do.</summary>
public static string ResetConfirmText(LayoutOwner? who) =>
who is null
? "No character's own layout is in use, so there is nothing to reset."
: $"Replace {Describe(who)}'s panel layout with the default for new characters?\nOpen panels move to the default's places. This can't be undone.";
/// <summary>Why /rc layout default or reset can't run (null: it can), with the usage.</summary>
public static string? CharacterLayoutProblem(string verb, bool running, bool perCharacter, bool inWorld, LayoutOwner? inUse, bool switching)
{
string why;
if (!running) why = ReasonText(DefaultReason.NotRunning);
else if (!perCharacter) why = ReasonText(DefaultReason.SettingOff);
else if (!inWorld) why = ReasonText(DefaultReason.NotInWorld);
else if (switching) why = "the layout is still switching; try again in a moment";
else if (inUse is null) why = ReasonText(DefaultReason.NoCharacterName);
else return null;
return $"Can't {verb}: {why}. {Usage}";
}
public static string ResetAskReply(LayoutOwner who, LayoutFiles defaults) =>
$"This replaces {Describe(who)}'s panel layout with the default for new characters ({defaults.PanelState}): open panels move to the default's places. To go ahead: /rc layout reset confirm.";
public static string ResetDoneReply(LayoutOwner who) =>
$"{Describe(who)}'s panel layout was reset from the default: the panels are in the default's places now.";
public static string MakeDefaultDoneReply(LayoutOwner who, LayoutFiles defaults) =>
$"{Describe(who)}'s panel layout is now the default for new characters ({defaults.PanelState} and {defaults.ImGuiIni}). Characters that already have a layout keep their own.";
public static string FailedReply(string what, string error) => $"Can't {what}: {error}.";
public const string BusyReply = "Can't: a panel layout change is already waiting; try again in a moment. " + Usage;
}
/// <summary>A switch to start: write out <see cref="From"/> (when it is a character's), seed or reseed
/// <see cref="To"/>'s files, load them. One at a time, in order with the other UI writes.</summary>
internal readonly record struct LayoutSwitch(int Gen, LayoutOwner? From, bool FromKnown, LayoutOwner? To, bool Reseed, long ForLoginMs)
{
/// <summary>The layout switched away from is a character's and is kept (not a reset): its files are written out first.</summary>
public bool FlushFrom => FromKnown && From is not null && !Reseed;
}
/// <summary>
/// One client's layout bookkeeping, render thread only: which layout it should use, when to start a
/// switch, and whether panels may draw. A switch is asked for (Tick), done in the background
/// (PanelLayout: files, then the stores), then applied on the render thread (MarkApplied), one at a time.
/// After a login (or the hot reload that marks one), panels draw only once the character's layout is
/// applied, so they never show first at the default places and then jump.
/// </summary>
internal sealed class PanelLayoutSession
{
private int _gen; // the last switch asked for
private LayoutOwner? _target; // ... and the layout it goes to
private bool _asked; // a switch was asked for at least once
private long _askedAtMs;
private long _askedForLogin; // the login (LoginCompleteAtMs) that switch was decided for; 0 = not in the world
private int _appliedGen;
private LayoutOwner? _applied;
private long _readyForLogin; // the login whose layout is applied; 0 = none
private bool _reseedWanted; // /rc layout reset confirm: the next switch copies the default over the character's files
/// <summary>The layout applied last (null = the default). Meaningful once <see cref="AnyApplied"/>.</summary>
public LayoutOwner? AppliedLayout => _applied;
public bool AnyApplied => _appliedGen > 0;
/// <summary>A switch was asked for and isn't applied yet.</summary>
public bool InFlight => _asked && _appliedGen != _gen;
/// <summary>The layout the client should use, as of the last Tick; meaningful while <see cref="Decided"/>.</summary>
public LayoutOwner? Wanted { get; private set; }
/// <summary>False only in the world while the character's name isn't settled yet.</summary>
public bool Decided { get; private set; }
/// <summary>The next switch reseeds the character's files from the default (a reset).</summary>
public void WantReseed() => _reseedWanted = true;
/// <summary>
/// Once a frame. <paramref name="identityRecorded"/>: the login's identity is recorded
/// (SessionStateRegistry); <paramref name="identity"/> is it (null: no character name).
/// Returns a switch to start, or null.
/// </summary>
public LayoutSwitch? Tick(long nowMs, bool perCharacter, bool inWorld, long loginAtMs, bool identityRecorded, LayoutOwner? identity)
{
if (!inWorld)
{
Decided = true;
Wanted = null;
}
// (A login time of 0 in the world: the flag is set, its time not yet; wait for it.)
else if (loginAtMs != 0 && (identityRecorded || nowMs - loginAtMs >= PanelLayoutPolicy.IdentityWaitMs))
{
Decided = true;
Wanted = PanelLayoutPolicy.Choose(perCharacter, inWorld, identity);
}
else
{
Decided = false;
_reseedWanted = false; // a new login: a reset asked for the old one is dropped
return null; // the name is on its way: no switch, and panels wait (ReadyToDraw)
}
if (InFlight) return null; // one switch at a time; the next Tick after it is applied looks again
long forLogin = inWorld ? loginAtMs : 0;
bool reseed = _reseedWanted && Wanted is not null && Equals(Wanted, _applied);
_reseedWanted = false;
if (_asked && Equals(Wanted, _target) && !reseed)
{
// Already in use (a relogin to the layout the client had, or the default with the setting off).
if (forLogin != 0) _readyForLogin = forLogin;
return null;
}
var sw = new LayoutSwitch(++_gen, _asked ? _target : null, _asked, Wanted, reseed, forLogin);
_target = Wanted;
_asked = true;
_askedAtMs = nowMs;
_askedForLogin = forLogin;
return sw;
}
/// <summary>Switch <paramref name="gen"/> is applied on the render thread (its files are in the stores and the ImGui context).</summary>
public void MarkApplied(int gen)
{
if (gen != _gen || gen == _appliedGen) return;
_appliedGen = gen;
_applied = _target;
if (_askedForLogin != 0) _readyForLogin = _askedForLogin;
}
/// <summary>
/// True when panels may draw: outside the world always (nothing draws there), in the world once the
/// layout decided for this login is applied. A switch stuck past ApplyGiveUpMs stops holding them.
/// </summary>
public bool ReadyToDraw(long nowMs, bool inWorld, long loginAtMs)
{
if (!inWorld) return true;
if (loginAtMs != 0 && _readyForLogin == loginAtMs) return true;
return Decided && InFlight && nowMs - _askedAtMs >= PanelLayoutPolicy.ApplyGiveUpMs;
}
}

View file

@ -18,13 +18,17 @@
// without a barlayout= row gives the toolbar one row, no icon limit.
//
// Stored under %LocalAppData%\RynthCore\panel_state.txt — survives reloads
// and out-of-game (the Runtime dir might be wiped during deploy).
// and out-of-game (the Runtime dir might be wiped during deploy). That is the
// PC-wide default; in the world a client uses its character's own copy,
// layouts\<server>\<character>\panel_state.txt (PanelLayout switches the file
// with SwitchTo). Saves are atomic: a temp file, then a replace.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI;
@ -48,8 +52,10 @@ internal static class PanelStateStore
private static (double Left, double Top)? _barFloatingPosition;
private static int _barRows = BarLayout.DefaultRows, _barMaxPerRow = BarLayout.NoLimit;
private static bool _loaded;
private static string? _path; // the file in use (SwitchTo); null = the PC-wide default
private static string FilePath
/// <summary>The PC-wide default file: %LocalAppData%\RynthCore\panel_state.txt.</summary>
internal static string DefaultPath
{
get
{
@ -58,6 +64,48 @@ internal static class PanelStateStore
}
}
private static string FilePath => _path ?? DefaultPath;
/// <summary>The file in use now (the default, or the character's). Any thread.</summary>
internal static string CurrentPath
{
get { lock (Sync) return FilePath; }
}
/// <summary>
/// Panel layout per character (PanelLayout): from now on the store reads and writes
/// <paramref name="path"/>. With <paramref name="flushCurrent"/> the file in use is written
/// out first (a character's layout being left); the default is never written by a switch.
/// Everything in memory is then replaced by <paramref name="path"/>'s contents (none: an empty
/// layout). The UI writer's thread, in order with the other saves.
/// </summary>
internal static void SwitchTo(string path, bool flushCurrent)
{
lock (Sync)
{
if (flushCurrent && _loaded) Save();
Panels.Clear();
_barPosition = null;
_barFloating = false;
_barFloatingPosition = null;
_barRows = BarLayout.DefaultRows;
_barMaxPerRow = BarLayout.NoLimit;
_path = path;
_loaded = false;
Load();
}
}
/// <summary>The file's text for what is in memory now (/rc layout default writes it as the default). Any thread.</summary>
internal static string Snapshot()
{
lock (Sync)
{
Load();
return Format();
}
}
public static (double Left, double Top)? BarPosition
{
get { lock (Sync) { Load(); return _barPosition; } }
@ -276,34 +324,8 @@ internal static class PanelStateStore
if (!string.IsNullOrEmpty(dir))
Directory.CreateDirectory(dir);
using var sw = new StreamWriter(path, append: false);
sw.WriteLine("# RynthCore Avalonia panel state — auto-generated, hand-edits OK.");
if (_barPosition is { } bar)
{
// Always emit the extended form if we have any floating state to
// remember; legacy 2-column form only when no popout has happened.
if (_barFloating || _barFloatingPosition is not null)
{
(double fl, double ft) = _barFloatingPosition ?? (0, 0);
sw.WriteLine(FormattableString.Invariant(
$"bar={bar.Left:0.##},{bar.Top:0.##},{(_barFloating ? "floating" : "docked")},{fl:0.##},{ft:0.##}"));
}
else
{
sw.WriteLine(FormattableString.Invariant($"bar={bar.Left:0.##},{bar.Top:0.##}"));
}
}
// Only when changed: a file that never had the row reads back the same.
if (_barRows != BarLayout.DefaultRows || _barMaxPerRow != BarLayout.NoLimit)
sw.WriteLine("barlayout=" + BarLayout.Format(_barRows, _barMaxPerRow));
foreach (var kv in Panels)
{
PanelEntry e = kv.Value;
sw.WriteLine(FormattableString.Invariant(
$"panel.{kv.Key}={(e.Open ? "open" : "closed")},{e.Left:0.##},{e.Top:0.##},{e.Width:0.##},{e.Height:0.##},{(e.Floating ? "floating" : "docked")},{e.FloatingLeft:0.##},{e.FloatingTop:0.##}"));
}
// Atomic (temp file, then replace): a client that dies mid-save leaves the old file.
EngineSettingsFile.WriteAtomic(path, new UTF8Encoding(false).GetBytes(Format()));
}
catch (Exception ex)
{
@ -311,6 +333,40 @@ internal static class PanelStateStore
}
}
/// <summary>The file's text for what is in memory (under Sync).</summary>
private static string Format()
{
var sw = new StringBuilder();
sw.AppendLine("# RynthCore Avalonia panel state — auto-generated, hand-edits OK.");
if (_barPosition is { } bar)
{
// Always emit the extended form if we have any floating state to
// remember; legacy 2-column form only when no popout has happened.
if (_barFloating || _barFloatingPosition is not null)
{
(double fl, double ft) = _barFloatingPosition ?? (0, 0);
sw.AppendLine(FormattableString.Invariant(
$"bar={bar.Left:0.##},{bar.Top:0.##},{(_barFloating ? "floating" : "docked")},{fl:0.##},{ft:0.##}"));
}
else
{
sw.AppendLine(FormattableString.Invariant($"bar={bar.Left:0.##},{bar.Top:0.##}"));
}
}
// Only when changed: a file that never had the row reads back the same.
if (_barRows != BarLayout.DefaultRows || _barMaxPerRow != BarLayout.NoLimit)
sw.AppendLine("barlayout=" + BarLayout.Format(_barRows, _barMaxPerRow));
foreach (var kv in Panels)
{
PanelEntry e = kv.Value;
sw.AppendLine(FormattableString.Invariant(
$"panel.{kv.Key}={(e.Open ? "open" : "closed")},{e.Left:0.##},{e.Top:0.##},{e.Width:0.##},{e.Height:0.##},{(e.Floating ? "floating" : "docked")},{e.FloatingLeft:0.##},{e.FloatingTop:0.##}"));
}
return sw.ToString();
}
private static bool TryParseDoubles(string csv, int expected, out double[] values)
{
string[] parts = csv.Split(',');

View file

@ -49,6 +49,16 @@ internal static class RadarSettingsStore
/// <summary>ImGui face: a left-click on a dot selects that object in game.</summary>
public static bool ClickToSelect = true;
/// <summary>ImGui face: the object selected in game gets a ring round its marker (and an edge arrow
/// when it is off the picture). On by default (2026-10-31).</summary>
public static bool HighlightSelected = true;
/// <summary>...and the hover label (name, distance, health) beside it. Off by default: the box covers
/// the radar, and the ring alone says which one is selected (2026-10-31).</summary>
public static bool ShowSelectedLabel = false;
/// <summary>The ring's colour (ARGB): magenta, a hue none of the kinds use by default.</summary>
public const uint DefaultSelectedColor = 0xFFFF2ED9;
public static uint SelectedColor = DefaultSelectedColor;
/// <summary>ImGui face: the World Map's picture drawn behind the radar while you're outdoors (off by default).</summary>
public static bool ShowWorldMap;
/// <summary>How strongly that picture shows (the radar's own Opacity applies on top).</summary>
@ -136,7 +146,12 @@ internal static class RadarSettingsStore
/// <summary>The kind's colour (ARGB); white for a kind this engine doesn't know.</summary>
public static uint KindColor(byte kind) => kind < KindColors.Length ? KindColors[kind] : 0xFFFFFFFF;
public static void ResetKindColors() => Array.Copy(DefaultKindColors, KindColors, KindColors.Length);
/// <summary>Every kind's colour, and the selection ring's, back to the defaults.</summary>
public static void ResetKindColors()
{
Array.Copy(DefaultKindColors, KindColors, KindColors.Length);
SelectedColor = DefaultSelectedColor;
}
/// <summary>Every marker size, name box and text size back to its default (show boxes and colours stay).</summary>
public static void ResetSizes()
@ -204,6 +219,12 @@ internal static class RadarSettingsStore
case "showLifestones": ShowLifestones = val == "1"; break;
case "showGroundItems": ShowGroundItems = val == "1"; break;
case "clickSelect": ClickToSelect = val == "1"; break;
case "selectHighlight": HighlightSelected = val == "1"; break;
case "selectLabel": ShowSelectedLabel = val == "1"; break;
case "selectedColor":
if (uint.TryParse(val, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint sc))
SelectedColor = sc;
break;
case "worldMap": ShowWorldMap = val == "1"; break;
case "worldMapOpacity":
if (float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float wo) && float.IsFinite(wo))
@ -267,6 +288,11 @@ internal static class RadarSettingsStore
sw.WriteLine($"showLifestones={(ShowLifestones ? "1" : "0")}");
sw.WriteLine($"showGroundItems={(ShowGroundItems ? "1" : "0")}");
sw.WriteLine($"clickSelect={(ClickToSelect ? "1" : "0")}");
sw.WriteLine($"selectHighlight={(HighlightSelected ? "1" : "0")}");
sw.WriteLine($"selectLabel={(ShowSelectedLabel ? "1" : "0")}");
// Like the kind colours: only when it differs from the default.
if (SelectedColor != DefaultSelectedColor)
sw.WriteLine(FormattableString.Invariant($"selectedColor={SelectedColor:X8}"));
sw.WriteLine($"worldMap={(ShowWorldMap ? "1" : "0")}");
sw.WriteLine(FormattableString.Invariant($"worldMapOpacity={WorldMapOpacity:0.##}"));
sw.WriteLine(FormattableString.Invariant($"compassSize={CompassSize:0.##}"));

View file

@ -334,6 +334,8 @@ internal static class SettingsPanel
case SettingKind.Spacer:
return Spacer();
case SettingKind.Button:
// A button that asks first is the ImGui panel's only (this panel is being retired).
if (row.Confirm != null) return null;
return ButtonRow(row.Label, row.ButtonText ?? row.Label, () =>
{
// A settings edit is pushed like a typed value; the tab is rebuilt so the

View file

@ -101,7 +101,7 @@ internal static class PluginWindows
string sig = WindowPlan.Signature(w);
if (Live.TryGetValue(title, out Hosted? h) && h.Signature == sig) continue;
SectionWindowDecl decl = w;
Func<IImGuiPanel> face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title, decl.FitHeight, decl.MinWidth);
Func<IImGuiPanel> face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title, decl.FitHeight, decl.MinWidth, decl.DrawScale);
if (takeOvers.Contains(title))
{
// An engine panel's place: its key, saved place and open state stay; nothing to reopen.

View file

@ -1,7 +1,8 @@
// ============================================================================
// RynthCore.Engine - UI/TrackerSettings.cs
// The Tracker panel's background opacity, shared by its ImGui and Avalonia
// faces: %APPDATA%\RynthCore\rynthtracker_settings.json ({"bgAlpha":0-255}).
// The Tracker panel's background opacity and its text-only look, shared by its
// ImGui and Avalonia faces: %APPDATA%\RynthCore\rynthtracker_settings.json
// ({"bgAlpha":0-255,"textOnly":false}).
// Loaded on the engine init worker; saves go through UiBackgroundWriter so
// the ImGui face never writes a file from AC's thread.
// ============================================================================
@ -15,11 +16,14 @@ namespace RynthCore.Engine.UI;
internal static class TrackerSettings
{
private static volatile int _bgAlpha = 0xCC; // ~80%
private static volatile bool _textOnly;
private static volatile bool _loaded;
private static readonly object LoadSync = new();
// RYNTHCORE_TRACKER_SETTINGS: another file (tools\TrackerSettingsTests).
private static string SettingsPath =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthtracker_settings.json");
Environment.GetEnvironmentVariable("RYNTHCORE_TRACKER_SETTINGS") is { Length: > 0 } over ? over
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthtracker_settings.json");
/// <summary>Background alpha 0-255.</summary>
public static byte BgAlpha
@ -31,6 +35,20 @@ internal static class TrackerSettings
}
}
/// <summary>
/// Text only (2026-11-01, the owner: "make the window invisible besides the writing"): docked, the
/// panel has no frame, title or background, only its rows (shadowed), and clicks pass through
/// except over them.
/// </summary>
public static bool TextOnly
{
get
{
EnsureLoaded();
return _textOnly;
}
}
/// <summary>Sets the alpha now; <paramref name="save"/> writes the file in the background.</summary>
public static void SetBgAlpha(byte alpha, bool save)
{
@ -40,6 +58,14 @@ internal static class TrackerSettings
UiBackgroundWriter.Enqueue("tracker settings", Save);
}
/// <summary>Text only on or off, saved in the background.</summary>
public static void SetTextOnly(bool on)
{
EnsureLoaded();
_textOnly = on;
UiBackgroundWriter.Enqueue("tracker settings", Save);
}
public static void EnsureLoaded()
{
if (_loaded) return;
@ -54,6 +80,8 @@ internal static class TrackerSettings
using var doc = JsonDocument.Parse(File.ReadAllText(path));
if (doc.RootElement.TryGetProperty("bgAlpha", out var v))
_bgAlpha = Math.Clamp(v.GetInt32(), 0, 255);
if (doc.RootElement.TryGetProperty("textOnly", out var t) && t.ValueKind is JsonValueKind.True or JsonValueKind.False)
_textOnly = t.GetBoolean();
}
}
catch { }
@ -61,13 +89,17 @@ internal static class TrackerSettings
}
}
/// <summary>The settings file's text.</summary>
internal static string ToJson(int bgAlpha, bool textOnly) =>
$"{{\"bgAlpha\":{bgAlpha},\"textOnly\":{(textOnly ? "true" : "false")}}}";
private static void Save()
{
try
{
string path = SettingsPath;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, $"{{\"bgAlpha\":{_bgAlpha}}}");
File.WriteAllText(path, ToJson(_bgAlpha, _textOnly));
}
catch { }
}