From c3e15480e59ace4b3b15aa276431978066fec8dc Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Mon, 5 Oct 2026 08:03:08 -0400 Subject: [PATCH] RynthCore as of 2026-10-05 (internal 0d3c210): dashboard slide-outs on the left (Ranges with the selected monster, Files, Patrol), fixed draggable vital bar, click an item to add a loot rule, loot rules by WCID, chat and loot editor typing no longer leaks into the game, title-bar text size, plugin API v76 (close container), plugin exception traces, plates drawn under the game UI (in testing), launcher account passwords encrypted with Windows DPAPI (in testing), release 2026.10.5.1 --- .../AccountProfileDialog.axaml.cs | 14 +- src/RynthCore.App.Avalonia/MainWindow.axaml | 2 +- .../MainWindow.axaml.cs | 22 +- .../RynthCore.App.Avalonia.csproj | 1 + src/RynthCore.App/AcLaunchArgumentBuilder.cs | 37 +- .../AccountPasswordProtection.cs | 138 +++++ src/RynthCore.App/AppSettingsStore.cs | 103 +++- src/RynthCore.App/LaunchAccountProfile.cs | 79 ++- .../Compatibility/AcMainThreadQueue.cs | 11 + .../Compatibility/ClientHelperHooks.cs | 59 +++ .../Compatibility/RynthCoreChatCommands.cs | 48 +- src/RynthCore.Engine/D3D9/AcUiPassHook.cs | 156 ++++++ .../D3D9/Nav3DRenderInjector.cs | 190 ++++++- src/RynthCore.Engine/EngineLifecycle.cs | 3 + src/RynthCore.Engine/EntryPoint.cs | 3 + src/RynthCore.Engine/Hooking/MinHook.cs | 2 + src/RynthCore.Engine/ImGui/DX9Backend.cs | 53 ++ .../ImGui/EngineFrameController.cs | 68 +-- src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs | 8 + src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs | 16 +- src/RynthCore.Engine/ImGui/ImGuiTextFocus.cs | 81 +++ .../ImGui/MonsterHud/MonsterHud.cs | 9 +- .../ImGui/MonsterHud/MonsterHudSettings.cs | 34 +- .../ImGui/MonsterHud/MonsterHudSettingsUi.cs | 69 ++- .../ImGui/MonsterHud/PlayerPlate.cs | 247 +++++++-- .../ImGui/Panels/DashboardDrawers.cs | 319 +++++++++++ src/RynthCore.Engine/ImGui/Panels/FaceKit.cs | 1 + .../ImGui/Panels/InventoryFace.cs | 9 + .../ImGui/Panels/LootAddDialog.cs | 380 +++++++++++++ .../ImGui/Panels/LootEditorFace.cs | 16 + .../ImGui/Panels/RangesSlideOut.cs | 501 ++++++++++++++++++ .../ImGui/Panels/RynthAiFace.Drawers.cs | 139 +++++ .../ImGui/Panels/RynthAiFace.cs | 117 ++-- .../ImGui/ScriptWindowReplay.cs | 3 + src/RynthCore.Engine/ImGui/UnderUiLayer.cs | 46 +- src/RynthCore.Engine/ImGui/Win32Backend.cs | 142 ++++- .../Plugins/PluginContract.cs | 14 +- src/RynthCore.Engine/Plugins/PluginManager.cs | 83 ++- src/RynthCore.Engine/UI/Data/LootEditData.cs | 49 ++ src/RynthCore.Engine/UI/Data/SettingsData.cs | 34 +- .../UI/RynthAiDashboardState.cs | 82 +-- src/RynthCore.Injector/LaunchCommand.cs | 23 +- .../RynthCore.Injector.csproj | 2 + src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 2 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 17 + .../LauncherSettingsTests.csproj | 6 +- tools/LauncherSettingsTests/Program.cs | 169 ++++++ tools/check_offthread_mutators.py | 2 + tools/navdata/test_gen_locations.py | 191 ------- tools/pe_pattern.py | 5 +- 50 files changed, 3315 insertions(+), 490 deletions(-) create mode 100644 src/RynthCore.App/AccountPasswordProtection.cs create mode 100644 src/RynthCore.Engine/D3D9/AcUiPassHook.cs create mode 100644 src/RynthCore.Engine/ImGui/ImGuiTextFocus.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs delete mode 100644 tools/navdata/test_gen_locations.py diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs index 0a530d1..8ec66c6 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs @@ -27,9 +27,11 @@ internal partial class AccountProfileDialog : Window AccountBox.Text = profile.AccountName; AliasBox.Text = profile.Alias; UserPrefsPathBox.Text = profile.UserPrefsPath; - PasswordHintText.Text = string.IsNullOrEmpty(profile.Password) - ? "No password is saved for this profile yet." - : "A password is already saved for this profile. It stays hidden unless you replace or clear it."; + PasswordHintText.Text = profile.PasswordNeedsReentry + ? "Password needs re-entering: the saved one can't be read on this Windows user (settings copied from another user or PC?). Type it again to launch this account." + : !profile.HasSavedPassword + ? "No password is saved for this profile yet." + : "A password is saved for this profile, encrypted for this Windows user. It stays hidden unless you replace or clear it."; SaveButton.Click += (_, _) => SaveAndClose(); CancelButton.Click += (_, _) => Close(false); @@ -116,12 +118,14 @@ internal partial class AccountProfileDialog : Window _profile.AccountName = AccountBox.Text.Trim(); if (ClearPasswordCheckBox.IsChecked == true) { - _profile.Password = string.Empty; + _profile.ClearPassword(); } else if (!string.IsNullOrEmpty(PasswordBox.Text)) { - _profile.Password = PasswordBox.Text; + // Encrypted at once (DPAPI, this Windows user); the plain text isn't kept on the profile. + _profile.SetPassword(PasswordBox.Text); } + PasswordBox.Text = string.Empty; _profile.Alias = AliasBox.Text?.Trim() ?? string.Empty; _profile.UserPrefsPath = UserPrefsPathBox.Text?.Trim() ?? string.Empty; diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml b/src/RynthCore.App.Avalonia/MainWindow.axaml index 87e5db8..4176226 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml @@ -199,7 +199,7 @@ diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index 2a6f970..d413a97 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -215,6 +215,17 @@ internal partial class MainWindow : Window LauncherDiag.Info("SETTINGS: " + migration); try { AppendActivity("Settings: " + migration); } catch { } } + // Password notes carry counts and account names only, never a password. + if (AppSettingsStore.LastPasswordMigrationNote is string passwordMigration) + { + LauncherDiag.Info("SETTINGS: " + passwordMigration); + try { AppendActivity("Settings: " + passwordMigration); } catch { } + } + if (AppSettingsStore.LastPasswordProblemNote is string passwordProblem) + { + LauncherDiag.Info("SETTINGS: " + passwordProblem); + try { AppendActivity("Settings: " + passwordProblem); } catch { } + } _settings.ServerProfiles ??= []; _settings.AccountProfiles ??= []; _settings.CheckedLaunchAccountProfileIds ??= []; @@ -3247,12 +3258,8 @@ internal partial class MainWindow : Window { try { - string args = _launchArgumentBuilder.BuildArguments(server, account); - string password = account.Password ?? string.Empty; - if (!string.IsNullOrEmpty(password)) - args = args.Replace(password, "********", StringComparison.Ordinal); - - return args; + // Never decrypts: a saved password shows as the mask. + return _launchArgumentBuilder.BuildMaskedArguments(server, account); } catch (Exception ex) { @@ -4338,7 +4345,8 @@ internal partial class MainWindow : Window { int digits = Math.Max(2, _settings.AccountProfiles.Count.ToString().Length); return _settings.AccountProfiles - .Select((account, index) => $"{FormatOrdinal(index, digits)} {account.DisplayName}") + .Select((account, index) => $"{FormatOrdinal(index, digits)} {account.DisplayName}" + + (account.PasswordNeedsReentry ? " [password needs re-entering]" : string.Empty)) .ToArray(); } diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index fb146b9..21664e8 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -30,6 +30,7 @@ + diff --git a/src/RynthCore.App/AcLaunchArgumentBuilder.cs b/src/RynthCore.App/AcLaunchArgumentBuilder.cs index 7508979..871a2e8 100644 --- a/src/RynthCore.App/AcLaunchArgumentBuilder.cs +++ b/src/RynthCore.App/AcLaunchArgumentBuilder.cs @@ -6,6 +6,14 @@ namespace RynthCore.App; internal sealed class AcLaunchArgumentBuilder { + /// Text shown in place of the password in previews. + public const string PasswordMask = "********"; + + /// + /// The client's command line, with the saved password decrypted now. The result carries the + /// password: hand it to the process and never log, display or keep it. Throws when the saved + /// password can't be decrypted on this Windows user (never launches with an empty one instead). + /// public string BuildArguments(LaunchServerProfile server, LaunchAccountProfile account) { ArgumentNullException.ThrowIfNull(server); @@ -13,17 +21,42 @@ internal sealed class AcLaunchArgumentBuilder Validate(server, account); + if (!account.TryGetPasswordForLaunch(out string password, out string problem)) + throw new InvalidOperationException(problem); + + return Build(server, account, password); + } + + /// + /// The same command line for display: the password is never decrypted, a saved one shows as + /// . + /// + public string BuildMaskedArguments(LaunchServerProfile server, LaunchAccountProfile account) + { + ArgumentNullException.ThrowIfNull(server); + ArgumentNullException.ThrowIfNull(account); + + Validate(server, account); + + if (account.PasswordNeedsReentry) + return LaunchAccountProfile.PasswordNeedsReentryMessage(account.AccountName); + + return Build(server, account, account.HasSavedPassword ? PasswordMask : string.Empty); + } + + private static string Build(LaunchServerProfile server, LaunchAccountProfile account, string password) + { return server.Emulator switch { AcEmulatorKind.Ace => string.Join(" ", "-a", Quote(account.AccountName), - "-v", Quote(account.Password), + "-v", Quote(password), "-h", Quote(server.ConnectionString), "-rodat", server.RodatEnabled ? "on" : "off"), AcEmulatorKind.Gdle => string.Join(" ", "-h", Quote(server.Host), "-p", server.Port.ToString(CultureInfo.InvariantCulture), - "-a", Quote($"{account.AccountName}:{account.Password}"), + "-a", Quote($"{account.AccountName}:{password}"), "-rodat", server.RodatEnabled ? "on" : "off"), _ => throw new InvalidOperationException($"Unsupported emulator type '{server.Emulator}'.") }; diff --git a/src/RynthCore.App/AccountPasswordProtection.cs b/src/RynthCore.App/AccountPasswordProtection.cs new file mode 100644 index 0000000..e99b14f --- /dev/null +++ b/src/RynthCore.App/AccountPasswordProtection.cs @@ -0,0 +1,138 @@ +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; + +namespace RynthCore.App; + +/// +/// Saved account passwords are encrypted with Windows DPAPI (CryptProtectData, CurrentUser +/// scope, the same call System.Security.Cryptography.ProtectedData makes) plus an app-specific +/// entropy constant, and kept in settings as base64 (LaunchAccountProfile.PasswordProtected). +/// Only the Windows user that saved a password can decrypt it; settings copied to another user +/// or PC can't be decrypted, and such an account shows "password needs re-entering". +/// +/// Decrypt only at the moment of use (building the client's launch arguments) and never keep +/// the result in a long-lived object. Never log, display or copy a password. +/// +/// Shared source: compiled into the launcher, RynthCore.Injector (--launch) and +/// tools\LauncherSettingsTests. +/// +internal static class AccountPasswordProtection +{ + // Changing this makes every saved password unreadable. Bump the suffix only with a migration. + private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("RynthCore.Launcher.AccountPassword.v1"); + + private const int CryptProtectUiForbidden = 0x1; + + /// Encrypts a password for this Windows user. Empty in, empty out. + public static string Protect(string? plainText) + { + if (string.IsNullOrEmpty(plainText)) + return string.Empty; + + byte[] plain = Encoding.UTF8.GetBytes(plainText); + try + { + return Convert.ToBase64String(Transform(plain, protect: true)); + } + finally + { + Array.Clear(plain); + } + } + + /// + /// Decrypts a value written by . False when it can't be read on this + /// Windows user (copied from another user or PC, damaged base64, wrong entropy). + /// + public static bool TryUnprotect(string? protectedBase64, out string plainText) + { + plainText = string.Empty; + if (string.IsNullOrEmpty(protectedBase64)) + return false; + + byte[] blob; + try + { + blob = Convert.FromBase64String(protectedBase64); + } + catch (FormatException) + { + return false; + } + + byte[]? plain = null; + try + { + plain = Transform(blob, protect: false); + plainText = Encoding.UTF8.GetString(plain); + return true; + } + catch (Exception ex) when (ex is Win32Exception or PlatformNotSupportedException or EntryPointNotFoundException or DllNotFoundException) + { + return false; + } + finally + { + if (plain != null) + Array.Clear(plain); + } + } + + /// True when the value decrypts on this Windows user (the password itself is discarded). + public static bool CanUnprotect(string? protectedBase64) => TryUnprotect(protectedBase64, out _); + + private static byte[] Transform(byte[] input, bool protect) + { + GCHandle inputHandle = GCHandle.Alloc(input, GCHandleType.Pinned); + GCHandle entropyHandle = GCHandle.Alloc(Entropy, GCHandleType.Pinned); + var output = new DataBlob(); + try + { + var inputBlob = new DataBlob { cbData = input.Length, pbData = inputHandle.AddrOfPinnedObject() }; + var entropyBlob = new DataBlob { cbData = Entropy.Length, pbData = entropyHandle.AddrOfPinnedObject() }; + + bool ok = protect + ? CryptProtectData(ref inputBlob, null, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output) + : CryptUnprotectData(ref inputBlob, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output); + if (!ok) + throw new Win32Exception(Marshal.GetLastWin32Error()); + + byte[] result = new byte[output.cbData]; + if (output.cbData > 0) + Marshal.Copy(output.pbData, result, 0, output.cbData); + return result; + } + finally + { + if (output.pbData != IntPtr.Zero) + { + // Wipe the native copy (the plain text, when decrypting) before freeing it. + for (int i = 0; i < output.cbData; i++) + Marshal.WriteByte(output.pbData, i, 0); + LocalFree(output.pbData); + } + inputHandle.Free(); + entropyHandle.Free(); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct DataBlob + { + public int cbData; + public IntPtr pbData; + } + + [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern bool CryptProtectData(ref DataBlob pDataIn, string? szDataDescr, ref DataBlob pOptionalEntropy, + IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut); + + [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern bool CryptUnprotectData(ref DataBlob pDataIn, IntPtr ppszDataDescr, ref DataBlob pOptionalEntropy, + IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut); + + [DllImport("kernel32.dll")] + private static extern IntPtr LocalFree(IntPtr hMem); +} diff --git a/src/RynthCore.App/AppSettingsStore.cs b/src/RynthCore.App/AppSettingsStore.cs index 1c7aa7b..c9c48f8 100644 --- a/src/RynthCore.App/AppSettingsStore.cs +++ b/src/RynthCore.App/AppSettingsStore.cs @@ -46,11 +46,112 @@ internal static class AppSettingsStore /// public static string? LastMigrationNote { get; private set; } + /// + /// Set when the last Load() encrypted plain-text account passwords from an older settings + /// file ("migrated N account password(s) to encrypted storage"), or could not. Never holds a + /// password. Null otherwise. + /// + public static string? LastPasswordMigrationNote { get; private set; } + + /// + /// Set when the last Load() found saved passwords this Windows user can't decrypt (settings + /// copied from another user or PC); those accounts have PasswordNeedsReentry set. Null otherwise. + /// + public static string? LastPasswordProblemNote { get; private set; } + public static AppSettings Load() { LastLoadDiagnostic = null; LastMigrationNote = null; - return ApplyDecalAccounts(LoadShared()); + LastPasswordMigrationNote = null; + LastPasswordProblemNote = null; + // Passwords after the Decal accounts: a save before ApplyDecalAccounts would drop + // decal-accounts.json (every account still reads as RynthCore at that point). + AppSettings settings = ApplyDecalAccounts(LoadShared()); + MigratePasswords(settings); + return settings; + } + + /// + /// Encrypts plain-text passwords from an older appsettings.json (LaunchAccountProfile + /// "Password") into PasswordProtected and saves once, .bak included, so the plain text is + /// gone from both files. Also marks accounts whose encrypted password this Windows user can't + /// decrypt. Never logs or reports a password. + /// + private static void MigratePasswords(AppSettings settings) + { + int migrated = 0, cleared = 0, failed = 0; + var unreadable = new List(); + foreach (LaunchAccountProfile account in settings.AccountProfiles ?? new List()) + { + if (account.LegacyPlainPassword != null) + { + if (account.LegacyPlainPassword.Length == 0) + { + account.LegacyPlainPassword = null; + cleared++; + continue; + } + try + { + account.PasswordProtected = AccountPasswordProtection.Protect(account.LegacyPlainPassword); + account.LegacyPlainPassword = null; + account.PasswordNeedsReentry = false; + migrated++; + } + catch + { + failed++; // kept as it was (still usable); the next load tries again + } + continue; + } + + if (!string.IsNullOrEmpty(account.PasswordProtected) && + !AccountPasswordProtection.CanUnprotect(account.PasswordProtected)) + { + account.PasswordNeedsReentry = true; + unreadable.Add(string.IsNullOrWhiteSpace(account.AccountName) ? account.Id : account.AccountName); + } + } + + if (unreadable.Count > 0) + { + LastPasswordProblemNote = $"{unreadable.Count} saved account password(s) can't be decrypted on this Windows user " + + $"(settings copied from another user or PC?) and need re-entering: {string.Join(", ", unreadable)}."; + } + + if (migrated + cleared == 0) + { + if (failed > 0) + LastPasswordMigrationNote = $"Could not encrypt {failed} account password(s); they stay as they were and the next start tries again."; + return; + } + + try + { + Save(settings); + // Save() moved the old file (plain text) to .bak: replace it with the encrypted one. + File.Copy(SettingsPath, BackupPath, overwrite: true); + if (migrated == 0 && failed == 0) + return; // only empty plain-text fields removed + LastPasswordMigrationNote = $"migrated {migrated} account password(s) to encrypted storage"; + if (failed > 0) + LastPasswordMigrationNote += $"; {failed} could not be encrypted and stay as they were"; + int quarantined = CountQuarantinedFiles(); + if (quarantined > 0) + LastPasswordMigrationNote += $". {quarantined} older appsettings.json.corrupt-* file(s) in {SettingsDirectory} " + + "may still hold plain-text passwords; delete them when no longer needed"; + } + catch (Exception ex) + { + LastPasswordMigrationNote = $"Could not save the encrypted account passwords ({ex.GetType().Name}); the next save retries."; + } + } + + private static int CountQuarantinedFiles() + { + try { return Directory.GetFiles(SettingsDirectory, "appsettings.json.corrupt-*").Length; } + catch { return 0; } } private static AppSettings LoadShared() diff --git a/src/RynthCore.App/LaunchAccountProfile.cs b/src/RynthCore.App/LaunchAccountProfile.cs index ac75d6b..c66b3ce 100644 --- a/src/RynthCore.App/LaunchAccountProfile.cs +++ b/src/RynthCore.App/LaunchAccountProfile.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; namespace RynthCore.App; @@ -12,7 +13,26 @@ internal sealed class LaunchAccountProfile public string Id { get; set; } = Guid.NewGuid().ToString("N"); public string AccountName { get; set; } = string.Empty; - public string Password { get; set; } = string.Empty; + + /// The saved password, DPAPI-encrypted for the current Windows user (base64, see + /// AccountPasswordProtection). Empty = no password saved. Decrypt only when launching: + /// TryGetPasswordForLaunch. + public string PasswordProtected { get; set; } = string.Empty; + + /// Plain-text "Password" from a settings file written before passwords were encrypted. + /// Read only: AppSettingsStore.Load encrypts it into PasswordProtected and clears this, so it + /// is never written again (null is skipped on save). Stays set only if encryption failed. + [JsonPropertyName("Password")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? LegacyPlainPassword { get; set; } + + /// Set when the saved password can't be decrypted on this Windows user (settings copied + /// from another user or PC). The UI asks for the password again; launching is refused. + [JsonIgnore] + public bool PasswordNeedsReentry { get; set; } + + [JsonIgnore] + public bool HasSavedPassword => !string.IsNullOrEmpty(PasswordProtected) || !string.IsNullOrEmpty(LegacyPlainPassword); public string CharacterName { get; set; } = string.Empty; public string Alias { get; set; } = string.Empty; public string ServerId { get; set; } = string.Empty; @@ -65,7 +85,9 @@ internal sealed class LaunchAccountProfile { Id = Id, AccountName = AccountName, - Password = Password, + PasswordProtected = PasswordProtected, + LegacyPlainPassword = LegacyPlainPassword, + PasswordNeedsReentry = PasswordNeedsReentry, CharacterName = CharacterName, Alias = Alias, ServerId = ServerId, @@ -84,7 +106,9 @@ internal sealed class LaunchAccountProfile { Id = source.Id; AccountName = source.AccountName; - Password = source.Password; + PasswordProtected = source.PasswordProtected; + LegacyPlainPassword = source.LegacyPlainPassword; + PasswordNeedsReentry = source.PasswordNeedsReentry; CharacterName = source.CharacterName; Alias = source.Alias; ServerId = source.ServerId; @@ -98,6 +122,55 @@ internal sealed class LaunchAccountProfile OnLoginWaitMs = source.OnLoginWaitMs; } + /// Saves a new password (encrypted at once; the plain text is not kept). + public void SetPassword(string? plainText) + { + PasswordProtected = AccountPasswordProtection.Protect(plainText); + LegacyPlainPassword = null; + PasswordNeedsReentry = false; + } + + public void ClearPassword() + { + PasswordProtected = string.Empty; + LegacyPlainPassword = null; + PasswordNeedsReentry = false; + } + + /// + /// The password to hand the client, decrypted now. True with "" when none is saved. False + /// (and PasswordNeedsReentry set) when the saved one can't be decrypted on this Windows user; + /// the caller must not launch with an empty password instead. Use the result at once and + /// don't store it. + /// + public bool TryGetPasswordForLaunch(out string password, out string problem) + { + problem = string.Empty; + if (!string.IsNullOrEmpty(LegacyPlainPassword)) + { + password = LegacyPlainPassword; + return true; + } + if (string.IsNullOrEmpty(PasswordProtected)) + { + password = string.Empty; + return true; + } + if (AccountPasswordProtection.TryUnprotect(PasswordProtected, out password)) + { + PasswordNeedsReentry = false; + return true; + } + + PasswordNeedsReentry = true; + problem = PasswordNeedsReentryMessage(AccountName); + return false; + } + + public static string PasswordNeedsReentryMessage(string? accountName) => + $"The saved password for account '{accountName}' can't be read on this Windows user " + + "(settings copied from another user or PC?). Password needs re-entering: edit the account and type it again."; + public override string ToString() { return DisplayName; diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 519b0d3..0b445d6 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -146,6 +146,11 @@ internal static class AcMainThreadQueue // send like Trade, so it rides the ring too. A = PlayerTraining.TrainKind, B = stype, C = XP // (skill credits for TrainKind.TrainWithCredits: Event_TrainSkillAdvancementClass, 0x0047). Train, + // v76 CloseContainer (2026-10-04): CM_Inventory::Event_NoLongerViewingContents (the + // 0x0195 game action the client sends when a corpse/chest window closes). An inventory + // send like DropItem; in the ring so a close queued before the next corpse's UseObject + // goes out first, in the same drain. A = container id. + CloseContainer, } // Four payload slots cover every routed action (the 4th was added for @@ -332,6 +337,9 @@ internal static class AcMainThreadQueue public static bool EnqueueDropItem(uint objectId) => Enqueue(ActionKind.DropItem, objectId, 0, 0); + public static bool EnqueueCloseContainer(uint containerId) => + Enqueue(ActionKind.CloseContainer, containerId, 0, 0); + public static bool EnqueueTrade(uint op, uint a, uint b) => Enqueue(ActionKind.Trade, op, a, b); @@ -531,6 +539,9 @@ internal static class AcMainThreadQueue case ActionKind.DropItem: ClientHelperHooks.DropItem(e.A); break; + case ActionKind.CloseContainer: + ClientHelperHooks.CloseContainer(e.A); + break; case ActionKind.Trade: PlayerTrade.RunQueued(e.A, e.B, e.C); break; diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index cfc9844..e034e41 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -94,6 +94,20 @@ internal static class ClientHelperHooks [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate byte EventDropItemDelegate(uint objectId); + // CM_Inventory::Event_NoLongerViewingContents(ulong containerId) - the 0x0195 + // NoLongerViewingContents game action, the packet the client sends to close an external + // container (corpse, chest). Same generated shape as Event_DropItem (cdecl, returns bool, + // one argument) with opcode 0x0195. Entry 0x006ACBB0. Its one caller is + // ClientUISystem::SetGroundContainer(newId, notifyServer) @0x005652B0, which sends it for + // the old ground container when notifyServer is set: the container window's close and + // opening a second container both go through there. ACE (Player.HandleActionNoLongerViewingContents) + // closes the container if this player is its viewer and answers with CloseGroundContainer + // (0x0052); the client's own handler for that tears the window down + // (SetGroundContainer(0, false)), clears the pending-request slot for that container + // (ACCWeenieObject::RecordResponse) and runs ACCObjectMaint::StopViewingObjectContents. + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate byte EventNoLongerViewingContentsDelegate(uint containerId); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void UseObjectDelegate(IntPtr clientUiSystem, uint objectId); @@ -132,6 +146,8 @@ internal static class ClientHelperHooks private const int EventGetAndWieldItemVa = 0x006AC950; // CM_Inventory::Event_DropItem — drop an item on the ground (FALLBACK only; pattern-scanned). private const int EventDropItemVa = 0x006AC880; + // CM_Inventory::Event_NoLongerViewingContents - close an external container (FALLBACK only; pattern-scanned). + private const int EventNoLongerViewingContentsVa = 0x006ACBB0; private const int UseObjectVa = 0x00565750; private const int PlayerSystemVa = 0x0087119C; private const int InqPlayerCoordsVa = 0x00560E00; @@ -155,6 +171,7 @@ internal static class ClientHelperHooks private static EventGiveObjectRequestDelegate? _eventGiveObjectRequest; private static EventGetAndWieldItemDelegate? _eventGetAndWieldItem; private static EventDropItemDelegate? _eventDropItem; + private static EventNoLongerViewingContentsDelegate? _eventNoLongerViewingContents; private static InqPlayerCoordsDelegate? _inqPlayerCoords; private static GetPlayerIdDelegate? _getPlayerId; private static AddTextToScrollDelegate? _addTextToScroll; @@ -182,6 +199,7 @@ internal static class ClientHelperHooks public static bool HasGiveObjectTo => _eventGiveObjectRequest != null; public static bool HasWieldItem => _eventGetAndWieldItem != null; public static bool HasDropItem => _eventDropItem != null; + public static bool HasCloseContainer => _eventNoLongerViewingContents != null; public static bool HasGetCurCoords => _inqPlayerCoords != null; public static bool HasGetPlayerId => _getPlayerId != null; public static bool HasGetGroundContainerId => true; @@ -219,6 +237,11 @@ internal static class ClientHelperHooks // unique (1 match @0x006AC880) over the engine's scan window against both acclient // copies (C:\Turbine and C:\Games\RynthCore\AcClient), 2026-09-30. private static readonly byte?[] PatEventDropItem = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x1B ]; + // CM_Inventory::Event_NoLongerViewingContents @0x006ACBB0. Byte-identical to Event_DropItem + // except the opcode immediate (0x0195, so the last two bytes are 0x95 0x01 where DropItem has + // 0x1B). Verified unique (1 match @0x006ACBB0) over the engine's scan window against + // C:\Games\RynthCore\AcClient\acclient.exe, 2026-10-04. + private static readonly byte?[] PatEventNoLongerViewingContents = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x95, 0x01 ]; private static readonly byte?[] PatInqPlayerCoords =[ 0x83, 0xEC, 0x10, 0x53, 0x8B, 0x5C, 0x24, 0x1C, 0x55, 0x56 ]; private static readonly byte?[] PatGetPlayerId = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x07 ]; private static readonly byte?[] PatAddTextToScroll = [ 0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84 ]; @@ -281,6 +304,7 @@ internal static class ClientHelperHooks _eventGiveObjectRequest = Bind(text, "ClientHelper.Event_GiveObjectRequest", PatEventGiveObjectRequest, EventGiveObjectRequestVa); _eventGetAndWieldItem = Bind(text, "ClientHelper.Event_GetAndWieldItem", PatEventGetAndWieldItem, EventGetAndWieldItemVa); _eventDropItem = Bind(text, "ClientHelper.Event_DropItem", PatEventDropItem, EventDropItemVa); + _eventNoLongerViewingContents = Bind(text, "ClientHelper.Event_NoLongerViewingContents", PatEventNoLongerViewingContents, EventNoLongerViewingContentsVa); _inqPlayerCoords = Bind(text, "ClientHelper.InqPlayerCoords", PatInqPlayerCoords, InqPlayerCoordsVa); _getPlayerId = Bind(text, "ClientHelper.GetPlayerId", PatGetPlayerId, GetPlayerIdVa); _addTextToScroll = Bind(text, "ClientHelper.AddTextToScroll", PatAddTextToScroll, AddTextToScrollVa); @@ -776,6 +800,40 @@ internal static class ClientHelperHooks } } + /// + /// Close an external container (a corpse, a chest) the way the client does when its window + /// is closed: CM_Inventory::Event_NoLongerViewingContents (cdecl) at 0x006ACBB0, the 0x0195 + /// NoLongerViewingContents game action. Packet only, like DropItem: no busy count (m_cBusy), + /// no pending-request slot (it is not an inventory request; RecordRequest is not called). + /// The server closes the container if this player is viewing it and answers with + /// CloseGroundContainer (0x0052), whose client handler closes the window and raises + /// StopViewingObjectContents to the plugins. A container this player isn't viewing is + /// ignored by the server (no answer). Runs on AC's main thread, in the action ring, so a + /// close queued just before the next UseObject goes out first, in the same frame. + /// + public static bool CloseContainer(uint containerId) + { + // An inventory game-action send, like DropItem / WieldItem: main thread only. + if (!MainThreadGuard.IsOnMainThread()) + return _eventNoLongerViewingContents != null && IsValidObjectId(containerId) + && AcMainThreadQueue.EnqueueCloseContainer(containerId); + + if (_eventNoLongerViewingContents == null) return false; + if (!IsValidObjectId(containerId)) return false; + + try + { + byte rv = _eventNoLongerViewingContents(containerId); + RynthLog.Verbose($"Compat: Event_NoLongerViewingContents container=0x{containerId:X8} rv={rv}"); + return rv != 0; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: Event_NoLongerViewingContents threw - {ex.Message}"); + return false; + } + } + public static bool TryGetCurCoords(out double northSouth, out double eastWest) { northSouth = 0; @@ -1172,6 +1230,7 @@ internal static class ClientHelperHooks _eventGiveObjectRequest = null; _eventGetAndWieldItem = null; _eventDropItem = null; + _eventNoLongerViewingContents = null; _inqPlayerCoords = null; _getPlayerId = null; Volatile.Write(ref _cachedPlayerId, 0); diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 809413b..125d05f 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -45,6 +45,10 @@ namespace RynthCore.Engine.Compatibility; /// () and why; aelrynth/other force it for this session. /// /rc mastery — the Aelrynth mastery feed's state (), /// and ask the server for /mastery-data again. +/// /rc worldlayer [auto|uipass|transition|endscene] — where the world overlays +/// (nameplates, combat text, Nav3D markers) draw in AC's frame +/// (): alone it reports the path and counters; +/// a mode forces it for this session (A/B checks). Auto at every start; not saved. /// /// internal static class RynthCoreChatCommands @@ -141,6 +145,14 @@ internal static class RynthCoreChatCommands return true; } + // /rc worldlayer [auto|uipass|transition|endscene] : where the world overlays draw + if (IsVerb(sub, "worldlayer", out string worldArgs)) + { + try { HandleWorldLayerCommand(worldArgs); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc worldlayer failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + // /rc vtank [clear] : what the engine knows about VTank's macro (Decal bridge only); // clear = VTank was stopped with its own button, which the engine can't see. if (IsVerb(sub, "vtank", out string vtankArgs)) @@ -404,6 +416,33 @@ internal static class RynthCoreChatCommands MasteryFeed.RequestRefresh(); } + /// + /// /rc worldlayer: report (no argument / status) or force (auto, uipass, transition, + /// endscene) where the world overlays draw. The render thread picks the mode up next + /// frame; the DIP hook is switched at the next frame boundary. + /// + private static void HandleWorldLayerCommand(string arg) + { + D3D9.WorldLayerMode? mode = arg.ToLowerInvariant() switch + { + "auto" => D3D9.WorldLayerMode.Auto, + "uipass" or "ui" => D3D9.WorldLayerMode.UiPass, + "transition" or "zenable" => D3D9.WorldLayerMode.Transition, + "endscene" => D3D9.WorldLayerMode.EndScene, + _ => null, + }; + if (mode is { } m) + { + D3D9.Nav3DRenderInjector.Mode = m; + Reply($"World overlays now: {D3D9.Nav3DRenderInjector.DescribePath()} (this session only)."); + return; + } + if (arg.Length > 0 && !arg.Equals("status", StringComparison.OrdinalIgnoreCase)) + Reply("Usage: /rc worldlayer [auto|uipass|transition|endscene]"); + Reply(D3D9.Nav3DRenderInjector.Describe()); + Reply(ImGuiBackend.UnderUiLayer.Describe()); + } + private static bool IsVerb(string sub, string verb, out string args) { args = string.Empty; @@ -422,7 +461,8 @@ internal static class RynthCoreChatCommands /// private static void HandlePlatesCommand(string args) { - const string usage = "Usage: /rv plates [on|off] | all on|off | self [numbers|name|firstperson] [on|off] | " + + const string usage = "Usage: /rv plates [on|off] | all on|off | self [numbers|name|firstperson|lock] [on|off] | " + + "self fixed|follow|unlock|reset | " + "debuffs [on|off] | others [on|off] | numbers [dealt|taken|heals|kills] [on|off] | " + "gains [xp|lum|radiance] [on|off] | npcs [on|off] | npcs dist |max | players [on|off] | all|engaged |dist |max |scale |opacity |lift | " + "names|hp|level|weak|distance|fade|click [on|off] | reset | status | test"; @@ -469,6 +509,12 @@ internal static class RynthCoreChatCommands case "numbers": case "text": S.SelfNumbers = Flag(subValue, S.SelfNumbers); break; case "name": S.SelfName = Flag(subValue, S.SelfName); break; case "firstperson": case "fp": S.SelfHideFirstPerson = Flag(subValue, S.SelfHideFirstPerson); break; + // Placement: fixed on screen (drag it while unlocked) or following the character. + case "fixed": case "screen": S.SelfPlacement = ImGuiBackend.Hud.SelfPlacement.Fixed; break; + case "follow": case "world": S.SelfPlacement = ImGuiBackend.Hud.SelfPlacement.Follow; break; + case "lock": S.SelfLocked = subValue == null || Flag(subValue, S.SelfLocked); break; + case "unlock": S.SelfLocked = false; break; + case "reset": S.SelfFixedX = S.DefaultSelfFixedX; S.SelfFixedY = S.DefaultSelfFixedY; break; case "position": case "pos": { string? w = subValue?.ToLowerInvariant(); diff --git a/src/RynthCore.Engine/D3D9/AcUiPassHook.cs b/src/RynthCore.Engine/D3D9/AcUiPassHook.cs new file mode 100644 index 0000000..5fffa56 --- /dev/null +++ b/src/RynthCore.Engine/D3D9/AcUiPassHook.cs @@ -0,0 +1,156 @@ +// ============================================================================ +// RynthCore.Engine - D3D9/AcUiPassHook.cs +// Hooks AC's RenderUI::RenderObjects, the call that draws AC's 2D UI, so the +// world overlays (Nav3D markers, nameplates, combat text) draw right before +// it: after ALL of AC's 3D (alpha-sorted foliage and effects included) and +// under every AC window. +// +// Why a function hook and not a D3D state signal (2026-10-04, plates drew +// behind foliage): AC's frame is Client::UseTime -> SceneTool::StartFrame -> +// SmartBox::Draw (the whole 3D scene) -> SceneTool::EndFrame, and EndFrame +// sets a full-screen viewport, calls RenderUI::RenderObjects (each UI +// element's surface, in z-order), KeyStone::Update, the debug HUDs, restores +// the viewport and ends the scene. Inside SmartBox::Draw, ZENABLE goes 1->0 +// more than once before the UI: the outdoor sky pass after the landblocks +// (LScape -> sky pass 1, depth mode ALWAYS/no-write, DrawObjCellForDummies) +// draws with Z off, and only AFTER it does SmartBox::RenderNormalMode flush +// the deferred alpha list (D3DPolyRender::FlushAlphaList(0)) - where the +// alpha-sorted foliage and effects draw. The old "first ZENABLE 1->0" signal +// fired at that sky pass, so the alpha list covered the plates. The entry of +// RenderUI::RenderObjects is exactly "3D done, 2D UI begins", costs one call +// per frame instead of work on every draw, and needs no prediction. +// Evidence and addresses: ops/overnight/2026-10-04-plates-foliage.md (Aeshnidae). +// +// The function takes no arguments and returns nothing (it loads ecx itself; +// its caller doesn't use eax/ecx/edx after it), so a cdecl void() detour is +// exact. AC's main thread only (the render thread). A frame where AC draws no +// UI never calls it; the overlays then draw at EndScene (the existing +// fallback), which is also "after all 3D". +// +// Teardown: EngineLifecycle calls Uninstall before EndSceneHook.Uninstall, so +// the detour stops entering the overlay code before UnderUiLayer/DX9Backend +// are torn down (EndSceneHook.Uninstall then waits 80 ms for a call in flight). +// The hook is only disabled, like every Compatibility hook at MH_DisableHook(ALL); +// the next generation's HookCreate reclaims the target (reload recovery / the +// loader facade). +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.D3D9; + +internal static class AcUiPassHook +{ + // RenderUI::RenderObjects on the 4,841,472-byte client. Pattern is the source of truth. + private const int RenderObjectsFallbackVa = 0x004488A0; + + // mov eax,[list count]; sub esp,8; push esi; xor esi,esi; test eax,eax; + // mov byte [in-render flag],1; mov dword [..],0; mov ecx,imm; jbe +10; + // mov eax,[list head]; test eax,eax; je +5; lea esi,[eax-8]; jmp +2; xor esi,esi; + // test esi,esi; mov [esp+8],ecx; je +20. Unique in .text (checked 2026-10-04 on + // both C:\Turbine and C:\Games\RynthCore\AcClient copies); absolute addresses wildcarded. + private static readonly byte?[] RenderObjectsPattern = + [ + 0xA1, null, null, null, null, + 0x83, 0xEC, 0x08, + 0x56, + 0x33, 0xF6, + 0x85, 0xC0, + 0xC6, 0x05, null, null, null, null, 0x01, + 0xC7, 0x05, null, null, null, null, 0x00, 0x00, 0x00, 0x00, + 0xB9, null, null, null, null, + 0x76, 0x10, + 0xA1, null, null, null, null, + 0x85, 0xC0, + 0x74, 0x05, + 0x8D, 0x70, 0xF8, + 0xEB, 0x02, + 0x33, 0xF6, + 0x85, 0xF6, + 0x89, 0x4C, 0x24, 0x08, + 0x74, 0x20, + ]; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void RenderObjectsD(); + + private static RenderObjectsD? _original; + private static RenderObjectsD? _detour; + private static IntPtr _target; + private static long _calls; + + /// True once the hook is live. Read on AC's render thread every frame. + public static volatile bool IsInstalled; + + public static string Status { get; private set; } = "not installed"; + + /// AC UI passes seen since install (diagnostics). + public static long Calls => Interlocked.Read(ref _calls); + + /// InitWorker step. Resolves and hooks RenderUI::RenderObjects. Idempotent. + public static void Initialize() + { + if (IsInstalled) return; + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + Status = "acclient.exe not available"; + return; + } + + var r = HookResolver.Resolve(text, "AcUiPassHook.RenderUI::RenderObjects", + RenderObjectsPattern, RenderObjectsFallbackVa); + if (!r.Success) + { + Status = $"not resolved ({r.Detail}); overlays use the ZENABLE transition"; + RynthLog.Compat($"AcUiPassHook: {Status}"); + return; + } + + try + { + _target = r.Address; + _detour = Detour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_detour); + _original = Marshal.GetDelegateForFunctionPointer(MinHook.HookCreate(_target, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(_target); + IsInstalled = true; + Status = $"hooked RenderUI::RenderObjects @ 0x{_target.ToInt32():X8} ({r.Detail})"; + RynthLog.Compat($"AcUiPassHook: {Status}"); + } + catch (Exception ex) + { + Status = $"install failed: {ex.Message}"; + RynthLog.Compat($"AcUiPassHook: install threw {ex.GetType().Name}: {ex.Message}"); + } + } + + /// + /// Engine shutdown / hot reload (lifecycle thread), before the render-side teardown: + /// stops the detour drawing at once, then disables the hook. Idempotent. + /// + public static void Uninstall() + { + if (!IsInstalled) return; + IsInstalled = false; // the detour checks this first: no overlay draw from here on + Thread.MemoryBarrier(); + int status = MinHook.MH_DisableHook(_target); + Status = $"uninstalled (disable = {MinHook.StatusString(status)})"; + RynthLog.Compat($"AcUiPassHook: {Status}"); + } + + private static void Detour() + { + Interlocked.Increment(ref _calls); + if (IsInstalled && !EngineLifecycle.IsShuttingDown) + { + try { Nav3DRenderInjector.OnAcUiPass(); } + catch { /* never let an overlay problem take AC's UI pass down */ } + } + _original!(); + } +} diff --git a/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs b/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs index f710890..a64fc9c 100644 --- a/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs +++ b/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs @@ -1,8 +1,22 @@ // ═══════════════════════════════════════════════════════════════════════════ // RynthCore.Engine — D3D9/Nav3DRenderInjector.cs -// Hooks DrawIndexedPrimitive to inject nav marker rendering at the -// 3D→UI boundary. When ZENABLE transitions from 1→0, renders markers -// so they appear after the 3D world but before the game's UI pass. +// Where the world overlays (Nav3D markers, then UnderUiLayer's nameplates and +// combat text) draw in AC's frame: after AC's 3D world, before AC's 2D UI. +// At most once per frame (one flag for every path). +// +// Paths, in order of preference (WorldLayerMode.Auto): +// UI pass AcUiPassHook: the entry of AC's RenderUI::RenderObjects, after +// all 3D including the alpha-sorted foliage/effects list. One +// call per frame; the DrawIndexedPrimitive hook below is then +// switched OFF (no per-draw cost). +// Transition only when the UI-pass hook isn't installed: the DIP hook spots +// ZENABLE going 1->0 after 3D draws. Known to fire too early +// outdoors (AC's sky pass after the landblocks draws with Z off, +// before the alpha list), so foliage can cover the overlays. +// EndScene the fallback (EngineFrameController): a frame where neither +// fired (no AC UI this frame, portal space, a loading screen). +// "/rc worldlayer" reports the path and counters, and "/rc worldlayer +// auto|uipass|transition|endscene" forces a path for the session (A/B checks). // ═══════════════════════════════════════════════════════════════════════════ using System; @@ -12,6 +26,19 @@ using RynthCore.Engine.Hooking; namespace RynthCore.Engine.D3D9; +/// Where the world overlays draw. Session only (/rc worldlayer); Auto at every start. +internal enum WorldLayerMode +{ + /// UI pass when the hook is installed, else the ZENABLE transition. + Auto, + /// Only at AC's UI pass (EndScene fallback otherwise). + UiPass, + /// Only at the first ZENABLE 1->0 transition (the pre-2026-10-04 behaviour). + Transition, + /// Always at EndScene (over AC's UI): for comparison only. + EndScene, +} + internal static class Nav3DRenderInjector { private const uint D3DRS_ZENABLE = 7; @@ -23,7 +50,9 @@ internal static class Nav3DRenderInjector private static DrawIndexedPrimitiveD? _originalDIP; private static DrawIndexedPrimitiveD? _hookDelegate; + private static IntPtr _dipTarget; private static bool _hookInstalled; + private static bool _dipEnabled; private static bool _inRender; // Per-frame transition detection @@ -31,8 +60,24 @@ internal static class Nav3DRenderInjector private static bool _markersRenderedThisFrame; private static bool _seen3D; + // Frames whose overlays drew at each place (diagnostics; AC's render thread). + private static long _atUiPass, _atTransition, _atEndScene; + + /// Session override, set by /rc worldlayer (any thread; read on AC's render thread). + public static volatile WorldLayerMode Mode = WorldLayerMode.Auto; + + /// The world overlays already drew this frame (any path). public static bool RenderedThisFrame => _markersRenderedThisFrame; + /// True while the overlays themselves are drawing (the draw hooks ignore those draws). + internal static bool InOverlayRender => _inRender; + + private static bool UseUiPass => + Mode == WorldLayerMode.UiPass || (Mode == WorldLayerMode.Auto && AcUiPassHook.IsInstalled); + + private static bool UseTransition => + Mode == WorldLayerMode.Transition || (Mode == WorldLayerMode.Auto && !AcUiPassHook.IsInstalled); + public static void ResetFrame() { _markersRenderedThisFrame = false; @@ -55,6 +100,8 @@ internal static class Nav3DRenderInjector MinHook.HookCreate(addr, hookPtr)); Thread.MemoryBarrier(); MinHook.Enable(addr); + _dipTarget = addr; + _dipEnabled = true; _hookInstalled = true; RynthLog.D3D9("Nav3DRenderInjector: DrawIndexedPrimitive hook installed."); @@ -65,6 +112,97 @@ internal static class Nav3DRenderInjector } } + /// + /// Frame boundary (end of EndScene, AC's render thread): the DIP hook runs only + /// when the transition path needs it. With the UI-pass hook live it is switched + /// off, so AC's draws pay nothing. + /// + public static void SyncHookState() + { + // Teardown: AcUiPassHook.Uninstall flips Auto to "transition"; don't re-patch then. + if (!_hookInstalled || EngineLifecycle.IsShuttingDown) return; + bool want = UseTransition; + if (want == _dipEnabled) return; + int status = want ? MinHook.MH_EnableHook(_dipTarget) : MinHook.MH_DisableHook(_dipTarget); + if (status == MinHook.MH_OK || status == MinHook.MH_ERROR_ENABLED || status == MinHook.MH_ERROR_DISABLED) + { + _dipEnabled = want; + RynthLog.D3D9($"Nav3DRenderInjector: DrawIndexedPrimitive hook {(want ? "enabled" : "disabled")} " + + $"(world overlays: {DescribePath()})."); + } + else if (want) + { + RynthLog.D3D9($"Nav3DRenderInjector: re-enabling the DrawIndexedPrimitive hook failed ({MinHook.StatusString(status)})."); + } + else + { + // Couldn't switch it off: harmless, the detour returns early when not needed. + _dipEnabled = true; + } + } + + /// AcUiPassHook: AC's RenderUI::RenderObjects is about to draw AC's 2D UI. + public static void OnAcUiPass() + { + if (!UseUiPass) return; + IntPtr dev = ImGuiBackend.EngineFrameController.CachedDevice; + if (dev == IntPtr.Zero) return; + if (PresentWorldOverlays(dev, sceneViewport: true)) + _atUiPass++; + } + + /// + /// EngineFrameController, EndScene, before the ImGui panels: draws the overlays + /// when no earlier path did this frame, then closes the frame for them (the ImGui + /// panels' own draws can't trigger the transition path afterwards). + /// + public static void PresentAtEndScene(IntPtr dev) + { + if (_markersRenderedThisFrame || dev == IntPtr.Zero) return; + _markersRenderedThisFrame = true; + _inRender = true; + try { ImGuiBackend.DX9Backend.RenderNav3D(dev); } + catch { } + try { ImGuiBackend.UnderUiLayer.PresentFallback(dev); } + catch { } + _inRender = false; + _atEndScene++; + } + + /// Draws the Nav3D markers, then the world overlays, once per frame. False: not drawn here. + private static bool PresentWorldOverlays(IntPtr dev, bool sceneViewport) + { + if (_markersRenderedThisFrame) return false; + // Decal clients: VVS/Decal/UB draw 3D into their own render targets too; only AC's + // back buffer gets the markers and nameplates (measured 2026-09-30: without this they + // showed up inside a Virindi window). Checked once per frame, only with Decal. + if (DecalD3D9.Enabled && !ImGuiBackend.DX9Backend.IsRenderingToBackBuffer(dev)) return false; + + _markersRenderedThisFrame = true; + _inRender = true; + try + { + // At the UI pass AC has set a full-screen viewport; the markers project + // with the 3D view's (captured at the last EndScene). + ImGuiBackend.DX9Backend.RenderNav3D(dev, sceneViewport); + } + catch + { + } + // The world overlays (nameplates, combat text) go here too, over the + // markers and under AC's UI. UnderUiLayer presents a list at most once. + try + { + if (sceneViewport) ImGuiBackend.UnderUiLayer.PresentAtUiPass(dev); + else ImGuiBackend.UnderUiLayer.PresentAtTransition(dev); + } + catch + { + } + _inRender = false; + return true; + } + private static int Detour(IntPtr dev, uint primitiveType, int baseVertexIndex, uint minVertexIndex, uint numVertices, uint startIndex, uint primCount) @@ -73,37 +211,20 @@ internal static class Nav3DRenderInjector return _originalDIP!(dev, primitiveType, baseVertexIndex, minVertexIndex, numVertices, startIndex, primCount); + if (!UseTransition) + return _originalDIP!(dev, primitiveType, baseVertexIndex, + minVertexIndex, numVertices, startIndex, primCount); + ImGuiBackend.DX9Backend.DeviceGetRenderState(dev, D3DRS_ZENABLE, out uint zEnable); if (zEnable != 0) _seen3D = true; // Detect 3D→UI transition: ZENABLE goes from 1→0 after 3D draws - // Decal clients: VVS/Decal/UB draw 3D into their own render targets too; only AC's - // back buffer gets the markers and nameplates (measured 2026-09-30: without this they - // showed up inside a Virindi window). Evaluated only at a transition, and only with Decal. - if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0 && - (!DecalD3D9.Enabled || ImGuiBackend.DX9Backend.IsRenderingToBackBuffer(dev))) + if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0) { - _markersRenderedThisFrame = true; - _inRender = true; - try - { - ImGuiBackend.DX9Backend.RenderNav3D(dev); - } - catch - { - } - // The world overlays (nameplates, combat text) go here too, over the - // markers and under AC's UI. Its own frame flag: drawn at most once. - try - { - ImGuiBackend.UnderUiLayer.PresentAtTransition(dev); - } - catch - { - } - _inRender = false; + if (PresentWorldOverlays(dev, sceneViewport: false)) + _atTransition++; } _lastZEnable = zEnable; @@ -111,4 +232,19 @@ internal static class Nav3DRenderInjector return _originalDIP!(dev, primitiveType, baseVertexIndex, minVertexIndex, numVertices, startIndex, primCount); } + + /// The path the overlays use now, for status lines. + public static string DescribePath() => Mode switch + { + WorldLayerMode.UiPass => AcUiPassHook.IsInstalled ? "AC UI pass (forced)" : "AC UI pass (forced, hook missing: EndScene)", + WorldLayerMode.Transition => _hookInstalled ? "ZENABLE 1->0 transition (forced)" : "ZENABLE transition (forced, DIP hook missing: EndScene)", + WorldLayerMode.EndScene => "EndScene (forced, over AC's UI)", + _ => AcUiPassHook.IsInstalled ? "AC UI pass (auto)" : "ZENABLE 1->0 transition (auto: UI-pass hook not installed)", + }; + + /// One line for /rc worldlayer status and /rc imgui diag. + public static string Describe() => + $"world overlays: {DescribePath()}; frames drawn at UI pass {_atUiPass}, at transition {_atTransition}, " + + $"at EndScene {_atEndScene}; DIP hook {(_hookInstalled ? (_dipEnabled ? "on" : "off") : "not installed")}; " + + $"UI-pass hook: {AcUiPassHook.Status}, {AcUiPassHook.Calls} calls"; } diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index da752f6..dbb8416 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -133,6 +133,9 @@ internal static class EngineLifecycle // plugin-mutating UI command while the plugins are shutting down. Step("UiDataHub.Disarm", () => UI.Data.UiDataHub.Disarm()); + // AC's UI-pass hook draws the world overlays mid-frame from the same render-side + // state EndSceneHook.Uninstall tears down: stop it first (its 80 ms drain covers both). + Step("AcUiPassHook.Uninstall", () => AcUiPassHook.Uninstall()); Step("EndSceneHook.Uninstall", () => EndSceneHook.Uninstall()); // Give in-flight EndScene calls a chance to drain. AC's render thread diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index f82c7f3..67dc12f 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -658,6 +658,9 @@ public static class EntryPoint Step("vector-update hooks", VectorUpdateServerDispatchHooks.Initialize); Step("update-object-inventory hooks", UpdateObjectInventoryHooks.Initialize); Step("view-object-contents hooks", ViewObjectContentsHooks.Initialize); + // RenderUI::RenderObjects: the world overlays (nameplates, Nav3D markers) draw at + // the start of AC's 2D UI pass, after all 3D incl. foliage (2026-10-04). + Step("UI-pass overlay hook", AcUiPassHook.Initialize); Step("vendor hooks", VendorHooks.Initialize); Step("chat callback hooks", ChatCallbackHooks.Initialize); Step("raw packet hooks", RawPacketHooks.Initialize); diff --git a/src/RynthCore.Engine/Hooking/MinHook.cs b/src/RynthCore.Engine/Hooking/MinHook.cs index cc52e10..bf0f758 100644 --- a/src/RynthCore.Engine/Hooking/MinHook.cs +++ b/src/RynthCore.Engine/Hooking/MinHook.cs @@ -24,6 +24,8 @@ internal static unsafe class MinHook public const int MH_ERROR_NOT_INITIALIZED = 2; public const int MH_ERROR_ALREADY_CREATED = 3; public const int MH_ERROR_NOT_CREATED = 4; + public const int MH_ERROR_ENABLED = 5; + public const int MH_ERROR_DISABLED = 6; // ─── Core API ───────────────────────────────────────────────────── // diff --git a/src/RynthCore.Engine/ImGui/DX9Backend.cs b/src/RynthCore.Engine/ImGui/DX9Backend.cs index 31af988..1fa9201 100644 --- a/src/RynthCore.Engine/ImGui/DX9Backend.cs +++ b/src/RynthCore.Engine/ImGui/DX9Backend.cs @@ -1104,6 +1104,59 @@ internal static unsafe class DX9Backend _navTrigReady = true; } + // AC's 3D view viewport, read at EndScene (AC has put it back by then; the EndScene + // fallback has always drawn the markers with it). AC's render thread only. + private static D3DVIEWPORT9 _sceneViewport; + private static bool _hasSceneViewport; + + /// + /// EndScene, before anything of ours touches the viewport: remembers AC's 3D view + /// viewport for at the UI pass, where AC has + /// set a full-screen one. AC's render thread. + /// + public static void CaptureSceneViewport(IntPtr pDevice) + { + if (!_coreInitialized || _getViewport == null || pDevice == IntPtr.Zero) return; + D3DVIEWPORT9 vp; + if (_getViewport(pDevice, &vp) >= 0 && vp.Width > 0 && vp.Height > 0) + { + _sceneViewport = vp; + _hasSceneViewport = true; + } + } + + /// + /// ; with (AC's UI + /// pass) the markers draw in AC's 3D view viewport (from the last EndScene) when the + /// current one differs, and the current one is put back afterwards. + /// + public static void RenderNav3D(IntPtr pDevice, bool sceneViewport) + { + if (!sceneViewport || !_hasSceneViewport || !_coreInitialized || pDevice == IntPtr.Zero || + _getViewport == null || _setViewport == null) + { + RenderNav3D(pDevice); + return; + } + D3DVIEWPORT9 current; + if (_getViewport(pDevice, ¤t) < 0) + { + RenderNav3D(pDevice); + return; + } + D3DVIEWPORT9 scene = _sceneViewport; + bool same = current.X == scene.X && current.Y == scene.Y && current.Width == scene.Width && + current.Height == scene.Height && current.MinZ == scene.MinZ && current.MaxZ == scene.MaxZ; + if (same) + { + RenderNav3D(pDevice); + return; + } + _setViewport(pDevice, &scene); + try { RenderNav3D(pDevice); } + finally { _setViewport(pDevice, ¤t); } + } + public static void RenderNav3D(IntPtr pDevice) { // Nav3D only needs the cached function pointers + nav trig + GameMatrixCapture; diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 435c4ea..30ef6a1 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -247,10 +247,16 @@ internal static class EngineFrameController // accumulates, RenderedThisFrame stays false on every frame, and the // end-of-frame fallback below paints markers OVER the UI. This call was // dropped in the v0.19 Nav3D double-buffer refactor — restored here. + // Since 2026-10-04 this is the second choice: with AcUiPassHook live the + // overlays draw at AC's UI pass and SyncHookState (end of frame) switches + // this hook off; it comes back for /rc worldlayer transition or without it. D3D9.Nav3DRenderInjector.Install(pDevice); // Capture the game's View/Projection matrices before ImGui touches them GameMatrixCapture.CaptureFrame(pDevice); + // ...and AC's 3D view viewport: at AC's UI pass (AcUiPassHook) the viewport is + // full-screen, and the Nav3D markers draw in this one there. + DX9Backend.CaptureSceneViewport(pDevice); // Refresh the player-skill snapshot on AC's main thread (this // EndScene runs on it). The plugin tick is pumped off-thread and @@ -310,24 +316,13 @@ internal static class EngineFrameController try { Compatibility.AcMainThreadQueue.Drain(); } catch (Exception ex) { RynthLog.Plugin($"AcMainThreadQueue.Drain threw {ex.GetType().Name}: {ex.Message}"); } - // Nav3DRenderInjector fires mid-frame at the 3D→UI ZENABLE - // transition — that's the only pipeline position where markers - // can render BEHIND AC's UI (the UI pass draws after ZENABLE - // turns off, and the end-of-frame fallback is past it entirely). - // - // The injector accumulates state per-frame via DrawIndexedPrimitive - // callbacks during AC's draws (which fire before this EndScene), - // so by the time we check RenderedThisFrame here, its decision - // for the current frame is final. ResetFrame at the END of - // OnEndScene primes it for the next frame's accumulation. - // - // Historically the engine forced the end-of-frame fallback ONLY - // because the injector's hit-rate varied across motion, producing - // flicker when some frames painted at the 3D→UI boundary and - // others at end-of-frame. We accept that risk here: the user - // wants markers behind the UI, and a frame the injector misses - // simply doesn't render markers (less jarring than a Z-order flip). - bool nav3DAlreadyRendered = D3D9.Nav3DRenderInjector.RenderedThisFrame; + // The world overlays (Nav3D markers, nameplates, combat text) normally drew + // mid-frame, before this EndScene: at the start of AC's 2D UI pass + // (AcUiPassHook), or without that hook at the 3D->UI ZENABLE transition + // (Nav3DRenderInjector's DIP hook). A frame where neither fired (portal space, + // a loading screen, no AC UI) draws them at EndScene instead - see + // Nav3DRenderInjector.PresentAtEndScene below. ResetFrame at the END of + // OnEndScene primes the next frame. // Publish the live device pointer for the off-render-thread plugin // pump (see PumpPluginFrame). The D3D9 device is a stable COM @@ -365,17 +360,12 @@ internal static class EngineFrameController uiTicks = Stopwatch.GetTimestamp() - t0; } - // Fallback render — only fires when the injector missed this - // frame's 3D→UI transition. _coreInitialized is enough — this - // does not touch font / vertex buffer state. - if (!nav3DAlreadyRendered) - DX9Backend.RenderNav3D(pDevice); - - // The world overlays built last frame (nameplates, combat text) normally - // drew at this frame's 3D->UI transition, under AC's UI. If that wasn't - // seen, they draw here - still under the ImGui panels. No-op when they - // already drew (UnderUiLayer presents a list once). - UnderUiLayer.PresentFallback(pDevice); + // Fallback: the Nav3D markers and the world overlays built last frame + // (nameplates, combat text), when neither the UI pass nor the transition + // drew them this frame - still under the ImGui panels. No-op when they + // already drew (one per-frame flag for every path; UnderUiLayer presents + // a list once). _coreInitialized is enough for the markers. + D3D9.Nav3DRenderInjector.PresentAtEndScene(pDevice); if (imguiEnabled) { @@ -400,6 +390,10 @@ internal static class EngineFrameController // never fires again — every subsequent frame falls back to the // end-of-frame draw (which paints over the UI). D3D9.Nav3DRenderInjector.ResetFrame(); + // The DIP hook only runs while the transition path is in use (no UI-pass + // hook, or /rc worldlayer transition); switched here, between frames. + try { D3D9.Nav3DRenderInjector.SyncHookState(); } + catch (Exception ex) { RynthLog.D3D9($"Nav3DRenderInjector.SyncHookState threw {ex.GetType().Name}: {ex.Message}"); } // What this frame built for the world overlays is presented next frame. UnderUiLayer.EndFrame(); } @@ -518,6 +512,7 @@ internal static class EngineFrameController $"inWorld={PanelsLive} content={HasImGuiContentNoRestore()} idle={_imguiIdle} framesBuilt={_framesBuilt} uiScale={_uiScale:0.##} avaloniaScale={UI.AvaloniaOverlay.InputScale:0.##} display={_lastDisplaySize.X:0}x{_lastDisplaySize.Y:0}", DX9Backend.DescribeLastFrame(), UnderUiLayer.Describe(), + D3D9.Nav3DRenderInjector.Describe(), $"capture: {Win32Backend.DescribeCapture()}", }; lines.AddRange(ImGuiPopOuts.Describe()); @@ -569,6 +564,7 @@ internal static class EngineFrameController _imguiIdle = true; Win32Backend.DiscardQueuedInput(); Win32Backend.ClearCaptureFlags(); + ImGuiTextFocus.ClearMain(); return false; } @@ -624,6 +620,7 @@ internal static class EngineFrameController ImGuiNET.ImGui.NewFrame(); frameStarted = true; + ImGuiTextFocus.BeginFrame(); if (_dropImGuiTextFocus) { // An Avalonia TextBox took the keyboard: end ImGui's text edit. @@ -661,7 +658,17 @@ internal static class EngineFrameController // rule; io.WantTextInput is true only while a text field is edited. // MonsterHud.WantsMouse: the cursor is on a clickable nameplate (or a // press that began on one is held), so that click is the plate's. - Win32Backend.UpdateCaptureFlags(io.WantCaptureMouse || Hud.MonsterHud.WantsMouse, io.WantTextInput); + // Keyboard: io.WantTextInput lags the box by a frame (ImGui publishes it from + // the previous frame's widgets), so a box that went active this frame counts + // too (ImGuiTextFocus): the keys typed right after the click stay out of AC. + ImGuiTextFocus.EndMainFrame(io.WantTextInput); + bool typing = io.WantTextInput || ImGuiTextFocus.MainBoxActive; + Win32Backend.UpdateCaptureFlags(io.WantCaptureMouse || Hud.MonsterHud.WantsMouse, typing); + // The UI is released (Insert): no text box keeps the keyboard. Keys are not + // gated by the toggle any more (Win32Backend.UpdateCaptureFlags), so the edit + // ends instead and the next keys go to the game. + if (typing && !Win32Backend.UiCaptureEnabled) + _dropImGuiTextFocus = true; ArbitrateTextFocus(io.WantTextInput); return true; } @@ -678,6 +685,7 @@ internal static class EngineFrameController } Win32Backend.ClearCaptureFlags(); + ImGuiTextFocus.ClearMain(); RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui error: {ex.GetType().Name}: {ex.Message}"); return false; } diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index e3d2959..f153763 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -912,8 +912,12 @@ internal static class ImGuiPanelHost } } + /// The panel whose face is drawing right now (names a text box's owner in the input log). AC thread. + internal static string? DrawingTitle { get; private set; } + private static void DrawBody(Entry entry) { + DrawingTitle = entry.Title; try { entry.Instance!.Draw(); @@ -925,6 +929,10 @@ internal static class ImGuiPanelHost if (entry.Failures >= MaxFailures) entry.Error = $"{entry.Title} stopped drawing after repeated errors: {ex.Message}"; } + finally + { + DrawingTitle = null; + } } private static float HeaderButtonsWidth(Entry entry, float s, bool popped) diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs index cc8f110..feceed4 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -114,6 +114,15 @@ internal static unsafe class ImGuiPopOuts public static bool IsPopped(string title) => Pops.ContainsKey(title); + /// + /// A pop-out's text box holds the keyboard: the game WndProc routes keys to it + /// (RouteInput) and lets none of them reach AC. AC thread. + /// + public static bool HasTextFocus => _keyboard is { WantTextInput: true }; + + /// The pop-out typing into a text box, or null (for the input log). AC thread. + public static string? TextFocusTitle => _keyboard is { WantTextInput: true } k ? k.Title : null; + /// The screen position of the game window's client origin (to place a pop-out where the docked panel was). public static Vector2 ClientOriginOnScreen() { @@ -204,6 +213,7 @@ internal static unsafe class ImGuiPopOuts if (!Pops.Remove(title, out PopOut? pop)) return; Order.Remove(pop); if (_keyboard == pop) _keyboard = null; + ImGuiTextFocus.ForgetPopOut(title); try { pop.Window?.Dispose(); } catch (Exception ex) { RynthLog.UI($"ImGuiPopOuts: {title} window dispose threw {ex.Message}"); } pop.Window = null; pop.Surface.Dispose(); @@ -462,6 +472,7 @@ internal static unsafe class ImGuiPopOuts io.AddKeyEvent(ImGuiKey.ModAlt, (GetKeyState(VK_MENU) & 0x8000) != 0); _current = pop; + ImGuiTextFocus.BeginFrame(); ImGuiNET.ImGui.NewFrame(); started = true; if (pop.DropTextFocus) @@ -520,7 +531,10 @@ internal static unsafe class ImGuiPopOuts pop.PushTicks += Stopwatch.GetTimestamp() - built; } - pop.WantTextInput = io.WantTextInput; + // io.WantTextInput lags a frame behind the box (ImGui publishes it from the + // previous frame's widgets); a box that went active this frame counts too, so + // the keys typed right after the click already come here, not to AC. + pop.WantTextInput = ImGuiTextFocus.EndPopOutFrame(pop.Title, io.WantTextInput); pop.IdleInterval = Stopwatch.Frequency / ImGuiPanelHost.PopOutIdleHz(pop.Title); if (pop.WantTextInput) _keyboard = pop; else if (_keyboard == pop) _keyboard = null; diff --git a/src/RynthCore.Engine/ImGui/ImGuiTextFocus.cs b/src/RynthCore.Engine/ImGui/ImGuiTextFocus.cs new file mode 100644 index 0000000..dc800a9 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/ImGuiTextFocus.cs @@ -0,0 +1,81 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/ImGuiTextFocus.cs +// Which RynthCore ImGui text box holds the keyboard, per ImGui context (the +// main frame and each pop-out), seen from the box itself: FaceKit.TextBox and +// the script-window replay call NoteActive while their InputText is the +// active item. That is the same frame the click lands, one frame ahead of +// io.WantTextInput (which ImGui publishes from the previous frame's widgets). +// +// Used two ways by Win32Backend's WndProc: +// * keyboard capture: a box active in the last frame keeps keys from AC +// even before io.WantTextInput catches up (the click-then-type frame); +// * the leak diagnostic: a key-down or char that is about to reach AC while +// a box was active logs one "[Input] key reached AC ..." line per burst. +// +// Threads: AC's main thread only (ImGui frames and the game WndProc both run +// there). No locks. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class ImGuiTextFocus +{ + private static string? _frameOwner; // the frame being built + private static string? _mainOwner; // the last main frame's + private static readonly Dictionary PopOwners = new(StringComparer.OrdinalIgnoreCase); + + /// A text box is the active item in the frame being built. AC thread, in the draw. + public static void NoteActive(string id) + { + if (_frameOwner != null) return; + string? panel = ImGuiPanelHost.DrawingTitle; + _frameOwner = string.IsNullOrEmpty(panel) ? id : panel + " " + id; + if (ImGuiPopOuts.InPopOutFrame) _frameOwner += " (popped out)"; + } + + /// A frame (main or pop-out) is about to be built. + public static void BeginFrame() => _frameOwner = null; + + /// The main frame was built. is its io.WantTextInput. + public static void EndMainFrame(bool wantTextInput) + { + _mainOwner = _frameOwner ?? (wantTextInput ? "a text field in the client" : null); + _frameOwner = null; + } + + /// No main frame this tick (nothing ImGui open, or the frame failed): no box. + public static void ClearMain() + { + _mainOwner = null; + _frameOwner = null; + } + + /// A box was active in the last main frame (FaceKit / script windows only). + public static bool MainBoxActive => _mainOwner != null; + + /// A pop-out's frame was built. Returns true when one of its boxes was active. + public static bool EndPopOutFrame(string title, bool wantTextInput) + { + string? owner = _frameOwner ?? (wantTextInput ? title + " (popped out)" : null); + _frameOwner = null; + if (owner != null) PopOwners[title] = owner; + else PopOwners.Remove(title); + return owner != null; + } + + public static void ForgetPopOut(string title) => PopOwners.Remove(title); + + /// The box holding the keyboard (main frame first), or null. + public static string? ActiveOwner + { + get + { + if (_mainOwner != null) return _mainOwner; + foreach (string owner in PopOwners.Values) return owner; + return null; + } + } +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs index 7c50612..5a077ee 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs @@ -220,7 +220,7 @@ internal static class MonsterHud /// plate, or a press that began on one is still held. Read after the frame is /// built, on AC's render thread. /// - public static bool WantsMouse => _wantsMouse; + public static bool WantsMouse => _wantsMouse || PlayerPlate.WantsMouse; /// Plates being tracked (diagnostics). public static int PlateCount => Plates.Count; @@ -237,6 +237,7 @@ internal static class MonsterHud { // Draw recomputes it; a frame that doesn't draw the plates never wants the mouse. _wantsMouse = false; + PlayerPlate.ClearMouse(); try { if (!MonsterHudSettings.Loaded) @@ -716,13 +717,15 @@ internal static class MonsterHud /// AC's render thread, inside the ImGui frame (between NewFrame and Render). public static void Draw(float uiScale) { - if (!_hasContent) { ResetClick(); return; } + if (!_hasContent) { ResetClick(); PlayerPlate.DropDrag(); return; } try { - if (!TryBeginFrame(uiScale, out Frame f)) { ResetClick(); return; } + if (!TryBeginFrame(uiScale, out Frame f)) { ResetClick(); PlayerPlate.DropDrag(); return; } DrawPlates(ref f, MonsterHudSettings.Enabled); PlayerPlate.Draw(ref f); CombatText.Draw(ref f); + // The player plate fixed on screen: ImGui's background list (the normal UI pass), not the layer above. + PlayerPlate.DrawScreen(ref f); } catch (Exception ex) { diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs index a0cb9ae..0777b5e 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs @@ -66,6 +66,17 @@ internal static class MonsterHudSettings public static bool SelfNumbers = false; // "cur/max" beside each bar public static bool SelfName = false; public static bool SelfHideFirstPerson = true; + /// + /// Fixed on screen (default since 2026-10-05: a plate tied to the head jitters while you move) or + /// following the character (SelfPosition, SelfHideFirstPerson). Fixed draws with the normal UI. + /// + public static SelfPlacement SelfPlacement = SelfPlacement.Fixed; + /// Fixed mode: the plate can't be dragged (and never takes a click). Unlock to move it. + public static bool SelfLocked = true; + /// Fixed mode: where the bars' centre sits, as a fraction of the screen (kept on screen when drawn). + public static float SelfFixedX = DefaultSelfFixedX, SelfFixedY = DefaultSelfFixedY; + /// Just under a third-person character, clear of the chat in the bottom-left corner. + public const float DefaultSelfFixedX = 0.5f, DefaultSelfFixedY = 0.68f; // Combat text (CombatText): floating numbers and the kill burst. public static bool Numbers = true; @@ -166,6 +177,10 @@ internal static class MonsterHudSettings case "selfNumbers": SelfNumbers = val == "1"; break; case "selfName": SelfName = val == "1"; break; case "selfHideFirstPerson": SelfHideFirstPerson = val == "1"; break; + case "selfPlacement": SelfPlacement = val.Equals("follow", StringComparison.OrdinalIgnoreCase) ? SelfPlacement.Follow : SelfPlacement.Fixed; break; + case "selfLocked": SelfLocked = val == "1"; break; + case "selfFixedX": if (TryF(val, out float fx)) SelfFixedX = Math.Clamp(fx, 0f, 1f); break; + case "selfFixedY": if (TryF(val, out float fy)) SelfFixedY = Math.Clamp(fy, 0f, 1f); break; case "numbers": Numbers = val == "1"; break; case "numDealt": NumDealt = val == "1"; break; case "numTaken": NumTaken = val == "1"; break; @@ -230,6 +245,10 @@ internal static class MonsterHudSettings sw.WriteLine($"selfNumbers={B(SelfNumbers)}"); sw.WriteLine($"selfName={B(SelfName)}"); sw.WriteLine($"selfHideFirstPerson={B(SelfHideFirstPerson)}"); + sw.WriteLine($"selfPlacement={(SelfPlacement == SelfPlacement.Follow ? "follow" : "fixed")}"); + sw.WriteLine($"selfLocked={B(SelfLocked)}"); + sw.WriteLine(FormattableString.Invariant($"selfFixedX={SelfFixedX:0.####}")); + sw.WriteLine(FormattableString.Invariant($"selfFixedY={SelfFixedY:0.####}")); sw.WriteLine($"numbers={B(Numbers)}"); sw.WriteLine($"numDealt={B(NumDealt)}"); sw.WriteLine($"numTaken={B(NumTaken)}"); @@ -262,6 +281,7 @@ internal static class MonsterHudSettings ShowDebuffs = true; ShowOthersDebuff = true; NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false; SelfPlate = true; SelfNumbers = false; SelfName = false; SelfHideFirstPerson = true; + SelfPlacement = SelfPlacement.Fixed; SelfLocked = true; SelfFixedX = DefaultSelfFixedX; SelfFixedY = DefaultSelfFixedY; Numbers = true; NumDealt = true; NumTaken = true; NumHeals = true; NumKills = true; NumSize = 1.0f; NumTime = 1.0f; NumRestores = true; KeepOnScreen = true; GainSize = 1.0f; GainTime = 1.0f; SelfPosition = SelfPlatePosition.Above; @@ -269,6 +289,14 @@ internal static class MonsterHudSettings Save(); } + /// The fixed plate back to its default spot (and saved). Render / chat thread. + public static void ResetSelfPosition() + { + SelfFixedX = DefaultSelfFixedX; + SelfFixedY = DefaultSelfFixedY; + Save(); + } + /// Every master switch at once ("/rv plates all on|off"). public static void SetAll(bool on) { @@ -283,7 +311,8 @@ internal static class MonsterHudSettings $"names {OnOff(ShowNames)}, hp {OnOff(ShowHpNumbers)}, level {OnOff(ShowLevel)}, weak {OnOff(ShowWeakness)}, " + $"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " + $"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)}; " + - $"self {OnOff(SelfPlate)} (numbers {OnOff(SelfNumbers)}, name {OnOff(SelfName)}, hide in first person {OnOff(SelfHideFirstPerson)}); " + + $"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " + + $"numbers {OnOff(SelfNumbers)}, name {OnOff(SelfName)}, hide in first person {OnOff(SelfHideFirstPerson)}); " + $"combat text {OnOff(Numbers)} (dealt {OnOff(NumDealt)}, taken {OnOff(NumTaken)}, heals {OnOff(NumHeals)}, kills {OnOff(NumKills)}); " + $"gains {OnOff(Gains)} (xp {OnOff(GainXp)}, lum {OnOff(GainLum)}, radiance {OnOff(GainRadiance)})."); @@ -292,3 +321,6 @@ internal static class MonsterHudSettings /// Player plate placement: over the head, under the feet, or beside the character. internal enum SelfPlatePosition { Above, Below, Left, Right } + +/// Player plate: fixed at a saved screen spot (draggable when unlocked), or following the character. +internal enum SelfPlacement { Fixed, Follow } diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs index bda925e..01e3023 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs @@ -91,15 +91,56 @@ internal static class MonsterHudSettingsUi Section("Your plate", w); changed |= Toggle("Show your plate", ref MonsterHudSettings.SelfPlate, - "Health, stamina and mana bars over your own head. Chat: /rv plates self."); + "Your own health, stamina and mana bars: fixed on screen, or following your character. Chat: /rv plates self."); changed |= Toggle("Numbers on your bars", ref MonsterHudSettings.SelfNumbers, "\"cur / max\" inside each bar (taller bars).", sub: true); changed |= Toggle("Your name", ref MonsterHudSettings.SelfName, null, sub: true); - changed |= Toggle("Hide in first person", ref MonsterHudSettings.SelfHideFirstPerson, - "When the camera is at your head the plate would sit mid-screen; hide it then.", sub: true); - changed |= SelfPositionPick("Over your head", SelfPlatePosition.Above); - changed |= SelfPositionPick("Under your feet", SelfPlatePosition.Below); - changed |= SelfPositionPick("Beside you, left", SelfPlatePosition.Left); - changed |= SelfPositionPick("Beside you, right", SelfPlatePosition.Right); + + bool fixedOn = MonsterHudSettings.SelfPlacement == SelfPlacement.Fixed; + if (Toggle("Fixed on screen", ref fixedOn, + "The bars stay where you put them on the screen, so they don't move with your character. " + + "Unlock to drag them. Chat: /rv plates self fixed.", radio: true, sub: true)) + { + MonsterHudSettings.SelfPlacement = SelfPlacement.Fixed; + changed = true; + } + if (fixedOn) + { + bool unlocked = !MonsterHudSettings.SelfLocked; + bool locked = MonsterHudSettings.SelfLocked; + if (Toggle("Lock position", ref locked, + "Locked, the plate can't be grabbed or clicked, so play never moves it. " + + "Untick it, then drag the plate (it shows a frame) and tick it again. Chat: /rv plates self lock on|off.", indent: 32)) + { + MonsterHudSettings.SelfLocked = locked; + changed = true; + } + if (unlocked) + Note("Unlocked: drag your plate anywhere on the screen, then lock it again.", w, indent: 32); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.SetCursorScreenPos(ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(32, 0)); + if (SmallButton("Reset position")) + MonsterHudSettings.ResetSelfPosition(); // saves + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Back to the default spot, just under your character. Chat: /rv plates self reset."); + } + + bool follow = MonsterHudSettings.SelfPlacement == SelfPlacement.Follow; + if (Toggle("Follow your character", ref follow, + "The bars ride along with your character in the world (they move as it moves). Chat: /rv plates self follow.", + radio: true, sub: true)) + { + MonsterHudSettings.SelfPlacement = SelfPlacement.Follow; + changed = true; + } + if (follow) + { + changed |= SelfPositionPick("Over your head", SelfPlatePosition.Above); + changed |= SelfPositionPick("Under your feet", SelfPlatePosition.Below); + changed |= SelfPositionPick("Beside you, left", SelfPlatePosition.Left); + changed |= SelfPositionPick("Beside you, right", SelfPlatePosition.Right); + changed |= Toggle("Hide in first person", ref MonsterHudSettings.SelfHideFirstPerson, + "When the camera is at your head the plate would sit mid-screen; hide it then.", indent: 32); + } Section("Look", w); changed |= SliderF("Scale", ref MonsterHudSettings.Scale, MonsterHudSettings.MinScale, MonsterHudSettings.MaxScale, "%.2f", w); @@ -161,17 +202,18 @@ internal static class MonsterHudSettingsUi private static bool SelfPositionPick(string label, SelfPlatePosition pos) { bool on = MonsterHudSettings.SelfPosition == pos; - if (!Toggle(label, ref on, "Where your plate sits. Chat: /rv plates self position above|below|left|right.", radio: true, sub: true)) + if (!Toggle(label, ref on, "Where your plate sits. Chat: /rv plates self position above|below|left|right.", radio: true, indent: 32)) return false; MonsterHudSettings.SelfPosition = pos; return true; } - private static bool Toggle(string label, ref bool value, string? tip, bool radio = false, bool sub = false) + private static bool Toggle(string label, ref bool value, string? tip, bool radio = false, bool sub = false, float indent = 0) { var dl = ImGuiNET.ImGui.GetWindowDrawList(); ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - if (sub) ImGuiNET.ImGui.SetCursorScreenPos(ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(16, 0)); + if (sub && indent <= 0) indent = 16; + if (indent > 0) ImGuiNET.ImGui.SetCursorScreenPos(ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(indent, 0)); Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); float labelW = ImGuiNET.ImGui.CalcTextSize(label).X; ImGuiNET.ImGui.PushID(label); @@ -238,9 +280,14 @@ internal static class MonsterHudSettingsUi ImGuiNET.ImGui.PopFont(); } - private static void Note(string text, float w) + private static void Note(string text, float w, float indent = 0) { ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + if (indent > 0) + { + ImGuiNET.ImGui.SetCursorPosX(ImGuiNET.ImGui.GetCursorPosX() + indent); + w -= indent; + } ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); ImGuiNET.ImGui.TextUnformatted(text); ImGuiNET.ImGui.PopTextWrapPos(); diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs index 8455a63..c1779e5 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs @@ -7,12 +7,27 @@ // // Data: PlayerVitalsHooks.TryGetSnapshot, the buffed values AC's own vital // bars show, kept on AC's main thread (a lock and a struct copy per frame). -// Position: the player's live pose, projected like the monster plates -// (MonsterHud.Project handles the landblock frame). // -// First person: when the camera is inside or right at the head, the plate -// would sit in the middle of the screen, so it hides (setting; on by -// default). The head point is still published for the gain text. +// Two placements (MonsterHudSettings.SelfPlacement): +// Fixed on screen (default since 2026-10-05: tied to the head the plate +// jittered while the character moved). The bars sit at a saved screen +// spot (fractions of the screen, so a resize keeps it in place, then +// clamped inside the screen). Drawn by DrawScreen into ImGui's +// background list, i.e. with the normal UI (over AC's windows, under +// every ImGui panel), not through the under-UI 3D layer: a screen HUD +// element doesn't belong to the world. "Lock position" (on by default) +// makes it untouchable; unlocked, a frame shows and a left-drag anywhere +// on the plate moves it (WantsMouse keeps that press from AC), saved on +// release. Reset puts it back at the default spot. +// Follow character: the player's live pose, projected like the monster +// plates (MonsterHud.Project handles the landblock frame), above the +// head, under the feet or beside the character; drawn by Draw into the +// monster plates' list (UnderUiLayer). +// +// First person (follow mode): when the camera is inside or right at the +// head, the plate would sit in the middle of the screen, so it hides +// (setting; on by default). The head point is published either way, for the +// gain text. // // Render thread only. Engine-owned statics. // ============================================================================ @@ -47,6 +62,16 @@ internal static class PlayerPlate private static BarState _hp, _st, _mn; private static float _alpha; + // Fixed mode: dragging (unlocked only). + private static bool _hover, _dragging, _wantsMouse; + private static Vector2 _grab; // cursor minus the bars' centre when the drag began + + /// + /// Fixed mode, unlocked: the cursor is on the plate (or a drag is held), so the click is the plate's. + /// MonsterHud.WantsMouse includes it. Render thread. + /// + public static bool WantsMouse => _wantsMouse; + /// Where the head is on screen this frame (valid when ). public static Vector2 HeadScreen { get; private set; } public static bool HeadOnScreen { get; private set; } @@ -61,8 +86,18 @@ internal static class PlayerPlate _alpha = 0f; HeadOnScreen = false; FirstPerson = false; + DropDrag(); } + /// No fixed plate this frame: no hover, no drag, no capture. + public static void DropDrag() + { + _hover = _dragging = _wantsMouse = false; + } + + /// Clears last frame's capture before a frame (Update); DrawScreen sets it again. + public static void ClearMouse() => _wantsMouse = false; + public static void Draw(ref MonsterHud.Frame f) { // Head point (AC landblock-local), used by the gain text even when the plate is off. @@ -72,38 +107,14 @@ internal static class PlayerPlate head.X > -40 && head.X < f.Display.X + 40 && head.Y > -40 && head.Y < f.Display.Y + 40; HeadScreen = head; PlateTop = head.Y; + // Fixed on screen: DrawScreen paints it with the normal UI (gain text stays over the head). + if (MonsterHudSettings.SelfPlacement == SelfPlacement.Fixed) return; bool show = MonsterHudSettings.SelfPlate && HeadOnScreen && !(FirstPerson && MonsterHudSettings.SelfHideFirstPerson) && PlayerVitalsHooks.TryGetSnapshot(out _); - float kAlpha = 1f - MathF.Exp(-f.Dt * 12f); - _alpha += ((show ? MonsterHudSettings.Opacity : 0f) - _alpha) * kAlpha; - if (!show) { if (_alpha < 0.02f) _alpha = 0f; return; } - if (_alpha < 0.01f) return; - - PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot v); - float kBar = 1f - MathF.Exp(-f.Dt * 14f); - Step(ref _hp, v.Health, v.MaxHealth, f.Now, kBar, f.Dt); - Step(ref _st, v.Stamina, v.MaxStamina, f.Now, kBar, f.Dt); - Step(ref _mn, v.Mana, v.MaxMana, f.Now, kBar, f.Dt); - - float a = Math.Clamp(_alpha, 0f, 1f); - float k = MonsterHudSettings.Scale * f.UiScale; - bool numbers = MonsterHudSettings.SelfNumbers; - // With numbers on, the bars grow to fit bold, outlined text that reads over any fill. - float barW = MathF.Round((numbers ? 124f : 96f) * k); - float barH = MathF.Round((numbers ? 15f : 5f) * k); - float gap = MathF.Max(2f, MathF.Round(2f * k)); - float round = MathF.Max(1f, 1.5f * k); - // Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up). - float smallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale); - ImFontPtr small = ImGuiFonts.Sharp(smallSize, bold: true); - - ImDrawListPtr dl = f.Dl; - float blockH = 3 * barH + 2 * gap; - float nameH = 0f; - float nameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale); - ImFontPtr nameFont = ImGuiFonts.Sharp(nameSize, bold: true); - if (MonsterHudSettings.SelfName) nameH = nameSize + 3f * k; + if (!Advance(ref f, show)) return; + Layout l = Measure(f.UiScale); + float k = l.K, barW = l.BarW, blockH = l.BlockH, nameH = l.NameH; // Where the block goes: above the head (default), under the feet, or beside the character. float left, y; @@ -141,29 +152,169 @@ internal static class PlayerPlate left = Math.Clamp(left, 4f, MathF.Max(4f, f.Display.X - barW - 4f)); y = Math.Clamp(y, 4f + nameH, MathF.Max(4f + nameH, f.Display.Y - blockH - 4f)); } + float top = Paint(f.Dl, ref l, MathF.Round(left), MathF.Round(y)); + // Gain text floats above the plate when it's over the head, else above the head itself. + PlateTop = where == SelfPlatePosition.Above ? top : head.Y; + } + + /// + /// Fixed on screen: the plate at its saved spot, into ImGui's background list (the normal UI pass: + /// over AC's windows, under every panel), and the drag while unlocked. After , + /// inside the ImGui frame. Render thread. + /// + public static void DrawScreen(ref MonsterHud.Frame f) + { + if (MonsterHudSettings.SelfPlacement != SelfPlacement.Fixed) { DropDrag(); return; } + bool show = MonsterHudSettings.SelfPlate && PlayerVitalsHooks.TryGetSnapshot(out _); + if (!Advance(ref f, show)) { DropDrag(); return; } + Layout l = Measure(f.UiScale); + + // The bars' centre from the saved fractions, then the block kept inside the screen. + Vector2 display = f.Display; + float cx = MonsterHudSettings.SelfFixedX * display.X, cy = MonsterHudSettings.SelfFixedY * display.Y; + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + bool unlocked = !MonsterHudSettings.SelfLocked; + if (_dragging) + { + if (unlocked && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) + { + cx = io.MousePos.X - _grab.X; + cy = io.MousePos.Y - _grab.Y; + } + else + { + // Let go (or locked mid-drag): keep where it is, saved. + _dragging = false; + MonsterHudSettings.Save(); + } + } + float left = Math.Clamp(cx - l.BarW * 0.5f, 4f, MathF.Max(4f, display.X - l.BarW - 4f)); + float y = Math.Clamp(cy - l.BlockH * 0.5f, 4f + l.NameH, MathF.Max(4f + l.NameH, display.Y - l.BlockH - 4f)); left = MathF.Round(left); y = MathF.Round(y); - PaintOne(dl, ref _hp, left, y, barW, barH, round, a, HealthCol, numbers, small, smallSize); - PaintOne(dl, ref _st, left, y + barH + gap, barW, barH, round, a, StaminaCol, numbers, small, smallSize); - PaintOne(dl, ref _mn, left, y + 2 * (barH + gap), barW, barH, round, a, ManaCol, numbers, small, smallSize); - float top = y - 1f; + if (_dragging && display.X > 1 && display.Y > 1) + { + // The spot as fractions (clamped, so letting go off screen keeps it reachable). + MonsterHudSettings.SelfFixedX = Math.Clamp((left + l.BarW * 0.5f) / display.X, 0f, 1f); + MonsterHudSettings.SelfFixedY = Math.Clamp((y + l.BlockH * 0.5f) / display.Y, 0f, 1f); + } + // The plate's rect (name included), a little padded: the drag surface. + float pad = MathF.Round(4f * l.K); + var r0 = new Vector2(left - pad, y - l.NameH - pad); + var r1 = new Vector2(left + l.BarW + pad, y + l.BlockH + pad); + Drag(unlocked, r0, r1, new Vector2(left + l.BarW * 0.5f, y + l.BlockH * 0.5f)); + + ImDrawListPtr dl = ImGuiNET.ImGui.GetBackgroundDrawList(); + if (unlocked) + { + // Unlocked: a frame says it can be moved (brighter while hovered or dragged). + float a = Math.Clamp(_alpha, 0.35f, 1f); + bool hot = _hover || _dragging; + dl.AddRectFilled(r0, r1, MonsterHud.Mul(hot ? 0x40000000u : 0x28000000u, a), 3f); + dl.AddRect(r0, r1, MonsterHud.Mul(hot ? FrameHot : FrameCol, a), 3f, ImDrawFlags.None, hot ? 1.5f : 1f); + } + Paint(dl, ref l, left, y); + } + + private static readonly uint FrameCol = MonsterHud.C(0xB026D9E6), FrameHot = MonsterHud.C(0xFF26D9E6); + + /// Hover and a left-drag on the unlocked plate (the MonsterHud plate-click pattern). + private static void Drag(bool unlocked, Vector2 r0, Vector2 r1, Vector2 centre) + { + bool prevHover = _hover; + _hover = false; + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + bool usable = unlocked && Win32Backend.IsUiCaptureEnabled() && (!io.WantCaptureMouse || _dragging); + if (usable) + { + Vector2 m = io.MousePos; + _hover = m.X >= r0.X && m.X <= r1.X && m.Y >= r0.Y && m.Y <= r1.Y; + } + if (!_dragging && usable && (_hover || prevHover) && Win32Backend.MouseCaptured && + ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left) && + !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Right) && !ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Middle)) + { + // The press went where last frame's hover put the capture: the drag starts. + _dragging = true; + _grab = io.MousePos - centre; + } + if (_hover || _dragging) + { + ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeAll); + if (_hover && !_dragging) + ImGuiNET.ImGui.SetTooltip(DragTip); + } + _wantsMouse = _hover || _dragging; + } + + private const string DragTip = "Drag to move your plate.\nLock it again in Vision > Nameplates > Your plate (or /rv plates self lock)."; + + /// Fades the plate in / out and steps the bars; false when nothing should be painted. + private static bool Advance(ref MonsterHud.Frame f, bool show) + { + float kAlpha = 1f - MathF.Exp(-f.Dt * 12f); + _alpha += ((show ? MonsterHudSettings.Opacity : 0f) - _alpha) * kAlpha; + if (!show) { if (_alpha < 0.02f) _alpha = 0f; return false; } + if (_alpha < 0.01f) return false; + + PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot v); + float kBar = 1f - MathF.Exp(-f.Dt * 14f); + Step(ref _hp, v.Health, v.MaxHealth, f.Now, kBar, f.Dt); + Step(ref _st, v.Stamina, v.MaxStamina, f.Now, kBar, f.Dt); + Step(ref _mn, v.Mana, v.MaxMana, f.Now, kBar, f.Dt); + return true; + } + + /// The plate's sizes and fonts this frame. + private struct Layout + { + public float K, BarW, BarH, Gap, Round, BlockH, NameH, SmallSize, NameSize; + public bool Numbers; + public ImFontPtr Small, NameFont; + } + + private static Layout Measure(float uiScale) + { + Layout l = default; + float k = l.K = MonsterHudSettings.Scale * uiScale; + bool numbers = l.Numbers = MonsterHudSettings.SelfNumbers; + // With numbers on, the bars grow to fit bold, outlined text that reads over any fill. + l.BarW = MathF.Round((numbers ? 124f : 96f) * k); + l.BarH = MathF.Round((numbers ? 15f : 5f) * k); + l.Gap = MathF.Max(2f, MathF.Round(2f * k)); + l.Round = MathF.Max(1f, 1.5f * k); + // Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up). + l.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale); + l.Small = ImGuiFonts.Sharp(l.SmallSize, bold: true); + l.BlockH = 3 * l.BarH + 2 * l.Gap; + l.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale); + l.NameFont = ImGuiFonts.Sharp(l.NameSize, bold: true); + l.NameH = MonsterHudSettings.SelfName ? l.NameSize + 3f * k : 0f; + return l; + } + + /// Paints the three bars (and the name over them) with their top-left at (left, y); returns the plate's top. + private static float Paint(ImDrawListPtr dl, ref Layout l, float left, float y) + { + float a = Math.Clamp(_alpha, 0f, 1f); + PaintOne(dl, ref _hp, left, y, l.BarW, l.BarH, l.Round, a, HealthCol, l.Numbers, l.Small, l.SmallSize); + PaintOne(dl, ref _st, left, y + l.BarH + l.Gap, l.BarW, l.BarH, l.Round, a, StaminaCol, l.Numbers, l.Small, l.SmallSize); + PaintOne(dl, ref _mn, left, y + 2 * (l.BarH + l.Gap), l.BarW, l.BarH, l.Round, a, ManaCol, l.Numbers, l.Small, l.SmallSize); + float top = y - 1f; if (MonsterHudSettings.SelfName) { string name = PlayerName(); if (name.Length > 0) { - ImFontPtr font = nameFont; - float size = nameSize; - float w = MonsterHud.TextWidth(font, size, name); - var pos = new Vector2(MathF.Round(left + (barW - w) * 0.5f), MathF.Round(y - 3f * k - size)); - MonsterHud.OutlinedText(dl, font, size, pos, a, name); - dl.AddText(font, size, pos, MonsterHud.Mul(NameCol, a), name); + float w = MonsterHud.TextWidth(l.NameFont, l.NameSize, name); + var pos = new Vector2(MathF.Round(left + (l.BarW - w) * 0.5f), MathF.Round(y - 3f * l.K - l.NameSize)); + MonsterHud.OutlinedText(dl, l.NameFont, l.NameSize, pos, a, name); + dl.AddText(l.NameFont, l.NameSize, pos, MonsterHud.Mul(NameCol, a), name); top = pos.Y; } } - // Gain text floats above the plate when it's over the head, else above the head itself. - PlateTop = where == SelfPlatePosition.Above ? top : head.Y; + return top; } /// The camera at (or inside) the head: AC's first-person view. @@ -228,5 +379,7 @@ internal static class PlayerPlate public static string Describe() => $"Self plate {(MonsterHudSettings.SelfPlate ? "on" : "off")}" + - (FirstPerson ? " (first person" + (MonsterHudSettings.SelfHideFirstPerson ? ", hidden)." : ").") : "."); + (MonsterHudSettings.SelfPlacement == SelfPlacement.Fixed + ? (MonsterHudSettings.SelfLocked ? ", fixed on screen (locked)." : ", fixed on screen (unlocked: drag it).") + : FirstPerson ? ", follows you (first person" + (MonsterHudSettings.SelfHideFirstPerson ? ", hidden)." : ").") : ", follows you."); } diff --git a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs new file mode 100644 index 0000000..00af2e3 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs @@ -0,0 +1,319 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/DashboardDrawers.cs +// The RynthAi dashboard's slide-out drawers (Tom 2026-10-05: every drawer on +// the dashboard's left edge; only the vitals / target bars stay at its +// bottom). One tab per drawer, stacked down the left edge; a click slides +// that drawer's panel out to the left (to the right when the dashboard sits +// too close to the screen's left edge for the widest drawer). One drawer is +// open at a time: opening one closes the other, so the panels never stack +// and the tabs never jump. +// +// The mechanics live here (tabs, slide, side, placement, the one window); +// each drawer only draws its panel (DashboardDrawer.DrawPanel) and says how +// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files and +// Patrol (RynthAiFace.Drawers.cs). +// +// A top-level ImGui window of its own, begun from inside the dashboard's Draw +// and placed against the dashboard's window every frame, so it follows the +// dashboard (and goes away with it). Each drawer's open/closed is saved with +// the dashboard's state (RynthAiDashboardState). Popped out the tabs are +// hidden: a popped-out dashboard is its own small window and the area around +// it lets clicks through to the game, so a drawer beside it couldn't be used +// (the dashboard falls back to its inline files block and patrol popup). +// +// AC thread only (inside the dashboard's Draw). +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +/// One drawer on the dashboard's left edge: its tab's look and its panel. +internal abstract class DashboardDrawer +{ + /// Set by the host: close this drawer from inside the panel (its close button). + public DashboardDrawers? Host { get; set; } + + /// Unique among the drawers ("##drawer_tab_" + Key is the tab's id). + public abstract string Key { get; } + /// Phosphor glyph on the tab. + public abstract string Icon { get; } + /// Lower-case name for "Hide the …" tooltips. + public abstract string Name { get; } + /// The closed tab's tooltip; : it slides out to the right. + public abstract string TabTooltip(bool right); + + /// Panel size in pixels at text scale . + public abstract float Width(float k); + public abstract float Height(float k); + + /// Every frame before drawing: while any of the panel is out (subscriptions, data). + public virtual void Update(bool showing) { } + + /// Draws the whole panel at (the host clips it to the part slid out). + public abstract void DrawPanel(Vector2 origin, float width, float height, float k); + + /// The saved open/closed (RynthAiDashboardState). + public abstract bool SavedOpen { get; } + public abstract void SaveOpen(bool open); + + private string? _tabId, _hideTip; + /// The tab's ImGui id and open tooltip (built once). + internal string TabId => _tabId ??= "##drawer_tab_" + Key; + internal string HideTip => _hideTip ??= "Hide the " + Name + "."; + + protected void Close() => Host?.Close(this); + + protected static float CalcWidth(ImFontPtr font, string text) + { + ImGuiNET.ImGui.PushFont(font); + float w = ImGuiNET.ImGui.CalcTextSize(text).X; + ImGuiNET.ImGui.PopFont(); + return w; + } + + // ── The shared panel frame: background, title row (icon + TITLE + note | close) ── + + protected static readonly uint DTeal = RynthTheme.Argb(0xFF26D9E6), DMute = RynthTheme.Argb(0xFFB8C8D8), + DWhite = RynthTheme.Argb(0xFFF2F7FC), DBtnFill = RynthTheme.Argb(0xFF16283A), DBtnBord = RynthTheme.Argb(0xFF34587A); + protected const float Pad = 6, TitleH = 18; + + /// Paints the panel's background and title row; returns the y under the title (pixels). + protected float PanelFrame(Vector2 origin, float panelW, float panelH, float k, string icon, string title, string? note, string closeTip) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(origin, origin + new Vector2(panelW, panelH), RynthTheme.RynthAiBackground, RynthTheme.RynthAiRounding); + dl.AddRect(origin, origin + new Vector2(panelW, panelH), RynthTheme.RynthAiBorder, RynthTheme.RynthAiRounding); + + float x = origin.X + Pad * k, w = panelW - 2 * Pad * k, y = origin.Y + Pad * k; + ImFontPtr f11 = ImGuiFonts.Get(UiFont.Dash11), f9 = ImGuiFonts.Get(UiFont.Dash9); + float th = TitleH * k; + float iconW = CalcWidth(f11, icon); + dl.AddText(f11, f11.FontSize, new Vector2(x, y + (th - f11.FontSize) * 0.5f), DTeal, icon); + dl.AddText(f11, f11.FontSize, new Vector2(x + iconW + 4 * k, y + (th - f11.FontSize) * 0.5f), DWhite, title); + if (note != null) + { + float tw = CalcWidth(f11, title); + dl.AddText(f9, f9.FontSize, new Vector2(x + iconW + 4 * k + tw + 4 * k, y + (th - f9.FontSize) * 0.5f + 1), DMute, note); + } + Vector2 closeSize = new(18 * k, 16 * k); + if (FaceKit.IconButton("##drawer_close", PhosphorIcons.X, new Vector2(x + w - closeSize.X, y + (th - closeSize.Y) * 0.5f), + closeSize, DMute, DBtnFill, border: DBtnBord, font: UiFont.Dash10)) + Close(); + ImGuiNET.ImGui.SetItemTooltip(closeTip); + return y + th + 4 * k; + } +} + +/// The tabs and the one open drawer beside the RynthAi dashboard. +internal sealed class DashboardDrawers +{ + private const string WindowId = "##rynthai_drawers"; + private const float SlideSeconds = 0.14f; + + private static readonly uint Teal = RynthTheme.Argb(0xFF26D9E6), Mute = RynthTheme.Argb(0xFFB8C8D8), + White = RynthTheme.Argb(0xFFF2F7FC), BtnFill = RynthTheme.Argb(0xFF16283A), BtnBord = RynthTheme.Argb(0xFF34587A); + + private readonly DashboardDrawer[] _drawers; + private int _open = -1; // the drawer open (or opening); -1 none + private int _shown = -1; // the drawer whose panel draws (a closing one until it has slid in) + private float _t; // slide position of _shown, 0 closed .. 1 open + private bool _loaded; + + public DashboardDrawers(params DashboardDrawer[] drawers) + { + _drawers = drawers; + foreach (DashboardDrawer d in drawers) d.Host = this; + } + + public bool IsOpen(DashboardDrawer d) => _open >= 0 && _drawers[_open] == d; + + /// Opens (closing the open one), or closes it when it is the open one. + public void Toggle(DashboardDrawer d) + { + if (IsOpen(d)) Close(d); + else Open(d); + } + + public void Open(DashboardDrawer d) + { + EnsureLoaded(); + int i = Array.IndexOf(_drawers, d); + if (i < 0 || i == _open) return; + if (_open >= 0) _drawers[_open].SaveOpen(false); + _open = i; + d.SaveOpen(true); + if (_shown != i) + { + // Another drawer was out (or sliding in): this one slides out from closed. + _shown = i; + _t = 0f; + } + } + + public void Close(DashboardDrawer d) + { + if (!IsOpen(d)) return; + _open = -1; + d.SaveOpen(false); + } + + /// The dashboard closed: every drawer drops its subscriptions. AC thread. + public void Detach() + { + foreach (DashboardDrawer d in _drawers) d.Update(false); + } + + private void EnsureLoaded() + { + if (_loaded) return; + _loaded = true; + // The first drawer saved open wins (one at a time); any other saved open is closed. + for (int i = 0; i < _drawers.Length; i++) + { + if (!_drawers[i].SavedOpen) continue; + if (_open < 0) _open = i; + else _drawers[i].SaveOpen(false); + } + _shown = _open; + _t = _open >= 0 ? 1f : 0f; + } + + /// + /// Draws the tabs and the open drawer. Call at the end of the dashboard's Draw, inside its + /// body child (whose rect is the dashboard's: the face is chromeless). + /// + public void Draw() + { + if (ImGuiPopOuts.InPopOutFrame) + { + // Popped out: no tabs (see the header). Nothing polled meanwhile. + Detach(); + return; + } + EnsureLoaded(); + + // Slide. + float target = _open >= 0 && _open == _shown ? 1f : 0f; + if (_t != target) + { + float step = ImGuiNET.ImGui.GetIO().DeltaTime / SlideSeconds; + if (step <= 0 || float.IsNaN(step)) step = 1f; + _t = target > _t ? MathF.Min(1f, _t + step) : MathF.Max(0f, _t - step); + } + if (_t <= 0f && _open < 0) _shown = -1; + float ease = _t * _t * (3f - 2f * _t); + bool showing = _shown >= 0 && ease > 0.001f; + for (int i = 0; i < _drawers.Length; i++) _drawers[i].Update(showing && i == _shown); + + // Geometry (pixels; k follows the dashboard's text size). + Vector2 dashPos = ImGuiNET.ImGui.GetWindowPos(), dashSize = ImGuiNET.ImGui.GetWindowSize(); + Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; + float k = MathF.Max(1f, ImGuiFonts.Get(UiFont.Dash11).FontSize / 11f); + int n = _drawers.Length; + float tabW = 14 * k, tabGap = 3 * k, tabTop = 4 * k; + // Tabs share the dashboard's height (40 tall at most, 20 at least: they may run past a minimized dashboard). + float tabH = MathF.Max(20 * k, MathF.Min(40 * k, (dashSize.Y - 2 * tabTop - (n - 1) * tabGap) / Math.Max(1, n))); + float tabsH = n * tabH + (n - 1) * tabGap; + float widest = 0; + foreach (DashboardDrawer d in _drawers) widest = MathF.Max(widest, d.Width(k)); + float panelW = showing ? _drawers[_shown].Width(k) : widest; + float panelH = showing ? _drawers[_shown].Height(k) : 0; + float dashRight = dashPos.X + dashSize.X; + // Left unless there's no room there for the widest drawer and more on the right (so the tabs never switch sides + // as drawers open and close). + bool right = dashPos.X < tabW + widest && display.X - dashRight > dashPos.X; + float shown = showing ? panelW * ease : 0; + + float winX = right ? dashRight : dashPos.X - tabW - shown; + float winW = tabW + shown; + float tabX = right ? dashRight : dashPos.X - tabW; + // Neither side has room (a very wide dashboard): keep it on the screen, over the dashboard. + float shift = 0; + if (winX < 0) shift = -winX; + else if (display.X > 1 && winX + winW > display.X) shift = display.X - (winX + winW); + winX += shift; + tabX += shift; + + float winY = dashPos.Y; + float tabsBottom = tabTop + tabsH; // relative to the dashboard's top + float winH = showing ? MathF.Max(panelH, tabsBottom) : tabsBottom; + if (display.Y > 1 && winY + winH > display.Y) winY = MathF.Max(0, display.Y - winH); + float tabY = dashPos.Y + tabTop; + winH = MathF.Max(winH, tabY + tabsH - winY); + + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(winX, winY), ImGuiCond.Always); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(winW, winH), ImGuiCond.Always); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 0f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, Vector2.One); + bool visible = ImGuiNET.ImGui.Begin(WindowId, WindowFlags); + ImGuiNET.ImGui.PopStyleVar(4); + try + { + if (visible) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash10)); + try + { + if (showing) + { + // The panel's visible part; its content slides with the open edge. + float visX0 = right ? tabX + tabW : winX; + float contentX = right ? tabX + tabW + shown - panelW : winX; + Vector2 vMin = new(visX0, winY), vMax = new(visX0 + shown, winY + panelH); + DashboardDrawer d = _drawers[_shown]; + ImGuiNET.ImGui.PushClipRect(vMin, vMax, true); + ImGuiNET.ImGui.PushID(d.Key); + try { d.DrawPanel(new Vector2(contentX, winY), panelW, panelH, k); } + finally + { + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.PopClipRect(); + } + } + for (int i = 0; i < n; i++) + DrawTab(_drawers[i], new Vector2(tabX, tabY + i * (tabH + tabGap)), new Vector2(tabW, tabH), right, k); + } + finally { ImGuiNET.ImGui.PopFont(); } + } + } + finally + { + ImGuiNET.ImGui.End(); + } + } + + private const ImGuiWindowFlags WindowFlags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize + | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoDocking + | ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoNav; + + private void DrawTab(DashboardDrawer d, Vector2 pos, Vector2 size, bool right, float k) + { + bool open = IsOpen(d); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(d.TabId, size); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + // Like SetItemTooltip (same delay), but the closed tooltip is only built while it shows. + if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip)) + ImGuiNET.ImGui.SetTooltip(open ? d.HideTip : d.TabTooltip(right)); + if (clicked) Toggle(d); + + uint fill = ImGuiNET.ImGui.IsItemActive() ? FaceKit.Darken(BtnFill) : hot ? FaceKit.Lighten(BtnFill) : BtnFill; + ImDrawFlags corners = right ? ImDrawFlags.RoundCornersRight : ImDrawFlags.RoundCornersLeft; + dl.AddRectFilled(pos, pos + size, fill, 4 * k, corners); + dl.AddRect(pos, pos + size, open ? Teal : BtnBord, 4 * k, corners); + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); + float half = size.Y * 0.5f; + PhosphorIcons.DrawCentered(dl, f10, d.Icon, pos, new Vector2(size.X, half), open ? Teal : Mute); + // The caret points the way the drawer will move. + string caret = right == open ? PhosphorIcons.CaretLeft : PhosphorIcons.CaretRight; + PhosphorIcons.DrawCentered(dl, f10, caret, pos + new Vector2(0, half), new Vector2(size.X, half), hot ? White : Mute); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs b/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs index 0d56558..5820054 100644 --- a/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs +++ b/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs @@ -201,6 +201,7 @@ internal static class FaceKit ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3f); bool result = ImGuiNET.ImGui.InputText(id, buffer, (uint)buffer.Length, flags); active = ImGuiNET.ImGui.IsItemActive(); + if (active) ImGuiTextFocus.NoteActive(id); // keys stay out of AC from this frame on ImGuiNET.ImGui.PopStyleVar(3); ImGuiNET.ImGui.PopStyleColor(3); if (buffer[0] == 0 && !active && hint.Length > 0) diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index 1dddede..8203e1d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -102,6 +102,8 @@ internal sealed partial class InventoryFace : IImGuiPanel private InventoryItem? _splitItem; private int _splitAmount = 1; private uint _splitTarget; + // "Add to loot profile..." (right-click): RynthAi builds the rule, the popup previews it. + private readonly LootAddDialog _lootAdd = new("##inv_lootadd"); // Status line cache. private string _statusText = string.Empty; @@ -120,6 +122,7 @@ internal sealed partial class InventoryFace : IImGuiPanel InventoryModel.Hover(0); InventoryModel.Unsubscribe(); _dragItem = _pressItem = null; + _lootAdd.Cancel(); } // ===================================================================== @@ -155,6 +158,7 @@ internal sealed partial class InventoryFace : IImGuiPanel DrawDragGhost(); ContextMenu(view); SplitDialog(view); + _lootAdd.Draw(); _picker.Draw(); } @@ -883,6 +887,11 @@ internal sealed partial class InventoryFace : IImGuiPanel if (target != null && it.Wielder == 0 && ImGuiNET.ImGui.MenuItem(target.MenuLabel, "", false, idle && InventoryModel.GiveAvailable)) Act(InventoryActionKind.Give, it, target.Id, target.Name, 0); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Add to loot profile...")) + _lootAdd.Open(it.Id, it.Name, toOpenProfile: false); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Make a RynthAi loot rule for this item (preview first)"); if (!idle) ImGuiNET.ImGui.TextDisabled("(an item action is waiting)"); } diff --git a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs new file mode 100644 index 0000000..34b14fc --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs @@ -0,0 +1,380 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/LootAddDialog.cs +// "Add to loot profile": the small popup that turns a clicked item into a +// loot rule (2026-10-04). Opened from the Inventory panel's right-click menu +// and from the Loot Editor's "Add selected item"; /ra loot add is the chat +// twin (no popup, defaults straight in). +// +// item its name and the profile the rule goes to +// match name + class (default), name only, items like this +// action Keep, Keep # (with the count), Salvage, Sell, Read +// name the rule's name (empty: RynthAi's default, "Keep Copper Pea") +// preview the rule in words, where it goes in the list and why, notes +// Add RynthAi inserts it, saves (old file kept as .bak) and reloads +// +// RynthAi builds the rule (LootSdk LootItemRules) and does the insert and the +// save; this face only posts item_preview / item_add / item_close through +// LootEditCommands and shows LootEditStateDto.ItemDraft. A face owns one of +// these and calls Draw once per frame outside any child window. +// ============================================================================ + +using System; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class LootAddDialog +{ + private static readonly string[] MatchLabels = { "Name + class", "Name only", "Items like this" }; + private static readonly string[] MatchTips = + { + "This exact item: its name and its kind (object class).", + "Anything with this exact name.", + "Its kind plus key properties: material, workmanship, slot, armor / damage, ratings and spells, at least as good as this one. No name.", + }; + private static readonly int[] ActionIds = + { LootEditVocabulary.Keep, LootEditVocabulary.KeepUpTo, LootEditVocabulary.Salvage, LootEditVocabulary.Sell, LootEditVocabulary.Read }; + private static readonly string[] ActionLabels = { "Keep", "Keep #", "Salvage", "Sell", "Read" }; + + private readonly string _id; + private bool _open, _openRequested, _subscribed; + private uint _itemId; + private string _itemName = string.Empty; + private bool _toOpenProfile; + + // What the popup asks for (0 / -1 = RynthAi's default). + private int _match, _action, _keep = -1; + private readonly byte[] _name = new byte[128]; + private int _keepEdit = 1; + + // Seqs are unique across popups (the inventory's and the editor's share RynthAi's one draft): + // a popup only takes an answer to something it asked. + private static int s_seq; + private readonly System.Collections.Generic.HashSet _mine = new(); + private int _seq; + private DateTime _sentAt; + private long _seenVersion = -1; + private LootEditItemDraftDto? _draft; + private bool _adding; + private DateTime _addedAt; + private bool _justAdded; + + /// True once after an add went through (the Loot Editor scrolls to the new rule). + public bool TakeAdded() + { + bool v = _justAdded; + _justAdded = false; + return v; + } + + public LootAddDialog(string id) => _id = id; + + public bool IsOpen => _open; + + /// + /// Opens the popup for (0: the item selected in the + /// game, resolved once). : the rule goes to the + /// profile open in the Loot Editor, else to the one RynthAi loots with. + /// + public void Open(uint itemId, string itemName, bool toOpenProfile) + { + _itemId = itemId; + _itemName = itemName ?? string.Empty; + _toOpenProfile = toOpenProfile; + _match = 0; + _action = 0; + _keep = -1; + Array.Clear(_name); + _draft = null; + _adding = false; + _addedAt = default; + _mine.Clear(); + if (!_subscribed) + { + UiSources.LootEdit.Subscribe(); + _subscribed = true; + } + _openRequested = true; + Send("item_preview"); + } + + private void Send(string op) + { + _seq = System.Threading.Interlocked.Increment(ref s_seq); + _mine.Add(_seq); + _sentAt = DateTime.UtcNow; + LootEditCommands.Send(new LootEditCmd + { + Op = op, + Item = new LootEditItemRequestDto + { + ItemId = _itemId, Match = _match, Action = _action, KeepCount = _keep, + RuleName = Utf8(_name).Trim(), ToOpenProfile = _toOpenProfile, Seq = _seq, + }, + }); + } + + /// The owning face was hidden: drop the popup (and its subscription and draft). + public void Cancel() + { + if (_open || _subscribed) Close(); + _openRequested = false; + } + + private void Close() + { + if (_open || _subscribed) LootEditCommands.Simple("item_close"); + _open = false; + if (_subscribed) + { + UiSources.LootEdit.Unsubscribe(); + _subscribed = false; + } + } + + /// Once per frame, outside any child window. + public void Draw() + { + if (_openRequested) + { + _openRequested = false; + _open = true; + ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always); + ImGuiNET.ImGui.OpenPopup(_id); + } + if (!_open) return; + TakeDraft(); + + PushStyle(); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8)); + bool visible = ImGuiNET.ImGui.BeginPopup(_id, ImGuiWindowFlags.AlwaysAutoResize); + ImGuiNET.ImGui.PopStyleVar(); + if (!visible) + { + PopStyle(); + Close(); // clicked outside, or Esc + return; + } + try + { + if (Body()) ImGuiNET.ImGui.CloseCurrentPopup(); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + PopStyle(); + } + } + + private void TakeDraft() + { + var snap = UiSources.LootEdit.Current; + if (snap == null || snap.Version == _seenVersion) return; + _seenVersion = snap.Version; + LootEditItemDraftDto? d = snap.Value.State?.ItemDraft; + if (d == null || !_mine.Contains(d.Seq) || (_draft != null && d.Seq < _draft.Seq)) return; + bool first = _draft == null; + _draft = d; + if (d.ItemId != 0) _itemId = d.ItemId; // the selected item, from now on by id + if (d.ItemName.Length > 0) _itemName = d.ItemName; + if (d.Seq == _seq) + { + if (_adding) + { + _adding = false; + if (d.Added) + { + _addedAt = DateTime.UtcNow; + _justAdded = true; + } + } + if (!ImGuiNET.ImGui.IsAnyItemActive() || first) _keepEdit = Math.Max(0, d.KeepCount); + } + } + + /// The popup's contents; true when it should close. + private bool Body() + { + const float w = 380; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.Plus + " Add to loot profile"); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.TextUnformatted(_itemName.Length > 0 ? _itemName : "the selected item"); + ImGuiNET.ImGui.Separator(); + + LootEditItemDraftDto? d = _draft; + bool current = d != null && d.Seq == _seq; + if (d == null) + { + bool slow = (DateTime.UtcNow - _sentAt).TotalSeconds > 3; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, slow ? Amber : Mute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(slow + ? "No answer from RynthAi. Is it loaded? (A RynthAi older than this feature doesn't answer; /ra loot add needs the new one too.)" + : "Building the rule..."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + return CloseRow(w); + } + + if (d.Added && _addedAt != default) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Green); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(d.Message + (d.TargetInUse ? ". RynthAi loots with it now." : " (not the profile RynthAi loots with).")); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + if ((DateTime.UtcNow - _addedAt).TotalSeconds > 2.5) return CloseNow(); + return CloseRow(w); + } + + // Where it goes. + if (d.TargetFile.Length > 0) + { + ImGuiNET.ImGui.TextDisabled("Profile:"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextUnformatted(d.TargetFile + (d.TargetInUse ? " (in use)" : " (not the one RynthAi loots with)")); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(d.TargetPath); + } + + bool changed = false; + // Match. + ImGuiNET.ImGui.TextDisabled("Match:"); + for (int i = 0; i < MatchLabels.Length; i++) + { + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.RadioButton(MatchLabels[i] + "##m" + i.ToString(CultureInfo.InvariantCulture), d.Match == i) && d.Match != i) + { + _match = i; + changed = true; + } + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(MatchTips[i]); + } + + // Action. + ImGuiNET.ImGui.TextDisabled("Action:"); + for (int i = 0; i < ActionIds.Length; i++) + { + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.RadioButton(ActionLabels[i] + "##a" + i.ToString(CultureInfo.InvariantCulture), d.Action == ActionIds[i]) && d.Action != ActionIds[i]) + { + _action = ActionIds[i]; + changed = true; + } + } + if (d.Action == LootEditVocabulary.KeepUpTo) + { + ImGuiNET.ImGui.TextDisabled("Keep up to:"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(110); + ImGuiNET.ImGui.InputInt("##la_keep", ref _keepEdit, 1, 10); + _keepEdit = Math.Max(0, _keepEdit); + bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit() || (ImGuiNET.ImGui.IsItemEdited() && !ImGuiNET.ImGui.IsItemActive()); + if (done && _keepEdit != d.KeepCount) + { + _keep = _keepEdit; + _action = LootEditVocabulary.KeepUpTo; + changed = true; + } + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextDisabled(d.Stackable ? "(counts stack sizes)" : "(items)"); + } + + // Name. + ImGuiNET.ImGui.TextDisabled("Name:"); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(w - 50); + ImGuiNET.ImGui.InputText("##la_name", _name, (uint)_name.Length); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) changed = true; + if (Utf8(_name).Trim().Length == 0 && d.DefaultRuleName.Length > 0) + ImGuiNET.ImGui.TextDisabled("Left empty, the rule is named \"" + d.DefaultRuleName + "\"."); + + // Preview. + ImGuiNET.ImGui.Separator(); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, current ? Teal : Faded(Teal)); + foreach (string line in d.Preview) ImGuiNET.ImGui.TextUnformatted(line); + ImGuiNET.ImGui.PopStyleColor(); + if (d.OrderNote.Length > 0) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.TextUnformatted(d.OrderNote); + ImGuiNET.ImGui.PopStyleColor(); + } + if (d.Notes.Count > 0) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + foreach (string n in d.Notes) ImGuiNET.ImGui.TextUnformatted(n); + ImGuiNET.ImGui.PopStyleColor(); + } + if (!d.Ok && d.Error.Length > 0) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Red); + ImGuiNET.ImGui.TextUnformatted(d.Error); + ImGuiNET.ImGui.PopStyleColor(); + } + ImGuiNET.ImGui.PopTextWrapPos(); + + if (changed) + { + Send("item_preview"); // Add waits for the answer (the preview shows faded until then) + current = false; + } + + // Add / Cancel. + Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + bool canAdd = current && d.Ok && !_adding; + string addLabel = _adding ? "Adding..." : PhosphorIcons.Plus + " Add rule"; + if (Button("##la_add", addLabel, bp, new Vector2(110, 24), canAdd ? Green : Mute, canAdd ? StartBg : BtnFill, canAdd)) + { + _adding = true; + Send("item_add"); + } + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip(d.InsertAt >= 0 + ? $"Insert at {d.InsertAt + 1} of {d.RuleCount + 1}, save {d.TargetFile} (old file kept as .bak) and reload it" + : "Add the rule"); + if (Button("##la_cancel", "Cancel", bp + new Vector2(116, 0), new Vector2(80, 24), Text, BtnFill)) + return CloseNow(); + ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28)); + ImGuiNET.ImGui.Dummy(new Vector2(w, 0)); + return false; + } + + private bool CloseRow(float w) + { + Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); + bool close = Button("##la_close", "Close", bp, new Vector2(80, 24), Text, BtnFill); + ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28)); + ImGuiNET.ImGui.Dummy(new Vector2(w, 0)); + return close && CloseNow(); + } + + private bool CloseNow() + { + Close(); + return true; + } + + private static void PushStyle() + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, Lighten(BtnFill)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Separator, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + } + + private static void PopStyle() + { + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(7); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs index 235957f..e013cf7 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs @@ -120,6 +120,8 @@ internal sealed class LootEditorFace : IImGuiPanel private const string OtherNumber = "Other number..."; private readonly Picker _picker = new("##loot_pick"); + // "Add selected item": a rule for the item selected in the game, into the open profile. + private readonly LootAddDialog _lootAdd = new("##loot_additem"); // ── List ───────────────────────────────────────────────────────────── @@ -171,6 +173,7 @@ internal sealed class LootEditorFace : IImGuiPanel { UiSources.LootEdit.WantRule(-1); UiSources.LootEdit.Unsubscribe(); + _lootAdd.Cancel(); } // ===================================================================== @@ -202,6 +205,10 @@ internal sealed class LootEditorFace : IImGuiPanel else RuleView(origin, size, w); } End(origin, size); + _lootAdd.Draw(); + // An item rule added to the open profile: show it (the state already carries it and its Focus). + if (_lootAdd.TakeAdded() && _mode == Mode.List && _state != null && _state.Focus >= 0 && _state.Focus < _state.Rules.Count) + _scrollTo = _state.Focus; _picker.Draw(); } @@ -708,6 +715,15 @@ internal sealed class LootEditorFace : IImGuiPanel Expect(Await.OpenFocus); } ImGuiNET.ImGui.SetItemTooltip("Add a rule at the end and edit it"); + string itemLabel = PhosphorIcons.Plus + " Add selected item"; + float itemW = ButtonWidth(itemLabel) + 6; + bool canItem = s.Path.Length > 0 && !s.Dirty && (!s.ReadOnly || s.Format == "json"); + if (Button("##add_item", itemLabel, new Vector2(p.X + addW + 6, p.Y), new Vector2(itemW, h), canItem ? Teal : Mute, BtnFill, canItem)) + _lootAdd.Open(0, string.Empty, toOpenProfile: true); + ImGuiNET.ImGui.SetItemTooltip(canItem + ? "A rule for the item selected in the game (click it first): preview, then add it here" + : s.Dirty ? "Save or discard your edits first" : "This profile is read-only here"); + addW += itemW + 6; MessageText(new Vector2(p.X + addW + 8, p.Y), p.X + w - grip - 4, h); NextLine(p, h); } diff --git a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs new file mode 100644 index 0000000..3e275dc --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs @@ -0,0 +1,501 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RangesSlideOut.cs +// The RynthAi dashboard's "Ranges" drawer (a player request, Tom 2026-10-04): +// a small tab on the dashboard's left edge; clicking it slides a narrow panel +// out to the left (to the right when the dashboard sits too close to the +// screen's left edge for it). Top to bottom: +// title ruler + RANGES (yd) | close +// monster the selected creature: name, priority / damage type / weak +// to, weapon; Edit opens its Monster Detail page, the skull its +// row on the Damage panel (weapon, off hand, pet, debuffs). +// "Select a monster" with nothing selected; "Not a monster" for +// players, NPCs, pets and items (Edit off). +// ranges slider + number rows: Monster range, Nav point reach, Ring +// range, Approach range, Blast range (0 = off), Corpse range +// (max). Labels are short; min/max/step, tooltips and saving +// are the Settings panel's rows (SettingsSchema.Find). +// Values save exactly like the Settings face: a private copy of the hub's +// settings, the row's Set, SettingsCommands.Save of the whole copy (RynthAi +// saves it to the profile). A newer fetch replaces the copy while nothing here +// is typed in or dragged, so Settings > Ranges and this drawer follow each +// other. A slider saves when it's let go; a typed value on Enter or focus loss +// (clamped; bad input reverts). Number boxes are FaceKit.TextBox, so typing +// keeps keys out of AC (ImGuiTextFocus). +// +// One of the dashboard's left-edge drawers (DashboardDrawers.cs: the tab, the +// slide, the side, the window; one drawer open at a time). Open/closed is +// saved with the dashboard's state (RynthAiDashboardState.RangesOpen). Popped +// out the tabs are hidden (see DashboardDrawers); Settings > Ranges still +// works there. +// +// AC thread only (inside the dashboard's Draw). The selection is read once a +// frame while the drawer shows and resolved only when it changes; display +// strings are built when the selection or its data changes, not per frame. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Text; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; +using Rule = RynthCore.Engine.UI.Panels.MonstersPanel.Rule; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class RangesSlideOut : DashboardDrawer +{ + // ── Palette (the dashboard's, ARGB) ──────────────────────────────── + private static readonly uint Teal = C(0xFF26D9E6), TealSoft = C(0xFF264C59), Amber = C(0xFFE8B333), + Gold = C(0xFFFFD16A), Mute = C(0xFFB8C8D8), White = C(0xFFF2F7FC), BarBg = C(0xFF141F29), + BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A); + private static uint C(uint argb) => RynthTheme.Argb(argb); + + // ── Rows: (Settings row label, short label here) ──────────────────── + private static readonly (string Schema, string Short)[] Wanted = + { + ("Monster Range", "Monster range"), + (SettingsSchema.NavPointReachLabel, "Nav point reach"), + ("Ring Range", "Ring range"), + ("Approach Range", "Approach range"), + ("Blast Range (yd)", "Blast (0=off)"), + ("Corpse Max (yd)", "Corpse range"), + }; + + private sealed class Row + { + public required SettingRow Setting; + public required string Label; + public required string Tip; + public required bool IsInt; + public readonly byte[] Buffer = new byte[24]; + public double Shown = double.NaN; + public bool Typing, Dragging; + public double DragValue; + } + + private static Row[]? _rows; + + private static Row[] Rows => _rows ??= BuildRows(); + + private static Row[] BuildRows() + { + var list = new List(Wanted.Length); + foreach (var (schema, label) in Wanted) + { + SettingRow? s = SettingsSchema.Find(schema); + if (s?.Get == null || s.Set == null) continue; // renamed in the schema: leave it out + string tip = s.Tooltip ?? schema; + if (schema == "Corpse Max (yd)") tip = "Corpse Max on Settings > Ranges.\n" + tip; + list.Add(new Row { Setting = s, Label = label, Tip = tip, IsInt = s.Kind == SettingKind.Int }); + } + return list.ToArray(); + } + + // ── State ──────────────────────────────────────────────────────────── + private RynthAiSettings? _data; + private long _seenVersion = -1; + private bool _busy; // a row was typed in or dragged last frame + private bool _subSettings, _subMonster; + + // The selection, resolved when it changes. + private enum SelKind { None, Unknown, Monster, NotMonster } + private uint _selId = uint.MaxValue; + private long _selSince, _selChecked; + private SelKind _kind = SelKind.None; + private string _selName = ""; + private uint _selWcid; + private long _damageSeen = -1, _rulesSeen = -1; + private bool _factsDirty = true; + private string _facts1 = "", _facts2 = "", _factsTip = ""; + private string _editTip = NoEditTip, _damageTip = NoDamageTip; + private const string NoEditTip = "Select a monster to edit its rule."; + private const string NoDamageTip = "Select a monster to see it on the Damage panel."; + private bool _factsGold; + + private const uint TypeCreature = 0x10; // ITEM_TYPE TYPE_CREATURE + private const uint BfPlayer = 0x8; // PublicWeenieDesc BF_PLAYER + private const uint BfVendor = 0x200; // PublicWeenieDesc BF_VENDOR + private const uint PetOwnerIid = 44; // PropertyInstanceId PetOwner (summoned pets) + + // ── Drawer ─────────────────────────────────────────────────────────── + + public override string Key => "ranges"; + public override string Icon => PhosphorIcons.Ruler; + public override string Name => "ranges"; + public override bool SavedOpen => RynthAiDashboardState.RangesOpen; + public override void SaveOpen(bool open) => RynthAiDashboardState.SetRangesOpen(open); + + public override string TabTooltip(bool right) => right + ? "Ranges: monster range, nav point reach and more, and the selected monster.\nClick to slide them out (to the right: there's no room on the left)." + : "Ranges: monster range, nav point reach and more, and the selected monster.\nClick to slide them out."; + + public override float Width(float k) => 250 * k; + public override float Height(float k) => PanelHeight(k); + + /// While the panel is out: the selection, the hub subscriptions, a newer settings fetch. + public override void Update(bool showing) + { + if (showing) ReadSelection(); + SetSubscriptions(showing, showing && _kind == SelKind.Monster); + if (showing) TakeNewerSettings(force: false); + } + + // ── Panel ──────────────────────────────────────────────────────────── + + private const float LineH = 15, RowH = 20, RowGap = 3; + + private static float PanelHeight(float k) => + (Pad + TitleH + 4 + 3 * LineH + 6 + 3 + Math.Max(1, Rows.Length) * (RowH + RowGap) + Pad) * k; + + public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + // Title row: ruler + RANGES (yards) | close. + float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.Ruler, "RANGES", "yards", "Hide the ranges"); + float x = origin.X + Pad * k, w = panelW - 2 * Pad * k; + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); + + MonsterBlock(dl, x, y, w, k); + y += 3 * LineH * k + 6 * k; + dl.AddLine(new Vector2(x, y), new Vector2(x + w, y), BtnBord); + y += 3 * k; + + if (_data == null) + { + dl.AddText(f10, f10.FontSize, new Vector2(x, y + 4 * k), Mute, + UiSources.Settings.Current == null ? "Waiting for RynthAi…" : "Loading…"); + _busy = false; + return; + } + + bool busy = false; + Row[] rows = Rows; + float labelW = 0; + foreach (Row r in rows) labelW = MathF.Max(labelW, CalcWidth(f10, r.Label)); + labelW += 6 * k; + for (int i = 0; i < rows.Length; i++) + { + ImGuiNET.ImGui.PushID(i); + busy |= NumberRow(rows[i], x, y, w, labelW, k); + ImGuiNET.ImGui.PopID(); + y += (RowH + RowGap) * k; + } + _busy = busy; + } + + // ── Number rows: label | slider | box ──────────────────────────────── + + /// Returns true while the row is typed in or dragged. + private bool NumberRow(Row r, float x, float y, float w, float labelW, float k) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + SettingRow s = r.Setting; + double value = Math.Clamp(s.Get!(_data!), s.Min, s.Max); + double shownValue = r.Dragging ? r.DragValue : value; + float h = RowH * k; + + // Label (tooltip: the Settings row's). + float fs = ImGuiNET.ImGui.GetFontSize(); + dl.AddText(new Vector2(x, y + (h - fs) * 0.5f), White, r.Label); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + ImGuiNET.ImGui.InvisibleButton("##label", new Vector2(Math.Max(1, labelW - 2 * k), h)); + ImGuiNET.ImGui.SetItemTooltip(r.Tip); + + // Box at the right. + float boxW = 46 * k; + float boxX = x + w - boxW; + if (!r.Typing && r.Shown != shownValue) WriteValue(r, shownValue); + FaceKit.TextBox("##v", r.Buffer, new Vector2(boxX, y), boxW, "", out bool typing, + ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll, h); + r.Typing = typing; + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + if (TryParse(r.Buffer, out double typed)) + { + double clamped = Math.Clamp(r.IsInt ? Math.Round(typed) : typed, s.Min, s.Max); + Changed(r, clamped); + } + else WriteValue(r, value); // bad input reverts + } + ImGuiNET.ImGui.SetItemTooltip(r.Tip); + + // Slider between them: drag (or click) to pick, saved when let go. + float sx = x + labelW, sw = boxX - 6 * k - sx; + if (sw > 10 * k) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(sx, y)); + ImGuiNET.ImGui.InvisibleButton("##slider", new Vector2(sw, h)); + bool active = ImGuiNET.ImGui.IsItemActive(); + bool hot = active || ImGuiNET.ImGui.IsItemHovered(); + float knobR = 5 * k; + float trackX0 = sx + knobR, trackX1 = sx + sw - knobR; + if (active && trackX1 > trackX0) + { + float f = Math.Clamp((ImGuiNET.ImGui.GetMousePos().X - trackX0) / (trackX1 - trackX0), 0f, 1f); + r.DragValue = Snap(s.Min + f * (s.Max - s.Min), s, r.IsInt); + r.Dragging = true; + shownValue = r.DragValue; + } + if (ImGuiNET.ImGui.IsItemDeactivated() && r.Dragging) + { + r.Dragging = false; + if (r.DragValue != value) Changed(r, r.DragValue); + } + ImGuiNET.ImGui.SetItemTooltip(r.Tip); + + float cy = y + h * 0.5f; + float frac = s.Max > s.Min ? (float)((shownValue - s.Min) / (s.Max - s.Min)) : 0f; + float kx = trackX0 + (trackX1 - trackX0) * Math.Clamp(frac, 0f, 1f); + dl.AddRectFilled(new Vector2(trackX0, cy - 2 * k), new Vector2(trackX1, cy + 2 * k), BarBg, 2 * k); + dl.AddRect(new Vector2(trackX0, cy - 2 * k), new Vector2(trackX1, cy + 2 * k), BtnBord, 2 * k); + if (kx > trackX0) dl.AddRectFilled(new Vector2(trackX0, cy - 2 * k), new Vector2(kx, cy + 2 * k), TealSoft, 2 * k); + dl.AddCircleFilled(new Vector2(kx, cy), knobR, hot ? White : Teal); + } + return r.Typing || r.Dragging; + } + + private static double Snap(double v, SettingRow s, bool isInt) + { + double step = s.Step > 0 ? s.Step : 1; + v = s.Min + Math.Round((v - s.Min) / step) * step; + v = isInt ? Math.Round(v) : Math.Round(v, 4); + return Math.Clamp(v, s.Min, s.Max); + } + + /// Saves a new value the way the Settings face does (the row's Set, the whole payload). + private void Changed(Row r, double value) + { + TakeNewerSettings(force: true); + if (_data == null) return; + r.Setting.Set!(_data, value); + SettingsCommands.Save(_data.Clone()); + WriteValue(r, value); + } + + /// A newer fetch replaces the copy unless a row is in use (force: about to save anyway). + private void TakeNewerSettings(bool force) + { + var snap = UiSources.Settings.Current; + if (snap == null || snap.Version == _seenVersion || (_busy && !force)) return; + _seenVersion = snap.Version; + _data = snap.Value.Clone(); + } + + private static void WriteValue(Row r, double value) + { + string text = r.IsInt ? ((long)Math.Round(value)).ToString(CultureInfo.InvariantCulture) + : value.ToString("G4", CultureInfo.InvariantCulture); + int n = Encoding.UTF8.GetBytes(text, 0, text.Length, r.Buffer, 0); + r.Buffer[Math.Min(n, r.Buffer.Length - 1)] = 0; + r.Shown = value; + } + + private static bool TryParse(byte[] buffer, out double value) + { + int len = Array.IndexOf(buffer, (byte)0); + if (len < 0) len = buffer.Length; + return double.TryParse(Encoding.UTF8.GetString(buffer, 0, len), NumberStyles.Float, CultureInfo.InvariantCulture, out value); + } + + // ── Selected monster ───────────────────────────────────────────────── + + private void MonsterBlock(ImDrawListPtr dl, float x, float y, float w, float k) + { + ImFontPtr f11 = ImGuiFonts.Get(UiFont.Dash11), f10 = ImGuiFonts.Get(UiFont.Dash10); + float lh = LineH * k; + bool monster = _kind == SelKind.Monster; + if (monster) BuildFacts(); + + // Buttons at the right of the name line: Edit (Monster Detail), Damage panel row. + Vector2 bsize = new(20 * k, lh); + float bx = x + w - 2 * bsize.X - 2 * k; + if (FaceKit.IconButton("##mon_edit", PhosphorIcons.PencilSimple, new Vector2(bx, y), bsize, monster ? Teal : Mute, BtnFill, + enabled: monster, border: BtnBord, font: UiFont.Dash10)) + DamageDetailFace.Show(_selWcid, _selName); + ImGuiNET.ImGui.SetItemTooltip(monster ? _editTip : NoEditTip); + if (FaceKit.IconButton("##mon_damage", PhosphorIcons.Skull, new Vector2(bx + bsize.X + 2 * k, y), bsize, monster ? Teal : Mute, BtnFill, + enabled: monster, border: BtnBord, font: UiFont.Dash10)) + { + if (!ImGuiPanelHost.IsOpen(DamageFace.Title)) PanelRouter.ToggleMonsters(); + } + ImGuiNET.ImGui.SetItemTooltip(monster ? _damageTip : NoDamageTip); + + // Name line. + string name; uint nameColor; + switch (_kind) + { + case SelKind.None: name = "Select a monster"; nameColor = Mute; break; + case SelKind.Unknown: name = _selName.Length > 0 ? _selName : "Reading…"; nameColor = Mute; break; + default: name = _selName.Length > 0 ? _selName : "(no name)"; nameColor = monster ? White : Mute; break; + } + float crossW = CalcWidth(f11, PhosphorIcons.Crosshair); + dl.AddText(f11, f11.FontSize, new Vector2(x, y + (lh - f11.FontSize) * 0.5f), monster ? Teal : Mute, PhosphorIcons.Crosshair); + dl.PushClipRect(new Vector2(x, y), new Vector2(bx - 4 * k, y + lh), true); + dl.AddText(f11, f11.FontSize, new Vector2(x + crossW + 4 * k, y + (lh - f11.FontSize) * 0.5f), nameColor, name); + dl.PopClipRect(); + + // Two fact lines (one tooltip over both). + float fy = y + lh; + string l1, l2; + uint c1 = Mute; + switch (_kind) + { + case SelKind.None: l1 = "Click one to see its rule here."; l2 = ""; break; + case SelKind.Unknown: l1 = ""; l2 = ""; break; + case SelKind.NotMonster: l1 = "Not a monster"; l2 = ""; c1 = Amber; break; + default: l1 = _facts1; l2 = _facts2; c1 = _factsGold ? Gold : Mute; break; + } + dl.PushClipRect(new Vector2(x, fy), new Vector2(x + w, fy + 2 * lh), true); + if (l1.Length > 0) dl.AddText(f10, f10.FontSize, new Vector2(x, fy + (lh - f10.FontSize) * 0.5f), c1, l1); + if (l2.Length > 0) dl.AddText(f10, f10.FontSize, new Vector2(x, fy + lh + (lh - f10.FontSize) * 0.5f), Mute, l2); + dl.PopClipRect(); + if (monster && _factsTip.Length > 0) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, fy)); + ImGuiNET.ImGui.InvisibleButton("##mon_facts", new Vector2(w, 2 * lh)); + ImGuiNET.ImGui.SetItemTooltip(_factsTip); + } + } + + /// Reads the selection (one read a frame) and classifies it when it changes. + private void ReadSelection() + { + uint sel = ClientHelperHooks.GetSelectedItemId(); + long now = Environment.TickCount64; + if (sel == _selId && (_kind != SelKind.Unknown || now - _selChecked < 250)) return; + if (sel != _selId) { _selId = sel; _selSince = now; } + _selChecked = now; + _factsDirty = true; + _selWcid = 0; + if (sel == 0) { _kind = SelKind.None; _selName = ""; return; } + + _selName = ClientObjectHooks.TryGetSnapshotName(sel, out string n) ? n : ""; + SelKind kind = Classify(sel); + // Not in the snapshots a second on: something that isn't out in the world (an item). + if (kind == SelKind.Unknown && now - _selSince > 1000) kind = SelKind.NotMonster; + if (kind == SelKind.Monster) + { + ClientObjectHooks.TryGetObjectWcid(sel, out _selWcid); // 0: the rule alone (by name) + _editTip = "Edit " + _selName + ": its Monster Detail page (priority, damage type, shapes).\n" + + "On Default, a change there gives it a rule of its own."; + _damageTip = "Damage panel: " + _selName + "'s row (weapon, off hand, pet, debuffs).\n" + + "The selected monster is highlighted (and listed first with Nearby first on)."; + } + _kind = kind; + } + + private static SelKind Classify(uint id) + { + if (!ClientObjectHooks.TryGetSnapshotItemType(id, out uint type)) return SelKind.Unknown; + if ((type & TypeCreature) == 0) return SelKind.NotMonster; + if (!ClientObjectHooks.TryGetSnapshotPwdInfo(id, out uint bf, out _, out _)) return SelKind.Unknown; + if ((bf & (BfPlayer | BfVendor)) != 0) return SelKind.NotMonster; + if (ClientObjectHooks.TryGetObjectInstanceIdProperty(id, PetOwnerIid, out uint owner) && owner != 0) return SelKind.NotMonster; + if (!ClientObjectHooks.TryGetSnapshotAttackable(id, out bool attackable)) return SelKind.Unknown; + return attackable ? SelKind.Monster : SelKind.NotMonster; // not attackable: an NPC + } + + /// Priority / damage type / weak to and the weapon, rebuilt when the monster or its data changes. + private void BuildFacts() + { + var dmg = UiSources.Damage.Current; + var rules = UiSources.MonsterRules.Current; + long dv = dmg?.Version ?? -1, rv = rules?.Version ?? -1; + if (!_factsDirty && dv == _damageSeen && rv == _rulesSeen) return; + _factsDirty = false; + _damageSeen = dv; + _rulesSeen = rv; + + string name = _selName; + DamageRow? row = null; + if (dmg != null) + foreach (DamageRow r in dmg.Value.Rows) + if (!r.IsDefault && (_selWcid != 0 ? r.Wcid == _selWcid : r.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) + { + row = r; + break; + } + + var tip = new StringBuilder(); + string prio = "?", dtype = "?"; + _factsGold = false; + if (rules != null) + { + MonsterRulesSnapshot rs = rules.Value; + Rule? own = rs.FindRule(name); + Rule? cover = own == null ? DamageCommands.CoveringRule(rs.Parsed.Rules, name) : null; + Rule use = own ?? cover ?? rs.DefaultRule(); + prio = use.Priority.ToString(CultureInfo.InvariantCulture); + dtype = string.IsNullOrEmpty(use.DamageType) ? "Auto" : use.DamageType; + _factsGold = own != null; + tip.Append("Priority ").Append(prio).Append(", damage type ").Append(dtype).Append(": ") + .Append(own != null ? "its own rule." : cover != null ? "the name rule \"" + cover.Name + "\"." : "Default (no rule of its own).") + .Append('\n'); + } + else tip.Append("Monster rules loading…\n"); + + string weakTop = ""; + if (row != null && row.Weak.Length > 0) + { + int comma = row.Weak.IndexOf(','); + string first = comma > 0 ? row.Weak.Substring(0, comma) : row.Weak; + int sp = first.IndexOf(' '); + weakTop = sp > 0 ? first.Substring(0, sp) : first; + tip.Append("Weak to: ").Append(row.Weak); + if (row.WeakSrc.Length > 0) tip.Append(" (").Append(row.WeakSrc).Append(')'); + tip.Append('\n'); + } + _facts1 = "Prio " + prio + " · " + dtype + (weakTop.Length > 0 ? " · weak " + weakTop : ""); + + if (row == null) + { + _facts2 = dmg == null ? "Loading…" : "Not on the Damage panel yet"; + tip.Append(dmg == null ? "" : "Nothing learned about it yet: it joins the Damage panel once fought.\n"); + } + else if (row.AssignedWid != 0) + { + string wname = row.AssignedWeapon.Length > 0 ? row.AssignedWeapon : "Weapon " + row.AssignedWid.ToString(CultureInfo.InvariantCulture); + _facts2 = "Weapon " + wname; + tip.Append("Weapon: ").Append(wname).Append(" (set for it).\n"); + } + else + { + _facts2 = row.BestWid != 0 ? "Weapon Auto: " + row.BestWeapon : "Weapon Auto"; + tip.Append("Weapon: Auto").Append(row.BestWid != 0 ? " (learned best: " + row.BestWeapon + ")" : "").Append(".\n"); + } + tip.Append("Gold = its own rule. Edit opens Monster Detail; the skull, the Damage panel."); + _factsTip = tip.ToString(); + } + + // ── Hub subscriptions ──────────────────────────────────────────────── + + private void SetSubscriptions(bool settings, bool monster) + { + if (settings != _subSettings) + { + _subSettings = settings; + if (settings) { UiSources.Settings.Subscribe(); UiSources.Settings.RequestRefresh(); } + else UiSources.Settings.Unsubscribe(); + } + if (monster != _subMonster) + { + _subMonster = monster; + if (monster) + { + UiSources.Damage.Subscribe(); + UiSources.MonsterRules.Subscribe(); + UiSources.Damage.RequestRefresh(); + UiSources.MonsterRules.RequestRefresh(); + } + else + { + UiSources.Damage.Unsubscribe(); + UiSources.MonsterRules.Unsubscribe(); + } + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs new file mode 100644 index 0000000..cc3946b --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs @@ -0,0 +1,139 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RynthAiFace.Drawers.cs +// The RynthAi dashboard's left-edge drawers that draw with the dashboard's +// own helpers (DashboardDrawers.cs has the tabs and the slide; the Ranges +// drawer is RangesSlideOut.cs): +// Loaded files meta state and bot activity, then the Profile / Nav / Loot +// / Meta pickers and the Loot Editor button. Until +// 2026-10-05 this block folded out inside the dashboard +// (the caret on the control row); a popped-out dashboard +// still shows it inline that way (no drawers popped out). +// Patrol this dungeon's hazard cells (mark / unmark / clear), the +// recorded hazards and the saved routes. Was the Patrol +// launcher's right-click popup; right-click now opens this +// drawer (popped out: still the popup). +// AC thread only (inside the dashboard's Draw). +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class RynthAiFace +{ + /// Meta state, bot activity and the four file pickers. + private sealed class FilesDrawer : DashboardDrawer + { + private readonly RynthAiFace _face; + public FilesDrawer(RynthAiFace face) => _face = face; + + public override string Key => "files"; + public override string Icon => PhosphorIcons.Files; + public override string Name => "loaded files"; + public override bool SavedOpen => RynthAiDashboardState.FilesOpen; + public override void SaveOpen(bool open) => RynthAiDashboardState.SetFilesOpen(open); + + public override string TabTooltip(bool right) + { + RynthAiView? v = _face._view; + return "Loaded files: the Profile, Nav, Loot and Meta pickers, meta state and bot activity.\n" + + "Profile: " + (v?.ProfileText ?? "Default") + "\nNav: " + (v?.NavText ?? "None") + + "\nLoot: " + (v?.LootText ?? "None") + "\nMeta: " + (v?.MetaText ?? "None") + + (right ? "\n\nClick to slide them out (to the right: there's no room on the left)." : "\n\nClick to slide them out."); + } + + private const float LineH = 15, SelRow = 16, SelGap = 3; + + public override float Width(float k) => 230 * k; + public override float Height(float k) => + (Pad + TitleH + 4 + 2 * LineH + 6) * k + 4 * SelRow + 3 * SelGap + Pad * k; + + public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) + { + float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.Files, "LOADED FILES", null, "Hide the loaded files"); + float x = origin.X + Pad * k, w = panelW - 2 * Pad * k; + RynthAiView? view = _face._view; + RynthAiSnapshot raw = _face._raw; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); + float lh = LineH * k; + + // Meta state / bot activity: label, then the value (amber) on the same line. + float labelW = MathF.Max(CalcWidth(f10, "Meta state:"), CalcWidth(f10, "Bot activity:")) + 6 * k; + InfoLine(dl, f10, x, y, w, lh, labelW, "Meta state:", view?.MetaStateText ?? "Default"); + y += lh; + InfoLine(dl, f10, x, y, w, lh, labelW, "Bot activity:", view?.BotActivityText ?? "Idle"); + y += lh + 6 * k; + + _face.Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, x, y, w, null); + y += SelRow + SelGap; + _face.Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, x, y, w, null); + y += SelRow + SelGap; + _face.Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, x, y, w, raw); + y += SelRow + SelGap; + _face.Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, x, y, w, null); + } + + private static void InfoLine(ImDrawListPtr dl, ImFontPtr f, float x, float y, float w, float lh, float labelW, string label, string value) + { + float ty = y + (lh - f.FontSize) * 0.5f; + dl.AddText(f, f.FontSize, new Vector2(x, ty), Mute, label); + dl.PushClipRect(new Vector2(x + labelW, y), new Vector2(x + w, y + lh), true); + dl.AddText(f, f.FontSize, new Vector2(x + labelW, ty), Amber, value); + dl.PopClipRect(); + } + } + + /// Hazard cells and saved routes (the Patrol launcher's right-click). + private sealed class PatrolDrawer : DashboardDrawer + { + private bool _sub; + + public override string Key => "patrol"; + public override string Icon => PhosphorIcons.Footprints; + public override string Name => "patrol drawer"; + public override bool SavedOpen => RynthAiDashboardState.PatrolOpen; + public override void SaveOpen(bool open) => RynthAiDashboardState.SetPatrolOpen(open); + + public override string TabTooltip(bool right) => right + ? "Patrol: this dungeon's hazard cells, recorded hazards and saved routes (also: right-click Patrol).\nClick to slide it out (to the right: there's no room on the left)." + : "Patrol: this dungeon's hazard cells, recorded hazards and saved routes (also: right-click Patrol).\nClick to slide it out."; + + public override float Width(float k) => 260 * k; + public override float Height(float k) => 320 * k; + + public override void Update(bool showing) + { + if (showing == _sub) return; + _sub = showing; + if (showing) { UiSources.Patrol.Subscribe(); UiSources.Patrol.RequestRefresh(); } + else UiSources.Patrol.Unsubscribe(); + } + + public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) + { + float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.Footprints, "PATROL & ROUTES", null, "Hide the patrol drawer"); + float x = origin.X + Pad * k; + // A scrolling child for the lists. A child window is clipped to its parent's clip rect, + // so the host's slide clip covers it too. + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + Vector2 size = new(panelW - 2 * Pad * k, MathF.Max(1, origin.Y + panelH - Pad * k - y)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + bool open = ImGuiNET.ImGui.BeginChild("##patrol_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (open) + { + PatrolInfo info = UiSources.Patrol.Current?.Value ?? new PatrolInfo(); + PatrolBody(info, withTitle: false); + } + } + finally { ImGuiNET.ImGui.EndChild(); } + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index 6107121..6e0bb4b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -5,9 +5,10 @@ // made compact with Phosphor icons, after DrakBot's dashboard. Top to bottom: // title row RYNTHAI DASHBOARD | target, vitals, lock, opacity -/+, // minimize, pop out -// header grid macro RUNNING/STOPPED, meta state, bot activity | pickers -// control row (ON/OFF when minimized) combat, buffing, nav, looting and -// meta toggles ... force rebuff +// header grid popped out only: meta state, bot activity | pickers (docked, +// they are the Loaded files drawer) +// control row macro start/stop, combat, buffing, nav, looting and meta +// toggles, bot activity ... force rebuff // launchers one row of icon buttons (names in tooltips; labels too // when the panel is wide enough) // footer FPS | version | uptime @@ -15,6 +16,11 @@ // toggled from the title row. Last on purpose, like DrakBot's // target row: what comes and goes with a fight never moves // the buttons above it. +// drawers tabs on the left edge (DashboardDrawers.cs), one open at a +// time, a window of their own beside the dashboard: Ranges +// (RangesSlideOut.cs), Loaded files and Patrol +// (RynthAiFace.Drawers.cs). Everything that slides out goes +// left; only the bars stay at the bottom (Tom 2026-10-05). // Minimized keeps the title row, the control row and the bars. The window's // minimum height is the content's, and toggling the bars or minimize fits the // window to the content. Data: UiSources.RynthAi (a RynthAiView with every @@ -33,7 +39,7 @@ using RynthCore.Engine.UI.Data; namespace RynthCore.Engine.ImGuiBackend.Panels; -internal sealed class RynthAiFace : IImGuiPanel +internal sealed partial class RynthAiFace : IImGuiPanel { public const string Title = "RynthAi"; @@ -67,6 +73,12 @@ internal sealed class RynthAiFace : IImGuiPanel private int _fpsShown = -1; private long _upShown = -1; private bool _patrolOpen; + // The drawers on the dashboard's left edge (their own window, placed against this one). + private readonly DashboardDrawers _drawers; + private readonly PatrolDrawer _patrol = new(); + // This frame's data, for the drawers. + private RynthAiView? _view; + private RynthAiSnapshot _raw = Empty; // Picker toggle: ImGui closes a popup on the press outside it, so remember // whether it was showing when the selector press began (a second click closes). private readonly int[] _pickerShownFrame = { -10, -10, -10, -10 }; @@ -75,11 +87,14 @@ internal sealed class RynthAiFace : IImGuiPanel // frame: the window's minimum height. _fit: resize the window to it once. private float _contentHeight; private bool _fit; - // Files folded/open flipped: size the window to that mode's own remembered size. - private bool _modeFlip, _modeFlipApply; - private Vector2 _winLogical; // the window's size in logical units, last frame (docked only) private const float GripRoom = 12; + public RynthAiFace() + { + // Tab order top to bottom; the first one saved open wins at load. + _drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol); + } + public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight : RynthAiDashboardState.Minimized ? 54 : 180); @@ -94,6 +109,7 @@ internal sealed class RynthAiFace : IImGuiPanel { UiSources.RynthAi.Unsubscribe(); if (_patrolOpen) { UiSources.Patrol.Unsubscribe(); _patrolOpen = false; } + _drawers.Detach(); } public void Draw() @@ -101,6 +117,9 @@ internal sealed class RynthAiFace : IImGuiPanel RynthAiView? view = UiSources.RynthAi.Current?.Value; RynthAiSnapshot raw = view?.Raw ?? Empty; bool minimized = RynthAiDashboardState.Minimized; + bool popped = ImGuiPopOuts.InPopOutFrame; + _view = view; + _raw = raw; uint boxBg = (C(0xFF0A121A) & 0x00FFFFFF) | ((uint)(view?.PanelAlpha ?? 242) << 24); Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); @@ -109,13 +128,14 @@ internal sealed class RynthAiFace : IImGuiPanel TitleRow(raw, x0, width, minimized); Gap(4); - // The Profile/Nav/Loot/Meta pickers only while expanded (the caret on the control row). - if (!minimized && RynthAiDashboardState.ShowFiles) + // Popped out (no drawers there): the Profile/Nav/Loot/Meta pickers inline while expanded + // (the caret on the control row). Docked they are the Loaded files drawer. + if (popped && !minimized && RynthAiDashboardState.FilesOpen) { HeaderGrid(view, raw, x0, width); Gap(4); } - ControlRow(view, raw, x0, width, minimized, boxBg); + ControlRow(view, raw, x0, width, minimized, popped, boxBg); if (!minimized) { Gap(4); @@ -126,6 +146,8 @@ internal sealed class RynthAiFace : IImGuiPanel Bars(view, raw, x0, width, boxBg); PatrolPopup(); MeasureAndFit(start.Y); + // Last: a window of its own, placed against this one's rect (hidden popped out). + _drawers.Draw(); } /// @@ -139,28 +161,6 @@ internal sealed class RynthAiFace : IImGuiPanel float place = ImGuiPanelHost.PlacementScale(); // + room for the host's resize grip, which is painted over the body's bottom-right corner. _contentHeight = MathF.Ceiling(px / place) + GripRoom; - if (!ImGuiPopOuts.InPopOutFrame) - { - if (_modeFlip) - { - // The flip happened mid-frame, so this frame measured the old layout: size next frame. - _modeFlip = false; - _modeFlipApply = true; - } - else if (_modeFlipApply) - { - _modeFlipApply = false; - _fit = false; - bool open = RynthAiDashboardState.ShowFiles; - bool known = RynthAiDashboardState.TryGetFilesModeSize(open, out float mw, out float mh); - float w = known ? mw : ImGuiNET.ImGui.GetWindowWidth() / place; - // Folded always shrinks to its one line; open comes back at the size it last had. - float h = open && known ? MathF.Max(mh, _contentHeight) : _contentHeight; - ImGuiPanelHost.RequestSize(Title, new Vector2(w, h)); - return; - } - _winLogical = new Vector2(ImGuiNET.ImGui.GetWindowWidth() / place, ImGuiNET.ImGui.GetWindowHeight() / place); - } if (_fit && !ImGuiPopOuts.InPopOutFrame) { _fit = false; @@ -272,11 +272,7 @@ internal sealed class RynthAiFace : IImGuiPanel const float foldW = 18f; Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, rx, ry, rw - foldW - 2, null); if (IconButton("##files_fold", new Vector2(rx + rw - foldW, ry), new Vector2(foldW, 16), PhosphorIcons.CaretUp, UiFont.Dash11, BtnFill, Mute, BtnBord, 2)) - { - RynthAiDashboardState.SetFilesModeSize(true, _winLogical.X, _winLogical.Y); - RynthAiDashboardState.SetShowFiles(false); - _modeFlip = true; - } + RynthAiDashboardState.SetFilesOpen(false); ImGuiNET.ImGui.SetItemTooltip("Fold the loaded files into one line"); ry += 16 + 3; Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, rx, ry, rw, null); @@ -394,7 +390,7 @@ internal sealed class RynthAiFace : IImGuiPanel private const float Square = 24, SquareStep = 27, RowPad = 3; - private void ControlRow(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, bool minimized, uint boxBg) + private void ControlRow(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, bool minimized, bool popped, uint boxBg) { var dl = ImGuiNET.ImGui.GetWindowDrawList(); float top = ImGuiNET.ImGui.GetCursorScreenPos().Y; @@ -423,19 +419,16 @@ internal sealed class RynthAiFace : IImGuiPanel Toggle("##t_meta", PhosphorIcons.Code, raw.MetaEnabled, 4, new Vector2(x, y), "Meta (the macro rules)"); x += SquareStep; - // The pickers fold out from a caret left of FR (expanded mode, while folded away). + // Popped out: the pickers fold out from a caret left of FR (expanded mode, while folded away). + // Docked they are the Loaded files drawer on the left edge. const float caretW = 16f; - bool caret = !minimized && !RynthAiDashboardState.ShowFiles; + bool caret = popped && !minimized && !RynthAiDashboardState.FilesOpen; float frX = x0 + width - 5 - Square; if (caret) { if (IconButton("##files_open", new Vector2(frX - 4 - caretW, y), new Vector2(caretW, Square), PhosphorIcons.CaretDown, UiFont.Dash11, BtnFill, Teal, BtnBord, 2)) - { - RynthAiDashboardState.SetFilesModeSize(false, _winLogical.X, _winLogical.Y); - RynthAiDashboardState.SetShowFiles(true); - _modeFlip = true; - } + RynthAiDashboardState.SetFilesOpen(true); ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") + "\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") + "\n\nClick to show the Profile, Nav, Loot and Meta pickers."); @@ -508,13 +501,20 @@ internal sealed class RynthAiFace : IImGuiPanel x += bw + LauncherGap; Launcher("##l_items", PhosphorIcons.Backpack, "Items", "Items", x, y, bw, labels, () => PanelRouter.Toggle("Items")); x += bw + LauncherGap; + bool popped = ImGuiPopOuts.InPopOutFrame; Launcher("##l_patrol", PhosphorIcons.Footprints, "Patrol", - "Patrol. Left-click: start dungeon patrol. Right-click: routes & recorded hazards.", x, y, bw, labels, - () => RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}")); + popped ? "Patrol. Left-click: start dungeon patrol. Right-click: routes & recorded hazards." + : "Patrol. Left-click: start dungeon patrol. Right-click: routes & recorded hazards (the Patrol drawer, left).", + x, y, bw, labels, () => RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}")); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { - ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1)); - ImGuiNET.ImGui.OpenPopup("##patrol"); + if (popped) + { + // Popped out there are no drawers: the popup, as before. + ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1)); + ImGuiNET.ImGui.OpenPopup("##patrol"); + } + else _drawers.Toggle(_patrol); } ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH)); @@ -682,7 +682,7 @@ internal sealed class RynthAiFace : IImGuiPanel dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? ""); } - // ── Patrol flyout (right-click Patrol) ──────────────────────────────── + // ── Patrol popup (right-click Patrol, popped out; docked it's the Patrol drawer) ── private void PatrolPopup() { @@ -704,11 +704,20 @@ internal sealed class RynthAiFace : IImGuiPanel var snap = UiSources.Patrol.Current; PatrolInfo info = snap?.Value ?? new PatrolInfo(); + PatrolBody(info, withTitle: true); + ImGuiNET.ImGui.EndPopup(); + } + /// The patrol lists at the cursor (the popup's body and the Patrol drawer's). + private static void PatrolBody(PatrolInfo info, bool withTitle) + { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash10)); - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), PhosphorIcons.Footprints + " PATROL & ROUTES"); - ImGuiNET.ImGui.PopFont(); + if (withTitle) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash11)); + ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), PatrolTitle); + ImGuiNET.ImGui.PopFont(); + } Section("THIS DUNGEON"); if (info.InDungeon) @@ -759,9 +768,9 @@ internal sealed class RynthAiFace : IImGuiPanel ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "• " + name); ImGuiNET.ImGui.PopFont(); - ImGuiNET.ImGui.EndPopup(); } + private const string PatrolTitle = PhosphorIcons.Footprints + " PATROL & ROUTES"; private const string MarkHazardLabel = PhosphorIcons.Warning + " Mark cell as hazard"; private static void Section(string text) diff --git a/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs b/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs index d03be2e..6a22324 100644 --- a/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs +++ b/src/RynthCore.Engine/ImGui/ScriptWindowReplay.cs @@ -356,6 +356,7 @@ internal static unsafe class ScriptWindowReplay int v = had ? local : op.I0; bool changed = ImGuiNative.igInputInt(str, &v, op.I1, op.I2, (ImGuiInputTextFlags)op.Flags) != 0; bool active = ImGuiNative.igIsItemActive() != 0; + if (active) ImGuiTextFocus.NoteActive("number box"); uint seq = 0; if (changed) { @@ -371,6 +372,7 @@ internal static unsafe class ScriptWindowReplay float v = had ? local : op.A; bool changed = ImGuiNative.igInputFloat(str, &v, op.B, op.C, pool + op.Str2, (ImGuiInputTextFlags)op.Flags) != 0; bool active = ImGuiNative.igIsItemActive() != 0; + if (active) ImGuiTextFocus.NoteActive("number box"); uint seq = 0; if (changed && float.IsFinite(v)) { @@ -584,6 +586,7 @@ internal static unsafe class ScriptWindowReplay edited = ImGuiNative.igIsItemEdited() != 0; } t.Active = ImGuiNative.igIsItemActive() != 0; + if (t.Active) ImGuiTextFocus.NoteActive("text box"); // keys stay out of AC from this frame on // EnterReturnsTrue: true = Enter pressed (submitted); edits still send the text, unsubmitted. // Otherwise true = edited. diff --git a/src/RynthCore.Engine/ImGui/UnderUiLayer.cs b/src/RynthCore.Engine/ImGui/UnderUiLayer.cs index d4336ff..f8a374f 100644 --- a/src/RynthCore.Engine/ImGui/UnderUiLayer.cs +++ b/src/RynthCore.Engine/ImGui/UnderUiLayer.cs @@ -14,23 +14,26 @@ // (no per-frame allocation once they have grown). // Commit at the end of EndScene the list just built becomes the one to // show during the NEXT frame; the other list is built into next. -// Present the next frame, Nav3DRenderInjector's DrawIndexedPrimitive hook -// spots AC's 3D->UI transition (ZENABLE 1->0) and calls -// PresentAtTransition, right after the Nav3D markers: the list goes -// through DX9Backend with a full state save/restore. -// Fallback a frame whose transition wasn't seen (portal space, a loading -// screen, the injector missing it) presents the list at EndScene -// instead, before the ImGui panels - the same place RenderNav3D's -// fallback draws. A list is presented at most once: no double draw. +// Present the next frame, right after the Nav3D markers, when AC's 2D UI +// pass begins (D3D9.AcUiPassHook -> Nav3DRenderInjector -> +// PresentAtUiPass; after all of AC's 3D, alpha-sorted foliage +// included). Without that hook, Nav3DRenderInjector's +// DrawIndexedPrimitive hook spots ZENABLE going 1->0 instead +// (PresentAtTransition; fires before the foliage outdoors). Either +// way the list goes through DX9Backend with a full state save/restore. +// Fallback a frame where neither fired (portal space, a loading screen, no +// AC UI this frame) presents the list at EndScene instead, before +// the ImGui panels - the same place RenderNav3D's fallback draws. +// A list is presented at most once: no double draw. // // The plates are therefore one frame behind the frame they were built in - // the same lag the Nav3D markers have, since both project with the camera // GameMatrixCapture took at the previous EndScene - on both paths, so a frame // that falls back doesn't jump. // -// Threads: AC's render thread only (EndScene and the DIP detour both run on -// it). Shutdown may run on the lifecycle thread while AC's thread is still in -// the DIP detour: it unpublishes the lists, waits for a present in flight to +// Threads: AC's render thread only (EndScene, the UI-pass detour and the DIP +// detour all run on it). Shutdown may run on the lifecycle thread while AC's +// thread is still in a detour: it unpublishes the lists, waits for a present in flight to // finish, then frees them. // ============================================================================ @@ -55,8 +58,8 @@ internal static unsafe class UnderUiLayer /// True after returned a list this frame. AC's render thread. public static bool IsBuilding => _building != null; - /// Frames presented at the transition / at the EndScene fallback (diagnostics). - private static long _atTransition, _atFallback; + /// Frames presented at AC's UI pass / at the transition / at the EndScene fallback (diagnostics). + private static long _atUiPass, _atTransition, _atFallback; /// /// Inside the main ImGui frame, main context current: a cleared draw list to @@ -96,8 +99,19 @@ internal static unsafe class UnderUiLayer } /// - /// EndScene, before the ImGui panels are submitted: when the transition wasn't - /// seen this frame, the overlays are drawn here instead. AC's render thread. + /// Called by AcUiPassHook (through Nav3DRenderInjector) when AC's 2D UI pass begins: + /// draws last frame's world overlays after all of AC's 3D (foliage included) and + /// under AC's UI. RenderDrawList sets its own full-screen viewport. AC's render thread. + /// + public static void PresentAtUiPass(IntPtr device) + { + if (Present(device)) _atUiPass++; + } + + /// + /// EndScene, before the ImGui panels are submitted: when neither the UI pass nor + /// the transition drew them this frame, the overlays are drawn here instead. + /// AC's render thread. /// public static void PresentFallback(IntPtr device) { @@ -137,7 +151,7 @@ internal static unsafe class UnderUiLayer /// One line for /rc imgui diag. public static string Describe() => - $"under-UI layer: presented at 3D->UI {_atTransition}, at EndScene (fallback) {_atFallback}"; + $"under-UI layer: presented at AC UI pass {_atUiPass}, at 3D->UI transition {_atTransition}, at EndScene (fallback) {_atFallback}"; /// /// Engine shutdown, before DX9Backend and the ImGui context go. Any thread: diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index 2b89283..cd35762 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -39,6 +39,10 @@ internal static unsafe class Win32Backend private const uint WM_SYSKEYDOWN = 0x0104; private const uint WM_SYSKEYUP = 0x0105; private const uint WM_CHAR = 0x0102; + private const uint WM_DEADCHAR = 0x0103; + private const uint WM_SYSCHAR = 0x0106; + private const uint WM_SYSDEADCHAR = 0x0107; + private const uint WM_UNICHAR = 0x0109; private const uint WM_SETCURSOR = 0x0020; private const uint WM_XBUTTONDOWN = 0x020B; private const uint WM_XBUTTONUP = 0x020C; @@ -713,7 +717,10 @@ internal static unsafe class Win32Backend SyncFocusState(io); bool insertDown = (GetAsyncKeyState(VK_INSERT) & 0x8000) != 0; - if (insertDown && !_insertWasDown) + // GetAsyncKeyState reads the physical key whatever window has focus: without + // the focus test, Insert (or Shift/Ctrl+Insert paste/copy) pressed in another + // client or app flipped this client's capture off unseen. + if (insertDown && !_insertWasDown && _hasFocus) { _uiCaptureEnabled = !_uiCaptureEnabled; RynthLog.Render($"Win32Backend: ImGui capture {(_uiCaptureEnabled ? "ENABLED" : "DISABLED")} (Insert)"); @@ -894,7 +901,7 @@ internal static unsafe class Win32Backend // ── Chat capture: consume all key input for the chat TextBox ──── // Game HWND keeps Win32 focus throughout; callbacks dispatch Text // updates to the panel on Avalonia's UI thread — no Avalonia focus needed. - if (ChatCaptureActive && IsKeyMessage(msg)) + if (ChatCaptureActive && (IsKeyMessage(msg) || IsExtraCharMessage(msg))) { if (msg == WM_CHAR) { @@ -975,7 +982,7 @@ internal static unsafe class Win32Backend // !ImGuiTextInputActive: the same rule for an ImGui text box. ExpireStaleCaptureFlags(); if (msg == WM_KEYDOWN && (int)wParam == VK_RETURN && !IsExtendedKey(lParam) && !ChatCaptureActive && !AvaloniaTextInputActive - && !ImGuiTextInputActive + && !ImGuiTextInputActive && !ImGuiPopOuts.HasTextFocus && RynthCore.Engine.Compatibility.ChatHooks.RynthChatOwnsChat) { if (OnChatCaptureActivated != null) @@ -1082,9 +1089,16 @@ internal static unsafe class Win32Backend // the game, except key-ups. A key held before the click must still get // its release, or AC's edge-triggered input stays latched (the "character // keeps moving" bug); a stray key-up reaching AC is harmless. - if (_wantCaptureKeyboard && IsKeyMessage(msg) && msg != WM_KEYUP && msg != WM_SYSKEYUP) + // A pop-out's text box counts the same (RouteInput above took its keys; the + // dead-key / Alt+key char messages it doesn't route are dropped here). + if ((_wantCaptureKeyboard || ImGuiPopOuts.HasTextFocus) && IsTextKeyMessage(msg)) return IntPtr.Zero; + // Field check: a key-down or char about to reach AC while a RynthCore text box + // was active in the last frame is a leak. One log line per typing burst. + if (IsTextKeyMessage(msg)) + NoteKeyReachingGame(msg, wParam); + // ── Background FPS unlock: lie to AC so it never idle-throttles ── if (msg == WM_ACTIVATEAPP && EndSceneHook.FpsLimitEnabled) return CallWindowProcA(_originalWndProc, hWnd, msg, (IntPtr)1, lParam); @@ -1486,6 +1500,19 @@ internal static unsafe class Win32Backend || msg == WM_CHAR; } + /// Char messages besides WM_CHAR: dead keys (accents) and Alt+key chars. + private static bool IsExtraCharMessage(uint msg) + { + return msg == WM_DEADCHAR || msg == WM_SYSCHAR || msg == WM_SYSDEADCHAR || msg == WM_UNICHAR; + } + + /// What a text box keeps from AC: key-downs and every char message. Never + /// key-ups (a key held before the edit began must still be released in AC). + private static bool IsTextKeyMessage(uint msg) + { + return msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN || msg == WM_CHAR || IsExtraCharMessage(msg); + } + private static bool IsFocusMessage(uint msg) { return msg == WM_SETFOCUS || msg == WM_KILLFOCUS || msg == WM_ACTIVATEAPP; @@ -1506,22 +1533,33 @@ internal static unsafe class Win32Backend /// /// Publishes what the ImGui frame just built wants: - /// is io.WantCaptureMouse, io.WantTextInput. + /// is io.WantCaptureMouse, a text box holds the + /// keyboard (io.WantTextInput, or a box that went active this frame). /// Keyboard capture follows text input only (not IsAnyItemActive), so holding /// a slider never swallows game keys. The Insert toggle (_uiCaptureEnabled) - /// and game focus gate both. + /// and game focus gate the mouse only. + /// + /// The keyboard is not gated (2026-10-04, keys typed into Chat Filters also + /// reached AC): ImGui is fed every key whatever the gate says (EnqueueInput), so a + /// box left open with the gate shut typed into the box AND the game. A key that + /// reaches the game WndProc means AC has keyboard focus anyway; Insert-off ends + /// the text edit instead (EngineFrameController), so keys go back to the game. /// public static void UpdateCaptureFlags(bool wantMouse, bool wantTextInput) { bool live = _uiCaptureEnabled && _hasFocus; _wantCaptureMouse = live && wantMouse; - _wantCaptureKeyboard = live && wantTextInput; - ImGuiTextInputActive = live && wantTextInput; + _wantCaptureKeyboard = wantTextInput; + ImGuiTextInputActive = wantTextInput; + if (wantTextInput) _keyboardExpiryLogged = false; Volatile.Write(ref _captureFlagsTicks, Stopwatch.GetTimestamp()); } + /// The Insert toggle: false while the player has released the UI. AC thread. + public static bool UiCaptureEnabled => _uiCaptureEnabled; + public static string DescribeCapture() => - $"wantMouse={_wantCaptureMouse} wantText={_wantCaptureKeyboard} insertToggle={_uiCaptureEnabled} focus={_hasFocus} heldButtons=0x{_heldMouseButtons:X} heldForGame={_heldButtonsBelongToGame}"; + $"wantMouse={_wantCaptureMouse} wantText={_wantCaptureKeyboard} popOutText={ImGuiPopOuts.TextFocusTitle ?? "-"} insertToggle={_uiCaptureEnabled} focus={_hasFocus} heldButtons=0x{_heldMouseButtons:X} heldForGame={_heldButtonsBelongToGame}"; /// No ImGui frame this tick: ImGui wants nothing. public static void ClearCaptureFlags() @@ -1531,14 +1569,92 @@ internal static unsafe class Win32Backend ImGuiTextInputActive = false; } - /// Clears capture flags that no ImGui frame has refreshed recently. + /// + /// Keyboard capture outlives a missing frame for this long, counted from the first + /// message after the last frame (see ExpireStaleCaptureFlags). Longer than the mouse's: + /// the FPS governor can run a client at 1 fps. + /// + private const int KeyboardStaleMs = 1500; + private static long _firstMessageSinceFrameTicks; + private static bool _keyboardExpiryLogged; + + /// + /// Clears capture flags that no ImGui frame has refreshed recently. + /// Mouse: 250 ms after the last frame, as before. Keyboard: only once messages have + /// kept arriving for KeyboardStaleMs with no frame. Counting from the frame let a + /// stall leak keys: AC's thread runs both the frames and this WndProc, so the keys + /// typed during a slow stretch (a long frame or pop-out readback, AC busy) are + /// dispatched together right after it, and every one of them found the flag "stale" + /// and went to AC while the box was still open. + /// private static void ExpireStaleCaptureFlags() { if (!_wantCaptureMouse && !_wantCaptureKeyboard && !ImGuiTextInputActive) return; - long age = Stopwatch.GetTimestamp() - Volatile.Read(ref _captureFlagsTicks); - if (age > Stopwatch.Frequency * CaptureStaleMs / 1000) - ClearCaptureFlags(); + long now = Stopwatch.GetTimestamp(); + long frame = Volatile.Read(ref _captureFlagsTicks); + if (_wantCaptureMouse && now - frame > Stopwatch.Frequency * CaptureStaleMs / 1000) + _wantCaptureMouse = false; + if (!_wantCaptureKeyboard && !ImGuiTextInputActive) + return; + if (_firstMessageSinceFrameTicks < frame) + { + _firstMessageSinceFrameTicks = now; // the first message since that frame + return; + } + long waited = now - _firstMessageSinceFrameTicks; + if (waited <= Stopwatch.Frequency * KeyboardStaleMs / 1000) + return; + _wantCaptureKeyboard = false; + ImGuiTextInputActive = false; + if (!_keyboardExpiryLogged) + { + _keyboardExpiryLogged = true; + RynthLog.UI($"[Input] keyboard capture released: no ImGui frame for {(now - frame) * 1000 / Stopwatch.Frequency} ms while a text box was open (owner: {ImGuiTextFocus.ActiveOwner ?? "unknown"})."); + } + } + + // ── Leak diagnostic ───────────────────────────────────────────────── + private const int LeakBurstGapMs = 2000; // keys closer together than this are one burst + private const int MaxLeakLines = 100; // per engine load + private static long _leakBurstEndTicks; + private static int _leakLines; + private static int _leakKeysInBurst; + + /// + /// A key-down or char is about to reach AC. If a RynthCore text box was active in the + /// last frame (ImGuiTextFocus, which reads the box itself, not the capture flags), that + /// is a keyboard leak: log it, once per typing burst. AC thread (WndProc). + /// + private static void NoteKeyReachingGame(uint msg, IntPtr wParam) + { + string? owner = ImGuiTextFocus.ActiveOwner; + if (owner == null) return; + long now = Stopwatch.GetTimestamp(); + bool newBurst = now > _leakBurstEndTicks; + _leakBurstEndTicks = now + Stopwatch.Frequency * LeakBurstGapMs / 1000; + if (!newBurst) + { + _leakKeysInBurst++; + return; + } + int previous = _leakKeysInBurst; + _leakKeysInBurst = 1; + if (_leakLines >= MaxLeakLines) return; + _leakLines++; + string name = msg switch + { + WM_KEYDOWN => "WM_KEYDOWN", + WM_SYSKEYDOWN => "WM_SYSKEYDOWN", + WM_CHAR => "WM_CHAR", + WM_SYSCHAR => "WM_SYSCHAR", + WM_DEADCHAR => "WM_DEADCHAR", + WM_SYSDEADCHAR => "WM_SYSDEADCHAR", + WM_UNICHAR => "WM_UNICHAR", + _ => $"0x{msg:X4}", + }; + RynthLog.UI($"[Input] key reached AC while an ImGui text box was active (owner: {owner}; {name} 0x{(long)wParam:X}" + + (previous > 1 ? $"; previous burst {previous} keys" : "") + $"; {DescribeCapture()})."); } /// diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index fe9faea..c07ac2c 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -771,6 +771,15 @@ internal struct RynthCoreAPI /// to capacity - 1; worldName may be null). Never the launcher's profile name. Any thread. /// Requires API v75+. public IntPtr GetServerInfoFn; + + /// v76: int CloseContainer(uint containerId): close an external container (a + /// corpse, a chest) as the client does when its window is closed: the 0x0195 + /// NoLongerViewingContents game action (CM_Inventory::Event_NoLongerViewingContents). Not an + /// inventory request: no busy count, no pending-request slot. The server answers with + /// CloseGroundContainer, which closes the window and raises StopViewingObjectContents. Runs on + /// AC's main thread (queued in the action ring from other threads, ahead of anything queued + /// after it). Returns 1 if sent or queued. Requires API v76+. + public IntPtr CloseContainerFn; } /// v72 bits. @@ -958,7 +967,7 @@ internal unsafe struct VendorTradeStatusNative /// Current API version. Bump when adding fields to RynthCoreAPI. internal static class PluginContractVersion { - public const uint Current = 75; + public const uint Current = 76; } internal static class ClientActionHookFlags @@ -1473,3 +1482,6 @@ internal unsafe delegate int GetCharacterTitlesCallbackDelegate(uint* ids, int m [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetServerInfoCallbackDelegate(byte* worldName, int capacity); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int CloseContainerCallbackDelegate(uint containerId); diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index e821153..bd92ad1 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; +using System.Threading; using RynthCore.Engine.Compatibility; using RynthCore.Engine.UI.ScriptWindows; using RynthCore.Engine.D3D9; @@ -257,6 +258,7 @@ internal static class PluginManager private static GetVTankStateCallbackDelegate? _getVTankStateCallback; // v74 private static GetCharacterTitlesCallbackDelegate? _getCharacterTitlesCallback; // v75 private static GetServerInfoCallbackDelegate? _getServerInfoCallback; // v75 + private static CloseContainerCallbackDelegate? _closeContainerCallback; // v76 private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback; private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback; private static VendorBuyCallbackDelegate? _vendorBuyCallback; @@ -602,7 +604,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatBarEnter threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatBarEnter threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } } @@ -975,7 +977,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatWindowText threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatWindowText threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } } @@ -1057,7 +1059,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Error($"PluginManager: {plugin.DisplayName} Tick threw {ex.GetType().Name}: {ex.Message} - disabled."); + RynthLog.Error($"PluginManager: {plugin.DisplayName} Tick threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled."); } finally { @@ -1072,6 +1074,20 @@ internal static class PluginManager D3D9.Nav3DRenderer.CommitFrame(); } + // The first PluginTraceLimit plugin exceptions also log their stack trace: "Tick threw + // IndexOutOfRangeException" alone left a crash undiagnosable (2026-10-04). Capped so a plugin + // failing in an event every tick can't flood the log. + private const int PluginTraceLimit = 20; + private static int _pluginTracesLogged; + + private static string PluginTrace(Exception ex) + { + if (string.IsNullOrEmpty(ex.StackTrace) || Interlocked.Increment(ref _pluginTracesLogged) > PluginTraceLimit) + return string.Empty; + string inner = ex.InnerException is { } ie ? $"\n inner {ie.GetType().Name}: {ie.Message}\n{ie.StackTrace}" : string.Empty; + return "\n" + ex.StackTrace + inner; + } + public static void RenderAll() { // Suppress plugin rendering while we are not in-world. The window between @@ -1098,7 +1114,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Error($"PluginManager: {plugin.DisplayName} Render threw {ex.GetType().Name}: {ex.Message} - disabled."); + RynthLog.Error($"PluginManager: {plugin.DisplayName} Render threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled."); } } } @@ -1325,7 +1341,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLogout threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLogout threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1410,7 +1426,7 @@ internal static class PluginManager { threw = true; plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatWindowText threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnChatWindowText threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1463,7 +1479,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnSelectedTargetChange threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnSelectedTargetChange threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1504,7 +1520,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnBusyCountIncremented threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnBusyCountIncremented threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1545,7 +1561,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnBusyCountDecremented threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnBusyCountDecremented threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1586,7 +1602,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCombatModeChange threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCombatModeChange threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1641,7 +1657,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnSmartBoxEvent threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnSmartBoxEvent threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1709,7 +1725,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateObject threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateObject threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1754,7 +1770,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnDeleteObject threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnDeleteObject threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1801,7 +1817,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCreateObject threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCreateObject threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1842,7 +1858,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateObjectInventory threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateObjectInventory threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1883,7 +1899,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnViewObjectContents threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnViewObjectContents threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1924,7 +1940,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnStopViewingObjectContents threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnStopViewingObjectContents threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -1965,7 +1981,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorOpen threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorOpen threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2006,7 +2022,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorClose threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorClose threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2057,7 +2073,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateHealth threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUpdateHealth threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2108,7 +2124,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCombatDamage threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnCombatDamage threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2162,7 +2178,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnKillNotification threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnKillNotification threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2209,7 +2225,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnEnchantmentAdded threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnEnchantmentAdded threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2250,7 +2266,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnEnchantmentRemoved threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnEnchantmentRemoved threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2342,7 +2358,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2420,7 +2436,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUIInitialized threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnUIInitialized threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2452,7 +2468,7 @@ internal static class PluginManager catch (Exception ex) { plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLoginComplete threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLoginComplete threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); } finally { @@ -2616,6 +2632,7 @@ internal static class PluginManager unsafe { _getVTankStateCallback ??= GetVTankStateAction; } unsafe { _getCharacterTitlesCallback ??= GetCharacterTitlesAction; } unsafe { _getServerInfoCallback ??= GetServerInfoAction; } + _closeContainerCallback ??= CloseContainerAction; _getVendorInfoCallback ??= GetVendorInfoAction; _getVendorItemsCallback ??= GetVendorItemsAction; _vendorBuyCallback ??= VendorBuyAction; @@ -2752,6 +2769,7 @@ internal static class PluginManager _api.GetVTankStateFn = Marshal.GetFunctionPointerForDelegate(_getVTankStateCallback); _api.GetCharacterTitlesFn = Marshal.GetFunctionPointerForDelegate(_getCharacterTitlesCallback); _api.GetServerInfoFn = Marshal.GetFunctionPointerForDelegate(_getServerInfoCallback); + _api.CloseContainerFn = Marshal.GetFunctionPointerForDelegate(_closeContainerCallback); _api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback); _api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback); _api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback); @@ -3729,7 +3747,7 @@ internal static class PluginManager } catch (Exception ex) { - RynthLog.Plugin($"PluginManager: UiSubmit threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: UiSubmit threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); return -1; } } @@ -3746,7 +3764,7 @@ internal static class PluginManager } catch (Exception ex) { - RynthLog.Plugin($"PluginManager: UiPollEvents threw {ex.GetType().Name}: {ex.Message}"); + RynthLog.Plugin($"PluginManager: UiPollEvents threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); return 0; } } @@ -3810,6 +3828,13 @@ internal static class PluginManager /// v72: see PluginContract.TradeCloseFn. private static int TradeCloseAction() => ToAbiBool(PlayerTrade.Close()); + /// v76: close an external container (see PluginContract.CloseContainerFn). + private static int CloseContainerAction(uint containerId) + { + Compatibility.AcActionTrace.Record("CloseContainer", containerId); + return ToAbiBool(ClientHelperHooks.CloseContainer(containerId)); + } + /// v70: wield into a chosen slot (see PluginContract.WieldItemFn). private static int WieldItemAction(uint objectId, uint equipMask) { diff --git a/src/RynthCore.Engine/UI/Data/LootEditData.cs b/src/RynthCore.Engine/UI/Data/LootEditData.cs index 2e162a0..7148ea5 100644 --- a/src/RynthCore.Engine/UI/Data/LootEditData.cs +++ b/src/RynthCore.Engine/UI/Data/LootEditData.cs @@ -43,6 +43,8 @@ internal sealed class LootEditStateDto public int Focus { get; set; } = -1; public List Files { get; set; } = new(); public List Rules { get; set; } = new(); + /// "Add to loot profile" popup's rule (added 2026-10); null from an older RynthAi. + public LootEditItemDraftDto? ItemDraft { get; set; } } internal sealed class LootEditFileDto @@ -119,6 +121,53 @@ internal sealed class LootEditCmd public string? Expect { get; set; } public bool Force { get; set; } public LootEditRuleDto? Rule { get; set; } + /// item_preview / item_add (added 2026-10). + public LootEditItemRequestDto? Item { get; set; } +} + +/// "Add to loot profile": the popup's ask (LootEditWire's LootEditItemRequest). +internal sealed class LootEditItemRequestDto +{ + /// 0 = the item selected in the game. + public uint ItemId { get; set; } + /// 0 name + class, 1 name only, 2 items like this. + public int Match { get; set; } + /// VTank action code; 0 = the item's default. + public int Action { get; set; } + /// -1 = default (one full stack). + public int KeepCount { get; set; } = -1; + public string RuleName { get; set; } = string.Empty; + /// True: the profile open in the Loot Editor; false: the one RynthAi loots with. + public bool ToOpenProfile { get; set; } + public int Seq { get; set; } +} + +/// The rule an item makes and what an add did (LootEditWire's LootEditItemDraft). +internal sealed class LootEditItemDraftDto +{ + public int Seq { get; set; } + public bool Ok { get; set; } + public string Error { get; set; } = string.Empty; + public uint ItemId { get; set; } + public string ItemName { get; set; } = string.Empty; + public string ClassName { get; set; } = string.Empty; + public bool Stackable { get; set; } + public string TargetPath { get; set; } = string.Empty; + public string TargetFile { get; set; } = string.Empty; + public bool TargetInUse { get; set; } + public string Format { get; set; } = string.Empty; + public int Match { get; set; } + public int Action { get; set; } + public int KeepCount { get; set; } + public string RuleName { get; set; } = string.Empty; + public string DefaultRuleName { get; set; } = string.Empty; + public List Preview { get; set; } = new(); + public int InsertAt { get; set; } = -1; + public int RuleCount { get; set; } + public string OrderNote { get; set; } = string.Empty; + public List Notes { get; set; } = new(); + public bool Added { get; set; } + public string Message { get; set; } = string.Empty; } internal sealed class LootEditVocabDto diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 682f67b..e8f4e4e 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -299,6 +299,29 @@ internal static class SettingsSchema "Follow/Nav Min Distance (metas: FollowNavMin, or VTank's NavCloseStopRange). Follow stops this " + "close to its leader, and the nav marker ring shows it. Dungeon doorways use at most 1 yd."; + // Also shown by the dashboard's Ranges slide-out (ImGui/Panels/RangesSlideOut.cs), which + // edits these same rows (found by label with Find). + public const string MonsterRangeTip = + "How far away a monster can be for the bot to attack it, in yards. Monsters inside it also\n" + + "count as \"in combat\" for buffing and the In Combat heal/stamina/mana thresholds."; + public const string RingRangeTip = + "Ring spells replace a monster's other shape when at least Min Ring Targets monsters are\n" + + "within this many yards (the monster's rule needs Ring on)."; + public const string ApproachRangeTip = + "VTank's Approach Distance, in yards (metas: ApproachRange or ApproachDistance). Saved with\n" + + "the profile for metas; RynthAi's own combat doesn't use it at the moment."; + public const string CorpseMaxTip = + "Corpses within this many yards are walked to and looted (Looting on). Further ones are left."; + + /// The first row with on any tab (null if none). Not for per-frame use. + public static SettingRow? Find(string label) + { + foreach (SettingsTab tab in Tabs) + foreach (SettingRow row in tab.Rows) + if (row.Label == label) return row; + return null; + } + public static readonly string[] AttackHeights = { "Low", "Medium", "High" }; public static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; @@ -559,13 +582,14 @@ internal static class SettingsSchema new("Ranges", new[] { Section("Standard Ranges (Yards)"), - Int("Monster Range", s => s.MonsterRange, (s, v) => s.MonsterRange = v, 1, 200, 1), - Int("Ring Range", s => s.RingRange, (s, v) => s.RingRange = v, 1, 50, 1), - Int("Approach Range", s => s.ApproachRange, (s, v) => s.ApproachRange = v, 1, 50, 1), + Int("Monster Range", s => s.MonsterRange, (s, v) => s.MonsterRange = v, 1, 200, 1, MonsterRangeTip), + Int("Ring Range", s => s.RingRange, (s, v) => s.RingRange = v, 1, 50, 1, RingRangeTip), + Int("Approach Range", s => s.ApproachRange, (s, v) => s.ApproachRange = v, 1, 50, 1, ApproachRangeTip), Spacer(), Section("Corpse Acquisition (Yards)"), - Double("Corpse Max (yd)", s => s.CorpseApproachRangeMax, (s, v) => s.CorpseApproachRangeMax = v, 0.5, 50.0, 0.5), - Double("Corpse Min (yd)", s => s.CorpseApproachRangeMin, (s, v) => s.CorpseApproachRangeMin = v, 0.5, 20.0, 0.5), + Double("Corpse Max (yd)", s => s.CorpseApproachRangeMax, (s, v) => s.CorpseApproachRangeMax = v, 0.5, 50.0, 0.5, CorpseMaxTip), + Double("Corpse Min (yd)", s => s.CorpseApproachRangeMin, (s, v) => s.CorpseApproachRangeMin = v, 0.5, 20.0, 0.5, + "How close to walk to a corpse before opening it, in yards (never more than Corpse Max)."), }), new("Navigation", new[] diff --git a/src/RynthCore.Engine/UI/RynthAiDashboardState.cs b/src/RynthCore.Engine/UI/RynthAiDashboardState.cs index 2503f9e..31f2692 100644 --- a/src/RynthCore.Engine/UI/RynthAiDashboardState.cs +++ b/src/RynthCore.Engine/UI/RynthAiDashboardState.cs @@ -4,9 +4,15 @@ // faces, and the ImGui face's target bar and player vitals toggles, // persisted to %AppData%\RynthCore\rynthai_avalonia.cache (line 1 // minimized|expanded, line 2 unused, line 3 target|notarget, line 4 -// vitals|novitals). Line 2 was the Monsters button's Simple/Advanced mode, -// retired 2026-10-01 with the basic Monsters panel: it is still written -// ("advanced") so the lines after it keep their places, and ignored on read. +// vitals|novitals; line 5 filesopen|nofiles, the Loaded files drawer; line 9 +// ranges|noranges, the Ranges drawer; line 10 patrol|nopatrol, the Patrol +// drawer: the left-edge drawers, ImGui/Panels/DashboardDrawers.cs). Line 2 +// was the Monsters button's Simple/Advanced mode, retired 2026-10-01 with the +// basic Monsters panel: it is still written ("advanced") so the lines after +// it keep their places, and ignored on read. Lines 7 and 8 (the dashboard's +// size with the files block folded / open) are unused since the files moved +// to a drawer (2026-10-05); kept as read so the lines after them keep their +// places. // // Deliberately NOT on RynthAiPanel: the engine loads this before // AvaloniaOverlay.Start(), and touching RynthAiPanel there runs its static @@ -26,11 +32,13 @@ internal static class RynthAiDashboardState private static volatile bool _minimized; private static volatile bool _showTargetBar = true; private static volatile bool _showVitals = true; - private static volatile bool _showFiles; // the Profile/Nav/Loot/Meta block (folded by default) + private static volatile bool _filesOpen; // the Loaded files drawer (Profile/Nav/Loot/Meta pickers); a popped-out + // dashboard shows the same block inline instead private static volatile bool _barCollapsed; // the RynthCore bar shows only its grip + expand - // The dashboard's size (logical units) with the files folded and open, so flipping - // between them brings back each one's own size. Zero = not set yet (fit to content). - private static float _foldedW, _foldedH, _openW, _openH; + private static volatile bool _rangesOpen; // the Ranges drawer beside the dashboard is open + private static volatile bool _patrolOpen; // the Patrol drawer beside the dashboard is open + // Lines 7 and 8, unused since 2026-10-05: written back as read. + private static string _line7 = "-", _line8 = "-"; private static bool _loaded; private static readonly object LoadSync = new(); @@ -77,16 +85,19 @@ internal static class RynthAiDashboardState UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); } - /// The dashboard shows the loaded-files block (Profile/Nav/Loot/Meta pickers, meta state). Any thread. - public static bool ShowFiles + /// + /// The loaded-files block (Profile/Nav/Loot/Meta pickers, meta state) is open: the Loaded files drawer + /// beside the dashboard, or the block inline on a popped-out dashboard. Any thread. + /// + public static bool FilesOpen { - get { EnsureLoaded(); return _showFiles; } + get { EnsureLoaded(); return _filesOpen; } } - public static void SetShowFiles(bool show) + public static void SetFilesOpen(bool open) { EnsureLoaded(); - _showFiles = show; + _filesOpen = open; UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); } @@ -103,37 +114,31 @@ internal static class RynthAiDashboardState UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); } - /// The size the dashboard had last time with the files folded (open). False if never set. - public static bool TryGetFilesModeSize(bool open, out float width, out float height) + /// The Ranges drawer (ImGui/Panels/RangesSlideOut.cs) is open beside the dashboard. Any thread. + public static bool RangesOpen { - EnsureLoaded(); - width = open ? _openW : _foldedW; - height = open ? _openH : _foldedH; - return width > 0 && height > 0; + get { EnsureLoaded(); return _rangesOpen; } } - public static void SetFilesModeSize(bool open, float width, float height) + public static void SetRangesOpen(bool open) { EnsureLoaded(); - if (width <= 0 || height <= 0) return; - if (open) { _openW = width; _openH = height; } else { _foldedW = width; _foldedH = height; } + _rangesOpen = open; UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); } - private static void ParseSize(string line, out float w, out float h) + /// The Patrol drawer (routes and recorded hazards) is open beside the dashboard. Any thread. + public static bool PatrolOpen { - w = h = 0; - string[] parts = line.Split(','); - if (parts.Length == 2 - && float.TryParse(parts[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float pw) - && float.TryParse(parts[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float ph)) - { - w = pw; h = ph; - } + get { EnsureLoaded(); return _patrolOpen; } } - private static string SizeText(float w, float h) => - w > 0 && h > 0 ? FormattableString.Invariant($"{w:0.#},{h:0.#}") : "-"; + public static void SetPatrolOpen(bool open) + { + EnsureLoaded(); + _patrolOpen = open; + UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); + } /// Reads the file if it hasn't been read yet. Engine init calls this so AC's thread never does. public static void EnsureLoaded() @@ -152,10 +157,12 @@ internal static class RynthAiDashboardState _showTargetBar = lines.Length < 3 || !lines[2].Trim().Equals("notarget", StringComparison.OrdinalIgnoreCase); _showVitals = lines.Length < 4 || !lines[3].Trim().Equals("novitals", StringComparison.OrdinalIgnoreCase); // "filesopen" only once the player opened them; the old "files" default reads as folded. - _showFiles = lines.Length >= 5 && lines[4].Trim().Equals("filesopen", StringComparison.OrdinalIgnoreCase); + _filesOpen = lines.Length >= 5 && lines[4].Trim().Equals("filesopen", StringComparison.OrdinalIgnoreCase); _barCollapsed = lines.Length >= 6 && lines[5].Trim().Equals("barcollapsed", StringComparison.OrdinalIgnoreCase); - if (lines.Length >= 7) ParseSize(lines[6].Trim(), out _foldedW, out _foldedH); - if (lines.Length >= 8) ParseSize(lines[7].Trim(), out _openW, out _openH); + if (lines.Length >= 7 && lines[6].Trim().Length > 0) _line7 = lines[6].Trim(); + if (lines.Length >= 8 && lines[7].Trim().Length > 0) _line8 = lines[7].Trim(); + _rangesOpen = lines.Length >= 9 && lines[8].Trim().Equals("ranges", StringComparison.OrdinalIgnoreCase); + _patrolOpen = lines.Length >= 10 && lines[9].Trim().Equals("patrol", StringComparison.OrdinalIgnoreCase); } } catch { /* corrupt cache: start expanded */ } @@ -171,8 +178,9 @@ internal static class RynthAiDashboardState Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllText(path, (_minimized ? "minimized" : "expanded") + "\nadvanced\n" + (_showTargetBar ? "target" : "notarget") + "\n" + (_showVitals ? "vitals" : "novitals") + "\n" - + (_showFiles ? "filesopen" : "nofiles") + "\n" + (_barCollapsed ? "barcollapsed" : "bar") + "\n" - + SizeText(_foldedW, _foldedH) + "\n" + SizeText(_openW, _openH) + "\n"); + + (_filesOpen ? "filesopen" : "nofiles") + "\n" + (_barCollapsed ? "barcollapsed" : "bar") + "\n" + + _line7 + "\n" + _line8 + "\n" + + (_rangesOpen ? "ranges" : "noranges") + "\n" + (_patrolOpen ? "patrol" : "nopatrol") + "\n"); } catch { /* best-effort */ } } diff --git a/src/RynthCore.Injector/LaunchCommand.cs b/src/RynthCore.Injector/LaunchCommand.cs index 47fa1fd..9039176 100644 --- a/src/RynthCore.Injector/LaunchCommand.cs +++ b/src/RynthCore.Injector/LaunchCommand.cs @@ -233,7 +233,25 @@ internal static class LaunchCommand string conn = ComputeConnectionString(server); string rodat = server.RodatEnabled ? "on" : "off"; string acct = account.AccountName ?? string.Empty; - string pwd = account.Password ?? string.Empty; + // Saved passwords are DPAPI-encrypted for the Windows user that saved them + // (LaunchAccountProfile.PasswordProtected). Decrypted here, at the moment of use; + // never logged. A plain "Password" means the launcher hasn't migrated the file yet. + string pwd; + if (!string.IsNullOrEmpty(account.Password)) + { + pwd = account.Password; + Log("WARNING: this account's password is still stored in plain text; open the launcher once to encrypt it."); + } + else if (string.IsNullOrEmpty(account.PasswordProtected)) + { + pwd = string.Empty; + } + else if (!RynthCore.App.AccountPasswordProtection.TryUnprotect(account.PasswordProtected, out pwd)) + { + Log($"The saved password for account '{acct}' can't be read on this Windows user (settings copied from another user or PC?). " + + "Password needs re-entering: edit the account in the launcher and type it again."); + return 2; + } string arguments = server.Emulator == EmulatorKind.Gdle ? string.Join(" ", @@ -400,7 +418,8 @@ internal static class LaunchCommand { public string Id { get; set; } = string.Empty; public string AccountName { get; set; } = string.Empty; - public string Password { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; // legacy plain text (pre-encryption files) + public string PasswordProtected { get; set; } = string.Empty; // DPAPI, base64 public string CharacterName { get; set; } = string.Empty; public string ServerId { get; set; } = string.Empty; public int OnLoginWaitMs { get; set; } diff --git a/src/RynthCore.Injector/RynthCore.Injector.csproj b/src/RynthCore.Injector/RynthCore.Injector.csproj index d094b0c..d52d682 100644 --- a/src/RynthCore.Injector/RynthCore.Injector.csproj +++ b/src/RynthCore.Injector/RynthCore.Injector.csproj @@ -19,6 +19,8 @@ + + diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index ee4dc55..726e4c2 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -151,6 +151,8 @@ public struct RynthCoreApiNative // v75: the character's titles and which server this is public IntPtr GetCharacterTitlesFn; // int GetCharacterTitles(uint* ids, int maxCount, uint* currentTitle) -> count, -1 unknown public IntPtr GetServerInfoFn; // int GetServerInfo(byte* worldName, int capacity) -> flags (bit0 Aelrynth, bit1 staging, bit2 world name known) + // v76: close an external container (corpse, chest) like the client's window close + public IntPtr CloseContainerFn; // int CloseContainer(uint containerId) -> 1 sent or queued } /// diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 7e17e2d..a772e66 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -136,6 +136,8 @@ public readonly unsafe struct RynthCoreHost public bool HasGetCharacterTitles => _api.Version >= 75 && _api.GetCharacterTitlesFn != IntPtr.Zero; /// v75: (which server this is). public bool HasGetServerInfo => _api.Version >= 75 && _api.GetServerInfoFn != IntPtr.Zero; + /// v76: (close a corpse or chest like the client's window close). + public bool HasCloseContainer => _api.Version >= 76 && _api.CloseContainerFn != IntPtr.Zero; public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero; public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero; public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero; @@ -1670,6 +1672,21 @@ public readonly unsafe struct RynthCoreHost ((delegate* unmanaged[Cdecl])_api.WieldItemFn)(objectId, equipMask) != 0; } + /// + /// v76: close an external container (a corpse, a chest) the way the client does when its + /// window is closed: the 0x0195 NoLongerViewingContents game action. It is not an inventory + /// request, so it adds nothing to the busy count and doesn't hold the client's one pending + /// item request. The server closes the container (if this player is viewing it) and answers + /// with CloseGroundContainer, so OnStopViewingObjectContents follows. Queued on AC's + /// main thread ahead of any action queued after it (a following UseObject goes out after + /// it, in the same frame). False when the engine predates v76. Check . + /// + public bool CloseContainer(uint containerId) + { + return HasCloseContainer && + ((delegate* unmanaged[Cdecl])_api.CloseContainerFn)(containerId) != 0; + } + /// /// v71: submits this plugin's complete set of script windows (display-list format 1, /// RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2). Call only from the plugin's own tick or diff --git a/tools/LauncherSettingsTests/LauncherSettingsTests.csproj b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj index c3dac72..c5fd01b 100644 --- a/tools/LauncherSettingsTests/LauncherSettingsTests.csproj +++ b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj @@ -5,7 +5,9 @@ (src\RynthCore.App\AppSettingsStore.cs and DecalAccountModes.cs, compiled in): the choice lives in decal-accounts.json, appsettings.json never holds a value an older launcher can't read, migration of a file that does, and what happens when an older launcher edits the - accounts. Works in a temp folder, never in %APPDATA%\RynthCore. + accounts; and saved account passwords (DPAPI-encrypted, AccountPasswordProtection.cs): round + trip, migration of a plain-text file, undecryptable blobs, nothing leaking into files or notes. + Works in a temp folder, never in %APPDATA%\RynthCore. Windows only (DPAPI). Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -23,7 +25,9 @@ + + diff --git a/tools/LauncherSettingsTests/Program.cs b/tools/LauncherSettingsTests/Program.cs index 9684b96..22c2735 100644 --- a/tools/LauncherSettingsTests/Program.cs +++ b/tools/LauncherSettingsTests/Program.cs @@ -148,6 +148,136 @@ internal static class Program Check(SidecarIds().SequenceEqual(new[] { "a", "b" }), "rewritten when the list changed"); CheckSharedFilesSafe(); }); + + // ── saved account passwords (DPAPI) ───────────────────────────────── + // Test-only passwords; nothing here touches the real settings file. + const string Pw = "t3st pw \"quoted\" ü"; + const string Pw2 = "Second-Test-Pw"; + + Scenario("password round trip", root, () => + { + AppSettings s = Sample(); + s.AccountProfiles[0].SetPassword(Pw); + AppSettingsStore.Save(s); + AppSettingsStore.Save(s); // .bak too + CheckNoPlainText(Pw); + CheckNoPlainText("t3st pw"); + Check(!RawAccount("a").ContainsKey("Password"), "no plain \"Password\" field written"); + Check(!string.IsNullOrEmpty((string?)RawAccount("a")["PasswordProtected"]), "PasswordProtected written"); + Check(OldLauncherCanRead(Main_), "the old launcher can still read the file"); + + AppSettings loaded = AppSettingsStore.Load(); + LaunchAccountProfile a = loaded.AccountProfiles.First(x => x.Id == "a"); + Check(a.TryGetPasswordForLaunch(out string got, out _) && got == Pw, "decrypts to the saved password"); + Check(!a.PasswordNeedsReentry && a.HasSavedPassword, "saved, readable"); + Check(AppSettingsStore.LastPasswordMigrationNote == null && AppSettingsStore.LastPasswordProblemNote == null, "no password notes"); + + var builder = new AcLaunchArgumentBuilder(); + LaunchServerProfile ace = Server(AcEmulatorKind.Ace), gdle = Server(AcEmulatorKind.Gdle); + Check(builder.BuildArguments(ace, a).Contains("-v \"t3st pw \\\"quoted\\\" ü\""), "ACE args carry the password (-v)"); + Check(builder.BuildArguments(gdle, a).Contains("-a \"A:t3st pw \\\"quoted\\\" ü\""), "GDLE args carry account:password (-a)"); + string preview = builder.BuildMaskedArguments(ace, a); + Check(!preview.Contains("t3st") && preview.Contains("-v " + AcLaunchArgumentBuilder.PasswordMask), "preview masked: " + preview); + LaunchAccountProfile noPw = loaded.AccountProfiles.First(x => x.Id == "b"); + Check(builder.BuildMaskedArguments(ace, noPw).Contains("-v \"\""), "preview of an account without a password"); + Check(builder.BuildArguments(ace, noPw).Contains("-v \"\""), "no saved password still launches as before (empty)"); + + LaunchAccountProfile copy = a.Clone(); + Check(copy.PasswordProtected == a.PasswordProtected, "Clone keeps the encrypted password"); + copy.SetPassword(Pw2); + Check(copy.TryGetPasswordForLaunch(out string got2, out _) && got2 == Pw2, "a new password replaces it"); + copy.ClearPassword(); + Check(!copy.HasSavedPassword && copy.TryGetPasswordForLaunch(out string none, out _) && none.Length == 0, "clear"); + Check(AccountPasswordProtection.Protect(Pw) != AccountPasswordProtection.Protect(Pw), "each encryption differs (salted blobs)"); + }); + + Scenario("migrate plain-text passwords from an older file", root, () => + { + string legacy = """ + { "EnginePath": "X", "AccountProfiles": [ + { "Id": "a", "AccountName": "A", "Password": "PLAIN-PW-ONE", "InjectionMode": "RynthCore" }, + { "Id": "b", "AccountName": "B", "Password": "PLAIN-PW-TWO", "InjectionMode": "RynthCore" }, + { "Id": "c", "AccountName": "C", "Password": "", "InjectionMode": "Decal" }, + { "Id": "d", "AccountName": "D" } ] } + """; + File.WriteAllText(Main_, legacy); + File.WriteAllText(Bak, legacy); + File.WriteAllText(Sidecar, """{ "DecalBridgeAccountIds": [ "b" ] }"""); + File.WriteAllText(Main_ + ".corrupt-20260101-000000", "{ old quarantined file"); + + AppSettings loaded = AppSettingsStore.Load(); + Check(AppSettingsStore.LastPasswordMigrationNote?.StartsWith("migrated 2 account password(s) to encrypted storage") == true, + "one note: " + AppSettingsStore.LastPasswordMigrationNote); + Check(AppSettingsStore.LastPasswordMigrationNote?.Contains("corrupt-") == true, "note points at the quarantined file"); + Check(PwOf(loaded, "a") == "PLAIN-PW-ONE" && PwOf(loaded, "b") == "PLAIN-PW-TWO", "passwords kept"); + Check(!loaded.AccountProfiles.First(x => x.Id == "c").HasSavedPassword, "empty plain password = none saved"); + Check(loaded.AccountProfiles.All(x => x.LegacyPlainPassword == null), "no plain text left on the profiles"); + CheckNoPlainText("PLAIN-PW-ONE"); + CheckNoPlainText("PLAIN-PW-TWO"); + Check(!File.ReadAllText(Main_).Contains("\"Password\"") && !File.ReadAllText(Bak).Contains("\"Password\""), + "no \"Password\" field in appsettings.json or .bak"); + Check(Mode(loaded, "b") == InjectionMode.DecalBridge && SidecarIds().SequenceEqual(new[] { "b" }), + "decal-accounts.json survives the migration save"); + Check(loaded.EnginePath == "X", "other settings kept"); + CheckNotesClean("PLAIN-PW-ONE", "PLAIN-PW-TWO"); + + AppSettings again = AppSettingsStore.Load(); + Check(AppSettingsStore.LastPasswordMigrationNote == null, "second load: nothing left to migrate"); + Check(PwOf(again, "a") == "PLAIN-PW-ONE", "second load decrypts"); + }); + + Scenario("undecryptable password (copied from another Windows user or PC)", root, () => + { + AppSettings s = Sample(); + s.AccountProfiles[0].SetPassword(Pw); + s.AccountProfiles[1].SetPassword(Pw2); + s.AccountProfiles[2].SetPassword(Pw2); + AppSettingsStore.Save(s); + // Blobs this user can't open: a valid one with a byte changed (DPAPI's integrity + // check fails as it does with another user's key), random bytes, and non-base64. + byte[] blob = Convert.FromBase64String(s.AccountProfiles[0].PasswordProtected); + blob[^5] ^= 0x5A; + SetRaw("a", Convert.ToBase64String(blob)); + SetRaw("b", Convert.ToBase64String(Guid.NewGuid().ToByteArray())); + SetRaw("c", "not base64 !!"); + + AppSettings loaded = AppSettingsStore.Load(); // must not throw + Check(AppSettingsStore.LastLoadDiagnostic == null, "the file is not taken for corrupt"); + Check(loaded.AccountProfiles.All(x => x.PasswordNeedsReentry), "all three marked \"password needs re-entering\""); + Check(AppSettingsStore.LastPasswordProblemNote?.Contains("3 saved account password(s)") == true && + AppSettingsStore.LastPasswordProblemNote.Contains("need re-entering"), + "problem note: " + AppSettingsStore.LastPasswordProblemNote); + + LaunchAccountProfile a = loaded.AccountProfiles.First(x => x.Id == "a"); + var builder = new AcLaunchArgumentBuilder(); + LaunchServerProfile ace = Server(AcEmulatorKind.Ace); + string? error = null; + try { builder.BuildArguments(ace, a); } + catch (InvalidOperationException ex) { error = ex.Message; } + Check(error?.Contains("needs re-entering") == true, "launch refused, not launched with an empty password: " + error); + Check(builder.BuildMaskedArguments(ace, a).Contains("needs re-entering"), "preview says so"); + Check(!a.TryGetPasswordForLaunch(out string empty, out _) && empty.Length == 0, "TryGetPasswordForLaunch false"); + + a.SetPassword(Pw2); // re-entered in the account editor + Check(!a.PasswordNeedsReentry && a.TryGetPasswordForLaunch(out string got, out _) && got == Pw2, "re-entering fixes it"); + AppSettingsStore.Save(loaded); + AppSettings reloaded = AppSettingsStore.Load(); + Check(!reloaded.AccountProfiles.First(x => x.Id == "a").PasswordNeedsReentry, "fixed after reload"); + Check(reloaded.AccountProfiles.First(x => x.Id == "b").PasswordNeedsReentry, "the others still need re-entering"); + CheckNoPlainText(Pw2); + }); + + Scenario("nothing leaks into notes, previews or other files", root, () => + { + File.WriteAllText(Main_, """{ "AccountProfiles": [ { "Id": "a", "AccountName": "A", "Password": "LEAK-CHECK-PW" } ] }"""); + AppSettings loaded = AppSettingsStore.Load(); + CheckNotesClean("LEAK-CHECK-PW"); + Check(!loaded.AccountProfiles[0].ToString().Contains("LEAK-CHECK-PW"), "display name has no password"); + Check(!new AcLaunchArgumentBuilder().BuildMaskedArguments(Server(AcEmulatorKind.Gdle), loaded.AccountProfiles[0]).Contains("LEAK-CHECK-PW"), + "GDLE preview masked"); + AppSettingsStore.Save(loaded); + CheckNoPlainText("LEAK-CHECK-PW"); + }); } finally { @@ -247,6 +377,45 @@ internal static class Program catch (JsonException) { return false; } } + private static LaunchServerProfile Server(AcEmulatorKind kind) => new() + { + Id = "s", Name = "Test", Host = "127.0.0.1", Port = 9000, Emulator = kind + }; + + private static string PwOf(AppSettings s, string id) => + s.AccountProfiles.First(a => a.Id == id).TryGetPasswordForLaunch(out string pw, out _) ? pw : ""; + + private static JsonObject RawAccount(string id) => + JsonNode.Parse(File.ReadAllText(Main_))!["AccountProfiles"]!.AsArray() + .First(a => (string?)a!["Id"] == id)!.AsObject(); + + private static void SetRaw(string id, string passwordProtected) + { + JsonNode root = JsonNode.Parse(File.ReadAllText(Main_))!; + foreach (JsonNode? a in root["AccountProfiles"]!.AsArray()) + if ((string?)a!["Id"] == id) a["PasswordProtected"] = passwordProtected; + File.WriteAllText(Main_, root.ToJsonString()); + } + + /// No file the store wrote in the test folder (settings, .bak, .tmp, decal-accounts) holds the password. + private static void CheckNoPlainText(string password) + { + foreach (string file in Directory.GetFiles(_dir)) + { + if (file.Contains(".corrupt-")) continue; // planted by the test itself + Check(!File.ReadAllText(file).Contains(password), $"{Path.GetFileName(file)} has no plain-text password"); + } + } + + /// The store's notes (what the launcher logs and shows in the activity panel) hold no password. + private static void CheckNotesClean(params string[] passwords) + { + foreach (string? note in new[] { AppSettingsStore.LastLoadDiagnostic, AppSettingsStore.LastMigrationNote, + AppSettingsStore.LastPasswordMigrationNote, AppSettingsStore.LastPasswordProblemNote }) + foreach (string pw in passwords) + Check(note == null || !note.Contains(pw), "note has no password: " + note); + } + private static void Check(bool ok, string what) { _checks++; diff --git a/tools/check_offthread_mutators.py b/tools/check_offthread_mutators.py index 37dc95a..8e95e8d 100644 --- a/tools/check_offthread_mutators.py +++ b/tools/check_offthread_mutators.py @@ -62,6 +62,8 @@ MUTATOR_DELEGATES = { "_eventStackableMerge", "_addTextToScroll", # CM_Inventory sends (inventory game actions): give, wield, drop (Inventory panel) "_eventGiveObjectRequest", "_eventGetAndWieldItem", "_eventDropItem", + # CM_Inventory::Event_NoLongerViewingContents (0x0195, close a corpse/chest; v76 CloseContainer) + "_eventNoLongerViewingContents", "_setAutoRun", "_turnToHeading", "_stopCompletely", "_setMotion", "_changeCombatMode", "_sendShopEvent", # VendorTrade: gmVendorUI::SendShopEvent (vendor buy/sell + busy count) diff --git a/tools/navdata/test_gen_locations.py b/tools/navdata/test_gen_locations.py deleted file mode 100644 index d0f0cc9..0000000 --- a/tools/navdata/test_gen_locations.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Offline tests for gen_locations.py: the coordinate conversion (checked with -towns whose map coordinates every player knows), the place classification, -and a small fake world through build(). No server needed. - -Run: python tools/navdata/test_gen_locations.py -""" - -import json -import os -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import gen_locations as g # noqa: E402 - - -class CoordinateTests(unittest.TestCase): - def check(self, cell, x, y, ns, ew): - got_ns, got_ew = g.cell_to_map(cell, x, y) - self.assertAlmostEqual(got_ns, ns, delta=0.051, msg='NS of %08X' % cell) - self.assertAlmostEqual(got_ew, ew, delta=0.051, msg='EW of %08X' % cell) - - def test_known_towns(self): - # The towns' drop points (the server's points_of_interest) against their - # well-known map coordinates. - self.check(0xA9B40019, 84.0, 7.1, 42.1, 33.6) # Holtburg 42.1N 33.6E - self.check(0x7D64000D, 31.9, 104.6, -21.5, -1.8) # Yaraq 21.5S 1.8W - self.check(0xDA55001D, 84.8, 99.0, -33.5, 72.8) # Shoushi 33.5S 72.8E - - def test_landblock_corners(self): - # The map's centre line: landblock 0x7F7F at x = y = 84 is 0.0, 0.0 ... 0x7F*8 = 1016, - # 1016 + 84/24 = 1019.5. - self.check(0x7F7F0001, 84.0, 84.0, 0.0, 0.0) - # The south-west corner of the world. - self.check(0x00000001, 0.0, 0.0, -101.95, -101.95) - - def test_format(self): - self.assertEqual(g.fmt_coord(42.08, 33.6), '42.1N, 33.6E') - self.assertEqual(g.fmt_coord(-21.51, -1.82), '21.5S, 1.8W') - - def test_outdoor_cell(self): - self.assertTrue(g.is_outdoor_cell(0xA9B40019)) - self.assertTrue(g.is_outdoor_cell(0x828E0000)) - self.assertFalse(g.is_outdoor_cell(0xA9B40100)) - self.assertFalse(g.is_outdoor_cell(0x016C01BC)) - - -class PlaceTests(unittest.TestCase): - def setUp(self): - # Landblock A9B4 has outdoor objects whose lowest stands at z 40. - self.world = g.World([(0xA9B4, 40.0, 60.0, 12)]) - - def test_places(self): - w = self.world - self.assertEqual(w.place(0xA9B40019, 42.0), 'outdoor') - self.assertEqual(w.place(0xA9B40105, 41.0), 'building') - self.assertEqual(w.place(0xA9B40105, 10.0), 'underground') - self.assertEqual(w.place(0x016C01BC, 0.0), 'dungeon') - self.assertTrue(w.is_surface(0xA9B40105, 41.0)) - self.assertFalse(w.is_surface(0x016C01BC, 0.0)) - - def test_dungeon_names(self): - self.assertEqual(g.dungeon_name('Portal to Mines of Despair'), 'Mines of Despair') - self.assertEqual(g.dungeon_name('Mines of Despair Portal'), 'Mines of Despair') - self.assertEqual(g.dungeon_name('Four Towers Entrance'), 'Four Towers') - self.assertEqual(g.dungeon_name('Portal'), 'Portal') - - def test_unescape(self): - self.assertIsNone(g.unescape('NULL')) - self.assertEqual(g.unescape('a\\tb\\nc\\\\d'), 'a\tb\nc\\d') - - -def fake_rows(): - """A tiny world: Holtburg and Yaraq with portals both ways, a dungeon under - a portal near Holtburg, a lifestone, a vendor, an NPC and a monster.""" - def t(*v): - return [None if x is None else str(x) for x in v] - return { - 'surface': [t(0xA9B4, 40.0, 60.0, 10), t(0x7D64, 5.0, 9.0, 10), t(0xA9B3, 30.0, 50.0, 3)], - 'poi': [t('Holtburg', 42820, 0xA9B40019, 84.0, 7.1, 42.0), t('Yaraq', 42824, 0x7D64000D, 31.9, 104.6, 6.0), - t('Marketplace', 23032, 0x016C01BC, 49.2, -31.9, 0.0)], - 'portals': [ - # guid wcid cell x y z name dcell dx dy dz minlvl maxlvl quest desc bitmask - t(1, 100, 0xA9B40020, 90.0, 20.0, 42.0, 'Yaraq Portal', 0x7D64000D, 31.9, 104.6, 6.0, None, None, None, None, 1), - t(2, 101, 0x7D640010, 40.0, 100.0, 6.0, 'Holtburg Portal', 0xA9B40019, 84.0, 7.1, 42.0, None, None, None, None, 1), - t(3, 102, 0xA9B30005, 30.0, 30.0, 31.0, 'Portal to Glimmering Cave', 0x01AB0100, 10.0, -10.0, 0.0, 12, None, None, - 'A cave.', 1), - t(4, 103, 0x01AB0105, 12.0, -12.0, 0.0, 'Holtburg', 0xA9B40019, 84.0, 7.1, 42.0, None, None, None, None, 1), - t(5, 104, 0xA9B40021, 95.0, 25.0, 42.0, 'Quest Portal', 0x7D64000D, 31.9, 104.6, 6.0, None, None, 'flag', None, 1), - t(6, 105, 0xA9B40022, 96.0, 26.0, 42.0, 'Sealed Portal', 0x7D64000D, 31.9, 104.6, 6.0, None, None, None, None, 0), - t(7, 100, 0xA9B40020, 90.0, 20.0, 42.0, 'Yaraq Portal', 0x7D64000D, 31.9, 104.6, 6.0, None, None, None, None, 1), - ], - 'places': [ - # guid wcid wtype cell x y z name template attackable - t(10, 509, 25, 0xA9B40018, 80.0, 10.0, 42.0, 'Life Stone', None, None), - t(11, 600, 12, 0xA9B40150, 70.0, 30.0, 44.0, 'Shopkeeper Renald', 'Shopkeeper', None), - t(12, 601, 10, 0xA9B4001A, 60.0, 40.0, 42.0, 'Town Crier', 'Herald', 0), - t(13, 602, 10, 0xA9B4001B, 61.0, 41.0, 42.0, 'Drudge Skulker', None, 1), - t(14, 603, 10, 0xA9B4001C, 62.0, 42.0, 42.0, 'Invisible Event Controller', None, 0), - t(15, 604, 10, 0x01AB0110, 20.0, -20.0, 0.0, 'Cave Hermit', None, 0), - ], - 'recalls': [ - t(2041, 'Aerlinthe Recall', 0xBAE8001D, 84.0, 105.0, 26.0), - t(4907, 'Celestial Hand Stronghold Recall', 0x016002A5, 80.0, -160.0, 0.0), - t(4213, 'Colosseum Recall', 0x00AF0118, 40.0, -13.2, 0.0), - ], - } - - -class BuildTests(unittest.TestCase): - def setUp(self): - self.locs, self.recalls, self.route = g.build(fake_rows()) - self.by_name = {} - for l in self.locs: - self.by_name.setdefault((l['type'], l['name']), l) - - def test_towns(self): - h = self.by_name[('Town', 'Holtburg')] - self.assertAlmostEqual(h['ns'], 42.08, delta=0.01) - self.assertAlmostEqual(h['ew'], 33.6, delta=0.01) - m = self.by_name[('Landmark', 'Marketplace')] - self.assertNotIn('ns', m) # a dungeon: no map position - - def test_portals_and_dungeons(self): - p = self.by_name[('Portal', 'Yaraq Portal')] - self.assertEqual(p['dest']['place'], 'outdoor') - self.assertEqual(sum(1 for l in self.locs if l['name'] == 'Yaraq Portal'), 1) # duplicate dropped - d = self.by_name[('Dungeon', 'Glimmering Cave')] - self.assertEqual(d['lb'], '01AB') - self.assertEqual(d['minLevel'], 12) - cave = self.by_name[('Portal', 'Portal to Glimmering Cave')] - self.assertEqual(cave['dest']['name'], 'Glimmering Cave') - exit_ = self.by_name[('Portal', 'Holtburg')] - self.assertNotIn('ns', exit_) - self.assertIn('Glimmering Cave', exit_['desc']) - self.assertTrue(self.by_name[('Portal', 'Quest Portal')]['quest']) - self.assertTrue(self.by_name[('Portal', 'Sealed Portal')]['closed']) - - def test_places(self): - self.assertIn(('Lifestone', 'Life Stone'), self.by_name) - v = self.by_name[('Vendor', 'Shopkeeper Renald')] - self.assertEqual(v['place'], 'building') - self.assertNotIn(('NPC', 'Drudge Skulker'), self.by_name) # attackable: a monster - self.assertNotIn(('NPC', 'Invisible Event Controller'), self.by_name) # not a person - self.assertEqual(self.by_name[('NPC', 'Town Crier')]['desc'], 'Herald.') - self.assertIn('Glimmering Cave', self.by_name[('NPC', 'Cave Hermit')]['desc']) - - def test_recalls(self): - spells = {r['spell']: r for r in self.recalls} - self.assertIn(2041, spells) - self.assertNotIn(4907, spells) # placeholder destination - self.assertEqual(spells[4213]['place'], 'dungeon') - self.assertAlmostEqual(spells[2041]['ns'], 84.09, delta=0.01) - - def test_routing_list(self): - names = [r[4] for r in self.route] - # Surface to surface only; no quest-locked, closed, dungeon or duplicate portals. - self.assertEqual(sorted(names), ['Holtburg Portal', 'Yaraq Portal']) - y = [r for r in self.route if r[4] == 'Yaraq Portal'][0] - self.assertAlmostEqual(y[2], -21.51, delta=0.01) - self.assertAlmostEqual(y[3], -1.82, delta=0.01) - - def test_outputs(self): - import tempfile - with tempfile.TemporaryDirectory() as d: - g.write_outputs(d, self.locs, self.recalls, self.route, 'test') - doc = json.load(open(os.path.join(d, 'locations.json'), encoding='utf-8')) - self.assertEqual(doc['version'], 1) - self.assertEqual(len(doc['locations']), len(self.locs)) - lines = open(os.path.join(d, 'portals.tsv'), encoding='utf-8').read().splitlines() - self.assertEqual(len(lines), 2) - self.assertEqual(len(lines[0].split('\t')), 5) - - -class GeneratedDataTests(unittest.TestCase): - """Checks the committed output (tools/navdata/NavData), when it is there.""" - PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'NavData', 'locations.json') - - def test_known_towns_in_data(self): - if not os.path.exists(self.PATH): - self.skipTest('no generated locations.json') - doc = json.load(open(self.PATH, encoding='utf-8')) - towns = {l['name']: l for l in doc['locations'] if l['type'] == 'Town'} - for name, ns, ew in (('Holtburg', 42.1, 33.6), ('Yaraq', -21.5, -1.8), ('Shoushi', -33.5, 72.8)): - self.assertIn(name, towns) - self.assertAlmostEqual(towns[name]['ns'], ns, delta=0.1, msg=name) - self.assertAlmostEqual(towns[name]['ew'], ew, delta=0.1, msg=name) - - -if __name__ == '__main__': - unittest.main(verbosity=1) diff --git a/tools/pe_pattern.py b/tools/pe_pattern.py index f513c0d..75583cb 100644 --- a/tools/pe_pattern.py +++ b/tools/pe_pattern.py @@ -303,7 +303,10 @@ def _compat_dir(): def parse_engine_patterns(): srcs = {} - for f in glob.glob(os.path.join(_compat_dir(), "*.cs")): + # Compatibility/ holds nearly every hook; D3D9/AcUiPassHook.cs (RenderUI::RenderObjects) + # is the one function hook that lives with the render code. + engine_dir = os.path.dirname(_compat_dir()) + for f in glob.glob(os.path.join(_compat_dir(), "*.cs")) + glob.glob(os.path.join(engine_dir, "D3D9", "*.cs")): with open(f, "r", encoding="utf-8") as fh: # Strip // line comments so commas / brackets inside an inline disasm # comment (e.g. `0x84, 0xC0 // MOV AL,[ESP+4]; TEST AL,AL`) can't corrupt