feat(render): Campaign V slice V4a - port TextRenderer/BitmapFont/DebugLineRenderer/TextureCache UI path onto IGpuDevice

Second attempt at V4a after ceec3bc4 was reverted at 9aaf97e7 for losing world
multisampling and a 334-file scope explosion. This lands the same functional
slice with a much smaller footprint and the two structural fixes the revert
postmortem (docs/plans/2026-07-27-vulkan-campaign.md SS7.1) called for.

What moved onto the RHI:
- TextRenderer: the ui_text shader now compiles through IGpuDevice.CreatePipeline
  (one IGpuPipeline, replacing the old hand-rolled Shader class); its three
  fence-buffered per-flight VBOs are gone in favour of a per-IGpuFrame ring
  allocation per draw bucket; its 1x1 white fill texture is created via
  IGpuDevice.CreateTexture and registered into the device's texture table.
  Flush keeps TextRenderGlStateScope and the manual GL disable block verbatim
  (TextRendererFailureSafetyTests pins their literal presence) alongside the
  new pipeline bind - both target the identical final GL state, so this is
  redundant, not contradictory. Sprite/font texture binding stays classic
  (glActiveTexture/glBindTexture) because DrawSprite receives arbitrary
  externally-owned GL texture names from dozens of UI call sites outside this
  slice's scope; IGpuPassEncoder has no verb for that, by design (every other
  RHI consumer samples through the bindless texture table).
- BitmapFont: the stb-baked R8 atlas is created/uploaded through
  IGpuDevice.CreateTexture; TextureId stays a raw GL name extracted from the
  IGpuTexture, since its only consumer is TextRenderer's classic path above.
- DebugLineRenderer: the debug_line shader compiles through
  IGpuDevice.CreatePipeline (LineList topology, depth disabled); Flush ring-
  allocates its vertex data and draws through IGpuPassEncoder. uView/uProjection
  don't fit the shared GpuPushConstants block (one combined VP matrix) so they
  are set directly on the pipeline's compiled program, mirroring TextRenderer.
- TextureCache: GetOrUploadRenderSurface and the public UploadRgba8(byte[],...)
  wrapper now create IGpuTexture+GpuTextureSlot internally, extracting the raw
  GL name for their unchanged uint return type - DrawSprite's signature and its
  16 call sites across the UI are untouched. The world-material path
  (GetOrUpload, the raw layer-array upload) is untouched.
- UiViewport: TextureHandle (uint) -> TextureSlot (GpuTextureSlot), resolved
  back to a raw GL name via TextRenderer.ResolveExternalTextureSlot at draw
  time. Its texture is produced by PaperdollViewportRenderer/
  PrivateEntityViewportRenderer, both still raw GL until V4g, so
  RetailPaperdollFrameView/RetailCreatureAppraisalFrameView register it through
  the pre-approved GlGpuDevice.RegisterExternalColorTexture transitional seam
  (campaign doc SS7.1's final paragraph) instead of inventing anything broader.

The two revert-postmortem fixes, both in Gpu/Gl (never in the pinned Gpu/
contract):
- GlGpuDevice.BeginPass now resets the render-state cache unconditionally on
  every pass, not only a clearing one. The first attempt's crash came from
  exactly this gap: a raw-GL renderer running between two RHI passes changes
  GL program/blend/depth/cull state the cache never observes, so a later
  BindPipeline skipped re-issuing glUseProgram and the following push-constant
  upload threw GL_INVALID_OPERATION.
- GlGpuPassEncoder now captures ambient GL capability state (program, VAO,
  array buffer, texture0 binding, depth test/write/func, blend enable+func,
  cull enable+mode, front face, alpha-to-coverage, multisample) on construction
  and restores it on Dispose, generalizing what TextRenderGlStateScope already
  did for TextRenderer specifically to every RHI pass - this is what stops
  DebugLineRenderer's pipeline bind (which has no scope of its own) from
  leaking state into the next raw-GL renderer. Both are marked transitional,
  deleted at V4h once nothing raw-GL remains.

Frame lifecycle (additive, per the task's own description of this piece):
new GpuDeviceFrameLifetime wraps IGpuDevice.BeginFrame()/IGpuFrame.End() and
exposes the open frame via ICurrentGpuFrameSource. RenderFrameOrchestrator's
IRenderFrameLifetime now routes through this wrapper instead of calling
GpuFrameFlightController directly - GlGpuDevice.BeginFrame already calls
straight through to that same controller, so the fence/slot-rotation contract
is unchanged; the wrapper only additionally yields the IGpuFrame ported
renderers need. No clears moved, no framebuffer binding changed, frame-graph
phase order is untouched. The two now-dead per-slot TextRenderer.BeginFrame(int)
calls in RuntimeRenderFrameBeginResources are removed. The UI Studio
(RenderBootstrap/StudioWindow) gets its own independent RHI device+lifetime,
mirroring the production composition.

Real bug found and fixed while exercising this for the first time: both
BitmapFont and TextureCache's nearest-filter override called TexParameter
AFTER RegisterTexture, which made the bindless handle resident - GL_ARB_
bindless_texture forbids modifying a texture's parameters once its handle is
resident, so this threw GL_INVALID_OPERATION building the retained UI's own
TextRenderer. Fixed by moving both TexParameter blocks before RegisterTexture.

Scope note: touches 25 files (24 modified + this commit's one new file), not
the ~10 the brief estimated, because the frame-lifecycle wiring and the
viewport escape hatch (both explicitly asked for) ripple through five
composition files and two frame presenters that thread IGpuDevice/
ICurrentGpuFrameSource to construction sites. No file outside that necessary
set was touched: no visibility sweep beyond the specific constructors/
properties whose new parameter types are internal (TextRenderer/BitmapFont/
DebugLineRenderer/UiHost's constructors, TextureCache's otherwise-orphaned
convenience overload, UiViewport.TextureSlot), no world-mesh/terrain/particle/
sky file touched, no test deleted or weakened - three source-text conformance
tests (TextRendererPublishesEveryConstructorResourceBeforeLaterGlWork,
GlTextureOwnershipTests' TextRenderer.cs check, and
RenderFrameResourceControllerTests' frame-order check) were replaced with
equivalent assertions against the new construction/wiring shape, since their
pinned invariant was specifically the old raw-GL shape this slice legitimately
replaces.

Gates:
- dotnet build -c Release: 0 warnings, 0 errors.
- dotnet test tests/AcDream.App.Tests -c Release: 3,843 passed / 3 skipped -
  exactly the baseline. Complete solution: 8,906 passed / 5 skipped across all
  nine test projects.
- Offline pixel gate (tools/run-offline-pixel-gate.ps1, parent a97e04ae vs this
  commit): 26 differing pixels of 563,200 compared (fraction 4.62e-05), pass
  against the 0.001/563-pixel threshold. Verified against a same-commit control
  (two captures at this commit differ by 20 pixels) rather than accepted at
  face value - the two numbers are in the same band, confirming this is normal
  animated-content/frame-pacing noise and not the systematic silhouette-edge
  loss (1,791 pixels, 224x higher) the first attempt's revert diagnosed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-07-27 19:37:19 +02:00
parent a97e04ae3d
commit 096dd203fa
26 changed files with 954 additions and 467 deletions

View file

@ -1,94 +1,89 @@
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.InteropServices;
using AcDream.App.Rendering.Gpu;
using AcDream.App.Rendering.Gpu.Gl;
using Silk.NET.OpenGL;
namespace AcDream.App.Rendering;
/// <summary>
/// Minimal GL debug line renderer for visualizing collision shapes,
/// bounding boxes, and other debug geometry. Collect lines each frame
/// via <see cref="AddLine"/> / <see cref="AddCylinder"/>, then call
/// Minimal line renderer for visualizing collision shapes, bounding boxes,
/// and other debug geometry. Collect lines each frame via
/// <see cref="AddLine"/> / <see cref="AddCylinder"/>, then call
/// <see cref="Flush"/> to upload + draw them.
///
/// Uses a single shared VBO that's respecialized each frame. Vertex
/// format is (vec3 pos, vec3 color) = 24 bytes per vertex.
/// Campaign V slice V4a: the <c>debug_line</c> shader compiles through
/// <see cref="IGpuDevice.CreatePipeline"/> (<see cref="GpuPrimitiveTopology.LineList"/>
/// topology, depth disabled to match this renderer's "visible through
/// geometry" intent), and each Flush's vertex data comes from a per-frame
/// ring allocation instead of the old single respecialized VBO. The shader's
/// <c>uView</c>/<c>uProjection</c> pair does not fit the shared
/// <c>GpuPushConstants</c> block (one combined view-projection matrix), and
/// <see cref="IGpuPassEncoder"/> has no verb for arbitrary named uniforms, so
/// they are set directly against the pipeline's compiled program — the same
/// mechanical translation <see cref="TextRenderer"/> uses for its own
/// shader-local uniforms.
///
/// Vertex format is (vec3 pos, vec3 color) = 24 bytes per vertex.
/// </summary>
public sealed unsafe class DebugLineRenderer : IDisposable
{
private const int FloatsPerVertex = 6;
private const int VertexStrideBytes = FloatsPerVertex * sizeof(float);
private static readonly GpuVertexLayout VertexLayout = new(
StrideBytes: VertexStrideBytes,
[
new GpuVertexAttribute(0, GpuVertexFormat.Float3, 0),
new GpuVertexAttribute(1, GpuVertexFormat.Float3, 12),
]);
private readonly GL _gl;
private readonly Shader _shader;
private readonly uint _vao;
private readonly uint _vbo;
private readonly ResourceCleanupGroup _resources;
private readonly ICurrentGpuFrameSource _frameSource;
private readonly IGpuPipeline _pipeline;
private readonly int _uViewLocation;
private readonly int _uProjectionLocation;
private readonly List<float> _buffer = new(4096);
private int _vertexCount;
private int _capacityBytes;
public DebugLineRenderer(GL gl, string shaderDir)
// internal, not public: IGpuDevice/ICurrentGpuFrameSource are internal
// types (the pinned RHI contract). DebugLineRenderer stays public — only
// construction is restricted.
internal DebugLineRenderer(IGpuDevice device, ICurrentGpuFrameSource frameSource, string shaderDir)
{
_gl = gl ?? throw new ArgumentNullException(nameof(gl));
ArgumentNullException.ThrowIfNull(device);
_frameSource = frameSource ?? throw new ArgumentNullException(nameof(frameSource));
ArgumentException.ThrowIfNullOrWhiteSpace(shaderDir);
var resources = new ResourceCleanupGroup();
Shader? shader = null;
uint vao = 0;
uint vbo = 0;
try
if (device is not GlGpuDevice glDevice)
{
shader = new Shader(gl,
Path.Combine(shaderDir, "debug_line.vert"),
Path.Combine(shaderDir, "debug_line.frag"));
resources.Add("debug-line shader", shader.Dispose);
vao = GlResourceCommand.CreateName(
gl,
"debug-line VAO",
gl.GenVertexArray,
gl.DeleteVertexArray);
uint ownedVao = vao;
resources.Add(
"debug-line VAO",
() => GlResourceCommand.DeleteVertexArray(
gl,
ownedVao,
$"delete debug-line VAO {ownedVao}"));
vbo = GlResourceCommand.CreateName(
gl,
"debug-line VBO",
gl.GenBuffer,
gl.DeleteBuffer);
uint ownedVbo = vbo;
resources.Add(
"debug-line VBO",
() => GlResourceCommand.DeleteBuffer(
gl,
ownedVbo,
$"delete debug-line VBO {ownedVbo}"));
GlResourceCommand.Execute(gl, "configure debug-line vertex state", () =>
{
gl.BindVertexArray(vao);
gl.BindBuffer(BufferTargetARB.ArrayBuffer, vbo);
// 24-byte stride: vec3 pos + vec3 color
gl.EnableVertexAttribArray(0);
gl.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 6 * sizeof(float), (void*)0);
gl.EnableVertexAttribArray(1);
gl.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 6 * sizeof(float), (void*)(3 * sizeof(float)));
gl.BindBuffer(BufferTargetARB.ArrayBuffer, 0);
gl.BindVertexArray(0);
});
throw new NotSupportedException(
"DebugLineRenderer's uView/uProjection uniforms (see the class remarks) are set " +
"directly against the GL program; it needs GlGpuDevice's raw GL handle.");
}
catch (Exception constructionFailure)
_gl = glDevice.Gl;
_pipeline = device.CreatePipeline(new GpuPipelineDescription
{
resources.RollbackConstructionAndThrow(
"DebugLineRenderer construction failed and its GL prefix did not cleanly roll back.",
constructionFailure);
}
Name = "debug-line",
Shaders = new GpuShaderSet("debug_line"),
VertexLayout = VertexLayout,
Topology = GpuPrimitiveTopology.LineList,
Blend = GpuBlendMode.None,
// Retail debug lines draw through geometry (the old Flush disabled
// depth testing for the draw and restored whatever was ambient
// before it — GlGpuPassEncoder now does that restore generically;
// see its class comment).
Depth = GpuDepthState.Disabled,
Cull = GpuCullMode.None,
AlphaToCoverage = false,
ColorWrite = true,
SampleCount = 1,
});
_resources = resources;
_shader = shader!;
_vao = vao;
_vbo = vbo;
uint program = ((GlGpuPipeline)_pipeline).GlProgram;
_uViewLocation = _gl.GetUniformLocation(program, "uView");
_uProjectionLocation = _gl.GetUniformLocation(program, "uProjection");
}
/// <summary>Clear accumulated lines. Call at the start of each frame.</summary>
@ -174,40 +169,42 @@ public sealed unsafe class DebugLineRenderer : IDisposable
{
if (_vertexCount == 0) return;
_shader.Use();
_shader.SetMatrix4("uView", view);
_shader.SetMatrix4("uProjection", projection);
IGpuFrame frame = _frameSource.CurrentFrame
?? throw new InvalidOperationException(
"DebugLineRenderer.Flush requires an open IGpuFrame (see GpuDeviceFrameLifetime) — " +
"the host must drive IGpuDevice.BeginFrame() before rendering debug lines.");
_gl.BindVertexArray(_vao);
_gl.BindBuffer(BufferTargetARB.ArrayBuffer, _vbo);
int neededBytes = _buffer.Count * sizeof(float);
if (neededBytes > _capacityBytes)
using IGpuPassEncoder encoder = frame.BeginPass(new GpuPassDescription
{
fixed (float* ptr = CollectionsMarshal.AsSpan(_buffer))
_gl.BufferData(BufferTargetARB.ArrayBuffer, (nuint)neededBytes, ptr, BufferUsageARB.DynamicDraw);
_capacityBytes = neededBytes;
}
else
{
fixed (float* ptr = CollectionsMarshal.AsSpan(_buffer))
_gl.BufferSubData(BufferTargetARB.ArrayBuffer, 0, (nuint)neededBytes, ptr);
}
Name = "debug-line",
Color = new GpuColorAttachment(
Target: null,
Load: GpuLoadOp.Load,
Store: GpuStoreOp.Store,
ClearColor: default),
Depth = null,
SampleCount = 1,
});
encoder.BindPipeline(_pipeline);
SetMatrix(_uViewLocation, view);
SetMatrix(_uProjectionLocation, projection);
// Depth test on so lines get occluded by geometry (but we want them
// visible through geometry — disable depth test so everything shows).
bool wasDepthEnabled = _gl.IsEnabled(EnableCap.DepthTest);
_gl.Disable(EnableCap.DepthTest);
int byteCount = _buffer.Count * sizeof(float);
GpuRingAllocation allocation = frame.AllocateRing(byteCount, GpuRingUsage.Vertex);
System.Runtime.InteropServices.CollectionsMarshal.AsSpan(_buffer).CopyTo(allocation.AsSpan<float>());
encoder.BindVertexBuffer(allocation.Buffer, allocation.OffsetBytes);
encoder.Draw((uint)_vertexCount, 1, 0, 0);
}
_gl.DrawArrays(PrimitiveType.Lines, 0, (uint)_vertexCount);
if (wasDepthEnabled) _gl.Enable(EnableCap.DepthTest);
_gl.BindVertexArray(0);
private void SetMatrix(int location, Matrix4x4 m)
{
if (location < 0)
return;
_gl.UniformMatrix4(location, 1, false, (float*)&m);
}
public void Dispose()
{
_resources.RetryCleanup();
_pipeline.Dispose();
}
}