acdream/src/AcDream.App/Rendering/Gpu/Gl/GlRingBufferState.cs
Erik 4f94ad7ddd feat(render): Campaign V slice V1 - OpenGL RHI backend (dark)
Implements GlGpuDevice and the rest of AcDream.App.Rendering.Gpu.Gl,
filling the V0-pinned IGpuDevice contract on OpenGL 4.3. This is the
first of the port slices described in
docs/plans/2026-07-27-vulkan-campaign.md: every later renderer port
(V2 onward) needs a real, driver-proven GL implementation of the RHI
to port onto, and the GL backend is deliberately built to be
behaviour-preserving rather than optimal, because that is what turns
each subsequent slice's pixel gate into a strict identity check
instead of a moving target. The Vulkan backend (V5+) is where the
actual efficiency gains land.

GlGpuDevice is a fresh root, not derived from Chorizite's
BaseGraphicsDevice/OpenGLGraphicsDevice - shedding that inheritance is
one of the things this campaign explicitly does. It owns its own
BindlessSupport instance rather than sharing the legacy WB render
path's, which is what lets it be constructed the moment a GL context
and a GpuFrameFlightController exist, with no dependency on when
WorldRenderCompositionPhase happens to detect bindless support later
in startup. The ring buffer keeps a managed staging array plus a real
GL buffer per flight slot and flushes with one BufferSubData
immediately before each Draw/DrawIndexed/MultiDrawIndexedIndirect
(never at bind time, since a renderer may still write after binding);
V1 throws on an over-capacity ring request rather than growing it,
since nothing consumes the device yet and a silent grow would hide a
future renderer's real working set. The texture table is a bump/free-
list allocator over a managed uvec2 handle array, gated through the
frame-flight retirement queue so a released slot cannot be reused
while a submitted frame might still read it. Push constants are
applied by uniform name on the currently-bound program, cached per
program, and explicitly re-applied whenever BindPipeline switches
programs - GL uniforms are per-program state, so the "survives
pipeline changes within a pass" guarantee the interface documents (a
freebie on Vulkan's shared pipeline layout) has to be emulated here.

BindlessSupport gained one additive method,
GetResidentHandle(texture, sampler), calling the same
ArbBindlessTexture.GetTextureSamplerHandle entry point
ManagedGLTextureArray already uses through a different path. The
existing GetResidentHandle(texture) cannot express
IGpuDevice.RegisterTexture's documented pair semantics ("the same
texture registered with two samplers occupies two slots"), so this
was the minimal change needed rather than a workaround.

The pure bookkeeping - ring watermark/alignment arithmetic, the
texture-slot allocator, render-state diffing, the push-constant field-
to-uniform-name table, and GL format mapping - lives in small GL-free
classes so it is unit-testable without a live context, following the
same seam pattern GpuFrameFlightController already uses for its fence
API. GlGpuTimerPool follows suit with an injectable timer-query API.

The device is constructed in HostInputCameraCompositionPhase
immediately after the frame-flight controller (the same phase that
already builds GpuFrameFlightController), rather than in
WorldRenderCompositionPhase as first considered: GlGpuDevice's self-
contained bindless detection means it has no ordering dependency on
the legacy WB path's BindlessSupport, so it can be proven against the
real driver as early as possible while keeping the composition change
to one phase. Composition, publication, and shutdown wiring follow
the existing acquire/publish/fault-injection pattern exactly, and GPU
device disposal is scheduled through the frame-flight retirement queue
before that queue itself is torn down. Nothing consumes the device
yet - that starts at V4a - so this slice's pixel gate is trivially a
tripwire.

App tests: 3834 passed / 3 skipped (V0 baseline 3785 + 49 new: ring,
texture-slot, render-state, push-constant, format-mapping, enum-
mapping, and timer-pool tests, plus one new fault-injection point in
the existing composition theory).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 15:11:04 +02:00

