feat(render): Campaign V slice V4a - port TextRenderer/BitmapFont/DebugLineRenderer/TextureCache onto IGpuDevice
TextRenderer, BitmapFont, DebugLineRenderer, and TextureCache's UI-texture
upload path (GetOrUploadRenderSurface/UploadRgba8) now issue every draw and
resource creation through the pinned IGpuDevice/IGpuFrame/IGpuPassEncoder
RHI contract instead of raw GL. This is the RHI's first real production
consumer - V0-V3 only established the contract, GL backend skeleton, and a
shader-dialect migration with no live GL exercise. TextRenderer owns one
IGpuPipeline (ui_text shader, straight-alpha blend, depth disabled) and
allocates a per-bucket ring each Flush; BitmapFont's atlas texture is
created and uploaded via device.CreateTexture/.Upload; DebugLineRenderer
mirrors the same one-pipeline-per-Flush shape for its line-list draws.
World-path TextureCache methods (GetOrUpload, the raw-GL layer-array
upload) are untouched - still legacy GL, still out of scope.
Frame lifecycle: GpuDeviceFrameLifetime (RenderFrameOrchestrator.cs) wraps
IGpuDevice.BeginFrame()/IGpuFrame.End() inside the existing
IRenderFrameLifetime bracket HostInputCameraCompositionPhase already opens
per callback, additively - no frame-graph restructuring. Ported renderers
reach the frame via ICurrentGpuFrameSource, a plain interface (not a
delegate field) so WorldSceneDiagnosticsController keeps passing its
existing "no stored window/delegate" architectural-conformance test.
Two real bugs surfaced by actually exercising the RHI against a live GL
context (nothing here was previously reachable before this slice):
- GlGpuDevice.BeginFrame() now resets the render-state cache every frame.
The cache assumes it is the sole writer of GL program/blend/depth/cull
state, which was true while it had zero real consumers, but every
still-legacy renderer (WbDrawDispatcher, terrain, particles, EnvCells)
mutates that same GL state directly and never informs the cache. Once a
legacy renderer ran between two RHI binds, the cache's belief about the
current GL program went stale, so a later BindPipeline(text shader)
skipped re-issuing glUseProgram and the following push-constant upload
threw GL_INVALID_OPERATION against whatever program was actually bound.
Reset() at the frame boundary is the same defensive move BeginPass
already makes after a forced clear (see its comment); it costs one
redundant state application on the frame's first bind.
- GL_MULTISAMPLE has no representation in the pinned contract. Added a
GL-backend-internal Multisample field to GlRenderStateSnapshot/Changes,
computed from GpuPipelineDescription.SampleCount at BindPipeline time -
mirrors how Vulkan bakes MSAA into the pipeline instead of a separate
toggle.
Collateral, scoped to keep the port real rather than a stub:
- GpuTextureSlot (Unassigned = uint.MaxValue, NOT 0) now flows through
every consumer of TextureCache.GetOrUploadRenderSurface/UploadRgba8 and
TextRenderer.DrawSprite - the entire retained UI layer, since a pervasive
Func<uint,(uint,int,int)> sprite-resolve delegate threads through nearly
every UI element/controller. Every prior `== 0` / `!= 0` "no texture"
check became `.IsAssigned` / `!.IsAssigned`; slot 0 is a real assigned
slot (the device's default white texture), so the old sentinel would
have produced live visual regressions if left in place.
- GpuTextureSlot/IGpuDevice/IGpuFrame are internal, so ~270 previously
public AcDream.App types that touched them (directly or transitively)
are now internal too - safe, since AcDream.App is an exe with no
external project references; only the two test projects consume it, via
InternalsVisibleTo. A handful of unrelated types the sweep caught
(ElementInfo/ImportedLayout's property-bag hierarchy, several enums used
as public [Theory] parameters, CursorFeedbackSnapshot's DragAcceptState)
were reverted back to public where making them internal would have
either cascaded into unrelated files or broken xUnit's public-member
discovery.
- ExternalViewportTextureBridge (new) registers the still-raw-GL FBO
color textures PrivateEntityViewportRenderer/PaperdollViewportRenderer
produce (V4g's scope) into the device's texture table for
UiViewport.TextureHandle, via a temporary
GlGpuDevice.RegisterExternalColorTexture escape hatch (internal, not
part of IGpuDevice) deleted when V4g ports those viewports.
- TextRenderGlStateScope.cs and its test deleted: the pipeline description
now bakes what it used to restore by hand.
- ResourceCleanupGroupTests/GlTextureOwnershipTests: the two source-text
conformance tests keyed to TextRenderer's old multi-resource
construction shape (Shader + per-flight FrameBufferSet array + white
texture + tracked VAO/VBO, all via ResourceCleanupGroup) no longer apply
- that shape is gone, replaced by one IGpuPipeline created through
IGpuDevice. The construction-order test is deleted; the checked-commit
texture-creation check now targets GlGpuTexture (which already used
the same GlResourceCommand.CreateName primitive before this slice).
Gates:
- dotnet build -c Release: 0 warnings, 0 errors (AcDream.App has
TreatWarningsAsErrors).
- dotnet test tests/AcDream.App.Tests -c Release: 3,840 passed / 3
skipped (was 3,843/3 entering this slice - net 3 fewer tests:
TextRendererFailureSafetyTests.cs deleted (2, tested the now-deleted
TextRenderGlStateScope) plus the one retired ResourceCleanupGroupTests
method). Full solution: 8,908 passed / 5 skipped across all nine test
projects.
- Offline pixel gate (tools/run-offline-pixel-gate.ps1, parent ec414d60
vs this commit): differing fraction 0.318% (1,791/563,200 compared
pixels), above the 0.001 threshold. Investigated pixel-by-pixel rather
than waved through: a diff heatmap plus 4x crops at the differing
clusters show zero differences anywhere in the retained UI, terrain,
scenery, or static meshes - every differing pixel sits on continuously-
animated ambient content (flying-insect sprites over the swamp, foliage
sparkle/dew glints) whose exact phase depends on elapsed wall-clock
time, the same category the gate's own sky-masking rationale already
documents and the campaign doc's coverage table explicitly excludes
("Not covered - particles"). Confirming evidence: two same-commit
captures at HEAD compare clean against each other (0.0025%), and two
same-commit captures at the parent compare clean against each other
(0.0044%) - only base-vs-head is consistently elevated, which is what
frame-pacing drift from genuinely new per-frame RHI work (BeginFrame,
ring resets, the render-state reset above) would produce against a
fixed wall-clock capture deadline, not a rendering defect. Recommend a
quick user visual check of this capture pair alongside the automated
result, matching how V2c's particle work was already handled in this
campaign (flagged for user visual confirmation rather than blocked on
an automated gate that cannot cover animated content).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
ec414d60cd
commit
ceec3bc440
334 changed files with 3660 additions and 3840 deletions
|
|
@ -1,94 +1,56 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Silk.NET.OpenGL;
|
||||
|
||||
namespace AcDream.App.Rendering;
|
||||
|
||||
/// <summary>
|
||||
/// Minimal GL debug line renderer for visualizing collision shapes,
|
||||
/// Minimal 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
|
||||
/// <see cref="Flush"/> to upload + draw them.
|
||||
/// <see cref="Flush"/> to upload + draw them through the current
|
||||
/// <see cref="IGpuFrame"/>.
|
||||
///
|
||||
/// 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: ported onto <see cref="IGpuDevice"/>. Owns one
|
||||
/// pipeline (LINE_LIST topology, depth disabled — lines must show through
|
||||
/// geometry, matching the prior explicit <c>DepthTest</c> disable) and draws
|
||||
/// with the frame's ring rather than a persistent respecialized VBO. Vertex
|
||||
/// format is (vec3 pos, vec3 color) = 24 bytes per vertex, unchanged.
|
||||
/// </summary>
|
||||
public sealed unsafe class DebugLineRenderer : IDisposable
|
||||
internal sealed class DebugLineRenderer : IDisposable
|
||||
{
|
||||
private readonly GL _gl;
|
||||
private readonly Shader _shader;
|
||||
private readonly uint _vao;
|
||||
private readonly uint _vbo;
|
||||
private readonly ResourceCleanupGroup _resources;
|
||||
private readonly IGpuDevice _device;
|
||||
private readonly IGpuPipeline _pipeline;
|
||||
|
||||
private static readonly GpuVertexLayout VertexLayout = new(
|
||||
StrideBytes: 24,
|
||||
[
|
||||
new GpuVertexAttribute(0, GpuVertexFormat.Float3, 0),
|
||||
new GpuVertexAttribute(1, GpuVertexFormat.Float3, 12),
|
||||
]);
|
||||
|
||||
private readonly List<float> _buffer = new(4096);
|
||||
private int _vertexCount;
|
||||
private int _capacityBytes;
|
||||
|
||||
public DebugLineRenderer(GL gl, string shaderDir)
|
||||
public DebugLineRenderer(IGpuDevice device)
|
||||
{
|
||||
_gl = gl ?? throw new ArgumentNullException(nameof(gl));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(shaderDir);
|
||||
var resources = new ResourceCleanupGroup();
|
||||
Shader? shader = null;
|
||||
uint vao = 0;
|
||||
uint vbo = 0;
|
||||
try
|
||||
_device = device ?? throw new ArgumentNullException(nameof(device));
|
||||
_pipeline = _device.CreatePipeline(new GpuPipelineDescription
|
||||
{
|
||||
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);
|
||||
});
|
||||
}
|
||||
catch (Exception constructionFailure)
|
||||
{
|
||||
resources.RollbackConstructionAndThrow(
|
||||
"DebugLineRenderer construction failed and its GL prefix did not cleanly roll back.",
|
||||
constructionFailure);
|
||||
}
|
||||
|
||||
_resources = resources;
|
||||
_shader = shader!;
|
||||
_vao = vao;
|
||||
_vbo = vbo;
|
||||
Name = "debug-line",
|
||||
Shaders = new GpuShaderSet("debug_line"),
|
||||
VertexLayout = VertexLayout,
|
||||
Topology = GpuPrimitiveTopology.LineList,
|
||||
Blend = GpuBlendMode.None,
|
||||
// Retail debug lines are drawn visible THROUGH geometry — the
|
||||
// prior GL path captured+disabled DepthTest around the draw and
|
||||
// restored whatever the caller had before. A dedicated pipeline
|
||||
// bakes "always visible" directly, which is simpler and exactly
|
||||
// as behaviour-preserving since nothing else shares this pipeline.
|
||||
Depth = GpuDepthState.Disabled,
|
||||
Cull = GpuCullMode.None,
|
||||
ColorWrite = true,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Clear accumulated lines. Call at the start of each frame.</summary>
|
||||
|
|
@ -169,45 +131,40 @@ public sealed unsafe class DebugLineRenderer : IDisposable
|
|||
AddLine(c[2], c[6], color); AddLine(c[3], c[7], color);
|
||||
}
|
||||
|
||||
/// <summary>Upload + draw all accumulated lines.</summary>
|
||||
public void Flush(Matrix4x4 view, Matrix4x4 projection)
|
||||
/// <summary>Upload + draw all accumulated lines against the current frame.</summary>
|
||||
public void Flush(Matrix4x4 view, Matrix4x4 projection, IGpuFrame frame)
|
||||
{
|
||||
if (_vertexCount == 0) return;
|
||||
ArgumentNullException.ThrowIfNull(frame);
|
||||
|
||||
_shader.Use();
|
||||
_shader.SetMatrix4("uView", view);
|
||||
_shader.SetMatrix4("uProjection", projection);
|
||||
int byteCount = _buffer.Count * sizeof(float);
|
||||
GpuRingAllocation allocation = frame.AllocateRing(byteCount, GpuRingUsage.Vertex);
|
||||
CollectionsMarshal.AsSpan(_buffer).CopyTo(allocation.AsSpan<float>());
|
||||
|
||||
_gl.BindVertexArray(_vao);
|
||||
_gl.BindBuffer(BufferTargetARB.ArrayBuffer, _vbo);
|
||||
|
||||
int neededBytes = _buffer.Count * sizeof(float);
|
||||
if (neededBytes > _capacityBytes)
|
||||
using IGpuPassEncoder pass = 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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
_gl.DrawArrays(PrimitiveType.Lines, 0, (uint)_vertexCount);
|
||||
|
||||
if (wasDepthEnabled) _gl.Enable(EnableCap.DepthTest);
|
||||
|
||||
_gl.BindVertexArray(0);
|
||||
Name = "debug-lines",
|
||||
Color = new GpuColorAttachment(
|
||||
Target: null,
|
||||
Load: GpuLoadOp.Load,
|
||||
Store: GpuStoreOp.Store,
|
||||
ClearColor: default),
|
||||
Depth = null,
|
||||
SampleCount = 1,
|
||||
});
|
||||
pass.BindPipeline(_pipeline);
|
||||
pass.BindVertexBuffer(allocation.Buffer, allocation.OffsetBytes);
|
||||
// Same combined-matrix convention every other ported shader uses
|
||||
// (WbDrawDispatcher, TerrainModernRenderer, ParticleRenderer):
|
||||
// C# multiplies view * projection once and uploads the single
|
||||
// uViewProjection the shader now declares, replacing the separate
|
||||
// uView/uProjection uniforms.
|
||||
pass.SetPushConstants(GpuPushConstants.Default with { ViewProjection = view * projection });
|
||||
pass.Draw((uint)_vertexCount, instanceCount: 1, firstVertex: 0, firstInstance: 0);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_resources.RetryCleanup();
|
||||
_pipeline.Dispose();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue