inital SK upload

This commit is contained in:
BlankenshipG 2026-04-26 14:27:26 -04:00
commit 5edb6915ed
125 changed files with 2659 additions and 107 deletions

View file

@ -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();

View file

@ -0,0 +1,110 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore;
namespace RynthCore.App.Avalonia;
/// <summary>
/// One-shot host metadata for the Avalonia launcher: helps confirm the renamed apphost
/// (<c>RynthCore.exe</c>) sits next to matching <c>.runtimeconfig.json</c> / <c>.deps.json</c> after installer staging.
/// </summary>
internal static class LauncherHostDiagnostics
{
/// <summary>Single line for the in-window activity feed (short).</summary>
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}";
}
/// <summary>Writes a detailed block to the desktop rolling launcher log.</summary>
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);
}

View file

@ -285,6 +285,15 @@
<CheckBox x:Name="SkipLoginLogosCheckBox" Content="Skip login logos" />
<CheckBox x:Name="AutoInjectAfterLaunchCheckBox" Content="Auto inject after launch" />
<CheckBox x:Name="WatchForAcStartCheckBox" Content="Watch for AC start" />
<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">
<ComboBoxItem Content="Error" />
<ComboBoxItem Content="Warning" />
<ComboBoxItem Content="Info" />
<ComboBoxItem Content="Debug" />
<ComboBoxItem Content="Trace" />
</ComboBox>
<Button x:Name="SaveBehaviorButton"
Content="Save Launch Behavior"
HorizontalAlignment="Left" />
@ -302,7 +311,7 @@
<Button x:Name="InjectRunningAcButton" Content="Inject Into Running AC" Margin="0,0,8,8" />
<Button x:Name="RefreshSessionsButton" Content="Refresh Sessions" Margin="0,0,8,8" />
</WrapPanel>
<TextBlock Text="Manual inject targets the first detected acclient.exe session."
<TextBlock Text="Manual inject target scope follows the 'Inject all running AC sessions' launch behavior toggle."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
</StackPanel>

View file

