Snapshot for release 2026.10.19.1 (internal fa7a8f6)

This commit is contained in:
Tom Bohar 2026-10-19 09:11:20 -04:00
commit 44074df011
110 changed files with 8017 additions and 291 deletions

View file

@ -157,11 +157,19 @@ internal static class AppraisalHooks
}
}
/// <summary>The object was created again: its data is current, not merely kept.</summary>
public static void MarkLive(uint guid)
/// <summary>
/// The object was created again: its data is current, not merely kept. Except data kept since
/// a release longer ago than ReleasedObjectRetention.StaleAfterMs: the client sent no updates
/// meanwhile, so it is dropped here (the next appraisal refreshes it). Returns true when it was.
/// </summary>
public static bool MarkLive(uint guid, long nowMs)
{
lock (_cacheLock)
_released.Forget(guid);
{
if (!_released.TakeLive(guid, nowMs)) return false;
EvictLocked(guid);
return true;
}
}
/// <summary>Drops the data of objects released longer ago than the retention time. Timer thread.</summary>

View file

@ -7,7 +7,10 @@
//
// Per tick: take the new candidates, the one-shot login sweep, then look at the pending
// list in order (at most MaxEvaluatedPerTick, at most MaxPerTick sends) and decide each
// one with AutoIdPolicy. Waits stay; skips leave; a send leaves only when the main-thread
// one with AutoIdPolicy. When the evaluation budget runs out with items still unlooked-at,
// the ones just evaluated (and kept) move to the back, so the next tick starts where this
// one stopped: with more than MaxEvaluatedPerTick items waiting, a newer item at the end
// is reached in a few ticks instead of never (review fix 2026-10-18). Waits stay; skips leave; a send leaves only when the main-thread
// queue took it (a refusal, in a transition or with the ring full, keeps the entry and
// ends this tick's sending).
//
@ -93,6 +96,7 @@ internal sealed class AutoIdDrain
private int _incomingCount;
private readonly List<Pending> _pending = new(256);
private readonly HashSet<uint> _pendingIds = new();
private readonly List<Pending> _rotateScratch = new(MaxEvaluatedPerTick);
private int _pendingCount;
private long _lastInventorySendMs;
private long _sweptLoginAt;
@ -225,11 +229,14 @@ internal sealed class AutoIdDrain
bool sending = true;
int keep = 0, evaluated = 0;
int keptBeforeBudgetEnd = -1; // evaluated-and-kept items at the front when the budget ran out
for (int i = 0; i < _pending.Count; i++)
{
Pending p = _pending[i];
if (!sending || sent >= MaxPerTick || evaluated >= MaxEvaluatedPerTick)
{
if (keptBeforeBudgetEnd < 0 && sending && sent < MaxPerTick)
keptBeforeBudgetEnd = keep; // only the evaluation budget ended it (not a send limit or a refusal)
_pending[keep++] = p;
continue;
}
@ -293,6 +300,15 @@ internal sealed class AutoIdDrain
}
}
_pending.RemoveRange(keep, _pending.Count - keep);
// Round-robin: [evaluated and kept | not looked at] becomes [not looked at | evaluated and kept].
if (keptBeforeBudgetEnd > 0 && keptBeforeBudgetEnd < _pending.Count)
{
_rotateScratch.Clear();
for (int i = 0; i < keptBeforeBudgetEnd; i++) _rotateScratch.Add(_pending[i]);
_pending.RemoveRange(0, keptBeforeBudgetEnd);
_pending.AddRange(_rotateScratch);
_rotateScratch.Clear();
}
Volatile.Write(ref _pendingCount, _pending.Count);
return sent;
}

View file

@ -164,10 +164,12 @@ internal static class AutoIdService
return;
// Created again: data kept since a client release is current again (and still cached
// if the release was inside ReleasedObjectRetention's time).
AppraisalHooks.MarkLive(objectId);
bool cached = AppraisalHooks.HasAppraisalData(objectId);
// if the release was inside ReleasedObjectRetention's time), unless it was kept so long
// that it may be out of date (StaleAfterMs): then it is dropped and the object, uncached,
// is a candidate again.
long now = Environment.TickCount64;
AppraisalHooks.MarkLive(objectId, now);
bool cached = AppraisalHooks.HasAppraisalData(objectId);
AutoIdEligibility.CreateDecision decision;
lock (_gate)
decision = _eligibility.OnCreate(objectId, now, cached);

View file

@ -179,6 +179,10 @@ internal static class HeartbeatLogger
}
// Safety net for the main-thread message box count (MainThreadFreeze).
MessageBoxHooks.ReconcileStaleMainThreadCount();
// gateov=N = the world-transition gate's safety valve has opened N times (a death/portal
// that outlasted WorldTransitionState.MaxHoldMs); omitted while 0.
try { int gov = PlayerLifecycleLog.GateOverrides; if (gov > 0) vaField += $" gateov={gov}"; }
catch { }
// pump=paused = plugin ticks paused because AC's main thread is frozen
// (MainThreadFreeze); omitted while running.
try { if (MainThreadFreeze.Paused) vaField += $" pump=paused stall={MainThreadFreeze.MainThreadStallMs}ms"; }

View file

@ -31,6 +31,8 @@ internal static class PlayerLifecycleLog
private static readonly WorldTransitionState _state = new();
private static long _settleUntil; // published copy for other threads
private static volatile bool _portaling, _dead;
private static volatile bool _gateOpen; // the valve opened, or engine.json TransitionGate is off
private static int _gateOverrides;
private static long _portalEnteredAt, _diedAt;
/// <summary>
@ -39,7 +41,13 @@ internal static class PlayerLifecycleLog
/// (BusyCountHooks' force-clear). As of the last game tick; any thread.
/// </summary>
public static bool InWorldTransition =>
_dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _settleUntil);
!_gateOpen && (_dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _settleUntil));
/// <summary>
/// Times the transition gate's safety valve opened (a transition held more than
/// WorldTransitionState.MaxHoldMs without a break), for the heartbeat (gateov=N).
/// </summary>
public static int GateOverrides => Volatile.Read(ref _gateOverrides);
/// <summary>
/// When the last settle window ends (TickCount64; 0 = no transition yet), as of the last
@ -92,13 +100,25 @@ internal static class PlayerLifecycleLog
uint landblock = cell >> 16;
long now = Environment.TickCount64;
bool gateSetting = true;
try { gateSetting = Plugins.EngineSettings.TransitionGate; } catch { }
_state.Enabled = gateSetting;
WorldTransitionState.Edge edges = _state.Sample(now, dead, portaling, landblock);
_dead = _state.Dead;
_portaling = _state.Portaling;
Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs);
PublishGate();
if (edges == WorldTransitionState.Edge.None)
return;
if ((edges & WorldTransitionState.Edge.GateOverride) != 0)
{
Interlocked.Exchange(ref _gateOverrides, _state.Overrides);
RynthLog.Warn($"[Lifecycle] world-transition gate OPENED by its safety valve after {_state.HeldForMs(now) / 1000} s held without a break " +
$"(dead={_state.Dead}, portaling={_state.Portaling}, health {health}/{maxHealth}, landblock 0x{landblock:X4}); queued game actions run again. " +
"A character that reads dead after a revive, or a stuck portal flag, would otherwise freeze every bot. " +
$"Open #{_state.Overrides} this session; engine.json TransitionGate=false turns the gate off.");
}
if ((edges & WorldTransitionState.Edge.Died) != 0)
{
_diedAt = now;
@ -126,11 +146,19 @@ internal static class PlayerLifecycleLog
{
long now = Environment.TickCount64;
bool started = _state.OnTeleportMessage(now);
Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs);
PublishGate();
if (started)
RynthLog.Info($"[Lifecycle] PlayerTeleport (0xF751) received in landblock 0x{_state.Landblock:X4}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s.");
}
// Published for other threads: with the gate open (valve or setting off) the settle window reads as
// none, so InWorldTransition and AutoId's post-transition defer let go too.
private static void PublishGate()
{
_gateOpen = !_state.Enabled || _state.Overridden;
Interlocked.Exchange(ref _settleUntil, _gateOpen ? 0 : _state.SettleUntilMs);
}
private static string Ago(long since, long now) =>
since == 0 ? "?" : $"{(now - since) / 1000.0:0.0}s";
}

View file

@ -208,6 +208,40 @@ internal static class ProcessExitHooks
// never reaches the last-chance filter). Which codes count: CrashExitRule.
private static bool IsCrashExit(uint code) => CrashExitRule.IsCrashExit(code);
// Review fix (2026-10-18): the managed dump this file used to write on TerminateProcess /
// NtTerminateProcess (f9c62ed, for Lucy's Town) was removed above on the grounds that
// createdump covers it. It covers only the paths the CLR itself ends: an AV that unwinds
// through one of our managed detours, or reaches the CLR's unhandled-exception filter (both
// checked offline with a small CoreCLR host: createdump runs). It does NOT cover a native AV
// that AC's own handler catches and answers with TerminateProcess: no CLR frame, no CLR
// filter, and nothing else here writes a dump. So the dump is back on that path, with what
// made the old one risky taken out:
// - after the native log flush, so the crash log is on disk whatever happens next;
// - on its own thread with a bounded wait (CrashDumpWaitMs): if the dying process is stuck
// on a lock, the exit goes ahead after that, never hangs; a 0-byte file is deleted by
// the next client's log housekeeping;
// - once per process, and not at all when createdump already wrote clr_<pid>_*.dmp;
// - small type only (CrashDump.WriteSelfDump), which also needs free space
// (DumpBudget.SmallDumpMinFree), and only the newest few are kept.
private static int _crashDumped;
private const int CrashDumpWaitMs = 20_000;
private static void DumpCrashOnce(string via, uint code)
{
if (Interlocked.Exchange(ref _crashDumped, 1) != 0) return;
try
{
var worker = new Thread(() =>
{
try { CrashDump.WriteCrashDumpOnce(via, code); }
catch { }
}) { IsBackground = true, Name = "RynthCore.CrashDump" };
worker.Start();
worker.Join(CrashDumpWaitMs);
}
catch { /* never block or break the exit */ }
}
private static bool TerminateProcessDetour(IntPtr hProcess, uint exitCode)
{
// Only log when terminating ourselves: TerminateProcess on other process handles is a
@ -215,7 +249,11 @@ internal static class ProcessExitHooks
bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle();
if (selfKill)
{
if (IsCrashExit(exitCode)) SehTrampoline.FlushCrashLog(exitCode);
if (IsCrashExit(exitCode))
{
SehTrampoline.FlushCrashLog(exitCode);
DumpCrashOnce("TerminateProcess", exitCode);
}
else LogTermination("TerminateProcess", hProcess, exitCode);
}
try { return _terminateOriginal!(hProcess, exitCode); }
@ -246,7 +284,11 @@ internal static class ProcessExitHooks
if (selfKill)
{
// A second flush (TerminateProcess calls this) writes nothing: records are written once.
if (IsCrashExit(exitStatus)) SehTrampoline.FlushCrashLog(exitStatus);
if (IsCrashExit(exitStatus))
{
SehTrampoline.FlushCrashLog(exitStatus);
DumpCrashOnce("NtTerminateProcess", exitStatus);
}
else LogTermination("NtTerminateProcess", processHandle, exitStatus);
}
try { return _ntTermOriginal!(processHandle, exitStatus); }

View file

@ -11,7 +11,10 @@
// - when RetainMs has passed (Expire, from AutoIdService's timer);
// - when the SERVER deleted the object (0xF747; AppraisalHooks.EvictObject);
// - at a session clear (logout), and under AppraisalHooks' object cap.
// A re-create (OnLive) makes the object current again.
// A re-create (TakeLive) makes the object current again, but data kept for StaleAfterMs or
// longer is dropped then (review fix 2026-10-18): the client sent no updates for an object it
// had released, so a stack count or a structure kept that long may be minutes old. A re-create
// after a short absence (walking out of and back into view) still finds its data.
//
// Pure bookkeeping (released ids and when); no locking (AppraisalHooks holds its lock).
// Compiled into tools\EngineRobustnessTests.
@ -26,6 +29,9 @@ internal sealed class ReleasedObjectRetention
public const long DefaultRetainMs = 10L * 60 * 1000;
public const int DefaultMaxReleased = 4096;
/// <summary>A re-create this long after the release no longer trusts the kept data.</summary>
public const long StaleAfterMs = 2L * 60 * 1000;
private readonly Dictionary<uint, long> _releasedAt;
private readonly long _retainMs;
private readonly int _max;
@ -56,6 +62,17 @@ internal sealed class ReleasedObjectRetention
/// <summary>The object is current again (re-created), or its data was dropped for another reason.</summary>
public void Forget(uint id) => _releasedAt.Remove(id);
/// <summary>
/// The object was created again. Returns true when it had been released for
/// <paramref name="staleAfterMs"/> or longer (its kept data may be out of date: drop it);
/// false when it was not released, or only briefly. Either way it is current again.
/// </summary>
public bool TakeLive(uint id, long nowMs, long staleAfterMs = StaleAfterMs)
{
if (!_releasedAt.Remove(id, out long at)) return false;
return nowMs - at >= staleAfterMs;
}
public bool IsReleased(uint id) => _releasedAt.ContainsKey(id);
/// <summary>Released ids whose data has outlived RetainMs: removed here and added to <paramref name="expired"/>.</summary>

View file

@ -398,24 +398,47 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc skills [show|hide|toggle] : the ImGui Skills panel; /rc progression opens it on its
// Progression tab (ILT worlds; the tab shows once RynthILT reports ILT features).
if (IsVerb(sub, "skills", out string skillsArgs))
// /rc oracle-skills <skills|attrs|progress|off> : RynthOracle says which SkillsFace body to embed
// in its window (engine bridge; Silentkelpie's design). Any valid form also tells the engine that
// Oracle has the tabs, which hides the standalone Skills bar icon and routes /rc skills there.
if (IsVerb(sub, "oracle-skills", out string oracleSkillsArgs))
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SkillsFace.Title))
Reply("The Skills panel isn't available (the ImGui layer is off?).");
else if (!TryPanelMode(skillsArgs, out bool? show))
Reply("Usage: /rc skills [show|hide|toggle]");
string a = oracleSkillsArgs.Trim().ToLowerInvariant();
int tab = a switch
{
"off" or "clear" or "none" or "-1" => -1,
"0" or "skills" or "skill" => 0,
"1" or "attrs" or "attributes" or "vitals" => 1,
"2" or "progress" or "progression" => 2,
_ => -2,
};
if (tab == -2)
Reply("Usage: /rc oracle-skills <skills|attrs|progress|off>");
else
SetPanelOpen(ImGuiBackend.Panels.SkillsFace.Title, show);
{
ImGuiBackend.Panels.OracleSkillsEmbed.Announce();
if (tab < 0) ImGuiBackend.Panels.OracleSkillsEmbed.Clear();
else ImGuiBackend.Panels.OracleSkillsEmbed.SetActiveTab(tab);
}
return true;
}
if (sub.Equals("progression", StringComparison.OrdinalIgnoreCase))
// /rc skills [show|hide|toggle] : RynthOracle's Skills tab when Oracle provides it (see
// SkillsRouting), else the standalone ImGui Skills panel. /rc progression (or progress) opens the
// Progress tab / the panel's Progression tab (ILT worlds; it shows once RynthILT reports ILT features).
if (IsVerb(sub, "skills", out string skillsArgs))
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SkillsFace.Title))
if (!TryPanelMode(skillsArgs, out bool? show))
Reply("Usage: /rc skills [show|hide|toggle]");
else if (!ImGuiBackend.Panels.SkillsRouting.SetOpen(show))
Reply("The Skills panel isn't available (the ImGui layer is off?).");
return true;
}
if (sub.Equals("progression", StringComparison.OrdinalIgnoreCase)
|| sub.Equals("progress", StringComparison.OrdinalIgnoreCase))
{
if (!ImGuiBackend.Panels.SkillsRouting.Open(2))
Reply("The Skills panel isn't available (the ImGui layer is off?).");
else
ImGuiBackend.Panels.SkillsFace.ShowProgression();
return true;
}

View file

@ -25,6 +25,14 @@
// fight, AC streams the neighbour in without tearing the player's world down, and a 5 s
// hold there would stall every border fight.
//
// Safety valve (2026-10-18 review): the gate holds everything, with no way out but the
// transition ending. Dead is "MaxHealth > 0 && Health == 0" and the portal flag is AC's own;
// if a revived character kept reading Health 0, or the flag stuck, every bot would freeze
// silently. So a transition that has held CONTINUOUSLY for MaxHoldMs opens the gate by
// itself (Overridden: counted in Overrides, announced once through Edge.GateOverride) and
// stays open until the raw transition ends. Enabled = false (engine.json TransitionGate)
// turns the gate off altogether.
//
// Pure: AC main thread only (single writer and reader: the UseTime sample and both
// main-thread drains). Compiled into tools\EngineRobustnessTests.
// ============================================================================
@ -37,6 +45,12 @@ internal sealed class WorldTransitionState
{
public const long SettleMs = 5_000;
/// <summary>
/// A transition held this long without a break opens the gate. A real death + portal +
/// settle is well under 30 s (a slow portal load or a very long death screen included).
/// </summary>
public const long MaxHoldMs = 120_000;
[Flags]
public enum Edge
{
@ -46,6 +60,8 @@ internal sealed class WorldTransitionState
PortalEntered = 4,
PortalExited = 8,
LandblockJump = 16,
/// <summary>The valve opened: the transition outlasted <see cref="MaxHoldMs"/>.</summary>
GateOverride = 32,
}
private bool _init;
@ -58,8 +74,46 @@ internal sealed class WorldTransitionState
/// <summary>Last time a gate check saw the transition (0 = never).</summary>
public long LastBlockedMs { get; private set; }
/// <summary>False = the gate is off (engine.json TransitionGate): nothing is ever held.</summary>
public bool Enabled { get; set; } = true;
/// <summary>The valve is open: the current transition outlasted <see cref="MaxHoldMs"/>.</summary>
public bool Overridden { get; private set; }
/// <summary>Times the valve has opened, over the life of this state.</summary>
public int Overrides { get; private set; }
/// <summary>How long the current transition has been held, as of the last sample (0 = none).</summary>
public long HeldForMs(long nowMs) => _heldSinceMs == 0 ? 0 : nowMs - _heldSinceMs;
private long _heldSinceMs;
/// <summary>Dead, portaling, or inside the settle window, whatever the valve and the setting say.</summary>
public bool RawInTransition(long nowMs) => Dead || Portaling || nowMs < SettleUntilMs;
/// <summary>One game-tick sample. Returns the edges crossed (for the lifecycle log).</summary>
public Edge Sample(long nowMs, bool dead, bool portaling, uint landblock)
{
Edge edges = SampleCore(nowMs, dead, portaling, landblock);
if (!RawInTransition(nowMs))
{
_heldSinceMs = 0;
Overridden = false;
}
else if (_heldSinceMs == 0)
{
_heldSinceMs = nowMs;
}
else if (!Overridden && nowMs - _heldSinceMs >= MaxHoldMs)
{
Overridden = true;
Overrides++;
edges |= Edge.GateOverride;
}
return edges;
}
private Edge SampleCore(long nowMs, bool dead, bool portaling, uint landblock)
{
if (!_init)
{
@ -115,8 +169,11 @@ internal sealed class WorldTransitionState
return Math.Abs(dx) > 1 || Math.Abs(dy) > 1;
}
/// <summary>Dead, portaling, or inside the settle window.</summary>
public bool InTransition(long nowMs) => Dead || Portaling || nowMs < SettleUntilMs;
/// <summary>
/// Dead, portaling, or inside the settle window, and the gate is on and its valve has not
/// opened: the answer every drain and every "is it safe to poke AC" check wants.
/// </summary>
public bool InTransition(long nowMs) => Enabled && !Overridden && RawInTransition(nowMs);
public enum Verdict { Run, Hold, Drop }

View file

@ -36,6 +36,9 @@ internal static class CrashDump
IntPtr userStreamParam,
IntPtr callbackParam);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool GetDiskFreeSpaceExW(string directory, out ulong freeAvailable, out ulong total, out ulong totalFree);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
@ -73,6 +76,14 @@ internal static class CrashDump
string dir = Path.Combine(LogPaths.LogDirectory, "dumps");
Directory.CreateDirectory(dir);
// The small dump is tens of MB; with the volume nearly full it would only fail halfway.
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 stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{stamp}.dmp");
return WriteDumpFile(dumpPath, DumpTypePreferred, DumpTypeFallback, reason);
@ -84,6 +95,45 @@ internal static class CrashDump
}
}
/// <summary>Free bytes available to this user on the volume holding <paramref name="dir"/>; -1 when unknown.</summary>
internal static long FreeBytes(string dir)
{
try
{
if (GetDiskFreeSpaceExW(dir, out ulong avail, out _, out _))
return avail > long.MaxValue ? long.MaxValue : (long)avail;
}
catch { }
return -1;
}
/// <summary>Crash dumps (<c>crash_&lt;pid&gt;_*.dmp</c>) kept in Logs\dumps.</summary>
internal const int CrashDumpsKept = 5;
/// <summary>
/// On a crash exit (ProcessExitHooks): one small dump of this process unless CoreCLR's
/// createdump already wrote <c>clr_&lt;pid&gt;_*.dmp</c> for it. Never throws.
/// </summary>
internal static void WriteCrashDumpOnce(string via, uint code)
{
try
{
string dir = Path.Combine(LogPaths.LogDirectory, "dumps");
try
{
if (Directory.Exists(dir) && Directory.GetFiles(dir, $"clr_{Environment.ProcessId}_*.dmp").Length > 0)
return; // the CLR's own crash dump is there: a second one adds nothing
}
catch { }
if (WriteSelfDump($"{via} 0x{code:X8}", out string path, "crash"))
{
RynthLog.Info($"ProcessExit: crash dump written {path} ({via} 0x{code:X8})");
PruneDumps(dir, "crash_", CrashDumpsKept);
}
}
catch { }
}
// Writes one dump to <paramref name="path"/>. On ERROR_INVALID_PARAMETER (87: AC's ancient
// dbghelp 6.1 rejected a flag) retries with <paramref name="fallbackType"/>. Never leaves a
// 0-byte or partial .dmp behind (it reads as a crash marker during triage; observed:
@ -216,6 +266,12 @@ internal static class CrashDump
Directory.CreateDirectory(dir);
string path = Path.Combine(dir, $"{OutOfMemoryDumpPrefix}{Environment.ProcessId}_{DateTime.Now:yyyyMMdd_HHmmss}.dmp");
if (!ReserveFullDump(dir, path, out string refusal))
{
RynthLog.Error($"CrashDump: OUT OF MEMORY full-memory dump skipped ({refusal}); writing the small dump instead.");
WriteSelfDump(reason, out _, "oom-small");
return;
}
if (WriteDumpFile(path, DumpTypeFull, DumpTypeFullFallback, reason))
{
_fullDumpWrittenPath = path;
@ -235,6 +291,96 @@ internal static class CrashDump
}
}
// Every client runs this check-then-create under one machine-wide (per logon session) mutex,
// and the empty placeholder it creates counts against the next client's check, so clients that
// hit OUT OF MEMORY together cannot all pass the check before any of them has started writing.
private const string FullDumpGateName = @"Local\RynthCore.FullDumpGate";
private const int FullDumpGateWaitMs = 10_000;
/// <summary>
/// Whether a full dump may be written to <paramref name="path"/> now (<see cref="DumpBudget"/>:
/// free space on the volume, and the number and bytes of full dumps already in the folder from
/// ALL clients). On a refusal it first prunes the folder down to
/// <c>OutOfMemoryDumpsKept - 1</c> (dumps of dead clients and our own older ones) and asks again.
/// On success an empty placeholder exists at <paramref name="path"/>.
/// </summary>
private static bool ReserveFullDump(string dir, string path, out string refusal)
{
refusal = string.Empty;
Mutex? gate = null;
bool held = false;
try
{
try
{
gate = new Mutex(false, FullDumpGateName);
held = gate.WaitOne(FullDumpGateWaitMs);
}
catch (AbandonedMutexException) { held = true; } // a client died holding it: ours now
catch { /* no mutex available: decide without it */ }
long estimate = DumpBudget.EstimateFullDumpBytes(PrivateBytes());
DumpVerdict verdict = EvaluateFolder(dir, estimate, out long free, out int count, out long bytes);
if (verdict != DumpVerdict.Full)
{
// Older dumps are the thing most likely to be in the way: make room for this one.
PruneDumps(dir, OutOfMemoryDumpPrefix, Math.Max(0, OutOfMemoryDumpsKept - 1));
verdict = EvaluateFolder(dir, estimate, out free, out count, out bytes);
}
if (verdict != DumpVerdict.Full)
{
refusal = $"{verdict}: {(free < 0 ? "free space unknown" : (free / (1024 * 1024)) + " MB free")}, dump needs ~{estimate / (1024 * 1024)} MB, " +
$"{count} full dump(s) / {bytes / (1024 * 1024)} MB already in {dir}";
return false;
}
try
{
using (new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite)) { }
}
catch (Exception ex)
{
refusal = $"cannot create {path}: {ex.GetType().Name}";
return false;
}
return true;
}
finally
{
if (gate != null)
{
if (held) { try { gate.ReleaseMutex(); } catch { } }
gate.Dispose();
}
}
}
private static DumpVerdict EvaluateFolder(string dir, long estimate, out long free, out int count, out long bytes)
{
free = FreeBytes(dir);
count = 0;
bytes = 0;
try
{
foreach (FileInfo f in new DirectoryInfo(dir).GetFiles(OutOfMemoryDumpPrefix + "*.dmp"))
{
count++;
try { bytes += f.Length; } catch { }
}
}
catch { }
return DumpBudget.Evaluate(free, estimate, count, bytes);
}
private static long PrivateBytes()
{
try
{
using var p = System.Diagnostics.Process.GetCurrentProcess();
return p.PrivateMemorySize64;
}
catch { return 0; }
}
/// <summary>
/// Deletes all but the newest <paramref name="keep"/> <paramref name="prefix"/>*.dmp files in
/// <paramref name="dir"/>. The folder is shared by every client: a dump whose name carries

View file

@ -0,0 +1,62 @@
using System;
namespace RynthCore.Engine;
/// <summary>
/// Whether a full-memory dump may be written now. Pure arithmetic (the disk and folder are read
/// by <see cref="CrashDump"/>), so tools\EngineRobustnessTests runs it directly.
///
/// A full dump is about the size of the process (a 32-bit client: up to ~4 GB), the client is
/// frozen while it is written, and every client that hits the OUT OF MEMORY box at once writes
/// one. So: the volume must keep a margin free afterwards, and the dumps already in the folder
/// (all clients, live or not) are capped in number and in bytes. When the verdict is not
/// <see cref="DumpVerdict.Full"/> the caller writes the small dump instead.
/// </summary>
internal enum DumpVerdict
{
Full = 0,
/// <summary>Free space unknown, or less than the dump plus <see cref="DumpBudget.MinFreeAfterFullDump"/>.</summary>
LowDisk,
/// <summary><see cref="DumpBudget.MaxFullDumpsAllPids"/> or more full dumps are already in the folder.</summary>
TooManyDumps,
/// <summary>The full dumps in the folder plus this one would pass <see cref="DumpBudget.MaxFullDumpBytesAllPids"/>.</summary>
TooManyBytes,
}
internal static class DumpBudget
{
/// <summary>Free space that must remain on the volume after a full dump.</summary>
internal const long MinFreeAfterFullDump = 2L * 1024 * 1024 * 1024;
/// <summary>Full dumps in the folder, all clients together, before another is refused.</summary>
internal const int MaxFullDumpsAllPids = 4;
/// <summary>Bytes of full dumps in the folder, all clients together, including the one about to be written.</summary>
internal const long MaxFullDumpBytesAllPids = 14L * 1024 * 1024 * 1024;
/// <summary>A full dump holds the private memory plus the mapped images and the dump's own tables.</summary>
internal const long FullDumpOverheadBytes = 512L * 1024 * 1024;
/// <summary>The small (Normal + handle data) dump is tens of MB; it still needs some room.</summary>
internal const long SmallDumpMinFree = 200L * 1024 * 1024;
/// <summary>Largest a 32-bit client can be; the estimate when the process size cannot be read.</summary>
internal const long FallbackProcessBytes = 4L * 1024 * 1024 * 1024;
internal static long EstimateFullDumpBytes(long privateBytes)
=> (privateBytes > 0 ? privateBytes : FallbackProcessBytes) + FullDumpOverheadBytes;
/// <param name="freeBytes">Free bytes available to this user on the dump volume; negative = unknown.</param>
/// <param name="estimateBytes">The size this dump is expected to have.</param>
/// <param name="existingCount">Full dumps already in the folder (any client, any state).</param>
/// <param name="existingBytes">Their combined size.</param>
internal static DumpVerdict Evaluate(long freeBytes, long estimateBytes, int existingCount, long existingBytes)
{
if (freeBytes < 0 || freeBytes - estimateBytes < MinFreeAfterFullDump) return DumpVerdict.LowDisk;
if (existingCount >= MaxFullDumpsAllPids) return DumpVerdict.TooManyDumps;
if (existingBytes + estimateBytes > MaxFullDumpBytesAllPids) return DumpVerdict.TooManyBytes;
return DumpVerdict.Full;
}
internal static bool SmallDumpAllowed(long freeBytes) => freeBytes >= SmallDumpMinFree;
}

View file

@ -165,16 +165,98 @@ public static class EntryPoint
private const long ManualReloadWindowMs = 10_000;
internal static void NoteManualReload() => Interlocked.Exchange(ref _manualReloadAtMs, Environment.TickCount64);
/// <summary>True when ERl / the bar RL / /rc rl / the hotkey marked a hand reload within the window
/// (does not clear the mark).</summary>
private static bool IsRecentManualReload()
{
long manualAt = Volatile.Read(ref _manualReloadAtMs);
return manualAt != 0 && Environment.TickCount64 - manualAt < ManualReloadWindowMs;
}
/// <summary>
/// In the world after a successful login, and not yet logged out: with
/// engine.json HoldReloadInWorld on, an automatic reload waits. Character select /
/// disconnected / never logged in are safe to reload. (From SilentKelpie's PR 6.)
/// </summary>
private static bool IsInWorldForAutoReloadDeferral()
{
try
{
if (!Compatibility.LoginLifecycleHooks.HasObservedLoginComplete) return false;
if (Compatibility.LogoutLifecycleHooks.HasObservedLogout) return false;
int mode = Compatibility.UiFlowHooks.CurrentMode;
// Explicit non-world screens: safe for an automatic reload.
if (mode == Compatibility.UiFlowHooks.ModeCharacterManagement
|| mode == Compatibility.UiFlowHooks.ModeDisconnected
|| mode == Compatibility.UiFlowHooks.ModeIntro
|| mode == Compatibility.UiFlowHooks.ModeCharGen
|| mode == Compatibility.UiFlowHooks.ModeCredits
|| mode == Compatibility.UiFlowHooks.ModeDataPatch
|| mode == Compatibility.UiFlowHooks.ModeEpilogue)
return false;
// ModeGamePlay, or ModeNone before the first mode sample after login: hold.
return true;
}
catch { return false; }
}
/// <summary>
/// The opt-in in-world hold (engine.json HoldReloadInWorld, default off; ReloadInWorldGate). Only
/// called with the setting on. Waits, with the game running on this engine, while the player is in
/// the world and the reload is an automatic one, for at most HoldReloadInWorldMaxMinutes; a hand
/// reload that arrives meanwhile (ERl, RL, /rc rl, hotkey) or switching the setting off ends the
/// wait. Returns true when a hand reload ended it, so the caller skips the plugin deferral too.
/// Never throws; any failure fails open to "reload now".
/// </summary>
private static bool HoldReloadWhileInWorld()
{
try
{
var maxWait = TimeSpan.FromMinutes(ReloadInWorldGate.ClampMaxMinutes(EngineSettings.HoldReloadInWorldMaxMinutes));
ReloadInWorldGate.Outcome outcome = ReloadInWorldGate.Run(
// Re-read each poll: a hand reload or the setting turned off in the meantime ends the hold.
stillHold: () => ReloadInWorldGate.ShouldHold(IsRecentManualReload(), EngineSettings.HoldReloadInWorld, IsInWorldForAutoReloadDeferral()),
log: msg => RynthLog.Info(msg),
notify: why => Compatibility.AcMainThreadQueue.EnqueueWriteToChat(
$"[RynthCore] A new RynthCore build is ready. It loads when you leave the world ({why}; at most {maxWait.TotalMinutes:0.#} minutes).", 1),
maxWait: maxWait,
waited: out TimeSpan waited);
if (outcome != ReloadInWorldGate.Outcome.Clear)
RynthLog.Info($"engine reload: in-world hold {outcome} after {waited.TotalSeconds:0.0} s.");
}
catch (Exception ex)
{
RynthLog.Warn($"engine reload: in-world hold failed ({ex.GetType().Name}: {ex.Message}); reloading now.");
}
// A hand reload that came in during the wait set the mark again: it counts as by hand.
return IsRecentManualReload();
}
/// <summary>
/// Reload deferral (2026-10-05, see ReloadDeferral.cs): asks the plugins
/// (RynthPluginReloadBlocker) and waits up to ReloadDeferral.DefaultCap while one objects,
/// e.g. "engine reload waiting: RynthAi in combat (a monster engaged, ...)". Says so in chat
/// once. Never throws; a query that fails counts as "nothing objects".
/// With engine.json HoldReloadInWorld on (default off), an automatic reload first waits until
/// the player leaves the world (HoldReloadWhileInWorld); a hand reload is never held.
/// </summary>
private static void DeferReloadWhilePluginsObject()
{
long manualAt = Interlocked.Exchange(ref _manualReloadAtMs, 0);
if (manualAt != 0 && Environment.TickCount64 - manualAt < ManualReloadWindowMs)
bool byHand = manualAt != 0 && Environment.TickCount64 - manualAt < ManualReloadWindowMs;
bool hold = false;
try { hold = EngineSettings.HoldReloadInWorld; } catch { } // opt-in, default off: any failure = no hold
if (hold && ReloadInWorldGate.ShouldHold(byHand, hold, IsInWorldForAutoReloadDeferral()))
{
if (HoldReloadWhileInWorld())
{
Interlocked.Exchange(ref _manualReloadAtMs, 0);
byHand = true;
}
}
if (byHand)
{
RynthLog.Info("engine reload: asked for by hand (ERl), so it isn't deferred for the plugins.");
return;
@ -702,7 +784,12 @@ public static class EntryPoint
// a module-resolved stack sweep for the AV (0xC0000005) / fail-fast
// (0xC0000602) classes that bypass managed handlers, into a dedicated
// native-crash.log so the next crash self-reports instead of going dark.
SehTrampoline.InstallCrashLogger(System.IO.Path.Combine(LogPaths.LogDirectory, "native-crash.log"));
// The shared file has one fixed name, so no per-PID rotation covers it: move a big one
// aside on the first generation, before the native side opens it. (Later generations
// keep the handle the first one opened, so rotating then would only be ignored.)
if (_initCount <= 1 && LogPaths.RotateNativeCrashLogAtStartup())
RynthLog.Compat("native-crash.log was over 1 MB at startup: moved to native-crash.log.old");
SehTrampoline.InstallCrashLogger(System.IO.Path.Combine(LogPaths.LogDirectory, LogPaths.NativeCrashLogName));
}
if (!ConfigureImGuiNativeLibrary(engineDir))

View file

@ -278,6 +278,11 @@ internal static class EngineFrameController
// in ImGui-off mode so Avalonia owner-window binding works.
EnsureCore(pDevice);
// Settings > Display: borderless windowed + AC window placement. Throttled; reads only
// here - the window itself is changed from the game WndProc (AcWindowChrome).
try { UI.AcWindowChrome.Tick(_gameHwnd); }
catch (Exception ex) { RynthLog.UI($"AcWindowChrome.Tick threw {ex.GetType().Name}: {ex.Message}"); }
// 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.

View file

@ -67,10 +67,18 @@ internal static class ImGuiBar
ScriptWindow? Window = null);
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
// Item Count has no icon of its own since 2026-10-18: Inventory's Count button, /rc itemcount, the Character menu.
// Skills moves under RynthOracle (Skills / Attributes / Progress tabs): its icon shows only while Oracle's
// tabs can't be reached (SkillsRouting.ShowSkillsBarIcon), so nobody loses the way in. Mini Remote stays.
private static readonly string[] ImGuiOnlyBarPanels =
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title,
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.MiniRemoteFace.Title,
Panels.CharactersFace.Title };
/// <summary>An ImGui-only panel's bar button is wanted: it has a face, and Skills only while Oracle can't host it.</summary>
private static bool ImGuiOnlyWanted(string title) =>
ImGuiPanelHost.HasFace(title)
&& (title != Panels.SkillsFace.Title || Panels.SkillsRouting.ShowSkillsBarIcon);
// The ILT section: ImGui-only Infinite Leaftide panels (Bounties and Guardian, both RynthILT's).
// They never get buttons of their own; one ILT button stands for them, shown only on Infinite
// Leaftide (IltInfo.IsIlt) with RynthILT loaded (IltInfo.PluginLoaded), and only for the ones
@ -726,12 +734,12 @@ internal static class ImGuiBar
ImGuiNET.ImGui.PopStyleVar(3);
}
/// <summary>Bit i set: ImGuiOnlyBarPanels[i] has a face now.</summary>
/// <summary>Bit i set: ImGuiOnlyBarPanels[i] gets a button now (a face, and for Skills no Oracle tabs).</summary>
private static int ImGuiOnlyMask()
{
int mask = 0;
for (int i = 0; i < ImGuiOnlyBarPanels.Length; i++)
if (ImGuiPanelHost.HasFace(ImGuiOnlyBarPanels[i])) mask |= 1 << i;
if (ImGuiOnlyWanted(ImGuiOnlyBarPanels[i])) mask |= 1 << i;
return mask;
}
@ -755,7 +763,7 @@ internal static class ImGuiBar
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));
}
foreach (string title in ImGuiOnlyBarPanels)
if (ImGuiPanelHost.HasFace(title) && !LauncherOnly.Contains(title))
if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title))
{
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));

View file

@ -459,6 +459,7 @@ internal static class ImGuiPanelHost
Apply(req.Title, req.Kind, placeScale);
RemoveUnregistered();
SweepEmbedded();
Panels.OracleSkillsEmbed.Sweep(Environment.TickCount64); // Oracle's Skills embed that stopped drawing
List<Entry> order;
lock (Sync) order = DrawOrder;
@ -512,6 +513,8 @@ internal static class ImGuiPanelHost
{
if (_restored) return;
_restored = true;
// Settings > Display "Remember Open Windows and Positions" (default on).
if (!Plugins.EngineSettings.RememberWindowLayout) return;
List<string> titles = new();
// Script windows (dynamic) open when their owner says so, not from the saved state.
lock (Sync)

View file

@ -16,7 +16,9 @@
// so copy is mouse-driven). Right-click a line to copy it or to make a rule
// from it: move / copy lines like it to a tab, hide them, colour them. A line
// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go
// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them).
// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). The
// coordinates are also drawn as underlined links: click points RynthNav's
// arrow there (its overlay opens), Ctrl+click walks there.
// Follows the newest line until you scroll up; the scroll for new lines is set
// in the same frame they're drawn (DrawLines; until 2026-10-11 it landed a frame
// late and the text bounced). Scrolled up, the view holds still. The history is
@ -584,10 +586,18 @@ internal sealed class ChatFace : IImGuiPanel
dl.AddText(font, font.FontSize, tp, col, line.Text, textW);
else
foreach (Seg seg in lay.Segs)
{
dl.AddText(font, font.FontSize, tp + seg.Offset, seg.Argb == 0 ? col : RynthTheme.Argb(seg.Argb), seg.Text);
if (seg.Link >= 0) // a map coordinate: underlined, it's clickable
{
Vector2 u = tp + seg.Offset + new Vector2(0, font.FontSize - 1);
dl.AddLine(u, u + new Vector2(seg.W, 0), RynthTheme.Argb(LinkCol), 1f);
}
}
}
ImGuiNET.ImGui.Dummy(new Vector2(wrapW, Math.Max(1, total)));
HandleSelection(basePos, wrapW, scrollY, viewH, n);
HoverLink(basePos, tsW, n, out ChatCoord? hoveredLink);
HandleSelection(basePos, wrapW, scrollY, viewH, n, hoveredLink);
HandleLineMenu(basePos, wrapW, n);
_lastScrollY = scrollY;
@ -675,7 +685,17 @@ internal sealed class ChatFace : IImGuiPanel
{
ChatLine line = _vis[i];
ChatSpan[]? spans = line.Route.Spans;
if (spans != null)
// Map coordinates ("82.3N, 34.2E") become links. Found here, when the line is measured,
// never per frame; a line without any keeps the plain (or highlighted) path.
List<ChatCoord> coords = ChatCoords.MayHaveCoords(line.Text) ? ChatCoords.Find(line.Text) : NoCoords;
if (coords.Count > 0)
{
ChatSpan[] withLinks = ChatCoords.LinkSpans(spans, coords, LinkCol);
SpanLayout lay = LayoutSpans(font, line.Text, withLinks, textW, coords);
_lay[i] = lay;
_h[i] = lay.Height;
}
else if (spans != null)
{
SpanLayout lay = LayoutSpans(font, line.Text, spans, textW);
_lay[i] = lay;
@ -705,21 +725,40 @@ internal sealed class ChatFace : IImGuiPanel
// ── Highlighted lines: hand layout ───────────────────────────────────
private readonly record struct Seg(string Text, Vector2 Offset, uint Argb); // Argb 0 = the line's colour
// Argb 0 = the line's colour. W: the run's width. Link: index into SpanLayout.Links (a map
// coordinate drawn as a link: click = RynthNav arrow, Ctrl+click = go), -1 for plain text.
private readonly record struct Seg(string Text, Vector2 Offset, uint Argb, float W = 0f, int Link = -1);
private sealed class SpanLayout
{
public required float Height;
public required Seg[] Segs;
/// <summary>The line's map coordinates (ChatCoords), when any are drawn as links.</summary>
public ChatCoord[]? Links;
}
/// <summary>Coordinate links in chat lines: soft teal, underlined (0xAARRGGBB, like ChatSpan.Argb).</summary>
private const uint LinkCol = 0xFF5ECFE0;
private static readonly List<ChatCoord> NoCoords = new();
/// <summary>
/// Word-wraps <paramref name="text"/> to <paramref name="wrapW"/> and cuts each
/// row where a highlight starts or ends, so every run is drawn in its own
/// colour. Called when a line is measured, never per frame.
/// <paramref name="links"/>: the line's map coordinates, whose runs get a link index.
/// </summary>
private static SpanLayout LayoutSpans(ImFontPtr font, string text, ChatSpan[] spans, float wrapW)
private static SpanLayout LayoutSpans(ImFontPtr font, string text, ChatSpan[] spans, float wrapW, List<ChatCoord>? links = null)
{
// Which coordinate link a run [s0, s1) belongs to (-1 none).
int LinkOf(int s0, int s1)
{
if (links == null) return -1;
for (int k = 0; k < links.Count; k++)
if (s0 >= links[k].Start && s1 <= links[k].Start + links[k].Length) return k;
return -1;
}
float size = font.FontSize;
float Width(int start, int end) => end <= start ? 0 : font.CalcTextSizeA(size, float.MaxValue, 0f, text[start..end]).X;
@ -776,13 +815,14 @@ internal sealed class ChatFace : IImGuiPanel
int s0 = Math.Max(span.Start, a), s1 = Math.Min(span.Start + span.Length, b);
if (s1 <= s0) continue;
if (s0 > c) { segs.Add(new Seg(text[c..s0], new Vector2(sx, y), 0)); sx += Width(c, s0); }
segs.Add(new Seg(text[s0..s1], new Vector2(sx, y), span.Argb));
sx += Width(s0, s1);
float spanW = Width(s0, s1);
segs.Add(new Seg(text[s0..s1], new Vector2(sx, y), span.Argb, spanW, LinkOf(s0, s1)));
sx += spanW;
c = s1;
}
if (c < b) segs.Add(new Seg(text[c..b], new Vector2(sx, y), 0));
}
return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray() };
return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray(), Links = links?.ToArray() };
}
/// <summary>Index of the line containing content y (clamped to the list).</summary>
@ -797,7 +837,53 @@ internal sealed class ChatFace : IImGuiPanel
return Math.Min(lo, Math.Max(0, n - 1));
}
private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n)
/// <summary>
/// The map coordinate link under the mouse, if any (hand cursor and a tooltip). Only the
/// hovered line's runs are looked at.
/// </summary>
private void HoverLink(Vector2 basePos, float tsW, int n, out ChatCoord? link)
{
link = null;
if (n == 0 || _selDragging || !ImGuiNET.ImGui.IsWindowHovered()) return;
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
float contentY = mouse.Y - basePos.Y;
if (contentY < 0 || contentY >= _tops[n]) return;
int i = FirstAtOrBelow(contentY, n);
if (_lay[i] is not { Links: { Length: > 0 } links } lay) return;
Vector2 tp = basePos + new Vector2(3 + tsW, _tops[i]);
float h = ImGuiNET.ImGui.GetFontSize();
foreach (Seg seg in lay.Segs)
{
if (seg.Link < 0 || seg.Link >= links.Length) continue;
Vector2 a = tp + seg.Offset, b = a + new Vector2(seg.W, h);
if (mouse.X < a.X || mouse.X >= b.X || mouse.Y < a.Y || mouse.Y >= b.Y) continue;
link = links[seg.Link];
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
bool nav = ImGuiPanelHost.HasFace(RynthNavFace.Title);
SafeImGui.SetTooltip(nav
? $"Click: point the arrow at {link.Value.Text}\nCtrl+click: RynthNav walks there\nRight-click: more"
: $"{link.Value.Text}\n(RynthNav isn't loaded: no arrow)");
return;
}
}
/// <summary>A click on a coordinate link: RynthNav's arrow there, or (Ctrl) walk there.</summary>
private void ClickLink(ChatCoord c)
{
if (!ImGuiPanelHost.HasFace(RynthNavFace.Title)) { Flash("RynthNav isn't loaded", 1.5); return; }
if (ImGuiNET.ImGui.GetIO().KeyCtrl)
{
RynthNavCommands.Go(c.Text, c.Ns, c.Ew);
Flash("Going to " + c.Text, 1.5);
}
else
{
RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew);
Flash("Arrow: " + c.Text, 1.5);
}
}
private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n, ChatCoord? hoveredLink = null)
{
if (n == 0) { ClearSelection(); return; }
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
@ -814,6 +900,7 @@ internal sealed class ChatFace : IImGuiPanel
_selDragging = true;
_selMoved = false;
_selDown = mouse;
_downLink = hoveredLink; // a click (no drag) on it acts on release
return;
}
@ -827,8 +914,15 @@ internal sealed class ChatFace : IImGuiPanel
if (ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return;
_selDragging = false;
// A drag (even within one line) copies; a plain click just clears.
if (!_selMoved && _selEnd == _selAnchor) { ClearSelection(); return; }
// A drag (even within one line) copies; a plain click just clears, or follows a
// coordinate link it was pressed on.
if (!_selMoved && _selEnd == _selAnchor)
{
ChatCoord? link = _downLink;
ClearSelection();
if (link is { } c) ClickLink(c);
return;
}
int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd);
var parts = new List<string>(hi - lo + 1);
for (int i = lo; i <= hi && i < _vis.Count; i++) parts.Add(CopyText(_vis[i]));
@ -855,8 +949,12 @@ internal sealed class ChatFace : IImGuiPanel
{
_selAnchor = _selEnd = -1;
_selDragging = _selMoved = false;
_downLink = null;
}
/// <summary>The coordinate link the left button went down on (acted on if it comes up without a drag).</summary>
private ChatCoord? _downLink;
// ── Input ────────────────────────────────────────────────────────────
private void DrawInput(Vector2 p, float w, float h)

View file

@ -196,6 +196,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel
Label("Checked after the rules above, only for lines no rule moved or hid.", Mute);
Label("Tick to hide the lines; pick a tab to move them there instead.", Mute);
ImGuiNET.ImGui.PopFont();
bool retail = ChatModel.HideInRetailChat;
if (ImGuiNET.ImGui.Checkbox("Hidden lines are hidden in the retail chat too##hideretail", ref retail))
{
ChatModel.HideInRetailChat = retail;
ChatModel.SaveSettings();
}
SafeImGui.SetItemTooltip("On: a line a rule or standard filter hides doesn't print in AC's own chat window either.\n" +
"Off: hiding only applies to RynthChat; the retail chat shows everything.\n" +
"Moved / copied lines still show in the retail chat either way.");
foreach (string group in UI.Panels.RynthChatPresets.Groups)
{
int on = 0, total = 0;

View file

@ -409,6 +409,28 @@ internal sealed class DamageDetailFace : IImGuiPanel
pick => DamageCommands.EditRule(name, r => r.ExVuln = pick),
"A vulnerability of another element, on top of Vuln (which follows the attack's element).");
// Melee/missile attack power against it
string power = string.IsNullOrEmpty(view.AttackPower) ? "Default" : view.AttackPower;
Combo("Power", "##power", DamageCommands.AttackPowerModes, power,
pick => DamageCommands.EditRule(name, r => r.AttackPower = pick),
(isDefault
? "Melee/missile attack power for every monster without its own. Default = the Power settings (Melee Combat).\n"
: "Melee/missile attack power against the monsters it covers. Default = the DEFAULT line's.\n") +
"High = 100%. Reckless = 80% (needs Recklessness trained, else 100%).\n" +
"Variable = a new random power each attack, between Variable Min and Max (Settings).\n" +
"Reckless + Variable = random, kept inside the Recklessness band (20-80%).");
// Pull-away kite: tag then run until the mob is clear of its spawn pack
ImGuiNET.ImGui.SameLine(0, 14);
string kite = string.IsNullOrEmpty(view.Kite) ? "Default" : view.Kite;
Combo("Kite", "##kite", DamageCommands.KiteModes, kite,
pick => DamageCommands.EditRule(name, r => r.Kite = pick),
(isDefault
? "Pull-away for every monster without its own. Default = Off (fight in place).\n"
: "Pull-away for the monsters it covers. Default = the DEFAULT line's.\n") +
"Off = kill where it stands. PullAway = tag, run until it has been dragged\n" +
"Kite Pull Distance metres from its lock spot (Settings > Melee Combat), then kill.");
// The DEFAULT line's own choice is the Prefer chip in the Damage panel's top bar.
if (!isDefault)
Combo("Prefer", "##prefer", DamageCommands.PreferredDamages, string.IsNullOrEmpty(view.PreferredDamage) ? "Auto" : view.PreferredDamage,

View file

@ -222,17 +222,26 @@ internal static class FaceKit
/// <summary>
/// One popup list per face, opened from any button: call Open from the
/// button's click and Draw once per frame at the end of the face's Draw
/// (outside any child window, so the popup id always matches).
/// (outside any child window, so the popup id always matches). Long lists
/// (Slayer Type's creature names, materials, long keys) get a type-to-filter
/// box so players can pick by name instead of scrolling.
/// </summary>
internal sealed class Picker
{
/// <summary>Show the filter box when the list is at least this long.</summary>
private const int FilterAt = 12;
private const float FilterH = 22f;
private const float RowH = 20f;
private readonly string _popupId;
private readonly byte[] _filter = new byte[64];
private string[] _items = Array.Empty<string>();
private int _selected = -1;
private Action<int>? _onPick;
private Vector2 _pos;
private float _width = 220;
private bool _openRequested;
private bool _focusFilter;
public Picker(string popupId) => _popupId = popupId;
@ -244,6 +253,8 @@ internal static class FaceKit
_pos = below;
_width = width;
_openRequested = items.Length > 0;
_filter[0] = 0; // clear the previous open's filter
_focusFilter = items.Length >= FilterAt;
}
public void Draw()
@ -255,38 +266,74 @@ internal static class FaceKit
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(_pos.X, 0, Math.Max(0, display.X - _width)), _pos.Y));
ImGuiNET.ImGui.OpenPopup(_popupId);
}
bool filterOn = _items.Length >= FilterAt;
string filterText = filterOn ? Utf8(_filter) : string.Empty;
// Count matches so the popup height tracks a short filtered list.
int shown = 0;
if (!filterOn) shown = _items.Length;
else
{
for (int i = 0; i < _items.Length; i++)
if (FilterMatch(_items[i], filterText)) shown++;
}
float listH = Math.Min(Math.Max(shown, 1) * RowH + 4, 340);
float totalH = listH + (filterOn ? FilterH + 4 : 0);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(_width, Math.Min(_items.Length * 21 + 4, 340)));
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(_width, totalH));
bool open = ImGuiNET.ImGui.BeginPopup(_popupId);
ImGuiNET.ImGui.PopStyleVar(3);
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
if (filterOn)
{
Vector2 fp = ImGuiNET.ImGui.GetCursorScreenPos();
if (_focusFilter)
{
_focusFilter = false;
ImGuiNET.ImGui.SetKeyboardFocusHere(0); // next widget = the filter box
}
TextBox("##pick_filter", _filter, fp, ImGuiNET.ImGui.GetContentRegionAvail().X, "Type to filter...", out _,
ImGuiInputTextFlags.None, FilterH);
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(fp.X, fp.Y + FilterH + 2));
filterText = Utf8(_filter);
}
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float iw = ImGuiNET.ImGui.GetContentRegionAvail().X;
for (int i = 0; i < _items.Length; i++)
{
if (filterOn && !FilterMatch(_items[i], filterText)) continue;
ImGuiNET.ImGui.PushID(i);
Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos();
bool click = ImGuiNET.ImGui.InvisibleButton("##it", new Vector2(iw, 20));
bool click = ImGuiNET.ImGui.InvisibleButton("##it", new Vector2(iw, RowH));
bool hot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.PopID();
bool sel = i == _selected;
dl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? Selected : hot ? Lighten(BtnFill) : BtnFill);
dl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord);
dl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : Text, _items[i]);
dl.AddRectFilled(ip, ip + new Vector2(iw, RowH), sel ? Selected : hot ? Lighten(BtnFill) : BtnFill);
dl.AddRect(ip, ip + new Vector2(iw, RowH), BtnBord);
dl.AddText(ip + new Vector2(6, (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : Text, _items[i]);
if (click)
{
Action<int>? act = _onPick;
ImGuiNET.ImGui.CloseCurrentPopup();
act?.Invoke(i);
act?.Invoke(i); // still the original index for the caller
}
}
ImGuiNET.ImGui.EndPopup();
}
/// <summary>Case-insensitive substring match; empty filter shows everything.</summary>
private static bool FilterMatch(string item, string filter)
{
if (filter.Length == 0) return true;
return item.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
// ── Text buffers ─────────────────────────────────────────────────────

View file

@ -16,7 +16,9 @@
// 25 px title band isn't stretched) follow AcClientReborn's InventoryGeometry.
// Credit: OpenAC (Tom's project) for the layout and sprite research.
//
// title retail title bar "Inventory of <name>", tool toggles, close
// title retail title bar "Inventory of <name>", Vault, Remote / Sort / Count /
// GInv (text, icons or one menu: InventoryTitleLayout), size / tools /
// Modern toggles, close
// tools search, sort, category chips (toggle, the funnel in the title)
// paperdoll the 24 equip slots at their retail places (the 3D figure isn't
// drawn, so the retail "Slots" view is always on)
@ -134,6 +136,10 @@ internal sealed partial class InventoryFace
private string? _hoverLabel, _hoverLabel2;
private string _titleText = "Inventory";
private string? _titleFor;
// The title cut to its room (InventoryTitleLayout.Elide), kept while the text and the room stay the same.
private string _titleCut = string.Empty;
private string? _titleCutFor;
private float _titleCutRoom, _titleCutW;
// =====================================================================
// Body
@ -230,71 +236,128 @@ internal sealed partial class InventoryFace
dl.AddRect(o, o + new Vector2(barW, h - 1), Gold, 4);
}
// Two toggles at the bar's right end: the tools row and the Modern look.
float btn = MathF.Round(18 * s);
var b2 = new Vector2(o.X + barW - 8 * s - btn, o.Y + (h - btn) * 0.5f);
var b1 = new Vector2(b2.X - btn - 2 * s, b2.Y);
var bPlus = new Vector2(b1.X - btn - 6 * s, b2.Y);
var bMinus = new Vector2(bPlus.X - btn - 2 * s, b2.Y);
if (TitleToggle("##inv_smaller", PhosphorIcons.Minus, bMinus, btn, false))
InventorySettingsStore.StepSize(-1);
SafeImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)");
if (TitleToggle("##inv_bigger", PhosphorIcons.Plus, bPlus, btn, false))
InventorySettingsStore.StepSize(+1);
SafeImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)");
if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, b1, btn, InventorySettingsStore.ShowTools))
{
// Closing the search / filter row shows every item again.
if (InventorySettingsStore.ShowTools) ClearFilters();
InventorySettingsStore.SetShowTools(!InventorySettingsStore.ShowTools);
}
ImGuiNET.ImGui.SetItemTooltip("Search, sort and filter");
if (TitleToggle("##inv_modern", PhosphorIcons.SquaresFour, b2, btn, false))
InventorySettingsStore.SetClassic(false);
ImGuiNET.ImGui.SetItemTooltip("Modern look");
// Vault (Aelrynth only): the contents area shows the account vault instead of the open pack.
float leftmost = bMinus.X;
if (VaultFeed.Available)
{
var vsz = new Vector2(MathF.Round(38 * s), btn);
var bV = new Vector2(bMinus.X - vsz.X - 8 * s, b2.Y);
if (TitleTextToggle("##inv_vault", "Vault", bV, vsz, _vaultOpen))
{
_vaultOpen = !_vaultOpen;
if (_vaultOpen) VaultFeed.ViewOpened();
}
ImGuiNET.ImGui.SetItemTooltip("Your Aelrynth account vault");
leftmost = bV.X;
}
else
{
_vaultOpen = false;
}
// Drag surface: the bar left of the toggles (moves the panel, like the header).
float dragW = Math.Max(1, leftmost - o.X - 2);
ImGuiNET.ImGui.SetCursorScreenPos(o);
ImGuiNET.ImGui.InvisibleButton("##inv_titledrag", new Vector2(dragW, h));
ImGuiPanelHost.DragWindowWithLastItem();
// "Inventory of <name>", centred on the bar (left of the toggles when it's narrow).
// "Inventory of <name>": its width decides how much room the layout owes the title.
if (!ReferenceEquals(_titleFor, view.PlayerName))
{
_titleFor = view.PlayerName;
_titleText = view.PlayerName.Length > 0 ? "Inventory of " + view.PlayerName : "Inventory";
}
ImFontPtr f = ImGuiFonts.Get(UiFont.UiBold11);
ImGuiNET.ImGui.PushFont(f);
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_titleText);
ImGuiNET.ImGui.PopFont();
float titlePx = 12 * s;
ts *= titlePx / f.FontSize;
float tx = o.X + (barW - ts.X) * 0.5f;
if (tx + ts.X > leftmost - 4) tx = Math.Max(o.X + 10 * s, leftmost - 4 - ts.X);
dl.PushClipRect(o + new Vector2(6 * s, 0), new Vector2(leftmost - 2, o.Y + h), true);
dl.AddText(f, titlePx, new Vector2(tx, o.Y + (h - ts.Y) * 0.5f), White, _titleText);
dl.PopClipRect();
float titleK = titlePx / f.FontSize;
ImGuiNET.ImGui.PushFont(f);
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_titleText) * titleK;
ImGuiNET.ImGui.PopFont();
// Where everything goes (UI/InventoryTitleLayout, tested): the four toggles at the right end, Vault
// next to them (always there on a vault server), then the related-panel buttons as text, as icons or
// as one "more" menu, whichever leaves the title its room. Nothing lands off the panel.
InventoryTitleLayout lay = InventoryTitleLayout.Compute(barW, s, VaultFeed.Available, ts.X);
float btn = lay.Btn;
float by = o.Y + (h - btn) * 0.5f;
Vector2 At(TitleSlot sl) => new(o.X + sl.X, by);
if (TitleToggle("##inv_smaller", PhosphorIcons.Minus, At(lay.Smaller), btn, false))
InventorySettingsStore.StepSize(-1);
SafeImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)");
if (TitleToggle("##inv_bigger", PhosphorIcons.Plus, At(lay.Bigger), btn, false))
InventorySettingsStore.StepSize(+1);
SafeImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)");
if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, At(lay.Tools), btn, InventorySettingsStore.ShowTools))
{
// Closing the search / filter row shows every item again.
if (InventorySettingsStore.ShowTools) ClearFilters();
InventorySettingsStore.SetShowTools(!InventorySettingsStore.ShowTools);
}
ImGuiNET.ImGui.SetItemTooltip("Search, sort and filter");
if (TitleToggle("##inv_modern", PhosphorIcons.SquaresFour, At(lay.Modern), btn, false))
InventorySettingsStore.SetClassic(false);
ImGuiNET.ImGui.SetItemTooltip("Modern look");
// Vault (Aelrynth only): the contents area shows the account vault instead of the open pack.
if (lay.Vault.Present)
{
if (TitleTextToggle("##inv_vault", "Vault", At(lay.Vault), new Vector2(lay.Vault.W, btn), _vaultOpen))
{
_vaultOpen = !_vaultOpen;
if (_vaultOpen) VaultFeed.ViewOpened();
}
ImGuiNET.ImGui.SetItemTooltip("Your Aelrynth account vault");
}
else if (!VaultFeed.Available)
{
_vaultOpen = false;
}
// Related panels: Mini Remote, RynthSort, Item Count, Global Inventory.
switch (lay.Mode)
{
case TitleExtrasMode.Text:
if (TitleTextToggle("##inv_miniremote", "Remote", At(lay.Remote), new Vector2(lay.Remote.W, btn), MiniRemoteOpen))
ToggleMiniRemote();
SafeImGui.SetItemTooltip(MiniRemoteTip);
if (TitleTextToggle("##inv_rsort", "Sort", At(lay.Sort), new Vector2(lay.Sort.W, btn), RynthSortOpen))
ToggleRynthSort();
SafeImGui.SetItemTooltip(RynthSortTip());
if (TitleTextToggle("##inv_itemcount", "Count", At(lay.Count), new Vector2(lay.Count.W, btn), ItemCountOpen))
ToggleItemCount();
SafeImGui.SetItemTooltip(ItemCountTip);
if (TitleTextToggle("##inv_ginv", "GInv", At(lay.GInv), new Vector2(lay.GInv.W, btn), GlobalInventoryOpen))
ToggleGlobalInventory();
SafeImGui.SetItemTooltip(GlobalInventoryTip());
break;
case TitleExtrasMode.Icons:
if (TitleToggle("##inv_miniremote", PhosphorIcons.SlidersHorizontal, At(lay.Remote), btn, MiniRemoteOpen))
ToggleMiniRemote();
SafeImGui.SetItemTooltip(MiniRemoteTip);
if (TitleToggle("##inv_rsort", PhosphorIcons.SortAscending, At(lay.Sort), btn, RynthSortOpen))
ToggleRynthSort();
SafeImGui.SetItemTooltip(RynthSortTip());
if (TitleToggle("##inv_itemcount", PhosphorIcons.Bag, At(lay.Count), btn, ItemCountOpen))
ToggleItemCount();
SafeImGui.SetItemTooltip(ItemCountTip);
if (TitleToggle("##inv_ginv", PhosphorIcons.GlobeHemisphereWest, At(lay.GInv), btn, GlobalInventoryOpen))
ToggleGlobalInventory();
SafeImGui.SetItemTooltip(GlobalInventoryTip());
break;
case TitleExtrasMode.Menu:
if (TitleToggle("##inv_more", PhosphorIcons.DotsThree, At(lay.More), btn,
MiniRemoteOpen || RynthSortOpen || ItemCountOpen || GlobalInventoryOpen))
_openMore = true;
ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory");
break;
}
RelatedMenu();
// Drag surface: the bar left of the buttons (moves the panel, like the header).
float dragW = Math.Max(1, lay.LeftmostX - 2);
ImGuiNET.ImGui.SetCursorScreenPos(o);
ImGuiNET.ImGui.InvisibleButton("##inv_titledrag", new Vector2(dragW, h));
ImGuiPanelHost.DragWindowWithLastItem();
// The title: centred on the bar when it fits, else against the left edge and cut with "...".
float room = lay.TitleWidth - 4 * s;
if (room >= 1)
{
string shown = _titleText;
if (ts.X > room)
{
if (!ReferenceEquals(_titleCutFor, _titleText) || _titleCutRoom != room)
{
CutTitle(f, titleK, room);
}
shown = _titleCut;
ts.X = _titleCutW;
}
if (shown.Length > 0)
{
float left = o.X + lay.TitleLeft + 4 * s;
float tx = Math.Clamp(o.X + (barW - ts.X) * 0.5f, left, Math.Max(left, o.X + lay.TitleRight - ts.X));
dl.PushClipRect(o + new Vector2(lay.TitleLeft, 0), new Vector2(o.X + lay.TitleRight, o.Y + h), true);
dl.AddText(f, titlePx, new Vector2(tx, o.Y + (h - ts.Y) * 0.5f), White, shown);
dl.PopClipRect();
}
}
// The retail close button.
var cp = new Vector2(o.X + barW, o.Y);
@ -310,6 +373,17 @@ internal sealed partial class InventoryFace
}
}
/// <summary>Cuts the title text to <paramref name="room"/> px (only when it changed): _titleCut and its width.</summary>
private void CutTitle(ImFontPtr font, float k, float room)
{
ImGuiNET.ImGui.PushFont(font);
_titleCut = InventoryTitleLayout.Elide(_titleText, room, t => ImGuiNET.ImGui.CalcTextSize(t).X * k);
_titleCutW = _titleCut.Length == 0 ? 0 : ImGuiNET.ImGui.CalcTextSize(_titleCut).X * k;
ImGuiNET.ImGui.PopFont();
_titleCutFor = _titleText;
_titleCutRoom = room;
}
private static bool TitleToggle(string id, string glyph, Vector2 pos, float size, bool on)
{
ImGuiNET.ImGui.SetCursorScreenPos(pos);
@ -640,6 +714,45 @@ internal sealed partial class InventoryFace
private VaultItem? _vaultCtx;
private bool _openVaultCtx;
/// <summary>The vault view's caption: how full it is, or the read's status before the first read.</summary>
private static string VaultCaption(VaultSnapshot? snap)
{
if (snap == null) return VaultFeed.Status;
int n = snap.Items.Length;
return snap.Max > 0 ? $"Aelrynth Vault: {n:N0} of {snap.Max:N0}" : $"Aelrynth Vault: {n:N0}";
}
/// <summary>What the vault view says before it has been read.</summary>
private static string VaultEmptyText => VaultFeed.Unsupported ? "The vault is not open on this server yet." : "Click Refresh to read the vault.";
/// <summary>
/// The vault's right-click menu (both looks): Withdraw the item. Call it in the panel's own window
/// (not inside a child), so the popup opened and drawn here share one ID.
/// </summary>
private void VaultContextMenu()
{
if (_openVaultCtx)
{
_openVaultCtx = false;
ImGuiNET.ImGui.OpenPopup("##vault_ctx");
}
PushMenuStyle();
if (ImGuiNET.ImGui.BeginPopup("##vault_ctx"))
{
VaultItem? it = _vaultCtx;
if (it == null) ImGuiNET.ImGui.CloseCurrentPopup();
else
{
SafeImGui.TextDisabled(it.Name);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Withdraw", "", false, VaultFeed.Available))
VaultFeed.Withdraw(it);
}
ImGuiNET.ImGui.EndPopup();
}
PopMenuStyle();
}
/// <summary>A small labelled button in the title bar.</summary>
private static bool TitleTextToggle(string id, string label, Vector2 pos, Vector2 size, bool on)
{
@ -671,9 +784,7 @@ internal sealed partial class InventoryFace
VaultSnapshot? snap = VaultFeed.Snapshot;
VaultItem[] items = snap?.Items ?? Array.Empty<VaultItem>();
int cells = snap == null ? 0 : Math.Max(snap.Max, items.Length);
string caption = snap == null ? VaultFeed.Status
: snap.Max > 0 ? $"Aelrynth Vault: {items.Length:N0} of {snap.Max:N0}" : $"Aelrynth Vault: {items.Length:N0}";
CenterText(dl, ImGuiFonts.Get(UiFont.Ui14), caption, new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White, 12 * s);
CenterText(dl, ImGuiFonts.Get(UiFont.Ui14), VaultCaption(snap), new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White, 12 * s);
// Read again (the vault changes when anything is deposited or withdrawn).
var rb = new Vector2(gridPos.X + gridW - 44 * s, field.Y + 1 * s);
@ -738,29 +849,10 @@ internal sealed partial class InventoryFace
}
else if (snap == null && !VaultFeed.Awaiting)
{
dl.AddText(gridPos + new Vector2(4, 22 * s), Mute, VaultFeed.Unsupported ? "The vault is not open on this server yet." : "Click Refresh to read the vault.");
dl.AddText(gridPos + new Vector2(4, 22 * s), Mute, VaultEmptyText);
}
if (_openVaultCtx)
{
_openVaultCtx = false;
ImGuiNET.ImGui.OpenPopup("##vault_ctx");
}
PushMenuStyle();
if (ImGuiNET.ImGui.BeginPopup("##vault_ctx"))
{
VaultItem? it = _vaultCtx;
if (it == null) ImGuiNET.ImGui.CloseCurrentPopup();
else
{
SafeImGui.TextDisabled(it.Name);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Withdraw", "", false, VaultFeed.Available))
VaultFeed.Withdraw(it);
}
ImGuiNET.ImGui.EndPopup();
}
PopMenuStyle();
VaultContextMenu();
if (snap != null) // nothing to scroll before the vault has been read
Scrollbar("##inv_vaultsb", new Vector2(gridPos.X + gridW, gridPos.Y), rows * cell, s, ref _vaultFirstRow, totalRows, rows);

View file

@ -6,7 +6,11 @@
// pictures (InventoryFace.Classic.cs; Phase 2)
// Modern the Phase 1 layout, below
//
// header burden (percent of capacity) and pyreals; item count
// header burden (percent of capacity) and pyreals; item count; buttons for
// Mini Remote, RynthSort (/rsort), Item Count (/rc itemcount) and
// Global Inventory (/ginv), folded into one menu when the header is short;
// on Aelrynth also the Vault (always there; the grid shows the account
// vault, picking a pack goes back)
// tools search box, attribute filter (InventoryFace.AttrFilter.cs), sort
// picker; category chips
// packs All, Main pack, each side pack (its icon and fill), Worn
@ -36,6 +40,8 @@ using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Net;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.ScriptWindows;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
@ -201,12 +207,99 @@ internal sealed partial class InventoryFace : IImGuiPanel
float bodyH = Math.Max(60, origin.Y + size.Y - 6 - bottomH - bodyPos.Y);
float colW = w >= 380 ? 128 : 46;
PackColumn(view, bodyPos, colW, bodyH);
Grid(new Vector2(bodyPos.X + colW + 4, bodyPos.Y), new Vector2(w - colW - 4, bodyH));
// The Vault (Aelrynth) takes the grid's place; picking a pack in the column goes back to it.
if (_vaultOpen && (!VaultFeed.Available || _pack != _vaultOpenedOnPack)) _vaultOpen = false;
if (_vaultOpen) ModernVault(new Vector2(bodyPos.X + colW + 4, bodyPos.Y), new Vector2(w - colW - 4, bodyH));
else Grid(new Vector2(bodyPos.X + colW + 4, bodyPos.Y), new Vector2(w - colW - 4, bodyH));
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bodyPos.X, bodyPos.Y + bodyH + 4));
Zones(view, w);
StatusRow(w);
}
/// <summary>RynthInventory's Global Inventory script window key (UiWindow "RynthInventory/Main").</summary>
private const string GlobalInventoryKey = "RynthInventory/Main";
/// <summary>RynthSort's script window key (UiWindow "RynthSort/Main").</summary>
private const string RynthSortKey = "RynthSort/Main";
private static bool MiniRemoteOpen => ImGuiPanelHost.IsOpen(MiniRemoteFace.Title);
private static bool ItemCountOpen => ImGuiPanelHost.IsOpen(ItemCountFace.Title);
private static bool RynthSortOpen => ScriptWindowRegistry.IsOpen(RynthSortKey);
private static bool GlobalInventoryOpen => ScriptWindowRegistry.IsOpen(GlobalInventoryKey);
private const string MiniRemoteTip = "Mini Remote (/rc miniremote): remote, sections and HUDs";
private const string ItemCountTip = "Item Count (/rc itemcount): how many of each named item you carry";
private static string RynthSortTip() => ScriptWindowRegistry.Has(RynthSortKey)
? "RynthSort (/rsort): pack sort rules and auto-sort"
: "RynthSort (/rsort) - needs the RynthSort plugin";
private static string GlobalInventoryTip() => ScriptWindowRegistry.Has(GlobalInventoryKey)
? "Global Inventory (/ginv): every character's saved packs and storage"
: "Global Inventory (/ginv) - needs the RynthInventory plugin";
/// <summary>Opens or closes the Item Count panel (same as /rc itemcount).</summary>
private static void ToggleItemCount()
{
if (!ImGuiPanelHost.HasFace(ItemCountFace.Title)) return;
PanelRouter.Toggle(ItemCountFace.Title);
}
/// <summary>Opens or closes the Mini Remote (same as /rc miniremote).</summary>
private static void ToggleMiniRemote()
{
if (!ImGuiPanelHost.HasFace(MiniRemoteFace.Title)) return;
PanelRouter.Toggle(MiniRemoteFace.Title);
}
/// <summary>
/// Opens or closes a plugin script window by key, or runs <paramref name="fallbackCmd"/>
/// when the plugin hasn't submitted it yet.
/// </summary>
private static void ToggleScriptWindow(string key, string fallbackCmd)
{
if (ScriptWindowRegistry.Has(key))
{
ScriptWindowRegistry.PlayerSetVisible(key, !ScriptWindowRegistry.IsOpen(key));
return;
}
ServerMenus.Run(fallbackCmd);
}
/// <summary>Opens or closes RynthInventory's Global Inventory (same as /ginv).</summary>
private static void ToggleGlobalInventory() => ToggleScriptWindow(GlobalInventoryKey, "/ginv");
/// <summary>Opens or closes RynthSort (same as /rsort).</summary>
private static void ToggleRynthSort() => ToggleScriptWindow(RynthSortKey, "/rsort");
// The "more" menu both looks use when their bar is too short for the four buttons.
private bool _openMore;
/// <summary>The "more" popup: the four related panels as menu lines (checked while open). Draw where its button was.</summary>
private void RelatedMenu()
{
if (_openMore)
{
_openMore = false;
ImGuiNET.ImGui.OpenPopup("##inv_more_menu");
}
PushMenuStyle();
if (ImGuiNET.ImGui.BeginPopup("##inv_more_menu"))
{
if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", MiniRemoteOpen, ImGuiPanelHost.HasFace(MiniRemoteFace.Title)))
ToggleMiniRemote();
SafeImGui.SetItemTooltip(MiniRemoteTip);
if (ImGuiNET.ImGui.MenuItem("RynthSort", "/rsort", RynthSortOpen))
ToggleRynthSort();
SafeImGui.SetItemTooltip(RynthSortTip());
if (ImGuiNET.ImGui.MenuItem("Item Count", "/rc itemcount", ItemCountOpen, ImGuiPanelHost.HasFace(ItemCountFace.Title)))
ToggleItemCount();
SafeImGui.SetItemTooltip(ItemCountTip);
if (ImGuiNET.ImGui.MenuItem("Global Inventory", "/ginv", GlobalInventoryOpen))
ToggleGlobalInventory();
SafeImGui.SetItemTooltip(GlobalInventoryTip());
ImGuiNET.ImGui.EndPopup();
}
PopMenuStyle();
}
// ── Header: burden, pyreals, count ──────────────────────────────────
private void Header(InventoryView view, float w)
@ -239,11 +332,62 @@ internal sealed partial class InventoryFace : IImGuiPanel
InventorySettingsStore.SetClassic(true);
ImGuiNET.ImGui.SetItemTooltip("Classic look (the retail inventory window)");
// Related panels (Mini Remote, RynthSort, Item Count, Global Inventory): four icons when the room
// left of the Classic / Close buttons holds them, else one "more" menu, else none (the Character
// menu has them all). The item count text gives way last. On Aelrynth the Vault button sits next
// to the Classic button and takes its room first: it is never dropped
// (UI/InventoryTitleLayout.InventoryHeaderLayout, tested in tools/BarDeclutterTests).
float cw = ImGuiNET.ImGui.CalcTextSize(_countText).X;
dl.AddText(new Vector2(tb.X - cw - 6, ty), Mute, _countText);
float leftEnd = x + 20 + ImGuiNET.ImGui.CalcTextSize(view.PyrealText).X + 6;
InventoryHeaderLayout hl = InventoryHeaderLayout.Compute(w, leftEnd - p.X, cw, VaultFeed.Available);
Vector2 At(TitleSlot s) => new(p.X + s.X, p.Y + 1);
var btn22 = new Vector2(InventoryHeaderLayout.Btn, InventoryHeaderLayout.Btn);
if (hl.Plan.Extras == TitleExtrasMode.Icons)
{
if (IconButton("##inv_ginv", PhosphorIcons.GlobeHemisphereWest, At(hl.GInv), btn22,
GlobalInventoryOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11))
ToggleGlobalInventory();
SafeImGui.SetItemTooltip(GlobalInventoryTip());
if (IconButton("##inv_itemcount", PhosphorIcons.Bag, At(hl.Count), btn22,
ItemCountOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11))
ToggleItemCount();
SafeImGui.SetItemTooltip(ItemCountTip);
if (IconButton("##inv_rsort", PhosphorIcons.SortAscending, At(hl.Sort), btn22,
RynthSortOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11))
ToggleRynthSort();
SafeImGui.SetItemTooltip(RynthSortTip());
if (IconButton("##inv_miniremote", PhosphorIcons.SquaresFour, At(hl.Remote), btn22,
MiniRemoteOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11))
ToggleMiniRemote();
SafeImGui.SetItemTooltip(MiniRemoteTip);
}
else if (hl.Plan.Extras == TitleExtrasMode.Menu)
{
if (IconButton("##inv_more", PhosphorIcons.DotsThree, At(hl.More), btn22,
MiniRemoteOpen || RynthSortOpen || ItemCountOpen || GlobalInventoryOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11))
_openMore = true;
ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory");
}
RelatedMenu();
// Vault (Aelrynth only): the grid shows the account vault instead of the packs.
if (hl.Plan.Vault)
{
if (IconButton("##inv_vault_m", PhosphorIcons.TreasureChest, At(hl.Vault), btn22,
_vaultOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11))
{
_vaultOpen = !_vaultOpen;
_vaultOpenedOnPack = _pack;
if (_vaultOpen) VaultFeed.ViewOpened();
}
ImGuiNET.ImGui.SetItemTooltip("Your Aelrynth account vault");
}
if (hl.Plan.ShowCount) dl.AddText(new Vector2(p.X + hl.CountX, ty), Mute, _countText);
float countLeft = hl.Plan.ShowCount ? p.X + hl.CountX : p.X + hl.RightEdge;
// Drag surface: the empty part of the header, between the pyreals and the count.
float dragFrom = x + 20 + ImGuiNET.ImGui.CalcTextSize(view.PyrealText).X + 6, dragTo = tb.X - cw - 10;
float dragFrom = leftEnd, dragTo = countLeft - 4;
if (dragTo > dragFrom)
{
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(dragFrom, p.Y));
@ -612,6 +756,109 @@ internal sealed partial class InventoryFace : IImGuiPanel
ImGuiNET.ImGui.PopStyleColor();
}
// The pack showing when the Modern Vault opened (picking another pack closes the Vault).
private uint _vaultOpenedOnPack;
/// <summary>
/// The Modern look's Vault: the account vault's items in the grid's style, a caption with how full
/// it is and Refresh. Read-only apart from right-click > Withdraw (VaultContextMenu).
/// </summary>
private void ModernVault(Vector2 pos, Vector2 size)
{
VaultSnapshot? snap = VaultFeed.Snapshot;
VaultItem[] items = snap?.Items ?? Array.Empty<VaultItem>();
var pdl = ImGuiNET.ImGui.GetWindowDrawList();
const float CapH = 22;
float ty = pos.Y + (CapH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
pdl.AddText(new Vector2(pos.X + 4, ty), Text, VaultCaption(snap));
if (IconButton("##vault_refresh_m", PhosphorIcons.ArrowsClockwise, new Vector2(pos.X + size.X - 22, pos.Y), new Vector2(22, 20),
VaultFeed.Awaiting ? Teal : Amber, BtnFill, font: UiFont.Ui11))
VaultFeed.RequestRefresh();
ImGuiNET.ImGui.SetItemTooltip("Read the vault again");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, pos.Y + CapH));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(3, 3));
ImGuiNET.ImGui.BeginChild("##inv_vault_grid", new Vector2(size.X, Math.Max(30, size.Y - CapH)), ImGuiChildFlags.AlwaysUseWindowPadding);
ImGuiNET.ImGui.PopStyleVar();
float avail = ImGuiNET.ImGui.GetContentRegionAvail().X;
int cols = Math.Max(1, (int)(avail / Cell));
int rows = (items.Length + cols - 1) / cols;
Vector2 o = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
if (items.Length == 0)
{
string empty = snap == null ? (VaultFeed.Awaiting ? "Reading the vault..." : VaultEmptyText) : "The vault is empty.";
dl.AddText(o + new Vector2(4, 4), Mute, empty);
ImGuiNET.ImGui.Dummy(new Vector2(avail, 20));
}
else
{
var content = new Vector2(cols * Cell, Math.Max(rows * Cell, 1));
ImGuiNET.ImGui.InvisibleButton("##vault_cells_m", content, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
bool hovered = ImGuiNET.ImGui.IsItemHovered();
Vector2 mouse = ImGuiNET.ImGui.GetMousePos();
int hoverIdx = -1;
if (hovered)
{
int c = (int)((mouse.X - o.X) / Cell), r = (int)((mouse.Y - o.Y) / Cell);
if (c >= 0 && c < cols && r >= 0 && r < rows && r * cols + c < items.Length) hoverIdx = r * cols + c;
}
// Visible rows only.
Vector2 clipMin = ImGuiNET.ImGui.GetWindowPos(), clipMax = clipMin + ImGuiNET.ImGui.GetWindowSize();
int firstRow = Math.Max(0, (int)((clipMin.Y - o.Y) / Cell));
int lastRow = Math.Min(rows - 1, (int)((clipMax.Y - o.Y) / Cell));
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts
for (int r = firstRow; r <= lastRow; r++)
{
for (int c = 0; c < cols; c++)
{
int i = r * cols + c;
if (i >= items.Length) break;
VaultItem it = items[i];
var cmin = new Vector2(o.X + c * Cell, o.Y + r * Cell);
var cmax = cmin + new Vector2(Cell - 2, Cell - 2);
dl.AddRectFilled(cmin, cmax, i == hoverIdx ? CellHot : CellBg, 3);
Vector2 imin = cmin + new Vector2(2, 2);
if (ScriptIcons.TryGetItem(it.Icon, it.Underlay, it.Overlay, it.Effects, it.ItemType, out IntPtr tex))
{
IconSampling.Begin(dl);
dl.AddImage(tex, imin, imin + new Vector2(Icon, Icon));
IconSampling.End(dl);
}
else
dl.AddRectFilled(imin, imin + new Vector2(Icon, Icon), Placeholder, 2);
if (it.Stack > 1)
{
string st = it.Stack.ToString(CultureInfo.InvariantCulture);
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(st);
var tp = new Vector2(cmax.X - ts.X - 2, cmax.Y - ts.Y - 1);
dl.AddText(tp + Vector2.One, StackShadow, st);
dl.AddText(tp, StackCol, st);
}
}
}
ImGuiNET.ImGui.PopFont();
if (hoverIdx >= 0)
{
VaultItem hot = items[hoverIdx];
SafeImGui.SetTooltip(hot.Stack > 1 ? $"{hot.Name} ({hot.Stack:N0})" : hot.Name);
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
{
_vaultCtx = hot;
_openVaultCtx = true;
}
}
}
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleColor();
VaultContextMenu(); // in the panel's window, outside the child
}
/// <summary>An item's icon (with underlay and overlay) from the shared icon cache, or a placeholder.</summary>
private static void DrawItemIcon(ImDrawListPtr dl, uint objectId, Vector2 min, float size, uint tint = 0xFFFFFFFF)
{

View file

@ -82,12 +82,23 @@ internal sealed class ItemsFace : IImGuiPanel
foreach (var (groupName, idx) in groups)
{
if (groups.Count > 1) KindHeading(groupName, idx.Count, bw);
foreach (int i in idx)
for (int k = 0; k < idx.Count; k++)
{
int i = idx[k];
ItemsPanel.WeaponEntry wpn = _data.Weapons[i];
ImGuiNET.ImGui.PushID("w" + i);
int r = Row(wpn.Name, wpn.Element, shown++, bw, _data.MissingIds.Contains(wpn.Id));
int r = Row(wpn.Name, wpn.Element, shown++, bw, _data.MissingIds.Contains(wpn.Id), k > 0, k < idx.Count - 1);
ImGuiNET.ImGui.PopID();
// Up / down inside its group: the order is RynthAi's preference (the buff wand, the
// first weapon of a kind), and it couldn't be changed but by removing and re-adding.
if (r == 3 || r == 4)
{
int j = idx[r == 3 ? k - 1 : k + 1];
(_data.Weapons[i], _data.Weapons[j]) = (_data.Weapons[j], _data.Weapons[i]);
Save();
removed = true; // the indexes moved: draw the rest next frame
break;
}
if (r == 1)
{
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
@ -121,8 +132,15 @@ internal sealed class ItemsFace : IImGuiPanel
{
ItemsPanel.ConsumableEntry c = _data.Consumables[i];
ImGuiNET.ImGui.PushID("c" + i);
int r = Row(c.Name, c.Type, i, bw, missing: false);
int r = Row(c.Name, c.Type, i, bw, missing: false, canUp: i > 0, canDown: i < _data.Consumables.Count - 1);
ImGuiNET.ImGui.PopID();
if (r == 3 || r == 4)
{
int j = r == 3 ? i - 1 : i + 1;
(_data.Consumables[i], _data.Consumables[j]) = (_data.Consumables[j], _data.Consumables[i]);
Save();
break;
}
if (r == 1)
{
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
@ -248,18 +266,21 @@ internal sealed class ItemsFace : IImGuiPanel
}
private const string MissingSuffix = " (missing)";
// The up / down buttons' width in a row (two 20 px buttons and their gaps).
private const float MoveW = 46;
/// <summary>
/// Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0.
/// Name | up | down | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del,
/// 3 for up, 4 for down, else 0. Up / down are drawn dim and do nothing at the ends.
/// <paramref name="missing"/>: the item isn't carried any more (amber, a warning icon,
/// "(missing)" and a tooltip saying what to do).
/// </summary>
private static int Row(string name, string value, int index, float w, bool missing)
private static int Row(string name, string value, int index, float w, bool missing, bool canUp = false, bool canDown = false)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, 24), index % 2 == 0 ? RowAlt : PanelBg);
float nameW = w - 146;
float nameW = w - 146 - MoveW;
float ty = p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.PushClipRect(p, p + new Vector2(nameW, 24), true);
if (missing)
@ -280,8 +301,14 @@ internal sealed class ItemsFace : IImGuiPanel
ImGuiNET.ImGui.SetTooltip("Not in your pack any more - select the item in your inventory and click\n"
+ "Add Selected Weapon again, or remove this entry.");
int result = 0;
if (Button("##pick", value, new Vector2(p.X + nameW + 2, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1;
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(p.X + nameW + 102, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2;
float bx = p.X + nameW + 2;
if (IconButton("##up", PhosphorIcons.CaretUp, new Vector2(bx, p.Y + 2), new Vector2(20, 20), canUp ? Teal : Mute, BtnFill) && canUp) result = 3;
ImGuiNET.ImGui.SetItemTooltip("Move up");
if (IconButton("##down", PhosphorIcons.CaretDown, new Vector2(bx + 22, p.Y + 2), new Vector2(20, 20), canDown ? Teal : Mute, BtnFill) && canDown) result = 4;
ImGuiNET.ImGui.SetItemTooltip("Move down");
bx += MoveW;
if (Button("##pick", value, new Vector2(bx, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1;
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(bx + 100, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2;
ImGuiNET.ImGui.SetItemTooltip("Remove");
NextLine(p, 24);
return result;

View file

@ -9,7 +9,13 @@
// match name + class (default), name only, items like this
// T11 "Include T11 attributes": also require the item's T11 tier,
// grade, damage %, modifiers, slot special and Cast on Strike,
// each at least this item's (any match; 2026-10-07)
// each at least this item's (any match; 2026-10-07). With a
// RynthAi that has it, the attribute checklist below replaces it.
// attrs the attribute checklist (2026-10-18): every attribute the item
// has, grouped (Item, Weapon / Armor, Ratings, Spells, Pet
// essence, T11, Requirements); tick a row to require it, pick
// >= / = / <= (spells: or better / exact / any tier), type a
// value. "Items like this" pre-ticks its usual set.
// action Keep, Keep # (with the count), Salvage, Sell, Read
// name the rule's name (empty: RynthAi's default, "Keep Copper Pea")
// preview the rule in words, where it goes in the list and why, notes
@ -55,6 +61,13 @@ internal sealed class LootAddDialog
private readonly byte[] _name = new byte[128];
private int _keepEdit = 1;
// The attribute checklist: the rows the player changed (sent with every ask; the rest keep
// RynthAi's defaults), each typed value's text box, and the box being typed in (a new
// draft doesn't overwrite it).
private readonly System.Collections.Generic.Dictionary<string, LootEditItemChoiceDto> _choices = new();
private readonly System.Collections.Generic.Dictionary<string, byte[]> _valueBufs = new();
private string _editingId = string.Empty;
// Seqs are unique across popups (the inventory's and the editor's share RynthAi's one draft):
// a popup only takes an answer to something it asked.
private static int s_seq;
@ -94,6 +107,9 @@ internal sealed class LootAddDialog
_keep = -1;
_includeT11 = false;
Array.Clear(_name);
_choices.Clear();
_valueBufs.Clear();
_editingId = string.Empty;
_draft = null;
_adding = false;
_addedAt = default;
@ -119,6 +135,8 @@ internal sealed class LootAddDialog
{
ItemId = _itemId, Match = _match, Action = _action, KeepCount = _keep,
RuleName = Utf8(_name).Trim(), ToOpenProfile = _toOpenProfile, IncludeT11 = _includeT11, Seq = _seq,
// Null until the player changes a row: RynthAi's defaults (and its notes about them).
Choices = _choices.Count == 0 ? null : new System.Collections.Generic.List<LootEditItemChoiceDto>(_choices.Values),
},
});
}
@ -198,13 +216,21 @@ internal sealed class LootAddDialog
}
}
if (!ImGuiNET.ImGui.IsAnyItemActive() || first) _keepEdit = Math.Max(0, d.KeepCount);
// Value boxes show what the rule uses now, except the one being typed in.
foreach (LootEditItemAttributeDto a in d.Attributes)
{
if (!a.Editable || a.Id == _editingId) continue;
if (!_valueBufs.TryGetValue(a.Id, out byte[]? buf)) _valueBufs[a.Id] = buf = new byte[32];
WriteUtf8(buf, a.Value);
}
}
}
/// <summary>The popup's contents; true when it should close.</summary>
private bool Body()
{
const float w = 380;
// Wider with the checklist (label, comparison, value on one line).
float w = _draft?.AttributesSupported == true ? 440 : 380;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.Plus + " Add to loot profile");
ImGuiNET.ImGui.PopStyleColor();
@ -260,24 +286,31 @@ internal sealed class LootAddDialog
if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(MatchTips[i]);
}
// T11 attributes. Shown for every item: a non-T11 item answers with a note saying so.
bool t11 = _includeT11;
if (ImGuiNET.ImGui.Checkbox("Include T11 attributes##la_t11", ref t11))
if (d.AttributesSupported)
{
_includeT11 = t11;
changed = true;
changed |= DrawAttributes(d, w);
}
if (ImGuiNET.ImGui.IsItemHovered())
SafeImGui.SetTooltip(
"Also require this item's T11 tier (the server's stamped tier when it sends one), weapon grade,\n" +
"damage %, gear grade, every modifier, slot special and Cast on Strike, each at least as good\n" +
"as this one. Works with any match.\n" +
"Not added: Can Wield (depends on your character), Zone Locked (depends on where it was assessed),\n" +
"and property slots / Tainted (bag state, not quality).");
if (!d.IsT11)
else
{
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.TextDisabled("(not a T11 item)");
// An older RynthAi: the single T11 box. Shown for every item: a non-T11 item answers with a note saying so.
bool t11 = _includeT11;
if (ImGuiNET.ImGui.Checkbox("Include T11 attributes##la_t11", ref t11))
{
_includeT11 = t11;
changed = true;
}
if (ImGuiNET.ImGui.IsItemHovered())
SafeImGui.SetTooltip(
"Also require this item's T11 tier (the server's stamped tier when it sends one), weapon grade,\n" +
"damage %, gear grade, every modifier, slot special and Cast on Strike, each at least as good\n" +
"as this one. Works with any match.\n" +
"Not added: Can Wield (depends on your character), Zone Locked (depends on where it was assessed),\n" +
"and property slots / Tainted (bag state, not quality).");
if (!d.IsT11)
{
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.TextDisabled("(not a T11 item)");
}
}
// Action.
@ -370,6 +403,129 @@ internal sealed class LootAddDialog
return false;
}
/// <summary>
/// The attribute checklist: a scrolling list of the item's rows by group, each with a tick,
/// its comparison and its value (typed, or the item's named value). A group header's
/// "all" / "none" ticks its rows. True when a choice changed (the caller asks again).
/// </summary>
private bool DrawAttributes(LootEditItemDraftDto d, float w)
{
System.Collections.Generic.List<LootEditItemAttributeDto> rows = d.Attributes;
ImGuiNET.ImGui.TextDisabled("Attributes:");
ImGuiNET.ImGui.SameLine();
if (rows.Count == 0)
{
ImGuiNET.ImGui.TextDisabled("none known yet (assess the item, then reopen)");
return false;
}
int ticked = rows.FindAll(r => r.On).Count;
SafeImGui.TextDisabled($"{ticked} of {rows.Count} required (tick what the rule needs)");
int groups = 0;
string? last = null;
foreach (LootEditItemAttributeDto r in rows)
if (r.Group != last) { groups++; last = r.Group; }
float lineH = ImGuiNET.ImGui.GetFrameHeightWithSpacing();
float h = Math.Min(rows.Count * lineH + groups * lineH + 8, 300);
bool changed = false;
const float opX = 230, valueX = 330;
ImGuiNET.ImGui.BeginChild("##la_attrs", new Vector2(w, h), ImGuiChildFlags.Borders);
string? group = null;
foreach (LootEditItemAttributeDto r in rows)
{
if (r.Group != group)
{
group = r.Group;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.TextUnformatted(group);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.SameLine(opX);
if (ImGuiNET.ImGui.SmallButton("all##la_all_" + group)) changed |= TickGroup(rows, group, true);
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("none##la_none_" + group)) changed |= TickGroup(rows, group, false);
}
bool on = r.On;
if (ImGuiNET.ImGui.Checkbox(r.Label + "##la_on_" + r.Id, ref on))
{
SetChoice(r, on: on);
changed = true;
}
if (ImGuiNET.ImGui.IsItemHovered() && r.Tip.Length > 0) SafeImGui.SetTooltip(r.Tip);
// The comparison: a picker when the row offers more than one.
ImGuiNET.ImGui.SameLine(opX);
if (r.Ops.Count > 1)
{
ImGuiNET.ImGui.SetNextItemWidth(90);
if (ImGuiNET.ImGui.BeginCombo("##la_op_" + r.Id, LootAttrOps.Label(r.Op)))
{
foreach (int op in r.Ops)
if (ImGuiNET.ImGui.Selectable(LootAttrOps.Label(op) + "##la_opv_" + r.Id + op.ToString(CultureInfo.InvariantCulture), op == r.Op) && op != r.Op)
{
SetChoice(r, op: op, on: true); // picking a comparison means "require it"
changed = true;
}
ImGuiNET.ImGui.EndCombo();
}
}
else
SafeImGui.TextDisabled(LootAttrOps.Label(r.Op));
// The value: a box for numbers, the item's value (by name) for the rest.
ImGuiNET.ImGui.SameLine(valueX);
if (r.Editable)
{
if (!_valueBufs.TryGetValue(r.Id, out byte[]? buf))
{
_valueBufs[r.Id] = buf = new byte[32];
WriteUtf8(buf, r.Value);
}
ImGuiNET.ImGui.SetNextItemWidth(w - valueX - 16);
ImGuiNET.ImGui.InputText("##la_val_" + r.Id, buf, (uint)buf.Length, ImGuiInputTextFlags.CharsDecimal);
if (ImGuiNET.ImGui.IsItemActive()) _editingId = r.Id;
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_editingId = string.Empty;
SetChoice(r, value: Utf8(buf).Trim(), on: true); // typing a value means "require it"
changed = true;
}
else if (_editingId == r.Id && !ImGuiNET.ImGui.IsItemActive())
_editingId = string.Empty;
if (ImGuiNET.ImGui.IsItemHovered())
SafeImGui.SetTooltip("This item: " + r.ItemValue + ". Type another value to require that instead.");
}
else
SafeImGui.TextDisabled(r.ItemValue);
}
ImGuiNET.ImGui.EndChild();
return changed;
}
/// <summary>Ticks or clears every row of <paramref name="group"/>; true when one changed.</summary>
private bool TickGroup(System.Collections.Generic.List<LootEditItemAttributeDto> rows, string group, bool on)
{
bool changed = false;
foreach (LootEditItemAttributeDto r in rows)
{
if (r.Group != group || r.On == on) continue;
SetChoice(r, on: on);
changed = true;
}
return changed;
}
/// <summary>The player's choice for a row: its current state with the given parts changed.</summary>
private void SetChoice(LootEditItemAttributeDto r, bool? on = null, int? op = null, string? value = null)
{
if (!_choices.TryGetValue(r.Id, out LootEditItemChoiceDto? c))
_choices[r.Id] = c = new LootEditItemChoiceDto { Id = r.Id, On = r.On, Op = r.Op, Value = r.Editable && r.Value != r.ItemValue ? r.Value : string.Empty };
if (on.HasValue) c.On = on.Value;
if (op.HasValue) c.Op = op.Value;
if (value != null) c.Value = value == r.ItemValue ? string.Empty : value;
}
private bool CloseRow(float w)
{
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);

View file

@ -123,6 +123,10 @@ internal sealed partial class MiniRemoteFace
_remoteWindowSize = ImGuiNET.ImGui.GetWindowSize() / ImGuiPanelHost.PlacementScale();
_section = next;
_fitPending = true;
// Non-Remote sections need the left rail (or they draw as an orphan body with no
// hub tab bar). Rail-off is only for Remote + miniremote-window (Gear/Games/…).
if (!IsRemote && !RailShown)
PanelColumnStore.Set(RailKey, 1f);
if (IsRemote)
{
// Back on the remote: RynthAi's asks again; the engine grid gets the size it had.
@ -504,8 +508,17 @@ internal sealed partial class MiniRemoteFace
ImGuiNET.ImGui.Separator();
bool rail = RailShown;
if (ImGuiNET.ImGui.MenuItem("Show the sections rail", "", rail))
PanelColumnStore.Set(RailKey, rail ? 0f : 1f);
SafeImGui.SetItemTooltip("The column of sections down the left. Hidden, RynthAi's remote shows its own tab bar again "
+ "(Gear, Games and the other ILT tabs), and a section is picked here or with /rc miniremote section <name>.");
{
bool hide = rail;
PanelColumnStore.Set(RailKey, hide ? 0f : 1f);
// Hiding the rail only restores the Remote tab bar when we are on Remote
// (Surface → miniremote-window). Off-Remote + rail off left Crafting/etc.
// as a lone body in docked and undocked windows (2026-10-16).
if (hide && !IsRemote)
SelectSection(SectionCatalog.RemoteId);
}
SafeImGui.SetItemTooltip("The column of sections down the left. Hidden, the window returns to Remote so "
+ "RynthAi's tab bar shows again (Pets, Crafting, Gear, Games, Vaulted), and a section is picked "
+ "here or with /rc miniremote section <name> (that turns the rail back on).");
}
}

View file

@ -48,6 +48,7 @@ using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Plugins;
using RynthCore.Engine.UI.Data;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Engine.UI.Sections;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
@ -137,6 +138,11 @@ internal sealed partial class MiniRemoteFace : IImGuiPanel
UI.Sections.SectionRegistry.Snapshot snap = UI.Sections.SectionRegistry.Current;
TakeRequestedSection(snap);
// Safety: rail-off + non-Remote draws only that section's body (no hub tabs). Snap
// back to Remote so undocked/docked Mini Remote keeps Pets/Crafting/Gear/Games/Vaulted.
if (!RailShown && !IsRemote)
SelectSection(SectionCatalog.RemoteId);
// The rail, then everything else to its right (the indent keeps each line there).
float railW = RailShown ? DrawRail(snap, origin, size) : 0f;
if (railW > 0)

View file

@ -157,19 +157,21 @@ internal sealed class NavFace : IImGuiPanel
// Breadcrumbs | Route overlay (RynthAi's NavOverlaySettings; saved per character)
p = ImGuiNET.ImGui.GetCursorScreenPos();
if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half,
"Record the trail you walk and draw it on the ground (/ra navtrail on|off).\nTurning it off hides the trail; /ra navtrail clear wipes it."))
// Also on Settings > Navigation. The local settings copy takes the new value too, so a reach
// save from this panel before the next settings fetch doesn't send the old one back.
if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half, SettingsSchema.BreadcrumbsTip))
{
bool on = !_data.TrackBreadcrumbs;
NavCommands.Send(new NavCmd { Cmd = "setBreadcrumbs", On = on });
_data.TrackBreadcrumbs = on;
if (_settings?.TrackBreadcrumbs != null) _settings.TrackBreadcrumbs = on;
}
if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half,
"Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\nto the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate."))
if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half, SettingsSchema.RouteOverlayTip))
{
bool on = !_data.ShowRouteOverlay;
NavCommands.Send(new NavCmd { Cmd = "setRouteOverlay", On = on });
_data.ShowRouteOverlay = on;
if (_settings?.ShowRouteOverlay != null) _settings.ShowRouteOverlay = on;
}
NextLine(p, 26);

View file

@ -0,0 +1,120 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/OracleSkillsEmbed.cs
// Bridges RynthOracle's Skills / Attributes / Progress tabs to the engine
// SkillsFace body so raise/train/progression stay in one place under Oracle.
// Oracle sets ActiveTab (`/rc oracle-skills <skills|attrs|progress|off>`) while
// those tabs are selected; ScriptWindowFace for the Oracle window draws the
// embed after the script tab strip.
//
// Idea and first version: Silentkelpie (RynthCore PR 6).
//
// Lifecycle (the part that must not leak): the embedded SkillsFace is "shown"
// exactly once when it first draws, and "hidden" exactly once when it stops:
// - Clear() (Oracle left the tabs: `/rc oracle-skills off`),
// - the Oracle window closed / removed / its plugin unloaded (ScriptWindowFace
// OnHidden, ScriptWindowRegistry removal and Reset on engine shutdown),
// - a safety sweep: no draw for IdleMs (window collapsed, owner crashed).
// Redraws while shown only refresh the idle clock (NoteDrawn). SkillsFace binds
// its OnShown / OnHidden here; the callbacks go through a ShownLatch, so they
// alternate no matter how often or from which thread these are called.
//
// Skills stays reachable without Oracle: TabsAvailable is true only while the
// Oracle window is registered AND Oracle has announced itself by sending any
// `/rc oracle-skills` (an older Oracle never does), so the standalone Skills bar
// icon / panel stays for everyone who cannot reach the Oracle tabs.
//
// Pure of ImGui and the plugin registry, so tools/BarDeclutterTests compiles it.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.ImGuiBackend.Panels;
/// <summary>Which SkillsFace body Oracle wants drawn inside its window (-1 = none).</summary>
internal static class OracleSkillsEmbed
{
/// <summary>0 = Skills, 1 = Attributes, 2 = Progress (ILT Progression). -1 = off.</summary>
private static int _activeTab = -1;
/// <summary>1 once Oracle has sent a `/rc oracle-skills` (any argument) in this engine generation.</summary>
private static int _announced;
private static long _lastDrawnMs;
private static Action? _onShown, _onHidden;
private static readonly ShownLatch Latch = new(
static () => _onShown?.Invoke(),
static () => _onHidden?.Invoke());
/// <summary>No draw for this long and the embed counts as hidden (Oracle collapsed, closed unseen, crashed).</summary>
public const long IdleMs = 1000;
/// <summary>Oracle panel key prefix used by ScriptWindowRegistry ("script:…").</summary>
public const string OraclePanelKeyFragment = "RynthOracle/Oracle";
public static int ActiveTab => Volatile.Read(ref _activeTab);
/// <summary>True between the first embed draw and the hide (Clear, window gone, idle).</summary>
public static bool IsShown => Latch.IsShown;
/// <summary>SkillsFace hands over what to run on the shown / hidden edges. Once per engine generation.</summary>
public static void Bind(Action shown, Action hidden)
{
_onShown = shown;
_onHidden = hidden;
}
/// <summary>The command saw `/rc oracle-skills` from the Oracle plugin: it has the tabs. Any thread.</summary>
public static void Announce() => Volatile.Write(ref _announced, 1);
/// <summary>
/// Whether the Oracle Skills / Attributes / Progress tabs can be reached: the Oracle script window is
/// registered and Oracle has announced the bridge. False for an Oracle without the tabs, or none.
/// </summary>
public static bool TabsAvailable(bool oracleWindowRegistered) =>
oracleWindowRegistered && Volatile.Read(ref _announced) != 0;
/// <summary>Called from the Oracle plugin (pump/render) when a Skills-family tab is shown. Out of range = off.</summary>
public static void SetActiveTab(int tab)
{
if (tab is < 0 or > 2) { Clear(); return; }
Volatile.Write(ref _activeTab, tab);
}
/// <summary>Clears the embed when Oracle leaves Skills / Attributes / Progress, and hides the face. Any thread.</summary>
public static void Clear()
{
Volatile.Write(ref _activeTab, -1);
Latch.Hide();
}
/// <summary>
/// The embed drew this frame (AC thread): keeps it shown. The face's OnShown runs on the first
/// frame only. Ignored when the embed was cleared meanwhile.
/// </summary>
public static void NoteDrawn(long nowMs)
{
if (ActiveTab < 0) return;
Volatile.Write(ref _lastDrawnMs, nowMs);
Latch.Show();
}
/// <summary>Once a frame (AC thread): hides an embed that stopped drawing for IdleMs.</summary>
public static void Sweep(long nowMs)
{
if (!Latch.IsShown) return;
if (nowMs - Volatile.Read(ref _lastDrawnMs) > IdleMs) Latch.Hide();
}
/// <summary>Engine shutdown / reload: hide the face and forget the announcement.</summary>
public static void Shutdown()
{
Clear();
Volatile.Write(ref _announced, 0);
}
public static bool IsOraclePanel(string panelKey) =>
panelKey.Contains(OraclePanelKeyFragment, StringComparison.OrdinalIgnoreCase);
}

View file

@ -1020,6 +1020,22 @@ internal sealed partial class RynthAiFace : IImGuiPanel
PanelRouter.Toggle(title);
}
/// <summary>
/// A Character menu line that opens Skills (0), Attributes (1) or Progress (2): in RynthOracle when its tabs
/// are there, else the standalone Skills panel on that tab. Checked while the place it opens is showing it.
/// </summary>
private static void SkillsMenuItem(string label, string command, int tab, string tooltip)
{
bool viaOracle = SkillsRouting.OracleTabsAvailable;
if (!viaOracle && (tab != 0 || !ImGuiPanelHost.HasFace(SkillsFace.Title))) return; // standalone Skills has its own tab strip
bool on = viaOracle
? UI.ScriptWindows.ScriptWindowRegistry.IsOpen(OracleMainKey) && OracleSkillsEmbed.ActiveTab == tab
: ImGuiPanelHost.IsOpen(SkillsFace.Title);
if (ImGuiNET.ImGui.MenuItem(label, viaOracle ? SkillsRouting.OracleCommand(tab) : command, on))
SkillsRouting.Open(tab);
SafeImGui.SetItemTooltip(viaOracle ? "RynthOracle's " + label + " tab: " + tooltip : tooltip);
}
// RynthOracle's script window keys (RynthOraclePlugin: UiWindow keys).
private const string OracleMainKey = "RynthOracle/Oracle";
private const string OracleTimersKey = "RynthOracle/QuestTimers";
@ -1074,9 +1090,23 @@ internal sealed partial class RynthAiFace : IImGuiPanel
SafeImGui.SetItemTooltip(hasOracle
? "RynthOracle's Fellowship tab: members, leader, open / locked, XP sharing and (Infinite Leaftide) the /fship commands."
: "RynthOracle's Fellowship tab (RynthOracle isn't loaded).");
PanelMenuItem(SkillsFace.Title, "/rc skills");
// Skills / Attributes / Progress live under RynthOracle (raise/train + ILT planners) when Oracle
// provides the tabs; otherwise these open the standalone Skills panel (SkillsRouting).
SkillsMenuItem("Skills", "/rc skills", 0, "Raise and train skills.");
SkillsMenuItem("Attributes", "/ro attrs", 1, "Attributes and vitals.");
SkillsMenuItem("Progress", "/rc progression", 2, "Augmentation, Enlightenment and XP planners (Infinite Leaftide).");
PanelMenuItem(InventoryFace.Title, "/rc inventory");
PanelMenuItem(ItemCountFace.Title, "/rc itemcount");
// RynthInventory's script window (same as /ginv and Inventory's GInv button).
const string ginvKey = "RynthInventory/Main";
bool hasGinv = UI.ScriptWindows.ScriptWindowRegistry.Has(ginvKey);
if (ImGuiNET.ImGui.MenuItem("Global Inventory", "/ginv",
hasGinv && UI.ScriptWindows.ScriptWindowRegistry.IsOpen(ginvKey), hasGinv))
UI.ScriptWindows.ScriptWindowRegistry.PlayerSetVisible(ginvKey,
!UI.ScriptWindows.ScriptWindowRegistry.IsOpen(ginvKey));
SafeImGui.SetItemTooltip(hasGinv
? "Every character's saved packs and storage (RynthInventory)."
: "Global Inventory (RynthInventory isn't loaded).");
PanelMenuItem(CharactersFace.Title, "/rc characters");
UI.ServerMenus.DrawImGuiMenu(separatorFirst: true);

View file

@ -36,7 +36,14 @@ internal sealed unsafe class ScriptWindowFace : IImGuiPanel
public void OnShown() => NoteVisibility(visible: true);
/// <summary>Closed: as OnShown; a close the owner didn't ask for is the player's X unless the bar said otherwise.</summary>
public void OnHidden() => NoteVisibility(visible: false);
public void OnHidden()
{
// Leaving Oracle hides the Skills embed (its face's OnHidden runs once, releasing the
// Progression subscription) so a later non-Oracle script window never inherits ActiveTab.
if (OracleSkillsEmbed.IsOraclePanel(_window.PanelKey))
OracleSkillsEmbed.Clear();
NoteVisibility(visible: false);
}
private void NoteVisibility(bool visible)
{
@ -60,6 +67,13 @@ internal sealed unsafe class ScriptWindowFace : IImGuiPanel
ScriptWindowMetrics.Refresh();
ReportGeometry();
ScriptWindowReplay.Draw(_window);
// Oracle Skills / Attributes / Progress: after the script tab strip, draw the
// engine SkillsFace body (raise/train/progression) into the remaining space.
if (OracleSkillsEmbed.IsOraclePanel(_window.PanelKey))
{
int tab = OracleSkillsEmbed.ActiveTab;
if (tab >= 0) SkillsFace.DrawEmbedded(tab);
}
}
finally
{

View file

@ -243,7 +243,7 @@ internal sealed class SettingsRows
}
// Label | [caption]; Click posts its own work (never runs plugin code on AC's thread).
private static void ButtonRow(SettingRow row, float w)
private void ButtonRow(SettingRow row, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
@ -252,7 +252,16 @@ internal sealed class SettingsRows
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f));
if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label))
{
// 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.
if (row.Edit != null)
{
row.Edit(_data);
SettingsCommands.Save(_data.Clone());
}
row.Click?.Invoke();
}
Tooltip(row);
}

View file

@ -0,0 +1,62 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/ShownLatch.cs
// A shown / hidden pair that fires its callbacks once per transition.
//
// Show() runs the "shown" callback only when the latch is off; Hide() runs the
// "hidden" callback only when it is on. Calling either twice in a row is a no-op,
// so a face that wants to be "kept shown" every frame (Show) cannot re-run its
// setup, and a hide that never had a show (or a second hide) cannot unbalance a
// refcount like UiSource.Subscribe / Unsubscribe.
//
// Pure (no ImGui, no engine state). Any thread: the callbacks run under the
// latch's own lock, so a Show and a Hide from two threads still alternate.
// If the shown callback throws, the latch stays on, so the matching Hide runs.
// Tests: tools/BarDeclutterTests.
// ============================================================================
using System;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class ShownLatch
{
private readonly object _gate = new();
private readonly Action _shown;
private readonly Action _hidden;
private volatile bool _on;
public ShownLatch(Action shown, Action hidden)
{
_shown = shown;
_hidden = hidden;
}
/// <summary>True between a Show that ran its callback and the Hide that ends it.</summary>
public bool IsShown => _on;
/// <summary>Turns the latch on. Returns true (and runs the callback) only on the off to on edge.</summary>
public bool Show()
{
if (_on) return false;
lock (_gate)
{
if (_on) return false;
_on = true;
_shown();
return true;
}
}
/// <summary>Turns the latch off. Returns true (and runs the callback) only on the on to off edge.</summary>
public bool Hide()
{
if (!_on) return false;
lock (_gate)
{
if (!_on) return false;
_on = false;
_hidden();
return true;
}
}
}

View file

@ -595,11 +595,15 @@ internal sealed partial class SkillsFace
SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture));
foreach (string line in e.Plan) SafeImGui.BulletText(line);
DrawEnlCalculator(e, w);
int coinsPerToken = e.CoinsPerToken;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Coins per token (shop price)##prog_cpt", ref coinsPerToken))
SendProg("coinspertoken " + Math.Max(0, coinsPerToken).ToString(CultureInfo.InvariantCulture));
if (e.TokensShort.Length > 0) Label(e.TokensShort, Dim);
if (!string.IsNullOrEmpty(e.Ecoins)) Label(e.Ecoins, Text);
if (!string.IsNullOrEmpty(e.EcoinsLum)) Label(e.EcoinsLum, Dim);
ImGuiNET.ImGui.Separator();
if (e.Blockers.Length == 0) Label("Client-side checks pass.", Green);
@ -649,6 +653,171 @@ internal sealed partial class SkillsFace
}
}
// ── Enl calculator ──────────────────────────────────────────────────
//
// RynthILT's AppendEnlCalculatorJson (Silentkelpie's rynth PR 6 drew it first): per-level cost rows, still-need /
// have materials and the 301-325 sigil craft chain. Read-only: it only draws the Progression snapshot already
// subscribed by ProgressionShown, so it adds no subscription and no per-frame work beyond the table rows
// (row text is formatted once per snapshot, in the DTOs). A snapshot without the fields (older RynthILT) has
// empty arrays and nothing here is drawn.
//
// Width: the three tables are w - 16 wide inside the Indent(8) of DrawEnlPlanner, with a stretch label
// column and narrow fixed number columns scaled down below the retail width (300); text in a cell wraps at
// the cell instead of running off the panel. Level rows show a preview (12), "Show all" lists up to 100 in a
// table that scrolls on its own.
private const float EnlRetailTableWidth = 284f; // retail panel width (300) - 16
private bool _enlShowAllLevels;
private string _enlToggleLabel = "";
private int _enlToggleTotal = -1;
private bool _enlToggleAll;
private void DrawEnlCalculator(EnlPlanner e, float w)
{
if (!e.HasCalculator) return;
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
if (!ImGuiNET.ImGui.CollapsingHeader("Enl calculator##prog_enl_calc", ImGuiTreeNodeFlags.DefaultOpen))
return;
float tw = Math.Max(120f, w - 16);
float k = Math.Min(1f, tw / EnlRetailTableWidth); // fixed columns shrink on a narrower panel
DrawEnlLevels(e.Levels, tw, k);
DrawEnlMaterials(e.Materials, tw, k);
DrawEnlChain(e, tw, k);
}
private void DrawEnlLevels(EnlLevelRow[] rows, float tw, float k)
{
if (rows.Length == 0) return;
bool canExpand = EnlCalculatorView.CanExpand(rows.Length);
bool all = canExpand && _enlShowAllLevels;
int shown = EnlCalculatorView.VisibleLevels(rows.Length, all);
ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp;
var size = new Vector2(tw, 0);
if (all)
{
// Own scroll area, a preview's worth of rows tall (+ header): the long list never pushes the panel.
flags |= ImGuiTableFlags.ScrollY;
size.Y = (ImGuiNET.ImGui.GetTextLineHeightWithSpacing() + 4f) * (EnlCalculatorView.PreviewLevels + 1);
}
ImGuiNET.ImGui.PushTextWrapPos(0f); // wrap in the cell, not at the panel's wrap position
try
{
if (ImGuiNET.ImGui.BeginTable("##enl_levels", 4, flags, size))
{
ImGuiNET.ImGui.TableSetupColumn("Enl", ImGuiTableColumnFlags.WidthFixed, 40 * k);
ImGuiNET.ImGui.TableSetupColumn("Item", ImGuiTableColumnFlags.WidthFixed, 84 * k);
ImGuiNET.ImGui.TableSetupColumn("Qty", ImGuiTableColumnFlags.WidthFixed, 44 * k);
ImGuiNET.ImGui.TableSetupColumn("Lum");
if (all) ImGuiNET.ImGui.TableSetupScrollFreeze(0, 1);
ImGuiNET.ImGui.TableHeadersRow();
for (int i = 0; i < shown; i++)
{
EnlLevelRow row = rows[i];
uint c = row.Ok ? Green : Amber;
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); Label(row.LevelText, c);
ImGuiNET.ImGui.TableNextColumn(); Label(row.Item, c);
ImGuiNET.ImGui.TableNextColumn(); Label(row.CountText, c);
ImGuiNET.ImGui.TableNextColumn(); Label(row.Lum, c);
}
ImGuiNET.ImGui.EndTable();
}
}
finally
{
ImGuiNET.ImGui.PopTextWrapPos();
}
if (canExpand)
{
// The label is rebuilt only when the row count or the mode changes, not every frame.
if (_enlToggleTotal != rows.Length || _enlToggleAll != all)
{
_enlToggleTotal = rows.Length;
_enlToggleAll = all;
_enlToggleLabel = (all ? "Show first " + EnlCalculatorView.PreviewLevels.ToString(CultureInfo.InvariantCulture)
: "Show all " + Math.Min(rows.Length, EnlCalculatorView.MaxLevels).ToString(CultureInfo.InvariantCulture) + " steps")
+ "##enl_lv_all";
}
if (ImGuiNET.ImGui.SmallButton(_enlToggleLabel)) _enlShowAllLevels = !all;
}
Label("Green = pack items and banked luminance still cover that step (simulated in order).", Dim);
}
private static void DrawEnlMaterials(EnlMaterialRow[] rows, float tw, float k)
{
if (rows.Length == 0) return;
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
Label("Still need / have", Text);
ImGuiNET.ImGui.PushTextWrapPos(0f);
try
{
if (ImGuiNET.ImGui.BeginTable("##enl_mats", 3,
ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, new Vector2(tw, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Material");
ImGuiNET.ImGui.TableSetupColumn("Still need", ImGuiTableColumnFlags.WidthFixed, 72 * k);
ImGuiNET.ImGui.TableSetupColumn("Have", ImGuiTableColumnFlags.WidthFixed, 72 * k);
ImGuiNET.ImGui.TableHeadersRow();
int n = Math.Min(rows.Length, EnlCalculatorView.MaxListRows);
for (int i = 0; i < n; i++)
{
EnlMaterialRow m = rows[i];
uint c = m.Ok ? Green : Amber;
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); Label(m.Label, c);
ImGuiNET.ImGui.TableNextColumn(); Label(m.Need, c);
ImGuiNET.ImGui.TableNextColumn(); Label(m.Have, c);
}
ImGuiNET.ImGui.EndTable();
}
}
finally
{
ImGuiNET.ImGui.PopTextWrapPos();
}
}
private static void DrawEnlChain(EnlPlanner e, float tw, float k)
{
EnlChainRow[] rows = e.Chain;
if (rows.Length == 0) return;
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
Label("Sigil craft chain (301-325)", Text);
if (!string.IsNullOrEmpty(e.ChainNote)) Label(e.ChainNote, Dim); // wraps at the panel's wrap position
ImGuiNET.ImGui.PushTextWrapPos(0f);
try
{
if (ImGuiNET.ImGui.BeginTable("##enl_chain", 3,
ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, new Vector2(tw, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Item");
ImGuiNET.ImGui.TableSetupColumn("Need", ImGuiTableColumnFlags.WidthFixed, 72 * k);
ImGuiNET.ImGui.TableSetupColumn("Have", ImGuiTableColumnFlags.WidthFixed, 72 * k);
ImGuiNET.ImGui.TableHeadersRow();
int n = Math.Min(rows.Length, EnlCalculatorView.MaxListRows);
for (int i = 0; i < n; i++)
{
EnlChainRow r = rows[i];
uint c = r.Ok ? Green : Amber;
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); Label(r.DisplayLabel, c);
ImGuiNET.ImGui.TableNextColumn(); Label(r.NeedText, c);
ImGuiNET.ImGui.TableNextColumn(); Label(r.HaveText, c);
}
ImGuiNET.ImGui.EndTable();
}
}
finally
{
ImGuiNET.ImGui.PopTextWrapPos();
}
}
// ── Confirm ─────────────────────────────────────────────────────────
/// <summary>The Progression tab's Yes/No popup (outside the body child, like DrawConfirm).</summary>

View file

@ -37,6 +37,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.ImGuiBackend.Hud;
@ -186,7 +187,17 @@ internal sealed partial class SkillsFace : IImGuiPanel
private long _masteryPendingUntilMs;
private int _masteryPendingVersion;
public void OnShown()
// Shown / hidden exactly once per visible stretch, however often the host (or the Oracle embed) asks:
// the Progression subscription it takes in OnShownCore is given back in OnHiddenCore, once.
private readonly ShownLatch _life;
public SkillsFace() => _life = new ShownLatch(OnShownCore, OnHiddenCore);
public void OnShown() => _life.Show();
public void OnHidden() => _life.Hide();
private void OnShownCore()
{
PlayerProgressHooks.Want();
PlayerProgressHooks.RefreshSoon();
@ -196,22 +207,85 @@ internal sealed partial class SkillsFace : IImGuiPanel
ProgressionShown();
}
public void OnHidden() => ProgressionHidden();
private void OnHiddenCore() => ProgressionHidden();
public void Draw()
{
int req = Interlocked.Exchange(ref _requestedTab, -1);
if (req >= 0) _tab = req;
PlayerProgressHooks.Want();
Refresh();
ApplyProgressionRequest();
if (_tab == 2 && !ProgressionTabVisible) _tab = 0;
float w = Begin(out Vector2 origin, out Vector2 size);
DrawBody(w, origin, size, showOwnTabs: true);
End(origin, size);
_picker.Draw();
DrawMulti();
DrawConfirm();
DrawProgressionConfirm();
}
/// <summary>
/// Oracle-hosted body (the old Skills panel's tabs, without its frame or tab strip).
/// Called each frame the Oracle window shows a Skills / Attributes / Progress tab.
/// The first frame runs OnShown (via OracleSkillsEmbed's latch); OracleSkillsEmbed.Clear,
/// the Oracle window closing and the idle sweep run OnHidden. AC thread.
/// </summary>
public static void DrawEmbedded(int tab)
{
if (_embed == null)
{
_embed = new SkillsFace();
OracleSkillsEmbed.Bind(_embed.OnShown, _embed.OnHidden);
}
OracleSkillsEmbed.NoteDrawn(Environment.TickCount64);
_embed.DrawHosted(tab);
}
/// <summary>Selects Skills (0), Attributes (1) or Progress (2) on the next standalone Draw.</summary>
public static void RequestTab(int tab)
{
tab = tab < 0 ? 0 : tab > 2 ? 2 : tab;
Volatile.Write(ref _requestedTab, tab);
}
private static int _requestedTab = -1;
/// <summary>Shared instance that draws inside Oracle (no separate Skills window).</summary>
private static SkillsFace? _embed;
private void DrawHosted(int tab)
{
_tab = tab < 0 ? 0 : tab > 2 ? 2 : tab;
PlayerProgressHooks.Want();
Refresh();
ApplyProgressionRequest();
// Progress tab on a world without ILT: the tab stays selected and DrawProgression explains.
Vector2 avail = ImGuiNET.ImGui.GetContentRegionAvail();
float w = Math.Max(40f, avail.X);
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
DrawBody(w, origin, new Vector2(w, Math.Max(120f, avail.Y)), showOwnTabs: false);
_picker.Draw();
DrawMulti();
DrawConfirm();
DrawProgressionConfirm();
}
private void DrawBody(float w, Vector2 origin, Vector2 size, bool showOwnTabs)
{
DrawSummary(w);
DrawTabs(w);
if (showOwnTabs) DrawTabs(w);
if (_tab == 0) DrawToolbar(w);
if (_tab != 2) DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap());
float bodyH = Math.Max(60, showOwnTabs
? Remaining(origin, size) - GripOverlap()
: size.Y - (ImGuiNET.ImGui.GetCursorScreenPos().Y - origin.Y));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH));
@ -230,12 +304,6 @@ internal sealed partial class SkillsFace : IImGuiPanel
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
End(origin, size);
_picker.Draw();
DrawMulti();
DrawConfirm();
DrawProgressionConfirm();
}
// ── Data ────────────────────────────────────────────────────────────

View file

@ -0,0 +1,84 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/SkillsRouting.cs
// Where "open Skills" goes. Skills / Attributes / Progress live under RynthOracle
// when its tabs can be reached; otherwise the standalone Skills panel stays the
// way in, so nobody loses Skills (bar icon, /rc skills, the Character menu).
//
// "Can be reached" = the Oracle script window is registered AND Oracle has
// announced the bridge with `/rc oracle-skills` (OracleSkillsEmbed.TabsAvailable);
// an Oracle without the tabs never announces, so it counts as absent.
// ============================================================================
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.ScriptWindows;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal static class SkillsRouting
{
/// <summary>Oracle's main script window (UiWindow "RynthOracle/Oracle").</summary>
public const string OracleKey = OracleSkillsEmbed.OraclePanelKeyFragment;
/// <summary>Oracle provides the Skills / Attributes / Progress tabs now. Any thread.</summary>
public static bool OracleTabsAvailable => OracleSkillsEmbed.TabsAvailable(ScriptWindowRegistry.Has(OracleKey));
/// <summary>The bar's Skills icon shows exactly when Oracle can't provide the tabs. Any thread.</summary>
public static bool ShowSkillsBarIcon => !OracleTabsAvailable;
/// <summary>The Oracle command that selects a tab: skills, attrs or progress.</summary>
public static string OracleCommand(int tab) => tab switch
{
1 => "/ro attrs",
2 => "/ro progress",
_ => "/ro skills",
};
/// <summary>
/// Opens Skills (0), Attributes (1) or Progress (2): in Oracle when its tabs are there, else the
/// standalone Skills panel on that tab. Returns false when neither exists (no ImGui layer).
/// </summary>
public static bool Open(int tab)
{
if (OracleTabsAvailable)
{
ServerMenus.Run(OracleCommand(tab));
return true;
}
if (!ImGuiPanelHost.HasFace(SkillsFace.Title)) return false;
if (tab == 2)
{
SkillsFace.ShowProgression();
return true;
}
SkillsFace.RequestTab(tab);
if (!ImGuiPanelHost.IsOpen(SkillsFace.Title)) PanelRouter.Toggle(SkillsFace.Title);
return true;
}
/// <summary>
/// "/rc skills show|hide|toggle". With Oracle: show opens Oracle on Skills, hide closes Oracle only while
/// it is showing a Skills-family tab, toggle closes it when it already shows Skills. Without: the panel.
/// </summary>
public static bool SetOpen(bool? show)
{
if (!OracleTabsAvailable)
{
if (!ImGuiPanelHost.HasFace(SkillsFace.Title)) return false;
if (show == null || show.Value != ImGuiPanelHost.IsOpen(SkillsFace.Title))
PanelRouter.Toggle(SkillsFace.Title);
return true;
}
bool oracleOpen = ScriptWindowRegistry.IsOpen(OracleKey);
int tab = OracleSkillsEmbed.ActiveTab;
bool onSkills = oracleOpen && tab == 0;
if (show == false || (show == null && onSkills))
{
if (oracleOpen && tab >= 0) ScriptWindowRegistry.PlayerSetVisible(OracleKey, false);
return true;
}
if (show == true && onSkills) return true;
ServerMenus.Run(OracleCommand(0));
return true;
}
}

View file

@ -116,6 +116,39 @@ internal static class LogPaths
}
}
/// <summary>The shared native crash log every client appends to (see <see cref="RotateNativeCrashLogAtStartup"/>).</summary>
internal const string NativeCrashLogName = "native-crash.log";
/// <summary>A native-crash.log larger than this is moved aside when a client starts.</summary>
internal const long NativeCrashLogRotateBytes = 1L * 1024 * 1024;
/// <summary>
/// Engine-startup rotation of the SHARED native-crash.log (one fixed name for every client,
/// so <see cref="RotateAtStartup"/>'s per-PID rule does not cover it). Over
/// <see cref="NativeCrashLogRotateBytes"/> it moves to native-crash.log.old (replacing the
/// previous one). Must run BEFORE the native logger opens the file. A client that already has
/// it open (they open it share-delete) keeps writing to the moved file, which the logger's
/// own byte budget keeps bounded; nothing is lost, it just continues in the .old file.
/// Best-effort; never throws. Returns true when it moved the file.
/// </summary>
internal static bool RotateNativeCrashLogAtStartup()
{
try
{
string active = Path.Combine(LogDirectory, NativeCrashLogName);
if (!File.Exists(active)) return false;
if (new FileInfo(active).Length < NativeCrashLogRotateBytes) return false;
string rotated = active + ".old";
try { if (File.Exists(rotated)) File.Delete(rotated); } catch { }
File.Move(active, rotated);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Startup housekeeping: delete per-client session logs (and their .old
/// rotations) older than <see cref="MaxLogAge"/>. Each client launch produces a

View file

@ -41,10 +41,20 @@ internal static class EngineSettings
private static bool _serverMessageStream = true;
private static bool _flightRecorder = true;
private static bool _insertReleasesUi;
// Settings > Display: strip AC window chrome while windowed (default off).
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: 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).
private static bool _loadAllServerPlugins;
// Read-only, like EnableLargeAddressAlignmentFix: only a hand-set value is written back.
private static int _maxHotReloads = ReloadCapNotice.DefaultMaxHotReloads;
// "HoldReloadInWorld": opt-in (default off). On = an automatic engine reload waits until the player
// leaves the world, for at most _holdReloadInWorldMaxMinutes (ReloadInWorldGate).
private static bool _holdReloadInWorld;
private static int _holdReloadInWorldMaxMinutes = ReloadInWorldGate.DefaultMaxMinutes;
// "IltServerNames" / "IltHosts": what counts as Infinite Leaftide (Compatibility/IltInfo.cs).
// null = not in the file: IltDetect's defaults.
private static List<string>? _iltServerNames;
@ -53,6 +63,8 @@ internal static class EngineSettings
// For testing only (https, or http to this PC); read only, like MaxHotReloads.
private static string? _reportEndpoint;
private static Compatibility.AutoIdMode _autoIdMode = Compatibility.AutoIdPolicy.DefaultMode;
// "TransitionGate": default true. False = queued game actions are never held for a death / portal.
private static bool _transitionGate = true;
private static bool _loaded;
public static IReadOnlyList<string> PluginPaths
@ -221,7 +233,7 @@ internal static class EngineSettings
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
if (_enableImGuiBackend == value) return;
_enableImGuiBackend = value;
Save();
Save("EnableImGuiBackend");
}
}
@ -282,7 +294,7 @@ internal static class EngineSettings
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
if (_closeOnServerDisconnect == value) return;
_closeOnServerDisconnect = value;
Save();
Save("CloseOnServerDisconnect");
}
}
@ -364,7 +376,7 @@ internal static class EngineSettings
EnsureLoaded();
bool changed = enabled ? _disabledUiHooks.Remove(name) : _disabledUiHooks.Add(name);
if (changed)
Save();
Save("DisabledUiHooks");
}
/// <summary>"ServerMessageStream" in engine.json (default true): the kill switch for the
@ -410,7 +422,68 @@ internal static class EngineSettings
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
if (_insertReleasesUi == value) return;
_insertReleasesUi = value;
Save();
Save("InsertReleasesUi");
}
}
/// <summary>"BorderlessWindowed" in engine.json (default false, 2026-10-18): strip the AC
/// window caption and thick frame while staying windowed. Exclusive fullscreen is left alone,
/// and chrome is only ever given back to a window this setting stripped (AcWindowChrome).
/// Set in game in Settings > Display. From SilentKelpie's PR 6.</summary>
public static bool BorderlessWindowed
{
get
{
EnsureLoaded();
return _borderlessWindowed;
}
set
{
EnsureLoaded();
if (_borderlessWindowed == value) return;
_borderlessWindowed = value;
Save("BorderlessWindowed");
// AcWindowChrome applies the style from the game thread; keep this file free of
// HWND / UI refs so EngineSettingsTests can compile it alone.
}
}
/// <summary>"RememberWindowLayout" in engine.json (default true: Rynth panels have always been
/// remembered). Off: panel_state.txt is not overwritten and open panels are not reopened from
/// the last session. Does not touch the AC window itself (RememberAcWindowPosition).
/// Set in game in Settings > Display.</summary>
public static bool RememberWindowLayout
{
get
{
EnsureLoaded();
return _rememberWindowLayout;
}
set
{
EnsureLoaded();
if (_rememberWindowLayout == value) return;
_rememberWindowLayout = value;
Save("RememberWindowLayout");
}
}
/// <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>
public static bool RememberAcWindowPosition
{
get
{
EnsureLoaded();
return _rememberAcWindowPosition;
}
set
{
EnsureLoaded();
if (_rememberAcWindowPosition == value) return;
_rememberAcWindowPosition = value;
Save("RememberAcWindowPosition");
}
}
@ -429,6 +502,49 @@ internal static class EngineSettings
}
}
/// <summary>"HoldReloadInWorld" in engine.json (default false, opt-in; from SilentKelpie's PR 6):
/// when true, an automatic engine reload (the loader's file watcher, an engine deploy) waits until
/// the player logs out / reaches character select instead of reloading mid-session, for at most
/// <see cref="HoldReloadInWorldMaxMinutes"/>. A reload asked for by hand (ERl, the bar RL button,
/// /rc rl, the hotkey) is never held. A workaround for CoreCLR re-init crashes on stacked
/// mid-session reloads. Only a true is written to the file. Set in game in Settings > Misc.</summary>
public static bool HoldReloadInWorld
{
get
{
EnsureLoaded();
return _holdReloadInWorld;
}
set
{
EnsureLoaded();
if (_holdReloadInWorld == value) return;
_holdReloadInWorld = value;
Save("HoldReloadInWorld");
}
}
/// <summary>"HoldReloadInWorldMaxMinutes" in engine.json (default 10, valid 1-240): how long
/// <see cref="HoldReloadInWorld"/> holds a reload before it gives up, logs once, and reloads
/// anyway. The hold never lasts forever. Out-of-range values are clamped; only a non-default
/// value is written to the file.</summary>
public static int HoldReloadInWorldMaxMinutes
{
get
{
EnsureLoaded();
return _holdReloadInWorldMaxMinutes;
}
set
{
EnsureLoaded();
int v = ReloadInWorldGate.ClampMaxMinutes(value);
if (_holdReloadInWorldMaxMinutes == v) return;
_holdReloadInWorldMaxMinutes = v;
Save("HoldReloadInWorldMaxMinutes");
}
}
/// <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>
@ -475,7 +591,7 @@ internal static class EngineSettings
else list.RemoveAt(at);
// Replaced, never edited in place: IltInfo reads the old list on other threads.
_iltServerNames = list;
Save();
Save("IltServerNames");
return true;
}
@ -505,7 +621,29 @@ internal static class EngineSettings
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
if (_autoIdMode == value) return;
_autoIdMode = value;
Save();
Save("AutoIdMode");
}
}
/// <summary>"TransitionGate" in engine.json (default true): the world-transition gate
/// (Compatibility/WorldTransitionState.cs) holds the engine's queued game actions (casts, uses,
/// appraisals, chat commands...) while the character is dead or in portal space, and for 5 s
/// after. False turns the gate off entirely: nothing is held. Even with it on, a gate held
/// continuously for WorldTransitionState.MaxHoldMs opens by itself (logged once, counted in the
/// heartbeat as gateov=N) in case a revived character reads as dead or the portal flag sticks.</summary>
public static bool TransitionGate
{
get
{
EnsureLoaded();
return _transitionGate;
}
set
{
EnsureLoaded();
if (_transitionGate == value) return;
_transitionGate = value;
Save("TransitionGate");
}
}
@ -519,7 +657,7 @@ internal static class EngineSettings
return;
}
_pluginPaths.Add(full);
Save();
Save("PluginPaths");
}
public static void RemovePluginPath(int index)
@ -528,7 +666,7 @@ internal static class EngineSettings
if (index >= 0 && index < _pluginPaths.Count)
{
_pluginPaths.RemoveAt(index);
Save();
Save("PluginPaths");
}
}
@ -661,11 +799,32 @@ internal static class EngineSettings
(iruEl.ValueKind == JsonValueKind.True || iruEl.ValueKind == JsonValueKind.False))
_insertReleasesUi = iruEl.GetBoolean();
if (doc.RootElement.TryGetProperty("BorderlessWindowed", out var blwEl) &&
(blwEl.ValueKind == JsonValueKind.True || blwEl.ValueKind == JsonValueKind.False))
_borderlessWindowed = blwEl.GetBoolean();
if (doc.RootElement.TryGetProperty("RememberWindowLayout", out var rwlEl) &&
(rwlEl.ValueKind == JsonValueKind.True || rwlEl.ValueKind == JsonValueKind.False))
_rememberWindowLayout = rwlEl.GetBoolean();
if (doc.RootElement.TryGetProperty("RememberAcWindowPosition", out var rapEl) &&
(rapEl.ValueKind == JsonValueKind.True || rapEl.ValueKind == JsonValueKind.False))
_rememberAcWindowPosition = rapEl.GetBoolean();
if (doc.RootElement.TryGetProperty("MaxHotReloads", out var mhrEl) &&
mhrEl.ValueKind == JsonValueKind.Number &&
mhrEl.TryGetInt32(out int mhr))
_maxHotReloads = mhr;
if (doc.RootElement.TryGetProperty("HoldReloadInWorld", out var hriwEl) &&
(hriwEl.ValueKind == JsonValueKind.True || hriwEl.ValueKind == JsonValueKind.False))
_holdReloadInWorld = hriwEl.GetBoolean();
if (doc.RootElement.TryGetProperty("HoldReloadInWorldMaxMinutes", out var hrimEl) &&
hrimEl.ValueKind == JsonValueKind.Number &&
hrimEl.TryGetInt32(out int hrim))
_holdReloadInWorldMaxMinutes = ReloadInWorldGate.ClampMaxMinutes(hrim);
if (doc.RootElement.TryGetProperty("ReportEndpoint", out var repEl) &&
repEl.ValueKind == JsonValueKind.String &&
repEl.GetString() is { Length: > 0 } rep)
@ -676,6 +835,10 @@ internal static class EngineSettings
Compatibility.AutoIdPolicy.TryParseMode(aimEl.GetString(), out Compatibility.AutoIdMode aim))
_autoIdMode = aim;
if (doc.RootElement.TryGetProperty("TransitionGate", out var tgEl) &&
(tgEl.ValueKind == JsonValueKind.True || tgEl.ValueKind == JsonValueKind.False))
_transitionGate = tgEl.GetBoolean();
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
{
@ -732,21 +895,38 @@ internal static class EngineSettings
return list;
}
/// <summary>Every engine.json key EnsureLoaded reads or Save writes. Save rewrites these from
/// memory (one written only when not the default is left out, as before) and keeps every
/// other key as the file had it. A new engine.json setting goes here too
/// (tools/EngineSettingsTests checks this list against this file).</summary>
/// <summary>Every engine.json key EnsureLoaded reads or Save writes. A save writes only the keys
/// this client changed (Save(key); one written only when not the default is left out, which
/// removes it) and keeps every other key as the file had it. A new engine.json setting goes
/// here too, and its setter calls Save("Key") (tools/EngineSettingsTests checks this list and
/// the Save calls against this file).</summary>
internal static readonly HashSet<string> OwnedKeys = new(StringComparer.Ordinal)
{
"PluginPaths", "EnableImGuiShell", "EnablePlugins", "EnableDatShareHook",
"EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount",
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
"FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
"FlightRecorder", "InsertReleasesUi", "BorderlessWindowed", "RememberWindowLayout",
"RememberAcWindowPosition", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel",
"LoadAllServerPlugins",
"LoadAllServerPlugins", "TransitionGate",
"HoldReloadInWorld", "HoldReloadInWorldMaxMinutes",
};
// The engine.json keys this client changed this session. Every client keeps the whole settings
// in memory, so writing all of the engine's keys back let a client that never touched a setting
// put its stale value over another client's change (last writer won). Only these keys are
// written now; every other key keeps what the file holds. Idea from Silentkelpie (rynth PR #6).
private static readonly HashSet<string> _changedKeys = new(StringComparer.Ordinal);
private static readonly object _changedLock = new();
/// <summary>Saves engine.json after <paramref name="key"/> changed (only changed keys are written).</summary>
private static void Save(string key)
{
lock (_changedLock) _changedKeys.Add(key);
Save();
}
private static void Save()
{
try
@ -796,12 +976,24 @@ internal static class EngineSettings
w.WriteBoolean("EnableLargeAddressAlignmentFix", false);
if (_insertReleasesUi) // default false: leave the file as it was
w.WriteBoolean("InsertReleasesUi", true);
if (_borderlessWindowed) // default false: leave the file as it was
w.WriteBoolean("BorderlessWindowed", true);
if (!_rememberWindowLayout) // default true: leave the file as it was
w.WriteBoolean("RememberWindowLayout", 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
w.WriteBoolean("CloseOnServerDisconnect", false);
if (!_transitionGate) // default true: only a hand-set false is written
w.WriteBoolean("TransitionGate", false);
if (_loadAllServerPlugins) // default false: only a hand-set true is written
w.WriteBoolean("LoadAllServerPlugins", true);
if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written
w.WriteNumber("MaxHotReloads", _maxHotReloads);
if (_holdReloadInWorld) // default false: only a true is written
w.WriteBoolean("HoldReloadInWorld", true);
if (_holdReloadInWorldMaxMinutes != ReloadInWorldGate.DefaultMaxMinutes) // only a non-default value is written
w.WriteNumber("HoldReloadInWorldMaxMinutes", _holdReloadInWorldMaxMinutes);
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
@ -813,7 +1005,13 @@ internal static class EngineSettings
// Keep the keys others write (the launcher's), and swap the file in atomically.
string? existing = File.Exists(SettingsPath) ? File.ReadAllText(SettingsPath) : null;
byte[]? merged = EngineSettingsFile.Merge(existing, ms.ToArray(), OwnedKeys, out string? readError);
string[] changed;
lock (_changedLock)
{
changed = new string[_changedKeys.Count];
_changedKeys.CopyTo(changed);
}
byte[]? merged = EngineSettingsFile.Merge(existing, ms.ToArray(), OwnedKeys, out string? readError, changed);
if (merged == null)
{
RynthLog.Warn($"EngineSettings: not saving - {SettingsPath} can't be read ({readError}), and rewriting it would lose what it holds. The change holds until the client closes; fix or delete the file to save again.");

View file

@ -25,7 +25,15 @@ internal static class EngineSettingsFile
/// nothing to keep. Returns null, with <paramref name="error"/> set, when the existing file
/// isn't a readable JSON object: overwriting it would lose whatever it holds.
/// </summary>
public static byte[]? Merge(string? existingJson, byte[] ownedJson, ICollection<string> ownedKeys, out string? error)
/// <param name="changedKeys">
/// When given (and the file exists): only these of the engine's keys are taken from
/// <paramref name="ownedJson"/> (one it left out, at its default, is removed); every other
/// key, owned or not, keeps the file's value. So a client that changed one setting doesn't
/// write its stale copy of the others over what other clients saved since.
/// Idea from Silentkelpie (rynth PR #6); re-implemented against our key set.
/// </param>
public static byte[]? Merge(string? existingJson, byte[] ownedJson, ICollection<string> ownedKeys, out string? error,
ICollection<string>? changedKeys = null)
{
error = null;
JsonDocument? existing = null;
@ -55,8 +63,11 @@ internal static class EngineSettingsFile
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
// Only the changed keys when there's a file to keep the rest from.
bool onlyChanged = changedKeys != null && existing != null;
foreach (JsonProperty p in owned.RootElement.EnumerateObject())
{
if (onlyChanged && !changedKeys!.Contains(p.Name)) continue;
if (!written.Add(p.Name)) continue;
p.WriteTo(w);
}
@ -64,7 +75,7 @@ internal static class EngineSettingsFile
{
foreach (JsonProperty p in existing.RootElement.EnumerateObject())
{
if (ownedKeys.Contains(p.Name)) continue;
if (onlyChanged ? changedKeys!.Contains(p.Name) : ownedKeys.Contains(p.Name)) continue;
if (!written.Add(p.Name)) continue; // also drops a duplicate key in the old file
p.WriteTo(w);
}

View file

@ -134,6 +134,9 @@ internal static class ManagedPlugins
}
}
// How long the unload waits for the plugin contexts to be collected before naming the ones still held.
private const long UnloadCheckMs = 1500;
/// <summary>Unloads every retired plugin's context. Last step of EngineLifecycle.Shutdown.</summary>
public static void UnloadRetired()
{
@ -147,17 +150,59 @@ internal static class ManagedPlugins
}
#if ENGINE_CORECLR
string vaBefore = retired.Count > 0 ? Compatibility.AddressSpace.Describe() : "";
var refs = new List<(string Name, WeakReference Context)>(retired.Count);
foreach (Entry e in retired)
{
e.Context.Unload();
// Context.Unload only starts the collection; "after" is right after the request, so the
// NEXT reload's "va before" is where a context that never collects shows up.
if (retired.Count > 0)
RynthLog.Plugin($"ManagedPlugins: {retired.Count} plugin context(s) unloading: {string.Join(", ", retired.ConvertAll(e => e.Name))} (va before: {vaBefore}, after: {Compatibility.AddressSpace.Describe()}).");
refs.Add((e.Name, new WeakReference(e.Context, trackResurrection: true)));
}
retired.Clear(); // drop our own strong references before checking
// Context.Unload only starts the collection. A context still alive after a few collections
// is held by something (a thread, a timer, an event, a cached type in a shared context) and
// keeps everything the plugin loaded: every reload then loses that much address space for
// good (300-480 MB on some reloads, 2026-10-19). Name the ones that stay, so the culprit shows.
if (refs.Count > 0)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
while (refs.Exists(r => r.Context.IsAlive) && sw.ElapsedMilliseconds < UnloadCheckMs)
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (refs.Exists(r => r.Context.IsAlive)) System.Threading.Thread.Sleep(20);
}
var alive = refs.FindAll(r => r.Context.IsAlive).ConvertAll(r => r.Name);
RynthLog.Plugin($"ManagedPlugins: {refs.Count} plugin context(s) unloaded in {sw.ElapsedMilliseconds} ms (va before: {vaBefore}, after: {Compatibility.AddressSpace.Describe()})" +
(alive.Count == 0 ? "; all collected." : $"; STILL HELD after {UnloadCheckMs} ms (their memory stays): {string.Join(", ", alive)}."));
}
#endif
}
#if ENGINE_CORECLR
/// <summary>A plugin and its private dependencies (from the plugin's folder).</summary>
/// <summary>
/// Runtime\PluginShared: the RynthSuite plugins' common dependencies (RynthCore.PluginSdk,
/// PluginCore, MoonSharp, ...), installed with RynthCore so each plugin in the update feed stays
/// one DLL (v88, 2026-10-19). Each plugin still loads its own copy into its own collectible
/// context, so it unloads with the plugin. Null when the folder isn't there.
/// </summary>
internal static readonly string? SharedDir = FindSharedDir();
private static string? FindSharedDir()
{
try
{
// The shim sits in Runtime\ (the engine itself may run from Runtime\.engine_loads\).
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
if (a.GetName().Name != "RynthCore.Shim" || string.IsNullOrEmpty(a.Location)) continue;
string dir = Path.Combine(Path.GetDirectoryName(a.Location)!, "PluginShared");
return Directory.Exists(dir) ? dir : null;
}
}
catch { }
return null;
}
/// <summary>A plugin and its private dependencies (its own folder, then Runtime\PluginShared).</summary>
private sealed class PluginLoadContext : AssemblyLoadContext
{
private readonly string _dir;
@ -190,16 +235,28 @@ internal static class ManagedPlugins
string fx = Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location)!, name.Name + ".dll");
return File.Exists(fx) ? LoadFromAssemblyPath(fx) : null;
}
string candidate = Path.Combine(_dir, name.Name + ".dll");
return File.Exists(candidate) ? LoadFromFile(candidate) : null;
string? path = Pick(name.Name + ".dll");
return path != null ? LoadFromFile(path) : null;
}
// The plugin's own copy or the shared one; with both, the newer file (a dev build carries
// fresh dependencies beside it; a launcher update leaves stale ones beside a new plugin).
private string? Pick(string fileName)
{
string own = Path.Combine(_dir, fileName);
string? shared = SharedDir != null ? Path.Combine(SharedDir, fileName) : null;
bool hasOwn = File.Exists(own), hasShared = shared != null && File.Exists(shared);
if (hasOwn && hasShared)
return File.GetLastWriteTimeUtc(shared!) > File.GetLastWriteTimeUtc(own) ? shared : own;
return hasOwn ? own : hasShared ? shared : null;
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string candidate = Path.Combine(_dir, unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
string? path = Pick(unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
? unmanagedDllName
: unmanagedDllName + ".dll");
return File.Exists(candidate) ? LoadUnmanagedDllFromPath(candidate) : IntPtr.Zero;
return path != null ? LoadUnmanagedDllFromPath(path) : IntPtr.Zero;
}
}
#endif

View file

@ -25,5 +25,8 @@ internal static class PluginContractVersion
// server plugins declare their server in their manifest; from SilentKelpie's build).
// v87: GetWieldedItems (what the player wields and where, from the server's wield / contain /
// drop messages: EquipmentTracker; the client's own fields go stale, 2026-10-18).
public const uint Current = 87;
// v88: managed plugins find their common dependencies in Runtime\PluginShared (installed with
// RynthCore), so the update feed ships each managed plugin as one DLL; releases build the
// plugins managed (collectible: a reload frees them) and they declare minEngineApi 88.
public const uint Current = 88;
}

View file

@ -40,7 +40,12 @@ internal static partial class PluginManager
private readonly record struct PendingEnchantmentAdded(uint SpellId, double DurationSeconds);
private readonly record struct PendingEnchantmentRemoved(uint EnchantmentId);
private const int MaxPendingIncomingChats = 256;
// A /myquests reply is one line per quest flag (hundreds on a played character) and arrives
// in one burst; a slow pump tick (a busy plugin window) must not drop its head. Lines are short
// strings, so a deep queue costs little. Drops are counted and logged (DispatchQueuedChatWindowText).
private const int MaxPendingIncomingChats = 4096;
private static long _droppedIncomingChats; // lines dropped unheard since the last log
private static long _droppedIncomingChatsLoggedMs; // when that was last logged
private const int MaxPendingBusyCountEvents = 128;
private const int MaxPendingTargetChanges = 128;
private const int MaxPendingCombatModeChanges = 128;
@ -674,7 +679,10 @@ internal static partial class PluginManager
lock (PendingIncomingChatsLock)
{
if (_pendingIncomingChats.Count >= MaxPendingIncomingChats)
{
_pendingIncomingChats.Dequeue().Held?.Decide(eat: false); // dropped unheard: it shows
_droppedIncomingChats++;
}
_pendingIncomingChats.Enqueue(new PendingIncomingChat(text, chatType, held));
}
@ -1722,14 +1730,26 @@ internal static partial class PluginManager
System.Threading.Interlocked.Exchange(ref _chatPumpBeatMs, Environment.TickCount64);
PendingIncomingChat[] pending;
long dropped = 0;
lock (PendingIncomingChatsLock)
{
if (_pendingIncomingChats.Count == 0)
return;
// Report drops at most every 10 s (a flood would otherwise flood the log too).
long nowMs = Environment.TickCount64;
if (_droppedIncomingChats > 0 && nowMs - _droppedIncomingChatsLoggedMs >= 10_000)
{
dropped = _droppedIncomingChats;
_droppedIncomingChats = 0;
_droppedIncomingChatsLoggedMs = nowMs;
}
pending = _pendingIncomingChats.ToArray();
pending = _pendingIncomingChats.Count == 0 ? Array.Empty<PendingIncomingChat>() : _pendingIncomingChats.ToArray();
_pendingIncomingChats.Clear();
}
// Logged outside the lock: AC's main thread queues chat under it.
if (dropped > 0)
RynthLog.Plugin($"PluginManager: {dropped} incoming chat line(s) dropped before plugins heard them (queue full at {MaxPendingIncomingChats}).");
if (pending.Length == 0)
return;
unsafe
{
@ -1775,6 +1795,14 @@ internal static partial class PluginManager
}
eaten = HeldChatQueue.PluginsAteIt(eat, threw);
// RynthChat's Hide rules / standard filters live in the engine, not in a plugin, so
// without this a hidden line still printed in AC's own chat window. Only a held line
// can still be kept out (one already printed has gone); a failure lets it show.
if (!eaten && evt.Held != null)
{
try { eaten = UI.Data.ChatModel.ShouldHideInRetail(evt.Text, unchecked((int)evt.ChatType)); }
catch (Exception ex) { RynthLog.Plugin($"PluginManager: retail chat filter check failed ({ex.GetType().Name}: {ex.Message})."); }
}
}
finally
{

View file

@ -0,0 +1,123 @@
// ============================================================================
// RynthCore.Engine - ReloadInWorldGate.cs
// Optionally holds an automatic hot reload while the player is in the world.
//
// From SilentKelpie's RynthCore PR 6 (2026-10-16), reworked 2026-10-18 into an opt-in:
// stacked FileWatcher reloads mid-session were killing clients on his machine: the loader
// shut the engine down, then CoreCLR re-init AVed / never logged "Reload: complete".
// ReloadDeferral only waits for plugin blockers; it does not stop a quiet in-world unload.
// This gate waits with the old engine still mapped until the player is out of the world.
//
// Differences from the PR, all the owner's decisions:
// - OFF by default: engine.json "HoldReloadInWorld" (Settings > Misc, "Hold reloads while in
// the world"). Off, nothing here runs and a reload behaves exactly as before.
// - A reload asked for by hand (ERl, the bar RL button, /rc rl, the hotkey) is never held;
// only automatic ones (the file watcher, an engine deploy) are.
// - It never holds forever: after "HoldReloadInWorldMaxMinutes" (default 10) it gives up,
// logs once that it is reloading anyway, and the reload goes ahead.
//
// Pure: the "still hold?" query, clock, sleep and log are injected so tools\ReloadInWorldGateTests
// can run offline. EntryPoint wires it from DeferReloadWhilePluginsObject.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine;
internal static class ReloadInWorldGate
{
/// <summary>How often we ask again while holding for the world.</summary>
public static readonly TimeSpan DefaultPoll = TimeSpan.FromSeconds(2);
/// <summary>While waiting, the "still holding" line repeats this often (first line at once).</summary>
public static readonly TimeSpan DefaultLogEvery = TimeSpan.FromSeconds(30);
/// <summary>Default for engine.json "HoldReloadInWorldMaxMinutes".</summary>
public const int DefaultMaxMinutes = 10;
public const int MinMaxMinutes = 1;
public const int MaxMaxMinutes = 240;
/// <summary>Keeps a configured bound inside its valid range (1-240 minutes).</summary>
public static int ClampMaxMinutes(int minutes) => Math.Clamp(minutes, MinMaxMinutes, MaxMaxMinutes);
public enum Outcome
{
/// <summary>Not holding (off, by hand, or not in the world): reload at once.</summary>
Clear,
/// <summary>Was in the world, then left (or the hold was switched off / bypassed by hand); reload now.</summary>
ClearedAfterWait,
/// <summary>Still in the world at the bound: the hold gave up, reload anyway.</summary>
TimedOut,
}
/// <summary>
/// True when a reload should wait: the hold is switched on, the client is in the world, and
/// the reload is an automatic one. A reload asked for by hand is never held.
/// </summary>
public static bool ShouldHold(bool byHand, bool holdEnabled, bool inWorld)
=> holdEnabled && inWorld && !byHand;
/// <summary>
/// Polls <paramref name="stillHold"/> until it is false or <paramref name="maxWait"/> has passed
/// (then <see cref="Outcome.TimedOut"/>: the caller reloads anyway). A query that throws counts
/// as "not holding", so a broken gate cannot wedge the client.
/// </summary>
public static Outcome Run(
Func<bool> stillHold,
Action<string> log,
Action<string>? notify,
TimeSpan maxWait,
out TimeSpan waited,
Func<DateTime>? clock = null,
Action<TimeSpan>? sleep = null,
TimeSpan? poll = null,
TimeSpan? logEvery = null)
{
clock ??= static () => DateTime.UtcNow;
sleep ??= static t => Thread.Sleep(t);
TimeSpan pollSpan = poll ?? DefaultPoll;
TimeSpan logSpan = logEvery ?? DefaultLogEvery;
waited = TimeSpan.Zero;
if (!SafeHold(stillHold)) return Outcome.Clear;
DateTime start = clock();
log($"engine reload waiting: player is in the world (Hold reloads while in the world is on; loads after logout / character select, or after at most {maxWait.TotalMinutes:0.#} min).");
try
{
notify?.Invoke("player is in the world");
}
catch { /* chat must not abort the wait */ }
DateTime lastLog = start;
while (true)
{
// Never sleep past the bound: the give-up happens on time, not up to a poll late.
TimeSpan left = maxWait - (clock() - start);
sleep(left > TimeSpan.Zero && left < pollSpan ? left : pollSpan);
DateTime now = clock();
waited = now - start;
if (!SafeHold(stillHold))
{
log($"engine reload: hold released after {waited.TotalSeconds:0.0} s (left the world, or reload asked for by hand, or the hold was switched off); reloading now.");
return Outcome.ClearedAfterWait;
}
if (waited >= maxWait)
{
log($"engine reload: held {waited.TotalMinutes:0.#} min, reloading anyway (still in the world at the HoldReloadInWorldMaxMinutes bound of {maxWait.TotalMinutes:0.#} min).");
return Outcome.TimedOut;
}
if (now - lastLog >= logSpan)
{
lastLog = now;
log($"engine reload waiting: still in the world ({waited.TotalSeconds:0} s so far; loads after logout / character select, or at {maxWait.TotalMinutes:0.#} min).");
}
}
}
private static bool SafeHold(Func<bool> stillHold)
{
try { return stillHold(); }
catch { return false; } // fail open: a broken query must not wedge the client
}
}

View file

@ -0,0 +1,412 @@
// ============================================================================
// RynthCore.Engine - UI/AcWindowChrome.cs
// Settings > Display helpers for the Asheron's Call game HWND:
// - Borderless windowed: strip caption / thick frame while leaving the client
// windowed (not exclusive fullscreen). Chrome is only given back to a window
// WE stripped: that is recorded as an HWND property (SetProp) holding the
// window's style from before, which outlives an in-process engine hot reload
// and dies with the process. No marker and the setting off = hands off.
// - Remember placement (opt-in): persist the outer window rect per client
// (ac_window.<server-character>.txt) and put it back once after login.
// Original: SilentKelpie (RynthCore PR 6). Decisions live in AcWindowChromePolicy.
//
// Threading. Tick runs inside EndScene (the render callback) and only READS there
// (styles, rect, the marker); anything that changes the window - the style, a
// SetWindowPos that moves or resizes it - is posted to the game window's own WndProc
// (Win32Backend.PostToGameThread, the way pop-out windows are created), so it never
// runs inside the render call. Rect files are written by UiBackgroundWriter, never
// on the render thread. With no WndProc subclass (ImGui backend off) the feature
// stays inactive instead of touching the window from the render thread.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Plugins;
using static RynthCore.Engine.UI.AcWindowChromePolicy;
namespace RynthCore.Engine.UI;
internal static class AcWindowChrome
{
private const int GwlStyle = -16;
private const uint SwpNosize = 0x0001;
private const uint SwpNomove = 0x0002;
private const uint SwpNozorder = 0x0004;
private const uint SwpNoactivate = 0x0010;
private const uint SwpFramechanged = 0x0020;
// HWND properties: they live on the window, so they survive an engine hot reload.
private const string StyleProp = "RynthCore.AcWindowChrome.StyleBeforeBorderless";
private const string PlacementDoneProp = "RynthCore.AcWindowChrome.PlacementRestored";
private const long TickIntervalMs = 2000;
private const long SaveIntervalMs = 10000;
private const long NoKeyFallbackMs = 90000; // no character this long: use the shared file
private const long PostStuckMs = 10000; // a posted job that never ran may be posted again
private const long StyleRetryMs = 10000; // a style change that does not stick is not retried every tick
private static readonly object Sync = new();
private static readonly Action PostedWork = RunOnGameThread;
private static long _nextTickMs, _nextSaveMs, _firstTickMs, _workPostedAtMs, _nextStyleActionMs;
private static int _workPosted;
private static Rect? _lastWritten;
private static bool _loggedNoExecutor;
// ── Frame loop (EndScene): reads + posts only ────────────────────────
/// <summary>Call from the frame loop; throttled. Never changes the window itself.</summary>
public static void Tick(IntPtr hwnd)
{
if (hwnd == IntPtr.Zero) return;
long now = Environment.TickCount64;
if (now < _nextTickMs) return;
_nextTickMs = now + TickIntervalMs;
if (_firstTickMs == 0) _firstTickMs = now;
try
{
if (!ImGuiBackend.Win32Backend.CanRunOnGameThread)
{
// No WndProc subclass to run window changes from: stay out of the window.
if (!_loggedNoExecutor && (EngineSettings.BorderlessWindowed || EngineSettings.RememberAcWindowPosition))
{
_loggedNoExecutor = true;
RynthLog.UI("AcWindowChrome: no game-thread executor (ImGui backend off); display chrome inactive.");
}
return;
}
int style = GetWindowLong(hwnd, GwlStyle);
bool work = now >= Interlocked.Read(ref _nextStyleActionMs)
&& DecideBorderless(EngineSettings.BorderlessWindowed, ReadMarker(hwnd), style,
LooksExclusiveFullscreen(hwnd, style)).Action != ChromeAction.None;
if (EngineSettings.RememberAcWindowPosition && !PlacementDone(hwnd) && KeyReady(now, out _))
work = true;
if (work) PostWork(now);
MaybeSavePlacement(hwnd, now, style);
}
catch (Exception ex)
{
try { RynthLog.UI($"AcWindowChrome: tick failed - {ex.Message}"); } catch { }
}
}
/// <summary>A Settings > Display toggle changed: apply it on the game thread soon (not inline).</summary>
public static void RequestApply()
{
try
{
if (ImGuiBackend.Win32Backend.CanRunOnGameThread)
PostWork(Environment.TickCount64);
// else: Tick applies it once a game-thread executor exists.
}
catch (Exception ex)
{
try { RynthLog.UI($"AcWindowChrome: apply request failed - {ex.Message}"); } catch { }
}
}
private static void PostWork(long now)
{
// One job in flight; a job that never ran (window gone, reload) may be re-posted after a while.
if (Interlocked.CompareExchange(ref _workPosted, 1, 0) != 0 && now - _workPostedAtMs < PostStuckMs)
return;
_workPostedAtMs = now;
Volatile.Write(ref _workPosted, 1);
if (!ImGuiBackend.Win32Backend.PostToGameThread(PostedWork))
Volatile.Write(ref _workPosted, 0);
}
// ── Game thread (the game WndProc) ───────────────────────────────────
private static void RunOnGameThread()
{
Volatile.Write(ref _workPosted, 0);
try
{
IntPtr hwnd = ResolveGameHwnd();
if (hwnd == IntPtr.Zero) return;
lock (Sync)
{
if (EngineSettings.RememberAcWindowPosition && !PlacementDone(hwnd))
TryRestorePlacement(hwnd);
ApplyBorderless(hwnd);
}
}
catch (Exception ex)
{
try { RynthLog.UI($"AcWindowChrome: apply failed - {ex.Message}"); } catch { }
}
}
private static void ApplyBorderless(IntPtr hwnd)
{
int style = GetWindowLong(hwnd, GwlStyle);
ChromeDecision d = DecideBorderless(EngineSettings.BorderlessWindowed, ReadMarker(hwnd), style,
LooksExclusiveFullscreen(hwnd, style));
if (d.Action != ChromeAction.None)
Interlocked.Exchange(ref _nextStyleActionMs, Environment.TickCount64 + StyleRetryMs);
switch (d.Action)
{
case ChromeAction.Strip:
SetWindowLong(hwnd, GwlStyle, d.NewStyle);
SetProp(hwnd, StyleProp, new IntPtr(d.NewMarker));
Refresh(hwnd);
RynthLog.UI("AcWindowChrome: borderless windowed on.");
break;
case ChromeAction.Restore:
SetWindowLong(hwnd, GwlStyle, d.NewStyle);
RemoveProp(hwnd, StyleProp);
Refresh(hwnd);
RynthLog.UI("AcWindowChrome: window borders restored.");
break;
case ChromeAction.ClearMarker:
RemoveProp(hwnd, StyleProp);
RynthLog.UI("AcWindowChrome: borderless marker cleared (" + d.Reason + ").");
break;
}
}
// Style change only: same outer rect, non-client area rebuilt.
private static void Refresh(IntPtr hwnd)
=> SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0,
SwpNomove | SwpNosize | SwpNozorder | SwpNoactivate | SwpFramechanged);
private static void TryRestorePlacement(IntPtr hwnd)
{
if (!KeyReady(Environment.TickCount64, out string? key)) return; // still at the login screen
// One attempt per window, even a skipped one; the HWND carries it across a hot reload.
SetProp(hwnd, PlacementDoneProp, new IntPtr(1));
if (IsIconic(hwnd) || IsZoomed(hwnd)) return;
string path = PlacementPath(key);
if (!File.Exists(path)) return;
Rect saved;
try
{
if (!TryParsePlacement(File.ReadAllLines(path), out saved)) return;
}
catch (Exception ex)
{
try { RynthLog.UI($"AcWindowChrome: read placement failed - {ex.Message}"); } catch { }
return;
}
PlacementVerdict v = EvaluatePlacement(true, LooksExclusiveFullscreen(hwnd, GetWindowLong(hwnd, GwlStyle)),
saved, Monitors());
if (v != PlacementVerdict.Ok)
{
RynthLog.UI($"AcWindowChrome: saved placement not restored ({v}); leaving AC where it is.");
return;
}
SetWindowPos(hwnd, IntPtr.Zero, saved.Left, saved.Top, saved.Width, saved.Height,
SwpNozorder | SwpNoactivate);
_lastWritten = saved;
RynthLog.UI(FormattableString.Invariant(
$"AcWindowChrome: restored AC window to ({saved.Left},{saved.Top}) {saved.Width}x{saved.Height}."));
}
// ── Saving the rect (read on the render thread, written in the background) ──
private static void MaybeSavePlacement(IntPtr hwnd, long now, int style)
{
if (!EngineSettings.RememberAcWindowPosition) return;
if (now < _nextSaveMs) return;
// Not before the restore attempt: it would overwrite the saved rect with the launch position.
if (!PlacementDone(hwnd)) return;
_nextSaveMs = now + SaveIntervalMs;
TrySavePlacement(hwnd, style, now, force: false);
}
private static void TrySavePlacement(IntPtr hwnd, int style, long now, bool force)
{
if (!KeyReady(now, out string? key)) return;
if (IsIconic(hwnd) || IsZoomed(hwnd)) return;
if (!GetWindowRect(hwnd, out RECT wr)) return;
var cur = new Rect(wr.Left, wr.Top, wr.Right, wr.Bottom);
PlacementVerdict v = EvaluatePlacement(true, LooksExclusiveFullscreen(hwnd, style), cur, Monitors());
if (!force && !ShouldWritePlacement(v, cur, _lastWritten)) return;
if (v != PlacementVerdict.Ok) return;
_lastWritten = cur;
string path = PlacementPath(key);
UiBackgroundWriter.Enqueue("ac window placement", () => WritePlacement(path, cur));
}
private static void WritePlacement(string path, Rect r)
{
try
{
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(path, FormatPlacement(r));
}
catch (Exception ex)
{
try { RynthLog.UI($"AcWindowChrome: save placement failed - {ex.Message}"); } catch { }
}
}
/// <summary>Settings > Display "Save Layout Now". Runs on the render thread (a button in a
/// frame): everything that touches a file is queued to the background writer.</summary>
public static void SaveLayoutNow()
{
try
{
IntPtr hwnd = ResolveGameHwnd();
if (hwnd != IntPtr.Zero && EngineSettings.RememberAcWindowPosition)
TrySavePlacement(hwnd, GetWindowLong(hwnd, GwlStyle), Environment.TickCount64, force: true);
}
catch (Exception ex)
{
try { RynthLog.UI($"AcWindowChrome: save window failed - {ex.Message}"); } catch { }
}
try { ImGuiBackend.Hud.MonsterHudSettings.Save(); } catch { /* best-effort */ }
try
{
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);
});
}
}
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).
UiBackgroundWriter.Enqueue("panel state (save now)", PanelStateStore.Flush);
try
{
AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Saved open windows and HUD positions.", 1);
}
catch { /* chat may not be ready */ }
}
// ── Helpers ──────────────────────────────────────────────────────────
private static bool KeyReady(long now, out string? key)
=> TryResolveKey(SessionStateRegistry.LastServerName, SessionStateRegistry.LastCharacterName,
_firstTickMs == 0 ? 0 : now - _firstTickMs, NoKeyFallbackMs, out key);
private static string PlacementPath(string? key)
{
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(root, "RynthCore", PlacementFileName(key));
}
private static int ReadMarker(IntPtr hwnd) => unchecked((int)GetProp(hwnd, StyleProp).ToInt64());
private static bool PlacementDone(IntPtr hwnd) => GetProp(hwnd, PlacementDoneProp) != IntPtr.Zero;
/// <summary>Game HWND for Settings toggles (EntryPoint, else Win32Backend).</summary>
internal static IntPtr ResolveGameHwndForSettings() => ResolveGameHwnd();
private static IntPtr ResolveGameHwnd()
{
IntPtr hwnd = EntryPoint.GameHwnd;
if (hwnd != IntPtr.Zero) return hwnd;
try { return ImGuiBackend.Win32Backend.GameHwnd; } catch { return IntPtr.Zero; }
}
/// <summary>True when the outer rect fills a monitor and has no caption: exclusive fullscreen or
/// an already borderless fullscreen; do not fight it.</summary>
private static bool LooksExclusiveFullscreen(IntPtr hwnd, int style)
{
if ((style & WsCaption) != 0) return false;
if (!GetWindowRect(hwnd, out RECT wr)) return false;
IntPtr mon = MonitorFromWindow(hwnd, 2 /* MONITOR_DEFAULTTONEAREST */);
if (mon == IntPtr.Zero) return false;
var mi = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() };
if (!GetMonitorInfo(mon, ref mi)) return false;
int mw = mi.rcMonitor.Right - mi.rcMonitor.Left;
int mh = mi.rcMonitor.Bottom - mi.rcMonitor.Top;
int ww = wr.Right - wr.Left;
int wh = wr.Bottom - wr.Top;
return Math.Abs(ww - mw) <= 4 && Math.Abs(wh - mh) <= 4
&& Math.Abs(wr.Left - mi.rcMonitor.Left) <= 4
&& Math.Abs(wr.Top - mi.rcMonitor.Top) <= 4;
}
private static List<Rect> Monitors()
{
var list = new List<Rect>(4);
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, (IntPtr mon, IntPtr dc, ref RECT rc, IntPtr data) =>
{
var mi = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() };
if (GetMonitorInfo(mon, ref mi))
list.Add(new Rect(mi.rcMonitor.Left, mi.rcMonitor.Top, mi.rcMonitor.Right, mi.rcMonitor.Bottom));
return true;
}, IntPtr.Zero);
return list;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
private struct MONITORINFO
{
public int cbSize;
public RECT rcMonitor;
public RECT rcWork;
public uint dwFlags;
}
private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData);
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool IsZoomed(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern bool SetProp(IntPtr hWnd, string lpString, IntPtr hData);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetProp(IntPtr hWnd, string lpString);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr RemoveProp(IntPtr hWnd, string lpString);
}

View file

