Snapshot for release 2026.10.12.1 (internal ef4d41d)

This commit is contained in:
Tom Bohar 2026-10-12 00:33:12 -04:00
commit b0f9d74b21
54 changed files with 5062 additions and 935 deletions

View file

@ -984,11 +984,46 @@ internal static class AcMainThreadQueue
_castTargetId = targetId;
_castSpellId = spellId;
_castQueuedAt = NowMs;
_castStopWaitNoted = false;
_castPending = 1;
return true;
}
}
// Casts that waited for a movement stop queued ahead of them (counted once per cast).
private static long _castStopWaits;
private static bool _castStopWaitNoted;
/// <summary>Casts that waited one or more ticks for a stop queued ahead of them.</summary>
public static long CastStopWaitCount => Interlocked.Read(ref _castStopWaits);
/// <summary>A movement stop (autorun off, a motion off, StopMovement, StopCompletely).</summary>
private static bool IsMovementStop(in Entry e) => e.Kind switch
{
ActionKind.SetAutoRun => e.A == 0,
ActionKind.SetMotion => e.B == 0,
ActionKind.StopMovement or ActionKind.StopCompletely => true,
_ => false,
};
/// <summary>
/// True when the action ring holds a movement stop queued at or before <paramref name="castQueuedAt"/>.
/// Main thread only (the ring's sole consumer). Entries are stamped under the producer lock, so
/// their times rise from head to tail and the walk stops at the first newer one.
/// </summary>
private static bool StopQueuedAtOrBefore(long castQueuedAt)
{
int head = _head;
int tail = Volatile.Read(ref _tail);
for (int i = head; i != tail; i++)
{
ref readonly Entry e = ref _slots[i & Mask];
if (e.At > castQueuedAt) return false;
if (IsMovementStop(e)) return true;
}
return false;
}
// Drained on AC's MAIN thread from the Client::UseTime detour (game-logic tick).
// Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the
// cast directly (SelectItem + ClientMagicSystem::CastSpell via the SEH trampoline).
@ -1028,6 +1063,62 @@ internal static class AcMainThreadQueue
return;
}
// ── A stop queued before the cast goes first (2026-10-12) ─────────────
// Casts drain here (Client::UseTime, before the tick), the action ring at EndScene,
// so an autorun-off or a motion-off the bot queued BEFORE its cast used to run AFTER
// it: the cast's FreeHandsAndCastSpell -> MaybeStopCompletely sent its stop with AC's
// locomotion still on, and the queued stops followed as extra MoveToStates. Wait (at
// most until EndScene drains the ring, about one frame; the ring's own gesture defer
// is shorter than CastDeferMaxMs) while one is queued; past the limit cast anyway.
if (StopQueuedAtOrBefore(Volatile.Read(ref _castQueuedAt)))
{
if (castAge <= CastDeferMaxMs)
{
if (!_castStopWaitNoted)
{
_castStopWaitNoted = true;
Interlocked.Increment(ref _castStopWaits);
try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: "cast waits for a movement stop queued before it"); } catch { }
}
return; // retry next tick, after the ring drains
}
}
// ── The stop goes a server answer ahead of the cast (2026-10-12, PreCastStopRules) ──
long castStamp = Volatile.Read(ref _castQueuedAt);
if (_preStopFor != castStamp) { _preStopFor = castStamp; _preStopSent = false; }
long nowMs = NowMs;
PreCastStep step = PreCastStopRules.Decide(
_preStopSent ? 0 : CommandInterpreterHooks.ReadControlledByServer(),
_preStopSent,
Interlocked.Read(ref _playerMotionEchoes) - _preStopEchoBase,
nowMs - _preStopAt);
if (step == PreCastStep.SendStop)
{
if (castAge <= CastDeferMaxMs)
{
_preStopEchoBase = Interlocked.Read(ref _playerMotionEchoes);
if (CommandInterpreterHooks.StopCompletely())
{
_preStopSent = true;
_preStopAt = nowMs;
Interlocked.Increment(ref _preCastStops);
try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: "pre-cast stop sent; the cast waits for the server's answer"); } catch { }
return; // cast on a later tick, after the answer
}
}
step = PreCastStep.CastNow; // couldn't send it: cast as before
}
else if (step == PreCastStep.Wait)
{
if (castAge <= CastDeferMaxMs + PreCastStopRules.EchoMaxMs)
return;
step = PreCastStep.CastWithoutStop;
}
bool withoutStop = step == PreCastStep.CastWithoutStop;
if (withoutStop && Interlocked.Read(ref _playerMotionEchoes) == _preStopEchoBase)
Interlocked.Increment(ref _preCastEchoTimeouts);
uint target, spell;
lock (_castLock)
{
@ -1038,6 +1129,23 @@ internal static class AcMainThreadQueue
}
if (castAge > LateActionLogMs)
NoteStale($"CastSpell({spell})", castAge, dropped: false);
CombatActionHooks.CastSpell(target, unchecked((int)spell));
CombatActionHooks.CastSpell(target, unchecked((int)spell), suppressMoveStop: withoutStop);
}
// Pre-cast stop state (main thread only).
private static long _preStopFor = long.MinValue;
private static bool _preStopSent;
private static long _preStopAt;
private static long _preStopEchoBase;
private static long _playerMotionEchoes;
private static long _preCastStops;
private static long _preCastEchoTimeouts;
/// <summary>Casts whose stop the engine sent ahead of them.</summary>
public static long PreCastStopCount => Interlocked.Read(ref _preCastStops);
/// <summary>Of those, casts that went without seeing the server's answer (EchoMaxMs ran out).</summary>
public static long PreCastEchoTimeoutCount => Interlocked.Read(ref _preCastEchoTimeouts);
/// <summary>An autonomous UpdateMotion for the player arrived (SmartBoxHooks, main thread).</summary>
public static void NotePlayerMotionEcho() => Interlocked.Increment(ref _playerMotionEchoes);
}

View file

@ -928,6 +928,9 @@ internal static class ClientHelperHooks
// refreshed every EndScene by EngineFrameController, 0 = no player / not ready.
private static int _cachedPlayerId;
/// <summary>The player id last read on the main thread (0 = none yet); no native call.</summary>
public static uint CachedPlayerId => unchecked((uint)Volatile.Read(ref _cachedPlayerId));
public static uint GetPlayerId()
{
if (_getPlayerId == null)

View file

@ -474,7 +474,14 @@ internal static class CombatActionHooks
}
}
public static bool CastSpell(uint targetId, int spellId)
public static bool CastSpell(uint targetId, int spellId) => CastSpell(targetId, spellId, suppressMoveStop: false);
/// <param name="suppressMoveStop">
/// The engine already sent this cast's stop and the server answered it (AcMainThreadQueue
/// DrainCasts, PreCastStopRules): FreeHandsAndCastSpell's MaybeStopCompletely is made to send
/// nothing for the length of the call, so no stop rides in the cast's frame.
/// </param>
internal static bool CastSpell(uint targetId, int spellId, bool suppressMoveStop)
{
if (spellId <= 0) return false;
if (_castSpellClient == null) return false;
@ -543,7 +550,11 @@ internal static class CombatActionHooks
// busy leak. BusyCountHooks reconciles the delta once the cast
// gesture completes.
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
bool okCast = SehTrampoline.FreeHandsCast(_freeHandsCastPtr, mgr, (uint)spellId, targetId);
int savedCtl = 0;
IntPtr suppressed = suppressMoveStop ? CommandInterpreterHooks.BeginCastStopSuppression(out savedCtl) : IntPtr.Zero;
bool okCast;
try { okCast = SehTrampoline.FreeHandsCast(_freeHandsCastPtr, mgr, (uint)spellId, targetId); }
finally { if (suppressed != IntPtr.Zero) CommandInterpreterHooks.EndCastStopSuppression(suppressed, savedCtl); }
BusyCountHooks.NoteDirectCastIssued(busyBefore);
if (!okCast && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] AV in FreeHandsAndCastSpell spell={spellId} target=0x{targetId:X8} — caught");
@ -560,7 +571,11 @@ internal static class CombatActionHooks
// buff self-casts were the dominant leak source (4322 plugin
// clears / 10h soak, nearly all on buffs).
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
bool ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, (uint)spellId, 0);
int savedCtl = 0;
IntPtr suppressed = suppressMoveStop ? CommandInterpreterHooks.BeginCastStopSuppression(out savedCtl) : IntPtr.Zero;
bool ok;
try { ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, (uint)spellId, 0); }
finally { if (suppressed != IntPtr.Zero) CommandInterpreterHooks.EndCastStopSuppression(suppressed, savedCtl); }
BusyCountHooks.NoteDirectCastIssued(busyBefore);
if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] AV in self-CastSpell spell={spellId} — caught");

View file

@ -25,6 +25,19 @@ internal static class CommandInterpreterHooks
private const int TakeControlOffsetFromSetAutoRun = ReferenceCommandInterpreterTakeControlFromServer - ReferenceCommandInterpreterSetAutoRun;
private const int ClearAllCommandsOffsetFromSetAutoRun = ReferenceCommandInterpreterClearAllCommands - ReferenceCommandInterpreterSetAutoRun;
// CommandInterpreter::SendMovementEvent (vtable slot 19 = +0x4C, VA 0x006B55C0, thiscall,
// no args, plain ret): sends the current raw motion state to the server as a MoveToState
// (0xF61C). Bound from the live vtable and accepted only when it sits at the reference
// distance from SetAutoRun (same binary layout); otherwise it stays null and SetAutoRun
// behaves as before (no send).
private const int VtblSendMovementEventIndex = 19;
private const int ReferenceCommandInterpreterSendMovementEvent = 0x006B55C0;
private const int SendMovementEventOffsetFromSetAutoRun = ReferenceCommandInterpreterSendMovementEvent - ReferenceCommandInterpreterSetAutoRun;
// CommandInterpreter.autoRun (int): SetAutoRun(val, ...) compares and writes [this+0x48];
// ToggleAutoRun reads it (acclient 0x006B5790 / 0x006B4C00).
internal const int CmdInterpAutoRunOffset = 0x48;
// Verified unique + lands at the Reference VA offline (tools/pe_pattern.py).
// Primary resolution; the *Offset deltas below remain as fallback only.
private static readonly byte?[] SetMotionPattern = [ 0x8B, 0x41, 0x08, 0x81, 0xEC, 0x0C, 0x01, 0x00 ];
@ -61,6 +74,9 @@ internal static class CommandInterpreterHooks
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void ClearAllCommandsDelegate(IntPtr thisPtr);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void SendMovementEventDelegate(IntPtr thisPtr);
private static IntPtr _smartboxStaticAddr;
private static IntPtr _boundCmdInterp;
private static bool _absResolved;
@ -74,8 +90,15 @@ internal static class CommandInterpreterHooks
private static PlayerTeleportedDelegate? _playerTeleported;
private static TakeControlFromServerDelegate? _takeControlFromServer;
private static ClearAllCommandsDelegate? _clearAllCommands;
private static SendMovementEventDelegate? _sendMovementEvent;
private static bool _sendMovementEventMissLogged;
private static long _autoRunMovementSends;
private static string _statusMessage = "Not probed yet.";
/// <summary>MoveToStates sent after an autorun change (diagnostics).</summary>
public static long AutoRunMovementSends => System.Threading.Interlocked.Read(ref _autoRunMovementSends);
public static bool HasSendMovementEvent => _sendMovementEvent != null;
public static bool IsInitialized { get; private set; }
public static bool HasTapJump => _commenceJump != null && _doJump != null;
public static bool HasSetAutoRun => _setAutoRun != null;
@ -152,9 +175,39 @@ internal static class CommandInterpreterHooks
try
{
// Tell the server, like AC's own autorun key and Decal's SetAutorun (2026-10-12).
// CommandInterpreter::SetAutoRun(val, applyMovement) only changes the LOCAL motion
// (MovePlayer -> DoMotion/StopMotion); it never sends a MoveToState. AC's autorun key
// (HandleKeyboardCommand 0x090000C7) is ToggleAutoRun + SendMovementEvent, and
// Decal's IACHooks::SetAutorun (Decal.dll 0x18025C10) is SetAutoRun(on, 1) followed by
// one more no-arg cmdinterp call. Without the send the server never learned that the
// bot started or stopped running: the client ran on AutonomousPositions alone, and the
// next SendMovementEvent - a SetMotion turn-off, or the cast's own
// FreeHandsAndCastSpell -> MaybeStopCompletely -> StopCompletely - delivered a burst
// of stops for a run the server had never seen (flight 63260, 12:27:44 / 12:35:55 /
// 12:38:56: every bad burst had no forward command; the harmless ones began with
// WalkForward). Sent only when AC's flag really changed: nav re-sends autorun every
// tick and AC ignores an unchanged value, so a send each time would spam the server.
int before = TryReadAutoRunFlag(_boundCmdInterp);
_setAutoRun!(_boundCmdInterp, enabled ? 1 : 0, 1);
int after = TryReadAutoRunFlag(_boundCmdInterp);
bool sent = false;
if (before >= 0 && after >= 0 && before != after)
{
if (_sendMovementEvent != null)
{
_sendMovementEvent(_boundCmdInterp);
System.Threading.Interlocked.Increment(ref _autoRunMovementSends);
sent = true;
}
else if (!_sendMovementEventMissLogged)
{
_sendMovementEventMissLogged = true;
RynthLog.Compat("Move: SetAutoRun changed AC's autorun but SendMovementEvent is not bound - the server is not told (old behavior).");
}
}
if (ShouldLogMove(n))
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} -> ok (cmdInterp=0x{_boundCmdInterp.ToInt32():X8})");
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} -> ok (cmdInterp=0x{_boundCmdInterp.ToInt32():X8}, autorun {before}->{after}{(sent ? ", MoveToState sent" : "")})");
return true;
}
catch (Exception ex)
@ -165,6 +218,55 @@ internal static class CommandInterpreterHooks
}
}
// CommandInterpreter.controlled_by_server (int, +0x34): LoseControlToServer sets it to 1,
// TakeControlFromServer to 0. MaybeStopCompletely (vtable +0xC0, 0x006B4AD0) - the first thing
// ClientMagicSystem::FreeHandsAndCastSpell (0x00567C90) does - calls StopCompletely (and so
// sends a MoveToState) only while it is 0, i.e. while the player has control.
internal const int CmdInterpControlledByServerOffset = 0x34;
/// <summary>1 the server has control (a cast sends no stop), 0 the player has (a cast sends one), -1 unknown. Main thread.</summary>
public static int ReadControlledByServer()
{
if (!MainThreadGuard.IsOnMainThread() || !TryBindDelegates()) return -1;
try { return Marshal.ReadInt32(_boundCmdInterp + CmdInterpControlledByServerOffset) != 0 ? 1 : 0; }
catch { return -1; }
}
/// <summary>
/// For the length of one cast call: makes MaybeStopCompletely see "server has control", so
/// FreeHandsAndCastSpell sends no stop in the cast's frame. Only for a cast whose stop the
/// engine already sent a server answer ahead (PreCastStop). Returns the command interpreter to
/// pass to <see cref="EndCastStopSuppression"/>, or Zero when nothing was changed.
/// </summary>
public static IntPtr BeginCastStopSuppression(out int saved)
{
saved = 0;
if (!MainThreadGuard.IsOnMainThread() || !TryBindDelegates()) return IntPtr.Zero;
try
{
IntPtr ci = _boundCmdInterp;
saved = Marshal.ReadInt32(ci + CmdInterpControlledByServerOffset);
if (saved != 0) return IntPtr.Zero; // already no stop: nothing to do
Marshal.WriteInt32(ci + CmdInterpControlledByServerOffset, 1);
return ci;
}
catch { return IntPtr.Zero; }
}
public static void EndCastStopSuppression(IntPtr cmdInterp, int saved)
{
if (cmdInterp == IntPtr.Zero || !MainThreadGuard.IsOnMainThread()) return;
try { Marshal.WriteInt32(cmdInterp + CmdInterpControlledByServerOffset, saved); } catch { }
}
/// <summary>AC's autorun flag (0/1), or -1 when it can't be read.</summary>
private static int TryReadAutoRunFlag(IntPtr cmdInterp)
{
if (cmdInterp == IntPtr.Zero) return -1;
try { return Marshal.ReadInt32(cmdInterp + CmdInterpAutoRunOffset) != 0 ? 1 : 0; }
catch { return -1; }
}
public static bool SetMotion(uint motion, bool enabled)
{
if (!MainThreadGuard.IsOnMainThread())
@ -461,6 +563,21 @@ internal static class CommandInterpreterHooks
_takeControlFromServer = Marshal.GetDelegateForFunctionPointer<TakeControlFromServerDelegate>(takeControlPtr);
_clearAllCommands = Marshal.GetDelegateForFunctionPointer<ClearAllCommandsDelegate>(clearAllCommandsPtr);
// Optional: SendMovementEvent from the vtable, only at the reference distance from
// SetAutoRun. A miss leaves it null (SetAutoRun then sends nothing, as before) and never
// fails the binding of the others.
IntPtr sendMovementPtr = Marshal.ReadIntPtr(vtable, VtblSendMovementEventIndex * IntPtr.Size);
if (sendMovementPtr == AddOffset(setAutoRunPtr, SendMovementEventOffsetFromSetAutoRun)
&& SmartBoxLocator.IsPointerInModule(sendMovementPtr))
{
_sendMovementEvent = Marshal.GetDelegateForFunctionPointer<SendMovementEventDelegate>(sendMovementPtr);
}
else
{
_sendMovementEvent = null;
RynthLog.Compat($"Compat: CommandInterpreter::SendMovementEvent not bound (vtable slot {VtblSendMovementEventIndex} = 0x{sendMovementPtr.ToInt32():X8}, expected SetAutoRun{SendMovementEventOffsetFromSetAutoRun:+0;-0}) - autorun changes are not sent to the server.");
}
_smartboxStaticAddr = selectedStaticAddr;
_boundCmdInterp = cmdInterp;
IsInitialized = true;
@ -496,6 +613,7 @@ internal static class CommandInterpreterHooks
_playerTeleported = null;
_takeControlFromServer = null;
_clearAllCommands = null;
_sendMovementEvent = null;
IsInitialized = false;
_statusMessage = "Not probed yet.";
}

View file

@ -59,6 +59,9 @@ internal static class GameTickHooks
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
/// <summary>Client::UseTime returned 0: AC's game loop is exiting (any exit path).</summary>
public static bool GameLoopExiting => Volatile.Read(ref _exitLatch) != 0;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
@ -203,6 +206,10 @@ internal static class GameTickHooks
// Flight recorder: per-second summary, stall detectors, scheduled automatic dump.
try { Net.FlightRecorder.MainTick(); }
catch { }
// AC's "server has disconnected" screen: close the client after a short wait so a
// launcher can relaunch it (EngineSettings.CloseOnServerDisconnect).
try { ServerDisconnectClose.MainTick(); }
catch { }
// MUST return Client::UseTime's own bool — AC loops do/while on it.
return result;

View file

@ -0,0 +1,51 @@
namespace RynthCore.Engine.Compatibility;
// ============================================================================
// The stop before a cast goes a server answer ahead of the cast (2026-10-12).
//
// ClientMagicSystem::FreeHandsAndCastSpell (every cast path: ours, the UI's, Decal's
// ClientMagicSystem::CastSpell) starts with cmdinterp->MaybeStopCompletely(): while the player
// has control of the character (controlled_by_server == 0) that is StopCompletely, and so a
// MoveToState stop in the SAME frame as the CastTargetedSpell. Flight 63260: every run of
// projectile casts that never landed began with a stop burst in a cast's frame; ACE launches
// projectiles from its own physics copy of the caster, which such a frame can leave wrong.
//
// So, for a queued cast while the player has control, AcMainThreadQueue.DrainCasts:
// 1. sends the stop itself (CommandInterpreterHooks.StopCompletely) and does not cast;
// 2. waits for the server's answer to it - the next UpdateMotion for the player
// (SmartBoxHooks counts them) - or EchoMaxMs;
// 3. then casts with MaybeStopCompletely's stop suppressed (the state it would send is the
// one just sent and answered).
// With the server in control (after a cast's server turn: the usual case between casts) the
// cast sends no stop anyway and goes at once. Pure decision code (no AC access), so the tests
// in tools/PreCastStopTests compile it on its own.
// ============================================================================
internal enum PreCastStep
{
/// <summary>Cast now, as before (no stop would ride with it, or the state can't be read).</summary>
CastNow,
/// <summary>Send the pre-cast stop now; don't cast this tick.</summary>
SendStop,
/// <summary>The stop went out; wait for the server's answer.</summary>
Wait,
/// <summary>The stop was answered (or the wait ran out): cast, without the cast's own stop.</summary>
CastWithoutStop,
}
internal static class PreCastStopRules
{
/// <summary>The longest a cast waits for the server's answer to its stop.</summary>
public const long EchoMaxMs = 750;
/// <param name="controlledByServer">1 server has control, 0 the player has, -1 unknown.</param>
/// <param name="stopSent">The pre-cast stop for this cast already went out.</param>
/// <param name="echoesSinceStop">Player UpdateMotions counted since the stop went out.</param>
/// <param name="msSinceStop">Milliseconds since the stop went out.</param>
public static PreCastStep Decide(int controlledByServer, bool stopSent, long echoesSinceStop, long msSinceStop)
{
if (stopSent)
return echoesSinceStop > 0 || msSinceStop >= EchoMaxMs ? PreCastStep.CastWithoutStop : PreCastStep.Wait;
return controlledByServer == 0 ? PreCastStep.SendStop : PreCastStep.CastNow;
}
}

View file