@ -75,6 +75,8 @@ internal partial class MainWindow : Window
_serverStatusTimer.Start();
Closing += (_, _) => SaveWindowLayout();
AppendActivity("Avalonia launcher preview ready.");
// One-line host/runtime sidecar check (full detail in Desktop RynthCore-Launcher.log).
AppendActivity(LauncherHostDiagnostics.BuildActivitySummaryLine());
_ = RefreshServerStatusesAsync();
}
@ -152,6 +154,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);
}
private void BuildPluginLoadout()
@ -722,12 +726,18 @@ 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.EnabledPluginIds = GetSelectedPluginIds().ToList();
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()
@ -844,7 +854,11 @@ internal partial class MainWindow : Window
LaunchServerProfile? contextServer = ResolveServerForAccount(account);
string accountKey = BuildAccountKey(account.AccountName);
if (!string.IsNullOrWhiteSpace(accountKey) && activeAccountKeys.Contains(accountKey))
bool allowMultipleClients = _settings.AllowMultipleClients;
// In single-client mode, keep one active session per account to avoid accidental duplicate launches.
if (!allowMultipleClients &&
!string.IsNullOrWhiteSpace(accountKey) &&
activeAccountKeys.Contains(accountKey))
{
string serverLabel = contextServer?.DisplayName ?? "the configured server";
AppendActivity($"Skipped {account.DisplayName}: account '{account.AccountName}' already has a running session on {serverLabel}.");
@ -1111,6 +1125,7 @@ internal partial class MainWindow : Window
foreach (string p in _pluginDllPaths)
w.WriteStringValue(p);
w.WriteEndArray();
w.WriteString("LoggingLevel", GetSelectedLoggingLevel());
w.WriteEndObject();
}
File.WriteAllBytes(engineSettingsPath, ms.ToArray());
@ -1156,18 +1171,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<Process> orderedTargets = targets.OrderBy(process => process.Id).ToList();
bool injectAllSessions = InjectAllRunningAcCheckBox.IsChecked == true;
IReadOnlyList<Process> 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)
@ -1181,6 +1206,38 @@ 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;
}
LoggingLevelComboBox.SelectedIndex = 0;
}
private void OnPrimarySelectionChanged()
{
if (_suppressPrimarySelectionChanged)

View file

@ -1,6 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Launcher assembly version (bump when changing launcher-only behavior). -->
<Version>0.1.3</Version>
<AssemblyVersion>0.1.3.0</AssemblyVersion>
<FileVersion>0.1.3.0</FileVersion>
<InformationalVersion>0.1.3-x64-prereq-probe</InformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows7.0</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
@ -11,6 +16,8 @@
<RootNamespace>RynthCore.App.Avalonia</RootNamespace>
<AssemblyName>RynthCore.App.Avalonia</AssemblyName>
<RuntimeIdentifiers>win-x86</RuntimeIdentifiers>
<!-- Build-Installer.ps1 publishes self-contained so RynthCore.exe does not require a machine-wide
.NET 10 Desktop Runtime. Local dotnet build or dotnet run still use the SDK. -->
<ApplicationIcon>LogoCore.ico</ApplicationIcon>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
</PropertyGroup>
@ -25,6 +32,12 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" />
<!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj" />
</ItemGroup>
<ItemGroup>

View file

@ -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 List<string> EnabledPluginIds { get; set; } = [];
public List<string> PluginDllPaths { get; set; } = [];
public List<LaunchServerProfile> ServerProfiles { get; set; } = [];

View file

@ -0,0 +1,130 @@
using System.Globalization;
using System.Text;
namespace RynthCore;
/// <summary>
/// Desktop text logs with a fixed size cap and per-day roll retention. Active file lives on the user
/// desktop as <c>{fileStem}.log</c>. When the active file reaches <see cref="MaxActiveFileBytes"/>,
/// it is moved into <c>Desktop\RynthLogs\</c> with a time-stamped name, then a new active file is
/// created. For each <paramref name="fileStem"/> and each calendar day, at most
/// <see cref="MaxRolledFilesPerLocalDay"/> archived files are kept (oldest for that day deleted first).
/// </summary>
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");
/// <summary>Pre-defined stems for the three Rynth products (one file each on the desktop).</summary>
public const string StemEngine = "RynthCore";
public const string StemLauncher = "RynthCore-Launcher";
public const string StemInjector = "RynthCore-Injector";
private static readonly object Gate = new();
/// <param name="fileStem">File name without extension, e.g. <see cref="StemEngine"/>.</param>
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;
}
}

View file

@ -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;
/// <summary>
/// Registry probe for the optional x64 framework-dependent tools (Loot Editor, Monster Editor).
/// Must match <c>IsNetDesktop10PlusX64Present</c> and its helpers in <c>installer/RynthCore.iss</c>
/// (Path A: <c>Microsoft.WindowsDesktop.App</c> shared folders; Path B: <c>sharedhost</c> Version;
/// Path C: <c>InstalledManifests\x64</c> manifest-10. bands). Uses 64-bit registry view from an x86 process.
/// </summary>
[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";
/// <summary>True if the x64 FDD tool prerequisite is met, or the OS is 32-bit (N/A, same as Inno skip).</summary>
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);
/// <summary>First numeric segment of a "10.0.5" style folder or version string (Pascal: Copy before first '.').</summary>
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;
}
}

View file

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>RynthCore</RootNamespace>
<AssemblyName>RynthCore.DesktopLog</AssemblyName>
<Version>1.0.1</Version>
</PropertyGroup>
</Project>

View file

@ -11,6 +11,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;
@ -21,7 +22,8 @@ namespace RynthCore.Engine;
public static class EntryPoint
{
internal const string BuildStamp = "2026-03-30-v54-patternscan";
// Human-readable build label for logs; bump when shipping a new RynthBundle or notable engine change.
internal const string BuildStamp = "2026-04-23-v61-bundle-0411-runtime-detection-fix";
private const int MaxRecentLogLines = 256;
private static int _initialized;
private static bool _imGuiResolverConfigured;
@ -29,7 +31,19 @@ public static class EntryPoint
private static readonly object LogLock = new();
private static readonly Queue<string> RecentLogLines = new();
/// <summary>Set true to enable verbose startup logging (hook ready messages, plugin lifecycle, etc.).</summary>
internal enum EngineLogLevel
{
Error = 0,
Warning = 1,
Info = 2,
Debug = 3,
Trace = 4
}
/// <summary>Active engine logging threshold loaded from engine settings.</summary>
internal static EngineLogLevel LoggingLevel = EngineLogLevel.Info;
/// <summary>Legacy convenience flag used by existing verbose call sites.</summary>
internal static bool VerboseLogging = false;
/// <summary>Set by ImGuiController once the game window is confirmed. Read by AvaloniaOverlay.</summary>
@ -43,8 +57,15 @@ public static class EntryPoint
try
{
LoggingLevel = ParseLoggingLevel(EngineSettings.LoggingLevel);
VerboseLogging = LoggingLevel >= EngineLogLevel.Debug;
RynthLog.Info($"RynthCoreInit called (build {BuildStamp}) - spawning init thread...");
RynthLog.Info($"Engine logging level: {LoggingLevel}");
CrashLogger.Install();
// MultiClientHooks installs MinHook-based detours immediately. P/Invoke resolves
// minhook.x86.dll before InitWorker runs — preload from the engine directory so
// LoadLibrary succeeds (avoids false "multi-client hook failed" when the DLL exists).
TryPreloadMinHookForEarlyInit();
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
var thread = new Thread(InitWorker)
@ -86,6 +107,33 @@ public static class EntryPoint
return Path.GetDirectoryName(new string(buffer, 0, (int)length));
}
/// <summary>
/// Loads MinHook on the RynthCoreInit thread so <see cref="MultiClientHooks.Initialize"/> can
/// call <see cref="Hooking.MinHook"/> P/Invokes without relying on the default DLL search path
/// (which often resolves against the AC client directory, not <c>Runtime\</c>).
/// </summary>
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}");
}
}
private static bool PreloadNativeDll(string engineDir, string dllName)
{
foreach (string path in GetNativeDllCandidates(engineDir, dllName))
@ -347,10 +395,8 @@ public static class EntryPoint
while (RecentLogLines.Count > MaxRecentLogLines)
RecentLogLines.Dequeue();
string logPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"RynthCore.log");
File.AppendAllText(logPath, line + "\n");
// 10 MB roll + 10 per local day, archives under Desktop\RynthLogs\ (RynthCore.DesktopLog)
DesktopRollingLog.AppendLine(DesktopRollingLog.StemEngine, line);
}
}
catch
@ -360,10 +406,26 @@ public static class EntryPoint
internal static void LogVerbose(string message)
{
if (VerboseLogging)
if (ShouldLog(EngineLogLevel.Debug))
Log(message);
}
internal static bool ShouldLog(EngineLogLevel level) => level <= LoggingLevel;
private 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;
return Enum.TryParse(normalized, ignoreCase: true, out EngineLogLevel parsed)
? parsed
: EngineLogLevel.Info;
}
internal static string[] GetRecentLogLines()
{
lock (LogLock)

View file

@ -13,6 +13,7 @@ internal static class EngineSettings
"engine.json");
private static List<string> _pluginPaths = new();
private static string _loggingLevel = "Info";
private static bool _loaded;
public static IReadOnlyList<string> PluginPaths
@ -24,6 +25,15 @@ internal static class EngineSettings
}
}
public static string LoggingLevel
{
get
{
EnsureLoaded();
return _loggingLevel;
}
}
public static void AddPluginPath(string path)
{
EnsureLoaded();
@ -66,6 +76,14 @@ internal static class EngineSettings
_pluginPaths.Add(val);
}
}
if (doc.RootElement.TryGetProperty("LoggingLevel", out var loggingLevelElement) &&
loggingLevelElement.ValueKind == JsonValueKind.String)
{
string? configuredLevel = loggingLevelElement.GetString();
if (!string.IsNullOrWhiteSpace(configuredLevel))
_loggingLevel = configuredLevel;
}
}
catch (Exception ex)
{
@ -88,6 +106,7 @@ internal static class EngineSettings
foreach (string p in _pluginPaths)
w.WriteStringValue(p);
w.WriteEndArray();
w.WriteString("LoggingLevel", _loggingLevel);
w.WriteEndObject();
}
File.WriteAllBytes(SettingsPath, ms.ToArray());

View file

@ -57,4 +57,43 @@ internal sealed class LoadedPlugin
public bool Failed { get; set; }
public string DisplayName { get; set; } = "";
public string VersionString { get; set; } = "";
/// <summary>
/// Drops managed delegates wrapping exports so the native module can fully unload after
/// the host calls FreeLibrary (hot-reload / rescan).
/// </summary>
internal void ClearResolvedDelegates()
{
Init = null;
Shutdown = null;
GetName = null;
GetVersion = null;
OnLoginComplete = null;
OnUIInitialized = null;
OnBusyCountIncremented = null;
OnBusyCountDecremented = null;
OnSelectedTargetChange = null;
OnCombatModeChange = null;
OnSmartBoxEventPtr = IntPtr.Zero;
OnSmartBoxEvent = null;
OnDeleteObject = null;
OnCreateObject = null;
OnUpdateObjectPtr = IntPtr.Zero;
OnUpdateObject = null;
OnUpdateObjectInventory = null;
OnViewObjectContents = null;
OnStopViewingObjectContents = null;
OnVendorOpen = null;
OnVendorClose = null;
OnUpdateHealthPtr = IntPtr.Zero;
OnUpdateHealth = null;
OnChatWindowTextPtr = IntPtr.Zero;
OnChatWindowText = null;
OnChatBarEnter = null;
OnBarAction = null;
OnEnchantmentAdded = null;
OnEnchantmentRemoved = null;
Tick = null;
Render = null;
}
}

View file

@ -79,6 +79,9 @@ internal static class PluginLoader
/// </summary>
public static void Unload(LoadedPlugin plugin)
{
// Release managed thunks first so the module ref-count can drop to zero on FreeLibrary.
plugin.ClearResolvedDelegates();
if (plugin.ModuleHandle != IntPtr.Zero)
{
FreeLibrary(plugin.ModuleHandle);

View file

@ -1501,6 +1501,18 @@ internal static class PluginManager
var loaded = PluginLoader.LoadAll(_pluginsDir, _shadowRootDir, _loadGeneration);
_plugins.AddRange(loaded);
// Track DLL file names and canonical paths already staged this generation. Extra paths
// often repeat the same plugin as under Runtime\Plugins (e.g. RynthCore.Plugin.RynthAi.dll
// in both); a second File.Copy to the same shadow file name fails while the first copy
// is still mapped ("used by another process") and breaks hot-reload ordering for later DLLs.
var loadedBasenames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var loadedCanonicalPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var p in loaded)
{
loadedBasenames.Add(p.FileName);
TryAddCanonicalPath(loadedCanonicalPaths, p.SourceFilePath);
}
// Extra DLL paths from engine settings
var extraPaths = EngineSettings.PluginPaths;
for (int i = 0; i < extraPaths.Count; i++)
@ -1511,10 +1523,48 @@ internal static class PluginManager
RynthLog.Plugin($"PluginManager: Extra plugin not found: {dllPath}");
continue;
}
string baseName = Path.GetFileName(dllPath);
if (loadedBasenames.Contains(baseName))
{
RynthLog.Plugin($"PluginManager: Skipping extra plugin (same file name already loaded from plugins directory or earlier extra path): {dllPath}");
continue;
}
if (TryGetCanonicalPath(dllPath, out string extraCanon) && loadedCanonicalPaths.Contains(extraCanon))
{
RynthLog.Plugin($"PluginManager: Skipping extra plugin (same resolved path already loaded): {dllPath}");
continue;
}
RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath}");
var plugin = PluginLoader.LoadSingle(dllPath, _shadowRootDir, _loadGeneration);
if (plugin != null)
{
_plugins.Add(plugin);
loadedBasenames.Add(plugin.FileName);
TryAddCanonicalPath(loadedCanonicalPaths, plugin.SourceFilePath);
}
}
}
private static void TryAddCanonicalPath(HashSet<string> set, string path)
{
if (TryGetCanonicalPath(path, out string canon))
set.Add(canon);
}
private static bool TryGetCanonicalPath(string path, out string canonical)
{
try
{
canonical = Path.GetFullPath(path);
return true;
}
catch
{
canonical = string.Empty;
return false;
}
}

View file

@ -29,12 +29,18 @@
<Optimize>false</Optimize>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
<PackageReference Include="Avalonia" Version="11.2.3" />
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Skia" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.3" />
<!-- Overrides Avalonia.FreeDesktop transitive Tmds.DBus.Protocol (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>
@ -44,6 +50,10 @@
<!-- Prevent trimmer from removing ImGui.NET's DllImport methods -->
<!-- Root Avalonia assemblies so the AOT trimmer keeps them intact -->
<ItemGroup>
<TrimmerRootAssembly Include="RynthCore.DesktopLog" />
</ItemGroup>
<ItemGroup>
<TrimmerRootAssembly Include="ImGui.NET" />
<TrimmerRootAssembly Include="Avalonia" />
@ -62,38 +72,19 @@
<BundledSupportDll Include="Native\minhook.x86.dll" />
</ItemGroup>
<!-- Single ImGui native beside the engine: EntryPoint tries Runtime\RynthCore.cimgui.dll first (see EntryPoint.GetImGuiNativeCandidates). -->
<Target Name="CopyBundledNativeDlls" AfterTargets="Build">
<Copy
SourceFiles="@(BundledNativeDll)"
DestinationFiles="@(BundledNativeDll->'$(OutputPath)Native\%(Filename)%(Extension)')"
SkipUnchangedFiles="true" />
<Copy
SourceFiles="@(BundledNativeDll)"
DestinationFiles="@(BundledNativeDll->'$(OutputPath)Native\RynthCore.%(Filename)%(Extension)')"
SkipUnchangedFiles="true" />
<Copy
SourceFiles="@(BundledNativeDll)"
DestinationFiles="@(BundledNativeDll->'$(OutputPath)%(Filename)%(Extension)')"
SkipUnchangedFiles="true" />
<Copy
SourceFiles="@(BundledNativeDll)"
DestinationFiles="@(BundledNativeDll->'$(OutputPath)RynthCore.%(Filename)%(Extension)')"
SkipUnchangedFiles="true" />
<!-- ImGui.NET / publish may still emit plain cimgui.dll or Native\ copies; keep one prefixed name next to the engine. -->
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />
<Delete Files="$(OutputPath)Native\cimgui.dll" Condition="Exists('$(OutputPath)Native\cimgui.dll')" />
<Delete Files="$(OutputPath)Native\RynthCore.cimgui.dll" Condition="Exists('$(OutputPath)Native\RynthCore.cimgui.dll')" />
</Target>
<Target Name="CopyBundledNativeDllsToPublish" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<Copy
SourceFiles="@(BundledNativeDll)"
DestinationFiles="@(BundledNativeDll->'$(PublishDir)Native\%(Filename)%(Extension)')"
SkipUnchangedFiles="true" />
<Copy
SourceFiles="@(BundledNativeDll)"
DestinationFiles="@(BundledNativeDll->'$(PublishDir)Native\RynthCore.%(Filename)%(Extension)')"
SkipUnchangedFiles="true" />
<Copy
SourceFiles="@(BundledNativeDll)"
DestinationFiles="@(BundledNativeDll->'$(PublishDir)%(Filename)%(Extension)')"
SkipUnchangedFiles="true" />
<Copy
SourceFiles="@(BundledNativeDll)"
DestinationFiles="@(BundledNativeDll->'$(PublishDir)RynthCore.%(Filename)%(Extension)')"
@ -104,6 +95,13 @@
SkipUnchangedFiles="true" />
</Target>
<!-- Run after the full publish graph so package/ILC drops of cimgui.dll are removed last. -->
<Target Name="DedupePublishedCimguiCopies" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
<Delete Files="$(PublishDir)Native\cimgui.dll" Condition="Exists('$(PublishDir)Native\cimgui.dll')" />
<Delete Files="$(PublishDir)Native\RynthCore.cimgui.dll" Condition="Exists('$(PublishDir)Native\RynthCore.cimgui.dll')" />
</Target>
<Target Name="CopyBundledSupportDlls" AfterTargets="Build">
<Copy
SourceFiles="@(BundledSupportDll)"

View file

@ -20,43 +20,50 @@ internal static class RynthLog
/// <summary>D3D9 subsystem: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary>
internal static void D3D9(string msg)
{
if (D3D9Enabled) Write(msg);
if (D3D9Enabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
/// <summary>Compatibility hooks: SmartBox, client objects, combat, movement, vitals, chat, etc.</summary>
internal static void Compat(string msg)
{
if (CompatEnabled) Write(msg);
if (CompatEnabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
/// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary>
internal static void Render(string msg)
{
if (RenderEnabled) Write(msg);
if (RenderEnabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
/// <summary>Plugin system: loader, manager, lifecycle callbacks.</summary>
internal static void Plugin(string msg)
{
if (PluginEnabled) Write(msg);
if (PluginEnabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
/// <summary>UI / Avalonia overlay subsystem.</summary>
internal static void UI(string msg)
{
if (UIEnabled) Write(msg);
if (UIEnabled) WriteAt(EntryPoint.EngineLogLevel.Info, msg);
}
/// <summary>Verbose-only log (any category). Only written when VerboseLogging is on.</summary>
/// <summary>Debug-level log (any category).</summary>
internal static void Verbose(string msg)
{
if (EntryPoint.VerboseLogging) Write(msg);
WriteAt(EntryPoint.EngineLogLevel.Debug, msg);
}
/// <summary>Always-on log for critical / uncategorised messages.</summary>
internal static void Info(string msg) => Write(msg);
internal static void Trace(string msg) => WriteAt(EntryPoint.EngineLogLevel.Trace, msg);
internal static void Debug(string msg) => WriteAt(EntryPoint.EngineLogLevel.Debug, msg);
internal static void Info(string msg) => WriteAt(EntryPoint.EngineLogLevel.Info, msg);
internal static void Warning(string msg) => WriteAt(EntryPoint.EngineLogLevel.Warning, msg);
internal static void Error(string msg) => WriteAt(EntryPoint.EngineLogLevel.Error, msg);
// ── Sink ─────────────────────────────────────────────────────────────
private static void Write(string message) => EntryPoint.Log(message);
private static void WriteAt(EntryPoint.EngineLogLevel level, string message)
{
if (EntryPoint.ShouldLog(level))
EntryPoint.Log(message);
}
}

View file

@ -1,4 +1,5 @@
using System;
using RynthCore;
namespace RynthCore.Injector;
@ -15,6 +16,14 @@ internal static class Program
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine($"FATAL EXCEPTION: {ex}");
try
{
DesktopRollingLog.AppendLine(DesktopRollingLog.StemInjector,
$"FATAL: {ex.GetType().Name}: {ex.Message}");
}
catch
{
}
Console.ResetColor();
return 99;
}
@ -29,36 +38,50 @@ internal static class Program
private static int Run(string[] args)
{
var service = new EngineInjectionService();
void Line(string s)
{
Console.WriteLine(s);
try
{
string t = DateTime.Now.ToString("HH:mm:ss.fff");
DesktopRollingLog.AppendLine(DesktopRollingLog.StemInjector, $"[{t}] {s}");
}
catch
{
}
}
Console.WriteLine("========================================");
Console.WriteLine(" RynthCore Injector Console ");
Console.WriteLine("========================================");
Console.WriteLine();
Line("========================================");
Line(" RynthCore Injector Console ");
Line("========================================");
Line("");
string? enginePath = service.TryResolveEnginePath(args.Length > 0 ? args[0] : null);
if (enginePath == null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Could not locate {EngineInjectionService.EngineDllName}.");
Console.WriteLine("Copy it next to the injector or pass the full path as the first argument.");
Line($"Could not locate {EngineInjectionService.EngineDllName}.");
Line("Copy it next to the injector or pass the full path as the first argument.");
Console.ResetColor();
return 1;
}
InjectionResult result = service.InjectFirstRunning(enginePath, Console.WriteLine);
Console.WriteLine();
InjectionResult result = service.InjectFirstRunning(enginePath, Line);
Line("");
if (result.Success)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(result.Summary);
Console.WriteLine("Check Desktop\\RynthCore.log for in-process status.");
Line(result.Summary);
Line("Check Desktop\\RynthCore.log for in-process engine output. " +
"RynthCore-Launcher.log and RynthCore-Injector.log list launcher/injector. " +
"Each file rolls at 10 MB; up to 10 roll segments per day per file under Desktop\\RynthLogs.");
Console.ResetColor();
return 0;
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(result.Summary);
Line(result.Summary);
Console.ResetColor();
return result.ExitCode;
}

View file

@ -1,6 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj" />
</ItemGroup>
<PropertyGroup>
<!-- Build-Installer.ps1 publishes this project self-contained for the bundle (see BUILD.md). -->
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>