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:
Erik 2026-07-27 18:22:08 +02:00
parent ec414d60cd
commit ceec3bc440
334 changed files with 3660 additions and 3840 deletions

View file

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using AcDream.Core.Combat;
using AcDream.Core.Items;
@ -8,7 +8,7 @@ using AcDream.Core.Selection;
namespace AcDream.App.UI.Layout;
/// <summary>
/// Binds the imported gmToolbarUI window (LayoutDesc 0x21000016) to live data
/// Binds the imported gmToolbarUI window (LayoutDesc 0x21000016) to live data —
/// the gm*UI::PostInit analogue. Finds the 18 shortcut slots (UiItemList) by id,
/// populates them from the persisted PlayerDescription shortcuts
/// (UpdateFromPlayerDesc), re-binds deferred slots when an item's CreateObject
@ -24,7 +24,7 @@ namespace AcDream.App.UI.Layout;
/// <c>CreateObject</c> resolves a formerly-unknown guid.
/// </para>
/// </summary>
public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelController
internal sealed class ToolbarController : IItemListDragHandler, IRetainedPanelController
{
// Slot element ids in slot-index order (toolbar LayoutDesc 0x21000016, pre-dump).
// Row 1 = slots 0-8 (0x100001A7..0x100001AF), Row 2 = slots 9-17 (0x100006B7..0x100006BF).
@ -39,7 +39,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
// SelectedObjectController owns the health/mana meters and both stack controls,
// including retail's initial-hidden state and selection-driven visibility.
// Four mutually-exclusive combat-mode indicator elements exactly one visible at a time.
// Four mutually-exclusive combat-mode indicator elements — exactly one visible at a time.
// Index 0 = NonCombat (peace), 1 = Melee, 2 = Missile, 3 = Magic.
// Retail ref: gmToolbarUI::RecvNotice_SetCombatMode (acclient_2013_pseudo_c.txt:196632-196669)
// SetVisible's exactly one element depending on the incoming mode.
@ -64,9 +64,9 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
private readonly ClientObjectTable _repo;
private readonly CombatState? _combatState;
private readonly ShortcutStore _store;
private readonly Func<ItemType, uint, uint, uint, uint, uint> _iconIds; // (itemType, icon, underlay, overlay, effects) → GL tex
private readonly Func<ItemType, uint, uint, uint, uint, uint>? _dragIconIds;
private readonly Action<uint> _useItem; // guid fire UseObject
private readonly Func<ItemType, uint, uint, uint, uint, GpuTextureSlot> _iconIds; // (itemType, icon, underlay, overlay, effects) → GL tex
private readonly Func<ItemType, uint, uint, uint, uint, GpuTextureSlot>? _dragIconIds;
private readonly Action<uint> _useItem; // guid → fire UseObject
private readonly Action<ShortcutEntry>? _sendAddShortcut;
private readonly Action<uint>? _sendRemoveShortcut; // (index)
private readonly ItemInteractionController? _itemInteraction;
@ -83,8 +83,8 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
// Retail ref: UIElement_UIItem::SetShortcutNum (acclient_2013_pseudo_c.txt:229465);
// gmToolbarUI::RecvNotice_SetCombatMode (196610-196621) re-stamps ghosting.
// Occupancy branch (decomp 229481):
// occupied regular 0x10000042 / ghosted 0x10000043
// empty background digit 0x1000005e (stance-independent)
// occupied → regular 0x10000042 / ghosted 0x10000043
// empty → background digit 0x1000005e (stance-independent)
private uint[]? _regularDigits;
private uint[]? _ghostedDigits;
private uint[]? _emptyDigits;
@ -94,7 +94,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
ImportedLayout layout,
ClientObjectTable repo,
ShortcutStore shortcuts,
Func<ItemType, uint, uint, uint, uint, uint> iconIds,
Func<ItemType, uint, uint, uint, uint, GpuTextureSlot> iconIds,
Action<uint> useItem,
CombatState? combatState,
uint[]? regularDigits,
@ -110,7 +110,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
Func<uint>? playerGuid = null,
Action<uint, uint, int>? sendPutItemInContainer = null,
UiDatFont? ammoFont = null,
Func<ItemType, uint, uint, uint, uint, uint>? dragIconIds = null)
Func<ItemType, uint, uint, uint, uint, GpuTextureSlot>? dragIconIds = null)
{
_repo = repo;
_combatState = combatState;
@ -193,7 +193,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
_examineButton.OnClick = () => _itemInteraction?.ExamineSelectedOrEnterMode(_selectedObjectId());
// Port of gmToolbarUI::RecvNotice_SetCombatMode (acclient_2013_pseudo_c.txt:196632-196669):
// exactly one indicator visible at a time. Default to NonCombat (peace) the player
// exactly one indicator visible at a time. Default to NonCombat (peace) — the player
// always spawns in peace mode; retail has not yet called SetVisible when PostInit runs.
SetCombatMode(CombatMode.NonCombat);
@ -204,7 +204,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
_selection.Changed += OnSelectionChanged;
// D.5.4: the table now holds ALL objects (creatures, NPCs, etc.), so filter
// to our 18 shortcut guids else every creature spawn in a busy zone
// to our 18 shortcut guids — else every creature spawn in a busy zone
// needlessly re-populates the bar (gmToolbarUI::SetDelayedShortcutNum pattern).
repo.ObjectAdded += OnRepositoryObjectChanged;
repo.ObjectUpdated += OnRepositoryObjectChanged;
@ -310,22 +310,22 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
/// if the shortcut list is refreshed outside the repo-event path.
/// </summary>
/// <param name="layout">Imported toolbar layout (LayoutDesc 0x21000016).</param>
/// <param name="repo">Live item repository must stay alive for the controller's lifetime.</param>
/// <param name="repo">Live item repository — must stay alive for the controller's lifetime.</param>
/// <param name="shortcuts">
/// Runtime-owned retail shortcut manager. The toolbar borrows this exact
/// mutable owner; it never reconstructs another slot map.
/// </param>
/// <param name="iconIds">Resolves (itemType, iconId, underlayId, overlayId, effects) GL texture handle.</param>
/// <param name="iconIds">Resolves (itemType, iconId, underlayId, overlayId, effects) → GL texture handle.</param>
/// <param name="useItem">Callback fired when a bound slot is clicked; receives the item guid.</param>
/// <param name="combatState">
/// Optional live combat state when provided, the toolbar subscribes to
/// Optional live combat state — when provided, the toolbar subscribes to
/// <see cref="CombatState.CombatModeChanged"/> and updates the four mutually-exclusive
/// combat-mode indicator elements accordingly.
/// Pass null to skip live wiring (e.g. in unit tests that don't exercise the indicator).
/// </param>
/// <param name="regularDigits">
/// Regular digit DID array (property 0x10000042 from LayoutDesc 0x21000037 element
/// 0x1000034A under composite 0x10000346). Index i slot label digit (i+1) RenderSurface id.
/// 0x1000034A under composite 0x10000346). Index i → slot label digit (i+1) RenderSurface id.
/// Null if the dat lookup failed (no digits drawn). Retail reference:
/// UIElement_UIItem::SetShortcutNum (acclient_2013_pseudo_c.txt:229465).
/// </param>
@ -333,14 +333,14 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
/// <param name="emptyDigits">
/// Empty-slot background digit DID array (property 0x1000005e, stance-independent).
/// Used when a slot is EMPTY (ItemId == 0). Retail ref: UIElement_UIItem::SetShortcutNum
/// (decomp 229481) else branch when m_elem_Icon->m_state == 0x1000001c (empty state).
/// (decomp 229481) — else branch when m_elem_Icon->m_state == 0x1000001c (empty state).
/// Null if the dat lookup failed (empty slots draw no digit, which is safe).
/// </param>
public static ToolbarController Bind(
ImportedLayout layout,
ClientObjectTable repo,
ShortcutStore shortcuts,
Func<ItemType, uint, uint, uint, uint, uint> iconIds,
Func<ItemType, uint, uint, uint, uint, GpuTextureSlot> iconIds,
Action<uint> useItem,
CombatState? combatState = null,
uint[]? regularDigits = null,
@ -356,7 +356,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
Func<uint>? playerGuid = null,
Action<uint, uint, int>? sendPutItemInContainer = null,
UiDatFont? ammoFont = null,
Func<ItemType, uint, uint, uint, uint, uint>? dragIconIds = null)
Func<ItemType, uint, uint, uint, uint, GpuTextureSlot>? dragIconIds = null)
{
var c = new ToolbarController(layout, repo, shortcuts, iconIds, useItem, combatState,
regularDigits, ghostedDigits, emptyDigits, itemInteraction,
@ -427,15 +427,15 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
if (list is null) continue;
var item = _repo.Get(guid);
if (item is null) continue; // deferred: ObjectAdded re-calls Populate
uint tex = _iconIds(item.Type, item.IconId, item.IconUnderlayId, item.IconOverlayId, item.Effects);
uint dragTex = _dragIconIds?.Invoke(
item.Type, item.IconId, item.IconUnderlayId, item.IconOverlayId, item.Effects) ?? 0u;
GpuTextureSlot tex = _iconIds(item.Type, item.IconId, item.IconUnderlayId, item.IconOverlayId, item.Effects);
GpuTextureSlot? dragTex = _dragIconIds?.Invoke(
item.Type, item.IconId, item.IconUnderlayId, item.IconOverlayId, item.Effects);
list.Cell.SetItem(guid, tex, entry, dragTex);
}
// Re-stamp slot number labels after any item change.
// Digit SPRITE SOURCE depends on occupancy (decomp UIElement_UIItem::SetShortcutNum:229481):
// occupied → regular 0x10000042 / ghosted 0x10000043; empty → background 0x1000005e.
// occupied → regular 0x10000042 / ghosted 0x10000043; empty → background 0x1000005e.
// The digit is ALWAYS shown on top-row slots (SetVisible(1) at decomp 229511).
RestampShortcutNumbers();
}
@ -450,7 +450,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
/// </summary>
public void SetCombatMode(CombatMode mode)
{
// Index mode mapping matches CombatIndicatorIds declaration order:
// Index → mode mapping matches CombatIndicatorIds declaration order:
// 0 = NonCombat (peace), 1 = Melee, 2 = Missile, 3 = Magic.
bool[] show =
{
@ -475,14 +475,14 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
/// <summary>
/// Push digit-array references and shortcut-number state into every slot cell.
/// Top row (indices 08): SetShortcutNum(i, _shortcutsGhosted) — numbers 19 always shown
/// Top row (indices 0–8): SetShortcutNum(i, _shortcutsGhosted) — numbers 1–9 always shown
/// (the digit is ALWAYS visible, SetVisible(1) at decomp 229511; only the sprite
/// SOURCE differs by occupancy see UIElement_UIItem::SetShortcutNum decomp 229481).
/// Bottom row (indices 917): ClearShortcutNum() — retail shows no numbers there.
/// SOURCE differs by occupancy — see UIElement_UIItem::SetShortcutNum decomp 229481).
/// Bottom row (indices 9–17): ClearShortcutNum() — retail shows no numbers there.
/// Retail ref: UIElement_UIItem::SetShortcutNum (acclient_2013_pseudo_c.txt:229465);
/// gmToolbarUI::RecvNotice_SetCombatMode (196610-196621).
/// Occupancy → source: occupied → regular 0x10000042 / ghosted 0x10000043;
/// empty background 0x1000005e (decomp 229481/229493).
/// Occupancy → source: occupied → regular 0x10000042 / ghosted 0x10000043;
/// empty → background 0x1000005e (decomp 229481/229493).
/// </summary>
private void RestampShortcutNumbers()
{
@ -494,7 +494,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
cell.GhostedDigits = _ghostedDigits;
cell.EmptyDigits = _emptyDigits;
if (i < 9)
cell.SetShortcutNum(i, _shortcutsGhosted); // top row: slot labels 19 always shown
cell.SetShortcutNum(i, _shortcutsGhosted); // top row: slot labels 1–9 always shown
else
cell.ClearShortcutNum(); // bottom row: no slot labels
}
@ -503,7 +503,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
/// <summary>
/// Wire the <see cref="UiItemSlot.Clicked"/> callback on a slot cell so that
/// clicking a bound item fires <see cref="_useItem"/> with the slot's current guid.
/// Mirrors retail's <c>gmToolbarUI</c> click <c>UseShortcut</c> dispatch.
/// Mirrors retail's <c>gmToolbarUI</c> click → <c>UseShortcut</c> dispatch.
/// </summary>
private void WireClick(UiItemList list)
{
@ -662,12 +662,12 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
return true;
}
// ── IItemListDragHandler (B.2 live handler) ──────────────────────────────
// ── IItemListDragHandler (B.2 live handler) ──────────────────────────────
// Retail: gmToolbarUI is the m_dragHandler for every shortcut slot list.
// Retail model (remove-on-lift / place-on-drop / no-restore):
// lift RemoveShortcut (0x019D) + store.Remove (slot empties immediately)
// drop AddShortcut (0x019C) + optional swap of evicted item into source
// off-bar release the lift's removal stands (no restore)
// lift → RemoveShortcut (0x019D) + store.Remove (slot empties immediately)
// drop → AddShortcut (0x019C) + optional swap of evicted item into source
// off-bar release → the lift's removal stands (no restore)
// Retail ref: gmToolbarUI::HandleDropRelease acclient_2013_pseudo_c.txt:197971
/// <inheritdoc/>
@ -678,7 +678,7 @@ public sealed class ToolbarController : IItemListDragHandler, IRetainedPanelCont
if (payload.ObjId != 0 && _selectedObjectId() != payload.ObjId)
_selectItem?.Invoke(payload.ObjId);
// Retail RecvNotice_ItemListBeginDrag RemoveShortcut (0x004bd930/0x004bd450): the lifted
// Retail RecvNotice_ItemListBeginDrag → RemoveShortcut (0x004bd930/0x004bd450): the lifted
// shortcut leaves the bar (+ wire) the instant the drag starts; it's re-placed only on a
// drop onto a slot. Off-bar release leaves it removed.
_sendRemoveShortcut?.Invoke((uint)payload.SourceSlot);