diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index a411843..d34b87b 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -4089,6 +4089,31 @@ internal partial class MainWindow : Window // thread not draining the marshalled-action queue), and a stale heartbeat // file. private readonly Dictionary _wedgeZeroFpsSinceUtc = new(); + // One open handle per client log for the wedge check's tail read (2026-11-02): reopening the + // log every poll made Windows Defender rescan the whole changed file on each open (300 ms at + // worst on an old PC). Reopened when the engine's startup rotation has moved the file: the open + // one (now .log.old) is shorter than the file on disk once that outgrows it, or far longer + // while the new one is small. Closed when the client goes. + private readonly Dictionary _wedgeLogStreams = new(); + + private FileStream WedgeLog(int pid, string path, long lengthOnDisk) + { + if (_wedgeLogStreams.TryGetValue(pid, out FileStream? open)) + { + long held = open.Length; // the engine may have written since lengthOnDisk was read + if (held >= lengthOnDisk && held - lengthOnDisk < 1_000_000) return open; + CloseWedgeLog(pid); + } + var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + _wedgeLogStreams[pid] = fs; + return fs; + } + + private void CloseWedgeLog(int pid) + { + if (_wedgeLogStreams.Remove(pid, out FileStream? fs)) + try { fs.Dispose(); } catch { } + } // PIDs held off for a full-memory dump, and since when (DumpInProgressRule.Decide caps the // hold at MaxHold). Kept while held or expired, dropped once no dump is in progress. private readonly Dictionary _dumpHoldSinceUtc = new(); @@ -4201,6 +4226,9 @@ internal partial class MainWindow : Window foreach (int stale in _wedgeZeroFpsSinceUtc.Keys.ToList()) if (!targets.Any(p => { try { return p.Id == stale; } catch { return false; } })) _wedgeZeroFpsSinceUtc.Remove(stale); + foreach (int gone in _wedgeLogStreams.Keys.ToList()) + if (!targets.Any(p => { try { return p.Id == gone; } catch { return false; } })) + CloseWedgeLog(gone); foreach (Process process in targets) { @@ -4238,7 +4266,7 @@ internal partial class MainWindow : Window // as wedged too (same containment applies). bool hbStale = (DateTime.Now - fi.LastWriteTime).TotalSeconds > 120; - using var fs = new FileStream(logPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + FileStream fs = WedgeLog(pid, logPath, fi.Length); // 16KB tail: enough to contain the every-30s combat-mode-stuck // line for the item-lock detector, still cheap per poll. long want = Math.Min(16384, fs.Length); @@ -4283,7 +4311,7 @@ internal partial class MainWindow : Window continue; } } - catch { continue; } + catch { CloseWedgeLog(pid); continue; } // STRONGEST signal: the engine's own watchdog confirmed a permanent // main-thread wedge. Act immediately — it already held ~10s+ before diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs index a36ce99..b8214c6 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs @@ -192,6 +192,7 @@ internal static class ChatCommandReplies V("sense", RynthCore.Engine.UI.Data.SenseLayout.Usage, RynthCore.Engine.UI.Data.SenseLayout.IsValidArgs), V("characters", "Usage: /rc characters (opens or closes RynthNet's Characters window)", NoArgs, "chars"), V("itemcount", "Usage: /rc itemcount (opens or closes the Item Count panel)", NoArgs, "itemhud"), + V("itemtool", "Usage: /rc itemtool (opens or closes the Item Tool panel: chest looter and Quick give)", NoArgs), V("resetbar", "Usage: /rc resetbar (moves the RynthCore bar back to the top-left corner)", NoArgs, "barreset"), V("actionstate", "Usage: /rc actionstate (the client's item-action gates)", NoArgs, "actions"), V("unlockactions", "Usage: /rc unlockactions (opens the client's item-action gates now)", NoArgs, "unlock"), diff --git a/src/RynthCore.Engine/Compatibility/InventoryModel.cs b/src/RynthCore.Engine/Compatibility/InventoryModel.cs index befc1d4..22b23e9 100644 --- a/src/RynthCore.Engine/Compatibility/InventoryModel.cs +++ b/src/RynthCore.Engine/Compatibility/InventoryModel.cs @@ -513,7 +513,7 @@ internal static partial class InventoryModel _playerName = name ?? string.Empty; } sig = Mix(sig, (uint)burden, (uint)pyreals, (uint)capacity, (uint)(pyreals >> 32), (uint)_scratchItems.Count, - aetheria, (uint)_playerName.Length, (uint)containerSlots, 0); + aetheria, (uint)_playerName.Length, (uint)containerSlots, Net.InventoryOrder.ListHash(player, true)); if (sig == _lastSignature && _current.PlayerId == player) return; _lastSignature = sig; @@ -577,6 +577,10 @@ internal static partial class InventoryModel packs[p + 1].Used = CountTowardCapacity(packs[p + 1].Items); packs[p + 1].FillText = Fill(packs[p + 1].Used, cap); } + // The side packs in the pack column's order, top first (the server's pack-slot list, as retail's + // column and RynthSort's pack numbers have them), when that list names every one; else id order. + if (Net.InventoryOrder.TryGetOrder(player, true, out uint[] column)) + Net.InventoryOrder.SortByColumn(packs, 1, static p => p.Id, column); view.Packs = packs; view.SlotItems = slotItems.ToArray(); view.Worn = worn.ToArray(); diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 8f3f29e..60d846a 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -675,6 +675,12 @@ internal static class RynthCoreChatCommands "The Item Count panel isn't available (the ImGui layer is off?)."); return; + case "itemtool": + // The ImGui Item Tool panel (chest looter + Quick give), like its bar button. + TogglePanel(ImGuiBackend.Panels.ItemToolFace.Title, "Item Tool panel", + "The Item Tool panel isn't available (the ImGui layer is off, or RynthAi isn't loaded)."); + return; + case "resetbar": case "barreset": RynthLog.Compat("RynthCoreChatCommands: /rc resetbar — resetting overlay bar position."); diff --git a/src/RynthCore.Engine/D3D9/VideoPatchPolicy.cs b/src/RynthCore.Engine/D3D9/VideoPatchPolicy.cs index 3499018..4d4f231 100644 --- a/src/RynthCore.Engine/D3D9/VideoPatchPolicy.cs +++ b/src/RynthCore.Engine/D3D9/VideoPatchPolicy.cs @@ -137,11 +137,15 @@ internal static class VideoPatchPolicy return VideoPatchMode.Off; } - /// Stores a character's mode; "all" is never stored, "off" removes the line. + /// + /// Stores a character's mode; "all" is never stored. A character's "off" is a line of its own + /// (2026-11-02): removing the line let the Default line ("Default=unfocused") come back on + /// the next login, so Off never stuck. Default's own "off" removes its line. + /// public bool Set(string key, VideoPatchMode mode) { if (!IsSaved(mode)) return false; - if (mode == VideoPatchMode.Off) Modes.Remove(key); + if (mode == VideoPatchMode.Off && key.Equals(DefaultCharacterKey, StringComparison.OrdinalIgnoreCase)) Modes.Remove(key); else Modes[key] = mode; return true; } @@ -171,7 +175,8 @@ internal static class VideoPatchPolicy } if (TryParse(value, out VideoPatchMode mode) && IsSaved(mode)) { - if (mode != VideoPatchMode.Off) model.Modes[key] = mode; + if (mode != VideoPatchMode.Off || !key.Equals(DefaultCharacterKey, StringComparison.OrdinalIgnoreCase)) + model.Modes[key] = mode; // a character's "off" overrides the Default line continue; } model.Other.Add(raw); diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index 0942ce2..f10593d 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -163,6 +163,8 @@ internal static class EngineLifecycle // The ambient light floor's hook passes AC's own colour from here on (no floor). Step("AmbientLight.Uninstall", () => AmbientLight.Uninstall()); Step("EndSceneHook.Uninstall", () => EndSceneHook.Uninstall()); + // The font atlas baked before login, when no ImGui context took it (EngineFrameController). + Step("ImGui fonts without a context", () => ImGuiBackend.EngineFrameController.FreeFontsWithoutContext()); // Give in-flight EndScene calls a chance to drain. AC's render thread // may still be inside our detour right now; sleeping a few frames is @@ -241,6 +243,7 @@ internal static class EngineLifecycle Volatile.Write(ref _hasShutDown, 1); RynthLog.Info("EngineLifecycle: Shutdown complete."); + EntryPoint.CloseLogFile(); // the log's open handle (EntryPoint.AppendWithRetry) } private static void Step(string name, Action action) diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 247e479..5dea9c3 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -812,6 +812,12 @@ public static class EntryPoint return; } + // The plugin files' antivirus scans (after an update every one is new) run on + // workers from here, during the hook steps, not one file at a time in + // LoadPlugins (Plugins/PluginFilePrefetch.cs). + if (Plugins.EngineSettings.EnablePlugins) + PluginFilePrefetch.Start(Plugins.EngineSettings.PluginPaths); + // One-shot read-only string-anchor diagnostic. Runs only if the // user has dropped a candidate-string list at // %APPDATA%\RynthCore\string_anchors.txt — otherwise no-ops. @@ -986,14 +992,11 @@ public static class EntryPoint // Panel layout per character (UI/PanelLayout): before the EndScene hook, so the first // frame already asks for the right layout (after a hot reload, the character's). UI.PanelLayout.Initialize(); - if (Plugins.EngineSettings.EnablePlugins) - { - RynthLog.Info("InitWorker DIAG — calling PluginManager.LoadPlugins."); - PluginManager.LoadPlugins(engineDir); - RynthLog.Info("InitWorker DIAG — PluginManager.LoadPlugins returned."); - } - else - RynthLog.Info("InitWorker: plugin loading disabled via engine.json (EnablePlugins=false)."); + + // The first font atlas bakes now, during the world load, instead of after the + // EndScene hook's warm-up (~2 s of every login; ImGuiFonts.StartInitialBake). + if (WillRunImGui()) + ImGuiBackend.EngineFrameController.StartEarlyFontBake(); // Defer D3D9 hooking until after character login. By that point // the game's device is fully initialized and stable, avoiding the @@ -1009,12 +1012,17 @@ public static class EntryPoint // viewport platform/renderer. Avalonia floating panels still // work because they ride a separate LayeredWindow (GDI), not // the D3D9 swap chain. + // + // Subscribed before the plugins load (2026-11-02): the EndScene hook, ImGui and the + // engine's panels don't need them, and a login during a slow load (15-20 s after an + // update) used to wait for all of it. The plugin pump still starts only once they + // are loaded (OpenPluginPumpGate), so InitPlugins sees the whole list. if (InitAborted()) return; LoginLifecycleHooks.LoginComplete += RunPostLoginBootstrap; // ── Fast-login race guard (first launch, initCount==1) ─────────── // AC's SendLoginCompleteNotification can fire DURING the ~9 s - // hook-init / plugin-load window above — i.e. BEFORE the line above + // hook-init window above (before 2026-11-02 the plugin load too) — i.e. BEFORE the line above // subscribed RunPostLoginBootstrap. SignalLoginComplete raises the // event exactly once and does NOT replay for late subscribers, so a // fast login leaves RunPostLoginBootstrap never called: no EndScene @@ -1031,6 +1039,17 @@ public static class EntryPoint RunPostLoginBootstrap(); } + if (InitAborted()) return; + if (Plugins.EngineSettings.EnablePlugins) + { + RynthLog.Info("InitWorker DIAG — calling PluginManager.LoadPlugins."); + PluginManager.LoadPlugins(engineDir); + RynthLog.Info("InitWorker DIAG — PluginManager.LoadPlugins returned."); + } + else + RynthLog.Info("InitWorker: plugin loading disabled via engine.json (EnablePlugins=false)."); + OpenPluginPumpGate(PumpGatePluginsLoaded); + RynthLog.Info($"InitWorker: post-init checkpoint, _initCount={_initCount}"); if (InitAborted()) return; @@ -1231,6 +1250,7 @@ public static class EntryPoint ImGuiBackend.Panels.MonstersFace.Register(); ImGuiBackend.Panels.NavFace.Register(); ImGuiBackend.Panels.ItemsFace.Register(); + ImGuiBackend.Panels.ItemToolFace.Register(); // chest looter + Quick give (RynthAi's Item Tool) // Load the dashboard state file here, not on AC's thread. NOT through // RynthAiPanel: see the dispatcher invariant above ChatModel.EnsureSettingsLoaded. RynthAiDashboardState.EnsureLoaded(); @@ -1479,10 +1499,8 @@ public static class EntryPoint $"D3D9: Decal coexistence — '{DecalDetection.DetectedModule}' loaded, " + "skipping EndScene hook and ImGui init. " + "In-game overlay bars are disabled; Avalonia floating panels still work."); - if (Plugins.EngineSettings.EnablePlugins) - InitPluginsForDecalCoexistence(); - else - RynthLog.Info("DecalCoexistence: plugin pump disabled via engine.json (EnablePlugins=false)."); + _pumpForDecal = true; + OpenPluginPumpGate(PumpGateLogin); return; } @@ -1493,6 +1511,41 @@ public static class EntryPoint } RynthLog.Info("D3D9: Login complete — starting D3D9 bootstrapper."); D3D9Bootstrapper.Start(); + OpenPluginPumpGate(PumpGateLogin); + } + + // The plugin pump's two conditions (2026-11-02): login (RunPostLoginBootstrap) and the + // plugins loaded (InitWorker, after LoadPlugins, or at once without plugins). The + // bootstrap now runs as soon as login comes, which can be while the plugins still load; + // the pump waits for both, so InitPlugins never runs on a half-built list. + private const int PumpGateLogin = 1; + private const int PumpGatePluginsLoaded = 2; + private static int _pumpGate; + private static bool _pumpForDecal; // written before the login bit is set + + private static void OpenPluginPumpGate(int condition) + { + const int both = PumpGateLogin | PumpGatePluginsLoaded; + int before = Interlocked.Or(ref _pumpGate, condition); + if (before == both) + return; // opened already + if ((before | condition) != both) + { + if (condition == PumpGateLogin && Plugins.EngineSettings.EnablePlugins) + RynthLog.Info("NormalPluginPump: login came while the plugins load; it starts once they are loaded (the EndScene hook and ImGui start now)."); + return; + } + if (EngineLifecycle.IsShuttingDown) + return; + + if (_pumpForDecal) + { + if (Plugins.EngineSettings.EnablePlugins) + InitPluginsForDecalCoexistence(); + else + RynthLog.Info("DecalCoexistence: plugin pump disabled via engine.json (EnablePlugins=false)."); + return; + } // 2026-05-16: the plugin lifecycle no longer ticks from the EndScene // path. The 2026-05-10 design ran InitPlugins/ProcessPendingActions/ @@ -1512,6 +1565,14 @@ public static class EntryPoint RynthLog.Info("NormalPluginPump: disabled via engine.json (EnablePlugins=false)."); } + /// + /// The D3D9 path will make an ImGui context after login: the EndScene hook and the ImGui + /// backend are on, cimgui is loaded and Decal isn't in the way. Init worker. + /// + private static bool WillRunImGui() => + Plugins.EngineSettings.EnableD3D9Hook && Plugins.EngineSettings.EnableImGuiBackend + && _imGuiNativeHandle != IntPtr.Zero && !UseDecalCoexistencePath(); + private static int _decalInGameLogged; /// @@ -1912,8 +1973,71 @@ public static class EntryPoint } } + // The log stays open while the engine runs (2026-11-02). Opened and closed for every line, it made + // Windows Defender rescan the whole file (2-4 MB) on each close, dozens of times a second per client + // in a fight: two cores for five clients. Each line is still flushed to the OS at once. Delete sharing + // lets the next engine's startup rotation rename it; after shutdown (CloseLogFile) every line opens + // and closes the file again, so an unloaded engine never holds it. Under LogLock. + private static FileStream? _logStream; + private static bool _logStreamClosed; + // The open handle follows a renamed file: the startup rotation (LogPaths.RotateAtStartup) runs + // after the first lines are written, so it lets go first (ReleaseLogFile); and the path is checked + // every LogPathCheckMs, so a file moved or deleted by anything else is reopened at its path + // (2026-11-02: a reload's rotation left a client writing into its .log.old). + private const long LogPathCheckMs = 2000; + private static long _logPathCheckedAt; + + /// Lets go of the open log (the next line opens it again). Before the log is renamed. + internal static void ReleaseLogFile() + { + lock (LogLock) + { + try { _logStream?.Dispose(); } catch { } + _logStream = null; + } + } + + /// EngineLifecycle's last step: lines after it open and close the file each time. + internal static void CloseLogFile() + { + lock (LogLock) + { + _logStreamClosed = true; + try { _logStream?.Dispose(); } catch { } + _logStream = null; + } + } + private static void AppendWithRetry(string line) { + byte[] bytes = System.Text.Encoding.UTF8.GetBytes(line); + if (!_logStreamClosed) + { + try + { + long now = Environment.TickCount64; + if (_logStream != null && now - _logPathCheckedAt >= LogPathCheckMs) + { + _logPathCheckedAt = now; + if (!File.Exists(LogPaths.LogFilePath)) { try { _logStream.Dispose(); } catch { } _logStream = null; } + } + _logStream ??= new FileStream( + LogPaths.LogFilePath, + FileMode.Append, + FileAccess.Write, + FileShare.ReadWrite | FileShare.Delete); + _logStream.Seek(0, SeekOrigin.End); // the loader and the injector append to it too + _logStream.Write(bytes, 0, bytes.Length); + _logStream.Flush(); + return; + } + catch + { + try { _logStream?.Dispose(); } catch { } + _logStream = null; // the open-per-line path below, and a fresh handle next line + } + } + // Retry briefly to tolerate concurrent writers (loader DLL, injector // process). FileShare.ReadWrite on each open lets multiple writers // append; the small delays smooth over rare lock collisions. @@ -1927,7 +2051,6 @@ public static class EntryPoint FileMode.Append, FileAccess.Write, FileShare.ReadWrite); - byte[] bytes = System.Text.Encoding.UTF8.GetBytes(line); fs.Write(bytes, 0, bytes.Length); return; } diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 47339e2..acec36a 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -234,6 +234,30 @@ internal static class EngineFrameController } } + /// + /// Init worker, before the plugins load and before the EndScene hook can go in (2026-11-02): + /// starts the first atlas's bake (~2 s) for the game window's DPI scale, so it runs during the + /// world load rather than after login. Init's first part then finds it baking or baked; for a + /// different scale it bakes again (ImGuiFonts.StartInitialBake). + /// + internal static void StartEarlyFontBake() + { + float scale = UiScale.ForWindow(FindGameWindow()); + if (ImGuiFonts.StartInitialBake(scale)) + RynthLog.UI($"EngineFrameController: the font atlas bakes now, before login (scale {scale:0.##})."); + } + + /// + /// Engine shutdown, after the EndScene hook is gone: frees an atlas baked before login for a + /// context that was never made (no login, or the hook never got that far). With a context, + /// did it; a second call finds nothing to free. + /// + internal static void FreeFontsWithoutContext() + { + if (_context == IntPtr.Zero && !_imguiInitialized) + ImGuiFonts.Free(); + } + /// The new context's ini handling, flags, DPI scale and theme (Init's first part). Context current. private static void SetUpContext(ImGuiIOPtr io) { diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index f3c7fb5..3d1815a 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -81,7 +81,8 @@ internal static class ImGuiBar // Skills moves under RynthOracle (Skills / Attributes / Progress tabs): its icon shows only while Oracle's // tabs can't be reached (SkillsRouting.ShowSkillsBarIcon), so nobody loses the way in. Mini Remote stays. private static readonly string[] ImGuiOnlyBarPanels = - { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.MiniRemoteFace.Title }; + { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.MiniRemoteFace.Title, + Panels.ItemToolFace.Title }; /// An ImGui-only panel's bar button is wanted: it has a face, and Skills only while Oracle can't host it. private static bool ImGuiOnlyWanted(string title) => @@ -117,8 +118,10 @@ internal static class ImGuiBar ["Inventory"] = PhosphorIcons.Package, // not Backpack: the dashboard's Items launcher has that ["Log"] = PhosphorIcons.TerminalWindow, ["Item Count"] = PhosphorIcons.Bag, + ["Item Tool"] = PhosphorIcons.Wrench, ["Mini Remote"] = PhosphorIcons.SquaresFour, ["Characters"] = PhosphorIcons.UsersThree, + ["Item Tool"] = PhosphorIcons.Wrench, // RynthAi's chest looter + Quick give // Plugin windows with a bar button of their own (script windows, by title). ["RynthSort"] = PhosphorIcons.SortAscending, ["Oracle"] = PhosphorIcons.Sparkle, diff --git a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs index bf1fa42..6538205 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs @@ -433,6 +433,7 @@ internal static unsafe class ImGuiFonts private static System.Threading.Thread? _bakeThread; private static Bake? _bakeDone; // set by the worker as it ends + private static float _bakeScale; // the scale _bakeThread bakes for private static readonly List FreeThreads = new(); /// @@ -452,6 +453,7 @@ internal static unsafe class ImGuiFonts try { _bakeDone = null; + _bakeScale = scale; _bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps, prepare: false)); return false; } @@ -468,16 +470,26 @@ internal static unsafe class ImGuiFonts /// /// The first atlas of a context, baked on a worker (see the header): reading the font files if /// the init worker hasn't, making their native copies, queueing every font, rasterizing, the - /// BGRA copy and freeing the TTF copies all happen there. AC thread, once the scale is known. - /// False when no worker could be started (the caller then calls ). + /// BGRA copy and freeing the TTF copies all happen there. AC thread, once the scale is known, + /// or the init worker before login (EngineFrameController.StartEarlyFontBake; never both at + /// once: the EndScene hook goes in after that call). False when no worker could be started + /// (the caller then calls ). /// public static bool StartInitialBake(float scale) { - if (_bakeThread != null) return true; + if (_bakeThread != null) + { + // Started early, on the init worker before login (EngineFrameController.StartEarlyFontBake), + // for the scale the game window had then: kept when the context gets that scale too. + if (_bakeScale == scale) return true; + RynthLog.UI($"ImGuiFonts: the atlas baked before login is for scale {_bakeScale:0.##}, the context's is {scale:0.##}: baking again."); + DropBake(); + } List steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse(); try { _bakeDone = null; + _bakeScale = scale; _bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps, prepare: true)); return true; } @@ -489,6 +501,18 @@ internal static unsafe class ImGuiFonts } } + /// Waits for the running bake and frees what it made, never swapped in. + private static void DropBake() + { + _bakeThread?.Join(); + _bakeThread = null; + Bake? pending = _bakeDone; + _bakeDone = null; + if (pending == null) return; + if (pending.Atlas != IntPtr.Zero) ImGuiNative.ImFontAtlas_destroy((ImFontAtlas*)pending.Atlas); + FreeBgraPixels(pending.Bgra); + } + /// /// Render thread, with 's context current: swaps a finished bake (the /// first atlas, or a re-bake) into it. True when the atlas changed (the caller makes its @@ -642,15 +666,7 @@ internal static unsafe class ImGuiFonts { // A worker may still read the buffers below (a bake) or free an atlas. WaitForWorkers(); - if (_bakeThread != null || _bakeDone != null) - { - _bakeThread = null; - Bake? pending = _bakeDone; - _bakeDone = null; - if (pending != null && pending.Atlas != IntPtr.Zero) - ImGuiNative.ImFontAtlas_destroy((ImFontAtlas*)pending.Atlas); // baked, never swapped in - if (pending != null) FreeBgraPixels(pending.Bgra); - } + DropBake(); // baked, never swapped in FreeBgraPixels(_bgra); _bgra = IntPtr.Zero; _bgraWidth = _bgraHeight = 0; diff --git a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicMainTab.cs b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicMainTab.cs index f5cb768..f8f2e07 100644 --- a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicMainTab.cs +++ b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicMainTab.cs @@ -8,7 +8,7 @@ // (the subsystem toggles) with a live line // Ranges monster range, ring range, approach, follow/nav min // Behavior autostack, autocram, peace mode / rebuff when idle, -// navigation first, looting first, rare corpses only, +// navigate only, looting first, rare corpses only, // manage fellowship // Magic and pets dispel items / self, M. charges when off, summon pets, // pet range, pet min monsters @@ -50,7 +50,7 @@ internal sealed class ClassicMainTab : IClassicTab private static readonly (string Schema, string Label)[] BehaviorRight = { - ("Boost Nav Priority", "Navigation first"), ("Boost Loot Priority", "Looting first"), + ("Boost Nav Priority", "Navigate only (no hunting, no looting)"), ("Boost Loot Priority", "Looting first"), ("Loot Only Rare Corpses", "Rare corpses only"), ("Auto Fellowship Management", "Manage fellowship"), }; diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs new file mode 100644 index 0000000..7a61065 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ItemToolFace.cs @@ -0,0 +1,143 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ItemToolFace.cs +// The Item Tool panel: two small tools of RynthAi's, each picked, started and +// stopped by the player. Engine only, ImGui only; the work is RynthAi's +// (RynthAiPlugin.ItemTool.cs), this is its buttons and status lines. +// +// Chest looter "Pick a chest. Pick a key. It just loots the chest based on the +// current loot profile until it's out of keys." +// Select the chest in the world, press Use selected as chest; +// select the key in your pack, press Use selected as key; Start. +// Quick give Select an item in your pack (Use selected as item) and a player +// or NPC in the world (Use selected as target), press Give: every +// such item in your packs is handed over, one give at a time. +// The target's name is shown (PLAYER for a player). +// +// Data: ItemToolSource (RynthPluginGetItemToolJson, 250 ms while open). Buttons +// post words to RynthPluginItemToolCommand (ItemToolCommands.Send), the same +// words as "/ra itemtool ...". Draw reads a snapshot and posts; no AC calls. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class ItemToolFace : IImGuiPanel +{ + public const string Title = "Item Tool"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(320, 400), new Vector2(240, 260), EdgeToEdge: true, GripInBody: true), + () => new ItemToolFace()); + + public void OnShown() + { + UiSources.ItemTool.Subscribe(); + UiSources.ItemTool.RequestRefresh(); + } + + public void OnHidden() => UiSources.ItemTool.Unsubscribe(); + + public void Draw() + { + float w = Begin(out Vector2 origin, out Vector2 size); + ItemToolSnapshot? snap = UiSources.ItemTool.Current?.Value; + float bodyH = Math.Max(30, Remaining(origin, size) - GripOverlap()); + ImGuiNET.ImGui.BeginChild("##itemtool_body", new Vector2(w, bodyH)); + if (snap == null) + Wrapped("Waiting for RynthAi (log in, and RynthAi must be loaded).", Mute, w); + else + { + DrawChest(snap.Chest, w); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + Separator(w); + DrawGive(snap.Give, w); + } + ImGuiNET.ImGui.EndChild(); + End(origin, size); + } + + // ── Chest looter ──────────────────────────────────────────────────── + + private static void DrawChest(ChestToolState c, float w) + { + Label("Chest looter", Teal); + Wrapped("Loots the chest with the current loot profile, then waits for it to re-lock and goes again, until the key is used up.", Mute, w); + Pick("Chest:", c.Name, "(none: select the chest in the world)", w); + Pick("Key:", c.Key, "(none: select the key in your pack)", w); + + bool ready = c.Name.Length > 0 && c.Key.Length > 0; + int hit = WrapButtons("##chest_pick", new[] { "Use selected as chest", "Use selected as key" }, w, 22, + new[] { !c.Running, !c.Running }); + if (hit == 0) ItemToolCommands.Send("chest set"); + else if (hit == 1) ItemToolCommands.Send("chest key"); + + hit = StartStop("##chest_run", "Start", "Stop", ready && !c.Running, c.Running, w); + if (hit == 0) ItemToolCommands.Send("chest start"); + else if (hit == 1) ItemToolCommands.Send("chest stop"); + + Wrapped(c.Status, c.Running ? Amber : Text, w); + } + + // ── Quick give ────────────────────────────────────────────────────── + + private static void DrawGive(GiveToolState g, float w) + { + Label("Quick give", Teal); + Wrapped("Hands every matching item in your packs to one player or NPC, one give at a time, until none is left or you press Stop. Never worn gear.", Mute, w); + Pick("Item:", g.Item, "(none: select the item in your pack)", w); + Pick("Target:", g.Target, "(none: select the player or NPC in the world)", w); + + bool ready = g.Item.Length > 0 && g.Target.Length > 0; + int hit = WrapButtons("##give_pick", new[] { "Use selected as item", "Use selected as target" }, w, 22, + new[] { !g.Running, !g.Running }); + if (hit == 0) ItemToolCommands.Send("giveitem"); + else if (hit == 1) ItemToolCommands.Send("givetarget"); + + hit = StartStop("##give_run", "Give", "Stop", ready && !g.Running, g.Running, w); + if (hit == 0) ItemToolCommands.Send("give"); + else if (hit == 1) ItemToolCommands.Send("givestop"); + + Wrapped(g.Status, g.Running ? Amber : Text, w); + } + + // ── Pieces ────────────────────────────────────────────────────────── + + /// "Label value" (amber while nothing is picked, the hint then). + private static void Pick(string label, string value, string hint, float w) + { + Label(label, Mute); + ImGuiNET.ImGui.SameLine(0, 6); + bool none = value.Length == 0; + Wrapped(none ? hint : value, none ? Mute : Text, Math.Max(40, w - ImGuiNET.ImGui.CalcTextSize(label).X - 10)); + } + + /// A Start and a Stop button side by side; returns 0 (start), 1 (stop) or -1. + private static int StartStop(string id, string startLabel, string stopLabel, bool canStart, bool canStop, float w) + { + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + const float h = 24; + float bw = Math.Max(ButtonWidth(startLabel), ButtonWidth(stopLabel)) + 20; + int hit = -1; + ImGuiNET.ImGui.PushID(id); + if (Button("##start", startLabel, start, new Vector2(bw, h), Text, StartBg, canStart)) hit = 0; + if (Button("##stop", stopLabel, new Vector2(start.X + bw + 6, start.Y), new Vector2(bw, h), Text, StopBg, canStop)) hit = 1; + ImGuiNET.ImGui.PopID(); + NextLine(start, h + 4); + return hit; + } + + private static void Wrapped(string text, uint color, float w) + { + if (text.Length == 0) return; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs index 7a29131..f6fcc43 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs @@ -288,7 +288,7 @@ internal sealed partial class MetaFace : IImGuiPanel Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); const float refreshW = 26; float saveAsW = BtnW("Save As", 60), indW = SaveIndicatorWidth(); - float pickW = Math.Max(60, w - refreshW - saveAsW - indW - 12); + float pickW = Math.Max(60, w - refreshW * 2 - saveAsW - indW - 16); int picked = Picker("##file", _fileDisplay, _fileDisplays, MetaVocabulary.CurrentFileIndex(_data), p, pickW); if (picked >= 0 && picked < _data.Files.Count) { @@ -302,6 +302,18 @@ internal sealed partial class MetaFace : IImGuiPanel UiSources.Meta.RequestRefresh(); ImGuiNET.ImGui.SetItemTooltip("Refresh file list"); x += refreshW + 4; + // Reload: read the loaded meta's file again (the same as picking it in the list), e.g. after + // a new build of it was copied in. + int cur = MetaVocabulary.CurrentFileIndex(_data); + string? reloadPath = cur >= 0 && cur < _data.Files.Count ? _data.Files[cur].Path : _data.CurrentMetaPath; + if (IconButton("##reload", PhosphorIcons.ArrowCounterClockwise, new Vector2(x, p.Y), new Vector2(refreshW, 22), TextDim, BtnFill, BtnBord, + font: UiFont.Ui14) && !string.IsNullOrEmpty(reloadPath)) + { + FlushEdit(); + MetaCommands.Simple("load_file", path: reloadPath); + } + ImGuiNET.ImGui.SetItemTooltip("Reload this meta from its file"); + x += refreshW + 4; 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(); @@ -875,6 +887,9 @@ internal sealed partial class MetaFace : IImGuiPanel /// one more entry after the items ("+ New state..."): picking it returns items.Length. Returns the /// picked index or -1. /// + // Set when a picker's list is opened; the first frame of the list scrolls its chosen row to the top. + private bool _pickerScrollToSelected; + private int Picker(string id, string shown, string[] items, int selected, Vector2 pos, float width, float height = 22, string? extra = null, string? badge = null) { @@ -888,6 +903,7 @@ internal sealed partial class MetaFace : IImGuiPanel Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(pos.X, 0, Math.Max(0, display.X - listW)), pos.Y + height)); ImGuiNET.ImGui.OpenPopup("##list"); + _pickerScrollToSelected = true; } bool hot = ImGuiNET.ImGui.IsItemHovered(); dl.AddRectFilled(pos, pos + new Vector2(width, height), hot ? Lighten(BtnFill) : BtnFill, 3); @@ -931,6 +947,8 @@ internal sealed partial class MetaFace : IImGuiPanel ImGuiNET.ImGui.PopID(); bool isExtra = i == items.Length; bool sel = !isExtra && i == selected; + // The list opens with the chosen row at its top, not at the first row every time. + if (sel && _pickerScrollToSelected) ImGuiNET.ImGui.SetScrollHereY(0f); 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, @@ -942,6 +960,7 @@ internal sealed partial class MetaFace : IImGuiPanel } } ImGuiNET.ImGui.EndPopup(); + _pickerScrollToSelected = false; } ImGuiNET.ImGui.PopID(); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, pos.Y + height)); diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index f0720c0..1206914 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -1144,6 +1144,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel SkillsMenuItem("Progress", "/rc progression", 2, "Augmentation, Enlightenment and XP planners (Infinite Leaftide)."); PanelMenuItem(InventoryFace.Title, "/rc inventory"); PanelMenuItem(ItemCountFace.Title, "/rc itemcount"); + PanelMenuItem(ItemToolFace.Title, "/rc itemtool"); // RynthInventory's script window (same as /ginv and Inventory's GInv button). const string ginvKey = "RynthInventory/Main"; bool hasGinv = UI.ScriptWindows.ScriptWindowRegistry.Has(ginvKey); diff --git a/src/RynthCore.Engine/LogPaths.cs b/src/RynthCore.Engine/LogPaths.cs index ee3e987..e6b99ee 100644 --- a/src/RynthCore.Engine/LogPaths.cs +++ b/src/RynthCore.Engine/LogPaths.cs @@ -100,6 +100,7 @@ internal static class LogPaths if (size < MaxLogBytes) return; string rotated = RotatedLogFilePath; + EntryPoint.ReleaseLogFile(); // the engine's open handle would follow the file to .old try { if (File.Exists(rotated)) File.Delete(rotated); } catch { } try { File.Move(active, rotated); } diff --git a/src/RynthCore.Engine/Net/InventoryOrder.cs b/src/RynthCore.Engine/Net/InventoryOrder.cs index 79477fe..2d4224a 100644 --- a/src/RynthCore.Engine/Net/InventoryOrder.cs +++ b/src/RynthCore.Engine/Net/InventoryOrder.cs @@ -76,6 +76,21 @@ internal static class InventoryOrder return false; } + /// + /// A hash of one list (FNV-1a over its ids), 0 when it isn't known: a cheap "did this list + /// change" for a view that is rebuilt only on change. Allocates nothing. + /// + public static uint ListHash(uint container, bool slotKind) + { + lock (Gate) + { + if (!Lists.TryGetValue((container, slotKind), out List? l)) return 0; + uint h = 2166136261u ^ (uint)l.Count; + foreach (uint id in l) h = (h ^ id) * 16777619u; + return h == 0 ? 1u : h; + } + } + /// /// One whole server message, starting at its opcode (the way ServerMessageStream delivers it). /// Anything else is ignored; a malformed one is dropped. @@ -104,9 +119,16 @@ internal static class InventoryOrder // The login message is the only place the main pack's order arrives, and a hot reload of the engine // (every deploy, and any crash recovery) would lose it until the next login. So the lists are // saved as they change and read back when the engine starts. Layout: 'IORD', version u32, list count - // u32, then per list: container u32, slot-kind u8, count u32, ids u32 each. + // u32, then per list: container u32, slot-kind u8, count u32, ids u32 each; version 2 adds the + // player's id (u32) after the list count. The player matters after a restore: their lists are the + // ones never dropped for room (Evict), and a version 1 file didn't say who they were, so a hunt + // that opened 64 corpses after an engine reload pushed the main pack's lists out. private const uint Magic = 0x44524F49; // "IORD" + private const uint FormatVersion = 2; + + /// The character whose login list this is (0 before one was seen or restored). + public static uint Player { get { lock (Gate) return _player; } } public static byte[] Serialize() { @@ -114,7 +136,7 @@ internal static class InventoryOrder { var ms = new System.IO.MemoryStream(); var w = new System.IO.BinaryWriter(ms); - w.Write(Magic); w.Write(1u); w.Write((uint)Lists.Count); + w.Write(Magic); w.Write(FormatVersion); w.Write((uint)Lists.Count); w.Write(_player); foreach (KeyValuePair<(uint, bool), List> kv in Lists) { w.Write(kv.Key.Item1); w.Write(kv.Key.Item2 ? (byte)1 : (byte)0); w.Write((uint)kv.Value.Count); @@ -130,10 +152,19 @@ internal static class InventoryOrder { try { - if (data.Length < 12 || U32(data, 0) != Magic || U32(data, 4) != 1) return false; + if (data.Length < 12 || U32(data, 0) != Magic) return false; + uint format = U32(data, 4); + if (format is not (1 or 2)) return false; uint lists = U32(data, 8); if (lists > 4096) return false; int at = 12; + uint player = 0; + if (format >= 2) + { + if (data.Length < 16) return false; + player = U32(data, 12); + at = 16; + } var loaded = new Dictionary<(uint, bool), List>(); for (uint i = 0; i < lists; i++) { @@ -145,10 +176,12 @@ internal static class InventoryOrder for (uint k = 0; k < n; k++) { l.Add(U32(data, at)); at += 4; } loaded[(container, slot)] = l; } + if (player == 0) player = PlayerOf(loaded.Keys); lock (Gate) { Lists.Clear(); Touched.Clear(); + _player = player; foreach (KeyValuePair<(uint, bool), List> kv in loaded) { Lists[kv.Key] = kv.Value; Touched[kv.Key.Item1] = ++_clock; } Evict(); _version++; @@ -158,6 +191,49 @@ internal static class InventoryOrder catch (ArgumentOutOfRangeException) { return false; } } + /// + /// Puts [..] in 's + /// order (a pack-slot list: the pack column, top first) when it names every one of them; else + /// leaves them as they are and returns false (one the list lacks would land somewhere made up). + /// Entries of the list that aren't among them (foci, packs not read) don't matter. Pure. + /// + public static bool SortByColumn(T[] items, int start, Func idOf, IReadOnlyList column) + { + if (start < 0 || start > items.Length) return false; + var rank = new Dictionary(column.Count); + for (int i = 0; i < column.Count; i++) rank.TryAdd(column[i], i); + for (int i = start; i < items.Length; i++) + if (!rank.ContainsKey(idOf(items[i]))) return false; + Array.Sort(items, start, items.Length - start, Comparer.Create((a, b) => rank[idOf(a)].CompareTo(rank[idOf(b)]))); + return true; + } + + /// + /// A saved order file belongs to this client when it was written after the client's process + /// started (a minute's slack for clock rounding); an older one is a recycled process id's. + /// Its age says nothing else: it is only written when an order changes, so a quiet client's + /// file can be days old and still right. Unknown start time: trust it (the name has the pid). + /// + internal static bool SavedFileIsOurs(DateTime writtenUtc, DateTime? processStartUtc) => + processStartUtc is not DateTime start || writtenUtc >= start - TimeSpan.FromMinutes(1); + + /// + /// The player in a version 1 file: the one container with a pack-slot list in the player id + /// range (ACE's player guids, 0x50000001-0x5FFFFFFF). Only the login list has that; an opened + /// side pack or corpse is an item id. 0 when none or several. + /// + internal static uint PlayerOf(IEnumerable<(uint Container, bool Slot)> keys) + { + uint found = 0; + foreach ((uint c, bool slot) in keys) + { + if (!slot || c < 0x50000000u || c > 0x5FFFFFFFu || c == found) continue; + if (found != 0) return 0; + found = c; + } + return found; + } + // ── ViewContents: container, count, count x (id, type) ────────────────── private static void OnViewContents(ReadOnlySpan p) diff --git a/src/RynthCore.Engine/Net/ServerMessageStream.cs b/src/RynthCore.Engine/Net/ServerMessageStream.cs index a40bc4c..f8a8eb4 100644 --- a/src/RynthCore.Engine/Net/ServerMessageStream.cs +++ b/src/RynthCore.Engine/Net/ServerMessageStream.cs @@ -125,10 +125,22 @@ internal static unsafe class ServerMessageStream { _orderRestored = true; string f = OrderFile; - // Only this client's own file, and not a stale one (a recycled process id). - if (File.Exists(f) && DateTime.UtcNow - File.GetLastWriteTimeUtc(f) < TimeSpan.FromHours(24) - && InventoryOrder.Restore(File.ReadAllBytes(f))) - RynthLog.Compat("ServerMessageStream: restored the server's item order saved before this engine loaded."); + // Only this client's own file: one written since this process started (an older one + // is a recycled process id's). The file is only written when an order changes, so its + // age says nothing else: the 24-hour limit this replaces refused a quiet client's file + // a day after its last move, and that client then had no order until it logged in again. + if (File.Exists(f)) + { + DateTime written = File.GetLastWriteTimeUtc(f); + if (!InventoryOrder.SavedFileIsOurs(written, ProcessStartUtc())) + RynthLog.Compat($"ServerMessageStream: item order file is older than this client ({written:yyyy-MM-dd HH:mm} UTC): not used. Pack orders are known again after the next login."); + else if (InventoryOrder.Restore(File.ReadAllBytes(f))) + RynthLog.Compat($"ServerMessageStream: restored the server's item order saved before this engine loaded (player 0x{InventoryOrder.Player:X8})."); + else + RynthLog.Compat("ServerMessageStream: item order file unreadable: not used. Pack orders are known again after the next login."); + } + else + RynthLog.Compat("ServerMessageStream: no saved item order for this client (normal before its first login)."); _orderSavedVersion = InventoryOrder.Version; return; } @@ -145,6 +157,12 @@ internal static unsafe class ServerMessageStream } } + private static DateTime? ProcessStartUtc() + { + try { using var me = System.Diagnostics.Process.GetCurrentProcess(); return me.StartTime.ToUniversalTime(); } + catch { return null; } + } + public static void Pump(bool pluginsWant) { KeepInventoryOrder(Environment.TickCount64); diff --git a/src/RynthCore.Engine/Plugins/PluginFilePrefetch.cs b/src/RynthCore.Engine/Plugins/PluginFilePrefetch.cs new file mode 100644 index 0000000..7c7b987 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/PluginFilePrefetch.cs @@ -0,0 +1,106 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/PluginFilePrefetch.cs +// Opens the plugin files (PluginFilePrefetchList) on a few worker threads as the +// init worker starts, seconds ahead of LoadPlugins. Nothing is loaded or kept open. +// +// Why (2026-11-02): the first open of a new or changed file waits while the +// antivirus (Windows Defender's real-time protection) scans all of it. After an +// update every plugin file is new, and the one-file-at-a-time plugin load spent +// 15-20 s in those scans: 8 s reading the manifests, 12 s loading 14 plugins, all +// before the EndScene hook went in. Measured offline on the same 116 files +// (27 MB): opened one at a time 15.1 s, on 8 threads 4.6 s; loaded again after +// that, the whole plugin set took 0.6 s instead of 15 s. Scans of different files +// run at once, and a load that opens a file still being scanned just waits for +// that scan, so nothing here has to finish before LoadPlugins starts. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Threading; + +namespace RynthCore.Engine.Plugins; + +internal static class PluginFilePrefetch +{ + private const int MaxThreads = 8; + + private static readonly ConcurrentQueue Queue = new(); + private static readonly object SlowestLock = new(); + private static int _started; + private static int _remaining; + private static int _total; + private static long _startTicks; + private static double _slowestMs; + private static string _slowest = ""; + + /// Starts the workers (once per engine generation). Init worker. + public static void Start(IReadOnlyList pluginPaths) + { + if (Interlocked.Exchange(ref _started, 1) != 0) return; + List files; + try + { +#if ENGINE_CORECLR + files = PluginFilePrefetchList.Build(pluginPaths, ManagedPlugins.SharedDir); +#else + files = PluginFilePrefetchList.Build(pluginPaths, null); +#endif + } + catch (Exception ex) + { + RynthLog.Plugin($"PluginFilePrefetch: file list failed ({ex.GetType().Name}: {ex.Message}); the plugins load without it."); + return; + } + if (files.Count == 0) return; + + foreach (string f in files) Queue.Enqueue(f); + _total = _remaining = files.Count; + _startTicks = Stopwatch.GetTimestamp(); + int threads = Math.Min(files.Count, Math.Clamp(Environment.ProcessorCount, 2, MaxThreads)); + RynthLog.Plugin($"PluginFilePrefetch: opening {files.Count} plugin file(s) on {threads} thread(s) ahead of the plugin load (antivirus scans of new files run at once)."); + for (int i = 0; i < threads; i++) + { + try { EngineThreads.Start($"PluginFilePrefetch.{i}", Worker); } + catch (Exception ex) + { + RynthLog.Plugin($"PluginFilePrefetch: thread {i} did not start ({ex.GetType().Name}); the others go on."); + break; + } + } + } + + private static void Worker() + { + while (!EngineThreads.Stopping && Queue.TryDequeue(out string? path)) + { + long t0 = Stopwatch.GetTimestamp(); + Touch(path); + double ms = Stopwatch.GetElapsedTime(t0).TotalMilliseconds; + lock (SlowestLock) + { + if (ms > _slowestMs) { _slowestMs = ms; _slowest = Path.GetFileName(path); } + } + if (Interlocked.Decrement(ref _remaining) == 0) + { + double total = Stopwatch.GetElapsedTime(_startTicks).TotalMilliseconds; + RynthLog.Plugin($"PluginFilePrefetch: {_total} file(s) opened in {total:0} ms (slowest {_slowest} {_slowestMs:0} ms)."); + } + } + } + + private static void Touch(string path) + { + try + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1, FileOptions.SequentialScan); + fs.ReadByte(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // The load opens it again and reports what's wrong. + } + } +} diff --git a/src/RynthCore.Engine/Plugins/PluginFilePrefetchList.cs b/src/RynthCore.Engine/Plugins/PluginFilePrefetchList.cs new file mode 100644 index 0000000..be1bf17 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/PluginFilePrefetchList.cs @@ -0,0 +1,67 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/PluginFilePrefetchList.cs +// The files PluginFilePrefetch opens ahead of the plugin load: each listed +// plugin's DLL first (in engine.json order: the manifest gate reads them first), +// then the other DLLs and PDBs in each plugin's folder (its dependencies and +// symbols, which ManagedPlugins loads), then Runtime\PluginShared's DLLs. +// Top-level files only; each file once (any case); missing plugins skipped. +// +// BCL only, so tools\PluginManifestTests compiles it too. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; + +namespace RynthCore.Engine.Plugins; + +internal static class PluginFilePrefetchList +{ + public static List Build(IReadOnlyList pluginPaths, string? sharedDir) + { + var files = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var folders = new List(); + var seenFolders = new HashSet(StringComparer.OrdinalIgnoreCase); + + void Add(string path) + { + string full; + try { full = Path.GetFullPath(path); } + catch { return; } + if (seen.Add(full)) files.Add(full); + } + + foreach (string path in pluginPaths) + { + if (string.IsNullOrWhiteSpace(path)) continue; + string trimmed = path.Trim(); + if (!File.Exists(trimmed)) continue; + Add(trimmed); + string? dir = Path.GetDirectoryName(Path.GetFullPath(trimmed)); + if (dir != null && seenFolders.Add(dir)) folders.Add(dir); + } + + foreach (string dir in folders) + AddFolder(dir, Add, withPdbs: true); + if (!string.IsNullOrEmpty(sharedDir)) + AddFolder(sharedDir, Add, withPdbs: false); + return files; + } + + private static void AddFolder(string dir, Action add, bool withPdbs) + { + try + { + if (!Directory.Exists(dir)) return; + var found = new List(Directory.GetFiles(dir, "*.dll", SearchOption.TopDirectoryOnly)); + if (withPdbs) found.AddRange(Directory.GetFiles(dir, "*.pdb", SearchOption.TopDirectoryOnly)); + found.Sort(StringComparer.OrdinalIgnoreCase); + foreach (string f in found) add(f); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A folder that can't be listed is left to the load itself. + } + } +} diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 19576f0..bb0849b 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -2706,6 +2706,7 @@ internal static partial class PluginManager private static void LoadPluginsFromDisk() { _loadGeneration++; + long loadT0 = System.Diagnostics.Stopwatch.GetTimestamp(); // Plugin discovery is opt-in via the launcher UI: users add specific // DLL paths through "Add Plugin DLL", which the launcher persists to @@ -2754,10 +2755,14 @@ internal static partial class PluginManager // a newer engine API or a missing plugin, and put required plugins first. Without // manifests the list loads exactly as before. Server plugins: the connect host picks this // server's (the others stay unloaded; their runtimes would only take address space). + long planT0 = System.Diagnostics.Stopwatch.GetTimestamp(); PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(candidates, PluginContractVersion.Current, RawFileVersion, Compatibility.ServerInfo.LaunchHost, EngineSettings.LoadAllServerPlugins); + double planMs = System.Diagnostics.Stopwatch.GetElapsedTime(planT0).TotalMilliseconds; foreach (string line in plan.Log) RynthLog.Plugin($"PluginManager: {line}"); + // A first open after an update waits for the antivirus scan of the file (PluginFilePrefetch). + RynthLog.Plugin($"PluginManager: {candidates.Count} manifest(s) read in {planMs:0} ms."); if (plan.SkippedForServer.Count > 0) RynthLog.Info($"PluginManager: {plan.SkippedForServer.Count} server plugin(s) for other servers not loaded (host {Compatibility.ServerInfo.HostDescription})."); RememberSkippedServerPlugins(plan.SkippedServerPlugins); @@ -2777,8 +2782,10 @@ internal static partial class PluginManager // Address space before and after each load: a 32-bit client runs out on the largest // free block, and a reload stacks copies (Compatibility/AddressSpace.cs). RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath} (va before: {Compatibility.AddressSpace.Describe()})"); + long oneT0 = System.Diagnostics.Stopwatch.GetTimestamp(); var plugin = PluginLoader.LoadSingle(dllPath, _shadowRootDir, _loadGeneration); - RynthLog.Plugin($"PluginManager: loaded {Path.GetFileName(dllPath)}{(plugin == null ? " (FAILED)" : "")} (va after: {Compatibility.AddressSpace.Describe()})"); + double oneMs = System.Diagnostics.Stopwatch.GetElapsedTime(oneT0).TotalMilliseconds; + RynthLog.Plugin($"PluginManager: loaded {Path.GetFileName(dllPath)}{(plugin == null ? " (FAILED)" : "")} in {oneMs:0} ms (va after: {Compatibility.AddressSpace.Describe()})"); Compatibility.MemoryUse.Mark($"{Path.GetFileNameWithoutExtension(dllPath)} loaded"); if (plugin != null) { @@ -2791,7 +2798,7 @@ internal static partial class PluginManager // RenderAll / RenderOverlayAll iterate only this snapshot; without it they see no plugins. PublishPluginsRenderSnapshot(); - RynthLog.Plugin($"PluginManager: render snapshot published ({_plugins.Count} plugin(s))."); + RynthLog.Plugin($"PluginManager: render snapshot published ({_plugins.Count} plugin(s)); the plugins loaded in {System.Diagnostics.Stopwatch.GetElapsedTime(loadT0).TotalMilliseconds:0} ms (manifests {planMs:0} ms)."); } private static void TryAddCanonicalPath(HashSet set, string path) @@ -2909,6 +2916,7 @@ internal static partial class PluginManager plugin.NotStartedReason = ""; LoadedPlugin? outer = EnterDispatch(plugin); + long initT0 = System.Diagnostics.Stopwatch.GetTimestamp(); try { int result = plugin.Init!(ref _api); @@ -2918,7 +2926,7 @@ internal static partial class PluginManager plugin.Failed = false; plugin.UIInitializedDispatched = false; plugin.LoginCompleteDispatched = false; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} initialized OK (api v{PluginContractVersion.Current})."); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} initialized OK (api v{PluginContractVersion.Current}) in {System.Diagnostics.Stopwatch.GetElapsedTime(initT0).TotalMilliseconds:0} ms."); Compatibility.MemoryUse.Mark($"{plugin.DisplayName} Init"); } else @@ -3027,11 +3035,12 @@ internal static partial class PluginManager continue; LoadedPlugin? outer = EnterDispatch(plugin); + long loginT0 = System.Diagnostics.Stopwatch.GetTimestamp(); try { plugin.OnLoginComplete(); plugin.LoginCompleteDispatched = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnLoginComplete."); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnLoginComplete ({System.Diagnostics.Stopwatch.GetElapsedTime(loginT0).TotalMilliseconds:0} ms)."); Compatibility.MemoryUse.Mark($"{plugin.DisplayName} OnLoginComplete"); } catch (Exception ex) diff --git a/src/RynthCore.Engine/UI/Data/ItemToolData.cs b/src/RynthCore.Engine/UI/Data/ItemToolData.cs new file mode 100644 index 0000000..bf87132 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ItemToolData.cs @@ -0,0 +1,110 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ItemToolData.cs +// The Item Tool panel's data (ImGui/Panels/ItemToolFace.cs): RynthAi's chest +// looter and Quick give, as RynthAi's RynthPluginGetItemToolJson reports them +// (picked chest/key/item/target and a status line each), and the panel's +// buttons as words posted to RynthPluginItemToolCommand (the same words as +// "/ra itemtool ..."; RynthAi's RynthAiPlugin.ItemTool.cs runs them on its tick). +// +// RynthPluginGetItemToolJson frees its previous buffer on each call, so the hub +// is its only caller (ItemToolSource, 250 ms while the panel is open). The +// command export is the panel's alone: Quick give starts only from a button +// pressed here or a line the player types, never from a remote command. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Text.Json.Serialization; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class ItemToolSnapshot +{ + [JsonPropertyName("chest")] public ChestToolState Chest { get; set; } = new(); + [JsonPropertyName("give")] public GiveToolState Give { get; set; } = new(); +} + +internal sealed class ChestToolState +{ + [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; + [JsonPropertyName("key")] public string Key { get; set; } = string.Empty; + [JsonPropertyName("status")] public string Status { get; set; } = string.Empty; + [JsonPropertyName("running")] public bool Running { get; set; } + [JsonPropertyName("looted")] public int Looted { get; set; } +} + +internal sealed class GiveToolState +{ + [JsonPropertyName("item")] public string Item { get; set; } = string.Empty; + [JsonPropertyName("target")] public string Target { get; set; } = string.Empty; + [JsonPropertyName("status")] public string Status { get; set; } = string.Empty; + [JsonPropertyName("running")] public bool Running { get; set; } + [JsonPropertyName("given")] public int Given { get; set; } +} + +[JsonSerializable(typeof(ItemToolSnapshot))] +internal sealed partial class ItemToolJsonContext : JsonSerializerContext { } + +/// RynthPluginGetItemToolJson while the Item Tool panel is open (250 ms, and after each button). +internal sealed unsafe class ItemToolSource : UiSource +{ + private delegate* unmanaged[Cdecl] _get; + private string? _lastJson; + + public ItemToolSource() : base("ItemTool", periodMs: 250) { } + + protected internal override void Poll() + { + if (_get == null) + _get = (delegate* unmanaged[Cdecl])PluginExportBinder.Resolve("RynthAi", "RynthPluginGetItemToolJson"); + if (_get == null) return; + IntPtr ptr = _get(); + string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringAnsi(ptr); + if (string.IsNullOrEmpty(json) || json == _lastJson) return; + ItemToolSnapshot? parsed; + try { parsed = JsonSerializer.Deserialize(json, ItemToolJsonContext.Default.ItemToolSnapshot); } + catch { return; } + if (parsed == null) return; + _lastJson = json; + Publish(parsed); + } + + protected internal override void Reset() + { + _get = null; + _lastJson = null; + ClearSnapshot(); + } +} + +internal static unsafe class ItemToolCommands +{ + private static delegate* unmanaged[Cdecl] _command; + + static ItemToolCommands() + { + PluginManager.PluginsUnloaded += () => _command = null; + } + + /// + /// Posts one Item Tool command ("chest set", "chest key", "chest start", "chest stop", "giveitem", + /// "givetarget", "give", "givestop"). Runs on the pump; RynthAi older than this build has no such + /// export: the click is logged and dropped. + /// + public static void Send(string words) => UiDataHub.Post("Item Tool " + words, () => + { + if (_command == null) + _command = (delegate* unmanaged[Cdecl])PluginExportBinder.Resolve("RynthAi", "RynthPluginItemToolCommand"); + if (_command == null) + { + RynthLog.UI($"ItemToolCommands: RynthPluginItemToolCommand not exported; dropped '{words}' (RynthAi is older than the Item Tool)."); + return; + } + IntPtr ansi = Marshal.StringToHGlobalAnsi(words); + try { _command(ansi); } + finally { Marshal.FreeHGlobal(ansi); } + UiSources.ItemTool.RequestRefresh(); + }); +} diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 4ace2d9..f558eb0 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -252,6 +252,7 @@ internal sealed class RynthAiSettings public bool BoostLootPriority { get; set; } public bool LootOnlyRareCorpses { get; set; } public bool LootJumpEnabled { get; set; } + public bool LootChestsMacroOff { get; set; } = true; // Pickup with macro off; a RynthAi that doesn't send it leaves it on public int LootJumpHeight { get; set; } = 10; public int LootOwnership { get; set; } // Recover your own death corpse whole (default on), and travel back to it after a death @@ -1237,7 +1238,8 @@ internal static class SettingsSchema new("Navigation", new[] { - Bool("Boost Nav Priority", s => s.BoostNavPriority, (s, v) => s.BoostNavPriority = v), + Bool("Boost Nav Priority", s => s.BoostNavPriority, (s, v) => s.BoostNavPriority = v, + "Navigate only: no hunting, no looting, no fighting back. With a route it walks it; without one it stands idle. Buffs and heals still run."), Float(NavPointReachLabel, s => s.FollowNavMin, (s, v) => s.FollowNavMin = v, 0.5f, 20f, 0.1f, NavPointReachTip), Spacer(), Section("Infinite Leaftide"), @@ -1392,6 +1394,8 @@ internal static class SettingsSchema Bool("Loot Only Rare Corpses", s => s.LootOnlyRareCorpses, (s, v) => s.LootOnlyRareCorpses = v), Bool("Learn Unknown Spells", s => s.ReadUnknownScrolls, (s, v) => s.ReadUnknownScrolls = v, "Loots scrolls of spells you don't know and can learn (magic school trained or\nspecialized, skill high enough), and reads them when it's safe. Scrolls already\nin your pack are read too. Needs Enable Looting for corpses."), + Bool("Pickup with macro off", s => s.LootChestsMacroOff, (s, v) => s.LootChestsMacroOff = v, + "A chest you open is looted by the loaded loot profile even with the macro or Looting off."), Bool("Stop Looting When Pack Full", s => s.StopLootingWhenPackFull, (s, v) => s.StopLootingWhenPackFull = v, "Don't start on another corpse when no pack has a free slot (says so once in chat)."), Bool("Jump When Looting", s => s.LootJumpEnabled, (s, v) => s.LootJumpEnabled = v, gates: true), diff --git a/src/RynthCore.Engine/UI/Data/UiSources.cs b/src/RynthCore.Engine/UI/Data/UiSources.cs index 8a086cb..d3009b1 100644 --- a/src/RynthCore.Engine/UI/Data/UiSources.cs +++ b/src/RynthCore.Engine/UI/Data/UiSources.cs @@ -23,6 +23,7 @@ internal static class UiSources public static readonly LuaSource Lua = new(); public static readonly NavSource Nav = new(); public static readonly ItemsSource Items = new(); + public static readonly ItemToolSource ItemTool = new(); public static readonly VisionSource Vision = new(); public static readonly RynthNavSource RynthNav = new(); public static readonly RynthNavAtlasSource RynthNavAtlas = new(); @@ -48,6 +49,7 @@ internal static class UiSources UiDataHub.Register(Lua); UiDataHub.Register(Nav); UiDataHub.Register(Items); + UiDataHub.Register(ItemTool); UiDataHub.Register(Vision); UiDataHub.Register(RynthNav); UiDataHub.Register(RynthNavAtlas); diff --git a/src/RynthCore.StatusAgent/Program.cs b/src/RynthCore.StatusAgent/Program.cs index 418a009..c4a3f6b 100644 --- a/src/RynthCore.StatusAgent/Program.cs +++ b/src/RynthCore.StatusAgent/Program.cs @@ -146,6 +146,10 @@ FileSystemWatcher? watcher = opts.Once ? null : TryArmStatusWatcher(cfg.StatusDi string _lastSummaryShape = ""; long _lastSummaryMs = 0; const long SummaryEveryMs = 10 * 60_000; +// aggregate.json is a debugging copy: at most every 5 s (2026-11-02). The cycle runs on every status +// write (several a second), and Windows Defender scans each rewrite of the file. +long _lastAggregateWriteMs = long.MinValue / 2; +const long AggregateEveryMs = 5_000; try { @@ -220,8 +224,9 @@ async Task RunCycleAsync() server?.UpdateLatest(bytes); server?.UpdateRaiseClients(clients); - if (cfg.WriteAggregateFile) + if (cfg.WriteAggregateFile && Environment.TickCount64 - _lastAggregateWriteMs >= AggregateEveryMs) { + _lastAggregateWriteMs = Environment.TickCount64; try { Directory.CreateDirectory(cfg.StatusDirectory); diff --git a/tools/ChatCommandReplyTests/Program.cs b/tools/ChatCommandReplyTests/Program.cs index 5319ea4..15b736d 100644 --- a/tools/ChatCommandReplyTests/Program.cs +++ b/tools/ChatCommandReplyTests/Program.cs @@ -105,6 +105,7 @@ internal static class Program ("sense", "sense compact", "sense frob on"), ("characters", "chars", "characters now"), ("itemcount", "itemhud", "itemcount now"), + ("itemtool", "itemtool", "itemtool now"), ("resetbar", "barreset", "resetbar now"), ("actionstate", "actions", "actionstate now"), ("unlockactions", "unlock", "unlockactions now"), diff --git a/tools/NetMessageTests/InventoryOrderTests.cs b/tools/NetMessageTests/InventoryOrderTests.cs index 981b90d..6cf9988 100644 --- a/tools/NetMessageTests/InventoryOrderTests.cs +++ b/tools/NetMessageTests/InventoryOrderTests.cs @@ -38,6 +38,21 @@ internal static unsafe partial class Program ? string.Join(",", ids.Select(i => (i & 0xFFFF).ToString("X"))) : "unknown"; + // The order file as engines before version 2 wrote it: no player id after the list count. + private static byte[] OldFormatFile((uint Container, bool Slot, uint[] Ids)[] lists) + { + var ms = new MemoryStream(); + var w = new BinaryWriter(ms); + w.Write(0x44524F49u); w.Write(1u); w.Write((uint)lists.Length); + foreach ((uint c, bool slot, uint[] ids) in lists) + { + w.Write(c); w.Write(slot ? (byte)1 : (byte)0); w.Write((uint)ids.Length); + foreach (uint id in ids) w.Write(id); + } + w.Flush(); + return ms.ToArray(); + } + private static byte[] MessageWithGuid(uint opcode, uint guid) { var b = new byte[8]; @@ -118,6 +133,49 @@ internal static unsafe partial class Program Check(!InventoryOrder.Restore(saved.AsSpan(0, saved.Length - 3)), "a truncated file is refused"); Eq(Order(Player, false) + "|" + Order(Player, true), before, "and a refused file changes nothing"); + Case("inventory order: after a restore the player's lists are still never dropped for room"); + Check(InventoryOrder.Restore(saved), "restored"); + Eq(InventoryOrder.Player, Player, "the file says whose lists they are"); + for (uint c = 0; c < 200; c++) + InventoryOrder.Observe(GameEvent(0x0196, 0x90000000 + c, 1, 0xA0000000 + c, 0)); + Eq(Order(Player, false) + "|" + Order(Player, true), before, "the main pack and the pack column survive 200 corpses"); + + Case("inventory order: a version 1 file (no player in it) still keeps the player's lists"); + byte[] v1 = OldFormatFile(new[] { (Player, false, new uint[] { 0x80000001 }), (Player, true, new uint[] { 0x80000004, 0x80000005 }), + (0x80000004u, false, new uint[] { 0x80000009 }), (0x80000004u, true, Array.Empty()) }); + Check(InventoryOrder.Restore(v1), "a version 1 file is accepted"); + Eq(InventoryOrder.Player, Player, "the player is the one container in the player id range with a pack column"); + for (uint c = 0; c < 200; c++) + InventoryOrder.Observe(GameEvent(0x0196, 0x90000000 + c, 1, 0xA0000000 + c, 0)); + Eq(Order(Player, true), "4,5", "its pack column survives 200 corpses"); + Eq(InventoryOrder.PlayerOf(new[] { (Player, true), (Player + 1, true) }), 0u, "two candidates: none guessed"); + Eq(InventoryOrder.PlayerOf(new[] { (0x80000004u, true) }), 0u, "an item id is never the player"); + + Case("inventory order: a saved file is this client's when written after it started, however old"); + var start = new DateTime(2026, 10, 30, 12, 0, 0, DateTimeKind.Utc); + Check(InventoryOrder.SavedFileIsOurs(start.AddDays(2), start), "written two days ago by this client: used"); + Check(InventoryOrder.SavedFileIsOurs(start.AddSeconds(-20), start), "clock rounding: used"); + Check(!InventoryOrder.SavedFileIsOurs(start.AddHours(-1), start), "written before this client started (a recycled pid): not used"); + Check(InventoryOrder.SavedFileIsOurs(start, null), "start time unknown: used"); + + Case("inventory order: a list's hash changes when the list does"); + InventoryOrder.Reset(); + Eq(InventoryOrder.ListHash(Player, true), 0u, "unknown: 0"); + InventoryOrder.Observe(PlayerDescriptionMsg(40, new uint[] { 0x80000001, 0x80000004, 0x80000005 }, new uint[] { 0, 1, 1 }, 0)); + uint h1 = InventoryOrder.ListHash(Player, true); + Check(h1 != 0, "known: not 0"); + InventoryOrder.Observe(GameEvent(0x0022, 0x80000005, Player, 0, 1)); + Eq(Order(Player, true), "5,4", "a pack moved to the top of the column"); + Check(InventoryOrder.ListHash(Player, true) != h1, "and the hash changed"); + + Case("inventory order: side packs sorted into the pack column's order"); + uint[] packs = { Player, 0x80000002, 0x80000003, 0x80000004 }; + Check(InventoryOrder.SortByColumn(packs, 1, x => x, new uint[] { 0x80000004, 0x80000F01, 0x80000002, 0x80000003 }), "a column naming every pack (a focus between)"); + Eq(string.Join(",", packs.Select(x => (x & 0xFFFF).ToString("X"))), "1,4,2,3", "main pack stays first, the top pack next"); + uint[] packs2 = { Player, 0x80000002, 0x80000003 }; + Check(!InventoryOrder.SortByColumn(packs2, 1, x => x, new uint[] { 0x80000003 }), "a pack the column lacks: refused"); + Eq(string.Join(",", packs2.Select(x => (x & 0xFFFF).ToString("X"))), "1,2,3", "and left in id order"); + Case("inventory order: junk never throws and never invents a list"); InventoryOrder.Reset(); var rng = new Random(5); diff --git a/tools/PluginManifestTests/PluginManifestTests.csproj b/tools/PluginManifestTests/PluginManifestTests.csproj index 496f29b..7a335aa 100644 --- a/tools/PluginManifestTests/PluginManifestTests.csproj +++ b/tools/PluginManifestTests/PluginManifestTests.csproj @@ -12,7 +12,9 @@ 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. + folders keeps the first and warns; + - the plugin file prefetch list (src\RynthCore.Engine\Plugins\PluginFilePrefetchList.cs, compiled in): + listed plugins first, then each plugin folder's DLLs and PDBs, then PluginShared's DLLs. 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) @@ -39,6 +41,7 @@ + diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index c5908cd..75d8a1c 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -65,6 +65,7 @@ internal static class Program Run(nameof(DedupeSameNameTwoFolders), DedupeSameNameTwoFolders); Run(nameof(DedupeAgainstAlreadyLoaded), DedupeAgainstAlreadyLoaded); Run(nameof(DedupeKeepsOrderAndText), DedupeKeepsOrderAndText); + Run(nameof(PrefetchListOrderAndScope), PrefetchListOrderAndScope); foreach (string dll in args) Run("Plugin " + Path.GetFileName(dll), () => CheckBuiltPlugin(dll)); } @@ -783,6 +784,35 @@ internal static class Program Eq(PluginPathDedupe.Dedupe(Array.Empty()).Load.Count, 0, "empty list"); } + // ── Prefetch file list (src\RynthCore.Engine\Plugins\PluginFilePrefetchList.cs) ── + + private static void PrefetchListOrderAndScope() + { + string suite = Path.Combine(_root, "prefetch"); + string ai = Path.Combine(suite, "RynthAi"), chat = Path.Combine(suite, "RynthChat"), shared = Path.Combine(suite, "PluginShared"); + foreach (string d in new[] { ai, chat, shared, Path.Combine(ai, "Sub") }) Directory.CreateDirectory(d); + void Touch(string path) => File.WriteAllText(path, "x"); + string aiDll = Path.Combine(ai, "RynthCore.Plugin.RynthAi.dll"), chatDll = Path.Combine(chat, "RynthCore.Plugin.RynthChat.dll"); + Touch(aiDll); Touch(Path.Combine(ai, "RynthCore.Plugin.RynthAi.pdb")); Touch(Path.Combine(ai, "ImGui.NET.dll")); + Touch(Path.Combine(ai, "settings.json")); Touch(Path.Combine(ai, "Sub", "Nested.dll")); + Touch(chatDll); Touch(Path.Combine(chat, "ImGui.NET.dll")); + Touch(Path.Combine(shared, "RynthCore.PluginSdk.dll")); Touch(Path.Combine(shared, "RynthCore.PluginSdk.pdb")); + + string[] listed = { chatDll, Path.Combine(suite, "Missing", "RynthCore.Plugin.Missing.dll"), Path.Combine(ai, "RYNTHCORE.PLUGIN.RYNTHAI.DLL"), "" }; + List files = PluginFilePrefetchList.Build(listed, shared); + string Rel(string f) => Path.GetRelativePath(suite, f).Replace('\\', '/'); + string got = string.Join("|", files.Select(Rel)); + Eq(Rel(files[0]), "RynthChat/RynthCore.Plugin.RynthChat.dll", "listed plugins first, in list order"); + Check(Rel(files[1]).Equals("RynthAi/RynthCore.Plugin.RynthAi.dll", StringComparison.OrdinalIgnoreCase), $"second listed plugin second: {got}"); + Eq(files.Count(f => f.EndsWith("RynthCore.Plugin.RynthAi.dll", StringComparison.OrdinalIgnoreCase)), 1, "a plugin listed in another case is opened once"); + Check(files.Any(f => Rel(f) == "RynthAi/RynthCore.Plugin.RynthAi.pdb") && files.Any(f => Rel(f) == "RynthAi/ImGui.NET.dll") + && files.Any(f => Rel(f) == "RynthChat/ImGui.NET.dll"), $"each plugin folder's DLLs and PDBs: {got}"); + Check(!files.Any(f => f.EndsWith(".json")) && !files.Any(f => f.Contains("Nested")), $"no other files, no subfolders: {got}"); + Check(!files.Any(f => f.Contains("Missing")), "a missing plugin adds nothing"); + Eq(Rel(files[^1]), "PluginShared/RynthCore.PluginSdk.dll", "the shared folder's DLLs last, without PDBs"); + Eq(PluginFilePrefetchList.Build(Array.Empty(), null).Count, 0, "nothing listed, nothing opened"); + } + private static string FindUp(string relative) { for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent) diff --git a/tools/VideoPatchTests/Program.cs b/tools/VideoPatchTests/Program.cs index edd2004..e6cab31 100644 --- a/tools/VideoPatchTests/Program.cs +++ b/tools/VideoPatchTests/Program.cs @@ -173,13 +173,20 @@ internal static class Program Check(hand.ModeFor("X/Z") == VideoPatchMode.Off, "a hand-written 'all' loads as off (a start never hides AC's UI)"); } + // 2026-11-02: Off chosen in Settings came back as "World when unfocused" on the next login: the + // character's line was removed and the Default line applied. A character's off is now kept. private static void OffRemovesTheLine() { Case("OffRemovesTheLine"); - var m = VideoPatchPolicy.Parse(null); + var m = VideoPatchPolicy.Parse(new[] { "Default=unfocused" }); 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"); + Check(VideoPatchPolicy.Serialize(m).Contains("X/Y=off"), "a character's off is a line of its own"); + var back = RoundTripModel(m); + Check(back.ModeFor("X/Y") == VideoPatchMode.Off, "and it wins over Default=unfocused after a reload"); + Check(back.ModeFor("X/Q") == VideoPatchMode.Unfocused, "a character without a line still gets Default"); + back.Set("Default", VideoPatchMode.Off); + Check(!VideoPatchPolicy.Serialize(back).Any(l => l.StartsWith("Default=")), "Default's off removes its line"); } private static void DefaultLineAndUnknownLines()