@ -77,6 +77,7 @@ namespace RynthCore.Engine.Compatibility;
/// the last minutes of client/server messages and engine markers) to
/// Logs\flight-&lt;pid&gt;-&lt;time&gt;.txt; <c>/rc flightdump auto &lt;reason&gt;</c> is the rate-limited
/// automatic form. <c>/rc flight [status|mark &lt;text&gt;|on|off|auto on|off]</c>.</item>
/// <item><c>/rc quit</c> / <c>/rc exit</c> - closes the client cleanly, as its close button does.</item>
/// <item><c>/rc report [text]</c> - "Report a problem" (<see cref="Report.ProblemReport"/>): alone it
/// opens the panel; with text it sends that report now, with the recent log attached
/// (the panel is where the log can be left out). One report a minute.</item>
@ -254,6 +255,15 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc quit | /rc exit : close the client cleanly (as its close button; the character logs off)
if (IsVerb(sub, "quit", out _) || IsVerb(sub, "exit", out _))
{
Reply("Closing the client.");
try { ServerDisconnectClose.CloseClientNow("/rc quit"); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc quit failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc report [text] : Report a problem - alone it opens the panel; with text it sends now (with the log)
if (IsVerb(sub, "report", out string reportArgs))
{

View file

@ -0,0 +1,131 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ServerDisconnectClose.cs
//
// Closes the client when AC lost the server (2026-10-11). AC then shows "The server
// has disconnected. Please try again in a few minutes." with only a Quit Game button,
// and the client sat there until someone clicked it, so no launcher relaunched it.
//
// Signal: UIFlow mode Disconnected (0x10000002, UiFlowHooks), which AC switches to only
// when the connection is gone. In the logs of 2026-10-05..11 it appears exactly at the
// eight drops (World -> Disconnected seven times, CharacterSelect -> Disconnected once)
// and never on a logout (World -> CharacterSelect) or a quit (no screen change). The
// other candidates were weaker: ClientNet::LogOffServer also runs on every quit (twice,
// from Client::Disconnect and Client::CleanupNet) and came up to 142 s after the screen;
// the logoff request AC sends (gmGamePlayUI::EndSession -> LogOffCharacter) looks like
// any other logoff.
//
// What it does (AC's main thread, GameTickHooks post-tick, so the mode poll just ran):
// - first tick on the screen: logs it and asks the flight recorder for a dump (the
// last minutes of traffic say whether the server went quiet or sent a disconnect);
// - after ServerDisconnectClosePolicy.DefaultDelayMs (5 s; longer while that dump is
// being written): posts WM_CLOSE to the game window, the same as its close button.
// That runs the normal shutdown: Win32Backend stops the plugin pump and starts
// EngineLifecycle.Shutdown, AC's UseTime returns 0 and the client exits with 0;
// - still open 20 s later: posts WM_CLOSE once more; 60 s later: says so and stops.
// Off (engine.json CloseOnServerDisconnect false, Settings > Misc): only the log line.
// Polled rather than evented, so a hot reload on the screen still closes the client.
// ============================================================================
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class ServerDisconnectClose
{
private const uint WM_CLOSE = 0x0010;
[DllImport("user32.dll", SetLastError = true)]
private static extern bool PostMessageW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool IsWindow(IntPtr hWnd);
private static readonly ServerDisconnectClosePolicy Policy = new();
private static int _fromMode;
/// <summary>AC's main thread, every game tick (GameTickHooks, after the queue drain).</summary>
public static void MainTick()
{
int mode = UiFlowHooks.CurrentMode;
bool disconnected = mode == UiFlowHooks.ModeDisconnected;
if (!disconnected && !Policy.OnScreen)
return; // the common case: two reads and out
long now = Environment.TickCount64;
bool exiting = GameTickHooks.GameLoopExiting || UiFlowHooks.ClientCleanupStarted || EngineThreads.Stopping;
bool enabled = EngineSettings.CloseOnServerDisconnect;
bool dumpBusy = false;
try { dumpBusy = Net.FlightRecorder.DumpPendingOrRunning; } catch { }
long onScreenMs = Policy.OnScreenMs(now);
switch (Policy.Update(now, disconnected, enabled, exiting, dumpBusy))
{
case ServerDisconnectClosePolicy.Verdict.Detected:
OnDetected(enabled);
break;
case ServerDisconnectClosePolicy.Verdict.Close:
PostClose($"closing the client after {onScreenMs / 1000.0:0.0}s on the Disconnected screen{(dumpBusy ? " (waited for the flight dump)" : "")}");
break;
case ServerDisconnectClosePolicy.Verdict.Retry:
PostClose($"the client is still open {ServerDisconnectClosePolicy.RetryAfterMs / 1000}s after WM_CLOSE - sending it again");
break;
case ServerDisconnectClosePolicy.Verdict.GiveUp:
RynthLog.Error($"ServerDisconnect: the client is still open {ServerDisconnectClosePolicy.GiveUpAfterMs / 1000}s after WM_CLOSE (sent twice) - not trying again. Click Quit Game.");
break;
case ServerDisconnectClosePolicy.Verdict.Left:
RynthLog.Warn($"ServerDisconnect: the Disconnected screen went away after {onScreenMs / 1000.0:0.0}s (now {UiFlowHooks.ModeName(mode)}) before the client closed.");
break;
}
}
private static void OnDetected(bool enabled)
{
_fromMode = UiFlowHooks.PreviousMode;
string who = DescribeSession();
string action = enabled
? $"closing the client in {Policy.DelayMs / 1000}s so a launcher can relaunch it (Close on server disconnect, Settings > Misc)"
: "Close on server disconnect is off (Settings > Misc) - the client stays on this screen";
RynthLog.Warn($"ServerDisconnect: AC lost the server and shows its 'server has disconnected' screen ({UiFlowHooks.ModeName(_fromMode)} -> Disconnected){who}; {action}.");
try { Net.FlightRecorder.RequestAuto("server disconnect (the Disconnected screen)", "engine"); }
catch { }
}
private static string DescribeSession()
{
try
{
string ch = SessionStateRegistry.LastCharacterName;
string acct = SessionStateRegistry.LastAccountName;
string world = AccountHooks.AnnouncedWorldName ?? SessionStateRegistry.LastServerName;
if (string.IsNullOrEmpty(ch) && string.IsNullOrEmpty(acct) && string.IsNullOrEmpty(world))
return "";
return $" - {(string.IsNullOrEmpty(ch) ? "?" : ch)} ({(string.IsNullOrEmpty(acct) ? "?" : acct)}) on {(string.IsNullOrEmpty(world) ? "?" : world)}";
}
catch { return ""; }
}
/// <summary>
/// Closes the client now, the way its close button does (WM_CLOSE: AC logs the character
/// off and the engine shuts down normally). /rc quit, and RynthAi's /ra, /mt and /ub quit.
/// </summary>
public static void CloseClientNow(string why) => PostClose(why);
private static void PostClose(string why)
{
IntPtr hwnd = ImGuiBackend.Win32Backend.GameHwnd;
if (hwnd == IntPtr.Zero || !IsWindow(hwnd))
{
try { hwnd = Process.GetCurrentProcess().MainWindowHandle; } catch { hwnd = IntPtr.Zero; }
}
if (hwnd == IntPtr.Zero)
{
RynthLog.Error($"ServerDisconnect: {why}, but the game window isn't known - can't close the client.");
return;
}
bool ok = PostMessageW(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
int err = ok ? 0 : Marshal.GetLastWin32Error();
RynthLog.Warn($"ServerDisconnect: {why} - WM_CLOSE to 0x{hwnd.ToInt64():X} {(ok ? "posted" : $"FAILED (Win32 error {err})")}.");
}
}

View file

@ -0,0 +1,112 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ServerDisconnectClosePolicy.cs
//
// When to close the client after AC lost the server (ServerDisconnectClose.cs does
// the closing). No engine dependencies: tools/DisconnectCloseTests compiles this file.
//
// Fed once per game tick with the clock and what the engine sees:
// - disconnected: AC's UIFlow mode is Disconnected (0x10000002), the screen that says
// "The server has disconnected. Please try again in a few minutes." with only a
// Quit Game button. AC switches to it only when the connection is gone; a logout
// goes to character select and a quit never changes the screen.
// - enabled: engine.json CloseOnServerDisconnect.
// - exiting: the client is already closing (UseTime returned 0 / Client::Cleanup).
// - dumpBusy: the flight recorder is writing (or about to write) its dump of the
// disconnect; the close waits for it, up to DumpGraceMs more.
//
// Answers, at most once each per visit to the screen:
// Detected - first tick on the screen (log it, ask for a flight dump);
// Close - DelayMs on the screen: close the client (WM_CLOSE);
// Retry - RetryAfterMs after Close and still here: close again;
// GiveUp - GiveUpAfterMs after Close and still here: say so, stop trying;
// Left - the screen went away before the client closed (start over next time).
// ============================================================================
namespace RynthCore.Engine.Compatibility;
internal sealed class ServerDisconnectClosePolicy
{
public const long DefaultDelayMs = 5000;
public const long DumpGraceMs = 10000;
public const long RetryAfterMs = 20000;
public const long GiveUpAfterMs = 60000;
public enum Verdict { None, Detected, Close, Retry, GiveUp, Left }
private readonly long _delayMs;
private long _sinceMs; // when the screen was first seen; 0 = not on it
private long _closedAtMs; // when Close was answered; 0 = not yet
private int _attempts; // Close + Retry answers this visit
private bool _gaveUp;
public ServerDisconnectClosePolicy(long delayMs = DefaultDelayMs)
{
_delayMs = delayMs < 0 ? 0 : delayMs;
}
public long DelayMs => _delayMs;
/// <summary>On the Disconnected screen (as of the last Update).</summary>
public bool OnScreen => _sinceMs != 0;
/// <summary>Milliseconds on the screen as of <paramref name="nowMs"/>, 0 when not on it.</summary>
public long OnScreenMs(long nowMs) => _sinceMs == 0 ? 0 : nowMs - _sinceMs;
public int Attempts => _attempts;
public Verdict Update(long nowMs, bool disconnected, bool enabled, bool exiting, bool dumpBusy)
{
if (exiting)
return Verdict.None;
if (!disconnected)
{
if (_sinceMs == 0)
return Verdict.None;
Reset();
return Verdict.Left;
}
if (_sinceMs == 0)
{
_sinceMs = nowMs == 0 ? 1 : nowMs;
return Verdict.Detected;
}
if (!enabled)
return Verdict.None;
long onScreen = nowMs - _sinceMs;
if (_attempts == 0)
{
if (onScreen < _delayMs)
return Verdict.None;
if (dumpBusy && onScreen < _delayMs + DumpGraceMs)
return Verdict.None;
_attempts = 1;
_closedAtMs = nowMs;
return Verdict.Close;
}
long sinceClose = nowMs - _closedAtMs;
if (_attempts == 1 && sinceClose >= RetryAfterMs)
{
_attempts = 2;
return Verdict.Retry;
}
if (!_gaveUp && sinceClose >= GiveUpAfterMs)
{
_gaveUp = true;
return Verdict.GiveUp;
}
return Verdict.None;
}
private void Reset()
{
_sinceMs = 0;
_closedAtMs = 0;
_attempts = 0;
_gaveUp = false;
}
}

View file

@ -131,6 +131,8 @@ internal static class SmartBoxHooks
try
{
if (info.Opcode == PositionUpdateOpcode && info.RawObjectId != 0)
NotePlayerMotionEcho(blob, info);
TryQueueHealthUpdate(blob, info);
TryQueueDamageEvent(blob, info);
@ -671,6 +673,24 @@ internal static class SmartBoxHooks
}
}
// UpdateMotion (0xF74C) for the player with the autonomous flag set: the server's answer to a
// MoveToState from this client (layout: opcode, guid, u16 instance, u16 movement seq, u16
// server-control seq, u8 autonomous at +14). Counted for the pre-cast stop (PreCastStopRules).
private static void NotePlayerMotionEcho(IntPtr blob, SmartBoxEventInfo info)
{
if (info.BlobSize < 16) return;
uint player = ClientHelperHooks.CachedPlayerId;
if (player == 0 || info.RawObjectId != player) return;
try
{
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (payloadPtr == IntPtr.Zero) return;
if (Marshal.ReadByte(IntPtr.Add(payloadPtr, 14)) != 0)
AcMainThreadQueue.NotePlayerMotionEcho();
}
catch { }
}
private static void TryQueueHealthUpdate(IntPtr blob, SmartBoxEventInfo info)
{
if (info.Opcode != 0x01C0 || info.BlobSize < 12 || blob == IntPtr.Zero)

View file

@ -5,7 +5,9 @@
// Same content as the Avalonia bar, as square Phosphor icon buttons with
// the names in tooltips: the grip (RC: build stamp tooltip), one button per
// registered panel except the ones the RynthAi launcher opens (PanelIcons;
// an unknown panel shows its first letter), reload (RL) and pop out.
// an unknown panel shows its first letter), one per plugin script window that
// asked for a button (WindowFlags.BarButton: RynthSort, Oracle, ...; tooltip =
// its title; the set is rebuilt as plugins come and go), reload (RL) and pop out.
// Dragging the grip moves the bar; the position is the shared bar= row in
// panel_state.txt. Right-click a panel button (or the grip for the bar
// itself) to choose which face shows it docked; the grip's menu also has the
@ -48,8 +50,10 @@ internal static class ImGuiBar
private static readonly PanelFace[] Faces = { PanelFace.Avalonia, PanelFace.ImGui, PanelFace.Both };
private static readonly string[] FaceNames = { "Avalonia", "ImGui", "Both (side by side)" };
// Window: a plugin's script window with a bar button of its own (WindowFlags.BarButton);
// the button toggles it through ScriptWindowRegistry, like the Scripts menu does.
private sealed record ButtonInfo(string Title, string Id, string PopupId, string Icon, bool Letter, string Tooltip,
bool ImGuiOnly = false);
bool ImGuiOnly = false, ScriptWindow? Window = null);
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
private static readonly string[] ImGuiOnlyBarPanels =
@ -84,6 +88,10 @@ internal static class ImGuiBar
["Log"] = PhosphorIcons.TerminalWindow,
["Item Count"] = PhosphorIcons.Bag,
["Mini Remote"] = PhosphorIcons.SquaresFour,
// Plugin windows with a bar button of their own (script windows, by title).
["RynthSort"] = PhosphorIcons.SortAscending,
["Oracle"] = PhosphorIcons.Sparkle,
["Global Inventory"] = PhosphorIcons.GlobeHemisphereWest,
};
/// <summary>A panel's bar icon: its Phosphor icon, else its first letter (letter = true).</summary>
@ -111,6 +119,10 @@ internal static class ImGuiBar
}
private static ButtonInfo[]? _buttons;
// What _buttons was built from: the plugin windows' snapshot (a new array on every change)
// and which ImGui-only panels had a face. Either changing rebuilds the buttons.
private static ScriptBarItem[]? _builtScriptButtons;
private static int _builtImGuiOnlyMask;
private static string _tooltip = "";
private static bool _placed;
private static Vector2 _pos, _persistedPos;
@ -366,8 +378,11 @@ internal static class ImGuiBar
{
ImGuiNET.ImGui.SameLine();
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText))
PanelRouter.Toggle(b.Title);
ImGuiNET.ImGui.SetItemTooltip(b.Tooltip);
{
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !ImGuiPanelHost.IsOpen(b.Window.PanelKey));
else PanelRouter.Toggle(b.Title);
}
ImGuiNET.ImGui.SetItemTooltip(b.Tooltip); // a plugin window's title arrives with '%' doubled (EnsureButtons)
if (b.ImGuiOnly) continue; // no Avalonia face: no face to choose
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
ImGuiNET.ImGui.OpenPopup(b.PopupId);
@ -390,8 +405,8 @@ internal static class ImGuiBar
}
// Script windows (decision 2): one button with a menu, only while a ShowInBar
// script window exists. They never get buttons of their own (EnsureButtons
// lists OverlayHost's engine panels only; script windows are dynamic entries).
// script window exists. A window that also sets BarButton (plugin windows such as
// RynthSort's) has a button of its own instead (EnsureButtons) and isn't listed here.
ScriptBarItem[] scripts = ScriptWindowRegistry.BarItems;
if (scripts.Length > 0)
{
@ -591,9 +606,27 @@ internal static class ImGuiBar
ImGuiNET.ImGui.PopStyleVar(3);
}
/// <summary>Bit i set: ImGuiOnlyBarPanels[i] has a face now.</summary>
private static int ImGuiOnlyMask()
{
int mask = 0;
for (int i = 0; i < ImGuiOnlyBarPanels.Length; i++)
if (ImGuiPanelHost.HasFace(ImGuiOnlyBarPanels[i])) mask |= 1 << i;
return mask;
}
/// <summary>
/// The bar's buttons, rebuilt when the set changes: a plugin window with a bar button
/// appeared, went (plugin unloaded, window dropped) or was renamed, or an ImGui-only
/// panel's face was registered or removed. AC thread, every frame (two cheap checks).
/// </summary>
private static void EnsureButtons()
{
if (_buttons != null) return;
ScriptBarItem[] scriptButtons = ScriptWindowRegistry.BarButtons;
int mask = ImGuiOnlyMask();
if (_buttons != null && ReferenceEquals(scriptButtons, _builtScriptButtons) && mask == _builtImGuiOnlyMask) return;
_builtScriptButtons = scriptButtons;
_builtImGuiOnlyMask = mask;
var list = new List<ButtonInfo>();
foreach (var (title, _) in OverlayHost.GetPanels())
if (!LauncherOnly.Contains(title))
@ -608,6 +641,17 @@ internal static class ImGuiBar
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, title, ImGuiOnly: true));
}
// Plugin script windows that asked for a button (RynthSort, Oracle, ...): after the
// engine's own. Only while the plugin is loaded and has submitted the window.
foreach (ScriptBarItem item in scriptButtons)
{
ScriptWindow w = item.Window;
string title = w.Title.Length > 0 ? w.Title : w.Key;
string icon = IconFor(title, out bool letter);
string id = "##bar_sw" + w.Hash.ToString("X8");
// The tooltip goes through SetItemTooltip, a format function: the plugin's text with '%' doubled.
list.Add(new ButtonInfo(title, id, id + "_face", icon, letter, title.Replace("%", "%%"), ImGuiOnly: true, Window: w));
}
_buttons = list.ToArray();
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face and size. Ctrl+wheel over the bar: size.";
}

View file

@ -65,6 +65,7 @@ internal static unsafe class ImGuiFonts
// dashes are in MainRanges.
private static readonly ushort[] SymbolCodepoints =
{
0x2264, 0x2265, // ≤ ≥ (Meta rule list: "Prismatic Taper ≤ 50")
0x25CF, // ● (Meta source: unapplied edits)
};

View file

@ -17,7 +17,11 @@
// from it: move / copy lines like it to a tab, hide them, colour them. A line
// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go
// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them).
// Follows the newest line until you scroll up.
// 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
// as long as the "Chat history" setting (ChatHistory, up to 10,000 lines): no
// per-frame work walks all of it, and re-measuring after a resize is time-sliced.
//
// The input line belongs to ChatModel (UI/Data/ChatData.cs): Win32Backend
// turns the chat keys into ChatModel edits on AC's thread, which is also
@ -74,7 +78,11 @@ internal sealed class ChatFace : IImGuiPanel
private readonly List<float> _h = new(512);
private readonly List<SpanLayout?> _lay = new(512);
private float[] _tops = new float[1];
private int _heightsFrom; // first line whose height needs measuring
private int _heightsFrom; // first new line: not measured at all yet
// Lines below this index were measured for another width or font, or not at all (a
// rebuild gives them one row each until then): MeasureLines catches up a few ms a frame.
private int _measuredFrom;
private float _rowH = 13f; // one row of the chat font: an unmeasured line's height
private bool _topsDirty = true;
private long _seenLinesVersion = -1, _seenRoutes = -1, _lastId;
private string _seenTab = "", _seenSearch = "";
@ -88,6 +96,13 @@ internal sealed class ChatFace : IImGuiPanel
// tail: the view is moved up by as much, so the lines being read stay put instead of
// sliding away.
private float _droppedAbove;
// The part of a dropped-lines move ImGui's whole-pixel scroll couldn't take, carried
// into the next one (heights can be fractional at some DPI scales).
private float _scrollCarry;
// The list's scrollbar width (always shown), and a correction to the list width
// DrawLines works out before its BeginChild, should the child ever report another.
private const float ListScrollbarW = 10f;
private float _wrapFix;
private float _inputScroll;
// Selection: indices into _vis.
@ -100,12 +115,14 @@ internal sealed class ChatFace : IImGuiPanel
// Unread lines per tab since it was last on screen (Id of the newest line seen there).
private readonly Dictionary<string, long> _seenId = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, (int Count, bool Mention)> _unread = new(StringComparer.OrdinalIgnoreCase);
private long _unreadLines = -1, _unreadRoutes = -1, _unreadTabsVersion = -1;
private long _unreadLines = -1, _unreadRoutes = -1, _unreadTabsVersion = -1, _unreadCountedTo;
private string _unreadTab = "";
private bool _openSettings, _openNewTab, _focusNewTab, _openTabMenu, _openLineMenu, _openRename;
/// <summary>A line colour changed and isn't saved yet (saved once the picker is let go).</summary>
private bool _coloursDirty;
/// <summary>The Chat history slider's value while it's held (0: not held).</summary>
private int _historyEdit;
private string? _ctxTab, _renameFrom;
private ChatLine? _ctxLine;
private string _ctxPattern = "";
@ -129,7 +146,7 @@ internal sealed class ChatFace : IImGuiPanel
_stick = true;
_seenRoutes = -1; // full rebuild on the first frame
_seenId.Clear(); // every tab starts read
_unreadLines = -1;
_unreadLines = _unreadRoutes = -1; // a full recount
}
public void OnHidden()
@ -351,22 +368,30 @@ internal sealed class ChatFace : IImGuiPanel
long newest = lines.Length > 0 ? lines[^1].Id : 0;
_seenId[current] = newest;
long routes = ChatModel.RoutesVersion, tabsVersion = ChatModel.FiltersVersion;
if (linesVersion == _unreadLines && routes == _unreadRoutes && tabsVersion == _unreadTabsVersion
&& string.Equals(current, _unreadTab, StringComparison.Ordinal)) return;
bool recount = routes != _unreadRoutes || tabsVersion != _unreadTabsVersion
|| !string.Equals(current, _unreadTab, StringComparison.Ordinal);
if (!recount && linesVersion == _unreadLines) return;
_unreadLines = linesVersion;
_unreadRoutes = routes;
_unreadTabsVersion = tabsVersion;
_unreadTab = current;
_unread.Clear();
// Only new lines arrived: count just those (lines past _unreadCountedTo). A full recount
// walks every unread line of every tab - up to the whole history per tab (3.7 ms at
// 10,000 lines, tools/ChatHistoryBench), which used to run on every new batch.
if (recount) _unread.Clear();
foreach (string tab in ChatModel.AllTabs())
{
if (!_seenId.TryGetValue(tab, out long seen)) { _seenId[tab] = newest; continue; } // a new tab starts read
long from = recount ? seen : Math.Max(seen, _unreadCountedTo);
int count = 0;
bool mention = false;
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > seen; i--)
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > from; i--)
if (ChatModel.LineInTab(lines[i], tab)) { count++; mention |= lines[i].Route.Mention; }
if (count > 0) _unread[tab] = (count, mention);
if (count == 0) continue;
_unread.TryGetValue(tab, out var had);
_unread[tab] = (had.Count + count, had.Mention || mention);
}
_unreadCountedTo = newest;
}
private void DrawSearch(Vector2 p, float w)
@ -399,9 +424,9 @@ internal sealed class ChatFace : IImGuiPanel
_h.Clear();
_lay.Clear();
foreach (ChatLine line in lines)
if (ChatModel.LineVisible(line, tab, search)) { _vis.Add(line); _h.Add(0); _lay.Add(null); }
if (ChatModel.LineVisible(line, tab, search)) { _vis.Add(line); _h.Add(_rowH); _lay.Add(null); }
_lastId = lines.Length > 0 ? lines[^1].Id : _lastId;
_heightsFrom = 0;
_heightsFrom = _measuredFrom = _vis.Count; // all unmeasured: MeasureLines, newest first
_topsDirty = true;
ClearSelection();
_stick = true; // a rebuild re-pins to the newest line
@ -423,6 +448,7 @@ internal sealed class ChatFace : IImGuiPanel
_h.RemoveRange(0, drop);
_lay.RemoveRange(0, drop);
_heightsFrom = Math.Max(0, _heightsFrom - drop);
_measuredFrom = Math.Max(0, _measuredFrom - drop);
if (_selAnchor >= 0) { _selAnchor -= drop; _selEnd -= drop; if (_selAnchor < 0 || _selEnd < 0) ClearSelection(); }
_topsDirty = true;
}
@ -433,7 +459,7 @@ internal sealed class ChatFace : IImGuiPanel
if (!ChatModel.LineVisible(line, tab, search)) continue;
if (_heightsFrom > _vis.Count) _heightsFrom = _vis.Count;
_vis.Add(line);
_h.Add(0);
_h.Add(_rowH);
_lay.Add(null);
_topsDirty = true;
}
@ -444,81 +470,85 @@ internal sealed class ChatFace : IImGuiPanel
private void DrawLines(Vector2 size)
{
// Lines left the top of a full buffer while not following: scroll up by as much
// in THIS frame's BeginChild. (SetScrollY only lands in the next frame's Begin,
// after this frame has drawn the shortened list at the old scroll - the text
// jumped up for a frame and a strip at the bottom went blank, several times a
// second in busy chat.) A frame with wheel input waits a frame: this would
// override the wheel's own scroll.
bool compensated = false;
if (_droppedAbove > 0f)
{
if (Following) _droppedAbove = 0f;
else if (ImGuiNET.ImGui.GetIO().MouseWheel == 0f)
{
ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, Math.Max(0f, _lastScrollY - _droppedAbove)));
_droppedAbove = 0f;
compensated = true;
}
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, 10f);
bool open = ImGuiNET.ImGui.BeginChild("##chat_lines", size, ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar);
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) { ImGuiNET.ImGui.EndChild(); return; }
float fontSize = ChatModel.FontSize;
ImFontPtr font = ImGuiFonts.Chat(fontSize);
ImGuiNET.ImGui.PushFont(font);
bool showTs = ChatModel.ShowTimestamps;
float wrapW = Math.Max(20, ImGuiNET.ImGui.GetContentRegionAvail().X - 6);
// The text starts after the timestamp and wraps under itself.
// The lines are measured BEFORE the list's BeginChild, so this frame's scroll can be
// set for this frame's lines (see "Where the view goes" below). The width they wrap
// to is the child's: its width less its scrollbar (always shown) and a margin;
// _wrapFix corrects that guess if the child ever reports otherwise.
float wrapW = Math.Max(20, MathF.Floor(size.X) - ListScrollbarW - 6 + _wrapFix);
float tsW = showTs ? ImGuiNET.ImGui.CalcTextSize("00:00:00 ").X : 0;
MeasureLines(font, wrapW, tsW, fontSize, showTs, MathF.Floor(size.Y));
float total = _tops[_vis.Count];
// Where the view goes this frame. (2026-10-11, the chat "bouncing": until now the
// view followed the newest line with SetScrollHereY at the end of the frame, which
// only lands in the NEXT frame's Begin. So every batch of new lines was first drawn
// at the old scroll: with the buffer full, lines leave the top as others arrive,
// and the text jumped by the difference - up and back down when a long line left
// and a short one came - then snapped into place a frame later. A popped-out chat
// redraws at 5 Hz while idle, so the wrong frame stayed up for 200 ms.) Now the
// content height and the scroll are both handed to this frame's BeginChild:
// • the content size, so ImGui's scroll limit is this frame's and not last frame's
// (it clamps any scroll set before Begin to the limit it knows);
// • following: the bottom (the limit clamps 'total' to exactly the bottom);
// • not following: only the lines dropped off a full buffer's top, so what is
// being read stays put (fractions carried, so rounding can't creep the view).
// A frame with wheel input over the list leaves the scroll to the wheel (this would
// override it); a drag-select scrolls the list itself.
Vector2 listPos = ImGuiNET.ImGui.GetCursorScreenPos();
bool wheelHere = ImGuiNET.ImGui.GetIO().MouseWheel != 0f
&& ImGuiNET.ImGui.IsMouseHoveringRect(listPos, listPos + size, false);
ImGuiNET.ImGui.SetNextWindowContentSize(new Vector2(0f, total));
bool compensated = false;
if (Following)
{
_droppedAbove = 0f;
_scrollCarry = 0f;
// Not counted as "our move": a scrollbar drag in this Begin overrides it, and the
// check below must see that to stop following.
if (!wheelHere && !_selDragging)
ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, total));
}
else if (_droppedAbove != 0f && !wheelHere)
{
float target = _lastScrollY + _scrollCarry - _droppedAbove;
float applied = MathF.Round(Math.Max(0f, target)); // ImGui rounds scroll to whole pixels
_scrollCarry = target > 0f ? target - applied : 0f;
ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, applied));
_droppedAbove = 0f;
compensated = true;
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, ListScrollbarW);
bool open = ImGuiNET.ImGui.BeginChild("##chat_lines", size, ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar);
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) { ImGuiNET.ImGui.EndChild(); ImGuiNET.ImGui.PopFont(); return; }
// The child's real width, should the guess above ever be off (a style change):
// measured again now, and the guess corrected from the next frame on.
float realWrapW = Math.Max(20, ImGuiNET.ImGui.GetContentRegionAvail().X - 6);
if (Math.Abs(realWrapW - wrapW) > 0.5f)
{
_wrapFix += realWrapW - wrapW;
wrapW = realWrapW;
MeasureLines(font, wrapW, tsW, fontSize, showTs, MathF.Floor(size.Y));
total = _tops[_vis.Count];
}
float textW = Math.Max(20, wrapW - tsW);
if (wrapW != _seenWrap || fontSize != _seenFont || showTs != _seenTs)
{
_seenWrap = wrapW;
_seenFont = fontSize;
_seenTs = showTs;
_heightsFrom = 0;
}
if (_heightsFrom < _vis.Count)
{
for (int i = _heightsFrom; i < _vis.Count; i++)
{
ChatLine line = _vis[i];
ChatSpan[]? spans = line.Route.Spans;
if (spans != null)
{
SpanLayout lay = LayoutSpans(font, line.Text, spans, textW);
_lay[i] = lay;
_h[i] = lay.Height;
}
else
{
_lay[i] = null;
_h[i] = ImGuiNET.ImGui.CalcTextSize(line.Text, false, textW).Y;
}
}
_heightsFrom = _vis.Count;
_topsDirty = true;
}
if (_topsDirty)
{
if (_tops.Length < _vis.Count + 1) _tops = new float[Math.Max(_vis.Count + 1, _tops.Length * 2)];
_tops[0] = 0;
for (int i = 0; i < _vis.Count; i++) _tops[i + 1] = _tops[i] + _h[i];
_topsDirty = false;
}
int n = _vis.Count;
float total = _tops[n];
// Following the tail until the user scrolls away from it.
float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY();
if (compensated) _lastScrollY = scrollY; // our move, not the user's
else if (Math.Abs(scrollY - _lastScrollY) > 0.5f) _scrollCarry = 0f; // the user's: start afresh
// Wheel up over the chat stops following at once; reaching the bottom again resumes it.
// Not while it has nothing to scroll: no scroll change would ever turn following back on.
if (maxY > 0f && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.GetIO().MouseWheel > 0f)
@ -555,8 +585,6 @@ internal sealed class ChatFace : IImGuiPanel
HandleLineMenu(basePos, wrapW, n);
_lastScrollY = scrollY;
if (ChatModel.AutoScroll && _stick && !_selDragging && total > viewH)
ImGuiNET.ImGui.SetScrollHereY(1f);
// "Copied N lines" / "Rule added", top-right, for a moment.
if (_flash != null)
@ -574,8 +602,93 @@ internal sealed class ChatFace : IImGuiPanel
}
}
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopFont(); // pushed before the child, for MeasureLines
}
/// <summary>Time MeasureLines may spend a frame catching up on lines measured for another width.</summary>
private const double MeasureBudgetMs = 2.0;
private static readonly long MeasureBudgetTicks = (long)(System.Diagnostics.Stopwatch.Frequency * MeasureBudgetMs / 1000);
/// <summary>
/// Brings the line heights and tops up to date for this wrap width, font and timestamp
/// setting. Chat font pushed. New lines are measured at once. When the width, font or
/// timestamps change (or after a rebuild) every line needs measuring again: 16 ms at
/// 10,000 lines (tools/ChatHistoryBench), every frame of a resize drag. So that is done
/// a slice at a time: the lines in view first, then from the newest line up, for
/// MeasureBudgetMs a frame; the others keep their old height meanwhile. Scrolled up,
/// the view is moved by however much the lines above it grew or shrank, so what's being
/// read stays put (the same way as lines dropping off the top).
/// </summary>
private void MeasureLines(ImFontPtr font, float wrapW, float tsW, float fontSize, bool showTs, float viewH)
{
// The text starts after the timestamp and wraps under itself.
float textW = Math.Max(20, wrapW - tsW);
_rowH = font.FontSize;
if (wrapW != _seenWrap || fontSize != _seenFont || showTs != _seenTs)
{
_seenWrap = wrapW;
_seenFont = fontSize;
_seenTs = showTs;
_measuredFrom = Math.Min(_heightsFrom, _vis.Count); // all measured so far is stale
}
bool changed = false;
for (int i = _heightsFrom; i < _vis.Count; i++) { MeasureLine(font, i, textW); changed = true; }
_heightsFrom = _vis.Count;
if (_measuredFrom > 0)
{
UpdateTops();
int n = _vis.Count;
bool following = Following;
// Where the view will be (last frame's scroll, less any move still to come).
float viewTop = _lastScrollY + _scrollCarry - _droppedAbove;
int firstVisible = following || n == 0 ? int.MaxValue : FirstAtOrBelow(Math.Max(0f, viewTop), n);
if (!following)
for (int i = firstVisible; i < Math.Min(n, _measuredFrom) && _tops[i] < viewTop + viewH; i++)
MeasureLine(font, i, textW);
float grewAbove = 0f;
long t0 = System.Diagnostics.Stopwatch.GetTimestamp();
int count = 0;
while (_measuredFrom > 0)
{
int i = --_measuredFrom;
float old = _h[i];
MeasureLine(font, i, textW);
if (i < firstVisible) grewAbove += _h[i] - old;
if ((++count & 15) == 0 && System.Diagnostics.Stopwatch.GetTimestamp() - t0 > MeasureBudgetTicks) break;
}
if (!following) _droppedAbove -= grewAbove;
changed = true;
}
if (changed) _topsDirty = true;
UpdateTops();
}
private void MeasureLine(ImFontPtr font, int i, float textW)
{
ChatLine line = _vis[i];
ChatSpan[]? spans = line.Route.Spans;
if (spans != null)
{
SpanLayout lay = LayoutSpans(font, line.Text, spans, textW);
_lay[i] = lay;
_h[i] = lay.Height;
}
else
{
_lay[i] = null;
_h[i] = ImGuiNET.ImGui.CalcTextSize(line.Text, false, textW).Y;
}
}
private void UpdateTops()
{
if (!_topsDirty && _tops.Length > _vis.Count) return;
if (_tops.Length < _vis.Count + 1) _tops = new float[Math.Max(_vis.Count + 1, _tops.Length * 2)];
_tops[0] = 0;
for (int i = 0; i < _vis.Count; i++) _tops[i + 1] = _tops[i] + _h[i];
_topsDirty = false;
}
private void Flash(string message, double seconds = 2.0)
@ -871,6 +984,18 @@ internal sealed class ChatFace : IImGuiPanel
if (ImGuiNET.ImGui.SliderInt("Background", ref pct, 0, 100, "%d%%"))
ChatModel.BackgroundAlpha = (int)MathF.Round(pct * 2.55f);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatModel.SaveSettings();
// How many lines the chat keeps (ChatHistory): applied when the slider is let go, so
// dragging it down doesn't cut the history at every step on the way.
int history = _historyEdit > 0 ? _historyEdit : ChatModel.HistoryLines;
if (ImGuiNET.ImGui.SliderInt("Chat history", ref history, ChatHistory.MinLines, ChatHistory.MaxLines, "%d lines"))
_historyEdit = ChatHistory.Clamp(history);
if (ImGuiNET.ImGui.IsItemDeactivated() && _historyEdit > 0)
{
ChatModel.SetHistoryLines(_historyEdit);
_historyEdit = 0;
}
ImGuiNET.ImGui.SetItemTooltip("How many lines the chat keeps, all tabs together (default 2000).\n" +
"About 2 MB of memory per 1000 lines. Lowering it drops the oldest lines.");
ImGuiNET.ImGui.PopItemWidth();
bool ts = ChatModel.ShowTimestamps;

