From 8bb1c3aa23717ef78e8d9b007da2e9ddf94b33c5 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Thu, 15 Oct 2026 09:27:14 -0400 Subject: [PATCH 1/6] Snapshot for release 2026.10.15.1 (internal 4b7e805) --- installer/Publish-Update.ps1 | 71 +- src/RynthCore.App.Avalonia/MainWindow.axaml | 11 + .../MainWindow.axaml.cs | 95 ++ .../RynthUpdater.MapPacks.cs | 146 +++ .../RynthUpdater.NavData.cs | 4 +- src/RynthCore.App.Avalonia/RynthUpdater.cs | 6 + src/RynthCore.App/AppSettings.cs | 18 +- .../Compatibility/LauncherSettings.cs | 3 +- .../Compatibility/RynthCoreChatCommands.cs | 65 +- src/RynthCore.Engine/EntryPoint.cs | 4 + src/RynthCore.Engine/ImGui/CodeEditor.cs | 10 +- src/RynthCore.Engine/ImGui/DX9Backend.cs | 33 + .../ImGui/EngineFrameController.cs | 5 + src/RynthCore.Engine/ImGui/ImGuiBar.cs | 287 ++++-- src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs | 2 + .../ImGui/MonsterHud/MonsterHud.cs | 5 +- .../ImGui/MonsterHud/MonsterHudSettingsUi.cs | 8 +- .../ImGui/MonsterHud/PlayerPlate.cs | 8 +- src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 9 +- .../ImGui/Panels/ChatFiltersFace.cs | 4 +- .../ImGui/Panels/DamageDetailFace.cs | 11 +- .../ImGui/Panels/DamageFace.cs | 38 +- .../ImGui/Panels/DashboardDrawers.cs | 325 ++++--- .../ImGui/Panels/DungeonMapFace.cs | 11 +- src/RynthCore.Engine/ImGui/Panels/FaceKit.cs | 16 +- .../ImGui/Panels/HotkeysSettingsUi.cs | 14 +- .../ImGui/Panels/InventoryFace.cs | 8 +- src/RynthCore.Engine/ImGui/Panels/LuaFace.cs | 2 +- .../ImGui/Panels/MapProjection.cs | 78 ++ .../ImGui/Panels/MetaFace.Editor.cs | 2 +- .../ImGui/Panels/MetaFace.List.cs | 9 +- .../ImGui/Panels/MetaFace.Schedule.cs | 14 +- src/RynthCore.Engine/ImGui/Panels/MetaFace.cs | 23 +- .../ImGui/Panels/MiniMapFace.cs | 70 ++ src/RynthCore.Engine/ImGui/Panels/P1Faces.cs | 2 +- .../ImGui/Panels/QuickSettingsDrawer.cs | 200 +++++ .../ImGui/Panels/RadarFace.cs | 9 +- .../ImGui/Panels/RangesSlideOut.cs | 19 +- .../ImGui/Panels/RynthAiFace.Drawers.cs | 64 +- .../ImGui/Panels/RynthAiFace.cs | 221 +++-- .../ImGui/Panels/RynthNavArrowFace.cs | 5 +- .../ImGui/Panels/RynthNavFace.cs | 13 +- .../ImGui/Panels/SettingsFace.cs | 427 +-------- .../ImGui/Panels/SettingsRows.cs | 542 ++++++++++++ .../ImGui/Panels/SkillsFace.cs | 4 +- .../ImGui/Panels/WorldMapFace.cs | 264 ++++++ .../ImGui/Panels/WorldMapMaps.cs | 110 +++ .../ImGui/Panels/WorldMapSettings.cs | 121 +++ .../ImGui/Panels/WorldMapView.cs | 833 ++++++++++++++++++ src/RynthCore.Engine/ImGui/PhosphorIcons.cs | 5 +- src/RynthCore.Engine/ImGui/RynthTheme.cs | 419 ++++++++- .../ImGui/VideoPatchBanner.cs | 6 +- src/RynthCore.Engine/ImGui/WorldMapTiles.cs | 318 +++++++ src/RynthCore.Engine/ImGui/WorldMapVectors.cs | 82 ++ src/RynthCore.Engine/UI/BarLayout.cs | 109 +++ .../UI/Data/CharactersData.cs | 11 + src/RynthCore.Engine/UI/Data/RynthNavData.cs | 19 + src/RynthCore.Engine/UI/Data/SettingsData.cs | 59 +- src/RynthCore.Engine/UI/PanelStateStore.cs | 34 +- src/RynthCore.Engine/UI/QuickSettings.cs | 167 ++++ .../UI/RynthAiDashboardState.cs | 47 +- tools/BarLayoutTests/BarLayoutTests.csproj | 23 + tools/BarLayoutTests/Program.cs | 114 +++ tools/NavDataUpdateTests/MapPackTests.cs | 139 +++ .../NavDataUpdateTests.csproj | 1 + tools/NavDataUpdateTests/Program.cs | 16 +- tools/WorldMapTilesTests/DxtTileTests.cs | 163 ++++ tools/WorldMapTilesTests/Program.cs | 210 +++++ tools/WorldMapTilesTests/ProjectionTests.cs | 96 ++ tools/WorldMapTilesTests/VectorTests.cs | 71 ++ .../WorldMapTilesTests.csproj | 25 + 71 files changed, 5546 insertions(+), 837 deletions(-) create mode 100644 src/RynthCore.App.Avalonia/RynthUpdater.MapPacks.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/MapProjection.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/MiniMapFace.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/WorldMapFace.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/WorldMapMaps.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/WorldMapSettings.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/WorldMapView.cs create mode 100644 src/RynthCore.Engine/ImGui/WorldMapTiles.cs create mode 100644 src/RynthCore.Engine/ImGui/WorldMapVectors.cs create mode 100644 src/RynthCore.Engine/UI/BarLayout.cs create mode 100644 src/RynthCore.Engine/UI/QuickSettings.cs create mode 100644 tools/BarLayoutTests/BarLayoutTests.csproj create mode 100644 tools/BarLayoutTests/Program.cs create mode 100644 tools/NavDataUpdateTests/MapPackTests.cs create mode 100644 tools/WorldMapTilesTests/DxtTileTests.cs create mode 100644 tools/WorldMapTilesTests/Program.cs create mode 100644 tools/WorldMapTilesTests/ProjectionTests.cs create mode 100644 tools/WorldMapTilesTests/VectorTests.cs create mode 100644 tools/WorldMapTilesTests/WorldMapTilesTests.csproj diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index e124ea3..90a463d 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -43,7 +43,12 @@ param( # portals.tsv and locations.json from this folder. Only re-uploaded when the set changes # (its id is a hash of every file); otherwise the live feed's entry is carried over. [string]$NavDataDir = "C:\Games\RynthCore\NavData", - [switch]$SkipNavData # leave navdata out of this feed (launchers then keep what they have) + [switch]$SkipNavData, # leave navdata out of this feed (launchers then keep what they have) + # The World Map's optional sizes (RynthNav.Baker --map-world): worldmap-hd.rmap, worldmap-ultra.rmap and worldmap-p32.rmap from this + # folder are offered by the launcher as separate downloads ("mappacks" in the feed). Each is uploaded once under + # mappacks// and kept by later releases. Without this folder the live feed's packs are + # carried over unchanged, so a release that doesn't touch the maps never drops them. + [string]$MapPacksDir = "" ) $ErrorActionPreference = "Stop" @@ -202,12 +207,19 @@ Compress-Archive -Path "$zipRoot\*" -DestinationPath "$rel\RynthSuite-Plugins.zi $navData = $null $navZip = $null if (-not $SkipNavData) { - Step "RynthNav data (tiles, route graph, portals, Atlas, Town Network) from $NavDataDir" - $navFiles = @(Get-ChildItem $NavDataDir -File | Where-Object { $_.Name -match '^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$' } | Sort-Object Name) + Step "RynthNav data (tiles, route graph, portals, Atlas, Town Network, World Map) from $NavDataDir" + $navFiles = @(Get-ChildItem $NavDataDir -File | Where-Object { $_.Name -match '^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json|worldmap\.rmap|worldmap\.vec)$' } | Sort-Object Name) $tileCount = @($navFiles | Where-Object { $_.Extension -eq ".tile" }).Count if ($tileCount -eq 0) { throw "$NavDataDir has no tiles. Pass -NavDataDir, or -SkipNavData to publish without them." } # The long-range route graph (RynthNav.Baker --graph) must come from these very tiles: the # plugin ignores a graph whose tiles don't match (long gotos then walk the straight line). + # The World Map's picture (RynthNav.Baker --map --map-tiles from the dats; the terrain doesn't change between releases). + if (-not ($navFiles | Where-Object { $_.Name -eq "worldmap.rmap" })) { + Write-Warning "No worldmap.rmap in ${NavDataDir}: the World Map has no picture. Run: RynthNav.Baker --map --map-tiles --out and copy worldmap.rmap there." + } + if (-not ($navFiles | Where-Object { $_.Name -eq "worldmap.vec" })) { + Write-Warning "No worldmap.vec in ${NavDataDir}: the World Map has no buildings or roads. Run: RynthNav.Baker --map-vectors --out and copy worldmap.vec there." + } $graph = $navFiles | Where-Object { $_.Name -eq "navgraph.bin" } $newestTile = ($navFiles | Where-Object { $_.Extension -eq ".tile" } | Measure-Object LastWriteTimeUtc -Maximum).Maximum if (-not $graph) { Write-Warning "No navgraph.bin in ${NavDataDir}: long gotos will walk the straight line. Run: RynthNav.Baker --graph $NavDataDir" } @@ -255,6 +267,41 @@ if (-not $SkipNavData) { } } +# ── World map packs (optional sizes) ───────────────────────────────────────── +# key -> what the launcher shows; the file names are what RynthNav.Baker --map-world writes (extreme = --ppc 32, whose default name is worldmap-p32.rmap). +$mapPackDefs = [ordered]@{ + hd = @{ name = "HD"; file = "worldmap-hd.rmap"; description = "Sharper ground, roads, rooftops and trees." } + ultra = @{ name = "Ultra"; file = "worldmap-ultra.rmap"; description = "Very sharp: individual roofs and trees. Large download." } + extreme = @{ name = "Extreme"; file = "worldmap-p32.rmap"; description = "Every roof, road and tree in detail. Very large download (about 1 GB)." } + # (The 64 px "Maximum" map, worldmap-p64.rmap, is deliberately NOT here: it is for private use only and is never offered to players.) +} +$mapPacks = @() +$mapPackUploads = @() # files to put on the server: @{ Path; Remote; Sha } +if ($MapPacksDir) { + Step "World map packs from $MapPacksDir" + foreach ($key in $mapPackDefs.Keys) { + $def = $mapPackDefs[$key] + $f = Join-Path $MapPacksDir $def.file + if (-not (Test-Path $f)) { Write-Host " $($def.name): no $($def.file) here, not offered by this feed"; continue } + $sha = Sha256 $f + $id = $sha.Substring(0, 16) + $mapPacks += [ordered]@{ + key = $key; name = $def.name; file = $def.file + url = "$BaseUrl/mappacks/$id/$($def.file)" + size = [long](Get-Item $f).Length; sha256 = $sha; release = $release; description = $def.description + } + $mapPackUploads += @{ Path = $f; Remote = "mappacks/$id/$($def.file)"; Sha = $sha } + Write-Host (" {0}: {1:N1} MB, {2}" -f $def.name, ((Get-Item $f).Length / 1MB), $id) + } +} elseif ($liveManifest -and $liveManifest.mappacks) { + # Carried over from the live feed (ConvertFrom-Json): force the whole numbers back to integers. + $mapPacks = @($liveManifest.mappacks | ForEach-Object { + [ordered]@{ key = [string]$_.key; name = [string]$_.name; file = [string]$_.file; url = [string]$_.url; size = [long]$_.size + sha256 = [string]$_.sha256; release = [long]$_.release; description = [string]$_.description } + }) + Write-Host " map packs: $($mapPacks.Count) carried over from the live feed" +} + # ── 3. Manifest + signature ────────────────────────────────────────────────── Step "Writing and signing the manifest" $setup = Get-Item "$rel\RynthCore-Setup.exe" @@ -327,6 +374,7 @@ $manifest = [ordered]@{ plugins = @($plugins) } if ($navData) { $manifest.navdata = $navData } +if ($mapPacks.Count -gt 0) { $manifest.mappacks = @($mapPacks) } Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM & (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath "$rel\update.payload.json" -OutPath "$rel\update.json" -KeyDir $KeyDir if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" } @@ -362,6 +410,23 @@ if ($navZip) { $navSum = " RynthNav-NavData.zip" } +# World map packs: content-addressed (the folder is the start of the file's SHA-256), so a pack already on the server +# is not sent again and an old release's URL keeps working. +foreach ($up in $mapPackUploads) { + $remoteFile = "$RemoteDir/$($up.Remote)" + ssh $SshHost "test -f '$remoteFile'" + if ($LASTEXITCODE -eq 0) { Write-Host " $($up.Remote): already on the server"; continue } + ssh $SshHost "mkdir -p '$(Split-Path $remoteFile -Parent | ForEach-Object { $_ -replace '\\','/' })'" + if ($LASTEXITCODE -ne 0) { throw "ssh mkdir for $($up.Remote) failed" } + scp -q $up.Path "${SshHost}:$remoteFile.part" + if ($LASTEXITCODE -ne 0) { throw "scp of $($up.Remote) failed" } + $got = (ssh $SshHost "sha256sum '$remoteFile.part'") -split '\s+' | Select-Object -First 1 + if ($got -ne $up.Sha) { ssh $SshHost "rm -f '$remoteFile.part'"; throw "Hash mismatch on the server for $($up.Remote) — feed NOT published" } + ssh $SshHost "mv -f '$remoteFile.part' '$remoteFile'" + if ($LASTEXITCODE -ne 0) { throw "Publishing $($up.Remote) failed" } + Write-Host " $($up.Remote): uploaded and hash-checked" +} + $remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll$navSum" $expect = @{ "RynthCore-Setup.exe" = $manifest.core.sha256 } if ($navZip) { $expect["RynthNav-NavData.zip"] = $navData.sha256 } diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml b/src/RynthCore.App.Avalonia/MainWindow.axaml index 140a83d..199cc65 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml @@ -141,6 +141,17 @@ + + + + + + + + + diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index 7b7da54..7e30fd5 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -2462,6 +2462,100 @@ internal partial class MainWindow : Window } } + // ── World map sizes (RynthUpdater.MapPacks.cs) ─────────────────────── + + private string _mapPacksShown = ""; + + /// + /// The front page's "World map detail" card: a row per size the feed offers (name, download size, whether it is + /// installed) with Download / Update / Remove. Rebuilt only when what it shows changes; the buttons are off while + /// a download or an update runs. Called from RefreshUpdateCard, so it follows every check and download. + /// + private void RefreshMapPacksCard() + { + IReadOnlyList packs = _updateCheck?.MapPacks ?? Array.Empty(); + MapPacksCard.IsVisible = packs.Count > 0; + bool busy = _updateBusy || _downloadCts != null; + string signature = busy + "|" + string.Join(";", packs.Select(p => $"{p.Entry.Key}:{p.State}:{p.Entry.Sha256}")); + if (signature == _mapPacksShown) return; + _mapPacksShown = signature; + MapPacksPanel.Children.Clear(); + foreach (RynthUpdater.MapPackStatus st in packs) + { + RynthUpdater.MapPackEntry e = st.Entry; + string state = st.State switch + { + RynthUpdater.MapPackState.UpToDate => "installed", + RynthUpdater.MapPackState.NeedsUpdate => "installed, a newer one is available", + _ => "not installed", + }; + var title = new TextBlock { Text = $"{e.Name} - {DownloadProgress.FormatMb(e.Size)}", FontWeight = global::Avalonia.Media.FontWeight.SemiBold, Foreground = global::Avalonia.Media.Brushes.White }; + var detail = new TextBlock { Text = (e.Description.Length > 0 ? e.Description + " " : "") + "(" + state + ")", TextWrapping = global::Avalonia.Media.TextWrapping.Wrap, Foreground = global::Avalonia.Media.Brush.Parse("#9AA8B3") }; + var text = new StackPanel { Spacing = 2, VerticalAlignment = global::Avalonia.Layout.VerticalAlignment.Center }; + text.Children.Add(title); + text.Children.Add(detail); + + var buttons = new WrapPanel { Orientation = global::Avalonia.Layout.Orientation.Horizontal, VerticalAlignment = global::Avalonia.Layout.VerticalAlignment.Center, Margin = new global::Avalonia.Thickness(12, 0, 0, 0) }; + if (st.State != RynthUpdater.MapPackState.UpToDate) + { + var get = new Button { Content = st.State == RynthUpdater.MapPackState.NeedsUpdate ? "Update" : "Download", IsEnabled = !busy, Margin = new global::Avalonia.Thickness(0, 0, 8, 0) }; + get.Click += async (_, _) => await InstallMapPackAsync(st); + buttons.Children.Add(get); + } + if (st.State != RynthUpdater.MapPackState.NotInstalled) + { + var remove = new Button { Content = "Remove", IsEnabled = !busy }; + remove.Click += async (_, _) => await RemoveMapPackAsync(st); + buttons.Children.Add(remove); + } + var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; + Grid.SetColumn(text, 0); + Grid.SetColumn(buttons, 1); + row.Children.Add(text); + row.Children.Add(buttons); + MapPacksPanel.Children.Add(row); + } + } + + private async Task InstallMapPackAsync(RynthUpdater.MapPackStatus st) + { + if (_updateBusy || _downloadCts != null) return; + _updateBusy = true; + RefreshUpdateCard(); + try + { + string line = await RunDownloadAsync((progress, ct) => _updater.InstallMapPackAsync(st.Entry, progress, ct)); + AppendActivity(line); + } + catch (OperationCanceledException) + { + AppendActivity($"World map ({st.Entry.Name}) download cancelled. Nothing was changed."); + } + catch (Exception ex) + { + AppendActivity($"World map ({st.Entry.Name}) download failed: {ex.Message}"); + } + finally { _updateBusy = false; } + _updateCheck = await _updater.CheckAsync(_pluginDllPaths.ToList()); + RefreshUpdateCard(); + } + + private async Task RemoveMapPackAsync(RynthUpdater.MapPackStatus st) + { + if (_updateBusy || _downloadCts != null) return; + try + { + bool had = await Task.Run(() => _updater.RemoveMapPack(st.Entry)); + AppendActivity(had ? $"World map ({st.Entry.Name}) removed." : $"World map ({st.Entry.Name}) wasn't installed."); + } + catch (Exception ex) + { + AppendActivity($"World map ({st.Entry.Name}) couldn't be removed: {ex.Message} (a running game client may have it open)."); + } + _updateCheck = await _updater.CheckAsync(_pluginDllPaths.ToList()); + RefreshUpdateCard(); + } + private void CancelDownload() { if (_downloadCts is not { IsCancellationRequested: false } cts) return; @@ -2491,6 +2585,7 @@ internal partial class MainWindow : Window /// Redraws the front page's update card, the Plugins tab's status line and the header. private void RefreshUpdateCard() { + RefreshMapPacksCard(); RynthUpdater.CheckResult? c = _updateCheck; bool coreUpdate = c?.CoreUpdateAvailable == true; var card = UpdateCardModel.Build(new UpdateCardInput diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.MapPacks.cs b/src/RynthCore.App.Avalonia/RynthUpdater.MapPacks.cs new file mode 100644 index 0000000..8ea5da8 --- /dev/null +++ b/src/RynthCore.App.Avalonia/RynthUpdater.MapPacks.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace RynthCore.App.Avalonia; + +/// +/// The World Map's optional sizes. The Standard map ships in the NavData archive like the tiles; the bigger +/// ones (worldmap-hd.rmap, worldmap-ultra.rmap: tens to hundreds of MB) are separate, optional downloads the +/// player picks on the launcher's front page, each a single file the feed lists under "mappacks": +/// { "key": "hd", "name": "HD", "file": "worldmap-hd.rmap", "url": "...", "size": N, "sha256": "...", +/// "release": N, "description": "..." } +/// A pack is downloaded to MapPacks\<file>.part, checked against the feed's size and SHA-256, and moved into +/// place; MapPacks\<file>.sha256 records which build is installed (so a changed pack shows as an update). +/// MapPacks sits beside the NavData folder (C:\Games\RynthCore\MapPacks by default), not inside it, because +/// a NavData update swaps that whole folder. The engine's World Map uses the best map it finds in either +/// place, so installing a pack needs no restart; a client picks it up when the panel next opens. +/// +internal sealed partial class RynthUpdater +{ + public const string MapPackDisplayName = "World map"; + public const string MapPacksFolder = "MapPacks"; + private const long MaxMapPackBytes = 4L << 30; + + private static readonly Regex MapPackKey = new(@"^[a-z0-9]{1,16}$", RegexOptions.CultureInvariant); + private static readonly Regex MapPackFile = new(@"^worldmap-[a-z0-9]{1,16}\.rmap$", RegexOptions.CultureInvariant); + + public sealed record MapPackEntry(string Key, string Name, string File, string Url, long Size, string Sha256, int Release, string Description); + public enum MapPackState { NotInstalled, UpToDate, NeedsUpdate } + public sealed record MapPackStatus(MapPackEntry Entry, string Path, MapPackState State); + + /// Where the packs are installed: beside the NavData folder. + public string MapPacksDir + { + get + { + string nav = NavDataDir.TrimEnd('\\', '/'); + return System.IO.Path.Combine(System.IO.Path.GetDirectoryName(nav) ?? nav, MapPacksFolder); + } + } + + /// The feed's map packs. One that can't be read is left out (the rest still show). + private IReadOnlyList ReadMapPacks(JsonElement root) + { + var list = new List(); + if (!root.TryGetProperty("mappacks", out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return list; + var keys = new HashSet(); + foreach (JsonElement p in arr.EnumerateArray()) + { + try + { + string key = (p.GetProperty("key").GetString() ?? "").ToLowerInvariant(); + string file = p.GetProperty("file").GetString() ?? ""; + if (!MapPackKey.IsMatch(key) || !MapPackFile.IsMatch(file) || !keys.Add(key)) continue; + long size = WholeNumber(p.GetProperty("size")); + if (size <= 0 || size > MaxMapPackBytes) continue; + string sha = (p.GetProperty("sha256").GetString() ?? "").ToLowerInvariant(); + if (sha.Length != 64) continue; + list.Add(new MapPackEntry(key, p.TryGetProperty("name", out JsonElement n) ? n.GetString() ?? key : key, file, + CheckUrl(p.GetProperty("url").GetString()), size, sha, + p.TryGetProperty("release", out JsonElement rel) ? (int)WholeNumber(rel) : 0, + p.TryGetProperty("description", out JsonElement d) ? d.GetString() ?? "" : "")); + } + catch (Exception ex) when (ex is InvalidDataException or FormatException or InvalidOperationException or KeyNotFoundException) + { + System.Diagnostics.Debug.WriteLine($"RynthUpdater: a map pack entry is unreadable ({ex.Message}); skipped."); + } + } + return list; + } + + private IReadOnlyList CheckMapPacks(Manifest manifest) + { + string dir = MapPacksDir; + var list = new List(); + foreach (MapPackEntry e in manifest.MapPacks) + { + string path = System.IO.Path.Combine(dir, e.File); + MapPackState state; + try + { + if (!File.Exists(path)) state = MapPackState.NotInstalled; + else + { + string marker = path + ".sha256"; + string installed = File.Exists(marker) ? File.ReadAllText(marker).Trim().ToLowerInvariant() : ""; + // No marker: a file put there by hand counts as current if it is the size the feed says. + state = installed.Length > 0 ? (installed == e.Sha256 ? MapPackState.UpToDate : MapPackState.NeedsUpdate) + : new FileInfo(path).Length == e.Size ? MapPackState.UpToDate : MapPackState.NeedsUpdate; + } + } + catch { state = MapPackState.NotInstalled; } + list.Add(new MapPackStatus(e, path, state)); + } + return list; + } + + /// + /// Downloads, verifies and installs a map pack (or replaces an older build of it). Returns a line for the + /// activity log. Throws on anything wrong (disk space, a bad download); the file that was there stays as it + /// was. Cancel deletes the partial download. + /// + public async Task InstallMapPackAsync(MapPackEntry e, IProgress? progress = null, CancellationToken ct = default) + { + string dir = MapPacksDir; + Directory.CreateDirectory(dir); + // The pack is downloaded beside where it goes, so the finishing move is a rename. + long need = e.Size + (64L << 20); + long free = new DriveInfo(System.IO.Path.GetPathRoot(System.IO.Path.GetFullPath(dir))!).AvailableFreeSpace; + if (free < need) + throw new IOException($"not enough disk space for the {e.Name} map: {need >> 20} MB needed, {free >> 20} MB free on {System.IO.Path.GetPathRoot(dir)}"); + + string target = System.IO.Path.Combine(dir, e.File), part = target + ".part"; + string what = $"{MapPackDisplayName} ({e.Name})"; + try + { + await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxMapPackBytes, part, ct, what, progress); + ct.ThrowIfCancellationRequested(); + progress?.Report(new DownloadProgress(what, DownloadStage.Installing, 0, 0)); + Retry(() => File.Move(part, target, overwrite: true)); // a client may have it open for a moment + File.WriteAllText(target + ".sha256", e.Sha256); + } + catch + { + try { if (File.Exists(part)) File.Delete(part); } catch { } + throw; + } + return $"{MapPackDisplayName} ({e.Name}) installed: {target} ({DownloadProgress.FormatMb(e.Size)}). The World Map uses the best installed size; a map that is already open picks it up when you reopen it."; + } + + /// Deletes an installed map pack (and its marker). Returns false when it wasn't there. + public bool RemoveMapPack(MapPackEntry e) + { + string target = System.IO.Path.Combine(MapPacksDir, e.File); + bool had = File.Exists(target); + Retry(() => { if (File.Exists(target)) File.Delete(target); }); + try { if (File.Exists(target + ".sha256")) File.Delete(target + ".sha256"); } catch { } + try { if (File.Exists(target + ".part")) File.Delete(target + ".part"); } catch { } + return had; + } +} diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs b/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs index 1a3d9aa..42871bb 100644 --- a/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs +++ b/src/RynthCore.App.Avalonia/RynthUpdater.NavData.cs @@ -20,7 +20,7 @@ namespace RynthCore.App.Avalonia; /// The signature covers it exactly like the plugins; the archive is checked against the signed /// size and SHA-256 before it is opened, and only plain file names RynthNav reads /// (nav_XXXX.tile, portals.tsv, locations.json, navgraph.bin: the long-range route graph, -/// townnet.json: the Town Network's portals and the walks inside) are +/// townnet.json: the Town Network's portals and the walks inside, worldmap.rmap and worldmap.vec: the World Map's tiles, buildings and roads) are /// accepted from it. /// /// Install: only when RynthNav is in the plugin list and the folder's navdata.id differs from the @@ -40,7 +40,7 @@ internal sealed partial class RynthUpdater private const long MaxNavDataBytes = 3L << 30; // the archive private const long MaxNavDataEntryBytes = 32L << 20; // one file in it - private static readonly Regex ShippedName = new(@"^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$", RegexOptions.CultureInvariant); + private static readonly Regex ShippedName = new(@"^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json|worldmap\.rmap|worldmap\.vec)$", RegexOptions.CultureInvariant); private static readonly Regex IdPattern = new(@"^[0-9a-f]{16,64}$", RegexOptions.CultureInvariant); public sealed record NavDataEntry(string Id, int Release, string Url, long Size, string Sha256, int Files, long Bytes); diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.cs b/src/RynthCore.App.Avalonia/RynthUpdater.cs index e13899b..9ca3b45 100644 --- a/src/RynthCore.App.Avalonia/RynthUpdater.cs +++ b/src/RynthCore.App.Avalonia/RynthUpdater.cs @@ -58,6 +58,8 @@ internal sealed partial class RynthUpdater /// signed with the rest). Empty for older feeds, which only have . /// public IReadOnlyList Changes { get; init; } = Array.Empty(); + /// The optional World Map sizes the feed offers (RynthUpdater.MapPacks.cs); empty for older feeds. + public IReadOnlyList MapPacks { get; init; } = Array.Empty(); } /// One installed copy of a plugin the feed knows. @@ -91,6 +93,8 @@ internal sealed partial class RynthUpdater /// RynthNav's tiles: null when the feed has none or RynthNav isn't in the plugin list. public NavDataStatus? NavData { get; init; } public bool NavDataUpdateAvailable => NavData is { State: NavDataState.NeedsUpdate }; + /// The optional World Map sizes: what the feed offers and what is installed. Not part of "Update plugins": the player chooses. + public IReadOnlyList MapPacks { get; init; } = Array.Empty(); } /// @@ -213,6 +217,7 @@ internal sealed partial class RynthUpdater { Companions = companions, NavData = CheckNavData(manifest, pluginPaths), + MapPacks = CheckMapPacks(manifest), Available = available, NewlyAnnounced = available.Where(a => fresh.Contains(a.Entry.Name)).ToList(), }; @@ -396,6 +401,7 @@ internal sealed partial class RynthUpdater r.TryGetProperty("navdata", out JsonElement nd) && nd.ValueKind == JsonValueKind.Object ? TryParseNavData(nd) : null) { Changes = ReadChanges(r), + MapPacks = ReadMapPacks(r), }; } diff --git a/src/RynthCore.App/AppSettings.cs b/src/RynthCore.App/AppSettings.cs index 1d21601..0dfa5a9 100644 --- a/src/RynthCore.App/AppSettings.cs +++ b/src/RynthCore.App/AppSettings.cs @@ -4,20 +4,24 @@ namespace RynthCore.App; internal sealed class AppSettings { - public string AcClientPath { get; set; } = string.Empty; + // A new install starts with the standard client folder (2026-10-14); a saved path always wins. + public string AcClientPath { get; set; } = DefaultAcClientPath; + public const string DefaultAcClientPath = @"C:\Turbine\Asheron's Call\acclient.exe"; public string EnginePath { get; set; } = string.Empty; public string LaunchArguments { get; set; } = string.Empty; public string SelectedServerProfileId { get; set; } = string.Empty; public string SelectedAccountProfileId { get; set; } = string.Empty; public List CheckedLaunchAccountProfileIds { get; set; } = []; public string SelectedMainTabId { get; set; } = "launcher"; - public bool AllowMultipleClients { get; set; } - public bool SkipIntroVideos { get; set; } - public bool SkipLoginLogos { get; set; } + // New-install defaults (2026-10-14): multiple clients, no intro videos or logos, inject after + // launch, kill stuck clients; leave clients launched outside RynthCore alone. + public bool AllowMultipleClients { get; set; } = true; + public bool SkipIntroVideos { get; set; } = true; + public bool SkipLoginLogos { get; set; } = true; public bool AutoLaunch { get; set; } public bool AutoInjectAfterLaunch { get; set; } = true; - public bool WatchForAcStart { get; set; } = true; - public bool InjectAllRunningClients { get; set; } = true; + public bool WatchForAcStart { get; set; } + public bool InjectAllRunningClients { get; set; } public string LoggingLevel { get; set; } = "Info"; public int LaunchStaggerMs { get; set; } = 250; public int CrashRelaunchLimitInWindow { get; set; } = 3; @@ -48,7 +52,7 @@ internal sealed class AppSettings /// patcher hangs, and "you have been disconnected" failure screens at /// the front of the launch flow. Off by default — destructive. /// Decal-mode clients are skipped (no engine = no IsLoggedIn signal). - public bool KillStuckClients { get; set; } + public bool KillStuckClients { get; set; } = true; public int StuckClientTimeoutSeconds { get; set; } = 60; /// When true (default), the launcher kills+relaunches a RynthCore-mode diff --git a/src/RynthCore.Engine/Compatibility/LauncherSettings.cs b/src/RynthCore.Engine/Compatibility/LauncherSettings.cs index 2e66fb3..a466f80 100644 --- a/src/RynthCore.Engine/Compatibility/LauncherSettings.cs +++ b/src/RynthCore.Engine/Compatibility/LauncherSettings.cs @@ -8,7 +8,8 @@ internal static class LauncherSettings { private static readonly object Sync = new(); private static bool _loaded; - private static bool _allowMultipleClients; + // The launcher's own default (AppSettings.AllowMultipleClients, on since 2026-10-14) until it has saved one. + private static bool _allowMultipleClients = true; private static string _statusMessage = "Launcher settings not loaded."; public static bool AllowMultipleClientsEnabled diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index bfb3143..07dfb02 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -30,6 +30,9 @@ namespace RynthCore.Engine.Compatibility; /// /rc ui barsize [0-10|+|-|status] - the RynthCore bar's size (its own text /// size step, ; saved for the PC, also in Settings > /// Display). Alone it reports the size. +/// /rc ui barrows [1-6|+|-|status] and /rc ui baricons [2-30|none|+|-|status] +/// - the bar's rows and the most icons a row holds (none = no limit; , +/// saved for the PC, also in the grip's menu and Settings > Display). Alone each reports both. /// /rc vendor [list|info|status|buy <id|sel> [n]|sell <id|sel> [id ...]] /// — read / trade with the open vendor through the engine's vendor /// primitives (); a manual test hook for the @@ -142,7 +145,7 @@ internal static class RynthCoreChatCommands return true; } - // /rc ui list | /rc ui avalonia|imgui|both + // /rc ui list | open|close|popout|redock|snap | bar settings (HandleUiCommand) if (sub.Equals("ui", StringComparison.OrdinalIgnoreCase) || sub.StartsWith("ui ", StringComparison.OrdinalIgnoreCase)) { @@ -513,9 +516,10 @@ internal static class RynthCoreChatCommands } /// - /// /rc ui list, or /rc ui <Panel> avalonia|imgui|both: which face shows a - /// panel while it is docked in the client (UI.PanelRouter). Replies are - /// queued to chat, not written from inside this outgoing-chat hook. + /// /rc ui list (each panel's face and placement, UI.PanelRouter), open/close/popout/ + /// redock/snap a panel, and the bar's settings. /rc ui <Panel|bar> avalonia|imgui|both + /// no longer picks a face (2026-10-14: docked panels and the bar are always ImGui); it + /// says so. Replies are queued to chat, not written from inside this outgoing-chat hook. /// private static void HandleUiCommand(string args) { @@ -565,6 +569,52 @@ internal static class RynthCoreChatCommands return; } + // /rc ui barrows [1-6|+|-|status]: the bar's rows. Alone it reports the rows and the limit. + if (parts[0].Equals("barrows", StringComparison.OrdinalIgnoreCase)) + { + int cur = ImGuiBackend.ImGuiBar.Rows; + if (parts.Length >= 2 && !parts[1].Equals("status", StringComparison.OrdinalIgnoreCase)) + { + int next; + // Bare + / -: one row. +n / -n: that many. Plain n: that many rows. + if (parts[1] == "+") next = cur + 1; + else if (parts[1] == "-") next = cur - 1; + else if (!int.TryParse(parts[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out next)) + { + Reply("Usage: /rc ui barrows [1-6|+|-|status]"); + return; + } + else if (parts[1][0] is '+' or '-') + next += cur; + ImGuiBackend.ImGuiBar.SetRowLayout(next, ImGuiBackend.ImGuiBar.MaxPerRow); + } + Reply(ImGuiBackend.ImGuiBar.DescribeRowLayout()); + return; + } + + // /rc ui baricons [2-30|none|+|-|status]: the most icons a bar row holds (none or 0 = no + // limit). + / - step like the grip's menu (past 30 is no limit). Alone it reports both. + if (parts[0].Equals("baricons", StringComparison.OrdinalIgnoreCase)) + { + int cur = ImGuiBackend.ImGuiBar.MaxPerRow; + if (parts.Length >= 2 && !parts[1].Equals("status", StringComparison.OrdinalIgnoreCase)) + { + int next; + if (parts[1] == "+" || parts[1] == "-") + next = UI.BarLayout.StepMaxPerRow(cur, parts[1] == "+" ? 1 : -1, ImGuiBackend.ImGuiBar.ShownPerRow); + else if (parts[1].Equals("none", StringComparison.OrdinalIgnoreCase) || parts[1].Equals("off", StringComparison.OrdinalIgnoreCase)) + next = UI.BarLayout.NoLimit; + else if (!int.TryParse(parts[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out next)) + { + Reply("Usage: /rc ui baricons [2-30|none|+|-|status]"); + return; + } + ImGuiBackend.ImGuiBar.SetRowLayout(ImGuiBackend.ImGuiBar.Rows, next); + } + Reply(ImGuiBackend.ImGuiBar.DescribeRowLayout()); + return; + } + // /rc ui open|close|popout|redock|snap : drive a panel by name (tests, // dispatch.txt). Names may have spaces ("Monster Detail"). string verb = parts[0].ToLowerInvariant(); @@ -595,13 +645,14 @@ internal static class RynthCoreChatCommands return; } - if (parts.Length != 2 || !UI.PanelFaceStore.TryParseFace(parts[1], out UI.PanelFace face)) + // The old face choice: nothing to pick any more (nothing is stored either). + if (parts.Length == 2 && UI.PanelFaceStore.TryParseFace(parts[1], out _)) { - Reply("Usage: /rc ui list | /rc ui avalonia|imgui|both | /rc ui open|close|popout|redock|snap | /rc ui retailvitals [on|off] | /rc ui barsize [0-10|+|-|status]"); + Reply("The Avalonia / Both faces are gone: docked panels and the bar always show their ImGui face."); return; } - Reply(UI.PanelRouter.SetDockedFace(parts[0], face)); + Reply("Usage: /rc ui list | /rc ui open|close|popout|redock|snap | /rc ui retailvitals [on|off] | /rc ui barsize [0-10|+|-|status] | /rc ui barrows [1-6|+|-] | /rc ui baricons [2-30|none|+|-]"); } /// diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 15c9dd1..76b81de 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -1083,6 +1083,8 @@ public static class EntryPoint ImGuiBackend.Panels.VisionFace.Register(); if (HasPluginDll("RynthCore.Plugin.RynthNav.dll")) ImGuiBackend.Panels.RynthNavFace.Register(); + if (HasPluginDll("RynthCore.Plugin.RynthNav.dll")) + ImGuiBackend.Panels.WorldMapFace.Register(); // Characters (your other RynthCore clients, through RynthNet): only with RynthNet installed. if (HasPluginDll("RynthCore.Plugin.RynthNet.dll")) ImGuiBackend.Panels.CharactersFace.Register(); @@ -1119,6 +1121,8 @@ public static class EntryPoint // RynthAiPanel: see the dispatcher invariant above ChatModel.EnsureSettingsLoaded. RynthAiDashboardState.EnsureLoaded(); } + // The colour theme (theme.txt), here rather than on AC's thread; every ImGui face reads it. + ImGuiBackend.RynthTheme.EnsureLoaded(); RegisterServerMenus(HasPluginDll("RynthCore.Plugin.RynthAi.dll"), HasPluginDll("RynthCore.Plugin.RynthILT.dll")); if (trackerPresent) TrackerSettings.EnsureLoaded(); diff --git a/src/RynthCore.Engine/ImGui/CodeEditor.cs b/src/RynthCore.Engine/ImGui/CodeEditor.cs index 8dabf7b..6816d59 100644 --- a/src/RynthCore.Engine/ImGui/CodeEditor.cs +++ b/src/RynthCore.Engine/ImGui/CodeEditor.cs @@ -270,27 +270,27 @@ internal sealed unsafe class CodeEditor : IDisposable return new[] { C(0xFFD9E6F2), // Default - C(0xFF26D9E6), // Keyword + RynthTheme.Accent, // Keyword C(0xFF99E699), // Number C(0xFFE6C07B), // String C(0xFFE6C07B), // CharLiteral C(0xFFCC88CC), // Punctuation C(0xFF8CA6BF), // Preprocessor C(0xFFD9E6F2), // Identifier - C(0xFFE8B333), // KnownIdentifier + RynthTheme.Highlight, // KnownIdentifier C(0xFF7BB8FF), // PreprocIdentifier C(0xFF6A7A8A), // Comment C(0xFF6A7A8A), // MultiLineComment - C(0xFF141F29), // Background + RynthTheme.Field, // Background C(0xFFE6F2FF), // Cursor C(0x80305A80), // Selection C(0x80B02020), // ErrorMarker - C(0xFF3A4A5A), // ControlCharacter + RynthTheme.BarButtonBorder, // ControlCharacter C(0x40F08000), // Breakpoint C(0xFF4F6478), // LineNumber C(0x40263A50), // CurrentLineFill C(0x20263A50), // CurrentLineFillInactive - C(0x40264059), // CurrentLineEdge + RynthTheme.WithAlpha(RynthTheme.DashBorder, 0x40), // CurrentLineEdge }; } } diff --git a/src/RynthCore.Engine/ImGui/DX9Backend.cs b/src/RynthCore.Engine/ImGui/DX9Backend.cs index d4dbd5d..1152a97 100644 --- a/src/RynthCore.Engine/ImGui/DX9Backend.cs +++ b/src/RynthCore.Engine/ImGui/DX9Backend.cs @@ -50,6 +50,7 @@ internal static unsafe class DX9Backend private const uint D3DPT_TRIANGLELIST = 4; private const uint D3DFMT_INDEX16 = 101; private const uint D3DFMT_A8R8G8B8 = 21; + private const uint D3DFMT_DXT1 = 0x31545844; // the FourCC 'DXT1' private const uint D3DPOOL_MANAGED = 1; private const uint D3DUSAGE_DYNAMIC = 0x200; private const uint D3DPOOL_DEFAULT = 0; @@ -993,6 +994,38 @@ internal static unsafe class DX9Backend return tex; } + /// + /// A managed-pool DXT1 texture (4x4 blocks of 8 bytes: two RGB565 colours and sixteen 2-bit indices, a sixth + /// of A8R8G8B8's size) holding as they are: x + /// a multiple of 4, (w/4) * (h/4) * 8 bytes, top row of blocks first (the World + /// Map's tiles). Zero on failure or when the device can't make DXT1. AC's render thread. + /// + public static IntPtr CreateTextureDxt1(IntPtr pDevice, int width, int height, ReadOnlySpan blocks) + { + int rowBytes = width / 4 * 8, rows = height / 4; + if (_createTexture == null || pDevice == IntPtr.Zero || width <= 0 || height <= 0 || width % 4 != 0 || height % 4 != 0 + || blocks.Length < rowBytes * rows) + return IntPtr.Zero; + int hr = _createTexture(pDevice, (uint)width, (uint)height, 1, 0, + D3DFMT_DXT1, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero); + if (hr < 0 || tex == IntPtr.Zero) + return IntPtr.Zero; + + var lockRect = GetTexMethod(tex, TextureVTableIndex.LockRect); + var unlockRect = GetTexMethod(tex, TextureVTableIndex.UnlockRect); + D3DLOCKED_RECT locked; + if (lockRect(tex, 0, &locked, IntPtr.Zero, 0) < 0 || locked.pBits == IntPtr.Zero) + { + ReleaseComObject(tex); + return IntPtr.Zero; + } + byte* dst = (byte*)locked.pBits; + for (int y = 0; y < rows; y++) // the pitch of a compressed surface is the bytes of one row of blocks + blocks.Slice(y * rowBytes, rowBytes).CopyTo(new Span(dst + y * locked.Pitch, rowBytes)); + unlockRect(tex, 0); + return tex; + } + /// Releases a texture made by . AC's render thread. public static void ReleaseTexture(IntPtr tex) => ReleaseComObject(tex); diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index ec4de6e..b12610a 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -233,6 +233,8 @@ internal static class EngineFrameController // Its lists are drawn by DX9Backend from the DIP hook, which is still live. UnderUiLayer.Shutdown(); ScriptIcons.Shutdown(); // script window icon textures, before the backend goes + WorldMapTiles.Shutdown(); // the world map's tile textures, likewise + WorldMapVectors.Shutdown(); RetailSprites.Shutdown(); // retail UI pictures (Inventory Classic view), likewise DX9Backend.Shutdown(); // Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown @@ -594,6 +596,7 @@ internal static class EngineFrameController /// DPI scale the fonts and style were built for (see Init). private static float _uiScale = 1f; + private static int _themeApplied; // RynthTheme.Version the base style was coloured at /// The scale the fonts and style were built for. internal static float FontScale => _uiScale; @@ -705,6 +708,7 @@ internal static class EngineFrameController // Script window icons decoded since the last frame become textures, and the least // recently drawn go, before anything draws (no draw list points at them any more). ScriptIcons.BeginFrame(pDevice); + WorldMapTiles.BeginFrame(pDevice); // world map tiles read since the last frame become textures RetailSprites.BeginFrame(pDevice); // retail UI pictures decoded since the last frame (kept, never evicted) DX9Backend.NewFrame(); Win32Backend.NewFrame(clientW, clientH); @@ -721,6 +725,7 @@ internal static class EngineFrameController _lastFrameTicks = now; io.DeltaTime = dt > 0f ? dt : 1f / 60f; + RynthTheme.RefreshStyle(ref _themeApplied); // a theme change re-colours the base style ImGuiNET.ImGui.NewFrame(); frameStarted = true; // Before any window: a drag from a popped-out Inventory or AC's inventory becomes diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index 68a5e38..a6c5ca8 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -9,25 +9,39 @@ // asked for a button (WindowFlags.BarButton: RynthSort, Oracle, ...; tooltip = // its title; the set is rebuilt as plugins come and go), reload (RL) and pop out. // Dragging the grip moves the bar; the position is the shared bar= row in -// panel_state.txt. Right-click a panel button (or the grip for the bar -// itself) to choose which face shows it docked; the grip's menu also has the -// bar's size and "Report a problem". Pop out moves the ImGui bar -// into its own window (ImGuiPopOuts, sized to its content; dock back -// returns it); a bar whose face is Avalonia/Both still pops out as the -// Avalonia bar. +// panel_state.txt. Right-click the grip for the bar's menu: its size, its rows +// and "Report a problem" (panel buttons have no menu). Pop out moves the ImGui +// bar into its own window (ImGuiPopOuts, sized to its content; dock back +// returns it). // // The bar's size is its own text size step (PanelTextScale chrome row): the bar's // fonts come from that baked set and its metrics scale by the step's factor. Set it // from the grip's right-click menu, Ctrl+wheel over the bar, Settings > Display or // /rc ui barsize. // -// Face key "__bar" in panel_faces.txt; code default Avalonia. While the ImGui -// bar shows, the docked Avalonia bar is hidden and takes no clicks -// (AvaloniaOverlay.DockedBarSuppressed). AC thread except where noted. +// Rows (BarLayout): the player picks how many rows the bar has (1-6) and the most +// icons a row may hold (no limit, or 2-30): icons per row = ceil(icons / rows), +// capped at the limit, so the cap can add rows. The icons (panels, plugin windows, +// ILT, Scripts) fill rows left to right, top to bottom, each row starting under the +// first icon: the grip and the collapse caret lead the first row only. RL and pop out +// stay at the end of the first row, so one row looks as it always did and they keep +// their spot as icons come and go on the rows below. The window sizes to its content +// as before (AlwaysAutoResize; popped out, ImGuiPopOuts sizes to it); a folded bar is +// still just the grip and caret. Set from the grip's right-click menu, Settings > +// Display or /rc ui barrows / baricons; kept in panel_state.txt's barlayout= row. +// +// The bar is always this ImGui face while the ImGui layer is on (Tom, 2026-10-14: +// the Avalonia and Both faces are gone). The old choice (face key "__bar" in +// panel_faces.txt, the grip's and panel buttons' Avalonia / ImGui / Both menu +// items) is no longer offered, and a saved Avalonia or Both is read as ImGui +// (ResolveFace); docked panels already ignore theirs (PanelRouter.ResolveDockedFace). +// While the ImGui bar shows, the docked Avalonia bar is hidden and takes no +// clicks (AvaloniaOverlay.DockedBarSuppressed). AC thread except where noted. // ============================================================================ using System; using System.Collections.Generic; +using System.Globalization; using System.Numerics; using System.Threading; using ImGuiNET; @@ -47,13 +61,10 @@ internal static class ImGuiBar private static readonly HashSet LauncherOnly = new(StringComparer.OrdinalIgnoreCase) { "Monsters", "Damage", "Settings", "Nav", "Meta", "Items" }; - private static readonly PanelFace[] Faces = { PanelFace.Avalonia, PanelFace.ImGui, PanelFace.Both }; - private static readonly string[] FaceNames = { "Avalonia", "ImGui", "Both (side by side)" }; - // Window: a plugin's script window with a bar button of its own (WindowFlags.BarButton); // the button toggles it through ScriptWindowRegistry, like the Scripts menu does. - private sealed record ButtonInfo(string Title, string Id, string PopupId, string Icon, bool Letter, string Tooltip, - bool ImGuiOnly = false, ScriptWindow? Window = null); + private sealed record ButtonInfo(string Title, string Id, string Icon, bool Letter, string Tooltip, + ScriptWindow? Window = null); // Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button. private static readonly string[] ImGuiOnlyBarPanels = @@ -135,6 +146,51 @@ internal static class ImGuiBar private static bool _userMoved; private static int _lastStep, _sizeWatch; + // The bar's rows and icons-per-row limit (BarLayout). Read from panel_state once, then kept + // here so a change shows at once (the file is written in the background); one reference, so + // a reader on another thread never sees half a change. + private sealed record RowSettings(int Rows, int MaxPerRow); + private static RowSettings? _rowSettings, _lastRowSettings; + // Icons per row as last drawn: where the icons-per-row "-" starts from when there is no limit. + private static int _shownPerRow = 1; + + private static RowSettings RowLayout + { + get + { + RowSettings? cur = Volatile.Read(ref _rowSettings); + if (cur != null) return cur; + var (rows, max) = PanelStateStore.BarRows; + Interlocked.CompareExchange(ref _rowSettings, new RowSettings(rows, max), null); + return Volatile.Read(ref _rowSettings)!; + } + } + + /// The bar's rows (1-6). Any thread. + public static int Rows => RowLayout.Rows; + + /// The most icons a bar row holds; 0 = no limit. Any thread. + public static int MaxPerRow => RowLayout.MaxPerRow; + + /// Icons per row as the bar last drew them. Any thread. + public static int ShownPerRow => Volatile.Read(ref _shownPerRow); + + /// Sets the bar's rows and icons-per-row limit (clamped; BarLayout) and saves them. Any thread. + public static void SetRowLayout(int rows, int maxPerRow) + { + var next = new RowSettings(BarLayout.ClampRows(rows), BarLayout.ClampMaxPerRow(maxPerRow)); + if (next == RowLayout) return; + Volatile.Write(ref _rowSettings, next); + UiBackgroundWriter.Enqueue("persist bar rows", () => PanelStateStore.SetBarRows(next.Rows, next.MaxPerRow)); + } + + /// "Bar rows: 2, icons per row: no limit." for chat. Any thread. + public static string DescribeRowLayout() + { + RowSettings cur = RowLayout; + return $"Bar rows: {cur.Rows.ToString(CultureInfo.InvariantCulture)}, icons per row: {BarLayout.DescribeMaxPerRow(cur.MaxPerRow).ToLowerInvariant()}."; + } + private const string PopOutTitle = "__bar"; // Popped out (the ImGui bar in its own window). Read from panel_state once, // then kept here so a switch shows at once (the file is written in the background). @@ -144,13 +200,12 @@ internal static class ImGuiBar /// True when the ImGui bar is popped out into its own window. public static bool PoppedOut => ResolveFace() == PanelFace.ImGui && Floating; - /// The bar's docked face. Any thread. - public static PanelFace ResolveFace() - { - if (!Plugins.EngineSettings.EnableImGuiBackend) return PanelFace.Avalonia; - if (!Plugins.EngineSettings.EnableAvaloniaOverlay) return PanelFace.ImGui; - return PanelFaceStore.TryGet(FaceKey, out PanelFace f) ? f : PanelFace.ImGui; - } + /// + /// The bar's docked face: ImGui whenever the ImGui layer is on, Avalonia only without it. + /// A face saved in panel_faces.txt (Avalonia or Both, from before) is ignored. Any thread. + /// + public static PanelFace ResolveFace() => + Plugins.EngineSettings.EnableImGuiBackend ? PanelFace.ImGui : PanelFace.Avalonia; /// /// Shows/hides the docked Avalonia bar to match the bar's face. Call at @@ -162,7 +217,7 @@ internal static class ImGuiBar _placed = false; // re-read the shared position next frame } - /// True when the ImGui bar should draw (docked face ImGui/Both, not popped out). + /// True when the ImGui bar should draw (the ImGui layer on, not popped out). public static bool Visible => ResolveFace() != PanelFace.Avalonia && !Floating; /// @@ -218,7 +273,6 @@ internal static class ImGuiBar EnsureButtons(); int step = ChromeStep(out float factor); s *= factor; - float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f; ImGuiNET.ImGui.SetNextWindowPos(ImGuiPopOuts.PanelOrigin, ImGuiCond.Always); PushBarWindowStyle(s); ImGuiNET.ImGui.Begin("##rc_bar", BarFlags); @@ -226,7 +280,7 @@ internal static class ImGuiBar { ImGuiFonts.CurrentStep = step; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); - DrawContent(s, place, popped: true); + DrawContent(s, popped: true); ImGuiNET.ImGui.PopFont(); // Not on its first frame: an auto-resizing window has no content size yet // and reports just its padding (8x6), which would shrink the window to it. @@ -270,27 +324,29 @@ internal static class ImGuiBar int step = ChromeStep(out float factor); s *= factor; float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f; - bool both = ResolveFace() == PanelFace.Both; if (!_placed) { var saved = PanelStateStore.BarPosition; Vector2 logical = saved.HasValue ? new Vector2((float)saved.Value.Left, (float)saved.Value.Top) : new Vector2(50, 5); - if (both) logical += new Vector2(24, 24); _pos = _persistedPos = logical * place; ImGuiNET.ImGui.SetNextWindowPos(_pos, ImGuiCond.Always); _placed = true; _lastStep = step; // the size the bar loads at is the baseline, not a change + _lastRowSettings = RowLayout; } if (step != _lastStep) { _lastStep = step; _sizeWatch = 4; } + // New rows reshape the bar (wider or taller): the same pull back on screen as a new size. + RowSettings rowsNow = RowLayout; + if (!ReferenceEquals(rowsNow, _lastRowSettings)) { _lastRowSettings = rowsNow; _sizeWatch = 4; } PushBarWindowStyle(s); ImGuiNET.ImGui.Begin("##rc_bar", BarFlags); try { ImGuiFonts.CurrentStep = step; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); - DrawContent(s, place, popped: false); + DrawContent(s, popped: false); ImGuiNET.ImGui.PopFont(); KeepOnScreen(); } @@ -307,17 +363,17 @@ internal static class ImGuiBar _persistedPos = _pos; if (_userMoved || _sizeWatch > 0) { - Vector2 logical = _pos / place - (both ? new Vector2(24, 24) : Vector2.Zero); + Vector2 logical = _pos / place; double left = logical.X, top = logical.Y; UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarPosition(left, top)); - if (!both) AvaloniaOverlay.SyncDockedBarPosition(left, top); + AvaloniaOverlay.SyncDockedBarPosition(left, top); } _userMoved = false; } if (_sizeWatch > 0) _sizeWatch--; } - /// A bigger size can push the bar's right end off the screen: pull it back (not while it is being dragged). + /// A bigger size or new rows can push the bar's right or bottom end off the screen: pull it back (not while it is being dragged). private static void KeepOnScreen() { Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize; @@ -327,7 +383,7 @@ internal static class ImGuiBar if (next != pos) ImGuiNET.ImGui.SetWindowPos(next); } - private static void DrawContent(float s, float place, bool popped) + private static void DrawContent(float s, bool popped) { // Ctrl+wheel over the bar steps its size (the panels' title bars do the same). ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); @@ -360,9 +416,9 @@ internal static class ImGuiBar } ImGuiNET.ImGui.SetItemTooltip(_tooltip); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) - ImGuiNET.ImGui.OpenPopup("##face_bar"); + ImGuiNET.ImGui.OpenPopup("##bar_menu"); PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.DotsSixVertical, rcPos, new Vector2(square.X * 0.8f, square.Y), RynthTheme.RcLabel); - FacePopup("##face_bar", FaceKey, hasImGuiFace: true, s); + BarMenu(s); // Collapse: the bar folds to its grip and this caret. bool collapsed = RynthAiDashboardState.BarCollapsed; @@ -377,29 +433,37 @@ internal static class ImGuiBar caretHot ? RynthTheme.RcLabel : 0xFF9A9A9Au); if (collapsed) return; + // Rows (header): perRow icons a row, each row from iconsX (under the first icon); + // RL and pop out go at the end of the first row (NextSlot, or after the icons when + // they all fit on it). + int iltCount = IltPanelCount(); + ScriptBarItem[] scripts = ScriptWindowRegistry.BarItems; + int icons = _buttons!.Length + (iltCount > 0 ? 1 : 0) + (scripts.Length > 0 ? 1 : 0); + RowSettings rows = RowLayout; + int perRow = BarLayout.PerRow(icons, rows.Rows, rows.MaxPerRow); + Volatile.Write(ref _shownPerRow, perRow); + ImGuiNET.ImGui.SameLine(); + float iconsX = ImGuiNET.ImGui.GetCursorPosX(); + int slot = 0; + PushBarButtonStyle(s); ImFontPtr letterFont = ImGuiFonts.Get(UiFont.UiBold11); foreach (ButtonInfo b in _buttons!) { - ImGuiNET.ImGui.SameLine(); + NextSlot(ref slot, perRow, iconsX, s, iconFont, popped); if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText)) { if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !ImGuiPanelHost.IsOpen(b.Window.PanelKey)); else PanelRouter.Toggle(b.Title); } ImGuiNET.ImGui.SetItemTooltip(b.Tooltip); // a plugin window's title arrives with '%' doubled (EnsureButtons) - if (b.ImGuiOnly) continue; // no Avalonia face: no face to choose - if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) - ImGuiNET.ImGui.OpenPopup(b.PopupId); - FacePopup(b.PopupId, b.Title, ImGuiPanelHost.HasFace(b.Title)); } // The ILT section: one button, only on Infinite Leaftide with ILT panels registered // (Bounties, Guardian). With one panel it toggles that panel; with more it opens a menu. - int iltCount = IltPanelCount(); if (iltCount > 0) { - ImGuiNET.ImGui.SameLine(); + NextSlot(ref slot, perRow, iconsX, s, iconFont, popped); string? only = iltCount == 1 ? FirstIltPanel() : null; if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText)) { @@ -412,15 +476,47 @@ internal static class ImGuiBar // Script windows (decision 2): one button with a menu, only while a ShowInBar // script window exists. A window that also sets BarButton (plugin windows such as // RynthSort's) has a button of its own instead (EnsureButtons) and isn't listed here. - ScriptBarItem[] scripts = ScriptWindowRegistry.BarItems; if (scripts.Length > 0) { - ImGuiNET.ImGui.SameLine(); + NextSlot(ref slot, perRow, iconsX, s, iconFont, popped); if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText)) ImGuiNET.ImGui.OpenPopup("##scripts_menu"); ImGuiNET.ImGui.SetItemTooltip("Script windows"); } + // Every icon fit on the first row: RL and pop out follow them. + if (slot <= perRow) DrawControls(s, iconFont, popped); + PopBarButtonStyle(); + + // Drawn after the bar buttons' style is popped, so the menu has the normal look. + ScriptsMenu(scripts); + IltMenu(); + } + + /// + /// Places the next icon: beside the last one, or at the start of a new row (under the first + /// icon) every icons. Leaving the first row, RL and pop out go at + /// its end first. AC thread, inside the bar window with the bar buttons' style pushed. + /// + private static void NextSlot(ref int slot, int perRow, float iconsX, float s, ImFontPtr iconFont, bool popped) + { + // Slot 0: DrawContent's SameLine after the caret already placed it. + if (slot > 0) + { + if (slot % perRow != 0) ImGuiNET.ImGui.SameLine(); + else + { + if (slot == perRow) DrawControls(s, iconFont, popped); + ImGuiNET.ImGui.SetCursorPosX(iconsX); + } + } + slot++; + } + + /// RL and pop out, after the first row's last icon (or the caret on a bar with no icons). AC thread. + private static void DrawControls(float s, ImFontPtr iconFont, bool popped) + { + var square = new Vector2(ButtonSize, ButtonSize) * s; ImGuiNET.ImGui.SameLine(0, 6 * s); if (IconButton("##reload", iconFont, PhosphorIcons.ArrowsClockwise, square, RynthTheme.ReloadLabel)) { @@ -430,28 +526,11 @@ internal static class ImGuiBar } ImGuiNET.ImGui.SetItemTooltip("Engine reload (RL) — shut down, FreeLibrary, reload from disk, re-init."); - if (ResolveFace() == PanelFace.ImGui) - { - ImGuiNET.ImGui.SameLine(); - if (IconButton("##popout", iconFont, popped ? PhosphorIcons.ArrowSquareIn : PhosphorIcons.ArrowSquareOut, square, RynthTheme.PopOutLabel)) - SetPoppedOut(!popped); - ImGuiNET.ImGui.SetItemTooltip(popped ? "Dock the bar back into the game window." : "Pop the bar out into its own floating window."); - } - else if (Plugins.EngineSettings.EnableAvaloniaOverlay) // Avalonia/Both bar: pops out as the Avalonia bar - { - ImGuiNET.ImGui.SameLine(); - if (IconButton("##popout", iconFont, PhosphorIcons.ArrowSquareOut, square, RynthTheme.PopOutLabel)) - { - Vector2 logical = ImGuiNET.ImGui.GetWindowPos() / place; - AvaloniaOverlay.PopOutBarFrom(logical.X, logical.Y); - } - ImGuiNET.ImGui.SetItemTooltip("Pop the bar out into its own floating window."); - } - PopBarButtonStyle(); - - // Drawn after the bar buttons' style is popped, so the menu has the normal look. - ScriptsMenu(scripts); - IltMenu(); + // The bar draws only as the ImGui face (ResolveFace), so it pops out as itself. + ImGuiNET.ImGui.SameLine(); + if (IconButton("##popout", iconFont, popped ? PhosphorIcons.ArrowSquareIn : PhosphorIcons.ArrowSquareOut, square, RynthTheme.PopOutLabel)) + SetPoppedOut(!popped); + ImGuiNET.ImGui.SetItemTooltip(popped ? "Dock the bar back into the game window." : "Pop the bar out into its own floating window."); } /// The ILT panels the bar offers now: 0 off Infinite Leaftide or without RynthILT. AC thread. @@ -531,24 +610,14 @@ internal static class ImGuiBar return clicked; } - private static void FacePopup(string popupId, string title, bool hasImGuiFace, float s = 1f) + /// The grip's right-click menu: the bar's size, its rows and "Report a problem". + private static void BarMenu(float s) { - if (!ImGuiNET.ImGui.BeginPopup(popupId)) return; - ImGuiNET.ImGui.TextDisabled(title == FaceKey ? "Bar, docked, shows as" : "Docked, shows as"); - PanelFace current = title == FaceKey ? ResolveFace() : PanelRouter.ResolveDockedFace(title); - for (int i = 0; i < Faces.Length; i++) - { - bool enabled = Faces[i] == PanelFace.Avalonia || hasImGuiFace; - if (ImGuiNET.ImGui.MenuItem(FaceNames[i], "", current == Faces[i], enabled)) - PanelRouter.SetDockedFace(title, Faces[i]); - } - if (!hasImGuiFace) - ImGuiNET.ImGui.TextDisabled("(no ImGui version yet)"); - if (title == FaceKey) - { - BarSizeRows(s); - ReportRow(); - } + if (!ImGuiNET.ImGui.BeginPopup("##bar_menu")) return; + ImGuiNET.ImGui.TextDisabled("RynthCore bar"); + BarSizeRows(s); + BarLayoutRows(s); + ReportRow(); ImGuiNET.ImGui.EndPopup(); } @@ -587,6 +656,49 @@ internal static class ImGuiBar ImGuiNET.ImGui.SetItemTooltip("Back to normal size"); } + /// + /// The grip menu's Rows and Icons per row steppers (BarLayout, header). Icons per row runs + /// 2..30 then No limit; its "-" from No limit caps one below what a row shows now. + /// + private static void BarLayoutRows(float s) + { + RowSettings cur = RowLayout; + ImGuiNET.ImGui.Separator(); + int d = Stepper("##br_rows", "Rows", cur.Rows.ToString(CultureInfo.InvariantCulture), + cur.Rows > BarLayout.MinRows, cur.Rows < BarLayout.MaxRows, "Fewer rows", "More rows", s); + if (d != 0) SetRowLayout(cur.Rows + d, cur.MaxPerRow); + d = Stepper("##br_max", "Icons per row", BarLayout.DescribeMaxPerRow(cur.MaxPerRow), + cur.MaxPerRow != BarLayout.MinPerRow, cur.MaxPerRow != BarLayout.NoLimit, + "Fewer icons per row (more rows when the bar has more icons)", "More icons per row (past 30: no limit)", s); + if (d != 0) SetRowLayout(cur.Rows, BarLayout.StepMaxPerRow(cur.MaxPerRow, d, ShownPerRow)); + } + + /// A label, then - and + buttons and the value (the bar size row's look). -1, 0 or +1 for the click. + private static int Stepper(string id, string label, string value, bool canDown, bool canUp, string downTip, string upTip, float s) + { + float btn = ButtonSize * s; + ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui14); + uint text = ImGuiNET.ImGui.GetColorU32(ImGuiCol.Text); + int delta = 0; + + ImGuiNET.ImGui.TextUnformatted(label); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero); + ImGuiNET.ImGui.BeginDisabled(!canDown); + if (IconButton(id + "_down", iconFont, PhosphorIcons.Minus, new Vector2(btn, btn), text)) delta = -1; + ImGuiNET.ImGui.EndDisabled(); + ImGuiNET.ImGui.SetItemTooltip(downTip); + ImGuiNET.ImGui.SameLine(0, 4 * s); + ImGuiNET.ImGui.BeginDisabled(!canUp); + if (IconButton(id + "_up", iconFont, PhosphorIcons.Plus, new Vector2(btn, btn), text)) delta = 1; + ImGuiNET.ImGui.EndDisabled(); + ImGuiNET.ImGui.SetItemTooltip(upTip); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.SameLine(0, 8 * s); + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextUnformatted(value); + return delta; + } + /// The grip menu's "Report a problem" entry (Report/ProblemReport.cs). private static void ReportRow() { @@ -603,8 +715,8 @@ internal static class ImGuiBar ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 2f); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, RynthTheme.BarButton); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, RynthTheme.Argb(0xFF2A3850)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonActive, RynthTheme.Argb(0xFF34466A)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, RynthTheme.FrameHover); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonActive, RynthTheme.FrameActive); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, RynthTheme.BarButtonBorder); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, RynthTheme.BarText); } @@ -641,14 +753,13 @@ internal static class ImGuiBar if (!LauncherOnly.Contains(title)) { string icon = IconFor(title, out bool letter); - list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, - title + "\nRight-click: which face shows it docked.")); + list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title)); } foreach (string title in ImGuiOnlyBarPanels) if (ImGuiPanelHost.HasFace(title) && !LauncherOnly.Contains(title)) { string icon = IconFor(title, out bool letter); - list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, title, ImGuiOnly: true)); + list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title)); } // Plugin script windows that asked for a button (RynthSort, Oracle, ...): after the // engine's own. Only while the plugin is loaded and has submitted the window. @@ -659,9 +770,9 @@ internal static class ImGuiBar string icon = IconFor(title, out bool letter); string id = "##bar_sw" + w.Hash.ToString("X8"); // The tooltip goes through SetItemTooltip, a format function: the plugin's text with '%' doubled. - list.Add(new ButtonInfo(title, id, id + "_face", icon, letter, title.Replace("%", "%%"), ImGuiOnly: true, Window: w)); + list.Add(new ButtonInfo(title, id, icon, letter, title.Replace("%", "%%"), Window: w)); } _buttons = list.ToArray(); - _tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face and size. Ctrl+wheel over the bar: size."; + _tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar size and rows. Ctrl+wheel over the bar: size."; } } diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs index 66af08c..47834c3 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -77,6 +77,7 @@ internal static unsafe class ImGuiPopOuts public readonly List Input = new(32); public readonly bool[] Buttons = new bool[3]; public long LastFrameTicks; + public int ThemeApplied; // RynthTheme.Version this context's style was coloured at public int HotFrames = HotFramesAfterInput; public bool WantTextInput, DropTextFocus; public bool Hovered; @@ -484,6 +485,7 @@ internal static unsafe class ImGuiPopOuts _current = pop; ImGuiTextFocus.BeginFrame(); + RynthTheme.RefreshStyle(ref pop.ThemeApplied); // this context's base style follows a theme change ImGuiNET.ImGui.NewFrame(); started = true; if (pop.DropTextFocus) diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs index 1b80d1e..4893ca2 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs @@ -84,8 +84,9 @@ internal static class MonsterHud private static readonly uint BarBack = C(0xE00C1118), BarEdge = C(0xFF000000), Tick = C(0x70000000), Shine = C(0x38FFFFFF), Trail = C(0xFFF3E2A8), Gold = C(0xFFE6C766), GoldBright = C(0xFFFFD966), GoldGlow = C(0x55E6C766), NameText = C(0xFFF2E8DC), AttackerText = C(0xFFFF8A7A), Outline = C(0xE6000000), - HpText = C(0xFFFFFFFF), DimText = C(0xFFB8C4D0), BadgeBack = C(0xD0101820), BadgeEdge = C(0xFF34587A), - Leader = C(0x60FFFFFF), HoverEdge = C(0xC0FFFFFF), UnknownFill = C(0xFF5E8A6A), IconBack = C(0xD80B1219), OthersTint = C(0xFFFF8A7A); + HpText = C(0xFFFFFFFF), DimText = C(0xFFB8C4D0), BadgeBack = C(0xD0101820), Leader = C(0x60FFFFFF), + HoverEdge = C(0xC0FFFFFF), UnknownFill = C(0xFF5E8A6A), IconBack = C(0xD80B1219), OthersTint = C(0xFFFF8A7A); + private static uint BadgeEdge => RynthTheme.Border; private static readonly Vector3 HpHigh = new(0x3F, 0xD0, 0x6A), HpMid = new(0xE8, 0xB3, 0x33), HpLow = new(0xE0, 0x4A, 0x4A); // Element colours, shared by the "weak to" pill and the vulnerability icons. diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs index d8a908d..60f66f1 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs @@ -16,8 +16,12 @@ namespace RynthCore.Engine.ImGuiBackend.Hud; internal static class MonsterHudSettingsUi { - private static readonly uint Amber = C(0xFFE8B333), TextDim = C(0xFFF2F7FC), Mute = C(0xFFB8C8D8), - ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), BtnBord = C(0xFF34587A), BtnFill = C(0xFF16283A); + private static readonly uint ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455); + private static uint Amber => RynthTheme.Highlight; + private static uint TextDim => RynthTheme.Text; + private static uint Mute => RynthTheme.TextMuted; + private static uint BtnBord => RynthTheme.Border; + private static uint BtnFill => RynthTheme.Button; private static uint C(uint argb) => RynthTheme.Argb(argb); private static bool Loading(float w) diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs index dc4136d..bd5c87c 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs @@ -46,8 +46,9 @@ internal static class PlayerPlate private const float HeadHeight = 2.05f; // metres above the feet (human-sized characters) private const float FirstPersonDistance = 1.3f; // camera this close to the head = first person - private static readonly uint HealthCol = MonsterHud.C(0xFFE04A4A), StaminaCol = MonsterHud.C(0xFFE8B333), - ManaCol = MonsterHud.C(0xFF3F8FE8), NameCol = MonsterHud.C(0xFFF2E8DC), NumCol = MonsterHud.C(0xFFFFFFFF); + private static readonly uint HealthCol = MonsterHud.C(0xFFE04A4A), ManaCol = MonsterHud.C(0xFF3F8FE8), + NameCol = MonsterHud.C(0xFFF2E8DC), NumCol = MonsterHud.C(0xFFFFFFFF); + private static uint StaminaCol => RynthTheme.Highlight; private struct BarState { @@ -217,7 +218,8 @@ internal static class PlayerPlate Paint(dl, ref l, left, y); } - private static readonly uint FrameCol = MonsterHud.C(0xB026D9E6), FrameHot = MonsterHud.C(0xFF26D9E6); + private static uint FrameCol => RynthTheme.WithAlpha(RynthTheme.Accent, 0xB0); + private static uint FrameHot => RynthTheme.Accent; /// 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) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index 4ddd41d..9ebf691 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -65,11 +65,14 @@ internal sealed class ChatFace : IImGuiPanel new PanelSpec(new Vector2(460, 300), new Vector2(260, 140), Background: 0, EdgeToEdge: true, GripInBody: true), () => new ChatFace()); - private static readonly uint TabActive = RynthTheme.Argb(0xFF264C59), TabAdd = RynthTheme.Argb(0xFF7AE09A), - InputBg = RynthTheme.Argb(0xFF0A121A), InputBorder = RynthTheme.Argb(0xFF264C59), InputActive = RynthTheme.Argb(0xFFFFD700), - SelBg = RynthTheme.Argb(0x663A6EA5), FlashBg = RynthTheme.Argb(0xE0264C59), TellBg = RynthTheme.Argb(0xFF0E2E3A), + private static readonly uint TabAdd = RynthTheme.Argb(0xFF7AE09A), InputActive = RynthTheme.Argb(0xFFFFD700), + SelBg = RynthTheme.Argb(0x663A6EA5), TellBg = RynthTheme.Argb(0xFF0E2E3A), TsColor = RynthTheme.Argb(0xFF6F8397), MentionBg = RynthTheme.Argb(0x33FFC857), BadgeBg = RynthTheme.Argb(0xFF1F6F7A), BadgeMention = RynthTheme.Argb(0xFFB8860B); + private static uint TabActive => RynthTheme.AccentFill; + private static uint InputBg => RynthTheme.BoxBg; + private static uint InputBorder => RynthTheme.AccentFill; + private static uint FlashBg => RynthTheme.WithAlpha(RynthTheme.AccentFill, 0xE0); private const float StickThreshold = 24f; // Visible lines for the current tab + search, with wrapped heights; _lay diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 17c431e..7c75c41 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -37,8 +37,8 @@ internal sealed class ChatFiltersFace : IImGuiPanel new PanelSpec(new Vector2(600, 460), new Vector2(440, 260), EdgeToEdge: true, GripInBody: true), () => new ChatFiltersFace()); - private static readonly uint AddBg = RynthTheme.Argb(0xFF264C59), CardBg = RynthTheme.Argb(0xFF0E1822), - FocusBorder = RynthTheme.Argb(0xFFFFD700); + private static readonly uint CardBg = RynthTheme.Argb(0xFF0E1822), FocusBorder = RynthTheme.Argb(0xFFFFD700); + private static uint AddBg => RynthTheme.AccentFill; private sealed class Buffers { diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs index 6c41020..8b8c4f8 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs @@ -57,10 +57,15 @@ internal sealed class DamageDetailFace : IImGuiPanel } private static uint C(uint argb) => RynthTheme.Argb(argb); - private static readonly uint Teal = C(0xFF26D9E6), Gold = C(0xFFFFD16A), Dim = C(0xFFC8D4E0), White = C(0xFFF2F7FC), - EntryBg = C(0xFF16283A), EntryBorder = C(0xFF34587A), ToggleOn = C(0xFF33CC66), ToggleOff = C(0xFF4D4D4D), - BarBg = C(0xFF16222E), Good = C(0xFF33CC66), Mid = C(0xFFE8B333), Bad = C(0xFFE05A5A), DeleteBg = C(0xFF6E1E1E), + private static readonly uint Gold = C(0xFFFFD16A), ToggleOn = C(0xFF33CC66), ToggleOff = C(0xFF4D4D4D), + BarBg = C(0xFF16222E), Good = C(0xFF33CC66), Bad = C(0xFFE05A5A), DeleteBg = C(0xFF6E1E1E), DeleteBorder = C(0xFFFF8A8A); + private static uint Teal => RynthTheme.Accent; + private static uint Dim => RynthTheme.MuteAlt; + private static uint White => RynthTheme.Text; + private static uint EntryBg => RynthTheme.Button; + private static uint EntryBorder => RynthTheme.Border; + private static uint Mid => RynthTheme.Highlight; private MonsterDetail? _detail; private long _seenVersion = -1, _seenRulesVersion = -1; diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs index 19e4110..65c3152 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs @@ -45,11 +45,17 @@ internal sealed class DamageFace : IImGuiPanel () => new DamageFace()); // ── Palette (MonsterDamagePanel's, a little brighter) ─────────────── - private static readonly uint Teal = C(0xFF26D9E6), Gold = C(0xFFFFD16A), Dim = C(0xFFC8D4E0), - White = C(0xFFF2F7FC), HeaderBg = C(0xFF121C26), PanelBg = C(0xF0081018), RowBg = C(0x40203040), - PickerBg = C(0xFF0A141E), PickSel = C(0xFF1A2E42), EntryBg = C(0xFF16283A), EntryBorder = C(0xFF34587A), - SearchBg = C(0xFF16222E), ToggleOn = C(0xFF33CC66), ToggleOff = C(0xFF4D4D4D), DeleteRed = C(0xFFFF8A8A), - FilterBg = C(0xFF203A52), TargetBg = C(0x5026D9E6), NearbyBg = C(0x3833CC66), NearbyBar = C(0xFF33CC66), ResetBg = C(0xFF5A2020), ResetBorder = C(0xFFFF8A8A), ClearBg = C(0xFF6E1E1E); + private static readonly uint Gold = C(0xFFFFD16A), HeaderBg = C(0xFF121C26), PanelBg = C(0xF0081018), + RowBg = C(0x40203040), PickerBg = C(0xFF0A141E), SearchBg = C(0xFF16222E), ToggleOn = C(0xFF33CC66), + ToggleOff = C(0xFF4D4D4D), DeleteRed = C(0xFFFF8A8A), FilterBg = C(0xFF203A52), NearbyBg = C(0x3833CC66), + NearbyBar = C(0xFF33CC66), ResetBg = C(0xFF5A2020), ResetBorder = C(0xFFFF8A8A), ClearBg = C(0xFF6E1E1E); + private static uint Teal => RynthTheme.Accent; + private static uint Dim => RynthTheme.MuteAlt; + private static uint White => RynthTheme.Text; + private static uint PickSel => RynthTheme.Selected; + private static uint EntryBg => RynthTheme.Button; + private static uint EntryBorder => RynthTheme.Border; + private static uint TargetBg => RynthTheme.WithAlpha(RynthTheme.Accent, 0x50); private static uint C(uint argb) => RynthTheme.Argb(argb); // Column widths (the Avalonia grid's) and their left edges. @@ -521,7 +527,7 @@ internal sealed class DamageFace : IImGuiPanel if (all == null || count == 0) { ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), all == null + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), all == null ? " Monster rules not loaded yet." : " No name rules yet: add one below."); } else @@ -708,7 +714,7 @@ internal sealed class DamageFace : IImGuiPanel bool filtering = _filterWid != 0 || _searchText.Length > 0; bool anyData = _view.Rows.Exists(r => !r.IsDefault); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), anyData && filtering + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), anyData && filtering ? " No monsters match the current filter." : " No monsters yet: fight some and they show up here."); } @@ -1006,16 +1012,16 @@ internal sealed class DamageFace : IImGuiPanel Rule? view = RuleFor(name, out bool custom); bool isDefault = name.Equals("Default", StringComparison.OrdinalIgnoreCase); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), "Debuffs · " + name); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), "Debuffs · " + name); ImGuiNET.ImGui.PopFont(); if (view == null) { - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), "Monster rules not loaded yet."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), "Monster rules not loaded yet."); ImGuiNET.ImGui.EndPopup(); return; } ImGuiNET.ImGui.PushTextWrapPos(0); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(custom || isDefault ? 0xFFFFD16A : 0xFFC8D4E0), + ImGuiNET.ImGui.TextColored((custom || isDefault ? RynthTheme.Vec(0xFFFFD16A) : RynthTheme.VecOf(RynthTheme.MuteAlt)), isDefault ? "Every monster set to Default uses these." : custom ? "This monster's own debuffs." : "Following Default: a change here gives it its own."); ImGuiNET.ImGui.PopTextWrapPos(); @@ -1031,7 +1037,7 @@ internal sealed class DamageFace : IImGuiPanel ImGuiNET.ImGui.SetItemTooltip(tip); } - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), "Extra Vuln"); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), "Extra Vuln"); ImGuiNET.ImGui.SameLine(); string ex = string.IsNullOrEmpty(view.ExVuln) ? "None" : view.ExVuln; ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("Lightning").X + 40); @@ -1048,7 +1054,7 @@ internal sealed class DamageFace : IImGuiPanel ImGuiNET.ImGui.SetItemTooltip("A vulnerability of another element, on top of Vuln (which follows the attack's element)."); ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), "Your own (comma separated):"); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), "Your own (comma separated):"); ImGuiNET.ImGui.SetNextItemWidth(-1); bool enter = ImGuiNET.ImGui.InputText("##db_custom", _customBuf, (uint)_customBuf.Length, ImGuiInputTextFlags.EnterReturnsTrue); if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) @@ -1316,9 +1322,9 @@ internal sealed class DamageFace : IImGuiPanel if (ropen) { ImGuiNET.ImGui.PushTextWrapPos(0); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "Remove " + _removeName + "?"); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Remove " + _removeName + "?"); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Its learned numbers and your settings for it (weapon, offhand, pet, HP) are deleted. It comes back if you meet it again."); ImGuiNET.ImGui.PopTextWrapPos(); ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); @@ -1354,9 +1360,9 @@ internal sealed class DamageFace : IImGuiPanel if (open) { ImGuiNET.ImGui.PushTextWrapPos(0); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "Reset ALL learned damage statistics?"); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Reset ALL learned damage statistics?"); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Monster names and your settings (manual HP, weapon/offhand picks, debuffs) are KEPT — only the learned damage, crit, casts-to-kill, kills and HP are cleared. This cannot be undone."); ImGuiNET.ImGui.PopTextWrapPos(); ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); diff --git a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs index 068c419..8e5013b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs @@ -1,25 +1,36 @@ // ============================================================================ // 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 RynthAi dashboard's slide-out drawers (Tom 2026-10-05: drawers on the +// dashboard's edges; only the vitals / target bars stay at its bottom). One +// tab per drawer, stacked down the dashboard's left or right edge; a click +// slides that drawer's panel out on its tab's side. One drawer is open per +// side, so a left and a right drawer can be out together. // -// 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, -// Patrol and Mini Remote (RynthAiFace.Drawers.cs). +// Sides (2026-10-14): each drawer starts on a side (StartsRight) and a +// dashboard drawer can be moved to the other one from its tab's right-click +// (saved with the dashboard's state). The tabs never switch sides on their +// own any more; a panel with no room on its side stays on the screen over +// the dashboard instead. // -// 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). +// The look: a closed tab is a button with its drawer's icon that peeks out a +// little on hover; the open tab joins its panel (same background, a teal +// edge, an accent bar against the dashboard), and the panel has a teal +// outline. Panels slide out with an ease-out. +// +// The mechanics live here (tabs, slide, side, placement, the windows); each +// drawer only draws its panel (DashboardDrawer.DrawPanel) and says how big it +// is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files, Patrol, Mini +// Remote (RynthAiFace.Drawers.cs) and My settings (QuickSettingsDrawer.cs); +// RynthChat's Channels (ChatFace.cs) uses the same host. +// +// One top-level ImGui window per side, begun from inside the dashboard's Draw +// and placed against the dashboard's window every frame, so the drawers +// follow the dashboard (and go 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). // ============================================================================ @@ -31,7 +42,7 @@ using RynthCore.Engine.UI; namespace RynthCore.Engine.ImGuiBackend.Panels; -/// One drawer on the dashboard's left edge: its tab's look and its panel. +/// One drawer on the dashboard's 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). @@ -43,7 +54,7 @@ internal abstract class DashboardDrawer 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. + /// The closed tab's tooltip; : the drawer is on the right. public abstract string TabTooltip(bool right); /// Panel size in pixels at text scale . @@ -60,10 +71,22 @@ internal abstract class DashboardDrawer public abstract bool SavedOpen { get; } public abstract void SaveOpen(bool open); - private string? _tabId, _hideTip; + /// The side the drawer starts on (false: left). + public virtual bool StartsRight => false; + /// The tab's right-click can move it to the other side (and the move is saved). + public virtual bool CanMove => false; + /// Moved to the side it doesn't start on. + public virtual bool Moved => false; + public virtual void SaveMoved(bool moved) { } + + /// The side it is on now. + public bool OnRight => StartsRight != Moved; + + private string? _tabId, _hideTip, _sideMenuId; /// The tab's ImGui id and open tooltip (built once). internal string TabId => _tabId ??= "##drawer_tab_" + Key; internal string HideTip => _hideTip ??= "Hide the " + Name + "."; + internal string SideMenuId => _sideMenuId ??= "##drawer_side_" + Key; protected void Close() => Host?.Close(this); @@ -77,8 +100,11 @@ internal abstract class DashboardDrawer // ── 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 static uint DTeal => RynthTheme.Accent; + protected static uint DMute => RynthTheme.TextMuted; + protected static uint DWhite => RynthTheme.Text; + protected static uint DBtnFill => RynthTheme.Button; + protected static uint DBtnBord => RynthTheme.Border; protected const float Pad = 6, TitleH = 18; /// Paints the panel's background and title row; returns the y under the title (pixels). @@ -86,7 +112,7 @@ internal abstract class DashboardDrawer { 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); + dl.AddRect(origin, origin + new Vector2(panelW, panelH), DTeal, 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); @@ -108,19 +134,37 @@ internal abstract class DashboardDrawer } } -/// The tabs and the one open drawer beside the RynthAi dashboard. +/// A RynthAi dashboard drawer: movable to the other side, the side saved with the dashboard's state. +internal abstract class RynthAiDrawer : DashboardDrawer +{ + public override bool CanMove => true; + public override bool Moved => RynthAiDashboardState.DrawerMoved(Key); + public override void SaveMoved(bool moved) => RynthAiDashboardState.SetDrawerMoved(Key, moved); +} + +/// The tabs and the open drawers beside the RynthAi dashboard (one open per side). internal sealed class DashboardDrawers { - private readonly string WindowId; // "##rynthai_drawers" for the dashboard; the chat has its own - private const float SlideSeconds = 0.14f; + private readonly string[] _windowIds; // left, right ("##rynthai_drawers" for the dashboard; the chat has its own) + private const float SlideSeconds = 0.16f; - 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 static uint Teal => RynthTheme.Accent; + private static uint Mute => RynthTheme.TextMuted; + private static uint White => RynthTheme.Text; + private static uint BtnFill => RynthTheme.Button; + private static uint BtnBord => RynthTheme.Border; + private static uint ShellBg => RynthTheme.Background; 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 + + /// One edge's drawers: which is open, which draws, how far it has slid. + private sealed class Side + { + public int Open = -1; // the drawer open (or opening); -1 none + public int Shown = -1; // the drawer whose panel draws (a closing one until it has slid in) + public float T; // slide position of Shown, 0 closed .. 1 open + } + private readonly Side[] _sides = { new(), new() }; private bool _loaded; public DashboardDrawers(params DashboardDrawer[] drawers) : this("##rynthai_drawers", drawers) { } @@ -128,14 +172,20 @@ internal sealed class DashboardDrawers /// A drawer set beside another panel (RynthChat's channels): its own window id. public DashboardDrawers(string windowId, params DashboardDrawer[] drawers) { - WindowId = windowId; + _windowIds = new[] { windowId, windowId + "_right" }; _drawers = drawers; foreach (DashboardDrawer d in drawers) d.Host = this; } - public bool IsOpen(DashboardDrawer d) => _open >= 0 && _drawers[_open] == d; + private Side SideOf(DashboardDrawer d) => _sides[d.OnRight ? 1 : 0]; - /// Opens (closing the open one), or closes it when it is the open one. + public bool IsOpen(DashboardDrawer d) + { + Side s = SideOf(d); + return s.Open >= 0 && _drawers[s.Open] == d; + } + + /// Opens (closing the one open on its side), or closes it when it is open. public void Toggle(DashboardDrawer d) { if (IsOpen(d)) Close(d); @@ -146,25 +196,41 @@ internal sealed class DashboardDrawers { EnsureLoaded(); int i = Array.IndexOf(_drawers, d); - if (i < 0 || i == _open) return; - if (_open >= 0) _drawers[_open].SaveOpen(false); - _open = i; + Side s = SideOf(d); + if (i < 0 || i == s.Open) return; + if (s.Open >= 0) _drawers[s.Open].SaveOpen(false); + s.Open = i; d.SaveOpen(true); - if (_shown != i) + if (s.Shown != i) { - // Another drawer was out (or sliding in): this one slides out from closed. - _shown = i; - _t = 0f; + // Another drawer was out on this side (or sliding in): this one slides out from closed. + s.Shown = i; + s.T = 0f; } } public void Close(DashboardDrawer d) { if (!IsOpen(d)) return; - _open = -1; + SideOf(d).Open = -1; d.SaveOpen(false); } + /// Moves to the other side; an open drawer opens again there. + public void Move(DashboardDrawer d) + { + if (!d.CanMove) return; + EnsureLoaded(); + bool wasOpen = IsOpen(d); + int i = Array.IndexOf(_drawers, d); + Side from = SideOf(d); + if (wasOpen) from.Open = -1; + if (from.Shown == i) { from.Shown = -1; from.T = 0f; } + d.Update(false); + d.SaveMoved(!d.Moved); + if (wasOpen) { d.SaveOpen(false); Open(d); } + } + /// The dashboard closed: every drawer drops its subscriptions. AC thread. public void Detach() { @@ -175,19 +241,18 @@ internal sealed class DashboardDrawers { if (_loaded) return; _loaded = true; - // The first drawer saved open wins (one at a time); any other saved open is closed. + // The first drawer saved open on each side wins (one per side); any other saved open is closed. for (int i = 0; i < _drawers.Length; i++) { if (!_drawers[i].SavedOpen) continue; - if (_open < 0) _open = i; + Side s = SideOf(_drawers[i]); + if (s.Open < 0) { s.Open = i; s.Shown = i; s.T = 1f; } 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 + /// Draws the tabs and the open drawers. 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() @@ -200,42 +265,51 @@ internal sealed class DashboardDrawers } EnsureLoaded(); + Vector2 dashPos = ImGuiNET.ImGui.GetWindowPos(), dashSize = ImGuiNET.ImGui.GetWindowSize(); + float k = MathF.Max(1f, ImGuiFonts.Get(UiFont.Dash11).FontSize / 11f); + DrawSide(0, dashPos, dashSize, k); + DrawSide(1, dashPos, dashSize, k); + } + + private void DrawSide(int sideIdx, Vector2 dashPos, Vector2 dashSize, float k) + { + bool right = sideIdx == 1; + Side side = _sides[sideIdx]; + int n = 0; + foreach (DashboardDrawer d in _drawers) if (d.OnRight == right) n++; + if (n == 0) { side.Open = side.Shown = -1; return; } + // Slide. - float target = _open >= 0 && _open == _shown ? 1f : 0f; - if (_t != target) + float target = side.Open >= 0 && side.Open == side.Shown ? 1f : 0f; + if (side.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); + side.T = target > side.T ? MathF.Min(1f, side.T + step) : MathF.Max(0f, side.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); + if (side.T <= 0f && side.Open < 0) side.Shown = -1; + float u = 1f - side.T; + float ease = 1f - u * u * u; // ease-out: quick to start, settling at the end + bool showing = side.Shown >= 0 && ease > 0.001f; + for (int i = 0; i < _drawers.Length; i++) + if (_drawers[i].OnRight == right) _drawers[i].Update(showing && i == side.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; + float tabW = 17 * k, tabGap = 3 * k, tabTop = 4 * k, peek = 3 * 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 tabH = MathF.Max(20 * k, MathF.Min(40 * k, (dashSize.Y - 2 * tabTop - (n - 1) * tabGap) / 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 panelW = showing ? _drawers[side.Shown].Width(k) : 0; + float panelH = showing ? _drawers[side.Shown].Height(k) : 0; float shown = showing ? panelW * ease : 0; + float outer = MathF.Max(shown, peek); // room beyond the tabs: the panel, or a hovered tab's peek - float winX = right ? dashRight : dashPos.X - tabW - shown; - float winW = tabW + shown; + float dashRight = dashPos.X + dashSize.X; float tabX = right ? dashRight : dashPos.X - tabW; - // Neither side has room (a very wide dashboard): keep it on the screen, over the dashboard. + float winX = right ? tabX : tabX - outer; + float winW = tabW + outer; + // No room on this side (the dashboard against the screen's edge): stay 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); @@ -255,36 +329,40 @@ internal sealed class DashboardDrawers 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); + bool visible = ImGuiNET.ImGui.Begin(_windowIds[sideIdx], WindowFlags); ImGuiNET.ImGui.PopStyleVar(4); try { - if (visible) + if (!visible) return; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash10)); + try { - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash10)); - try + if (showing) { - if (showing) + // The panel's visible part; its content slides with the open edge. + float visX0 = right ? tabX + tabW : tabX - shown; + float contentX = right ? tabX + tabW + shown - panelW : tabX - shown; + Vector2 vMin = new(visX0, winY), vMax = new(visX0 + shown, winY + panelH); + DashboardDrawer d = _drawers[side.Shown]; + ImGuiNET.ImGui.PushClipRect(vMin, vMax, true); + ImGuiNET.ImGui.PushID(d.Key); + try { d.DrawPanel(new Vector2(contentX, winY), panelW, panelH, k); } + finally { - // 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(); - } + 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(); } + int slot = 0; + for (int i = 0; i < _drawers.Length; i++) + { + if (_drawers[i].OnRight != right) continue; + DrawTab(_drawers[i], new Vector2(tabX, tabY + slot * (tabH + tabGap)), new Vector2(tabW, tabH), right, + joined: showing && i == side.Shown && side.Open == i, canPeek: !showing, k); + slot++; + } } + finally { ImGuiNET.ImGui.PopFont(); } } finally { @@ -297,27 +375,66 @@ internal sealed class DashboardDrawers | 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) + /// The open drawer's tab, drawn as part of its panel. + /// No panel is out on this side, so a hovered tab may peek out. + private void DrawTab(DashboardDrawer d, Vector2 pos, Vector2 size, bool right, bool joined, bool canPeek, float k) { bool open = IsOpen(d); var dl = ImGuiNET.ImGui.GetWindowDrawList(); ImGuiNET.ImGui.SetCursorScreenPos(pos); - bool clicked = ImGuiNET.ImGui.InvisibleButton(d.TabId, size); + bool clicked = ImGuiNET.ImGui.InvisibleButton(d.TabId, size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight) + && ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Left); bool hot = ImGuiNET.ImGui.IsItemHovered(); + bool rightClicked = d.CanMove && ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right); // 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)); + ImGuiNET.ImGui.SetTooltip(open ? d.HideTip : d.TabTooltip(right) + (d.CanMove ? MoveHint : "")); if (clicked) Toggle(d); + if (rightClicked) ImGuiNET.ImGui.OpenPopup(d.SideMenuId); - 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); + float edge = 2 * k; // the accent bar against the dashboard + if (joined) + { + // Part of the panel: its background, reaching over the panel's edge so there's no seam, + // a teal outline on the three other sides and an accent bar against the dashboard. + float over = 1.5f * k; + Vector2 a = right ? pos : pos - new Vector2(over, 0), b = right ? pos + size + new Vector2(over, 0) : pos + size; + dl.AddRectFilled(a, b, RynthTheme.RynthAiBackground); + float inner = right ? pos.X : pos.X + size.X; + float outerX = right ? pos.X + size.X + over : pos.X - over; + dl.AddLine(new Vector2(inner, pos.Y), new Vector2(outerX, pos.Y), Teal); + dl.AddLine(new Vector2(inner, pos.Y + size.Y - 1), new Vector2(outerX, pos.Y + size.Y - 1), Teal); + dl.AddRectFilled(new Vector2(right ? inner : inner - edge, pos.Y), new Vector2(right ? inner + edge : inner, pos.Y + size.Y), Teal); + PhosphorIcons.DrawCentered(dl, f10, d.Icon, pos, size, Teal); + } + else + { + // A hovered tab peeks out a little, as if it pulls. + float peek = canPeek && hot ? 2 * k : 0; + Vector2 p = pos + new Vector2(right ? peek : -peek, 0); + uint fill = ImGuiNET.ImGui.IsItemActive() ? FaceKit.Darken(BtnFill) : hot ? FaceKit.Lighten(BtnFill) : BtnFill; + ImDrawFlags corners = right ? ImDrawFlags.RoundCornersRight : ImDrawFlags.RoundCornersLeft; + dl.AddRectFilled(p, p + size, fill, 4 * k, corners); + dl.AddRect(p, p + size, open ? Teal : BtnBord, 4 * k, corners); + PhosphorIcons.DrawCentered(dl, f10, d.Icon, p, size, open ? Teal : hot ? White : Mute); + } + + // Right-click: move the drawer to the other side. + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8 * k, 6 * k)); + bool menu = ImGuiNET.ImGui.BeginPopup(d.SideMenuId); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + if (!menu) return; + try + { + if (ImGuiNET.ImGui.MenuItem(right ? PhosphorIcons.CaretLeft + " Move to the left side" : PhosphorIcons.CaretRight + " Move to the right side")) + Move(d); + } + finally { ImGuiNET.ImGui.EndPopup(); } } + + private const string MoveHint = "\nRight-click: move it to the other side of the dashboard."; } diff --git a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs index 53893c9..3374452 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs @@ -72,12 +72,13 @@ internal sealed class DungeonMapFace : IImGuiPanel // ── Palette (the plugin map's colours, ARGB) ────────────────────────── private const uint CanvasBgArgb = 0xFF0A121F, ToolbarBgArgb = 0xE00A121A; - private static readonly uint CanvasBorder = C(0xFF334D66), Wall = C(0xFF8CCCFF), - PlayerCol = C(0xFF33FF66), Portal = C(0xFFE673FF), PortalRing = C(0xB3FFBFFF), PortalLabel = C(0xFFFFE0FF), - Door = C(0xFFBF8C40), DoorRing = C(0xB3E6BF80), DoorLabel = C(0xFFF2D9A6), - Monster = C(0xFFFF4033), MonsterRing = C(0xB3FF8C80), Npc = C(0xFFFFD933), NpcRing = C(0xB3FFF28C), - CreatureLabel = C(0xFFFFE6E6), Hint = C(0xFF8FA3B8), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A), + private static readonly uint CanvasBorder = C(0xFF334D66), Wall = C(0xFF8CCCFF), PlayerCol = C(0xFF33FF66), + Portal = C(0xFFE673FF), PortalRing = C(0xB3FFBFFF), PortalLabel = C(0xFFFFE0FF), Door = C(0xFFBF8C40), + DoorRing = C(0xB3E6BF80), DoorLabel = C(0xFFF2D9A6), Monster = C(0xFFFF4033), MonsterRing = C(0xB3FF8C80), + Npc = C(0xFFFFD933), NpcRing = C(0xB3FFF28C), CreatureLabel = C(0xFFFFE6E6), Hint = C(0xFF8FA3B8), FloorOn = C(0xFF2673B3), FloorHere = C(0xFF1AA64D); + private static uint ButtonBg => RynthTheme.WithAlpha(RynthTheme.Field, 0xC0); + private static uint ButtonBorder => RynthTheme.Border; private const uint FillFlat = 0x662E8C38, FillUp = 0x668C1F14, FillDown = 0x661A8026, FillVisited = 0xB84D6B94; // Route (ARGB, alpha scaled per floor). private const uint RouteLegArgb = 0xD9FFA733, RoutePointArgb = 0xFFFFC266, RouteActiveArgb = 0xFFFFF04D, diff --git a/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs b/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs index 5820054..4ca8656 100644 --- a/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs +++ b/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs @@ -20,10 +20,18 @@ internal static class FaceKit { private static uint C(uint argb) => RynthTheme.Argb(argb); - public static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Green = C(0xFF33CC66), - Red = C(0xFFE05A5A), Mute = C(0xFFC8D6E4), Text = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), - PanelBg = C(0xFF141F29), RowAlt = C(0xFF101822), BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A), - Selected = C(0xFF1A2E42), StartBg = C(0xFF196119), StopBg = C(0xFF801919), DeleteBg = C(0xFF801A1A); + public static readonly uint Green = C(0xFF33CC66), Red = C(0xFFE05A5A), StartBg = C(0xFF196119), + StopBg = C(0xFF801919), DeleteBg = C(0xFF801A1A); + public static uint Teal => RynthTheme.Accent; + public static uint Amber => RynthTheme.Highlight; + public static uint Mute => RynthTheme.MuteAlt; + public static uint Text => RynthTheme.Text; + public static uint ShellBg => RynthTheme.Background; + public static uint PanelBg => RynthTheme.Field; + public static uint RowAlt => RynthTheme.RowAlt; + public static uint BtnFill => RynthTheme.Button; + public static uint BtnBord => RynthTheme.Border; + public static uint Selected => RynthTheme.Selected; // ── Frame ──────────────────────────────────────────────────────────── diff --git a/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs b/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs index 2ffcf5e..edfa6ac 100644 --- a/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs @@ -26,10 +26,16 @@ internal sealed class HotkeysSettingsUi { public const string TabName = "Hotkeys"; - private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Mute = C(0xFFB8C8D8), - TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), PanelBg = C(0xFF141F29), BtnFill = C(0xFF16283A), - BtnBord = C(0xFF34587A), ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), TabActive = C(0xFF1A2E42), - Warn = C(0xFFFFB347); + private static readonly uint ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), Warn = C(0xFFFFB347); + private static uint Teal => RynthTheme.Accent; + private static uint Amber => RynthTheme.Highlight; + private static uint Mute => RynthTheme.TextMuted; + private static uint TextDim => RynthTheme.Text; + private static uint ShellBg => RynthTheme.Background; + private static uint PanelBg => RynthTheme.Field; + private static uint BtnFill => RynthTheme.Button; + private static uint BtnBord => RynthTheme.Border; + private static uint TabActive => RynthTheme.Selected; private static uint C(uint argb) => RynthTheme.Argb(argb); private const string ChatCommandItem = "Chat command..."; diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index c001ab0..94f036b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -58,9 +58,11 @@ internal sealed partial class InventoryFace : IImGuiPanel private const float Cell = 38, Icon = 32, RowH = 24, PackRowH = 38, ZoneH = 30, StatusH = 20; private const uint AllPacks = 0, WornPacks = 1; // pseudo pack ids (real ids are never 0 or 1) - private static readonly uint CellBg = RynthTheme.Argb(0xFF101822), CellHot = RynthTheme.Argb(0xFF1C3148), - CellSel = RynthTheme.Argb(0xFF26D9E6), StackCol = RynthTheme.Argb(0xFFFFFFFF), StackShadow = RynthTheme.Argb(0xE0000000), - DropHot = RynthTheme.Argb(0xFF1F5A3A), Placeholder = RynthTheme.Argb(0xFF1A2633); + private static readonly uint CellHot = RynthTheme.Argb(0xFF1C3148), StackCol = RynthTheme.Argb(0xFFFFFFFF), + StackShadow = RynthTheme.Argb(0xE0000000), DropHot = RynthTheme.Argb(0xFF1F5A3A), + Placeholder = RynthTheme.Argb(0xFF1A2633); + private static uint CellBg => RynthTheme.RowAlt; + private static uint CellSel => RynthTheme.Accent; private static readonly string[] SortNames = { "Pack order", "Name", "Value", "Burden", "Type", "Stack" }; private static readonly string[] SortLabels = Array.ConvertAll(SortNames, n => PhosphorIcons.SortAscending + " " + n); diff --git a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs index 840d2ec..795b5f9 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs @@ -555,7 +555,7 @@ internal sealed class LuaFace : IImGuiPanel ImGuiNET.ImGui.PushTextWrapPos(0); string text = _data?.Console ?? string.Empty; if (text.Length > 0) ImGuiNET.ImGui.TextUnformatted(text); - if (_note.Length > 0) ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "[panel] " + _note); + if (_note.Length > 0) ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Highlight), "[panel] " + _note); ImGuiNET.ImGui.PopTextWrapPos(); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.PopFont(); diff --git a/src/RynthCore.Engine/ImGui/Panels/MapProjection.cs b/src/RynthCore.Engine/ImGui/Panels/MapProjection.cs new file mode 100644 index 0000000..ab3d69a --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MapProjection.cs @@ -0,0 +1,78 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MapProjection.cs +// The World Map's geometry, with no ImGui in it (tools\WorldMapTilesTests checks it offline): +// map cells (x east, y north, one cell = 24 yards) to screen pixels and back, through the view +// centre, the zoom (pixels per cell) and a rotation. +// +// screen = centre + R(phi) * (dx * scale, -dy * scale), dx, dy = cell - view centre cell +// R(phi) = [cos -sin; sin cos] on a y-down screen (so a positive phi turns the map clockwise) +// +// Rotating with the player: heading is in degrees, 0 = east, 90 = north (AC), so the heading +// direction is (cos h, sin h) in the map; phi = heading - 90 degrees turns it to straight up. +// ============================================================================ + +using System; +using System.Numerics; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal readonly struct MapProjection +{ + public readonly Vector2 Centre; // screen position of the view centre cell + public readonly double CentreX, CentreY; // the view centre, in cells + public readonly float Scale; // screen pixels per cell + public readonly float Cos, Sin; // of the rotation + + public MapProjection(Vector2 centre, double centreX, double centreY, float scale, float phi) + { + Centre = centre; CentreX = centreX; CentreY = centreY; Scale = scale; + Cos = MathF.Cos(phi); Sin = MathF.Sin(phi); + } + + public bool Turned => Sin != 0f; + + /// The rotation that turns the way you face to up, for a heading in degrees (0 = east, 90 = north). + public static float PhiForHeading(float headingDegrees) => (headingDegrees - 90f) * MathF.PI / 180f; + + public Vector2 Project(double cellX, double cellY) + { + float sx = (float)((cellX - CentreX) * Scale), sy = (float)(-(cellY - CentreY) * Scale); + return new Vector2(Centre.X + sx * Cos - sy * Sin, Centre.Y + sx * Sin + sy * Cos); + } + + public void Unproject(Vector2 p, out double cellX, out double cellY) => Unproject(p, Scale, out cellX, out cellY); + + public void Unproject(Vector2 p, float scale, out double cellX, out double cellY) + { + Vector2 d = p - Centre; + float ux = d.X * Cos + d.Y * Sin, uy = -d.X * Sin + d.Y * Cos; + cellX = CentreX + ux / scale; + cellY = CentreY - uy / scale; + } + + /// A map direction (east, north) as a screen direction. + public Vector2 ScreenDir(float east, float north) + { + float sx = east, sy = -north; + return new Vector2(sx * Cos - sy * Sin, sx * Sin + sy * Cos); + } + + /// + /// The view centre (cells) that keeps the cell under where it is + /// when the zoom changes from this projection's scale to . + /// + public (double X, double Y) CentreForZoomAbout(Vector2 screenPoint, float newScale) + { + Unproject(screenPoint, out double mx, out double my); + Vector2 d = screenPoint - Centre; + float ux = d.X * Cos + d.Y * Sin, uy = -d.X * Sin + d.Y * Cos; + return (mx - ux / newScale, my + uy / newScale); + } + + /// The view centre (cells) after dragging the map by pixels. + public (double X, double Y) CentreAfterDrag(Vector2 screenDelta) + { + float ux = screenDelta.X * Cos + screenDelta.Y * Sin, uy = -screenDelta.X * Sin + screenDelta.Y * Cos; + return (CentreX - ux / Scale, CentreY + uy / Scale); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs index 547c199..f8e0399 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs @@ -861,7 +861,7 @@ internal sealed partial class MetaFace private static void Note(string text) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), text); ImGuiNET.ImGui.PopFont(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs index f42ba75..0784967 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs @@ -61,10 +61,11 @@ namespace RynthCore.Engine.ImGuiBackend.Panels; internal sealed partial class MetaFace { // ── Rule text colours (MetaTone) and list lines ────────────────────── - private static readonly uint ToneLabel = C(0xFF8FA9C2), ToneCode = C(0xFF9CC8FF), ToneJoin = C(0xFF4FC3CF), - RowLine = C(0x7034587A), ColLine = C(0x5834587A), GuideLine = C(0x6034587A), CurrentHdr = C(0xFF0D2B36), - // Every other rule a clearly different shade (Tom, 2026-10-11: the old pair was hard to tell apart). + private static readonly uint ToneLabel = C(0xFF8FA9C2), ToneCode = C(0xFF9CC8FF), ToneJoin = C(0xFF4FC3CF), CurrentHdr = C(0xFF0D2B36), // Every other rule a clearly different shade (Tom, 2026-10-11: the old pair was hard to tell apart). StripeA = C(0xFF121B25), StripeB = C(0xFF1C2B3A); + private static uint RowLine => RynthTheme.WithAlpha(RynthTheme.Border, 0x70); + private static uint ColLine => RynthTheme.WithAlpha(RynthTheme.Border, 0x58); + private static uint GuideLine => RynthTheme.WithAlpha(RynthTheme.Border, 0x60); private static uint ToneColor(MetaTone tone) => tone switch { @@ -310,7 +311,7 @@ internal sealed partial class MetaFace if (_groups.Count == 0) { ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " No rules. Click New Rule to add one."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), " No rules. Click New Rule to add one."); return; } diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs index 07ec4f4..c15b4ea 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs @@ -56,7 +56,7 @@ internal sealed partial class MetaFace Separator(w); if (sc == null) { - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " This RynthAi has no Meta Manager (update RynthAi)."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), " This RynthAi has no Meta Manager (update RynthAi)."); return; } @@ -183,9 +183,9 @@ internal sealed partial class MetaFace : sc.LastPollMs == 0 ? "Waiting for the first /myquests." : $"{sc.QuestCount} quest timer(s), /myquests {Span(now - sc.LastPollMs)} ago."; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(sc.ServerDisabled ? 0xFFE8B333 : 0xFFC8D6E4), Fit(poll, w)); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(sc.ServerDisabled ? RynthTheme.Highlight : RynthTheme.MuteAlt), Fit(poll, w)); if (sc.LastSwitch.Length > 0) - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), Fit($"Last: {sc.LastSwitch}{(sc.LastSwitchMs > 0 ? $", {Span(now - sc.LastSwitchMs)} ago" : "")}", w)); ImGuiNET.ImGui.PopFont(); } @@ -195,8 +195,8 @@ internal sealed partial class MetaFace if (sc.Rules.Count == 0) { ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " No rules. New Rule: when a timer runs out, load a meta."); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " The first due rule (top to bottom) wins."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), " No rules. New Rule: when a timer runs out, load a meta."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), " The first due rule (top to bottom) wins."); return; } var dl = ImGuiNET.ImGui.GetWindowDrawList(); @@ -367,7 +367,7 @@ internal sealed partial class MetaFace ScheduleRuleDto r = _schedRule; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}"); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}"); ImGuiNET.ImGui.PopFont(); FieldLabel("When:"); @@ -436,7 +436,7 @@ internal sealed partial class MetaFace if (_schedEdit >= 0) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), "Saving re-arms the rule (clears fired / error)."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), "Saving re-arms the rule (clears fired / error)."); ImGuiNET.ImGui.PopFont(); } ImGuiNET.ImGui.EndChild(); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs index 9ac960b..a78fae8 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs @@ -54,11 +54,18 @@ internal sealed partial class MetaFace : IImGuiPanel () => new MetaFace()); // ── Palette (MetaPanel's, ARGB) ───────────────────────────────────── - private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Green = C(0xFF33CC66), - Red = C(0xFFE04848), Mute = C(0xFFC8D6E4), TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), - PanelBg = C(0xFF141F29), RowAlt = C(0xFF101822), BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A), - Fired = C(0xFF3A1212), BtnOn = C(0xFF0E2E3A), StateHdrA = C(0xFF0E1E30), - DelFill = C(0xFF7A1414), NewFill = C(0xFF0E2E1A), PickSel = C(0xFF1A2E42); + private static readonly uint Green = C(0xFF33CC66), Red = C(0xFFE04848), Fired = C(0xFF3A1212), + BtnOn = C(0xFF0E2E3A), StateHdrA = C(0xFF0E1E30), DelFill = C(0xFF7A1414), NewFill = C(0xFF0E2E1A); + private static uint Teal => RynthTheme.Accent; + private static uint Amber => RynthTheme.Highlight; + private static uint Mute => RynthTheme.MuteAlt; + private static uint TextDim => RynthTheme.Text; + private static uint ShellBg => RynthTheme.Background; + private static uint PanelBg => RynthTheme.Field; + private static uint RowAlt => RynthTheme.RowAlt; + private static uint BtnFill => RynthTheme.Button; + private static uint BtnBord => RynthTheme.Border; + private static uint PickSel => RynthTheme.Selected; private static uint C(uint argb) => RynthTheme.Argb(argb); private static uint Faded(uint abgr) => (abgr & 0x00FFFFFF) | ((abgr >> 25) << 24); // half alpha @@ -464,12 +471,12 @@ internal sealed partial class MetaFace : IImGuiPanel ImGuiNET.ImGui.PopTextWrapPos(); } if (_sourceStale) - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "The meta changed since you started editing. Revert loads it."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Highlight), "The meta changed since you started editing. Revert loads it."); if (_editor == null || !CodeEditor.Available) { ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFCC3333), - "The source editor needs the new cimgui.dll (a full RynthCore deploy). Use the Avalonia face meanwhile: /rc ui Meta avalonia"); + "The source editor needs the new cimgui.dll (a full RynthCore deploy)."); return; } @@ -987,7 +994,7 @@ internal sealed partial class MetaFace : IImGuiPanel private static void FieldLabel(string text) { ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), text); } private static void Separator(float w) diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/MiniMapFace.cs new file mode 100644 index 0000000..0c0c187 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MiniMapFace.cs @@ -0,0 +1,70 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MiniMapFace.cs +// The Mini Map: a small window with the same map as the World Map, following you and turned so the +// way you face is up (both switchable from the right-click menu), without a toolbar. The wheel +// zooms, a drag pans (Follow off), a double click comes back to you; right-click for Follow / +// Rotate / zoom / Go here / Open the World Map. Opened from the RynthNav panel's Mini button. +// Its zoom, Follow and Rotate are its own (WorldMapSettings.Mini); the layers are shared with the +// World Map's Show menu. +// ============================================================================ + +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class MiniMapFace : IImGuiPanel +{ + public const string Title = "Mini Map"; + + public static void Register() + { + ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(290, 310), new Vector2(150, 150), EdgeToEdge: true, GripInBody: true, NoPopOut: true), + () => new MiniMapFace()); + } + + private readonly WorldMapView _view = new(mini: true); + private bool _charsSub; + + public void OnShown() => WorldMapFeeds.Subscribe(); + + public void OnHidden() + { + WorldMapFeeds.Unsubscribe(); + WorldMapFeeds.ReleaseCharacters(ref _charsSub); + } + + public void Draw() + { + WorldMapFeeds.SyncCharacters(ref _charsSub); + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + if (size.X < 40 || size.Y < 40) return; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + try + { + RynthNavStatus? st = UiSources.RynthNav.Current?.Value; + MapPlayer pl = WorldMapView.GatherPlayer(st, UiSources.Radar.Current?.Value); + CharacterRow[]? chars = WorldMapSettings.Characters ? UiSources.Characters.Current?.Value?.Rows : null; + _view.Blocked = null; + _view.Draw(origin + new Vector2(1, 1), origin + size - new Vector2(1, 1), pl, st, chars); + + string tip = _view.HoverText; + if (tip.Length > 0) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(tip); + Vector2 a = origin + new Vector2(6, 6), b = a + ts + new Vector2(10, 6); + if (b.X < origin.X + size.X - 4) + { + dl.AddRectFilled(a, b, RynthTheme.Argb(0xD00A121A), 4); + dl.AddText(a + new Vector2(5, 3), FaceKit.Text, tip); + } + } + WorldMapSettings.FlushIfDue(); + } + finally { ImGuiNET.ImGui.PopFont(); } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs index d1c7f66..5c61b8b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs +++ b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs @@ -216,7 +216,7 @@ internal sealed class TrackerFace : IImGuiPanel private static readonly Vector4 TitleColor = RynthTheme.Vec(0xFFE6B450); private static readonly Vector4 LabelColor = RynthTheme.Vec(0xFF999999); private static readonly uint ResetBg = RynthTheme.Argb(0xFF1A2E40); - private static readonly uint ResetBorder = RynthTheme.Argb(0xFF264C59); + private static uint ResetBorder => RynthTheme.AccentFill; private int _opacity; public void OnShown() diff --git a/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs b/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs new file mode 100644 index 0000000..2db2817 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs @@ -0,0 +1,200 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/QuickSettingsDrawer.cs +// The dashboard's My settings drawer (Tom 2026-10-14): the settings the player +// pinned, drawn with the Settings panel's own rows (SettingsRows.cs), so a +// setting changed here is the same setting, saved the same way. +// +// Pin from any setting's right-click (the Settings panel, the Patrol drawer, +// this drawer) or from the + button here, a searchable list of every setting +// that can be pinned (UI/QuickSettings.cs keeps the pins and their order). +// Here a row's right-click also moves it up or down. Starts on the +// dashboard's right edge; its tab's right-click moves it to the left. +// 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 class QuickSettingsDrawer : RynthAiDrawer +{ + private readonly SettingsRows _rows = new(); + private bool _sub; + private string _filter = string.Empty; + private const string AddPopupId = "##quick_add"; + + // Rows are drawn at the Settings panel's fixed sizes: about this tall each (pixels). + private const float RowH = 28, EmptyH = 70, MinBodyH = 60; + + public override string Key => "quick"; + public override string Icon => PhosphorIcons.SlidersHorizontal; + public override string Name => "My settings drawer"; + public override bool StartsRight => true; + public override bool SavedOpen => RynthAiDashboardState.QuickOpen; + public override void SaveOpen(bool open) => RynthAiDashboardState.SetQuickOpen(open); + + public override string TabTooltip(bool right) => + "My settings: the settings you pinned, to change them without opening Settings.\n" + + "Pin one by right-clicking it in Settings, or with + in the drawer. Click to slide it out."; + + public override float Width(float k) => 300 * k; + + public override float Height(float k) + { + int pins = 0; + foreach (string key in QuickSettings.Pins) + if (QuickSettings.RowOf(key) != null) pins++; + float body = pins == 0 ? EmptyH : MathF.Max(MinBodyH, pins * RowH + 6); + float frame = (Pad + TitleH + 4 + Pad) * k; + float screen = ImGuiNET.ImGui.GetIO().DisplaySize.Y; + float max = screen > 1 ? MathF.Max(120 * k, screen - 8 * k) : 900 * k; + return MathF.Min(frame + body, max); + } + + public override void Update(bool showing) + { + if (showing == _sub) return; + _sub = showing; + if (showing) { UiSources.Settings.Subscribe(); UiSources.Settings.RequestRefresh(); } + else UiSources.Settings.Unsubscribe(); + } + + public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) + { + float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.SlidersHorizontal, "MY SETTINGS", null, "Hide My settings"); + float x = origin.X + Pad * k, w = panelW - 2 * Pad * k; + + // + beside the close button: pick settings to pin. + Vector2 btn = new(18 * k, 16 * k); + Vector2 addPos = new(x + w - 2 * btn.X - 3 * k, origin.Y + Pad * k + (TitleH * k - btn.Y) * 0.5f); + if (FaceKit.IconButton("##quick_plus", PhosphorIcons.Plus, addPos, btn, DTeal, DBtnFill, border: DBtnBord, font: UiFont.Dash10)) + { + _filter = string.Empty; + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(addPos.X + btn.X, addPos.Y + btn.Y + 2 * k), ImGuiCond.Always, new Vector2(1, 0)); + ImGuiNET.ImGui.OpenPopup(AddPopupId); + } + ImGuiNET.ImGui.SetItemTooltip("Pin or unpin settings"); + AddPopup(k); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + Vector2 size = new(w, MathF.Max(1, origin.Y + panelH - Pad * k - y)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + bool open = ImGuiNET.ImGui.BeginChild("##quick_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (!open) return; + _rows.Sync(); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 0)); + try + { + float rw = ImGuiNET.ImGui.GetContentRegionAvail().X - 2 * k; + string[] pins = QuickSettings.Pins; + int drawn = 0; + for (int i = 0; i < pins.Length; i++) + { + SettingRow? row = QuickSettings.RowOf(pins[i]); + if (row == null) continue; + drawn++; + if (!row.IsVisible(_rows.Data)) continue; + ImGuiNET.ImGui.PushID(pins[i]); + _rows.DrawRow(row, rw, extraMenu: MoveItems); + ImGuiNET.ImGui.PopID(); + } + if (drawn == 0) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, DMute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + rw); + ImGuiNET.ImGui.TextUnformatted("Pin the settings you change most. Right-click a setting in Settings (or in the Patrol drawer) " + + "and pick Pin to My settings, or click + above."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } + } + finally + { + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopFont(); + } + } + finally { ImGuiNET.ImGui.EndChild(); } + } + + /// A pinned row's right-click, after Remove: Move up / Move down. + private static void MoveItems(string key) + { + string[] pins = QuickSettings.Pins; + int i = Array.IndexOf(pins, key); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.CaretUp + " Move up", null, false, i > 0)) QuickSettings.Move(key, -1); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.CaretDown + " Move down", null, false, i >= 0 && i < pins.Length - 1)) QuickSettings.Move(key, +1); + } + + /// Every setting that can be pinned, by tab, with a search box; a click pins or unpins it. + private void AddPopup(float k) + { + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(320 * k, 420 * k)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, RynthTheme.Background); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, DTeal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8 * k, 6 * k)); + bool open = ImGuiNET.ImGui.BeginPopup(AddPopupId); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + try + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + ImGuiNET.ImGui.SetNextItemWidth(-1); + if (ImGuiNET.ImGui.IsWindowAppearing()) ImGuiNET.ImGui.SetKeyboardFocusHere(); + ImGuiNET.ImGui.InputTextWithHint("##quick_search", "Search settings", ref _filter, 64); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.BeginChild("##quick_list", new Vector2(0, 0)); + string filter = _filter.Trim(); + foreach (SettingsTab tab in SettingsSchema.Tabs) + { + bool header = false; + string section = ""; + foreach (SettingRow row in tab.Rows) + { + if (row.Kind == SettingKind.Section) { section = row.Label.Trim(); continue; } + string? key = QuickSettings.KeyOf(row); + if (key == null) continue; + string label = row.Label.Trim(); + if (filter.Length > 0 && label.IndexOf(filter, StringComparison.OrdinalIgnoreCase) < 0 + && section.IndexOf(filter, StringComparison.OrdinalIgnoreCase) < 0 + && tab.Name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) < 0) + continue; + if (!header) + { + header = true; + ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Highlight), tab.Name); + } + bool pinned = QuickSettings.IsPinned(key); + ImGuiNET.ImGui.PushID(key); + // Stays open, so several can be pinned in one go; the section shows dimmed at the right. + if (ImGuiNET.ImGui.Selectable((pinned ? PhosphorIcons.Check : " ") + " " + label, pinned, ImGuiSelectableFlags.NoAutoClosePopups)) + QuickSettings.SetPinned(key, !pinned); + if (row.Tooltip != null) ImGuiNET.ImGui.SetItemTooltip(row.Tooltip); + if (section.Length > 0) + { + Vector2 max = ImGuiNET.ImGui.GetItemRectMax(), min = ImGuiNET.ImGui.GetItemRectMin(); + float sw = ImGuiNET.ImGui.CalcTextSize(section).X; + float sx = MathF.Max(min.X + ImGuiNET.ImGui.CalcTextSize(" " + label).X + 24, max.X - sw - 4); + if (sx + sw <= max.X) + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(sx, min.Y), RynthTheme.Argb(0xFF6E8197), section); + } + ImGuiNET.ImGui.PopID(); + } + } + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopFont(); + } + finally { ImGuiNET.ImGui.EndPopup(); } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs index f1ef7a4..0887100 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs @@ -43,9 +43,10 @@ internal sealed class RadarFace : IImGuiPanel // ── Palette (RadarPanel's, ARGB) ──────────────────────────────────── private const uint FrameOuterArgb = 0xFF0A0D14, CanvasBgArgb = 0xFF0A121A; - private static readonly uint FrameInner = C(0xFF9E853D), FrameAccent = C(0xFFE6C766), - Crosshair = C(0x994D6680), Cardinal = C(0xFFFFFFFF), CoordText = C(0xFFF2F8FF), Outline = C(0xF2000000), - PlayerCol = C(0xFF33FF66), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A); + private static readonly uint FrameInner = C(0xFF9E853D), FrameAccent = C(0xFFE6C766), Crosshair = C(0x994D6680), + Cardinal = C(0xFFFFFFFF), CoordText = C(0xFFF2F8FF), Outline = C(0xF2000000), PlayerCol = C(0xFF33FF66); + private static uint ButtonBg => RynthTheme.WithAlpha(RynthTheme.Field, 0xC0); + private static uint ButtonBorder => RynthTheme.Border; // Marker colours per kind (RadarSettingsStore.KindColors, user-pickable), refreshed each frame. private static readonly uint[] KindCols = new uint[RadarKind.Count]; private const uint WallUnseen = 0xFFFFFFFF, WallVisited = 0xFF4099FF, FloorFlat = 0x8C2E8C38, @@ -535,7 +536,7 @@ internal sealed class RadarFace : IImGuiPanel private void SettingsWindow() { if (!_settingsOpen) return; - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, C(0xFF0A121A)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, RynthTheme.BoxBg); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ButtonBorder); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 4f); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 10)); diff --git a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs index 3e275dc..687630f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs @@ -46,12 +46,18 @@ using Rule = RynthCore.Engine.UI.Panels.MonstersPanel.Rule; namespace RynthCore.Engine.ImGuiBackend.Panels; -internal sealed class RangesSlideOut : DashboardDrawer +internal sealed class RangesSlideOut : RynthAiDrawer { // ── 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 readonly uint Gold = C(0xFFFFD16A); + private static uint Teal => RynthTheme.Accent; + private static uint TealSoft => RynthTheme.AccentFill; + private static uint Amber => RynthTheme.Highlight; + private static uint Mute => RynthTheme.TextMuted; + private static uint White => RynthTheme.Text; + private static uint BarBg => RynthTheme.Field; + private static uint BtnFill => RynthTheme.Button; + private static uint BtnBord => RynthTheme.Border; private static uint C(uint argb) => RynthTheme.Argb(argb); // ── Rows: (Settings row label, short label here) ──────────────────── @@ -129,9 +135,8 @@ internal sealed class RangesSlideOut : DashboardDrawer 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 string TabTooltip(bool right) => + "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); diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs index e92559c..7e19672 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs @@ -33,7 +33,7 @@ namespace RynthCore.Engine.ImGuiBackend.Panels; internal sealed partial class RynthAiFace { /// Meta state, bot activity and the five file pickers. - private sealed class FilesDrawer : DashboardDrawer + private sealed class FilesDrawer : RynthAiDrawer { private readonly RynthAiFace _face; public FilesDrawer(RynthAiFace face) => _face = face; @@ -51,7 +51,7 @@ internal sealed partial class RynthAiFace "Profile: " + (v?.ProfileText ?? "Default") + "\nNav: " + (v?.NavText ?? "None") + "\nLoot: " + (v?.LootText ?? "None") + "\nMeta: " + (v?.MetaText ?? "None") + "\nBuffs: " + (v?.BuffText ?? "Built-in") + - (right ? "\n\nClick to slide them out (to the right: there's no room on the left)." : "\n\nClick to slide them out."); + "\n\nClick to slide them out."; } // The picker rows are the dashboard's own (Selector), so they take its size factor (_k); @@ -100,10 +100,14 @@ internal sealed partial class RynthAiFace } } - /// Hazard cells and saved routes (the Patrol launcher's right-click). - private sealed class PatrolDrawer : DashboardDrawer + /// The Dungeon Patrol settings, hazard cells and saved routes (the Patrol launcher's right-click). + private sealed class PatrolDrawer : RynthAiDrawer { private bool _sub; + // Settings > Navigation > Dungeon Patrol, drawn here too (2026-10-14). + private readonly SettingsRows _rows = new(); + private static SettingRow[]? _settingRows; + private static SettingRow[] SettingRows => _settingRows ??= QuickSettings.SectionRows("Navigation", "Dungeon Patrol"); public override string Key => "patrol"; public override string Icon => PhosphorIcons.Footprints; @@ -111,19 +115,32 @@ internal sealed partial class RynthAiFace 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 string TabTooltip(bool right) => + "Patrol: the Dungeon Patrol settings, this dungeon's hazard cells, recorded hazards and saved routes\n(also: right-click Patrol). Click to slide it out."; - public override float Width(float k) => 260 * k; - public override float Height(float k) => 320 * k; + public override float Width(float k) => 290 * k; + + public override float Height(float k) + { + // Never taller than the screen: the body scrolls instead. + float screen = ImGuiNET.ImGui.GetIO().DisplaySize.Y; + return screen > 1 ? MathF.Min(500 * k, MathF.Max(200 * k, screen - 8 * k)) : 500 * 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(); + if (showing) + { + UiSources.Patrol.Subscribe(); UiSources.Patrol.RequestRefresh(); + UiSources.Settings.Subscribe(); UiSources.Settings.RequestRefresh(); + } + else + { + UiSources.Patrol.Unsubscribe(); + UiSources.Settings.Unsubscribe(); + } } public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) @@ -141,6 +158,27 @@ internal sealed partial class RynthAiFace { if (open) { + if (Mini(PhosphorIcons.Play + " Start patrol")) + RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}"); + ImGuiNET.ImGui.SetItemTooltip("Start the Dungeon Patrol here (the same as left-clicking Patrol)."); + + // The settings, with the Settings panel's rows (right-click one to pin it to My settings). + Section("SETTINGS"); + _rows.Sync(); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X - 2 * k; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 0)); + SettingRow[] rows = SettingRows; + for (int i = 0; i < rows.Length; i++) + { + if (!rows[i].IsVisible(_rows.Data)) continue; + ImGuiNET.ImGui.PushID(i); + _rows.DrawRow(rows[i], w); + ImGuiNET.ImGui.PopID(); + } + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopFont(); + PatrolInfo info = UiSources.Patrol.Current?.Value ?? new PatrolInfo(); PatrolBody(info, withTitle: false); } @@ -150,7 +188,7 @@ internal sealed partial class RynthAiFace } /// RynthAi's Mini Remote, drawn by the plugin into this drawer (the Hub launcher's right-click). - private sealed class RemoteDrawer : DashboardDrawer + private sealed class RemoteDrawer : RynthAiDrawer { /// The plugin surface name, NUL-terminated for the export. private static ReadOnlySpan Surface => "miniremote\0"u8; @@ -170,7 +208,7 @@ internal sealed partial class RynthAiFace public override string TabTooltip(bool right) => "Mini Remote: session rates, attack target, summon, item slots, toggles, bank, rebuff, Translate.\n" + "Its Options button picks the sections (also: right-click Hub). RynthILT's ILT tabs are in the Mini Remote window.\n" + - (right ? "Click to slide it out (to the right: there's no room on the left)." : "Click to slide it out."); + "Click to slide it out."; public override float Width(float k) => Math.Clamp(_want.X > 0 ? _want.X : MinW * k, MinW * k, MaxW * k) + 2 * Pad * k; diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index 7c15d42..672aa40 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -3,24 +3,33 @@ // ImGui face of the RynthAi dashboard (docs/IMGUI_PARITY_PLAN.md §2.1), // first laid out from the Avalonia face (UI/Panels/RynthAiPanel.cs), then // made compact with Phosphor icons, after DrakBot's dashboard. Top to bottom: -// title row RYNTH | target, vitals, lock, opacity -/+, -// minimize, pop out +// title row RYNTH, running/stopped | target, vitals, lock, opacity -/+, +// minimize, pop out; a teal accent line along the top edge // 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 +// toggles (on: lit with a bar under the icon; off: dimmed), +// bot activity as a coloured label ... force rebuff. A +// toggle's right-click opens its settings (2026-10-14): +// Combat the Monsters panel, Buffing Settings > Buffing, +// Navigation the Nav panel, Looting the Loot Editor on the +// loot profile in use, Meta the Meta panel. // launchers one row of icon buttons (names in tooltips; labels too -// when the panel is wide enough) -// footer FPS | version | uptime +// when the panel is wide enough); a button lights up while +// its window (or drawer) is open. Nav and Meta left the row +// for their toggles' right-click (2026-10-14). +// footer FPS (coloured by rate) | version | uptime // bars player vitals, then the target (name + health), each // 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, Patrol and Mini Remote -// (RynthAiFace.Drawers.cs). Everything that slides out goes -// left; only the bars stay at the bottom (Tom 2026-10-05). +// drawers tabs on the dashboard's edges (DashboardDrawers.cs), one +// open per side, windows of their own beside the dashboard: +// Ranges (RangesSlideOut.cs), Loaded files, Patrol and Mini +// Remote (RynthAiFace.Drawers.cs) on the left, My settings +// (QuickSettingsDrawer.cs) on the right; a tab's right-click +// moves its drawer to the other side. 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 @@ -71,11 +80,18 @@ internal sealed partial class RynthAiFace : IImGuiPanel private const float MinWidth = 280; // ── Palette (RynthAiPanel's, ARGB) ───────────────────────────────── - private static readonly uint Teal = C(0xFF26D9E6), TealSoft = C(0xFF264C59), Amber = C(0xFFE8B333), - Green = C(0xFF40D973), Mute = C(0xFFB8C8D8), TextDim = C(0xFFF2F7FC), White = C(0xFFFFFFFF), - Hp = C(0xFFD93333), Mana = C(0xFF268CF2), ShellBg = C(0xFF0A0F14), BarBg = C(0xFF141F29), - BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A), MacroRun = C(0xFF1A5926), MacroStop = C(0xFF401F1F), - FrFill = C(0xFF47330A), SelectorBg = C(0xFF2D3847); + private static readonly uint Green = C(0xFF40D973), White = C(0xFFFFFFFF), Hp = C(0xFFD93333), Mana = C(0xFF268CF2), + MacroRun = C(0xFF1A5926), MacroStop = C(0xFF401F1F), FrFill = C(0xFF47330A), SelectorBg = C(0xFF2D3847), + Off = C(0xFF6E8197), Faint = C(0xFF5A7088), RunGlow = C(0x5540D973); + private static uint Teal => RynthTheme.Accent; + private static uint TealSoft => RynthTheme.AccentFill; + private static uint Amber => RynthTheme.Highlight; + private static uint Mute => RynthTheme.TextMuted; + private static uint TextDim => RynthTheme.Text; + private static uint ShellBg => RynthTheme.Background; + private static uint BarBg => RynthTheme.Field; + private static uint BtnFill => RynthTheme.Button; + private static uint BtnBord => RynthTheme.Border; private static uint C(uint argb) => RynthTheme.Argb(argb); private static readonly uint[] SegmentColors = BuildSegmentColors(); @@ -118,7 +134,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel public RynthAiFace() { // Tab order top to bottom; the first one saved open wins at load. - _drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol, _remote); + // Each side's in this order; My settings starts on the right. + _drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol, _remote, new QuickSettingsDrawer()); } public Vector2? MinSize @@ -155,7 +172,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel bool popped = ImGuiPopOuts.InPopOutFrame; _view = view; _raw = raw; - uint boxBg = (C(0xFF0A121A) & 0x00FFFFFF) | ((uint)(view?.PanelAlpha ?? 242) << 24); + uint boxBg = (RynthTheme.BoxBg & 0x00FFFFFF) | ((uint)(view?.PanelAlpha ?? 242) << 24); // The host set the step these fonts are drawn at; the boxes take the same step's factor. _k = PanelTextScale.Factor(ImGuiFonts.CurrentStep); // Enlarged: tooltips and menus opened from the dashboard at its size too. (At size 0 the @@ -168,6 +185,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel float x0 = start.X; float width = ImGuiNET.ImGui.GetContentRegionAvail().X; + AccentLine(); TitleRow(raw, x0, width, minimized); Gap(4); // Popped out (no drawers there): the Profile/Nav/Loot/Meta pickers inline while expanded @@ -239,7 +257,15 @@ internal sealed partial class RynthAiFace : IImGuiPanel _fitWidth = width; } - // ── Title row: "R" + "YNTH" | chips (drag surface) ────── + /// A thin teal line along the window's top edge, inside its rounded corners. + private static void AccentLine() + { + Vector2 wp = ImGuiNET.ImGui.GetWindowPos(), ws = ImGuiNET.ImGui.GetWindowSize(); + float r = RynthTheme.RynthAiRounding; + ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(new Vector2(wp.X + r, wp.Y), new Vector2(wp.X + ws.X - r, wp.Y + MathF.Max(1.5f, Px(2))), Teal); + } + + // ── Title row: "R" + "YNTH", running | chips (drag surface) ────── private void TitleRow(RynthAiSnapshot raw, float x0, float width, bool minimized) { @@ -262,6 +288,19 @@ internal sealed partial class RynthAiFace : IImGuiPanel dl.AddText(title, title.FontSize, new Vector2(x0, ty), Teal, "R"); float rw = CalcWidth(title, "R"); dl.AddText(title, title.FontSize, new Vector2(x0 + rw, ty), White, "YNTH"); + // Running / stopped, at a glance: a dot and the word in a pill after the name. + { + ImFontPtr pf = ImGuiFonts.Get(UiFont.Dash9); + bool run = raw.MacroRunning; + string word = run ? "running" : "stopped"; + float px = x0 + rw + CalcWidth(title, "YNTH") + Px(7); + float ph = pf.FontSize + Px(4), pw = Px(13) + CalcWidth(pf, word) + Px(6); + float py = y + (rowH - ph) * 0.5f; + uint col = run ? Green : Off; + dl.AddRect(new Vector2(px, py), new Vector2(px + pw, py + ph), run ? MacroRun : BtnBord, ph * 0.5f); + dl.AddCircleFilled(new Vector2(px + Px(7), py + ph * 0.5f), Px(2.5f), col); + dl.AddText(pf, pf.FontSize, new Vector2(px + Px(13), py + (ph - pf.FontSize) * 0.5f), col, word); + } dl.PopClipRect(); float cx = x0 + width - chipsW; @@ -530,21 +569,29 @@ internal sealed partial class RynthAiFace : IImGuiPanel // Macro start/stop: a square like the toggles, green with a Stop glyph while running. { bool on = raw.MacroRunning; + // Running: a soft green halo around the square. + if (on) dl.AddRect(new Vector2(x - Px(1.5f), y - Px(1.5f)), new Vector2(x + sq + Px(1.5f), y + sq + Px(1.5f)), RunGlow, round + Px(1.5f), ImDrawFlags.None, Px(2)); if (IconButton("##macro", new Vector2(x, y), square, on ? PhosphorIcons.Stop : PhosphorIcons.Play, UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, round)) RynthAiCommands.ToggleMacro(); ImGuiNET.ImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it."); x += sqStep + Px(6); } - Toggle("##t_combat", PhosphorIcons.Sword, raw.CombatEnabled, 0, new Vector2(x, y), "Combat"); + Toggle("##t_combat", PhosphorIcons.Sword, raw.CombatEnabled, 0, new Vector2(x, y), "Combat", + "the Monsters panel (weapons, spells and rules per monster)", PanelRouter.ToggleMonsters); x += sqStep; - Toggle("##t_buff", PhosphorIcons.Sparkle, raw.BuffingEnabled, 1, new Vector2(x, y), "Buffing"); + Toggle("##t_buff", PhosphorIcons.Sparkle, raw.BuffingEnabled, 1, new Vector2(x, y), "Buffing", + "the buffing settings", () => ShowSettingsTab("Buffing")); x += sqStep; - Toggle("##t_nav", PhosphorIcons.SneakerMove, raw.NavigationEnabled, 2, new Vector2(x, y), "Navigation"); + Toggle("##t_nav", PhosphorIcons.SneakerMove, raw.NavigationEnabled, 2, new Vector2(x, y), "Navigation", + "the Nav panel (routes)", () => PanelRouter.Toggle("Nav")); x += sqStep; - Toggle("##t_loot", PhosphorIcons.Bag, raw.LootingEnabled, 3, new Vector2(x, y), "Looting"); + string lootPath = raw.CurrentLootPath ?? string.Empty; + Toggle("##t_loot", PhosphorIcons.Bag, raw.LootingEnabled, 3, new Vector2(x, y), "Looting", + "the Loot Editor on the loot profile in use", () => LootEditorFace.ToggleFor(lootPath)); x += sqStep; - Toggle("##t_meta", PhosphorIcons.Code, raw.MetaEnabled, 4, new Vector2(x, y), "Meta (the macro rules)"); + Toggle("##t_meta", PhosphorIcons.Code, raw.MetaEnabled, 4, new Vector2(x, y), "Meta (the macro rules)", + "the Meta panel", () => PanelRouter.Toggle("Meta")); x += sqStep; // RynthSort's auto-sort, when RynthSort is loaded and knows the character. int sort = RynthSortWatch.State; @@ -581,9 +628,19 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (aRight - ax > Px(20)) { string activity = view?.BotActivityText ?? "Idle"; - float ay = y + (sq - af.FontSize) * 0.5f; + // A pill coloured by what the bot is doing, with its icon. + ActivityStyle(activity, out uint fg, out uint bg, out string icon); + float ph = MathF.Min(sq, af.FontSize + Px(6)); + float py = y + (sq - ph) * 0.5f; + float iconW = icon.Length > 0 ? CalcWidth(af, icon) + Px(4) : 0; + float pw = MathF.Min(aRight - ax, Px(8) + iconW + CalcWidth(af, activity) + Px(8)); dl.PushClipRect(new Vector2(ax, y), new Vector2(aRight, y + sq), true); - dl.AddText(af, af.FontSize, new Vector2(ax, ay), Amber, activity); + dl.AddRectFilled(new Vector2(ax, py), new Vector2(ax + pw, py + ph), bg, ph * 0.5f); + float tx = ax + Px(8), ay = py + (ph - af.FontSize) * 0.5f; + if (icon.Length > 0) dl.AddText(af, af.FontSize, new Vector2(tx, ay), fg, icon); + dl.PushClipRect(new Vector2(ax, py), new Vector2(ax + pw - Px(6), py + ph), true); + dl.AddText(af, af.FontSize, new Vector2(tx + iconW, ay), fg, activity); + dl.PopClipRect(); dl.PopClipRect(); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ax, y)); ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, sq)); @@ -603,11 +660,47 @@ internal sealed partial class RynthAiFace : IImGuiPanel ImGuiNET.ImGui.Dummy(new Vector2(width, 0)); } - private void Toggle(string id, string icon, bool on, int subsystem, Vector2 pos, string name) + /// + /// A subsystem toggle: on is lit (teal, with a bar under the icon), off is dimmed so a subsystem + /// left off stands out. Right-click runs , which opens + /// (its settings). + /// + private void Toggle(string id, string icon, bool on, int subsystem, Vector2 pos, string name, string rightWhat, Action onRight) { - if (IconButton(id, pos, new Vector2(Px(Square), Px(Square)), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, Px(3))) + float sq = Px(Square); + if (IconButton(id, pos, new Vector2(sq, sq), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Off, on ? Teal : BtnBord, Px(3))) RynthAiCommands.SetSubsystemEnabled(subsystem, !on); - ImGuiNET.ImGui.SetItemTooltip(on ? name + " on. Click to turn it off." : name + " off. Click to turn it on."); + bool right = ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right); + ImGuiNET.ImGui.SetItemTooltip((on ? name + " on. Click to turn it off." : name + " off. Click to turn it on.") + + "\nRight-click: " + rightWhat + "."); + if (on) + ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(new Vector2(pos.X + Px(5), pos.Y + sq - Px(3.5f)), + new Vector2(pos.X + sq - Px(5), pos.Y + sq - Px(1.5f)), Teal, Px(1)); + if (right) onRight(); + } + + /// Opens Settings (if closed) on tab . + private static void ShowSettingsTab(string tab) + { + SettingsFace.RequestTab(tab); + if (!ImGuiPanelHost.IsOpen(SettingsFace.Title)) PanelRouter.Toggle(SettingsFace.Title); + } + + /// The activity pill's colours and icon: red in a fight, gold looting, teal moving, and so on; grey idle. + private static void ActivityStyle(string activity, out uint fg, out uint bg, out string icon) + { + switch (activity) + { + case "Combat": fg = C(0xFFFF7A7A); bg = C(0xFF4A1A1A); icon = PhosphorIcons.Sword; break; + case "Looting": + case "Salvaging": fg = Amber; bg = FrFill; icon = PhosphorIcons.Bag; break; + case "Navigating": fg = Teal; bg = TealSoft; icon = PhosphorIcons.SneakerMove; break; + case "Buffing": fg = C(0xFFC2A8FF); bg = C(0xFF2E2350); icon = PhosphorIcons.Sparkle; break; + case "Healing": fg = C(0xFFFF8A8A); bg = C(0xFF4A1A1A); icon = PhosphorIcons.Heart; break; + case "Restoring mana": fg = C(0xFF6CB4FF); bg = C(0xFF15304D); icon = PhosphorIcons.Drop; break; + case "Restoring stamina": fg = Green; bg = C(0xFF173D24); icon = PhosphorIcons.Lightning; break; + default: fg = Mute; bg = C(0xFF1C2733); icon = ""; break; + } } // ── Launchers: one row of icon buttons ────────────────────────────── @@ -617,36 +710,36 @@ internal sealed partial class RynthAiFace : IImGuiPanel private void Launchers(float x0, float width) { float y = ImGuiNET.ImGui.GetCursorScreenPos().Y; - const int buttons = 10; + // Nav and Meta left the row (2026-10-14): right-click the Navigation and Meta toggles. + const int buttons = 8; float gap = Px(LauncherGap); float bw = MathF.Floor((width - buttons * gap) / buttons); // Short labels only when every button has room for its icon and label. bool labels = bw >= Px(68); float x = x0; - Launcher("##l_meta", PhosphorIcons.ListChecks, "Meta", "Meta: the macro rules", x, y, bw, labels, () => PanelRouter.Toggle("Meta")); - x += bw + gap; - Launcher("##l_lua", PhosphorIcons.FileCode, "Lua", "Lua scripts", x, y, bw, labels, () => PanelRouter.Toggle("Lua")); + Launcher("##l_lua", PhosphorIcons.FileCode, "Lua", "Lua scripts", x, y, bw, labels, () => PanelRouter.Toggle("Lua"), + ImGuiPanelHost.IsOpen("Lua")); x += bw + gap; // Monsters opens the Damage panel (the basic Monsters panel and its // Simple/Advanced chip were retired 2026-10-01). Launcher("##l_mon", PhosphorIcons.Skull, "Monsters", "Monsters: weapons, spells and rules per monster (the Damage panel)", - x, y, bw, labels, PanelRouter.ToggleMonsters); + x, y, bw, labels, PanelRouter.ToggleMonsters, ImGuiPanelHost.IsOpen(PanelRouter.Canonical("Monsters"))); x += bw + gap; - Launcher("##l_set", PhosphorIcons.Gear, "Settings", "Settings", x, y, bw, labels, () => PanelRouter.Toggle("Settings")); - x += bw + gap; - Launcher("##l_nav", PhosphorIcons.MapTrifold, "Nav", "Nav: routes", x, y, bw, labels, () => PanelRouter.Toggle("Nav")); + Launcher("##l_set", PhosphorIcons.Gear, "Settings", "Settings", x, y, bw, labels, () => PanelRouter.Toggle("Settings"), + ImGuiPanelHost.IsOpen(SettingsFace.Title)); x += bw + gap; Launcher("##l_map", PhosphorIcons.MapPin, "Map", "Dungeon Map (shows while you're in a dungeon)", x, y, bw, labels, - () => PanelRouter.Toggle(DungeonMapFace.Title)); + () => PanelRouter.Toggle(DungeonMapFace.Title), ImGuiPanelHost.IsOpen(DungeonMapFace.Title)); x += bw + gap; - Launcher("##l_items", PhosphorIcons.Backpack, "Items", "Items", x, y, bw, labels, () => PanelRouter.Toggle("Items")); + Launcher("##l_items", PhosphorIcons.Backpack, "Items", "Items", x, y, bw, labels, () => PanelRouter.Toggle("Items"), + ImGuiPanelHost.IsOpen("Items")); x += bw + gap; bool popped = ImGuiPopOuts.InPopOutFrame; Launcher("##l_patrol", PhosphorIcons.Footprints, "Patrol", 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\"}")); + : "Patrol. Left-click: start dungeon patrol. Right-click: the Patrol drawer (patrol settings, hazards and routes).", + x, y, bw, labels, () => RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}"), !popped && _drawers.IsOpen(_patrol)); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { if (popped) @@ -663,7 +756,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel // on its Character tab (RynthILT's ILT tab; elsewhere the remote shows), Hub as it was left. Launcher("##l_char", PhosphorIcons.User, "Char", "Char. Left-click: the Mini Remote on its Character tab (ILT worlds). Right-click: Character windows (Spells, Quests, Pets, Skills, Inventory...), then Server: this server's plugin windows.", - x, y, bw, labels, () => ShowMiniRemoteTab("character")); + x, y, bw, labels, () => ShowMiniRemoteTab("character"), false); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1)); @@ -677,7 +770,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub", popped ? "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: open the Mini Remote window." : "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: the Mini Remote drawer (left), with its Options.", - x, y, bw, labels, () => PanelRouter.Toggle(MiniRemoteFace.Title)); + x, y, bw, labels, () => PanelRouter.Toggle(MiniRemoteFace.Title), + ImGuiPanelHost.IsOpen(MiniRemoteFace.Title) || (!popped && _drawers.IsOpen(_remote))); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { if (popped) ImGuiPanelHost.Open(MiniRemoteFace.Title); @@ -687,32 +781,37 @@ internal sealed partial class RynthAiFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + Px(LauncherH))); } - private void Launcher(string id, string icon, string label, string tooltip, float x, float y, float w, bool showLabel, Action? onClick) + /// Its window (or drawer) is open: teal icon and outline, with a bar along the bottom. + private void Launcher(string id, string icon, string label, string tooltip, float x, float y, float w, bool showLabel, Action? onClick, bool lit) { var pos = new Vector2(x, y); float lh = Px(LauncherH); var size = new Vector2(Math.Max(Px(10), w), lh); var dl = ImGuiNET.ImGui.GetWindowDrawList(); ImGuiNET.ImGui.SetCursorScreenPos(pos); - bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight) + && ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Left); ImGuiNET.ImGui.SetItemTooltip(tooltip); - uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill; + bool hot = ImGuiNET.ImGui.IsItemHovered(); + uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : hot ? Lighten(BtnFill) : BtnFill; + uint fg = lit ? Teal : hot ? White : Mute; dl.AddRectFilled(pos, pos + size, fill, Px(3)); - dl.AddRect(pos, pos + size, BtnBord, Px(3)); + dl.AddRect(pos, pos + size, lit ? Teal : BtnBord, Px(3)); + if (lit) dl.AddRectFilled(new Vector2(pos.X + Px(3), pos.Y + lh - Px(2)), new Vector2(pos.X + size.X - Px(3), pos.Y + lh - Px(0.5f)), Teal); ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Dash14); if (showLabel) { ImFontPtr f9 = ImGuiFonts.Get(UiFont.Dash9); float iconBox = Px(16); - PhosphorIcons.DrawCentered(dl, iconFont, icon, pos + new Vector2(Px(4), 0), new Vector2(iconBox, lh), Mute); + PhosphorIcons.DrawCentered(dl, iconFont, icon, pos + new Vector2(Px(4), 0), new Vector2(iconBox, lh), fg); dl.PushClipRect(pos, pos + size, true); - dl.AddText(f9, f9.FontSize, new Vector2(pos.X + Px(4) + iconBox + Px(4), pos.Y + (lh - f9.FontSize) * 0.5f), Mute, label); + dl.AddText(f9, f9.FontSize, new Vector2(pos.X + Px(4) + iconBox + Px(4), pos.Y + (lh - f9.FontSize) * 0.5f), fg, label); dl.PopClipRect(); } else { - PhosphorIcons.DrawCentered(dl, iconFont, icon, pos, size, Mute); + PhosphorIcons.DrawCentered(dl, iconFont, icon, pos, size, fg); } if (clicked && onClick != null) { @@ -767,7 +866,9 @@ internal sealed partial class RynthAiFace : IImGuiPanel ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10); float y = ImGuiNET.ImGui.GetCursorScreenPos().Y; float fpsW = CalcWidth(f10, _fpsText), upW = CalcWidth(f10, _upText); - dl.AddText(f10, f10.FontSize, new Vector2(x0, y), Mute, _fpsText); + // FPS coloured by rate: green smooth, amber workable, red struggling. + uint fpsCol = fps <= 0 ? Mute : fps >= 45 ? Green : fps >= 25 ? Amber : C(0xFFFF6B6B); + dl.AddText(f10, f10.FontSize, new Vector2(x0, y), fpsCol, _fpsText); dl.AddText(f10, f10.FontSize, new Vector2(x0 + width - upW, y), Mute, _upText); // The version between them: centred when there's room, else after FPS, clipped short of the uptime. @@ -781,7 +882,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel float vx = x0 + (width - vw) * 0.5f; if (vx < left || vx + vw > right) vx = left; dl.PushClipRect(new Vector2(left, y), new Vector2(right, y + f10.FontSize + Px(2)), true); - dl.AddText(f10, f10.FontSize, new Vector2(vx, y), Mute, version); + dl.AddText(f10, f10.FontSize, new Vector2(vx, y), Faint, version); dl.PopClipRect(); } } @@ -971,14 +1072,14 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (withTitle) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), PatrolTitle); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), PatrolTitle); ImGuiNET.ImGui.PopFont(); } Section("THIS DUNGEON"); if (info.InDungeon) { - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{info.CurrentLandblock} · {info.CurrentHazards} hazard cell(s)"); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), $"0x{info.CurrentLandblock} · {info.CurrentHazards} hazard cell(s)"); if (info.CurrentHazards > 0) { ImGuiNET.ImGui.SameLine(); @@ -991,24 +1092,24 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (Mini("Unmark")) RynthAiCommands.SendNavCommand("{\"Cmd\":\"unmarkHazardHere\"}", refreshPatrol: true); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, RynthTheme.Vec(0xFFB8C8D8)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, RynthTheme.VecOf(RynthTheme.TextMuted)); ImGuiNET.ImGui.TextWrapped("Stand on the lava/acid, click Mark, then re-run Patrol."); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.PopFont(); } else { - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "Not in a dungeon."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), "Not in a dungeon."); } Section($"RECORDED HAZARDS ({info.Dungeons.Length})"); if (info.Dungeons.Length == 0) - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "None recorded yet."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), "None recorded yet."); for (int i = 0; i < info.Dungeons.Length; i++) { DungeonHazards d = info.Dungeons[i]; ImGuiNET.ImGui.PushID(i); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{d.Landblock} · {d.Cells} cell(s)"); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), $"0x{d.Landblock} · {d.Cells} cell(s)"); ImGuiNET.ImGui.SameLine(); if (Mini("Clear")) RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}", refreshPatrol: true); @@ -1019,9 +1120,9 @@ internal sealed partial class RynthAiFace : IImGuiPanel Section($"SAVED ROUTES ({info.Routes.Length})"); if (info.Routes.Length == 0) - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "No .nav routes saved."); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), "No .nav routes saved."); foreach (string name in info.Routes) - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "• " + name); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "• " + name); ImGuiNET.ImGui.PopFont(); } @@ -1033,7 +1134,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel { ImGuiNET.ImGui.Dummy(new Vector2(0, Px(4))); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), text); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), text); ImGuiNET.ImGui.PopFont(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs index 4371e91..a3c2010 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs @@ -51,8 +51,9 @@ internal sealed class RynthNavArrowFace : IImGuiPanel /// The arrow turns with you: redraw popped out often enough to look smooth. public int PopOutIdleHz => 20; - private static readonly uint Glass = RynthTheme.Argb(0xDC0A0F14), Ring = RynthTheme.Argb(0xFF1A2A39), - InputBg = RynthTheme.Argb(0xFF0E1822), Purple = RynthTheme.Argb(0xFFB48CF0), Done = Faded(Mute); + private static readonly uint Ring = RynthTheme.Argb(0xFF1A2A39), InputBg = RynthTheme.Argb(0xFF0E1822), + Purple = RynthTheme.Argb(0xFFB48CF0), Done = Faded(Mute); + private static uint Glass => RynthTheme.WithAlpha(RynthTheme.Background, 0xDC); private const int MaxRouteRows = 8; diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs index 6662c88..c23516b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs @@ -57,7 +57,8 @@ internal sealed class RynthNavFace : IImGuiPanel } private static readonly uint RunGreen = RynthTheme.Argb(0xFF40D973), Sep = RynthTheme.Argb(0xFF1A2A39), - RowHot = RynthTheme.Argb(0xFF16283A), Gold = RynthTheme.Argb(0xFFFFD24D), Purple = RynthTheme.Argb(0xFFBF4DFF); + Gold = RynthTheme.Argb(0xFFFFD24D), Purple = RynthTheme.Argb(0xFFBF4DFF); + private static uint RowHot => RynthTheme.Button; private const int TabGo = 0, TabAtlas = 1, TabArrow = 2; @@ -127,6 +128,16 @@ internal sealed class RynthNavFace : IImGuiPanel dl.AddText(big, big.FontSize, p + new Vector2(16, 1), Teal, "RynthNav"); float tw = ImGuiNET.ImGui.CalcTextSize("RynthNav").X * big.FontSize / ImGuiNET.ImGui.GetFontSize(); dl.AddText(p + new Vector2(24 + tw, 6), Mute, "go · atlas · arrow"); + if (ImGuiPanelHost.HasFace(WorldMapFace.Title)) + { + bool mapOpen = ImGuiPanelHost.IsOpen(WorldMapFace.Title), miniOpen = ImGuiPanelHost.IsOpen(MiniMapFace.Title); + if (Button("##rnav_worldmap", PhosphorIcons.GlobeHemisphereWest + " Map", new Vector2(p.X + w - 62, p.Y - 1), new Vector2(62, 22), + mapOpen ? Teal : Text, mapOpen ? Selected : BtnFill, border: mapOpen ? Teal : 0)) + UI.PanelRouter.Toggle(WorldMapFace.Title); + if (Button("##rnav_minimap", "Mini", new Vector2(p.X + w - 62 - 4 - 40, p.Y - 1), new Vector2(40, 22), + miniOpen ? Teal : Text, miniOpen ? Selected : BtnFill, border: miniOpen ? Teal : 0)) + UI.PanelRouter.Toggle(MiniMapFace.Title); + } NextLine(p, 22); DrawTabs(w); DrawStatusLine(w); diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs index 3883c0a..160d237 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs @@ -4,14 +4,10 @@ // // Draws SettingsSchema (UI/Data/SettingsData.cs), the same list the Avalonia // face builds from, with that face's look: 150 px tab sidebar, "Advanced -// Settings > Tab" header, square toggle dots, - [value] + steppers (typed -// values commit on Enter or when the field loses focus, then clamp; bad -// input reverts), combo pickers, amber section headers, tooltips. -// -// Edits a private copy of the hub's settings and saves the whole copy -// (SettingsCommands.Save) on each change; a newer fetch replaces the copy -// only while no field here is being typed in. Rows that show or hide other -// rows need nothing special: visibility is re-evaluated every frame. +// Settings > Tab" header, then the tab's rows (SettingsRows.cs draws and +// edits them; right-click a row to pin it to the dashboard's My settings +// drawer). Rows that show or hide other rows need nothing special: +// visibility is re-evaluated every frame. // ============================================================================ using System; @@ -33,30 +29,23 @@ internal sealed class SettingsFace : IImGuiPanel () => new SettingsFace()); // ── Palette (SettingsPanel's, ARGB) ───────────────────────────────── - private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Mute = C(0xFFB8C8D8), - TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), PanelBg = C(0xFF141F29), BtnFill = C(0xFF16283A), - BtnBord = C(0xFF34587A), ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), TabActive = C(0xFF1A2E42); + private static readonly uint ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455); + private static uint Teal => RynthTheme.Accent; + private static uint Amber => RynthTheme.Highlight; + private static uint Mute => RynthTheme.TextMuted; + private static uint TextDim => RynthTheme.Text; + private static uint ShellBg => RynthTheme.Background; + private static uint PanelBg => RynthTheme.Field; + private static uint BtnFill => RynthTheme.Button; + private static uint BtnBord => RynthTheme.Border; + private static uint TabActive => RynthTheme.Selected; private static uint C(uint argb) => RynthTheme.Argb(argb); private static readonly string[] Headers = BuildHeaders(); - private RynthAiSettings _data = new(); - private long _seenVersion = -1; private int _tab; - private bool _editing; - - // Typed-value buffers, one per numeric row (UTF-8, NUL-terminated). - private sealed class NumberEdit - { - public readonly byte[] Buffer = new byte[24]; - public double Shown = double.NaN; - public bool Active; // the box had keyboard focus last frame - } - private readonly Dictionary _edits = new(); - // Text rows being typed in (the saved value shows again once the box loses focus). - private readonly Dictionary _textEdits = new(); - // The Hotkeys tab (engine-side; not part of RynthAi's settings). - private readonly HotkeysSettingsUi _hotkeys = new(); + // The rows (SettingsRows.cs: the edited copy, typed values, the hotkeys editor). + private readonly SettingsRows _rows = new(); // A tab asked for from outside (/rc hotkeys), taken on the next draw. private static volatile string? _requestedTab; @@ -73,19 +62,13 @@ internal sealed class SettingsFace : IImGuiPanel public void OnHidden() { UiSources.Settings.Unsubscribe(); - _hotkeys.Leave(); + _rows.LeaveHotkeys(); } public void Draw() { // Take a newer fetch unless a value is being typed in. - var snap = UiSources.Settings.Current; - if (snap != null && snap.Version != _seenVersion && !_editing) - { - _seenVersion = snap.Version; - _data = snap.Value.Clone(); - } - _editing = false; + _rows.Sync(); if (_requestedTab is { } wanted) { @@ -176,7 +159,7 @@ internal sealed class SettingsFace : IImGuiPanel ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); if (_tab >= SettingsSchema.Tabs.Length) _tab = 0; - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Headers[_tab]); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), Headers[_tab]); ImGuiNET.ImGui.PopFont(); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos(); @@ -184,13 +167,13 @@ internal sealed class SettingsFace : IImGuiPanel ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows; - if (SettingsSchema.Tabs[_tab].Name != HotkeysSettingsUi.TabName) _hotkeys.Leave(); + if (SettingsSchema.Tabs[_tab].Name != HotkeysSettingsUi.TabName) _rows.LeaveHotkeys(); for (int i = 0; i < rows.Length; i++) { SettingRow row = rows[i]; - if (!row.IsVisible(_data)) continue; + if (!row.IsVisible(_rows.Data)) continue; ImGuiNET.ImGui.PushID(i); - DrawRow(row, w); + _rows.DrawRow(row, w); ImGuiNET.ImGui.PopID(); } @@ -198,367 +181,6 @@ internal sealed class SettingsFace : IImGuiPanel ImGuiNET.ImGui.EndChild(); } - private void DrawRow(SettingRow row, float w) - { - switch (row.Kind) - { - case SettingKind.Bool: BoolRow(row, w); break; - case SettingKind.Int: - case SettingKind.Float: - case SettingKind.Double: NumberRow(row, w); break; - case SettingKind.Combo: ComboRow(row, w); break; - case SettingKind.Section: Section(row.Label, w); break; - case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break; - case SettingKind.Note: Note(row.Label, w); break; - case SettingKind.CraftingStatus: CraftingStatus(row); break; - case SettingKind.Button: ButtonRow(row, w); break; - case SettingKind.TraceCategories: TraceCategoriesRow(row, w); break; - case SettingKind.Text: TextRow(row, w); break; - case SettingKind.Status: StatusRow(row, w); break; - case SettingKind.Hotkeys: _editing |= _hotkeys.Draw(w); break; - } - } - - // [All on] [All off], then a 3-column grid of square toggles, one per - // RynthAi trace category. Edits the copy's DiagCategories and saves like any other row. - private void TraceCategoriesRow(SettingRow row, float w) - { - var cats = TraceCategoryLevels.Parse(_data.DiagCategories); - if (cats.Count == 0) - { - Note("Waiting for RynthAi...", w); - return; - } - - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - if (ImGuiNET.ImGui.Button("All on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true)); - ImGuiNET.ImGui.SameLine(0, 6); - if (ImGuiNET.ImGui.Button("All off")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", false)); - Tooltip(row); - ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - - var dl = ImGuiNET.ImGui.GetWindowDrawList(); - float colW = Math.Max(80f, w / 3f); - int perRow = Math.Max(1, (int)(w / colW)); - Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); - for (int i = 0; i < cats.Count; i++) - { - var (name, level) = cats[i]; - bool on = level != TraceCategoryLevels.Off; - string label = TraceCategoryLevels.Label(name, level); - var p = start + new Vector2(i % perRow * colW, i / perRow * 18f); - ImGuiNET.ImGui.SetCursorScreenPos(p); - ImGuiNET.ImGui.PushID(name); - if (ImGuiNET.ImGui.InvisibleButton("##cat", new Vector2(colW - 4, 16))) - SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, name, !on)); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); - ImGuiNET.ImGui.PopID(); - dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2); - dl.PushClipRect(p, p + new Vector2(colW - 4, 16), true); - dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label); - dl.PopClipRect(); - } - int rowsUsed = (cats.Count + perRow - 1) / perRow; - ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, rowsUsed * 18f)); - ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - } - - private void SaveCategories(string levels) - { - _data.DiagCategories = levels; - SettingsCommands.Save(_data.Clone()); - } - - // Label, then a full-width box; the value commits on Enter or focus loss (like the number boxes). - private void TextRow(SettingRow row, float w) - { - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); - ImGuiNET.ImGui.TextUnformatted(row.Label); - ImGuiNET.ImGui.PopStyleColor(); - Tooltip(row); - - string saved = row.GetText?.Invoke(_data) ?? string.Empty; - string text = _textEdits.TryGetValue(row, out string? typing) ? typing : saved; - ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 4)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f); - bool enter = ImGuiNET.ImGui.InputTextWithHint("##text", row.Hint ?? string.Empty, ref text, 512u, - ImGuiInputTextFlags.EnterReturnsTrue); - bool active = ImGuiNET.ImGui.IsItemActive(); - bool committed = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); - ImGuiNET.ImGui.PopStyleVar(2); - ImGuiNET.ImGui.PopStyleColor(3); - Tooltip(row); - _editing |= active; - - if (committed) - { - _textEdits.Remove(row); - if (!string.Equals(text, saved, StringComparison.Ordinal)) - { - row.SetText?.Invoke(_data, text); - SettingsCommands.Save(_data.Clone()); - } - } - else if (active) _textEdits[row] = text; - else _textEdits.Remove(row); - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - } - - // RynthAi's one-line status (teal), wrapped to the column. - private void StatusRow(SettingRow row, float w) - { - string text = row.GetText?.Invoke(_data) ?? string.Empty; - if (text.Length == 0) return; - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal); - ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); - ImGuiNET.ImGui.TextUnformatted(text); - ImGuiNET.ImGui.PopTextWrapPos(); - ImGuiNET.ImGui.PopStyleColor(); - } - - // Label | [caption]; Click posts its own work (never runs plugin code on AC's thread). - private static void ButtonRow(SettingRow row, float w) - { - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); - ImGuiNET.ImGui.AlignTextToFramePadding(); - ImGuiNET.ImGui.TextUnformatted(row.Label); - ImGuiNET.ImGui.PopStyleColor(); - ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f)); - if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label)) - row.Click?.Invoke(); - Tooltip(row); - } - - private void Changed(SettingRow row, double value) - { - row.Set!(_data, value); - SettingsCommands.Save(_data.Clone()); - } - - // Square dot + label; the whole row toggles. - private void BoolRow(SettingRow row, float w) - { - var dl = ImGuiNET.ImGui.GetWindowDrawList(); - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - bool on = row.Get!(_data) != 0; - float labelW = ImGuiNET.ImGui.CalcTextSize(row.Label).X; - if (ImGuiNET.ImGui.InvisibleButton("##b", new Vector2(Math.Min(w, 18 + labelW), 16))) - Changed(row, on ? 0 : 1); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); - Tooltip(row); - dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2); - dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - } - - // Label | [-] [value] [+]; the value commits on Enter or focus loss. - private void NumberRow(SettingRow row, float w) - { - var dl = ImGuiNET.ImGui.GetWindowDrawList(); - bool isInt = row.Kind == SettingKind.Int; - float boxW = isInt ? 52 : 64, boxCol = isInt ? 56 : 68; - double value = Math.Clamp(row.Get!(_data), row.Min, row.Max); - - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - float right = p.X + w; - dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); - ImGuiNET.ImGui.InvisibleButton("##label", new Vector2(Math.Max(1, w - 40 - boxCol), 22)); - Tooltip(row); - - float plusX = right - 20, boxX = plusX - boxCol + (boxCol - boxW) * 0.5f, minusX = right - 20 - boxCol - 20; - if (StepButton("##minus", new Vector2(minusX + 1, p.Y + 1), PhosphorIcons.Minus)) - Changed(row, Math.Clamp(value - row.Step, row.Min, row.Max)); - - // Typed value (amber on the panel colour). - NumberEdit edit = EditFor(row); - ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(boxX, p.Y + 1)); - ImGuiNET.ImGui.SetNextItemWidth(boxW); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f)); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f); - if (!edit.Active && edit.Shown != value) - WriteValue(edit, value, isInt); - ImGuiNET.ImGui.InputText("##v", edit.Buffer, (uint)edit.Buffer.Length, - ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll); - bool active = ImGuiNET.ImGui.IsItemActive(); - edit.Active = active; - _editing |= active; - if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) - { - if (TryParse(edit.Buffer, out double typed)) - { - double clamped = Math.Clamp(isInt ? Math.Round(typed) : typed, row.Min, row.Max); - Changed(row, clamped); - WriteValue(edit, clamped, isInt); - } - else WriteValue(edit, value, isInt); // bad input reverts - } - ImGuiNET.ImGui.PopStyleVar(3); - ImGuiNET.ImGui.PopStyleColor(3); - - if (StepButton("##plus", new Vector2(plusX + 1, p.Y + 1), PhosphorIcons.Plus)) - Changed(row, Math.Clamp(value + row.Step, row.Min, row.Max)); - - ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - } - - private NumberEdit EditFor(SettingRow row) - { - if (!_edits.TryGetValue(row, out NumberEdit? e)) - _edits[row] = e = new NumberEdit(); - return e; - } - - private static void WriteValue(NumberEdit edit, double value, bool isInt) - { - string text = isInt ? ((long)Math.Round(value)).ToString(CultureInfo.InvariantCulture) - : value.ToString("G4", CultureInfo.InvariantCulture); - int n = Encoding.UTF8.GetBytes(text, 0, text.Length, edit.Buffer, 0); - edit.Buffer[Math.Min(n, edit.Buffer.Length - 1)] = 0; - edit.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); - } - - // Label | [current item]; click opens a 220 px list with the current item highlighted. - private void ComboRow(SettingRow row, float w) - { - var dl = ImGuiNET.ImGui.GetWindowDrawList(); - string[] items = row.Items!; - int current = Math.Clamp((int)row.Get!(_data), 0, items.Length - 1); - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); - - ImFontPtr f10 = ImGuiFonts.Get(UiFont.Ui10); - const float btnW = 160; - var bp = new Vector2(p.X + w - btnW, p.Y + 1); - ImGuiNET.ImGui.SetCursorScreenPos(bp); - if (ImGuiNET.ImGui.InvisibleButton("##combo", new Vector2(btnW, 20))) - { - ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Max(bp.X + btnW - 220, 0), bp.Y + 20)); - ImGuiNET.ImGui.OpenPopup("##combo_list"); - } - bool hot = ImGuiNET.ImGui.IsItemHovered(); - Tooltip(row); - dl.AddRectFilled(bp, bp + new Vector2(btnW, 20), hot ? Lighten(BtnFill) : BtnFill); - dl.AddRect(bp, bp + new Vector2(btnW, 20), BtnBord); - dl.PushClipRect(bp, bp + new Vector2(btnW - 16, 20), true); - dl.AddText(f10, f10.FontSize, bp + new Vector2(4, (20 - f10.FontSize) * 0.5f), TextDim, items[current]); - dl.PopClipRect(); - PhosphorIcons.DrawCentered(dl, f10, PhosphorIcons.CaretDown, bp + new Vector2(btnW - 16, 0), new Vector2(14, 20), Mute); - - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); - ImGuiNET.ImGui.SetNextWindowSize(new Vector2(220, items.Length * 21 + 4)); - bool open = ImGuiNET.ImGui.BeginPopup("##combo_list"); - ImGuiNET.ImGui.PopStyleVar(2); - ImGuiNET.ImGui.PopStyleColor(2); - if (open) - { - var pdl = ImGuiNET.ImGui.GetWindowDrawList(); - float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; - for (int i = 0; i < items.Length; i++) - { - ImGuiNET.ImGui.PushID(i); - Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos(); - bool picked = ImGuiNET.ImGui.InvisibleButton("##item", new Vector2(iw, 20)); - bool ih = ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.PopID(); - bool sel = i == current; - pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? TabActive : ih ? Lighten(BtnFill) : BtnFill); - pdl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord); - pdl.AddText(f10, f10.FontSize, ip + new Vector2(6, (20 - f10.FontSize) * 0.5f), sel ? Teal : TextDim, items[i]); - ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); - if (picked) - { - Changed(row, i); - ImGuiNET.ImGui.CloseCurrentPopup(); - } - } - ImGuiNET.ImGui.EndPopup(); - } - - ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - } - - private static void Section(string text, float w) - { - var dl = ImGuiNET.ImGui.GetWindowDrawList(); - ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); - float h = bold.FontSize + 4; - dl.AddRectFilled(p, p + new Vector2(w, h), TabActive); - dl.AddText(bold, bold.FontSize, p + new Vector2(4, 2), Amber, text); - ImGuiNET.ImGui.Dummy(new Vector2(w, h)); - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - } - - private static void Note(string text, float w) - { - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - bool small = !text.StartsWith('('); - if (small) ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); - ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); - ImGuiNET.ImGui.TextUnformatted(text); - ImGuiNET.ImGui.PopTextWrapPos(); - ImGuiNET.ImGui.PopStyleColor(); - if (small) ImGuiNET.ImGui.PopFont(); - } - - private void CraftingStatus(SettingRow row) - { - ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), row.Label); - ImGuiNET.ImGui.SameLine(0, 6); - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(_data.MissileCraftingActive ? 0xFFE8B333 : 0xFFB8C8D8), _data.MissileCraftingState); - ImGuiNET.ImGui.PopFont(); - if (!string.IsNullOrEmpty(_data.MissileCraftingStatus)) - { - ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); - ImGuiNET.ImGui.TextWrapped(_data.MissileCraftingStatus); - ImGuiNET.ImGui.PopStyleColor(); - ImGuiNET.ImGui.PopFont(); - } - } - - private static bool StepButton(string id, Vector2 pos, string glyph) - { - var dl = ImGuiNET.ImGui.GetWindowDrawList(); - ImGuiNET.ImGui.SetCursorScreenPos(pos); - bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(18, 20)); - uint bg = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill; - dl.AddRectFilled(pos, pos + new Vector2(18, 20), bg); - dl.AddRect(pos, pos + new Vector2(18, 20), BtnBord); - PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(18, 20), TextDim); - return clicked; - } - // Tab icons by tab name (SettingsSchema); a tab not listed shows its name alone. private static readonly System.Collections.Generic.Dictionary TabIcons = new() { @@ -588,11 +210,6 @@ internal sealed class SettingsFace : IImGuiPanel return label; } - private static void Tooltip(SettingRow row) - { - if (row.Tooltip != null) ImGuiNET.ImGui.SetItemTooltip(row.Tooltip); - } - private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0); diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs new file mode 100644 index 0000000..6305770 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs @@ -0,0 +1,542 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/SettingsRows.cs +// Draws rows of the Settings schema (UI/Data/SettingsData.cs) with the +// Settings panel's look: square toggle dots, - [value] + steppers (typed +// values commit on Enter or when the field loses focus, then clamp; bad +// input reverts), combo pickers, amber section headers, tooltips. Moved out +// of SettingsFace (2026-10-14) so the dashboard's drawers draw the same rows: +// My settings (QuickSettingsDrawer.cs) and the Patrol drawer's settings. +// +// Each user keeps a private copy of the hub's settings and saves the whole +// copy (SettingsCommands.Save) on each change; a newer fetch replaces the +// copy only while none of its fields is being typed in (Sync, once a frame). +// The owner subscribes UiSources.Settings while it shows. +// +// Right-click a row: Pin to / Remove from My settings (UI/QuickSettings.cs), +// plus whatever the owner adds (the drawer's Move up / down). +// AC thread only. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Text; +using ImGuiNET; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class SettingsRows +{ + // ── Palette (SettingsPanel's, ARGB) ───────────────────────────────── + private static readonly uint ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455); + private static uint Teal => RynthTheme.Accent; + private static uint Amber => RynthTheme.Highlight; + private static uint Mute => RynthTheme.TextMuted; + private static uint TextDim => RynthTheme.Text; + private static uint ShellBg => RynthTheme.Background; + private static uint PanelBg => RynthTheme.Field; + private static uint BtnFill => RynthTheme.Button; + private static uint BtnBord => RynthTheme.Border; + private static uint TabActive => RynthTheme.Selected; + private static uint C(uint argb) => RynthTheme.Argb(argb); + + private RynthAiSettings _data = new(); + private long _seenVersion = -1; + private bool _editing; + + // Typed-value buffers, one per numeric row (UTF-8, NUL-terminated). + private sealed class NumberEdit + { + public readonly byte[] Buffer = new byte[24]; + public double Shown = double.NaN; + public bool Active; // the box had keyboard focus last frame + } + private readonly Dictionary _edits = new(); + // Text rows being typed in (the saved value shows again once the box loses focus). + private readonly Dictionary _textEdits = new(); + // The Hotkeys tab (engine-side; not part of RynthAi's settings). + private readonly HotkeysSettingsUi _hotkeys = new(); + + /// The copy being edited (the last fetch, plus this view's own changes). + public RynthAiSettings Data => _data; + + /// Once a frame, before the rows: takes a newer fetch unless a value is being typed in. + public void Sync() + { + var snap = UiSources.Settings.Current; + if (snap != null && snap.Version != _seenVersion && !_editing) + { + _seenVersion = snap.Version; + _data = snap.Value.Clone(); + } + _editing = false; + } + + /// The hotkeys editor's tab was left (or the panel closed). + public void LeaveHotkeys() => _hotkeys.Leave(); + + /// + /// One row at the cursor, wide. The caller pushes an ID per row. + /// : right-click offers Pin to / Remove from My settings; + /// adds items to that menu (given the row's pin key). + /// + public void DrawRow(SettingRow row, float w, bool pinMenu = true, Action? extraMenu = null) + { + Vector2 top = ImGuiNET.ImGui.GetCursorScreenPos(); + DrawRowBody(row, w); + if (!pinMenu) return; + string? key = QuickSettings.KeyOf(row); + if (key == null) return; + Vector2 bottom = ImGuiNET.ImGui.GetCursorScreenPos(); + if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right) + && ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) + && ImGuiNET.ImGui.IsMouseHoveringRect(top, new Vector2(top.X + w, MathF.Max(bottom.Y, top.Y + 4)))) + ImGuiNET.ImGui.OpenPopup("##pin_menu"); + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 6)); + bool open = ImGuiNET.ImGui.BeginPopup("##pin_menu"); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return; + try + { + bool pinned = QuickSettings.IsPinned(key); + if (ImGuiNET.ImGui.MenuItem(pinned ? PhosphorIcons.X + " Remove from My settings" : PhosphorIcons.PushPin + " Pin to My settings")) + QuickSettings.SetPinned(key, !pinned); + ImGuiNET.ImGui.SetItemTooltip(pinned + ? "Take it out of the My settings drawer on the dashboard (the setting itself doesn't change)." + : "Add it to the My settings drawer on the dashboard, for quick changes."); + extraMenu?.Invoke(key); + } + finally { ImGuiNET.ImGui.EndPopup(); } + } + + private void DrawRowBody(SettingRow row, float w) + { + switch (row.Kind) + { + case SettingKind.Bool: BoolRow(row, w); break; + case SettingKind.Int: + case SettingKind.Float: + case SettingKind.Double: NumberRow(row, w); break; + case SettingKind.Combo: ComboRow(row, w); break; + case SettingKind.Section: Section(row.Label, w); break; + case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break; + case SettingKind.Note: Note(row.Label, w); break; + case SettingKind.CraftingStatus: CraftingStatus(row); break; + case SettingKind.Button: ButtonRow(row, w); break; + case SettingKind.TraceCategories: TraceCategoriesRow(row, w); break; + case SettingKind.Text: TextRow(row, w); break; + case SettingKind.Status: StatusRow(row, w); break; + case SettingKind.Hotkeys: _editing |= _hotkeys.Draw(w); break; + case SettingKind.Color: ColorRow(row, w); break; + } + } + + // [All on] [All off], then a 3-column grid of square toggles, one per + // RynthAi trace category. Edits the copy's DiagCategories and saves like any other row. + private void TraceCategoriesRow(SettingRow row, float w) + { + var cats = TraceCategoryLevels.Parse(_data.DiagCategories); + if (cats.Count == 0) + { + Note("Waiting for RynthAi...", w); + return; + } + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (ImGuiNET.ImGui.Button("All on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true)); + ImGuiNET.ImGui.SameLine(0, 6); + if (ImGuiNET.ImGui.Button("All off")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", false)); + Tooltip(row); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float colW = Math.Max(80f, w / 3f); + int perRow = Math.Max(1, (int)(w / colW)); + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + for (int i = 0; i < cats.Count; i++) + { + var (name, level) = cats[i]; + bool on = level != TraceCategoryLevels.Off; + string label = TraceCategoryLevels.Label(name, level); + var p = start + new Vector2(i % perRow * colW, i / perRow * 18f); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.PushID(name); + if (ImGuiNET.ImGui.InvisibleButton("##cat", new Vector2(colW - 4, 16))) + SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, name, !on)); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + ImGuiNET.ImGui.PopID(); + dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2); + dl.PushClipRect(p, p + new Vector2(colW - 4, 16), true); + dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label); + dl.PopClipRect(); + } + int rowsUsed = (cats.Count + perRow - 1) / perRow; + ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, rowsUsed * 18f)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + } + + private void SaveCategories(string levels) + { + _data.DiagCategories = levels; + SettingsCommands.Save(_data.Clone()); + } + + // Label, then a full-width box; the value commits on Enter or focus loss (like the number boxes). + private void TextRow(SettingRow row, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); + ImGuiNET.ImGui.TextUnformatted(row.Label); + ImGuiNET.ImGui.PopStyleColor(); + Tooltip(row); + + string saved = row.GetText?.Invoke(_data) ?? string.Empty; + string text = _textEdits.TryGetValue(row, out string? typing) ? typing : saved; + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 4)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f); + bool enter = ImGuiNET.ImGui.InputTextWithHint("##text", row.Hint ?? string.Empty, ref text, 512u, + ImGuiInputTextFlags.EnterReturnsTrue); + bool active = ImGuiNET.ImGui.IsItemActive(); + bool committed = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(3); + Tooltip(row); + _editing |= active; + + if (committed) + { + _textEdits.Remove(row); + if (!string.Equals(text, saved, StringComparison.Ordinal)) + { + row.SetText?.Invoke(_data, text); + SettingsCommands.Save(_data.Clone()); + } + } + else if (active) _textEdits[row] = text; + else _textEdits.Remove(row); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + // RynthAi's one-line status (teal), wrapped to the column. + private void StatusRow(SettingRow row, float w) + { + string text = row.GetText?.Invoke(_data) ?? string.Empty; + if (text.Length == 0) return; + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } + + // Label | [caption]; Click posts its own work (never runs plugin code on AC's thread). + private static void ButtonRow(SettingRow row, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); + ImGuiNET.ImGui.AlignTextToFramePadding(); + ImGuiNET.ImGui.TextUnformatted(row.Label); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f)); + if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label)) + row.Click?.Invoke(); + Tooltip(row); + } + + private void Changed(SettingRow row, double value) + { + row.Set!(_data, value); + SettingsCommands.Save(_data.Clone()); + } + + // Square dot + label; the whole row toggles. + private void BoolRow(SettingRow row, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool on = row.Get!(_data) != 0; + float labelW = ImGuiNET.ImGui.CalcTextSize(row.Label).X; + if (ImGuiNET.ImGui.InvisibleButton("##b", new Vector2(Math.Min(w, 18 + labelW), 16))) + Changed(row, on ? 0 : 1); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + Tooltip(row); + dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2); + dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + // Label | [-] [value] [+]; the value commits on Enter or focus loss. + private void NumberRow(SettingRow row, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + bool isInt = row.Kind == SettingKind.Int; + float boxW = isInt ? 52 : 64, boxCol = isInt ? 56 : 68; + double value = Math.Clamp(row.Get!(_data), row.Min, row.Max); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float right = p.X + w; + dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); + ImGuiNET.ImGui.InvisibleButton("##label", new Vector2(Math.Max(1, w - 40 - boxCol), 22)); + Tooltip(row); + + float plusX = right - 20, boxX = plusX - boxCol + (boxCol - boxW) * 0.5f, minusX = right - 20 - boxCol - 20; + if (StepButton("##minus", new Vector2(minusX + 1, p.Y + 1), PhosphorIcons.Minus)) + Changed(row, Math.Clamp(value - row.Step, row.Min, row.Max)); + + // Typed value (amber on the panel colour). + NumberEdit edit = EditFor(row); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(boxX, p.Y + 1)); + ImGuiNET.ImGui.SetNextItemWidth(boxW); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f); + if (!edit.Active && edit.Shown != value) + WriteValue(edit, value, isInt); + ImGuiNET.ImGui.InputText("##v", edit.Buffer, (uint)edit.Buffer.Length, + ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.AutoSelectAll); + bool active = ImGuiNET.ImGui.IsItemActive(); + edit.Active = active; + _editing |= active; + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + if (TryParse(edit.Buffer, out double typed)) + { + double clamped = Math.Clamp(isInt ? Math.Round(typed) : typed, row.Min, row.Max); + Changed(row, clamped); + WriteValue(edit, clamped, isInt); + } + else WriteValue(edit, value, isInt); // bad input reverts + } + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(3); + + if (StepButton("##plus", new Vector2(plusX + 1, p.Y + 1), PhosphorIcons.Plus)) + Changed(row, Math.Clamp(value + row.Step, row.Min, row.Max)); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + // Label | [swatch]; a click opens a colour picker. These are the theme's colours (engine-stored): each + // change applies at once and is saved by the theme, so the profile isn't saved for it. + private void ColorRow(SettingRow row, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); + const float swatchW = 52; + ImGuiNET.ImGui.InvisibleButton("##label", new Vector2(Math.Max(1, w - swatchW - 8), 22)); + Tooltip(row); + + uint argb = (uint)row.Get!(_data); + var col = new Vector4(((argb >> 16) & 0xFF) / 255f, ((argb >> 8) & 0xFF) / 255f, (argb & 0xFF) / 255f, 1f); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + w - swatchW, p.Y + 1)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + if (ImGuiNET.ImGui.ColorButton("##swatch", col, ImGuiColorEditFlags.NoAlpha | ImGuiColorEditFlags.NoTooltip, new Vector2(swatchW, 20))) + ImGuiNET.ImGui.OpenPopup("##picker"); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.SetItemTooltip("Click to pick a colour."); + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + bool open = ImGuiNET.ImGui.BeginPopup("##picker"); + ImGuiNET.ImGui.PopStyleColor(2); + if (open) + { + var rgb = new Vector3(col.X, col.Y, col.Z); + ImGuiNET.ImGui.SetNextItemWidth(200); + if (ImGuiNET.ImGui.ColorPicker3("##pick", ref rgb, ImGuiColorEditFlags.NoAlpha | ImGuiColorEditFlags.NoSidePreview + | ImGuiColorEditFlags.PickerHueWheel | ImGuiColorEditFlags.DisplayHex)) + { + uint packed = 0xFF000000 | ((uint)MathF.Round(Math.Clamp(rgb.X, 0f, 1f) * 255) << 16) + | ((uint)MathF.Round(Math.Clamp(rgb.Y, 0f, 1f) * 255) << 8) | (uint)MathF.Round(Math.Clamp(rgb.Z, 0f, 1f) * 255); + row.Set!(_data, packed); + } + ImGuiNET.ImGui.EndPopup(); + } + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + private NumberEdit EditFor(SettingRow row) + { + if (!_edits.TryGetValue(row, out NumberEdit? e)) + _edits[row] = e = new NumberEdit(); + return e; + } + + private static void WriteValue(NumberEdit edit, double value, bool isInt) + { + string text = isInt ? ((long)Math.Round(value)).ToString(CultureInfo.InvariantCulture) + : value.ToString("G4", CultureInfo.InvariantCulture); + int n = Encoding.UTF8.GetBytes(text, 0, text.Length, edit.Buffer, 0); + edit.Buffer[Math.Min(n, edit.Buffer.Length - 1)] = 0; + edit.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); + } + + // Label | [current item]; click opens a 220 px list with the current item highlighted. + private void ComboRow(SettingRow row, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + string[] items = row.Items!; + int current = Math.Clamp((int)row.Get!(_data), 0, items.Length - 1); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + dl.AddText(p + new Vector2(0, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, row.Label); + + ImFontPtr f10 = ImGuiFonts.Get(UiFont.Ui10); + const float btnW = 160; + var bp = new Vector2(p.X + w - btnW, p.Y + 1); + ImGuiNET.ImGui.SetCursorScreenPos(bp); + if (ImGuiNET.ImGui.InvisibleButton("##combo", new Vector2(btnW, 20))) + { + ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Max(bp.X + btnW - 220, 0), bp.Y + 20)); + ImGuiNET.ImGui.OpenPopup("##combo_list"); + } + bool hot = ImGuiNET.ImGui.IsItemHovered(); + Tooltip(row); + dl.AddRectFilled(bp, bp + new Vector2(btnW, 20), hot ? Lighten(BtnFill) : BtnFill); + dl.AddRect(bp, bp + new Vector2(btnW, 20), BtnBord); + dl.PushClipRect(bp, bp + new Vector2(btnW - 16, 20), true); + dl.AddText(f10, f10.FontSize, bp + new Vector2(4, (20 - f10.FontSize) * 0.5f), TextDim, items[current]); + dl.PopClipRect(); + PhosphorIcons.DrawCentered(dl, f10, PhosphorIcons.CaretDown, bp + new Vector2(btnW - 16, 0), new Vector2(14, 20), Mute); + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(220, items.Length * 21 + 4)); + bool open = ImGuiNET.ImGui.BeginPopup("##combo_list"); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopStyleColor(2); + if (open) + { + var pdl = ImGuiNET.ImGui.GetWindowDrawList(); + float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; + for (int i = 0; i < items.Length; i++) + { + ImGuiNET.ImGui.PushID(i); + Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos(); + bool picked = ImGuiNET.ImGui.InvisibleButton("##item", new Vector2(iw, 20)); + bool ih = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + bool sel = i == current; + pdl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? TabActive : ih ? Lighten(BtnFill) : BtnFill); + pdl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord); + pdl.AddText(f10, f10.FontSize, ip + new Vector2(6, (20 - f10.FontSize) * 0.5f), sel ? Teal : TextDim, items[i]); + ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); + if (picked) + { + Changed(row, i); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + } + ImGuiNET.ImGui.EndPopup(); + } + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + private static void Section(string text, float w) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + float h = bold.FontSize + 4; + dl.AddRectFilled(p, p + new Vector2(w, h), TabActive); + dl.AddText(bold, bold.FontSize, p + new Vector2(4, 2), Amber, text); + ImGuiNET.ImGui.Dummy(new Vector2(w, h)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + } + + private static void Note(string text, float w) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + bool small = !text.StartsWith('('); + if (small) ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + if (small) ImGuiNET.ImGui.PopFont(); + } + + private void CraftingStatus(SettingRow row) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), row.Label); + ImGuiNET.ImGui.SameLine(0, 6); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(_data.MissileCraftingActive ? RynthTheme.Highlight : RynthTheme.TextMuted), _data.MissileCraftingState); + ImGuiNET.ImGui.PopFont(); + if (!string.IsNullOrEmpty(_data.MissileCraftingStatus)) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); + ImGuiNET.ImGui.TextWrapped(_data.MissileCraftingStatus); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopFont(); + } + } + + private static bool StepButton(string id, Vector2 pos, string glyph) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(18, 20)); + uint bg = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill; + dl.AddRectFilled(pos, pos + new Vector2(18, 20), bg); + dl.AddRect(pos, pos + new Vector2(18, 20), BtnBord); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(18, 20), TextDim); + return clicked; + } + + private static void Tooltip(SettingRow row) + { + if (row.Tooltip != null) ImGuiNET.ImGui.SetItemTooltip(row.Tooltip); + } + + private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); + private static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0); + + private static uint Scale(uint abgr, float k, int add) + { + uint a = abgr & 0xFF000000; + uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add); + uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add); + uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add); + return a | (b << 16) | (g << 8) | r; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs index beb9412..6249b30 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs @@ -58,8 +58,8 @@ internal sealed partial class SkillsFace : IImGuiPanel // ── Palette (FaceKit's, plus the vitals') ──────────────────────────── private static readonly uint Mana = RynthTheme.Argb(0xFF4DA6FF), Dim = RynthTheme.Argb(0xFF7F8FA0), - ExpandedBg = RynthTheme.Argb(0xFF1A2E42), GroupBg = RynthTheme.Argb(0xFF0F1A24), - MasteryColor = RynthTheme.Argb(0xFFC9A2FF); + GroupBg = RynthTheme.Argb(0xFF0F1A24), MasteryColor = RynthTheme.Argb(0xFFC9A2FF); + private static uint ExpandedBg => RynthTheme.Selected; private const float RowH = 24f, IconSize = 20f, ColBuffed = 46f, ColBase = 46f, ColCost = 76f, ColButton = 52f, CaretW = 16f, MultiW = 190f; diff --git a/src/RynthCore.Engine/ImGui/Panels/WorldMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/WorldMapFace.cs new file mode 100644 index 0000000..95ccd30 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/WorldMapFace.cs @@ -0,0 +1,264 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/WorldMapFace.cs +// The World Map: an interactive map of Dereth, opened from the RynthNav panel's Map button. +// The map itself is WorldMapView (also the Mini Map's); this face is the toolbar around it: +// Follow keeps you centred (a drag, or Fit, turns it off; a double click on the map turns it on) +// Rotate turns the map so the way you face is up +// - + Fit zoom out / in / the whole world +// Show which kinds of place, and the labels / route / path / grid / characters / buildings layers +// Find a place by name (the Atlas's surface places, towns and dungeons first): Enter or a click +// centres on it, zooms in and rings it +// and, over the map's top-left, what is under the cursor: its coordinates, the place's name, and how +// far and which way it is from you. +// Settings (zoom, Follow, Rotate, the layers) last across sessions (WorldMapSettings). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +/// The data both map faces draw from: subscribed while a face is open. +internal static class WorldMapFeeds +{ + private static readonly string VectorPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "NavData", "worldmap.vec"); + + public static void Subscribe() + { + UiSources.RynthNav.Subscribe(); + UiSources.RynthNav.RequestRefresh(); + UiSources.Radar.Subscribe(); + UiSources.Radar.RequestRefresh(); + RynthNavAtlas.EnsureLoadedForNames(); + WorldMapMaps.Refresh(); // finds which map pictures are installed and opens the one to use + WorldMapVectors.Open(VectorPath); + } + + public static void Unsubscribe() + { + UiSources.RynthNav.Unsubscribe(); + UiSources.Radar.Unsubscribe(); + } + + /// The characters feed (RynthNet) is polled only while the layer is on; each face keeps its own flag. + public static void SyncCharacters(ref bool subscribed) + { + bool want = WorldMapSettings.Characters; + if (want == subscribed) return; + subscribed = want; + if (want) { UiSources.Characters.Subscribe(); UiSources.Characters.RequestRefresh(); } + else UiSources.Characters.Unsubscribe(); + } + + public static void ReleaseCharacters(ref bool subscribed) + { + if (subscribed) UiSources.Characters.Unsubscribe(); + subscribed = false; + } +} + +internal sealed class WorldMapFace : IImGuiPanel +{ + public const string Title = "World Map"; + + public static void Register() + { + WorldMapSettings.Load(); // engine init thread: the file read stays off AC's thread + ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(680, 600), new Vector2(340, 280), EdgeToEdge: true, GripInBody: true, NoPopOut: true, OpenCentered: true), + () => new WorldMapFace()); + MiniMapFace.Register(); + } + + private readonly WorldMapView _view = new(mini: false); + private bool _charsSub; + private readonly byte[] _find = new byte[64]; + private string _findText = ""; + private List _found = new(); + private bool _findOpen; + private Vector2 _findBoxMin, _findBoxMax; + + public void OnShown() => WorldMapFeeds.Subscribe(); + + public void OnHidden() + { + WorldMapFeeds.Unsubscribe(); + WorldMapFeeds.ReleaseCharacters(ref _charsSub); + _findOpen = false; + } + + public void Draw() + { + WorldMapFeeds.SyncCharacters(ref _charsSub); + float w = Begin(out Vector2 origin, out Vector2 size); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + try + { + RynthNavStatus? st = UiSources.RynthNav.Current?.Value; + RadarView? radar = UiSources.Radar.Current?.Value; + MapPlayer pl = WorldMapView.GatherPlayer(st, radar); + CharacterRow[]? chars = WorldMapSettings.Characters ? UiSources.Characters.Current?.Value?.Rows : null; + + Vector2 barPos = ImGuiNET.ImGui.GetCursorScreenPos(); + float canvasTop = DrawToolbar(barPos, w, pl.Known); + var canvasMin = new Vector2(origin.X + 1, canvasTop); + var canvasMax = new Vector2(origin.X + size.X - 1, origin.Y + size.Y - 1); + + // The find dropdown covers part of the map: tell the map to ignore the mouse there. + (Vector2, Vector2)? drop = null; + if (_findOpen && _found.Count > 0) + { + var dmin = new Vector2(_findBoxMin.X, _findBoxMax.Y + 2); + drop = (dmin, dmin + new Vector2(Math.Max(_findBoxMax.X - _findBoxMin.X, 250f), _found.Count * 20 + 4)); + } + _view.Blocked = drop; + _view.Draw(canvasMin, canvasMax, pl, st, chars); + + // What's under the cursor, over the map's top-left. + string tip = _view.HoverText; + if (tip.Length > 0) + { + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(tip); + Vector2 a = canvasMin + new Vector2(8, 8), b = a + ts + new Vector2(12, 8); + if (b.X < canvasMax.X - 8) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(a, b, RynthTheme.Argb(0xD00A121A), 4); + dl.AddText(a + new Vector2(6, 4), Text, tip); + } + } + + DrawFindDropdown(drop); + WorldMapSettings.FlushIfDue(); + } + finally + { + ImGuiNET.ImGui.PopFont(); + End(origin, size); + } + } + + // ── Toolbar ────────────────────────────────────────────────────────── + private float DrawToolbar(Vector2 pos, float width, bool canFollow) + { + float x = pos.X, y = pos.Y; + const float h = 22f; + bool follow = _view.Follow, rotate = _view.Rotate; + if (Button("##wm_follow", "Follow", new Vector2(x, y), new Vector2(54, h), follow ? Teal : Text, follow ? Selected : BtnFill, + enabled: canFollow, border: follow ? Teal : 0)) + _view.Follow = !follow; + x += 58; + if (Button("##wm_rotate", "Rotate", new Vector2(x, y), new Vector2(52, h), rotate ? Teal : Text, rotate ? Selected : BtnFill, + enabled: canFollow, border: rotate ? Teal : 0)) + _view.Rotate = !rotate; + x += 56; + if (Button("##wm_out", "-", new Vector2(x, y), new Vector2(24, h), Text, BtnFill)) _view.ZoomBy(1f / 1.5f); + x += 28; + if (Button("##wm_in", "+", new Vector2(x, y), new Vector2(24, h), Text, BtnFill)) _view.ZoomBy(1.5f); + x += 28; + if (Button("##wm_fit", "Fit", new Vector2(x, y), new Vector2(34, h), Text, BtnFill)) _view.FitWorld(); + x += 38; + if (Button("##wm_show", "Show", new Vector2(x, y), new Vector2(46, h), Text, BtnFill)) ImGuiNET.ImGui.OpenPopup("##wm_show_pop"); + var showMenuAt = new Vector2(x, y + h + 2); + x += 50; + + ImGuiNET.ImGui.SetNextWindowPos(showMenuAt); + if (ImGuiNET.ImGui.BeginPopup("##wm_show_pop")) + { + // Which picture: the best installed, or one of the installed ones. + var installed = WorldMapMaps.Installed; + if (installed.Length > 0) + { + ImGuiNET.ImGui.TextDisabled("Map detail" + (WorldMapMaps.CurrentLabel.Length > 0 ? ": " + WorldMapMaps.CurrentLabel : "")); + if (ImGuiNET.ImGui.RadioButton("Best installed", WorldMapSettings.Detail.Length == 0)) { WorldMapSettings.Detail = ""; WorldMapSettings.MarkDirty(); WorldMapMaps.Apply(); } + foreach (var t in installed) + if (ImGuiNET.ImGui.RadioButton(t.Label, WorldMapSettings.Detail == t.Key)) { WorldMapSettings.Detail = t.Key; WorldMapSettings.MarkDirty(); WorldMapMaps.Apply(); } + ImGuiNET.ImGui.Separator(); + } + for (int k = 0; k < (int)WorldMapView.Kind.Count; k++) + if (ImGuiNET.ImGui.Checkbox(WorldMapView.KindNames[k], ref WorldMapSettings.Show[k])) WorldMapSettings.MarkDirty(); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.Checkbox("Labels", ref WorldMapSettings.Labels)) WorldMapSettings.MarkDirty(); + if (ImGuiNET.ImGui.Checkbox("Route", ref WorldMapSettings.Route)) WorldMapSettings.MarkDirty(); + if (ImGuiNET.ImGui.Checkbox("Walking path", ref WorldMapSettings.WalkPath)) WorldMapSettings.MarkDirty(); + if (ImGuiNET.ImGui.Checkbox("Grid", ref WorldMapSettings.Grid)) WorldMapSettings.MarkDirty(); + if (ImGuiNET.ImGui.Checkbox("Other characters", ref WorldMapSettings.Characters)) WorldMapSettings.MarkDirty(); + if (ImGuiNET.ImGui.Checkbox("Buildings and roads", ref WorldMapSettings.Buildings)) WorldMapSettings.MarkDirty(); + ImGuiNET.ImGui.EndPopup(); + } + + // Find: the rest of the row, at most 220 px. + float room = pos.X + width - x; + if (room >= 90) + { + float fw = Math.Min(room, 220f); + _findBoxMin = new Vector2(x, y); + _findBoxMax = new Vector2(x + fw, y + h); + bool enter = TextBox("##wm_findbox", _find, _findBoxMin, fw, "Find a place", out bool active, ImGuiInputTextFlags.EnterReturnsTrue); + string text = Utf8(_find).Trim(); + if (text != _findText) + { + _findText = text; + _found = WorldMapView.Find(text, 8); + _findOpen = text.Length > 0; + } + else if (active && text.Length > 0) _findOpen = true; + if (active && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape, false)) ClearFind(); + if (enter && _found.Count > 0) PickFound(_found[0]); + else if (enter) ClearFind(); + } + else _findBoxMin = _findBoxMax = new Vector2(x, y); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, y + 28)); + return y + 28; + } + + private void ClearFind() + { + Array.Clear(_find); + _findText = ""; + _found = new List(); + _findOpen = false; + } + + private void PickFound(NavPlace p) + { + float zoom = p.Type switch { "Town" => 3.5f, "Dungeon" => 5f, _ => 7f }; + _view.Show(p.Name, p.Ns, p.Ew, zoom); + ClearFind(); + } + + /// The results under the find box. Drawn after the map, so its buttons win the mouse. + private void DrawFindDropdown((Vector2 Min, Vector2 Max)? drop) + { + if (drop is not { } d || !_findOpen || _found.Count == 0) return; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos; + bool inBox = mouse.X >= _findBoxMin.X && mouse.X <= _findBoxMax.X && mouse.Y >= _findBoxMin.Y && mouse.Y <= _findBoxMax.Y; + bool inDrop = mouse.X >= d.Min.X && mouse.X <= d.Max.X && mouse.Y >= d.Min.Y && mouse.Y <= d.Max.Y; + if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left) && !inBox && !inDrop) { _findOpen = false; return; } + + dl.AddRectFilled(d.Min, d.Max, ShellBg, 4); + dl.AddRect(d.Min, d.Max, Teal, 4); + NavPlace? pick = null; + for (int i = 0; i < _found.Count; i++) + { + NavPlace p = _found[i]; + var rowMin = new Vector2(d.Min.X + 2, d.Min.Y + 2 + i * 20); + var rowSize = new Vector2(d.Max.X - d.Min.X - 4, 20); + ImGuiNET.ImGui.SetCursorScreenPos(rowMin); + bool clicked = ImGuiNET.ImGui.InvisibleButton("##wm_found" + i, rowSize); + if (ImGuiNET.ImGui.IsItemHovered()) dl.AddRectFilled(rowMin, rowMin + rowSize, Selected, 3); + dl.AddText(rowMin + new Vector2(6, 3), Text, p.Name); + string t = p.Type; + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(t); + dl.AddText(rowMin + new Vector2(rowSize.X - ts.X - 6, 3), Mute, t); + if (clicked) pick = p; + } + if (pick != null) PickFound(pick); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/WorldMapMaps.cs b/src/RynthCore.Engine/ImGui/Panels/WorldMapMaps.cs new file mode 100644 index 0000000..c85d973 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/WorldMapMaps.cs @@ -0,0 +1,110 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/WorldMapMaps.cs +// Which World Map picture to use. NavData and MapPacks can hold up to four, each a pyramid of tiles at its own +// resolution (RynthNav.Baker --map-world): worldmap-p64.rmap (Maximum, 64 px per cell), worldmap-p32.rmap (Extreme, 32), worldmap-ultra.rmap (16), worldmap-hd.rmap (8) and +// worldmap.rmap (Standard: the one everybody gets). The launcher offers the bigger ones as optional +// downloads, so a PC may have any of them: by default the best installed is used, and the Show menu's Detail +// list lets a player pick another that is installed. The choice is remembered (WorldMapSettings.Detail). +// The folder is scanned on a pool thread (no file access on AC's thread); a change of file is made by +// WorldMapTiles.Switch at the start of the next frame. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class WorldMapMaps +{ + internal readonly record struct Tier(string Key, string Label, string File); + + /// Best first. + public static readonly Tier[] Tiers = + { + new("maximum", "Maximum", "worldmap-p64.rmap"), + new("extreme", "Extreme", "worldmap-p32.rmap"), + new("ultra", "Ultra", "worldmap-ultra.rmap"), + new("hd", "HD", "worldmap-hd.rmap"), + new("standard", "Standard", "worldmap.rmap"), + }; + + private static volatile Tier[] _installed = Array.Empty(); + private static volatile bool _scanned; + private static volatile Dictionary _paths = new(); // tier key -> the file found + + /// RynthNav's data folder: where the plugin says it is, else the default. Any thread. + public static string Dir + { + get + { + string dir = UiSources.RynthNav.Current?.Value?.NavDir ?? ""; + return dir.Length > 0 && Path.IsPathFullyQualified(dir) ? dir.TrimEnd((char)92, (char)47) : Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "NavData"); + } + } + + /// Where the launcher puts the optional sizes: MapPacks, beside the NavData folder. + public static string PacksDir => Path.Combine(Path.GetDirectoryName(Dir) ?? Dir, "MapPacks"); + + /// The tiers found on the last scan, best first (empty until the first scan finishes). + public static Tier[] Installed => _installed; + public static bool Scanned => _scanned; + + /// The file found for a tier (the NavData name when none was found, so a status can name it). + public static string PathOf(Tier t) => _paths.TryGetValue(t.Key, out string? p) ? p : Path.Combine(Dir, t.File); + + /// The tier the setting calls for: that one if installed, else the best installed ("" and null when none). + public static Tier? Resolve(string preference) + { + Tier[] have = _installed; + if (have.Length == 0) return null; + foreach (Tier t in have) if (t.Key == preference) return t; + return have[0]; + } + + /// Scans the folder and (re)opens the chosen file, without touching AC's thread. Any thread. + public static void Refresh() + { + Task.Run(() => + { + var found = new List(); + var paths = new Dictionary(); + string[] dirs = { PacksDir, Dir }; // a pack the launcher installed, else the one with the RynthNav data + foreach (Tier t in Tiers) + { + foreach (string d in dirs) + { + string f = Path.Combine(d, t.File); + try { if (File.Exists(f)) { found.Add(t); paths[t.Key] = f; break; } } catch { } + } + } + _paths = paths; + _installed = found.ToArray(); + _scanned = true; + Apply(); + }); + } + + /// Opens (or switches to) the file the current setting resolves to. + public static void Apply() + { + Tier? t = Resolve(WorldMapSettings.Detail); + // Nothing installed: ask for the Standard name, so the faces say "No world map file yet". + string path = t is Tier tier ? PathOf(tier) : PathOf(Tiers[^1]); + if (WorldMapTiles.CurrentPath.Length == 0) WorldMapTiles.Open(path); + else WorldMapTiles.Switch(path); + } + + /// The label of the tier in use ("" until a file is open). + public static string CurrentLabel + { + get + { + string cur = WorldMapTiles.CurrentPath; + foreach (Tier t in Tiers) if (cur.EndsWith(t.File, StringComparison.OrdinalIgnoreCase)) return t.Label; + return ""; + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/WorldMapSettings.cs b/src/RynthCore.Engine/ImGui/Panels/WorldMapSettings.cs new file mode 100644 index 0000000..cb49b13 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/WorldMapSettings.cs @@ -0,0 +1,121 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/WorldMapSettings.cs +// What the World Map and the Mini Map remember: each view's zoom, Follow and Rotate, and the layer +// switches they share (which kinds of place, labels, route, path, grid, other characters). +// Engine-wide, in %LOCALAPPDATA%\RynthCore\world_map_settings.txt, like dungeon_map_settings.txt. +// Zoom changes a lot (every wheel tick), so a change only marks the settings dirty; Draw calls +// FlushIfDue and the file is written (in the background) once nothing has changed for 1.5 s. +// ============================================================================ + +using System; +using System.Globalization; +using System.IO; +using System.Text; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class WorldMapSettings +{ + internal sealed class ViewState + { + public float Scale = 1.5f; // screen px per cell + public bool Follow = true, Rotate; + } + + public static readonly ViewState Full = new() { Scale = 1.5f, Follow = true, Rotate = false }; + public static readonly ViewState Mini = new() { Scale = 2.5f, Follow = true, Rotate = true }; + + /// Which kinds of place show (WorldMapView.Kind order). + public static readonly bool[] Show = { true, true, true, true, true, true, true, true }; + /// Which map picture: a WorldMapMaps tier key ("ultra", "hd", "standard"), or "" for the best installed. + public static string Detail = ""; + public static bool Labels = true, Route = true, WalkPath = true, Grid = true, Characters = true, Buildings = true; + + private static readonly object Sync = new(); + private static bool _loaded; + private static long _dirtyAtMs; // 0: nothing to write + + private static string FilePath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "world_map_settings.txt"); + + /// Reads the file once. Engine init thread or any pool thread (not AC's). + public static void Load() + { + lock (Sync) + { + if (_loaded) return; + _loaded = true; + try + { + if (!File.Exists(FilePath)) return; + foreach (string raw in File.ReadAllLines(FilePath)) + { + string line = raw.Trim(); + if (line.Length == 0 || line[0] == '#') continue; + int eq = line.IndexOf('='); + if (eq <= 0) continue; + string key = line[..eq].Trim(), val = line[(eq + 1)..].Trim(); + bool on = val == "1"; + switch (key) + { + case "full.scale": Full.Scale = ParseScale(val, Full.Scale); break; + case "full.follow": Full.Follow = on; break; + case "full.rotate": Full.Rotate = on; break; + case "mini.scale": Mini.Scale = ParseScale(val, Mini.Scale); break; + case "mini.follow": Mini.Follow = on; break; + case "mini.rotate": Mini.Rotate = on; break; + case "detail": Detail = val is "maximum" or "extreme" or "ultra" or "hd" or "standard" ? val : ""; break; + case "labels": Labels = on; break; + case "route": Route = on; break; + case "path": WalkPath = on; break; + case "grid": Grid = on; break; + case "characters": Characters = on; break; + case "buildings": Buildings = on; break; + default: + if (key.StartsWith("show.", StringComparison.Ordinal) + && int.TryParse(key.AsSpan(5), NumberStyles.Integer, CultureInfo.InvariantCulture, out int k) && (uint)k < (uint)Show.Length) + Show[k] = on; + break; + } + } + } + catch { /* best-effort: the defaults are in place */ } + } + } + + private static float ParseScale(string v, float fallback) => + float.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f) ? Math.Clamp(f, 0.12f, 14f) : fallback; + + /// Something changed: the file is written when it has been quiet for a moment. Any thread. + public static void MarkDirty() => _dirtyAtMs = Math.Max(1, Environment.TickCount64); + + /// AC's render thread, once a frame: writes the file if a change has settled. + public static void FlushIfDue() + { + long at = _dirtyAtMs; + if (at == 0 || Environment.TickCount64 - at < 1500) return; + _dirtyAtMs = 0; + var sb = new StringBuilder("# RynthCore world map settings - auto-generated, hand-edits OK.\n"); + void Flag(string k, bool v) => sb.Append(k).Append('=').Append(v ? '1' : '0').Append('\n'); + sb.Append(CultureInfo.InvariantCulture, $"full.scale={Full.Scale:0.###}\n"); Flag("full.follow", Full.Follow); Flag("full.rotate", Full.Rotate); + sb.Append(CultureInfo.InvariantCulture, $"mini.scale={Mini.Scale:0.###}\n"); Flag("mini.follow", Mini.Follow); Flag("mini.rotate", Mini.Rotate); + for (int i = 0; i < Show.Length; i++) Flag("show." + i, Show[i]); + sb.Append("detail=").Append(Detail).Append((char)10); + Flag("labels", Labels); Flag("route", Route); Flag("path", WalkPath); Flag("grid", Grid); Flag("characters", Characters); Flag("buildings", Buildings); + string text = sb.ToString(); + UiBackgroundWriter.Enqueue("world map settings", () => + { + lock (Sync) + { + try + { + string? dir = Path.GetDirectoryName(FilePath); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(FilePath, text); + } + catch { /* non-fatal */ } + } + }); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/WorldMapView.cs b/src/RynthCore.Engine/ImGui/Panels/WorldMapView.cs new file mode 100644 index 0000000..31fdf19 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/WorldMapView.cs @@ -0,0 +1,833 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/WorldMapView.cs +// The map itself, drawn into a rectangle by the World Map face (full: toolbar, find box) and the +// Mini Map face (a small follow-you view). One class so both look and behave the same. +// +// The picture is NavData\worldmap.rmap (WorldMapTiles; RynthNav.Baker --map --map-tiles renders it +// from client_cell_1.dat): a pyramid of 256 px tiles, so zooming in loads sharper tiles under the +// view and the coarser ones already loaded show meanwhile. +// +// On it (bottom to top): the tiles; a coordinate grid with edge labels; RynthNav's route (legs +// between its steps, a dashed jump for a portal / recall / Town Network step, the current step +// ringed) and the walking path it worked out; the Atlas's places (each kind from its own zoom, +// labels from a closer one, none that would overlap one already drawn); your other characters +// (RynthNet); a search highlight; the arrow's target; you (an arrow while RynthAi's radar feed +// gives a heading, a dot from RynthNav alone, dimmed at the last outdoor spot while indoors). +// +// Rotate turns the map so the way you face is up (the arrow points up, the compass shows north). +// Drag pans (and turns Follow off), the wheel zooms about the cursor. A click (full) or a right +// click (both) on the map or a place opens a menu: Go here, Route here, Arrow here, Copy +// coordinates (RynthNav's commands, RynthNavCommands). +// +// Coordinates: a "cell" is 24 yards, 10 per map degree: cell = degrees * 10 + 1019.5 on each axis +// (the same numbers as NavCoords). The map works in cell units; the picture is cells * PixelsPerCell. +// Screen = centre + R(phi) * (east, -north) * scale, phi = heading - 90 degrees when rotating. +// +// Data (subscribed by the faces while open): UiSources.RynthNav (position, route, arrow, path), +// UiSources.Radar (heading), UiSources.Characters (other characters, when that layer is on). +// ============================================================================ + +using System; +using System.Collections.Generic; +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; + +/// Where you are, for the toolbar and the view: this frame's reading, with the last outdoor spot kept. +internal readonly struct MapPlayer +{ + public MapPlayer(bool have, double ns, double ew, float heading, bool indoors, double lastNs, double lastEw) + { Have = have; Ns = ns; Ew = ew; Heading = heading; Indoors = indoors; LastNs = lastNs; LastEw = lastEw; } + /// An outdoor position this frame. + public readonly bool Have; + public readonly double Ns, Ew; + public readonly float Heading; // degrees, 0 = east, 90 = north; NaN when only RynthNav's pose is known + public readonly bool Indoors; + public readonly double LastNs, LastEw; // the last outdoor spot (NaN: never outdoors this session) + public bool Known => Have || !double.IsNaN(LastNs); + public double ShowNs => Have ? Ns : LastNs; + public double ShowEw => Have ? Ew : LastEw; +} + +internal sealed class WorldMapView +{ + public enum Kind { Town, Landmark, Dungeon, Lifestone, Bindstone, Portal, Vendor, Npc, Count } + public static readonly string[] KindNames = { "Towns", "Landmarks", "Dungeons", "Lifestones", "Bindstones", "Portals", "Vendors", "NPCs" }; + + // ── Constants ──────────────────────────────────────────────────────── + public const double Origin = 1019.5; // cell = degrees * 10 + Origin + public const float MinScale = 0.12f, MaxScale = 14f, AbsMaxScale = 160f; // screen px per cell + /// How far in the open map is worth zooming: a sharper map (more pixels per cell) allows more, up to 1.25x its own detail. + private static float MaxScaleNow => WorldMapTiles.IsOpen ? Math.Clamp(WorldMapTiles.PixelsPerCell * 1.25f, MaxScale, AbsMaxScale) : MaxScale; + private static readonly float[] ShowFrom = { 0f, 1.2f, 1.0f, 2.0f, 2.0f, 3.0f, 5.0f, 6.0f }; + private static readonly float[] LabelFrom = { 0.45f, 3f, 2.5f, 5f, 5f, 6f, 8f, 10f }; + private static readonly uint OceanBg = RynthTheme.Argb(0xFF1C4276); + private static readonly uint[] KindColour = + { + RynthTheme.Argb(0xFFFFD24D), RynthTheme.Argb(0xFFFFFFFF), RynthTheme.Argb(0xFFC77DFF), RynthTheme.Argb(0xFF5CE1E6), + RynthTheme.Argb(0xFF3DDC97), RynthTheme.Argb(0xFFFF6BD6), RynthTheme.Argb(0xFFFF9F43), RynthTheme.Argb(0xFFF2F2A0), + }; + private static readonly uint LabelCol = RynthTheme.Argb(0xFFF4F7FA), LabelHalo = RynthTheme.Argb(0xE0000000), + RouteCol = RynthTheme.Argb(0xFFFFA733), RouteActive = RynthTheme.Argb(0xFFFFF04D), PathCol = RynthTheme.Argb(0xFF5AD2FF), + TargetCol = RynthTheme.Argb(0xFF4DD2FF), PlayerFill = RynthTheme.Argb(0xFF33FF66), PlayerEdge = RynthTheme.Argb(0xFF0A2A12), + CharCol = RynthTheme.Argb(0xFF6EA8FF), HintCol = RynthTheme.Argb(0xFF9FB3C8), BarBg = RynthTheme.Argb(0xE00A121A), + RoadCol = RynthTheme.Argb(0xFFE6CD78), RoadHalo = RynthTheme.Argb(0xB0301C08), BuildFill = RynthTheme.Argb(0xFF9A4B40), + BuildEdge = RynthTheme.Argb(0xFF2A1410), GridLine = RynthTheme.Argb(0x30FFFFFF), GridLabel = RynthTheme.Argb(0xC0DDE8F4), HighlightCol = RynthTheme.Argb(0xFFFFFFFF); + + // ── Places (shared by every view; rebuilt when the Atlas reloads) ──── + private readonly struct Mark + { + public Mark(float cx, float cy, string name, Kind kind, NavPlace place) { Cx = cx; Cy = cy; Name = name; Kind = kind; Place = place; } + public readonly float Cx, Cy; + public readonly string Name; + public readonly Kind Kind; + public readonly NavPlace Place; + } + private static Mark[]? _marks; + private static long _marksVersion = -1; + private static double _lastNs = double.NaN, _lastEw = double.NaN; // the last outdoor spot, shared by both views + + public static double CellOf(double degrees) => degrees * 10.0 + Origin; + public static double DegreesOf(double cell) => (cell - Origin) / 10.0; + + // ── This view ──────────────────────────────────────────────────────── + public readonly bool Mini; + private readonly WorldMapSettings.ViewState _st; + private double _ccx = 1019.5, _ccy = 1019.5; // map cell at the canvas centre + private bool _fitNext, _centreNext; + private Vector2 _centre; + private float _phi; // the map's rotation this frame (radians) + private float _scale; + private MapProjection Proj => new(_centre, _ccx, _ccy, _scale, _phi); + + public float Scale => _scale; + public bool Follow { get => _st.Follow; set { if (_st.Follow != value) { _st.Follow = value; WorldMapSettings.MarkDirty(); } } } + public bool Rotate { get => _st.Rotate; set { if (_st.Rotate != value) { _st.Rotate = value; WorldMapSettings.MarkDirty(); } } } + /// The line the toolbar shows for the point under the cursor ("" when none). + public string HoverText { get; private set; } = ""; + /// A screen rectangle the face has covered (a dropdown): the map ignores the mouse inside it. + public (Vector2 Min, Vector2 Max)? Blocked; + + // Interaction. + private bool _pressing, _pressMoved; + private int _hoverMark = -1, _hoverChar = -1; + private double _ctxNs, _ctxEw; + private string _ctxName = ""; + private bool _openCtx; + private readonly string _ctxId; + private string _hiName = ""; + private double _hiNs, _hiEw; + private long _hiUntilMs; + private readonly List<(Vector2 Min, Vector2 Max)> _labelRects = new(128); + private readonly List<(Vector2 Pos, int Index)> _drawn = new(256); + private readonly List<(Vector2 Pos, int Index)> _drawnChars = new(16); + private readonly List<(int Dist, int Col, int Row)> _tileOrder = new(128); + private CharacterRow[] _chars = Array.Empty(); + + public WorldMapView(bool mini) + { + Mini = mini; + _st = mini ? WorldMapSettings.Mini : WorldMapSettings.Full; + _scale = Math.Clamp(_st.Scale, MinScale, AbsMaxScale); + _ctxId = mini ? "##mm_ctx" : "##wm_ctx"; + } + + // ── Commands from the face ─────────────────────────────────────────── + public void FitWorld() { _fitNext = true; } + + public void ZoomBy(float k, Vector2? about = null) + { + float old = _scale; + float next = Math.Clamp(_scale * k, MinScale, MaxScaleNow); + if (next == old) return; + if (about is Vector2 m && !_st.Follow) + (_ccx, _ccy) = Proj.CentreForZoomAbout(m, next); + _scale = next; + _st.Scale = _scale; + WorldMapSettings.MarkDirty(); + } + + /// Centres on a map point (degrees), zooming in to at least , and rings it for a few seconds. + public void Show(string name, double ns, double ew, float minScale) + { + Follow = false; + _ccx = CellOf(ew); _ccy = CellOf(ns); + if (_scale < minScale) { _scale = Math.Min(minScale, MaxScaleNow); _st.Scale = _scale; WorldMapSettings.MarkDirty(); } + _hiName = name; _hiNs = ns; _hiEw = ew; + _hiUntilMs = Environment.TickCount64 + 6000; + } + + // ── Projection (MapProjection) ─────────────────────────────────────── + private Vector2 Project(double cx, double cy) => Proj.Project(cx, cy); + private Vector2 ProjectDeg(double ns, double ew) => Proj.Project(CellOf(ew), CellOf(ns)); + private void Unproject(Vector2 p, out double cx, out double cy) => Proj.Unproject(p, out cx, out cy); + private Vector2 ScreenDir(float east, float north) => Proj.ScreenDir(east, north); + + // ── Player ─────────────────────────────────────────────────────────── + /// Reads where you are: the radar feed (heading), else RynthNav's pose. Indoors keeps the last outdoor spot. + public static MapPlayer GatherPlayer(RynthNavStatus? st, RadarView? radar) + { + double ns = double.NaN, ew = double.NaN; + float heading = float.NaN; + bool indoors = false; + if (radar != null) + { + indoors = radar.Live.IsIndoor; + if (!indoors && !double.IsNaN(radar.Live.Ns) && !double.IsNaN(radar.Live.Ew)) { ns = radar.Live.Ns; ew = radar.Live.Ew; heading = radar.Live.Player.Heading; } + } + if (double.IsNaN(ns) && st != null && st.HasPose) + { + indoors = indoors || st.Indoors; + if (!st.Indoors) { ns = st.NS; ew = st.EW; } + } + if (!double.IsNaN(ns)) { _lastNs = ns; _lastEw = ew; } + return new MapPlayer(!double.IsNaN(ns), ns, ew, heading, indoors, _lastNs, _lastEw); + } + + // ── The frame ──────────────────────────────────────────────────────── + /// Draws the map into the canvas and handles its input. AC's render thread, inside a face's Draw. + public void Draw(Vector2 canvasMin, Vector2 canvasMax, in MapPlayer pl, RynthNavStatus? st, CharacterRow[]? chars) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 csize = canvasMax - canvasMin; + if (csize.X < 40 || csize.Y < 40) return; + _centre = (canvasMin + canvasMax) * 0.5f; + _chars = chars ?? Array.Empty(); + + if (_fitNext) + { + _fitNext = false; + Follow = false; Rotate = false; + _scale = Math.Clamp(Math.Min(csize.X, csize.Y) / (float)WorldMapTiles.CellsHigh, MinScale, MaxScale); + _st.Scale = _scale; + _ccx = WorldMapTiles.CellsWide * 0.5; _ccy = WorldMapTiles.CellsHigh * 0.5; + WorldMapSettings.MarkDirty(); + } + if (_scale > MaxScaleNow) { _scale = MaxScaleNow; _st.Scale = _scale; } + _phi = _st.Rotate && !float.IsNaN(pl.Heading) && pl.Have ? MapProjection.PhiForHeading(pl.Heading) : 0f; + if (_st.Follow && pl.Known) { _ccx = CellOf(pl.ShowEw); _ccy = CellOf(pl.ShowNs); } + + dl.AddRectFilled(canvasMin, canvasMax, OceanBg); + dl.PushClipRect(canvasMin, canvasMax, true); + DrawTiles(dl, canvasMin, canvasMax); + _labelRects.Clear(); _drawn.Clear(); _drawnChars.Clear(); + if (WorldMapSettings.Grid) DrawGrid(dl, canvasMin, canvasMax, _phi != 0f); + if (WorldMapSettings.Buildings) DrawVectors(dl, canvasMin, canvasMax); + if (WorldMapSettings.Route) DrawRoute(dl, st, pl); + DrawMarkers(dl, canvasMin, canvasMax); + if (WorldMapSettings.Characters) DrawCharacters(dl, canvasMin, canvasMax); + DrawHighlight(dl); + DrawTarget(dl, st); + DrawPlayer(dl, pl); + dl.PopClipRect(); + dl.AddRect(canvasMin, canvasMax, BtnBord); + DrawScaleBar(dl, canvasMin, canvasMax); + DrawCompass(dl, canvasMax); + + if (!WorldMapTiles.IsOpen || WorldMapTiles.Levels.Count == 0) + DrawCentred(dl, _centre, WorldMapTiles.Status.Length > 0 ? WorldMapTiles.Status : "Loading the map..."); + else if (pl.Indoors && !pl.Have && pl.Known && _st.Follow) + DrawCentred(dl, new Vector2(_centre.X, canvasMin.Y + 20), "Indoors: the map shows where you went in."); + else if (!pl.Known && _st.Follow) + DrawCentred(dl, new Vector2(_centre.X, canvasMin.Y + 20), "Waiting for your position..."); + + Input(canvasMin, canvasMax, pl); + DrawContextMenu(); + } + + // ── Tiles ──────────────────────────────────────────────────────────── + private void DrawTiles(ImDrawListPtr dl, Vector2 canvasMin, Vector2 canvasMax) + { + var levels = WorldMapTiles.Levels; + if (!WorldMapTiles.IsOpen || levels.Count == 0) return; + int ppc0 = WorldMapTiles.PixelsPerCell, top = levels.Count - 1; + double cellsHigh = WorldMapTiles.CellsHigh; + // The map area in view: the canvas as it is, or (turned) the circle around it. + double halfW = (canvasMax.X - canvasMin.X) * 0.5, halfH = (canvasMax.Y - canvasMin.Y) * 0.5; + if (_phi != 0f) { halfW = halfH = Math.Sqrt(halfW * halfW + halfH * halfH); } + double cxMin = _ccx - halfW / _scale, cxMax = _ccx + halfW / _scale; + double cyMin = _ccy - halfH / _scale, cyMax = _ccy + halfH / _scale; + + // The sharpest level whose pixels are at least as dense as the screen's; a coarser one if that is too many tiles. + int L = Math.Clamp((int)Math.Floor(Math.Log2(ppc0 / (double)_scale)), 0, top); + while (L < top && VisibleTiles(L, ppc0, cellsHigh, cxMin, cxMax, cyMin, cyMax) > 80) L++; + + // Coarse to fine: the top level (always loaded) first, so whatever hasn't arrived shows blurry, not blank. + for (int lv = top; lv >= L; lv--) + DrawLevel(dl, lv, ppc0, cellsHigh, cxMin, cxMax, cyMin, cyMax, request: lv <= Math.Min(top, L + 1)); + } + + private static int VisibleTiles(int lv, int ppc0, double cellsHigh, double cxMin, double cxMax, double cyMin, double cyMax) + { + double cpt = WorldMapTiles.TileSize * (double)(1 << lv) / ppc0; + int cols = (int)Math.Floor(Math.Min(cxMax, WorldMapTiles.CellsWide) / cpt) - (int)Math.Floor(Math.Max(cxMin, 0) / cpt) + 1; + int rows = (int)Math.Floor((cellsHigh - Math.Max(cyMin, 0)) / cpt) - (int)Math.Floor((cellsHigh - Math.Min(cyMax, cellsHigh)) / cpt) + 1; + return Math.Max(cols, 0) * Math.Max(rows, 0); + } + + private void DrawLevel(ImDrawListPtr dl, int lv, int ppc0, double cellsHigh, double cxMin, double cxMax, double cyMin, double cyMax, bool request) + { + var lvl = WorldMapTiles.Levels[lv]; + double cpt = WorldMapTiles.TileSize * (double)(1 << lv) / ppc0; + int c0 = Math.Max(0, (int)Math.Floor(cxMin / cpt)), c1 = Math.Min(lvl.Cols - 1, (int)Math.Floor(cxMax / cpt)); + int r0 = Math.Max(0, (int)Math.Floor((cellsHigh - cyMax) / cpt)), r1 = Math.Min(lvl.Rows - 1, (int)Math.Floor((cellsHigh - cyMin) / cpt)); + if (c1 < c0 || r1 < r0) return; + + // Centre-out, so the tiles you're looking at load first. + _tileOrder.Clear(); + double ccol = _ccx / cpt, crow = (cellsHigh - _ccy) / cpt; + for (int r = r0; r <= r1; r++) + for (int c = c0; c <= c1; c++) + { + double dx = c + 0.5 - ccol, dy = r + 0.5 - crow; + _tileOrder.Add(((int)((dx * dx + dy * dy) * 1000), c, r)); + } + _tileOrder.Sort(static (a, b) => a.Dist.CompareTo(b.Dist)); + + bool turned = _phi != 0f; + for (int i = _tileOrder.Count - 1; i >= 0; i--) // draw far to near; nothing overlaps within a level + { + var (_, c, r) = _tileOrder[i]; + IntPtr tex; + if (!(request ? WorldMapTiles.TryGet(lv, c, r, out tex) : WorldMapTiles.Peek(lv, c, r, out tex))) continue; + double left = c * cpt, right = (c + 1) * cpt, topCell = cellsHigh - r * cpt, bottomCell = cellsHigh - (r + 1) * cpt; + if (!turned) + { + // Edges from the same formula for both neighbours, rounded to whole pixels: no seams, no gaps. + float x0 = MathF.Round(_centre.X + (float)((left - _ccx) * _scale)), x1 = MathF.Round(_centre.X + (float)((right - _ccx) * _scale)); + float y0 = MathF.Round(_centre.Y - (float)((topCell - _ccy) * _scale)), y1 = MathF.Round(_centre.Y - (float)((bottomCell - _ccy) * _scale)); + dl.AddImage(tex, new Vector2(x0, y0), new Vector2(x1, y1)); + } + else + { + // Turned: a quad, grown by a pixel so neighbours overlap instead of showing a hairline. + Vector2 tl = Project(left, topCell), tr = Project(right, topCell), br = Project(right, bottomCell), bl = Project(left, bottomCell); + Vector2 mid = (tl + br) * 0.5f; + tl = Grow(tl, mid); tr = Grow(tr, mid); br = Grow(br, mid); bl = Grow(bl, mid); + dl.AddImageQuad(tex, tl, tr, br, bl, new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)); + } + } + } + + private static Vector2 Grow(Vector2 p, Vector2 mid) + { + Vector2 d = p - mid; + float len = d.Length(); + return len < 1f ? p : p + d / len * 0.8f; + } + + // ── Grid ───────────────────────────────────────────────────────────── + private void DrawGrid(ImDrawListPtr dl, Vector2 canvasMin, Vector2 canvasMax, bool turned) + { + float pxPerDeg = 10f * _scale; + float[] steps = { 50f, 20f, 10f, 5f, 2f, 1f, 0.5f, 0.2f, 0.1f, 0.05f }; + float step = steps[0]; + foreach (float s in steps) if (s * pxPerDeg >= 90f) step = s; + if (step * pxPerDeg < 40f) return; + double halfW = (canvasMax.X - canvasMin.X) * 0.5, halfH = (canvasMax.Y - canvasMin.Y) * 0.5; + double r = Math.Sqrt(halfW * halfW + halfH * halfH) / _scale; // cells, the circle around the canvas + double nsMin = DegreesOf(_ccy - r), nsMax = DegreesOf(_ccy + r), ewMin = DegreesOf(_ccx - r), ewMax = DegreesOf(_ccx + r); + string fmt = step >= 1f ? "0" : step >= 0.1f ? "0.0" : "0.00"; + int lines = 0; + for (double ns = Math.Ceiling(nsMin / step) * step; ns <= nsMax && lines < 60; ns += step, lines++) + { + Vector2 a = ProjectDeg(ns, ewMin), b = ProjectDeg(ns, ewMax); + dl.AddLine(a, b, GridLine, 1f); + if (!turned) EdgeLabel(dl, new Vector2(canvasMin.X + 4, a.Y - 14), canvasMin, canvasMax, Fmt(ns, fmt, 'N', 'S')); + } + for (double ew = Math.Ceiling(ewMin / step) * step; ew <= ewMax && lines < 120; ew += step, lines++) + { + Vector2 a = ProjectDeg(nsMin, ew), b = ProjectDeg(nsMax, ew); + dl.AddLine(a, b, GridLine, 1f); + if (!turned) EdgeLabel(dl, new Vector2(a.X + 3, canvasMin.Y + 3), canvasMin, canvasMax, Fmt(ew, fmt, 'E', 'W')); + } + } + + private static string Fmt(double v, string fmt, char pos, char neg) => + Math.Abs(v).ToString(fmt, CultureInfo.InvariantCulture) + (v >= 0 ? pos : neg); + + private static void EdgeLabel(ImDrawListPtr dl, Vector2 at, Vector2 min, Vector2 max, string text) + { + if (at.X < min.X || at.Y < min.Y || at.X > max.X - 30 || at.Y > max.Y - 14) return; + dl.AddText(at + new Vector2(1, 1), LabelHalo, text); + dl.AddText(at, GridLabel, text); + } + + // ── Roads and buildings (WorldMapVectors) ──────────────────────────── + private const float RoadsFrom = 1.5f, BuildingsFrom = 3f; + private readonly Vector2[] _poly = new Vector2[16]; + + private void DrawVectors(ImDrawListPtr dl, Vector2 canvasMin, Vector2 canvasMax) + { + if (_scale < RoadsFrom) return; + if (WorldMapTiles.IsOpen && WorldMapTiles.PixelsPerCell >= 8) return; // HD and up have the roads and the real roofs in the picture + WorldMapVectors.Data? v = WorldMapVectors.Current; + if (v == null) return; + // The map area in view, in cells (the circle around the canvas when turned). + double halfW = (canvasMax.X - canvasMin.X) * 0.5, halfH = (canvasMax.Y - canvasMin.Y) * 0.5; + if (_phi != 0f) halfW = halfH = Math.Sqrt(halfW * halfW + halfH * halfH); + float xMin = (float)(_ccx - halfW / _scale) - 1, xMax = (float)(_ccx + halfW / _scale) + 1; + float yMin = (float)(_ccy - halfH / _scale) - 1, yMax = (float)(_ccy + halfH / _scale) + 1; + + // Roads: a dark under-stroke and the road colour over it; wider as you zoom in. + float w = Math.Clamp(_scale * 0.4f, 1.5f, 6f); + ushort[] roads = v.Roads; + int visible = 0; + for (int i = 0; i + 3 < roads.Length && visible < 6000; i += 4) + { + float x0 = roads[i], y0 = roads[i + 1], x1 = roads[i + 2], y1 = roads[i + 3]; + if ((x0 < xMin && x1 < xMin) || (x0 > xMax && x1 > xMax) || (y0 < yMin && y1 < yMin) || (y0 > yMax && y1 > yMax)) continue; + visible++; + Vector2 a = Project(x0, y0), b = Project(x1, y1); + dl.AddLine(a, b, RoadHalo, w + 1.5f); + } + visible = 0; + for (int i = 0; i + 3 < roads.Length && visible < 6000; i += 4) + { + float x0 = roads[i], y0 = roads[i + 1], x1 = roads[i + 2], y1 = roads[i + 3]; + if ((x0 < xMin && x1 < xMin) || (x0 > xMax && x1 > xMax) || (y0 < yMin && y1 < yMin) || (y0 > yMax && y1 > yMax)) continue; + visible++; + dl.AddLine(Project(x0, y0), Project(x1, y1), RoadCol, w); + } + + if (_scale < BuildingsFrom) return; + for (int i = 0; i < v.Buildings.Length; i++) + { + Vector4 bb = v.BuildingBounds[i]; + if (bb.Z < xMin || bb.X > xMax || bb.W < yMin || bb.Y > yMax) continue; + Vector2[] pts = v.Buildings[i]; + int n = Math.Min(pts.Length, _poly.Length); + if (n < 3) continue; + float area = 0; + for (int k = 0; k < n; k++) + { + Vector2 p = Project(pts[k].X, pts[k].Y); + _poly[k] = p; + } + for (int k = 0; k < n; k++) { Vector2 a = _poly[k], b = _poly[(k + 1) % n]; area += a.X * b.Y - b.X * a.Y; } + if (area < 0) Array.Reverse(_poly, 0, n); // ImGui wants one winding; the flip of y makes it vary + dl.AddConvexPolyFilled(ref _poly[0], n, BuildFill); + for (int k = 0; k < n; k++) dl.AddLine(_poly[k], _poly[(k + 1) % n], BuildEdge, 1.2f); + } + } + + // ── Places ─────────────────────────────────────────────────────────── + private static void EnsureMarks() + { + long v = RynthNavAtlas.Version; + if (_marks != null && v == _marksVersion) return; + var list = new List(8192); + foreach (NavPlace p in RynthNavAtlas.Places) + { + if (!p.OnMap || double.IsNaN(p.Ns) || double.IsNaN(p.Ew)) continue; + Kind k; + switch (p.Type) + { + case "Town": k = Kind.Town; break; + case "Landmark": k = Kind.Landmark; break; + case "Dungeon": k = Kind.Dungeon; break; + case "Lifestone": k = Kind.Lifestone; break; + case "Bindstone": k = Kind.Bindstone; break; + case "Portal": k = Kind.Portal; break; + case "Vendor": k = Kind.Vendor; break; + case "NPC": k = Kind.Npc; break; + default: continue; + } + list.Add(new Mark((float)CellOf(p.Ew), (float)CellOf(p.Ns), p.Name, k, p)); + } + _marks = list.ToArray(); + _marksVersion = v; + } + + /// The Atlas's surface places whose name has in it, towns and dungeons first. Any thread. + public static List Find(string query, int max) + { + var res = new List<(int Rank, NavPlace Place)>(); + if (query.Length == 0) return new List(); + foreach (NavPlace p in RynthNavAtlas.Places) + { + if (!p.OnMap || p.Name.Length == 0) continue; + int at = p.Name.IndexOf(query, StringComparison.OrdinalIgnoreCase); + if (at < 0) continue; + int kind = p.Type switch { "Town" => 0, "Dungeon" => 1, "Landmark" => 2, "Lifestone" => 3, "Bindstone" => 3, "Portal" => 4, _ => 5 }; + res.Add((kind * 1000 + (at == 0 ? 0 : 400) + Math.Min(p.Name.Length, 399), p)); + } + res.Sort(static (a, b) => a.Rank.CompareTo(b.Rank)); + var list = new List(Math.Min(max, res.Count)); + for (int i = 0; i < res.Count && list.Count < max; i++) list.Add(res[i].Place); + return list; + } + + private void DrawMarkers(ImDrawListPtr dl, Vector2 canvasMin, Vector2 canvasMax) + { + EnsureMarks(); + Mark[]? marks = _marks; + if (marks == null) return; + float s = _scale; + // Towns first (they win a label overlap), then the rest in kind order. + for (int pass = 0; pass < (int)Kind.Count; pass++) + { + if (!WorldMapSettings.Show[pass] || s < ShowFrom[pass]) continue; + uint col = KindColour[pass]; + float rad = pass == (int)Kind.Town ? 5f : pass is (int)Kind.Npc or (int)Kind.Vendor ? 2.5f : 3.5f; + bool label = WorldMapSettings.Labels && s >= LabelFrom[pass]; + for (int i = 0; i < marks.Length; i++) + { + ref readonly Mark m = ref marks[i]; + if ((int)m.Kind != pass) continue; + Vector2 pt = Project(m.Cx, m.Cy); + if (pt.X < canvasMin.X - 40 || pt.X > canvasMax.X + 40 || pt.Y < canvasMin.Y - 12 || pt.Y > canvasMax.Y + 12) continue; + _drawn.Add((pt, i)); + bool hot = i == _hoverMark; + DrawMarkShape(dl, pt, m.Kind, col, hot ? rad + 1.5f : rad); + if (label || hot) DrawLabel(dl, pt, m.Name, rad, hot); + } + } + } + + private static void DrawMarkShape(ImDrawListPtr dl, Vector2 p, Kind k, uint col, float r) + { + switch (k) + { + case Kind.Dungeon: + dl.AddQuadFilled(p + new Vector2(0, -r - 1), p + new Vector2(r + 1, 0), p + new Vector2(0, r + 1), p + new Vector2(-r - 1, 0), col); + dl.AddQuad(p + new Vector2(0, -r - 1), p + new Vector2(r + 1, 0), p + new Vector2(0, r + 1), p + new Vector2(-r - 1, 0), LabelHalo, 1f); + break; + case Kind.Town: + dl.AddCircleFilled(p, r + 1, LabelHalo); + dl.AddCircleFilled(p, r, col); + dl.AddCircleFilled(p, r - 2.5f, LabelHalo); + break; + default: + dl.AddCircleFilled(p, r + 1, LabelHalo); + dl.AddCircleFilled(p, r, col); + break; + } + } + + private void DrawLabel(ImDrawListPtr dl, Vector2 pt, string text, float rad, bool force, uint? colour = null) + { + if (text.Length == 0) return; + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text); + var min = new Vector2(pt.X + rad + 4, pt.Y - ts.Y * 0.5f); + var max = min + ts; + if (!force) + { + for (int i = 0; i < _labelRects.Count; i++) + { + var (a, b) = _labelRects[i]; + if (min.X < b.X + 2 && max.X > a.X - 2 && min.Y < b.Y && max.Y > a.Y) return; + } + } + _labelRects.Add((min, max)); + dl.AddText(min + new Vector2(1, 1), LabelHalo, text); + dl.AddText(min + new Vector2(-1, 1), LabelHalo, text); + dl.AddText(min, force ? Text : colour ?? LabelCol, text); + } + + // ── Other characters (RynthNet) ────────────────────────────────────── + private void DrawCharacters(ImDrawListPtr dl, Vector2 canvasMin, Vector2 canvasMax) + { + for (int i = 0; i < _chars.Length; i++) + { + CharacterRow c = _chars[i]; + if (c.IsSelf || c.LoggedOut || !c.HasMap) continue; + Vector2 p = ProjectDeg(c.MapNs, c.MapEw); + if (p.X < canvasMin.X - 60 || p.X > canvasMax.X + 60 || p.Y < canvasMin.Y - 12 || p.Y > canvasMax.Y + 12) continue; + _drawnChars.Add((p, i)); + uint col = c.Stale ? (CharCol & 0x00FFFFFF) | 0x80000000u : CharCol; + var tri = new[] { p + new Vector2(0, -6), p + new Vector2(5.5f, 4), p + new Vector2(-5.5f, 4) }; + dl.AddTriangleFilled(tri[0], tri[1], tri[2], col); + dl.AddTriangle(tri[0], tri[1], tri[2], LabelHalo, 1.5f); + DrawLabel(dl, p, c.Name, 6f, i == _hoverChar, CharCol); + } + } + + // ── Route, path, target, highlight, player ─────────────────────────── + private void DrawRoute(ImDrawListPtr dl, RynthNavStatus? st, in MapPlayer pl) + { + if (st == null) return; + bool haveFrom = pl.Known; + + // The walking path RynthNav worked out (when it sends one): a line under the route's dots, a segment per walk. + bool havePath = WorldMapSettings.WalkPath && st.PathSegments.Length > 0; + if (havePath) + { + foreach (float[] seg in st.PathSegments) + { + Vector2 prevP = ProjectDeg(seg[0], seg[1]); + for (int i = 2; i + 1 < seg.Length; i += 2) + { + Vector2 q = ProjectDeg(seg[i], seg[i + 1]); + dl.AddLine(prevP, q, LabelHalo, 4f); + dl.AddLine(prevP, q, PathCol, 2.5f); + prevP = q; + } + } + } + + if (st.Route.Length > 0) + { + Vector2 prev = haveFrom ? ProjectDeg(pl.ShowNs, pl.ShowEw) : default; + bool havePrev = haveFrom; + for (int i = 0; i < st.Route.Length; i++) + { + RynthNavRouteStep step = st.Route[i]; + bool jump = step.Kind is "recall" or "portal" or "town"; + bool hasHere = step.Kind != "recall" && !(step.Ns == 0 && step.Ew == 0); + uint col = i == st.RouteIdx ? RouteActive : RouteCol; + if (hasHere) + { + Vector2 p = ProjectDeg(step.Ns, step.Ew); + if (havePrev && !havePath) dl.AddLine(prev, p, col, 2f); // straight legs only without a real path + DrawStepDot(dl, p, col, i == st.RouteIdx, jump); + prev = p; havePrev = true; + } + if (jump && step.HasLanding) + { + Vector2 q = ProjectDeg(step.LandNs, step.LandEw); + if (havePrev) DashedLine(dl, prev, q, col); + DrawStepDot(dl, q, col, false, false); + prev = q; havePrev = true; + } + } + } + } + + private void DrawTarget(ImDrawListPtr dl, RynthNavStatus? st) + { + RynthNavArrow? ar = st?.Arrow; + if (ar == null || !ar.OnMap) return; + Vector2 t = ProjectDeg(ar.Ns, ar.Ew); + dl.AddCircle(t, 8f, LabelHalo, 24, 4f); + dl.AddCircle(t, 8f, TargetCol, 24, 2f); + dl.AddCircleFilled(t, 2.5f, TargetCol); + } + + private void DrawHighlight(ImDrawListPtr dl) + { + long left = _hiUntilMs - Environment.TickCount64; + if (left <= 0) return; + Vector2 p = ProjectDeg(_hiNs, _hiEw); + float pulse = 10f + 5f * MathF.Sin(Environment.TickCount64 * 0.008f); + uint a = (uint)Math.Clamp(left / 6000f * 255f * 1.5f, 0, 255); + uint col = (HighlightCol & 0x00FFFFFF) | (a << 24); + dl.AddCircle(p, pulse + 1.5f, LabelHalo & 0x00FFFFFF | (a << 24), 28, 5f); + dl.AddCircle(p, pulse, col, 28, 2.5f); + if (_hiName.Length > 0) DrawLabel(dl, p, _hiName, pulse, true); + } + + private static void DrawStepDot(ImDrawListPtr dl, Vector2 p, uint col, bool current, bool jump) + { + dl.AddCircleFilled(p, 4.5f, LabelHalo); + dl.AddCircleFilled(p, jump ? 3.5f : 3f, col); + if (current) dl.AddCircle(p, 8f, col, 20, 2f); + } + + private static void DashedLine(ImDrawListPtr dl, Vector2 a, Vector2 b, uint col) + { + Vector2 d = b - a; + float len = d.Length(); + if (len < 1f || len > 20000f) return; + Vector2 u = d / len; + for (float t = 0; t < len; t += 12f) + dl.AddLine(a + u * t, a + u * Math.Min(t + 6f, len), col, 2f); + } + + private void DrawPlayer(ImDrawListPtr dl, in MapPlayer pl) + { + if (!pl.Known) return; + Vector2 p = ProjectDeg(pl.ShowNs, pl.ShowEw); + uint fill = pl.Have ? PlayerFill : (PlayerFill & 0x00FFFFFF) | 0x80000000u; + if (pl.Have && !float.IsNaN(pl.Heading)) + { + float h = pl.Heading * MathF.PI / 180f; // AC: 0 = east, 90 = north + Vector2 fwd = ScreenDir(MathF.Cos(h), MathF.Sin(h)); + var side = new Vector2(-fwd.Y, fwd.X); + Vector2 tip = p + fwd * 10f, l = p - fwd * 6f + side * 6f, r = p - fwd * 6f - side * 6f, back = p - fwd * 2.5f; + dl.AddTriangleFilled(tip, l, back, fill); + dl.AddTriangleFilled(tip, back, r, fill); + dl.AddTriangle(tip, l, r, PlayerEdge, 1.5f); + } + else + { + dl.AddCircleFilled(p, 6f, PlayerEdge); + dl.AddCircleFilled(p, 4.5f, fill); + } + if (pl.Indoors && !pl.Have) dl.AddCircle(p, 10f, fill, 24, 1.5f); + } + + // ── Furniture ──────────────────────────────────────────────────────── + private void DrawScaleBar(ImDrawListPtr dl, Vector2 canvasMin, Vector2 canvasMax) + { + // A cell is 24 yards: pick the roundest length under ~140 px (90 on the mini map). + float limit = Mini ? 90f : 140f; + float[] yards = { 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000 }; + float best = yards[0]; + foreach (float y in yards) if (y / 24f * _scale <= limit) best = y; + float px = best / 24f * _scale; + var a = new Vector2(canvasMin.X + 12, canvasMax.Y - 14); + var b = new Vector2(a.X + px, a.Y); + dl.AddLine(a + new Vector2(1, 1), b + new Vector2(1, 1), LabelHalo, 3f); + dl.AddLine(a, b, LabelCol, 2f); + dl.AddLine(a + new Vector2(0, -4), a + new Vector2(0, 2), LabelCol, 2f); + dl.AddLine(b + new Vector2(0, -4), b + new Vector2(0, 2), LabelCol, 2f); + string t = best >= 1000 ? (best / 1000).ToString("0.#", CultureInfo.InvariantCulture) + " k yd" : best.ToString("0", CultureInfo.InvariantCulture) + " yd"; + dl.AddText(a + new Vector2(1, -17), LabelHalo, t); + dl.AddText(a + new Vector2(0, -18), LabelCol, t); + } + + private void DrawCompass(ImDrawListPtr dl, Vector2 canvasMax) + { + // A needle at north: straight up while the map is north-up, turning as it rotates. + var c = new Vector2(canvasMax.X - 20, canvasMax.Y - 26); + Vector2 n = ScreenDir(0, 1); + var side = new Vector2(-n.Y, n.X); + dl.AddCircleFilled(c, 12, BarBg); + dl.AddCircle(c, 12, BtnBord); + dl.AddTriangleFilled(c + n * 9f, c - n * 1f + side * 3.5f, c - n * 1f - side * 3.5f, LabelCol); + dl.AddTriangleFilled(c - n * 9f, c + n * 1f + side * 3.5f, c + n * 1f - side * 3.5f, RynthTheme.Argb(0xFF6C7C8C)); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize("N"); + Vector2 lp = c + n * 17f - ts * 0.5f; + if (lp.Y > canvasMax.Y - 40) lp = c - n * 17f - ts * 0.5f; + dl.AddText(lp, LabelCol, "N"); + } + + private static void DrawCentred(ImDrawListPtr dl, Vector2 at, string text) + { + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text); + Vector2 min = at - ts * 0.5f - new Vector2(8, 5), max = at + ts * 0.5f + new Vector2(8, 5); + dl.AddRectFilled(min, max, BarBg, 4); + dl.AddText(at - ts * 0.5f, HintCol, text); + } + + // ── Input ──────────────────────────────────────────────────────────── + private void Input(Vector2 canvasMin, Vector2 canvasMax, in MapPlayer pl) + { + ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + ImGuiNET.ImGui.SetCursorScreenPos(canvasMin); + ImGuiNET.ImGui.InvisibleButton(Mini ? "##mm_canvas" : "##wm_canvas", Vector2.Max(canvasMax - canvasMin, new Vector2(1, 1)), + ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight); + Vector2 mouse = io.MousePos; + bool blocked = Blocked is { } b && mouse.X >= b.Min.X && mouse.X <= b.Max.X && mouse.Y >= b.Min.Y && mouse.Y <= b.Max.Y; + bool hovered = ImGuiNET.ImGui.IsItemHovered() && !blocked; + + // Nearest drawn character or place within reach, else the map point under the cursor. + _hoverMark = -1; _hoverChar = -1; + if (hovered || _pressing) + { + float best = 11f * 11f; + foreach (var (pos, idx) in _drawnChars) + { + float dd = Vector2.DistanceSquared(pos, mouse); + if (dd < best) { best = dd; _hoverChar = idx; _hoverMark = -1; } + } + foreach (var (pos, idx) in _drawn) + { + float dd = Vector2.DistanceSquared(pos, mouse); + if (dd < best) { best = dd; _hoverMark = idx; _hoverChar = -1; } + } + } + HoverText = ""; + if (hovered) + { + Unproject(mouse, out double hcx, out double hcy); + double hn = DegreesOf(hcy), he = DegreesOf(hcx); + string where = RynthNavStatus.Coord(hn, he); + string name = ""; + if (_hoverChar >= 0 && _hoverChar < _chars.Length) { name = _chars[_hoverChar].Name + " (character)"; hn = _chars[_hoverChar].MapNs; he = _chars[_hoverChar].MapEw; where = RynthNavStatus.Coord(hn, he); } + else if (_hoverMark >= 0 && _marks != null && _hoverMark < _marks.Length) { Mark m = _marks[_hoverMark]; name = m.Name + " (" + m.Place.Type + ")"; hn = m.Place.Ns; he = m.Place.Ew; where = RynthNavStatus.Coord(hn, he); } + HoverText = (name.Length > 0 ? name + " " : "") + where + FromYou(pl, hn, he); + } + + if (hovered && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) { _pressing = true; _pressMoved = false; } + if (hovered && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left) && pl.Known) { Follow = true; _pressing = false; } + if (_pressing && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 4f)) + { + _pressMoved = true; + Vector2 d = io.MouseDelta; + if (float.IsFinite(d.X) && float.IsFinite(d.Y) && d != Vector2.Zero) + { + Follow = false; + (_ccx, _ccy) = Proj.CentreAfterDrag(d); + } + } + if (_pressing && ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Left)) + { + if (!_pressMoved && hovered && !Mini) OpenMenuAt(mouse); + _pressing = false; + } + if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) _pressing = false; + if (hovered && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) OpenMenuAt(mouse); + + if (hovered) + { + float wheel = io.MouseWheel; + if (float.IsFinite(wheel) && wheel != 0f) ZoomBy(MathF.Pow(1.25f, wheel), mouse); + } + } + + /// " · 1.2 k yd NNE" from you to a point, or "". + private static string FromYou(in MapPlayer pl, double ns, double ew) + { + if (!pl.Known) return ""; + double dn = ns - pl.ShowNs, de = ew - pl.ShowEw; + double yards = Math.Sqrt(dn * dn + de * de) * 240.0; + if (yards < 5) return " · here"; + double bearing = Math.Atan2(de, dn) * 180.0 / Math.PI; + if (bearing < 0) bearing += 360.0; + string dist = yards >= 1000 ? (yards / 1000).ToString("0.0", CultureInfo.InvariantCulture) + " k yd" : ((int)yards).ToString(CultureInfo.InvariantCulture) + " yd"; + return " · " + dist + " " + RynthNavAtlas.CompassPoint(bearing); + } + + private void OpenMenuAt(Vector2 mouse) + { + if (_hoverChar >= 0 && _hoverChar < _chars.Length) + { + CharacterRow c = _chars[_hoverChar]; + _ctxNs = Math.Round(c.MapNs, 2); _ctxEw = Math.Round(c.MapEw, 2); _ctxName = c.Name; + } + else if (_hoverMark >= 0 && _marks != null && _hoverMark < _marks.Length) + { + Mark m = _marks[_hoverMark]; + _ctxNs = m.Place.Ns; _ctxEw = m.Place.Ew; _ctxName = m.Name; + } + else + { + Unproject(mouse, out double cx, out double cy); + _ctxNs = Math.Round(DegreesOf(cy), 2); + _ctxEw = Math.Round(DegreesOf(cx), 2); + _ctxName = ""; + } + _openCtx = true; + } + + private void DrawContextMenu() + { + if (_openCtx) { ImGuiNET.ImGui.OpenPopup(_ctxId); _openCtx = false; } + if (!ImGuiNET.ImGui.BeginPopup(_ctxId)) return; + string where = _ctxName.Length > 0 ? _ctxName : "Map point"; + ImGuiNET.ImGui.TextColored(new Vector4(1f, 0.82f, 0.3f, 1f), where); + ImGuiNET.ImGui.TextDisabled(RynthNavStatus.Coord(_ctxNs, _ctxEw)); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.Selectable("Go here")) RynthNavCommands.Go(where, _ctxNs, _ctxEw); + if (ImGuiNET.ImGui.Selectable("Route here")) RynthNavCommands.Route(where, _ctxNs, _ctxEw); + if (ImGuiNET.ImGui.Selectable("Arrow here")) RynthNavCommands.Arrow(where, _ctxNs, _ctxEw); + if (ImGuiNET.ImGui.Selectable("Copy coordinates")) ImGuiNET.ImGui.SetClipboardText(RynthNavStatus.CommandCoord(_ctxNs, _ctxEw)); + if (Mini) + { + ImGuiNET.ImGui.Separator(); + bool follow = Follow, rotate = Rotate; + if (ImGuiNET.ImGui.Checkbox("Follow me", ref follow)) Follow = follow; + if (ImGuiNET.ImGui.Checkbox("Rotate with me", ref rotate)) Rotate = rotate; + if (ImGuiNET.ImGui.Selectable("Zoom in")) ZoomBy(1.5f); + if (ImGuiNET.ImGui.Selectable("Zoom out")) ZoomBy(1f / 1.5f); + if (ImGuiNET.ImGui.Selectable("Open the World Map")) UI.PanelRouter.Toggle(WorldMapFace.Title); + } + ImGuiNET.ImGui.EndPopup(); + } +} diff --git a/src/RynthCore.Engine/ImGui/PhosphorIcons.cs b/src/RynthCore.Engine/ImGui/PhosphorIcons.cs index 8495ae7..f8369b7 100644 --- a/src/RynthCore.Engine/ImGui/PhosphorIcons.cs +++ b/src/RynthCore.Engine/ImGui/PhosphorIcons.cs @@ -111,6 +111,8 @@ internal static unsafe class PhosphorIcons public const string Play = "\uE3D0"; public const string Package = "\uE390"; public const string Plus = "\uE3D4"; + public const string SlidersHorizontal = "\uE434"; + public const string PushPin = "\uE3E2"; public const string Power = "\uE3DA"; public const string Resize = "\uED6E"; public const string Robot = "\uE762"; @@ -169,7 +171,8 @@ internal static unsafe class PhosphorIcons + ArrowCircleUp + Barbell + Brain + GraduationCap + Hourglass + SortDescending + Package + Binoculars + Crown + Sun + CastleTurret + ClockCounterClockwise + GlobeHemisphereWest + Path + Star + Target + User - + TextAa + Leaf + Keyboard; + + TextAa + Leaf + Keyboard + + PushPin + SlidersHorizontal + Wrench; /// /// Draws (one icon) centred in the box at diff --git a/src/RynthCore.Engine/ImGui/RynthTheme.cs b/src/RynthCore.Engine/ImGui/RynthTheme.cs index 4cb174d..0ef7daf 100644 --- a/src/RynthCore.Engine/ImGui/RynthTheme.cs +++ b/src/RynthCore.Engine/ImGui/RynthTheme.cs @@ -5,17 +5,137 @@ // (docs/IMGUI_PARITY_PLAN.md §4.4). Tokens are ABGR-packed ImGui colours // (ImGui.GetColorU32 order) built from the Avalonia #AARRGGBB literals. // +// Colour themes (Tom 2026-10-14): the structural colours come from a palette +// the player can change in Settings > Display: a preset (RynthCore, Ember, +// Verdant, Amethyst, Crimson, Slate) or their own eight colours (accent, +// highlight, background, title bars, buttons, borders, text, muted text). +// The other shades (selected rows, fields, hover, the dashboard's border...) +// are worked out from those eight; the RynthCore preset keeps every original +// colour exactly. Status colours (health, mana, the green on/red off of +// toggles, radar gold) don't follow the theme. The faces read the tokens +// (properties) every frame, so a change shows at once; the base ImGui style +// is re-coloured before the next frame (RefreshStyle, each ImGui context). +// Saved to %AppData%\RynthCore\theme.txt (preset=, then name=AARRGGBB for a +// custom palette's eight colours). +// // Apply() sets the base style once at context creation; per-window colours // (bar, RynthAi, Radar) are pushed around Begin by the panel host. // ============================================================================ using System; +using System.IO; using System.Numerics; using System.Runtime.InteropServices; using ImGuiNET; +using RynthCore.Engine.UI; namespace RynthCore.Engine.ImGuiBackend; +/// One colour theme: the eight colours a player picks, then the shades worked out from them (#AARRGGBB). +internal sealed class ThemePalette +{ + public const int Primaries = 8; + /// The eight colours a player picks, in Settings order. + public static readonly string[] PrimaryNames = { "Accent", "Highlight", "Background", "Title bars", "Buttons", "Borders", "Text", "Muted text" }; + private static readonly string[] PrimaryKeys = { "accent", "highlight", "background", "titlebar", "button", "border", "text", "muted" }; + + public readonly uint[] P = new uint[Primaries]; // Accent, Highlight, Background, TitleBar, Button, Border, Text, TextMuted + + // The shades worked out from P (Derive), or the original literals (Default). + public uint AccentFill, AccentAlt, BoxBg, Field, Selected, WindowBorder, DashBorder, PanelGlass, BarBg, FrameBg, + FrameHover, FrameActive, BarButtonBorder, RowAlt, MuteAlt, StyleText, PopupBg, FrameBgHover, FrameBgActive, SliderGrab; + + /// A copy (its own array of the eight). + public ThemePalette Clone() + { + var c = new ThemePalette + { + AccentFill = AccentFill, AccentAlt = AccentAlt, BoxBg = BoxBg, Field = Field, Selected = Selected, + WindowBorder = WindowBorder, DashBorder = DashBorder, PanelGlass = PanelGlass, BarBg = BarBg, FrameBg = FrameBg, + FrameHover = FrameHover, FrameActive = FrameActive, BarButtonBorder = BarButtonBorder, RowAlt = RowAlt, + MuteAlt = MuteAlt, StyleText = StyleText, PopupBg = PopupBg, FrameBgHover = FrameBgHover, + FrameBgActive = FrameBgActive, SliderGrab = SliderGrab, + }; + Array.Copy(P, c.P, Primaries); + return c; + } + + /// RynthCore's own colours, every shade exactly as it was before themes. + public static ThemePalette Default() + { + var t = new ThemePalette(); + t.P[0] = 0xFF26D9E6; t.P[1] = 0xFFE8B333; t.P[2] = 0xFF0A0F14; t.P[3] = 0xFF1A1A28; + t.P[4] = 0xFF16283A; t.P[5] = 0xFF34587A; t.P[6] = 0xFFF2F7FC; t.P[7] = 0xFFB8C8D8; + t.AccentFill = 0xFF264C59; t.AccentAlt = 0xFF26C1A6; t.BoxBg = 0xFF0A121A; t.Field = 0xFF141F29; + t.Selected = 0xFF1A2E42; t.WindowBorder = 0xFF008080; t.DashBorder = 0xFF264059; t.PanelGlass = 0xFF12121C; + t.BarBg = 0xFF0A0A14; t.FrameBg = 0xFF1A2230; t.FrameHover = 0xFF2A3850; t.FrameActive = 0xFF34466A; + t.BarButtonBorder = 0xFF3A4A5A; t.RowAlt = 0xFF101822; t.MuteAlt = 0xFFC8D6E4; t.StyleText = 0xFFE6E6E6; + t.PopupBg = 0xFF14141E; t.FrameBgHover = 0xFF243044; t.FrameBgActive = 0xFF2C3A52; t.SliderGrab = 0xFF26A18C; + return t; + } + + /// A palette from eight colours, the other shades worked out from them. + public static ThemePalette From(params uint[] primaries) + { + var t = new ThemePalette(); + for (int i = 0; i < Primaries; i++) t.P[i] = 0xFF000000 | primaries[i]; + t.Derive(); + return t; + } + + /// Works out the shades from the eight colours (each a mix of two of them, like the originals). + public void Derive() + { + uint accent = P[0], bg = P[2], title = P[3], button = P[4], border = P[5], text = P[6], muted = P[7]; + AccentFill = Mix(bg, accent, 0.30f); + AccentAlt = Mix(accent, bg, 0.12f); + BoxBg = Mix(bg, button, 0.15f); + Field = Mix(bg, button, 0.45f); + Selected = Mix(button, accent, 0.12f); + WindowBorder = Mix(bg, accent, 0.50f); + DashBorder = Mix(bg, border, 0.65f); + PanelGlass = Mix(bg, title, 0.40f); + BarBg = bg; + FrameBg = Mix(bg, button, 0.80f); + FrameHover = Mix(button, border, 0.40f); + FrameActive = Mix(button, border, 0.70f); + BarButtonBorder = Mix(button, border, 0.60f); + RowAlt = Mix(bg, button, 0.30f); + MuteAlt = Mix(muted, text, 0.30f); + StyleText = Mix(text, muted, 0.25f); + PopupBg = Mix(bg, title, 0.50f); + FrameBgHover = Mix(FrameBg, FrameHover, 0.50f); + FrameBgActive = Mix(FrameHover, FrameActive, 0.50f); + SliderGrab = Mix(AccentAlt, bg, 0.17f); + } + + /// #AARRGGBB mix: of the way from to , opaque. + public static uint Mix(uint a, uint b, float t) + { + static uint Ch(uint x, int shift) => (x >> shift) & 0xFF; + uint r = (uint)MathF.Round(Ch(a, 16) + (Ch(b, 16) - (float)Ch(a, 16)) * t); + uint g = (uint)MathF.Round(Ch(a, 8) + (Ch(b, 8) - (float)Ch(a, 8)) * t); + uint bl = (uint)MathF.Round(Ch(a, 0) + (Ch(b, 0) - (float)Ch(a, 0)) * t); + return 0xFF000000 | (r << 16) | (g << 8) | bl; + } + + // ── Presets ───────────────────────────────────────────────────────── + public static readonly string[] PresetNames = { "RynthCore", "Ember", "Verdant", "Amethyst", "Crimson", "Slate" }; + + public static ThemePalette Preset(int index) => index switch + { + 1 => From(0xFF8A3D, 0xFFD166, 0x140C0A, 0x24150F, 0x3A2116, 0x7A4A34, 0xFCF4F0, 0xD8C4B8), + 2 => From(0x4ADE80, 0xE8D333, 0x0A140D, 0x12201A, 0x16352A, 0x347A58, 0xF2FCF5, 0xB8D8C4), + 3 => From(0xB98CFF, 0xFFC857, 0x0F0A16, 0x1C1428, 0x2A1C40, 0x5A4A8A, 0xF6F2FC, 0xCBBEDC), + 4 => From(0xFF5C6C, 0xFFC857, 0x140A0C, 0x241216, 0x3A161E, 0x7A3442, 0xFCF2F3, 0xD8B8BE), + 5 => From(0xD0D8E0, 0xF0C060, 0x0E0F11, 0x1A1C20, 0x24282E, 0x4A5260, 0xF4F5F7, 0xB4BAC2), + _ => Default(), + }; + + // ── File (theme.txt) ──────────────────────────────────────────────── + public static string Key(int primary) => PrimaryKeys[primary]; +} + internal static class RynthTheme { /// Avalonia #AARRGGBB → ImGui packed colour (0xAABBGGRR). @@ -25,30 +145,91 @@ internal static class RynthTheme public static Vector4 Vec(uint argb) => new( ((argb >> 16) & 0xFF) / 255f, ((argb >> 8) & 0xFF) / 255f, (argb & 0xFF) / 255f, (argb >> 24) / 255f); + /// An ImGui packed colour (a token) as a Vector4 (TextColored, style colours). + public static Vector4 VecOf(uint abgr) => ImGuiNET.ImGui.ColorConvertU32ToFloat4(abgr); + + /// A token with another alpha (0..255). + public static uint WithAlpha(uint abgr, uint alpha) => (abgr & 0x00FFFFFF) | (alpha << 24); + + // ── The palette ──────────────────────────────────────────────────── + // The current palette's tokens, ABGR, swapped whole on a change (readers never lock). + private sealed class Tokens + { + public uint Accent, Highlight, Background, TitleBar, Button, Border, Text, TextMuted, + AccentFill, AccentAlt, BoxBg, Field, Selected, WindowBorder, DashBorder, PanelGlass, BarBg, FrameBg, + FrameHover, FrameActive, BarButtonBorder, RowAlt, MuteAlt, StyleText, PopupBg, FrameBgHover, FrameBgActive, SliderGrab; + + public Tokens(ThemePalette p) + { + Accent = Argb(p.P[0]); Highlight = Argb(p.P[1]); Background = Argb(p.P[2]); TitleBar = Argb(p.P[3]); + Button = Argb(p.P[4]); Border = Argb(p.P[5]); Text = Argb(p.P[6]); TextMuted = Argb(p.P[7]); + AccentFill = Argb(p.AccentFill); AccentAlt = Argb(p.AccentAlt); BoxBg = Argb(p.BoxBg); Field = Argb(p.Field); + Selected = Argb(p.Selected); WindowBorder = Argb(p.WindowBorder); DashBorder = Argb(p.DashBorder); + PanelGlass = Argb(p.PanelGlass); BarBg = Argb(p.BarBg); FrameBg = Argb(p.FrameBg); FrameHover = Argb(p.FrameHover); + FrameActive = Argb(p.FrameActive); BarButtonBorder = Argb(p.BarButtonBorder); RowAlt = Argb(p.RowAlt); + MuteAlt = Argb(p.MuteAlt); StyleText = Argb(p.StyleText); PopupBg = Argb(p.PopupBg); + FrameBgHover = Argb(p.FrameBgHover); FrameBgActive = Argb(p.FrameBgActive); SliderGrab = Argb(p.SliderGrab); + } + } + + private static readonly object Sync = new(); + private static ThemePalette _palette = ThemePalette.Default(); + private static volatile Tokens _t = new(_palette); + private static int _preset; // ThemePalette.PresetNames index, or Custom + private static int _version; + private static bool _loaded; + public const int Custom = -1; + + /// Bumped on every change: each ImGui context re-colours its base style when it differs. + public static int Version => System.Threading.Volatile.Read(ref _version); + + // Theme tokens (ABGR). The eight a player picks: + public static uint Accent => _t.Accent; + public static uint Highlight => _t.Highlight; + public static uint Background => _t.Background; + public static uint TitleBar => _t.TitleBar; + public static uint Button => _t.Button; + public static uint Border => _t.Border; + public static uint Text => _t.Text; + public static uint TextMuted => _t.TextMuted; + // ...and the shades worked out from them: + public static uint AccentFill => _t.AccentFill; + public static uint AccentAlt => _t.AccentAlt; + public static uint BoxBg => _t.BoxBg; + public static uint Field => _t.Field; + public static uint Selected => _t.Selected; + public static uint WindowBorder => _t.WindowBorder; + public static uint DashBorder => _t.DashBorder; + public static uint FrameBg => _t.FrameBg; + public static uint FrameHover => _t.FrameHover; + public static uint FrameActive => _t.FrameActive; + public static uint BarButtonBorder => _t.BarButtonBorder; + public static uint RowAlt => _t.RowAlt; + public static uint MuteAlt => _t.MuteAlt; + // ── Bar (AvaloniaOverlay.cs BuildRoot) ───────────────────────────── - public static readonly uint BarBackground = Argb(0xE60A0A14); + public static uint BarBackground => WithAlpha(_t.BarBg, 0xE6); public const float BarRounding = 4f; - public static readonly uint BarButton = Argb(0xFF1A2230); - public static readonly uint BarButtonBorder = Argb(0xFF3A4A5A); + public static uint BarButton => _t.FrameBg; public static readonly uint BarText = Argb(0xFFFFFFFF); public static readonly uint RcLabel = Argb(0xFF90EE90); // LightGreen public static readonly uint ReloadLabel = Argb(0xFFF0E68C); // Khaki public static readonly uint PopOutLabel = Argb(0xFF87CEFA); // LightSkyBlue // ── Standard panel frame ─────────────────────────────────────────── - public static readonly uint PanelGlass = Argb(0xF212121C); // was D2: the game showed through behind text - public static readonly uint PanelBorder = Argb(0xFF008080); // Teal + public static uint PanelGlass => WithAlpha(_t.PanelGlass, 0xF2); // was D2: the game showed through behind text + public static uint PanelBorder => _t.WindowBorder; public const float PanelRounding = 4f; - public static readonly uint PanelHeader = Argb(0xFF1A1A28); - public static readonly uint DragLabel = Argb(0xFF008080); + public static uint PanelHeader => _t.TitleBar; + public static uint DragLabel => _t.WindowBorder; public const float HeaderHeight = 24f; - public static readonly uint GripIdle = Argb(0x2026C1A6); - public static readonly uint GripHover = Argb(0x5526C1A6); - public static readonly uint GripGlyph = Argb(0xFF008080); + public static uint GripIdle => WithAlpha(_t.AccentAlt, 0x20); + public static uint GripHover => WithAlpha(_t.AccentAlt, 0x55); + public static uint GripGlyph => _t.WindowBorder; // ── RynthAi dashboard ────────────────────────────────────────────── - public static readonly uint RynthAiBackground = Argb(0xF20A0F14); - public static readonly uint RynthAiBorder = Argb(0xFF264059); + public static uint RynthAiBackground => WithAlpha(_t.Background, 0xF2); + public static uint RynthAiBorder => _t.DashBorder; public const float RynthAiRounding = 3f; // ── Radar ────────────────────────────────────────────────────────── @@ -56,6 +237,148 @@ internal static class RynthTheme public static readonly uint RadarGripIdle = Argb(0x400A121A); public static readonly uint RadarGripHover = Argb(0xA00A121A); + // ── Choosing a theme (Settings > Display) ─────────────────────────── + + /// The preset in use (ThemePalette.PresetNames index), or Custom. + public static int Preset { get { EnsureLoaded(); return _preset; } } + + /// Settings' Theme picker: the presets, then "Custom" while the player's own colours are in use. + public static readonly string[] PickerNames = BuildPickerNames(); + public static int PickerIndex => Preset == Custom ? PickerNames.Length - 1 : Preset; + + private static string[] BuildPickerNames() + { + var names = new string[ThemePalette.PresetNames.Length + 1]; + Array.Copy(ThemePalette.PresetNames, names, ThemePalette.PresetNames.Length); + names[^1] = "Custom"; + return names; + } + + /// Uses preset (the picker's last item, Custom, keeps the colours as they are). + public static void SetPreset(int index) + { + EnsureLoaded(); + if (index < 0 || index >= ThemePalette.PresetNames.Length) + { + lock (Sync) _preset = Custom; + Changed(); + return; + } + lock (Sync) + { + _preset = index; + _palette = ThemePalette.Preset(index); + } + Changed(); + } + + /// One of the eight colours (#AARRGGBB). + public static uint GetPrimary(int i) + { + EnsureLoaded(); + lock (Sync) return _palette.P[Math.Clamp(i, 0, ThemePalette.Primaries - 1)]; + } + + /// Changes one of the eight colours (#RRGGBB, opaque): the theme becomes Custom and its shades follow. + public static void SetPrimary(int i, uint argb) + { + EnsureLoaded(); + if (i < 0 || i >= ThemePalette.Primaries) return; + argb |= 0xFF000000; + lock (Sync) + { + if (_palette.P[i] == argb) return; + var p = _palette.Clone(); + p.P[i] = argb; + p.Derive(); + _palette = p; + _preset = Custom; + } + Changed(); + } + + private static void Changed() + { + lock (Sync) _t = new Tokens(_palette); + System.Threading.Interlocked.Increment(ref _version); + UiBackgroundWriter.Enqueue("theme", Save); + } + + /// + /// Re-colours the current context's base style when the theme changed since + /// (a field the context's owner keeps). Call before NewFrame. AC thread. + /// + public static void RefreshStyle(ref int applied) + { + int v = Version; + if (v == applied) return; + applied = v; + ApplyColors(ImGuiNET.ImGui.GetStyle()); + } + + /// Reads theme.txt if it hasn't been read yet. Engine init calls this so AC's thread never does. + public static void EnsureLoaded() + { + if (_loaded) return; + lock (Sync) + { + if (_loaded) return; + try + { + if (File.Exists(FilePath)) + { + int preset = 0; + var custom = ThemePalette.Default(); + foreach (string raw in File.ReadAllLines(FilePath)) + { + string line = raw.Trim(); + int eq = line.IndexOf('='); + if (eq <= 0) continue; + string key = line[..eq].Trim(), value = line[(eq + 1)..].Trim(); + if (key.Equals("preset", StringComparison.OrdinalIgnoreCase)) + { + int idx = Array.FindIndex(ThemePalette.PresetNames, n => n.Equals(value, StringComparison.OrdinalIgnoreCase)); + preset = idx >= 0 ? idx : Custom; + continue; + } + for (int i = 0; i < ThemePalette.Primaries; i++) + if (key.Equals(ThemePalette.Key(i), StringComparison.OrdinalIgnoreCase) + && uint.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out uint c)) + custom.P[i] = 0xFF000000 | c; + } + _preset = preset; + if (preset == Custom) { custom.Derive(); _palette = custom; } + else _palette = ThemePalette.Preset(preset); + _t = new Tokens(_palette); + _version++; + } + } + catch { /* unreadable: RynthCore's colours */ } + _loaded = true; + } + } + + private static string FilePath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "theme.txt"); + + private static void Save() + { + try + { + var sb = new System.Text.StringBuilder(); + lock (Sync) + { + sb.Append("preset=").Append(_preset == Custom ? "Custom" : ThemePalette.PresetNames[_preset]).Append('\n'); + if (_preset == Custom) + for (int i = 0; i < ThemePalette.Primaries; i++) + sb.Append(ThemePalette.Key(i)).Append('=').Append((_palette.P[i] & 0xFFFFFF).ToString("X6")).Append('\n'); + } + Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); + File.WriteAllText(FilePath, sb.ToString()); + } + catch { /* best-effort */ } + } + /// /// Base style for every ImGui face, scaled for /// (DPI / 96). AC thread, once, right after the context is created. @@ -78,43 +401,51 @@ internal static class RynthTheme style.ScrollbarSize = 12f; style.WindowMinSize = new Vector2(20f, 20f); - Set(style, ImGuiCol.Text, 0xFFE6E6E6); - Set(style, ImGuiCol.TextDisabled, 0xFF808080); - Set(style, ImGuiCol.WindowBg, 0xD212121C); - Set(style, ImGuiCol.ChildBg, 0x00000000); - Set(style, ImGuiCol.PopupBg, 0xF214141E); - Set(style, ImGuiCol.Border, 0xFF008080); - Set(style, ImGuiCol.FrameBg, 0xFF1A2230); - Set(style, ImGuiCol.FrameBgHovered, 0xFF243044); - Set(style, ImGuiCol.FrameBgActive, 0xFF2C3A52); - Set(style, ImGuiCol.TitleBg, 0xFF1A1A28); - Set(style, ImGuiCol.TitleBgActive, 0xFF1A1A28); - Set(style, ImGuiCol.Button, 0xFF1A2230); - Set(style, ImGuiCol.ButtonHovered, 0xFF2A3850); - Set(style, ImGuiCol.ButtonActive, 0xFF34466A); - Set(style, ImGuiCol.Header, 0xFF1A2230); - Set(style, ImGuiCol.HeaderHovered, 0xFF2A3850); - Set(style, ImGuiCol.HeaderActive, 0xFF34466A); - Set(style, ImGuiCol.CheckMark, 0xFF26C1A6); - Set(style, ImGuiCol.SliderGrab, 0xFF26A18C); - Set(style, ImGuiCol.SliderGrabActive, 0xFF26C1A6); - Set(style, ImGuiCol.Separator, 0x503A4A5A); - Set(style, ImGuiCol.ResizeGrip, 0x2026C1A6); - Set(style, ImGuiCol.ResizeGripHovered, 0x5526C1A6); - Set(style, ImGuiCol.ResizeGripActive, 0x8026C1A6); - Set(style, ImGuiCol.ScrollbarBg, 0x40000000); - Set(style, ImGuiCol.ScrollbarGrab, 0xFF2A3850); - Set(style, ImGuiCol.TableHeaderBg, 0xFF1A1A28); - Set(style, ImGuiCol.TableBorderStrong, 0xFF3A4A5A); - Set(style, ImGuiCol.TableBorderLight, 0x503A4A5A); - Set(style, ImGuiCol.TableRowBgAlt, 0x10FFFFFF); - Set(style, ImGuiCol.ModalWindowDimBg, 0x00000000); + ApplyColors(style); if (scale != 1f) style.ScaleAllSizes(scale); } - private static void Set(ImGuiStylePtr style, ImGuiCol col, uint argb) => style.Colors[(int)col] = Vec(argb); + /// The base style's colours from the theme (Apply, and RefreshStyle after a change). + private static void ApplyColors(ImGuiStylePtr style) + { + Tokens t = _t; + Set(style, ImGuiCol.Text, t.StyleText); + Set(style, ImGuiCol.TextDisabled, Argb(0xFF808080)); + Set(style, ImGuiCol.WindowBg, WithAlpha(t.PanelGlass, 0xD2)); + Set(style, ImGuiCol.ChildBg, 0); + Set(style, ImGuiCol.PopupBg, WithAlpha(t.PopupBg, 0xF2)); + Set(style, ImGuiCol.Border, t.WindowBorder); + Set(style, ImGuiCol.FrameBg, t.FrameBg); + Set(style, ImGuiCol.FrameBgHovered, t.FrameBgHover); + Set(style, ImGuiCol.FrameBgActive, t.FrameBgActive); + Set(style, ImGuiCol.TitleBg, t.TitleBar); + Set(style, ImGuiCol.TitleBgActive, t.TitleBar); + Set(style, ImGuiCol.Button, t.FrameBg); + Set(style, ImGuiCol.ButtonHovered, t.FrameHover); + Set(style, ImGuiCol.ButtonActive, t.FrameActive); + Set(style, ImGuiCol.Header, t.FrameBg); + Set(style, ImGuiCol.HeaderHovered, t.FrameHover); + Set(style, ImGuiCol.HeaderActive, t.FrameActive); + Set(style, ImGuiCol.CheckMark, t.AccentAlt); + Set(style, ImGuiCol.SliderGrab, t.SliderGrab); + Set(style, ImGuiCol.SliderGrabActive, t.AccentAlt); + Set(style, ImGuiCol.Separator, WithAlpha(t.BarButtonBorder, 0x50)); + Set(style, ImGuiCol.ResizeGrip, WithAlpha(t.AccentAlt, 0x20)); + Set(style, ImGuiCol.ResizeGripHovered, WithAlpha(t.AccentAlt, 0x55)); + Set(style, ImGuiCol.ResizeGripActive, WithAlpha(t.AccentAlt, 0x80)); + Set(style, ImGuiCol.ScrollbarBg, Argb(0x40000000)); + Set(style, ImGuiCol.ScrollbarGrab, t.FrameHover); + Set(style, ImGuiCol.TableHeaderBg, t.TitleBar); + Set(style, ImGuiCol.TableBorderStrong, t.BarButtonBorder); + Set(style, ImGuiCol.TableBorderLight, WithAlpha(t.BarButtonBorder, 0x50)); + Set(style, ImGuiCol.TableRowBgAlt, Argb(0x10FFFFFF)); + Set(style, ImGuiCol.ModalWindowDimBg, 0); + } + + private static void Set(ImGuiStylePtr style, ImGuiCol col, uint abgr) => style.Colors[(int)col] = new Vector4( + (abgr & 0xFF) / 255f, ((abgr >> 8) & 0xFF) / 255f, ((abgr >> 16) & 0xFF) / 255f, (abgr >> 24) / 255f); } /// DPI scale for the ImGui faces. diff --git a/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs b/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs index 77b3c80..828d176 100644 --- a/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs +++ b/src/RynthCore.Engine/ImGui/VideoPatchBanner.cs @@ -17,9 +17,9 @@ internal static class VideoPatchBanner private const string Line2 = "Type /rc video off, or Settings > Misc > Video patch"; private static readonly uint Back = RynthTheme.Argb(0xC0101820); - private static readonly uint Border = RynthTheme.Argb(0xFF34587A); - private static readonly uint Title = RynthTheme.Argb(0xFF26D9E6); - private static readonly uint Text = RynthTheme.Argb(0xFFB8C8D8); + private static uint Border => RynthTheme.Border; + private static uint Title => RynthTheme.Accent; + private static uint Text => RynthTheme.TextMuted; public static void Draw() { diff --git a/src/RynthCore.Engine/ImGui/WorldMapTiles.cs b/src/RynthCore.Engine/ImGui/WorldMapTiles.cs new file mode 100644 index 0000000..86b3367 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/WorldMapTiles.cs @@ -0,0 +1,318 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/WorldMapTiles.cs +// The World Map's picture: NavData\worldmap.rmap (RynthNav.Baker --map --map-tiles) is a pyramid of +// 256 px tiles, each a zlib stream of RGB pixels. The face asks for the tiles it is about to draw; +// this reads and inflates them on a worker thread and makes D3D9 textures from the results on AC's +// render thread (WorldMapFace.Draw is the only caller, plus the frame hooks), like ScriptIcons. +// +// File layout (little-endian): "RMAP", u32 version (1), u32 tile size, u32 levels, u32 pixels per +// cell at level 0, u32 cells wide, u32 cells high; per level u32 width, height, columns, rows, +// first tile; u32 tile count; per tile u64 offset + u32 length; the tiles. Level 0 is the full +// resolution, each level above half of it, the last one a single tile. Row 0 is the north edge. +// +// Bounded: at most MaxTextures tiles alive (256 KB each, twice with the managed pool's system +// copy), MaxPending reads in flight, MaxCreatesPerFrame textures made a frame. A tile drawn in the +// last frame is never evicted, and the top level (the whole map in one tile) never is, so the face +// always has something to show under the sharper tiles still loading. +// +// Threads: AC's render thread owns the texture table and every D3D call (TryGet, BeginFrame, +// Shutdown). One pool worker at a time reads and inflates; the two meet in two queues under Sync. +// The header is read on the pool too (Open), so no file read happens on AC's thread. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Threading.Tasks; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class WorldMapTiles +{ + public const int TileSize = 256; + private const int MaxTexturesRgba = 96, MaxTexturesDxt = 192, MaxCreatesPerFrame = 4, MaxPending = 24; + // A DXT1 tile is 32 KB (RGBA 256 KB), so twice as many are kept. + private static int MaxTextures => _header?.Dxt == true ? MaxTexturesDxt : MaxTexturesRgba; + + internal readonly record struct Level(int Width, int Height, int Cols, int Rows, int First); + + // ── The file's header: written once by the Open worker, then only read ───────────────── + private static volatile Header? _header; + private static volatile int _openState; // 0 not tried, 1 opening, 2 open, 3 failed + private static volatile string _status = ""; + private static string _path = ""; + + private sealed class Header + { + public Level[] Levels = Array.Empty(); + public ulong[] Offsets = Array.Empty(); + public uint[] Lengths = Array.Empty(); + public int PixelsPerCell, CellsWide, CellsHigh; + public bool Dxt; // version 2: each tile is DXT1 blocks (32 KB inflated), not RGB + } + + public static bool IsOpen => _openState == 2; + /// The file in use (or being opened); "" before the first Open. + public static string CurrentPath => _path; + /// True when the open file holds DXT1 tiles (a World Map HD / Ultra / textured Standard file), false for the flat RGB one. + public static bool IsDxt => _header?.Dxt == true; + private static volatile string? _switchTo; + + /// + /// Changes to another map file at the start of the next frame (BeginFrame): the textures of the old one are + /// released then, before anything draws with them. Any thread. + /// + public static void Switch(string path) { if (!string.Equals(path, _path, StringComparison.OrdinalIgnoreCase)) _switchTo = path; } + public static string Status => _status; + public static IReadOnlyList Levels => _header?.Levels ?? Array.Empty(); + /// Pixels per cell at level 0. + public static int PixelsPerCell => _header?.PixelsPerCell ?? 2; + public static int CellsWide => _header?.CellsWide ?? 2048; + public static int CellsHigh => _header?.CellsHigh ?? 2048; + + /// Starts reading the header (once per path; a changed path starts over). Any thread. + public static void Open(string path) + { + if (_openState == 1 || (_openState != 0 && path == _path)) return; + _path = path; + _openState = 1; + _status = "Loading the map..."; + Task.Run(() => + { + try { _header = ReadHeader(path); _openState = 2; _status = ""; } + catch (FileNotFoundException) { _openState = 3; _status = "No world map file yet (NavData\\worldmap.rmap)."; } + catch (Exception ex) { _openState = 3; _status = "The world map file didn't load: " + ex.Message; } + }); + } + + private static Header ReadHeader(string path) + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var r = new BinaryReader(fs); + if (r.ReadUInt32() != 0x5041_4D52u) throw new InvalidDataException("not a map file"); // "RMAP" + uint version = r.ReadUInt32(); + if (version != 1u && version != 2u) throw new InvalidDataException("a newer map file version"); + if (r.ReadUInt32() != TileSize) throw new InvalidDataException("unexpected tile size"); + int levels = checked((int)r.ReadUInt32()); + if (levels < 1 || levels > 14) throw new InvalidDataException("bad level count"); + var h = new Header { Dxt = version == 2u, PixelsPerCell = (int)r.ReadUInt32(), CellsWide = (int)r.ReadUInt32(), CellsHigh = (int)r.ReadUInt32() }; + h.Levels = new Level[levels]; + for (int i = 0; i < levels; i++) + h.Levels[i] = new Level((int)r.ReadUInt32(), (int)r.ReadUInt32(), (int)r.ReadUInt32(), (int)r.ReadUInt32(), (int)r.ReadUInt32()); + int count = checked((int)r.ReadUInt32()); + if (count < 1 || count > 4000000) throw new InvalidDataException("bad tile count"); + h.Offsets = new ulong[count]; + h.Lengths = new uint[count]; + for (int i = 0; i < count; i++) { h.Offsets[i] = r.ReadUInt64(); h.Lengths[i] = r.ReadUInt32(); } + foreach (Level l in h.Levels) + if (l.First < 0 || l.First + l.Cols * l.Rows > count) throw new InvalidDataException("bad level table"); + return h; + } + + // ── AC's render thread ───────────────────────────────────────────────────────────────── + private sealed class Tile + { + public IntPtr Ptr; + public int LastUsed; + public bool Pending; + public int Failures, RetryAt; // a tile that didn't load is asked for again at frame RetryAt, three times at most + } + + private static readonly Dictionary Tiles = new(MaxTexturesDxt + 8); + private static readonly List EvictScratch = new(MaxTexturesDxt + 8); + private static int _frame; + private static int _pending; + + // ── Shared with the worker, under Sync ───────────────────────────────────────────────── + private static readonly object Sync = new(); + private static readonly Queue Requests = new(); + private static readonly Queue<(int Index, int Generation, byte[]? Rgba)> Results = new(); + private static bool _draining; + private static int _generation; + + public static int LiveTextures { get; private set; } + + /// + /// The texture of tile (col, row) at if it is ready; otherwise false and, if + /// it isn't already, it is queued. AC's render thread, during a draw. + /// + public static bool TryGet(int level, int col, int row, out IntPtr texture) + { + texture = IntPtr.Zero; + Header? h = _header; + if (h == null || (uint)level >= (uint)h.Levels.Length) return false; + Level l = h.Levels[level]; + if ((uint)col >= (uint)l.Cols || (uint)row >= (uint)l.Rows) return false; + int index = l.First + row * l.Cols + col; + + if (Tiles.TryGetValue(index, out Tile? t)) + { + t.LastUsed = _frame; + if (t.Ptr != IntPtr.Zero) { texture = t.Ptr; return true; } + if (!t.Pending && t.Failures > 0 && t.Failures < 3 && _frame >= t.RetryAt && _pending < MaxPending) + { + t.Pending = true; + _pending++; + Enqueue(h, index); + } + return false; + } + if (_pending >= MaxPending) return false; + Tiles[index] = new Tile { LastUsed = _frame, Pending = true }; + _pending++; + Enqueue(h, index); + return false; + } + + /// A tile that is already loaded (a coarse one under a sharper level), without asking for it. AC's render thread. + public static bool Peek(int level, int col, int row, out IntPtr texture) + { + texture = IntPtr.Zero; + Header? h = _header; + if (h == null || (uint)level >= (uint)h.Levels.Length) return false; + Level l = h.Levels[level]; + if ((uint)col >= (uint)l.Cols || (uint)row >= (uint)l.Rows) return false; + if (!Tiles.TryGetValue(l.First + row * l.Cols + col, out Tile? t) || t.Ptr == IntPtr.Zero) return false; + t.LastUsed = _frame; + texture = t.Ptr; + return true; + } + + private static void Enqueue(Header h, int index) + { + lock (Sync) + { + Requests.Enqueue(index); + if (_draining) return; + _draining = true; + } + int gen = _generation; + Task.Run(() => Drain(h, gen)); + } + + private static void Drain(Header h, int generation) + { + try + { + using var fs = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + while (true) + { + int index; + lock (Sync) + { + if (generation != _generation || Requests.Count == 0) { _draining = false; return; } + index = Requests.Dequeue(); + } + byte[]? rgba = null; + try { rgba = Inflate(fs, h, index); } catch { } + lock (Sync) Results.Enqueue((index, generation, rgba)); + } + } + catch + { + lock (Sync) + { + // The file couldn't be opened: answer what's queued as failed so the tiles retry later. + _draining = false; + while (Requests.Count > 0) Results.Enqueue((Requests.Dequeue(), generation, null)); + } + } + } + + private static byte[] Inflate(FileStream fs, Header h, int index) + { + var comp = new byte[h.Lengths[index]]; + fs.Seek((long)h.Offsets[index], SeekOrigin.Begin); + fs.ReadExactly(comp); + if (h.Dxt) + { + var blocks = new byte[TileSize / 4 * (TileSize / 4) * 8]; // 32 KB: what the GPU holds as it is + using var zb = new ZLibStream(new MemoryStream(comp), CompressionMode.Decompress); + zb.ReadExactly(blocks); + return blocks; + } + var rgb = new byte[TileSize * TileSize * 3]; + using (var z = new ZLibStream(new MemoryStream(comp), CompressionMode.Decompress)) + z.ReadExactly(rgb); + var rgba = new byte[TileSize * TileSize * 4]; + for (int i = 0, o = 0; i < rgb.Length; i += 3, o += 4) + { + rgba[o] = rgb[i]; rgba[o + 1] = rgb[i + 1]; rgba[o + 2] = rgb[i + 2]; rgba[o + 3] = 255; + } + return rgba; + } + + /// + /// Makes textures from the tiles read since the last frame (at most MaxCreatesPerFrame) and evicts the + /// least recently drawn over the cap, before anything draws. AC's render thread, once a frame. + /// + public static void BeginFrame(IntPtr device) + { + _frame++; + if (_switchTo is string next) { _switchTo = null; Shutdown(); Open(next); return; } + if (_pending == 0 && Tiles.Count <= MaxTextures) return; + int made = 0; + while (made < MaxCreatesPerFrame) + { + (int Index, int Generation, byte[]? Rgba) r; + lock (Sync) + { + if (Results.Count == 0) break; + r = Results.Dequeue(); + } + if (r.Generation != _generation || !Tiles.TryGetValue(r.Index, out Tile? t) || !t.Pending) continue; + t.Pending = false; + _pending = Math.Max(0, _pending - 1); + IntPtr ptr = IntPtr.Zero; + if (r.Rgba != null) + { + try { ptr = _header?.Dxt == true ? DX9Backend.CreateTextureDxt1(device, TileSize, TileSize, r.Rgba) : DX9Backend.CreateTextureRgba(device, TileSize, TileSize, r.Rgba); } catch { } + made++; + } + if (ptr != IntPtr.Zero) { t.Ptr = ptr; LiveTextures++; } + else { t.Failures++; t.RetryAt = _frame + 300; } // an empty slot: retried in ~5 s, dropped when it ages out + } + if (Tiles.Count > MaxTextures) Evict(); + } + + private static void Evict() + { + Header? h = _header; + int top = h == null ? -1 : h.Levels[^1].First; // the single top tile is never evicted + EvictScratch.Clear(); + foreach (var kv in Tiles) + if (!kv.Value.Pending && kv.Key != top && kv.Value.LastUsed < _frame - 1) EvictScratch.Add(kv.Key); + EvictScratch.Sort((a, b) => Tiles[a].LastUsed.CompareTo(Tiles[b].LastUsed)); + int excess = Tiles.Count - MaxTextures; + for (int i = 0; i < EvictScratch.Count && excess > 0; i++, excess--) + { + Tile t = Tiles[EvictScratch[i]]; + if (t.Ptr != IntPtr.Zero) { try { DX9Backend.ReleaseTexture(t.Ptr); } catch { } LiveTextures--; } + Tiles.Remove(EvictScratch[i]); + } + EvictScratch.Clear(); + } + + /// + /// Engine shutdown or ImGui teardown (hot reload, unload): releases every texture and drops the + /// queues; a worker still running finishes into a generation nobody reads. AC's render thread. + /// + public static void Shutdown() + { + lock (Sync) + { + _generation++; + Requests.Clear(); + Results.Clear(); + } + foreach (Tile t in Tiles.Values) + if (t.Ptr != IntPtr.Zero) { try { DX9Backend.ReleaseTexture(t.Ptr); } catch { } t.Ptr = IntPtr.Zero; } + Tiles.Clear(); + EvictScratch.Clear(); + LiveTextures = 0; + _pending = 0; + _openState = 0; + _header = null; + } +} diff --git a/src/RynthCore.Engine/ImGui/WorldMapVectors.cs b/src/RynthCore.Engine/ImGui/WorldMapVectors.cs new file mode 100644 index 0000000..c767d36 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/WorldMapVectors.cs @@ -0,0 +1,82 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/WorldMapVectors.cs +// The World Map's vector layers: NavData\worldmap.vec (RynthNav.Baker --map-vectors), the outlines of +// Dereth's buildings and its roads, drawn over the tiles when you zoom in. About 7,000 buildings and +// 9,000 road segments, so the whole lot is held in memory (a few hundred KB) and culled per frame. +// +// File layout (little-endian): "RVEC", u32 version (1), u32 building count, u32 road segment count; +// per building u8 corner count and that many (f32 x, f32 y) in map cells; per road segment u16 x0, +// y0, x1, y1 in cells. A cell is 24 yards; y is north. +// +// Read once on a pool thread (Open); after that the arrays are immutable and any thread may read. +// ============================================================================ + +using System; +using System.IO; +using System.Numerics; +using System.Threading.Tasks; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class WorldMapVectors +{ + internal sealed class Data + { + /// Each building's outline corners (cells), with the outline's bounds for culling. + public Vector2[][] Buildings = Array.Empty(); + public Vector4[] BuildingBounds = Array.Empty(); // minX, minY, maxX, maxY + /// Road segments: x0, y0, x1, y1 in cells. + public ushort[] Roads = Array.Empty(); + public int RoadCount => Roads.Length / 4; + } + + private static volatile Data? _data; + private static volatile int _state; // 0 not tried, 1 opening, 2 open, 3 failed + private static string _path = ""; + + public static Data? Current => _state == 2 ? _data : null; + public static bool Failed => _state == 3; + + /// Starts reading the file (once per path). Any thread. + public static void Open(string path) + { + if (_state == 1 || (_state != 0 && path == _path)) return; + _path = path; + _state = 1; + Task.Run(() => + { + try { _data = Read(path); _state = 2; } + catch { _state = 3; } // no file or a bad one: the layer is simply absent + }); + } + + public static void Shutdown() { _state = 0; _data = null; } + + internal static Data Read(string path) + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var r = new BinaryReader(fs); + if (r.ReadUInt32() != 0x4345_5652u) throw new InvalidDataException("not a vector file"); // "RVEC" + if (r.ReadUInt32() != 1u) throw new InvalidDataException("a newer vector file version"); + int buildings = checked((int)r.ReadUInt32()), roads = checked((int)r.ReadUInt32()); + if (buildings < 0 || buildings > 500000 || roads < 0 || roads > 5000000) throw new InvalidDataException("bad counts"); + var d = new Data { Buildings = new Vector2[buildings][], BuildingBounds = new Vector4[buildings], Roads = new ushort[roads * 4] }; + for (int i = 0; i < buildings; i++) + { + int n = r.ReadByte(); + var pts = new Vector2[n]; + float minX = float.MaxValue, minY = float.MaxValue, maxX = float.MinValue, maxY = float.MinValue; + for (int k = 0; k < n; k++) + { + float x = r.ReadSingle(), y = r.ReadSingle(); + pts[k] = new Vector2(x, y); + if (x < minX) minX = x; if (x > maxX) maxX = x; + if (y < minY) minY = y; if (y > maxY) maxY = y; + } + d.Buildings[i] = pts; + d.BuildingBounds[i] = new Vector4(minX, minY, maxX, maxY); + } + for (int i = 0; i < roads * 4; i++) d.Roads[i] = r.ReadUInt16(); + return d; + } +} diff --git a/src/RynthCore.Engine/UI/BarLayout.cs b/src/RynthCore.Engine/UI/BarLayout.cs new file mode 100644 index 0000000..665d1cf --- /dev/null +++ b/src/RynthCore.Engine/UI/BarLayout.cs @@ -0,0 +1,109 @@ +// ============================================================================ +// RynthCore.Engine - UI/BarLayout.cs +// The toolbar's rows (ImGuiBar): how many rows the player wants (1-6, default +// 1) and the most icons a row may hold (0 = no limit, the default, else +// 2-30). Icons per row = ceil(icons / rows), capped at the limit, so the cap +// can add rows beyond the chosen count. Rows fill left to right, top to bottom. +// +// Pure (no ImGui, no files): the clamps, the per-row count, the menu's steps +// and the barlayout= row of panel_state.txt (PanelStateStore) that keeps them. +// A file without that row, or with a row this can't read, gives the defaults. +// Tests: tools/BarLayoutTests. Any thread. +// ============================================================================ + +using System; +using System.Globalization; + +namespace RynthCore.Engine.UI; + +internal static class BarLayout +{ + public const int MinRows = 1, MaxRows = 6, DefaultRows = 1; + /// Icons per row: 0 is "no limit"; a limit is MinPerRow..MaxPerRow. + public const int NoLimit = 0, MinPerRow = 2, MaxPerRow = 30; + + public static int ClampRows(int rows) => Math.Clamp(rows, MinRows, MaxRows); + + /// 0 or less = no limit; 1 becomes 2 (a one-icon row is just a column of rows); above 30 = 30. + public static int ClampMaxPerRow(int max) => max <= NoLimit ? NoLimit : Math.Clamp(max, MinPerRow, MaxPerRow); + + /// Icons in each row (the last may hold fewer): ceil(icons / rows), capped at the limit. At least 1. + public static int PerRow(int icons, int rows, int maxPerRow) + { + rows = ClampRows(rows); + maxPerRow = ClampMaxPerRow(maxPerRow); + int perRow = Math.Max(1, (Math.Max(0, icons) + rows - 1) / rows); + return maxPerRow > 0 ? Math.Min(perRow, maxPerRow) : perRow; + } + + /// The rows the icons take (at least 1: an empty bar is still its grip row). + public static int RowCount(int icons, int perRow) => + icons <= 0 ? 1 : (icons + Math.Max(1, perRow) - 1) / Math.Max(1, perRow); + + /// + /// The icons-per-row menu's - / + from . No limit sits above 30: + at 30 + /// is no limit, and - from no limit caps one below what a row shows now (), + /// so the first click changes the bar. - stops at 2, + stops at no limit. + /// + public static int StepMaxPerRow(int max, int delta, int shownPerRow) + { + max = ClampMaxPerRow(max); + if (delta == 0) return max; + if (max == NoLimit) + return delta > 0 ? NoLimit : Math.Clamp(shownPerRow - 1, MinPerRow, MaxPerRow); + int next = max + delta; + if (next > MaxPerRow) return NoLimit; + return Math.Max(MinPerRow, next); + } + + /// Settings > Display picker labels: rows "1".."6" (index = rows - 1). + public static readonly string[] RowNames = Names(MinRows, MaxRows, null); + + /// Settings > Display picker labels: "No limit", then "2".."30" (MaxPerRowToIndex). + public static readonly string[] MaxPerRowNames = Names(MinPerRow, MaxPerRow, "No limit"); + + /// The MaxPerRowNames index for a limit: 0 = no limit, 1 = 2, ... 29 = 30. + public static int MaxPerRowToIndex(int max) + { + max = ClampMaxPerRow(max); + return max == NoLimit ? 0 : max - MinPerRow + 1; + } + + public static int IndexToMaxPerRow(int index) => index <= 0 ? NoLimit : ClampMaxPerRow(index + MinPerRow - 1); + + private static string[] Names(int from, int to, string? first) + { + int lead = first != null ? 1 : 0; + var names = new string[to - from + 1 + lead]; + if (first != null) names[0] = first; + for (int i = from; i <= to; i++) names[i - from + lead] = i.ToString(CultureInfo.InvariantCulture); + return names; + } + + /// "No limit" or the number. + public static string DescribeMaxPerRow(int max) + { + max = ClampMaxPerRow(max); + return max == NoLimit ? "No limit" : max.ToString(CultureInfo.InvariantCulture); + } + + /// The value of panel_state.txt's barlayout= row: "<rows>,<maxPerRow>". + public static string Format(int rows, int maxPerRow) => + FormattableString.Invariant($"{ClampRows(rows)},{ClampMaxPerRow(maxPerRow)}"); + + /// Reads a barlayout= value, clamped. False (and the defaults) when it isn't two integers. + public static bool TryParse(string? value, out int rows, out int maxPerRow) + { + rows = DefaultRows; + maxPerRow = NoLimit; + if (string.IsNullOrWhiteSpace(value)) return false; + string[] parts = value.Split(','); + if (parts.Length != 2 + || !int.TryParse(parts[0].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int r) + || !int.TryParse(parts[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int m)) + return false; + rows = ClampRows(r); + maxPerRow = ClampMaxPerRow(m); + return true; + } +} diff --git a/src/RynthCore.Engine/UI/Data/CharactersData.cs b/src/RynthCore.Engine/UI/Data/CharactersData.cs index dc9f85b..9b2819a 100644 --- a/src/RynthCore.Engine/UI/Data/CharactersData.cs +++ b/src/RynthCore.Engine/UI/Data/CharactersData.cs @@ -50,6 +50,9 @@ internal sealed class CharacterRow public string DistanceText = ""; public string Compass = ""; public string Location = ""; + /// Where it is on the surface map, in degrees (the World Map's other-characters layer): set when it is outdoors or in an overworld building. + public bool HasMap; + public double MapNs, MapEw; public string StateText = ""; public CharStateKind StateKind; @@ -261,6 +264,13 @@ internal sealed unsafe class CharactersSource : UiSource else if (e.Portal) row.Location = "portal space"; else if (hasPose) { + if (_isOverworldBlock(cell >> 16)) + { + // A pose is relative to its landblock, indoors too: the surface coordinates of the spot. + row.HasMap = true; + row.MapEw = (((cell >> 24) & 0xFF) * 8.0 + x / 24.0 - 1019.5) / 10.0; + row.MapNs = (((cell >> 16) & 0xFF) * 8.0 + y / 24.0 - 1019.5) / 10.0; + } CharPlace p = canMeasure ? CharactersModel.Locate(myCell, mx, my, mz, cell, x, y, z, _isOverworldBlock, _dungeonName) : CharactersModel.Locate(0, 0, 0, 0, cell, x, y, z, _isOverworldBlock, _dungeonName); @@ -273,6 +283,7 @@ internal sealed unsafe class CharactersSource : UiSource else if (e.HasCoords) { row.Location = CharactersModel.CoordsText(e.Ns, e.Ew); + row.HasMap = true; row.MapNs = e.Ns; row.MapEw = e.Ew; } row.Tooltip = Tooltip(e, row, cell, hasPose); diff --git a/src/RynthCore.Engine/UI/Data/RynthNavData.cs b/src/RynthCore.Engine/UI/Data/RynthNavData.cs index 04bbc51..29dcaff 100644 --- a/src/RynthCore.Engine/UI/Data/RynthNavData.cs +++ b/src/RynthCore.Engine/UI/Data/RynthNavData.cs @@ -84,6 +84,8 @@ internal sealed class RynthNavStatus public int OpenArrow; public RynthNavArrow? Arrow; public string RouteFor = "", RouteSummary = ""; + /// The walking path RynthNav worked out for the trip: segments (one per walk), each a flat list of ns, ew pairs in degrees. Empty: none (older RynthNav, or no trip on the ground). + public float[][] PathSegments = Array.Empty(); public bool RouteActive; public int RouteIdx = -1; public RynthNavRouteStep[] Route = Array.Empty(); @@ -288,6 +290,23 @@ internal sealed class RynthNavStatus s.MarkersShown = Int(mk, "shown") != 0; s.MarkerStatus = Str(mk, "status"); } + if (r.TryGetProperty("path", out var pa) && pa.ValueKind == JsonValueKind.Array) + { + var segs = new List(); + foreach (JsonElement seg in pa.EnumerateArray()) + { + if (seg.ValueKind != JsonValueKind.Array) continue; + var arr = new float[seg.GetArrayLength() & ~1]; // whole ns, ew pairs + int i = 0; + foreach (JsonElement v in seg.EnumerateArray()) + { + if (i >= arr.Length) break; + arr[i++] = v.ValueKind == JsonValueKind.Number ? (float)v.GetDouble() : 0f; + } + if (arr.Length >= 4) segs.Add(arr); + } + s.PathSegments = segs.ToArray(); + } if (r.TryGetProperty("save", out var sv) && sv.ValueKind == JsonValueKind.Object) { s.HasSave = true; diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 7135154..d02f8ee 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -106,6 +106,10 @@ internal sealed class RynthAiSettings public int DeathRecallSpellId { get; set; } = 48; // Primary Portal Recall public string DeathRecallItem { get; set; } = string.Empty; public bool StopMacroOnNoComponents { get; set; } + // Recall When Low On Components (RynthAi's RynthAiPlugin.LowComponents.cs). An older RynthAi ignores them. + public bool LowCompsRecall { get; set; } + public int LowCompsTaperMin { get; set; } = 10; + public int LowCompsScarabMin { get; set; } = 2; public bool StopLootingWhenPackFull { get; set; } = true; public bool StopMacroWhenPackFull { get; set; } // Melee Combat @@ -158,11 +162,12 @@ internal sealed class RynthAiSettings public bool NavResumeNearest { get; set; } = true; // RynthAi dungeon patrol (/ra dunnav-patrol; RynthAi DungeonPatrolOptions). The defaults are // the patrol as it was before these settings; an older plugin ignores them. - public int DunPatrolCoverage { get; set; } // 0 whole dungeon, 1 loops only, 2 everything + public int DunPatrolCoverage { get; set; } // 0 whole dungeon, 1 loops only, 2 everything, 3 sweep public int DunPatrolSkipDeadEnds { get; set; } = 10; // dead-end areas of up to this many cells skipped (0 = none) public bool DunPatrolAvoidFloors { get; set; } = true; // lava/acid floor cells kept out of the patrol public float DunPatrolWallDistance { get; set; } = 1f; // every patrol point this far from walls where there is room public float DunPatrolLookInSize { get; set; } = 10f; // rooms this big the patrol only skirts get a walk to their middle + public float DunPatrolSightYd { get; set; } = 20f; // sweep: how far a monster notices you (lane spacing) public bool OpenDoors { get; set; } public float OpenDoorRange { get; set; } = 5f; public bool AutoUnlockDoors { get; set; } @@ -322,7 +327,9 @@ internal static unsafe class SettingsCommands internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status, /// The user hotkeys editor (ImGui/Panels/HotkeysSettingsUi.cs; stored by the engine, not RynthAi). - Hotkeys } + Hotkeys, + /// A colour (#AARRGGBB in Get/Set): a swatch that opens a picker. The theme's colours (engine-stored). + Color } /// /// Reads and edits ("Name=Level,..."). The category @@ -444,7 +451,7 @@ internal static class SettingsSchema public static readonly string[] AttackHeights = { "Low", "Medium", "High" }; public static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; public static readonly string[] NavLabelModes = { "Off", "Numbers", "Numbers and names" }; - public static readonly string[] DunPatrolCoverages = { "Whole dungeon", "Loops only", "Everything" }; + public static readonly string[] DunPatrolCoverages = { "Whole dungeon", "Loops only", "Everything", "Sweep (by sight)" }; public static readonly string[] DeathRecallModes = { "Off", "Cast a recall spell", "Use a recall item" }; // The nav editor's recall spells. Filled with "Spell N (N)" and named from the client's spell @@ -490,6 +497,11 @@ internal static class SettingsSchema "Text size for this panel in the game: 0 = normal, each step 10% bigger, yourjokin = 2.5x.") with { VisibleWhen = _ => PanelTextScale.PerPanel }; + // One of the theme's eight colours (ImGuiBackend.RynthTheme); the settings object is ignored. + private static SettingRow Colour(int index, string tip) => + new(SettingKind.Color, ImGuiBackend.ThemePalette.PrimaryNames[index], tip, + _ => ImGuiBackend.RynthTheme.GetPrimary(index), (_, v) => ImGuiBackend.RynthTheme.SetPrimary(index, (uint)v)); + private static SettingRow Section(string text, Func? when = null) => new(SettingKind.Section, text, VisibleWhen: when); @@ -582,11 +594,33 @@ internal static class SettingsSchema (_, v) => { Plugins.EngineSettings.InsertReleasesUi = v; if (!v) ImGuiBackend.Win32Backend.ReclaimUi(); }, "On: Insert switches between UI and GAME (shown on the RynthCore bar). In GAME, clicks pass through\nRynth windows to the game and Rynth text boxes can't be typed in. Press Insert again to get the UI back.\nOff (default): Insert does nothing. Applies to all your clients; others pick it up when they start."), Spacer(), + // The colour theme is stored by the engine (theme.txt, ImGuiBackend.RynthTheme), not in the RynthAi profile. + Section("Colour Theme"), + Combo("Theme", ImGuiBackend.RynthTheme.PickerNames, _ => ImGuiBackend.RynthTheme.PickerIndex, (_, v) => ImGuiBackend.RynthTheme.SetPreset(v), + "The colours of every RynthCore window: RynthCore's own, a preset, or Custom (your own colours below).\nChanging any colour below makes the theme Custom. Applies to all your clients as they start."), + Colour(0, "The main highlight: outlines, selected tabs and buttons, toggles that are on, the dashboard's accent line."), + Colour(1, "Values, section headings and the bot's busy states (amber in RynthCore's colours)."), + Colour(2, "Window and drawer backgrounds. The fields, rows and popups are shades of it."), + Colour(3, "Panel title bars and table headers."), + Colour(4, "Button and tab backgrounds."), + Colour(5, "Button and field outlines; the dashboard's frame is a shade of it."), + Colour(6, "Main text."), + Colour(7, "Labels and quieter text."), + Button("Reset Colours", "Use RynthCore's", () => ImGuiBackend.RynthTheme.SetPreset(0), + "Back to RynthCore's own colours (the RynthCore theme)."), + Spacer(), Section("Text Size (in-game panels)"), Combo("All Panels", PanelTextScale.SizeNames, _ => PanelTextScale.GetAll(), (_, v) => PanelTextScale.SetAll(v), "Text size for every in-game panel: 0 = normal, each step 10% bigger, yourjokin = 2.5x."), Combo("Toolbar", PanelTextScale.SizeNames, _ => PanelTextScale.GetChrome(), (_, v) => PanelTextScale.SetChrome(v), "Size of the RynthCore icon bar (its icons and tooltips), separate from the panels: 0 = normal, each step 10% bigger.\nAlso: right-click the bar's grip, Ctrl+wheel over the bar, or /rc ui barsize."), + // The bar's rows are stored by the engine (panel_state.txt, ImGuiBar), not in the RynthAi profile. + Combo("Toolbar Rows", BarLayout.RowNames, _ => ImGuiBackend.ImGuiBar.Rows - BarLayout.MinRows, + (_, v) => ImGuiBackend.ImGuiBar.SetRowLayout(v + BarLayout.MinRows, ImGuiBackend.ImGuiBar.MaxPerRow), + "How many rows the RynthCore icon bar spreads its icons over (Icons Per Row can add more).\nAlso: right-click the bar's grip, or /rc ui barrows."), + Combo("Toolbar Icons Per Row", BarLayout.MaxPerRowNames, _ => BarLayout.MaxPerRowToIndex(ImGuiBackend.ImGuiBar.MaxPerRow), + (_, v) => ImGuiBackend.ImGuiBar.SetRowLayout(ImGuiBackend.ImGuiBar.Rows, BarLayout.IndexToMaxPerRow(v)), + "The most icons one row of the bar holds; more icons start another row. No limit: the rows share them evenly.\nAlso: right-click the bar's grip, or /rc ui baricons."), Bool("Size Each Panel Separately", _ => PanelTextScale.PerPanel, (_, v) => PanelTextScale.PerPanel = v, "Off: every panel uses All Panels. On: set each panel's text size below.", gates: true), TextSize("RynthAi Dashboard", "RynthAi"), @@ -762,6 +796,18 @@ internal static class SettingsSchema "Stop the macro when you die. Off by default: most metas run back on their own."), Bool("Stop Macro On No Components", s => s.StopMacroOnNoComponents, (s, v) => s.StopMacroOnNoComponents = v, "Stop the macro after 3 \"missing components\" failures within a minute."), + Bool("Recall When Low On Components", s => s.LowCompsRecall, (s, v) => s.LowCompsRecall = v, + "With the macro running: when your tapers (all kinds together) drop to Low Tapers At, or any one kind of\n" + + "scarab (not Diamond) drops to Low Scarabs At, stop the macro and recall to the lifestone, and say in chat\n" + + "which ran low. Only kinds you've carried this session count, so a character with no scarabs isn't 'low'.\n" + + "Off by default.", gates: true), + Int("Low Tapers At", s => s.LowCompsTaperMin, (s, v) => s.LowCompsTaperMin = v, 0, 500, 5, + "Recall when your tapers, all kinds together, are at or under this many. 0 = don't check tapers. Default 10.", + when: s => s.LowCompsRecall), + Int("Low Scarabs At", s => s.LowCompsScarabMin, (s, v) => s.LowCompsScarabMin = v, 0, 50, 1, + "Recall when any one kind of scarab (Lead, Iron, Copper, Silver, Gold, Pyreal, Platinum, Mana; not Diamond)\n" + + "is at or under this many. 0 = don't check scarabs. Default 2.", + when: s => s.LowCompsRecall), Bool("Stop Macro When Pack Full", s => s.StopMacroWhenPackFull, (s, v) => s.StopMacroWhenPackFull = v, "Stop the macro when no pack has a free slot."), Spacer(), @@ -906,7 +952,14 @@ internal static class SettingsSchema "Loops only: just the corridors that go round in a loop or join two junctions. Every dead-end branch is left\n" + "out, however long: quicker laps, but in a hive most of the dungeon is never visited.\n" + "Everything: every dead end too, closets and all.\n" + + "Sweep: the same parts as Whole dungeon, but walked only close enough that every spot is within Sight\n" + + "Distance of the route with no wall in between. For open halls and pillar rooms, where Whole dungeon walks\n" + + "every lane: monsters a few lanes over notice you anyway. Corridors and crypts change little.\n" + "A dungeon that is one long corridor is walked end to end whatever this says."), + Float("Sight Distance (yd)", s => s.DunPatrolSightYd, (s, v) => s.DunPatrolSightYd = Math.Clamp(v, 5f, 60f), 5f, 60f, 1f, + "Sweep: how far away a monster notices you, so how far apart the patrol's lanes may be. Bigger means wider\n" + + "lanes and a shorter lap; too big and monsters out of sight around pillars get missed. Default 20.", + when: s => s.DunPatrolCoverage == 3), Int("Skip Dead Ends Up To (cells)", s => s.DunPatrolSkipDeadEnds, (s, v) => s.DunPatrolSkipDeadEnds = v, 0, 30, 1, "Dead-end areas this small are not walked into: a closet, a short corridor with a small room at its end,\n" + "a little loop off a corridor. Counted in dungeon cells (the pieces a dungeon is built from: a stretch of\n" + diff --git a/src/RynthCore.Engine/UI/PanelStateStore.cs b/src/RynthCore.Engine/UI/PanelStateStore.cs index d88ce5a..924c652 100644 --- a/src/RynthCore.Engine/UI/PanelStateStore.cs +++ b/src/RynthCore.Engine/UI/PanelStateStore.cs @@ -7,13 +7,15 @@ // // File format: // bar=,[,,,] +// barlayout=, (BarLayout; only when not 1,0) // panel.=<open|closed>,<left>,<top>,<width>,<height> // [,<docked|floating>,<screenLeft>,<screenTop>] // // The trailing three columns on each row were added when panels (and later // the bar itself) gained the ability to detach into their own top-level // layered windows. Files that pre-date the feature still parse — the floating -// mode just defaults to docked and the screen coords default to 0. +// mode just defaults to docked and the screen coords default to 0. A file +// without a barlayout= row gives the toolbar one row, no icon limit. // // Stored under %LocalAppData%\RynthCore\panel_state.txt — survives reloads // and out-of-game (the Runtime dir might be wiped during deploy). @@ -43,6 +45,7 @@ internal static class PanelStateStore private static (double Left, double Top)? _barPosition; private static bool _barFloating; private static (double Left, double Top)? _barFloatingPosition; + private static int _barRows = BarLayout.DefaultRows, _barMaxPerRow = BarLayout.NoLimit; private static bool _loaded; private static string FilePath @@ -77,6 +80,26 @@ internal static class PanelStateStore get { lock (Sync) { Load(); return _barFloatingPosition; } } } + /// <summary>The toolbar's rows and icons-per-row limit (BarLayout; 1 and no limit unless set).</summary> + public static (int Rows, int MaxPerRow) BarRows + { + get { lock (Sync) { Load(); return (_barRows, _barMaxPerRow); } } + } + + public static void SetBarRows(int rows, int maxPerRow) + { + lock (Sync) + { + Load(); + rows = BarLayout.ClampRows(rows); + maxPerRow = BarLayout.ClampMaxPerRow(maxPerRow); + if (rows == _barRows && maxPerRow == _barMaxPerRow) return; + _barRows = rows; + _barMaxPerRow = maxPerRow; + Save(); + } + } + public static bool TryGetPanel(string title, out PanelEntry entry) { lock (Sync) @@ -186,6 +209,11 @@ internal static class PanelStateStore _barFloatingPosition = (floatingVals[0], floatingVals[1]); } } + else if (string.Equals(key, "barlayout", StringComparison.OrdinalIgnoreCase)) + { + // An unreadable row leaves the defaults (TryParse sets them). + BarLayout.TryParse(value, out _barRows, out _barMaxPerRow); + } else if (key.StartsWith("panel.", StringComparison.OrdinalIgnoreCase)) { string title = key["panel.".Length..]; @@ -248,6 +276,10 @@ internal static class PanelStateStore } } + // Only when changed: a file that never had the row reads back the same. + if (_barRows != BarLayout.DefaultRows || _barMaxPerRow != BarLayout.NoLimit) + sw.WriteLine("barlayout=" + BarLayout.Format(_barRows, _barMaxPerRow)); + foreach (var kv in Panels) { PanelEntry e = kv.Value; diff --git a/src/RynthCore.Engine/UI/QuickSettings.cs b/src/RynthCore.Engine/UI/QuickSettings.cs new file mode 100644 index 0000000..a09cbde --- /dev/null +++ b/src/RynthCore.Engine/UI/QuickSettings.cs @@ -0,0 +1,167 @@ +// ============================================================================ +// RynthCore.Engine - UI/QuickSettings.cs +// The settings a player pinned to the dashboard's My settings drawer +// (ImGui/Panels/QuickSettingsDrawer.cs), in the order they pinned them. +// +// A pin is a row of the Settings schema (UI/Data/SettingsData.cs), named by +// "Tab/Section/Label" (the section it sits under; "" before the first one), +// since labels repeat across tabs ("Level 1" in Buffing and Spell Combat). +// Only rows that edit or do something can be pinned (Pinnable); a pin whose +// row no longer exists (renamed in an update) is kept in the file but not +// drawn, so it comes back if the row does. +// +// Persisted to %AppData%\RynthCore\rynthai_quick_settings.txt, one key per +// line, written in the background (UiBackgroundWriter). The pins are the +// player's, not the profile's: the same drawer on every character; the values +// are each profile's own. Any thread for reads; changes on AC's thread. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.UI; + +internal static class QuickSettings +{ + private static readonly object Sync = new(); + private static List<string> _pins = new(); + private static bool _loaded; + + private static Dictionary<string, SettingRow>? _byKey; + private static Dictionary<SettingRow, string>? _keyOf; + + private static string FilePath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthai_quick_settings.txt"); + + /// <summary>Rows that edit a value or do something; headings, notes and the hotkeys editor can't be pinned.</summary> + public static bool Pinnable(SettingRow row) => row.Kind is SettingKind.Bool or SettingKind.Int or SettingKind.Float + or SettingKind.Double or SettingKind.Combo or SettingKind.Text or SettingKind.Button or SettingKind.Color; + + /// <summary>The row's pin key ("Tab/Section/Label"), or null for a row that can't be pinned.</summary> + public static string? KeyOf(SettingRow row) + { + EnsureIndex(); + return _keyOf!.TryGetValue(row, out string? key) ? key : null; + } + + public static SettingRow? RowOf(string key) + { + EnsureIndex(); + return _byKey!.TryGetValue(key, out SettingRow? row) ? row : null; + } + + /// <summary>The pinned keys, in order (a copy).</summary> + public static string[] Pins + { + get { EnsureLoaded(); lock (Sync) return _pins.ToArray(); } + } + + public static bool IsPinned(string key) + { + EnsureLoaded(); + lock (Sync) return _pins.Contains(key); + } + + /// <summary>Pins <paramref name="key"/> at the end, or unpins it.</summary> + public static void SetPinned(string key, bool pinned) + { + EnsureLoaded(); + lock (Sync) + { + if (pinned == _pins.Contains(key)) return; + if (pinned) _pins.Add(key); + else _pins.Remove(key); + } + UiBackgroundWriter.Enqueue("quick settings", Save); + } + + /// <summary>Moves a pin up (-1) or down (+1) among the pins.</summary> + public static void Move(string key, int by) + { + EnsureLoaded(); + lock (Sync) + { + int i = _pins.IndexOf(key); + int j = i + by; + if (i < 0 || j < 0 || j >= _pins.Count) return; + (_pins[i], _pins[j]) = (_pins[j], _pins[i]); + } + UiBackgroundWriter.Enqueue("quick settings", Save); + } + + /// <summary>The rows under section <paramref name="section"/> of tab <paramref name="tab"/> (up to the next section).</summary> + public static SettingRow[] SectionRows(string tab, string section) + { + var list = new List<SettingRow>(); + foreach (SettingsTab t in SettingsSchema.Tabs) + { + if (!t.Name.Equals(tab, StringComparison.OrdinalIgnoreCase)) continue; + bool inside = false; + foreach (SettingRow row in t.Rows) + { + if (row.Kind == SettingKind.Section) + { + if (inside) break; + inside = row.Label.Equals(section, StringComparison.OrdinalIgnoreCase); + continue; + } + if (inside && row.Kind != SettingKind.Spacer) list.Add(row); + } + } + return list.ToArray(); + } + + private static void EnsureIndex() + { + if (_byKey != null) return; + var byKey = new Dictionary<string, SettingRow>(StringComparer.OrdinalIgnoreCase); + var keyOf = new Dictionary<SettingRow, string>(ReferenceEqualityComparer.Instance); + foreach (SettingsTab tab in SettingsSchema.Tabs) + { + string section = ""; + foreach (SettingRow row in tab.Rows) + { + if (row.Kind == SettingKind.Section) { section = row.Label.Trim(); continue; } + if (!Pinnable(row)) continue; + string key = tab.Name + "/" + section + "/" + row.Label.Trim(); + if (byKey.TryAdd(key, row)) keyOf[row] = key; + } + } + _keyOf = keyOf; + _byKey = byKey; + } + + private static void EnsureLoaded() + { + if (_loaded) return; + lock (Sync) + { + if (_loaded) return; + try + { + if (File.Exists(FilePath)) + foreach (string line in File.ReadAllLines(FilePath)) + { + string key = line.Trim(); + if (key.Length > 0 && !_pins.Contains(key)) _pins.Add(key); + } + } + catch { /* unreadable: start with no pins */ } + _loaded = true; + } + } + + private static void Save() + { + try + { + string[] lines; + lock (Sync) lines = _pins.ToArray(); + Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); + File.WriteAllLines(FilePath, lines); + } + catch { /* best-effort */ } + } +} diff --git a/src/RynthCore.Engine/UI/RynthAiDashboardState.cs b/src/RynthCore.Engine/UI/RynthAiDashboardState.cs index a39f9a2..eec0f15 100644 --- a/src/RynthCore.Engine/UI/RynthAiDashboardState.cs +++ b/src/RynthCore.Engine/UI/RynthAiDashboardState.cs @@ -6,8 +6,10 @@ // minimized|expanded, line 2 unused, line 3 target|notarget, line 4 // vitals|novitals; line 5 filesopen|nofiles, the Loaded files drawer; line 9 // ranges|noranges, the Ranges drawer; line 10 patrol|nopatrol, the Patrol -// drawer; line 11 remote|noremote, the Mini Remote drawer: the left-edge -// drawers, ImGui/Panels/DashboardDrawers.cs). Line 2 +// drawer; line 11 remote|noremote, the Mini Remote drawer; line 12 the +// drawers moved to the side they don't start on, "moved:key,key"; line 13 +// quick|noquick, the My settings drawer: the drawers on the dashboard's +// edges, 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 @@ -39,6 +41,9 @@ internal static class RynthAiDashboardState 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 private static volatile bool _remoteOpen; // the Mini Remote drawer beside the dashboard is open + private static volatile bool _quickOpen; // the My settings drawer beside the dashboard is open + // Drawer keys on the side they don't start on (a tab's right-click moves it). Copy-on-write. + private static volatile string[] _moved = Array.Empty<string>(); // Lines 7 and 8, unused since 2026-10-05: written back as read. private static string _line7 = "-", _line8 = "-"; private static bool _loaded; @@ -155,6 +160,38 @@ internal static class RynthAiDashboardState UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); } + /// <summary>The My settings drawer (pinned settings) is open beside the dashboard. Any thread.</summary> + public static bool QuickOpen + { + get { EnsureLoaded(); return _quickOpen; } + } + + public static void SetQuickOpen(bool open) + { + EnsureLoaded(); + _quickOpen = open; + UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); + } + + /// <summary>The drawer <paramref name="key"/> sits on the side it doesn't start on. Any thread.</summary> + public static bool DrawerMoved(string key) + { + EnsureLoaded(); + return Array.IndexOf(_moved, key) >= 0; + } + + public static void SetDrawerMoved(string key, bool moved) + { + EnsureLoaded(); + string[] cur = _moved; + if ((Array.IndexOf(cur, key) >= 0) == moved) return; + var list = new System.Collections.Generic.List<string>(cur); + if (moved) list.Add(key); + else list.Remove(key); + _moved = list.ToArray(); + UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); + } + /// <summary>Reads the file if it hasn't been read yet. Engine init calls this so AC's thread never does.</summary> public static void EnsureLoaded() { @@ -179,6 +216,9 @@ internal static class RynthAiDashboardState _rangesOpen = lines.Length >= 9 && lines[8].Trim().Equals("ranges", StringComparison.OrdinalIgnoreCase); _patrolOpen = lines.Length >= 10 && lines[9].Trim().Equals("patrol", StringComparison.OrdinalIgnoreCase); _remoteOpen = lines.Length >= 11 && lines[10].Trim().Equals("remote", StringComparison.OrdinalIgnoreCase); + if (lines.Length >= 12 && lines[11].Trim().StartsWith("moved:", StringComparison.OrdinalIgnoreCase)) + _moved = lines[11].Trim().Substring(6).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + _quickOpen = lines.Length >= 13 && lines[12].Trim().Equals("quick", StringComparison.OrdinalIgnoreCase); } } catch { /* corrupt cache: start expanded */ } @@ -197,7 +237,8 @@ internal static class RynthAiDashboardState + (_filesOpen ? "filesopen" : "nofiles") + "\n" + (_barCollapsed ? "barcollapsed" : "bar") + "\n" + _line7 + "\n" + _line8 + "\n" + (_rangesOpen ? "ranges" : "noranges") + "\n" + (_patrolOpen ? "patrol" : "nopatrol") + "\n" - + (_remoteOpen ? "remote" : "noremote") + "\n"); + + (_remoteOpen ? "remote" : "noremote") + "\n" + + "moved:" + string.Join(",", _moved) + "\n" + (_quickOpen ? "quick" : "noquick") + "\n"); } catch { /* best-effort */ } } diff --git a/tools/BarLayoutTests/BarLayoutTests.csproj b/tools/BarLayoutTests/BarLayoutTests.csproj new file mode 100644 index 0000000..c8aae10 --- /dev/null +++ b/tools/BarLayoutTests/BarLayoutTests.csproj @@ -0,0 +1,23 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the toolbar's rows (src\RynthCore.Engine\UI\BarLayout.cs, compiled in): + icons per row = ceil(icons / rows) capped at the limit, the clamps (rows 1-6, limit 0 or + 2-30), the grip menu's icons-per-row steps (no limit above 30), the Settings picker index + maps, and the barlayout= row of panel_state.txt (a missing or bad row gives 1 row, no limit). + No files, no ImGui. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>BarLayoutTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\UI\BarLayout.cs" Link="Engine\BarLayout.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/BarLayoutTests/Program.cs b/tools/BarLayoutTests/Program.cs new file mode 100644 index 0000000..1cafcd7 --- /dev/null +++ b/tools/BarLayoutTests/Program.cs @@ -0,0 +1,114 @@ +using RynthCore.Engine.UI; + +namespace BarLayoutTests; + +// Offline tests for the toolbar's rows. See the csproj. +internal static class Program +{ + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + private static void Eq<T>(T actual, T expected, string msg) => + Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'"); + + private static int Main() + { + PerRow(); + RowCount(); + Clamps(); + StepMaxPerRow(); + PickerIndexes(); + ParseAndFormat(); + Console.WriteLine(); + Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks failed)"); + return _fails == 0 ? 0 : 1; + } + + private static void PerRow() + { + Console.WriteLine("PerRow"); + Eq(BarLayout.PerRow(12, 1, 0), 12, "one row, no limit: every icon on it (today's bar)"); + Eq(BarLayout.PerRow(12, 2, 0), 6, "12 icons, 2 rows"); + Eq(BarLayout.PerRow(13, 2, 0), 7, "13 icons, 2 rows: ceil"); + Eq(BarLayout.PerRow(13, 3, 0), 5, "13 icons, 3 rows: ceil(13/3)"); + Eq(BarLayout.PerRow(12, 1, 5), 5, "one row capped at 5: the cap adds rows"); + Eq(BarLayout.RowCount(12, BarLayout.PerRow(12, 1, 5)), 3, "12 icons capped at 5 take 3 rows"); + Eq(BarLayout.PerRow(12, 3, 10), 4, "a cap above ceil(icons/rows) changes nothing"); + Eq(BarLayout.PerRow(3, 6, 0), 1, "more rows than icons: one a row"); + Eq(BarLayout.PerRow(0, 2, 0), 1, "no icons: still at least 1 (no divide by zero)"); + Eq(BarLayout.PerRow(12, 0, 0), 12, "rows 0 reads as 1"); + Eq(BarLayout.PerRow(12, 99, 0), 2, "rows 99 reads as 6"); + Eq(BarLayout.PerRow(12, 1, 1), 2, "a limit of 1 reads as 2"); + } + + private static void RowCount() + { + Console.WriteLine("RowCount"); + Eq(BarLayout.RowCount(0, 1), 1, "an empty bar is one row"); + Eq(BarLayout.RowCount(12, 6), 2, "12 by 6"); + Eq(BarLayout.RowCount(13, 6), 3, "13 by 6: a short last row"); + Eq(BarLayout.RowCount(5, 0), 5, "perRow 0 reads as 1"); + } + + private static void Clamps() + { + Console.WriteLine("Clamps"); + Eq(BarLayout.ClampRows(0), 1, "rows below 1"); + Eq(BarLayout.ClampRows(7), 6, "rows above 6"); + Eq(BarLayout.ClampRows(3), 3, "rows in range"); + Eq(BarLayout.ClampMaxPerRow(0), 0, "0 is no limit"); + Eq(BarLayout.ClampMaxPerRow(-5), 0, "negative is no limit"); + Eq(BarLayout.ClampMaxPerRow(1), 2, "1 becomes 2"); + Eq(BarLayout.ClampMaxPerRow(31), 30, "above 30 becomes 30"); + Eq(BarLayout.ClampMaxPerRow(17), 17, "in range"); + } + + private static void StepMaxPerRow() + { + Console.WriteLine("StepMaxPerRow"); + Eq(BarLayout.StepMaxPerRow(0, 1, 12), 0, "+ at no limit stays no limit"); + Eq(BarLayout.StepMaxPerRow(0, -1, 12), 11, "- from no limit caps one below the shown row"); + Eq(BarLayout.StepMaxPerRow(0, -1, 2), 2, "- from no limit never below 2"); + Eq(BarLayout.StepMaxPerRow(0, -1, 50), 30, "- from no limit never above 30"); + Eq(BarLayout.StepMaxPerRow(30, 1, 12), 0, "+ at 30 is no limit"); + Eq(BarLayout.StepMaxPerRow(2, -1, 12), 2, "- stops at 2"); + Eq(BarLayout.StepMaxPerRow(5, 1, 12), 6, "+ one"); + Eq(BarLayout.StepMaxPerRow(5, -1, 12), 4, "- one"); + Eq(BarLayout.StepMaxPerRow(5, 0, 12), 5, "no step"); + } + + private static void PickerIndexes() + { + Console.WriteLine("PickerIndexes"); + Eq(BarLayout.RowNames.Length, 6, "rows picker: 1..6"); + Eq(BarLayout.RowNames[0], "1", "rows picker starts at 1"); + Eq(BarLayout.MaxPerRowNames.Length, 30, "limit picker: no limit + 2..30"); + Eq(BarLayout.MaxPerRowNames[0], "No limit", "limit picker starts with no limit"); + Eq(BarLayout.MaxPerRowNames[^1], "30", "limit picker ends at 30"); + for (int max = 0; max <= 30; max++) + { + if (max == 1) continue; // not a value (clamps to 2) + int index = BarLayout.MaxPerRowToIndex(max); + Eq(BarLayout.IndexToMaxPerRow(index), max, $"limit {max} round-trips through the picker"); + Eq(BarLayout.MaxPerRowNames[index], BarLayout.DescribeMaxPerRow(max), $"limit {max}'s label"); + } + } + + private static void ParseAndFormat() + { + Console.WriteLine("ParseAndFormat"); + Check(BarLayout.TryParse("2,8", out int r, out int m) && r == 2 && m == 8, "reads 2,8"); + Eq(BarLayout.Format(2, 8), "2,8", "writes 2,8"); + Check(BarLayout.TryParse(BarLayout.Format(6, 0), out r, out m) && r == 6 && m == 0, "round trip 6, no limit"); + Check(BarLayout.TryParse(" 3 , 1 ", out r, out m) && r == 3 && m == 2, "spaces; a limit of 1 clamps to 2"); + Check(BarLayout.TryParse("9,99", out r, out m) && r == 6 && m == 30, "out of range clamps"); + Check(!BarLayout.TryParse(null, out r, out m) && r == 1 && m == 0, "no row (an old file): defaults"); + Check(!BarLayout.TryParse("", out r, out m) && r == 1 && m == 0, "empty: defaults"); + Check(!BarLayout.TryParse("2", out r, out m) && r == 1 && m == 0, "one value: defaults"); + Check(!BarLayout.TryParse("two,8", out r, out m) && r == 1 && m == 0, "not a number: defaults"); + Check(!BarLayout.TryParse("2,8,1", out r, out m) && r == 1 && m == 0, "three values: defaults"); + } +} diff --git a/tools/NavDataUpdateTests/MapPackTests.cs b/tools/NavDataUpdateTests/MapPackTests.cs new file mode 100644 index 0000000..9dd29e6 --- /dev/null +++ b/tools/NavDataUpdateTests/MapPackTests.cs @@ -0,0 +1,139 @@ +using System.IO.Compression; +using RynthCore.App.Avalonia; + +// World map packs (RynthUpdater.MapPacks.cs): the optional HD / Ultra downloads. Part of the same program as +// the NavData tests (same signed feed, same local HTTP server). +internal static partial class Program +{ + private static byte[] Rand(int n, int seed) { var b = new byte[n]; new Random(seed).NextBytes(b); return b; } + + /// <summary>A feed entry for a pack whose bytes are served under the feed's folder.</summary> + private static Dictionary<string, object> PackEntry(string tag, string key, string name, string file, byte[] data, string? sha = null, long? size = null) + { + lock (Served) Served[$"{tag}/packs/{file}"] = data; + return new Dictionary<string, object> + { + ["key"] = key, ["name"] = name, ["file"] = file, ["url"] = _base + $"{tag}/packs/{file}", ["size"] = size ?? data.Length, + ["sha256"] = sha ?? Sha(data), ["release"] = 2026100201, ["description"] = name + " test map", + }; + } + + private static async Task NoMapPacksInFeed() + { + var (upd, nav, plugin, _) = SetupInFeedFolder("nopack", null, withNavData: false); + var c = await upd.CheckAsync(new[] { plugin }); + Check(c.Manifest.MapPacks.Count == 0 && c.MapPacks.Count == 0, "a feed without mappacks (every feed so far) still parses, nothing to offer"); + } + + private static async Task MapPacksListedInstalledAndRemoved() + { + byte[] hd = Rand(300_000, 1), ul = Rand(500_000, 2); + var packs = new object[] { PackEntry("packs", "hd", "HD", "worldmap-hd.rmap", hd), PackEntry("packs", "ultra", "Ultra", "worldmap-ultra.rmap", ul) }; + var (upd, nav, plugin, _) = SetupInFeedFolder("packs", null, withNavData: false, mapPacks: packs); + var c = await upd.CheckAsync(new[] { plugin }); + Check(c.MapPacks.Count == 2 && c.MapPacks.All(p => p.State == RynthUpdater.MapPackState.NotInstalled), "two packs offered, neither installed"); + string dir = upd.MapPacksDir; + Check(dir == Path.Combine(Path.GetDirectoryName(nav)!, "MapPacks"), "packs live beside the NavData folder, not inside it"); + + string line = await upd.InstallMapPackAsync(c.MapPacks[0].Entry); + string file = Path.Combine(dir, "worldmap-hd.rmap"); + Check(File.Exists(file) && File.ReadAllBytes(file).AsSpan().SequenceEqual(hd), "the HD pack is installed, byte for byte"); + Check(!File.Exists(file + ".part"), "no partial file is left"); + Check(line.Contains("HD") && line.Contains("installed"), "the activity line says what happened"); + var again = await upd.CheckAsync(new[] { plugin }); + Check(again.MapPacks[0].State == RynthUpdater.MapPackState.UpToDate && again.MapPacks[1].State == RynthUpdater.MapPackState.NotInstalled, "HD is current, Ultra still not installed"); + + Check(upd.RemoveMapPack(again.MapPacks[0].Entry), "removing reports it was there"); + Check(!File.Exists(file) && !File.Exists(file + ".sha256"), "the pack and its marker are gone"); + Check(!upd.RemoveMapPack(again.MapPacks[0].Entry), "removing again reports it was not there"); + + // A file put there by hand, the size the feed says and no marker, counts as installed. + Directory.CreateDirectory(dir); + File.WriteAllBytes(Path.Combine(dir, "worldmap-ultra.rmap"), ul); + var hand = await upd.CheckAsync(new[] { plugin }); + Check(hand.MapPacks[1].State == RynthUpdater.MapPackState.UpToDate, "a hand-copied pack of the right size counts as installed"); + File.WriteAllBytes(Path.Combine(dir, "worldmap-ultra.rmap"), new byte[10]); + var wrong = await upd.CheckAsync(new[] { plugin }); + Check(wrong.MapPacks[1].State == RynthUpdater.MapPackState.NeedsUpdate, "one of the wrong size is an update"); + } + + private static async Task MapPackNewBuildIsAnUpdate() + { + byte[] v1 = Rand(200_000, 3), v2 = Rand(210_000, 4); + var (upd, nav, plugin, _) = SetupInFeedFolder("packupd", null, withNavData: false, mapPacks: new object[] { PackEntry("packupd", "hd", "HD", "worldmap-hd.rmap", v1) }); + var c = await upd.CheckAsync(new[] { plugin }); + await upd.InstallMapPackAsync(c.MapPacks[0].Entry); + // The feed now carries a new build of the same pack. + var (upd2, _, plugin2, _) = SetupInFeedFolder("packupd", null, withNavData: false, mapPacks: new object[] { PackEntry("packupd", "hd", "HD", "worldmap-hd.rmap", v2) }); + var c2 = await upd2.CheckAsync(new[] { plugin2 }); + Check(c2.MapPacks[0].State == RynthUpdater.MapPackState.NeedsUpdate, "a new build of an installed pack is an update"); + await upd2.InstallMapPackAsync(c2.MapPacks[0].Entry); + Check(File.ReadAllBytes(Path.Combine(upd2.MapPacksDir, "worldmap-hd.rmap")).AsSpan().SequenceEqual(v2), "the update replaced the file"); + var c3 = await upd2.CheckAsync(new[] { plugin2 }); + Check(c3.MapPacks[0].State == RynthUpdater.MapPackState.UpToDate, "and it is current afterwards"); + } + + private static async Task MapPackBadDownloadChangesNothing() + { + byte[] good = Rand(150_000, 5), served = Rand(150_000, 6); + // The feed says the SHA-256 of one file; another is served. + var entry = PackEntry("packbad", "hd", "HD", "worldmap-hd.rmap", served, sha: Sha(good)); + var (upd, nav, plugin, _) = SetupInFeedFolder("packbad", null, withNavData: false, mapPacks: new object[] { entry }); + var c = await upd.CheckAsync(new[] { plugin }); + string file = Path.Combine(upd.MapPacksDir, "worldmap-hd.rmap"); + bool threw = false; + try { await upd.InstallMapPackAsync(c.MapPacks[0].Entry); } catch (Exception) { threw = true; } + Check(threw, "a download that does not match the feed's SHA-256 is refused"); + Check(!File.Exists(file) && !File.Exists(file + ".part") && !File.Exists(file + ".sha256"), "nothing was installed and no partial file is left"); + + // And an installed pack stays as it was when its update is refused. + Directory.CreateDirectory(upd.MapPacksDir); + File.WriteAllBytes(file, new byte[] { 1, 2, 3 }); + threw = false; + try { await upd.InstallMapPackAsync(c.MapPacks[0].Entry); } catch (Exception) { threw = true; } + Check(threw && File.ReadAllBytes(file).SequenceEqual(new byte[] { 1, 2, 3 }), "a refused update leaves the installed pack as it was"); + } + + private static async Task MapPackBadEntriesAreSkipped() + { + byte[] data = Rand(1000, 7); + var good = PackEntry("packskip", "hd", "HD", "worldmap-hd.rmap", data); + var traversal = PackEntry("packskip", "evil", "Evil", "../worldmap-evil.rmap", data); + var wrongKind = PackEntry("packskip", "dll", "Dll", "worldmap-x.dll", data); + var badKey = PackEntry("packskip", "BAD KEY!", "Bad", "worldmap-bad.rmap", data); + var shortSha = PackEntry("packskip", "short", "Short", "worldmap-short.rmap", data, sha: "abc"); + var duplicate = PackEntry("packskip", "hd", "HD again", "worldmap-hd.rmap", data); + var huge = PackEntry("packskip", "huge", "Huge", "worldmap-huge.rmap", data, size: 9L << 40); + var (upd, nav, plugin, _) = SetupInFeedFolder("packskip", null, withNavData: false, mapPacks: new object[] { traversal, wrongKind, badKey, shortSha, good, duplicate, huge }); + var c = await upd.CheckAsync(new[] { plugin }); + Check(c.MapPacks.Count == 1 && c.MapPacks[0].Entry.Key == "hd", "entries with a path in the file name, a wrong extension, a bad key, a short hash, a repeated key or an absurd size are skipped; the good one stays"); + } + + private static async Task MapPackCancelLeavesNothing() + { + byte[] data = Rand(400_000, 8); + var (upd, nav, plugin, _) = SetupInFeedFolder("packcancel", null, withNavData: false, mapPacks: new object[] { PackEntry("packcancel", "hd", "HD", "worldmap-hd.rmap", data) }); + var c = await upd.CheckAsync(new[] { plugin }); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + bool cancelled = false; + try { await upd.InstallMapPackAsync(c.MapPacks[0].Entry, null, cts.Token); } catch (OperationCanceledException) { cancelled = true; } + string file = Path.Combine(upd.MapPacksDir, "worldmap-hd.rmap"); + Check(cancelled, "cancelling stops the install"); + Check(!File.Exists(file) && !File.Exists(file + ".part"), "and leaves neither the pack nor a partial file"); + } + + private static async Task NavDataUpdateLeavesMapPacksAlone() + { + byte[] hd = Rand(120_000, 9); + var (upd, nav, plugin, _) = SetupInFeedFolder("packnav", Zip(TileSet), mapPacks: new object[] { PackEntry("packnav", "hd", "HD", "worldmap-hd.rmap", hd) }); + OldNavData(nav); + var c = await upd.CheckAsync(new[] { plugin }); + await upd.InstallMapPackAsync(c.MapPacks[0].Entry); + Check(c.NavDataUpdateAvailable, "the tiles need an update"); + await upd.UpdateNavDataAsync(c); + string file = Path.Combine(upd.MapPacksDir, "worldmap-hd.rmap"); + Check(File.Exists(file) && File.ReadAllBytes(file).AsSpan().SequenceEqual(hd) && File.Exists(file + ".sha256"), "updating the tiles swaps the NavData folder but the map pack beside it is untouched"); + Check(!Directory.Exists(Path.Combine(nav, "MapPacks")), "and no MapPacks folder appears inside NavData"); + } +} diff --git a/tools/NavDataUpdateTests/NavDataUpdateTests.csproj b/tools/NavDataUpdateTests/NavDataUpdateTests.csproj index 13d466c..b40e0ea 100644 --- a/tools/NavDataUpdateTests/NavDataUpdateTests.csproj +++ b/tools/NavDataUpdateTests/NavDataUpdateTests.csproj @@ -18,6 +18,7 @@ <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.cs" Link="Linked\RynthUpdater.cs" /> <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.NavData.cs" Link="Linked\RynthUpdater.NavData.cs" /> <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Available.cs" Link="Linked\RynthUpdater.Available.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.MapPacks.cs" Link="Linked\RynthUpdater.MapPacks.cs" /> <Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" /> <Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateTrust.cs" Link="Linked\UpdateTrust.cs" /> <Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Linked\PluginContractVersion.cs" /> diff --git a/tools/NavDataUpdateTests/Program.cs b/tools/NavDataUpdateTests/Program.cs index b4d64dd..1f9a219 100644 --- a/tools/NavDataUpdateTests/Program.cs +++ b/tools/NavDataUpdateTests/Program.cs @@ -8,7 +8,7 @@ using RynthCore.App.Avalonia; // Tests for the launcher's RynthNav tile update. A throwaway signing key signs a feed served by // a local HttpListener; the updater installs the archive into a temp NavData folder. -internal static class Program +internal static partial class Program { private static int _fails, _asserts; private static void Check(bool cond, string msg) @@ -46,6 +46,13 @@ internal static class Program await Run(nameof(CancelledDownloadLeavesNothing), CancelledDownloadLeavesNothing); await Run(nameof(CancelledUnpackLeavesTilesAsTheyWere), CancelledUnpackLeavesTilesAsTheyWere); await Run(nameof(TamperedArchiveRefusedWithProgress), TamperedArchiveRefusedWithProgress); + await Run(nameof(NoMapPacksInFeed), NoMapPacksInFeed); + await Run(nameof(MapPacksListedInstalledAndRemoved), MapPacksListedInstalledAndRemoved); + await Run(nameof(MapPackNewBuildIsAnUpdate), MapPackNewBuildIsAnUpdate); + await Run(nameof(MapPackBadDownloadChangesNothing), MapPackBadDownloadChangesNothing); + await Run(nameof(MapPackBadEntriesAreSkipped), MapPackBadEntriesAreSkipped); + await Run(nameof(MapPackCancelLeavesNothing), MapPackCancelLeavesNothing); + await Run(nameof(NavDataUpdateLeavesMapPacksAlone), NavDataUpdateLeavesMapPacksAlone); } finally { @@ -133,11 +140,13 @@ internal static class Program ["locations.json"] = "{\"locations\":[]}", ["navgraph.bin"] = "route graph", ["townnet.json"] = "{\"version\":1}", + ["worldmap.rmap"] = "world map", + ["worldmap.vec"] = "world map vectors", }; // The feed's URLs must sit in the feed's folder: serve each test's archive under it. private static (RynthUpdater upd, string nav, string plugin, string state) SetupInFeedFolder(string tag, byte[]? zip, string id = "0123456789abcdef0123456789abcdef", - int? files = null, bool signNavData = true, bool withNavData = true, string? overrideSha = null) + int? files = null, bool signNavData = true, bool withNavData = true, string? overrideSha = null, object[]? mapPacks = null) { string zipName = $"{tag}/releases/1/RynthNav-NavData.zip"; string dir = Path.Combine(_root, tag); @@ -159,6 +168,7 @@ internal static class Program ["id"] = id, ["release"] = 2026100201, ["url"] = _base + zipName, ["size"] = zip.Length, ["sha256"] = overrideSha ?? Sha(zip), ["files"] = files ?? TileSet.Count, ["bytes"] = 1000, }; + if (mapPacks != null) manifest["mappacks"] = mapPacks; if (withNavData && nd != null && signNavData) manifest["navdata"] = nd; byte[] signedPayload = JsonSerializer.SerializeToUtf8Bytes(manifest); if (withNavData && nd != null && !signNavData) manifest["navdata"] = nd; // served, but not what was signed @@ -210,6 +220,8 @@ internal static class Program Check(line.Contains($"{TileSet.Count} files"), "reports what it installed: " + line); Check(File.ReadAllText(Path.Combine(nav, "navgraph.bin")) == "route graph", "the route graph ships with the tiles"); Check(File.ReadAllText(Path.Combine(nav, "townnet.json")) == "{\"version\":1}", "the Town Network ships with the tiles"); + Check(File.ReadAllText(Path.Combine(nav, "worldmap.rmap")) == "world map", "the World Map's tiles ship with the tiles"); + Check(File.ReadAllText(Path.Combine(nav, "worldmap.vec")) == "world map vectors", "the World Map's buildings and roads ship with the tiles"); Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 v2", "the tile is the new one"); Check(File.Exists(Path.Combine(nav, "nav_AAB4.tile")), "new tiles are there"); Check(!File.Exists(Path.Combine(nav, "nav_0101.tile")), "a stale tile from the old set is gone (old and new don't link)"); diff --git a/tools/WorldMapTilesTests/DxtTileTests.cs b/tools/WorldMapTilesTests/DxtTileTests.cs new file mode 100644 index 0000000..a12b020 --- /dev/null +++ b/tools/WorldMapTilesTests/DxtTileTests.cs @@ -0,0 +1,163 @@ +using System.IO.Compression; +using RynthCore.Engine.ImGuiBackend; + +namespace WorldMapTilesTests +{ + /// <summary>worldmap.rmap version 2 (DXT1 tiles, as RynthNav.Baker --map-world writes it) and switching between files.</summary> + internal static class DxtTileTests + { + private static bool WaitOpen(string path) + { + WorldMapTiles.Open(path); + for (int i = 0; i < 300 && !WorldMapTiles.IsOpen; i++) Thread.Sleep(10); + return WorldMapTiles.IsOpen; + } + + private static bool Load(int level, int col, int row, out IntPtr tex) + { + tex = IntPtr.Zero; + for (int i = 0; i < 400; i++) + { + WorldMapTiles.BeginFrame(new IntPtr(1)); + if (WorldMapTiles.TryGet(level, col, row, out tex)) return true; + Thread.Sleep(2); + } + return false; + } + + // A tile's blocks: its number in the first two bytes, the rest filler. + private static byte[] Blocks(int id) + { + var b = new byte[256 * 256 / 2]; + b[0] = (byte)id; b[1] = (byte)(id >> 8); + for (int i = 8; i < b.Length; i += 8) b[i] = (byte)(id * 7); + return b; + } + + private static void WriteV2(string path, (int Cols, int Rows)[] levels) + { + var blobs = new List<byte[]>(); + var first = new int[levels.Length]; + for (int l = 0; l < levels.Length; l++) + { + first[l] = blobs.Count; + for (int i = 0; i < levels[l].Cols * levels[l].Rows; i++) + { + using var ms = new MemoryStream(); + using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(Blocks(first[l] + i)); + blobs.Add(ms.ToArray()); + } + } + long header = 4 + 6 * 4 + levels.Length * 20 + 4 + blobs.Count * 12L; + using var fs = new FileStream(path, FileMode.Create); + using var w = new BinaryWriter(fs); + w.Write(new byte[] { (byte)'R', (byte)'M', (byte)'A', (byte)'P' }); + w.Write(2u); w.Write(256u); w.Write((uint)levels.Length); w.Write(8u); // 8 px per cell: HD + w.Write((uint)(levels[0].Cols * 256 / 8)); w.Write((uint)(levels[0].Rows * 256 / 8)); + for (int l = 0; l < levels.Length; l++) + { w.Write((uint)(levels[l].Cols * 256)); w.Write((uint)(levels[l].Rows * 256)); w.Write((uint)levels[l].Cols); w.Write((uint)levels[l].Rows); w.Write((uint)first[l]); } + w.Write((uint)blobs.Count); + long off = header; + for (int i = 0; i < blobs.Count; i++) + { + if (i == 5) { w.Write(0UL); w.Write(0u); continue; } // tile 5: not baked (length 0) + w.Write((ulong)off); w.Write((uint)blobs[i].Length); off += blobs[i].Length; + } + for (int i = 0; i < blobs.Count; i++) if (i != 5) w.Write(blobs[i]); + } + + public static void Run(Action<bool, string> check, string dir) + { + WorldMapTiles.Shutdown(); + string v2 = Path.Combine(dir, "dxt.rmap"); + // 16 x 16 tiles at level 0 (256, more than the 192 cap), 8 x 8, then 4 x 4. + WriteV2(v2, new[] { (16, 16), (8, 8), (4, 4) }); + check(WaitOpen(v2), "dxt: the version 2 file opens"); + check(WorldMapTiles.IsDxt, "dxt: it is recognised as DXT1"); + check(WorldMapTiles.PixelsPerCell == 8 && WorldMapTiles.Levels.Count == 3, "dxt: 8 px per cell, three levels"); + + // A tile reaches the device as DXT1 blocks, untouched: its own number is in the first block. + int before = DX9Backend.DxtCreated; + bool got = Load(1, 3, 2, out IntPtr t); + int id = 256 + 2 * 8 + 3; + check(got && DX9Backend.DxtCreated == before + 1, "dxt: a tile is made with the DXT1 upload (not RGBA)"); + check(got && DX9Backend.Live.TryGetValue(t, out var px) && px.R == (byte)id && px.G == (byte)(id >> 8), "dxt: its blocks are that tile's, as written"); + + // A tile the baker didn't make (length 0) never loads and never throws. + check(!Load(0, 5, 0, out _) || true, "dxt: an unbaked tile is asked for without trouble"); + check(!WorldMapTiles.Peek(0, 5, 0, out _), "dxt: an unbaked tile has no texture"); + + // The cap is 192 textures, not 96. + Check(WorldMapTiles.Peek(1, 3, 2, out _), check, "dxt: the first tile is still there"); + int loaded = 0; + for (int i = 6; i < 6 + 230; i++) if (Load(0, i % 16, i / 16, out _)) loaded++; + for (int i = 0; i < 4; i++) WorldMapTiles.BeginFrame(new IntPtr(1)); + check(loaded == 230, $"dxt: 230 tiles loaded in turn ({loaded})"); + check(WorldMapTiles.LiveTextures <= 192 && DX9Backend.Live.Count <= 192, $"dxt: never over 192 textures (engine {WorldMapTiles.LiveTextures}, backend {DX9Backend.Live.Count})"); + check(WorldMapTiles.LiveTextures > 150, $"dxt: and more than the RGBA cap of 96 are kept ({WorldMapTiles.LiveTextures})"); + check(DX9Backend.Created - DX9Backend.Released == DX9Backend.Live.Count, "dxt: every texture that left the table was released"); + + // Switching files: the old textures go at the start of the next frame, then the new file opens. + string v1 = Path.Combine(dir, "flat.rmap"); + WriteFlat(v1); + WorldMapTiles.Switch(v1); + for (int i = 0; i < 400 && !(WorldMapTiles.IsOpen && WorldMapTiles.CurrentPath == v1); i++) { WorldMapTiles.BeginFrame(new IntPtr(1)); Thread.Sleep(5); } + check(WorldMapTiles.CurrentPath == v1 && WorldMapTiles.IsOpen, "switch: the other file is open"); + check(!WorldMapTiles.IsDxt && WorldMapTiles.PixelsPerCell == 2, "switch: and it is the flat, 2 px per cell one"); + check(DX9Backend.Live.Count == 0 && WorldMapTiles.LiveTextures == 0, "switch: the old file's textures were all released"); + check(Load(0, 0, 0, out IntPtr ft) && DX9Backend.Live[ft].A == 255, "switch: a tile of the new file loads (RGBA)"); + + // Switching to the file already open does nothing. + int made = DX9Backend.Created; + WorldMapTiles.Switch(v1); + for (int i = 0; i < 5; i++) WorldMapTiles.BeginFrame(new IntPtr(1)); + check(DX9Backend.Created == made && WorldMapTiles.IsOpen, "switch: to the same file is a no-op"); + WorldMapTiles.Shutdown(); + } + + private static void Check(bool ok, Action<bool, string> check, string what) => check(ok, what); + + /// <summary>A real version 2 file from the baker (a partial bake is fine: tiles it didn't make have no texture).</summary> + public static void RealDxt(string path, Action<bool, string> check) + { + System.Console.WriteLine("real DXT1 file: " + path); + WorldMapTiles.Shutdown(); + check(WaitOpen(path), "real dxt: opens (" + WorldMapTiles.Status + ")"); + if (!WorldMapTiles.IsOpen) return; + var lv = WorldMapTiles.Levels; + check(WorldMapTiles.IsDxt && WorldMapTiles.PixelsPerCell >= 2 && lv.Count >= 5, $"real dxt: DXT1, {WorldMapTiles.PixelsPerCell} px per cell, {lv.Count} levels"); + check(lv[0].Cols == lv[0].Rows && lv[^1].Cols == 1, "real dxt: square, down to one tile"); + check(Load(lv.Count - 1, 0, 0, out IntPtr top) && DX9Backend.Live.ContainsKey(top), "real dxt: the whole-world tile loads"); + // Holtburg (42.1N, 33.6E: cell 1355.5, 1440.5) at the sharpest level, and a few levels up. + int ppc = WorldMapTiles.PixelsPerCell; + int col = (int)(1355.5 * ppc / 256), row = (int)((2048 - 1440.5) * ppc / 256); + check(lv[0].Width == 2048 * ppc && lv[0].Cols == 2048 * ppc / 256, $"real dxt: level 0 is {lv[0].Width} px = 2048 cells x {ppc}"); + if (path.EndsWith("worldmap-p32.rmap", StringComparison.OrdinalIgnoreCase) || lv[0].Cols * lv[0].Rows > 1000) + { + bool all = true; + for (int l = 0; l < Math.Min(lv.Count, 4); l++) + if (!Load(l, col >> l, row >> l, out _)) all = false; + check(all, $"real dxt: the Holtburg tile loads at levels 0-3 (level 0 col {col}, row {row})"); + } + WorldMapTiles.Shutdown(); + } + + // A one-level, one-tile version 1 (RGB) file at 2 px per cell. + private static void WriteFlat(string path) + { + var raw = new byte[256 * 256 * 3]; + for (int i = 0; i < raw.Length; i += 3) { raw[i] = 20; raw[i + 1] = 60; raw[i + 2] = 120; } + using var ms = new MemoryStream(); + using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(raw); + byte[] blob = ms.ToArray(); + long header = 4 + 6 * 4 + 20 + 4 + 12; + using var fs = new FileStream(path, FileMode.Create); + using var w = new BinaryWriter(fs); + w.Write(new byte[] { (byte)'R', (byte)'M', (byte)'A', (byte)'P' }); + w.Write(1u); w.Write(256u); w.Write(1u); w.Write(2u); w.Write(128u); w.Write(128u); + w.Write(256u); w.Write(256u); w.Write(1u); w.Write(1u); w.Write(0u); + w.Write(1u); w.Write((ulong)header); w.Write((uint)blob.Length); + w.Write(blob); + } + } +} diff --git a/tools/WorldMapTilesTests/Program.cs b/tools/WorldMapTilesTests/Program.cs new file mode 100644 index 0000000..f7ab7a7 --- /dev/null +++ b/tools/WorldMapTilesTests/Program.cs @@ -0,0 +1,210 @@ +using System.IO.Compression; +using RynthCore.Engine.ImGuiBackend; + +namespace RynthCore.Engine.ImGuiBackend +{ + /// <summary>Stands in for the engine's D3D9 backend: a "texture" is a counter, remembering its first pixel.</summary> + internal static class DX9Backend + { + public static readonly Dictionary<IntPtr, (byte R, byte G, byte B, byte A)> Live = new(); + private static long _next = 0x1000; + public static int Created, Released; + + public static IntPtr CreateTextureRgba(IntPtr device, int width, int height, ReadOnlySpan<byte> rgba) + { + if (width != 256 || height != 256 || rgba.Length != 256 * 256 * 4) return IntPtr.Zero; + var p = new IntPtr(_next += 0x10); + Live[p] = (rgba[0], rgba[1], rgba[2], rgba[3]); + Created++; + return p; + } + + public static int DxtCreated; + + /// <summary>A DXT1 tile: the first two bytes (the first block's colour 0) say which tile it is.</summary> + public static IntPtr CreateTextureDxt1(IntPtr device, int width, int height, ReadOnlySpan<byte> blocks) + { + if (width != 256 || height != 256 || blocks.Length != 256 * 256 / 2) return IntPtr.Zero; + var p = new IntPtr(_next += 0x10); + Live[p] = (blocks[0], blocks[1], 0, 255); + Created++; DxtCreated++; + return p; + } + + public static void ReleaseTexture(IntPtr tex) { if (Live.Remove(tex)) Released++; } + } +} + +namespace WorldMapTilesTests +{ + /// <summary>The map file's layout (RynthNav.Baker WorldMapRender.WriteRmap), written here independently.</summary> + internal static class Program + { + private static int _checks, _failed; + private static readonly IntPtr Dev = new(1); + + private static int Main(string[] args) + { + string dir = Path.Combine(Path.GetTempPath(), "wmtiles-" + Environment.ProcessId); + Directory.CreateDirectory(dir); + try + { + ProjectionTests.Run(Check); + Synthetic(Path.Combine(dir, "synthetic.rmap")); + VectorTests.Run(Check, dir, args.Length > 1 ? args[1] : null); + DxtTileTests.Run(Check, dir); + if (args.Length > 0) Real(args[0]); + if (args.Length > 2) DxtTileTests.RealDxt(args[2], Check); + } + finally { try { Directory.Delete(dir, true); } catch { } } + Console.WriteLine(_failed == 0 ? $"OK: {_checks} checks" : $"FAILED: {_failed} of {_checks} checks"); + return _failed == 0 ? 0 : 1; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (!ok) { _failed++; Console.WriteLine("FAIL: " + what); } + } + + // A tile's colour from its level and position, so a read tile can be told from any other. + private static (byte R, byte G, byte B) Colour(int level, int col, int row) => + ((byte)(40 + level * 60), (byte)(10 + col * 17), (byte)(10 + row * 17)); + + private static void WriteSynthetic(string path, (int Cols, int Rows)[] levels) + { + var blobs = new List<byte[]>(); + var first = new int[levels.Length]; + for (int l = 0; l < levels.Length; l++) + { + first[l] = blobs.Count; + for (int r = 0; r < levels[l].Rows; r++) + for (int c = 0; c < levels[l].Cols; c++) + { + var (cr, cg, cb) = Colour(l, c, r); + var raw = new byte[256 * 256 * 3]; + for (int i = 0; i < raw.Length; i += 3) { raw[i] = cr; raw[i + 1] = cg; raw[i + 2] = cb; } + using var ms = new MemoryStream(); + using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(raw); + blobs.Add(ms.ToArray()); + } + } + long header = 4 + 6 * 4 + levels.Length * 20 + 4 + blobs.Count * 12L; + using var fs = new FileStream(path, FileMode.Create); + using var w = new BinaryWriter(fs); + w.Write(new byte[] { (byte)'R', (byte)'M', (byte)'A', (byte)'P' }); + w.Write(1u); w.Write(256u); w.Write((uint)levels.Length); w.Write(2u); + w.Write((uint)(levels[0].Cols * 256 / 2)); w.Write((uint)(levels[0].Rows * 256 / 2)); + for (int l = 0; l < levels.Length; l++) + { w.Write((uint)(levels[l].Cols * 256)); w.Write((uint)(levels[l].Rows * 256)); w.Write((uint)levels[l].Cols); w.Write((uint)levels[l].Rows); w.Write((uint)first[l]); } + w.Write((uint)blobs.Count); + long off = header; + foreach (byte[] b in blobs) { w.Write((ulong)off); w.Write((uint)b.Length); off += b.Length; } + foreach (byte[] b in blobs) w.Write(b); + } + + private static bool WaitOpen(string path) + { + WorldMapTiles.Open(path); + for (int i = 0; i < 300 && !WorldMapTiles.IsOpen; i++) Thread.Sleep(10); + return WorldMapTiles.IsOpen; + } + + private static void WaitStatus() + { + for (int i = 0; i < 300 && (WorldMapTiles.Status.Length == 0 || WorldMapTiles.Status == "Loading the map..."); i++) Thread.Sleep(10); + } + + /// <summary>Asks for a tile each frame, as a face does, until it's there or the time is up.</summary> + private static bool Load(int level, int col, int row, out IntPtr tex) + { + tex = IntPtr.Zero; + for (int i = 0; i < 400; i++) + { + WorldMapTiles.BeginFrame(Dev); + if (WorldMapTiles.TryGet(level, col, row, out tex)) return true; + Thread.Sleep(2); + } + return false; + } + + private static void Synthetic(string path) + { + // 12x12 tiles at level 0 (144, more than the 96-texture cap), 6x6, then 3x3. + WriteSynthetic(path, new[] { (12, 12), (6, 6), (3, 3) }); + Check(WaitOpen(path), "the file opens"); + Check(WorldMapTiles.Levels.Count == 3, "three levels"); + Check(WorldMapTiles.Levels.Count == 3 && WorldMapTiles.Levels[0].Cols == 12 && WorldMapTiles.Levels[1].First == 144 && WorldMapTiles.Levels[2].First == 144 + 36, "level table"); + Check(WorldMapTiles.PixelsPerCell == 2 && WorldMapTiles.CellsWide == 1536 && WorldMapTiles.CellsHigh == 1536, "pixels per cell and size in cells"); + + // A tile arrives with its own pixels, and Peek sees it only once loaded. + Check(!WorldMapTiles.Peek(1, 4, 5, out _), "peek: not loaded yet"); + bool got = Load(1, 4, 5, out IntPtr t); + Check(got, "a tile loads"); + var (er, eg, eb) = Colour(1, 4, 5); + Check(got && DX9Backend.Live.TryGetValue(t, out var px) && px.R == er && px.G == eg && px.B == eb && px.A == 255, "its pixels are that tile's, opaque"); + Check(WorldMapTiles.Peek(1, 4, 5, out IntPtr again) && again == t, "peek finds it"); + Check(!WorldMapTiles.TryGet(1, 6, 0, out _) && !WorldMapTiles.TryGet(1, 0, 6, out _) && !WorldMapTiles.TryGet(3, 0, 0, out _) && !WorldMapTiles.TryGet(-1, 0, 0, out _), "out of range: nothing"); + + // Tiles by column and row: the colours say which one came back. + Check(Load(0, 0, 0, out IntPtr a) && Load(0, 11, 11, out IntPtr b) && a != b + && DX9Backend.Live[a].G == Colour(0, 0, 0).G && DX9Backend.Live[b].G == Colour(0, 11, 11).G && DX9Backend.Live[b].B == Colour(0, 11, 11).B, "tiles by column and row"); + + // The cap: 120 tiles of level 0, each loaded once and left; the table never holds more than 96 and the oldest go. + Check(Load(2, 0, 0, out IntPtr topFirst), "the first tile of the top level loads"); + int loaded = 0; + for (int i = 0; i < 120; i++) if (Load(0, i % 12, i / 12, out _)) loaded++; + for (int i = 0; i < 4; i++) WorldMapTiles.BeginFrame(Dev); + Check(loaded == 120, "120 tiles loaded in turn (" + loaded + ")"); + Check(WorldMapTiles.LiveTextures <= 96 && DX9Backend.Live.Count <= 96, $"never over 96 textures (engine {WorldMapTiles.LiveTextures}, backend {DX9Backend.Live.Count})"); + Check(DX9Backend.Created - DX9Backend.Released == DX9Backend.Live.Count && WorldMapTiles.LiveTextures == DX9Backend.Live.Count, "every texture that left the table was released"); + Check(!WorldMapTiles.Peek(0, 0, 0, out _), "the oldest was evicted"); + Check(WorldMapTiles.Peek(0, 119 % 12, 119 / 12, out _), "the newest is kept"); + Check(WorldMapTiles.Peek(2, 0, 0, out IntPtr topAgain) && topAgain == topFirst, "the top level's first tile is never evicted"); + + // Shutdown: nothing left alive, and it can open again. + WorldMapTiles.Shutdown(); + Check(DX9Backend.Live.Count == 0 && WorldMapTiles.LiveTextures == 0, "shutdown released every texture"); + Check(!WorldMapTiles.IsOpen && WorldMapTiles.Levels.Count == 0, "shutdown closed the file"); + Check(WaitOpen(path) && Load(1, 0, 0, out _), "it opens again after shutdown"); + WorldMapTiles.Shutdown(); + + // A file that isn't a map, and a missing one: a status, no throw. + string dir = Path.GetDirectoryName(path)!; + string junk = Path.Combine(dir, "junk.rmap"); + File.WriteAllBytes(junk, new byte[64]); + WorldMapTiles.Open(junk); + WaitStatus(); + Check(!WorldMapTiles.IsOpen && WorldMapTiles.Status.Contains("didn't load"), "a bad file says so: " + WorldMapTiles.Status); + WorldMapTiles.Shutdown(); + WorldMapTiles.Open(Path.Combine(dir, "nothere.rmap")); + WaitStatus(); + Check(!WorldMapTiles.IsOpen && WorldMapTiles.Status.Contains("No world map file"), "a missing file says so: " + WorldMapTiles.Status); + WorldMapTiles.Shutdown(); + } + + private static void Real(string path) + { + Console.WriteLine("real file: " + path); + Check(WaitOpen(path), "real: opens (" + WorldMapTiles.Status + ")"); + if (!WorldMapTiles.IsOpen) return; + var lv = WorldMapTiles.Levels; + Check(lv.Count == 5 && lv[0].Width == 4096 && lv[4].Cols == 1 && lv[4].Rows == 1, "real: 5 levels, 4096 px down to one tile"); + Check(WorldMapTiles.PixelsPerCell == 2 && WorldMapTiles.CellsWide == 2048, "real: 2 px per cell over 2048 cells"); + // The top tile is the whole map: mostly deep sea (blue), so its corner pixel is the sea colour. + Check(Load(4, 0, 0, out IntPtr top) && DX9Backend.Live[top].B > DX9Backend.Live[top].R, "real: the top tile loads and its corner is sea"); + // Every tile of every level inflates to a full opaque tile. + int bad = 0, total = 0; + for (int l = 0; l < lv.Count; l++) + for (int r = 0; r < lv[l].Rows; r++) + for (int c = 0; c < lv[l].Cols; c++) + { + total++; + if (!Load(l, c, r, out _)) bad++; + } + Check(bad == 0, $"real: all {total} tiles load ({bad} failed)"); + WorldMapTiles.Shutdown(); + Check(DX9Backend.Live.Count == 0, "real: shutdown released all"); + } + } +} diff --git a/tools/WorldMapTilesTests/ProjectionTests.cs b/tools/WorldMapTilesTests/ProjectionTests.cs new file mode 100644 index 0000000..11ebd71 --- /dev/null +++ b/tools/WorldMapTilesTests/ProjectionTests.cs @@ -0,0 +1,96 @@ +using System.Numerics; +using RynthCore.Engine.ImGuiBackend.Panels; + +namespace WorldMapTilesTests +{ + /// <summary>MapProjection: cells to screen and back, and the rotation that puts the way you face up.</summary> + internal static class ProjectionTests + { + private static bool Near(Vector2 a, Vector2 b, float eps = 0.001f) => Vector2.Distance(a, b) < eps; + + public static void Run(Action<bool, string> check) + { + var centre = new Vector2(400, 300); + var north = new MapProjection(centre, 1000, 1000, 2f, 0f); + + // Map-up: north is up the screen, east is right, 2 px per cell. + check(Near(north.Project(1000, 1000), centre), "the view centre cell is at the screen centre"); + check(Near(north.Project(1010, 1000), centre + new Vector2(20, 0)), "east is to the right, scale px per cell"); + check(Near(north.Project(1000, 1010), centre + new Vector2(0, -20)), "north is up the screen"); + check(!north.Turned, "no rotation is not turned"); + check(MathF.Abs(MapProjection.PhiForHeading(90f)) < 1e-6f, "facing north needs no rotation"); + + // Round trips, through every rotation. + var rnd = new Random(7); + bool roundTrip = true; + for (int i = 0; i < 200; i++) + { + var p = new MapProjection(new Vector2(rnd.Next(100, 900), rnd.Next(100, 700)), rnd.NextDouble() * 2000, rnd.NextDouble() * 2000, + 0.12f + (float)rnd.NextDouble() * 13f, (float)(rnd.NextDouble() * Math.PI * 2)); + double cx = rnd.NextDouble() * 2048, cy = rnd.NextDouble() * 2048; + p.Unproject(p.Project(cx, cy), out double bx, out double by); + if (Math.Abs(bx - cx) > 0.01 || Math.Abs(by - cy) > 0.01) roundTrip = false; + } + check(roundTrip, "unproject(project(cell)) is the cell, at any zoom and rotation"); + + // Rotating with the player: the heading is straight up whatever it is. + bool headingUp = true; + foreach (float h in new[] { 0f, 30f, 45f, 90f, 135f, 180f, 225f, 270f, 359f }) + { + var p = new MapProjection(centre, 1000, 1000, 3f, MapProjection.PhiForHeading(h)); + float r = h * MathF.PI / 180f; + if (!Near(p.ScreenDir(MathF.Cos(r), MathF.Sin(r)), new Vector2(0, -1), 0.001f)) headingUp = false; + // And a point ahead of the player, in the map, is above them on screen. + Vector2 ahead = p.Project(1000 + 10 * Math.Cos(r), 1000 + 10 * Math.Sin(r)); + if (!(ahead.Y < centre.Y - 29f && MathF.Abs(ahead.X - centre.X) < 0.01f)) headingUp = false; + } + check(headingUp, "the way you face is up on screen at every heading"); + + // Where the compass needle and your right hand go. + var east = new MapProjection(centre, 0, 0, 1f, MapProjection.PhiForHeading(0f)); // facing east + check(Near(east.ScreenDir(0, 1), new Vector2(-1, 0)), "facing east: north is on your left"); + var south = new MapProjection(centre, 0, 0, 1f, MapProjection.PhiForHeading(270f)); + check(Near(south.ScreenDir(0, 1), new Vector2(0, 1)), "facing south: north is behind you (down)"); + var facingNorth = new MapProjection(centre, 0, 0, 1f, MapProjection.PhiForHeading(90f)); + check(Near(facingNorth.ScreenDir(1, 0), new Vector2(1, 0)), "facing north: east is on your right"); + var facingWest = new MapProjection(centre, 0, 0, 1f, MapProjection.PhiForHeading(180f)); + check(Near(facingWest.ScreenDir(0, 1), new Vector2(1, 0)), "facing west: north is on your right"); + + // Zoom about the cursor: the cell under the mouse stays under the mouse. + bool zoomFixed = true; + for (int i = 0; i < 100; i++) + { + var p = new MapProjection(new Vector2(300, 250), rnd.NextDouble() * 2000, rnd.NextDouble() * 2000, 0.3f + (float)rnd.NextDouble() * 6f, + (float)(rnd.NextDouble() * Math.PI * 2)); + var mouse = new Vector2(rnd.Next(0, 600), rnd.Next(0, 500)); + float next = p.Scale * (0.4f + (float)rnd.NextDouble() * 3f); + p.Unproject(mouse, out double bx, out double by); + var (nx, ny) = p.CentreForZoomAbout(mouse, next); + var after = new MapProjection(p.Centre, nx, ny, next, MathF.Atan2(p.Sin, p.Cos)); + if (!Near(after.Project(bx, by), mouse, 0.05f)) zoomFixed = false; + } + check(zoomFixed, "zooming about the cursor keeps the cell under it"); + + // Dragging: the cell that was under the mouse moves with it. + bool dragFollows = true; + for (int i = 0; i < 100; i++) + { + var p = new MapProjection(new Vector2(300, 250), rnd.NextDouble() * 2000, rnd.NextDouble() * 2000, 0.3f + (float)rnd.NextDouble() * 6f, + (float)(rnd.NextDouble() * Math.PI * 2)); + var mouse = new Vector2(rnd.Next(0, 600), rnd.Next(0, 500)); + var delta = new Vector2(rnd.Next(-80, 80), rnd.Next(-80, 80)); + p.Unproject(mouse, out double bx, out double by); + var (nx, ny) = p.CentreAfterDrag(delta); + var after = new MapProjection(p.Centre, nx, ny, p.Scale, MathF.Atan2(p.Sin, p.Cos)); + if (!Near(after.Project(bx, by), mouse + delta, 0.05f)) dragFollows = false; + } + check(dragFollows, "dragging moves the map with the mouse, at any rotation"); + + // Dragging right moves the map right: the centre cell moves west (smaller x) when not rotated. + var (dx, _) = north.CentreAfterDrag(new Vector2(20, 0)); + check(Math.Abs(dx - (1000 - 10)) < 1e-6, "dragging 20 px right at 2 px per cell moves the centre 10 cells west"); + var (_, dy) = north.CentreAfterDrag(new Vector2(0, 20)); + check(Math.Abs(dy - (1000 + 10)) < 1e-6, "dragging 20 px down moves the centre 10 cells north"); + } + } +} diff --git a/tools/WorldMapTilesTests/VectorTests.cs b/tools/WorldMapTilesTests/VectorTests.cs new file mode 100644 index 0000000..7727d9c --- /dev/null +++ b/tools/WorldMapTilesTests/VectorTests.cs @@ -0,0 +1,71 @@ +using System.Numerics; +using RynthCore.Engine.ImGuiBackend; + +namespace WorldMapTilesTests +{ + /// <summary>worldmap.vec (RynthNav.Baker WorldMapVectors.Write), written here independently, and the engine's reader.</summary> + internal static class VectorTests + { + private static void WaitDone() + { + for (int i = 0; i < 300 && WorldMapVectors.Current == null && !WorldMapVectors.Failed; i++) Thread.Sleep(10); + } + + public static void Run(Action<bool, string> check, string dir, string? realPath) + { + string path = Path.Combine(dir, "synthetic.vec"); + using (var fs = new FileStream(path, FileMode.Create)) + using (var w = new BinaryWriter(fs)) + { + w.Write(new byte[] { (byte)'R', (byte)'V', (byte)'E', (byte)'C' }); + w.Write(1u); w.Write(2u); w.Write(3u); + w.Write((byte)3); foreach (var (x, y) in new[] { (10f, 20f), (14f, 20f), (12f, 25.5f) }) { w.Write(x); w.Write(y); } + w.Write((byte)4); foreach (var (x, y) in new[] { (100f, 100f), (102f, 100f), (102f, 103f), (100f, 103f) }) { w.Write(x); w.Write(y); } + foreach (ushort v in new ushort[] { 1, 2, 3, 4, 2000, 2001, 2002, 2003, 7, 7, 8, 8 }) w.Write(v); + } + WorldMapVectors.Open(path); + WaitDone(); + var d = WorldMapVectors.Current; + check(d != null && !WorldMapVectors.Failed, "vectors: the file opens"); + if (d != null) + { + check(d.Buildings.Length == 2 && d.Buildings[0].Length == 3 && d.Buildings[1].Length == 4, "vectors: two buildings with 3 and 4 corners"); + check(d.Buildings[0][2] == new Vector2(12f, 25.5f) && d.Buildings[1][3] == new Vector2(100f, 103f), "vectors: corners as written"); + check(d.BuildingBounds[0] == new Vector4(10f, 20f, 14f, 25.5f) && d.BuildingBounds[1] == new Vector4(100f, 100f, 102f, 103f), "vectors: bounds for culling"); + check(d.RoadCount == 3 && d.Roads[0] == 1 && d.Roads[3] == 4 && d.Roads[4] == 2000 && d.Roads[11] == 8, "vectors: three road segments as written"); + } + WorldMapVectors.Shutdown(); + check(WorldMapVectors.Current == null, "vectors: shutdown drops the data"); + + string junk = Path.Combine(dir, "junk.vec"); + File.WriteAllBytes(junk, new byte[40]); + WorldMapVectors.Open(junk); + WaitDone(); + check(WorldMapVectors.Current == null && WorldMapVectors.Failed, "vectors: a bad file is a failure, not a throw"); + WorldMapVectors.Shutdown(); + WorldMapVectors.Open(Path.Combine(dir, "nothere.vec")); + WaitDone(); + check(WorldMapVectors.Current == null && WorldMapVectors.Failed, "vectors: a missing file is a failure, not a throw"); + WorldMapVectors.Shutdown(); + + if (realPath == null) return; + Console.WriteLine("real vectors: " + realPath); + WorldMapVectors.Open(realPath); + WaitDone(); + var r = WorldMapVectors.Current; + check(r != null, "real vectors: opens"); + if (r == null) return; + check(r.Buildings.Length > 5000 && r.RoadCount > 5000, $"real vectors: {r.Buildings.Length} buildings, {r.RoadCount} road segments"); + bool inRange = true, corners = true; + foreach (Vector2[] b in r.Buildings) + { + if (b.Length < 3 || b.Length > 10) corners = false; + foreach (Vector2 p in b) if (p.X < -10 || p.X > 2060 || p.Y < -10 || p.Y > 2060) inRange = false; + } + for (int i = 0; i < r.Roads.Length; i++) if (r.Roads[i] > 2048) inRange = false; + check(corners, "real vectors: every outline has 3 to 10 corners"); + check(inRange, "real vectors: everything is inside the map"); + WorldMapVectors.Shutdown(); + } + } +} diff --git a/tools/WorldMapTilesTests/WorldMapTilesTests.csproj b/tools/WorldMapTilesTests/WorldMapTilesTests.csproj new file mode 100644 index 0000000..3f25666 --- /dev/null +++ b/tools/WorldMapTilesTests/WorldMapTilesTests.csproj @@ -0,0 +1,25 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the World Map's tile loader (DXT1 version 2 files, switching files) and its projection (Panels\MapProjection.cs, compiled in) (src\RynthCore.Engine\ImGui\WorldMapTiles.cs, + compiled in; DX9Backend is a stub here): the worldmap.rmap header and tile layout as + RynthNav.Baker writes it with its map-tiles option, the tile lookups, the texture cap and eviction, + and that Shutdown releases every texture. + Run: dotnet run -c Release, optionally with the paths of a worldmap.rmap and a worldmap.vec as the arguments (exit 0 = pass, 1 = fail; a real file is checked too when given) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>WorldMapTilesTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\ImGui\WorldMapTiles.cs" Link="Engine\WorldMapTiles.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\MapProjection.cs" Link="Engine\MapProjection.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\ImGui\WorldMapVectors.cs" Link="Engine\WorldMapVectors.cs" /> + </ItemGroup> + +</Project> From 516ad2bdf29675ed972d592bae192523164c7cdd Mon Sep 17 00:00:00 2001 From: Tom Bohar <tombohar@gmail.com> Date: Thu, 15 Oct 2026 20:32:34 -0400 Subject: [PATCH 2/6] Snapshot for release 2026.10.15.2 (internal 9094d68) --- installer/Publish-Update.ps1 | 19 +- .../AccountProfileDialog.axaml | 5 +- .../AccountProfileDialog.axaml.cs | 69 ++- .../FirstLoginDialog.axaml | 44 ++ .../FirstLoginDialog.axaml.cs | 122 +++++ .../MainWindow.axaml.cs | 219 +++++++- .../RynthCore.App.Avalonia.csproj | 10 +- .../AcClientLaunchSettingsService.cs | 17 +- src/RynthCore.App/AcLaunchArgumentBuilder.cs | 50 +- src/RynthCore.App/FirstLoginRules.cs | 98 ++++ src/RynthCore.App/LaunchAccountProfile.cs | 18 + src/RynthCore.App/UserPrefsSwapRecovery.cs | 87 +++ .../Compatibility/AcMainThreadQueue.cs | 30 +- .../Compatibility/ChatCallbackHooks.cs | 7 +- .../Compatibility/ClientHelperHooks.cs | 3 + .../Compatibility/ConfirmationResponder.cs | 203 +++++++ .../Compatibility/DatFileShareHooks.cs | 215 ++++---- src/RynthCore.Engine/Compatibility/IltInfo.cs | 53 +- .../Compatibility/RynthCoreChatCommands.cs | 228 +++++++- .../Compatibility/ServerInfo.cs | 49 +- .../Compatibility/SmartBoxHooks.cs | 10 + src/RynthCore.Engine/EngineLifecycle.cs | 3 + src/RynthCore.Engine/EntryPoint.cs | 54 +- src/RynthCore.Engine/Hooking/MinHook.cs | 15 +- .../ImGui/EngineFrameController.cs | 4 + src/RynthCore.Engine/ImGui/ImGuiBar.cs | 20 +- src/RynthCore.Engine/ImGui/ImGuiFontTest.cs | 4 +- src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs | 150 ++++- .../ImGui/MonsterHud/MonsterHudSettingsUi.cs | 4 +- .../ImGui/MonsterHud/PlayerPlate.cs | 2 +- .../ImGui/Panels/BountiesFace.cs | 4 +- .../ImGui/Panels/CharactersFace.cs | 10 +- src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 4 +- .../ImGui/Panels/ChatFiltersFace.cs | 8 +- .../ImGui/Panels/DamageDetailFace.cs | 34 +- .../ImGui/Panels/DamageFace.cs | 36 +- .../ImGui/Panels/DashboardDrawers.cs | 4 +- .../ImGui/Panels/DungeonMapFace.cs | 2 +- .../ImGui/Panels/HotkeysSettingsUi.cs | 16 +- .../ImGui/Panels/InventoryFace.AttrFilter.cs | 6 +- .../ImGui/Panels/InventoryFace.Classic.cs | 8 +- .../ImGui/Panels/InventoryFace.MultiSelect.cs | 6 +- .../ImGui/Panels/InventoryFace.cs | 6 +- .../ImGui/Panels/ItemCountFace.cs | 4 +- .../ImGui/Panels/ItemsFace.cs | 2 +- .../ImGui/Panels/LootAddDialog.cs | 12 +- .../ImGui/Panels/LootEditorFace.cs | 28 +- src/RynthCore.Engine/ImGui/Panels/LuaFace.cs | 18 +- .../ImGui/Panels/MetaFace.Editor.cs | 14 +- .../ImGui/Panels/MetaFace.List.cs | 24 +- .../ImGui/Panels/MetaFace.Schedule.cs | 16 +- src/RynthCore.Engine/ImGui/Panels/MetaFace.cs | 8 +- .../ImGui/Panels/MiniRemoteFace.Sections.cs | 511 ++++++++++++++++++ .../ImGui/Panels/MiniRemoteFace.cs | 102 +++- src/RynthCore.Engine/ImGui/Panels/NavFace.cs | 6 +- src/RynthCore.Engine/ImGui/Panels/P1Faces.cs | 6 +- .../ImGui/Panels/QuickSettingsDrawer.cs | 4 +- .../ImGui/Panels/RadarFace.cs | 6 +- .../ImGui/Panels/RangesSlideOut.cs | 12 +- .../ImGui/Panels/ReportFace.cs | 2 +- .../ImGui/Panels/RynthAiFace.Drawers.cs | 14 +- .../ImGui/Panels/RynthAiFace.cs | 124 +++-- .../ImGui/Panels/RynthNavArrowFace.cs | 12 +- .../ImGui/Panels/RynthNavFace.cs | 34 +- .../ImGui/Panels/SenseFace.cs | 2 +- .../ImGui/Panels/ServerPickSettingsUi.cs | 126 +++++ .../ImGui/Panels/SettingsFace.cs | 2 +- .../ImGui/Panels/SettingsRows.cs | 11 +- .../ImGui/Panels/SkillsFace.Progression.cs | 10 +- .../ImGui/Panels/SkillsFace.cs | 18 +- .../ImGui/Panels/VisionFace.cs | 4 +- .../ImGui/Panels/WorldMapFace.cs | 2 +- .../ImGui/Panels/WorldMapView.cs | 4 +- src/RynthCore.Engine/ImGui/RynthCoreShell.cs | 84 +-- src/RynthCore.Engine/ImGui/SafeImGui.cs | 44 ++ src/RynthCore.Engine/Net/AelrynthVaultWire.cs | 26 +- src/RynthCore.Engine/Net/ChatOrigin.cs | 54 ++ .../Plugins/EngineSettings.cs | 54 +- src/RynthCore.Engine/Plugins/LoadedPlugin.cs | 8 + .../Plugins/PluginContract.cs | 31 ++ .../Plugins/PluginContractVersion.cs | 6 +- src/RynthCore.Engine/Plugins/PluginLoader.cs | 1 + .../Plugins/PluginManager.ServerPlugins.cs | 153 ++++++ src/RynthCore.Engine/Plugins/PluginManager.cs | 274 +++++++--- .../Plugins/PluginManifestGate.cs | 70 ++- src/RynthCore.Engine/RynthLog.cs | 11 + src/RynthCore.Engine/UI/Data/SettingsData.cs | 15 +- .../UI/ScriptWindows/ScriptWindowRegistry.cs | 32 ++ .../UI/Sections/NotLoadedServers.cs | 63 +++ .../UI/Sections/SectionCatalog.cs | 226 ++++++++ .../UI/Sections/SectionManifest.cs | 253 +++++++++ .../UI/Sections/SectionRegistry.cs | 277 ++++++++++ .../UI/Sections/ServerForce.cs | 134 +++++ .../UI/Sections/ServerForceStore.cs | 160 ++++++ .../UI/Sections/ServerSelection.cs | 131 +++++ .../UI/Sections/ServerSelectionStore.cs | 53 ++ .../UI/Sections/ServerStateJson.cs | 89 +++ src/RynthCore.Engine/UI/ServerMenus.cs | 340 +++++++----- src/RynthCore.Injector/LaunchCommand.cs | 7 + .../Manifest/RynthPluginManifest.cs | 126 +++++ src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 5 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 94 ++++ .../build/RynthCore.PluginSdk.targets | 50 +- src/RynthCore.StatusAgent/AgentConfig.cs | 5 +- .../LocalStatusServer.cs | 69 ++- src/RynthCore.StatusAgent/Program.cs | 13 + .../RynthCore.StatusAgent.csproj | 3 +- src/RynthCore.StatusAgent/ServeGuard.cs | 155 ++++++ .../EngineSettingsTests.csproj | 3 + tools/EngineSettingsTests/Program.cs | 30 + .../LauncherSettingsTests.csproj | 2 + tools/LauncherSettingsTests/Program.cs | 131 ++++- .../LauncherUpdateTests.csproj | 1 + tools/NetMessageTests/NetMessageTests.csproj | 1 + tools/NetMessageTests/VaultWireTests.cs | 12 + tools/PluginManifestTests/Program.cs | 147 ++++- tools/SectionsTests/Program.cs | 452 ++++++++++++++++ tools/SectionsTests/SectionsTests.csproj | 36 ++ tools/StatusAgentTests/Program.cs | 48 ++ .../StatusAgentTests/StatusAgentTests.csproj | 1 + tools/check_imgui_calls.py | 217 +++++++- 121 files changed, 6498 insertions(+), 793 deletions(-) create mode 100644 src/RynthCore.App.Avalonia/FirstLoginDialog.axaml create mode 100644 src/RynthCore.App.Avalonia/FirstLoginDialog.axaml.cs create mode 100644 src/RynthCore.App/FirstLoginRules.cs create mode 100644 src/RynthCore.App/UserPrefsSwapRecovery.cs create mode 100644 src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs create mode 100644 src/RynthCore.Engine/ImGui/SafeImGui.cs create mode 100644 src/RynthCore.Engine/Net/ChatOrigin.cs create mode 100644 src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs create mode 100644 src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs create mode 100644 src/RynthCore.Engine/UI/Sections/SectionCatalog.cs create mode 100644 src/RynthCore.Engine/UI/Sections/SectionManifest.cs create mode 100644 src/RynthCore.Engine/UI/Sections/SectionRegistry.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerForce.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerForceStore.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerSelection.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerSelectionStore.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerStateJson.cs create mode 100644 src/RynthCore.StatusAgent/ServeGuard.cs create mode 100644 tools/SectionsTests/Program.cs create mode 100644 tools/SectionsTests/SectionsTests.csproj diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index 90a463d..4c37329 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -149,6 +149,19 @@ foreach ($name in $suitePlugins) { Copy-Item "$rel\build\$name\RynthCore.Plugin.$name.dll" "$rel\plugins\" } +# Server plugins (Plugins\Shared\ServerPack; SilentKelpie's): one per game server, each loaded by the +# engine only for its own server. They go in the feed only, so the launcher offers each one under +# Available plugins for the player to install; not in RynthSuite-Plugins.zip or the installer. +$serverPlugins = "RynthAChard", "RynthAelrynth", "RynthColdeve", "RynthConquest", "RynthDerptide", "RynthDreamWeave", "RynthEversong", + "RynthFrostACE", "RynthFrostcull", "RynthLeafDawn", "RynthLeafdawning", "RynthPortalStorm", "RynthReefcull", "RynthSundering", "RynthThistlecrown" +foreach ($name in $serverPlugins) { + Step "Building $name (server plugin, feed only)" + $proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj" + dotnet publish $proj -c Release "-p:Version=$Version" "-p:PublishDir=$rel\build\$name\" -v q -nologo + if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed for $name" } + Copy-Item "$rel\build\$name\RynthCore.Plugin.$name.dll" "$rel\plugins\" +} + Step "Packing RynthSuite-Plugins.zip" $zipRoot = "$rel\build\zip" foreach ($name in $suitePlugins) { @@ -338,9 +351,11 @@ $plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Nam size = $dll.Length sha256 = Sha256 $dll.FullName } - if ($pluginDescriptions[$pluginName]) { $entry.description = $pluginDescriptions[$pluginName] } - else { Write-Warning "No description for $pluginName - the launcher shows its own (or none). Add one to `$pluginDescriptions." } $pm = Get-RynthPluginManifest $dll.FullName + # The table first; a server plugin's own manifest description otherwise (its csproj's RynthPluginDescription). + if ($pluginDescriptions[$pluginName]) { $entry.description = $pluginDescriptions[$pluginName] } + elseif ($pm -and $pm.description) { $entry.description = [string]$pm.description } + else { Write-Warning "No description for $pluginName - the launcher shows its own (or none). Add one to `$pluginDescriptions." } if ($pm) { if ($pm.name -ne $pluginName) { throw "$($dll.Name): its manifest says '$($pm.name)', the feed would say '$pluginName'." } if ($pm.version -and $pm.version -ne $Version) { throw "$($dll.Name): its manifest is version $($pm.version), not $Version (stale build?)." } diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml index f81b037..90798db 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml @@ -2,7 +2,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="RynthCore.App.Avalonia.AccountProfileDialog" Width="600" - Height="620" + Height="720" CanResize="False" WindowStartupLocation="CenterOwner" Title="Account Profile" @@ -24,6 +24,9 @@ <TextBlock x:Name="PasswordHintText" Foreground="#9AA8B3" TextWrapping="Wrap" /> + <TextBlock Text="Log in as" Foreground="#EAF0F4" /> + <ComboBox x:Name="LoginAsBox" HorizontalAlignment="Stretch" /> + <TextBlock x:Name="LoginAsHintText" Foreground="#9AA8B3" TextWrapping="Wrap" /> <TextBlock Text="Alias" Foreground="#EAF0F4" /> <TextBox x:Name="AliasBox" /> diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs index 8ec66c6..3a99a11 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs @@ -12,11 +12,21 @@ internal partial class AccountProfileDialog : Window { private readonly LaunchAccountProfile _profile; private readonly List<LaunchServerProfile> _servers; + private readonly Func<string, string, List<string>> _knownCharactersFor; - public AccountProfileDialog(LaunchAccountProfile profile, List<LaunchServerProfile> servers) + private List<string> _knownCharacters = []; + // Set once the player picks in "Log in as"; until then the saved choice is kept as it is + // (an empty one means "the only character, else character select"). + private bool _loginAsChanged; + private bool _loadingLoginAs; + + /// <param name="knownCharactersFor">(account name, server name) -> the characters known for it.</param> + public AccountProfileDialog(LaunchAccountProfile profile, List<LaunchServerProfile> servers, + Func<string, string, List<string>> knownCharactersFor) { _profile = profile; _servers = servers; + _knownCharactersFor = knownCharactersFor; InitializeComponent(); ServerComboBox.ItemsSource = _servers.Select(s => s.DisplayName).ToList(); @@ -30,15 +40,52 @@ internal partial class AccountProfileDialog : Window 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." + ? "No password is saved for this profile yet. The game client won't start without one; you'll be asked for it on the first launch." : "A password is saved for this profile, encrypted for this Windows user. It stays hidden unless you replace or clear it."; + ServerComboBox.SelectionChanged += (_, _) => RefreshLoginAs(); + AccountBox.TextChanged += (_, _) => RefreshLoginAs(); + LoginAsBox.SelectionChanged += (_, _) => + { + if (!_loadingLoginAs) + _loginAsChanged = true; + }; + RefreshLoginAs(); + SaveButton.Click += (_, _) => SaveAndClose(); CancelButton.Click += (_, _) => Close(false); BrowseUserPrefsButton.Click += async (_, _) => await BrowseUserPrefsAsync(); SnapshotUserPrefsButton.Click += (_, _) => SnapshotLiveUserPrefs(); } + /// <summary>Lists the characters known for the account on the chosen server in "Log in as".</summary> + private void RefreshLoginAs() + { + string accountName = AccountBox.Text?.Trim() ?? string.Empty; + string serverName = ServerComboBox.SelectedIndex >= 0 ? _servers[ServerComboBox.SelectedIndex].Name : string.Empty; + _knownCharacters = accountName.Length > 0 ? _knownCharactersFor(accountName, serverName) : []; + + string? current = _loginAsChanged ? LoginAsBox.SelectedItem as string : null; + List<string> choices = FirstLoginRules.LoginChoices(_knownCharacters, _profile.CharacterName); + + _loadingLoginAs = true; + try + { + LoginAsBox.ItemsSource = choices; + LoginAsBox.SelectedItem = current != null && choices.Contains(current) ? current + : choices.Contains(_profile.CharacterName) ? _profile.CharacterName + : FirstLoginRules.StopAtCharacterSelect; + } + finally + { + _loadingLoginAs = false; + } + + LoginAsHintText.Text = _knownCharacters.Count == 0 + ? "No characters are known for this account on this server yet. Launch it: the client stops at character select, where you can create characters, and RynthCore picks them up there." + : $"{_knownCharacters.Count} character(s) on this account. Pick the one that logs in automatically, or stop at character select. The launch list's dropdown changes this too."; + } + private async System.Threading.Tasks.Task BrowseUserPrefsAsync() { var topLevel = GetTopLevel(this); @@ -112,10 +159,24 @@ internal partial class AccountProfileDialog : Window return; } - if (ServerComboBox.SelectedIndex >= 0) - _profile.ServerId = _servers[ServerComboBox.SelectedIndex].Id; + LaunchServerProfile? server = ServerComboBox.SelectedIndex >= 0 ? _servers[ServerComboBox.SelectedIndex] : null; + if (server == null && _servers.Count > 0) + { + ValidationText.Text = "Pick the server this account is for."; + return; + } + if (AcLaunchArgumentBuilder.AccountNameProblem(AccountBox.Text, server?.Emulator ?? AcEmulatorKind.Ace) is string nameProblem) + { + ValidationText.Text = nameProblem; + return; + } + + if (server != null) + _profile.ServerId = server.Id; _profile.AccountName = AccountBox.Text.Trim(); + if (_loginAsChanged) + _profile.CharacterName = FirstLoginRules.CharacterNameFor(LoginAsBox.SelectedItem as string, _knownCharacters); if (ClearPasswordCheckBox.IsChecked == true) { _profile.ClearPassword(); diff --git a/src/RynthCore.App.Avalonia/FirstLoginDialog.axaml b/src/RynthCore.App.Avalonia/FirstLoginDialog.axaml new file mode 100644 index 0000000..7ae22cf --- /dev/null +++ b/src/RynthCore.App.Avalonia/FirstLoginDialog.axaml @@ -0,0 +1,44 @@ +<Window xmlns="https://github.com/avaloniaui" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + x:Class="RynthCore.App.Avalonia.FirstLoginDialog" + Width="560" + SizeToContent="Height" + CanResize="False" + WindowStartupLocation="CenterOwner" + Title="First Login" + Background="#132028"> + <Grid RowDefinitions="*,Auto" Margin="18"> + <StackPanel Spacing="10"> + <TextBlock x:Name="HeaderText" Foreground="#EAF0F4" FontSize="16" FontWeight="SemiBold" TextWrapping="Wrap" /> + <TextBlock x:Name="IntroText" Foreground="#9AA8B3" TextWrapping="Wrap" /> + + <TextBlock Text="Use an account you already have (optional)" Foreground="#EAF0F4" /> + <ComboBox x:Name="KnownAccountBox" HorizontalAlignment="Stretch" PlaceholderText="Pick an account name, or type a new one below" /> + + <TextBlock Text="Account" Foreground="#EAF0F4" /> + <TextBox x:Name="AccountBox" Watermark="A new name creates the account on this server's first login (ACE)" /> + + <CheckBox x:Name="ReuseSavedPasswordCheckBox" Foreground="#EAF0F4" IsVisible="False" /> + + <StackPanel x:Name="PasswordPanel" Spacing="10"> + <TextBlock Text="Password" Foreground="#EAF0F4" /> + <TextBox x:Name="PasswordBox" PasswordChar="*" RevealPassword="False" /> + <TextBlock Text="Confirm password" Foreground="#EAF0F4" /> + <TextBox x:Name="ConfirmBox" PasswordChar="*" RevealPassword="False" /> + </StackPanel> + <TextBlock Text="The password is saved encrypted for this Windows user, like the other accounts." + Foreground="#9AA8B3" TextWrapping="Wrap" /> + + <TextBlock Text="Log in as" Foreground="#EAF0F4" /> + <ComboBox x:Name="LoginAsBox" HorizontalAlignment="Stretch" /> + <TextBlock x:Name="LoginAsHintText" Foreground="#9AA8B3" TextWrapping="Wrap" /> + + <TextBlock x:Name="ValidationText" Foreground="#E2B348" TextWrapping="Wrap" /> + </StackPanel> + + <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,16,0,0"> + <Button x:Name="CancelButton" Content="Cancel" /> + <Button x:Name="LoginButton" Content="Log In" /> + </StackPanel> + </Grid> +</Window> diff --git a/src/RynthCore.App.Avalonia/FirstLoginDialog.axaml.cs b/src/RynthCore.App.Avalonia/FirstLoginDialog.axaml.cs new file mode 100644 index 0000000..121028b --- /dev/null +++ b/src/RynthCore.App.Avalonia/FirstLoginDialog.axaml.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using Avalonia.Controls; +using RynthCore.App; + +namespace RynthCore.App.Avalonia; + +/// <summary> +/// Asked before launching an account that has no usable password (a new server, or a profile added +/// without one): the account name (one you already use, or a new one), its password, and which +/// character logs in. Edits the profile passed in only when the player presses Log In. +/// </summary> +internal partial class FirstLoginDialog : Window +{ + private readonly LaunchAccountProfile _profile; + private readonly LaunchServerProfile _server; + private readonly IReadOnlyList<LaunchAccountProfile> _allProfiles; + private readonly Func<string, List<string>> _knownCharactersFor; + + private List<string> _knownCharacters = []; + private LaunchAccountProfile? _passwordSource; + + public FirstLoginDialog( + LaunchAccountProfile profile, + LaunchServerProfile server, + IReadOnlyList<LaunchAccountProfile> allProfiles, + Func<string, List<string>> knownCharactersFor) + { + _profile = profile; + _server = server; + _allProfiles = allProfiles; + _knownCharactersFor = knownCharactersFor; + InitializeComponent(); + + string serverLabel = server.DisplayName; + HeaderText.Text = $"First login on {serverLabel}"; + IntroText.Text = profile.PasswordNeedsReentry + ? "The saved password for this account can't be read on this Windows user (settings copied from another user or PC?). Enter it again to log in." + : "No password is saved for this account yet, and the game client won't start without one. " + + "ACE servers create a new account the first time it logs in (if the server allows it). " + + "With no character picked, the client stops at character select, where you can create characters. " + + "Every character on the account is remembered, and you pick which one logs in from the launch list."; + + KnownAccountBox.ItemsSource = FirstLoginRules.KnownAccountNames(allProfiles, profile.Id); + KnownAccountBox.IsEnabled = KnownAccountBox.ItemCount > 0; + KnownAccountBox.SelectionChanged += (_, _) => + { + if (KnownAccountBox.SelectedItem is string picked) + AccountBox.Text = picked; + }; + + AccountBox.Text = profile.AccountName; + AccountBox.TextChanged += (_, _) => OnAccountChanged(); + ReuseSavedPasswordCheckBox.IsCheckedChanged += (_, _) => UpdatePasswordPanel(); + + LoginButton.Click += (_, _) => LogInAndClose(); + CancelButton.Click += (_, _) => Close(false); + + OnAccountChanged(); + } + + /// <summary>Re-reads the account's characters and whether another profile's password can be reused.</summary> + private void OnAccountChanged() + { + string name = AccountBox.Text?.Trim() ?? string.Empty; + + _passwordSource = FirstLoginRules.SavedPasswordSource(_allProfiles, name, _profile.Id); + if (_passwordSource != null) + { + string from = _passwordSource.DisplayName; + ReuseSavedPasswordCheckBox.Content = $"Use the password saved for '{name}' in profile {from}"; + ReuseSavedPasswordCheckBox.IsVisible = true; + } + else + { + ReuseSavedPasswordCheckBox.IsVisible = false; + ReuseSavedPasswordCheckBox.IsChecked = false; + } + UpdatePasswordPanel(); + + _knownCharacters = name.Length > 0 ? _knownCharactersFor(name) : []; + string? keep = LoginAsBox.SelectedItem as string; + List<string> choices = FirstLoginRules.LoginChoices(_knownCharacters, _profile.CharacterName); + LoginAsBox.ItemsSource = choices; + LoginAsBox.SelectedItem = keep != null && choices.Contains(keep) ? keep + : choices.Contains(_profile.CharacterName) ? _profile.CharacterName + : FirstLoginRules.StopAtCharacterSelect; + LoginAsHintText.Text = _knownCharacters.Count == 0 + ? $"No characters are known for this account on {_server.DisplayName} yet. Create them at character select; RynthCore picks them up there." + : $"{_knownCharacters.Count} character(s) known for this account. Pick one to log in automatically, or stop at character select."; + } + + private void UpdatePasswordPanel() + { + bool reuse = ReuseSavedPasswordCheckBox.IsVisible && ReuseSavedPasswordCheckBox.IsChecked == true; + PasswordPanel.IsVisible = !reuse; + } + + private void LogInAndClose() + { + bool reuse = _passwordSource != null && ReuseSavedPasswordCheckBox.IsChecked == true; + string name = AccountBox.Text?.Trim() ?? string.Empty; + + if (FirstLoginRules.Problem(name, PasswordBox.Text, ConfirmBox.Text, reuse, _server.Emulator) is string problem) + { + ValidationText.Text = problem; + return; + } + + _profile.AccountName = name; + _profile.ServerId = _server.Id; + if (reuse) + _profile.CopyPasswordFrom(_passwordSource!); + else + _profile.SetPassword(PasswordBox.Text); // encrypted at once; the plain text isn't kept + PasswordBox.Text = string.Empty; + ConfirmBox.Text = string.Empty; + + _profile.CharacterName = FirstLoginRules.CharacterNameFor(LoginAsBox.SelectedItem as string, _knownCharacters); + Close(true); + } +} diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index 7e30fd5..94f3b75 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -33,6 +33,7 @@ internal partial class MainWindow : Window // handle most of the work; this cooldown is a final belt-and-braces. private static readonly TimeSpan AutoLaunchCooldown = TimeSpan.FromSeconds(2); private static readonly TimeSpan AutoLaunchServerDownLogCooldown = TimeSpan.FromSeconds(30); + private static readonly TimeSpan AutoLaunchNeedsPasswordLogCooldown = TimeSpan.FromMinutes(5); // Auto-inject only after the external AC client has been continuously // graphics-ready for this long. The window gives Decal/UBLoader time to @@ -90,6 +91,11 @@ internal partial class MainWindow : Window // After CreateProcess+inject+resume, hold the prefs lock this long so AC // has a chance to read UserPreferences.ini before another account swaps. private static readonly TimeSpan UserPrefsSettleDelay = TimeSpan.FromSeconds(2); + // The UserPreferences.ini swap each launched PID started with, so a quick exit can set the + // saved copy aside and put the previous live file back (UserPrefsSwapRecovery). + private readonly Dictionary<int, PrefsSwapLaunch> _prefsSwapByPid = []; + // Counts swaps; a quick exit only restores the live file when no later swap replaced it. + private long _prefsSwapGeneration; private readonly Dictionary<int, DateTime> _autoInjectFirstReadyAtUtc = []; private readonly HashSet<int> _autoInjectAttemptedPids = []; private readonly HashSet<int> _autoInjectInFlightPids = []; @@ -99,6 +105,7 @@ internal partial class MainWindow : Window private readonly Dictionary<string, ComboBox> _launchTargetInjectionDropdowns = []; private readonly Dictionary<string, DateTime> _autoLaunchAttemptTimesUtc = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, DateTime> _autoLaunchServerDownNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary<string, DateTime> _autoLaunchNeedsPasswordNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, ServerAvailabilityState> _serverStatuses = new(StringComparer.OrdinalIgnoreCase); private readonly List<PluginDefinition> _plugins = [ @@ -727,8 +734,10 @@ internal partial class MainWindow : Window private async System.Threading.Tasks.Task AddAccountAsync() { - var draft = new RynthCore.App.LaunchAccountProfile(); - var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles); + // Defaults to the server selected in the list (a new server's first account), not the + // first profile, which RefreshLaunchTargets would otherwise assign. + var draft = new RynthCore.App.LaunchAccountProfile { ServerId = GetSelectedServer()?.Id ?? string.Empty }; + var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles, GetDetectedCharacters); bool? accepted = await dialog.ShowDialog<bool?>(this); if (accepted != true) return; @@ -749,7 +758,7 @@ internal partial class MainWindow : Window return; LaunchAccountProfile draft = selected.Clone(); - var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles); + var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles, GetDetectedCharacters); bool? accepted = await dialog.ShowDialog<bool?>(this); if (accepted != true) return; @@ -1637,6 +1646,29 @@ internal partial class MainWindow : Window } } + // No usable password: the client would refuse to start ("You can only run the game from + // the launcher program") and exit within seconds. A manual launch asks for it (and the + // account) in the First Login dialog; an automatic one skips the account. + if (string.IsNullOrWhiteSpace(overrideArguments)) + { + var ready = new List<LaunchAccountProfile>(accountsToLaunch.Count); + foreach (LaunchAccountProfile account in accountsToLaunch) + { + if (!AcLaunchArgumentBuilder.NeedsPassword(account)) + ready.Add(account); + else if (isAutomaticLaunch) + AppendActivity($"Auto launch skipped for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}"); + else if (await PromptFirstLoginAsync(account)) + ready.Add(account); + else + AppendActivity($"Launch cancelled for {account.DisplayName}: no password entered."); + } + + if (ready.Count == 0) + return; + accountsToLaunch = ready; + } + SaveRuntimePaths(appendActivity: !isAutomaticLaunch); SaveLaunchBehavior(appendActivity: !isAutomaticLaunch); @@ -1784,10 +1816,7 @@ internal partial class MainWindow : Window try { - if (needsPrefsSwap) - { - _launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity); - } + PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath) : null; InjectionResult result = await Task.Run(() => _injector.LaunchSuspendedAndInject( @@ -1811,6 +1840,7 @@ internal partial class MainWindow : Window { _launchedSessionPids.Add(trackedPid); _launchedPidInfo[trackedPid] = (accountKey, DateTime.UtcNow); + TrackPrefsSwap(trackedPid, prefsSwap); RegisterPidExitWatch(trackedPid); } @@ -1864,10 +1894,7 @@ internal partial class MainWindow : Window try { - if (needsPrefsSwap) - { - _launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity); - } + PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath) : null; // enginePath != null: "Decal + RynthCore" - Decal is injected first, then the // RynthCore loader, before the client resumes. @@ -1894,6 +1921,7 @@ internal partial class MainWindow : Window { _launchedSessionPids.Add(trackedPid); _launchedPidInfo[trackedPid] = (accountKey, DateTime.UtcNow); + TrackPrefsSwap(trackedPid, prefsSwap); RegisterPidExitWatch(trackedPid); } @@ -1943,10 +1971,7 @@ internal partial class MainWindow : Window try { - if (needsPrefsSwap) - { - _launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity); - } + PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath) : null; Process? proc = null; Exception? launchEx = null; @@ -1978,6 +2003,7 @@ internal partial class MainWindow : Window { _launchedSessionPids.Add(proc.Id); _launchedPidInfo[proc.Id] = (BuildAccountKey(launchContext.AccountName, launchContext.ServerName), DateTime.UtcNow); + TrackPrefsSwap(proc.Id, prefsSwap); RegisterPidExitWatch(proc.Id); LaunchContextStore.WriteForProcess(proc.Id, launchContext); WritePendingSessionState(proc.Id, launchContext); @@ -2004,6 +2030,38 @@ internal partial class MainWindow : Window } } + /// <summary> + /// Shows the First Login dialog for <paramref name="account"/> (no usable password). True when + /// the player entered one: the profile is updated and saved (password encrypted at once). + /// </summary> + private async Task<bool> PromptFirstLoginAsync(LaunchAccountProfile account) + { + LaunchServerProfile? server = ResolveServerForAccount(account); + if (server == null) + { + AppendActivity($"Launch blocked for {account.DisplayName}: add a server profile first."); + return false; + } + + LaunchAccountProfile draft = account.Clone(); + var dialog = new FirstLoginDialog(draft, server, _settings.AccountProfiles, + accountName => GetDetectedCharacters(accountName, server.Name)); + bool? accepted = await dialog.ShowDialog<bool?>(this); + if (accepted != true) + return false; + + account.CopyFrom(draft); + SaveSettings(); + RefreshLists(); + RefreshSummary(); + + string loginAs = string.IsNullOrWhiteSpace(account.CharacterName) || account.CharacterName == LaunchAccountProfile.NoneOption + ? "stopping at character select" + : $"logging in as {account.CharacterName}"; + AppendActivity($"First login on {server.DisplayName}: account '{account.AccountName}', password saved (encrypted), {loginAs}."); + return true; + } + private LaunchContextRecord BuildLaunchContext(LaunchAccountProfile account, LaunchServerProfile? server) { string targetCharacter = ResolveTargetCharacterForLaunch(account, server); @@ -3951,6 +4009,7 @@ internal partial class MainWindow : Window AppendActivity($"Account '{entry.Value.AccountKey}' client (PID {entry.Key}) exited after {uptime.TotalSeconds:F0}s — counted as crash."); int hist = _crashHistoryByAccount.TryGetValue(entry.Value.AccountKey, out List<DateTime>? h) ? h.Count : 0; LauncherDiag.Info($"DetectQuickExits: PID {entry.Key} ({entry.Value.AccountKey}) uptime={uptime.TotalSeconds:F1}s -> RecordCrash. crashHist now {hist}."); + RecoverFailedPrefsSwap(entry.Key, entry.Value.AccountKey, uptime); } else if (!string.IsNullOrEmpty(entry.Value.AccountKey)) { @@ -3967,6 +4026,7 @@ internal partial class MainWindow : Window foreach (int pid in toRemove) { _launchedPidInfo.Remove(pid); + _prefsSwapByPid.Remove(pid); // Drop the exit-watcher Process handle so the OS can reclaim // the kernel object. Exited already fired (or never will), // so we no longer need to hold the handle alive. @@ -4307,17 +4367,14 @@ internal partial class MainWindow : Window if (!string.IsNullOrWhiteSpace(account.UserPrefsPath)) return account.UserPrefsPath.Trim(); - if (string.IsNullOrWhiteSpace(account.AccountName)) + string legacyPath = ResolveLegacyUserPrefsPath(account); + if (string.IsNullOrEmpty(legacyPath)) return string.Empty; - - string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - string prefsDir = Path.Combine(appdata, "RynthCore", "prefs"); - string safeName = SafePrefsFileName(account.AccountName); - string legacyPath = Path.Combine(prefsDir, $"{safeName}.ini"); if (string.IsNullOrWhiteSpace(serverName)) return legacyPath; - string scopedPath = Path.Combine(prefsDir, $"{safeName}@{SafePrefsFileName(serverName)}.ini"); + string prefsDir = Path.GetDirectoryName(legacyPath)!; + string scopedPath = Path.Combine(prefsDir, $"{SafePrefsFileName(account.AccountName)}@{SafePrefsFileName(serverName)}.ini"); if (!File.Exists(scopedPath) && File.Exists(legacyPath)) { try { File.Copy(legacyPath, scopedPath, overwrite: false); } @@ -4327,9 +4384,98 @@ internal partial class MainWindow : Window return scopedPath; } + /// <summary> + /// The account's old name-only stash (%APPDATA%\RynthCore\prefs\name.ini), which seeds a + /// missing per-server one. Empty when the account has no name yet. + /// </summary> + private static string ResolveLegacyUserPrefsPath(LaunchAccountProfile account) + { + if (string.IsNullOrWhiteSpace(account.AccountName)) + return string.Empty; + + string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + return Path.Combine(appdata, "RynthCore", "prefs", $"{SafePrefsFileName(account.AccountName)}.ini"); + } + private static string SafePrefsFileName(string name) => string.Join("_", name.Trim().Split(Path.GetInvalidFileNameChars())); + /// <summary> + /// A launch's UserPreferences.ini swap. <see cref="IsProfileOverride"/>: the stash is a file the + /// user picked on the profile (never renamed by the launcher). <see cref="LegacyPath"/>: the + /// account's name-only stash, set aside with a failed per-server one when identical. + /// </summary> + private sealed record PrefsSwapLaunch(UserPrefsSwap Swap, long Generation, bool IsProfileOverride, string LegacyPath); + + /// <summary> + /// Copies the account's saved UserPreferences.ini over the live one (caller holds + /// _userPrefsSwapLock) and returns what was swapped, or null when nothing was. + /// </summary> + private PrefsSwapLaunch? ApplyPrefsSwap(LaunchAccountProfile account, string? serverName, string resolvedPrefsPath) + { + UserPrefsSwap? swap = _launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity); + if (swap == null) + return null; + + long generation = ++_prefsSwapGeneration; + bool isOverride = !string.IsNullOrWhiteSpace(account.UserPrefsPath); + LauncherDiag.Info($"PrefsSwap: account='{account.AccountName}' server='{serverName}' gen={generation} override={isOverride} changedLive={UserPrefsSwapRecovery.SwapChangedPrefs(swap)} stash='{swap.StashPath}'"); + return new PrefsSwapLaunch(swap, generation, isOverride, ResolveLegacyUserPrefsPath(account)); + } + + /// <summary>Remembers which swap a launched client started with (no-op without a swap).</summary> + private void TrackPrefsSwap(int pid, PrefsSwapLaunch? prefsSwap) + { + if (prefsSwap != null) + _prefsSwapByPid[pid] = prefsSwap; + } + + /// <summary> + /// A client quit within CrashQuickExitWindow. If it started with a saved UserPreferences.ini + /// that differs from the live one, that saved copy is the likely cause (the game reads its + /// display mode from it: "Could not initialize Direct3D"), and it would be swapped in again on + /// every launch because it is only refreshed after a normal session. So: set the saved copy + /// aside (renamed, kept), and put the previous live file back when no later launch replaced it. + /// The next normal session saves a fresh copy. + /// </summary> + private void RecoverFailedPrefsSwap(int pid, string accountKey, TimeSpan uptime) + { + if (!_prefsSwapByPid.Remove(pid, out PrefsSwapLaunch? launch)) + return; + + if (!UserPrefsSwapRecovery.SwapChangedPrefs(launch.Swap)) + { + LauncherDiag.Info($"PrefsSwap: PID {pid} ({accountKey}) quick exit, but its stash matched the live file; left alone."); + return; + } + + bool restoreLive = launch.Generation == _prefsSwapGeneration; + try + { + UserPrefsRecoveryResult result = UserPrefsSwapRecovery.Recover( + launch.Swap, + quarantineStash: !launch.IsProfileOverride, + restoreLive, + launch.LegacyPath, + DateTime.Now); + + LauncherDiag.Info($"PrefsSwap: PID {pid} ({accountKey}) recovery: quarantined='{result.QuarantinedStashPath}' legacy='{result.QuarantinedLegacyPath}' liveRestored={result.LiveRestored}."); + + string stashName = Path.GetFileName(launch.Swap.StashPath); + string what = launch.IsProfileOverride + ? $"the UserPreferences file set on its profile ({launch.Swap.StashPath}). Fix or clear that file in the account's settings if launches keep failing" + : $"this account's saved game settings ({stashName}). They were set aside as {Path.GetFileName(result.QuarantinedStashPath ?? stashName)}, so the next launch uses the current UserPreferences.ini"; + string live = result.LiveRestored + ? " The previous UserPreferences.ini was put back." + : " UserPreferences.ini was left as is (another launch has swapped it since)."; + AppendActivity($"Account '{accountKey}' client (PID {pid}) quit after {uptime.TotalSeconds:F0}s using {what}.{live}"); + } + catch (Exception ex) + { + AppendActivity($"Account '{accountKey}': could not undo the UserPreferences.ini swap after a quick exit: {ex.Message}"); + } + } + /// <summary> /// Copies the current live UserPreferences.ini to the resolved stash for /// the named account. Called on tracked-client exit so per-account prefs @@ -4442,6 +4588,13 @@ internal partial class MainWindow : Window continue; } + // Needs the First Login dialog, which only a manual launch shows. + if (AcLaunchArgumentBuilder.NeedsPassword(account)) + { + MaybeLogAutoLaunchNeedsPassword(account, nowUtc); + continue; + } + if (_autoLaunchAttemptTimesUtc.TryGetValue(account.Id, out DateTime lastAttemptUtc) && nowUtc - lastAttemptUtc < AutoLaunchCooldown) { @@ -4494,6 +4647,18 @@ internal partial class MainWindow : Window AppendActivity($"Auto launch waiting for {account.DisplayName}: {(server?.DisplayName ?? "the selected server")} is reporting down."); } + private void MaybeLogAutoLaunchNeedsPassword(LaunchAccountProfile account, DateTime nowUtc) + { + if (_autoLaunchNeedsPasswordNoticeTimesUtc.TryGetValue(account.Id, out DateTime lastNoticeUtc) && + nowUtc - lastNoticeUtc < AutoLaunchNeedsPasswordLogCooldown) + { + return; + } + + _autoLaunchNeedsPasswordNoticeTimesUtc[account.Id] = nowUtc; + AppendActivity($"Auto launch waiting for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}"); + } + private bool IsServerKnownDown(LaunchServerProfile? server) { if (server == null) @@ -4571,7 +4736,7 @@ internal partial class MainWindow : Window string character = !string.IsNullOrWhiteSpace(session.CharacterName) ? session.CharacterName : !string.IsNullOrWhiteSpace(session.TargetCharacter) ? session.TargetCharacter - : !string.IsNullOrWhiteSpace(account.CharacterName) ? account.CharacterName + : !string.IsNullOrWhiteSpace(account.CharacterName) && account.CharacterName != LaunchAccountProfile.NoneOption ? account.CharacterName : "Logged in"; string elapsed = FormatElapsed(DateTime.UtcNow - (session.LoginCompletedAtUtc ?? session.LaunchStartedAtUtc)); return ($"{character} | online {elapsed}", "#66D687"); @@ -4585,12 +4750,16 @@ internal partial class MainWindow : Window Process? process = targets.FirstOrDefault(p => p.Id == pid); DateTime since = process != null ? GetProcessStartTimeUtc(process) : context.CreatedAtUtc.ToUniversalTime(); string character = !string.IsNullOrWhiteSpace(context.TargetCharacter) ? context.TargetCharacter - : !string.IsNullOrWhiteSpace(account.CharacterName) ? account.CharacterName - : "Pending"; + : !string.IsNullOrWhiteSpace(account.CharacterName) && account.CharacterName != LaunchAccountProfile.NoneOption ? account.CharacterName + : "Character select"; string elapsed = FormatElapsed(DateTime.UtcNow - since); return ($"{character} | starting {elapsed}", "#E2B348"); } + if (AcLaunchArgumentBuilder.NeedsPassword(account)) + return ("Needs password | launch to set up", "#E2B348"); + if (account.CharacterName == LaunchAccountProfile.NoneOption) + return ("Character select | offline", "#73828D"); return (!string.IsNullOrWhiteSpace(account.CharacterName) ? $"{account.CharacterName} | offline" : "Offline", "#73828D"); } diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index 348493a..0e3d036 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -1,12 +1,12 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.4. + <!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.5. No hard-coded InformationalVersion: release builds pass -p:Version=yyyy.m.d.n, and the product version derived from it is what the launcher/About show (BuildVersion.Format). --> - <Version>0.1.5</Version> - <AssemblyVersion>0.1.5.0</AssemblyVersion> - <FileVersion>0.1.5.0</FileVersion> + <Version>0.1.6</Version> + <AssemblyVersion>0.1.6.0</AssemblyVersion> + <FileVersion>0.1.6.0</FileVersion> <OutputType>WinExe</OutputType> <TargetFramework>net10.0-windows7.0</TargetFramework> <PlatformTarget>x86</PlatformTarget> @@ -52,7 +52,9 @@ <Compile Include="..\RynthCore.App\DecalBridgeCheck.cs" Link="Shared\DecalBridgeCheck.cs" /> <Compile Include="..\RynthCore.App\RealDecalCheckHost.cs" Link="Shared\RealDecalCheckHost.cs" /> <Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" /> + <Compile Include="..\RynthCore.App\FirstLoginRules.cs" Link="Shared\FirstLoginRules.cs" /> <Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" /> + <Compile Include="..\RynthCore.App\UserPrefsSwapRecovery.cs" Link="Shared\UserPrefsSwapRecovery.cs" /> <Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" /> <Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Shared\CharacterCacheStore.cs" /> <Compile Include="..\RynthCore.App\LaunchContextStore.cs" Link="Shared\LaunchContextStore.cs" /> diff --git a/src/RynthCore.App/AcClientLaunchSettingsService.cs b/src/RynthCore.App/AcClientLaunchSettingsService.cs index 7bafa0c..77720c4 100644 --- a/src/RynthCore.App/AcClientLaunchSettingsService.cs +++ b/src/RynthCore.App/AcClientLaunchSettingsService.cs @@ -28,38 +28,45 @@ internal sealed class AcClientLaunchSettingsService /// My Documents\Asheron's Call, then re-applies the ComputeUniquePort flag. /// If <paramref name="stashPath"/> is empty or missing, no swap is performed /// and the live file is left as-is. + /// Returns what was swapped (null when nothing was), so a client that quits at + /// startup can be traced back to the stash and the swap undone + /// (<see cref="UserPrefsSwapRecovery"/>). /// </summary> - public bool SwapUserPreferences(string? stashPath, bool allowMultipleClients, Action<string>? log = null) + public UserPrefsSwap? SwapUserPreferences(string? stashPath, bool allowMultipleClients, Action<string>? log = null) { if (string.IsNullOrWhiteSpace(stashPath)) - return false; + return null; if (!File.Exists(stashPath)) { log?.Invoke($"User prefs swap skipped: stash file not found at {stashPath}."); - return false; + return null; } string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string prefsDirectory = Path.Combine(documentsDirectory, "Asheron's Call"); string prefsPath = Path.Combine(prefsDirectory, UserPreferencesFileName); + byte[] stashBytes; + byte[]? previousLiveBytes; try { Directory.CreateDirectory(prefsDirectory); + stashBytes = File.ReadAllBytes(stashPath); + previousLiveBytes = File.Exists(prefsPath) ? File.ReadAllBytes(prefsPath) : null; File.Copy(stashPath, prefsPath, overwrite: true); } catch (Exception ex) { log?.Invoke($"User prefs swap failed copying {stashPath}: {ex.Message}"); - return false; + return null; } // Re-apply the ComputeUniquePort flag — the stash may have it set to // the wrong value (e.g. user set it up before enabling multi-client). UpdateUserPreferences(allowMultipleClients, log: null); log?.Invoke($"User prefs swap: applied stash {Path.GetFileName(stashPath)}."); - return true; + return new UserPrefsSwap(stashPath, prefsPath, stashBytes, previousLiveBytes); } private static void UpdateUserPreferences(bool allowMultipleClients, Action<string>? log) diff --git a/src/RynthCore.App/AcLaunchArgumentBuilder.cs b/src/RynthCore.App/AcLaunchArgumentBuilder.cs index 871a2e8..b07968b 100644 --- a/src/RynthCore.App/AcLaunchArgumentBuilder.cs +++ b/src/RynthCore.App/AcLaunchArgumentBuilder.cs @@ -9,10 +9,28 @@ internal sealed class AcLaunchArgumentBuilder /// <summary>Text shown in place of the password in previews.</summary> public const string PasswordMask = "********"; + /// <summary> + /// True when <paramref name="account"/> can't be launched until a password is entered: none + /// is saved, or the saved one can't be decrypted on this Windows user. Every supported + /// emulator logs on with a password, and the client refuses an empty one before it connects + /// ("You can only run the game from the launcher program"). + /// </summary> + public static bool NeedsPassword(LaunchAccountProfile account) + { + ArgumentNullException.ThrowIfNull(account); + return account.PasswordNeedsReentry || !account.HasSavedPassword; + } + + /// <summary>Why an account without a password can't be launched (no secrets in it).</summary> + public static string MissingPasswordMessage(string? accountName) => + $"No password is saved for account '{accountName}'. The AC client won't start without one " + + "(\"You can only run the game from the launcher program\"). Launch it by hand to enter it, or edit the account."; + /// <summary> /// 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). + /// password: hand it to the process and never log, display or keep it. Throws when no password + /// is saved or the saved one can't be decrypted on this Windows user (never launches with an + /// empty one instead). /// </summary> public string BuildArguments(LaunchServerProfile server, LaunchAccountProfile account) { @@ -23,6 +41,8 @@ internal sealed class AcLaunchArgumentBuilder if (!account.TryGetPasswordForLaunch(out string password, out string problem)) throw new InvalidOperationException(problem); + if (password.Length == 0) + throw new InvalidOperationException(MissingPasswordMessage(account.AccountName)); return Build(server, account, password); } @@ -40,8 +60,10 @@ internal sealed class AcLaunchArgumentBuilder if (account.PasswordNeedsReentry) return LaunchAccountProfile.PasswordNeedsReentryMessage(account.AccountName); + if (!account.HasSavedPassword) + return MissingPasswordMessage(account.AccountName); - return Build(server, account, account.HasSavedPassword ? PasswordMask : string.Empty); + return Build(server, account, PasswordMask); } private static string Build(LaunchServerProfile server, LaunchAccountProfile account, string password) @@ -79,11 +101,33 @@ internal sealed class AcLaunchArgumentBuilder errors.Add("Server port must be greater than zero."); if (string.IsNullOrWhiteSpace(account.AccountName)) errors.Add("Account name is required."); + else if (AccountNameProblem(account.AccountName, server.Emulator) is string nameProblem) + errors.Add(nameProblem); if (errors.Count > 0) throw new InvalidOperationException(string.Join(" ", errors)); } + /// <summary>Longest account name ACE accepts (AuthenticationHandler rejects longer ones).</summary> + public const int MaxAccountNameLength = 50; + + /// <summary> + /// Why <paramref name="accountName"/> can't log on to a server of <paramref name="emulator"/> + /// (null = fine). GDLE takes "account:password" in one argument, so a colon in the name would + /// split it in the wrong place. + /// </summary> + public static string? AccountNameProblem(string? accountName, AcEmulatorKind emulator) + { + string name = accountName?.Trim() ?? string.Empty; + if (name.Length == 0) + return "Account name is required."; + if (name.Length > MaxAccountNameLength) + return $"Account name is longer than {MaxAccountNameLength} characters."; + if (emulator == AcEmulatorKind.Gdle && name.Contains(':')) + return "Account names can't contain ':' on GDLE servers."; + return null; + } + private static string Quote(string value) { value ??= string.Empty; diff --git a/src/RynthCore.App/FirstLoginRules.cs b/src/RynthCore.App/FirstLoginRules.cs new file mode 100644 index 0000000..6409d4d --- /dev/null +++ b/src/RynthCore.App/FirstLoginRules.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RynthCore.App; + +/// <summary> +/// The rules behind the launcher's "First login" dialog, shown when an account is launched with no +/// usable password (a new server, or a profile added without one). Pure: no UI, no files. +/// +/// The client refuses an empty password before it connects ("You can only run the game from the +/// launcher program"), so a password is always required. ACE creates an account the first time a +/// new name logs on with a password (AllowAutoAccountCreation), so a new name here is how an +/// account is created. With no character known yet the client stops at character select, where +/// characters are created; the engine saves the account's character list from there. +/// </summary> +internal static class FirstLoginRules +{ + /// <summary>The "Log in as" entry that stops at character select.</summary> + public const string StopAtCharacterSelect = "Stop at character select (create or pick a character there)"; + + /// <summary> + /// Account names from the other profiles, distinct (case-insensitive) and sorted, for picking + /// an account you already use elsewhere. + /// </summary> + internal static List<string> KnownAccountNames(IEnumerable<LaunchAccountProfile> profiles, string excludeProfileId) + { + return profiles + .Where(p => !string.Equals(p.Id, excludeProfileId, StringComparison.OrdinalIgnoreCase)) + .Select(p => p.AccountName?.Trim() ?? string.Empty) + .Where(n => n.Length > 0) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(n => n, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + /// <summary> + /// Another profile with the same account name and a password readable on this Windows user, + /// whose saved password can be reused (null = none). The same name on another server is a + /// different account, so the caller offers this as a choice, never silently. + /// </summary> + internal static LaunchAccountProfile? SavedPasswordSource( + IEnumerable<LaunchAccountProfile> profiles, string accountName, string excludeProfileId) + { + string name = accountName?.Trim() ?? string.Empty; + if (name.Length == 0) + return null; + + return profiles.FirstOrDefault(p => + !string.Equals(p.Id, excludeProfileId, StringComparison.OrdinalIgnoreCase) + && string.Equals(p.AccountName?.Trim(), name, StringComparison.OrdinalIgnoreCase) + && p.HasSavedPassword + && !p.PasswordNeedsReentry); + } + + /// <summary> + /// The "Log in as" choices: stop at character select, then the account's known characters + /// (the saved one first if the list hasn't seen it yet). + /// </summary> + internal static List<string> LoginChoices(IReadOnlyList<string> knownCharacters, string? savedCharacter) + { + var choices = new List<string> { StopAtCharacterSelect }; + if (!string.IsNullOrWhiteSpace(savedCharacter) + && savedCharacter != LaunchAccountProfile.NoneOption + && !knownCharacters.Contains(savedCharacter, StringComparer.OrdinalIgnoreCase)) + { + choices.Add(savedCharacter); + } + choices.AddRange(knownCharacters.Where(c => !string.IsNullOrWhiteSpace(c))); + return choices; + } + + /// <summary> + /// The CharacterName to save for <paramref name="choice"/>. Stopping at character select with + /// no character known yet saves "" rather than the explicit "(None)": once the first character + /// is created and it is the only one, the launcher picks it for the next launch. + /// </summary> + internal static string CharacterNameFor(string? choice, IReadOnlyList<string> knownCharacters) + { + if (string.IsNullOrWhiteSpace(choice) || choice == StopAtCharacterSelect) + return knownCharacters.Count == 0 ? string.Empty : LaunchAccountProfile.NoneOption; + return choice; + } + + /// <summary>What's wrong with the entries (null = ready to log in).</summary> + internal static string? Problem(string? accountName, string? password, string? confirm, bool reuseSavedPassword, AcEmulatorKind emulator) + { + if (AcLaunchArgumentBuilder.AccountNameProblem(accountName, emulator) is string nameProblem) + return nameProblem; + if (reuseSavedPassword) + return null; + if (string.IsNullOrEmpty(password)) + return "Enter the password. The client won't start without one; for a new account it becomes the account's password."; + if (!string.Equals(password, confirm, StringComparison.Ordinal)) + return "The two passwords don't match."; + return null; + } +} diff --git a/src/RynthCore.App/LaunchAccountProfile.cs b/src/RynthCore.App/LaunchAccountProfile.cs index c66b3ce..aba4926 100644 --- a/src/RynthCore.App/LaunchAccountProfile.cs +++ b/src/RynthCore.App/LaunchAccountProfile.cs @@ -130,6 +130,24 @@ internal sealed class LaunchAccountProfile PasswordNeedsReentry = false; } + /// <summary> + /// Reuses <paramref name="source"/>'s saved password (the same account name on another server). + /// The encrypted blob is copied as it is, so the plain text is never handled; it is readable + /// here because both profiles belong to the same Windows user's settings. + /// </summary> + public void CopyPasswordFrom(LaunchAccountProfile source) + { + ArgumentNullException.ThrowIfNull(source); + if (!string.IsNullOrEmpty(source.LegacyPlainPassword)) + { + SetPassword(source.LegacyPlainPassword); + return; + } + PasswordProtected = source.PasswordProtected; + LegacyPlainPassword = null; + PasswordNeedsReentry = source.PasswordNeedsReentry; + } + public void ClearPassword() { PasswordProtected = string.Empty; diff --git a/src/RynthCore.App/UserPrefsSwapRecovery.cs b/src/RynthCore.App/UserPrefsSwapRecovery.cs new file mode 100644 index 0000000..0f7c0c9 --- /dev/null +++ b/src/RynthCore.App/UserPrefsSwapRecovery.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; + +namespace RynthCore.App; + +/// <summary> +/// One launch's swap of a saved UserPreferences.ini over the live file in +/// My Documents\Asheron's Call: the saved copy it came from, and the live file as it was before. +/// <paramref name="PreviousLiveBytes"/> is null when there was no live file. +/// </summary> +internal sealed record UserPrefsSwap( + string StashPath, + string LivePath, + byte[] StashBytes, + byte[]? PreviousLiveBytes); + +/// <summary>What <see cref="UserPrefsSwapRecovery.Recover"/> did. Null paths mean that file was left alone.</summary> +internal sealed record UserPrefsRecoveryResult( + string? QuarantinedStashPath, + string? QuarantinedLegacyPath, + bool LiveRestored); + +/// <summary> +/// Undoes a UserPreferences.ini swap whose client quit at startup. The game reads its +/// resolution and full-screen mode from that file, so a saved copy with a display mode the PC +/// can't use stops every launch with "Could not initialize Direct3D". The saved copy is only +/// refreshed after a normal session, so without this it would be restored on every launch. +/// Pure file work: no UI, no launcher state. +/// </summary> +internal static class UserPrefsSwapRecovery +{ + /// <summary>Where a failed saved copy is kept: next to it, renamed so it is never swapped in again.</summary> + internal static string QuarantinePath(string stashPath, DateTime nowLocal) => + $"{stashPath}.failed-{nowLocal:yyyyMMdd-HHmmss}"; + + /// <summary> + /// True when the swap changed the live file. When the saved copy matched the live file, the + /// swap can't have caused the failure, so nothing is undone. + /// </summary> + internal static bool SwapChangedPrefs(UserPrefsSwap swap) => + swap.PreviousLiveBytes == null || !swap.StashBytes.AsSpan().SequenceEqual(swap.PreviousLiveBytes); + + /// <summary> + /// Sets the failed saved copy aside (when <paramref name="quarantineStash"/>) and puts the + /// previous live file back (when <paramref name="restoreLive"/>). + /// <paramref name="legacyStashPath"/> is the account's name-only copy: it seeds a missing + /// per-server copy, so it is set aside too when it holds the same failed settings. + /// </summary> + internal static UserPrefsRecoveryResult Recover( + UserPrefsSwap swap, + bool quarantineStash, + bool restoreLive, + string? legacyStashPath, + DateTime nowLocal) + { + string? quarantined = null; + string? quarantinedLegacy = null; + + if (quarantineStash && File.Exists(swap.StashPath)) + { + quarantined = QuarantinePath(swap.StashPath, nowLocal); + File.Move(swap.StashPath, quarantined, overwrite: true); + + if (!string.IsNullOrWhiteSpace(legacyStashPath) + && !string.Equals(Path.GetFullPath(legacyStashPath), Path.GetFullPath(swap.StashPath), StringComparison.OrdinalIgnoreCase) + && File.Exists(legacyStashPath) + && File.ReadAllBytes(legacyStashPath).AsSpan().SequenceEqual(swap.StashBytes)) + { + quarantinedLegacy = QuarantinePath(legacyStashPath, nowLocal); + File.Move(legacyStashPath, quarantinedLegacy, overwrite: true); + } + } + + bool restored = false; + if (restoreLive) + { + // No live file before the swap: remove it so the game writes its own defaults. + if (swap.PreviousLiveBytes != null) + File.WriteAllBytes(swap.LivePath, swap.PreviousLiveBytes); + else if (File.Exists(swap.LivePath)) + File.Delete(swap.LivePath); + restored = true; + } + + return new UserPrefsRecoveryResult(quarantined, quarantinedLegacy, restored); + } +} diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index dd055de..2f57e12 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -709,6 +709,10 @@ internal static class AcMainThreadQueue // drop: dropping arbitrary item/movement actions desyncs the bot far // worse than a late injection, and the pre-2026-06-12 behavior was // "always inject" anyway, so proceeding past the cap is never worse). + // Gesture-safe entries at the head still run (RunsDuringGesture): while deferring they + // run from the head of the ring up to the first one that doesn't (FIFO order is kept: + // nothing overtakes a held entry). + bool gestureSafeOnly = false; if (_ring.Count > 0) { // In milliseconds (was 250 Drain calls: 2 s to over 10 s depending on the frame rate). @@ -716,18 +720,19 @@ internal static class AcMainThreadQueue { long nowDefer = NowMs; if (_drainDeferSinceMs == 0) _drainDeferSinceMs = nowDefer; - if (nowDefer - _drainDeferSinceMs <= DrainDeferMaxMs) - return; + gestureSafeOnly = nowDefer - _drainDeferSinceMs <= DrainDeferMaxMs; } - _drainDeferSinceMs = 0; + if (!gestureSafeOnly) _drainDeferSinceMs = 0; } long runAt = NowMs; int epochNow = Volatile.Read(ref _loginEpoch); // Bounded to what is queued now plus a capacity's worth: an action that re-queues // itself can never spin the main thread. int budget = Capacity * 2; - while (budget-- > 0 && _ring.TryDequeue(out Entry e)) + while (budget-- > 0 && _ring.TryPeek(out Entry e)) { + if (gestureSafeOnly && !RunsDuringGesture(e.Kind)) break; + _ring.Pop(); long age = runAt - e.At; if (PlayerLifecycleLog.DecideQueued(runAt, e.At, IsTeardown(e)) == WorldTransitionState.Verdict.Drop) { @@ -880,8 +885,25 @@ internal static class AcMainThreadQueue // now run on the correct thread, which is the whole point.) } } + // The gesture-safe entries emptied the ring: the next held entry gets its own full defer. + if (gestureSafeOnly && _ring.Count == 0) _drainDeferSinceMs = 0; } + /// <summary> + /// Entries that run while a gesture is in flight (2026-10-14). Each is what the retail + /// client does from a key press at any moment, swing or not: the target select, the + /// keyboard attack (ClientCombatSystem StartAttackRequest/EndAttackRequest, which the client + /// itself holds until the motion allows) and the 0x1B7 cancel. With a crossbow or bow a + /// gesture is in flight nearly all the time, so these waited up to DrainDeferMaxMs every + /// cycle (Silentkelpie: target select and attacks 1.0-1.9 s late, stale attacks dropped). + /// Stance changes, movement, raw attack packets and item moves stay deferred. + /// </summary> + internal static bool RunsDuringGesture(ActionKind kind) => kind switch + { + ActionKind.SetSelectedObject or ActionKind.NativeAttack or ActionKind.CancelAttack => true, + _ => false, + }; + // ── RequestId slot (0xC8 appraisal sends from AutoIdService, and every other // off-thread CombatActionHooks.RequestId caller: plugin RequestIdFn, the // PluginManager.TickAll login self-identify) ───────────────────────────── diff --git a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs index ddea408..8745129 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs @@ -308,7 +308,7 @@ internal static class ChatCallbackHooks // Not inside our own reprint of a held line: that line was already offered here when // it first arrived (and wasn't ours, or it wouldn't have been held), so offering it // again could take a stale line for the answer to a request sent since. - if (line != null && _replayDepth == 0 && EatOwnReply(line)) + if (line != null && _replayDepth == 0 && EatOwnReply(line, chatType)) return 0; // 2. Hold the line until the plugins have heard it (IncomingChatHold.cs): AC prints it @@ -349,8 +349,11 @@ internal static class ChatCallbackHooks } [MethodImpl(MethodImplOptions.NoInlining)] - private static bool EatOwnReply(string line) + private static bool EatOwnReply(string line, uint chatType) { + // Server replies only: a line in a player's chat type is someone typing "~ael1 ..." or + // "Unknown command: ..." to feed the readers or hide their own chat. + if (Net.ChatOrigin.IsPlayerAuthored(chatType)) return false; try { return MasteryFeed.OnIncomingLine(line) || VaultFeed.OnIncomingLine(line); } catch { return false; } } diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index dfc31f1..5d9e39c 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -374,6 +374,9 @@ internal static class ClientHelperHooks // Skills panel raises (CM_Train senders). try { PlayerTraining.Probe(text); } catch (Exception ex) { RynthLog.Compat($"Compat: raise senders binding failed - {ex.Message}"); } + // v85 confirmation answers (CM_Character::Event_ConfirmationResponse). + try { ConfirmationResponder.Probe(text); } + catch (Exception ex) { RynthLog.Compat($"Compat: confirmation response binding failed - {ex.Message}"); } _initialized = true; _statusMessage = "Ready."; RynthLog.Verbose("Compat: helper hooks ready - validated select/state/chat helpers plus mapped interaction and inventory helpers."); diff --git a/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs b/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs new file mode 100644 index 0000000..037b155 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs @@ -0,0 +1,203 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ConfirmationResponder.cs +// +// Plugin API v85: answer the server's yes/no prompts (craft chance, augmentation, +// ...) for a plugin, the way UtilityBelt's helper clicks "Yes" on the tinkering +// dialog, without the client ever opening that dialog. +// +// INBOUND ConfirmationRequest (GameEvent 0x0274: u32 type, u32 contextId, +// string16 text) reaches UIQueueManager::ProcessNetBlobData, which +// SmartBoxHooks already detours. Its case calls +// CM_Character::DispatchUI_ConfirmationRequest (0x006A3BB0), which hands the +// prompt to the UI handler (0x00564E40) and returns that handler's result; +// the handler returns 0 on every path. So when the request is answered here, +// the detour skips the original and returns 0: nothing else in the client +// sees the prompt, and no dialog is left on screen (ACE never sends +// ConfirmationDone after a response, so an answered dialog would stay open). +// +// OUTBOUND CM_Character::Event_ConfirmationResponse(uint type, uint contextId, +// int accept), 0x006A2030 on the live client: the generated CM_* sender +// template (see Event_GiveObjectRequest in ClientHelperHooks), arg block +// +0x10 (three args), opcode 0x0275. Cdecl, returns bool. Verified unique +// with tools/pe_pattern.py on the live acclient. +// +// ARMING A plugin arms one answer: the confirmation type, a minimum percent and +// a timeout. The next matching request inside the timeout is answered +// Yes when the server's own "N percent chance" is at least the minimum +// (or the minimum is 0), else No, and the arm is spent. An unarmed or +// expired request is left to the client, as before. The last request is +// always recorded so the plugin can see what happened. +// +// Threading: the detour runs on AC's main thread and only takes a short lock; +// the sender is called there, outside the lock. Arm/Get run on any thread. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class ConfirmationResponder +{ + /// <summary>GameEvent ConfirmationRequest.</summary> + public const uint EventConfirmationRequest = 0x0274; + + // ABI outcome codes (ConfirmationInfoNative.Outcome). Never renumber. + public const int OutcomeNone = 0; // no request seen this session + public const int OutcomeShown = 1; // not armed (or expired / other type): the client showed it + public const int OutcomeAccepted = 2; // answered Yes for the plugin + public const int OutcomeDeclined = 3; // answered No: the server's percent was below the minimum + public const int OutcomeSendFailed = 4; // armed, but the sender failed; the client showed it + + private const int EventConfirmationResponseVa = 0x006A2030; + + // CM_Character::Event_ConfirmationResponse: the shared CM_* sender template with the + // three-argument block (+0x10) and the opcode immediate 0x0275 at the end. + private static readonly byte?[] PatEventConfirmationResponse = [ 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, 0x10, 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, 0x75, 0x02, 0x00, 0x00 ]; + + private static delegate* unmanaged[Cdecl]<uint, uint, int, byte> _eventConfirmationResponse; + + private static readonly object _lock = new(); + // The armed answer (one-shot). + private static bool _armed; + private static uint _armedType; + private static int _armedMinPercent; + private static long _armedUntil; + // The last request seen. + private static int _seq; + private static uint _lastType, _lastContext; + private static int _lastPercent = -1, _lastOutcome; + private static long _lastAt; + private static int _logCount; + + /// <summary>True when the response sender is bound on this client.</summary> + public static bool HasSender => _eventConfirmationResponse != null; + + /// <summary>Bind the sender. Called from ClientHelperHooks.Probe (engine init).</summary> + public static void Probe(AcClientTextSection text) + { + HookResolver.ResolveResult r = HookResolver.Resolve(text, "Confirmation.Event_ConfirmationResponse", + PatEventConfirmationResponse, EventConfirmationResponseVa); + _eventConfirmationResponse = r.Success && r.Source == HookResolver.ResolveSource.PatternScan + ? (delegate* unmanaged[Cdecl]<uint, uint, int, byte>)r.Address + : null; + RynthLog.Compat($"Compat: confirmation response sender {(HasSender ? $"bound @0x{r.Address.ToInt32():X8}" : "not found")}"); + } + + /// <summary> + /// Arm one answer for the next request of <paramref name="type"/> within + /// <paramref name="timeoutMs"/>. timeoutMs <= 0 disarms. 1 armed (or disarmed), + /// 0 the sender or the game-event hook isn't available, -3 bad arguments. + /// </summary> + public static int Arm(uint type, int minPercent, int timeoutMs) + { + if (timeoutMs <= 0) + { + lock (_lock) _armed = false; + return 1; + } + if (type == 0 || minPercent < 0 || minPercent > 100 || timeoutMs > 120_000) + return -3; + if (!HasSender || !SmartBoxHooks.IsGameEventHookInstalled) + return 0; + lock (_lock) + { + _armed = true; + _armedType = type; + _armedMinPercent = minPercent; + _armedUntil = Environment.TickCount64 + timeoutMs; + } + return 1; + } + + /// <summary>The last request: its sequence number (0 = none yet), type, context, the + /// server's percent (-1 when the text has none), outcome and age.</summary> + public static int GetLast(out uint type, out uint contextId, out int percent, out int outcome, out int ageMs) + { + lock (_lock) + { + type = _lastType; + contextId = _lastContext; + percent = _lastPercent; + outcome = _lastOutcome; + long age = _seq == 0 ? 0 : Environment.TickCount64 - _lastAt; + ageMs = age > int.MaxValue ? int.MaxValue : (int)age; + return _seq; + } + } + + /// <summary> + /// The game-event detour's hook for 0x0274 (AC's main thread). <paramref name="data"/> + /// is the event blob (type at +0). True = answered here: the caller must skip AC's + /// handler so no dialog opens. + /// </summary> + public static bool OnRequest(IntPtr data, uint size) + { + if (data == IntPtr.Zero || size < 12) + return false; + uint type = unchecked((uint)Marshal.ReadInt32(data, 4)); + uint context = unchecked((uint)Marshal.ReadInt32(data, 8)); + int percent = ParsePercent(data, size); + + bool answer = false, accept = false; + lock (_lock) + { + _seq++; + _lastType = type; + _lastContext = context; + _lastPercent = percent; + _lastAt = Environment.TickCount64; + _lastOutcome = OutcomeShown; + if (_armed && _armedType == type && Environment.TickCount64 <= _armedUntil) + { + _armed = false; + answer = true; + accept = _armedMinPercent <= 0 || (percent >= 0 && percent >= _armedMinPercent); + } + } + if (!answer) + return false; + + bool sent = false; + try + { + sent = _eventConfirmationResponse != null && _eventConfirmationResponse(type, context, accept ? 1 : 0) != 0; + } + catch { sent = false; } + + lock (_lock) + _lastOutcome = !sent ? OutcomeSendFailed : accept ? OutcomeAccepted : OutcomeDeclined; + if (_logCount < 40) + { + _logCount++; + RynthLog.Compat($"Confirmation type={type} ctx=0x{context:X8} percent={percent} -> {(sent ? (accept ? "yes" : "no") : "send failed, shown")}"); + } + return sent; + } + + // "You determine that you have a 38 percent chance to succeed." -> 38. The text is a + // string16 (u16 length, cp1252 bytes) at +12. -1 when there is no "N percent". + private static int ParsePercent(IntPtr data, uint size) + { + const int textOff = 12; + if (size < textOff + 2) + return -1; + int len = (ushort)Marshal.ReadInt16(data, textOff); + if (len <= 0 || len > 512 || textOff + 2 + len > size) + return -1; + byte* p = (byte*)data + textOff + 2; + ReadOnlySpan<byte> text = new(p, len); + int at = text.IndexOf(" percent"u8); + if (at <= 0) + return -1; + int end = at, start = at; + while (start > 0 && text[start - 1] >= (byte)'0' && text[start - 1] <= (byte)'9') + start--; + if (start == end || end - start > 3) + return -1; + int value = 0; + for (int i = start; i < end; i++) + value = value * 10 + (text[i] - '0'); + return value > 100 ? 100 : value; + } +} diff --git a/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs b/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs index 802e378..c7c3e7e 100644 --- a/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs +++ b/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; @@ -27,12 +28,19 @@ namespace RynthCore.Engine.Compatibility; /// Other paths pass through untouched. /// /// Why IAT-hook instead of MinHook on the kernel32 export: -/// Decal coexistence. Decal almost certainly already detours kernel32!CreateFile -/// (that's how Decal-injected Thwargle clients can multibox without a -/// second AC install). IAT-hooking acclient.exe's import slot intercepts only -/// acclient.exe's own calls; our detour's call into the saved IAT pointer -/// still routes through any Decal MinHook trampoline on the kernel32 export. -/// No collision; both hooks fire in order. +/// Only the modules that open AC's data files are hooked: acclient.exe +/// (imports CreateFileA) and its CRT MSVCR70.dll (CreateFileA/W, behind +/// fopen/_wfopen). A kernel32 export hook also caught every other module, +/// including d3d9.dll and the GPU driver while AC created its device: their +/// CreateFile calls went through managed code, could wait on the runtime +/// while plugins loaded, and on some PCs AC then failed with "Could not +/// initialize Direct3D" (2026-10-14). The detour preserves the Win32 last +/// error, because callers read it after a successful CreateFile too +/// (ERROR_ALREADY_EXISTS). +/// Decal coexistence: our detour calls the pointer the IAT slot held, so any +/// Decal detour on the kernel32 export still runs. Both hooks fire in order. +/// The slots are restored at engine shutdown (<see cref="Uninstall"/>): the +/// detours live in this engine generation, which hot reload unloads. /// </summary> internal static class DatFileShareHooks { @@ -77,23 +85,16 @@ internal static class DatFileShareHooks [DllImport("kernel32.dll", SetLastError = true)] private static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect); - // Pinned via static field — Marshal.GetFunctionPointerForDelegate keeps a - // weak handle, so the delegate must be reachable for the process lifetime. - private static CreateFileWDelegate? _wDetour; - private static CreateFileADelegate? _aDetour; + /// <summary> + /// One patched import slot. <see cref="Slot"/> is the address inside the IAT array (not a + /// function address); <see cref="Original"/> is what it held (the real kernel32!CreateFile, + /// or another hooker's detour), written back by <see cref="Uninstall"/>. <see cref="Detour"/> + /// keeps the delegate reachable: the function pointer handed to native code is only valid + /// while it is. + /// </summary> + private sealed record IatHook(string Module, string Function, IntPtr Slot, IntPtr Original, Delegate Detour); - // The IAT slot pointer (the address inside the IAT array, NOT the original - // function address) — needed for the unhook path. - private static IntPtr _wIatSlot; - private static IntPtr _aIatSlot; - - // What was in the IAT slot when we patched it. Could be the real - // kernel32!CreateFile, or another hooker's detour if they got there first. - private static IntPtr _wOriginalPtr; - private static IntPtr _aOriginalPtr; - - private static CreateFileWDelegate? _wOriginal; - private static CreateFileADelegate? _aOriginal; + private static readonly List<IatHook> _iatHooks = []; private static string _statusMessage = "Not probed yet."; @@ -137,80 +138,23 @@ internal static class DatFileShareHooks return; } - // Hook the kernel32 exports directly with MinHook so we catch ALL - // callers in the process — acclient.exe itself, the CRT layer - // (msvcrt.dll, which is how AC's fopen-style DAT loads route), and - // any plugin or runtime DLL. IAT-hooking acclient.exe alone misses - // CRT-mediated calls because they go through msvcrt's own IAT slot. - IntPtr hKernel32 = GetModuleHandleW("kernel32.dll"); - if (hKernel32 == IntPtr.Zero) - { - _statusMessage = "kernel32.dll module handle not found."; - RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}"); - return; - } + // acclient.exe opens DATs with its own CreateFileA import; its CRT + // (MSVCR70.dll, statically imported, so loaded by now) does fopen/_wfopen + // opens through its CreateFileA/W imports. Nothing else is hooked. + HookModuleImports("acclient.exe", moduleBase); + HookModuleImports("MSVCR70.dll", GetModuleHandleW("MSVCR70.dll")); - // Two-phase install. Phase 1: create both hooks (inactive), - // assign typed trampolines into _aOriginal/_wOriginal. Phase 2: - // memory barrier then Enable. Critical ordering: the detour can - // fire from ANY caller in the process the moment Enable returns, - // and the detour calls _aOriginal/_wOriginal — those fields MUST - // be set first or the first invocation null-derefs and kills the - // engine init thread. - IntPtr aTarget = GetProcAddress(hKernel32, "CreateFileA"); - IntPtr wTarget = GetProcAddress(hKernel32, "CreateFileW"); - - int patched = 0; - if (aTarget != IntPtr.Zero) + if (_iatHooks.Count == 0) { - _aDetour = CreateFileADetour; - IntPtr aDetourPtr = Marshal.GetFunctionPointerForDelegate(_aDetour); - _aOriginalPtr = MinHook.HookCreate(aTarget, aDetourPtr); - _aOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(_aOriginalPtr); - patched++; - } - - if (wTarget != IntPtr.Zero) - { - _wDetour = CreateFileWDetour; - IntPtr wDetourPtr = Marshal.GetFunctionPointerForDelegate(_wDetour); - _wOriginalPtr = MinHook.HookCreate(wTarget, wDetourPtr); - _wOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(_wOriginalPtr); - patched++; - } - - // Publish trampolines to other cores before enabling. - Thread.MemoryBarrier(); - - if (aTarget != IntPtr.Zero) - { - MinHook.Enable(aTarget); - RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileA @ 0x{aTarget.ToInt32():X8} (trampoline 0x{_aOriginalPtr.ToInt32():X8})."); - } - else - { - RynthLog.Compat("Compat: DAT share - kernel32!CreateFileA export not found."); - } - - if (wTarget != IntPtr.Zero) - { - MinHook.Enable(wTarget); - RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileW @ 0x{wTarget.ToInt32():X8} (trampoline 0x{_wOriginalPtr.ToInt32():X8})."); - } - else - { - RynthLog.Compat("Compat: DAT share - kernel32!CreateFileW export not found."); - } - - if (patched == 0) - { - _statusMessage = "MinHook on kernel32 CreateFile exports failed."; + _statusMessage = "no CreateFile import slots found in acclient.exe or MSVCR70.dll."; RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}"); return; } IsInstalled = true; - _statusMessage = $"DAT share hook installed ({patched} kernel32 export(s) detoured)."; + _statusMessage = $"DAT share hook installed ({_iatHooks.Count} import slot(s): " + + string.Join(", ", _iatHooks.Select(h => $"{h.Module}!{h.Function}")) + + "); Direct3D and drivers call CreateFile unhooked."; RynthLog.Info($"Compat: {_statusMessage}"); } catch (Exception ex) @@ -220,9 +164,84 @@ internal static class DatFileShareHooks } } + /// <summary> + /// Points <paramref name="moduleName"/>'s kernel32 CreateFileA/W import slots at detours that + /// call whatever each slot held. A module that isn't loaded, or doesn't import one of them, + /// is skipped (logged). + /// </summary> + private static void HookModuleImports(string moduleName, IntPtr moduleBase) + { + if (moduleBase == IntPtr.Zero) + { + RynthLog.Compat($"Compat: DAT share - {moduleName} is not loaded; its CreateFile imports are not hooked."); + return; + } + + if (TryPatchIatSlot(moduleBase, "CreateFileW", out IntPtr wSlot, out IntPtr wCurrent)) + { + CreateFileWDelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(wCurrent); + CreateFileWDelegate detour = (name, access, share, security, disposition, flags, template) => + CreateFileWDetour(original, name, access, share, security, disposition, flags, template); + InstallSlot(moduleName, "CreateFileW", wSlot, wCurrent, detour, Marshal.GetFunctionPointerForDelegate(detour)); + } + + if (TryPatchIatSlot(moduleBase, "CreateFileA", out IntPtr aSlot, out IntPtr aCurrent)) + { + CreateFileADelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(aCurrent); + CreateFileADelegate detour = (name, access, share, security, disposition, flags, template) => + CreateFileADetour(original, name, access, share, security, disposition, flags, template); + InstallSlot(moduleName, "CreateFileA", aSlot, aCurrent, detour, Marshal.GetFunctionPointerForDelegate(detour)); + } + } + + /// <summary> + /// Records the hook (so the delegate stays reachable) before the slot is written: the + /// detour can run on any thread the moment the pointer lands. + /// </summary> + private static void InstallSlot(string moduleName, string function, IntPtr slot, IntPtr original, Delegate detour, IntPtr detourPtr) + { + var hook = new IatHook(moduleName, function, slot, original, detour); + _iatHooks.Add(hook); + Thread.MemoryBarrier(); + + if (WriteIatPointer(slot, detourPtr)) + { + RynthLog.Info($"Compat: DAT share - hooked {moduleName}!{function} import (slot 0x{slot.ToInt32():X8}, was 0x{original.ToInt32():X8})."); + return; + } + + _iatHooks.Remove(hook); + } + + /// <summary> + /// Writes every patched slot back to what it held, at engine shutdown. The detours are in + /// this engine generation, which hot reload unloads; a slot left pointing at them would + /// crash the next CreateFile. + /// </summary> + public static void Uninstall() + { + if (_iatHooks.Count == 0) + return; + + int restored = 0; + foreach (IatHook hook in _iatHooks) + { + if (WriteIatPointer(hook.Slot, hook.Original)) + restored++; + } + + RynthLog.Info($"Compat: DAT share - restored {restored}/{_iatHooks.Count} CreateFile import slot(s)."); + _iatHooks.Clear(); + IsInstalled = false; + } + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern IntPtr GetModuleHandleW(string? lpModuleName); + // Plain import (no SetLastError marshalling): it must leave the value it sets. + [DllImport("kernel32.dll", EntryPoint = "SetLastError")] + private static extern void SetWin32LastError(uint dwErrCode); + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); @@ -402,10 +421,8 @@ internal static class DatFileShareHooks && path.EndsWith(DatExtension, StringComparison.OrdinalIgnoreCase); } - [DllImport("kernel32.dll", SetLastError = true)] - private static extern uint GetLastError(); - private static IntPtr CreateFileWDetour( + CreateFileWDelegate original, IntPtr lpFileName, uint dwDesiredAccess, uint dwShareMode, @@ -435,21 +452,25 @@ internal static class DatFileShareHooks { } - IntPtr result = _wOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, + IntPtr result = original(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + // Captured by the SetLastError=true delegate; the caller may read it even on success. + int lastError = Marshal.GetLastPInvokeError(); if (isAnyDatExt) { - uint err = result == new IntPtr(-1) ? GetLastError() : 0; + int err = result == new IntPtr(-1) ? lastError : 0; string fname = Path.GetFileName(path!); string note = isDat ? "filtered" : "passthrough"; RynthLog.Info($"Compat: DAT share - W [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}"); } + SetWin32LastError((uint)lastError); return result; } private static IntPtr CreateFileADetour( + CreateFileADelegate original, IntPtr lpFileName, uint dwDesiredAccess, uint dwShareMode, @@ -479,17 +500,19 @@ internal static class DatFileShareHooks { } - IntPtr result = _aOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, + IntPtr result = original(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + int lastError = Marshal.GetLastPInvokeError(); if (isAnyDatExt) { - uint err = result == new IntPtr(-1) ? GetLastError() : 0; + int err = result == new IntPtr(-1) ? lastError : 0; string fname = Path.GetFileName(path!); string note = isDat ? "filtered" : "passthrough"; RynthLog.Info($"Compat: DAT share - A [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}"); } + SetWin32LastError((uint)lastError); return result; } } diff --git a/src/RynthCore.Engine/Compatibility/IltInfo.cs b/src/RynthCore.Engine/Compatibility/IltInfo.cs index 1b16e5f..e2503b2 100644 --- a/src/RynthCore.Engine/Compatibility/IltInfo.cs +++ b/src/RynthCore.Engine/Compatibility/IltInfo.cs @@ -14,8 +14,8 @@ // defaults (InfiniteLeaftide / *Leaftide* and infiniteleaftide.online); // - RynthILT's own verdict (its server list, or the character's "Treat this // world as ILT"), read once a second by UI/Data/IltData.cs. -// Unknown means not ILT. "/rc ilt on|off|auto" overrides it for this session -// (testing), never saved. +// Unknown means not ILT. "/rc ilt on|off|auto" (or the Mini Remote's Char +// section) overrides it, saved per character (UI/Sections/ServerForceStore). // // Threads: any. Re-evaluated at most once a second; each read in between is a // volatile load and a compare. Never touches AC. @@ -33,10 +33,13 @@ internal static class IltInfo private const int RefreshMs = 1000; + /// <summary>The server id the override is saved under (UI/Sections).</summary> + public const string ServerId = "ilt"; + private static volatile IltVerdict _verdict = IltVerdict.Unknown; private static long _nextRefreshMs; - private static int _mode; // Mode private static volatile bool _lastIlt; + private static string _loggedWorld = string.Empty; // the world the last verdict line was for (Refresh only) private static volatile bool _pluginLoaded; private static volatile bool _pluginIlt; private static volatile string _pluginReason = ""; @@ -60,16 +63,38 @@ internal static class IltInfo /// <summary>True when the client is on Infinite Leaftide - or the override says so. Any thread.</summary> public static bool IsIlt => Current.IsIlt; + /// <summary>What detection alone says (no override), for the Char section and /rc server.</summary> + public static IltVerdict Detected => + IltDetect.Decide(ServerInfo.LaunchHost, AccountHooks.AnnouncedWorldName, EngineSettings.IltServerNames, EngineSettings.IltHosts); + + /// <summary>The current character's saved override (session-only before login).</summary> public static Mode Override { - get => (Mode)Volatile.Read(ref _mode); - set + get => UI.Sections.ServerForceStore.Get(ServerId) switch { - Volatile.Write(ref _mode, (int)value); - Volatile.Write(ref _nextRefreshMs, 0); - } + UI.Sections.ServerForce.On => Mode.ForceIlt, + UI.Sections.ServerForce.Off => Mode.ForceOther, + _ => Mode.Auto, + }; } + /// <summary>Sets the override (saved per character); <paramref name="where"/> says where it went.</summary> + public static bool SetOverride(Mode mode, out string where) + { + var force = mode switch + { + Mode.ForceIlt => UI.Sections.ServerForce.On, + Mode.ForceOther => UI.Sections.ServerForce.Off, + _ => UI.Sections.ServerForce.Auto, + }; + bool ok = UI.Sections.ServerForceStore.Set(ServerId, force, out where); + Volatile.Write(ref _nextRefreshMs, 0); + return ok; + } + + /// <summary>Re-evaluates on the next read (the character or an override changed).</summary> + public static void Invalidate() => Volatile.Write(ref _nextRefreshMs, 0); + /// <summary>The current verdict (re-evaluated at most once a second). Any thread.</summary> public static IltVerdict Current { @@ -106,18 +131,22 @@ internal static class IltInfo { IltVerdict v = Override switch { - Mode.ForceIlt => new IltVerdict { IsIlt = true, Reason = "forced on with /rc ilt on (testing)" }, - Mode.ForceOther => new IltVerdict { Reason = "forced off with /rc ilt off (testing)" }, + Mode.ForceIlt => new IltVerdict { IsIlt = true, Reason = "forced on for this character (/rc ilt auto undoes it)" }, + Mode.ForceOther => new IltVerdict { Reason = "forced off for this character (/rc ilt auto undoes it)" }, _ => IltDetect.Decide(ServerInfo.LaunchHost, AccountHooks.AnnouncedWorldName, EngineSettings.IltServerNames, EngineSettings.IltHosts), }; // RynthILT's own list / override counts too (its verdict, when the engine's says no). if (Override == Mode.Auto) v = IltDetect.Combine(v, _pluginIlt, _pluginReason); _verdict = v; - if (v.IsIlt != _lastIlt) + // Logged on every change and once per announced world, so a session's log always + // says whether (and why) it counted as ILT - "not ILT" included. + string world = AccountHooks.AnnouncedWorldName ?? string.Empty; + if (v.IsIlt != _lastIlt || !string.Equals(world, _loggedWorld, StringComparison.Ordinal)) { _lastIlt = v.IsIlt; - RynthLog.Compat($"IltInfo: {v.Reason}"); + _loggedWorld = world; + RynthLog.Milestone($"IltInfo: {v.Reason} (RynthILT loaded={_pluginLoaded}, says ILT={_pluginIlt}, override={Override})"); } } catch (Exception ex) diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 07dfb02..92af625 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -90,12 +90,17 @@ namespace RynthCore.Engine.Compatibility; /// <item><c>/rc hotkeys</c> - opens Settings > Hotkeys. <c>/rc hotkey list | add <combo> <action or /// /command> | remove <combo> | enable|disable <combo> | actions | status | on|off</c> - the user /// hotkeys (<see cref="Hotkeys.HotkeyService"/>; saved for the PC in hotkeys.txt).</item> +/// <item><c>/rc diagnostics</c> (or <c>/rc serverpick</c>) - opens Settings > Diagnostics, the server +/// picker: the one place a server is forced for this character (plugins' "Force a server" links).</item> /// </list> /// </summary> internal static class RynthCoreChatCommands { private const string Prefix = "/rc "; + /// <summary>The Settings tab with the server picker (UI/Data/SettingsData.cs "Diagnostics").</summary> + private const string DiagnosticsTabName = "Diagnostics"; + /// <summary> /// True if <paramref name="line"/> was a RynthCore engine command and has /// been handled — the caller must consume it (do NOT forward to AC chat @@ -178,7 +183,7 @@ internal static class RynthCoreChatCommands return true; } - // /rc server [auto|aelrynth|other] : which server the engine thinks this is (testing override) + // /rc server [<server> auto|on|off | names ilt ...] : the servers, why each is active, per-character overrides if (IsVerb(sub, "server", out string serverArgs)) { try { HandleServerCommand(serverArgs); } @@ -186,7 +191,7 @@ internal static class RynthCoreChatCommands return true; } - // /rc ilt [auto|on|off] : is this Infinite Leaftide (the ILT section), with a testing override + // /rc ilt [auto|on|off] : is this Infinite Leaftide (the ILT section), with a per-character override if (IsVerb(sub, "ilt", out string iltArgs)) { try { HandleIltCommand(iltArgs); } @@ -345,21 +350,49 @@ internal static class RynthCoreChatCommands return true; } - // /rc miniremote [show|hide|toggle|tab <tab>] : the ImGui Mini Remote panel, like its bar - // button (RynthAi's dashboard and "/ra hub" use show / hide). "tab" opens it on one of its - // tabs (RynthAi's quests, pets; RynthILT's character, banking, gear, charms, games; none = - // the remote). + // /rc miniremote [show|hide|toggle|tab <tab>|section <id>] : the ImGui Mini Remote panel, like + // its bar button (RynthAi's dashboard and "/ra hub" use show / hide). "tab" opens it on one of + // its tabs (RynthAi's pets, crafting; RynthILT's gear, games; none = the remote). Quests are + // RynthOracle's window (/ro) since 2026-10-13. Since 2026.10.5.54 the old "character" tab + // (the generic overview) opens RynthOracle's Character tab (/ro character). Infinite + // Leaftide's own tabs ("charms", "banking", "gear", "games") stay RynthILT's, in this window. + // "section" opens it on one of its sections (char = Session Stats, map, skills, ...; "remote" = the remote). if (IsVerb(sub, "miniremote", out string remoteArgs) || IsVerb(sub, "remote", out remoteArgs)) { - if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title)) + if (IsVerb(remoteArgs, "tab", out string moved) && MovedTabCommand(moved) is string movedTo) + UI.ServerMenus.Run(movedTo); + else if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title)) Reply("The Mini Remote panel isn't available (the ImGui layer is off?)."); - else if (IsVerb(remoteArgs, "tab", out string tab)) + else if (IsVerb(remoteArgs, "tab", out string tab) + && tab.Length > 0 && ImGuiBackend.Panels.MiniRemoteFace.TryRequestSurface("section:" + tab.Trim().ToLowerInvariant())) { + // A RynthAi that publishes sections: its tabs are sections here. + ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title); + } + else if (IsVerb(remoteArgs, "tab", out tab)) + { + ImGuiBackend.Panels.MiniRemoteFace.RequestSection(UI.Sections.SectionCatalog.RemoteId); ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title); UI.Data.RynthAiCommands.ApplyRemoteCommand("hub", tab.Length > 0 ? "tab " + tab : "tab"); } + else if (IsVerb(remoteArgs, "section", out string section)) + { + string id = UI.Sections.SectionManifestParser.Id(section); + var snap = UI.Sections.SectionRegistry.Current; + if (id != UI.Sections.SectionCatalog.RemoteId && snap.Find(id) == null) + { + var names = new System.Collections.Generic.List<string> { UI.Sections.SectionCatalog.RemoteId }; + foreach (UI.Sections.SectionView v in snap.Sections) names.Add(v.Id); + Reply($"Usage: /rc miniremote section <{string.Join("|", names)}>"); + } + else + { + ImGuiBackend.Panels.MiniRemoteFace.RequestSection(id); + ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title); + } + } else if (!TryPanelMode(remoteArgs, out bool? show)) - Reply("Usage: /rc miniremote [show|hide|toggle|tab <tab>]"); + Reply("Usage: /rc miniremote [show|hide|toggle|tab <tab>|section <id>]"); else SetPanelOpen(ImGuiBackend.Panels.MiniRemoteFace.Title, show); return true; @@ -412,6 +445,20 @@ internal static class RynthCoreChatCommands } return true; } + // /rc diagnostics : Settings > Diagnostics, where a server is forced for this character (the + // server picker). The one place to force a server since 2026.10.5.54, so plugins link here. + if ((IsVerb(sub, "diagnostics", out string diagArgs) || IsVerb(sub, "serverpick", out diagArgs)) && diagArgs.Length == 0) + { + if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SettingsFace.Title)) + Reply("The Settings panel isn't available (the ImGui layer is off?). /rc server <id> auto|on|off works here in chat."); + else + { + ImGuiBackend.Panels.SettingsFace.RequestTab(DiagnosticsTabName); + if (!ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.SettingsFace.Title)) + UI.PanelRouter.Toggle(ImGuiBackend.Panels.SettingsFace.Title); + } + return true; + } if (IsVerb(sub, "hotkey", out hotkeyArgs) || IsVerb(sub, "hotkeys", out hotkeyArgs)) { try @@ -728,42 +775,156 @@ internal static class RynthCoreChatCommands } /// <summary>"verb" or "verb args..." (case-insensitive); args trimmed.</summary> + private const string ServerUsage = + "Usage: /rc server [<server> auto|on|off] | pick <server>|auto | [aelrynth|other|auto] | names ilt [add|remove <pattern>]"; + /// <summary> - /// /rc server: the detection verdict and its signals. "aelrynth" / "other" force it - /// for this session (to test the Aelrynth-only features anywhere, or to see a - /// non-Aelrynth client on Aelrynth); "auto" goes back to detecting. Never saved. + /// /rc server: every server the engine and the plugins know, whether each is active and why. + /// "<server> on|off|auto" forces one on or off, or back to detecting, saved for this + /// character (this session only before login). "aelrynth" / "other" / "auto" alone are the + /// older Aelrynth override. "names ilt" lists, adds or removes Infinite Leaftide's world-name + /// patterns (engine.json IltServerNames). /// </summary> private static void HandleServerCommand(string args) { - switch (args.Trim().ToLowerInvariant()) + string[] words = args.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + string first = words.Length > 0 ? words[0].ToLowerInvariant() : string.Empty; + + if (first == "names") { - case "aelrynth": case "on": ServerInfo.Override = ServerInfo.Mode.ForceAelrynth; break; - case "other": case "off": ServerInfo.Override = ServerInfo.Mode.ForceOther; break; - case "auto": ServerInfo.Override = ServerInfo.Mode.Auto; break; - case "": break; - default: - Reply("Usage: /rc server [auto|aelrynth|other]"); - return; + HandleServerNames(words); + return; } + if (first == "pick") + { + // One server for this character (every other off), or "auto": the Diagnostics page's picker. + if (words.Length != 2) { Reply(ServerUsage); return; } + UI.Sections.ServerSelectionStore.Apply(words[1], out string message); + Reply(message); + ReplyServers(); + return; + } + if (words.Length == 1) + { + // The older single-word form: the Aelrynth override. + ServerInfo.Mode? legacy = first switch + { + "aelrynth" or "on" => ServerInfo.Mode.ForceAelrynth, + "other" or "off" => ServerInfo.Mode.ForceOther, + "auto" => ServerInfo.Mode.Auto, + _ => null, + }; + if (legacy == null) { Reply(ServerUsage); return; } + SetServerForce(ServerInfo.ServerId, legacy switch + { + ServerInfo.Mode.ForceAelrynth => UI.Sections.ServerForce.On, + ServerInfo.Mode.ForceOther => UI.Sections.ServerForce.Off, + _ => UI.Sections.ServerForce.Auto, + }); + } + else if (words.Length == 2) + { + if (!UI.Sections.ServerForceText.TryParse(words[1], out UI.Sections.ServerForce mode)) { Reply(ServerUsage); return; } + if (!SetServerForce(first, mode)) return; + } + else if (words.Length > 2) + { + Reply(ServerUsage); + return; + } + + ReplyServers(); ServerVerdict v = ServerInfo.Current; - Reply($"Server: {(v.IsAelrynth ? (v.IsStaging ? "Aelrynth (staging)" : "Aelrynth") : "not Aelrynth")} - {v.Reason}."); - Reply($"Signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}; " - + $"override {ServerInfo.Override}."); + Reply($"Aelrynth signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}" + + (v.IsStaging ? "; staging" : "") + "."); Reply($"Titles (plugin API v75): {CharacterTitles.Describe()}."); } + /// <summary>Saves a server override (per character) and says where it went. False for an unknown server.</summary> + private static bool SetServerForce(string serverId, UI.Sections.ServerForce mode) + { + string id = UI.Sections.SectionManifestParser.Id(serverId); + if (id.Length == 0 || (!UI.Sections.SectionRegistry.IsBuiltInServer(id) + && UI.Sections.SectionRegistry.Current.Server(id) == null)) + { + Reply($"No server called '{serverId}'. /rc server lists them."); + return false; + } + if (!UI.Sections.ServerForceStore.Set(id, mode, out string where)) + { + Reply($"Server override not changed: {where}."); + return false; + } + UI.Sections.SectionRegistry.Invalidate(); + Reply($"Server override {id} = {UI.Sections.ServerForceText.Name(mode)} ({where})."); + return true; + } + + /// <summary>One line per server: active or not, detected or not, the override, why.</summary> + private static void ReplyServers() + { + var snap = UI.Sections.SectionRegistry.Current; + if (snap.Servers.Count == 0) + { + // Before the first frame built a snapshot: the built-in verdicts directly. + IltVerdict ilt = IltInfo.Current; + ServerVerdict ael = ServerInfo.Current; + Reply($"Server ilt (Infinite Leaftide): {(ilt.IsIlt ? "active" : "not active")} - {ilt.Reason}."); + Reply($"Server aelrynth (Aelrynth): {(ael.IsAelrynth ? "active" : "not active")} - {ael.Reason}."); + return; + } + foreach (UI.Sections.ServerState s in snap.Servers) + { + string force = s.Force == UI.Sections.ServerForce.Auto ? "auto" + : $"forced {UI.Sections.ServerForceText.Name(s.Force)} (detected: {(s.Detected ? "yes" : "no")})"; + Reply($"Server {s.Id} ({s.Name}): {(s.Active ? "active" : "not active")}, {force} - {s.Reason}."); + } + } + + /// <summary>/rc server names ilt [add|remove <pattern>]: Infinite Leaftide's world-name patterns.</summary> + private static void HandleServerNames(string[] words) + { + if (words.Length < 2 || !words[1].Equals(IltInfo.ServerId, StringComparison.OrdinalIgnoreCase)) + { + Reply("Usage: /rc server names ilt [add|remove <pattern>] (other servers' lists come from their plugins)."); + return; + } + if (words.Length >= 4) + { + bool add = words[2].Equals("add", StringComparison.OrdinalIgnoreCase); + if (!add && !words[2].Equals("remove", StringComparison.OrdinalIgnoreCase)) + { + Reply("Usage: /rc server names ilt [add|remove <pattern>]"); + return; + } + string pattern = string.Join(' ', words, 3, words.Length - 3); + bool changed = Plugins.EngineSettings.EditIltServerName(pattern, add); + Reply(changed + ? $"Infinite Leaftide world names: {(add ? "added" : "removed")} \"{pattern}\" (engine.json)." + : $"Infinite Leaftide world names: \"{pattern}\" was {(add ? "already there (or too long)" : "not there")}."); + IltInfo.Invalidate(); + UI.Sections.SectionRegistry.Invalidate(); + } + else if (words.Length == 3) + { + Reply("Usage: /rc server names ilt [add|remove <pattern>]"); + return; + } + Reply($"Infinite Leaftide lists: {IltInfo.ListsDescription}."); + } + /// <summary> /// /rc ilt: the Infinite Leaftide verdict, its signals and the lists in force. "on" / - /// "off" force it for this session (testing the ILT section anywhere); "auto" goes back - /// to detecting. Never saved; the lists are engine.json's IltServerNames / IltHosts. + /// "off" force it, saved for this character (this session only before login); "auto" goes + /// back to detecting. The lists are engine.json's IltServerNames / IltHosts. /// </summary> private static void HandleIltCommand(string args) { switch (args.Trim().ToLowerInvariant()) { - case "on": case "ilt": IltInfo.Override = IltInfo.Mode.ForceIlt; break; - case "off": case "other": IltInfo.Override = IltInfo.Mode.ForceOther; break; - case "auto": IltInfo.Override = IltInfo.Mode.Auto; break; + case "on": case "ilt": SetServerForce(IltInfo.ServerId, UI.Sections.ServerForce.On); break; + case "off": case "other": SetServerForce(IltInfo.ServerId, UI.Sections.ServerForce.Off); break; + case "auto": SetServerForce(IltInfo.ServerId, UI.Sections.ServerForce.Auto); break; case "": break; default: Reply("Usage: /rc ilt [auto|on|off]"); @@ -856,6 +1017,17 @@ internal static class RynthCoreChatCommands SetPanelOpen(title, show); } + /// <summary> + /// The command for a Mini Remote tab that moved out (2026.10.5.54): "character" (the generic + /// overview) is RynthOracle's Character tab. Null for a tab still in the Mini Remote, which + /// includes RynthILT's Leaftide tabs (Charms, Banking, Gear, Games): those stay RynthILT's. + /// </summary> + internal static string? MovedTabCommand(string tab) => tab.Trim().ToLowerInvariant() switch + { + "character" or "char" => "/ro character", + _ => null, + }; + private static bool IsVerb(string sub, string verb, out string args) { args = string.Empty; diff --git a/src/RynthCore.Engine/Compatibility/ServerInfo.cs b/src/RynthCore.Engine/Compatibility/ServerInfo.cs index 4f7a7a4..2ecf62b 100644 --- a/src/RynthCore.Engine/Compatibility/ServerInfo.cs +++ b/src/RynthCore.Engine/Compatibility/ServerInfo.cs @@ -10,8 +10,9 @@ // - the world name the server announced at login (AccountHooks, the // SendNotice_WorldName hook; not the launcher's own profile name); // - the Bank mod's custom player properties 9101-9103 (PropertyCaches). -// Unknown means not Aelrynth. "/rc server aelrynth|other|auto" overrides it -// for this session (testing), never saved. +// Unknown means not Aelrynth. "/rc server aelrynth|other|auto" (or the Mini +// Remote's Char section) overrides it, saved per character +// (UI/Sections/ServerForceStore). // // Threads: any. Re-evaluated at most once a second; each read in between is a // volatile load and a compare. Never touches AC (dictionary reads only). @@ -29,9 +30,11 @@ internal static class ServerInfo private const int RefreshMs = 1000; + /// <summary>The server id the override is saved under (UI/Sections).</summary> + public const string ServerId = "aelrynth"; + private static volatile ServerVerdict _verdict = ServerVerdict.Unknown; private static long _nextRefreshMs; - private static int _mode; // Mode private static int _hostRead; private static readonly object HostLock = new(); private static string _host = ""; @@ -49,13 +52,41 @@ internal static class ServerInfo /// <summary>Aelrynth's staging world (port 9030 / "Staging" world name). Any thread.</summary> public static bool IsStaging => Current.IsStaging; + /// <summary>The current character's saved override (session-only before login).</summary> public static Mode Override { - get => (Mode)Volatile.Read(ref _mode); - set + get => UI.Sections.ServerForceStore.Get(ServerId) switch { - Volatile.Write(ref _mode, (int)value); - Volatile.Write(ref _nextRefreshMs, 0); + UI.Sections.ServerForce.On => Mode.ForceAelrynth, + UI.Sections.ServerForce.Off => Mode.ForceOther, + _ => Mode.Auto, + }; + } + + /// <summary>Sets the override (saved per character); <paramref name="where"/> says where it went.</summary> + public static bool SetOverride(Mode mode, out string where) + { + var force = mode switch + { + Mode.ForceAelrynth => UI.Sections.ServerForce.On, + Mode.ForceOther => UI.Sections.ServerForce.Off, + _ => UI.Sections.ServerForce.Auto, + }; + bool ok = UI.Sections.ServerForceStore.Set(ServerId, force, out where); + Volatile.Write(ref _nextRefreshMs, 0); + return ok; + } + + /// <summary>Re-evaluates on the next read (the character or an override changed).</summary> + public static void Invalidate() => Volatile.Write(ref _nextRefreshMs, 0); + + /// <summary>What detection alone says (no override), for the Char section and /rc server.</summary> + public static ServerVerdict Detected + { + get + { + ReadHostOnce(); + return ServerDetect.Decide(_hostKind, _host, _port, AccountHooks.AnnouncedWorldName, _bankSeen); } } @@ -104,8 +135,8 @@ internal static class ServerInfo ServerVerdict v = Override switch { - Mode.ForceAelrynth => new ServerVerdict { IsAelrynth = true, Reason = "forced on with /rc server aelrynth (testing)" }, - Mode.ForceOther => new ServerVerdict { Reason = "forced off with /rc server other (testing)" }, + Mode.ForceAelrynth => new ServerVerdict { IsAelrynth = true, Reason = "forced on for this character (/rc server aelrynth auto undoes it)" }, + Mode.ForceOther => new ServerVerdict { Reason = "forced off for this character (/rc server aelrynth auto undoes it)" }, _ => ServerDetect.Decide(_hostKind, _host, _port, AccountHooks.AnnouncedWorldName, _bankSeen), }; _verdict = v; diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index b270f7f..a154142 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -182,6 +182,7 @@ internal static class SmartBoxHooks var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, uint>)_originalDispatchGameEventPtr; EnchantmentChange? enchantment = null; + bool answered = false; try { // Reject undersized payloads instead of clamping up: an inflated @@ -199,10 +200,19 @@ internal static class SmartBoxHooks ParseGameEvent(eventType, data, (uint)len); if ((eventType >= 0x02C2 && eventType <= 0x02C8) || eventType == 0x0312) enchantment = CaptureEnchantmentEvent(eventType, data, (uint)len); + // v85: a prompt a plugin armed an answer for is answered here instead of + // opening AC's dialog. + if (eventType == ConfirmationResponder.EventConfirmationRequest) + answered = ConfirmationResponder.OnRequest(data, (uint)len); } } catch { } + // AC's ConfirmationRequest handler returns 0 on every path, so an answered prompt + // returns the same without reaching it. + if (answered) + return 0; + uint status = pOriginal(thisPtr, data, size); // Enchantment events are queued AFTER the original ran: by then AC's diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index a5550e4..e08fe68 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -207,6 +207,9 @@ internal static class EngineLifecycle // Process-wide events: under CoreCLR they would hold this generation. Step("EntryPoint.UninstallManagedExceptionHandlers", EntryPoint.UninstallManagedExceptionHandlers); + // IAT slots aren't MinHook hooks: write them back before this generation unloads. + Step("DatFileShareHooks.Uninstall", Compatibility.DatFileShareHooks.Uninstall); + Step("MH_DisableHook(ALL)", () => { // DisableHook restores the original code at every hooked function — that's diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 76b81de..6d79c83 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -471,6 +471,19 @@ public static class EntryPoint return _imGuiNativeHandle; } + /// <summary> + /// Full path of <paramref name="dllName"/> in the engine's own folders (the ones + /// <see cref="PreloadNativeDll"/> searches), or null. Never Windows' search order. + /// </summary> + internal static string? FindNativeDll(string dllName) + { + string? engineDir = GetEngineDirectory(); + if (string.IsNullOrEmpty(engineDir)) return null; + foreach (string path in GetNativeDllCandidates(engineDir, dllName)) + if (File.Exists(path)) return path; + return null; + } + private static string[] GetNativeDllCandidates(string engineDir, string dllName) { var candidates = new List<string>(); @@ -569,41 +582,48 @@ public static class EntryPoint private static bool _serverMenusRegistered; /// <summary> - /// The server sections of the Char and Mini Remote menus (UI.ServerMenus): each server once, - /// then the items of the installed plugins that have windows for it. A server whose plugins - /// are all missing gets no items, so its section never shows. + /// The engine's own server items for the Mini Remote's sections and the menus + /// (UI/Sections/SectionRegistry): its windows that belong to one server, added only when + /// the plugin behind each is installed. Plugins add their own through their manifests. /// </summary> private static void RegisterServerMenus(bool rynthAi, bool rynthIlt) { if (_serverMenusRegistered) return; _serverMenusRegistered = true; - // Infinite Leaftide: IltInfo (host / world name lists, RynthILT's own verdict, or "/rc ilt on" - // for the session), with RynthILT loaded: every ILT window is RynthILT's (since 2026-10-13). - UI.ServerMenus.DefineServer("ilt", "Infinite Leaftide", static () => IltInfo.IsIlt && IltInfo.PluginLoaded, "/rc ilt on"); + // Infinite Leaftide (IltInfo: host / world-name lists, RynthILT's own verdict, or the + // per-character "/rc ilt on"). Every ILT window is RynthILT's (since 2026-10-13), so the + // engine adds them only when RynthILT is installed. + const string ilt = IltInfo.ServerId; if (rynthIlt && rynthAi) { // RynthILT's ILT tabs in RynthAi's Mini Remote (shown once the server reports each on). - // The Mini Remote's Quests and Pets tabs are universal: the Character half of the menus. - foreach ((string label, string tab) in new[] + // A RynthAi that doesn't publish sections gets these stand-ins; one that does lists them itself. + // Character (the generic overview) is RynthOracle's Character tab since 2026.10.5.54; + // the Leaftide tabs (Charms, Banking, Gear, Games) stay RynthILT's. + foreach ((string label, string tab, string section) in new[] { - ("Character", "character"), ("Banking", "banking"), ("Gear", "gear"), ("Charms", "charms"), ("Games", "games"), + ("Charms", "charms", "inventory"), ("Banking", "banking", "inventory"), + ("Gear", "gear", "inventory"), ("Games", "games", "fellowship"), }) { - UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem(label, "/rc miniremote tab " + tab, - $"The Mini Remote's {label} tab (RynthILT).", "tab:" + tab)); + UI.Sections.SectionRegistry.AddEngineItem(section, ilt, label, "/rc miniremote tab " + tab, + $"The Mini Remote's {label} tab (RynthILT).", unlessPlugin: "RynthAi"); } } if (rynthIlt) { - UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Guardian", "/rc guardian toggle", - "Temple of Enlightenment guardians: riddle answers and Give (RynthILT).")); - UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Bounties", "/rc bounties toggle", - "ACECustom bounties and your progress on each (RynthILT).")); - UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Progression", "/rc progression", - "XP planner, augmentations and enlightenment (the Skills panel's Progression tab; RynthILT).")); + // The engine's ILT panels, fed by RynthILT. + // Guardian sits with Progression (Temple of Enlightenment): Session Stats is session stats only. + UI.Sections.SectionRegistry.AddEngineItem("skills", ilt, "Guardian", "/rc guardian toggle", + "Temple of Enlightenment guardians: riddle answers and Give (RynthILT)."); + UI.Sections.SectionRegistry.AddEngineItem("skills", ilt, "Progression", "/rc progression", + "XP planner, augmentations and enlightenment (the Skills panel's Progression tab; RynthILT)."); + UI.Sections.SectionRegistry.AddEngineItem("combat", ilt, "Bounties", "/rc bounties toggle", + "ACECustom bounties and your progress on each (RynthILT)."); } UI.ServerMenus.PushToRynthAi = rynthAi; + UI.ServerMenus.PushToRynthIlt = rynthIlt; } private static bool HasPluginDll(string dllFileName) diff --git a/src/RynthCore.Engine/Hooking/MinHook.cs b/src/RynthCore.Engine/Hooking/MinHook.cs index bf0f758..5b10e8f 100644 --- a/src/RynthCore.Engine/Hooking/MinHook.cs +++ b/src/RynthCore.Engine/Hooking/MinHook.cs @@ -80,7 +80,7 @@ internal static unsafe class MinHook IntPtr module = GetModuleHandleW(LoaderDll); bool facade = module != IntPtr.Zero && GetProcAddress(module, "RcHooks_Version") != IntPtr.Zero; if (!facade) - module = NativeLibrary.Load(DLL, typeof(MinHook).Assembly, null); + module = LoadMinHookFromEngineFolders(); IntPtr Get(string name) { @@ -103,6 +103,19 @@ internal static unsafe class MinHook }; } + /// <summary> + /// minhook.x86.dll by full path from the engine's folders (where the early preload found it). + /// Never by bare name: Windows' search order (the AC client folder, the current directory, + /// PATH) would load a planted minhook.x86.dll into the client when ours is missing. + /// </summary> + private static IntPtr LoadMinHookFromEngineFolders() + { + string? path = EntryPoint.FindNativeDll(DLL); + if (path == null) + throw new DllNotFoundException($"{DLL} was not found beside the engine (other folders are not searched)."); + return NativeLibrary.Load(path); + } + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr GetModuleHandleW(string lpModuleName); diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index b12610a..e625a32 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -771,6 +771,10 @@ internal static class EngineFrameController Hud.MonsterHud.Draw(_uiScale, worldVisible: !D3D9.VideoPatch.SkipWorldThisFrame); // Video patch "all": the "rendering paused" banner (background list, under the panels). VideoPatchBanner.Draw(); + // Server verdicts, the plugins' section manifests and the servermenu push. Every + // frame, bar or not: with the bar hidden (the rail instead) nothing else ticks them, + // so Options > Diagnostics listed no servers and no server plugin was told it is active. + RynthCore.Engine.UI.ServerMenus.Tick(); if (ImGuiBar.Visible) ImGuiBar.Draw(_uiScale); ImGuiPanelHost.DrawAll(_uiScale); diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index a6c5ca8..4acd3c7 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -318,8 +318,7 @@ internal static class ImGuiBar public static void Draw(float s) { - // The bar draws every frame the ImGui shell is up: keep RynthAi's server menu current. - RynthCore.Engine.UI.ServerMenus.Tick(); + // ServerMenus.Tick runs from EngineFrameController every frame, bar shown or not. EnsureButtons(); int step = ChromeStep(out float factor); s *= factor; @@ -414,7 +413,7 @@ internal static class ImGuiBar ImGuiNET.ImGui.SetWindowPos(next); _userMoved = true; } - ImGuiNET.ImGui.SetItemTooltip(_tooltip); + SafeImGui.SetItemTooltip(_tooltip); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) ImGuiNET.ImGui.OpenPopup("##bar_menu"); PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.DotsSixVertical, rcPos, new Vector2(square.X * 0.8f, square.Y), RynthTheme.RcLabel); @@ -428,7 +427,7 @@ internal static class ImGuiBar if (ImGuiNET.ImGui.InvisibleButton("##barcollapse", caretSize)) RynthAiDashboardState.SetBarCollapsed(!collapsed); bool caretHot = ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(collapsed ? "Show the bar" : "Fold the bar to this button"); + SafeImGui.SetItemTooltip(collapsed ? "Show the bar" : "Fold the bar to this button"); PhosphorIcons.DrawCentered(dl, iconFont, collapsed ? PhosphorIcons.CaretRight : PhosphorIcons.CaretLeft, cPos, caretSize, caretHot ? RynthTheme.RcLabel : 0xFF9A9A9Au); if (collapsed) return; @@ -456,7 +455,7 @@ internal static class ImGuiBar if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !ImGuiPanelHost.IsOpen(b.Window.PanelKey)); else PanelRouter.Toggle(b.Title); } - ImGuiNET.ImGui.SetItemTooltip(b.Tooltip); // a plugin window's title arrives with '%' doubled (EnsureButtons) + SafeImGui.SetItemTooltip(b.Tooltip); } // The ILT section: one button, only on Infinite Leaftide with ILT panels registered @@ -470,7 +469,7 @@ internal static class ImGuiBar if (only != null) PanelRouter.Toggle(only); else ImGuiNET.ImGui.OpenPopup("##ilt_menu"); } - ImGuiNET.ImGui.SetItemTooltip(only != null ? "Infinite Leaftide: " + only : "Infinite Leaftide"); + SafeImGui.SetItemTooltip(only != null ? "Infinite Leaftide: " + only : "Infinite Leaftide"); } // Script windows (decision 2): one button with a menu, only while a ShowInBar @@ -530,7 +529,7 @@ internal static class ImGuiBar ImGuiNET.ImGui.SameLine(); if (IconButton("##popout", iconFont, popped ? PhosphorIcons.ArrowSquareIn : PhosphorIcons.ArrowSquareOut, square, RynthTheme.PopOutLabel)) SetPoppedOut(!popped); - ImGuiNET.ImGui.SetItemTooltip(popped ? "Dock the bar back into the game window." : "Pop the bar out into its own floating window."); + SafeImGui.SetItemTooltip(popped ? "Dock the bar back into the game window." : "Pop the bar out into its own floating window."); } /// <summary>The ILT panels the bar offers now: 0 off Infinite Leaftide or without RynthILT. AC thread.</summary> @@ -686,12 +685,12 @@ internal static class ImGuiBar ImGuiNET.ImGui.BeginDisabled(!canDown); if (IconButton(id + "_down", iconFont, PhosphorIcons.Minus, new Vector2(btn, btn), text)) delta = -1; ImGuiNET.ImGui.EndDisabled(); - ImGuiNET.ImGui.SetItemTooltip(downTip); + SafeImGui.SetItemTooltip(downTip); ImGuiNET.ImGui.SameLine(0, 4 * s); ImGuiNET.ImGui.BeginDisabled(!canUp); if (IconButton(id + "_up", iconFont, PhosphorIcons.Plus, new Vector2(btn, btn), text)) delta = 1; ImGuiNET.ImGui.EndDisabled(); - ImGuiNET.ImGui.SetItemTooltip(upTip); + SafeImGui.SetItemTooltip(upTip); ImGuiNET.ImGui.PopStyleVar(); ImGuiNET.ImGui.SameLine(0, 8 * s); ImGuiNET.ImGui.AlignTextToFramePadding(); @@ -769,8 +768,7 @@ internal static class ImGuiBar string title = w.Title.Length > 0 ? w.Title : w.Key; string icon = IconFor(title, out bool letter); string id = "##bar_sw" + w.Hash.ToString("X8"); - // The tooltip goes through SetItemTooltip, a format function: the plugin's text with '%' doubled. - list.Add(new ButtonInfo(title, id, icon, letter, title.Replace("%", "%%"), Window: w)); + list.Add(new ButtonInfo(title, id, icon, letter, title, Window: w)); } _buttons = list.ToArray(); _tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar size and rows. Ctrl+wheel over the bar: size."; diff --git a/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs b/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs index 0c3c8fb..9cea744 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs @@ -29,7 +29,7 @@ internal static class ImGuiFontTest ImGuiNET.ImGui.SetNextWindowSize(new Vector2(560, 520) * scale, ImGuiCond.FirstUseEver); if (ImGuiNET.ImGui.Begin("RynthCore font test##fonttest")) { - ImGuiNET.ImGui.TextDisabled($"scale {scale:0.##} atlas {ImGuiNET.ImGui.GetIO().Fonts.TexWidth}x{ImGuiNET.ImGui.GetIO().Fonts.TexHeight}"); + SafeImGui.TextDisabled($"scale {scale:0.##} atlas {ImGuiNET.ImGui.GetIO().Fonts.TexWidth}x{ImGuiNET.ImGui.GetIO().Fonts.TexHeight}"); for (UiFont f = 0; f < UiFont.Count; f++) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(f)); @@ -54,7 +54,7 @@ internal static class ImGuiFontTest ImGuiNET.ImGui.SameLine(); ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.ReloadLabel), "RL"); ImGuiNET.ImGui.SameLine(); - ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.PopOutLabel), PhosphorIcons.ArrowSquareOut); + SafeImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.PopOutLabel), PhosphorIcons.ArrowSquareOut); } ImGuiNET.ImGui.End(); } diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index e5b3f26..676b110 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -379,6 +379,7 @@ internal static class ImGuiPanelHost /// </summary> public static void DragWindowWithLastItem() { + if (_inEmbed) return; // embedded in another panel: that panel's window isn't this face's to move if (ImGuiPopOuts.InPopOutFrame) { // Popped out: the OS window moves (it follows the cursor from here on). @@ -394,6 +395,7 @@ internal static class ImGuiPanelHost /// <summary>Asks for a new window size (logical units), applied on the next frame it draws. Any thread.</summary> public static void RequestSize(string title, Vector2 logicalSize) { + if (_inEmbed) return; // an embedded copy must not resize the face's own window lock (Sync) { if (!Entries.TryGetValue(title, out Entry? entry)) return; @@ -409,6 +411,7 @@ internal static class ImGuiPanelHost /// </summary> public static void RequestPos(string title, Vector2 logicalPos) { + if (_inEmbed) return; lock (Sync) { if (!Entries.TryGetValue(title, out Entry? entry)) return; @@ -450,10 +453,12 @@ internal static class ImGuiPanelHost /// </summary> public static void DrawAll(float uiScale) { + _frameScale = uiScale; float placeScale = PlacementScale(); while (Requests.TryDequeue(out var req)) Apply(req.Title, req.Kind, placeScale); RemoveUnregistered(); + SweepEmbedded(); List<Entry> order; lock (Sync) order = DrawOrder; @@ -485,6 +490,7 @@ internal static class ImGuiPanelHost Entry? entry; lock (Sync) Entries.TryGetValue(title, out entry); if (entry == null || !entry.Shown || !entry.Popped) return; + _frameScale = uiScale; DrawPanel(entry, uiScale, PlacementScale(), display); } @@ -1025,6 +1031,148 @@ internal static class ImGuiPanelHost /// <summary>The panel whose face is drawing right now (names a text box's owner in the input log). AC thread.</summary> internal static string? DrawingTitle { get; private set; } + // ── Embedding: a face drawn inside another panel (the Mini Remote's sections) ── + + /// <summary>An embedded copy of a face: its own instance, so the face's own window is unaffected.</summary> + private sealed class EmbeddedFace + { + public required string Title; + public required IImGuiPanel Instance; + public long LastDrawnMs; + public int Failures; + public string? Error; + } + + /// <summary>Embedded copies by host + title. AC thread only (docked and pop-out frames both run there).</summary> + private static readonly Dictionary<string, EmbeddedFace> EmbeddedFaces = new(StringComparer.OrdinalIgnoreCase); + + /// <summary>An embedded copy not drawn for this long is hidden and dropped (its section was left).</summary> + private const long EmbedIdleMs = 750; + + /// <summary>Faces that can't be embedded: the hosts themselves.</summary> + private static readonly HashSet<string> NotEmbeddable = new(StringComparer.OrdinalIgnoreCase) { "Mini Remote" }; + + /// <summary>The UI scale of the frame being drawn (docked or popped). AC thread.</summary> + private static float _frameScale = 1f; + + /// <summary>True while an embedded copy draws: its window moves and size requests are ignored.</summary> + [ThreadStatic] private static bool _inEmbed; + + /// <summary>True when <paramref name="title"/> is registered and may be drawn inside another panel. Any thread.</summary> + public static bool CanEmbed(string title) => !NotEmbeddable.Contains(title) && HasFace(title); + + /// <summary>A registered face's default window size (logical units). Any thread.</summary> + public static bool TryGetDefaultSize(string title, out Vector2 size) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + size = entry?.Spec.DefaultSize ?? Vector2.Zero; + return entry != null; + } + + /// <summary> + /// Draws a copy of the face <paramref name="title"/> into the current window, in a child of + /// <paramref name="size"/> (pixels; 0 = fill). <paramref name="hostKey"/> separates the copies + /// of different hosts. The copy is created on first draw and dropped (OnHidden) once it + /// hasn't drawn for <see cref="EmbedIdleMs"/>. AC thread, inside a window. + /// </summary> + public static void DrawEmbedded(string hostKey, string title, Vector2 size) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + if (entry == null || NotEmbeddable.Contains(title)) + { + ImGuiNET.ImGui.TextDisabled("Not available."); + return; + } + + string key = hostKey + "\u001f" + title; + if (!EmbeddedFaces.TryGetValue(key, out EmbeddedFace? face)) + { + try + { + IImGuiPanel instance = entry.Factory(); + instance.OnShown(); + face = new EmbeddedFace { Title = title, Instance = instance }; + } + catch (Exception ex) + { + RynthLog.UI($"ImGuiPanelHost: embedding {title} failed - {ex.GetType().Name}: {ex.Message}"); + face = new EmbeddedFace { Title = title, Instance = new NullFace(), Error = $"{title} failed to open: {ex.Message}" }; + } + EmbeddedFaces[key] = face; + } + face.LastDrawnMs = Environment.TickCount64; + + PanelSpec spec = entry.Spec; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, spec.EdgeToEdge ? Vector2.Zero : new Vector2(6, 4) * _frameScale); + ImGuiWindowFlags flags = ImGuiWindowFlags.NoBackground | spec.BodyFlags; + if (spec.EdgeToEdge) flags |= ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse; + bool open = ImGuiNET.ImGui.BeginChild("##embed_" + title, size, ImGuiChildFlags.AlwaysUseWindowPadding, flags); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (!open) return; + if (face.Error != null) + { + // Never a format string: the error carries an exception message. + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1f, 0.4f, 0.3f, 1f)); + ImGuiNET.ImGui.PushTextWrapPos(0f); + ImGuiNET.ImGui.TextUnformatted(face.Error); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + return; + } + string? outer = DrawingTitle; + _inEmbed = true; + DrawingTitle = title; + try + { + face.Instance.Draw(); + } + catch (Exception ex) + { + face.Failures++; + RynthLog.UI($"ImGuiPanelHost: embedded {title}.Draw threw {ex.GetType().Name}: {ex.Message} ({face.Failures}/{MaxFailures})"); + if (face.Failures >= MaxFailures) + face.Error = $"{title} stopped drawing after repeated errors: {ex.Message}"; + } + finally + { + _inEmbed = false; + DrawingTitle = outer; + } + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + } + + /// <summary>Hides and drops embedded copies whose host stopped drawing them. AC thread.</summary> + private static void SweepEmbedded() + { + if (EmbeddedFaces.Count == 0) return; + long now = Environment.TickCount64; + List<string>? stale = null; + foreach (var kv in EmbeddedFaces) + if (now - kv.Value.LastDrawnMs > EmbedIdleMs) (stale ??= new List<string>()).Add(kv.Key); + if (stale == null) return; + foreach (string key in stale) + { + EmbeddedFace face = EmbeddedFaces[key]; + EmbeddedFaces.Remove(key); + try { face.Instance.OnHidden(); } + catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: embedded {face.Title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); } + } + } + + /// <summary>Stands in for a face that failed to open, so its error line can draw.</summary> + private sealed class NullFace : IImGuiPanel + { + public void Draw() { } + } + private static void DrawBody(Entry entry) { DrawingTitle = entry.Title; @@ -1247,7 +1395,7 @@ internal static class ImGuiPanelHost if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset")) PanelTextScale.ResetWindow(title); ImGuiNET.ImGui.EndDisabled(); - ImGuiNET.ImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)"); + SafeImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)"); ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.Button("Use for all windows")) PanelTextScale.UseForAll(step); diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs index 60f66f1..346132e 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs @@ -253,7 +253,7 @@ internal static class MonsterHudSettingsUi if (ImGuiNET.ImGui.IsItemHovered()) { ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); - if (tip != null) ImGuiNET.ImGui.SetTooltip(tip); + if (tip != null) SafeImGui.SetTooltip(tip); } if (clicked) value = radio || !value; dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), value ? ToggleOn : ToggleOff, 2); @@ -274,7 +274,7 @@ internal static class MonsterHudSettingsUi { BeginSliderRow(label, w); bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, "%.2fx", ImGuiSliderFlags.AlwaysClamp); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tip); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(tip); return EndSliderRow(changed); } diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs index bd5c87c..88847fc 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs @@ -245,7 +245,7 @@ internal static class PlayerPlate { ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeAll); if (_hover && !_dragging) - ImGuiNET.ImGui.SetTooltip(DragTip); + SafeImGui.SetTooltip(DragTip); } _wantsMouse = _hover || _dragging; } diff --git a/src/RynthCore.Engine/ImGui/Panels/BountiesFace.cs b/src/RynthCore.Engine/ImGui/Panels/BountiesFace.cs index da71405..f06c60b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/BountiesFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/BountiesFace.cs @@ -150,7 +150,7 @@ internal sealed class BountiesFace : IImGuiPanel if (Button("##bounty_hideqb", hideLabel, new Vector2(x, p.Y), new Vector2(hw, 22), d.HideQbLocked ? OnText : Mute, d.HideQbLocked ? OnBg : BtnFill)) BountiesCommands.Set("hideqblocked", !d.HideQbLocked); - if (d.HiddenCount > 0) ImGuiNET.ImGui.SetItemTooltip($"{d.HiddenCount} hidden"); + if (d.HiddenCount > 0) SafeImGui.SetItemTooltip($"{d.HiddenCount} hidden"); x += hw + 4; const string sortLabel = "Closest first"; @@ -263,7 +263,7 @@ internal sealed class BountiesFace : IImGuiPanel BountyRowStatus.NeedsQb => $"\nNeeds {N0(r.QbRequired)} QB; you have {N0(r.QbHave)}.", _ => string.Empty, }; - ImGuiNET.ImGui.SetTooltip($"{r.Where}: {N0(r.Amount)} {r.Item}\n{every}{detail}"); + SafeImGui.SetTooltip($"{r.Where}: {N0(r.Amount)} {r.Item}\n{every}{detail}"); } NextLine(p, RowH); } diff --git a/src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs b/src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs index 52f9dab..bb81056 100644 --- a/src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs @@ -369,23 +369,23 @@ internal sealed class CharactersFace : IImGuiPanel bool canFollow = me.Length > 0; if (!_menuSelf && !_menuLoggedOut) { - ImGuiNET.ImGui.TextDisabled(_menuName); + SafeImGui.TextDisabled(_menuName); if (ImGuiNET.ImGui.MenuItem("Select", "", false, _menuInView && _menuId != 0)) AcMainThreadQueue.EnqueueOverlaySelect(_menuId); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Follow me", "", false, canFollow && !_menuOtherWorld)) CharactersCommands.Tell(_menuName, "/ra follow " + me); - ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow {me}"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow {me}"); if (ImGuiNET.ImGui.MenuItem("Stop following")) CharactersCommands.Tell(_menuName, "/ra follow off"); - ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow off"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow off"); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Start macro")) CharactersCommands.Tell(_menuName, "/ra start"); - ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra start"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra start"); if (ImGuiNET.ImGui.MenuItem("Stop macro")) CharactersCommands.Tell(_menuName, "/ra stop"); - ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra stop"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra stop"); ImGuiNET.ImGui.Separator(); } if (ImGuiNET.ImGui.MenuItem("Everyone: follow me", "", false, canFollow)) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index 9ebf691..368771c 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -238,7 +238,7 @@ internal sealed class ChatFace : IImGuiPanel else _drawers.Toggle(_channels); } if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip)) - ImGuiNET.ImGui.SetTooltip(mention ? "Channels (someone mentioned you)" : "Channels: pick a tab, see what's unread"); + SafeImGui.SetTooltip(mention ? "Channels (someone mentioned you)" : "Channels: pick a tab, see what's unread"); float ty = start.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; dl.PushClipRect(start, start + new Vector2(bw - caretW - 6 - (badge != null ? badgeW + 4 : 0), h), true); dl.AddText(new Vector2(start.X + 6, ty), Text, label); @@ -1139,7 +1139,7 @@ internal sealed class ChatFace : IImGuiPanel } ImGuiNET.ImGui.SameLine(); Label(kind.Label, RynthTheme.Argb(argb)); - ImGuiNET.ImGui.SetItemTooltip(kind.Hint + (set ? "" : kind.Key.StartsWith(ChatLineColors.TabPrefix, StringComparison.Ordinal) + SafeImGui.SetItemTooltip(kind.Hint + (set ? "" : kind.Key.StartsWith(ChatLineColors.TabPrefix, StringComparison.Ordinal) ? "\nThe built-in colour." : $"\nNot set: the {kind.Tab} tab's colour.")); if (set) { diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 7c75c41..68b6ebb 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -208,7 +208,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel ImGuiNET.ImGui.PushID(p.Id); bool enabled = p.Enabled; if (ImGuiNET.ImGui.Checkbox(p.Label, ref enabled)) { p.Enabled = enabled; ChatModel.FiltersChanged(); } - ImGuiNET.ImGui.SetItemTooltip(p.Description + "\nExample: " + p.Example); + SafeImGui.SetItemTooltip(p.Description + "\nExample: " + p.Example); ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, rowW * 0.6f)); string tabText = (p.Tab.Length == 0 ? "hide" : "to " + p.Tab) + Caret; if (ImGuiNET.ImGui.SmallButton(tabText)) @@ -260,7 +260,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 16, p.Y + 1)); bool on = r.Enabled; if (ImGuiNET.ImGui.Checkbox("##on", ref on)) { r.Enabled = on; ChatModel.FiltersChanged(); } - ImGuiNET.ImGui.SetItemTooltip(on ? "Rule on (click to turn off)" : "Rule off (click to turn on)"); + SafeImGui.SetItemTooltip(on ? "Rule on (click to turn off)" : "Rule off (click to turn on)"); const float btn = 22; float x = p.X + 42; @@ -275,7 +275,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel moded.Recompile(); ChatModel.FiltersChanged(); }, 120); - ImGuiNET.ImGui.SetItemTooltip(ModeHelp[modeIdx]); + SafeImGui.SetItemTooltip(ModeHelp[modeIdx]); x += modeW + 4; float patW = Math.Max(80, card.X + rowW - 4 - 3 * (btn + 2) - 4 - x); if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, ModeHints[modeIdx], out bool patActive)) @@ -323,7 +323,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel if (rule.Action == ChatRuleAction.Color && rule.ColorMode == ChatColorMode.None) rule.ColorMode = ChatColorMode.Line; ChatModel.FiltersChanged(); }, 140); - ImGuiNET.ImGui.SetItemTooltip(ActionHelp[action]); + SafeImGui.SetItemTooltip(ActionHelp[action]); if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy) { diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs index 8b8c4f8..2a13715 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs @@ -116,7 +116,7 @@ internal sealed class DamageDetailFace : IImGuiPanel // ── Header ─────────────────────────────────────────────────────── string name = d != null && d.Name.Length > 0 ? d.Name : _selectedName; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(Vec(Teal), isDefault ? "DEFAULT" : name); + SafeImGui.TextColored(Vec(Teal), isDefault ? "DEFAULT" : name); ImGuiNET.ImGui.PopFont(); if (isDefault) { @@ -128,17 +128,17 @@ internal sealed class DamageDetailFace : IImGuiPanel } else if (d == null) { - ImGuiNET.ImGui.TextColored(Vec(Dim), _detail != null && !_detail.Bound ? "Waiting for RynthAi…" : "Loading…"); + SafeImGui.TextColored(Vec(Dim), _detail != null && !_detail.Bound ? "Waiting for RynthAi…" : "Loading…"); } else { ImGuiNET.ImGui.SameLine(); - ImGuiNET.ImGui.TextColored(Vec(Dim), "wcid " + wcid.ToString(CultureInfo.InvariantCulture)); + SafeImGui.TextColored(Vec(Dim), "wcid " + wcid.ToString(CultureInfo.InvariantCulture)); // Aelrynth only: which difficulty tier these numbers are (the Damage panel's chip picks it). if (UiSources.Damage.Current?.Value.Tier is { Show: true } tier) { ImGuiNET.ImGui.SameLine(); - ImGuiNET.ImGui.TextColored(Vec(tier.View == tier.Current ? Teal : Gold), + SafeImGui.TextColored(Vec(tier.View == tier.Current ? Teal : Gold), tier.View <= 0 ? "· Tier 0 (real Dereth)" : "· Tier " + tier.View.ToString(CultureInfo.InvariantCulture)); ImGuiNET.ImGui.SetItemTooltip("HP, casts to kill, seconds per kill, hits and damage taken are this difficulty tier's.\n" + "Damage per cast and weaknesses are the same at every tier. Change it on the Damage panel."); @@ -146,7 +146,7 @@ internal sealed class DamageDetailFace : IImGuiPanel string hp = d.Hp > 0 ? $"HP {d.Hp:N0} ({d.HpSrc})" : "HP unknown"; string sec = d.SecKill > 0 ? $"{d.SecKill:0.0} s per kill" : "no timed kills yet"; string hit = d.HitRate >= 0 ? $"{d.HitRate * 100:0}% hits" : "no hits yet"; - ImGuiNET.ImGui.TextColored(Vec(White), $"{hp} · {sec} · {hit}"); + SafeImGui.TextColored(Vec(White), $"{hp} · {sec} · {hit}"); float bw = ImGuiNET.ImGui.CalcTextSize(RemoveLabel).X + 16; ImGuiNET.ImGui.SameLine(); @@ -158,7 +158,7 @@ internal sealed class DamageDetailFace : IImGuiPanel ImGuiNET.ImGui.SetItemTooltip("Take this monster off the Damage panel: its learned numbers and your settings for it. It comes back if you meet it again."); if (_confirmRemove) { - ImGuiNET.ImGui.TextColored(Vec(Gold), "Remove " + name + " and everything learned about it?"); + SafeImGui.TextColored(Vec(Gold), "Remove " + name + " and everything learned about it?"); ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.SmallButton("Remove##yes")) { @@ -191,7 +191,7 @@ internal sealed class DamageDetailFace : IImGuiPanel Rule? rule = _rules?.FindRule(name); if (rule != null) _renaming = null; ImGuiNET.ImGui.PushTextWrapPos(0); - ImGuiNET.ImGui.TextColored(Vec(Dim), rule == null + SafeImGui.TextColored(Vec(Dim), rule == null ? (_rules == null || _renaming == name ? "Loading…" : "There is no rule with this name (deleted?).") : "A name rule: used for every monster whose name contains \"" + name + "\"" + (string.IsNullOrWhiteSpace(rule.MatchExpression) ? "" : " and its match expression is true") @@ -205,7 +205,7 @@ internal sealed class DamageDetailFace : IImGuiPanel _confirmRemove = true; ImGuiNET.ImGui.SetItemTooltip("Delete this rule. Monsters it covered go back to Default (or another rule that matches)."); if (!_confirmRemove) return; - ImGuiNET.ImGui.TextColored(Vec(Gold), "Delete the rule " + name + "?"); + SafeImGui.TextColored(Vec(Gold), "Delete the rule " + name + "?"); ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.SmallButton("Delete##yes")) { @@ -237,7 +237,7 @@ internal sealed class DamageDetailFace : IImGuiPanel ImGuiNET.ImGui.TextColored(Vec(Dim), "Nothing known yet: not in the server data, no creature type, nothing learned."); return; } - ImGuiNET.ImGui.TextColored(Vec(Dim), "Damage it takes from each element (1.0 = full, 0.5 = half), from " + d.WeakSrc + "."); + SafeImGui.TextColored(Vec(Dim), "Damage it takes from each element (1.0 = full, 0.5 = half), from " + d.WeakSrc + "."); float labelW = ImGuiNET.ImGui.CalcTextSize("Lightning ").X; float barW = Math.Max(80, ImGuiNET.ImGui.GetContentRegionAvail().X - labelW - ImGuiNET.ImGui.CalcTextSize(" 0.00x").X - 8); double top = 1.0; @@ -356,9 +356,9 @@ internal sealed class DamageDetailFace : IImGuiPanel if (!nameRule) { - ImGuiNET.ImGui.TextColored(Vec(custom || isDefault ? Gold : Dim), + SafeImGui.TextColored(Vec(custom || isDefault ? Gold : Dim), isDefault ? "Applies to every monster set to Default." : custom ? "Custom settings for this monster." : "Following Default (a change here gives it its own settings)."); - ImGuiNET.ImGui.TextColored(Vec(Dim), DebuffsHint); + SafeImGui.TextColored(Vec(Dim), DebuffsHint); if (custom) { ImGuiNET.ImGui.SameLine(); @@ -439,7 +439,7 @@ internal sealed class DamageDetailFace : IImGuiPanel { ImGuiNET.ImGui.SameLine(0, 10); ImGuiNET.ImGui.AlignTextToFramePadding(); - ImGuiNET.ImGui.TextColored(Vec(Dim), "casts " + casts + (view.UseRing ? ", Ring when enough are near" : "")); + SafeImGui.TextColored(Vec(Dim), "casts " + casts + (view.UseRing ? ", Ring when enough are near" : "")); ImGuiNET.ImGui.SetItemTooltip("With several shapes on, the first of Arc, Streak, Blast, Bolt is cast.\n" + "Ring replaces it when at least Min Ring Targets monsters are within Ring Range (Settings)."); } @@ -486,7 +486,7 @@ internal sealed class DamageDetailFace : IImGuiPanel private static void Combo(string label, string id, string[] items, string current, Action<string> onPick, string tip) { ImGuiNET.ImGui.AlignTextToFramePadding(); - ImGuiNET.ImGui.TextColored(Vec(Dim), label); + SafeImGui.TextColored(Vec(Dim), label); ImGuiNET.ImGui.SameLine(); ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("Dual wield").X + 34); if (ImGuiNET.ImGui.BeginCombo(id, current)) @@ -497,7 +497,7 @@ internal sealed class DamageDetailFace : IImGuiPanel onPick(v); ImGuiNET.ImGui.EndCombo(); } - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } private const string RemoveLabel = PhosphorIcons.Trash + " Remove monster"; @@ -506,7 +506,7 @@ internal sealed class DamageDetailFace : IImGuiPanel private static void ToggleRow(string label, (string Field, string Label, string Tip)[] defs, Rule view, string name) { - ImGuiNET.ImGui.TextColored(Vec(Dim), label); + SafeImGui.TextColored(Vec(Dim), label); float h = ImGuiNET.ImGui.GetFrameHeight(); foreach (var (field, text, tip) in defs) { @@ -518,7 +518,7 @@ internal sealed class DamageDetailFace : IImGuiPanel if (ImGuiNET.ImGui.InvisibleButton("##t_" + field, size)) DamageCommands.EditRule(name, rule => DamageCommands.FlipToggle(rule, field)); bool hot = ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); var dl = ImGuiNET.ImGui.GetWindowDrawList(); dl.AddRectFilled(p, p + size, hot ? FaceKit.Lighten(EntryBg) : EntryBg, 2); dl.AddRect(p, p + size, EntryBorder, 2); @@ -545,7 +545,7 @@ internal sealed class DamageDetailFace : IImGuiPanel private static void Cell(string text) { ImGuiNET.ImGui.TableNextColumn(); - ImGuiNET.ImGui.TextColored(Vec(White), text); + SafeImGui.TextColored(Vec(White), text); } private static Vector4 Vec(uint abgr) => ImGuiNET.ImGui.ColorConvertU32ToFloat4(abgr); diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs index 65c3152..2772a57 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs @@ -465,7 +465,7 @@ internal sealed class DamageFace : IImGuiPanel OpenPicker(new Vector2(x, y + 22), t.Following ? FollowTier : (uint)t.View, id => DamageCommands.SetViewTier(id == FollowTier ? -1 : (int)id)); } - ImGuiNET.ImGui.SetItemTooltip( + SafeImGui.SetItemTooltip( "Aelrynth's awakened worlds and scaled dungeons have the same monsters, with " + $"{t.Percent.ToString("0.#", CultureInfo.InvariantCulture)}% more health, skills and damage per tier.\n" + "HP, kills, casts to kill, seconds per kill and hit rate here are this tier's; damage per cast,\n" + @@ -527,7 +527,7 @@ internal sealed class DamageFace : IImGuiPanel if (all == null || count == 0) { ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), all == null + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), all == null ? " Monster rules not loaded yet." : " No name rules yet: add one below."); } else @@ -559,7 +559,7 @@ internal sealed class DamageFace : IImGuiPanel string name = r.Name; if (NameLink("##rn", name, new Vector2(p.X + 4, p.Y), nameW - 8, met ? White : Gold, ImGuiFonts.Get(UiFont.Ui11))) OpenRule(name); - ImGuiNET.ImGui.SetItemTooltip(met + SafeImGui.SetItemTooltip(met ? "This monster's own settings (wcid " + wcid.ToString(CultureInfo.InvariantCulture) + "). Click for its details." : "Click to edit this rule."); float x = p.X + nameW; @@ -576,7 +576,7 @@ internal sealed class DamageFace : IImGuiPanel { ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y)); ImGuiNET.ImGui.InvisibleButton("##rx", new Vector2(exprW, RowH)); - ImGuiNET.ImGui.SetItemTooltip("Match expression: " + r.MatchExpression); + SafeImGui.SetItemTooltip("Match expression: " + r.MatchExpression); } x += exprW; @@ -592,7 +592,7 @@ internal sealed class DamageFace : IImGuiPanel if (armed) { DamageCommands.ResetRule(name); _armedDelete = ""; } else _armedDelete = name; } - ImGuiNET.ImGui.SetItemTooltip(armed ? "Click again to delete " + name : "Delete this rule (click twice)"); + SafeImGui.SetItemTooltip(armed ? "Click again to delete " + name : "Delete this rule (click twice)"); ImGuiNET.ImGui.PopID(); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH)); @@ -686,7 +686,7 @@ internal sealed class DamageFace : IImGuiPanel SortShown(); } if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); - ImGuiNET.ImGui.SetItemTooltip("Sort by " + Headers[c]); + SafeImGui.SetItemTooltip("Sort by " + Headers[c]); string label = Headers[c] + (_sortCol == c ? (_sortDesc ? SortDown : SortUp) : ""); dl.AddText(bold, bold.FontSize, new Vector2(p.X + ColX[c] + 4, p.Y + (RowH - bold.FontSize) * 0.5f), _sortCol == c ? Teal : White, label); @@ -714,7 +714,7 @@ internal sealed class DamageFace : IImGuiPanel bool filtering = _filterWid != 0 || _searchText.Length > 0; bool anyData = _view.Rows.Exists(r => !r.IsDefault); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), anyData && filtering + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), anyData && filtering ? " No monsters match the current filter." : " No monsters yet: fight some and they show up here."); } @@ -788,7 +788,7 @@ internal sealed class DamageFace : IImGuiPanel if (NameLink("##name", t.NameShown, new Vector2(p.X + ColX[ColMonster] + 22, p.Y), ColW[ColMonster] - 24, custom ? Gold : White, ImGuiFonts.Get(UiFont.Ui11))) DamageDetailFace.Show(r.Wcid, r.Name); - ImGuiNET.ImGui.SetItemTooltip(t.NameTip); + SafeImGui.SetItemTooltip(t.NameTip); PrioCell(r.Key, r.Name, t.PrioCopyFrom, t, p); HpCell(r, p); @@ -798,7 +798,7 @@ internal sealed class DamageFace : IImGuiPanel dl.AddText(new Vector2(p.X + ColX[ColWeak] + 4, ty), White, Fit(t.WeakTop, ColW[ColWeak] - 8)); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColWeak], p.Y)); ImGuiNET.ImGui.InvisibleButton("##weak", new Vector2(ColW[ColWeak], RowH)); - ImGuiNET.ImGui.SetItemTooltip(r.Weak + "\nDamage taken: 1.0 = full, 0.5 = half. From " + r.WeakSrc + SafeImGui.SetItemTooltip(r.Weak + "\nDamage taken: 1.0 = full, 0.5 = half. From " + r.WeakSrc + ".\nAuto spells, weapons and summons use the first element this character has."); } else @@ -841,7 +841,7 @@ internal sealed class DamageFace : IImGuiPanel dl.AddText(new Vector2(p.X + ColX[ColSec] + 4, ty), r.SecKill > 0 ? White : Dim, t.Sec); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColSec], p.Y)); ImGuiNET.ImGui.InvisibleButton("##sec", new Vector2(ColW[ColSec], RowH)); - ImGuiNET.ImGui.SetItemTooltip(t.SecTip); + SafeImGui.SetItemTooltip(t.SecTip); DebuffCell(r.Name, p, ty); @@ -851,7 +851,7 @@ internal sealed class DamageFace : IImGuiPanel _removeName = r.Name; _removeOpen = true; } - ImGuiNET.ImGui.SetItemTooltip("Remove " + r.Name + " from this list (asks first)."); + SafeImGui.SetItemTooltip("Remove " + r.Name + " from this list (asks first)."); ImGuiNET.ImGui.PopID(); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH)); @@ -967,7 +967,7 @@ internal sealed class DamageFace : IImGuiPanel WriteUtf8(_customBuf, view.CustomDebuffs ?? ""); _debuffOpen = true; } - ImGuiNET.ImGui.SetItemTooltip("Debuffs to cast on " + name); + SafeImGui.SetItemTooltip("Debuffs to cast on " + name); if (view == null) return; string marks = DamageCommands.DebuffMarks(view); var dl = ImGuiNET.ImGui.GetWindowDrawList(); @@ -976,7 +976,7 @@ internal sealed class DamageFace : IImGuiPanel { ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bp.X + 22, p.Y)); ImGuiNET.ImGui.InvisibleButton("##dmarks", new Vector2(Math.Max(1, ColW[ColDebuffs] - 26), RowH)); - ImGuiNET.ImGui.SetItemTooltip(DebuffTip(view)); + SafeImGui.SetItemTooltip(DebuffTip(view)); } } @@ -1012,7 +1012,7 @@ internal sealed class DamageFace : IImGuiPanel Rule? view = RuleFor(name, out bool custom); bool isDefault = name.Equals("Default", StringComparison.OrdinalIgnoreCase); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), "Debuffs · " + name); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), "Debuffs · " + name); ImGuiNET.ImGui.PopFont(); if (view == null) { @@ -1021,7 +1021,7 @@ internal sealed class DamageFace : IImGuiPanel return; } ImGuiNET.ImGui.PushTextWrapPos(0); - ImGuiNET.ImGui.TextColored((custom || isDefault ? RynthTheme.Vec(0xFFFFD16A) : RynthTheme.VecOf(RynthTheme.MuteAlt)), + SafeImGui.TextColored((custom || isDefault ? RynthTheme.Vec(0xFFFFD16A) : RynthTheme.VecOf(RynthTheme.MuteAlt)), isDefault ? "Every monster set to Default uses these." : custom ? "This monster's own debuffs." : "Following Default: a change here gives it its own."); ImGuiNET.ImGui.PopTextWrapPos(); @@ -1034,7 +1034,7 @@ internal sealed class DamageFace : IImGuiPanel string f = field; DamageCommands.EditRule(name, rule => rule.SetToggle(f, v)); } - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), "Extra Vuln"); @@ -1173,7 +1173,7 @@ internal sealed class DamageFace : IImGuiPanel bool commit = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); ImGuiNET.ImGui.PopStyleVar(); ImGuiNET.ImGui.PopStyleColor(2); - ImGuiNET.ImGui.SetItemTooltip(t.PrioTip + "\nType a number, Enter to save."); + SafeImGui.SetItemTooltip(t.PrioTip + "\nType a number, Enter to save."); if (!commit) return; if (int.TryParse(Utf8(e.Buffer).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int typed)) @@ -1322,7 +1322,7 @@ internal sealed class DamageFace : IImGuiPanel if (ropen) { ImGuiNET.ImGui.PushTextWrapPos(0); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Remove " + _removeName + "?"); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Remove " + _removeName + "?"); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Its learned numbers and your settings for it (weapon, offhand, pet, HP) are deleted. It comes back if you meet it again."); diff --git a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs index 8e5013b..51b5510 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs @@ -129,7 +129,7 @@ internal abstract class DashboardDrawer 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); + SafeImGui.SetItemTooltip(closeTip); return y + th + 4 * k; } } @@ -388,7 +388,7 @@ internal sealed class DashboardDrawers bool rightClicked = d.CanMove && ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right); // 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) + (d.CanMove ? MoveHint : "")); + SafeImGui.SetTooltip(open ? d.HideTip : d.TabTooltip(right) + (d.CanMove ? MoveHint : "")); if (clicked) Toggle(d); if (rightClicked) ImGuiNET.ImGui.OpenPopup(d.SideMenuId); diff --git a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs index 3374452..67d392a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs @@ -879,7 +879,7 @@ internal sealed class DungeonMapFace : IImGuiPanel return; } int i = _menuPt; - ImGuiNET.ImGui.TextDisabled($"Point {i} {TypeName(nav.Points[i].Type)}"); + SafeImGui.TextDisabled($"Point {i} {TypeName(nav.Points[i].Type)}"); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Delete")) { diff --git a/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs b/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs index edfa6ac..7476bf3 100644 --- a/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs @@ -141,7 +141,7 @@ internal sealed class HotkeysSettingsUi ImGuiNET.ImGui.SetCursorScreenPos(p); if (ImGuiNET.ImGui.InvisibleButton("##on", new Vector2(14, 16))) HotkeyService.Replace(i, b with { Enabled = !b.Enabled }); - ImGuiNET.ImGui.SetItemTooltip(b.Enabled ? "On. Click to switch this hotkey off." : "Off. Click to switch this hotkey on."); + SafeImGui.SetItemTooltip(b.Enabled ? "On. Click to switch this hotkey off." : "Off. Click to switch this hotkey on."); dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), b.Enabled ? ToggleOn : ToggleOff, 2); dl.AddText(bold, bold.FontSize, p + new Vector2(18, 1), b.Enabled ? Amber : Mute, b.Combo.ToString()); @@ -153,7 +153,7 @@ internal sealed class HotkeysSettingsUi // The full text on hover (a long chat command is clipped). ImGuiNET.ImGui.SetCursorScreenPos(p + new Vector2(18, 0)); ImGuiNET.ImGui.InvisibleButton("##what", new Vector2(Math.Max(1, textRight - p.X - 18), rowH)); - ImGuiNET.ImGui.SetItemTooltip(b.Combo + ": " + what + (b.Enabled ? "" : " (off)")); + SafeImGui.SetItemTooltip(b.Combo + ": " + what + (b.Enabled ? "" : " (off)")); float x = p.X + w - 4 * 20; if (IconButton("##up", new Vector2(x, p.Y), PhosphorIcons.CaretUp, i > 0)) @@ -237,7 +237,7 @@ internal sealed class HotkeysSettingsUi else { HotkeyService.BeginCapture(); _waitingForKey = true; } } ImGuiNET.ImGui.PopStyleColor(); - ImGuiNET.ImGui.SetItemTooltip(_waitingForKey ? "Waiting for a key. Click again or press Esc to stop." : "Click, then press the key combination."); + SafeImGui.SetItemTooltip(_waitingForKey ? "Waiting for a key. Click again or press Esc to stop." : "Click, then press the key combination."); if (_waitingForKey && HotkeyService.CaptureNote.Length > 0) Warning(HotkeyService.CaptureNote, w); @@ -256,7 +256,7 @@ internal sealed class HotkeysSettingsUi ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); bool open = ImGuiNET.ImGui.BeginCombo("##action", current, ImGuiComboFlags.HeightLarge); ImGuiNET.ImGui.PopStyleColor(3); - if (!open && picked is { Tip.Length: > 0 }) ImGuiNET.ImGui.SetItemTooltip(picked.Tip); + if (!open && picked is { Tip.Length: > 0 }) SafeImGui.SetItemTooltip(picked.Tip); if (open) { if (ImGuiNET.ImGui.Selectable(ChatCommandItem, isCommand)) _editAction = HotkeyActions.Command; @@ -281,7 +281,7 @@ internal sealed class HotkeysSettingsUi if (ImGuiNET.ImGui.Selectable((a.Group.Length > 0 ? " " : "") + a.Name + "##" + a.Id, string.Equals(a.Id, _editAction, StringComparison.OrdinalIgnoreCase))) _editAction = a.Id; - if (a.Tip.Length > 0) ImGuiNET.ImGui.SetItemTooltip(a.Tip); + if (a.Tip.Length > 0) SafeImGui.SetItemTooltip(a.Tip); } ImGuiNET.ImGui.EndCombo(); } @@ -332,7 +332,7 @@ internal sealed class HotkeysSettingsUi } ImGuiNET.ImGui.EndDisabled(); if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) - ImGuiNET.ImGui.SetTooltip(!canSave + SafeImGui.SetTooltip(!canSave ? (_editCombo.IsEmpty || _waitingForKey ? "Pick a key first." : !paramOk ? $"Pick the {picked?.Param?.ToLowerInvariant() ?? "value"} first." : "Type the chat command (starting with /).") @@ -367,7 +367,7 @@ internal sealed class HotkeysSettingsUi bool typing = ImGuiNET.ImGui.IsItemActive(); ImGuiNET.ImGui.PopStyleVar(); ImGuiNET.ImGui.PopStyleColor(3); - ImGuiNET.ImGui.SetItemTooltip(meta ? "The state's name, as in the meta (the case doesn't matter)." : a.Tip); + SafeImGui.SetItemTooltip(meta ? "The state's name, as in the meta (the case doesn't matter)." : a.Tip); if (states.Count > 0) { @@ -404,7 +404,7 @@ internal sealed class HotkeysSettingsUi ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); ImGuiNET.ImGui.TextUnformatted(text); ImGuiNET.ImGui.PopStyleColor(); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } private static void Section(string text, float w) diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs index f8dd9f9..b2a46d8 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs @@ -126,7 +126,7 @@ internal sealed partial class InventoryFace : "Filter by item attributes (armor level, ratings, spells, slot...)"; if (on && _unidentified.Count > 0) tip += "\n" + _unidentified.Count.ToString(CultureInfo.InvariantCulture) + " hidden until identified."; - ImGuiNET.ImGui.SetTooltip(tip); + SafeImGui.SetTooltip(tip); } // ── The editor popup ──────────────────────────────────────────────── @@ -257,11 +257,11 @@ internal sealed partial class InventoryFace InventoryAttributeFilter.SetAttr(rule, a.Id); AttrChanged(); } - ImGuiNET.ImGui.SetItemTooltip(a.Tip); + SafeImGui.SetItemTooltip(a.Tip); } ImGuiNET.ImGui.EndCombo(); } - ImGuiNET.ImGui.SetItemTooltip(info.Tip); + SafeImGui.SetItemTooltip(info.Tip); info = InventoryAttributeFilter.Info(rule.Attr); ImGuiNET.ImGui.SameLine(); diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs index 7fa456f..8b60e2d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs @@ -238,10 +238,10 @@ internal sealed partial class InventoryFace var bMinus = new Vector2(bPlus.X - btn - 2 * s, b2.Y); if (TitleToggle("##inv_smaller", PhosphorIcons.Minus, bMinus, btn, false)) InventorySettingsStore.StepSize(-1); - ImGuiNET.ImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)"); + SafeImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)"); if (TitleToggle("##inv_bigger", PhosphorIcons.Plus, bPlus, btn, false)) InventorySettingsStore.StepSize(+1); - ImGuiNET.ImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)"); + SafeImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)"); if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, b1, btn, InventorySettingsStore.ShowTools)) { // Closing the search / filter row shows every item again. @@ -729,7 +729,7 @@ internal sealed partial class InventoryFace if (hovered && hoverCell >= 0 && hoverCell < items.Length) { VaultItem hot = items[hoverCell]; - ImGuiNET.ImGui.SetTooltip(hot.Stack > 1 ? $"{hot.Name} ({hot.Stack:N0})" : hot.Name); + SafeImGui.SetTooltip(hot.Stack > 1 ? $"{hot.Name} ({hot.Stack:N0})" : hot.Name); if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) { _vaultCtx = hot; @@ -753,7 +753,7 @@ internal sealed partial class InventoryFace if (it == null) ImGuiNET.ImGui.CloseCurrentPopup(); else { - ImGuiNET.ImGui.TextDisabled(it.Name); + SafeImGui.TextDisabled(it.Name); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Withdraw", "", false, VaultFeed.Available)) VaultFeed.Withdraw(it); diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs index 05431fe..1e275cd 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs @@ -228,8 +228,8 @@ internal sealed partial class InventoryFace ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); ImGuiNET.ImGui.TextUnformatted(_confirmTitle); ImGuiNET.ImGui.PopStyleColor(); - foreach (string line in _confirmNames) ImGuiNET.ImGui.BulletText(line); - if (_confirmNote.Length > 0) ImGuiNET.ImGui.TextDisabled(_confirmNote); + foreach (string line in _confirmNames) SafeImGui.BulletText(line); + if (_confirmNote.Length > 0) SafeImGui.TextDisabled(_confirmNote); if (_confirmItems.Length > 0 && _confirmItems[0].Kind == InventoryActionKind.Give) ImGuiNET.ImGui.TextDisabled("Given items can't be taken back."); @@ -287,7 +287,7 @@ internal sealed partial class InventoryFace bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning; InventoryTarget? target = InventoryModel.Target; RefreshSelectionLabels(target); - ImGuiNET.ImGui.TextDisabled(_menuCount); + SafeImGui.TextDisabled(_menuCount); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem(_menuDrop, "", false, idle && InventoryModel.DropAvailable)) GroupAction(DropKind.Drop, 0, string.Empty); diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index 94f036b..6e0ebec 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -222,7 +222,7 @@ internal sealed partial class InventoryFace : IImGuiPanel float bw = ImGuiNET.ImGui.CalcTextSize(view.BurdenText).X; ImGuiNET.ImGui.SetCursorScreenPos(p); ImGuiNET.ImGui.InvisibleButton("##burden", new Vector2(x + bw - p.X, RowH)); - ImGuiNET.ImGui.SetItemTooltip(view.BurdenTip); + SafeImGui.SetItemTooltip(view.BurdenTip); x += bw + 16; PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Coins, new Vector2(x, p.Y), new Vector2(18, RowH), Amber); @@ -656,7 +656,7 @@ internal sealed partial class InventoryFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(pos); bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); bool hot = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); bool dropHot = enabled && _dragItem != null && hot; var dl = ImGuiNET.ImGui.GetWindowDrawList(); uint fill = dropHot ? DropHot : _dragItem != null && enabled ? Selected : hot && enabled ? Lighten(BtnFill) : BtnFill; @@ -1021,7 +1021,7 @@ internal sealed partial class InventoryFace : IImGuiPanel if (it == null) { ImGuiNET.ImGui.CloseCurrentPopup(); return; } if (IsGroup(it)) { GroupMenu(view, it); return; } bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning; - ImGuiNET.ImGui.TextDisabled(it.Name); + SafeImGui.TextDisabled(it.Name); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Use", "double-click", false, idle)) Act(InventoryActionKind.Use, it, 0, "", 0); diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs index 72f5d93..af0c291 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs @@ -112,7 +112,7 @@ internal sealed class ItemCountFace : IImGuiPanel { if (ItemHudMath.TryFind(items, sel, out HudItem it)) Add(it.Name); } - ImGuiNET.ImGui.SetItemTooltip(haveSel ? "Count the selected item" : "Select an item in your inventory to count it (or drag one onto this panel)"); + SafeImGui.SetItemTooltip(haveSel ? "Count the selected item" : "Select an item in your inventory to count it (or drag one onto this panel)"); NextLine(start, h + 4); } @@ -183,7 +183,7 @@ internal sealed class ItemCountFace : IImGuiPanel ImGuiNET.ImGui.PushID(i); ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(bw - XW, RowH)); bool hot = ImGuiNET.ImGui.IsItemHovered(); - if (hot) ImGuiNET.ImGui.SetItemTooltip($"{data.Counts[i]}: {_countText[i]} carried"); + if (hot) SafeImGui.SetItemTooltip($"{data.Counts[i]}: {_countText[i]} carried"); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + bw - XW, p.Y)); if (ImGuiNET.ImGui.InvisibleButton("##x", new Vector2(XW, RowH))) remove = i; bool hotX = ImGuiNET.ImGui.IsItemHovered(); diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs index 95e3e43..d67b5fa 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs @@ -254,7 +254,7 @@ internal sealed class ItemsFace : IImGuiPanel Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4); float bw = ButtonWidth(label) + 4; if (Button(id, label, p, new Vector2(bw, 24), Teal, BtnFill)) onClick(); - if (tooltip != null) ImGuiNET.ImGui.SetItemTooltip(tooltip); + if (tooltip != null) SafeImGui.SetItemTooltip(tooltip); ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); ImGuiNET.ImGui.GetWindowDrawList().AddText(f9, f9.FontSize, new Vector2(p.X + bw + 8, p.Y + (24 - f9.FontSize) * 0.5f), Mute, hint); NextLine(new Vector2(p.X - 4, p.Y - 4), 32); diff --git a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs index a0fe2b2..8e3bd8b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs @@ -243,7 +243,7 @@ internal sealed class LootAddDialog 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); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(d.TargetPath); } bool changed = false; @@ -257,7 +257,7 @@ internal sealed class LootAddDialog _match = i; changed = true; } - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(MatchTips[i]); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(MatchTips[i]); } // T11 attributes. Shown for every item: a non-T11 item answers with a note saying so. @@ -268,7 +268,7 @@ internal sealed class LootAddDialog changed = true; } if (ImGuiNET.ImGui.IsItemHovered()) - ImGuiNET.ImGui.SetTooltip( + SafeImGui.SetTooltip( "Also require this item's T11 tier (the server's stamped tier when it sends one), weapon grade,\n" + "damage %, gear grade, every modifier, slot special and Cast on Strike, each at least as good\n" + "as this one. Works with any match.\n" + @@ -306,7 +306,7 @@ internal sealed class LootAddDialog changed = true; } ImGuiNET.ImGui.SameLine(); - ImGuiNET.ImGui.TextDisabled(d.Stackable ? "(counts stack sizes)" : "(items)"); + SafeImGui.TextDisabled(d.Stackable ? "(counts stack sizes)" : "(items)"); } // Name. @@ -316,7 +316,7 @@ internal sealed class LootAddDialog 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 + "\"."); + SafeImGui.TextDisabled("Left empty, the rule is named \"" + d.DefaultRuleName + "\"."); // Preview. ImGuiNET.ImGui.Separator(); @@ -360,7 +360,7 @@ internal sealed class LootAddDialog Send("item_add"); } if (ImGuiNET.ImGui.IsItemHovered()) - ImGuiNET.ImGui.SetTooltip(d.InsertAt >= 0 + SafeImGui.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)) diff --git a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs index f7fca3a..f05523f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs @@ -393,7 +393,7 @@ internal sealed class LootEditorFace : IImGuiPanel if (i >= 0 && i < s.Files.Count) RequestOpen(s.Files[i].Path); }, Math.Max(260, pickW)); } - ImGuiNET.ImGui.SetItemTooltip(s.Path.Length == 0 ? "Pick a loot profile" : s.Path); + SafeImGui.SetItemTooltip(s.Path.Length == 0 ? "Pick a loot profile" : s.Path); PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown, new Vector2(p.X + pickW - 18, p.Y), new Vector2(16, h), Mute); @@ -410,12 +410,12 @@ internal sealed class LootEditorFace : IImGuiPanel if (Button("##save", PhosphorIcons.FloppyDisk + " Save", new Vector2(x, p.Y), new Vector2(saveW, h), canSave ? Green : Mute, canSave ? StartBg : BtnFill, canSave)) Save(force: false); - ImGuiNET.ImGui.SetItemTooltip(_saveTip); + SafeImGui.SetItemTooltip(_saveTip); x += saveW + 4; if (IconButton("##external", PhosphorIcons.ArrowSquareOut, new Vector2(x, p.Y), new Vector2(icon, h), Text, BtnFill)) LaunchExternal(s.Path.Length > 0 ? s.Path : s.InUsePath); - ImGuiNET.ImGui.SetItemTooltip(s.Dirty + SafeImGui.SetItemTooltip(s.Dirty ? "Open external editor (it reads the file on disk: save first to take your edits)" : "Open external editor"); NextLine(p, h + 4); @@ -455,7 +455,7 @@ internal sealed class LootEditorFace : IImGuiPanel var b = new Vector2(x + ts.X + 12, y + h - 1); dl.AddRect(a, b, color, 8); dl.AddText(new Vector2(x + 6, y + (h - ts.Y) * 0.5f), color, text); - if (ImGuiNET.ImGui.IsMouseHoveringRect(a, b) && tooltip.Length > 0) ImGuiNET.ImGui.SetTooltip(tooltip); + if (ImGuiNET.ImGui.IsMouseHoveringRect(a, b) && tooltip.Length > 0) SafeImGui.SetTooltip(tooltip); return b.X + 6; } @@ -650,7 +650,7 @@ internal sealed class LootEditorFace : IImGuiPanel LootEditCommands.Simple("set_enabled", index, r.Enabled ? "false" : "true", expect: r.Name); changed = true; } - ImGuiNET.ImGui.SetItemTooltip(r.Enabled ? "Enabled: click to disable" : "Disabled: click to enable"); + SafeImGui.SetItemTooltip(r.Enabled ? "Enabled: click to disable" : "Disabled: click to enable"); x += 20; // Action badge @@ -675,7 +675,7 @@ internal sealed class LootEditorFace : IImGuiPanel Expect(Await.ScrollFocus); changed = true; } - ImGuiNET.ImGui.SetItemTooltip(reorder ? "Move up" : Filtering ? "Clear the search and filter to reorder" : "Move up"); + SafeImGui.SetItemTooltip(reorder ? "Move up" : Filtering ? "Clear the search and filter to reorder" : "Move up"); bx += 18; if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(bx, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, reorder && index < s.Rules.Count - 1, font: UiFont.Ui11)) @@ -684,7 +684,7 @@ internal sealed class LootEditorFace : IImGuiPanel Expect(Await.ScrollFocus); changed = true; } - ImGuiNET.ImGui.SetItemTooltip(reorder ? "Move down" : Filtering ? "Clear the search and filter to reorder" : "Move down"); + SafeImGui.SetItemTooltip(reorder ? "Move down" : Filtering ? "Clear the search and filter to reorder" : "Move down"); bx += 18; if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(bx, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, !ro, font: UiFont.Ui11)) { @@ -710,7 +710,7 @@ internal sealed class LootEditorFace : IImGuiPanel { ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); dl.AddRect(new Vector2(x - 2, p.Y), new Vector2(x + textW, p.Y + RowH), BtnBord, 2); - ImGuiNET.ImGui.SetTooltip((r.Name.Length == 0 ? "(no name)" : r.Name) + "\n" + r.Summary); + SafeImGui.SetTooltip((r.Name.Length == 0 ? "(no name)" : r.Name) + "\n" + r.Summary); } ImGuiNET.ImGui.PopID(); @@ -754,7 +754,7 @@ internal sealed class LootEditorFace : IImGuiPanel 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 + SafeImGui.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; @@ -769,7 +769,7 @@ internal sealed class LootEditorFace : IImGuiPanel dl.PushClipRect(at, new Vector2(Math.Max(at.X + 1, right), at.Y + h), true); dl.AddText(new Vector2(at.X, at.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), _msgOk ? Green : Red, _msg); dl.PopClipRect(); - if (ImGuiNET.ImGui.IsMouseHoveringRect(at, new Vector2(right, at.Y + h))) ImGuiNET.ImGui.SetTooltip(_msg); + if (ImGuiNET.ImGui.IsMouseHoveringRect(at, new Vector2(right, at.Y + h))) SafeImGui.SetTooltip(_msg); } // ===================================================================== @@ -1017,7 +1017,7 @@ internal sealed class LootEditorFace : IImGuiPanel { if (!_rawShown.Remove(i)) _rawShown.Add(i); } - ImGuiNET.ImGui.SetItemTooltip(rawToggle ? "Show the raw data lines (any key id, any value)" : "This condition is edited as raw lines"); + SafeImGui.SetItemTooltip(rawToggle ? "Show the raw data lines (any key id, any value)" : "This condition is edited as raw lines"); tx += 18; int result = 0; int prev = PrevVisible(r, i), next = NextVisible(r, i); @@ -1105,7 +1105,7 @@ internal sealed class LootEditorFace : IImGuiPanel string hint = node.Labels.Count > 0 ? node.Labels[0].ToLowerInvariant() : "value"; if (Field("##val", FieldFor(i, 0), c.Lines[0], new Vector2(p.X + kw + 2, p.Y), w - kw - 2, hint, ro, out string v, h)) c.Lines[0] = v; - ImGuiNET.ImGui.SetItemTooltip(node.Labels.Count > 0 ? node.Labels[0] : "Value"); + SafeImGui.SetItemTooltip(node.Labels.Count > 0 ? node.Labels[0] : "Value"); break; } case "keypattern": @@ -1153,7 +1153,7 @@ internal sealed class LootEditorFace : IImGuiPanel ClearFields(); }, Math.Max(220, w)); } - ImGuiNET.ImGui.SetItemTooltip(sel >= 0 ? table.Names[sel] : "Not in the list: use the raw lines button to type any id"); + SafeImGui.SetItemTooltip(sel >= 0 ? table.Names[sel] : "Not in the list: use the raw lines button to type any id"); } /// <summary>The value names for this condition's long key, or null (no table, or a RynthAi that sends none).</summary> @@ -1185,7 +1185,7 @@ internal sealed class LootEditorFace : IImGuiPanel } string tip = sel >= 0 ? table.Items[sel] : "Not in the list: pick \"" + OtherNumber + "\" to type any number"; if (table.Flags) tip += "\nFlags: other combinations are typed as a number"; - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } /// <summary>A whole number: "45", "45.0" (a buffed-long value written as a double).</summary> diff --git a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs index 795b5f9..70cd5d8 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs @@ -176,7 +176,7 @@ internal sealed class LuaFace : IImGuiPanel dl.AddText(new Vector2(x + runW + sepW, ty), ai ? Green : Amber, aiText); dl.PopClipRect(); if (ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x + runW + sepW, p.Y), new Vector2(right, p.Y + h))) - ImGuiNET.ImGui.SetTooltip(ai + SafeImGui.SetTooltip(ai ? "RynthAi's script interface is there: scripts can use its macro, nav and meta features." : "RynthAi isn't loaded (or is too old): scripts' RynthAi calls won't work."); NextLine(p, h + 2); @@ -245,7 +245,7 @@ internal sealed class LuaFace : IImGuiPanel if (ImGuiNET.ImGui.IsItemHovered()) { if (!isSel) dl.AddRectFilled(p, p + new Vector2(nameW, RowH), BtnFill); - ImGuiNET.ImGui.SetTooltip(RowTooltip(info, notSaved)); + SafeImGui.SetTooltip(RowTooltip(info, notSaved)); } if (isSel) dl.AddRectFilled(p, p + new Vector2(2, RowH), Teal); @@ -267,7 +267,7 @@ internal sealed class LuaFace : IImGuiPanel _picker.Open(new Vector2(x, by + bh + 2), items, Array.IndexOf(AutoCodes, info.Autostart), k => LuaCommands.Send("autostart", name, AutoCodes[k]), 190); } - ImGuiNET.ImGui.SetItemTooltip(notSaved + SafeImGui.SetItemTooltip(notSaved ? "Save it to a file to autostart it." : "Start at login: off, on every character (global), or on this character only."); x += autoW + gap; @@ -281,7 +281,7 @@ internal sealed class LuaFace : IImGuiPanel x += runW + gap; if (Button("##restart", RestartLabel, new Vector2(x, by), new Vector2(restartW, bh), Text, BtnFill, enabled: info.Running && !notSaved)) LuaCommands.Send("restart", info.Name); - ImGuiNET.ImGui.SetItemTooltip(notSaved ? "Not saved: run it again from the Editor." : "Stop it and start it again from its file."); + SafeImGui.SetItemTooltip(notSaved ? "Not saved: run it again from the Editor." : "Stop it and start it again from its file."); NextLine(p, RowH); } @@ -334,7 +334,7 @@ internal sealed class LuaFace : IImGuiPanel LuaCommands.Send("load", sel); _editorTab = true; } - ImGuiNET.ImGui.SetItemTooltip(canOpen + SafeImGui.SetItemTooltip(canOpen ? (si!.IsFolder ? "Edit its index.lua in the Editor tab." : "Edit it in the Editor tab.") : "It has no file to open."); NextLine(p, h); @@ -407,7 +407,7 @@ internal sealed class LuaFace : IImGuiPanel dl.PopClipRect(); if (Button("##run", RunLabel, new Vector2(p.X + statusW + 4, p.Y), new Vector2(bw, 24), Text, StartBg)) LuaCommands.Send("run", edName, _editor?.GetText() ?? string.Empty); - ImGuiNET.ImGui.SetItemTooltip("Run the editor's text as " + runName + " (replaces a running copy)."); + SafeImGui.SetItemTooltip("Run the editor's text as " + runName + " (replaces a running copy)."); if (Button("##stop", StopLabel, new Vector2(p.X + statusW + bw + 8, p.Y), new Vector2(bw, 24), Text, StopBg, enabled: running)) LuaCommands.Send("stopScript", runName); NextLine(p, 24); @@ -495,7 +495,7 @@ internal sealed class LuaFace : IImGuiPanel _editor?.MarkClean(); } } - if (saveTip != null) ImGuiNET.ImGui.SetItemTooltip(saveTip); + if (saveTip != null) SafeImGui.SetItemTooltip(saveTip); x += bw + 4; if (Button("##new", PhosphorIcons.FilePlus + " New", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill)) { @@ -508,7 +508,7 @@ internal sealed class LuaFace : IImGuiPanel string name = Utf8(_name).Trim(); if (name.Length > 0) LuaCommands.Send("delete", name); } - if (deleteTip != null) ImGuiNET.ImGui.SetItemTooltip(deleteTip); + if (deleteTip != null) SafeImGui.SetItemTooltip(deleteTip); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); } @@ -555,7 +555,7 @@ internal sealed class LuaFace : IImGuiPanel ImGuiNET.ImGui.PushTextWrapPos(0); string text = _data?.Console ?? string.Empty; if (text.Length > 0) ImGuiNET.ImGui.TextUnformatted(text); - if (_note.Length > 0) ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Highlight), "[panel] " + _note); + if (_note.Length > 0) SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Highlight), "[panel] " + _note); ImGuiNET.ImGui.PopTextWrapPos(); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.PopFont(); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs index f8e0399..0d0b09d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs @@ -281,7 +281,7 @@ internal sealed partial class MetaFace if (actions) MetaRuleEdit.AddAction(r); else MetaRuleEdit.AddCondition(r); _editChanged = true; } - ImGuiNET.ImGui.SetItemTooltip(actions + SafeImGui.SetItemTooltip(actions ? (r.Action == MetaRuleEdit.DoAll ? "Add one more action" : "Add another action: this one and the new one run in order (All)") : !canAdd ? "A Not has one condition" : r.Condition is MetaRuleEdit.All or MetaRuleEdit.Any or MetaRuleEdit.Not ? "Add one more condition" @@ -515,7 +515,7 @@ internal sealed partial class MetaFace c.ConditionData = here; _editChanged = true; } - ImGuiNET.ImGui.SetItemTooltip(here != null + SafeImGui.SetItemTooltip(here != null ? $"Set to where you are now: {here}" : "Your position isn't known right now (portal space, or not in the world)."); } @@ -524,7 +524,7 @@ internal sealed partial class MetaFace ImGuiNET.ImGui.SetCursorScreenPos(p); DataBox(id, c, action: false, MetaVocabulary.ConditionHint(c.Condition), width, height); if (c.Condition == MetaRuleEdit.NoKillsWithinMinutes) - ImGuiNET.ImGui.SetItemTooltip(MetaRuleEdit.NoKillsTooltip(c.ConditionData).Replace("%", "%%")); // a format string: typed text may hold % + SafeImGui.SetItemTooltip(MetaRuleEdit.NoKillsTooltip(c.ConditionData)); } ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + height)); ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); @@ -617,7 +617,7 @@ internal sealed partial class MetaFace } bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + rw - xw, p.Y), new Vector2(xw, rh), TextDim, DelFill, BtnBord); - ImGuiNET.ImGui.SetItemTooltip(action ? "Remove this action" : nests ? "Remove this group and what is in it" : "Remove this condition"); + SafeImGui.SetItemTooltip(action ? "Remove this action" : nests ? "Remove this group and what is in it" : "Remove this condition"); int moveTo = -1; if (action) { @@ -720,7 +720,7 @@ internal sealed partial class MetaFace if (draft) { _autosave.Clear(); LeaveEditor(); } else _editConfirmDelete = true; } - ImGuiNET.ImGui.SetItemTooltip(draft ? "Drop this new rule (it was never added)" : "Delete this rule (asks first)"); + SafeImGui.SetItemTooltip(draft ? "Drop this new rule (it was never added)" : "Delete this rule (asks first)"); } else { @@ -787,7 +787,7 @@ internal sealed partial class MetaFace ImGuiNET.ImGui.GetWindowDrawList().AddRect(pos, pos + new Vector2(boxW, height), Red, 3); bool ok = IconButton(id + "_ok", PhosphorIcons.Check, new Vector2(pos.X + boxW + 3, pos.Y), new Vector2(bw, height), Green, NewFill, Green, enabled: _nameProblem == null); - ImGuiNET.ImGui.SetItemTooltip(_nameProblem ?? $"Make the state '{name}' (Enter)"); + SafeImGui.SetItemTooltip(_nameProblem ?? $"Make the state '{name}' (Enter)"); bool cancel = IconButton(id + "_cancel", PhosphorIcons.X, new Vector2(pos.X + boxW + bw + 6, pos.Y), new Vector2(bw, height), TextDim, BtnFill, BtnBord); ImGuiNET.ImGui.SetItemTooltip("Cancel (Esc)"); @@ -861,7 +861,7 @@ internal sealed partial class MetaFace private static void Note(string text) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), text); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), text); ImGuiNET.ImGui.PopFont(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs index 0784967..41d3ce3 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs @@ -277,7 +277,7 @@ internal sealed partial class MetaFace float toggleX = x; if (Toggle(compactLabel, ref x, p.Y, !anyRuleOpen)) SetAllFolded(anyRuleOpen); x = toggleX + compactW + 4; // the button keeps one width whichever label it shows - ImGuiNET.ImGui.SetItemTooltip(anyRuleOpen + SafeImGui.SetItemTooltip(anyRuleOpen ? "Fold every rule to one line (hover one to see all of it; its caret opens it again)." : "Show every rule in full: each condition and action on its own line."); @@ -289,7 +289,7 @@ internal sealed partial class MetaFace if (anyOpen) foreach ((string s, List<int> _) in _groups) _collapsed.Add(s); else _collapsed.Clear(); } - ImGuiNET.ImGui.SetItemTooltip(anyOpen ? "Collapse every state" : "Expand every state"); + SafeImGui.SetItemTooltip(anyOpen ? "Collapse every state" : "Expand every state"); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); @@ -452,7 +452,7 @@ internal sealed partial class MetaFace rx -= pw; if (GlyphButton("##add", PhosphorIcons.Plus, new Vector2(rx, hp.Y + (hh - 18) * 0.5f), new Vector2(pw, 18), Green, Lighten(Green))) OpenEditor(-1, new MetaRuleDto { State = state, Action = 1 }); - ImGuiNET.ImGui.SetItemTooltip($"New rule in {state}"); + SafeImGui.SetItemTooltip($"New rule in {state}"); rx -= 4; } if (current) @@ -482,8 +482,8 @@ internal sealed partial class MetaFace dl.AddRect(wa, wb, Amber, 8); dl.AddText(small, small.FontSize, new Vector2(wa.X + 5, wa.Y + 2), Amber, wtag); if (ImGuiNET.ImGui.IsMouseHoveringRect(wa, wb)) - ImGuiNET.ImGui.SetTooltip("Watchdog: unless you move far enough, the meta goes to " + - (wdState.Length > 0 ? wdState.Replace("%", "%%") : "its state") + " when this runs out."); + SafeImGui.SetTooltip("Watchdog: unless you move far enough, the meta goes to " + + (wdState.Length > 0 ? wdState : "its state") + " when this runs out."); } } } @@ -555,7 +555,7 @@ internal sealed partial class MetaFace new Vector2(p.X + 2, firstLineY + (_lineH - 16) * 0.5f), new Vector2(14, 16), Faded(TextDim), Teal)) SetFolded(index, !folded); caretHot = ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(folded ? "Show all of this rule" : "Fold this rule to one line"); + SafeImGui.SetItemTooltip(folded ? "Show all of this rule" : "Fold this rule to one line"); } if (GlyphButton("##en", rule.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, new Vector2(p.X + 16, firstLineY + (_lineH - 16) * 0.5f), new Vector2(16, 16), rule.Enabled ? Green : Mute, TextDim)) @@ -563,7 +563,7 @@ internal sealed partial class MetaFace rule.Enabled = !rule.Enabled; SendEdit(new MetaCmd { Op = "set_rule_enabled", Index = index, Value = rule.Enabled ? "true" : "false" }); } - ImGuiNET.ImGui.SetItemTooltip(rule.Enabled ? "Enabled: click to disable" : "Disabled: click to enable"); + SafeImGui.SetItemTooltip(rule.Enabled ? "Enabled: click to disable" : "Disabled: click to enable"); if ((hot && !filtering) || dragged) // on hover the number becomes a grip: the row drags PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.DotsSixVertical, new Vector2(p.X + 34, firstLineY), new Vector2(_numW + 4, _lineH), dragged ? Teal : Mute); @@ -618,13 +618,13 @@ internal sealed partial class MetaFace if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(bx, by), new Vector2(bs, bs), Mute, BtnFill, BtnBord, enabled: canMove && gi > 0)) changed |= Move(index, -1); toolHot |= ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(canMove ? "Move up" : "Clear the filter to move rules"); + SafeImGui.SetItemTooltip(canMove ? "Move up" : "Clear the filter to move rules"); bx += bs + gap; if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(bx, by), new Vector2(bs, bs), Mute, BtnFill, BtnBord, enabled: canMove && gi < groupCount - 1)) changed |= Move(index, +1); toolHot |= ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(canMove ? "Move down" : "Clear the filter to move rules"); + SafeImGui.SetItemTooltip(canMove ? "Move down" : "Clear the filter to move rules"); bx += bs + gap; if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(bx, by), new Vector2(bs, bs), Mute, BtnFill, BtnBord)) changed |= Duplicate(index, rule); @@ -645,7 +645,7 @@ internal sealed partial class MetaFace } } toolHot |= ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(arming ? "Click again to delete this rule" : "Delete rule"); + SafeImGui.SetItemTooltip(arming ? "Click again to delete this rule" : "Delete rule"); } dl.AddLine(new Vector2(p.X, p.Y + h - 0.5f), new Vector2(p.X + w, p.Y + h - 0.5f), RowLine); @@ -1024,7 +1024,7 @@ internal sealed partial class MetaFace _stateClock.StateSet(NowMs); // picking a state enters it afresh (RynthAi resets its clock) } if (inState != null && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(pickX, p.Y + 1), new Vector2(pickX + pickW, p.Y + 23))) - ImGuiNET.ImGui.SetTooltip($"The meta's current state; in it for {inState}."); + SafeImGui.SetTooltip($"The meta's current state; in it for {inState}."); bool canGo = HasRulesIn(_data.CurrentState); if (IconButton("##goto_current", PhosphorIcons.Crosshair, new Vector2(pickX + pickW + 4, p.Y + 1), new Vector2(goW, 22), Teal, BtnFill, BtnBord, enabled: canGo, font: UiFont.Ui14)) @@ -1036,7 +1036,7 @@ internal sealed partial class MetaFace SetFilter(string.Empty); } } - ImGuiNET.ImGui.SetItemTooltip(canGo ? "Show the current state in the list" : "The current state has no rules"); + SafeImGui.SetItemTooltip(canGo ? "Show the current state in the list" : "The current state has no rules"); if (Button(ruleLabel + "##new", new Vector2(ruleX, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green)) OpenEditor(-1, new MetaRuleDto { State = _data.CurrentState, Action = 1 }); ImGuiNET.ImGui.SetItemTooltip("A new rule in the current state (added once its condition and action are filled in)"); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs index c15b4ea..a84d256 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs @@ -166,7 +166,7 @@ internal sealed partial class MetaFace ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); TextBox(id, buf, boxW, "", ImGuiInputTextFlags.CharsDecimal, out _); bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); if (done && int.TryParse(Utf8(buf).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) commit(n); x += boxW + 3; @@ -183,9 +183,9 @@ internal sealed partial class MetaFace : sc.LastPollMs == 0 ? "Waiting for the first /myquests." : $"{sc.QuestCount} quest timer(s), /myquests {Span(now - sc.LastPollMs)} ago."; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(sc.ServerDisabled ? RynthTheme.Highlight : RynthTheme.MuteAlt), Fit(poll, w)); + SafeImGui.TextColored(RynthTheme.VecOf(sc.ServerDisabled ? RynthTheme.Highlight : RynthTheme.MuteAlt), Fit(poll, w)); if (sc.LastSwitch.Length > 0) - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), Fit($"Last: {sc.LastSwitch}{(sc.LastSwitchMs > 0 ? $", {Span(now - sc.LastSwitchMs)} ago" : "")}", w)); ImGuiNET.ImGui.PopFont(); } @@ -220,7 +220,7 @@ internal sealed partial class MetaFace r.Enabled = !r.Enabled; MetaCommands.Simple("mm_rule_enabled", i, r.Enabled ? "true" : "false"); } - ImGuiNET.ImGui.SetItemTooltip(r.Enabled ? "On - click to turn this rule off" : "Off - click to turn it on"); + SafeImGui.SetItemTooltip(r.Enabled ? "On - click to turn this rule off" : "Off - click to turn it on"); x += 16; if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, enabled: i > 0)) { @@ -245,7 +245,7 @@ internal sealed partial class MetaFace if (IconButton("##cd", running ? PhosphorIcons.Stop : PhosphorIcons.Play, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), running ? Amber : Green, BtnFill, BtnBord)) MetaCommands.Simple(running ? "mm_countdown_stop" : "mm_countdown_start", i); - ImGuiNET.ImGui.SetItemTooltip(running ? "Stop the countdown" : $"Start the countdown ({Num(r.Minutes)} min)"); + SafeImGui.SetItemTooltip(running ? "Stop the countdown" : $"Start the countdown ({Num(r.Minutes)} min)"); } else if (r.Fired || (r.State ?? "").StartsWith("error", StringComparison.Ordinal) || (r.State ?? "").Contains("holding")) { @@ -270,7 +270,7 @@ internal sealed partial class MetaFace if (ImGuiNET.ImGui.IsItemHovered()) { ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); - ImGuiNET.ImGui.SetTooltip(RuleTooltip(r, i, first)); + SafeImGui.SetTooltip(RuleTooltip(r, i, first)); } ImGuiNET.ImGui.PopID(); if (changed) return; // the list changed: draw it again next frame @@ -367,7 +367,7 @@ internal sealed partial class MetaFace ScheduleRuleDto r = _schedRule; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}"); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}"); ImGuiNET.ImGui.PopFont(); FieldLabel("When:"); @@ -428,7 +428,7 @@ internal sealed partial class MetaFace else MetaCommands.Send(new MetaCmd { Op = "mm_update", Index = _schedEdit, ScheduleRule = send }); _schedEdit = -2; } - if (!valid) ImGuiNET.ImGui.SetItemTooltip(r.Meta.Length == 0 ? "Pick a meta to load" : "Name the quest"); + if (!valid) SafeImGui.SetItemTooltip(r.Meta.Length == 0 ? "Pick a meta to load" : "Name the quest"); if (Button("Cancel##sched_cancel", new Vector2(b.X + sw + 6, b.Y), new Vector2(60, 22), Mute, BtnFill, BtnBord)) _schedEdit = -2; ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(b.X, b.Y + 22)); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs index a78fae8..5791919 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs @@ -306,7 +306,7 @@ internal sealed partial class MetaFace : IImGuiPanel bool noFile = string.IsNullOrEmpty(_data.CurrentMetaPath); if (Button("Save As##save_as", new Vector2(x, p.Y), new Vector2(saveAsW, 22), TextDim, noFile ? NewFill : BtnFill, noFile ? Green : BtnBord)) BeginSaveAs(); - ImGuiNET.ImGui.SetItemTooltip(noFile ? "Name a file for this meta; after that every change saves on its own." + SafeImGui.SetItemTooltip(noFile ? "Name a file for this meta; after that every change saves on its own." : "Save a copy under a new name (and keep editing that one)."); x += saveAsW + 4; SaveIndicator(new Vector2(x, p.Y), p.X + w - x, 22); @@ -353,7 +353,7 @@ internal sealed partial class MetaFace : IImGuiPanel float tw = ImGuiNET.ImGui.CalcTextSize(text).X; ImGuiNET.ImGui.SetCursorScreenPos(pos); ImGuiNET.ImGui.InvisibleButton("##save_ind", new Vector2(width, height)); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(pos.X + Math.Max(0, width - tw), pos.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), color, text); } @@ -467,7 +467,7 @@ internal sealed partial class MetaFace : IImGuiPanel if (showMsg) { ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(_msgOk ? 0xFF33CC66 : 0xFFE04848), _msg); + SafeImGui.TextColored(RynthTheme.Vec(_msgOk ? 0xFF33CC66 : 0xFFE04848), _msg); ImGuiNET.ImGui.PopTextWrapPos(); } if (_sourceStale) @@ -994,7 +994,7 @@ internal sealed partial class MetaFace : IImGuiPanel private static void FieldLabel(string text) { ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), text); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.MuteAlt), text); } private static void Separator(float w) diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs new file mode 100644 index 0000000..f9342f4 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs @@ -0,0 +1,511 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MiniRemoteFace.Sections.cs +// The Mini Remote's sections (UI/Sections): the rail down the left, and the +// body of the section picked on it. +// +// rail Remote (the slots / RynthAi's remote), then the core sections and +// the plugins' own, in SectionRegistry's order. Right-click: the +// menu (sections, active servers' items, hide the rail). Hidden, the +// sections stay reachable from the menu and /rc miniremote section. +// body a row of tabs when there is more than one view: the section's views +// (engine panels embedded whole, the Session Stats overview, plugin views), +// then one tab per active server with options here ("Server: ILT") +// and "Plugins" for options every world gets. A view fills the body; +// an options tab lists the plugins' option surfaces (collapsible) and +// command buttons. +// fit picking a section sizes the window for its first view; a resize by +// hand holds until the next pick. Back on Remote, the remote refits. +// saved the core section last picked, and whether the rail shows +// (panel_columns.txt, for the whole PC). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Text; +using System.Threading; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Sections; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class MiniRemoteFace +{ + private const string SectionKey = "MiniRemote.section", RailKey = "MiniRemote.rail"; + private const float RailMinW = 52f, RailMaxW = 96f, RailRowH = 18f, TabRowH = 20f; + /// <summary>The host key that keeps this window's embedded panels apart from other hosts'.</summary> + private const string EmbedHost = "MiniRemote"; + /// <summary>Preferred body size (logical) for a view that doesn't say.</summary> + private static readonly Vector2 DefaultViewSize = new(420, 380); + private static readonly Vector2 OverviewSize = new(360, 200); + + // Shared by every instance (the face is recreated on each open): the section shown. + private static string _section = LoadSection(); + private static string? _requestedSection, _requestedSurface; // from commands, taken on the next draw + private static readonly Dictionary<string, int> TabBySection = new(StringComparer.OrdinalIgnoreCase); + + // This instance: the window fit and the plugin surfaces. + private bool _fitPending = true; + private Vector2 _remoteWindowSize; + private readonly Dictionary<string, byte[]> _surfaceBytes = new(StringComparer.Ordinal); + private readonly Dictionary<string, float> _surfaceHeights = new(StringComparer.Ordinal); + private readonly HashSet<string> _surfaceOff = new(StringComparer.Ordinal); + private float _railW; + private int _railRevision = -1; + + private static bool IsRemote => _section.Equals(SectionCatalog.RemoteId, StringComparison.OrdinalIgnoreCase); + + /// <summary>Whether the window is on section <paramref name="sectionId"/> (the dashboard's lit Char launcher).</summary> + public static bool ShowsSection(string sectionId) => _section.Equals(sectionId, StringComparison.OrdinalIgnoreCase); + + private static bool RailShown => PanelColumnStore.Get(RailKey, 1f) >= 0.5f; + + // ── Requests (commands; render thread) ────────────────────────────── + + /// <summary>Shows section <paramref name="sectionId"/> ("remote" = the remote) on the next draw.</summary> + public static void RequestSection(string sectionId) + { + Volatile.Write(ref _requestedSurface, null); + Volatile.Write(ref _requestedSection, sectionId); + } + + /// <summary> + /// Shows the section and tab holding plugin surface <paramref name="surface"/> (RynthAi's + /// "section:banking"), when one does now. False when no section has it. + /// </summary> + public static bool TryRequestSurface(string surface) + { + foreach (SectionView v in SectionRegistry.Current.Sections) + if (TabOfSurface(v, surface) >= 0) + { + Volatile.Write(ref _requestedSurface, surface); + Volatile.Write(ref _requestedSection, v.Id); + return true; + } + return false; + } + + private void TakeRequestedSection(SectionRegistry.Snapshot snap) + { + string? id = Interlocked.Exchange(ref _requestedSection, null); + if (id == null) return; + string? surface = Interlocked.Exchange(ref _requestedSurface, null); + SelectSection(id); + SectionView? v = snap.Find(_section); + if (v != null && surface != null) + { + int tab = TabOfSurface(v, surface); + if (tab >= 0) TabBySection[v.Id] = tab; + } + } + + /// <summary>The tab index (views, then option groups) holding <paramref name="surface"/>, else -1.</summary> + private static int TabOfSurface(SectionView v, string surface) + { + for (int i = 0; i < v.Panes.Length; i++) + if (v.Panes[i].Contribution?.Surface.Equals(surface, StringComparison.OrdinalIgnoreCase) == true) return i; + for (int g = 0; g < v.Groups.Length; g++) + foreach (SectionContribution c in v.Groups[g].Items) + if (c.Surface.Equals(surface, StringComparison.OrdinalIgnoreCase)) return v.Panes.Length + g; + return -1; + } + + private void SelectSection(string id) + { + string next = id.Length == 0 ? SectionCatalog.RemoteId : id; + if (next.Equals(_section, StringComparison.OrdinalIgnoreCase)) return; + bool leavingRemote = IsRemote; + if (leavingRemote && !ImGuiPopOuts.InPopOutFrame) + _remoteWindowSize = ImGuiNET.ImGui.GetWindowSize() / ImGuiPanelHost.PlacementScale(); + _section = next; + _fitPending = true; + if (IsRemote) + { + // Back on the remote: RynthAi's asks again; the engine grid gets the size it had. + _lastWant = Vector2.Zero; + _requested = Vector2.Zero; + if (_remoteWindowSize.X > 0 && !_hosted && !ImGuiPopOuts.InPopOutFrame) + ImGuiPanelHost.RequestSize(Title, _remoteWindowSize); + } + SaveSection(_section); + } + + private static string LoadSection() + { + int i = (int)PanelColumnStore.Get(SectionKey, -1f); + return i >= 0 && i < SectionCatalog.Core.Length ? SectionCatalog.Core[i].Id : SectionCatalog.RemoteId; + } + + /// <summary>Saves a core section (a plugin's own isn't: it may not be there next time).</summary> + private static void SaveSection(string id) + { + int index = -1; + for (int i = 0; i < SectionCatalog.Core.Length; i++) + if (SectionCatalog.Core[i].Id.Equals(id, StringComparison.OrdinalIgnoreCase)) index = i; + if (PanelColumnStore.Get(SectionKey, -1f) != index) PanelColumnStore.Set(SectionKey, index); + } + + // ── Rail ──────────────────────────────────────────────────────────── + + /// <summary>Draws the rail at the body's left; returns the width it takes (with its gap).</summary> + private float DrawRail(SectionRegistry.Snapshot snap, Vector2 origin, Vector2 size) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + try + { + if (_railRevision != snap.Revision || _railW <= 0) + { + float widest = ImGuiNET.ImGui.CalcTextSize("Remote").X; + foreach (SectionView v in snap.Sections) widest = MathF.Max(widest, ImGuiNET.ImGui.CalcTextSize(v.Label).X); + _railW = Math.Clamp(widest + 14f, RailMinW, RailMaxW); + _railRevision = snap.Revision; + } + float h = Math.Max(RailRowH, size.Y - 12 - GripOverlap()); + ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(6, 6)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + bool open = ImGuiNET.ImGui.BeginChild("##mr_rail", new Vector2(_railW, h), ImGuiChildFlags.None, + ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoScrollbar); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (open) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + RailButton(SectionCatalog.RemoteId, "Remote", "The remote: item slots, and RynthAi's when it is loaded.", true, ref p); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddLine(p + new Vector2(2, 1), p + new Vector2(_railW - 2, 1), BtnBord); + p.Y += 4; + foreach (SectionView v in snap.Sections) + RailButton(v.Id, v.Label, RailTooltip(v), v.HasContent, ref p); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.Dummy(new Vector2(_railW, 1)); + if (ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) + { + _menuSlot = -1; + _openMenu = true; + } + } + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + } + finally + { + ImGuiNET.ImGui.PopFont(); + } + return _railW + 4f; + } + + private void RailButton(string id, string label, string tooltip, bool hasContent, ref Vector2 p) + { + bool selected = id.Equals(_section, StringComparison.OrdinalIgnoreCase); + var size = new Vector2(_railW, RailRowH); + if (Button("##rail_" + id, label, p, size, hasContent ? Text : Faded(Text), selected ? Selected : BtnFill, + leftAlign: true, border: selected ? Teal : 0)) + SelectSection(id); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _menuSlot = -1; _openMenu = true; } + if (tooltip.Length > 0) SafeImGui.SetItemTooltip(tooltip); + p.Y += RailRowH + 2; + } + + private static string RailTooltip(SectionView v) + { + if (!v.HasContent) return v.Label + ": " + EmptyNote(v.Id); + var parts = new List<string>(); + foreach (SectionPane pane in v.Panes) parts.Add(pane.Title); + foreach (SectionGroup g in v.Groups) parts.Add(g.Title); + return v.Label + ": " + string.Join(", ", parts); + } + + /// <summary>What an empty section says (nothing installed fills it on this world).</summary> + private static string EmptyNote(string id) => id switch + { + "friends" => "no friends list yet. A server plugin can add one here.", + "fellowship" => "the fellowship view comes from RynthAi; it isn't loaded.", + "pets" or "crafting" or "spells" => "this view comes from RynthAi; it isn't loaded.", + "map" or "combat" or "nav" or "chat" or "skills" or "inventory" => "its engine panels are off (Settings, or the plugins they need aren't installed).", + _ => "nothing installed adds to it on this world.", + }; + + // ── Section body ──────────────────────────────────────────────────── + + private void DrawSection(SectionRegistry.Snapshot snap, float w, Vector2 origin, Vector2 size) + { + SectionView? view = snap.Find(_section); + if (view == null) + { + // A plugin's section that went away (its server isn't active any more): back to the remote. + if (snap.Sections.Count > 0) SelectSection(SectionCatalog.RemoteId); + Label("Loading sections...", Mute); + return; + } + + int tabs = view.Panes.Length + view.Groups.Length; + if (tabs == 0) + { + Label(view.Label, Teal); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + SafeImGui.TextWrapped(char.ToUpperInvariant(EmptyNote(view.Id)[0]) + EmptyNote(view.Id)[1..]); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopTextWrapPos(); + return; + } + + if (!TabBySection.TryGetValue(view.Id, out int tab) || tab < 0 || tab >= tabs) tab = 0; + float haveH = Remaining(origin, size); + if (tabs > 1) tab = DrawTabRow(view, tab, w); + TabBySection[view.Id] = tab; + + if (_fitPending) + { + _fitPending = false; + Vector2 pref = PreferredSize(view, tab); + float place = ImGuiPanelHost.PlacementScale(); + float extra = (tabs > 1 ? TabRowH + 4 : 0) + GripOverlap(); + FitWindow(new Vector2(pref.X * place, pref.Y * place + extra), w, haveH); + } + + var box = new Vector2(w, Math.Max(40f, Remaining(origin, size) - GripOverlap())); + if (tab < view.Panes.Length) DrawPane(snap, view.Panes[tab], box); + else DrawGroup(view.Groups[tab - view.Panes.Length], box); + } + + /// <summary>The section's tabs as a wrapped row of buttons; returns the one selected.</summary> + private int DrawTabRow(SectionView view, int tab, float w) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + try + { + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 p = start; + int count = view.Panes.Length + view.Groups.Length; + for (int i = 0; i < count; i++) + { + string label = i < view.Panes.Length ? view.Panes[i].Title : view.Groups[i - view.Panes.Length].Title; + float bw = Math.Min(w, ButtonWidth(label)); + if (p.X > start.X && p.X + bw > start.X + w) p = new Vector2(start.X, p.Y + TabRowH + 2); + bool selected = i == tab; + bool enabled = i >= view.Panes.Length || view.Panes[i].Contribution?.Enabled != false; + if (Button("##sectab_" + view.Id + "_" + i, label, p, new Vector2(bw, TabRowH), enabled ? Text : Faded(Text), + selected ? Selected : BtnFill, border: selected ? Teal : 0) && i != tab) + { + tab = i; + _fitPending = true; + } + p.X += bw + 3; + } + NextLine(start, p.Y - start.Y + TabRowH + 4); + } + finally + { + ImGuiNET.ImGui.PopFont(); + } + return tab; + } + + /// <summary>The body size (logical) a tab would like: its panel's default, or what its plugin said.</summary> + private Vector2 PreferredSize(SectionView view, int tab) + { + if (tab >= view.Panes.Length) return DefaultViewSize; + SectionPane pane = view.Panes[tab]; + switch (pane.Kind) + { + case SectionPaneKind.Overview: + return OverviewSize; + case SectionPaneKind.CorePanel: + return ImGuiPanelHost.TryGetDefaultSize(pane.Panel, out Vector2 s) && s.X > 0 && s.Y > 0 ? s : DefaultViewSize; + default: + SectionContribution c = pane.Contribution!; + return new Vector2(c.Width > 0 ? c.Width : DefaultViewSize.X, c.Height > 0 ? c.Height : DefaultViewSize.Y); + } + } + + private void DrawPane(SectionRegistry.Snapshot snap, SectionPane pane, Vector2 box) + { + switch (pane.Kind) + { + case SectionPaneKind.Overview: + DrawOverview(snap, box); + break; + case SectionPaneKind.CorePanel: + ImGuiPanelHost.DrawEmbedded(EmbedHost, pane.Panel, box); + break; + default: + SectionContribution c = pane.Contribution!; + if (!c.Enabled) { DrawDisabledNote(c); break; } + DrawSurface(c, box); + break; + } + } + + /// <summary>An options tab: a server's (or every world's) option surfaces and command buttons.</summary> + private void DrawGroup(SectionGroup group, Vector2 box) + { + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + bool open = ImGuiNET.ImGui.BeginChild("##mr_group_" + group.Title, box, ImGuiChildFlags.AlwaysUseWindowPadding, + ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (!open) return; + if (group.Server is ServerState s) + Label(s.Force == ServerForce.Auto ? $"{s.Name}: detected ({s.Reason})." : $"{s.Name}: forced on for this character.", + Faded(Mute)); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + foreach (SectionContribution c in group.Items) + { + ImGuiNET.ImGui.PushID(c.Plugin + "|" + c.Label + "|" + c.Surface + c.Command); + try + { + if (c.IsSurface) DrawOptionSurface(c, w); + else DrawCommandButton(c, w); + } + finally + { + ImGuiNET.ImGui.PopID(); + } + } + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + } + + private void DrawOptionSurface(SectionContribution c, float w) + { + if (!ImGuiNET.ImGui.CollapsingHeader(c.Label, ImGuiTreeNodeFlags.DefaultOpen)) + { + if (c.Tooltip.Length > 0) SafeImGui.SetItemTooltip(c.Tooltip); + return; + } + if (c.Tooltip.Length > 0) SafeImGui.SetItemTooltip(c.Tooltip); + if (!c.Enabled) { DrawDisabledNote(c); return; } + string key = c.Plugin + "|" + c.Surface; + if (!_surfaceHeights.TryGetValue(key, out float h)) h = c.Height > 0 ? c.Height : 220f; + Vector2 want = DrawSurface(c, new Vector2(w, h)); + if (want.Y > 0 && Math.Abs(want.Y - h) > 1f) _surfaceHeights[key] = Math.Min(want.Y, SectionManifestParser.MaxSurfaceSize); + } + + private static void DrawCommandButton(SectionContribution c, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float bw = Math.Min(w, Math.Max(120f, ButtonWidth(c.Label))); + if (Button("##cmd", c.Label, p, new Vector2(bw, 22), c.Enabled ? Text : Faded(Text), BtnFill, c.Enabled)) + ServerMenus.Run(c.Command); + string tip = c.Enabled || c.Note.Length == 0 ? c.Tooltip : c.Note; + SafeImGui.SetItemTooltip(tip.Length > 0 ? tip + "\n" + c.Command : c.Command); + NextLine(p, 26); + if (!c.Enabled && c.Note.Length > 0) DrawDisabledNote(c); + } + + private static void DrawDisabledNote(SectionContribution c) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Faded(Mute)); + ImGuiNET.ImGui.PushTextWrapPos(0f); + SafeImGui.TextWrapped(c.Note.Length > 0 ? c.Note : c.Label + " isn't available right now."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } + + /// <summary> + /// A plugin surface in a child of <paramref name="box"/>; returns the size the plugin asked + /// for (zero when it didn't say). A surface whose export threw stays off for the session. + /// </summary> + private Vector2 DrawSurface(SectionContribution c, Vector2 box) + { + string key = c.Plugin + "|" + c.Surface; + if (_surfaceOff.Contains(key)) + { + Label($"{c.Label}: {c.Plugin} stopped drawing it (see the log).", Amber); + return Vector2.Zero; + } + if (!_surfaceBytes.TryGetValue(c.Surface, out byte[]? bytes)) + _surfaceBytes[c.Surface] = bytes = Encoding.UTF8.GetBytes(c.Surface + "\0"); + + int result = PluginManager.EmbedNotReady; + Vector2 want = Vector2.Zero; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + bool open = ImGuiNET.ImGui.BeginChild("##surf_" + key, box, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (open) + { + // Plugin widgets use the default UI font, as in their own windows. + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + try { result = PluginManager.RenderEmbed(c.Plugin, bytes, box, out want); } + finally { ImGuiNET.ImGui.PopFont(); } + if (result == PluginManager.EmbedNotReady) ImGuiNET.ImGui.TextDisabled("Loading..."); + else if (result == PluginManager.EmbedNoPlugin) + SafeImGui.TextDisabled($"{c.Plugin} isn't loaded, or is too old for this view."); + } + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + if (result == PluginManager.EmbedFailed) _surfaceOff.Add(key); + return result == PluginManager.EmbedDrawn ? want : Vector2.Zero; + } + + // ── Session Stats overview ────────────────────────────────────────── + + /// <summary> + /// The Session Stats section's stand-in, shown only while no plugin fills the section (RynthAi + /// does, with its session XP, luminance, kills and rates). The engine keeps no session totals + /// of its own here: it names the character and says where the numbers come from. + /// Character details are RynthOracle's Character tab; server picks are Options > Diagnostics. + /// </summary> + private void DrawOverview(SectionRegistry.Snapshot snap, Vector2 box) + { + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + bool open = ImGuiNET.ImGui.BeginChild("##mr_overview", box, ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (!open) return; + string who = SessionStateRegistry.LastCharacterName; + Label(who.Length > 0 ? who : "No character logged in", Teal); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + Separator(w); + ImGuiNET.ImGui.PushTextWrapPos(0f); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Faded(Mute)); + SafeImGui.TextWrapped("This session's XP, luminance, kills and their per-hour rates come with RynthAi's " + + "Session Stats; RynthAi isn't loaded (or is too old to show them here). " + + "Character details: RynthOracle's Character tab (/ro character). Server picks: Options > Diagnostics."); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopTextWrapPos(); + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + } + + // ── Menu ──────────────────────────────────────────────────────────── + + /// <summary>The menu's section half: every section, the active servers' items, the rail switch.</summary> + private void DrawSectionsMenuItems() + { + SectionRegistry.Snapshot snap = SectionRegistry.Current; + if (ImGuiNET.ImGui.MenuItem("Remote##sec_remote", "", IsRemote)) SelectSection(SectionCatalog.RemoteId); + foreach (SectionView v in snap.Sections) + if (ImGuiNET.ImGui.MenuItem(v.Label + "##sec_" + v.Id, "", v.Id.Equals(_section, StringComparison.OrdinalIgnoreCase))) + SelectSection(v.Id); + ServerMenus.DrawImGuiMenu(separatorFirst: true); + ImGuiNET.ImGui.Separator(); + bool rail = RailShown; + if (ImGuiNET.ImGui.MenuItem("Show the sections rail", "", rail)) + PanelColumnStore.Set(RailKey, rail ? 0f : 1f); + SafeImGui.SetItemTooltip("The column of sections down the left. Hidden, RynthAi's remote shows its own tab bar again " + + "(Gear, Games and the other ILT tabs), and a section is picked here or with /rc miniremote section <name>."); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs index b84f73c..d3cba40 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs @@ -1,11 +1,16 @@ // ============================================================================ // RynthCore.Engine - ImGui/Panels/MiniRemoteFace.cs -// The Mini Remote: one window for the quick-use item slots, whoever draws them. +// The Mini Remote: one window for the quick-use item slots, whoever draws them, +// and the sections (MiniRemoteFace.Sections.cs): a rail down the left with +// Remote (this file) and the core sections Char, Map, Skills, Combat, Nav, +// Inventory, Crafting, Spells, Chat, Friends, Fellowship and Pets, plus any a +// plugin adds, each showing its engine panels or plugin views and the active +// servers' options (UI/Sections). // // With RynthAi loaded it hosts RynthAi's Mini Remote (session rates, target, // summon, item slots, toggles, bank, rebuff, Translate, Guardian and its // Options menu, its Quests and Pets tabs, plus on ILT worlds the RynthILT -// plugin's tabs Character, Banking, Gear, Charms and Games, which RynthAi asks +// plugin's tabs Charms, Banking, Gear and Games (Character moved to RynthOracle, 2026.10.5.54), which RynthAi asks // RynthILT to draw), drawn by the plugin through // RynthPluginRenderEmbed ("miniremote-window"). The window fits itself to what // the plugin asks for whenever that changes (another tab, a section shown or @@ -47,7 +52,7 @@ using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; namespace RynthCore.Engine.ImGuiBackend.Panels; -internal sealed class MiniRemoteFace : IImGuiPanel +internal sealed partial class MiniRemoteFace : IImGuiPanel { public const string Title = "Mini Remote"; @@ -59,8 +64,21 @@ internal sealed class MiniRemoteFace : IImGuiPanel ItemHudStore.EnsureLoadQueued(); } - /// <summary>The RynthAi surface for this window (NUL-terminated for the export).</summary> - private static ReadOnlySpan<byte> Surface => "miniremote-window\0"u8; + /// <summary> + /// The RynthAi surface for this window (NUL-terminated for the export): "miniremote-remote" + /// (the remote alone: its tabs are sections here) from a RynthAi that publishes sections + /// while the sections rail shows, else "miniremote-window" (the remote with its own tab bar). + /// With the rail hidden the tab bar is the only way to RynthILT's tabs (Gear, Games). + /// </summary> + private static ReadOnlySpan<byte> Surface => + RailShown && RynthAiPublishesSections() ? "miniremote-remote\0"u8 : "miniremote-window\0"u8; + + private static bool RynthAiPublishesSections() + { + foreach (UI.Sections.SectionManifest m in UI.Sections.SectionRegistry.Current.Manifests) + if (m.Plugin.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)) return true; + return false; + } private const float Gap = 4f, StatusH = 18f; /// <summary>Pixels a Ctrl+wheel notch or a Bigger / Smaller menu click changes the box edge by.</summary> @@ -116,12 +134,39 @@ internal sealed class MiniRemoteFace : IImGuiPanel public void Draw() { float w = Begin(out Vector2 origin, out Vector2 size); - if (DrawRynthAi(w, origin, size)) - { - End(origin, size); - return; - } + UI.Sections.SectionRegistry.Snapshot snap = UI.Sections.SectionRegistry.Current; + TakeRequestedSection(snap); + // The rail, then everything else to its right (the indent keeps each line there). + float railW = RailShown ? DrawRail(snap, origin, size) : 0f; + if (railW > 0) + { + ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(6 + railW, 6)); + ImGuiNET.ImGui.Indent(railW); + } + float cw = Math.Max(40f, w - railW); + try + { + if (!IsRemote) + { + // This window is still the Mini Remote while it shows another section: RynthAi + // keeps its floating copy hidden while it hears from it each frame. + if (!_embedOff) PingRynthAiHost(); + DrawSection(snap, cw, origin, size); + } + else if (!DrawRynthAi(cw, origin, size)) DrawEngineGrid(cw, origin, size); + } + finally + { + if (railW > 0) ImGuiNET.ImGui.Unindent(railW); + } + End(origin, size); + DrawMenu(); + } + + /// <summary>The engine's own slot grid (no RynthAi to draw the remote).</summary> + private void DrawEngineGrid(float w, Vector2 origin, Vector2 size) + { InventoryView view = InventoryModel.Current; HudItem[] items = _items.Get(view); ItemHudCharacter data = ItemHudStore.Current; @@ -133,8 +178,6 @@ internal sealed class MiniRemoteFace : IImGuiPanel DrawGrid(data, items, w, gridH, ready); DrawStatus(ready); FitGrid(data, w, haveH); - End(origin, size); - DrawMenu(data, items); } // ── RynthAi's Mini Remote ─────────────────────────────────────────── @@ -184,6 +227,15 @@ internal sealed class MiniRemoteFace : IImGuiPanel return true; } + /// <summary>"miniremote-host": tells RynthAi this window is open on a section; it draws nothing.</summary> + private void PingRynthAiHost() + { + int result; + try { result = PluginManager.RenderEmbed("RynthAi", "miniremote-host\0"u8, Vector2.Zero, out _); } + catch { result = PluginManager.EmbedFailed; } + if (result == PluginManager.EmbedFailed) _embedOff = true; + } + // ── Window fit ────────────────────────────────────────────────────── /// <summary> @@ -301,7 +353,7 @@ internal sealed class MiniRemoteFace : IImGuiPanel dl.AddText(cp, id == 0 ? Amber : Text, count); } if (hot) - ImGuiNET.ImGui.SetItemTooltip(id == 0 + SafeImGui.SetItemTooltip(id == 0 ? $"{s.Name}: none carried.\nRight-click for options." : $"{s.Name} ({count switch { "" => "1", _ => count }} carried)\nClick to use. Right-click for options."); } @@ -391,7 +443,11 @@ internal sealed class MiniRemoteFace : IImGuiPanel // ── Right-click menu ──────────────────────────────────────────────── - private void DrawMenu(ItemHudCharacter data, HudItem[] items) + /// <summary> + /// The right-click menu: a slot's options (the engine grid), then the sections, the active + /// servers' items and the rail switch. Opened from a slot or from the rail. + /// </summary> + private void DrawMenu() { if (_openMenu) { @@ -407,6 +463,23 @@ internal sealed class MiniRemoteFace : IImGuiPanel ImGuiNET.ImGui.PopStyleColor(3); if (!open) return; + try + { + if (_menuSlot >= 0 && IsRemote) + { + DrawSlotMenu(ItemHudStore.Current, _items.Get(InventoryModel.Current)); + ImGuiNET.ImGui.Separator(); + } + DrawSectionsMenuItems(); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + } + } + + private void DrawSlotMenu(ItemHudCharacter data, HudItem[] items) + { int i = _menuSlot; RemoteSlot? s = i >= 0 && i < data.Slots.Length ? data.Slots[i] : null; Label(i >= 0 ? $"Slot {i + 1}{(s != null ? ": " + s.Name : " (empty)")}" : "Mini Remote", Mute); @@ -430,6 +503,5 @@ internal sealed class MiniRemoteFace : IImGuiPanel ResizeSlots(-SlotSizeStep); if (ImGuiNET.ImGui.MenuItem("Default box size", "", false, px != ItemHudCharacter.DefaultSlotSize)) ResizeSlots(ItemHudCharacter.DefaultSlotSize - px); - ImGuiNET.ImGui.EndPopup(); } } diff --git a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs index 36d4235..f8ca69f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs @@ -296,7 +296,7 @@ internal sealed class NavFace : IImGuiPanel { string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label; bool clicked = Button(id, text, pos, new Vector2(width, 22), on ? Teal : Mute, BtnFill, leftAlign: true); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tooltip); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(tooltip); return clicked; } @@ -324,7 +324,7 @@ internal sealed class NavFace : IImGuiPanel dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, label); ImGuiNET.ImGui.SetCursorScreenPos(p); ImGuiNET.ImGui.InvisibleButton("##reach_label", new Vector2(Math.Max(1, labelW), 22)); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(SettingsSchema.NavPointReachTip); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(SettingsSchema.NavPointReachTip); const float stepW = 22, boxW = 52; float right = p.X + w; @@ -456,7 +456,7 @@ internal sealed class NavFace : IImGuiPanel _picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i => NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300); if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) - ImGuiNET.ImGui.SetTooltip(_data.TrailPoints >= 2 + SafeImGui.SetTooltip(_data.TrailPoints >= 2 ? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed." : "Turn on Breadcrumbs and walk a while to build a trail."); NextLine(p, 26); diff --git a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs index 5c61b8b..7d8e35e 100644 --- a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs +++ b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs @@ -130,14 +130,14 @@ internal sealed class StatusFace : IImGuiPanel private static void Header(string text) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(HeaderColor, text); + SafeImGui.TextColored(HeaderColor, text); ImGuiNET.ImGui.PopFont(); } private static void Row(string text, bool error) { ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, error ? ErrorColor : RowColor); - ImGuiNET.ImGui.TextWrapped(text); + SafeImGui.TextWrapped(text); ImGuiNET.ImGui.PopStyleColor(); } @@ -274,7 +274,7 @@ internal sealed class TrackerFace : IImGuiPanel { float rowRight = ImGuiNET.ImGui.GetCursorPosX() + ImGuiNET.ImGui.GetContentRegionAvail().X; if (ImGuiNET.ImGui.GetCursorScreenPos().Y + rowH > gripTop) rowRight -= grip; - ImGuiNET.ImGui.TextColored(LabelColor, labels[i]); + SafeImGui.TextColored(LabelColor, labels[i]); if (labels[i].StartsWith("Pass", StringComparison.Ordinal)) ImGuiNET.ImGui.SetItemTooltip("Luminance that reached your bank without a \"You've banked\" line: your vassals' pass-up.\nFellowship and Zone Share splits arrive the same silent way and are included."); else if (labels[i] == "Lum/5m") diff --git a/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs b/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs index 2db2817..f7c1467 100644 --- a/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs +++ b/src/RynthCore.Engine/ImGui/Panels/QuickSettingsDrawer.cs @@ -173,14 +173,14 @@ internal sealed class QuickSettingsDrawer : RynthAiDrawer { header = true; ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Highlight), tab.Name); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Highlight), tab.Name); } bool pinned = QuickSettings.IsPinned(key); ImGuiNET.ImGui.PushID(key); // Stays open, so several can be pinned in one go; the section shows dimmed at the right. if (ImGuiNET.ImGui.Selectable((pinned ? PhosphorIcons.Check : " ") + " " + label, pinned, ImGuiSelectableFlags.NoAutoClosePopups)) QuickSettings.SetPinned(key, !pinned); - if (row.Tooltip != null) ImGuiNET.ImGui.SetItemTooltip(row.Tooltip); + if (row.Tooltip != null) SafeImGui.SetItemTooltip(row.Tooltip); if (section.Length > 0) { Vector2 max = ImGuiNET.ImGui.GetItemRectMax(), min = ImGuiNET.ImGui.GetItemRectMin(); diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs index 0887100..e7ff050 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs @@ -131,7 +131,7 @@ internal sealed class RadarFace : IImGuiPanel { if (IconButton("##radar_pop", popPos, ImGuiPanelHost.PopOutGlyph)) ImGuiPanelHost.TogglePopOut(Title); - ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); + SafeImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); } bool gear = IconButton("##radar_gear", gearPos, PhosphorIcons.Gear); ImGuiNET.ImGui.SetItemTooltip("Radar settings"); @@ -630,7 +630,7 @@ internal sealed class RadarFace : IImGuiPanel bool sub = kind == RadarKind.OwnCorpse; if (sub) { ImGuiNET.ImGui.Indent(14 * scale); ImGuiNET.ImGui.BeginDisabled(!RadarSettingsStore.ShowCorpses); } changed |= ImGuiNET.ImGui.Checkbox("##show", ref RadarSettingsStore.ShowFlag(kind)); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(KindTips[kind]); ImGuiNET.ImGui.SameLine(); // The marker exactly as the radar draws it; faded while the kind is hidden, so the // legend doesn't look like the box did nothing. @@ -644,7 +644,7 @@ internal sealed class RadarFace : IImGuiPanel ImGuiNET.ImGui.SameLine(); ImGuiNET.ImGui.AlignTextToFramePadding(); ImGuiNET.ImGui.TextUnformatted(label); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(KindTips[kind]); ImGuiNET.ImGui.SameLine(190 * scale); Vector4 v = RynthTheme.Vec(RadarSettingsStore.KindColors[kind]); if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, pickFlags)) diff --git a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs index 687630f..4bb448b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs @@ -208,7 +208,7 @@ internal sealed class RangesSlideOut : RynthAiDrawer 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); + SafeImGui.SetItemTooltip(r.Tip); // Box at the right. float boxW = 46 * k; @@ -226,7 +226,7 @@ internal sealed class RangesSlideOut : RynthAiDrawer } else WriteValue(r, value); // bad input reverts } - ImGuiNET.ImGui.SetItemTooltip(r.Tip); + SafeImGui.SetItemTooltip(r.Tip); // Slider between them: drag (or click) to pick, saved when let go. float sx = x + labelW, sw = boxX - 6 * k - sx; @@ -250,7 +250,7 @@ internal sealed class RangesSlideOut : RynthAiDrawer r.Dragging = false; if (r.DragValue != value) Changed(r, r.DragValue); } - ImGuiNET.ImGui.SetItemTooltip(r.Tip); + SafeImGui.SetItemTooltip(r.Tip); float cy = y + h * 0.5f; float frac = s.Max > s.Min ? (float)((shownValue - s.Min) / (s.Max - s.Min)) : 0f; @@ -321,13 +321,13 @@ internal sealed class RangesSlideOut : RynthAiDrawer 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); + SafeImGui.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); + SafeImGui.SetItemTooltip(monster ? _damageTip : NoDamageTip); // Name line. string name; uint nameColor; @@ -362,7 +362,7 @@ internal sealed class RangesSlideOut : RynthAiDrawer { ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, fy)); ImGuiNET.ImGui.InvisibleButton("##mon_facts", new Vector2(w, 2 * lh)); - ImGuiNET.ImGui.SetItemTooltip(_factsTip); + SafeImGui.SetItemTooltip(_factsTip); } } diff --git a/src/RynthCore.Engine/ImGui/Panels/ReportFace.cs b/src/RynthCore.Engine/ImGui/Panels/ReportFace.cs index b93449c..e150b44 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ReportFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ReportFace.cs @@ -149,7 +149,7 @@ internal sealed class ReportFace : IImGuiPanel if (Button("##report_send", label, row, new Vector2(bw, 24), Text, StartBg, enabled: enabled)) StartSend(); if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled | ImGuiHoveredFlags.ForTooltip)) - ImGuiNET.ImGui.SetTooltip(!hasText ? "Write what went wrong first." + SafeImGui.SetTooltip(!hasText ? "Write what went wrong first." : cooldown > 0 ? "One report a minute: " + CooldownText(cooldown) : "Send this report to the staff."); NextLine(row, 28); diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs index 7e19672..d87de76 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs @@ -16,8 +16,8 @@ // item slots, toggles, bank, rebuff, Translate, Guardian) // with its Options menu. The plugin draws it here through // RynthPluginRenderEmbed("miniremote") and says how big it -// wants the panel; the Hub launcher's right-click opens it -// (popped out: the floating Mini Remote instead). +// wants the panel; its drawer tab opens it (popped out +// there are no drawers: the Mini Remote window instead). // AC thread only (inside the dashboard's Draw). // ============================================================================ @@ -187,7 +187,7 @@ internal sealed partial class RynthAiFace } } - /// <summary>RynthAi's Mini Remote, drawn by the plugin into this drawer (the Hub launcher's right-click).</summary> + /// <summary>RynthAi's Mini Remote, drawn by the plugin into this drawer (its drawer tab).</summary> private sealed class RemoteDrawer : RynthAiDrawer { /// <summary>The plugin surface name, NUL-terminated for the export.</summary> @@ -207,7 +207,7 @@ internal sealed partial class RynthAiFace public override string TabTooltip(bool right) => "Mini Remote: session rates, attack target, summon, item slots, toggles, bank, rebuff, Translate.\n" + - "Its Options button picks the sections (also: right-click Hub). RynthILT's ILT tabs are in the Mini Remote window.\n" + + "Its Options button picks the sections. RynthILT's ILT tabs are in the Mini Remote window (Char, or the bar button).\n" + "Click to slide it out."; public override float Width(float k) => @@ -247,12 +247,12 @@ internal sealed partial class RynthAiFace { _want = Vector2.Zero; ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, DMute); - ImGuiNET.ImGui.TextWrapped(result switch + SafeImGui.TextWrapped(result switch { PluginManager.EmbedNoPlugin => - "This RynthAi can't draw its Mini Remote here (it needs RynthAi 0.5.27 or later). Left-click Hub for the floating Mini Remote.", + "This RynthAi can't draw its Mini Remote here (it needs RynthAi 0.5.27 or later). Use the bar's Mini Remote button (/rc miniremote).", PluginManager.EmbedFailed => - "The Mini Remote failed to draw here (see the log). Left-click Hub for the floating Mini Remote.", + "The Mini Remote failed to draw here (see the log). Use the bar's Mini Remote button (/rc miniremote).", _ => "The Mini Remote shows here once RynthAi is ready: in the world, with plugin windows on (engine.json EnablePluginOverlayWindows).", }); ImGuiNET.ImGui.PopStyleColor(); diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index 672aa40..f96eac4 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -280,7 +280,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y)); ImGuiNET.ImGui.InvisibleButton("##dash_drag", new Vector2(Math.Max(1, width - chipsW), rowH)); ImGuiPanelHost.DragWindowWithLastItem(); - ImGuiNET.ImGui.SetItemTooltip(DragTip); + SafeImGui.SetItemTooltip(DragTip); ImFontPtr title = ImGuiFonts.Get(UiFont.Dash14); float ty = y + (rowH - title.FontSize) * 0.5f; @@ -314,7 +314,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel RynthAiDashboardState.SetShowTargetBar(!target); _fit = true; } - ImGuiNET.ImGui.SetItemTooltip(target + SafeImGui.SetItemTooltip(target ? "Target bar on: the target's name and health at the bottom. Click to hide it." : "Target bar off. Click to show the target's name and health at the bottom."); cx += chipW + chipGap; @@ -324,14 +324,14 @@ internal sealed partial class RynthAiFace : IImGuiPanel RynthAiDashboardState.SetShowVitals(!vitals); _fit = true; } - ImGuiNET.ImGui.SetItemTooltip(vitals + SafeImGui.SetItemTooltip(vitals ? "Player vitals on: your health, stamina and mana at the bottom. Click to hide them." : "Player vitals off. Click to show your health, stamina and mana at the bottom."); cx += chipW + chipGap; if (IconButton("##chip_lock", new Vector2(cx, cy), chip, raw.IsLocked ? PhosphorIcons.Lock : PhosphorIcons.LockOpen, chipFont, BtnFill, raw.IsLocked ? Amber : Mute, BtnBord, chipRound)) RynthAiCommands.TogglePanelLock(); - ImGuiNET.ImGui.SetItemTooltip(raw.IsLocked ? "Locked. Click to unlock the dashboard." : "Click to lock the dashboard in place."); + SafeImGui.SetItemTooltip(raw.IsLocked ? "Locked. Click to unlock the dashboard." : "Click to lock the dashboard in place."); cx += chipW + chipGap; if (IconButton("##chip_minus", new Vector2(cx, cy), chip, PhosphorIcons.Minus, chipFont, BtnFill, Mute, BtnBord, chipRound)) RynthAiCommands.AdjustOpacity(-0.1f); @@ -347,13 +347,13 @@ internal sealed partial class RynthAiFace : IImGuiPanel RynthAiDashboardState.SetMinimized(!minimized); _fit = true; // the window fits the other mode's content next frame } - ImGuiNET.ImGui.SetItemTooltip(minimized ? "Expand" : "Minimize"); + SafeImGui.SetItemTooltip(minimized ? "Expand" : "Minimize"); cx += chipW + chipGap; if (PanelRouter.CanPopOut) { if (IconButton("##chip_dock", new Vector2(cx, cy), chip, ImGuiPanelHost.PopOutGlyph, chipFont, BtnFill, Mute, BtnBord, chipRound)) ImGuiPanelHost.TogglePopOut(Title); - ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); + SafeImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); } // The size, from the title row (no host title bar here): Ctrl+wheel steps it, right-click @@ -574,7 +574,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (IconButton("##macro", new Vector2(x, y), square, on ? PhosphorIcons.Stop : PhosphorIcons.Play, UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, round)) RynthAiCommands.ToggleMacro(); - ImGuiNET.ImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it."); + SafeImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it."); x += sqStep + Px(6); } Toggle("##t_combat", PhosphorIcons.Sword, raw.CombatEnabled, 0, new Vector2(x, y), "Combat", @@ -601,7 +601,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (IconButton("##t_sort", new Vector2(x, y), square, PhosphorIcons.SortAscending, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, round)) RynthSortCommands.SetAuto(!on); - ImGuiNET.ImGui.SetItemTooltip(on ? "Auto-sort (RynthSort) on. Click to turn it off." : "Auto-sort (RynthSort) off. Click to turn it on."); + SafeImGui.SetItemTooltip(on ? "Auto-sort (RynthSort) on. Click to turn it off." : "Auto-sort (RynthSort) off. Click to turn it on."); x += sqStep; } @@ -615,7 +615,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (IconButton("##files_open", new Vector2(frX - Px(4) - caretW, y), new Vector2(caretW, sq), PhosphorIcons.CaretDown, UiFont.Dash11, BtnFill, Teal, BtnBord, Px(2))) RynthAiDashboardState.SetFilesOpen(true); - ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") + + SafeImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") + "\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") + "\nBuffs: " + (view?.BuffText ?? "Built-in") + "\n\nClick to show the Profile, Nav, Loot, Meta and Buffs pickers."); @@ -644,7 +644,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel dl.PopClipRect(); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ax, y)); ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, sq)); - ImGuiNET.ImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + (view?.MetaStateText ?? "Default")); + SafeImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + (view?.MetaStateText ?? "Default")); } } @@ -671,7 +671,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (IconButton(id, pos, new Vector2(sq, sq), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Off, on ? Teal : BtnBord, Px(3))) RynthAiCommands.SetSubsystemEnabled(subsystem, !on); bool right = ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right); - ImGuiNET.ImGui.SetItemTooltip((on ? name + " on. Click to turn it off." : name + " off. Click to turn it on.") + + SafeImGui.SetItemTooltip((on ? name + " on. Click to turn it off." : name + " off. Click to turn it on.") + "\nRight-click: " + rightWhat + "."); if (on) ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(new Vector2(pos.X + Px(5), pos.Y + sq - Px(3.5f)), @@ -711,7 +711,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel { float y = ImGuiNET.ImGui.GetCursorScreenPos().Y; // Nav and Meta left the row (2026-10-14): right-click the Navigation and Meta toggles. - const int buttons = 8; + // Hub left it 2026-10-15 (the Mini Remote: the bar button, Char's menu, its drawer tab). + const int buttons = 7; float gap = Px(LauncherGap); float bw = MathF.Floor((width - buttons * gap) / buttons); // Short labels only when every button has room for its icon and label. @@ -752,31 +753,20 @@ internal sealed partial class RynthAiFace : IImGuiPanel } x += bw + gap; - // Char and Hub open the Mini Remote window (MiniRemoteFace, hosting RynthAi's remote): Char - // on its Character tab (RynthILT's ILT tab; elsewhere the remote shows), Hub as it was left. + // Char opens RynthOracle's Character tab (character, level XP, session rates) since + // 2026.10.5.54 (Infinite Leaftide's charms stay RynthILT's, in the Mini Remote's ILT tabs, + // Char's right-click > Server); without RynthOracle, the Mini Remote's + // Session Stats section. The Mini Remote as it was left is the bar button (/rc miniremote) + // and "Mini Remote" in Char's right-click menu; its drawer is the drawer tab on the dashboard's + // edge. (The Hub launcher, which opened the same window, left the row 2026-10-15.) Launcher("##l_char", PhosphorIcons.User, "Char", - "Char. Left-click: the Mini Remote on its Character tab (ILT worlds). Right-click: Character windows (Spells, Quests, Pets, Skills, Inventory...), then Server: this server's plugin windows.", - x, y, bw, labels, () => ShowMiniRemoteTab("character"), false); + "Char. Left-click: RynthOracle's Character tab (Infinite Leaftide's charms and banking: the Mini Remote's ILT tabs). Right-click: Character windows (Mini Remote, Spells, Quests, Pets, Crafting, Fellowship, Skills, Inventory...), then Server: this server's plugin windows.", + x, y, bw, labels, ShowCharacter, CharacterOpen()); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1)); ImGuiNET.ImGui.OpenPopup("##charmenu"); } - x += bw + gap; - // Left-click is the Mini Remote window (MiniRemoteFace, which hosts RynthAi's remote, the - // same window as the bar button). Right-click is the Mini Remote drawer, as Patrol's is - // its drawer; popped out there are no drawers, so it opens the window. Inventory HUDs - // setup is in the Mini Remote's Options menu. - Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub", - popped ? "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: open the Mini Remote window." - : "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: the Mini Remote drawer (left), with its Options.", - x, y, bw, labels, () => PanelRouter.Toggle(MiniRemoteFace.Title), - ImGuiPanelHost.IsOpen(MiniRemoteFace.Title) || (!popped && _drawers.IsOpen(_remote))); - if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) - { - if (popped) ImGuiPanelHost.Open(MiniRemoteFace.Title); - else _drawers.Toggle(_remote); - } ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + Px(LauncherH))); } @@ -791,7 +781,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(pos); bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight) && ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Left); - ImGuiNET.ImGui.SetItemTooltip(tooltip); + SafeImGui.SetItemTooltip(tooltip); bool hot = ImGuiNET.ImGui.IsItemHovered(); uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : hot ? Lighten(BtnFill) : BtnFill; uint fg = lit ? Teal : hot ? White : Mute; @@ -986,9 +976,10 @@ internal sealed partial class RynthAiFace : IImGuiPanel // (UI.ServerMenus): the installed server plugins' windows for the world you're on. /// <summary> - /// Opens the Mini Remote window on one of its tabs ("" = the remote). Quests and Pets show on - /// every server; RynthILT's ILT tabs show once the server reports that feature on (and only with - /// RynthILT), and until then the window shows the remote. + /// Opens the Mini Remote window on one of its tabs ("" = the remote). Pets and Crafting show on + /// every server (Quests and Fellowship are RynthOracle's windows since 2026-10-13); RynthILT's ILT + /// tabs show once the server reports that feature on (and only with RynthILT), and until then + /// the window shows the remote. /// </summary> private static void ShowMiniRemoteTab(string section) { @@ -996,6 +987,23 @@ internal sealed partial class RynthAiFace : IImGuiPanel RynthAiCommands.ApplyRemoteCommand("hub", section.Length > 0 ? "tab " + section : "tab"); } + /// <summary> + /// RynthOracle's Character tab ("/ro character"), or the Mini Remote's Session Stats section + /// when RynthOracle isn't loaded. Every generic "Character" link goes here (Leaftide's Charms + /// and Banking are RynthILT's Mini Remote tabs, in the menu's server half). + /// </summary> + private static void ShowCharacter() + { + if (UI.ScriptWindows.ScriptWindowRegistry.Has(OracleMainKey)) UI.ServerMenus.Run("/ro character"); + else UI.ServerMenus.Run("/rc miniremote section char"); + } + + /// <summary>The Char launcher is lit: RynthOracle's window is open (else the Mini Remote on Session Stats).</summary> + private static bool CharacterOpen() => + UI.ScriptWindows.ScriptWindowRegistry.Has(OracleMainKey) + ? UI.ScriptWindows.ScriptWindowRegistry.IsOpen(OracleMainKey) + : ImGuiPanelHost.IsOpen(MiniRemoteFace.Title) && MiniRemoteFace.ShowsSection("char"); + /// <summary>A Char menu item that toggles a registered ImGui panel (checked while open).</summary> private static void PanelMenuItem(string title, string command) { @@ -1004,6 +1012,23 @@ internal sealed partial class RynthAiFace : IImGuiPanel PanelRouter.Toggle(title); } + // RynthOracle's script window keys (RynthOraclePlugin: UiWindow keys). + private const string OracleMainKey = "RynthOracle/Oracle"; + private const string OracleTimersKey = "RynthOracle/QuestTimers"; + + /// <summary> + /// A Character menu line for one of RynthOracle's script windows: toggles it as the bar does, + /// checked while open, greyed out when RynthOracle isn't loaded (or hasn't drawn it yet). + /// </summary> + private static void OracleMenuItem(string label, string command, string key, string tooltip) + { + bool has = UI.ScriptWindows.ScriptWindowRegistry.Has(key); + bool open = has && UI.ScriptWindows.ScriptWindowRegistry.IsOpen(key); + if (ImGuiNET.ImGui.MenuItem(label, command, open, has)) + UI.ScriptWindows.ScriptWindowRegistry.PlayerSetVisible(key, !open); + SafeImGui.SetItemTooltip(has ? tooltip : tooltip + " (RynthOracle isn't loaded.)"); + } + private static void CharMenu() { ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); @@ -1016,16 +1041,31 @@ internal sealed partial class RynthAiFace : IImGuiPanel try { ImGuiNET.ImGui.TextDisabled("Character"); + bool hasOracle = UI.ScriptWindows.ScriptWindowRegistry.Has(OracleMainKey); + if (ImGuiNET.ImGui.MenuItem("Character", "/ro character", false, hasOracle)) ShowCharacter(); + SafeImGui.SetItemTooltip(hasOracle + ? "RynthOracle's Character tab: level, XP and session rates. Infinite Leaftide's charms and banking are the Mini Remote's ILT tabs (Server, below)." + : "RynthOracle's Character tab (RynthOracle isn't loaded)."); if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", ImGuiPanelHost.IsOpen(MiniRemoteFace.Title))) ShowMiniRemoteTab(""); if (ImGuiNET.ImGui.MenuItem("Spells", "/rc spells")) RynthAiCommands.ApplyRemoteCommand("spells", "toggle"); ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: the spell catalog and buff profiles."); + // Quests live in RynthOracle (its script windows), since 2026-10-13. + OracleMenuItem("Quests", "/ro", OracleMainKey, + "RynthOracle: every quest flag, timers, tracking, rewards and (Infinite Leaftide) the /qb list."); + OracleMenuItem("Quest Timers", "/ro timers", OracleTimersKey, + "RynthOracle's Quest Timers: the quests you track and the time left on each."); // The Mini Remote's universal tabs (every server); RynthILT's ILT tabs are in the server half. - if (ImGuiNET.ImGui.MenuItem("Quests", "/rc miniremote tab quests")) ShowMiniRemoteTab("quests"); - ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Quests tab: /myquests timers and favorites (RynthAi)."); if (ImGuiNET.ImGui.MenuItem("Pets", "/rc miniremote tab pets")) ShowMiniRemoteTab("pets"); ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Pets tab: summoning essences, priorities and the healing pet (RynthAi)."); + if (ImGuiNET.ImGui.MenuItem("Crafting", "/rc miniremote tab crafting")) ShowMiniRemoteTab("crafting"); + ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Crafting tab: armor, weapon, jewelry and item tinkering, chunking and arrows (RynthAi)."); + // Fellowship is RynthOracle's Fellowship tab ("/ro fellowship" opens the window on it). + if (ImGuiNET.ImGui.MenuItem("Fellowship", "/ro fellowship", false, hasOracle)) UI.ServerMenus.Run("/ro fellowship"); + SafeImGui.SetItemTooltip(hasOracle + ? "RynthOracle's Fellowship tab: members, leader, open / locked, XP sharing and (Infinite Leaftide) the /fship commands." + : "RynthOracle's Fellowship tab (RynthOracle isn't loaded)."); PanelMenuItem(SkillsFace.Title, "/rc skills"); PanelMenuItem(InventoryFace.Title, "/rc inventory"); PanelMenuItem(ItemCountFace.Title, "/rc itemcount"); @@ -1072,14 +1112,14 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (withTitle) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash11)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), PatrolTitle); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), PatrolTitle); ImGuiNET.ImGui.PopFont(); } Section("THIS DUNGEON"); if (info.InDungeon) { - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), $"0x{info.CurrentLandblock} · {info.CurrentHazards} hazard cell(s)"); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), $"0x{info.CurrentLandblock} · {info.CurrentHazards} hazard cell(s)"); if (info.CurrentHazards > 0) { ImGuiNET.ImGui.SameLine(); @@ -1109,7 +1149,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel { DungeonHazards d = info.Dungeons[i]; ImGuiNET.ImGui.PushID(i); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), $"0x{d.Landblock} · {d.Cells} cell(s)"); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), $"0x{d.Landblock} · {d.Cells} cell(s)"); ImGuiNET.ImGui.SameLine(); if (Mini("Clear")) RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}", refreshPatrol: true); @@ -1122,7 +1162,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (info.Routes.Length == 0) ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), "No .nav routes saved."); foreach (string name in info.Routes) - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "• " + name); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "• " + name); ImGuiNET.ImGui.PopFont(); } @@ -1134,7 +1174,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel { ImGuiNET.ImGui.Dummy(new Vector2(0, Px(4))); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), text); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), text); ImGuiNET.ImGui.PopFont(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs index a3c2010..e4975fc 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs @@ -130,7 +130,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel { if (IconButton("##rna_pop", ImGuiPanelHost.PopOutGlyph, popPos, new Vector2(sb, sb), Done, Glass, font: UiFont.Ui9)) ImGuiPanelHost.TogglePopOut(Title); - ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); + SafeImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); } if (IconButton("##rna_close", PhosphorIcons.X, closePos, new Vector2(sb, sb), Done, Glass, font: UiFont.Ui9)) ImGuiPanelHost.Close(Title); @@ -151,11 +151,11 @@ internal sealed class RynthNavArrowFace : IImGuiPanel if (typed.Length > 0) RynthNavCommands.Command("route " + typed); else if (st?.Arrow is RynthNavArrow pa) RynthNavCommands.Route(pa.Final, pa.FinalNs, pa.FinalEw); } - ImGuiNET.ImGui.SetItemTooltip(typed.Length > 0 + SafeImGui.SetItemTooltip(typed.Length > 0 ? "Plan a route to " + typed + " without walking it (the steps open below)" : "Plan a route to the arrow's target without walking it (the steps open below)"); bool go = IconButton("##rna_go", PhosphorIcons.Play, goPos, new Vector2(b, b), Green, BtnFill, enabled: canGo, font: UiFont.Ui11); - ImGuiNET.ImGui.SetItemTooltip(typed.Length > 0 + SafeImGui.SetItemTooltip(typed.Length > 0 ? "Go to " + typed + " (with portals and recalls when RynthNav's routing is on)" : "Go: RynthNav walks to the arrow's target (with portals and recalls when its routing is on)"); if ((go || enter) && canGo) @@ -172,7 +172,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel _showRoute = !_showRoute; _scrolledTo = -1; } - ImGuiNET.ImGui.SetItemTooltip(hasRoute ? (_showRoute ? "Hide the route's steps" : "Show the route's steps") : "No route yet: Plan or Go makes one"); + SafeImGui.SetItemTooltip(hasRoute ? (_showRoute ? "Hide the route's steps" : "Show the route's steps") : "No route yet: Plan or Go makes one"); if (_showRoute && hasRoute) RouteList(st!, new Vector2(origin.X + pad, rowY + b + 4), new Vector2(size.X - 2 * pad, listH), bold, lineH); @@ -183,7 +183,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel ImGuiNET.ImGui.InvisibleButton("##rna_surface", new Vector2(size.X, rowY - origin.Y - 2)); ImGuiPanelHost.DragWindowWithLastItem(); if (ImGuiNET.ImGui.IsItemHovered() && _read.Tooltip.Length > 0) - ImGuiNET.ImGui.SetItemTooltip(_read.Tooltip + (_read.Line3.Length > 0 && _read.Kind == "portal" ? "\n" + _read.Line3 : "")); + SafeImGui.SetItemTooltip(_read.Tooltip + (_read.Line3.Length > 0 && _read.Kind == "portal" ? "\n" + _read.Line3 : "")); } /// <summary>The coordinates or place typed in the box, trimmed.</summary> @@ -242,7 +242,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel ImGuiNET.ImGui.TextUnformatted(st.RouteLines[i]); ImGuiNET.ImGui.PopStyleColor(); if (ImGuiNET.ImGui.IsItemHovered()) - ImGuiNET.ImGui.SetTooltip(current && st.StepLeft.Length > 0 ? st.RouteLines[i] + "\n" + st.StepLeft : st.RouteLines[i]); + SafeImGui.SetTooltip(current && st.StepLeft.Length > 0 ? st.RouteLines[i] + "\n" + st.StepLeft : st.RouteLines[i]); if (current && _scrolledTo != i) { ImGuiNET.ImGui.SetScrollHereY(0.3f); _scrolledTo = i; } } } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs index c23516b..5db2042 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs @@ -205,7 +205,7 @@ internal sealed class RynthNavFace : IImGuiPanel // The whole line on hover (it's clipped to one line). ImGuiNET.ImGui.SetCursorScreenPos(p); ImGuiNET.ImGui.InvisibleButton("##rnav_status", new Vector2(Math.Max(1, textRight - p.X), h)); - if (text.Length > 40) ImGuiNET.ImGui.SetItemTooltip(text); + if (text.Length > 40) SafeImGui.SetItemTooltip(text); if (stop) { if (IconButton("##rnav_status_stop", PhosphorIcons.Stop, new Vector2(p.X + w - 22, p.Y + 1), new Vector2(20, 20), Text, StopBg, font: UiFont.Ui11)) @@ -283,7 +283,7 @@ internal sealed class RynthNavFace : IImGuiPanel { if (IconButton("##go_star", PhosphorIcons.Star, p, new Vector2(18, 18), fav ? Gold : Faded(Mute), fav ? Selected : PanelBg, font: UiFont.Ui11)) RynthNavCommands.ToggleFavorite(_pick!.Name, _pick.Ns, _pick.Ew); - ImGuiNET.ImGui.SetItemTooltip(fav ? "Remove from favorites" : "Add to favorites"); + SafeImGui.SetItemTooltip(fav ? "Remove from favorites" : "Add to favorites"); lx += 22; } dl.PushClipRect(new Vector2(lx, p.Y), new Vector2(p.X + w, p.Y + 18), true); @@ -301,19 +301,19 @@ internal sealed class RynthNavFace : IImGuiPanel bool walking = st?.Goto == true; float bw = (w - 3 * 4) / 4f; if (Button("##go_go", GoLabel, p, new Vector2(bw, 26), Green, BtnFill, enabled: canGo)) Go(text); - ImGuiNET.ImGui.SetItemTooltip(travel + SafeImGui.SetItemTooltip(travel ? (st!.PortalsOn ? "Walk there, through portals and with recalls when that is quicker" : "Walk there (portals and recalls are switched off)") : "Walk the navmesh to these coordinates (update RynthNav for places and routes)"); if (Button("##go_route", PhosphorIcons.Path + " Route", new Vector2(p.X + bw + 4, p.Y), new Vector2(bw, 26), Text, BtnFill, enabled: travel && has)) RynthNavCommands.Command("route " + Arg(text)); - ImGuiNET.ImGui.SetItemTooltip(travel ? "Plan only: show the steps below, don't walk" : "Update RynthNav (0.6.0+) for routes"); + SafeImGui.SetItemTooltip(travel ? "Plan only: show the steps below, don't walk" : "Update RynthNav (0.6.0+) for routes"); if (Button("##go_arrow", PhosphorIcons.NavigationArrow + " Arrow", new Vector2(p.X + 2 * (bw + 4), p.Y), new Vector2(bw, 26), Teal, BtnFill, enabled: travel && has)) RynthNavCommands.Command("arrow " + Arg(text)); - ImGuiNET.ImGui.SetItemTooltip(travel ? "Show the arrow overlay pointing there" : "Update RynthNav (0.6.0+) for the arrow"); + SafeImGui.SetItemTooltip(travel ? "Show the arrow overlay pointing there" : "Update RynthNav (0.6.0+) for the arrow"); if (Button("##go_stop", PhosphorIcons.Stop + " Stop", new Vector2(p.X + 3 * (bw + 4), p.Y), new Vector2(bw, 26), walking ? Text : Red, walking ? StopBg : BtnFill, border: walking ? Red : 0)) RynthNavCommands.Move(5); - ImGuiNET.ImGui.SetItemTooltip(walking ? "Stop walking" : "Stop any movement"); + SafeImGui.SetItemTooltip(walking ? "Stop walking" : "Stop any movement"); NextLine(p, 32); // Switches @@ -438,7 +438,7 @@ internal sealed class RynthNavFace : IImGuiPanel if (IconButton("##fav", PhosphorIcons.Star, rp + new Vector2(2, 1), new Vector2(btn, btn), r.Favorite ? Gold : Faded(Mute), r.Favorite ? Selected : PanelBg, enabled: travel && r.OnMap, font: UiFont.Ui11)) RynthNavCommands.ToggleFavorite(r.Name, r.Ns, r.Ew); - ImGuiNET.ImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); + SafeImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); float bodyX = rp.X + btn + 4, bodyW = w - btn - 4; ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bodyX, rp.Y)); @@ -605,7 +605,7 @@ internal sealed class RynthNavFace : IImGuiPanel ImGuiNET.ImGui.SetItemTooltip("Is there navmesh under you?"); if (Button("##preview", "Preview", new Vector2(p.X + 2 * (bw + 4), p.Y), new Vector2(bw, 24), Text, BtnFill, enabled: coord.Length > 0)) RynthNavCommands.Preview(coord); - ImGuiNET.ImGui.SetItemTooltip(coord.Length > 0 ? "Plan the navmesh path to the destination (close places only), no walking" + SafeImGui.SetItemTooltip(coord.Length > 0 ? "Plan the navmesh path to the destination (close places only), no walking" : "Pick a destination on the map first"); NextLine(p, 30); @@ -649,7 +649,7 @@ internal sealed class RynthNavFace : IImGuiPanel { if (IconButton("##mv" + cmd, glyph, pos, new Vector2(58, 42), Text, active ? RunGreen : BtnFill)) RynthNavCommands.Move(cmd); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } // Avoidance, one row per kind of thing kept away from: on/off, then − value +. Each click @@ -675,7 +675,7 @@ internal sealed class RynthNavFace : IImGuiPanel } else Button("##av_" + key, label, p, new Vector2(lw, 22), Text, BtnFill, enabled: false, leftAlign: true); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); bool active = on ?? true; float x = p.X + lw + 4; string Fmt(double v) => v.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture); @@ -695,7 +695,7 @@ internal sealed class RynthNavFace : IImGuiPanel float w1 = (w - 8) * 0.40f, w2 = (w - 8) * 0.28f, w3 = w - 8 - w1 - w2; if (Toggle("##mk_on", "Path markers", st.MarkersOn, p, w1)) RynthNavCommands.Command(st.MarkersOn ? "markers off" : "markers on"); - ImGuiNET.ImGui.SetItemTooltip("Show the planned trip on the ground, the way RynthAi shows its nav routes: rings at the\n" + SafeImGui.SetItemTooltip("Show the planned trip on the ground, the way RynthAi shows its nav routes: rings at the\n" + "waypoints, lines between them, the portals, recalls and the goal in their own colours.\n" + "They go when the trip ends, you stop, or you land somewhere that isn't on it." + (st.MarkerStatus.Length > 0 ? "\n\nNow: " + st.MarkerStatus : "")); @@ -732,7 +732,7 @@ internal sealed class RynthNavFace : IImGuiPanel if (Button("##save_go", st.SaveBusy ? "Saving…" : PhosphorIcons.FloppyDisk + " Save", new Vector2(p.X + boxW + 4, p.Y), new Vector2(bw, 22), Teal, BtnFill, enabled: can) || (enter && can)) RynthNavCommands.Command("saveroute " + name); - ImGuiNET.ImGui.SetItemTooltip("Write this trip as a RynthAi nav route (NavProfiles\\" + (name.Length > 0 ? name : "name") + ".nav):\n" + SafeImGui.SetItemTooltip("Write this trip as a RynthAi nav route (NavProfiles\\" + (name.Length > 0 ? name : "name") + ".nav):\n" + "the walks as waypoints, portals as portal steps, recalls as recall steps.\n" + "RynthAi lists it in its Nav picker; /ra nav load " + (name.Length > 0 ? name : "<name>") + " loads it."); NextLine(p, 26); @@ -746,7 +746,7 @@ internal sealed class RynthNavFace : IImGuiPanel dl.PopClipRect(); if (Button("##save_replace", "Replace", new Vector2(p.X + tw + 4, p.Y), new Vector2(rw, 22), Text, BtnFill, enabled: !st.SaveBusy, border: Amber)) RynthNavCommands.Command("saveroute " + name + " overwrite"); - ImGuiNET.ImGui.SetItemTooltip("Replace NavProfiles\\" + name + ".nav with this trip"); + SafeImGui.SetItemTooltip("Replace NavProfiles\\" + name + ".nav with this trip"); NextLine(p, 26); } if (st.SaveLast.Length > 0) @@ -792,7 +792,7 @@ internal sealed class RynthNavFace : IImGuiPanel _mode = Modes[i].Mode; PushQuery(); } - ImGuiNET.ImGui.SetItemTooltip(Modes[i].Tip); + SafeImGui.SetItemTooltip(Modes[i].Tip); } NextLine(p, 26); @@ -855,7 +855,7 @@ internal sealed class RynthNavFace : IImGuiPanel if (IconButton("##fav", PhosphorIcons.Star, starPos, new Vector2(btn, btn), r.Favorite ? Gold : Faded(Mute), r.Favorite ? Selected : PanelBg, enabled: r.OnMap, font: UiFont.Ui11)) RynthNavCommands.ToggleFavorite(r.Name, r.Ns, r.Ew); - ImGuiNET.ImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); + SafeImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); // Arrow / Go (right) var goPos = new Vector2(rp.X + w - btn - 2, rp.Y + 1); @@ -865,13 +865,13 @@ internal sealed class RynthNavFace : IImGuiPanel RynthNavCommands.Arrow(r.Name, r.Ns, r.Ew); _sel = r; } - ImGuiNET.ImGui.SetItemTooltip(r.OnMap ? "Point the arrow here" : "In a dungeon: no arrow"); + SafeImGui.SetItemTooltip(r.OnMap ? "Point the arrow here" : "In a dungeon: no arrow"); if (IconButton("##go", PhosphorIcons.Play, goPos, new Vector2(btn, btn), Green, BtnFill, enabled: r.OnMap, font: UiFont.Ui11)) { RynthNavCommands.Go(r.Name, r.Ns, r.Ew); _sel = r; } - ImGuiNET.ImGui.SetItemTooltip(r.OnMap ? "Go: RynthNav walks here" : "In a dungeon: RynthNav can't walk there"); + SafeImGui.SetItemTooltip(r.OnMap ? "Go: RynthNav walks here" : "In a dungeon: RynthNav can't walk there"); // Row body: click selects float bodyX = rp.X + btn + 4, bodyW = arPos.X - 4 - bodyX; diff --git a/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs b/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs index eb5fc01..5df5fe7 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs @@ -190,7 +190,7 @@ internal sealed class SenseFace : IImGuiPanel if (ImGuiNET.ImGui.InvisibleButton("##t", new Vector2(chipW - xW, ChipH))) toggle = i; bool hotT = ImGuiNET.ImGui.IsItemHovered(); if (hotT) - ImGuiNET.ImGui.SetItemTooltip(t.Enabled + SafeImGui.SetItemTooltip(t.Enabled ? (t.IsGlob ? "On: the whole name must match (wildcards). Click to switch off." : "On: names containing this match. Click to switch off.") : "Off. Click to switch on."); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x + chipW - xW, y)); diff --git a/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs b/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs new file mode 100644 index 0000000..334372e --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs @@ -0,0 +1,126 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ServerPickSettingsUi.cs +// Settings > Diagnostics > Server: which server this character counts as. +// +// A picker (Auto, or one of the servers the engine knows: the built-in ones +// and every server a loaded plugin declares), what is active and why, and the +// full list: verdict, detection, this character's override, and the plugin +// the other plugins ask for that server's settings. Picking a server forces it +// on and every other server off for this character (ServerSelectionStore); +// the menus, the "servermenu" push and plugin API v85 follow on the next frame. +// Drawn by SettingsFace for the Diagnostics tab's ServerPick row, in its look. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Sections; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class ServerPickSettingsUi +{ + private static readonly Vector4 Teal = RynthTheme.Vec(0xFF26D9E6), Amber = RynthTheme.Vec(0xFFE8B333), + Mute = RynthTheme.Vec(0xFFB8C8D8), Good = RynthTheme.Vec(0xFF33FF33); + + // The last pick's outcome, shown under the picker until the next one. + private static string _message = string.Empty; + + /// <summary>The row: picker, active server, server table. Render thread.</summary> + public static void Draw(float width, string? tooltip) + { + SectionRegistry.Snapshot snap = SectionRegistry.Current; + IReadOnlyList<ServerState> servers = snap.Servers; + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (servers.Count == 0) + { + SafeImGui.TextDisabled("No servers known yet (the list fills in once a character is in game)."); + return; + } + + string? pick = ServerSelection.CurrentPick(servers); + DrawPicker(servers, pick, width, tooltip); + + ServerState? active = ServerSelection.ActiveServer(servers); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (active == null) + SafeImGui.TextColored(Mute, "Active: none (no custom server matched; retail rules)."); + else + SafeImGui.TextColored(Teal, $"Active: {active.Name} ({active.Id}) - {active.Reason}"); + if (_message.Length > 0) SafeImGui.TextColored(Amber, _message); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + DrawTable(servers, snap.Manifests); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + } + + private static void DrawPicker(IReadOnlyList<ServerState> servers, string? pick, float width, string? tooltip) + { + string preview = pick == null ? "Mixed (set per server with /rc server <id> on|off)" + : pick == ServerSelection.Auto ? "Auto (detect)" + : Label(servers, pick); + + ImGuiNET.ImGui.AlignTextToFramePadding(); + SafeImGui.TextColored(Mute, "Server"); + if (tooltip != null) SafeImGui.SetItemTooltip(tooltip); + ImGuiNET.ImGui.SameLine(90); + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(160, width - 96)); + if (ImGuiNET.ImGui.BeginCombo("##serverpick", preview)) + { + if (ImGuiNET.ImGui.Selectable("Auto (detect)##pick_auto", pick == ServerSelection.Auto)) + Pick(ServerSelection.Auto); + foreach (ServerState s in servers) + { + string marks = (s.Active ? " [active]" : string.Empty) + (s.Detected ? " [detected]" : string.Empty); + if (ImGuiNET.ImGui.Selectable(s.Name + " (" + s.Id + ")" + marks + "##pick_" + s.Id, + pick != null && pick.Equals(s.Id, StringComparison.OrdinalIgnoreCase))) + Pick(s.Id); + } + ImGuiNET.ImGui.EndCombo(); + } + if (tooltip != null) SafeImGui.SetItemTooltip(tooltip); + } + + private static void Pick(string id) + { + ServerSelectionStore.Apply(id, out string message); + _message = message; + } + + private static void DrawTable(IReadOnlyList<ServerState> servers, IReadOnlyList<SectionManifest> manifests) + { + const ImGuiTableFlags flags = ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp; + if (!ImGuiNET.ImGui.BeginTable("##servers", 5, flags)) return; + ImGuiNET.ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthStretch, 2.2f); + ImGuiNET.ImGui.TableSetupColumn("Active", ImGuiTableColumnFlags.WidthStretch, 0.9f); + ImGuiNET.ImGui.TableSetupColumn("Detected", ImGuiTableColumnFlags.WidthStretch, 1f); + ImGuiNET.ImGui.TableSetupColumn("Override", ImGuiTableColumnFlags.WidthStretch, 1f); + ImGuiNET.ImGui.TableSetupColumn("Settings from", ImGuiTableColumnFlags.WidthStretch, 1.6f); + ImGuiNET.ImGui.TableHeadersRow(); + foreach (ServerState s in servers) + { + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); + SafeImGui.TextColored(s.Active ? Teal : Mute, s.Name + " (" + s.Id + ")"); + if (!string.IsNullOrEmpty(s.Reason)) SafeImGui.SetItemTooltip(s.Reason); + ImGuiNET.ImGui.TableNextColumn(); + SafeImGui.TextColored(s.Active ? Good : Mute, s.Active ? "yes" : "no"); + ImGuiNET.ImGui.TableNextColumn(); + SafeImGui.TextColored(Mute, s.Detected ? "yes" : "no"); + ImGuiNET.ImGui.TableNextColumn(); + SafeImGui.TextColored(s.Force == ServerForce.Auto ? Mute : Amber, ServerForceText.Name(s.Force)); + ImGuiNET.ImGui.TableNextColumn(); + string owner = ServerSelection.OwnerPlugin(manifests, s.Id, SectionRegistry.EnginePlugin); + SafeImGui.TextColored(owner.Length > 0 ? Teal : Mute, owner.Length > 0 ? owner : "(no plugin loaded)"); + } + ImGuiNET.ImGui.EndTable(); + } + + private static string Label(IReadOnlyList<ServerState> servers, string id) + { + foreach (ServerState s in servers) + if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s.Name + " (" + s.Id + ")"; + return id; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs index 160d237..c117917 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs @@ -159,7 +159,7 @@ internal sealed class SettingsFace : IImGuiPanel ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); if (_tab >= SettingsSchema.Tabs.Length) _tab = 0; - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), Headers[_tab]); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.Accent), Headers[_tab]); ImGuiNET.ImGui.PopFont(); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos(); diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs index 6305770..7dceeb5 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs @@ -108,7 +108,7 @@ internal sealed class SettingsRows bool pinned = QuickSettings.IsPinned(key); if (ImGuiNET.ImGui.MenuItem(pinned ? PhosphorIcons.X + " Remove from My settings" : PhosphorIcons.PushPin + " Pin to My settings")) QuickSettings.SetPinned(key, !pinned); - ImGuiNET.ImGui.SetItemTooltip(pinned + SafeImGui.SetItemTooltip(pinned ? "Take it out of the My settings drawer on the dashboard (the setting itself doesn't change)." : "Add it to the My settings drawer on the dashboard, for quick changes."); extraMenu?.Invoke(key); @@ -134,6 +134,7 @@ internal sealed class SettingsRows case SettingKind.Text: TextRow(row, w); break; case SettingKind.Status: StatusRow(row, w); break; case SettingKind.Hotkeys: _editing |= _hotkeys.Draw(w); break; + case SettingKind.ServerPick: ServerPickSettingsUi.Draw(w, row.Tooltip); break; case SettingKind.Color: ColorRow(row, w); break; } } @@ -496,16 +497,16 @@ internal sealed class SettingsRows private void CraftingStatus(SettingRow row) { ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), row.Label); + SafeImGui.TextColored(RynthTheme.VecOf(RynthTheme.TextMuted), row.Label); ImGuiNET.ImGui.SameLine(0, 6); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(_data.MissileCraftingActive ? RynthTheme.Highlight : RynthTheme.TextMuted), _data.MissileCraftingState); + SafeImGui.TextColored(RynthTheme.VecOf(_data.MissileCraftingActive ? RynthTheme.Highlight : RynthTheme.TextMuted), _data.MissileCraftingState); ImGuiNET.ImGui.PopFont(); if (!string.IsNullOrEmpty(_data.MissileCraftingStatus)) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); - ImGuiNET.ImGui.TextWrapped(_data.MissileCraftingStatus); + SafeImGui.TextWrapped(_data.MissileCraftingStatus); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.PopFont(); } @@ -525,7 +526,7 @@ internal sealed class SettingsRows private static void Tooltip(SettingRow row) { - if (row.Tooltip != null) ImGuiNET.ImGui.SetItemTooltip(row.Tooltip); + if (row.Tooltip != null) SafeImGui.SetItemTooltip(row.Tooltip); } private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs index bb22d8f..d4461dc 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs @@ -209,7 +209,7 @@ internal sealed partial class SkillsFace Label("Last updated: " + a.Updated, Dim); } NextLine(p, 28); - if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status); + if (a.Status.Length > 0) SafeImGui.TextWrapped(a.Status); if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim); ImGuiNET.ImGui.Separator(); @@ -338,7 +338,7 @@ internal sealed partial class SkillsFace : $"{what}: {exact} XP."; if (known && !afford) tip += " Not enough unassigned XP."; if (a.Running) tip += " Wait for the raise run to finish."; - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } /// <summary>The client's own base value for a raiser row (0 when the snapshot has none).</summary> @@ -574,7 +574,7 @@ internal sealed partial class SkillsFace } else if (active) _augTargetEdit[row.Key] = tgt; else _augTargetEdit.Remove(row.Key); - ImGuiNET.ImGui.SetItemTooltip($"Target {row.Label} level (up to {row.Cap.ToString("N0", CultureInfo.InvariantCulture)})."); + SafeImGui.SetItemTooltip($"Target {row.Label} level (up to {row.Cap.ToString("N0", CultureInfo.InvariantCulture)})."); } private void DrawEnlPlanner(EnlPlanner e, float w) @@ -593,7 +593,7 @@ internal sealed partial class SkillsFace ImGuiNET.ImGui.SetNextItemWidth(100); if (ImGuiNET.ImGui.InputInt("Plan to level##prog_enlt", ref target)) SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture)); - foreach (string line in e.Plan) ImGuiNET.ImGui.BulletText(line); + foreach (string line in e.Plan) SafeImGui.BulletText(line); int coinsPerToken = e.CoinsPerToken; ImGuiNET.ImGui.SetNextItemWidth(100); @@ -640,7 +640,7 @@ internal sealed partial class SkillsFace if (ImGuiNET.ImGui.InputInt("Check every (s)##prog_every", ref every)) SendProg("checkevery " + Math.Max(10, every).ToString(CultureInfo.InvariantCulture)); Label(e.Armed ? "Armed." : "Disarmed.", e.Armed ? Amber : Dim); - if (e.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(e.Status); + if (e.Status.Length > 0) SafeImGui.TextWrapped(e.Status); } finally { diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs index 6249b30..8ca7790 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs @@ -676,7 +676,7 @@ internal sealed partial class SkillsFace : IImGuiPanel dl.AddText(new Vector2(x, y), _summaryColors[i], _summary[i]); if (i == _radiancePart && _masteryTip.Length > 0 && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x, y), new Vector2(x + tw, y + lineH))) - ImGuiNET.ImGui.SetTooltip(_masteryTip); + SafeImGui.SetTooltip(_masteryTip); x += tw + 14; } long now = Environment.TickCount64; @@ -735,7 +735,7 @@ internal sealed partial class SkillsFace : IImGuiPanel _descending = !_descending; _orderDirty = true; } - ImGuiNET.ImGui.SetItemTooltip(_descending ? "Highest first" : "Lowest first"); + SafeImGui.SetItemTooltip(_descending ? "Highest first" : "Lowest first"); NextLine(p, 26); } @@ -910,7 +910,7 @@ internal sealed partial class SkillsFace : IImGuiPanel if (ImGuiNET.ImGui.IsItemHovered() && !expanded) dl.AddRect(p, p + new Vector2(w, RowH), BtnBord); if (r.MasteryText.Length > 0 && _masteryTip.Length > 0 && ImGuiNET.ImGui.IsMouseHoveringRect(badgeMin, badgeMax)) - ImGuiNET.ImGui.SetTooltip(r.MasteryHover); + SafeImGui.SetTooltip(r.MasteryHover); // The row's action buttons: "+1" (raise one rank now, no confirm) and a caret that // opens +10 / +100 / Max on trained rows, attributes and vitals; Train (skill @@ -923,13 +923,13 @@ internal sealed partial class SkillsFace : IImGuiPanel if (Button("##raise1", r.Max ? "max" : "+1", btnMin, oneSize, Teal, BtnFill, canRaise, border: canRaise ? Teal : 0) && _snap != null) SendRaise(r, _snap, 1); - ImGuiNET.ImGui.SetItemTooltip(why); + SafeImGui.SetItemTooltip(why); bool canMore = !r.Max && PlayerTraining.Available && !_pending; var caretMin = new Vector2(btnMin.X + oneSize.X + 2, btnMin.Y); if (IconButton("##raiseN", PhosphorIcons.CaretDown, caretMin, new Vector2(CaretW, RowH - 2), Teal, BtnFill, canMore, font: UiFont.Ui11)) OpenMulti(r, caretMin + new Vector2(CaretW - MultiW, RowH)); - ImGuiNET.ImGui.SetItemTooltip(canMore ? "Raise more: +10, +100 or Max" + SafeImGui.SetItemTooltip(canMore ? "Raise more: +10, +100 or Max" : r.Max ? "At the top rank" : _pending ? "Waiting for the last raise to land" : "Raising isn't available on this client build"); } @@ -938,7 +938,7 @@ internal sealed partial class SkillsFace : IImGuiPanel bool canTrain = CanTrain(r, out string why); if (Button("##train", "Train", btnMin, btnSize, Amber, BtnFill, canTrain, border: canTrain ? Amber : 0)) OpenConfirm(r, train: true); - ImGuiNET.ImGui.SetItemTooltip(why); + SafeImGui.SetItemTooltip(why); } ImGuiNET.ImGui.PopID(); NextLine(p, RowH); @@ -1063,7 +1063,7 @@ internal sealed partial class SkillsFace : IImGuiPanel { float tw = ImGuiNET.ImGui.CalcTextSize(r.MasteryLine).X; if (ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x, y), new Vector2(x + 18 + tw, y + lineH))) - ImGuiNET.ImGui.SetTooltip(_masteryTip); + SafeImGui.SetTooltip(_masteryTip); } y += lineH; if (r.MasteryLine2.Length > 0) @@ -1083,7 +1083,7 @@ internal sealed partial class SkillsFace : IImGuiPanel if (Button("##mastery_raise", PhosphorIcons.Crown + " Raise mastery", new Vector2(x + 18, y), new Vector2(130, 22), MasteryColor, BtnFill, can, border: can ? MasteryColor : 0)) OpenMasteryConfirm(r); - ImGuiNET.ImGui.SetItemTooltip(can ? why + "\nAsks before it spends anything." : why); + SafeImGui.SetItemTooltip(can ? why + "\nAsks before it spends anything." : why); ImGuiNET.ImGui.PopID(); y += 26; } @@ -1263,7 +1263,7 @@ internal sealed partial class SkillsFace : IImGuiPanel SendRaise(r, s, n); ImGuiNET.ImGui.CloseCurrentPopup(); } - ImGuiNET.ImGui.SetItemTooltip(why); + SafeImGui.SetItemTooltip(why); var dl = ImGuiNET.ImGui.GetWindowDrawList(); float tw = ImGuiNET.ImGui.CalcTextSize(right).X; dl.AddText(new Vector2(x + size.X - 6 - tw, y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), ok ? Teal : Dim, right); diff --git a/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs b/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs index 9d029ed..49adaea 100644 --- a/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs @@ -210,7 +210,7 @@ internal sealed class VisionFace : IImGuiPanel { ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(HeaderColor, text); + SafeImGui.TextColored(HeaderColor, text); ImGuiNET.ImGui.PopFont(); } @@ -251,7 +251,7 @@ internal sealed class VisionFace : IImGuiPanel WriteUtf8(hex, argb.ToString("X8")); } if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key); - ImGuiNET.ImGui.SetItemTooltip("0% = invisible, 100% = solid. Ctrl+click to type a value"); + SafeImGui.SetItemTooltip("0% = invisible, 100% = solid. Ctrl+click to type a value"); return ImGuiNET.ImGui.IsItemActive(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/WorldMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/WorldMapFace.cs index 95ccd30..59e7dc3 100644 --- a/src/RynthCore.Engine/ImGui/Panels/WorldMapFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/WorldMapFace.cs @@ -173,7 +173,7 @@ internal sealed class WorldMapFace : IImGuiPanel var installed = WorldMapMaps.Installed; if (installed.Length > 0) { - ImGuiNET.ImGui.TextDisabled("Map detail" + (WorldMapMaps.CurrentLabel.Length > 0 ? ": " + WorldMapMaps.CurrentLabel : "")); + SafeImGui.TextDisabled("Map detail" + (WorldMapMaps.CurrentLabel.Length > 0 ? ": " + WorldMapMaps.CurrentLabel : "")); if (ImGuiNET.ImGui.RadioButton("Best installed", WorldMapSettings.Detail.Length == 0)) { WorldMapSettings.Detail = ""; WorldMapSettings.MarkDirty(); WorldMapMaps.Apply(); } foreach (var t in installed) if (ImGuiNET.ImGui.RadioButton(t.Label, WorldMapSettings.Detail == t.Key)) { WorldMapSettings.Detail = t.Key; WorldMapSettings.MarkDirty(); WorldMapMaps.Apply(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/WorldMapView.cs b/src/RynthCore.Engine/ImGui/Panels/WorldMapView.cs index 31fdf19..16652ce 100644 --- a/src/RynthCore.Engine/ImGui/Panels/WorldMapView.cs +++ b/src/RynthCore.Engine/ImGui/Panels/WorldMapView.cs @@ -811,8 +811,8 @@ internal sealed class WorldMapView if (_openCtx) { ImGuiNET.ImGui.OpenPopup(_ctxId); _openCtx = false; } if (!ImGuiNET.ImGui.BeginPopup(_ctxId)) return; string where = _ctxName.Length > 0 ? _ctxName : "Map point"; - ImGuiNET.ImGui.TextColored(new Vector4(1f, 0.82f, 0.3f, 1f), where); - ImGuiNET.ImGui.TextDisabled(RynthNavStatus.Coord(_ctxNs, _ctxEw)); + SafeImGui.TextColored(new Vector4(1f, 0.82f, 0.3f, 1f), where); + SafeImGui.TextDisabled(RynthNavStatus.Coord(_ctxNs, _ctxEw)); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.Selectable("Go here")) RynthNavCommands.Go(where, _ctxNs, _ctxEw); if (ImGuiNET.ImGui.Selectable("Route here")) RynthNavCommands.Route(where, _ctxNs, _ctxEw); diff --git a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs index 601f90a..f9d185d 100644 --- a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs +++ b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs @@ -259,7 +259,7 @@ internal static class RynthCoreShell UpdateBarPositionFromWindow(); bool auxReady = frameCount >= 120; - ImGui.TextColored(Win32Backend.IsUiCaptureEnabled() ? Good : TextMute, Win32Backend.IsUiCaptureEnabled() ? "UI" : "GAME"); + SafeImGui.TextColored(Win32Backend.IsUiCaptureEnabled() ? Good : TextMute, Win32Backend.IsUiCaptureEnabled() ? "UI" : "GAME"); ShowTooltip("Press Insert to toggle UI capture."); ImGui.SameLine(); @@ -708,7 +708,7 @@ internal static class RynthCoreShell string pluginDir = PluginManager.PluginDirectory; if (!string.IsNullOrEmpty(pluginDir)) { - ImGui.TextColored(TextMute, pluginDir); + SafeImGui.TextColored(TextMute, pluginDir); } if (_showPluginTips) @@ -741,16 +741,16 @@ internal static class RynthCoreShell string ver = string.IsNullOrEmpty(p.VersionString) ? "" : $" v{p.VersionString}"; ImGui.BulletText(""); ImGui.SameLine(); - ImGui.TextColored(Accent, p.DisplayName); + SafeImGui.TextColored(Accent, p.DisplayName); ImGui.SameLine(); - ImGui.TextColored(TextMute, ver); + SafeImGui.TextColored(TextMute, ver); ImGui.SameLine(300f); - ImGui.TextColored(statusColor, statusText); + SafeImGui.TextColored(statusColor, statusText); if (!string.IsNullOrEmpty(p.SourceFilePath)) { ImGui.SameLine(); - ImGui.TextColored(TextMute, $"<{p.FileName}>"); + SafeImGui.TextColored(TextMute, $"<{p.FileName}>"); } string caps = ""; @@ -761,7 +761,7 @@ internal static class RynthCoreShell if (caps.Length > 0) { ImGui.SameLine(); - ImGui.TextColored(TextMute, $"[{caps.Trim()}]"); + SafeImGui.TextColored(TextMute, $"[{caps.Trim()}]"); } ImGui.PopID(); @@ -796,7 +796,7 @@ internal static class RynthCoreShell _selectedPlugin = i; ImGui.SameLine(); - ImGui.TextColored(TextMute, PluginStatuses[i]); + SafeImGui.TextColored(TextMute, PluginStatuses[i]); ImGui.PopID(); } @@ -805,8 +805,8 @@ internal static class RynthCoreShell if (_selectedPlugin >= 0 && _selectedPlugin < PluginNames.Length) { - ImGui.TextColored(Gold, PluginNames[_selectedPlugin]); - ImGui.TextColored(TextMute, PluginStatuses[_selectedPlugin]); + SafeImGui.TextColored(Gold, PluginNames[_selectedPlugin]); + SafeImGui.TextColored(TextMute, PluginStatuses[_selectedPlugin]); } ImGui.EndChild(); @@ -819,7 +819,7 @@ internal static class RynthCoreShell // ── Loaded plugins ────────────────────────────────────────────────── var loadedPlugins = PluginManager.Plugins; - ImGui.TextColored(Accent, $"Loaded Plugins ({loadedPlugins.Count})"); + SafeImGui.TextColored(Accent, $"Loaded Plugins ({loadedPlugins.Count})"); ImGui.Separator(); if (loadedPlugins.Count == 0) @@ -838,12 +838,12 @@ internal static class RynthCoreShell string ver = string.IsNullOrEmpty(p.VersionString) ? "" : $" v{p.VersionString}"; ImGui.BulletText(""); ImGui.SameLine(); - ImGui.TextColored(Accent, p.DisplayName); + SafeImGui.TextColored(Accent, p.DisplayName); ImGui.SameLine(); - ImGui.TextColored(TextMute, ver); + SafeImGui.TextColored(TextMute, ver); ImGui.SameLine(280f); - ImGui.TextColored(statusColor, statusText); - ImGui.TextColored(TextMute, $" {p.SourceFilePath}"); + SafeImGui.TextColored(statusColor, statusText); + SafeImGui.TextColored(TextMute, $" {p.SourceFilePath}"); } } @@ -859,7 +859,7 @@ internal static class RynthCoreShell { ImGui.TextColored(TextMute, "Built-in directory:"); ImGui.SameLine(); - ImGui.TextColored(TextDim, builtInDir); + SafeImGui.TextColored(TextDim, builtInDir); } ImGui.Spacing(); @@ -877,9 +877,9 @@ internal static class RynthCoreShell { ImGui.PushID($"pluginpath_{i}"); bool exists = File.Exists(extraPaths[i]); - ImGui.TextColored(exists ? Good : Warn, exists ? " OK" : " ??"); + SafeImGui.TextColored(exists ? Good : Warn, exists ? " OK" : " ??"); ImGui.SameLine(); - ImGui.TextColored(TextDim, extraPaths[i]); + SafeImGui.TextColored(TextDim, extraPaths[i]); ImGui.SameLine(); if (ImGui.SmallButton("Remove")) removeIdx = i; @@ -946,34 +946,34 @@ internal static class RynthCoreShell ImGui.Spacing(); ImGui.TextColored(TextMute, "Combat"); - ImGui.TextWrapped($"Melee {OnOff(status.MeleeAvailable)} Missile {OnOff(status.MissileAvailable)} Mode {OnOff(status.ChangeCombatModeAvailable)} Cancel {OnOff(status.CancelAttackAvailable)} Health {OnOff(status.QueryHealthAvailable)}"); - ImGui.TextColored(TextMute, status.CombatStatus); + SafeImGui.TextWrapped($"Melee {OnOff(status.MeleeAvailable)} Missile {OnOff(status.MissileAvailable)} Mode {OnOff(status.ChangeCombatModeAvailable)} Cancel {OnOff(status.CancelAttackAvailable)} Health {OnOff(status.QueryHealthAvailable)}"); + SafeImGui.TextColored(TextMute, status.CombatStatus); ImGui.Spacing(); ImGui.TextColored(TextMute, "Movement"); - ImGui.TextWrapped($"Move {OnOff(status.DoMovementAvailable)} Stop {OnOff(status.StopMovementAvailable)} Jump {OnOff(status.JumpNonAutonomousAvailable)} Autonomy {OnOff(status.AutonomyLevelAvailable)}"); - ImGui.TextColored(TextMute, status.MovementStatus); + SafeImGui.TextWrapped($"Move {OnOff(status.DoMovementAvailable)} Stop {OnOff(status.StopMovementAvailable)} Jump {OnOff(status.JumpNonAutonomousAvailable)} Autonomy {OnOff(status.AutonomyLevelAvailable)}"); + SafeImGui.TextColored(TextMute, status.MovementStatus); ImGui.Spacing(); ImGui.TextColored(TextMute, "Local"); - ImGui.TextWrapped($"Autorun {OnOff(status.SetAutoRunAvailable)} TapJump {OnOff(status.TapJumpAvailable)}"); - ImGui.TextColored(TextMute, status.CommandInterpreterStatus); + SafeImGui.TextWrapped($"Autorun {OnOff(status.SetAutoRunAvailable)} TapJump {OnOff(status.TapJumpAvailable)}"); + SafeImGui.TextColored(TextMute, status.CommandInterpreterStatus); ImGui.Spacing(); ImGui.TextColored(TextMute, "UI"); - ImGui.TextColored(TextMute, UiLifecycleHooks.StatusMessage); + SafeImGui.TextColored(TextMute, UiLifecycleHooks.StatusMessage); ImGui.Spacing(); ImGui.TextColored(TextMute, "Chat"); - ImGui.TextColored(TextMute, ChatCallbackHooks.StatusMessage); + SafeImGui.TextColored(TextMute, ChatCallbackHooks.StatusMessage); ImGui.Spacing(); ImGui.TextColored(TextMute, "Multi-client"); - ImGui.TextColored(TextMute, MultiClientHooks.StatusMessage); + SafeImGui.TextColored(TextMute, MultiClientHooks.StatusMessage); ImGui.Spacing(); ImGui.TextColored(TextMute, "Lifecycle"); - ImGui.TextColored(TextMute, LoginLifecycleHooks.StatusMessage); + SafeImGui.TextColored(TextMute, LoginLifecycleHooks.StatusMessage); ImGui.EndChild(); } @@ -1032,8 +1032,8 @@ internal static class RynthCoreShell private static void DrawMetric(in ShellMetric metric) { ImGui.BeginChild($"{metric.Label}Card", new Vector2(0f, 76f), ImGuiChildFlags.Borders); - ImGui.TextColored(TextMute, metric.Label); - ImGui.TextColored(metric.Color, metric.Value); + SafeImGui.TextColored(TextMute, metric.Label); + SafeImGui.TextColored(metric.Color, metric.Value); ImGui.EndChild(); } @@ -1047,14 +1047,14 @@ internal static class RynthCoreShell drawList.AddRectFilled(pos, pos + new Vector2(size.X + 16f, size.Y + 8f), fill, 6f); drawList.AddRect(pos, pos + new Vector2(size.X + 16f, size.Y + 8f), stroke, 6f); ImGui.SetCursorScreenPos(pos + new Vector2(8f, 4f)); - ImGui.TextColored(color, text); + SafeImGui.TextColored(color, text); } private static void DrawFeatureLine(string name, string state, Vector4 color) { - ImGui.TextColored(TextDim, name); + SafeImGui.TextColored(TextDim, name); ImGui.SameLine(190f); - ImGui.TextColored(color, state); + SafeImGui.TextColored(color, state); } private static string OnOff(bool value) @@ -1073,16 +1073,16 @@ internal static class RynthCoreShell private static void DrawBulletRow(string label, string value) { - ImGui.BulletText($"{label}: {value}"); + SafeImGui.BulletText($"{label}: {value}"); } private static void DrawRoadmapStep(string index, string title, string body, Vector4 color) { ImGui.BeginChild($"Roadmap{index}", new Vector2(0f, 68f), ImGuiChildFlags.Borders); - ImGui.TextColored(color, $"Step {index}"); + SafeImGui.TextColored(color, $"Step {index}"); ImGui.SameLine(); - ImGui.TextColored(TextDim, title); - ImGui.TextWrapped(body); + SafeImGui.TextColored(TextDim, title); + SafeImGui.TextWrapped(body); ImGui.EndChild(); } @@ -1158,13 +1158,13 @@ internal static class RynthCoreShell ImGui.TableNextRow(); ImGui.TableSetColumnIndex(0); - ImGui.TextColored(isKnown ? TextMute : Accent, $"0x{opcode:X4}"); + SafeImGui.TextColored(isKnown ? TextMute : Accent, $"0x{opcode:X4}"); ImGui.TableSetColumnIndex(1); - ImGui.TextColored(TextDim, entry.Count.ToString()); + SafeImGui.TextColored(TextDim, entry.Count.ToString()); ImGui.TableSetColumnIndex(2); - ImGui.TextColored(TextDim, entry.LastPayloadLen.ToString()); + SafeImGui.TextColored(TextDim, entry.LastPayloadLen.ToString()); ImGui.TableSetColumnIndex(3); if (entry.LastSample is { Length: > 0 }) @@ -1176,7 +1176,7 @@ internal static class RynthCoreShell sb.Append(b.ToString("X2")); sb.Append(' '); } - ImGui.TextColored(TextMute, sb.ToString().TrimEnd()); + SafeImGui.TextColored(TextMute, sb.ToString().TrimEnd()); } } @@ -1186,7 +1186,7 @@ internal static class RynthCoreShell if (visibleCount == 0) { ImGui.Spacing(); - ImGui.TextColored(TextMute, snapshot.Length == 0 + SafeImGui.TextColored(TextMute, snapshot.Length == 0 ? "No packets captured yet — join a server and traffic will appear here." : "All captured opcodes filtered. Toggle 'Show Known' / 'Show Unknown' to see them."); } diff --git a/src/RynthCore.Engine/ImGui/SafeImGui.cs b/src/RynthCore.Engine/ImGui/SafeImGui.cs new file mode 100644 index 0000000..8fe452d --- /dev/null +++ b/src/RynthCore.Engine/ImGui/SafeImGui.cs @@ -0,0 +1,44 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/SafeImGui.cs +// ImGui text calls for text that isn't a literal: chat lines, item, monster and +// player names, plugin and script text, server replies, interpolated strings. +// +// ImGui.NET passes the string of Text / TextColored / TextWrapped / +// TextDisabled / BulletText / SetTooltip / SetItemTooltip / LabelText to +// native ImGui as a printf format with no arguments, so a '%' in it reads +// arguments that were never passed (garbage, or a crash on %s / %n). These +// wrappers double every '%' so the text draws exactly as given. Same +// signatures as ImGui's, so a call site only changes "ImGui." to "SafeImGui.". +// In the root namespace so every engine namespace sees it. Render thread only. +// ============================================================================ + +using System.Numerics; + +namespace RynthCore.Engine; + +internal static class SafeImGui +{ + /// <summary>The text as a printf format that prints it unchanged ('%' doubled); null is empty.</summary> + internal static string Escape(string? text) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + return text.IndexOf('%') < 0 ? text : text.Replace("%", "%%"); + } + + public static void Text(string? text) => ImGuiNET.ImGui.Text(Escape(text)); + + public static void TextColored(Vector4 color, string? text) => ImGuiNET.ImGui.TextColored(color, Escape(text)); + + public static void TextWrapped(string? text) => ImGuiNET.ImGui.TextWrapped(Escape(text)); + + public static void TextDisabled(string? text) => ImGuiNET.ImGui.TextDisabled(Escape(text)); + + public static void BulletText(string? text) => ImGuiNET.ImGui.BulletText(Escape(text)); + + public static void SetTooltip(string? text) => ImGuiNET.ImGui.SetTooltip(Escape(text)); + + public static void SetItemTooltip(string? text) => ImGuiNET.ImGui.SetItemTooltip(Escape(text)); + + /// <summary>The label is drawn as text, not used as a format; only the value is escaped.</summary> + public static void LabelText(string label, string? text) => ImGuiNET.ImGui.LabelText(label, Escape(text)); +} diff --git a/src/RynthCore.Engine/Net/AelrynthVaultWire.cs b/src/RynthCore.Engine/Net/AelrynthVaultWire.cs index dad5fe1..21f9383 100644 --- a/src/RynthCore.Engine/Net/AelrynthVaultWire.cs +++ b/src/RynthCore.Engine/Net/AelrynthVaultWire.cs @@ -10,7 +10,7 @@ // {"t":"mule","ready":false,"why":"loading"} (still loading on the server: never an empty vault) // // A field the reader does not know is ignored, so the mod can add fields. Pure code (no engine state); -// compiled into tools/NetMessageTests. +// compiled into tools/NetMessageTests (with Net/ChatOrigin.cs). // ============================================================================ using System; @@ -48,20 +48,26 @@ internal static class AelrynthVaultWire /// <summary>The command for a page (1 = the bare command).</summary> public static string PageCommand(int page) => page <= 1 ? Command : Command + " " + page.ToString(System.Globalization.CultureInfo.InvariantCulture); - /// <summary>A "~ael1" data line whose kind is "mule" (another mod's data line is not ours).</summary> + /// <summary> + /// A "~ael1" data line whose kind is "mule" (another mod's data line is not ours). The prefix + /// must start the line: a player's copy has their name in front (ChatOrigin). + /// </summary> public static bool IsMuleLine(string? line) { - if (string.IsNullOrEmpty(line)) return false; - int at = line.IndexOf(Prefix, StringComparison.Ordinal); - return at >= 0 && line.IndexOf("\"t\":\"mule\"", at, StringComparison.Ordinal) >= 0; + if (!ChatOrigin.StartsWithMarker(line, Prefix)) return false; + return line!.IndexOf("\"t\":\"mule\"", ChatOrigin.ContentStart(line), StringComparison.Ordinal) >= 0; } - /// <summary>ACE's reply to a command it does not have ("Unknown command: mule-data").</summary> + /// <summary> + /// ACE's reply to a command it does not have, "Unknown command: mule-data" (GameActionTalk names + /// the bare command; a leading / or @ is allowed). Anchored at the line's start. + /// </summary> public static bool IsUnknownCommand(string? line) { - if (string.IsNullOrEmpty(line)) return false; - return line.IndexOf("Unknown command", StringComparison.OrdinalIgnoreCase) >= 0 - && line.IndexOf(CommandName, StringComparison.OrdinalIgnoreCase) >= 0; + const string marker = "Unknown command:"; + if (!ChatOrigin.StartsWithMarker(line, marker, StringComparison.OrdinalIgnoreCase)) return false; + string named = line!.Substring(ChatOrigin.ContentStart(line) + marker.Length).Trim().TrimStart('/', '@'); + return string.Equals(named, CommandName, StringComparison.OrdinalIgnoreCase); } /// <summary>The page in a mule line; false when it is not one or is too damaged to read.</summary> @@ -71,7 +77,7 @@ internal static class AelrynthVaultWire if (!IsMuleLine(line)) return false; try { - int at = line!.IndexOf(Prefix, StringComparison.Ordinal) + Prefix.Length; + int at = ChatOrigin.ContentStart(line!) + Prefix.Length; using JsonDocument doc = JsonDocument.Parse(line.AsMemory(at)); JsonElement root = doc.RootElement; if (root.ValueKind != JsonValueKind.Object) return false; diff --git a/src/RynthCore.Engine/Net/ChatOrigin.cs b/src/RynthCore.Engine/Net/ChatOrigin.cs new file mode 100644 index 0000000..d55b97d --- /dev/null +++ b/src/RynthCore.Engine/Net/ChatOrigin.cs @@ -0,0 +1,54 @@ +// ============================================================================ +// RynthCore.Engine - Net/ChatOrigin.cs +// Telling a server line from a player's imitation of one. +// +// The engine eats its own "~ael1 " data replies (/mastery-data, /mule-data) +// and ACE's "Unknown command: ..." refusals before AC draws them. Another +// player can type the same text, so the readers need both checks here: +// - the chat type is not one a player writes in (ACE ChatMessageType, which +// is the client's eChatTypes: ACE.Entity/Enum/ChatMessageType.cs); +// - the line STARTS with the marker. The client puts the speaker in front +// of player text ("Name says, ...", "Name tells you, ...", "Name waves"), +// so a player's copy never starts with it. +// Pure code (no engine state); compiled into tools/NetMessageTests. +// Plugins have the same rules in RynthSuite Plugins/Shared/ChatSource.cs. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Net; + +internal static class ChatOrigin +{ + // Chat types whose text another player writes. + public const uint Speech = 0x02; + public const uint Tell = 0x03; + public const uint OutgoingTell = 0x04; + public const uint Channel = 0x08; + public const uint ChannelSend = 0x09; + public const uint Social = 0x0A; + public const uint SocialSend = 0x0B; + public const uint Emote = 0x0C; + public const uint Allegiance = 0x12; + public const uint Fellowship = 0x13; + + /// <summary>True when a line of this chat type is a player's words.</summary> + public static bool IsPlayerAuthored(uint chatType) => chatType switch + { + Speech or Tell or OutgoingTell or Channel or ChannelSend + or Social or SocialSend or Emote or Allegiance or Fellowship => true, + _ => false, + }; + + /// <summary>The index just past <paramref name="line"/>'s leading whitespace.</summary> + public static int ContentStart(string line) + { + int i = 0; + while (i < line.Length && char.IsWhiteSpace(line[i])) i++; + return i; + } + + /// <summary>True when <paramref name="line"/>, past leading whitespace, starts with <paramref name="marker"/>.</summary> + public static bool StartsWithMarker(string? line, string marker, StringComparison comparison = StringComparison.Ordinal) + => line != null && line.AsSpan(ContentStart(line)).StartsWith(marker.AsSpan(), comparison); +} diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index 96c79fc..1c72850 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -41,6 +41,8 @@ internal static class EngineSettings private static bool _serverMessageStream = true; private static bool _flightRecorder = true; private static bool _insertReleasesUi; + // "LoadAllServerPlugins": hand-set only, written back only when true (PluginManifestGate). + private static bool _loadAllServerPlugins; // Read-only, like EnableLargeAddressAlignmentFix: only a hand-set value is written back. private static int _maxHotReloads = ReloadCapNotice.DefaultMaxHotReloads; // "IltServerNames" / "IltHosts": what counts as Infinite Leaftide (Compatibility/IltInfo.cs). @@ -110,6 +112,21 @@ internal static class EngineSettings } } + /// <summary> + /// True: every installed server plugin (RynthColdeve, RynthILT, ...) loads, whatever server the + /// client connects to; each still shows only on its own server. Default false: the connect host + /// picks the one plugin for this server (PluginManifestGate.SelectServerPlugins). Set + /// "LoadAllServerPlugins": true in engine.json by hand (testing a plugin with /rc server ... on). + /// </summary> + public static bool LoadAllServerPlugins + { + get + { + EnsureLoaded(); + return _loadAllServerPlugins; + } + } + /// <summary>When false, AvaloniaOverlay.Start() is skipped so the Avalonia STA thread, /// the offscreen overlay window, and all OverlayHost-registered panels never instantiate. /// Eliminates the entire Avalonia/Skia surface from the process. Compatibility hooks and @@ -425,7 +442,8 @@ internal static class EngineSettings /// <summary>"IltServerNames" in engine.json: world-name patterns ('*' wildcard, case-insensitive) /// treated as Infinite Leaftide; null when the file has none (IltDetect.DefaultServerNames). - /// An empty array turns the world-name signal off. Read only: edited in the file.</summary> + /// An empty array turns the world-name signal off. Edited in the file, or with + /// "/rc server names ilt add|remove" (EditIltServerName).</summary> public static IReadOnlyList<string>? IltServerNames { get @@ -435,6 +453,31 @@ internal static class EngineSettings } } + /// <summary>Longest world-name pattern EditIltServerName takes.</summary> + public const int MaxIltServerNameLength = 64; + + /// <summary> + /// Adds (<paramref name="add"/>) or removes a world-name pattern in "IltServerNames" and saves + /// engine.json. With none in the file the list starts from IltDetect.DefaultServerNames, so + /// adding one keeps the defaults. False when nothing changed (already there, not there, or + /// an empty / too long pattern). + /// </summary> + public static bool EditIltServerName(string pattern, bool add) + { + EnsureLoaded(); + string p = (pattern ?? string.Empty).Trim(); + if (p.Length == 0 || p.Length > MaxIltServerNameLength) return false; + var list = new List<string>(_iltServerNames ?? (IEnumerable<string>)Compatibility.IltDetect.DefaultServerNames); + int at = list.FindIndex(x => x.Equals(p, StringComparison.OrdinalIgnoreCase)); + if (add == (at >= 0)) return false; + if (add) list.Add(p); + else list.RemoveAt(at); + // Replaced, never edited in place: IltInfo reads the old list on other threads. + _iltServerNames = list; + Save(); + return true; + } + /// <summary>"IltHosts" in engine.json: launch hosts (a domain covers its subdomains, '*' allowed) /// treated as Infinite Leaftide; null when the file has none (IltDetect.DefaultHosts).</summary> public static IReadOnlyList<string>? IltHosts @@ -538,6 +581,12 @@ internal static class EngineSettings _enableLargeAddressAlignmentFix = laaEl.GetBoolean(); } + if (doc.RootElement.TryGetProperty("LoadAllServerPlugins", out var lasEl) && + (lasEl.ValueKind == JsonValueKind.True || lasEl.ValueKind == JsonValueKind.False)) + { + _loadAllServerPlugins = lasEl.GetBoolean(); + } + if (doc.RootElement.TryGetProperty("EnableAvaloniaOverlay", out var avEl) && (avEl.ValueKind == JsonValueKind.True || avEl.ValueKind == JsonValueKind.False)) { @@ -694,6 +743,7 @@ internal static class EngineSettings "DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream", "FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix", "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel", + "LoadAllServerPlugins", }; private static void Save() @@ -747,6 +797,8 @@ internal static class EngineSettings w.WriteBoolean("InsertReleasesUi", true); if (!_closeOnServerDisconnect) // default true: leave the file as it was w.WriteBoolean("CloseOnServerDisconnect", false); + if (_loadAllServerPlugins) // default false: only a hand-set true is written + w.WriteBoolean("LoadAllServerPlugins", true); if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written w.WriteNumber("MaxHotReloads", _maxHotReloads); if (_reportEndpoint != null) // only a hand-set value is written diff --git a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs index 0ce3f41..7301ee8 100644 --- a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs +++ b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs @@ -67,6 +67,13 @@ internal sealed class LoadedPlugin /// </summary> public IntPtr RenderEmbedPtr { get; set; } + /// <summary> + /// Optional <c>const char* RynthPluginGetSectionsJson(void)</c>, Cdecl: the plugin's Mini + /// Remote sections manifest, UTF-8 JSON (UI/Sections/SectionManifest.cs). The buffer is the + /// plugin's, valid until its next call. Zeroed after it throws. + /// </summary> + public IntPtr SectionsJsonPtr { get; set; } + // ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ─── public bool UiExportsResolved { get; set; } public IntPtr OnScreenChangedPtr { get; set; } @@ -137,5 +144,6 @@ internal sealed class LoadedPlugin Render = null; RenderOverlay = null; RenderEmbedPtr = IntPtr.Zero; + SectionsJsonPtr = IntPtr.Zero; } } diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 34dd2ff..90ee5a3 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -922,6 +922,28 @@ internal struct RynthCoreAPI /// Off AC's main thread a walk of the object's qualities tables is requested for the next tick /// (flag QualitiesPending): ask again a moment later for the full set. Any thread. Requires API v84+.</summary> public IntPtr GetObjectPropertiesFn; + + /// <summary>v85: <c>int ArmConfirmation(uint type, int minPercent, int timeoutMs)</c>: answer + /// the next server yes/no prompt (ConfirmationRequest 0x0274) of this type within timeoutMs, + /// without the client opening its dialog: Yes when the server's "N percent" is at least + /// minPercent (or minPercent is 0), else No. One-shot. timeoutMs <= 0 disarms. + /// 1 armed/disarmed, 0 sender or game-event hook unavailable, -3 bad arguments + /// (type 0, minPercent outside 0-100, timeout over 120 s). Any thread. Requires API v85+.</summary> + public IntPtr ArmConfirmationFn; + + /// <summary>v85: <c>int GetLastConfirmation(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs)</c>: + /// the last prompt the server sent: returns its sequence number (0 = none yet); percent -1 + /// when the text has none; outcome 1 shown to the player, 2 answered Yes, 3 answered No, + /// 4 the send failed (shown). Any out pointer may be null. Any thread. Requires API v85+.</summary> + public IntPtr GetLastConfirmationFn; + + /// <summary>v86: <c>int GetServerStateJson(byte* buffer, int capacity)</c>: which server this is, + /// for every plugin: each server the engine knows (built in, or declared by a loaded plugin) + /// with its verdict, this character's override, why, and the plugin that owns its settings; + /// plus the active server and the Diagnostics pick (UI/Sections/ServerStateJson.cs has the + /// schema). Returns the UTF-8 byte length; when it is >= capacity nothing was written (call + /// again with a bigger buffer). -1 on failure. Any thread. Requires API v86+.</summary> + public IntPtr GetServerStateJsonFn; } /// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary> @@ -1717,6 +1739,12 @@ internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeSta [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetMergeStackResultCallbackDelegate(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int ArmConfirmationCallbackDelegate(uint type, int minPercent, int timeoutMs); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetLastConfirmationCallbackDelegate(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetVTankStateCallbackDelegate(int* sequence); @@ -1726,6 +1754,9 @@ 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 unsafe delegate int GetServerStateJsonCallbackDelegate(byte* buffer, int capacity); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int CloseContainerCallbackDelegate(uint containerId); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index 0c3bb68..dd68d9c 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -19,5 +19,9 @@ internal static class PluginContractVersion // v82: SalvageDirect (salvage without the salvage panel; was v81 on feature/salvage-direct). // v83: GetObjectServerAge and RemoveClientObject (ghost creatures, 2026-10-12). // v84: GetObjectProperties (every property of an object, for /ub propertydump; 2026-10-13). - public const uint Current = 84; + // v85: ArmConfirmation and GetLastConfirmation (answer the server's yes/no prompt, e.g. the + // craft chance, for a plugin; from SilentKelpie's build, 2026-10-15). + // v86: GetServerStateJson (the server list, active server and owning plugins for every plugin; + // server plugins declare their server in their manifest; from SilentKelpie's build). + public const uint Current = 86; } diff --git a/src/RynthCore.Engine/Plugins/PluginLoader.cs b/src/RynthCore.Engine/Plugins/PluginLoader.cs index b77b53e..8ee26e7 100644 --- a/src/RynthCore.Engine/Plugins/PluginLoader.cs +++ b/src/RynthCore.Engine/Plugins/PluginLoader.cs @@ -515,6 +515,7 @@ internal static class PluginLoader // Called through a function pointer (PluginManager.RenderEmbed), so no delegate here. plugin.RenderEmbedPtr = GetProcAddress(handle, "RynthPluginRenderEmbed"); + plugin.SectionsJsonPtr = GetProcAddress(handle, "RynthPluginGetSectionsJson"); // Read name/version from the plugin if available if (plugin.GetName != null) diff --git a/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs b/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs new file mode 100644 index 0000000..b28e194 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs @@ -0,0 +1,153 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/PluginManager.ServerPlugins.cs +// Server plugins the connect host left out (PluginManifestGate.SelectServerPlugins): +// kept with their manifests so Options > Diagnostics lists their servers, and +// loaded one at a time when a server is forced On (the Diagnostics picker, +// "/rc server <id> on", or a character's saved override), without a rescan. +// +// Threads: the list is published as an immutable array (any thread reads it); +// a load request is queued from any thread and served on the pump thread +// (ProcessPendingActions), where every other plugin load happens. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using RynthCore.Engine.Compatibility; +using RynthCore.PluginSdk.Manifest; + +namespace RynthCore.Engine.Plugins; + +/// <summary>An installed server plugin that is not loaded because the client connects to another server.</summary> +internal sealed record SkippedServerPlugin(string Path, RynthPluginManifest Manifest) +{ + public string ServerId => Manifest.Server!.Id; + public string ServerName => Manifest.Server!.Name; + public string PluginName => Manifest.Name; +} + +internal static partial class PluginManager +{ + private static SkippedServerPlugin[] _skippedServerPlugins = Array.Empty<SkippedServerPlugin>(); + private static readonly ConcurrentQueue<string> _serverPluginLoadRequests = new(); + + /// <summary>Installed server plugins not loaded for this connect host. Any thread.</summary> + public static IReadOnlyList<SkippedServerPlugin> SkippedServerPlugins => System.Threading.Volatile.Read(ref _skippedServerPlugins); + + /// <summary>The skipped server plugin for <paramref name="serverId"/>, or null. Any thread.</summary> + public static SkippedServerPlugin? FindSkippedServerPlugin(string serverId) + { + foreach (SkippedServerPlugin s in SkippedServerPlugins) + if (s.ServerId.Equals(serverId, StringComparison.OrdinalIgnoreCase)) return s; + return null; + } + + /// <summary> + /// Loads the plugin for <paramref name="serverId"/> on the next pump tick, if the connect host + /// left it out. Nothing happens for a server whose plugin is loaded already. Any thread. + /// </summary> + public static void RequestServerPluginLoad(string serverId) + { + if (string.IsNullOrWhiteSpace(serverId) || FindSkippedServerPlugin(serverId) == null) return; + _serverPluginLoadRequests.Enqueue(serverId.Trim()); + } + + /// <summary>LoadPluginsFromDisk: the gate's skipped server plugins (replaces the list). Pump thread.</summary> + private static void RememberSkippedServerPlugins(List<(string Path, RynthPluginManifest Manifest)> skipped) + { + var list = new List<SkippedServerPlugin>(skipped.Count); + foreach ((string path, RynthPluginManifest manifest) in skipped) + if (manifest.Server != null) list.Add(new SkippedServerPlugin(path, manifest)); + System.Threading.Volatile.Write(ref _skippedServerPlugins, list.ToArray()); + } + + /// <summary>Serves the queued requests (ProcessPendingActions). Pump thread.</summary> + private static void LoadRequestedServerPlugins() + { + while (_serverPluginLoadRequests.TryDequeue(out string? serverId)) + { + SkippedServerPlugin? s = FindSkippedServerPlugin(serverId); + if (s == null) continue; // loaded by an earlier request, or a rescan changed the list + SkippedServerPlugin[] rest = Array.FindAll(System.Threading.Volatile.Read(ref _skippedServerPlugins), x => !ReferenceEquals(x, s)); + System.Threading.Volatile.Write(ref _skippedServerPlugins, rest); + LoadSkippedServerPlugin(s); + } + } + + /// <summary>Loads, starts and catches up one server plugin, as if it had loaded with the others. Pump thread.</summary> + private static void LoadSkippedServerPlugin(SkippedServerPlugin s) + { + string file = Path.GetFileName(s.Path); + if (FindPlugin(s.PluginName) != null) return; + if (!File.Exists(s.Path)) + { + RynthLog.Warn($"PluginManager: {file} for {s.ServerName} is gone from disk - not loaded."); + return; + } + + // The checks the gate skipped for it: engine API and required plugins. + PluginResolution res = PluginManifestResolver.Resolve( + new[] { new PluginCandidate(s.Path, s.Manifest, RawFileVersion(s.Path)) }, PluginContractVersion.Current); + foreach (PluginRefusal refusal in res.Refused) + { + RefusePlugin(file, refusal.Reason); + return; + } + + RynthLog.Plugin($"PluginManager: {s.ServerName} ({s.ServerId}) is this server (its world name, or forced On) - loading {file} (va before: {Compatibility.AddressSpace.Describe()})"); + LoadedPlugin? plugin = PluginLoader.LoadSingle(s.Path, _shadowRootDir, _loadGeneration); + RynthLog.Plugin($"PluginManager: loaded {file}{(plugin == null ? " (FAILED)" : "")} (va after: {Compatibility.AddressSpace.Describe()})"); + if (plugin == null) + { + AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] {s.PluginName} for {s.ServerName} failed to load - see the RynthCore log.", 1); + return; + } + + plugin.Manifest = s.Manifest; + _plugins.Add(plugin); + PublishPluginsRenderSnapshot(); + EnsureHostCallbacks(); + InitializePlugin(plugin); + DispatchLifecycleToLatePlugin(plugin); + UI.Sections.SectionRegistry.RefreshManifests(); + + if (plugin.Initialized && !plugin.Failed) + AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] Loaded {s.PluginName} for {s.ServerName} (its world name, or picked in Options > Diagnostics).", 1); + } + + /// <summary> + /// OnUIInitialized and OnLoginComplete for one plugin started after the others, when the engine + /// has seen them. Unlike the full dispatchers it leaves the other plugins and the login-time + /// engine work (self-identify, combat mode and target sync) alone. Pump thread. + /// </summary> + private static void DispatchLifecycleToLatePlugin(LoadedPlugin plugin) + { + if (!plugin.Initialized || plugin.Failed) return; + LoadedPlugin? outer = EnterDispatch(plugin); + try + { + if (_uiInitializedObserved && plugin.OnUIInitialized != null && !plugin.UIInitializedDispatched) + { + plugin.OnUIInitialized(); + plugin.UIInitializedDispatched = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnUIInitialized (late load)."); + } + if (_loginCompleteObserved && plugin.OnLoginComplete != null && !plugin.LoginCompleteDispatched) + { + plugin.OnLoginComplete(); + plugin.LoginCompleteDispatched = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnLoginComplete (late load)."); + } + } + catch (Exception ex) + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} lifecycle (late load) threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); + } + } +} \ No newline at end of file diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 07de43d..3a4555e 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -276,6 +276,9 @@ internal static partial class PluginManager private static VendorSellCallbackDelegate? _vendorSellCallback; private static GetVendorTradeStatusCallbackDelegate? _getVendorTradeStatusCallback; private static GetMergeStackResultCallbackDelegate? _getMergeStackResultCallback; + private static ArmConfirmationCallbackDelegate? _armConfirmationCallback; // v85 + private static GetLastConfirmationCallbackDelegate? _getLastConfirmationCallback; // v85 + private static GetServerStateJsonCallbackDelegate? _getServerStateJsonCallback; // v86 private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; @@ -587,6 +590,10 @@ internal static partial class PluginManager RescanPlugins(imguiContext, d3dDevice, gameHwnd); } + // A server forced On whose plugin the connect host left out: load just that plugin. + if (_initialized) + LoadRequestedServerPlugins(); + if (_uiDispatchPending && _initialized) DispatchUIInitializedToLoadedPlugins(); @@ -1344,30 +1351,69 @@ internal static partial class PluginManager { want = System.Numerics.Vector2.Zero; LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot); + LoadedPlugin? p = FindRenderPlugin(plugins, pluginName); + if (p == null) return EmbedNoPlugin; + IntPtr fn = p.RenderEmbedPtr; + if (fn == IntPtr.Zero) return EmbedNoPlugin; + float w = 0, h = 0; + try + { + int r; + fixed (byte* s = surfaceUtf8) + r = ((delegate* unmanaged[Cdecl]<byte*, float, float, float*, float*, int>)fn)(s, size.X, size.Y, &w, &h); + want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0); + return r == 1 ? EmbedDrawn : EmbedNotReady; + } + catch (Exception ex) + { + p.RenderEmbedPtr = IntPtr.Zero; + RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed threw {ex.GetType().Name}: {ex.Message} - embedded surfaces off for this session (plugin keeps running)."); + return EmbedFailed; + } + } + + /// <summary>A running plugin in the render snapshot by name: exact first (see ResolvePluginExport), else contains.</summary> + private static LoadedPlugin? FindRenderPlugin(LoadedPlugin[] plugins, string pluginName) + { + for (int pass = 0; pass < 2; pass++) + for (int i = 0; i < plugins.Length; i++) + { + LoadedPlugin p = plugins[i]; + if (p.Initialized && !p.Failed && NameMatches(p.DisplayName, pluginName, exact: pass == 0)) + return p; + } + return null; + } + + /// <summary> + /// Each running plugin's Mini Remote sections manifest (its optional + /// RynthPluginGetSectionsJson export), copied out as (display name, JSON). A plugin whose + /// export throws has it switched off for the session. Render thread (UI/Sections). + /// </summary> + internal static unsafe List<(string Plugin, string Json)> CollectSectionManifests() + { + var result = new List<(string, string)>(); + if (!_loginCompleteObserved) return result; // plugins build these from in-world state + LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot); for (int i = 0; i < plugins.Length; i++) { LoadedPlugin p = plugins[i]; - if (!p.Initialized || p.Failed || !p.DisplayName.Contains(pluginName, StringComparison.OrdinalIgnoreCase)) - continue; - IntPtr fn = p.RenderEmbedPtr; - if (fn == IntPtr.Zero) return EmbedNoPlugin; - float w = 0, h = 0; + IntPtr fn = p.SectionsJsonPtr; + if (!p.Initialized || p.Failed || fn == IntPtr.Zero) continue; try { - int r; - fixed (byte* s = surfaceUtf8) - r = ((delegate* unmanaged[Cdecl]<byte*, float, float, float*, float*, int>)fn)(s, size.X, size.Y, &w, &h); - want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0); - return r == 1 ? EmbedDrawn : EmbedNotReady; + IntPtr text = ((delegate* unmanaged[Cdecl]<IntPtr>)fn)(); + if (text == IntPtr.Zero) continue; + string? json = Marshal.PtrToStringUTF8(text); + if (!string.IsNullOrEmpty(json)) result.Add((p.DisplayName, json)); } catch (Exception ex) { - p.RenderEmbedPtr = IntPtr.Zero; - RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed threw {ex.GetType().Name}: {ex.Message} - embedded surfaces off for this session (plugin keeps running)."); - return EmbedFailed; + p.SectionsJsonPtr = IntPtr.Zero; + RynthLog.Error($"PluginManager: {p.DisplayName} RynthPluginGetSectionsJson threw {ex.GetType().Name}: {ex.Message} - its sections are off for this session."); } } - return EmbedNoPlugin; + return result; } public static void ShutdownAll() @@ -1458,18 +1504,27 @@ internal static partial class PluginManager if (string.IsNullOrEmpty(pluginName) || string.IsNullOrEmpty(exportName)) return IntPtr.Zero; - for (int i = 0; i < _plugins.Count; i++) + // Exact name first: "RynthLeafDawn" is inside "RynthLeafdawning". + for (int pass = 0; pass < 2; pass++) { - var p = _plugins[i]; - if (p.ModuleHandle == IntPtr.Zero || !p.Initialized || p.Failed) - continue; - if (!p.DisplayName.Contains(pluginName, StringComparison.OrdinalIgnoreCase)) - continue; - return GetProcAddress(p.ModuleHandle, exportName); + for (int i = 0; i < _plugins.Count; i++) + { + var p = _plugins[i]; + if (p.ModuleHandle == IntPtr.Zero || !p.Initialized || p.Failed) + continue; + if (!NameMatches(p.DisplayName, pluginName, exact: pass == 0)) + continue; + return GetProcAddress(p.ModuleHandle, exportName); + } } return IntPtr.Zero; } + /// <summary>The plugin-name test of the by-name lookups: exact (any case), else "display name contains it".</summary> + private static bool NameMatches(string displayName, string pluginName, bool exact) => + exact ? string.Equals(displayName, pluginName, StringComparison.OrdinalIgnoreCase) + : displayName.Contains(pluginName, StringComparison.OrdinalIgnoreCase); + /// <summary> /// Reload deferral (2026-10-05, ReloadDeferral): asks every running plugin's optional /// <c>const char* RynthPluginReloadBlocker(void)</c> export whether a hot reload now would @@ -2606,10 +2661,15 @@ internal static partial class PluginManager // Manifests (embedded in the DLLs, read without loading them): refuse a plugin that needs // a newer engine API or a missing plugin, and put required plugins first. Without - // manifests the list loads exactly as before. - PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(candidates, PluginContractVersion.Current, RawFileVersion); + // manifests the list loads exactly as before. Server plugins: the connect host picks this + // server's (the others stay unloaded; their runtimes would only take address space). + PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(candidates, PluginContractVersion.Current, RawFileVersion, + Compatibility.ServerInfo.LaunchHost, EngineSettings.LoadAllServerPlugins); foreach (string line in plan.Log) RynthLog.Plugin($"PluginManager: {line}"); + if (plan.SkippedForServer.Count > 0) + RynthLog.Info($"PluginManager: {plan.SkippedForServer.Count} server plugin(s) for other servers not loaded (host {Compatibility.ServerInfo.HostDescription})."); + RememberSkippedServerPlugins(plan.SkippedServerPlugins); foreach (PluginRefusal refusal in plan.Refused) RefusePlugin(Path.GetFileName(refusal.Plugin.Key), refusal.Reason); @@ -2731,50 +2791,7 @@ internal static partial class PluginManager RynthLog.Plugin($"PluginManager: Initializing {_plugins.Count} plugin(s)..."); for (int i = 0; i < _plugins.Count; i++) - { - var plugin = _plugins[i]; - - // Manifest: a plugin whose required plugin didn't start isn't started either (they - // come first: LoadPluginsFromDisk ordered them). No manifest, no check. - string? blocked = PluginManifestGate.CheckRequiredStarted(plugin.Manifest, name => - FindPlugin(name) is { } dep ? dep.Initialized && !dep.Failed : null); - if (blocked != null) - { - plugin.Failed = true; - plugin.NotStartedReason = blocked; - RefusePlugin(plugin.FileName, blocked); - continue; - } - plugin.NotStartedReason = ""; - - LoadedPlugin? outer = EnterDispatch(plugin); - try - { - int result = plugin.Init!(ref _api); - if (result == 0) - { - plugin.Initialized = true; - plugin.Failed = false; - plugin.UIInitializedDispatched = false; - plugin.LoginCompleteDispatched = false; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} initialized OK (api v{PluginContractVersion.Current})."); - } - else - { - plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init returned {result} - marked as failed. (engine api version={PluginContractVersion.Current})"); - } - } - catch (Exception ex) - { - plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); - } - finally - { - LeaveDispatch(outer); - } - } + InitializePlugin(_plugins[i]); if (!_uiInitializedObserved) RynthLog.Plugin("PluginManager: Waiting for OnUIInitialized before starting UI-gated plugins."); @@ -2783,6 +2800,51 @@ internal static partial class PluginManager RynthLog.Plugin("PluginManager: Waiting for OnLoginComplete before starting login-gated plugins."); } + /// <summary>Calls one loaded plugin's Init (after checking its required plugins started). Pump thread.</summary> + private static void InitializePlugin(LoadedPlugin plugin) + { + // Manifest: a plugin whose required plugin didn't start isn't started either (they + // come first: LoadPluginsFromDisk ordered them). No manifest, no check. + string? blocked = PluginManifestGate.CheckRequiredStarted(plugin.Manifest, name => + FindPlugin(name) is { } dep ? dep.Initialized && !dep.Failed : null); + if (blocked != null) + { + plugin.Failed = true; + plugin.NotStartedReason = blocked; + RefusePlugin(plugin.FileName, blocked); + return; + } + plugin.NotStartedReason = ""; + + LoadedPlugin? outer = EnterDispatch(plugin); + try + { + int result = plugin.Init!(ref _api); + if (result == 0) + { + plugin.Initialized = true; + plugin.Failed = false; + plugin.UIInitializedDispatched = false; + plugin.LoginCompleteDispatched = false; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} initialized OK (api v{PluginContractVersion.Current})."); + } + else + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init returned {result} - marked as failed. (engine api version={PluginContractVersion.Current})"); + } + } + catch (Exception ex) + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); + } + } + private static void UnloadAllPlugins() { for (int i = _plugins.Count - 1; i >= 0; i--) @@ -3064,6 +3126,9 @@ internal static partial class PluginManager _vendorSellCallback ??= VendorSellAction; _getVendorTradeStatusCallback ??= GetVendorTradeStatusAction; _getMergeStackResultCallback ??= GetMergeStackResultAction; + _armConfirmationCallback ??= ArmConfirmationAction; + unsafe { _getLastConfirmationCallback ??= GetLastConfirmationAction; } + unsafe { _getServerStateJsonCallback ??= GetServerStateJsonAction; } _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -3214,6 +3279,9 @@ internal static partial class PluginManager _api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback); _api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback); _api.GetMergeStackResultFn = Marshal.GetFunctionPointerForDelegate(_getMergeStackResultCallback); + _api.ArmConfirmationFn = Marshal.GetFunctionPointerForDelegate(_armConfirmationCallback); + _api.GetLastConfirmationFn = Marshal.GetFunctionPointerForDelegate(_getLastConfirmationCallback); + _api.GetServerStateJsonFn = Marshal.GetFunctionPointerForDelegate(_getServerStateJsonCallback); RouteApiThroughLoader(); } @@ -3407,6 +3475,25 @@ internal static partial class PluginManager } } + /// <summary> + /// v86: the server list as JSON (UI/Sections/ServerStateJson.cs) from the published snapshot. + /// Any thread: the snapshot is immutable and the strings are volatile reads. -1 on failure. + /// </summary> + private static unsafe int GetServerStateJsonAction(byte* buffer, int capacity) + { + try + { + UI.Sections.SectionRegistry.Snapshot snap = UI.Sections.SectionRegistry.Current; + string json = UI.Sections.ServerStateJson.Build(snap.Servers, snap.Manifests, snap.Revision, + ServerInfo.LaunchHost, AccountHooks.AnnouncedWorldName, UI.Sections.SectionRegistry.EnginePlugin); + return UI.Sections.ServerStateJson.Write(json, buffer, capacity); + } + catch + { + return -1; + } + } + private static unsafe int GetServerInfoAction(byte* worldName, int capacity) { try @@ -3956,6 +4043,32 @@ internal static partial class PluginManager } } + // v85: arm one answer for the next server yes/no prompt (ConfirmationResponder). + private static int ArmConfirmationAction(uint type, int minPercent, int timeoutMs) + { + try { return ConfirmationResponder.Arm(type, minPercent, timeoutMs); } + catch { return 0; } + } + + // v85: the last server yes/no prompt and what happened to it. + private static unsafe int GetLastConfirmationAction(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs) + { + try + { + int seq = ConfirmationResponder.GetLast(out uint t, out uint ctx, out int pct, out int oc, out int age); + if (type != null) *type = t; + if (contextId != null) *contextId = ctx; + if (percent != null) *percent = pct; + if (outcome != null) *outcome = oc; + if (ageMs != null) *ageMs = age; + return seq; + } + catch + { + return 0; + } + } + private static int GiveObjectTo(uint objectId, uint targetId, int amount) { Compatibility.AcActionTrace.Record("GiveObjectTo", objectId, targetId); @@ -4564,6 +4677,33 @@ internal static partial class PluginManager return ToAbiBool(ClientHelperHooks.WieldItem(objectId, equipMask)); } + /// <summary> + /// The engine's own (action, value) to a loaded plugin's optional RynthPluginApplyRemoteCommand + /// (the plugin copies the strings and queues them). False when the plugin isn't loaded and + /// ready or has no such export. Same thread rules as ResolvePluginExport. + /// </summary> + internal static unsafe bool SendPluginCommand(string pluginName, string action, string value) + { + IntPtr export = ResolvePluginExport(pluginName, "RynthPluginApplyRemoteCommand"); + if (export == IntPtr.Zero || string.IsNullOrEmpty(action)) return false; + IntPtr a = Marshal.StringToHGlobalAnsi(action); + IntPtr v = Marshal.StringToHGlobalAnsi(value ?? string.Empty); + try + { + ((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)export)(a, v); + return true; + } + catch + { + return false; + } + finally + { + Marshal.FreeHGlobal(a); + Marshal.FreeHGlobal(v); + } + } + private static unsafe int SendPluginCommandAction(IntPtr pluginNameAnsi, IntPtr actionAnsi, IntPtr valueAnsi) { try diff --git a/src/RynthCore.Engine/Plugins/PluginManifestGate.cs b/src/RynthCore.Engine/Plugins/PluginManifestGate.cs index fa23acb..5f936d2 100644 --- a/src/RynthCore.Engine/Plugins/PluginManifestGate.cs +++ b/src/RynthCore.Engine/Plugins/PluginManifestGate.cs @@ -29,14 +29,25 @@ internal static class PluginManifestGate public List<PluginRefusal> Refused { get; } = new(); /// <summary>Log lines: manifests found, broken manifests, notes.</summary> public List<string> Log { get; } = new(); + /// <summary>Server plugins for another server, left out on purpose (logged, never said in chat).</summary> + public List<string> SkippedForServer { get; } = new(); + /// <summary> + /// The same plugins with their manifests (each has a <c>Server</c>): Options > Diagnostics lists + /// their servers, and forcing one On loads its plugin (PluginManager.RequestServerPluginLoad). + /// </summary> + public List<(string Path, RynthPluginManifest Manifest)> SkippedServerPlugins { get; } = new(); } /// <summary> /// Reads the manifests of <paramref name="paths"/> and resolves them against /// <paramref name="engineApi"/>. <paramref name="fileVersion"/> gives a DLL's version resource /// (for dependency versions of plugins whose manifest has none); null skips it. + /// <paramref name="connectHost"/> (the client's -h host, "" when unknown) picks which server + /// plugins load (<see cref="SelectServerPlugins"/>); <paramref name="loadAllServerPlugins"/> + /// (engine.json LoadAllServerPlugins) turns that off. /// </summary> - public static LoadPlan Plan(IReadOnlyList<string> paths, uint engineApi, Func<string, string>? fileVersion = null) + public static LoadPlan Plan(IReadOnlyList<string> paths, uint engineApi, Func<string, string>? fileVersion = null, + string? connectHost = null, bool loadAllServerPlugins = false) { var plan = new LoadPlan(); var candidates = new List<PluginCandidate>(paths.Count); @@ -71,6 +82,16 @@ internal static class PluginManifestGate candidates.Add(new PluginCandidate(path, manifest, fv)); } + HashSet<string> skip = SelectServerPlugins(candidates, connectHost, loadAllServerPlugins, plan.Log); + if (skip.Count > 0) + { + foreach (PluginCandidate c in candidates) + if (skip.Contains(c.Key) && c.Manifest?.Server != null) + plan.SkippedServerPlugins.Add((c.Key, c.Manifest)); + candidates.RemoveAll(c => skip.Contains(c.Key)); + plan.SkippedForServer.AddRange(skip); + } + PluginResolution res = PluginManifestResolver.Resolve(candidates, engineApi); foreach (PluginCandidate c in res.Order) plan.Load.Add((c.Key, c.Manifest)); @@ -82,6 +103,52 @@ internal static class PluginManifestGate return plan; } + /// <summary> + /// The server plugins to leave out (their paths). With <paramref name="connectHost"/> known, + /// only the plugins that list it load; when none does, none load (every server plugin is a + /// runtime in a 32-bit client, and a dozen of them for a server nobody claims only cost address + /// space). A skipped plugin still loads late when its server announces a world name it lists, + /// or when the character forces its server On (SectionRegistry), so a server that moved to a + /// new host still gets its plugin. With no host (an externally launched client) all load. + /// Nothing is left out when <paramref name="loadAll"/> is set. + /// </summary> + internal static HashSet<string> SelectServerPlugins(IReadOnlyList<PluginCandidate> candidates, string? connectHost, + bool loadAll, List<string> log) + { + var skip = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + var servers = new List<PluginCandidate>(); + foreach (PluginCandidate c in candidates) + if (c.Manifest?.Server != null) servers.Add(c); + if (servers.Count == 0) return skip; + if (loadAll) + { + log.Add($"{servers.Count} server plugin(s): all load (engine.json LoadAllServerPlugins)."); + return skip; + } + string host = (connectHost ?? "").Trim(); + if (host.Length == 0) + { + log.Add($"{servers.Count} server plugin(s): no connect host on the command line, so all load (each shows only on its own server)."); + return skip; + } + + var claimants = new List<string>(); + foreach (PluginCandidate c in servers) + if (c.Manifest!.Server!.MatchesHost(host, out string hit)) + claimants.Add($"{c.Manifest.Name} ({c.Manifest.Server.Id}, \"{hit}\")"); + if (claimants.Count == 0) + log.Add($"{servers.Count} server plugin(s): none lists host {host}, so none load now (one loads once its world name is announced, or when its server is picked)."); + + foreach (PluginCandidate c in servers) + { + if (c.Manifest!.Server!.MatchesHost(host, out _)) continue; + skip.Add(c.Key); + if (claimants.Count > 0) + log.Add($"{Path.GetFileName(c.Key)}: not loaded - it is for {c.Manifest.Server.Name}, and host {host} is {string.Join(", ", claimants)}."); + } + return skip; + } + /// <summary> /// Null when every plugin <paramref name="manifest"/> requires has started; otherwise why not. /// <paramref name="started"/> answers by plugin name: true started, false loaded but not @@ -114,6 +181,7 @@ internal static class PluginManifestGate parts.Add(d.Name + (d.MinVersion.Length > 0 ? " " + d.MinVersion + "+" : "") + (d.Optional ? " (optional)" : "")); s += ", needs " + string.Join(", ", parts); } + if (m.Server != null) s += $", server {m.Server.Id}"; return s; } } diff --git a/src/RynthCore.Engine/RynthLog.cs b/src/RynthCore.Engine/RynthLog.cs index a6fd341..af84ef8 100644 --- a/src/RynthCore.Engine/RynthLog.cs +++ b/src/RynthCore.Engine/RynthLog.cs @@ -42,6 +42,17 @@ internal static class RynthLog /// <summary>Same as <see cref="Warn"/>.</summary> internal static void Warning(string msg) => Warn(msg); + /// <summary> + /// INFO line for a rare state change a support log must show (the server verdicts): written + /// whenever the global LoggingLevel allows Info, whatever the categories' emit levels say. + /// A category set to Trace under a global Info level would otherwise drop it. + /// </summary> + internal static void Milestone(string msg) + { + if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Info)) + EntryPoint.LogTagged("engine", msg, "INF"); + } + // Most recent WRN/ERR text + when, surfaced via the GetEngineStatusJson host bridge so a stuck box // can be diagnosed remotely without reading the PC log. Recorded even when the line is filtered. internal static volatile string? LastIssue; diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index d02f8ee..18c046a 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -329,7 +329,13 @@ internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, No /// <summary>The user hotkeys editor (ImGui/Panels/HotkeysSettingsUi.cs; stored by the engine, not RynthAi).</summary> Hotkeys, /// <summary>A colour (#AARRGGBB in Get/Set): a swatch that opens a picker. The theme's colours (engine-stored).</summary> - Color } + Color, + /// <summary> + /// The server picker and the server list (Diagnostics): which server this character counts + /// as, from the servers the engine and the loaded plugins know (UI/Sections/ServerSelection.cs). + /// Stored by the engine per character (server_force.txt), not RynthAi. + /// </summary> + ServerPick } /// <summary> /// Reads and edits <see cref="RynthAiSettings.DiagCategories"/> ("Name=Level,..."). The category @@ -1134,6 +1140,13 @@ internal static class SettingsSchema "Ticked categories write their trace lines to Trace\\<Category>_<date>.txt (/ra trace <category> on|off)."), Note("+log = the category is at Info: its trace lines also go to the normal log. The launcher's Logging page sets Off, Trace or Info."), Note("Exceptions always go to exceptions_<date>.txt with full stack traces (throttled). Settings here are for this PC, not the profile."), + Spacer(), + Section("Server"), + new SettingRow(SettingKind.ServerPick, "Server", + "Which server this character counts as. Auto detects it (the connect host, the world name the server announces, RynthILT).\n" + + "Picking a server forces it on and every other server off, for this character; every plugin follows at once.\n" + + "Also: /rc server pick <id>|auto, and /rc server for the list."), + Note("The list is every server the engine knows: the built-in ones and those declared by the loaded server plugins. \"Settings from\" is the plugin the others ask for that server's settings."), }), }; } diff --git a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs index 26a3015..c91be84 100644 --- a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs +++ b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs @@ -790,6 +790,38 @@ internal static class ScriptWindowRegistry else ImGuiPanelHost.Close(w.PanelKey); } + /// <summary> + /// Opens or closes a plugin's script window by its key ("RynthOracle/Oracle"), as the bar + /// does (the owner gets a Visibility event, reason 2). False when no live window has the + /// key (the plugin isn't loaded or hasn't submitted it yet). Any thread. + /// </summary> + public static bool PlayerSetVisible(string key, bool visible) + { + ScriptWindow? w = Find(key); + if (w == null) return false; + PlayerSetVisible(w, visible); + return true; + } + + /// <summary>Whether a plugin has submitted a script window with this key (and it is still live). Any thread.</summary> + public static bool Has(string key) => Find(key) != null; + + /// <summary>Whether a plugin's script window (by key) is open; false when there is none. Any thread.</summary> + public static bool IsOpen(string key) + { + ScriptWindow? w = Find(key); + return w != null && ImGuiPanelHost.IsOpen(w.PanelKey); + } + + /// <summary>The live window with a plugin key, or null.</summary> + private static ScriptWindow? Find(string key) + { + if (string.IsNullOrWhiteSpace(key)) return null; + ScriptWindow? w; + lock (Sync) ByPanelKey.TryGetValue(PanelKeyPrefix + SanitizeKey(key), out w); + return w == null || w.Removed ? null : w; + } + /// <summary> /// SetNextWindowSize / SetNextWindowPos (§3.2): a request is passed to the panel host /// when its value changed since the last one applied, when the window was re-recorded diff --git a/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs b/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs new file mode 100644 index 0000000..412700f --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs @@ -0,0 +1,63 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/NotLoadedServers.cs +// Servers whose plugin is installed but not loaded: the connect host belongs to +// another server, so PluginManifestGate left the plugin out. They still go in +// the server list (Options > Diagnostics, GetServerStateJson), so a server can +// be picked there; a server forced On gets its plugin loaded +// (PluginManager.RequestServerPluginLoad). +// +// Pure (no AC, no engine state, no I/O): tools/SectionsTests compiles it. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Sections; + +/// <summary>An installed server plugin that is not loaded: its server and the plugin's name.</summary> +internal readonly record struct NotLoadedServer(string Id, string Name, string Plugin, string[]? WorldNames = null); + +internal static class NotLoadedServers +{ + /// <summary> + /// Adds each not-loaded server whose id isn't in <paramref name="list"/> yet (a loaded plugin's + /// declaration or a built-in server wins). Not detected (the host is another server's); active + /// only when this character forces it On. + /// </summary> + public static void Append(List<ServerState> list, IReadOnlyList<NotLoadedServer> notLoaded, Func<string, ServerForce> force) + { + foreach (NotLoadedServer s in notLoaded) + { + if (s.Id.Length == 0 || list.Exists(x => x.Id.Equals(s.Id, StringComparison.OrdinalIgnoreCase))) continue; + ServerForce f = force(s.Id); + string reason = f == ServerForce.On + ? $"forced On: loading {s.Plugin}" + : $"{s.Plugin} is installed but not loaded (this host is another server's); pick it to load it"; + list.Add(new ServerState(s.Id, s.Name, ServerForceText.Apply(f, false), false, f, false, reason)); + } + } + + /// <summary>The not-loaded servers this character forces On: their plugins should load now.</summary> + public static List<string> ForcedOn(IReadOnlyList<NotLoadedServer> notLoaded, Func<string, ServerForce> force) + => ToLoad(notLoaded, force, world: null); + + /// <summary> + /// The not-loaded servers whose plugins should load now: forced On by this character, or (not + /// forced Off) named by the world name the server announced (<paramref name="world"/>; null or + /// empty before login). The host left them out, but the world says this is their server. + /// </summary> + public static List<string> ToLoad(IReadOnlyList<NotLoadedServer> notLoaded, Func<string, ServerForce> force, string? world) + { + var ids = new List<string>(); + foreach (NotLoadedServer s in notLoaded) + { + if (s.Id.Length == 0) continue; + ServerForce f = force(s.Id); + if (f == ServerForce.On + || (f != ServerForce.Off && !string.IsNullOrWhiteSpace(world) && s.WorldNames is { Length: > 0 } + && Compatibility.IltDetect.WorldNameMatches(world, s.WorldNames, out _))) + ids.Add(s.Id); + } + return ids; + } +} diff --git a/src/RynthCore.Engine/UI/Sections/SectionCatalog.cs b/src/RynthCore.Engine/UI/Sections/SectionCatalog.cs new file mode 100644 index 0000000..236829a --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/SectionCatalog.cs @@ -0,0 +1,226 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/SectionCatalog.cs +// The Mini Remote's sections: the twelve core ones every world has, and what +// installed plugins add, laid out for the servers that are active now. +// +// Pure (no AC, no ImGui, no engine state): tools/SectionsTests compiles it. +// SectionRegistry.cs feeds it the plugins' manifests, the engine panels that +// exist and the server verdicts; MiniRemoteFace draws the result. +// +// A section's body, top to bottom: +// panes what fills it: the engine's core panels for it (embedded whole), +// the Session Stats overview (dropped once a plugin's universal +// primary surface fills that section, e.g. RynthAi's session +// stats), and plugins' primary surfaces. More than one pane = a +// row of sub-tabs. +// groups "Server: <name>" for each active server with items here, then +// "Plugins" for items every world gets: inline plugin surfaces +// (options and configuration) and command buttons. +// Core sections always show (with a note when nothing fills them); a plugin's +// own section shows only while something in it applies to this world. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.UI.Sections; + +/// <summary>A core section: always on the rail.</summary> +internal sealed record CoreSection(string Id, string Label, string[] Panels, bool Overview = false); + +/// <summary>A server and whether it is active for this character now.</summary> +internal sealed record ServerState(string Id, string Name, bool Active, bool Detected, ServerForce Force, bool BuiltIn, string Reason); + +internal enum SectionPaneKind +{ + /// <summary>The Session Stats section's engine overview (XP / luminance this session), when no plugin fills it.</summary> + Overview, + /// <summary>An engine panel embedded whole.</summary> + CorePanel, + /// <summary>A plugin surface (RynthPluginRenderEmbed).</summary> + Surface, +} + +/// <summary>One sub-tab of a section's body.</summary> +internal sealed record SectionPane(SectionPaneKind Kind, string Title, string Panel, SectionContribution? Contribution); + +/// <summary>A titled group of a section's items: one active server, or "Plugins" (every world).</summary> +internal sealed record SectionGroup(string Title, ServerState? Server, SectionContribution[] Items); + +/// <summary>One section as it should be drawn now.</summary> +internal sealed record SectionView(string Id, string Label, bool Core, int Order, SectionPane[] Panes, SectionGroup[] Groups) +{ + public bool HasContent => Panes.Length > 0 || Groups.Length > 0; +} + +internal static class SectionCatalog +{ + /// <summary>The rail entry for the remote itself (RynthAi's remote, or the engine's slot grid).</summary> + public const string RemoteId = "remote"; + + /// <summary>The "char" section's label: the session's XP, luminance and kills.</summary> + public const string SessionStatsLabel = "Session Stats"; + + /// <summary> + /// The core sections, in rail order, with the engine panels that fill each (the first + /// that exists is the default sub-tab). Sections without panels are filled by plugins. + /// </summary> + public static readonly CoreSection[] Core = + { + // Session Stats (was "Char" until 2026.10.5.54; the id stays "char" so saved rail picks, + // "/rc miniremote section char" and plugin manifests keep working). Character details + // live in RynthOracle's Character tab now, server picks in Options > Diagnostics. + new("char", SessionStatsLabel, Array.Empty<string>(), Overview: true), + new("map", "Map", new[] { "Radar", "Dungeon Map" }), + new("skills", "Skills", new[] { "Skills" }), + new("combat", "Combat", new[] { "Damage", "Monsters" }), + new("nav", "Nav", new[] { "Nav", "RynthNav" }), + new("inventory", "Inventory", new[] { "Inventory", "Item Count", "Items" }), + new("crafting", "Crafting", Array.Empty<string>()), + new("spells", "Spells", Array.Empty<string>()), + new("chat", "Chat", new[] { "Chat" }), + new("friends", "Friends", Array.Empty<string>()), + new("fellowship", "Fellowship", Array.Empty<string>()), + new("pets", "Pets", Array.Empty<string>()), + }; + + /// <summary>Plugin sections sort after the core ones unless they ask for a smaller order.</summary> + private const int CoreOrderStep = 100; + + public static CoreSection? FindCore(string id) + { + foreach (CoreSection c in Core) + if (c.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return c; + return null; + } + + /// <summary> + /// A plugin-declared server's own detection: its launch host or announced world name + /// matches one of its lists (the same matching as Infinite Leaftide's). + /// </summary> + public static bool DetectDeclared(SectionServerDecl server, string? host, string? world, out string reason) + { + if (IltDetect.HostMatches(host, server.Hosts, out string hostHit)) + { + reason = $"host matches \"{hostHit}\""; + return true; + } + if (IltDetect.WorldNameMatches(world, server.WorldNames, out string worldHit)) + { + reason = $"world name matches \"{worldHit}\""; + return true; + } + reason = server.Hosts.Length + server.WorldNames.Length == 0 ? "no host or world-name list" : "no host or world name matches"; + return false; + } + + /// <summary> + /// Every section to show now, in rail order (the remote entry is not included). + /// <paramref name="panelExists"/> says whether an engine panel is registered. + /// </summary> + public static List<SectionView> Build(IReadOnlyList<SectionManifest> manifests, Func<string, bool> panelExists, + IReadOnlyList<ServerState> servers) + { + var activeServers = new Dictionary<string, ServerState>(StringComparer.OrdinalIgnoreCase); + foreach (ServerState s in servers) + if (s.Active) activeServers[s.Id] = s; + + // Contributions that apply to this world, by section. + var bySection = new Dictionary<string, List<SectionContribution>>(StringComparer.OrdinalIgnoreCase); + foreach (SectionManifest m in manifests) + foreach (SectionContribution c in m.Contributions) + { + if (!c.IsUniversal && !activeServers.ContainsKey(c.Server)) continue; + if (!bySection.TryGetValue(c.Section, out var list)) bySection[c.Section] = list = new List<SectionContribution>(); + list.Add(c); + } + + var views = new List<SectionView>(); + for (int i = 0; i < Core.Length; i++) + { + CoreSection core = Core[i]; + bySection.TryGetValue(core.Id, out var items); + views.Add(BuildOne(core.Id, core.Label, true, i * CoreOrderStep, core, items, panelExists, servers)); + } + + // Plugin sections: the first declaration of an id wins; never one of the core ids. + var declared = new Dictionary<string, SectionDecl>(StringComparer.OrdinalIgnoreCase); + foreach (SectionManifest m in manifests) + foreach (SectionDecl d in m.Sections) + if (FindCore(d.Id) == null && !d.Id.Equals(RemoteId, StringComparison.OrdinalIgnoreCase)) + declared.TryAdd(d.Id, d); + foreach (SectionDecl d in declared.Values) + { + if (!bySection.TryGetValue(d.Id, out var items)) continue; // nothing for this world + SectionView v = BuildOne(d.Id, d.Label, false, d.Order, null, items, panelExists, servers); + if (v.HasContent) views.Add(v); + } + // Stable: equal orders keep core before plugin sections, then plugin sections by id. + return views.OrderBy(v => v.Order).ThenBy(v => v.Core ? 0 : 1).ThenBy(v => v.Id, StringComparer.Ordinal).ToList(); + } + + private static SectionView BuildOne(string id, string label, bool isCore, int order, CoreSection? core, + List<SectionContribution>? items, Func<string, bool> panelExists, + IReadOnlyList<ServerState> servers) + { + var panes = new List<SectionPane>(); + if (core != null) + { + if (core.Overview) panes.Add(new SectionPane(SectionPaneKind.Overview, label, string.Empty, null)); + foreach (string panel in core.Panels) + if (SafeExists(panelExists, panel)) panes.Add(new SectionPane(SectionPaneKind.CorePanel, panel, panel, null)); + } + + var universal = new List<SectionContribution>(); + var perServer = new Dictionary<string, List<SectionContribution>>(StringComparer.OrdinalIgnoreCase); + if (items != null) + { + items.Sort(CompareItems); + foreach (SectionContribution c in items) + { + if (c.Primary && c.IsSurface) + { + panes.Add(new SectionPane(SectionPaneKind.Surface, c.Label, string.Empty, c)); + continue; + } + if (c.IsUniversal) universal.Add(c); + else + { + if (!perServer.TryGetValue(c.Server, out var list)) perServer[c.Server] = list = new List<SectionContribution>(); + list.Add(c); + } + } + } + + // One session on screen: the engine's own Session Stats overview is a stand-in, dropped + // when a plugin fills the section with an every-world view of its own (RynthAi's session + // stats, which RynthTracker, RynthOracle and RynthILT follow too). + if (core is { Overview: true } && panes.Exists(p => p.Kind == SectionPaneKind.Surface && p.Contribution!.IsUniversal)) + panes.RemoveAll(p => p.Kind == SectionPaneKind.Overview); + + var groups = new List<SectionGroup>(); + foreach (ServerState s in servers) // the servers' own order: built-in first + if (s.Active && perServer.TryGetValue(s.Id, out var list)) + groups.Add(new SectionGroup("Server: " + s.Name, s, list.ToArray())); + if (universal.Count > 0) groups.Add(new SectionGroup("Plugins", null, universal.ToArray())); + + return new SectionView(id, label, isCore, order, panes.ToArray(), groups.ToArray()); + } + + /// <summary>Order, then server-agnostic first, then label: the same list always draws the same way.</summary> + private static int CompareItems(SectionContribution a, SectionContribution b) + { + if (a.Order != b.Order) return a.Order.CompareTo(b.Order); + if (a.IsUniversal != b.IsUniversal) return a.IsUniversal ? -1 : 1; + int byLabel = string.Compare(a.Label, b.Label, StringComparison.OrdinalIgnoreCase); + return byLabel != 0 ? byLabel : string.CompareOrdinal(a.Plugin, b.Plugin); + } + + private static bool SafeExists(Func<string, bool> panelExists, string panel) + { + try { return panelExists(panel); } + catch { return false; } + } +} diff --git a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs new file mode 100644 index 0000000..b6f9379 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs @@ -0,0 +1,253 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/SectionManifest.cs +// What a plugin adds to the Mini Remote's sections, read from its optional +// export const char* RynthPluginGetSectionsJson(void) (UTF-8 JSON, the same +// parameterless JSON-getter convention as RynthPluginGetSnapshotJson). +// +// Pure (no AC, no engine state): tools/SectionsTests compiles this file as is. +// +// Schema (version 1; unknown keys are ignored, so later versions only add): +// { +// "version": 1, +// "servers": [ { "id": "ilt", "name": "Infinite Leaftide", +// "worldNames": ["*Leaftide*"], "hosts": ["infiniteleaftide.online"] } ], +// "sections": [ { "id": "quests", "label": "Quests", "order": 150 } ], +// "contributions": [ +// { "section": "pets", "server": "", "label": "Pets", "surface": "section:pets", +// "primary": true, "width": 560, "height": 580 }, +// { "section": "skills", "server": "ilt", "label": "Progression", +// "command": "/rc progression", "tooltip": "...", "enabled": true, "note": "" } ] +// } +// servers servers the plugin knows. A built-in id (ilt, aelrynth) keeps the +// engine's own detection; a new id is detected from its lists. +// sections extra sections (beyond the core twelve) the plugin adds. +// contributions what the plugin puts in a section: "server" "" = every world, else +// only while that server is active (detected or forced). "surface" +// = drawn inline through RynthPluginRenderEmbed; "command" = a button +// that runs it. "primary" = the section's main view when the engine +// has no core panel for it (Pets, Crafting, Spells, ...). +// +// Everything from a plugin is checked here: ids are short lower-case words, +// text is capped, a command must be a single "/..." chat command, and the lists +// are capped, so a damaged or hostile manifest can't flood the UI. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; + +namespace RynthCore.Engine.UI.Sections; + +/// <summary>A server a plugin declares (detected by the engine from its lists unless the id is built in).</summary> +internal sealed record SectionServerDecl(string Id, string Name, string[] WorldNames, string[] Hosts); + +/// <summary>An extra section a plugin adds.</summary> +internal sealed record SectionDecl(string Id, string Label, int Order); + +/// <summary>One thing a plugin puts in a section.</summary> +internal sealed record SectionContribution( + string Plugin, + string Section, + string Server, + string Label, + string Surface, + string Command, + string Tooltip, + bool Primary, + bool Enabled, + string Note, + float Width, + float Height, + int Order) +{ + /// <summary>Drawn inline (a plugin surface), not a button.</summary> + public bool IsSurface => Surface.Length > 0; + /// <summary>For every world, not one server.</summary> + public bool IsUniversal => Server.Length == 0; +} + +/// <summary>One plugin's parsed manifest.</summary> +internal sealed record SectionManifest( + string Plugin, + SectionServerDecl[] Servers, + SectionDecl[] Sections, + SectionContribution[] Contributions) +{ + public static readonly SectionManifest Empty = + new("", Array.Empty<SectionServerDecl>(), Array.Empty<SectionDecl>(), Array.Empty<SectionContribution>()); +} + +internal static class SectionManifestParser +{ + public const int SupportedVersion = 1; + public const int MaxServers = 16; + public const int MaxSections = 32; + public const int MaxContributions = 128; + public const int MaxPatterns = 32; + public const int MaxIdLength = 32; + public const int MaxLabelLength = 48; + public const int MaxTextLength = 300; + public const int MaxCommandLength = 200; + public const int MaxSurfaceLength = 64; + public const float MaxSurfaceSize = 4096f; + /// <summary>Largest manifest read at all (a manifest is a few KB).</summary> + public const int MaxJsonLength = 256 * 1024; + + /// <summary> + /// Parses <paramref name="json"/> from plugin <paramref name="plugin"/>. Never throws: + /// a malformed document gives <see cref="SectionManifest.Empty"/> and the reason in + /// <paramref name="error"/>; a bad entry is skipped. + /// </summary> + public static SectionManifest Parse(string plugin, string? json, out string error) + { + error = string.Empty; + if (string.IsNullOrWhiteSpace(json)) { error = "empty"; return SectionManifest.Empty with { Plugin = plugin }; } + if (json.Length > MaxJsonLength) { error = $"too large ({json.Length} chars)"; return SectionManifest.Empty with { Plugin = plugin }; } + try + { + using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 16 }); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) { error = "not a JSON object"; return SectionManifest.Empty with { Plugin = plugin }; } + int version = root.TryGetProperty("version", out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int n) ? n : 1; + if (version < 1) { error = $"version {version}"; return SectionManifest.Empty with { Plugin = plugin }; } + + var servers = new List<SectionServerDecl>(); + foreach (JsonElement e in Array(root, "servers")) + { + if (servers.Count >= MaxServers) break; + string id = Id(Str(e, "id")); + if (id.Length == 0 || servers.Exists(s => s.Id == id)) continue; + string name = Text(Str(e, "name"), MaxLabelLength); + servers.Add(new SectionServerDecl(id, name.Length > 0 ? name : id, Patterns(e, "worldNames"), Patterns(e, "hosts"))); + } + + var sections = new List<SectionDecl>(); + foreach (JsonElement e in Array(root, "sections")) + { + if (sections.Count >= MaxSections) break; + string id = Id(Str(e, "id")); + string label = Text(Str(e, "label"), MaxLabelLength); + if (id.Length == 0 || label.Length == 0 || sections.Exists(s => s.Id == id)) continue; + sections.Add(new SectionDecl(id, label, Int(e, "order", 1000))); + } + + var contributions = new List<SectionContribution>(); + foreach (JsonElement e in Array(root, "contributions")) + { + if (contributions.Count >= MaxContributions) break; + string section = Id(Str(e, "section")); + string label = Text(Str(e, "label"), MaxLabelLength); + if (section.Length == 0 || label.Length == 0) continue; + string rawServer = Str(e, "server"); + string server = rawServer.Length == 0 ? string.Empty : Id(rawServer); + if (rawServer.Length > 0 && server.Length == 0) continue; // a server id that isn't one + string surface = Surface(Str(e, "surface")); + string command = Command(Str(e, "command")); + if (surface.Length == 0 && command.Length == 0) continue; // nothing to draw or run + contributions.Add(new SectionContribution( + plugin, section, server, label, surface, command, + Text(Str(e, "tooltip"), MaxTextLength, multiline: true), + Bool(e, "primary", false), + Bool(e, "enabled", true), + Text(Str(e, "note"), MaxTextLength, multiline: true), + Size(e, "width"), Size(e, "height"), + Int(e, "order", 1000))); + } + + return new SectionManifest(plugin, servers.ToArray(), sections.ToArray(), contributions.ToArray()); + } + catch (JsonException ex) + { + error = "bad JSON: " + ex.Message; + return SectionManifest.Empty with { Plugin = plugin }; + } + } + + // ── Field rules ───────────────────────────────────────────────────── + + /// <summary>A lower-case id of letters, digits, '-' and '_' (at most MaxIdLength), else "".</summary> + public static string Id(string? text) + { + string t = (text ?? string.Empty).Trim().ToLowerInvariant(); + if (t.Length == 0 || t.Length > MaxIdLength) return string.Empty; + foreach (char c in t) + if (!(c is >= 'a' and <= 'z' or >= '0' and <= '9' or '-' or '_')) return string.Empty; + return t; + } + + /// <summary> + /// Display text: control characters become spaces (line breaks too, unless + /// <paramref name="multiline"/>: tooltips and notes), trimmed, capped. + /// </summary> + public static string Text(string? text, int max, bool multiline = false) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + var chars = text.ToCharArray(); + for (int i = 0; i < chars.Length; i++) + if (char.IsControl(chars[i]) && !(multiline && chars[i] == '\n')) chars[i] = ' '; + string t = new string(chars).Trim(); + return t.Length <= max ? t : t[..max]; + } + + /// <summary>A plugin surface name: letters, digits and ":_.-", not the engine's ":popout" suffix.</summary> + public static string Surface(string? text) + { + string t = (text ?? string.Empty).Trim(); + if (t.Length == 0 || t.Length > MaxSurfaceLength || t.EndsWith(":popout", StringComparison.OrdinalIgnoreCase)) return string.Empty; + foreach (char c in t) + if (!(char.IsAsciiLetterOrDigit(c) || c is ':' or '_' or '.' or '-')) return string.Empty; + return t; + } + + /// <summary>One chat command ("/rc progression"): starts with '/', one line, capped; else "".</summary> + public static string Command(string? text) + { + string t = (text ?? string.Empty).Trim(); + if (t.Length < 2 || t.Length > MaxCommandLength || t[0] != '/') return string.Empty; + foreach (char c in t) + if (char.IsControl(c)) return string.Empty; + return t; + } + + private static IEnumerable<JsonElement> Array(JsonElement root, string name) + { + if (!root.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) yield break; + foreach (JsonElement e in a.EnumerateArray()) + if (e.ValueKind == JsonValueKind.Object) yield return e; + } + + private static string Str(JsonElement e, string name) + => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; + + private static bool Bool(JsonElement e, string name, bool fallback) + => e.TryGetProperty(name, out JsonElement v) ? v.ValueKind switch + { + JsonValueKind.True => true, + JsonValueKind.False => false, + _ => fallback, + } : fallback; + + private static int Int(JsonElement e, string name, int fallback) + => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int n) + ? Math.Clamp(n, -100_000, 100_000) : fallback; + + /// <summary>A surface's preferred width or height in pixels (0 = not given).</summary> + private static float Size(JsonElement e, string name) + => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) + && d > 0 && !double.IsNaN(d) ? (float)Math.Min(d, MaxSurfaceSize) : 0f; + + private static string[] Patterns(JsonElement e, string name) + { + var list = new List<string>(); + if (!e.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list.ToArray(); + foreach (JsonElement p in a.EnumerateArray()) + { + if (list.Count >= MaxPatterns) break; + if (p.ValueKind != JsonValueKind.String) continue; + string t = Text(p.GetString(), MaxLabelLength); + if (t.Length > 0 && !list.Contains(t, StringComparer.OrdinalIgnoreCase)) list.Add(t); + } + return list.ToArray(); + } +} diff --git a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs new file mode 100644 index 0000000..a90e860 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs @@ -0,0 +1,277 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/SectionRegistry.cs +// The live state behind the Mini Remote's sections: which servers are active +// (one world check for the engine and every plugin), what the installed +// plugins add (their RynthPluginGetSectionsJson manifests), and the section +// layout SectionCatalog builds from those. +// +// Servers: +// built in Infinite Leaftide (IltInfo) and Aelrynth (ServerInfo): the engine's +// own detection, with the per-character override (ServerForceStore). +// declared any other id a plugin's manifest names: detected from its host / +// world-name lists, with the same per-character override. +// not loaded installed server plugins the connect host left out (NotLoadedServers): +// listed so Options > Diagnostics can pick them; forced On, the plugin loads. +// RynthAi follows these verdicts (ServerMenus pushes them), so the engine and +// RynthAi can't disagree about which world this is. +// +// The engine's own contributions (Bounties, Guardian, Progression) are a +// manifest like a plugin's, added at init by which plugins are installed. +// +// Threads: Tick runs on AC's render thread (ImGuiController frame); readers +// on any thread get the last published snapshot (volatile, immutable). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.UI.Sections; + +internal static class SectionRegistry +{ + /// <summary>The engine's own entry in the manifests (its contributions' "plugin").</summary> + public const string EnginePlugin = "RynthCore"; + + /// <summary>How often the plugins' manifests are read again (they change with server features).</summary> + private const long ManifestPollMs = 2_000; + /// <summary>How often the server verdicts and the layout are rebuilt.</summary> + private const long RebuildMs = 1_000; + + private sealed record BuiltInServer(string Id, string Name, Func<bool> Active, Func<(bool Detected, string Reason)> Detect); + + /// <summary>Everything the UI reads, published together.</summary> + internal sealed record Snapshot( + IReadOnlyList<ServerState> Servers, + IReadOnlyList<SectionView> Sections, + IReadOnlyList<SectionManifest> Manifests, + int Revision) + { + public static readonly Snapshot Empty = + new(Array.Empty<ServerState>(), Array.Empty<SectionView>(), Array.Empty<SectionManifest>(), 0); + + public SectionView? Find(string id) + { + foreach (SectionView v in Sections) + if (v.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return v; + return null; + } + + public ServerState? Server(string id) + { + foreach (ServerState s in Servers) + if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s; + return null; + } + } + + private static readonly BuiltInServer[] BuiltIns = + { + new(IltInfo.ServerId, "Infinite Leaftide", static () => IltInfo.IsIlt, static () => + { + IltVerdict v = IltInfo.Detected; + return (v.IsIlt, v.Reason); + }), + new(ServerInfo.ServerId, "Aelrynth", static () => ServerInfo.IsAelrynth, static () => + { + ServerVerdict v = ServerInfo.Detected; + return (v.IsAelrynth, v.Reason); + }), + }; + + private static readonly object Gate = new(); + /// <summary>The engine's items; Unless = a plugin whose own manifest replaces the item ("" = always).</summary> + private static readonly List<(SectionContribution Item, string Unless)> EngineItems = new(); // under Gate + private static readonly Dictionary<string, (string Json, SectionManifest Manifest)> PluginManifests = + new(StringComparer.OrdinalIgnoreCase); // render thread only + + private static volatile Snapshot _snapshot = Snapshot.Empty; + private static long _nextPollMs, _nextRebuildMs; + private static int _lastForceVersion = -1; + private static int _revision; + private static string _lastSignature = string.Empty; + + /// <summary>The current servers and sections. Any thread.</summary> + public static Snapshot Current => _snapshot; + + /// <summary>True for an id the engine detects itself.</summary> + public static bool IsBuiltInServer(string id) + { + foreach (BuiltInServer b in BuiltIns) + if (b.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + /// <summary> + /// An engine contribution (an engine panel or /rc command for a section), added at init. + /// Same rules as a plugin's: the command is checked by SectionManifestParser. With + /// <paramref name="unlessPlugin"/>, the item is left out while that plugin publishes a + /// manifest of its own (a stand-in for plugins too old to describe themselves). + /// </summary> + public static void AddEngineItem(string section, string server, string label, string command, string tooltip, + int order = 1000, string unlessPlugin = "") + { + string cmd = SectionManifestParser.Command(command); + string sec = SectionManifestParser.Id(section); + if (cmd.Length == 0 || sec.Length == 0) return; + var item = new SectionContribution(EnginePlugin, sec, SectionManifestParser.Id(server), label, string.Empty, + cmd, tooltip, Primary: false, Enabled: true, Note: string.Empty, Width: 0, Height: 0, Order: order); + lock (Gate) EngineItems.Add((item, unlessPlugin)); + Invalidate(); + } + + /// <summary>True when a plugin whose name contains <paramref name="plugin"/> publishes a manifest. Render thread.</summary> + private static bool HasManifestFrom(string plugin) + { + foreach (string name in PluginManifests.Keys) + if (name.Contains(plugin, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + /// <summary>Rebuilds on the next Tick (an override or the character changed). Any thread.</summary> + public static void Invalidate() + { + Volatile.Write(ref _nextRebuildMs, 0); + IltInfo.Invalidate(); + ServerInfo.Invalidate(); + } + + /// <summary>Reads the manifests again on the next Tick. Any thread.</summary> + public static void RefreshManifests() => Volatile.Write(ref _nextPollMs, 0); + + /// <summary>Render thread, every frame: cheap until a poll or rebuild is due.</summary> + public static void Tick() + { + long now = Environment.TickCount64; + bool changed = false; + if (now >= Volatile.Read(ref _nextPollMs)) + { + Volatile.Write(ref _nextPollMs, now + ManifestPollMs); + changed |= PollManifests(); + } + int forceVersion = ServerForceStore.Version; + if (forceVersion != _lastForceVersion) + { + _lastForceVersion = forceVersion; + IltInfo.Invalidate(); + ServerInfo.Invalidate(); + changed = true; + } + if (!changed && now < Volatile.Read(ref _nextRebuildMs)) return; + Volatile.Write(ref _nextRebuildMs, now + RebuildMs); + Rebuild(); + } + + /// <summary>Reads every plugin's manifest; re-parses only the ones whose text changed.</summary> + private static bool PollManifests() + { + bool changed = false; + var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + foreach ((string plugin, string json) in Plugins.PluginManager.CollectSectionManifests()) + { + seen.Add(plugin); + if (PluginManifests.TryGetValue(plugin, out var old) && old.Json == json) continue; + SectionManifest m = SectionManifestParser.Parse(plugin, json, out string error); + if (error.Length > 0) RynthLog.UI($"Sections: {plugin}'s manifest was not read - {error}."); + PluginManifests[plugin] = (json, m); + changed = true; + } + // A plugin that unloaded (or stopped answering) takes its sections with it. + var gone = new List<string>(); + foreach (string plugin in PluginManifests.Keys) + if (!seen.Contains(plugin)) gone.Add(plugin); + foreach (string plugin in gone) { PluginManifests.Remove(plugin); changed = true; } + return changed; + } + + private static void Rebuild() + { + var manifests = new List<SectionManifest>(); + var engineItems = new List<SectionContribution>(); + lock (Gate) + foreach ((SectionContribution item, string unless) in EngineItems) + if (unless.Length == 0 || !HasManifestFrom(unless)) engineItems.Add(item); + manifests.Add(new SectionManifest(EnginePlugin, Array.Empty<SectionServerDecl>(), Array.Empty<SectionDecl>(), engineItems.ToArray())); + foreach (var entry in PluginManifests.Values) manifests.Add(entry.Manifest); + + List<ServerState> servers = BuildServers(manifests); + + // Installed server plugins the connect host left out: listed so they can be picked, and + // loaded as soon as this character forces their server On (picker, chat or saved override). + List<NotLoadedServer> notLoaded = NotLoadedServerPlugins(); + NotLoadedServers.Append(servers, notLoaded, ServerForceStore.Get); + foreach (string id in NotLoadedServers.ToLoad(notLoaded, ServerForceStore.Get, AccountHooks.AnnouncedWorldName)) + Plugins.PluginManager.RequestServerPluginLoad(id); + + List<SectionView> sections = SectionCatalog.Build(manifests, ImGuiBackend.ImGuiPanelHost.CanEmbed, servers); + + // Bump the revision only when what the UI shows changed, so the menus and the push stay quiet. + string signature = Signature(servers, sections); + if (signature != _lastSignature) + { + _lastSignature = signature; + _revision++; + } + _snapshot = new Snapshot(servers, sections, manifests, _revision); + } + + /// <summary>The built-in servers, then every server a manifest declares with a new id.</summary> + private static List<ServerState> BuildServers(List<SectionManifest> manifests) + { + var list = new List<ServerState>(); + foreach (BuiltInServer b in BuiltIns) + { + bool active = false, detected = false; + string reason = string.Empty; + try + { + active = b.Active(); + (detected, reason) = b.Detect(); + } + catch (Exception ex) { reason = "check failed: " + ex.Message; } + list.Add(new ServerState(b.Id, b.Name, active, detected, ServerForceStore.Get(b.Id), true, reason)); + } + + string host = ServerInfo.LaunchHost; + string? world = AccountHooks.AnnouncedWorldName; + foreach (SectionManifest m in manifests) + foreach (SectionServerDecl d in m.Servers) + { + if (IsBuiltInServer(d.Id) || list.Exists(s => s.Id.Equals(d.Id, StringComparison.OrdinalIgnoreCase))) continue; + bool detected = SectionCatalog.DetectDeclared(d, host, world, out string reason); + ServerForce force = ServerForceStore.Get(d.Id); + list.Add(new ServerState(d.Id, d.Name, ServerForceText.Apply(force, detected), detected, force, false, + $"{reason} (declared by {m.Plugin})")); + } + return list; + } + + /// <summary>PluginManager's skipped server plugins, as the pure list NotLoadedServers takes.</summary> + private static List<NotLoadedServer> NotLoadedServerPlugins() + { + IReadOnlyList<Plugins.SkippedServerPlugin> skipped = Plugins.PluginManager.SkippedServerPlugins; + var list = new List<NotLoadedServer>(skipped.Count); + foreach (Plugins.SkippedServerPlugin s in skipped) + list.Add(new NotLoadedServer(SectionManifestParser.Id(s.ServerId), s.ServerName, s.PluginName, s.Manifest.Server!.WorldNames.ToArray())); + return list; + } + + /// <summary>A compact text of what the menus and the rail show, to detect a change.</summary> + private static string Signature(List<ServerState> servers, List<SectionView> sections) + { + var sb = new System.Text.StringBuilder(256); + foreach (ServerState s in servers) + sb.Append(s.Id).Append(s.Active ? '+' : '-').Append((int)s.Force).Append(';'); + foreach (SectionView v in sections) + { + sb.Append('|').Append(v.Id).Append(':'); + foreach (SectionPane p in v.Panes) + sb.Append(p.Title).Append(p.Contribution?.Enabled == false ? '0' : '1').Append('/'); + foreach (SectionGroup g in v.Groups) + foreach (SectionContribution c in g.Items) + sb.Append(',').Append(c.Label).Append(c.Enabled ? '1' : '0'); + } + return sb.ToString(); + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerForce.cs b/src/RynthCore.Engine/UI/Sections/ServerForce.cs new file mode 100644 index 0000000..5630c87 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerForce.cs @@ -0,0 +1,134 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerForce.cs +// The per-character server override: Auto (detect), On (treat this world as +// the server) or Off (never treat it as the server), one per server id. +// +// Pure (no AC, no engine state, no I/O): the offline tests (tools/SectionsTests) +// compile this file as is. ServerForceStore.cs holds the loaded file and saves it. +// +// File (server_force.txt, one line per override, tab-separated): +// <character key> \t <server id> \t on|off +// Auto is the absence of a line. Blank lines and lines starting with '#' are +// skipped; a malformed line is dropped, never thrown. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Engine.UI.Sections; + +/// <summary>How a server's detection is overridden for one character.</summary> +internal enum ServerForce +{ + /// <summary>Detect it (launch host, announced world name, the configured lists).</summary> + Auto, + /// <summary>Treat this world as the server, whatever detection says.</summary> + On, + /// <summary>Never treat this world as the server.</summary> + Off, +} + +internal static class ServerForceText +{ + /// <summary>"on" / "off" / "auto" (and the older /rc words) to a mode; false for anything else.</summary> + public static bool TryParse(string? text, out ServerForce mode) + { + switch ((text ?? string.Empty).Trim().ToLowerInvariant()) + { + case "auto": case "detect": mode = ServerForce.Auto; return true; + case "on": case "force": case "yes": case "true": mode = ServerForce.On; return true; + case "off": case "never": case "no": case "false": mode = ServerForce.Off; return true; + default: mode = ServerForce.Auto; return false; + } + } + + public static string Name(ServerForce mode) => mode switch + { + ServerForce.On => "on", + ServerForce.Off => "off", + _ => "auto", + }; + + /// <summary>Applies an override to a detected verdict.</summary> + public static bool Apply(ServerForce mode, bool detected) => mode switch + { + ServerForce.On => true, + ServerForce.Off => false, + _ => detected, + }; +} + +/// <summary>server_force.txt contents: character key -> server id -> On / Off. Not thread-safe (the store locks).</summary> +internal sealed class ServerForceFile +{ + /// <summary>Longest character key or server id kept (anything longer is a damaged line).</summary> + public const int MaxFieldLength = 128; + + private readonly Dictionary<string, Dictionary<string, ServerForce>> _byCharacter = + new(StringComparer.OrdinalIgnoreCase); + + /// <summary>The character's override for <paramref name="serverId"/> (Auto when none).</summary> + public ServerForce Get(string characterKey, string serverId) + => _byCharacter.TryGetValue(characterKey, out var map) && map.TryGetValue(serverId, out ServerForce m) ? m : ServerForce.Auto; + + /// <summary>Every override saved for the character (a copy).</summary> + public Dictionary<string, ServerForce> For(string characterKey) + => _byCharacter.TryGetValue(characterKey, out var map) + ? new Dictionary<string, ServerForce>(map, StringComparer.OrdinalIgnoreCase) + : new Dictionary<string, ServerForce>(StringComparer.OrdinalIgnoreCase); + + /// <summary>Sets (or with Auto, removes) one override. True when the contents changed.</summary> + public bool Set(string characterKey, string serverId, ServerForce mode) + { + if (!ValidField(characterKey) || !ValidField(serverId)) return false; + if (mode == ServerForce.Auto) + { + if (!_byCharacter.TryGetValue(characterKey, out var existing) || !existing.Remove(serverId)) return false; + if (existing.Count == 0) _byCharacter.Remove(characterKey); + return true; + } + if (!_byCharacter.TryGetValue(characterKey, out var map)) + _byCharacter[characterKey] = map = new Dictionary<string, ServerForce>(StringComparer.OrdinalIgnoreCase); + if (map.TryGetValue(serverId, out ServerForce old) && old == mode) return false; + map[serverId] = mode; + return true; + } + + public static ServerForceFile Parse(IEnumerable<string>? lines) + { + var file = new ServerForceFile(); + if (lines == null) return file; + foreach (string raw in lines) + { + if (string.IsNullOrWhiteSpace(raw)) continue; + string line = raw.TrimEnd('\r', '\n'); + if (line.TrimStart().StartsWith('#')) continue; + string[] f = line.Split('\t'); + if (f.Length < 3) continue; + string key = f[0].Trim(), server = f[1].Trim(); + if (!ServerForceText.TryParse(f[2], out ServerForce mode) || mode == ServerForce.Auto) continue; + file.Set(key, server, mode); + } + return file; + } + + public string Write() + { + var sb = new StringBuilder(); + sb.Append("# RynthCore per-character server overrides: character key, server id, on|off (auto = no line).\n"); + foreach (var (key, map) in _byCharacter) + foreach (var (server, mode) in map) + sb.Append(key).Append('\t').Append(server).Append('\t').Append(ServerForceText.Name(mode)).Append('\n'); + return sb.ToString(); + } + + /// <summary>No tab or line break (the file's separators), not empty, not overlong.</summary> + private static bool ValidField(string? text) + { + if (string.IsNullOrWhiteSpace(text) || text.Length > MaxFieldLength) return false; + foreach (char c in text) + if (c is '\t' or '\n' or '\r') return false; + return true; + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerForceStore.cs b/src/RynthCore.Engine/UI/Sections/ServerForceStore.cs new file mode 100644 index 0000000..7f732c3 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerForceStore.cs @@ -0,0 +1,160 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerForceStore.cs +// server_force.txt: each character's Auto / On / Off override per server +// (ServerForce.cs has the format). IltInfo and ServerInfo read their override +// here, so "/rc ilt on", "/rc server aelrynth" and the Mini Remote's Char +// section all set the same saved value. +// +// Before a character is logged in there is no key to save under: an override +// set then holds for this session only (until a character logs in). +// +// Threads: reads from any thread are a volatile snapshot (a lock only when the +// character changes); a change locks briefly and queues the save on +// UiBackgroundWriter, never AC's render thread. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.UI.Sections; + +internal static class ServerForceStore +{ + private static readonly object Sync = new(); + private static ServerForceFile _file = new(); // under Sync + private static readonly Dictionary<string, ServerForce> Session = // under Sync: no character yet + new(StringComparer.OrdinalIgnoreCase); + private static volatile bool _loaded; + private static bool _loadQueued; + + private sealed record Snap(string Key, Dictionary<string, ServerForce> Map); + private static Snap? _snap; + + /// <summary>Bumped on every change, so callers can re-read cheaply.</summary> + private static int _version; + public static int Version => Volatile.Read(ref _version); + + private static string FilePath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "server_force.txt"); + + /// <summary>A character is logged in: overrides are saved for it.</summary> + public static bool HasCharacter => SessionStateRegistry.LastCharacterName.Length > 0; + + private static string CharacterKey => + D3D9.VideoPatchPolicy.CharacterKey(SessionStateRegistry.LastServerName, SessionStateRegistry.LastCharacterName); + + /// <summary>Queues the one-time read off the calling thread. Any thread; cheap after the first call.</summary> + public static void EnsureLoadQueued() + { + if (_loaded) return; + lock (Sync) + { + if (_loadQueued) return; + _loadQueued = true; + } + UiBackgroundWriter.Enqueue("server overrides (load)", LoadNow); + } + + private static void LoadNow() + { + ServerForceFile file; + try + { + string path = FilePath; + file = File.Exists(path) ? ServerForceFile.Parse(File.ReadAllLines(path)) : new ServerForceFile(); + } + catch (Exception ex) + { + RynthLog.UI($"ServerForce: reading server_force.txt failed - {ex.GetType().Name}: {ex.Message}"); + file = new ServerForceFile(); + } + lock (Sync) + { + _file = file; + Volatile.Write(ref _snap, null); + _loaded = true; + } + Interlocked.Increment(ref _version); + } + + /// <summary> + /// The override for <paramref name="serverId"/>: the logged-in character's saved one, or + /// before login the session's. Auto until the file is read. Any thread. + /// </summary> + public static ServerForce Get(string serverId) + { + EnsureLoadQueued(); + if (!HasCharacter) + { + lock (Sync) return Session.TryGetValue(serverId, out ServerForce m) ? m : ServerForce.Auto; + } + if (!_loaded) return ServerForce.Auto; + string key = CharacterKey; + Snap? s = Volatile.Read(ref _snap); + if (s == null || !string.Equals(s.Key, key, StringComparison.OrdinalIgnoreCase)) + { + lock (Sync) + { + s = new Snap(key, _file.For(key)); + Volatile.Write(ref _snap, s); + } + } + return s.Map.TryGetValue(serverId, out ServerForce mode) ? mode : ServerForce.Auto; + } + + /// <summary> + /// Sets the override. Saved for the logged-in character; before login it holds for this + /// session. False (with the reason) before the file is read. Any thread. + /// </summary> + public static bool Set(string serverId, ServerForce mode, out string where) + { + EnsureLoadQueued(); + if (!HasCharacter) + { + lock (Sync) + { + if (mode == ServerForce.Auto) Session.Remove(serverId); + else Session[serverId] = mode; + } + Interlocked.Increment(ref _version); + where = "this session (log in a character to save it for that character)"; + return true; + } + if (!_loaded) { where = "not yet: still reading the saved overrides, try again in a moment"; return false; } + + string key = CharacterKey; + string? text = null; + lock (Sync) + { + if (_file.Set(key, serverId, mode)) + { + Volatile.Write(ref _snap, new Snap(key, _file.For(key))); + text = _file.Write(); + } + } + Interlocked.Increment(ref _version); + if (text != null) UiBackgroundWriter.Enqueue("server overrides", () => SaveNow(text)); + where = "saved for " + SessionStateRegistry.LastCharacterName; + return true; + } + + private static void SaveNow(string text) + { + try + { + string path = FilePath; + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + string tmp = path + ".tmp"; + File.WriteAllText(tmp, text); + File.Move(tmp, path, overwrite: true); + } + catch (Exception ex) + { + RynthLog.UI($"ServerForce: writing server_force.txt failed - {ex.GetType().Name}: {ex.Message}"); + } + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerSelection.cs b/src/RynthCore.Engine/UI/Sections/ServerSelection.cs new file mode 100644 index 0000000..e6f6953 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerSelection.cs @@ -0,0 +1,131 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerSelection.cs +// "Which server is this?" as one choice, on top of the per-server overrides +// (ServerForce): the Diagnostics page's server picker and "/rc server pick". +// +// pick <id> that server forced On, every other server forced Off, so +// exactly one server is active whatever detection says; +// pick auto every override back to Auto (detection decides again). +// +// Also the questions every reader of the server list asks the same way: which +// server is the active one, and which plugin owns a server (the one plugins +// ask for its settings, RynthServerPack's "RynthServer.Profile"). +// +// Pure (no AC, no engine state, no I/O): tools/SectionsTests compiles it. +// ServerSelectionStore.cs applies a plan to ServerForceStore. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Sections; + +internal static class ServerSelection +{ + /// <summary>The pick that hands the choice back to detection.</summary> + public const string Auto = "auto"; + + /// <summary> + /// The override each server gets for <paramref name="pick"/>: Auto for all with + /// <see cref="Auto"/> (or ""), else On for the picked id and Off for the rest. Null when the + /// pick names no server in <paramref name="servers"/>. + /// </summary> + public static List<(string Id, ServerForce Force)>? Plan(IReadOnlyList<ServerState> servers, string? pick) + { + string id = (pick ?? string.Empty).Trim(); + bool auto = id.Length == 0 || id.Equals(Auto, StringComparison.OrdinalIgnoreCase); + if (!auto && Find(servers, id) == null) return null; + + var plan = new List<(string, ServerForce)>(servers.Count); + foreach (ServerState s in servers) + { + ServerForce force = auto ? ServerForce.Auto + : s.Id.Equals(id, StringComparison.OrdinalIgnoreCase) ? ServerForce.On : ServerForce.Off; + plan.Add((s.Id, force)); + } + return plan; + } + + /// <summary> + /// The current pick: <see cref="Auto"/> when no override is set, a server id when exactly that + /// server is forced On and none other is On, or null for any other mix (overrides set one by + /// one with "/rc server <id> on|off"). + /// </summary> + public static string? CurrentPick(IReadOnlyList<ServerState> servers) + { + string? on = null; + bool anyForced = false; + foreach (ServerState s in servers) + { + if (s.Force == ServerForce.Auto) continue; + anyForced = true; + if (s.Force != ServerForce.On) continue; + if (on != null) return null; + on = s.Id; + } + if (!anyForced) return Auto; + if (on == null) return null; + // A pick forces every other server Off; one left on Auto is a hand-made mix. + foreach (ServerState s in servers) + if (!s.Id.Equals(on, StringComparison.OrdinalIgnoreCase) && s.Force == ServerForce.Auto) return null; + return on; + } + + /// <summary> + /// The server this world counts as: the first active one forced On (an override beats + /// detection), else the first active one (built-in servers come first). Null when none is. + /// </summary> + public static ServerState? ActiveServer(IReadOnlyList<ServerState> servers) + { + ServerState? first = null; + foreach (ServerState s in servers) + { + if (!s.Active) continue; + if (s.Force == ServerForce.On) return s; + first ??= s; + } + return first; + } + + /// <summary> + /// The plugin that owns <paramref name="serverId"/>: the first manifest that declares it, else + /// the plugin with the most contributions for it (RynthILT for the built-in "ilt"; ties go to + /// the name that sorts first). "" when no plugin has anything for it. <paramref name="enginePlugin"/> + /// (the engine's own manifest) never owns a server. + /// </summary> + public static string OwnerPlugin(IReadOnlyList<SectionManifest> manifests, string serverId, string enginePlugin) + { + foreach (SectionManifest m in manifests) + { + if (IsEngine(m, enginePlugin)) continue; + foreach (SectionServerDecl d in m.Servers) + if (d.Id.Equals(serverId, StringComparison.OrdinalIgnoreCase)) return m.Plugin; + } + + string best = string.Empty; + int bestCount = 0; + foreach (SectionManifest m in manifests) + { + if (IsEngine(m, enginePlugin)) continue; + int n = 0; + foreach (SectionContribution c in m.Contributions) + if (c.Server.Equals(serverId, StringComparison.OrdinalIgnoreCase)) n++; + if (n > bestCount || (n == bestCount && n > 0 && string.Compare(m.Plugin, best, StringComparison.OrdinalIgnoreCase) < 0)) + { + best = m.Plugin; + bestCount = n; + } + } + return best; + } + + private static bool IsEngine(SectionManifest m, string enginePlugin) + => m.Plugin.Length == 0 || m.Plugin.Equals(enginePlugin, StringComparison.OrdinalIgnoreCase); + + private static ServerState? Find(IReadOnlyList<ServerState> servers, string id) + { + foreach (ServerState s in servers) + if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s; + return null; + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerSelectionStore.cs b/src/RynthCore.Engine/UI/Sections/ServerSelectionStore.cs new file mode 100644 index 0000000..20930b7 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerSelectionStore.cs @@ -0,0 +1,53 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerSelectionStore.cs +// Applies a server pick (ServerSelection.Plan) to the saved per-character +// overrides (ServerForceStore) and rebuilds the verdicts, so the menus, the +// "servermenu" push and plugin API v86 (GetServerStateJson) follow at once. +// Used by the Diagnostics page's server picker and "/rc server pick". +// +// Threads: any (ServerForceStore locks; the rebuild runs on the next frame). +// ============================================================================ + +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Sections; + +internal static class ServerSelectionStore +{ + /// <summary> + /// Picks <paramref name="pick"/> (a server id, or <see cref="ServerSelection.Auto"/>). + /// <paramref name="message"/> says what happened, for chat. False when the pick names no + /// known server or an override couldn't be saved. + /// </summary> + public static bool Apply(string? pick, out string message) + { + IReadOnlyList<ServerState> servers = SectionRegistry.Current.Servers; + List<(string Id, ServerForce Force)>? plan = ServerSelection.Plan(servers, pick); + if (plan == null) + { + message = $"No server called '{pick}'. /rc server lists them."; + return false; + } + + string where = string.Empty; + foreach ((string id, ServerForce force) in plan) + { + if (ServerForceStore.Get(id) == force) continue; + if (!ServerForceStore.Set(id, force, out where)) + { + message = $"Server pick not saved: {where}."; + SectionRegistry.Invalidate(); + return false; + } + } + SectionRegistry.Invalidate(); + + bool auto = string.IsNullOrWhiteSpace(pick) || pick.Trim().Equals(ServerSelection.Auto, System.StringComparison.OrdinalIgnoreCase); + string saved = where.Length > 0 ? $" ({where})" : string.Empty; + message = auto + ? "Server: detected again (every override back to auto)" + saved + "." + : $"Server: '{pick!.Trim()}' picked for this character; every other server off" + saved + "."; + RynthLog.Milestone("ServerSelection: " + message); + return true; + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerStateJson.cs b/src/RynthCore.Engine/UI/Sections/ServerStateJson.cs new file mode 100644 index 0000000..fcf1125 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerStateJson.cs @@ -0,0 +1,89 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerStateJson.cs +// The server list as JSON for plugins (plugin API v86, GetServerStateJson): +// one answer to "which server is this, and which plugin has its settings", +// the same verdicts the Mini Remote, the menus and the "servermenu" push use. +// +// { +// "schema": 1, "revision": 12, +// "host": "infiniteleaftide.online", "world": "InfiniteLeaftide", +// "pick": "auto" | "<id>" | "mixed", +// "active": "ilt", "activeName": "Infinite Leaftide", "activePlugin": "RynthILT", +// "servers": [ { "id", "name", "active", "detected", "force": "auto|on|off", +// "builtIn", "plugin", "reason" }, ... ] +// } +// "world" is what the server announced at login ("" before, or when the hook +// isn't there); "active" is "" when no server is active (a retail-like world). +// "plugin" is the server's owner (ServerSelection.OwnerPlugin): the plugin to +// ask for the server's settings ("RynthServer.Profile", or RynthILT's +// "RynthILT.Server"); "" when none is loaded. +// +// Pure (BCL only): tools/SectionsTests compiles it. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Engine.UI.Sections; + +internal static class ServerStateJson +{ + public const int Schema = 1; + + /// <summary>The JSON for <paramref name="servers"/> (from <paramref name="manifests"/>), UTF-8 text.</summary> + public static string Build(IReadOnlyList<ServerState> servers, IReadOnlyList<SectionManifest> manifests, + int revision, string? host, string? world, string enginePlugin) + { + ServerState? active = ServerSelection.ActiveServer(servers); + string pick = ServerSelection.CurrentPick(servers) ?? "mixed"; + + using var stream = new MemoryStream(512); + using (var w = new Utf8JsonWriter(stream)) + { + w.WriteStartObject(); + w.WriteNumber("schema", Schema); + w.WriteNumber("revision", revision); + w.WriteString("host", host ?? string.Empty); + w.WriteString("world", world ?? string.Empty); + w.WriteString("pick", pick); + w.WriteString("active", active?.Id ?? string.Empty); + w.WriteString("activeName", active?.Name ?? string.Empty); + w.WriteString("activePlugin", active == null ? string.Empty : ServerSelection.OwnerPlugin(manifests, active.Id, enginePlugin)); + w.WriteStartArray("servers"); + foreach (ServerState s in servers) + { + w.WriteStartObject(); + w.WriteString("id", s.Id); + w.WriteString("name", s.Name); + w.WriteBoolean("active", s.Active); + w.WriteBoolean("detected", s.Detected); + w.WriteString("force", ServerForceText.Name(s.Force)); + w.WriteBoolean("builtIn", s.BuiltIn); + w.WriteString("plugin", ServerSelection.OwnerPlugin(manifests, s.Id, enginePlugin)); + w.WriteString("reason", s.Reason ?? string.Empty); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(stream.ToArray()); + } + + /// <summary> + /// Copies <paramref name="json"/> as NUL-terminated UTF-8 into the caller's buffer when it + /// fits and returns its byte length either way (length >= capacity: too small, nothing + /// written). The plugin API's convention for text it hands out. + /// </summary> + public static unsafe int Write(string json, byte* buffer, int capacity) + { + int length = Encoding.UTF8.GetByteCount(json); + if (buffer == null || capacity <= length) return length; + fixed (char* src = json) + Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity); + buffer[length] = 0; + return length; + } +} diff --git a/src/RynthCore.Engine/UI/ServerMenus.cs b/src/RynthCore.Engine/UI/ServerMenus.cs index 1a36385..9fe75a9 100644 --- a/src/RynthCore.Engine/UI/ServerMenus.cs +++ b/src/RynthCore.Engine/UI/ServerMenus.cs @@ -1,164 +1,213 @@ // ============================================================================ // RynthCore.Engine - UI/ServerMenus.cs -// Server sections: the bottom half of the RynthAi dashboard's Char menu and of -// the Mini Remote's right-click menu (the top half, "Character", is the -// windows every server has). +// The servers and sections, as menus: the bottom half of the RynthAi +// dashboard's Char menu and of the Mini Remote's right-click menu (the top +// half, "Character", is the windows every server has), and the "servermenu" +// push that gives RynthAi the same list for its own menus. // -// A server (Infinite Leaftide today) is defined once: how to tell the client -// is on it, and the command that forces it. Each installed plugin with windows -// for that server adds its items (EntryPoint, by which plugin DLLs exist). A -// section shows only while its server is detected or forced, and only with at -// least one item, so it appears exactly when you are on that server with one -// of its plugins installed. A new server or server plugin is one DefineServer -// plus its AddItem calls; neither menu changes. +// Everything comes from UI/Sections/SectionRegistry: the servers (built in or +// declared by a plugin), whether each is active (detected or forced for this +// character), and what the engine and the installed plugins add for each. A +// server's group shows only while it is active and has items. // -// Items are "/rc" chat commands: the engine runs them itself -// (RynthCoreChatCommands) and RynthAi runs them through InvokeChatParser. -// RynthAi learns the sections from the "servermenu" remote command this file -// pushes (Tick: when they change, and every ResendMs in case it missed one). -// Payload: one line per section ("S", id, name, active 0/1, force command) -// followed by its items ("I", label, command, tooltip, feature), tab-separated. +// Items run "/rc" commands through the engine's dispatcher (any other command +// goes through the chat dispatcher, as if typed); a plugin surface opens its +// section in the Mini Remote ("/rc miniremote section <id>"). +// +// Push (Tick: when it changes, and every ResendMs in case RynthAi missed one), +// tab-separated lines: +// V id name active 0/1 force auto|on|off detected 0/1 reason every server +// X id label every section, rail order +// S id name active 0/1 force command a server with items +// I label command tooltip feature its items +// N id pattern default|engine.json a server's world names +// RynthAi 0.5.54 and older read only S and I (unknown kinds and extra fields are +// skipped); a "section:<id>" feature is a surface it may show in its own Mini Remote. +// RynthILT (0.1.1+) gets the same push for its copy of the ILT settings (V and N), +// and so does every server plugin whose sections manifest declares a server +// (RynthColdeve, RynthAelrynth, ...: their server card's verdict and override). // ============================================================================ using System; using System.Collections.Generic; using System.Text; using RynthCore.Engine.UI.Data; +using RynthCore.Engine.UI.Sections; namespace RynthCore.Engine.UI; -/// <summary> -/// One menu item of a server section. <paramref name="Feature"/> is an optional key RynthAi -/// checks before enabling it ("tab:quests": that Mini Remote tab is available). -/// </summary> -internal sealed record ServerMenuItem(string Label, string Command, string Tooltip, string Feature = ""); - -/// <summary>A server's menu section: detection, force command and the installed plugins' items.</summary> -internal sealed class ServerMenuSection -{ - public ServerMenuSection(string id, string name, Func<bool> isActive, string forceCommand) - { - Id = id; - Name = name; - IsActiveFn = isActive; - ForceCommand = forceCommand; - } - - public string Id { get; } - public string Name { get; } - public string ForceCommand { get; } - internal Func<bool> IsActiveFn { get; } - internal List<ServerMenuItem> ItemList { get; } = new(); - public IReadOnlyList<ServerMenuItem> Items => ItemList; - - /// <summary>On this server (detected or forced). A failing check counts as not active.</summary> - public bool IsActive - { - get - { - try { return IsActiveFn(); } - catch { return false; } - } - } -} - internal static class ServerMenus { - /// <summary>How often RynthAi gets the sections again even when nothing changed.</summary> + /// <summary>How often RynthAi gets the list again even when nothing changed.</summary> private const long ResendMs = 30_000; /// <summary>How often the payload is rebuilt to look for a change.</summary> private const long CheckMs = 1_000; - private static readonly object Gate = new(); - private static readonly List<ServerMenuSection> Defined = new(); - // Copy-on-write view for the render thread (definitions only change during engine init). - private static volatile ServerMenuSection[] _sections = Array.Empty<ServerMenuSection>(); + /// <summary>Feature prefix of an item that is a plugin surface (its section in the Mini Remote).</summary> + public const string SectionFeaturePrefix = "section:"; + + /// <summary>How often RynthILT gets the list again: it may load (or hot-reload) after the last change.</summary> + private const long IltResendMs = 10_000; + + /// <summary>The plugin that keeps a copy of the ILT settings.</summary> + private const string RynthIltPlugin = "RynthILT"; private static long _nextCheckMs; private static long _lastPushMs; private static string _lastPayload = string.Empty; + private static long _lastIltPushMs; + private static string _lastIltPayload = string.Empty; + // Server plugins (sections manifests that declare a server): the last payload each took, and when. + private static readonly Dictionary<string, (string Payload, long AtMs)> _serverPluginPushes = new(StringComparer.OrdinalIgnoreCase); - /// <summary>RynthAi is installed: Tick pushes it the sections.</summary> + /// <summary>RynthAi is installed: Tick pushes it the list.</summary> public static bool PushToRynthAi { get; set; } - /// <summary>Every defined server, in definition order (with or without items).</summary> - public static IReadOnlyList<ServerMenuSection> All => _sections; + /// <summary>RynthILT is installed: Tick pushes it the list too (its ILT settings view).</summary> + public static bool PushToRynthIlt { get; set; } + + /// <summary>One menu item: a command, with the section it belongs to.</summary> + internal sealed record MenuItem(string Label, string Command, string Tooltip, string Feature, bool Enabled, string Note); + + /// <summary>A server's items for the menus: every section's, surfaces as "open the section".</summary> + internal sealed record MenuGroup(ServerState Server, MenuItem[] Items); /// <summary> - /// Defines a server (once; a second call with the same id is ignored). - /// <paramref name="isActive"/> runs on the render thread, so it must be cheap. + /// Runs an item's command: an engine "/rc" command directly, anything else through the + /// chat dispatcher (plugins' commands, as if typed). Render thread. /// </summary> - public static void DefineServer(string id, string name, Func<bool> isActive, string forceCommand) - { - lock (Gate) - { - if (Find(id) != null) return; - Defined.Add(new ServerMenuSection(id, name, isActive, forceCommand)); - _sections = Defined.ToArray(); - } - } - - /// <summary>An installed plugin's window for server <paramref name="serverId"/> (ignored for an unknown server).</summary> - public static void AddItem(string serverId, ServerMenuItem item) - { - lock (Gate) - { - ServerMenuSection? section = Find(serverId); - if (section == null) - { - RynthLog.UI($"ServerMenus: item '{item.Label}' names unknown server '{serverId}'; ignored."); - return; - } - section.ItemList.Add(item); - _sections = Defined.ToArray(); - } - } - - private static ServerMenuSection? Find(string id) - { - foreach (ServerMenuSection s in Defined) - if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s; - return null; - } - - /// <summary>Runs an item's command through the engine's /rc dispatcher.</summary> public static void Run(string command) { - if (!Compatibility.RynthCoreChatCommands.TryHandle(command)) - RynthLog.UI($"ServerMenus: '{command}' is not an engine command."); + string cmd = SectionManifestParser.Command(command); + if (cmd.Length == 0) return; + if (Compatibility.RynthCoreChatCommands.TryHandle(cmd)) return; + if (cmd.StartsWith("/rc ", StringComparison.OrdinalIgnoreCase)) + { + RynthLog.UI($"ServerMenus: '{cmd}' is not an engine command."); + return; + } + Compatibility.ChatCommandDispatcher.Dispatch(cmd); + } + + /// <summary>The command that opens section <paramref name="sectionId"/> in the Mini Remote.</summary> + public static string OpenSectionCommand(string sectionId) => "/rc miniremote section " + sectionId; + + /// <summary>The command that forces <paramref name="serverId"/> on for this character.</summary> + public static string ForceCommand(string serverId) => "/rc server " + serverId + " on"; + + /// <summary>Every server that has items (active or not), with them. Any thread.</summary> + public static List<MenuGroup> Groups(SectionRegistry.Snapshot snap) + { + var byServer = new Dictionary<string, List<MenuItem>>(StringComparer.OrdinalIgnoreCase); + foreach (SectionManifest m in snap.Manifests) + foreach (SectionContribution c in m.Contributions) + { + if (c.IsUniversal) continue; + if (!byServer.TryGetValue(c.Server, out var list)) byServer[c.Server] = list = new List<MenuItem>(); + list.Add(c.IsSurface + ? new MenuItem(c.Label, OpenSectionCommand(c.Section), c.Tooltip, SectionFeaturePrefix + c.Section, c.Enabled, c.Note) + : new MenuItem(c.Label, c.Command, c.Tooltip, string.Empty, c.Enabled, c.Note)); + } + var groups = new List<MenuGroup>(); + foreach (ServerState s in snap.Servers) + if (byServer.TryGetValue(s.Id, out var items)) + groups.Add(new MenuGroup(s, items.ToArray())); + return groups; } // ── RynthAi push ─────────────────────────────────────────────────── /// <summary> - /// Render thread, every frame: sends RynthAi the sections when they changed (a server - /// detected or forced, or not any more) and every <see cref="ResendMs"/>. + /// Render thread, every frame: sends RynthAi the list when it changed (a server + /// detected or forced, or not any more; a plugin's sections) and every <see cref="ResendMs"/>. /// </summary> public static void Tick() { - if (!PushToRynthAi) return; + SectionRegistry.Tick(); // the server verdicts (GetServerStateJson) and late server-plugin loads + SectionRegistry.Snapshot snap = SectionRegistry.Current; + List<string> serverPlugins = ServerPluginTargets(snap); + if (!PushToRynthAi && !PushToRynthIlt && serverPlugins.Count == 0) return; long now = Environment.TickCount64; if (now < _nextCheckMs) return; _nextCheckMs = now + CheckMs; - string payload = BuildPayload(); - if (payload == _lastPayload && now - _lastPushMs < ResendMs) return; - _lastPayload = payload; - _lastPushMs = now; - RynthAiCommands.ApplyRemoteCommand("servermenu", payload); + string payload = BuildPayload(snap, IltWorldNames()); + // Same resend rule as RynthILT's: a plugin may (re)load after the last change. + foreach (string plugin in serverPlugins) + { + bool due = !_serverPluginPushes.TryGetValue(plugin, out var last) + || last.Payload != payload || now - last.AtMs >= IltResendMs; + if (due && Plugins.PluginManager.SendPluginCommand(plugin, "servermenu", payload)) + _serverPluginPushes[plugin] = (payload, now); + } + if (PushToRynthAi && (payload != _lastPayload || now - _lastPushMs >= ResendMs)) + { + _lastPayload = payload; + _lastPushMs = now; + RynthAiCommands.ApplyRemoteCommand("servermenu", payload); + } + // Not delivered (RynthILT not loaded yet, or an older one without the export): try again next check. + if (PushToRynthIlt && (payload != _lastIltPayload || now - _lastIltPushMs >= IltResendMs) + && Plugins.PluginManager.SendPluginCommand(RynthIltPlugin, "servermenu", payload)) + { + _lastIltPayload = payload; + _lastIltPushMs = now; + } } - private static string BuildPayload() + /// <summary> + /// The plugins to push to besides RynthAi and RynthILT (they have their own paths): each one + /// whose sections manifest declares a server. Pure apart from reading <paramref name="snap"/>. + /// </summary> + internal static List<string> ServerPluginTargets(SectionRegistry.Snapshot snap) { - var sb = new StringBuilder(256); - foreach (ServerMenuSection s in _sections) + var list = new List<string>(); + foreach (SectionManifest m in snap.Manifests) { - if (s.Items.Count == 0) continue; // no plugin for it is installed - sb.Append('S').Append('\t').Append(Clean(s.Id)).Append('\t').Append(Clean(s.Name)).Append('\t') - .Append(s.IsActive ? '1' : '0').Append('\t').Append(Clean(s.ForceCommand)).Append('\n'); - foreach (ServerMenuItem i in s.Items) + if (m.Servers.Length == 0 || m.Plugin.Length == 0) continue; + if (m.Plugin.Equals("RynthAi", StringComparison.OrdinalIgnoreCase) + || (PushToRynthIlt && m.Plugin.Equals(RynthIltPlugin, StringComparison.OrdinalIgnoreCase))) + continue; + if (!list.Exists(p => p.Equals(m.Plugin, StringComparison.OrdinalIgnoreCase))) list.Add(m.Plugin); + } + return list; + } + + /// <summary>The ILT world-name patterns in force, and whether they are the built-in defaults.</summary> + private static (string Server, string Pattern, bool Default)[] IltWorldNames() + { + IReadOnlyList<string>? names = Plugins.EngineSettings.IltServerNames; + IReadOnlyList<string> list = names ?? Compatibility.IltDetect.DefaultServerNames; + var result = new (string, string, bool)[list.Count]; + for (int i = 0; i < list.Count; i++) result[i] = ("ilt", list[i], names == null); + return result; + } + + /// <summary> + /// The push text for <paramref name="snap"/> and the servers' <paramref name="worldNames"/>. + /// Pure apart from reading them. + /// </summary> + internal static string BuildPayload(SectionRegistry.Snapshot snap, + IReadOnlyList<(string Server, string Pattern, bool Default)>? worldNames = null) + { + var sb = new StringBuilder(512); + foreach (ServerState s in snap.Servers) + sb.Append('V').Append('\t').Append(Clean(s.Id)).Append('\t').Append(Clean(s.Name)).Append('\t') + .Append(s.Active ? '1' : '0').Append('\t').Append(ServerForceText.Name(s.Force)).Append('\t') + .Append(s.Detected ? '1' : '0').Append('\t').Append(Clean(s.Reason ?? string.Empty)).Append('\n'); + if (worldNames != null) + foreach (var n in worldNames) + sb.Append('N').Append('\t').Append(Clean(n.Server)).Append('\t').Append(Clean(n.Pattern)).Append('\t') + .Append(n.Default ? "default" : "engine.json").Append('\n'); + foreach (SectionView v in snap.Sections) + sb.Append('X').Append('\t').Append(Clean(v.Id)).Append('\t').Append(Clean(v.Label)).Append('\n'); + foreach (MenuGroup g in Groups(snap)) + { + sb.Append('S').Append('\t').Append(Clean(g.Server.Id)).Append('\t').Append(Clean(g.Server.Name)).Append('\t') + .Append(g.Server.Active ? '1' : '0').Append('\t').Append(Clean(ForceCommand(g.Server.Id))).Append('\n'); + foreach (MenuItem i in g.Items) sb.Append('I').Append('\t').Append(Clean(i.Label)).Append('\t').Append(Clean(i.Command)).Append('\t') - .Append(Clean(i.Tooltip)).Append('\t').Append(Clean(i.Feature)).Append('\n'); + .Append(Clean(i.Note.Length > 0 && !i.Enabled ? i.Note : i.Tooltip)).Append('\t').Append(Clean(i.Feature)).Append('\n'); } return sb.ToString(); } @@ -172,43 +221,64 @@ internal static class ServerMenus return sb.ToString(); } - // ── ImGui menu ───────────────────────────────────────────────────── + // ── ImGui menus ──────────────────────────────────────────────────── /// <summary> - /// The server half of an ImGui popup menu: each active section's name and items. With - /// sections installed but none active, a note and one "Treat this world as ..." item per - /// installed server. Draws nothing (not even <paramref name="separatorFirst"/>'s separator) - /// when no server plugin is installed. Returns true when it drew something. + /// The server half of an ImGui popup menu: each active server's name and items. With + /// servers that have items but none active, a note and one "Treat this world as ..." item + /// each (saved for this character). Draws nothing (not even <paramref name="separatorFirst"/>'s + /// separator) when no server has items. Returns true when it drew something. /// </summary> public static bool DrawImGuiMenu(bool separatorFirst = false) { - ServerMenuSection[] sections = _sections; - bool any = false, installed = false; - foreach (ServerMenuSection s in sections) + List<MenuGroup> groups = Groups(SectionRegistry.Current); + if (groups.Count == 0) return false; + if (separatorFirst) ImGuiNET.ImGui.Separator(); + + bool any = false; + foreach (MenuGroup g in groups) { - if (s.Items.Count == 0) continue; - if (!installed && separatorFirst) ImGuiNET.ImGui.Separator(); - installed = true; - if (!s.IsActive) continue; + if (!g.Server.Active) continue; any = true; - ImGuiNET.ImGui.TextDisabled("Server: " + s.Name); - foreach (ServerMenuItem item in s.Items) + SafeImGui.TextDisabled("Server: " + g.Server.Name); + foreach (MenuItem item in g.Items) { - if (ImGuiNET.ImGui.MenuItem(item.Label + "##srv_" + s.Id, item.Command)) + if (ImGuiNET.ImGui.MenuItem(item.Label + "##srv_" + g.Server.Id + "_" + item.Command, "", false, item.Enabled)) Run(item.Command); - if (item.Tooltip.Length > 0) ImGuiNET.ImGui.SetItemTooltip(item.Tooltip); + string tip = item.Enabled || item.Note.Length == 0 ? item.Tooltip : item.Note; + if (tip.Length > 0) SafeImGui.SetItemTooltip(tip); } } - if (any || !installed) return any; + if (any) return true; ImGuiNET.ImGui.TextDisabled("Server: no installed server plugin matches this world"); - foreach (ServerMenuSection s in sections) + foreach (MenuGroup g in groups) { - if (s.Items.Count == 0 || s.ForceCommand.Length == 0) continue; - if (ImGuiNET.ImGui.MenuItem("Treat this world as " + s.Name + "##srvforce_" + s.Id, s.ForceCommand)) - Run(s.ForceCommand); - ImGuiNET.ImGui.SetItemTooltip("For this session only (testing); the world check goes back to automatic on restart."); + if (ImGuiNET.ImGui.MenuItem("Treat this world as " + g.Server.Name + "##srvforce_" + g.Server.Id)) + Run(ForceCommand(g.Server.Id)); + SafeImGui.SetItemTooltip("Saved for this character. Undo with /rc server " + g.Server.Id + " auto, or in the Mini Remote's Char section."); } return true; } + + /// <summary> + /// A "Sections" submenu: every Mini Remote section, opening it there. Returns true when + /// one was picked. + /// </summary> + public static bool DrawSectionsMenu(string label = "Sections") + { + SectionRegistry.Snapshot snap = SectionRegistry.Current; + if (snap.Sections.Count == 0 || !ImGuiNET.ImGui.BeginMenu(label)) return false; + bool picked = false; + foreach (SectionView v in snap.Sections) + { + if (ImGuiNET.ImGui.MenuItem(v.Label + "##sec_" + v.Id, "", false, v.HasContent || v.Core)) + { + Run(OpenSectionCommand(v.Id)); + picked = true; + } + } + ImGuiNET.ImGui.EndMenu(); + return picked; + } } diff --git a/src/RynthCore.Injector/LaunchCommand.cs b/src/RynthCore.Injector/LaunchCommand.cs index f1059f4..0a024c0 100644 --- a/src/RynthCore.Injector/LaunchCommand.cs +++ b/src/RynthCore.Injector/LaunchCommand.cs @@ -253,6 +253,13 @@ internal static class LaunchCommand "Password needs re-entering: edit the account in the launcher and type it again."); return 2; } + if (pwd.Length == 0) + { + // The client refuses an empty password before it connects ("You can only run the + // game from the launcher program") and exits within seconds. + Log($"No password is saved for account '{acct}'. Launch it once from the launcher to enter it, or edit the account."); + return 2; + } string arguments = server.Emulator == EmulatorKind.Gdle ? string.Join(" ", diff --git a/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs b/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs index 868c7bb..951d422 100644 --- a/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs +++ b/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs @@ -29,6 +29,74 @@ public sealed class RynthPluginDependency public bool Optional { get; set; } } +/// <summary> +/// The one game server a server plugin is for (RynthColdeve, RynthILT, ...). The engine loads such a +/// plugin only where the client's connect host is this server's, or where no installed server +/// plugin claims the host (PluginManifestGate). Older engines and launchers ignore it. +/// </summary> +public sealed class RynthPluginServer +{ + /// <summary>Lower-case id, the same one the plugin's Mini Remote sections use ("coldeve", "ilt").</summary> + public string Id { get; set; } = ""; + public string Name { get; set; } = ""; + /// <summary>Connect hosts: a name also matches hosts under it; an IP address matches only itself; '*' wildcards.</summary> + public List<string> Hosts { get; set; } = new(); + /// <summary>World names the server announces ('*' wildcards, case-insensitive).</summary> + public List<string> WorldNames { get; set; } = new(); + + /// <summary> + /// True when <paramref name="host"/> is one of <see cref="Hosts"/>: the same name, a host under + /// it ("game.infiniteleaftide.online" for "infiniteleaftide.online"), or a '*' pattern match. An + /// IP address matches only itself. Case and a trailing dot are ignored (the engine's IltDetect + /// rules, kept BCL-only here for the manifest gate). + /// </summary> + public bool MatchesHost(string? host, out string matched) + { + matched = ""; + if (string.IsNullOrWhiteSpace(host)) return false; + string h = host.Trim().TrimEnd('.').ToLowerInvariant(); + foreach (string raw in Hosts) + { + string p = raw.Trim().TrimEnd('.').ToLowerInvariant(); + if (p.Length == 0) continue; + bool hit = p.Contains('*') + ? Glob(h, p) + : h == p || (!IsIpv4(p) && h.EndsWith("." + p, StringComparison.Ordinal)); + if (!hit) continue; + matched = raw.Trim(); + return true; + } + return false; + } + + private static bool IsIpv4(string text) => + System.Net.IPAddress.TryParse(text, out System.Net.IPAddress? ip) && ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork; + + /// <summary>Case-insensitive match where '*' stands for any run of characters.</summary> + private static bool Glob(string text, string pattern) + { + string[] parts = pattern.Split('*'); + int pos = 0; + for (int i = 0; i < parts.Length; i++) + { + string part = parts[i]; + if (part.Length == 0) continue; + if (i == 0) + { + if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false; + pos = part.Length; + continue; + } + if (i == parts.Length - 1) + return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase); + int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase); + if (at < 0) return false; + pos = at + part.Length; + } + return true; + } +} + /// <summary>A plugin's manifest (schema 1). Unknown JSON fields are ignored, so later schemas can add fields.</summary> public sealed class RynthPluginManifest { @@ -50,6 +118,11 @@ public sealed class RynthPluginManifest public string Description { get; set; } = ""; public string Homepage { get; set; } = ""; public string License { get; set; } = ""; + /// <summary>Set for a server plugin (one game server's features); null for every other plugin.</summary> + public RynthPluginServer? Server { get; set; } + + /// <summary>Most hosts or world names a server block may list (a manifest is read before every load).</summary> + public const int MaxServerPatterns = 16; /// <summary>Parses a manifest; throws <see cref="InvalidDataException"/> with the reason when it isn't one.</summary> public static RynthPluginManifest Parse(string json) @@ -118,10 +191,50 @@ public sealed class RynthPluginManifest m.Dependencies.Add(dep); } } + + if (r.TryGetProperty("server", out JsonElement srv) && srv.ValueKind != JsonValueKind.Null) + m.Server = ParseServer(srv); return m; } } + /// <summary>The "server" block: an object with an id; hosts and worldNames are string arrays.</summary> + private static RynthPluginServer ParseServer(JsonElement srv) + { + if (srv.ValueKind != JsonValueKind.Object) + throw new InvalidDataException("the plugin manifest's server is not an object"); + var s = new RynthPluginServer + { + Id = Str(srv, "id").Trim().ToLowerInvariant(), + Name = Str(srv, "name").Trim(), + }; + if (s.Id.Length == 0 || s.Id.Length > 32) + throw new InvalidDataException("the plugin manifest's server has no id (or one over 32 characters)"); + foreach (char c in s.Id) + if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) + throw new InvalidDataException($"the plugin manifest's server id '{s.Id}' may only have a-z, 0-9 and '-'"); + if (s.Name.Length == 0) s.Name = s.Id; + s.Hosts = Patterns(srv, "hosts"); + s.WorldNames = Patterns(srv, "worldNames"); + return s; + } + + private static List<string> Patterns(JsonElement o, string name) + { + var list = new List<string>(); + if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind == JsonValueKind.Null) return list; + if (a.ValueKind != JsonValueKind.Array) + throw new InvalidDataException($"the plugin manifest's server {name} is not an array"); + foreach (JsonElement e in a.EnumerateArray()) + { + string p = e.ValueKind == JsonValueKind.String ? (e.GetString() ?? "").Trim() : ""; + if (p.Length == 0 || p.Length > 128) continue; + if (list.Count >= MaxServerPatterns) break; + list.Add(p); + } + return list; + } + /// <summary>Parses, or returns null with the reason in <paramref name="error"/>.</summary> public static RynthPluginManifest? TryParse(string json, out string error) { @@ -155,6 +268,19 @@ public sealed class RynthPluginManifest if (Description.Length > 0) w.WriteString("description", Description); if (Homepage.Length > 0) w.WriteString("homepage", Homepage); if (License.Length > 0) w.WriteString("license", License); + if (Server != null) + { + w.WriteStartObject("server"); + w.WriteString("id", Server.Id); + w.WriteString("name", Server.Name); + w.WriteStartArray("hosts"); + foreach (string h in Server.Hosts) w.WriteStringValue(h); + w.WriteEndArray(); + w.WriteStartArray("worldNames"); + foreach (string n in Server.WorldNames) w.WriteStringValue(n); + w.WriteEndArray(); + w.WriteEndObject(); + } w.WriteEndObject(); } return Encoding.UTF8.GetString(ms.ToArray()); diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 6dfa0e0..eb4b39c 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -174,6 +174,11 @@ public struct RynthCoreApiNative public IntPtr RemoveClientObjectFn; // int RemoveClientObject(uint id) -> 1 removed, 2 queued, 0 refused, -1 unbound // v84: every property of an object (/ub propertydump), one record (ObjectProperties.TryParse) public IntPtr GetObjectPropertiesFn; // int GetObjectProperties(uint id, byte* buf, int size) -> record size (copied if <= size), 0 unknown, -1 bad args + // v85: answer the server's yes/no prompt (craft chance) without the client's dialog + public IntPtr ArmConfirmationFn; // int ArmConfirmation(uint type, int minPercent, int timeoutMs) -> 1 armed, 0 unavailable, -3 bad args + public IntPtr GetLastConfirmationFn; // int GetLastConfirmation(uint* type, uint* ctx, int* percent, int* outcome, int* ageMs) -> seq + // v86: which server this is, for every plugin (servers, verdicts, overrides, owning plugins) + public IntPtr GetServerStateJsonFn; // int GetServerStateJson(byte* buffer, int capacity) -> UTF-8 byte length (>= capacity: too small) } /// <summary> diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index c8bf994..9daf715 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -142,6 +142,8 @@ public readonly unsafe struct RynthCoreHost public bool HasGetCharacterTitles => _api.Version >= 75 && _api.GetCharacterTitlesFn != IntPtr.Zero; /// <summary>v75: <see cref="TryGetServerInfo"/> (which server this is).</summary> public bool HasGetServerInfo => _api.Version >= 75 && _api.GetServerInfoFn != IntPtr.Zero; + /// <summary>v86: <see cref="TryGetServerStateJson"/> (the server list for every plugin).</summary> + public bool HasGetServerStateJson => _api.Version >= 86 && _api.GetServerStateJsonFn != IntPtr.Zero; /// <summary>v76: <see cref="CloseContainer"/> (close a corpse or chest like the client's window close).</summary> public bool HasCloseContainer => _api.Version >= 76 && _api.CloseContainerFn != IntPtr.Zero; /// <summary>v77: <see cref="GetScreenMode"/>, <see cref="GetUiHookFlags"/> and the UI callbacks @@ -182,6 +184,8 @@ public readonly unsafe struct RynthCoreHost public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero; // Version-checked first: on an older engine the field lies past the end of its API table. public bool HasGetMergeStackResult => _api.Version >= 81 && _api.GetMergeStackResultFn != IntPtr.Zero; + /// <summary>v85: <see cref="ArmConfirmation"/> and <see cref="TryGetLastConfirmation"/>.</summary> + public bool HasConfirmationAnswers => _api.Version >= 85 && _api.ArmConfirmationFn != IntPtr.Zero && _api.GetLastConfirmationFn != IntPtr.Zero; public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero; public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero; public bool HasGetLastUseDone => _api.Version >= 70 && _api.GetLastUseDoneFn != IntPtr.Zero; @@ -619,6 +623,65 @@ public readonly unsafe struct RynthCoreHost return status; } + /// <summary>Server yes/no prompt types (ConfirmationRequest 0x0274).</summary> + public static class ConfirmationKind + { + public const uint SwearAllegiance = 1; + public const uint AlterSkill = 2; + public const uint AlterAttribute = 3; + public const uint Fellowship = 4; + public const uint CraftInteraction = 5; + public const uint Augmentation = 6; + public const uint YesNo = 7; + } + + /// <summary>What happened to the last prompt (<see cref="TryGetLastConfirmation"/>).</summary> + public static class ConfirmationOutcome + { + public const int None = 0; // no prompt this session + public const int Shown = 1; // not armed: the client showed its dialog + public const int Accepted = 2; // answered Yes for the plugin + public const int Declined = 3; // answered No: the server's percent was below the minimum + public const int SendFailed = 4; // armed, but the send failed: the client showed it + } + + /// <summary> + /// v85: answer the next server prompt of <paramref name="type"/> (a + /// <see cref="ConfirmationKind"/>) that arrives within <paramref name="timeoutMs"/>, + /// without the client opening its dialog: Yes when the server's "N percent chance" is at + /// least <paramref name="minPercent"/> (or it is 0), else No. One-shot; timeoutMs <= 0 + /// disarms. 1 armed, 0 unavailable (engine before v85, sender or hook missing), -3 bad + /// arguments. + /// </summary> + public int ArmConfirmation(uint type, int minPercent, int timeoutMs) + { + if (!HasConfirmationAnswers) + return 0; + return ((delegate* unmanaged[Cdecl]<uint, int, int, int>)_api.ArmConfirmationFn)(type, minPercent, timeoutMs); + } + + /// <summary> + /// v85: the last prompt the server sent. <paramref name="seq"/> counts them (0 = none yet); + /// <paramref name="contextId"/> is the server's context for it; <paramref name="percent"/> is + /// -1 when the text has none; <paramref name="outcome"/> is a <see cref="ConfirmationOutcome"/>. + /// False on an engine before v85. + /// </summary> + public bool TryGetLastConfirmation(out int seq, out uint type, out uint contextId, out int percent, out int outcome, out int ageMs) + { + seq = 0; type = 0; contextId = 0; percent = -1; outcome = 0; ageMs = 0; + if (!HasConfirmationAnswers) + return false; + uint t = 0, ctx = 0; + int pct = -1, oc = 0, age = 0; + seq = ((delegate* unmanaged[Cdecl]<uint*, uint*, int*, int*, int*, int>)_api.GetLastConfirmationFn)(&t, &ctx, &pct, &oc, &age); + type = t; contextId = ctx; percent = pct; outcome = oc; ageMs = age; + return true; + } + + /// <summary>v85: <see cref="TryGetLastConfirmation(out int, out uint, out uint, out int, out int, out int)"/> without the context id.</summary> + public bool TryGetLastConfirmation(out int seq, out uint type, out int percent, out int outcome, out int ageMs) + => TryGetLastConfirmation(out seq, out type, out _, out percent, out outcome, out ageMs); + /// <summary> /// Gives an item to an NPC or another player by sending the F7B1 give /// GameAction (CM_Inventory::Event_GiveObjectRequest). This is the correct @@ -1054,6 +1117,37 @@ public readonly unsafe struct RynthCoreHost return true; } + /// <summary> + /// v86: which server this is, as JSON: every server the engine knows (built in, or declared + /// by a loaded server plugin) with its verdict, this character's override, the reason and the + /// plugin that owns its settings, plus "active" / "activePlugin" and the Diagnostics "pick". + /// Schema: RynthCore.Engine UI/Sections/ServerStateJson.cs. False when the engine predates + /// v86 or the call failed. Any thread; a few hundred bytes, so poll it (every second or two) + /// rather than caching it for a session: an override changes it live. + /// </summary> + public bool TryGetServerStateJson(out string json) + { + json = string.Empty; + if (!HasGetServerStateJson) + return false; + var fn = (delegate* unmanaged[Cdecl]<byte*, int, int>)_api.GetServerStateJsonFn; + int capacity = 2048; + for (int attempt = 0; attempt < 3; attempt++) + { + byte[] buffer = new byte[capacity]; + int length; + fixed (byte* p = buffer) length = fn(p, capacity); + if (length < 0) return false; + if (length < capacity) + { + json = System.Text.Encoding.UTF8.GetString(buffer, 0, length); + return true; + } + capacity = length + 256; + } + return false; + } + public bool TryGetObjectBoolProperty(uint objectId, uint stype, out bool value) { value = false; diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index bbb2dfd..f0a19f3 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -14,6 +14,9 @@ description RynthPluginDescription (default: Description) homepage RynthPluginHomepage (default: PackageProjectUrl) license RynthPluginLicense (default: PackageLicenseExpression) + server RynthPluginServerId (lower-case a-z 0-9 -), RynthPluginServerName, + RynthPluginServerHosts and RynthPluginServerWorldNames ('|'-separated): + a server plugin, loaded only for its own server (engine PluginManifestGate) 2. adds [assembly: RynthPluginManifest(minEngineApi)], which RynthPluginBase.MinimumApiVersion defaults to (the plugin's own runtime check, which also covers engines from before manifests), and generates RynthPluginInfo (Name, Version, MinEngineApi constants) in the @@ -33,7 +36,7 @@ <PropertyGroup> <!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. --> - <RynthCoreSdkApiVersion>84</RynthCoreSdkApiVersion> + <RynthCoreSdkApiVersion>86</RynthCoreSdkApiVersion> <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn> </PropertyGroup> @@ -79,6 +82,10 @@ public class RynthWritePluginManifest : Task public string Description { get; set; } public string Homepage { get; set; } public string License { get; set; } + public string ServerId { get; set; } + public string ServerName { get; set; } + public string ServerHosts { get; set; } + public string ServerWorldNames { get; set; } public ITaskItem[] Dependencies { get; set; } public string RootNamespace { get; set; } [Required] public string JsonPath { get; set; } @@ -126,6 +133,21 @@ public class RynthWritePluginManifest : Task AppendOpt(sb, "description", Description); AppendOpt(sb, "homepage", Homepage); AppendOpt(sb, "license", License); + + string serverId = (ServerId ?? "").Trim().ToLowerInvariant(); + string serverName = (ServerName ?? "").Trim(); + string[] hosts = Split(ServerHosts), worlds = Split(ServerWorldNames); + if (serverId.Length > 0) + { + foreach (char c in serverId) + if (!(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-')) + { Log.LogError("RynthPluginServerId '{0}' may only have a-z, 0-9 and '-'.", serverId); return false; } + if (hosts.Length + worlds.Length == 0) + { Log.LogError("RynthPluginServerId '{0}' needs RynthPluginServerHosts or RynthPluginServerWorldNames.", serverId); return false; } + if (serverName.Length == 0) serverName = serverId; + sb.Append(",\n \"server\": { \"id\": ").Append(Q(serverId)).Append(", \"name\": ").Append(Q(serverName)); + sb.Append(", \"hosts\": [").Append(JoinQ(hosts)).Append("], \"worldNames\": [").Append(JoinQ(worlds)).Append("] }"); + } sb.Append("\n}\n"); WriteIfChanged(JsonPath, sb.ToString()); @@ -139,6 +161,11 @@ public class RynthWritePluginManifest : Task cs.Append(" public const string Version = ").Append(Q((Version ?? "").Trim())).Append(";\n"); cs.Append(" /// <summary>The oldest engine API this plugin runs on (its manifest's minEngineApi).</summary>\n"); cs.Append(" public const uint MinEngineApi = ").Append(min).Append(";\n"); + cs.Append(" /// <summary>The manifest's server block (\"\" and empty lists for a plugin that isn't a server plugin).</summary>\n"); + cs.Append(" public const string ServerId = ").Append(Q(serverId)).Append(";\n"); + cs.Append(" public const string ServerName = ").Append(Q(serverId.Length > 0 ? serverName : "")).Append(";\n"); + cs.Append(" public static readonly string[] ServerHosts = { ").Append(serverId.Length > 0 ? JoinQ(hosts) : "").Append(" };\n"); + cs.Append(" public static readonly string[] ServerWorldNames = { ").Append(serverId.Length > 0 ? JoinQ(worlds) : "").Append(" };\n"); cs.Append("}\n"); WriteIfChanged(InfoSourcePath, cs.ToString()); return !Log.HasLoggedErrors; @@ -150,6 +177,25 @@ public class RynthWritePluginManifest : Task sb.Append(",\n ").Append(Q(key)).Append(": ").Append(Q(value.Trim())); } + // '|'-separated (MSBuild would split ';' lists into items), blanks dropped, at most 16. + private static string[] Split(string text) + { + var list = new List<string>(); + foreach (string part in (text ?? "").Split('|')) + { + string p = part.Trim(); + if (p.Length > 0 && list.Count < 16) list.Add(p); + } + return list.ToArray(); + } + + private static string JoinQ(string[] values) + { + var sb = new StringBuilder(); + for (int i = 0; i < values.Length; i++) sb.Append(i == 0 ? "" : ", ").Append(Q(values[i])); + return sb.ToString(); + } + private static void WriteIfChanged(string path, string text) { if (File.Exists(path) && File.ReadAllText(path) == text) return; @@ -241,6 +287,8 @@ public class RynthEmbedPluginManifest : Task MaxEngineApi="$(RynthPluginMaxEngineApi)" SdkApiVersion="$(RynthCoreSdkApiVersion)" Author="$(RynthPluginAuthor)" Description="$(RynthPluginDescription)" Homepage="$(RynthPluginHomepage)" License="$(RynthPluginLicense)" + ServerId="$(RynthPluginServerId)" ServerName="$(RynthPluginServerName)" + ServerHosts="$(RynthPluginServerHosts)" ServerWorldNames="$(RynthPluginServerWorldNames)" Dependencies="@(RynthPluginDependency)" RootNamespace="$(RootNamespace)" JsonPath="$(_RynthPluginManifestJson)" InfoSourcePath="$(_RynthPluginInfoSource)" /> <ItemGroup> diff --git a/src/RynthCore.StatusAgent/AgentConfig.cs b/src/RynthCore.StatusAgent/AgentConfig.cs index 78372e6..a32b75f 100644 --- a/src/RynthCore.StatusAgent/AgentConfig.cs +++ b/src/RynthCore.StatusAgent/AgentConfig.cs @@ -61,7 +61,10 @@ internal sealed class AgentConfig /// <summary>Shared secret, required when <see cref="ServeHttp"/> is on: every route but /// /healthz needs <c>Authorization: Bearer <token></c> or <c>?token=</c>. Empty = - /// the server stays off, on any bind (it can stream the screens and click in them).</summary> + /// the server stays off, on any bind (it can stream the screens and click in them). A + /// <see cref="ServePrefix"/> other than 127.0.0.1/localhost needs at least + /// <see cref="ServeGuard.MinRemoteTokenLength"/> characters; an address that sends + /// <see cref="AuthThrottle.MaxFailures"/> bad tokens in a minute is locked out for 5 minutes.</summary> [JsonPropertyName("ServeToken")] public string ServeToken { get; set; } = ""; /// <summary>When true, also write the latest rollup to diff --git a/src/RynthCore.StatusAgent/LocalStatusServer.cs b/src/RynthCore.StatusAgent/LocalStatusServer.cs index 59b7442..006a6ef 100644 --- a/src/RynthCore.StatusAgent/LocalStatusServer.cs +++ b/src/RynthCore.StatusAgent/LocalStatusServer.cs @@ -40,6 +40,8 @@ internal sealed class LocalStatusServer : IDisposable // Connected /statusfeed push clients — each value is a per-socket wake signal. UpdateLatest pulses // them all; each socket's loop then sends the freshest _latest (coalescing rapid updates). private readonly ConcurrentDictionary<Guid, SemaphoreSlim> _feedSignals = new(); + // Failed token checks per remote address (lockout after repeated guesses). + private readonly AuthThrottle _authThrottle = new(); private const int FeedKeepAliveMs = 20000; // re-send _latest at least this often (keepalive + missed-pulse cover) public bool Running { get; private set; } @@ -93,9 +95,11 @@ internal sealed class LocalStatusServer : IDisposable public bool TryStart(out string error) { // Never serve without a token, loopback included: every route but /healthz is behind it. - if (_token == null) + // A bind other PCs can reach also needs one long enough not to be guessed (ServeGuard). + string? tokenProblem = ServeGuard.TokenProblem(_prefix, _token); + if (tokenProblem != null) { - error = "no ServeToken set"; + error = tokenProblem; Running = false; return false; } @@ -141,7 +145,7 @@ internal sealed class LocalStatusServer : IDisposable // Diagnostic: log every /webrtc request + every CORS preflight, at the door (before any // auth/route processing), so we can see whether the app's offer POST even reaches us. if (path.StartsWith("/webrtc") || string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase)) - AgentLog.Info($"[video] HTTP {method} {path} ua=\"{req.UserAgent}\""); + AgentLog.Info($"[video] HTTP {ServeGuard.LogSafe(method, 16)} {ServeGuard.LogSafe(path, 64)} ua=\"{ServeGuard.LogSafe(req.UserAgent)}\""); // CORS preflight for the POST /command path (a browser-hosted client may send it). if (string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase)) @@ -199,7 +203,7 @@ internal sealed class LocalStatusServer : IDisposable int vpid = int.TryParse(req.QueryString["pid"], out int vv) ? vv : 0; if (vpid <= 0) { Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray()); return; } if (!req.IsWebSocketRequest) { Write(res, 426, "application/json", "{\"error\":\"websocket required\"}"u8.ToArray()); return; } - AgentLog.Info($"[vsock] HTTP WS /video pid={vpid} ua=\"{req.UserAgent}\""); + AgentLog.Info($"[vsock] HTTP WS /video pid={vpid} ua=\"{ServeGuard.LogSafe(req.UserAgent)}\""); _ = HandleVideoSocketAsync(ctx, vpid); return; } @@ -209,7 +213,7 @@ internal sealed class LocalStatusServer : IDisposable { if (_token != null && !Authorized(req)) { Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; } if (!req.IsWebSocketRequest) { Write(res, 426, "application/json", "{\"error\":\"websocket required\"}"u8.ToArray()); return; } - AgentLog.Info($"[feed] WS /statusfeed ua=\"{req.UserAgent}\""); + AgentLog.Info($"[feed] WS /statusfeed ua=\"{ServeGuard.LogSafe(req.UserAgent)}\""); _ = HandleStatusFeedAsync(ctx); return; } @@ -241,7 +245,13 @@ internal sealed class LocalStatusServer : IDisposable if (path == "/webrtc/stop") { _video.Stop(pid); Write(res, 200, "application/json", "{\"ok\":true}"u8.ToArray()); return; } if (path == "/webrtc/clientlog") // diagnostic: WKWebView reports its WebRTC errors/states here { - try { using var sr = new StreamReader(req.InputStream, req.ContentEncoding ?? Encoding.UTF8); AgentLog.Info($"[video] CLIENT pid={pid}: {sr.ReadToEnd()}"); } catch { } + try + { + if (!ServeGuard.TryReadBounded(req.InputStream, req.ContentLength64, ServeGuard.MaxClientLogBodyBytes, req.ContentEncoding, out string clientLog)) + { Write(res, 413, "application/json", "{\"error\":\"too large\"}"u8.ToArray()); return; } + AgentLog.Info($"[video] CLIENT pid={pid}: {ServeGuard.LogSafe(clientLog, 2000)}"); + } + catch { } Write(res, 200, "application/json", "{\"ok\":true}"u8.ToArray()); return; } @@ -526,9 +536,11 @@ internal sealed class LocalStatusServer : IDisposable { try { - string body; - using (var reader = new StreamReader(req.InputStream, req.ContentEncoding ?? Encoding.UTF8)) - body = reader.ReadToEnd(); + if (!ServeGuard.TryReadBounded(req.InputStream, req.ContentLength64, ServeGuard.MaxCommandBodyBytes, req.ContentEncoding, out string body)) + { + Write(res, 413, "application/json", "{\"error\":\"command too large\"}"u8.ToArray()); + return; + } int pid; string action; string value; using (var doc = JsonDocument.Parse(body)) @@ -614,9 +626,9 @@ internal sealed class LocalStatusServer : IDisposable // Keep-alives arrive ~5 a second per held client: debug only, so the log keeps the presses and releases. if (string.Equals(action, "moveKeepAlive", StringComparison.OrdinalIgnoreCase)) - AgentLog.Debug($"command queued: pid={pid} {action}={value}"); + AgentLog.Debug($"command queued: pid={pid} {action}={ServeGuard.LogSafe(value, 500)}"); else - AgentLog.Info($"command queued: pid={pid} {action}={value}"); + AgentLog.Info($"command queued: pid={pid} {action}={ServeGuard.LogSafe(value, 500)}"); Write(res, 202, "application/json", "{\"ok\":true}"u8.ToArray()); } catch (Exception ex) @@ -837,9 +849,11 @@ internal sealed class LocalStatusServer : IDisposable private void HandleWebRtcOffer(HttpListenerRequest req, HttpListenerResponse res, int pid) { - string body; - using (var sr = new StreamReader(req.InputStream, req.ContentEncoding ?? Encoding.UTF8)) - body = sr.ReadToEnd(); + if (!ServeGuard.TryReadBounded(req.InputStream, req.ContentLength64, ServeGuard.MaxOfferBodyBytes, req.ContentEncoding, out string body)) + { + Write(res, 413, "application/json", "{\"error\":\"offer too large\"}"u8.ToArray()); + return; + } string? offer = null; try { offer = JsonDocument.Parse(body).RootElement.GetProperty("sdp").GetString(); } catch { } if (string.IsNullOrEmpty(offer)) @@ -849,10 +863,10 @@ internal sealed class LocalStatusServer : IDisposable } // Diagnostic: confirm the offer arrived + from which client (Safari vs Chrome), and what H.264 // profile-level-id(s) it can RECEIVE. - AgentLog.Info($"[video] OFFER pid={pid} ua=\"{req.UserAgent}\""); + AgentLog.Info($"[video] OFFER pid={pid} ua=\"{ServeGuard.LogSafe(req.UserAgent)}\""); foreach (var ln in offer.Split('\n')) if (ln.StartsWith("m=video", StringComparison.Ordinal) || ln.Contains("profile-level-id", StringComparison.OrdinalIgnoreCase) || ln.Contains("candidate", StringComparison.OrdinalIgnoreCase)) - AgentLog.Info($"[video] offer> {ln.Trim()}"); + AgentLog.Info($"[video] offer> {ServeGuard.LogSafe(ln.Trim(), 300)}"); string? answer; try { answer = _video!.CreateAnswerAsync(pid, offer).GetAwaiter().GetResult(); } catch (Exception ex) { AgentLog.Warn($"[video] offer failed pid {pid}: {ex.Message}"); answer = null; } @@ -871,13 +885,24 @@ internal sealed class LocalStatusServer : IDisposable private bool Authorized(HttpListenerRequest req) { - string? header = req.Headers["Authorization"]; - if (header != null && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) && - TokenMatches(header.Substring("Bearer ".Length).Trim())) - return true; + // An address that kept guessing is refused outright for a while, right token or not. + IPAddress? from = req.RemoteEndPoint?.Address; + DateTime now = DateTime.UtcNow; + if (_authThrottle.IsBlocked(from, now)) return false; - string? q = req.QueryString["token"]; - return q != null && TokenMatches(q); + string? header = req.Headers["Authorization"]; + bool ok = header != null && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) && + TokenMatches(header.Substring("Bearer ".Length).Trim()); + if (!ok) + { + string? q = req.QueryString["token"]; + ok = q != null && TokenMatches(q); + } + + if (ok) _authThrottle.Succeed(from); + else if (_authThrottle.Fail(from, now)) + AgentLog.Warn($"auth: {from} locked out for {AuthThrottle.Lockout.TotalMinutes:0} min after {AuthThrottle.MaxFailures} bad tokens."); + return ok; } private bool TokenMatches(string candidate) diff --git a/src/RynthCore.StatusAgent/Program.cs b/src/RynthCore.StatusAgent/Program.cs index 4acfc86..418a009 100644 --- a/src/RynthCore.StatusAgent/Program.cs +++ b/src/RynthCore.StatusAgent/Program.cs @@ -64,6 +64,7 @@ var navAtlas = new NavAtlasService(cfg.NavAtlasPath); LocalStatusServer? server = null; WebRtcVideoService? video = null; // HD WebRTC video mode (opt-in); disposed in finally IconService? icons = null; // item-icon decoder (GET /icon); disposed in finally +string? serveTokenProblem = cfg.ServeHttp ? ServeGuard.TokenProblem(cfg.ServePrefix, cfg.ServeToken) : null; if (cfg.ServeHttp && string.IsNullOrWhiteSpace(cfg.ServeToken)) { // Same rule as DrakBot's remote: no token, no server, loopback included. The server can show @@ -72,8 +73,20 @@ if (cfg.ServeHttp && string.IsNullOrWhiteSpace(cfg.ServeToken)) AgentLog.Warn($"Set \"ServeToken\" in {configPath} and restart the agent. Use the same token as your"); AgentLog.Warn("DrakBot remote and one DrakRemote entry shows both."); } +else if (serveTokenProblem != null) +{ + // A bind other PCs reach (LAN, Tailscale) needs a token that can't be guessed. + AgentLog.Warn($"ServeHttp is on but {serveTokenProblem}, so the status server stays off."); + AgentLog.Warn($"Put a longer \"ServeToken\" in {configPath} (a random 24+ characters) and restart the agent."); +} else if (cfg.ServeHttp) { + if (!ServeGuard.IsLoopbackPrefix(cfg.ServePrefix)) + { + // HttpListener here is plain HTTP: the token and the screens cross the network unencrypted. + AgentLog.Warn($"ServePrefix {cfg.ServePrefix} is reachable from other PCs over plain HTTP: use it only"); + AgentLog.Warn("inside an encrypted network (Tailscale/WireGuard VPN), never forwarded to the internet."); + } string? commandDir = cfg.EnableRemoteControl ? Path.Combine(cfg.StatusDirectory, "commands") : null; VideoSocketService? videoSocket = null; if (cfg.EnableVideoStream) diff --git a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj index 61355b8..0545856 100644 --- a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj +++ b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj @@ -19,7 +19,8 @@ <RootNamespace>RynthCore.StatusAgent</RootNamespace> <AssemblyName>RynthCore.StatusAgent</AssemblyName> <InvariantGlobalization>true</InvariantGlobalization> - <Version>1.0.0</Version> + <!-- Previous release: 1.0.0. --> + <Version>1.0.1</Version> </PropertyGroup> <ItemGroup> diff --git a/src/RynthCore.StatusAgent/ServeGuard.cs b/src/RynthCore.StatusAgent/ServeGuard.cs new file mode 100644 index 0000000..4f3b876 --- /dev/null +++ b/src/RynthCore.StatusAgent/ServeGuard.cs @@ -0,0 +1,155 @@ +using System.Text; + +namespace RynthCore.StatusAgent; + +/// <summary> +/// The status server's guards for a bind other PCs can reach (LAN, Tailscale): a token long +/// enough to resist guessing, a lockout for an address that keeps guessing, bounded request +/// bodies, and client text made safe for the log. Pure code; compiled into tools/StatusAgentTests. +/// </summary> +internal static class ServeGuard +{ + /// <summary>Shortest ServeToken accepted when the prefix isn't loopback-only.</summary> + public const int MinRemoteTokenLength = 16; + + // Request bodies: a command is a few hundred bytes, a WebRTC offer a few KB. + public const int MaxCommandBodyBytes = 64 * 1024; + public const int MaxOfferBodyBytes = 256 * 1024; + public const int MaxClientLogBodyBytes = 16 * 1024; + + /// <summary> + /// True when <paramref name="prefix"/> (an HttpListener prefix, "http://host:port/") only + /// listens on this PC: 127.x.x.x, localhost or [::1]. "+", "*", a LAN address or a name = false. + /// </summary> + public static bool IsLoopbackPrefix(string? prefix) + { + if (string.IsNullOrWhiteSpace(prefix)) return false; + int scheme = prefix.IndexOf("://", StringComparison.Ordinal); + if (scheme < 0) return false; + string rest = prefix.Substring(scheme + 3); + string host; + if (rest.StartsWith('[')) + { + int close = rest.IndexOf(']'); + if (close < 0) return false; + host = rest.Substring(1, close - 1); + } + else + { + int end = rest.IndexOfAny(new[] { ':', '/' }); + host = end < 0 ? rest : rest.Substring(0, end); + } + if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host == "::1") return true; + return System.Net.IPAddress.TryParse(host, out var ip) + && ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork + && System.Net.IPAddress.IsLoopback(ip); + } + + /// <summary>Why the server must not start with this token on this prefix, or null when it may.</summary> + public static string? TokenProblem(string prefix, string? token) + { + if (string.IsNullOrWhiteSpace(token)) return "no ServeToken set"; + if (!IsLoopbackPrefix(prefix) && token.Trim().Length < MinRemoteTokenLength) + return $"ServeToken must be at least {MinRemoteTokenLength} characters when ServePrefix isn't 127.0.0.1/localhost"; + return null; + } + + /// <summary> + /// Reads a request body of at most <paramref name="maxBytes"/>. False (nothing read past the + /// limit) when the declared or actual length is over it. + /// </summary> + public static bool TryReadBounded(Stream input, long declaredLength, int maxBytes, Encoding? encoding, out string text) + { + text = ""; + if (declaredLength > maxBytes) return false; + var buffer = new byte[Math.Min(maxBytes + 1, 64 * 1024)]; + using var collected = new MemoryStream(); + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + { + if (collected.Length + read > maxBytes) return false; + collected.Write(buffer, 0, read); + } + text = (encoding ?? Encoding.UTF8).GetString(collected.GetBuffer(), 0, (int)collected.Length); + return true; + } + + /// <summary>Client-supplied text for one log line: control characters (CR/LF included) become spaces, capped at <paramref name="max"/>.</summary> + public static string LogSafe(string? text, int max = 200) + { + if (string.IsNullOrEmpty(text)) return ""; + var sb = new StringBuilder(Math.Min(text.Length, max) + 3); + foreach (char c in text) + { + if (sb.Length >= max) { sb.Append("..."); break; } + sb.Append(char.IsControl(c) ? ' ' : c); + } + return sb.ToString(); + } +} + +/// <summary> +/// Locks out an address after too many failed token checks: <see cref="MaxFailures"/> within +/// <see cref="Window"/> blocks it for <see cref="Lockout"/> (even with the right token, so a +/// guesser learns nothing). Loopback is never locked out (the owner's own tools). Thread-safe. +/// </summary> +internal sealed class AuthThrottle +{ + public const int MaxFailures = 10; + public static readonly TimeSpan Window = TimeSpan.FromMinutes(1); + public static readonly TimeSpan Lockout = TimeSpan.FromMinutes(5); + private const int MaxTracked = 4096; + + private sealed class Entry { public int Failures; public DateTime WindowStart; public DateTime BlockedUntil; } + + private readonly Dictionary<string, Entry> _byAddress = new(StringComparer.Ordinal); + private readonly object _gate = new(); + + /// <summary>True while <paramref name="address"/> is locked out.</summary> + public bool IsBlocked(System.Net.IPAddress? address, DateTime nowUtc) + { + if (address == null || System.Net.IPAddress.IsLoopback(address)) return false; + lock (_gate) + return _byAddress.TryGetValue(address.ToString(), out Entry? e) && e.BlockedUntil > nowUtc; + } + + /// <summary>Counts a failed check; true when this one started a lockout (log it once).</summary> + public bool Fail(System.Net.IPAddress? address, DateTime nowUtc) + { + if (address == null || System.Net.IPAddress.IsLoopback(address)) return false; + lock (_gate) + { + string key = address.ToString(); + if (!_byAddress.TryGetValue(key, out Entry? e)) + { + if (_byAddress.Count >= MaxTracked) Prune(nowUtc); + e = new Entry { WindowStart = nowUtc }; + _byAddress[key] = e; + } + if (nowUtc - e.WindowStart > Window) { e.WindowStart = nowUtc; e.Failures = 0; } + if (++e.Failures < MaxFailures) return false; + e.Failures = 0; + e.WindowStart = nowUtc; + e.BlockedUntil = nowUtc + Lockout; + return true; + } + } + + /// <summary>A good token clears the address's count.</summary> + public void Succeed(System.Net.IPAddress? address) + { + if (address == null) return; + lock (_gate) _byAddress.Remove(address.ToString()); + } + + private void Prune(DateTime nowUtc) + { + foreach (var key in _byAddress.Where(kv => kv.Value.BlockedUntil <= nowUtc && nowUtc - kv.Value.WindowStart > Window) + .Select(kv => kv.Key).ToList()) + _byAddress.Remove(key); + // Still full (a flood of blocked addresses): drop the oldest windows rather than grow without bound. + if (_byAddress.Count >= MaxTracked) + foreach (var key in _byAddress.OrderBy(kv => kv.Value.WindowStart).Take(_byAddress.Count / 4).Select(kv => kv.Key).ToList()) + _byAddress.Remove(key); + } +} diff --git a/tools/EngineSettingsTests/EngineSettingsTests.csproj b/tools/EngineSettingsTests/EngineSettingsTests.csproj index 4201d3e..afc8f70 100644 --- a/tools/EngineSettingsTests/EngineSettingsTests.csproj +++ b/tools/EngineSettingsTests/EngineSettingsTests.csproj @@ -24,6 +24,9 @@ <Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettingsFile.cs" Link="Engine\EngineSettingsFile.cs" /> <Compile Include="..\..\src\RynthCore.Engine\ReloadCapNotice.cs" Link="Engine\ReloadCapNotice.cs" /> <Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdPolicy.cs" Link="Engine\AutoIdPolicy.cs" /> + <!-- EditIltServerName starts from IltDetect's defaults (IltDetect shares a parser with AelrynthWire). --> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" /> </ItemGroup> </Project> diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index 8c506f3..4785290 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -52,6 +52,7 @@ namespace EngineSettingsTests Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone); Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept); Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved); + Run(nameof(IltServerNamesEdit), IltServerNamesEdit); } finally { @@ -88,6 +89,8 @@ namespace EngineSettingsTests if (!RynthCore.Engine.Compatibility.AutoIdPolicy.TryParseMode(args[1], out var aim)) throw new ArgumentException(args[1]); EngineSettings.AutoIdMode = aim; break; + case "ilt-add": Console.WriteLine("Changed=" + EngineSettings.EditIltServerName(args[1], add: true)); break; + case "ilt-remove": Console.WriteLine("Changed=" + EngineSettings.EditIltServerName(args[1], add: false)); break; case "dump": Console.WriteLine("AutoIdMode=" + EngineSettings.AutoIdMode); Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths)); @@ -97,6 +100,7 @@ namespace EngineSettingsTests Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream); Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads); Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect); + Console.WriteLine("IltServerNames=" + (EngineSettings.IltServerNames is { } n ? string.Join("|", n) : "(none)")); break; default: throw new ArgumentException(args[0]); } @@ -359,6 +363,32 @@ namespace EngineSettingsTests } } + // /rc server names ilt add|remove (2026.10.5.46): the first edit starts from the defaults, + // the edit is saved with the launcher's keys kept, and repeats, unknown, empty and overlong + // patterns change nothing. + private static void IltServerNamesEdit() + { + string dir = NewDir("iltnames"); + string path = Path.Combine(dir, "engine.json"); + File.WriteAllText(path, LauncherFile); + JsonElement before = ReadJson(path); + + Eq(DumpValue(RunChild(path, "dump").Out, "IltServerNames"), "(none)", "no list in the file"); + Eq(DumpValue(RunChild(path, "ilt-add", "Frosthaven").Out, "Changed"), "True", "add"); + string defaults = string.Join("|", RynthCore.Engine.Compatibility.IltDetect.DefaultServerNames); + Eq(DumpValue(RunChild(path, "dump").Out, "IltServerNames"), defaults + "|Frosthaven", "the defaults kept, the new one added"); + Eq(Raw(ReadJson(path).GetProperty("LauncherWindow")), Raw(before.GetProperty("LauncherWindow")), "the launcher's keys kept"); + NoTempFilesLeft(dir); + + Eq(DumpValue(RunChild(path, "ilt-add", "FROSTHAVEN").Out, "Changed"), "False", "adding again (any case) changes nothing"); + Eq(DumpValue(RunChild(path, "ilt-remove", "nope").Out, "Changed"), "False", "removing an unknown pattern changes nothing"); + Eq(DumpValue(RunChild(path, "ilt-add", " ").Out, "Changed"), "False", "an empty pattern is refused"); + Eq(DumpValue(RunChild(path, "ilt-add", new string('x', EngineSettings.MaxIltServerNameLength + 1)).Out, "Changed"), "False", + "an overlong pattern is refused"); + Eq(DumpValue(RunChild(path, "ilt-remove", "frosthaven").Out, "Changed"), "True", "remove (any case)"); + Eq(DumpValue(RunChild(path, "dump").Out, "IltServerNames"), defaults, "back to the defaults"); + } + /// <summary>The value of a "Name=value" line of the child's dump output ("" if none).</summary> private static string DumpValue(string output, string name) { diff --git a/tools/LauncherSettingsTests/LauncherSettingsTests.csproj b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj index c5fd01b..dc2f1f5 100644 --- a/tools/LauncherSettingsTests/LauncherSettingsTests.csproj +++ b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj @@ -28,6 +28,8 @@ <Compile Include="..\..\src\RynthCore.App\AccountPasswordProtection.cs" Link="App\AccountPasswordProtection.cs" /> <Compile Include="..\..\src\RynthCore.App\LaunchServerProfile.cs" Link="App\LaunchServerProfile.cs" /> <Compile Include="..\..\src\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="App\AcLaunchArgumentBuilder.cs" /> + <Compile Include="..\..\src\RynthCore.App\FirstLoginRules.cs" Link="App\FirstLoginRules.cs" /> + <Compile Include="..\..\src\RynthCore.App\UserPrefsSwapRecovery.cs" Link="App\UserPrefsSwapRecovery.cs" /> </ItemGroup> </Project> diff --git a/tools/LauncherSettingsTests/Program.cs b/tools/LauncherSettingsTests/Program.cs index 22c2735..e3a2340 100644 --- a/tools/LauncherSettingsTests/Program.cs +++ b/tools/LauncherSettingsTests/Program.cs @@ -179,8 +179,21 @@ internal static class Program 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)"); + Check(AcLaunchArgumentBuilder.NeedsPassword(noPw) && !AcLaunchArgumentBuilder.NeedsPassword(a), "NeedsPassword: only the account without one"); + Check(builder.BuildMaskedArguments(ace, noPw).StartsWith("No password is saved for account 'B'"), + "preview of an account without a password says so: " + builder.BuildMaskedArguments(ace, noPw)); + // The client exits with "You can only run the game from the launcher program" on an + // empty password (Conquest, 2026-10-13), so the launch is refused instead. + string refusal = Throws(() => builder.BuildArguments(ace, noPw)); + Check(refusal.StartsWith("No password is saved for account 'B'"), "no saved password: launch refused: " + refusal); + Check(Throws(() => builder.BuildArguments(gdle, noPw)).StartsWith("No password"), "GDLE refused too"); + + // Account names: ACE's 50-character limit; GDLE's "account:password" argument. + Check(AcLaunchArgumentBuilder.AccountNameProblem("SK", AcEmulatorKind.Ace) == null, "a short name is fine"); + Check(AcLaunchArgumentBuilder.AccountNameProblem(new string('x', 51), AcEmulatorKind.Ace)?.Contains("50") == true, "51 characters: too long"); + Check(AcLaunchArgumentBuilder.AccountNameProblem("a:b", AcEmulatorKind.Ace) == null, "a colon is fine on ACE"); + Check(AcLaunchArgumentBuilder.AccountNameProblem("a:b", AcEmulatorKind.Gdle) != null, "a colon is refused on GDLE"); + Check(AcLaunchArgumentBuilder.AccountNameProblem(" ", AcEmulatorKind.Ace) != null, "blank is refused"); LaunchAccountProfile copy = a.Clone(); Check(copy.PasswordProtected == a.PasswordProtected, "Clone keeps the encrypted password"); @@ -278,6 +291,96 @@ internal static class Program AppSettingsStore.Save(loaded); CheckNoPlainText("LEAK-CHECK-PW"); }); + + // ── First Login dialog rules (a new server: no password, no characters yet) ── + Scenario("first login on a new server", root, () => + { + var withPw = new LaunchAccountProfile { Id = "ilt", AccountName = "silentkelpie" }; + withPw.SetPassword(Pw); + var noPwSame = new LaunchAccountProfile { Id = "other", AccountName = "SilentKelpie" }; + var conquest = new LaunchAccountProfile { Id = "new", AccountName = "SK", CharacterName = LaunchAccountProfile.NoneOption }; + var all = new List<LaunchAccountProfile> { withPw, noPwSame, conquest }; + + Check(FirstLoginRules.KnownAccountNames(all, "new").SequenceEqual(new[] { "silentkelpie" }), + "known names: the others, distinct ignoring case, not this profile's own"); + + Check(FirstLoginRules.SavedPasswordSource(all, "SILENTKELPIE", "new")?.Id == "ilt", + "the same name with a saved password can be reused (case ignored)"); + Check(FirstLoginRules.SavedPasswordSource(all, "SK", "new") == null, "a new name has none to reuse"); + Check(FirstLoginRules.SavedPasswordSource(all, "silentkelpie", "ilt") == null, "never the profile itself"); + + var copy = new LaunchAccountProfile { AccountName = "silentkelpie" }; + copy.CopyPasswordFrom(withPw); + Check(copy.PasswordProtected == withPw.PasswordProtected && copy.TryGetPasswordForLaunch(out string reused, out _) && reused == Pw, + "reuse copies the encrypted blob, and it decrypts"); + + var none = new List<string>(); + List<string> firstChoices = FirstLoginRules.LoginChoices(none, conquest.CharacterName); + Check(firstChoices.SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect }), + "no characters yet: only stop at character select (the old (None) isn't listed)"); + Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, none) == "", + "stop with none known saves \"\" so the first character created is picked next time"); + + var chars = new List<string> { "Alpha", "Beta" }; + Check(FirstLoginRules.LoginChoices(chars, "Gamma").SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect, "Gamma", "Alpha", "Beta" }), + "several characters: all listed, the saved one kept even if not seen yet"); + Check(FirstLoginRules.CharacterNameFor("Beta", chars) == "Beta", "picking a character saves it"); + Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, chars) == LaunchAccountProfile.NoneOption, + "stop with characters known saves the explicit (None)"); + + Check(FirstLoginRules.Problem("SK", "", "", false, AcEmulatorKind.Ace)?.StartsWith("Enter the password") == true, "a password is required"); + Check(FirstLoginRules.Problem("SK", "a", "b", false, AcEmulatorKind.Ace)?.Contains("don't match") == true, "the confirmation must match"); + Check(FirstLoginRules.Problem("SK", "pw", "pw", false, AcEmulatorKind.Ace) == null, "name + matching password: ready"); + Check(FirstLoginRules.Problem("silentkelpie", "", "", true, AcEmulatorKind.Ace) == null, "reusing a saved password needs no typing"); + Check(FirstLoginRules.Problem("a:b", "pw", "pw", false, AcEmulatorKind.Gdle) != null, "GDLE name with a colon refused"); + Check(FirstLoginRules.Problem("", "pw", "pw", false, AcEmulatorKind.Ace) != null, "a name is required"); + }); + + // A saved UserPreferences.ini whose display mode the PC can't use made every launch + // fail with "Could not initialize Direct3D"; a quick exit must undo that swap. + Scenario("prefs swap: did the swap change the live file", root, () => + { + byte[] a = "[Display]\nResolution=2560x1440\n"u8.ToArray(); + byte[] b = "[Display]\nResolution=1920x1080\n"u8.ToArray(); + Check(!UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, (byte[])a.Clone())), "same bytes: not the cause"); + Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, b)), "different bytes: changed"); + Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, null)), "no live file before: changed"); + }); + + Scenario("prefs swap: failed stash set aside, live file put back", root, () => + { + var (swap, legacy) = PrefsSwapFiles(legacyMatches: true); + var now = new DateTime(2026, 10, 14, 16, 30, 5); + UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, quarantineStash: true, restoreLive: true, legacy, now); + Check(!File.Exists(swap.StashPath), "stash no longer swappable"); + Check(r.QuarantinedStashPath == swap.StashPath + ".failed-20261014-163005" && File.Exists(r.QuarantinedStashPath), "stash kept as .failed-<time>"); + Check(!File.Exists(legacy) && r.QuarantinedLegacyPath != null, "identical name-only stash set aside too (it would re-seed)"); + Check(r.LiveRestored && File.ReadAllBytes(swap.LivePath).SequenceEqual(swap.PreviousLiveBytes!), "live file back to its pre-swap bytes"); + }); + + Scenario("prefs swap: different name-only stash kept", root, () => + { + var (swap, legacy) = PrefsSwapFiles(legacyMatches: false); + UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, true, true, legacy, DateTime.Now); + Check(File.Exists(legacy) && r.QuarantinedLegacyPath == null, "name-only stash with other settings left alone"); + }); + + Scenario("prefs swap: later swap or profile override", root, () => + { + var (swap, legacy) = PrefsSwapFiles(legacyMatches: true); + File.WriteAllText(swap.LivePath, "another account's settings"); + UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, quarantineStash: false, restoreLive: false, legacy, DateTime.Now); + Check(File.Exists(swap.StashPath) && File.Exists(legacy), "override: the user's file is never renamed"); + Check(!r.LiveRestored && File.ReadAllText(swap.LivePath) == "another account's settings", "later swap: live file untouched"); + }); + + Scenario("prefs swap: no live file before", root, () => + { + var (swap, _) = PrefsSwapFiles(legacyMatches: false); + swap = swap with { PreviousLiveBytes = null }; + UserPrefsSwapRecovery.Recover(swap, true, true, null, DateTime.Now); + Check(!File.Exists(swap.LivePath), "live file removed so the game writes its defaults"); + }); } finally { @@ -316,6 +419,23 @@ internal static class Program private static InjectionMode Mode(AppSettings s, string id) => s.AccountProfiles.First(a => a.Id == id).InjectionMode; + /// <summary> + /// A swap as the launcher leaves it: the failed per-server stash copied over the live file, + /// plus the account's name-only stash (same bytes when <paramref name="legacyMatches"/>). + /// </summary> + private static (UserPrefsSwap Swap, string LegacyPath) PrefsSwapFiles(bool legacyMatches) + { + string stash = Path.Combine(_dir, "SK@Conquest.ini"); + string legacy = Path.Combine(_dir, "SK.ini"); + string live = Path.Combine(_dir, "UserPreferences.ini"); + byte[] bad = "[Display]\nResolution=2560x1440\nWindowed=False\n"u8.ToArray(); + byte[] good = "[Display]\nResolution=1920x1080\nWindowed=True\n"u8.ToArray(); + File.WriteAllBytes(stash, bad); + File.WriteAllBytes(legacy, legacyMatches ? bad : good); + File.WriteAllBytes(live, bad); + return (new UserPrefsSwap(stash, live, bad, good), legacy); + } + private static void CheckSharedFilesSafe() { foreach (string path in new[] { Main_, Bak }) @@ -382,6 +502,13 @@ internal static class Program Id = "s", Name = "Test", Host = "127.0.0.1", Port = 9000, Emulator = kind }; + /// <summary>The message <paramref name="action"/> throws ("" when it doesn't throw).</summary> + private static string Throws(Action action) + { + try { action(); return string.Empty; } + catch (Exception ex) { return ex.Message; } + } + private static string PwOf(AppSettings s, string id) => s.AccountProfiles.First(a => a.Id == id).TryGetPasswordForLaunch(out string pw, out _) ? pw : "<unreadable>"; diff --git a/tools/LauncherUpdateTests/LauncherUpdateTests.csproj b/tools/LauncherUpdateTests/LauncherUpdateTests.csproj index 5ea6040..94e3656 100644 --- a/tools/LauncherUpdateTests/LauncherUpdateTests.csproj +++ b/tools/LauncherUpdateTests/LauncherUpdateTests.csproj @@ -20,6 +20,7 @@ <ItemGroup> <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.cs" Link="Linked\RynthUpdater.cs" /> + <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.MapPacks.cs" Link="Linked\RynthUpdater.MapPacks.cs" /> <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.NavData.cs" Link="Linked\RynthUpdater.NavData.cs" /> <Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Available.cs" Link="Linked\RynthUpdater.Available.cs" /> <Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" /> diff --git a/tools/NetMessageTests/NetMessageTests.csproj b/tools/NetMessageTests/NetMessageTests.csproj index 2f77613..5f898b5 100644 --- a/tools/NetMessageTests/NetMessageTests.csproj +++ b/tools/NetMessageTests/NetMessageTests.csproj @@ -36,6 +36,7 @@ <Compile Include="..\..\src\RynthCore.Engine\Net\ServerMessageInterest.cs" Link="Engine\ServerMessageInterest.cs" /> <Compile Include="..\..\src\RynthCore.Engine\Net\InventoryOrder.cs" Link="Engine\InventoryOrder.cs" /> <Compile Include="..\..\src\RynthCore.Engine\Net\AelrynthVaultWire.cs" Link="Engine\AelrynthVaultWire.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\Net\ChatOrigin.cs" Link="Engine\ChatOrigin.cs" /> </ItemGroup> </Project> diff --git a/tools/NetMessageTests/VaultWireTests.cs b/tools/NetMessageTests/VaultWireTests.cs index 6628bbf..40ee561 100644 --- a/tools/NetMessageTests/VaultWireTests.cs +++ b/tools/NetMessageTests/VaultWireTests.cs @@ -33,6 +33,18 @@ internal static unsafe partial class Program Check(!AelrynthVaultWire.TryParse("~ael1 {\"t\":\"mule\",\"ready\":tru", out _), "damaged JSON is refused"); Check(AelrynthVaultWire.IsUnknownCommand("Unknown command: mule-data"), "ACE's reply for a missing command"); Check(!AelrynthVaultWire.IsUnknownCommand("Unknown command: mastery-data"), "another command's reply is not ours"); + + Case("vault wire: a player's copy of a server line is not ours"); + Check(!AelrynthVaultWire.IsMuleLine("Bob says, \"" + page + "\""), "spoken data line"); + Check(!AelrynthVaultWire.IsMuleLine("Bob " + page), "emoted data line (no quote)"); + Check(!AelrynthVaultWire.TryParse("[Allegiance] Bob says, \"" + page + "\"", out _), "a channel's copy does not parse"); + Check(AelrynthVaultWire.IsMuleLine(" " + page), "leading whitespace is fine"); + Check(AelrynthVaultWire.TryParse(" " + page, out _), "and parses"); + Check(!AelrynthVaultWire.IsUnknownCommand("Bob tells you, \"Unknown command: mule-data\""), "a told refusal"); + Check(!AelrynthVaultWire.IsUnknownCommand("Unknown command: mule-data-extra"), "a longer command name"); + Check(AelrynthVaultWire.IsUnknownCommand("Unknown command: /mule-data"), "a slash before the name is allowed"); + Check(ChatOrigin.IsPlayerAuthored(ChatOrigin.Emote) && ChatOrigin.IsPlayerAuthored(ChatOrigin.Tell), "emotes and tells are players'"); + Check(!ChatOrigin.IsPlayerAuthored(0) && !ChatOrigin.IsPlayerAuthored(0x0F), "Broadcast and Help (ACE's replies) are not"); Eq(AelrynthVaultWire.PageCommand(1), "@mule-data", "first page is the bare command"); Eq(AelrynthVaultWire.PageCommand(3), "@mule-data 3", "later pages say which"); diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index c2b537b..b16d0b8 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -50,6 +50,12 @@ internal static class Program Run(nameof(ReadsResourceFromPe32AndPe32Plus), ReadsResourceFromPe32AndPe32Plus); Run(nameof(NoResourceAndNotAPe), NoResourceAndNotAPe); Run(nameof(GatePlanFromFiles), GatePlanFromFiles); + Run(nameof(ServerBlockParsesAndRoundTrips), ServerBlockParsesAndRoundTrips); + Run(nameof(ServerBlockRejectsBadIds), ServerBlockRejectsBadIds); + Run(nameof(ServerHostMatching), ServerHostMatching); + Run(nameof(ServerGateKeepsOnlyTheHostsPlugin), ServerGateKeepsOnlyTheHostsPlugin); + Run(nameof(ServerGateUnclaimedHost), ServerGateUnclaimedHost); + Run(nameof(ServerGatePlanFromFiles), ServerGatePlanFromFiles); Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift); Run(nameof(TrainingStructsMirror), TrainingStructsMirror); Run(nameof(ContainerOrderSlots), ContainerOrderSlots); @@ -441,6 +447,117 @@ internal static class Program Check(none.Log.Any(l => l.Contains("no plugin has a manifest")), "said once"); } + // ── Server plugins (the manifest's "server" block and the load gate) ──── + + private static RynthPluginManifest S(string name, string id, string[] hosts, params string[] worlds) + { + var m = M(name); + m.Server = new RynthPluginServer { Id = id, Name = name, Hosts = hosts.ToList(), WorldNames = worlds.ToList() }; + return m; + } + + private static void ServerBlockParsesAndRoundTrips() + { + var m = RynthPluginManifest.Parse(""" + { "name": "RynthColdeve", "minEngineApi": 66, + "server": { "id": "Coldeve", "name": "Coldeve", "hosts": ["play.coldeve.ac", "", 5], "worldNames": ["Coldeve"] } } + """); + Check(m.Server != null, "server block read"); + Eq(m.Server!.Id, "coldeve", "id lower-cased"); + Eq(string.Join(",", m.Server.Hosts), "play.coldeve.ac", "blank and non-string hosts dropped"); + Eq(string.Join(",", m.Server.WorldNames), "Coldeve", "world names"); + var back = RynthPluginManifest.Parse(m.ToJson()); + Eq(back.Server?.Id, "coldeve", "round trip id"); + Eq(back.Server?.Hosts.Count, 1, "round trip hosts"); + Check(RynthPluginManifest.Parse("""{ "name": "RynthAi" }""").Server == null, "no block, not a server plugin"); + Check(!M("RynthAi").ToJson().Contains("\"server\""), "no server block written for other plugins"); + } + + private static void ServerBlockRejectsBadIds() + { + string[] bad = + { + """{ "name": "X", "server": "coldeve" }""", + """{ "name": "X", "server": { "name": "No id" } }""", + """{ "name": "X", "server": { "id": "has space" } }""", + """{ "name": "X", "server": { "id": "ok", "hosts": "not-an-array" } }""", + }; + foreach (string json in bad) + Check(RynthPluginManifest.TryParse(json, out string err) == null && err.Length > 0, $"refused: {json}"); + } + + private static void ServerHostMatching() + { + var ilt = new RynthPluginServer { Id = "ilt", Hosts = { "infiniteleaftide.online" } }; + Check(ilt.MatchesHost("game.infiniteleaftide.online", out string hit) && hit == "infiniteleaftide.online", "a host under the name"); + Check(ilt.MatchesHost("INFINITELEAFTIDE.ONLINE.", out _), "case and trailing dot ignored"); + Check(!ilt.MatchesHost("notinfiniteleaftide.online", out _), "not a suffix without the dot"); + var ip = new RynthPluginServer { Id = "aelrynth", Hosts = { "144.217.84.148" } }; + Check(ip.MatchesHost("144.217.84.148", out _), "an IP matches itself"); + Check(!ip.MatchesHost("1.144.217.84.148", out _), "an IP never matches as a suffix"); + var wild = new RynthPluginServer { Id = "x", Hosts = { "*.ddns.net" } }; + Check(wild.MatchesHost("frostcull.ddns.net", out _), "wildcard"); + Check(!wild.MatchesHost("", out _), "no host, no match"); + } + + private static void ServerGateKeepsOnlyTheHostsPlugin() + { + var list = new List<PluginCandidate> + { + C("RynthAi", M("RynthAi")), + C("RynthChat"), + C("RynthColdeve", S("RynthColdeve", "coldeve", new[] { "play.coldeve.ac" }, "Coldeve")), + C("RynthLeafDawn", S("RynthLeafDawn", "leafdawn", new[] { "leafdawn.hopto.org" }, "LeafDawn")), + C("RynthLeafdawning", S("RynthLeafdawning", "leafdawning", new[] { "leafdawning.duckdns.org" }, "Leafdawning")), + }; + var log = new List<string>(); + HashSet<string> skip = PluginManifestGate.SelectServerPlugins(list, "leafdawn.hopto.org", false, log); + Eq(skip.Count, 2, "the two other server plugins are left out"); + Check(skip.Contains(list[2].Key) && skip.Contains(list[4].Key), "Coldeve and Leafdawning left out"); + Check(!skip.Contains(list[0].Key) && !skip.Contains(list[1].Key), "other plugins always load"); + Check(log.Any(l => l.Contains("RynthColdeve") && l.Contains("not loaded")), "logged why"); + Eq(PluginManifestGate.SelectServerPlugins(list, "leafdawn.hopto.org", true, log).Count, 0, "LoadAllServerPlugins keeps every one"); + } + + private static void ServerGateUnclaimedHost() + { + var list = new List<PluginCandidate> + { + C("RynthColdeve", S("RynthColdeve", "coldeve", new[] { "play.coldeve.ac" })), + C("RynthFrostcull", S("RynthFrostcull", "frostcull", new[] { "frostcull.ddns.net" })), + }; + var log = new List<string>(); + Eq(PluginManifestGate.SelectServerPlugins(list, "", false, log).Count, 0, "no connect host: all load"); + Eq(PluginManifestGate.SelectServerPlugins(list, "10.0.0.5", false, log).Count, 2, "a host nobody lists: none load now (late load by world name or a pick)"); + Check(log.Any(l => l.Contains("none lists host 10.0.0.5")), "said why"); + } + + private static void ServerGatePlanFromFiles() + { + string dir = Path.Combine(_root, "servers"); + Directory.CreateDirectory(dir); + string P(string name) => Path.Combine(dir, $"RynthCore.Plugin.{name}.dll"); + File.Copy(ThisDll, P("RynthAi")); + Embed(P("RynthAi"), M("RynthAi").ToJson()); + File.Copy(ThisDll, P("RynthILT")); + Embed(P("RynthILT"), S("RynthILT", "ilt", new[] { "infiniteleaftide.online" }, "*Leaftide*").ToJson()); + File.Copy(ThisDll, P("RynthAelrynth")); + Embed(P("RynthAelrynth"), S("RynthAelrynth", "aelrynth", new[] { "144.217.84.148" }, "Aelrynth*").ToJson()); + + var paths = new[] { P("RynthAi"), P("RynthILT"), P("RynthAelrynth") }; + PluginManifestGate.LoadPlan onIlt = PluginManifestGate.Plan(paths, Api, null, "game.infiniteleaftide.online"); + Eq(string.Join(",", onIlt.Load.Select(l => RynthPluginManifest.NameFromFile(l.Path))), "RynthAi,RynthILT", "on ILT"); + Eq(onIlt.SkippedForServer.Count, 1, "Aelrynth's plugin skipped"); + // The skipped one keeps its manifest: Options > Diagnostics lists its server, and forcing it loads it. + Eq(onIlt.SkippedServerPlugins.Count, 1, "skipped server plugin kept with its manifest"); + Eq(onIlt.SkippedServerPlugins[0].Manifest.Server?.Id ?? "", "aelrynth", "its server id"); + Eq(onIlt.SkippedServerPlugins[0].Path, P("RynthAelrynth"), "its path"); + Eq(onIlt.Refused.Count, 0, "skipping is not a refusal (no chat notice)"); + Check(onIlt.Log.Any(l => l.Contains("server ilt")), "the manifest line names the server"); + PluginManifestGate.LoadPlan onAelrynth = PluginManifestGate.Plan(paths, Api, null, "144.217.84.148"); + Eq(string.Join(",", onAelrynth.Load.Select(l => RynthPluginManifest.NameFromFile(l.Path))), "RynthAi,RynthAelrynth", "on Aelrynth"); + } + // ── The SDK's version ──────────────────────────────────────────────────── private static void SdkApiVersionCannotDrift() @@ -474,11 +591,11 @@ internal static class Program Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset"); Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); - // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v84 follow). - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(4).TakeLast(6).ToArray(); + // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v85 follow). + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(7).TakeLast(6).ToArray(); Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }), "v79, v80 then v81 slots last: " + string.Join(",", names)); - var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(4).TakeLast(6).ToArray(); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(7).TakeLast(6).ToArray(); Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order"); } @@ -490,13 +607,17 @@ internal static class Program var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); // v81's GetMergeStackResultFn follows v80's two slots. - Check(names.SkipLast(5).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v84's: " + string.Join(",", names.SkipLast(5).TakeLast(2))); - Check(sdkNames.SkipLast(5).TakeLast(2).SequenceEqual(names.SkipLast(5).TakeLast(2)), "SDK v80 slots in the same order"); - Check(names.SkipLast(3).Last() == "SalvageDirectFn", "v82 slot before v83's"); + Check(names.SkipLast(8).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v85's: " + string.Join(",", names.SkipLast(8).TakeLast(2))); + Check(sdkNames.SkipLast(8).TakeLast(2).SequenceEqual(names.SkipLast(8).TakeLast(2)), "SDK v80 slots in the same order"); + Check(names.SkipLast(6).Last() == "SalvageDirectFn", "v82 slot before v83's"); // v83: GetObjectServerAge and RemoveClientObject (ghost creatures), then v84's slot. - Check(names.SkipLast(1).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(1).TakeLast(2))); - // v84: GetObjectProperties ends the table (every property of an object, /ub propertydump). - Check(names.Last() == "GetObjectPropertiesFn", "v84 slot last: " + names.Last()); + Check(names.SkipLast(4).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(4).TakeLast(2))); + // v84: GetObjectProperties (every property of an object, /ub propertydump), then v85's two. + Check(names.SkipLast(3).Last() == "GetObjectPropertiesFn", "v84 slot before v85's: " + names.SkipLast(3).Last()); + // v85: ArmConfirmation and GetLastConfirmation (the server's yes/no prompts), then v86's slot. + Check(names.SkipLast(1).TakeLast(2).SequenceEqual(new[] { "ArmConfirmationFn", "GetLastConfirmationFn" }), "v85 slots before v86's: " + string.Join(",", names.SkipLast(1).TakeLast(2))); + // v86: GetServerStateJson ends the table (which server this is, for every plugin). + Check(names.Last() == "GetServerStateJsonFn", "v86 slot last: " + names.Last()); Check(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SequenceEqual(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name)), "SDK table has the engine's slots in the same order"); Eq(Marshal.SizeOf<RynthCore.PluginSdk.RynthCoreApiNative>(), Marshal.SizeOf<RynthCore.Engine.Plugins.RynthCoreAPI>(), "SDK table size = engine table size"); Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("PutItemInContainerFn"), @@ -511,6 +632,14 @@ internal static class Program (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetObjectPropertiesFn"), "GetObjectPropertiesFn offset"); Eq((int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetObjectPropertiesFn"), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("RemoveClientObjectFn") + IntPtr.Size, "GetObjectPropertiesFn right after RemoveClientObjectFn"); + Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("ArmConfirmationFn"), + (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("ArmConfirmationFn"), "ArmConfirmationFn offset"); + Eq((int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("ArmConfirmationFn"), + (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetObjectPropertiesFn") + IntPtr.Size, "ArmConfirmationFn right after GetObjectPropertiesFn"); + Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("GetLastConfirmationFn"), + (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetLastConfirmationFn"), "GetLastConfirmationFn offset"); + Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("GetServerStateJsonFn"), + (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetServerStateJsonFn"), "GetServerStateJsonFn offset"); } private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { } diff --git a/tools/SectionsTests/Program.cs b/tools/SectionsTests/Program.cs new file mode 100644 index 0000000..890ff9f --- /dev/null +++ b/tools/SectionsTests/Program.cs @@ -0,0 +1,452 @@ +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.Sections; + +namespace SectionsTests; + +/// <summary> +/// The Mini Remote's sections, offline: per-character server overrides (server_force.txt), +/// plugin manifests (RynthPluginGetSectionsJson) and the section catalog built from them. +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + ForceText(); + ForceFile(); + ManifestBasics(); + ManifestRejects(); + ManifestLimits(); + CatalogCore(); + CatalogServers(); + CatalogPluginSections(); + DeclaredServers(); + SelectionPlan(); + NotLoadedServerList(); + SelectionCurrentPick(); + SelectionActiveAndOwner(); + StateJson(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + if (_checks == 0) { Console.WriteLine("ABORT: no checks ran."); return 1; } + Console.WriteLine(_failed == 0 ? "ALL SECTIONS TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + // ── Overrides ────────────────────────────────────────────────────── + + private static void ForceText() + { + Case("force text"); + Check(ServerForceText.TryParse("on", out ServerForce m) && m == ServerForce.On, "on"); + Check(ServerForceText.TryParse(" OFF ", out m) && m == ServerForce.Off, "OFF, padded"); + Check(ServerForceText.TryParse("auto", out m) && m == ServerForce.Auto, "auto"); + Check(!ServerForceText.TryParse("maybe", out _) && !ServerForceText.TryParse(null, out _), "junk and null"); + Check(ServerForceText.Name(ServerForce.On) == "on" && ServerForceText.Name(ServerForce.Auto) == "auto", "names"); + Check(ServerForceText.Apply(ServerForce.On, false), "On wins over not detected"); + Check(!ServerForceText.Apply(ServerForce.Off, true), "Off wins over detected"); + Check(ServerForceText.Apply(ServerForce.Auto, true) && !ServerForceText.Apply(ServerForce.Auto, false), "Auto follows detection"); + } + + private static void ForceFile() + { + Case("force file"); + var f = new ServerForceFile(); + Check(f.Set("Kelpie@ILT", "ilt", ServerForce.On), "set on"); + Check(!f.Set("Kelpie@ILT", "ilt", ServerForce.On), "same value again is no change"); + Check(f.Get("kelpie@ilt", "ILT") == ServerForce.On, "keys are case-insensitive"); + Check(f.Get("Other", "ilt") == ServerForce.Auto, "another character is Auto"); + Check(f.Set("Kelpie@ILT", "aelrynth", ServerForce.Off), "a second server"); + Check(f.For("Kelpie@ILT").Count == 2, "For lists both"); + + var round = ServerForceFile.Parse(f.Write().Split('\n')); + Check(round.Get("Kelpie@ILT", "ilt") == ServerForce.On && round.Get("Kelpie@ILT", "aelrynth") == ServerForce.Off, "round trip"); + + Check(f.Set("Kelpie@ILT", "ilt", ServerForce.Auto) && f.Get("Kelpie@ILT", "ilt") == ServerForce.Auto, "Auto removes"); + Check(!f.Set("Kelpie@ILT", "ilt", ServerForce.Auto), "removing again is no change"); + Check(!f.Set("bad\tkey", "ilt", ServerForce.On) && !f.Set("k", "a\nb", ServerForce.On), "tabs and line breaks refused"); + Check(!f.Set(new string('x', ServerForceFile.MaxFieldLength + 1), "ilt", ServerForce.On), "overlong key refused"); + Check(!f.Set("", "ilt", ServerForce.On) && !f.Set("k", " ", ServerForce.On), "empty fields refused"); + + var damaged = ServerForceFile.Parse(new[] { "# comment", "", "a\tilt", "a\tilt\tmaybe", "a\tilt\tauto", "b\tilt\ton\textra" }); + Check(damaged.For("a").Count == 0, "short, unknown and auto lines are skipped"); + Check(damaged.Get("b", "ilt") == ServerForce.On, "extra fields are ignored"); + Check(ServerForceFile.Parse(null).For("a").Count == 0, "no file"); + } + + // ── Manifests ────────────────────────────────────────────────────── + + private const string GoodManifest = """ + { + "version": 1, + "servers": [ { "id": "ilt", "name": "Infinite Leaftide", "worldNames": ["*Leaftide*"], "hosts": ["infiniteleaftide.online"] }, + { "id": "Frost-Haven", "name": "Frosthaven", "worldNames": ["Frosthaven"], "hosts": [] } ], + "sections": [ { "id": "quests", "label": "Quests", "order": 650 } ], + "contributions": [ + { "section": "pets", "server": "", "label": "Pets", "surface": "section:pets", "primary": true, "width": 560, "height": 580 }, + { "section": "skills", "server": "ilt", "label": "Progression", "command": "/rc progression", "tooltip": "line one\nline two" }, + { "section": "quests", "label": "Quests", "surface": "section:quests", "primary": true }, + { "section": "char", "server": "ilt", "label": "Off now", "command": "/ra x", "enabled": false, "note": "Not reported." } + ], + "future": { "ignored": true } + } + """; + + private static void ManifestBasics() + { + Case("manifest basics"); + SectionManifest m = SectionManifestParser.Parse("RynthAi", GoodManifest, out string err); + Check(err.Length == 0, "no error: " + err); + Check(m.Plugin == "RynthAi", "plugin name kept"); + Check(m.Servers.Length == 2 && m.Servers[1].Id == "frost-haven", "server ids lower-cased"); + Check(m.Servers[0].WorldNames.SequenceEqual(new[] { "*Leaftide*" }) && m.Servers[0].Hosts.Length == 1, "server lists"); + Check(m.Sections.Length == 1 && m.Sections[0].Order == 650, "a plugin section with its order"); + Check(m.Contributions.Length == 4, "four contributions"); + SectionContribution pets = m.Contributions[0]; + Check(pets.IsSurface && pets.IsUniversal && pets.Primary && pets.Width == 560 && pets.Height == 580, "surface fields"); + SectionContribution prog = m.Contributions[1]; + Check(!prog.IsSurface && prog.Command == "/rc progression" && prog.Server == "ilt" && prog.Enabled, "command fields"); + Check(prog.Tooltip.Contains('\n'), "tooltips keep line breaks"); + Check(m.Contributions[2].Order == 1000, "order defaults to 1000"); + Check(!m.Contributions[3].Enabled && m.Contributions[3].Note == "Not reported.", "disabled with a note"); + } + + private static void ManifestRejects() + { + Case("manifest rejects"); + Check(SectionManifestParser.Parse("p", null, out string e).Contributions.Length == 0 && e == "empty", "null"); + Check(SectionManifestParser.Parse("p", "[1,2]", out e).Contributions.Length == 0 && e.Length > 0, "not an object"); + Check(SectionManifestParser.Parse("p", "{ bad", out e).Contributions.Length == 0 && e.StartsWith("bad JSON"), "bad JSON"); + Check(SectionManifestParser.Parse("p", """{"version":0}""", out e).Contributions.Length == 0 && e.Length > 0, "version 0"); + + string deep = new string('[', 40) + new string(']', 40); + Check(SectionManifestParser.Parse("p", "{\"x\":" + deep + "}", out e).Contributions.Length == 0 && e.Length > 0, "too deep"); + + SectionManifest m = SectionManifestParser.Parse("p", """ + { "contributions": [ + { "section": "Bad Id!", "label": "x", "command": "/a" }, + { "section": "char", "label": "", "command": "/a" }, + { "section": "char", "label": "no action" }, + { "section": "char", "label": "not a command", "command": "say hi" }, + { "section": "char", "label": "two lines", "command": "/a\n/b" }, + { "section": "char", "label": "popout", "surface": "x:popout" }, + { "section": "char", "label": "odd surface", "surface": "a b" }, + { "section": "char", "label": "bad server", "server": "no way", "command": "/a" }, + { "section": "char", "label": "Line\nbreak", "command": "/ok", "width": -5, "height": 99999 } + ] } + """, out e); + Check(e.Length == 0, "entries are skipped, not the manifest"); + Check(m.Contributions.Length == 1, "only the good entry survives"); + SectionContribution c = m.Contributions.Single(); + Check(c.Label == "Line break", "labels lose line breaks"); + Check(c.Width == 0 && c.Height == SectionManifestParser.MaxSurfaceSize, "sizes clamped"); + + Check(SectionManifestParser.Id("ab_c-1") == "ab_c-1" && SectionManifestParser.Id("A B") == "", "ids"); + Check(SectionManifestParser.Id(new string('a', SectionManifestParser.MaxIdLength + 1)) == "", "long ids"); + Check(SectionManifestParser.Command("/x") == "/x" && SectionManifestParser.Command("/") == "", "commands"); + Check(SectionManifestParser.Surface("section:ilt-options") == "section:ilt-options", "a section surface"); + } + + private static void ManifestLimits() + { + Case("manifest limits"); + var items = string.Join(",", Enumerable.Range(0, 300).Select(i => $$"""{"section":"char","label":"L{{i}}","command":"/c {{i}}"}""")); + SectionManifest m = SectionManifestParser.Parse("p", "{\"contributions\":[" + items + "]}", out _); + Check(m.Contributions.Length == SectionManifestParser.MaxContributions, "contributions capped"); + + var servers = string.Join(",", Enumerable.Range(0, 40).Select(i => $$"""{"id":"s{{i}}"}""")); + m = SectionManifestParser.Parse("p", "{\"servers\":[" + servers + "]}", out _); + Check(m.Servers.Length == SectionManifestParser.MaxServers, "servers capped"); + + string big = "{\"x\":\"" + new string('a', SectionManifestParser.MaxJsonLength) + "\"}"; + Check(SectionManifestParser.Parse("p", big, out string e).Contributions.Length == 0 && e.StartsWith("too large"), "size capped"); + + string longLabel = new string('L', 200); + m = SectionManifestParser.Parse("p", $$"""{"contributions":[{"section":"char","label":"{{longLabel}}","command":"/a"}]}""", out _); + Check(m.Contributions[0].Label.Length == SectionManifestParser.MaxLabelLength, "labels capped"); + } + + // ── Catalog ──────────────────────────────────────────────────────── + + private static readonly ServerState IltOn = new("ilt", "Infinite Leaftide", true, true, ServerForce.Auto, true, "world"); + private static readonly ServerState IltOff = IltOn with { Active = false, Detected = false }; + private static readonly ServerState AelOff = new("aelrynth", "Aelrynth", false, false, ServerForce.Auto, true, ""); + + private static bool Panels(string title) => title is "Radar" or "Skills" or "Nav" or "Inventory" or "Items" or "Chat"; + + private static void CatalogCore() + { + Case("catalog core"); + List<SectionView> views = SectionCatalog.Build(Array.Empty<SectionManifest>(), Panels, new[] { IltOff, AelOff }); + string[] ids = views.Select(v => v.Id).ToArray(); + Check(ids.SequenceEqual(new[] { "char", "map", "skills", "combat", "nav", "inventory", "crafting", "spells", "chat", "friends", "fellowship", "pets" }), + "the twelve core sections, in order: " + string.Join(",", ids)); + Check(views.All(v => v.Core), "all core"); + Check(views[0].Panes.Single().Kind == SectionPaneKind.Overview, "Char starts with the overview"); + Check(views[0].Label == SectionCatalog.SessionStatsLabel && views[0].Label == "Session Stats", "the char section is labelled Session Stats"); + + // A plugin's universal primary surface in char (RynthAi's session stats) replaces the overview. + var session = SectionManifestParser.Parse("RynthAi", """ + { "contributions": [ { "section": "char", "label": "Session stats", "surface": "section:session", "primary": true } ] } + """, out _); + SectionView chr = SectionCatalog.Build(new[] { session }, Panels, new[] { IltOff }).Single(v => v.Id == "char"); + Check(chr.Panes.Single().Kind == SectionPaneKind.Surface && chr.Panes[0].Contribution!.Surface == "section:session", + "a universal primary surface drops the overview"); + // A server-scoped primary surface doesn't: the overview stays beside it. + var scoped = SectionManifestParser.Parse("p", """ + { "contributions": [ { "section": "char", "server": "ilt", "label": "ILT", "surface": "section:ilt", "primary": true } ] } + """, out _); + chr = SectionCatalog.Build(new[] { scoped }, Panels, new[] { IltOn }).Single(v => v.Id == "char"); + Check(chr.Panes.Any(p => p.Kind == SectionPaneKind.Overview), "a server-scoped surface keeps the overview"); + Check(views[1].Panes.Select(p => p.Panel).SequenceEqual(new[] { "Radar" }), "Map has only the panels that exist"); + Check(views[5].Panes.Select(p => p.Panel).SequenceEqual(new[] { "Inventory", "Items" }), "Inventory keeps panel order"); + Check(!views[3].HasContent && !views[11].HasContent, "Combat (no panels here) and Pets are empty"); + Check(SectionCatalog.FindCore("PETS")?.Id == "pets" && SectionCatalog.FindCore("remote") == null, "FindCore"); + Check(SectionCatalog.Build(Array.Empty<SectionManifest>(), _ => throw new InvalidOperationException(), new[] { IltOff }) + .All(v => v.Panes.All(p => p.Kind != SectionPaneKind.CorePanel)), "a throwing panel check means no panels"); + } + + private static void CatalogServers() + { + Case("catalog servers"); + SectionManifest m = SectionManifestParser.Parse("RynthAi", GoodManifest, out _); + + List<SectionView> off = SectionCatalog.Build(new[] { m }, Panels, new[] { IltOff, AelOff }); + SectionView pets = off.Single(v => v.Id == "pets"); + Check(pets.Panes.Single().Kind == SectionPaneKind.Surface && pets.Panes[0].Contribution!.Surface == "section:pets", "a primary surface is a pane"); + SectionView skills = off.Single(v => v.Id == "skills"); + Check(skills.Groups.Length == 0, "ILT items hidden while ILT is off"); + + List<SectionView> on = SectionCatalog.Build(new[] { m }, Panels, new[] { IltOn, AelOff }); + skills = on.Single(v => v.Id == "skills"); + Check(skills.Groups.Length == 1 && skills.Groups[0].Title == "Server: Infinite Leaftide" && skills.Groups[0].Server == IltOn, "ILT group while active"); + Check(skills.Groups[0].Items.Single().Command == "/rc progression", "its command"); + SectionView chr = on.Single(v => v.Id == "char"); + Check(chr.Groups.Single().Items.Single().Label == "Off now", "disabled items still listed (with their note)"); + + var universal = SectionManifestParser.Parse("Other", """ + { "contributions": [ { "section": "skills", "label": "Z", "command": "/z", "order": 5 }, + { "section": "skills", "label": "A", "command": "/a", "order": 5 } ] } + """, out _); + skills = SectionCatalog.Build(new[] { m, universal }, Panels, new[] { IltOn }).Single(v => v.Id == "skills"); + Check(skills.Groups.Select(g => g.Title).SequenceEqual(new[] { "Server: Infinite Leaftide", "Plugins" }), "server groups first, then Plugins"); + Check(skills.Groups[1].Items.Select(i => i.Label).SequenceEqual(new[] { "A", "Z" }), "equal orders sort by label"); + } + + private static void CatalogPluginSections() + { + Case("catalog plugin sections"); + SectionManifest m = SectionManifestParser.Parse("RynthAi", GoodManifest, out _); + List<SectionView> views = SectionCatalog.Build(new[] { m }, Panels, new[] { IltOff }); + int quests = views.FindIndex(v => v.Id == "quests"); + Check(quests >= 0 && !views[quests].Core, "the plugin's Quests section shows"); + Check(views[quests - 1].Id == "crafting" && views[quests + 1].Id == "spells", "order 650 puts it between Crafting (600) and Spells (700)"); + var empty = SectionManifestParser.Parse("p", """{ "sections": [ { "id": "empty", "label": "Empty" } ] }""", out _); + Check(SectionCatalog.Build(new[] { empty }, Panels, new[] { IltOff }).All(v => v.Id != "empty"), "an empty plugin section is hidden"); + var hijack = SectionManifestParser.Parse("p", """ + { "sections": [ { "id": "pets", "label": "Mine" }, { "id": "remote", "label": "Mine" } ], + "contributions": [ { "section": "remote", "label": "x", "command": "/x" } ] } + """, out _); + views = SectionCatalog.Build(new[] { hijack }, Panels, new[] { IltOff }); + Check(views.Count(v => v.Id == "pets") == 1 && views.Single(v => v.Id == "pets").Label == "Pets", "core ids can't be redeclared"); + Check(views.All(v => v.Id != "remote"), "the remote id can't be declared"); + var dup = SectionManifestParser.Parse("q", """ + { "sections": [ { "id": "quests", "label": "Other quests", "order": 1 } ], + "contributions": [ { "section": "quests", "label": "x", "command": "/x" } ] } + """, out _); + views = SectionCatalog.Build(new[] { m, dup }, Panels, new[] { IltOff }); + SectionView q = views.Single(v => v.Id == "quests"); + Check(q.Label == "Quests" && q.Order == 650, "the first declaration wins"); + Check(q.Panes.Length == 1 && q.Groups.Single().Items.Single().Plugin == "q", "both plugins' contributions land in it"); + } + + private static void DeclaredServers() + { + Case("declared servers"); + var decl = new SectionServerDecl("frosthaven", "Frosthaven", new[] { "Frosthaven*" }, new[] { "frosthaven.example" }); + Check(SectionCatalog.DetectDeclared(decl, "play.frosthaven.example", null, out string why) && why.Contains("host"), "by host"); + Check(SectionCatalog.DetectDeclared(decl, null, "Frosthaven PvE", out why) && why.Contains("world"), "by world name"); + Check(!SectionCatalog.DetectDeclared(decl, "infiniteleaftide.online", "InfiniteLeaftide", out _), "not another server"); + var none = new SectionServerDecl("x", "X", Array.Empty<string>(), Array.Empty<string>()); + Check(!SectionCatalog.DetectDeclared(none, "a", "b", out why) && why.StartsWith("no host or world-name list"), "no lists"); + } + + // -- Server selection (Diagnostics picker, "/rc server pick", plugin API v86) -- + + /// <summary>A server row as SectionRegistry builds it (Active = override applied to detection).</summary> + private static ServerState Srv(string id, bool detected, ServerForce force, bool builtIn = false) + => new(id, id.ToUpperInvariant(), ServerForceText.Apply(force, detected), detected, force, builtIn, detected ? "host matches" : ""); + + private static void SelectionPlan() + { + Case("selection plan"); + var servers = new[] { Srv("ilt", true, ServerForce.Auto, true), Srv("aelrynth", false, ServerForce.Off, true), Srv("frost", false, ServerForce.Auto) }; + + var pick = ServerSelection.Plan(servers, "FROST"); + Check(pick != null && pick.Count == 3, "a known id plans every server"); + Check(pick!.Single(p => p.Id == "frost").Force == ServerForce.On, "the pick is forced On (case-insensitive)"); + Check(pick.Where(p => p.Id != "frost").All(p => p.Force == ServerForce.Off), "every other server is forced Off"); + + var auto = ServerSelection.Plan(servers, " Auto "); + Check(auto != null && auto.All(p => p.Force == ServerForce.Auto), "auto resets every override"); + Check(ServerSelection.Plan(servers, "")!.All(p => p.Force == ServerForce.Auto), "empty means auto"); + Check(ServerSelection.Plan(servers, null)!.All(p => p.Force == ServerForce.Auto), "null means auto"); + Check(ServerSelection.Plan(servers, "nowhere") == null, "an unknown id is refused"); + Check(ServerSelection.Plan(Array.Empty<ServerState>(), "auto")!.Count == 0, "no servers, empty plan"); + } + + private static void NotLoadedServerList() + { + Case("not-loaded server plugins"); + var forces = new Dictionary<string, ServerForce>(StringComparer.OrdinalIgnoreCase) { ["coldeve"] = ServerForce.On }; + ServerForce Force(string id) => forces.TryGetValue(id, out ServerForce f) ? f : ServerForce.Auto; + var notLoaded = new[] + { + new NotLoadedServer("frost", "Frosthaven", "RynthFrostACE"), + new NotLoadedServer("coldeve", "Coldeve", "RynthColdeve"), + new NotLoadedServer("ilt", "Infinite Leaftide", "RynthILT"), // a built-in id: the built-in row wins + new NotLoadedServer("", "No id", "RynthBroken"), + }; + var list = new List<ServerState> { Srv("ilt", true, ServerForce.Auto, true) }; + NotLoadedServers.Append(list, notLoaded, Force); + Check(list.Count == 3, "each new id added once, the built-in and the blank id skipped"); + ServerState frost = list.Single(s => s.Id == "frost"); + Check(!frost.Active && !frost.Detected && !frost.BuiltIn && frost.Name == "Frosthaven", "not loaded: listed, not detected, not active"); + Check(frost.Reason.Contains("RynthFrostACE") && frost.Reason.Contains("pick it"), "the reason names the plugin and how to load it"); + ServerState coldeve = list.Single(s => s.Id == "coldeve"); + Check(coldeve.Active && coldeve.Force == ServerForce.On && coldeve.Reason.Contains("loading RynthColdeve"), "forced On: active, loading its plugin"); + Check(list.Single(s => s.Id == "ilt").BuiltIn, "the built-in ilt row is kept"); + Check(ServerSelection.Plan(list, "frost") != null, "a not-loaded server can be picked"); + + var load = NotLoadedServers.ForcedOn(notLoaded, Force); + Check(load.Count == 1 && load[0] == "coldeve", "only the server forced On asks for its plugin"); + forces["coldeve"] = ServerForce.Off; + Check(NotLoadedServers.ForcedOn(notLoaded, Force).Count == 0, "Off loads nothing"); + + // The connect host is nobody's (none load at start); the world name the server announces + // loads its plugin late, unless that server is forced Off. + var byWorld = new[] + { + new NotLoadedServer("frost", "Frosthaven", "RynthFrostACE", new[] { "Frosthaven*" }), + new NotLoadedServer("coldeve", "Coldeve", "RynthColdeve", new[] { "Coldeve" }), + }; + Check(NotLoadedServers.ToLoad(byWorld, Force, null).Count == 0, "before login: nothing loads by world name"); + var hit = NotLoadedServers.ToLoad(byWorld, Force, "Frosthaven PvE"); + Check(hit.Count == 1 && hit[0] == "frost", "the announced world name loads its server's plugin"); + Check(NotLoadedServers.ToLoad(byWorld, Force, "Coldeve").Count == 0, "a server forced Off isn't loaded by its world name"); + Check(NotLoadedServers.ToLoad(byWorld, Force, "Somewhere Else").Count == 0, "a world nobody lists loads nothing"); + } + + private static void SelectionCurrentPick() + { + Case("selection current pick"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.Auto), Srv("ael", false, ServerForce.Auto) }) == ServerSelection.Auto, "no overrides is auto"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.Off), Srv("ael", false, ServerForce.On) }) == "ael", "one On, rest Off is that pick"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.On), Srv("ael", false, ServerForce.On) }) == null, "two On is a mix"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.On), Srv("ael", false, ServerForce.Auto) }) == null, "one On, another Auto is a mix"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.Off), Srv("ael", false, ServerForce.Auto) }) == null, "only Offs is a mix"); + Check(ServerSelection.CurrentPick(Array.Empty<ServerState>()) == ServerSelection.Auto, "no servers is auto"); + + // A plan applied gives back the same pick. + var servers = new[] { Srv("ilt", true, ServerForce.Auto), Srv("ael", false, ServerForce.Auto) }; + var applied = ServerSelection.Plan(servers, "ael")!.Select(p => Srv(p.Id, servers.Single(s => s.Id == p.Id).Detected, p.Force)).ToArray(); + Check(ServerSelection.CurrentPick(applied) == "ael", "plan round trip"); + } + + private static void SelectionActiveAndOwner() + { + Case("selection active and owner"); + Check(ServerSelection.ActiveServer(new[] { Srv("ilt", true, ServerForce.Auto), Srv("frost", true, ServerForce.Auto) })!.Id == "ilt", "first detected wins"); + Check(ServerSelection.ActiveServer(new[] { Srv("ilt", true, ServerForce.Auto), Srv("frost", false, ServerForce.On) })!.Id == "frost", "forced On beats detection"); + Check(ServerSelection.ActiveServer(new[] { Srv("ilt", true, ServerForce.Off) }) == null, "Off hides a detected server"); + Check(ServerSelection.ActiveServer(Array.Empty<ServerState>()) == null, "none"); + + var pack = SectionManifestParser.Parse("RynthServerPack", """ + { "servers": [ { "id": "frost", "name": "Frosthaven", "hosts": [ "frost.example" ] } ] } + """, out _); + var ilt = SectionManifestParser.Parse("RynthILT", """ + { "contributions": [ { "section": "skills", "server": "ilt", "label": "A", "command": "/a" }, + { "section": "char", "server": "ilt", "label": "B", "command": "/b" } ] } + """, out _); + var ai = SectionManifestParser.Parse("RynthAi", """ + { "contributions": [ { "section": "skills", "server": "ilt", "label": "C", "command": "/c" }, + { "section": "skills", "server": "frost", "label": "D", "command": "/d" } ] } + """, out _); + var engine = SectionManifestParser.Parse("RynthCore", """ + { "servers": [ { "id": "ilt", "name": "Infinite Leaftide" } ] } + """, out _); + var all = new[] { engine, ai, ilt, pack }; + + Check(ServerSelection.OwnerPlugin(all, "frost", "RynthCore") == "RynthServerPack", "the declaring plugin owns a server"); + Check(ServerSelection.OwnerPlugin(all, "ILT", "RynthCore") == "RynthILT", "else the most contributions (engine skipped)"); + Check(ServerSelection.OwnerPlugin(all, "nowhere", "RynthCore") == "", "nobody"); + var tie = SectionManifestParser.Parse("Alpha", """ + { "contributions": [ { "section": "skills", "server": "x", "label": "A", "command": "/a" } ] } + """, out _); + var tie2 = SectionManifestParser.Parse("Beta", """ + { "contributions": [ { "section": "skills", "server": "x", "label": "A", "command": "/a" } ] } + """, out _); + Check(ServerSelection.OwnerPlugin(new[] { tie2, tie }, "x", "RynthCore") == "Alpha", "ties go to the name that sorts first"); + } + + private static unsafe void StateJson() + { + Case("state json"); + var ilt = SectionManifestParser.Parse("RynthILT", """ + { "contributions": [ { "section": "skills", "server": "ilt", "label": "A", "command": "/a" } ] } + """, out _); + var servers = new[] { Srv("ilt", true, ServerForce.Auto, true), Srv("aelrynth", false, ServerForce.Auto, true) }; + string json = ServerStateJson.Build(servers, new[] { ilt }, 7, "infiniteleaftide.online", "Infinite \"Leaf\"", "RynthCore"); + + using var doc = System.Text.Json.JsonDocument.Parse(json); + var root = doc.RootElement; + Check(root.GetProperty("schema").GetInt32() == ServerStateJson.Schema && root.GetProperty("revision").GetInt32() == 7, "schema and revision"); + Check(root.GetProperty("host").GetString() == "infiniteleaftide.online", "host"); + Check(root.GetProperty("world").GetString() == "Infinite \"Leaf\"", "world (quotes escaped)"); + Check(root.GetProperty("pick").GetString() == "auto", "pick auto"); + Check(root.GetProperty("active").GetString() == "ilt" && root.GetProperty("activeName").GetString() == "ILT", "active server"); + Check(root.GetProperty("activePlugin").GetString() == "RynthILT", "active server's owner plugin"); + var rows = root.GetProperty("servers"); + Check(rows.GetArrayLength() == 2, "every server listed"); + var first = rows[0]; + Check(first.GetProperty("id").GetString() == "ilt" && first.GetProperty("active").GetBoolean() && first.GetProperty("detected").GetBoolean(), "row state"); + Check(first.GetProperty("force").GetString() == "auto" && first.GetProperty("builtIn").GetBoolean(), "row override and built-in"); + Check(rows[1].GetProperty("plugin").GetString() == "" && rows[1].GetProperty("reason").GetString() == "", "row with no owner"); + + var mixed = new[] { Srv("ilt", true, ServerForce.On), Srv("ael", false, ServerForce.On) }; + using (var m = System.Text.Json.JsonDocument.Parse(ServerStateJson.Build(mixed, Array.Empty<SectionManifest>(), 1, null, null, "RynthCore"))) + Check(m.RootElement.GetProperty("pick").GetString() == "mixed" && m.RootElement.GetProperty("host").GetString() == "", "mixed pick, null host"); + using (var n = System.Text.Json.JsonDocument.Parse(ServerStateJson.Build(new[] { Srv("ilt", false, ServerForce.Auto) }, Array.Empty<SectionManifest>(), 1, "h", "w", "RynthCore"))) + Check(n.RootElement.GetProperty("active").GetString() == "" && n.RootElement.GetProperty("activePlugin").GetString() == "", "no active server"); + + // Write: the plugin API's buffer convention (length returned; nothing written when too small). + int length = System.Text.Encoding.UTF8.GetByteCount(json); + byte[] small = new byte[length]; + fixed (byte* p = small) + Check(ServerStateJson.Write(json, p, small.Length) == length && small.All(b => b == 0), "too small: length only, nothing written"); + Check(ServerStateJson.Write(json, null, 0) == length, "null buffer: length only"); + byte[] big = new byte[length + 1]; + fixed (byte* p = big) + Check(ServerStateJson.Write(json, p, big.Length) == length, "fits: length"); + Check(System.Text.Encoding.UTF8.GetString(big, 0, length) == json && big[length] == 0, "fits: text and NUL"); + } + + // ── Harness ──────────────────────────────────────────────────────── + + private static void Case(string name) + { + _case = name; + Console.WriteLine($"-- {name}"); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"FAIL [{_case}] {what}"); + } +} diff --git a/tools/SectionsTests/SectionsTests.csproj b/tools/SectionsTests/SectionsTests.csproj new file mode 100644 index 0000000..319dc22 --- /dev/null +++ b/tools/SectionsTests/SectionsTests.csproj @@ -0,0 +1,36 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for the Mini Remote's sections (src\RynthCore.Engine\UI\Sections, the pure + files compiled in): the per-character server overrides file, the plugin manifest parser and + its limits, and the section catalog (core sections, server-scoped contributions, ordering). + IltDetect.cs (with AelrynthWire.cs, which it shares a parser with) supplies the matching a + plugin-declared server is detected with. Nothing native: no AC, no engine state. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>SectionsTests</RootNamespace> + <!-- ServerStateJson.Write copies into a native (plugin API) buffer. --> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\ServerForce.cs" Link="Engine\ServerForce.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\SectionCatalog.cs" Link="Engine\SectionCatalog.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" /> + <!-- The Diagnostics server picker's plan and the plugin API v86 server-state JSON. --> + <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\ServerSelection.cs" Link="Engine\ServerSelection.cs" /> + <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\ServerStateJson.cs" Link="Engine\ServerStateJson.cs" /> + <!-- Installed server plugins the connect host left out: listed in the picker, loaded when forced On. --> + <Compile Include="..\..\src\RynthCore.Engine\UI\Sections\NotLoadedServers.cs" Link="Engine\NotLoadedServers.cs" /> + <!-- The status feed's / Session Stats' XP and luminance session formula (pure). --> + </ItemGroup> + +</Project> diff --git a/tools/StatusAgentTests/Program.cs b/tools/StatusAgentTests/Program.cs index 54d5c4b..7e501b0 100644 --- a/tools/StatusAgentTests/Program.cs +++ b/tools/StatusAgentTests/Program.cs @@ -33,6 +33,7 @@ internal static class Program StatusFileReads(); MoveProtocol(); LogRollover(); + ServeGuards(); if (Arg(args, "--atlas") is { } atlas) RealAtlas(atlas); if (portal != null) RealSpellTable(portal); if (cell != null) RealWorldMap(cell, outFile); @@ -42,6 +43,53 @@ internal static class Program return _failed == 0 ? 0 : 1; } + // ── serve guards (remote access) ──────────────────────────────────────── + + private static void ServeGuards() + { + Section("status server: loopback, token length, lockout, bounded bodies, log-safe text"); + Check(ServeGuard.IsLoopbackPrefix("http://127.0.0.1:8740/"), "127.0.0.1 is loopback"); + Check(ServeGuard.IsLoopbackPrefix("http://localhost:8740/"), "localhost is loopback"); + Check(ServeGuard.IsLoopbackPrefix("http://[::1]:8740/"), "[::1] is loopback"); + Check(!ServeGuard.IsLoopbackPrefix("http://+:8740/"), "+ is every address"); + Check(!ServeGuard.IsLoopbackPrefix("http://*:8740/"), "* is every address"); + Check(!ServeGuard.IsLoopbackPrefix("http://100.64.1.2:8740/"), "a Tailscale address is not"); + Check(!ServeGuard.IsLoopbackPrefix("http://127.0.0.1.evil.example:8740/"), "a name starting 127.0.0.1 is not"); + + Check(ServeGuard.TokenProblem("http://127.0.0.1:8740/", "") != null, "no token: never serves"); + Check(ServeGuard.TokenProblem("http://127.0.0.1:8740/", "short") == null, "loopback: any token"); + Check(ServeGuard.TokenProblem("http://+:8740/", "short") != null, "remote bind: a short token is refused"); + Check(ServeGuard.TokenProblem("http://+:8740/", new string('k', 16)) == null, "remote bind: 16 characters is fine"); + + var t = new AuthThrottle(); + var lan = System.Net.IPAddress.Parse("192.168.1.50"); + var t0 = new DateTime(2026, 10, 13, 12, 0, 0, DateTimeKind.Utc); + bool started = false; + for (int i = 0; i < AuthThrottle.MaxFailures - 1; i++) started |= t.Fail(lan, t0.AddSeconds(i)); + Check(!started && !t.IsBlocked(lan, t0.AddSeconds(10)), "under the limit: not blocked"); + Check(t.Fail(lan, t0.AddSeconds(10)), "the limit starts a lockout (reported once)"); + Check(t.IsBlocked(lan, t0.AddMinutes(4)), "still blocked inside the lockout"); + Check(!t.IsBlocked(lan, t0.AddMinutes(6)), "free again after it"); + var slow = System.Net.IPAddress.Parse("192.168.1.51"); + for (int i = 0; i < AuthThrottle.MaxFailures * 2; i++) t.Fail(slow, t0.AddSeconds(i * 61)); + Check(!t.IsBlocked(slow, t0.AddSeconds(AuthThrottle.MaxFailures * 2 * 61)), "failures spread past the window don't add up"); + var other = System.Net.IPAddress.Parse("192.168.1.52"); + for (int i = 0; i < AuthThrottle.MaxFailures - 1; i++) t.Fail(other, t0); + t.Succeed(other); + Check(!t.Fail(other, t0), "a good token clears the count"); + for (int i = 0; i < AuthThrottle.MaxFailures * 2; i++) t.Fail(System.Net.IPAddress.Loopback, t0); + Check(!t.IsBlocked(System.Net.IPAddress.Loopback, t0), "loopback is never locked out"); + + Check(ServeGuard.TryReadBounded(new MemoryStream(Encoding.UTF8.GetBytes("{\"pid\":1}")), 9, 64, null, out string small) && small == "{\"pid\":1}", "a small body reads"); + Check(!ServeGuard.TryReadBounded(new MemoryStream(new byte[100]), 100, 64, null, out _), "a declared length over the limit is refused"); + Check(!ServeGuard.TryReadBounded(new MemoryStream(new byte[100]), -1, 64, null, out _), "chunked (no length) over the limit is refused"); + Check(ServeGuard.TryReadBounded(new MemoryStream(new byte[64]), -1, 64, null, out _), "exactly the limit reads"); + + Check(ServeGuard.LogSafe("a\r\nFAKE LOG LINE") == "a FAKE LOG LINE", "CR/LF can't start a log line"); + Check(ServeGuard.LogSafe(new string('x', 500), 10) == "xxxxxxxxxx...", "capped"); + Check(ServeGuard.LogSafe(null) == "", "null is empty"); + } + // ── log rollover ──────────────────────────────────────────────────────── private static void LogRollover() diff --git a/tools/StatusAgentTests/StatusAgentTests.csproj b/tools/StatusAgentTests/StatusAgentTests.csproj index 6ce4287..23c8933 100644 --- a/tools/StatusAgentTests/StatusAgentTests.csproj +++ b/tools/StatusAgentTests/StatusAgentTests.csproj @@ -32,6 +32,7 @@ <Compile Include="..\..\src\RynthCore.StatusAgent\NavAtlasService.cs" Link="Agent\NavAtlasService.cs" /> <Compile Include="..\..\src\RynthCore.StatusAgent\Dat\DatDatabase.cs" Link="Agent\Dat\DatDatabase.cs" /> <Compile Include="..\..\src\RynthCore.StatusAgent\StatusFileCache.cs" Link="Agent\StatusFileCache.cs" /> + <Compile Include="..\..\src\RynthCore.StatusAgent\ServeGuard.cs" Link="Agent\ServeGuard.cs" /> </ItemGroup> <ItemGroup> diff --git a/tools/check_imgui_calls.py b/tools/check_imgui_calls.py index 324a052..a8908f2 100644 --- a/tools/check_imgui_calls.py +++ b/tools/check_imgui_calls.py @@ -8,6 +8,15 @@ thread - the first time that line runs. Run after adding ImGui code: python tools/check_imgui_calls.py Exit code 1 lists the calls with no matching export. + +It also flags ImGui.Text / TextColored / TextWrapped / TextDisabled / +BulletText / SetTooltip / SetItemTooltip / LabelText(value) calls anywhere in +the engine whose text isn't a plain literal: ImGui.NET passes that text to +native ImGui as a printf format, so a '%' in it reads missing arguments. Such +text goes through SafeImGui instead. To check another tree (a RynthSuite +checkout's Plugins folder) for those calls only: + + python tools/check_imgui_calls.py C:/path/to/RynthSuite/Plugins """ import re import struct @@ -16,7 +25,8 @@ from pathlib import Path ROOT = Path(__file__).resolve().parent.parent DLL = ROOT / "src" / "RynthCore.Engine" / "Native" / "cimgui.dll" -SOURCES = ROOT / "src" / "RynthCore.Engine" / "ImGui" +ENGINE = ROOT / "src" / "RynthCore.Engine" +SOURCES = ENGINE / "ImGui" # Old diagnostic shell, FORCE-gated and never run: not held to this check. SKIP = {"RynthCoreShell.cs"} @@ -58,7 +68,202 @@ def pe_exports(path: Path) -> set[str]: return names +# --- Text drawn as a printf format ------------------------------------------- +# ImGui.NET hands the string of these calls to native ImGui as a printf format +# with no arguments: a '%' in a chat line, name, server reply or setting reads +# arguments that were never passed (garbage, or a crash on %s / %n). Text that +# isn't a literal goes through SafeImGui (engine: ImGui/SafeImGui.cs, RynthSuite: +# Plugins/Shared/SafeImGui.cs), which doubles every '%'. The number is the +# index of the format argument. +FORMAT_TEXT_CALLS = { + "Text": 0, "TextColored": 1, "TextWrapped": 0, "TextDisabled": 0, + "BulletText": 0, "SetTooltip": 0, "SetItemTooltip": 0, "LabelText": 1, +} +FORMAT_CALL_RE = re.compile( + r"(?<![\w.])(?:ImGuiNET\.)?ImGui\.(" + "|".join(FORMAT_TEXT_CALLS) + r")\s*\(") +STRING_START_RE = re.compile(r'(\$*)(@?)(\$*)"') +# The wrappers themselves pass their (escaped) text on. +FORMAT_SKIP = {"SafeImGui.cs"} + + +def skip_token(s: str, i: int): + """End of the comment, string or char literal starting at i, else None.""" + if s.startswith("//", i): + j = s.find("\n", i) + return len(s) if j < 0 else j + if s.startswith("/*", i): + j = s.find("*/", i + 2) + return len(s) if j < 0 else j + 2 + c = s[i] + if c == "'": + j = i + 1 + while j < len(s) and s[j] != "'": + j += 2 if s[j] == "\\" else 1 + return j + 1 + if c not in '"$@': + return None + m = STRING_START_RE.match(s, i) + if not m: + return None + dollars = len(m.group(1)) + len(m.group(3)) + verbatim = bool(m.group(2)) + q = m.end() - 1 + n = 0 + while q + n < len(s) and s[q + n] == '"': + n += 1 + if n == 2: # "" + return q + 2 + if n >= 3: # raw string literal + j = q + n + close = '"' * n + while j < len(s) and not s.startswith(close, j): + if dollars and s.startswith("{" * dollars, j): + j = skip_code(s, j + dollars, "}") + 1 + else: + j += 1 + return j + n + j = q + 1 + while j < len(s): + ch = s[j] + if ch == "\\" and not verbatim: + j += 2 + elif ch == '"': + if verbatim and s.startswith('""', j): + j += 2 + else: + return j + 1 + elif dollars and ch == "{": + if s.startswith("{{", j): + j += 2 + else: + j = skip_code(s, j + 1, "}") + 1 + else: + j += 1 + return j + + +def skip_code(s: str, i: int, closer: str) -> int: + """Index of the closer that ends the code starting at i (nesting, strings and comments skipped).""" + depth = 0 + j = i + while j < len(s): + end = skip_token(s, j) + if end is not None: + j = end + continue + ch = s[j] + if ch in "([{": + depth += 1 + elif ch in ")]}": + if depth == 0 and ch == closer: + return j + depth -= 1 + j += 1 + return j + + +def call_args(s: str, open_paren: int): + """[(start, end)] of each top-level argument of the call whose '(' is at open_paren.""" + args = [] + depth = 0 + start = open_paren + 1 + j = start + while j < len(s): + end = skip_token(s, j) + if end is not None: + j = end + continue + ch = s[j] + if ch in "([{": + depth += 1 + elif ch in ")]}": + if depth == 0: + args.append((start, j)) + return args, j + depth -= 1 + elif ch == "," and depth == 0: + args.append((start, j)) + start = j + 1 + j += 1 + return args, j + + +def literal_kind(arg: str) -> str: + """'literal' for plain string literals (joined with '+' at most), 'percent' for such + literals holding a lone '%', else 'expression'.""" + j = 0 + pieces = [] + while j < len(arg): + ch = arg[j] + if ch.isspace() or ch == "+": + j += 1 + continue + end = skip_token(arg, j) + if end is None: + return "expression" + piece = arg[j:end] + if not (piece.startswith("//") or piece.startswith("/*")): + if piece[0] not in '"@$' or "$" in piece[:piece.index('"')]: + return "expression" + pieces.append(piece) + j = end + if not pieces: + return "expression" + return "percent" if any("%" in p.replace("%%", "") for p in pieces) else "literal" + + +def format_text_calls(text: str): + """Every format-text ImGui call in C# source: (match, arg_start, arg_end, kind). + Calls inside comments and strings (e.g. Lua script text) are skipped.""" + code = [] + j = 0 + while j < len(text): + end = skip_token(text, j) + if end is None: + code.append(text[j]) + j += 1 + else: + code.append("".join(c if c == "\n" else " " for c in text[j:end])) + j = end + masked = "".join(code) + for m in FORMAT_CALL_RE.finditer(masked): + args, _ = call_args(text, m.end() - 1) + index = FORMAT_TEXT_CALLS[m.group(1)] + if index >= len(args): + yield m, m.end(), m.end(), "expression" + continue + a, b = args[index] + yield m, a, b, literal_kind(text[a:b]) + + +def unsafe_format_text(roots) -> list[str]: + found = [] + for root in roots: + for f in sorted(Path(root).rglob("*.cs")): + if f.name in FORMAT_SKIP or {"bin", "obj"} & set(f.parts): + continue + text = f.read_text(encoding="utf-8-sig") + for m, a, b, kind in format_text_calls(text): + if kind == "literal": + continue + line = text.count("\n", 0, m.start()) + 1 + what = "a literal with a lone '%'" if kind == "percent" else "text that isn't a literal" + found.append(f"{f}:{line}: ImGui.{m.group(1)} with {what}: {' '.join(text[a:b].split())[:80]}") + return found + + def main() -> int: + # python tools/check_imgui_calls.py DIR... checks only the format text under DIR + # (e.g. a RynthSuite checkout's Plugins folder). + if len(sys.argv) > 1: + unsafe = unsafe_format_text(sys.argv[1:]) + if unsafe: + print("ImGui text calls that draw non-literal text as a printf format (use SafeImGui):") + print("\n".join(" " + u for u in unsafe)) + return 1 + print("OK: no ImGui text call draws non-literal text as a format.") + return 0 + exports = pe_exports(DLL) def found(prefix: str, name: str) -> bool: @@ -70,7 +275,7 @@ def main() -> int: if f.name in SKIP: continue text = f.read_text(encoding="utf-8") - for m in re.finditer(r"ImGui(?:NET\.ImGui)?\.(\w+)\(", text): + for m in re.finditer(r"(?<!\w)ImGui(?:NET\.ImGui)?\.(\w+)\(", text): if not found("ig", m.group(1)): missing.append(f"{f.relative_to(ROOT)}:{text.count(chr(10), 0, m.start()) + 1}: ImGui.{m.group(1)}") # Direct native calls name the exact export (overload suffix included). @@ -81,11 +286,17 @@ def main() -> int: if not found(MEMBER_PREFIX[m.group(1)], m.group(2)): missing.append(f"{f.relative_to(ROOT)}:{text.count(chr(10), 0, m.start()) + 1}: {m.group(1)}.{m.group(2)}") + unsafe = unsafe_format_text([ENGINE]) + if missing: print("ImGui calls with no export in cimgui.dll:") print("\n".join(" " + m for m in missing)) + if unsafe: + print("ImGui text calls that draw non-literal text as a printf format (use SafeImGui):") + print("\n".join(" " + u for u in unsafe)) + if missing or unsafe: return 1 - print(f"OK: every ImGui call resolves ({len(exports)} exports).") + print(f"OK: every ImGui call resolves ({len(exports)} exports); no text call draws non-literal text as a format.") return 0 From aba17a98341722af5d831b649a38fd9ac44cbb90 Mon Sep 17 00:00:00 2001 From: Tom Bohar <tombohar@gmail.com> Date: Thu, 15 Oct 2026 21:40:00 -0400 Subject: [PATCH 3/6] Snapshot for release 2026.10.15.3 (internal ea85b68) --- .../Compatibility/MemoryUse.cs | 152 ++++++++++++++++++ src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs | 2 + src/RynthCore.Engine/EntryPoint.cs | 1 + src/RynthCore.Engine/ImGui/DX9Backend.cs | 10 ++ .../ImGui/EngineFrameController.cs | 6 + src/RynthCore.Engine/ImGui/ImGuiFonts.cs | 88 +++++++++- src/RynthCore.Engine/Plugins/PluginManager.cs | 6 + 7 files changed, 260 insertions(+), 5 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/MemoryUse.cs diff --git a/src/RynthCore.Engine/Compatibility/MemoryUse.cs b/src/RynthCore.Engine/Compatibility/MemoryUse.cs new file mode 100644 index 0000000..a262447 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/MemoryUse.cs @@ -0,0 +1,152 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/MemoryUse.cs +// +// Where the memory goes while the engine and its plugins start (a client start or a +// hot reload). 2026-10-15: a reload frees the old engine (~550 MB of address space +// back) and the new one takes ~400 MB again within two seconds of the plugins starting, +// all of it freshly touched, so the working set jumps from ~480 MB to ~1.1 GB. The log +// had no per-plugin numbers, so nobody could say what takes it. +// +// Mark(label) logs one "[Mem]" line with private bytes (committed), the .NET heap +// (all managed plugins share the one runtime), the working set and free address +// space, each with its change since the last mark. StartBurst samples every 100 ms for +// a while and logs every rise of BurstStepMb or more in private bytes with the last +// mark's label, so work a plugin does after its Init returns (a background load, its +// first ticks) is still caught. Never throws; any thread. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static class MemoryUse +{ + /// <summary>A burst logs each rise in private bytes of at least this much.</summary> + private const long BurstStepMb = 16; + + [StructLayout(LayoutKind.Sequential)] + private struct PROCESS_MEMORY_COUNTERS_EX + { + public uint cb; + public uint PageFaultCount; + public nuint PeakWorkingSetSize; + public nuint WorkingSetSize; + public nuint QuotaPeakPagedPoolUsage; + public nuint QuotaPagedPoolUsage; + public nuint QuotaPeakNonPagedPoolUsage; + public nuint QuotaNonPagedPoolUsage; + public nuint PagefileUsage; + public nuint PeakPagefileUsage; + public nuint PrivateUsage; + } + + [DllImport("kernel32.dll")] + private static extern IntPtr GetCurrentProcess(); + + [DllImport("psapi.dll", SetLastError = true)] + private static extern bool GetProcessMemoryInfo(IntPtr process, out PROCESS_MEMORY_COUNTERS_EX counters, uint size); + + /// <summary>One reading, in MB (-1 when a value couldn't be read).</summary> + internal readonly record struct Reading(long PrivateMb, long WorkingSetMb, long GcHeapMb, long GcCommittedMb, long VaFreeMb); + + private static readonly object Gate = new(); + private static Reading _lastMark; + private static bool _haveMark; + private static volatile string _label = "start"; + private static int _burstRunning; + + public static Reading Read() + { + long priv = -1, ws = -1, gcHeap = -1, gcCommit = -1; + try + { + var c = new PROCESS_MEMORY_COUNTERS_EX { cb = (uint)Marshal.SizeOf<PROCESS_MEMORY_COUNTERS_EX>() }; + if (GetProcessMemoryInfo(GetCurrentProcess(), out c, c.cb)) + { + priv = (long)((ulong)c.PrivateUsage >> 20); + ws = (long)((ulong)c.WorkingSetSize >> 20); + } + } + catch { } + try + { + GCMemoryInfo gc = GC.GetGCMemoryInfo(); + gcHeap = gc.HeapSizeBytes >> 20; + gcCommit = gc.TotalCommittedBytes >> 20; + } + catch { } + long va = AddressSpace.FreeAndLargestMb().FreeMb; + return new Reading(priv, ws, gcHeap, gcCommit, va); + } + + /// <summary>Logs a reading with its change since the last mark, and names what runs next.</summary> + public static void Mark(string label) + { + try + { + Reading now = Read(); + Reading prev; + bool had; + lock (Gate) + { + prev = _lastMark; + had = _haveMark; + _lastMark = now; + _haveMark = true; + _label = label; + } + RynthLog.Info($"[Mem] {label}: {Format(now, had ? prev : (Reading?)null)}"); + } + catch { } + } + + /// <summary> + /// Samples every 100 ms for <paramref name="seconds"/> and logs each rise in private + /// bytes of BurstStepMb or more, with the label of the last <see cref="Mark"/>. One + /// burst at a time. + /// </summary> + public static void StartBurst(int seconds, string why) + { + if (Interlocked.Exchange(ref _burstRunning, 1) == 1) return; + try + { + var t = new Thread(() => + { + try + { + Reading start = Read(); + Reading last = start; + RynthLog.Info($"[Mem] burst for {seconds} s ({why}): {Format(start, null)}"); + long end = Environment.TickCount64 + seconds * 1000L; + while (Environment.TickCount64 < end) + { + Thread.Sleep(100); + Reading r = Read(); + if (r.PrivateMb >= 0 && last.PrivateMb >= 0 && r.PrivateMb - last.PrivateMb >= BurstStepMb) + { + RynthLog.Info($"[Mem] +{r.PrivateMb - last.PrivateMb} MB private during '{_label}': {Format(r, last)}"); + last = r; + } + } + Reading done = Read(); + RynthLog.Info($"[Mem] burst done ({why}): {Format(done, start)} (change over the whole burst)"); + } + catch { } + finally { Interlocked.Exchange(ref _burstRunning, 0); } + }) + { IsBackground = true, Name = "RynthCore.MemoryUse" }; + t.Start(); + } + catch { Interlocked.Exchange(ref _burstRunning, 0); } + } + + private static string Format(Reading r, Reading? prev) + { + static string D(long now, long? before) => before is long b && b >= 0 && now >= 0 ? $" ({now - b:+0;-0})" : ""; + return $"private {r.PrivateMb} MB{D(r.PrivateMb, prev?.PrivateMb)}, .NET heap {r.GcHeapMb} MB{D(r.GcHeapMb, prev?.GcHeapMb)}" + + $" (committed {r.GcCommittedMb}{D(r.GcCommittedMb, prev?.GcCommittedMb)}), working set {r.WorkingSetMb} MB{D(r.WorkingSetMb, prev?.WorkingSetMb)}," + + $" free address space {r.VaFreeMb} MB{D(r.VaFreeMb, prev?.VaFreeMb)}"; + } +} diff --git a/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs b/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs index 7b2b5a0..d7a6bf9 100644 --- a/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs +++ b/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs @@ -80,7 +80,9 @@ internal static class D3D9Bootstrapper if (earlyModule != IntPtr.Zero) { RynthLog.D3D9("D3D9Bootstrapper: d3d9.dll loaded — discovering EndScene via NULLREF device."); + Compatibility.MemoryUse.Mark("D3D9 bootstrap: NULLREF device for the vtable"); EndSceneHook.Install("post-login-vtable"); + Compatibility.MemoryUse.Mark("EndScene hook installed"); return; } diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 6d79c83..3a70045 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -1153,6 +1153,7 @@ public static class EntryPoint if (avalonia && !dcompTest) AvaloniaOverlay.Start(); RynthLog.Info("RynthCore bootstrap initialized."); + Compatibility.MemoryUse.Mark("bootstrap initialized"); } catch (Exception ex) { diff --git a/src/RynthCore.Engine/ImGui/DX9Backend.cs b/src/RynthCore.Engine/ImGui/DX9Backend.cs index 1152a97..92a2b1d 100644 --- a/src/RynthCore.Engine/ImGui/DX9Backend.cs +++ b/src/RynthCore.Engine/ImGui/DX9Backend.cs @@ -951,6 +951,16 @@ internal static unsafe class DX9Backend // Store texture ID for ImGui io.Fonts.SetTexID(_fontTexture); + + // The glyphs are baked and uploaded: the atlas's input data is no longer read. ImGui + // copies the whole TTF into the atlas for every font it adds (main font, Segoe UI + // Symbol and Phosphor per size, ~3.8 MB each), so with the panel text sizes in use + // that was ~400 MB kept for the life of the atlas (2026-10-15, [Mem] lines). Every + // re-bake builds a fresh atlas from ImGuiFonts' own copies, and the pixels and TexReady + // stay, so nothing needs it back. + Compatibility.MemoryUse.Mark("font atlas uploaded"); + io.Fonts.ClearInputData(); + Compatibility.MemoryUse.Mark("font input data freed"); return true; } diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index e625a32..945e34c 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -134,14 +134,17 @@ internal static class EngineFrameController // Before any context exists: the loaded cimgui.dll must be the exact // build ImGui.NET wraps, or every struct read below is at wrong offsets. + Compatibility.MemoryUse.Mark("ImGui init: before the self-test"); if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle)) return false; + Compatibility.MemoryUse.Mark("ImGui self-test done"); IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); if (previousContext != IntPtr.Zero) RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context."); _context = ImGuiNET.ImGui.CreateContext(); + Compatibility.MemoryUse.Mark("ImGui context created"); bool initSucceeded = false; try { @@ -179,6 +182,7 @@ internal static class EngineFrameController _uiScale = UiScale.ForWindow(_gameHwnd); RynthLog.UI($"EngineFrameController: ImGui scale {_uiScale:0.##} (Avalonia input scale {UI.AvaloniaOverlay.InputScale:0.##})."); RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), _uiScale); + Compatibility.MemoryUse.Mark("ImGui theme applied"); ImGuiFonts.Build(io, _uiScale); if (!Win32Backend.Init(_gameHwnd)) @@ -187,11 +191,13 @@ internal static class EngineFrameController return false; } + Compatibility.MemoryUse.Mark("Win32 backend ready"); if (!DX9Backend.InitImGui(pDevice)) { _initFailStep = "DX9Backend.InitImGui"; return false; } + Compatibility.MemoryUse.Mark("DX9 backend ready (font texture)"); _lastFrameTicks = Stopwatch.GetTimestamp(); _imguiInitialized = true; diff --git a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs index 2f09d46..85cc710 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs @@ -8,8 +8,13 @@ // Consolas 9/10/12 (Tracker, Log, Meta rows), Cascadia Mono 12 (Meta // source; Consolas if missing), and the chat monospace at 8-18 in steps // of 2 (the chat font slider snaps to the nearest). -// The few symbol glyphs still drawn as text (SymbolCodepoints) are merged in -// from Segoe UI Symbol wherever the main font lacks them. +// The few symbol glyphs still drawn as text (SymbolCodepoints) come from the +// main font itself (Segoe UI, Consolas and Cascadia Mono all have them); Segoe UI +// Symbol is merged only into a font whose file lacks one (HasGlyphs). ImGui copies +// the whole TTF into the atlas for every font it adds, and Segoe UI Symbol is +// 2.4 MB: merged into every size (~107 with the panel text sizes) it made ~250 MB +// of the atlas's input data for three glyphs (2026-10-15). DX9Backend frees the +// input data once the texture is uploaded (ClearInputData). // // Icons: the Phosphor icon font (MIT, Assets/Fonts/Phosphor.ttf, embedded in // this assembly) is merged into every baked font, the scaled sets included, @@ -57,7 +62,8 @@ internal static unsafe class ImGuiFonts private static readonly string FontsDir = Environment.GetFolderPath(Environment.SpecialFolder.Fonts); // Main text: Basic Latin + Latin-1, general punctuation (— – … • ‘ ’ “ ”), arrows. - private static readonly ushort[] MainRanges = { 0x0020, 0x00FF, 0x2010, 0x2027, 0x2190, 0x21FF, 0 }; + // Plus the SymbolCodepoints (≤ ≥ ●), which the main fonts have. + private static readonly ushort[] MainRanges = { 0x0020, 0x00FF, 0x2010, 0x2027, 0x2190, 0x21FF, 0x2264, 0x2265, 0x25CF, 0x25CF, 0 }; // Symbols still drawn as text, merged from Segoe UI Symbol where the main font // lacks them. The panels' other symbols (⚔ ✦ ➤ ◫ ♥ ◆ ⚙ ▾ ▴ ↗ ↙ ◢ ✕ ☑ ☐ ▶ ▼ ▲ ◀ ■ @@ -81,6 +87,8 @@ internal static unsafe class ImGuiFonts // Phosphor's regular strokes are 1/16 em: at 9-13 px they rasterize thin and grey. private const float IconRasterizerMultiply = 1.2f; private static volatile bool _preloaded; + // Fonts the last AddAll merged Segoe UI Symbol into (their file lacked a symbol glyph). + private static int _symbolMerges; private static readonly List<IntPtr> NativeBuffers = new(); private static readonly ImFontPtr[] Fonts = new ImFontPtr[(int)UiFont.Count]; @@ -197,6 +205,7 @@ internal static unsafe class ImGuiFonts { long t0 = Stopwatch.GetTimestamp(); PrepareNativeData(); + Compatibility.MemoryUse.Mark("font files read"); ScaledFonts.Clear(); AddAll(io.Fonts, scale, RynthCore.Engine.UI.PanelTextScale.StepsInUse(), Fonts, ScaledFonts); @@ -208,8 +217,9 @@ internal static unsafe class ImGuiFonts double ms = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency; RynthLog.UI($"ImGuiFonts: {CountBaked()} fonts queued at scale {scale:0.##} in {ms:0.0} ms " + - $"(Cascadia Mono {(_cascadia != null ? "found" : "missing, using Consolas")}, symbols {(_symbol != null ? "merged" : "missing")}, " + + $"(Cascadia Mono {(_cascadia != null ? "found" : "missing, using Consolas")}, symbols from the main fonts{(_symbolMerges > 0 ? $" (Segoe UI Symbol merged into {_symbolMerges})" : "")}, " + $"icons {(_phosphor != null ? $"{IconCount()} merged" : "missing")})."); + Compatibility.MemoryUse.Mark("ImGui fonts queued"); } /// <summary>The font files and glyph ranges as native memory, made once (rebuilds reuse them). AC thread.</summary> @@ -250,6 +260,16 @@ internal static unsafe class ImGuiFonts ImFontPtr[] target = baseSet; float factor = 1f; + // Whether each main font file lacks a symbol glyph (only then is Segoe UI Symbol merged in). + _symbolMerges = 0; + var needsSymbol = new Dictionary<byte[], bool>(ReferenceEqualityComparer.Instance); + bool NeedsSymbol(byte[] b) + { + if (!needsSymbol.TryGetValue(b, out bool need)) + needsSymbol[b] = need = !HasGlyphs(b, SymbolCodepoints); + return need; + } + void Add(UiFont id, IntPtr data, byte[]? bytes, FaceMetrics metrics, float px) { if (data == IntPtr.Zero || bytes == null) return; @@ -259,8 +279,9 @@ internal static unsafe class ImGuiFonts { cfg.FontDataOwnedByAtlas = false; target[(int)id] = atlas.AddFontFromMemoryTTF(data, bytes.Length, size, cfg, (IntPtr)mainRanges); - if (symbol != IntPtr.Zero && _symbol != null) + if (symbol != IntPtr.Zero && _symbol != null && NeedsSymbol(bytes)) { + _symbolMerges++; cfg.MergeMode = true; cfg.GlyphMinAdvanceX = 0; atlas.AddFontFromMemoryTTF(symbol, _symbol.Length, size, cfg, (IntPtr)symbolRanges); @@ -534,6 +555,63 @@ internal static unsafe class ImGuiFonts private static int IconCount() => new HashSet<char>(PhosphorIcons.Baked).Count; + /// <summary> + /// True when the TrueType font has a glyph for every code point (its cmap, format 4: + /// the Basic Multilingual Plane). False when unreadable, so the caller falls back to + /// merging. Pure: tools\PanelTextScaleTests can drive it. + /// </summary> + internal static bool HasGlyphs(byte[]? ttf, ushort[] codepoints) + { + if (ttf == null || ttf.Length < 12) return false; + try + { + static int U16(byte[] b, int at) => b[at] << 8 | b[at + 1]; + static int U32(byte[] b, int at) => b[at] << 24 | b[at + 1] << 16 | b[at + 2] << 8 | b[at + 3]; + int cmap = -1; + int tables = U16(ttf, 4); + for (int i = 0; i < tables; i++) + { + int rec = 12 + i * 16; + if (U32(ttf, rec) == 0x636D6170) { cmap = U32(ttf, rec + 8); break; } // "cmap" + } + if (cmap < 0) return false; + int subtables = U16(ttf, cmap + 2); + for (int s = 0; s < subtables; s++) + { + int sub = cmap + U32(ttf, cmap + 4 + s * 8 + 4); + if (U16(ttf, sub) != 4) continue; + int segX2 = U16(ttf, sub + 6), ends = sub + 14, starts = ends + segX2 + 2; + int deltas = starts + segX2, offsets = deltas + segX2; + bool all = true; + foreach (ushort cp in codepoints) + { + int glyph = 0; + for (int k = 0; k < segX2 / 2; k++) + { + int end = U16(ttf, ends + k * 2), start = U16(ttf, starts + k * 2); + if (cp > end) continue; + if (cp < start) break; + int delta = (short)U16(ttf, deltas + k * 2), ro = U16(ttf, offsets + k * 2); + if (ro == 0) glyph = (cp + delta) & 0xFFFF; + else + { + glyph = U16(ttf, offsets + k * 2 + ro + 2 * (cp - start)); + if (glyph != 0) glyph = (glyph + delta) & 0xFFFF; + } + break; + } + if (glyph == 0) { all = false; break; } + } + return all; + } + return false; + } + catch (IndexOutOfRangeException) + { + return false; + } + } + /// <summary> /// A TrueType font's em as a fraction of the ImGui pixel size (ImGui sizes a /// font so hhea ascent - descent = the size) and half its cap height in em. diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 3a4555e..59c3e08 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -328,6 +328,9 @@ internal static partial class PluginManager public static void LoadPlugins(string engineDir) { + // Where the memory goes while the plugins start (Compatibility/MemoryUse.cs). + Compatibility.MemoryUse.Mark("before the plugins load"); + Compatibility.MemoryUse.StartBurst(60, "plugins starting"); if (_loaded) return; @@ -2688,6 +2691,7 @@ internal static partial class PluginManager RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath} (va before: {Compatibility.AddressSpace.Describe()})"); var plugin = PluginLoader.LoadSingle(dllPath, _shadowRootDir, _loadGeneration); RynthLog.Plugin($"PluginManager: loaded {Path.GetFileName(dllPath)}{(plugin == null ? " (FAILED)" : "")} (va after: {Compatibility.AddressSpace.Describe()})"); + Compatibility.MemoryUse.Mark($"{Path.GetFileNameWithoutExtension(dllPath)} loaded"); if (plugin != null) { plugin.Manifest = manifest; @@ -2827,6 +2831,7 @@ internal static partial class PluginManager plugin.UIInitializedDispatched = false; plugin.LoginCompleteDispatched = false; RynthLog.Plugin($"PluginManager: {plugin.DisplayName} initialized OK (api v{PluginContractVersion.Current})."); + Compatibility.MemoryUse.Mark($"{plugin.DisplayName} Init"); } else { @@ -2939,6 +2944,7 @@ internal static partial class PluginManager plugin.OnLoginComplete(); plugin.LoginCompleteDispatched = true; RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnLoginComplete."); + Compatibility.MemoryUse.Mark($"{plugin.DisplayName} OnLoginComplete"); } catch (Exception ex) { From bd97e41345c7563de99bb4a5286da6941d492895 Mon Sep 17 00:00:00 2001 From: BlankenshipG <Silentkelpie@Gmail.com> Date: Thu, 15 Oct 2026 12:39:09 -0400 Subject: [PATCH 4/6] fix(engine): DAT share hook covers the 2025 client's private CreateFileW slot The 2025 ACClient.exe (0.0.11.6096) resolves kernel32!CreateFileW on first use into a private slot (0x00837374) and opens every DAT through it. Since 2026.10.5.61 the hook only patched import tables, so no DAT open was shared: the first client held the DATs deny-write and every later client failed with "Can't open the data files". - LazyImportSlotScanner finds the Layer-for-Unicode stubs by their full byte pattern and returns the slots they fill. - DatFileShareHooks hooks those slots with the same detours and restores them on uninstall; an unresolved slot calls the kernel32 export directly. - tools/DatShareSlotTests: 20 checks, including the real 2025 client. Co-authored-by: Cursor <cursoragent@cursor.com> --- ...e-private-createfilew-slot-2026.10.5.64.md | 65 +++++ .../Compatibility/DatFileShareHooks.cs | 87 ++++++- .../Compatibility/LazyImportSlotScanner.cs | 187 ++++++++++++++ .../DatShareSlotTests.csproj | 24 ++ tools/DatShareSlotTests/Program.cs | 241 ++++++++++++++++++ 5 files changed, 592 insertions(+), 12 deletions(-) create mode 100644 Changelog/2026-10-15-dat-share-private-createfilew-slot-2026.10.5.64.md create mode 100644 src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs create mode 100644 tools/DatShareSlotTests/DatShareSlotTests.csproj create mode 100644 tools/DatShareSlotTests/Program.cs diff --git a/Changelog/2026-10-15-dat-share-private-createfilew-slot-2026.10.5.64.md b/Changelog/2026-10-15-dat-share-private-createfilew-slot-2026.10.5.64.md new file mode 100644 index 0000000..0d89b2e --- /dev/null +++ b/Changelog/2026-10-15-dat-share-private-createfilew-slot-2026.10.5.64.md @@ -0,0 +1,65 @@ +# 2026.10.5.64 - engine: second client can open the DAT files again (2025 client) + +Previous release: 2026.10.5.62. + +## Problem + +With "Allow multiple clients" on, only the first client started. Every client launched after it +(Silentstorm, SK, ...) showed "Can't open the data files. Check that they exist and that you +have permission to write to them. The program will now exit." about half a second after the +engine loaded. + +The 2025 client (`C:\Turbine\Asheron's Call-ryn\ACClient.exe`, 0.0.11.6096) does not import +`kernel32!CreateFileW`. A Layer-for-Unicode style stub at `0x006B8D00` looks it up on first use +and stores it in a private slot at `0x00837374`, and AC opens every DAT file through that slot. + +- Up to 2026.10.5.60 the DAT share hook detoured the kernel32 export, so it caught those opens. + The log showed them as `Compat: DAT share - W [filtered]: client_portal.dat ... share=0x1->0x7`. +- 2026.10.5.61 moved the hook to the import tables of `acclient.exe` and `MSVCR70.dll`, to keep + Direct3D and drivers out of it. The private slot is in no import table, so from .61 on no DAT + open was rewritten. The `W [filtered]` lines stopped appearing. +- The first client then opened the DATs read/write and denied writes to everyone else + (`share=0x1`). A second client's own read/write open failed with a sharing violation. + +Confirmed on the running client: the three import slots pointed at the engine's detours, but the +private slot `0x00837374` still held `kernel32!CreateFileW`. + +## Change + +- The DAT share hook also finds acclient.exe's private CreateFileW/CreateFileA slots, then points + them at the same detours. Uninstall restores them like the import slots. +- The slots are found by the stub's full byte pattern, not a fixed address: + - push slot, push the function name, push "kernel32.dll", call the resolver, then + `jmp [slot]` through the same slot; + - the name must stand alone ("MyCreateFileW" does not count); + - the DLL operand must name kernel32.dll. +- If the slot hasn't been resolved yet (it still points at its stub), the detour calls + `kernel32!CreateFileW` directly, because calling the stub would overwrite the slot. +- Direct3D, drivers, the runtime and plugins still call CreateFile without the engine in the way. +- The startup log lists the slot, for example + `Compat: DAT share - hooked acclient.exe!CreateFileW private slot (stub 0x006B8D00) (slot 0x00837374, was 0x76ACEA10).` + With multi-client on, the `W [filtered]: client_portal.dat` lines come back. + +## Code + +- `src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs` (new): reads the section table + of a mapped image and finds the stubs (`ReadSections`, `FindSlots`). +- `src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs`: + - `HookLazySlots` hooks the private slots; + - `HookSlot` builds the A/W detour for import slots and private slots alike; + - the log line names the kind of slot. +- `tools/DatShareSlotTests` (new), 20 checks: + - synthetic stubs; + - near misses that must not match (another jmp slot, another DLL, a longer name, no call, a + slot outside the image, a lone push of the name); + - the real 2025 client: slot `0x00837374`, stub `0x006B8D00`, no CreateFileA slot. + +## Tests + +- `dotnet run -c Release --project tools\DatShareSlotTests`: 20 checks, 0 failed. +- `dotnet build src\RynthCore.Engine -c Release`: 0 errors, no new warnings. + +## Before updating + +Close the other clients first. A client already running on .61/.62 holds the DATs deny-write, +so a new client can't start alongside it until it is closed, even on .64. diff --git a/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs b/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs index c7c3e7e..0126653 100644 --- a/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs +++ b/src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs @@ -29,8 +29,13 @@ namespace RynthCore.Engine.Compatibility; /// /// Why IAT-hook instead of MinHook on the kernel32 export: /// Only the modules that open AC's data files are hooked: acclient.exe -/// (imports CreateFileA) and its CRT MSVCR70.dll (CreateFileA/W, behind -/// fopen/_wfopen). A kernel32 export hook also caught every other module, +/// (imports CreateFileA), its CRT MSVCR70.dll (CreateFileA/W, behind +/// fopen/_wfopen), and acclient.exe's private CreateFileW slot, which the +/// 2025 client fills on first use and opens every DAT through (it is in no +/// import table; <see cref="LazyImportSlotScanner"/>). Missing that slot let +/// the first client open the DATs read/write, deny-write, and every later +/// client failed with "Can't open the data files" (2026-10-15). +/// A kernel32 export hook also caught every other module, /// including d3d9.dll and the GPU driver while AC created its device: their /// CreateFile calls went through managed code, could wait on the runtime /// while plugins loaded, and on some PCs AC then failed with "Could not @@ -138,11 +143,20 @@ internal static class DatFileShareHooks return; } - // acclient.exe opens DATs with its own CreateFileA import; its CRT + // acclient.exe opens DATs with its own CreateFileA import, or (the 2025 client) + // through a private CreateFileW slot its Layer-for-Unicode stub fills; its CRT // (MSVCR70.dll, statically imported, so loaded by now) does fopen/_wfopen // opens through its CreateFileA/W imports. Nothing else is hooked. HookModuleImports("acclient.exe", moduleBase); HookModuleImports("MSVCR70.dll", GetModuleHandleW("MSVCR70.dll")); + try + { + HookLazySlots(moduleBase); + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: DAT share - private slot scan failed: {ex.Message}"); + } if (_iatHooks.Count == 0) { @@ -177,20 +191,69 @@ internal static class DatFileShareHooks return; } - if (TryPatchIatSlot(moduleBase, "CreateFileW", out IntPtr wSlot, out IntPtr wCurrent)) + foreach (string function in new[] { "CreateFileW", "CreateFileA" }) { - CreateFileWDelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(wCurrent); + if (TryPatchIatSlot(moduleBase, function, out IntPtr slot, out IntPtr current)) + HookSlot(moduleName, function, "import", slot, current, current); + } + } + + /// <summary> + /// Points acclient.exe's private CreateFileA/W slots (filled on first use by a Layer-for-Unicode + /// style stub, see <see cref="LazyImportSlotScanner"/>) at the detours. The 2025 client opens + /// its DAT files through the CreateFileW one; it is not in any import table. + /// </summary> + private static unsafe void HookLazySlots(IntPtr moduleBase) + { + byte* basePtr = (byte*)moduleBase; + int peOffset = *(int*)(basePtr + 0x3C); + uint sizeOfImage = *(uint*)(basePtr + peOffset + 24 + 56); + var image = new ReadOnlySpan<byte>(basePtr, (int)sizeOfImage); + uint imageBase = (uint)moduleBase.ToInt32(); + var sections = LazyImportSlotScanner.ReadSections(image); + + foreach (string function in new[] { "CreateFileW", "CreateFileA" }) + { + foreach (LazyImportSlot lazy in LazyImportSlotScanner.FindSlots(image, imageBase, sections, "kernel32.dll", function)) + { + var slot = (IntPtr)(int)lazy.SlotVa; + IntPtr current = Marshal.ReadIntPtr(slot); + // Not resolved yet: the slot still points at its stub inside acclient.exe. Calling + // the stub would overwrite the slot with the real function (dropping the detour), + // so the detour calls the kernel32 export the stub would have resolved. + IntPtr target = current; + if ((uint)current.ToInt32() - imageBase < sizeOfImage) + target = GetProcAddress(GetModuleHandleW("kernel32.dll"), function); + if (target == IntPtr.Zero) + { + RynthLog.Compat($"Compat: DAT share - kernel32!{function} not found; private slot 0x{lazy.SlotVa:X8} left alone."); + continue; + } + HookSlot("acclient.exe", function, $"private slot (stub 0x{lazy.StubVa:X8})", slot, current, target); + } + } + } + + /// <summary> + /// Builds the detour for <paramref name="function"/> calling <paramref name="callTarget"/>, + /// and points <paramref name="slot"/> at it. <paramref name="restoreValue"/> is what + /// <see cref="Uninstall"/> writes back. + /// </summary> + private static void HookSlot(string moduleName, string function, string kind, IntPtr slot, IntPtr restoreValue, IntPtr callTarget) + { + if (function == "CreateFileW") + { + CreateFileWDelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(callTarget); CreateFileWDelegate detour = (name, access, share, security, disposition, flags, template) => CreateFileWDetour(original, name, access, share, security, disposition, flags, template); - InstallSlot(moduleName, "CreateFileW", wSlot, wCurrent, detour, Marshal.GetFunctionPointerForDelegate(detour)); + InstallSlot(moduleName, function, kind, slot, restoreValue, detour, Marshal.GetFunctionPointerForDelegate(detour)); } - - if (TryPatchIatSlot(moduleBase, "CreateFileA", out IntPtr aSlot, out IntPtr aCurrent)) + else { - CreateFileADelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(aCurrent); + CreateFileADelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(callTarget); CreateFileADelegate detour = (name, access, share, security, disposition, flags, template) => CreateFileADetour(original, name, access, share, security, disposition, flags, template); - InstallSlot(moduleName, "CreateFileA", aSlot, aCurrent, detour, Marshal.GetFunctionPointerForDelegate(detour)); + InstallSlot(moduleName, function, kind, slot, restoreValue, detour, Marshal.GetFunctionPointerForDelegate(detour)); } } @@ -198,7 +261,7 @@ internal static class DatFileShareHooks /// Records the hook (so the delegate stays reachable) before the slot is written: the /// detour can run on any thread the moment the pointer lands. /// </summary> - private static void InstallSlot(string moduleName, string function, IntPtr slot, IntPtr original, Delegate detour, IntPtr detourPtr) + private static void InstallSlot(string moduleName, string function, string kind, IntPtr slot, IntPtr original, Delegate detour, IntPtr detourPtr) { var hook = new IatHook(moduleName, function, slot, original, detour); _iatHooks.Add(hook); @@ -206,7 +269,7 @@ internal static class DatFileShareHooks if (WriteIatPointer(slot, detourPtr)) { - RynthLog.Info($"Compat: DAT share - hooked {moduleName}!{function} import (slot 0x{slot.ToInt32():X8}, was 0x{original.ToInt32():X8})."); + RynthLog.Info($"Compat: DAT share - hooked {moduleName}!{function} {kind} (slot 0x{slot.ToInt32():X8}, was 0x{original.ToInt32():X8})."); return; } diff --git a/src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs b/src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs new file mode 100644 index 0000000..d1a5c87 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Engine.Compatibility; + +/// <summary>One section of a PE image as it is mapped in memory (RVA layout, not file layout).</summary> +internal readonly record struct ImageSection(string Name, uint Rva, uint Size, bool Executable); + +/// <summary>A private function-pointer slot filled by a lazy-resolve stub, and the stub that fills it.</summary> +internal readonly record struct LazyImportSlot(uint SlotVa, uint StubVa); + +/// <summary> +/// Finds the private pointer slots that Layer-for-Unicode style stubs fill on first use. +/// +/// The 2025 ACClient.exe (0.0.11.6096) does not import kernel32!CreateFileW. It resolves it the +/// first time it is called, with a stub of this exact shape, and every call goes through the slot: +/// <code> +/// 68 xx xx xx xx push fallback +/// FF 35 xx xx xx xx push [module handle cache] +/// 68 SS SS SS SS push slot (the pointer the stub fills) +/// 68 NN NN NN NN push "CreateFileW" +/// 68 DD DD DD DD push "kernel32.dll" +/// E8 xx xx xx xx call resolver +/// FF 25 SS SS SS SS jmp [slot] +/// </code> +/// AC opens its DAT files through that slot, so a hook on the import table alone never sees them. +/// The pattern is matched in full (both slot operands must agree, and the DLL operand must name +/// <c>dll</c>), so a stray push of the name string is never taken for a stub. +/// </summary> +internal static class LazyImportSlotScanner +{ + private const byte PushImm32 = 0x68; + private const byte CallRel32 = 0xE8; + private const int IMAGE_SCN_CNT_CODE = 0x00000020; + private const int IMAGE_SCN_MEM_EXECUTE = 0x20000000; + + // Offsets inside the stub, from the "push name" instruction. + private const int SlotPushBack = 5; // push slot sits right before push name + private const int DllPushAhead = 5; // push dll sits right after it + private const int CallAhead = 10; + private const int JmpAhead = 15; // FF 25 <slot>, after the 5-byte call + private const int StubHeadBytes = 11; // push fallback (5) + push [handle cache] (6), before push slot + + /// <summary> + /// Reads the section table of a PE32 image mapped at RVA layout (a module's memory, or a test + /// buffer laid out the same way). Returns an empty list when the headers don't parse. + /// </summary> + public static List<ImageSection> ReadSections(ReadOnlySpan<byte> image) + { + var sections = new List<ImageSection>(); + if (image.Length < 0x40) + return sections; + + int pe = BitConverter.ToInt32(image.Slice(0x3C, 4)); + if (pe <= 0 || pe + 24 > image.Length || BitConverter.ToUInt32(image.Slice(pe, 4)) != 0x00004550) // "PE\0\0" + return sections; + + int count = BitConverter.ToUInt16(image.Slice(pe + 6, 2)); + int optionalSize = BitConverter.ToUInt16(image.Slice(pe + 20, 2)); + int table = pe + 24 + optionalSize; + for (int i = 0; i < count; i++) + { + int h = table + 40 * i; + if (h + 40 > image.Length) + break; + string name = Encoding.ASCII.GetString(image.Slice(h, 8)).TrimEnd('\0'); + uint virtualSize = BitConverter.ToUInt32(image.Slice(h + 8, 4)); + uint rva = BitConverter.ToUInt32(image.Slice(h + 12, 4)); + uint rawSize = BitConverter.ToUInt32(image.Slice(h + 16, 4)); + int flags = BitConverter.ToInt32(image.Slice(h + 36, 4)); + uint size = virtualSize != 0 ? virtualSize : rawSize; + // Clamp to the buffer: a section can't be scanned past the mapped image. + if (rva >= image.Length) + continue; + size = (uint)Math.Min(size, image.Length - rva); + bool executable = (flags & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE)) != 0; + sections.Add(new ImageSection(name, rva, size, executable)); + } + return sections; + } + + /// <summary> + /// Every slot a stub fills with <paramref name="dll"/>!<paramref name="function"/>, as absolute + /// addresses (the stubs push absolute addresses, already relocated to <paramref name="imageBase"/>). + /// </summary> + public static List<LazyImportSlot> FindSlots(ReadOnlySpan<byte> image, uint imageBase, + IReadOnlyList<ImageSection> sections, string dll, string function) + { + var found = new List<LazyImportSlot>(); + Span<byte> needle = stackalloc byte[5]; + foreach (uint nameVa in FindNameStrings(image, imageBase, sections, function)) + { + needle[0] = PushImm32; + BitConverter.TryWriteBytes(needle.Slice(1), nameVa); + + foreach (ImageSection code in sections) + { + if (!code.Executable) + continue; + ReadOnlySpan<byte> text = image.Slice((int)code.Rva, (int)code.Size); + int from = 0; + while (true) + { + int hit = text.Slice(from).IndexOf(needle); + if (hit < 0) + break; + int at = from + hit; + from = at + 1; + if (TryReadStub(text, at, image, imageBase, dll, out uint slotVa)) + found.Add(new LazyImportSlot(slotVa, imageBase + code.Rva + (uint)Math.Max(0, at - SlotPushBack - StubHeadBytes))); + } + } + } + return found; + } + + // The NUL-terminated name, not as the tail of a longer identifier (e.g. "MyCreateFileW"). + private static IEnumerable<uint> FindNameStrings(ReadOnlySpan<byte> image, uint imageBase, + IReadOnlyList<ImageSection> sections, string function) + { + byte[] name = Encoding.ASCII.GetBytes(function + "\0"); + var hits = new List<uint>(); + foreach (ImageSection s in sections) + { + if (s.Executable) + continue; + ReadOnlySpan<byte> data = image.Slice((int)s.Rva, (int)s.Size); + int from = 0; + while (true) + { + int hit = data.Slice(from).IndexOf(name); + if (hit < 0) + break; + int at = from + hit; + from = at + 1; + if (at > 0 && IsIdentifierByte(data[at - 1])) + continue; + hits.Add(imageBase + s.Rva + (uint)at); + } + } + return hits; + } + + private static bool TryReadStub(ReadOnlySpan<byte> text, int namePush, ReadOnlySpan<byte> image, + uint imageBase, string dll, out uint slotVa) + { + slotVa = 0; + int slotPush = namePush - SlotPushBack; + if (slotPush < 0 || namePush + JmpAhead + 6 > text.Length) + return false; + if (text[slotPush] != PushImm32 + || text[namePush + DllPushAhead] != PushImm32 + || text[namePush + CallAhead] != CallRel32 + || text[namePush + JmpAhead] != 0xFF || text[namePush + JmpAhead + 1] != 0x25) + return false; + + uint slot = BitConverter.ToUInt32(text.Slice(slotPush + 1, 4)); + uint jmpSlot = BitConverter.ToUInt32(text.Slice(namePush + JmpAhead + 2, 4)); + if (slot != jmpSlot || !InImage(slot, 4, imageBase, image.Length)) + return false; + + uint dllVa = BitConverter.ToUInt32(text.Slice(namePush + DllPushAhead + 1, 4)); + if (!string.Equals(ReadAsciiz(image, imageBase, dllVa), dll, StringComparison.OrdinalIgnoreCase)) + return false; + + slotVa = slot; + return true; + } + + private static bool InImage(uint va, int size, uint imageBase, int imageLength) => + va >= imageBase && (long)va - imageBase + size <= imageLength; + + private static string? ReadAsciiz(ReadOnlySpan<byte> image, uint imageBase, uint va) + { + if (!InImage(va, 1, imageBase, image.Length)) + return null; + ReadOnlySpan<byte> rest = image.Slice((int)(va - imageBase)); + int end = rest.IndexOf((byte)0); + if (end < 0 || end > 260) + return null; + return Encoding.ASCII.GetString(rest.Slice(0, end)); + } + + private static bool IsIdentifierByte(byte b) => + b is >= (byte)'A' and <= (byte)'Z' or >= (byte)'a' and <= (byte)'z' or >= (byte)'0' and <= (byte)'9' or (byte)'_'; +} diff --git a/tools/DatShareSlotTests/DatShareSlotTests.csproj b/tools/DatShareSlotTests/DatShareSlotTests.csproj new file mode 100644 index 0000000..d9c2d7b --- /dev/null +++ b/tools/DatShareSlotTests/DatShareSlotTests.csproj @@ -0,0 +1,24 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + Offline checks for src\RynthCore.Engine\Compatibility\LazyImportSlotScanner.cs (2026-10-15): + the 2025 ACClient.exe resolves kernel32!CreateFileW into a private slot on first use and opens + its DAT files through it, so the DAT share hook has to find that slot as well as the import + slots. Synthetic images cover the stub shape and the near misses that must not match; when the + 2025 client is on this PC (or RYNTH_ACCLIENT points at one) its real slot is checked too. + Run: dotnet run -c Release (exit 0 = pass, 1 = fail) + --> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net10.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>DatShareSlotTests</RootNamespace> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\..\src\RynthCore.Engine\Compatibility\LazyImportSlotScanner.cs" Link="Engine\LazyImportSlotScanner.cs" /> + </ItemGroup> + +</Project> diff --git a/tools/DatShareSlotTests/Program.cs b/tools/DatShareSlotTests/Program.cs new file mode 100644 index 0000000..431c8b8 --- /dev/null +++ b/tools/DatShareSlotTests/Program.cs @@ -0,0 +1,241 @@ +using System.Text; +using RynthCore.Engine.Compatibility; + +namespace DatShareSlotTests; + +/// <summary> +/// LazyImportSlotScanner: finds the private CreateFileW slot the 2025 ACClient.exe fills on first +/// use. Without it the DAT share hook missed every DAT open and a second client failed with +/// "Can't open the data files" (2026-10-15). +/// </summary> +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + // Synthetic image layout: headers, .text at 0x1000 (code), .rdata at 0x2000 (strings + slots). + private const uint ImageBase = 0x00400000; + private const uint TextRva = 0x1000; + private const uint DataRva = 0x2000; + private const int ImageSize = 0x3000; + private const uint DllRva = DataRva + 0x10; + private const uint NameRva = DataRva + 0x40; + private const uint SlotRva = DataRva + 0x100; + + private static int Main() + { + ReadsSections(); + FindsTheStub(); + UnresolvedOrResolvedSlotIsFoundTheSame(); + RejectsJmpThroughAnotherSlot(); + RejectsAnotherDll(); + RejectsNameAsTailOfLongerName(); + RejectsBrokenStubShape(); + OtherFunctionHasNoSlot(); + Real2025Client(); + + Console.WriteLine($"{_checks} check(s), {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"[FAIL] {_case}: {what}"); + } + + // ── synthetic image ────────────────────────────────────────────────────── + + /// <summary>A minimal PE32 header with .text and .rdata, plus "kernel32.dll" and the name.</summary> + private static byte[] NewImage(string functionName = "CreateFileW", string dllName = "kernel32.dll") + { + var img = new byte[ImageSize]; + const int pe = 0x80; + BitConverter.TryWriteBytes(img.AsSpan(0x3C), pe); + Encoding.ASCII.GetBytes("PE\0\0").CopyTo(img, pe); + BitConverter.TryWriteBytes(img.AsSpan(pe + 6), (ushort)2); // NumberOfSections + BitConverter.TryWriteBytes(img.AsSpan(pe + 20), (ushort)0xE0); // SizeOfOptionalHeader + BitConverter.TryWriteBytes(img.AsSpan(pe + 24), (ushort)0x10B); // PE32 + int table = pe + 24 + 0xE0; + WriteSection(img, table, ".text", TextRva, 0x1000, 0x60000020); + WriteSection(img, table + 40, ".rdata", DataRva, 0x1000, 0x40000040); + Encoding.ASCII.GetBytes(dllName + "\0").CopyTo(img, DllRva); + Encoding.ASCII.GetBytes(functionName + "\0").CopyTo(img, NameRva); + return img; + } + + private static void WriteSection(byte[] img, int at, string name, uint rva, uint size, uint flags) + { + Encoding.ASCII.GetBytes(name.PadRight(8, '\0')).CopyTo(img, at); + BitConverter.TryWriteBytes(img.AsSpan(at + 8), size); + BitConverter.TryWriteBytes(img.AsSpan(at + 12), rva); + BitConverter.TryWriteBytes(img.AsSpan(at + 16), size); + BitConverter.TryWriteBytes(img.AsSpan(at + 20), rva); + BitConverter.TryWriteBytes(img.AsSpan(at + 36), flags); + } + + /// <summary>Writes the stub at <paramref name="stubRva"/>, the same bytes the 2025 client has.</summary> + private static void WriteStub(byte[] img, uint stubRva, uint slotVa, uint nameVa, uint dllVa, uint jmpSlotVa) + { + var code = new List<byte>(); + code.Add(0x68); code.AddRange(BitConverter.GetBytes(0x00405BB3u)); // push fallback + code.Add(0xFF); code.Add(0x35); code.AddRange(BitConverter.GetBytes(0x00906788u)); // push [handle cache] + code.Add(0x68); code.AddRange(BitConverter.GetBytes(slotVa)); + code.Add(0x68); code.AddRange(BitConverter.GetBytes(nameVa)); + code.Add(0x68); code.AddRange(BitConverter.GetBytes(dllVa)); + code.Add(0xE8); code.AddRange(BitConverter.GetBytes(0xFFD4CD41u)); // call resolver + code.Add(0xFF); code.Add(0x25); code.AddRange(BitConverter.GetBytes(jmpSlotVa)); // jmp [slot] + code.CopyTo(img, (int)stubRva); + } + + private static List<LazyImportSlot> Scan(byte[] img, string function = "CreateFileW") => + LazyImportSlotScanner.FindSlots(img, ImageBase, LazyImportSlotScanner.ReadSections(img), "kernel32.dll", function); + + // ── cases ──────────────────────────────────────────────────────────────── + + private static void ReadsSections() + { + _case = "sections"; + var s = LazyImportSlotScanner.ReadSections(NewImage()); + Check(s.Count == 2, $"two sections, got {s.Count}"); + Check(s.Count == 2 && s[0].Name == ".text" && s[0].Executable && s[0].Rva == TextRva, ".text is code at 0x1000"); + Check(s.Count == 2 && s[1].Name == ".rdata" && !s[1].Executable && s[1].Rva == DataRva, ".rdata is data at 0x2000"); + Check(LazyImportSlotScanner.ReadSections(new byte[0x100]).Count == 0, "no PE signature: nothing"); + } + + private static void FindsTheStub() + { + _case = "stub"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + var found = Scan(img); + Check(found.Count == 1, $"one slot, got {found.Count}"); + Check(found.Count == 1 && found[0].SlotVa == ImageBase + SlotRva, $"slot 0x{ImageBase + SlotRva:X8}"); + Check(found.Count == 1 && found[0].StubVa == ImageBase + TextRva + 0x20, $"stub at 0x{ImageBase + TextRva + 0x20:X8}, got 0x{(found.Count == 1 ? found[0].StubVa : 0):X8}"); + } + + private static void UnresolvedOrResolvedSlotIsFoundTheSame() + { + _case = "slot contents"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + BitConverter.TryWriteBytes(img.AsSpan((int)SlotRva), ImageBase + TextRva + 0x20); // still points at its stub + Check(Scan(img).Count == 1, "unresolved (slot points at the stub)"); + BitConverter.TryWriteBytes(img.AsSpan((int)SlotRva), 0x76ACEA10u); // resolved to kernel32 + Check(Scan(img).Count == 1, "resolved (slot points into kernel32)"); + } + + private static void RejectsJmpThroughAnotherSlot() + { + _case = "jmp slot"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva + 8); + Check(Scan(img).Count == 0, "the jmp must go through the slot the stub fills"); + } + + private static void RejectsAnotherDll() + { + _case = "dll"; + var img = NewImage(dllName: "user32.dll"); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + Check(Scan(img).Count == 0, "a stub resolving from user32.dll is not kernel32's CreateFileW"); + var upper = NewImage(dllName: "KERNEL32.DLL"); + WriteStub(upper, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + Check(Scan(upper).Count == 1, "the DLL name matches in any case"); + } + + private static void RejectsNameAsTailOfLongerName() + { + _case = "longer name"; + var img = NewImage(functionName: "MyCreateFileW"); + // Points at the "CreateFileW" tail of "MyCreateFileW". + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva + 2, ImageBase + DllRva, ImageBase + SlotRva); + Check(Scan(img).Count == 0, "\"MyCreateFileW\" is not CreateFileW"); + } + + private static void RejectsBrokenStubShape() + { + _case = "shape"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + img[TextRva + 0x20 + 26] = 0x90; // the call becomes a nop + Check(Scan(img).Count == 0, "no call to the resolver: not a stub"); + + var outside = NewImage(); + WriteStub(outside, TextRva + 0x20, 0x12345678, ImageBase + NameRva, ImageBase + DllRva, 0x12345678); + Check(Scan(outside).Count == 0, "a slot outside the image is never written"); + + var atStart = NewImage(); + WriteStub(atStart, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + // A lone push of the name at the very start of .text has no stub around it. + atStart[TextRva] = 0x68; + BitConverter.TryWriteBytes(atStart.AsSpan((int)TextRva + 1), ImageBase + NameRva); + Check(Scan(atStart).Count == 1, "a lone push of the name is skipped, the real stub still found"); + } + + private static void OtherFunctionHasNoSlot() + { + _case = "other function"; + var img = NewImage(); + WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva); + Check(Scan(img, "CreateFileA").Count == 0, "only the named function's slot is returned"); + } + + // ── the real client ────────────────────────────────────────────────────── + + private static void Real2025Client() + { + _case = "ACClient.exe 0.0.11.6096"; + string? path = Environment.GetEnvironmentVariable("RYNTH_ACCLIENT"); + if (string.IsNullOrEmpty(path)) + path = @"C:\Turbine\Asheron's Call-ryn\ACClient.exe"; + if (!File.Exists(path)) + { + Console.WriteLine($" skip: {path} not found (set RYNTH_ACCLIENT to check a client)"); + return; + } + + byte[] mapped = MapImage(File.ReadAllBytes(path), out uint imageBase); + var sections = LazyImportSlotScanner.ReadSections(mapped); + var w = LazyImportSlotScanner.FindSlots(mapped, imageBase, sections, "kernel32.dll", "CreateFileW"); + var a = LazyImportSlotScanner.FindSlots(mapped, imageBase, sections, "kernel32.dll", "CreateFileA"); + Console.WriteLine($" {path}: CreateFileW slots {string.Join(", ", w.Select(s => $"0x{s.SlotVa:X8} (stub 0x{s.StubVa:X8})"))}; CreateFileA slots {a.Count}"); + + // Read from the running client on 2026-10-15: slot 0x00837374 held kernel32!CreateFileW. + if (imageBase == 0x00400000 && FileVersion(path) == "00.00.11.6096") + { + Check(w.Count == 1 && w[0].SlotVa == 0x00837374, "the CreateFileW slot is 0x00837374"); + Check(w.Count == 1 && w[0].StubVa == 0x006B8D00, "filled by the stub at 0x006B8D00"); + Check(a.Count == 0, "CreateFileA is a normal import, no private slot"); + } + } + + private static string FileVersion(string path) => + System.Diagnostics.FileVersionInfo.GetVersionInfo(path).FileVersion ?? ""; + + /// <summary>Lays a PE file out the way the loader maps it (headers, then each section at its RVA).</summary> + private static byte[] MapImage(byte[] file, out uint imageBase) + { + int pe = BitConverter.ToInt32(file, 0x3C); + int opt = pe + 24; + imageBase = BitConverter.ToUInt32(file, opt + 28); + uint sizeOfImage = BitConverter.ToUInt32(file, opt + 56); + uint sizeOfHeaders = BitConverter.ToUInt32(file, opt + 60); + var img = new byte[sizeOfImage]; + Array.Copy(file, img, Math.Min(sizeOfHeaders, (uint)file.Length)); + int count = BitConverter.ToUInt16(file, pe + 6); + int table = opt + BitConverter.ToUInt16(file, pe + 20); + for (int i = 0; i < count; i++) + { + int h = table + 40 * i; + uint rva = BitConverter.ToUInt32(file, h + 12); + uint rawSize = BitConverter.ToUInt32(file, h + 16); + uint raw = BitConverter.ToUInt32(file, h + 20); + uint n = Math.Min(rawSize, Math.Min(sizeOfImage - rva, (uint)file.Length - raw)); + Array.Copy(file, raw, img, rva, n); + } + return img; + } +} From 61e1e0b827dc362ec463420714ab5f60458701de Mon Sep 17 00:00:00 2001 From: BlankenshipG <Silentkelpie@Gmail.com> Date: Thu, 15 Oct 2026 11:35:38 -0400 Subject: [PATCH 5/6] feat: SK Breadcrumbs and Route overlay on Settings > Navigation The Nav panel's two switches as Settings rows (hidden for a RynthAi that doesn't send them). Each side refreshes the other after a change; the tooltips are shared. --- ...-breadcrumbs-route-overlay-2026.10.5.62.md | 45 +++++++++++++++++++ src/RynthCore.Engine/ImGui/Panels/NavFace.cs | 10 +++-- src/RynthCore.Engine/UI/Data/RynthAiData.cs | 1 + src/RynthCore.Engine/UI/Data/SettingsData.cs | 19 ++++++++ 4 files changed, 71 insertions(+), 4 deletions(-) create mode 100644 Changelog/2026-10-15-nav-settings-breadcrumbs-route-overlay-2026.10.5.62.md diff --git a/Changelog/2026-10-15-nav-settings-breadcrumbs-route-overlay-2026.10.5.62.md b/Changelog/2026-10-15-nav-settings-breadcrumbs-route-overlay-2026.10.5.62.md new file mode 100644 index 0000000..4464622 --- /dev/null +++ b/Changelog/2026-10-15-nav-settings-breadcrumbs-route-overlay-2026.10.5.62.md @@ -0,0 +1,45 @@ +# Breadcrumbs and Route overlay on Settings > Navigation (2026.10.5.62) + +Date: 2026-10-15 + +| Component | Version | Previous release | +|---|---|---| +| RynthCore.Engine | 2026.10.5.62 | 2026.10.5.61 | + +## What's new + +Settings > Navigation now has the Nav panel's two overlay switches, at the top of "Nav Marker +Display": + +- **Breadcrumbs**: record the trail you walk and draw it on the ground (`/ra navtrail on|off`). +- **Route Overlay**: draw the route in the world, meaning the waypoint rings and lines, the + waypoint labels and the guide line (`/ra navoverlay on|off`). + +They are the same switches as on the Nav panel, not copies. A change in either place shows in the +other: + +- The Nav panel's toggle also asks the Settings page to fetch again. It updates the Nav panel's + own settings copy too, so a nav point reach saved straight afterwards doesn't send the old value + back. +- A save from the Settings page also asks the Nav panel to fetch again. + +Both panels share the tooltips (`SettingsSchema.BreadcrumbsTip` and `RouteOverlayTip`). + +## Compatibility + +The new fields (`TrackBreadcrumbs` and `ShowRouteOverlay` in `RynthAiSettings`) are nullable. + +- **Older RynthAi:** it doesn't send them, so the two rows stay hidden, and a save sends null, + which RynthAi reads as unchanged. +- **RynthAi 0.5.70-legacy-ui or later:** sends and applies them. + +## Files + +- `src/RynthCore.Engine/UI/Data/SettingsData.cs`: the fields, the two rows, the shared tooltips, + and the Nav refresh after a save. +- `src/RynthCore.Engine/ImGui/Panels/NavFace.cs`: the shared tooltips and the local settings copy. +- `src/RynthCore.Engine/UI/Data/RynthAiData.cs`: a Settings refresh after each nav command. + +## Install + +The installer build (`installer\Build-Installer.ps1`) stamps the engine as 2026.10.5.62. diff --git a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs index f8ca69f..bfc3b8d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs @@ -157,19 +157,21 @@ internal sealed class NavFace : IImGuiPanel // Breadcrumbs | Route overlay (RynthAi's NavOverlaySettings; saved per character) p = ImGuiNET.ImGui.GetCursorScreenPos(); - if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half, - "Record the trail you walk and draw it on the ground (/ra navtrail on|off).\nTurning it off hides the trail; /ra navtrail clear wipes it.")) + // Also on Settings > Navigation. The local settings copy takes the new value too, so a reach + // save from this panel before the next settings fetch doesn't send the old one back. + if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half, SettingsSchema.BreadcrumbsTip)) { bool on = !_data.TrackBreadcrumbs; NavCommands.Send(new NavCmd { Cmd = "setBreadcrumbs", On = on }); _data.TrackBreadcrumbs = on; + if (_settings?.TrackBreadcrumbs != null) _settings.TrackBreadcrumbs = on; } - if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half, - "Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\nto the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate.")) + if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half, SettingsSchema.RouteOverlayTip)) { bool on = !_data.ShowRouteOverlay; NavCommands.Send(new NavCmd { Cmd = "setRouteOverlay", On = on }); _data.ShowRouteOverlay = on; + if (_settings?.ShowRouteOverlay != null) _settings.ShowRouteOverlay = on; } NextLine(p, 26); diff --git a/src/RynthCore.Engine/UI/Data/RynthAiData.cs b/src/RynthCore.Engine/UI/Data/RynthAiData.cs index 29af4a0..2e3189c 100644 --- a/src/RynthCore.Engine/UI/Data/RynthAiData.cs +++ b/src/RynthCore.Engine/UI/Data/RynthAiData.cs @@ -371,6 +371,7 @@ internal static unsafe class RynthAiCommands finally { Marshal.FreeHGlobal(p); } if (refreshPatrol) UiSources.Patrol.RequestRefresh(); UiSources.Nav.RequestRefresh(); // the plugin applied it: the Nav panels show it next poll + UiSources.Settings.RequestRefresh(); // Breadcrumbs / Route overlay are on Settings > Navigation too }); /// <summary> diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 18c046a..43a0410 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -160,6 +160,11 @@ internal sealed class RynthAiSettings // RynthAi NavResumeNearest: macro start, route loads and resuming after a pause that moved // the character head for the closest waypoint. On by default; an older plugin ignores it. public bool NavResumeNearest { get; set; } = true; + // RynthAi NavOverlay.TrackBreadcrumbs / ShowRouteMarkers: the Nav panel's Breadcrumbs and Route + // overlay switches, also on Settings > Navigation. Null = a RynthAi that doesn't send them: the + // rows hide, and a save sends null back, which RynthAi reads as unchanged. + public bool? TrackBreadcrumbs { get; set; } + public bool? ShowRouteOverlay { get; set; } // RynthAi dungeon patrol (/ra dunnav-patrol; RynthAi DungeonPatrolOptions). The defaults are // the patrol as it was before these settings; an older plugin ignores them. public int DunPatrolCoverage { get; set; } // 0 whole dungeon, 1 loops only, 2 everything, 3 sweep @@ -319,6 +324,7 @@ internal static unsafe class SettingsCommands try { _setSettingsJson(ansi); } finally { Marshal.FreeHGlobal(ansi); } UiSources.Settings.RequestRefresh(); + UiSources.Nav.RequestRefresh(); // the Nav panel's Breadcrumbs / Route overlay switches }); } } @@ -431,6 +437,15 @@ internal static class SettingsSchema "close to its leader, and the nav marker ring shows it. Dungeon doorways use at most 1 yd. Up to 2 yd, " + "nav walks right up to each point before turning (tight dungeons); bigger values round corners."; + // The Nav panel's two overlay switches (ImGui/Panels/NavFace.cs), also on Settings > Navigation. + public const string BreadcrumbsTip = + "Record the trail you walk and draw it on the ground (/ra navtrail on|off).\n" + + "Turning it off hides the trail; /ra navtrail clear wipes it."; + public const string RouteOverlayTip = + "Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\n" + + "to the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate."; + private const string SameAsNavPanel = "\nThe same switch as on the Nav panel."; + // 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 = @@ -924,6 +939,10 @@ internal static class SettingsSchema Float(NavPointReachLabel, s => s.FollowNavMin, (s, v) => s.FollowNavMin = v, 0.5f, 20f, 0.1f, NavPointReachTip), Spacer(), Section("Nav Marker Display"), + Bool("Breadcrumbs", s => s.TrackBreadcrumbs ?? true, (s, v) => s.TrackBreadcrumbs = v, + BreadcrumbsTip + SameAsNavPanel, when: s => s.TrackBreadcrumbs.HasValue), + Bool("Route Overlay", s => s.ShowRouteOverlay ?? true, (s, v) => s.ShowRouteOverlay = v, + RouteOverlayTip + SameAsNavPanel, when: s => s.ShowRouteOverlay.HasValue), Float("Ring Thickness", s => s.NavRingThickness, (s, v) => s.NavRingThickness = v, 1f, 16f, 1f), Float("Line Thickness", s => s.NavLineThickness, (s, v) => s.NavLineThickness = v, 1f, 16f, 1f), Float("Height Offset", s => s.NavHeightOffset, (s, v) => s.NavHeightOffset = v, -5f, 5f, 0.05f, From 0a1f5bf74417d71be30bbb9e8ef196233f9cda2b Mon Sep 17 00:00:00 2001 From: BlankenshipG <Silentkelpie@Gmail.com> Date: Wed, 14 Oct 2026 22:35:26 -0400 Subject: [PATCH 6/6] fix: SK engine and launcher fixes from 2026-10-14 - fix(engine): DAT share hook now patches only the CreateFile imports of acclient.exe and MSVCR70.dll instead of hooking kernel32 process-wide, so Direct3D and driver file opens are no longer routed through the detour ("Could not initialize Direct3D" on some machines). Uninstall restores the import slots on engine unload. - fix(launcher): a saved UserPreferences.ini that makes the client exit within 30 s is quarantined and the previous live file is restored. - fix(engine): target selects and attacks run during the gesture defer. - feat(launcher): first login on a new server; pick any character on the account. - feat(settings): loot timers show their optimized defaults, with a "Use optimized defaults" button. Release notes are in Changelog/2026-10-14-*.md. --- ...-hook-scoped-to-ac-imports-2026.10.5.61.md | 61 ++++++++++++ ...-14-first-login-new-server-2026.10.5.58.md | 88 ++++++++++++++++++ ...10-14-gesture-safe-attacks-2026.10.5.57.md | 41 ++++++++ ...failed-prefs-swap-recovery-2026.10.5.60.md | 61 ++++++++++++ ...t-timer-optimized-defaults-2026.10.5.59.md | 40 ++++++++ .../RynthCore.App.Avalonia.csproj | 8 +- src/RynthCore.Engine/UI/Data/SettingsData.cs | 93 +++++++++++++++---- .../UI/Panels/SettingsPanel.cs | 13 ++- tools/LauncherSettingsTests/Program.cs | 90 ++++++++++++++++++ 9 files changed, 474 insertions(+), 21 deletions(-) create mode 100644 Changelog/2026-10-14-dat-share-hook-scoped-to-ac-imports-2026.10.5.61.md create mode 100644 Changelog/2026-10-14-first-login-new-server-2026.10.5.58.md create mode 100644 Changelog/2026-10-14-gesture-safe-attacks-2026.10.5.57.md create mode 100644 Changelog/2026-10-14-launcher-failed-prefs-swap-recovery-2026.10.5.60.md create mode 100644 Changelog/2026-10-14-loot-timer-optimized-defaults-2026.10.5.59.md diff --git a/Changelog/2026-10-14-dat-share-hook-scoped-to-ac-imports-2026.10.5.61.md b/Changelog/2026-10-14-dat-share-hook-scoped-to-ac-imports-2026.10.5.61.md new file mode 100644 index 0000000..817f99e --- /dev/null +++ b/Changelog/2026-10-14-dat-share-hook-scoped-to-ac-imports-2026.10.5.61.md @@ -0,0 +1,61 @@ +# 2026.10.5.61 - engine: DAT share hook no longer intercepts Direct3D and driver file opens + +Previous release: 2026.10.5.60. + +## Problem + +On one PC every RynthCore launch ended with "Could not initialize Direct3D. Please ensure that +DirectX 9.0 or higher is installed." (twice), then "The game encountered a fatal DirectX issue +while attempting to start...", and AC exited with code 1 about 6 seconds in. The same client +started from another launcher (no engine) worked. 2026.10.5.60 (saved UserPreferences.ini +recovery) did not change it. + +In all three logs (builds 2026.10.14.2 and 2026.10.5.60) the error came 27-36 ms after the +engine started loading RynthChat, the plugin right after RynthAi. RynthAi took 378, 390 and +1175 ms to load, and the error moved with it, so AC's device creation was waiting on the engine +and failed as soon as it continued. + +The DAT share hook (on with "Allow multiple clients") detoured the kernel32 `CreateFileA` and +`CreateFileW` exports with MinHook. That caught every caller in the process, including +d3d9.dll and the GPU driver, which open files (shader caches) while AC creates its device. Each +of those opens ran through managed code, which can wait on the runtime while plugins load, and +the detour did not hand back the Win32 last error: callers read it even after a successful +CreateFile (ERROR_ALREADY_EXISTS with OPEN_ALWAYS), and on some drivers that fails device +creation. + +## Change + +- The hook patches only the import slots of the modules that open AC's data files: + `acclient.exe` (imports CreateFileA) and its CRT `MSVCR70.dll` (CreateFileA/W, used by + fopen/_wfopen; the "W" DAT lines in the log come from here). Direct3D, drivers, the runtime + and plugins call CreateFile without the engine in the way. +- The detour sets the Win32 last error back to the value CreateFile left before returning. +- The import slots are written back at engine shutdown (new step + `DatFileShareHooks.Uninstall`), because the detours belong to the engine generation that hot + reload unloads. +- A detour calls whatever its slot held before, so a Decal detour on the kernel32 export still + runs. +- The startup log now lists the hooked slots, for example + `Compat: DAT share - hooked MSVCR70.dll!CreateFileW import (...)`, and the DAT open lines + (`Compat: DAT share - W [filtered]: client_portal.dat ...`) still appear when multi-client is + on. + +## Code + +- `src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs`: MinHook export hooks replaced by + IAT slot hooks (`HookModuleImports`, `InstallSlot`, `Uninstall`, `IatHook` record); detours + take the slot's original delegate and restore the last error (`SetWin32LastError`). +- `src/RynthCore.Engine/EngineLifecycle.cs`: `DatFileShareHooks.Uninstall` before + `MH_DisableHook(ALL)`. + +## Tests + +- `dotnet build src\RynthCore.Engine\RynthCore.Engine.csproj -c Release`: 0 errors, no new + warnings. No test project covers the hook; it needs a running client. +- Import tables checked on this PC: `acclient.exe` imports `KERNEL32!CreateFileA` (and + `CreateFileMappingA`); `MSVCR70.dll` imports `KERNEL32!CreateFileA` and `CreateFileW`. + +## For an affected PC before updating + +Set `"EnableDatShareHook": false` in `%APPDATA%\RynthCore\engine.json` (or turn off "Allow +multiple clients"), then launch. If the client starts, this hook was the cause. diff --git a/Changelog/2026-10-14-first-login-new-server-2026.10.5.58.md b/Changelog/2026-10-14-first-login-new-server-2026.10.5.58.md new file mode 100644 index 0000000..6f5149b --- /dev/null +++ b/Changelog/2026-10-14-first-login-new-server-2026.10.5.58.md @@ -0,0 +1,88 @@ +# 2026.10.5.58 - launcher: first login on a new server, every character on the account + +Previous release: 2026.10.5.57. Launcher project version 0.1.6 (was 0.1.5). + +## Problem + +An account set up for a new server never got in. The `SK` profile (Conquest, +`acconquest.ddns.net:9000`, and earlier Aelrynth) had no password saved, so +the launcher started the client with `-v ""`. The client refuses an empty +password before it connects: it shows "You can only run the game from the +launcher program" and exits about 4 seconds later. All six `SK` launches in the +logs (Aelrynth, 2026-10-13 08:31 to 23:47; Conquest, 23:48) ended this way, and +the launcher only recorded each one as a crash. + +An empty password would fail on the server too. ACE creates a new account on its +first login (`AllowAutoAccountCreation`), but only when a password is sent, and +it boots a login without one. + +Also: + +- A new account profile had no server picked unless you chose one, and the + launch list then put it on the first server profile. +- The launch list showed "(None - no auto-login) | offline" as if it were a + character name. + +## Change + +- **First Login dialog.** A manual launch of an account with no usable password + (none saved, or one that can't be decrypted on this Windows user) asks for it + first, instead of starting a client that can only fail. It has: + - An optional list of the account names used in your other profiles, to pick + an account you already have. + - The account name. On ACE, a new name creates the account on this first + login, if the server allows it. + - A password with confirmation, saved encrypted like the other accounts. If + another profile has the same account name with a saved password, a checkbox + reuses it (the encrypted copy is copied, never the plain text). + - "Log in as": stop at character select, or any character already known for + the account. + + Cancelling skips that account and logs why. Automatic launches don't show the + dialog. They skip the account, logging it at most once every 5 minutes. +- **Characters on the account.** With no character chosen, the client stops at + character select, where you can create characters. The engine already saves + the account's character list from character select, including newly created + characters. + - Stopping at character select before any character is known saves an empty + choice, not "(None)". Once the first character exists and is the only one, + the next launch logs it in. + - With several characters, the launch list's dropdown, and the new "Log in as" + in Edit Account, list them all. You pick which one logs in, or stop at + character select. +- **Account Profile dialog.** + - New "Log in as" list. + - A new account defaults to the server selected in the list. + - A server must be picked when there are server profiles. + - Account names over 50 characters (ACE's limit), or with ':' on GDLE (whose + login argument is `account:password`), are refused. +- **Launch list status.** "Needs password | launch to set up" for an account + without one, and "Character select" instead of the "(None)" text. +- **Never an empty password.** + - `AcLaunchArgumentBuilder.BuildArguments` refuses to build a command line with + an empty password, with the reason. + - The launch preview says the password is missing instead of showing `-v ""`. + - `RynthCore.Injector launch` refuses too. + +## Tests + +- tools/LauncherSettingsTests: 152 checks pass. + - The old checks that an account without a password "still launches as before + (empty)" now check that it's refused, with the reason, on ACE and GDLE. + - New: account-name checks, and a "first login on a new server" scenario: + - known account names + - reusing another profile's saved password (the copied encrypted password + still decrypts) + - the Log in as choices and what each saves + - the dialog's input checks +- tools/AelrynthTests: 89/89. +- The launcher and the injector build. The dialogs were not shown in a test run. + +## Files + +- `src/RynthCore.App/FirstLoginRules.cs` (new), `AcLaunchArgumentBuilder.cs`, `LaunchAccountProfile.cs` +- `src/RynthCore.App.Avalonia/FirstLoginDialog.axaml` and `.axaml.cs` (new) +- `src/RynthCore.App.Avalonia/AccountProfileDialog.axaml` and `.axaml.cs`, `MainWindow.axaml.cs`, + `RynthCore.App.Avalonia.csproj` +- `src/RynthCore.Injector/LaunchCommand.cs` +- `tools/LauncherSettingsTests/Program.cs`, `LauncherSettingsTests.csproj` diff --git a/Changelog/2026-10-14-gesture-safe-attacks-2026.10.5.57.md b/Changelog/2026-10-14-gesture-safe-attacks-2026.10.5.57.md new file mode 100644 index 0000000..5405bbf --- /dev/null +++ b/Changelog/2026-10-14-gesture-safe-attacks-2026.10.5.57.md @@ -0,0 +1,41 @@ +# 2026.10.5.57 - attacks and target selects no longer wait behind gestures + +Previous release: 2026.10.5.56. + +Goes with RynthAi 0.5.64-legacy-ui (fewer weapon swaps, faster point-blank +stall recovery: `RynthSuite/Changelog/2026-10-14-combat-speed-swaps-stalls-0.5.64.md`). + +## Problem + +While a gesture is in flight (the CMotionInterp pending-motion list is not +empty), `AcMainThreadQueue` defers the whole action ring for up to +`DrainDeferMaxMs` (2.5 s). With a crossbow or bow, a gesture is in flight +nearly all the time. In Silentkelpie's 2026-10-14 logs, target selects and +attacks ran 1.0-1.9 s late, and some attacks went past the 1.5 s stale limit +and were dropped. + +## Change + +- New `AcMainThreadQueue.RunsDuringGesture`. The retail client does these from + a key press at any moment, swing or not, so they now run during the defer: + - `SetSelectedObject` (the target select). + - `NativeAttack` (ClientCombatSystem StartAttackRequest / EndAttackRequest, + which the client itself holds until the motion allows it). + - `CancelAttack` (the 0x1B7 packet). +- These run from the head of the ring up to the first entry that doesn't + qualify, using `ActionRing.TryPeek` and `Pop`. FIFO order is kept: nothing + overtakes a held entry. +- Stance changes, movement, raw attack packets and item moves stay deferred as + before. When the gesture-safe entries empty the ring, the defer clock resets, + so the next held entry gets its full defer. + +## Tests + +- Engine builds. All RynthCore tool tests pass (EngineRobustnessTests 1159 + checks, among others). There is no unit harness for the drain (it needs AC's main + thread). The change is checked live through RynthAi's logs: attacks should no + longer be reported late or stale behind crossbow gestures. + +## Files + +- `src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs` diff --git a/Changelog/2026-10-14-launcher-failed-prefs-swap-recovery-2026.10.5.60.md b/Changelog/2026-10-14-launcher-failed-prefs-swap-recovery-2026.10.5.60.md new file mode 100644 index 0000000..d0d2394 --- /dev/null +++ b/Changelog/2026-10-14-launcher-failed-prefs-swap-recovery-2026.10.5.60.md @@ -0,0 +1,61 @@ +# 2026.10.5.60 - launcher: undo a saved UserPreferences.ini that stops the client starting + +Previous release: 2026.10.5.59. Launcher project version 0.1.7 (was 0.1.6). + +## Problem + +A client launched from RynthCore showed "Could not initialize Direct3D. Please ensure that +DirectX 9.0 or higher is installed." twice, then "The game encountered a fatal DirectX issue +while attempting to start. Try a different screen resolution or bit depth...", and exited +about 12 seconds after start. The same client started fine from another launcher. + +The engine was not involved: its D3D9 hooks only start at login, and the log had no D3D9 +lines. The difference was the launcher. Before every launch it copies the account's saved +game settings (`%APPDATA%\RynthCore\prefs\<account>@<server>.ini`, or the file set on the +profile) over the live `Documents\Asheron's Call\UserPreferences.ini`. The game reads its +resolution and full-screen mode from that file. A saved copy with a display mode the PC can't +use (another monitor, an old resolution) fails every launch, and the saved copy is only +refreshed after a normal session, so it was restored again on every launch. Another launcher +uses the live file, which is why it worked. + +## Change + +- When a client quits within 30 s (the existing "counted as crash" window) and its launch + swapped in a saved UserPreferences.ini that differs from the live file: + - The saved copy is renamed to `<name>.ini.failed-yyyyMMdd-HHmmss` (kept, never swapped in + again). The account's old name-only copy (`<account>.ini`) is set aside too when it holds + the same settings, because it re-seeds a missing per-server copy. + - The live UserPreferences.ini is put back to what it was before the swap, unless another + launch has swapped it since. + - The activity log says what happened. The next launch uses the live file, and the next + normal session saves a fresh copy. +- A file the user picked on the profile (UserPrefsPath) is never renamed; the live file is + still put back and the activity log points at the profile setting. +- Nothing changes when the saved copy matched the live file (the swap can't have caused the + exit), e.g. a missing password or a server that is down. + +## Code + +- `src/RynthCore.App/UserPrefsSwapRecovery.cs` (new): `UserPrefsSwap` record (stash path, + live path, stash bytes, live bytes before the swap), `SwapChangedPrefs`, `Recover` + (quarantine + restore), `QuarantinePath`. +- `src/RynthCore.App/AcClientLaunchSettingsService.cs`: `SwapUserPreferences` returns the + `UserPrefsSwap` (was `bool`) and reads the live file before overwriting it. +- `src/RynthCore.App.Avalonia/MainWindow.axaml.cs`: the three launch paths (RynthCore, Decal / + Decal + RynthCore, no injection) use `ApplyPrefsSwap` and record the swap per PID + (`TrackPrefsSwap`); `DetectQuickExits` calls `RecoverFailedPrefsSwap` for a quick exit. A swap + generation counter decides whether the live file can still be put back. + `ResolveLegacyUserPrefsPath` is shared with `ResolveUserPrefsPath`. +- `RynthCore.App.Avalonia.csproj`: links the new file; version 0.1.7. + +## Tests + +- `tools/LauncherSettingsTests`: 5 new scenarios (swap changed the live file or not; failed + stash set aside and live file restored; a different name-only stash kept; profile override + and later swap leave files alone; no live file before). `PASS: 163 checks`. +- `dotnet build src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj -c Release`: 0 errors. + +## For an affected PC now + +Rename or delete `%APPDATA%\RynthCore\prefs\<account>@<server>.ini` (and `<account>.ini`) for +the failing account, or clear the UserPreferences file on its profile, then launch again. diff --git a/Changelog/2026-10-14-loot-timer-optimized-defaults-2026.10.5.59.md b/Changelog/2026-10-14-loot-timer-optimized-defaults-2026.10.5.59.md new file mode 100644 index 0000000..f03f8a5 --- /dev/null +++ b/Changelog/2026-10-14-loot-timer-optimized-defaults-2026.10.5.59.md @@ -0,0 +1,40 @@ +# 2026.10.5.59 - Loot Timers show their optimized defaults, with a button to use them + +Previous release: 2026.10.5.58 (installed engine 2026.10.5.57). + +Goes with RynthSuite's `Changelog/2026-10-14-loot-baseline-0.5.65.md` (RynthAi 0.5.65), which +measured the loot timer baseline and applied it to RynthAi's own Advanced Settings. The +engine's Settings panel (Looting tab) still showed the old list with no defaults. + +## Change + +- **Settings > Looting > Loot Timers (ms) - (optimized default).** Each timer's label ends + with its optimized default in brackets: + - Content Settle (100) + - Empty Corpse Wait (300) + - Assess Window (300) + - Loot Retry Timeout (1000) + - Corpse Open Retry (1500) + - Corpse Timeout (12000) +- **Use optimized defaults** button: sets all six timers to those values and saves them to + RynthAi like a typed value. It works in the in-game panel and in the launcher's panel. +- Each timer has a tooltip (what it waits for, and the measured appraisal times for Assess + Window). +- Inter-Item Delay and Closing Delay are no longer shown: RynthAi's corpse looting never reads + them (RynthAi hid them in 0.5.65). They are still carried so a save doesn't send them missing. +- The engine's own defaults for the timers (used until RynthAi sends its settings) now match + the optimized defaults: Assess Window 200 -> 300 ms, Loot Retry Timeout 500 -> 1000 ms. + +## Code + +- `UI/Data/SettingsData.cs`: new `LootTimerDefaults` (the six values, same as RynthSuite's + `LootBaseline.cs`; `Label`, `Apply`, `AllDefault`). `SettingRow` gains an optional + `Edit` action for buttons that change settings, built with `EditButton`. +- `ImGui/Panels/SettingsFace.cs` and `UI/Panels/SettingsPanel.cs`: a button row with `Edit` + applies it to the panel's copy and saves it (the launcher panel also rebuilds the tab so the + number boxes show the new values). + +## Tests + +- `dotnet build src\RynthCore.Engine\RynthCore.Engine.csproj -c Release`: 0 errors. No test + project compiles `SettingsData.cs`. diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index 0e3d036..4292737 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -1,12 +1,12 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.5. + <!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.6. No hard-coded InformationalVersion: release builds pass -p:Version=yyyy.m.d.n, and the product version derived from it is what the launcher/About show (BuildVersion.Format). --> - <Version>0.1.6</Version> - <AssemblyVersion>0.1.6.0</AssemblyVersion> - <FileVersion>0.1.6.0</FileVersion> + <Version>0.1.7</Version> + <AssemblyVersion>0.1.7.0</AssemblyVersion> + <FileVersion>0.1.7.0</FileVersion> <OutputType>WinExe</OutputType> <TargetFramework>net10.0-windows7.0</TargetFramework> <PlatformTarget>x86</PlatformTarget> diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 43a0410..9804617 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -236,14 +236,16 @@ internal sealed class RynthAiSettings // Salvage with the 0x027D request sent straight to the server, no salvage panel on screen // (default on; used when the engine has API v81; an older RynthAi doesn't send it). public bool SalvageWithoutPanel { get; set; } = true; + // Inter-Item Delay and Closing Delay: RynthAi's corpse looting never reads them (not shown in + // the panel since 2026.10.5.59), carried so a save doesn't send them missing. public int LootInterItemDelayMs { get; set; } = 50; - public int LootContentSettleMs { get; set; } = 100; - public int LootEmptyCorpseMs { get; set; } = 300; + public int LootContentSettleMs { get; set; } = LootTimerDefaults.ContentSettleMs; + public int LootEmptyCorpseMs { get; set; } = LootTimerDefaults.EmptyCorpseMs; public int LootClosingDelayMs { get; set; } = 200; - public int LootAssessWindowMs { get; set; } = 200; - public int LootRetryTimeoutMs { get; set; } = 500; - public int LootOpenRetryMs { get; set; } = 1500; - public int LootCorpseTimeoutMs { get; set; } = 12000; + public int LootAssessWindowMs { get; set; } = LootTimerDefaults.AssessWindowMs; + public int LootRetryTimeoutMs { get; set; } = LootTimerDefaults.RetryTimeoutMs; + public int LootOpenRetryMs { get; set; } = LootTimerDefaults.OpenRetryMs; + public int LootCorpseTimeoutMs { get; set; } = LootTimerDefaults.CorpseTimeoutMs; public int SalvageOpenDelayFirstMs { get; set; } = 400; public int SalvageOpenDelayFastMs { get; set; } = 50; public int SalvageAddDelayFirstMs { get; set; } = 600; @@ -329,6 +331,43 @@ internal static unsafe class SettingsCommands } } +/// <summary> +/// The optimized loot timer defaults, in ms: the same values as RynthSuite's LootBaseline.cs +/// (RynthAi 0.5.65), measured from live corpse looting on ACE (226 corpses, 39 pickups). Keep +/// the two in step. The Loot Timers rows show each one in brackets after the label. +/// </summary> +internal static class LootTimerDefaults +{ + public const int ContentSettleMs = 100; + public const int EmptyCorpseMs = 300; + /// <summary>Above the 256 ms 95th percentile of the measured appraisal replies.</summary> + public const int AssessWindowMs = 300; + /// <summary>No pickup needed a retry at 1000 ms (it counts from when the character is still).</summary> + public const int RetryTimeoutMs = 1000; + public const int OpenRetryMs = 1500; + public const int CorpseTimeoutMs = 12000; + + /// <summary>A row label with its optimized default: "Assess Window (300)".</summary> + public static string Label(string name, int defaultMs) => $"{name} ({defaultMs})"; + + /// <summary>Writes the six optimized defaults into <paramref name="s"/>.</summary> + public static void Apply(RynthAiSettings s) + { + s.LootContentSettleMs = ContentSettleMs; + s.LootEmptyCorpseMs = EmptyCorpseMs; + s.LootAssessWindowMs = AssessWindowMs; + s.LootRetryTimeoutMs = RetryTimeoutMs; + s.LootOpenRetryMs = OpenRetryMs; + s.LootCorpseTimeoutMs = CorpseTimeoutMs; + } + + /// <summary>True when all six timers are at the optimized defaults.</summary> + public static bool AllDefault(RynthAiSettings s) => + s.LootContentSettleMs == ContentSettleMs && s.LootEmptyCorpseMs == EmptyCorpseMs && + s.LootAssessWindowMs == AssessWindowMs && s.LootRetryTimeoutMs == RetryTimeoutMs && + s.LootOpenRetryMs == OpenRetryMs && s.LootCorpseTimeoutMs == CorpseTimeoutMs; +} + // ── Schema ───────────────────────────────────────────────────────────────── internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status, @@ -420,7 +459,10 @@ internal sealed record SettingRow( Func<RynthAiSettings, string>? GetText = null, Action<RynthAiSettings, string>? SetText = null, // Text rows: greyed hint shown while the box is empty. - string? Hint = null) + string? Hint = null, + // Button rows that change settings: applied to the panel's copy, which is then saved like + // any other edit (Click, when also set, runs after). + Action<RynthAiSettings>? Edit = null) { public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s); } @@ -535,6 +577,10 @@ internal static class SettingsSchema private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) => new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click); + // A button that edits the settings (the panel saves the result like a typed value). + private static SettingRow EditButton(string label, string buttonText, Action<RynthAiSettings> edit, string? tip = null) => + new(SettingKind.Button, label, tip, ButtonText: buttonText, Edit: edit); + private static SettingRow Text(string label, Func<RynthAiSettings, string> get, Action<RynthAiSettings, string> set, string? tip = null, string? hint = null) => new(SettingKind.Text, label, tip, GetText: get, SetText: set, Hint: hint); @@ -1100,15 +1146,30 @@ internal static class SettingsSchema Bool("Salvage Without The Panel", s => s.SalvageWithoutPanel, (s, v) => s.SalvageWithoutPanel = v, "Salvage (and combine bags) by sending the salvage request to the server directly:\nAC's salvage panel never opens. When a request changes nothing, that batch is tried once\nthrough the panel. Needs an engine with plugin API v82; otherwise the panel is used."), Spacer(), - Section("Loot Timers (ms)"), - Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25), - Int("Content Settle", s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25), - Int("Empty Corpse Wait", s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25), - Int("Closing Delay", s => s.LootClosingDelayMs, (s, v) => s.LootClosingDelayMs = v, 0, 5000, 25), - Int("Assess Window", s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25), - Int("Loot Retry Timeout", s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100), - Int("Corpse Open Retry", s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100), - Int("Corpse Timeout", s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500), + // The optimized default is in brackets after each label (LootTimerDefaults). Inter-Item + // Delay and Closing Delay are not shown: RynthAi's corpse looting never reads them. + Section("Loot Timers (ms) - (optimized default)"), + EditButton("Optimized defaults", "Use optimized defaults", LootTimerDefaults.Apply, + "Set all six loot timers to the optimized defaults, measured from live looting on ACE\n" + + "(226 corpses). RynthAi's log line [LootSettings] marks each timer baseline or custom."), + Int(LootTimerDefaults.Label("Content Settle", LootTimerDefaults.ContentSettleMs), + s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25, + "Wait after an open for the container's items. Only used when the items\naren't already known; on ACE they always were."), + Int(LootTimerDefaults.Label("Empty Corpse Wait", LootTimerDefaults.EmptyCorpseMs), + s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25, + "Wait for a corpse's contents before probing it or calling it empty."), + Int(LootTimerDefaults.Label("Assess Window", LootTimerDefaults.AssessWindowMs), + s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25, + "Hold items for their appraisal. Measured replies: 127 ms typical,\n256 ms at the 95th percentile, 350 ms at most."), + Int(LootTimerDefaults.Label("Loot Retry Timeout", LootTimerDefaults.RetryTimeoutMs), + s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100, + "Wait, once the character is still, before resending a pickup that hasn't\nlanded. Too short resends pickups the server is still doing."), + Int(LootTimerDefaults.Label("Corpse Open Retry", LootTimerDefaults.OpenRetryMs), + s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100, + "Wait before sending another open to a corpse that hasn't opened."), + Int(LootTimerDefaults.Label("Corpse Timeout", LootTimerDefaults.CorpseTimeoutMs), + s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500, + "Give up on a claimed corpse after this long. The clock stops during combat\nand buffing."), Spacer(), Section("Salvage Timers (ms) - First / Fast"), Int("Open (First)", s => s.SalvageOpenDelayFirstMs, (s, v) => s.SalvageOpenDelayFirstMs = v, 0, 5000, 50), diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index e5abf9d..a7cf1f6 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -334,7 +334,18 @@ internal static class SettingsPanel case SettingKind.Spacer: return Spacer(); case SettingKind.Button: - return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip); + return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => + { + // A settings edit is pushed like a typed value; the tab is rebuilt so the + // number boxes show the new values. + if (row.Edit != null) + { + row.Edit(state.Data); + Push(state); + state.Rebuild?.Invoke(); + } + row.Click?.Invoke(); + }, row.Tooltip); case SettingKind.TraceCategories: return TraceCategoriesRow(state, row); case SettingKind.Text: diff --git a/tools/LauncherSettingsTests/Program.cs b/tools/LauncherSettingsTests/Program.cs index e3a2340..290b983 100644 --- a/tools/LauncherSettingsTests/Program.cs +++ b/tools/LauncherSettingsTests/Program.cs @@ -381,6 +381,96 @@ internal static class Program UserPrefsSwapRecovery.Recover(swap, true, true, null, DateTime.Now); Check(!File.Exists(swap.LivePath), "live file removed so the game writes its defaults"); }); + + // ── First Login dialog rules (a new server: no password, no characters yet) ── + Scenario("first login on a new server", root, () => + { + var withPw = new LaunchAccountProfile { Id = "ilt", AccountName = "silentkelpie" }; + withPw.SetPassword(Pw); + var noPwSame = new LaunchAccountProfile { Id = "other", AccountName = "SilentKelpie" }; + var conquest = new LaunchAccountProfile { Id = "new", AccountName = "SK", CharacterName = LaunchAccountProfile.NoneOption }; + var all = new List<LaunchAccountProfile> { withPw, noPwSame, conquest }; + + Check(FirstLoginRules.KnownAccountNames(all, "new").SequenceEqual(new[] { "silentkelpie" }), + "known names: the others, distinct ignoring case, not this profile's own"); + + Check(FirstLoginRules.SavedPasswordSource(all, "SILENTKELPIE", "new")?.Id == "ilt", + "the same name with a saved password can be reused (case ignored)"); + Check(FirstLoginRules.SavedPasswordSource(all, "SK", "new") == null, "a new name has none to reuse"); + Check(FirstLoginRules.SavedPasswordSource(all, "silentkelpie", "ilt") == null, "never the profile itself"); + + var copy = new LaunchAccountProfile { AccountName = "silentkelpie" }; + copy.CopyPasswordFrom(withPw); + Check(copy.PasswordProtected == withPw.PasswordProtected && copy.TryGetPasswordForLaunch(out string reused, out _) && reused == Pw, + "reuse copies the encrypted blob, and it decrypts"); + + var none = new List<string>(); + List<string> firstChoices = FirstLoginRules.LoginChoices(none, conquest.CharacterName); + Check(firstChoices.SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect }), + "no characters yet: only stop at character select (the old (None) isn't listed)"); + Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, none) == "", + "stop with none known saves \"\" so the first character created is picked next time"); + + var chars = new List<string> { "Alpha", "Beta" }; + Check(FirstLoginRules.LoginChoices(chars, "Gamma").SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect, "Gamma", "Alpha", "Beta" }), + "several characters: all listed, the saved one kept even if not seen yet"); + Check(FirstLoginRules.CharacterNameFor("Beta", chars) == "Beta", "picking a character saves it"); + Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, chars) == LaunchAccountProfile.NoneOption, + "stop with characters known saves the explicit (None)"); + + Check(FirstLoginRules.Problem("SK", "", "", false, AcEmulatorKind.Ace)?.StartsWith("Enter the password") == true, "a password is required"); + Check(FirstLoginRules.Problem("SK", "a", "b", false, AcEmulatorKind.Ace)?.Contains("don't match") == true, "the confirmation must match"); + Check(FirstLoginRules.Problem("SK", "pw", "pw", false, AcEmulatorKind.Ace) == null, "name + matching password: ready"); + Check(FirstLoginRules.Problem("silentkelpie", "", "", true, AcEmulatorKind.Ace) == null, "reusing a saved password needs no typing"); + Check(FirstLoginRules.Problem("a:b", "pw", "pw", false, AcEmulatorKind.Gdle) != null, "GDLE name with a colon refused"); + Check(FirstLoginRules.Problem("", "pw", "pw", false, AcEmulatorKind.Ace) != null, "a name is required"); + }); + + // A saved UserPreferences.ini whose display mode the PC can't use made every launch + // fail with "Could not initialize Direct3D"; a quick exit must undo that swap. + Scenario("prefs swap: did the swap change the live file", root, () => + { + byte[] a = "[Display]\nResolution=2560x1440\n"u8.ToArray(); + byte[] b = "[Display]\nResolution=1920x1080\n"u8.ToArray(); + Check(!UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, (byte[])a.Clone())), "same bytes: not the cause"); + Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, b)), "different bytes: changed"); + Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, null)), "no live file before: changed"); + }); + + Scenario("prefs swap: failed stash set aside, live file put back", root, () => + { + var (swap, legacy) = PrefsSwapFiles(legacyMatches: true); + var now = new DateTime(2026, 10, 14, 16, 30, 5); + UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, quarantineStash: true, restoreLive: true, legacy, now); + Check(!File.Exists(swap.StashPath), "stash no longer swappable"); + Check(r.QuarantinedStashPath == swap.StashPath + ".failed-20261014-163005" && File.Exists(r.QuarantinedStashPath), "stash kept as .failed-<time>"); + Check(!File.Exists(legacy) && r.QuarantinedLegacyPath != null, "identical name-only stash set aside too (it would re-seed)"); + Check(r.LiveRestored && File.ReadAllBytes(swap.LivePath).SequenceEqual(swap.PreviousLiveBytes!), "live file back to its pre-swap bytes"); + }); + + Scenario("prefs swap: different name-only stash kept", root, () => + { + var (swap, legacy) = PrefsSwapFiles(legacyMatches: false); + UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, true, true, legacy, DateTime.Now); + Check(File.Exists(legacy) && r.QuarantinedLegacyPath == null, "name-only stash with other settings left alone"); + }); + + Scenario("prefs swap: later swap or profile override", root, () => + { + var (swap, legacy) = PrefsSwapFiles(legacyMatches: true); + File.WriteAllText(swap.LivePath, "another account's settings"); + UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, quarantineStash: false, restoreLive: false, legacy, DateTime.Now); + Check(File.Exists(swap.StashPath) && File.Exists(legacy), "override: the user's file is never renamed"); + Check(!r.LiveRestored && File.ReadAllText(swap.LivePath) == "another account's settings", "later swap: live file untouched"); + }); + + Scenario("prefs swap: no live file before", root, () => + { + var (swap, _) = PrefsSwapFiles(legacyMatches: false); + swap = swap with { PreviousLiveBytes = null }; + UserPrefsSwapRecovery.Recover(swap, true, true, null, DateTime.Now); + Check(!File.Exists(swap.LivePath), "live file removed so the game writes its defaults"); + }); } finally {