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/LauncherDiag.cs b/src/RynthCore.App.Avalonia/LauncherDiag.cs
index a73faf0..494e6d3 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;
@@ -18,7 +19,8 @@ namespace RynthCore.App.Avalonia;
///
internal static class LauncherDiag
{
- private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs";
+ // Installer-chosen RynthCore folder (falls back to C:\Games\RynthCore).
+ private static readonly string UnifiedLogDirectory = RynthInstallPaths.CoreLogsDir;
private const string UnifiedLogFileName = "RynthCore.log";
private static readonly object LogLock = new();
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 5a585cb..cecd02d 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 = RynthInstallPaths.ReadSetting("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();
+ RynthInstallPaths.DeleteUserSetting("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 (EngineSettings.LoggingLevel).
+ 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)
@@ -2988,7 +3118,7 @@ internal partial class MainWindow : Window
// Tail the per-PID log for the last heartbeat line. Cheap: seek to
// the end, read ~2KB, FileShare-tolerant of the engine's writer.
- string logPath = System.IO.Path.Combine(@"C:\Games\RynthCore\Logs", $"RynthCore.{pid}.log");
+ string logPath = System.IO.Path.Combine(RynthInstallPaths.CoreLogsDir, $"RynthCore.{pid}.log");
string tail;
try
{
diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj
index fdefb66..32276bc 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 @@
+
+
+
+
+
+
@@ -53,4 +67,9 @@
+
+
+
+
+
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.App/RynthInstallPaths.cs b/src/RynthCore.App/RynthInstallPaths.cs
new file mode 100644
index 0000000..ddf0554
--- /dev/null
+++ b/src/RynthCore.App/RynthInstallPaths.cs
@@ -0,0 +1,128 @@
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+
+namespace RynthCore.Install;
+
+///
+/// Resolves where RynthCore and RynthSuite are installed. The installer lets the user pick
+/// both folders and records them under Software\Rynth (HKCU for a per-user install,
+/// HKLM for an all-users install), so nothing may assume C:\Games\... any more.
+///
+/// Resolution order per folder: environment override (RYNTHCORE_DIR /
+/// RYNTHSUITE_DIR, for dev setups) → HKCU → HKLM (32-bit view, where the 32-bit
+/// installer writes) → the historical default under C:\Games. Results are cached
+/// for the life of the process.
+///
+/// Linked into every RynthCore project (Engine, Loader, Injector, launcher, StatusAgent);
+/// RynthSuite keeps an identical copy in Shared/RynthInstallPaths.cs — change both together.
+/// Registry access is a direct RegGetValueW P/Invoke so it works under NativeAOT and trimming
+/// without pulling in Microsoft.Win32.Registry.
+///
+internal static class RynthInstallPaths
+{
+ /// Default RynthCore folder (pre-2026.10.4.2 installs always used this).
+ public const string DefaultCoreDir = @"C:\Games\RynthCore";
+
+ /// Default RynthSuite folder (pre-2026.10.4.2 installs always used this).
+ public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
+
+ /// Registry key (under HKCU or HKLM) written by the installer.
+ public const string RegistryKey = @"Software\Rynth";
+
+ private static string? _coreDir;
+ private static string? _suiteDir;
+
+ /// RynthCore install folder (launcher, Runtime\, Logs\, Tools\).
+ public static string CoreDir => _coreDir ??= Resolve("RYNTHCORE_DIR", "CoreDir", DefaultCoreDir);
+
+ /// RynthSuite folder (plugins and their data, e.g. RynthAi\).
+ public static string SuiteDir => _suiteDir ??= Resolve("RYNTHSUITE_DIR", "SuiteDir", DefaultSuiteDir);
+
+ /// Unified RynthCore log folder (<CoreDir>\Logs).
+ public static string CoreLogsDir => Path.Combine(CoreDir, "Logs");
+
+ /// RynthAi plugin home and data root (<SuiteDir>\RynthAi).
+ public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi");
+
+ /// Reads a string value from Software\Rynth (HKCU first, then HKLM 32-bit view); null when absent.
+ public static string? ReadSetting(string valueName)
+ => ReadRegistryString(HKEY_CURRENT_USER, valueName, 0)
+ ?? ReadRegistryString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY);
+
+ /// Deletes a value from HKCU Software\Rynth (used for one-shot installer hand-offs). Best effort.
+ public static void DeleteUserSetting(string valueName)
+ {
+ try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RegistryKey, valueName); } catch { }
+ }
+
+ private static string Resolve(string envVar, string valueName, string fallback)
+ {
+ string? fromEnv = null;
+ try { fromEnv = Environment.GetEnvironmentVariable(envVar); } catch { }
+
+ foreach (string? candidate in new[] { fromEnv, ReadSetting(valueName) })
+ {
+ string? normalized = Normalize(candidate);
+ if (normalized != null) return normalized;
+ }
+ return fallback;
+ }
+
+ /// Accepts only absolute paths; trims whitespace, quotes and trailing separators.
+ private static string? Normalize(string? path)
+ {
+ if (string.IsNullOrWhiteSpace(path)) return null;
+ string p = path.Trim().Trim('"').TrimEnd('\\', '/');
+ if (p.Length == 2 && p[1] == ':') p += "\\"; // keep "D:" as the drive root "D:\"
+ try
+ {
+ if (!Path.IsPathFullyQualified(p)) return null;
+ string full = Path.GetFullPath(p);
+ return full.Length > 3 ? full.TrimEnd('\\') : full; // "D:\" stays a root
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
+ // ── Win32 registry (advapi32) ───────────────────────────────────────────
+
+ 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;
+
+ [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? ReadRegistryString(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, RegistryKey, valueName, flags, IntPtr.Zero, null, ref bytes) != ERROR_SUCCESS || bytes < 2)
+ return null;
+
+ var buffer = new char[(bytes + 1) / 2];
+ if (RegGetValueW(root, 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
+ {
+ // Missing advapi32 entry point or access denied — fall back to the defaults.
+ return null;
+ }
+ }
+}
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/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/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs
index a61602b..6c56e0e 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());
@@ -1634,10 +1684,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/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/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs
index 77193b7..e9d0dcf 100644
--- a/src/RynthCore.Engine/ImGui/Win32Backend.cs
+++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs
@@ -1025,11 +1025,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 ────────────────
@@ -1040,7 +1044,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)
@@ -1129,6 +1133,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);
}
@@ -1139,6 +1151,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 8cc3008..91095fb 100644
--- a/src/RynthCore.Engine/LogPaths.cs
+++ b/src/RynthCore.Engine/LogPaths.cs
@@ -21,13 +21,15 @@
using System;
using System.IO;
+using RynthCore.Install;
namespace RynthCore.Engine;
internal static class LogPaths
{
/// Unified log directory for all RynthCore components.
- internal const string LogDirectory = @"C:\Games\RynthCore\Logs";
+ // Installer-chosen RynthCore folder (registry Software\Rynth\CoreDir; falls back to C:\Games\RynthCore).
+ internal static readonly string LogDirectory = RynthInstallPaths.CoreLogsDir;
/// Shared launch/orchestration log (injector + launcher + per-engine session pointer).
internal const string SharedLogFileName = "RynthCore.log";
diff --git a/src/RynthCore.Engine/LogSettings.cs b/src/RynthCore.Engine/LogSettings.cs
new file mode 100644
index 0000000..cda2df7
--- /dev/null
+++ b/src/RynthCore.Engine/LogSettings.cs
@@ -0,0 +1,245 @@
+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;
+ 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: keep defaults for this pass; the next timestamp change retries.
+ globalText ??= EngineSettings.LoggingLevel;
+ }
+
+ 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 a9b1a31..1698fcd 100644
--- a/src/RynthCore.Engine/Plugins/EngineSettings.cs
+++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs
@@ -26,8 +26,10 @@ 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 string _loggingLevel = "Info";
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
private static bool _decalInGameImGui = true;
private static bool _decalStandDown = true;
@@ -178,6 +180,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
@@ -205,6 +220,18 @@ internal static class EngineSettings
}
}
+ /// Engine log threshold from engine.json "LoggingLevel", written by the launcher's
+ /// Logging level box: Error, Warning, Info (default), Debug/Verbose or Trace. Parsed by
+ /// EntryPoint.ParseLoggingLevel at init; unknown values fall back to Info.
+ public static string LoggingLevel
+ {
+ get
+ {
+ EnsureLoaded();
+ return _loggingLevel;
+ }
+ }
+
/// "DecalBridge" in engine.json: Auto (default), On or Off. Only matters when
/// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md):
/// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello
@@ -386,6 +413,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))
{
@@ -429,6 +462,14 @@ internal static class EngineSettings
_disabledUiHooks.Add(hookName.Trim());
}
}
+
+ if (doc.RootElement.TryGetProperty("LoggingLevel", out var logLevelEl) &&
+ logLevelEl.ValueKind == JsonValueKind.String)
+ {
+ string? configuredLevel = logLevelEl.GetString();
+ if (!string.IsNullOrWhiteSpace(configuredLevel))
+ _loggingLevel = configuredLevel;
+ }
}
catch (Exception ex)
{
@@ -459,8 +500,12 @@ 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);
+ // Preserve the launcher-chosen level; dropping it here would reset logging to Info.
+ w.WriteString("LoggingLevel", _loggingLevel);
+ CopyUnownedFields(w);
if (_decalBridgeMode != DecalBridgeMode.Auto) // default: leave the file as it was
w.WriteString("DecalBridge", _decalBridgeMode.ToString());
if (!_decalInGameImGui) // default true: leave the file as it was
@@ -485,6 +530,37 @@ internal static class EngineSettings
RynthLog.Plugin($"EngineSettings: Failed to save: {ex.Message}");
}
}
+
+ // Fields Save() writes itself; everything else in engine.json belongs to the launcher
+ // (LogCategories, EnableDcompOverlay, ...) and is copied through untouched.
+ private static readonly string[] OwnedFields =
+ {
+ "PluginPaths", "EnableImGuiShell", "EnablePlugins", "EnableDatShareHook", "EnableAvaloniaOverlay",
+ "EnableD3D9Hook", "EnableEngine", "EngineHookCount", "EnableImGuiBackend", "EnablePluginOverlayWindows",
+ "EnableHangMinidump", "DrawCustomVitalBars", "PreventIdleLogoff", "LoggingLevel",
+ // Save() writes these only when non-default, so copying them through would duplicate keys.
+ "DecalBridge", "DecalInGameImGui", "DecalStandDown",
+ };
+
+ /// Writes every top-level engine.json field not in as-is.
+ private static void CopyUnownedFields(Utf8JsonWriter w)
+ {
+ try
+ {
+ if (!File.Exists(SettingsPath)) return;
+ using var doc = JsonDocument.Parse(File.ReadAllText(SettingsPath));
+ if (doc.RootElement.ValueKind != JsonValueKind.Object) return;
+ foreach (JsonProperty p in doc.RootElement.EnumerateObject())
+ {
+ if (Array.IndexOf(OwnedFields, p.Name) >= 0) continue;
+ p.WriteTo(w);
+ }
+ }
+ catch
+ {
+ // Unreadable file: write only the owned fields (previous behaviour).
+ }
+ }
}
/// engine.json "DecalBridge" (see ).
diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj
index 3a15a25..bf8c366 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 @@
+
+
@@ -159,4 +164,9 @@
SkipUnchangedFiles="true" />
+
+
+
+
+
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/MetaData.cs b/src/RynthCore.Engine/UI/Data/MetaData.cs
index ee3c1b4..ecdfa8c 100644
--- a/src/RynthCore.Engine/UI/Data/MetaData.cs
+++ b/src/RynthCore.Engine/UI/Data/MetaData.cs
@@ -231,7 +231,8 @@ internal static unsafe class MetaCommands
/// Names, hints and .af keywords shared by the Meta faces (mirror RynthSuite's MetaSchema).
internal static class MetaVocabulary
{
- public const string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
+ /// RynthAi's meta folder under the installed RynthSuite folder (installer-chosen).
+ public static string MetaFolder => System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
public static readonly string[] ConditionNames =
{
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 1333323..918f949 100644
--- a/src/RynthCore.Injector/Program.cs
+++ b/src/RynthCore.Injector/Program.cs
@@ -2,13 +2,15 @@ using System;
using System.IO;
using System.Linq;
using System.Text;
+using RynthCore.Install;
namespace RynthCore.Injector;
internal static class Program
{
// Unified log path — must stay in sync with RynthCore.Engine.LogPaths.
- private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs";
+ // Installer-chosen RynthCore folder (falls back to C:\Games\RynthCore).
+ private static readonly string UnifiedLogDirectory = RynthInstallPaths.CoreLogsDir;
private const string UnifiedLogFileName = "RynthCore.log";
private static int Main(string[] args)
diff --git a/src/RynthCore.Injector/RynthCore.Injector.csproj b/src/RynthCore.Injector/RynthCore.Injector.csproj
index d52d682..b70a802 100644
--- a/src/RynthCore.Injector/RynthCore.Injector.csproj
+++ b/src/RynthCore.Injector/RynthCore.Injector.csproj
@@ -11,6 +11,8 @@
+
+
diff --git a/src/RynthCore.Loader/EntryPoint.cs b/src/RynthCore.Loader/EntryPoint.cs
index 01fe674..4b76d41 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;
@@ -31,7 +32,8 @@ public static class EntryPoint
// Unified log path — must stay in sync with RynthCore.Engine.LogPaths.
// The loader cannot reference the engine assembly (it loads it
// dynamically), so the constants are mirrored here.
- private const string UnifiedLogDirectory = @"C:\Games\RynthCore\Logs";
+ // Installer-chosen RynthCore folder (falls back to C:\Games\RynthCore).
+ private static readonly string UnifiedLogDirectory = RynthInstallPaths.CoreLogsDir;
private const string UnifiedLogFileName = "RynthCore.log";
///
/// Subdirectory beside the loader where reload-generation copies of the
diff --git a/src/RynthCore.Loader/RynthCore.Loader.csproj b/src/RynthCore.Loader/RynthCore.Loader.csproj
index f5f41d1..306faee 100644
--- a/src/RynthCore.Loader/RynthCore.Loader.csproj
+++ b/src/RynthCore.Loader/RynthCore.Loader.csproj
@@ -26,6 +26,11 @@
false
+
+
+
+
+
diff --git a/src/RynthCore.StatusAgent/AgentConfig.cs b/src/RynthCore.StatusAgent/AgentConfig.cs
index 8610076..b0ed556 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;
@@ -27,10 +28,10 @@ internal sealed class AgentConfig
[JsonPropertyName("TimeoutSeconds")] public int TimeoutSeconds { get; set; } = 15;
/// Directory holding the engine's per-client status files.
- [JsonPropertyName("StatusDirectory")] public string StatusDirectory { get; set; } = @"C:\Games\RynthCore\Logs\status";
+ [JsonPropertyName("StatusDirectory")] public string StatusDirectory { get; set; } = Path.Combine(RynthInstallPaths.CoreLogsDir, "status");
/// Directory holding per-client RynthCore.<pid>.log files (heartbeat fallback).
- [JsonPropertyName("LogDirectory")] public string LogDirectory { get; set; } = @"C:\Games\RynthCore\Logs";
+ [JsonPropertyName("LogDirectory")] public string LogDirectory { get; set; } = RynthInstallPaths.CoreLogsDir;
/// When true and no status file exists for a running client, derive
/// basic status from that client's heartbeat log line. Lets the agent work
@@ -97,12 +98,12 @@ internal sealed class AgentConfig
/// portal.dat used to decode item icons for GET /icon (read-only inventory viewer). Defaults to
/// the RynthCore client's private copy. If the file is absent (e.g. an agent running off the game box)
/// /icon 404s and the app falls back to text rows — no other feature is affected.
- [JsonPropertyName("IconDatPath")] public string IconDatPath { get; set; } = @"C:\Games\RynthCore\AcClient\client_portal.dat";
+ [JsonPropertyName("IconDatPath")] public string IconDatPath { get; set; } = Path.Combine(RynthInstallPaths.CoreDir, "AcClient", "client_portal.dat");
/// Directory of RynthAi's baked dungeon floor-plan maps ({landblock:X8}_{layer}.bin), served as
/// PNGs via GET /map for the app's dungeon-map viewer. If the folder is absent (agent off the game box)
/// /maps returns an empty list and /map 404s — no other feature is affected.
- [JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps";
+ [JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = Path.Combine(RynthInstallPaths.RynthAiDir, "Maps");
/// cell.dat the landscape map (GET /worldmap) is drawn from, once, then cached as worldmap-v1.jpg in
/// . Absent = no world map (capabilities.worldMap false); nothing else changes.
diff --git a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj
index 31cf6d9..49bc151 100644
--- a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj
+++ b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj
@@ -30,4 +30,9 @@
+
+
+
+
+