View file

@ -87,6 +87,8 @@ internal sealed class DamageFace : IImGuiPanel
private sealed class RowText
{
public string Wcid = "", Tier = "", Crit = "", NonCrit = "", Casts = "", Kills = "";
/// <summary>The name as shown: "Rampager (2 kinds)" for a row of several wcids.</summary>
public string NameShown = "", NameTip = "";
public string Weapon = "", Offhand = "", Pet = "", WeakTop = "", Sec = "", SecTip = "";
public bool CritSet, NonCritSet, WeaponGold, OffhandGold, PetGold;
public string[] TierLines = Array.Empty<string>();
@ -250,7 +252,8 @@ internal sealed class DamageFace : IImGuiPanel
if (_filterWid != 0 && r.Wid != _filterWid) continue;
if (_searchText.Length > 0
&& r.Name.IndexOf(_searchText, StringComparison.OrdinalIgnoreCase) < 0
&& !r.Wcid.ToString(CultureInfo.InvariantCulture).Contains(_searchText, StringComparison.Ordinal))
&& !r.Wcid.ToString(CultureInfo.InvariantCulture).Contains(_searchText, StringComparison.Ordinal)
&& !Array.Exists(r.Wcids, w => w.ToString(CultureInfo.InvariantCulture).Contains(_searchText, StringComparison.Ordinal)))
continue;
}
_shown.Add(r);
@ -306,6 +309,20 @@ internal sealed class DamageFace : IImGuiPanel
}
BuildPrio(r.Name, t);
t.Wcid = r.Wcid.ToString(inv);
const string DetailTip = "Details: weaknesses, accuracy, damage, summons, damage taken and spell settings (wcid ";
if (r.Wcids.Length > 1)
{
// Monsters of one name with several weenies (retail has five Rampagers): one row.
t.NameShown = r.Name + " (" + r.Wcids.Length.ToString(inv) + " kinds)";
t.NameTip = r.Wcids.Length.ToString(inv) + " kinds of " + r.Name + ": wcids " + string.Join(", ", r.Wcids) + ".\n"
+ "Kills and fights are added up; a weapon, offhand, pet or HP set here applies to all of them.\n"
+ DetailTip + t.Wcid + ", the one with the most kills).";
}
else
{
t.NameShown = r.Name;
t.NameTip = DetailTip + t.Wcid + ").";
}
t.Tier = DamageSource.FormatTier(r.Tier);
t.CritSet = r.CritN > 0;
t.Crit = t.CritSet ? r.Crit.ToString("0", inv) : "—";
@ -762,10 +779,10 @@ internal sealed class DamageFace : IImGuiPanel
}
}
ImGuiNET.ImGui.SetItemTooltip("Follow the Default config (spells, weapon). Uncheck to customize this monster.");
if (NameLink("##name", r.Name, new Vector2(p.X + ColX[ColMonster] + 22, p.Y), ColW[ColMonster] - 24, custom ? Gold : White,
if (NameLink("##name", t.NameShown, new Vector2(p.X + ColX[ColMonster] + 22, p.Y), ColW[ColMonster] - 24, custom ? Gold : White,
ImGuiFonts.Get(UiFont.Ui11)))
DamageDetailFace.Show(r.Wcid, r.Name);
ImGuiNET.ImGui.SetItemTooltip("Details: weaknesses, accuracy, damage, summons, damage taken and spell settings (wcid " + t.Wcid + ").");
ImGuiNET.ImGui.SetItemTooltip(t.NameTip);
PrioCell(r.Key, r.Name, t.PrioCopyFrom, t, p);
HpCell(r, p);

View file

@ -2,7 +2,9 @@
// RynthCore.Engine - ImGui/Panels/ItemsFace.cs
// ImGui face of the Items panel (UI/Panels/ItemsPanel.cs): weapons (name,
// element, Del), consumables (name, type, Del), each with "Add Selected",
// and mana stone tapping (on/off, keep count, min max-mana to tap).
// and mana stone tapping (on/off, keep count, min max-mana to tap). A listed
// weapon the character no longer carries (RynthAi's missingIds) shows in amber
// with a warning icon and "(missing)", and says what to do in its tooltip.
//
// Edits change a private copy and save the whole payload (ItemsCommands,
// pump thread). A newer snapshot replaces the copy; snapshots from before
@ -62,7 +64,7 @@ internal sealed class ItemsFace : IImGuiPanel
{
ItemsPanel.WeaponEntry wpn = _data.Weapons[i];
ImGuiNET.ImGui.PushID("w" + i);
int r = Row(wpn.Name, wpn.Element, i, bw);
int r = Row(wpn.Name, wpn.Element, i, bw, _data.MissingIds.Contains(wpn.Id));
ImGuiNET.ImGui.PopID();
if (r == 1)
{
@ -94,7 +96,7 @@ 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);
int r = Row(c.Name, c.Type, i, bw, missing: false);
ImGuiNET.ImGui.PopID();
if (r == 1)
{
@ -200,16 +202,38 @@ internal sealed class ItemsFace : IImGuiPanel
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
}
/// <summary>Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0.</summary>
private static int Row(string name, string value, int index, float w)
private const string MissingSuffix = " (missing)";
/// <summary>
/// Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0.
/// <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)
{
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 ty = p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.PushClipRect(p, p + new Vector2(nameW, 24), true);
dl.AddText(new Vector2(p.X + 6, p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, name);
if (missing)
{
float x = p.X + 6;
dl.AddText(new Vector2(x, ty), Amber, PhosphorIcons.Warning);
x += ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.Warning).X + 4;
dl.AddText(new Vector2(x, ty), Amber, name);
x += ImGuiNET.ImGui.CalcTextSize(name).X;
dl.AddText(new Vector2(x, ty), Amber, MissingSuffix);
}
else
{
dl.AddText(new Vector2(p.X + 6, ty), Text, name);
}
dl.PopClipRect();
if (missing && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseHoveringRect(p, p + new Vector2(nameW, 24)))
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;

View file

@ -4,6 +4,7 @@
//
// [<- Back] Edit rule Saved
// State: [Combat v]
// Name: [Optional: a name to find this rule by ]
// +- Conditions ------ [+ Add] -+ +- Actions --------- [+ Add] -+
// | [Landblock == v] | | [Chat Command v] |
// | [A9B40000 ][Set current] | | [/say hello ] |
@ -15,6 +16,13 @@
// first of an All (a single action into the first of a DoAll), or adds one
// more to an All / Any / DoAll.
//
// Groups (2026-10-11): an All / Any / Not, nested or the column's own, and a
// DoAll is a box (tint, border and left bar in its colour: All teal, Any
// amber, Not rose) around its picker and everything in it, so a box inside
// a box shows what belongs where; a nested group's line says what it means
// ("any of the conditions inside"). Rows alternate a light shade; a DoAll's
// actions are numbered in the order they run.
//
// Saving: every change marks the rule dirty (MetaAutosave); 0.75 s after the
// last change, and never while a text box is being typed in, the rule goes
// to RynthAi as add_rule (a new rule, the first time, and only once its
@ -68,6 +76,11 @@ internal sealed partial class MetaFace
private string? _nameProblem;
private const string NewStateEntry = PhosphorIcons.Plus + " New state...";
// The rule's Name box (MetaRuleDto.Name; one line, MaxNameLength bytes of UTF-8).
private readonly byte[] _ruleNameBytes = new byte[MetaRuleEdit.MaxNameLength + 1];
private string? _ruleNameShown; // the name the box was last filled from
private bool _ruleNameActive, _focusRuleName;
private const string BackLabel = PhosphorIcons.ArrowLeft + " Back";
private const string AddLabel = PhosphorIcons.Plus + " Add";
private const string SetCurrentLabel = PhosphorIcons.MapPin + " Set current";
@ -86,6 +99,7 @@ internal sealed partial class MetaFace
_lastSaved = index >= 0 ? rule.Clone() : null;
_autosave.Clear();
_fields.Clear();
_ruleNameShown = null;
_editConfirmDelete = false;
_editTyping = false;
CancelNaming();
@ -136,6 +150,7 @@ internal sealed partial class MetaFace
}
if (!_autosave.Take()) return;
MetaRuleDto send = _editRule.Clone();
send.Name = send.Name.Trim(); // the box keeps a space you just typed; the rule doesn't
if (_editIndex < 0)
{
_editIndex = _data.Rules.Count; // add_rule appends
@ -163,7 +178,6 @@ internal sealed partial class MetaFace
{
SendEdit(new MetaCmd { Op = "delete_rule", Index = index });
_data.Rules.RemoveAt(index);
_expanded.Clear();
RebuildCaches();
}
}
@ -195,7 +209,7 @@ internal sealed partial class MetaFace
float indW = SaveIndicatorWidth(editor: true);
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
float tx = top.X + backW + 8;
string title = _editIndex < 0 ? "New rule" : "Edit rule";
string title = _editIndex < 0 ? "New rule" : r.Name.Trim().Length > 0 ? r.Name.Trim() : "Edit rule";
ImGuiNET.ImGui.PushFont(bold);
dl.AddText(new Vector2(tx, top.Y + (22 - bold.FontSize) * 0.5f), Teal, Fit(title, Math.Max(10, top.X + w - indW - 8 - tx)));
ImGuiNET.ImGui.PopFont();
@ -203,7 +217,7 @@ internal sealed partial class MetaFace
// State: [picker]
float y = top.Y + 26;
float lw = ImGuiNET.ImGui.CalcTextSize("State:").X + 6;
float lw = Math.Max(ImGuiNET.ImGui.CalcTextSize("State:").X, ImGuiNET.ImGui.CalcTextSize("Name:").X) + 6;
dl.AddText(new Vector2(top.X, y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "State:");
string? state = StatePicker("##ed_state", r.State, _statePicks, IndexOf(_statePicks, r.State),
new Vector2(top.X + lw, y), w - lw, out _);
@ -212,7 +226,12 @@ internal sealed partial class MetaFace
r.State = state; // a new state is made by moving this rule into it
_editChanged = true;
}
y += 22 + ProblemLine("##ed_state", new Vector2(top.X + lw, y + 22), w - lw) + 6;
y += 22 + ProblemLine("##ed_state", new Vector2(top.X + lw, y + 22), w - lw) + 4;
// Name: [optional]
dl.AddText(new Vector2(top.X, y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Name:");
NameBox(new Vector2(top.X + lw, y), w - lw);
y += 22 + 6;
// Conditions | Actions
const float footerH = 24;
@ -279,44 +298,191 @@ internal sealed partial class MetaFace
private void ConditionsBody(MetaRuleDto r, float w)
{
int picked = FlowPicker("##ed_cond", MetaVocabulary.ConditionName(r.Condition), MetaVocabulary.ConditionNames, r.Condition, w);
if (picked >= 0 && picked != r.Condition)
var dl = ImGuiNET.ImGui.GetWindowDrawList();
BeginBacks(dl);
try
{
SetCondition(r, picked);
_editChanged = true;
// An All / Any / Not is a box around its picker and everything in it.
bool card = MetaVocabulary.IsCompositeCondition(r.Condition);
Vector2 top = CardOpen(card);
float iw = card ? w - CardInset - CardPadR : w;
int picked = FlowPicker("##ed_cond", MetaVocabulary.ConditionName(r.Condition), MetaVocabulary.ConditionNames, r.Condition, iw);
if (picked >= 0 && picked != r.Condition)
{
SetCondition(r, picked);
_editChanged = true;
}
if (!card || !MetaVocabulary.IsCompositeCondition(r.Condition))
{
if (!MetaVocabulary.IsCompositeCondition(r.Condition)) ConditionField("##ed_cdata", r, iw, 22);
CardClose(card, top, w, GroupColor(r.Condition, false), GroupTint(r.Condition, false), 0);
return;
}
GroupLabel(r.Condition switch
{
MetaRuleEdit.Not => "Not: true while the condition inside is false",
MetaRuleEdit.All => "All of these:",
_ => "Any of these:",
}, GroupColor(r.Condition, false));
if (r.Children.Count == 0) Note("None yet: + Add (top right).");
SubRules(r.Children, action: false, 0, r.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, iw);
CardClose(card, top, w, GroupColor(r.Condition, false), GroupTint(r.Condition, false), 0);
}
if (!MetaVocabulary.IsCompositeCondition(r.Condition))
finally
{
ConditionField("##ed_cdata", r, w, 22);
return;
EndBacks(dl);
}
SmallLabel(r.Condition switch
{
MetaRuleEdit.Not => "Not: true while this one is false",
MetaRuleEdit.All => "All of these:",
_ => "Any of these:",
});
if (r.Children.Count == 0) Note("None yet: + Add (top right).");
SubRules(r.Children, action: false, 0, r.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, w);
}
private void ActionsBody(MetaRuleDto r, float w)
{
int picked = FlowPicker("##ed_act", MetaVocabulary.ActionName(r.Action), MetaVocabulary.ActionNames, r.Action, w);
if (picked >= 0 && picked != r.Action)
var dl = ImGuiNET.ImGui.GetWindowDrawList();
BeginBacks(dl);
try
{
r.Action = picked;
if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear();
bool card = MetaVocabulary.IsAllAction(r.Action); // a DoAll is a box around its actions
Vector2 top = CardOpen(card);
float iw = card ? w - CardInset - CardPadR : w;
int picked = FlowPicker("##ed_act", MetaVocabulary.ActionName(r.Action), MetaVocabulary.ActionNames, r.Action, iw);
if (picked >= 0 && picked != r.Action)
{
r.Action = picked;
if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear();
_editChanged = true;
}
if (!card || !MetaVocabulary.IsAllAction(r.Action))
{
if (!MetaVocabulary.IsAllAction(r.Action)) ActionField("##ed_adata", r, iw, 22, problemLine: true);
CardClose(card, top, w, GroupColor(MetaRuleEdit.DoAll, true), GroupTint(MetaRuleEdit.DoAll, true), 0);
return;
}
GroupLabel("All of these, in order:", GroupColor(MetaRuleEdit.DoAll, true));
if (r.ActionChildren.Count == 0) Note("None yet: + Add (top right).");
SubRules(r.ActionChildren, action: true, 0, int.MaxValue, iw);
CardClose(card, top, w, GroupColor(MetaRuleEdit.DoAll, true), GroupTint(MetaRuleEdit.DoAll, true), 0);
}
finally
{
EndBacks(dl);
}
}
// =====================================================================
// Group boxes and row stripes (2026-10-11: "hard to see what's what in All and Any")
// =====================================================================
//
// An All / Any / Not (and a DoAll) is a box: a tint and a border in the group's colour (All
// teal, Any amber, Not rose), an accent bar down its left, around its picker and everything in
// it; a box inside a box is another, so what belongs where shows at a glance. Rows of a list
// alternate a light shade. A box's height is known only after its contents are laid out, so
// boxes and stripes are recorded while the rows are placed and drawn at the end on a channel
// under them (outer boxes first, each list's stripes over its box).
private const float CardInset = 9, CardPadR = 5, CardPadT = 5, CardPadB = 4;
private static readonly uint Rose = C(0xFFE07A9A), StripeOver = C(0x12FFFFFF);
private readonly List<(Vector2 Min, Vector2 Max, uint Fill, uint Border, uint Accent, int Order)> _backs = new();
private void BeginBacks(ImDrawListPtr dl)
{
_backs.Clear();
dl.ChannelsSplit(2);
dl.ChannelsSetCurrent(1); // widgets over the boxes
}
private void EndBacks(ImDrawListPtr dl)
{
dl.ChannelsSetCurrent(0);
// Outer before inner (Order = 2 x depth for a box, + 1 for its list's stripes).
_backs.Sort((x, y) => x.Order.CompareTo(y.Order));
foreach (var b in _backs)
{
if (b.Fill != 0) dl.AddRectFilled(b.Min, b.Max, b.Fill, b.Border != 0 ? 4f : 0f);
if (b.Accent != 0) dl.AddRectFilled(b.Min, new Vector2(b.Min.X + 3, b.Max.Y), b.Accent, 2f);
if (b.Border != 0) dl.AddRect(b.Min, b.Max, b.Border, 4f);
}
_backs.Clear();
dl.ChannelsMerge();
}
/// <summary>Starts a box at the cursor when <paramref name="card"/> (its contents indented); returns its top-left.</summary>
private static Vector2 CardOpen(bool card)
{
Vector2 top = ImGuiNET.ImGui.GetCursorScreenPos();
if (!card) return top;
ImGuiNET.ImGui.Indent(CardInset); // moves the cursor in; the box's rows keep to it
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ImGuiNET.ImGui.GetCursorScreenPos().X, top.Y + CardPadT));
return top;
}
/// <summary>Ends a box opened at <paramref name="top"/>, <paramref name="w"/> wide, and records it.</summary>
private void CardClose(bool card, Vector2 top, float w, uint color, uint tint, int depth)
{
if (!card) return;
float endY = ImGuiNET.ImGui.GetCursorScreenPos().Y - ImGuiNET.ImGui.GetStyle().ItemSpacing.Y + CardPadB;
ImGuiNET.ImGui.Unindent(CardInset);
_backs.Add((top, new Vector2(top.X + w, endY), tint, (color & 0x00FFFFFF) | 0x80000000u, color, depth * 2));
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(top.X, endY + 3));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
}
/// <summary>A group's colour: All (and DoAll) teal, Any amber, Not rose.</summary>
private static uint GroupColor(int kind, bool action) => action ? Teal : kind switch
{
MetaRuleEdit.Any => Amber,
MetaRuleEdit.Not => Rose,
_ => Teal,
};
/// <summary>A group box's fill: its colour, faint, over the column.</summary>
private static uint GroupTint(int kind, bool action) => action ? C(0xFF10262E) : kind switch
{
MetaRuleEdit.Any => C(0xFF2A2412),
MetaRuleEdit.Not => C(0xFF2C1622),
_ => C(0xFF10262E),
};
/// <summary>What a nested group's line says after its picker.</summary>
private static string GroupWords(int kind) => kind switch
{
MetaRuleEdit.All => "all of the conditions inside",
MetaRuleEdit.Any => "any of the conditions inside",
_ => "true while the condition inside is false",
};
private static void GroupLabel(string text, uint color)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.PopFont();
}
/// <summary>The rule's name: optional, one line; saves like every other change.</summary>
private void NameBox(Vector2 pos, float width)
{
if (!_ruleNameActive && !ReferenceEquals(_ruleNameShown, _editRule.Name))
{
WriteUtf8(_ruleNameBytes, _editRule.Name);
_ruleNameShown = _editRule.Name;
}
ImGuiNET.ImGui.SetCursorScreenPos(pos);
if (_focusRuleName)
{
ImGuiNET.ImGui.SetKeyboardFocusHere();
_focusRuleName = false;
}
bool edited = TextBox("##ed_name", _ruleNameBytes, width, "Optional: a name to find this rule by",
ImGuiInputTextFlags.None, out _ruleNameActive);
ImGuiNET.ImGui.SetItemTooltip("Shown in bold over the rule in the list (and instead of its condition in Compact).");
_typingNow |= _ruleNameActive; // autosave waits until the box is left
if (edited)
{
string typed = MetaRuleEdit.CleanName(Utf8(_ruleNameBytes));
_editRule.Name = typed;
_ruleNameShown = typed;
_editChanged = true;
}
if (!MetaVocabulary.IsAllAction(r.Action))
{
ActionField("##ed_adata", r, w, 22, problemLine: true);
return;
}
SmallLabel("All of these, in order:");
if (r.ActionChildren.Count == 0) Note("None yet: + Add (top right).");
SubRules(r.ActionChildren, action: true, 0, int.MaxValue, w);
}
private static void SetCondition(MetaRuleDto c, int picked)
@ -385,15 +551,21 @@ internal sealed partial class MetaFace
}
if (problemLine) extra = ProblemLine(id, new Vector2(p.X, p.Y + height), width);
}
else if (a.Action == 3) // Embedded Nav Route
else if (a.Action == 3) // Embedded Nav Route: Patrol, nav files, the meta's routes
{
int picked = Picker(id, a.ActionData.Length == 0 ? "Select route..." : a.ActionData, _routePicks,
Array.IndexOf(_routePicks, a.ActionData), p, width, height);
if (picked >= 0 && _routePicks[picked] != a.ActionData)
int sel = IndexOf(_routeValues, a.ActionData);
string shown = a.ActionData.Length == 0 ? "Select route..." : sel >= 0 ? _routeLabels[sel] : a.ActionData;
int picked = Picker(id, shown, _routeLabels, sel, p, width, height);
if (picked >= 0 && _routeValues[picked] != a.ActionData)
{
a.ActionData = _routePicks[picked];
a.ActionData = _routeValues[picked]; // the name RynthAi looks up, not the list's label
_editChanged = true;
}
// (The picker's last item is a spacer, so the hover is checked on its rectangle.)
if (MetaVocabulary.PatrolRoute.Equals(a.ActionData, StringComparison.OrdinalIgnoreCase)
&& !MetaVocabulary.HasRoute(_data, a.ActionData)
&& ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseHoveringRect(p, p + new Vector2(width, height)))
ImGuiNET.ImGui.SetTooltip("RynthAi's dungeon patrol (/ra dunnav-patrol): a circular hunt through every room of the dungeon you're in. Needs no nav file; only works inside a dungeon.");
}
else if (!MetaRuleEdit.ActionTakesData(a.Action) && a.ActionData.Length == 0)
NoteAt(p, "Nothing to set.", height);
@ -407,58 +579,87 @@ internal sealed partial class MetaFace
}
// Sub-conditions nest (All/Any/Not under All/Any/Not, MaxSubConditionDepth levels; a Not takes
// one); DoAll's sub-actions are a flat list. Each row: [type][value][x]; in a narrow column the
// value goes on a second line. The top level's "+ Add" is in the column header.
// one); DoAll's sub-actions are a flat list that runs in order, so each is numbered and has up /
// down. A row: [type][value]([up][down])[x]; every other row a light shade; in a narrow column the
// value goes on a second line. A nested All / Any / Not is a box (its picker, what it means, then
// its conditions inside, indented). The top level's "+ Add" is in the column header.
private void SubRules(List<MetaRuleDto> subs, bool action, int depth, int maxCount, float w)
{
string[] names = action ? MetaVocabulary.ActionNames : MetaVocabulary.ConditionNames;
bool narrow = w < 300;
const float rh = 20, xw = 20;
const float rh = 20, xw = 20, aw = 16, childIndent = 10;
for (int i = 0; i < subs.Count; i++)
{
MetaRuleDto sub = subs[i];
ImGuiNET.ImGui.PushID(i);
bool nests = !action && MetaVocabulary.IsCompositeCondition(sub.Condition) && depth < MetaVocabulary.MaxSubConditionDepth;
Vector2 cardTop = CardOpen(nests);
float rw = nests ? w - CardInset - CardPadR : w; // the row's width (inside its box)
float tools = xw + (action ? 2 * (aw + 2) : 0); // [up][down][x] or [x]
float lead = action ? 16 : 0; // a DoAll's step number
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float pickW = narrow ? w - xw - 4 : (w - xw - 8) * 0.45f;
float pickW = narrow ? rw - tools - lead - 4 : (rw - tools - lead - 8) * 0.45f;
if (action)
{
string step = (i + 1).ToString(System.Globalization.CultureInfo.InvariantCulture);
ImGuiNET.ImGui.GetWindowDrawList().AddText(
new Vector2(p.X + lead - 4 - ImGuiNET.ImGui.CalcTextSize(step).X, p.Y + (rh - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
Faded(Mute), step);
}
int current = action ? sub.Action : sub.Condition;
string shown = action ? MetaVocabulary.ActionName(sub.Action) : MetaVocabulary.ConditionName(sub.Condition);
int picked = Picker("##type", shown, names, current, p, pickW, rh);
int picked = Picker("##type", shown, names, current, new Vector2(p.X + lead, p.Y), pickW, rh);
if (picked >= 0 && picked != current)
{
if (action) sub.Action = picked; else SetCondition(sub, picked);
_editChanged = true;
}
bool nests = !action && MetaVocabulary.IsCompositeCondition(sub.Condition) && depth < MetaVocabulary.MaxSubConditionDepth;
bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + w - xw, p.Y), new Vector2(xw, rh), TextDim, DelFill, BtnBord);
ImGuiNET.ImGui.SetItemTooltip(action ? "Remove this action" : "Remove this condition");
bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + rw - xw, p.Y), new Vector2(xw, rh), TextDim, DelFill, BtnBord);
ImGuiNET.ImGui.SetItemTooltip(action ? "Remove this action" : nests ? "Remove this group and what is in it" : "Remove this condition");
int moveTo = -1;
if (action)
{
float ax = p.X + rw - xw - 2 - 2 * (aw + 2);
if (IconButton("##sub_up", PhosphorIcons.ArrowUp, new Vector2(ax, p.Y), new Vector2(aw, rh), Mute, BtnFill, BtnBord, enabled: i > 0))
moveTo = i - 1;
ImGuiNET.ImGui.SetItemTooltip("Run this action earlier");
if (IconButton("##sub_dn", PhosphorIcons.ArrowDown, new Vector2(ax + aw + 2, p.Y), new Vector2(aw, rh), Mute, BtnFill, BtnBord,
enabled: i < subs.Count - 1))
moveTo = i + 1;
ImGuiNET.ImGui.SetItemTooltip("Run this action later");
}
float rowH = rh;
if (nests)
{
if (!narrow)
NoteAt(new Vector2(p.X + pickW + 6, p.Y), sub.Condition == MetaRuleEdit.Not ? "(the condition below)" : "(the conditions below)", rh);
NoteAt(new Vector2(p.X + pickW + 6, p.Y), GroupWords(sub.Condition), rh, GroupColor(sub.Condition, false));
}
else
{
Vector2 vp = narrow ? new Vector2(p.X + 12, p.Y + rh + 2) : new Vector2(p.X + pickW + 4, p.Y);
float vw = narrow ? w - 12 : w - pickW - 4 - xw - 4;
Vector2 vp = narrow ? new Vector2(p.X + lead + 12, p.Y + rh + 2) : new Vector2(p.X + lead + pickW + 4, p.Y);
float vw = narrow ? rw - lead - 12 : rw - lead - pickW - 4 - tools - 4;
ImGuiNET.ImGui.SetCursorScreenPos(vp);
if (action) ActionField("##data", sub, vw, rh, problemLine: false);
else ConditionField("##data", sub, vw, rh);
if (narrow) rowH = rh * 2 + 2;
// Every other row a light shade, reaching halfway into the gaps so the shades meet.
if (i % 2 == 1)
_backs.Add((new Vector2(p.X - 4, p.Y - 4.5f), new Vector2(p.X + rw + 3, p.Y + rowH + 4.5f), StripeOver, 0, 0, depth * 2 + 1));
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH + 2));
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH + 5));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
if (!removed && nests)
{
ImGuiNET.ImGui.Indent(14);
SmallLabel(sub.Condition switch { MetaRuleEdit.Not => "Not:", MetaRuleEdit.All => "All of:", _ => "Any of:" });
SubRules(sub.Children, action: false, depth + 1, sub.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, w - 14);
ImGuiNET.ImGui.Unindent(14);
ImGuiNET.ImGui.Indent(childIndent);
if (sub.Children.Count == 0) Note("None yet: + Add below.");
SubRules(sub.Children, action: false, depth + 1, sub.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, rw - childIndent);
ImGuiNET.ImGui.Unindent(childIndent);
}
CardClose(nests, cardTop, w, GroupColor(sub.Condition, false), GroupTint(sub.Condition, false), depth + 1);
ImGuiNET.ImGui.PopID();
if (removed)
{
@ -466,6 +667,12 @@ internal sealed partial class MetaFace
_editChanged = true;
break; // indices shifted: the rest draws next frame
}
if (moveTo >= 0)
{
(subs[i], subs[moveTo]) = (subs[moveTo], subs[i]);
_editChanged = true;
break;
}
}
// Nested groups get their own Add; the top level's is in the column header.
@ -539,12 +746,12 @@ internal sealed partial class MetaFace
/// (<paramref name="isNew"/> true) once its name box is confirmed; else null.
/// </summary>
private string? StatePicker(string id, string shown, string[] items, int selected, Vector2 pos, float width, out bool isNew,
float height = 22)
float height = 22, string? badge = null)
{
isNew = false;
uint key = ImGuiNET.ImGui.GetID(id);
if (_namingKey == key) return NamingBox(id, pos, width, height, out isNew);
int picked = Picker(id, shown, items, selected, pos, width, height, NewStateEntry);
int picked = Picker(id, shown, items, selected, pos, width, height, NewStateEntry, badge);
if (picked == items.Length)
{
_namingKey = key;
@ -650,12 +857,6 @@ internal sealed partial class MetaFace
return -1;
}
private static void SmallLabel(string text)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), text);
ImGuiNET.ImGui.PopFont();
}
private static void Note(string text)
{
@ -664,8 +865,9 @@ internal sealed partial class MetaFace
ImGuiNET.ImGui.PopFont();
}
private static void NoteAt(Vector2 p, string text, float height)
private static void NoteAt(Vector2 p, string text, float height, uint color = 0)
{
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + 4, p.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), text);
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + 4, p.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
color != 0 ? color : Faded(Mute), text);
}
}

