diff --git a/README.md b/README.md index 1dde503..6c3457b 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,12 @@ timing, position/velocity, movement, control/force state, tasks, camera/clipping and error counters. F1 also has a Live Overlay toggle. Visibility stays selected across scene changes during the session; `--debug-overlay` enables it at startup. +Level changes keep the same window and Vulkan renderer, preserving window bounds, +focus and fullscreen state. UI scales uniformly on widescreen: prompts/F1 stay +centered, objectives stay bottom-right and F2 stays top-left. Use +`--width 1920 --height 1080` for an initial window/offscreen size; resizing and F11 +update UI placement and clicks. + The original lab pickup is internally tagged `shrinkray`; the original objective art identifies it as the **jet pack**. Its practice prompt accepts **Y** or a click on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the @@ -107,6 +113,9 @@ scripts/build-windows.sh scripts/package.sh ``` +After building, `scripts/test-window-transitions.sh` runs a local Linux fullscreen/ +ultrawide regression using installed Xvfb, Xfwm, D-Bus and xprop. + The publish scripts perform equivalent self-contained publishes: ```bash diff --git a/docs/architecture.md b/docs/architecture.md index a8e6b56..69a2b0f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -68,8 +68,9 @@ remain provisional. TaskStates and TaskActivation retain original case/sentinel/numeric gates. OriginalSave accounts for every TSK byte and preserves unknown data. SceneInteractions implements star/trophy/lab jetpack contacts, Carl dialogue dispatch and LOAD requests, tracking -contact entry by source offset (duplicate tags remain distinct). Main disposes -renderer/window/audio before rebuilding the next scene, carrying task/items/score. +contact entry by source offset (duplicate tags remain distinct). Main owns a +RenderSession across loads, replacing scene resources and per-level audio while +preserving the window/Vulkan core and carrying task/items/score. Checkpoint CLI saves use atomic replacement outside asset directories; complete runtime saves, menus and configuration are not yet implemented. @@ -98,8 +99,9 @@ PracticePrompt implements source strict Yes/No regions and keyboard dispatch; Program pauses simulation while modal, clears held input and rebuilds VR04 on Yes. SceneHud appends source640x480 screen quads; the Vulkan overlay pipeline disables depth and draws after world geometry using identity transforms. Full HUD state -and practice highlighting remain incomplete. Fixed-size authored art -is scaled with the viewport; input uses matching logical-window coordinates. +and practice highlighting remain incomplete. UiViewport applies uniform art scale +and explicit anchors; input maps logical coordinates into actual drawable pixels +before inverse modal mapping. Prepared effects/effects.json preserves251 original SoundEffects.omt identities and RIFF payloads, including one MPEG-in-RIFF resource whose playback is unverified. @@ -170,3 +172,9 @@ key and never enters the menu's pause/input-reset boundary. F1 selects the full menu layout while open, otherwise the same overlay ranges display compact live diagnostics. The source viewport/projection decision supplies actual camera/far data. No debug visibility state is written into the original TSK wire format. + +RenderSession owns presentation until exit. Renderer replacement stages scene +buffers/textures/descriptors, preserving device/surface/swapchain/layouts/pipelines +and current targets. Resize/fullscreen replace size-dependent resources. Revision +and native identities support checks. See presentation-and-ui.md for rollback, +widescreen policy and runtime verification boundaries. diff --git a/docs/compatibility.md b/docs/compatibility.md index 6aaf548..483e36f 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -23,6 +23,8 @@ separate evidence categories. **The game is not fully reconstructed/playable yet | Null-material visibility | Binary rule implemented/tested | Original DX renderer skips null pointers; proxy geometry retained | | SDL3 presentation/input | Linux Xvfb + GTX1070 | Six frames; injected keyboard event received | | Swapchain resize | Linux tested | 960x720 ->800x600, zero validation errors | +| Persistent level presentation | Native GTX1070 six-load pass |One window/renderer; stable IDs/core resources, bounds/focus/fullscreen; invalid load retains rendering; zero cumulative Vulkan errors | +| Widescreen HUD/debug UI | Managed matrix + native captures/pointer pass |Uniform proportions, centered modal/F1, anchored HUD/F2;4:3/16:9/21:9/32:9, DPI and strict boundary checks | | F1 debug menu | Managed/SDL audio tests + native Linux GTX1070 window pass |Pause/actions/input capture/resume/800x600 resize, zero validation errors;33 prepared scene/start choices; intentional modern tools, no new Windows runtime claim | | F1 Force Control | Menu/director/interaction checks + native Linux SDL pass |Persistent override through source shots; disable/reset restores normal ownership; actual movement with neutron1a active, zero Vulkan errors; music handoff regression passes | | F2 live debug overlay | Managed timing/layout/menu + native Linux SDL pass |Non-pausing movement, visibility/repeat/menu priority and800x600 resize; all checks true, zero Vulkan errors; session persistence; modern tools, no new Windows runtime claim | @@ -40,7 +42,7 @@ separate evidence categories. **The game is not fully reconstructed/playable yet | Dynamic actors/sprites/models | Linux GPU pass |Carl/Goddard/Jimmy morphs, source Canv timing and9 original lab props; billboard/alpha, pivots and playback timing remain provisional | | Scene music/speech | Linux dummy-device pass |CAM stops music before speech; full lab chain stays silent, DEFAULT restarts on completion/skip; reset tested. Packaged Linux/Wine64 lifecycle checks pass; speakers/latency/native Windows unverified | | VR01 star/trophy contacts | Source-data tests pass |5-point stars,300 trophy, acquired flags and contact-enter semantics; distance/exclusions/box approximation | -| RETURN / renderer recreation |Source byte/helper/director tests + Linux headless pass |Lab/VR04/lab restores live departure root and companion, retains STRT yaw and suppresses intro once; fresh TSK loading separate; fades/window transition unverified | +| RETURN / scene reload |Source/director tests + Linux headless pass |Lab/VR04/lab restores departure root/companion using one renderer, retains STRT yaw and suppresses intro; fresh TSK loading separate; original fades unverified | | Supplied scene availability |All35 GAMs supplied;33 have OMT geometry |Level3B/E GAMs are duplicate four-entity records apart from level code; registered OMT archives absent, normal gameplay use unverified; no substitution or established blocker | | Lab task/contact route | Managed input replay + headless GPU pass |887 input-only movement steps with live contacts/NPC updates reachSCENE60, score150, jetpack andlevel1; separate direct-contact GPU rebuild check | | Lab underground passage |2763-step managed input replay pass |Both switches,2 clear crossings and timed reclosure; closed-gate negative sweep; explicit riverlab/SCENE65 fixture, prior progression and original comparison unverified | @@ -94,6 +96,14 @@ pass. See artifacts/live-debug-window.log and live-debug-return.log. No new Windows runtime claim is made. Both self-contained platform packages rebuild successfully with this addition. +Persistent presentation/widescreen checkpoint: full regression suite passes in +artifacts/persistent-widescreen-full-tests.log, including539 preserved hashes. +Native6-load/one-window/one-renderer fullscreen/bounds/focus/pointer checks pass +with zero enabled-layer errors (artifacts/window-transition-final.log). F1/force +and F2 input checks still pass. Both packages rebuild; packaged Linux1920x1080 +lab/VR04/lab retains one renderer and exact RETURN state with validation unavailable. +No new native Windows runtime claim is made. + Known visual/behavior limits include incomplete lighting/fog/blend/culling/material mapping, inferred model/root pivot, provisional collision/cadence/animation timing, close-wall camera clipping near Jimmy, incomplete class-specific triggers/interactions, diff --git a/docs/debug-menu.md b/docs/debug-menu.md index 5958591..5959d70 100644 --- a/docs/debug-menu.md +++ b/docs/debug-menu.md @@ -106,3 +106,7 @@ Native Linux GTX1070 window test passes with zero Vulkan validation errors: artifacts/debug-window.log. GPU screenshots debug-menu.png and debug-window.open.ppm show the menu. Source/build/regression evidence does not constitute new native Windows verification. Full regression and package status is in progress.md. + +Debug text scales uniformly with resolution. F1 uses a centered authored canvas +on widescreen; F2 stays top-left. The window/device survive level changes. See +presentation-and-ui.md for lifecycle, ultrawide and high-DPI pointer checks. diff --git a/docs/decisions.md b/docs/decisions.md index b67c56c..325d8c9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -92,3 +92,11 @@ across scene rebuilds in memory, independently of TSK state. Reuse the existing font/buffers, give F1 display priority and measure wall-frame intervals separately from simulation ticks. Report the rendered camera/projection, not a guessed mode. +21. **Own presentation at application lifetime.** Replace scene GPU resources + transactionally, retaining the SDL window, Vulkan core and user window state. + Size changes may recreate targets/swapchain. Per-level audio/gameplay remain + separate; source fades are still open. +22. **Uniform UI with anchors.** Preserve4:3 source positions, center modal/F1 + canvases and anchor objectives bottom/right and F2 top-left. Map logical input + through actual drawable dimensions with double precision for strict bounds. + This is authorized modern widescreen policy, not original algorithm recovery. diff --git a/docs/infrastructure.md b/docs/infrastructure.md index 5beb0ba..989618e 100644 --- a/docs/infrastructure.md +++ b/docs/infrastructure.md @@ -1,5 +1,11 @@ # Native infrastructure and package scope +Presentation now survives level loads: one SDL window/device with scene-resource +replacement. Uniform widescreen UI and input mapping are documented in +presentation-and-ui.md. The optional scripts/test-window-transitions.sh uses +installed Xvfb/Xfwm/D-Bus for isolated Linux fullscreen checks; these are not game +dependencies. --width/--height choose initial window/offscreen dimensions. + Verified environment: Ubuntu 24.04 x86-64; project-local .NET SDK 10.0.402, Silk.NET 2.23.0, SDL 3.4.2 built from official source (Linux) and official x64 SDL3.dll (Windows). GLSL compiled to Vulkan 1.3 SPIR-V and checked by spirv-val. diff --git a/docs/presentation-and-ui.md b/docs/presentation-and-ui.md new file mode 100644 index 0000000..b4921af --- /dev/null +++ b/docs/presentation-and-ui.md @@ -0,0 +1,80 @@ +# Persistent presentation and widescreen UI + +User-requested modern presentation/layout, 2026-10-25. Original assets and hashes +remain unchanged. These policies are separate from original fade/progression recovery. + +## Presentation lifetime + +Program.Main owns RenderSession until application exit. Each Run replaces level, +controller and audio state; SDL window/title changes do not recreate the window. +Position, logical/drawable dimensions, focus and fullscreen state survive loading. + +VulkanRenderer.ReplaceScene validates bounds and stages vertex/index buffers, +textures, sampler and descriptor pool/sets after DeviceWaitIdle. Instance, device, +surface, swapchain, targets, pipelines and layouts stay alive. Resize/fullscreen +changes still replace size-dependent swapchain/targets. SceneRevision increments +on success and RendererIdentity exposes core handles for verification. + +Old scene resources remain available until staging succeeds. Failure cleans partial +new resources and restores the prior set. Invalid indices/RGBA are runtime-tested +to preserve revision, identities and rendering; allocation-failure rollback is +implemented without fault injection. Loading remains synchronous; source fades +and loading presentation remain unfinished. + +## Uniform layout and pointer mapping + +UiViewport uses scale=min(drawableWidth/640,drawableHeight/480). Logical dimensions +are drawable dimensions divided by that common scale. Art/glyph X/Y proportions +match while the3D scene fills the viewport. + +| UI | Anchor | +| --- | --- | +| Objective pad/text/digit | Bottom-right delta from authored640x480 | +| Practice prompt/F1 menu | Centered authored canvas | +| F2 live panel | Top-left safe inset | + +Original4:3 positions, objective edge clipping and strict practice hit regions +remain. Widescreen anchors are an explicit port policy. --width/--height choose +initial window/offscreen dimensions64..8192; subsequent loads retain actual size. + +Mouse coordinates map from SDL logical dimensions into actual drawable pixels +before inverse modal mapping. Double precision avoids ultrawide cancellation that +turned boundary225 into225.00003. Fractional DPI with independently rounded pixel +dimensions uses the same mapping. + +## Verification + +UiViewport/Hud/DebugOverlay tests cover nine aspect/resolution fixtures,4:3 +equivalence,16:9/21:9/32:9, square/portrait,1.5x/2x DPI and fractional rounded +drawable dimensions. They verify glyph/art proportions, anchors, centered layouts +and strict Yes/No boundaries. The full suite passes in +artifacts/persistent-widescreen-full-tests.log, including539 unchanged originals. + +Actual headless lab/VR04/lab Run transitions retain one renderer with revisions +1/2/3 at1280x720, exact RETURN root/companion and zero Vulkan errors +(artifacts/persistent-practice-return.log). + +Native GTX1070: six loads, one window/renderer at960x720,1280x720,1680x720, +2560x720 and fullscreen3440x1440. Checks assert unchanged window ID/bounds/focus, +renderer identities across loading, fullscreen retention/restored windowed bounds, +native practice pointer mapping, rejected-load retention and zero cumulative +validation errors. Captures were visually inspected. Evidence: +artifacts/window-transition-final.log and window-transitions/*.png. Existing F1/ +force-control and F2 input checks also pass from widescreen startup sizes. + +``` +source scripts/env.sh +dotnet build +scripts/test-window-transitions.sh +``` + +The runner uses installed Xvfb/Xfwm with private X11/D-Bus and artifact-backed +configuration. Bare Xvfb lacks a window manager to honor fullscreen requests. +NEUTRON_WINDOW_TEST=1 scripts/test.sh can use an existing managed display. These +are test dependencies; the game adds none. Linux runtime/cross-publishing does +not establish new native Windows or original visual/gameplay equivalence. + +Both platform self-contained builds pass. The packaged Linux executable also +passes1920x1080 lab/VR04/lab with one renderer and exact RETURN root/companion +(artifacts/package-persistent-return.log; validation layers unavailable for this +standalone invocation). Native source/fullscreen checks above enable validation. diff --git a/docs/progress.md b/docs/progress.md index 45057b6..7761c55 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -4,6 +4,28 @@ user-verified Windows rendering checkpoint into an interactive original lab and jet pack tutorial flow. This is not a verified faithful complete scene or release. +## Persistent window/renderer and widescreen UI + +Main now owns one RenderSession. Per-level Run replaces scene resources while +retaining the SDL window and Vulkan core; resize/fullscreen replace size-dependent +targets. Window bounds, focus and fullscreen survive loading. Invalid replacement +validation retains rendering. Per-level audio/gameplay still rebuild; fades remain +unfinished. UiViewport scales art/glyphs uniformly with bottom/right HUD anchors, +centered prompts/F1 and top-left F2. Pointer mapping handles logical/drawable size, +fractional DPI rounding and strict source boundaries. + +Nine aspect/resolution fixtures and high-DPI checks pass. Full suite passes with +539 unchanged originals; final targeted viewport checks pass. Native GTX1070: +six loads, one window/renderer, stable native/core IDs and bounds/focus/fullscreen, +restored windowed bounds,4:3 through32:9/fullscreen3440x1440, native Yes/No mapping, +rejected-load retention and zero validation errors (artifacts/window-transition-final.log). +Captures were visually inspected. F1/force and F2 input checks still pass. Actual +headless lab/VR04/lab retains one renderer/revisions1/2/3 and exact RETURN root/ +companion at1280x720. Both self-contained packages are rebuilt. The packaged Linux +1920x1080 lab/VR04/lab check also retains one renderer and exact RETURN state +(validation unavailable in that standalone invocation). No new Windows runtime +check is claimed. Details: presentation-and-ui.md. + ## User-requested live debug overlay F2 toggles a compact, non-pausing live diagnostics panel. F1 also offers Live diff --git a/docs/tasks.md b/docs/tasks.md index 865f50b..e0f7a14 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -35,6 +35,10 @@ compile, runtime and original-fidelity verification are separate. restores authored ownership when disabled, clears on reset/new scene. - [x] F2 live diagnostics plus F1 visibility toggle; non-pausing compact overlay, measured frame timing and session-owned visibility across scene rebuilds. +- [x] Application-owned window/Vulkan renderer across loads; bounded scene + replacement and native fullscreen/bounds/focus retention checks. +- [x] Uniform widescreen game/debug UI with anchors and matched native pointer + mapping, strict boundaries and high-DPI rounding checks. ## Immediate continuation diff --git a/scripts/package.sh b/scripts/package.sh index ba9727b..7223af7 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -51,6 +51,8 @@ The menu pauses gameplay/audio and provides diagnostics, camera/cutscene control energy/jetpack/task changes, level/start selection, reset and Force Control toggle. F2 toggles compact live diagnostics without pausing; --debug-overlay enables it at startup. F1's Live Overlay toggle controls the same session preference. +Level changes retain the window, fullscreen and size. HUD/debug UI scales uniformly +on widescreen; --width 1920 --height 1080 sets initial window/offscreen dimensions. C pauses into inspection and resumes the chase camera. F11 fullscreen, Escape quit. Inspection: arrows/WASD orbit, +/- zoom, 1 idle, 2 run, 3 jump, 4 scratch preview. Append --inspect to start directly in the old scene inspector. diff --git a/scripts/test-window-transitions.sh b/scripts/test-window-transitions.sh new file mode 100755 index 0000000..d6a4f67 --- /dev/null +++ b/scripts/test-window-transitions.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Build first with dotnet build, then run this local Linux fullscreen/scene check. +# Requires the installed Xfwm window manager; never downloads dependencies. +set -euo pipefail +source "$(dirname "$0")/env.sh" + +for task_tool in xfwm4 xprop dbus-run-session xvfb-run dotnet; do + if ! command -v "$task_tool" >/dev/null 2>&1; then + printf 'Missing window-test dependency: %s\n' "$task_tool" >&2 + exit 1 + fi +done + +umask 077 +mkdir -p artifacts/window-test-environment +NEUTRON_WINDOW_TEST_DIR="$(mktemp -d "$NEUTRON_ROOT/artifacts/window-test-environment/run.XXXXXX")" +export NEUTRON_WINDOW_TEST_DIR +export XDG_CONFIG_HOME="$NEUTRON_WINDOW_TEST_DIR/config" +export XDG_CACHE_HOME="$NEUTRON_WINDOW_TEST_DIR/cache" +export XDG_DATA_HOME="$NEUTRON_WINDOW_TEST_DIR/data" +export XDG_STATE_HOME="$NEUTRON_WINDOW_TEST_DIR/state" +export XDG_RUNTIME_DIR="$NEUTRON_WINDOW_TEST_DIR/runtime" +mkdir -p "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME" "$XDG_DATA_HOME" "$XDG_STATE_HOME" "$XDG_RUNTIME_DIR" +export NO_AT_BRIDGE=1 GIO_USE_VFS=local +export GDK_BACKEND=x11 SDL_VIDEODRIVER=x11 +unset SESSION_MANAGER +export SDL_AUDIODRIVER="${SDL_AUDIODRIVER:-dummy}" + +# A bare Xvfb server cannot honor asynchronous EWMH fullscreen requests. Give +# this private display its own window manager and session bus. XDG paths keep +# all generated preferences/cache under artifacts without changing HOME. +exec xvfb-run -a -s '-screen 0 3440x1440x24' dbus-run-session -- bash -s -- "$@" <<'WINDOW_TEST' +set -euo pipefail +task_wm_log="$NEUTRON_WINDOW_TEST_DIR/xfwm4.log" +xfwm4 --compositor=off > "$task_wm_log" 2>&1 & +task_wm_pid=$! +cleanup() { + kill "$task_wm_pid" 2>/dev/null || true + wait "$task_wm_pid" 2>/dev/null || true +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +task_wm_ready=false +for ((task_try = 0; task_try < 50; task_try++)); do + if ! kill -0 "$task_wm_pid" 2>/dev/null; then + printf 'Window manager exited; see %s\n' "$task_wm_log" >&2 + exit 1 + fi + if [[ "$(xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null)" == *"window id"* ]]; then + task_wm_ready=true + break + fi + sleep 0.1 +done +if [[ "$task_wm_ready" != true ]]; then + printf 'Window manager did not become ready; see %s\n' "$task_wm_log" >&2 + exit 1 +fi + +dotnet run --no-build -- --smoke-window-transitions "$@" +WINDOW_TEST diff --git a/scripts/test.sh b/scripts/test.sh index f131344..ebc27a1 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -13,6 +13,7 @@ dotnet run --project tests/GamePort.InteractionTests -- ../Original dotnet run --project tests/GamePort.CheckpointTests -- ../Original dotnet run --project tests/GamePort.DebugMenuTests -- ../Original dotnet run --project tests/GamePort.DebugOverlayTests +dotnet run --project tests/GamePort.UiViewportTests dotnet run --project tests/GamePort.DebugDiagnosticsTests SDL_AUDIODRIVER=dummy dotnet run --project tests/GamePort.AudioPauseTests dotnet run --project tests/GamePort.LabRouteTests -- ../Original @@ -56,6 +57,7 @@ SDL_AUDIODRIVER=dummy dotnet run --no-build -- --scene-audio-smoke artifacts/ext SDL_AUDIODRIVER=dummy dotnet run --no-build -- --cutscene-audio-smoke artifacts/extracted/level1b/entities/entities.json python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then + dotnet run --no-build -- --smoke-window-transitions dotnet run --no-build -- --smoke-debug-overlay --screenshot artifacts/test-live-debug-window.ppm dotnet run --no-build -- --smoke-debug-menu --screenshot artifacts/test-debug-window.ppm dotnet run --no-build -- --smoke-objective-window --screenshot artifacts/test-objective-window.ppm diff --git a/src/GamePort/Application/DebugMenuOverlay.cs b/src/GamePort/Application/DebugMenuOverlay.cs index 432449c..2ecb26d 100644 --- a/src/GamePort/Application/DebugMenuOverlay.cs +++ b/src/GamePort/Application/DebugMenuOverlay.cs @@ -65,7 +65,8 @@ public sealed class DebugMenuOverlay /// Layout uses the same640x480 reference viewport as the original HUD. /// Compact mode uses a corner panel with58 columns and smaller live text. /// - public void Update(Mesh destination, IReadOnlyList lines, int selectedLine = -1, bool compact = false) + public void Update(Mesh destination, IReadOnlyList lines, int selectedLine = -1, bool compact = false, + uint viewportWidth = 640, uint viewportHeight = 480) { ArgumentNullException.ThrowIfNull(destination); ArgumentNullException.ThrowIfNull(lines); @@ -73,6 +74,8 @@ public sealed class DebugMenuOverlay if (selectedLine < -1 || selectedLine >= lines.Count) throw new ArgumentOutOfRangeException(nameof(selectedLine)); if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length) throw new ArgumentException("Destination omits debug overlay ranges", nameof(destination)); + var viewport = new UiViewport(viewportWidth, viewportHeight); + var anchor = compact ? Vector2.Zero : viewport.CenterOffset; var background = FindDraw(firstIndex, 6); var highlight = FindDraw(firstIndex + 6, 6); background.Visible = lines.Count > 0; @@ -120,9 +123,9 @@ public sealed class DebugMenuOverlay destination.Vertices[start + 2] = new(Position(x + width, y + height), maxUv, color); destination.Vertices[start + 3] = new(Position(x, y + height), new(minUv.X, maxUv.Y), color); } - } - private static Vector3 Position(float x, float y) => new(2 * x / 640 - 1, 2 * y / 480 - 1, 0); + Vector3 Position(float x, float y) => viewport.ToNdc(new Vector2(x, y) + anchor); + } private static PngImage CreateFont() { diff --git a/src/GamePort/Application/RenderSession.cs b/src/GamePort/Application/RenderSession.cs new file mode 100644 index 0000000..cb3790a --- /dev/null +++ b/src/GamePort/Application/RenderSession.cs @@ -0,0 +1,58 @@ +using GamePort.Assets; +using GamePort.Platform; +using GamePort.Rendering.Vulkan; + +namespace GamePort.Application; + +/// Application-owned presentation; level loads replace only scene resources. +public sealed class RenderSession : IDisposable +{ + private VulkanRenderer? renderer; + private bool videoInitialized; + public nint Window { get; private set; } + public int WindowCreationCount { get; private set; } + public int RendererCreationCount { get; private set; } + public bool Fullscreen => Window != 0 && (Sdl.SDL_GetWindowFlags(Window) & 1) != 0; + public bool HasInputFocus => Window == 0 || (Sdl.SDL_GetWindowFlags(Window) & 0x200) != 0; + + public VulkanRenderer LoadScene(Mesh mesh, PngImage fallback, bool headless, string title, + uint width, uint height, bool validation) + { + if (renderer != null) + { + if (headless != (Window == 0)) throw new InvalidOperationException("Cannot change presentation mode during a session"); + if (Window != 0 && !Sdl.SDL_SetWindowTitle(Window, title)) throw new InvalidOperationException(Sdl.Error); + renderer.ReplaceScene(mesh, fallback); + return renderer; + } + if (!headless) + { + if (!Sdl.SDL_Init(Sdl.InitVideo)) throw new InvalidOperationException(Sdl.Error); + videoInitialized = true; + Window = Sdl.SDL_CreateWindow(title, checked((int)width), checked((int)height), + Sdl.WindowVulkan | Sdl.WindowResizable | Sdl.WindowHighPixelDensity); + if (Window == 0) throw new InvalidOperationException(Sdl.Error); + WindowCreationCount++; + } + renderer = new(mesh, fallback, width, height, Window, validation); + RendererCreationCount++; + return renderer; + } + + public void ToggleFullscreen() + { + if (Window != 0 && !Sdl.SDL_SetWindowFullscreen(Window, !Fullscreen)) throw new InvalidOperationException(Sdl.Error); + } + + public void Dispose() + { + var current = renderer; + renderer = null; + try { current?.Dispose(); } + finally + { + if (Window != 0) { Sdl.SDL_DestroyWindow(Window); Window = 0; } + if (videoInitialized) { Sdl.SDL_Quit(); videoInitialized = false; } + } + } +} diff --git a/src/GamePort/Application/SceneHud.cs b/src/GamePort/Application/SceneHud.cs index 804ff7e..3394f07 100644 --- a/src/GamePort/Application/SceneHud.cs +++ b/src/GamePort/Application/SceneHud.cs @@ -72,12 +72,14 @@ public sealed class SceneHud /// Writes the final merged buffer, including when later visual composers copied these vertices. public void Update(Mesh destination, int currentObjective, bool objectivesVisible, bool practiceVisible, - float objectiveYOffset = -69, bool objectiveContentVisible = true) + float objectiveYOffset = -69, bool objectiveContentVisible = true, + uint viewportWidth = 640, uint viewportHeight = 480) { if (!float.IsFinite(objectiveYOffset) || objectiveYOffset < -480 || objectiveYOffset > 480) throw new ArgumentOutOfRangeException(nameof(objectiveYOffset)); if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length) throw new ArgumentException("Destination omits HUD ranges", nameof(destination)); + var viewport = new UiViewport(viewportWidth, viewportHeight); foreach (var quad in quads) { var draw = destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex && d.ScreenSpace @@ -88,7 +90,8 @@ public sealed class SceneHud var digit = quad.Canvas is >= 83 and <= 85; var x = quad.Canvas == 169 ? 210f : digit ? 393f : 384f; var y = quad.Canvas == 169 ? 210f : (quad.Canvas == 156 ? 380f : digit ? 450f : 448f) + objectiveYOffset; - Vector3 Position(float px, float py) => new(2 * px / 640 - 1, 2 * py / 480 - 1, 0); + var anchor = quad.Canvas == 169 ? viewport.CenterOffset : viewport.BottomRightOffset; + Vector3 Position(float px, float py) => viewport.ToNdc(new Vector2(px, py) + anchor); destination.Vertices[quad.VertexOffset].Position = Position(x, y); destination.Vertices[quad.VertexOffset + 1].Position = Position(x + quad.Width, y); destination.Vertices[quad.VertexOffset + 2].Position = Position(x + quad.Width, y + quad.Height); diff --git a/src/GamePort/Application/UiViewport.cs b/src/GamePort/Application/UiViewport.cs new file mode 100644 index 0000000..677432d --- /dev/null +++ b/src/GamePort/Application/UiViewport.cs @@ -0,0 +1,67 @@ +using System.Numerics; + +namespace GamePort.Application; + +/// +/// Modern viewport policy for original640x480 UI: uniform art/text scale with +/// explicit anchors. The3D scene still occupies the entire physical viewport. +/// +public readonly struct UiViewport +{ + private readonly double pixelScale, modalPixelX, modalPixelY; + private readonly uint pixelWidth, pixelHeight; + public float Scale { get; } + public float LogicalWidth { get; } + public float LogicalHeight { get; } + public Vector2 CenterOffset => new((LogicalWidth - 640) / 2, (LogicalHeight - 480) / 2); + public Vector2 BottomRightOffset => new(LogicalWidth - 640, LogicalHeight - 480); + + public UiViewport(uint width, uint height) + { + if (width == 0 || height == 0) throw new ArgumentOutOfRangeException(nameof(width), "UI viewport must be nonzero"); + pixelWidth = width; pixelHeight = height; + pixelScale = Math.Min(width / 640d, height / 480d); + Scale = (float)pixelScale; + LogicalWidth = (float)(width / pixelScale); + LogicalHeight = (float)(height / pixelScale); + modalPixelX = (width - 640 * pixelScale) / 2; + modalPixelY = (height - 480 * pixelScale) / 2; + } + + /// Map anchored logical coordinates into Vulkan overlay NDC, Y down. + public Vector3 ToNdc(Vector2 logicalPoint) + { + Validate(logicalPoint); + return new(2 * logicalPoint.X / LogicalWidth - 1, 2 * logicalPoint.Y / LogicalHeight - 1, 0); + } + + /// + /// Inverse of centered modal placement. Use SDL logical window dimensions + /// with SDL logical pointer pixels; render using drawable pixel dimensions. + /// Coordinates remain unclamped to preserve strict original Yes/No bounds. + /// + public Vector2 InverseModal(Vector2 windowPixels) + { + Validate(windowPixels); + // Subtract the physical center before dividing, using double precision. + // Float logical-space cancellation can turn an exact source boundary225 + // into225.00003 on ultrawide and incorrectly enter a strict hit region. + return new((float)((windowPixels.X - modalPixelX) / pixelScale), + (float)((windowPixels.Y - modalPixelY) / pixelScale)); + } + + /// Map SDL logical mouse coordinates to the actual drawable before + /// hit testing; this also handles fractional DPI sizes rounded by the OS. + public Vector2 InverseModal(Vector2 windowPoint, uint windowWidth, uint windowHeight) + { + Validate(windowPoint); + if (windowWidth == 0 || windowHeight == 0) throw new ArgumentOutOfRangeException(nameof(windowWidth)); + return new((float)(((double)windowPoint.X * pixelWidth / windowWidth - modalPixelX) / pixelScale), + (float)(((double)windowPoint.Y * pixelHeight / windowHeight - modalPixelY) / pixelScale)); + } + + private static void Validate(Vector2 point) + { + if (!float.IsFinite(point.X) || !float.IsFinite(point.Y)) throw new ArgumentOutOfRangeException(nameof(point)); + } +} diff --git a/src/GamePort/Application/WindowTransitionSmoke.cs b/src/GamePort/Application/WindowTransitionSmoke.cs new file mode 100644 index 0000000..8b7987e --- /dev/null +++ b/src/GamePort/Application/WindowTransitionSmoke.cs @@ -0,0 +1,170 @@ +using System.Numerics; +using GamePort.Assets; +using GamePort.Game; +using GamePort.Platform; +using GamePort.Rendering.Vulkan; + +namespace GamePort.Application; + +/// Local native presentation/scene-resource regression, not a gameplay replay. +public static class WindowTransitionSmoke +{ + private readonly record struct WindowState(uint Id, int X, int Y, int Width, int Height, bool Fullscreen, bool Focused); + + public static int Run(RenderSession session, string assets, string prepared, string output, bool validation) + { + Directory.CreateDirectory(output); + VulkanRenderer? renderer = null; + Mesh? mesh = null; + SceneHud? hud = null; + DebugMenuOverlay? overlay = null; + GamLevel? level = null; + var sceneNumber = 0; + var menu = new DebugMenu([], null, null); + menu.Toggle(30); + var diagnostics = new DebugDiagnostics { Enabled = true }; + var viewportCases = new (uint Width, uint Height, string Scene, string Ui)[] + { + (960, 720, "level1b", "menu"), + (1280, 720, "VR04", "practice"), + (1680, 720, "level1b", "objectives"), + (2560, 720, "level1", "live") + }; + foreach (var test in viewportCases) + { + if (renderer != null) Resize(test.Width, test.Height); + Replace(test.Scene, test.Width, test.Height); + Render(test.Ui, $"{sceneNumber}-{test.Scene}-{test.Width}x{test.Height}"); + if (test.Ui == "practice") CheckPracticePointer(); + } + + var windowed = State(); + session.ToggleFullscreen(); + Require(Sdl.SDL_SyncWindow(session.Window), Sdl.Error); + DrainAndResize(); + Require(session.Fullscreen, "SDL did not enter fullscreen"); + Replace("VR04", renderer!.Width, renderer.Height); + Render("practice", "fullscreen-practice"); + CheckPracticePointer(); + Replace("level1b", renderer.Width, renderer.Height); + Render("menu", "fullscreen-menu"); + session.ToggleFullscreen(); + Require(Sdl.SDL_SyncWindow(session.Window), Sdl.Error); + DrainAndResize(); + var restored = State(); + Require(!restored.Fullscreen && restored.Width == windowed.Width && restored.Height == windowed.Height + && restored.X == windowed.X && restored.Y == windowed.Y, "Windowed bounds did not survive fullscreen and scene replacement"); + + var revision = renderer.SceneRevision; + var identity = renderer.Identity; + Reject(() => renderer.ReplaceScene(new Mesh([new(Vector3.Zero, Vector2.Zero, Vector3.One)], [0, 1, 2]), PngImage.White)); + Reject(() => renderer.ReplaceScene(mesh!, new PngImage(2, 2, [255]))); + Require(renderer.SceneRevision == revision && renderer.Identity == identity, "Rejected replacement changed presentation state"); + Render("live", "after-rejected-replacement"); + Require(session.WindowCreationCount == 1 && session.RendererCreationCount == 1 && renderer.ValidationErrors == 0, + "Window/renderer were recreated or Vulkan validation failed"); + Console.WriteLine($"Window transition check: scenes={sceneNumber}, windows={session.WindowCreationCount}, renderers={session.RendererCreationCount}, fullscreen retained=True, bounds retained=True, invalid scene retained=True, Vulkan errors={renderer.ValidationErrors}."); + return 0; + + void Replace(string name, uint width, uint height) + { + level = GamLevel.Load(AssetPath.Resolve(assets, "gam/" + name + ".gam")); + var world = Mesh.LoadSceneJson(AssetPath.Resolve(prepared, name + "/scene.json")); + hud = new(world, Path.Combine(prepared, "ui/ui.json")); + overlay = new(hud.Mesh); + mesh = overlay.Mesh; + var before = renderer == null ? (WindowState?)null : State(); + var beforeIdentity = renderer?.Identity; + var beforeRenderer = renderer; + renderer = session.LoadScene(mesh, PngImage.White, false, "Neutron — persistent-window check", width, height, validation); + sceneNumber++; + if (before != null) + { + Require(ReferenceEquals(renderer, beforeRenderer) && renderer.Identity == beforeIdentity, + "Scene replacement recreated the device/surface/swapchain/pipelines"); + Require(State() == before.Value, "Scene replacement changed native window state"); + } + else + { + Require(Sdl.SDL_SetWindowPosition(session.Window, 37, 53) && Sdl.SDL_SyncWindow(session.Window), Sdl.Error); + DrainAndResize(); + } + Require(renderer.SceneRevision == sceneNumber, "Wrong scene revision after resource replacement"); + Console.WriteLine($"PASS retained presentation for{name}: revision={renderer.SceneRevision}, window={Sdl.SDL_GetWindowID(session.Window)}, size={renderer.Width}x{renderer.Height}, fullscreen={session.Fullscreen}."); + } + + void Resize(uint width, uint height) + { + Require(Sdl.SDL_SetWindowSize(session.Window, (int)width, (int)height) && Sdl.SDL_SyncWindow(session.Window), Sdl.Error); + DrainAndResize(); + Require(Sdl.SDL_GetWindowSize(session.Window, out var logicalWidth, out var logicalHeight), Sdl.Error); + Require(Sdl.SDL_GetWindowSizeInPixels(session.Window, out var pixelWidth, out var pixelHeight), Sdl.Error); + Require(logicalWidth == width && logicalHeight == height && renderer!.Width == pixelWidth && renderer.Height == pixelHeight, + "Window/drawable dimensions did not match resize"); + } + + void DrainAndResize() + { + while (Sdl.SDL_PollEvent(out var e)) + if (e.Type == Sdl.Quit) throw new InvalidOperationException("Window closed during transition check"); + if (!Sdl.SDL_GetWindowSizeInPixels(session.Window, out var width, out var height)) throw new InvalidOperationException(Sdl.Error); + if (renderer != null && (renderer.Width != width || renderer.Height != height)) renderer.Resize(); + } + + WindowState State() + { + if (!Sdl.SDL_GetWindowPosition(session.Window, out var x, out var y) + || !Sdl.SDL_GetWindowSize(session.Window, out var width, out var height)) + throw new InvalidOperationException(Sdl.Error); + return new(Sdl.SDL_GetWindowID(session.Window), x, y, width, height, session.Fullscreen, session.HasInputFocus); + } + + void Render(string mode, string filename) + { + var start = level!.FindStart() ?? level.Entities.First(e => e.Kind == "STRT"); + hud!.Update(mesh!, 1, mode == "objectives", mode == "practice", -69, true, renderer!.Width, renderer.Height); + var status = new DebugStatus(level.Code, start.Tag!, start.Position, start.Rotation.Y, 0, true, + 20, 0, 30, "NONE", true, 0, SceneProjection.FarPlane(level.Code), false); + var view = mode == "menu" ? menu.View(status) : new DebugMenuView([], -1); + var lines = mode == "live" ? diagnostics.Lines(status, + new(Vector3.Zero, 0, "IDLE", 0, 0, 0, 0, 0, -1, false, renderer.ValidationErrors, false)) : view.Lines; + overlay!.Update(mesh!, lines, view.SelectedLine, mode == "live", renderer.Width, renderer.Height); + var projection = SceneProjection.CreateGameplay(level.Code, (float)renderer.Width / renderer.Height); + projection.M22 *= -1; + var camera = Matrix4x4.CreateLookAtLeftHanded(start.CameraPosition, start.Position + new Vector3(0, 80, 0), Vector3.UnitY); + renderer.UpdateVertices(mesh!.Vertices); + renderer.Render(camera * projection); + renderer.SavePpm(Path.Combine(output, filename + ".ppm")); + Require(renderer.ValidationErrors == 0, "Vulkan error during scene/UI render"); + } + + void CheckPracticePointer() + { + Require(Sdl.SDL_GetWindowSize(session.Window, out var width, out var height), Sdl.Error); + var layout = new UiViewport(renderer!.Width, renderer.Height); + foreach (var yes in new[] { true, false }) + { + var authored = new Vector2(yes ? 265 : 355, 270); + var pixel = (authored + layout.CenterOffset) * layout.Scale; + Sdl.SDL_WarpMouseInWindow(session.Window, pixel.X * width / renderer.Width, pixel.Y * height / renderer.Height); + DrainAndResize(); // SDL mouse state reflects the most recent event pump. + Sdl.SDL_GetMouseState(out var x, out var y); + var prompt = new PracticePrompt(); + bool? accepted = null; + prompt.Chosen += (_, value) => accepted = value; + prompt.Show(0); prompt.Click(layout.InverseModal(new(x, y), (uint)width, (uint)height)); + Require(accepted == yes && !prompt.Active, + $"Scaled native pointer missed practice bounds: expected={yes}, target={pixel}, mouse=<{x},{y}>, authored={layout.InverseModal(new(x, y), (uint)width, (uint)height)}"); + } + Console.WriteLine($"PASS native scaled practice pointer at{width}x{height}."); + } + } + + private static void Require(bool condition, string message) + { if (!condition) throw new InvalidOperationException(message); } + private static void Reject(Action action) + { + try { action(); } catch (ArgumentException) { return; } + throw new InvalidOperationException("Expected bounded scene replacement rejection"); + } +} diff --git a/src/GamePort/Platform/Sdl.cs b/src/GamePort/Platform/Sdl.cs index 53b3c83..db4c192 100644 --- a/src/GamePort/Platform/Sdl.cs +++ b/src/GamePort/Platform/Sdl.cs @@ -38,6 +38,12 @@ internal static unsafe class Sdl public static string Error=>Marshal.PtrToStringUTF8(SDL_GetError())??"SDL error"; [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] public static extern nint SDL_CreateWindow([MarshalAs(UnmanagedType.LPUTF8Str)]string title,int w,int h,ulong flags); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_DestroyWindow(nint window); + [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern uint SDL_GetWindowID(nint window); + [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern ulong SDL_GetWindowFlags(nint window); + [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_GetWindowPosition(nint window,out int x,out int y); + [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowPosition(nint window,int x,int y); + [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SyncWindow(nint window); + [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_WarpMouseInWindow(nint window,float x,float y); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowTitle(nint window,[MarshalAs(UnmanagedType.LPUTF8Str)]string title); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PollEvent(out Event e); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern byte** SDL_Vulkan_GetInstanceExtensions(out uint count); diff --git a/src/GamePort/Program.cs b/src/GamePort/Program.cs index b1610b3..1bd4360 100644 --- a/src/GamePort/Program.cs +++ b/src/GamePort/Program.cs @@ -15,12 +15,13 @@ internal static class Program { try { + using var presentation = new RenderSession(); OriginalSave? carriedSave = null; var returning = false; var diagnostics = new DebugDiagnostics { Enabled = args.Contains("--debug-overlay") }; while (true) { - var result = Run(args, carriedSave, returning, diagnostics, out var continuation); + var result = Run(args, carriedSave, returning, diagnostics, presentation, out var continuation); if (result != 0 || continuation == null) return result; args = continuation.Args; carriedSave = continuation.Save; returning = continuation.Returning; } @@ -39,7 +40,8 @@ internal static class Program private sealed record SceneContinuation(string[] Args, OriginalSave Save, bool Returning); - private static int Run(string[] args, OriginalSave? carriedSave, bool returning, DebugDiagnostics diagnostics, out SceneContinuation? continuation) + private static int Run(string[] args, OriginalSave? carriedSave, bool returning, DebugDiagnostics diagnostics, + RenderSession presentation, out SceneContinuation? continuation) { continuation = null; if (args.Contains("--help")) @@ -68,6 +70,7 @@ internal static class Program --headless Render offscreen through Vulkan --screenshot PATH Save actual GPU readback as PPM --frames N Exit after N frames (headless default: 1) + --width N --height N Initial window/offscreen size (default960x720) --audio PATH Play recovered WAV; --loop-audio repeats it --audio-smoke PATH Verify audio-stream consumption --scene-audio-smoke PATH Verify music/speech streams from entities.json @@ -88,6 +91,7 @@ internal static class Program --debug-overlay Start with live F2 diagnostics visible --smoke-debug-menu SDL debug navigation/pause/actions/resize check --smoke-debug-overlay SDL live diagnostics/input/menu/resize check + --smoke-window-transitions Persistent window/renderer and widescreen UI check --verify-assets Decode all original PNG/ASE files --smoke-window Test keyboard event/resize (requires --frames 6 or more) --no-validation Disable development validation @@ -100,6 +104,19 @@ internal static class Program return 0; } var root = AssetPath.FindOriginal(Option(args, "--assets")); + if (args.Contains("--smoke-window-transitions")) + { + var preparedCandidates = new List(); + if (Option(args, "--scene") is { } explicitScene) + preparedCandidates.Add(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(explicitScene)!, ".."))); + preparedCandidates.AddRange([Path.Combine(AppContext.BaseDirectory, "scenes"), "artifacts/extracted"]); + var prepared = preparedCandidates + .FirstOrDefault(p => File.Exists(Path.Combine(p, "ui/ui.json"))) + ?? throw new DirectoryNotFoundException("Prepare scene/UI assets before window transition check"); + var output = Option(args, "--screenshot") is { } capture + ? Path.Combine(Path.GetDirectoryName(Path.GetFullPath(capture))!, "window-transitions") : "artifacts/window-transitions"; + return WindowTransitionSmoke.Run(presentation, root, Path.GetFullPath(prepared), output, !args.Contains("--no-validation")); + } var saveOutput = Option(args, "--write-save"); if (saveOutput != null) { @@ -386,17 +403,15 @@ internal static class Program throw new ArgumentException("Invalid frame count; window smoke requires at least six frames."); if (practiceWindowSmoke && (headless || frames < 12 || level?.Code != "LV1B" || loadedSave != null)) throw new ArgumentException("Practice window smoke requires fresh LV1B and at least12 windowed frames."); - nint window = 0; - if (!headless) + var width = uint.Parse(Option(args, "--width") ?? "960"); + var height = uint.Parse(Option(args, "--height") ?? "720"); + if (width is < 64 or > 8192 || height is < 64 or > 8192) throw new ArgumentException("Viewport dimensions must be64..8192"); + var renderer = presentation.LoadScene(mesh, texture, headless, + walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", + width, height, !args.Contains("--no-validation")); + var window = presentation.Window; + Console.WriteLine($"Scene presentation: revision={renderer.SceneRevision}, windows={presentation.WindowCreationCount}, renderers={presentation.RendererCreationCount}, window ID={(window == 0 ? 0 : Sdl.SDL_GetWindowID(window))}, size={renderer.Width}x{renderer.Height}."); { - if (!Sdl.SDL_Init(Sdl.InitVideo)) throw new InvalidOperationException(Sdl.Error); - window = Sdl.SDL_CreateWindow(walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", 960, 720, - Sdl.WindowVulkan | Sdl.WindowResizable | Sdl.WindowHighPixelDensity); - if (window == 0) { Sdl.SDL_Quit(); throw new InvalidOperationException(Sdl.Error); } - } - try - { - using var renderer = new VulkanRenderer(mesh, texture, 960, 720, window, !args.Contains("--no-validation")); using var audio = Option(args, "--audio") is { } audioFile ? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null; using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null; @@ -492,14 +507,13 @@ internal static class Program var keys = new HashSet(); var debugCapturedKeys = new HashSet(); var running = true; - var fullscreen = false; var sawKey = false; var didResize = false; var clock = Stopwatch.StartNew(); var animationStarted = 0.0; var animationSwitched = false; var inspecting = !walking; - var active = true; + var active = presentation.HasInputFocus; var mouseJump = false; var stepClock = new FixedStepClock(); double poseTime = initialPoseTime; @@ -597,7 +611,7 @@ internal static class Program { Sdl.SDL_GetMouseState(out var x, out var y); if (!Sdl.SDL_GetWindowSize(window, out var w, out var h) || w < 1 || h < 1) return Vector2.Zero; - return new(x * 640 / w, y * 480 / h); + return new UiViewport(renderer.Width, renderer.Height).InverseModal(new(x, y), (uint)w, (uint)h); } while (running) { @@ -689,8 +703,7 @@ internal static class Program } if (e.Scancode == 68 && e.Repeat == 0) { - fullscreen = !fullscreen; - if (!Sdl.SDL_SetWindowFullscreen(window, fullscreen)) throw new InvalidOperationException(Sdl.Error); + presentation.ToggleFullscreen(); } } if (e.Type == Sdl.KeyUp) keys.Remove(e.Scancode); @@ -776,7 +789,7 @@ internal static class Program && director is { Controlled: true, InventoryEnabled: true }); objectivePanel?.Step(0, director?.ControlledTag != null, practice.Active); hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible, - practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible); + practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible, renderer.Width, renderer.Height); var gameplayProjection = originalCamera || simulation != null && !inspecting; var cameraMode = !inspecting && director?.CameraEye != null ? "CUTSCENE" : simulation != null && !inspecting ? "GAMEPLAY" : originalCamera ? "STRT" : "ORBIT"; @@ -795,7 +808,8 @@ internal static class Program renderer.ValidationErrors, debugMenu.Open || practice.Active || inspecting || !active)); var liveDebugVisible = !debugMenu.Open && liveDebugLines.Length > 0; debugOverlay.Update(mesh, debugMenu.Open ? debugView.Lines : liveDebugLines, - debugMenu.Open ? debugView.SelectedLine : -1, compact: !debugMenu.Open); + debugMenu.Open ? debugView.SelectedLine : -1, compact: !debugMenu.Open, + viewportWidth: renderer.Width, viewportHeight: renderer.Height); var projection = gameplayProjection ? SceneProjection.CreateGameplay(level?.Code, (float)renderer.Width / renderer.Height) : Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 3, (float)renderer.Width / renderer.Height, Math.Max(radius / 10000, 0.01f), radius * 20); @@ -1066,10 +1080,6 @@ internal static class Program } return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0; } - finally - { - if (window != 0) { Sdl.SDL_DestroyWindow(window); Sdl.SDL_Quit(); } - } } private const string WalkTitle = "Jimmy Neutron — lab checkpoint | Arrows move | Shift / Insert / right mouse jump | F1 menu | F2 overlay | R reset | C inspect"; diff --git a/src/GamePort/Rendering/Vulkan/VulkanRenderer.cs b/src/GamePort/Rendering/Vulkan/VulkanRenderer.cs index 0f200e9..2eb71d4 100644 --- a/src/GamePort/Rendering/Vulkan/VulkanRenderer.cs +++ b/src/GamePort/Rendering/Vulkan/VulkanRenderer.cs @@ -36,7 +36,7 @@ public sealed unsafe class VulkanRenderer : IDisposable private Sampler sampler; private readonly List textures=[]; private readonly Dictionary descriptors=[]; - private readonly Mesh mesh; + private Mesh mesh; private readonly nint window; private SurfaceKHR surface; private KhrSurface? surfaceApi; @@ -52,8 +52,14 @@ public sealed unsafe class VulkanRenderer : IDisposable public int ValidationErrors { get; private set; } public uint Width=>width; public uint Height=>height; + public int SceneRevision { get; private set; } + public RendererIdentity Identity => new(unchecked((ulong)instance.Handle), unchecked((ulong)device.Handle), + surface.Handle, swapchain.Handle, pipeline.Handle, pipelineLayout.Handle, descriptorLayout.Handle); private sealed record Texture(Image Image,DeviceMemory Memory,ImageView View); + private sealed record SceneResources(Mesh Mesh, Buffer VertexBuffer, DeviceMemory VertexMemory, + Buffer IndexBuffer, DeviceMemory IndexMemory, DescriptorPool DescriptorPool, Sampler Sampler, + Texture[] Textures, KeyValuePair[] Descriptors); private static void Check(Result result,string operation) {if(result!=Result.Success)throw new InvalidOperationException($"{operation}: {result}");} @@ -63,6 +69,7 @@ public sealed unsafe class VulkanRenderer : IDisposable debugCallback=OnValidation; try { + ValidateScene(mesh,texture); CreateInstance(validation); if(window!=0) { @@ -81,10 +88,97 @@ public sealed unsafe class VulkanRenderer : IDisposable CreatePipeline(); if(window!=0)CreateSwapchain(); CreateTarget(); + SceneRevision=1; } catch{Dispose();throw;} } + /// + /// Replace only scene buffers/textures/descriptors. The renderer, SDL surface, + /// pipelines, swapchain and current render target remain alive. Staging keeps + /// the previous scene usable if allocation/upload of the replacement fails. + /// + public void ReplaceScene(Mesh replacement,PngImage fallback) + { + ObjectDisposedException.ThrowIf(device.Handle==0,this); + ValidateScene(replacement,fallback); + Check(vk.DeviceWaitIdle(device),"ReplaceSceneWaitIdle"); + var previous=DetachScene(); + mesh=replacement; + try + { + UploadBuffers(); + CreateDescriptors(fallback); + } + catch + { + vk.DeviceWaitIdle(device); + DestroySceneResources(); + RestoreScene(previous); + throw; + } + DestroySceneResources(previous); + SceneRevision++; + } + + private static void ValidateScene(Mesh mesh,PngImage fallback) + { + ArgumentNullException.ThrowIfNull(mesh); + ArgumentNullException.ThrowIfNull(fallback); + if(mesh.Vertices.Length==0 || mesh.Indices.Length==0 || mesh.Indices.Length%3!=0 + || mesh.Indices.Any(i=>i>=mesh.Vertices.Length)) + throw new ArgumentException("Scene requires nonempty, bounded triangle geometry.",nameof(mesh)); + if(mesh.Draws.Any(d=>(ulong)d.FirstIndex+d.IndexCount>(ulong)mesh.Indices.Length)) + throw new ArgumentException("Scene draw exceeds index buffer.",nameof(mesh)); + ValidateTexture(fallback); + foreach(var image in mesh.Textures.Values)ValidateTexture(image); + + static void ValidateTexture(PngImage image) + { + ArgumentNullException.ThrowIfNull(image); + if(image.Width is 0 or >8192 || image.Height is 0 or >8192 + || (long)image.Width*image.Height*4!=image.Rgba.LongLength) + throw new ArgumentException("Scene texture has invalid dimensions or RGBA length.",nameof(image)); + } + } + + private SceneResources DetachScene() + { + var scene=new SceneResources(mesh,vertexBuffer,vertexMemory,indexBuffer,indexMemory, + descriptorPool,sampler,textures.ToArray(),descriptors.ToArray()); + vertexBuffer=default;vertexMemory=default;indexBuffer=default;indexMemory=default; + descriptorPool=default;sampler=default;textures.Clear();descriptors.Clear(); + return scene; + } + + private void RestoreScene(SceneResources scene) + { + mesh=scene.Mesh; + vertexBuffer=scene.VertexBuffer;vertexMemory=scene.VertexMemory; + indexBuffer=scene.IndexBuffer;indexMemory=scene.IndexMemory; + descriptorPool=scene.DescriptorPool;sampler=scene.Sampler; + textures.AddRange(scene.Textures); + foreach(var entry in scene.Descriptors)descriptors.Add(entry.Key,entry.Value); + } + + private void DestroySceneResources() => DestroySceneResources(DetachScene()); + + private void DestroySceneResources(SceneResources scene) + { + if(scene.DescriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,scene.DescriptorPool,null); + if(scene.Sampler.Handle!=0)vk.DestroySampler(device,scene.Sampler,null); + foreach(var texture in scene.Textures) + { + vk.DestroyImageView(device,texture.View,null); + vk.DestroyImage(device,texture.Image,null); + vk.FreeMemory(device,texture.Memory,null); + } + if(scene.VertexBuffer.Handle!=0)vk.DestroyBuffer(device,scene.VertexBuffer,null); + if(scene.VertexMemory.Handle!=0)vk.FreeMemory(device,scene.VertexMemory,null); + if(scene.IndexBuffer.Handle!=0)vk.DestroyBuffer(device,scene.IndexBuffer,null); + if(scene.IndexMemory.Handle!=0)vk.FreeMemory(device,scene.IndexMemory,null); + } + private uint OnValidation(DebugUtilsMessageSeverityFlagsEXT severity,DebugUtilsMessageTypeFlagsEXT type,DebugUtilsMessengerCallbackDataEXT* data,void* user) { if((severity&DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)!=0)ValidationErrors++; @@ -178,12 +272,23 @@ public sealed unsafe class VulkanRenderer : IDisposable } private void MakeBuffer(ulong size,BufferUsageFlags usage,MemoryPropertyFlags flags,out Buffer buffer,out DeviceMemory memory) { - var info=new BufferCreateInfo{SType=StructureType.BufferCreateInfo,Size=size,Usage=usage,SharingMode=SharingMode.Exclusive}; - Check(vk.CreateBuffer(device,&info,null,out buffer),"CreateBuffer"); - vk.GetBufferMemoryRequirements(device,buffer,out var requirements); - var allocation=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=requirements.Size,MemoryTypeIndex=MemoryType(requirements.MemoryTypeBits,flags)}; - Check(vk.AllocateMemory(device,&allocation,null,out memory),"AllocateBufferMemory"); - Check(vk.BindBufferMemory(device,buffer,memory,0),"BindBufferMemory"); + buffer=default;memory=default; + try + { + var info=new BufferCreateInfo{SType=StructureType.BufferCreateInfo,Size=size,Usage=usage,SharingMode=SharingMode.Exclusive}; + Check(vk.CreateBuffer(device,&info,null,out buffer),"CreateBuffer"); + vk.GetBufferMemoryRequirements(device,buffer,out var requirements); + var allocation=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=requirements.Size,MemoryTypeIndex=MemoryType(requirements.MemoryTypeBits,flags)}; + Check(vk.AllocateMemory(device,&allocation,null,out memory),"AllocateBufferMemory"); + Check(vk.BindBufferMemory(device,buffer,memory,0),"BindBufferMemory"); + } + catch + { + if(buffer.Handle!=0)vk.DestroyBuffer(device,buffer,null); + if(memory.Handle!=0)vk.FreeMemory(device,memory,null); + buffer=default;memory=default; + throw; + } } private void UploadBuffers() { @@ -203,17 +308,30 @@ public sealed unsafe class VulkanRenderer : IDisposable private void CopyToMemory(DeviceMemory memory,ReadOnlySpan bytes) { void* data;Check(vk.MapMemory(device,memory,0,(ulong)bytes.Length,0,&data),"MapMemory"); - bytes.CopyTo(new Span(data,bytes.Length));vk.UnmapMemory(device,memory); + try{bytes.CopyTo(new Span(data,bytes.Length));} + finally{vk.UnmapMemory(device,memory);} } private void MakeImage(uint w,uint h,Format format,ImageUsageFlags usage,ImageAspectFlags aspect,out Image image,out DeviceMemory memory,out ImageView view) { - var info=new ImageCreateInfo{SType=StructureType.ImageCreateInfo,ImageType=ImageType.Type2D,Format=format,Extent=new Extent3D(w,h,1),MipLevels=1,ArrayLayers=1,Samples=SampleCountFlags.Count1Bit,Tiling=ImageTiling.Optimal,Usage=usage,SharingMode=SharingMode.Exclusive,InitialLayout=ImageLayout.Undefined}; - Check(vk.CreateImage(device,&info,null,out image),"CreateImage"); - vk.GetImageMemoryRequirements(device,image,out var req); - var alloc=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=req.Size,MemoryTypeIndex=MemoryType(req.MemoryTypeBits,MemoryPropertyFlags.DeviceLocalBit)}; - Check(vk.AllocateMemory(device,&alloc,null,out memory),"AllocateImageMemory");Check(vk.BindImageMemory(device,image,memory,0),"BindImageMemory"); - var vi=new ImageViewCreateInfo{SType=StructureType.ImageViewCreateInfo,Image=image,ViewType=ImageViewType.Type2D,Format=format,SubresourceRange=new ImageSubresourceRange(aspect,0,1,0,1)}; - Check(vk.CreateImageView(device,&vi,null,out view),"CreateImageView"); + image=default;memory=default;view=default; + try + { + var info=new ImageCreateInfo{SType=StructureType.ImageCreateInfo,ImageType=ImageType.Type2D,Format=format,Extent=new Extent3D(w,h,1),MipLevels=1,ArrayLayers=1,Samples=SampleCountFlags.Count1Bit,Tiling=ImageTiling.Optimal,Usage=usage,SharingMode=SharingMode.Exclusive,InitialLayout=ImageLayout.Undefined}; + Check(vk.CreateImage(device,&info,null,out image),"CreateImage"); + vk.GetImageMemoryRequirements(device,image,out var req); + var alloc=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=req.Size,MemoryTypeIndex=MemoryType(req.MemoryTypeBits,MemoryPropertyFlags.DeviceLocalBit)}; + Check(vk.AllocateMemory(device,&alloc,null,out memory),"AllocateImageMemory");Check(vk.BindImageMemory(device,image,memory,0),"BindImageMemory"); + var vi=new ImageViewCreateInfo{SType=StructureType.ImageViewCreateInfo,Image=image,ViewType=ImageViewType.Type2D,Format=format,SubresourceRange=new ImageSubresourceRange(aspect,0,1,0,1)}; + Check(vk.CreateImageView(device,&vi,null,out view),"CreateImageView"); + } + catch + { + if(view.Handle!=0)vk.DestroyImageView(device,view,null); + if(image.Handle!=0)vk.DestroyImage(device,image,null); + if(memory.Handle!=0)vk.FreeMemory(device,memory,null); + image=default;memory=default;view=default; + throw; + } } private void Begin() { @@ -234,21 +352,39 @@ public sealed unsafe class VulkanRenderer : IDisposable } private Texture UploadTexture(PngImage image) { - MakeBuffer((ulong)image.Rgba.Length,BufferUsageFlags.TransferSrcBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out var staging,out var memory); - CopyToMemory(memory,image.Rgba); - MakeImage(image.Width,image.Height,Format.R8G8B8A8Unorm,ImageUsageFlags.TransferDstBit|ImageUsageFlags.SampledBit,ImageAspectFlags.ColorBit,out var texture,out var textureMemory,out var view); - Begin();Barrier(texture,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit); - var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(image.Width,image.Height,1)}; - vk.CmdCopyBufferToImage(command,staging,texture,ImageLayout.TransferDstOptimal,1,©); - Barrier(texture,ImageLayout.TransferDstOptimal,ImageLayout.ShaderReadOnlyOptimal,AccessFlags.TransferWriteBit,AccessFlags.ShaderReadBit,PipelineStageFlags.TransferBit,PipelineStageFlags.FragmentShaderBit);Submit(); - vk.DestroyBuffer(device,staging,null);vk.FreeMemory(device,memory,null); - var result=new Texture(texture,textureMemory,view);textures.Add(result);return result; + Buffer staging=default;DeviceMemory memory=default; + Image texture=default;DeviceMemory textureMemory=default;ImageView view=default; + try + { + MakeBuffer((ulong)image.Rgba.Length,BufferUsageFlags.TransferSrcBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out staging,out memory); + CopyToMemory(memory,image.Rgba); + MakeImage(image.Width,image.Height,Format.R8G8B8A8Unorm,ImageUsageFlags.TransferDstBit|ImageUsageFlags.SampledBit,ImageAspectFlags.ColorBit,out texture,out textureMemory,out view); + Begin();Barrier(texture,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit); + var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(image.Width,image.Height,1)}; + vk.CmdCopyBufferToImage(command,staging,texture,ImageLayout.TransferDstOptimal,1,©); + Barrier(texture,ImageLayout.TransferDstOptimal,ImageLayout.ShaderReadOnlyOptimal,AccessFlags.TransferWriteBit,AccessFlags.ShaderReadBit,PipelineStageFlags.TransferBit,PipelineStageFlags.FragmentShaderBit);Submit(); + var result=new Texture(texture,textureMemory,view); + textures.Add(result); + texture=default;textureMemory=default;view=default; + return result; + } + finally + { + if(staging.Handle!=0)vk.DestroyBuffer(device,staging,null); + if(memory.Handle!=0)vk.FreeMemory(device,memory,null); + if(view.Handle!=0)vk.DestroyImageView(device,view,null); + if(texture.Handle!=0)vk.DestroyImage(device,texture,null); + if(textureMemory.Handle!=0)vk.FreeMemory(device,textureMemory,null); + } } private void CreateDescriptors(PngImage fallback) { - var binding=new DescriptorSetLayoutBinding{Binding=0,DescriptorType=DescriptorType.CombinedImageSampler,DescriptorCount=1,StageFlags=ShaderStageFlags.FragmentBit}; - var layout=new DescriptorSetLayoutCreateInfo{SType=StructureType.DescriptorSetLayoutCreateInfo,BindingCount=1,PBindings=&binding}; - Check(vk.CreateDescriptorSetLayout(device,&layout,null,out descriptorLayout),"CreateDescriptorSetLayout"); + if(descriptorLayout.Handle==0) + { + var binding=new DescriptorSetLayoutBinding{Binding=0,DescriptorType=DescriptorType.CombinedImageSampler,DescriptorCount=1,StageFlags=ShaderStageFlags.FragmentBit}; + var layout=new DescriptorSetLayoutCreateInfo{SType=StructureType.DescriptorSetLayoutCreateInfo,BindingCount=1,PBindings=&binding}; + Check(vk.CreateDescriptorSetLayout(device,&layout,null,out descriptorLayout),"CreateDescriptorSetLayout"); + } var count=(uint)mesh.Textures.Count+1; var size=new DescriptorPoolSize(DescriptorType.CombinedImageSampler,count); var poolInfo=new DescriptorPoolCreateInfo{SType=StructureType.DescriptorPoolCreateInfo,MaxSets=count,PoolSizeCount=1,PPoolSizes=&size}; @@ -328,9 +464,17 @@ public sealed unsafe class VulkanRenderer : IDisposable } private void DestroyTarget() { - vk.DestroyFramebuffer(device,framebuffer,null);vk.DestroyImageView(device,colorView,null);vk.DestroyImageView(device,depthView,null); - vk.DestroyImage(device,color,null);vk.DestroyImage(device,depth,null);vk.FreeMemory(device,colorMemory,null);vk.FreeMemory(device,depthMemory,null); - vk.DestroyBuffer(device,readback,null);vk.FreeMemory(device,readbackMemory,null); + if(framebuffer.Handle!=0)vk.DestroyFramebuffer(device,framebuffer,null); + if(colorView.Handle!=0)vk.DestroyImageView(device,colorView,null); + if(depthView.Handle!=0)vk.DestroyImageView(device,depthView,null); + if(color.Handle!=0)vk.DestroyImage(device,color,null); + if(depth.Handle!=0)vk.DestroyImage(device,depth,null); + if(colorMemory.Handle!=0)vk.FreeMemory(device,colorMemory,null); + if(depthMemory.Handle!=0)vk.FreeMemory(device,depthMemory,null); + if(readback.Handle!=0)vk.DestroyBuffer(device,readback,null); + if(readbackMemory.Handle!=0)vk.FreeMemory(device,readbackMemory,null); + framebuffer=default;colorView=default;depthView=default;color=default;depth=default; + colorMemory=default;depthMemory=default;readback=default;readbackMemory=default; } private void CreateSwapchain() { @@ -352,7 +496,9 @@ public sealed unsafe class VulkanRenderer : IDisposable { if(window==0)return; Sdl.SDL_GetWindowSizeInPixels(window,out var w,out var h);if(w<1||h<1)return; - Check(vk.DeviceWaitIdle(device),"ResizeWaitIdle");DestroyTarget();swapApi!.DestroySwapchain(device,swapchain,null);CreateSwapchain();CreateTarget(); + Check(vk.DeviceWaitIdle(device),"ResizeWaitIdle");DestroyTarget(); + swapApi!.DestroySwapchain(device,swapchain,null);swapchain=default;swapImages=[]; + CreateSwapchain();CreateTarget(); } public void Render(Matrix4x4 mvp) { @@ -416,17 +562,13 @@ public sealed unsafe class VulkanRenderer : IDisposable if(device.Handle!=0) { vk.DeviceWaitIdle(device); - if(framebuffer.Handle!=0)DestroyTarget(); + DestroyTarget(); if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null); if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null); if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null); if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null); - if(descriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,descriptorPool,null); + DestroySceneResources(); if(descriptorLayout.Handle!=0)vk.DestroyDescriptorSetLayout(device,descriptorLayout,null); - if(sampler.Handle!=0)vk.DestroySampler(device,sampler,null); - foreach(var t in textures){vk.DestroyImageView(device,t.View,null);vk.DestroyImage(device,t.Image,null);vk.FreeMemory(device,t.Memory,null);} - if(vertexBuffer.Handle!=0)vk.DestroyBuffer(device,vertexBuffer,null);if(vertexMemory.Handle!=0)vk.FreeMemory(device,vertexMemory,null); - if(indexBuffer.Handle!=0)vk.DestroyBuffer(device,indexBuffer,null);if(indexMemory.Handle!=0)vk.FreeMemory(device,indexMemory,null); if(acquired.Handle!=0)vk.DestroySemaphore(device,acquired,null);if(finished.Handle!=0)vk.DestroySemaphore(device,finished,null); if(swapchain.Handle!=0)swapApi!.DestroySwapchain(device,swapchain,null); if(pool.Handle!=0)vk.DestroyCommandPool(device,pool,null); @@ -438,3 +580,8 @@ public sealed unsafe class VulkanRenderer : IDisposable vk.Dispose(); } } + +/// Presentation/device identities for transition verification; swapchain +/// identity may legitimately change on resize, unlike device and surface. +public readonly record struct RendererIdentity(ulong Instance,ulong Device,ulong Surface, + ulong Swapchain,ulong Pipeline,ulong PipelineLayout,ulong DescriptorLayout); diff --git a/tests/GamePort.DebugOverlayTests/GamePort.DebugOverlayTests.csproj b/tests/GamePort.DebugOverlayTests/GamePort.DebugOverlayTests.csproj index 513f179..17797f6 100644 --- a/tests/GamePort.DebugOverlayTests/GamePort.DebugOverlayTests.csproj +++ b/tests/GamePort.DebugOverlayTests/GamePort.DebugOverlayTests.csproj @@ -5,5 +5,6 @@ + diff --git a/tests/GamePort.DebugOverlayTests/Program.cs b/tests/GamePort.DebugOverlayTests/Program.cs index c60a64c..9c0cc7c 100644 --- a/tests/GamePort.DebugOverlayTests/Program.cs +++ b/tests/GamePort.DebugOverlayTests/Program.cs @@ -26,6 +26,28 @@ Check(final.Draws.Skip(1).Count(d => d.Visible) == 3, "Live panel has no selecte overlay.Update(final, ["Menu", "Resume", "Camera"], 1); Check(final.Vertices[2].Position.X == menuRight && final.Vertices[3].Position.Y == menuBottom, "Returning to menu restores its full layout using the same buffers"); +foreach (var (width, height) in new[] { (1920u, 1080u), (3440u, 1440u), (3840u, 1080u), (1080u, 1920u) }) +{ + Vector2 Pixel(int index) + { + var p = final.Vertices[index].Position; + return new((p.X + 1) * width / 2, (p.Y + 1) * height / 2); + } + var viewport = new UiViewport(width, height); + overlay.Update(final, ["Menu", "Resume", "Camera"], 1, viewportWidth: width, viewportHeight: height); + var backgroundLeft = Pixel(1).X; var backgroundRight = Pixel(2).X; + Check(MathF.Abs((backgroundLeft + backgroundRight) / 2 - width / 2f) < .003f, + "F1 panel centers in the wide physical viewport"); + var character = Pixel(9); + Check(MathF.Abs((Pixel(10).X - character.X) / 7 - (Pixel(12).Y - character.Y) / 9.8f) < .0001f, + "F1 glyphs retain equal X/Y scale"); + overlay.Update(final, ["F2 LIVE DEBUG", "ROOT X 10 Y 20 Z 30"], compact: true, viewportWidth: width, viewportHeight: height); + Check(Vector2.Distance(Pixel(1), new Vector2(8 * viewport.Scale)) < .003f, + "F2 remains at the uniform top-left safe inset"); + character = Pixel(9); + Check(MathF.Abs((Pixel(10).X - character.X) / 5.6f - (Pixel(12).Y - character.Y) / 7.84f) < .0001f, + "F2 glyphs are never stretched across widescreen"); +} overlay.Update(final, [new string('X', 100)], -1); Check(final.Draws.Skip(1).Count(d => d.Visible) == 2, "Long labels clip to bounded text range"); overlay.Update(final, []); diff --git a/tests/GamePort.HudTests/GamePort.HudTests.csproj b/tests/GamePort.HudTests/GamePort.HudTests.csproj index 06192a1..d112e45 100644 --- a/tests/GamePort.HudTests/GamePort.HudTests.csproj +++ b/tests/GamePort.HudTests/GamePort.HudTests.csproj @@ -5,6 +5,7 @@ + diff --git a/tests/GamePort.HudTests/Program.cs b/tests/GamePort.HudTests/Program.cs index dde679d..427b6fe 100644 --- a/tests/GamePort.HudTests/Program.cs +++ b/tests/GamePort.HudTests/Program.cs @@ -50,6 +50,27 @@ try Check(final.Draws.Skip(1).All(d => !d.Visible), "Timed-out objective has no remaining overlay draw"); panel.Key(true); panel.Step(1); PresentPanel(); Check(final.Draws.Skip(1).Count(d => d.Visible) == 3, "O reopens timed-out panel through the timer"); + foreach (var (width, height) in new[] { (1920u, 1080u), (3440u, 1440u), (3840u, 1080u), (1080u, 1920u) }) + { + hud.Update(final, 1, true, true, viewportWidth: width, viewportHeight: height); + var viewport = new UiViewport(width, height); + Vector2 Pixel(int index) + { + var p = final.Vertices[index].Position; + return new((p.X + 1) * width / 2, (p.Y + 1) * height / 2); + } + var pad = Pixel(1); var modal = Pixel(29); + Check(Vector2.Distance(pad, new(width - 256 * viewport.Scale, height - 169 * viewport.Scale)) < .003f, + "Objective pad remains bottom/right anchored"); + var modalExpected = (new Vector2(210, 210) + viewport.CenterOffset) * viewport.Scale; + Check(Vector2.Distance(modal, modalExpected) < .003f, "Modal shifts with centered authored canvas"); + Check(MathF.Abs((Pixel(30).X - modal.X) / 207 - (Pixel(32).Y - modal.Y) / 100) < .0001f, + "Original modal art has equal physical X/Y scale"); + Check(MathF.Abs((Pixel(2).X - pad.X) / 320 - (Pixel(4).Y - pad.Y) / 173) < .0001f, + "Objective pad is never stretched in widescreen"); + } + hud.Update(final, 2, true, true); + Near(final.Vertices[1].Position, new(.2f, 2*311f/480-1, 0), "Returning to4:3 restores source positions"); Reject(() => hud.Update(source, 1, true, false), "Missing final ranges"); Reject(() => hud.Update(final, 1, true, false, float.NaN), "Nonfinite HUD offset"); File.WriteAllText(path, Manifest(entries.Select(e => new { e.id, width=e.id==120 ? 0 : e.width, e.height, e.path }))); diff --git a/tests/GamePort.UiViewportTests/GamePort.UiViewportTests.csproj b/tests/GamePort.UiViewportTests/GamePort.UiViewportTests.csproj new file mode 100644 index 0000000..3bbffd1 --- /dev/null +++ b/tests/GamePort.UiViewportTests/GamePort.UiViewportTests.csproj @@ -0,0 +1,8 @@ + + Exenet10.0enableenablefalse + + + + + + diff --git a/tests/GamePort.UiViewportTests/Program.cs b/tests/GamePort.UiViewportTests/Program.cs new file mode 100644 index 0000000..7890b69 --- /dev/null +++ b/tests/GamePort.UiViewportTests/Program.cs @@ -0,0 +1,84 @@ +using System.Numerics; +using GamePort.Application; +using GamePort.Game; + +var sizes = new (uint Width, uint Height)[] { (640, 480), (960, 720), (1920, 1080), + (2560, 1080), (3440, 1440), (3840, 1080), (1080, 1920), (1920, 1920), (3840, 2160) }; +foreach (var (width, height) in sizes) +{ + var viewport = new UiViewport(width, height); + var a = Pixels(viewport.ToNdc(new(100, 100)), width, height); + var b = Pixels(viewport.ToNdc(new(200, 140)), width, height); + Near((b.X - a.X) / 100, viewport.Scale, "Horizontal art scale"); + Near((b.Y - a.Y) / 40, viewport.Scale, "Vertical art scale"); + NearVector(Pixels(viewport.ToNdc(new Vector2(320, 240) + viewport.CenterOffset), width, height), + new(width / 2f, height / 2f), "Centered authored canvas"); + NearVector(Pixels(viewport.ToNdc(new Vector2(640, 480) + viewport.BottomRightOffset), width, height), + new(width, height), "Bottom-right authored canvas"); + Near(Pixels(viewport.ToNdc(new Vector2(704, 480) + viewport.BottomRightOffset), width, height).X, + width + 64 * viewport.Scale, "Original HUD overscan remains clipped rather than squeezed"); + NearVector(Pixels(viewport.ToNdc(new(8, 8)), width, height), new(8 * viewport.Scale), "Corner safe inset scales uniformly"); + + var pointer = new Vector2(265, 270); + NearVector(viewport.InverseModal((pointer + viewport.CenterOffset) * viewport.Scale), pointer, + "Render/input mappings are inverses"); + foreach (var (point, choice) in new[] { (new Vector2(265, 270), true), (new Vector2(355, 270), false) }) + { + var prompt = new PracticePrompt(); + bool? selected = null; + prompt.Chosen += (_, yes) => selected = yes; + prompt.Show(0); + prompt.Click(viewport.InverseModal(Pixels(viewport.ToNdc(point + viewport.CenterOffset), width, height))); + Check(!prompt.Active && selected == choice, "Centered practice hit regions match visible art"); + } + foreach (var boundary in new[] { new Vector2(225, 270), new Vector2(305, 270), + new Vector2(265, 240), new Vector2(265, 300), new Vector2(315, 270), new Vector2(395, 270) }) + { + var prompt = new PracticePrompt(); + prompt.Show(0); + prompt.Click(viewport.InverseModal(Pixels(viewport.ToNdc(boundary + viewport.CenterOffset), width, height))); + Check(prompt.Active, $"Strict source boundary must remain unselected: {width}x{height} {boundary}"); + } +} +Console.WriteLine("PASS uniform4:3/widescreen/ultrawide/portrait scale, anchors and strict modal input regions"); + +foreach (var (width, height) in new[] { (800u, 600u), (1280u, 720u), (1720u, 720u) }) +{ + var logical = new UiViewport(width, height); + var authored = new Vector2(265, 270); + var pointer = (authored + logical.CenterOffset) * logical.Scale; + foreach (var (numerator, denominator) in new[] { (2u, 1u), (3u, 2u) }) + { + var pixelWidth = width * numerator / denominator; + var pixelHeight = height * numerator / denominator; + var drawable = new UiViewport(pixelWidth, pixelHeight); + var drawn = Pixels(drawable.ToNdc(authored + drawable.CenterOffset), pixelWidth, pixelHeight); + NearVector(pointer * numerator / denominator, drawn, "High-DPI drawable art corresponds to logical pointer pixels"); + NearVector(logical.InverseModal(pointer), authored, "High-DPI pointer returns original modal coordinates"); + } +} +var classic = new UiViewport(640, 480); +var fractional = new UiViewport(1922, 1082); +var authoredPoint = new Vector2(265, 270); +var drawnPoint = Pixels(fractional.ToNdc(authoredPoint + fractional.CenterOffset), 1922, 1082); +var logicalPoint = new Vector2(drawnPoint.X * 1281 / 1922, drawnPoint.Y * 721 / 1082); +NearVector(fractional.InverseModal(logicalPoint, 1281, 721), authoredPoint, + "Fractional DPI with independently rounded drawable dimensions maps to actual art"); +Reject(() => fractional.InverseModal(Vector2.Zero, 0, 721)); +var old = classic.ToNdc(new(384, 311)); +Check(Vector3.Distance(old, new(.2f, 2 * 311f / 480 - 1, 0)) < .00001f, "Original4:3 NDC is unchanged"); +Reject(() => new UiViewport(0, 480)); +Reject(() => new UiViewport(640, 0)); +Reject(() => classic.ToNdc(new(float.NaN, 0))); +Reject(() => classic.InverseModal(new(0, float.PositiveInfinity))); +Console.WriteLine("PASS high-DPI mapping, original4:3 compatibility and invalid viewport/input rejection"); + +static Vector2 Pixels(Vector3 ndc, uint width, uint height) => new((ndc.X + 1) * width / 2, (ndc.Y + 1) * height / 2); +static void Near(float actual, float expected, string message) => Check(MathF.Abs(actual - expected) < .002f, $"{message}: {actual} != {expected}"); +static void NearVector(Vector2 actual, Vector2 expected, string message) => Check(Vector2.Distance(actual, expected) < .003f, $"{message}: {actual} != {expected}"); +static void Check(bool value, string message) { if (!value) throw new InvalidOperationException(message); } +static void Reject(Action action) +{ + try { action(); } catch (ArgumentOutOfRangeException) { return; } + throw new InvalidOperationException("Expected invalid UI viewport/input rejection"); +}