diff --git a/Changelog/2026-10-08-merge-rynth-main-into-pr2.md b/Changelog/2026-10-08-merge-rynth-main-into-pr2.md
new file mode 100644
index 0000000..8688851
--- /dev/null
+++ b/Changelog/2026-10-08-merge-rynth-main-into-pr2.md
@@ -0,0 +1,36 @@
+# 2026-10-08 - Merge rynth/main (2026.10.6.1 .. 2026.10.8.2) into sk/features-on-rynth-main
+
+Brings PR #2 up to date with rynth/main so it merges cleanly. No new features.
+
+## Where rynth/main already had the same feature, rynth/main's version wins
+
+- **Install paths.** `src/Shared/RynthInstallPaths.cs` (read-only, byte-identical with
+ RynthSuite's copy) replaces PR #2's `src/RynthCore.App/RynthInstallPaths.cs`. Every
+ project links the shared file.
+- **Installer plugin hand-off.** The launcher's one-shot `PendingPluginRegistration` read and
+ delete moved into `RynthCore.App.Avalonia/InstallerHandoff.cs`, so the shared resolver stays
+ read-only.
+- **Chat filters.** rynth/main's match modes (`ChatRuleMatching`) and standard filters
+ (`ChatFilterPresets`) replace PR #2's versions; `UI/Panels/RynthChatPresets.cs` is removed.
+ A `"presets"` block saved by PR #2 builds is ignored.
+- **Item info.** rynth/main's `/ra iteminfo` wins (RynthSuite drops PR #2's Mag-Tools item
+ info window). One `ItemInfoOnSelect` setting (rynth/main's, default on); PR #2's Item Info
+ section and its "Item Info Options" button are removed.
+- **engine.json saving.** rynth/main's `EngineSettingsFile.Merge` keeps the launcher's keys, so
+ PR #2's `CopyUnownedFields` is removed. `EnablePluginOverlayWindows` is added to
+ `EngineSettings.OwnedKeys`.
+- **LoggingLevel.** The launcher owns the key; `EngineSettings` no longer reads or writes it.
+ `LogSettings` reads it and keeps the current level when engine.json is half-written.
+
+## Kept from both sides
+
+- `EngineFrameController`: frames run for the video-patch banner (rynth/main) and for plugin
+ overlay windows (PR #2).
+- `InventoryFace`: closing ends a popped-out drag (`ItemDragBridge`, PR #2) and clears
+ `UiDropTargets.EngineDragObject` (rynth/main).
+
+## Checks
+
+- Release builds: Engine, App.Avalonia, Loader, Injector, StatusAgent.
+- All `tools/*Tests` pass (28 suites, including ChatFilterTests 800/800,
+ EngineSettingsTests 125, InstallPathsTests 56).
diff --git a/RynthCore.sln b/RynthCore.sln
index 971bb41..e450961 100644
--- a/RynthCore.sln
+++ b/RynthCore.sln
@@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Engine", "src\Ryn
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Injector", "src\RynthCore.Injector\RynthCore.Injector.csproj", "{A1B2C3D4-0002-0002-0002-000000000002}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.DesktopLog", "src\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj", "{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}"
+EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Loader", "src\RynthCore.Loader\RynthCore.Loader.csproj", "{A1B2C3D4-0006-0006-0006-000000000006}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
@@ -63,6 +65,18 @@ Global
{A1B2C3D4-0002-0002-0002-000000000002}.Release|Any CPU.Build.0 = Release|Any CPU
{A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.ActiveCfg = Release|Any CPU
{A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.Build.0 = Release|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.Build.0 = Debug|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.Build.0 = Debug|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.ActiveCfg = Release|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.Build.0 = Release|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.Build.0 = Release|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.ActiveCfg = Release|Any CPU
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.Build.0 = Release|Any CPU
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.ActiveCfg = Debug|x86
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.Build.0 = Debug|x86
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
@@ -179,6 +193,7 @@ Global
{2B283E05-12BB-45F9-B8E5-8F53C1FAB737} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{BB0C5CB5-6C75-4C17-9348-5CA0C481B65C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{A72E31D3-5D91-4C39-A30C-A96A492BBE82} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
+ {D1E2F3A4-5678-4ABC-8DEF-1234567890AB} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}
{C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}
diff --git a/src/RynthCore.App.Avalonia/App.axaml.cs b/src/RynthCore.App.Avalonia/App.axaml.cs
index 150a5b9..d0fa2db 100644
--- a/src/RynthCore.App.Avalonia/App.axaml.cs
+++ b/src/RynthCore.App.Avalonia/App.axaml.cs
@@ -1,6 +1,8 @@
+using System;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
+using RynthCore;
namespace RynthCore.App.Avalonia;
@@ -13,6 +15,18 @@ public partial class App : Application
public override void OnFrameworkInitializationCompleted()
{
+ try
+ {
+ string t = DateTime.Now.ToString("O");
+ DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher,
+ $"[{t}] [pid:{Environment.ProcessId}] RynthCore.App.Avalonia started (launcher).");
+ // Detailed host + sidecar file layout (see LauncherHostDiagnostics) for runtime mis-detection triage.
+ LauncherHostDiagnostics.AppendDesktopLogBlock(t);
+ }
+ catch
+ {
+ }
+
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
desktop.MainWindow = new MainWindow();
diff --git a/src/RynthCore.App.Avalonia/EngineJsonStore.cs b/src/RynthCore.App.Avalonia/EngineJsonStore.cs
index 69c07d2..2254a4e 100644
--- a/src/RynthCore.App.Avalonia/EngineJsonStore.cs
+++ b/src/RynthCore.App.Avalonia/EngineJsonStore.cs
@@ -120,4 +120,19 @@ internal static class EngineJsonStore
fields[field] = doc.RootElement.Clone();
Write(fields);
}
+
+ ///
+ /// Sets a single string field (e.g. "LoggingLevel"), preserving every other field.
+ ///
+ public static void SetString(string field, string value)
+ {
+ Dictionary fields = Read();
+
+ using var ms = new MemoryStream();
+ using (var w = new Utf8JsonWriter(ms))
+ w.WriteStringValue(value);
+ using var doc = JsonDocument.Parse(ms.ToArray());
+ fields[field] = doc.RootElement.Clone();
+ Write(fields);
+ }
}
diff --git a/src/RynthCore.App.Avalonia/InstallerHandoff.cs b/src/RynthCore.App.Avalonia/InstallerHandoff.cs
new file mode 100644
index 0000000..1bd9feb
--- /dev/null
+++ b/src/RynthCore.App.Avalonia/InstallerHandoff.cs
@@ -0,0 +1,67 @@
+// ============================================================================
+// RynthCore.App.Avalonia - InstallerHandoff.cs
+// One-shot values the installer leaves under Software\Rynth for the launcher
+// (today only PendingPluginRegistration). Kept apart from RynthInstallPaths,
+// which is shared with RynthSuite and must stay read-only.
+// ============================================================================
+
+using System;
+using System.Runtime.InteropServices;
+using RynthCore.Install;
+
+namespace RynthCore.App.Avalonia;
+
+internal static class InstallerHandoff
+{
+ ///
+ /// Reads a string value from Software\Rynth (HKCU first, then the HKLM 32-bit view,
+ /// where the 32-bit installer writes); null when absent or unreadable.
+ ///
+ public static string? Read(string valueName)
+ => ReadString(HKEY_CURRENT_USER, valueName, 0)
+ ?? ReadString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY);
+
+ /// Deletes a consumed value from HKCU Software\Rynth. Best effort.
+ public static void DeleteUserValue(string valueName)
+ {
+ try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RynthInstallPaths.RegistryKey, valueName); } catch { }
+ }
+
+ 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 uint MaxValueBytes = 64 * 1024;
+
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
+ private static extern int RegGetValueW(IntPtr hkey, string lpSubKey, string lpValue, uint dwFlags,
+ IntPtr pdwType, char[]? pvData, ref uint pcbData);
+
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
+ private static extern int RegDeleteKeyValueW(IntPtr hkey, string lpSubKey, string lpValueName);
+
+ private static string? ReadString(IntPtr root, string valueName, uint viewFlags)
+ {
+ try
+ {
+ uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlags;
+ uint bytes = 0;
+ if (RegGetValueW(root, RynthInstallPaths.RegistryKey, valueName, flags, IntPtr.Zero, null, ref bytes) != ERROR_SUCCESS
+ || bytes < 2 || bytes > MaxValueBytes)
+ return null;
+
+ var buffer = new char[(bytes + 1) / 2];
+ if (RegGetValueW(root, RynthInstallPaths.RegistryKey, valueName, flags, IntPtr.Zero, buffer, ref bytes) != ERROR_SUCCESS)
+ return null;
+
+ int len = Array.IndexOf(buffer, '\0');
+ return new string(buffer, 0, len >= 0 ? len : buffer.Length);
+ }
+ catch
+ {
+ return null; // missing entry point or access denied: no hand-off
+ }
+ }
+}
diff --git a/src/RynthCore.App.Avalonia/LauncherDiag.cs b/src/RynthCore.App.Avalonia/LauncherDiag.cs
index 22c3070..4056c79 100644
--- a/src/RynthCore.App.Avalonia/LauncherDiag.cs
+++ b/src/RynthCore.App.Avalonia/LauncherDiag.cs
@@ -2,6 +2,7 @@ using System;
using System.IO;
using System.Text;
using System.Threading;
+using RynthCore.Install;
namespace RynthCore.App.Avalonia;
diff --git a/src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs b/src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs
new file mode 100644
index 0000000..4b1eed3
--- /dev/null
+++ b/src/RynthCore.App.Avalonia/LauncherHostDiagnostics.cs
@@ -0,0 +1,110 @@
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Text;
+using RynthCore;
+
+namespace RynthCore.App.Avalonia;
+
+///
+/// One-shot host metadata for the Avalonia launcher: helps confirm the renamed apphost
+/// (RynthCore.exe) sits next to matching .runtimeconfig.json / .deps.json after installer staging.
+///
+internal static class LauncherHostDiagnostics
+{
+ /// Single line for the in-window activity feed (short).
+ internal static string BuildActivitySummaryLine()
+ {
+ string exe = TryGetHostExePath();
+ string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory;
+ HostSidecars side = DescribeSidecars(dir);
+ // x64 FDD tool prereq: same registry keys as installer/RynthCore.iss (see NetDesktopX64Prerequisite).
+ string suiteTools = NetDesktopX64Prerequisite.IsSatisfied()
+ ? "x64 suite tools: .NET 10+ OK (registry, same as setup)"
+ : "x64 suite tools: .NET 10+ not found — install x64 runtime from " + NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl;
+ if (!Environment.Is64BitOperatingSystem)
+ suiteTools = "x64 suite tools: n/a on 32-bit OS (same as setup)";
+
+ return
+ $"Host: {RuntimeInformation.FrameworkDescription}, arch={RuntimeInformation.ProcessArchitecture}, " +
+ $"runtimeconfig={(side.RenamedRuntimeConfig ? "RynthCore" : side.LegacyRuntimeConfig ? "App.Avalonia (mismatch?)" : "missing")}, " +
+ $"deps={(side.RenamedDeps ? "RynthCore" : side.LegacyDeps ? "App.Avalonia (mismatch?)" : "missing")}; {suiteTools}";
+ }
+
+ /// Writes a detailed block to the desktop rolling launcher log.
+ internal static void AppendDesktopLogBlock(string timestampIso)
+ {
+ try
+ {
+ string exe = TryGetHostExePath();
+ string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory;
+ HostSidecars side = DescribeSidecars(dir);
+
+ var sb = new StringBuilder(512);
+ sb.Append('[').Append(timestampIso).Append("] [pid:").Append(Environment.ProcessId).AppendLine("] Launcher host resolution:");
+ sb.Append(" ProcessPath: ").AppendLine(exe);
+ sb.Append(" BaseDirectory: ").AppendLine(AppContext.BaseDirectory);
+ sb.Append(" Framework: ").AppendLine(RuntimeInformation.FrameworkDescription);
+ sb.Append(" OSDescription: ").AppendLine(RuntimeInformation.OSDescription);
+ sb.Append(" ProcessArchitecture: ").AppendLine(RuntimeInformation.ProcessArchitecture.ToString());
+ sb.Append(" CLR: ").AppendLine(Environment.Version.ToString());
+ sb.Append(" RynthCore.runtimeconfig.json: ").AppendLine(side.RenamedRuntimeConfig ? "present" : "absent");
+ sb.Append(" RynthCore.App.Avalonia.runtimeconfig.json: ").AppendLine(side.LegacyRuntimeConfig ? "present (unexpected if exe is RynthCore.exe)" : "absent");
+ sb.Append(" RynthCore.deps.json: ").AppendLine(side.RenamedDeps ? "present" : "absent");
+ sb.Append(" RynthCore.App.Avalonia.deps.json: ").AppendLine(side.LegacyDeps ? "present (unexpected if exe is RynthCore.exe)" : "absent");
+ // Loot/Monster editors are x64 FDD: probe matches RynthCore.iss prerequisite page (64-bit registry view).
+ sb.Append(" x64 FDD tool runtime (Loot/Monster, same checks as installer): ")
+ .AppendLine(NetDesktopX64Prerequisite.IsSatisfied() ? "present" : "not detected")
+ .Append(" .NET 10+ x64 download hub: ")
+ .AppendLine(NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl);
+
+ DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher, sb.ToString());
+ }
+ catch
+ {
+ // Logging must never prevent startup.
+ }
+ }
+
+ private static string TryGetHostExePath()
+ {
+ try
+ {
+ // Prefer the actual apphost path (works for published rename to RynthCore.exe).
+ string? p = Environment.ProcessPath;
+ if (!string.IsNullOrWhiteSpace(p))
+ return p;
+ }
+ catch
+ {
+ // ignore
+ }
+
+ try
+ {
+ return typeof(App).Assembly.Location;
+ }
+ catch
+ {
+ return string.Empty;
+ }
+ }
+
+ private static HostSidecars DescribeSidecars(string directory)
+ {
+ if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory))
+ return new HostSidecars(false, false, false, false);
+
+ bool renamedRc = File.Exists(Path.Combine(directory, "RynthCore.runtimeconfig.json"));
+ bool legacyRc = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.runtimeconfig.json"));
+ bool renamedDeps = File.Exists(Path.Combine(directory, "RynthCore.deps.json"));
+ bool legacyDeps = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.deps.json"));
+ return new HostSidecars(renamedRc, legacyRc, renamedDeps, legacyDeps);
+ }
+
+ private readonly record struct HostSidecars(
+ bool RenamedRuntimeConfig,
+ bool LegacyRuntimeConfig,
+ bool RenamedDeps,
+ bool LegacyDeps);
+}
diff --git a/src/RynthCore.App.Avalonia/LoggingSettingsStore.cs b/src/RynthCore.App.Avalonia/LoggingSettingsStore.cs
new file mode 100644
index 0000000..eb3b801
--- /dev/null
+++ b/src/RynthCore.App.Avalonia/LoggingSettingsStore.cs
@@ -0,0 +1,192 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using RynthCore.Install;
+
+namespace RynthCore.App.Avalonia;
+
+///
+/// Launcher-side access to every live logging switch:
+///
+/// - Engine: engine.json "LoggingLevel" (global threshold) and "LogCategories" (per-category emit
+/// level). The engine polls engine.json once a second, so edits apply to running clients.
+/// - RynthAi: Logs\Diagnostics\diagnostics.json "Categories" and "Events" (Off / Trace / Info).
+/// RynthAi polls it every couple of seconds and rewrites it with the full catalog on load.
+///
+///
+internal static class LoggingSettingsStore
+{
+ /// One engine log category as shown in the launcher.
+ internal readonly record struct EngineCategory(string Name, string DefaultLevel, string Description);
+
+ /// One RynthAi category / event row read from diagnostics.json.
+ internal sealed record DiagnosticsRow(string Key, string Level, string Description);
+
+ /// Global level choices (engine.json "LoggingLevel"), most to least quiet.
+ internal static readonly string[] GlobalLevels = { "Off", "Error", "Warning", "Info", "Debug", "Trace" };
+
+ /// Engine category emit levels. Info = normal log; Debug/Trace show only at that global level.
+ internal static readonly string[] EngineCategoryLevels = { "Off", "Trace", "Debug", "Info" };
+
+ /// RynthAi category / event levels: Off, Trace (trace file only), Info (also the normal log).
+ internal static readonly string[] RynthAiLevels = { "Off", "Trace", "Info" };
+
+ /// Must match RynthCore.Engine.LogCategory names and LogSettings defaults.
+ internal static readonly EngineCategory[] EngineCategories =
+ {
+ new("General", "Info", "Uncategorised engine lines."),
+ new("D3D9", "Info", "D3D9 hook, EndScene, bootstrapper, matrix capture, nav markers."),
+ new("Compat", "Info", "Client hooks: objects, combat, movement, vitals, chat."),
+ new("Render", "Off", "ImGui rendering and Win32 input (very chatty)."),
+ new("Plugin", "Info", "Plugin loader/manager and every plugin host Log line."),
+ new("UI", "Info", "Avalonia overlay and panels."),
+ new("Verbose", "Debug", "Detail lines across all subsystems (Info = always in the normal log)."),
+ };
+
+ private const string EngineCategoriesProperty = "LogCategories";
+
+ /// RynthAi's diagnostics.json (created by RynthAi on its first load).
+ internal static string DiagnosticsPath =>
+ Path.Combine(RynthInstallPaths.RynthAiDir, "Logs", "Diagnostics", "diagnostics.json");
+
+ // ── Engine ──────────────────────────────────────────────────────────
+
+ /// Current engine category levels; categories missing from engine.json get their defaults.
+ internal static Dictionary ReadEngineCategoryLevels()
+ {
+ var result = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (EngineCategory c in EngineCategories) result[c.Name] = c.DefaultLevel;
+
+ Dictionary fields = EngineJsonStore.Read();
+ if (fields.TryGetValue(EngineCategoriesProperty, out JsonElement cats) && cats.ValueKind == JsonValueKind.Object)
+ {
+ foreach (JsonProperty p in cats.EnumerateObject())
+ {
+ if (p.Value.ValueKind == JsonValueKind.String && result.ContainsKey(p.Name))
+ result[p.Name] = p.Value.GetString() ?? result[p.Name];
+ }
+ }
+ return result;
+ }
+
+ /// Sets one engine category level in engine.json, preserving every other field.
+ internal static void SetEngineCategoryLevel(string category, string level)
+ {
+ Dictionary levels = ReadEngineCategoryLevels();
+ levels[category] = level;
+
+ using var ms = new MemoryStream();
+ using (var w = new Utf8JsonWriter(ms))
+ {
+ w.WriteStartObject();
+ foreach (EngineCategory c in EngineCategories)
+ w.WriteString(c.Name, levels[c.Name]);
+ w.WriteEndObject();
+ }
+
+ Dictionary fields = EngineJsonStore.Read();
+ using var doc = JsonDocument.Parse(ms.ToArray());
+ fields[EngineCategoriesProperty] = doc.RootElement.Clone();
+ EngineJsonStore.Write(fields);
+ }
+
+ // ── RynthAi ─────────────────────────────────────────────────────────
+
+ ///
+ /// Reads RynthAi's category and event rows. Returns false (with empty lists) when diagnostics.json
+ /// does not exist yet or cannot be parsed (e.g. RynthAi is mid-write; retry later).
+ ///
+ internal static bool TryReadRynthAi(out List categories, out List events, out string? error)
+ {
+ categories = new List();
+ events = new List();
+ error = null;
+ try
+ {
+ if (!File.Exists(DiagnosticsPath))
+ {
+ error = "diagnostics.json not found - start RynthAi once to create it.";
+ return false;
+ }
+ if (JsonNode.Parse(File.ReadAllText(DiagnosticsPath)) is not JsonObject root)
+ {
+ error = "diagnostics.json is not a JSON object.";
+ return false;
+ }
+ ReadRows(root["Categories"] as JsonArray, "Name", categories);
+ ReadRows(root["Events"] as JsonArray, "Key", events);
+ if (categories.Count == 0)
+ error = "diagnostics.json has no category list - update RynthAi to 0.6.18 or later.";
+ return true;
+ }
+ catch (Exception ex)
+ {
+ error = $"diagnostics.json unreadable ({ex.GetType().Name}: {ex.Message}).";
+ return false;
+ }
+ }
+
+ /// Sets a RynthAi category level ("Off", "Trace", "Info") and keeps "Traces" in sync.
+ internal static void SetRynthAiCategoryLevel(string category, string level)
+ => UpdateDiagnostics("Categories", "Name", category, level);
+
+ /// Sets a RynthAi key-event level ("Off", "Trace", "Info").
+ internal static void SetRynthAiEventLevel(string eventKey, string level)
+ => UpdateDiagnostics("Events", "Key", eventKey, level);
+
+ private static void ReadRows(JsonArray? array, string keyField, List into)
+ {
+ if (array == null) return;
+ foreach (JsonNode? node in array)
+ {
+ if (node is not JsonObject o) continue;
+ string key = o[keyField]?.GetValue() ?? string.Empty;
+ if (key.Length == 0) continue;
+ into.Add(new DiagnosticsRow(
+ key,
+ o["Level"]?.GetValue() ?? "Off",
+ o["Description"]?.GetValue() ?? string.Empty));
+ }
+ }
+
+ /// Read-modify-write of one row's Level; every other field in the file is preserved.
+ private static void UpdateDiagnostics(string section, string keyField, string key, string level)
+ {
+ string path = DiagnosticsPath;
+ if (JsonNode.Parse(File.ReadAllText(path)) is not JsonObject root)
+ throw new InvalidDataException("diagnostics.json is not a JSON object.");
+ if (root[section] is not JsonArray rows)
+ throw new InvalidDataException($"diagnostics.json has no \"{section}\" list.");
+
+ bool found = false;
+ foreach (JsonNode? node in rows)
+ {
+ if (node is JsonObject o && string.Equals(o[keyField]?.GetValue(), key, StringComparison.OrdinalIgnoreCase))
+ {
+ o["Level"] = level;
+ found = true;
+ }
+ }
+ if (!found)
+ throw new KeyNotFoundException($"\"{key}\" is not in diagnostics.json {section}.");
+
+ // RynthAi reads Categories when present, but older readers (and /ra trace status) use Traces.
+ if (section == "Categories")
+ {
+ var traces = new JsonArray();
+ foreach (JsonNode? node in rows)
+ {
+ if (node is JsonObject o && !string.Equals(o["Level"]?.GetValue(), "Off", StringComparison.OrdinalIgnoreCase))
+ traces.Add(o["Name"]?.GetValue());
+ }
+ root["Traces"] = traces;
+ }
+
+ // Atomic swap so RynthAi's poll never reads a half-written file.
+ string tmp = path + ".tmp";
+ File.WriteAllText(tmp, root.ToJsonString(new JsonSerializerOptions { WriteIndented = false }));
+ File.Move(tmp, path, overwrite: true);
+ }
+}
diff --git a/src/RynthCore.App.Avalonia/MainWindow.Logging.cs b/src/RynthCore.App.Avalonia/MainWindow.Logging.cs
new file mode 100644
index 0000000..90abc2c
--- /dev/null
+++ b/src/RynthCore.App.Avalonia/MainWindow.Logging.cs
@@ -0,0 +1,153 @@
+using System;
+using System.Collections.Generic;
+using Avalonia.Controls;
+using Avalonia.Layout;
+using Avalonia.Media;
+
+namespace RynthCore.App.Avalonia;
+
+///
+/// Runtime tab → Logging card and the live global Logging level box. Every change is written
+/// straight to engine.json / diagnostics.json (see ); running
+/// clients poll those files, so nothing needs a restart or the Save button.
+///
+internal partial class MainWindow
+{
+ private static readonly IBrush LogNameBrush = new SolidColorBrush(Color.Parse("#EAF0F4"));
+ private static readonly IBrush LogMutedBrush = new SolidColorBrush(Color.Parse("#9AA8B3"));
+
+ // Set while the rows are being (re)built so programmatic selections don't write files.
+ private bool _suppressLoggingEvents;
+
+ /// Wires the Logging card and the live global level box. Called once after LoadRuntimeControls.
+ private void InitLoggingControls()
+ {
+ LoggingLevelComboBox.SelectionChanged += (_, _) => OnGlobalLoggingLevelChanged();
+ ReloadLoggingButton.Click += (_, _) => BuildLoggingRows();
+ BuildLoggingRows();
+ }
+
+ /// Global level changed: persist to the launcher settings and push to engine.json now.
+ private void OnGlobalLoggingLevelChanged()
+ {
+ if (_suppressLoggingEvents) return;
+ string level = GetSelectedLoggingLevel();
+ if (string.Equals(level, _settings.LoggingLevel, StringComparison.OrdinalIgnoreCase)) return;
+ try
+ {
+ _settings.LoggingLevel = level;
+ SaveSettings();
+ EngineJsonStore.SetString("LoggingLevel", level);
+ AppendActivity($"Logging level set to {level} (applied live to running clients).");
+ }
+ catch (Exception ex)
+ {
+ AppendActivity($"Failed to save logging level: {ex.Message}");
+ }
+ }
+
+ /// (Re)builds the engine category, RynthAi category and RynthAi event rows from disk.
+ private void BuildLoggingRows()
+ {
+ _suppressLoggingEvents = true;
+ try
+ {
+ EngineLogCategoriesPanel.Children.Clear();
+ Dictionary engineLevels = LoggingSettingsStore.ReadEngineCategoryLevels();
+ foreach (LoggingSettingsStore.EngineCategory cat in LoggingSettingsStore.EngineCategories)
+ {
+ string name = cat.Name;
+ EngineLogCategoriesPanel.Children.Add(BuildLoggingRow(
+ name, cat.Description, LoggingSettingsStore.EngineCategoryLevels, engineLevels[name],
+ level =>
+ {
+ LoggingSettingsStore.SetEngineCategoryLevel(name, level);
+ AppendActivity($"Engine log category {name} set to {level} (applied live).");
+ }));
+ }
+
+ RynthAiLogCategoriesPanel.Children.Clear();
+ RynthAiLogEventsPanel.Children.Clear();
+ bool ok = LoggingSettingsStore.TryReadRynthAi(
+ out List categories,
+ out List events,
+ out string? error);
+
+ foreach (LoggingSettingsStore.DiagnosticsRow row in categories)
+ {
+ string key = row.Key;
+ RynthAiLogCategoriesPanel.Children.Add(BuildLoggingRow(
+ key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level,
+ level =>
+ {
+ LoggingSettingsStore.SetRynthAiCategoryLevel(key, level);
+ AppendActivity($"RynthAi log category {key} set to {level} (applied live).");
+ }));
+ }
+ foreach (LoggingSettingsStore.DiagnosticsRow row in events)
+ {
+ string key = row.Key;
+ RynthAiLogEventsPanel.Children.Add(BuildLoggingRow(
+ key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level,
+ level =>
+ {
+ LoggingSettingsStore.SetRynthAiEventLevel(key, level);
+ AppendActivity($"RynthAi log event {key} set to {level} (applied live).");
+ }));
+ }
+
+ LoggingStatusText.Text = ok && error == null
+ ? $"engine.json: {EngineJsonStore.Path}\ndiagnostics.json: {LoggingSettingsStore.DiagnosticsPath}"
+ : $"RynthAi: {error}";
+ }
+ catch (Exception ex)
+ {
+ LoggingStatusText.Text = $"Failed to load logging settings: {ex.Message}";
+ }
+ finally
+ {
+ _suppressLoggingEvents = false;
+ }
+ }
+
+ /// One "Name | level box | description" row. runs on user changes only.
+ private Control BuildLoggingRow(string name, string description, string[] levels, string current, Action apply)
+ {
+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("170,110,*") };
+
+ grid.Children.Add(new TextBlock
+ {
+ Text = name,
+ Foreground = LogNameBrush,
+ VerticalAlignment = VerticalAlignment.Center,
+ });
+
+ var combo = new ComboBox { ItemsSource = levels, MinWidth = 100, Margin = new global::Avalonia.Thickness(0, 0, 8, 0) };
+ int index = Array.FindIndex(levels, l => string.Equals(l, current, StringComparison.OrdinalIgnoreCase));
+ combo.SelectedIndex = index >= 0 ? index : 0;
+ combo.SelectionChanged += (_, _) =>
+ {
+ if (_suppressLoggingEvents || combo.SelectedItem is not string level) return;
+ try { apply(level); }
+ catch (Exception ex)
+ {
+ AppendActivity($"Failed to set {name} to {level}: {ex.Message}");
+ // Show what is actually on disk; posted so the combo raising this event isn't torn down mid-handler.
+ global::Avalonia.Threading.Dispatcher.UIThread.Post(BuildLoggingRows);
+ }
+ };
+ Grid.SetColumn(combo, 1);
+ grid.Children.Add(combo);
+
+ var desc = new TextBlock
+ {
+ Text = description,
+ Foreground = LogMutedBrush,
+ TextWrapping = TextWrapping.Wrap,
+ VerticalAlignment = VerticalAlignment.Center,
+ };
+ Grid.SetColumn(desc, 2);
+ grid.Children.Add(desc);
+ return grid;
+ }
+}
diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml b/src/RynthCore.App.Avalonia/MainWindow.axaml
index 4176226..31ba128 100644
--- a/src/RynthCore.App.Avalonia/MainWindow.axaml
+++ b/src/RynthCore.App.Avalonia/MainWindow.axaml
@@ -366,7 +366,17 @@
-
+
+
+
+
+
+
+
+
+
+
@@ -409,6 +419,42 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -423,7 +469,7 @@
-
diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs
index 0a0c414..1f3c9ef 100644
--- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs
+++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs
@@ -18,6 +18,7 @@ using Avalonia.Media;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using RynthCore.Injector;
+using RynthCore.Install;
namespace RynthCore.App.Avalonia;
@@ -136,6 +137,8 @@ internal partial class MainWindow : Window
SessionList.ItemsSource = _sessionItems;
LoadSettings();
LoadRuntimeControls();
+ InitLoggingControls();
+ ApplyInstallerPluginRegistration();
LoadPluginDllPaths();
BuildPluginLoadout();
WireEvents();
@@ -149,6 +152,8 @@ internal partial class MainWindow : Window
Closing += (_, _) => SaveWindowLayout();
ShowVersion();
AppendActivity("Avalonia launcher preview ready.");
+ // One-line host/runtime sidecar check (full detail in Desktop RynthCore-Launcher.log).
+ AppendActivity(LauncherHostDiagnostics.BuildActivitySummaryLine());
_ = RefreshServerStatusesAsync();
_updateTimer.Tick += async (_, _) => await CheckForUpdatesAsync();
_updateTimer.Start();
@@ -307,6 +312,8 @@ internal partial class MainWindow : Window
AutoLaunchHeaderCheckBox.IsChecked = _settings.AutoLaunch;
AutoInjectAfterLaunchCheckBox.IsChecked = _settings.AutoInjectAfterLaunch;
WatchForAcStartCheckBox.IsChecked = _settings.WatchForAcStart;
+ InjectAllRunningAcCheckBox.IsChecked = _settings.InjectAllRunningClients;
+ SetLoggingLevelSelection(_settings.LoggingLevel);
OverrideWindowTitleCheckBox.IsChecked = _settings.OverrideWindowTitle;
LaunchStaggerMsBox.Value = _settings.LaunchStaggerMs;
CrashRelaunchLimitBox.Value = _settings.CrashRelaunchLimitInWindow;
@@ -1309,6 +1316,8 @@ internal partial class MainWindow : Window
_settings.AutoLaunch = AutoLaunchHeaderCheckBox.IsChecked == true;
_settings.AutoInjectAfterLaunch = AutoInjectAfterLaunchCheckBox.IsChecked == true;
_settings.WatchForAcStart = WatchForAcStartCheckBox.IsChecked == true;
+ _settings.InjectAllRunningClients = InjectAllRunningAcCheckBox.IsChecked == true;
+ _settings.LoggingLevel = GetSelectedLoggingLevel();
_settings.OverrideWindowTitle = OverrideWindowTitleCheckBox.IsChecked == true;
if (LaunchStaggerMsBox.Value is decimal staggerMs)
_settings.LaunchStaggerMs = (int)staggerMs;
@@ -1323,8 +1332,12 @@ internal partial class MainWindow : Window
if (_settings.EnabledPluginIds.Count == 0)
_settings.EnabledPluginIds.Add("rynthcore-engine");
SaveSettings();
+ SyncPluginPathsToEngineSettings();
if (appendActivity)
+ {
+ AppendActivity($"Logging level saved: {_settings.LoggingLevel}.");
AppendActivity("Launch behavior saved.");
+ }
}
private void SaveAutoLaunchPreference()
@@ -1981,6 +1994,78 @@ internal partial class MainWindow : Window
AppendActivity($"Runtime loadout updated: {Path.GetFileName(dllPath)} {(enabled ? "enabled" : "disabled")} (engine.json synced).");
}
+ ///
+ /// Applies the installer's one-shot plugin hand-off: the full installer writes the plugin
+ /// DLL paths it placed in the user-chosen RynthSuite folder to
+ /// Software\Rynth\PendingPluginRegistration (';'-separated). Each existing DLL is added
+ /// to the Plugins list, and any entry with the same file name that no longer exists (e.g. the
+ /// old C:\Games\RynthSuite\... path after moving the Suite folder) is replaced.
+ /// Rows pointing inside the RynthCore folder whose file the installer removed are dropped too.
+ /// The value is consumed once (deleted from HKCU; remembered in settings for HKLM).
+ ///
+ private void ApplyInstallerPluginRegistration()
+ {
+ try
+ {
+ string? pending = InstallerHandoff.Read("PendingPluginRegistration");
+ if (string.IsNullOrWhiteSpace(pending)
+ || string.Equals(pending, _settings.AppliedInstallerPluginRegistration, StringComparison.OrdinalIgnoreCase))
+ return;
+
+ _settings.PluginDllPaths ??= [];
+ var added = new List();
+
+ // The installer clears loose DLLs out of the RynthCore folder (old 0.4.x layouts kept plugins
+ // and SDK DLLs there), so drop rows that pointed inside it and are now gone. Rows elsewhere are
+ // left alone, since a missing file there may just be on a drive that isn't mounted.
+ string coreRoot = Path.TrimEndingDirectorySeparator(RynthInstallPaths.CoreDir) + Path.DirectorySeparatorChar;
+ bool IsRemovedCoreFile(string p) =>
+ p.StartsWith(coreRoot, StringComparison.OrdinalIgnoreCase) && !File.Exists(p);
+ int pruned = _settings.PluginDllPaths.RemoveAll(IsRemovedCoreFile);
+ _settings.DisabledPluginDllPaths.RemoveAll(IsRemovedCoreFile);
+
+ foreach (string raw in pending.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ string path;
+ try { path = Path.GetFullPath(raw); } catch { continue; }
+ if (!File.Exists(path)) continue;
+
+ string fileName = Path.GetFileName(path);
+ // Drop stale rows for the same plugin that point at a file which is gone.
+ _settings.PluginDllPaths.RemoveAll(p =>
+ string.Equals(Path.GetFileName(p), fileName, StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(p, path, StringComparison.OrdinalIgnoreCase)
+ && !File.Exists(p));
+
+ if (!_settings.PluginDllPaths.Any(p => string.Equals(p, path, StringComparison.OrdinalIgnoreCase)))
+ {
+ _settings.PluginDllPaths.Add(path);
+ added.Add(fileName);
+ }
+ }
+
+ _settings.AppliedInstallerPluginRegistration = pending;
+ SaveSettings();
+ InstallerHandoff.DeleteUserValue("PendingPluginRegistration");
+
+ _pluginDllPaths.Clear();
+ foreach (string p in _settings.PluginDllPaths) _pluginDllPaths.Add(p);
+ SyncPluginPathsToEngineSettings();
+
+ string msg = added.Count > 0
+ ? $"Installer registered plugin(s): {string.Join(", ", added)} (engine.json synced)."
+ : "Installer plugin registration already up to date.";
+ if (pruned > 0)
+ msg += $" Removed {pruned} plugin path(s) for files the installer cleared from {RynthInstallPaths.CoreDir}.";
+ LauncherDiag.Info("PLUGINS: " + msg);
+ try { AppendActivity(msg); } catch { }
+ }
+ catch (Exception ex)
+ {
+ LauncherDiag.Info("PLUGINS: installer registration failed: " + ex.Message);
+ }
+ }
+
private void LoadPluginDllPaths()
{
_pluginDllPaths.Clear();
@@ -2069,6 +2154,8 @@ internal partial class MainWindow : Window
.Where(p => !disabled.Contains(p))
.ToList();
EngineJsonStore.SetStringArray("PluginPaths", enabledPaths);
+ // The engine reads its log verbosity from engine.json on init and on change (LogSettings).
+ EngineJsonStore.SetString("LoggingLevel", GetSelectedLoggingLevel());
}
catch (Exception ex)
{
@@ -2564,18 +2651,28 @@ internal partial class MainWindow : Window
try
{
SetOperationState(true);
- Process target = targets.OrderBy(process => process.Id).First();
- AppendActivity($"Applying selected loadout to running AC (PID {target.Id}).");
+ IReadOnlyList orderedTargets = targets.OrderBy(process => process.Id).ToList();
+ bool injectAllSessions = InjectAllRunningAcCheckBox.IsChecked == true;
+ IReadOnlyList targetsToInject = injectAllSessions
+ ? orderedTargets
+ : [orderedTargets[0]];
+ AppendActivity(injectAllSessions
+ ? $"Applying selected loadout to {targetsToInject.Count} running AC session(s)."
+ : $"Applying selected loadout to first running AC session (PID {targetsToInject[0].Id}).");
- InjectionResult result = await Task.Run(() => _injector.InjectIntoProcess(target, enginePath, AppendActivity));
- if (result.Success)
+ foreach (Process target in targetsToInject)
{
- _launchedSessionPids.Add(target.Id);
- AppendActivity($"Injection complete for PID {target.Id}.");
- }
- else
- {
- AppendActivity($"Injection failed: {result.Summary}");
+ AppendActivity($"Injecting running AC (PID {target.Id}).");
+ InjectionResult result = await Task.Run(() => _injector.InjectIntoProcess(target, enginePath, AppendActivity));
+ if (result.Success)
+ {
+ _launchedSessionPids.Add(target.Id);
+ AppendActivity($"Injection complete for PID {target.Id}.");
+ }
+ else
+ {
+ AppendActivity($"Injection failed for PID {target.Id}: {result.Summary}");
+ }
}
}
catch (Exception ex)
@@ -2589,6 +2686,39 @@ internal partial class MainWindow : Window
}
}
+ private string GetSelectedLoggingLevel()
+ {
+ return LoggingLevelComboBox.SelectedItem is ComboBoxItem item
+ ? item.Content?.ToString() ?? "Info"
+ : "Info";
+ }
+
+ private void SetLoggingLevelSelection(string? loggingLevel)
+ {
+ string desiredLevel = string.IsNullOrWhiteSpace(loggingLevel) ? "Info" : loggingLevel.Trim();
+ if (LoggingLevelComboBox.Items == null)
+ {
+ LoggingLevelComboBox.SelectedIndex = 0;
+ return;
+ }
+
+ foreach (object? item in LoggingLevelComboBox.Items)
+ {
+ if (item is not ComboBoxItem comboItem)
+ continue;
+
+ string candidate = comboItem.Content?.ToString() ?? string.Empty;
+ if (!string.Equals(candidate, desiredLevel, StringComparison.OrdinalIgnoreCase))
+ continue;
+
+ LoggingLevelComboBox.SelectedItem = comboItem;
+ return;
+ }
+
+ // Unknown saved value: fall back to Info (index 3 after Off, Error, Warning), not the quietest level.
+ LoggingLevelComboBox.SelectedIndex = 3;
+ }
+
private void OnPrimarySelectionChanged()
{
if (_suppressPrimarySelectionChanged)
diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj
index 5b4479a..6ff3d50 100644
--- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj
+++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj
@@ -1,6 +1,12 @@
+
+ 0.1.5
+ 0.1.5.0
+ 0.1.5.0
WinExe
net10.0-windows7.0
x86
@@ -11,6 +17,8 @@
RynthCore.App.Avalonia
RynthCore.App.Avalonia
win-x86
+
LogoCore.ico
true
@@ -25,6 +33,12 @@
+
+
+
+
+
+
diff --git a/src/RynthCore.App/AppSettings.cs b/src/RynthCore.App/AppSettings.cs
index fec333f..0da12e9 100644
--- a/src/RynthCore.App/AppSettings.cs
+++ b/src/RynthCore.App/AppSettings.cs
@@ -17,6 +17,8 @@ internal sealed class AppSettings
public bool AutoLaunch { get; set; }
public bool AutoInjectAfterLaunch { get; set; } = true;
public bool WatchForAcStart { get; set; } = true;
+ public bool InjectAllRunningClients { get; set; } = true;
+ public string LoggingLevel { get; set; } = "Info";
public int LaunchStaggerMs { get; set; } = 250;
public int CrashRelaunchLimitInWindow { get; set; } = 3;
public int CrashRelaunchWindowMinutes { get; set; } = 5;
@@ -62,6 +64,14 @@ internal sealed class AppSettings
/// the UI), but is filtered out when syncing PluginPaths into engine.json.
/// Case-insensitive set semantics; comparisons must use OrdinalIgnoreCase.
public List DisabledPluginDllPaths { get; set; } = [];
+
+ ///
+ /// Last installer plugin hand-off (registry Software\Rynth\PendingPluginRegistration)
+ /// the launcher applied. Lets an all-users install, whose HKLM value the launcher cannot
+ /// delete, register its plugins once without re-adding a plugin the user later removed.
+ ///
+ public string? AppliedInstallerPluginRegistration { get; set; }
+
public List ServerProfiles { get; set; } = [];
public List AccountProfiles { get; set; } = [];
diff --git a/src/RynthCore.DesktopLog/DesktopRollingLog.cs b/src/RynthCore.DesktopLog/DesktopRollingLog.cs
new file mode 100644
index 0000000..ea43e85
--- /dev/null
+++ b/src/RynthCore.DesktopLog/DesktopRollingLog.cs
@@ -0,0 +1,130 @@
+using System.Globalization;
+using System.Text;
+
+namespace RynthCore;
+
+///
+/// Desktop text logs with a fixed size cap and per-day roll retention. Active file lives on the user
+/// desktop as {fileStem}.log. When the active file reaches ,
+/// it is moved into Desktop\RynthLogs\ with a time-stamped name, then a new active file is
+/// created. For each and each calendar day, at most
+/// archived files are kept (oldest for that day deleted first).
+///
+public static class DesktopRollingLog
+{
+ // 10 MB active segment, up to 10 rolled segments per local calendar day.
+ public const long MaxActiveFileBytes = 10L * 1024 * 1024;
+ public const int MaxRolledFilesPerLocalDay = 10;
+
+ private static readonly string DesktopDir =
+ Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
+
+ private static readonly string ArchiveDir = Path.Combine(DesktopDir, "RynthLogs");
+
+ /// Pre-defined stems for the three Rynth products (one file each on the desktop).
+ public const string StemEngine = "RynthCore";
+ public const string StemLauncher = "RynthCore-Launcher";
+ public const string StemInjector = "RynthCore-Injector";
+
+ private static readonly object Gate = new();
+
+ /// File name without extension, e.g. .
+ public static void AppendLine(string fileStem, string line)
+ {
+ string stem = SanitizeStem(fileStem);
+ string text = line ?? string.Empty;
+ if (text.Length > 0 && text[^1] is not '\n' and not '\r')
+ text += Environment.NewLine;
+
+ lock (Gate)
+ {
+ try
+ {
+ string active = Path.Combine(DesktopDir, stem + ".log");
+ Directory.CreateDirectory(ArchiveDir);
+
+ if (File.Exists(active) && new FileInfo(active).Length + Encoding.UTF8.GetByteCount(text) > MaxActiveFileBytes)
+ RotateToArchive(stem, active);
+
+ using var stream = new FileStream(active, FileMode.Append, FileAccess.Write, FileShare.Read);
+ var bytes = Encoding.UTF8.GetBytes(text);
+ stream.Write(bytes, 0, bytes.Length);
+ }
+ catch
+ {
+ // Intentionally silent: logging must not crash host.
+ }
+ }
+ }
+
+ // Moves current active file to RynthLogs; trims same-day archives for this stem, then the move.
+ private static void RotateToArchive(string stem, string activePath)
+ {
+ string ymd = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
+ string prefix = stem + "-roll-" + ymd + "-";
+
+ PruneOldestRolledForPrefix(prefix);
+
+ string destName = prefix + DateTime.Now.ToString("HHmmssfff", CultureInfo.InvariantCulture) + ".log";
+ string destPath = Path.Combine(ArchiveDir, destName);
+ if (File.Exists(destPath)) File.Delete(destPath);
+ try
+ {
+ File.Move(activePath, destPath, overwrite: false);
+ }
+ catch
+ {
+ try
+ {
+ if (File.Exists(destPath)) File.Delete(destPath);
+ }
+ catch
+ {
+ // ignore
+ }
+
+ if (File.Exists(activePath)) File.Delete(activePath);
+ }
+ }
+
+ // Ensures that after a new file with this prefix is created, at most MaxRolledFilesPerLocalDay rolled files for this prefix+day exist.
+ private static void PruneOldestRolledForPrefix(string prefix)
+ {
+ if (!Directory.Exists(ArchiveDir)) return;
+
+ var todaysRolled = new DirectoryInfo(ArchiveDir)
+ .GetFiles(prefix + "*.log", SearchOption.TopDirectoryOnly)
+ .OrderBy(f => f.CreationTimeUtc)
+ .ThenBy(f => f.Name, StringComparer.OrdinalIgnoreCase)
+ .ToList();
+
+ // Delete oldest rolled segments until a new one would not exceed the daily cap.
+ while (todaysRolled.Count >= MaxRolledFilesPerLocalDay)
+ {
+ try
+ {
+ todaysRolled[0].Delete();
+ todaysRolled.RemoveAt(0);
+ }
+ catch
+ {
+ break;
+ }
+ }
+ }
+
+ private static string SanitizeStem(string? stem)
+ {
+ if (string.IsNullOrWhiteSpace(stem)) return "RynthLog";
+ var invalid = Path.GetInvalidFileNameChars();
+ var b = new StringBuilder(stem.Length);
+ foreach (var ch in stem.Trim())
+ {
+ if (!invalid.Contains(ch) && ch != Path.DirectorySeparatorChar && ch != Path.AltDirectorySeparatorChar)
+ b.Append(ch);
+ }
+
+ string t = b.ToString();
+ return t.Length == 0 ? "RynthLog" : t;
+ }
+}
diff --git a/src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs b/src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs
new file mode 100644
index 0000000..a73d61d
--- /dev/null
+++ b/src/RynthCore.DesktopLog/NetDesktopX64Prerequisite.cs
@@ -0,0 +1,105 @@
+// Detects the same "Suite tools" .NET 10+ x64 prerequisite as the Inno installer
+// (installer\RynthCore.iss, IsNetDesktop* helpers). If you change registry checks here,
+// update RynthCore.iss in lockstep and vice versa.
+
+using System;
+using System.Globalization;
+using System.Linq;
+using System.Runtime.Versioning;
+using Microsoft.Win32;
+
+namespace RynthCore;
+
+///
+/// Registry probe for the optional x64 framework-dependent tools (Loot Editor, Monster Editor).
+/// Must match IsNetDesktop10PlusX64Present and its helpers in installer/RynthCore.iss
+/// (Path A: Microsoft.WindowsDesktop.App shared folders; Path B: sharedhost Version;
+/// Path C: InstalledManifests\x64 manifest-10. bands). Uses 64-bit registry view from an x86 process.
+///
+[SupportedOSPlatform("windows")]
+public static class NetDesktopX64Prerequisite
+{
+ // Same string as RynthCore.iss DotNet10DesktopDownloadUrl (x64 runtime hub; user picks Desktop / ASP.NET as needed).
+ public const string DotNet10RuntimeDownloadUrl = "https://dotnet.microsoft.com/en-us/download/dotnet/10.0/runtime";
+
+ /// True if the x64 FDD tool prerequisite is met, or the OS is 32-bit (N/A, same as Inno skip).
+ public static bool IsSatisfied()
+ {
+ if (!Environment.Is64BitOperatingSystem)
+ return true;
+
+ return
+ IsWindowsDesktopSharedFramework10Plus()
+ || IsDotNet10BandInInstalledManifestsX64()
+ || IsSharedHostVersion10PlusX64();
+ }
+
+ // Path A: HKLM\SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App\10.x.y
+ private static bool IsWindowsDesktopSharedFramework10Plus()
+ {
+ using RegistryKey? base64 = OpenLocalMachine64();
+ using RegistryKey? key = base64?.OpenSubKey(@"SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App");
+ if (key is null)
+ return false;
+
+ foreach (string name in key.GetSubKeyNames())
+ {
+ if (ParseMajorFromVersionFolder(name) >= 10)
+ return true;
+ }
+
+ return false;
+ }
+
+ // Path B: sharedhost Version 10+ under Setup\InstalledVersions\x64\sharedhost
+ private static bool IsSharedHostVersion10PlusX64()
+ {
+ if (ReadSharedHostMajor(@"SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost") >= 10)
+ return true;
+ if (ReadSharedHostMajor(@"SOFTWARE\Microsoft\dotnet\Setup\InstalledVersions\x64\sharedhost") >= 10)
+ return true;
+ return false;
+ }
+
+ private static int ReadSharedHostMajor(string subKeyPath)
+ {
+ using RegistryKey? base64 = OpenLocalMachine64();
+ using RegistryKey? key = base64?.OpenSubKey(subKeyPath);
+ if (key is null)
+ return 0;
+ string? v = key.GetValue("Version") as string;
+ if (string.IsNullOrWhiteSpace(v))
+ return 0;
+ return ParseMajorFromVersionFolder(v.Trim());
+ }
+
+ // Path C: InstalledManifests x64, subkeys like ...Manifest-10.0.100
+ private static bool IsDotNet10BandInInstalledManifestsX64()
+ {
+ using RegistryKey? base64 = OpenLocalMachine64();
+ using RegistryKey? key = base64?.OpenSubKey(@"SOFTWARE\Microsoft\dotnet\InstalledManifests\x64");
+ if (key is null)
+ return false;
+
+ return key.GetSubKeyNames().Any(s => s != null
+ && s.IndexOf("Manifest-10.", StringComparison.OrdinalIgnoreCase) >= 0);
+ }
+
+ private static RegistryKey? OpenLocalMachine64() =>
+ RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
+
+ /// First numeric segment of a "10.0.5" style folder or version string (Pascal: Copy before first '.').
+ private static int ParseMajorFromVersionFolder(string name)
+ {
+ int dot = name.IndexOf('.');
+ if (dot <= 0)
+ return 0;
+ return int.TryParse(
+ name.AsSpan(0, dot),
+ NumberStyles.Integer,
+ CultureInfo.InvariantCulture,
+ out int m)
+ ? m
+ : 0;
+ }
+}
diff --git a/src/RynthCore.DesktopLog/RynthCore.DesktopLog.csproj b/src/RynthCore.DesktopLog/RynthCore.DesktopLog.csproj
new file mode 100644
index 0000000..76bf537
--- /dev/null
+++ b/src/RynthCore.DesktopLog/RynthCore.DesktopLog.csproj
@@ -0,0 +1,10 @@
+
+
+ net10.0
+ enable
+ enable
+ RynthCore
+ RynthCore.DesktopLog
+ 1.0.1
+
+
diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs
index f652df1..1acd7ab 100644
--- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs
+++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs
@@ -241,6 +241,24 @@ internal static class ClientObjectHooks
private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue;
private static bool _loggedObjectIdentityServe;
private const int ObjectIdentityPrefetchThrottleMs = 500;
+
+ // Create-time identity seeds. ACCObjectMaint::CreateObject receives the server's
+ // PublicWeenieDesc, which already carries the object's name and ITEM_TYPE before
+ // qualities/appraisal exist. The main-thread snapshot above can't resolve names for
+ // ~10 s after login (qualities not populated yet), so off-thread readers fall back to
+ // these seeds when the snapshot has no entry (or reports type 0). Entries live from
+ // create until delete; the cap only guards against a missed delete hook.
+ private static readonly object _createSeedLock = new();
+ private static readonly Dictionary _createSeedNames = new(1024);
+ private static readonly Dictionary _createSeedTypes = new(1024);
+ private const int CreateSeedCap = 16384;
+ // PublicWeenieDesc field offsets (Chorizite Weenie.cs; same layout the PWD-direct
+ // fallbacks in TryGetObjectName / TryGetItemType read from the embedded copy).
+ // PwdTypeOffset is declared with the other PublicWeenieDesc offsets further down.
+ private const int PwdNameOffset = 4;
+ private static int _createSeedCount;
+ private static bool _loggedCreateSeedServe;
+
// Every id the same walk visited, swapped whole (readers never see a half-built array).
private static volatile uint[] _liveObjectIds = Array.Empty();
@@ -393,6 +411,7 @@ internal static class ClientObjectHooks
private static readonly object _weeniePtrSwapLock = new();
private static Dictionary _weeniePtrFront = new(512);
private static Dictionary _weeniePtrBack = new(512);
+
// Diagnostic (temporary): periodic snapshot-size log + live-read probe of
// objects with a position but no cached name. Remove once the missing-
// monsters cause is pinned. _diagSampleBuf preallocated to stay low-alloc.
@@ -2019,8 +2038,9 @@ internal static class ClientObjectHooks
value = 0;
if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0)
return false;
+ // Off-thread: served from the main-thread PWD byte snapshot, never from AC memory.
if (!MainThreadGuard.IsOnMainThread())
- return false;
+ return TryGetPwdSnapshotRawInt32(objectId, pwdFieldOffset, out value);
if (_getWeenieObject == null)
{
if (!Probe() || _getWeenieObject == null)
@@ -2393,6 +2413,19 @@ internal static class ClientObjectHooks
// Off-thread: serve from the main-thread snapshot populated by PrefetchObjectIdentity().
if (!MainThreadGuard.IsOnMainThread())
{
+ lock (_objectIdentityCacheLock)
+ {
+ // A zero snapshot value means qualities weren't populated when the walk
+ // ran; prefer the create-time descriptor type in that case.
+ if (_objectTypeCache.TryGetValue(objectId, out typeFlags) && typeFlags != 0)
+ return true;
+ }
+ if (TryGetCreateSeedType(objectId, out uint seeded))
+ {
+ typeFlags = seeded;
+ return true;
+ }
+ // Snapshot hit with flags=0 is still an answer (static scenery often has no type).
lock (_objectIdentityCacheLock)
{
if (_objectTypeCache.TryGetValue(objectId, out typeFlags))
@@ -3341,6 +3374,101 @@ internal static class ClientObjectHooks
}
}
+ ///
+ /// Records an object's name and ITEM_TYPE straight from the PublicWeenieDesc passed
+ /// to ACCObjectMaint::CreateObject. Called from the create hook on AC's main thread,
+ /// after the original returns. The descriptor is server data that exists before the
+ /// object's qualities do, so this makes names/types readable off-thread immediately
+ /// instead of after the first successful identity snapshot (~10 s at login).
+ /// Every read is pointer-validated; a bad descriptor simply records nothing.
+ ///
+ internal static void SeedIdentityFromCreate(uint objectId, IntPtr weenieDesc)
+ {
+ if (objectId == 0 || weenieDesc == IntPtr.Zero)
+ return;
+
+ try
+ {
+ // PublicWeenieDesc derives from PackObj, so a real descriptor starts with an
+ // acclient.exe vtable; reject anything else before reading fields.
+ if (!LooksLikeAcHeapObject(weenieDesc))
+ return;
+
+ bool gotName = TryReadPwdString(weenieDesc, PwdNameOffset, out string name);
+
+ uint typeFlags = 0;
+ IntPtr typeAddr = weenieDesc + PwdTypeOffset;
+ bool gotType = IsReadablePointer(typeAddr);
+ if (gotType)
+ typeFlags = unchecked((uint)Marshal.ReadInt32(typeAddr));
+
+ if (!gotName && (!gotType || typeFlags == 0))
+ return;
+
+ lock (_createSeedLock)
+ {
+ // Safety valve for a missed delete: drop everything rather than grow forever.
+ // The live snapshot covers anything still in the world.
+ if (_createSeedNames.Count >= CreateSeedCap || _createSeedTypes.Count >= CreateSeedCap)
+ {
+ _createSeedNames.Clear();
+ _createSeedTypes.Clear();
+ }
+ if (gotName)
+ _createSeedNames[objectId] = name;
+ if (gotType && typeFlags != 0)
+ _createSeedTypes[objectId] = typeFlags;
+ }
+
+ int seedNo = System.Threading.Interlocked.Increment(ref _createSeedCount);
+ // First few samples let a log reader confirm the descriptor offsets resolve
+ // to sensible names/types on this client build.
+ if (seedNo <= 5)
+ RynthLog.Compat($"[CreateSeed] #{seedNo} 0x{objectId:X8} name='{(gotName ? name : "")}' type=0x{typeFlags:X8}");
+ if (!_loggedCreateSeedServe && seedNo >= 50)
+ {
+ _loggedCreateSeedServe = true;
+ int names, types;
+ lock (_createSeedLock) { names = _createSeedNames.Count; types = _createSeedTypes.Count; }
+ RynthLog.Compat($"ClientObjectHooks: create-descriptor identity seeds active — {names} names, {types} types captured at CreateObject.");
+ }
+ }
+ catch
+ {
+ // Descriptor read failures are non-fatal; the periodic snapshot still runs.
+ }
+ }
+
+ /// Drops create-time seeds for a deleted object (called from the delete hook).
+ internal static void ForgetCreateSeed(uint objectId)
+ {
+ lock (_createSeedLock)
+ {
+ _createSeedNames.Remove(objectId);
+ _createSeedTypes.Remove(objectId);
+ }
+ }
+
+ private static bool TryGetCreateSeedName(uint objectId, out string name)
+ {
+ lock (_createSeedLock)
+ {
+ if (_createSeedNames.TryGetValue(objectId, out string? seeded) && seeded.Length > 0)
+ {
+ name = seeded;
+ return true;
+ }
+ }
+ name = string.Empty;
+ return false;
+ }
+
+ private static bool TryGetCreateSeedType(uint objectId, out uint typeFlags)
+ {
+ lock (_createSeedLock)
+ return _createSeedTypes.TryGetValue(objectId, out typeFlags);
+ }
+
public static bool TryGetObjectName(uint objectId, out string name)
{
name = string.Empty;
@@ -3356,6 +3484,10 @@ internal static class ClientObjectHooks
return true;
}
}
+ // Snapshot miss (login burst / object newer than the last walk): serve the
+ // name captured from the create descriptor.
+ if (TryGetCreateSeedName(objectId, out name))
+ return true;
name = string.Empty;
return false;
}
@@ -3809,6 +3941,21 @@ internal static class ClientObjectHooks
&& PwdLayout.TryGetInt(e.Bytes, stype, out value);
}
+ ///
+ /// Off-thread read of one 4-byte PWD field by raw offset (the
+ /// contract) from the main-thread snapshot. False for objects the last walk didn't see.
+ ///
+ private static bool TryGetPwdSnapshotRawInt32(uint objectId, int pwdFieldOffset, out int value)
+ {
+ value = 0;
+ if (pwdFieldOffset < 0 || pwdFieldOffset + 4 > PwdLayout.Size)
+ return false;
+ if (!TryGetPwdSnapshot(objectId, out PwdEntry e))
+ return false;
+ value = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(((ReadOnlySpan)e.Bytes).Slice(pwdFieldOffset));
+ return true;
+ }
+
private static bool TryGetPwdSnapshotFloat(uint objectId, uint stype, out double value)
{
value = 0;
diff --git a/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs b/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs
index 9377b39..558a192 100644
--- a/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs
+++ b/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs
@@ -81,6 +81,9 @@ internal static class CreateObjectHooks
if (count <= 0)
RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}");
+ // Capture name/type from the create descriptor BEFORE the plugin is told about the
+ // object, so its off-thread classifier can read them on the very first attempt.
+ ClientObjectHooks.SeedIdentityFromCreate(objectId, weenieDesc);
PluginManager.QueueCreateObject(objectId);
AutoIdService.Enqueue(objectId);
return result;
diff --git a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs
index 3f8df11..151dffd 100644
--- a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs
+++ b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs
@@ -71,6 +71,7 @@ internal static class DeleteObjectHooks
if (objectId != 0)
{
PaletteCache.Remove(objectId);
+ ClientObjectHooks.ForgetCreateSeed(objectId);
PluginManager.QueueDeleteObject(objectId);
AutoIdService.Evict(objectId);
}
diff --git a/src/RynthCore.Engine/Compatibility/DragDropHooks.cs b/src/RynthCore.Engine/Compatibility/DragDropHooks.cs
new file mode 100644
index 0000000..6b221bc
--- /dev/null
+++ b/src/RynthCore.Engine/Compatibility/DragDropHooks.cs
@@ -0,0 +1,110 @@
+// ============================================================================
+// RynthCore.Engine - Compatibility/DragDropHooks.cs
+// Hooks UIElementManager::StartDragandDrop so the engine knows which item AC
+// is actually dragging. AC does not change the selected object when a drag
+// starts, so the selection is the previously clicked item, not the dragged one.
+//
+// The dragged UI element is resolved to an object id with AC's own
+// UIElement_ItemList::InqDropIconInfo (the same call AC makes when the drop
+// lands), then handed to ItemDragBridge, which republishes it to ImGui.
+//
+// Threads: AC's main thread (AC's input / UI processing).
+// ============================================================================
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using RynthCore.Engine.Hooking;
+using RynthCore.Engine.ImGuiBackend;
+
+namespace RynthCore.Engine.Compatibility;
+
+internal static unsafe class DragDropHooks
+{
+ // bool __thiscall UIElementManager::StartDragandDrop(UIElementManager*, UIElement* elem, int clickX, int clickY)
+ private const int StartDragandDropVa = 0x0045E120;
+ // void __cdecl UIElement_ItemList::InqDropIconInfo(const UIElement* icon, uint& itemId, uint& spellId, DropItemFlags& flags)
+ private const int InqDropIconInfoVa = 0x004E3380;
+
+ // Both verified unique in the shipped client (sub esp,34h / mov edi,[esp+48h] / mov esi,ecx prologue;
+ // InqDropIconInfo zeroes its out-params up front).
+ private static readonly byte?[] StartDragandDropPattern =
+ [
+ 0x83, 0xEC, 0x34, 0x53, 0x55, 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x48, 0x85, 0xFF, 0x8B, 0xF1, 0x0F, 0x84,
+ null, null, null, null, 0xA1, null, null, null, null, 0x85, 0xC0
+ ];
+ private static readonly byte?[] InqDropIconInfoPattern =
+ [
+ 0x8B, 0x44, 0x24, 0x10, 0x83, 0xEC, 0x3C, 0x53, 0x55, 0x8B, 0x6C, 0x24, 0x50, 0x56, 0x8B, 0x74, 0x24, 0x4C,
+ 0x33, 0xDB, 0x3B, 0xF3, 0x57, 0x8B, 0x7C, 0x24, 0x54, 0x89, 0x1F
+ ];
+
+ private static IntPtr _originalStartDrag;
+ private static delegate* unmanaged[Cdecl] _inqDropIconInfo;
+ private static int _logCount;
+
+ /// The drag-start hook is live, so ItemDragBridge gets the real dragged item.
+ public static bool IsInstalled { get; private set; }
+ public static string StatusMessage { get; private set; } = "Not probed yet.";
+
+ public static void Initialize()
+ {
+ if (IsInstalled) return;
+ if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
+ {
+ StatusMessage = "acclient.exe not available.";
+ return;
+ }
+
+ var inq = HookResolver.Resolve(text, "DragDrop.InqDropIconInfo", InqDropIconInfoPattern, InqDropIconInfoVa);
+ var start = HookResolver.Resolve(text, "DragDrop.StartDragandDrop", StartDragandDropPattern, StartDragandDropVa);
+ // A guessed address for either would mean calling or patching the wrong code: pattern hits only.
+ if (inq.Source != HookResolver.ResolveSource.PatternScan || start.Source != HookResolver.ResolveSource.PatternScan)
+ {
+ StatusMessage = $"drag-start hook skipped (InqDropIconInfo {inq.Detail}, StartDragandDrop {start.Detail}).";
+ RynthLog.Compat($"Compat: {StatusMessage}");
+ return;
+ }
+
+ try
+ {
+ _inqDropIconInfo = (delegate* unmanaged[Cdecl])inq.Address;
+ delegate* unmanaged[Thiscall] detour = &StartDragandDropDetour;
+ MinHook.Hook(start.Address, (IntPtr)detour, out _originalStartDrag);
+ IsInstalled = true;
+ StatusMessage = $"Hooked UIElementManager::StartDragandDrop @ 0x{start.Address.ToInt32():X8}.";
+ RynthLog.Info($"Compat: drag-start hook ready - StartDragandDrop=0x{start.Address.ToInt32():X8}, InqDropIconInfo=0x{inq.Address.ToInt32():X8}");
+ }
+ catch (Exception ex)
+ {
+ StatusMessage = ex.Message;
+ RynthLog.Compat($"Compat: drag-start hook failed - {ex.Message}");
+ }
+ }
+
+ [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
+ private static byte StartDragandDropDetour(IntPtr manager, IntPtr element, int clickX, int clickY)
+ {
+ try
+ {
+ if (element != IntPtr.Zero && _inqDropIconInfo != null)
+ {
+ uint itemId = 0, spellId = 0, flags = 0;
+ _inqDropIconInfo(element, &itemId, &spellId, &flags);
+ // Spell-bar drags carry a spell id and no item.
+ if (itemId != 0)
+ {
+ if (_logCount < 20) { _logCount++; RynthLog.UI($"DragDropHooks: AC drag start item=0x{itemId:X8} flags=0x{flags:X}"); }
+ ItemDragBridge.OnNativeDragStart(itemId);
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ try { RynthLog.Compat($"Compat: drag-start detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
+ }
+
+ var original = (delegate* unmanaged[Thiscall])_originalStartDrag;
+ return original(manager, element, clickX, clickY);
+ }
+}
diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs
index 677e141..f6ec650 100644
--- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs
+++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs
@@ -458,6 +458,11 @@ internal static class EndSceneHook
if (_uiFrameCount < 30)
RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}");
}
+
+ // ImGui draw data (in-client panels, plugin overlay windows such as the ILT Hub)
+ // is submitted LAST so it sits on top of the Avalonia layer. Built in OnEndScene;
+ // guarded internally, so an ImGui draw failure can't skip the original EndScene.
+ EngineFrameController.RenderDeferredImGui();
}
catch (Exception ex)
{
diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs
index 990338b..6456fdb 100644
--- a/src/RynthCore.Engine/EngineLifecycle.cs
+++ b/src/RynthCore.Engine/EngineLifecycle.cs
@@ -162,6 +162,7 @@ internal static class EngineLifecycle
// tick pump and plugins go away — both otherwise keep firing in the old
// generation's (intentionally still-mapped) module across hot-reloads.
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
+ Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher());
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.
diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs
index 3dc855a..a45fc36 100644
--- a/src/RynthCore.Engine/EntryPoint.cs
+++ b/src/RynthCore.Engine/EntryPoint.cs
@@ -12,6 +12,7 @@ using System.Runtime.InteropServices;
using System.Threading;
using System.Collections.Generic;
using ImGuiNET;
+using RynthCore;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins;
@@ -45,7 +46,21 @@ public static class EntryPoint
private static readonly Queue RecentLogLines = new();
private static long _recentLogSeq;
- /// Set true to enable verbose startup logging (hook ready messages, plugin lifecycle, etc.).
+ internal enum EngineLogLevel
+ {
+ /// As a global threshold: nothing but errors. As a category level: never written.
+ Off = -1,
+ Error = 0,
+ Warning = 1,
+ Info = 2,
+ Debug = 3,
+ Trace = 4
+ }
+
+ /// Active engine logging threshold loaded from engine settings.
+ internal static EngineLogLevel LoggingLevel = EngineLogLevel.Info;
+
+ /// Legacy convenience flag used by existing verbose call sites.
internal static bool VerboseLogging = false;
/// Set by EngineFrameController once the game window is confirmed. Read by AvaloniaOverlay.
@@ -154,8 +169,14 @@ public static class EntryPoint
}
catch { }
+ // engine.json "LoggingLevel" + "LogCategories" (launcher Logging card) set the threshold
+ // and per-category levels first so every line written below honours them. The watcher
+ // started later re-reads them whenever the launcher edits the file.
+ string logSummary = LogSettings.Reload();
+
// Set up the unified log sink BEFORE anything else so all
- // subsequent failures are captured in C:\Games\RynthCore\Logs.
+ // subsequent failures are captured in \Logs (installer-chosen;
+ // resolved here on the init worker, never under the loader lock).
LogPaths.EnsureLogDirectory();
if (_initCount <= 1)
{
@@ -170,10 +191,18 @@ public static class EntryPoint
InstallManagedExceptionHandlers();
- RynthLog.Info("================================================================");
- RynthLog.Info($"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}");
- RynthLog.Info($" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}");
- RynthLog.Info("================================================================");
+ // The banner bypasses the category levels: it must be in every log, whatever engine.json says.
+ LogTagged("engine", "================================================================", "INF");
+ LogTagged("engine", $"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}", "INF");
+ LogTagged("engine", $" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}", "INF");
+ LogTagged("engine", $" logging {logSummary}", "INF");
+ LogTagged("engine", "================================================================", "INF");
+ string hiddenCategories = LogSettings.HiddenCategoriesWarning();
+ if (hiddenCategories.Length > 0) RynthLog.Warn(hiddenCategories);
+
+ // Live logging config: launcher edits to engine.json apply without a client restart.
+ // Stopped in EngineLifecycle.Shutdown before the module can be unloaded.
+ LogSettings.StartWatcher();
CrashLogger.Install();
@@ -181,18 +210,10 @@ public static class EntryPoint
// logging AC's main-thread native stack when its EndScene beat stalls.
MainThreadHangWatchdog.Start();
- // MultiClientHooks.Initialize installs MinHook detours synchronously
- // here, BEFORE InitWorker spawns and runs the main PreloadNativeDll
- // pass. If we don't preload minhook.x86.dll first, the P/Invoke
- // into minhook fails with DllNotFoundException and the multi-
- // client hook silently skips — which means AC's
- // Client::IsAlreadyRunning check fires unpatched on the second-
- // and-later concurrent acclient.exe processes.
- string? earlyEngineDir = GetEngineDirectory();
- if (!string.IsNullOrEmpty(earlyEngineDir))
- PreloadNativeDll(earlyEngineDir, "minhook.x86.dll");
- else
- RynthLog.Info("Early-init: could not resolve engine directory — minhook may not be preloaded before MultiClientHooks.");
+ // MultiClientHooks installs MinHook-based detours immediately. P/Invoke resolves
+ // minhook.x86.dll before InitWorker runs, so preload it from the engine directory;
+ // otherwise Client::IsAlreadyRunning fires unpatched on second-and-later clients.
+ TryPreloadMinHookForEarlyInit();
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
// DatFileShareHooks force-shares AC's data files at the CreateFile
@@ -300,6 +321,33 @@ public static class EntryPoint
return new string(buffer, 0, (int)length);
}
+ ///
+ /// Loads MinHook on the RynthCoreInit thread so can
+ /// call P/Invokes without relying on the default DLL search path
+ /// (which often resolves against the AC client directory, not Runtime\).
+ ///
+ private static void TryPreloadMinHookForEarlyInit()
+ {
+ try
+ {
+ string? engineDir = GetEngineDirectory();
+ if (string.IsNullOrEmpty(engineDir))
+ {
+ RynthLog.Info("Early MinHook preload skipped: could not resolve engine directory.");
+ return;
+ }
+
+ if (PreloadNativeDll(engineDir, "minhook.x86.dll"))
+ RynthLog.Verbose($"Early MinHook preload OK (engine dir: {engineDir})");
+ else
+ RynthLog.Info($"Early MinHook preload failed: minhook.x86.dll not found beside engine ({engineDir}).");
+ }
+ catch (Exception ex)
+ {
+ RynthLog.Info($"Early MinHook preload exception: {ex.Message}");
+ }
+ }
+
///
/// No-op anchor whose address is taken via `&EngineDirAnchor` to give us a
/// stable pointer inside the engine's own module image — used by
@@ -656,6 +704,8 @@ public static class EntryPoint
Step("account hooks", AccountHooks.Initialize);
Step("client combat hooks", () => ClientCombatHooks.Probe());
Step("selected-target hooks", SelectedTargetHooks.Initialize);
+ // Which item AC is dragging (AC keeps the old selection during a drag).
+ Step("drag-start hook", DragDropHooks.Initialize);
Step("smartbox hooks", SmartBoxHooks.Initialize);
Step("player vitals hooks", PlayerVitalsHooks.Initialize);
Step("enchantment hooks", () => EnchantmentHooks.Initialize());
@@ -1639,10 +1689,34 @@ public static class EntryPoint
internal static void LogVerbose(string message)
{
- if (VerboseLogging)
+ if (ShouldLog(EngineLogLevel.Debug))
Log(message);
}
+ ///
+ /// True when a line at passes the global threshold. Off-level lines
+ /// never pass; an Off threshold blocks everything (errors bypass this gate).
+ ///
+ internal static bool ShouldLog(EngineLogLevel level)
+ => level != EngineLogLevel.Off && level <= LoggingLevel;
+
+ /// Parses the global level: Off, Error, Warning/Warn, Info, Debug/Verbose, Trace. Unknown → Info.
+ internal static EngineLogLevel ParseLoggingLevel(string? configuredLevel)
+ {
+ if (string.IsNullOrWhiteSpace(configuredLevel))
+ return EngineLogLevel.Info;
+
+ string normalized = configuredLevel.Trim();
+ if (string.Equals(normalized, "Verbose", StringComparison.OrdinalIgnoreCase))
+ return EngineLogLevel.Debug;
+ if (string.Equals(normalized, "Warn", StringComparison.OrdinalIgnoreCase))
+ return EngineLogLevel.Warning;
+
+ return Enum.TryParse(normalized, ignoreCase: true, out EngineLogLevel parsed) && Enum.IsDefined(parsed)
+ ? parsed
+ : EngineLogLevel.Info;
+ }
+
internal static string[] GetRecentLogLines()
{
lock (LogLock)
diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs
index a223450..ee29fee 100644
--- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs
+++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs
@@ -23,6 +23,7 @@ using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins;
+using RynthCore.Install;
namespace RynthCore.Engine.ImGuiBackend;
@@ -48,6 +49,9 @@ internal static class EngineFrameController
private static bool _imguiInitFailed;
private static bool _coreResolved;
private static bool _pluginsInitialized;
+ // Pump frames plugin init has waited for the ImGui context (PumpPluginFrame; ~16 ms each).
+ private static int _pluginInitContextWaits;
+ private const int PluginInitContextMaxWaits = 300;
private static IntPtr _context;
private static IntPtr _gameHwnd;
@@ -61,6 +65,25 @@ internal static class EngineFrameController
///
internal static volatile IntPtr CachedDevice;
private static int _pluginPumpInFrame; // re-entrancy guard for the pump
+
+ // ImGui pipeline diagnostics (render thread only): one-time lines plus a 30 s heartbeat so a
+ // log shows whether frames start, which branch runs and whether draw data is submitted.
+ private const long HeartbeatIntervalMs = 30_000;
+ private static long _engineErrorCount;
+ private static long _nextEngineErrorLogAt;
+ private static bool _loggedFirstSubmit;
+ private static int _loggedBranch = -1;
+ private static string _initFailStep = "unknown";
+ private static long _drawSubmits;
+ private static long _nextHeartbeatAt;
+
+ // Device for this frame's built ImGui draw data, submitted by RenderDeferredImGui after the
+ // Avalonia blit. Render thread only; Zero = nothing pending. The draw data stays valid until
+ // the next NewFrame on the main context.
+ private static IntPtr _deferredSubmitDevice;
+ // Build + pop-out time of the frame waiting in _deferredSubmitDevice (UiFrameStats adds the submit).
+ private static long _deferredUiTicks;
+
private static long _lastFrameTicks;
private static int _frameCount;
@@ -103,7 +126,10 @@ internal static class EngineFrameController
return true;
if (!EnsureCore(pDevice))
+ {
+ _initFailStep = "EnsureCore (game window not found)";
return false;
+ }
// Before any context exists: the loaded cimgui.dll must be the exact
// build ImGui.NET wraps, or every struct read below is at wrong offsets.
@@ -131,7 +157,7 @@ internal static class EngineFrameController
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}");
+ RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
}
catch (Exception ex)
{
@@ -155,10 +181,16 @@ internal static class EngineFrameController
ImGuiFonts.Build(io, _uiScale);
if (!Win32Backend.Init(_gameHwnd))
+ {
+ _initFailStep = "Win32Backend.Init";
return false;
+ }
if (!DX9Backend.InitImGui(pDevice))
+ {
+ _initFailStep = "DX9Backend.InitImGui";
return false;
+ }
_lastFrameTicks = Stopwatch.GetTimestamp();
_imguiInitialized = true;
@@ -229,6 +261,8 @@ internal static class EngineFrameController
// EngineSettings.EnableImGuiBackend, so world→screen capture, nav-
// marker rendering, and plugin lifecycle stay alive when the ImGui
// surface is disabled.
+ // A frame that throws before its build must not resubmit last frame's draw data.
+ _deferredSubmitDevice = IntPtr.Zero;
try
{
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
@@ -344,10 +378,10 @@ internal static class EngineFrameController
// calls it at all.
// ── ImGui-gated work ─────────────────────────────────────────
- // The frame is BUILT here and SUBMITTED after the Nav3D fallback and
- // the vital HUD, so ImGui windows sit above both. The Avalonia quad
- // (EndSceneHook, after this returns) stays topmost while both stacks
- // run, matching input order: Avalonia gets the first hit test.
+ // The frame is BUILT here and SUBMITTED by RenderDeferredImGui, which
+ // EndSceneHook calls after the Avalonia quad, so ImGui windows sit above
+ // the Nav3D fallback, the vital HUD and the Avalonia panels. Input order
+ // matches: Win32Backend gives ImGui the mouse while it wants it.
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
bool imguiBuilt = false;
long uiTicks = 0;
@@ -370,17 +404,33 @@ internal static class EngineFrameController
if (imguiEnabled)
{
long t0 = Stopwatch.GetTimestamp();
- if (imguiBuilt)
- SubmitImGuiFrame(pDevice);
// Popped-out panels: their own contexts, windows and render targets.
if (_imguiInitialized)
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
- UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0));
+ long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0);
+ if (imguiBuilt)
+ {
+ _deferredUiTicks = ticks;
+ _deferredSubmitDevice = pDevice;
+ }
+ else
+ {
+ UiFrameStats.Record(ticks);
+ }
}
}
catch (Exception ex)
{
- RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}");
+ // An exception here skips everything after it this frame (including RunImGuiFrame), so
+ // the first one gets a stack trace; repeats are summarised every 30 s instead of per frame.
+ _engineErrorCount++;
+ long errNow = Environment.TickCount64;
+ if (_engineErrorCount == 1)
+ RynthLog.Error($"EngineFrameController: engine frame error (rest of this frame skipped): {ex}");
+ else if (errNow >= _nextEngineErrorLogAt)
+ RynthLog.Error($"EngineFrameController: engine frame errors so far={_engineErrorCount}, latest {ex.GetType().Name}: {ex.Message}");
+ if (errNow >= _nextEngineErrorLogAt)
+ _nextEngineErrorLogAt = errNow + HeartbeatIntervalMs;
}
finally
{
@@ -442,14 +492,26 @@ internal static class EngineFrameController
return; // never re-enter PluginManager from two stacks
try
{
- // Plugins only get the ImGui context when they may draw with it
- // (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels
- // don't need plugins to see it, and handing it over switched
- // RynthAi into its legacy-ImGui setup (first ImGui-on test,
- // 2026-09-28) - plugins must behave exactly as in Avalonia-only mode.
- IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero;
+ // Plugins only get the ImGui context when they may draw with it: the
+ // ImGui shell (EnableImGuiShell, FORCE-gated) or their own overlay
+ // windows (EnablePluginOverlayWindows: RynthAi's ILT Hub, HUDs, Item
+ // Info; RynthPluginRenderOverlay). RynthAi only reads the context for
+ // those windows, so this does not switch it into a legacy-ImGui setup.
+ bool pluginsDraw = Plugins.EngineSettings.EnableImGuiShell
+ || (Plugins.EngineSettings.EnablePluginOverlayWindows && Plugins.EngineSettings.EnableImGuiBackend);
+ // _context is written by the render thread (Init); this is the pump thread.
+ IntPtr pluginContext = pluginsDraw ? System.Threading.Volatile.Read(ref _context) : IntPtr.Zero;
if (!_pluginsInitialized)
{
+ // The plugin host copies the context once at init, so wait for the
+ // render path's ImGui init (first ImGui frame) rather than hand over
+ // zero for the whole session. Bounded: a failed or stalled ImGui init
+ // must not hold plugins (and the bot) back.
+ if (pluginsDraw && pluginContext == IntPtr.Zero && !_imguiInitFailed
+ && ++_pluginInitContextWaits <= PluginInitContextMaxWaits)
+ return;
+ if (pluginsDraw && pluginContext == IntPtr.Zero)
+ RynthLog.Warn($"EngineFrameController: plugins initialised without an ImGui context (imguiInitFailed={_imguiInitFailed}, waits={_pluginInitContextWaits}) - plugin overlay windows will not draw this session.");
_pluginsInitialized = true;
PluginManager.InitPlugins(pluginContext, device, _gameHwnd);
}
@@ -501,9 +563,16 @@ internal static class EngineFrameController
if (!PanelsLive) return false;
ImGuiPanelHost.RestoreOnce();
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame
- || D3D9.VideoPatch.WantsBanner;
+ || D3D9.VideoPatch.WantsBanner || PluginOverlayWindowsLive;
}
+ ///
+ /// In the world, with the shell off, and some loaded plugin exports
+ /// RynthPluginRenderOverlay: its windows need a frame every frame.
+ ///
+ private static bool PluginOverlayWindowsLive =>
+ PanelsLive && Plugins.EngineSettings.EnablePluginOverlayWindows && PluginManager.HasOverlayPlugins;
+
///
/// Panel faces show only in the world, like the Avalonia overlay (hidden
/// between characters, not closed). Also off as soon as AC leaves the world screen
@@ -544,7 +613,8 @@ internal static class EngineFrameController
}
private static bool HasImGuiContentNoRestore() =>
- Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner));
+ Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner))
+ || PluginOverlayWindowsLive;
// Keyboard owner between the stacks (plan §3.2 d): whichever side started
// text entry most recently keeps the keyboard.
@@ -573,6 +643,7 @@ internal static class EngineFrameController
if (!Init(pDevice))
{
_imguiInitFailed = true;
+ RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session.");
return false;
}
}
@@ -596,7 +667,6 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context);
bool frameStarted = false;
bool frameEnded = false;
-
try
{
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
@@ -644,6 +714,9 @@ internal static class EngineFrameController
ImGuiNET.ImGui.NewFrame();
frameStarted = true;
+ // Before any window: a drag from a popped-out Inventory or AC's inventory becomes
+ // a payload the client's drop targets (Mini Remote slots) see this frame.
+ ItemDragBridge.SubmitMainFrame(io);
ImGuiTextFocus.BeginFrame();
if (_dropImGuiTextFocus)
{
@@ -653,11 +726,29 @@ internal static class EngineFrameController
}
// EnableImGuiShell gates the old diagnostic shell and plugin-drawn
// ImGui windows (plugin code on AC's thread: FORCE-gated, stays off).
+ int branch;
if (Plugins.EngineSettings.EnableImGuiShell)
{
+ branch = 1;
RynthCoreShell.Render(_frameCount);
PluginManager.RenderAll();
}
+ else if (PluginOverlayWindowsLive)
+ {
+ branch = 2;
+ // Only the opt-in extra windows (RynthPluginRenderOverlay), never the
+ // plugins' full ImGui UIs.
+ PluginManager.RenderOverlayAll();
+ }
+ else
+ {
+ branch = 0;
+ }
+ if (branch != _loggedBranch)
+ {
+ _loggedBranch = branch;
+ RynthLog.Info($"EngineFrameController: ImGui plugin branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none")}.");
+ }
if (PanelsLive)
{
// World overlays: built into UnderUiLayer's list, drawn next frame at
@@ -744,6 +835,24 @@ internal static class EngineFrameController
_prevAvaloniaText = avaloniaText;
}
+ ///
+ /// Submits this frame's ImGui draw data. EndSceneHook calls it after
+ /// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia layer.
+ /// Runs whether or not the Avalonia blit ran (character select, Avalonia off), and is
+ /// a no-op when built nothing this frame. Never throws.
+ ///
+ public static void RenderDeferredImGui()
+ {
+ IntPtr device = _deferredSubmitDevice;
+ if (device == IntPtr.Zero)
+ return;
+ _deferredSubmitDevice = IntPtr.Zero; // one submission per frame, even if it throws
+
+ long t0 = Stopwatch.GetTimestamp();
+ SubmitImGuiFrame(device);
+ UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0));
+ }
+
/// Draws the frame produced.
private static void SubmitImGuiFrame(IntPtr pDevice)
{
@@ -751,7 +860,15 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context);
try
{
- DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice);
+ ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
+ DX9Backend.RenderDrawData(drawData, pDevice);
+ _drawSubmits++;
+ if (!_loggedFirstSubmit)
+ {
+ _loggedFirstSubmit = true;
+ RynthLog.Info("EngineFrameController: first ImGui draw submitted.");
+ }
+ LogHeartbeatIfDue(drawData);
}
catch (Exception ex)
{
@@ -763,6 +880,29 @@ internal static class EngineFrameController
}
}
+ ///
+ /// Every 30 s: built ImGui frames, submits, draw list / vertex counts of the
+ /// latest frame and the overlay-window stats from PluginManager. Zero draw lists means no
+ /// ImGui window was drawn that frame. One string per interval; no per-frame allocation.
+ ///
+ private static void LogHeartbeatIfDue(ImDrawDataPtr drawData)
+ {
+ long now = Environment.TickCount64;
+ if (now < _nextHeartbeatAt) return;
+ bool first = _nextHeartbeatAt == 0;
+ _nextHeartbeatAt = now + HeartbeatIntervalMs;
+ if (first) return; // first interval starts now; the first-frame line already covers t=0
+
+ int lists = 0, vertices = 0;
+ unsafe
+ {
+ // ImDrawData: +4 CmdListsCount, +8 TotalIdxCount, +12 TotalVtxCount (see CLAUDE.md offsets).
+ byte* p = (byte*)drawData.NativePtr;
+ if (p != null) { lists = *(int*)(p + 4); vertices = *(int*)(p + 12); }
+ }
+ RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesBuilt} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}.");
+ }
+
internal static IntPtr FindGameWindow()
{
uint pid = GetCurrentProcessId();
diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs
index f153763..f55b35d 100644
--- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs
+++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs
@@ -66,7 +66,11 @@ internal sealed record PanelSpec(
ImGuiWindowFlags BodyFlags = ImGuiWindowFlags.None,
// Where the panel first opens (logical units) when nothing is saved for its
// key; null = the cascade. (Script windows: a FirstUseEver position.)
- Vector2? DefaultPos = null);
+ Vector2? DefaultPos = null,
+ // With nothing saved and no DefaultPos: open centred in the game view rather
+ // than in the top-left cascade, where popped-out panels (separate windows
+ // above the game frame) usually sit and would hide it.
+ bool OpenCentered = false);
/// An ImGui panel face. One instance per open; dropped on close.
internal interface IImGuiPanel
@@ -648,6 +652,10 @@ internal static class ImGuiPanelHost
{
pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position)
}
+ else if (entry.Spec.OpenCentered && CenteredLogicalPos(size, placeScale) is Vector2 centered)
+ {
+ pos = centered;
+ }
else
{
int shown = 0;
@@ -667,6 +675,104 @@ internal static class ImGuiPanelHost
entry.NeedsPlacement = true;
entry.DesiredPos = entry.Pos != pos * placeScale ? pos * placeScale : null;
entry.DesiredForDisplay = ImGuiNET.ImGui.GetIO().DisplaySize;
+
+ // Popped-out windows sit above the game frame, so a docked panel opening under
+ // one would be invisible. The new spot is saved by the open's Persist, so the
+ // panel comes back where it could be seen.
+ if (ClearOfPopOuts(entry.Pos, entry.Size) is Vector2 clear)
+ {
+ RynthLog.UI($"ImGuiPanelHost: {entry.Title} would open under a popped-out window; " +
+ $"moved from ({entry.Pos.X:0},{entry.Pos.Y:0}) to ({clear.X:0},{clear.Y:0}).");
+ entry.Pos = clear;
+ entry.PersistedPos = clear;
+ entry.DesiredPos = null; // don't pull it back under the pop-out as the display grows
+ }
+ }
+
+ /// Above this share of a docked panel hidden by popped-out windows, it opens elsewhere.
+ private const float MaxCoveredFraction = 0.5f;
+ /// Candidate spots per axis when looking for a clear place (a grid over the game view).
+ private const int ClearSpotSteps = 8;
+
+ ///
+ /// A spot (client px) for a docked window of at
+ /// that popped-out windows hide less, nearest the original among the least-covered; null when
+ /// at most half of it is covered or no spot is better.
+ ///
+ private static Vector2? ClearOfPopOuts(Vector2 pos, Vector2 size)
+ {
+ float area = size.X * size.Y;
+ if (area <= 0) return null;
+ List<(Vector2 Min, Vector2 Max)> covers = PopOutRectsInClient();
+ if (covers.Count == 0) return null;
+ float covered = CoveredArea(pos, size, covers);
+ if (covered <= area * MaxCoveredFraction) return null;
+
+ Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
+ if (display.X <= 1 || display.Y <= 1) return null;
+ Vector2 room = Vector2.Max(Vector2.Zero, display - size);
+
+ // Pass 1: the least coverage any grid spot reaches. Pass 2: the nearest spot within
+ // 2% of the panel's area of that, so a nearly-as-clear nearby spot beats a far one.
+ float least = float.MaxValue;
+ for (int i = 0; i <= ClearSpotSteps; i++)
+ for (int j = 0; j <= ClearSpotSteps; j++)
+ least = Math.Min(least, CoveredArea(GridSpot(room, i, j), size, covers));
+ if (least >= covered) return null;
+
+ float tolerance = least + area * 0.02f;
+ Vector2? best = null;
+ float bestDist = float.MaxValue;
+ for (int i = 0; i <= ClearSpotSteps; i++)
+ for (int j = 0; j <= ClearSpotSteps; j++)
+ {
+ Vector2 spot = GridSpot(room, i, j);
+ if (CoveredArea(spot, size, covers) > tolerance) continue;
+ float dist = Vector2.DistanceSquared(spot, pos);
+ if (dist < bestDist) { bestDist = dist; best = spot; }
+ }
+ return best;
+ }
+
+ private static Vector2 GridSpot(Vector2 room, int i, int j) =>
+ new(MathF.Round(room.X * i / ClearSpotSteps), MathF.Round(room.Y * j / ClearSpotSteps));
+
+ /// Visible popped-out windows' rects in the game window's client px (ImGui coordinates).
+ private static List<(Vector2 Min, Vector2 Max)> PopOutRectsInClient()
+ {
+ Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen();
+ var rects = new List<(Vector2, Vector2)>();
+ foreach (var (left, top, width, height) in UI.LayeredWindow.VisibleContentRects())
+ {
+ var min = new Vector2(left, top) - origin;
+ rects.Add((min, min + new Vector2(width, height)));
+ }
+ return rects;
+ }
+
+ /// Area of the window hidden by (overlaps between covers count twice).
+ private static float CoveredArea(Vector2 pos, Vector2 size, List<(Vector2 Min, Vector2 Max)> covers)
+ {
+ Vector2 max = pos + size;
+ float total = 0;
+ foreach (var (cMin, cMax) in covers)
+ {
+ float w = MathF.Min(max.X, cMax.X) - MathF.Max(pos.X, cMin.X);
+ float h = MathF.Min(max.Y, cMax.Y) - MathF.Max(pos.Y, cMin.Y);
+ if (w > 0 && h > 0) total += w * h;
+ }
+ return total;
+ }
+
+ ///
+ /// Top-left (logical units) that centres a window of logical in the
+ /// game view; null while the display size isn't known yet.
+ ///
+ private static Vector2? CenteredLogicalPos(Vector2 size, float placeScale)
+ {
+ Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
+ if (display.X <= 1 || display.Y <= 1 || placeScale <= 0) return null;
+ return Vector2.Max(Vector2.Zero, (display / placeScale - size) * 0.5f);
}
private static Vector2 ClampToDisplay(Vector2 pos, Vector2 size)
diff --git a/src/RynthCore.Engine/ImGui/ItemDragBridge.cs b/src/RynthCore.Engine/ImGui/ItemDragBridge.cs
new file mode 100644
index 0000000..6cbd4e8
--- /dev/null
+++ b/src/RynthCore.Engine/ImGui/ItemDragBridge.cs
@@ -0,0 +1,251 @@
+// ============================================================================
+// RynthCore.Engine - ImGui/ItemDragBridge.cs
+// Carries an item drag into the MAIN ImGui context when it didn't start there,
+// so drop targets in the client (RynthAi's Mini Remote slots) can take it:
+//
+// • A popped-out Inventory: the pop-out has its own ImGui context and holds
+// mouse capture for the whole drag, so the main context never sees it.
+// The pop-out face reports the dragged item (NotePopOutDrag); the main
+// frame republishes it as an extern payload. The main context sees no
+// button press, so the payload uses PayloadAutoExpire: it is delivered to
+// the hovered target on the first frame it is no longer submitted.
+// • AC's own inventory: a press that began on the game belongs to the game,
+// and ImGui ignores hovering for it. DragDropHooks reports the item AC
+// starts dragging (OnNativeDragStart); a carried one is republished the
+// same way, under PayloadType, and delivered when ImGui sees the button go
+// up. AC does not select the dragged item, so without that hook the bridge
+// can only guess from the selection: the guess goes out under
+// NativePayloadType, which targets treat as unreliable.
+//
+// A native drag released over an ImGui window would otherwise complete in AC
+// as a drop on the 3D view (the item lands on the ground). TryRedirectNativeDrop
+// moves that button-up back to where the drag began, which AC treats as
+// putting the item back.
+//
+// Threads: AC's main thread only (game WndProc, EndScene, pop-out frames).
+// ============================================================================
+
+using System;
+using System.Diagnostics;
+using ImGuiNET;
+using RynthCore.Engine.Compatibility;
+
+namespace RynthCore.Engine.ImGuiBackend;
+
+internal static unsafe class ItemDragBridge
+{
+ /// Payload type for one item (uint object id). Must match RynthAi's MiniRemoteHud.ItemPayloadType.
+ public const string PayloadType = "RYNTH_INV_ITEM";
+
+ ///
+ /// Payload type for a game drag whose item was guessed from the selection (DragDropHooks not
+ /// installed). Any game left-drag with a carried item selected looks like this (moving an AC
+ /// panel too), so targets should take it only where a wrong item does no harm (RynthAi: empty
+ /// slots). Must match MiniRemoteHud.GameItemPayloadType.
+ ///
+ public const string NativePayloadType = "RYNTH_GAME_ITEM";
+
+ private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202;
+ private const int MK_LBUTTON = 0x0001, MK_OTHER = 0x0002 | 0x0010 | 0x0020 | 0x0040;
+ /// Movement (px, squared) before a game press counts as a drag.
+ private const int DragThresholdSq = 5 * 5;
+ /// AC may select the pressed item a few messages after the press: keep re-reading it this long.
+ private static readonly long SelectionSettleTicks = Stopwatch.Frequency / 2;
+ /// A pop-out drag with no report for this long is over (the pop-out closed mid-drag).
+ private static readonly long PopOutStaleTicks = Stopwatch.Frequency;
+
+ // Popped-out Inventory drag.
+ private static uint _popOutItem;
+ private static long _popOutSeenAt;
+
+ // Native (AC inventory) drag.
+ private static bool _pressPending;
+ private static IntPtr _pressLParam;
+ private static int _pressX, _pressY;
+ private static long _pressAt;
+ private static uint _nativeItem;
+ /// _nativeItem came from AC's drag start (DragDropHooks), not from the selection.
+ private static bool _nativeFromHook;
+ /// The left button is down on a press that belongs to the game.
+ private static bool _gamePressHeld;
+ private static bool _nativeReleased;
+ /// The cursor was over an ImGui window in the last main frame (only tracked during a native drag).
+ private static bool _overImGui;
+
+ // ── Popped-out Inventory ────────────────────────────────────────────────
+
+ /// A popped-out Inventory is dragging (call every pop-out frame of the drag).
+ public static void NotePopOutDrag(uint itemId)
+ {
+ if (itemId == 0) return;
+ if (_popOutItem != itemId)
+ RynthLog.UI($"ItemDragBridge: pop-out drag 0x{itemId:X8} published to the client.");
+ _popOutItem = itemId;
+ _popOutSeenAt = Stopwatch.GetTimestamp();
+ }
+
+ /// The popped-out Inventory's drag ended (dropped or cancelled).
+ public static void EndPopOutDrag() => _popOutItem = 0;
+
+ // ── Native drag (game WndProc) ──────────────────────────────────────────
+
+ ///
+ /// Every game-window mouse message, after the backend decided who owns the held buttons.
+ /// : the current press began on the game, not on ImGui.
+ ///
+ public static void OnGameMouse(uint msg, IntPtr wParam, IntPtr lParam, bool gameOwned)
+ {
+ int keys = (int)((long)wParam & 0xFFFF);
+ switch (msg)
+ {
+ case WM_LBUTTONDOWN:
+ // Only a plain left press that belongs to the game can be an inventory drag.
+ _pressPending = gameOwned && (keys & MK_OTHER) == 0;
+ _pressLParam = lParam;
+ _pressX = LoWord(lParam);
+ _pressY = HiWord(lParam);
+ _pressAt = Stopwatch.GetTimestamp();
+ _gamePressHeld = _pressPending;
+ if (_pressPending) { _nativeItem = 0; _nativeFromHook = false; _nativeReleased = false; }
+ break;
+
+ case WM_MOUSEMOVE:
+ if ((keys & MK_LBUTTON) == 0)
+ {
+ // A release we never saw (outside the window): finish the drag.
+ _pressPending = false;
+ _gamePressHeld = false;
+ if (_nativeItem != 0) _nativeReleased = true;
+ break;
+ }
+ if (_pressPending)
+ {
+ int dx = LoWord(lParam) - _pressX, dy = HiWord(lParam) - _pressY;
+ if (dx * dx + dy * dy >= DragThresholdSq)
+ {
+ _pressPending = false;
+ // With the drag-start hook the real item arrives through OnNativeDragStart.
+ if (_nativeItem == 0 && !DragDropHooks.IsInstalled)
+ {
+ _nativeItem = CarriedSelection();
+ if (_nativeItem != 0)
+ RynthLog.UI($"ItemDragBridge: native inventory drag 0x{_nativeItem:X8} (from the selection) published to ImGui.");
+ }
+ }
+ }
+ else if (_nativeItem != 0 && !_nativeFromHook && !_nativeReleased && Stopwatch.GetTimestamp() - _pressAt < SelectionSettleTicks)
+ {
+ // The selection can trail the press by a few messages: follow it while it settles.
+ uint sel = CarriedSelection();
+ if (sel != 0) _nativeItem = sel;
+ }
+ break;
+
+ case WM_LBUTTONUP:
+ _pressPending = false;
+ _gamePressHeld = false;
+ if (_nativeItem != 0) _nativeReleased = true;
+ break;
+ }
+ }
+
+ ///
+ /// AC started dragging (DragDropHooks, AC's main thread). Taken while
+ /// a game-owned left press is held and only for items the player carries.
+ ///
+ public static void OnNativeDragStart(uint itemId)
+ {
+ if (!_gamePressHeld || itemId == 0 || !IsCarried(itemId)) return;
+ _pressPending = false;
+ _nativeItem = itemId;
+ _nativeFromHook = true;
+ _nativeReleased = false;
+ RynthLog.UI($"ItemDragBridge: native inventory drag 0x{itemId:X8} published to ImGui.");
+ }
+
+ ///
+ /// A native item drag is being released over an ImGui window: returns the press position
+ /// to send AC instead, so AC puts the item back rather than dropping it on the ground.
+ ///
+ public static bool TryRedirectNativeDrop(uint msg, out IntPtr pressLParam)
+ {
+ pressLParam = _pressLParam;
+ if (msg != WM_LBUTTONUP || _nativeItem == 0 || !_overImGui) return false;
+ RynthLog.UI($"ItemDragBridge: native drag 0x{_nativeItem:X8} released over an ImGui window; AC gets the drop back at its start ({_pressX},{_pressY}).");
+ return true;
+ }
+
+ // ── Main frame (after ImGui.NewFrame, before any window) ────────────────
+
+ /// Republishes a pop-out or native drag in the main context for this frame.
+ public static void SubmitMainFrame(ImGuiIOPtr io)
+ {
+ uint id = 0;
+ string type = PayloadType;
+ if (_popOutItem != 0)
+ {
+ if (Stopwatch.GetTimestamp() - _popOutSeenAt > PopOutStaleTicks) _popOutItem = 0;
+ else id = _popOutItem;
+ }
+
+ if (id == 0 && _nativeItem != 0)
+ {
+ type = _nativeFromHook ? PayloadType : NativePayloadType;
+ // After the button-up, stop once ImGui itself sees the button up: that frame
+ // delivers the drop (the payload outlives its last submission by one frame).
+ if (_nativeReleased && !io.MouseDown[0])
+ {
+ _nativeItem = 0;
+ _nativeFromHook = false;
+ _nativeReleased = false;
+ _overImGui = false;
+ return;
+ }
+ id = _nativeItem;
+ _overImGui = ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
+ }
+
+ if (id == 0) return;
+ const ImGuiDragDropFlags flags = ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip
+ | ImGuiDragDropFlags.PayloadAutoExpire;
+ if (ImGuiNET.ImGui.BeginDragDropSource(flags))
+ {
+ ImGuiNET.ImGui.SetDragDropPayload(type, (IntPtr)(&id), sizeof(uint));
+ ImGuiNET.ImGui.EndDragDropSource();
+ }
+ }
+
+ /// Forget every drag (focus lost, logout, engine shutdown).
+ public static void Reset()
+ {
+ _popOutItem = 0;
+ _pressPending = false;
+ _gamePressHeld = false;
+ _nativeItem = 0;
+ _nativeFromHook = false;
+ _nativeReleased = false;
+ _overImGui = false;
+ }
+
+ /// The game's selected object when the player carries it, else 0.
+ private static uint CarriedSelection()
+ {
+ uint id = ClientHelperHooks.GetSelectedItemId();
+ return IsCarried(id) ? id : 0;
+ }
+
+ /// is in the player's pack, a side pack, or worn.
+ private static bool IsCarried(uint id)
+ {
+ if (id == 0 || !ClientHelperHooks.HasGetPlayerId) return false;
+ uint player = ClientHelperHooks.GetPlayerId();
+ if (player == 0 || id == player) return false;
+ if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) return false;
+ if (wielder == player || container == player) return true;
+ // Side pack in the main pack.
+ return container != 0 && ClientObjectHooks.TryGetObjectOwnershipInfo(container, out uint outer, out _, out _) && outer == player;
+ }
+
+ private static int LoWord(IntPtr l) => unchecked((short)((long)l & 0xFFFF));
+ private static int HiWord(IntPtr l) => unchecked((short)(((long)l >> 16) & 0xFFFF));
+}
diff --git a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs
index 42b1e9f..558e47b 100644
--- a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs
+++ b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs
@@ -44,7 +44,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
{
DungeonMapSettingsStore.Load(); // engine init thread: the file read stays off AC's thread
ImGuiPanelHost.Register(Title,
- new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true),
+ new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true, OpenCentered: true),
() => new DungeonMapFace());
}
diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs
index 807801e..ab31f00 100644
--- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs
+++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs
@@ -620,7 +620,7 @@ internal sealed partial class InventoryFace
_hover = it;
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
- _selected = it.Id;
+ SelectItem(it);
_pressItem = it;
_pressAt = ImGuiNET.ImGui.GetMousePos();
}
diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs
index 296dbe0..2c1b9f8 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;
+ ItemDragBridge.EndPopOutDrag();
UiDropTargets.EngineDragObject = 0;
_lootAdd.Cancel();
}
@@ -477,7 +478,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
- _selected = hot.Id;
+ SelectItem(hot);
_pressItem = hot;
_pressAt = mouse;
}
@@ -751,6 +752,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
_dragItem = null;
_pressItem = null;
if (item == null) return;
+ ItemDragBridge.EndPopOutDrag();
Vector2 m = ImGuiNET.ImGui.GetMousePos();
foreach (Target t in _targets)
{
@@ -765,13 +767,50 @@ internal sealed partial class InventoryFace : IImGuiPanel
}
}
- private void DrawDragGhost()
+ ///
+ /// ImGui drag-and-drop payload type for one item (uint object id), published while an item is
+ /// dragged so other ImGui windows (RynthAi's Mini Remote slots) can accept the drop. Must
+ /// match MiniRemoteHud.ItemPayloadType in RynthAi.
+ ///
+ public const string ItemPayloadType = "RYNTH_INV_ITEM";
+
+ ///
+ /// Selects here and in the game, like a click in the retail inventory, so
+ /// "selected item" features (Mini Remote slots, item info, loot rules) see it too.
+ ///
+ private void SelectItem(InventoryItem it)
+ {
+ _selected = it.Id;
+ // Queued, not called inline: Draw runs inside EndScene, and AC's SetSelectedObject rebuilds
+ // UI elements, so it runs at the main-thread queue's drain point instead.
+ if (ClientHelperHooks.GetSelectedItemId() != it.Id)
+ AcMainThreadQueue.EnqueueSetSelectedObject(it.Id);
+ }
+
+ private unsafe void DrawDragGhost()
{
if (_dragItem == null) return;
var fg = ImGuiNET.ImGui.GetForegroundDrawList();
Vector2 m = ImGuiNET.ImGui.GetMousePos() - new Vector2(Icon * 0.5f, Icon * 0.5f);
DrawItemIcon(fg, _dragItem.Id, m, Icon, 0xD0FFFFFF);
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
+
+ // A popped-out Inventory draws in its own ImGui context: the client's drop targets
+ // only see the drag through the bridge, which republishes it in the main context.
+ if (ImGuiPopOuts.InPopOutFrame)
+ {
+ ItemDragBridge.NotePopOutDrag(_dragItem.Id);
+ return;
+ }
+
+ // Re-submitted every frame of the drag (an extern source expires when it isn't); the
+ // ghost above is the preview, so no ImGui tooltip.
+ if (ImGuiNET.ImGui.BeginDragDropSource(ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip))
+ {
+ uint id = _dragItem.Id;
+ ImGuiNET.ImGui.SetDragDropPayload(ItemPayloadType, (IntPtr)(&id), sizeof(uint));
+ ImGuiNET.ImGui.EndDragDropSource();
+ }
}
// ── Tooltip ─────────────────────────────────────────────────────────
@@ -898,6 +937,11 @@ internal sealed partial class InventoryFace : IImGuiPanel
_lootAdd.Open(it.Id, it.Name, toOpenProfile: false);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Make a RynthAi loot rule for this item (preview first)");
+ if (!it.IsPack && ImGuiNET.ImGui.MenuItem("Add to item count HUD"))
+ UI.Data.RynthAiCommands.ApplyRemoteCommand("itemhudadd", it.Name);
+ if (ImGuiNET.ImGui.IsItemHovered())
+ ImGuiNET.ImGui.SetTooltip("Track how many of these you carry on RynthAi's floating item count HUD (/ra itemhud add)");
+ if (!it.IsPack) MiniRemoteMenu(it);
if (!idle)
ImGuiNET.ImGui.TextDisabled("(an item action is waiting)");
}
@@ -908,6 +952,36 @@ internal sealed partial class InventoryFace : IImGuiPanel
}
}
+ /// RynthAi Mini Remote quick-use grid size (HudState.MiniRemoteSlotCount, 6 rows of 5).
+ private const int MiniRemoteSlots = 30, MiniRemoteColumns = 5;
+
+ ///
+ /// "Add to Mini Remote" submenu: first empty slot, or a numbered grid laid out like the
+ /// remote's own slots. RynthAi validates the item and reports the result in chat.
+ ///
+ private static void MiniRemoteMenu(InventoryItem it)
+ {
+ if (!ImGuiNET.ImGui.BeginMenu("Add to Mini Remote")) return;
+ if (ImGuiNET.ImGui.MenuItem("First empty slot"))
+ UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot", "first " + it.Id.ToString(CultureInfo.InvariantCulture));
+ ImGuiNET.ImGui.Separator();
+ ImGuiNET.ImGui.TextDisabled("Or pick a slot (replaces what's there):");
+ for (int i = 0; i < MiniRemoteSlots; i++)
+ {
+ if (i % MiniRemoteColumns != 0) ImGuiNET.ImGui.SameLine();
+ string label = (i + 1).ToString("00", CultureInfo.InvariantCulture);
+ if (ImGuiNET.ImGui.Button(label, new Vector2(28, 0)))
+ {
+ UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot",
+ (i + 1).ToString(CultureInfo.InvariantCulture) + " " + it.Id.ToString(CultureInfo.InvariantCulture));
+ ImGuiNET.ImGui.CloseCurrentPopup();
+ }
+ }
+ ImGuiNET.ImGui.Separator();
+ ImGuiNET.ImGui.TextDisabled("Tip: you can also drag the item onto a slot.");
+ ImGuiNET.ImGui.EndMenu();
+ }
+
// ── Split dialog ────────────────────────────────────────────────────
private void SplitDialog(InventoryView view)
diff --git a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs
index baa21e6..36d4235 100644
--- a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs
+++ b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs
@@ -1,21 +1,28 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/NavFace.cs
// ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status,
-// Start/Stop, route type and insert mode, Add Waypoint / Portal (not yet) /
-// Recall / Clear / Save / Dungeon Patrol, a chat waypoint, Save As, the nav
-// file picker, the nav point reach (RynthAi's FollowNavMin, the same row as
-// Settings > Navigation), and the waypoint list (click selects the insert
-// point, X deletes, => marks the active one).
+// Start/Stop, route type and insert mode, the Breadcrumbs and Route overlay
+// toggles, Add Waypoint / Portal (selected object) /
+// Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate /
+// delete / set active / move here on the selection; nearest, reverse, snap to
+// path, point at selection, pause, simplify; recording and trail -> route),
+// a chat waypoint, Save As, the nav file picker, the nav point reach
+// (RynthAi's FollowNavMin, the same row as Settings > Navigation), and the
+// waypoint list (click selects, Ctrl/Shift-click multi-selects, double-click
+// sets active, right-click edits, X or Delete deletes, => marks the active one).
//
// Data: UiSources.Nav (hub) and NavCommands. Button actions change a private
// copy at once; the plugin applies commands immediately, so the next
-// snapshot (requested right after) replaces the copy. The reach row reads
-// UiSources.Settings and saves through SettingsCommands, like the Settings face.
+// snapshot (requested right after) replaces the copy. Edits send indices into
+// the route this face shows, so the selection is remapped locally as the copy
+// changes. The reach row reads UiSources.Settings and saves through
+// SettingsCommands, like the Settings face.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
+using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
@@ -28,7 +35,7 @@ internal sealed class NavFace : IImGuiPanel
public const string Title = "Nav";
public static void Register() => ImGuiPanelHost.Register(Title,
- new PanelSpec(new Vector2(400, 560), new Vector2(360, 380), EdgeToEdge: true),
+ new PanelSpec(new Vector2(400, 680), new Vector2(360, 440), EdgeToEdge: true),
() => new NavFace());
private static readonly string[] Actions =
@@ -38,12 +45,30 @@ internal sealed class NavFace : IImGuiPanel
};
private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation";
private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As";
- private static readonly bool[] ActionsEnabled = { true, false, true, true, true, true };
+
+ // Route editor rows. Edit acts on the selected waypoints; Tools on the route.
+ private static readonly string[] EditActions =
+ {
+ PhosphorIcons.ArrowUp + " Up", PhosphorIcons.ArrowDown + " Down", PhosphorIcons.Copy + " Duplicate",
+ PhosphorIcons.Trash + " Delete", PhosphorIcons.Target + " Set Active", PhosphorIcons.Crosshair + " Move Here",
+ };
+ private static readonly string[] ToolActions =
+ {
+ PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path",
+ PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify",
+ };
+ private static readonly string[] RowMenu =
+ { "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" };
+ private const string FromTrail = PhosphorIcons.Footprints + " Route from Trail...";
+ private readonly bool[] _editEnabled = new bool[6];
private NavPayload _data = new();
private long _seenVersion = -1;
private readonly List _pointText = new();
- private int _selected = -1, _addMode;
+ // _selected is the focus row (insert point, chat editing); _multi is every selected row,
+ // always containing _selected when it is set. _anchor starts Shift-click ranges.
+ private int _selected = -1, _anchor = -1, _addMode;
+ private readonly HashSet _multi = new();
private bool _typing;
private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)";
private string _fileLabel = "Select nav file...";
@@ -130,13 +155,32 @@ internal sealed class NavFace : IImGuiPanel
});
NextLine(p, 26);
+ // Breadcrumbs | Route overlay (RynthAi's NavOverlaySettings; saved per character)
+ p = ImGuiNET.ImGui.GetCursorScreenPos();
+ if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half,
+ "Record the trail you walk and draw it on the ground (/ra navtrail on|off).\nTurning it off hides the trail; /ra navtrail clear wipes it."))
+ {
+ bool on = !_data.TrackBreadcrumbs;
+ NavCommands.Send(new NavCmd { Cmd = "setBreadcrumbs", On = on });
+ _data.TrackBreadcrumbs = on;
+ }
+ if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half,
+ "Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\nto the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate."))
+ {
+ bool on = !_data.ShowRouteOverlay;
+ NavCommands.Send(new NavCmd { Cmd = "setRouteOverlay", On = on });
+ _data.ShowRouteOverlay = on;
+ }
+ NextLine(p, 26);
+
typing |= ReachRow(w);
// Actions
- int action = WrapButtons("nav_act", Actions, w, 24, ActionsEnabled);
+ int action = WrapButtons("nav_act", Actions, w, 24);
switch (action)
{
case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break;
+ case 1: NavCommands.Send(new NavCmd { Cmd = "addPortal", AddMode = _addMode, InsertAt = _selected }); break;
case 2:
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected }));
@@ -144,13 +188,15 @@ internal sealed class NavFace : IImGuiPanel
case 3:
NavCommands.Send(new NavCmd { Cmd = "clearRoute" });
_data.Points.Clear();
- _selected = -1;
+ ClearSelection();
RebuildPointText();
break;
case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break;
case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break;
}
+ RouteEditor(w);
+
// Chat waypoint: sent as if typed when the route reaches it. Selecting an
// existing chat waypoint loads its command here; Update saves the edit.
bool chatSelected = _selected >= 0 && _selected < _data.Points.Count
@@ -230,6 +276,9 @@ internal sealed class NavFace : IImGuiPanel
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH));
Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X);
+ if (!typing && _multi.Count > 0 && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Delete, false)
+ && (ImGuiNET.ImGui.IsWindowHovered() || ImGuiNET.ImGui.IsWindowFocused()))
+ DeleteSelected();
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
@@ -239,6 +288,18 @@ internal sealed class NavFace : IImGuiPanel
_picker.Draw();
}
+ ///
+ /// A checkbox-style toggle button: ticked box and teal text when on, empty box and muted
+ /// text when off. Returns true when clicked (the caller flips the value).
+ ///
+ private static bool OverlayToggle(string id, string label, bool on, Vector2 pos, float width, string tooltip)
+ {
+ string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label;
+ bool clicked = Button(id, text, pos, new Vector2(width, 22), on ? Teal : Mute, BtnFill, leftAlign: true);
+ if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tooltip);
+ return clicked;
+ }
+
///
/// Nav point reach (yd): how close nav gets to each nav point before moving on. Label,
/// [-] value [+]; the typed value commits on Enter or when the box loses focus. Saves the
@@ -303,20 +364,24 @@ internal sealed class NavFace : IImGuiPanel
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float h = 22;
if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; }
- bool active = i == _data.ActiveNavIndex, selected = i == _selected;
+ bool active = i == _data.ActiveNavIndex, selected = _multi.Contains(i);
ImGuiNET.ImGui.PushID(i);
// Row click selects (drawn first so the X button on top wins).
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks
- if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) _selected = i;
+ if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) ClickRow(i);
+ if (ImGuiNET.ImGui.IsItemHovered() && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
+ SetActive(i);
+ if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
+ {
+ if (!selected) SelectOnly(i);
+ _picker.Open(ImGuiNET.ImGui.GetIO().MousePos, RowMenu, -1, RowMenuPick, width: 140);
+ }
dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt);
if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11))
{
NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i });
- if (_selected == i) _selected = -1;
- else if (_selected > i) _selected--;
- _data.Points.RemoveAt(i);
- RebuildPointText();
+ RemoveLocal(new HashSet { i });
ImGuiNET.ImGui.PopID();
return;
}
@@ -331,6 +396,216 @@ internal sealed class NavFace : IImGuiPanel
}
}
+ ///
+ /// Route editor: Edit row (on the selection), Tools row (on the route), the Record toggle
+ /// with "Route from Trail...", and the last edit's result. Picker-backed buttons (pause,
+ /// simplify, trail) double as the confirmation for edits that can't be undone.
+ ///
+ private void RouteEditor(float w)
+ {
+ int n = _multi.Count, count = _data.Points.Count;
+ bool one = n == 1 && _selected >= 0;
+ _editEnabled[0] = n > 0 && _multi.Min() > 0;
+ _editEnabled[1] = n > 0 && _multi.Max() < count - 1;
+ _editEnabled[2] = _editEnabled[3] = n > 0;
+ _editEnabled[4] = _editEnabled[5] = one;
+ Label(n > 1 ? $"Edit ({n} selected)" : "Edit", Mute);
+ switch (WrapButtons("nav_edit", EditActions, w, 22, _editEnabled))
+ {
+ case 0: MoveSelected(-1); break;
+ case 1: MoveSelected(+1); break;
+ case 2: DuplicateSelected(); break;
+ case 3: DeleteSelected(); break;
+ case 4: SetActive(_selected); break;
+ case 5: NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
+ }
+
+ Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
+ switch (WrapButtons("nav_tools", ToolActions, w, 22))
+ {
+ case 0: NavCommands.Send(new NavCmd { Cmd = "nearestActive" }); break;
+ case 1:
+ if (count < 2) break;
+ NavCommands.Send(new NavCmd { Cmd = "reverseRoute" });
+ ReverseLocal();
+ break;
+ case 2: NavCommands.Send(new NavCmd { Cmd = "snapToPath" }); break;
+ case 3: NavCommands.Send(new NavCmd { Cmd = "addPointAtSelected", AddMode = _addMode, InsertAt = _selected }); break;
+ case 4:
+ _picker.Open(at, NavCommands.PauseLabels, -1, i => NavCommands.Send(new NavCmd
+ { Cmd = "addPause", Seconds = NavCommands.PauseSeconds[i], AddMode = _addMode, InsertAt = _selected }), width: 140);
+ break;
+ case 5:
+ _picker.Open(at, NavCommands.SimplifyLabels, -1, i =>
+ NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300);
+ break;
+ }
+
+ // Record | Route from Trail...
+ Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
+ float half = (w - 4) / 2;
+ if (OverlayToggle("##record", "Record route", _data.IsRecording, p, half,
+ "Add a point every few yards as you walk, and portal steps as you use portals\n(/ra navrec on|off). Points go into the current route."))
+ {
+ bool on = !_data.IsRecording;
+ NavCommands.Send(new NavCmd { Cmd = "setRecording", On = on });
+ _data.IsRecording = on;
+ }
+ Vector2 tp = new(p.X + half + 4, p.Y);
+ if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2))
+ _picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i =>
+ NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300);
+ if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
+ ImGuiNET.ImGui.SetTooltip(_data.TrailPoints >= 2
+ ? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed."
+ : "Turn on Breadcrumbs and walk a while to build a trail.");
+ NextLine(p, 26);
+
+ if (_data.EditStatus.Length > 0) Label(_data.EditStatus, Amber);
+ }
+
+ /// Plain click selects one row, Ctrl toggles a row, Shift selects from the anchor.
+ private void ClickRow(int i)
+ {
+ var io = ImGuiNET.ImGui.GetIO();
+ if (io.KeyShift && _anchor >= 0)
+ {
+ if (!io.KeyCtrl) _multi.Clear();
+ for (int k = Math.Min(_anchor, i); k <= Math.Max(_anchor, i); k++) _multi.Add(k);
+ _selected = i;
+ }
+ else if (io.KeyCtrl)
+ {
+ if (!_multi.Remove(i)) { _multi.Add(i); _selected = i; }
+ else if (_selected == i) _selected = _multi.Count > 0 ? _multi.Min() : -1;
+ _anchor = i;
+ }
+ else SelectOnly(i);
+ }
+
+ private void SelectOnly(int i)
+ {
+ _multi.Clear();
+ _multi.Add(i);
+ _selected = _anchor = i;
+ }
+
+ private void ClearSelection()
+ {
+ _multi.Clear();
+ _selected = _anchor = -1;
+ }
+
+ private List SelectedIndices()
+ {
+ var list = new List(_multi);
+ list.Sort();
+ return list;
+ }
+
+ private void RowMenuPick(int item)
+ {
+ switch (item)
+ {
+ case 0: if (_selected >= 0) SetActive(_selected); break;
+ case 1: if (_selected >= 0) NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
+ case 2: MoveSelected(-1); break;
+ case 3: MoveSelected(+1); break;
+ case 4: DuplicateSelected(); break;
+ case 5: DeleteSelected(); break;
+ }
+ }
+
+ private void SetActive(int i)
+ {
+ if (i < 0 || i >= _data.Points.Count) return;
+ NavCommands.Send(new NavCmd { Cmd = "setActive", Index = i });
+ _data.ActiveNavIndex = i;
+ }
+
+ /// Moves the selected rows one slot, the way the plugin does (NavRouteEditing.Move).
+ private void MoveSelected(int delta)
+ {
+ if (_multi.Count == 0) return;
+ NavCommands.Send(new NavCmd { Cmd = "movePoints", Indices = SelectedIndices(), Delta = delta });
+ var pts = _data.Points;
+ var sel = new HashSet();
+ foreach (int i in _multi) sel.Add(pts[i]);
+ NavPoint? focus = _selected >= 0 ? pts[_selected] : null, anchor = _anchor >= 0 && _anchor < pts.Count ? pts[_anchor] : null;
+ if (delta < 0)
+ {
+ for (int i = 1; i < pts.Count; i++)
+ if (sel.Contains(pts[i]) && !sel.Contains(pts[i - 1])) (pts[i - 1], pts[i]) = (pts[i], pts[i - 1]);
+ }
+ else
+ {
+ for (int i = pts.Count - 2; i >= 0; i--)
+ if (sel.Contains(pts[i]) && !sel.Contains(pts[i + 1])) (pts[i + 1], pts[i]) = (pts[i], pts[i + 1]);
+ }
+ _multi.Clear();
+ for (int i = 0; i < pts.Count; i++) if (sel.Contains(pts[i])) _multi.Add(i);
+ _selected = focus != null ? pts.IndexOf(focus) : -1;
+ _anchor = anchor != null ? pts.IndexOf(anchor) : _selected;
+ RebuildPointText();
+ }
+
+ /// Each selected row gets a copy right after it (as the plugin does); the copies end up selected.
+ private void DuplicateSelected()
+ {
+ if (_multi.Count == 0) return;
+ NavCommands.Send(new NavCmd { Cmd = "duplicatePoints", Indices = SelectedIndices() });
+ var result = new List(_data.Points.Count + _multi.Count);
+ var copies = new HashSet();
+ for (int i = 0; i < _data.Points.Count; i++)
+ {
+ NavPoint pt = _data.Points[i];
+ result.Add(pt);
+ if (!_multi.Contains(i)) continue;
+ copies.Add(result.Count);
+ result.Add(new NavPoint { Type = pt.Type, Desc = pt.Desc, Text = pt.Text, NS = pt.NS, EW = pt.EW, Z = pt.Z });
+ }
+ _data.Points = result;
+ _multi.Clear();
+ _multi.UnionWith(copies);
+ _selected = _anchor = _multi.Count > 0 ? _multi.Min() : -1;
+ RebuildPointText();
+ }
+
+ private void DeleteSelected()
+ {
+ if (_multi.Count == 0) return;
+ NavCommands.Send(new NavCmd { Cmd = "deletePoints", Indices = SelectedIndices() });
+ RemoveLocal(new HashSet(_multi));
+ }
+
+ /// Drops rows from the local copy and shifts the selection past them.
+ private void RemoveLocal(HashSet removed)
+ {
+ int Shift(int i) { int s = 0; foreach (int r in removed) if (r < i) s++; return i - s; }
+ var keep = new List();
+ foreach (int i in _multi) if (!removed.Contains(i)) keep.Add(Shift(i));
+ _selected = _selected >= 0 && !removed.Contains(_selected) ? Shift(_selected) : -1;
+ _anchor = _anchor >= 0 && !removed.Contains(_anchor) ? Shift(_anchor) : _selected;
+ _multi.Clear();
+ _multi.UnionWith(keep);
+ if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
+ for (int i = _data.Points.Count - 1; i >= 0; i--) if (removed.Contains(i)) _data.Points.RemoveAt(i);
+ RebuildPointText();
+ }
+
+ private void ReverseLocal()
+ {
+ int last = _data.Points.Count - 1;
+ _data.Points.Reverse();
+ var flipped = new List();
+ foreach (int i in _multi) flipped.Add(last - i);
+ _multi.Clear();
+ _multi.UnionWith(flipped);
+ if (_selected >= 0) _selected = last - _selected;
+ if (_anchor >= 0) _anchor = last - _anchor;
+ RebuildPointText();
+ }
+
private void TakeSnapshot()
{
var snap = UiSources.Nav.Current;
@@ -338,7 +613,11 @@ internal sealed class NavFace : IImGuiPanel
_seenVersion = snap.Version;
_data = snap.Value.Clone();
_navFiles = _data.NavFiles.ToArray();
- if (_selected >= _data.Points.Count) _selected = -1;
+ int count = _data.Points.Count;
+ _multi.RemoveWhere(i => i >= count);
+ if (_selected >= count) _selected = -1;
+ if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
+ if (_anchor >= count) _anchor = _selected;
RebuildPointText();
UpdateLabels();
}
diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs
index 50c90a6..472c111 100644
--- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs
+++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs
@@ -145,6 +145,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
}
Bars(view, raw, x0, width, boxBg);
PatrolPopup();
+ CharMenu();
MeasureAndFit(start.Y);
// Last: a window of its own, placed against this one's rect (hidden popped out).
_drawers.Draw();
@@ -477,7 +478,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
private void Launchers(float x0, float width)
{
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
- const int buttons = 8;
+ const int buttons = 10;
float bw = MathF.Floor((width - buttons * LauncherGap) / buttons);
// Short labels only when every button has room for its icon and label.
bool labels = bw >= 68;
@@ -516,6 +517,25 @@ internal sealed partial class RynthAiFace : IImGuiPanel
}
else _drawers.Toggle(_patrol);
}
+ x += bw + LauncherGap;
+
+ // Char and Hub open RynthAi's own ImGui overlay windows (Mini Remote, which is the ILT
+ // Hub, its section windows, Inventory HUDs). They draw only when the engine hands plugins
+ // its ImGui context.
+ Launcher("##l_char", PhosphorIcons.User, "Char",
+ "Char. Left-click: ILT Hub / Mini Remote (/ra hub show). Right-click: Hub windows, Progression (Skills panel).",
+ x, y, bw, labels, () => RynthAiCommands.ApplyRemoteCommand("hub", "show"));
+ if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
+ {
+ ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1));
+ ImGuiNET.ImGui.OpenPopup("##charmenu");
+ }
+ x += bw + LauncherGap;
+ Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub",
+ "Hub. Left-click: Mini Remote (/ra remote). Right-click: Inventory HUDs setup (/ra huds).",
+ x, y, bw, labels, () => RynthAiCommands.ApplyRemoteCommand("remote", "toggle"));
+ if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
+ RynthAiCommands.ApplyRemoteCommand("huds", "show");
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH));
}
@@ -708,6 +728,46 @@ internal sealed partial class RynthAiFace : IImGuiPanel
dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? "");
}
+ // ── Char menu (right-click Char): RynthAi's character windows ──────────
+
+ /// ILT Hub section windows: menu label and the "/ra hub open" section name RynthAi parses.
+ private static readonly (string Label, string Section)[] HubSections =
+ {
+ ("Character", "character"), ("Quests", "quests"), ("Pets", "pets"),
+ ("Banking", "banking"), ("Gear", "gear"), ("Games", "games"), ("Guardian", "guardian"),
+ };
+
+ private static void CharMenu()
+ {
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
+ ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
+ bool open = ImGuiNET.ImGui.BeginPopup("##charmenu");
+ ImGuiNET.ImGui.PopStyleVar();
+ ImGuiNET.ImGui.PopStyleColor(2);
+ if (!open) return;
+ try
+ {
+ // The Mini Remote is the ILT Hub; each former Hub tab is its own window (toggled).
+ if (ImGuiNET.ImGui.MenuItem("Mini Remote (ILT Hub)", "/ra hub"))
+ RynthAiCommands.ApplyRemoteCommand("hub", "toggle");
+ ImGuiNET.ImGui.Separator();
+ foreach ((string label, string section) in HubSections)
+ {
+ if (ImGuiNET.ImGui.MenuItem(label, "/ra hub open " + section))
+ RynthAiCommands.ApplyRemoteCommand("hub", "open " + section + " toggle");
+ }
+ ImGuiNET.ImGui.Separator();
+ if (ImGuiNET.ImGui.MenuItem("Progression (Skills panel)"))
+ SkillsFace.ShowProgression();
+ ImGuiNET.ImGui.SetItemTooltip("XP planner, augmentations and enlightenment (ILT worlds)");
+ }
+ finally
+ {
+ ImGuiNET.ImGui.EndPopup();
+ }
+ }
+
// ── Patrol popup (right-click Patrol, popped out; docked it's the Patrol drawer) ──
private void PatrolPopup()
diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs
index bdf3135..de18c2d 100644
--- a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs
+++ b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs
@@ -53,14 +53,27 @@ internal sealed class SettingsFace : IImGuiPanel
public bool Active; // the box had keyboard focus last frame
}
private readonly Dictionary _edits = new();
+ // Text rows being typed in (the saved value shows again once the box loses focus).
+ private readonly Dictionary _textEdits = new();
+
+ /// Extra sidebar tab after the schema tabs; drawn from UiSources.Charms, not settings rows.
+ private const string CharmsTabName = "Charms Tracking";
+ private static int CharmsTab => SettingsSchema.Tabs.Length;
+ private const string CharmsHeader = "Advanced Settings > " + CharmsTabName;
public void OnShown()
{
UiSources.Settings.Subscribe();
UiSources.Settings.RequestRefresh();
+ UiSources.Charms.Subscribe();
+ UiSources.Charms.RequestRefresh();
}
- public void OnHidden() => UiSources.Settings.Unsubscribe();
+ public void OnHidden()
+ {
+ UiSources.Settings.Unsubscribe();
+ UiSources.Charms.Unsubscribe();
+ }
public void Draw()
{
@@ -100,9 +113,9 @@ internal sealed class SettingsFace : IImGuiPanel
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
SettingsTab[] tabs = SettingsSchema.Tabs;
- for (int i = 0; i < tabs.Length; i++)
+ for (int i = 0; i <= tabs.Length; i++)
{
- string tabName = tabs[i].Name;
+ string tabName = i < tabs.Length ? tabs[i].Name : CharmsTabName;
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.PushID(i);
@@ -133,14 +146,23 @@ internal sealed class SettingsFace : IImGuiPanel
float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
- if (_tab >= SettingsSchema.Tabs.Length) _tab = 0;
- ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Headers[_tab]);
+ if (_tab > CharmsTab) _tab = 0;
+ bool charms = _tab == CharmsTab;
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), charms ? CharmsHeader : Headers[_tab]);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos();
dl.AddLine(lp, lp + new Vector2(w, 0), BtnBord);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
+ if (charms)
+ {
+ CharmsTabContent(w);
+ ImGuiNET.ImGui.PopStyleVar();
+ ImGuiNET.ImGui.EndChild();
+ return;
+ }
+
SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows;
for (int i = 0; i < rows.Length; i++)
{
@@ -168,9 +190,132 @@ internal sealed class SettingsFace : IImGuiPanel
case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break;
case SettingKind.Note: Note(row.Label, w); break;
case SettingKind.CraftingStatus: CraftingStatus(row); break;
+ case SettingKind.Button: ButtonRow(row, w); break;
+ case SettingKind.TraceCategories: TraceCategoriesRow(row, w); break;
+ case SettingKind.Text: TextRow(row, w); break;
+ case SettingKind.Status: StatusRow(row, w); break;
}
}
+ // [All on] [All off] [ILT Hub on], then a 3-column grid of square toggles, one per
+ // RynthAi trace category. Edits the copy's DiagCategories and saves like any other row.
+ private void TraceCategoriesRow(SettingRow row, float w)
+ {
+ var cats = TraceCategoryLevels.Parse(_data.DiagCategories);
+ if (cats.Count == 0)
+ {
+ Note("Waiting for RynthAi...", w);
+ return;
+ }
+
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
+ if (ImGuiNET.ImGui.Button("All on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true));
+ ImGuiNET.ImGui.SameLine(0, 6);
+ if (ImGuiNET.ImGui.Button("All off")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", false));
+ ImGuiNET.ImGui.SameLine(0, 6);
+ if (ImGuiNET.ImGui.Button("ILT Hub on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true, "Ilt"));
+ Tooltip(row);
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
+
+ var dl = ImGuiNET.ImGui.GetWindowDrawList();
+ float colW = Math.Max(80f, w / 3f);
+ int perRow = Math.Max(1, (int)(w / colW));
+ Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
+ for (int i = 0; i < cats.Count; i++)
+ {
+ var (name, level) = cats[i];
+ bool on = level != TraceCategoryLevels.Off;
+ string label = TraceCategoryLevels.Label(name, level);
+ var p = start + new Vector2(i % perRow * colW, i / perRow * 18f);
+ ImGuiNET.ImGui.SetCursorScreenPos(p);
+ ImGuiNET.ImGui.PushID(name);
+ if (ImGuiNET.ImGui.InvisibleButton("##cat", new Vector2(colW - 4, 16)))
+ SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, name, !on));
+ if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
+ ImGuiNET.ImGui.PopID();
+ dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2);
+ dl.PushClipRect(p, p + new Vector2(colW - 4, 16), true);
+ dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label);
+ dl.PopClipRect();
+ }
+ int rowsUsed = (cats.Count + perRow - 1) / perRow;
+ ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, rowsUsed * 18f));
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
+ }
+
+ private void SaveCategories(string levels)
+ {
+ _data.DiagCategories = levels;
+ SettingsCommands.Save(_data.Clone());
+ }
+
+ // Label, then a full-width box; the value commits on Enter or focus loss (like the number boxes).
+ private void TextRow(SettingRow row, float w)
+ {
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
+ ImGuiNET.ImGui.TextUnformatted(row.Label);
+ ImGuiNET.ImGui.PopStyleColor();
+ Tooltip(row);
+
+ string saved = row.GetText?.Invoke(_data) ?? string.Empty;
+ string text = _textEdits.TryGetValue(row, out string? typing) ? typing : saved;
+ ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 4));
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
+ ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
+ ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f);
+ bool enter = ImGuiNET.ImGui.InputTextWithHint("##text", row.Hint ?? string.Empty, ref text, 512u,
+ ImGuiInputTextFlags.EnterReturnsTrue);
+ bool active = ImGuiNET.ImGui.IsItemActive();
+ bool committed = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
+ ImGuiNET.ImGui.PopStyleVar(2);
+ ImGuiNET.ImGui.PopStyleColor(3);
+ Tooltip(row);
+ _editing |= active;
+
+ if (committed)
+ {
+ _textEdits.Remove(row);
+ if (!string.Equals(text, saved, StringComparison.Ordinal))
+ {
+ row.SetText?.Invoke(_data, text);
+ SettingsCommands.Save(_data.Clone());
+ }
+ }
+ else if (active) _textEdits[row] = text;
+ else _textEdits.Remove(row);
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
+ }
+
+ // RynthAi's one-line status (teal), wrapped to the column.
+ private void StatusRow(SettingRow row, float w)
+ {
+ string text = row.GetText?.Invoke(_data) ?? string.Empty;
+ if (text.Length == 0) return;
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal);
+ ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
+ ImGuiNET.ImGui.TextUnformatted(text);
+ ImGuiNET.ImGui.PopTextWrapPos();
+ ImGuiNET.ImGui.PopStyleColor();
+ }
+
+ // Label | [caption]; Click posts its own work (never runs plugin code on AC's thread).
+ private static void ButtonRow(SettingRow row, float w)
+ {
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
+ ImGuiNET.ImGui.AlignTextToFramePadding();
+ ImGuiNET.ImGui.TextUnformatted(row.Label);
+ ImGuiNET.ImGui.PopStyleColor();
+ ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f));
+ if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label))
+ row.Click?.Invoke();
+ Tooltip(row);
+ }
+
private void Changed(SettingRow row, double value)
{
row.Set!(_data, value);
@@ -382,6 +527,130 @@ internal sealed class SettingsFace : IImGuiPanel
}
}
+ // ── Charms Tracking tab ───────────────────────────────────────────────
+
+ private static readonly uint CharmOn = C(0xFF33FF33), CharmDisabled = C(0xFFFF5555);
+
+ /// Summary line, one table row per ACECustom registry charm, then how each column is known.
+ private static void CharmsTabContent(float w)
+ {
+ var snap = UiSources.Charms.Current;
+ if (snap == null)
+ {
+ Note("Waiting for RynthAi...", w);
+ return;
+ }
+ CharmsInfo info = snap.Value;
+ if (!info.Available)
+ {
+ Note("Charm tracking is for ILT (Infinite Leaftide / ACECustom) worlds."
+ + (info.World.Length > 0 ? " Current world: " + info.World + "." : ""), w);
+ Note("Use /ra hub force on to treat this world as ILT.", w);
+ return;
+ }
+
+ ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333),
+ $"{info.AcquiredCount} of {info.Total} acquired | {info.ActiveCount} active");
+ ImGuiNET.ImGui.PopFont();
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
+
+ ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.CellPadding, new Vector2(4, 3));
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableRowBg, PanelBg);
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableRowBgAlt, ShellBg);
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableHeaderBg, TabActive);
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableBorderLight, BtnBord);
+ const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit;
+ if (ImGuiNET.ImGui.BeginTable("##charms", 5, flags, new Vector2(w, 0)))
+ {
+ ImGuiNET.ImGui.TableSetupColumn("Charm", ImGuiTableColumnFlags.WidthStretch);
+ ImGuiNET.ImGui.TableSetupColumn("Acquired", ImGuiTableColumnFlags.WidthFixed, 70);
+ ImGuiNET.ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.WidthFixed, 44);
+ ImGuiNET.ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 32);
+ ImGuiNET.ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthFixed, 56);
+ ImGuiNET.ImGui.TableHeadersRow();
+
+ CharmRow[] rows = info.Charms;
+ for (int i = 0; i < rows.Length; i++)
+ {
+ CharmRow r = rows[i];
+ ImGuiNET.ImGui.PushID(i);
+ ImGuiNET.ImGui.TableNextRow();
+
+ ImGuiNET.ImGui.TableNextColumn();
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), r.Name);
+ if (r.Effect.Length > 0) ImGuiNET.ImGui.SetItemTooltip(r.Effect);
+
+ ImGuiNET.ImGui.TableNextColumn();
+ switch (r.Acquired)
+ {
+ case "carried":
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), r.Count > 1 ? $"Carried x{r.Count}" : "Carried");
+ ImGuiNET.ImGui.SetItemTooltip("In your pack or equipped.");
+ break;
+ case "seen":
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "Stored");
+ ImGuiNET.ImGui.SetItemTooltip("Owned but not carried"
+ + (r.LastSeen.Length > 0 ? " (last carried " + r.LastSeen + ")" : "")
+ + ". The client only sees items you carry.");
+ break;
+ default:
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "Not yet");
+ break;
+ }
+
+ ImGuiNET.ImGui.TableNextColumn();
+ if (r.Acquired != "carried")
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "-");
+ else if (r.Active == "on")
+ ColoredText(CharmOn, "ON");
+ else if (r.Active == "off")
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "OFF");
+ else
+ {
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "?");
+ ImGuiNET.ImGui.SetItemTooltip("Waiting for the charm's appraisal (requested automatically).");
+ }
+
+ ImGuiNET.ImGui.TableNextColumn();
+ string tier = r.Tier <= 0 ? "-" : r.MaxTier > 0 ? $"{r.Tier}/{r.MaxTier}" : r.Tier.ToString(CultureInfo.InvariantCulture);
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), tier);
+
+ ImGuiNET.ImGui.TableNextColumn();
+ if (r.Server == "off")
+ {
+ ColoredText(CharmDisabled, "Disabled");
+ ImGuiNET.ImGui.SetItemTooltip("The server refused or reported this charm as disabled.");
+ }
+ else if (r.Server == "on")
+ ColoredText(CharmOn, "Enabled");
+ else
+ {
+ ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "-");
+ ImGuiNET.ImGui.SetItemTooltip("Not reported. The server only tells players when a charm is refused.");
+ }
+
+ ImGuiNET.ImGui.PopID();
+ }
+ ImGuiNET.ImGui.EndTable();
+ }
+ ImGuiNET.ImGui.PopStyleColor(4);
+ ImGuiNET.ImGui.PopStyleVar();
+
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
+ Note("Double-click a carried charm in your pack to toggle it. Status comes from the charm's appraisal "
+ + "(Status: ON/OFF) or your character's ability flag. Charms not carried are inactive.", w);
+ Note("Stored = carried by this character before; RynthAi remembers it per character.", w);
+ }
+
+ /// TextUnformatted in a packed ImGui colour.
+ private static void ColoredText(uint abgr, string text)
+ {
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, abgr);
+ ImGuiNET.ImGui.TextUnformatted(text);
+ ImGuiNET.ImGui.PopStyleColor();
+ }
+
private static bool StepButton(string id, Vector2 pos, string glyph)
{
var dl = ImGuiNET.ImGui.GetWindowDrawList();
@@ -409,6 +678,8 @@ internal sealed class SettingsFace : IImGuiPanel
["Crafting"] = PhosphorIcons.Hammer,
["Looting"] = PhosphorIcons.Bag,
["Vendoring"] = PhosphorIcons.Storefront,
+ ["Diagnostics"] = PhosphorIcons.Wrench,
+ [CharmsTabName] = PhosphorIcons.Gift,
};
private static readonly System.Collections.Generic.Dictionary TabLabels = new();
diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs
new file mode 100644
index 0000000..e329f6f
--- /dev/null
+++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs
@@ -0,0 +1,479 @@
+// ============================================================================
+// RynthCore.Engine - ImGui/Panels/SkillsFace.Progression.cs
+// The Skills panel's Progression tab, shown on ILT-like worlds only:
+// - XP planner: exact XP for the next N raises of every attribute and vital,
+// from the client's XP tables (raising stays on the Attributes & Vitals tab).
+// - Attribute raiser: infinite attributes past the retail cap. RynthAi reads the
+// server's costs ("/xp all") and raises with "/attr", by hand (+1 / +10) or on a
+// timer from unassigned XP, in the order and mode set here.
+// - Augmentations / Enlightenment: RynthAi's ILT Hub planners. RynthAi owns the
+// math and the saved inputs (UiSources.Progression snapshot); edits and
+// actions go back as "prog ..." remote commands. /enl and arming
+// auto-enlighten ask here first; the server still shows its own dialog.
+// ============================================================================
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Numerics;
+using ImGuiNET;
+using RynthCore.Engine.UI;
+using RynthCore.Engine.UI.Data;
+using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
+
+namespace RynthCore.Engine.ImGuiBackend.Panels;
+
+internal sealed partial class SkillsFace
+{
+ private const string ProgConfirmId = "##skills_prog_confirm";
+
+ private int _planLevels = 10; // XP planner: raises to price per row
+ private bool _progSubscribed;
+
+ // The confirm the Progression tab asked for; the command is sent only on its Yes button.
+ private string _progConfirmTitle = "", _progConfirmText = "", _progConfirmYes = "", _progConfirmCommand = "";
+ private bool _progConfirmOpenRequested;
+
+ // Set by ShowProgression (any panel, AC thread); the tab is selected once RynthAi's snapshot
+ // says it exists (the first poll lands a step after the panel opens).
+ private static bool _progressionRequested;
+
+ /// RynthAi reports an ILT-like world (its ILT Hub exists and the server has ILT features).
+ private static bool ProgressionTabVisible => UiSources.Progression.Current?.Value.Available == true;
+
+ /// Opens the Skills panel (if closed) on the Progression tab. AC thread.
+ public static void ShowProgression()
+ {
+ _progressionRequested = true;
+ if (!ImGuiPanelHost.IsOpen(Title)) PanelRouter.Toggle(Title);
+ }
+
+ /// Draw: applies a pending ShowProgression once the tab exists.
+ private void ApplyProgressionRequest()
+ {
+ if (!_progressionRequested || !ProgressionTabVisible) return;
+ _progressionRequested = false;
+ _tab = 2;
+ }
+
+ private void ProgressionShown()
+ {
+ if (_progSubscribed) return;
+ _progSubscribed = true;
+ UiSources.Progression.Subscribe();
+ UiSources.Progression.RequestRefresh();
+ }
+
+ private void ProgressionHidden()
+ {
+ _progressionRequested = false;
+ if (!_progSubscribed) return;
+ _progSubscribed = false;
+ UiSources.Progression.Unsubscribe();
+ }
+
+ /// Sends "prog <value>" to RynthAi; the snapshot re-polls after its next tick applies it.
+ private static void SendProg(string value)
+ {
+ RynthAiCommands.ApplyRemoteCommand("prog", value);
+ UiSources.Progression.RequestRefreshAfterPluginTick();
+ }
+
+ private void AskProgConfirm(string title, string text, string yes, string command)
+ {
+ _progConfirmTitle = title;
+ _progConfirmText = text;
+ _progConfirmYes = yes;
+ _progConfirmCommand = command;
+ _progConfirmOpenRequested = true;
+ }
+
+ // ── Body ────────────────────────────────────────────────────────────
+
+ private void DrawProgression(float w)
+ {
+ ProgressionInfo? info = UiSources.Progression.Current?.Value;
+ ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4));
+ try
+ {
+ DrawXpPlanner(w);
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
+ if (info == null || !info.Available)
+ {
+ Message("Augmentations and Enlightenment need RynthAi's ILT Hub on an ILT world.", w);
+ return;
+ }
+ DrawAttrRaiser(info.Attr, w);
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
+ DrawAugPlanner(info.Aug, w);
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
+ DrawEnlPlanner(info.Enl, w);
+ ImGuiNET.ImGui.Dummy(new Vector2(0, 8));
+ }
+ finally
+ {
+ ImGuiNET.ImGui.PopStyleVar();
+ }
+ }
+
+ private void DrawXpPlanner(float w)
+ {
+ Section("XP planner", w);
+ if (_snap == null || _dat == null || _attributes.Count == 0)
+ {
+ Message("Waiting for your character's data...", w);
+ return;
+ }
+ ImGuiNET.ImGui.Indent(8);
+ long have = _snap.UnassignedXp;
+ Label($"Unassigned XP: {have:N0}", have > 0 ? Teal : Mute);
+ ImGuiNET.ImGui.SetNextItemWidth(160);
+ ImGuiNET.ImGui.SliderInt("Raises to plan##prog_lv", ref _planLevels, 1, 100);
+
+ if (ImGuiNET.ImGui.BeginTable("##prog_xp", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
+ new Vector2(w - 16, 0)))
+ {
+ ImGuiNET.ImGui.TableSetupColumn("Stat");
+ ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 50);
+ ImGuiNET.ImGui.TableSetupColumn("Next raise", ImGuiTableColumnFlags.WidthFixed, 100);
+ ImGuiNET.ImGui.TableSetupColumn($"Next {_planLevels}", ImGuiTableColumnFlags.WidthFixed, 120);
+ ImGuiNET.ImGui.TableHeadersRow();
+ foreach (Row r in _attributes) PlannerRow(r, have);
+ foreach (Row r in _vitals) PlannerRow(r, have);
+ ImGuiNET.ImGui.EndTable();
+ }
+ Label("Exact costs from the client's XP tables. Raise on the Attributes & Vitals tab"
+ + (ProgressionTabVisible ? ", or past the cap with the Attribute raiser below." : "."), Dim);
+ ImGuiNET.ImGui.Unindent(8);
+ }
+
+ private void PlannerRow(Row r, long have)
+ {
+ ImGuiNET.ImGui.TableNextRow();
+ ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Name);
+ ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Base.ToString(CultureInfo.InvariantCulture));
+ uint[]? table = r.Table;
+ int left = table == null ? 0 : Math.Max(0, table.Length - 1 - (int)Math.Min(r.Ranks, (uint)int.MaxValue));
+ ImGuiNET.ImGui.TableNextColumn();
+ if (table == null || left == 0) { Label(table == null ? "-" : "max", Dim); ImGuiNET.ImGui.TableNextColumn(); Label("-", Dim); return; }
+ long one = SkillDat.CostOf(table, r.Ranks, r.Spent, 1);
+ Label(one >= 0 ? one.ToString("N0", CultureInfo.InvariantCulture) : "-", one >= 0 && one <= have ? Teal : Dim);
+ ImGuiNET.ImGui.TableNextColumn();
+ int n = Math.Min(_planLevels, left);
+ long many = SkillDat.CostOf(table, r.Ranks, r.Spent, n);
+ string text = many >= 0 ? many.ToString("N0", CultureInfo.InvariantCulture) : "-";
+ if (n < _planLevels) text += $" ({n} to max)";
+ Label(text, many >= 0 && many <= have ? Teal : Dim);
+ }
+
+ private static readonly string[] AttrModes =
+ {
+ "Priority - top of the order first",
+ "Round robin - one level each, in order",
+ "Cheapest next level first",
+ };
+
+ private string? _attrKeepEdit; // reserve box being typed in (null = show RynthAi's value)
+ private int? _attrEveryEdit; // interval box being typed in
+
+ private void DrawAttrRaiser(AttrRaiser? a, float w)
+ {
+ Section("Attribute raiser (infinite attributes)", w);
+ ImGuiNET.ImGui.Indent(8);
+ float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24;
+ ImGuiNET.ImGui.PushTextWrapPos(wrap);
+ try
+ {
+ if (a == null) { Label("Update RynthAi to use the attribute raiser.", Mute); return; }
+ if (a.Off) { Label(a.Reason, Mute); return; }
+
+ Label(a.Unassigned, Teal);
+ Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
+ if (a.Running)
+ {
+ if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop");
+ }
+ else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal))
+ SendProg("attrrun");
+ if (Button("##attr_costs", "Refresh costs", new Vector2(p.X + 116, p.Y), new Vector2(110, 24), Text, BtnFill))
+ SendProg("attrcosts");
+ NextLine(p, 28);
+ if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status);
+ if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim);
+
+ ImGuiNET.ImGui.Separator();
+ bool auto = a.Auto;
+ if (ImGuiNET.ImGui.Checkbox("Auto-raise from unassigned XP##attr_auto", ref auto))
+ SendProg("attrauto " + (auto ? "on" : "off"));
+ ImGuiNET.ImGui.SameLine();
+ // Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send
+ // restarts the auto-raise timer).
+ int every = _attrEveryEdit ?? a.Every;
+ ImGuiNET.ImGui.SetNextItemWidth(90);
+ bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue);
+ bool everyActive = ImGuiNET.ImGui.IsItemActive();
+ if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
+ {
+ _attrEveryEdit = null;
+ if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture));
+ }
+ else _attrEveryEdit = everyActive ? every : null;
+ if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim);
+
+ int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1);
+ ImGuiNET.ImGui.SetNextItemWidth(260);
+ if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length))
+ SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture));
+
+ // The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an
+ // Enter on an untouched box can't round the reserve.
+ string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep;
+ string keep = _attrKeepEdit ?? shownKeep;
+ ImGuiNET.ImGui.SetNextItemWidth(140);
+ bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u,
+ ImGuiInputTextFlags.EnterReturnsTrue);
+ bool keepActive = ImGuiNET.ImGui.IsItemActive();
+ if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
+ {
+ _attrKeepEdit = null;
+ if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal))
+ SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal));
+ }
+ else _attrKeepEdit = keepActive ? keep : null;
+ ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes.");
+
+ DrawAttrTable(a, w);
+ Label("Tick the stats Raise now / auto-raise may spend on; arrows set the order. " + a.CostsAge + ".", Dim);
+ }
+ finally
+ {
+ ImGuiNET.ImGui.PopTextWrapPos();
+ ImGuiNET.ImGui.Unindent(8);
+ }
+ }
+
+ private void DrawAttrTable(AttrRaiser a, float w)
+ {
+ if (!ImGuiNET.ImGui.BeginTable("##prog_attr", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
+ new Vector2(w - 16, 0)))
+ return;
+ ImGuiNET.ImGui.TableSetupColumn("Raise", ImGuiTableColumnFlags.WidthFixed, 40);
+ ImGuiNET.ImGui.TableSetupColumn("Stat");
+ ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 56);
+ ImGuiNET.ImGui.TableSetupColumn("Next level", ImGuiTableColumnFlags.WidthFixed, 80);
+ ImGuiNET.ImGui.TableSetupColumn("Order / by hand", ImGuiTableColumnFlags.WidthFixed, 150);
+ ImGuiNET.ImGui.TableHeadersRow();
+ for (int i = 0; i < a.Rows.Length; i++)
+ {
+ AttrRow r = a.Rows[i];
+ ImGuiNET.ImGui.PushID("attr_" + r.Key);
+ ImGuiNET.ImGui.TableNextRow();
+
+ ImGuiNET.ImGui.TableNextColumn();
+ bool on = r.On;
+ if (ImGuiNET.ImGui.Checkbox("##on", ref on)) SendProg($"attron {r.Key} {(on ? "on" : "off")}");
+
+ ImGuiNET.ImGui.TableNextColumn();
+ Label($"{i + 1}. {r.Label}", r.On ? Text : Mute);
+
+ ImGuiNET.ImGui.TableNextColumn();
+ int clientBase = ClientBase(r);
+ Label(clientBase > 0 ? clientBase.ToString("N0", CultureInfo.InvariantCulture)
+ : r.Base >= 0 ? r.Base.ToString("N0", CultureInfo.InvariantCulture) : "-", Text);
+
+ ImGuiNET.ImGui.TableNextColumn();
+ Label(r.Cost, r.Afford ? Teal : Dim);
+
+ ImGuiNET.ImGui.TableNextColumn();
+ ImGuiNET.ImGui.BeginDisabled(i == 0);
+ if (ImGuiNET.ImGui.ArrowButton("##up", ImGuiDir.Up)) SendProg($"attrmove {r.Key} up");
+ ImGuiNET.ImGui.EndDisabled();
+ ImGuiNET.ImGui.SameLine(0, 2);
+ ImGuiNET.ImGui.BeginDisabled(i == a.Rows.Length - 1);
+ if (ImGuiNET.ImGui.ArrowButton("##down", ImGuiDir.Down)) SendProg($"attrmove {r.Key} down");
+ ImGuiNET.ImGui.EndDisabled();
+ ImGuiNET.ImGui.SameLine(0, 6);
+ ImGuiNET.ImGui.BeginDisabled(a.Running);
+ if (ImGuiNET.ImGui.SmallButton("+1")) SendProg($"attrraise {r.Key} 1");
+ ImGuiNET.ImGui.SameLine(0, 2);
+ if (ImGuiNET.ImGui.SmallButton("+10")) SendProg($"attrraise {r.Key} 10");
+ ImGuiNET.ImGui.EndDisabled();
+ ImGuiNET.ImGui.PopID();
+ }
+ ImGuiNET.ImGui.EndTable();
+ }
+
+ /// The client's own base value for a raiser row (0 when the snapshot has none).
+ private int ClientBase(AttrRow r)
+ {
+ List rows = r.Vital ? _vitals : _attributes;
+ foreach (Row row in rows)
+ if (row.Name.Equals(r.Label, StringComparison.OrdinalIgnoreCase)) return row.Base;
+ return 0;
+ }
+
+ private void DrawAugPlanner(AugPlanner a, float w)
+ {
+ Section("Augmentations", w);
+ ImGuiNET.ImGui.Indent(8);
+ try
+ {
+ if (a.Off) { Label("/aug is not available on this server.", Mute); return; }
+ if (ImGuiNET.ImGui.SmallButton("Load /aug##prog")) SendProg("augload");
+ ImGuiNET.ImGui.SameLine();
+ Label(a.Status, Dim);
+
+ string lpc = a.LumPerCoin.ToString(CultureInfo.InvariantCulture);
+ ImGuiNET.ImGui.SetNextItemWidth(160);
+ if (ImGuiNET.ImGui.InputTextWithHint("Lum per Enlightened Coin##prog_lpc", "0 = don't price coins", ref lpc, 24u))
+ SendProg("lumpercoin " + lpc.Replace(" ", "", StringComparison.Ordinal));
+
+ if (ImGuiNET.ImGui.BeginTable("##prog_augs", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
+ new Vector2(w - 16, 0)))
+ {
+ ImGuiNET.ImGui.TableSetupColumn("Aug");
+ ImGuiNET.ImGui.TableSetupColumn("Current", ImGuiTableColumnFlags.WidthFixed, 56);
+ ImGuiNET.ImGui.TableSetupColumn("Target", ImGuiTableColumnFlags.WidthFixed, 86);
+ ImGuiNET.ImGui.TableSetupColumn("Luminance", ImGuiTableColumnFlags.WidthFixed, 80);
+ ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 60);
+ ImGuiNET.ImGui.TableHeadersRow();
+ foreach (AugRow row in a.Rows)
+ {
+ ImGuiNET.ImGui.TableNextRow();
+ ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Label);
+ ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Current.ToString(CultureInfo.InvariantCulture));
+ ImGuiNET.ImGui.TableNextColumn();
+ int tgt = row.Target;
+ ImGuiNET.ImGui.SetNextItemWidth(80);
+ if (ImGuiNET.ImGui.InputInt("##prog_tgt_" + row.Key, ref tgt, 0))
+ SendProg($"augtarget {row.Key} {Math.Clamp(tgt, 0, Math.Max(row.Cap, 0))}");
+ ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Lum);
+ ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Coins > 0 ? row.Coins.ToString(CultureInfo.InvariantCulture) : "-");
+ }
+ ImGuiNET.ImGui.EndTable();
+ }
+ Label(a.Total, Amber);
+ if (a.Short.Length > 0) Label(a.Short, Text);
+ Label(a.Banked, Dim);
+ }
+ finally
+ {
+ ImGuiNET.ImGui.Unindent(8);
+ }
+ }
+
+ private void DrawEnlPlanner(EnlPlanner e, float w)
+ {
+ Section("Enlightenment", w);
+ ImGuiNET.ImGui.Indent(8);
+ float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; // window-local x
+ ImGuiNET.ImGui.PushTextWrapPos(wrap);
+ try
+ {
+ if (e.Off) { Label("/enl is not available on this server.", Mute); return; }
+ Label(e.Header, Text);
+ Label(e.Next, Teal);
+
+ int target = e.Target;
+ ImGuiNET.ImGui.SetNextItemWidth(100);
+ if (ImGuiNET.ImGui.InputInt("Plan to level##prog_enlt", ref target))
+ SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture));
+ foreach (string line in e.Plan) ImGuiNET.ImGui.BulletText(line);
+
+ int coinsPerToken = e.CoinsPerToken;
+ ImGuiNET.ImGui.SetNextItemWidth(100);
+ if (ImGuiNET.ImGui.InputInt("Coins per token (shop price)##prog_cpt", ref coinsPerToken))
+ SendProg("coinspertoken " + Math.Max(0, coinsPerToken).ToString(CultureInfo.InvariantCulture));
+ if (e.TokensShort.Length > 0) Label(e.TokensShort, Dim);
+
+ ImGuiNET.ImGui.Separator();
+ if (e.Blockers.Length == 0) Label("Client-side checks pass.", Green);
+ foreach (string b in e.Blockers) Label(b, Amber);
+ Label(e.ServerChecks, Dim);
+
+ Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
+ if (Button("##prog_enl", "Enlighten now...", p, new Vector2(150, 24), Text, BtnFill, border: Teal))
+ AskProgConfirm("Enlighten",
+ "Send /enl now?\n\nEnlightening resets your level and wipes unassigned XP.\n"
+ + "The server will show its own Yes/No dialog - you must click Yes there.",
+ "Send /enl", "enlighten");
+ NextLine(p, 28);
+
+ ImGuiNET.ImGui.Separator();
+ bool auto = e.Auto;
+ if (ImGuiNET.ImGui.Checkbox("Auto-enlighten when ready##prog_auto", ref auto))
+ {
+ if (auto)
+ AskProgConfirm("Arm auto-enlighten",
+ "Auto-enlighten will send /enl whenever the checks pass (peace mode, level, materials).\n"
+ + "You still have to click Yes in the AC dialog each time.\n\nArm it for this session?",
+ "Arm", "autoenl on");
+ else
+ SendProg("autoenl off");
+ }
+ if (e.Auto && !e.Armed)
+ {
+ ImGuiNET.ImGui.SameLine();
+ if (ImGuiNET.ImGui.SmallButton("Arm for this session...##prog_arm"))
+ AskProgConfirm("Arm auto-enlighten", "Arm auto-enlighten for this session?", "Arm", "autoenl arm");
+ }
+ bool spend = e.SpendFirst;
+ if (ImGuiNET.ImGui.Checkbox("Spend unassigned XP on attributes first##prog_spend", ref spend))
+ SendProg("spendfirst " + (spend ? "on" : "off"));
+ int every = e.CheckEvery;
+ ImGuiNET.ImGui.SetNextItemWidth(100);
+ if (ImGuiNET.ImGui.InputInt("Check every (s)##prog_every", ref every))
+ SendProg("checkevery " + Math.Max(10, every).ToString(CultureInfo.InvariantCulture));
+ Label(e.Armed ? "Armed." : "Disarmed.", e.Armed ? Amber : Dim);
+ if (e.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(e.Status);
+ }
+ finally
+ {
+ ImGuiNET.ImGui.PopTextWrapPos();
+ ImGuiNET.ImGui.Unindent(8);
+ }
+ }
+
+ // ── Confirm ─────────────────────────────────────────────────────────
+
+ /// The Progression tab's Yes/No popup (outside the body child, like DrawConfirm).
+ private void DrawProgressionConfirm()
+ {
+ if (_progConfirmOpenRequested)
+ {
+ _progConfirmOpenRequested = false;
+ ImGuiNET.ImGui.OpenPopup(ProgConfirmId);
+ }
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
+ ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
+ ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
+ ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
+ bool open = ImGuiNET.ImGui.BeginPopup(ProgConfirmId);
+ ImGuiNET.ImGui.PopStyleVar(2);
+ ImGuiNET.ImGui.PopStyleColor(2);
+ if (!open) return;
+ try
+ {
+ ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
+ Label(_progConfirmTitle, Amber);
+ ImGuiNET.ImGui.PopFont();
+ ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 320);
+ Label(_progConfirmText, Text);
+ ImGuiNET.ImGui.PopTextWrapPos();
+
+ Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
+ if (Button("##prog_yes", _progConfirmYes, p, new Vector2(120, 24), Text, StartBg))
+ {
+ SendProg(_progConfirmCommand);
+ ImGuiNET.ImGui.CloseCurrentPopup();
+ }
+ if (Button("##prog_no", "Cancel", new Vector2(p.X + 126, p.Y), new Vector2(90, 24), Text, BtnFill))
+ ImGuiNET.ImGui.CloseCurrentPopup();
+ NextLine(p, 28);
+ }
+ finally
+ {
+ ImGuiNET.ImGui.EndPopup();
+ }
+ }
+}
diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs
index d4b55a0..beb9412 100644
--- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs
+++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs
@@ -45,7 +45,7 @@ using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
-internal sealed class SkillsFace : IImGuiPanel
+internal sealed partial class SkillsFace : IImGuiPanel
{
public const string Title = "Skills";
@@ -127,7 +127,7 @@ internal sealed class SkillsFace : IImGuiPanel
}
// ── State ───────────────────────────────────────────────────────────
- private int _tab; // 0 skills, 1 attributes & vitals
+ private int _tab; // 0 skills, 1 attributes & vitals, 2 progression (ILT worlds)
private SortKey _sort = SortKey.Name;
private bool _descending;
private readonly bool[] _collapsed = { false, false, false, true };
@@ -193,18 +193,23 @@ internal sealed class SkillsFace : IImGuiPanel
SkillDat.EnsureLoadQueued();
PortalSpellTable.EnsureLoadQueued();
MasteryFeed.PanelOpened(); // asks only on Aelrynth, and only if the last reply is stale
+ ProgressionShown();
}
+ public void OnHidden() => ProgressionHidden();
+
public void Draw()
{
PlayerProgressHooks.Want();
Refresh();
+ ApplyProgressionRequest();
+ if (_tab == 2 && !ProgressionTabVisible) _tab = 0;
float w = Begin(out Vector2 origin, out Vector2 size);
DrawSummary(w);
DrawTabs(w);
if (_tab == 0) DrawToolbar(w);
- DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
+ if (_tab != 2) DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap());
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
@@ -212,7 +217,9 @@ internal sealed class SkillsFace : IImGuiPanel
ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH));
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
EnsureWidths();
- if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead)
+ if (_tab == 2)
+ DrawProgression(bw);
+ else if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead)
Message("Waiting for your character's data...", bw);
else if (_dat == null)
Message("Loading skill names from the client's portal.dat: " + SkillDat.Status, bw);
@@ -228,6 +235,7 @@ internal sealed class SkillsFace : IImGuiPanel
_picker.Draw();
DrawMulti();
DrawConfirm();
+ DrawProgressionConfirm();
}
// ── Data ────────────────────────────────────────────────────────────
@@ -691,13 +699,18 @@ internal sealed class SkillsFace : IImGuiPanel
private void DrawTabs(float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
- float half = (w - 4) * 0.5f;
- if (Button("##tab_skills", "Skills", p, new Vector2(half, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill,
+ // The Progression tab only exists on ILT-like worlds (RynthAi's snapshot says so).
+ int count = ProgressionTabVisible ? 3 : 2;
+ float tabW = (w - 4 * (count - 1)) / count;
+ if (Button("##tab_skills", "Skills", p, new Vector2(tabW, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill,
border: _tab == 0 ? Teal : 0))
_tab = 0;
- if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + half + 4, p.Y), new Vector2(half, 22),
+ if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + tabW + 4, p.Y), new Vector2(tabW, 22),
_tab == 1 ? Teal : Text, _tab == 1 ? Selected : BtnFill, border: _tab == 1 ? Teal : 0))
_tab = 1;
+ if (count == 3 && Button("##tab_prog", "Progression", new Vector2(p.X + 2 * (tabW + 4), p.Y), new Vector2(tabW, 22),
+ _tab == 2 ? Teal : Text, _tab == 2 ? Selected : BtnFill, border: _tab == 2 ? Teal : 0))
+ _tab = 2;
NextLine(p, 26);
}
diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs
index 35f70f4..65b5c44 100644
--- a/src/RynthCore.Engine/ImGui/Win32Backend.cs
+++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs
@@ -991,11 +991,15 @@ internal static unsafe class Win32Backend
// HUD drag (keeps our SetCapture from fighting NewFrame's). No-op
// unless the HUD is drawn.
if (IsMouseMessage(msg))
+ {
TrackMouseButtons(msg, wParam);
+ ItemDragBridge.OnGameMouse(msg, wParam, lParam, _heldButtonsBelongToGame);
+ }
else if (msg == WM_KILLFOCUS)
{
_heldMouseButtons = 0;
_heldButtonsBelongToGame = false;
+ ItemDragBridge.Reset();
}
// ── Avalonia panel hit-test & input forwarding ────────────────
@@ -1006,7 +1010,7 @@ internal static unsafe class Win32Backend
{
// fall through: AC gets the message
}
- else if (IsMouseMessage(msg))
+ else if (IsMouseMessage(msg) && !ImGuiOwnsMouseOverAvalonia())
{
bool handled = TryForwardToAvalonia(msg, wParam, lParam);
if (handled)
@@ -1097,6 +1101,14 @@ internal static unsafe class Win32Backend
}
}
+ // An AC inventory item dragged onto an ImGui window: AC must not drop it on the
+ // ground behind the window. It gets the release where the drag began instead.
+ if (ItemDragBridge.TryRedirectNativeDrop(msg, out IntPtr pressLParam))
+ {
+ CallWindowProcA(_originalWndProc, hWnd, WM_MOUSEMOVE, (IntPtr)MK_LBUTTON, pressLParam);
+ return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, pressLParam);
+ }
+
// Pass through to original WndProc
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
}
@@ -1107,6 +1119,17 @@ internal static unsafe class Win32Backend
}
}
+ ///
+ /// ImGui windows are drawn on top of the Avalonia layer, so when the cursor is over
+ /// an ImGui window (or an ImGui widget is active) mouse input must go to ImGui
+ /// instead of the Avalonia panel underneath. An Avalonia drag/resize that is already
+ /// in progress keeps its capture so the release is never lost.
+ ///
+ private static bool ImGuiOwnsMouseOverAvalonia()
+ {
+ return _wantCaptureMouse && !AvaloniaOverlay.HasPointerCapture;
+ }
+
///
/// If the cursor is over the Avalonia shell panel, PostMessage the mouse event to
/// the off-screen Avalonia HWND and return true (caller should suppress game delivery).
diff --git a/src/RynthCore.Engine/LogPaths.cs b/src/RynthCore.Engine/LogPaths.cs
index 3e2cced..e67cbf1 100644
--- a/src/RynthCore.Engine/LogPaths.cs
+++ b/src/RynthCore.Engine/LogPaths.cs
@@ -21,6 +21,7 @@
using System;
using System.IO;
+using RynthCore.Install;
namespace RynthCore.Engine;
diff --git a/src/RynthCore.Engine/LogSettings.cs b/src/RynthCore.Engine/LogSettings.cs
new file mode 100644
index 0000000..5e98f44
--- /dev/null
+++ b/src/RynthCore.Engine/LogSettings.cs
@@ -0,0 +1,248 @@
+using System;
+using System.IO;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using RynthCore.Engine.Plugins;
+
+namespace RynthCore.Engine;
+
+///
+/// Engine log categories. Each one has a configurable emit level (see ).
+/// Names are the keys of engine.json "LogCategories" and must stay stable.
+///
+internal enum LogCategory
+{
+ /// Uncategorised RynthLog.Info lines.
+ General = 0,
+ /// D3D9: vtable, EndScene, bootstrapper, matrix capture, nav3D.
+ D3D9,
+ /// Compatibility hooks: client objects, combat, movement, vitals, chat, ...
+ Compat,
+ /// ImGui rendering: context, DX9 backend, Win32 input, shell.
+ Render,
+ /// Plugin system, including every line plugins write through the host Log API.
+ Plugin,
+ /// UI / Avalonia overlay.
+ UI,
+ /// Verbose detail lines (RynthLog.Verbose / RynthLog.Debug).
+ Verbose,
+}
+
+///
+/// Live engine logging configuration, read from %APPDATA%\RynthCore\engine.json:
+///
+/// - "LoggingLevel" — global threshold: Off, Error, Warning, Info, Debug, Trace.
+/// - "LogCategories" — per-category emit level: { "Compat": "Info", "Verbose": "Debug", ... }.
+/// The emit level is the level a category's lines are written AT, so a line shows when
+/// its emit level is within the global threshold. Setting a Trace/Debug category to
+/// Info puts it in the normal (Info) log; Off silences the category entirely.
+///
+/// A background thread polls the file's timestamp once a second, so launcher edits apply to a
+/// running client without a restart. Errors are always written, even when the level is Off.
+///
+internal static class LogSettings
+{
+ /// engine.json property holding the per-category levels.
+ internal const string CategoriesProperty = "LogCategories";
+
+ private const int PollIntervalMs = 1000;
+
+ // Default emit level per LogCategory (index = enum value): categories at Info,
+ // Render off, verbose lines at Debug.
+ private static readonly EntryPoint.EngineLogLevel[] Defaults =
+ {
+ EntryPoint.EngineLogLevel.Info, // General
+ EntryPoint.EngineLogLevel.Info, // D3D9
+ EntryPoint.EngineLogLevel.Info, // Compat
+ EntryPoint.EngineLogLevel.Off, // Render
+ EntryPoint.EngineLogLevel.Info, // Plugin
+ EntryPoint.EngineLogLevel.Info, // UI
+ EntryPoint.EngineLogLevel.Debug, // Verbose
+ };
+
+ // Replaced wholesale on reload (never mutated after publish) so hot-path readers on any
+ // thread can index it without a lock.
+ private static EntryPoint.EngineLogLevel[] _levels = (EntryPoint.EngineLogLevel[])Defaults.Clone();
+
+ private static readonly object WatcherLock = new();
+ private static Thread? _watcherThread;
+ private static ManualResetEventSlim? _stopSignal;
+ private static DateTime _stampUtc = DateTime.MinValue;
+
+ private static string SettingsPath => Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "engine.json");
+
+ /// Current emit level for a category (cheap; safe on hot paths).
+ internal static EntryPoint.EngineLogLevel LevelFor(LogCategory category)
+ {
+ EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
+ int i = (int)category;
+ return (uint)i < (uint)levels.Length ? levels[i] : EntryPoint.EngineLogLevel.Info;
+ }
+
+ /// True when a line in this category would be written right now.
+ internal static bool IsEnabled(LogCategory category) => EntryPoint.ShouldLog(LevelFor(category));
+
+ /// 3-char severity tag written into each log line.
+ internal static string Tag(EntryPoint.EngineLogLevel level) => level switch
+ {
+ EntryPoint.EngineLogLevel.Error => "ERR",
+ EntryPoint.EngineLogLevel.Warning => "WRN",
+ EntryPoint.EngineLogLevel.Debug => "DBG",
+ EntryPoint.EngineLogLevel.Trace => "TRC",
+ _ => "INF",
+ };
+
+ ///
+ /// Reads the global level and category levels from engine.json and publishes them.
+ /// Called once at init (before the first log line) and again by the watcher on change.
+ /// Missing or unreadable values fall back to their defaults. Returns a one-line summary.
+ ///
+ internal static string Reload()
+ {
+ string? globalText = null;
+ bool readFailed = false;
+ var levels = (EntryPoint.EngineLogLevel[])Defaults.Clone();
+
+ try
+ {
+ string path = SettingsPath;
+ if (File.Exists(path))
+ {
+ _stampUtc = File.GetLastWriteTimeUtc(path);
+ // ReadAllText strips a UTF-8/UTF-16 BOM that JsonDocument would choke on.
+ using var doc = JsonDocument.Parse(File.ReadAllText(path));
+ JsonElement root = doc.RootElement;
+
+ if (root.TryGetProperty("LoggingLevel", out JsonElement levelEl) && levelEl.ValueKind == JsonValueKind.String)
+ globalText = levelEl.GetString();
+
+ if (root.TryGetProperty(CategoriesProperty, out JsonElement catsEl) && catsEl.ValueKind == JsonValueKind.Object)
+ {
+ foreach (JsonProperty p in catsEl.EnumerateObject())
+ {
+ if (p.Value.ValueKind != JsonValueKind.String) continue;
+ if (!Enum.TryParse(p.Name, ignoreCase: true, out LogCategory cat) || !Enum.IsDefined(cat)) continue;
+ if (TryParseCategoryLevel(p.Value.GetString(), out EntryPoint.EngineLogLevel lvl))
+ levels[(int)cat] = lvl;
+ }
+ }
+ }
+ }
+ catch
+ {
+ // Half-written / corrupt file: category defaults for this pass and the global level as it
+ // was; the next timestamp change retries.
+ readFailed = true;
+ }
+
+ if (!readFailed || globalText != null)
+ EntryPoint.LoggingLevel = EntryPoint.ParseLoggingLevel(globalText);
+ Volatile.Write(ref _levels, levels);
+ EntryPoint.VerboseLogging = IsEnabled(LogCategory.Verbose);
+ return Describe();
+ }
+
+ /// Human-readable "level=Info D3D9=Info Compat=Info ..." summary for the log.
+ internal static string Describe()
+ {
+ var sb = new StringBuilder();
+ sb.Append("level=").Append(EntryPoint.LoggingLevel);
+ EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
+ for (int i = 0; i < levels.Length; i++)
+ sb.Append(' ').Append((LogCategory)i).Append('=').Append(levels[i]);
+ return sb.ToString();
+ }
+
+ ///
+ /// Categories whose emit level is more verbose than the global level, so none of their lines
+ /// are written (e.g. every category at Trace with LoggingLevel Info: an almost empty log).
+ /// Empty when nothing is hidden.
+ ///
+ internal static string HiddenCategoriesWarning()
+ {
+ EntryPoint.EngineLogLevel global = EntryPoint.LoggingLevel;
+ EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
+ var hidden = new StringBuilder();
+ for (int i = 0; i < levels.Length; i++)
+ {
+ if (levels[i] == EntryPoint.EngineLogLevel.Off || levels[i] <= global) continue;
+ if (hidden.Length > 0) hidden.Append(", ");
+ hidden.Append((LogCategory)i).Append('=').Append(levels[i]);
+ }
+ return hidden.Length == 0 ? ""
+ : $"LogSettings: {hidden} write above the global LoggingLevel ({global}), so those lines are NOT logged. " +
+ "Raise LoggingLevel to the most verbose category level, or set the categories to Info.";
+ }
+
+ /// Starts the once-a-second engine.json poll. Idempotent.
+ internal static void StartWatcher()
+ {
+ lock (WatcherLock)
+ {
+ if (_watcherThread != null) return;
+ _stopSignal = new ManualResetEventSlim(false);
+ ManualResetEventSlim stop = _stopSignal;
+ _watcherThread = new Thread(() => WatchLoop(stop))
+ {
+ IsBackground = true,
+ Name = "RynthCore.LogSettingsWatcher",
+ };
+ _watcherThread.Start();
+ }
+ }
+
+ ///
+ /// Stops and joins the poll thread. Called from EngineLifecycle.Shutdown so the thread never
+ /// runs inside an old engine generation after a hot reload.
+ ///
+ internal static void StopWatcher()
+ {
+ Thread? thread;
+ lock (WatcherLock)
+ {
+ thread = _watcherThread;
+ _stopSignal?.Set();
+ _watcherThread = null;
+ }
+ thread?.Join(2000);
+ }
+
+ private static void WatchLoop(ManualResetEventSlim stop)
+ {
+ while (!stop.Wait(PollIntervalMs))
+ {
+ try
+ {
+ string path = SettingsPath;
+ if (!File.Exists(path) || File.GetLastWriteTimeUtc(path) == _stampUtc)
+ continue;
+
+ string summary = Reload();
+ // Bypasses the category levels so a change is visible whenever Info is in range.
+ if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Info))
+ EntryPoint.LogTagged("engine", $"LogSettings: engine.json changed - logging reloaded ({summary}).", "INF");
+ string hidden = HiddenCategoriesWarning();
+ if (hidden.Length > 0) RynthLog.Warn(hidden);
+ }
+ catch
+ {
+ // Logging configuration must never take the client down; retry next poll.
+ }
+ }
+ }
+
+ ///
+ /// Parses a category emit level: Off, Trace, Debug (or Verbose), Info, Warning (or Warn), Error.
+ ///
+ private static bool TryParseCategoryLevel(string? text, out EntryPoint.EngineLogLevel level)
+ {
+ level = EntryPoint.EngineLogLevel.Info;
+ if (string.IsNullOrWhiteSpace(text)) return false;
+ string t = text.Trim();
+ if (t.Equals("Verbose", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Debug; return true; }
+ if (t.Equals("Warn", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Warning; return true; }
+ return Enum.TryParse(t, ignoreCase: true, out level) && Enum.IsDefined(level);
+ }
+}
diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs
index 3aeb966..9648037 100644
--- a/src/RynthCore.Engine/Plugins/EngineSettings.cs
+++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs
@@ -26,6 +26,7 @@ internal static class EngineSettings
private static bool _enableEngine = true;
private static int _engineHookCount = int.MaxValue;
private static bool _enableImGuiBackend = true;
+ private static bool _enablePluginOverlayWindows = true;
private static bool _enableHangMinidump = true;
private static bool _preventIdleLogoff = true;
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
@@ -180,6 +181,19 @@ internal static class EngineSettings
}
}
+ /// When true (default) and the ImGui shell is off, plugins that export
+ /// RynthPluginRenderOverlay draw their extra ImGui windows (RynthAi: ILT Hub, Item Info)
+ /// beside the Avalonia UI. engine.json "EnablePluginOverlayWindows": false hides them.
+ /// Needs .
+ public static bool EnablePluginOverlayWindows
+ {
+ get
+ {
+ EnsureLoaded();
+ return _enablePluginOverlayWindows;
+ }
+ }
+
/// When true, MainThreadHangWatchdog writes a minidump to
/// Logs\dumps\ the first time AC's main thread is confirmed permanently
/// wedged — a targeted post-mortem to replace always-on procdump (which
@@ -421,6 +435,12 @@ internal static class EngineSettings
_enableImGuiBackend = ibEl.GetBoolean();
}
+ if (doc.RootElement.TryGetProperty("EnablePluginOverlayWindows", out var powEl) &&
+ (powEl.ValueKind == JsonValueKind.True || powEl.ValueKind == JsonValueKind.False))
+ {
+ _enablePluginOverlayWindows = powEl.GetBoolean();
+ }
+
if (doc.RootElement.TryGetProperty("EnableHangMinidump", out var hmEl) &&
(hmEl.ValueKind == JsonValueKind.True || hmEl.ValueKind == JsonValueKind.False))
{
@@ -487,7 +507,7 @@ internal static class EngineSettings
{
"PluginPaths", "EnableImGuiShell", "EnablePlugins", "EnableDatShareHook",
"EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount",
- "EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
+ "EnableImGuiBackend", "EnablePluginOverlayWindows", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
"FlightRecorder", "InsertReleasesUi",
};
@@ -515,6 +535,7 @@ internal static class EngineSettings
w.WriteBoolean("EnableEngine", _enableEngine);
w.WriteNumber("EngineHookCount", _engineHookCount);
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
+ w.WriteBoolean("EnablePluginOverlayWindows", _enablePluginOverlayWindows);
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff);
if (_decalBridgeMode != DecalBridgeMode.Auto) // default: leave the file as it was
diff --git a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs
index 8d572a3..b2ce607 100644
--- a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs
+++ b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs
@@ -54,6 +54,11 @@ internal sealed class LoadedPlugin
public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; }
public PluginTickDelegate? Tick { get; set; }
public PluginRenderDelegate? Render { get; set; }
+ /// Optional RynthPluginRenderOverlay: ImGui windows drawn while the ImGui shell is off.
+ public PluginRenderDelegate? RenderOverlay { get; set; }
+
+ /// Set after the first RenderOverlay call has been logged (render thread only).
+ public bool RenderOverlayLogged { get; set; }
// ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ───
public bool UiExportsResolved { get; set; }
@@ -85,4 +90,44 @@ internal sealed class LoadedPlugin
public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; }
/// Why the plugin was not started (a required plugin missing or failed); empty otherwise.
public string NotStartedReason { get; set; } = "";
+
+ ///
+ /// Drops managed delegates wrapping exports so the native module can fully unload after
+ /// the host calls FreeLibrary (hot-reload / rescan).
+ ///
+ internal void ClearResolvedDelegates()
+ {
+ Init = null;
+ Shutdown = null;
+ GetName = null;
+ GetVersion = null;
+ OnLoginComplete = null;
+ OnUIInitialized = null;
+ OnBusyCountIncremented = null;
+ OnBusyCountDecremented = null;
+ OnSelectedTargetChange = null;
+ OnCombatModeChange = null;
+ OnSmartBoxEventPtr = IntPtr.Zero;
+ OnSmartBoxEvent = null;
+ OnDeleteObject = null;
+ OnCreateObject = null;
+ OnUpdateObjectPtr = IntPtr.Zero;
+ OnUpdateObject = null;
+ OnUpdateObjectInventory = null;
+ OnViewObjectContents = null;
+ OnStopViewingObjectContents = null;
+ OnVendorOpen = null;
+ OnVendorClose = null;
+ OnUpdateHealthPtr = IntPtr.Zero;
+ OnUpdateHealth = null;
+ OnChatWindowTextPtr = IntPtr.Zero;
+ OnChatWindowText = null;
+ OnChatBarEnter = null;
+ OnBarAction = null;
+ OnEnchantmentAdded = null;
+ OnEnchantmentRemoved = null;
+ Tick = null;
+ Render = null;
+ RenderOverlay = null;
+ }
}
diff --git a/src/RynthCore.Engine/Plugins/PluginLoader.cs b/src/RynthCore.Engine/Plugins/PluginLoader.cs
index 1b45302..8e73b3a 100644
--- a/src/RynthCore.Engine/Plugins/PluginLoader.cs
+++ b/src/RynthCore.Engine/Plugins/PluginLoader.cs
@@ -89,6 +89,9 @@ internal static class PluginLoader
///
public static void Unload(LoadedPlugin plugin)
{
+ // Release managed thunks first so the module ref-count can drop to zero on FreeLibrary.
+ plugin.ClearResolvedDelegates();
+
if (ManagedPlugins.IsManagedHandle(plugin.ModuleHandle))
{
ManagedPlugins.Unload(plugin.ModuleHandle); // a managed plugin really goes away
@@ -506,6 +509,10 @@ internal static class PluginLoader
if (renderPtr != IntPtr.Zero)
plugin.Render = Marshal.GetDelegateForFunctionPointer(renderPtr);
+ IntPtr renderOverlayPtr = GetProcAddress(handle, "RynthPluginRenderOverlay");
+ if (renderOverlayPtr != IntPtr.Zero)
+ plugin.RenderOverlay = Marshal.GetDelegateForFunctionPointer(renderOverlayPtr);
+
// Read name/version from the plugin if available
if (plugin.GetName != null)
{
diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs
index 9537dd2..44ab67e 100644
--- a/src/RynthCore.Engine/Plugins/PluginManager.cs
+++ b/src/RynthCore.Engine/Plugins/PluginManager.cs
@@ -1140,6 +1140,109 @@ internal static partial class PluginManager
}
}
+ ///
+ /// ImGui-shell-off counterpart of : calls the optional
+ /// RynthPluginRenderOverlay export, where a plugin draws only the extra windows that have
+ /// no Avalonia panel (e.g. RynthAi's ILT Hub). They float beside the Avalonia UI and add to it.
+ /// A throw switches off just that plugin's overlay windows; the plugin is NOT marked Failed,
+ /// so its tick/automation and Avalonia panels keep running.
+ ///
+ public static void RenderOverlayAll()
+ {
+ _overlayCalls++;
+ if (!_loginCompleteObserved)
+ {
+ if (!_loggedOverlayWaitingForLogin)
+ {
+ _loggedOverlayWaitingForLogin = true;
+ RynthLog.Info("PluginManager: RenderOverlayAll called - waiting for login before drawing overlay windows.");
+ }
+ return; // same not-in-world crash zone guard as RenderAll
+ }
+
+ LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot);
+
+ // Count plugins that will actually be called; log whenever that set changes.
+ int bound = 0;
+ for (int i = 0; i < plugins.Length; i++)
+ {
+ var p = plugins[i];
+ if (p.Initialized && !p.Failed && p.RenderOverlay != null) bound++;
+ }
+ _overlayBound = bound;
+ if (bound != _loggedOverlayBound || plugins.Length != _loggedOverlayTotal)
+ {
+ _loggedOverlayBound = bound;
+ _loggedOverlayTotal = plugins.Length;
+ var sb = new System.Text.StringBuilder();
+ for (int i = 0; i < plugins.Length; i++)
+ {
+ var p = plugins[i];
+ if (sb.Length > 0) sb.Append(", ");
+ sb.Append(p.DisplayName).Append('(')
+ .Append(p.RenderOverlay != null ? "overlay" : "no-overlay")
+ .Append(p.Initialized ? "" : ",not-init")
+ .Append(p.Failed ? ",failed" : "")
+ .Append(')');
+ }
+ RynthLog.Info($"PluginManager: RenderOverlayAll login seen, {bound} of {plugins.Length} plugin(s) will draw overlay windows: {sb}.");
+ }
+
+ for (int i = 0; i < plugins.Length; i++)
+ {
+ var plugin = plugins[i];
+ var overlay = plugin.RenderOverlay;
+ if (!plugin.Initialized || plugin.Failed || overlay == null)
+ continue;
+
+ if (!plugin.RenderOverlayLogged)
+ {
+ // One line per plugin per session: proves the engine is actually driving the overlay export.
+ plugin.RenderOverlayLogged = true;
+ RynthLog.Plugin($"PluginManager: first RenderOverlay call for {plugin.DisplayName}.");
+ }
+
+ try
+ {
+ overlay();
+ }
+ catch (Exception ex)
+ {
+ plugin.RenderOverlay = null;
+ RynthLog.Error($"PluginManager: {plugin.DisplayName} RenderOverlay threw {ex.GetType().Name}: {ex.Message} - overlay windows off for this session (plugin keeps running).");
+ }
+ }
+ }
+
+ // RenderOverlayAll diagnostics (render thread only).
+ private static long _overlayCalls;
+ private static int _overlayBound;
+ private static bool _loggedOverlayWaitingForLogin;
+ private static int _loggedOverlayBound = -1;
+ private static int _loggedOverlayTotal = -1;
+
+ ///
+ /// True when an initialized, healthy plugin exports RynthPluginRenderOverlay. Reads the
+ /// render snapshot only (no lock, no allocation): safe every frame on the render thread.
+ ///
+ internal static bool HasOverlayPlugins
+ {
+ get
+ {
+ LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot);
+ for (int i = 0; i < plugins.Length; i++)
+ {
+ var p = plugins[i];
+ if (p.Initialized && !p.Failed && p.RenderOverlay != null) return true;
+ }
+ return false;
+ }
+ }
+
+ /// Overlay stats for the ImGui heartbeat line.
+ internal static string DescribeOverlayState()
+ => $"overlayCalls={_overlayCalls} loginSeen={_loginCompleteObserved} overlayPlugins={_overlayBound}";
+
public static void ShutdownAll()
{
RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)...");
diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj
index a18b6e4..3530706 100644
--- a/src/RynthCore.Engine/RynthCore.Engine.csproj
+++ b/src/RynthCore.Engine/RynthCore.Engine.csproj
@@ -6,6 +6,9 @@
win-x86
Library
true
+
+ $(WarningsAsErrors);CS0162
enable
true
Shared
@@ -66,6 +69,8 @@
+
+
diff --git a/src/RynthCore.Engine/RynthLog.cs b/src/RynthCore.Engine/RynthLog.cs
index 6fe4d4d..7a97386 100644
--- a/src/RynthCore.Engine/RynthLog.cs
+++ b/src/RynthCore.Engine/RynthLog.cs
@@ -4,73 +4,58 @@ namespace RynthCore.Engine;
///
/// Centralised logging — every log call in the Engine routes through here.
-/// Toggle categories on/off at runtime to suppress entire subsystems.
-/// Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…").
+/// Each category method writes at that category's emit level (engine.json "LogCategories",
+/// editable live from the launcher; see ), gated by the global
+/// "LoggingLevel". Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…").
///
internal static class RynthLog
{
- // ── Category toggles (flip to false to silence a subsystem) ──────────
-
- internal static bool D3D9Enabled = true;
- internal static bool CompatEnabled = true;
- internal static bool RenderEnabled = false; // ImGui, DX9Backend, Win32Backend
- internal static bool PluginEnabled = true;
- internal static bool UIEnabled = true;
-
// ── Category methods ─────────────────────────────────────────────────
/// D3D9 subsystem: vtable, EndScene, bootstrapper, matrix capture, nav3D.
- internal static void D3D9(string msg)
- {
- if (D3D9Enabled) Write(msg);
- }
+ internal static void D3D9(string msg) => WriteCategory(LogCategory.D3D9, msg);
/// Compatibility hooks: SmartBox, client objects, combat, movement, vitals, chat, etc.
- internal static void Compat(string msg)
- {
- if (CompatEnabled) Write(msg);
- }
+ internal static void Compat(string msg) => WriteCategory(LogCategory.Compat, msg);
/// ImGui rendering: context, DX9 backend, Win32 input, shell.
- internal static void Render(string msg)
- {
- if (RenderEnabled) Write(msg);
- }
+ internal static void Render(string msg) => WriteCategory(LogCategory.Render, msg);
- /// Plugin system: loader, manager, lifecycle callbacks.
- internal static void Plugin(string msg)
- {
- if (PluginEnabled) Write(msg);
- }
+ /// Plugin system: loader, manager, lifecycle callbacks, plugin host Log lines.
+ internal static void Plugin(string msg) => WriteCategory(LogCategory.Plugin, msg);
/// UI / Avalonia overlay subsystem.
- internal static void UI(string msg)
- {
- if (UIEnabled) Write(msg);
- }
+ internal static void UI(string msg) => WriteCategory(LogCategory.UI, msg);
- /// Verbose-only log (any category). Only written when VerboseLogging is on.
- internal static void Verbose(string msg)
- {
- if (EntryPoint.VerboseLogging) Write(msg);
- }
+ /// Verbose detail (any subsystem). Debug by default; set the Verbose category to Info to see it in the normal log.
+ internal static void Verbose(string msg) => WriteCategory(LogCategory.Verbose, msg);
- /// Always-on log for critical / uncategorised messages (INFO).
- internal static void Info(string msg) => Write(msg);
+ /// Same as .
+ internal static void Debug(string msg) => WriteCategory(LogCategory.Verbose, msg);
+
+ /// Trace-level line: written only when the global level is Trace.
+ internal static void Trace(string msg) => WriteAt(EntryPoint.EngineLogLevel.Trace, msg);
+
+ /// Uncategorised line (General category, Info by default).
+ internal static void Info(string msg) => WriteCategory(LogCategory.General, msg);
+
+ /// Same as .
+ internal static void Warning(string msg) => Warn(msg);
// Most recent WRN/ERR text + when, surfaced via the GetEngineStatusJson host bridge so a stuck box
- // can be diagnosed remotely without reading the PC log.
+ // can be diagnosed remotely without reading the PC log. Recorded even when the line is filtered.
internal static volatile string? LastIssue;
internal static DateTime LastIssueUtc;
- /// Always-on WARN line — a recoverable problem worth grepping for.
+ /// WARN line — a recoverable problem worth grepping for. Hidden only at level Error/Off.
internal static void Warn(string msg)
{
LastIssue = msg; LastIssueUtc = DateTime.UtcNow;
- EntryPoint.LogTagged("engine", msg, "WRN");
+ if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Warning))
+ EntryPoint.LogTagged("engine", msg, "WRN");
}
- /// Always-on ERROR line — a fault/crash/disable. Triage with grep "[ERR]".
+ /// Always-on ERROR line — a fault/crash/disable, written even at level Off. Triage with grep "[ERR]".
internal static void Error(string msg)
{
LastIssue = msg; LastIssueUtc = DateTime.UtcNow;
@@ -154,7 +139,24 @@ internal static class RynthLog
: $"thread {Environment.CurrentManagedThreadId}";
}
+ /// True when a line in would be written (guard expensive messages).
+ internal static bool IsEnabled(LogCategory category) => LogSettings.IsEnabled(category);
+
// ── Sink ─────────────────────────────────────────────────────────────
- private static void Write(string message) => EntryPoint.Log(message);
+ /// Uncategorised line (General category); used by the Move/UseDone traces.
+ private static void Write(string? message)
+ {
+ if (message != null)
+ WriteCategory(LogCategory.General, message);
+ }
+
+ private static void WriteCategory(LogCategory category, string message)
+ => WriteAt(LogSettings.LevelFor(category), message);
+
+ private static void WriteAt(EntryPoint.EngineLogLevel level, string message)
+ {
+ if (EntryPoint.ShouldLog(level))
+ EntryPoint.LogTagged("engine", message, LogSettings.Tag(level));
+ }
}
diff --git a/src/RynthCore.Engine/UI/Data/CharmsData.cs b/src/RynthCore.Engine/UI/Data/CharmsData.cs
new file mode 100644
index 0000000..3d3cac4
--- /dev/null
+++ b/src/RynthCore.Engine/UI/Data/CharmsData.cs
@@ -0,0 +1,78 @@
+// ============================================================================
+// RynthCore.Engine - UI/Data/CharmsData.cs
+// RynthAi's ACECustom charm tracker for the Settings panel's "Charms
+// Tracking" tab. RynthAi owns the charm registry (WCIDs, ability flags) and
+// the per-character "seen" memory; this side only shows the snapshot.
+// ============================================================================
+
+using System;
+using System.Runtime.InteropServices;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using RynthCore.Engine.Plugins;
+
+namespace RynthCore.Engine.UI.Data;
+
+/// RynthPluginGetCharmsJson's payload.
+internal sealed class CharmsInfo
+{
+ /// False off ILT-like worlds (or before RynthAi's ILT Hub exists).
+ [JsonPropertyName("available")] public bool Available { get; set; }
+ [JsonPropertyName("world")] public string World { get; set; } = "";
+ [JsonPropertyName("total")] public int Total { get; set; }
+ [JsonPropertyName("acquiredCount")] public int AcquiredCount { get; set; }
+ [JsonPropertyName("activeCount")] public int ActiveCount { get; set; }
+ [JsonPropertyName("charms")] public CharmRow[] Charms { get; set; } = Array.Empty();
+}
+
+internal sealed class CharmRow
+{
+ [JsonPropertyName("name")] public string Name { get; set; } = "";
+ [JsonPropertyName("effect")] public string Effect { get; set; } = "";
+ /// "carried" (in pack / equipped now), "seen" (carried before, now elsewhere) or "no".
+ [JsonPropertyName("acquired")] public string Acquired { get; set; } = "no";
+ /// Copies carried right now.
+ [JsonPropertyName("count")] public int Count { get; set; }
+ /// Best tier carried or last seen; 0 until an appraisal reports it.
+ [JsonPropertyName("tier")] public int Tier { get; set; }
+ [JsonPropertyName("maxTier")] public int MaxTier { get; set; }
+ /// Ability toggled on: "on", "off" or "unknown".
+ [JsonPropertyName("active")] public string Active { get; set; } = "unknown";
+ /// Server-side global switch as far as the client has learned it: "on", "off" or "unknown".
+ [JsonPropertyName("server")] public string Server { get; set; } = "unknown";
+ /// yyyy-MM-dd the charm was last carried (empty when never).
+ [JsonPropertyName("lastSeen")] public string LastSeen { get; set; } = "";
+}
+
+[JsonSerializable(typeof(CharmsInfo))]
+internal sealed partial class CharmsJsonContext : JsonSerializerContext { }
+
+///
+/// RynthPluginGetCharmsJson (single static buffer: one caller only) while the Settings panel
+/// is open. Every 2 s is plenty: charm state only changes when one is picked up or toggled.
+///
+internal sealed unsafe class CharmsSource : UiSource
+{
+ private delegate* unmanaged[Cdecl] _getCharmsJson;
+
+ public CharmsSource() : base("Charms", periodMs: 2000) { }
+
+ protected internal override void Poll()
+ {
+ if (_getCharmsJson == null)
+ _getCharmsJson = (delegate* unmanaged[Cdecl])PluginExportBinder.Resolve("RynthAi", "RynthPluginGetCharmsJson");
+ if (_getCharmsJson == null) return;
+ IntPtr p = _getCharmsJson();
+ string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}";
+ CharmsInfo info;
+ try { info = JsonSerializer.Deserialize(json, CharmsJsonContext.Default.CharmsInfo) ?? new CharmsInfo(); }
+ catch (JsonException) { info = new CharmsInfo(); }
+ Publish(info);
+ }
+
+ protected internal override void Reset()
+ {
+ _getCharmsJson = null;
+ ClearSnapshot();
+ }
+}
diff --git a/src/RynthCore.Engine/UI/Data/NavData.cs b/src/RynthCore.Engine/UI/Data/NavData.cs
index a659d3d..e6976b9 100644
--- a/src/RynthCore.Engine/UI/Data/NavData.cs
+++ b/src/RynthCore.Engine/UI/Data/NavData.cs
@@ -40,6 +40,17 @@ internal sealed class NavPayload
public int ActiveNavIndex { get; set; }
public List NavFiles { get; set; } = new();
public List Points { get; set; } = new();
+ /// RynthAi records (and draws) the walked breadcrumb trail. Older plugins omit it (false).
+ public bool TrackBreadcrumbs { get; set; }
+ /// RynthAi draws the route overlay (rings / lines, waypoint labels, guide line).
+ public bool ShowRouteOverlay { get; set; }
+ /// Route recording is on (points are added as you walk). Older plugins omit it.
+ public bool IsRecording { get; set; }
+ /// Breadcrumb trail size, for "Trail to route" / "Backtrack".
+ public int TrailPoints { get; set; }
+ public double TrailYards { get; set; }
+ /// The last route edit's result, for a few seconds after it (empty otherwise).
+ public string EditStatus { get; set; } = string.Empty;
/// A copy a face may change (its own point list); the points themselves are shared.
public NavPayload Clone()
@@ -60,6 +71,12 @@ internal sealed class NavCmd
public int InsertAt { get; set; } = -1;
public string NavName { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty; // addChat
+ public bool On { get; set; } // setBreadcrumbs / setRouteOverlay / setRecording
+ public List? Indices { get; set; } // movePoints / duplicatePoints / deletePoints
+ public int Delta { get; set; } // movePoints: -1 up, +1 down
+ public double Seconds { get; set; } // addPause
+ public double Yards { get; set; } // simplifyRoute tolerance
+ public bool Reverse { get; set; } // trailToRoute: backtrack
}
[JsonSerializable(typeof(NavPayload))]
@@ -105,6 +122,19 @@ internal static class NavCommands
public static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" };
public static readonly string[] AddModes = { "End", "Above", "Below" };
+ public static readonly double[] PauseSeconds = { 1, 2, 3, 5, 10, 15, 30, 60 };
+ public static readonly string[] PauseLabels = Array.ConvertAll(PauseSeconds, s => $"Pause {s:0} s");
+
+ public static readonly double[] SimplifyYards = { 0.5, 1, 2, 3, 5 };
+ public static readonly string[] SimplifyLabels =
+ Array.ConvertAll(SimplifyYards, y => $"Drop points within {y:0.#} yd of a straight line");
+
+ public static readonly string[] TrailChoices =
+ {
+ "Replace route with the trail (walk it again)",
+ "Replace route with a backtrack (walk it back)",
+ };
+
/// Route picker index for the plugin's RouteType (1 Circular, 2 Linear, 3 Follow, else Once).
public static int RouteIndex(int routeType) => routeType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 };
diff --git a/src/RynthCore.Engine/UI/Data/ProgressionData.cs b/src/RynthCore.Engine/UI/Data/ProgressionData.cs
new file mode 100644
index 0000000..4c31042
--- /dev/null
+++ b/src/RynthCore.Engine/UI/Data/ProgressionData.cs
@@ -0,0 +1,148 @@
+// ============================================================================
+// RynthCore.Engine - UI/Data/ProgressionData.cs
+// RynthAi's ILT progression planners (augmentations, enlightenment) and the
+// infinite-attribute raiser for the Skills panel's Progression tab. RynthAi owns the math and the persisted
+// inputs; this side only shows the snapshot and sends "prog ..." remote
+// commands (RynthAiCommands.ApplyRemoteCommand) for edits and actions.
+// ============================================================================
+
+using System;
+using System.Runtime.InteropServices;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using RynthCore.Engine.Plugins;
+
+namespace RynthCore.Engine.UI.Data;
+
+/// RynthPluginGetProgressionJson's payload. Display strings arrive preformatted.
+internal sealed class ProgressionInfo
+{
+ /// False off ILT-like worlds (or before the ILT Hub exists): the tab is hidden.
+ [JsonPropertyName("available")] public bool Available { get; set; }
+ [JsonPropertyName("world")] public string World { get; set; } = "";
+ [JsonPropertyName("aug")] public AugPlanner Aug { get; set; } = new();
+ [JsonPropertyName("enl")] public EnlPlanner Enl { get; set; } = new();
+ /// Absent from an older RynthAi: stays empty and the section shows "update RynthAi".
+ [JsonPropertyName("attr")] public AttrRaiser? Attr { get; set; }
+}
+
+/// RynthAi's IltAttributeRaiser: server costs ("/xp all") and the raise settings.
+internal sealed class AttrRaiser
+{
+ /// The raiser can't run here; says why.
+ [JsonPropertyName("off")] public bool Off { get; set; }
+ [JsonPropertyName("reason")] public string Reason { get; set; } = "";
+ [JsonPropertyName("auto")] public bool Auto { get; set; }
+ /// Minutes between auto-raise runs.
+ [JsonPropertyName("every")] public int Every { get; set; } = 5;
+ /// 0 priority, 1 round robin, 2 cheapest first.
+ [JsonPropertyName("mode")] public int Mode { get; set; }
+ [JsonPropertyName("running")] public bool Running { get; set; }
+ /// XP reserve, preformatted ("0", "1.50B").
+ [JsonPropertyName("keep")] public string Keep { get; set; } = "0";
+ /// XP reserve in full ("1,234,567"): what the reserve box edits.
+ [JsonPropertyName("keepFull")] public string KeepFull { get; set; } = "";
+ [JsonPropertyName("status")] public string Status { get; set; } = "";
+ [JsonPropertyName("lastRun")] public string LastRun { get; set; } = "";
+ [JsonPropertyName("unassigned")] public string Unassigned { get; set; } = "";
+ /// Time to the next auto run ("" when auto is off).
+ [JsonPropertyName("next")] public string Next { get; set; } = "";
+ [JsonPropertyName("costsAge")] public string CostsAge { get; set; } = "";
+ /// In raise-priority order.
+ [JsonPropertyName("rows")] public AttrRow[] Rows { get; set; } = Array.Empty();
+}
+
+internal sealed class AttrRow
+{
+ /// /attr abbreviation: str end coo qui foc sel hea sta man.
+ [JsonPropertyName("key")] public string Key { get; set; } = "";
+ [JsonPropertyName("label")] public string Label { get; set; } = "";
+ [JsonPropertyName("vital")] public bool Vital { get; set; }
+ /// Ticked: "Raise now" and auto-raise may spend on it.
+ [JsonPropertyName("on")] public bool On { get; set; }
+ /// Base value RynthAi last saw in a server reply (-1 = unknown; the panel prefers the client's).
+ [JsonPropertyName("base")] public int Base { get; set; } = -1;
+ /// Next-level cost from "/xp all", preformatted ("?" until read).
+ [JsonPropertyName("cost")] public string Cost { get; set; } = "?";
+ [JsonPropertyName("afford")] public bool Afford { get; set; }
+}
+
+internal sealed class AugPlanner
+{
+ /// The server reports /aug off.
+ [JsonPropertyName("off")] public bool Off { get; set; }
+ [JsonPropertyName("status")] public string Status { get; set; } = "";
+ [JsonPropertyName("lumPerCoin")] public long LumPerCoin { get; set; }
+ [JsonPropertyName("rows")] public AugRow[] Rows { get; set; } = Array.Empty();
+ [JsonPropertyName("total")] public string Total { get; set; } = "";
+ /// Empty when the bank holds enough Enlightened Coins.
+ [JsonPropertyName("short")] public string Short { get; set; } = "";
+ [JsonPropertyName("banked")] public string Banked { get; set; } = "";
+}
+
+internal sealed class AugRow
+{
+ [JsonPropertyName("key")] public string Key { get; set; } = "";
+ [JsonPropertyName("label")] public string Label { get; set; } = "";
+ [JsonPropertyName("cur")] public int Current { get; set; }
+ [JsonPropertyName("tgt")] public int Target { get; set; }
+ /// Highest target allowed (the aug's cap, or the current level when the server reports more).
+ [JsonPropertyName("cap")] public int Cap { get; set; }
+ [JsonPropertyName("lum")] public string Lum { get; set; } = "-";
+ [JsonPropertyName("coins")] public long Coins { get; set; }
+}
+
+internal sealed class EnlPlanner
+{
+ /// The server reports /enl off.
+ [JsonPropertyName("off")] public bool Off { get; set; }
+ [JsonPropertyName("header")] public string Header { get; set; } = "";
+ [JsonPropertyName("next")] public string Next { get; set; } = "";
+ [JsonPropertyName("enl")] public int Level { get; set; }
+ [JsonPropertyName("target")] public int Target { get; set; }
+ [JsonPropertyName("plan")] public string[] Plan { get; set; } = Array.Empty();
+ [JsonPropertyName("coinsPerToken")] public int CoinsPerToken { get; set; }
+ [JsonPropertyName("tokensShort")] public string TokensShort { get; set; } = "";
+ /// Client-side requirements not yet met; empty = the client checks pass.
+ [JsonPropertyName("blockers")] public string[] Blockers { get; set; } = Array.Empty();
+ [JsonPropertyName("serverChecks")] public string ServerChecks { get; set; } = "";
+ [JsonPropertyName("auto")] public bool Auto { get; set; }
+ /// Auto-enlighten is disarmed every session until confirmed again.
+ [JsonPropertyName("armed")] public bool Armed { get; set; }
+ [JsonPropertyName("spendFirst")] public bool SpendFirst { get; set; }
+ [JsonPropertyName("checkEvery")] public int CheckEvery { get; set; }
+ [JsonPropertyName("status")] public string Status { get; set; } = "";
+}
+
+[JsonSerializable(typeof(ProgressionInfo))]
+internal sealed partial class ProgressionJsonContext : JsonSerializerContext { }
+
+///
+/// RynthPluginGetProgressionJson (single static buffer: one caller only) while the Skills
+/// panel is open, and right after each Progression edit (RequestRefreshAfterPluginTick).
+///
+internal sealed unsafe class ProgressionSource : UiSource
+{
+ private delegate* unmanaged[Cdecl] _getProgressionJson;
+
+ public ProgressionSource() : base("Progression", periodMs: 1000) { }
+
+ protected internal override void Poll()
+ {
+ if (_getProgressionJson == null)
+ _getProgressionJson = (delegate* unmanaged[Cdecl])PluginExportBinder.Resolve("RynthAi", "RynthPluginGetProgressionJson");
+ if (_getProgressionJson == null) return;
+ IntPtr p = _getProgressionJson();
+ string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}";
+ ProgressionInfo info;
+ try { info = JsonSerializer.Deserialize(json, ProgressionJsonContext.Default.ProgressionInfo) ?? new ProgressionInfo(); }
+ catch (JsonException) { info = new ProgressionInfo(); }
+ Publish(info);
+ }
+
+ protected internal override void Reset()
+ {
+ _getProgressionJson = null;
+ ClearSnapshot();
+ }
+}
diff --git a/src/RynthCore.Engine/UI/Data/RynthAiData.cs b/src/RynthCore.Engine/UI/Data/RynthAiData.cs
index 28d58f2..4f02cb4 100644
--- a/src/RynthCore.Engine/UI/Data/RynthAiData.cs
+++ b/src/RynthCore.Engine/UI/Data/RynthAiData.cs
@@ -265,6 +265,7 @@ internal static unsafe class RynthAiCommands
private static delegate* unmanaged[Cdecl] _adjustOpacity;
private static delegate* unmanaged[Cdecl] _togglePanelLock;
private static delegate* unmanaged[Cdecl] _sendNavCommand;
+ private static delegate* unmanaged[Cdecl] _applyRemoteCommand;
static RynthAiCommands()
{
@@ -272,6 +273,7 @@ internal static unsafe class RynthAiCommands
{
_toggleMacro = null; _setSubsystemEnabled = null; _selectProfile = null; _forceRebuff = null;
_cancelForceRebuff = null; _adjustOpacity = null; _togglePanelLock = null; _sendNavCommand = null;
+ _applyRemoteCommand = null;
};
}
@@ -341,6 +343,29 @@ internal static unsafe class RynthAiCommands
if (refreshPatrol) UiSources.Patrol.RequestRefresh();
UiSources.Nav.RequestRefresh(); // the plugin applied it: the Nav panels show it next poll
});
+
+ ///
+ /// RynthPluginApplyRemoteCommand(action, value) - the same (action, value) pairs as the
+ /// plugin's /ra chat commands ("huds","show"; "remote","toggle"; "hub","show" ...).
+ /// Older RynthAi builds without the export drop the command (logged once per bind miss).
+ ///
+ public static void ApplyRemoteCommand(string action, string value) => Run("remote command " + action, () =>
+ {
+ if (_applyRemoteCommand == null) _applyRemoteCommand = (delegate* unmanaged[Cdecl])Export("RynthPluginApplyRemoteCommand");
+ if (_applyRemoteCommand == null)
+ {
+ RynthLog.UI($"RynthAiCommands: RynthPluginApplyRemoteCommand not exported; dropped '{action} {value}'.");
+ return;
+ }
+ IntPtr a = Marshal.StringToHGlobalAnsi(action);
+ IntPtr b = Marshal.StringToHGlobalAnsi(value);
+ try { _applyRemoteCommand(a, b); }
+ finally
+ {
+ Marshal.FreeHGlobal(a);
+ Marshal.FreeHGlobal(b);
+ }
+ });
}
/// RynthPluginGetPatrolInfoJson's payload (patrol flyout).
diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs
index 3b5c6f4..81508bd 100644
--- a/src/RynthCore.Engine/UI/Data/SettingsData.cs
+++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs
@@ -11,6 +11,7 @@
// ============================================================================
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
@@ -47,6 +48,13 @@ internal sealed class RynthAiSettings
// Decal bridge: stop RynthAi's macro when VTank's starts (one bot per client). Default on;
// an older RynthAi doesn't send it, and a missing field must not read as "off".
public bool YieldToVTank { get; set; } = true;
+ // Server Features (RynthAi ServerFeatureGate): world names that turn on the ILT Hub, the
+ // Progression planners and the attribute raiser, plus a manual override. An older RynthAi
+ // doesn't send them; RynthAi lays a save over its current values, so these defaults are
+ // only ever shown, never applied. ServerFeaturesStatus is read-only (RynthAi ignores it).
+ public string FeatureServerNames { get; set; } = "InfiniteLeaftide, *Leaftide*";
+ public bool ForceServerFeatures { get; set; }
+ public string ServerFeaturesStatus { get; set; } = string.Empty;
public bool EnableRaycasting { get; set; }
public bool UseArcs { get; set; }
public float BowArcVelocity { get; set; } = 25f;
@@ -219,6 +227,15 @@ internal sealed class RynthAiSettings
public int SalvageSalvageDelayMs { get; set; } = 50;
public int SalvageResultDelayFirstMs { get; set; } = 1000;
public int SalvageResultDelayFastMs { get; set; } = 250;
+ // Ground loot
+ public bool EnableGroundLoot { get; set; }
+ // Diagnostics (RynthAi's RynthLog: per PC in Logs\Diagnostics\diagnostics.json, not the profile)
+ public bool DiagDebugToChat { get; set; }
+ public bool DiagFileLogAll { get; set; } = true;
+ /// "Name=Level" per trace category, ','-joined; Level 0 Off, 1 Trace, 2 Info. See .
+ public string DiagCategories { get; set; } = string.Empty;
+ /// Read-only (RynthAi ignores it on save): the diagnostics folder.
+ public string DiagFolder { get; set; } = string.Empty;
/// A private copy for a face to edit (all members are values or strings).
public RynthAiSettings Clone() => (RynthAiSettings)MemberwiseClone();
@@ -289,7 +306,60 @@ internal static unsafe class SettingsCommands
// ── Schema ─────────────────────────────────────────────────────────────────
-internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus }
+internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status }
+
+///
+/// Reads and edits ("Name=Level,..."). The category
+/// list comes from RynthAi, so a category it adds shows up without an engine change.
+///
+internal static class TraceCategoryLevels
+{
+ public const int Off = 0, Trace = 1, Info = 2;
+
+ /// The categories in RynthAi's order; malformed entries are skipped.
+ public static List<(string Name, int Level)> Parse(string? levels)
+ {
+ var list = new List<(string, int)>();
+ if (string.IsNullOrWhiteSpace(levels)) return list;
+ foreach (string entry in levels.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ int eq = entry.IndexOf('=');
+ if (eq <= 0 || !int.TryParse(entry[(eq + 1)..], out int level)) continue;
+ list.Add((entry[..eq], Math.Clamp(level, Off, Info)));
+ }
+ return list;
+ }
+
+ private static string Format(List<(string Name, int Level)> list)
+ {
+ var parts = new string[list.Count];
+ for (int i = 0; i < list.Count; i++) parts[i] = list[i].Name + "=" + list[i].Level;
+ return string.Join(",", parts);
+ }
+
+ ///
+ /// Turns tracing on or off for one category (empty with a
+ /// : every category starting with it; both empty: all). On keeps
+ /// a category already at Info at Info, the same rule as /ra trace.
+ ///
+ public static string Set(string? levels, string name, bool on, string prefix = "")
+ {
+ List<(string Name, int Level)> list = Parse(levels);
+ for (int i = 0; i < list.Count; i++)
+ {
+ var (n, level) = list[i];
+ bool match = name.Length > 0
+ ? string.Equals(n, name, StringComparison.OrdinalIgnoreCase)
+ : n.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
+ if (!match) continue;
+ list[i] = (n, !on ? Off : level == Off ? Trace : level);
+ }
+ return Format(list);
+ }
+
+ /// Checkbox label: the name, plus " +log" at Info (trace lines also go to the normal log).
+ public static string Label(string name, int level) => level == Info ? name + " +log" : name;
+}
///
/// One row of a settings tab. Numeric values go through double (bools as
@@ -307,7 +377,15 @@ internal sealed record SettingRow(
double Step = 1,
string[]? Items = null,
Func? VisibleWhen = null,
- bool Gates = false)
+ bool Gates = false,
+ // Button rows: the button's caption (Label is the row label) and its action. Any thread.
+ string? ButtonText = null,
+ Action? Click = null,
+ // Text rows: the string value (committed on Enter / focus loss); Status rows: GetText only.
+ Func? GetText = null,
+ Action? SetText = null,
+ // Text rows: greyed hint shown while the box is empty.
+ string? Hint = null)
{
public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s);
}
@@ -387,6 +465,17 @@ internal static class SettingsSchema
private static SettingRow Note(string text, Func? when = null) =>
new(SettingKind.Note, text, VisibleWhen: when);
+ private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) =>
+ new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click);
+
+ private static SettingRow Text(string label, Func get, Action set,
+ string? tip = null, string? hint = null) =>
+ new(SettingKind.Text, label, tip, GetText: get, SetText: set, Hint: hint);
+
+ // A one-line status RynthAi computes (read-only; empty = hidden).
+ private static SettingRow Status(Func get) =>
+ new(SettingKind.Status, "", GetText: get, VisibleWhen: s => !string.IsNullOrEmpty(get(s)));
+
private static SettingRow[] Tiers(Func[] get, Action[] set)
{
var rows = new SettingRow[get.Length];
@@ -538,6 +627,17 @@ internal static class SettingsSchema
"With Decal: when VTank's macro starts (/vt start), RynthAi's macro stops, and it won't start while VTank runs.\nOne bot per client. Without Decal this does nothing. Also: /ra vtankyield on|off."),
Bool("Enable Raycasting", s => s.EnableRaycasting, (s, v) => s.EnableRaycasting = v),
Spacer(),
+ Section("Server Features (ILT / infinite attributes)"),
+ Status(s => s.ServerFeaturesStatus),
+ Text("Servers", s => s.FeatureServerNames, (s, v) => s.FeatureServerNames = v,
+ "Comma-separated world names that turn on the ILT Hub, the Skills panel's Progression planners\n" +
+ "and the attribute raiser. * is a wildcard (*Leaftide* matches any name containing Leaftide).\n" +
+ "Case does not matter. Saved with the RynthAi profile.",
+ hint: "InfiniteLeaftide, *Leaftide*"),
+ Bool("Force enable on this server (manual override)", s => s.ForceServerFeatures, (s, v) => s.ForceServerFeatures = v,
+ "Turn the features on for whatever world you are on, even if it is not in the list.\n" +
+ "Each feature still follows what the server reports (for example /xp off keeps the attribute raiser off)."),
+ Spacer(),
Section("Missile Arc Velocities (m/s)"),
Bool("Use Arcs for Missile LoS", s => s.UseArcs, (s, v) => s.UseArcs = v,
"A missile target must pass both the straight line and the real arrow arc, ceilings included (dungeons too).\nWhen off, all missile LoS checks are linear (eye-to-eye).", gates: true),
@@ -782,6 +882,8 @@ internal static class SettingsSchema
"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),
Int("Jump Height", s => s.LootJumpHeight, (s, v) => s.LootJumpHeight = v, 1, 100, 5, when: s => s.LootJumpEnabled),
+ Bool("Loot Items On Ground", s => s.EnableGroundLoot, (s, v) => s.EnableGroundLoot = v,
+ "Pick up loose items on the ground that match your loot profile, within Corpse Max range.\nCorpses always come first. Status and rescan: /ra groundloot."),
Spacer(),
Section("Corpse Ownership"),
Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v),
@@ -800,6 +902,8 @@ internal static class SettingsSchema
"After the salvage queue empties, move same-name bags together so the server merges them."),
Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v,
"When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."),
+ Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"),
+ "Opens the item count HUD / Mini Remote setup window (/ra huds)."),
Spacer(),
Section("Loot Timers (ms)"),
Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25),
@@ -842,5 +946,24 @@ internal static class SettingsSchema
Spacer(),
Note("Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match."),
}),
+
+ new("Diagnostics", new[]
+ {
+ Section("Logging & Debugging"),
+ Bool("Debug to chat", s => s.DiagDebugToChat, (s, v) => s.DiagDebugToChat = v,
+ "Echo trace lines and errors from the categories ticked below into the chat window.\nAlso: /ra debug on|off."),
+ Bool("Daily RynthAi log file", s => s.DiagFileLogAll, (s, v) => s.DiagFileLogAll = v,
+ "Mirror every RynthAi log line to rynthai_.txt in the log folder (kept 7 days).\nAlso: /ra logs file on|off."),
+ Button("Log Folder", "Open", () => RynthAiCommands.ApplyRemoteCommand("logs", "open"),
+ "Open RynthAi's Logs\\Diagnostics folder in Explorer (/ra logs open)."),
+ Button("Old Log Files", "Prune", () => RynthAiCommands.ApplyRemoteCommand("logs", "prune"),
+ "Delete diagnostics files past the retention limit now (/ra logs prune)."),
+ Spacer(),
+ Section("Trace Per Category"),
+ new SettingRow(SettingKind.TraceCategories, "Categories",
+ "Ticked categories write their trace lines to Trace\\_.txt (/ra trace on|off)."),
+ Note("+log = the category is at Info: its trace lines also go to the normal log. The launcher's Logging page sets Off, Trace or Info."),
+ Note("Exceptions always go to exceptions_.txt with full stack traces (throttled). Settings here are for this PC, not the profile."),
+ }),
};
}
diff --git a/src/RynthCore.Engine/UI/Data/UiSources.cs b/src/RynthCore.Engine/UI/Data/UiSources.cs
index a4cdd47..4be0072 100644
--- a/src/RynthCore.Engine/UI/Data/UiSources.cs
+++ b/src/RynthCore.Engine/UI/Data/UiSources.cs
@@ -16,6 +16,8 @@ internal static class UiSources
public static readonly TrackerSource Tracker = new();
public static readonly RynthAiSource RynthAi = new();
public static readonly PatrolSource Patrol = new();
+ public static readonly ProgressionSource Progression = new();
+ public static readonly CharmsSource Charms = new();
public static readonly RadarSource Radar = new();
public static readonly SettingsSource Settings = new();
public static readonly MetaSource Meta = new();
@@ -52,6 +54,8 @@ internal static class UiSources
UiDataHub.Register(Radar);
UiDataHub.Register(RynthAi);
UiDataHub.Register(Patrol);
+ UiDataHub.Register(Progression);
+ UiDataHub.Register(Charms);
UiDataHub.Register(PluginStatus);
UiDataHub.Register(Log);
UiDataHub.Register(Tracker);
diff --git a/src/RynthCore.Engine/UI/LayeredWindow.cs b/src/RynthCore.Engine/UI/LayeredWindow.cs
index e3d168e..9539cd8 100644
--- a/src/RynthCore.Engine/UI/LayeredWindow.cs
+++ b/src/RynthCore.Engine/UI/LayeredWindow.cs
@@ -367,6 +367,25 @@ internal sealed unsafe class LayeredWindow : IDisposable
}
}
+ ///
+ /// The content rects (screen px: left, top, width, height) of every visible panel window.
+ /// They sit above the game window, so nothing drawn in the game frame can show over them.
+ ///
+ internal static List<(int Left, int Top, int Width, int Height)> VisibleContentRects()
+ {
+ LayeredWindow[] windows;
+ lock (_instancesLock)
+ {
+ windows = new LayeredWindow[_instances.Count];
+ _instances.Values.CopyTo(windows, 0);
+ }
+ var rects = new List<(int, int, int, int)>(windows.Length);
+ foreach (LayeredWindow w in windows)
+ if (w.IsVisible && w.Width > 0 && w.Height > 0)
+ rects.Add((w.ScreenLeft, w.ScreenTop, w.Width, w.Height));
+ return rects;
+ }
+
private static readonly HashSet _sweptLogged = new();
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
diff --git a/src/RynthCore.Engine/UI/Panels/NavPanel.cs b/src/RynthCore.Engine/UI/Panels/NavPanel.cs
index d69153c..62d46be 100644
--- a/src/RynthCore.Engine/UI/Panels/NavPanel.cs
+++ b/src/RynthCore.Engine/UI/Panels/NavPanel.cs
@@ -171,9 +171,29 @@ internal static class NavPanel
{ e.Handled = true; picker.Close(); }
};
+ // Waypoint list controls live for the panel's lifetime. Rebuild() only refills
+ // waypointStack: a ScrollViewer recreated (or given a new Content) resets its
+ // offset to the top, which made the list jump back every poll and impossible to edit.
+ var waypointStack = new StackPanel { Spacing = 1 };
+ var waypointScroll = new ScrollViewer
+ {
+ VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
+ HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
+ Content = waypointStack,
+ };
+ var waypointHost = new Border { Height = 200, Child = waypointScroll };
+
+ // Last plugin JSON the panel was built from. A rebuild from a user action
+ // (optimistic local edit) clears it so the next poll always resyncs with the plugin.
+ string lastJson = string.Empty;
+ bool rebuildFromPoll = false;
+
void Rebuild()
{
+ if (!rebuildFromPoll) lastJson = string.Empty;
+ Vector keepOffset = waypointScroll.Offset;
content.Children.Clear();
+ waypointStack.Children.Clear();
var d = state.Data;
bool navActive = d.MacroRunning && d.NavigationEnabled;
@@ -439,7 +459,6 @@ internal static class NavPanel
FontSize = 10,
});
- var waypointStack = new StackPanel { Spacing = 1 };
for (int i = 0; i < d.Points.Count; i++)
{
int ci = i;
@@ -516,16 +535,10 @@ internal static class NavPanel
waypointStack.Children.Add(row);
}
- content.Children.Add(new Border
- {
- Height = 200,
- Child = new ScrollViewer
- {
- VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
- HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
- Content = waypointStack,
- },
- });
+ content.Children.Add(waypointHost); // same instance every rebuild — keeps scroll offset
+ // Re-apply after layout too: the re-attach / new row extent can coerce it to 0.
+ waypointScroll.Offset = keepOffset;
+ Dispatcher.UIThread.Post(() => waypointScroll.Offset = keepOffset, DispatcherPriority.Loaded);
}
// ── Poll timer ────────────────────────────────────────────────────────
@@ -536,6 +549,9 @@ internal static class NavPanel
timer.Tick += (_, _) =>
{
if (picker.ActivePicker != null || state.Typing) return;
+ // A rebuild between press and release eats the click on X / row select. seenVersion
+ // is left alone, so the change is picked up once the pointer leaves the list.
+ if (waypointHost.IsPointerOver) return;
var snap = UiSources.Nav.Current;
if (snap == null || snap.Version == seenVersion) return;
seenVersion = snap.Version;
diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs
index 914160a..df6f44e 100644
--- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs
+++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs
@@ -333,6 +333,25 @@ internal static class SettingsPanel
return SectionHeader(row.Label);
case SettingKind.Spacer:
return Spacer();
+ case SettingKind.Button:
+ return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip);
+ case SettingKind.TraceCategories:
+ return TraceCategoriesRow(state, row);
+ case SettingKind.Text:
+ return TextRow(row.Label, row.GetText?.Invoke(d) ?? string.Empty, row.Hint, v =>
+ {
+ row.SetText?.Invoke(state.Data, v);
+ Push(state);
+ }, row.Tooltip);
+ case SettingKind.Status:
+ {
+ string status = row.GetText?.Invoke(d) ?? string.Empty;
+ return status.Length == 0 ? null : new TextBlock
+ {
+ Text = status, Foreground = ColTeal, FontSize = 11,
+ TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 2),
+ };
+ }
case SettingKind.Note:
return new TextBlock
{
@@ -416,6 +435,53 @@ internal static class SettingsPanel
return row;
}
+ /// Label above a full-width text box; commits on Enter or focus loss when the text changed.
+ private static Control TextRow(string label, string value, string? hint, Action onChange, string? tooltip = null)
+ {
+ string committed = value;
+ var box = new StackPanel { Margin = new Thickness(0, 2, 0, 2) };
+ box.Children.Add(new TextBlock { Text = label, Foreground = ColTextDim, FontSize = 11, Margin = new Thickness(0, 0, 0, 2) });
+ var tb = new TextBox
+ {
+ Text = value,
+ Watermark = hint,
+ FontSize = 11,
+ Height = 22,
+ Padding = new Thickness(4, 2),
+ Background = ColPanelBg,
+ Foreground = ColAmber,
+ BorderBrush = ColBtnBord,
+ BorderThickness = new Thickness(1),
+ VerticalContentAlignment = VerticalAlignment.Center,
+ };
+ DisableInnerScroll(tb);
+ void Commit()
+ {
+ string text = tb.Text ?? string.Empty;
+ if (string.Equals(text, committed, StringComparison.Ordinal)) return;
+ committed = text;
+ onChange(text);
+ }
+ // Same keyboard gate as the number boxes: typed keys go to Avalonia, not the game.
+ tb.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
+ tb.LostFocus += (_, _) =>
+ {
+ Win32Backend.AvaloniaTextInputActive = false;
+ Commit();
+ };
+ tb.KeyDown += (_, e) =>
+ {
+ if (e.Key == Avalonia.Input.Key.Enter) Commit();
+ };
+ box.Children.Add(tb);
+ if (tooltip != null)
+ {
+ ToolTip.SetTip(box, tooltip);
+ ToolTip.SetShowDelay(box, 400);
+ }
+ return box;
+ }
+
private static Control IntRow(string label, int value, int min, int max, int step, Action onChange, string? tooltip = null)
{
int current = Math.Clamp(value, min, max);
@@ -699,6 +765,96 @@ internal static class SettingsPanel
return row;
}
+ /// Label on the left, a single action button on the right.
+ private static Control ButtonRow(string label, string buttonText, Action onClick, string? tooltip = null)
+ {
+ var btn = new Button
+ {
+ Content = buttonText,
+ FontSize = 10,
+ Height = 20,
+ MinWidth = 160,
+ Padding = new Thickness(4, 1),
+ Background = ColBtnFill,
+ Foreground = ColTextDim,
+ BorderBrush = ColBtnBord,
+ BorderThickness = new Thickness(1),
+ HorizontalContentAlignment = HorizontalAlignment.Center,
+ };
+ btn.Click += (_, _) => onClick();
+
+ var row = new Grid
+ {
+ ColumnDefinitions = new ColumnDefinitions("*,Auto"),
+ Margin = new Thickness(0, 2, 0, 2),
+ Height = 22,
+ };
+ var lblBlock = new TextBlock { Text = label, Foreground = ColTextDim, FontSize = 11, VerticalAlignment = VerticalAlignment.Center };
+ Grid.SetColumn(lblBlock, 0);
+ Grid.SetColumn(btn, 1);
+ row.Children.Add(lblBlock);
+ row.Children.Add(btn);
+
+ if (tooltip != null)
+ {
+ ToolTip.SetTip(row, tooltip);
+ ToolTip.SetShowDelay(row, 400);
+ }
+ return row;
+ }
+
+ ///
+ /// [All on] [All off] [ILT Hub on] over a 3-column grid of toggles, one per RynthAi trace
+ /// category. Each change edits DiagCategories, saves, and rebuilds the tab so the grid redraws.
+ ///
+ private static Control TraceCategoriesRow(PanelState state, SettingRow row)
+ {
+ var cats = TraceCategoryLevels.Parse(state.Data.DiagCategories);
+ if (cats.Count == 0)
+ return new TextBlock { Text = "Waiting for RynthAi...", Foreground = ColMute, FontSize = 10, Margin = new Thickness(0, 2, 0, 0) };
+
+ void Save(string levels)
+ {
+ state.Data.DiagCategories = levels;
+ Push(state);
+ state.Rebuild?.Invoke();
+ }
+
+ Button Bulk(string text, Func next)
+ {
+ var b = new Button
+ {
+ Content = text, FontSize = 10, Height = 20, Padding = new Thickness(6, 1),
+ Background = ColBtnFill, Foreground = ColTextDim, BorderBrush = ColBtnBord, BorderThickness = new Thickness(1),
+ };
+ b.Click += (_, _) => Save(next());
+ return b;
+ }
+
+ var box = new StackPanel { Margin = new Thickness(0, 2, 0, 2) };
+ var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 0, 0, 4) };
+ buttons.Children.Add(Bulk("All on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true)));
+ buttons.Children.Add(Bulk("All off", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", false)));
+ buttons.Children.Add(Bulk("ILT Hub on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true, "Ilt")));
+ if (row.Tooltip != null)
+ {
+ ToolTip.SetTip(buttons, row.Tooltip);
+ ToolTip.SetShowDelay(buttons, 400);
+ }
+ box.Children.Add(buttons);
+
+ var grid = new Avalonia.Controls.Primitives.UniformGrid { Columns = 3 };
+ foreach (var (name, level) in cats)
+ {
+ string catName = name;
+ bool on = level != TraceCategoryLevels.Off;
+ grid.Children.Add(BoolRow(TraceCategoryLevels.Label(name, level), on,
+ v => Save(TraceCategoryLevels.Set(state.Data.DiagCategories, catName, v))));
+ }
+ box.Children.Add(grid);
+ return box;
+ }
+
// SimpleTheme wraps TextBox content in a ScrollViewer, and its vertical
// scrollbar's up RepeatButton is a filled triangle Path. On these short
// (Height=20) single-line numeric fields that scrollbar shows and the
diff --git a/src/RynthCore.Injector/LaunchCommand.cs b/src/RynthCore.Injector/LaunchCommand.cs
index 9039176..f1059f4 100644
--- a/src/RynthCore.Injector/LaunchCommand.cs
+++ b/src/RynthCore.Injector/LaunchCommand.cs
@@ -5,6 +5,7 @@ using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
+using RynthCore.Install;
namespace RynthCore.Injector;
@@ -37,7 +38,7 @@ internal static class LaunchCommand
{
// The "bulletproof" private AC copy intended for RynthCore launches — a
// separate DAT lock domain from the shared Turbine install.
- private const string PrivateAcClientPath = @"C:\Games\RynthCore\AcClient\acclient.exe";
+ private static readonly string PrivateAcClientPath = Path.Combine(RynthInstallPaths.CoreDir, "AcClient", "acclient.exe");
// Matches LaunchAccountProfile.NoneOption — explicit opt-out of auto-login.
private const string NoneOption = "(None — no auto-login)";
diff --git a/src/RynthCore.Injector/Program.cs b/src/RynthCore.Injector/Program.cs
index dec625f..1951ab1 100644
--- a/src/RynthCore.Injector/Program.cs
+++ b/src/RynthCore.Injector/Program.cs
@@ -2,6 +2,7 @@ using System;
using System.IO;
using System.Linq;
using System.Text;
+using RynthCore.Install;
namespace RynthCore.Injector;
diff --git a/src/RynthCore.Loader/EntryPoint.cs b/src/RynthCore.Loader/EntryPoint.cs
index e9329db..8f8412b 100644
--- a/src/RynthCore.Loader/EntryPoint.cs
+++ b/src/RynthCore.Loader/EntryPoint.cs
@@ -19,6 +19,7 @@ using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
+using RynthCore.Install;
namespace RynthCore.Loader;
diff --git a/src/RynthCore.StatusAgent/AgentConfig.cs b/src/RynthCore.StatusAgent/AgentConfig.cs
index d18bc4e..78372e6 100644
--- a/src/RynthCore.StatusAgent/AgentConfig.cs
+++ b/src/RynthCore.StatusAgent/AgentConfig.cs
@@ -1,5 +1,6 @@
using System.Text.Json;
using System.Text.Json.Serialization;
+using RynthCore.Install;
namespace RynthCore.StatusAgent;