File diff suppressed because it is too large Load diff

View file

@ -207,7 +207,7 @@ internal sealed partial class MetaFace
ScheduleRuleDto r = sc.Rules[i];
bool first = i == sc.FirstMatch && sc.Enabled;
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
dl.AddRectFilled(p, p + new Vector2(w, h), i % 2 == 0 ? PanelBg : RowAlt);
dl.AddRectFilled(p, p + new Vector2(w, h), i % 2 == 0 ? StripeA : StripeB);
ImGuiNET.ImGui.PushID(1000 + i);
bool changed = false;
float x = p.X + 1;

View file

@ -3,11 +3,13 @@
// ImGui face of the Meta panel (docs/IMGUI_PARITY_PLAN.md §2.13), with the
// Avalonia face's look and three views:
//
// List file picker / refresh / Save As / "Saved" indicator; Visual|Source;
// Meta, Debug; rules grouped by state (collapsible, red while
// firing), rows with enable, expand, up/down within the state,
// duplicate, and delete on the far right (click twice); click a row
// to edit it; State picker and New Rule at the bottom.
// List (MetaFace.List.cs) file picker / refresh / Save As / "Saved"
// indicator; Visual|Source; Meta, Debug; a filter; rules grouped
// by state, each rule in full (every condition and action on its
// own line, or one line in Compact) with lines between rules and
// columns; move / duplicate / delete on the hovered row and on
// right-click; click a row to edit it; State picker and New Rule
// at the bottom.
// Editor (MetaFace.Editor.cs) state; Conditions and Actions side by side
// (stacked when the panel is narrow), each with "+ Add"; Set current
// for landblock / landcell; every change saves on its own.
@ -55,7 +57,7 @@ internal sealed partial class MetaFace : IImGuiPanel
private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Green = C(0xFF33CC66),
Red = C(0xFFE04848), Mute = C(0xFFC8D6E4), TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14),
PanelBg = C(0xFF141F29), RowAlt = C(0xFF101822), BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A),
Fired = C(0xFF3A1212), BtnOn = C(0xFF0E2E3A), StateHdrA = C(0xFF0E1E30), StateHdrB = C(0xFF162A40),
Fired = C(0xFF3A1212), BtnOn = C(0xFF0E2E3A), StateHdrA = C(0xFF0E1E30),
DelFill = C(0xFF7A1414), NewFill = C(0xFF0E2E1A), PickSel = C(0xFF1A2E42);
private static uint C(uint argb) => RynthTheme.Argb(argb);
private static uint Faded(uint abgr) => (abgr & 0x00FFFFFF) | ((abgr >> 25) << 24); // half alpha
@ -66,11 +68,9 @@ internal sealed partial class MetaFace : IImGuiPanel
private MetaPayload _data = new();
private long _seenVersion = -1;
private List<(string State, List<int> Rules)> _groups = new();
private string[] _condText = Array.Empty<string>(), _actText = Array.Empty<string>();
private string[] _groupLabel = Array.Empty<string>();
private bool[] _groupFiring = Array.Empty<bool>();
private string[] _statePicks = Array.Empty<string>(), _statesOnly = Array.Empty<string>();
private string[] _routePicks = Array.Empty<string>(), _fileDisplays = Array.Empty<string>();
private string[] _routeLabels = Array.Empty<string>(), _routeValues = Array.Empty<string>(), _fileDisplays = Array.Empty<string>();
private string _fileDisplay = "-- None --", _sourceFileLabel = "File: Unsaved";
private IReadOnlyList<string> _completionNavs = Array.Empty<string>();
@ -78,8 +78,8 @@ internal sealed partial class MetaFace : IImGuiPanel
private readonly Dictionary<(string Text, int Width), string> _fit = new();
private View _view = View.List;
private readonly MetaStateClock _stateClock = new();
private readonly HashSet<string> _collapsed = new();
private readonly HashSet<int> _expanded = new();
private bool _saveAs, _saveAsFocus;
private readonly byte[] _saveName = new byte[128];
@ -195,6 +195,7 @@ internal sealed partial class MetaFace : IImGuiPanel
if (snap == null || snap.Version == _seenVersion) return;
_seenVersion = snap.Version;
MetaPayload fresh = snap.Value;
_stateClock.Snapshot(fresh.Snapshot, NowMs);
CheckApplyResult(fresh);
_data = fresh.Clone();
RebuildCaches();
@ -211,21 +212,12 @@ internal sealed partial class MetaFace : IImGuiPanel
{
List<MetaRuleDto> rules = _data.Rules;
_groups = MetaVocabulary.GroupByState(rules);
_condText = new string[rules.Count];
_actText = new string[rules.Count];
for (int i = 0; i < rules.Count; i++)
{
_condText[i] = MetaVocabulary.RowConditionText(rules[i]);
_actText[i] = MetaVocabulary.RowActionText(rules[i]);
}
_groupLabel = new string[_groups.Count];
_groupFiring = new bool[_groups.Count];
for (int g = 0; g < _groups.Count; g++)
{
bool firing = false;
foreach (int i in _groups[g].Rules) firing |= rules[i].LastFiredMs < 1500;
_groupFiring[g] = firing;
_groupLabel[g] = firing ? $"{_groups[g].State} ({_groups[g].Rules.Count}) — firing" : $"{_groups[g].State} ({_groups[g].Rules.Count})";
}
// States made here that the snapshot doesn't list yet (dropped once it does, or on a meta switch).
if (!string.Equals(_statesPath, _data.CurrentMetaPath, StringComparison.OrdinalIgnoreCase))
@ -241,47 +233,20 @@ internal sealed partial class MetaFace : IImGuiPanel
_statePicks = With(_statePicks, s);
_statesOnly = With(_statesOnly, s);
}
_routePicks = MetaVocabulary.RoutePicks(_data);
(_routeLabels, _routeValues) = MetaVocabulary.RoutePicks(_data);
_fileDisplays = new string[_data.Files.Count];
for (int i = 0; i < _fileDisplays.Length; i++) _fileDisplays[i] = _data.Files[i].Display;
_fileDisplay = MetaVocabulary.CurrentFileDisplay(_data);
_sourceFileLabel = "File: " + (string.IsNullOrEmpty(_data.CurrentMetaPath) ? "Unsaved" : System.IO.Path.GetFileName(_data.CurrentMetaPath));
_completionNavs = MetaVocabulary.CompletionNavs(_data);
_fit.Clear();
RebuildListText(rules); // after the states: a Set State to a missing state shows in red
}
// =====================================================================
// List view
// File bar and mode row (the list itself: MetaFace.List.cs)
// =====================================================================
private void ListView(Vector2 origin, Vector2 size)
{
float w = size.X;
LoadSaveBar(w);
Separator(w);
ModeRow(w, source: false);
Separator(w);
if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000)
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), Fit(_listNote, w));
ImGuiNET.ImGui.PopFont();
}
const float bottomH = 24;
float listH = Math.Max(40, origin.Y + size.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - bottomH - 9);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGuiNET.ImGui.BeginChild("##meta_rules", new Vector2(w, listH));
RuleList(ImGuiNET.ImGui.GetContentRegionAvail().X);
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
Separator(w);
BottomBar(w);
}
private void LoadSaveBar(float w)
{
if (_saveAs)
@ -458,255 +423,8 @@ internal sealed partial class MetaFace : IImGuiPanel
_editor.RequestFocus();
}
// Condition/action split of the rule list (dragged in its header) and where
// the text starts within a row (from the last row drawn).
// Condition/action split of the rule list (dragged in its header; saved per PC).
private static float _condFrac = Math.Clamp(RynthCore.Engine.UI.PanelColumnStore.Get("Meta.condFrac", 0.5f), 0.15f, 0.85f);
private float _textStartOff;
/// <summary>The far-right delete button and the gap before it: the row text ends this far from the edge.</summary>
private const float DeleteColumnW = 30;
private void RuleList(float w)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
if (_groups.Count == 0)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " No rules. Click New Rule to add one.");
return;
}
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
List<MetaRuleDto> rules = _data.Rules;
// Condition | Action header; drag the divider to move the split (saved per PC).
if (_textStartOff > 0)
{
Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos();
const float hh = 16;
float tx = hp.X + _textStartOff, tw = Math.Max(1, hp.X + w - DeleteColumnW - tx);
float split = tw * _condFrac;
float hy = hp.Y + (hh - bold.FontSize) * 0.5f;
dl.AddText(bold, bold.FontSize, new Vector2(tx + 3, hy), C(0xFFC8D6E4), "Condition");
dl.AddText(bold, bold.FontSize, new Vector2(tx + split + 4, hy), C(0xFFC8D6E4), "Action");
if (FaceKit.ColumnDivider("##meta_split", tx + split, hp.Y, hh, ref split, 40,
_ => RynthCore.Engine.UI.PanelColumnStore.Set("Meta.condFrac", _condFrac)))
_condFrac = Math.Clamp(split / tw, 0.15f, 0.85f);
ImGuiNET.ImGui.Dummy(new Vector2(w, hh));
}
for (int g = 0; g < _groups.Count; g++)
{
(string state, List<int> members) = _groups[g];
bool collapsed = _collapsed.Contains(state);
bool firing = _groupFiring[g];
// Header: caret, State (n) [— firing]; click toggles.
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos();
float hh = bold.FontSize + 6;
ImGuiNET.ImGui.PushID(g);
if (ImGuiNET.ImGui.InvisibleButton("##hdr", new Vector2(w, hh)))
{
if (collapsed) _collapsed.Remove(state); else _collapsed.Add(state);
}
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
ImGuiNET.ImGui.PopID();
uint hc = firing ? Red : Amber;
dl.AddRectFilled(hp, hp + new Vector2(w, hh), g % 2 == 0 ? StateHdrA : StateHdrB);
dl.AddText(bold, bold.FontSize, hp + new Vector2(3, 3), hc, collapsed ? PhosphorIcons.CaretRight : PhosphorIcons.CaretDown);
dl.AddText(bold, bold.FontSize, hp + new Vector2(18, 3), hc, _groupLabel[g]);
if (collapsed) continue;
for (int gi = 0; gi < members.Count; gi++)
{
int index = members[gi];
if (index >= rules.Count) break;
if (RuleRow(rules[index], index, gi, members.Count, w)) return; // the list changed: redraw next frame
}
}
}
/// <summary>One rule row plus its expanded children. True when a click changed the list.</summary>
private bool RuleRow(MetaRuleDto rule, int index, int gi, int groupCount, float w)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
bool firing = rule.LastFiredMs < 1500;
bool hasChildren = (MetaVocabulary.IsCompositeCondition(rule.Condition) && rule.Children.Count > 0)
|| (MetaVocabulary.IsAllAction(rule.Action) && rule.ActionChildren.Count > 0);
bool expanded = _expanded.Contains(index);
const float h = 20;
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
dl.AddRectFilled(p, p + new Vector2(w, h), firing ? Fired : gi % 2 == 0 ? PanelBg : RowAlt);
ImGuiNET.ImGui.PushID(index);
bool changed = false;
// Enable
float x = p.X + 1;
if (IconButton("##en", rule.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, new Vector2(x, p.Y + 2), new Vector2(14, 16),
rule.Enabled ? Green : Mute, BtnFill, BtnBord))
{
rule.Enabled = !rule.Enabled;
SendEdit(new MetaCmd { Op = "set_rule_enabled", Index = index, Value = rule.Enabled ? "true" : "false" });
}
ImGuiNET.ImGui.SetItemTooltip(rule.Enabled ? "Enabled — click to disable" : "Disabled — click to enable");
x += 16;
// Expand (only with children)
if (hasChildren && IconButton("##exp", expanded ? PhosphorIcons.Minus : PhosphorIcons.Plus, new Vector2(x + 2, p.Y + 3), new Vector2(14, 14),
Teal, BtnFill, BtnBord))
{
if (expanded) _expanded.Remove(index); else _expanded.Add(index);
}
x += 18;
// Up / down within the state (Appendix A3: the plugin now swaps within the state too)
if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, enabled: gi > 0))
changed |= Move(index, -1);
ImGuiNET.ImGui.SetItemTooltip("Move up");
x += 18;
if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord,
enabled: gi < groupCount - 1))
changed |= Move(index, +1);
ImGuiNET.ImGui.SetItemTooltip("Move down");
x += 18;
// Duplicate
if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord))
{
SendEdit(new MetaCmd { Op = "duplicate_rule", Index = index, Rule = rule.Clone() });
_data.Rules.Insert(Math.Min(index + 1, _data.Rules.Count), rule.Clone());
changed = true;
}
ImGuiNET.ImGui.SetItemTooltip("Duplicate rule");
x += 20;
// Delete: on its own at the far right, away from the other buttons (2026-10-05). A rule
// with anything in it takes a second click within 3 s; an empty Never -> None one goes at once.
bool arming = _confirmDeleteIndex == index && _confirmDelete != null && NowMs < _confirmDeleteUntil
&& MetaRuleEdit.SameContent(_confirmDelete, rule);
float delW = arming ? BtnW("Delete?", 50) : 20;
float delX = p.X + w - delW - 2;
if (arming
? Button("Delete?##del", new Vector2(delX, p.Y + 2), new Vector2(delW, 16), TextDim, DelFill, Red)
: IconButton("##del", PhosphorIcons.Trash, new Vector2(delX, p.Y + 2), new Vector2(delW, 16), TextDim, DelFill, BtnBord))
{
if (arming || MetaRuleEdit.IsPlaceholder(rule))
{
SendEdit(new MetaCmd { Op = "delete_rule", Index = index });
_data.Rules.RemoveAt(index);
_expanded.Clear();
_confirmDelete = null;
changed = true;
}
else
{
_confirmDelete = rule.Clone();
_confirmDeleteIndex = index;
_confirmDeleteUntil = NowMs + 3000;
}
}
ImGuiNET.ImGui.SetItemTooltip(arming ? "Click again to delete this rule" : "Delete rule");
// Condition | action text; clicking it edits the rule.
float textW = Math.Max(1, p.X + w - DeleteColumnW - x);
_textStartOff = x - p.X;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y));
if (ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(textW, h)))
OpenEditor(index, rule);
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
ImGuiNET.ImGui.PopID();
if (!changed)
{
float col = textW * _condFrac;
float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
uint condCol = firing ? Red : TextDim, actCol = firing ? Amber : C(0xFFC8D8E8);
if (!rule.Enabled) { condCol = Faded(condCol); actCol = Faded(actCol); }
dl.AddText(new Vector2(x + 3, ty), condCol, Fit(_condText[index], col - 5));
// The armed "Delete?" button is wider than the column gap: the action text stops short of it.
float actW = Math.Min(textW - col - 4, delX - 6 - (x + col + 2));
dl.AddText(new Vector2(x + col + 2, ty), actCol, Fit(_actText[index], actW));
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
if (changed)
{
RebuildCaches();
return true;
}
if (hasChildren && expanded) ExpandedChildren(rule);
return false;
}
private void ExpandedChildren(MetaRuleDto rule)
{
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
ImGuiNET.ImGui.PushFont(f9);
Vector4 amber = RynthTheme.Vec(0xFFE8B333), mute = RynthTheme.Vec(0xFFC8D6E4);
ImGuiNET.ImGui.Indent(22);
if (MetaVocabulary.IsCompositeCondition(rule.Condition) && rule.Children.Count > 0)
{
ImGuiNET.ImGui.TextColored(amber, " " + MetaVocabulary.ConditionName(rule.Condition) + ":");
foreach (MetaRuleDto child in rule.Children)
ImGuiNET.ImGui.TextColored(mute, " • " + MetaVocabulary.CondText(child));
}
if (MetaVocabulary.IsAllAction(rule.Action) && rule.ActionChildren.Count > 0)
{
ImGuiNET.ImGui.TextColored(amber, " All (actions):");
foreach (MetaRuleDto child in rule.ActionChildren)
ImGuiNET.ImGui.TextColored(mute, " • " + MetaVocabulary.ActText(child));
}
ImGuiNET.ImGui.Unindent(22);
ImGuiNET.ImGui.PopFont();
}
private bool Move(int index, int direction)
{
int other = MetaVocabulary.SwapPartner(_data.Rules, index, direction);
if (other < 0) return false;
SendEdit(new MetaCmd { Op = direction < 0 ? "move_up" : "move_down", Index = index });
(_data.Rules[index], _data.Rules[other]) = (_data.Rules[other], _data.Rules[index]);
_expanded.Clear();
return true;
}
private void BottomBar(float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float labelW = ImGuiNET.ImGui.CalcTextSize("State:").X;
dl.AddText(new Vector2(p.X, p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "State:");
// Buttons sized from their text, so a larger panel text size can't overflow them
// (2026-10-05: "+ New Rule" spilled past its fixed 72 px button).
string ruleLabel = PhosphorIcons.Plus + " New Rule";
float newW = ImGuiNET.ImGui.CalcTextSize(ruleLabel).X + 18;
// The bar sits on the body's bottom edge: it stops short of the resize grip (GripInBody).
float grip = ImGuiPanelHost.BodyGripReserve;
float ruleX = p.X + w - grip - newW;
float pickX = p.X + labelW + 4;
float pickW = Math.Max(40, ruleX - 4 - pickX);
// The meta's current state. "+ New state..." at the end of the list makes one: it starts
// with an empty Never -> None rule (that rule is what keeps it), becomes the current state
// like any state picked here, and that rule opens in the editor.
string? chosen = StatePicker("##cur_state", _data.CurrentState, _statePicks, Array.IndexOf(_statePicks, _data.CurrentState),
new Vector2(pickX, p.Y + 1), pickW, out bool isNew);
if (chosen != null)
{
if (isNew) CreateState(chosen, openIt: true);
_data.CurrentState = chosen;
MetaCommands.Simple("set_state", value: chosen);
}
if (Button(ruleLabel + "##new", new Vector2(ruleX, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green))
OpenEditor(-1, new MetaRuleDto { State = _data.CurrentState, Action = 1 });
ImGuiNET.ImGui.SetItemTooltip("A new rule in the current state (added once its condition and action are filled in)");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24));
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
}
// =====================================================================
// Source view
@ -1125,7 +843,7 @@ internal sealed partial class MetaFace : IImGuiPanel
/// picked index or -1.
/// </summary>
private int Picker(string id, string shown, string[] items, int selected, Vector2 pos, float width, float height = 22,
string? extra = null)
string? extra = null, string? badge = null)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImGuiNET.ImGui.PushID(id);
@ -1146,7 +864,16 @@ internal sealed partial class MetaFace : IImGuiPanel
const float caretW = 14;
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown,
new Vector2(pos.X + width - caretW - 3, pos.Y), new Vector2(caretW, height), Mute);
dl.AddText(pos + new Vector2(6, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, Fit(shown, width - 6 - caretW - 6));
// A badge (seconds in state) sits right-aligned before the arrow; the text is cut before it.
float badgeW = 0;
if (!string.IsNullOrEmpty(badge))
{
badgeW = ImGuiNET.ImGui.CalcTextSize(badge).X + 8;
if (badgeW > width * 0.5f) badgeW = 0;
else dl.AddText(new Vector2(pos.X + width - caretW - 3 - badgeW + 2, pos.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
Faded(Teal), badge);
}
dl.AddText(pos + new Vector2(6, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, Fit(shown, width - 6 - caretW - 6 - badgeW));
int picked = -1;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
@ -1278,9 +1005,15 @@ internal sealed partial class MetaFace : IImGuiPanel
string shown = text;
if (ImGuiNET.ImGui.CalcTextSize(text).X > width)
{
int n = text.Length;
while (n > 0 && ImGuiNET.ImGui.CalcTextSize(text.AsSpan(0, n).ToString() + "…").X > width) n--;
shown = text.Substring(0, n) + "…";
// The longest start that fits with "…" (binary search: long expressions are cut often,
// and the cache empties with every snapshot while rules fire).
int lo = 0, hi = text.Length - 1;
while (lo < hi)
{
int mid = (lo + hi + 1) / 2;
if (ImGuiNET.ImGui.CalcTextSize(text.Substring(0, mid) + "…").X <= width) lo = mid; else hi = mid - 1;
}
shown = text.Substring(0, lo) + "…";
}
if (_fit.Count > 4000) _fit.Clear(); // widths change while a panel is resized
_fit[key] = shown;

View file

@ -63,6 +63,16 @@ internal static unsafe class FlightRecorder
public static bool Enabled => _cap != null && !_paused;
/// <summary>An automatic dump is scheduled or a dump is being written right now.</summary>
public static bool DumpPendingOrRunning
{
get
{
if (Volatile.Read(ref _dumping) != 0) return true;
lock (ScheduleLock) return _scheduledReason != null;
}
}
// ── setup ──────────────────────────────────────────────────────────────
public static void Initialize()

View file

@ -30,6 +30,7 @@ internal static class EngineSettings
private static bool _enableImGuiBackend = true;
private static bool _enableHangMinidump = true;
private static bool _preventIdleLogoff = true;
private static bool _closeOnServerDisconnect = true;
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
private static bool _decalInGameImGui = true;
private static bool _decalStandDown = true;
@ -231,6 +232,27 @@ internal static class EngineSettings
}
}
/// <summary>"CloseOnServerDisconnect" in engine.json (default true, 2026-10-11): when AC shows
/// its "The server has disconnected" screen (UIFlow mode Disconnected, only a Quit Game
/// button), the engine closes the client a few seconds later the way the window's close
/// button does (Compatibility/ServerDisconnectClose.cs), so a launcher's auto-relaunch can
/// bring it back. Off: the client stays on that screen. Set in game in Settings > Misc.</summary>
public static bool CloseOnServerDisconnect
{
get
{
EnsureLoaded();
return _closeOnServerDisconnect;
}
set
{
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
if (_closeOnServerDisconnect == value) return;
_closeOnServerDisconnect = value;
Save();
}
}
/// <summary>"DecalBridge" in engine.json: Auto (default), On or Off. Only matters when
/// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md):
/// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello
@ -552,6 +574,10 @@ internal static class EngineSettings
_preventIdleLogoff = pilEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("CloseOnServerDisconnect", out var cosdEl) &&
(cosdEl.ValueKind == JsonValueKind.True || cosdEl.ValueKind == JsonValueKind.False))
_closeOnServerDisconnect = cosdEl.GetBoolean();
if (doc.RootElement.TryGetProperty("IltServerNames", out var ilnEl) &&
ilnEl.ValueKind == JsonValueKind.Array)
_iltServerNames = ReadStringList(ilnEl);
@ -601,7 +627,7 @@ internal static class EngineSettings
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
"FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
"MaxHotReloads", "ReportEndpoint",
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect",
};
private static void Save()
@ -650,6 +676,8 @@ internal static class EngineSettings
w.WriteBoolean("EnableLargeAddressAlignmentFix", false);
if (_insertReleasesUi) // default false: leave the file as it was
w.WriteBoolean("InsertReleasesUi", true);
if (!_closeOnServerDisconnect) // default true: leave the file as it was
w.WriteBoolean("CloseOnServerDisconnect", false);
if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written
w.WriteNumber("MaxHotReloads", _maxHotReloads);
if (_reportEndpoint != null) // only a hand-set value is written

View file

@ -844,6 +844,26 @@ internal struct RynthCoreAPI
/// must equal that price; 0 skips the comparison. Same results and threading as Raise.
/// Requires API v79+.</summary>
public IntPtr TrainSkillFn;
/// <summary>v80: <c>int GetContainerOrder(uint containerId, int slotKind, uint* ids, int maxIds)</c>:
/// the items in one of the player's containers in their real slot order, as the server keeps it
/// (Net/InventoryOrder: the login message, a pack's contents list and every item move), where
/// GetContainerContents is in object-id order. slotKind 0 = the ordinary items (slot 0 first);
/// 1 = the side packs and foci in the main pack (the pack column, top first). Writes at most
/// maxIds ids (ids may be null with maxIds 0 to ask the count) and returns how many there are,
/// or -1 when no full list for that container has been seen (a side pack the server hasn't
/// listed yet): then the order is unknown, never guessed. Any thread. Requires API v80+.</summary>
public IntPtr GetContainerOrderFn;
/// <summary>v80: <c>int PutItemInContainer(uint itemId, uint containerId, int placement)</c>: move an
/// item into a container at a slot (the 0x19 PutItemInContainer game action, the packet only:
/// CM_Inventory::Event_PutItemInContainer), as a drop on a cell of the pack grid does. Within one
/// container it reorders: placement is the index the item should end at, counted without it.
/// MoveItemInternal ignores its slot argument (first empty slot); this doesn't. The server decides
/// (full pack, busy) and answers as for any move. Queued to AC's main thread when called off it.
/// Returns 1 sent or queued, 0 refused before sending (bad ids, negative placement), -1 the
/// sender isn't bound on this client. Requires API v80+.</summary>
public IntPtr PutItemInContainerFn;
}
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
@ -1664,3 +1684,9 @@ internal unsafe delegate int RaiseCallbackDelegate(uint kind, uint stype, uint r
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int TrainSkillCallbackDelegate(uint stype, int expectedCredits);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetContainerOrderCallbackDelegate(uint containerId, int slotKind, uint* ids, int maxIds);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int PutItemInContainerCallbackDelegate(uint itemId, uint containerId, int placement);

View file

@ -15,5 +15,5 @@ namespace RynthCore.Engine.Plugins;
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary>
internal static class PluginContractVersion
{
public const uint Current = 79;
public const uint Current = 80;
}

View file

@ -264,6 +264,8 @@ internal static partial class PluginManager
private static GetTrainingInfoCallbackDelegate? _getTrainingInfoCallback; // v79
private static RaiseCallbackDelegate? _raiseCallback; // v79
private static TrainSkillCallbackDelegate? _trainSkillCallback; // v79
private static GetContainerOrderCallbackDelegate? _getContainerOrderCallback; // v80
private static PutItemInContainerCallbackDelegate? _putItemInContainerCallback; // v80
private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback;
private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback;
private static VendorBuyCallbackDelegate? _vendorBuyCallback;
@ -2787,6 +2789,8 @@ internal static partial class PluginManager
unsafe { _getTrainingInfoCallback ??= GetTrainingInfoAction; } // v79
unsafe { _raiseCallback ??= RaiseAction; }
_trainSkillCallback ??= TrainSkillAction;
unsafe { _getContainerOrderCallback ??= GetContainerOrderAction; } // v80
_putItemInContainerCallback ??= PutItemInContainerAction;
_getVendorInfoCallback ??= GetVendorInfoAction;
_getVendorItemsCallback ??= GetVendorItemsAction;
_vendorBuyCallback ??= VendorBuyAction;
@ -2930,6 +2934,8 @@ internal static partial class PluginManager
_api.GetTrainingInfoFn = Marshal.GetFunctionPointerForDelegate(_getTrainingInfoCallback);
_api.RaiseFn = Marshal.GetFunctionPointerForDelegate(_raiseCallback);
_api.TrainSkillFn = Marshal.GetFunctionPointerForDelegate(_trainSkillCallback);
_api.GetContainerOrderFn = Marshal.GetFunctionPointerForDelegate(_getContainerOrderCallback);
_api.PutItemInContainerFn = Marshal.GetFunctionPointerForDelegate(_putItemInContainerCallback);
_api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback);
_api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback);
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
@ -4041,6 +4047,41 @@ internal static partial class PluginManager
}
}
// ── v80: slot order and placed moves (Net/InventoryOrder, ClientHelperHooks) ──
/// <summary>v80: see PluginContract.GetContainerOrderFn.</summary>
private static unsafe int GetContainerOrderAction(uint containerId, int slotKind, uint* ids, int maxIds)
{
try
{
if (containerId == 0 || slotKind is < 0 or > 1 || maxIds < 0 || (ids == null && maxIds > 0)) return -1;
if (!Net.InventoryOrder.TryGetOrder(containerId, slotKind == 1, out uint[] order)) return -1;
int n = Math.Min(order.Length, maxIds);
for (int i = 0; i < n; i++) ids[i] = order[i];
return order.Length;
}
catch
{
return -1;
}
}
/// <summary>v80: see PluginContract.PutItemInContainerFn.</summary>
private static int PutItemInContainerAction(uint itemId, uint containerId, int placement)
{
try
{
if (!ClientHelperHooks.HasPutItemInContainer) return -1;
Compatibility.AcActionTrace.Record("PutItemInContainer", itemId, containerId);
return ToAbiBool(ClientHelperHooks.PutItemInContainerAt(itemId, containerId, placement));
}
catch (Exception ex)
{
RynthLog.Compat($"PutItemInContainer failed - {ex.GetType().Name}: {ex.Message}");
return 0;
}
}
/// <summary>v78: see PluginContract.SetServerMessageInterestFn.</summary>
private static unsafe int SetServerMessageInterestAction(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount)
{

View file

@ -4,8 +4,9 @@
// the Avalonia UI/Panels/RynthChatPanel.cs) and both filter editors:
//
// • ChatSource (hub, 100 ms) pulls new lines from RynthChatGetScrollbackJson
// on the pump thread, keeps the newest 500, routes and colours them with
// the rules, and writes the chat log. It also hands each new line to the
// on the pump thread, keeps the newest ChatModel.HistoryLines ("Chat
// history", 2,000 by default; 500 before 2026-10-11, see ChatHistory.cs),
// routes and colours them with the rules, and writes the chat log. It also hands each new line to the
// Discord relay and ticks it (UI/Data/Discord/ChatDiscord.cs), which keeps
// this source subscribed while it is on.
// • ChatModel holds the settings (rynthchat_settings.json), the regex
@ -25,13 +26,14 @@
// colours add up, a higher rule winning where two overlap.
//
// Threads: rules are evaluated ONLY on the pump (ChatSource) - each new line
// once, and every kept line again when the rules change - and the result is
// once, and every kept line again when the rules change (in 8 ms slices, newest
// first, since the history can be 10,000 lines) - and the result is
// stored on the line (ChatLine.Route). The faces just read routes; no regex
// runs per frame. The one UI-thread evaluation is the rule editor's test box,
// on a keystroke. Every regex has a 15 ms match timeout; a rule that times
// out is marked Slow and skipped until it is edited, so a pathological
// pattern costs one timeout, not one per line. A rule that never times out
// but spends over 100 ms re-routing the kept lines is marked Slow too: the
// but spends over 100 ms (per 500 lines) re-routing the kept lines is marked Slow too: the
// pump is the plugin tick thread, and a slow re-route holds every plugin's
// tick (ChatRouter.Charge).
//
@ -63,205 +65,28 @@ using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Data;
/// <summary>One scrollback line. Immutable except its Route, which the pump replaces.</summary>
internal sealed class ChatLine
{
public ChatLine(long id, string ts, string chan, int chatType, string? sender, string text)
{
Id = id;
Timestamp = ts;
Channel = chan;
ChatType = chatType;
Sender = sender;
Text = text;
ColorKind = ChatLineColors.KindOf(chatType, chan, text);
ChatLineColors.NoteKind(ColorKind);
// The text already names the speaker ("Bob says, ..."); until 2026-09-29
// the sender was printed in front of it as well ("Bob: Bob says, ...").
FormattedText = $"{ts} {text}";
}
/// <summary>Engine-assigned, increasing for the whole session (the plugin's own
/// seq restarts after RL).</summary>
public long Id { get; }
/// <summary>RynthChat's own number for the line (restarts when its plugin reloads); 0 when not
/// from RynthChat. The Discord relay tells news from scrollback by it.</summary>
public ulong Seq { get; init; }
public string Timestamp { get; }
/// <summary>The channel tab it belongs to (ChatClassifier in the plugin).</summary>
public string Channel { get; }
/// <summary>AC's ChatMessageType; -1 from RynthChat before 0.2.0.</summary>
public int ChatType { get; }
/// <summary>Who spoke, for player speech; metadata only (mentions, rules from a line).</summary>
public string? Sender { get; }
/// <summary>The line as AC printed it. Rules match this.</summary>
public string Text { get; }
/// <summary>Which line colour setting applies ("say", "chan:General", ...), or null:
/// its tab's colour (ChatLineColors.KindOf, worked out once here).</summary>
public string? ColorKind { get; }
/// <summary>"HH:mm:ss text": copy, log and the Avalonia face.</summary>
public string FormattedText { get; }
private ChatRoute _route = ChatRoute.Default;
/// <summary>Where the rules put this line and how it's coloured. Written by the
/// pump (before the line is published, and again when the rules change); any thread reads.</summary>
public ChatRoute Route
{
get => Volatile.Read(ref _route);
internal set => Volatile.Write(ref _route, value);
}
}
/// <summary>A run of the line's Text drawn in its own colour (0xAARRGGBB).</summary>
internal readonly record struct ChatSpan(int Start, int Length, uint Argb);
/// <summary>The rules' verdict for one line. Immutable.</summary>
internal sealed class ChatRoute
{
public static readonly ChatRoute Default = new(false, true, null, null, null, false);
public ChatRoute(bool hidden, bool inHome, string[]? tabs, uint? lineArgb, ChatSpan[]? spans, bool mention)
{
Hidden = hidden;
InHome = inHome;
Tabs = tabs;
LineArgb = lineArgb;
Spans = spans;
Mention = mention;
}
/// <summary>A Hide rule matched: shown nowhere.</summary>
public bool Hidden { get; }
/// <summary>Shown under All and its channel tab (false once a Move rule took it away).</summary>
public bool InHome { get; }
/// <summary>Tabs a Move or Copy rule sent it to.</summary>
public string[]? Tabs { get; }
/// <summary>Whole-line colour from a rule; null = the channel colour.</summary>
public uint? LineArgb { get; }
/// <summary>Matched-text colours: offsets into Text, sorted, not overlapping.</summary>
public ChatSpan[]? Spans { get; }
/// <summary>Someone said your name (or a mention word).</summary>
public bool Mention { get; }
public bool ShowsIn(string tab, string channel)
{
if (Hidden) return false;
if (InHome && (tab == "All" || string.Equals(tab, channel, StringComparison.OrdinalIgnoreCase))) return true;
if (Tabs != null)
foreach (string t in Tabs)
if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
}
internal enum ChatRuleAction
{
/// <summary>Only in the rule's tab: leaves All and its channel tab.</summary>
Move,
/// <summary>Also in the rule's tab.</summary>
Copy,
/// <summary>Nowhere.</summary>
Hide,
/// <summary>No routing: the rule only colours.</summary>
Color,
}
internal enum ChatColorMode { None, Line, Match }
/// <summary>
/// One rule. Its fields are edited in place by a rule editor (then
/// ChatModel.FiltersChanged); the pump reads each field once per line, and a
/// half-applied edit is re-routed by the version bump that follows it.
/// New RynthChat lines while a chat face or the Discord relay holds it (100 ms). Publishes
/// the newest ChatModel.HistoryLines (the "Chat history" setting; 500 until 2026-10-11),
/// routed, and keeps RynthChat's own ring the same length (RynthChatSetCapacity).
/// </summary>
internal sealed class ChatFilterRule
{
public const int TimeoutMs = 15;
public volatile bool Enabled = true;
public volatile string Pattern = "";
/// <summary>The Move / Copy target. Empty: a Move or Copy rule routes nowhere (it can still colour).</summary>
public volatile string Tab = "";
public volatile ChatRuleAction Action = ChatRuleAction.Move;
public volatile ChatColorMode ColorMode = ChatColorMode.None;
/// <summary>How Pattern is read: a regex (the default, and every rule saved before
/// 2026-10-05) or plain text. Recompile after changing it.</summary>
public volatile ChatMatchMode Mode = ChatMatchMode.Regex;
/// <summary>A new rule's colour (amber).</summary>
public const uint DefaultColor = 0xFFFFD27A;
/// <summary>0xAARRGGBB.</summary>
public volatile uint ColorArgb = DefaultColor;
private volatile WhenSpec _when = WhenSpec.Any;
/// <summary>"" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions).</summary>
public string When
{
get => _when.Raw;
set => _when = WhenSpec.Parse(value);
}
/// <summary>Kept lines this rule matched (recounted when the rules change, then
/// counted up as lines arrive). Written by the pump; the editor shows it.</summary>
public int Hits;
public volatile Regex? Compiled;
/// <summary>The pattern doesn't compile (or is empty).</summary>
public volatile bool Invalid;
/// <summary>Why it doesn't compile; null when it does or is just empty.</summary>
public volatile string? Error;
/// <summary>A match timed out: skipped until the pattern is edited.</summary>
public volatile bool Slow;
/// <summary>Compiles the pattern once (after every pattern edit). Any thread.</summary>
public void Recompile()
{
Slow = false;
// A Regex rule compiles exactly as before; plain text is escaped (ChatRuleMatching).
Regex? rx = ChatRuleMatching.Compile(Mode, Pattern, TimeoutMs, out string? error);
Compiled = rx;
Error = error;
Invalid = rx == null;
}
/// <summary>Does the rule route (Move / Copy with a tab, or Hide)?</summary>
public bool Routes => Action == ChatRuleAction.Hide
|| (Action is ChatRuleAction.Move or ChatRuleAction.Copy && Tab.Length > 0);
internal bool WhenMatches(string channel, int chatType)
{
WhenSpec w = _when;
if (w.Channel != null) return string.Equals(w.Channel, channel, StringComparison.OrdinalIgnoreCase);
if (w.Type >= 0) return w.Type == chatType;
return true;
}
private sealed class WhenSpec
{
public static readonly WhenSpec Any = new("", null, -1);
public readonly string Raw;
public readonly string? Channel;
public readonly int Type;
private WhenSpec(string raw, string? channel, int type) { Raw = raw; Channel = channel; Type = type; }
public static WhenSpec Parse(string? raw)
{
raw = (raw ?? "").Trim();
(string? channel, int type) = ChatRuleMatching.ParseWhen(raw);
return channel == null && type < 0 ? Any : new WhenSpec(raw, channel, type);
}
}
}
/// <summary>New RynthChat lines while a chat face or the Discord relay holds it (100 ms). Publishes the newest 500, routed.</summary>
internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
{
private const int MaxLines = 500;
private delegate* unmanaged[Cdecl]<ulong, IntPtr> _get;
// RynthChat 0.3.0+: how many lines its ring keeps. Null for an older plugin (it keeps 500).
private delegate* unmanaged[Cdecl]<int, int> _setCapacity;
private int _sentCapacity;
private ulong _sinceSeq;
private long _nextId = 1;
private bool _boundLogged;
private long _routedVersion = -1;
private string _routedName = "";
// A re-route pass in progress (the rules changed): its router, and the Id below which the
// kept lines still carry the old routes. It runs newest first, RerouteSliceMs per poll.
private ChatRouter? _passRouter;
private long _passBelowId;
private const double RerouteSliceMs = 8;
private static readonly long RerouteSliceTicks = (long)(Stopwatch.Frequency * RerouteSliceMs / 1000);
public ChatSource() : base("Chat", periodMs: 100) { }
@ -290,26 +115,25 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
if (ChatModel.SendLinePtr == IntPtr.Zero)
ChatModel.SendLinePtr = PluginExportBinder.Resolve("RynthChat", "RynthChatSendLine");
ChatModel.PluginBound = _get != null;
int maxLines = ChatModel.HistoryLines;
if (_get != null) SyncPluginCapacity(maxLines);
ChatModel.PumpLog(null);
// The rules (or the name mentions look for) changed: route the kept lines again.
long version = ChatModel.FiltersVersion;
string name = ChatModel.PumpCharacterName();
ChatRouter router = ChatModel.PumpRouter(name);
TrimToLength(maxLines);
if (version != _routedVersion || name != _routedName)
{
_routedVersion = version;
_routedName = name;
ChatLine[]? kept = Current?.Value;
router.BeginPass();
try
{
if (kept != null)
foreach (ChatLine line in kept) line.Route = router.Evaluate(line, null);
}
finally { router.EndPass(); }
ChatModel.BumpRoutes();
_passRouter = router;
_passBelowId = long.MaxValue;
router.BeginPass(Current?.Value.Length ?? 0);
router.EndPass(); // paused until its slice below
}
if (_passRouter != null) ContinueReroute(_passRouter);
if (_get == null) return;
@ -353,16 +177,74 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
}
ChatLine[] old = Current?.Value ?? Array.Empty<ChatLine>();
int keepOld = Math.Max(0, Math.Min(old.Length, MaxLines - added.Count));
int skipAdded = Math.Max(0, added.Count - MaxLines);
var lines = new ChatLine[keepOld + added.Count - skipAdded];
Array.Copy(old, old.Length - keepOld, lines, 0, keepOld);
added.CopyTo(skipAdded, lines, keepOld, added.Count - skipAdded);
Publish(lines);
Publish(ChatHistory.Merge(old, added, maxLines));
ChatModel.PumpLog(added);
RelayRead(added);
}
/// <summary>
/// One time slice of re-routing the kept lines with <paramref name="router"/>, newest
/// first. Up to 2,000 lines take one slice (5 ms, tools/ChatHistoryBench), as the whole
/// pass did before; 10,000 take about four polls. Lines that arrive meanwhile are routed
/// with the same router as they come in. The faces rebuild once, when the pass is done.
/// </summary>
private void ContinueReroute(ChatRouter router)
{
ChatLine[] kept = Current?.Value ?? Array.Empty<ChatLine>();
int i = LastIndexBelow(kept, _passBelowId);
long t0 = Stopwatch.GetTimestamp();
int n = 0;
router.ResumePass();
try
{
while (i >= 0)
{
ChatLine line = kept[i--];
line.Route = router.Evaluate(line, null);
_passBelowId = line.Id;
if ((++n & 31) == 0 && Stopwatch.GetTimestamp() - t0 > RerouteSliceTicks) break;
}
}
finally { router.EndPass(); }
if (i >= 0) return; // more next poll
_passRouter = null;
ChatModel.BumpRoutes();
}
/// <summary>The index of the newest line whose Id is below <paramref name="id"/> (Ids increase), or -1.</summary>
private static int LastIndexBelow(ChatLine[] lines, long id)
{
int lo = 0, hi = lines.Length; // first index with Id >= id
while (lo < hi)
{
int mid = (lo + hi) >> 1;
if (lines[mid].Id < id) lo = mid + 1; else hi = mid;
}
return lo - 1;
}
/// <summary>The setting was lowered: drop the oldest kept lines now, not only when new ones arrive.</summary>
private void TrimToLength(int maxLines)
{
ChatLine[]? kept = Current?.Value;
if (kept != null && ChatHistory.Trim(kept, maxLines) is { } trimmed) Publish(trimmed);
}
/// <summary>Tells RynthChat (0.3.0+) the history length once it's bound and whenever the setting moves.</summary>
private void SyncPluginCapacity(int maxLines)
{
if (_setCapacity == null)
{
_setCapacity = (delegate* unmanaged[Cdecl]<int, int>)PluginExportBinder.Resolve("RynthChat", "RynthChatSetCapacity");
if (_setCapacity == null) return; // an older RynthChat: its ring stays at 500
}
if (_sentCapacity == maxLines) return;
int applied = _setCapacity(maxLines);
if (applied <= 0) return; // the plugin isn't up yet: try again next poll
_sentCapacity = maxLines;
RynthLog.UI($"ChatSource: RynthChat keeps {applied} lines (chat history {maxLines}).");
}
/// <summary>Every scrollback read goes to the Discord relay, empty or not (its first read is a baseline).</summary>
private static void RelayRead(IReadOnlyList<ChatLine> added)
{
@ -451,6 +333,8 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
// RL loads a fresh plugin copy whose scrollback numbers from 1 again.
// The lines already shown stay.
_get = null;
_setCapacity = null;
_sentCapacity = 0;
_sinceSeq = 0;
Discord.ChatDiscord.PumpSourceReset();
ChatModel.SendLinePtr = IntPtr.Zero;
@ -458,236 +342,6 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
}
}
/// <summary>
/// Evaluates the rules for one line: a snapshot of the rule list plus the
/// mention regex. Built by ChatModel.PumpRouter (pump) or for the editor's
/// test box (UI thread). One thread per router: each one's cost counters are
/// its own (the pump's lives on the pump; the test box builds a fresh one).
/// </summary>
internal sealed class ChatRouter
{
/// <summary>Mentions colour the name like this (amber).</summary>
public const uint MentionArgb = 0xFFFFC857;
// The 15 ms timeout only catches a pattern that is slow on one line. One that
// costs a millisecond or two per line never times out, yet re-routing the 500
// kept lines (on every keystroke in the rule editor) then holds the pump -
// which is the plugin tick thread - for a second or more. So during a
// re-route pass each rule's matching time is added up, and a rule that uses
// more than PassBudgetMs is marked Slow like a timed-out one. An ordinary
// rule takes a few microseconds a line, a few ms for the pass. One reading
// counts at most MaxChargeMs, so a GC pause or a descheduled thread in the
// middle of a match doesn't condemn the rule on its own.
private const double PassBudgetMs = 100, MaxChargeMs = 30;
private static readonly long PassBudgetTicks = (long)(Stopwatch.Frequency * PassBudgetMs / 1000);
private static readonly long MaxChargeTicks = (long)(Stopwatch.Frequency * MaxChargeMs / 1000);
/// <summary>ChatMessageType Emote (0x0C).</summary>
private const int EmoteType = 0x0C;
private readonly ChatFilterRule[] _rules;
private readonly Regex? _mention;
private readonly string _self;
private readonly bool _countHits;
private readonly long[] _passTicks;
private bool _inPass;
/// <param name="self">Your character's name ("" unknown): your own emotes don't mention you.</param>
/// <param name="countHits">Count matches into ChatFilterRule.Hits (the pump's router; not the test box's).</param>
public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits)
{
_rules = rules;
_mention = mention;
_self = self.Trim();
_countHits = countHits;
_passTicks = new long[rules.Length];
}
/// <summary>Before routing every kept line again: hit counts restart, and each rule's time is watched.</summary>
public void BeginPass()
{
ResetHits();
Array.Clear(_passTicks);
_inPass = true;
}
public void EndPass() => _inPass = false;
/// <summary>Adds a rule's matching time during a pass; marks it Slow past the budget. False once it's Slow.</summary>
private bool Charge(int i, long ticks, List<Step>? trace)
{
if (!_inPass) return true;
_passTicks[i] += Math.Min(ticks, MaxChargeTicks);
if (_passTicks[i] <= PassBudgetTicks) return true;
MarkSlow(_rules[i], trace, i, $"over {PassBudgetMs:0} ms to re-route the kept lines");
return false;
}
/// <summary>Before routing every kept line again.</summary>
public void ResetHits()
{
foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0);
}
/// <summary>One step of the editor's test: rule index (-1 = mention) and what it did.</summary>
public readonly record struct Step(int Rule, string What);
public ChatRoute Evaluate(ChatLine line, List<Step>? trace) =>
Evaluate(line.Text, line.Channel, line.ChatType, trace);
public ChatRoute Evaluate(string text, string channel, int chatType, List<Step>? trace)
{
bool hidden = false, inHome = true, routed = false;
List<string>? tabs = null;
uint? lineArgb = null;
List<(int Start, int Length, uint Argb)>? spans = null;
for (int i = 0; i < _rules.Length; i++)
{
ChatFilterRule rule = _rules[i];
if (!rule.Enabled || rule.Slow) continue;
Regex? rx = rule.Compiled;
if (rx == null) continue;
ChatRuleAction action = rule.Action;
ChatColorMode mode = rule.ColorMode;
string tab = rule.Tab;
bool routes = action == ChatRuleAction.Hide
|| (action is ChatRuleAction.Move or ChatRuleAction.Copy && tab.Length > 0);
bool wantsRoute = routes && !routed;
bool wantsLine = mode == ChatColorMode.Line && lineArgb == null;
bool wantsMatch = mode == ChatColorMode.Match;
// Nothing left for it to decide (the test box still shows that it matches).
if (!wantsRoute && !wantsLine && !wantsMatch && trace == null) continue;
if (!rule.WhenMatches(channel, chatType)) continue;
Match m;
long t0 = Stopwatch.GetTimestamp();
try { m = rx.Match(text); }
catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); continue; }
if (!Charge(i, Stopwatch.GetTimestamp() - t0, trace)) continue;
if (!m.Success) continue;
if (_countHits) Interlocked.Increment(ref rule.Hits);
var what = trace != null ? new StringBuilder() : null;
if (wantsRoute)
{
switch (action)
{
case ChatRuleAction.Hide:
hidden = routed = true;
what?.Append("hides it");
break;
case ChatRuleAction.Move:
inHome = false;
routed = true;
AddTab(ref tabs, tab);
what?.Append("moves it to ").Append(tab);
break;
case ChatRuleAction.Copy:
AddTab(ref tabs, tab);
what?.Append("copies it to ").Append(tab);
break;
}
}
else if (routes && trace != null)
what!.Append("(a Move/Hide above already decided the tab)");
if (hidden)
{
trace?.Add(new Step(i, what!.ToString()));
break;
}
if (wantsLine)
{
lineArgb = rule.ColorArgb;
what?.Append(what.Length > 0 ? ", " : "").Append("colours the line");
}
else if (mode == ChatColorMode.Line && trace != null)
what!.Append(what.Length > 0 ? ", " : "").Append("(line colour already set above)");
if (wantsMatch)
{
int n = 0;
long t1 = Stopwatch.GetTimestamp();
try
{
for (; m.Success && n < 16; m = m.NextMatch())
if (m.Length > 0) { (spans ??= new()).Add((m.Index, m.Length, rule.ColorArgb)); n++; }
}
catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); }
if (!rule.Slow) Charge(i, Stopwatch.GetTimestamp() - t1, trace);
what?.Append(what.Length > 0 ? ", " : "").Append(n == 1 ? "colours the match" : $"colours {n} matches");
}
if (what is { Length: 0 }) what.Append("matches, but has nothing to do yet (no tab, no colour)");
trace?.Add(new Step(i, what!.ToString()));
}
bool mention = false;
if (!hidden && _mention != null && ChatModel.MentionEligible(channel, chatType))
{
try
{
Match m = _mention.Match(text);
for (int n = 0; m.Success && n < 8; m = m.NextMatch(), n++)
{
// Your own emote prints as "Tom waves." (type Emote, your name first): that's you, not a mention.
if (m.Index == 0 && chatType == EmoteType && _self.Length > 0
&& string.Equals(m.Value, _self, StringComparison.OrdinalIgnoreCase)) continue;
mention = true;
(spans ??= new()).Add((m.Index, m.Length, MentionArgb));
}
}
catch (RegexMatchTimeoutException) { }
if (mention) trace?.Add(new Step(-1, "mentions you (highlighted)"));
}
if (!hidden && inHome && tabs == null && lineArgb == null && spans == null && !mention)
return ChatRoute.Default;
return new ChatRoute(hidden, inHome, tabs?.ToArray(), lineArgb, Resolve(spans, text.Length), mention);
}
private static void AddTab(ref List<string>? tabs, string tab)
{
tabs ??= new List<string>(2);
foreach (string t in tabs) if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return;
tabs.Add(tab);
}
private static void MarkSlow(ChatFilterRule rule, List<Step>? trace, int index, string why)
{
if (!rule.Slow)
{
rule.Slow = true;
RynthLog.UI($"ChatModel: rule \"{rule.Pattern}\" is too slow ({why}) and is skipped until edited.");
// Lines already routed with it are routed again without it.
ChatModel.BumpFiltersVersion();
}
trace?.Add(new Step(index, "too slow - now skipped until edited"));
}
/// <summary>Overlapping spans: the earlier one (a higher rule) keeps its characters.</summary>
private static ChatSpan[]? Resolve(List<(int Start, int Length, uint Argb)>? spans, int textLength)
{
if (spans == null || spans.Count == 0) return null;
if (spans.Count == 1)
return new[] { new ChatSpan(spans[0].Start, spans[0].Length, spans[0].Argb) };
var owner = new int[textLength]; // 0 = free, else span index + 1
for (int s = 0; s < spans.Count; s++)
{
int end = Math.Min(textLength, spans[s].Start + spans[s].Length);
for (int c = spans[s].Start; c < end; c++)
if (owner[c] == 0) owner[c] = s + 1;
}
var result = new List<ChatSpan>();
for (int c = 0; c < textLength;)
{
int o = owner[c];
int start = c;
while (c < textLength && owner[c] == o) c++;
if (o != 0) result.Add(new ChatSpan(start, c - start, spans[o - 1].Argb));
}
return result.ToArray();
}
}
internal static class ChatModel
{
/// <summary>Channel tabs; must match ChatClassifier in the plugin.</summary>
@ -771,6 +425,16 @@ internal static class ChatModel
public static volatile bool MentionSound;
/// <summary>Extra words to highlight, comma-separated.</summary>
public static volatile string MentionWords = "";
/// <summary>How many lines the scrollback keeps, all tabs together (ChatHistory; "Chat history" in the gear menu).</summary>
public static volatile int HistoryLines = ChatHistory.DefaultLines;
public static void SetHistoryLines(int lines)
{
lines = ChatHistory.Clamp(lines);
if (lines == HistoryLines) return;
HistoryLines = lines;
SaveSettings();
}
public static void SetCtrlGatedClickThrough(bool on)
{
@ -1668,6 +1332,7 @@ internal static class ChatModel
MentionHighlight = dto.MentionHighlight;
MentionSound = dto.MentionSound;
MentionWords = dto.MentionWords ?? "";
HistoryLines = ChatHistory.Clamp(dto.HistoryLines ?? 0); // absent before 2026-10-11: the default
ChatLineColors.Load(dto.LineColors); // absent before 2026-10-08: nothing set
var tabs = new List<string>();
@ -1734,6 +1399,8 @@ internal static class ChatModel
MentionHighlight = MentionHighlight,
MentionSound = MentionSound,
MentionWords = MentionWords,
// Left out at the default, so a file follows the default if it ever changes.
HistoryLines = HistoryLines == ChatHistory.DefaultLines ? null : HistoryLines,
LineColors = ChatLineColors.ToJson(), // null (left out) until a colour is set
CustomTabs = Volatile.Read(ref _customTabs),
Filters = Filters.Select(ToDto).ToArray(),

View file

@ -0,0 +1,70 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ChatHistory.cs
// How long RynthChat's scrollback is (the chat setting "Chat history",
// 2026-10-11; a fixed 500 lines before) and the newest-N bookkeeping that
// goes with it. No engine state: tools/ChatHistoryBench compiles it in.
//
// The length applies to both copies of the scrollback: the engine's
// (ChatSource's published ChatLine[]) and RynthChat's own ring, which the
// engine resizes through the plugin's RynthChatSetCapacity export (RynthChat
// 0.3.0; an older plugin keeps its 500). Lines are numbered by the plugin and
// the engine either way, so the Discord relay's seq bookkeeping is untouched.
//
// Cost, measured by tools/ChatHistoryBench (x86, like acclient): about 1.8 MB
// of managed memory per 1,000 lines (engine 1.2, plugin ring 0.6, the face's
// lists 0.04), so 18 MB at 10,000 against the 1.3-2.3 GB of address space a
// client has free. Per poll the work grows with the new lines, not the length
// (one array copy: 11 us at 10,000). What grows with it: the first read after
// a bind or reload (15 ms at 2,000, 59 ms at 10,000, once), re-routing after
// a rule edit (7 / 27 ms, done in 8 ms slices) and re-measuring after a resize
// (4 / 15 ms, done in 2 ms slices a frame). The table is in that tool's header.
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.UI.Data;
internal static class ChatHistory
{
public const int DefaultLines = 2000;
public const int MinLines = 500;
public const int MaxLines = 10000;
/// <summary>The setting moves in steps of this many lines.</summary>
public const int StepLines = 500;
/// <summary>A stored or typed length made valid: 0 or less (absent) is the default.</summary>
public static int Clamp(int lines)
{
if (lines <= 0) return DefaultLines;
lines = (int)Math.Round(lines / (double)StepLines) * StepLines;
return Math.Clamp(lines, MinLines, MaxLines);
}
/// <summary>
/// The newest <paramref name="max"/> of <paramref name="old"/> followed by
/// <paramref name="added"/>, as a new array (the published one is never changed:
/// faces on other threads read it). Cost: one copy of the kept references.
/// </summary>
public static T[] Merge<T>(T[] old, IReadOnlyList<T> added, int max)
{
max = Math.Max(1, max);
int skipAdded = Math.Max(0, added.Count - max);
int takeAdded = added.Count - skipAdded;
int keepOld = Math.Max(0, Math.Min(old.Length, max - takeAdded));
var lines = new T[keepOld + takeAdded];
Array.Copy(old, old.Length - keepOld, lines, 0, keepOld);
for (int i = 0; i < takeAdded; i++) lines[keepOld + i] = added[skipAdded + i];
return lines;
}
/// <summary>The newest <paramref name="max"/> lines, or null when there are no more than that.</summary>
public static T[]? Trim<T>(T[] lines, int max)
{
max = Math.Max(1, max);
if (lines.Length <= max) return null;
var kept = new T[max];
Array.Copy(lines, lines.Length - max, kept, 0, max);
return kept;
}
}

View file

@ -0,0 +1,452 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ChatRouting.cs
// RynthChat's lines and rules: ChatLine (one scrollback line), ChatRoute (the
// rules' verdict for it), ChatFilterRule and ChatRouter (which evaluates the
// rules). Moved out of ChatData.cs (2026-10-11) unchanged, so tools can run
// the real classes without the engine (tools/ChatHistoryBench). How the rules
// work and on which thread: see the header of ChatData.cs.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.UI.Data;
/// <summary>One scrollback line. Immutable except its Route, which the pump replaces.</summary>
internal sealed class ChatLine
{
public ChatLine(long id, string ts, string chan, int chatType, string? sender, string text)
{
Id = id;
Timestamp = ts;
Channel = chan;
ChatType = chatType;
Sender = sender;
Text = text;
ColorKind = ChatLineColors.KindOf(chatType, chan, text);
ChatLineColors.NoteKind(ColorKind);
// The text already names the speaker ("Bob says, ..."); until 2026-09-29
// the sender was printed in front of it as well ("Bob: Bob says, ...").
FormattedText = $"{ts} {text}";
}
/// <summary>Engine-assigned, increasing for the whole session (the plugin's own
/// seq restarts after RL).</summary>
public long Id { get; }
/// <summary>RynthChat's own number for the line (restarts when its plugin reloads); 0 when not
/// from RynthChat. The Discord relay tells news from scrollback by it.</summary>
public ulong Seq { get; init; }
public string Timestamp { get; }
/// <summary>The channel tab it belongs to (ChatClassifier in the plugin).</summary>
public string Channel { get; }
/// <summary>AC's ChatMessageType; -1 from RynthChat before 0.2.0.</summary>
public int ChatType { get; }
/// <summary>Who spoke, for player speech; metadata only (mentions, rules from a line).</summary>
public string? Sender { get; }
/// <summary>The line as AC printed it. Rules match this.</summary>
public string Text { get; }
/// <summary>Which line colour setting applies ("say", "chan:General", ...), or null:
/// its tab's colour (ChatLineColors.KindOf, worked out once here).</summary>
public string? ColorKind { get; }
/// <summary>"HH:mm:ss text": copy, log and the Avalonia face.</summary>
public string FormattedText { get; }
private ChatRoute _route = ChatRoute.Default;
/// <summary>Where the rules put this line and how it's coloured. Written by the
/// pump (before the line is published, and again when the rules change); any thread reads.</summary>
public ChatRoute Route
{
get => Volatile.Read(ref _route);
internal set => Volatile.Write(ref _route, value);
}
}
/// <summary>A run of the line's Text drawn in its own colour (0xAARRGGBB).</summary>
internal readonly record struct ChatSpan(int Start, int Length, uint Argb);
/// <summary>The rules' verdict for one line. Immutable.</summary>
internal sealed class ChatRoute
{
public static readonly ChatRoute Default = new(false, true, null, null, null, false);
public ChatRoute(bool hidden, bool inHome, string[]? tabs, uint? lineArgb, ChatSpan[]? spans, bool mention)
{
Hidden = hidden;
InHome = inHome;
Tabs = tabs;
LineArgb = lineArgb;
Spans = spans;
Mention = mention;
}
/// <summary>A Hide rule matched: shown nowhere.</summary>
public bool Hidden { get; }
/// <summary>Shown under All and its channel tab (false once a Move rule took it away).</summary>
public bool InHome { get; }
/// <summary>Tabs a Move or Copy rule sent it to.</summary>
public string[]? Tabs { get; }
/// <summary>Whole-line colour from a rule; null = the channel colour.</summary>
public uint? LineArgb { get; }
/// <summary>Matched-text colours: offsets into Text, sorted, not overlapping.</summary>
public ChatSpan[]? Spans { get; }
/// <summary>Someone said your name (or a mention word).</summary>
public bool Mention { get; }
public bool ShowsIn(string tab, string channel)
{
if (Hidden) return false;
if (InHome && (tab == "All" || string.Equals(tab, channel, StringComparison.OrdinalIgnoreCase))) return true;
if (Tabs != null)
foreach (string t in Tabs)
if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
}
internal enum ChatRuleAction
{
/// <summary>Only in the rule's tab: leaves All and its channel tab.</summary>
Move,
/// <summary>Also in the rule's tab.</summary>
Copy,
/// <summary>Nowhere.</summary>
Hide,
/// <summary>No routing: the rule only colours.</summary>
Color,
}
internal enum ChatColorMode { None, Line, Match }
/// <summary>
/// One rule. Its fields are edited in place by a rule editor (then
/// ChatModel.FiltersChanged); the pump reads each field once per line, and a
/// half-applied edit is re-routed by the version bump that follows it.
/// </summary>
internal sealed class ChatFilterRule
{
public const int TimeoutMs = 15;
public volatile bool Enabled = true;
public volatile string Pattern = "";
/// <summary>The Move / Copy target. Empty: a Move or Copy rule routes nowhere (it can still colour).</summary>
public volatile string Tab = "";
public volatile ChatRuleAction Action = ChatRuleAction.Move;
public volatile ChatColorMode ColorMode = ChatColorMode.None;
/// <summary>How Pattern is read: a regex (the default, and every rule saved before
/// 2026-10-05) or plain text. Recompile after changing it.</summary>
public volatile ChatMatchMode Mode = ChatMatchMode.Regex;
/// <summary>A new rule's colour (amber).</summary>
public const uint DefaultColor = 0xFFFFD27A;
/// <summary>0xAARRGGBB.</summary>
public volatile uint ColorArgb = DefaultColor;
private volatile WhenSpec _when = WhenSpec.Any;
/// <summary>"" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions).</summary>
public string When
{
get => _when.Raw;
set => _when = WhenSpec.Parse(value);
}
/// <summary>Kept lines this rule matched (recounted when the rules change, then
/// counted up as lines arrive). Written by the pump; the editor shows it.</summary>
public int Hits;
public volatile Regex? Compiled;
/// <summary>The pattern doesn't compile (or is empty).</summary>
public volatile bool Invalid;
/// <summary>Why it doesn't compile; null when it does or is just empty.</summary>
public volatile string? Error;
/// <summary>A match timed out: skipped until the pattern is edited.</summary>
public volatile bool Slow;
/// <summary>Compiles the pattern once (after every pattern edit). Any thread.</summary>
public void Recompile()
{
Slow = false;
// A Regex rule compiles exactly as before; plain text is escaped (ChatRuleMatching).
Regex? rx = ChatRuleMatching.Compile(Mode, Pattern, TimeoutMs, out string? error);
Compiled = rx;
Error = error;
Invalid = rx == null;
}
/// <summary>Does the rule route (Move / Copy with a tab, or Hide)?</summary>
public bool Routes => Action == ChatRuleAction.Hide
|| (Action is ChatRuleAction.Move or ChatRuleAction.Copy && Tab.Length > 0);
internal bool WhenMatches(string channel, int chatType)
{
WhenSpec w = _when;
if (w.Channel != null) return string.Equals(w.Channel, channel, StringComparison.OrdinalIgnoreCase);
if (w.Type >= 0) return w.Type == chatType;
return true;
}
private sealed class WhenSpec
{
public static readonly WhenSpec Any = new("", null, -1);
public readonly string Raw;
public readonly string? Channel;
public readonly int Type;
private WhenSpec(string raw, string? channel, int type) { Raw = raw; Channel = channel; Type = type; }
public static WhenSpec Parse(string? raw)
{
raw = (raw ?? "").Trim();
(string? channel, int type) = ChatRuleMatching.ParseWhen(raw);
return channel == null && type < 0 ? Any : new WhenSpec(raw, channel, type);
}
}
}
/// <summary>
/// Evaluates the rules for one line: a snapshot of the rule list plus the
/// mention regex. Built by ChatModel.PumpRouter (pump) or for the editor's
/// test box (UI thread). One thread per router: each one's cost counters are
/// its own (the pump's lives on the pump; the test box builds a fresh one).
/// </summary>
internal sealed class ChatRouter
{
/// <summary>Mentions colour the name like this (amber).</summary>
public const uint MentionArgb = 0xFFFFC857;
// The 15 ms timeout only catches a pattern that is slow on one line. One that
// costs a millisecond or two per line never times out, yet re-routing the 500
// kept lines (on every keystroke in the rule editor) then holds the pump -
// which is the plugin tick thread - for a second or more. So during a
// re-route pass each rule's matching time is added up, and a rule that uses
// more than PassBudgetMs is marked Slow like a timed-out one. An ordinary
// rule takes a few microseconds a line, a few ms for the pass. One reading
// counts at most MaxChargeMs, so a GC pause or a descheduled thread in the
// middle of a match doesn't condemn the rule on its own.
// Since the history length became a setting (2026-10-11, up to 10,000 lines) the
// budget is PassBudgetMs per 500 kept lines, so a longer history doesn't condemn a
// rule sooner; the pump re-routes in time slices (ChatSource), so a pass no longer
// holds the tick thread for its whole length either.
private const double PassBudgetMs = 100, MaxChargeMs = 30;
private const int PassBudgetLines = 500;
private static readonly long PassBudgetTicks = (long)(Stopwatch.Frequency * PassBudgetMs / 1000);
private static readonly long MaxChargeTicks = (long)(Stopwatch.Frequency * MaxChargeMs / 1000);
/// <summary>ChatMessageType Emote (0x0C).</summary>
private const int EmoteType = 0x0C;
private readonly ChatFilterRule[] _rules;
private readonly Regex? _mention;
private readonly string _self;
private readonly bool _countHits;
private readonly long[] _passTicks;
private long _passBudgetTicks = PassBudgetTicks;
private bool _inPass;
/// <param name="self">Your character's name ("" unknown): your own emotes don't mention you.</param>
/// <param name="countHits">Count matches into ChatFilterRule.Hits (the pump's router; not the test box's).</param>
public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits)
{
_rules = rules;
_mention = mention;
_self = self.Trim();
_countHits = countHits;
_passTicks = new long[rules.Length];
}
/// <summary>
/// Before routing the <paramref name="lines"/> kept lines again: hit counts restart, and
/// each rule's time is watched (PassBudgetMs per PassBudgetLines lines, never less than
/// PassBudgetMs).
/// </summary>
public void BeginPass(int lines = PassBudgetLines)
{
ResetHits();
Array.Clear(_passTicks);
_passBudgetTicks = PassBudgetTicks * Math.Max(PassBudgetLines, lines) / PassBudgetLines;
_inPass = true;
}
/// <summary>The pass is over, or paused between two time slices (lines routed meanwhile aren't charged).</summary>
public void EndPass() => _inPass = false;
/// <summary>The next time slice of a pass begun with BeginPass.</summary>
public void ResumePass() => _inPass = true;
/// <summary>Adds a rule's matching time during a pass; marks it Slow past the budget. False once it's Slow.</summary>
private bool Charge(int i, long ticks, List<Step>? trace)
{
if (!_inPass) return true;
_passTicks[i] += Math.Min(ticks, MaxChargeTicks);
if (_passTicks[i] <= _passBudgetTicks) return true;
MarkSlow(_rules[i], trace, i, $"over {PassBudgetMs:0} ms per {PassBudgetLines} lines to re-route the kept lines");
return false;
}
/// <summary>Before routing every kept line again.</summary>
public void ResetHits()
{
foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0);
}
/// <summary>One step of the editor's test: rule index (-1 = mention) and what it did.</summary>
public readonly record struct Step(int Rule, string What);
public ChatRoute Evaluate(ChatLine line, List<Step>? trace) =>
Evaluate(line.Text, line.Channel, line.ChatType, trace);
public ChatRoute Evaluate(string text, string channel, int chatType, List<Step>? trace)
{
bool hidden = false, inHome = true, routed = false;
List<string>? tabs = null;
uint? lineArgb = null;
List<(int Start, int Length, uint Argb)>? spans = null;
for (int i = 0; i < _rules.Length; i++)
{
ChatFilterRule rule = _rules[i];
if (!rule.Enabled || rule.Slow) continue;
Regex? rx = rule.Compiled;
if (rx == null) continue;
ChatRuleAction action = rule.Action;
ChatColorMode mode = rule.ColorMode;
string tab = rule.Tab;
bool routes = action == ChatRuleAction.Hide
|| (action is ChatRuleAction.Move or ChatRuleAction.Copy && tab.Length > 0);
bool wantsRoute = routes && !routed;
bool wantsLine = mode == ChatColorMode.Line && lineArgb == null;
bool wantsMatch = mode == ChatColorMode.Match;
// Nothing left for it to decide (the test box still shows that it matches).
if (!wantsRoute && !wantsLine && !wantsMatch && trace == null) continue;
if (!rule.WhenMatches(channel, chatType)) continue;
Match m;
long t0 = Stopwatch.GetTimestamp();
try { m = rx.Match(text); }
catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); continue; }
if (!Charge(i, Stopwatch.GetTimestamp() - t0, trace)) continue;
if (!m.Success) continue;
if (_countHits) Interlocked.Increment(ref rule.Hits);
var what = trace != null ? new StringBuilder() : null;
if (wantsRoute)
{
switch (action)
{
case ChatRuleAction.Hide:
hidden = routed = true;
what?.Append("hides it");
break;
case ChatRuleAction.Move:
inHome = false;
routed = true;
AddTab(ref tabs, tab);
what?.Append("moves it to ").Append(tab);
break;
case ChatRuleAction.Copy:
AddTab(ref tabs, tab);
what?.Append("copies it to ").Append(tab);
break;
}
}
else if (routes && trace != null)
what!.Append("(a Move/Hide above already decided the tab)");
if (hidden)
{
trace?.Add(new Step(i, what!.ToString()));
break;
}
if (wantsLine)
{
lineArgb = rule.ColorArgb;
what?.Append(what.Length > 0 ? ", " : "").Append("colours the line");
}
else if (mode == ChatColorMode.Line && trace != null)
what!.Append(what.Length > 0 ? ", " : "").Append("(line colour already set above)");
if (wantsMatch)
{
int n = 0;
long t1 = Stopwatch.GetTimestamp();
try
{
for (; m.Success && n < 16; m = m.NextMatch())
if (m.Length > 0) { (spans ??= new()).Add((m.Index, m.Length, rule.ColorArgb)); n++; }
}
catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); }
if (!rule.Slow) Charge(i, Stopwatch.GetTimestamp() - t1, trace);
what?.Append(what.Length > 0 ? ", " : "").Append(n == 1 ? "colours the match" : $"colours {n} matches");
}
if (what is { Length: 0 }) what.Append("matches, but has nothing to do yet (no tab, no colour)");
trace?.Add(new Step(i, what!.ToString()));
}
bool mention = false;
if (!hidden && _mention != null && ChatModel.MentionEligible(channel, chatType))
{
try
{
Match m = _mention.Match(text);
for (int n = 0; m.Success && n < 8; m = m.NextMatch(), n++)
{
// Your own emote prints as "Tom waves." (type Emote, your name first): that's you, not a mention.
if (m.Index == 0 && chatType == EmoteType && _self.Length > 0
&& string.Equals(m.Value, _self, StringComparison.OrdinalIgnoreCase)) continue;
mention = true;
(spans ??= new()).Add((m.Index, m.Length, MentionArgb));
}
}
catch (RegexMatchTimeoutException) { }
if (mention) trace?.Add(new Step(-1, "mentions you (highlighted)"));
}
if (!hidden && inHome && tabs == null && lineArgb == null && spans == null && !mention)
return ChatRoute.Default;
return new ChatRoute(hidden, inHome, tabs?.ToArray(), lineArgb, Resolve(spans, text.Length), mention);
}
private static void AddTab(ref List<string>? tabs, string tab)
{
tabs ??= new List<string>(2);
foreach (string t in tabs) if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return;
tabs.Add(tab);
}
private static void MarkSlow(ChatFilterRule rule, List<Step>? trace, int index, string why)
{
if (!rule.Slow)
{
rule.Slow = true;
RynthLog.UI($"ChatModel: rule \"{rule.Pattern}\" is too slow ({why}) and is skipped until edited.");
// Lines already routed with it are routed again without it.
ChatModel.BumpFiltersVersion();
}
trace?.Add(new Step(index, "too slow - now skipped until edited"));
}
/// <summary>Overlapping spans: the earlier one (a higher rule) keeps its characters.</summary>
private static ChatSpan[]? Resolve(List<(int Start, int Length, uint Argb)>? spans, int textLength)
{
if (spans == null || spans.Count == 0) return null;
if (spans.Count == 1)
return new[] { new ChatSpan(spans[0].Start, spans[0].Length, spans[0].Argb) };
var owner = new int[textLength]; // 0 = free, else span index + 1
for (int s = 0; s < spans.Count; s++)
{
int end = Math.Min(textLength, spans[s].Start + spans[s].Length);
for (int c = spans[s].Start; c < end; c++)
if (owner[c] == 0) owner[c] = s + 1;
}
var result = new List<ChatSpan>();
for (int c = 0; c < textLength;)
{
int o = owner[c];
int start = c;
while (c < textLength && owner[c] == o) c++;
if (o != 0) result.Add(new ChatSpan(start, c - start, spans[o - 1].Argb));
}
return result.ToArray();
}
}

View file

@ -62,6 +62,8 @@ internal sealed class RynthChatSettingsDto
// 2026-10-08: per-kind line colours (ChatLineColors), { "say": "#RRGGBB", "chan:General": ..., "tab:Chat": ... };
// only the colours the user set, and absent while none is.
[JsonPropertyName("lineColors")] public Dictionary<string, string>? LineColors { get; set; }
// 2026-10-11: how many lines the scrollback keeps (ChatHistory); absent at the default (2000).
[JsonPropertyName("historyLines")] public int? HistoryLines { get; set; }
[JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; }
[JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; }
}

View file

@ -40,6 +40,10 @@ internal sealed class DamageRow
public bool HpEst;
public double Crit; public int CritN; public double NonCrit; public int NonCritN;
public double Casts; public int Kills; public string Key = "";
/// <summary>Every wcid of a row of several kinds (monsters of one name, e.g. retail's five
/// Rampagers), ascending; empty for one kind. Wcid is the one edits and details go to; the
/// plugin applies an edit to all of them.</summary>
public uint[] Wcids = Array.Empty<uint>();
/// <summary>Per-monster (wcid) weapon state, the same on every row of a wcid.</summary>
public uint AssignedWid; public string AssignedWeapon = "";
public uint BestWid; public string BestWeapon = "";
@ -288,6 +292,12 @@ internal sealed unsafe class DamageSource : UiSource<DamageView>
if (e.TryGetProperty("assignedOffName", out var aon)) row.AssignedOffName = aon.GetString() ?? "";
if (e.TryGetProperty("isDefault", out var idf)) row.IsDefault = idf.GetBoolean();
if (e.TryGetProperty("hpEst", out var he)) row.HpEst = he.ValueKind == JsonValueKind.True;
if (e.TryGetProperty("wcids", out var wa) && wa.ValueKind == JsonValueKind.Array)
{
var kinds = new List<uint>();
foreach (var w in wa.EnumerateArray()) if (w.TryGetInt64(out long wl)) kinds.Add((uint)wl);
if (kinds.Count > 1) row.Wcids = kinds.ToArray();
}
if (e.TryGetProperty("pet", out var pc)) row.Pet = pc.GetString() ?? "";
if (e.TryGetProperty("petLabel", out var pl)) row.PetLabel = pl.GetString() ?? "Auto";
if (e.TryGetProperty("weak", out var wk)) row.Weak = wk.GetString() ?? "";

View file

@ -115,6 +115,8 @@ internal sealed class MetaPayload
public MetaApplyResult? ApplyResult { get; set; }
/// <summary>The Meta Manager; null from a RynthAi without it.</summary>
public SchedulePayload? Schedule { get; set; }
/// <summary>Seconds in state and the Watchdog; null from a RynthAi without it.</summary>
public MetaStateSnapshot? Snapshot { get; set; }
/// <summary>Deep copy of the rules; the rest is shared (faces never change it).</summary>
public MetaPayload Clone()
@ -381,19 +383,53 @@ internal static class MetaVocabulary
return states.ToArray();
}
/// <summary>Embedded Nav's route picker: nav files, then "[emb] key" for embedded routes.</summary>
public static string[] RoutePicks(MetaPayload d)
/// <summary>Embedded Nav Route's "Patrol": RynthAi's dungeon patrol (/ra dunnav-patrol) when the
/// meta and NavProfiles have no route by that name (RynthAi MetaManager.IsPatrolRoute).</summary>
public const string PatrolRoute = "Patrol";
/// <summary>A route of the meta or NavProfiles called <paramref name="name"/> (any case).</summary>
public static bool HasRoute(MetaPayload d, string name)
{
var routes = new List<string>();
foreach (string n in d.NavFiles) if (n != "None") routes.Add(n);
foreach (string k in d.EmbeddedNavKeys) if (!routes.Contains(k)) routes.Add($"[emb] {k}");
return routes.ToArray();
foreach (string n in d.NavFiles) if (string.Equals(n, name, StringComparison.OrdinalIgnoreCase)) return true;
foreach (string k in d.EmbeddedNavKeys) if (string.Equals(k, name, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>Nav names for source completion (nav files and embedded keys, no duplicates).</summary>
/// <summary>
/// Embedded Nav Route's picker: Patrol (the dungeon patrol) first, nav files, then the meta's own
/// routes. Labels are what the list shows ("[emb] key" for embedded routes); values are what the
/// rule stores, the name RynthAi looks up (2026-10-11: the label was stored, so an embedded route
/// picked here was "Route missing").
/// </summary>
public static (string[] Labels, string[] Values) RoutePicks(MetaPayload d)
{
var labels = new List<string>();
var values = new List<string>();
if (!HasRoute(d, PatrolRoute))
{
labels.Add(PatrolRoute + " (dungeon patrol, no nav file)");
values.Add(PatrolRoute);
}
foreach (string n in d.NavFiles)
{
if (n == "None") continue;
labels.Add(n);
values.Add(n);
}
foreach (string k in d.EmbeddedNavKeys)
{
if (values.Contains(k)) continue;
labels.Add($"[emb] {k}");
values.Add(k);
}
return (labels.ToArray(), values.ToArray());
}
/// <summary>Nav names for source completion (Patrol, nav files and embedded keys, no duplicates).</summary>
public static IReadOnlyList<string> CompletionNavs(MetaPayload d)
{
var combined = new List<string>(d.NavFiles.Count + d.EmbeddedNavKeys.Count);
var combined = new List<string>(d.NavFiles.Count + d.EmbeddedNavKeys.Count + 1);
if (!HasRoute(d, PatrolRoute)) combined.Add(PatrolRoute);
combined.AddRange(d.NavFiles);
foreach (string n in d.EmbeddedNavKeys) if (!combined.Contains(n)) combined.Add(n);
return combined;

View file

@ -141,9 +141,21 @@ internal static class MetaRuleEdit
/// STATE: block per state that has rules), so this rule is what keeps an empty state.</summary>
public static MetaRuleDto Placeholder(string state) => new() { State = state, Condition = Never, Action = NoAction };
/// <summary>The longest rule name the editor takes.</summary>
public const int MaxNameLength = 80;
/// <summary>A typed rule name: one line (RynthAi writes it as a "~~ @name" comment line), no longer
/// than <see cref="MaxNameLength"/>. The editor trims the ends when it sends the rule.</summary>
public static string CleanName(string? typed)
{
if (string.IsNullOrEmpty(typed)) return string.Empty;
string s = typed.Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ');
return s.Length > MaxNameLength ? s.Substring(0, MaxNameLength) : s;
}
public static bool IsPlaceholder(MetaRuleDto r) =>
r.Condition == Never && r.Action == NoAction && r.ConditionData.Length == 0 && r.ActionData.Length == 0
&& r.Children.Count == 0 && r.ActionChildren.Count == 0;
&& r.Children.Count == 0 && r.ActionChildren.Count == 0 && r.Name.Length == 0;
/// <summary>False for conditions with nothing to type: Never, Always, Character Death, Any Vendor Open,
/// Vendor Closed, Need To Buff, Portalspace Entered / Exited, Navroute Empty (and the composites).</summary>
@ -227,11 +239,11 @@ internal static class MetaRuleEdit
r.ActionChildren.Add(new MetaRuleDto { State = r.State, Action = NoAction });
}
/// <summary>Same state, condition, action, data, enabled flag and children (not LastFiredMs).</summary>
/// <summary>Same state, name, condition, action, data, enabled flag and children (not LastFiredMs).</summary>
public static bool SameContent(MetaRuleDto a, MetaRuleDto b)
{
if (!string.Equals(a.State, b.State, StringComparison.Ordinal) || a.Condition != b.Condition || a.Action != b.Action
|| a.Enabled != b.Enabled
|| a.Enabled != b.Enabled || !string.Equals(a.Name, b.Name, StringComparison.Ordinal)
|| !string.Equals(a.ConditionData, b.ConditionData, StringComparison.Ordinal)
|| !string.Equals(a.ActionData, b.ActionData, StringComparison.Ordinal)
|| a.Children.Count != b.Children.Count || a.ActionChildren.Count != b.ActionChildren.Count)

View file

@ -0,0 +1,486 @@
// ============================================================================
// RynthCore.Engine - UI/Data/MetaRowText.cs
// How the Meta panel's rule list reads a rule (2026-10-11 readability pass):
// words in one colour, the values you typed in another, state names in the
// state headers' amber, and a problem (an empty chat command, a Set State to
// a state that doesn't exist) in red.
//
// Count Prismatic Taper ≤ 50 (was "Inventory Item Count <=: Prismatic Taper, 50")
// Expr getcharintprop[25]<30
// and not Spell 512 ≥ 305 s left (an All of two: one line each, joined by "and")
// /vt opt set enablecombat true (a DoAll: one line per action, in order)
// → ReBuff
//
// Full form: a list of lines (nested All / Any indent under an "and any of"
// line). Compact form: one line ("a and (b or c)", actions joined by " · ").
// An All or Any of one condition is just that condition, as RynthAi runs it.
//
// No ImGui here (tools/MetaEditTests compiles this file): MetaFace turns
// tones into colours and draws the lines.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Engine.UI.Data;
/// <summary>What a piece of rule text is, for its colour.</summary>
internal enum MetaTone : byte
{
/// <summary>Words: "Count", "Spell", "s left".</summary>
Label,
/// <summary>What was typed: an item name, a number, a chat command.</summary>
Value,
/// <summary>A state name (Set / Call Meta State, Watchdog).</summary>
State,
/// <summary>An expression or regex.</summary>
Code,
/// <summary>"and" / "or" / "not".</summary>
Join,
/// <summary>Never, None, "(nothing)".</summary>
Dim,
/// <summary>Something that won't work as written: "(empty)", a missing state.</summary>
Warn,
}
internal readonly struct MetaSeg
{
public readonly string Text;
public readonly MetaTone Tone;
public MetaSeg(string text, MetaTone tone) { Text = text; Tone = tone; }
public override string ToString() => Text;
}
/// <summary>One line of a rule's condition or action column (full form).</summary>
internal sealed class MetaLine
{
/// <summary>Nesting: the line starts this many slots in (a guide line is drawn in each).</summary>
public int Depth;
/// <summary>The line is an item of an and / or list: <see cref="Join"/> sits in a slot before it,
/// so the items' text lines up whether or not they have a join word.</summary>
public bool Slot;
/// <summary>"and" / "or" on a list's second and later items; "" otherwise.</summary>
public string Join = string.Empty;
public MetaSeg[] Segs = Array.Empty<MetaSeg>();
public string Plain()
{
var sb = new StringBuilder();
if (Join.Length > 0) sb.Append(Join).Append(' ');
foreach (MetaSeg s in Segs) sb.Append(s.Text);
return sb.ToString();
}
}
/// <summary>What the text needs from outside: spell names, which states exist.</summary>
internal sealed class MetaTextContext
{
/// <summary>A spell's name, or null when unknown (the spell table may still be loading).</summary>
public Func<uint, string?>? SpellName;
/// <summary>The meta's states (any case); null skips the missing-state check.</summary>
public ICollection<string>? States;
/// <summary>True when the meta or NavProfiles has a route of this name (then "Patrol" is that
/// route, not the dungeon patrol); null: no route is called Patrol.</summary>
public Func<string, bool>? RouteExists;
/// <summary>Set when a spell id was shown as a number for want of a name.</summary>
public bool MissedSpellName;
public bool StateExists(string s)
{
if (States == null) return true;
foreach (string x in States)
if (string.Equals(x, s, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
}
internal static class MetaRowText
{
public const int All = 2, Any = 3, Not = 20, DoAll = 4;
private const int MaxLevels = 8; // the editor nests 4; a hand-written file could go deeper
public const string Le = "≤", Ge = "≥", Arrow = "→", Dot = "·";
// =====================================================================
// Conditions
// =====================================================================
/// <summary>The condition column's lines. An All / Any of two or more at the top lists its
/// conditions one per line, the second and later ones starting "and" / "or".</summary>
public static MetaLine[] ConditionLines(MetaRuleDto rule, MetaTextContext ctx)
{
var lines = new List<MetaLine>();
Cond(rule, 0, slot: false, join: "", lead: null, lines, ctx, 0);
return lines.ToArray();
}
// c's lines. depth/slot/join place its first line (an item of the parent's list gets the slot);
// lead goes before its text on that line ("not ").
private static void Cond(MetaRuleDto c, int depth, bool slot, string join, List<MetaSeg>? lead,
List<MetaLine> lines, MetaTextContext ctx, int level)
{
if (level > MaxLevels)
{
lines.Add(Line(depth, slot, join, lead, new MetaSeg("…", MetaTone.Dim)));
return;
}
if (c.Condition is All or Any)
{
List<MetaRuleDto> kids = c.Children;
string what = c.Condition == All ? "all of" : "any of";
if (kids.Count == 0)
{
lines.Add(Line(depth, slot, join, lead, new MetaSeg(what, MetaTone.Label), new MetaSeg(" (nothing)", MetaTone.Warn)));
return;
}
if (kids.Count == 1)
{
Cond(kids[0], depth, slot, join, lead, lines, ctx, level + 1); // the same as the one condition
return;
}
string word = c.Condition == All ? "and" : "or";
int kidDepth = depth;
if (slot || lead != null)
{
// An item of a list, or after "not": an "all of" / "any of" line, the conditions under it.
lines.Add(Line(depth, slot, join, lead, new MetaSeg(what, MetaTone.Label)));
kidDepth = depth + 1;
}
for (int i = 0; i < kids.Count; i++)
Cond(kids[i], kidDepth, slot: true, join: i == 0 ? "" : word, lead: null, lines, ctx, level + 1);
return;
}
if (c.Condition == Not)
{
var notLead = new List<MetaSeg>();
if (lead != null) notLead.AddRange(lead);
notLead.Add(new MetaSeg("not ", MetaTone.Join));
if (c.Children.Count == 0)
{
notLead.Add(new MetaSeg("(nothing)", MetaTone.Warn));
lines.Add(Line(depth, slot, join, notLead));
return;
}
Cond(c.Children[0], depth, slot, join, notLead, lines, ctx, level + 1);
return;
}
lines.Add(Line(depth, slot, join, lead, Leaf(c, ctx)));
}
/// <summary>The condition on one line: "a and (b or c)", "not (a and b)".</summary>
public static MetaSeg[] ConditionCompact(MetaRuleDto rule, MetaTextContext ctx)
{
var segs = new List<MetaSeg>();
CondCompact(rule, segs, nested: false, ctx, 0);
return segs.ToArray();
}
private static void CondCompact(MetaRuleDto c, List<MetaSeg> o, bool nested, MetaTextContext ctx, int level)
{
if (level > MaxLevels) { o.Add(new MetaSeg("…", MetaTone.Dim)); return; }
if (c.Condition is All or Any)
{
List<MetaRuleDto> kids = c.Children;
if (kids.Count == 0)
{
o.Add(new MetaSeg(c.Condition == All ? "all of" : "any of", MetaTone.Label));
o.Add(new MetaSeg(" (nothing)", MetaTone.Warn));
return;
}
if (kids.Count == 1) { CondCompact(kids[0], o, nested, ctx, level + 1); return; }
string word = c.Condition == All ? " and " : " or ";
if (nested) o.Add(new MetaSeg("(", MetaTone.Join));
for (int i = 0; i < kids.Count; i++)
{
if (i > 0) o.Add(new MetaSeg(word, MetaTone.Join));
CondCompact(kids[i], o, nested: true, ctx, level + 1);
}
if (nested) o.Add(new MetaSeg(")", MetaTone.Join));
return;
}
if (c.Condition == Not)
{
o.Add(new MetaSeg("not ", MetaTone.Join));
if (c.Children.Count == 0) o.Add(new MetaSeg("(nothing)", MetaTone.Warn));
else CondCompact(c.Children[0], o, nested: true, ctx, level + 1);
return;
}
o.AddRange(Leaf(c, ctx));
}
/// <summary>One plain condition (not All / Any / Not).</summary>
public static MetaSeg[] Leaf(MetaRuleDto c, MetaTextContext ctx)
{
string d = (c.ConditionData ?? string.Empty).Trim();
switch (c.Condition)
{
case 0: return One("Never", MetaTone.Dim);
case 1: return One("Always", MetaTone.Label);
case 4: return Typed("Chat matches ", d, MetaTone.Code);
case 27: return Typed("Chat captures ", d, MetaTone.Code);
case 26: return Typed("Expr ", d, MetaTone.Code);
case 5: return Typed("Free pack slots " + Le + " ", d, MetaTone.Value);
case 6: return Seconds("In state " + Ge + " ", d);
case 21: return Seconds("In state (P) " + Ge + " ", d);
case 7: return One("Character death", MetaTone.Label);
case 8: return One("Vendor open", MetaTone.Label);
case 9: return One("Vendor closed", MetaTone.Label);
case 10: return ItemCount(d, Le);
case 11: return ItemCount(d, Ge);
case 12: return MobsNamed(d);
case 13: return PriorityMobs(d);
case 14: return One("Need to buff", MetaTone.Label);
case 15:
return d.Length == 0
? new[] { new MetaSeg("No mobs within ", MetaTone.Label), new MetaSeg("20", MetaTone.Value), new MetaSeg(" (default)", MetaTone.Dim) }
: new[] { new MetaSeg("No mobs within ", MetaTone.Label), new MetaSeg(d, MetaTone.Value) };
case 16: return Typed("Landblock ", d.ToUpperInvariant(), MetaTone.Value);
case 17: return Typed("Landcell ", d.ToUpperInvariant(), MetaTone.Value);
case 18: return One("Entered portal space", MetaTone.Label);
case 19: return One("Left portal space", MetaTone.Label);
case 22: return SpellLeft(d, Ge, ctx);
case 23: return SpellLeft(d, Le, ctx);
case 24: return Unit("Burden " + Ge + " ", d, "%");
case 25: return Typed("Off route " + Ge + " ", d, MetaTone.Value);
case 28: return One("Nav route empty", MetaTone.Label);
case 29: return Typed("Health " + Le + " ", d, MetaTone.Value);
case 30: return Unit("Health " + Ge + " ", d, "%");
case 31: return Typed("Mana " + Le + " ", d, MetaTone.Value);
case 32: return Unit("Mana " + Ge + " ", d, "%");
case 33: return Typed("Stamina " + Le + " ", d, MetaTone.Value);
case 34: return Unit("Vitae " + Ge + " ", d, "%");
case 35: return Unit("No kill for ", d, " min");
default:
// A condition this engine doesn't know yet (a newer RynthAi): its number and data.
string name = "Condition " + c.Condition.ToString(CultureInfo.InvariantCulture);
return d.Length == 0 ? One(name, MetaTone.Label)
: new[] { new MetaSeg(name + " ", MetaTone.Label), new MetaSeg(d, MetaTone.Value) };
}
}
// "Count Prismatic Taper ≤ 50" from "Prismatic Taper,50" (the count after the last comma).
private static MetaSeg[] ItemCount(string d, string op)
{
int comma = d.LastIndexOf(',');
if (comma < 0) return Typed("Count ", d, MetaTone.Value);
string name = d.Substring(0, comma).Trim(), count = d.Substring(comma + 1).Trim();
return new[]
{
new MetaSeg("Count ", MetaTone.Label), Val(name), new MetaSeg(" " + op + " ", MetaTone.Label), Val(count),
};
}
// "Mobs Drudge ≥ 3 within 20" from "Drudge,20,3" (name regex, distance, count; the regex may hold commas).
private static MetaSeg[] MobsNamed(string d)
{
int c2 = d.LastIndexOf(',');
int c1 = c2 > 0 ? d.LastIndexOf(',', c2 - 1) : -1;
if (c1 < 0) return Typed("Mobs named ", d, MetaTone.Code);
string name = d.Substring(0, c1).Trim(), dist = d.Substring(c1 + 1, c2 - c1 - 1).Trim(), count = d.Substring(c2 + 1).Trim();
return new[]
{
new MetaSeg("Mobs ", MetaTone.Label), new MetaSeg(name.Length == 0 ? "(any name)" : name, name.Length == 0 ? MetaTone.Warn : MetaTone.Code),
new MetaSeg(" " + Ge + " ", MetaTone.Label), Val(count), new MetaSeg(" within ", MetaTone.Label), Val(dist),
};
}
// "Priority mobs ≥ 1 within 20" from "1,20" (count, distance).
private static MetaSeg[] PriorityMobs(string d)
{
int comma = d.IndexOf(',');
if (comma < 0) return Typed("Priority mobs ", d, MetaTone.Value);
return new[]
{
new MetaSeg("Priority mobs " + Ge + " ", MetaTone.Label), Val(d.Substring(0, comma).Trim()),
new MetaSeg(" within ", MetaTone.Label), Val(d.Substring(comma + 1).Trim()),
};
}
// "Spell Strength Other VI ≥ 300 s left" from "2293,300" (spell id, seconds).
private static MetaSeg[] SpellLeft(string d, string op, MetaTextContext ctx)
{
int comma = d.IndexOf(',');
string id = (comma < 0 ? d : d.Substring(0, comma)).Trim();
string secs = comma < 0 ? "" : d.Substring(comma + 1).Trim();
string shown = id;
if (uint.TryParse(id, NumberStyles.None, CultureInfo.InvariantCulture, out uint sid))
{
string? name = ctx.SpellName?.Invoke(sid);
if (!string.IsNullOrEmpty(name)) shown = name;
else ctx.MissedSpellName = true;
}
return new[]
{
new MetaSeg("Spell ", MetaTone.Label), id.Length == 0 ? new MetaSeg("(not set)", MetaTone.Warn) : Val(shown),
new MetaSeg(" " + op + " ", MetaTone.Label), Val(secs), new MetaSeg(" s left", MetaTone.Label),
};
}
private static MetaSeg[] Seconds(string label, string d) => Unit(label, d, " s");
private static MetaSeg[] Unit(string label, string d, string unit) =>
d.Length == 0
? new[] { new MetaSeg(label, MetaTone.Label), new MetaSeg("(not set)", MetaTone.Warn) }
: new[] { new MetaSeg(label, MetaTone.Label), Val(d), new MetaSeg(unit, MetaTone.Label) };
// =====================================================================
// Actions
// =====================================================================
/// <summary>The action column's lines: one per action, a DoAll's in order.</summary>
public static MetaLine[] ActionLines(MetaRuleDto rule, MetaTextContext ctx)
{
var lines = new List<MetaLine>();
Act(rule, lines, ctx, 0);
return lines.ToArray();
}
private static void Act(MetaRuleDto a, List<MetaLine> lines, MetaTextContext ctx, int level)
{
if (a.Action == DoAll && level <= MaxLevels)
{
if (a.ActionChildren.Count == 0)
{
lines.Add(Line(0, false, "", null, new MetaSeg("do all", MetaTone.Label), new MetaSeg(" (nothing)", MetaTone.Warn)));
return;
}
foreach (MetaRuleDto kid in a.ActionChildren) Act(kid, lines, ctx, level + 1);
return;
}
lines.Add(Line(0, false, "", null, ActionLeaf(a, ctx)));
}
/// <summary>The actions on one line, joined by " · ".</summary>
public static MetaSeg[] ActionCompact(MetaRuleDto rule, MetaTextContext ctx)
{
var segs = new List<MetaSeg>();
foreach (MetaLine line in ActionLines(rule, ctx))
{
if (segs.Count > 0) segs.Add(new MetaSeg(" " + Dot + " ", MetaTone.Dim));
segs.AddRange(line.Segs);
}
return segs.ToArray();
}
/// <summary>One action (not DoAll).</summary>
public static MetaSeg[] ActionLeaf(MetaRuleDto a, MetaTextContext ctx)
{
string d = (a.ActionData ?? string.Empty).Trim();
switch (a.Action)
{
case 0: return d.Length == 0 ? One("None", MetaTone.Dim) : Typed("None ", d, MetaTone.Value);
case 1:
// A command reads as itself ("/vt opt set ..."); plain text is said in chat.
if (d.Length == 0) return new[] { new MetaSeg("Chat ", MetaTone.Label), new MetaSeg("(empty)", MetaTone.Warn) };
return d.StartsWith('/') ? new[] { Val(d) } : new[] { new MetaSeg("Chat ", MetaTone.Label), Val(d) };
case 2: return StateRef(Arrow + " ", d, ctx);
case 5: return StateRef("Call " + Arrow + " ", d, ctx);
case 6: return One("Return from call", MetaTone.Label);
case 3:
{
int semi = d.IndexOf(';');
string route = semi >= 0 ? d.Substring(0, semi).Trim() : d;
// "Patrol" with no route of that name: RynthAi's dungeon patrol (/ra dunnav-patrol).
if (string.Equals(route, "Patrol", StringComparison.OrdinalIgnoreCase) && ctx.RouteExists?.Invoke(route) != true)
return new[] { new MetaSeg("Nav ", MetaTone.Label), new MetaSeg(route, MetaTone.Value), new MetaSeg(" (dungeon patrol)", MetaTone.Dim) };
return Typed("Nav ", route, MetaTone.Value);
}
case 7: return Typed("Expr ", d, MetaTone.Code);
case 8: return Typed("Chat expr ", d, MetaTone.Code);
case 9: return Watchdog(d, ctx);
case 10: return One("Clear watchdog", MetaTone.Label);
case 11:
{
// "variable;option" (RynthAi keeps metaf's GetOpt {Option} {Variable} as variable;option).
int semi = d.IndexOf(';');
if (semi < 0) return Typed("Get option ", d, MetaTone.Value);
return new[]
{
new MetaSeg("Get option ", MetaTone.Label), Val(d.Substring(semi + 1).Trim()),
new MetaSeg(" " + Arrow + " ", MetaTone.Label), new MetaSeg(d.Substring(0, semi).Trim(), MetaTone.Code),
};
}
case 12:
{
int semi = d.IndexOf(';');
if (semi < 0) return Typed("Set option ", d, MetaTone.Value);
return new[]
{
new MetaSeg("Set ", MetaTone.Label), Val(d.Substring(0, semi).Trim()),
new MetaSeg(" = ", MetaTone.Label), Val(d.Substring(semi + 1).Trim()),
};
}
case 13:
{
int semi = d.IndexOf(';');
return Typed("Create view ", semi >= 0 ? d.Substring(0, semi).Trim() : d, MetaTone.Value);
}
case 14: return Typed("Destroy view ", d, MetaTone.Value);
case 15: return One("Destroy all views", MetaTone.Label);
default:
string name = "Action " + a.Action.ToString(CultureInfo.InvariantCulture);
return d.Length == 0 ? One(name, MetaTone.Label)
: new[] { new MetaSeg(name + " ", MetaTone.Label), new MetaSeg(d, MetaTone.Value) };
}
}
private static MetaSeg[] StateRef(string label, string state, MetaTextContext ctx)
{
if (state.Length == 0) return new[] { new MetaSeg(label, MetaTone.Label), new MetaSeg("(no state)", MetaTone.Warn) };
if (!ctx.StateExists(state))
return new[] { new MetaSeg(label, MetaTone.Label), new MetaSeg(state, MetaTone.Warn), new MetaSeg(" (no such state)", MetaTone.Warn) };
return new[] { new MetaSeg(label, MetaTone.Label), new MetaSeg(state, MetaTone.State) };
}
// "Watchdog 5 m in 30 s → Default" from "Default;5;30" (state; meters; seconds): if you haven't
// moved that far in that long, the meta goes to the state.
private static MetaSeg[] Watchdog(string d, MetaTextContext ctx)
{
string[] p = d.Split(';');
if (p.Length < 3) return Typed("Watchdog ", d, MetaTone.Value);
var segs = new List<MetaSeg>
{
new("Watchdog ", MetaTone.Label), Val(p[1].Trim()), new(" m in ", MetaTone.Label), Val(p[2].Trim()), new(" s ", MetaTone.Label),
};
segs.AddRange(StateRef(Arrow + " ", p[0].Trim(), ctx));
return segs.ToArray();
}
// =====================================================================
// Helpers
// =====================================================================
/// <summary>The text of segments, for search and tooltips.</summary>
public static string Plain(MetaSeg[] segs)
{
var sb = new StringBuilder();
foreach (MetaSeg s in segs) sb.Append(s.Text);
return sb.ToString();
}
private static MetaSeg Val(string text) =>
text.Length == 0 ? new MetaSeg("(not set)", MetaTone.Warn) : new MetaSeg(text, MetaTone.Value);
private static MetaSeg[] One(string text, MetaTone tone) => new[] { new MetaSeg(text, tone) };
// "Label value"; an empty value shows "(not set)".
private static MetaSeg[] Typed(string label, string value, MetaTone tone) =>
new[] { new MetaSeg(label, MetaTone.Label), value.Length == 0 ? new MetaSeg("(not set)", MetaTone.Warn) : new MetaSeg(value, tone) };
private static MetaLine Line(int depth, bool slot, string join, List<MetaSeg>? lead, params MetaSeg[] segs)
{
MetaSeg[] all = segs;
if (lead != null && lead.Count > 0)
{
all = new MetaSeg[lead.Count + segs.Length];
lead.CopyTo(all, 0);
segs.CopyTo(all, lead.Count);
}
return new MetaLine { Depth = depth, Slot = slot, Join = join, Segs = all };
}
private static MetaLine Line(int depth, bool slot, string join, List<MetaSeg> lead) =>
new() { Depth = depth, Slot = slot, Join = join, Segs = lead.ToArray() };
}

View file

@ -20,6 +20,10 @@ internal sealed class MetaRuleDto
public List<MetaRuleDto> Children { get; set; } = new();
public List<MetaRuleDto> ActionChildren { get; set; } = new();
public bool Enabled { get; set; } = true;
/// <summary>A name to find the rule by (top-level rules; "" = none). RynthAi saves it in .af as a
/// "~~ @name ..." line; one without rule names leaves it out of the snapshot ("").</summary>
public string Name { get => _name; set => _name = value ?? string.Empty; } // a JSON null is ""
private string _name = string.Empty;
public long LastFiredMs { get; set; } = 99999;
public MetaRuleDto Clone()
@ -27,7 +31,7 @@ internal sealed class MetaRuleDto
var r = new MetaRuleDto
{
State = State, Condition = Condition, ConditionData = ConditionData,
Action = Action, ActionData = ActionData, Enabled = Enabled, LastFiredMs = LastFiredMs,
Action = Action, ActionData = ActionData, Enabled = Enabled, Name = Name, LastFiredMs = LastFiredMs,
};
foreach (MetaRuleDto c in Children) r.Children.Add(c.Clone());
foreach (MetaRuleDto a in ActionChildren) r.ActionChildren.Add(a.Clone());

View file

@ -0,0 +1,67 @@
// ============================================================================
// RynthCore.Engine - UI/Data/MetaStateClock.cs
// The Meta panel's timers (2026-10-11): how long the meta has been in its
// current state, and the Watchdog's countdown, from RynthAi's state-machine
// snapshot ("snapshot" in RynthPluginGetMetaJson), counted on between
// snapshots. No ImGui: tools/MetaEditTests compiles this file.
// ============================================================================
using System;
namespace RynthCore.Engine.UI.Data;
/// <summary>RynthAi's meta state machine as of the snapshot ("snapshot"): how long the current state
/// has run, and the Watchdog. Read-only for the faces.</summary>
internal sealed class MetaStateSnapshot
{
public double SecondsInState { get; set; }
public bool WatchdogActive { get; set; }
public string WatchdogState { get; set; } = string.Empty;
public double WatchdogSecondsRemaining { get; set; }
}
/// <summary>
/// Seconds in the current state and the Watchdog's countdown between snapshots (they come every
/// couple of seconds): counted on from the last one, so the Meta panel's timers tick each second.
/// A state picked in the panel starts at 0 until the next snapshot says otherwise.
/// </summary>
internal sealed class MetaStateClock
{
private MetaStateSnapshot? _last;
private long _atMs;
public bool Known => _last != null;
public void Snapshot(MetaStateSnapshot? snap, long nowMs)
{
_last = snap;
_atMs = nowMs;
}
/// <summary>The panel set the state: its clock starts again.</summary>
public void StateSet(long nowMs)
{
if (_last == null) return;
_last = new MetaStateSnapshot { SecondsInState = 0 };
_atMs = nowMs;
}
public double SecondsInState(long nowMs) =>
_last == null ? 0 : _last.SecondsInState + Math.Max(0, nowMs - _atMs) / 1000.0;
/// <summary>Seconds until the Watchdog fires (its state in <paramref name="state"/>); -1 when none is set.</summary>
public double WatchdogLeft(long nowMs, out string state)
{
state = _last?.WatchdogState ?? string.Empty;
if (_last == null || !_last.WatchdogActive) return -1;
return Math.Max(0, _last.WatchdogSecondsRemaining - Math.Max(0, nowMs - _atMs) / 1000.0);
}
/// <summary>"42 s" under an hour (rules count seconds: "In state >= 300 s"), else "1:02:03".</summary>
public static string Format(double seconds)
{
long s = (long)Math.Max(0, seconds);
if (s < 3600) return s.ToString(System.Globalization.CultureInfo.InvariantCulture) + " s";
return string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{s / 3600}:{s / 60 % 60:00}:{s % 60:00}");
}
}

View file

@ -526,6 +526,12 @@ internal static class SettingsSchema
"While the 3D world isn't drawn the client runs at most this many frames a second, so the\n" +
"saved time is slept (0 = no extra cap). Saved for this PC. Also: /rc video fps <n>.",
when: _ => D3D9.VideoPatch.Mode != D3D9.VideoPatchMode.Off),
// Stored in engine.json for every client (EngineSettings), not in the RynthAi profile.
Bool("Close Client on Server Disconnect", _ => Plugins.EngineSettings.CloseOnServerDisconnect,
(_, v) => Plugins.EngineSettings.CloseOnServerDisconnect = v,
"On (default): when the game shows \"The server has disconnected\" (only a Quit Game button),\n" +
"the client closes itself 5 seconds later, so the launcher's auto-relaunch can start it again.\n" +
"A logout or a quit never shows that screen. Applies to all your clients; others pick it up when they start."),
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."),

View file

@ -61,6 +61,12 @@ internal static class ItemsPanel
[JsonPropertyName("manaTapMinMana")] public int ManaTapMinMana { get; set; } = 2500;
[JsonPropertyName("manaStoneKeepCount")]public int ManaStoneKeepCount{ get; set; } = 5;
[JsonPropertyName("currentTargetName")] public string CurrentTargetName { get; set; } = string.Empty;
/// <summary>
/// Listed weapons the character no longer carries (not in the pack, not wielded), by id
/// (RynthAi from 2026-10-11; empty from older plugins). Display only: RynthAi ignores
/// it when the payload is saved back.
/// </summary>
[JsonPropertyName("missingIds")] public List<int> MissingIds { get; set; } = new();
}
internal sealed class WeaponEntry

View file

@ -409,11 +409,17 @@ internal static class RynthChatPanel
{
ClearSelectionState();
chatStack.Children.Clear();
foreach (var line in CurrentLines())
// The newest 500 shown lines, as AppendLine trims to: the history can be 10,000
// lines since 2026-10-11 (ChatHistory), far too many TextBlocks. ImGui's face shows all.
var lines = CurrentLines();
int from = lines.Length;
for (int shown = 0; from > 0 && shown < 500; )
if (ChatModel.LineVisible(lines[--from], activeTab, searchFilter)) shown++;
if (lines.Length > 0) lastShownId = lines[^1].Id;
for (int i = from; i < lines.Length; i++)
{
lastShownId = line.Id;
if (!ChatModel.LineVisible(line, activeTab, searchFilter)) continue;
chatStack.Children.Add(MakeTextBlock(line));
if (!ChatModel.LineVisible(lines[i], activeTab, searchFilter)) continue;
chatStack.Children.Add(MakeTextBlock(lines[i]));
}
// A full rebuild (tab/filter/font change) re-pins to the newest line.
if (autoScrollCheck.IsChecked == true)

View file

@ -196,7 +196,13 @@ internal static class WindowFlags
public const uint HasError = 1u << 9;
/// <summary>RequestPos is a FirstUseEver default position (used only when nothing is saved).</summary>
public const uint PosIsDefault = 1u << 10;
public const uint Known = (1u << 11) - 1;
/// <summary>
/// With ShowInBar: the window gets a button of its own on the bar (icon, tooltip = title)
/// instead of a line in the Scripts menu. For plugin windows; engines before 2026-10-11
/// mask it off and list the window in the Scripts menu as before.
/// </summary>
public const uint BarButton = 1u << 11;
public const uint Known = (1u << 12) - 1;
}
internal static class DisplayListParser

View file

@ -460,15 +460,27 @@ internal static class ScriptWindowRegistry
private static readonly Dictionary<string, ScriptWindow> ByPanelKey = new(StringComparer.OrdinalIgnoreCase);
private static long _lastRejectLogTicks;
// The bar's Scripts menu: a copy-on-write snapshot of the ShowInBar windows, republished
// (under Sync) when the window set, a title or a ShowInBar flag changed. AC's thread
// reads it without taking Sync.
// The bar's Scripts menu and the windows with a bar button of their own: copy-on-write
// snapshots of the ShowInBar windows, republished (under Sync) when the window set, a
// title or a ShowInBar/BarButton flag changed. AC's thread reads them without taking Sync.
private static ScriptBarItem[] _barItems = Array.Empty<ScriptBarItem>();
private static ScriptBarItem[] _barButtons = Array.Empty<ScriptBarItem>();
private static bool _barDirty;
/// <summary>The Scripts menu's items, grouped (empty = no Scripts button). Any thread.</summary>
public static ScriptBarItem[] BarItems => Volatile.Read(ref _barItems);
/// <summary>
/// The windows that asked for a bar button of their own (ShowInBar + BarButton), sorted
/// like the menu. A new array whenever the set or a title changes, so the bar can compare
/// references to know when to rebuild its buttons. Any thread.
/// </summary>
public static ScriptBarItem[] BarButtons => Volatile.Read(ref _barButtons);
/// <summary>True when a window with these flags gets a bar button of its own (not a Scripts menu line).</summary>
public static bool HasOwnBarButton(uint flags) =>
(flags & (WindowFlags.ShowInBar | WindowFlags.BarButton)) == (WindowFlags.ShowInBar | WindowFlags.BarButton);
// ── Host functions ───────────────────────────────────────────────────
/// <summary>UiSubmit: the owner's complete window set. Pump thread, inside the owner's dispatch.</summary>
@ -629,28 +641,36 @@ internal static class ScriptWindowRegistry
ByPanelKey.Clear();
_barDirty = false;
Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>());
Volatile.Write(ref _barButtons, Array.Empty<ScriptBarItem>());
}
}
/// <summary>Rebuilds the Scripts menu snapshot when something it shows changed. Caller holds Sync.</summary>
/// <summary>
/// Rebuilds the Scripts menu and bar button snapshots when something they show changed.
/// A ShowInBar window goes in the menu, or on a button of its own with BarButton set.
/// Caller holds Sync.
/// </summary>
private static void PublishBarLocked()
{
if (!_barDirty) return;
_barDirty = false;
var rows = new List<(string Group, ScriptWindow W)>();
var menu = new List<(string Group, ScriptWindow W)>();
var buttons = new List<(string Group, ScriptWindow W)>();
foreach (ScriptWindowOwner o in Owners.Values)
foreach (ScriptWindow w in o.Windows.Values)
{
if ((w.Flags & WindowFlags.ShowInBar) == 0) continue;
int slash = w.Key.LastIndexOf('/');
string group = slash > 0 ? w.Key[..slash] : o.Plugin.DisplayName;
rows.Add((group, w));
(HasOwnBarButton(w.Flags) ? buttons : menu).Add((group, w));
}
if (rows.Count == 0)
{
Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>());
return;
}
Volatile.Write(ref _barItems, Snapshot(menu));
Volatile.Write(ref _barButtons, Snapshot(buttons));
}
private static ScriptBarItem[] Snapshot(List<(string Group, ScriptWindow W)> rows)
{
if (rows.Count == 0) return Array.Empty<ScriptBarItem>();
rows.Sort(static (a, b) =>
{
int c = string.Compare(a.Group, b.Group, StringComparison.OrdinalIgnoreCase);
@ -662,7 +682,7 @@ internal static class ScriptWindowRegistry
for (int i = 0; i < rows.Count; i++)
items[i] = new ScriptBarItem(rows[i].W, rows[i].Group,
groupStart: i == 0 || !string.Equals(rows[i].Group, rows[i - 1].Group, StringComparison.Ordinal));
Volatile.Write(ref _barItems, items);
return items;
}
// ── Windows ──────────────────────────────────────────────────────────
@ -677,7 +697,7 @@ internal static class ScriptWindowRegistry
bool specChanged = isNew || ((w.Flags ^ pw.Flags) & SpecFlags) != 0
|| w.DefaultSize != pw.DefaultSize || w.MinSize != pw.MinSize || w.DefaultPos != defaultPos;
bool titleChanged = w.Title != pw.Title;
if (isNew || titleChanged || ((w.Flags ^ pw.Flags) & WindowFlags.ShowInBar) != 0)
if (isNew || titleChanged || ((w.Flags ^ pw.Flags) & (WindowFlags.ShowInBar | WindowFlags.BarButton)) != 0)
_barDirty = true;
w.Flags = pw.Flags;
w.Title = pw.Title;
@ -862,7 +882,7 @@ internal static class ScriptWindowRegistry
+ $" flags=0x{w.Flags:X3}({DescribeFlags(w.Flags)}) error={(w.ErrorUtf8 != null ? "shown" : "none")}"
+ $" ops={w.List.OpCount} listSeq={w.List.ListSeq} playerSeq={w.PlayerVisibilitySeq}");
}
lines.Add($"script windows: {BarItems.Length} in the bar's Scripts menu");
lines.Add($"script windows: {BarItems.Length} in the bar's Scripts menu, {BarButtons.Length} with a bar button");
return lines;
}
@ -881,6 +901,7 @@ internal static class ScriptWindowRegistry
Add(WindowFlags.NoPopOut, "NoPopOut");
Add(WindowFlags.HasError, "HasError");
Add(WindowFlags.PosIsDefault, "PosIsDefault");
Add(WindowFlags.BarButton, "BarButton");
return sb.Length > 0 ? sb.ToString() : "none";
}
}

View file

@ -162,6 +162,9 @@ public struct RynthCoreApiNative
public IntPtr GetTrainingInfoFn; // int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int max) -> entries there are
public IntPtr RaiseFn; // int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent) -> RaiseResult
public IntPtr TrainSkillFn; // int TrainSkill(uint stype, int expectedCredits) -> RaiseResult
// v80: real slot order of a container's items, and moves that land at a slot
public IntPtr GetContainerOrderFn; // int GetContainerOrder(uint container, int slotKind, uint* ids, int max) -> count, -1 unknown
public IntPtr PutItemInContainerFn; // int PutItemInContainer(uint item, uint container, int placement) -> 1 sent, 0 refused, -1 unbound
}
/// <summary>

View file

@ -155,6 +155,14 @@ public readonly unsafe struct RynthCoreHost
/// (spend unassigned XP and skill credits like the character window).</summary>
public bool HasTraining => _api.Version >= 79 && _api.GetTrainingInfoFn != IntPtr.Zero
&& _api.RaiseFn != IntPtr.Zero && _api.TrainSkillFn != IntPtr.Zero;
/// <summary>v80: <see cref="TryGetContainerOrder"/> (a container's items in real slot order, and the
/// side packs' order in the pack column).</summary>
public bool HasContainerOrder => _api.Version >= 80 && _api.GetContainerOrderFn != IntPtr.Zero;
/// <summary>v80: <see cref="PutItemInContainer"/> (a move that lands at a slot; a reorder within a
/// pack). The sender can still be unbound on an odd client: the call then answers -1.</summary>
public bool HasPutItemInContainer => _api.Version >= 80 && _api.PutItemInContainerFn != IntPtr.Zero;
public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero;
public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero;
public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero;
@ -1784,6 +1792,47 @@ public readonly unsafe struct RynthCoreHost
? (RaiseResult)((delegate* unmanaged[Cdecl]<uint, int, int>)_api.TrainSkillFn)(stype, expectedCredits)
: RaiseResult.EngineTooOld;
// ─── Slot order and placed moves (API v80) ─────────────────────────────
// The server keeps every container's items in an order (the pack grid on screen); the engine
// follows it from the login message, a pack's contents list and every item move. A container
// is only known once a full list for it was seen: then and only then is there an order.
/// <summary>
/// v80: the items in <paramref name="containerId"/> in real slot order (slot 0 first), or with
/// <paramref name="slotKind"/> the side packs and foci in the main pack (the pack column, top
/// first). <paramref name="count"/> = how many there are; the buffer grows to fit. False on an
/// engine before v80 or when the order isn't known (no full list for that container yet).
/// Any thread.
/// </summary>
public bool TryGetContainerOrder(uint containerId, bool slotKind, ref uint[] buffer, out int count)
{
count = 0;
if (!HasContainerOrder || containerId == 0) return false;
buffer ??= new uint[64];
var fn = (delegate* unmanaged[Cdecl]<uint, int, uint*, int, int>)_api.GetContainerOrderFn;
for (int attempt = 0; attempt < 3; attempt++)
{
int n;
fixed (uint* p = buffer) n = fn(containerId, slotKind ? 1 : 0, buffer.Length > 0 ? p : null, buffer.Length);
if (n < 0) return false;
if (n <= buffer.Length) { count = n; return true; }
buffer = new uint[Math.Max(n, buffer.Length * 2)];
}
return false;
}
/// <summary>
/// v80: moves <paramref name="itemId"/> into <paramref name="containerId"/> at slot
/// <paramref name="placement"/> (the index it should end at, counted without it), like a drop on
/// a cell of the pack grid; within one container it reorders. The server decides and answers as
/// for any move. 1 sent or queued, 0 refused before sending, -1 the sender isn't bound on this
/// client, -2 an engine before v80. Any thread (queued to AC's main thread).
/// </summary>
public int PutItemInContainer(uint itemId, uint containerId, int placement)
=> HasPutItemInContainer
? ((delegate* unmanaged[Cdecl]<uint, uint, int, int>)_api.PutItemInContainerFn)(itemId, containerId, placement)
: -2;
/// <summary>
/// v78: which reassembled server messages this plugin wants on its
/// <c>RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c> export (Cdecl;

View file

@ -33,7 +33,7 @@
<PropertyGroup>
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
<RynthCoreSdkApiVersion>79</RynthCoreSdkApiVersion>
<RynthCoreSdkApiVersion>80</RynthCoreSdkApiVersion>
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>
</PropertyGroup>