feat(engine,launcher): ILT Hub panel button, ImGui windows over Avalonia, live per-category logging

RynthAi Avalonia panel gains an ILT Hub button (hub show via ApplyRemoteCommand). ImGui draw data is submitted after the Avalonia blit and ImGui gets mouse priority when hovered. Engine reads LoggingLevel (now incl. Off) and LogCategories from engine.json live; launcher 0.1.5 edits engine and RynthAi log levels on the fly.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-04 18:52:01 -04:00
commit 6b94752128
15 changed files with 855 additions and 67 deletions

View file

@ -0,0 +1,60 @@
# 2026-10-04 — ILT Hub panel button, ImGui windows on top, live logging levels
Launcher 0.1.5. Needs RynthAi 0.6.18 for the RynthAi logging rows.
## ILT Hub button (Avalonia RynthAi panel)
* New **ILT Hub** launcher button (third row of the RynthAi panel launcher grid).
Sends `hub show` through the plugin's `RynthPluginApplyRemoteCommand` export —
the same path as typing `/ra hub show`.
* New `SendRemoteCmd(action, value)` helper marshals both strings, calls the
export and frees them (the plugin copies them and applies on its pump thread).
## Plugin ImGui windows draw on top of the Avalonia layer
* `EngineFrameController.RunImGuiFrame` still builds the ImGui frame at the same
point, but no longer submits the draw data. `EndSceneHook` now calls the new
`EngineFrameController.RenderDeferredImGui()` **after**
`OverlayTextureRenderer.Render`, so the plugin overlay windows (ILT Hub, Item
Info, ...) are drawn over the Avalonia panels.
* Input follows the new stacking: when ImGui is hovered or has an active widget,
mouse messages go to ImGui instead of the Avalonia panel underneath
(`Win32Backend.ImGuiOwnsMouseOverAvalonia`). An Avalonia drag/resize already
in progress keeps its capture so the release is never lost.
* Nothing is submitted twice: the pending draw is cleared at the start of each
ImGui frame and after submission.
## Live, per-category logging (engine + launcher)
### Engine
* New `LogSettings` reads engine.json:
* `"LoggingLevel"`: global threshold, now including **Off**
(Off, Error, Warning, Info, Debug, Trace; `Verbose`/`Warn` accepted).
* `"LogCategories"`: per-category emit level (Off, Trace, Debug, Info) for
General, D3D9, Compat, Render, Plugin, UI, Verbose. A category's lines are
written at its level, so a Trace/Debug category set to **Info** shows in the
normal log, and **Off** silences it.
* A background thread polls engine.json once a second and reloads on change
(logs `LogSettings: engine.json changed - logging reloaded (...)`). Stopped in
`EngineLifecycle.Shutdown` before unload.
* `RynthLog` category methods route through the category levels (the hard-coded
`*Enabled` booleans are gone; defaults are unchanged: Render Off, Verbose Debug,
everything else Info).
* Lines are tagged with their real level: `[DBG]` and `[TRC]` instead of `[INF]`.
* `Warn` is now hidden at level Error/Off; `Error` is always written.
`LastIssue` is still recorded for filtered warnings.
* `EngineSettings.Save()` now copies through engine.json fields it doesn't own
(e.g. `LogCategories`, `EnableDcompOverlay`) instead of dropping them.
### Launcher (Runtime tab)
* **Logging level** box gains **Off**, and applies immediately (writes
engine.json on change; no Save needed). Unknown saved values fall back to Info.
* New **Logging** card, every change saved immediately and applied live:
* Engine categories: Off / Trace / Debug / Info per category.
* RynthAi categories: Off / Trace / Info per category (diagnostics.json).
* RynthAi key events: Off / Trace / Info per event (diagnostics.json).
* Reload button re-reads both files.
* New `LoggingSettingsStore` does the read-modify-write of both files
(atomic temp-file swap for diagnostics.json, every other field preserved).

View file

@ -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;
/// <summary>
/// Launcher-side access to every live logging switch:
/// <list type="bullet">
/// <item>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.</item>
/// <item>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.</item>
/// </list>
/// </summary>
internal static class LoggingSettingsStore
{
/// <summary>One engine log category as shown in the launcher.</summary>
internal readonly record struct EngineCategory(string Name, string DefaultLevel, string Description);
/// <summary>One RynthAi category / event row read from diagnostics.json.</summary>
internal sealed record DiagnosticsRow(string Key, string Level, string Description);
/// <summary>Global level choices (engine.json "LoggingLevel"), most to least quiet.</summary>
internal static readonly string[] GlobalLevels = { "Off", "Error", "Warning", "Info", "Debug", "Trace" };
/// <summary>Engine category emit levels. Info = normal log; Debug/Trace show only at that global level.</summary>
internal static readonly string[] EngineCategoryLevels = { "Off", "Trace", "Debug", "Info" };
/// <summary>RynthAi category / event levels: Off, Trace (trace file only), Info (also the normal log).</summary>
internal static readonly string[] RynthAiLevels = { "Off", "Trace", "Info" };
/// <summary>Must match RynthCore.Engine.LogCategory names and LogSettings defaults.</summary>
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";
/// <summary>RynthAi's diagnostics.json (created by RynthAi on its first load).</summary>
internal static string DiagnosticsPath =>
Path.Combine(RynthInstallPaths.RynthAiDir, "Logs", "Diagnostics", "diagnostics.json");
// ── Engine ──────────────────────────────────────────────────────────
/// <summary>Current engine category levels; categories missing from engine.json get their defaults.</summary>
internal static Dictionary<string, string> ReadEngineCategoryLevels()
{
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (EngineCategory c in EngineCategories) result[c.Name] = c.DefaultLevel;
Dictionary<string, JsonElement> 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;
}
/// <summary>Sets one engine category level in engine.json, preserving every other field.</summary>
internal static void SetEngineCategoryLevel(string category, string level)
{
Dictionary<string, string> 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<string, JsonElement> fields = EngineJsonStore.Read();
using var doc = JsonDocument.Parse(ms.ToArray());
fields[EngineCategoriesProperty] = doc.RootElement.Clone();
EngineJsonStore.Write(fields);
}
// ── RynthAi ─────────────────────────────────────────────────────────
/// <summary>
/// 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).
/// </summary>
internal static bool TryReadRynthAi(out List<DiagnosticsRow> categories, out List<DiagnosticsRow> events, out string? error)
{
categories = new List<DiagnosticsRow>();
events = new List<DiagnosticsRow>();
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;
}
}
/// <summary>Sets a RynthAi category level ("Off", "Trace", "Info") and keeps "Traces" in sync.</summary>
internal static void SetRynthAiCategoryLevel(string category, string level)
=> UpdateDiagnostics("Categories", "Name", category, level);
/// <summary>Sets a RynthAi key-event level ("Off", "Trace", "Info").</summary>
internal static void SetRynthAiEventLevel(string eventKey, string level)
=> UpdateDiagnostics("Events", "Key", eventKey, level);
private static void ReadRows(JsonArray? array, string keyField, List<DiagnosticsRow> into)
{
if (array == null) return;
foreach (JsonNode? node in array)
{
if (node is not JsonObject o) continue;
string key = o[keyField]?.GetValue<string>() ?? string.Empty;
if (key.Length == 0) continue;
into.Add(new DiagnosticsRow(
key,
o["Level"]?.GetValue<string>() ?? "Off",
o["Description"]?.GetValue<string>() ?? string.Empty));
}
}
/// <summary>Read-modify-write of one row's Level; every other field in the file is preserved.</summary>
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<string>(), 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<string>(), "Off", StringComparison.OrdinalIgnoreCase))
traces.Add(o["Name"]?.GetValue<string>());
}
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);
}
}

View file

@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Runtime tab → Logging card and the live global Logging level box. Every change is written
/// straight to engine.json / diagnostics.json (see <see cref="LoggingSettingsStore"/>); running
/// clients poll those files, so nothing needs a restart or the Save button.
/// </summary>
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;
/// <summary>Wires the Logging card and the live global level box. Called once after LoadRuntimeControls.</summary>
private void InitLoggingControls()
{
LoggingLevelComboBox.SelectionChanged += (_, _) => OnGlobalLoggingLevelChanged();
ReloadLoggingButton.Click += (_, _) => BuildLoggingRows();
BuildLoggingRows();
}
/// <summary>Global level changed: persist to the launcher settings and push to engine.json now.</summary>
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}");
}
}
/// <summary>(Re)builds the engine category, RynthAi category and RynthAi event rows from disk.</summary>
private void BuildLoggingRows()
{
_suppressLoggingEvents = true;
try
{
EngineLogCategoriesPanel.Children.Clear();
Dictionary<string, string> 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<LoggingSettingsStore.DiagnosticsRow> categories,
out List<LoggingSettingsStore.DiagnosticsRow> 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;
}
}
/// <summary>One "Name | level box | description" row. <paramref name="apply"/> runs on user changes only.</summary>
private Control BuildLoggingRow(string name, string description, string[] levels, string current, Action<string> 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;
}
}

