From df67722b2d6f3e74bb7ee6b96c472832f7b6b2a9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 9 May 2026 03:05:23 +0100 Subject: [PATCH] Fix headless reload verification --- scripts/dev-reload.ps1 | 61 ++++++++++++++++++- src/Aquarium.Engine/AquariumHost.cs | 3 +- src/Aquarium.Engine/Platform/Win32Window.cs | 22 +++++-- src/Aquarium.Engine/Render/D3D11Renderer.cs | 45 +++++++++++--- .../Render/Shaders/Aquarium.hlsl | 2 +- state/evidence.jsonl | 1 + state/memory.json | 1 + state/scratch.md | 6 ++ 8 files changed, 125 insertions(+), 16 deletions(-) diff --git a/scripts/dev-reload.ps1 b/scripts/dev-reload.ps1 index aeda992..d1c115d 100644 --- a/scripts/dev-reload.ps1 +++ b/scripts/dev-reload.ps1 @@ -4,7 +4,8 @@ param( [switch]$BuildOnly, [switch]$Reopen, [int]$RetainSlots = 12, - [int]$StartupTimeoutSeconds = 5 + [int]$StartupTimeoutSeconds = 5, + [int]$HeadlessTimeoutSeconds = 15 ) $ErrorActionPreference = "Stop" @@ -38,6 +39,10 @@ function Stop-PreviousOwnedProcess { } $state = Import-Clixml -Path $statePath + if (-not ($state.PSObject.Properties.Name -contains "pid")) { + return + } + if (-not $state.pid) { return } @@ -133,6 +138,37 @@ function Wait-ForStartedAquarium { } } +function Wait-ForHeadlessAquarium { + param( + [System.Diagnostics.Process]$Process + ) + + $deadline = (Get-Date).AddSeconds([Math]::Max(1, $HeadlessTimeoutSeconds)) + while ((Get-Date) -lt $deadline) { + $Process.Refresh() + if ($Process.HasExited) { + $Process.WaitForExit() + $exitCode = [int]$Process.ExitCode + if ($exitCode -ne 0) { + throw "Headless Aquarium exited with code $exitCode.`n$(Get-StderrTail)" + } + + return + } + + Start-Sleep -Milliseconds 100 + } + + try { + Stop-Process -Id $Process.Id -Force -ErrorAction SilentlyContinue + } + catch { + # Best effort cleanup before surfacing the broken smoke test. + } + + throw "Headless Aquarium did not exit within $HeadlessTimeoutSeconds seconds; killed PID $($Process.Id).`n$(Get-StderrTail)" +} + function Start-AquariumProcess { param( [string]$SlotPath, @@ -273,7 +309,28 @@ if (-not (Test-Path $liveAssemblyPath)) { } $process = Start-AquariumProcess -SlotPath $slotPath -LiveAssemblyPath $liveAssemblyPath -RunHeadless:$Headless -Wait-ForStartedAquarium -Process $process -ExpectWindow:(-not $Headless) +if ($Headless) { + Wait-ForHeadlessAquarium -Process $process + + @{ + slot = $slotPath + builtAt = (Get-Date).ToString("o") + liveAssembly = $liveAssemblyPath + headless = $true + stdoutLog = $stdoutLogPath + stderrLog = $stderrLogPath + } | Export-Clixml -Path $statePath + + Write-Host "Headless Aquarium completed from disposable slot." + Write-Host " Slot: $slotPath" + Write-Host " CultCache: $cultCachePath" + Write-Host " Stdout: $stdoutLogPath" + Write-Host " Stderr: $stderrLogPath" + Remove-OldSlots + exit 0 +} + +Wait-ForStartedAquarium -Process $process -ExpectWindow:$true @{ slot = $slotPath diff --git a/src/Aquarium.Engine/AquariumHost.cs b/src/Aquarium.Engine/AquariumHost.cs index d24741a..fe94079 100644 --- a/src/Aquarium.Engine/AquariumHost.cs +++ b/src/Aquarium.Engine/AquariumHost.cs @@ -17,7 +17,7 @@ public static class AquariumHost var width = runtime.Options.Headless ? 640 : 1280; var height = runtime.Options.Headless ? 360 : 720; var iconPath = Path.Combine(AppContext.BaseDirectory, "Assets", "Aquarium-Engine-Icon.ico"); - using var window = Win32Window.Create("Epiphany Aquarium Engine", width, height, input, iconPath); + using var window = Win32Window.Create("Epiphany Aquarium Engine", width, height, input, iconPath, visible: !runtime.Options.Headless); window.PaintSplash("Aquarium", "Preparing runtime state"); using var renderer = new D3D11Renderer( window.Handle, @@ -58,6 +58,7 @@ public static class AquariumHost if (runtime.Options.Headless && ++frames >= 2) { + Console.WriteLine("Headless Aquarium completed requested frames."); break; } } diff --git a/src/Aquarium.Engine/Platform/Win32Window.cs b/src/Aquarium.Engine/Platform/Win32Window.cs index 3910e8d..c572d59 100644 --- a/src/Aquarium.Engine/Platform/Win32Window.cs +++ b/src/Aquarium.Engine/Platform/Win32Window.cs @@ -100,7 +100,7 @@ public sealed class Win32Window : IDisposable public int ClientHeight { get; private set; } - public static Win32Window Create(string title, int width, int height, InputState input, string? iconPath = null) + public static Win32Window Create(string title, int width, int height, InputState input, string? iconPath = null, bool visible = true) { var className = $"AquariumEngineWindow-{Guid.NewGuid():N}"; var instance = GetModuleHandle(null); @@ -180,11 +180,17 @@ public sealed class Win32Window : IDisposable throw new InvalidOperationException($"RegisterClassEx failed: {Marshal.GetLastWin32Error()}"); } + var style = WS_OVERLAPPEDWINDOW; + if (visible) + { + style |= WS_VISIBLE; + } + var handle = CreateWindowEx( 0, classNamePointer, titlePointer, - WS_OVERLAPPEDWINDOW | WS_VISIBLE, + style, CW_USEDEFAULT, CW_USEDEFAULT, width, @@ -199,7 +205,11 @@ public sealed class Win32Window : IDisposable throw new InvalidOperationException($"CreateWindowEx failed: {Marshal.GetLastWin32Error()}"); } - ShowWindow(handle, SW_SHOW); + if (visible) + { + ShowWindow(handle, SW_SHOW); + } + if (largeIcon != IntPtr.Zero) { SendMessage(handle, WM_SETICON, ICON_BIG, largeIcon); @@ -210,7 +220,11 @@ public sealed class Win32Window : IDisposable SendMessage(handle, WM_SETICON, ICON_SMALL, smallIcon); } - UpdateWindow(handle); + if (visible) + { + UpdateWindow(handle); + } + SetWindowText(handle, title); return new Win32Window(handle, className, windowProcedure, input, width, height, largeIcon, smallIcon, splashIcon); diff --git a/src/Aquarium.Engine/Render/D3D11Renderer.cs b/src/Aquarium.Engine/Render/D3D11Renderer.cs index 7792bd8..662e95e 100644 --- a/src/Aquarium.Engine/Render/D3D11Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D11Renderer.cs @@ -22,7 +22,7 @@ public sealed class D3D11Renderer : IDisposable private const int GridHeightTextureSize = 128; private const int DitherTextureSize = 512; private const int BloomLevelCount = 3; - private const int MediumVolumeDownscale = 2; + private const int MediumVolumeDownscale = 4; private const int FroxelCountX = 8; private const int FroxelCountY = 8; private const int FroxelCountZ = 4; @@ -141,7 +141,7 @@ public sealed class D3D11Renderer : IDisposable mediumVolumeHeight = Math.Max(1, height / MediumVolumeDownscale); ApplyGraphicsSettings(graphicsSettings ?? GraphicsSettings.Default); this.shaderPath = shaderPath ?? Path.Combine(AppContext.BaseDirectory, ShaderRelativePath); - startupProgress?.Invoke("Creating D3D11 device and swapchain"); + ReportStartupProgress(startupProgress, "Creating D3D11 device and swapchain"); var featureLevels = new[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0 }; var swapChainDescription = new SwapChainDescription @@ -172,14 +172,14 @@ public sealed class D3D11Renderer : IDisposable Console.WriteLine("D3D11 device and swapchain created."); - startupProgress?.Invoke("Creating swapchain render targets"); + ReportStartupProgress(startupProgress, "Creating swapchain render targets"); using var backBuffer = swapChain.GetBuffer(0); renderTargetView = device.CreateRenderTargetView(backBuffer); using var backBufferSurface = swapChain.GetBuffer(0); overlay = new DirectWriteOverlay(backBufferSurface, width, height); debugUi = CreateDebugUi(); - startupProgress?.Invoke("Compiling aquarium shaders"); + ReportStartupProgress(startupProgress, "Compiling aquarium shaders"); var initialShaders = CompileShaderSet(this.shaderPath); vertexShader = initialShaders.VertexShader; gridHeightPixelShader = initialShaders.GridHeightPixelShader; @@ -191,11 +191,11 @@ public sealed class D3D11Renderer : IDisposable bloomBlurVerticalPixelShader = initialShaders.BloomBlurVerticalPixelShader; resolvePixelShader = initialShaders.AquariumResolvePixelShader; lastShaderWriteUtc = File.GetLastWriteTimeUtc(this.shaderPath); - startupProgress?.Invoke("Creating Grid render targets and buffers"); + ReportStartupProgress(startupProgress, "Creating Grid render targets and buffers"); gridHeightTexture = CreateGridHeightTexture(); gridHeightRenderTargetView = device.CreateRenderTargetView(gridHeightTexture); gridHeightShaderResourceView = device.CreateShaderResourceView(gridHeightTexture); - startupProgress?.Invoke("Creating temporal render targets"); + ReportStartupProgress(startupProgress, "Creating temporal render targets"); sceneTexture = CreateHdrTexture(width, height); sceneRenderTargetView = device.CreateRenderTargetView(sceneTexture); sceneShaderResourceView = device.CreateShaderResourceView(sceneTexture); @@ -241,7 +241,7 @@ public sealed class D3D11Renderer : IDisposable historyControlTextureB = CreateHdrTexture(width, height); historyControlRenderTargetViewB = device.CreateRenderTargetView(historyControlTextureB); historyControlShaderResourceViewB = device.CreateShaderResourceView(historyControlTextureB); - startupProgress?.Invoke("Loading Aetheria blue-noise dither texture"); + ReportStartupProgress(startupProgress, "Loading Aetheria blue-noise dither texture"); ditherTexture = CreateDitherTexture(Path.Combine(AppContext.BaseDirectory, DitherTextureRelativePath)); ditherShaderResourceView = device.CreateShaderResourceView(ditherTexture); gridSampler = device.CreateSamplerState(new SamplerDescription @@ -341,7 +341,14 @@ public sealed class D3D11Renderer : IDisposable context.UpdateSubresource(froxelPrimitiveIds, froxelPrimitiveBuffer); context.UpdateSubresource(fieldInstances, fieldInstanceBuffer); RenderGridHeight(); - RenderMediumVolume(); + if (ShouldRenderMediumVolume()) + { + RenderMediumVolume(); + } + else + { + ClearMediumVolume(); + } RenderScene(); RenderBloom(); ResolveTemporal(); @@ -590,6 +597,22 @@ public sealed class D3D11Renderer : IDisposable context.Draw(3, 0); } + private bool ShouldRenderMediumVolume() + { + return MediumCompositeIntensity > 0.001f || (RenderDebugMode >= 9 && RenderDebugMode <= 11); + } + + private void ClearMediumVolume() + { + context.PSUnsetShaderResource(12); + context.PSUnsetShaderResource(13); + context.PSUnsetShaderResource(14); + context.OMSetRenderTargets(new[] { mediumVolumeRenderTargetView, mediumTransportRenderTargetView }); + context.RSSetViewport(0.0f, 0.0f, mediumVolumeWidth, mediumVolumeHeight, 0.0f, 1.0f); + context.ClearRenderTargetView(mediumVolumeRenderTargetView, new Color4(0.0f, 1.0f, 0.0f, 0.0f)); + context.ClearRenderTargetView(mediumTransportRenderTargetView, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); + } + private void RenderScene() { context.PSUnsetShaderResource(3); @@ -1024,6 +1047,12 @@ public sealed class D3D11Renderer : IDisposable return Compiler.CompileFromFile(path, entryPoint, profile, shaderFlags, EffectFlags.None); } + private static void ReportStartupProgress(Action? progress, string message) + { + Console.WriteLine($"Startup: {message}."); + progress?.Invoke(message); + } + private ShaderSet CompileShaderSet(string path) { var vertexShaderBytecode = CompileShader(path, "FullscreenTriangleVS", "vs_5_0"); diff --git a/src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl b/src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl index 3cb76ef..4f4f7cd 100644 --- a/src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl @@ -1492,7 +1492,7 @@ float mediumDensityColumnDebug(float3 rayDirection) float maxDensity = 0.0; float meanDensity = 0.0; - [unroll] + [loop] for (int sampleIndex = 0; sampleIndex < 16; sampleIndex++) { float z = lerp(-2.25, 3.5, ((float)sampleIndex + 0.5) / 16.0); diff --git a/state/evidence.jsonl b/state/evidence.jsonl index fe7adc1..3cb91b8 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -52,3 +52,4 @@ {"area":"renderer/volumetrics","lesson":"The first medium density view was too screen-ray dependent: it stored a completed half-res ray integral, so debug texture detail read as view-space soup. The pass now stores a 4x4 frustum slice atlas where each texel reconstructs a world point and evaluates field-local density; resolve integrates those stored cells front-to-back. Erosion noise is stationary in field-local space.","files":["src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl","docs/hlsl-renderer.md","docs/sdf-field-renderer-plan.md","state/memory.json","state/scratch.md"],"verification":["dotnet build Aquarium.Engine.slnx",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4"],"ts":"2026-05-09"} {"area":"renderer/volumetrics","lesson":"Do not label a view-dependent transport projection as Medium Density. Mode 9 now evaluates the registered medium field on a world-anchored Grid-altitude slice, while modes 10 and 11 remain frustum transport diagnostics. Density debugging and transport debugging are different tools.","files":["src/Aquarium.Engine/Render/D3D11Renderer.cs","src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl","docs/hlsl-renderer.md","state/scratch.md"],"verification":["dotnet build Aquarium.Engine.slnx"],"ts":"2026-05-09"} {"area":"renderer/volumetrics","lesson":"A single Grid-altitude density slice can be legitimately blank when local media live above or below the Grid. Mode 9 is now a world-anchored density column over the Grid plane, sampling a fixed z range and visualizing max/mean density. Source debug is boosted independently from physical transport so near-black source patches do not masquerade as useful diagnostics.","files":["src/Aquarium.Engine/Render/D3D11Renderer.cs","src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl","docs/hlsl-renderer.md","state/scratch.md"],"verification":["dotnet build Aquarium.Engine.slnx",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4"],"ts":"2026-05-09"} +{"area":"dev-reload/headless","lesson":"Headless verification must wait for the Aquarium process to exit after its requested frames, not return when the process merely starts. Hidden headless windows prevent stuck smoke tests from leaving visible non-responsive windows, stdout startup checkpoints reveal where startup wedged, and shader debug loops that call the registered medium stack should stay rolled instead of forcing D3DCompiler to unroll a huge expansion.","files":["scripts/dev-reload.ps1","src/Aquarium.Engine/AquariumHost.cs","src/Aquarium.Engine/Platform/Win32Window.cs","src/Aquarium.Engine/Render/D3D11Renderer.cs","src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl","state/memory.json","state/scratch.md"],"verification":["dotnet build Aquarium.Engine.slnx",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 60","Get-Process Aquarium.Engine returned no remaining processes"],"ts":"2026-05-09"} diff --git a/state/memory.json b/state/memory.json index db41cb2..adb6f84 100644 --- a/state/memory.json +++ b/state/memory.json @@ -90,6 +90,7 @@ "dev-reload builds disposable apphost slots so a running window does not lock normal build output. dev-watch hot reloads shaders and live runtime DLLs while preserving the last good process. Host/core/content changes, scripts, and src/Aquarium.Engine/Assets must rebuild and restart the apphost on demand. dev-watch must also relaunch if its recorded script-owned process is no longer running. For visible windows, dev-watch -ReopenWhenClosed reopens the last good visible slot without rebuilding.", "Live runtime reload is not successful just because dev-watch wrote live-current.txt. The watcher must see the host acknowledge the exact live DLL path in stdout, or treat the update as failed and keep the previous runtime/process alive.", "dev-watch must not use Start-Process -Wait to run dev-reload while dev-reload launches the long-lived Aquarium app. On Windows that can leave the watcher stuck after initial launch, never reaching the poll loop. Invoke the reload script synchronously and let dev-reload own the detached app process.", + "Headless dev-reload must prove process exit, not process creation. It should create a hidden window, wait for the requested frames to finish, kill/fail on timeout, and log renderer startup checkpoints to stdout so shader/resource failures cannot masquerade as hangs.", "Shader reload failure must keep the previous good shader objects bound. Live-runtime reload failure must keep the previous runtime alive. Rehydrate from CultCache before claiming reload survival." ], "salvage_without_baggage": [ diff --git a/state/scratch.md b/state/scratch.md index f3f6fef..f379d08 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -170,3 +170,9 @@ prototype integrated along the camera ray before surface composition. Aquarium now quarantines unreadable snapshots with a `.corrupt-` suffix and boots fresh state; CultLib single-file stores now write through a temp file and atomic replace to avoid future zero-byte live snapshots. +- Headless dev-reload correction: `-Headless` now creates a hidden Win32 window, + waits for the two-frame run to exit, kills and fails on timeout, and logs + renderer startup checkpoints to stdout. This exposed the real shader compile + failure: the medium density-column debug loop must stay rolled because forcing + an unroll expands the registered medium density stack beyond D3DCompiler's + tolerance.