diff --git a/native/Loader/Loader.c b/native/Loader/Loader.c index a9dd57b..84512af 100644 --- a/native/Loader/Loader.c +++ b/native/Loader/Loader.c @@ -145,33 +145,97 @@ static int IsManagedPe(const char* path) return nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress != 0; } -static void CleanStaleStagingFiles(const char* stagingDir) +// 1 = the process with this id is running and started before `staged` (the time its file +// was created), so the file may be that client's live engine; 0 = gone, or a newer +// process that only reuses the id. +static int ProcessOwnsStagedFile(DWORD pid, const FILETIME* staged) +{ + HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + if (!h) return GetLastError() == ERROR_ACCESS_DENIED; // running, can't look: leave it + int owns = WaitForSingleObject(h, 0) != WAIT_OBJECT_0; + FILETIME created, exited, kernel, user; + if (owns && GetProcessTimes(h, &created, &exited, &kernel, &user) && CompareFileTime(&created, staged) > 0) + owns = 0; + CloseHandle(h); + return owns; +} + +// Deletes the staged engines (.dll + .pdb) no client needs: this client's older +// generations, and the files of clients that have closed. Never another live client's: +// until 2026-10-09 every file went, and a client staging at the same moment (every +// watcher fires within ~1.5 s of an engine publish) lost its file mid-load - a missing +// file, or worse a "loaded" image with broken IL (ops/overnight/2026-10-08-gen4-corrupt-load.md). +static void CleanStaleStagingFiles(const char* stagingDir, int generation) { char pattern[MAX_PATH]; - _snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\RynthCore.Engine.p*.gen*.*", stagingDir); // .dll + .pdb + _snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\RynthCore.Engine.p*.gen*.*", stagingDir); WIN32_FIND_DATAA fd; HANDLE f = FindFirstFileA(pattern, &fd); if (f == INVALID_HANDLE_VALUE) return; + DWORD self = GetCurrentProcessId(); do { + unsigned long pid = 0; + int gen = 0; + if (sscanf_s(fd.cFileName, "RynthCore.Engine.p%lu.gen%d.", &pid, &gen) != 2) continue; + int stale = pid == self ? gen < generation : !ProcessOwnsStagedFile((DWORD)pid, &fd.ftCreationTime); + if (!stale) continue; char p[MAX_PATH]; _snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", stagingDir, fd.cFileName); - DeleteFileA(p); // fails for files a live process still maps: fine + DeleteFileA(p); // fails for files still mapped or guarded: fine } while (FindNextFileA(f, &fd)); FindClose(f); } +// Writes a copy of `src` to `dst` and returns a handle that keeps `dst` from being deleted +// (no FILE_SHARE_DELETE) until it is closed; INVALID_HANDLE_VALUE on failure. Held through +// the engine load, so nothing can pull the file out from under CoreCLR/LoadLibrary (a +// guard like this took 100 of 100 racing deletes in the offline repro, every load clean). +// The guard only reads, so the loader's own read-only opens of the file still succeed. +static HANDLE CopyGuarded(const char* src, const char* dst) +{ + HANDLE in = CreateFileA(src, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (in == INVALID_HANDLE_VALUE) return INVALID_HANDLE_VALUE; + HANDLE out = CreateFileA(dst, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (out == INVALID_HANDLE_VALUE) { + DWORD e = GetLastError(); + CloseHandle(in); + SetLastError(e); + return INVALID_HANDLE_VALUE; + } + static unsigned char buf[256 * 1024]; + DWORD read = 0, written = 0; + BOOL ok = TRUE; + while (ok && (ok = ReadFile(in, buf, sizeof buf, &read, NULL)) && read > 0) + ok = WriteFile(out, buf, read, &written, NULL) && written == read; + DWORD e = GetLastError(); + CloseHandle(in); + // The read-only guard opens before the writer closes, so there's no gap to delete in. + HANDLE guard = ok ? CreateFileA(dst, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL) : INVALID_HANDLE_VALUE; + if (guard == INVALID_HANDLE_VALUE && ok) e = GetLastError(); + CloseHandle(out); + if (guard == INVALID_HANDLE_VALUE) { + DeleteFileA(dst); + SetLastError(e); + } + return guard; +} + // Copies the canonical engine to .engine_loads\RynthCore.Engine.p.gen.dll so the // canonical file is never locked (a developer can copy over it) and every generation is -// a distinct module/assembly path. -static int StageEngine(int generation, char* stagedPath, size_t cap) +// a distinct module/assembly path. *guard keeps the copy undeletable until the caller +// closes it (after the load). +static int StageEngine(int generation, char* stagedPath, size_t cap, HANDLE* guard) { char stagingDir[MAX_PATH]; _snprintf_s(stagingDir, sizeof stagingDir, _TRUNCATE, "%s\\" STAGING_SUBDIR, g_loaderDir); CreateDirectoryA(stagingDir, NULL); - CleanStaleStagingFiles(stagingDir); + CleanStaleStagingFiles(stagingDir, generation); _snprintf_s(stagedPath, cap, _TRUNCATE, "%s\\RynthCore.Engine.p%lu.gen%d.dll", stagingDir, GetCurrentProcessId(), generation); - if (!CopyFileA(g_enginePath, stagedPath, FALSE)) { + *guard = CopyGuarded(g_enginePath, stagedPath); + if (*guard == INVALID_HANDLE_VALUE) { LoaderLog("ERR", "StageEngine: copy to %s failed (error %lu)", stagedPath, GetLastError()); return 0; } @@ -202,19 +266,24 @@ static unsigned int LoadAndInitEngine(void) HooksBeginGeneration(g_initCount); char staged[MAX_PATH]; - if (!StageEngine(g_initCount, staged, sizeof staged)) return 11; + HANDLE guard; + if (!StageEngine(g_initCount, staged, sizeof staged, &guard)) return 11; if (!FileLastWrite(g_enginePath, &g_canonicalWrite)) GetSystemTimeAsFileTime(&g_canonicalWrite); + // The guard stays open until the load returns; after that the image mapping holds the file. if (g_engineIsManaged) { int rc = ClrLoadEngine(g_initCount, staged); + CloseHandle(guard); if (rc != 0) { LoaderLog("ERR", "Managed engine gen %d failed to load (rc=%d)", g_initCount, rc); return 4; } } else { HMODULE m = LoadLibraryA(staged); + DWORD e = GetLastError(); + CloseHandle(guard); if (!m) { - LoaderLog("ERR", "LoadLibrary failed for engine (path=%s, error %lu)", staged, GetLastError()); + LoaderLog("ERR", "LoadLibrary failed for engine (path=%s, error %lu)", staged, e); return 4; } g_engineModule = m; diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index f153763..1b562c4 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -66,7 +66,10 @@ internal sealed record PanelSpec( ImGuiWindowFlags BodyFlags = ImGuiWindowFlags.None, // Where the panel first opens (logical units) when nothing is saved for its // key; null = the cascade. (Script windows: a FirstUseEver position.) - Vector2? DefaultPos = null); + Vector2? DefaultPos = null, + // No resize grip, docked or popped out: the face sizes itself (the RynthNav arrow + // fits its height to what it shows). Chromeless and GripInBody panels only. + bool NoResize = false); /// An ImGui panel face. One instance per open; dropped on close. internal interface IImGuiPanel @@ -628,7 +631,7 @@ internal static class ImGuiPanelHost bool standard = entry.Spec.Chrome == PanelChrome.Standard; int caption = standard ? (int)(RynthTheme.HeaderHeight * s) : 0; int buttons = standard ? (int)HeaderButtonsWidth(entry, s, popped: true) : 0; - ImGuiPopOuts.Open(entry.Title, left, top, (int)size.X, (int)size.Y, caption, buttons, s); + ImGuiPopOuts.Open(entry.Title, left, top, (int)size.X, (int)size.Y, caption, buttons, s, resizable: !entry.Spec.NoResize); entry.Popped = true; PersistPopped(entry, open: true, left, top, (int)size.X, (int)size.Y, placeScale); } @@ -789,7 +792,8 @@ internal static class ImGuiPanelHost // A GripInBody face (standard chrome, no strip under the body) is handled // the same way, over the corner the face leaves free. bool inlineGrip = standard && spec.GripInBody; - bool manualGrip = (!standard || inlineGrip) && !clickThrough && !popped; // popped: the window resizes itself + bool manualGrip = (!standard || inlineGrip) && !clickThrough && !popped // popped: the window resizes itself + && !spec.NoResize; Vector2 outerPos = ImGuiNET.ImGui.GetWindowPos(), outerSize = ImGuiNET.ImGui.GetWindowSize(); float gSize = GripSize(entry, uiScale); Vector2 gMin = GripMin(entry, uiScale, outerPos + outerSize); diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs index 70cea94..66af08c 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -148,7 +148,7 @@ internal static unsafe class ImGuiPopOuts /// current (its font atlas is shared). AC thread. /// public static void Open(string title, int left, int top, int width, int height, int captionHeight, int captionRightInset, float uiScale, - Action? draw = null, Action? onMoved = null, bool sizeToContent = false) + Action? draw = null, Action? onMoved = null, bool sizeToContent = false, bool resizable = true) { if (Pops.ContainsKey(title)) return; IntPtr main = ImGuiNET.ImGui.GetCurrentContext(); @@ -173,7 +173,7 @@ internal static unsafe class ImGuiPopOuts Title = title, Context = ctx, Left = left, Top = top, Width = Math.Max(80, width), Height = Math.Max(40, height), CaptionHeight = captionHeight, CaptionRightInset = captionRightInset, - Draw = draw, OnMoved = onMoved, SizeToContent = sizeToContent, ResizeGrip = !sizeToContent, + Draw = draw, OnMoved = onMoved, SizeToContent = sizeToContent, ResizeGrip = resizable && !sizeToContent, }; Pops[title] = pop; Order.Add(pop); diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs index 3278248..4371e91 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs @@ -9,8 +9,11 @@ // arrow turns with you every frame (the pose snapshot's heading); green // within 30 yd, amber while it points at a portal on a route; a // wand instead of the arrow when the next step is a recall. -// text name, distance and compass point, the route step. -// buttons pop out, hide; Go (RynthNav walks there) and Stop. +// text name, distance and compass point, the route step (n/m). +// row a box for coordinates or a place (Plan: route only; Enter or Go: RynthNav goes +// there), Plan, Go, Stop, and the caret: the route's steps open +// under it, current one green (the window fits its height). +// corner small pop out and hide buttons. No resize grip: it sizes itself. // // The target comes from RynthNav's status (UiSources.RynthNav); RynthNav owns // it and decides arrival. AC's render thread: snapshots only, no AC calls, and @@ -32,8 +35,10 @@ internal sealed class RynthNavArrowFace : IImGuiPanel { public const string Title = "RynthNav Arrow"; + // Sized to its content (FitHeight): these are only the first-open size and the narrowest it goes. public static void Register() => ImGuiPanelHost.Register(Title, - new PanelSpec(new Vector2(236, 84), new Vector2(236, 84), PanelChrome.None, Background: 0, Rounding: 6, EdgeToEdge: true), + new PanelSpec(new Vector2(232, 68), new Vector2(232, 60), PanelChrome.None, Background: 0, Rounding: 6, EdgeToEdge: true, + NoResize: true), () => new RynthNavArrowFace()); /// Shows the overlay (any thread). Only where ImGui faces are drawn. @@ -46,14 +51,26 @@ 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); + private static readonly uint Glass = RynthTheme.Argb(0xDC0A0F14), Ring = RynthTheme.Argb(0xFF1A2A39), + InputBg = RynthTheme.Argb(0xFF0E1822), Purple = RynthTheme.Argb(0xFFB48CF0), Done = Faded(Mute); + + private const int MaxRouteRows = 8; private readonly ArrowReadout _read = new(); + // What to go to: coordinates ("42.1N 33.6E", "42.1, 33.6") or a place the Atlas knows. + private readonly byte[] _target = new byte[128]; + private bool _showRoute; + // Plan was pressed: open the steps when the planned route arrives (a new Route array). + private RynthNavRouteStep[]? _openWhenNot; + private int _scrolledTo = -1; + private float _requestedH = -1; public void OnShown() { UiSources.RynthNav.Subscribe(); UiSources.RynthNav.RequestRefresh(); + _showRoute = false; + _requestedH = -1; } public void OnHidden() => UiSources.RynthNav.Unsubscribe(); @@ -63,62 +80,188 @@ internal sealed class RynthNavArrowFace : IImGuiPanel var dl = ImGuiNET.ImGui.GetWindowDrawList(); Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); - if (size.X < 40 || size.Y < 40) return; + if (size.X < 40 || size.Y < 30) return; RynthNavStatus? st = UiSources.RynthNav.Current?.Value; _read.Update(st); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f10 = ImGuiFonts.Get(UiFont.Ui10), f9 = ImGuiFonts.Get(UiFont.Ui9); + const float pad = 5, gap = 3; + float b = MathF.Round(MathF.Max(20, f10.FontSize + 8)); // buttons and the input row + float d = MathF.Round(bold.FontSize + f10.FontSize + 14); // the arrow's ring + float rowY = origin.Y + pad + d + 4; + bool hasRoute = st != null && st.Route.Length > 0 && st.RouteLines.Length > 0; + if (_openWhenNot != null && hasRoute && !ReferenceEquals(st!.Route, _openWhenNot)) { _showRoute = true; _scrolledTo = -1; _openWhenNot = null; } + if (!hasRoute) _showRoute = false; + float lineH = f10.FontSize + 3; + int rows = hasRoute ? Math.Min(st!.Route.Length, MaxRouteRows) : 0; + float listH = _showRoute ? MathF.Round(bold.FontSize + 4 + rows * lineH + 6) : 0; + float wantH = pad + d + 4 + b + pad + (_showRoute ? 4 + listH : 0); + FitHeight(wantH, size.Y); + dl.AddRectFilled(origin, origin + size, Glass, 6); dl.AddRect(origin, origin + size, BtnBord, 6); // The arrow, in a ring on the left. - float d = size.Y - 12; - Vector2 c = origin + new Vector2(6 + d * 0.5f, size.Y * 0.5f); + Vector2 c = origin + new Vector2(pad + d * 0.5f, pad + d * 0.5f); dl.AddCircleFilled(c, d * 0.5f, ShellBg, 32); dl.AddCircle(c, d * 0.5f, Ring, 32, 1.5f); - _read.DrawPointer(dl, c, d * 0.5f - 6); + _read.DrawPointer(dl, c, d * 0.5f - 5); - // Text. - float tx = origin.X + d + 14, right = origin.X + size.X - 6; - ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f10 = ImGuiFonts.Get(UiFont.Ui10), f9 = ImGuiFonts.Get(UiFont.Ui9); - dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 46, origin.Y + size.Y), true); - dl.AddText(bold, bold.FontSize, new Vector2(tx, origin.Y + 6), Teal, _read.Line1); + // Name, then distance and compass point (the route step on the right of it). + float tx = origin.X + pad + d + 8, right = origin.X + size.X - pad; + const float sb = 14; // the corner buttons: small, for a small panel + dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 2 * sb - 4, origin.Y + size.Y), true); + dl.AddText(bold, bold.FontSize, new Vector2(tx, origin.Y + pad + 2), Teal, _read.Line1); dl.PopClipRect(); - dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right, origin.Y + size.Y), true); - dl.AddText(f10, f10.FontSize, new Vector2(tx, origin.Y + 26), Text, _read.Line2); - dl.PopClipRect(); - dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - 48, origin.Y + size.Y), true); - dl.AddText(f9, f9.FontSize, new Vector2(tx, origin.Y + size.Y - 6 - f9.FontSize - 2), Mute, _read.Line3); + string step = _read.HasTarget && st?.Arrow is { Steps: > 1 } sa ? $"{sa.Step}/{sa.Steps}" : ""; + float stepW = step.Length > 0 ? f9.CalcTextSizeA(f9.FontSize, float.MaxValue, 0, step).X + 4 : 0; + float line2Y = origin.Y + pad + 2 + bold.FontSize + 4; + dl.PushClipRect(new Vector2(tx, origin.Y), new Vector2(right - stepW, origin.Y + size.Y), true); + if (_read.HasTarget) dl.AddText(f10, f10.FontSize, new Vector2(tx, line2Y), Text, _read.Line2); + else dl.AddText(f9, f9.FontSize, new Vector2(tx, line2Y + 1), Mute, _read.Line3.Length > 0 ? "Type coordinates or a place below" : ""); dl.PopClipRect(); + if (step.Length > 0) dl.AddText(f9, f9.FontSize, new Vector2(right - stepW + 4, line2Y + 1), Mute, step); - // Buttons (before the surface, so they win the hover). - const float b = 20, gap = 3; - var closePos = new Vector2(right - b, origin.Y + 5); - var popPos = closePos - new Vector2(b + gap, 0); + // Top-right corner: pop out, hide (small and flat). + var closePos = new Vector2(origin.X + size.X - 3 - sb, origin.Y + 3); + var popPos = closePos - new Vector2(sb + 2, 0); if (PanelRouter.CanPopOut) { - if (IconButton("##rna_pop", ImGuiPanelHost.PopOutGlyph, popPos, new Vector2(b, b), Mute, BtnFill, font: UiFont.Ui11)) + if (IconButton("##rna_pop", ImGuiPanelHost.PopOutGlyph, popPos, new Vector2(sb, sb), Done, Glass, font: UiFont.Ui9)) ImGuiPanelHost.TogglePopOut(Title); ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); } - if (IconButton("##rna_close", PhosphorIcons.X, closePos, new Vector2(b, b), Mute, BtnFill, font: UiFont.Ui11)) + if (IconButton("##rna_close", PhosphorIcons.X, closePos, new Vector2(sb, sb), Done, Glass, font: UiFont.Ui9)) ImGuiPanelHost.Close(Title); ImGuiNET.ImGui.SetItemTooltip("Hide the arrow (the RynthNav panel's Arrow tab shows it again)"); - var stopPos = new Vector2(right - b, origin.Y + size.Y - b - 5); + + // Bottom row: where to go, Plan, Go, Stop, the route's steps. + var routePos = new Vector2(right - b, rowY); + var stopPos = routePos - new Vector2(b + gap, 0); var goPos = stopPos - new Vector2(b + gap, 0); - bool canGo = _read.CanGo; - if (IconButton("##rna_go", PhosphorIcons.Play, goPos, new Vector2(b, b), Green, BtnFill, enabled: canGo, font: UiFont.Ui11) - && st?.Arrow is RynthNavArrow ar) - RynthNavCommands.Go(ar.Final, ar.FinalNs, ar.FinalEw); - ImGuiNET.ImGui.SetItemTooltip("Go: RynthNav walks there (with portals and recalls when its routing is on)"); + var planPos = goPos - new Vector2(b + gap, 0); + float inputX = origin.X + pad, inputW = planPos.X - gap - inputX; + string typed = TypedTarget(); + bool enter = TargetInput(inputX, rowY, inputW, b, f10); + bool canGo = typed.Length > 0 || _read.CanGo; + if (IconButton("##rna_plan", PhosphorIcons.Path, planPos, new Vector2(b, b), Teal, BtnFill, enabled: canGo, font: UiFont.Ui11) && canGo) + { + _openWhenNot = st?.Route ?? Array.Empty(); + 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 + ? "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 + ? "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) + { + if (typed.Length > 0) RynthNavCommands.Command("go " + typed); + else if (st?.Arrow is RynthNavArrow ar) RynthNavCommands.Go(ar.Final, ar.FinalNs, ar.FinalEw); + } if (IconButton("##rna_stop", PhosphorIcons.Stop, stopPos, new Vector2(b, b), Red, BtnFill, font: UiFont.Ui11)) RynthNavCommands.Move(5); ImGuiNET.ImGui.SetItemTooltip("Stop walking"); + if (IconButton("##rna_route", _showRoute ? PhosphorIcons.CaretUp : PhosphorIcons.CaretDown, routePos, new Vector2(b, b), _showRoute ? Teal : Mute, + _showRoute ? Selected : BtnFill, enabled: hasRoute, font: UiFont.Ui11)) + { + _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"); - // Surface: drag moves the overlay (the OS window when popped out). + if (_showRoute && hasRoute) + RouteList(st!, new Vector2(origin.X + pad, rowY + b + 4), new Vector2(size.X - 2 * pad, listH), bold, lineH); + + // Surface: drag moves the overlay (the OS window when popped out). The top part only: + // the row below is the input box and buttons, the list scrolls. ImGuiNET.ImGui.SetCursorScreenPos(origin); - ImGuiNET.ImGui.InvisibleButton("##rna_surface", size); + 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); + if (ImGuiNET.ImGui.IsItemHovered() && _read.Tooltip.Length > 0) + ImGuiNET.ImGui.SetItemTooltip(_read.Tooltip + (_read.Line3.Length > 0 && _read.Kind == "portal" ? "\n" + _read.Line3 : "")); + } + + /// The coordinates or place typed in the box, trimmed. + private string TypedTarget() + { + int n = Array.IndexOf(_target, (byte)0); + return System.Text.Encoding.UTF8.GetString(_target, 0, n < 0 ? _target.Length : n).Trim(); + } + + /// The target box, with a grey hint while empty; true when Enter was pressed in it. + private bool TargetInput(float x, float y, float w, float h, ImFontPtr font) + { + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); + ImGuiNET.ImGui.SetNextItemWidth(w); + ImGuiNET.ImGui.PushFont(font); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, InputBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(5, MathF.Max(0, (h - font.FontSize) * 0.5f))); + bool enter = ImGuiNET.ImGui.InputText("##rna_target", _target, (uint)_target.Length, ImGuiInputTextFlags.EnterReturnsTrue); + bool active = ImGuiNET.ImGui.IsItemActive(); + ImGuiNET.ImGui.SetItemTooltip("Coordinates (42.1N 33.6E) or a place the Atlas knows, then Enter or Go"); + ImGuiNET.ImGui.PopStyleVar(3); + ImGuiNET.ImGui.PopStyleColor(3); + if (_target[0] == 0 && !active) + ImGuiNET.ImGui.GetWindowDrawList().AddText(font, font.FontSize, new Vector2(x + 6, y + (h - font.FontSize) * 0.5f), Done, "42.1N 33.6E or a place"); + ImGuiNET.ImGui.PopFont(); + return enter; + } + + /// The route's steps under the row: the header, then one line each (done greyed, current green). + private void RouteList(RynthNavStatus st, Vector2 pos, Vector2 listSize, ImFontPtr bold, float lineH) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(pos, pos + listSize, ShellBg, 4); + dl.PushClipRect(pos, pos + new Vector2(listSize.X, bold.FontSize + 4), true); + dl.AddText(bold, bold.FontSize, pos + new Vector2(4, 2), Text, st.RouteHeader); + dl.PopClipRect(); + float top = pos.Y + bold.FontSize + 4; + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, top)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 3)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 0)); + if (ImGuiNET.ImGui.BeginChild("##rna_steps", new Vector2(listSize.X, pos.Y + listSize.Y - top - 2), ImGuiChildFlags.None, + ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.HorizontalScrollbar)) + { + int n = Math.Min(st.Route.Length, st.RouteLines.Length); + for (int i = 0; i < n; i++) + { + RynthNavRouteStep s = st.Route[i]; + bool current = st.RouteActive && i == st.RouteIdx, done = st.RouteActive && i < st.RouteIdx; + uint col = current ? Green : done ? Done + : s.Kind == "recall" ? Amber : s.Kind == "portal" ? Purple : s.Kind == "town" ? Teal : Text; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, col); + 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]); + if (current && _scrolledTo != i) { ImGuiNET.ImGui.SetScrollHereY(0.3f); _scrolledTo = i; } + } + } + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(2); + } + + /// + /// Fits the window's height to what it shows (the route list opens and closes it), docked. + /// Popped out the OS window keeps its size, as other faces do (RynthAiFace). + /// + private void FitHeight(float wantPx, float havePx) + { + if (ImGuiPopOuts.InPopOutFrame) return; + float place = ImGuiPanelHost.PlacementScale(); + float extra = ImGuiNET.ImGui.GetWindowHeight() - havePx; // anything around the body + float want = MathF.Ceiling((wantPx + extra) / place); + if (MathF.Abs(havePx - wantPx) < 1.5f || MathF.Abs(want - _requestedH) < 0.5f) return; + _requestedH = want; + ImGuiPanelHost.RequestSize(Title, new Vector2(ImGuiNET.ImGui.GetWindowWidth() / place, want)); } } diff --git a/tools/LoaderStagingTests/Run-Tests.ps1 b/tools/LoaderStagingTests/Run-Tests.ps1 new file mode 100644 index 0000000..c72d87a --- /dev/null +++ b/tools/LoaderStagingTests/Run-Tests.ps1 @@ -0,0 +1,24 @@ +# Builds and runs the offline staging checks against the real native/Loader/Loader.c (x86, MSVC): +# CleanStaleStagingFiles only deletes this client's older generations and closed clients' files, +# and CopyGuarded keeps the staged engine undeletable through the load. +$ErrorActionPreference = "Stop" +$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name +$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer" +$cl = "$vcBase\bin\Hostx86\x86\cl.exe" +$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name +$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer" +$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer" +$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared" +$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86" + +$L = (Resolve-Path (Join-Path $PSScriptRoot "..\..\native\Loader")).Path +$out = Join-Path $env:TEMP "LoaderStagingTests" +New-Item -ItemType Directory -Force $out | Out-Null +Push-Location $out +try { + & $cl /nologo /O2 /MT /W4 /wd4100 /I $L (Join-Path $PSScriptRoot "test.c") "$L\Hooks.c" "$L\Clr.c" "$L\Services.c" user32.lib /Fe:test.exe + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & .\test.exe @args + exit $LASTEXITCODE +} finally { Pop-Location } diff --git a/tools/LoaderStagingTests/test.c b/tools/LoaderStagingTests/test.c new file mode 100644 index 0000000..7270e8d --- /dev/null +++ b/tools/LoaderStagingTests/test.c @@ -0,0 +1,124 @@ +// Offline checks for Loader.c's staging: CleanStaleStagingFiles rules and CopyGuarded. +// Built with the real Loader.c included, so these are the shipped functions. +#include "Loader.c" + +static int fails; +#define CHECK(c, ...) do { if (c) printf("ok "); else { printf("FAIL "); fails++; } printf(__VA_ARGS__); printf("\n"); } while (0) + +static char dir[MAX_PATH]; + +static void Touch(const char* name, const FILETIME* created) +{ + char p[MAX_PATH]; + _snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", dir, name); + HANDLE h = CreateFileA(p, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (created) SetFileTime(h, created, NULL, NULL); + CloseHandle(h); +} + +static int Exists(const char* name) +{ + char p[MAX_PATH]; + _snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", dir, name); + return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES; +} + +static volatile LONG stop; +static char racePath[MAX_PATH]; +static volatile LONG deleted, refused32, refusedOther; +static DWORD WINAPI Deleter(LPVOID unused) +{ + while (!stop) { + if (DeleteFileA(racePath)) InterlockedIncrement(&deleted); + else if (GetLastError() == ERROR_SHARING_VIOLATION) InterlockedIncrement(&refused32); + else if (GetLastError() != ERROR_FILE_NOT_FOUND) InterlockedIncrement(&refusedOther); + } + return 0; +} + +int main(int argc, char** argv) +{ + InitializeCriticalSection(&g_logLock); + GetFullPathNameA("stage", sizeof dir, dir, NULL); + CreateDirectoryA(dir, NULL); + DWORD self = GetCurrentProcessId(); + + // A live other process (started now), a dead pid, and an old file for the live pid (pid reuse). + STARTUPINFOA si = { sizeof si }; + PROCESS_INFORMATION pi; + char cmd[] = "C:\\Windows\\System32\\ping.exe -n 30 127.0.0.1"; + CreateProcessA(NULL, cmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi); + Sleep(200); + DWORD live = pi.dwProcessId; + DWORD dead = 0; + for (DWORD p = 60000; p < 200000; p += 4) { // an id nothing is using + HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, p); + if (!h && GetLastError() == ERROR_INVALID_PARAMETER) { dead = p; break; } + if (h) CloseHandle(h); + } + FILETIME year2000 = { 0x0D53C000, 0x01BF53EB }; // older than any running process + + char n[12][96]; + _snprintf_s(n[0], 96, _TRUNCATE, "RynthCore.Engine.p%lu.gen1.dll", self); + _snprintf_s(n[1], 96, _TRUNCATE, "RynthCore.Engine.p%lu.gen1.pdb", self); + _snprintf_s(n[2], 96, _TRUNCATE, "RynthCore.Engine.p%lu.gen2.dll", self); + _snprintf_s(n[3], 96, _TRUNCATE, "RynthCore.Engine.p%lu.gen3.dll", self); // the one being staged now + _snprintf_s(n[4], 96, _TRUNCATE, "RynthCore.Engine.p%lu.gen4.dll", live); + _snprintf_s(n[5], 96, _TRUNCATE, "RynthCore.Engine.p%lu.gen4.pdb", live); + _snprintf_s(n[6], 96, _TRUNCATE, "RynthCore.Engine.p%lu.gen2.dll", dead); + _snprintf_s(n[7], 96, _TRUNCATE, "RynthCore.Engine.p%lu.gen2.pdb", dead); + _snprintf_s(n[8], 96, _TRUNCATE, "RynthCore.Engine.p%lu.gen9.dll", live); // older than the live process: a reused id + _snprintf_s(n[9], 96, _TRUNCATE, "RynthCore.Engine.p4.gen1.dll"); // System (pid 4): access denied = leave it + _snprintf_s(n[10], 96, _TRUNCATE, "RynthCore.Engine.dll.notours"); + for (int i = 0; i < 11; i++) Touch(n[i], i == 8 ? &year2000 : NULL); + + CleanStaleStagingFiles(dir, 3); + CHECK(!Exists(n[0]) && !Exists(n[1]) && !Exists(n[2]), "own older generations (dll + pdb) deleted"); + CHECK(Exists(n[3]), "own current generation kept"); + CHECK(Exists(n[4]) && Exists(n[5]), "a live client's files kept (pid %lu)", live); + CHECK(dead != 0 && !Exists(n[6]) && !Exists(n[7]), "a closed client's files deleted (pid %lu)", dead); + CHECK(!Exists(n[8]), "a file older than the process now using its id deleted"); + CHECK(Exists(n[9]), "pid that can't be opened (access denied) kept"); + CHECK(Exists(n[10]), "names not matching p.gen untouched"); + TerminateProcess(pi.hProcess, 0); + WaitForSingleObject(pi.hProcess, 5000); + CloseHandle(pi.hProcess); CloseHandle(pi.hThread); + CleanStaleStagingFiles(dir, 3); + CHECK(!Exists(n[4]) && !Exists(n[5]), "that client's files deleted once it closed"); + + // CopyGuarded: a native DLL (LoadLibrary path) copied under a guard, with a thread + // hammering DeleteFileA the whole time. + const char* src = argc > 1 ? argv[1] : "C:\\Windows\\SysWOW64\\version.dll"; + int clean = 0, trials = 50; + for (int t = 0; t < trials; t++) { + _snprintf_s(racePath, sizeof racePath, _TRUNCATE, "%s\\RynthCore.Engine.p%lu.gen%d.dll", dir, self, 100 + t); + stop = 0; deleted = 0; + HANDLE th = CreateThread(NULL, 0, Deleter, NULL, 0, NULL); + HANDLE guard = CopyGuarded(src, racePath); + // What CoreCLR does: open read-only, sharing read. + HANDLE ro = CreateFileA(racePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + HMODULE m = guard != INVALID_HANDLE_VALUE ? LoadLibraryExA(racePath, NULL, DONT_RESOLVE_DLL_REFERENCES) : NULL; + LONG delWhileGuarded = deleted; + if (guard != INVALID_HANDLE_VALUE) CloseHandle(guard); + stop = 1; + WaitForSingleObject(th, INFINITE); + CloseHandle(th); + // Mapped: still undeletable after the guard closes. + BOOL delAfter = DeleteFileA(racePath); + if (guard != INVALID_HANDLE_VALUE && ro != INVALID_HANDLE_VALUE && m && delWhileGuarded == 0 && !delAfter) clean++; + if (ro != INVALID_HANDLE_VALUE) CloseHandle(ro); + if (m) FreeLibrary(m); + DeleteFileA(racePath); + } + CHECK(clean == trials, "guarded copy: %d/%d trials loaded with no delete getting through (refused %ld, other errors %ld)", + clean, trials, refused32, refusedOther); + + // A copy that fails (missing source) leaves nothing behind and reports the error. + _snprintf_s(racePath, sizeof racePath, _TRUNCATE, "%s\\RynthCore.Engine.p%lu.gen999.dll", dir, self); + HANDLE bad = CopyGuarded("C:\\nope\\missing.dll", racePath); + CHECK(bad == INVALID_HANDLE_VALUE && GetLastError() != 0 && GetFileAttributesA(racePath) == INVALID_FILE_ATTRIBUTES, + "missing source: no guard, no partial file (error %lu)", GetLastError()); + + printf(fails ? "\n%d FAILED\n" : "\nALL PASSED\n", fails); + return fails; +}