View file

@ -316,8 +316,10 @@
Content="Rewrite AC window titles per account"
ToolTip.Tip="Replaces &quot;Asheron's Call&quot; with &quot;Account / Character @ Server&quot; on tracked clients so multi-box taskbars are readable. Untracked external clients are left alone." />
<CheckBox x:Name="InjectAllRunningAcCheckBox" Content="Inject all running AC sessions" />
<TextBlock Text="Logging level" Foreground="#EAF0F4" Margin="0,4,0,0" />
<ComboBox x:Name="LoggingLevelComboBox" SelectedIndex="0">
<TextBlock Text="Logging level (applies live)" Foreground="#EAF0F4" Margin="0,4,0,0" />
<ComboBox x:Name="LoggingLevelComboBox" SelectedIndex="3"
ToolTip.Tip="Engine log threshold. Written to engine.json immediately; running clients pick it up within a second. Off = errors only.">
<ComboBoxItem Content="Off" />
<ComboBoxItem Content="Error" />
<ComboBoxItem Content="Warning" />
<ComboBoxItem Content="Info" />
@ -363,6 +365,42 @@
</StackPanel>
</Border>
<!-- Live logging switches: engine categories (engine.json) and RynthAi categories/events
(diagnostics.json). Rows are built in code (MainWindow.Logging.cs). -->
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Grid.Column="0" Text="Logging" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" VerticalAlignment="Center" />
<Button Grid.Column="1" x:Name="ReloadLoggingButton" Content="Reload" />
</Grid>
<TextBlock Text="Every change is saved immediately and applies to running clients without a restart (engine within 1 s, RynthAi within 2 s). Set any Trace or Debug item to Info to see it in the normal log; Off silences it."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<Expander Header="Engine categories" IsExpanded="True" HorizontalAlignment="Stretch">
<StackPanel Spacing="4">
<TextBlock Text="The level each category's lines are written at. A line shows when its level is within the global Logging level above (Info = normal log)."
TextWrapping="Wrap" Foreground="#9AA8B3" />
<StackPanel x:Name="EngineLogCategoriesPanel" Spacing="2" />
</StackPanel>
</Expander>
<Expander Header="RynthAi categories" HorizontalAlignment="Stretch">
<StackPanel Spacing="4">
<TextBlock Text="Where each RynthAi category's trace lines go: Off = dropped, Trace = Logs\Diagnostics\Trace file only, Info = trace file and the normal log."
TextWrapping="Wrap" Foreground="#9AA8B3" />
<StackPanel x:Name="RynthAiLogCategoriesPanel" Spacing="2" />
</StackPanel>
</Expander>
<Expander Header="RynthAi key events" HorizontalAlignment="Stretch">
<StackPanel Spacing="4">
<TextBlock Text="Named milestones (Hub login, options refresh, ...). Off = dropped, Trace = trace file while that category is traced, Info = normal log."
TextWrapping="Wrap" Foreground="#9AA8B3" />
<StackPanel x:Name="RynthAiLogEventsPanel" Spacing="2" />
</StackPanel>
</Expander>
<TextBlock x:Name="LoggingStatusText" TextWrapping="Wrap" Foreground="#9AA8B3" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Recovery Actions" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />

View file

@ -137,6 +137,7 @@ internal partial class MainWindow : Window
SessionList.ItemsSource = _sessionItems;
LoadSettings();
LoadRuntimeControls();
InitLoggingControls();
ApplyInstallerPluginRegistration();
LoadPluginDllPaths();
BuildPluginLoadout();
@ -2065,7 +2066,8 @@ internal partial class MainWindow : Window
return;
}
LoggingLevelComboBox.SelectedIndex = 0;
// Unknown saved value: fall back to Info (index 3 after Off, Error, Warning), not the quietest level.
LoggingLevelComboBox.SelectedIndex = 3;
}
private void OnPrimarySelectionChanged()

View file

@ -1,12 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.3.
<!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.4.
No hard-coded InformationalVersion: release builds pass -p:Version=yyyy.m.d.n, and the
product version derived from it is what the launcher/About show (BuildVersion.Format). -->
<Version>0.1.4</Version>
<AssemblyVersion>0.1.4.0</AssemblyVersion>
<FileVersion>0.1.4.0</FileVersion>
<Version>0.1.5</Version>
<AssemblyVersion>0.1.5.0</AssemblyVersion>
<FileVersion>0.1.5.0</FileVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows7.0</TargetFramework>
<PlatformTarget>x86</PlatformTarget>

View file

@ -347,6 +347,11 @@ internal static class EndSceneHook
if (_uiFrameCount < 30)
RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}");
}
// ImGui draw data (plugin overlay windows, shell) is submitted LAST so it
// sits on top of the Avalonia layer. Built earlier in OnEndScene; guarded
// internally, so an ImGui draw failure can't skip the original EndScene.
EngineFrameController.RenderDeferredImGui();
}
catch (Exception ex)
{

View file

@ -145,6 +145,7 @@ internal static class EngineLifecycle
// tick pump and plugins go away — both otherwise keep firing in the old
// generation's (intentionally still-mapped) module across hot-reloads.
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher());
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.

View file

@ -45,6 +45,8 @@ public static class EntryPoint
internal enum EngineLogLevel
{
/// <summary>As a global threshold: nothing but errors. As a category level: never written.</summary>
Off = -1,
Error = 0,
Warning = 1,
Info = 2,
@ -109,10 +111,10 @@ public static class EntryPoint
}
catch { }
// engine.json "LoggingLevel" (launcher Logging level box) sets the threshold first so
// every line written below honours it; Debug/Trace also turn on the legacy verbose flag.
LoggingLevel = ParseLoggingLevel(EngineSettings.LoggingLevel);
VerboseLogging = LoggingLevel >= EngineLogLevel.Debug;
// 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 <CoreDir>\Logs (installer-chosen;
@ -134,9 +136,13 @@ public static class EntryPoint
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($" logging level={LoggingLevel} (verbose={VerboseLogging})");
RynthLog.Info($" logging {logSummary}");
RynthLog.Info("================================================================");
// 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();
// Diagnostic: catch the "client frozen, bot keeps running" hangs by
@ -1375,9 +1381,15 @@ public static class EntryPoint
Log(message);
}
internal static bool ShouldLog(EngineLogLevel level) => level <= LoggingLevel;
/// <summary>
/// True when a line at <paramref name="level"/> passes the global threshold. Off-level lines
/// never pass; an Off threshold blocks everything (errors bypass this gate).
/// </summary>
internal static bool ShouldLog(EngineLogLevel level)
=> level != EngineLogLevel.Off && level <= LoggingLevel;
private static EngineLogLevel ParseLoggingLevel(string? configuredLevel)
/// <summary>Parses the global level: Off, Error, Warning/Warn, Info, Debug/Verbose, Trace. Unknown → Info.</summary>
internal static EngineLogLevel ParseLoggingLevel(string? configuredLevel)
{
if (string.IsNullOrWhiteSpace(configuredLevel))
return EngineLogLevel.Info;
@ -1385,8 +1397,10 @@ public static class EntryPoint
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)
return Enum.TryParse(normalized, ignoreCase: true, out EngineLogLevel parsed) && Enum.IsDefined(parsed)
? parsed
: EngineLogLevel.Info;
}

View file

@ -73,6 +73,11 @@ internal static class EngineFrameController
/// </summary>
internal static volatile IntPtr CachedDevice;
private static int _pluginPumpInFrame; // re-entrancy guard for the pump
// ImGui draw data built by RunImGuiFrame, submitted later by RenderDeferredImGui
// (after the Avalonia blit). Render thread only. Device == 0 means nothing pending.
private static ImDrawDataPtr _deferredDrawData;
private static IntPtr _deferredDrawDevice;
private static long _lastFrameTicks;
private static int _frameCount;
@ -465,6 +470,9 @@ internal static class EngineFrameController
bool frameStarted = false;
bool frameEnded = false;
// A frame that throws before Render must not resubmit last frame's draw data.
_deferredDrawDevice = IntPtr.Zero;
try
{
_frameCount++;
@ -536,10 +544,12 @@ internal static class EngineFrameController
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
DX9Backend.RenderDrawData(drawData, pDevice);
// OverlayTextureRenderer.Render is now driven from EndSceneHook.EndSceneDetour
// directly so the Avalonia compositor runs even when EnableImGuiBackend=false.
// Leaving it out of this call site avoids double-blit when ImGui is also active.
// Submission is deferred to RenderDeferredImGui, which EndSceneHook calls
// AFTER OverlayTextureRenderer has blitted the Avalonia layer, so ImGui
// windows (plugin overlay windows such as the ILT Hub) sit on top of the
// Avalonia panels. The draw data stays valid until the next NewFrame.
_deferredDrawData = drawData;
_deferredDrawDevice = pDevice;
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
@ -567,6 +577,35 @@ internal static class EngineFrameController
}
}
/// <summary>
/// Submits this frame's ImGui draw data. EndSceneHook calls it after
/// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia
/// layer. Runs whether or not the Avalonia blit ran (character select, Avalonia
/// off), and is a no-op when RunImGuiFrame produced nothing this frame.
/// </summary>
public static void RenderDeferredImGui()
{
IntPtr device = _deferredDrawDevice;
if (device == IntPtr.Zero)
return;
_deferredDrawDevice = IntPtr.Zero; // one submission per frame, even if it throws
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
ImGuiNET.ImGui.SetCurrentContext(_context);
try
{
DX9Backend.RenderDrawData(_deferredDrawData, device);
}
catch (Exception ex)
{
RynthLog.Info($"EngineFrameController: frame {_frameCount} deferred ImGui draw error: {ex.GetType().Name}: {ex.Message}");
}
finally
{
ImGuiNET.ImGui.SetCurrentContext(previousContext);
}
}
internal static IntPtr FindGameWindow()
{
uint pid = GetCurrentProcessId();

View file

@ -927,7 +927,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)
@ -1007,6 +1007,17 @@ internal static unsafe class Win32Backend
/// 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).
/// </summary>
/// <summary>
/// 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.
/// </summary>
private static bool ImGuiOwnsMouseOverAvalonia()
{
return _wantCaptureMouse && !AvaloniaOverlay.HasPointerCapture;
}
private static bool TryForwardToAvalonia(uint msg, IntPtr wParam, IntPtr lParam)
{
IntPtr avHwnd = AvaloniaOverlay.AvaloniaHwnd;

View file

@ -0,0 +1,222 @@
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine;
/// <summary>
/// Engine log categories. Each one has a configurable emit level (see <see cref="LogSettings"/>).
/// Names are the keys of engine.json "LogCategories" and must stay stable.
/// </summary>
internal enum LogCategory
{
/// <summary>Uncategorised RynthLog.Info lines.</summary>
General = 0,
/// <summary>D3D9: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary>
D3D9,
/// <summary>Compatibility hooks: client objects, combat, movement, vitals, chat, ...</summary>
Compat,
/// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary>
Render,
/// <summary>Plugin system, including every line plugins write through the host Log API.</summary>
Plugin,
/// <summary>UI / Avalonia overlay.</summary>
UI,
/// <summary>Verbose detail lines (RynthLog.Verbose / RynthLog.Debug).</summary>
Verbose,
}
/// <summary>
/// Live engine logging configuration, read from %APPDATA%\RynthCore\engine.json:
/// <list type="bullet">
/// <item><c>"LoggingLevel"</c> — global threshold: Off, Error, Warning, Info, Debug, Trace.</item>
/// <item><c>"LogCategories"</c> — per-category emit level: <c>{ "Compat": "Info", "Verbose": "Debug", ... }</c>.
/// 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.</item>
/// </list>
/// 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.
/// </summary>
internal static class LogSettings
{
/// <summary>engine.json property holding the per-category levels.</summary>
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");
/// <summary>Current emit level for a category (cheap; safe on hot paths).</summary>
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;
}
/// <summary>True when a line in this category would be written right now.</summary>
internal static bool IsEnabled(LogCategory category) => EntryPoint.ShouldLog(LevelFor(category));
/// <summary>3-char severity tag written into each log line.</summary>
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",
};
/// <summary>
/// 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.
/// </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();
}
/// <summary>Human-readable "level=Info D3D9=Info Compat=Info ..." summary for the log.</summary>
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();
}
/// <summary>Starts the once-a-second engine.json poll. Idempotent.</summary>
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();
}
}
/// <summary>
/// Stops and joins the poll thread. Called from EngineLifecycle.Shutdown so the thread never
/// runs inside an old engine generation after a hot reload.
/// </summary>
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");
}
catch
{
// Logging configuration must never take the client down; retry next poll.
}
}
}
/// <summary>
/// Parses a category emit level: Off, Trace, Debug (or Verbose), Info, Warning (or Warn), Error.
/// </summary>
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);
}
}

