acdream/src/AcDream.App/Rendering/Wb/BuildingLoader.cs
Erik 9aaf97e785 Revert "Campaign V slice V4a" - it lost world multisampling
This reverts ceec3bc4. Two independent reasons, either sufficient.

The rendering regression. The slice deleted TextRenderGlStateScope, which
saved GL_MULTISAMPLE and GL_SAMPLE_ALPHA_TO_COVERAGE on entry, disabled them
for the text pass, and restored them on exit (TextRenderGlStateScope.cs:111-112
and 153-154 at the parent commit). Its replacement bakes that state into the
text pipeline but nothing restores it, and GlGpuPassEncoder.Dispose does not
either. Every world renderer is still raw GL at this point in the campaign, so
from the first UI frame onward the world drew with multisampling disabled.

The offline pixel gate caught it: 1,791 of 563,200 compared pixels differed,
0.318% against a 0.001 threshold. The commit message attributed this to
wall-clock-driven ambient animation shifting phase, and committed through the
failure. That explanation does not survive its own control: capturing twice at
the reverted-to commit differs by 19 pixels and twice at the slice's own commit
by 8, while base-versus-head differs by 1,791 - a 224x gap that no shared-noise
source explains. An amplified difference image settles it visually: the changed
pixels are the silhouette edges of every tree, building and rock, with terrain
interiors, water and the entire UI untouched. That is the signature of losing
edge antialiasing, not of animated sprites.

This is the exact failure mode two existing memory notes already warn about -
a mid-frame renderer must set every GL state it uses rather than inherit it,
and issue #52's lesson that a rendering migration must audit per-pass GL state
before declaring itself done.

The scope. The brief was three small leaf renderers plus additive frame-
lifecycle wiring, roughly ten files. The commit changed 334 files with 3,665
insertions and 3,845 deletions, including 323 public-to-internal visibility
conversions across the App assembly, 55 test files, two retired conformance
tests, and a self-described temporary escape hatch for bridging raw-GL viewport
textures. Even without the regression, that is not separable into the part
worth keeping and the part worth dropping.

Reverting rather than patching because the good work here - the RHI frame
lifecycle wiring and a genuine render-state-cache staleness fix - is small
enough to redo cleanly against a tightened spec, while untangling it from 300+
files of unrelated churn is not.

Post-revert: Release build clean, App suite back to 3,843 passed / 3 skipped,
offline pixel gate passing at 19 differing pixels.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 18:29:28 +02:00

230 lines
8.5 KiB
C#

using System.Collections.Generic;
using System.Numerics;
using AcDream.App.Rendering;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Types;
namespace AcDream.App.Rendering.Wb;
/// <summary>
/// Phase A8 (2026-05-26): static factory that builds a per-landblock
/// <see cref="BuildingRegistry"/> from a <see cref="LandBlockInfo"/>'s
/// <c>Buildings</c> array.
///
/// <para>Algorithm (mirrors WB's <c>PortalService.GetPortalsByBuilding</c> at
/// <c>WorldBuilder.Shared/Services/PortalService.cs:43-97</c>):</para>
/// <list type="bullet">
/// <item>Step A — seed the cell set from <c>BuildingInfo.Portals</c> entry portals.</item>
/// <item>Step B — BFS through <see cref="LoadedCell.Portals"/> to discover all
/// interior cells reachable from the entry portals (interior portals only;
/// exit portals — <c>OtherCellId == 0xFFFF</c> — terminate each BFS branch).</item>
/// <item>Step C — collect exit portal polygons in world space for the stencil
/// pipeline (Phase A8 Steps 1+2, RR7 scope).</item>
/// </list>
///
/// <para>Cells whose <c>LoadedCell</c> entries are missing from
/// <paramref name="cellsByCellId"/> are silently skipped (BFS bails at the
/// unloaded cell). In production, streaming loads all cells for a landblock
/// before <see cref="Build"/> runs, so the dict is always complete.</para>
///
/// <para><c>LoadedCell.BuildingId</c> is stamped here in RR4 after <c>reg.Add(building)</c>.</para>
///
/// <para>Retail references:
/// <c>docs/research/named-retail/acclient.h:32035</c> (<c>BuildInfo</c>) and
/// <c>:32094</c> (<c>CBldPortal</c>).</para>
/// </summary>
internal sealed class BuildingRegistryPublication
{
internal BuildingRegistryPublication(
BuildingInfo[] buildings,
uint landblockId,
IReadOnlyDictionary<uint, LoadedCell> cellsByCellId)
{
Buildings = buildings;
LandblockId = landblockId;
CellsByCellId = cellsByCellId;
PreparationCommitted = buildings.Length == 0;
}
internal BuildingInfo[] Buildings { get; }
internal uint LandblockId { get; }
internal IReadOnlyDictionary<uint, LoadedCell> CellsByCellId { get; }
internal BuildingRegistry Registry { get; } = new();
internal List<(LoadedCell Cell, uint BuildingId)> CellStamps { get; } = new();
internal int BuildingCursor { get; set; }
internal uint NextBuildingId { get; set; } = 1;
internal bool PreparationCommitted { get; set; }
internal bool PublicationCommitted { get; set; }
}
public static class BuildingLoader
{
/// <summary>
/// Builds a <see cref="BuildingRegistry"/> from the supplied landblock data.
/// Building IDs are allocated sequentially starting at 1 (0 is reserved for
/// "no building" semantics used by <c>LoadedCell.BuildingId</c> in RR4).
/// </summary>
public static BuildingRegistry Build(
LandBlockInfo info,
uint landblockId,
IReadOnlyDictionary<uint, LoadedCell> cellsByCellId)
{
BuildingRegistryPublication publication = PreparePublication(
info,
landblockId,
cellsByCellId);
while (!AdvancePreparationOne(publication))
{
}
CommitPublication(publication);
return publication.Registry;
}
internal static BuildingRegistryPublication PreparePublication(
LandBlockInfo info,
uint landblockId,
IReadOnlyDictionary<uint, LoadedCell> cellsByCellId)
{
ArgumentNullException.ThrowIfNull(info);
ArgumentNullException.ThrowIfNull(cellsByCellId);
int buildingCount = info.Buildings?.Count ?? 0;
var buildings = new BuildingInfo[buildingCount];
for (int index = 0; index < buildingCount; index++)
buildings[index] = info.Buildings![index];
return new BuildingRegistryPublication(
buildings,
landblockId,
cellsByCellId);
}
internal static bool AdvancePreparationOne(
BuildingRegistryPublication publication)
{
ArgumentNullException.ThrowIfNull(publication);
if (publication.PreparationCommitted)
return true;
if (publication.BuildingCursor >= publication.Buildings.Length)
{
publication.PreparationCommitted = true;
return true;
}
AddBuilding(
publication,
publication.Buildings[publication.BuildingCursor]);
publication.BuildingCursor++;
if (publication.BuildingCursor >= publication.Buildings.Length)
publication.PreparationCommitted = true;
return publication.PreparationCommitted;
}
internal static void CommitPublication(
BuildingRegistryPublication publication)
{
ArgumentNullException.ThrowIfNull(publication);
if (!publication.PreparationCommitted)
{
throw new InvalidOperationException(
"A building registry cannot publish before preparation completes.");
}
if (publication.PublicationCommitted)
return;
foreach ((LoadedCell cell, uint buildingId) in publication.CellStamps)
cell.BuildingId = buildingId;
publication.PublicationCommitted = true;
}
private static void AddBuilding(
BuildingRegistryPublication publication,
BuildingInfo bInfo)
{
uint lbMask = publication.LandblockId & 0xFFFF0000u;
var envCellIds = new HashSet<uint>();
var exitPortalPolys = new List<Vector3[]>();
// Step A: seed the cell set from BuildingInfo.Portals.
if (bInfo.Portals is not null)
{
foreach (var portal in bInfo.Portals)
{
if (portal.OtherCellId == 0xFFFF) continue;
envCellIds.Add(lbMask | portal.OtherCellId);
}
}
// Step B: BFS through interior portals.
var queue = new Queue<uint>(envCellIds);
while (queue.Count > 0)
{
uint current = queue.Dequeue();
if (!publication.CellsByCellId.TryGetValue(current, out var cell))
continue;
foreach (var portal in cell.Portals)
{
if (portal.OtherCellId == 0xFFFF) continue;
uint neighbourId = lbMask | portal.OtherCellId;
if (envCellIds.Add(neighbourId))
queue.Enqueue(neighbourId);
}
}
// Step C: collect exit portal polygons in world space.
foreach (uint cellId in envCellIds)
{
if (!publication.CellsByCellId.TryGetValue(cellId, out var cell))
continue;
for (int portalIndex = 0; portalIndex < cell.Portals.Count; portalIndex++)
{
if (cell.Portals[portalIndex].OtherCellId != 0xFFFF) continue;
if (portalIndex >= cell.PortalPolygons.Count) continue;
Vector3[] localPolygon = cell.PortalPolygons[portalIndex];
if (localPolygon.Length < 3) continue;
var worldPolygon = new Vector3[localPolygon.Length];
for (int vertexIndex = 0; vertexIndex < localPolygon.Length; vertexIndex++)
{
worldPolygon[vertexIndex] = Vector3.Transform(
localPolygon[vertexIndex],
cell.WorldTransform);
}
exitPortalPolys.Add(worldPolygon);
}
}
bool hasPortalBounds = false;
var portalMin = new Vector3(float.MaxValue);
var portalMax = new Vector3(float.MinValue);
foreach (Vector3[] polygon in exitPortalPolys)
{
foreach (Vector3 vertex in polygon)
{
hasPortalBounds = true;
portalMin = Vector3.Min(portalMin, vertex);
portalMax = Vector3.Max(portalMax, vertex);
}
}
if (envCellIds.Count == 0)
return;
uint buildingId = publication.NextBuildingId++;
publication.Registry.Add(new Building
{
BuildingId = buildingId,
EnvCellIds = envCellIds,
ExitPortalPolygons = exitPortalPolys,
HasPortalBounds = hasPortalBounds,
PortalBounds = hasPortalBounds
? new WbBoundingBox(portalMin, portalMax)
: default,
});
// Stamps remain off-side until the complete registry commits.
foreach (uint cellId in envCellIds)
{
if (publication.CellsByCellId.TryGetValue(cellId, out var cell))
publication.CellStamps.Add((cell, buildingId));
}
}
}