@ -0,0 +1,202 @@
// ============================================================================
// RynthCore.Engine - UI/AcWindowChromePolicy.cs
// The decisions behind Settings > Display for the Asheron's Call window, as pure
// functions (no HWND, no engine state) so tools\EngineSettingsTests can run them:
// - Borderless windowed: what to do given the setting, the "we stripped it" marker
// and the window's current style bits.
// - Window position: whether a saved or current rect is worth restoring / saving,
// and which file a client's rect lives in.
// AcWindowChrome does the Win32 work and asks these first.
// Idea and first version: SilentKelpie (RynthCore PR 6).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Engine.UI;
internal static class AcWindowChromePolicy
{
public const int WsCaption = 0x00C00000; // WS_BORDER | WS_DLGFRAME
public const int WsThickFrame = 0x00040000;
public const int WsSysMenu = 0x00080000;
public const int WsMinimizeBox = 0x00020000;
public const int WsMaximizeBox = 0x00010000;
public const int WsBorder = 0x00800000;
/// <summary>Caption + frame + sysmenu / min / max: the chrome Borderless Windowed removes.</summary>
public const int BorderChromeMask =
WsCaption | WsThickFrame | WsSysMenu | WsMinimizeBox | WsMaximizeBox | WsBorder;
// ── Borderless windowed ──────────────────────────────────────────────
internal enum ChromeAction
{
/// <summary>Leave the window alone.</summary>
None,
/// <summary>Remove the chrome and remember the style it had (NewMarker).</summary>
Strip,
/// <summary>Put the chrome we removed back (NewStyle) and drop the marker.</summary>
Restore,
/// <summary>The marker is stale (chrome is back already, or the marker is unusable): drop it.</summary>
ClearMarker,
}
internal readonly record struct ChromeDecision(ChromeAction Action, int NewStyle, int NewMarker, string Reason)
{
public static readonly ChromeDecision NoChange = new(ChromeAction.None, 0, 0, "");
}
/// <summary>
/// What to do about the window chrome right now.
/// <paramref name="marker"/> is the durable "WE stripped this window" record: the window's style
/// as it was before we stripped it (0 = never stripped by us). Chrome is only ever restored when
/// that marker exists, so a window that is chrome-less for any other reason (exclusive
/// fullscreen, an external borderless tool, a game option) is never touched with the setting off.
/// </summary>
public static ChromeDecision DecideBorderless(bool want, int marker, int style, bool looksExclusiveFullscreen)
{
bool hasChrome = (style & WsCaption) != 0;
if (want)
{
// Not ours to take over: it already looks like exclusive fullscreen.
if (marker == 0 && looksExclusiveFullscreen)
return new ChromeDecision(ChromeAction.None, 0, 0, "looks like exclusive fullscreen");
// No chrome: either we already did it (marker) or it never had any. Nothing to strip.
if (!hasChrome)
return ChromeDecision.NoChange;
// Strip. (Marker present with chrome back means the game put it back; strip again and
// remember this newer style.)
return new ChromeDecision(ChromeAction.Strip, style & ~BorderChromeMask, style, "strip");
}
// Setting off.
if (marker == 0)
return ChromeDecision.NoChange; // never ours: do nothing at all
if (hasChrome || (marker & WsCaption) == 0)
return new ChromeDecision(ChromeAction.ClearMarker, 0, 0, "marker stale");
return new ChromeDecision(ChromeAction.Restore, style | (marker & BorderChromeMask), 0, "restore");
}
// ── Window position ──────────────────────────────────────────────────
public const int MinWidth = 160, MinHeight = 120, MaxExtent = 16384;
private const int TitleProbeY = 16;
internal readonly record struct Rect(int Left, int Top, int Right, int Bottom)
{
public int Width => Right - Left;
public int Height => Bottom - Top;
public bool Contains(int x, int y) => x >= Left && x < Right && y >= Top && y < Bottom;
}
internal enum PlacementVerdict { Ok, OptedOut, ExclusiveFullscreen, TooSmall, TooLarge, OffScreen }
/// <summary>
/// Whether <paramref name="r"/> is a rect worth saving or restoring. Off-screen rects (a monitor
/// that is gone) are refused: the window's centre and the middle of its top edge must both be on
/// a monitor, so neither the window nor its title bar ends up unreachable.
/// </summary>
public static PlacementVerdict EvaluatePlacement(bool optedIn, bool looksExclusiveFullscreen,
Rect r, IReadOnlyList<Rect> monitors)
{
if (!optedIn) return PlacementVerdict.OptedOut;
if (looksExclusiveFullscreen) return PlacementVerdict.ExclusiveFullscreen;
if (r.Width < MinWidth || r.Height < MinHeight) return PlacementVerdict.TooSmall;
if (r.Width > MaxExtent || r.Height > MaxExtent) return PlacementVerdict.TooLarge;
int cx = r.Left + r.Width / 2;
if (!OnAnyMonitor(monitors, cx, r.Top + r.Height / 2) || !OnAnyMonitor(monitors, cx, r.Top + TitleProbeY))
return PlacementVerdict.OffScreen;
return PlacementVerdict.Ok;
}
private static bool OnAnyMonitor(IReadOnlyList<Rect> monitors, int x, int y)
{
for (int i = 0; i < monitors.Count; i++)
if (monitors[i].Contains(x, y)) return true;
return false;
}
/// <summary>Write only when the rect is saveable and differs from what was last written.</summary>
public static bool ShouldWritePlacement(PlacementVerdict verdict, Rect current, Rect? lastWritten)
=> verdict == PlacementVerdict.Ok && (lastWritten is null || lastWritten.Value != current);
// ── Per-client file ──────────────────────────────────────────────────
public const string SharedFileName = "ac_window.txt";
/// <summary>The per-client key: "&lt;server&gt;/&lt;character&gt;" (same shape as the other per-character
/// stores), or null while no character is known.</summary>
public static string? ClientKey(string? server, string? character)
{
string c = (character ?? string.Empty).Trim();
if (c.Length == 0) return null;
string s = (server ?? string.Empty).Trim();
return s.Length > 0 ? s + "/" + c : c;
}
/// <summary>
/// The file for a client's rect: "ac_window.&lt;safe name&gt;-&lt;hash&gt;.txt", or the shared
/// "ac_window.txt" when there is no key. The hash keeps names that sanitise alike apart.
/// </summary>
public static string PlacementFileName(string? key)
{
if (string.IsNullOrWhiteSpace(key)) return SharedFileName;
string k = key.Trim();
var sb = new StringBuilder(k.Length);
foreach (char ch in k)
{
if (sb.Length >= 48) break;
sb.Append(char.IsAsciiLetterOrDigit(ch) || ch == '-' ? char.ToLowerInvariant(ch) : '_');
}
uint h = 2166136261; // FNV-1a over the lower-cased key
foreach (char ch in k.ToLowerInvariant())
h = (h ^ ch) * 16777619;
return "ac_window." + sb + "-" + h.ToString("x8", CultureInfo.InvariantCulture) + ".txt";
}
/// <summary>
/// Whether the placement file can be read or written yet, and which key it uses. The character
/// is only known after login; the shared file is the fallback once a client has gone
/// <paramref name="fallbackAfterMs"/> without one.
/// </summary>
public static bool TryResolveKey(string? server, string? character, long msSinceFirstTick,
long fallbackAfterMs, out string? key)
{
key = ClientKey(server, character);
if (key != null) return true;
return msSinceFirstTick >= fallbackAfterMs; // key stays null: the shared file
}
// ── File format ──────────────────────────────────────────────────────
public static string FormatPlacement(Rect r)
=> string.Create(CultureInfo.InvariantCulture,
$"# RynthCore AC window placement - auto-generated.\nleft={r.Left}\ntop={r.Top}\nwidth={r.Width}\nheight={r.Height}\n");
public static bool TryParsePlacement(IEnumerable<string> lines, out Rect rect)
{
rect = default;
int left = 0, top = 0, width = 0, height = 0;
bool haveLeft = false, haveTop = false;
foreach (string raw in lines)
{
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#')) continue;
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string key = line[..eq].Trim();
if (!int.TryParse(line[(eq + 1)..].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) continue;
if (key.Equals("left", StringComparison.OrdinalIgnoreCase)) { left = n; haveLeft = true; }
else if (key.Equals("top", StringComparison.OrdinalIgnoreCase)) { top = n; haveTop = true; }
else if (key.Equals("width", StringComparison.OrdinalIgnoreCase)) width = n;
else if (key.Equals("height", StringComparison.OrdinalIgnoreCase)) height = n;
}
if (!haveLeft || !haveTop || width <= 0 || height <= 0) return false;
rect = new Rect(left, top, left + width, top + height);
return true;
}
}

View file

@ -1513,6 +1513,11 @@ internal class RynthOverlayWindow : Window
{
try
{
// Settings > Display "Remember Open Windows and Positions" (default on).
// Off: leave panels closed so a hand-arranged layout is not forced back.
if (!Plugins.EngineSettings.RememberWindowLayout)
return;
// Bar floating mode restores once AC's HWND is available. If we
// pop out before that, the FloatingPanelHost ctor takes its
// legacy code path (no marshal to game thread) and the layered

View file

@ -4,8 +4,8 @@
// "33.6E 42.1N", "0.5S, 101.2W"), for the chat window's right-click menu
// ("Arrow to ..." / "Go to ..." send them to RynthNav).
//
// Runs when a line's menu opens, never per frame. No engine dependencies:
// tools/ChatCoordTests compiles this file.
// Runs when a line's menu opens or a line is measured (the underlined links), never per
// frame. No engine dependencies besides ChatSpan: tools/ChatCoordTests compiles this file.
//
// To keep ordinary chat from turning into coordinates ("give me 5 s, 2 e"),
// a pair counts when both letters are capitals, or both numbers have a decimal
@ -53,6 +53,42 @@ internal static class ChatCoords
return found;
}
/// <summary>Cheap pre-check before the coordinate regex: a digit followed (soon) by a compass letter.
/// Never false for a line <see cref="Find"/> would find something in.</summary>
public static bool MayHaveCoords(string text)
{
for (int i = 0; i + 1 < text.Length; i++)
if (char.IsDigit(text[i]))
for (int j = i + 1; j < text.Length && j <= i + 2; j++)
if ("NnSsEeWw".IndexOf(text[j]) >= 0) return true;
return false;
}
/// <summary>
/// The rules' highlight spans with the coordinate links laid over them: a link keeps its own
/// colour (<paramref name="linkArgb"/>), and any highlight it overlaps is cut around it. The result
/// is sorted by start and never overlaps (given sorted, non-overlapping spans and coords).
/// </summary>
public static ChatSpan[] LinkSpans(ChatSpan[]? spans, List<ChatCoord> coords, uint linkArgb)
{
var result = new List<ChatSpan>();
foreach (ChatSpan s in spans ?? Array.Empty<ChatSpan>())
{
int a = s.Start, b = s.Start + s.Length;
foreach (ChatCoord c in coords)
{
int ca = c.Start, cb = c.Start + c.Length;
if (cb <= a || ca >= b) continue;
if (ca > a) result.Add(new ChatSpan(a, ca - a, s.Argb));
a = Math.Max(a, cb);
}
if (b > a) result.Add(new ChatSpan(a, b - a, s.Argb));
}
foreach (ChatCoord c in coords) result.Add(new ChatSpan(c.Start, c.Length, linkArgb));
result.Sort((x, y) => x.Start.CompareTo(y.Start));
return result.ToArray();
}
private static void Collect(Regex rx, string text, bool nsFirst, List<ChatCoord> found)
{
foreach (Match m in rx.Matches(text))

View file

@ -92,6 +92,8 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
protected internal override void Poll()
{
// Another client saved the shared settings: pick up its rules / filters (every 2 s at most).
ChatModel.PollSettingsFile();
try { PollLines(); }
finally
{
@ -392,14 +394,7 @@ internal static class ChatModel
};
/// <summary>The channel tab a ChatMessageType lands in; mirrors ChatClassifier.ChannelFor in the plugin.</summary>
public static string ChannelForType(int chatType) => (uint)chatType switch
{
0x02 or 0x03 or 0x04 or 0x0A or 0x0B or 0x0C or 0x12 or 0x13 => "Chat",
0x08 or 0x09 => "Channels",
0x00 or 0x05 or 0x0D or 0x14 or 0x17 or 0x18 or 0x19 or 0x1F => "System",
0x06 or 0x07 or 0x11 or 0x15 or 0x16 => "Combat",
_ => "Other",
};
public static string ChannelForType(int chatType) => ChatRetailVerdict.ChannelForType(chatType);
public static string ConditionLabel(string when)
{
@ -421,6 +416,11 @@ internal static class ChatModel
public static volatile bool ShowTimestamps = true;
/// <summary>Highlight your character's name (and MentionWords) in chat and channel lines.</summary>
public static volatile bool MentionHighlight = true;
/// <summary>
/// A line the rules or standard filters hide is also kept out of AC's own chat window, not
/// just RynthChat's (ShouldHideInRetail, from PluginManager's held-line verdict).
/// </summary>
public static volatile bool HideInRetailChat = true;
/// <summary>A short system beep on a new mention (at most every 3 s).</summary>
public static volatile bool MentionSound;
/// <summary>Extra words to highlight, comma-separated.</summary>
@ -739,6 +739,34 @@ internal static class ChatModel
return router;
}
// The retail-chat verdict's own router: no hit counting (RynthChat's pass already counts the
// same line), rebuilt when the rules or the name change. Pump thread only, like PumpRouter.
private static (long Version, string Name, ChatRouter Router)? _retailRouter;
/// <summary>
/// True when the rules or standard filters hide this incoming line, so AC shouldn't print
/// it either (HideInRetailChat). Pump thread (PluginManager, before the held line's verdict).
/// The channel is worked out the way the RynthChat plugin files the line (ChatRetailVerdict).
/// </summary>
internal static bool ShouldHideInRetail(string? text, int chatType)
{
if (!HideInRetailChat || string.IsNullOrEmpty(text)) return false;
string line = ChatSource.StripAcLinks(text, out _);
if (line.Length == 0) return false;
string name = PumpCharacterName();
long version = FiltersVersion;
var cached = _retailRouter;
ChatRouter router;
if (cached is { } c && c.Version == version && c.Name == name) router = c.Router;
else
{
router = new ChatRouter(Filters, mention: null, name, countHits: false);
_retailRouter = (version, name, router);
}
return ChatRetailVerdict.IsHidden(router, line, chatType);
}
/// <summary>A router for the rule editor's test box (UI thread, on an edit).</summary>
public static ChatRouter TestRouter()
{
@ -1309,13 +1337,54 @@ internal static class ChatModel
LoadSettings();
}
// Every client shares rynthchat_settings.json and saves its whole state, so a client that
// never re-read the file wrote back stale presets/rules over another client's change (last
// writer won; a ticked standard filter came back off). Each client now re-reads the file
// when someone else changes it (PollSettingsFile). SharedFileWatch remembers this client's own
// last write, so its own saves don't count as a change.
private static readonly SharedFileWatch SettingsWatch = new(pollMs: 2000);
/// <summary>
/// Pump thread (ChatSource.Poll): reloads the settings when another client saved the file.
/// Rules, standard filters, tabs and display options follow; this client's selected tab stays.
/// </summary>
internal static void PollSettingsFile()
{
if (Volatile.Read(ref _settingsLoaded) == 0) return;
try
{
string? json = SettingsWatch.Changed(Environment.TickCount64, SettingsPath); // null: nobody else saved
if (json == null) return;
RynthLog.UI("ChatModel: rynthchat_settings.json changed (another client saved it); reloading the rules and filters.");
LoadSettings(json, reload: true);
}
catch (Exception ex) { RynthLog.UI($"ChatModel: settings re-read failed ({ex.GetType().Name}: {ex.Message})."); }
}
private static void LoadSettings()
{
try
{
string path = SettingsPath;
if (!File.Exists(path)) return;
var dto = JsonSerializer.Deserialize(File.ReadAllText(path), RynthChatJsonContext.Default.RynthChatSettingsDto);
SettingsWatch.Seen(File.GetLastWriteTimeUtc(path));
LoadSettings(File.ReadAllText(path), reload: false);
}
catch (Exception ex)
{
RynthLog.UI($"ChatModel: settings load failed: {ex.Message}");
KeepUnreadable();
}
}
/// <param name="reload">Another client changed the file: presets it doesn't list go off, and
/// this client's selected tab is kept.</param>
private static void LoadSettings(string json, bool reload)
{
try
{
string path = SettingsPath;
var dto = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatSettingsDto);
if (dto == null) return;
if (dto.Version < SettingsVersion)
@ -1338,6 +1407,7 @@ internal static class ChatModel
AvaloniaOverlay.ChatCtrlGatedClickThrough = dto.CtrlGatedClickThrough;
ShowTimestamps = dto.ShowTimestamps;
MentionHighlight = dto.MentionHighlight;
HideInRetailChat = dto.HideInRetail ?? true; // absent before 2026-10-16: on
MentionSound = dto.MentionSound;
MentionWords = dto.MentionWords ?? "";
HistoryLines = ChatHistory.Clamp(dto.HistoryLines ?? 0); // absent before 2026-10-11: the default
@ -1358,6 +1428,13 @@ internal static class ChatModel
&& !IsBaseTab(rule.Tab) && !tabs.Contains(rule.Tab, StringComparer.OrdinalIgnoreCase))
tabs.Add(rule.Tab);
}
// The file lists only presets that are on or moved; on a reload every other one goes back off.
if (reload)
foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All)
{
preset.Enabled = false;
preset.Tab = "";
}
foreach (RynthChatPresetDto p in dto.Presets ?? Array.Empty<RynthChatPresetDto>())
{
var preset = p.Id == null ? null : RynthCore.Engine.UI.Panels.RynthChatPresets.Get(p.Id);
@ -1372,13 +1449,15 @@ internal static class ChatModel
_filters = rules.ToArray();
Interlocked.Increment(ref _filtersVersion);
if (!string.IsNullOrEmpty(dto.ActiveChannel) && AllTabs().Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase))
if (!reload && !string.IsNullOrEmpty(dto.ActiveChannel) && AllTabs().Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase))
ActiveChannel = dto.ActiveChannel;
else if (reload && !AllTabs().Contains(ActiveChannel, StringComparer.OrdinalIgnoreCase))
ActiveChannel = "All"; // the tab this client was on was removed elsewhere
}
catch (Exception ex)
catch (Exception ex) when (reload)
{
RynthLog.UI($"ChatModel: settings load failed: {ex.Message}");
KeepUnreadable();
// A half-written or broken file from another client: keep what this client has.
RynthLog.UI($"ChatModel: settings re-read skipped (unreadable: {ex.Message}).");
}
}
@ -1415,6 +1494,7 @@ internal static class ChatModel
ActiveChannel = ActiveChannel,
ShowTimestamps = ShowTimestamps,
MentionHighlight = MentionHighlight,
HideInRetail = HideInRetailChat,
MentionSound = MentionSound,
MentionWords = MentionWords,
// Left out at the default, so a file follows the default if it ever changes.
@ -1440,7 +1520,10 @@ internal static class ChatModel
string tmp = $"{path}.{Environment.ProcessId}.tmp"; // every client shares the file
try
{
File.WriteAllText(tmp, JsonSerializer.Serialize(dto, RynthChatJsonContext.Default.RynthChatSettingsDto));
string json = JsonSerializer.Serialize(dto, RynthChatJsonContext.Default.RynthChatSettingsDto);
// Before the swap: PollSettingsFile must see this text as ours, not another client's.
SettingsWatch.Saved(json);
File.WriteAllText(tmp, json);
File.Move(tmp, path, overwrite: true);
}
catch

View file

@ -142,6 +142,53 @@ internal static class ChatFilterPresets
L("Olthoi Swarm Gardener blisters your lower leg for 1 point of acid damage!", "Combat", EnemyCombat) },
new[] { L("You evaded Tusker Guard!", "Combat", EnemyCombat),
L("Bob says, \"it hit your head for 5 points of damage\"", "Chat", Say) }),
new("combat.melee_dealt", "Combat", "Melee / missile damage you deal",
"You slash … for N points of … damage!",
ChatMatchMode.Regex, @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*You \S+ .+ for \d+ points? of .+ damage", "chan:Combat",
new[] { L("You slash Drudge Slinker for 54 points of slashing damage!", "Combat", 22),
L("Recklessness! You slash Drudge for 80 points of slashing damage!", "Combat", 22) },
new[] { L("Bob says, \"You slash for fun\"", "Chat", Say) }),
new("combat.magic_dealt", "Combat", "Magic damage you deal",
"You … for N points with SpellName.",
ChatMatchMode.Regex, @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*You \S+ .+ for \d+ points? with ", "chan:Combat",
new[] { L("You freeze Drudge Slinker for 120 points with Frost Bolt VI.", "Combat", Magic) },
new[] { L("Bob says, \"points with Frost Bolt\"", "Chat", Say) }),
new("combat.melee_taken", "Combat", "Melee / missile damage you take",
"… your foot for N points of … damage!",
ChatMatchMode.Regex, @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*(?!You ).+ your [a-z ]+ for \d+ points? of .+ damage", "type:21",
new[] { L("Tusker Guard grazes your foot for 4 points of bludgeoning damage!", "Combat", EnemyCombat),
L("Critical hit! Olthoi Swarm Nymph nicks your head for 21 points of piercing damage!", "Combat", EnemyCombat) },
new[] { L("Bob says, \"your foot for 5 points\"", "Chat", Say) }),
new("combat.magic_taken", "Combat", "Magic damage you take",
"… you for N points with SpellName.",
ChatMatchMode.Regex, @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*(?!You ).+ you for \d+ points? with ", "chan:Combat",
new[] { L("Drudge Sorcerer scorches you for 40 points with Flame Bolt III.", "Combat", Magic) },
new[] { L("Bob says, \"you for 40 points with\"", "Chat", Say) }),
new("combat.recklessness", "Combat", "Recklessness hits",
"Recklessness! …",
ChatMatchMode.Contains, "Recklessness!", "chan:Combat",
new[] { L("Recklessness! You slash Drudge for 80 points of slashing damage!", "Combat", 22) },
new[] { L("Bob says, \"Recklessness!\"", "Chat", Say) }),
new("combat.sneak_attack", "Combat", "Sneak Attack hits",
"Sneak Attack! …",
ChatMatchMode.Contains, "Sneak Attack!", "chan:Combat",
new[] { L("Sneak Attack! You slash Drudge for 54 points of slashing damage!", "Combat", 22) },
new[] { L("Bob says, \"Sneak Attack!\"", "Chat", Say) }),
new("combat.periodic_healing", "Combat", "Periodic healing ticks",
"You receive N points of periodic healing.",
ChatMatchMode.Regex, @"^You receive \d+ points of periodic healing", "",
new[] { L("You receive 12 points of periodic healing.", "Other", Notice) },
new[] { L("Bob says, \"periodic healing\"", "Chat", Say) }),
new("combat.stamina", "Combat", "Stamina restore / spend",
"Restore / lose / gain stamina lines (Combat channel).",
ChatMatchMode.Regex, @"(?:restore|restores|regain|lose|loses) \d+ points? of (?:your )?stamina\b", "chan:Combat",
new[] { L("You cast Revitalize Self V and restore 40 points of your stamina.", "Combat", Magic) },
new[] { L("Bob says, \"restore 40 points of your stamina\"", "Chat", Say) }),
new("combat.mana", "Combat", "Mana restore / spend",
"Restore / gain / lose mana lines (Combat channel).",
ChatMatchMode.Regex, @"(?:restore|restores|regain|gain|gains|lose|loses) \d+ points? of (?:your )?mana\b|and also gain \d+ points of mana", "chan:Combat",
new[] { L("You cast Stamina to Mana Self V on yourself and lose 17 points of stamina and also gain 23 points of mana", "Combat", Magic) },
new[] { L("Bob says, \"gain 23 points of mana\"", "Chat", Say) }),
// ── Notices ─────────────────────────────────────────────────────
new("notice.busy", "Notices", "You're too busy",
@ -179,6 +226,63 @@ internal static class ChatFilterPresets
ChatMatchMode.StartsWith, "[LFG]", "",
new[] { L("[LFG] Bob says, \"LF tank for the Graveyard\"", "Other", ServerChannel) },
Array.Empty<(string, string, int)>()),
// ── Combat extras and items (UB-IT ChatFilterTool / classic ChatHandler) ──────
new("combat.attack_resists", "Combat", "Your spells resisted",
"A target resists one of your spells.",
ChatMatchMode.Contains, " resists your spell", "chan:Combat",
new[] { L("Drudge Slinker resists your spell", "Combat", EnemyCombat) },
new[] { L("Bob says, \"it resists your spell\"", "Chat", Say) }),
new("combat.defense_resists", "Combat", "You resist spells",
"You resist a spell cast by a monster.",
ChatMatchMode.StartsWith, "You resist the spell cast by ", "chan:Combat",
new[] { L("You resist the spell cast by Drudge Sorcerer", "Combat", EnemyCombat) },
new[] { L("Bob says, \"You resist the spell cast by him\"", "Chat", Say) }),
new("combat.dirty_fighting", "Combat", "Dirty Fighting procs",
"Dirty Fighting assault announcements.",
ChatMatchMode.StartsWith, "Dirty Fighting! ", "",
new[] { L("Dirty Fighting! Bob delivers a Traumatic Assault to Drudge!", "Combat", EnemyCombat) },
new[] { L("Bob says, \"Dirty Fighting!\"", "Chat", Say) }),
new("combat.missile_miss", "Combat", "Missile hit the environment",
"Your missile attack hit the environment.",
ChatMatchMode.StartsWith, "Your missile attack hit the environment", "",
new[] { L("Your missile attack hit the environment.", "Combat", EnemyCombat) },
Array.Empty<(string, string, int)>()),
new("item.heal_ok", "Items", "Healing kit success",
"You heal yourself for N Health points…",
ChatMatchMode.Contains, " heal yourself for ", "",
new[] { L("You heal yourself for 80 Health points. Your Treated Healing Kit has 16 uses left.", "Other", Notice) },
new[] { L("Bob says, \"heal yourself for fun\"", "Chat", Say) }),
new("item.salvage", "Items", "Salvage results",
"You obtain … using your knowledge of …",
ChatMatchMode.Regex, @"^You obtain .+ using your knowledge of ", "",
new[] { L("You obtain 12 Steel (ws 7.00) using your knowledge of Weapon Tinkering.", "Other", Notice) },
Array.Empty<(string, string, int)>()),
new("item.aetheria_surge", "Items", "Aetheria surges",
"Aetheria surges on…",
ChatMatchMode.StartsWith, "Aetheria surges on", "",
new[] { L("Aetheria surges on Bob, increasing his damage.", "Other", Notice) },
Array.Empty<(string, string, int)>()),
new("item.banked_lum", "Items", "Banked luminance",
"You've banked N Luminance.",
ChatMatchMode.StartsWith, "You've banked ", "",
new[] { L("You've banked 1,250 Luminance.", "Other", Notice) },
Array.Empty<(string, string, int)>()),
new("social.kill_task", "Social", "Kill task complete",
"You have killed N Xs! Your task is complete!",
ChatMatchMode.Regex, @"^You have killed \d+ .+Your task is complete!", "",
new[] { L("You have killed 50 Drudges! Your task is complete!", "Other", Notice) },
Array.Empty<(string, string, int)>()),
new("social.kill_task_progress", "Social", "Kill task progress",
"You have killed N Xs! You must kill M to complete your task.",
ChatMatchMode.Regex, @"^You have killed \d+ .+! You must kill \d+ to complete your task\.", "",
new[] { L("You have killed 12 Drudges! You must kill 50 to complete your task.", "Other", Notice) },
Array.Empty<(string, string, int)>()),
new("cast.expires", "Casting", "Spell expiry",
"… has expired. (does not spare rares — use Standard filters for that).",
ChatMatchMode.Contains, "has expired.", "type:7",
new[] { L("Strength Self VII has expired.", "Combat", Magic) },
new[] { L("Bob tells you, \"has expired.\"", "Chat", Tell) }),
};
public static ChatFilterPreset? Get(string id)

View file

@ -0,0 +1,66 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ChatRetailVerdict.cs
// Whether RynthChat's Hide rules / standard filters keep an incoming line out of
// AC's own chat window too (ChatModel.ShouldHideInRetail, asked from the plugin
// pump before a held line's verdict). The pure part, so tools/ChatFilterTests can
// run the real router over it: which channel the RynthChat plugin files the line
// under, and whether the rules hide it.
//
// Idea from Silentkelpie (rynth PR 6, 2026.10.16.23). The channel order follows the
// plugin's ChatBuffer.Add: RynthAi item info, then "[Rynth..." output, then a
// [General]/[Trade]-style tag, then the chat type.
// ============================================================================
using System;
namespace RynthCore.Engine.UI.Data;
internal static class ChatRetailVerdict
{
/// <summary>RynthAi's item info prefix (RynthChat's ChatClassifier.IsItemInfo): the Items tab.</summary>
public const string ItemInfoPrefix = "[RynthAi Item] ";
/// <summary>
/// The channel tab the RynthChat plugin files an incoming line under, so a rule held to a
/// channel ("chan:Channels") sees the same channel for the retail verdict as for RynthChat.
/// </summary>
public static string ChannelFor(string line, int chatType)
{
if (line.StartsWith(ItemInfoPrefix, StringComparison.Ordinal)) return "Items";
if (line.StartsWith("[Rynth", StringComparison.OrdinalIgnoreCase)) return "Rynth";
if (IsChannelTagged(line)) return "Channels";
return ChannelForType(chatType);
}
/// <summary>The channel tab for an AC ChatMessageType alone.</summary>
public static string ChannelForType(int chatType) => (uint)chatType switch
{
0x02 or 0x03 or 0x04 or 0x0A or 0x0B or 0x0C or 0x12 or 0x13 => "Chat",
// 0x08/0x09 = retail channel; 0x1C (28) = ILT/ACECustom tagged [Trade]/[General] lines.
0x08 or 0x09 or 0x1C => "Channels",
0x00 or 0x05 or 0x0D or 0x14 or 0x17 or 0x18 or 0x19 or 0x1F => "System",
0x06 or 0x07 or 0x11 or 0x15 or 0x16 => "Combat",
_ => "Other",
};
/// <summary>The RynthChat plugin's channel tags (ChatClassifier.IsChannelTagged): "[Trade] ..." etc.</summary>
public static bool IsChannelTagged(string text) =>
text.Length > 0 && text[0] == '['
&& (text.StartsWith("[General]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Trade]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[LFG]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Roleplay]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Society]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Celestial Hand]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Eldrytch Web]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Radiant Blood]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Admin]", StringComparison.OrdinalIgnoreCase));
/// <summary>
/// True when <paramref name="router"/> (the rules, then the ticked standard filters) hides the
/// line. A rule or filter that only moves or copies a line to a tab is not a hide: that line
/// still prints in AC's window.
/// </summary>
public static bool IsHidden(ChatRouter router, string line, int chatType) =>
router.Evaluate(line, ChannelFor(line, chatType), chatType, null).Hidden;
}

View file

@ -57,6 +57,8 @@ internal sealed class RynthChatSettingsDto
[JsonPropertyName("activeChannel")] public string? ActiveChannel { get; set; }
[JsonPropertyName("showTimestamps")] public bool ShowTimestamps { get; set; } = true;
[JsonPropertyName("mentionHighlight")] public bool MentionHighlight { get; set; } = true;
/// <summary>Hidden lines are also kept out of AC's chat window; null (older files) = on.</summary>
[JsonPropertyName("hideInRetail")] public bool? HideInRetail { get; set; }
[JsonPropertyName("mentionSound")] public bool MentionSound { get; set; }
[JsonPropertyName("mentionWords")] public string? MentionWords { get; set; }
// 2026-10-08: per-kind line colours (ChatLineColors), { "say": "#RRGGBB", "chan:General": ..., "tab:Chat": ... };

View file

@ -676,22 +676,22 @@ internal static unsafe class DamageCommands
MonstersPanel.Rule? from = string.IsNullOrEmpty(copyFrom) ? null
: rules.Rules.Find(r => !IsDefault(r) && r.Name.Equals(copyFrom, StringComparison.OrdinalIgnoreCase));
MonstersPanel.Rule clone = CopyOfDefault(from ?? s, name);
if (from != null) { clone.OffhandId = from.OffhandId; clone.PetDamage = from.PetDamage; clone.PreferredDamage = from.PreferredDamage; } // a name rule's own choices, kept
if (from != null) { clone.OffhandId = from.OffhandId; clone.PetDamage = from.PetDamage; clone.AttackPower = from.AttackPower; clone.Kite = from.Kite; clone.PreferredDamage = from.PreferredDamage; } // a name rule's own choices, kept
rules.Rules.Insert(defIdx >= 0 ? defIdx + 1 : 0, clone);
return clone;
}
/// <summary>
/// A new rule named <paramref name="name"/> with Default's settings. Off hand, pet and preferred
/// damage are left on "follow Default" (0 / PAuto / Auto) rather than copied, so a later change
/// on the DEFAULT line still reaches it.
/// A new rule named <paramref name="name"/> with Default's settings. Off hand, pet, attack
/// power, kite and preferred damage are left on "follow Default" (0 / PAuto / Default /
/// Default / Auto) rather than copied, so a later change on the DEFAULT line still reaches it.
/// </summary>
private static MonstersPanel.Rule CopyOfDefault(MonstersPanel.Rule s, string name) => new()
{
Name = name, Category = s.Category,
MatchExpression = "", // an exact-name rule matches by name, not by a (possibly false) expression
Priority = s.Priority, DamageType = s.DamageType, WeaponId = s.WeaponId, OffhandId = 0,
ExVuln = s.ExVuln, PetDamage = "PAuto", PreferredDamage = "Auto",
ExVuln = s.ExVuln, PetDamage = "PAuto", AttackPower = "Default", Kite = "Default", PreferredDamage = "Auto",
Fester = s.Fester, Broadside = s.Broadside, GravityWell = s.GravityWell,
Imperil = s.Imperil, Yield = s.Yield, Vuln = s.Vuln,
UseArc = s.UseArc, UseBolt = s.UseBolt, UseRing = s.UseRing, UseStreak = s.UseStreak, UseBlast = s.UseBlast, UseWall = s.UseWall,
@ -793,6 +793,14 @@ internal static unsafe class DamageCommands
/// <summary>Rule.OffhandId as RynthAi reads it: 0 = follow the DEFAULT line, 1-4 a mode, anything else an item id.</summary>
public static readonly string[] OffhandModeNames = { "Default", "Auto", "Shield", "Dual wield", "None" };
/// <summary>Rule.AttackPower choices, spelled as RynthAi reads them (AttackPowerModes).</summary>
public static readonly string[] AttackPowerModes =
{ "Default", "High", "Reckless", "Variable", "Reckless + Variable" };
/// <summary>Rule.Kite choices, spelled as RynthAi reads them (KiteModes).</summary>
public static readonly string[] KiteModes =
{ "Default", "Off", "PullAway" };
/// <summary>Rule.PetDamage choices; "PAuto" is shown as Auto.</summary>
public static readonly string[] PetDamageTypes =
{ "PAuto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };

View file

@ -0,0 +1,167 @@
// ============================================================================
// RynthCore.Engine - UI/Data/EnlRowConverters.cs
// Lenient readers for the Enl calculator's row arrays (levels / materials / chain
// in the Progression snapshot). The calculator is an add-on of the planner: a bad
// field in it must not turn the whole Progression snapshot into "unavailable" (the
// default for a JsonException), which would also hide the Augmentation planner and
// the attribute raiser. So:
// - null, or anything that is not an array, reads as an empty array;
// - a row that is not an object is skipped;
// - a field of the wrong type keeps its default, other fields of the row still read;
// - unknown fields are ignored; at most MaxRows rows are kept (RynthILT sends 100 at most).
// Read only (the engine never writes this JSON). No reflection: safe under trimming / NativeAOT.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Engine.UI.Data;
/// <summary>Reads a JSON array of row objects, tolerating whatever else shows up.</summary>
internal abstract class EnlRowsConverter<TRow> : JsonConverter<TRow[]> where TRow : class
{
/// <summary>Rows kept per array; the producer's own cap is 100 (levels).</summary>
internal const int MaxRows = 200;
// A JSON null reaches Read (and becomes an empty array) instead of null.
public override bool HandleNull => true;
/// <summary>Reads one row. The reader is on its StartObject; leave it on the matching EndObject.</summary>
protected abstract TRow ReadRow(ref Utf8JsonReader reader);
public override TRow[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartArray)
{
reader.Skip(); // a scalar stays as it is, an object is skipped whole
return Array.Empty<TRow>();
}
var rows = new List<TRow>();
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
reader.Skip();
continue;
}
TRow row = ReadRow(ref reader);
if (rows.Count < MaxRows) rows.Add(row);
}
return rows.Count == 0 ? Array.Empty<TRow>() : rows.ToArray();
}
public override void Write(Utf8JsonWriter writer, TRow[] value, JsonSerializerOptions options)
=> throw new NotSupportedException("The Enl calculator rows are read-only.");
// -- Field readers: the reader is on the value; each consumes exactly that value. --
protected static int ReadInt(ref Utf8JsonReader reader, int fallback = 0)
{
long v = ReadLong(ref reader, fallback);
return v > int.MaxValue ? int.MaxValue : v < int.MinValue ? int.MinValue : (int)v;
}
protected static long ReadLong(ref Utf8JsonReader reader, long fallback = 0)
{
switch (reader.TokenType)
{
case JsonTokenType.Number:
if (reader.TryGetInt64(out long l)) return l;
if (reader.TryGetDouble(out double d) && double.IsFinite(d))
return d >= long.MaxValue ? long.MaxValue : d <= long.MinValue ? long.MinValue : (long)d;
return fallback;
case JsonTokenType.String:
return long.TryParse(reader.GetString(), NumberStyles.Integer | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out long s) ? s : fallback;
default:
reader.Skip();
return fallback;
}
}
protected static bool ReadBool(ref Utf8JsonReader reader, bool fallback = false)
{
switch (reader.TokenType)
{
case JsonTokenType.True: return true;
case JsonTokenType.False: return false;
default:
reader.Skip();
return fallback;
}
}
protected static string ReadString(ref Utf8JsonReader reader, string fallback = "")
{
switch (reader.TokenType)
{
case JsonTokenType.String: return reader.GetString() ?? fallback;
case JsonTokenType.Number: return Encoding.UTF8.GetString(reader.ValueSpan);
default:
reader.Skip();
return fallback;
}
}
/// <summary>Moves to the next property name of the object being read; false at its EndObject.</summary>
protected static bool NextProperty(ref Utf8JsonReader reader)
=> reader.Read() && reader.TokenType == JsonTokenType.PropertyName;
}
internal sealed class EnlLevelRowsConverter : EnlRowsConverter<EnlLevelRow>
{
protected override EnlLevelRow ReadRow(ref Utf8JsonReader reader)
{
var row = new EnlLevelRow();
while (NextProperty(ref reader))
{
if (reader.ValueTextEquals("t")) { reader.Read(); row.Level = ReadInt(ref reader); }
else if (reader.ValueTextEquals("item")) { reader.Read(); row.Item = ReadString(ref reader, "-"); }
else if (reader.ValueTextEquals("count")) { reader.Read(); row.Count = ReadInt(ref reader); }
else if (reader.ValueTextEquals("lum")) { reader.Read(); row.Lum = ReadString(ref reader, "-"); }
else if (reader.ValueTextEquals("ok")) { reader.Read(); row.Ok = ReadBool(ref reader); }
else { reader.Read(); reader.Skip(); }
}
return row;
}
}
internal sealed class EnlMaterialRowsConverter : EnlRowsConverter<EnlMaterialRow>
{
protected override EnlMaterialRow ReadRow(ref Utf8JsonReader reader)
{
var row = new EnlMaterialRow();
while (NextProperty(ref reader))
{
if (reader.ValueTextEquals("label")) { reader.Read(); row.Label = ReadString(ref reader); }
else if (reader.ValueTextEquals("need")) { reader.Read(); row.Need = ReadString(ref reader, "0"); }
else if (reader.ValueTextEquals("have")) { reader.Read(); row.Have = ReadString(ref reader, "0"); }
else if (reader.ValueTextEquals("ok")) { reader.Read(); row.Ok = ReadBool(ref reader); }
else { reader.Read(); reader.Skip(); }
}
return row;
}
}
internal sealed class EnlChainRowsConverter : EnlRowsConverter<EnlChainRow>
{
protected override EnlChainRow ReadRow(ref Utf8JsonReader reader)
{
var row = new EnlChainRow();
while (NextProperty(ref reader))
{
if (reader.ValueTextEquals("label")) { reader.Read(); row.Label = ReadString(ref reader); }
else if (reader.ValueTextEquals("need")) { reader.Read(); row.Need = ReadLong(ref reader); }
else if (reader.ValueTextEquals("have")) { reader.Read(); row.Have = ReadLong(ref reader); }
else if (reader.ValueTextEquals("ok")) { reader.Read(); row.Ok = ReadBool(ref reader); }
else if (reader.ValueTextEquals("craft")) { reader.Read(); row.Craft = ReadBool(ref reader); }
else { reader.Read(); reader.Skip(); }
}
return row;
}
}

View file

@ -141,9 +141,55 @@ internal sealed class LootEditItemRequestDto
public bool ToOpenProfile { get; set; }
/// <summary>Also require the item's T11 attributes (added 2026-10-07; an older RynthAi ignores it).</summary>
public bool IncludeT11 { get; set; }
/// <summary>The attribute checklist's choices (added 2026-10-18); null: every row at its default.</summary>
public List<LootEditItemChoiceDto>? Choices { get; set; }
public int Seq { get; set; }
}
/// <summary>One checklist row as the player set it (LootEditWire's LootEditItemChoice).</summary>
internal sealed class LootEditItemChoiceDto
{
public string Id { get; set; } = string.Empty;
public bool On { get; set; }
/// <summary>A comparison code (LootAttrOps); -1 = the row's default.</summary>
public int Op { get; set; } = -1;
/// <summary>The typed value; empty = the item's own.</summary>
public string Value { get; set; } = string.Empty;
}
/// <summary>One row of the popup's attribute checklist (LootEditWire's LootEditItemAttribute).</summary>
internal sealed class LootEditItemAttributeDto
{
public string Id { get; set; } = string.Empty;
public string Group { get; set; } = string.Empty;
public string Label { get; set; } = string.Empty;
public string ItemValue { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
public int Op { get; set; }
public List<int> Ops { get; set; } = new();
public bool Editable { get; set; }
public bool On { get; set; }
public string Tip { get; set; } = string.Empty;
}
/// <summary>The checklist's comparison codes (LootSdk LootItemAttributeOp) and how the popup labels them.</summary>
internal static class LootAttrOps
{
public const int AtLeast = 0, Exactly = 1, AtMost = 2, Not = 3, SpellExact = 10, SpellOrBetter = 11, SpellAnyTier = 12;
public static string Label(int op) => op switch
{
AtLeast => ">=",
Exactly => "=",
AtMost => "<=",
Not => "not",
SpellExact => "exact",
SpellOrBetter => "or better",
SpellAnyTier => "any tier",
_ => "?",
};
}
/// <summary>The rule an item makes and what an add did (LootEditWire's LootEditItemDraft).</summary>
internal sealed class LootEditItemDraftDto
{
@ -172,6 +218,10 @@ internal sealed class LootEditItemDraftDto
public int RuleCount { get; set; }
public string OrderNote { get; set; } = string.Empty;
public List<string> Notes { get; set; } = new();
/// <summary>RynthAi has the attribute checklist (added 2026-10-18; false from an older one: the T11 box shows instead).</summary>
public bool AttributesSupported { get; set; }
/// <summary>The item's checklist rows in display order (added 2026-10-18).</summary>
public List<LootEditItemAttributeDto> Attributes { get; set; } = new();
public bool Added { get; set; }
public string Message { get; set; } = string.Empty;
}

View file

@ -8,6 +8,7 @@
// ============================================================================
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
@ -171,6 +172,94 @@ internal sealed class EnlPlanner
[JsonPropertyName("spendFirst")] public bool SpendFirst { get; set; }
[JsonPropertyName("checkEvery")] public int CheckEvery { get; set; }
[JsonPropertyName("status")] public string Status { get; set; } = "";
// Enl calculator (RynthILT's IltProgression.AppendEnlCalculatorJson; Silentkelpie's rynth PR 6): per-level
// rows, materials still-need / have, the 301-325 sigil chain and the e-coin lines. All of it is absent from
// an older RynthILT (or RynthAi) and from a server without ILT: the arrays stay empty, the strings "", and
// the calculator is not drawn. The row arrays are read leniently (see EnlRowConverters): a null, a
// non-array, a non-object row or a mistyped field costs that row, never the whole Progression snapshot.
[JsonPropertyName("levels")] [JsonConverter(typeof(EnlLevelRowsConverter))]
public EnlLevelRow[] Levels { get; set; } = Array.Empty<EnlLevelRow>();
[JsonPropertyName("materials")] [JsonConverter(typeof(EnlMaterialRowsConverter))]
public EnlMaterialRow[] Materials { get; set; } = Array.Empty<EnlMaterialRow>();
[JsonPropertyName("chain")] [JsonConverter(typeof(EnlChainRowsConverter))]
public EnlChainRow[] Chain { get; set; } = Array.Empty<EnlChainRow>();
[JsonPropertyName("chainNote")] public string ChainNote { get; set; } = "";
/// <summary>"E-coins needed: N have M (bank + pack)..." ("" when no e-coins are involved).</summary>
[JsonPropertyName("ecoins")] public string Ecoins { get; set; } = "";
/// <summary>"Lum to buy e-coins: ~X" or the hint to set Lum per e-coin ("" when no coins are needed).</summary>
[JsonPropertyName("ecoinsLum")] public string EcoinsLum { get; set; } = "";
/// <summary>The snapshot has anything for the calculator section to draw.</summary>
[JsonIgnore] public bool HasCalculator => Levels.Length > 0 || Materials.Length > 0 || Chain.Length > 0;
}
/// <summary>One enlightenment step of the calculator's per-level table (RynthILT lists at most 100).</summary>
internal sealed class EnlLevelRow
{
private string? _levelText, _countText;
/// <summary>The enlightenment level this step reaches.</summary>
[JsonPropertyName("t")] public int Level { get; set; }
/// <summary>"Tokens" / "Medallions" / "Sigils" / "Crests", or "-" for a step with no item.</summary>
[JsonPropertyName("item")] public string Item { get; set; } = "-";
[JsonPropertyName("count")] public int Count { get; set; }
/// <summary>Luminance for the step, preformatted ("1.50B"), "-" for none.</summary>
[JsonPropertyName("lum")] public string Lum { get; set; } = "-";
/// <summary>The simulated stock (pack items, the sigil chain, luminance) still covers this step.</summary>
[JsonPropertyName("ok")] public bool Ok { get; set; }
// Display text, formatted once per snapshot instead of every frame.
[JsonIgnore] public string LevelText => _levelText ??= Level.ToString(CultureInfo.InvariantCulture);
[JsonIgnore] public string CountText => _countText ??= Count > 0 ? Count.ToString("N0", CultureInfo.InvariantCulture) : "-";
}
/// <summary>Still-need vs have for one material (or luminance); need / have arrive preformatted.</summary>
internal sealed class EnlMaterialRow
{
[JsonPropertyName("label")] public string Label { get; set; } = "";
[JsonPropertyName("need")] public string Need { get; set; } = "0";
[JsonPropertyName("have")] public string Have { get; set; } = "0";
[JsonPropertyName("ok")] public bool Ok { get; set; }
}
/// <summary>One row of the 301-325 sigil craft chain. Craft rows count crafts left, raw rows what to get.</summary>
internal sealed class EnlChainRow
{
private string? _needText, _haveText, _displayLabel;
[JsonPropertyName("label")] public string Label { get; set; } = "";
[JsonPropertyName("need")] public long Need { get; set; }
[JsonPropertyName("have")] public long Have { get; set; }
[JsonPropertyName("ok")] public bool Ok { get; set; }
/// <summary>An in-between item the player crafts (Ascension Coins, Lifeblood Elixirs, Lifebloom Resins).</summary>
[JsonPropertyName("craft")] public bool Craft { get; set; }
/// <summary>The label with "(craft)" for an in-between item the player crafts.</summary>
[JsonIgnore] public string DisplayLabel => _displayLabel ??= Craft ? Label + " (craft)" : Label;
[JsonIgnore] public string NeedText => _needText ??= Need.ToString("N0", CultureInfo.InvariantCulture);
[JsonIgnore] public string HaveText => _haveText ??= Have.ToString("N0", CultureInfo.InvariantCulture);
}
/// <summary>How much of the Enl calculator the Progression tab draws (pure, so it is tested).</summary>
internal static class EnlCalculatorView
{
/// <summary>Per-level rows shown until "Show all" is pressed.</summary>
public const int PreviewLevels = 12;
/// <summary>Per-level rows drawn at most (RynthILT sends 100 at most), in a scrolling table.</summary>
public const int MaxLevels = 100;
/// <summary>Material / chain rows drawn at most (RynthILT sends 5 and 8).</summary>
public const int MaxListRows = 16;
/// <summary>Per-level rows to draw for <paramref name="total"/> rows; <paramref name="showAll"/> lifts the preview limit.</summary>
public static int VisibleLevels(int total, bool showAll)
{
if (total <= 0) return 0;
return Math.Min(total, showAll ? MaxLevels : PreviewLevels);
}
/// <summary>There are more rows than the preview shows, so the Show all toggle is offered.</summary>
public static bool CanExpand(int total) => total > PreviewLevels;
}
[JsonSerializable(typeof(ProgressionInfo))]
@ -201,10 +290,27 @@ internal sealed unsafe class ProgressionSource : UiSource<ProgressionInfo>
if (_getProgressionJson == null) return;
IntPtr p = _getProgressionJson();
string json = p == IntPtr.Zero ? "{}" : (_utf8 ? Marshal.PtrToStringUTF8(p) : Marshal.PtrToStringAnsi(p)) ?? "{}";
Publish(ParseJson(json));
}
/// <summary>
/// The snapshot for a plugin's JSON: an unreadable payload is an empty snapshot (Available false, the tab
/// hides), never an exception. The Enl calculator's own fields degrade on their own (EnlRowConverters).
/// </summary>
internal static ProgressionInfo ParseJson(string? json)
{
ProgressionInfo info;
try { info = JsonSerializer.Deserialize(json, ProgressionJsonContext.Default.ProgressionInfo) ?? new ProgressionInfo(); }
try { info = JsonSerializer.Deserialize(json ?? "{}", ProgressionJsonContext.Default.ProgressionInfo) ?? new ProgressionInfo(); }
catch (JsonException) { info = new ProgressionInfo(); }
Publish(info);
EnlPlanner? enl = info.Enl;
if (enl != null)
{
// JSON null into a string property: the UI reads .Length.
enl.ChainNote ??= "";
enl.Ecoins ??= "";
enl.EcoinsLum ??= "";
}
return info;
}
protected internal override void Reset()

View file

@ -371,6 +371,7 @@ internal static unsafe class RynthAiCommands
finally { Marshal.FreeHGlobal(p); }
if (refreshPatrol) UiSources.Patrol.RequestRefresh();
UiSources.Nav.RequestRefresh(); // the plugin applied it: the Nav panels show it next poll
UiSources.Settings.RequestRefresh(); // Breadcrumbs / Route overlay are on Settings > Navigation too
});
/// <summary>

View file

@ -124,6 +124,22 @@ internal sealed class RynthAiSettings
public bool UseNativeAttack { get; set; } = true;
public bool SummonPets { get; set; }
public int PetMinMonsters { get; set; } = 1;
// RynthAi's Variable attack power, environment-hit throttle and pull-away kite (2026-10-12 and
// 2026-10-16; Silentkelpie's). Mirrors of RynthAi's own settings, nullable like the Vaulted
// switch below: a RynthAi that predates them omits them, the rows stay hidden, and a save
// sends null, which RynthAi leaves alone. Their defaults here are only what a row shows for a
// value that arrived.
public int? VariablePowerMin { get; set; }
public int? VariablePowerMax { get; set; }
public int? MissileEnvironmentResponse { get; set; }
public int? MagicEnvironmentResponse { get; set; }
public int? EnvironmentImpactLimit { get; set; }
public int? EnvironmentImpactWindowSec { get; set; }
public int? EnvironmentApproachMeters { get; set; }
public int? EnvironmentMinDistance { get; set; }
public int? EnvironmentSkipSec { get; set; }
public int? KitePullMeters { get; set; }
public bool? KiteTagFirst { get; set; }
// Spell Combat
public int SpellCastIntervalMs { get; set; } = 400;
public int AttackSpellIntervalMs { get; set; } = 1500;
@ -151,6 +167,14 @@ internal sealed class RynthAiSettings
public double CorpseApproachRangeMin { get; set; } = 2.0;
// Navigation
public bool BoostNavPriority { get; set; }
/// <summary>
/// RynthAi's "Vaulted Dungeons" setting: the master switch of RynthILT's Vaulted Dungeons keeper
/// (Infinite Leaftide / ACECustom only), off by default. It lives in the RynthAi profile (this is
/// only a mirror, so there is exactly one copy); RynthILT reads it from RynthAi. Nullable like
/// the Nav panel's switches: a RynthAi that predates it omits it, the row then stays hidden and a
/// save sends null, which RynthAi leaves alone.
/// </summary>
public bool? EnableVaultedDungeons { get; set; }
public float FollowNavMin { get; set; } = 1.5f;
public float NavRingThickness { get; set; } = 6f;
public float NavLineThickness { get; set; } = 6f;
@ -163,6 +187,11 @@ internal sealed class RynthAiSettings
// RynthAi NavResumeNearest: macro start, route loads and resuming after a pause that moved
// the character head for the closest waypoint. On by default; an older plugin ignores it.
public bool NavResumeNearest { get; set; } = true;
// RynthAi NavOverlay.TrackBreadcrumbs / ShowRouteMarkers: the Nav panel's Breadcrumbs and Route
// overlay switches, also on Settings > Navigation. Null = a RynthAi that doesn't send them: the
// rows hide, and a save sends null back, which RynthAi reads as unchanged.
public bool? TrackBreadcrumbs { get; set; }
public bool? ShowRouteOverlay { get; set; }
// RynthAi dungeon patrol (/ra dunnav-patrol; RynthAi DungeonPatrolOptions). The defaults are
// the patrol as it was before these settings; an older plugin ignores them.
public int DunPatrolCoverage { get; set; } // 0 whole dungeon, 1 loops only, 2 everything, 3 sweep
@ -324,10 +353,40 @@ internal static unsafe class SettingsCommands
try { _setSettingsJson(ansi); }
finally { Marshal.FreeHGlobal(ansi); }
UiSources.Settings.RequestRefresh();
UiSources.Nav.RequestRefresh(); // the Nav panel's Breadcrumbs / Route overlay switches
});
}
}
/// <summary>
/// The optimized loot timer defaults, in ms: the same values as RynthSuite's LootBaseline.cs
/// (RynthAi), measured from live corpse looting on ACE (226 corpses, 39 pickups; from
/// Silentkelpie's PR 6). Keep the two in step. The "Use optimized defaults" button on Settings
/// writes them; the properties of <see cref="RynthAiSettings"/> keep their own initial values.
/// </summary>
internal static class LootTimerDefaults
{
public const int ContentSettleMs = 100;
public const int EmptyCorpseMs = 300;
/// <summary>Above the 256 ms 95th percentile of the measured appraisal replies.</summary>
public const int AssessWindowMs = 300;
/// <summary>No pickup needed a retry at 1000 ms (it counts from when the character is still).</summary>
public const int RetryTimeoutMs = 1000;
public const int OpenRetryMs = 1500;
public const int CorpseTimeoutMs = 12000;
/// <summary>Writes the six optimized defaults into <paramref name="s"/>.</summary>
public static void Apply(RynthAiSettings s)
{
s.LootContentSettleMs = ContentSettleMs;
s.LootEmptyCorpseMs = EmptyCorpseMs;
s.LootAssessWindowMs = AssessWindowMs;
s.LootRetryTimeoutMs = RetryTimeoutMs;
s.LootOpenRetryMs = OpenRetryMs;
s.LootCorpseTimeoutMs = CorpseTimeoutMs;
}
}
// ── Schema ─────────────────────────────────────────────────────────────────
internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status,
@ -419,7 +478,10 @@ internal sealed record SettingRow(
Func<RynthAiSettings, string>? GetText = null,
Action<RynthAiSettings, string>? SetText = null,
// Text rows: greyed hint shown while the box is empty.
string? Hint = null)
string? Hint = null,
// Button rows that change settings: applied to the panel's copy, which is then saved like
// any other edit (Click, when also set, runs after).
Action<RynthAiSettings>? Edit = null)
{
public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s);
}
@ -430,12 +492,23 @@ internal static class SettingsSchema
{
// Also drawn on the Nav panel (ImGui/Panels/NavFace.cs).
public const string NavPointReachLabel = "Nav point reach (yd)";
/// <summary>The Navigation row of RynthAi's Vaulted Dungeons master switch (<see cref="RynthAiSettings.EnableVaultedDungeons"/>).</summary>
public const string VaultedDungeonsLabel = "Vaulted Dungeons";
public const string NavPointReachTip =
"How close to get to each nav point before moving on to the next, in yards. VTank calls it " +
"Follow/Nav Min Distance (metas: FollowNavMin, or VTank's NavCloseStopRange). Follow stops this " +
"close to its leader, and the nav marker ring shows it. Dungeon doorways use at most 1 yd. Up to 2 yd, " +
"nav walks right up to each point before turning (tight dungeons); bigger values round corners.";
// The Nav panel's two overlay switches (ImGui/Panels/NavFace.cs), also on Settings > Navigation.
public const string BreadcrumbsTip =
"Record the trail you walk and draw it on the ground (/ra navtrail on|off).\n" +
"Turning it off hides the trail; /ra navtrail clear wipes it.";
public const string RouteOverlayTip =
"Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\n" +
"to the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate.";
private const string SameAsNavPanel = "\nThe same switch as on the Nav panel.";
// Also shown by the dashboard's Ranges slide-out (ImGui/Panels/RangesSlideOut.cs), which
// edits these same rows (found by label with Find).
public const string MonsterRangeTip =
@ -460,6 +533,12 @@ internal static class SettingsSchema
}
public static readonly string[] AttackHeights = { "Low", "Medium", "High" };
// RynthAi's EnvironmentResponse, in its order (0 Off .. 3).
public static readonly string[] EnvironmentResponses = { "Off", "Move closer", "New target", "Move closer, then new target" };
// The rows below show only once RynthAi has sent the value (an older RynthAi omits them).
private static bool HasVariablePower(RynthAiSettings s) => s.VariablePowerMin.HasValue;
private static bool HasEnvironmentThrottle(RynthAiSettings s) => s.EnvironmentImpactLimit.HasValue;
private static bool HasKite(RynthAiSettings s) => s.KitePullMeters.HasValue;
public static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
public static readonly string[] NavLabelModes = { "Off", "Numbers", "Numbers and names" };
public static readonly string[] DunPatrolCoverages = { "Whole dungeon", "Loops only", "Everything", "Sweep (by sight)" };
@ -498,8 +577,8 @@ internal static class SettingsSchema
new(SettingKind.Double, label, tip, get, set, min, max, step);
private static SettingRow Combo(string label, string[] items, Func<RynthAiSettings, int> get, Action<RynthAiSettings, int> set,
string? tip = null) =>
new(SettingKind.Combo, label, tip, s => get(s), (s, v) => set(s, (int)v), 0, items.Length - 1, 1, items);
string? tip = null, Func<RynthAiSettings, bool>? when = null) =>
new(SettingKind.Combo, label, tip, s => get(s), (s, v) => set(s, (int)v), 0, items.Length - 1, 1, items, VisibleWhen: when);
// Text size rows are stored by the engine (PanelTextScale), not in the
// RynthAi profile, so the settings object is ignored here.
@ -525,6 +604,10 @@ 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 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);
private static SettingRow Text(string label, Func<RynthAiSettings, string> get, Action<RynthAiSettings, string> set,
string? tip = null, string? hint = null) =>
new(SettingKind.Text, label, tip, GetText: get, SetText: set, Hint: hint);
@ -604,6 +687,27 @@ internal static class SettingsSchema
Bool("Insert Key Releases the UI", _ => Plugins.EngineSettings.InsertReleasesUi,
(_, v) => { Plugins.EngineSettings.InsertReleasesUi = v; if (!v) ImGuiBackend.Win32Backend.ReclaimUi(); },
"On: Insert switches between UI and GAME (shown on the RynthCore bar). In GAME, clicks pass through\nRynth windows to the game and Rynth text boxes can't be typed in. Press Insert again to get the UI back.\nOff (default): Insert does nothing. Applies to all your clients; others pick it up when they start."),
Bool("Borderless Windowed", _ => Plugins.EngineSettings.BorderlessWindowed,
(_, v) =>
{
Plugins.EngineSettings.BorderlessWindowed = v;
AcWindowChrome.RequestApply(); // applied from the game thread, not inside this frame
},
"On: hide the Asheron's Call window title bar and borders while staying windowed (exclusive fullscreen is left alone).\nOff (default): normal window chrome. Turning it off only gives back the chrome this setting removed.\nApplies to all your clients; others pick it up when they start."),
Spacer(),
Section("Window and HUD Layout"),
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."),
Bool("Remember Game Window Position", _ => Plugins.EngineSettings.RememberAcWindowPosition,
(_, v) =>
{
Plugins.EngineSettings.RememberAcWindowPosition = v;
AcWindowChrome.RequestApply();
},
"On: save the Asheron's Call window's position and size for each character and put it back after you log in.\nOff (default): the game window is never moved. A saved spot that is off-screen (a monitor that is gone) is ignored."),
Button("Save Layout Now", "Save", () => AcWindowChrome.SaveLayoutNow(),
"Write the open panels, the game window position (when Remember Game Window Position is on),\nthe Vision HUD and the ImGui window positions to disk now."),
Spacer(),
// The colour theme is stored by the engine (theme.txt, ImGuiBackend.RynthTheme), not in the RynthAi profile.
Section("Colour Theme"),
@ -719,6 +823,19 @@ internal static class SettingsSchema
"items after 30 s, at most 5 a second. Unselected monsters' nameplates show no level.\n" +
"Off: nothing in the background.\n" +
"RynthAi's own identifies (loot, monster weaknesses) are never limited. Applies to all your clients. Also: /rc autoid."),
// Stored in engine.json for every client (EngineSettings.HoldReloadInWorld, ReloadInWorldGate); opt-in.
Bool("Hold reloads while in the world", _ => Plugins.EngineSettings.HoldReloadInWorld,
(_, v) => Plugins.EngineSettings.HoldReloadInWorld = v,
"On: when a new RynthCore build is deployed (the automatic engine reload), the reload waits until you\n" +
"log out or reach character select instead of reloading mid-session. A workaround for client crashes\n" +
"when reloads stack up while you are in the world (SilentKelpie's).\n" +
"It never waits forever: after the time below it reloads anyway. A reload you ask for yourself\n" +
"(the RL button, ERl, /rc rl, the hotkey) is never held.\n" +
"Off (default): the engine reloads as soon as the new build is there. Applies to all your clients.", gates: true),
Int(" Give up holding after (min)", _ => Plugins.EngineSettings.HoldReloadInWorldMaxMinutes,
(_, v) => Plugins.EngineSettings.HoldReloadInWorldMaxMinutes = v, 1, 240, 1,
"How long a held reload waits for you to leave the world before it reloads anyway (default 10).",
when: _ => Plugins.EngineSettings.HoldReloadInWorld),
Spacer(),
Bool("Auto Cram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v,
"Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."),
@ -863,6 +980,48 @@ internal static class SettingsSchema
Int("Missile Power %", s => s.MissileAttackPower, (s, v) => s.MissileAttackPower = v, 0, 100, 5, when: s => s.MissileAttackPower >= 0),
Combo("Missile Attack Height", AttackHeights, s => s.MissileAttackHeight, (s, v) => s.MissileAttackHeight = v),
Spacer(),
Section("Variable Power (monster rules)", HasVariablePower),
Int("Variable Min %", s => s.VariablePowerMin ?? 50, (s, v) => s.VariablePowerMin = v, 0, 100, 5,
"A monster rule's Power picks per monster (Damage panel, a monster's detail):\n" +
"Default (the settings above), High (100%), Reckless (80%, needs Recklessness trained),\n" +
"Variable (a new random power each attack, between these two), or Reckless + Variable\n" +
"(random, kept inside the Recklessness band 20-80%).",
when: HasVariablePower),
Int("Variable Max %", s => s.VariablePowerMax ?? 100, (s, v) => s.VariablePowerMax = v, 0, 100, 5,
when: HasVariablePower),
Spacer(HasVariablePower),
Section("Hitting the Environment", HasEnvironmentThrottle),
Combo("Missile Response", EnvironmentResponses, s => s.MissileEnvironmentResponse ?? 0, (s, v) => s.MissileEnvironmentResponse = v,
"When arrows or bolts keep hitting walls or objects instead of the target\n" +
"(\"Your missile attack hit the environment.\"), stop shooting and:\n" +
" Move closer - run toward the target for a clearer shot\n" +
" New target - skip this one for a while and fight another\n" +
" Move closer, then new target - one approach, then switch\n" +
"The only monster in reach is never skipped. Off by default. Magic: Spell Combat tab.",
when: HasEnvironmentThrottle),
Int("Hits to trip", s => s.EnvironmentImpactLimit ?? 2, (s, v) => s.EnvironmentImpactLimit = v, 1, 10, 1,
"Environment hits on one target, within the window, before combat reacts (missiles and magic).",
when: HasEnvironmentThrottle),
Int("Window (s)", s => s.EnvironmentImpactWindowSec ?? 20, (s, v) => s.EnvironmentImpactWindowSec = v, 5, 120, 5,
when: HasEnvironmentThrottle),
Int("Move closer by (m)", s => s.EnvironmentApproachMeters ?? 6, (s, v) => s.EnvironmentApproachMeters = v, 1, 30, 1,
when: HasEnvironmentThrottle),
Int("Closest (m)", s => s.EnvironmentMinDistance ?? 3, (s, v) => s.EnvironmentMinDistance = v, 1, 30, 1,
"Never moves nearer than this. Already this close, a new target is picked instead.",
when: HasEnvironmentThrottle),
Int("Skip target (s)", s => s.EnvironmentSkipSec ?? 30, (s, v) => s.EnvironmentSkipSec = v, 5, 300, 5,
when: HasEnvironmentThrottle),
Spacer(HasEnvironmentThrottle),
Section("Pull Away (Kite)", HasKite),
Int("Pull Distance (m)", s => s.KitePullMeters ?? 20, (s, v) => s.KitePullMeters = v, 3, 100, 1,
"When a monster rule's Kite is PullAway (or Default follows the DEFAULT row set to PullAway),\n" +
"tag the mob then run until it has been dragged this many metres from where it stood, then kill it.\n" +
"Set per mob on the Damage panel (Kite). Off for every monster until a rule asks for it.",
when: HasKite),
Bool("Tag Before Fleeing", s => s.KiteTagFirst ?? true, (s, v) => s.KiteTagFirst = v,
"Land a hit before running so aggro sticks. Off = flee as soon as locked.",
when: HasKite),
Spacer(HasKite),
Bool("Use Native Attack", s => s.UseNativeAttack, (s, v) => s.UseNativeAttack = v,
"Uses the client's combat pipeline for attacks.\nThe client handles turn-to-face naturally (no backwards arrows)."),
Spacer(),
@ -894,6 +1053,17 @@ internal static class SettingsSchema
Int("Min Wall Targets", s => s.MinWallTargets, (s, v) => s.MinWallTargets = v, 1, 20, 1,
"How many monsters (the target included) must be in the wall's path, within Wall Range."),
Spacer(),
Section("Hitting the Environment", HasEnvironmentThrottle),
Combo("Magic Response", EnvironmentResponses, s => s.MagicEnvironmentResponse ?? 0, (s, v) => s.MagicEnvironmentResponse = v,
"When bolts, streaks, arcs or blasts keep stopping short of the target\n" +
"(a wall, a pillar, the ceiling) with no hit or resist, stop casting and:\n" +
" Move closer - run toward the target for a clearer line\n" +
" New target - skip this one for a while and fight another\n" +
" Move closer, then new target - one approach, then switch\n" +
"Rings and walls aren't judged. The only monster in reach is never skipped. Off by default.\n" +
"Hits to trip, the window, distances and the skip time: Melee Combat tab.",
when: HasEnvironmentThrottle),
Spacer(HasEnvironmentThrottle),
Section("Spell Difficulty (Min Buffed Skill)"),
Tiers(
new Func<RynthAiSettings, int>[] { s => s.MinSkillLevelTier1, s => s.MinSkillLevelTier2, s => s.MinSkillLevelTier3, s => s.MinSkillLevelTier4,
@ -930,7 +1100,24 @@ internal static class SettingsSchema
Bool("Boost Nav Priority", s => s.BoostNavPriority, (s, v) => s.BoostNavPriority = v),
Float(NavPointReachLabel, s => s.FollowNavMin, (s, v) => s.FollowNavMin = v, 0.5f, 20f, 0.1f, NavPointReachTip),
Spacer(),
Section("Infinite Leaftide"),
Bool(VaultedDungeonsLabel, s => s.EnableVaultedDungeons ?? false, (s, v) => s.EnableVaultedDungeons = v,
"Master switch of the Vaulted Dungeons keeper (Infinite Leaftide / ACECustom only). Off by default.\n" +
"While off the keeper does nothing: no recalls, no /rc quit, no Mini Remote tab, and a saved On or\n" +
"Auto Start is ignored. Turning it off while it runs stops it at once.\n" +
"On: the Mini Remote shows the \"Vaulted Dungeons\" tab on those worlds, where you pick a dungeon and a\n" +
"tied Portal Recall Gem and start it yourself (/ilt vaulted on); it never resumes by itself after a\n" +
"relog unless Auto Start On Arrival is ticked. Recalls wait while RynthAi is in combat or buffing.\n" +
"Kill Client (/rc quit after N minutes without a kill) restarts on luminance, your killing blows and\n" +
"pet captures; kills by pets or fellows that pay you no luminance do NOT.\n" +
"Needs RynthILT and a RynthAi that has this setting; the other settings are per character in RynthILT.",
when: s => s.EnableVaultedDungeons.HasValue),
Spacer(),
Section("Nav Marker Display"),
Bool("Breadcrumbs", s => s.TrackBreadcrumbs ?? true, (s, v) => s.TrackBreadcrumbs = v,
BreadcrumbsTip + SameAsNavPanel, when: s => s.TrackBreadcrumbs.HasValue),
Bool("Route Overlay", s => s.ShowRouteOverlay ?? true, (s, v) => s.ShowRouteOverlay = v,
RouteOverlayTip + SameAsNavPanel, when: s => s.ShowRouteOverlay.HasValue),
Float("Ring Thickness", s => s.NavRingThickness, (s, v) => s.NavRingThickness = v, 1f, 16f, 1f),
Float("Line Thickness", s => s.NavLineThickness, (s, v) => s.NavLineThickness = v, 1f, 16f, 1f),
Float("Height Offset", s => s.NavHeightOffset, (s, v) => s.NavHeightOffset = v, -5f, 5f, 0.05f,
@ -1086,19 +1273,30 @@ internal static class SettingsSchema
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."),
Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"),
"Opens the item count HUD / Mini Remote setup window (/ra huds)."),
"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,
"Salvage (and combine bags) by sending the salvage request to the server directly:\nAC's salvage panel never opens. When a request changes nothing, that batch is tried once\nthrough the panel. Needs an engine with plugin API v82; otherwise the panel is used."),
Spacer(),
Section("Loot Timers (ms)"),
EditButton("Optimized defaults", "Use optimized defaults", LootTimerDefaults.Apply,
"Set the six loot timers RynthAi's corpse looting reads (everything here except Inter-Item\n" +
"Delay and Closing Delay) to the optimized defaults, measured from live looting on ACE\n" +
"(226 corpses): Content Settle 100, Empty Corpse Wait 300, Assess Window 300,\n" +
"Loot Retry Timeout 1000, Corpse Open Retry 1500, Corpse Timeout 12000."),
Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25),
Int("Content Settle", s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25),
Int("Empty Corpse Wait", s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25),
Int("Content Settle", s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25,
"Wait after an open for the container's items. Only used when the items\naren't already known; on ACE they always were. Optimized default: 100."),
Int("Empty Corpse Wait", s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25,
"Wait for a corpse's contents before probing it or calling it empty. Optimized default: 300."),
Int("Closing Delay", s => s.LootClosingDelayMs, (s, v) => s.LootClosingDelayMs = v, 0, 5000, 25),
Int("Assess Window", s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25),
Int("Loot Retry Timeout", s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100),
Int("Corpse Open Retry", s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100),
Int("Corpse Timeout", s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500),
Int("Assess Window", s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25,
"Hold items for their appraisal. Measured replies: 127 ms typical,\n256 ms at the 95th percentile, 350 ms at most. Optimized default: 300."),
Int("Loot Retry Timeout", s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100,
"Wait, once the character is still, before resending a pickup that hasn't\nlanded. Too short resends pickups the server is still doing. Optimized default: 1000."),
Int("Corpse Open Retry", s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100,
"Wait before sending another open to a corpse that hasn't opened. Optimized default: 1500."),
Int("Corpse Timeout", s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500,
"Give up on a claimed corpse after this long. The clock stops during combat\nand buffing. Optimized default: 12000."),
Spacer(),
Section("Salvage Timers (ms) - First / Fast"),
Int("Open (First)", s => s.SalvageOpenDelayFirstMs, (s, v) => s.SalvageOpenDelayFirstMs = v, 0, 5000, 50),

View file

@ -0,0 +1,57 @@
// ============================================================================
// RynthCore.Engine - UI/Data/SharedFileWatch.cs
// Notices that ANOTHER client rewrote a settings file all clients share
// (rynthchat_settings.json), so ChatModel can re-read it. Every client saves its
// whole state, so a client that never re-read the file wrote back stale rules and
// ticked filters over another client's change (last writer won).
//
// Polled, not a FileSystemWatcher: no thread or event subscription to outlive an
// engine reload. A cheap timestamp check at most every PollMs; the file is only
// read when the timestamp moved, and a write this client made itself (Saved, called
// just before its swap) does not count as a change. Pure (no AC, no engine state):
// tools/ChatFilterTests compiles this file.
//
// Idea from Silentkelpie (rynth PR 6, 2026.10.16.23, ChatModel.PollSettingsFile).
// A read that fails (the other client is mid-swap) is retried at the next poll; his
// version marked the change as seen before reading, so a failed read lost it until
// somebody saved again.
// ============================================================================
using System;
using System.IO;
using System.Threading;
namespace RynthCore.Engine.UI.Data;
internal sealed class SharedFileWatch
{
private readonly long _pollMs;
private DateTime _seenWriteUtc;
private string? _lastSavedText;
private long _nextPollMs;
public SharedFileWatch(long pollMs = 2000) => _pollMs = pollMs;
/// <summary>The file was just loaded at start: its timestamp is not a change.</summary>
public void Seen(DateTime writtenUtc) => _seenWriteUtc = writtenUtc;
/// <summary>This client is about to write <paramref name="text"/> (call before the swap): that write is its own.</summary>
public void Saved(string text) => Volatile.Write(ref _lastSavedText, text);
/// <summary>
/// The file's text when another client changed it since the last look, else null (not time to
/// look yet, no file, same timestamp, or the text is this client's own last save). Throws when
/// the file can't be read; the change is then offered again at the next poll.
/// </summary>
public string? Changed(long nowMs, string path)
{
if (nowMs < _nextPollMs) return null;
_nextPollMs = nowMs + _pollMs;
if (!File.Exists(path)) return null;
DateTime written = File.GetLastWriteTimeUtc(path);
if (written == _seenWriteUtc) return null;
string text = File.ReadAllText(path);
_seenWriteUtc = written; // only after a good read
return text == Volatile.Read(ref _lastSavedText) ? null : text;
}
}

View file

@ -0,0 +1,266 @@
// ============================================================================
// RynthCore.Engine - UI/InventoryTitleLayout.cs
// The Classic Inventory title bar's left half: where the title, the Vault button
// and the related-panel buttons (Mini Remote, RynthSort, Item Count, Global
// Inventory) go, so nothing lands off the panel when the bar is narrow.
//
// The bar is 300 retail units wide (x scale), so at the retail size the room left of the
// four fixed toggles (- + tools Modern) is about 186 units. Vault is always placed (it is
// the only one with no other way in); the four related buttons collapse by priority:
// Text four text buttons (Remote Sort Count GInv), when the title keeps its minimum
// Icons four icon squares
// Menu one "more" square that opens a menu of the four
// None nothing fits (a bar far narrower than any real panel); the Character menu has them all
// The title gets what is left (TitleLeft..TitleRight) and is elided with an ellipsis.
//
// Pure (no ImGui, no files, no engine state). All X values are relative to the bar's
// left edge, in pixels; callers add the bar origin. Tests: tools/BarDeclutterTests.
// ============================================================================
using System;
namespace RynthCore.Engine.UI;
internal enum TitleExtrasMode { Text, Icons, Menu, None }
/// <summary>A button's span on the bar: left edge and width (width 0 = not drawn).</summary>
internal readonly record struct TitleSlot(float X, float W)
{
public float Right => X + W;
public bool Present => W > 0f;
}
/// <summary>The positions InventoryFace's Classic title bar draws, in bar-relative pixels.</summary>
internal readonly record struct InventoryTitleLayout(
TitleExtrasMode Mode,
float Btn,
TitleSlot Smaller, TitleSlot Bigger, TitleSlot Tools, TitleSlot Modern,
TitleSlot Vault,
TitleSlot Remote, TitleSlot Sort, TitleSlot Count, TitleSlot GInv,
TitleSlot More,
float TitleLeft, float TitleRight)
{
// Units at scale 1 (the retail art's), multiplied by the bar's scale.
public const float BtnUnits = 18, EdgeUnits = 8, PadUnits = 6, GapSmall = 2, GapGroup = 6, VaultGap = 8,
VaultUnits = 38, RemoteUnits = 48, SortUnits = 36, CountUnits = 40, GInvUnits = 42,
TextGap = 4, IconGap = 2, LeadGap = 4, TitleMinUnits = 56, TitleGap = 4;
/// <summary>The title's room (TitleRight - TitleLeft), never negative.</summary>
public float TitleWidth => Math.Max(0f, TitleRight - TitleLeft);
/// <summary>The left edge of everything drawn left of the title (Vault and the related buttons): the drag surface ends here.</summary>
public float LeftmostX
{
get
{
float x = Math.Min(Modern.X, Smaller.X);
if (Vault.Present) x = Math.Min(x, Vault.X);
if (Mode is TitleExtrasMode.Text or TitleExtrasMode.Icons) x = Math.Min(x, Remote.X);
if (Mode == TitleExtrasMode.Menu) x = Math.Min(x, More.X);
return x;
}
}
/// <summary>
/// Lays the bar out. <paramref name="barW"/> is the bar's width in pixels (the panel width less
/// the close button), <paramref name="s"/> its scale, <paramref name="vault"/> whether the Vault
/// button exists (VaultFeed.Available), <paramref name="titleWantW"/> the title text's full
/// width in pixels (it only decides how much room the title is owed: at most 56 units).
/// </summary>
public static InventoryTitleLayout Compute(float barW, float s, bool vault, float titleWantW)
{
if (!(s > 0f) || !float.IsFinite(s)) s = 1f;
if (!float.IsFinite(barW)) barW = 0f;
if (!float.IsFinite(titleWantW) || titleWantW < 0f) titleWantW = 0f;
float btn = MathF.Round(BtnUnits * s);
float pad = PadUnits * s;
// The four fixed toggles at the bar's right end (unchanged from the original Classic layout).
float modernX = barW - EdgeUnits * s - btn;
float toolsX = modernX - btn - GapSmall * s;
float biggerX = toolsX - btn - GapGroup * s;
float smallerX = biggerX - btn - GapSmall * s;
var modern = new TitleSlot(modernX, btn);
var tools = new TitleSlot(toolsX, btn);
var bigger = new TitleSlot(biggerX, btn);
var smaller = new TitleSlot(smallerX, btn);
// Vault sits next to the toggles, and is never dropped. On a bar too narrow to hold it
// without crossing the title area it is pushed to the left edge, never past it.
float edge = smallerX;
TitleSlot vaultSlot = default;
if (vault)
{
float vw = MathF.Round(VaultUnits * s);
float vx = Math.Max(0f, edge - vw - VaultGap * s);
vaultSlot = new TitleSlot(vx, vw);
edge = vx;
}
// The room left of `edge` is shared by the title and the related buttons. The title is owed
// TitleMinUnits (less if its whole text is shorter); take the richest button style that leaves it.
float titleMin = Math.Min(titleWantW, TitleMinUnits * s);
float lead = LeadGap * s;
float rw = MathF.Round(RemoteUnits * s), sw = MathF.Round(SortUnits * s),
cw = MathF.Round(CountUnits * s), gw = MathF.Round(GInvUnits * s);
float tg = TextGap * s, ig = IconGap * s;
// Right to left: GInv, Count, Sort, Remote.
float tGinvX = edge - lead - gw;
float tCountX = tGinvX - tg - cw;
float tSortX = tCountX - tg - sw;
float tRemoteX = tSortX - tg - rw;
float iGinvX = edge - lead - btn;
float iCountX = iGinvX - ig - btn;
float iSortX = iCountX - ig - btn;
float iRemoteX = iSortX - ig - btn;
float moreX = edge - lead - btn;
TitleExtrasMode mode;
float groupLeft;
if (tRemoteX - pad >= titleMin) { mode = TitleExtrasMode.Text; groupLeft = tRemoteX; }
else if (iRemoteX - pad >= titleMin) { mode = TitleExtrasMode.Icons; groupLeft = iRemoteX; }
else if (moreX - pad >= 0f) { mode = TitleExtrasMode.Menu; groupLeft = moreX; }
else { mode = TitleExtrasMode.None; groupLeft = edge; }
TitleSlot remote = default, sort = default, count = default, ginv = default, more = default;
switch (mode)
{
case TitleExtrasMode.Text:
remote = new TitleSlot(tRemoteX, rw);
sort = new TitleSlot(tSortX, sw);
count = new TitleSlot(tCountX, cw);
ginv = new TitleSlot(tGinvX, gw);
break;
case TitleExtrasMode.Icons:
remote = new TitleSlot(iRemoteX, btn);
sort = new TitleSlot(iSortX, btn);
count = new TitleSlot(iCountX, btn);
ginv = new TitleSlot(iGinvX, btn);
break;
case TitleExtrasMode.Menu:
more = new TitleSlot(moreX, btn);
break;
}
float titleRight = Math.Max(pad, groupLeft - TitleGap * s);
return new InventoryTitleLayout(mode, btn, smaller, bigger, tools, modern, vaultSlot,
remote, sort, count, ginv, more, pad, titleRight);
}
/// <summary>Header (Modern look) buttons: four 22 px icons at a 24 px pitch, or one "more" button.</summary>
public const float HeaderIconsW = 96, HeaderMenuW = 24, HeaderCountGap = 10;
/// <summary>
/// The Modern header's related-panel buttons for <paramref name="freeW"/> pixels between the pyreals
/// and the Classic / Close buttons, shared with the item count text (<paramref name="countW"/>).
/// Icons when all four and the count fit, else the one menu button, with the count text dropped last.
/// Text mode never applies here (Icons, Menu or None).
/// </summary>
public static TitleExtrasMode ChooseHeaderExtras(float freeW, float countW, out bool showCount)
{
if (!float.IsFinite(freeW)) freeW = 0f;
if (!float.IsFinite(countW) || countW < 0f) countW = 0f;
float count = countW + HeaderCountGap;
if (freeW >= HeaderIconsW + count) { showCount = true; return TitleExtrasMode.Icons; }
if (freeW >= HeaderMenuW + count) { showCount = true; return TitleExtrasMode.Menu; }
if (freeW >= HeaderMenuW) { showCount = false; return TitleExtrasMode.Menu; }
showCount = freeW >= count;
return TitleExtrasMode.None;
}
/// <summary>The Modern header's Vault button (Aelrynth): one 22 px icon at a 24 px pitch, left of the Classic button.</summary>
public const float HeaderVaultW = 24;
/// <summary>
/// <see cref="ChooseHeaderExtras"/> with the Vault button in the picture: when <paramref name="vault"/>
/// the Vault takes its 24 px first and is never dropped (it is the only way into the vault in the Modern
/// look); the four related buttons, the "more" menu and the count text share what is left, as before.
/// Without a vault the result is exactly ChooseHeaderExtras'.
/// </summary>
internal static HeaderPlan ChooseHeader(float freeW, float countW, bool vault)
{
if (!float.IsFinite(freeW)) freeW = 0f;
TitleExtrasMode extras = ChooseHeaderExtras(vault ? freeW - HeaderVaultW : freeW, countW, out bool showCount);
return new HeaderPlan(vault, extras, showCount);
}
/// <summary>
/// <paramref name="text"/> cut to fit <paramref name="maxW"/> pixels, ending in an ellipsis when
/// cut ("" when not even the ellipsis fits). <paramref name="measure"/> gives a string's width.
/// </summary>
public static string Elide(string text, float maxW, Func<string, float> measure)
{
if (text.Length == 0 || !(maxW > 0f)) return "";
if (measure(text) <= maxW) return text;
const string Ellipsis = "...";
if (measure(Ellipsis) > maxW) return "";
int lo = 0, hi = text.Length - 1; // longest prefix whose prefix + ellipsis still fits
while (lo < hi)
{
int mid = (lo + hi + 1) / 2;
if (measure(text.Substring(0, mid).TrimEnd() + Ellipsis) <= maxW) lo = mid; else hi = mid - 1;
}
return text.Substring(0, lo).TrimEnd() + Ellipsis;
}
}
/// <summary>What the Modern header draws between the pyreals and the Classic / Close buttons.</summary>
internal readonly record struct HeaderPlan(bool Vault, TitleExtrasMode Extras, bool ShowCount);
/// <summary>The Modern header's button positions, header-relative pixels (add the header's left edge).</summary>
internal readonly record struct InventoryHeaderLayout(
HeaderPlan Plan,
TitleSlot Close, TitleSlot Classic, TitleSlot Vault,
TitleSlot Remote, TitleSlot Sort, TitleSlot Count, TitleSlot GInv, TitleSlot More,
float RightEdge, float CountX)
{
public const float Btn = 22, Pitch = 24;
/// <summary>
/// Right to left: Close, Classic, the Vault (when there is one), then four related icons or the
/// "more" button, then the count text. <paramref name="w"/> is the header's width, <paramref name="leftEnd"/>
/// where the pyreals text ends (header-relative), <paramref name="countW"/> the count text's width.
/// </summary>
public static InventoryHeaderLayout Compute(float w, float leftEnd, float countW, bool vault)
{
if (!float.IsFinite(w)) w = 0f;
if (!float.IsFinite(leftEnd)) leftEnd = 0f;
if (!float.IsFinite(countW) || countW < 0f) countW = 0f;
var close = new TitleSlot(w - 22, Btn);
float classicX = w - 46;
var classic = new TitleSlot(classicX, Btn);
HeaderPlan plan = InventoryTitleLayout.ChooseHeader(classicX - 4 - leftEnd, countW, vault);
float anchor = classicX; // the next button goes at anchor - 24
TitleSlot vaultSlot = default;
if (plan.Vault)
{
vaultSlot = new TitleSlot(anchor - Pitch, Btn);
anchor = vaultSlot.X;
}
TitleSlot remote = default, sort = default, count = default, ginv = default, more = default;
float rightEdge = anchor - 2;
if (plan.Extras == TitleExtrasMode.Icons)
{
ginv = new TitleSlot(anchor - Pitch, Btn);
count = new TitleSlot(ginv.X - Pitch, Btn);
sort = new TitleSlot(count.X - Pitch, Btn);
remote = new TitleSlot(sort.X - Pitch, Btn);
rightEdge = remote.X - 2;
}
else if (plan.Extras == TitleExtrasMode.Menu)
{
more = new TitleSlot(anchor - Pitch, Btn);
rightEdge = more.X - 2;
}
return new InventoryHeaderLayout(plan, close, classic, vaultSlot, remote, sort, count, ginv, more,
rightEdge, rightEdge - countW - 4);
}
}

View file

@ -25,6 +25,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI;
@ -170,6 +171,18 @@ internal static class PanelStateStore
}
}
/// <summary>Rewrite panel_state.txt from the in-memory snapshot (Settings > Display "Save Layout
/// Now"). An explicit user action, so unlike the automatic saves it is NOT gated by
/// RememberWindowLayout: it writes even when that is off.</summary>
public static void Flush()
{
lock (Sync)
{
Load();
Save(force: true);
}
}
private static void Load()
{
if (_loaded) return;
@ -249,8 +262,13 @@ internal static class PanelStateStore
}
}
private static void Save()
private static void Save(bool force = false)
{
// Settings > Display "Remember Open Windows and Positions" (default on). Off: keep the last
// file; do not overwrite it while the user is rearranging.
if (!force && !EngineSettings.RememberWindowLayout)
return;
try
{
string path = FilePath;

View file

@ -129,6 +129,13 @@ internal static class MonstersPanel
public string PetDamage { get; set; } = "PAuto";
/// <summary>Debuffs the player typed in, comma separated (spell base or full names).</summary>
public string CustomDebuffs { get; set; } = string.Empty;
/// <summary>Melee/missile attack power for this monster: one of DamageData.AttackPowerModes
/// ("Default" follows the DEFAULT line, which follows the global Power settings). Rules saved
/// before 2026-10-12 load as Default.</summary>
public string AttackPower { get; set; } = "Default";
/// <summary>Pull-away kite for this monster: Default / Off / PullAway (RynthAi KiteModes).
/// Default follows the DEFAULT line (Off on that line). Rules saved before 2026-10-16 load as Default.</summary>
public string Kite { get; set; } = "Default";
public bool GetToggle(string field) => field switch
{
@ -1018,6 +1025,8 @@ internal static class MonstersPanel
var x = a[i]; var y = b[i];
if (x.Name != y.Name || x.Category != y.Category || x.Priority != y.Priority
|| x.DamageType != y.DamageType || x.PreferredDamage != y.PreferredDamage || x.ExVuln != y.ExVuln || x.PetDamage != y.PetDamage
|| (x.AttackPower ?? "") != (y.AttackPower ?? "")
|| (x.Kite ?? "") != (y.Kite ?? "")
|| x.WeaponId != y.WeaponId || x.OffhandId != y.OffhandId
|| x.MatchExpression != y.MatchExpression
|| x.Fester != y.Fester || x.Broadside != y.Broadside || x.GravityWell != y.GravityWell

View file

@ -90,6 +90,23 @@ internal static class RynthChatPresets
// Optional combat prefixes such as "Critical hit! " / "Sneak Attack! ".
private const string HitPrefix = @"^(?:[A-Z][\w ]{2,20}! )*";
// The new damage presets (melee_dealt ... magic_taken) name their prefixes: "Critical hit! ",
// "Sneak Attack! ", "Recklessness! ". HitPrefix above is left as it was for the older presets.
private const string KnownHitPrefix = @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*";
// Outgoing physical (melee / missile): "... for N points of X damage!"
private const string DealtMelee =
KnownHitPrefix + @"You \S+ .+ for \d+ points? of .+ damage";
// Outgoing war / void magic: "... for N points with SpellName."
private const string DealtMagic =
KnownHitPrefix + @"You \S+ .+ for \d+ points? with ";
// Incoming melee / missile: body-part hits ("... your foot for N points of ...").
private const string TakenMelee =
KnownHitPrefix + @"(?!You ).+ your [a-z ]+ for \d+ points? of .+ damage";
// Incoming spell damage: "... you for N points with SpellName."
private const string TakenMagic =
KnownHitPrefix + @"(?!You ).+ you for \d+ points? with ";
private static readonly Preset[] _all =
{
// ── Combat ────────────────────────────────────────────────────────
@ -99,6 +116,33 @@ internal static class RynthChatPresets
new("combat.defense_evades", "Combat", "You evade attacks",
"You evade a monster's attack.",
"You evaded Drudge Slinker!", Scope.NotPlayerChat, @"^You evaded "),
// Prefix-tagged and melee / missile / magic damage, each its own switch (the older
// "Damage you deal / take" below keep their meaning). Specific before umbrella: FirstMatch order.
new("combat.recklessness", "Combat", "Recklessness hits",
"Lines prefixed with \"Recklessness!\" (your reckless swings).",
"Recklessness! You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat,
@"^((?:Critical [Hh]it!|Sneak Attack!)\s+)*Recklessness!"),
new("combat.sneak_attack", "Combat", "Sneak Attack hits",
"Lines prefixed with \"Sneak Attack!\" (your sneak swings / shots).",
"Sneak Attack! You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat,
@"^((?:Critical [Hh]it!|Recklessness!)\s+)*Sneak Attack!"),
new("combat.critical", "Combat", "Critical hits",
"Lines prefixed with \"Critical hit!\" / \"Critical Hit!\".",
"Critical hit! You slash Drudge Slinker for 100 points of slashing damage!", Scope.NotPlayerChat,
@"^Critical [Hh]it!"),
new("combat.melee_dealt", "Combat", "Melee / missile damage you deal",
"Your weapon hits: \"You slash … for N points of … damage!\" (missile uses the same form).",
"You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, DealtMelee),
new("combat.magic_dealt", "Combat", "Magic damage you deal",
"Your war / void hits: \"You … for N points with SpellName.\"",
"You freeze Drudge Slinker for 120 points with Frost Bolt VI.", Scope.NotPlayerChat, DealtMagic),
new("combat.melee_taken", "Combat", "Melee / missile damage you take",
"Monster weapon hits on a body part (\"… grazes your foot for N points of …\").",
"Drudge Slinker grazes your foot for 12 points of slashing damage!", Scope.NotPlayerChat, TakenMelee),
new("combat.magic_taken", "Combat", "Magic damage you take",
"Spell damage on you: \"… you for N points with SpellName.\"",
"Drudge Sorcerer scorches you for 40 points with Flame Bolt III.", Scope.NotPlayerChat, TakenMagic),
new("combat.damage_dealt", "Combat", "Damage you deal",
"Your melee, missile and war-spell hits (including critical / sneak attack prefixes).",
"You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"You .+ for \d+ points? of "),
@ -122,6 +166,34 @@ internal static class RynthChatPresets
new("combat.monster_deaths", "Combat", "Monster death messages",
"Kill flavour text (\"You flatten…\", \"…is reduced to cinders!\").",
"Drudge Slinker is reduced to cinders!", Scope.NotPlayerChat, KillPattern),
new("combat.missile_miss", "Combat", "Missile hit the environment",
"\"Your missile attack hit the environment.\" (classic UB ChatFilter).",
"Your missile attack hit the environment.", Scope.NotPlayerChat,
@"^Your missile attack hit the environment\.\s*$"),
new("combat.periodic_damage", "Combat", "Periodic damage ticks",
"\"You receive N points of periodic … damage.\" DoTs on you.",
"You receive 8 points of periodic acid damage.", Scope.NotPlayerChat,
@"^You receive \d+ points of periodic .+damage"),
new("combat.stamina", "Combat", "Stamina restore / spend",
"Lines that restore or spend stamina (kits, consumables, S2H/S2M, Heal Self).",
"You cast Revitalize Self V and restore 40 points of your stamina.", Scope.NotPlayerChat,
@"(?:restore|restores|regain|regains|lose|loses) \d+ points? of (?:your )?stamina\b|and lose \d+ points of stamina"),
new("combat.mana", "Combat", "Mana restore / spend",
"Lines that restore or spend mana (consumables, S2M, mana stones' give line is under Items).",
"You cast Stamina to Mana Self V on yourself and lose 17 points of stamina and also gain 23 points of mana", Scope.NotPlayerChat,
@"(?:restore|restores|regain|regains|gain|gains|lose|loses) \d+ points? of (?:your )?mana\b|and also gain \d+ points of mana"),
new("combat.health", "Combat", "Health restore",
"Lines that restore health points (kits, heals, consumables) — not damage taken.",
"You heal yourself for 80 Health points.", Scope.NotPlayerChat,
@"(?:heal yourself for \d+|restore|restores|regain|regains) \d+ points? of (?:your )?health\b|heal yourself for \d+ Health"),
new("combat.fail_affect_you", "Combat", "Fails to affect you",
"\"… fails to affect you…\" (broader than the NPK-only filter).",
"Bob fails to affect you because he is not a player killer!", Scope.NotPlayerChat,
@" fails to affect you"),
new("combat.you_fail_affect", "Combat", "You fail to affect",
"\"You failed to affect…\" / \"You fail to affect…\" (non-PK and other).",
"You fail to affect Bob because you are not a player killer!", Scope.NotPlayerChat,
@"^You fail(?:ed)? to affect "),
// ── Casting ───────────────────────────────────────────────────────
new("cast.mine", "Casting", "Your spell words",
@ -145,6 +217,14 @@ internal static class RynthChatPresets
new("cast.expires", "Casting", "Spell expiry",
"\"… has expired.\" — rares (Brilliance / Prodigal / Spectral) are kept.",
"Strength Self VII has expired.", Scope.NotPlayerChat, @"^(?!.*(?:Brilliance|Prodigal|Spectral)).*\b(?:has|have) expired\."),
new("cast.give_take", "Casting", "Stamina / health / mana transfers",
"Self casts that spend one vital and restore another (S2M, S2H, …).",
"You cast Stamina to Mana Self V on yourself and lose 17 points of stamina and also gain 23 points of mana", Scope.NotPlayerChat,
@"^You cast .+ on yourself and lose \d+ points of .+ and also gain \d+ points of "),
new("cast.heal_self", "Casting", "Your heal / restore casts",
"\"You cast … and restore N points of your …\" (spell heals, not kits).",
"You cast Revitalize Self V and restore 40 points of your stamina.", Scope.NotPlayerChat,
@"^You cast .+ and restore \d+ points of your "),
// ── Items & utility ───────────────────────────────────────────────
new("item.heal_ok", "Items", "Healing kit success",
@ -153,6 +233,14 @@ internal static class RynthChatPresets
new("item.heal_fail", "Items", "Healing kit failure",
"\"You fail to heal yourself.\"",
"You fail to heal yourself. ", Scope.NotPlayerChat, @"^You fail to heal yourself\."),
new("item.healed_by_other", "Items", "Healed by another",
"\"X casts Y and restores N points of your …\"",
"Bob casts Heal Other VI and restores 80 points of your health.", Scope.NotPlayerChat,
@"^.+ casts .+ and restores \d+ points of your "),
new("item.consumable", "Items", "Food / potion restores",
"\"The X restores N points of your …\"",
"The Health Tonic restores 50 points of your health.", Scope.NotPlayerChat,
@"^The .+ restores \d+ points of your "),
new("item.salvage", "Items", "Salvage results",
"\"You obtain … using your knowledge of …\"",
"You obtain 12 Steel (ws 7.00) using your knowledge of Weapon Tinkering.", Scope.NotPlayerChat, @"^You obtain .+ using your knowledge of "),
@ -169,6 +257,15 @@ internal static class RynthChatPresets
new("item.regen", "Items", "Periodic healing ticks",
"\"You receive N points of periodic healing.\"",
"You receive 12 points of periodic healing.", Scope.NotPlayerChat, @"^You receive .+ points of periodic healing"),
new("item.aetheria_surge", "Items", "Aetheria surges",
"\"Aetheria surges on…\" (classic UB Misc filter).",
"Aetheria surges on Bob, increasing his damage.", Scope.NotPlayerChat, @"^Aetheria surges on"),
new("item.cloak", "Items", "Cloak procs",
"\"The cloak of…\" cloak cast lines (classic UB Misc filter).",
"The cloak of Bob weaves a protective spell.", Scope.NotPlayerChat, @"^The cloak of"),
new("item.banked_lum", "Items", "Banked luminance",
"\"You've banked N Luminance.\" (classic UB Misc filter).",
"You've banked 1,250 Luminance.", Scope.NotPlayerChat, @"^You've banked [\d,]+ Luminance\.\s*$"),
// ── Social & trade ────────────────────────────────────────────────
new("social.bot_spam", "Social", "Trade / buff bot spam",
@ -180,6 +277,16 @@ internal static class RynthChatPresets
new("social.kill_task", "Social", "Kill task complete",
"\"You have killed N Xs! Your task is complete!\"",
"You have killed 50 Drudges! Your task is complete!", Scope.NotPlayerChat, @"^You have killed \d+ .+Your task is complete!\s*$"),
new("social.kill_task_progress", "Social", "Kill task progress",
"\"You have killed N Xs! You must kill M to complete your task.\" (ACECustom / UB-IT).",
"You have killed 12 Drudges! You must kill 50 to complete your task.", Scope.NotPlayerChat,
@"^You have killed \d+ .+! You must kill \d+ to complete your task\.\s*$"),
new("social.too_busy", "Social", "You're too busy",
"\"You're too busy!\" (also Mag StatusTextYoureTooBusy when it lands in chat).",
"You're too busy!", Scope.NotPlayerChat, @"^You're too busy!\s*$"),
new("social.casting_status", "Social", "Casting status text",
"\"Casting …\" overlay lines when they appear in chat (Mag StatusTextCasting).",
"Casting Focus Self VII", Scope.NotPlayerChat, @"^Casting "),
new("social.general", "Social", "General channel",
"Everything said on General.",
"[General] Bob says, \"hi\"", Scope.ChannelsOnly, @"^\[General\]|says on the General channel"),
@ -197,6 +304,10 @@ internal static class RynthChatPresets
"[Society] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[(?:Society|Celestial Hand|Eldrytch Web|Radiant Blood)\]|says on the (?:Society|Celestial Hand|Eldrytch Web|Radiant Blood) channel"),
// ── NPCs ──────────────────────────────────────────────────────────
new("npc.arbitrator_spam", "NPCs", "Master Arbitrator spam",
"Selected Colosseum spam (title / key / arena instructions); keeps \"Well done!\" / \"Good Luck!\".",
"Master Arbitrator tells you, \"You shall be known…\"", Scope.Any,
@"(?:^Master Arbitrator tells you,.+(?:""You shall be known|""Take this knowledge|""Use the the key)|(?:\[Fellowship\] )?Master Arbitrator says,.+(?:""Your fellowship|""Use one of the|""Don't forget))"),
new("npc.arbitrator", "NPCs", "Master Arbitrator (Colosseum)",
"All Master Arbitrator speech and the fellowship-lock notice.",
"Master Arbitrator tells you, \"You shall be known…\"", Scope.Any,

View file

@ -334,7 +334,18 @@ internal static class SettingsPanel
case SettingKind.Spacer:
return Spacer();
case SettingKind.Button:
return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip);
return ButtonRow(row.Label, row.ButtonText ?? row.Label, () =>
{
// A settings edit is pushed like a typed value; the tab is rebuilt so the
// number boxes show the new values.
if (row.Edit != null)
{
row.Edit(state.Data);
Push(state);
state.Rebuild?.Invoke();
}
row.Click?.Invoke();
}, row.Tooltip);
case SettingKind.TraceCategories:
return TraceCategoriesRow(state, row);
case SettingKind.Text:

View file

@ -643,6 +643,8 @@ internal static class ScriptWindowRegistry
Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>());
Volatile.Write(ref _barButtons, Array.Empty<ScriptBarItem>());
}
// Engine reload / shutdown: the Skills embed hides and Oracle's announcement is forgotten.
ImGuiBackend.Panels.OracleSkillsEmbed.Shutdown();
}
/// <summary>
@ -882,6 +884,10 @@ internal static class ScriptWindowRegistry
w.Removed = true;
w.SubmittedVisible = false;
_barDirty = true;
// Oracle's window went (plugin unloaded or stopped drawing it): its Skills embed hides now,
// not at the next frame, which may never come (reload, shutdown).
if (ImGuiBackend.Panels.OracleSkillsEmbed.IsOraclePanel(w.PanelKey))
ImGuiBackend.Panels.OracleSkillsEmbed.Clear();
owner.Windows.Remove(w.Key);
if (ByPanelKey.TryGetValue(w.PanelKey, out ScriptWindow? cur) && ReferenceEquals(cur, w))
ByPanelKey.Remove(w.PanelKey);