View file

@ -385,6 +385,7 @@ internal static class EngineSettings
w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff);
// Preserve the launcher-chosen level; dropping it here would reset logging to Info.
w.WriteString("LoggingLevel", _loggingLevel);
CopyUnownedFields(w);
w.WriteEndObject();
}
File.WriteAllBytes(SettingsPath, ms.ToArray());
@ -394,4 +395,33 @@ 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",
};
/// <summary>Writes every top-level engine.json field not in <see cref="OwnedFields"/> as-is.</summary>
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).
}
}
}

View file

@ -4,92 +4,75 @@ namespace RynthCore.Engine;
/// <summary>
/// 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 <see cref="LogSettings"/>), gated by the global
/// "LoggingLevel". Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…").
/// </summary>
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 ─────────────────────────────────────────────────
/// <summary>D3D9 subsystem: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary>
internal static void D3D9(string msg)
{
if (D3D9Enabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
internal static void D3D9(string msg) => WriteCategory(LogCategory.D3D9, msg);
/// <summary>Compatibility hooks: SmartBox, client objects, combat, movement, vitals, chat, etc.</summary>
internal static void Compat(string msg)
{
if (CompatEnabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
internal static void Compat(string msg) => WriteCategory(LogCategory.Compat, msg);
/// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary>
internal static void Render(string msg)
{
if (RenderEnabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
internal static void Render(string msg) => WriteCategory(LogCategory.Render, msg);
/// <summary>Plugin system: loader, manager, lifecycle callbacks.</summary>
internal static void Plugin(string msg)
{
if (PluginEnabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
/// <summary>Plugin system: loader, manager, lifecycle callbacks, plugin host Log lines.</summary>
internal static void Plugin(string msg) => WriteCategory(LogCategory.Plugin, msg);
/// <summary>UI / Avalonia overlay subsystem.</summary>
internal static void UI(string msg)
{
if (UIEnabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
internal static void UI(string msg) => WriteCategory(LogCategory.UI, msg);
/// <summary>Debug-level log (any category).</summary>
internal static void Verbose(string msg)
{
WriteAt(EntryPoint.EngineLogLevel.Debug, msg);
}
/// <summary>Verbose detail (any subsystem). Debug by default; set the Verbose category to Info to see it in the normal log.</summary>
internal static void Verbose(string msg) => WriteCategory(LogCategory.Verbose, msg);
// Level-gated helpers (engine.json "LoggingLevel"). Warning/Error delegate to the always-on
// tagged WRN/ERR writers below so they are never filtered and still feed LastIssue.
/// <summary>Same as <see cref="Verbose"/>.</summary>
internal static void Debug(string msg) => WriteCategory(LogCategory.Verbose, msg);
/// <summary>Trace-level line: written only when the global level is Trace.</summary>
internal static void Trace(string msg) => WriteAt(EntryPoint.EngineLogLevel.Trace, msg);
internal static void Debug(string msg) => WriteAt(EntryPoint.EngineLogLevel.Debug, msg);
/// <summary>INFO line for uncategorised messages (written at the default Info level and finer).</summary>
internal static void Info(string msg) => WriteAt(EntryPoint.EngineLogLevel.Info, msg);
/// <summary>Uncategorised line (General category, Info by default).</summary>
internal static void Info(string msg) => WriteCategory(LogCategory.General, msg);
/// <summary>Alias kept for SK-local call sites; same as <see cref="Warn"/>.</summary>
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;
/// <summary>Always-on WARN line — a recoverable problem worth grepping for.</summary>
/// <summary>WARN line — a recoverable problem worth grepping for. Hidden only at level Error/Off.</summary>
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");
}
/// <summary>Always-on ERROR line — a fault/crash/disable. Triage with grep "[ERR]".</summary>
/// <summary>Always-on ERROR line — a fault/crash/disable, written even at level Off. Triage with grep "[ERR]".</summary>
internal static void Error(string msg)
{
LastIssue = msg; LastIssueUtc = DateTime.UtcNow;
EntryPoint.LogTagged("engine", msg, "ERR");
}
/// <summary>True when a line in <paramref name="category"/> would be written (guard expensive messages).</summary>
internal static bool IsEnabled(LogCategory category) => LogSettings.IsEnabled(category);
// ── Sink ─────────────────────────────────────────────────────────────
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.Log(message);
EntryPoint.LogTagged("engine", message, LogSettings.Tag(level));
}
}

View file

@ -59,6 +59,8 @@ internal static partial class RynthAiPanel
private delegate void FloatFn(float arg);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void PtrFn(IntPtr arg);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void PtrPtrFn(IntPtr a, IntPtr b);
// ── Color palette — exact match to LegacyDashboardRenderer ImGui Vector4
// floats (multiplied by 255 and rounded). Don't deepen these; the ImGui
@ -121,6 +123,8 @@ internal static partial class RynthAiPanel
private static VoidFn? _togglePanelMinimize;
private static PtrFn? _sendNavCommand;
private static GetSnapshotJsonFn? _getPatrolInfoJson;
// RynthPluginApplyRemoteCommand(action, value): queued and applied on the plugin pump thread.
private static PtrPtrFn? _applyRemoteCommand;
private static bool _bindingLogged;
/// <summary>
@ -693,7 +697,7 @@ internal static partial class RynthAiPanel
var launcherGrid = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,*,*"),
RowDefinitions = new RowDefinitions("Auto,Auto"),
RowDefinitions = new RowDefinitions("Auto,Auto,Auto"),
Margin = new Thickness(0, 4, 0, 0)
};
AddSplitLauncher(launcherGrid, 0, 0, "Meta", "⚙", "Lua", "<>",
@ -722,6 +726,16 @@ internal static partial class RynthAiPanel
ShowPatrolFlyout(patrolBtn);
}
};
// ILT Hub: same as typing "/ra hub show". The Hub is an ImGui overlay window with no
// Avalonia panel, so this is the panel's way to open it.
var iltHubBtn = AddLauncher(launcherGrid, 2, 0, "ILT Hub", "♥",
onClick: () =>
{
ClosePicker();
if (_applyRemoteCommand == null) TryBind();
SendRemoteCmd("hub", "show");
});
ToolTip.SetTip(iltHubBtn, "Open the ILT Hub window (/ra hub show).");
dash.Children.Add(launcherGrid);
@ -1518,6 +1532,7 @@ internal static partial class RynthAiPanel
_togglePanelMinimize = null;
_sendNavCommand = null;
_getPatrolInfoJson = null;
_applyRemoteCommand = null;
};
private static void TryBind()
@ -1537,6 +1552,7 @@ internal static partial class RynthAiPanel
_togglePanelMinimize ??= Bind<VoidFn>(plugin, "RynthPluginTogglePanelMinimize");
_sendNavCommand ??= Bind<PtrFn>(plugin, "RynthPluginSendNavCommand");
_getPatrolInfoJson ??= Bind<GetSnapshotJsonFn>(plugin, "RynthPluginGetPatrolInfoJson");
_applyRemoteCommand ??= Bind<PtrPtrFn>(plugin, "RynthPluginApplyRemoteCommand");
if (!_bindingLogged && _getSnapshotJson != null)
{
@ -1559,6 +1575,28 @@ internal static partial class RynthAiPanel
finally { Marshal.FreeHGlobal(ptr); }
}
/// <summary>
/// Sends an (action, value) pair to RynthPluginApplyRemoteCommand — the same path as
/// typing "/ra &lt;action&gt; &lt;value&gt;". The plugin copies both strings and applies
/// the command on its pump thread, so the buffers can be freed as soon as this returns.
/// </summary>
private static void SendRemoteCmd(string action, string value)
{
if (_applyRemoteCommand == null)
{
RynthLog.UI($"RynthAiPanel: RynthPluginApplyRemoteCommand not bound; dropped '{action} {value}'.");
return;
}
IntPtr a = Marshal.StringToHGlobalAnsi(action);
IntPtr b = Marshal.StringToHGlobalAnsi(value);
try { _applyRemoteCommand(a, b); }
finally
{
Marshal.FreeHGlobal(a);
Marshal.FreeHGlobal(b);
}
}
private sealed class Snapshot
{
[JsonPropertyName("macroRunning")] public bool MacroRunning { get; set; }