99 lines
3.9 KiB
C#

namespace AcDream.App.Rendering.Gpu.Gl;
/// <summary>
/// Pure bookkeeping for one flight slot's upload ring: an allocation cursor
/// that only grows across a frame, plus a separate "dirty" watermark that
/// tracks the byte range written since the last flush.
///
/// This is deliberately GL-free so it can be unit tested without a live
/// context. <see cref="GlGpuFrame"/> owns one instance per flight slot and
/// pairs it with a managed staging <c>byte[]</c> and a real GL buffer; the
/// staging array receives every <see cref="GpuRingAllocation.Data"/> write,
/// and immediately before each <c>Draw</c>/<c>DrawIndexed</c>/
/// <c>MultiDrawIndexedIndirect</c> the device uploads exactly the dirty range
/// via one <c>glBufferSubData</c> call and calls <see cref="TakeDirtyRange"/>
/// to reset the watermark. The allocation cursor itself only resets at
/// <see cref="Reset"/> (once per <c>BeginFrame</c>) — writes made after a
/// flush simply extend the dirty range again, to be picked up by the next
/// flush. This is what makes "flush before every draw, not at bind time"
/// correct: a renderer that writes after binding still gets uploaded before
/// its draw call runs.
/// </summary>
internal sealed class GlRingBufferState
{
private readonly int _capacityBytes;
private uint _cursor;
private int _dirtyStart = -1;
private int _dirtyEnd = -1;
public GlRingBufferState(int capacityBytes)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(capacityBytes);
_capacityBytes = capacityBytes;
}
public int CapacityBytes => _capacityBytes;
/// <summary>Bytes handed out since the last <see cref="Reset"/>.</summary>
public uint AllocatedBytes => _cursor;
/// <summary>
/// Reserves <paramref name="byteCount"/> bytes aligned to
/// <paramref name="alignmentBytes"/>, returning the aligned offset.
/// Throws — rather than truncating — when the request would exceed the
/// slot's capacity, because a silently shortened allocation would corrupt
/// the frame invisibly.
/// </summary>
public uint Allocate(int byteCount, uint alignmentBytes)
{
ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
uint aligned = AlignUp(_cursor, alignmentBytes);
long end = (long)aligned + byteCount;
if (end > _capacityBytes)
{
throw new InvalidOperationException(
$"Ring allocation of {byteCount} bytes at aligned offset {aligned} " +
$"needs {end} bytes; the ring slot is {_capacityBytes} bytes. " +
"Increase the per-slot ring capacity (GlGpuDevice's ringCapacityBytesPerSlot).");
}
_cursor = (uint)end;
if (byteCount > 0)
MarkDirty((int)aligned, (int)end);
return aligned;
}
/// <summary>Starts a new frame: rewinds the allocation cursor. Dirty state is untouched — a flush always runs before this is called.</summary>
public void Reset()
{
_cursor = 0;
_dirtyStart = -1;
_dirtyEnd = -1;
}
/// <summary>
/// Returns the byte range written since the last flush (start, length),
/// or (0, 0) when nothing is dirty, and clears the watermark.
/// </summary>
public (int Start, int Length) TakeDirtyRange()
{
if (_dirtyStart < 0)
return (0, 0);
(int start, int length) = (_dirtyStart, _dirtyEnd - _dirtyStart);
_dirtyStart = -1;
_dirtyEnd = -1;
return (start, length);
}
public bool HasDirtyBytes => _dirtyStart >= 0;
private void MarkDirty(int start, int end)
{
_dirtyStart = _dirtyStart < 0 ? start : Math.Min(_dirtyStart, start);
_dirtyEnd = Math.Max(_dirtyEnd, end);
}
internal static uint AlignUp(uint value, uint alignmentBytes) =>
alignmentBytes <= 1 ? value : (value + alignmentBytes - 1) / alignmentBytes * alignmentBytes;
}