From abf9146a5b1f732732abae2681c911087ce9dc2f Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Tue, 6 Oct 2026 08:47:11 -0400 Subject: [PATCH] Snapshot for release 2026.10.6.1 (internal 1cbe514) --- src/RynthCore.App.Avalonia/LauncherDiag.cs | 2 +- .../MainWindow.axaml.cs | 2 +- .../RynthCore.App.Avalonia.csproj | 5 + .../RynthUpdater.NavData.cs | 2 +- src/RynthCore.App.Avalonia/UsageStats.cs | 6 +- .../Compatibility/AcActionTrace.cs | 4 +- .../Compatibility/AcMainThreadQueue.cs | 211 +++- .../Compatibility/BusyCountHooks.cs | 242 +++-- .../Compatibility/ClientActionGates.cs | 15 +- .../Compatibility/GameTickHooks.cs | 3 + .../Compatibility/HeartbeatLogger.cs | 8 +- .../Compatibility/InventoryModel.cs | 4 + .../Compatibility/LoginLifecycleHooks.cs | 3 + .../Compatibility/RawPacketHooks.cs | 80 +- .../Compatibility/RynthCoreChatCommands.cs | 63 ++ .../Compatibility/SmartBoxHooks.cs | 3 + src/RynthCore.Engine/D3D9/AcUiPassHook.cs | 6 + src/RynthCore.Engine/D3D9/EndSceneHook.cs | 19 + .../D3D9/Nav3DRenderInjector.cs | 9 + src/RynthCore.Engine/D3D9/VideoPatch.cs | 589 +++++++++++ src/RynthCore.Engine/D3D9/VideoPatchPolicy.cs | 198 ++++ src/RynthCore.Engine/EngineLifecycle.cs | 3 + src/RynthCore.Engine/EntryPoint.cs | 5 + .../ImGui/EngineFrameController.cs | 14 +- src/RynthCore.Engine/ImGui/ImGuiBar.cs | 5 +- src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs | 2 +- .../ImGui/MonsterHud/MonsterHud.cs | 18 +- .../ImGui/Panels/ChatFiltersFace.cs | 95 +- .../ImGui/Panels/InventoryFace.cs | 6 + .../ImGui/Panels/ItemCountFace.cs | 249 +++++ .../ImGui/Panels/MetaFace.Editor.cs | 671 +++++++++++++ .../ImGui/Panels/MetaFace.Schedule.cs | 4 +- src/RynthCore.Engine/ImGui/Panels/MetaFace.cs | 472 ++++----- .../ImGui/Panels/MiniRemoteFace.cs | 278 ++++++ src/RynthCore.Engine/ImGui/Panels/P1Faces.cs | 4 + .../ImGui/Panels/RynthNavFace.cs | 78 +- src/RynthCore.Engine/ImGui/UiDropTargets.cs | 14 + .../ImGui/VideoPatchBanner.cs | 43 + src/RynthCore.Engine/ImGui/Win32Backend.cs | 61 +- src/RynthCore.Engine/LogPaths.cs | 2 +- src/RynthCore.Engine/Net/FlightCapture.cs | 932 ++++++++++++++++++ src/RynthCore.Engine/Net/FlightFormat.cs | 805 +++++++++++++++ src/RynthCore.Engine/Net/FlightRecorder.cs | 383 +++++++ src/RynthCore.Engine/Net/FlightRing.cs | 258 +++++ .../Plugins/EngineSettings.cs | 44 +- .../Plugins/EngineSettingsFile.cs | 119 +++ src/RynthCore.Engine/Plugins/PluginManager.cs | 71 +- .../Plugins/PluginPathDedupe.cs | 96 ++ src/RynthCore.Engine/RynthCore.Engine.csproj | 5 + src/RynthCore.Engine/UI/Data/ChatData.cs | 137 +-- .../UI/Data/ChatFilterPresets.cs | 190 ++++ .../UI/Data/ChatRuleMatching.cs | 113 +++ .../UI/Data/ChatSettingsDto.cs | 80 ++ src/RynthCore.Engine/UI/Data/ItemHudModel.cs | 290 ++++++ src/RynthCore.Engine/UI/Data/ItemHudStore.cs | 168 ++++ src/RynthCore.Engine/UI/Data/MetaData.cs | 52 +- src/RynthCore.Engine/UI/Data/MetaEditing.cs | 261 +++++ src/RynthCore.Engine/UI/Data/MetaLocation.cs | 42 + src/RynthCore.Engine/UI/Data/MetaRuleDto.cs | 36 + src/RynthCore.Engine/UI/Data/RynthNavData.cs | 24 + src/RynthCore.Engine/UI/Data/SettingsData.cs | 30 +- src/RynthCore.Engine/UI/LayeredWindow.cs | 72 +- .../UI/PanelDestroyFallback.cs | 42 + src/RynthCore.Injector/Program.cs | 2 +- .../RynthCore.Injector.csproj | 5 + src/RynthCore.Loader/EntryPoint.cs | 3 +- src/RynthCore.Loader/RynthCore.Loader.csproj | 5 + src/RynthCore.StatusAgent/AgentConfig.cs | 12 +- .../RynthCore.StatusAgent.csproj | 5 + src/Shared/RynthInstallPaths.cs | 186 ++++ tools/ChatFilterTests/ChatFilterTests.csproj | 29 + tools/ChatFilterTests/Program.cs | 320 ++++++ .../EngineSettingsTests.csproj | 27 + tools/EngineSettingsTests/Program.cs | 353 +++++++ .../FlightRecorderTests.csproj | 40 + tools/FlightRecorderTests/Program.cs | 853 ++++++++++++++++ .../InstallPathsTests.csproj | 24 + tools/InstallPathsTests/Program.cs | 167 ++++ tools/ItemHudTests/ItemHudTests.csproj | 24 + tools/ItemHudTests/Program.cs | 203 ++++ .../LauncherUpdateTests.csproj | 4 + tools/MetaEditTests/MetaEditTests.csproj | 27 + tools/MetaEditTests/Program.cs | 328 ++++++ .../NavDataUpdateTests.csproj | 4 + .../PanelWindowTests/PanelWindowTests.csproj | 23 + tools/PanelWindowTests/Program.cs | 48 + .../PluginManifestTests.csproj | 6 +- tools/PluginManifestTests/Program.cs | 85 ++ .../StatusAgentTests/StatusAgentTests.csproj | 4 + tools/UsageStatsTests/UsageStatsTests.csproj | 4 + tools/VideoPatchTests/Program.cs | 204 ++++ tools/VideoPatchTests/VideoPatchTests.csproj | 24 + tools/pe_pattern.py | 2 +- 93 files changed, 10170 insertions(+), 599 deletions(-) create mode 100644 src/RynthCore.Engine/D3D9/VideoPatch.cs create mode 100644 src/RynthCore.Engine/D3D9/VideoPatchPolicy.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs create mode 100644 src/RynthCore.Engine/ImGui/VideoPatchBanner.cs create mode 100644 src/RynthCore.Engine/Net/FlightCapture.cs create mode 100644 src/RynthCore.Engine/Net/FlightFormat.cs create mode 100644 src/RynthCore.Engine/Net/FlightRecorder.cs create mode 100644 src/RynthCore.Engine/Net/FlightRing.cs create mode 100644 src/RynthCore.Engine/Plugins/EngineSettingsFile.cs create mode 100644 src/RynthCore.Engine/Plugins/PluginPathDedupe.cs create mode 100644 src/RynthCore.Engine/UI/Data/ChatFilterPresets.cs create mode 100644 src/RynthCore.Engine/UI/Data/ChatRuleMatching.cs create mode 100644 src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs create mode 100644 src/RynthCore.Engine/UI/Data/ItemHudModel.cs create mode 100644 src/RynthCore.Engine/UI/Data/ItemHudStore.cs create mode 100644 src/RynthCore.Engine/UI/Data/MetaEditing.cs create mode 100644 src/RynthCore.Engine/UI/Data/MetaLocation.cs create mode 100644 src/RynthCore.Engine/UI/Data/MetaRuleDto.cs create mode 100644 src/RynthCore.Engine/UI/PanelDestroyFallback.cs create mode 100644 src/Shared/RynthInstallPaths.cs create mode 100644 tools/ChatFilterTests/ChatFilterTests.csproj create mode 100644 tools/ChatFilterTests/Program.cs create mode 100644 tools/EngineSettingsTests/EngineSettingsTests.csproj create mode 100644 tools/EngineSettingsTests/Program.cs create mode 100644 tools/FlightRecorderTests/FlightRecorderTests.csproj create mode 100644 tools/FlightRecorderTests/Program.cs create mode 100644 tools/InstallPathsTests/InstallPathsTests.csproj create mode 100644 tools/InstallPathsTests/Program.cs create mode 100644 tools/ItemHudTests/ItemHudTests.csproj create mode 100644 tools/ItemHudTests/Program.cs create mode 100644 tools/MetaEditTests/MetaEditTests.csproj create mode 100644 tools/MetaEditTests/Program.cs create mode 100644 tools/PanelWindowTests/PanelWindowTests.csproj create mode 100644 tools/PanelWindowTests/Program.cs create mode 100644 tools/VideoPatchTests/Program.cs create mode 100644 tools/VideoPatchTests/VideoPatchTests.csproj diff --git a/src/RynthCore.App.Avalonia/LauncherDiag.cs b/src/RynthCore.App.Avalonia/LauncherDiag.cs index a73faf0..22c3070 100644 --- a/src/RynthCore.App.Avalonia/LauncherDiag.cs +++ b/src/RynthCore.App.Avalonia/LauncherDiag.cs @@ -18,7 +18,7 @@ namespace RynthCore.App.Avalonia; /// internal static class LauncherDiag { - private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs"; + private static readonly string UnifiedLogDirectory = RynthCore.Install.RynthInstallPaths.CoreLogsDir; // C:\Games\RynthCore\Logs by default private const string UnifiedLogFileName = "RynthCore.log"; private static readonly object LogLock = new(); diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index 5a585cb..0a0c414 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -2988,7 +2988,7 @@ internal partial class MainWindow : Window // Tail the per-PID log for the last heartbeat line. Cheap: seek to // the end, read ~2KB, FileShare-tolerant of the engine's writer. - string logPath = System.IO.Path.Combine(@"C:\Games\RynthCore\Logs", $"RynthCore.{pid}.log"); + string logPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.CoreLogsDir, $"RynthCore.{pid}.log"); string tail; try { diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index fdefb66..5b4479a 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -53,4 +53,9 @@ + + + + + diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs b/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs index 2d2d27f..1a3d9aa 100644 --- a/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs +++ b/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs @@ -33,7 +33,7 @@ namespace RynthCore.App.Avalonia; /// internal sealed partial class RynthUpdater { - public const string NavDataDefaultDir = @"C:\Games\RynthCore\NavData"; + public static readonly string NavDataDefaultDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "NavData"); // C:\Games\RynthCore\NavData by default public const string NavDataIdFile = "navdata.id"; public const string NavDataLocalMarker = "navdata.local"; private const string RynthNavFile = "RynthCore.Plugin.RynthNav.dll"; diff --git a/src/RynthCore.App.Avalonia/UsageStats.cs b/src/RynthCore.App.Avalonia/UsageStats.cs index 44f9617..456a3e3 100644 --- a/src/RynthCore.App.Avalonia/UsageStats.cs +++ b/src/RynthCore.App.Avalonia/UsageStats.cs @@ -34,7 +34,7 @@ internal sealed class UsageStats public const string DefaultEndpoint = "https://aelrynth.com/rynth/ping"; /// Where the engine writes crash/hang minidumps (RynthCore.Engine CrashDump / LogPaths). - public const string DefaultDumpDirectory = @"C:\Games\RynthCore\Logs\dumps"; + public static readonly string DefaultDumpDirectory = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreLogsDir, "dumps"); // C:\Games\RynthCore\Logs\dumps by default public const int Schema = 1; private const int MaxCrashes = 1000; @@ -52,12 +52,12 @@ internal sealed class UsageStats private CancellationTokenSource _cts = new(); private int _sending; - public UsageStats(string endpoint = DefaultEndpoint, string? stateDir = null, string dumpDir = DefaultDumpDirectory) + public UsageStats(string endpoint = DefaultEndpoint, string? stateDir = null, string? dumpDir = null) { _endpoint = endpoint; _stateDir = stateDir ?? Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore"); - _dumpDir = dumpDir; + _dumpDir = dumpDir ?? DefaultDumpDirectory; } public string StatePath => Path.Combine(_stateDir, "usage-stats.json"); diff --git a/src/RynthCore.Engine/Compatibility/AcActionTrace.cs b/src/RynthCore.Engine/Compatibility/AcActionTrace.cs index dfe922f..829f600 100644 --- a/src/RynthCore.Engine/Compatibility/AcActionTrace.cs +++ b/src/RynthCore.Engine/Compatibility/AcActionTrace.cs @@ -13,7 +13,8 @@ // via Interlocked.Increment. Concurrent overwrites of the same slot are // tolerated (rare at depth 256; we only need the rough recent sequence). // -// REMOVE once Class B is diagnosed and fixed. +// Every Record also goes to the flight recorder (Net/FlightRecorder.cs) as an +// engine-call marker; keep the call if this file goes. // ============================================================================ using System; @@ -48,6 +49,7 @@ internal static class AcActionTrace _slots[slot].Name = name; _slots[slot].A = a; _slots[slot].B = b; + Net.FlightRecorder.EngineCall(name, a, b); } /// diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 6df75e7..06d1fa8 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -156,15 +156,105 @@ internal static class AcMainThreadQueue // Four payload slots cover every routed action (the 4th was added for // MoveItemInternal/SplitStackInternal: id, container, slot, amount). Floats are // carried as their IEEE bit pattern in a uint slot (BitConverter round-trip). - private readonly struct Entry(AcMainThreadQueue.ActionKind kind, uint a, uint b, uint c, uint d) + private readonly struct Entry(AcMainThreadQueue.ActionKind kind, uint a, uint b, uint c, uint d, long at, int epoch) { public readonly ActionKind Kind = kind; public readonly uint A = a; public readonly uint B = b; public readonly uint C = c; public readonly uint D = d; + /// Environment.TickCount64 when it was queued (2026-10-06). + public readonly long At = at; + /// The login it was queued in (). + public readonly int Epoch = epoch; } + // ── Age and login epoch of queued work (2026-10-06) ────────────────────────── + // Analysis by Silentkelpie; re-implemented here. Nothing queued here carried a time: the + // ring's gesture defer and the cast slot counted Drain()/tick CALLS (250 of them: about 2 s + // in front, over 10 s in a 30 fps background client), and past the cap everything queued + // ran however old - an attack on a mob that died meanwhile, a stance change or a turn from + // seconds ago, landing on top of whatever the bot had sent since (on ACE a stale mode change + // cancels a pending use's walk and fails a cast). The side queues (appraisals, health + // queries, chat) were bounded by count only and could run after a logout and a new login. + // Now every entry has its time and login; the defers are in milliseconds; at run time an + // attack, a stance change or a movement START older than StaleActionMs is dropped (the bot + // re-sends what it still wants), while stops always run and item actions run late (logged); + // side-queue entries from an earlier login, or older than their limit, are dropped. + private static int _loginEpoch; + + /// A new login begins (the logout pipeline): queued work from the old one is stale. + public static void NewLoginEpoch() => Interlocked.Increment(ref _loginEpoch); + + private static long NowMs => Environment.TickCount64; + + private const long DrainDeferMaxMs = 2_500; + private const long StaleActionMs = 1_500; + private const long LateActionLogMs = 1_000; + private const long CastDeferMaxMs = 3_000; + private const long RequestIdMaxAgeMs = 15_000; + private const long QueryHealthMaxAgeMs = 5_000; + private const long ChatMaxAgeMs = 30_000; + private const long ChatCommandMaxAgeMs = 15_000; + + private static long _staleDropped; + private static long _lateRun; + public static long StaleDroppedCount => Interlocked.Read(ref _staleDropped); + public static long LateRunCount => Interlocked.Read(ref _lateRun); + + // One summary line at most every StaleLogEveryMs (main thread only). + private const long StaleLogEveryMs = 5_000; + private static long _staleLogAt; + private static readonly System.Text.StringBuilder _staleNote = new(); + private static int _staleNoteCount; + + private static void NoteStale(string what, long ageMs, bool dropped) + { + if (dropped) Interlocked.Increment(ref _staleDropped); + else Interlocked.Increment(ref _lateRun); + if (_staleNoteCount < 8) + { + if (_staleNote.Length > 0) _staleNote.Append(", "); + _staleNote.Append(dropped ? "dropped " : "ran late ").Append(what).Append(' ').Append(ageMs).Append(" ms"); + } + _staleNoteCount++; + long now = NowMs; + if (now - _staleLogAt < StaleLogEveryMs) return; + _staleLogAt = now; + string line = $"AcMainThreadQueue: {_staleNoteCount} stale queued item(s): {_staleNote}{(_staleNoteCount > 8 ? ", ..." : "")}"; + _staleNote.Clear(); + _staleNoteCount = 0; + try { RynthLog.Compat(line); } catch { } + try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: line); } catch { } + } + + /// + /// An attack, a stance change or a movement start: dropped when older than StaleActionMs at + /// run time. Stops (autorun off, a motion off, StopMovement, StopCompletely, CancelAttack) and + /// item actions are never dropped. + /// + private static bool DropsWhenStale(in Entry e) => e.Kind switch + { + ActionKind.MeleeAttack or ActionKind.MissileAttack or ActionKind.NativeAttack => true, + ActionKind.ChangeCombatMode => true, + ActionKind.SetAutoRun => e.A != 0, + ActionKind.SetMotion => e.B != 0, + ActionKind.DoMovement or ActionKind.TurnToHeading or ActionKind.Jump + or ActionKind.CommenceJump or ActionKind.TapJump or ActionKind.DoJumpAutonomous + or ActionKind.LaunchJumpWithMotion => true, + _ => false, + }; + + private static string Describe(in Entry e) => e.Kind switch + { + ActionKind.SetAutoRun => e.A != 0 ? "SetAutoRun(on)" : "SetAutoRun(off)", + ActionKind.SetMotion => e.B != 0 ? $"SetMotion(0x{e.A:X8}, on)" : $"SetMotion(0x{e.A:X8}, off)", + ActionKind.ChangeCombatMode => $"ChangeCombatMode({e.A})", + ActionKind.UseObject => $"UseObject(0x{e.A:X8})", + ActionKind.MeleeAttack or ActionKind.MissileAttack => $"{e.Kind}(0x{e.A:X8})", + _ => e.Kind.ToString(), + }; + private const int Capacity = 256; // power of two private const int Mask = Capacity - 1; private static readonly Entry[] _slots = new Entry[Capacity]; @@ -193,7 +283,7 @@ internal static class AcMainThreadQueue return false; } - _slots[tail & Mask] = new Entry(kind, a, b, c, d); + _slots[tail & Mask] = new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch)); Volatile.Write(ref _tail, tail + 1); return true; } @@ -394,8 +484,7 @@ internal static class AcMainThreadQueue // Gesture-phase defer state for the action ring (mirrors the cast slot's // 56e6946 guard; see DrainDeferTickCap note below for why we PROCEED // rather than drop after the cap). - private static int _drainDeferTicks; - private const int DrainDeferTickCap = 250; + private static long _drainDeferSinceMs; public static void Drain() { @@ -471,16 +560,33 @@ internal static class AcMainThreadQueue // "always inject" anyway, so proceeding past the cap is never worse). if (head != tail) { - if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight - && ++_drainDeferTicks <= DrainDeferTickCap) - return; - _drainDeferTicks = 0; + // In milliseconds (was 250 Drain calls: 2 s to over 10 s depending on the frame rate). + if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight) + { + long nowDefer = NowMs; + if (_drainDeferSinceMs == 0) _drainDeferSinceMs = nowDefer; + if (nowDefer - _drainDeferSinceMs <= DrainDeferMaxMs) + return; + } + _drainDeferSinceMs = 0; } + long runAt = NowMs; + int epochNow = Volatile.Read(ref _loginEpoch); while (head != tail) { Entry e = _slots[head & Mask]; Volatile.Write(ref _head, ++head); + long age = runAt - e.At; + if (e.Epoch != epochNow || (age > StaleActionMs && DropsWhenStale(e))) + { + NoteStale(Describe(e) + (e.Epoch != epochNow ? " (queued before this login)" : ""), age, dropped: true); + tail = Volatile.Read(ref _tail); + continue; + } + if (age > LateActionLogMs) + NoteStale(Describe(e), age, dropped: false); + try { switch (e.Kind) @@ -620,7 +726,7 @@ internal static class AcMainThreadQueue // Kept in its OWN queue — NOT the gesture-deferred action ring above — so a backlog // of appraisals can never crowd out combat/movement actions or get gesture-deferred: // an appraisal is just a packet send and doesn't perturb AC's motion/UI state. - private static readonly System.Collections.Generic.Queue _requestIdQueue = new(); + private static readonly System.Collections.Generic.Queue<(uint Id, long At, int Epoch)> _requestIdQueue = new(); private static readonly object _requestIdLock = new(); private const int MaxRequestIdQueue = 256; @@ -635,7 +741,7 @@ internal static class AcMainThreadQueue Interlocked.Increment(ref _dropped); return false; } - _requestIdQueue.Enqueue(objectId); + _requestIdQueue.Enqueue((objectId, NowMs, Volatile.Read(ref _loginEpoch))); return true; } } @@ -647,15 +753,22 @@ internal static class AcMainThreadQueue // Bounded like DrainChatCommands: a re-queue never spins the main thread. int budget; lock (_requestIdLock) budget = _requestIdQueue.Count; + long now = NowMs; + int epoch = Volatile.Read(ref _loginEpoch); while (budget-- > 0) { - uint id; + (uint Id, long At, int Epoch) item; lock (_requestIdLock) { if (_requestIdQueue.Count == 0) return; - id = _requestIdQueue.Dequeue(); + item = _requestIdQueue.Dequeue(); } - try { CombatActionHooks.RequestId(id); } catch { } + if (item.Epoch != epoch || now - item.At > RequestIdMaxAgeMs) + { + NoteStale($"RequestId(0x{item.Id:X8})", now - item.At, dropped: true); + continue; + } + try { CombatActionHooks.RequestId(item.Id); } catch { } } } @@ -668,7 +781,7 @@ internal static class AcMainThreadQueue // result and only want the async 0x01C0 reply, so a target already waiting here is // not queued twice. Pre-sized, so enqueue does not allocate. private const int MaxQueryHealthQueue = 64; - private static readonly System.Collections.Generic.Queue _queryHealthQueue = new(MaxQueryHealthQueue); + private static readonly System.Collections.Generic.Queue<(uint Id, long At, int Epoch)> _queryHealthQueue = new(MaxQueryHealthQueue); private static readonly object _queryHealthLock = new(); private static int _queryHealthPending; // lock-free "anything queued?" for the per-frame drain @@ -678,14 +791,14 @@ internal static class AcMainThreadQueue if (targetId == 0) return false; lock (_queryHealthLock) { - if (_queryHealthQueue.Contains(targetId)) - return true; // already pending; one reply answers both + foreach (var q in _queryHealthQueue) + if (q.Id == targetId) return true; // already pending; one reply answers both if (_queryHealthQueue.Count >= MaxQueryHealthQueue) { Interlocked.Increment(ref _dropped); return false; } - _queryHealthQueue.Enqueue(targetId); + _queryHealthQueue.Enqueue((targetId, NowMs, Volatile.Read(ref _loginEpoch))); Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count); return true; } @@ -698,16 +811,23 @@ internal static class AcMainThreadQueue if (Volatile.Read(ref _queryHealthPending) == 0) return; int budget; lock (_queryHealthLock) budget = _queryHealthQueue.Count; + long now = NowMs; + int epoch = Volatile.Read(ref _loginEpoch); while (budget-- > 0) { - uint id; + (uint Id, long At, int Epoch) item; lock (_queryHealthLock) { if (_queryHealthQueue.Count == 0) { Volatile.Write(ref _queryHealthPending, 0); return; } - id = _queryHealthQueue.Dequeue(); + item = _queryHealthQueue.Dequeue(); Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count); } - try { CombatActionHooks.QueryHealth(id); } catch { } + if (item.Epoch != epoch || now - item.At > QueryHealthMaxAgeMs) + { + NoteStale($"QueryHealth(0x{item.Id:X8})", now - item.At, dropped: true); + continue; + } + try { CombatActionHooks.QueryHealth(item.Id); } catch { } } } @@ -718,7 +838,7 @@ internal static class AcMainThreadQueue // here and drain on the main thread from Drain(), alongside the item/movement // actions. WriteToChat's 100 ms rate-limit runs BEFORE the enqueue, so a bot retry // burst is dropped on the pump thread and this queue never fills with spam. - private static readonly System.Collections.Generic.Queue<(string Text, int ChatType)> _chatQueue = new(); + private static readonly System.Collections.Generic.Queue<(string Text, int ChatType, long At, int Epoch)> _chatQueue = new(); private static readonly object _chatLock = new(); private const int MaxChatQueue = 64; @@ -732,7 +852,7 @@ internal static class AcMainThreadQueue Interlocked.Increment(ref _dropped); return false; } - _chatQueue.Enqueue((text, chatType)); + _chatQueue.Enqueue((text, chatType, NowMs, Volatile.Read(ref _loginEpoch))); return true; } } @@ -744,14 +864,21 @@ internal static class AcMainThreadQueue // Bounded like DrainChatCommands: a re-queue never spins the main thread. int budget; lock (_chatLock) budget = _chatQueue.Count; + long now = NowMs; + int epoch = Volatile.Read(ref _loginEpoch); while (budget-- > 0) { - (string Text, int ChatType) item; + (string Text, int ChatType, long At, int Epoch) item; lock (_chatLock) { if (_chatQueue.Count == 0) return; item = _chatQueue.Dequeue(); } + if (item.Epoch != epoch || now - item.At > ChatMaxAgeMs) + { + NoteStale("a chat line", now - item.At, dropped: true); + continue; + } try { ClientHelperHooks.WriteToChat(item.Text, item.ChatType); } catch { } } @@ -769,7 +896,7 @@ internal static class AcMainThreadQueue // Dispatch() itself (rather than at each caller) covers all three at once. // A full command line can't ride the uint Entry ring, so it gets its own // string queue, same shape as the WriteToChat slot above. - private static readonly System.Collections.Generic.Queue _chatCommandQueue = new(); + private static readonly System.Collections.Generic.Queue<(string Text, long At, int Epoch)> _chatCommandQueue = new(); private static readonly object _chatCommandLock = new(); private const int MaxChatCommandQueue = 64; @@ -783,7 +910,7 @@ internal static class AcMainThreadQueue Interlocked.Increment(ref _dropped); return false; } - _chatCommandQueue.Enqueue(text); + _chatCommandQueue.Enqueue((text, NowMs, Volatile.Read(ref _loginEpoch))); return true; } } @@ -797,15 +924,22 @@ internal static class AcMainThreadQueue // waits for the next frame instead of spinning here. int budget; lock (_chatCommandLock) budget = _chatCommandQueue.Count; + long now = NowMs; + int epoch = Volatile.Read(ref _loginEpoch); while (budget-- > 0) { - string text; + (string Text, long At, int Epoch) item; lock (_chatCommandLock) { if (_chatCommandQueue.Count == 0) return; - text = _chatCommandQueue.Dequeue(); + item = _chatCommandQueue.Dequeue(); } - try { ChatCommandDispatcher.Dispatch(text); } + if (item.Epoch != epoch || now - item.At > ChatCommandMaxAgeMs) + { + NoteStale("a chat command", now - item.At, dropped: true); + continue; + } + try { ChatCommandDispatcher.Dispatch(item.Text); } catch { } } } @@ -827,9 +961,8 @@ internal static class AcMainThreadQueue // variant) can't park a cast forever: past the cap the cast is DROPPED — the // plugin's no-chat-resolve machinery already retries casts that produce no // chat, so a drop degrades to one retry cycle, never a wedge. - private static int _castDeferTicks; private static long _castDeferDrops; - private const int CastDeferTickCap = 250; // ~4-8 s at the 30-63 Hz UseTime rate + private static long _castQueuedAt; // TickCount64 when the pending cast was queued (2026-10-06) /// Casts dropped after deferring CastDeferTickCap ticks (stuck gesture). public static long CastDeferDropCount => Interlocked.Read(ref _castDeferDrops); @@ -843,6 +976,7 @@ internal static class AcMainThreadQueue if (_castPending != 0) return false; _castTargetId = targetId; _castSpellId = spellId; + _castQueuedAt = NowMs; _castPending = 1; return true; } @@ -869,18 +1003,23 @@ internal static class AcMainThreadQueue // Defer while the pending-motion list is non-empty (the exact structure // the tick walks); main-thread read, alloc-free, fail-open: if the read // itself fails we cast (pre-fix behavior) rather than park. + // In milliseconds from the queueing (was 250 game ticks, about 4-8 s): past + // CastDeferMaxMs the cast is dropped and logged with its age. RynthAi waits up to 7 s + // for a cast's answer before it sends another (ActionPacer), so a drop here can't + // leave two casts in flight. + long castAge = NowMs - Volatile.Read(ref _castQueuedAt); if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight) { - if (++_castDeferTicks <= CastDeferTickCap) + if (castAge <= CastDeferMaxMs) return; // retry next tick - // Gesture stuck past the cap — drop the cast instead of injecting + // Gesture stuck past the deadline — drop the cast instead of injecting // into a wedged motion graph; the plugin retries via no-chat-resolve. - lock (_castLock) { _castPending = 0; } - _castDeferTicks = 0; + uint dropped; + lock (_castLock) { dropped = _castSpellId; _castPending = 0; } Interlocked.Increment(ref _castDeferDrops); + NoteStale($"CastSpell({dropped}) behind a gesture", castAge, dropped: true); return; } - _castDeferTicks = 0; uint target, spell; lock (_castLock) @@ -890,6 +1029,8 @@ internal static class AcMainThreadQueue spell = _castSpellId; _castPending = 0; } + if (castAge > LateActionLogMs) + NoteStale($"CastSpell({spell})", castAge, dropped: false); CombatActionHooks.CastSpell(target, unchecked((int)spell)); } } diff --git a/src/RynthCore.Engine/Compatibility/BusyCountHooks.cs b/src/RynthCore.Engine/Compatibility/BusyCountHooks.cs index 6c3f8eb..c42e8a2 100644 --- a/src/RynthCore.Engine/Compatibility/BusyCountHooks.cs +++ b/src/RynthCore.Engine/Compatibility/BusyCountHooks.cs @@ -99,8 +99,25 @@ internal static class BusyCountHooks // CheckWatchdog on the main thread (post-tick). ≤1 tick latency — // irrelevant for a 2-5s watchdog; coalesces bursts for free. private static int _forceResetRequested; + private static string _forceResetRequestedWhy = ""; - public static void ForceResetBusyCount(bool clearMotion = false) + /// + /// The engine count to 0, and the plugins told: one busy-decremented event per unit dropped + /// (2026-10-06). ForceResetBusyCount's catch-up decrements go through the trampoline (no + /// detour, no event) and the resyncs below wrote the count straight, so the plugins' mirrors + /// (RynthAi's _busyCount, which gates buffs, combat and corpse opens) stayed up and their own + /// watchdogs fired a second reset 5-10 s later (Silentkelpie's analysis; verified). + /// + private static void DropShadowTo0() + { + int was = Interlocked.Exchange(ref _netBusyCount, 0); + for (int i = 0; i < was && i < 64; i++) + PluginManager.QueueBusyCountDecremented(); + } + + private static int ReadRealBusySigned() => TryReadRealBusy(out int v) ? v : int.MinValue; + + public static void ForceResetBusyCount(bool clearMotion = false, string why = "plugin request (host ForceResetBusyCount)") { // ⚠ MAIN THREAD ONLY (2026-06-12 cross-incident forensics, top-ranked // corruption writer): the plugin host API called this raw from the @@ -112,7 +129,9 @@ internal static class BusyCountHooks // Off-thread callers latch a request consumed post-tick instead. if (!MainThreadGuard.IsOnMainThread()) { + _forceResetRequestedWhy = why; Interlocked.Exchange(ref _forceResetRequested, 1); + Net.FlightRecorder.Mark(Net.FlightMark.BusyForceClearAsk, text: "off the game thread: latched for the next tick"); return; } @@ -131,6 +150,9 @@ internal static class BusyCountHooks } int was = _netBusyCount; + // Every reset is logged with who asked (2026-10-06; Silentkelpie's analysis counted 38 + // silent "(was real 0, shadow 0)" resets in 15 minutes). + try { RynthLog.Compat($"BusyCountHooks: force-reset by {why}: real {ReadRealBusySigned()}, engine count {was} -> 0."); } catch { } // Decrement exactly what the REAL field holds, never past zero. This used // to call the original decrement max(shadow, 3) times: with the real field @@ -140,13 +162,22 @@ internal static class BusyCountHooks // so this was never the item-action lock, but there is no reason to // write below zero. See ClientActionGates for the gates AC really checks. int real = Marshal.ReadInt32(_lastThisPtr + OffsetMCBusy); + Net.FlightRecorder.Mark(Net.FlightMark.BusyForceClear, unchecked((uint)real), unchecked((uint)was), + text: clearMotion ? "with the motion flush" : ""); if (_originalDecrementBusyCount != null && real > 0) { for (int i = 0; i < real && i < 20; i++) _originalDecrementBusyCount(_lastThisPtr); } - Interlocked.Exchange(ref _netBusyCount, 0); + DropShadowTo0(); + // Nothing of the old count is left for the reconciler (a late UseDone just finds 0). + lock (_directLock) + { + _directPending.Clear(); + _directLeak = 0; + _pendingCastBusyDelta = 0; + } try { Marshal.WriteInt32(_lastThisPtr + OffsetMCBusy, 0); } catch { /* non-fatal */ } @@ -223,8 +254,9 @@ internal static class BusyCountHooks return false; Marshal.WriteInt32(p + OffsetMCBusy, 0); - Interlocked.Exchange(ref _netBusyCount, 0); + DropShadowTo0(); Interlocked.Increment(ref _negativeRepairCount); + Net.FlightRecorder.Mark(Net.FlightMark.BusyNegativeRepair, unchecked((uint)was)); if (_updateCursorStateAddress != IntPtr.Zero) { try @@ -332,7 +364,14 @@ internal static class BusyCountHooks // stopped firing for 30+ min while ChangeCombatMode was re-sent and 191 // "too busy" refusals piled up, yet zero force-clears — classic desync.) private static long _realBusyPositiveTickMs; - private const long RealBusyWatchdogTimeoutMs = 4_000; + // 2026-10-06: was 4 s with no other condition, which zeroed the count of actions the + // server had not answered yet (a corpse walk, a 2.4 s kit, a 3.5 s vital cast) many times + // an hour. m_cBusy only drives the cursor (see ClientActionGates), so this is a cursor + // clean-up and runs only once the server has demonstrably gone quiet: the count positive + // for RealBusyWatchdogTimeoutMs AND no UseDone at all for RealBusyServerSilentMs AND no + // cast gesture animating. + private const long RealBusyWatchdogTimeoutMs = 12_000; + private const long RealBusyServerSilentMs = 12_000; private static int ReadRealBusy() { @@ -359,34 +398,108 @@ internal static class BusyCountHooks _lastThisPtr = IntPtr.Zero; Volatile.Write(ref _realBusyPositiveTickMs, 0); _realBusyNegativeSince = 0; - _pendingCastBusyDelta = 0; - _pendingCastGestureSeen = false; + lock (_directLock) + { + _pendingCastBusyDelta = 0; + _directPending.Clear(); + _directLeak = 0; + } + Volatile.Write(ref _lastUseDoneTickMs, 0); try { ClientActionGates.ResetTracking(); } catch { } } - // ── Direct-action busy reconciliation (source fix for the per-action leak) ── - // The engine's direct AC calls — casts (FreeHandsAndCastSpell / CastSpell) - // AND item actions (UseObject corpse-open / equip / item-use, UseObjectOn) — - // make AC increment m_cBusy synchronously, but they never register the queued - // action whose completion handler performs the matching decrements (that - // lives in the player-initiated flow we bypass). Result: EVERY such call - // leaked busy, caught only downstream by watchdogs (casts: 4322 plugin-side - // clears in one 10h soak; corpse opens: a force-clear every ~2s during loot - // grinds). Source fix: measure the real m_cBusy delta synchronously around - // the call (both run on AC's main thread, nothing interleaves, so the delta - // is exactly ours), then once the action GESTURE has completed - // ([CMI+0x80] empties — a use-reach is a sequenced motion just like a cast - // wind-up) — or after a timeout if it never starts (server refusal) — invoke - // the REAL DecrementBusyCount exactly delta times through the HOOKED entry, - // so the shadow counter and plugin busy events stay in sync. Deterministic, - // no ClearAllCommands side effects, never touches counts owned by others. - // A single accumulator serves both casts and item actions (all are - // engine-issued busy that should clear at the next gesture-end). - private static int _pendingCastBusyDelta; - private static long _pendingCastIssuedAtMs; - private static bool _pendingCastGestureSeen; + // ── UseDone: AC's own decrement (2026-10-06) ───────────────────────────── + // AC pairs every client action with the server's answer: sending a use or a cast + // increments m_cBusy (ClientUISystem::IncrementBusyCount, e.g. after + // CM_Magic::Event_CastUntargetedSpell @0x00567CB0), and the server's UseDone + // (GameEvent 0x01C7) decrements it INLINE in ClientUISystem::Handle_Item::UseDone + // (@0x005656A0: [ui+0x14]-1, UpdateCursorState at 0) - not through + // DecrementBusyCount, so neither this file's shadow count nor the plugins' mirrors + // ever saw it. That blind spot is where "busy count stuck" came from: the shadow + // climbed after every use and cast, and the plugin and the watchdogs below then + // force-cleared AC's REAL count while the server still owed answers (each later + // UseDone drove it to -1: ~190 negative repairs an hour on 10-05/10-06). The engine's + // direct UseObject / UseObjectOn / CastSpell go through the same client functions, + // so their busy is answered the same way: the reconciler below must not decrement it + // a second time. + // SmartBoxHooks calls this for every inbound UseDone, on AC's main thread, before AC + // handles it: the shadow and the plugin mirrors take the same -1 AC is about to take, + // and one unit of direct-action reconcile is dropped (AC pairs it itself). + private static long _lastUseDoneTickMs; + private static int _lateUseDone; + private static long _useDoneMirrored; + public static long UseDoneMirrorCount => Interlocked.Read(ref _useDoneMirrored); + + public static void OnUseDone() + { + Volatile.Write(ref _lastUseDoneTickMs, Environment.TickCount64); + // The flight recorder shows AC's inline -1 as an ordinary decrement: real after it, shadow after ours. + if (TryReadRealBusy(out int realBefore)) + { + Net.FlightRecorder.Mark(Net.FlightMark.BusyDecrement, unchecked((uint)(realBefore - 1)), + unchecked((uint)Math.Max(0, Volatile.Read(ref _netBusyCount) - 1))); + // Nothing is counted for this answer (its action was reconciled or reset already, or the + // count was never raised): AC's -1 makes the count negative. Swallow it at the next tick + // instead of after the 2 s grace below. + if (realBefore <= 0) + Volatile.Write(ref _lateUseDone, 1); + } + // AC pairs this UseDone with the oldest direct action still waiting for one: drop one + // unit of its delta from the reconciler (a FreeHandsAndCastSpell that added 2 keeps + // its unanswered second unit, which is a real leak and is reconciled). + lock (_directLock) + { + if (_directPending.Count > 0) + { + var e = _directPending.Dequeue(); + _pendingCastBusyDelta = Math.Max(0, _pendingCastBusyDelta - 1); + if (e.Delta > 1) + _directLeak += e.Delta - 1; + } + } + int now; + int was; + do + { + was = Volatile.Read(ref _netBusyCount); + if (was <= 0) return; // nothing of ours to pair (a player action we never counted, or already 0) + now = was - 1; + } + while (Interlocked.CompareExchange(ref _netBusyCount, now, was) != was); + Interlocked.Increment(ref _useDoneMirrored); + if (now <= 0) + Volatile.Write(ref _busyBecamePositiveTickMs, 0); + PluginManager.QueueBusyCountDecremented(); + } + + // ── Direct-action busy reconciliation ───────────────────────────────────── + // The engine's direct AC calls (casts via FreeHandsAndCastSpell / CastSpell, and + // UseObject / UseObjectOn) raise m_cBusy synchronously; the delta is measured around + // the call (both on AC's main thread, so it is exactly ours). + // 2026-10-06: this used to decrement the whole delta as soon as the gesture ended or + // 4 s passed, on the belief that nothing else would - but AC's UseDone handler does + // (see OnUseDone), so every answered action was decremented twice and the real count + // went to -1 until the negative repair below (~190 an hour). Now each direct action + // waits in _directPending for ITS UseDone (OnUseDone takes one unit off), and only + // what no UseDone will answer is decremented here: + // * the part of a delta above 1 (FreeHandsAndCastSpell readies the wand +1 and casts + // +1; the server answers the cast only), once no gesture animates; + // * an action with no UseDone after DirectActionAnswerMs (a wield gets none; a + // refusal the client never heard about), once no gesture animates. + // A late UseDone after that still drives the count to -1; the negative repair stays. + private readonly struct DirectAction + { + public readonly long IssuedAtMs; + public readonly int Delta; + public DirectAction(long at, int delta) { IssuedAtMs = at; Delta = delta; } + } + private static readonly System.Collections.Generic.Queue _directPending = new(); + private static readonly object _directLock = new(); // ResetSession can come from another thread + private static int _directLeak; + private static int _pendingCastBusyDelta; // what the reconciler may still decrement (display + clamp) private static int _reconcileLogCount; - private const long CastBusyReconcileTimeoutMs = 4_000; + // The longest answer in 3.7 h of healthy logs was 5.0 s (a vital cast; corpse walks 3.7 s). + private const long DirectActionAnswerMs = 6_000; /// Snapshot the real m_cBusy immediately before a direct cast/item-action call (-1 = unreadable). public static int CaptureRealBusyForCast() => ReadRealBusy(); @@ -402,37 +515,42 @@ internal static class BusyCountHooks if (after < 0) return; int delta = after - busyBefore; if (delta <= 0) return; - _pendingCastBusyDelta += delta; - _pendingCastIssuedAtMs = Environment.TickCount64; - _pendingCastGestureSeen = false; + lock (_directLock) + { + _pendingCastBusyDelta += delta; + _directPending.Enqueue(new DirectAction(Environment.TickCount64, delta)); + while (_directPending.Count > 64) _directLeak += _directPending.Dequeue().Delta; // never unbounded + } + } + + private static bool CastGestureAnimating() + { + try { return PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool g) && g; } + catch { return false; } } private static void ReconcileCastBusy(long now) { - int pending = _pendingCastBusyDelta; + int pending; + lock (_directLock) + { + // Actions the server never answered in time join the unanswered part. + while (_directPending.Count > 0 && now - _directPending.Peek().IssuedAtMs > DirectActionAnswerMs) + _directLeak += _directPending.Dequeue().Delta; + pending = _directLeak; + } if (pending <= 0) return; - bool gesture = false; - try { if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out gesture)) gesture = false; } - catch { gesture = false; } + // Never mid-gesture: the action's own animation is what it is still doing. + if (CastGestureAnimating()) + return; - if (gesture) + lock (_directLock) { - // Cast animation running — completion is the decrement point. - _pendingCastGestureSeen = true; - return; + _directLeak = Math.Max(0, _directLeak - pending); + _pendingCastBusyDelta = Math.Max(0, _pendingCastBusyDelta - pending); } - // Decrement once the observed gesture has ENDED, or after the timeout - // when no gesture was ever seen (refused cast / instant failure). The - // timeout matches the real-field watchdog window, so worst case this - // path is no slower than the old crutch. - if (!_pendingCastGestureSeen && now - _pendingCastIssuedAtMs <= CastBusyReconcileTimeoutMs) - return; - - _pendingCastBusyDelta = 0; - _pendingCastGestureSeen = false; - IntPtr p = _lastThisPtr; if (p == IntPtr.Zero || _decrementTargetAddress == IntPtr.Zero) return; if (!ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy)) return; @@ -451,6 +569,7 @@ internal static class BusyCountHooks var dec = Marshal.GetDelegateForFunctionPointer(_decrementTargetAddress); for (int i = 0; i < n; i++) dec(p); Interlocked.Increment(ref _reconcileCount); + Net.FlightRecorder.Mark(Net.FlightMark.BusyReconcile, (uint)n, unchecked((uint)ReadRealBusy())); if (_reconcileLogCount < 50 || _reconcileLogCount % 100 == 0) RynthLog.Compat($"BusyCountHooks: direct-action busy reconciled — decremented {n} (real now {ReadRealBusy()}, total reconciles {_reconcileLogCount + 1})."); _reconcileLogCount++; @@ -509,7 +628,7 @@ internal static class BusyCountHooks // Consume any off-thread force-reset request (plugin watchdogs): // the actual clear runs HERE, on the main thread. if (Interlocked.Exchange(ref _forceResetRequested, 0) == 1) - ForceResetBusyCount(); + ForceResetBusyCount(why: _forceResetRequestedWhy + " (latched from off the game thread)"); int realBusy = ReadRealBusy(); if (realBusy > 0) @@ -520,11 +639,15 @@ internal static class BusyCountHooks Volatile.Write(ref _realBusyPositiveTickMs, now); } else if (now - sinceR > RealBusyWatchdogTimeoutMs + && now - Volatile.Read(ref _lastUseDoneTickMs) > RealBusyServerSilentMs + && !CastGestureAnimating() && now - Volatile.Read(ref _lastWatchdogFireTickMs) > BusyWatchdogCooldownMs) { Volatile.Write(ref _lastWatchdogFireTickMs, now); - RynthLog.Compat($"BusyCountHooks: REAL m_cBusy stuck at {realBusy} for {now - sinceR}ms (counter={_netBusyCount}) — force-clearing desync."); - ForceResetBusyCount(); + long silent = now - Volatile.Read(ref _lastUseDoneTickMs); + RynthLog.Compat($"BusyCountHooks: REAL m_cBusy at {realBusy} for {now - sinceR}ms with no UseDone from the server for {(silent > 3_600_000 ? "ever" : silent + "ms")} (counter={_netBusyCount}) — resetting the cursor count (the server is quiet; nothing is waiting on it)."); + Net.FlightRecorder.Mark(Net.FlightMark.BusyWatchdog, (uint)realBusy, unchecked((uint)_netBusyCount), (uint)(now - sinceR), "real m_cBusy positive, server quiet"); + ForceResetBusyCount(why: "the engine's real-count watchdog (server quiet)"); Volatile.Write(ref _realBusyPositiveTickMs, 0); Volatile.Write(ref _busyBecamePositiveTickMs, 0); return; @@ -542,7 +665,13 @@ internal static class BusyCountHooks // Negative real field (ReadRealBusy folds every negative into its -1 // "unreadable" sentinel, so read it directly). See RepairNegativeBusy. bool haveReal = TryReadRealBusy(out int signedBusy); - if (haveReal && signedBusy < 0) + bool lateUseDone = Interlocked.Exchange(ref _lateUseDone, 0) == 1; + if (haveReal && signedBusy < 0 && lateUseDone && RepairNegativeBusy(out int lateNeg)) + { + _realBusyNegativeSince = 0; + RynthLog.Compat($"BusyCountHooks: a UseDone came with nothing counted for it; m_cBusy {lateNeg} -> 0 at once."); + } + else if (haveReal && signedBusy < 0) { if (_realBusyNegativeSince == 0) _realBusyNegativeSince = now; @@ -568,7 +697,7 @@ internal static class BusyCountHooks if (shadowSince != 0 && haveReal && signedBusy <= 0 && now - shadowSince >= BusyWatchdogTimeoutMs) { - Interlocked.Exchange(ref _netBusyCount, 0); + DropShadowTo0(); Volatile.Write(ref _busyBecamePositiveTickMs, 0); return; } @@ -592,7 +721,8 @@ internal static class BusyCountHooks Volatile.Write(ref _lastWatchdogFireTickMs, now); RynthLog.Compat($"BusyCountHooks: watchdog auto-resetting — busy stuck at {_netBusyCount} for {elapsed}ms."); - ForceResetBusyCount(); + Net.FlightRecorder.Mark(Net.FlightMark.BusyWatchdog, unchecked((uint)ReadRealBusy()), unchecked((uint)_netBusyCount), (uint)elapsed, "engine count stuck"); + ForceResetBusyCount(why: "the engine's count watchdog (real count unreadable)"); Volatile.Write(ref _busyBecamePositiveTickMs, 0); } @@ -606,6 +736,7 @@ internal static class BusyCountHooks catch (Exception ex) { try { RynthLog.Compat($"BusyCountHooks: Increment original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; } Interlocked.Increment(ref _incrementDispatchCount); int after = Interlocked.Increment(ref _netBusyCount); + Net.FlightRecorder.Mark(Net.FlightMark.BusyIncrement, unchecked((uint)Marshal.ReadInt32(thisPtr + OffsetMCBusy)), unchecked((uint)after)); if (after == 1) Volatile.Write(ref _busyBecamePositiveTickMs, Environment.TickCount64); PluginManager.QueueBusyCountIncremented(); @@ -622,6 +753,7 @@ internal static class BusyCountHooks catch (Exception ex) { try { RynthLog.Compat($"BusyCountHooks: Decrement original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; } Interlocked.Increment(ref _decrementDispatchCount); int after = Interlocked.Decrement(ref _netBusyCount); + Net.FlightRecorder.Mark(Net.FlightMark.BusyDecrement, unchecked((uint)Marshal.ReadInt32(thisPtr + OffsetMCBusy)), unchecked((uint)after)); if (after <= 0) Volatile.Write(ref _busyBecamePositiveTickMs, 0); PluginManager.QueueBusyCountDecremented(); diff --git a/src/RynthCore.Engine/Compatibility/ClientActionGates.cs b/src/RynthCore.Engine/Compatibility/ClientActionGates.cs index 9665c94..ebaa41b 100644 --- a/src/RynthCore.Engine/Compatibility/ClientActionGates.cs +++ b/src/RynthCore.Engine/Compatibility/ClientActionGates.cs @@ -340,7 +340,7 @@ internal static class ClientActionGates long heldMs = now - _attackSetSince; _attackSetSince = 0; - if (ClearAttackFlag()) + if (ClearAttackFlag($"watchdog: held {heldMs / 1000}s with no AttackDone")) { RynthLog.Compat($"ClientActionGates: attacking flag held {heldMs / 1000}s with no AttackDone — cleared. AC was refusing every item use/move ('while attacking')."); NotifyChat("Item actions were locked (the client never got the end of an attack). Unlocked."); @@ -395,7 +395,7 @@ internal static class ClientActionGates if (reason == null) return; - if (ClearPendingRequest()) + if (ClearPendingRequest("watchdog: " + reason)) { RynthLog.Compat( $"ClientActionGates: cleared a stuck item request — {RequestTypeName(type)} (type {type}) on 0x{objectId:X8}" + @@ -423,10 +423,12 @@ internal static class ClientActionGates /// Empty AC's pending-inventory-request slot, the same four stores /// RecordResponse makes when the server answers. Main thread only. /// - private static bool ClearPendingRequest() + private static bool ClearPendingRequest(string why) { if (!MainThreadGuard.IsOnMainThread() || !_requestReady) return false; + Net.FlightRecorder.Mark(Net.FlightMark.GateCleared, + unchecked((uint)Marshal.ReadInt32(new IntPtr(_reqTypeVa))), unchecked((uint)Marshal.ReadInt32(new IntPtr(_reqObjVa))), text: why); Marshal.WriteInt32(new IntPtr(_reqObjVa), 0); Marshal.WriteInt32(new IntPtr(_reqTypeVa), 0); Marshal.WriteInt32(new IntPtr(_reqTimeVa), 0); @@ -436,10 +438,11 @@ internal static class ClientActionGates } /// Clear AC's attacking flag, as HandleAttackDoneEvent does. Main thread only. - private static bool ClearAttackFlag() + private static bool ClearAttackFlag(string why) { if (!MainThreadGuard.IsOnMainThread() || !_attackReady) return false; + Net.FlightRecorder.Mark(Net.FlightMark.GateCleared, 0, 0, text: why); Marshal.WriteInt32(new IntPtr(_attackVa), 0); Interlocked.Increment(ref _attackClears); return true; @@ -468,12 +471,12 @@ internal static class ClientActionGates var done = new System.Collections.Generic.List(); if (TryReadPending(out uint type, out uint objectId, out double age) && type != 0) { - if (ClearPendingRequest()) + if (ClearPendingRequest(why)) done.Add($"cleared the pending item request ({RequestTypeName(type)} on 0x{objectId:X8}{(age >= 0 ? $", {age:0}s old" : string.Empty)})"); } if (TryReadAttacking(out bool attacking) && attacking) { - if (ClearAttackFlag()) + if (ClearAttackFlag(why)) done.Add("cleared the attacking flag"); } if (BusyCountHooks.RepairNegativeBusy(out int was)) diff --git a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs index d3a8734..a0ab5ce 100644 --- a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs +++ b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs @@ -200,6 +200,9 @@ internal static class GameTickHooks // keeping all engine-issued mutations after AC's pass is the invariant. try { BusyCountHooks.CheckWatchdog(); } catch { } + // Flight recorder: per-second summary, stall detectors, scheduled automatic dump. + try { Net.FlightRecorder.MainTick(); } + catch { } // MUST return Client::UseTime's own bool — AC loops do/while on it. return result; diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index 5a37c15..73027f6 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -162,7 +162,13 @@ internal static class HeartbeatLogger // every use/move/equip meanwhile); atk=1 = its attacking flag is set. Both // omitted while open, so a long run of req= in a log is the item-action lock. string gateField = ClientActionGates.HeartbeatField(); - RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}"); + // vp=:skip|draw cpu=N% = the video patch (D3D9/VideoPatch) and this + // client's CPU share of all cores. Omitted while the patch is off; the patch + // also logs before/after averages around each mode change. + string vpField = ""; + try { vpField = D3D9.VideoPatch.OnHeartbeat(draw); } + catch { } + RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}"); // Every 60 s: garbage collections and the time they paused the process. // Under the CoreCLR host the engine and managed plugins share one GC, so a diff --git a/src/RynthCore.Engine/Compatibility/InventoryModel.cs b/src/RynthCore.Engine/Compatibility/InventoryModel.cs index 3930e57..2b353cb 100644 --- a/src/RynthCore.Engine/Compatibility/InventoryModel.cs +++ b/src/RynthCore.Engine/Compatibility/InventoryModel.cs @@ -249,6 +249,9 @@ internal static class InventoryModel public static InventoryPending? Pending => Volatile.Read(ref _pending); public static InventoryResult? LastResult => Volatile.Read(ref _result); public static InventoryTarget? Target => Volatile.Read(ref _target); + /// The object selected in the game when it is one of the character's items, else 0 (4 Hz while subscribed). + public static uint SelectedItem => Volatile.Read(ref _selectedItem); + private static uint _selectedItem; public static bool DropAvailable => ClientHelperHooks.HasDropItem; public static bool GiveAvailable => ClientHelperHooks.HasGiveObjectTo; public static bool WieldAvailable => ClientHelperHooks.HasWieldItem; @@ -662,6 +665,7 @@ internal static class InventoryModel { uint sel = ClientHelperHooks.GetSelectedItemId(); uint player = ClientHelperHooks.GetPlayerId(); + Volatile.Write(ref _selectedItem, sel != 0 && _items.ContainsKey(sel) ? sel : 0u); InventoryTarget? cur = _target; if (sel == 0 || sel == player || _items.ContainsKey(sel) || !ClientObjectHooks.TryGetItemType(sel, out uint type) || (type & 0x10u) == 0) // creatures and players only diff --git a/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs b/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs index e4c8e7d..545f678 100644 --- a/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs +++ b/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs @@ -100,6 +100,9 @@ internal static class LoginLifecycleHooks public static void ResetObservation() { HasObservedLoginComplete = false; + // Queued engine work (appraisals, health queries, chat, actions) from this login is stale + // for the next one (2026-10-06, AcMainThreadQueue). + try { AcMainThreadQueue.NewLoginEpoch(); } catch { } _statusMessage = "Awaiting next SendLoginCompleteNotification."; _waitingLogged = false; } diff --git a/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs b/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs index 37260df..2bbec6a 100644 --- a/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs +++ b/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs @@ -1,16 +1,19 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Threading; using RynthCore.Engine.Hooking; namespace RynthCore.Engine.Compatibility; /// -/// Hooks the game's recvfrom socket function to intercept all S2C UDP packets. +/// Hooks the game's recvfrom socket function to intercept all S2C UDP packets, and (for +/// the flight recorder, Net/FlightRecorder.cs) its sendto function to see C2S packets. /// /// The acclient.exe data segment holds a pointer to the recvfrom implementation: -/// RecvFrom @ *(int*)0x007935AC -/// SendTo @ *(int*)0x007935A4 (not hooked — S2C discovery only) +/// RecvFrom @ *(int*)0x007935AC (WSOCK32 ordinal 17) +/// SendTo @ *(int*)0x007935A4 (WSOCK32 ordinal 20; hooked only while engine.json +/// "FlightRecorder" is on, the default) /// /// We read the function address, install a MinHook detour, call through to the /// original on every receive, then hand the buffer to RawPacketParser for @@ -21,17 +24,33 @@ namespace RynthCore.Engine.Compatibility; internal static class RawPacketHooks { private const int RecvFromPtrAddr = unchecked((int)0x007935AC); + private const int SendToPtrAddr = unchecked((int)0x007935A4); // Phase B: resolve the RecvFrom fn-ptr slot's address by code-xref ("call [slot]" = // FF 15 ), operand at offset 2; the VA stays as fallback. private static readonly byte?[] PatXrefRecvFromSlot = [ 0xFF, 0x15, null, null, null, null, 0x8B, 0xF0, 0x85, 0xF6, 0x7E, 0x67 ]; + // The SendTo slot, same way: its one "call [slot]" site (operand at offset 2). + private static readonly byte?[] PatXrefSendToSlot = [ 0xFF, 0x15, null, null, null, null, 0x8B, 0xF0, 0x83, 0xFE, 0xFF, 0x75 ]; + private static IntPtr _originalRecvFromPtr; + private static IntPtr _originalSendToPtr; + private static int _sendErrors; public static bool IsInstalled { get; private set; } + public static bool IsSendInstalled { get; private set; } + + /// sendto calls that returned an error since the engine started. + public static int SendErrors => Volatile.Read(ref _sendErrors); public static void Initialize() { + if (Plugins.EngineSettings.FlightRecorder) + { + try { InstallSendTo(); } + catch (Exception ex) { RynthLog.Compat($"RawPacket: SendTo hook failed - {ex.Message}"); } + } + if (IsInstalled) return; int slotAddr = RecvFromPtrAddr; @@ -68,6 +87,58 @@ internal static class RawPacketHooks } } + /// + /// The sendto detour, for the flight recorder only: it reads the datagram before the real + /// sendto runs and then calls it unchanged. Nothing managed runs after the real call + /// except one Interlocked counter on an error, so WSAGetLastError still sees sendto's error. + /// + private static void InstallSendTo() + { + if (IsSendInstalled) return; + + int slotAddr = SendToPtrAddr; + if (AcClientModule.TryReadTextSection(out AcClientTextSection text)) + slotAddr = HookResolver.ResolveData(text, "RawPacket.SendToSlot", PatXrefSendToSlot, 2, SendToPtrAddr).Address.ToInt32(); + + unsafe + { + IntPtr fnPtrAddr = new IntPtr(slotAddr); + if (!SmartBoxLocator.IsMemoryReadable(fnPtrAddr, 4)) + { + RynthLog.Compat($"RawPacket: SendTo pointer address 0x{slotAddr:X8} not readable - skipping."); + return; + } + IntPtr sendToAddr = Marshal.ReadIntPtr(fnPtrAddr); + if (sendToAddr == IntPtr.Zero) + { + RynthLog.Compat("RawPacket: SendTo pointer is null - skipping."); + return; + } + delegate* unmanaged[Stdcall] pDetour = &SendToDetour; + MinHook.Hook(sendToAddr, (IntPtr)pDetour, out _originalSendToPtr); + IsSendInstalled = true; + RynthLog.Verbose($"RawPacket: SendTo hook installed @ 0x{sendToAddr.ToInt32():X8}"); + } + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static unsafe int SendToDetour(IntPtr s, IntPtr buf, int len, int flags, IntPtr to, int tolen) + { + RecursionGuard.Tick("RawPacketHooks.SendTo"); + if (len > 0 && buf != IntPtr.Zero) + { + try { Net.FlightRecorder.OnOutbound((byte*)buf, len); } + catch { /* never affect game traffic */ } + } + + delegate* unmanaged[Stdcall] original = + (delegate* unmanaged[Stdcall])_originalSendToPtr; + int sent = original(s, buf, len, flags, to, tolen); + if (sent < 0) + Interlocked.Increment(ref _sendErrors); + return sent; + } + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] private static unsafe int RecvFromDetour( IntPtr s, IntPtr buf, int len, int flags, IntPtr from, IntPtr fromlen) @@ -88,7 +159,10 @@ internal static class RawPacketHooks // messages, one copy into a ring for the pump (never blocks, never allocates). // A MSG_PEEK (0x2) read leaves the datagram queued; the real read copies it. if ((flags & 0x2) == 0) + { Net.ServerMessageStream.OnDatagram((byte*)buf, bytesRead); + Net.FlightRecorder.OnInbound((byte*)buf, bytesRead); + } RawPacketParser.Parse((byte*)buf, bytesRead); } catch diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index e7cc57a..f30b58c 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -46,6 +46,11 @@ namespace RynthCore.Engine.Compatibility; /// /rc hooks [on|off <name>] (alias /rc uihooks) — the UI hooks /// (screen mode, client cleanup, tooltip, drag/drop; ): /// status, or switch one off/on (now and in engine.json). +/// /rc video [status|off|world|unfocused|all|fps <n>] (alias +/// /rc videopatch; "on" = world) — the video patch +/// (): stop drawing AC's 3D world (world), only while +/// the client is in the background (unfocused), or AC's UI too (all, session only). +/// Saved per character (also Settings > Misc); fps = the frame cap while patched. /// /rc mastery — the Aelrynth mastery feed's state (), /// and ask the server for /mastery-data again. /// /rc worldlayer [auto|uipass|transition|endscene] — where the world overlays @@ -57,6 +62,10 @@ namespace RynthCore.Engine.Compatibility; /// counters; on/off for this session (engine.json "ServerMessageStream": false is the /// kill switch); log = the SDK parsers run on live messages, results to the log; /// capture = raw datagrams to a .rnc file for tools/NetMessageTests. +/// /rc flightdump [note] - write the flight recorder (: +/// the last minutes of client/server messages and engine markers) to +/// Logs\flight-<pid>-<time>.txt; /rc flightdump auto <reason> is the rate-limited +/// automatic form. /rc flight [status|mark <text>|on|off|auto on|off]. /// /// internal static class RynthCoreChatCommands @@ -161,6 +170,18 @@ internal static class RynthCoreChatCommands return true; } + // /rc video [status|off|world|unfocused|all|fps ] : the video patch (stop drawing the 3D world) + if (IsVerb(sub, "video", out string videoArgs) || IsVerb(sub, "videopatch", out videoArgs)) + { + try + { + foreach (string l in D3D9.VideoPatch.HandleCommand(videoArgs)) + Reply(l); + } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc video failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + // /rc hooks [on|off ] : the UI hooks (screen mode, client cleanup, tooltip, drag/drop) if (IsVerb(sub, "hooks", out string hooksArgs) || IsVerb(sub, "uihooks", out hooksArgs)) { @@ -169,6 +190,30 @@ internal static class RynthCoreChatCommands return true; } + // /rc flightdump [note] | /rc flightdump auto : write the flight recorder now + if (IsVerb(sub, "flightdump", out string dumpArgs)) + { + try + { + foreach (string l in Net.FlightRecorder.HandleDumpCommand(dumpArgs)) + Reply(l); + } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc flightdump failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + + // /rc flight [status|mark |on|off|auto on|off] : the flight recorder + if (IsVerb(sub, "flight", out string flightArgs)) + { + try + { + foreach (string l in Net.FlightRecorder.HandleCommand(flightArgs)) + Reply(l); + } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc flight failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + // /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream if (IsVerb(sub, "netmsg", out string netArgs)) { @@ -219,6 +264,24 @@ internal static class RynthCoreChatCommands UI.PanelRouter.Toggle(ImGuiBackend.Panels.SenseFace.Title); return true; + case "itemcount": + case "itemhud": + // The ImGui Item Count panel (open/close), like its bar button. + if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.ItemCountFace.Title)) + Reply("The Item Count panel isn't available (the ImGui layer is off?)."); + else + UI.PanelRouter.Toggle(ImGuiBackend.Panels.ItemCountFace.Title); + return true; + + case "remote": + case "miniremote": + // The ImGui Mini Remote panel (open/close), like its bar button. + if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title)) + Reply("The Mini Remote panel isn't available (the ImGui layer is off?)."); + else + UI.PanelRouter.Toggle(ImGuiBackend.Panels.MiniRemoteFace.Title); + return true; + case "resetbar": case "barreset": RynthLog.Compat("RynthCoreChatCommands: /rc resetbar — resetting overlay bar position."); diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index db2f302..afa46b3 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -347,6 +347,9 @@ internal static class SmartBoxHooks // v70: the sequence and its error code as one 64-bit value, so a reader // on the plugin pump never pairs one UseDone's number with another's code. System.Threading.Interlocked.Exchange(ref _useDoneLast, ((long)(uint)seq << 32) | err); + // AC is about to take one off m_cBusy inline (Handle_Item::UseDone): the engine's + // shadow and the plugins' mirrors take it too (2026-10-06, BusyCountHooks.OnUseDone). + try { BusyCountHooks.OnUseDone(); } catch { } // Every one while RynthLog.ActionDoneTraceEnabled (the default; 2026-10-05: the // first 25 of a session couldn't show which completion a held cast was waiting on). if (RynthLog.ActionDoneTraceEnabled || _useDoneLogCount < 25) diff --git a/src/RynthCore.Engine/D3D9/AcUiPassHook.cs b/src/RynthCore.Engine/D3D9/AcUiPassHook.cs index 5fffa56..76d15f2 100644 --- a/src/RynthCore.Engine/D3D9/AcUiPassHook.cs +++ b/src/RynthCore.Engine/D3D9/AcUiPassHook.cs @@ -148,6 +148,12 @@ internal static class AcUiPassHook Interlocked.Increment(ref _calls); if (IsInstalled && !EngineLifecycle.IsShuttingDown) { + // Video patch "all": AC's 2D UI isn't drawn this frame (nor the world overlays, + // which skip with the 3D scene). Off, or any problem: AC's UI pass as usual. + bool skipUi = false; + try { skipUi = VideoPatch.SkipAcUiThisFrame; } + catch { } + if (skipUi) return; try { Nav3DRenderInjector.OnAcUiPass(); } catch { /* never let an overlay problem take AC's UI pass down */ } } diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index 1c0274d..677e141 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -24,6 +24,8 @@ internal static class EndSceneHook internal static int FpsTargetFocused = 60; internal static int FpsTargetBackground = 30; private static readonly Stopwatch _fpsTimer = Stopwatch.StartNew(); + // Video patch: the cap while AC's 3D scene isn't drawn (VideoPatch.FrameCapThisFrame). + private static readonly Stopwatch _videoPatchTimer = Stopwatch.StartNew(); private static bool _fpsLimiterLoggedOnce; private static int _fpsDebugCounter; private static long _fpsCounterStart; @@ -516,6 +518,23 @@ internal static class EndSceneHook } } + // ── Video patch frame cap ─────────────────────────────────── + // While the video patch skips AC's 3D scene, the loop would just spin faster on + // an empty frame: cap it (default 15 fps) so the time is slept. Stacks with the + // governor above (the lower rate wins); 0 = no cap (off, focused in "unfocused", + // outside the world, or /rc video fps 0). Game logic still runs every frame. + try + { + int vpCap = VideoPatch.FrameCapThisFrame(); + if (vpCap > 0) + { + double leftMs = 1000.0 / vpCap - _videoPatchTimer.Elapsed.TotalMilliseconds; + if (leftMs > 0) WaitFrame(Math.Min(leftMs, 1000.0 / VideoPatchPolicy.MinFrameCapFps)); + } + } + catch { /* never let the cap take EndScene down */ } + _videoPatchTimer.Restart(); + return _originalEndScene!(pDevice); } } diff --git a/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs b/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs index a64fc9c..f44632a 100644 --- a/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs +++ b/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs @@ -160,6 +160,8 @@ internal static class Nav3DRenderInjector { if (_markersRenderedThisFrame || dev == IntPtr.Zero) return; _markersRenderedThisFrame = true; + // Video patch: no 3D scene this frame, so no markers or plates over the black. + if (VideoPatch.SkipWorldThisFrame) return; _inRender = true; try { ImGuiBackend.DX9Backend.RenderNav3D(dev); } catch { } @@ -173,6 +175,13 @@ internal static class Nav3DRenderInjector private static bool PresentWorldOverlays(IntPtr dev, bool sceneViewport) { if (_markersRenderedThisFrame) return false; + // Video patch: the 3D scene wasn't drawn this frame; the overlays (projected with + // stale matrices) would float over black. Closed for the frame, nothing drawn. + if (VideoPatch.SkipWorldThisFrame) + { + _markersRenderedThisFrame = true; + return false; + } // Decal clients: VVS/Decal/UB draw 3D into their own render targets too; only AC's // back buffer gets the markers and nameplates (measured 2026-09-30: without this they // showed up inside a Virindi window). Checked once per frame, only with Decal. diff --git a/src/RynthCore.Engine/D3D9/VideoPatch.cs b/src/RynthCore.Engine/D3D9/VideoPatch.cs new file mode 100644 index 0000000..0861dc3 --- /dev/null +++ b/src/RynthCore.Engine/D3D9/VideoPatch.cs @@ -0,0 +1,589 @@ +// ============================================================================ +// RynthCore.Engine - D3D9/VideoPatch.cs +// The "video patch" (2026-10-05): stop the client drawing its 3D world (and, +// in "all", AC's 2D UI too) to save CPU and GPU on background clients. Game +// logic, physics, networking and the plugins keep running: only drawing stops. +// Written from scratch from AC's own frame (no third-party code). +// +// Where (addresses checked offline against our client, both copies; report in +// ops/overnight/2026-10-05-video-patch.md, Aeshnidae): +// Client::UseTime (0x00411FA0) runs the frame: ... SmartBox::UseTime (physics +// and object updates) -> SceneTool::StartFrame (Clear to black + BeginScene) +// -> SmartBox::Draw -> SceneTool::EndFrame (RenderUI::RenderObjects = AC's 2D +// UI, the debug HUDs, EndScene, Present) -> Device::DoFrameSleep. +// SmartBox::Draw (0x00455610) tail-jumps to SmartBox::DrawNoBlit (0x00454CC0), +// which sets the normal mode, updates the camera (SmartBox::update_viewer), +// calls SmartBox::RenderNormalMode (0x00453B40) when there is a viewer cell, +// then hands the mouse-pick result to the selection handler. +// RenderNormalMode is the whole 3D scene: FOV / view distance, the landscape +// or the cell's portal walk, objects, particles (RenderDevice vtable +0x48), +// then D3DPolyRender::FlushAlphaList(0) (the alpha-sorted foliage/effects) +// and two SmartBox callbacks: the targeting callback (+0x100, reports the +// selected object's on-screen box) and a post-render callback (+0x114). +// __thiscall, no stack arguments, plain `ret`: the detour returns without +// calling the original to skip the scene. update_viewer, the pick handling +// and everything outside SmartBox::Draw still run; the back buffer is still +// cleared by StartFrame, so the window shows black behind AC's UI. +// "All" also skips RenderUI::RenderObjects (AcUiPassHook asks SkipAcUiThisFrame). +// +// Safety: +// - A hook, not a byte patch: "off" (or the kill switch) is instant, and the +// detour only ever decides "call AC's original or not". +// - Kill switch: it is a UI hook slot named "VideoPatch" (UiHookRegistry): +// engine.json DisabledUiHooks ["VideoPatch"] keeps it out at the next start, +// /rc hooks off VideoPatch makes it a pass-through now. +// - Pattern first (HookResolver; tools\pe_pattern.py CHECK covers it), Decal +// guard (UiHookRegistry.TryInstall). Unresolved: logged once, and /rc video +// answers "unavailable". +// - Only in the world (PanelsLive's rule): login, character select and client +// teardown always draw. "All" never saves; a restart or an engine reload +// comes back with the character's saved mode (off/unfocused/world). +// - While the world is skipped, EndSceneHook caps the frame rate (FrameCapFps, +// default 15) so the freed time is slept, not spun. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.D3D9; + +internal static unsafe class VideoPatch +{ + // SmartBox::RenderNormalMode on the 4,841,472-byte client. Pattern is the source of truth. + private const int RenderNormalModeFallbackVa = 0x00453B40; + + // mov eax,[render device global]; sub esp,14h; push esi; mov esi,ecx; + // mov cl,[eax+0ACh]; test cl,cl; jz far (skip to FlushAlphaList); mov ecx,[esi+0Ch]; + // and ecx,0FFFFh; push ebx; cmp ecx,100h (cell id < 0x100 = outdoors); push edi; + // sbb edi,edi; neg edi; jnz +11h. Unique in the scanned window on both client copies + // (C:\Turbine and C:\Games\RynthCore\AcClient, 2026-10-05); the global and the jz + // target are wildcarded. + private static readonly byte?[] RenderNormalModePattern = + [ + 0xA1, null, null, null, null, + 0x83, 0xEC, 0x14, + 0x56, + 0x8B, 0xF1, + 0x8A, 0x88, 0xAC, 0x00, 0x00, 0x00, + 0x84, 0xC9, + 0x0F, 0x84, null, null, null, null, + 0x8B, 0x4E, 0x0C, + 0x81, 0xE1, 0xFF, 0xFF, 0x00, 0x00, + 0x53, + 0x81, 0xF9, 0x00, 0x01, 0x00, 0x00, + 0x57, + 0x1B, 0xFF, + 0xF7, 0xDF, + 0x75, 0x11, + ]; + + private static readonly UiHookSlot Slot = + UiHookRegistry.Register("VideoPatch", "SmartBox::RenderNormalMode - the 3D scene (video patch)", RenderNormalModeFallbackVa); + + private static IntPtr _origRenderNormalMode; + private static int _initialized; + + /// The hook is live (cleared first on shutdown, so the detour passes through). + public static volatile bool IsInstalled; + + // ── Mode and settings (any thread) ────────────────────────────────── + + private static volatile int _mode; // VideoPatchMode + private static volatile int _capFps = VideoPatchPolicy.DefaultFrameCapFps; + private static readonly object FileSync = new(); + private static VideoPatchPolicy.FileModel? _file; // under FileSync + private static string _loadedKey = string.Empty; // heartbeat thread + + public static VideoPatchMode Mode => (VideoPatchMode)_mode; + public static int FrameCapFps { get { EnsureFileLoaded(); return _capFps; } } + + // ── Per-frame decision (AC's render thread) ───────────────────────── + + private static int _decidedFrame = -1; + private static long _decidedAt; + private static VideoPatchDecision _frame; + private static readonly long DecisionMaxAge = Stopwatch.Frequency / 10; // 100 ms + private static readonly int OwnPid = Environment.ProcessId; + + // ── Counters (render thread writes; heartbeat reads) ──────────────── + + private static long _scenesSkipped, _scenesDrawn, _uiSkipped; + private static long _worldTicks; + private static int _worldFrames; + private static long _worldWindowStart; + /// AC's 3D scene cost per drawn frame, ms, over the last second (0 while skipped). + private static volatile float _worldMs; + + // ── Measurement (heartbeat thread) ────────────────────────────────── + + private const int RingSize = 5; + private static readonly float[] CpuRing = new float[RingSize], DrawRing = new float[RingSize], WorldRing = new float[RingSize]; + private static int _ringCount, _ringPos; + private static long _lastCpu100ns, _lastWallTicks; + private static float _lastCpuPct = -1; + private static long _lastSkipCount; + private static long _hbTick; + private static volatile string? _pendingChange; // "off -> world": the heartbeat logs "before" and arms "after" + private static long _afterDueTick; + private static string _afterLabel = string.Empty; + + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint pid); + [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess(); + [DllImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user); + + // ════════════════════════════════════════════════════════════════════ + // Install / uninstall + // ════════════════════════════════════════════════════════════════════ + + /// InitWorker step. Resolves and hooks SmartBox::RenderNormalMode. Idempotent. + public static void Initialize() + { + if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + Slot.Reason = "acclient.exe not available"; + RynthLog.Compat("VideoPatch: acclient.exe not available - unavailable."); + return; + } + if (!UiHookRegistry.SwitchedOn(Slot)) + return; + + HookResolver.ResolveResult r = HookResolver.Resolve(text, "VideoPatch.SmartBox::RenderNormalMode", RenderNormalModePattern, RenderNormalModeFallbackVa); + delegate* unmanaged[Thiscall] d = &RenderNormalModeDetour; + if (UiHookRegistry.TryInstall(Slot, r, (IntPtr)d, out IntPtr t)) + { + _origRenderNormalMode = t; + Thread.MemoryBarrier(); + if (UiHookRegistry.Enable(Slot)) + IsInstalled = true; + } + RynthLog.Compat(IsInstalled + ? $"VideoPatch: ready (SmartBox::RenderNormalMode @ 0x{Slot.Address.ToInt32():X8} via {Slot.Source}); mode stays off until /rc video or Settings." + : $"VideoPatch: unavailable - {Slot.Reason}."); + } + + /// + /// Engine shutdown / hot reload (lifecycle thread), with AcUiPassHook.Uninstall: the + /// detour passes straight to AC from here on, then the hook is disabled. Idempotent. + /// + public static void Uninstall() + { + if (!IsInstalled) return; + IsInstalled = false; + Thread.MemoryBarrier(); + int status = Hooking.MinHook.MH_DisableHook(Slot.Address); + RynthLog.Compat($"VideoPatch: uninstalled (disable = {Hooking.MinHook.StatusString(status)})."); + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] + private static void RenderNormalModeDetour(IntPtr smartBox) + { + bool skip = false; + try { skip = IsInstalled && CurrentFrame().SkipWorld; } + catch { /* draw normally */ } + if (skip) + { + Interlocked.Increment(ref _scenesSkipped); + return; + } + + long t0 = Stopwatch.GetTimestamp(); + ((delegate* unmanaged[Thiscall])_origRenderNormalMode)(smartBox); + long t1 = Stopwatch.GetTimestamp(); + Interlocked.Increment(ref _scenesDrawn); + _worldTicks += t1 - t0; + _worldFrames++; + if (_worldWindowStart == 0) _worldWindowStart = t1; + if (t1 - _worldWindowStart >= Stopwatch.Frequency) + { + _worldMs = _worldFrames > 0 ? (float)(_worldTicks * 1000.0 / Stopwatch.Frequency / _worldFrames) : 0f; + _worldTicks = 0; + _worldFrames = 0; + _worldWindowStart = t1; + } + } + + // ════════════════════════════════════════════════════════════════════ + // Per-frame decision (AC's render thread) + // ════════════════════════════════════════════════════════════════════ + + /// AC's 3D scene is (being) skipped this frame. Render thread. + public static bool SkipWorldThisFrame => _mode != 0 && IsInstalled && CurrentFrame().SkipWorld; + + /// AC's 2D UI is skipped this frame ("all"). Render thread (AcUiPassHook). + public static bool SkipAcUiThisFrame + { + get + { + if (_mode != (int)VideoPatchMode.All || !IsInstalled || !CurrentFrame().SkipAcUi) return false; + Interlocked.Increment(ref _uiSkipped); + return true; + } + } + + /// The "rendering paused" banner should draw (the ImGui frame asks). Render thread. + public static bool WantsBanner => _mode == (int)VideoPatchMode.All && IsInstalled && CurrentFrame().SkipAcUi; + + /// + /// The fps cap for the frame EndScene is finishing (0 = none). EndSceneHook, AC's render + /// thread, after the FPS governor. + /// + public static int FrameCapThisFrame() + { + if (_mode == 0 || !IsInstalled) return 0; + return VideoPatchPolicy.FrameCap(CurrentFrame(), _capFps); + } + + // One decision per frame (keyed by EndSceneHook's back-buffer frame count, and at most + // 100 ms old for a client whose EndScene isn't hooked), so the scene, the UI pass, the + // overlays, the banner and the cap of one frame agree. + private static VideoPatchDecision CurrentFrame() + { + int frame = EndSceneHook.BackBufferFrames; + long now = Stopwatch.GetTimestamp(); + if (frame != _decidedFrame || now - _decidedAt > DecisionMaxAge) + { + _decidedFrame = frame; + _decidedAt = now; + _frame = Evaluate(); + } + return _frame; + } + + private static VideoPatchDecision Evaluate() + { + var mode = (VideoPatchMode)_mode; + if (mode == VideoPatchMode.Off || !IsInstalled || !Slot.Enabled || EngineLifecycle.IsShuttingDown) + return VideoPatchDecision.None; + bool inWorld = LoginLifecycleHooks.HasObservedLoginComplete + && UiFlowHooks.InWorldOrUnknown + && !UiFlowHooks.ClientCleanupStarted; + bool focused = mode != VideoPatchMode.Unfocused || IsClientFocused(); + // "All" needs the banner/panels (our ImGui layer) and the UI-pass hook that skips + // AC's UI; without either it acts as "world". + bool uiSkippable = Plugins.EngineSettings.EnableImGuiBackend && AcUiPassHook.IsInstalled; + return VideoPatchPolicy.Decide(mode, inWorld, focused, uiSkippable); + } + + /// The game window, or any window of this process, is the foreground window (EndSceneHook's rule). + private static bool IsClientFocused() + { + IntPtr fg = GetForegroundWindow(); + if (fg == IntPtr.Zero) return false; + if (fg == ImGuiBackend.Win32Backend.GameHwnd) return true; + GetWindowThreadProcessId(fg, out uint pid); + return pid == (uint)OwnPid; + } + + // ════════════════════════════════════════════════════════════════════ + // Setting the mode + // ════════════════════════════════════════════════════════════════════ + + /// + /// Sets the mode now. : also store it for this character + /// (never for "all"). Any thread. Returns the reply for chat. + /// + public static string SetMode(VideoPatchMode mode, bool save, string source) + { + if (!IsInstalled && mode != VideoPatchMode.Off) + return $"Video patch unavailable: {Slot.Reason}."; + if (IsInstalled && !Slot.Enabled && mode != VideoPatchMode.Off) + return "Video patch is switched off (/rc hooks on VideoPatch to switch it back on)."; + + var old = (VideoPatchMode)_mode; + _mode = (int)mode; + _decidedFrame = int.MinValue; // the render thread decides again on its next look + Slot.Note("mode " + VideoPatchPolicy.Name(mode)); + string savedNote = string.Empty; + if (save) + { + if (VideoPatchPolicy.IsSaved(mode)) + { + string key = CurrentCharacterKey(); + lock (FileSync) + { + EnsureFileLoadedLocked(); + _file!.Set(key, mode); + SaveFileLocked(); + } + savedNote = key == VideoPatchPolicy.DefaultCharacterKey + ? " Saved as this PC's default (character name unknown)." + : " Saved for this character."; + } + else + { + savedNote = " This session only (\"all\" is never saved)."; + } + } + if (old != mode) + { + _pendingChange = $"{VideoPatchPolicy.Name(old)} -> {VideoPatchPolicy.Name(mode)}"; + RynthLog.Compat($"VideoPatch: mode {VideoPatchPolicy.Name(old)} -> {VideoPatchPolicy.Name(mode)} ({source})."); + } + return Describe(mode) + savedNote; + } + + /// Sets the frame cap used while the world is skipped (0 = none, else 5..60). Saved for the PC. + public static string SetFrameCap(int fps) + { + int cap = VideoPatchPolicy.ClampCap(fps); + lock (FileSync) + { + EnsureFileLoadedLocked(); + _file!.FrameCapFps = cap; + _capFps = cap; + SaveFileLocked(); + } + RynthLog.Compat($"VideoPatch: frame cap while patched -> {(cap > 0 ? cap + " fps" : "none")}."); + return cap > 0 + ? $"While the world isn't drawn the client runs at most {cap} fps (saved for this PC)." + : "No extra frame cap while the world isn't drawn (saved for this PC); the FPS limiter still applies."; + } + + private static string Describe(VideoPatchMode mode) => mode switch + { + VideoPatchMode.World => "Video patch: WORLD - AC's 3D world isn't drawn; AC's UI and the panels are. /rc video off to restore.", + VideoPatchMode.Unfocused => "Video patch: UNFOCUSED - the 3D world isn't drawn while another window has the focus; it draws again the moment you switch back.", + VideoPatchMode.All => "Video patch: ALL - nothing of AC's is drawn; the panels and a banner are. Type /rc video off (or Settings > Misc) to restore.", + _ => "Video patch: off - normal drawing.", + }; + + // ════════════════════════════════════════════════════════════════════ + // /rc video + // ════════════════════════════════════════════════════════════════════ + + /// /rc video [status|off|on|world|unfocused|all|fps <n>]. Returns the chat replies. + public static List HandleCommand(string args) + { + var replies = new List(); + string[] parts = (args ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (parts.Length == 0 || parts[0].Equals("status", StringComparison.OrdinalIgnoreCase)) + { + replies.AddRange(StatusLines()); + return replies; + } + if (parts[0].Equals("fps", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("cap", StringComparison.OrdinalIgnoreCase)) + { + if (parts.Length == 2 && int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int fps)) + replies.Add(SetFrameCap(fps)); + else + replies.Add($"Usage: /rc video fps <0|5-60> (now {(FrameCapFps > 0 ? FrameCapFps + " fps" : "none")})."); + return replies; + } + if (parts.Length == 1 && VideoPatchPolicy.TryParse(parts[0], out VideoPatchMode mode)) + { + replies.Add(SetMode(mode, save: true, "/rc video")); + return replies; + } + replies.Add("Usage: /rc video [status|off|world|unfocused|all|fps ]"); + return replies; + } + + public static List StatusLines() + { + EnsureFileLoaded(); + var lines = new List(); + if (!IsInstalled) + { + lines.Add($"Video patch unavailable: {Slot.Reason}."); + return lines; + } + var mode = (VideoPatchMode)_mode; + string active = mode == VideoPatchMode.Off ? "" : (Interlocked.Read(ref _scenesSkipped) > _lastSkipCount ? " (skipping now)" : " (drawing now)"); + lines.Add($"Video patch: {VideoPatchPolicy.Name(mode)}{active}{(Slot.Enabled ? "" : " - switched OFF (/rc hooks on VideoPatch)")}. " + + $"Saved for {CurrentCharacterKey()}: {VideoPatchPolicy.Name(SavedModeFor(CurrentCharacterKey()))}. " + + $"Frame cap while patched: {(_capFps > 0 ? _capFps + " fps" : "none")}."); + lines.Add($"Scenes drawn {Interlocked.Read(ref _scenesDrawn)}, skipped {Interlocked.Read(ref _scenesSkipped)}; AC UI passes skipped {Interlocked.Read(ref _uiSkipped)}; " + + $"3D scene cost {_worldMs:0.0} ms/frame; client CPU {(_lastCpuPct >= 0 ? _lastCpuPct.ToString("0.0", CultureInfo.InvariantCulture) + "%" : "n/a")} " + + $"(of all cores); {HookText()}."); + if (mode == VideoPatchMode.All && !(Plugins.EngineSettings.EnableImGuiBackend && AcUiPassHook.IsInstalled)) + lines.Add($"\"all\" acts as \"world\" here: {(Plugins.EngineSettings.EnableImGuiBackend ? "the UI-pass hook isn't installed (" + AcUiPassHook.Status + ")" : "the ImGui layer is off")}, so AC's UI keeps drawing."); + lines.Add("Modes: off | unfocused (world only while in the background) | world | all (session only). The phone live view shows what the client draws."); + return lines; + } + + private static string HookText() => $"hook @ 0x{Slot.Address.ToInt32():X8} via {Slot.Source}"; + + // ════════════════════════════════════════════════════════════════════ + // Settings file + // ════════════════════════════════════════════════════════════════════ + + private static string SettingPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "video_patch.txt"); + + private static string CurrentCharacterKey() => + VideoPatchPolicy.CharacterKey(SessionStateRegistry.LastServerName, SessionStateRegistry.LastCharacterName); + + private static VideoPatchMode SavedModeFor(string key) + { + lock (FileSync) + { + EnsureFileLoadedLocked(); + return _file!.ModeFor(key); + } + } + + private static void EnsureFileLoaded() + { + if (Volatile.Read(ref _file) != null) return; + lock (FileSync) EnsureFileLoadedLocked(); + } + + private static void EnsureFileLoadedLocked() + { + if (_file != null) return; + string[]? lines = null; + try + { + if (File.Exists(SettingPath)) lines = File.ReadAllLines(SettingPath); + } + catch (Exception ex) + { + RynthLog.Compat($"VideoPatch: could not read {SettingPath}: {ex.GetType().Name}: {ex.Message}"); + } + _file = VideoPatchPolicy.Parse(lines); + _capFps = _file.FrameCapFps; + } + + private static void SaveFileLocked() + { + try + { + string path = SettingPath; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllLines(path, VideoPatchPolicy.Serialize(_file!)); + } + catch (Exception ex) + { + RynthLog.Compat($"VideoPatch: could not write {SettingPath}: {ex.GetType().Name}: {ex.Message}"); + } + } + + // ════════════════════════════════════════════════════════════════════ + // Heartbeat: per-character load, CPU and before/after measurement + // ════════════════════════════════════════════════════════════════════ + + /// + /// HeartbeatLogger, once a second (its thread). Loads the character's saved mode + /// once the login is known, samples the process CPU, logs the before/after lines + /// around a mode change, and returns the heartbeat field (empty while off). + /// + public static string OnHeartbeat(int drawFps) + { + _hbTick++; + EnsureFileLoaded(); + float cpu = SampleCpuPercent(); + _lastCpuPct = cpu; + float worldMs = _worldMs; + long skips = Interlocked.Read(ref _scenesSkipped); + bool skipping = skips > _lastSkipCount; + _lastSkipCount = skips; + if (skipping) _worldMs = worldMs = 0f; // nothing drawn this second + + try { LoadForCharacter(); } + catch (Exception ex) { RynthLog.Compat($"VideoPatch: per-character load failed: {ex.GetType().Name}: {ex.Message}"); } + + // A mode change: "before" from the last seconds (this second is mixed, left out), + // "after" 10 s later from the 5 s before that. + string? change = Interlocked.Exchange(ref _pendingChange, null); + if (change != null) + { + RynthLog.Compat($"VideoPatch: {change} - before (last {Math.Min(_ringCount, RingSize)} s): {Averages()}."); + _afterDueTick = _hbTick + 10; + _afterLabel = change; + _ringCount = 0; + _ringPos = 0; + } + else + { + if (cpu >= 0) + { + CpuRing[_ringPos] = cpu; + DrawRing[_ringPos] = drawFps; + WorldRing[_ringPos] = worldMs; + _ringPos = (_ringPos + 1) % RingSize; + if (_ringCount < RingSize) _ringCount++; + } + if (_afterDueTick != 0 && _hbTick >= _afterDueTick) + { + _afterDueTick = 0; + RynthLog.Compat($"VideoPatch: {_afterLabel} - after (10 s on, last {Math.Min(_ringCount, RingSize)} s): {Averages()}."); + } + } + + var mode = (VideoPatchMode)_mode; + if (mode == VideoPatchMode.Off) return string.Empty; + string cpuText = cpu >= 0 ? cpu.ToString("0.0", CultureInfo.InvariantCulture) : "?"; + return $" vp={VideoPatchPolicy.Name(mode)}:{(skipping ? "skip" : "draw")} cpu={cpuText}%"; + } + + private static string Averages() + { + int n = Math.Min(_ringCount, RingSize); + if (n == 0) return "no samples yet"; + float c = 0, d = 0, w = 0; + for (int i = 0; i < n; i++) { c += CpuRing[i]; d += DrawRing[i]; w += WorldRing[i]; } + c /= n; d /= n; w /= n; + string frame = d > 0 ? (1000f / d).ToString("0.0", CultureInfo.InvariantCulture) + " ms" : "n/a"; + return string.Create(CultureInfo.InvariantCulture, + $"cpu={c:0.0}% of all cores, draw={d:0.0} fps (frame {frame}), 3D scene={w:0.00} ms/frame"); + } + + // Process CPU over the last heartbeat, as Task Manager shows it (share of all cores). + private static float SampleCpuPercent() + { + try + { + if (!GetProcessTimes(GetCurrentProcess(), out _, out _, out long kernel, out long user)) return -1; + long cpu = kernel + user; // 100 ns units + long wall = Stopwatch.GetTimestamp(); + float pct = -1; + if (_lastWallTicks != 0) + { + double wall100ns = (wall - _lastWallTicks) * 10_000_000.0 / Stopwatch.Frequency; + if (wall100ns > 0) + pct = (float)((cpu - _lastCpu100ns) * 100.0 / wall100ns / Math.Max(1, Environment.ProcessorCount)); + } + _lastCpu100ns = cpu; + _lastWallTicks = wall; + return pct; + } + catch + { + return -1; + } + } + + // The character's saved mode, applied when the client learns which character it is + // (login; an engine reload replays it). "All" is never saved, so a restart or a reload + // never comes back with AC's UI hidden. + private static void LoadForCharacter() + { + if (!LoginLifecycleHooks.HasObservedLoginComplete) return; + string key = CurrentCharacterKey(); + if (key == _loadedKey) return; + _loadedKey = key; + VideoPatchMode saved = SavedModeFor(key); + if (saved == (VideoPatchMode)_mode) return; + if (!IsInstalled) + { + if (saved != VideoPatchMode.Off) + RynthLog.Compat($"VideoPatch: {key} has '{VideoPatchPolicy.Name(saved)}' saved, but the hook is unavailable ({Slot.Reason})."); + return; + } + RynthLog.Compat($"VideoPatch: {key}: saved mode '{VideoPatchPolicy.Name(saved)}'."); + SetMode(saved, save: false, "saved for " + key); + } +} diff --git a/src/RynthCore.Engine/D3D9/VideoPatchPolicy.cs b/src/RynthCore.Engine/D3D9/VideoPatchPolicy.cs new file mode 100644 index 0000000..ebaecde --- /dev/null +++ b/src/RynthCore.Engine/D3D9/VideoPatchPolicy.cs @@ -0,0 +1,198 @@ +// ============================================================================ +// RynthCore.Engine - D3D9/VideoPatchPolicy.cs +// The pure part of the video patch (D3D9/VideoPatch.cs): the modes, what each +// one skips, the frame cap, and the settings file's text format. No engine, +// AC or file-system dependencies, so tools/VideoPatchTests compiles it in. +// +// Modes (also the Settings combo order, so the values are the combo indexes): +// Off normal. +// Unfocused World, only while the client window isn't the foreground window. +// World AC's 3D scene is not drawn; AC's 2D UI and our panels still are. +// All AC's 3D scene and AC's 2D UI are not drawn; our panels and a +// "rendering paused" banner are. Never saved (session only). +// +// Settings file (%LOCALAPPDATA%\RynthCore\video_patch.txt), one key=value a line: +// FrameCapFps=15 PC-wide: the fps cap while the world is skipped (0 = none) +// Aelrynth/Some Character=world per character ("/") +// Default=unfocused used when the client doesn't know its character +// Lines it doesn't understand are kept as they are. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace RynthCore.Engine.D3D9; + +internal enum VideoPatchMode +{ + Off = 0, + Unfocused = 1, + World = 2, + All = 3, +} + +/// What one frame skips. +internal readonly record struct VideoPatchDecision(bool SkipWorld, bool SkipAcUi) +{ + public static readonly VideoPatchDecision None = new(false, false); + public bool Any => SkipWorld || SkipAcUi; +} + +internal static class VideoPatchPolicy +{ + public const int DefaultFrameCapFps = 15; + public const int MinFrameCapFps = 5; + public const int MaxFrameCapFps = 60; + + public const string FrameCapKey = "FrameCapFps"; + public const string DefaultCharacterKey = "Default"; + + /// Settings combo labels, in enum order. + public static readonly string[] ComboItems = + { + "Off", + "World when unfocused", + "World (keep AC's UI)", + "All (session only)", + }; + + /// The command / file word for a mode. + public static string Name(VideoPatchMode mode) => mode switch + { + VideoPatchMode.Unfocused => "unfocused", + VideoPatchMode.World => "world", + VideoPatchMode.All => "all", + _ => "off", + }; + + /// Parses a command / file word. "on" means world (UtilityBelt's habit); "focus" means unfocused. + public static bool TryParse(string? text, out VideoPatchMode mode) + { + mode = VideoPatchMode.Off; + switch (text?.Trim().ToLowerInvariant()) + { + case "off": case "0": case "false": case "none": mode = VideoPatchMode.Off; return true; + case "on": case "1": case "true": case "world": case "3d": mode = VideoPatchMode.World; return true; + case "unfocused": case "focus": case "background": case "bg": mode = VideoPatchMode.Unfocused; return true; + case "all": case "full": case "everything": mode = VideoPatchMode.All; return true; + default: return false; + } + } + + /// + /// What a frame skips. Nothing outside the world (login, character select, portal + /// out to the character list, client teardown): there AC's screens are all UI, and + /// a skipped UI there would leave a black window nobody can type into. + /// : our ImGui layer is on (banner, panels) and AC's UI pass + /// is hooked. Without it "All" is "World", so AC's chat stays. + /// + public static VideoPatchDecision Decide(VideoPatchMode mode, bool inWorld, bool focused, bool uiSkippable) + { + if (!inWorld) return VideoPatchDecision.None; + return mode switch + { + VideoPatchMode.World => new(true, false), + VideoPatchMode.Unfocused => focused ? VideoPatchDecision.None : new(true, false), + VideoPatchMode.All => uiSkippable ? new(true, true) : new(true, false), + _ => VideoPatchDecision.None, + }; + } + + /// The fps cap for a frame (0 = none): the configured cap while the world is skipped. + public static int FrameCap(VideoPatchDecision decision, int configuredCapFps) => + decision.SkipWorld && configuredCapFps > 0 ? ClampCap(configuredCapFps) : 0; + + /// 0 stays 0 (no cap); anything else is held to 5..60. + public static int ClampCap(int fps) => fps <= 0 ? 0 : Math.Clamp(fps, MinFrameCapFps, MaxFrameCapFps); + + /// Only these modes are written to the file ("all" is session only). + public static bool IsSaved(VideoPatchMode mode) => mode != VideoPatchMode.All; + + /// The per-character key: "<server>/<character>", or "Default" without a character name. + public static string CharacterKey(string? server, string? character) + { + string c = (character ?? string.Empty).Trim(); + if (c.Length == 0) return DefaultCharacterKey; + string s = (server ?? string.Empty).Trim(); + // '=' would end the key early; neither name can hold one in AC, but be safe. + return (s.Length > 0 ? s + "/" + c : c).Replace('=', '_'); + } + + // ── The settings file ──────────────────────────────────────────────── + + internal sealed class FileModel + { + public int FrameCapFps = DefaultFrameCapFps; + /// Per-character saved modes (key = CharacterKey), case-insensitive. + public readonly Dictionary Modes = new(StringComparer.OrdinalIgnoreCase); + /// Lines this version doesn't understand, kept in order. + public readonly List Other = new(); + + /// The saved mode for a character; Off when none (and no "Default" line). + public VideoPatchMode ModeFor(string key) + { + if (Modes.TryGetValue(key, out VideoPatchMode m)) return m; + if (Modes.TryGetValue(DefaultCharacterKey, out m)) return m; + return VideoPatchMode.Off; + } + + /// Stores a character's mode; "all" is never stored, "off" removes the line. + public bool Set(string key, VideoPatchMode mode) + { + if (!IsSaved(mode)) return false; + if (mode == VideoPatchMode.Off) Modes.Remove(key); + else Modes[key] = mode; + return true; + } + } + + public static FileModel Parse(IEnumerable? lines) + { + var model = new FileModel(); + if (lines == null) return model; + foreach (string raw in lines) + { + string line = raw.Trim(); + if (line.Length == 0) continue; + int eq = line.LastIndexOf('='); + if (line.StartsWith('#') || eq <= 0) + { + model.Other.Add(raw); + continue; + } + string key = line[..eq].Trim(); + string value = line[(eq + 1)..].Trim(); + if (key.Equals(FrameCapKey, StringComparison.OrdinalIgnoreCase)) + { + if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int fps)) + model.FrameCapFps = ClampCap(fps); + continue; + } + if (TryParse(value, out VideoPatchMode mode) && IsSaved(mode)) + { + if (mode != VideoPatchMode.Off) model.Modes[key] = mode; + continue; + } + model.Other.Add(raw); + } + return model; + } + + public static List Serialize(FileModel model) + { + var lines = new List + { + "# RynthCore video patch: /=off|unfocused|world, Default=... without a name. /rc video", + $"{FrameCapKey}={model.FrameCapFps.ToString(CultureInfo.InvariantCulture)}", + }; + var keys = new List(model.Modes.Keys); + keys.Sort(StringComparer.OrdinalIgnoreCase); + foreach (string key in keys) + lines.Add($"{key}={Name(model.Modes[key])}"); + foreach (string other in model.Other) + if (!other.TrimStart().StartsWith("# RynthCore video patch", StringComparison.Ordinal)) + lines.Add(other); + return lines; + } +} diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index 27bc9e2..990338b 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -136,6 +136,8 @@ internal static class EngineLifecycle // AC's UI-pass hook draws the world overlays mid-frame from the same render-side // state EndSceneHook.Uninstall tears down: stop it first (its 80 ms drain covers both). Step("AcUiPassHook.Uninstall", () => AcUiPassHook.Uninstall()); + // The video patch's scene hook passes straight to AC from here on (AC draws again). + Step("VideoPatch.Uninstall", () => VideoPatch.Uninstall()); Step("EndSceneHook.Uninstall", () => EndSceneHook.Uninstall()); // Give in-flight EndScene calls a chance to drain. AC's render thread @@ -173,6 +175,7 @@ internal static class EngineLifecycle // it outlived this generation and locked the next one out of the file. Step("ChatModel.CloseLog", () => UI.Data.ChatModel.CloseLog()); Step("ServerMessageStream.Shutdown", () => Net.ServerMessageStream.Shutdown()); + Step("FlightRecorder.Shutdown", () => Net.FlightRecorder.Shutdown()); Step("PluginManager.ShutdownAll (defensive)", () => PluginManager.ShutdownAll()); diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index a61602b..3dc855a 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -698,8 +698,13 @@ public static class EntryPoint // RenderUI::RenderObjects: the world overlays (nameplates, Nav3D markers) draw at // the start of AC's 2D UI pass, after all 3D incl. foliage (2026-10-04). Step("UI-pass overlay hook", AcUiPassHook.Initialize); + // SmartBox::RenderNormalMode: the video patch (/rc video) skips AC's 3D scene on + // request; off until asked. Kill switch: engine.json DisabledUiHooks ["VideoPatch"]. + Step("video patch hook", VideoPatch.Initialize); Step("vendor hooks", VendorHooks.Initialize); Step("chat callback hooks", ChatCallbackHooks.Initialize); + // Flight recorder (Net/FlightRecorder.cs): before the packet hooks that feed it. + Step("flight recorder", Net.FlightRecorder.Initialize); Step("raw packet hooks", RawPacketHooks.Initialize); Step("property-update hooks", PropertyUpdateHooks.Initialize); Step("auto-id service", AutoIdService.Start); diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 681d284..c6eaba0 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -127,8 +127,8 @@ internal static class EngineFrameController // between launches. Allocated once, kept alive for the process lifetime. try { - const string iniPath = @"C:\Games\RynthSuite\RynthAi\imgui.ini"; - System.IO.Directory.CreateDirectory(@"C:\Games\RynthSuite\RynthAi"); + string iniPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini"); + System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir); IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath); unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; } RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}"); @@ -500,7 +500,8 @@ internal static class EngineFrameController if (Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled) return true; if (!PanelsLive) return false; ImGuiPanelHost.RestoreOnce(); - return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame; + return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame + || D3D9.VideoPatch.WantsBanner; } /// @@ -543,7 +544,7 @@ internal static class EngineFrameController } private static bool HasImGuiContentNoRestore() => - Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame)); + Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner)); // Keyboard owner between the stacks (plan §3.2 d): whichever side started // text entry most recently keeps the keyboard. @@ -661,7 +662,10 @@ internal static class EngineFrameController { // World overlays: built into UnderUiLayer's list, drawn next frame at // AC's 3D->UI transition (under AC's UI and every panel), no input. - Hud.MonsterHud.Draw(_uiScale); + // Video patch: with no 3D scene only the screen-fixed player plate draws. + Hud.MonsterHud.Draw(_uiScale, worldVisible: !D3D9.VideoPatch.SkipWorldThisFrame); + // Video patch "all": the "rendering paused" banner (background list, under the panels). + VideoPatchBanner.Draw(); if (ImGuiBar.Visible) ImGuiBar.Draw(_uiScale); ImGuiPanelHost.DrawAll(_uiScale); diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index b4da640..a861eae 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -45,7 +45,8 @@ internal static class ImGuiBar bool ImGuiOnly = false); // Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button. - private static readonly string[] ImGuiOnlyBarPanels = { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title }; + private static readonly string[] ImGuiOnlyBarPanels = + { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title }; // Known panels' icons (DrakBot's where the same window exists); others show their first letter. private static readonly Dictionary PanelIcons = new(StringComparer.OrdinalIgnoreCase) @@ -69,6 +70,8 @@ internal static class ImGuiBar ["Status"] = PhosphorIcons.Info, ["Inventory"] = PhosphorIcons.Package, // not Backpack: the dashboard's Items launcher has that ["Log"] = PhosphorIcons.TerminalWindow, + ["Item Count"] = PhosphorIcons.Bag, + ["Mini Remote"] = PhosphorIcons.SquaresFour, }; /// A panel's bar icon: its Phosphor icon, else its first letter (letter = true). diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs index a0a83d6..70cea94 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -676,7 +676,7 @@ internal static unsafe class ImGuiPopOuts public static string? RequestSnapshot(string title) { if (!Pops.TryGetValue(title, out PopOut? pop)) return null; - string path = System.IO.Path.Combine(@"C:\Games\RynthCore\Logs", $"popout_{title.Replace(' ', '_')}.bmp"); + string path = System.IO.Path.Combine(LogPaths.LogDirectory, $"popout_{title.Replace(' ', '_')}.bmp"); pop.Surface.SnapshotPath = path; pop.HotFrames = Math.Max(pop.HotFrames, 2); return path; diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs index 326ba6f..6e1476e 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs @@ -714,16 +714,24 @@ internal static class MonsterHud public ImDrawListPtr Dl; } - /// AC's render thread, inside the ImGui frame (between NewFrame and Render). - public static void Draw(float uiScale) + /// + /// AC's render thread, inside the ImGui frame (between NewFrame and Render). + /// false (the video patch skipped AC's 3D scene): only + /// the screen-fixed player plate draws; the world-anchored plates and combat text don't + /// (nothing to anchor them to, and no invisible plate takes a click). + /// + public static void Draw(float uiScale, bool worldVisible = true) { if (!_hasContent) { ResetClick(); PlayerPlate.DropDrag(); return; } try { if (!TryBeginFrame(uiScale, out Frame f)) { ResetClick(); PlayerPlate.DropDrag(); return; } - DrawPlates(ref f, MonsterHudSettings.Enabled); - PlayerPlate.Draw(ref f); - CombatText.Draw(ref f); + if (worldVisible) + { + DrawPlates(ref f, MonsterHudSettings.Enabled); + PlayerPlate.Draw(ref f); + CombatText.Draw(ref f); + } // The player plate fixed on screen: ImGui's background list (the normal UI pass), not the layer above. PlayerPlate.DrawScreen(ref f); } diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 5eb4e05..1886ef2 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -3,14 +3,17 @@ // ImGui face of the RynthChat rule editor (the old Avalonia face is // UI/Panels/RynthChatFiltersPanel.cs). One card per rule: // -// [#] [on] [regex ..........................] [up] [down] [delete] +// [#] [on] [Contains v] [pattern ...................] [up] [down] [delete] // When [Any line v] [Move to v] [Junk v] [Colour line v] [swatch] // (a regex error, a timed-out rule, a missing tab, or its hit count) // // The order and what each action does are spelled out in the header lines -// (and in UI/Data/ChatData.cs). Below the rules: Add, Import / Export (the -// clipboard, JSON), and a test box - paste a line, pick where it came from, -// and see which rules match and where it ends up. The test runs on an edit, +// (and in UI/Data/ChatData.cs). A pattern is plain text (Contains, Starts +// with, Ends with) or a regex (ChatRuleMatching.cs). Below the rules: Add, +// Standard filters (ready-made Hide rules, ChatFilterPresets.cs), Import / +// Export (the clipboard, JSON), and a test box - paste a line, pick where it +// came from, and see which rules match and where it ends up, which standard +// filter would catch it, or make a rule from it. The test runs on an edit, // never per frame; the chat itself is routed on the pump. // // The rules live in ChatModel. Each edit applies (the pump re-routes the @@ -62,12 +65,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel private int _testSourceSeen = -1; private long _testVersion = -1; private readonly List<(string Text, uint Color)> _testResult = new(); + private string _testLine = ""; // the tested text, timestamp removed ("Make rule" uses it) public void OnShown() => ChatModel.EnsureSettingsLoaded(); private const string AddLabel = PhosphorIcons.Plus + " Add rule"; private const string ImportLabel = PhosphorIcons.ClipboardText + " Import"; private const string ExportLabel = PhosphorIcons.Copy + " Export"; + private const string PresetsLabel = PhosphorIcons.ListChecks + " Standard filters"; + private const string MakeRuleLabel = PhosphorIcons.Plus + " Make rule"; private const string Caret = " " + PhosphorIcons.CaretDown; private static readonly string[] ActionLabels = { "Move to", "Copy to", "Hide", "Colour only" }; @@ -79,6 +85,20 @@ internal sealed class ChatFiltersFace : IImGuiPanel "Colour only: no routing; the rule just colours.", }; private static readonly string[] ColorLabels = { "No colour", "Colour line", "Colour match" }; + private static readonly string[] ModeHelp = + { + "Regex: a case-insensitive regular expression (^ start, $ end, \\d+ a number...).", + "Contains: the text anywhere in the line. Any case; . ( * \" are just characters.", + "Starts with: the line begins with the text. Any case.", + "Ends with: the line ends with the text. Any case.", + }; + private static readonly string[] ModeHints = + { + "regex, e.g. ^You have been healed", + "text, e.g. evaded your attack", + "text, e.g. You say, \"", + "text, e.g. has expired.", + }; public void Draw() { @@ -94,7 +114,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel } ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text, as a case-insensitive regex.", Mute); + Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text: plain text (any case) or a regex.", Mute); Label("Where it shows: Copy rules add a tab and go on; the first Move or Hide that matches decides.", Mute); Label("Colour: the first \"Colour line\" wins; \"Colour match\" colours every match (a higher rule wins an overlap).", Mute); ImGuiNET.ImGui.PopFont(); @@ -127,10 +147,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel if (Button("##add", AddLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(AddLabel) + 4, 24), Text, AddBg)) { // An empty pattern matches nothing until typed; saved now so the row survives a relaunch mid-edit. - var rule = new ChatFilterRule(); + // New rules are plain text (Contains); rules made from a chat line stay regexes. + var rule = new ChatFilterRule { Mode = ChatMatchMode.Contains }; edit = () => ChatModel.AddRule(rule); } - bx += ButtonWidth(AddLabel) + 8; + bx += ButtonWidth(AddLabel) + 4; + if (Button("##presets", PresetsLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(PresetsLabel), 24), Text, BtnFill)) + OpenPresetPicker(new Vector2(bx, ap.Y)); + ImGuiNET.ImGui.SetItemTooltip("Ready-made rules that hide common game spam (spell words, evades, busy...).\nPicking one adds it as a Hide rule you can edit or delete."); + bx += ButtonWidth(PresetsLabel) + 8; if (Button("##import", ImportLabel, new Vector2(bx, ap.Y), new Vector2(ButtonWidth(ImportLabel), 24), Text, BtnFill)) Flash(ChatModel.ImportRules(ChatModel.GetClipboardText())); ImGuiNET.ImGui.SetItemTooltip("Add the rules on the clipboard (an Export, or a rynthchat_settings.json) after these."); @@ -186,8 +211,21 @@ internal sealed class ChatFiltersFace : IImGuiPanel const float btn = 22; float x = p.X + 42; + int modeIdx = (int)r.Mode; + string modeText = ChatRuleMatching.Labels[modeIdx] + Caret; + float modeW = ButtonWidth(ChatRuleMatching.Labels[2] + Caret); // the widest, so patterns line up + ChatFilterRule moded = r; + if (Button("##mode", modeText, new Vector2(x, p.Y), new Vector2(modeW, rowH), Text, BtnFill, leftAlign: true)) + _picker.Open(new Vector2(x, p.Y + rowH + 2), ChatRuleMatching.Labels, modeIdx, k => + { + moded.Mode = (ChatMatchMode)k; + moded.Recompile(); + ChatModel.FiltersChanged(); + }, 120); + ImGuiNET.ImGui.SetItemTooltip(ModeHelp[modeIdx]); + x += modeW + 4; float patW = Math.Max(80, card.X + rowW - 4 - 3 * (btn + 2) - 4 - x); - if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, "regex, e.g. ^You have been healed", out bool patActive)) + if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, ModeHints[modeIdx], out bool patActive)) { r.Pattern = Utf8(b.Pattern); r.Recompile(); @@ -255,7 +293,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel rule.ColorMode = (ChatColorMode)k; ChatModel.FiltersChanged(); }, 130); - ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the regex matched."); + ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the rule matched."); if (r.ColorMode != ChatColorMode.None) { Vector2 sPos = flow.Place(rowH); @@ -314,7 +352,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel private static (string? Note, uint Color) RuleNote(ChatFilterRule r) { - if (r.Pattern.Length == 0) return ("Type a pattern: the rule matches nothing until then.", Faded(Mute)); + if (r.Pattern.Trim().Length == 0) return ("Type a pattern: the rule matches nothing until then.", Faded(Mute)); if (r.Invalid) return ("Regex error: " + (r.Error ?? "doesn't compile"), Red); if (r.Slow) return ("Too slow: matching it took too long (see the RynthCore log), so the rule is skipped. Edit the pattern to try again.", Amber); if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy && r.Tab.Length == 0) @@ -341,6 +379,20 @@ internal sealed class ChatFiltersFace : IImGuiPanel } } + /// The standard filters; a tick marks the ones already in the rules (picking one again turns it on). + private void OpenPresetPicker(Vector2 at) + { + ChatFilterPreset[] presets = ChatFilterPresets.All; + var labels = new string[presets.Length]; + for (int k = 0; k < presets.Length; k++) + { + ChatFilterRule? have = ChatModel.FindPresetRule(presets[k]); + string mark = have == null ? " " : have.Enabled ? PhosphorIcons.Check + " " : "(off) "; + labels[k] = mark + presets[k].PickerLabel; + } + _picker.Open(at + new Vector2(0, 26), labels, -1, k => Flash(ChatModel.AddPresetRule(presets[k])), 300); + } + private void OpenWhenPicker(ChatFilterRule rule, Vector2 at) { var labels = new string[ChatModel.Conditions.Length]; @@ -427,7 +479,18 @@ internal sealed class ChatFiltersFace : IImGuiPanel Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); string srcLabel = "from: " + ChatModel.Conditions[_testSource].Label + Caret; float srcW = Math.Min(ButtonWidth(srcLabel), 230); - TextBox("##test", _test, p, Math.Max(80, w - srcW - 4), "e.g. Bob tells you, \"hi\"", out _); + float makeW = ButtonWidth(MakeRuleLabel); + TextBox("##test", _test, p, Math.Max(80, w - srcW - makeW - 8), "e.g. Bob tells you, \"hi\"", out _); + var mp = new Vector2(p.X + w - srcW - makeW - 4, p.Y); + if (Button("##makerule", MakeRuleLabel, mp, new Vector2(makeW, 22), Text, AddBg, _testLine.Length > 0)) + { + // Plain text, held to where the line came from; pick what it does on the new card. + string when = ChatModel.Conditions[_testSource].Value; + string pattern = _testLine.Length > 140 ? _testLine[..140] : _testLine; + ChatModel.AddRule(new ChatFilterRule { Mode = ChatMatchMode.Contains, Pattern = pattern, When = when }); + Flash("Made a Contains rule from the test line: trim it down and pick what it does."); + } + ImGuiNET.ImGui.SetItemTooltip("Add a rule that matches this line as plain text (Contains), for lines from the source picked here."); var sp = new Vector2(p.X + w - srcW, p.Y); if (Button("##testsrc", srcLabel, sp, new Vector2(srcW, 22), Text, BtnFill, leftAlign: true)) { @@ -468,6 +531,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel text = text.Trim(); // A line copied from the chat starts with its timestamp; the rules never see that. if (text.Length > 9 && text[2] == ':' && text[5] == ':' && text[8] == ' ' && char.IsDigit(text[0])) text = text[9..]; + _testLine = text; if (text.Length == 0) { _testResult.Add(("Paste a line to see which rules match and where it goes.", Faded(Mute))); return; } string when = ChatModel.Conditions[_testSource].Value; @@ -498,6 +562,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel } uint color = RynthTheme.Argb(route.LineArgb ?? ChatModel.ChannelArgb(channel)); _testResult.Add((where + (route.LineArgb != null ? " (this is its colour)" : ""), route.Hidden ? Faded(Mute) : color)); + + // Not hidden: name a standard filter that would hide it (one not in the rules yet). + if (!route.Hidden) + foreach (ChatFilterPreset preset in ChatFilterPresets.All) + if (preset.Matches(text, channel, type) && ChatModel.FindPresetRule(preset) == null) + { + _testResult.Add(($"Standard filter \"{preset.PickerLabel}\" would hide it (Standard filters, above).", Teal)); + break; + } } /// Buffers for each rule; refilled from the rules when another face changed them, diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index 8203e1d..296dbe0 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -122,6 +122,7 @@ internal sealed partial class InventoryFace : IImGuiPanel InventoryModel.Hover(0); InventoryModel.Unsubscribe(); _dragItem = _pressItem = null; + UiDropTargets.EngineDragObject = 0; _lootAdd.Cancel(); } @@ -152,6 +153,7 @@ internal sealed partial class InventoryFace : IImGuiPanel InventoryModel.Hover(_dragItem == null ? _hover?.Id ?? 0 : 0); FinishDrag(); + UiDropTargets.EngineDragObject = _dragItem?.Id ?? 0; End(origin, size); Tooltip(); @@ -756,6 +758,10 @@ internal sealed partial class InventoryFace : IImGuiPanel DropOn(t.Kind, t.Id, t.Name, item); return; } + // Let go outside this panel: another engine panel that takes items (Item Count, + // Mini Remote, the Loot Editor) gets it, as with a drag out of AC's own inventory. + if (!ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem)) + UiDropTargets.TryClaim(item.Id, 0, out _); } } diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs new file mode 100644 index 0000000..72f5d93 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs @@ -0,0 +1,249 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ItemCountFace.cs +// The Item Count panel: chosen items by name, each with how many the character +// carries (every stack with that name, whole stacks summed; worn ones too, so +// wielded arrows count). Engine only, ImGui only. (An idea from Silentkelpie's +// rynth PR #1, done as an engine face.) +// +// add row a text box (Enter adds), Add, and "add the selected item" +// rows icon, name, count (amber when none carried); X removes +// drop drag an item from the game's inventory (or the Inventory panel) +// onto the panel to add its name (UiDropTargets) +// +// Data: InventoryModel's published view (the face subscribes while open) and +// ItemHudStore (item_huds.txt, per character). Draw reads snapshots and posts +// edits; no AC calls except a dropped item's name when it isn't carried (the +// Loot Editor's way); no file I/O; counts are worked out when the view or the +// list changes, not per frame. +// ============================================================================ + +using System; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.Data; +using RynthCore.Engine.UI.ScriptWindows; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class ItemCountFace : IImGuiPanel +{ + public const string Title = "Item Count"; + private const string DropKey = "ItemCount"; + + public static void Register() + { + ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(250, 230), new Vector2(170, 110), EdgeToEdge: true, GripInBody: true), + () => new ItemCountFace()); + ItemHudStore.EnsureLoadQueued(); + } + + private const float RowH = 22f, Icon = 18f, XW = 18f; + + private readonly byte[] _input = new byte[ItemHudCharacter.MaxNameLength + 1]; + private readonly HudItemCache _items = new(); + private string _message = ""; + private uint _messageColor; + private long _messageUntilMs; + + // Counts for the shown list, rebuilt when the carried items or the list change. + private int _countsItemsVersion = -1; + private ItemHudCharacter? _countsFor; + private string[] _countText = Array.Empty(); + private bool[] _none = Array.Empty(); + private uint[] _iconId = Array.Empty(); + + public void OnShown() + { + ItemHudStore.EnsureLoadQueued(); + InventoryModel.Subscribe(); + } + + public void OnHidden() => InventoryModel.Unsubscribe(); + + public void Draw() + { + float w = Begin(out Vector2 origin, out Vector2 size); + InventoryView view = InventoryModel.Current; + HudItem[] items = _items.Get(view); + ItemHudCharacter data = ItemHudStore.Current; + + DrawAddRow(w, view, items); + DrawStatus(view); + float bodyH = Math.Max(30, Remaining(origin, size) - GripOverlap()); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); + ImGuiNET.ImGui.BeginChild("##itemcount_rows", new Vector2(w, bodyH)); + DrawRows(data, items); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + End(origin, size); + + AcceptDrops(origin, size, items); + } + + // ── Add row ───────────────────────────────────────────────────────── + + private void DrawAddRow(float w, InventoryView view, HudItem[] items) + { + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 22, iconW = 22; + string addLabel = PhosphorIcons.Plus + " Add"; + float addW = ButtonWidth(addLabel); + float boxW = Math.Max(50, w - addW - iconW - 8); + bool ready = ItemHudStore.Loaded && ItemHudStore.HasCharacter; + + bool enter = TextBox("##itemcount_input", _input, start, boxW, "Item name", out _, ImGuiInputTextFlags.EnterReturnsTrue, h); + bool add = Button("##itemcount_add", addLabel, new Vector2(start.X + boxW + 4, start.Y), new Vector2(addW, h), Text, BtnFill, enabled: ready); + ImGuiNET.ImGui.SetItemTooltip("Count this item (Enter in the box does the same). The name must match the item's name; any case."); + if (enter || add) + { + string text = Utf8(_input); + if (Add(text)) WriteUtf8(_input, ""); + } + + uint sel = InventoryModel.SelectedItem; + bool haveSel = ready && sel != 0 && ItemHudMath.TryFind(items, sel, out _); + if (IconButton("##itemcount_sel", PhosphorIcons.Crosshair, new Vector2(start.X + boxW + 4 + addW + 4, start.Y), new Vector2(iconW, h), Text, BtnFill, enabled: haveSel)) + { + if (ItemHudMath.TryFind(items, sel, out HudItem it)) Add(it.Name); + } + ImGuiNET.ImGui.SetItemTooltip(haveSel ? "Count the selected item" : "Select an item in your inventory to count it (or drag one onto this panel)"); + NextLine(start, h + 4); + } + + private bool Add(string name) + { + string msg = ""; + bool ok = ItemHudStore.Update(d => d.WithCount(name, out msg), out string why); + if (!ok) { ShowMessage(why, Amber); return false; } + bool added = msg.StartsWith("Counting", StringComparison.Ordinal); + ShowMessage(msg, added ? Mute : Amber); + return added; + } + + private void ShowMessage(string text, uint color) + { + _message = text; + _messageColor = color; + _messageUntilMs = Environment.TickCount64 + 3000; + } + + private void DrawStatus(InventoryView view) + { + if (_message.Length > 0 && Environment.TickCount64 < _messageUntilMs) { Label(_message, _messageColor); return; } + if (!ItemHudStore.Loaded) Label("Loading...", Mute); + else if (!ItemHudStore.HasCharacter || view.PlayerId == 0) Label("Waiting for your character...", Mute); + else Label("Carried (all stacks):", Faded(Mute)); + } + + // ── Rows ──────────────────────────────────────────────────────────── + + private void RefreshCounts(ItemHudCharacter data, HudItem[] items) + { + if (ReferenceEquals(data, _countsFor) && _countsItemsVersion == _items.Version) return; + _countsFor = data; + _countsItemsVersion = _items.Version; + int n = data.Counts.Length; + _countText = new string[n]; + _none = new bool[n]; + _iconId = new uint[n]; + for (int i = 0; i < n; i++) + { + long c = ItemHudMath.Count(items, data.Counts[i]); + _countText[i] = c.ToString("N0", CultureInfo.InvariantCulture); + _none[i] = c == 0; + _iconId[i] = _items.IdOf(data.Counts[i]); + } + } + + private void DrawRows(ItemHudCharacter data, HudItem[] items) + { + float bw = ImGuiNET.ImGui.GetContentRegionAvail().X; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + if (data.Counts.Length == 0) + { + Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(6, 6); + dl.AddText(at, Faded(Mute), "Nothing counted yet: type a name above,\nor drag an item here."); + return; + } + RefreshCounts(data, items); + + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + float fontH = ImGuiNET.ImGui.GetFontSize(); + int remove = -1; + for (int i = 0; i < data.Counts.Length; i++) + { + var p = new Vector2(start.X, start.Y + i * RowH); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.PushID(i); + ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(bw - XW, RowH)); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + if (hot) ImGuiNET.ImGui.SetItemTooltip($"{data.Counts[i]}: {_countText[i]} carried"); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + bw - XW, p.Y)); + if (ImGuiNET.ImGui.InvisibleButton("##x", new Vector2(XW, RowH))) remove = i; + bool hotX = ImGuiNET.ImGui.IsItemHovered(); + if (hotX) ImGuiNET.ImGui.SetItemTooltip("Stop counting"); + ImGuiNET.ImGui.PopID(); + + uint bg = hot ? Lighten(PanelBg) : (i & 1) == 1 ? RowAlt : 0; + if (bg != 0) dl.AddRectFilled(p, p + new Vector2(bw, RowH), bg); + Vector2 ip = new(p.X + 3, p.Y + (RowH - Icon) * 0.5f); + if (_iconId[i] != 0 && ScriptIcons.TryGet(ScriptIconKind.Object, _iconId[i], out IntPtr tex)) + dl.AddImage(tex, ip, ip + new Vector2(Icon, Icon)); + else + dl.AddRect(ip, ip + new Vector2(Icon, Icon), Faded(BtnBord), 2); + + float ty = p.Y + (RowH - fontH) * 0.5f; + Vector2 cs = ImGuiNET.ImGui.CalcTextSize(_countText[i]); + float countX = p.X + bw - XW - 6 - cs.X; + dl.PushClipRect(new Vector2(p.X + Icon + 8, p.Y), new Vector2(countX - 6, p.Y + RowH), true); + dl.AddText(new Vector2(p.X + Icon + 8, ty), _none[i] ? Faded(Text) : Text, data.Counts[i]); + dl.PopClipRect(); + dl.AddText(new Vector2(countX, ty), _none[i] ? Amber : Teal, _countText[i]); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.X, new Vector2(p.X + bw - XW, p.Y), new Vector2(XW, RowH), + hotX ? Red : Faded(Mute)); + } + ImGuiNET.ImGui.SetCursorScreenPos(start); + ImGuiNET.ImGui.Dummy(new Vector2(bw, data.Counts.Length * RowH)); + + if (remove >= 0) + { + string name = data.Counts[remove]; + if (ItemHudStore.Update(d => d.WithoutCount(d.IndexOfCount(name)), out string why)) + ShowMessage($"Stopped counting \"{name}\".", Mute); + else ShowMessage(why, Amber); + } + } + + // ── Drops (an item dragged from the game's inventory or the Inventory panel) ── + + private void AcceptDrops(Vector2 origin, Vector2 size, HudItem[] items) + { + bool can = ItemHudStore.Loaded && ItemHudStore.HasCharacter; + UiDropTargets.Publish(DropKey, Title, origin, origin + size, can); + if (UiDropTargets.TryTake(DropKey, out uint itemId) && can) + { + string name = NameOf(itemId, items); + if (name.Length > 0) Add(name); + else ShowMessage("That item's name isn't known yet; try again in a moment.", Amber); + } + + if (!can || !UiDropTargets.AnyDragInProgress) return; + bool over = UiDropTargets.IsCursorOver(DropKey); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRect(origin + new Vector2(1, 1), origin + size - new Vector2(1, 1), over ? Green : Teal, 4, ImDrawFlags.None, over ? 3f : 1.5f); + } + + /// A dropped item's name: from the carried items, else the client's (a corpse's or chest's item). + internal static string NameOf(uint itemId, HudItem[] items) + { + if (ItemHudMath.TryFind(items, itemId, out HudItem it) && it.Name.Length > 0) return it.Name; + if (ClientObjectHooks.TryGetSnapshotName(itemId, out string n) && n.Length > 0) return n; + return ClientObjectHooks.TryGetObjectName(itemId, out n) ? n ?? string.Empty : string.Empty; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs new file mode 100644 index 0000000..a7115c7 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs @@ -0,0 +1,671 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MetaFace.Editor.cs +// The Meta panel's rule editor and its state pickers (2026-10-05 clean-up): +// +// [<- Back] Edit rule Saved +// State: [Combat v] +// +- Conditions ------ [+ Add] -+ +- Actions --------- [+ Add] -+ +// | [Landblock == v] | | [Chat Command v] | +// | [A9B40000 ][Set current] | | [/say hello ] | +// +-----------------------------+ +-----------------------------+ +// [Revert] [Delete rule] +// +// Conditions and Actions sit side by side, each scrolling on its own; under +// SideBySideMinWidth they stack. "+ Add" turns a single condition into the +// first of an All (a single action into the first of a DoAll), or adds one +// more to an All / Any / DoAll. +// +// 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 +// condition and action are filled in: MetaRuleEdit.ReadyToAdd) or +// update_rule, and RynthAi writes the file. Back, closing the panel and switching metas save +// at once. update_rule keeps the running rule's fired latch (RynthAi +// MetaRuleEdits), so a save never re-fires a rule, restarts the state's +// clocks or changes the current state. +// +// New states: every state picker (the rule's State, Set / Call Meta State +// targets, the bottom bar) ends with "+ New state...". Picking it turns the +// picker into a name box with OK / Cancel (Enter / Esc); the name is trimmed, +// must not be empty, contain { } or match an existing state (ignoring case, +// as RynthAi does). A state exists only while a rule uses it (RynthAi lists +// its rules' states; the .af file has a STATE: block per state with rules), +// so a new state is never left empty: +// - the rule's own State picker moves this rule into it; +// - a Set / Call Meta State target and the bottom bar add an empty +// Never -> None rule in it at once (it never fires; edit or delete it). +// The bottom bar also makes it the current state, like any state picked +// there, and opens that rule. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class MetaFace +{ + /// Under this width Conditions and Actions stack instead of sitting side by side. + private const float SideBySideMinWidth = 400; + + private MetaRuleDto? _editOriginal; // as opened (Revert); null for a new rule + private MetaRuleDto? _lastSaved; // as last sent to RynthAi; finds the rule again by content + private bool _editChanged; // set by this frame's widgets + private bool _typingNow, _editTyping; // a data box is being typed in (this frame / last frame) + private bool _editConfirmDelete; + private string _editFile = string.Empty; // the meta file the open rule belongs to + private string _listNote = string.Empty; // shown over the rule list for a few seconds + private long _listNoteAt; + + // The one state picker turned into a name box (ImGui id, 0 = none). + private uint _namingKey; + private readonly byte[] _nameBuf = new byte[64]; + private bool _nameFocus, _nameWasActive; + private string? _nameProblem; + private const string NewStateEntry = PhosphorIcons.Plus + " New state..."; + + private const string BackLabel = PhosphorIcons.ArrowLeft + " Back"; + private const string AddLabel = PhosphorIcons.Plus + " Add"; + private const string SetCurrentLabel = PhosphorIcons.MapPin + " Set current"; + + // ===================================================================== + // Open / save / leave + // ===================================================================== + + private void OpenEditor(int index, MetaRuleDto rule) + { + FlushEdit(); + _editIndex = index; + _editFile = EditFileOf(_data.CurrentMetaPath); + _editRule = index >= 0 ? rule.Clone() : rule; + _editOriginal = index >= 0 ? rule.Clone() : null; + _lastSaved = index >= 0 ? rule.Clone() : null; + _autosave.Clear(); + _fields.Clear(); + _editConfirmDelete = false; + _editTyping = false; + CancelNaming(); + _view = View.Editor; + } + + /// + /// Another meta was loaded while a rule was open (the Meta Manager, a chat command): the rule's + /// index means nothing in that meta, so the editor closes without saving into it. RynthAi + /// saving a .met as its .af is the same meta. + /// + private void EditorGuard() + { + if (string.Equals(_editFile, EditFileOf(_data.CurrentMetaPath), StringComparison.OrdinalIgnoreCase)) return; + bool lost = _autosave.Dirty; + _autosave.Clear(); + CancelNaming(); + _view = View.List; + _listNote = lost + ? "Another meta was loaded while you edited a rule; your last change to it was not saved." + : "Another meta was loaded, so the rule editor closed."; + _listNoteAt = NowMs; + } + + private static string EditFileOf(string? metaPath) => + string.IsNullOrEmpty(metaPath) ? string.Empty : MetaBackupPlan.WrittenFile(metaPath); + + private void LeaveEditor() + { + FlushEdit(); + CancelNaming(); + _view = View.List; + } + + /// Saves a pending edit now (Back, panel closed, meta switch). + private void FlushEdit() + { + if (_view == View.Editor && _autosave.Dirty) CommitEdit(); + } + + /// Sends the edited rule: add_rule the first time for a new rule, then update_rule. + private void CommitEdit() + { + if (!string.Equals(_editFile, EditFileOf(_data.CurrentMetaPath), StringComparison.OrdinalIgnoreCase)) + { + EditorGuard(); // never save into a meta loaded meanwhile + return; + } + if (!_autosave.Take()) return; + MetaRuleDto send = _editRule.Clone(); + if (_editIndex < 0) + { + _editIndex = _data.Rules.Count; // add_rule appends + SendEdit(new MetaCmd { Op = "add_rule", Rule = send }); + _data.Rules.Add(send.Clone()); + } + else + { + // Commands address rules by index: find the rule again in case the snapshot moved it. + if (_lastSaved != null) _editIndex = MetaRuleEdit.Locate(_data.Rules, _lastSaved, _editIndex); + SendEdit(new MetaCmd { Op = "update_rule", Index = _editIndex, Rule = send }); + if (_editIndex < _data.Rules.Count) _data.Rules[_editIndex] = send.Clone(); + } + _lastSaved = send.Clone(); + RebuildCaches(); + } + + private void DeleteEditedRule() + { + _autosave.Clear(); + if (_editIndex >= 0) + { + int index = _lastSaved != null ? MetaRuleEdit.Locate(_data.Rules, _lastSaved, _editIndex) : _editIndex; + if (index >= 0 && index < _data.Rules.Count) + { + SendEdit(new MetaCmd { Op = "delete_rule", Index = index }); + _data.Rules.RemoveAt(index); + _expanded.Clear(); + RebuildCaches(); + } + } + CancelNaming(); + _view = View.List; + } + + // ===================================================================== + // Editor view + // ===================================================================== + + private void EditorView(Vector2 size) + { + _editChanged = false; + _typingNow = false; + MetaRuleDto r = _editRule; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 top = ImGuiNET.ImGui.GetCursorScreenPos(); + float w = size.X; + + // [<- Back] New rule / Edit rule Saved + float backW = BtnW(BackLabel, 60); + if (Button(BackLabel + "##back", top, new Vector2(backW, 22), Mute, BtnFill, BtnBord)) + { + LeaveEditor(); + return; + } + ImGuiNET.ImGui.SetItemTooltip("Back to the rule list (saves this rule)"); + 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"; + 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(); + SaveIndicator(new Vector2(top.X + w - indW, top.Y), indW, 22); + + // State: [picker] + float y = top.Y + 26; + float lw = ImGuiNET.ImGui.CalcTextSize("State:").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 _); + if (state != null && state != r.State) + { + 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; + + // Conditions | Actions + const float footerH = 24; + float colsH = Math.Max(60, top.Y + size.Y - y - footerH - 6); + if (w >= SideBySideMinWidth) + { + float cw = (w - 6) * 0.5f; + Column("##ed_conds", new Vector2(top.X, y), new Vector2(cw, colsH), actions: false); + Column("##ed_acts", new Vector2(top.X + cw + 6, y), new Vector2(w - cw - 6, colsH), actions: true); + } + else + { + float ch = (colsH - 6) * 0.5f; + Column("##ed_conds", new Vector2(top.X, y), new Vector2(w, ch), actions: false); + Column("##ed_acts", new Vector2(top.X, y + ch + 6), new Vector2(w, colsH - ch - 6), actions: true); + } + + EditorFooter(new Vector2(top.X, y + colsH + 6), w, footerH); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(top.X, y + colsH + 6 + footerH)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + + if (_editChanged) + { + _autosave.Changed(NowMs); + _editConfirmDelete = false; + } + _editTyping = _typingNow; + } + + /// A bordered column: a fixed header (title, "+ Add") over a body that scrolls on its own. + private void Column(string id, Vector2 pos, Vector2 size, bool actions) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + MetaRuleDto r = _editRule; + const float hh = 24; + dl.AddRectFilled(pos, pos + size, PanelBg, 3); + dl.AddRectFilled(pos, pos + new Vector2(size.X, hh), StateHdrA, 3); + dl.AddRect(pos, pos + size, BtnBord, 3); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + dl.AddText(bold, bold.FontSize, pos + new Vector2(7, (hh - bold.FontSize) * 0.5f), Amber, actions ? "Actions" : "Conditions"); + + bool canAdd = actions || MetaRuleEdit.CanAddCondition(r); + float addW = BtnW(AddLabel, 52); + if (Button(AddLabel + id + "_add", new Vector2(pos.X + size.X - addW - 3, pos.Y + 2), new Vector2(addW, hh - 4), Teal, BtnFill, BtnBord, + enabled: canAdd)) + { + if (actions) MetaRuleEdit.AddAction(r); else MetaRuleEdit.AddCondition(r); + _editChanged = true; + } + ImGuiNET.ImGui.SetItemTooltip(actions + ? (r.Action == MetaRuleEdit.DoAll ? "Add one more action" : "Add another action: this one and the new one run in order (All)") + : !canAdd ? "A Not has one condition" + : r.Condition is MetaRuleEdit.All or MetaRuleEdit.Any or MetaRuleEdit.Not ? "Add one more condition" + : "Add another condition: the rule fires when all of them are true (All)"); + + ImGuiNET.ImGui.SetCursorScreenPos(pos + new Vector2(5, hh + 4)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); + ImGuiNET.ImGui.BeginChild(id, new Vector2(Math.Max(10, size.X - 10), Math.Max(10, size.Y - hh - 8))); + ImGuiNET.ImGui.PopStyleColor(); + float cw = Math.Max(40, ImGuiNET.ImGui.GetContentRegionAvail().X - 2); + if (actions) ActionsBody(r, cw); else ConditionsBody(r, cw); + ImGuiNET.ImGui.EndChild(); + } + + 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) + { + SetCondition(r, picked); + _editChanged = true; + } + if (!MetaVocabulary.IsCompositeCondition(r.Condition)) + { + ConditionField("##ed_cdata", r, w, 22); + return; + } + 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) + { + r.Action = picked; + if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear(); + _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) + { + c.Condition = picked; + if (!MetaVocabulary.IsCompositeCondition(picked)) c.Children.Clear(); + else if (picked == MetaRuleEdit.Not && c.Children.Count > 1) c.Children.RemoveRange(1, c.Children.Count - 1); + } + + /// A condition's value at the cursor: a text box (with Set current for landblock / landcell), + /// or a note when the condition takes nothing. Leaves the cursor under it. + private void ConditionField(string id, MetaRuleDto c, float width, float height) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (!MetaRuleEdit.ConditionTakesData(c.Condition) && c.ConditionData.Length == 0) + NoteAt(p, "Nothing to set.", height); + else if (MetaLocation.TakesPosition(c.Condition)) + { + // "Set current" fills in where the player is, from the engine's per-frame pose copy + // (no call into AC from here), in the 8-digit form RynthAi and VTank both read. + float bw = Math.Min(BtnW(SetCurrentLabel, 70), width * 0.5f); + float boxW = Math.Max(30, width - bw - 4); + ImGuiNET.ImGui.SetCursorScreenPos(p); + DataBox(id, c, action: false, MetaVocabulary.ConditionHint(c.Condition), boxW, height); + string? here = PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out uint cell, out _, out _, out _, out _, out _, out _, out _) && cell != 0 + ? MetaLocation.Text(c.Condition, cell) : null; + if (Button((bw >= BtnW(SetCurrentLabel, 0) ? SetCurrentLabel : PhosphorIcons.MapPin) + id + "_here", + new Vector2(p.X + width - bw, p.Y), new Vector2(bw, height), Teal, BtnFill, BtnBord, enabled: here != null) && here != null) + { + c.ConditionData = here; + _editChanged = true; + } + ImGuiNET.ImGui.SetItemTooltip(here != null + ? $"Set to where you are now: {here}" + : "Your position isn't known right now (portal space, or not in the world)."); + } + else + { + ImGuiNET.ImGui.SetCursorScreenPos(p); + DataBox(id, c, action: false, MetaVocabulary.ConditionHint(c.Condition), width, height); + if (c.Condition == MetaRuleEdit.NoKillsWithinMinutes) + ImGuiNET.ImGui.SetItemTooltip(MetaRuleEdit.NoKillsTooltip(c.ConditionData).Replace("%", "%%")); // a format string: typed text may hold % + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + height)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + /// An action's value at the cursor: a state picker (Set / Call Meta State), the route picker + /// (Embedded Nav Route), a text box, or a note. Leaves the cursor under it. + private void ActionField(string id, MetaRuleDto a, float width, float height, bool problemLine) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float extra = 0; + if (a.Action is 2 or 5) // Set / Call Meta State + { + string? target = StatePicker(id, a.ActionData.Length == 0 ? "Select state..." : a.ActionData, _statesOnly, + IndexOf(_statesOnly, a.ActionData), p, width, out bool isNew, height); + if (target != null) + { + if (isNew) CreateState(target, openIt: false); // an empty first rule keeps it + if (target != a.ActionData) + { + a.ActionData = target; + _editChanged = true; + } + } + if (problemLine) extra = ProblemLine(id, new Vector2(p.X, p.Y + height), width); + } + else if (a.Action == 3) // Embedded Nav Route + { + 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) + { + a.ActionData = _routePicks[picked]; + _editChanged = true; + } + } + else if (!MetaRuleEdit.ActionTakesData(a.Action) && a.ActionData.Length == 0) + NoteAt(p, "Nothing to set.", height); + else + { + ImGuiNET.ImGui.SetCursorScreenPos(p); + DataBox(id, a, action: true, MetaVocabulary.ActionHint(a.Action), width, height); + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + height + extra)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + // 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. + private void SubRules(List 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; + for (int i = 0; i < subs.Count; i++) + { + MetaRuleDto sub = subs[i]; + ImGuiNET.ImGui.PushID(i); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float pickW = narrow ? w - xw - 4 : (w - xw - 8) * 0.45f; + + 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); + 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"); + + 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); + } + 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; + 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; + } + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH + 2)); + 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.PopID(); + if (removed) + { + subs.RemoveAt(i); + _editChanged = true; + break; // indices shifted: the rest draws next frame + } + } + + // Nested groups get their own Add; the top level's is in the column header. + if (depth == 0 || subs.Count >= maxCount) return; + ImGuiNET.ImGui.PushID(depth * 1000 + subs.Count); + if (FlowButton(AddLabel + "##add_sub", Teal, BtnFill, BtnBord, height: 20)) + { + subs.Add(new MetaRuleDto { State = _editRule.State, Condition = MetaRuleEdit.Never }); + _editChanged = true; + } + ImGuiNET.ImGui.PopID(); + } + + /// [Revert] on the left (once something changed); Delete on its own at the far right. + private void EditorFooter(Vector2 p, float w, float h) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + bool canRevert = _editOriginal != null && !MetaRuleEdit.SameContent(_editRule, _editOriginal); + if (canRevert) + { + string label = PhosphorIcons.ArrowCounterClockwise + " Revert"; + if (Button(label + "##ed_revert", p, new Vector2(BtnW(label, 60), h), Mute, BtnFill, BtnBord)) + { + _editRule = _editOriginal!.Clone(); + _fields.Clear(); + _editChanged = true; + } + ImGuiNET.ImGui.SetItemTooltip("Undo every change since you opened this rule (and save that)"); + } + else + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + dl.AddText(new Vector2(p.X, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), + _editIndex < 0 ? "Added once it is filled in, or on Back." : "Changes save on their own."); + ImGuiNET.ImGui.PopFont(); + } + + bool draft = _editIndex < 0; + if (!_editConfirmDelete) + { + string label = PhosphorIcons.Trash + (draft ? " Discard" : " Delete rule"); + float dw = BtnW(label, 70); + if (Button(label + "##ed_del", new Vector2(p.X + w - dw, p.Y), new Vector2(dw, h), TextDim, DelFill, BtnBord)) + { + if (draft) { _autosave.Clear(); LeaveEditor(); } + else _editConfirmDelete = true; + } + ImGuiNET.ImGui.SetItemTooltip(draft ? "Drop this new rule (it was never added)" : "Delete this rule (asks first)"); + } + else + { + float kw = BtnW("Keep", 50), yw = BtnW("Delete", 56); + dl.AddText(new Vector2(p.X + w - kw - yw - 8 - ImGuiNET.ImGui.CalcTextSize("Delete this rule?").X - 6, + p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Red, "Delete this rule?"); + if (Button("Delete##ed_del_yes", new Vector2(p.X + w - kw - yw - 4, p.Y), new Vector2(yw, h), TextDim, DelFill, Red)) + { + DeleteEditedRule(); + return; + } + if (Button("Keep##ed_del_no", new Vector2(p.X + w - kw, p.Y), new Vector2(kw, h), Mute, BtnFill, BtnBord)) + _editConfirmDelete = false; + } + } + + // ===================================================================== + // State pickers and new states + // ===================================================================== + + /// + /// A state picker ending with "+ New state...". Returns the picked state, or a new state's name + /// ( true) once its name box is confirmed; else null. + /// + private string? StatePicker(string id, string shown, string[] items, int selected, Vector2 pos, float width, out bool isNew, + float height = 22) + { + 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); + if (picked == items.Length) + { + _namingKey = key; + Array.Clear(_nameBuf); + _nameFocus = true; + _nameWasActive = false; + _nameProblem = null; + return null; + } + return picked >= 0 ? items[picked] : null; + } + + /// The name box a state picker turns into: [name][OK][Cancel]; Enter = OK, Esc = Cancel. + private string? NamingBox(string id, Vector2 pos, float width, float height, out bool isNew) + { + isNew = false; + float bw = height + 4; + float boxW = Math.Max(30, width - 2 * (bw + 3)); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + if (_nameFocus) + { + ImGuiNET.ImGui.SetKeyboardFocusHere(); + _nameFocus = false; + } + bool enter = TextBox(id + "_name", _nameBuf, boxW, "New state name...", ImGuiInputTextFlags.EnterReturnsTrue, out bool active, height); + // Esc deactivates the box in the same frame, so "was it being typed in" is last frame's. + bool esc = (active || _nameWasActive) && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape, false); + _nameWasActive = active; + + string typed = Utf8(_nameBuf); + _nameProblem = MetaStateName.Problem(typed, _statePicks, out string name); + if (_nameProblem != null && name.Length > 0) + ImGuiNET.ImGui.GetWindowDrawList().AddRect(pos, pos + new Vector2(boxW, height), Red, 3); + bool ok = IconButton(id + "_ok", PhosphorIcons.Check, new Vector2(pos.X + boxW + 3, pos.Y), new Vector2(bw, height), Green, NewFill, Green, + enabled: _nameProblem == null); + ImGuiNET.ImGui.SetItemTooltip(_nameProblem ?? $"Make the state '{name}' (Enter)"); + bool cancel = IconButton(id + "_cancel", PhosphorIcons.X, new Vector2(pos.X + boxW + bw + 6, pos.Y), new Vector2(bw, height), + TextDim, BtnFill, BtnBord); + ImGuiNET.ImGui.SetItemTooltip("Cancel (Esc)"); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, pos.Y + height)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + + if ((enter || ok) && _nameProblem == null) + { + CancelNaming(); + AddLocalState(name); + isNew = true; + return name; + } + if (enter) _nameFocus = true; // a bad name: keep typing (the reason shows under it) + if (cancel || esc) CancelNaming(); + return null; + } + + /// The name box's problem under a picker in the editor's flow; its height (0 when none). + private float ProblemLine(string id, Vector2 pos, float width) + { + if (_namingKey == 0 || _namingKey != ImGuiNET.ImGui.GetID(id) || _nameProblem == null || Utf8(_nameBuf).Trim().Length == 0) + return 0; + ImFontPtr small = ImGuiFonts.Get(UiFont.Ui9); + ImGuiNET.ImGui.PushFont(small); + ImGuiNET.ImGui.GetWindowDrawList().AddText(pos + new Vector2(2, 1), Red, Fit(_nameProblem, width - 4)); + ImGuiNET.ImGui.PopFont(); + return small.FontSize + 3; + } + + private void CancelNaming() + { + _namingKey = 0; + _nameProblem = null; + } + + /// Offers in every state picker until the snapshot lists it. + private void AddLocalState(string name) + { + _localStates.Add(name); + if (IndexOf(_statePicks, name) < 0) _statePicks = With(_statePicks, name); + if (IndexOf(_statesOnly, name) < 0) _statesOnly = With(_statesOnly, name); + } + + /// + /// Makes state with its first rule, an empty Never -> None (it never fires), + /// added at once: a state exists only while a rule uses it, so this is what keeps it through a + /// save and reload. opens that rule in the editor. + /// + private void CreateState(string name, bool openIt) + { + AddLocalState(name); + MetaRuleDto first = MetaRuleEdit.Placeholder(name); + int index = _data.Rules.Count; // add_rule appends + SendEdit(new MetaCmd { Op = "add_rule", Rule = first.Clone() }); + _data.Rules.Add(first.Clone()); + RebuildCaches(); + if (openIt) OpenEditor(index, first); + } + + // ── Small helpers ──────────────────────────────────────────────────── + + private static int IndexOf(string[] items, string value) + { + for (int i = 0; i < items.Length; i++) + if (string.Equals(items[i], value, StringComparison.OrdinalIgnoreCase)) return i; + 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) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); + ImGuiNET.ImGui.PopFont(); + } + + private static void NoteAt(Vector2 p, string text, float height) + { + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + 4, p.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), text); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs index d87fc87..f6b51fa 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs @@ -83,12 +83,12 @@ internal sealed partial class MetaFace Separator(w); Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - const float newW = 80; + float newW = BtnW(PhosphorIcons.Plus + " New Rule", 80); if (Button(PhosphorIcons.Plus + " New Rule##sched_new", new Vector2(p.X, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green)) OpenScheduleEditor(-1, new ScheduleRuleDto { Meta = FirstMetaFile() }); if (sc.Rules.Count > 0) { - if (Button(PhosphorIcons.ArrowCounterClockwise + " Re-arm all##sched_reset", new Vector2(p.X + newW + 4, p.Y), new Vector2(86, 24), + if (Button(PhosphorIcons.ArrowCounterClockwise + " Re-arm all##sched_reset", new Vector2(p.X + newW + 4, p.Y), new Vector2(BtnW(PhosphorIcons.ArrowCounterClockwise + " Re-arm all", 86), 24), Mute, BtnFill, BtnBord)) MetaCommands.Simple("mm_reset", -1); ImGuiNET.ImGui.SetItemTooltip("Clear every rule's fired / error / holding state"); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs index 655bc50..aa3c6d2 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs @@ -3,16 +3,28 @@ // 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 / Save As; Visual|Source; Meta, Debug; -// rules grouped by state (collapsible, red while firing), rows with -// enable, expand, up/down within the state, duplicate, delete; click -// a row to edit it; State picker and New Rule at the bottom. -// Editor state, condition (with nested All/Any/Not sub-conditions), action -// (state and route pickers, DoAll sub-actions); Add/Save, Cancel. +// 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. +// 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. // Source the .af text in a coloured editor (CodeEditor) with Ctrl+Space // completion (and after "IF: " etc.); Apply shows the plugin's real // result; unapplied edits survive switching views; Revert. // +// Every state picker ends with "+ New state...", which turns it into a name +// box (Enter = OK, Esc = Cancel); see MetaFace.Editor.cs for how a new state +// is kept (a state exists while a rule uses it). +// +// Saving (2026-10-05): there is no Save button. RynthAi writes the meta file +// after every rule command (TryAutoSaveMetaCmd); the editor sends its rule +// 0.75 s after the last change (MetaAutosave), and at once on Back, close or +// a meta switch. The first save of a session first copies the file to +// .bak (MetaBackupPlan, MetaCommands.Backup). +// // Data: UiSources.Meta (hub snapshot) and MetaCommands. List edits change a // private copy at once and the next snapshot (taken after the plugin applied // the command) replaces it. @@ -62,8 +74,8 @@ internal sealed partial class MetaFace : IImGuiPanel private string _fileDisplay = "-- None --", _sourceFileLabel = "File: Unsaved"; private IReadOnlyList _completionNavs = Array.Empty(); - // Ellipsized row text, recomputed only when the column width changes. - private readonly Dictionary _fit = new(); + // Ellipsized text per (text, width), so one text shown at two widths doesn't recompute each frame. + private readonly Dictionary<(string Text, int Width), string> _fit = new(); private View _view = View.List; private readonly HashSet _collapsed = new(); @@ -71,6 +83,22 @@ internal sealed partial class MetaFace : IImGuiPanel private bool _saveAs, _saveAsFocus; private readonly byte[] _saveName = new byte[128]; + // States made with "+ New state..." that the snapshot doesn't list yet (MetaFace.Editor.cs). + private readonly HashSet _localStates = new(StringComparer.OrdinalIgnoreCase); + private string _statesPath = string.Empty; // the meta _localStates belong to + + // Delete on a rule row: the first click arms it (3 s), the second deletes. + private MetaRuleDto? _confirmDelete; + private int _confirmDeleteIndex = -1; + private long _confirmDeleteUntil; + + // ── Saving ─────────────────────────────────────────────────────────── + private readonly MetaAutosave _autosave = new(); + private readonly MetaBackupPlan _backup = new(); + private long _saveSentAt = -1; // ms (TickCount64) of the last rule command, for "Saving..." + private long _saveSentVersion; // the snapshot version then + private static long NowMs => Environment.TickCount64; + // ── Rule editor ────────────────────────────────────────────────────── private int _editIndex = -1; private MetaRuleDto _editRule = new() { Action = 1 }; @@ -109,10 +137,13 @@ internal sealed partial class MetaFace : IImGuiPanel UiSources.Meta.Subscribe(); UiSources.Meta.RequestRefresh(); CodeEditor.SetMetaVocabulary(MetaVocabulary.StructKeywords, MetaVocabulary.ConditionKeywords, MetaVocabulary.ActionKeywords); + _backup.NewSession(); // a new editing session: the first save backs the file up again } public void OnHidden() { + FlushEdit(); // closing saves the rule being edited at once + CancelNaming(); UiSources.Meta.Unsubscribe(); _editor?.Dispose(); _editor = null; @@ -125,6 +156,10 @@ internal sealed partial class MetaFace : IImGuiPanel public void Draw() { TakeSnapshot(); + if (_view == View.Editor) EditorGuard(); + // A new rule waits until it is filled in (MetaRuleEdit.ReadyToAdd); Back / close add it anyway. + if (_view == View.Editor && _autosave.Due(NowMs, _editTyping) && (_editIndex >= 0 || MetaRuleEdit.ReadyToAdd(_editRule))) + CommitEdit(); var dl = ImGuiNET.ImGui.GetWindowDrawList(); Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); @@ -192,8 +227,20 @@ internal sealed partial class MetaFace : IImGuiPanel _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)) + { + _statesPath = _data.CurrentMetaPath; + _localStates.Clear(); + } + foreach (string s in _data.States) _localStates.Remove(s); _statePicks = MetaVocabulary.StatePicks(_data); _statesOnly = _data.States.ToArray(); + foreach (string s in _localStates) + { + _statePicks = With(_statePicks, s); + _statesOnly = With(_statesOnly, s); + } _routePicks = MetaVocabulary.RoutePicks(_data); _fileDisplays = new string[_data.Files.Count]; for (int i = 0; i < _fileDisplays.Length; i++) _fileDisplays[i] = _data.Files[i].Display; @@ -214,6 +261,12 @@ internal sealed partial class MetaFace : IImGuiPanel 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); @@ -233,7 +286,7 @@ internal sealed partial class MetaFace : IImGuiPanel { if (_saveAs) { - float btn = 52, sx = ImGuiNET.ImGui.GetCursorScreenPos().X, y = ImGuiNET.ImGui.GetCursorScreenPos().Y; + float btn = BtnW(SaveLabel, 52), sx = ImGuiNET.ImGui.GetCursorScreenPos().X, y = ImGuiNET.ImGui.GetCursorScreenPos().Y; float boxW = w - btn - 26 - 8; if (_saveAsFocus) { ImGuiNET.ImGui.SetKeyboardFocusHere(); _saveAsFocus = false; } bool enter = TextBox("##save_name", _saveName, boxW, "Filename (no ext)...", ImGuiInputTextFlags.EnterReturnsTrue, out _); @@ -241,7 +294,14 @@ internal sealed partial class MetaFace : IImGuiPanel { string n = Utf8(_saveName).Trim(); if (n.Length > 0) - MetaCommands.Simple("save_file", path: System.IO.Path.Combine(MetaVocabulary.MetaFolder, n + ".af")); + { + string target = System.IO.Path.Combine(MetaVocabulary.MetaFolder, n + ".af"); + // Saving over another meta keeps that one's old copy as .bak. + MetaCommands.Backup(target, MetaBackupPlan.BackupOf(target)); + MetaCommands.Simple("save_file", path: target); + _saveSentAt = NowMs; + _saveSentVersion = _seenVersion; + } _saveAs = false; } if (IconButton("##save_as_x", PhosphorIcons.X, new Vector2(sx + boxW + 8 + btn, y), new Vector2(26, 22), TextDim, BtnFill, BtnBord, @@ -253,12 +313,17 @@ internal sealed partial class MetaFace : IImGuiPanel return; } + // [file v][refresh][Save As] Saved (no Save button: every change saves on its own) Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - const float refreshW = 26, saveW = 52, saveAsW = 60; - float pickW = w - refreshW - saveW - saveAsW - 12; + const float refreshW = 26; + float saveAsW = BtnW("Save As", 60), indW = SaveIndicatorWidth(); + float pickW = Math.Max(60, w - refreshW - saveAsW - indW - 12); int picked = Picker("##file", _fileDisplay, _fileDisplays, MetaVocabulary.CurrentFileIndex(_data), p, pickW); if (picked >= 0 && picked < _data.Files.Count) + { + FlushEdit(); // a meta switch saves a pending edit first MetaCommands.Simple("load_file", path: _data.Files[picked].Path); + } float x = p.X + pickW + 4; if (IconButton("##refresh", PhosphorIcons.ArrowsClockwise, new Vector2(x, p.Y), new Vector2(refreshW, 22), TextDim, BtnFill, BtnBord, @@ -266,18 +331,74 @@ internal sealed partial class MetaFace : IImGuiPanel UiSources.Meta.RequestRefresh(); ImGuiNET.ImGui.SetItemTooltip("Refresh file list"); x += refreshW + 4; - if (Button(SaveLabel + "##save", new Vector2(x, p.Y), new Vector2(saveW, 22), TextDim, BtnFill, BtnBord)) - { - if (!string.IsNullOrEmpty(_data.CurrentMetaPath)) MetaCommands.Simple("save_file", path: _data.CurrentMetaPath); - else BeginSaveAs(); - } - x += saveW + 4; - if (Button("Save As##save_as", new Vector2(x, p.Y), new Vector2(saveAsW, 22), TextDim, BtnFill, BtnBord)) + bool noFile = string.IsNullOrEmpty(_data.CurrentMetaPath); + if (Button("Save As##save_as", new Vector2(x, p.Y), new Vector2(saveAsW, 22), TextDim, noFile ? NewFill : BtnFill, noFile ? Green : BtnBord)) BeginSaveAs(); + ImGuiNET.ImGui.SetItemTooltip(noFile ? "Name a file for this meta; after that every change saves on its own." + : "Save a copy under a new name (and keep editing that one)."); + x += saveAsW + 4; + SaveIndicator(new Vector2(x, p.Y), p.X + w - x, 22); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); } + // ── "Saved" indicator ──────────────────────────────────────────────── + + private const string SavedText = PhosphorIcons.Check + " Saved", SavingText = PhosphorIcons.FloppyDisk + " Saving...", + EditingText = PhosphorIcons.PencilSimple + " Editing", NoFileText = PhosphorIcons.Warning + " Not saved", + DraftText = PhosphorIcons.PencilSimple + " Not added yet"; + + private static float SaveIndicatorWidth(bool editor = false) + { + float m = Math.Max(ImGuiNET.ImGui.CalcTextSize(SavedText).X, ImGuiNET.ImGui.CalcTextSize(SavingText).X); + m = Math.Max(m, Math.Max(ImGuiNET.ImGui.CalcTextSize(EditingText).X, ImGuiNET.ImGui.CalcTextSize(NoFileText).X)); + if (editor) m = Math.Max(m, ImGuiNET.ImGui.CalcTextSize(DraftText).X); + return m + 6; + } + + private (string Text, uint Color, string Tip) SaveStatus() + { + string file = System.IO.Path.GetFileName(_data.CurrentMetaPath ?? ""); + if (string.IsNullOrEmpty(file)) + return (NoFileText, Amber, "This meta has no file yet. Save As names one; after that every change saves on its own."); + if (_view == View.Editor && _autosave.Dirty && _editIndex < 0 && !_editTyping && !MetaRuleEdit.ReadyToAdd(_editRule)) + return (DraftText, Amber, "A new rule is added once its condition and action are filled in, or when you go Back."); + if (_view == View.Editor && _autosave.Dirty) + return _editTyping + ? (EditingText, Amber, "Saves when you leave the box (Enter, Tab or click elsewhere).") + : (SavingText, Amber, "Saving in a moment..."); + if (_saveSentAt >= 0 && _seenVersion == _saveSentVersion && NowMs - _saveSentAt < 2500) + return (SavingText, Amber, "Saving " + file + "..."); + string bak = System.IO.Path.GetFileName(MetaBackupPlan.BackupOf(MetaBackupPlan.WrittenFile(_data.CurrentMetaPath!))); + return (SavedText, Green, $"Every change saves to {file} on its own. The first change after opening this panel keeps the file as it was in {bak}."); + } + + /// The save status, right-aligned in (pos, width); hover for details. + private void SaveIndicator(Vector2 pos, float width, float height) + { + if (width < 8) return; + (string text, uint color, string tip) = SaveStatus(); + float tw = ImGuiNET.ImGui.CalcTextSize(text).X; + ImGuiNET.ImGui.SetCursorScreenPos(pos); + ImGuiNET.ImGui.InvisibleButton("##save_ind", new Vector2(width, height)); + ImGuiNET.ImGui.SetItemTooltip(tip); + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(pos.X + Math.Max(0, width - tw), pos.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), + color, text); + } + + /// + /// Every command that changes the meta's rules goes through here: before the first one of this + /// session the file is backed up, and the indicator shows "Saving..." until the next snapshot. + /// (RynthAi writes the file after each such command.) + /// + private void SendEdit(MetaCmd cmd) + { + if (_backup.Before(_data.CurrentMetaPath) is { } b) MetaCommands.Backup(b.File, b.Backup); + MetaCommands.Send(cmd); + _saveSentAt = NowMs; + _saveSentVersion = _seenVersion; + } + private void BeginSaveAs() { _saveAs = true; @@ -341,6 +462,8 @@ internal sealed partial class MetaFace : IImGuiPanel // the text starts within a row (from the last row drawn). private static float _condFrac = Math.Clamp(RynthCore.Engine.UI.PanelColumnStore.Get("Meta.condFrac", 0.5f), 0.15f, 0.85f); private float _textStartOff; + /// The far-right delete button and the gap before it: the row text ends this far from the edge. + private const float DeleteColumnW = 30; private void RuleList(float w) { @@ -360,7 +483,7 @@ internal sealed partial class MetaFace : IImGuiPanel { Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos(); const float hh = 16; - float tx = hp.X + _textStartOff, tw = Math.Max(1, hp.X + w - tx); + 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"); @@ -424,7 +547,7 @@ internal sealed partial class MetaFace : IImGuiPanel rule.Enabled ? Green : Mute, BtnFill, BtnBord)) { rule.Enabled = !rule.Enabled; - MetaCommands.Simple("set_rule_enabled", index, rule.Enabled ? "true" : "false"); + 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; @@ -451,29 +574,45 @@ internal sealed partial class MetaFace : IImGuiPanel // Duplicate if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord)) { - MetaCommands.Send(new MetaCmd { Op = "duplicate_rule", Index = index, Rule = rule.Clone() }); + 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 += 18; + x += 20; - // Delete - if (IconButton("##del", PhosphorIcons.Trash, new Vector2(x + 1, p.Y + 2), new Vector2(18, 16), TextDim, DelFill, BtnBord)) + // 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)) { - MetaCommands.Simple("delete_rule", index); - _data.Rules.RemoveAt(index); - _expanded.Clear(); - changed = true; + 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("Delete rule"); - x += 22; + ImGuiNET.ImGui.SetItemTooltip(arming ? "Click again to delete this rule" : "Delete rule"); // Condition | action text; clicking it edits the rule. - float textW = p.X + w - x; + 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(Math.Max(1, textW), h))) + if (ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(textW, h))) OpenEditor(index, rule); if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); ImGuiNET.ImGui.PopID(); @@ -485,7 +624,9 @@ internal sealed partial class MetaFace : IImGuiPanel 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)); - dl.AddText(new Vector2(x + col + 2, ty), actCol, Fit(_actText[index], col - 4)); + // 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)); @@ -527,7 +668,7 @@ internal sealed partial class MetaFace : IImGuiPanel { int other = MetaVocabulary.SwapPartner(_data.Rules, index, direction); if (other < 0) return false; - MetaCommands.Simple(direction < 0 ? "move_up" : "move_down", index); + 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; @@ -539,182 +680,34 @@ internal sealed partial class MetaFace : IImGuiPanel 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:"); - const float newW = 72; + // 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 pickW = w - labelW - 4 - newW - 4 - grip; - int picked = Picker("##cur_state", _data.CurrentState, _statePicks, Array.IndexOf(_statePicks, _data.CurrentState), - new Vector2(p.X + labelW + 4, p.Y + 1), pickW); - if (picked >= 0) + 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) { - _data.CurrentState = _statePicks[picked]; - MetaCommands.Simple("set_state", value: _statePicks[picked]); + if (isNew) CreateState(chosen, openIt: true); + _data.CurrentState = chosen; + MetaCommands.Simple("set_state", value: chosen); } - if (Button(PhosphorIcons.Plus + " New Rule##new", new Vector2(p.X + w - newW - grip, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green)) + 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)); } - // ===================================================================== - // Rule editor view - // ===================================================================== - - private void OpenEditor(int index, MetaRuleDto rule) - { - _editIndex = index; - _editRule = index >= 0 ? rule.Clone() : rule; - _fields.Clear(); - _view = View.Editor; - } - - private void EditorView(Vector2 size) - { - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0); - ImGuiNET.ImGui.BeginChild("##meta_editor", size); - ImGuiNET.ImGui.PopStyleColor(); - float w = ImGuiNET.ImGui.GetContentRegionAvail().X; - MetaRuleDto r = _editRule; - - if (FlowButton(PhosphorIcons.ArrowLeft + " Back to List##back", Mute, BtnFill, BtnBord)) _view = View.List; - Separator(w); - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _editIndex == -1 ? "New Rule" : $"Edit Rule (index {_editIndex})"); - ImGuiNET.ImGui.PopFont(); - - // State - FieldLabel("State:"); - int picked = FlowPicker("##ed_state", r.State, _statePicks, Array.IndexOf(_statePicks, r.State), w); - if (picked >= 0) r.State = _statePicks[picked]; - - // Condition - FieldLabel("Condition:"); - picked = FlowPicker("##ed_cond", MetaVocabulary.ConditionName(r.Condition), MetaVocabulary.ConditionNames, r.Condition, w); - if (picked >= 0) - { - r.Condition = picked; - if (!MetaVocabulary.IsCompositeCondition(picked)) r.Children.Clear(); - else if (picked == 20 && r.Children.Count > 1) r.Children.RemoveRange(1, r.Children.Count - 1); - } - if (!MetaVocabulary.IsCompositeCondition(r.Condition)) - DataBox("##ed_cdata", r, action: false, MetaVocabulary.ConditionHint(r.Condition), w); - else - SubRules(r.Children, r.Condition == 20 ? "Not (one condition):" : "Sub-Conditions", action: false, 0, - r.Condition == 20 ? 1 : int.MaxValue, w); - - // Action - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - Separator(w); - FieldLabel("Action:"); - picked = FlowPicker("##ed_act", MetaVocabulary.ActionName(r.Action), MetaVocabulary.ActionNames, r.Action, w); - if (picked >= 0) - { - r.Action = picked; - if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear(); - } - if (!MetaVocabulary.IsAllAction(r.Action)) - { - if (r.Action is 2 or 5) // Set / Call Meta State - { - picked = FlowPicker("##ed_astate", r.ActionData.Length == 0 ? "Select state..." : r.ActionData, - _statesOnly, Array.IndexOf(_statesOnly, r.ActionData), w); - if (picked >= 0) r.ActionData = _statesOnly[picked]; - } - else if (r.Action == 3) // Embedded Nav Route - { - picked = FlowPicker("##ed_route", r.ActionData.Length == 0 ? "Select route..." : r.ActionData, - _routePicks, Array.IndexOf(_routePicks, r.ActionData), w); - if (picked >= 0) r.ActionData = _routePicks[picked]; - } - else - DataBox("##ed_adata", r, action: true, MetaVocabulary.ActionHint(r.Action), w); - } - else - SubRules(r.ActionChildren, "Sub-Actions", action: true, 0, int.MaxValue, w); - - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - Separator(w); - - // Add/Save, Cancel - if (FlowButton(_editIndex == -1 ? "Add Rule##save_rule" : "Save Rule##save_rule", TextDim, NewFill, Green)) - { - if (_editIndex == -1) MetaCommands.Send(new MetaCmd { Op = "add_rule", Rule = r.Clone() }); - else MetaCommands.Send(new MetaCmd { Op = "update_rule", Index = _editIndex, Rule = r.Clone() }); - _view = View.List; - } - ImGuiNET.ImGui.SameLine(0, 6); - if (FlowButton("Cancel##cancel_rule", Mute, BtnFill, BtnBord)) _view = View.List; - - ImGuiNET.ImGui.EndChild(); - } - - // Sub-conditions nest (All/Any/Not under All/Any/Not, MaxSubConditionDepth - // levels; a Not takes one); DoAll's sub-actions are a flat list. - private void SubRules(List subs, string label, bool action, int depth, int maxCount, float w) - { - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), label); - ImGuiNET.ImGui.PopFont(); - - string[] names = action ? MetaVocabulary.ActionNames : MetaVocabulary.ConditionNames; - for (int i = 0; i < subs.Count; i++) - { - MetaRuleDto sub = subs[i]; - ImGuiNET.ImGui.PushID(i); - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - float half = (w - 24) * 0.5f; - - // Appendix A4: the label indexes by the sub-rule's own kind. - 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, half - 2, 20); - if (picked >= 0) - { - if (action) sub.Action = picked; - else - { - sub.Condition = picked; - if (!MetaVocabulary.IsCompositeCondition(picked)) sub.Children.Clear(); - else if (picked == 20 && sub.Children.Count > 1) sub.Children.RemoveRange(1, sub.Children.Count - 1); - } - } - - bool nests = !action && MetaVocabulary.IsCompositeCondition(sub.Condition) && depth < MetaVocabulary.MaxSubConditionDepth; - if (nests) - ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + half + 4, p.Y + (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), - TextDim, sub.Condition == 20 ? "(the condition below)" : "(the conditions below)"); - else - { - ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + half + 2, p.Y)); - DataBox("##data", sub, action, "data...", half, 20); - } - - bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + w - 20, p.Y), new Vector2(20, 20), TextDim, DelFill, BtnBord); - ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 21)); - ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); - - if (!removed && nests) - { - ImGuiNET.ImGui.Indent(14); - SubRules(sub.Children, sub.Condition switch { 20 => "Not:", 2 => "All of:", _ => "Any of:" }, - action: false, depth + 1, sub.Condition == 20 ? 1 : int.MaxValue, w - 14); - ImGuiNET.ImGui.Unindent(14); - } - ImGuiNET.ImGui.PopID(); - if (removed) - { - subs.RemoveAt(i); - break; // indices shifted: the rest draws next frame - } - } - - if (subs.Count >= maxCount) return; // a Not already has its one operand - ImGuiNET.ImGui.PushID(depth * 1000 + subs.Count); - if (FlowButton(PhosphorIcons.Plus + " Add##add_sub", Teal, BtnFill, BtnBord, height: 20)) - subs.Add(new MetaRuleDto { State = _editRule.State }); - ImGuiNET.ImGui.PopID(); - } - // ===================================================================== // Source view // ===================================================================== @@ -733,13 +726,11 @@ internal sealed partial class MetaFace : IImGuiPanel float w = size.X; var dl = ImGuiNET.ImGui.GetWindowDrawList(); - // File: name [Save] + // File: name Saved (Apply saves; no Save button) Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, _sourceFileLabel); - float lw = ImGuiNET.ImGui.CalcTextSize(_sourceFileLabel).X; - if (Button(SaveLabel + "##src_save", new Vector2(p.X + lw + 8, p.Y), new Vector2(52, 22), TextDim, BtnFill, BtnBord) - && !string.IsNullOrEmpty(_data.CurrentMetaPath)) - MetaCommands.Simple("save_file", path: _data.CurrentMetaPath); + float indW = SaveIndicatorWidth(); + dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, Fit(_sourceFileLabel, Math.Max(10, w - indW - 8))); + SaveIndicator(new Vector2(p.X + w - indW, p.Y), indW, 22); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); Separator(w); @@ -786,7 +777,9 @@ internal sealed partial class MetaFace : IImGuiPanel if (_editor == null) return; _applySeqBefore = _data.ApplyResult?.Seq ?? -1; _applySentAt = DateTime.Now; - MetaCommands.Send(new MetaCmd { Op = "set_source", Text = _editor.GetText() }); + // Apply replaces every rule and re-enters the current state (RynthAi's set_source); it is + // the one explicit "reload", never sent by autosave. + SendEdit(new MetaCmd { Op = "set_source", Text = _editor.GetText() }); SetMsg("Applying…", ok: true); } @@ -1126,15 +1119,19 @@ internal sealed partial class MetaFace : IImGuiPanel } /// - /// A picker button showing ; click opens a 240 px - /// list (current item highlighted). Returns the picked index or -1. + /// A picker button showing (cut with "..." before the arrow); click opens + /// a list at least 240 px wide (current item highlighted). , when given, is + /// one more entry after the items ("+ New state..."): picking it returns items.Length. Returns the + /// picked index or -1. /// - private static int Picker(string id, string shown, string[] items, int selected, Vector2 pos, float width, float height = 22) + private int Picker(string id, string shown, string[] items, int selected, Vector2 pos, float width, float height = 22, + string? extra = null) { var dl = ImGuiNET.ImGui.GetWindowDrawList(); ImGuiNET.ImGui.PushID(id); ImGuiNET.ImGui.SetCursorScreenPos(pos); - if (ImGuiNET.ImGui.InvisibleButton("##btn", new Vector2(Math.Max(1, width), height)) && items.Length > 0) + int rows = items.Length + (extra != null ? 1 : 0); + if (ImGuiNET.ImGui.InvisibleButton("##btn", new Vector2(Math.Max(1, width), height)) && rows > 0) { float listW = Math.Max(240, width); Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; @@ -1144,9 +1141,12 @@ internal sealed partial class MetaFace : IImGuiPanel bool hot = ImGuiNET.ImGui.IsItemHovered(); dl.AddRectFilled(pos, pos + new Vector2(width, height), hot ? Lighten(BtnFill) : BtnFill, 3); dl.AddRect(pos, pos + new Vector2(width, height), BtnBord, 3); - dl.PushClipRect(pos, pos + new Vector2(width - 4, height), true); - dl.AddText(pos + new Vector2(6, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, shown); - dl.PopClipRect(); + // The arrow has its own strip on the right; the text is cut before it (2026-10-05: long + // state names ran under the arrow). + 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)); int picked = -1; ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); @@ -1154,7 +1154,7 @@ internal sealed partial class MetaFace : IImGuiPanel ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); - ImGuiNET.ImGui.SetNextWindowSize(new Vector2(Math.Max(240, width), Math.Min(items.Length * 21 + 4, 320))); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(Math.Max(240, width), Math.Min(rows * 21 + 4, 320))); bool open = ImGuiNET.ImGui.BeginPopup("##list"); ImGuiNET.ImGui.PopStyleVar(3); ImGuiNET.ImGui.PopStyleColor(2); @@ -1162,17 +1162,19 @@ internal sealed partial class MetaFace : IImGuiPanel { var pdl = ImGuiNET.ImGui.GetWindowDrawList(); float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; - for (int i = 0; i < items.Length; i++) + for (int i = 0; i < rows; i++) { ImGuiNET.ImGui.PushID(i); Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos(); bool click = ImGuiNET.ImGui.InvisibleButton("##item", new Vector2(iw, 20)); bool ih = ImGuiNET.ImGui.IsItemHovered(); ImGuiNET.ImGui.PopID(); - bool sel = i == selected; - pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? PickSel : ih ? Lighten(BtnFill) : BtnFill); - pdl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord); - pdl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : TextDim, items[i]); + bool isExtra = i == items.Length; + bool sel = !isExtra && i == selected; + pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? PickSel : ih ? Lighten(BtnFill) : isExtra ? NewFill : BtnFill); + pdl.AddRect(ip, ip + new Vector2(iw, 20), isExtra ? Green : BtnBord); + pdl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), isExtra ? Green : sel ? Teal : TextDim, + Fit(isExtra ? extra! : items[i], iw - 12)); if (click) { picked = i; @@ -1187,8 +1189,24 @@ internal sealed partial class MetaFace : IImGuiPanel return picked; } + /// A button width that fits its label at the current font size (labels overflowed fixed + /// widths at larger panel text sizes, 2026-10-05); never under . + internal static float BtnW(string label, float min) + { + int cut = label.IndexOf("##", StringComparison.Ordinal); + return Math.Max(min, ImGuiNET.ImGui.CalcTextSize(cut >= 0 ? label[..cut] : label).X + 18); + } + + private static string[] With(string[] items, string added) + { + var grown = new string[items.Length + 1]; + items.CopyTo(grown, 0); + grown[^1] = added; + return grown; + } + /// A full-width picker at the layout cursor. - private static int FlowPicker(string id, string shown, string[] items, int selected, float width) + private int FlowPicker(string id, string shown, string[] items, int selected, float width) { Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); int picked = Picker(id, shown, items, selected, p, width); @@ -1209,11 +1227,13 @@ internal sealed partial class MetaFace : IImGuiPanel buf.Shown = value; } bool edited = TextBox(id, buf.Bytes, width, hint, ImGuiInputTextFlags.None, out buf.Active, height); + _typingNow |= buf.Active; // autosave waits until the box is left if (edited) { string typed = Utf8(buf.Bytes); if (action) rule.ActionData = typed; else rule.ConditionData = typed; buf.Shown = typed; + _editChanged = true; } } @@ -1253,7 +1273,8 @@ internal sealed partial class MetaFace : IImGuiPanel /// cut to with "…", cached per text and width. private string Fit(string text, float width) { - if (_fit.TryGetValue(text, out var hit) && Math.Abs(hit.Width - width) < 0.5f) return hit.Shown; + var key = (text, (int)MathF.Round(width)); + if (_fit.TryGetValue(key, out string? hit)) return hit; string shown = text; if (ImGuiNET.ImGui.CalcTextSize(text).X > width) { @@ -1261,7 +1282,8 @@ internal sealed partial class MetaFace : IImGuiPanel while (n > 0 && ImGuiNET.ImGui.CalcTextSize(text.AsSpan(0, n).ToString() + "…").X > width) n--; shown = text.Substring(0, n) + "…"; } - _fit[text] = (width, shown); + if (_fit.Count > 4000) _fit.Clear(); // widths change while a panel is resized + _fit[key] = shown; return shown; } diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs new file mode 100644 index 0000000..994379d --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs @@ -0,0 +1,278 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MiniRemoteFace.cs +// The Mini Remote: a small grid of slots the player fills with items; a click +// uses that item. Engine only, ImGui only. (An idea from Silentkelpie's rynth +// PR #1, done as an engine face.) +// +// slots the item's icon and carried count; an empty slot shows + +// click uses the slot's item (the same object if still carried, else a +// stack with its name); on an empty slot, puts the selected +// inventory item there +// right Set to the selected item, Clear, More / Fewer slots +// drop drag an item from the game's inventory (or the Inventory panel) +// onto a slot to put it there (UiDropTargets, one target a slot) +// status the use waiting for the server, or how the last one ended +// +// A click never calls AC from the render thread: it posts an InventoryModel +// Use request, which AC's main thread sends at its next tick behind the +// client's own item gate (one item action at a time; a click while one waits +// is refused, not queued). Slots are saved per character (ItemHudStore). +// ============================================================================ + +using System; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.Data; +using RynthCore.Engine.UI.ScriptWindows; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class MiniRemoteFace : IImGuiPanel +{ + public const string Title = "Mini Remote"; + + public static void Register() + { + ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(184, 150), new Vector2(110, 96), EdgeToEdge: true, GripInBody: true), + () => new MiniRemoteFace()); + ItemHudStore.EnsureLoadQueued(); + } + + private const float Slot = 36f, Gap = 4f, IconSize = 32f, StatusH = 18f; + private const string MenuId = "##miniremote_menu"; + private static readonly string[] DropKeys = BuildDropKeys(); + + private static string[] BuildDropKeys() + { + var keys = new string[ItemHudCharacter.MaxSlots]; + for (int i = 0; i < keys.Length; i++) keys[i] = "MiniRemote#" + i.ToString(CultureInfo.InvariantCulture); + return keys; + } + + private readonly HudItemCache _items = new(); + private string _message = ""; + private uint _messageColor; + private long _messageUntilMs; + private int _menuSlot = -1; + private bool _openMenu; + + // Per-slot resolved item and count text, rebuilt when the carried items or the slots change. + private int _resolvedItemsVersion = -1; + private ItemHudCharacter? _resolvedFor; + private uint[] _slotItem = Array.Empty(); + private string[] _slotCount = Array.Empty(); + + public void OnShown() + { + ItemHudStore.EnsureLoadQueued(); + InventoryModel.Subscribe(); + } + + public void OnHidden() + { + InventoryModel.Unsubscribe(); + _menuSlot = -1; + } + + public void Draw() + { + float w = Begin(out Vector2 origin, out Vector2 size); + InventoryView view = InventoryModel.Current; + HudItem[] items = _items.Get(view); + ItemHudCharacter data = ItemHudStore.Current; + bool ready = ItemHudStore.Loaded && ItemHudStore.HasCharacter && view.PlayerId != 0; + Resolve(data, items); + + float gridH = Math.Max(Slot, Remaining(origin, size) - StatusH - GripOverlap()); + DrawGrid(data, items, w, gridH, ready); + DrawStatus(ready); + End(origin, size); + DrawMenu(data, items); + } + + private void Resolve(ItemHudCharacter data, HudItem[] items) + { + if (ReferenceEquals(data, _resolvedFor) && _resolvedItemsVersion == _items.Version) return; + _resolvedFor = data; + _resolvedItemsVersion = _items.Version; + int n = data.Slots.Length; + _slotItem = new uint[n]; + _slotCount = new string[n]; + for (int i = 0; i < n; i++) + { + RemoteSlot? s = data.Slots[i]; + if (s == null) { _slotCount[i] = ""; continue; } + _slotItem[i] = ItemHudMath.Resolve(items, s); + long c = s.Name.Length > 0 ? ItemHudMath.Count(items, s.Name) : _slotItem[i] != 0 ? 1 : 0; + _slotCount[i] = c > 1 ? c.ToString(CultureInfo.InvariantCulture) : c == 0 ? "0" : ""; + } + } + + // ── Grid ──────────────────────────────────────────────────────────── + + private void DrawGrid(ItemHudCharacter data, HudItem[] items, float w, float h, bool ready) + { + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + int cols = Math.Max(1, (int)((w + Gap) / (Slot + Gap))); + bool dragging = ready && UiDropTargets.AnyDragInProgress; + int clicked = -1; + + for (int i = 0; i < data.Slots.Length; i++) + { + var p = new Vector2(start.X + (i % cols) * (Slot + Gap), start.Y + (i / cols) * (Slot + Gap)); + var max = p + new Vector2(Slot, Slot); + RemoteSlot? s = data.Slots[i]; + + // One drop target a slot, so the item lands where it was let go. + UiDropTargets.Publish(DropKeys[i], Title, p, max, ready); + if (UiDropTargets.TryTake(DropKeys[i], out uint dropped) && ready) + SetSlot(i, dropped, items); + + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.PushID(i); + if (ImGuiNET.ImGui.InvisibleButton("##slot", new Vector2(Slot, Slot))) clicked = i; + bool hot = ImGuiNET.ImGui.IsItemHovered(); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _menuSlot = i; _openMenu = true; } + ImGuiNET.ImGui.PopID(); + + bool dropHot = dragging && UiDropTargets.IsCursorOver(DropKeys[i]); + dl.AddRectFilled(p, max, dropHot ? Green : hot ? Lighten(BtnFill) : BtnFill, 3); + dl.AddRect(p, max, dropHot || dragging ? Teal : BtnBord, 3); + + uint id = s != null && i < _slotItem.Length ? _slotItem[i] : 0; + Vector2 ip = p + new Vector2((Slot - IconSize) * 0.5f, (Slot - IconSize) * 0.5f); + if (s == null) + { + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Plus, p, new Vector2(Slot, Slot), Faded(Mute)); + if (hot) ImGuiNET.ImGui.SetItemTooltip("Empty slot: click to put the selected inventory item here, or drag an item onto it."); + continue; + } + if (id != 0 && ScriptIcons.TryGet(ScriptIconKind.Object, id, out IntPtr tex)) + dl.AddImage(tex, ip, ip + new Vector2(IconSize, IconSize)); + else + { + string initial = s.Name.Length > 0 ? s.Name[..1].ToUpperInvariant() : "?"; + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(initial); + dl.AddText(p + (new Vector2(Slot, Slot) - ts) * 0.5f, Faded(Text), initial); + } + string count = _slotCount[i]; + if (count.Length > 0) + { + Vector2 cs = ImGuiNET.ImGui.CalcTextSize(count); + Vector2 cp = max - cs - new Vector2(3, 1); + dl.AddText(cp + new Vector2(1, 1), 0xE0000000, count); + dl.AddText(cp, id == 0 ? Amber : Text, count); + } + if (hot) + ImGuiNET.ImGui.SetItemTooltip(id == 0 + ? $"{s.Name}: none carried.\nRight-click for options." + : $"{s.Name} ({count switch { "" => "1", _ => count }} carried)\nClick to use. Right-click for options."); + } + int rows = (data.Slots.Length + cols - 1) / cols; + ImGuiNET.ImGui.SetCursorScreenPos(start); + ImGuiNET.ImGui.Dummy(new Vector2(w, Math.Min(h, rows * (Slot + Gap)))); + + if (clicked >= 0 && ready) Click(data, items, clicked); + else if (clicked >= 0) ShowMessage(ItemHudStore.Loaded ? "Waiting for your character..." : "Loading...", Amber); + } + + private void Click(ItemHudCharacter data, HudItem[] items, int i) + { + RemoteSlot? s = data.Slots[i]; + if (s == null) + { + uint sel = InventoryModel.SelectedItem; + if (sel != 0) SetSlot(i, sel, items); + else ShowMessage("Select an inventory item (or drag one here) to fill this slot.", Amber); + return; + } + uint id = i < _slotItem.Length ? _slotItem[i] : 0; + if (id == 0) { ShowMessage($"No {s.Name} carried.", Amber); return; } + // Posted to AC's main thread (InventoryModel's tick), never sent from here. + var request = new InventoryRequest { Kind = InventoryActionKind.Use, ItemId = id, ItemName = s.Name }; + if (!InventoryModel.Request(request, out string why)) ShowMessage(why, Amber); + } + + private void SetSlot(int i, uint itemId, HudItem[] items) + { + string name = ItemCountFace.NameOf(itemId, items); + if (name.Length == 0) { ShowMessage("That item's name isn't known yet; try again in a moment.", Amber); return; } + if (!ItemHudMath.TryFind(items, itemId, out _)) + ShowMessage($"{name} isn't in your inventory; the slot uses one once you carry it.", Mute); + else ShowMessage($"Slot {i + 1}: {name}.", Mute); + if (!ItemHudStore.Update(d => d.WithSlot(i, new RemoteSlot(itemId, name)), out string why)) ShowMessage(why, Amber); + } + + // ── Status ────────────────────────────────────────────────────────── + + private void ShowMessage(string text, uint color) + { + _message = text; + _messageColor = color; + _messageUntilMs = Environment.TickCount64 + 3500; + } + + private void DrawStatus(bool ready) + { + InventoryPending? pending = InventoryModel.Pending; + InventoryResult? last = InventoryModel.LastResult; + long nowTicks = System.Diagnostics.Stopwatch.GetTimestamp(); + string text; + uint color; + if (_message.Length > 0 && Environment.TickCount64 < _messageUntilMs) { text = _message; color = _messageColor; } + else if (pending != null) { text = pending.WaitingForGame ? "Waiting for the game: " + pending.Label : pending.Label + "..."; color = Teal; } + else if (last != null && nowTicks - last.AtTicks < System.Diagnostics.Stopwatch.Frequency * 4) { text = last.Text; color = last.Ok ? Green : Amber; } + else if (!ready) { text = ItemHudStore.Loaded ? "Waiting for your character..." : "Loading..."; color = Mute; } + else { text = "Click: use. Right-click: options."; color = Faded(Mute); } + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X - BodyGripRoom(); + dl.PushClipRect(p, p + new Vector2(Math.Max(10, w), StatusH), true); + dl.AddText(p + new Vector2(0, 2), color, text); + dl.PopClipRect(); + ImGuiNET.ImGui.Dummy(new Vector2(Math.Max(10, w), StatusH)); + } + + private static float BodyGripRoom() => ImGuiPanelHost.BodyGripReserve; + + // ── Right-click menu ──────────────────────────────────────────────── + + private void DrawMenu(ItemHudCharacter data, HudItem[] items) + { + if (_openMenu) + { + _openMenu = false; + ImGuiNET.ImGui.OpenPopup(MenuId); + } + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 6)); + bool open = ImGuiNET.ImGui.BeginPopup(MenuId); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(3); + if (!open) return; + + int i = _menuSlot; + RemoteSlot? s = i >= 0 && i < data.Slots.Length ? data.Slots[i] : null; + Label(i >= 0 ? $"Slot {i + 1}{(s != null ? ": " + s.Name : " (empty)")}" : "Mini Remote", Mute); + uint sel = InventoryModel.SelectedItem; + string selName = sel != 0 && ItemHudMath.TryFind(items, sel, out HudItem it) ? it.Name : ""; + if (ImGuiNET.ImGui.MenuItem(selName.Length > 0 ? "Set to " + selName : "Set to the selected item", "", false, i >= 0 && selName.Length > 0)) + SetSlot(i, sel, items); + if (ImGuiNET.ImGui.MenuItem("Clear slot", "", false, s != null)) + if (!ItemHudStore.Update(d => d.WithSlot(i, null), out string why)) ShowMessage(why, Amber); + ImGuiNET.ImGui.Separator(); + int n = data.Slots.Length; + if (ImGuiNET.ImGui.MenuItem($"More slots ({n} now)", "", false, n < ItemHudCharacter.MaxSlots)) + ItemHudStore.Update(d => d.WithSlotCount(d.Slots.Length + 4), out _); + if (ImGuiNET.ImGui.MenuItem("Fewer slots (drops the last 4)", "", false, n > ItemHudCharacter.MinSlots)) + ItemHudStore.Update(d => d.WithSlotCount(d.Slots.Length - 4), out _); + ImGuiNET.ImGui.EndPopup(); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs index b2015ec..e6029f8 100644 --- a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs +++ b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs @@ -36,6 +36,10 @@ internal static class P1Faces SkillsFace.Register(); // Sense (watch list of names, anywhere the client knows): ImGui only, like Skills. SenseFace.Register(); + // Item Count and Mini Remote (items by name with their carried count; a grid of + // items to use): ImGui only, saved per character in item_huds.txt. + ItemCountFace.Register(); + MiniRemoteFace.Register(); } } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs index 6bd139a..6662c88 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs @@ -9,8 +9,10 @@ // dungeons, towns, portals, with type and distance; takes // coordinates too), favorites and recent places while it's empty, // Go / Route / Arrow / Stop, the "Use portals and recalls" and -// "Recalls" switches, the route step by step (the current step -// highlighted, with the distance left), then two sections that +// "Recalls" switches, the path markers switches (RynthNav 0.6.6: +// the trip on the ground, labels, guide line), the route step by +// step (the current step highlighted, with the distance left) and +// "save as nav route" (a RynthAi .nav in NavProfiles), then two sections that // fold: Recalls (portal ties and where they land, "which tie was // it?", the recalls routes can use) and Info (here, the NavData // folder, the route graph, tiles; Load / Test / Preview and the @@ -327,6 +329,7 @@ internal sealed class RynthNavFace : IImGuiPanel } NextLine(p, 28); if (st.HasAvoid) AvoidRows(st, w); + if (st.HasMarkers) MarkerRow(st, w); } Line(w); @@ -507,6 +510,7 @@ internal sealed class RynthNavFace : IImGuiPanel dl.AddRectFilled(new Vector2(top.X, top.Y), new Vector2(top.X + 3, bottom), RunGreen, 1); } } + DrawSaveRoute(st, cw); } // ── Recalls section ────────────────────────────────────────────────── @@ -672,6 +676,76 @@ internal sealed class RynthNavFace : IImGuiPanel NextLine(p, 26); } + // Path markers (RynthNav 0.6.6+): the planned trip on the ground, its labels, the guide line. + // Each click sends /rnav markers ... (saved in rynthnav.json by RynthNav). + private static void MarkerRow(RynthNavStatus st, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float w1 = (w - 8) * 0.40f, w2 = (w - 8) * 0.28f, w3 = w - 8 - w1 - w2; + if (Toggle("##mk_on", "Path markers", st.MarkersOn, p, w1)) + RynthNavCommands.Command(st.MarkersOn ? "markers off" : "markers on"); + ImGuiNET.ImGui.SetItemTooltip("Show the planned trip on the ground, the way RynthAi shows its nav routes: rings at the\n" + + "waypoints, lines between them, the portals, recalls and the goal in their own colours.\n" + + "They go when the trip ends, you stop, or you land somewhere that isn't on it." + + (st.MarkerStatus.Length > 0 ? "\n\nNow: " + st.MarkerStatus : "")); + if (Toggle("##mk_labels", "Labels", st.MarkerLabels, new Vector2(p.X + w1 + 4, p.Y), w2)) + RynthNavCommands.Command(st.MarkerLabels ? "markers labels off" : "markers labels on"); + ImGuiNET.ImGui.SetItemTooltip("Names over the portal, recall, Town Network and goal markers."); + if (Toggle("##mk_guide", "Guide line", st.MarkerGuide, new Vector2(p.X + w1 + w2 + 8, p.Y), w3)) + RynthNavCommands.Command(st.MarkerGuide ? "markers guide off" : "markers guide on"); + ImGuiNET.ImGui.SetItemTooltip("A line from your feet to the next waypoint (to the nearest marker for a plan you're not walking)."); + NextLine(p, 26); + } + + // ── Save as nav route (RynthNav 0.6.6+) ────────────────────────────── + + private readonly byte[] _saveName = new byte[96]; + private string _saveSeenFor = "\u0001"; + + /// + /// Below the route: a name (the place's, to start with) and Save, which writes the trip as a + /// RynthAi nav route into NavProfiles (/rnav saveroute). A name already taken: Replace. + /// + private void DrawSaveRoute(RynthNavStatus st, float cw) + { + if (!st.HasSave || !st.CanSave) return; + if (st.SaveFor != _saveSeenFor) { _saveSeenFor = st.SaveFor; WriteUtf8(_saveName, st.SaveName); } + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + SectionLabel("SAVE AS NAV ROUTE"); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const float bw = 78; + float boxW = Math.Max(60, cw - bw - 4); + bool enter = TextBox("##save_name", _saveName, p, boxW, "Route name", out _, ImGuiInputTextFlags.EnterReturnsTrue); + string name = Utf8(_saveName).Trim(); + bool can = name.Length > 0 && !st.SaveBusy; + if (Button("##save_go", st.SaveBusy ? "Saving…" : PhosphorIcons.FloppyDisk + " Save", new Vector2(p.X + boxW + 4, p.Y), new Vector2(bw, 22), + Teal, BtnFill, enabled: can) || (enter && can)) + RynthNavCommands.Command("saveroute " + name); + ImGuiNET.ImGui.SetItemTooltip("Write this trip as a RynthAi nav route (NavProfiles\\" + (name.Length > 0 ? name : "name") + ".nav):\n" + + "the walks as waypoints, portals as portal steps, recalls as recall steps.\n" + + "RynthAi lists it in its Nav picker; /ra nav load " + (name.Length > 0 ? name : "") + " loads it."); + NextLine(p, 26); + if (st.SaveConflict.Length > 0 && st.SaveConflict.Equals(name, StringComparison.OrdinalIgnoreCase)) + { + p = ImGuiNET.ImGui.GetCursorScreenPos(); + float rw = 78, tw = Math.Max(40, cw - rw - 4); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.PushClipRect(p, new Vector2(p.X + tw, p.Y + 22), true); + dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Amber, name + ".nav is already there."); + dl.PopClipRect(); + if (Button("##save_replace", "Replace", new Vector2(p.X + tw + 4, p.Y), new Vector2(rw, 22), Text, BtnFill, enabled: !st.SaveBusy, border: Amber)) + RynthNavCommands.Command("saveroute " + name + " overwrite"); + ImGuiNET.ImGui.SetItemTooltip("Replace NavProfiles\\" + name + ".nav with this trip"); + NextLine(p, 26); + } + if (st.SaveLast.Length > 0) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Wrapped(st.SaveLast, Mute, cw); + ImGuiNET.ImGui.PopFont(); + } + } + private static bool Toggle(string id, string label, bool on, Vector2 pos, float width) { string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label; diff --git a/src/RynthCore.Engine/ImGui/UiDropTargets.cs b/src/RynthCore.Engine/ImGui/UiDropTargets.cs index 670334a..7d8f7a5 100644 --- a/src/RynthCore.Engine/ImGui/UiDropTargets.cs +++ b/src/RynthCore.Engine/ImGui/UiDropTargets.cs @@ -42,6 +42,20 @@ internal static class UiDropTargets private static readonly Dictionary Targets = new(StringComparer.Ordinal); private static readonly object Sync = new(); + /// + /// The item being dragged in the engine's own Inventory panel (0 = none). Set by + /// InventoryFace each frame; a drop outside that panel is offered here with TryClaim. + /// + public static uint EngineDragObject + { + get => System.Threading.Volatile.Read(ref _engineDrag); + set => System.Threading.Volatile.Write(ref _engineDrag, value); + } + private static uint _engineDrag; + + /// An item is being dragged, out of AC's UI or the Inventory panel (the faces' "drop here" look). AC thread. + public static bool AnyDragInProgress => EngineDragObject != 0 || Compatibility.UiElementHooks.CurrentDragObject != 0; + /// /// Once per frame from a face's Draw: .. is the /// body in screen coordinates as ImGui sees them (FaceKit.Begin's origin and size). diff --git a/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs b/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs new file mode 100644 index 0000000..77b3c80 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs @@ -0,0 +1,43 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/VideoPatchBanner.cs +// The "rendering paused" banner of the video patch's "all" mode +// (D3D9/VideoPatch.cs): AC draws nothing then (the back buffer is only +// cleared to black), so the window says why and how to get it back. Drawn on +// ImGui's background list, under every panel. AC's render thread, inside the +// main ImGui frame. +// ============================================================================ + +using System.Numerics; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class VideoPatchBanner +{ + private const string Line1 = "Rendering paused (video patch: all)"; + private const string Line2 = "Type /rc video off, or Settings > Misc > Video patch"; + + private static readonly uint Back = RynthTheme.Argb(0xC0101820); + private static readonly uint Border = RynthTheme.Argb(0xFF34587A); + private static readonly uint Title = RynthTheme.Argb(0xFF26D9E6); + private static readonly uint Text = RynthTheme.Argb(0xFFB8C8D8); + + public static void Draw() + { + if (!D3D9.VideoPatch.WantsBanner) return; + ImGuiNET.ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + Vector2 display = io.DisplaySize; + if (display.X <= 1 || display.Y <= 1) return; + + var dl = ImGuiNET.ImGui.GetBackgroundDrawList(); + Vector2 s1 = ImGuiNET.ImGui.CalcTextSize(Line1); + Vector2 s2 = ImGuiNET.ImGui.CalcTextSize(Line2); + float w = System.MathF.Max(s1.X, s2.X) + 32f; + float h = s1.Y + s2.Y + 28f; + Vector2 min = new((display.X - w) * 0.5f, (display.Y - h) * 0.5f); + Vector2 max = min + new Vector2(w, h); + dl.AddRectFilled(min, max, Back, 6f); + dl.AddRect(min, max, Border, 6f); + dl.AddText(new Vector2((display.X - s1.X) * 0.5f, min.Y + 10f), Title, Line1); + dl.AddText(new Vector2((display.X - s2.X) * 0.5f, min.Y + 18f + s1.Y), Text, Line2); + } +} diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index 77193b7..d22c61f 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -84,13 +84,10 @@ internal static unsafe class Win32Backend /// HWNDs drop WM_LBUTTONDOWN on Win11 in some focus states). public const uint WM_RYNTH_RUN_ACTION = 0x8002; - /// UI deep-dive finding P0-1 belt-and-braces (2026-07-02): - /// posted (not sent) by LayeredWindow.Dispose to destroy an HWND on the - /// game thread without blocking the calling thread — DestroyWindow must - /// run on the owning thread, but the caller (often the Avalonia UI - /// thread, e.g. redocking a panel) doesn't need to wait for it to - /// finish. wParam carries the HWND to destroy. - public const uint WM_RYNTH_DESTROY_HWND = 0x8003; + // 0x8003 was WM_RYNTH_DESTROY_HWND: LayeredWindow.Dispose's backup that posted a + // panel's DestroyWindow to the game thread. Removed 2026-10-05 - DestroyWindow only + // works on the window's owner thread, which isn't always the game thread. Panels now + // destroy themselves (LayeredWindow WM_RYNTH_SELF_DESTROY). Don't reuse 0x8003. /// Destroys floating-panel HWNDs on the game thread (their owner). /// wParam != 0 includes this engine load's own panels (sent synchronously by @@ -395,38 +392,6 @@ internal static unsafe class Win32Backend RunOnGameThread(() => { action(); return true; }); } - /// - /// UI deep-dive finding P0-1 (2026-07-02): posts (does not block on) a - /// DestroyWindow for onto the game thread. - /// DestroyWindow must run on the HWND's owning thread, but unlike - /// RunOnGameThread this never needs the caller to observe a result — so - /// it uses a dedicated PostMessage instead of the shared - /// RunOnGameThread action slot, avoiding any risk of blocking the - /// caller (e.g. LayeredWindow.Dispose called from the Avalonia UI - /// thread while redocking a panel) on the game thread's WndProc. - /// - public static void PostDestroyWindow(IntPtr hwnd) - { - if (hwnd == IntPtr.Zero) return; - if (_gameHwnd == IntPtr.Zero) - { - // No game thread to marshal to (e.g. very early/late in - // lifecycle) — best-effort inline as LayeredWindow.Dispose's own - // fallback already does for the RunOnGameThread-unavailable case. - DestroyWindow(hwnd); - return; - } - - GetWindowThreadProcessId(_gameHwnd, out uint gameThreadId); - if (gameThreadId == GetCurrentThreadId()) - { - DestroyWindow(hwnd); - return; - } - - PostMessage(_gameHwnd, WM_RYNTH_DESTROY_HWND, hwnd, IntPtr.Zero); - } - /// Deactivates chat capture. The game HWND retains focus throughout so no /// Win32 focus transfer is needed. public static void ReturnFocusToGame() => ChatCaptureActive = false; @@ -797,24 +762,6 @@ internal static unsafe class Win32Backend return IntPtr.Zero; } - if (msg == WM_RYNTH_DESTROY_HWND) - { - IntPtr target = wParam; - try - { - bool destroyed = DestroyWindow(target); - int err = destroyed ? 0 : Marshal.GetLastWin32Error(); - RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND DestroyWindow(0x{target.ToInt64():X}) = {destroyed} err={err}."); - // 5 = ACCESS_DENIED: the window belongs to another thread. At least - // take it off the screen so a closed panel can't linger beside a - // reopened one (ShowWindow works across threads). - if (!destroyed && err == 5) - ShowWindow(target, 0 /* SW_HIDE */); - } - catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND threw {ex.GetType().Name}: {ex.Message}"); } - return IntPtr.Zero; - } - if (msg == WM_RYNTH_SWEEP_PANELS) { try { UI.LayeredWindow.DestroyThreadPanelWindows(includeThisGeneration: wParam != IntPtr.Zero); } diff --git a/src/RynthCore.Engine/LogPaths.cs b/src/RynthCore.Engine/LogPaths.cs index 8cc3008..3e2cced 100644 --- a/src/RynthCore.Engine/LogPaths.cs +++ b/src/RynthCore.Engine/LogPaths.cs @@ -27,7 +27,7 @@ namespace RynthCore.Engine; internal static class LogPaths { /// Unified log directory for all RynthCore components. - internal const string LogDirectory = @"C:\Games\RynthCore\Logs"; + internal static string LogDirectory => RynthCore.Install.RynthInstallPaths.CoreLogsDir; // C:\Games\RynthCore\Logs by default /// Shared launch/orchestration log (injector + launcher + per-engine session pointer). internal const string SharedLogFileName = "RynthCore.log"; diff --git a/src/RynthCore.Engine/Net/FlightCapture.cs b/src/RynthCore.Engine/Net/FlightCapture.cs new file mode 100644 index 0000000..c633947 --- /dev/null +++ b/src/RynthCore.Engine/Net/FlightCapture.cs @@ -0,0 +1,932 @@ +// ============================================================================ +// RynthCore.Engine - Net/FlightCapture.cs +// What the flight recorder keeps from each datagram, and its stall detectors. +// +// Runs inside the sendto/recvfrom detours (Compatibility/RawPacketHooks.cs), after the +// real call, on the bytes the client sent or got. Per datagram: the header walk +// (AcPacketWire.LocateFragments), then for every fragment that starts a message, the +// opcode decides whether the message is kept. A kept message is its first +// FlightEntry.DataCap bytes, copied into the ring; decoding into text happens only when +// the ring is dumped (FlightFormat). No allocation, no lock on the datagram path +// (the engine-call table and the detectors take a small lock on the few messages +// they care about). +// +// Kept, client to server: every game action (0xF7B1) - AutonomousPosition at most one +// per AutoPosIntervalMs unless a sequence or the cell changed - and any other message. +// Kept, server to client: the game events in WantedEvent, the player's motion, +// position (rate-limited like AutonomousPosition), vector and effect messages, +// teleports, system text, and object messages (delete, pickup, state, motion) about +// the objects the character just used. +// +// Strictly read-only: nothing here changes, delays or drops traffic. +// Pure code (no engine state); compiled into tools/FlightRecorderTests. +// ============================================================================ + +using System; +using System.Buffers.Binary; +using System.Threading; + +namespace RynthCore.Engine.Net; + +/// Opcodes, game event types and game action types the recorder knows. +internal static class FlightOp +{ + // Top-level messages. + public const uint GameEvent = 0xF7B0, GameAction = 0xF7B1; + public const uint UpdateMotion = 0xF74C, UpdatePosition = 0xF748, PlayerTeleport = 0xF751, VectorUpdate = 0xF74E; + public const uint PlayEffect = 0xF755, PlayScriptId = 0xF754, ObjectDelete = 0xF747, PickupEvent = 0xF74A, SetState = 0xF74B; + public const uint ParentEvent = 0xF749, ServerMessage = 0xF7E0, PlayerCreate = 0xF746, CharacterLogOff = 0xF653; + public const uint InventoryRemoveObject = 0x0024, PlayerKilled = 0x019E, SetStackSize = 0x0197; + + // Game events (inside 0xF7B0). + public const uint EvPopupString = 0x0004, EvInventoryPutObjInContainer = 0x0022, EvWieldObject = 0x0023; + public const uint EvCloseGroundContainer = 0x0052, EvInventoryServerSaveFailed = 0x00A0, EvViewContents = 0x0196; + public const uint EvInventoryPutObjectIn3D = 0x019A, EvAttackDone = 0x01A7, EvMagicRemoveSpell = 0x01A8; + public const uint EvVictimNotification = 0x01AC, EvKillerNotification = 0x01AD, EvAttackerNotification = 0x01B1; + public const uint EvDefenderNotification = 0x01B2, EvEvasionAttacker = 0x01B3, EvEvasionDefender = 0x01B4; + public const uint EvCombatCommenceAttack = 0x01B8, EvUseDone = 0x01C7, EvConfirmationRequest = 0x0274; + public const uint EvWeenieError = 0x028A, EvWeenieErrorWithString = 0x028B; + public const uint EvMagicUpdateSpell = 0x02C1, EvMagicUpdateEnchantment = 0x02C2, EvMagicRemoveEnchantment = 0x02C3; + public const uint EvMagicUpdateMultipleEnchantments = 0x02C4, EvMagicRemoveMultipleEnchantments = 0x02C5; + public const uint EvMagicPurgeEnchantments = 0x02C6, EvMagicDispelEnchantment = 0x02C7; + public const uint EvMagicDispelMultipleEnchantments = 0x02C8, EvTransientString = 0x02EB, EvMagicPurgeBadEnchantments = 0x0312; + + // Game actions (inside 0xF7B1). + public const uint AcTargetedMeleeAttack = 0x0008, AcTargetedMissileAttack = 0x000A, AcTalk = 0x0015; + public const uint AcPutItemInContainer = 0x0019, AcGetAndWieldItem = 0x001A, AcDropItem = 0x001B; + public const uint AcTalkDirect = 0x0032, AcUseWithTarget = 0x0035, AcUse = 0x0036; + public const uint AcRaiseVital = 0x0044, AcRaiseAttribute = 0x0045, AcRaiseSkill = 0x0046, AcTrainSkill = 0x0047; + public const uint AcCastUntargetedSpell = 0x0048, AcCastTargetedSpell = 0x004A, AcChangeCombatMode = 0x0053; + public const uint AcStackableMerge = 0x0054, AcStackableSplitToContainer = 0x0055, AcStackableSplitTo3D = 0x0056; + public const uint AcTell = 0x005D, AcLoginComplete = 0x00A1, AcIdentifyObject = 0x00C8, AcGiveObjectRequest = 0x00CD; + public const uint AcChatChannel = 0x0147, AcNoLongerViewingContents = 0x0195, AcStackableSplitToWield = 0x019B; + public const uint AcCancelAttack = 0x01B7, AcQueryHealth = 0x01BF; + public const uint AcJump = 0xF61B, AcMoveToState = 0xF61C, AcDoMovementCommand = 0xF61E, AcTurnTo = 0xF649; + public const uint AcStopMovementCommand = 0xF661, AcAutonomyLevel = 0xF752, AcAutonomousPosition = 0xF753; + public const uint AcJumpNonAutonomous = 0xF7C9; + + // WeenieError codes the detectors look at. + public const uint ErrYoureTooBusy = 0x001D; + + /// The server-to-client game events the recorder keeps. + public static bool WantedEvent(uint ev) => ev switch + { + EvPopupString or EvInventoryPutObjInContainer or EvWieldObject or EvCloseGroundContainer + or EvInventoryServerSaveFailed or EvViewContents or EvInventoryPutObjectIn3D or EvAttackDone + or EvMagicRemoveSpell or EvVictimNotification or EvKillerNotification or EvAttackerNotification + or EvDefenderNotification or EvEvasionAttacker or EvEvasionDefender or EvCombatCommenceAttack + or EvUseDone or EvConfirmationRequest or EvWeenieError or EvWeenieErrorWithString + or EvMagicUpdateSpell or EvMagicUpdateEnchantment or EvMagicRemoveEnchantment + or EvMagicUpdateMultipleEnchantments or EvMagicRemoveMultipleEnchantments or EvMagicPurgeEnchantments + or EvMagicDispelEnchantment or EvMagicDispelMultipleEnchantments or EvTransientString + or EvMagicPurgeBadEnchantments => true, + _ => false, + }; + + /// Actions whose first argument (and for some the second) names the object the character uses. + public static bool UsesObject(uint action) => action is AcUse or AcUseWithTarget or AcPutItemInContainer + or AcNoLongerViewingContents or AcGiveObjectRequest or AcDropItem or AcGetAndWieldItem or AcIdentifyObject; +} + +/// The per-second marker's numbers (FlightMark.Summary), packed into the entry's Data. +internal struct FlightSummary +{ + public const int Size = 40; + public const int Unknown = int.MinValue; + + public int RealBusy; // AC's m_cBusy; Unknown when unreadable + public int ShadowBusy; // the engine's counter + public uint PendingType; // ClientActionGates pending item request type; 0xFFFFFFFF unknown + public uint PendingObject; + public byte Attacking; // 0/1, 255 unknown + public byte Gesture; // cast/action gesture animating: 0/1, 255 unknown + public ushort InPackets, InMessages, InKept, InRetransmits, InResendRequests; + public ushort OutPackets, OutMessages, OutKept, OutRetransmits, OutResendRequests; + public ushort SendErrors; + + public readonly void Write(Span d) + { + BinaryPrimitives.WriteInt32LittleEndian(d, RealBusy); + BinaryPrimitives.WriteInt32LittleEndian(d[4..], ShadowBusy); + BinaryPrimitives.WriteUInt32LittleEndian(d[8..], PendingType); + BinaryPrimitives.WriteUInt32LittleEndian(d[12..], PendingObject); + d[16] = Attacking; + d[17] = Gesture; + W(d, 0, InPackets); W(d, 1, InMessages); W(d, 2, InKept); W(d, 3, InRetransmits); W(d, 4, InResendRequests); + W(d, 5, OutPackets); W(d, 6, OutMessages); W(d, 7, OutKept); W(d, 8, OutRetransmits); W(d, 9, OutResendRequests); + W(d, 10, SendErrors); + } + + private static ushort R(ReadOnlySpan d, int i) => BinaryPrimitives.ReadUInt16LittleEndian(d[(18 + 2 * i)..]); + private static void W(Span d, int i, ushort v) => BinaryPrimitives.WriteUInt16LittleEndian(d[(18 + 2 * i)..], v); + + public static FlightSummary Read(ReadOnlySpan d) + { + var s = new FlightSummary(); + if (d.Length < Size) { s.RealBusy = s.ShadowBusy = Unknown; s.PendingType = 0xFFFFFFFF; s.Attacking = s.Gesture = 255; return s; } + s.RealBusy = BinaryPrimitives.ReadInt32LittleEndian(d); + s.ShadowBusy = BinaryPrimitives.ReadInt32LittleEndian(d[4..]); + s.PendingType = BinaryPrimitives.ReadUInt32LittleEndian(d[8..]); + s.PendingObject = BinaryPrimitives.ReadUInt32LittleEndian(d[12..]); + s.Attacking = d[16]; + s.Gesture = d[17]; + s.InPackets = R(d, 0); s.InMessages = R(d, 1); s.InKept = R(d, 2); s.InRetransmits = R(d, 3); s.InResendRequests = R(d, 4); + s.OutPackets = R(d, 5); s.OutMessages = R(d, 6); s.OutKept = R(d, 7); s.OutRetransmits = R(d, 8); s.OutResendRequests = R(d, 9); + s.SendErrors = R(d, 10); + return s; + } +} + +internal sealed unsafe class FlightCapture +{ + public const int AutoPosIntervalMs = 2000; // AutonomousPosition / the player's UpdatePosition + public const int EngineMatchMs = 1500; // an engine call explains an action sent this soon after + public const int EngineRepeatMs = 1000; // identical engine calls this close are folded into one line + public const int TargetMemoryMs = 20_000; // objects used this recently have their messages kept + public const int ResendMarkIntervalMs = 500; // resend-request markers per direction + public const int UseSettleMs = 1500; // UseDone(0) with nothing else this long after = refused + public const int UseRefusalStreak = 4; // refused uses in a row that trigger a dump + public const int UseUnansweredMs = 5000; // a use with no UseDone this long = unanswered + public const int UseUnansweredStreak = 3; + public const int TooBusyWindowMs = 20_000; + public const int TooBusyStreak = 3; + + public readonly FlightRing Ring; + private readonly Func _clock; + private readonly long _ticksPerSecond; + + private volatile uint _playerId; + public uint PlayerId => _playerId; + + // ── per direction (each touched by its own detour only) ──────────────── + private sealed class Side + { + public readonly uint[] Seen = new uint[256]; // fragment sequences of recent messages + public int SeenNext; + public long PosStamp; // last kept position message + public uint PosCell; + public ushort PosA, PosB, PosC, PosD; // its four sequence numbers + public uint PosSuppressed; + public long ResendStamp; + public uint ResendSuppressed; + // counters since the last summary + public int Packets, Messages, Kept, Retransmits, ResendRequests, SendErrors; + } + private readonly Side _in = new(), _out = new(); + + // ── objects the character used (written by outbound, read by inbound) ── + private readonly uint[] _targets = new uint[8]; + private readonly long[] _targetAt = new long[8]; + private int _targetNext; + + // ── engine calls waiting for their action ────────────────────────────── + private readonly object _engineLock = new(); + private struct PendingCall { public string? Name; public uint A, B; public long Stamp; public bool Used; } + private readonly PendingCall[] _pending = new PendingCall[16]; + private int _pendingNext; + private string? _repeatName; + private uint _repeatA, _repeatB, _repeatCount; + private long _repeatStamp; + + // ── stall detectors ──────────────────────────────────────────────────── + private readonly object _detectLock = new(); + private struct UseTrack { public uint Target; public bool Counted; public long Sent; public bool Answered; public uint Err; public long AnsweredAt; public bool Responded; public bool Settled; } + private readonly UseTrack[] _uses = new UseTrack[8]; + private int _useCount; + private int _refusedStreak, _unansweredStreak; + private readonly uint[] _refusedTargets = new uint[UseRefusalStreak]; + private readonly long[] _tooBusy = new long[TooBusyStreak]; + private int _tooBusyNext; + private string? _trigger; + + public FlightCapture(int capacityPow2, Func clock, long ticksPerSecond) + { + Ring = new FlightRing(capacityPow2); + _clock = clock; + _ticksPerSecond = ticksPerSecond; + } + + public long Now() => _clock(); + private long Ms(long ticks) => ticks * 1000 / _ticksPerSecond; + private long TicksFromMs(long ms) => ms * _ticksPerSecond / 1000; + + /// Set the player id when it is known some other way (also learned from game event headers). + public void SetPlayerId(uint id) { if (id != 0) _playerId = id; } + + // ── datagrams ────────────────────────────────────────────────────────── + + /// One datagram the client sent () or got. + public void OnDatagram(bool outbound, byte* data, int length, bool sendFailed = false) + { + if (data == null || length < AcPacketWire.HeaderSize) + return; + Side side = outbound ? _out : _in; + side.Packets++; + if (sendFailed) side.SendErrors++; + uint flags = AcPacketWire.ReadU32(data + 4); + bool retransmit = (flags & PacketFlags.Retransmission) != 0; + if (retransmit) side.Retransmits++; + + long now = 0; + if ((flags & (PacketFlags.RequestRetransmit | PacketFlags.Disconnect)) != 0) + { + now = _clock(); + NoteControl(outbound, side, flags, data, length, now); + } + + if (AcPacketWire.LocateFragments(data, length, out int pos, out int end) != PacketWalk.Ok) + return; + + int guard = 0; + while (pos + AcPacketWire.FragmentHeaderSize <= end && ++guard <= 64) + { + byte* frag = data + pos; + int size = AcPacketWire.ReadU16(frag + 10); + if (size < AcPacketWire.FragmentHeaderSize || pos + size > end) + break; + pos += size; + ushort index = AcPacketWire.ReadU16(frag + 12); + if (index != 0) + continue; + int msgLen = size - AcPacketWire.FragmentHeaderSize; + if (msgLen < 4) + continue; + uint seq = AcPacketWire.ReadU32(frag); + ushort count = AcPacketWire.ReadU16(frag + 8); + if (retransmit && Seen(side, seq)) + continue; // the first copy was already handled + Remember(side, seq); + side.Messages++; + if (now == 0) now = _clock(); + + FlightFlags f = FlightFlags.None; + if (count > 1) f |= FlightFlags.MultiFragment; + if (retransmit) f |= FlightFlags.Retransmit; + if (sendFailed) f |= FlightFlags.SendFailed; + int fullLen = count > 1 ? count * msgLen : msgLen; + byte* msg = frag + AcPacketWire.FragmentHeaderSize; + if (outbound) Outbound(msg, msgLen, fullLen, seq, f, now); + else Inbound(msg, msgLen, fullLen, seq, f, now); + } + } + + private static bool Seen(Side side, uint seq) + { + uint[] seen = side.Seen; + for (int i = 0; i < seen.Length; i++) + if (seen[i] == seq) return true; + return false; + } + + private static void Remember(Side side, uint seq) + { + side.Seen[side.SeenNext] = seq; + side.SeenNext = (side.SeenNext + 1) & (side.Seen.Length - 1); + } + + private void NoteControl(bool outbound, Side side, uint flags, byte* data, int length, long now) + { + uint bit = (flags & PacketFlags.Disconnect) != 0 ? PacketFlags.Disconnect : PacketFlags.RequestRetransmit; + uint count = 0, first = 0; + if (bit == PacketFlags.RequestRetransmit) + { + side.ResendRequests++; + // The resend list is the first optional header when ServerSwitch is absent (it is + // between ServerSwitch and the rest). Read it only when it is plainly there. + int p = AcPacketWire.HeaderSize + ((flags & PacketFlags.ServerSwitch) != 0 ? 8 : 0); + if (p + 8 <= length) + { + count = AcPacketWire.ReadU32(data + p); + first = count > 0 ? AcPacketWire.ReadU32(data + p + 4) : 0; + } + if (Ms(now - side.ResendStamp) < ResendMarkIntervalMs) + { + side.ResendSuppressed++; + return; + } + side.ResendStamp = now; + } + Span dirByte = stackalloc byte[4]; + dirByte[0] = (byte)(outbound ? FlightDir.Out : FlightDir.In); + BinaryPrimitives.WriteUInt16LittleEndian(dirByte[2..], (ushort)Math.Min(side.ResendSuppressed, ushort.MaxValue)); + Ring.WriteMarkBytes(now, FlightMark.NetControl, bit, count, first, dirByte); + side.ResendSuppressed = 0; + } + + // ── client to server ─────────────────────────────────────────────────── + + private void Outbound(byte* msg, int len, int fullLen, uint seq, FlightFlags f, long now) + { + uint opcode = AcPacketWire.ReadU32(msg); + if (opcode != FlightOp.GameAction || len < 12) + { + Keep(_out, now, FlightDir.Out, f, msg, len, fullLen, seq, 0); + return; + } + uint action = AcPacketWire.ReadU32(msg + 8); + uint arg0 = len >= 16 ? AcPacketWire.ReadU32(msg + 12) : 0; + uint arg1 = len >= 20 ? AcPacketWire.ReadU32(msg + 16) : 0; + + if (action == FlightOp.AcAutonomousPosition) + { + // Position(cell, xyz, wxyz) = 32 bytes after the action header, then 4 u16 sequences. + if (len >= 12 + 32 + 8) + { + uint cell = arg0; + byte* s = msg + 12 + 32; + if (!PositionChanged(_out, now, cell, AcPacketWire.ReadU16(s), AcPacketWire.ReadU16(s + 2), AcPacketWire.ReadU16(s + 4), AcPacketWire.ReadU16(s + 6))) + return; + } + Keep(_out, now, FlightDir.Out, f | FlightFlags.Client, msg, len, fullLen, seq, TakePosSuppressed(_out)); + return; + } + + if (FlightOp.UsesObject(action)) + { + NoteTarget(arg0, now); + if (action is FlightOp.AcUseWithTarget or FlightOp.AcPutItemInContainer or FlightOp.AcGiveObjectRequest) + NoteTarget(arg1, now); + } + + f |= MatchEngineCall(action, arg0, arg1, now) ? FlightFlags.Engine : FlightFlags.Client; + Keep(_out, now, FlightDir.Out, f, msg, len, fullLen, seq, 0); + + if (action == FlightOp.AcUse || action == FlightOp.AcUseWithTarget) + DetectUseSent(action == FlightOp.AcUse ? arg0 : arg1, counted: action == FlightOp.AcUse, now); + } + + // ── server to client ─────────────────────────────────────────────────── + + private void Inbound(byte* msg, int len, int fullLen, uint seq, FlightFlags f, long now) + { + uint opcode = AcPacketWire.ReadU32(msg); + uint obj = len >= 8 ? AcPacketWire.ReadU32(msg + 4) : 0; + switch (opcode) + { + case FlightOp.GameEvent: + { + if (len < 16) return; + if (obj != 0 && obj != _playerId) _playerId = obj; // game events are addressed to the player + uint ev = AcPacketWire.ReadU32(msg + 12); + if (!FlightOp.WantedEvent(ev)) return; + Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0); + uint a = len >= 20 ? AcPacketWire.ReadU32(msg + 16) : 0; + if (ev == FlightOp.EvUseDone) DetectUseDone(a, now); + else if (ev == FlightOp.EvViewContents) DetectOpened(a, now); + else if ((ev == FlightOp.EvWeenieError || ev == FlightOp.EvWeenieErrorWithString) && a == FlightOp.ErrYoureTooBusy) + DetectTooBusy(now); + return; + } + case FlightOp.UpdateMotion: + if (obj == _playerId && obj != 0) + { + Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0); + DetectPlayerMotion(msg, len, now); + } + else if (IsTarget(obj, now)) + { + Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0); + DetectResponse(obj, now); + } + return; + case FlightOp.UpdatePosition: + if (obj == 0 || obj != _playerId) return; + if (TryPositionPackSequences(msg + 8, len - 8, out uint cell, out ushort s1, out ushort s2, out ushort s3, out ushort s4) + && !PositionChanged(_in, now, cell, s1, s2, s3, s4)) + return; + Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, TakePosSuppressed(_in)); + return; + case FlightOp.VectorUpdate: + case FlightOp.PlayEffect: + case FlightOp.PlayScriptId: + case FlightOp.ParentEvent: + if (obj != 0 && (obj == _playerId || IsTarget(obj, now))) + Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0); + return; + case FlightOp.ObjectDelete: + case FlightOp.PickupEvent: + case FlightOp.SetState: + case FlightOp.InventoryRemoveObject: + case FlightOp.SetStackSize: + if (obj != 0 && (obj == _playerId || IsTarget(obj, now))) + { + Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0); + DetectResponse(obj, now); + } + return; + case FlightOp.PlayerCreate: + if (obj != 0) _playerId = obj; + Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0); + return; + case FlightOp.PlayerTeleport: + case FlightOp.CharacterLogOff: + case FlightOp.PlayerKilled: + Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0); + return; + case FlightOp.ServerMessage: + Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0); + if (ContainsTooBusy(msg + 4, len - 4)) + DetectTooBusy(now); + return; + } + } + + private void Keep(Side side, long now, FlightDir dir, FlightFlags f, byte* msg, int len, int fullLen, uint seq, uint suppressed) + { + side.Kept++; + Ring.WriteMessage(now, dir, f, msg, len, fullLen, seq, suppressed); + } + + // ── positions ────────────────────────────────────────────────────────── + + /// True when this position message should be kept (and remembers it as the last kept). + private bool PositionChanged(Side side, long now, uint cell, ushort a, ushort b, ushort c, ushort d) + { + bool keep = side.PosStamp == 0 || cell != side.PosCell || a != side.PosA || c != side.PosC || d != side.PosD + || Ms(now - side.PosStamp) >= AutoPosIntervalMs; + if (!keep) + { + side.PosSuppressed++; + return false; + } + side.PosStamp = now; + side.PosCell = cell; + side.PosA = a; side.PosB = b; side.PosC = c; side.PosD = d; + return true; + } + + private static uint TakePosSuppressed(Side side) + { + uint n = side.PosSuppressed; + side.PosSuppressed = 0; + return n; + } + + /// + /// PositionPack: flags, cell, xyz, the rotation parts the flags don't drop, velocity when + /// flagged, placement when flagged, then four u16 sequences (instance, position, teleport, + /// force position). + /// + public static bool TryPositionPackSequences(byte* p, int len, out uint cell, out ushort s1, out ushort s2, out ushort s3, out ushort s4) + { + cell = 0; s1 = s2 = s3 = s4 = 0; + if (len < 20) return false; + uint flags = AcPacketWire.ReadU32(p); + cell = AcPacketWire.ReadU32(p + 4); + int pos = 20; + for (uint bit = 0x08; bit <= 0x40; bit <<= 1) + if ((flags & bit) == 0) pos += 4; + if ((flags & 0x01) != 0) pos += 12; + if ((flags & 0x02) != 0) pos += 4; + if (pos + 8 > len) return false; + s1 = AcPacketWire.ReadU16(p + pos); + s2 = AcPacketWire.ReadU16(p + pos + 2); + s3 = AcPacketWire.ReadU16(p + pos + 4); + s4 = AcPacketWire.ReadU16(p + pos + 6); + return true; + } + + // ── objects the character used ───────────────────────────────────────── + + private void NoteTarget(uint id, long now) + { + if (id == 0 || id == _playerId) return; + for (int i = 0; i < _targets.Length; i++) + { + if (_targets[i] == id) { _targetAt[i] = now; return; } + } + int k = _targetNext; + _targets[k] = id; + _targetAt[k] = now; + _targetNext = (k + 1) & (_targets.Length - 1); + } + + private bool IsTarget(uint id, long now) + { + if (id == 0) return false; + for (int i = 0; i < _targets.Length; i++) + if (_targets[i] == id) return Ms(now - _targetAt[i]) <= TargetMemoryMs; + return false; + } + + // ── engine calls ─────────────────────────────────────────────────────── + + /// + /// The engine made a direct action call (AcActionTrace names). Writes a marker (identical + /// calls within EngineRepeatMs fold into one "repeated" line) and remembers the call so + /// the action it produces is tagged as the engine's. + /// + public void EngineCall(string name, uint a, uint b) + { + long now = _clock(); + lock (_engineLock) + { + if (Expects(name)) + { + ref PendingCall p = ref FindPending(name, a, b, now); + p.Name = name; p.A = a; p.B = b; p.Stamp = now; p.Used = false; + } + if (name == _repeatName) + { + if (a == _repeatA && b == _repeatB && Ms(now - _repeatStamp) < EngineRepeatMs) + { + _repeatCount++; + _repeatStamp = now; + return; + } + } + FlushRepeat(); + _repeatName = name; _repeatA = a; _repeatB = b; _repeatStamp = now; _repeatCount = 0; + } + Ring.WriteMark(now, FlightMark.EngineCall, name, a, b, 0, default); + } + + /// Writes the "repeated N more times" line for folded calls, if any (call under _engineLock). + private void FlushRepeat() + { + if (_repeatCount > 0 && _repeatName != null) + Ring.WriteMark(_repeatStamp, FlightMark.EngineCall, _repeatName, _repeatA, _repeatB, _repeatCount, default); + _repeatCount = 0; + } + + /// Flush a pending "repeated" line (before a dump). + public void FlushEngineRepeats() + { + lock (_engineLock) + { + FlushRepeat(); + _repeatName = null; + } + } + + private ref PendingCall FindPending(string name, uint a, uint b, long now) + { + for (int i = 0; i < _pending.Length; i++) + { + ref PendingCall p = ref _pending[i]; + if (p.Name == name && p.A == a && p.B == b) return ref p; + } + int k = _pendingNext; + _pendingNext = (k + 1) % _pending.Length; + return ref _pending[k]; + } + + private bool MatchEngineCall(uint action, uint arg0, uint arg1, long now) + { + lock (_engineLock) + { + int best = -1; + for (int i = 0; i < _pending.Length; i++) + { + ref PendingCall p = ref _pending[i]; + if (p.Name == null || p.Used || now < p.Stamp || Ms(now - p.Stamp) > EngineMatchMs) continue; + if (!Produces(p.Name, p.A, p.B, action, arg0, arg1)) continue; + if (best < 0 || p.Stamp < _pending[best].Stamp) best = i; // oldest first + } + if (best < 0) return false; + _pending[best].Used = true; + return true; + } + } + + /// Engine calls that send something to the server. + private static bool Expects(string name) => name switch + { + "SelectItem" or "SelectItem-dedup" or "OverlaySelect" => false, + _ => true, + }; + + /// Would engine call (a, b) send this action? + public static bool Produces(string name, uint a, uint b, uint action, uint arg0, uint arg1) + { + switch (name) + { + case "UseObject": + return (action == FlightOp.AcUse || action == FlightOp.AcUseWithTarget) && arg0 == a; + case "UseObjectOn": + case "UseEquippedItem": + return (action == FlightOp.AcUseWithTarget && arg0 == a && (b == 0 || arg1 == b)) + || (action == FlightOp.AcUse && arg0 == a); + case "CastSpell": + return (action == FlightOp.AcCastTargetedSpell && arg1 == b) + || (action == FlightOp.AcCastUntargetedSpell && arg0 == b); + case "ChangeCombatMode": + return action == FlightOp.AcChangeCombatMode && arg0 == a; + case "MeleeAttack": + return action == FlightOp.AcTargetedMeleeAttack && arg0 == a; + case "MissileAttack": + return action == FlightOp.AcTargetedMissileAttack && arg0 == a; + case "NativeAttack": + return action is FlightOp.AcTargetedMeleeAttack or FlightOp.AcTargetedMissileAttack; + case "CloseContainer": + return action == FlightOp.AcNoLongerViewingContents && arg0 == a; + case "MoveItemExternal": + case "MoveItemInternal": + return (action is FlightOp.AcPutItemInContainer or FlightOp.AcDropItem or FlightOp.AcGetAndWieldItem + or FlightOp.AcStackableMerge or FlightOp.AcStackableSplitToContainer or FlightOp.AcStackableSplitTo3D + or FlightOp.AcStackableSplitToWield && arg0 == a) + || (action == FlightOp.AcGiveObjectRequest && arg1 == a); + case "SplitStackInternal": + return action is FlightOp.AcStackableSplitToContainer or FlightOp.AcStackableSplitTo3D or FlightOp.AcStackableSplitToWield + && arg0 == a; + case "MergeStackInternal": + return action == FlightOp.AcStackableMerge && arg0 == a; + case "GiveObjectTo": + return action == FlightOp.AcGiveObjectRequest && arg1 == a; + case "WieldItem": + return action == FlightOp.AcGetAndWieldItem && arg0 == a; + case "CancelAttack": + return action == FlightOp.AcCancelAttack; + case "Raise": + return action is FlightOp.AcRaiseVital or FlightOp.AcRaiseAttribute or FlightOp.AcRaiseSkill; + case "TrainSkill": + return action == FlightOp.AcTrainSkill; + case "DoMovement": + case "StopMovement": + case "SetMotion": + case "SetAutoRun": + case "StopCompletely": + case "TurnToHeading": + return action is FlightOp.AcMoveToState or FlightOp.AcDoMovementCommand or FlightOp.AcStopMovementCommand or FlightOp.AcTurnTo; + case "TapJump": + case "DoJump": + case "CommenceJump": + case "LaunchJumpWithMotion": + case "JumpNonAutonomous": + return action is FlightOp.AcJump or FlightOp.AcJumpNonAutonomous or FlightOp.AcMoveToState; + default: + return false; + } + } + + // ── markers ──────────────────────────────────────────────────────────── + + public void Mark(FlightMark kind, uint a = 0, uint b = 0, uint c = 0, string? text = null) + => Ring.WriteMark(_clock(), kind, null, a, b, c, text.AsSpan()); + + // ── summary ──────────────────────────────────────────────────────────── + + /// Fills the link counters since the last call and resets them. + public void TakeCounters(ref FlightSummary s) + { + static ushort C(ref int v) { int x = Interlocked.Exchange(ref v, 0); return (ushort)Math.Clamp(x, 0, ushort.MaxValue); } + s.InPackets = C(ref _in.Packets); s.InMessages = C(ref _in.Messages); s.InKept = C(ref _in.Kept); + s.InRetransmits = C(ref _in.Retransmits); s.InResendRequests = C(ref _in.ResendRequests); + s.OutPackets = C(ref _out.Packets); s.OutMessages = C(ref _out.Messages); s.OutKept = C(ref _out.Kept); + s.OutRetransmits = C(ref _out.Retransmits); s.OutResendRequests = C(ref _out.ResendRequests); + s.SendErrors = C(ref _out.SendErrors); + } + + public void WriteSummary(in FlightSummary s) + { + Span d = stackalloc byte[FlightSummary.Size]; + s.Write(d); + Ring.WriteMarkBytes(_clock(), FlightMark.Summary, 0, 0, 0, d); + } + + // ── stall detectors ──────────────────────────────────────────────────── + // use refusal: a Use answered by UseDone(0) with nothing about it afterwards (no + // ViewContents, no message about the object, no player motion with an action in it) + // for UseSettleMs; UseRefusalStreak of those in a row. A ViewContents resets it. + // use unanswered: UseUnansweredStreak uses in a row with no UseDone for UseUnansweredMs. + // too busy: TooBusyStreak "You're too busy" (WeenieError 0x1D or the system text) + // within TooBusyWindowMs. + + /// A dump reason the detectors raised since the last call, or null. + public string? TakeTrigger() + { + lock (_detectLock) + { + string? t = _trigger; + _trigger = null; + return t; + } + } + + public int RefusedStreak { get { lock (_detectLock) return _refusedStreak; } } + + private void DetectUseSent(uint target, bool counted, long now) + { + lock (_detectLock) + { + SettleUses(now); + if (_useCount == _uses.Length) + { + Array.Copy(_uses, 1, _uses, 0, _uses.Length - 1); + _useCount--; + } + _uses[_useCount++] = new UseTrack { Target = target, Counted = counted, Sent = now }; + } + } + + private void DetectUseDone(uint err, long now) + { + lock (_detectLock) + { + for (int i = 0; i < _useCount; i++) + { + if (_uses[i].Answered) continue; + _uses[i].Answered = true; + _uses[i].Err = err; + _uses[i].AnsweredAt = now; + break; + } + } + } + + private void DetectOpened(uint container, long now) + { + lock (_detectLock) + { + for (int i = 0; i < _useCount; i++) + if (_uses[i].Target == container) _uses[i].Responded = true; + _refusedStreak = 0; + _unansweredStreak = 0; + } + } + + private void DetectResponse(uint obj, long now) + { + lock (_detectLock) + { + for (int i = 0; i < _useCount; i++) + if (_uses[i].Target == obj && now >= _uses[i].Sent) _uses[i].Responded = true; + } + } + + /// The player's motion: one carrying actions (a command list: eat, drink, a cast...) or a + /// server move/turn to an object answers the uses still open. + private void DetectPlayerMotion(byte* msg, int len, long now) + { + // opcode, guid, u16 instance, u16 movement, u16 server control, u8 autonomous, pad to 16, + // then u8 movement type, u8 flags, u16 style, then the type's data. + if (len < 24) return; + byte type = msg[16]; + uint target = 0; + bool action = false; + if (type == 0) + { + uint packed = AcPacketWire.ReadU32(msg + 20); + action = (packed >> 7) != 0; // number of commands + } + else if ((type == 6 || type == 8) && len >= 24) + { + target = AcPacketWire.ReadU32(msg + 20); + } + if (!action && target == 0) return; + lock (_detectLock) + { + for (int i = 0; i < _useCount; i++) + { + ref UseTrack u = ref _uses[i]; + if (u.Settled || now < u.Sent) continue; + if (action || u.Target == target) u.Responded = true; + } + } + } + + private void DetectTooBusy(long now) + { + lock (_detectLock) + { + _tooBusy[_tooBusyNext] = now; + _tooBusyNext = (_tooBusyNext + 1) % _tooBusy.Length; + long oldest = long.MaxValue; + foreach (long t in _tooBusy) + { + if (t == 0) return; + if (t < oldest) oldest = t; + } + if (Ms(now - oldest) <= TooBusyWindowMs) + { + _trigger ??= $"too-busy: {TooBusyStreak} \"You're too busy\" answers within {Ms(now - oldest) / 1000.0:0.0} s"; + Array.Clear(_tooBusy); + } + } + } + + /// Settle uses whose time is up (call regularly; also runs on every Use sent). + public void Tick() + { + long now = _clock(); + lock (_detectLock) SettleUses(now); + } + + private void SettleUses(long now) + { + int keep = 0; + for (int i = 0; i < _useCount; i++) + { + UseTrack u = _uses[i]; + bool done = false; + if (u.Answered) + { + if (!u.Counted) + { + done = u.Responded || u.Err != 0 || Ms(now - u.AnsweredAt) >= UseSettleMs; + } + else if (u.Responded || u.Err != 0) + { + done = true; + if (u.Responded) _refusedStreak = 0; + _unansweredStreak = 0; + } + else if (Ms(now - u.AnsweredAt) >= UseSettleMs) + { + done = true; + _unansweredStreak = 0; + _refusedTargets[_refusedStreak % _refusedTargets.Length] = u.Target; + _refusedStreak++; + if (_refusedStreak >= UseRefusalStreak) + { + _trigger ??= $"use-refusal: {_refusedStreak} uses in a row answered UseDone(0) with nothing opened ({TargetList()})"; + _refusedStreak = 0; + } + } + } + else if (Ms(now - u.Sent) >= UseUnansweredMs) + { + done = true; + if (!u.Counted) continue; // a use-with-target nobody answered: just drop it + _unansweredStreak++; + if (_unansweredStreak >= UseUnansweredStreak) + { + _trigger ??= $"use-unanswered: {_unansweredStreak} uses in a row got no UseDone within {UseUnansweredMs / 1000} s"; + _unansweredStreak = 0; + } + } + if (!done) + _uses[keep++] = u; + } + for (int i = keep; i < _useCount; i++) _uses[i] = default; + _useCount = keep; + } + + /// The refused objects, each once (trigger time only). + private string TargetList() + { + int n = Math.Min(_refusedStreak, _refusedTargets.Length); + var parts = new System.Collections.Generic.List(n); + for (int i = 0; i < n; i++) + { + string id = $"0x{_refusedTargets[i]:X8}"; + if (!parts.Contains(id)) parts.Add(id); + } + return string.Join(", ", parts); + } + + /// "too busy" in a u16-length-prefixed Latin-1 string, without allocating. + private static bool ContainsTooBusy(byte* p, int len) + { + if (len < 2) return false; + int n = Math.Min(AcPacketWire.ReadU16(p), len - 2); + byte* s = p + 2; + ReadOnlySpan needle = "too busy"u8; + for (int i = 0; i + needle.Length <= n; i++) + { + int k = 0; + while (k < needle.Length) + { + byte c = s[i + k]; + if (c >= (byte)'A' && c <= (byte)'Z') c = (byte)(c + 32); + if (c != needle[k]) break; + k++; + } + if (k == needle.Length) return true; + } + return false; + } +} + +/// At most one automatic dump per cooldown; manual dumps don't go through this. +internal sealed class FlightDumpPolicy +{ + private readonly long _cooldownMs; + private long _lastMs; + private bool _any; + private readonly object _lock = new(); + + public FlightDumpPolicy(long cooldownMs) { _cooldownMs = cooldownMs; } + + public long CooldownMs => _cooldownMs; + public int Refused { get; private set; } + + /// True (and the cooldown starts) when an automatic dump may be written now; + /// otherwise is how long until one may. + public bool TryAccept(long nowMs, out long waitMs) + { + lock (_lock) + { + if (_any && nowMs - _lastMs < _cooldownMs) + { + waitMs = _cooldownMs - (nowMs - _lastMs); + Refused++; + return false; + } + _any = true; + _lastMs = nowMs; + waitMs = 0; + return true; + } + } +} diff --git a/src/RynthCore.Engine/Net/FlightFormat.cs b/src/RynthCore.Engine/Net/FlightFormat.cs new file mode 100644 index 0000000..0968e2f --- /dev/null +++ b/src/RynthCore.Engine/Net/FlightFormat.cs @@ -0,0 +1,805 @@ +// ============================================================================ +// RynthCore.Engine - Net/FlightFormat.cs +// Turns flight recorder entries into one text line each, and writes a dump. +// +// Runs only when a dump is written (never on the game's hot path). Message layouts are +// the AC wire format as the Aelrynth/ACE server writes it: little-endian, strings are a +// u16 length + Latin-1 bytes padded to 4, "align" pads to 4 from the start of the +// message. An entry holds only the first FlightEntry.DataCap bytes of a message, so +// every read is bounds-checked and a cut-off message ends with "...". +// +// Chat the player says or reads (talk, tells, channels) is never written: only its length. +// +// Pure code (no engine state); compiled into tools/FlightRecorderTests. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; + +namespace RynthCore.Engine.Net; + +/// Bounds-checked little-endian reader over a kept message. +internal ref struct FlightReader +{ + private readonly ReadOnlySpan _b; + public int Pos; + public bool Ok; + + public FlightReader(ReadOnlySpan b, int pos = 0) { _b = b; Pos = pos; Ok = true; } + + public int Remaining => Math.Max(0, _b.Length - Pos); + private bool Need(int n) + { + if (Ok && Pos + n <= _b.Length) return true; + Ok = false; + Pos = _b.Length; + return false; + } + + public byte U8() => Need(1) ? _b[Pos++] : (byte)0; + public ushort U16() { if (!Need(2)) return 0; ushort v = (ushort)(_b[Pos] | (_b[Pos + 1] << 8)); Pos += 2; return v; } + public uint U32() { if (!Need(4)) return 0; uint v = (uint)(_b[Pos] | (_b[Pos + 1] << 8) | (_b[Pos + 2] << 16) | (_b[Pos + 3] << 24)); Pos += 4; return v; } + public int I32() => unchecked((int)U32()); + public float F32() => BitConverter.UInt32BitsToSingle(U32()); + public double F64() { uint lo = U32(); uint hi = U32(); return BitConverter.UInt64BitsToDouble(((ulong)hi << 32) | lo); } + public void Skip(int n) { if (Need(n)) Pos += n; } + public void Align() { int pad = (4 - (Pos & 3)) & 3; if (pad > 0 && Pos + pad <= _b.Length) Pos += pad; else if (pad > 0) Pos = _b.Length; } + + /// u16 length, Latin-1 bytes, padding to 4 from the string's start. Long text is cut to . + public string Str(int max = 96) + { + int start = Pos; + ushort n = U16(); + if (!Ok) return ""; + int have = Math.Min(n, Remaining); + int show = Math.Min(have, max); + var sb = new StringBuilder(show + 3); + for (int i = 0; i < show; i++) + { + byte c = _b[Pos + i]; + sb.Append(c < 32 ? ' ' : (char)c); + } + if (show < n) sb.Append("..."); + if (have < n) { Ok = false; Pos = _b.Length; return sb.ToString(); } + Pos += n; + int pad = (4 - ((Pos - start) & 3)) & 3; + if (Pos + pad <= _b.Length) Pos += pad; else Pos = _b.Length; + return sb.ToString(); + } +} + +internal static class FlightFormat +{ + private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; + + // ── names ────────────────────────────────────────────────────────────── + + public static string ActionName(uint a) => a switch + { + 0x0005 => "SetSingleCharacterOption", + FlightOp.AcTargetedMeleeAttack => "MeleeAttack", + FlightOp.AcTargetedMissileAttack => "MissileAttack", + FlightOp.AcTalk => "Talk", + FlightOp.AcPutItemInContainer => "PutItemInContainer", + FlightOp.AcGetAndWieldItem => "GetAndWieldItem", + FlightOp.AcDropItem => "DropItem", + FlightOp.AcTalkDirect => "TalkDirect", + FlightOp.AcUseWithTarget => "UseWithTarget", + FlightOp.AcUse => "Use", + FlightOp.AcRaiseVital => "RaiseVital", + FlightOp.AcRaiseAttribute => "RaiseAttribute", + FlightOp.AcRaiseSkill => "RaiseSkill", + FlightOp.AcTrainSkill => "TrainSkill", + FlightOp.AcCastUntargetedSpell => "CastUntargetedSpell", + FlightOp.AcCastTargetedSpell => "CastTargetedSpell", + FlightOp.AcChangeCombatMode => "ChangeCombatMode", + FlightOp.AcStackableMerge => "StackableMerge", + FlightOp.AcStackableSplitToContainer => "StackableSplitToContainer", + FlightOp.AcStackableSplitTo3D => "StackableSplitTo3D", + FlightOp.AcTell => "Tell", + 0x005F => "Buy", + 0x0060 => "Sell", + 0x0063 => "TeleToLifestone", + FlightOp.AcLoginComplete => "LoginComplete", + FlightOp.AcIdentifyObject => "IdentifyObject", + FlightOp.AcGiveObjectRequest => "GiveObjectRequest", + FlightOp.AcChatChannel => "ChatChannel", + FlightOp.AcNoLongerViewingContents => "NoLongerViewingContents", + FlightOp.AcStackableSplitToWield => "StackableSplitToWield", + 0x01A1 => "SetCharacterOptions", + FlightOp.AcCancelAttack => "CancelAttack", + FlightOp.AcQueryHealth => "QueryHealth", + 0x01DF => "Emote", + 0x01E1 => "SoulEmote", + 0x01E9 => "PingRequest", + 0x01F6 => "OpenTradeNegotiations", + 0x01F7 => "CloseTradeNegotiations", + 0x01F8 => "AddToTrade", + 0x01FA => "AcceptTrade", + 0x01FB => "DeclineTrade", + 0x0204 => "ResetTrade", + 0x0263 => "QueryItemMana", + 0x0275 => "ConfirmationResponse", + 0x0279 => "Suicide", + FlightOp.AcJump => "Jump", + FlightOp.AcMoveToState => "MoveToState", + FlightOp.AcDoMovementCommand => "DoMovementCommand", + FlightOp.AcTurnTo => "TurnTo", + FlightOp.AcStopMovementCommand => "StopMovementCommand", + 0xF6EA => "ForceObjectDescSend", + FlightOp.AcAutonomyLevel => "AutonomyLevel", + FlightOp.AcAutonomousPosition => "AutonomousPosition", + FlightOp.AcJumpNonAutonomous => "JumpNonAutonomous", + _ => $"action 0x{a:X4}", + }; + + public static string EventName(uint e) => e switch + { + FlightOp.EvPopupString => "PopupString", + FlightOp.EvInventoryPutObjInContainer => "InventoryPutObjInContainer", + FlightOp.EvWieldObject => "WieldObject", + FlightOp.EvCloseGroundContainer => "CloseGroundContainer", + FlightOp.EvInventoryServerSaveFailed => "InventoryServerSaveFailed", + FlightOp.EvViewContents => "ViewContents", + FlightOp.EvInventoryPutObjectIn3D => "InventoryPutObjectIn3D", + FlightOp.EvAttackDone => "AttackDone", + FlightOp.EvMagicRemoveSpell => "MagicRemoveSpell", + FlightOp.EvVictimNotification => "VictimNotification", + FlightOp.EvKillerNotification => "KillerNotification", + FlightOp.EvAttackerNotification => "AttackerNotification", + FlightOp.EvDefenderNotification => "DefenderNotification", + FlightOp.EvEvasionAttacker => "EvasionAttackerNotification", + FlightOp.EvEvasionDefender => "EvasionDefenderNotification", + FlightOp.EvCombatCommenceAttack => "CombatCommenceAttack", + FlightOp.EvUseDone => "UseDone", + FlightOp.EvConfirmationRequest => "ConfirmationRequest", + FlightOp.EvWeenieError => "WeenieError", + FlightOp.EvWeenieErrorWithString => "WeenieErrorWithString", + FlightOp.EvMagicUpdateSpell => "MagicUpdateSpell", + FlightOp.EvMagicUpdateEnchantment => "MagicUpdateEnchantment", + FlightOp.EvMagicRemoveEnchantment => "MagicRemoveEnchantment", + FlightOp.EvMagicUpdateMultipleEnchantments => "MagicUpdateMultipleEnchantments", + FlightOp.EvMagicRemoveMultipleEnchantments => "MagicRemoveMultipleEnchantments", + FlightOp.EvMagicPurgeEnchantments => "MagicPurgeEnchantments", + FlightOp.EvMagicDispelEnchantment => "MagicDispelEnchantment", + FlightOp.EvMagicDispelMultipleEnchantments => "MagicDispelMultipleEnchantments", + FlightOp.EvTransientString => "TransientString", + FlightOp.EvMagicPurgeBadEnchantments => "MagicPurgeBadEnchantments", + _ => $"event 0x{e:X4}", + }; + + public static string OpcodeName(uint op) => op switch + { + FlightOp.GameEvent => "GameEvent", + FlightOp.GameAction => "GameAction", + FlightOp.UpdateMotion => "UpdateMotion", + FlightOp.UpdatePosition => "UpdatePosition", + FlightOp.PlayerTeleport => "PlayerTeleport", + FlightOp.VectorUpdate => "VectorUpdate", + FlightOp.PlayEffect => "PlayEffect", + FlightOp.PlayScriptId => "PlayScriptId", + FlightOp.ObjectDelete => "ObjectDelete", + FlightOp.PickupEvent => "PickupEvent", + FlightOp.SetState => "SetState", + FlightOp.ParentEvent => "ParentEvent", + FlightOp.ServerMessage => "ServerMessage", + FlightOp.PlayerCreate => "PlayerCreate", + FlightOp.CharacterLogOff => "CharacterLogOff", + FlightOp.InventoryRemoveObject => "InventoryRemoveObject", + FlightOp.SetStackSize => "SetStackSize", + FlightOp.PlayerKilled => "PlayerKilled", + 0xF7C8 => "CharacterEnterWorldRequest", + 0xF657 => "CharacterEnterWorld", + 0xF7DE => "TurbineChat", + 0xF7E6 => "DDD_InterrogationResponse", + 0xF7EA => "DDD_EndDDD", + _ => $"msg 0x{op:X4}", + }; + + /// The WeenieError codes worth naming here (others print as hex). + public static string ErrorName(uint e) => e switch + { + 0x0000 => "none", + 0x001D => "YoureTooBusy", + 0x001B => "PhysicsCantTransition", + 0x001C => "PhysicsMaxDistanceExceeded", + 0x0020 => "IllegalInventoryTransaction", + 0x0023 => "MotionFailure", + 0x0024 => "YouCantJumpWhileInTheAir", + 0x0027 => "CarryingItem", + 0x0028 => "Frozen", + 0x0029 => "Stuck", + 0x002A => "YouAreTooEncumbered", + 0x0036 => "ActionCancelled", + 0x0037 => "ObjectGone", + 0x0038 => "NoObject", + 0x003D => "YouChargedTooFar", + 0x0400 => "YouDontHaveAllTheComponents", + 0x0401 => "YouDontHaveEnoughManaToCast", + 0x0402 => "YourSpellFizzled", + 0x0403 => "YourSpellTargetIsMissing", + 0x0404 => "YourProjectileSpellMislaunched", + 0x0406 => "MagicTargetOutOfRange", + 0x0409 => "MagicGeneralFailure", + 0x040A => "YouAreUnpreparedToCastASpell", + 0x042A => "CurrentlyAttacking", + 0x042B => "MissileAttackNotOk", + 0x042C => "TargetNotAcquired", + 0x043C => "YourHandsMustBeFree", + 0x0498 => "YouHaveMovedTooFar", + _ => "", + }; + + private static string Err(uint e) + { + string n = ErrorName(e); + return n.Length > 0 ? $"0x{e:X4} {n}" : $"0x{e:X4}"; + } + + /// Motion commands and stances by their low 16 bits (the interpreted state sends only those). + public static string MotionName(uint cmd) + { + uint k = cmd & 0xFFFF; + string? n = k switch + { + 0x0000 => "Invalid", + 0x0001 => "HoldRun", 0x0002 => "HoldSidestep", 0x0003 => "Ready", 0x0004 => "Stop", + 0x0005 => "WalkForward", 0x0006 => "WalkBackwards", 0x0007 => "RunForward", 0x0008 => "Fallen", + 0x0009 => "Interpolating", 0x000D => "TurnRight", 0x000E => "TurnLeft", 0x000F => "SideStepRight", + 0x0010 => "SideStepLeft", 0x0011 => "Dead", 0x0012 => "Crouch", 0x0013 => "Sitting", 0x0014 => "Sleeping", + 0x0015 => "Falling", 0x0016 => "Reload", 0x0017 => "Unload", 0x0018 => "Pickup", 0x0019 => "StoreInBackpack", + 0x001A => "Eat", 0x001B => "Drink", 0x001C => "Reading", 0x001D => "JumpCharging", + 0x002B => "MagicBlast", 0x002C => "MagicSelfHead", 0x002D => "MagicSelfHeart", 0x002E => "MagicBonus", + 0x002F => "MagicClap", 0x0030 => "MagicHarm", 0x0031 => "MagicHeal", 0x0032 => "MagicThrowMissile", + 0x0033 => "MagicRecoilMissile", 0x0034 => "MagicPenalty", 0x0035 => "MagicTransfer", 0x0036 => "MagicVision", + 0x0037 => "MagicEnchantItem", 0x0038 => "MagicPortal", 0x0039 => "MagicPray", 0x003A => "StopTurning", + 0x003B => "Jump", 0x003C => "HandCombat", 0x003D => "NonCombat", 0x003E => "SwordCombat", 0x003F => "BowCombat", + 0x0040 => "SwordShieldCombat", 0x0041 => "CrossbowCombat", 0x0043 => "SlingCombat", + 0x0044 => "TwoHandedSwordCombat", 0x0045 => "TwoHandedStaffCombat", 0x0046 => "DualWieldCombat", + 0x0047 => "ThrownWeaponCombat", 0x0049 => "Magic", 0x0050 => "FallDown", 0x0055 => "StaggerBackward", + 0x0056 => "StaggerForward", 0x0057 => "Sanctuary", + 0x0058 => "ThrustMed", 0x0059 => "ThrustLow", 0x005A => "ThrustHigh", 0x005B => "SlashHigh", 0x005C => "SlashMed", + 0x005D => "SlashLow", 0x005E => "BackhandHigh", 0x005F => "BackhandMed", 0x0060 => "BackhandLow", 0x0061 => "Shoot", + 0x0062 => "AttackHigh1", 0x0063 => "AttackMed1", 0x0064 => "AttackLow1", 0x0065 => "AttackHigh2", + 0x0066 => "AttackMed2", 0x0067 => "AttackLow2", 0x0068 => "AttackHigh3", 0x0069 => "AttackMed3", 0x006A => "AttackLow3", + 0x009C => "EnterGame", 0x009D => "ExitGame", 0x00A0 => "EnterPortal", 0x00A1 => "ExitPortal", + 0x00D3 => "CastSpell", 0x00E0 => "UseMagicStaff", 0x00E8 => "BowNoAmmo", 0x00E9 => "CrossBowNoAmmo", + 0x013B => "AtlatlCombat", 0x013C => "ThrownShieldCombat", + _ => null, + }; + if (n == null && k >= 0x006F && k <= 0x0078) n = $"MagicPowerUp{k - 0x006E:00}"; + return n ?? $"0x{cmd:X}"; + } + + private static string CombatMode(uint m) => m switch + { + 1 => "NonCombat", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => $"mode {m}", + }; + + private static string HoldKey(uint h) => h switch { 0 => "Invalid", 1 => "None", 2 => "Run", _ => $"hold{h}" }; + + private static string MovementType(byte t) => t switch + { + 0 => "State", 1 => "RawCommand", 2 => "InterpretedCommand", 3 => "StopRawCommand", 4 => "StopInterpretedCommand", + 5 => "StopCompletely", 6 => "MoveToObject", 7 => "MoveToPosition", 8 => "TurnToObject", 9 => "TurnToHeading", + _ => $"type{t}", + }; + + private static string F(float v) => float.IsFinite(v) ? v.ToString("0.##", Inv) : "nan"; + private static string Id(uint id) => $"0x{id:X8}"; + + /// Yaw in degrees from the (w, x, y, z) rotation (rotation about the vertical axis). + private static string Yaw(float w, float z) + { + double deg = 2 * Math.Atan2(z, w) * 180 / Math.PI; + deg %= 360; if (deg < 0) deg += 360; + return deg.ToString("0", Inv); + } + + // ── entries ──────────────────────────────────────────────────────────── + + /// The text after the direction arrow for one entry. + public static string Describe(in FlightRecord r) + { + try + { + FlightEntry e = r.Entry; + ReadOnlySpan data; + unsafe { data = new ReadOnlySpan(e.Data, e.Len).ToArray(); } + string s = e.Dir switch + { + FlightDir.Out => DescribeOut(data, e), + FlightDir.In => DescribeIn(data, e), + FlightDir.Mark => DescribeMark(data, e, r.Name), + _ => "?", + }; + return s; + } + catch (Exception ex) + { + return $"(undecodable: {ex.GetType().Name})"; + } + } + + private static string Tail(in FlightReader rd, FlightEntry e) + { + var sb = new StringBuilder(); + if (!rd.Ok) sb.Append(" ..."); + if ((e.Flags & FlightFlags.MultiFragment) != 0) sb.Append(" [multi-fragment]"); + if ((e.Flags & FlightFlags.Retransmit) != 0) sb.Append(" [retransmitted]"); + if ((e.Flags & FlightFlags.SendFailed) != 0) sb.Append(" [SEND FAILED]"); + if (e.Dir != FlightDir.Mark && e.B > 0) sb.Append($" (+{e.B} like it not kept)"); + return sb.ToString(); + } + + public static string DescribeOut(ReadOnlySpan d, FlightEntry e) + { + var rd = new FlightReader(d); + uint op = rd.U32(); + if (op != FlightOp.GameAction) + return $"{OpcodeName(op)} len={e.FullLen}" + Tail(rd, e); + + uint seq = rd.U32(); + uint action = rd.U32(); + string tag = (e.Flags & FlightFlags.Engine) != 0 ? "[eng] " : (e.Flags & FlightFlags.Client) != 0 ? "[cli] " : ""; + string body = action switch + { + FlightOp.AcUse => $"{Id(rd.U32())}", + FlightOp.AcUseWithTarget => $"{Id(rd.U32())} on {Id(rd.U32())}", + FlightOp.AcCastUntargetedSpell => $"spell {rd.U32()}", + FlightOp.AcCastTargetedSpell => Cast(ref rd), + FlightOp.AcChangeCombatMode => CombatMode(rd.U32()), + FlightOp.AcTargetedMeleeAttack => $"{Id(rd.U32())} height {rd.U32()} power {F(rd.F32())}", + FlightOp.AcTargetedMissileAttack => $"{Id(rd.U32())} height {rd.U32()} accuracy {F(rd.F32())}", + FlightOp.AcPutItemInContainer => $"{Id(rd.U32())} into {Id(rd.U32())} slot {rd.I32()}", + FlightOp.AcGetAndWieldItem => $"{Id(rd.U32())} mask 0x{rd.U32():X}", + FlightOp.AcDropItem => Id(rd.U32()), + FlightOp.AcGiveObjectRequest => Give(ref rd), + FlightOp.AcStackableMerge => $"{Id(rd.U32())} into {Id(rd.U32())} amount {rd.I32()}", + FlightOp.AcStackableSplitToContainer => $"{Id(rd.U32())} to {Id(rd.U32())} slot {rd.I32()} amount {rd.I32()}", + FlightOp.AcStackableSplitTo3D => $"{Id(rd.U32())} amount {rd.I32()}", + FlightOp.AcStackableSplitToWield => $"{Id(rd.U32())} mask 0x{rd.U32():X} amount {rd.I32()}", + FlightOp.AcNoLongerViewingContents => Id(rd.U32()), + FlightOp.AcIdentifyObject => Id(rd.U32()), + FlightOp.AcQueryHealth => Id(rd.U32()), + FlightOp.AcCancelAttack => "", + FlightOp.AcLoginComplete => "", + FlightOp.AcAutonomyLevel => $"level {rd.U32()}", + FlightOp.AcTalk or FlightOp.AcTell or FlightOp.AcTalkDirect or FlightOp.AcChatChannel or 0x01DF or 0x01E1 + => $"({e.FullLen} bytes, text not recorded)", + FlightOp.AcMoveToState => MoveToState(ref rd), + FlightOp.AcAutonomousPosition => AutonomousPosition(ref rd), + FlightOp.AcJump => Jump(ref rd), + FlightOp.AcJumpNonAutonomous => $"extent {F(rd.F32())}", + FlightOp.AcDoMovementCommand => $"{MotionName(rd.U32())} speed {F(rd.F32())} hold {HoldKey(rd.U32())}", + FlightOp.AcStopMovementCommand => $"{MotionName(rd.U32())} hold {HoldKey(rd.U32())}", + _ => RawArgs(ref rd), + }; + if (action is FlightOp.AcTalk or FlightOp.AcTell or FlightOp.AcTalkDirect or FlightOp.AcChatChannel or 0x01DF or 0x01E1) + rd.Ok = true; // the text is skipped on purpose + return $"{tag}{ActionName(action)} {body}".TrimEnd() + $" #{seq}" + Tail(rd, e); + } + + private static string Cast(ref FlightReader rd) { uint t = rd.U32(); uint s = rd.U32(); return $"spell {s} on {Id(t)}"; } + private static string Give(ref FlightReader rd) { uint t = rd.U32(); uint o = rd.U32(); int n = rd.I32(); return $"{Id(o)} x{n} to {Id(t)}"; } + + private static string RawArgs(ref FlightReader rd) + { + var sb = new StringBuilder(); + for (int i = 0; i < 4 && rd.Remaining >= 4; i++) + sb.Append(i == 0 ? "args " : " ").Append($"0x{rd.U32():X}"); + return sb.ToString(); + } + + private static string Position(ref FlightReader rd, bool rotation) + { + uint cell = rd.U32(); + float x = rd.F32(), y = rd.F32(), z = rd.F32(); + string s = $"@{Id(cell)} ({F(x)},{F(y)},{F(z)})"; + if (rotation) + { + float w = rd.F32(); rd.F32(); rd.F32(); float qz = rd.F32(); + s += $" yaw {Yaw(w, qz)}"; + } + return s; + } + + private static string Seqs(ref FlightReader rd) => $"seq i{rd.U16()}/s{rd.U16()}/t{rd.U16()}/f{rd.U16()}"; + + private static string MoveToState(ref FlightReader rd) + { + uint packed = rd.U32(); + uint flags = packed & 0x7FF; + uint ncmd = packed >> 11; + var sb = new StringBuilder(); + if ((flags & 0x001) != 0) sb.Append($"hold={HoldKey(rd.U32())} "); + if ((flags & 0x002) != 0) sb.Append($"style={MotionName(rd.U32())} "); + string fwd = (flags & 0x004) != 0 ? MotionName(rd.U32()) : ""; + string fwdHold = (flags & 0x008) != 0 ? HoldKey(rd.U32()) : ""; + string fwdSpeed = (flags & 0x010) != 0 ? F(rd.F32()) : ""; + if (fwd.Length > 0 || fwdHold.Length > 0 || fwdSpeed.Length > 0) + sb.Append($"fwd={(fwd.Length > 0 ? fwd : "-")}{(fwdHold.Length > 0 ? "(" + fwdHold + ")" : "")}{(fwdSpeed.Length > 0 ? "@" + fwdSpeed : "")} "); + string side = (flags & 0x020) != 0 ? MotionName(rd.U32()) : ""; + string sideHold = (flags & 0x040) != 0 ? HoldKey(rd.U32()) : ""; + string sideSpeed = (flags & 0x080) != 0 ? F(rd.F32()) : ""; + if (side.Length > 0 || sideHold.Length > 0 || sideSpeed.Length > 0) + sb.Append($"side={(side.Length > 0 ? side : "-")}{(sideHold.Length > 0 ? "(" + sideHold + ")" : "")}{(sideSpeed.Length > 0 ? "@" + sideSpeed : "")} "); + string turn = (flags & 0x100) != 0 ? MotionName(rd.U32()) : ""; + string turnHold = (flags & 0x200) != 0 ? HoldKey(rd.U32()) : ""; + string turnSpeed = (flags & 0x400) != 0 ? F(rd.F32()) : ""; + if (turn.Length > 0 || turnHold.Length > 0 || turnSpeed.Length > 0) + sb.Append($"turn={(turn.Length > 0 ? turn : "-")}{(turnHold.Length > 0 ? "(" + turnHold + ")" : "")}{(turnSpeed.Length > 0 ? "@" + turnSpeed : "")} "); + if (flags == 0) sb.Append("(no motion: stand still) "); + if (ncmd > 0) + { + sb.Append("cmds=["); + for (uint i = 0; i < ncmd && i < 8 && rd.Ok; i++) + { + ushort c = rd.U16(); ushort ps = rd.U16(); float sp = rd.F32(); + sb.Append(i > 0 ? " " : "").Append($"{MotionName(c)}@{F(sp)}#{ps & 0x7FFF}{((ps & 0x8000) != 0 ? "a" : "")}"); + } + if (ncmd > 8) { rd.Skip((int)(ncmd - 8) * 8); sb.Append(" ..."); } + sb.Append("] "); + } + sb.Append(Position(ref rd, rotation: true)).Append(' '); + sb.Append(Seqs(ref rd)); + byte contact = rd.U8(); + sb.Append($" contact={contact & 1}{((contact & 2) != 0 ? " longjump" : "")}"); + return sb.ToString(); + } + + private static string AutonomousPosition(ref FlightReader rd) + { + string pos = Position(ref rd, rotation: true); + string seqs = Seqs(ref rd); + byte contact = rd.U8(); + return $"{pos} {seqs} contact={contact & 1}"; + } + + private static string Jump(ref FlightReader rd) + { + float extent = rd.F32(); + float vx = rd.F32(), vy = rd.F32(), vz = rd.F32(); + return $"extent {F(extent)} velocity ({F(vx)},{F(vy)},{F(vz)}) {Seqs(ref rd)}"; + } + + public static string DescribeIn(ReadOnlySpan d, FlightEntry e) + { + var rd = new FlightReader(d); + uint op = rd.U32(); + string s; + switch (op) + { + case FlightOp.GameEvent: + { + rd.U32(); // player guid + uint seq = rd.U32(); + uint ev = rd.U32(); + s = $"{EventName(ev)} {DescribeEvent(ev, ref rd, e)}".TrimEnd() + $" #{seq}"; + break; + } + case FlightOp.UpdateMotion: s = "UpdateMotion " + UpdateMotion(ref rd); break; + case FlightOp.UpdatePosition: s = "UpdatePosition " + UpdatePosition(ref rd); break; + case FlightOp.PlayerTeleport: s = $"PlayerTeleport seq t{rd.U16()}"; break; + case FlightOp.VectorUpdate: + { + uint id = rd.U32(); + float vx = rd.F32(), vy = rd.F32(), vz = rd.F32(), ox = rd.F32(), oy = rd.F32(), oz = rd.F32(); + s = $"VectorUpdate {Id(id)} velocity ({F(vx)},{F(vy)},{F(vz)}) omega ({F(ox)},{F(oy)},{F(oz)})"; + break; + } + case FlightOp.PlayEffect: { uint id = rd.U32(); uint sc = rd.U32(); float sp = rd.F32(); s = $"PlayEffect {Id(id)} script 0x{sc:X} speed {F(sp)}"; break; } + case FlightOp.PlayScriptId: { uint id = rd.U32(); uint sc = rd.U32(); s = $"PlayScriptId {Id(id)} script 0x{sc:X}"; break; } + case FlightOp.ObjectDelete: { uint id = rd.U32(); s = $"ObjectDelete {Id(id)} i{rd.U16()}"; break; } + case FlightOp.PickupEvent: { uint id = rd.U32(); s = $"PickupEvent {Id(id)} i{rd.U16()} p{rd.U16()}"; break; } + case FlightOp.SetState: { uint id = rd.U32(); uint st = rd.U32(); s = $"SetState {Id(id)} state 0x{st:X}"; break; } + case FlightOp.ParentEvent: { uint p = rd.U32(); uint c = rd.U32(); s = $"ParentEvent {Id(c)} onto {Id(p)} loc {rd.I32()}"; break; } + case FlightOp.InventoryRemoveObject: s = $"InventoryRemoveObject {Id(rd.U32())}"; break; + case FlightOp.SetStackSize: { rd.U8(); uint id = rd.U32(); uint n = rd.U32(); s = $"SetStackSize {Id(id)} size {n}"; break; } + case FlightOp.ServerMessage: { string t = rd.Str(); uint ct = rd.U32(); s = $"ServerMessage \"{t}\" (chat type {ct})"; break; } + case FlightOp.PlayerCreate: s = $"PlayerCreate {Id(rd.U32())}"; break; + case FlightOp.CharacterLogOff: s = "CharacterLogOff"; break; + case FlightOp.PlayerKilled: { string t = rd.Str(); uint v = rd.U32(); uint k = rd.U32(); s = $"PlayerKilled \"{t}\" victim {Id(v)} killer {Id(k)}"; break; } + default: s = $"{OpcodeName(op)} len={e.FullLen}"; break; + } + return s + Tail(rd, e); + } + + private static string DescribeEvent(uint ev, ref FlightReader rd, FlightEntry e) + { + switch (ev) + { + case FlightOp.EvUseDone: return $"err {Err(rd.U32())}"; + case FlightOp.EvWeenieError: return Err(rd.U32()); + case FlightOp.EvWeenieErrorWithString: { uint c = rd.U32(); return $"{Err(c)} \"{rd.Str()}\""; } + case FlightOp.EvViewContents: + { + uint c = rd.U32(); + uint n = rd.U32(); + var sb = new StringBuilder($"{Id(c)} items {n}"); + for (uint i = 0; i < n && i < 6 && rd.Remaining >= 8; i++) + { + uint id = rd.U32(); rd.U32(); + sb.Append(i == 0 ? ": " : " ").Append(Id(id)); + } + if (n > 6) sb.Append(" ..."); + rd.Ok = true; // the item list is cut on purpose + return sb.ToString(); + } + case FlightOp.EvCloseGroundContainer: return Id(rd.U32()); + case FlightOp.EvInventoryServerSaveFailed: { uint i = rd.U32(); return $"{Id(i)} err {Err(rd.U32())}"; } + case FlightOp.EvInventoryPutObjInContainer: { uint i = rd.U32(); uint c = rd.U32(); int p = rd.I32(); uint t = rd.U32(); return $"{Id(i)} in {Id(c)} slot {p} type {t}"; } + case FlightOp.EvWieldObject: { uint i = rd.U32(); return $"{Id(i)} mask 0x{rd.U32():X}"; } + case FlightOp.EvInventoryPutObjectIn3D: return Id(rd.U32()); + case FlightOp.EvAttackDone: return $"err {Err(rd.U32())}"; + case FlightOp.EvCombatCommenceAttack: return ""; + case FlightOp.EvAttackerNotification: + { + string who = rd.Str(40); rd.U32(); double pct = rd.F64(); uint dmg = rd.U32(); uint crit = rd.U32(); + return $"hit '{who}' for {dmg}{(crit != 0 ? " (crit)" : "")}, {pct * 100:0}% left"; + } + case FlightOp.EvDefenderNotification: + { + string who = rd.Str(40); rd.U32(); double pct = rd.F64(); uint dmg = rd.U32(); + return $"'{who}' hit you for {dmg}, {pct * 100:0}% left"; + } + case FlightOp.EvEvasionAttacker: return $"'{rd.Str(40)}' evaded"; + case FlightOp.EvEvasionDefender: return $"evaded '{rd.Str(40)}'"; + case FlightOp.EvKillerNotification: + case FlightOp.EvVictimNotification: + case FlightOp.EvPopupString: + case FlightOp.EvTransientString: + return $"\"{rd.Str()}\""; + case FlightOp.EvConfirmationRequest: { uint t = rd.U32(); uint ctx = rd.U32(); return $"type {t} context {ctx} \"{rd.Str(60)}\""; } + case FlightOp.EvMagicUpdateEnchantment: + { + ushort spell = rd.U16(); ushort layer = rd.U16(); rd.U16(); rd.U16(); rd.U32(); rd.F64(); + double dur = rd.F64(); uint caster = rd.U32(); + return $"spell {spell} layer {layer} duration {dur.ToString("0", Inv)} s caster {Id(caster)}"; + } + case FlightOp.EvMagicRemoveEnchantment: + case FlightOp.EvMagicDispelEnchantment: + case FlightOp.EvMagicUpdateSpell: + case FlightOp.EvMagicRemoveSpell: + { + ushort spell = rd.U16(); ushort layer = rd.U16(); + return $"spell {spell} layer {layer}"; + } + case FlightOp.EvMagicUpdateMultipleEnchantments: + { + uint n = rd.U32(); ushort first = rd.U16(); + rd.Ok = true; + return $"{n} enchantments (first spell {first})"; + } + case FlightOp.EvMagicRemoveMultipleEnchantments: + case FlightOp.EvMagicDispelMultipleEnchantments: + { + uint n = rd.U32(); + var sb = new StringBuilder($"{n}:"); + for (uint i = 0; i < n && i < 6 && rd.Remaining >= 4; i++) { ushort sp = rd.U16(); rd.U16(); sb.Append($" {sp}"); } + rd.Ok = true; + return sb.ToString(); + } + case FlightOp.EvMagicPurgeEnchantments: + case FlightOp.EvMagicPurgeBadEnchantments: + return ""; + default: + return RawArgs(ref rd); + } + } + + private static string UpdateMotion(ref FlightReader rd) + { + uint id = rd.U32(); + ushort inst = rd.U16(), mov = rd.U16(), srv = rd.U16(); + byte auton = rd.U8(); + rd.Align(); + byte type = rd.U8(); + byte mflags = rd.U8(); + ushort style = rd.U16(); + var sb = new StringBuilder(); + sb.Append($"{Id(id)} {(auton != 0 ? "autonomous " : "server ")}{MovementType(type)} style={MotionName(style)}"); + switch (type) + { + case 0: + { + uint packed = rd.U32(); + uint fl = packed & 0x7F; + uint ncmd = packed >> 7; + string cur = (fl & 0x01) != 0 ? MotionName(rd.U16()) : ""; + string fwd = (fl & 0x02) != 0 ? MotionName(rd.U16()) : ""; + string side = (fl & 0x08) != 0 ? MotionName(rd.U16()) : ""; + string turn = (fl & 0x20) != 0 ? MotionName(rd.U16()) : ""; + string fs = (fl & 0x04) != 0 ? F(rd.F32()) : ""; + string ss = (fl & 0x10) != 0 ? F(rd.F32()) : ""; + string ts = (fl & 0x40) != 0 ? F(rd.F32()) : ""; + if (cur.Length > 0 && cur != MotionName(style)) sb.Append($" state.style={cur}"); + sb.Append($" fwd={(fwd.Length > 0 ? fwd : "Ready")}{(fs.Length > 0 ? "@" + fs : "")}"); + if (side.Length > 0) sb.Append($" side={side}{(ss.Length > 0 ? "@" + ss : "")}"); + if (turn.Length > 0) sb.Append($" turn={turn}{(ts.Length > 0 ? "@" + ts : "")}"); + if (ncmd > 0) + { + sb.Append(" cmds=["); + for (uint i = 0; i < ncmd && i < 8 && rd.Ok; i++) + { + ushort c = rd.U16(); ushort ps = rd.U16(); float sp = rd.F32(); + sb.Append(i > 0 ? " " : "").Append($"{MotionName(c)}@{F(sp)}#{ps & 0x7FFF}{((ps & 0x8000) != 0 ? "a" : "")}"); + } + sb.Append(']'); + } + rd.Align(); + if ((mflags & 1) != 0) sb.Append($" stick to {Id(rd.U32())}"); + break; + } + case 6: + case 7: + { + if (type == 6) sb.Append($" target {Id(rd.U32())}"); + uint cell = rd.U32(); float x = rd.F32(), y = rd.F32(), z = rd.F32(); + uint pf = rd.U32(); float dist = rd.F32(), min = rd.F32(), fail = rd.F32(), speed = rd.F32(), wr = rd.F32(), hd = rd.F32(); + float run = rd.F32(); + sb.Append($" origin @{Id(cell)} ({F(x)},{F(y)},{F(z)}) params 0x{pf:X} dist {F(dist)} min {F(min)} fail {F(fail)} speed {F(speed)} walkrun {F(wr)} heading {F(hd)} runrate {F(run)}"); + break; + } + case 8: + { + uint target = rd.U32(); float want = rd.F32(); + uint pf = rd.U32(); float speed = rd.F32(); float hd = rd.F32(); + sb.Append($" target {Id(target)} heading {F(want)} params 0x{pf:X} speed {F(speed)} ({F(hd)})"); + break; + } + case 9: + { + uint pf = rd.U32(); float speed = rd.F32(); float hd = rd.F32(); + sb.Append($" heading {F(hd)} params 0x{pf:X} speed {F(speed)}"); + break; + } + } + sb.Append($" seq i{inst}/m{mov}/c{srv}"); + return sb.ToString(); + } + + private static string UpdatePosition(ref FlightReader rd) + { + uint id = rd.U32(); + uint flags = rd.U32(); + uint cell = rd.U32(); + float x = rd.F32(), y = rd.F32(), z = rd.F32(); + float w = (flags & 0x08) == 0 ? rd.F32() : 0; + if ((flags & 0x10) == 0) rd.F32(); + if ((flags & 0x20) == 0) rd.F32(); + float qz = (flags & 0x40) == 0 ? rd.F32() : 0; + string vel = ""; + if ((flags & 0x01) != 0) { float vx = rd.F32(), vy = rd.F32(), vz = rd.F32(); vel = $" velocity ({F(vx)},{F(vy)},{F(vz)})"; } + if ((flags & 0x02) != 0) rd.U32(); + string seqs = $"seq i{rd.U16()}/p{rd.U16()}/t{rd.U16()}/f{rd.U16()}"; + return $"{Id(id)} @{Id(cell)} ({F(x)},{F(y)},{F(z)}) yaw {Yaw(w, qz)}{vel}{((flags & 0x04) != 0 ? " grounded" : "")} {seqs}"; + } + + public static string DescribeMark(ReadOnlySpan d, FlightEntry e, string? name) + { + string text = Latin1(d); + if ((e.Flags & FlightFlags.Truncated) != 0) text += "..."; + switch ((FlightMark)e.Kind) + { + case FlightMark.Note: return $"note: {text}"; + case FlightMark.EngineCall: + return e.C > 0 + ? $"engine {name}({Hex(e.A)}, {Hex(e.B)}) repeated {e.C} more time(s), last here" + : $"engine {name}({Hex(e.A)}, {Hex(e.B)})"; + case FlightMark.BusyIncrement: return $"m_cBusy +1 -> real {Busy(e.A)} (engine count {(int)e.B})"; + case FlightMark.BusyDecrement: return $"m_cBusy -1 -> real {Busy(e.A)} (engine count {(int)e.B})"; + case FlightMark.BusyForceClear: return $"m_cBusy force-cleared (was real {Busy(e.A)}, engine count {(int)e.B}){(text.Length > 0 ? " - " + text : "")}"; + case FlightMark.BusyForceClearAsk: return $"m_cBusy force-clear asked: {text}"; + case FlightMark.BusyReconcile: return $"m_cBusy reconcile: {e.A} decrement(s) for the engine's own action, real now {Busy(e.B)}"; + case FlightMark.BusyNegativeRepair: return $"m_cBusy was negative ({(int)e.A}) - reset to 0"; + case FlightMark.BusyWatchdog: return $"busy watchdog ({text}): real {Busy(e.A)}, engine count {(int)e.B}, stuck {e.C} ms"; + case FlightMark.GateCleared: + return e.A == 0 + ? $"action gate cleared: attacking flag ({text})" + : $"action gate cleared: pending item request type {e.A} on {Id(e.B)} ({text})"; + case FlightMark.EngineInit: return $"engine generation {e.A} started{(e.A >= 2 ? " (hot reload: everything before this was in the previous generation's buffer)" : "")}"; + case FlightMark.EngineShutdown: return $"engine shutting down{(text.Length > 0 ? " (" + text + ")" : "")}"; + case FlightMark.PluginReload: return $"plugin reload: {text}"; + case FlightMark.Trigger: return $"AUTO DUMP TRIGGER: {text}"; + case FlightMark.Dump: return $"DUMP REQUESTED{(text.Length > 0 ? ": " + text : "")}"; + case FlightMark.Summary: return Summary(d); + case FlightMark.NetControl: + { + string who = d.Length > 0 && d[0] == (byte)FlightDir.Out ? "client" : "server"; + ushort more = d.Length >= 4 ? (ushort)(d[2] | (d[3] << 8)) : (ushort)0; + string extra = more > 0 ? $" (+{more} more not marked)" : ""; + if (e.A == PacketFlags.Disconnect) return $"{who} sent DISCONNECT"; + return $"{who} asks for {e.B} lost packet(s) again (first seq {e.C}){extra}"; + } + default: return $"marker {e.Kind} {Hex(e.A)} {Hex(e.B)} {Hex(e.C)} {text}".TrimEnd(); + } + } + + private static string Summary(ReadOnlySpan d) + { + FlightSummary s = FlightSummary.Read(d); + string busy = s.RealBusy == FlightSummary.Unknown ? "?" : s.RealBusy.ToString(Inv); + string req = s.PendingType == 0xFFFFFFFF ? "?" : s.PendingType == 0 ? "none" : $"type {s.PendingType} on {Id(s.PendingObject)}"; + string atk = s.Attacking == 255 ? "?" : s.Attacking.ToString(Inv); + string ges = s.Gesture == 255 ? "?" : s.Gesture.ToString(Inv); + string loss = ""; + if (s.InRetransmits + s.OutRetransmits + s.InResendRequests + s.OutResendRequests + s.SendErrors > 0) + loss = $" | resent in {s.InRetransmits} out {s.OutRetransmits}, resend asks server {s.InResendRequests} client {s.OutResendRequests}" + + (s.SendErrors > 0 ? $", SEND ERRORS {s.SendErrors}" : ""); + return $"-- 1s: in {s.InPackets} pk/{s.InMessages} msg ({s.InKept} kept), out {s.OutPackets} pk/{s.OutMessages} msg ({s.OutKept} kept){loss}" + + $" | m_cBusy {busy} (engine {s.ShadowBusy}) | item request {req} | attacking {atk} | gesture {ges}"; + } + + private static string Busy(uint v) => unchecked((int)v) == FlightSummary.Unknown ? "?" : unchecked((int)v).ToString(Inv); + private static string Hex(uint v) => v == 0 ? "0" : $"0x{v:X}"; + + private static string Latin1(ReadOnlySpan d) + { + var sb = new StringBuilder(d.Length); + foreach (byte b in d) sb.Append(b < 32 ? ' ' : (char)b); + return sb.ToString(); + } + + // ── dump ─────────────────────────────────────────────────────────────── + + public static string Arrow(FlightDir dir) => dir switch + { + FlightDir.Out => "->", + FlightDir.In => "<-", + _ => "**", + }; + + /// + /// Writes the dump: a header, a legend, then one line per entry with its time relative to + /// (the moment the dump was asked for), the wall clock, the + /// arrow and the text. + /// + public static void WriteDump(TextWriter w, FlightRecord[] records, long zeroStamp, DateTime zeroLocal, + long ticksPerSecond, IEnumerable header) + { + w.WriteLine("RynthCore flight recorder dump"); + foreach (string h in header) w.WriteLine(h); + if (records.Length > 0) + { + double first = (records[0].Entry.Stamp - zeroStamp) * 1000.0 / ticksPerSecond; + double last = (records[^1].Entry.Stamp - zeroStamp) * 1000.0 / ticksPerSecond; + w.WriteLine($"Entries: {records.Length}, from {first / 1000.0:0.0} s to {last / 1000.0:+0.0;-0.0;0.0} s around the request."); + } + else + { + w.WriteLine("Entries: none."); + } + w.WriteLine(); + foreach (string l in Legend) w.WriteLine(l); + w.WriteLine(); + foreach (FlightRecord r in records) + w.WriteLine(Line(r, zeroStamp, zeroLocal, ticksPerSecond)); + } + + public static string Line(in FlightRecord r, long zeroStamp, DateTime zeroLocal, long ticksPerSecond) + { + double ms = (r.Entry.Stamp - zeroStamp) * 1000.0 / ticksPerSecond; + DateTime at = zeroLocal.AddMilliseconds(ms); + return $"{ms.ToString("+0;-0;0", Inv),9} ms {at.ToString("HH:mm:ss.fff", Inv)} {Arrow(r.Entry.Dir)} {Describe(r)}"; + } + + public static readonly string[] Legend = + { + "How to read: one line per message or marker, oldest first.", + " column 1: milliseconds relative to the dump request (negative = before it); column 2: local time.", + " -> client to server (what this client sent). [eng] = matches an engine direct-action call just before", + " (the 'engine ...' marker above it); [cli] = no engine call to match: the client's own path", + " (keyboard/mouse, or a plugin calling AC some other way). Movement matches are by time only.", + " <- server to client: game events (UseDone, ViewContents, errors, magic, combat), the player's own", + " motion/position/teleport, system text, and messages about objects the character just used.", + " ** engine markers: engine calls, m_cBusy changes and resets, action-gate clears, a per-second link", + " and client-state summary ('-- 1s'), hot reloads, notes and dump triggers.", + " '#n' is the action/event sequence; 'seq i/s/t/f' are the instance/server-control/teleport/force-position", + " sequences; '(+N like it not kept)' counts position updates skipped by the rate limit; '...' = cut off.", + " Chat text the player says or reads is not recorded.", + }; +} diff --git a/src/RynthCore.Engine/Net/FlightRecorder.cs b/src/RynthCore.Engine/Net/FlightRecorder.cs new file mode 100644 index 0000000..33bba5b --- /dev/null +++ b/src/RynthCore.Engine/Net/FlightRecorder.cs @@ -0,0 +1,383 @@ +// ============================================================================ +// RynthCore.Engine - Net/FlightRecorder.cs +// Always-on flight recorder: the last minutes of client<->server traffic that matters +// for "the character stopped doing things", plus the engine's own markers, dumped to +// a text file on request or when a stall is detected. +// +// Feeds (all cheap, none allocates on the hot path): +// - RawPacketHooks: every datagram sent (sendto detour, new) and received (the +// existing recvfrom detour) -> FlightCapture.OnDatagram; +// - AcActionTrace.Record (every engine direct-action call) -> EngineCall markers, +// used to tag the action that call sends as [eng]; +// - BusyCountHooks / ClientActionGates: m_cBusy changes, force-clears (plugin asks +// included), reconciles, negative repairs, gate clears; +// - GameTickHooks (AC's main thread, every tick) -> MainTick: a one-line summary per +// second (link counters, m_cBusy, the item-action gates, the cast gesture), the +// stall detectors, and starting a scheduled automatic dump. +// +// Dumps: /rc flightdump [note] (any time), /rc flightdump auto and the plugin +// command (SendPluginCommand("RynthCore.FlightRecorder", "dump", reason)) for automatic +// ones - at most one per AutoDumpCooldownMs, written AutoDumpDelayMs after the trigger so +// the aftermath is in it too. Files: Logs\flight--.txt, written on +// a short-lived engine thread. +// +// engine.json "FlightRecorder": false turns it off at the next client start (no sendto +// hook, nothing recorded); /rc flight off|on pauses it for the session. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Threading; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.Net; + +internal static unsafe class FlightRecorder +{ + public const int Capacity = 16384; // entries (152 bytes each, ~2.5 MB) + public const long AutoDumpCooldownMs = 10 * 60 * 1000; + public const int AutoDumpDelayMs = 3000; + public const int PruneDays = 14; + + /// The plugin name plugins pass to SendPluginCommand to reach the recorder. + public const string PluginCommandTarget = "RynthCore.FlightRecorder"; + + private static FlightCapture? _cap; + private static volatile bool _paused; + private static volatile bool _autoOff; + private static readonly FlightDumpPolicy Policy = new(AutoDumpCooldownMs); + private static long _lastSummaryMs; + private static int _lastSendErrors; + + private static readonly object ScheduleLock = new(); + private static string? _scheduledReason; + private static long _scheduledAtMs, _scheduledZeroStamp; + private static DateTime _scheduledZeroLocal; + + private static int _dumping; + private static string _lastDump = ""; + private static int _dumpsWritten; + + public static bool Enabled => _cap != null && !_paused; + + // ── setup ────────────────────────────────────────────────────────────── + + public static void Initialize() + { + if (_cap != null) return; + if (!EngineSettings.FlightRecorder) + { + RynthLog.Compat("FlightRecorder: off (engine.json \"FlightRecorder\": false)."); + return; + } + _cap = new FlightCapture(Capacity, Stopwatch.GetTimestamp, Stopwatch.Frequency); + uint gen = (uint)Math.Max(1, EntryPoint.InitCount); + _cap.Mark(FlightMark.EngineInit, gen); + RynthLog.Compat($"FlightRecorder: on ({Capacity} entries, {_cap.Ring.Bytes / 1024} KB); /rc flightdump writes it."); + if (gen <= 1) + PruneOldDumps(); + } + + public static void Shutdown() + { + FlightCapture? c = _cap; + if (c == null) return; + c.FlushEngineRepeats(); + c.Mark(FlightMark.EngineShutdown, text: EngineThreads.Stopping ? "hot reload or exit" : ""); + } + + // ── feeds ────────────────────────────────────────────────────────────── + + /// RecvFrom detour, after the real call, with the bytes the client got. + public static void OnInbound(byte* data, int length) + { + FlightCapture? c = _cap; + if (c == null || _paused) return; + c.OnDatagram(false, data, length); + } + + /// SendTo detour, before the real call, with the bytes the client sends. + public static void OnOutbound(byte* data, int length) + { + FlightCapture? c = _cap; + if (c == null || _paused) return; + c.OnDatagram(true, data, length); + } + + /// An engine direct-action call (AcActionTrace.Record). is a literal. + public static void EngineCall(string name, uint a, uint b) + { + FlightCapture? c = _cap; + if (c == null || _paused) return; + try { c.EngineCall(name, a, b); } catch { } + } + + public static void Mark(FlightMark kind, uint a = 0, uint b = 0, uint c = 0, string? text = null) + { + FlightCapture? cap = _cap; + if (cap == null || _paused) return; + try { cap.Mark(kind, a, b, c, text); } catch { } + } + + /// AC's main thread, every game tick (GameTickHooks, post-tick). + public static void MainTick() + { + FlightCapture? c = _cap; + if (c == null) return; + long now = Environment.TickCount64; + if (!_paused && now - _lastSummaryMs >= 1000) + { + _lastSummaryMs = now; + WriteSummary(c); + c.Tick(); + string? trigger = c.TakeTrigger(); + if (trigger != null) + RequestAuto(trigger, "engine"); + } + string? reason = null; + long zero = 0; + DateTime zeroLocal = default; + lock (ScheduleLock) + { + if (_scheduledReason != null && now >= _scheduledAtMs) + { + reason = _scheduledReason; + zero = _scheduledZeroStamp; + zeroLocal = _scheduledZeroLocal; + _scheduledReason = null; + } + } + if (reason != null) + StartDump("auto: " + reason, zero, zeroLocal, announce: true); + } + + private static void WriteSummary(FlightCapture c) + { + var s = new FlightSummary + { + RealBusy = FlightSummary.Unknown, + PendingType = 0xFFFFFFFF, + Attacking = 255, + Gesture = 255, + }; + try { if (BusyCountHooks.TryReadRealBusy(out int real)) s.RealBusy = real; } catch { } + s.ShadowBusy = BusyCountHooks.ShadowBusyCount; + try + { + if (ClientActionGates.TryReadPending(out uint type, out uint obj, out _)) { s.PendingType = type; s.PendingObject = obj; } + if (ClientActionGates.TryReadAttacking(out bool atk)) s.Attacking = atk ? (byte)1 : (byte)0; + } + catch { } + try { if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool g)) s.Gesture = g ? (byte)1 : (byte)0; } catch { } + c.TakeCounters(ref s); + int sendErrors = RawPacketHooks.SendErrors; + s.SendErrors = (ushort)Math.Clamp(sendErrors - _lastSendErrors, 0, ushort.MaxValue); + _lastSendErrors = sendErrors; + c.WriteSummary(s); + } + + // ── dumps ────────────────────────────────────────────────────────────── + + /// An automatic dump request (detector, plugin, /rc flightdump auto). Rate-limited. + public static string RequestAuto(string reason, string source) + { + FlightCapture? c = _cap; + if (c == null) return "Flight recorder is off."; + reason = Clean(reason, 100); + if (_autoOff) + { + c.Mark(FlightMark.Trigger, text: $"{source}: {reason} (automatic dumps are off: /rc flight auto on)"); + return "Automatic flight dumps are off for this session."; + } + long now = Environment.TickCount64; + if (!Policy.TryAccept(now, out long waitMs)) + { + c.Mark(FlightMark.Trigger, text: $"{source}: {reason} (no dump: one was written {(Policy.CooldownMs - waitMs) / 1000} s ago)"); + return $"Not dumped: the last automatic dump was {(Policy.CooldownMs - waitMs) / 1000} s ago (one per {Policy.CooldownMs / 60000} min)."; + } + c.Mark(FlightMark.Trigger, text: $"{source}: {reason}"); + lock (ScheduleLock) + { + _scheduledReason = $"{source}: {reason}"; + _scheduledAtMs = now + AutoDumpDelayMs; + _scheduledZeroStamp = Stopwatch.GetTimestamp(); + _scheduledZeroLocal = DateTime.Now; + } + RynthLog.Compat($"FlightRecorder: automatic dump in {AutoDumpDelayMs / 1000} s ({source}: {reason})."); + return $"Automatic flight dump in {AutoDumpDelayMs / 1000} s."; + } + + /// A manual dump now. Returns the file it is being written to. + public static string DumpNow(string note) + { + FlightCapture? c = _cap; + if (c == null) return "Flight recorder is off (engine.json \"FlightRecorder\": false)."; + note = Clean(note, 100); + c.Mark(FlightMark.Dump, text: note); + string? path = StartDump(note.Length > 0 ? "manual: " + note : "manual", Stopwatch.GetTimestamp(), DateTime.Now, announce: false); + return path == null ? "A dump is already being written; try again in a moment." : $"Flight recorder dump: {path}"; + } + + private static string? StartDump(string why, long zeroStamp, DateTime zeroLocal, bool announce) + { + FlightCapture? c = _cap; + if (c == null) return null; + if (Interlocked.CompareExchange(ref _dumping, 1, 0) != 0) + return null; + string path; + try + { + LogPaths.EnsureLogDirectory(); + string stem = $"flight-{Environment.ProcessId}-{DateTime.Now:yyyyMMdd-HHmmss}"; + path = Path.Combine(LogPaths.LogDirectory, stem + ".txt"); + for (int i = 2; File.Exists(path) && i < 100; i++) + path = Path.Combine(LogPaths.LogDirectory, $"{stem}-{i}.txt"); + } + catch (Exception ex) + { + Volatile.Write(ref _dumping, 0); + RynthLog.Compat($"FlightRecorder: dump failed - {ex.Message}"); + return null; + } + c.FlushEngineRepeats(); + string file = path; + try + { + EngineThreads.Start("RynthCore.FlightDump", () => WriteDumpFile(c, file, why, zeroStamp, zeroLocal, announce)); + } + catch (Exception ex) + { + Volatile.Write(ref _dumping, 0); + RynthLog.Compat($"FlightRecorder: dump thread failed - {ex.Message}"); + return null; + } + return path; + } + + private static void WriteDumpFile(FlightCapture c, string path, string why, long zeroStamp, DateTime zeroLocal, bool announce) + { + try + { + FlightRecord[] records = c.Ring.Snapshot(); + var header = new List + { + $"Reason: {why}", + $"Requested: {zeroLocal:yyyy-MM-dd HH:mm:ss.fff} (time 0 below)", + $"Client pid {Environment.ProcessId}, engine build {EntryPoint.BuildStamp}, generation {EntryPoint.InitCount}, player 0x{c.PlayerId:X8}", + $"Ring: {c.Ring.Capacity} entries, {c.Ring.Total} recorded since this engine generation started.", + }; + using (var w = new StreamWriter(path, false, new System.Text.UTF8Encoding(false), 256 * 1024)) + FlightFormat.WriteDump(w, records, zeroStamp, zeroLocal, Stopwatch.Frequency, header); + _lastDump = path; + Interlocked.Increment(ref _dumpsWritten); + RynthLog.Compat($"FlightRecorder: wrote {path} ({records.Length} entries; {why})."); + if (announce) + AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] Flight recorder saved ({why}): {path}", 1); + } + catch (Exception ex) + { + RynthLog.Compat($"FlightRecorder: writing {path} failed - {ex.GetType().Name}: {ex.Message}"); + } + finally + { + Volatile.Write(ref _dumping, 0); + } + } + + private static void PruneOldDumps() + { + try + { + if (!Directory.Exists(LogPaths.LogDirectory)) return; + DateTime cutoff = DateTime.Now.AddDays(-PruneDays); + foreach (string f in Directory.GetFiles(LogPaths.LogDirectory, "flight-*.txt")) + { + try { if (File.GetLastWriteTime(f) < cutoff) File.Delete(f); } catch { } + } + } + catch { } + } + + private static string Clean(string? s, int max) + { + if (string.IsNullOrWhiteSpace(s)) return ""; + s = s.Trim().Replace('\r', ' ').Replace('\n', ' '); + return s.Length > max ? s.Substring(0, max) : s; + } + + // ── commands ─────────────────────────────────────────────────────────── + + /// /rc flightdump [note] | /rc flightdump auto <reason> + public static string[] HandleDumpCommand(string args) + { + args = args.Trim(); + if (args.StartsWith("auto", StringComparison.OrdinalIgnoreCase) && (args.Length == 4 || args[4] == ' ')) + return new[] { RequestAuto(args.Length > 4 ? args.Substring(5) : "chat command", "command") }; + return new[] { DumpNow(args) }; + } + + /// /rc flight [status|mark <text>|on|off|auto on|off] + public static string[] HandleCommand(string args) + { + string[] parts = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries); + string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "status"; + string rest = parts.Length > 1 ? parts[1].Trim() : ""; + switch (verb) + { + case "mark": + case "note": + if (_cap == null) return new[] { "Flight recorder is off." }; + Mark(FlightMark.Note, text: Clean(rest, 100)); + return new[] { "Marked." }; + case "off": + _paused = true; + return new[] { "Flight recorder paused for this session (/rc flight on resumes)." }; + case "on": + _paused = false; + return new[] { _cap == null ? "Flight recorder is off in engine.json (\"FlightRecorder\": false); restart the client after changing it." : "Flight recorder recording." }; + case "auto": + if (rest.Equals("off", StringComparison.OrdinalIgnoreCase)) { _autoOff = true; return new[] { "Automatic flight dumps off for this session." }; } + if (rest.Equals("on", StringComparison.OrdinalIgnoreCase)) { _autoOff = false; return new[] { "Automatic flight dumps on." }; } + return new[] { "Usage: /rc flight auto on|off" }; + default: + return StatusLines(); + } + } + + public static string[] StatusLines() + { + FlightCapture? c = _cap; + if (c == null) + return new[] { "Flight recorder: off (engine.json \"FlightRecorder\": false)." }; + return new[] + { + $"Flight recorder: {(_paused ? "PAUSED" : "recording")}, {c.Ring.Total} entries recorded (ring {c.Ring.Capacity}, {c.Ring.Bytes / 1024} KB), " + + $"send hook {(RawPacketHooks.IsSendInstalled ? "installed" : "NOT installed")}, receive hook {(RawPacketHooks.IsInstalled ? "installed" : "NOT installed")}, player 0x{c.PlayerId:X8}", + $"Automatic dumps {(_autoOff ? "OFF" : "on")} (one per {AutoDumpCooldownMs / 60000} min, {Policy.Refused} refused by the limit); " + + $"refused-use streak {c.RefusedStreak}; dumps written {_dumpsWritten}{(_lastDump.Length > 0 ? ", last " + _lastDump : "")}", + "/rc flightdump [note] writes it now; /rc flight mark adds a note; /rc flight off|on|auto off|on.", + }; + } + + /// SendPluginCommand("RynthCore.FlightRecorder", action, value): "dump" (automatic, + /// rate-limited; value = reason) or "mark" (value = note). Any thread. + public static bool HandlePluginCommand(string? action, string? value) + { + if (_cap == null) return false; + switch ((action ?? "").Trim().ToLowerInvariant()) + { + case "dump": + RequestAuto(value ?? "", "plugin"); + return true; + case "mark": + case "note": + Mark(FlightMark.Note, text: Clean("plugin: " + value, 100)); + return true; + default: + return false; + } + } +} diff --git a/src/RynthCore.Engine/Net/FlightRing.cs b/src/RynthCore.Engine/Net/FlightRing.cs new file mode 100644 index 0000000..e607f59 --- /dev/null +++ b/src/RynthCore.Engine/Net/FlightRing.cs @@ -0,0 +1,258 @@ +// ============================================================================ +// RynthCore.Engine - Net/FlightRing.cs +// The flight recorder's ring: a fixed number of fixed-size entries, allocated once. +// +// Writers (the send/receive detours, the busy-count hooks, engine calls, any thread) +// claim a slot with one Interlocked.Increment and fill it in place: no allocation, no +// lock, never waits. A writer takes its slot by swapping the slot's Serial to minus its +// record number (compare-exchange), fills it, and publishes the record number; a reader +// copies a slot only when Serial is the number it expects before and after the copy, so a +// slot being rewritten is skipped (it was about to be overwritten anyway). +// +// An entry is a message (its first DataCap bytes, decoded only when dumped) or a +// marker (kind + three numbers, optional short text, optional string-literal name). +// +// Pure code (no engine state); compiled into tools/FlightRecorderTests. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.Net; + +internal enum FlightDir : byte +{ + None = 0, + /// Server to client. + In = 1, + /// Client to server. + Out = 2, + /// Engine-side marker. + Mark = 3, +} + +[Flags] +internal enum FlightFlags : byte +{ + None = 0, + /// Outbound action matched an engine direct-action call made just before. + Engine = 0x01, + /// Only the first DataCap bytes were kept. + Truncated = 0x02, + /// The message spans several fragments; only the first was seen. + MultiFragment = 0x04, + /// A retransmitted copy of a message not seen before. + Retransmit = 0x08, + /// sendto returned an error for the datagram carrying this message. + SendFailed = 0x10, + /// Outbound action with no engine call to match: the client's own path. + Client = 0x20, +} + +/// Marker kinds (FlightEntry.Kind when Dir == Mark). +internal enum FlightMark : ushort +{ + Note = 1, // text: a manual or plugin note + EngineCall = 2, // Name = call, A/B = args, C = collapsed repeats before it + BusyIncrement = 3, // A = real m_cBusy after, B = shadow after + BusyDecrement = 4, // A = real m_cBusy after, B = shadow after + BusyForceClear = 5, // A = real before, B = shadow before; text = who + BusyForceClearAsk = 6, // text = who asked (plugin host API, off-thread latch) + BusyReconcile = 7, // A = decrements done, B = real after + BusyNegativeRepair = 8, // A = value found (as int) + BusyWatchdog = 9, // A = real, B = shadow, C = ms stuck; text = which watchdog + GateCleared = 10, // A = request type (0 = attacking flag), B = object; text = why + EngineInit = 11, // A = engine generation (init count) + EngineShutdown = 12, + Summary = 13, // Data = FlightSummary + Trigger = 14, // text = reason (auto dump requested) + NetControl = 15, // A = flag bit, B = count, C = first sequence; dir byte in Data[0] + Dump = 16, // text = note (manual dump requested) + PluginReload = 17, // text = plugin +} + +[StructLayout(LayoutKind.Sequential)] +internal unsafe struct FlightEntry +{ + public const int DataCap = 120; + + /// Stopwatch timestamp. + public long Stamp; + /// 1-based record number once written; minus the number while being written; 0 never written. + public int Serial; + public FlightDir Dir; + public FlightFlags Flags; + /// Marker kind (FlightMark) for markers; 0 for messages. + public ushort Kind; + /// Bytes kept in Data. + public ushort Len; + /// Message length as seen (first fragment's payload, or count * size for multi-fragment), clamped. + public ushort FullLen; + /// Messages: fragment sequence. Markers: first number. + public uint A; + /// Messages: rate-limited copies dropped before this one. Markers: second number. + public uint B; + /// Messages: unused. Markers: third number. + public uint C; + public fixed byte Data[DataCap]; +} + +/// A copied, consistent entry plus the marker's name (string literal) if any. +internal struct FlightRecord +{ + public FlightEntry Entry; + public string? Name; +} + +internal sealed unsafe class FlightRing +{ + private readonly FlightEntry[] _slots; + private readonly string?[] _names; + private readonly int _mask; + private int _next; // records claimed (Interlocked) + + public FlightRing(int capacityPow2) + { + if (capacityPow2 < 16 || (capacityPow2 & (capacityPow2 - 1)) != 0) + throw new ArgumentOutOfRangeException(nameof(capacityPow2)); + _slots = new FlightEntry[capacityPow2]; + _names = new string?[capacityPow2]; + _mask = capacityPow2 - 1; + } + + public int Capacity => _slots.Length; + + /// Records ever written (2^31 is years of play; dumps use the last Capacity). + public int Total => Volatile.Read(ref _next); + + /// Approximate memory held by the ring, for status lines. + public int Bytes => _slots.Length * (sizeof(FlightEntry) + IntPtr.Size); + + /// Records dropped because their slot was still being written by a writer a whole + /// lap behind (a thread stalled for Capacity records; practically never). + public long Dropped => Interlocked.Read(ref _dropped); + private long _dropped; + + /// + /// Claims the next record number and takes its slot: the slot's Serial goes from its last + /// published value to -serial with one compare-exchange, so two writers never fill one slot + /// at once; a slot still owned by a stalled writer is skipped (counted in Dropped). + /// + private bool Own(out int i, out int serial) + { + serial = Interlocked.Increment(ref _next); + i = (serial - 1) & _mask; + int prev = Volatile.Read(ref _slots[i].Serial); + if (prev < 0 || Interlocked.CompareExchange(ref _slots[i].Serial, -serial, prev) != prev) + { + Interlocked.Increment(ref _dropped); + return false; + } + return true; + } + + /// A message: its first DataCap bytes. + public void WriteMessage(long stamp, FlightDir dir, FlightFlags flags, byte* msg, int len, int fullLen, uint fragSeq, uint suppressed) + { + if (!Own(out int i, out int serial)) return; + ref FlightEntry e = ref _slots[i]; + _names[i] = null; + int keep = len < 0 ? 0 : Math.Min(len, FlightEntry.DataCap); + e.Stamp = stamp; + e.Dir = dir; + e.Flags = keep < len ? flags | FlightFlags.Truncated : flags; + e.Kind = 0; + e.Len = (ushort)keep; + e.FullLen = (ushort)Math.Clamp(fullLen, 0, ushort.MaxValue); + e.A = fragSeq; + e.B = suppressed; + e.C = 0; + fixed (byte* d = e.Data) + { + if (keep > 0) Buffer.MemoryCopy(msg, d, FlightEntry.DataCap, keep); + } + Volatile.Write(ref e.Serial, serial); + } + + /// A marker. must be a string literal (or otherwise long-lived); + /// is copied (Latin-1, truncated to DataCap). + public void WriteMark(long stamp, FlightMark kind, string? name, uint a, uint b, uint c, ReadOnlySpan text) + { + if (!Own(out int i, out int serial)) return; + ref FlightEntry e = ref _slots[i]; + _names[i] = name; + int keep = Math.Min(text.Length, FlightEntry.DataCap); + e.Stamp = stamp; + e.Dir = FlightDir.Mark; + e.Flags = keep < text.Length ? FlightFlags.Truncated : FlightFlags.None; + e.Kind = (ushort)kind; + e.Len = (ushort)keep; + e.FullLen = (ushort)Math.Min(text.Length, ushort.MaxValue); + e.A = a; + e.B = b; + e.C = c; + fixed (byte* d = e.Data) + { + for (int k = 0; k < keep; k++) + { + char ch = text[k]; + d[k] = ch < 256 ? (byte)ch : (byte)'?'; + } + } + Volatile.Write(ref e.Serial, serial); + } + + /// A marker carrying raw bytes (the per-second summary). + public void WriteMarkBytes(long stamp, FlightMark kind, uint a, uint b, uint c, ReadOnlySpan bytes) + { + if (!Own(out int i, out int serial)) return; + ref FlightEntry e = ref _slots[i]; + _names[i] = null; + int keep = Math.Min(bytes.Length, FlightEntry.DataCap); + e.Stamp = stamp; + e.Dir = FlightDir.Mark; + e.Flags = FlightFlags.None; + e.Kind = (ushort)kind; + e.Len = (ushort)keep; + e.FullLen = (ushort)keep; + e.A = a; + e.B = b; + e.C = c; + fixed (byte* d = e.Data) + { + for (int k = 0; k < keep; k++) d[k] = bytes[k]; + } + Volatile.Write(ref e.Serial, serial); + } + + /// + /// Copies every complete entry, oldest first. Entries being written while this runs are + /// skipped. Allocates (dump time only). + /// + public FlightRecord[] Snapshot() + { + int total = Volatile.Read(ref _next); + int count = Math.Min(total, _slots.Length); + var list = new FlightRecord[count]; + int n = 0; + for (int s = total - count + 1; s <= total; s++) + { + int i = (s - 1) & _mask; + int before = Volatile.Read(ref _slots[i].Serial); + if (before != s) + continue; + FlightEntry copy = _slots[i]; + string? name = _names[i]; + Interlocked.MemoryBarrier(); + if (Volatile.Read(ref _slots[i].Serial) != s) + continue; + list[n].Entry = copy; + list[n].Name = name; + n++; + } + if (n != list.Length) + Array.Resize(ref list, n); + return list; + } +} diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index a9b1a31..2feb1c3 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -34,6 +34,7 @@ internal static class EngineSettings // "DisabledUiHooks": the UI hooks (Compatibility/UiHookRegistry) switched off by name. private static readonly HashSet _disabledUiHooks = new(StringComparer.OrdinalIgnoreCase); private static bool _serverMessageStream = true; + private static bool _flightRecorder = true; private static bool _loaded; public static IReadOnlyList PluginPaths @@ -288,6 +289,19 @@ internal static class EngineSettings } } + /// "FlightRecorder" in engine.json (default true): the always-on flight recorder + /// (Net/FlightRecorder.cs, /rc flightdump): a sendto hook plus a ring of the last minutes of + /// client/server traffic and engine markers. false = no sendto hook and nothing recorded, + /// from the next client start. + public static bool FlightRecorder + { + get + { + EnsureLoaded(); + return _flightRecorder; + } + } + public static void AddPluginPath(string path) { EnsureLoaded(); @@ -414,6 +428,10 @@ internal static class EngineSettings (smsEl.ValueKind == JsonValueKind.True || smsEl.ValueKind == JsonValueKind.False)) _serverMessageStream = smsEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("FlightRecorder", out var frEl) && + (frEl.ValueKind == JsonValueKind.True || frEl.ValueKind == JsonValueKind.False)) + _flightRecorder = frEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) && (pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False)) { @@ -436,6 +454,19 @@ internal static class EngineSettings } } + /// Every engine.json key EnsureLoaded reads or Save writes. Save rewrites these from + /// memory (one written only when not the default is left out, as before) and keeps every + /// other key as the file had it. A new engine.json setting goes here too + /// (tools/EngineSettingsTests checks this list against this file). + internal static readonly HashSet OwnedKeys = new(StringComparer.Ordinal) + { + "PluginPaths", "EnableImGuiShell", "EnablePlugins", "EnableDatShareHook", + "EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount", + "EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge", + "DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream", + "FlightRecorder", + }; + private static void Save() { try @@ -476,9 +507,20 @@ internal static class EngineSettings } if (!_serverMessageStream) // default true: leave the file as it was w.WriteBoolean("ServerMessageStream", false); + if (!_flightRecorder) // default true: leave the file as it was + w.WriteBoolean("FlightRecorder", false); w.WriteEndObject(); } - File.WriteAllBytes(SettingsPath, ms.ToArray()); + + // Keep the keys others write (the launcher's), and swap the file in atomically. + string? existing = File.Exists(SettingsPath) ? File.ReadAllText(SettingsPath) : null; + byte[]? merged = EngineSettingsFile.Merge(existing, ms.ToArray(), OwnedKeys, out string? readError); + if (merged == null) + { + RynthLog.Warn($"EngineSettings: not saving - {SettingsPath} can't be read ({readError}), and rewriting it would lose what it holds. The change holds until the client closes; fix or delete the file to save again."); + return; + } + EngineSettingsFile.WriteAtomic(SettingsPath, merged); } catch (Exception ex) { diff --git a/src/RynthCore.Engine/Plugins/EngineSettingsFile.cs b/src/RynthCore.Engine/Plugins/EngineSettingsFile.cs new file mode 100644 index 0000000..f0bc58e --- /dev/null +++ b/src/RynthCore.Engine/Plugins/EngineSettingsFile.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Threading; + +namespace RynthCore.Engine.Plugins; + +/// +/// File side of 's save: engine.json is shared (the launcher writes its +/// own keys there, e.g. EnableDcompOverlay), so a save keeps every top-level key the engine doesn't +/// own exactly as it was, and swaps the file in atomically (temp file, then replace) so a crash +/// mid-save can't leave a truncated engine.json. No logging and no engine state: the +/// EngineSettingsTests tool compiles this file in. +/// Idea from Silentkelpie (rynth PR #1, CopyUnownedFields); re-implemented here. +/// +internal static class EngineSettingsFile +{ + /// + /// The new engine.json: (a JSON object holding the keys the + /// engine writes, in its order), then every top-level key of + /// that is neither in nor written by the engine, value untouched. + /// A key in that the engine didn't write this time (one it only + /// writes when not the default) is left out, as before. A missing or empty existing file has + /// nothing to keep. Returns null, with set, when the existing file + /// isn't a readable JSON object: overwriting it would lose whatever it holds. + /// + public static byte[]? Merge(string? existingJson, byte[] ownedJson, ICollection ownedKeys, out string? error) + { + error = null; + JsonDocument? existing = null; + try + { + if (!string.IsNullOrWhiteSpace(existingJson)) + { + try + { + existing = JsonDocument.Parse(existingJson); + } + catch (JsonException ex) + { + error = ex.Message; + return null; + } + if (existing.RootElement.ValueKind != JsonValueKind.Object) + { + error = $"the top level is {existing.RootElement.ValueKind}, not an object"; + return null; + } + } + + using JsonDocument owned = JsonDocument.Parse(ownedJson); + var written = new HashSet(StringComparer.Ordinal); + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true })) + { + w.WriteStartObject(); + foreach (JsonProperty p in owned.RootElement.EnumerateObject()) + { + if (!written.Add(p.Name)) continue; + p.WriteTo(w); + } + if (existing != null) + { + foreach (JsonProperty p in existing.RootElement.EnumerateObject()) + { + if (ownedKeys.Contains(p.Name)) continue; + if (!written.Add(p.Name)) continue; // also drops a duplicate key in the old file + p.WriteTo(w); + } + } + w.WriteEndObject(); + } + return ms.ToArray(); + } + finally + { + existing?.Dispose(); + } + } + + /// + /// Writes to a temp file next to (unique per + /// process, since every client's engine can save), then swaps it in with File.Replace (or a + /// move when there is no file yet). A reader or another client's save holding the file for a + /// moment gets a few short retries. The temp file never stays behind. Throws on failure. + /// + public static void WriteAtomic(string path, byte[] bytes) + { + string tmp = $"{path}.{Environment.ProcessId}.{Guid.NewGuid():N}.tmp"; + try + { + File.WriteAllBytes(tmp, bytes); + for (int attempt = 1; ; attempt++) + { + try + { + if (File.Exists(path)) + File.Replace(tmp, path, destinationBackupFileName: null); + else + File.Move(tmp, path, overwrite: true); + return; + } + catch (IOException) when (attempt < 4) + { + Thread.Sleep(25 * attempt); + } + catch (UnauthorizedAccessException) when (attempt < 4) + { + Thread.Sleep(25 * attempt); + } + } + } + finally + { + try { if (File.Exists(tmp)) File.Delete(tmp); } catch { } + } + } +} diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 95775ba..6dff8e9 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -1407,6 +1407,7 @@ internal static partial class PluginManager } RynthLog.Plugin("PluginManager: Rescanning plugins..."); + Net.FlightRecorder.Mark(Net.FlightMark.PluginReload, text: "all plugins unloaded and loaded again (rescan)"); UnloadAllPlugins(); PluginLoader.CleanupShadowCopies(_shadowRootDir); @@ -2334,7 +2335,7 @@ internal static partial class PluginManager // bundled Plugins\ folder — that historically caused stray DLLs to // load on next start (or after hot-reload) without the user knowing. var extraPaths = EngineSettings.PluginPaths; - var candidates = new List(extraPaths.Count); + var present = new List(extraPaths.Count); for (int i = 0; i < extraPaths.Count; i++) { string dllPath = extraPaths[i]; @@ -2343,33 +2344,26 @@ internal static partial class PluginManager RynthLog.Plugin($"PluginManager: Extra plugin not found: {dllPath}"); continue; } - - // Skip if a plugin with the same filename was already loaded from the default directory. - // Both paths share the same session shadow dir — loading the same filename twice would - // try to overwrite a locked shadow copy and crash. - string extraFileName = Path.GetFileName(dllPath); - bool alreadyLoaded = false; - for (int j = 0; j < _plugins.Count; j++) - { - if (string.Equals(Path.GetFileName(_plugins[j].SourceFilePath), extraFileName, StringComparison.OrdinalIgnoreCase)) - { - alreadyLoaded = true; - break; - } - } - for (int j = 0; j < candidates.Count && !alreadyLoaded; j++) - { - if (string.Equals(Path.GetFileName(candidates[j]), extraFileName, StringComparison.OrdinalIgnoreCase)) - alreadyLoaded = true; - } - if (alreadyLoaded) - { - RynthLog.Plugin($"PluginManager: Extra plugin {extraFileName} already loaded from default directory — skipping."); - continue; - } - candidates.Add(dllPath); + present.Add(dllPath); } + // One plugin per file name, before any shadow copy: every shadow copy shares the session + // folder, so a second DLL of the same name would overwrite a mapped copy. The same file + // listed twice loads once; the same name from two folders is a conflict - the first wins + // (PluginPathDedupe). + var loadedSources = new List(_plugins.Count); + for (int j = 0; j < _plugins.Count; j++) + loadedSources.Add(_plugins[j].SourceFilePath); + PluginPathDedupe.Result deduped = PluginPathDedupe.Dedupe(present, loadedSources); + foreach (PluginPathDedupe.Skipped skipped in deduped.Skipped) + { + if (skipped.SameFile) + RynthLog.Plugin($"PluginManager: {skipped.Message}"); + else + RynthLog.Warn($"PluginManager: {skipped.Message}"); + } + List candidates = deduped.Load; + // Manifests (embedded in the DLLs, read without loading them): refuse a plugin that needs // a newer engine API or a missing plugin, and put required plugins first. Without // manifests the list loads exactly as before. @@ -3056,6 +3050,7 @@ internal static partial class PluginManager private static int CancelAttack() { + Compatibility.AcActionTrace.Record("CancelAttack"); return ToAbiBool(ClientActionHooks.CancelAttack()); } @@ -3584,6 +3579,7 @@ internal static partial class PluginManager private static int UseObjectOn(uint sourceObjectId, uint targetObjectId) { + Compatibility.AcActionTrace.Record("UseObjectOn", sourceObjectId, targetObjectId); LogPluginUse("UseObjectOn", sourceObjectId, targetObjectId); return ToAbiBool(ClientHelperHooks.UseObjectOn(sourceObjectId, targetObjectId)); } @@ -3633,31 +3629,37 @@ internal static partial class PluginManager private static int UseEquippedItem(uint sourceObjectId, uint targetObjectId) { + Compatibility.AcActionTrace.Record("UseEquippedItem", sourceObjectId, targetObjectId); return ToAbiBool(ClientHelperHooks.UseEquippedItem(sourceObjectId, targetObjectId)); } private static int MoveItemExternal(uint objectId, uint targetContainerId, int amount) { + Compatibility.AcActionTrace.Record("MoveItemExternal", objectId, targetContainerId); return ToAbiBool(ClientHelperHooks.MoveItemExternal(objectId, targetContainerId, amount)); } private static int MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount) { + Compatibility.AcActionTrace.Record("MoveItemInternal", objectId, targetContainerId); return ToAbiBool(ClientHelperHooks.MoveItemInternal(objectId, targetContainerId, slot, amount)); } private static int SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount) { + Compatibility.AcActionTrace.Record("SplitStackInternal", objectId, targetContainerId); return ToAbiBool(ClientHelperHooks.SplitStackInternal(objectId, targetContainerId, slot, amount)); } private static int MergeStackInternal(uint sourceObjectId, uint targetObjectId) { + Compatibility.AcActionTrace.Record("MergeStackInternal", sourceObjectId, targetObjectId); return ToAbiBool(ClientHelperHooks.MergeStackInternal(sourceObjectId, targetObjectId)); } private static int GiveObjectTo(uint objectId, uint targetId, int amount) { + Compatibility.AcActionTrace.Record("GiveObjectTo", objectId, targetId); return ToAbiBool(ClientHelperHooks.GiveObjectTo(objectId, targetId, amount)); } @@ -4129,6 +4131,7 @@ internal static partial class PluginManager /// v70: wield into a chosen slot (see PluginContract.WieldItemFn). private static int WieldItemAction(uint objectId, uint equipMask) { + Compatibility.AcActionTrace.Record("WieldItem", objectId, equipMask); return ToAbiBool(ClientHelperHooks.WieldItem(objectId, equipMask)); } @@ -4140,6 +4143,16 @@ internal static partial class PluginManager if (string.IsNullOrEmpty(name)) return 0; + // The flight recorder answers to a reserved name (no plugin export, no API bump): + // an engine without it finds no such plugin and returns 0, so a plugin can call it + // on any engine. + if (name == Net.FlightRecorder.PluginCommandTarget) + { + string? action = actionAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(actionAnsi) : null; + string? value = valueAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(valueAnsi) : null; + return Net.FlightRecorder.HandlePluginCommand(action, value) ? 1 : 0; + } + IntPtr export = ResolvePluginExport(name, "RynthPluginApplyRemoteCommand"); if (export == IntPtr.Zero) return 0; @@ -4245,7 +4258,11 @@ internal static partial class PluginManager catch { return 0; } } - private static void ForceResetBusyCountAction() => BusyCountHooks.ForceResetBusyCount(); + private static void ForceResetBusyCountAction() + { + Net.FlightRecorder.Mark(Net.FlightMark.BusyForceClearAsk, text: "a plugin (host ForceResetBusyCount)"); + BusyCountHooks.ForceResetBusyCount(); + } private static unsafe int GetObjectSpellIdsAction(uint guid, uint* spellIds, int maxCount) { diff --git a/src/RynthCore.Engine/Plugins/PluginPathDedupe.cs b/src/RynthCore.Engine/Plugins/PluginPathDedupe.cs new file mode 100644 index 0000000..b08d047 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/PluginPathDedupe.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace RynthCore.Engine.Plugins; + +/// +/// De-duplicates engine.json's PluginPaths before anything is shadow-copied or loaded. Every +/// plugin's shadow copy sits in the same session folder under its file name, so two entries with +/// one file name can never both load: the second copy would overwrite a mapped file. +/// - The same file listed twice (any case, / or \, ".." or "." segments): loaded once; a +/// harmless repeat, said once in the log. +/// - The same file name in two folders: a real conflict (two builds of one plugin). The one +/// listed first (or already loaded) wins; the other is ignored with a warning naming both. +/// No logging and no engine state: PluginManager writes the lines, and tools/PluginManifestTests +/// compiles this file in. +/// Idea from Silentkelpie (rynth PR #1); re-implemented here. +/// +internal static class PluginPathDedupe +{ + /// An entry that won't load: as listed, and the entry that loads + /// instead. : both name one file (a repeat), not two copies. + internal readonly record struct Skipped(string Path, string KeptPath, bool SameFile, bool KeptAlreadyLoaded) + { + public string Message => SameFile + ? (KeptAlreadyLoaded + ? $"{Path} is already loaded - listed twice in engine.json PluginPaths, loaded once." + : $"{Path} is listed twice in engine.json PluginPaths - loaded once.") + : $"plugin conflict: {System.IO.Path.GetFileName(Path)} is listed from two folders. " + + $"Using {KeptPath} ({(KeptAlreadyLoaded ? "already loaded" : "listed first")}); ignoring {Path}. " + + "Remove the one you don't want from the launcher's plugin list."; + } + + internal sealed class Result + { + public List Load { get; } = new(); + public List Skipped { get; } = new(); + } + + /// + /// in order, less repeats and file-name conflicts with an earlier + /// entry or with (plugins loaded before this pass). The paths + /// kept are returned as listed, not rewritten. + /// + public static Result Dedupe(IReadOnlyList paths, IEnumerable? alreadyLoaded = null) + { + var result = new Result(); + // File name -> (normalized full path, path as listed, already loaded?) + var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); + + if (alreadyLoaded != null) + { + foreach (string loaded in alreadyLoaded) + { + if (string.IsNullOrWhiteSpace(loaded)) continue; + string name = FileName(loaded); + if (!byName.ContainsKey(name)) + byName[name] = (Normalize(loaded), loaded, true); + } + } + + foreach (string path in paths) + { + if (string.IsNullOrWhiteSpace(path)) continue; + string name = FileName(path); + string full = Normalize(path); + if (byName.TryGetValue(name, out var kept)) + { + bool same = string.Equals(kept.Full, full, StringComparison.OrdinalIgnoreCase); + result.Skipped.Add(new Skipped(path, kept.Listed, same, kept.Loaded)); + continue; + } + byName[name] = (full, path, false); + result.Load.Add(path); + } + return result; + } + + private static string FileName(string path) => Path.GetFileName(path.Trim().TrimEnd('/', '\\')); + + /// Full path with \ separators and no trailing separator; the raw text if the path + /// can't be resolved (it then only matches itself). + internal static string Normalize(string path) + { + string p = path.Trim(); + try + { + p = Path.GetFullPath(p); + } + catch (Exception) + { + // Bad characters or the like: compare as written. + } + return p.Replace('/', '\\').TrimEnd('\\'); + } +} diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index 3a15a25..a18b6e4 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -159,4 +159,9 @@ SkipUnchangedFiles="true" /> + + + + + diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index e34b9d2..36545c0 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -11,7 +11,8 @@ // // Rules (2026-09-29 overhaul). Each rule is a case-insensitive regex matched // against the line's text as AC printed it (no timestamp, so ^ and $ work), -// optionally only for one channel or chat type. It can +// or plain text (Contains / Starts with / Ends with, 2026-10-05; see +// ChatRuleMatching.cs), optionally only for one channel or chat type. It can // Move the line to a tab (it leaves All and its channel tab), // Copy it to a tab as well (it stays where it was), // Hide it everywhere, or @@ -173,6 +174,9 @@ internal sealed class ChatFilterRule public volatile string Tab = ""; public volatile ChatRuleAction Action = ChatRuleAction.Move; public volatile ChatColorMode ColorMode = ChatColorMode.None; + /// How Pattern is read: a regex (the default, and every rule saved before + /// 2026-10-05) or plain text. Recompile after changing it. + public volatile ChatMatchMode Mode = ChatMatchMode.Regex; /// A new rule's colour (amber). public const uint DefaultColor = 0xFFFFD27A; /// 0xAARRGGBB. @@ -202,21 +206,11 @@ internal sealed class ChatFilterRule public void Recompile() { Slow = false; - string pattern = Pattern; - if (pattern.Length == 0) { Compiled = null; Error = null; Invalid = true; return; } - try - { - Compiled = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, - TimeSpan.FromMilliseconds(TimeoutMs)); - Error = null; - Invalid = false; - } - catch (ArgumentException ex) - { - Compiled = null; - Error = ex.Message; - Invalid = true; - } + // 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; } /// Does the rule route (Move / Copy with a tab, or Hide)? @@ -242,11 +236,8 @@ internal sealed class ChatFilterRule public static WhenSpec Parse(string? raw) { raw = (raw ?? "").Trim(); - if (raw.StartsWith("chan:", StringComparison.OrdinalIgnoreCase) && raw.Length > 5) - return new WhenSpec(raw, raw[5..], -1); - if (raw.StartsWith("type:", StringComparison.OrdinalIgnoreCase) && int.TryParse(raw[5..], out int t) && t >= 0) - return new WhenSpec(raw, null, t); - return Any; + (string? channel, int type) = ChatRuleMatching.ParseWhen(raw); + return channel == null && type < 0 ? Any : new WhenSpec(raw, channel, type); } } } @@ -702,6 +693,7 @@ internal static class ChatModel ("type:25", "Salvaging"), ("type:23", "Recall"), ("type:5", "System messages"), + ("type:26", "Notices (too busy, missing components)"), }; /// The channel tab a ChatMessageType lands in; mirrors ChatClassifier.ChannelFor in the plugin. @@ -813,6 +805,39 @@ internal static class ChatModel EditFilters(list => list.Add(rule)); } + /// The rule a standard filter adds, if the list has it (any action, on or off). + public static ChatFilterRule? FindPresetRule(ChatFilterPreset preset) + { + foreach (ChatFilterRule r in Filters) + if (preset.SameAs(r.Mode, r.Pattern, r.When)) return r; + return null; + } + + /// + /// Adds a standard filter as an ordinary Hide rule at the end (or turns on and shows the one + /// already there). Returns a message for the user. + /// + public static string AddPresetRule(ChatFilterPreset preset) + { + ChatFilterRule? have = FindPresetRule(preset); + if (have != null) + { + FocusRule = have; + if (have.Enabled) return $"\"{preset.Label}\" is already in your rules."; + have.Enabled = true; + FiltersChanged(); + return $"\"{preset.Label}\" was off; it is on again."; + } + AddRule(new ChatFilterRule + { + Mode = preset.Mode, + Pattern = preset.Pattern, + When = preset.When, + Action = ChatRuleAction.Hide, + }); + return $"Added \"{preset.Label}\": it hides those lines (edit or delete it like any rule)."; + } + /// /// A pattern for "lines like this": player speech keeps the speaker and the /// way they spoke ("^Bob tells you, \""); anything else is the whole line @@ -1102,6 +1127,8 @@ internal static class ChatModel // Kept while the rule is set to "No colour" too, so switching colour back on // after a relaunch finds the colour that was picked. Color = f.ColorMode != ChatColorMode.None || f.ColorArgb != ChatFilterRule.DefaultColor ? FormatColor(f.ColorArgb) : null, + // Absent for a Regex rule, so a file without plain-text rules is written as before. + Mode = ChatRuleMatching.ToJson(f.Mode), }; /// @@ -1134,6 +1161,8 @@ internal static class ChatModel _ => ChatColorMode.None, }, ColorArgb = ParseColor(f.Color) ?? ChatFilterRule.DefaultColor, + // Absent (every file before 2026-10-05): Regex, as those rules always were. + Mode = ChatRuleMatching.Parse(f.Mode), }; rule.Recompile(); return rule; @@ -1649,69 +1678,3 @@ internal static class ChatModel }); } } - -// JsonSerializerContext must be at namespace scope (not nested) for source generation. -internal sealed class RynthChatLineDto -{ - [JsonPropertyName("seq")] public ulong Seq { get; set; } - [JsonPropertyName("ts")] public string Ts { get; set; } = ""; - [JsonPropertyName("chan")] public string Chan { get; set; } = ""; - /// ChatMessageType; RynthChat before 0.2.0 doesn't send it. - [JsonPropertyName("type")] public int Type { get; set; } = -1; - [JsonPropertyName("sender")] public string? Sender { get; set; } - [JsonPropertyName("text")] public string Text { get; set; } = ""; -} - -// Property names match the legacy hand-written JSON so existing settings load. -internal sealed class RynthChatFilterDto -{ - [JsonPropertyName("pattern")] public string? Pattern { get; set; } - [JsonPropertyName("tab")] public string? Tab { get; set; } - [JsonPropertyName("enabled")] public bool Enabled { get; set; } = true; - // Version 2: - /// "move" | "copy" | "hide" | "color"; absent in version 1 (see ChatModel.FromDto). - [JsonPropertyName("action")] public string? Action { get; set; } - /// "" / absent: any line; "chan:Combat"; "type:3". - [JsonPropertyName("when")] public string? When { get; set; } - /// "line" | "match"; absent: no colour. - [JsonPropertyName("colorMode")] public string? ColorMode { get; set; } - /// "#RRGGBB". - [JsonPropertyName("color")] public string? Color { get; set; } -} - -internal sealed class RynthChatSettingsDto -{ - /// Absent (0) in version-1 files. - [JsonPropertyName("version")] public int Version { get; set; } - [JsonPropertyName("fontSize")] public double FontSize { get; set; } = 10; - [JsonPropertyName("backgroundAlpha")] public int BackgroundAlpha { get; set; } = 0xF2; - [JsonPropertyName("autoScroll")] public bool AutoScroll { get; set; } = true; - [JsonPropertyName("suppressChat")] public bool SuppressChat { get; set; } - [JsonPropertyName("logEnabled")] public bool LogEnabled { get; set; } - // Chat's own Ctrl-gated click-through, like RadarPanel's (2026-09-02). - [JsonPropertyName("ctrlGatedClickThrough")] public bool CtrlGatedClickThrough { get; set; } - [JsonPropertyName("activeChannel")] public string? ActiveChannel { get; set; } - [JsonPropertyName("showTimestamps")] public bool ShowTimestamps { get; set; } = true; - [JsonPropertyName("mentionHighlight")] public bool MentionHighlight { get; set; } = true; - [JsonPropertyName("mentionSound")] public bool MentionSound { get; set; } - [JsonPropertyName("mentionWords")] public string? MentionWords { get; set; } - [JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; } - [JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; } -} - -/// Export / import on the clipboard (the rule editor's Export and Import). -internal sealed class RynthChatRuleSetDto -{ - public const string FormatName = "rynthchat-rules/2"; - [JsonPropertyName("format")] public string? Format { get; set; } - [JsonPropertyName("tabs")] public string[]? Tabs { get; set; } - [JsonPropertyName("rules")] public RynthChatFilterDto[]? Rules { get; set; } -} - -[JsonSerializable(typeof(RynthChatLineDto[]))] -[JsonSerializable(typeof(RynthChatLineDto))] -[JsonSerializable(typeof(RynthChatSettingsDto))] -[JsonSerializable(typeof(RynthChatRuleSetDto))] -[JsonSerializable(typeof(RynthChatFilterDto[]))] -[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = false, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] -internal partial class RynthChatJsonContext : JsonSerializerContext { } diff --git a/src/RynthCore.Engine/UI/Data/ChatFilterPresets.cs b/src/RynthCore.Engine/UI/Data/ChatFilterPresets.cs new file mode 100644 index 0000000..5cdf759 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatFilterPresets.cs @@ -0,0 +1,190 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatFilterPresets.cs +// Standard filters: ready-made RynthChat rules for common game spam +// (2026-10-05; the idea of canned filters is Silentkelpie's, rynth PR #1). +// Picking one in the rule editor adds it as an ordinary Hide rule, which the +// player can then see, edit, move or delete like any other: there is no +// second filter engine and nothing new in rynthchat_settings.json. +// +// The patterns are our own. They were written from the lines the game sent +// our own characters (the RynthCore logs' [BuffChat] lines, with their chat +// types) and from the game's message text; none are copied from another +// filter list. Each is held to its chat type or channel where the game gives +// one, so a player who says the same words in Local or a tell is never +// hidden, and tools/ChatFilterTests checks every example below. +// +// Not included: NPC vendor and quest tells. They arrive as ordinary tells +// (type 3), the same as a player's, and nothing in the line tells them apart. +// ============================================================================ + +using System; +using System.Text.RegularExpressions; + +namespace RynthCore.Engine.UI.Data; + +/// One standard filter: a rule template plus lines it must and must not catch. +internal sealed class ChatFilterPreset +{ + public string Id { get; } + public string Group { get; } + public string Label { get; } + public string Description { get; } + public ChatMatchMode Mode { get; } + public string Pattern { get; } + /// The rule's When ("" any line, "chan:X", "type:N"). + public string When { get; } + /// Lines it hides: text, the channel tab it arrives in, its chat type. + public (string Text, string Channel, int Type)[] Catches { get; } + /// Lines it leaves alone (mostly the same words from a player). + public (string Text, string Channel, int Type)[] Spares { get; } + + private readonly Regex? _rx; + private readonly (string? Channel, int Type) _when; + + public ChatFilterPreset(string id, string group, string label, string description, + ChatMatchMode mode, string pattern, string when, + (string, string, int)[] catches, (string, string, int)[] spares) + { + Id = id; Group = group; Label = label; Description = description; + Mode = mode; Pattern = pattern; When = when; + Catches = catches; Spares = spares; + _rx = ChatRuleMatching.Compile(mode, pattern, 50, out _); + _when = ChatRuleMatching.ParseWhen(when); + } + + /// Would the rule this preset adds catch the line? + public bool Matches(string text, string channel, int chatType) + { + if (_rx == null || !ChatRuleMatching.WhenMatches(_when.Channel, _when.Type, channel, chatType)) return false; + try { return _rx.IsMatch(text); } + catch (RegexMatchTimeoutException) { return false; } + } + + /// Is a rule with these fields this preset (already added)? + public bool SameAs(ChatMatchMode mode, string pattern, string when) => + mode == Mode + && string.Equals(pattern, Pattern, StringComparison.Ordinal) + && string.Equals((when ?? "").Trim(), When, StringComparison.OrdinalIgnoreCase); + + public string PickerLabel => Group + ": " + Label; +} + +internal static class ChatFilterPresets +{ + // ChatMessageType numbers as RynthChat reports them (seen in the RynthCore logs). + private const int Magic = 7, Emote = 12, Spellcasting = 17, EnemyCombat = 21, Notice = 26, ServerChannel = 27; + private const int Say = 2, Tell = 3; + + private static (string, string, int) L(string text, string channel, int type) => (text, channel, type); + + public static readonly ChatFilterPreset[] All = + { + // ── Casting ───────────────────────────────────────────────────── + new("cast.mine", "Casting", "Your spell words", + "Your own incantations (You say, \"Malar Zhavik\"). Only spell-word lines: what you say in Local stays.", + ChatMatchMode.StartsWith, "You say, \"", "type:17", + new[] { L("You say, \"Malar Zhavik\"", "Combat", Spellcasting), L("You say, \"Puish Zharil\"", "Combat", Spellcasting) }, + new[] { L("You say, \"anyone selling keys?\"", "Chat", Say) }), + new("cast.others", "Casting", "Others' spell words", + "Incantations from other players and monsters (Drudge Sorcerer says, \"Zojak Equin\").", + ChatMatchMode.Regex, "^(?!You say, ).+ says, \"", "type:17", + new[] { L("Drudge Sorcerer says, \"Zojak Equin\"", "Combat", Spellcasting) }, + new[] { L("You say, \"Malar Zhavik\"", "Combat", Spellcasting), L("Bob says, \"Zojak Equin\"", "Chat", Say) }), + new("cast.components", "Casting", "Components used", + "The spell consumed the following components: ...", + ChatMatchMode.StartsWith, "The spell consumed the following components", "type:7", + new[] { L("The spell consumed the following components: Prismatic Taper", "Combat", Magic), + L("The spell consumed the following components: Prismatic Taper, Prismatic Taper", "Combat", Magic) }, + new[] { L("The spell consumed the following components: lots", "Chat", Say) }), + new("cast.fizzle", "Casting", "Spell fizzled", + "Your spell fizzled.", + ChatMatchMode.StartsWith, "Your spell fizzled", "type:7", + new[] { L("Your spell fizzled.", "Combat", Magic) }, + new[] { L("Bob tells you, \"Your spell fizzled again\"", "Chat", Tell) }), + new("cast.self", "Casting", "Spells you cast on yourself", + "You cast ... on yourself (buffs, Stamina to Mana and the like).", + ChatMatchMode.Regex, "^You cast .+ on yourself", "type:7", + new[] { L("You cast Focus Self I on yourself, but it is surpassed by Incantation of Focus Other", "Combat", Magic), + L("You cast Stamina to Mana Self V on yourself and lose 17 points of stamina and also gain 23 points of mana", "Combat", Magic) }, + new[] { L("You cast Impenetrability I on Driftwarden Robe, but it is surpassed by Impenetrability V", "Combat", Magic) }), + new("cast.surpassed", "Casting", "Spell already surpassed", + "You cast X on Y, but it is surpassed by Z (a weaker buff over a stronger one).", + ChatMatchMode.Contains, ", but it is surpassed by ", "type:7", + new[] { L("You cast Bludgeon Bane I on Driftwarden Robe, but it is surpassed by Bludgeon Bane V", "Combat", Magic) }, + new[] { L("You cast Revitalize Self V and restore 40 points of your stamina.", "Combat", Magic) }), + new("cast.no_components", "Casting", "Missing components", + "You don't have all the components for this spell.", + ChatMatchMode.StartsWith, "You don't have all the components", "type:26", + new[] { L("You don't have all the components for this spell.", "Other", Notice) }, + new[] { L("Bob says, \"You don't have all the components for this spell.\"", "Chat", Say) }), + new("cast.no_mana", "Casting", "Not enough mana", + "You don't have enough Mana to cast this spell.", + ChatMatchMode.StartsWith, "You don't have enough Mana", "type:26", + new[] { L("You don't have enough Mana to cast this spell.", "Other", Notice) }, + Array.Empty<(string, string, int)>()), + + // ── Combat ────────────────────────────────────────────────────── + new("combat.you_evaded", "Combat", "You evaded", + "You evaded Tusker Guard!", + ChatMatchMode.StartsWith, "You evaded ", "type:21", + new[] { L("You evaded Tusker Guard!", "Combat", EnemyCombat), L("You evaded Olthoi Swarm Gardener!", "Combat", EnemyCombat) }, + new[] { L("Bob tells you, \"You evaded my question\"", "Chat", Tell) }), + new("combat.evaded_you", "Combat", "Evaded your attack", + "Drudge Slinker evaded your attack.", + ChatMatchMode.EndsWith, " evaded your attack.", "chan:Combat", + new[] { L("Drudge Slinker evaded your attack.", "Combat", 22) }, + new[] { L("Bob says, \"it evaded your attack.\"", "Chat", Say) }), + new("combat.damage_taken", "Combat", "Damage you take", + "Tusker Guard grazes your foot for 4 points of bludgeoning damage! (critical hits too)", + ChatMatchMode.Regex, @"^(?:Critical hit! )?(?!You )\S.* (?:you|your [a-z ]+) for \d+ points? of ", "type:21", + new[] { L("Tusker Guard grazes your foot for 4 points of bludgeoning damage!", "Combat", EnemyCombat), + L("Critical hit! Olthoi Swarm Nymph nicks your head for 21 points of piercing damage!", "Combat", EnemyCombat), + L("Olthoi Swarm Gardener blisters your lower leg for 1 point of acid damage!", "Combat", EnemyCombat) }, + new[] { L("You evaded Tusker Guard!", "Combat", EnemyCombat), + L("Bob says, \"it hit your head for 5 points of damage\"", "Chat", Say) }), + + // ── Notices ───────────────────────────────────────────────────── + new("notice.busy", "Notices", "You're too busy", + "You're too busy!", + ChatMatchMode.Regex, "^You're too busy!$", "type:26", + new[] { L("You're too busy!", "Other", Notice) }, + new[] { L("You're too busy! (and other words)", "Other", Notice) }), + new("notice.pk_battle", "Notices", "Recent PK battle", + "You have been involved in a player killer battle too recently to do that! (and the same about a target)", + ChatMatchMode.Contains, "involved in a player killer battle too recently", "", + new[] { L("You have been involved in a player killer battle too recently to do that!", "Other", Notice), + L("Bob has been involved in a player killer battle too recently to do that!", "Combat", Magic) }, + new[] { L("You have been involved in a fight", "Other", Notice) }), + + // ── Social ────────────────────────────────────────────────────── + new("social.emotes", "Social", "Emotes", + "Every emote line (Bob waves.), yours included.", + ChatMatchMode.Regex, ".", "type:12", + new[] { L("Bob waves.", "Chat", Emote) }, + new[] { L("Bob says, \"waves\"", "Chat", Say) }), + + // ── Channels ──────────────────────────────────────────────────── + new("chan.general", "Channels", "General channel", + "[General] lines.", + ChatMatchMode.StartsWith, "[General]", "", + new[] { L("[General] Aja says, \"lol\"", "Other", ServerChannel), L("[General] Bob says, \"hi\"", "Channels", 8) }, + new[] { L("Bob says, \"[General] is quiet\"", "Chat", Say) }), + new("chan.trade", "Channels", "Trade channel", + "[Trade] lines (buying and selling spam).", + ChatMatchMode.StartsWith, "[Trade]", "", + new[] { L("[Trade] Bob says, \"WTS Black Opal\"", "Other", ServerChannel) }, + new[] { L("Bob tells you, \"[Trade] is spammy\"", "Chat", Tell) }), + new("chan.lfg", "Channels", "LFG channel", + "[LFG] lines.", + ChatMatchMode.StartsWith, "[LFG]", "", + new[] { L("[LFG] Bob says, \"LF tank for the Graveyard\"", "Other", ServerChannel) }, + Array.Empty<(string, string, int)>()), + }; + + public static ChatFilterPreset? Get(string id) + { + foreach (ChatFilterPreset p in All) + if (string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase)) return p; + return null; + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatRuleMatching.cs b/src/RynthCore.Engine/UI/Data/ChatRuleMatching.cs new file mode 100644 index 0000000..d2b4109 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatRuleMatching.cs @@ -0,0 +1,113 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatRuleMatching.cs +// How a RynthChat rule's pattern is read (2026-10-05; idea from Silentkelpie, +// rynth PR #1). A rule was always a case-insensitive regex. It can now also be +// plain text: Contains, Starts with or Ends with, any case, nothing special +// about . ( * " and the like. Plain text is escaped into a regex here, so the +// router (ChatData.cs) runs every rule the same way, with the same timeout. +// +// Backward compatible: a rule saved without a "mode" is a Regex rule and is +// compiled exactly as before (the pattern untouched, the same options), and a +// Regex rule is saved without a "mode", so its JSON doesn't change either. +// +// No engine state here: the rule editor, the settings code and +// tools/ChatFilterTests all use it. +// ============================================================================ + +using System; +using System.Text.RegularExpressions; + +namespace RynthCore.Engine.UI.Data; + +/// How a rule's pattern is matched against a line's text. +internal enum ChatMatchMode +{ + /// A case-insensitive regex (every rule before 2026-10-05). + Regex, + /// The text anywhere in the line. + Contains, + /// The line starts with the text. + StartsWith, + /// The line ends with the text (trailing spaces on either side don't count). + EndsWith, +} + +internal static class ChatRuleMatching +{ + /// The options every rule is compiled with (as before match modes). + public const RegexOptions Options = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant; + + /// Picker labels, in enum order. + public static readonly string[] Labels = { "Regex", "Contains", "Starts with", "Ends with" }; + + public static string Label(ChatMatchMode mode) => Labels[(int)mode]; + + /// + /// The regex a rule runs. Regex mode: the pattern as typed. Plain text: escaped, anchored + /// for Starts with / Ends with. Null when the rule matches nothing (an empty pattern, or + /// plain text that is only spaces). + /// + public static string? ToRegex(ChatMatchMode mode, string? pattern) + { + pattern ??= ""; + if (mode == ChatMatchMode.Regex) return pattern.Length == 0 ? null : pattern; + if (pattern.Trim().Length == 0) return null; + return mode switch + { + ChatMatchMode.StartsWith => "^" + Regex.Escape(pattern.TrimStart()), + ChatMatchMode.EndsWith => Regex.Escape(pattern.TrimEnd()) + @"\s*$", + _ => Regex.Escape(pattern), + }; + } + + /// Compiles a rule; null with set when the regex is bad, + /// null with no error when it matches nothing (see ). + public static Regex? Compile(ChatMatchMode mode, string? pattern, int timeoutMs, out string? error) + { + error = null; + string? expr = ToRegex(mode, pattern); + if (expr == null) return null; + try { return new Regex(expr, Options, TimeSpan.FromMilliseconds(timeoutMs)); } + catch (ArgumentException ex) { error = ex.Message; return null; } + } + + /// The "mode" a rule's JSON carries: absent (an older file or a Regex rule) is Regex. + public static ChatMatchMode Parse(string? json) => (json ?? "").Trim().ToLowerInvariant() switch + { + "contains" => ChatMatchMode.Contains, + "startswith" or "starts" or "starts with" => ChatMatchMode.StartsWith, + "endswith" or "ends" or "ends with" => ChatMatchMode.EndsWith, + _ => ChatMatchMode.Regex, + }; + + /// What a rule saves as "mode": nothing for Regex, so a Regex rule's JSON is as before. + public static string? ToJson(ChatMatchMode mode) => mode switch + { + ChatMatchMode.Contains => "contains", + ChatMatchMode.StartsWith => "startswith", + ChatMatchMode.EndsWith => "endswith", + _ => null, + }; + + /// + /// A rule's When: "" any line, "chan:Combat" one channel tab, "type:3" one ChatMessageType. + /// Anything else reads as any line. Channel is null and Type -1 when not set. + /// + public static (string? Channel, int Type) ParseWhen(string? raw) + { + raw = (raw ?? "").Trim(); + if (raw.StartsWith("chan:", StringComparison.OrdinalIgnoreCase) && raw.Length > 5) + return (raw[5..], -1); + if (raw.StartsWith("type:", StringComparison.OrdinalIgnoreCase) && int.TryParse(raw[5..], out int t) && t >= 0) + return (null, t); + return (null, -1); + } + + /// Does a line from with pass the When? + public static bool WhenMatches(string? channel, int type, string lineChannel, int chatType) + { + if (channel != null) return string.Equals(channel, lineChannel, StringComparison.OrdinalIgnoreCase); + if (type >= 0) return type == chatType; + return true; + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs new file mode 100644 index 0000000..54856b9 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs @@ -0,0 +1,80 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatSettingsDto.cs +// RynthChat's JSON: the scrollback lines the plugin hands over, the settings +// file (rynthchat_settings.json) and the rule editor's Export / Import. Moved +// out of ChatData.cs (2026-10-05) so tools/ChatFilterTests can load and save +// rules with the real serializer. +// ============================================================================ + +using System.Text.Json.Serialization; + +namespace RynthCore.Engine.UI.Data; + +// JsonSerializerContext must be at namespace scope (not nested) for source generation. +internal sealed class RynthChatLineDto +{ + [JsonPropertyName("seq")] public ulong Seq { get; set; } + [JsonPropertyName("ts")] public string Ts { get; set; } = ""; + [JsonPropertyName("chan")] public string Chan { get; set; } = ""; + /// ChatMessageType; RynthChat before 0.2.0 doesn't send it. + [JsonPropertyName("type")] public int Type { get; set; } = -1; + [JsonPropertyName("sender")] public string? Sender { get; set; } + [JsonPropertyName("text")] public string Text { get; set; } = ""; +} + +// Property names match the legacy hand-written JSON so existing settings load. +internal sealed class RynthChatFilterDto +{ + [JsonPropertyName("pattern")] public string? Pattern { get; set; } + [JsonPropertyName("tab")] public string? Tab { get; set; } + [JsonPropertyName("enabled")] public bool Enabled { get; set; } = true; + // Version 2: + /// "move" | "copy" | "hide" | "color"; absent in version 1 (see ChatModel.FromDto). + [JsonPropertyName("action")] public string? Action { get; set; } + /// "" / absent: any line; "chan:Combat"; "type:3". + [JsonPropertyName("when")] public string? When { get; set; } + /// "line" | "match"; absent: no colour. + [JsonPropertyName("colorMode")] public string? ColorMode { get; set; } + /// "#RRGGBB". + [JsonPropertyName("color")] public string? Color { get; set; } + // 2026-10-05: + /// "contains" | "startswith" | "endswith"; absent: a regex (ChatRuleMatching). + [JsonPropertyName("mode")] public string? Mode { get; set; } +} + +internal sealed class RynthChatSettingsDto +{ + /// Absent (0) in version-1 files. + [JsonPropertyName("version")] public int Version { get; set; } + [JsonPropertyName("fontSize")] public double FontSize { get; set; } = 10; + [JsonPropertyName("backgroundAlpha")] public int BackgroundAlpha { get; set; } = 0xF2; + [JsonPropertyName("autoScroll")] public bool AutoScroll { get; set; } = true; + [JsonPropertyName("suppressChat")] public bool SuppressChat { get; set; } + [JsonPropertyName("logEnabled")] public bool LogEnabled { get; set; } + // Chat's own Ctrl-gated click-through, like RadarPanel's (2026-09-02). + [JsonPropertyName("ctrlGatedClickThrough")] public bool CtrlGatedClickThrough { get; set; } + [JsonPropertyName("activeChannel")] public string? ActiveChannel { get; set; } + [JsonPropertyName("showTimestamps")] public bool ShowTimestamps { get; set; } = true; + [JsonPropertyName("mentionHighlight")] public bool MentionHighlight { get; set; } = true; + [JsonPropertyName("mentionSound")] public bool MentionSound { get; set; } + [JsonPropertyName("mentionWords")] public string? MentionWords { get; set; } + [JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; } + [JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; } +} + +/// Export / import on the clipboard (the rule editor's Export and Import). +internal sealed class RynthChatRuleSetDto +{ + public const string FormatName = "rynthchat-rules/2"; + [JsonPropertyName("format")] public string? Format { get; set; } + [JsonPropertyName("tabs")] public string[]? Tabs { get; set; } + [JsonPropertyName("rules")] public RynthChatFilterDto[]? Rules { get; set; } +} + +[JsonSerializable(typeof(RynthChatLineDto[]))] +[JsonSerializable(typeof(RynthChatLineDto))] +[JsonSerializable(typeof(RynthChatSettingsDto))] +[JsonSerializable(typeof(RynthChatRuleSetDto))] +[JsonSerializable(typeof(RynthChatFilterDto[]))] +[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = false, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +internal partial class RynthChatJsonContext : JsonSerializerContext { } diff --git a/src/RynthCore.Engine/UI/Data/ItemHudModel.cs b/src/RynthCore.Engine/UI/Data/ItemHudModel.cs new file mode 100644 index 0000000..b6fb96b --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ItemHudModel.cs @@ -0,0 +1,290 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ItemHudModel.cs +// The pure half of the Item Count and Mini Remote panels (ItemCountFace, +// MiniRemoteFace): what one character keeps, the item_huds.txt format, the +// carried count and which carried item a remote slot means. No engine calls, +// no I/O (ItemHudStore does that), so tools/ItemHudTests compiles this file. +// +// item_huds.txt (one section per character, "/"): +// # comment lines +// [Aelrynth/Drakkon] +// count=Mana Scarab +// count=Prismatic Taper +// slots=8 +// slot=0|0x80123456|Healing Kit +// slot=3|0x8012ABCD|Stamina Elixir +// Lines this version doesn't know are kept where they were. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace RynthCore.Engine.UI.Data; + +/// An item a Mini Remote slot uses: its id when set, and its name to find a new stack by. +internal sealed record RemoteSlot(uint Id, string Name); + +/// A carried item as the panels see it (from InventoryModel's view). +internal readonly record struct HudItem(uint Id, string Name, int Stack); + +/// One character's Item Count list and Mini Remote slots. Immutable. +internal sealed class ItemHudCharacter +{ + public const int MaxCounts = 30; + public const int MinSlots = 4, MaxSlots = 24, DefaultSlots = 8; + public const int MaxNameLength = 64; + + public static readonly ItemHudCharacter Empty = new(Array.Empty(), new RemoteSlot?[DefaultSlots], Array.Empty()); + + public ItemHudCharacter(string[] counts, RemoteSlot?[] slots, string[] other) + { + Counts = counts; + Slots = slots; + Other = other; + } + + /// Item names on the Item Count list, in the order added. + public string[] Counts { get; } + /// The remote's slots (null = empty); the length is the slot count. + public RemoteSlot?[] Slots { get; } + /// Lines of this section the file had that this version doesn't know. + public string[] Other { get; } + + public bool HasCount(string name) => IndexOfCount(name) >= 0; + + public int IndexOfCount(string name) + { + for (int i = 0; i < Counts.Length; i++) + if (string.Equals(Counts[i], name, StringComparison.OrdinalIgnoreCase)) return i; + return -1; + } + + public static string Clean(string? name) + { + string s = (name ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Replace('|', ' ').Trim(); + return s.Length > MaxNameLength ? s[..MaxNameLength] : s; + } + + /// Adds a name (trimmed; no duplicates, any case). Same instance when nothing changes. + public ItemHudCharacter WithCount(string name, out string message) + { + name = Clean(name); + if (name.Length == 0) { message = "Type an item name first."; return this; } + if (HasCount(name)) { message = $"\"{name}\" is already on the list."; return this; } + if (Counts.Length >= MaxCounts) { message = $"The list is full ({MaxCounts} items)."; return this; } + var next = new string[Counts.Length + 1]; + Array.Copy(Counts, next, Counts.Length); + next[^1] = name; + message = $"Counting \"{name}\"."; + return new ItemHudCharacter(next, Slots, Other); + } + + public ItemHudCharacter WithoutCount(int index) + { + if (index < 0 || index >= Counts.Length) return this; + var next = new string[Counts.Length - 1]; + Array.Copy(Counts, 0, next, 0, index); + Array.Copy(Counts, index + 1, next, index, Counts.Length - index - 1); + return new ItemHudCharacter(next, Slots, Other); + } + + public ItemHudCharacter WithSlot(int index, RemoteSlot? slot) + { + if (index < 0 || index >= Slots.Length) return this; + var next = (RemoteSlot?[])Slots.Clone(); + next[index] = slot == null ? null : slot with { Name = Clean(slot.Name) }; + return new ItemHudCharacter(Counts, next, Other); + } + + /// More or fewer slots (clamped); slots past the new end are dropped. + public ItemHudCharacter WithSlotCount(int count) + { + count = Math.Clamp(count, MinSlots, MaxSlots); + if (count == Slots.Length) return this; + var next = new RemoteSlot?[count]; + Array.Copy(Slots, next, Math.Min(count, Slots.Length)); + return new ItemHudCharacter(Counts, next, Other); + } +} + +/// Counting and slot lookup over the carried items. +internal static class ItemHudMath +{ + /// + /// How many of the character carries: every stack with that name + /// (any case), whole stacks summed; a single item counts 1. + /// + public static long Count(IReadOnlyList items, string name) + { + long total = 0; + foreach (HudItem it in items) + if (string.Equals(it.Name, name, StringComparison.OrdinalIgnoreCase)) + total += Math.Max(1, it.Stack); + return total; + } + + /// + /// The carried item a slot uses: the same object when it is still carried, else a stack + /// with the slot's name (the largest; a stack that merged or split gets a new id). 0 when none. + /// + public static uint Resolve(IReadOnlyList items, RemoteSlot slot) + { + uint byName = 0; + int best = -1; + foreach (HudItem it in items) + { + if (slot.Id != 0 && it.Id == slot.Id) return it.Id; + if (slot.Name.Length > 0 && string.Equals(it.Name, slot.Name, StringComparison.OrdinalIgnoreCase) && it.Stack > best) + { + best = it.Stack; + byName = it.Id; + } + } + return byName; + } + + /// The carried item with this id, if any. + public static bool TryFind(IReadOnlyList items, uint id, out HudItem item) + { + foreach (HudItem it in items) + if (it.Id == id) { item = it; return true; } + item = default; + return false; + } +} + +/// The item_huds.txt format: sections per character key, unknown lines kept. +internal static class ItemHudFile +{ + public const string Header = "# RynthCore Item Count and Mini Remote - auto-generated, hand-edits OK. /rc itemcount, /rc remote in game."; + + public sealed class Contents + { + /// Per character key (case-insensitive), in file order. + public readonly Dictionary Characters = new(StringComparer.OrdinalIgnoreCase); + public readonly List Order = new(); + /// Lines before the first section that aren't the header or comments we write. + public readonly List Preamble = new(); + + public ItemHudCharacter For(string key) => Characters.TryGetValue(key, out ItemHudCharacter? c) ? c : ItemHudCharacter.Empty; + + public void Set(string key, ItemHudCharacter c) + { + if (!Characters.ContainsKey(key)) Order.Add(key); + Characters[key] = c; + } + } + + public static Contents Parse(IEnumerable lines) + { + var result = new Contents(); + string? key = null; + List? counts = null, other = null; + RemoteSlot?[]? slots = null; + + void Flush() + { + if (key == null) return; + result.Set(key, new ItemHudCharacter(counts!.ToArray(), slots!, other!.ToArray())); + } + + foreach (string raw in lines) + { + string line = raw.TrimEnd('\r', '\n'); + string t = line.Trim(); + if (t.Length > 2 && t[0] == '[' && t[^1] == ']') + { + Flush(); + key = t[1..^1].Trim(); + counts = new List(); + other = new List(); + slots = new RemoteSlot?[ItemHudCharacter.DefaultSlots]; + continue; + } + if (key == null) + { + if (t.Length > 0 && !t.StartsWith('#')) result.Preamble.Add(line); + continue; + } + int eq = t.IndexOf('='); + string name = eq > 0 ? t[..eq].Trim() : string.Empty; + string val = eq > 0 ? t[(eq + 1)..] : string.Empty; + switch (name) + { + case "count": + { + string c = ItemHudCharacter.Clean(val); + if (c.Length > 0 && counts!.Count < ItemHudCharacter.MaxCounts && !counts.Exists(x => string.Equals(x, c, StringComparison.OrdinalIgnoreCase))) + counts.Add(c); + break; + } + case "slots": + if (int.TryParse(val.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) + { + n = Math.Clamp(n, ItemHudCharacter.MinSlots, ItemHudCharacter.MaxSlots); + var resized = new RemoteSlot?[n]; + Array.Copy(slots!, resized, Math.Min(n, slots!.Length)); + slots = resized; + } + break; + case "slot": + { + // slot=|<0xid>| + string[] f = val.Split('|', 3); + if (f.Length == 3 && int.TryParse(f[0].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int i) + && i >= 0 && i < ItemHudCharacter.MaxSlots && TryParseId(f[1], out uint id)) + { + if (i >= slots!.Length) + { + var grown = new RemoteSlot?[i + 1]; + Array.Copy(slots, grown, slots.Length); + slots = grown; + } + string sn = ItemHudCharacter.Clean(f[2]); + if (id != 0 || sn.Length > 0) slots[i] = new RemoteSlot(id, sn); + } + else other!.Add(line); + break; + } + default: + if (t.Length > 0 && !t.StartsWith('#')) other!.Add(line); + break; + } + } + Flush(); + return result; + } + + private static bool TryParseId(string s, out uint id) + { + s = s.Trim(); + if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + return uint.TryParse(s.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id); + return uint.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out id); + } + + public static string Write(Contents c) + { + var sb = new StringBuilder(); + sb.Append(Header).Append('\n'); + foreach (string p in c.Preamble) sb.Append(p).Append('\n'); + foreach (string key in c.Order) + { + ItemHudCharacter ch = c.Characters[key]; + sb.Append('\n').Append('[').Append(key).Append("]\n"); + foreach (string n in ch.Counts) sb.Append("count=").Append(n).Append('\n'); + sb.Append("slots=").Append(ch.Slots.Length.ToString(CultureInfo.InvariantCulture)).Append('\n'); + for (int i = 0; i < ch.Slots.Length; i++) + { + RemoteSlot? s = ch.Slots[i]; + if (s == null) continue; + sb.Append("slot=").Append(i.ToString(CultureInfo.InvariantCulture)).Append("|0x") + .Append(s.Id.ToString("X8", CultureInfo.InvariantCulture)).Append('|').Append(s.Name).Append('\n'); + } + foreach (string o in ch.Other) sb.Append(o).Append('\n'); + } + return sb.ToString(); + } +} diff --git a/src/RynthCore.Engine/UI/Data/ItemHudStore.cs b/src/RynthCore.Engine/UI/Data/ItemHudStore.cs new file mode 100644 index 0000000..01d15ed --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ItemHudStore.cs @@ -0,0 +1,168 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ItemHudStore.cs +// item_huds.txt for the Item Count and Mini Remote panels, per character +// ("/", the key the video patch uses). The format and the +// edits are ItemHudModel.cs (pure); this file holds the loaded contents and +// does the file I/O on UiBackgroundWriter, never on AC's render thread. +// +// Threads: the faces read and edit from AC's render thread. Reads are a +// volatile snapshot for the current character (a lock only when the character +// changes); edits take the lock briefly and queue the save. +// ============================================================================ + +using System; +using System.IO; +using System.Threading; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.UI.Data; + +internal static class ItemHudStore +{ + private static readonly object Sync = new(); + private static ItemHudFile.Contents? _file; // under Sync + private static volatile bool _loaded; + private static bool _loadQueued; + + private sealed record Snap(string Key, ItemHudCharacter Data); + private static Snap? _snap; + + private static string FilePath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "item_huds.txt"); + + public static bool Loaded => _loaded; + + /// A character is logged in (its name is known): lists are kept per character. + public static bool HasCharacter => SessionStateRegistry.LastCharacterName.Length > 0; + + public static string CharacterKey => + D3D9.VideoPatchPolicy.CharacterKey(SessionStateRegistry.LastServerName, SessionStateRegistry.LastCharacterName); + + /// Queues the one-time read off the calling thread. Any thread; cheap after the first call. + public static void EnsureLoadQueued() + { + if (_loaded) return; + lock (Sync) + { + if (_loadQueued) return; + _loadQueued = true; + } + UiBackgroundWriter.Enqueue("item huds (load)", LoadNow); + } + + private static void LoadNow() + { + ItemHudFile.Contents contents; + try + { + string path = FilePath; + contents = File.Exists(path) ? ItemHudFile.Parse(File.ReadAllLines(path)) : new ItemHudFile.Contents(); + } + catch (Exception ex) + { + RynthLog.UI($"ItemHud: reading item_huds.txt failed - {ex.GetType().Name}: {ex.Message}"); + contents = new ItemHudFile.Contents(); + } + lock (Sync) + { + _file = contents; + Volatile.Write(ref _snap, null); + _loaded = true; + } + } + + /// The current character's lists (empty before the file is read). Any thread. + public static ItemHudCharacter Current + { + get + { + if (!_loaded) return ItemHudCharacter.Empty; + string key = CharacterKey; + Snap? s = Volatile.Read(ref _snap); + if (s != null && string.Equals(s.Key, key, StringComparison.OrdinalIgnoreCase)) return s.Data; + lock (Sync) + { + ItemHudCharacter d = _file?.For(key) ?? ItemHudCharacter.Empty; + Volatile.Write(ref _snap, new Snap(key, d)); + return d; + } + } + } + + /// + /// Applies an edit to the current character's lists and saves them. False (with the + /// reason) before the file is read or before a character is logged in. + /// + public static bool Update(Func edit, out string why) + { + if (!_loaded) { why = "Still reading the saved lists..."; return false; } + if (!HasCharacter) { why = "Log in a character first: the lists are kept per character."; return false; } + string key = CharacterKey; + string text; + lock (Sync) + { + _file ??= new ItemHudFile.Contents(); + ItemHudCharacter cur = _file.For(key); + ItemHudCharacter next = edit(cur); + if (ReferenceEquals(next, cur)) { why = string.Empty; return true; } + _file.Set(key, next); + Volatile.Write(ref _snap, new Snap(key, next)); + text = ItemHudFile.Write(_file); + } + why = string.Empty; + UiBackgroundWriter.Enqueue("item huds", () => SaveNow(text)); + return true; + } + + private static void SaveNow(string text) + { + try + { + string path = FilePath; + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(path, text); + } + catch (Exception ex) + { + RynthLog.UI($"ItemHud: writing item_huds.txt failed - {ex.GetType().Name}: {ex.Message}"); + } + } +} + +/// +/// The character's carried items (packs and worn) as s, rebuilt only when +/// InventoryModel publishes a new view (at most a few times a second). One per face; AC's render thread. +/// +internal sealed class HudItemCache +{ + private InventoryView? _view; + private HudItem[] _items = Array.Empty(); + + /// Changes whenever the list is rebuilt. + public int Version { get; private set; } + + public HudItem[] Get(InventoryView view) + { + if (ReferenceEquals(view, _view)) return _items; + _view = view; + int n = view.Worn.Length; + foreach (InventoryPack p in view.Packs) n += p.Items.Length; + var list = new HudItem[n]; + int i = 0; + foreach (InventoryPack p in view.Packs) + foreach (InventoryItem it in p.Items) list[i++] = new HudItem(it.Id, it.Name, it.Stack); + foreach (InventoryItem it in view.Worn) list[i++] = new HudItem(it.Id, it.Name, it.Stack); + _items = list; + Version++; + return _items; + } + + /// The id of a carried item with this name (for its icon), 0 when none. + public uint IdOf(string name) + { + foreach (HudItem it in _items) + if (string.Equals(it.Name, name, StringComparison.OrdinalIgnoreCase)) return it.Id; + return 0; + } +} diff --git a/src/RynthCore.Engine/UI/Data/MetaData.cs b/src/RynthCore.Engine/UI/Data/MetaData.cs index ee3c1b4..5a5bd3b 100644 --- a/src/RynthCore.Engine/UI/Data/MetaData.cs +++ b/src/RynthCore.Engine/UI/Data/MetaData.cs @@ -23,31 +23,6 @@ using RynthCore.Engine.Plugins; namespace RynthCore.Engine.UI.Data; -internal sealed class MetaRuleDto -{ - public string State { get; set; } = "Default"; - public int Condition { get; set; } - public string ConditionData { get; set; } = string.Empty; - public int Action { get; set; } - public string ActionData { get; set; } = string.Empty; - public List Children { get; set; } = new(); - public List ActionChildren { get; set; } = new(); - public bool Enabled { get; set; } = true; - public long LastFiredMs { get; set; } = 99999; - - public MetaRuleDto Clone() - { - var r = new MetaRuleDto - { - State = State, Condition = Condition, ConditionData = ConditionData, - Action = Action, ActionData = ActionData, Enabled = Enabled, LastFiredMs = LastFiredMs, - }; - foreach (MetaRuleDto c in Children) r.Children.Add(c.Clone()); - foreach (MetaRuleDto a in ActionChildren) r.ActionChildren.Add(a.Clone()); - return r; - } -} - internal sealed class MetaFile { public string Path { get; set; } = string.Empty; @@ -226,12 +201,34 @@ internal static unsafe class MetaCommands public static void Simple(string op, int index = -1, string value = "", string path = "") => Send(new MetaCmd { Op = op, Index = index, Value = value, Path = path }); + + /// + /// Copies to (overwriting it) on the pump thread, + /// queued like a command, so it runs before any command sent after it reaches the plugin: the + /// copy is the file as it was before that save. Nothing happens when the file doesn't exist. + /// + public static void Backup(string file, string backup) + { + UiDataHub.Post("Meta backup", () => + { + try + { + if (!System.IO.File.Exists(file)) return; + System.IO.File.Copy(file, backup, overwrite: true); + RynthLog.UI($"Meta: backed up {System.IO.Path.GetFileName(file)} to {System.IO.Path.GetFileName(backup)} before the first save"); + } + catch (Exception ex) + { + RynthLog.UI($"Meta: backup of {file} failed: {ex.GetType().Name}: {ex.Message}"); + } + }); + } } /// Names, hints and .af keywords shared by the Meta faces (mirror RynthSuite's MetaSchema). internal static class MetaVocabulary { - public const string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + public static readonly string MetaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles"); public static readonly string[] ConditionNames = { @@ -246,6 +243,7 @@ internal static class MetaVocabulary "Chat Message Capture", "Navroute Empty", "Main Health <=", "Main Health % >=", "Main Mana <=", "Main Mana % >=", "Main Stam <=", "Vitae % >=", + "No Kills Within Minutes", // RynthAi only (2026-10-06) }; public static readonly string[] ConditionHints = @@ -260,6 +258,7 @@ internal static class MetaVocabulary "Percentage (e.g. 250)", "Distance (e.g. 10)", "Expression", "Regex pattern", "", "", "", "", "", "", "Vitae % (e.g. 5)", + "Minutes without a kill (e.g. 5 or 2.5)", }; public static readonly string[] ActionNames = @@ -294,6 +293,7 @@ internal static class MetaVocabulary "ChatCapture", "NavEmpty", "MainHealthLE", "MainHealthPHE", "MainManaLE", "MainManaPHE", "MainStamLE", "VitaePHE", + "NoKillsInMins", }; public static readonly string[] ActionKeywords = diff --git a/src/RynthCore.Engine/UI/Data/MetaEditing.cs b/src/RynthCore.Engine/UI/Data/MetaEditing.cs new file mode 100644 index 0000000..2102c3f --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/MetaEditing.cs @@ -0,0 +1,261 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/MetaEditing.cs +// The Meta editor's rules that don't need ImGui (2026-10-05 clean-up), kept +// here so Tools/MetaEditTests can check them offline: +// +// MetaStateName what a typed "+ New state..." name must be +// MetaAutosave when an edit is saved (debounce; never mid-typing) +// MetaBackupPlan the one .bak per editing session, before the first save +// MetaRuleEdit placeholder rule for a new state, Add condition / action, +// finding the edited rule again in a newer snapshot +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Data; + +/// +/// A new meta state's name. RynthAi matches state names ignoring case (MetaManager), so +/// "combat" next to "Combat" would be the same state: refused as a duplicate. The .af file writes +/// STATE: {name} and SetState {name}, so braces can't be in a name. +/// +internal static class MetaStateName +{ + public const int MaxLength = 48; + + /// Null when (trimmed into ) can be a new + /// state, else a short reason to show under the box. + public static string? Problem(string? typed, IEnumerable existing, out string name) + { + name = (typed ?? string.Empty).Trim(); + if (name.Length == 0) return "Type a name for the new state."; + if (name.Length > MaxLength) return $"At most {MaxLength} characters."; + foreach (char c in name) + { + if (c is '{' or '}') return "A state name can't contain { or }."; + if (char.IsControl(c)) return "A state name can't contain tabs or line breaks."; + } + foreach (string s in existing) + if (string.Equals(s, name, StringComparison.OrdinalIgnoreCase)) + return $"There is already a state called '{s}'."; + return null; + } +} + +/// +/// When the rule being edited is saved. Every change restarts a clock; +/// the change is saved once the clock runs out, but never while a text box is being typed in, so +/// a half-typed chat command or regex is not saved (and, on a running meta, can't fire) before the +/// user leaves the box. Back, closing the panel and switching metas save at once (). +/// +internal sealed class MetaAutosave +{ + public const double DebounceMs = 750; + + private bool _dirty; + private double _lastChangeMs; + + /// An edit that is not saved yet. + public bool Dirty => _dirty; + + public void Changed(double nowMs) + { + _dirty = true; + _lastChangeMs = nowMs; + } + + /// True when the pending edit should be saved now. + public bool Due(double nowMs, bool typing) => _dirty && !typing && nowMs - _lastChangeMs >= DebounceMs; + + /// Takes the pending edit for saving (a due one, or a flush). True when there was one. + public bool Take() + { + bool had = _dirty; + _dirty = false; + return had; + } + + /// Drops the pending edit (the rule was deleted or the draft discarded). + public void Clear() => _dirty = false; +} + +/// +/// One backup per meta file per editing session (the panel being open): before the first save +/// that would rewrite a file this session, copy it to <file>.bak (overwriting the last +/// session's). RynthAi saves a .met meta as the .af beside it (the .met is never written), so the +/// file to back up is that .af, if it exists yet. +/// +internal sealed class MetaBackupPlan +{ + private readonly HashSet _done = new(StringComparer.OrdinalIgnoreCase); + + /// The panel was opened: the next save of each file backs it up again. + public void NewSession() => _done.Clear(); + + /// The file a save to writes, and its backup, when this session + /// hasn't backed it up yet; null otherwise (or when the meta has no file). + public (string File, string Backup)? Before(string? metaPath) + { + if (string.IsNullOrWhiteSpace(metaPath)) return null; + string file = WrittenFile(metaPath); + if (!_done.Add(file)) return null; + return (file, BackupOf(file)); + } + + /// The file RynthAi writes when it saves the meta loaded from . + public static string WrittenFile(string metaPath) => + metaPath.EndsWith(".met", StringComparison.OrdinalIgnoreCase) ? System.IO.Path.ChangeExtension(metaPath, ".af") : metaPath; + + public static string BackupOf(string file) => file + ".bak"; +} + +/// Rule edits the editor makes. +internal static class MetaRuleEdit +{ + public const int Never = 0, All = 2, Any = 3, Not = 20; + public const int NoAction = 0, DoAll = 4; + /// "No Kills Within Minutes" (RynthAi MetaConditionType.NoKillsWithinMinutes, .af NoKillsInMins). + public const int NoKillsWithinMinutes = 35; + + /// The minutes box's tooltip: what the condition means, or why the typed value never holds. + public static string NoKillsTooltip(string data) + { + const string what = "True once you haven't killed anything for this many minutes (decimals allowed: 0.5 = 30 s).\n" + + "Before your first kill it counts from the macro start (or login). Only your own kills count.\n" + + "RynthAi only: VTank / metaf can't read it. Same clock as secondssincelastkill[]."; + string t = data.Trim(); + if (t.Length == 0) return what; + return MinutesOk(t) ? what : $"'{t}' isn't a number of minutes: this condition never holds.\n\n{what}"; + } + + /// The plugin's reading of the minutes (KillClock.TryParseMinutes): a number, not negative; + /// a comma decimal is accepted. + public static bool MinutesOk(string data) => + double.TryParse(data.Trim().Replace(',', '.'), System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out double m) + && !double.IsNaN(m) && !double.IsInfinity(m) && m >= 0; + + /// The rule a new state starts with: Never -> None, which never fires. A state exists only + /// while a rule uses it (RynthAi lists the states its rules name, and the .af file writes one + /// STATE: block per state that has rules), so this rule is what keeps an empty state. + public static MetaRuleDto Placeholder(string state) => new() { State = state, Condition = Never, Action = NoAction }; + + 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; + + /// 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). + public static bool ConditionTakesData(int condition) => + condition is not (Never or 1 or 7 or 8 or 9 or 14 or 18 or 19 or 28 or All or Any or Not); + + /// False for actions with nothing to type: None, Return From Call, Clear Watchdog, + /// Destroy All Views (and DoAll, which has sub-actions). + public static bool ActionTakesData(int action) => action is not (NoAction or 6 or 10 or 15 or DoAll); + + /// + /// A new rule is added by autosave only once it is filled in: every condition and action that + /// takes a value has one, and every All / Any / Not / DoAll has something in it. Otherwise a + /// rule built condition-first ("Always", then the chat command) would be added, and on a running + /// meta fire and latch, before its command was typed. Back / close add it as it is. + /// + public static bool ReadyToAdd(MetaRuleDto r) => ConditionReady(r, 0) && ActionReady(r); + + private static bool ConditionReady(MetaRuleDto c, int depth) + { + if (c.Condition is All or Any or Not) + { + if (c.Children.Count == 0 || depth > 8) return false; + foreach (MetaRuleDto child in c.Children) + if (!ConditionReady(child, depth + 1)) return false; + return true; + } + return !ConditionTakesData(c.Condition) || c.ConditionData.Trim().Length > 0; + } + + private static bool ActionReady(MetaRuleDto a) + { + if (a.Action == DoAll) + { + if (a.ActionChildren.Count == 0) return false; + foreach (MetaRuleDto child in a.ActionChildren) + if (!ActionReady(child)) return false; + return true; + } + return !ActionTakesData(a.Action) || a.ActionData.Trim().Length > 0; + } + + /// A Not already has its one condition. + public static bool CanAddCondition(MetaRuleDto r) => r.Condition != Not || r.Children.Count == 0; + + /// + /// "+ Add" in the Conditions column: All / Any get one more sub-condition (Never until it is + /// picked, so a half-made rule can't fire); an empty Not gets its operand; any other condition + /// becomes the first of an All, followed by the new one. + /// + public static void AddCondition(MetaRuleDto r) + { + if (r.Condition is All or Any || (r.Condition == Not && r.Children.Count == 0)) + { + r.Children.Add(new MetaRuleDto { State = r.State, Condition = Never }); + return; + } + if (r.Condition == Not) return; + var first = new MetaRuleDto { State = r.State, Condition = r.Condition, ConditionData = r.ConditionData }; + r.Condition = All; + r.ConditionData = string.Empty; + r.Children.Clear(); + r.Children.Add(first); + r.Children.Add(new MetaRuleDto { State = r.State, Condition = Never }); + } + + /// "+ Add" in the Actions column: a DoAll gets one more sub-action (None until picked); + /// any other action becomes the first of a DoAll, followed by the new one. + public static void AddAction(MetaRuleDto r) + { + if (r.Action == DoAll) + { + r.ActionChildren.Add(new MetaRuleDto { State = r.State, Action = NoAction }); + return; + } + var first = new MetaRuleDto { State = r.State, Action = r.Action, ActionData = r.ActionData }; + r.Action = DoAll; + r.ActionData = string.Empty; + r.ActionChildren.Clear(); + r.ActionChildren.Add(first); + r.ActionChildren.Add(new MetaRuleDto { State = r.State, Action = NoAction }); + } + + /// Same state, condition, action, data, enabled flag and children (not LastFiredMs). + 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 + || !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) + return false; + for (int i = 0; i < a.Children.Count; i++) + if (!SameContent(a.Children[i], b.Children[i])) return false; + for (int i = 0; i < a.ActionChildren.Count; i++) + if (!SameContent(a.ActionChildren[i], b.ActionChildren[i])) return false; + return true; + } + + /// + /// Where the rule last saved as is in (a newer + /// snapshot): when it is still there, else the nearest rule with the same + /// content, else (the snapshot doesn't show the save yet). Commands address + /// rules by index, so a save must not land on a rule that moved into the old slot. + /// + public static int Locate(IReadOnlyList rules, MetaRuleDto lastSaved, int hint) + { + if (hint >= 0 && hint < rules.Count && SameContent(rules[hint], lastSaved)) return hint; + int best = -1; + for (int i = 0; i < rules.Count; i++) + if (SameContent(rules[i], lastSaved) && (best < 0 || Math.Abs(i - hint) < Math.Abs(best - hint))) + best = i; + return best >= 0 ? best : hint; + } +} diff --git a/src/RynthCore.Engine/UI/Data/MetaLocation.cs b/src/RynthCore.Engine/UI/Data/MetaLocation.cs new file mode 100644 index 0000000..a9bcf23 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/MetaLocation.cs @@ -0,0 +1,42 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/MetaLocation.cs +// The Meta editor's "Set current" text for Landblock == / Landcell == +// conditions (2026-10-05). Self-contained: RynthSuite's RynthAiHostTests +// link this file and check that RynthAi's MetaManager matches the text it +// writes against the same position. +// +// How RynthAi reads them (MetaManager.EvaluateCondition): +// Landblock == hex; a value above FFFF is shifted down 16 bits (metaf and +// VTank write the full 8 digits, "A9B40000"), then compared +// with cellId >> 16. +// Landcell == hex, compared with the whole cell id ("A9B4001C"). +// So "Set current" writes 8 upper-case hex digits, the form the field hints +// show: the landblock with its low word zeroed, the landcell as it is. +// ============================================================================ + +using System.Globalization; + +namespace RynthCore.Engine.UI.Data; + +internal static class MetaLocation +{ + /// Condition indexes (MetaVocabulary.ConditionNames) that take a position. + public const int LandblockCondition = 16, LandcellCondition = 17; + + /// True for Landblock == and Landcell ==. + public static bool TakesPosition(int condition) => condition is LandblockCondition or LandcellCondition; + + /// "A9B40000": the landblock of . + public static string LandblockText(uint cellId) => (cellId & 0xFFFF0000u).ToString("X8", CultureInfo.InvariantCulture); + + /// "A9B4001C": the whole cell id. + public static string LandcellText(uint cellId) => cellId.ToString("X8", CultureInfo.InvariantCulture); + + /// The text for at ; null for other conditions. + public static string? Text(int condition, uint cellId) => condition switch + { + LandblockCondition => LandblockText(cellId), + LandcellCondition => LandcellText(cellId), + _ => null, + }; +} diff --git a/src/RynthCore.Engine/UI/Data/MetaRuleDto.cs b/src/RynthCore.Engine/UI/Data/MetaRuleDto.cs new file mode 100644 index 0000000..520d548 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/MetaRuleDto.cs @@ -0,0 +1,36 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/MetaRuleDto.cs +// One meta rule as the Meta panel sees it (RynthPluginGetMetaJson's "rules", +// add_rule / update_rule's "rule"). Split out of MetaData.cs (2026-10-05) so +// the offline editor tests (Tools/MetaEditTests) can compile it without the +// plugin bridge. +// ============================================================================ + +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class MetaRuleDto +{ + public string State { get; set; } = "Default"; + public int Condition { get; set; } + public string ConditionData { get; set; } = string.Empty; + public int Action { get; set; } + public string ActionData { get; set; } = string.Empty; + public List Children { get; set; } = new(); + public List ActionChildren { get; set; } = new(); + public bool Enabled { get; set; } = true; + public long LastFiredMs { get; set; } = 99999; + + public MetaRuleDto Clone() + { + var r = new MetaRuleDto + { + State = State, Condition = Condition, ConditionData = ConditionData, + Action = Action, ActionData = ActionData, Enabled = Enabled, LastFiredMs = LastFiredMs, + }; + foreach (MetaRuleDto c in Children) r.Children.Add(c.Clone()); + foreach (MetaRuleDto a in ActionChildren) r.ActionChildren.Add(a.Clone()); + return r; + } +} diff --git a/src/RynthCore.Engine/UI/Data/RynthNavData.cs b/src/RynthCore.Engine/UI/Data/RynthNavData.cs index a495be1..04bbc51 100644 --- a/src/RynthCore.Engine/UI/Data/RynthNavData.cs +++ b/src/RynthCore.Engine/UI/Data/RynthNavData.cs @@ -106,6 +106,11 @@ internal sealed class RynthNavStatus // The Town Network (RynthNav 0.6.2+): townnet.json loaded or not, and why. public bool HasTownNet, TownNetLoaded; public string TownNetStatus = ""; + // Path markers and "save as nav route" (RynthNav 0.6.6+; HasMarkers / HasSave false on older plugins). + public bool HasMarkers, MarkersOn, MarkerLabels, MarkerGuide, MarkersShown; + public string MarkerStatus = ""; + public bool HasSave, CanSave, SaveBusy; + public string SaveFor = "", SaveName = "", SaveConflict = "", SaveLast = ""; public bool HasTies; public int Tie1Known = -1, Tie2Known = -1; public string TiePending = ""; @@ -274,6 +279,25 @@ internal sealed class RynthNavStatus s.TownNetLoaded = Int(info, "townNet") != 0; s.TownNetStatus = Str(info, "townNetStatus"); } + if (r.TryGetProperty("markers", out var mk) && mk.ValueKind == JsonValueKind.Object) + { + s.HasMarkers = true; + s.MarkersOn = Int(mk, "on") != 0; + s.MarkerLabels = Int(mk, "labels") != 0; + s.MarkerGuide = Int(mk, "guide") != 0; + s.MarkersShown = Int(mk, "shown") != 0; + s.MarkerStatus = Str(mk, "status"); + } + if (r.TryGetProperty("save", out var sv) && sv.ValueKind == JsonValueKind.Object) + { + s.HasSave = true; + s.CanSave = Int(sv, "can") != 0; + s.SaveBusy = Int(sv, "busy") != 0; + s.SaveFor = Str(sv, "for"); + s.SaveName = Str(sv, "name"); + s.SaveConflict = Str(sv, "conflict"); + s.SaveLast = Str(sv, "last"); + } string meshHere = !s.HasInfo ? (s.TileLoaded ? "loaded" : "not loaded") : s.TileHere == 1 ? "yes" : s.TileHere == 0 ? "no (no tile for this landblock)" : "not checked yet"; s.InfoHere = s.HasPose diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index b3f0ca2..f936c2f 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -132,6 +132,9 @@ internal sealed class RynthAiSettings public float NavHeightOffset { get; set; } = 0.05f; public float NavSlopeSink { get; set; } = 1.5f; public bool ShowTerrainPassability { get; set; } = true; + // Nav3D extras (RynthAi NavOverlay), both off by default: 0 off, 1 numbers, 2 numbers and names. + public int NavLabelMode { get; set; } + public bool NavGuideLine { get; set; } public bool OpenDoors { get; set; } public float OpenDoorRange { get; set; } = 5f; public bool AutoUnlockDoors { get; set; } @@ -183,6 +186,8 @@ internal sealed class RynthAiSettings // (default off). A RynthAi that predates them doesn't send them; on must not read as off. public bool LootOwnCorpse { get; set; } = true; public bool TravelToOwnCorpse { get; set; } + // Selecting an item prints /ra iteminfo (default on; an older RynthAi doesn't send it). + public bool ItemInfoOnSelect { get; set; } = true; public bool EnableAutostack { get; set; } = true; public bool ReadUnknownScrolls { get; set; } = true; // VTank's default public bool EnableCombineSalvage { get; set; } = true; @@ -304,7 +309,8 @@ internal static class SettingsSchema public const string NavPointReachTip = "How close to get to each nav point before moving on to the next, in yards. VTank calls it " + "Follow/Nav Min Distance (metas: FollowNavMin, or VTank's NavCloseStopRange). Follow stops this " + - "close to its leader, and the nav marker ring shows it. Dungeon doorways use at most 1 yd."; + "close to its leader, and the nav marker ring shows it. Dungeon doorways use at most 1 yd. Up to 2 yd, " + + "nav walks right up to each point before turning (tight dungeons); bigger values round corners."; // Also shown by the dashboard's Ranges slide-out (ImGui/Panels/RangesSlideOut.cs), which // edits these same rows (found by label with Find). @@ -331,6 +337,7 @@ internal static class SettingsSchema public static readonly string[] AttackHeights = { "Low", "Medium", "High" }; public static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; + public static readonly string[] NavLabelModes = { "Off", "Numbers", "Numbers and names" }; private static SettingRow Bool(string label, Func get, Action set, string? tip = null, Func? when = null, bool gates = false) => @@ -446,6 +453,19 @@ internal static class SettingsSchema Bool("Enable FPS Limit", s => s.EnableFPSLimit, (s, v) => s.EnableFPSLimit = v, gates: true), Int("Focused FPS", s => s.TargetFPSFocused, (s, v) => s.TargetFPSFocused = v, 10, 240, 1, when: s => s.EnableFPSLimit), Int("Background FPS", s => s.TargetFPSBackground, (s, v) => s.TargetFPSBackground = v, 5, 60, 1, when: s => s.EnableFPSLimit), + // Stored by the engine (D3D9/VideoPatch, %LOCALAPPDATA%\RynthCore\video_patch.txt, per + // character), not in the RynthAi profile, so the settings object is ignored here. + Combo("Video patch", D3D9.VideoPatchPolicy.ComboItems, _ => (int)D3D9.VideoPatch.Mode, + (_, v) => D3D9.VideoPatch.SetMode((D3D9.VideoPatchMode)Math.Clamp(v, 0, 3), save: true, "Settings"), + "Stop drawing the game to save CPU and GPU (game logic, the bot and the plugins keep running).\n" + + "World when unfocused: the 3D world isn't drawn while another window has the focus.\n" + + "World: the 3D world is never drawn; AC's windows and these panels still are.\n" + + "All: AC's windows aren't drawn either (this session only; /rc video off restores).\n" + + "Saved for this character. The phone live view shows what the client draws. Also: /rc video."), + Int(" Frame cap while patched", _ => D3D9.VideoPatch.FrameCapFps, (_, v) => D3D9.VideoPatch.SetFrameCap(v), 0, 60, 1, + "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 .", + when: _ => D3D9.VideoPatch.Mode != D3D9.VideoPatchMode.Off), 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."), @@ -613,6 +633,10 @@ internal static class SettingsSchema "Extra downward offset on slopes only, per unit of terrain steepness. 0 = off; flat ground is unaffected. ~1.5 cancels the float for a default-radius ring."), Bool("Show Terrain Passability", s => s.ShowTerrainPassability, (s, v) => s.ShowTerrainPassability = v, "Highlight impassable terrain triangles in red."), + Combo("Waypoint Labels", NavLabelModes, s => Math.Clamp(s.NavLabelMode, 0, NavLabelModes.Length - 1), (s, v) => s.NavLabelMode = v, + "Text over the route's waypoints within 60 yd. Numbers: each point's number (as in the Nav panel).\nNumbers and names: also checkpoints and jumps, and what happens at a point\n(recall, chat, pause, portal, NPC, vendor) above it."), + Bool("Guide Line", s => s.NavGuideLine, (s, v) => s.NavGuideLine = v, + "A line from your character to the waypoint nav is heading for."), Spacer(), Section("Doors"), Bool("Open Doors While Navigating", s => s.OpenDoors, (s, v) => s.OpenDoors = v, @@ -631,7 +655,7 @@ internal static class SettingsSchema Float("Sweep Detect Mult", s => s.NavSweepMult, (s, v) => s.NavSweepMult = v, 0.5f, 10f, 0.1f, "Closest-approach detection radius multiplier."), Float("Lookahead (yd)", s => s.NavLookaheadYards, (s, v) => s.NavLookaheadYards = MathF.Max(0f, v), 0f, 30f, 0.5f, - "Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off."), + "Within this distance of a waypoint, blend the aim point toward the next one to round corners. The nav point reach limits it: 2 yd per yard of reach over 1 yd (none up to a 2 yd reach). 0 = off."), Float("Turn Rate (deg/s)", s => s.NavTurnRateDegPerSec, (s, v) => s.NavTurnRateDegPerSec = v, 30f, 720f, 15f, "Max turn speed while navigating. Higher = snappier turns, lower = gentler."), Float("Post-Portal Delay (s)", s => s.PostPortalDelaySec, (s, v) => s.PostPortalDelaySec = MathF.Max(0f, v), 0f, 30f, 0.25f, @@ -693,6 +717,8 @@ internal static class SettingsSchema "After a death, walk back to where you died with RynthNav (outdoor deaths only),\nfighting on the way as usual, recover the corpse, then carry on. Needs the macro\nrunning and RynthNav loaded. /ra owncorpse stop cancels."), Spacer(), Section("Inventory Management"), + Bool("Item Info On Select", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v, + "Selecting an item prints its details to chat, Mag-Tools style (/ra iteminfo),\nidentifying it first when needed. Items the bot selects while looting are skipped."), Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v), Bool("Enable Autocram", 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."), diff --git a/src/RynthCore.Engine/UI/LayeredWindow.cs b/src/RynthCore.Engine/UI/LayeredWindow.cs index 9ada298..e3d168e 100644 --- a/src/RynthCore.Engine/UI/LayeredWindow.cs +++ b/src/RynthCore.Engine/UI/LayeredWindow.cs @@ -1477,39 +1477,53 @@ internal sealed unsafe class LayeredWindow : IDisposable } // Off the screen now, and ask the window's own thread to destroy it - // (works for a window created on any thread). Only if that post fails - // fall back to the game-thread destroy below: doing both could destroy - // an unrelated window that reused the handle in between. + // (works for a window created on any thread, never blocks, and still + // works after Win32Backend has unhooked the game WndProc: the post + // goes to the panel, not to the game window). if (Retire(hwnd)) { DisposeDib(); return; } - // DestroyWindow MUST run on the thread that owns the HWND — Win32 - // silently no-ops it otherwise. The HWND was created on the game - // thread (see FloatingPanelHost ctor's RunOnGameThread wrap), so - // marshal the teardown there too. Without this, redocking left - // the original floating window visible but orphaned ("frozen - // duplicate"). - // - // UI deep-dive finding P0-1 (2026-07-02): this used to block via - // RunOnGameThread (a synchronous SendMessage) — Dispose is often - // called from the Avalonia UI thread (e.g. redocking a panel), - // and blocking it on the game thread's WndProc is part of the - // same AB-BA deadlock class the OnInput fix closes. Dispose - // doesn't need to observe the destroy completing, so post it - // instead — fire-and-forget, never blocks the caller. - try - { - RynthCore.Engine.ImGuiBackend.Win32Backend.PostDestroyWindow(hwnd); - } - catch (Exception ex) - { - RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: PostDestroyWindow threw {ex.GetType().Name}: {ex.Message}. Falling back to inline call on thread=0x{GetCurrentThreadId():X}."); - // Best-effort fallback if Win32Backend isn't available - // (e.g. early shutdown after it's already torn down). - bool destroyed = DestroyWindow(hwnd); - RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: fallback DestroyWindow(0x{hwnd.ToInt64():X}) = {destroyed}."); - } + // The post failed: the window is already gone, or its queue is full. + // DestroyWindow only works on the owner thread, so destroy here only + // when this thread owns it. The old backup posted the destroy to the + // game thread, which fails (ACCESS_DENIED) for a panel created on the + // Avalonia UI thread. + DestroyIfOwnedHere(hwnd); } DisposeDib(); } + + private static void DestroyIfOwnedHere(IntPtr hwnd) + { + try + { + uint owner = GetWindowThreadProcessId(hwnd, out _); + uint current = GetCurrentThreadId(); + bool ourClass = false; + if (owner != 0) + { + char* buffer = stackalloc char[128]; + int length = GetClassNameW(hwnd, buffer, 128); + ourClass = length > 0 && new string(buffer, 0, length).StartsWith(ClassNamePrefix, StringComparison.Ordinal); + } + + switch (PanelDestroyPlan.Choose(owner, current, ourClass)) + { + case PanelDestroyFallback.DestroyHere: + bool destroyed = DestroyWindow(hwnd); + RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: self-destroy post failed; DestroyWindow(0x{hwnd.ToInt64():X}) on its owner thread 0x{current:X} = {destroyed}."); + break; + case PanelDestroyFallback.LeaveHidden: + ShowWindowAsync(hwnd, SW_HIDE); + RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: self-destroy post to 0x{hwnd.ToInt64():X} failed; owner thread 0x{owner:X} is not this one (0x{current:X}), so it is left hidden (destroyed with its thread or by the shutdown sweep)."); + break; + default: + break; // already gone, nothing to destroy + } + } + catch (Exception ex) + { + RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: destroy fallback threw {ex.GetType().Name}: {ex.Message}."); + } + } } diff --git a/src/RynthCore.Engine/UI/PanelDestroyFallback.cs b/src/RynthCore.Engine/UI/PanelDestroyFallback.cs new file mode 100644 index 0000000..fb65f4d --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelDestroyFallback.cs @@ -0,0 +1,42 @@ +// ============================================================================= +// RynthCore.Engine - UI/PanelDestroyFallback.cs +// What LayeredWindow.Dispose does when it could NOT post the self-destroy to a +// panel window (the window is already gone, or its thread's queue is full). +// +// Win32 only lets the thread that created a window destroy it. The normal path +// (LayeredWindow.Retire) posts WM_RYNTH_SELF_DESTROY to the panel itself, so the +// panel's own WndProc destroys it on its owner thread. This is only the backup, +// and it never sends the destroy to another thread: a panel created on the +// Avalonia UI thread could not be destroyed by the game thread (ACCESS_DENIED). +// +// Pure, so tools\PanelWindowTests can check it. Idea from Silentkelpie +// (rynth PR #1, LayeredWindow.DestroyOnOwnerThread); re-implemented here. +// ============================================================================= + +namespace RynthCore.Engine.UI; + +internal enum PanelDestroyFallback +{ + /// No owner thread: the window no longer exists. Nothing to do. + AlreadyGone, + + /// The calling thread owns the window: DestroyWindow right here. + DestroyHere, + + /// Another thread owns it: leave it hidden (Retire already hid it). Never cross-thread DestroyWindow. + LeaveHidden, +} + +internal static class PanelDestroyPlan +{ + /// GetWindowThreadProcessId(hwnd); 0 when the window is gone. + /// GetCurrentThreadId(). + /// The window's class is one of our panel classes. A handle can be reused + /// once the window is gone; never destroy a window that isn't a panel. + internal static PanelDestroyFallback Choose(uint ownerThread, uint currentThread, bool ourPanel) + { + if (ownerThread == 0) return PanelDestroyFallback.AlreadyGone; + if (!ourPanel) return PanelDestroyFallback.AlreadyGone; // the handle now belongs to someone else + return ownerThread == currentThread ? PanelDestroyFallback.DestroyHere : PanelDestroyFallback.LeaveHidden; + } +} diff --git a/src/RynthCore.Injector/Program.cs b/src/RynthCore.Injector/Program.cs index 1333323..dec625f 100644 --- a/src/RynthCore.Injector/Program.cs +++ b/src/RynthCore.Injector/Program.cs @@ -8,7 +8,7 @@ namespace RynthCore.Injector; internal static class Program { // Unified log path — must stay in sync with RynthCore.Engine.LogPaths. - private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs"; + private static readonly string UnifiedLogDirectory = RynthCore.Install.RynthInstallPaths.CoreLogsDir; // C:\Games\RynthCore\Logs by default private const string UnifiedLogFileName = "RynthCore.log"; private static int Main(string[] args) diff --git a/src/RynthCore.Injector/RynthCore.Injector.csproj b/src/RynthCore.Injector/RynthCore.Injector.csproj index d52d682..f245dd3 100644 --- a/src/RynthCore.Injector/RynthCore.Injector.csproj +++ b/src/RynthCore.Injector/RynthCore.Injector.csproj @@ -23,4 +23,9 @@ + + + + + diff --git a/src/RynthCore.Loader/EntryPoint.cs b/src/RynthCore.Loader/EntryPoint.cs index 01fe674..e9329db 100644 --- a/src/RynthCore.Loader/EntryPoint.cs +++ b/src/RynthCore.Loader/EntryPoint.cs @@ -31,7 +31,8 @@ public static class EntryPoint // Unified log path — must stay in sync with RynthCore.Engine.LogPaths. // The loader cannot reference the engine assembly (it loads it // dynamically), so the constants are mirrored here. - private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs"; + // A property, not a field: resolved when the first log line is written, never in the type initializer. + private static string UnifiedLogDirectory => RynthCore.Install.RynthInstallPaths.CoreLogsDir; // C:\Games\RynthCore\Logs by default private const string UnifiedLogFileName = "RynthCore.log"; /// /// Subdirectory beside the loader where reload-generation copies of the diff --git a/src/RynthCore.Loader/RynthCore.Loader.csproj b/src/RynthCore.Loader/RynthCore.Loader.csproj index f5f41d1..4773d9c 100644 --- a/src/RynthCore.Loader/RynthCore.Loader.csproj +++ b/src/RynthCore.Loader/RynthCore.Loader.csproj @@ -30,4 +30,9 @@ + + + + + diff --git a/src/RynthCore.StatusAgent/AgentConfig.cs b/src/RynthCore.StatusAgent/AgentConfig.cs index 8610076..d18bc4e 100644 --- a/src/RynthCore.StatusAgent/AgentConfig.cs +++ b/src/RynthCore.StatusAgent/AgentConfig.cs @@ -27,10 +27,10 @@ internal sealed class AgentConfig [JsonPropertyName("TimeoutSeconds")] public int TimeoutSeconds { get; set; } = 15; /// Directory holding the engine's per-client status files. - [JsonPropertyName("StatusDirectory")] public string StatusDirectory { get; set; } = @"C:\Games\RynthCore\Logs\status"; + [JsonPropertyName("StatusDirectory")] public string StatusDirectory { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreLogsDir, "status"); /// Directory holding per-client RynthCore.<pid>.log files (heartbeat fallback). - [JsonPropertyName("LogDirectory")] public string LogDirectory { get; set; } = @"C:\Games\RynthCore\Logs"; + [JsonPropertyName("LogDirectory")] public string LogDirectory { get; set; } = RynthCore.Install.RynthInstallPaths.CoreLogsDir; /// When true and no status file exists for a running client, derive /// basic status from that client's heartbeat log line. Lets the agent work @@ -97,20 +97,20 @@ internal sealed class AgentConfig /// portal.dat used to decode item icons for GET /icon (read-only inventory viewer). Defaults to /// the RynthCore client's private copy. If the file is absent (e.g. an agent running off the game box) /// /icon 404s and the app falls back to text rows — no other feature is affected. - [JsonPropertyName("IconDatPath")] public string IconDatPath { get; set; } = @"C:\Games\RynthCore\AcClient\client_portal.dat"; + [JsonPropertyName("IconDatPath")] public string IconDatPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "AcClient", "client_portal.dat"); /// Directory of RynthAi's baked dungeon floor-plan maps ({landblock:X8}_{layer}.bin), served as /// PNGs via GET /map for the app's dungeon-map viewer. If the folder is absent (agent off the game box) /// /maps returns an empty list and /map 404s — no other feature is affected. - [JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps"; + [JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Maps"); /// cell.dat the landscape map (GET /worldmap) is drawn from, once, then cached as worldmap-v1.jpg in /// . Absent = no world map (capabilities.worldMap false); nothing else changes. - [JsonPropertyName("CellDatPath")] public string CellDatPath { get; set; } = @"C:\Games\RynthCore\AcClient\client_cell_1.dat"; + [JsonPropertyName("CellDatPath")] public string CellDatPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "AcClient", "client_cell_1.dat"); /// RynthNav's Atlas (NavData\locations.json), searched by GET /nav/search for the phone's Travel tab. /// Absent = no travel (capabilities.travel false). The travel itself also needs EnableRemoteControl. - [JsonPropertyName("NavAtlasPath")] public string NavAtlasPath { get; set; } = @"C:\Games\RynthCore\NavData\locations.json"; + [JsonPropertyName("NavAtlasPath")] public string NavAtlasPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "NavData", "locations.json"); public static string DefaultConfigPath => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), diff --git a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj index 31cf6d9..61355b8 100644 --- a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj +++ b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj @@ -30,4 +30,9 @@ + + + + + diff --git a/src/Shared/RynthInstallPaths.cs b/src/Shared/RynthInstallPaths.cs new file mode 100644 index 0000000..a28011d --- /dev/null +++ b/src/Shared/RynthInstallPaths.cs @@ -0,0 +1,186 @@ +// ============================================================================ +// RynthInstallPaths.cs - where RynthCore and RynthSuite are installed. +// +// ONE FILE, TWO COPIES: RynthCore src\Shared\RynthInstallPaths.cs (engine, +// launcher, injector, loader, StatusAgent) and RynthSuite +// Plugins\Shared\RynthInstallPaths.cs (plugins, Loot Editor). Keep them +// byte-identical; RynthSuite's RynthAi host tests compare the two when the +// RynthCore sibling is checked out. +// +// READ ONLY. This only answers "which folder"; it never writes or deletes a +// setting, and nothing here may be used to pick a DLL or EXE to load or run. +// +// Order, per folder (first usable answer wins): +// 1. environment variable RYNTHCORE_DIR / RYNTHSUITE_DIR (dev setups) +// 2. HKCU\Software\Rynth CoreDir / SuiteDir (per-user install) +// 3. HKLM\Software\Rynth CoreDir / SuiteDir, 32-bit view (all-users install) +// 4. C:\Games\RynthCore / C:\Games\RynthSuite (today's layout) +// A value counts only if it is an absolute path; anything else is skipped. +// With nothing set the result is exactly the old hard-coded folder. +// +// Idea from Silentkelpie (rynth PR #1); re-implemented here. +// ============================================================================ + +using System; +using System.IO; +using System.Runtime.InteropServices; + +namespace RynthCore.Install; + +/// Where reads settings from. Tests pass a fake. +internal interface IInstallSettingSource +{ + /// The process environment variable, or null. + string? EnvironmentVariable(string name); + + /// A string value under HKCU\Software\Rynth, or null. + string? CurrentUser(string valueName); + + /// A string value under HKLM\Software\Rynth (32-bit registry view), or null. + string? LocalMachine(string valueName); +} + +internal static class RynthInstallPaths +{ + /// RynthCore folder when nothing is set (launcher, Runtime\, Logs\, NavData\, AcClient\). + public const string DefaultCoreDir = @"C:\Games\RynthCore"; + + /// RynthSuite folder when nothing is set (plugins and their data, e.g. RynthAi\). + public const string DefaultSuiteDir = @"C:\Games\RynthSuite"; + + public const string CoreEnvironmentVariable = "RYNTHCORE_DIR"; + public const string SuiteEnvironmentVariable = "RYNTHSUITE_DIR"; + + /// Key under HKCU / HKLM. + public const string RegistryKey = @"Software\Rynth"; + public const string CoreValueName = "CoreDir"; + public const string SuiteValueName = "SuiteDir"; + + private static string? _coreDir; + private static string? _suiteDir; + + /// The RynthCore install folder. Resolved once per process. + public static string CoreDir => + _coreDir ??= Resolve(CoreEnvironmentVariable, CoreValueName, DefaultCoreDir, SystemInstallSettings.Instance); + + /// The RynthSuite install folder. Resolved once per process. + public static string SuiteDir => + _suiteDir ??= Resolve(SuiteEnvironmentVariable, SuiteValueName, DefaultSuiteDir, SystemInstallSettings.Instance); + + /// <CoreDir>\Logs - the unified log folder. + public static string CoreLogsDir => Path.Combine(CoreDir, "Logs"); + + /// <SuiteDir>\RynthAi - RynthAi's home and data root. + public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi"); + + /// + /// The first usable folder from : environment, then HKCU, + /// then HKLM, else exactly as given. Never throws. + /// + internal static string Resolve(string environmentVariable, string valueName, string fallback, IInstallSettingSource source) + { + string? found = Normalize(Ask(() => source.EnvironmentVariable(environmentVariable))) + ?? Normalize(Ask(() => source.CurrentUser(valueName))) + ?? Normalize(Ask(() => source.LocalMachine(valueName))); + return found ?? fallback; + } + + private static readonly char[] BadNameChars = { '*', '?', '<', '>', '"', '|' }; + + private static string? Ask(Func read) + { + try { return read(); } + catch { return null; } + } + + /// + /// An absolute folder path, tidied (whitespace and surrounding quotes trimmed, + /// trailing separators dropped except on a drive root); null when the value is + /// empty, relative or not a valid path. + /// + internal static string? Normalize(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + string path = value.Trim().Trim('"').Trim(); + if (path.Length == 0) return null; + // .NET accepts some names Windows folders can't have; refuse them here. + if (path.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || path.IndexOfAny(BadNameChars) >= 0) return null; + if (path.Length > 2 && path.IndexOf(':', 2) >= 0) return null; // a colon only after the drive letter + try + { + if (!Path.IsPathFullyQualified(path)) return null; + string full = Path.GetFullPath(path); + string root = Path.GetPathRoot(full) ?? string.Empty; + string trimmed = full.TrimEnd('\\', '/'); + return trimmed.Length < root.Length ? root : trimmed; + } + catch + { + return null; + } + } +} + +/// The real environment and registry (read only, advapi32 directly: NativeAOT and trim safe). +internal sealed class SystemInstallSettings : IInstallSettingSource +{ + public static readonly SystemInstallSettings Instance = new(); + + private SystemInstallSettings() { } + + public string? EnvironmentVariable(string name) => Environment.GetEnvironmentVariable(name); + + public string? CurrentUser(string valueName) => ReadString(HKEY_CURRENT_USER, valueName, 0); + + public string? LocalMachine(string valueName) => ReadString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY); + + private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001)); + private static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002)); + private const uint RRF_RT_REG_SZ = 0x00000002; + private const uint RRF_RT_REG_EXPAND_SZ = 0x00000004; + private const uint RRF_SUBKEY_WOW6432KEY = 0x00020000; + private const int ERROR_SUCCESS = 0; + private const int MaxValueBytes = 64 * 1024; + + // Every argument is a pointer or an integer, so no marshalling stub is needed. + [DllImport("advapi32.dll", ExactSpelling = true)] + private static extern int RegGetValueW(IntPtr hkey, IntPtr subKey, IntPtr valueName, uint flags, + IntPtr type, IntPtr data, IntPtr dataBytes); + + private static string? ReadString(IntPtr root, string valueName, uint viewFlag) + { + IntPtr subKey = IntPtr.Zero, name = IntPtr.Zero, size = IntPtr.Zero, data = IntPtr.Zero; + try + { + subKey = Marshal.StringToHGlobalUni(RynthInstallPaths.RegistryKey); + name = Marshal.StringToHGlobalUni(valueName); + size = Marshal.AllocHGlobal(sizeof(uint)); + uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlag; + + Marshal.WriteInt32(size, 0); + if (RegGetValueW(root, subKey, name, flags, IntPtr.Zero, IntPtr.Zero, size) != ERROR_SUCCESS) + return null; + int bytes = Marshal.ReadInt32(size); + if (bytes < 2 || bytes > MaxValueBytes) return null; + + data = Marshal.AllocHGlobal(bytes + 2); + Marshal.WriteInt32(size, bytes); + if (RegGetValueW(root, subKey, name, flags, IntPtr.Zero, data, size) != ERROR_SUCCESS) + return null; + int written = Math.Min(Marshal.ReadInt32(size), bytes); + Marshal.WriteInt16(data, written - (written % 2), 0); // terminate even if the value wasn't + return Marshal.PtrToStringUni(data); + } + catch + { + return null; // no advapi32, access denied, ... -> the next source / the default + } + finally + { + if (data != IntPtr.Zero) Marshal.FreeHGlobal(data); + if (size != IntPtr.Zero) Marshal.FreeHGlobal(size); + if (name != IntPtr.Zero) Marshal.FreeHGlobal(name); + if (subKey != IntPtr.Zero) Marshal.FreeHGlobal(subKey); + } + } +} diff --git a/tools/ChatFilterTests/ChatFilterTests.csproj b/tools/ChatFilterTests/ChatFilterTests.csproj new file mode 100644 index 0000000..d1950be --- /dev/null +++ b/tools/ChatFilterTests/ChatFilterTests.csproj @@ -0,0 +1,29 @@ + + + + + Exe + net10.0 + enable + enable + true + ChatFilterTests + + + + + + + + + diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs new file mode 100644 index 0000000..6e55fb2 --- /dev/null +++ b/tools/ChatFilterTests/Program.cs @@ -0,0 +1,320 @@ +using System.Text.Json; +using System.Text.RegularExpressions; +using RynthCore.Engine.UI.Data; + +namespace ChatFilterTests; + +/// +/// RynthChat rule match modes and standard filters without AC: a Regex rule compiles and matches +/// exactly as before; Contains / Starts with / Ends with match plain text; "mode" loads and saves, +/// and a file without it is a file of Regex rules, written back unchanged; every standard filter +/// catches its example lines and spares player speech. +/// +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + // Real lines from the RynthCore logs ([BuffChat] type=... text=...), plus player speech. + private static readonly string[] Lines = + { + "You evaded Tusker Guard!", + "Tusker Guard grazes your foot for 4 points of bludgeoning damage!", + "Critical hit! Olthoi Swarm Nymph nicks your head for 21 points of piercing damage!", + "You say, \"Malar Zhavik\"", + "The spell consumed the following components: Prismatic Taper", + "Your spell fizzled.", + "You cast Focus Self I on yourself, but it is surpassed by Incantation of Focus Other", + "You don't have all the components for this spell.", + "You're too busy!", + "AutoRun ON", + "In portal Space", + "[General] Aja says, \"lol\"", + "Bob tells you, \"you evade like a pro (really)\"", + "Bob says, \"$5 for the Black Opal?\"", + "", + }; + + private static int Main() + { + RegexModeUnchanged(); + LiveSettingsRulesUnchanged(); + Contains(); + StartsWith(); + EndsWith(); + EmptyAndBadPatterns(); + ModeJson(); + SettingsRoundTrip(); + WhenParsing(); + PresetsCatchAndSpare(); + PresetsWellFormed(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL CHAT FILTER TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + private static void Case(string name) + { + _case = name; + Console.WriteLine("- " + name); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } + + /// What a rule compiled to before match modes (ChatFilterRule.Recompile, 2026-09-29). + private static Regex? Before(string pattern, out string? error) + { + error = null; + if (pattern.Length == 0) return null; + try { return new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(15)); } + catch (ArgumentException ex) { error = ex.Message; return null; } + } + + private static Regex? Now(ChatMatchMode mode, string pattern) => ChatRuleMatching.Compile(mode, pattern, 15, out _); + + private static void SameAsBefore(string pattern, string why) + { + Regex? before = Before(pattern, out string? errBefore); + Regex? now = ChatRuleMatching.Compile(ChatMatchMode.Regex, pattern, 15, out string? errNow); + Check((before == null) == (now == null), $"{why}: compiles the same ('{pattern}')"); + Check(errBefore == errNow, $"{why}: same error ('{pattern}')"); + if (before == null || now == null) return; + Check(before.ToString() == now.ToString() && before.Options == now.Options, $"{why}: same regex and options ('{pattern}')"); + foreach (string line in Lines) + { + Match a = before.Match(line), b = now.Match(line); + Check(a.Success == b.Success && a.Index == b.Index && a.Length == b.Length, $"{why}: same match on '{line}' ('{pattern}')"); + } + } + + // ── Regex: as before ───────────────────────────────────────────────── + + private static void RegexModeUnchanged() + { + Case("regex rules compile and match exactly as before"); + foreach (string p in new[] + { + "You evade", "^You evaded ", @"for \d+ points? of", "^Bob tells you, \"", "Autorun On", "In portal Space", + @"^\[General\]", "(?i)fizzled", "busy!$", ".", "a|b", "[unclosed", "(", @"\", " spaced ", + }) + SameAsBefore(p, "regex"); + Check(ChatRuleMatching.ToRegex(ChatMatchMode.Regex, "^You evaded ") == "^You evaded ", "a regex pattern is used as typed"); + } + + /// Every rule in the live settings file (if any) still compiles to what it did. + private static void LiveSettingsRulesUnchanged() + { + Case("the rules in this PC's rynthchat_settings.json are unchanged (read only)"); + string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthchat_settings.json"); + if (!File.Exists(path)) { Console.WriteLine(" (no live settings file; skipped)"); return; } + string json = File.ReadAllText(path); + RynthChatSettingsDto? dto = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatSettingsDto); + Check(dto != null, "the live file reads"); + int n = 0; + foreach (RynthChatFilterDto f in dto?.Filters ?? Array.Empty()) + { + if (f.Mode != null) continue; // a plain-text rule saved by a newer build + Check(ChatRuleMatching.Parse(f.Mode) == ChatMatchMode.Regex, "a rule without mode is Regex"); + SameAsBefore(f.Pattern ?? "", "live rule"); + n++; + } + Console.WriteLine($" ({n} live rule(s) checked)"); + } + + // ── Plain text ─────────────────────────────────────────────────────── + + private static void Contains() + { + Case("Contains: plain text anywhere, any case, nothing special"); + Regex rx = Now(ChatMatchMode.Contains, "evaded TUSKER")!; + Check(rx.IsMatch("You evaded Tusker Guard!"), "anywhere, any case"); + Check(!rx.IsMatch("You evaded Olthoi Slayer!"), "not other text"); + Regex special = Now(ChatMatchMode.Contains, "(really)")!; + Check(special.IsMatch("Bob tells you, \"you evade like a pro (really)\""), "( ) are characters"); + Check(!special.IsMatch("really"), "...not a group"); + Regex money = Now(ChatMatchMode.Contains, "$5 for the")!; + Check(money.IsMatch("Bob says, \"$5 for the Black Opal?\""), "$ is a character"); + Regex dot = Now(ChatMatchMode.Contains, "fizzled.")!; + Check(dot.IsMatch("Your spell fizzled."), "a dot matches a dot"); + Check(!dot.IsMatch("Your spell fizzledX"), "...not any character"); + Regex quote = Now(ChatMatchMode.Contains, "You say, \"")!; + Check(quote.IsMatch("You say, \"Malar Zhavik\""), "a quote"); + Regex star = Now(ChatMatchMode.Contains, "a*b")!; + Check(star.IsMatch("x a*b y") && !star.IsMatch("aaab"), "* is a character"); + Regex spaced = Now(ChatMatchMode.Contains, " evaded ")!; + Check(spaced.IsMatch("You evaded Tusker Guard!") && !spaced.IsMatch("evaded"), "spaces in Contains count"); + Match m = rx.Match("You evaded Tusker Guard!"); + Check(m.Index == 4 && m.Length == "evaded TUSKER".Length, "the match is the text (Colour match colours just it)"); + } + + private static void StartsWith() + { + Case("Starts with"); + Regex rx = Now(ChatMatchMode.StartsWith, "you say, \"")!; + Check(rx.IsMatch("You say, \"Malar Zhavik\""), "the start, any case"); + Check(!rx.IsMatch("Bob says, \"You say, \\\"x\\\"\""), "not later in the line"); + Regex lead = Now(ChatMatchMode.StartsWith, " [General]")!; + Check(lead.IsMatch("[General] Aja says, \"lol\""), "leading spaces in the pattern don't count"); + Check(!lead.IsMatch("Bob says, \"[General]\""), "brackets are characters, at the start only"); + } + + private static void EndsWith() + { + Case("Ends with"); + Regex rx = Now(ChatMatchMode.EndsWith, "evaded your attack. ")!; + Check(rx.IsMatch("Drudge Slinker evaded your attack."), "the end, trailing pattern spaces ignored"); + Check(rx.IsMatch("Drudge Slinker evaded your attack. "), "trailing line spaces ignored"); + Check(!rx.IsMatch("Drudge Slinker evaded your attack. Again"), "not earlier in the line"); + Check(!rx.IsMatch("Drudge Slinker evaded your attackX"), "the dot is a dot"); + } + + private static void EmptyAndBadPatterns() + { + Case("empty and bad patterns"); + foreach (ChatMatchMode mode in Enum.GetValues()) + { + Check(ChatRuleMatching.Compile(mode, "", 15, out string? e) == null && e == null, $"{mode}: empty matches nothing, no error"); + Check(ChatRuleMatching.Compile(mode, null, 15, out _) == null, $"{mode}: null matches nothing"); + } + foreach (ChatMatchMode mode in new[] { ChatMatchMode.Contains, ChatMatchMode.StartsWith, ChatMatchMode.EndsWith }) + { + Check(ChatRuleMatching.Compile(mode, " ", 15, out _) == null, $"{mode}: spaces only match nothing"); + Check(ChatRuleMatching.Compile(mode, "[unclosed (", 15, out string? e) != null && e == null, $"{mode}: regex syntax is just text"); + } + Check(ChatRuleMatching.Compile(ChatMatchMode.Regex, "[unclosed", 15, out string? err) == null && err != null, "Regex: a bad regex reports its error"); + Check(ChatRuleMatching.Compile(ChatMatchMode.Regex, " ", 15, out _) != null, "Regex: spaces are a pattern (as before)"); + } + + // ── Saving and loading ─────────────────────────────────────────────── + + private static void ModeJson() + { + Case("mode in JSON"); + Check(ChatRuleMatching.ToJson(ChatMatchMode.Regex) == null, "Regex writes no mode"); + foreach (ChatMatchMode mode in Enum.GetValues()) + Check(ChatRuleMatching.Parse(ChatRuleMatching.ToJson(mode)) == mode, $"{mode} round-trips"); + Check(ChatRuleMatching.Parse(null) == ChatMatchMode.Regex, "absent: Regex"); + Check(ChatRuleMatching.Parse("") == ChatMatchMode.Regex, "empty: Regex"); + Check(ChatRuleMatching.Parse("CONTAINS") == ChatMatchMode.Contains, "any case"); + Check(ChatRuleMatching.Parse("StartsWith") == ChatMatchMode.StartsWith, "StartsWith (enum name)"); + Check(ChatRuleMatching.Parse("EndsWith") == ChatMatchMode.EndsWith, "EndsWith (enum name)"); + Check(ChatRuleMatching.Parse("fuzzy") == ChatMatchMode.Regex, "unknown: Regex"); + Check(ChatRuleMatching.Labels.Length == Enum.GetValues().Length, "a label per mode"); + } + + private const string OldFile = """ + {"version":2,"fontSize":10,"backgroundAlpha":242,"autoScroll":true,"suppressChat":false,"logEnabled":false, + "ctrlGatedClickThrough":false,"showTimestamps":true,"mentionHighlight":true,"mentionSound":false, + "customTabs":["Junk"], + "filters":[{"pattern":"In portal Space","tab":"Junk","enabled":true,"action":"move"}, + {"pattern":"^You evaded ","tab":"","enabled":false,"action":"hide","when":"type:21"}, + {"pattern":"fizzled","tab":"","enabled":true,"action":"color","colorMode":"match","color":"#FFD27A"}]} + """; + + private static void SettingsRoundTrip() + { + Case("settings: an old file loads as Regex rules and saves unchanged; plain-text rules round-trip"); + var opts = RynthChatJsonContext.Default.RynthChatSettingsDto; + RynthChatSettingsDto old = JsonSerializer.Deserialize(OldFile, opts)!; + Check(old.Filters!.Length == 3, "three rules"); + Check(old.Filters.All(f => f.Mode == null && ChatRuleMatching.Parse(f.Mode) == ChatMatchMode.Regex), "every old rule is Regex"); + string saved = JsonSerializer.Serialize(old, opts); + Check(!saved.Contains("\"mode\"", StringComparison.Ordinal), "saving old rules writes no mode key"); + string savedAgain = JsonSerializer.Serialize(JsonSerializer.Deserialize(saved, opts)!, opts); + Check(saved == savedAgain, "load + save is stable"); + + // A plain-text rule, as ChatModel.ToDto writes it, and back. + old.Filters[0].Mode = ChatRuleMatching.ToJson(ChatMatchMode.Contains); + old.Filters[1].Mode = ChatRuleMatching.ToJson(ChatMatchMode.StartsWith); + string withModes = JsonSerializer.Serialize(old, opts); + Check(withModes.Contains("\"mode\":\"contains\"", StringComparison.Ordinal), "Contains saved as mode=contains"); + RynthChatSettingsDto back = JsonSerializer.Deserialize(withModes, opts)!; + Check(ChatRuleMatching.Parse(back.Filters![0].Mode) == ChatMatchMode.Contains, "Contains loads back"); + Check(ChatRuleMatching.Parse(back.Filters[1].Mode) == ChatMatchMode.StartsWith, "StartsWith loads back"); + Check(ChatRuleMatching.Parse(back.Filters[2].Mode) == ChatMatchMode.Regex, "the untouched rule is still Regex"); + Check(back.Filters[1].When == "type:21" && back.Filters[1].Action == "hide" && !back.Filters[1].Enabled, "other fields kept"); + + // Export / Import uses the rule-set DTO: same field. + var set = new RynthChatRuleSetDto { Format = RynthChatRuleSetDto.FormatName, Rules = back.Filters }; + string exported = JsonSerializer.Serialize(set, RynthChatJsonContext.Default.RynthChatRuleSetDto); + RynthChatRuleSetDto imported = JsonSerializer.Deserialize(exported, RynthChatJsonContext.Default.RynthChatRuleSetDto)!; + Check(ChatRuleMatching.Parse(imported.Rules![0].Mode) == ChatMatchMode.Contains, "export / import keeps the mode"); + RynthChatFilterDto[]? bare = JsonSerializer.Deserialize("[{\"pattern\":\"x\"}]", RynthChatJsonContext.Default.RynthChatFilterDtoArray); + Check(bare != null && ChatRuleMatching.Parse(bare[0].Mode) == ChatMatchMode.Regex, "a bare old rule array imports as Regex"); + } + + private static void WhenParsing() + { + Case("When: the same reading as before"); + Check(ChatRuleMatching.ParseWhen("") == (null, -1), "empty: any"); + Check(ChatRuleMatching.ParseWhen(null) == (null, -1), "null: any"); + Check(ChatRuleMatching.ParseWhen(" chan:Combat ") == ("Combat", -1), "a channel"); + Check(ChatRuleMatching.ParseWhen("CHAN:Combat") == ("Combat", -1), "chan: any case"); + Check(ChatRuleMatching.ParseWhen("type:21") == (null, 21), "a type"); + Check(ChatRuleMatching.ParseWhen("type:x") == (null, -1), "a bad type: any"); + Check(ChatRuleMatching.ParseWhen("type:-1") == (null, -1), "a negative type: any"); + Check(ChatRuleMatching.ParseWhen("chan:") == (null, -1), "chan: with nothing: any"); + Check(ChatRuleMatching.WhenMatches("combat", -1, "Combat", 3), "channel any case"); + Check(!ChatRuleMatching.WhenMatches("Combat", -1, "Chat", 21), "other channel"); + Check(ChatRuleMatching.WhenMatches(null, 21, "Combat", 21) && !ChatRuleMatching.WhenMatches(null, 21, "Combat", 22), "type"); + Check(ChatRuleMatching.WhenMatches(null, -1, "Chat", 2), "any"); + } + + // ── Standard filters ───────────────────────────────────────────────── + + private static void PresetsCatchAndSpare() + { + Case("standard filters catch their lines and spare the others"); + foreach (ChatFilterPreset p in ChatFilterPresets.All) + { + Check(p.Catches.Length > 0, $"{p.Id}: has example lines"); + foreach (var (text, chan, type) in p.Catches) + Check(p.Matches(text, chan, type), $"{p.Id}: catches '{text}' ({chan}, type {type})"); + foreach (var (text, chan, type) in p.Spares) + Check(!p.Matches(text, chan, type), $"{p.Id}: spares '{text}' ({chan}, type {type})"); + // The same rule built the way ChatFilterRule.Recompile builds it. + Regex? rx = ChatRuleMatching.Compile(p.Mode, p.Pattern, 15, out string? err); + Check(rx != null && err == null, $"{p.Id}: compiles as a rule"); + } + + // Player speech: no filter that is held to a type or channel may take a say, a tell or an emote's text. + string[] speech = { "Bob says, \"You evaded Tusker Guard!\"", "Bob tells you, \"Your spell fizzled.\"", "You say, \"You're too busy!\"" }; + foreach (ChatFilterPreset p in ChatFilterPresets.All) + { + if (p.When.Length == 0) continue; // "" presets are checked by their own Spares + foreach (string s in speech) + { + Check(!p.Matches(s, "Chat", 2), $"{p.Id}: never a Local say ('{s}')"); + Check(!p.Matches(s, "Chat", 3), $"{p.Id}: never a tell ('{s}')"); + } + } + } + + private static void PresetsWellFormed() + { + Case("standard filters are well formed"); + var ids = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (ChatFilterPreset p in ChatFilterPresets.All) + { + Check(ids.Add(p.Id), $"{p.Id}: unique id"); + Check(p.Group.Length > 0 && p.Label.Length > 0 && p.Description.Length > 0, $"{p.Id}: named and described"); + Check(p.Pattern.Trim().Length > 0, $"{p.Id}: has a pattern"); + var (chan, type) = ChatRuleMatching.ParseWhen(p.When); + Check(p.When.Length == 0 || chan != null || type >= 0, $"{p.Id}: When '{p.When}' is one the rules read"); + Check(p.SameAs(p.Mode, p.Pattern, p.When), $"{p.Id}: SameAs itself"); + Check(!p.SameAs(p.Mode == ChatMatchMode.Regex ? ChatMatchMode.Contains : ChatMatchMode.Regex, p.Pattern, p.When), $"{p.Id}: another mode is another rule"); + Check(!p.SameAs(p.Mode, p.Pattern + "x", p.When), $"{p.Id}: another pattern is another rule"); + Check(ReferenceEquals(ChatFilterPresets.Get(p.Id), p), $"{p.Id}: found by id"); + } + Check(ChatFilterPresets.Get("no.such") == null, "an unknown id is null"); + Check(ChatFilterPresets.All.Length >= 10, "a useful set"); + } +} diff --git a/tools/EngineSettingsTests/EngineSettingsTests.csproj b/tools/EngineSettingsTests/EngineSettingsTests.csproj new file mode 100644 index 0000000..cb7ce80 --- /dev/null +++ b/tools/EngineSettingsTests/EngineSettingsTests.csproj @@ -0,0 +1,27 @@ + + + + + Exe + net10.0 + enable + enable + true + EngineSettingsTests + + + + + + + + diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs new file mode 100644 index 0000000..8c8437d --- /dev/null +++ b/tools/EngineSettingsTests/Program.cs @@ -0,0 +1,353 @@ +using System.Diagnostics; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine +{ + /// Stub of the engine's log: the lines go to stdout, where the parent test reads them. + internal static class RynthLog + { + internal static void Plugin(string msg) => Console.WriteLine("[PLG] " + msg); + internal static void Info(string msg) => Console.WriteLine("[INF] " + msg); + internal static void Warn(string msg) => Console.WriteLine("[WRN] " + msg); + } +} + +namespace EngineSettingsTests +{ + // Offline tests for saving engine.json. See the csproj. + internal static class Program + { + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + private static void Eq(T actual, T expected, string msg) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'"); + + private static string _root = ""; + + private static int Main(string[] args) + { + if (args.Length > 0 && args[0] == "--child") + return Child(args.Skip(1).ToArray()); + + _root = Path.Combine(Path.GetTempPath(), "rynth-engine-settings-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_root); + try + { + Run(nameof(MergeKeepsForeignKeys), MergeKeepsForeignKeys); + Run(nameof(MergeEmptyOrMissingFile), MergeEmptyOrMissingFile); + Run(nameof(MergeRefusesUnreadableFile), MergeRefusesUnreadableFile); + Run(nameof(WriteAtomicCreatesAndReplaces), WriteAtomicCreatesAndReplaces); + Run(nameof(OwnedKeysMatchEngineSettings), OwnedKeysMatchEngineSettings); + Run(nameof(SaveKeepsLauncherKeys), SaveKeepsLauncherKeys); + Run(nameof(SaveRoundTripsOwnedKeys), SaveRoundTripsOwnedKeys); + Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys); + Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone); + } + finally + { + try { Directory.Delete(_root, true); } catch { } + } + Console.WriteLine(); + Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} assertions)" : $"FAIL ({_fails} of {_asserts} assertions failed)"); + return _fails == 0 && _asserts > 0 ? 0 : 1; + } + + private static void Run(string name, Action test) + { + int before = _fails; + try { test(); } + catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] {name} threw {ex.GetType().Name}: {ex.Message}"); } + Console.WriteLine($"{(_fails == before ? "ok " : "FAIL")} {name}"); + } + + // ── The real EngineSettings, in a child process ───────────────────────── + + /// Runs in the child: one EngineSettings call against RYNTHCORE_ENGINE_SETTINGS. + private static int Child(string[] args) + { + try + { + switch (args[0]) + { + case "hook-off": EngineSettings.SetUiHookEnabled(args[1], false); break; + case "add-plugin": EngineSettings.AddPluginPath(args[1]); break; + case "imgui-off": EngineSettings.EnableImGuiBackend = false; break; + case "dump": + Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths)); + Console.WriteLine("StartTooltip=" + EngineSettings.IsUiHookEnabled("StartTooltip")); + Console.WriteLine("DecalBridge=" + EngineSettings.DecalBridgeMode); + Console.WriteLine("ImGuiBackend=" + EngineSettings.EnableImGuiBackend); + Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream); + break; + default: throw new ArgumentException(args[0]); + } + Console.WriteLine("CHILD-OK"); + return 0; + } + catch (Exception ex) + { + Console.WriteLine($"CHILD-THREW {ex.GetType().Name}: {ex.Message}"); + return 2; + } + } + + private static (int Exit, string Out) RunChild(string settingsPath, params string[] args) + { + var psi = new ProcessStartInfo(Environment.ProcessPath!) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + psi.ArgumentList.Add("--child"); + foreach (string a in args) psi.ArgumentList.Add(a); + psi.Environment["RYNTHCORE_ENGINE_SETTINGS"] = settingsPath; + using Process p = Process.Start(psi)!; + string output = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd(); + p.WaitForExit(); + return (p.ExitCode, output); + } + + private static string NewDir(string name) + { + string dir = Path.Combine(_root, name); + Directory.CreateDirectory(dir); + return dir; + } + + private static JsonElement ReadJson(string path) + { + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + return doc.RootElement.Clone(); + } + + private static string Raw(JsonElement el) => el.GetRawText().Replace(" ", "").Replace("\r", "").Replace("\n", ""); + + private static void NoTempFilesLeft(string dir) => + Eq(string.Join(",", Directory.GetFiles(dir).Select(Path.GetFileName).Where(n => n != "engine.json")), "", "only engine.json in the folder (no temp file left)"); + + // A launcher-written engine.json: the engine's keys plus the launcher's (and an unknown tool's). + private const string LauncherFile = """ + { + "PluginPaths": [ "C:\\Games\\RynthSuite\\Plugins\\RynthCore.Plugin.RynthAi.dll" ], + "EnableImGuiShell": false, + "EnableImGuiBackend": true, + "EnableDcompOverlay": true, + "DecalBridge": "On", + "DecalInGameImGui": true, + "LoggingLevel": "Debug", + "LauncherWindow": { "X": 10, "Y": -4, "Docked": [ "Plugins", { "Tab": 2 } ], "Note": null }, + "SomeNumber": 1.50, + "Unicode": "Dereth \u00e9 \u2014" + } + """; + + private static void SaveKeepsLauncherKeys() + { + string dir = NewDir("keeps"); + string path = Path.Combine(dir, "engine.json"); + File.WriteAllText(path, LauncherFile); + JsonElement before = ReadJson(path); + + var (exit, output) = RunChild(path, "hook-off", "StartTooltip"); + Eq(exit, 0, "child exit code (" + output.Trim() + ")"); + + JsonElement after = ReadJson(path); + foreach (string key in new[] { "EnableDcompOverlay", "LoggingLevel", "LauncherWindow", "SomeNumber", "Unicode" }) + { + Check(after.TryGetProperty(key, out JsonElement v), $"launcher key {key} kept"); + if (after.TryGetProperty(key, out v)) + Check(JsonElement.DeepEquals(v, before.GetProperty(key)), $"launcher key {key} value unchanged: {Raw(v)}"); + } + Eq(after.GetProperty("SomeNumber").GetRawText(), "1.50", "a number keeps its exact text"); + Eq(after.GetProperty("Unicode").GetString(), "Dereth \u00e9 \u2014", "non-ASCII text intact"); + + // The engine's own keys: written from memory as before. + Eq(string.Join(",", after.GetProperty("DisabledUiHooks").EnumerateArray().Select(e => e.GetString())), "StartTooltip", "DisabledUiHooks written"); + Eq(Raw(after.GetProperty("PluginPaths")), Raw(before.GetProperty("PluginPaths")), "PluginPaths kept"); + Eq(after.GetProperty("EnableImGuiShell").GetBoolean(), false, "EnableImGuiShell kept (read, written back)"); + Eq(after.GetProperty("DecalBridge").GetString(), "On", "DecalBridge On kept"); + Check(!after.TryGetProperty("DecalInGameImGui", out _), "DecalInGameImGui at its default is left out, as before"); + foreach (string key in new[] { "EnablePlugins", "EnableDatShareHook", "EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount", "EnableHangMinidump", "PreventIdleLogoff" }) + Check(after.TryGetProperty(key, out _), $"owned key {key} written as before"); + + // No key twice. + var names = after.EnumerateObject().Select(p => p.Name).ToList(); + Eq(names.Count, names.Distinct(StringComparer.Ordinal).Count(), "no duplicate keys"); + NoTempFilesLeft(dir); + + // A second save (another owned key) still keeps them. + (exit, output) = RunChild(path, "imgui-off"); + Eq(exit, 0, "second child exit code (" + output.Trim() + ")"); + after = ReadJson(path); + Eq(after.GetProperty("EnableImGuiBackend").GetBoolean(), false, "EnableImGuiBackend saved"); + Check(after.TryGetProperty("EnableDcompOverlay", out _) && after.TryGetProperty("LauncherWindow", out _), "launcher keys survive a second save"); + Eq(after.GetProperty("DisabledUiHooks").GetArrayLength(), 1, "first save's DisabledUiHooks kept"); + } + + private static void SaveRoundTripsOwnedKeys() + { + string dir = NewDir("roundtrip"); + string path = Path.Combine(dir, "engine.json"); + File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", "\"ServerMessageStream\": false, \"LoggingLevel\"")); + string plugin = Path.Combine(dir, "RynthCore.Plugin.RynthNav.dll"); + Eq(RunChild(path, "add-plugin", plugin).Exit, 0, "add-plugin"); + Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "hook-off"); + + var (exit, output) = RunChild(path, "dump"); + Eq(exit, 0, "dump"); + Check(output.Contains("PluginPaths=C:\\Games\\RynthSuite\\Plugins\\RynthCore.Plugin.RynthAi.dll|" + plugin), "plugin paths read back in order: " + output); + Check(output.Contains("StartTooltip=False"), "the hook is off after a reload"); + Check(output.Contains("DecalBridge=On"), "DecalBridge read back"); + Check(output.Contains("ServerMessageStream=False"), "ServerMessageStream false read back"); + Check(ReadJson(path).TryGetProperty("EnableDcompOverlay", out _), "launcher key still there"); + } + + private static void SaveWithoutFileWritesOwnedKeys() + { + string dir = NewDir("nofile"); + string path = Path.Combine(dir, "engine.json"); + var (exit, output) = RunChild(path, "hook-off", "CheckTooltip"); + Eq(exit, 0, "child exit code (" + output.Trim() + ")"); + Check(File.Exists(path), "engine.json created"); + JsonElement after = ReadJson(path); + Eq(after.GetProperty("DisabledUiHooks")[0].GetString(), "CheckTooltip", "the change saved"); + Check(after.EnumerateObject().All(p => EngineSettings.OwnedKeys.Contains(p.Name)), "only engine keys in a new file"); + NoTempFilesLeft(dir); + } + + private static void SaveLeavesMalformedFileAlone() + { + foreach ((string name, string content) in new[] + { + ("truncated", "{ \"PluginPaths\": [ \"C:\\\\Games\\\\a.dll\" ], \"EnableDcompOverlay\": tr"), + ("not-json", "this is not json"), + ("array-root", "[ 1, 2, 3 ]"), + }) + { + string dir = NewDir("bad-" + name); + string path = Path.Combine(dir, "engine.json"); + File.WriteAllText(path, content); + byte[] before = File.ReadAllBytes(path); + + var (exit, output) = RunChild(path, "hook-off", "StartTooltip"); + Eq(exit, 0, $"{name}: no crash ({output.Trim()})"); + Check(output.Contains("[WRN] EngineSettings: not saving"), $"{name}: says why it didn't save"); + Check(File.ReadAllBytes(path).SequenceEqual(before), $"{name}: the file is left exactly as it was"); + NoTempFilesLeft(dir); + } + + // An empty file (an old non-atomic save cut short) holds nothing to lose: it is rewritten. + string emptyDir = NewDir("bad-empty"); + string emptyPath = Path.Combine(emptyDir, "engine.json"); + File.WriteAllText(emptyPath, ""); + Eq(RunChild(emptyPath, "hook-off", "StartTooltip").Exit, 0, "empty: no crash"); + Eq(ReadJson(emptyPath).GetProperty("DisabledUiHooks")[0].GetString(), "StartTooltip", "empty: rewritten with the change"); + } + + // ── EngineSettingsFile, direct ────────────────────────────────────────── + + private static byte[] Owned(string json) => Encoding.UTF8.GetBytes(json); + private static readonly HashSet Keys = new(StringComparer.Ordinal) { "A", "B", "Optional" }; + + private static void MergeKeepsForeignKeys() + { + string existing = """{ "A": 1, "Foreign": { "x": [1, {"y": null}] }, "Optional": true, "B": "old", "Other": "kept", "Foreign": 99 }"""; + byte[]? merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 2, "B": "new" }"""), Keys, out string? err); + Check(merged != null && err == null, "merged"); + JsonElement r = JsonDocument.Parse(merged!).RootElement; + Eq(string.Join(",", r.EnumerateObject().Select(p => p.Name)), "A,B,Foreign,Other", "ours first in our order, then the others in file order, each once"); + Eq(r.GetProperty("A").GetInt32(), 2, "owned A updated"); + Eq(r.GetProperty("B").GetString(), "new", "owned B updated"); + Eq(Raw(r.GetProperty("Foreign")), """{"x":[1,{"y":null}]}""", "nested foreign object kept whole (first of a duplicate key)"); + Check(!r.TryGetProperty("Optional", out _), "an owned key not written this time is left out"); + + // A key we write but forgot to list as owned is still written once (ours wins). + byte[]? m2 = EngineSettingsFile.Merge("""{ "New": "file" }""", Owned("""{ "New": "ours" }"""), Keys, out _); + JsonElement r2 = JsonDocument.Parse(m2!).RootElement; + Eq(r2.EnumerateObject().Count(), 1, "unlisted key written once"); + Eq(r2.GetProperty("New").GetString(), "ours", "ours wins"); + + // Keys are case-sensitive, like the engine's reads: "a" is not "A". + byte[]? m3 = EngineSettingsFile.Merge("""{ "a": 5 }""", Owned("""{ "A": 1 }"""), Keys, out _); + Eq(JsonDocument.Parse(m3!).RootElement.GetProperty("a").GetInt32(), 5, "a differently-cased key is someone else's"); + } + + private static void MergeEmptyOrMissingFile() + { + foreach (string? existing in new[] { null, "", " \r\n " }) + { + byte[]? merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 1 }"""), Keys, out string? err); + Check(merged != null && err == null, $"'{existing}': merged"); + Eq(Raw(JsonDocument.Parse(merged!).RootElement), """{"A":1}""", $"'{existing}': only ours"); + } + } + + private static void MergeRefusesUnreadableFile() + { + foreach (string bad in new[] { "{ \"A\": ", "nope", "[1]", "\"text\"", "null", "{ \"A\": 1 } trailing" }) + { + byte[]? merged = EngineSettingsFile.Merge(bad, Owned("""{ "A": 1 }"""), Keys, out string? err); + Check(merged == null && !string.IsNullOrEmpty(err), $"'{bad}': refused with a reason"); + } + } + + private static void WriteAtomicCreatesAndReplaces() + { + string dir = NewDir("atomic"); + string path = Path.Combine(dir, "engine.json"); + EngineSettingsFile.WriteAtomic(path, Encoding.UTF8.GetBytes("{\"v\":1}")); + Eq(File.ReadAllText(path), "{\"v\":1}", "created"); + EngineSettingsFile.WriteAtomic(path, Encoding.UTF8.GetBytes("{\"v\":2}")); + Eq(File.ReadAllText(path), "{\"v\":2}", "replaced"); + NoTempFilesLeft(dir); + + // A file another process holds open without delete sharing: the swap fails after its + // retries, the old content stays whole, and the temp file is cleaned up. + using (new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + bool threw = false; + try { EngineSettingsFile.WriteAtomic(path, Encoding.UTF8.GetBytes("{\"v\":3}")); } + catch (IOException) { threw = true; } + catch (UnauthorizedAccessException) { threw = true; } + Check(threw, "a locked file makes the save fail (the caller logs it)"); + } + Eq(File.ReadAllText(path), "{\"v\":2}", "locked: old content intact"); + NoTempFilesLeft(dir); + } + + // Every key EngineSettings.cs reads or writes must be in OwnedKeys (and the other way round): + // a new setting left off the list would be kept from the old file instead of saved. + private static void OwnedKeysMatchEngineSettings() + { + string source = File.ReadAllText(FindUp(Path.Combine("src", "RynthCore.Engine", "Plugins", "EngineSettings.cs"))); + var used = new HashSet(StringComparer.Ordinal); + foreach (Match m in Regex.Matches(source, @"TryGetProperty\(""(\w+)""")) + used.Add(m.Groups[1].Value); + foreach (Match m in Regex.Matches(source, @"\bw\.Write\w*\(""(\w+)""")) + used.Add(m.Groups[1].Value); + Check(used.Count >= 16, $"found the keys in EngineSettings.cs ({used.Count})"); + foreach (string key in used) + Check(EngineSettings.OwnedKeys.Contains(key), $"EngineSettings.OwnedKeys lists \"{key}\""); + foreach (string key in EngineSettings.OwnedKeys) + Check(used.Contains(key), $"OwnedKeys \"{key}\" is read or written by EngineSettings.cs"); + } + + private static string FindUp(string relative) + { + for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent) + { + string p = Path.Combine(d.FullName, relative); + if (File.Exists(p)) return p; + } + throw new FileNotFoundException(relative); + } + } +} diff --git a/tools/FlightRecorderTests/FlightRecorderTests.csproj b/tools/FlightRecorderTests/FlightRecorderTests.csproj new file mode 100644 index 0000000..3fae4aa --- /dev/null +++ b/tools/FlightRecorderTests/FlightRecorderTests.csproj @@ -0,0 +1,40 @@ + + + + + Exe + net10.0-windows + enable + enable + true + true + FlightRecorderTests + false + true + + + + + + + + + + + diff --git a/tools/FlightRecorderTests/Program.cs b/tools/FlightRecorderTests/Program.cs new file mode 100644 index 0000000..245f357 --- /dev/null +++ b/tools/FlightRecorderTests/Program.cs @@ -0,0 +1,853 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using NetMessageTests; +using RynthCore.Engine.Net; + +namespace FlightRecorderTests; + +internal static unsafe class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + // Fake clock: one tick = one millisecond. + private static long _t = 1_000_000; + private static long Clock() => _t; + + private const uint Player = 0x50000ABC; + private const uint Corpse = 0x80068ACE; + private const uint Other = 0x80012345; + + private static int Main(string[] args) + { + RingBasics(); + RingWrapAndTruncation(); + RingConcurrent(); + + PlayerLearnedAndFilters(); + UsedObjectsKept(); + PositionRateLimit(); + RetransmitDedupe(); + ResendRequestMarker(); + EngineTagging(); + EngineRepeatFolding(); + + DetectUseRefusal(); + DetectUseRefusalDelayedAnswers(); + NoTriggerWhenCorpsesOpen(); + NoTriggerForDrinksAndKits(); + DetectUnanswered(); + DetectTooBusy(); + DumpPolicy(); + + DecodeOutbound(); + DecodeMoveToState(); + DecodeInboundEvents(); + DecodeMotion(); + DecodePositionAndObjects(); + DecodeMarkers(); + DecodeTruncatedAndGarbage(); + DumpFormat(); + + foreach (string path in args) + { + if (path == "--sample") SampleDump(); + else Replay(path); + } + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL FLIGHT RECORDER TESTS PASSED." : $"{_failed} FAILED."); + + Performance(); + return _failed == 0 ? 0 : 1; + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private static void Case(string name) + { + _case = name; + Console.WriteLine($"- {name}"); + } + + private static void Eq(T actual, T expected, string what) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{what}: expected {expected}, got {actual}"); + + private static void Has(string text, string part, string what) => + Check(text.Contains(part, StringComparison.Ordinal), $"{what}: expected \"{part}\" in \"{text}\""); + + private static void Lacks(string text, string part, string what) => + Check(!text.Contains(part, StringComparison.Ordinal), $"{what}: did not expect \"{part}\" in \"{text}\""); + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } + + private static FlightCapture NewCapture(int capacity = 1024) => new(capacity, Clock, 1000); + + private static uint _fragSeq = 1000; + + /// One datagram carrying in one fragment. + private static byte[] One(byte[] message, uint extraFlags = 0, uint? seq = null) + => Datagram.Build(extraFlags, 0, null, new Frag(seq ?? _fragSeq++, 1, 0, message)); + + private static void Feed(FlightCapture c, bool outbound, byte[] datagram) + { + fixed (byte* p = datagram) + c.OnDatagram(outbound, p, datagram.Length); + } + + private static void In(FlightCapture c, byte[] message, uint extraFlags = 0, uint? seq = null) => Feed(c, false, One(message, extraFlags, seq)); + private static void Out(FlightCapture c, byte[] message, uint extraFlags = 0, uint? seq = null) => Feed(c, true, One(message, extraFlags, seq)); + + private static uint _actionSeq = 1; + private static byte[] Action(uint type, Body body) => new Body().U32(0xF7B1).U32(_actionSeq++).U32(type).Bytes(body.ToArray()).ToArray(); + private static byte[] Event(uint type, Body body) => body.GameEvent(type, Player, 42); + + private static FlightRecord[] Recs(FlightCapture c) => c.Ring.Snapshot(); + private static string[] Lines(FlightCapture c) => Recs(c).Select(r => FlightFormat.Arrow(r.Entry.Dir) + " " + FlightFormat.Describe(r)).ToArray(); + private static string Last(FlightCapture c) { var r = Recs(c); return r.Length == 0 ? "" : FlightFormat.Arrow(r[^1].Entry.Dir) + " " + FlightFormat.Describe(r[^1]); } + private static int Count(FlightCapture c, FlightDir dir) => Recs(c).Count(r => r.Entry.Dir == dir); + + private static void LoginAs(FlightCapture c) => In(c, Event(0x01C7, new Body().U32(0))); // any game event names the player + + // Message builders (server side as the server writes them, client side as the client does). + private static byte[] UseDone(uint err) => Event(0x01C7, new Body().U32(err)); + private static byte[] ViewContents(uint container, params uint[] items) + { + var b = new Body().U32(container).U32((uint)items.Length); + foreach (uint i in items) b.U32(i).U32(0); + return Event(0x0196, b); + } + private static byte[] WeenieError(uint code) => Event(0x028A, new Body().U32(code)); + private static byte[] Use(uint obj) => Action(0x0036, new Body().U32(obj)); + private static byte[] UseWithTarget(uint src, uint dst) => Action(0x0035, new Body().U32(src).U32(dst)); + + /// UpdateMotion for : header, then a state with the given commands. + private static byte[] MotionState(uint obj, ushort style, ushort forward = 0, (ushort Cmd, float Speed)[]? cmds = null, bool autonomous = false) + { + cmds ??= Array.Empty<(ushort, float)>(); + uint flags = 0x1 | (forward != 0 ? 0x2u : 0); + var b = new Body().U32(0xF74C).U32(obj).U16(3).U16(7).U16(9).Bytes(autonomous ? (byte)1 : (byte)0, 0) // aligned to 16 + .Bytes(0, 0).U16(style) // movement type 0 (state), flags, style + .U32(flags | ((uint)cmds.Length << 7)).U16(style); + if (forward != 0) b.U16(forward); + foreach (var (cmd, speed) in cmds) b.U16(cmd).U16(0x8005).F32(speed); + while (b.Length % 4 != 0) b.Bytes(0); + return b.ToArray(); + } + + private static byte[] MotionMoveToObject(uint obj, uint target) + => new Body().U32(0xF74C).U32(obj).U16(3).U16(8).U16(10).Bytes(0, 0) + .Bytes(6, 0).U16(0x3C) + .U32(target).U32(0xA9B40017).F32(10).F32(20).F32(0) + .U32(0x1EE0F).F32(0.6f).F32(0).F32(15).F32(1).F32(15).F32(0).F32(1.5f).ToArray(); + + private static byte[] MotionTurnToObject(uint obj, uint target) + => new Body().U32(0xF74C).U32(obj).U16(3).U16(9).U16(11).Bytes(0, 0) + .Bytes(8, 0).U16(0x3D) + .U32(target).F32(90).U32(0x2).F32(1).F32(90).ToArray(); + + private static byte[] UpdatePosition(uint obj, uint cell, ushort posSeq, ushort tele = 1, ushort force = 1) + => new Body().U32(0xF748).U32(obj).U32(0x04 | 0x10 | 0x20).U32(cell).F32(1).F32(2).F32(3).F32(1).F32(0) + .U16(5).U16(posSeq).U16(tele).U16(force).ToArray(); + + private static byte[] AutoPos(uint cell, ushort inst = 5, ushort srv = 6, ushort tele = 1, ushort force = 1) + => Action(0xF753, new Body().U32(cell).F32(84.5f).F32(12.25f).F32(0).F32(1).F32(0).F32(0).F32(0) + .U16(inst).U16(srv).U16(tele).U16(force).Bytes(1, 0, 0, 0)); + + // ── ring ──────────────────────────────────────────────────────────────── + + private static void RingBasics() + { + Case("ring: order, kinds, names"); + var ring = new FlightRing(16); + byte[] m = { 1, 2, 3, 4, 5 }; + fixed (byte* p = m) ring.WriteMessage(10, FlightDir.In, FlightFlags.None, p, m.Length, m.Length, 7, 0); + ring.WriteMark(11, FlightMark.EngineCall, "UseObject", 0x80000001, 0, 0, default); + ring.WriteMark(12, FlightMark.Note, null, 0, 0, 0, "hello"); + var recs = ring.Snapshot(); + Eq(recs.Length, 3, "three entries"); + Eq(recs[0].Entry.Dir, FlightDir.In, "first is the message"); + Eq(recs[0].Entry.Len, (ushort)5, "message length kept"); + Eq(recs[0].Entry.A, 7u, "fragment sequence kept"); + Eq(recs[1].Name, "UseObject", "marker name"); + Eq(recs[2].Entry.Stamp, 12L, "stamp"); + Has(FlightFormat.Describe(recs[2]), "note: hello", "note text"); + Eq(ring.Total, 3, "total"); + } + + private static void RingWrapAndTruncation() + { + Case("ring: wrap keeps the newest Capacity, long messages are cut"); + var ring = new FlightRing(16); + for (uint i = 1; i <= 40; i++) ring.WriteMark(i, FlightMark.Note, null, i, 0, 0, "x"); + var recs = ring.Snapshot(); + Eq(recs.Length, 16, "capacity entries"); + Eq(recs[0].Entry.A, 25u, "oldest kept is #25"); + Eq(recs[^1].Entry.A, 40u, "newest is #40"); + Check(recs.Zip(recs.Skip(1)).All(p => p.First.Entry.Serial < p.Second.Entry.Serial), "oldest first"); + + byte[] big = new byte[300]; + for (int i = 0; i < big.Length; i++) big[i] = (byte)i; + fixed (byte* p = big) ring.WriteMessage(99, FlightDir.Out, FlightFlags.None, p, big.Length, big.Length, 1, 0); + var last = ring.Snapshot()[^1].Entry; + Eq((int)last.Len, FlightEntry.DataCap, "kept DataCap bytes"); + Eq(last.FullLen, (ushort)300, "full length remembered"); + Check((last.Flags & FlightFlags.Truncated) != 0, "flagged truncated"); + + string longText = new string('a', 500); + ring.WriteMark(100, FlightMark.Note, null, 0, 0, 0, longText); + Has(FlightFormat.Describe(ring.Snapshot()[^1]), "...", "long note cut with ..."); + } + + private static void RingConcurrent() + { + Case("ring: 4 writers and a reader, every copied entry is whole"); + var ring = new FlightRing(256); + int stop = 0; + long torn = 0, seen = 0; + var writers = Enumerable.Range(0, 4).Select(w => new Thread(() => + { + byte[] buf = new byte[64]; + uint n = 0; + while (Volatile.Read(ref stop) == 0) + { + n++; + uint v = (uint)(w << 24) | n; + for (int i = 0; i < buf.Length; i += 4) BinaryPrimitives.WriteUInt32LittleEndian(buf.AsSpan(i), v); + fixed (byte* p = buf) ring.WriteMessage(v, FlightDir.In, FlightFlags.None, p, buf.Length, buf.Length, v, v); + } + })).ToList(); + writers.ForEach(t => t.Start()); + var sw = Stopwatch.StartNew(); + while (sw.ElapsedMilliseconds < 400) + { + foreach (var r in ring.Snapshot()) + { + seen++; + FlightEntry e = r.Entry; + uint v = e.A; + bool ok = e.B == v && e.Stamp == v; + for (int i = 0; i < e.Len && ok; i += 4) + ok = BinaryPrimitives.ReadUInt32LittleEndian(new ReadOnlySpan(e.Data + i, 4)) == v; + if (!ok) torn++; + } + } + Volatile.Write(ref stop, 1); + writers.ForEach(t => t.Join()); + Check(seen > 1000, $"read many entries ({seen})"); + Eq(torn, 0L, "torn entries"); + } + + // ── what is kept ──────────────────────────────────────────────────────── + + private static void PlayerLearnedAndFilters() + { + Case("capture: the player id comes from game events; other objects' motion is not kept"); + var c = NewCapture(); + In(c, MotionState(Player, 0x3D)); // before the id is known: dropped + Eq(Count(c, FlightDir.In), 0, "nothing kept before the player is known"); + LoginAs(c); + Eq(c.PlayerId, Player, "player id learned"); + In(c, MotionState(Player, 0x3D)); + In(c, MotionState(Other, 0x3C)); // a monster + In(c, Event(0x0013, new Body().U32(0))); // PlayerDescription: not wanted + In(c, new Body().Str("hi").Str("Bob").U32(Other).U32(2).Message(0x02BB)); // local chat: never kept + In(c, WeenieError(0x001D)); + string[] lines = Lines(c); + Eq(lines.Length, 3, "UseDone (login), player motion, WeenieError"); + Check(lines.Any(l => l.Contains("UpdateMotion 0x50000ABC")), "player motion kept"); + Check(!lines.Any(l => l.Contains("0x80012345")), "monster motion not kept"); + Check(!lines.Any(l => l.Contains("Bob")), "chat not kept"); + } + + private static void UsedObjectsKept() + { + Case("capture: messages about an object the character just used are kept, for 20 s"); + var c = NewCapture(); + LoginAs(c); + Out(c, Use(Corpse)); + In(c, new Body().U32(Corpse).U16(1).Message(0xF747)); // delete + In(c, new Body().U32(Other).U16(1).Message(0xF747)); // someone else's + In(c, MotionState(Corpse, 0x3D)); // a door opening, say + string all = string.Join("\n", Lines(c)); + Has(all, $"ObjectDelete 0x{Corpse:X8}", "used object's delete kept"); + Lacks(all, $"ObjectDelete 0x{Other:X8}", "other delete not kept"); + Has(all, $"UpdateMotion 0x{Corpse:X8}", "used object's motion kept"); + _t += 21_000; + int before = Recs(c).Length; + In(c, new Body().U32(Corpse).U16(2).Message(0xF747)); + Eq(Recs(c).Length, before, "forgotten after 20 s"); + } + + private static void PositionRateLimit() + { + Case("capture: AutonomousPosition / the player's UpdatePosition are rate-limited, changes always kept"); + var c = NewCapture(); + LoginAs(c); + int start = Recs(c).Length; + for (int i = 0; i < 10; i++) { Out(c, AutoPos(0xA9B40017)); _t += 100; } + Eq(Recs(c).Length - start, 1, "one kept in a second"); + _t += 2000; + Out(c, AutoPos(0xA9B40017)); + var last = Recs(c)[^1]; + Eq(last.Entry.B, 9u, "the next kept one counts the 9 skipped"); + Has(FlightFormat.Describe(last), "(+9 like it not kept)", "described"); + Out(c, AutoPos(0xA9B40018)); + Has(Last(c), "@0xA9B40018", "cell change kept at once"); + Out(c, AutoPos(0xA9B40018, force: 2)); + Has(Last(c), "f2", "force-position change kept at once"); + + int n = Recs(c).Length; + for (ushort i = 0; i < 5; i++) In(c, UpdatePosition(Player, 0xA9B40018, (ushort)(10 + i))); + Eq(Recs(c).Length - n, 1, "server positions for the player: one kept"); + In(c, UpdatePosition(Player, 0xA9B40018, 20, tele: 2)); + Has(Last(c), "t2", "teleport sequence change kept"); + In(c, UpdatePosition(Other, 0xA9B40018, 21)); + Lacks(Last(c), "0x80012345", "other objects' positions not kept"); + } + + private static void RetransmitDedupe() + { + Case("capture: a retransmitted copy of a message already seen is not kept twice"); + var c = NewCapture(); + LoginAs(c); + byte[] msg = UseDone(0); + In(c, msg, seq: 777); + In(c, msg, Datagram.Retransmission, seq: 777); + In(c, msg, Datagram.Retransmission, seq: 778); // first copy lost: kept, flagged + var recs = Recs(c); + Eq(recs.Count(r => r.Entry.Dir == FlightDir.In), 3, "login + one + the unseen retransmit"); + Has(FlightFormat.Describe(recs[^1]), "[retransmitted]", "flagged"); + } + + private static void ResendRequestMarker() + { + Case("capture: a resend request in a packet header becomes a marker (rate-limited)"); + var c = NewCapture(); + byte[] nak = new Body().U32(1).U32(0x1000).U32(0).U16(1).U16(0).U16(12).U16(0).U32(2).U32(555).U32(556).ToArray(); + Feed(c, false, nak); + Feed(c, false, nak); + var marks = Recs(c).Where(r => r.Entry.Dir == FlightDir.Mark).ToArray(); + Eq(marks.Length, 1, "one marker within 500 ms"); + Has(FlightFormat.Describe(marks[0]), "server asks for 2 lost packet(s) again (first seq 555)", "described"); + _t += 600; + Feed(c, true, nak); + Has(Last(c), "client asks", "client side named"); + var s = new FlightSummary(); + c.TakeCounters(ref s); + Eq(s.InResendRequests, (ushort)2, "both server requests counted"); + Eq(s.OutResendRequests, (ushort)1, "client request counted"); + Eq(s.InPackets, (ushort)2, "packets counted"); + } + + private static void EngineTagging() + { + Case("capture: an action right after the engine's call is [eng], otherwise [cli]"); + var c = NewCapture(); + LoginAs(c); + c.EngineCall("UseObject", Corpse, 0); + _t += 20; + Out(c, Use(Corpse)); + Has(Last(c), "[eng] Use 0x80068ACE", "engine use"); + Out(c, Use(Corpse)); + Has(Last(c), "[cli] Use", "a second use without a call is the client's"); + c.EngineCall("UseObject", Corpse, 0); + _t += 2000; + Out(c, Use(Corpse)); + Has(Last(c), "[cli]", "too late to match"); + c.EngineCall("CastSpell", Other, 1234); + Out(c, Action(0x004A, new Body().U32(Other).U32(1234))); + Has(Last(c), "[eng] CastTargetedSpell spell 1234 on 0x80012345", "cast matched by spell"); + c.EngineCall("ChangeCombatMode", 1, 0); + Out(c, Action(0x0053, new Body().U32(8))); + Has(Last(c), "[cli] ChangeCombatMode Magic", "different mode does not match"); + c.EngineCall("SetAutoRun", 1, 0); + Out(c, Action(0xF61C, new Body().U32(0))); + Has(Last(c), "[eng] MoveToState", "movement matched by time"); + c.EngineCall("GiveObjectTo", Corpse, Other); + Out(c, Action(0x00CD, new Body().U32(Other).U32(Corpse).U32(1))); + Has(Last(c), "[eng] GiveObjectRequest 0x80068ACE x1 to 0x80012345", "give matched on the object"); + string engineLines = string.Join("\n", Lines(c).Where(l => l.StartsWith("**"))); + Has(engineLines, "engine UseObject(0x80068ACE, 0)", "engine call markers written"); + } + + private static void EngineRepeatFolding() + { + Case("capture: identical engine calls within 1 s fold into one line plus a 'repeated' line"); + var c = NewCapture(); + for (int i = 0; i < 30; i++) { c.EngineCall("SetMotion", 0x45000005, 0); _t += 33; } + Eq(Recs(c).Length, 1, "one line while repeating"); + c.EngineCall("StopCompletely", 0, 0); + string[] lines = Lines(c); + Eq(lines.Length, 3, "first, repeated, next"); + Has(lines[1], "repeated 29 more time(s)", "count of folded calls"); + Check(Recs(c)[1].Entry.Stamp < Recs(c)[2].Entry.Stamp, "repeat line at the last repeat's time"); + c.EngineCall("StopCompletely", 0, 0); + c.FlushEngineRepeats(); + Has(Last(c), "StopCompletely(0, 0) repeated 1 more time(s)", "flush before a dump"); + } + + // ── detectors ─────────────────────────────────────────────────────────── + + private static void DetectUseRefusal() + { + Case("detector: 4 uses answered UseDone(0) with nothing opened -> use-refusal trigger"); + var c = NewCapture(); + LoginAs(c); + uint[] corpses = { 0x80000001, 0x80000002, 0x80000003, 0x80000004 }; + foreach (uint id in corpses) + { + Out(c, Use(id)); + _t += 60; + In(c, UseDone(0)); + _t += 1600; + c.Tick(); + } + string? t = c.TakeTrigger(); + Check(t != null && t.StartsWith("use-refusal: 4 uses"), $"trigger ({t})"); + Check(t != null && t.Contains("0x80000004"), "names the objects"); + Eq(c.TakeTrigger(), null, "taken once"); + } + + private static void DetectUseRefusalDelayedAnswers() + { + Case("detector: the stall shape (each answer arrives after the next use) still triggers"); + var c = NewCapture(); + LoginAs(c); + for (int i = 0; i < 6; i++) + { + Out(c, Use(Corpse)); + _t += 65; + if (i > 0) In(c, UseDone(0)); // answers the previous use + _t += 1500; + c.Tick(); + } + _t += 2000; + c.Tick(); + Check(c.TakeTrigger()?.StartsWith("use-refusal") == true, "trigger"); + } + + private static void NoTriggerWhenCorpsesOpen() + { + Case("detector: opens that work never trigger; one open resets the streak"); + var c = NewCapture(); + LoginAs(c); + for (int i = 0; i < 10; i++) + { + uint id = 0x80001000u + (uint)i; + Out(c, Use(id)); + _t += 200; + In(c, MotionTurnToObject(Player, id)); + In(c, UseDone(0)); + In(c, ViewContents(id, 0x81000001)); + _t += 2000; + c.Tick(); + } + Eq(c.TakeTrigger(), null, "no trigger"); + for (int i = 0; i < 3; i++) { Out(c, Use(Corpse)); _t += 60; In(c, UseDone(0)); _t += 1600; c.Tick(); } + In(c, ViewContents(Other)); + for (int i = 0; i < 3; i++) { Out(c, Use(Corpse)); _t += 60; In(c, UseDone(0)); _t += 1600; c.Tick(); } + Eq(c.TakeTrigger(), null, "3 + open + 3 does not trigger"); + Eq(c.RefusedStreak, 3, "streak restarted after the open"); + } + + private static void NoTriggerForDrinksAndKits() + { + Case("detector: potions (player animation), kits (use-with-target) and errors don't count"); + var c = NewCapture(); + LoginAs(c); + for (int i = 0; i < 6; i++) + { + Out(c, Use(Other)); + _t += 50; + In(c, MotionState(Player, 0x3D, cmds: new[] { ((ushort)0x1B, 1f) })); // Drink + In(c, UseDone(0)); + _t += 2000; + c.Tick(); + } + for (int i = 0; i < 6; i++) + { + Out(c, UseWithTarget(0x80000777, Player)); + _t += 2400; + In(c, UseDone(0)); + _t += 2000; + c.Tick(); + } + for (int i = 0; i < 6; i++) + { + Out(c, Use(Corpse)); + _t += 50; + In(c, UseDone(0x0037)); // ObjectGone: an answer with an error + _t += 2000; + c.Tick(); + } + Eq(c.TakeTrigger(), null, "no trigger"); + } + + private static void DetectUnanswered() + { + Case("detector: 3 uses with no UseDone at all -> use-unanswered trigger"); + var c = NewCapture(); + LoginAs(c); + for (int i = 0; i < 3; i++) { Out(c, Use(Corpse)); _t += 5100; c.Tick(); } + Check(c.TakeTrigger()?.StartsWith("use-unanswered") == true, "trigger"); + } + + private static void DetectTooBusy() + { + Case("detector: 3 'too busy' within 20 s -> too-busy trigger (WeenieError or system text)"); + var c = NewCapture(); + LoginAs(c); + In(c, WeenieError(0x001D)); _t += 15_000; + In(c, WeenieError(0x001D)); _t += 15_000; + In(c, WeenieError(0x001D)); + Eq(c.TakeTrigger(), null, "spread over 30 s: none"); + _t += 1000; + In(c, new Body().Str("You're too busy!").U32(0x1A).Message(0xF7E0)); + Check(c.TakeTrigger()?.StartsWith("too-busy") == true, "three within 20 s"); + In(c, new Body().Str("You cast Heal Self on yourself").U32(0x1A).Message(0xF7E0)); + Eq(c.TakeTrigger(), null, "other system text is not 'too busy'"); + } + + private static void DumpPolicy() + { + Case("dump policy: one automatic dump per 10 minutes"); + var p = new FlightDumpPolicy(600_000); + Check(p.TryAccept(1000, out _), "first"); + Check(!p.TryAccept(2000, out long wait), "second within the cooldown"); + Eq(wait, 599_000L, "wait reported"); + Check(!p.TryAccept(600_999, out _), "just before"); + Check(p.TryAccept(601_000, out _), "after the cooldown"); + Eq(p.Refused, 2, "refusals counted"); + } + + // ── decoding ──────────────────────────────────────────────────────────── + + private static string DescribeOut(byte[] message, FlightFlags flags = FlightFlags.None) + { + var ring = new FlightRing(16); + fixed (byte* p = message) ring.WriteMessage(0, FlightDir.Out, flags, p, message.Length, message.Length, 1, 0); + return FlightFormat.Describe(ring.Snapshot()[0]); + } + + private static string DescribeIn(byte[] message) + { + var ring = new FlightRing(16); + fixed (byte* p = message) ring.WriteMessage(0, FlightDir.In, FlightFlags.None, p, message.Length, message.Length, 1, 0); + return FlightFormat.Describe(ring.Snapshot()[0]); + } + + private static void DecodeOutbound() + { + Case("decode: client actions"); + _actionSeq = 400; + Has(DescribeOut(Use(Corpse)), "Use 0x80068ACE #400", "use"); + Has(DescribeOut(UseWithTarget(0x80000777, Player)), "UseWithTarget 0x80000777 on 0x50000ABC", "use with target"); + Has(DescribeOut(Action(0x0048, new Body().U32(157))), "CastUntargetedSpell spell 157", "untargeted cast"); + Has(DescribeOut(Action(0x004A, new Body().U32(Other).U32(2000))), "CastTargetedSpell spell 2000 on 0x80012345", "targeted cast"); + Has(DescribeOut(Action(0x0053, new Body().U32(2))), "ChangeCombatMode Melee", "combat mode"); + Has(DescribeOut(Action(0x0008, new Body().U32(Other).U32(2).F32(0.5f))), "MeleeAttack 0x80012345 height 2 power 0.5", "melee"); + Has(DescribeOut(Action(0x0019, new Body().U32(Other).U32(Player).I32(0))), "PutItemInContainer 0x80012345 into 0x50000ABC slot 0", "put item"); + Has(DescribeOut(Action(0x001B, new Body().U32(Other))), "DropItem 0x80012345", "drop"); + Has(DescribeOut(Action(0x0195, new Body().U32(Corpse))), "NoLongerViewingContents 0x80068ACE", "no longer viewing"); + Has(DescribeOut(Action(0x01B7, new Body())), "CancelAttack", "cancel attack"); + Has(DescribeOut(Action(0xF61B, new Body().F32(0.8f).F32(0).F32(1).F32(5).U16(1).U16(2).U16(3).U16(4))), "Jump extent 0.8 velocity (0,1,5) seq i1/s2/t3/f4", "jump"); + Has(DescribeOut(AutoPos(0xA9B40017)), "AutonomousPosition @0xA9B40017 (84.5,12.25,0) yaw 0 seq i5/s6/t1/f1 contact=1", "autonomous position"); + string talk = DescribeOut(Action(0x0015, new Body().Str("my secret words"))); + Has(talk, "Talk (", "talk named"); + Lacks(talk, "secret", "talk text not written"); + Has(DescribeOut(Action(0x9999, new Body().U32(1).U32(2))), "action 0x9999 args 0x1 0x2", "unknown action raw"); + Has(DescribeOut(new Body().U32(0x1234).Message(0xF7C8)), "CharacterEnterWorldRequest", "non-action message"); + Has(DescribeOut(Use(Corpse), FlightFlags.Engine), "[eng] Use", "engine tag"); + } + + private static void DecodeMoveToState() + { + Case("decode: MoveToState raw motion state, commands, position, sequences"); + // hold key, style, forward command + hold + speed, turn command + speed, one command. + uint flags = 0x001 | 0x002 | 0x004 | 0x008 | 0x010 | 0x100 | 0x400; + var b = new Body().U32(flags | (1u << 11)) + .U32(2).U32(0x80000049).U32(0x44000007).U32(2).F32(1.25f).U32(0x6500000D).F32(1.5f) + .U16(0x31).U16(0x8007).F32(1) + .U32(0xA9B40017).F32(84.5f).F32(12.25f).F32(0).F32(0.7071f).F32(0).F32(0).F32(0.7071f) + .U16(11).U16(12).U16(13).U16(14).Bytes(1, 0, 0, 0); + string s = DescribeOut(Action(0xF61C, b)); + Has(s, "MoveToState hold=Run style=Magic fwd=RunForward(Run)@1.25 turn=TurnRight@1.5", "fields"); + Has(s, "cmds=[MagicHeal@1#7a]", "command with autonomous sequence"); + Has(s, "@0xA9B40017 (84.5,12.25,0) yaw 90", "position"); + Has(s, "seq i11/s12/t13/f14 contact=1", "sequences"); + Lacks(s, "...", "not cut"); + Has(DescribeOut(Action(0xF61C, new Body().U32(0).U32(0xA9B40017).F32(1).F32(2).F32(3).F32(1).F32(0).F32(0).F32(0).U16(1).U16(1).U16(1).U16(1).Bytes(1, 0, 0, 0))), + "(no motion: stand still)", "empty state"); + } + + private static void DecodeInboundEvents() + { + Case("decode: server game events"); + Has(DescribeIn(UseDone(0)), "UseDone err 0x0000 none #42", "use done"); + Has(DescribeIn(UseDone(0x0037)), "UseDone err 0x0037 ObjectGone", "use done error"); + Has(DescribeIn(ViewContents(Corpse, 1, 2, 3)), "ViewContents 0x80068ACE items 3: 0x00000001 0x00000002 0x00000003", "view contents"); + Has(DescribeIn(Event(0x0052, new Body().U32(Corpse))), "CloseGroundContainer 0x80068ACE", "close ground container"); + Has(DescribeIn(WeenieError(0x001D)), "WeenieError 0x001D YoureTooBusy", "too busy"); + Has(DescribeIn(WeenieError(0x0402)), "YourSpellFizzled", "fizzle"); + Has(DescribeIn(Event(0x028B, new Body().U32(0x0036).Str("Interrupted!"))), "WeenieErrorWithString 0x0036 ActionCancelled \"Interrupted!\"", "error with string"); + Has(DescribeIn(Event(0x00A0, new Body().U32(Other).U32(0x0020))), "InventoryServerSaveFailed 0x80012345 err 0x0020", "save failed"); + Has(DescribeIn(Event(0x0022, new Body().U32(Other).U32(Player).I32(3).U32(0))), "InventoryPutObjInContainer 0x80012345 in 0x50000ABC slot 3", "put in container"); + Has(DescribeIn(Event(0x01A7, new Body().U32(0))), "AttackDone err 0x0000", "attack done"); + Has(DescribeIn(Event(0x01B8, new Body())), "CombatCommenceAttack", "commence attack"); + Has(DescribeIn(Event(0x01B1, new Body().Str("Drudge Ravener").U32(1).Bytes(BitConverter.GetBytes(0.4)).U32(37).U32(1).U32(0).U32(0))), + "AttackerNotification hit 'Drudge Ravener' for 37 (crit), 40% left", "attacker notification"); + var ench = new Body().U16(2053).U16(1).U16(5).U16(0).U32(400).Bytes(BitConverter.GetBytes(0.0)).Bytes(BitConverter.GetBytes(1800.0)).U32(Player); + Has(DescribeIn(Event(0x02C2, ench)), "MagicUpdateEnchantment spell 2053 layer 1 duration 1800 s caster 0x50000ABC", "enchantment"); + Has(DescribeIn(Event(0x02C3, new Body().U16(2053).U16(1))), "MagicRemoveEnchantment spell 2053 layer 1", "remove enchantment"); + Has(DescribeIn(Event(0x02EB, new Body().Str("You can't do that"))), "TransientString \"You can't do that\"", "transient string"); + Has(DescribeIn(new Body().Str("You're too busy!").U32(0x1A).Message(0xF7E0)), "ServerMessage \"You're too busy!\" (chat type 26)", "system text"); + } + + private static void DecodeMotion() + { + Case("decode: UpdateMotion state, move-to-object, turn-to-object"); + string s = DescribeIn(MotionState(Player, 0x49, forward: 0x03, cmds: new[] { ((ushort)0x31, 1f) })); + Has(s, "UpdateMotion 0x50000ABC server State style=Magic fwd=Ready cmds=[MagicHeal@1#5a] seq i3/m7/c9", "state"); + Lacks(s, "...", "whole"); + Has(DescribeIn(MotionState(Player, 0x3D, autonomous: true)), "autonomous State style=NonCombat", "autonomous flag"); + string mt = DescribeIn(MotionMoveToObject(Player, Corpse)); + Has(mt, "MoveToObject style=HandCombat target 0x80068ACE origin @0xA9B40017 (10,20,0) params 0x1EE0F dist 0.6", "move to object"); + Has(mt, "runrate 1.5 seq i3/m8/c10", "run rate and sequences"); + Has(DescribeIn(MotionTurnToObject(Player, Corpse)), "TurnToObject style=NonCombat target 0x80068ACE heading 90 params 0x2 speed 1", "turn to object"); + } + + private static void DecodePositionAndObjects() + { + Case("decode: positions, teleport, object messages"); + Has(DescribeIn(UpdatePosition(Player, 0xA9B40017, 33, 4, 5)), "UpdatePosition 0x50000ABC @0xA9B40017 (1,2,3) yaw 0 grounded seq i5/p33/t4/f5", "update position"); + Has(DescribeIn(new Body().U16(7).U16(0).Message(0xF751)), "PlayerTeleport seq t7", "teleport"); + Has(DescribeIn(new Body().U32(Corpse).U16(2).U16(0).Message(0xF747)), "ObjectDelete 0x80068ACE i2", "delete"); + Has(DescribeIn(new Body().U32(Player).F32(0).F32(0).F32(5).F32(0).F32(0).F32(0).U16(1).U16(2).Message(0xF74E)), "VectorUpdate 0x50000ABC velocity (0,0,5)", "vector"); + Has(DescribeIn(new Body().U32(Player).U32(0x57).F32(1).Message(0xF755)), "PlayEffect 0x50000ABC script 0x57", "effect"); + Has(DescribeIn(new Body().Bytes(1).U32(Other).U32(9).U32(90).Message(0x0197)), "SetStackSize 0x80012345 size 9", "stack size"); + } + + private static void DecodeMarkers() + { + Case("decode: markers and the per-second summary"); + var c = NewCapture(); + c.Mark(FlightMark.BusyIncrement, 1, 1); + c.Mark(FlightMark.BusyForceClear, 2, 0, text: "with the motion flush"); + c.Mark(FlightMark.BusyWatchdog, 1, 0, 4100, "real m_cBusy stuck"); + c.Mark(FlightMark.GateCleared, 3, Corpse, text: "manual (/rc unlockactions)"); + c.Mark(FlightMark.GateCleared, 0, 0, text: "watchdog"); + c.Mark(FlightMark.EngineInit, 3); + c.Mark(FlightMark.Trigger, text: "plugin: loot wedge"); + var s = new FlightSummary { RealBusy = 1, ShadowBusy = 0, PendingType = 3, PendingObject = Corpse, Attacking = 0, Gesture = 1, InPackets = 12, InMessages = 30, InKept = 4, OutPackets = 8, OutMessages = 9, OutKept = 2, SendErrors = 1 }; + c.WriteSummary(s); + string all = string.Join("\n", Lines(c)); + Has(all, "** m_cBusy +1 -> real 1 (engine count 1)", "increment"); + Has(all, "m_cBusy force-cleared (was real 2, engine count 0) - with the motion flush", "force clear"); + Has(all, "busy watchdog (real m_cBusy stuck): real 1, engine count 0, stuck 4100 ms", "watchdog"); + Has(all, "action gate cleared: pending item request type 3 on 0x80068ACE (manual (/rc unlockactions))", "request gate"); + Has(all, "action gate cleared: attacking flag (watchdog)", "attack gate"); + Has(all, "engine generation 3 started (hot reload", "hot reload"); + Has(all, "AUTO DUMP TRIGGER: plugin: loot wedge", "trigger"); + Has(all, "-- 1s: in 12 pk/30 msg (4 kept), out 8 pk/9 msg (2 kept)", "summary counters"); + Has(all, "SEND ERRORS 1", "send errors"); + Has(all, "m_cBusy 1 (engine 0) | item request type 3 on 0x80068ACE | attacking 0 | gesture 1", "summary state"); + var u = new FlightSummary { RealBusy = FlightSummary.Unknown, PendingType = 0xFFFFFFFF, Attacking = 255, Gesture = 255 }; + c.WriteSummary(u); + Has(Last(c), "m_cBusy ? (engine 0) | item request ? | attacking ? | gesture ?", "unknowns"); + } + + private static void DecodeTruncatedAndGarbage() + { + Case("decode: cut-off messages end with '...', garbage never throws"); + // A MoveToState with 12 commands is longer than DataCap. + var b = new Body().U32(0x002 | (12u << 11)).U32(0x80000049); + for (int i = 0; i < 12; i++) b.U16(0x31).U16((ushort)i).F32(1); + b.U32(0xA9B40017).F32(1).F32(2).F32(3).F32(1).F32(0).F32(0).F32(0).U16(1).U16(1).U16(1).U16(1).Bytes(1, 0, 0, 0); + string s = DescribeOut(Action(0xF61C, b)); + Has(s, "...", "cut off"); + Lacks(s, "undecodable", "no exception"); + + var rnd = new Random(7); + int bad = 0; + for (int i = 0; i < 20000; i++) + { + int len = rnd.Next(0, 130); + byte[] m = new byte[len]; + rnd.NextBytes(m); + if (len >= 4 && rnd.Next(2) == 0) + { + uint[] ops = { 0xF7B0, 0xF7B1, 0xF74C, 0xF748, 0xF7E0, 0xF751, 0xF755, 0x0197 }; + BinaryPrimitives.WriteUInt32LittleEndian(m, ops[rnd.Next(ops.Length)]); + } + string d1 = rnd.Next(2) == 0 ? DescribeIn(m) : DescribeOut(m); + if (d1.Contains("undecodable")) bad++; + } + Eq(bad, 0, "random messages decoded without an exception"); + + var c = NewCapture(); + int crashes = 0; + for (int i = 0; i < 20000; i++) + { + byte[] d = new byte[rnd.Next(0, 200)]; + rnd.NextBytes(d); + if (d.Length >= 20 && rnd.Next(2) == 0) + { + BinaryPrimitives.WriteUInt32LittleEndian(d.AsSpan(4), 0x4); + BinaryPrimitives.WriteUInt16LittleEndian(d.AsSpan(16), (ushort)(d.Length - 20)); + } + try { Feed(c, rnd.Next(2) == 0, d); } catch { crashes++; } + } + Eq(crashes, 0, "random datagrams never throw"); + } + + private static void DumpFormat() + { + Case("dump: header, legend, one line per entry, time relative to the request"); + var c = NewCapture(); + LoginAs(c); + c.EngineCall("UseObject", Corpse, 0); + _t += 5; + Out(c, Use(Corpse)); + _t += 60; + In(c, UseDone(0)); + long zero = _t; + _t += 250; + c.Mark(FlightMark.Note, text: "after"); + var sw = new StringWriter(); + var recs = c.Ring.Snapshot(); + FlightFormat.WriteDump(sw, recs, zero, new DateTime(2026, 10, 6, 12, 0, 0), 1000, new[] { "Reason: test" }); + string[] lines = sw.ToString().Split(Environment.NewLine); + Eq(lines[0], "RynthCore flight recorder dump", "title"); + Eq(lines[1], "Reason: test", "header line"); + Has(lines[2], $"Entries: {recs.Length}", "entry count"); + Check(lines.Any(l => l.StartsWith("How to read")), "legend"); + string[] body = lines.Where(l => l.Contains(" ms ")).ToArray(); + Eq(body.Length, recs.Length, "one line per entry"); + Has(body.First(l => l.Contains("[eng] Use")), " -60 ms 11:59:59.940 -> [eng] Use 0x80068ACE", "outbound line"); + Has(body.First(l => l.Contains("UseDone") && l.Contains("12:00:00.000")), " 0 ms 12:00:00.000 <- UseDone err 0x0000 none", "inbound line at time 0"); + Has(body.First(l => l.Contains("note")), " +250 ms 12:00:00.250 ** note: after", "marker after the request"); + } + + // ── sample ────────────────────────────────────────────────────────────── + + /// "--sample": a made-up corpse-use stall, dumped to the console (what a dump looks like). + private static void SampleDump() + { + Console.WriteLine(); + Console.WriteLine("Sample dump (synthetic stall):"); + var c = NewCapture(4096); + LoginAs(c); + var s = new FlightSummary { RealBusy = 0, PendingType = 0, Attacking = 0, Gesture = 0, InPackets = 14, InMessages = 22, InKept = 3, OutPackets = 9, OutMessages = 7, OutKept = 2 }; + c.WriteSummary(s); + // A normal open: use, server turns the character, UseDone, contents. + c.EngineCall("UseObject", 0x80068ACD, 0); _t += 3; + Out(c, Use(0x80068ACD)); c.Mark(FlightMark.BusyIncrement, 1, 1); _t += 120; + In(c, MotionTurnToObject(Player, 0x80068ACD)); _t += 180; + In(c, UseDone(0)); In(c, ViewContents(0x80068ACD, 0x81000001, 0x81000002)); _t += 400; + Out(c, Action(0x0195, new Body().U32(0x80068ACD))); _t += 900; + // The onset: use in melee stance, a peace-mode swap 3 ms later. + c.EngineCall("UseObject", Corpse, 0); _t += 2; + Out(c, Use(Corpse)); _t += 3; + c.EngineCall("ChangeCombatMode", 1, 0); _t += 1; + Out(c, Action(0x0053, new Body().U32(1))); _t += 40; + In(c, MotionState(Player, 0x3D)); _t += 1500; + for (int i = 0; i < 4; i++) + { + c.EngineCall("UseObject", Corpse, 0); _t += 2; + Out(c, Use(Corpse)); _t += 65; + In(c, UseDone(0)); _t += 1600; + c.Tick(); + c.WriteSummary(s); + } + string? why = c.TakeTrigger(); + if (why != null) c.Mark(FlightMark.Trigger, text: "engine: " + why); + long zero = _t; + _t += 3000; + var recs = c.Ring.Snapshot(); + var w = new StringWriter(); + FlightFormat.WriteDump(w, recs, zero, new DateTime(2026, 10, 6, 6, 18, 50), 1000, new[] { "Reason: auto: " + (why ?? "?") }); + Console.WriteLine(w.ToString()); + } + + // ── captures ──────────────────────────────────────────────────────────── + + private static void Replay(string path) + { + Case($"replay {Path.GetFileName(path)} (server datagrams through the recorder)"); + byte[] all = File.ReadAllBytes(path); + if (all.Length < 4 || all[0] != 'R' || all[1] != 'N' || all[2] != 'C' || all[3] != '1') + { + Check(false, "not an RNC1 capture"); + return; + } + var c = new FlightCapture(16384, Clock, 1000); + int pos = 4, datagrams = 0; + long firstStamp = -1; + while (pos + 6 <= all.Length) + { + uint stamp = BinaryPrimitives.ReadUInt32LittleEndian(all.AsSpan(pos)); + int len = BinaryPrimitives.ReadUInt16LittleEndian(all.AsSpan(pos + 4)); + pos += 6; + if (pos + len > all.Length) break; + if (firstStamp < 0) firstStamp = stamp; + _t = 1_000_000 + (stamp - firstStamp); + fixed (byte* p = &all[pos]) c.OnDatagram(false, p, len); + pos += len; + datagrams++; + } + var recs = c.Ring.Snapshot(); + Console.WriteLine($" {datagrams} datagrams, {recs.Length} entries kept, player 0x{c.PlayerId:X8}"); + int undecodable = 0; + foreach (var r in recs.TakeLast(60)) + Console.WriteLine(" " + FlightFormat.Line(r, recs[^1].Entry.Stamp, DateTime.Now, 1000)); + foreach (var r in recs) if (FlightFormat.Describe(r).Contains("undecodable")) undecodable++; + Eq(undecodable, 0, "every kept entry decodes"); + } + + // ── cost ──────────────────────────────────────────────────────────────── + + private static void Performance() + { + Console.WriteLine(); + Console.WriteLine("Cost (hot path, real Stopwatch clock):"); + var c = new FlightCapture(16384, Stopwatch.GetTimestamp, Stopwatch.Frequency); + LoginAs(c); + byte[] autoPos = One(AutoPos(0xA9B40017)); + byte[] monsterPos = One(UpdatePosition(Other, 0xA9B40017, 1)); + byte[] playerMotion = One(MotionState(Player, 0x3D)); + byte[] create = One(new byte[400]); + BinaryPrimitives.WriteUInt32LittleEndian(create.AsSpan(36), 0xF745); // CreateObject: not kept + + void Run(string what, byte[] d, bool outbound, int n) + { + fixed (byte* p = d) + { + for (int i = 0; i < 2000; i++) c.OnDatagram(outbound, p, d.Length); // warm up + long before = GC.GetAllocatedBytesForCurrentThread(); + long t0 = Stopwatch.GetTimestamp(); + for (int i = 0; i < n; i++) c.OnDatagram(outbound, p, d.Length); + long ticks = Stopwatch.GetTimestamp() - t0; + long alloc = GC.GetAllocatedBytesForCurrentThread() - before; + double ns = ticks * 1e9 / Stopwatch.Frequency / n; + Console.WriteLine($" {what,-44} {ns,7:0} ns/datagram, {alloc} bytes allocated over {n}"); + _case = "cost"; + Eq(alloc, 0L, $"{what}: no allocation"); + } + } + + Run("AutonomousPosition (rate-limited away)", autoPos, true, 200_000); + Run("monster UpdatePosition (filtered out)", monsterPos, false, 200_000); + Run("CreateObject-size message (not kept)", create, false, 200_000); + Run("player UpdateMotion (kept: 120-byte copy)", playerMotion, false, 200_000); + Console.WriteLine($" ring memory: {c.Ring.Bytes / 1024} KB for {c.Ring.Capacity} entries ({sizeof(FlightEntry)} bytes each)"); + Console.WriteLine(_failed == 0 ? "COST CHECKS PASSED." : $"{_failed} FAILED (incl. cost)."); + } +} diff --git a/tools/InstallPathsTests/InstallPathsTests.csproj b/tools/InstallPathsTests/InstallPathsTests.csproj new file mode 100644 index 0000000..ca6334d --- /dev/null +++ b/tools/InstallPathsTests/InstallPathsTests.csproj @@ -0,0 +1,24 @@ + + + + + Exe + net10.0-windows + enable + enable + true + InstallPathsTests + + + + + + + diff --git a/tools/InstallPathsTests/Program.cs b/tools/InstallPathsTests/Program.cs new file mode 100644 index 0000000..c2d2e77 --- /dev/null +++ b/tools/InstallPathsTests/Program.cs @@ -0,0 +1,167 @@ +using RynthCore.Install; + +namespace InstallPathsTests; + +/// +/// RynthInstallPaths: where RynthCore and RynthSuite live. Order is environment, HKCU, HKLM, +/// then today's C:\Games folders. Idea from Silentkelpie (rynth PR #1); re-implemented here. +/// +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + NothingSetGivesTodaysFolders(); + Order(); + UnusableValuesAreSkipped(); + Tidying(); + SpacesInPaths(); + ThrowingSourceFallsThrough(); + RealRegistryMissingValueIsNull(); + + Console.WriteLine($"{_checks} check(s), {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"[FAIL] {_case}: {what}"); + } + + private static void Eq(string? actual, string? expected, string what) + => Check(string.Equals(actual, expected, StringComparison.Ordinal), $"{what}: expected '{expected}', got '{actual}'"); + + /// An in-memory environment and registry; records what was asked. + private sealed class Fake : IInstallSettingSource + { + public readonly Dictionary Env = new(); + public readonly Dictionary User = new(); + public readonly Dictionary Machine = new(); + public readonly List Asked = new(); + public bool Throw; + + public string? EnvironmentVariable(string name) { Asked.Add("env:" + name); if (Throw) throw new InvalidOperationException(); return Env.GetValueOrDefault(name); } + public string? CurrentUser(string valueName) { Asked.Add("hkcu:" + valueName); if (Throw) throw new UnauthorizedAccessException(); return User.GetValueOrDefault(valueName); } + public string? LocalMachine(string valueName) { Asked.Add("hklm:" + valueName); if (Throw) throw new IOException(); return Machine.GetValueOrDefault(valueName); } + } + + private static string Core(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.CoreEnvironmentVariable, + RynthInstallPaths.CoreValueName, RynthInstallPaths.DefaultCoreDir, f); + + private static string Suite(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.SuiteEnvironmentVariable, + RynthInstallPaths.SuiteValueName, RynthInstallPaths.DefaultSuiteDir, f); + + private static void NothingSetGivesTodaysFolders() + { + _case = "nothing set"; + var f = new Fake(); + Eq(Core(f), @"C:\Games\RynthCore", "core default is today's folder"); + Eq(Suite(f), @"C:\Games\RynthSuite", "suite default is today's folder"); + Eq(Path.Combine(Core(f), "Logs"), @"C:\Games\RynthCore\Logs", "logs under the default"); + Eq(Path.Combine(Suite(f), "RynthAi"), @"C:\Games\RynthSuite\RynthAi", "RynthAi under the default"); + Check(f.Asked.Contains("env:RYNTHCORE_DIR") && f.Asked.Contains("hkcu:CoreDir") && f.Asked.Contains("hklm:CoreDir"), + "all three sources asked for the core folder"); + Check(f.Asked.Contains("env:RYNTHSUITE_DIR") && f.Asked.Contains("hkcu:SuiteDir") && f.Asked.Contains("hklm:SuiteDir"), + "all three sources asked for the suite folder"); + Eq(RynthInstallPaths.RegistryKey, @"Software\Rynth", "registry key"); + } + + private static void Order() + { + _case = "order"; + var f = new Fake(); + f.Machine["CoreDir"] = @"D:\Machine\RynthCore"; + Eq(Core(f), @"D:\Machine\RynthCore", "HKLM beats the default"); + + f.User["CoreDir"] = @"E:\User\RynthCore"; + Eq(Core(f), @"E:\User\RynthCore", "HKCU beats HKLM"); + + f.Env["RYNTHCORE_DIR"] = @"F:\Dev\RynthCore"; + Eq(Core(f), @"F:\Dev\RynthCore", "environment beats HKCU"); + + f.Asked.Clear(); + Core(f); + Check(f.Asked.Count == 1 && f.Asked[0] == "env:RYNTHCORE_DIR", "a usable environment value stops the search"); + + // The two folders are independent. + var g = new Fake(); + g.User["SuiteDir"] = @"E:\Suite"; + Eq(Core(g), @"C:\Games\RynthCore", "a suite setting leaves the core folder alone"); + Eq(Suite(g), @"E:\Suite", "suite from HKCU"); + g.Env["RYNTHCORE_DIR"] = @"F:\Core"; + Eq(Suite(g), @"E:\Suite", "a core variable leaves the suite folder alone"); + } + + private static void UnusableValuesAreSkipped() + { + _case = "unusable values"; + foreach (string? bad in new[] { null, "", " ", "\"\"", @"Games\RynthCore", @"..\RynthCore", "RynthCore", "C:", @"C:Games", "D:\\bad|name", "\0" }) + { + var f = new Fake(); + f.Env["RYNTHCORE_DIR"] = bad; + f.User["CoreDir"] = bad; + f.Machine["CoreDir"] = @"D:\Machine"; + Eq(Core(f), @"D:\Machine", $"'{bad}' in env and HKCU falls through to HKLM"); + + var g = new Fake(); + g.Machine["CoreDir"] = bad; + Eq(Core(g), @"C:\Games\RynthCore", $"'{bad}' in HKLM falls back to the default"); + } + } + + private static void Tidying() + { + _case = "tidying"; + Eq(RynthInstallPaths.Normalize(@"D:\Rynth\"), @"D:\Rynth", "trailing separator dropped"); + Eq(RynthInstallPaths.Normalize(@"D:\Rynth\\"), @"D:\Rynth", "doubled trailing separator dropped"); + Eq(RynthInstallPaths.Normalize("D:/Rynth/Core/"), @"D:\Rynth\Core", "forward slashes"); + Eq(RynthInstallPaths.Normalize(" \"D:\\Rynth\" "), @"D:\Rynth", "whitespace and quotes trimmed"); + Eq(RynthInstallPaths.Normalize(@"D:\Rynth\.\Core\..\Suite"), @"D:\Rynth\Suite", "dot segments resolved"); + Eq(RynthInstallPaths.Normalize(@"D:\"), @"D:\", "a drive root stays a root"); + Eq(RynthInstallPaths.Normalize(@"\\nas\games\RynthCore\"), @"\\nas\games\RynthCore", "UNC path"); + } + + private static void SpacesInPaths() + { + _case = "spaces"; + var f = new Fake(); + f.User["SuiteDir"] = @"C:\Program Files (x86)\Rynth Suite\"; + Eq(Suite(f), @"C:\Program Files (x86)\Rynth Suite", "HKCU value with spaces"); + Eq(Path.Combine(Suite(f), "RynthAi", "MetaFiles"), @"C:\Program Files (x86)\Rynth Suite\RynthAi\MetaFiles", "joined path keeps the spaces"); + + var g = new Fake(); + g.Env["RYNTHCORE_DIR"] = "\"D:\\My Games\\Rynth Core\""; + Eq(Core(g), @"D:\My Games\Rynth Core", "quoted environment value with spaces"); + + var h = new Fake(); + h.Machine["CoreDir"] = @" E:\Tom's Games\RynthCore "; + Eq(Core(h), @"E:\Tom's Games\RynthCore", "HKLM value with spaces and an apostrophe, padded"); + } + + private static void ThrowingSourceFallsThrough() + { + _case = "throwing source"; + var f = new Fake { Throw = true }; + Eq(Core(f), @"C:\Games\RynthCore", "every source throws -> default, no exception"); + Check(f.Asked.Count == 3, "all three sources were still tried"); + } + + private static void RealRegistryMissingValueIsNull() + { + _case = "real registry (read only)"; + string missing = "NoSuchValue-" + Guid.NewGuid().ToString("N"); + Check(SystemInstallSettings.Instance.CurrentUser(missing) == null, "HKCU read of a missing value is null"); + Check(SystemInstallSettings.Instance.LocalMachine(missing) == null, "HKLM read of a missing value is null"); + Check(SystemInstallSettings.Instance.EnvironmentVariable(missing) == null, "missing environment variable is null"); + // Whatever this machine has set, the live answers are absolute folders. + Check(Path.IsPathFullyQualified(RynthInstallPaths.CoreDir), "CoreDir is absolute: " + RynthInstallPaths.CoreDir); + Check(Path.IsPathFullyQualified(RynthInstallPaths.SuiteDir), "SuiteDir is absolute: " + RynthInstallPaths.SuiteDir); + Eq(RynthInstallPaths.CoreLogsDir, Path.Combine(RynthInstallPaths.CoreDir, "Logs"), "CoreLogsDir"); + Eq(RynthInstallPaths.RynthAiDir, Path.Combine(RynthInstallPaths.SuiteDir, "RynthAi"), "RynthAiDir"); + } +} diff --git a/tools/ItemHudTests/ItemHudTests.csproj b/tools/ItemHudTests/ItemHudTests.csproj new file mode 100644 index 0000000..c5f9588 --- /dev/null +++ b/tools/ItemHudTests/ItemHudTests.csproj @@ -0,0 +1,24 @@ + + + + + Exe + net10.0 + enable + enable + true + ItemHudTests + + + + + + + diff --git a/tools/ItemHudTests/Program.cs b/tools/ItemHudTests/Program.cs new file mode 100644 index 0000000..81ec7ed --- /dev/null +++ b/tools/ItemHudTests/Program.cs @@ -0,0 +1,203 @@ +using RynthCore.Engine.UI.Data; + +namespace ItemHudTests; + +/// The Item Count / Mini Remote model: counting, slot lookup, edits and item_huds.txt. +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + CountSumsStacks(); + ResolveSlots(); + CountListEdits(); + SlotEdits(); + FileRoundTrip(); + PerCharacterSections(); + UnknownLinesKept(); + BadFileValues(); + EditsAreImmutable(); + + Console.WriteLine(_failed == 0 ? $"PASS ({_checks} assertions)" : $"FAIL ({_failed} of {_checks} assertions)"); + return _failed == 0 ? 0 : 1; + } + + private static void Case(string name) { _case = name; Console.WriteLine("ok " + name); } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"FAIL {_case}: {what}"); + } + + private static readonly HudItem[] Pack = + { + new(0x80000001, "Mana Scarab", 25), + new(0x80000002, "Mana Scarab", 100), + new(0x80000003, "mana scarab", 3), // any case + new(0x80000004, "Prismatic Taper", 0), // a single item can report 0 + new(0x80000005, "Healing Kit", 1), + new(0x80000006, "Greater Mana Scarab", 7),// a different item + new(0x80000007, "Deadly Arrow", 250), // worn (wielded ammo) + }; + + private static void CountSumsStacks() + { + Case("CountSumsStacks"); + Check(ItemHudMath.Count(Pack, "Mana Scarab") == 128, "every Mana Scarab stack summed, any case"); + Check(ItemHudMath.Count(Pack, "Prismatic Taper") == 1, "an item without a stack size counts 1"); + Check(ItemHudMath.Count(Pack, "Deadly Arrow") == 250, "worn ammo counts"); + Check(ItemHudMath.Count(Pack, "Lockpick") == 0, "none carried is 0"); + Check(ItemHudMath.Count(Pack, "Scarab") == 0, "the name must match, not just contain"); + Check(ItemHudMath.Count(Array.Empty(), "Mana Scarab") == 0, "no items"); + } + + private static void ResolveSlots() + { + Case("ResolveSlots"); + Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0x80000001, "Mana Scarab")) == 0x80000001, "the same object while carried"); + Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0x8000FFFF, "Mana Scarab")) == 0x80000002, "gone (merged/used up): the largest stack with its name"); + Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0x8000FFFF, "Lockpick")) == 0, "nothing with that name: 0"); + Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0, "healing kit")) == 0x80000005, "no id: by name, any case"); + Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0x80000005, "")) == 0x80000005, "no name: by id"); + Check(ItemHudMath.TryFind(Pack, 0x80000004, out HudItem t) && t.Name == "Prismatic Taper", "TryFind by id"); + Check(!ItemHudMath.TryFind(Pack, 0x12345678, out _), "TryFind misses"); + } + + private static void CountListEdits() + { + Case("CountListEdits"); + var c = ItemHudCharacter.Empty; + c = c.WithCount(" Mana Scarab ", out string m1); + Check(c.Counts.SequenceEqual(new[] { "Mana Scarab" }) && m1.StartsWith("Counting", StringComparison.Ordinal), "added, trimmed"); + var same = c.WithCount("MANA SCARAB", out string m2); + Check(ReferenceEquals(same, c) && m2.Contains("already"), "a duplicate in another case is refused"); + Check(ReferenceEquals(c.WithCount(" ", out string m3), c) && m3.Length > 0, "an empty name is refused"); + c = c.WithCount("Healing Kit", out _).WithCount("Lock|pick", out _); + Check(c.Counts.Length == 3 && c.Counts[2] == "Lock pick", "a bar can't break the file format"); + c = c.WithoutCount(c.IndexOfCount("healing kit")); + Check(c.Counts.SequenceEqual(new[] { "Mana Scarab", "Lock pick" }), "removed by name, any case"); + Check(ReferenceEquals(c.WithoutCount(9), c), "a bad index changes nothing"); + var full = ItemHudCharacter.Empty; + for (int i = 0; i < ItemHudCharacter.MaxCounts + 3; i++) full = full.WithCount("Item " + i, out _); + Check(full.Counts.Length == ItemHudCharacter.MaxCounts, "capped"); + string longName = new('x', 200); + Check(ItemHudCharacter.Empty.WithCount(longName, out _).Counts[0].Length == ItemHudCharacter.MaxNameLength, "long names cut"); + } + + private static void SlotEdits() + { + Case("SlotEdits"); + var c = ItemHudCharacter.Empty; + Check(c.Slots.Length == ItemHudCharacter.DefaultSlots && c.Slots.All(s => s == null), "8 empty slots by default"); + c = c.WithSlot(2, new RemoteSlot(0x80000005, "Healing Kit")); + Check(c.Slots[2] == new RemoteSlot(0x80000005, "Healing Kit"), "slot set"); + Check(ReferenceEquals(c.WithSlot(99, new RemoteSlot(1, "x")), c), "out of range: no change"); + c = c.WithSlotCount(12); + Check(c.Slots.Length == 12 && c.Slots[2]?.Name == "Healing Kit", "more slots keep the filled ones"); + c = c.WithSlotCount(1); + Check(c.Slots.Length == ItemHudCharacter.MinSlots && c.Slots[2]?.Name == "Healing Kit", "at least 4 slots"); + c = c.WithSlotCount(1000); + Check(c.Slots.Length == ItemHudCharacter.MaxSlots, "at most 24"); + c = c.WithSlot(2, null); + Check(c.Slots[2] == null, "cleared"); + } + + private static ItemHudFile.Contents RoundTrip(ItemHudFile.Contents c) => + ItemHudFile.Parse(ItemHudFile.Write(c).Split('\n')); + + private static void FileRoundTrip() + { + Case("FileRoundTrip"); + var c = new ItemHudFile.Contents(); + var d = ItemHudCharacter.Empty.WithCount("Mana Scarab", out _).WithCount("Deadly Arrow", out _) + .WithSlotCount(12).WithSlot(0, new RemoteSlot(0x80123456, "Healing Kit")).WithSlot(11, new RemoteSlot(0x8012ABCD, "Stamina Elixir")); + c.Set("Aelrynth/Drakkon", d); + string text = ItemHudFile.Write(c); + Check(text.StartsWith(ItemHudFile.Header, StringComparison.Ordinal), "header first"); + Check(text.Contains("[Aelrynth/Drakkon]\n") && text.Contains("count=Mana Scarab\n") && text.Contains("slots=12\n") + && text.Contains("slot=0|0x80123456|Healing Kit\n") && text.Contains("slot=11|0x8012ABCD|Stamina Elixir\n"), "readable lines"); + var back = RoundTrip(c).For("aelrynth/drakkon"); + Check(back.Counts.SequenceEqual(d.Counts), "counts back, in order (key any case)"); + Check(back.Slots.Length == 12 && back.Slots[0] == d.Slots[0] && back.Slots[11] == d.Slots[11] && back.Slots[5] == null, "slots back"); + Check(ItemHudFile.Write(RoundTrip(c)) == text, "a second save is identical"); + } + + private static void PerCharacterSections() + { + Case("PerCharacterSections"); + var c = new ItemHudFile.Contents(); + c.Set("Aelrynth/One", ItemHudCharacter.Empty.WithCount("Mana Scarab", out _)); + c.Set("Aelrynth/Two", ItemHudCharacter.Empty.WithCount("Healing Kit", out _)); + c.Set("Other/One", ItemHudCharacter.Empty.WithSlot(1, new RemoteSlot(5, "Pyreal"))); + var back = RoundTrip(c); + Check(back.For("Aelrynth/One").Counts.SequenceEqual(new[] { "Mana Scarab" }), "first character"); + Check(back.For("Aelrynth/Two").Counts.SequenceEqual(new[] { "Healing Kit" }), "second character apart"); + Check(back.For("Other/One").Counts.Length == 0 && back.For("Other/One").Slots[1]?.Name == "Pyreal", "same name on another server apart"); + Check(ReferenceEquals(back.For("Nobody/Here"), ItemHudCharacter.Empty), "an unknown character: empty"); + Check(back.Order.SequenceEqual(new[] { "Aelrynth/One", "Aelrynth/Two", "Other/One" }), "file order kept"); + } + + private static void UnknownLinesKept() + { + Case("UnknownLinesKept"); + string[] file = + { + "# a comment", + "future=1", + "[A/B]", + "count=Mana Scarab", + "iconSize=24", + "slot=0|0x00000005|Pyreal", + }; + var c = ItemHudFile.Parse(file); + Check(c.Preamble.SequenceEqual(new[] { "future=1" }), "a line before any section kept"); + Check(c.For("A/B").Other.SequenceEqual(new[] { "iconSize=24" }), "an unknown line in a section kept"); + string text = ItemHudFile.Write(c); + Check(text.Contains("future=1\n") && text.Contains("iconSize=24\n"), "and written back"); + Check(!text.Contains("# a comment"), "comments are ours to write"); + } + + private static void BadFileValues() + { + Case("BadFileValues"); + string[] file = + { + "[A/B]", + "count=", + "count=Mana Scarab", + "count=MANA SCARAB", + "slots=banana", + "slots=2", + "slot=x|0x5|Pyreal", + "slot=3|zzz|Pyreal", + "slot=30|0x5|Pyreal", + "slot=1|0x0|", + "slot=2|17|Decimal Id", + }; + var d = ItemHudFile.Parse(file).For("A/B"); + Check(d.Counts.SequenceEqual(new[] { "Mana Scarab" }), "empty and duplicate counts dropped"); + Check(d.Slots.Length == ItemHudCharacter.MinSlots, "slots clamped to the minimum"); + Check(d.Slots[1] == null, "a slot with no id and no name stays empty"); + Check(d.Slots[2] == new RemoteSlot(17, "Decimal Id"), "a decimal id reads"); + Check(d.Other.Count(o => o.StartsWith("slot=", StringComparison.Ordinal)) == 3, "unreadable slot lines kept as they were"); + Check(ItemHudFile.Parse(Array.Empty()).Order.Count == 0, "an empty file"); + } + + private static void EditsAreImmutable() + { + Case("EditsAreImmutable"); + var a = ItemHudCharacter.Empty.WithCount("Mana Scarab", out _).WithSlot(0, new RemoteSlot(1, "Pyreal")); + string[] counts = a.Counts; + var slots = a.Slots; + var b = a.WithCount("Healing Kit", out _).WithSlot(0, null).WithSlotCount(12); + Check(counts.Length == 1 && a.Counts.Length == 1, "the old lists are unchanged"); + Check(slots[0]?.Name == "Pyreal" && a.Slots.Length == ItemHudCharacter.DefaultSlots, "the old slots are unchanged"); + Check(b.Counts.Length == 2 && b.Slots[0] == null && b.Slots.Length == 12, "the new ones have the edits"); + Check(ItemHudCharacter.Empty.Counts.Length == 0 && ItemHudCharacter.Empty.Slots.All(s => s == null), "Empty stays empty"); + } +} diff --git a/tools/LauncherUpdateTests/LauncherUpdateTests.csproj b/tools/LauncherUpdateTests/LauncherUpdateTests.csproj index 9100fea..5ea6040 100644 --- a/tools/LauncherUpdateTests/LauncherUpdateTests.csproj +++ b/tools/LauncherUpdateTests/LauncherUpdateTests.csproj @@ -28,4 +28,8 @@ + + + + diff --git a/tools/MetaEditTests/MetaEditTests.csproj b/tools/MetaEditTests/MetaEditTests.csproj new file mode 100644 index 0000000..3f07b50 --- /dev/null +++ b/tools/MetaEditTests/MetaEditTests.csproj @@ -0,0 +1,27 @@ + + + + + Exe + net10.0 + enable + enable + true + MetaEditTests + + + + + + + + + diff --git a/tools/MetaEditTests/Program.cs b/tools/MetaEditTests/Program.cs new file mode 100644 index 0000000..110fd0b --- /dev/null +++ b/tools/MetaEditTests/Program.cs @@ -0,0 +1,328 @@ +using System.Globalization; +using RynthCore.Engine.UI.Data; + +namespace MetaEditTests; + +/// +/// The Meta editor's rules without AC or ImGui: what a new state may be called, when an edit is +/// saved, which file is backed up once per session, the "Set current" landblock / landcell text, +/// and the rule edits behind "+ New state..." and "+ Add". +/// +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + StateNames(); + AutosaveDebounce(); + BackupOncePerSession(); + LocationText(); + Placeholder(); + AddCondition(); + AddAction(); + TakesData(); + NoKillsMinutes(); + SameContentAndLocate(); + + Console.WriteLine(); + Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL: {_failed} of {_checks} checks"); + return _failed == 0 ? 0 : 1; + } + + // ── New state names ────────────────────────────────────────────────── + + private static void StateNames() + { + Case("new state names"); + string[] states = { "Default", "Combat", "Loot Run" }; + Eq(MetaStateName.Problem(" Buff ", states, out string n), null, "a new name is fine"); + Eq(n, "Buff", "trimmed"); + True(MetaStateName.Problem("", states, out _) != null, "empty refused"); + True(MetaStateName.Problem(" ", states, out _) != null, "blank refused"); + True(MetaStateName.Problem(null, states, out _) != null, "null refused"); + True(MetaStateName.Problem("Combat", states, out _) != null, "duplicate refused"); + True(MetaStateName.Problem(" combat ", states, out _)?.Contains("Combat") == true, "duplicate ignoring case, names the existing one"); + True(MetaStateName.Problem("loot run", states, out _) != null, "duplicate with a space, any case"); + True(MetaStateName.Problem("A{b}", states, out _) != null, "braces refused (.af writes STATE: {name})"); + True(MetaStateName.Problem("a\tb", states, out _) != null, "tab refused"); + True(MetaStateName.Problem(new string('x', MetaStateName.MaxLength + 1), states, out _) != null, "too long refused"); + Eq(MetaStateName.Problem(new string('x', MetaStateName.MaxLength), states, out _), null, "longest allowed"); + Eq(MetaStateName.Problem("Default 2", states, out _), null, "a name containing an existing one is fine"); + Eq(MetaStateName.Problem("Ärger", Array.Empty(), out _), null, "non-ASCII fine"); + } + + // ── Autosave ───────────────────────────────────────────────────────── + + private static void AutosaveDebounce() + { + Case("autosave debounce"); + var a = new MetaAutosave(); + False(a.Dirty, "clean at start"); + False(a.Due(10_000, typing: false), "nothing to save"); + False(a.Take(), "nothing to take"); + + a.Changed(1000); + True(a.Dirty, "dirty after a change"); + False(a.Due(1000 + 749, typing: false), "not before 750 ms"); + True(a.Due(1000 + 750, typing: false), "due at 750 ms"); + + a.Changed(1500); // another change restarts the clock + False(a.Due(1000 + 800, typing: false), "a later change restarts the clock"); + True(a.Due(1500 + 750, typing: false), "due 750 ms after the last change"); + + False(a.Due(1500 + 5000, typing: true), "never while a box is being typed in"); + True(a.Due(1500 + 5000, typing: false), "due as soon as the box is left"); + + True(a.Take(), "take the pending edit"); + False(a.Dirty, "clean after taking"); + False(a.Due(99_999, typing: false), "nothing due after a save"); + + a.Changed(2000); + True(a.Take(), "a flush (Back / close / meta switch) takes it before the debounce"); + False(a.Take(), "only once"); + + a.Changed(3000); + a.Clear(); + False(a.Dirty, "Clear drops it (deleted rule / discarded draft)"); + + // Typing burst: one save, not one per key. + var b = new MetaAutosave(); + int saves = 0; + for (int t = 0; t <= 3000; t += 16) + { + bool typing = t < 2000; + if (typing && t % 160 == 0) b.Changed(t); // a key every 160 ms for 2 s + if (b.Due(t, typing) && b.Take()) saves++; + } + Eq(saves, 1, "a 2 s typing burst saves once, after the box is left"); + } + + // ── Backup ─────────────────────────────────────────────────────────── + + private static void BackupOncePerSession() + { + Case("one backup per session"); + var p = new MetaBackupPlan(); + string farm = Path.Combine("C:\\Games", "RynthSuite", "RynthAi", "MetaFiles", "farm.af"); + Eq(p.Before(farm), (farm, farm + ".bak"), "first save backs the file up"); + Eq(p.Before(farm), null, "not again this session"); + Eq(p.Before(farm.ToUpperInvariant()), null, "same file in another case"); + string other = Path.ChangeExtension(farm, null) + "2.af"; + Eq(p.Before(other), (other, other + ".bak"), "another meta: its own backup"); + Eq(p.Before(farm), null, "switching back: still once per file"); + p.NewSession(); + Eq(p.Before(farm), (farm, farm + ".bak"), "a new session backs up again (overwrites the .bak)"); + Eq(p.Before(""), null, "a meta without a file: nothing"); + Eq(p.Before(null), null, "null path: nothing"); + + string met = Path.ChangeExtension(farm, ".met"); + string metAf = Path.ChangeExtension(farm, ".af"); + var q = new MetaBackupPlan(); + Eq(q.Before(met), (metAf, metAf + ".bak"), "a .met meta saves as the .af beside it: that is what is backed up"); + Eq(MetaBackupPlan.WrittenFile(farm), farm, ".af written as is"); + } + + // ── Set current ────────────────────────────────────────────────────── + + private static void LocationText() + { + Case("set current (landblock / landcell)"); + Eq(MetaLocation.LandblockText(0xA9B4001C), "A9B40000", "landblock: 8 digits, low word zero"); + Eq(MetaLocation.LandcellText(0xA9B4001C), "A9B4001C", "landcell: the whole cell"); + Eq(MetaLocation.LandcellText(0x00070143), "00070143", "leading zeros kept"); + Eq(MetaLocation.Text(16, 0x8B370105), "8B370000", "Landblock == is condition 16"); + Eq(MetaLocation.Text(17, 0x8B370105), "8B370105", "Landcell == is condition 17"); + Eq(MetaLocation.Text(15, 0x8B370105), null, "other conditions: none"); + True(MetaLocation.TakesPosition(16) && MetaLocation.TakesPosition(17) && !MetaLocation.TakesPosition(18), "TakesPosition"); + + // A copy of RynthAi's MetaManager reading (Landblock_EQ / Landcell_EQ); RynthAiHostTests + // run the real one against MetaLocation. + foreach (uint cell in new uint[] { 0xA9B4001C, 0x00070143, 0x0000FFFF, 0x00010001, 0xFFFF0100, 0x12340031 }) + { + True(BlockMatches(MetaLocation.LandblockText(cell), cell), $"landblock text matches its own cell {cell:X8}"); + True(CellMatches(MetaLocation.LandcellText(cell), cell), $"landcell text matches its own cell {cell:X8}"); + False(BlockMatches(MetaLocation.LandblockText(cell), cell ^ 0x00010000), $"not the next landblock {cell:X8}"); + False(CellMatches(MetaLocation.LandcellText(cell), cell ^ 1), $"not the next cell {cell:X8}"); + } + } + + private static bool BlockMatches(string data, uint cellId) + { + uint landblock = cellId >> 16; + if (uint.TryParse(data, NumberStyles.HexNumber, null, out uint hex)) + { + if (hex > 0xFFFF) hex >>= 16; + return landblock == hex; + } + return false; + } + + private static bool CellMatches(string data, uint cellId) => + uint.TryParse(data, NumberStyles.HexNumber, null, out uint hex) && cellId == hex; + + // ── Rule edits ─────────────────────────────────────────────────────── + + private static void Placeholder() + { + Case("a new state's first rule"); + MetaRuleDto r = MetaRuleEdit.Placeholder("Buff"); + Eq(r.State, "Buff", "in the new state"); + Eq(r.Condition, 0, "Never"); + Eq(r.Action, 0, "None"); + True(r.Enabled, "enabled (it can't fire anyway)"); + True(MetaRuleEdit.IsPlaceholder(r), "is the placeholder"); + r.ActionData = "x"; + False(MetaRuleEdit.IsPlaceholder(r), "with data it isn't"); + False(MetaRuleEdit.IsPlaceholder(new MetaRuleDto { Condition = 1 }), "Always isn't"); + } + + private static void AddCondition() + { + Case("+ Add condition"); + var r = new MetaRuleDto { State = "S", Condition = 16, ConditionData = "A9B40000" }; + True(MetaRuleEdit.CanAddCondition(r), "can add to a single condition"); + MetaRuleEdit.AddCondition(r); + Eq(r.Condition, MetaRuleEdit.All, "a single condition becomes an All"); + Eq(r.ConditionData, "", "the All has no data"); + Eq(r.Children.Count, 2, "old + new"); + Eq(r.Children[0].Condition, 16, "the old condition first"); + Eq(r.Children[0].ConditionData, "A9B40000", "with its data"); + Eq(r.Children[1].Condition, MetaRuleEdit.Never, "the new one is Never until picked"); + Eq(r.Children[1].State, "S", "same state"); + MetaRuleEdit.AddCondition(r); + Eq(r.Children.Count, 3, "an All gets one more"); + + var any = new MetaRuleDto { Condition = MetaRuleEdit.Any }; + MetaRuleEdit.AddCondition(any); + Eq(any.Children.Count, 1, "an empty Any gets its first"); + + var not = new MetaRuleDto { Condition = MetaRuleEdit.Not }; + True(MetaRuleEdit.CanAddCondition(not), "an empty Not can take one"); + MetaRuleEdit.AddCondition(not); + Eq(not.Children.Count, 1, "Not got its operand"); + False(MetaRuleEdit.CanAddCondition(not), "a full Not can't"); + MetaRuleEdit.AddCondition(not); + Eq(not.Children.Count, 1, "adding to a full Not does nothing"); + Eq(not.Condition, MetaRuleEdit.Not, "still a Not"); + } + + private static void AddAction() + { + Case("+ Add action"); + var r = new MetaRuleDto { Action = 1, ActionData = "/say hi" }; + MetaRuleEdit.AddAction(r); + Eq(r.Action, MetaRuleEdit.DoAll, "a single action becomes a DoAll"); + Eq(r.ActionData, "", "the DoAll has no data"); + Eq(r.ActionChildren.Count, 2, "old + new"); + Eq(r.ActionChildren[0].ActionData, "/say hi", "old first, data kept"); + Eq(r.ActionChildren[1].Action, MetaRuleEdit.NoAction, "the new one is None until picked"); + MetaRuleEdit.AddAction(r); + Eq(r.ActionChildren.Count, 3, "a DoAll gets one more"); + } + + private static void TakesData() + { + Case("which conditions / actions have a value"); + foreach (int c in new[] { 0, 1, 7, 8, 9, 14, 18, 19, 28, 2, 3, 20 }) + False(MetaRuleEdit.ConditionTakesData(c), $"condition {c} has no value"); + foreach (int c in new[] { 4, 5, 6, 10, 11, 12, 13, 15, 16, 17, 21, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35 }) + True(MetaRuleEdit.ConditionTakesData(c), $"condition {c} has a value"); + foreach (int a in new[] { 0, 4, 6, 10, 15 }) + False(MetaRuleEdit.ActionTakesData(a), $"action {a} has no value"); + foreach (int a in new[] { 1, 2, 3, 5, 7, 8, 9, 11, 12, 13, 14 }) + True(MetaRuleEdit.ActionTakesData(a), $"action {a} has a value"); + + Case("a new rule is added once filled in"); + False(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 1, Action = 1 }), "Always -> Chat with no command: not yet"); + True(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 1, Action = 1, ActionData = "/say hi" }), "Always -> /say hi"); + False(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 1, Action = 1, ActionData = " " }), "blank command: not yet"); + False(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 16, Action = 6 }), "Landblock with no value: not yet"); + True(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 16, ConditionData = "A9B40000", Action = 6 }), "Landblock -> Return"); + True(MetaRuleEdit.ReadyToAdd(MetaRuleEdit.Placeholder("S")), "Never -> None"); + var all = new MetaRuleDto { Condition = MetaRuleEdit.All, Action = 6 }; + False(MetaRuleEdit.ReadyToAdd(all), "an empty All: not yet"); + all.Children.Add(new MetaRuleDto { Condition = 4 }); + False(MetaRuleEdit.ReadyToAdd(all), "an All with an empty Chat Message: not yet"); + all.Children[0].ConditionData = "hello"; + True(MetaRuleEdit.ReadyToAdd(all), "All(Chat Message: hello) -> Return"); + var doAll = new MetaRuleDto { Condition = 1, Action = MetaRuleEdit.DoAll }; + False(MetaRuleEdit.ReadyToAdd(doAll), "an empty DoAll: not yet"); + doAll.ActionChildren.Add(new MetaRuleDto { Action = 2 }); + False(MetaRuleEdit.ReadyToAdd(doAll), "DoAll(Set Meta State with no state): not yet"); + doAll.ActionChildren[0].ActionData = "Buff"; + True(MetaRuleEdit.ReadyToAdd(doAll), "DoAll(Set Meta State Buff)"); + } + + // ── No Kills Within Minutes (2026-10-06) ───────────────────────────── + + private static void NoKillsMinutes() + { + Case("No Kills Within Minutes: the minutes box"); + Eq(MetaRuleEdit.NoKillsWithinMinutes, 35, "RynthAi's enum value (appended after Vitae % >=)"); + True(MetaRuleEdit.ConditionTakesData(MetaRuleEdit.NoKillsWithinMinutes), "takes a value"); + False(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 35, Action = 6 }), "no minutes yet: not added"); + True(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 35, ConditionData = "5", Action = 6 }), "5 minutes -> Return"); + foreach (string ok in new[] { "5", "0", "2.5", " 10 ", "0,5", "1e1" }) + True(MetaRuleEdit.MinutesOk(ok), $"'{ok}' is minutes"); + foreach (string bad in new[] { "", "abc", "-1", "5m", "NaN", "Infinity" }) + False(MetaRuleEdit.MinutesOk(bad), $"'{bad}' is not"); + False(MetaRuleEdit.NoKillsTooltip("5").Contains("isn't a number"), "a number: the plain explanation"); + True(MetaRuleEdit.NoKillsTooltip("five").Contains("never holds"), "not a number: says it never holds"); + False(MetaRuleEdit.NoKillsTooltip("").Contains("isn't a number"), "empty: the plain explanation"); + } + + private static void SameContentAndLocate() + { + Case("finding the edited rule again"); + MetaRuleDto R(string state, int cond, string data) => new() { State = state, Condition = cond, ConditionData = data, Action = 1, ActionData = "/x" }; + var a = R("S", 4, "a"); + var b = R("S", 4, "b"); + var c = R("T", 4, "a"); + True(MetaRuleEdit.SameContent(a, a.Clone()), "a clone is the same"); + var fired = a.Clone(); + fired.LastFiredMs = 5; + True(MetaRuleEdit.SameContent(a, fired), "LastFiredMs doesn't count"); + False(MetaRuleEdit.SameContent(a, b), "data differs"); + False(MetaRuleEdit.SameContent(a, c), "state differs"); + var child1 = a.Clone(); child1.Children.Add(R("S", 1, "")); + var child2 = a.Clone(); child2.Children.Add(R("S", 0, "")); + False(MetaRuleEdit.SameContent(child1, child2), "children compared"); + False(MetaRuleEdit.SameContent(a, child1), "child count compared"); + + var list = new List { b, a, c }; + Eq(MetaRuleEdit.Locate(list, a, 1), 1, "still at its index"); + Eq(MetaRuleEdit.Locate(list, a, 0), 1, "moved: found by content"); + Eq(MetaRuleEdit.Locate(list, R("S", 4, "zzz"), 2), 2, "not in the snapshot yet: the hint"); + Eq(MetaRuleEdit.Locate(list, a, 7), 1, "a hint past the end: found"); + var dupes = new List { a.Clone(), b, a.Clone(), c, a.Clone() }; + Eq(MetaRuleEdit.Locate(dupes, a, 3), 2, "duplicates: the nearest to the hint"); + } + + // ── Checks ─────────────────────────────────────────────────────────── + + private static void Case(string name) + { + _case = name; + Console.WriteLine("== " + name); + } + + private static void True(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } + + private static void False(bool ok, string what) => True(!ok, what); + + private static void Eq(T actual, T expected, string what) + { + _checks++; + if (EqualityComparer.Default.Equals(actual, expected)) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}: expected <{expected}>, got <{actual}>"); + } +} diff --git a/tools/NavDataUpdateTests/NavDataUpdateTests.csproj b/tools/NavDataUpdateTests/NavDataUpdateTests.csproj index cf337b3..13d466c 100644 --- a/tools/NavDataUpdateTests/NavDataUpdateTests.csproj +++ b/tools/NavDataUpdateTests/NavDataUpdateTests.csproj @@ -23,4 +23,8 @@ + + + + diff --git a/tools/PanelWindowTests/PanelWindowTests.csproj b/tools/PanelWindowTests/PanelWindowTests.csproj new file mode 100644 index 0000000..ffcfe43 --- /dev/null +++ b/tools/PanelWindowTests/PanelWindowTests.csproj @@ -0,0 +1,23 @@ + + + + + Exe + net10.0 + enable + enable + true + PanelWindowTests + + + + + + + diff --git a/tools/PanelWindowTests/Program.cs b/tools/PanelWindowTests/Program.cs new file mode 100644 index 0000000..92c9097 --- /dev/null +++ b/tools/PanelWindowTests/Program.cs @@ -0,0 +1,48 @@ +using RynthCore.Engine.UI; + +namespace PanelWindowTests; + +/// +/// The backup path of LayeredWindow.Dispose (PanelDestroyPlan.Choose). Win32 only lets the creating +/// thread destroy a window. Idea from Silentkelpie (rynth PR #1); re-implemented here. +/// +internal static class Program +{ + private static int _checks, _failed; + + private static int Main() + { + const uint game = 0x1A2C, avalonia = 0x2B40; + + Check(PanelDestroyPlan.Choose(0, game, ourPanel: false) == PanelDestroyFallback.AlreadyGone, + "window gone (no owner thread) -> nothing"); + Check(PanelDestroyPlan.Choose(0, game, ourPanel: true) == PanelDestroyFallback.AlreadyGone, + "window gone even if the class looked like ours -> nothing"); + + Check(PanelDestroyPlan.Choose(game, game, ourPanel: true) == PanelDestroyFallback.DestroyHere, + "game thread owns it, game thread disposing -> destroy here"); + Check(PanelDestroyPlan.Choose(avalonia, avalonia, ourPanel: true) == PanelDestroyFallback.DestroyHere, + "Avalonia UI thread owns it, Avalonia UI thread disposing -> destroy here"); + + Check(PanelDestroyPlan.Choose(avalonia, game, ourPanel: true) == PanelDestroyFallback.LeaveHidden, + "panel made on the Avalonia UI thread, disposed from the game thread -> leave hidden, no cross-thread destroy"); + Check(PanelDestroyPlan.Choose(game, avalonia, ourPanel: true) == PanelDestroyFallback.LeaveHidden, + "panel made on the game thread, disposed from the Avalonia UI thread (redock) -> leave hidden"); + + Check(PanelDestroyPlan.Choose(game, game, ourPanel: false) == PanelDestroyFallback.AlreadyGone, + "handle reused by a window that isn't a panel -> never destroy it"); + Check(PanelDestroyPlan.Choose(avalonia, game, ourPanel: false) == PanelDestroyFallback.AlreadyGone, + "handle reused on another thread -> never touch it"); + + Console.WriteLine($"{_checks} check(s), {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"[FAIL] {what}"); + } +} diff --git a/tools/PluginManifestTests/PluginManifestTests.csproj b/tools/PluginManifestTests/PluginManifestTests.csproj index 264a67d..496f29b 100644 --- a/tools/PluginManifestTests/PluginManifestTests.csproj +++ b/tools/PluginManifestTests/PluginManifestTests.csproj @@ -9,7 +9,10 @@ this test's own DLL with UpdateResource, as the build does); - the SDK's API version can't drift: RynthCoreHost.CurrentApiVersion, the SDK's table size (RynthCoreApiNative vs the engine's RynthCoreAPI, compiled in) and the build targets' - RynthCoreSdkApiVersion all match PluginContractVersion.Current. + RynthCoreSdkApiVersion all match PluginContractVersion.Current; + - PluginPaths de-duplication (src\RynthCore.Engine\Plugins\PluginPathDedupe.cs, compiled in): + the same DLL listed twice (any case or slashes) loads once; the same file name from two + folders keeps the first and warns. Extra arguments are plugin DLLs to read and check (e.g. a RynthSuite publish folder's). Never loads a plugin, never touches %APPDATA% or C:\Games. Run: dotnet run -c Release [plugin.dll ...] (arguments after a double dash) (exit 0 = pass, 1 = fail) @@ -35,6 +38,7 @@ + diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 5e63ac9..c9a5e7c 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -53,6 +53,11 @@ internal static class Program Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift); Run(nameof(TrainingStructsMirror), TrainingStructsMirror); Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum); + Run(nameof(DedupeSamePathTwice), DedupeSamePathTwice); + Run(nameof(DedupeCaseAndSlashes), DedupeCaseAndSlashes); + Run(nameof(DedupeSameNameTwoFolders), DedupeSameNameTwoFolders); + Run(nameof(DedupeAgainstAlreadyLoaded), DedupeAgainstAlreadyLoaded); + Run(nameof(DedupeKeepsOrderAndText), DedupeKeepsOrderAndText); foreach (string dll in args) Run("Plugin " + Path.GetFileName(dll), () => CheckBuiltPlugin(dll)); } @@ -489,6 +494,86 @@ internal static class Program "the SDK assembly carries no manifest attribute"); } + // ── PluginPaths de-duplication (PluginPathDedupe; Silentkelpie, rynth PR #1) ── + + private const string SuiteDir = @"C:\Games\RynthSuite\Plugins"; + private const string OtherDir = @"D:\Old\RynthSuite"; + + private static void DedupeSamePathTwice() + { + string ai = Path.Combine(SuiteDir, "RynthCore.Plugin.RynthAi.dll"); + string chat = Path.Combine(SuiteDir, "RynthCore.Plugin.RynthChat.dll"); + var r = PluginPathDedupe.Dedupe(new[] { ai, chat, ai }); + Eq(string.Join("|", r.Load), ai + "|" + chat, "loads each once, in order"); + Eq(r.Skipped.Count, 1, "one skipped"); + Check(r.Skipped[0].SameFile && r.Skipped[0].Path == ai && r.Skipped[0].KeptPath == ai, "repeat flagged as the same file"); + Check(r.Skipped[0].Message.Contains("listed twice") && !r.Skipped[0].Message.Contains("conflict"), "repeat is not called a conflict: " + r.Skipped[0].Message); + } + + private static void DedupeCaseAndSlashes() + { + string ai = SuiteDir + @"\RynthCore.Plugin.RynthAi.dll"; + string[] spellings = + { + ai.ToUpperInvariant(), + ai.Replace('\\', '/'), + @"C:\Games\RynthSuite\Plugins\..\Plugins\.\rynthcore.plugin.rynthai.DLL", + " " + ai + " ", + }; + foreach (string other in spellings) + { + var r = PluginPathDedupe.Dedupe(new[] { ai, other }); + Eq(r.Load.Count, 1, $"'{other}' loads once"); + Check(r.Skipped.Count == 1 && r.Skipped[0].SameFile, $"'{other}' is the same file, not a conflict"); + } + Eq(PluginPathDedupe.Normalize("C:/Games/RynthSuite/Plugins/"), @"C:\Games\RynthSuite\Plugins", "normalize: slashes and trailing separator"); + } + + private static void DedupeSameNameTwoFolders() + { + string first = Path.Combine(SuiteDir, "RynthCore.Plugin.RynthAi.dll"); + string second = Path.Combine(OtherDir, "rynthcore.plugin.rynthai.dll"); + string nav = Path.Combine(OtherDir, "RynthCore.Plugin.RynthNav.dll"); + var r = PluginPathDedupe.Dedupe(new[] { first, nav, second }); + Eq(string.Join("|", r.Load), first + "|" + nav, "the first listed wins; other plugins in that folder still load"); + Eq(r.Skipped.Count, 1, "one skipped"); + PluginPathDedupe.Skipped s = r.Skipped[0]; + Check(!s.SameFile && !s.KeptAlreadyLoaded, "flagged as a conflict between two copies"); + Eq(s.KeptPath, first, "kept path"); + Check(s.Message.StartsWith("plugin conflict") && s.Message.Contains(first) && s.Message.Contains(second) && s.Message.Contains("listed first"), + "warning names both copies and which won: " + s.Message); + + // Reversed order: the other one wins. First listed is the rule, not a folder preference. + var rev = PluginPathDedupe.Dedupe(new[] { second, first }); + Eq(rev.Load.Single(), second, "reversed: the first listed wins"); + } + + private static void DedupeAgainstAlreadyLoaded() + { + string loaded = Path.Combine(SuiteDir, "RynthCore.Plugin.RynthAi.dll"); + string copy = Path.Combine(OtherDir, "RynthCore.Plugin.RynthAi.dll"); + var r = PluginPathDedupe.Dedupe(new[] { loaded.ToLowerInvariant(), copy }, new[] { loaded }); + Eq(r.Load.Count, 0, "nothing new to load"); + Eq(r.Skipped.Count, 2, "both skipped"); + Check(r.Skipped[0].SameFile && r.Skipped[0].KeptAlreadyLoaded && r.Skipped[0].Message.Contains("already loaded"), "same file as a loaded plugin"); + Check(!r.Skipped[1].SameFile && r.Skipped[1].KeptAlreadyLoaded && r.Skipped[1].Message.Contains("already loaded"), "a second copy of a loaded plugin is a conflict"); + } + + private static void DedupeKeepsOrderAndText() + { + string[] paths = + { + Path.Combine(SuiteDir, "RynthCore.Plugin.RynthChat.dll"), + "", + Path.Combine(SuiteDir, "RynthCore.Plugin.RynthAi.dll"), + Path.Combine(SuiteDir, "RynthCore.Plugin.RynthNav.dll"), + }; + var r = PluginPathDedupe.Dedupe(paths); + Eq(string.Join("|", r.Load), paths[0] + "|" + paths[2] + "|" + paths[3], "no duplicates: everything loads, as listed, text unchanged"); + Eq(r.Skipped.Count, 0, "nothing skipped"); + Eq(PluginPathDedupe.Dedupe(Array.Empty()).Load.Count, 0, "empty list"); + } + private static string FindUp(string relative) { for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent) diff --git a/tools/StatusAgentTests/StatusAgentTests.csproj b/tools/StatusAgentTests/StatusAgentTests.csproj index d47a65e..6ce4287 100644 --- a/tools/StatusAgentTests/StatusAgentTests.csproj +++ b/tools/StatusAgentTests/StatusAgentTests.csproj @@ -34,4 +34,8 @@ + + + + diff --git a/tools/UsageStatsTests/UsageStatsTests.csproj b/tools/UsageStatsTests/UsageStatsTests.csproj index be4bef4..6c997c2 100644 --- a/tools/UsageStatsTests/UsageStatsTests.csproj +++ b/tools/UsageStatsTests/UsageStatsTests.csproj @@ -23,4 +23,8 @@ + + + + diff --git a/tools/VideoPatchTests/Program.cs b/tools/VideoPatchTests/Program.cs new file mode 100644 index 0000000..6662793 --- /dev/null +++ b/tools/VideoPatchTests/Program.cs @@ -0,0 +1,204 @@ +using RynthCore.Engine.D3D9; + +namespace VideoPatchTests; + +/// The video patch's modes, focus logic, frame cap and settings file (VideoPatchPolicy). +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + OffNeverSkips(); + WorldSkipsSceneOnly(); + UnfocusedFollowsFocus(); + AllSkipsUiOnlyWithImGui(); + OutsideTheWorldNothingSkips(); + FrameCap(); + CommandWords(); + ComboMatchesEnum(); + CharacterKeys(); + FileRoundTrip(); + AllIsNeverSaved(); + OffRemovesTheLine(); + DefaultLineAndUnknownLines(); + BadFileValues(); + + Console.WriteLine(_failed == 0 ? $"PASS ({_checks} assertions)" : $"FAIL ({_failed} of {_checks} assertions)"); + return _failed == 0 ? 0 : 1; + } + + private static void Case(string name) { _case = name; Console.WriteLine("ok " + name); } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"FAIL {_case}: {what}"); + } + + private static VideoPatchDecision D(VideoPatchMode m, bool inWorld = true, bool focused = true, bool imgui = true) => + VideoPatchPolicy.Decide(m, inWorld, focused, imgui); + + private static void OffNeverSkips() + { + Case("OffNeverSkips"); + foreach (bool w in new[] { true, false }) + foreach (bool f in new[] { true, false }) + foreach (bool i in new[] { true, false }) + Check(!D(VideoPatchMode.Off, w, f, i).Any, $"off skipped something (world={w} focused={f} imgui={i})"); + } + + private static void WorldSkipsSceneOnly() + { + Case("WorldSkipsSceneOnly"); + foreach (bool f in new[] { true, false }) + { + var d = D(VideoPatchMode.World, focused: f); + Check(d.SkipWorld, "world mode must skip the 3D scene"); + Check(!d.SkipAcUi, "world mode must keep AC's UI"); + } + } + + private static void UnfocusedFollowsFocus() + { + Case("UnfocusedFollowsFocus"); + Check(!D(VideoPatchMode.Unfocused, focused: true).Any, "focused client must draw everything"); + var bg = D(VideoPatchMode.Unfocused, focused: false); + Check(bg.SkipWorld && !bg.SkipAcUi, "background client: world skipped, UI kept"); + // Switching back is per frame: the decision has no memory. + Check(!D(VideoPatchMode.Unfocused, focused: true).Any, "focus back must draw again at once"); + } + + private static void AllSkipsUiOnlyWithImGui() + { + Case("AllSkipsUiOnlyWithImGui"); + var all = D(VideoPatchMode.All); + Check(all.SkipWorld && all.SkipAcUi, "all with ImGui: scene and AC UI skipped"); + var noImgui = D(VideoPatchMode.All, imgui: false); + Check(noImgui.SkipWorld && !noImgui.SkipAcUi, "all without the ImGui layer falls back to world (AC's chat stays)"); + Check(D(VideoPatchMode.All, focused: true).SkipAcUi, "all ignores focus"); + } + + private static void OutsideTheWorldNothingSkips() + { + Case("OutsideTheWorldNothingSkips"); + foreach (VideoPatchMode m in Enum.GetValues()) + foreach (bool f in new[] { true, false }) + Check(!D(m, inWorld: false, focused: f).Any, $"{m} skipped outside the world (login/character select must draw)"); + } + + private static void FrameCap() + { + Case("FrameCap"); + var skip = new VideoPatchDecision(true, false); + Check(VideoPatchPolicy.FrameCap(skip, 15) == 15, "default cap"); + Check(VideoPatchPolicy.FrameCap(skip, 0) == 0, "0 = no cap"); + Check(VideoPatchPolicy.FrameCap(skip, 2) == VideoPatchPolicy.MinFrameCapFps, "cap clamps up to the minimum"); + Check(VideoPatchPolicy.FrameCap(skip, 500) == VideoPatchPolicy.MaxFrameCapFps, "cap clamps down to the maximum"); + Check(VideoPatchPolicy.FrameCap(VideoPatchDecision.None, 15) == 0, "no cap while drawing"); + Check(VideoPatchPolicy.FrameCap(D(VideoPatchMode.Unfocused, focused: true), 15) == 0, "no cap for a focused 'unfocused' client"); + Check(VideoPatchPolicy.FrameCap(D(VideoPatchMode.Unfocused, focused: false), 15) == 15, "cap for a background 'unfocused' client"); + Check(VideoPatchPolicy.ClampCap(-3) == 0, "negative = no cap"); + } + + private static void CommandWords() + { + Case("CommandWords"); + (string word, VideoPatchMode mode)[] words = + { + ("off", VideoPatchMode.Off), ("OFF", VideoPatchMode.Off), ("on", VideoPatchMode.World), + ("world", VideoPatchMode.World), ("unfocused", VideoPatchMode.Unfocused), ("focus", VideoPatchMode.Unfocused), + ("all", VideoPatchMode.All), (" all ", VideoPatchMode.All), + }; + foreach ((string word, VideoPatchMode mode) in words) + Check(VideoPatchPolicy.TryParse(word, out VideoPatchMode m) && m == mode, $"'{word}' -> {mode}"); + Check(!VideoPatchPolicy.TryParse("status", out _), "'status' is not a mode"); + Check(!VideoPatchPolicy.TryParse(null, out _), "null is not a mode"); + foreach (VideoPatchMode m in Enum.GetValues()) + Check(VideoPatchPolicy.TryParse(VideoPatchPolicy.Name(m), out VideoPatchMode back) && back == m, $"Name({m}) round-trips"); + } + + private static void ComboMatchesEnum() + { + Case("ComboMatchesEnum"); + Check(VideoPatchPolicy.ComboItems.Length == Enum.GetValues().Length, "one combo item per mode"); + Check(VideoPatchPolicy.ComboItems[(int)VideoPatchMode.Off] == "Off", "index 0 is Off"); + Check(VideoPatchPolicy.ComboItems[(int)VideoPatchMode.All].Contains("session"), "All says it is session only"); + } + + private static void CharacterKeys() + { + Case("CharacterKeys"); + Check(VideoPatchPolicy.CharacterKey("Aelrynth", "Some Guy") == "Aelrynth/Some Guy", "server/character"); + Check(VideoPatchPolicy.CharacterKey("", "Some Guy") == "Some Guy", "no server"); + Check(VideoPatchPolicy.CharacterKey("Aelrynth", "") == VideoPatchPolicy.DefaultCharacterKey, "no character = Default"); + Check(VideoPatchPolicy.CharacterKey(null, null) == VideoPatchPolicy.DefaultCharacterKey, "nulls = Default"); + Check(!VideoPatchPolicy.CharacterKey("A=B", "C").Contains('='), "no '=' in a key"); + } + + private static VideoPatchPolicy.FileModel RoundTripModel(VideoPatchPolicy.FileModel m) => + VideoPatchPolicy.Parse(VideoPatchPolicy.Serialize(m)); + + private static void FileRoundTrip() + { + Case("FileRoundTrip"); + var m = VideoPatchPolicy.Parse(null); + Check(m.FrameCapFps == VideoPatchPolicy.DefaultFrameCapFps, "missing file = default cap"); + Check(m.ModeFor("Aelrynth/A") == VideoPatchMode.Off, "missing file = off"); + m.FrameCapFps = 10; + m.Set("Aelrynth/A", VideoPatchMode.World); + m.Set("Aelrynth/B", VideoPatchMode.Unfocused); + var back = RoundTripModel(m); + Check(back.FrameCapFps == 10, "cap round-trips"); + Check(back.ModeFor("Aelrynth/A") == VideoPatchMode.World, "A round-trips"); + Check(back.ModeFor("aelrynth/b") == VideoPatchMode.Unfocused, "B round-trips (case-insensitive)"); + Check(back.ModeFor("Aelrynth/C") == VideoPatchMode.Off, "unknown character = off"); + var twice = RoundTripModel(back); + Check(string.Join("\n", VideoPatchPolicy.Serialize(twice)) == string.Join("\n", VideoPatchPolicy.Serialize(back)), "serialize is stable"); + Check(VideoPatchPolicy.Serialize(twice).Count(l => l.StartsWith("# RynthCore video patch")) == 1, "one header line"); + } + + private static void AllIsNeverSaved() + { + Case("AllIsNeverSaved"); + var m = VideoPatchPolicy.Parse(null); + m.Set("X/Y", VideoPatchMode.World); + Check(!m.Set("X/Y", VideoPatchMode.All), "Set(all) refuses"); + Check(m.ModeFor("X/Y") == VideoPatchMode.World, "Set(all) keeps the saved mode"); + var hand = VideoPatchPolicy.Parse(new[] { "X/Z=all" }); + Check(hand.ModeFor("X/Z") == VideoPatchMode.Off, "a hand-written 'all' loads as off (a start never hides AC's UI)"); + } + + private static void OffRemovesTheLine() + { + Case("OffRemovesTheLine"); + var m = VideoPatchPolicy.Parse(null); + m.Set("X/Y", VideoPatchMode.World); + m.Set("X/Y", VideoPatchMode.Off); + Check(!VideoPatchPolicy.Serialize(m).Any(l => l.StartsWith("X/Y")), "off leaves no line"); + } + + private static void DefaultLineAndUnknownLines() + { + Case("DefaultLineAndUnknownLines"); + var m = VideoPatchPolicy.Parse(new[] { "Default=unfocused", "SomethingNew=42", "# a note", "Aelrynth/A=world" }); + Check(m.ModeFor("Aelrynth/Q") == VideoPatchMode.Unfocused, "Default applies to characters without a line"); + Check(m.ModeFor("Aelrynth/A") == VideoPatchMode.World, "own line wins over Default"); + var lines = VideoPatchPolicy.Serialize(m); + Check(lines.Contains("SomethingNew=42"), "unknown key kept"); + Check(lines.Contains("# a note"), "comment kept"); + } + + private static void BadFileValues() + { + Case("BadFileValues"); + var m = VideoPatchPolicy.Parse(new[] { "FrameCapFps=abc", "Aelrynth/A=sideways", "=world", "" }); + Check(m.FrameCapFps == VideoPatchPolicy.DefaultFrameCapFps, "bad cap keeps the default"); + Check(m.ModeFor("Aelrynth/A") == VideoPatchMode.Off, "bad mode = off"); + Check(VideoPatchPolicy.Parse(new[] { "FrameCapFps=1" }).FrameCapFps == VideoPatchPolicy.MinFrameCapFps, "cap 1 clamps to the minimum"); + Check(VideoPatchPolicy.Parse(new[] { "FrameCapFps=0" }).FrameCapFps == 0, "cap 0 = none"); + } +} diff --git a/tools/VideoPatchTests/VideoPatchTests.csproj b/tools/VideoPatchTests/VideoPatchTests.csproj new file mode 100644 index 0000000..5693074 --- /dev/null +++ b/tools/VideoPatchTests/VideoPatchTests.csproj @@ -0,0 +1,24 @@ + + + + + Exe + net10.0 + enable + enable + true + VideoPatchTests + + + + + + + diff --git a/tools/pe_pattern.py b/tools/pe_pattern.py index f350366..13dcfce 100644 --- a/tools/pe_pattern.py +++ b/tools/pe_pattern.py @@ -312,7 +312,7 @@ def _compat_dir(): def parse_engine_patterns(): srcs = {} # Compatibility/ holds nearly every hook; D3D9/AcUiPassHook.cs (RenderUI::RenderObjects) - # is the one function hook that lives with the render code. + # and D3D9/VideoPatch.cs (SmartBox::RenderNormalMode) live with the render code. engine_dir = os.path.dirname(_compat_dir()) for f in glob.glob(os.path.join(_compat_dir(), "*.cs")) + glob.glob(os.path.join(engine_dir, "D3D9", "*.cs")): with open(f, "r", encoding="utf-8") as fh: