acdream/tests/AcDream.App.Tests/Rendering/TerrainAtlasDetailTextureTests.cs
Erik ae6513126e fix(render): detail overlay is fogged after the combine like retail; VM1 review fixes
Opus dual-lens review of 05970306 + 388457a7 (APPROVE WITH FIXES). Four
items, all landed:

1. FOG (behavioural). Retail's D3D fixed-function fog stage runs AFTER the
   texture-stage pipeline, so the detail contribution must be fogged, not
   just the base. mesh_modern.frag already fogs the base colour
   (applyFog(rgb, vWorldPos)) before mesh_detail's replay draws over it;
   mesh_detail.frag previously emitted raw detail.rgb, understating fog by
   f*a*(fog-detail). Fix: mesh_detail.vert now outputs vWorldPos (mirroring
   mesh_modern.vert); mesh_detail.frag declares the identical SceneLighting
   UBO and applyFog function (copied verbatim, same binding/std140/math) and
   fogs detail.rgb before emitting it. This collapses algebraically to
   retail's fog-after-combine order:
     (1-a)*mix(base,fog,f) + a*mix(detail,fog,f) = mix(lerp(base,detail,a),fog,f)
   RetailDetailTextureContract gains ExpectedFogged(base,detail,opacity,fog,
   fogFactor); RetailDetailTextureContractTests pins the identity across 200
   random samples within 1e-6.

2. EnvCellRenderer.Rhi.cs's DrawEnvCell-category comment still said "apply
   the 10-50 m positive-view-depth fade" — a stale claim from before VM1
   removed the fade. Replaced with the mip-chain attenuation statement that
   mesh_detail.vert's header comment already carries.

3. Added the test the VM1 contract required but never had: TerrainAtlas
   .TryCreateDetailTexture uploads a full mip chain (MipLevelCount ==
   RhiWorldTextureArray.MipLevelsFor(w,h), GenerateMipChain called) and
   registers with the repeat/linear world sampler, not single-level or
   clamped. Drives the private method directly (reflection) against a
   synthetic PFID_A8R8G8B8 RenderSurface through a minimal in-memory
   IDatReaderWriter fake, so the lane stays hermetic (no installed DAT).

4. #226 pseudocode note: noted that retail's stage-1 OUTPUT alpha
   (MODULATE(TEXTURE, CURRENT), 0x0059c549) — the framebuffer blend weight a
   delayed-alpha subset composites with — is not modelled; acdream instead
   draws a second pass weighted by detail.a*diffuseAlpha. Identical for
   opaque subsets, a bounded difference on translucent building/EnvCell
   subsets already covered by the existing AP-34 shared-alpha-queue
   divergence row. Also qualified the tmpmaterial.Diffuse.a = 1f (0x0059cb99)
   citation to name its exact branch (burnedInStaticLights < 0 &&
   *(render_device+0x7e4) == 0); the other branch leaves diffuse FromVertex,
   but the opaque->1 / fading->opacity mapping still holds either way.

Nit also folded in: EnvCellRendererTests' new SubmitRhi instance-alpha test
is now a [Theory] over WbRenderPass.Opaque and .Transparent, pinning the
bind-before-first-draw invariant on both passes.

Regenerated mesh_detail's committed SPIR-V and the shader manifest
(tools/compile-shaders.ps1); no other shader pair changed.

Verified: dotnet build AcDream.slnx -c Release (0 warnings, 0 errors);
dotnet test on AcDream.App.Tests (Release, hermetic lanes) green, including
the shader manifest tests explicitly; AcDream.Core.Tests unaffected/green.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 22:39:58 +02:00

173 lines
6.9 KiB
C#

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using AcDream.App.Rendering;
using AcDream.App.Rendering.Gpu;
using AcDream.App.Rendering.Wb;
using AcDream.App.Tests.Rendering.Gpu;
using AcDream.Content;
using DatReaderWriter;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Enums;
using DatReaderWriter.Lib.IO;
using DatReaderWriter.Types;
using Xunit;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Campaign VM VM1 review fix: pins the two facts the #226 note relies on
/// for retail's mip-driven attenuation to actually be true — <c>TerrainAtlas
/// .TryCreateDetailTexture</c> (~TerrainAtlas.cs:488-556) must upload a FULL
/// mip chain, and it must be sampled with the repeat/linear world sampler,
/// or the "attenuation is the sampler's linear mip chain" claim in
/// mesh_detail.vert's header comment and the VM1 commit is unverified.
/// Drives the private method directly (reflection, same pattern as
/// EnvCellRendererTests' private-method tests) against a synthetic
/// PFID_A8R8G8B8 RenderSurface, so no installed DAT is required — this lane
/// stays hermetic.
/// </summary>
public sealed class TerrainAtlasDetailTextureTests
{
private const uint SurfaceTextureId = 0x05001787u;
private const uint RenderSurfaceId = 0x06006D58u;
[Fact]
public void DetailTexture_UploadsFullMipChainAndUsesRepeatLinearSampler()
{
const int width = 4;
const int height = 4;
using var device = new RecordingGpuDevice();
device.Clear();
var dats = new FakeDetailTextureDats();
dats.Register(new SurfaceTexture
{
Textures = new List<QualifiedDataId<RenderSurface>> { RenderSurfaceId },
}, SurfaceTextureId);
dats.Register(new RenderSurface
{
Width = width,
Height = height,
Format = PixelFormat.PFID_A8R8G8B8,
SourceData = new byte[width * height * 4],
}, RenderSurfaceId);
var terrain = new TMTerrainDesc
{
TerrainTex = new TerrainTex
{
DetailTextureId = SurfaceTextureId,
DetailTexTiling = 4u,
},
};
IGpuSampler sampler = device.CreateSampler(GpuSamplerDescription.WorldRepeat);
MethodInfo method = typeof(TerrainAtlas).GetMethod(
"TryCreateDetailTexture",
BindingFlags.NonPublic | BindingFlags.Static)!;
object? result = method.Invoke(
null,
new object[] { device, dats, sampler, terrain, "building" });
Assert.NotNull(result);
// Full mip chain: TerrainAtlas.cs sizes MipLevelCount from
// RhiWorldTextureArray.MipLevelsFor(decoded.Width, decoded.Height) and
// then calls GenerateMipChain() — not a single-level upload.
RecordingGpuTexture texture = Assert.Single(device.CreatedTextures);
Assert.Equal(width, texture.Width);
Assert.Equal(height, texture.Height);
int expectedMipLevels = RhiWorldTextureArray.MipLevelsFor(width, height);
Assert.True(expectedMipLevels > 1, "the test fixture must exercise a real mip chain, not a 1x1 edge case");
Assert.Equal(expectedMipLevels, texture.MipLevelCount);
Assert.True(texture.MipChainGenerated);
// Repeat/linear sampler: the exact sampler GpuBindingModel world
// draws use, not WorldClamp (the alpha atlas' sampler) or any
// point-filtered UI sampler.
GpuRecordedTextureRegistration registration = Assert.Single(
device.Calls.OfType<GpuRecordedTextureRegistration>());
Assert.Equal(GpuSamplerDescription.WorldRepeat, registration.Sampler);
Assert.Equal(GpuFilter.Linear, registration.Sampler.MinFilter);
Assert.Equal(GpuFilter.Linear, registration.Sampler.MagFilter);
Assert.Equal(GpuMipFilter.Linear, registration.Sampler.MipFilter);
Assert.Equal(GpuAddressMode.Repeat, registration.Sampler.AddressU);
Assert.Equal(GpuAddressMode.Repeat, registration.Sampler.AddressV);
}
/// <summary>
/// Minimal synthetic <see cref="IDatReaderWriter"/> — same shape as the
/// NoopDatReaderWriter pattern already used for hermetic tests
/// (LiveEntityNetworkOnPositionCollapseMatrixTests), except <c>Get</c>
/// resolves from an explicit id-&gt;object map instead of always missing.
/// Every other member is unreachable by TryCreateDetailTexture and throws
/// if that assumption ever changes.
/// </summary>
private sealed class FakeDetailTextureDats : IDatReaderWriter
{
private readonly Dictionary<uint, IDBObj> _objects = new();
public void Register<T>(T obj, uint id) where T : IDBObj => _objects[id] = obj;
public string SourceDirectory => string.Empty;
public IDatDatabase Portal => throw new NotSupportedException();
public IDatDatabase Cell => throw new NotSupportedException();
public ReadOnlyDictionary<uint, IDatDatabase> CellRegions { get; } =
new(new Dictionary<uint, IDatDatabase>());
public IDatDatabase HighRes => throw new NotSupportedException();
public IDatDatabase Language => throw new NotSupportedException();
public IDatDatabase Local => throw new NotSupportedException();
public ReadOnlyDictionary<uint, uint> RegionFileMap { get; } =
new(new Dictionary<uint, uint>());
public int PortalIteration => 0;
public int CellIteration => 0;
public int HighResIteration => 0;
public int LanguageIteration => 0;
public bool TryGetFileBytes(
uint regionId,
uint fileId,
ref byte[] bytes,
out int bytesRead)
{
bytesRead = 0;
return false;
}
public IEnumerable<uint> GetAllIdsOfType<T>() where T : IDBObj =>
Array.Empty<uint>();
public IEnumerable<IDatReaderWriter.IdResolution> ResolveId(uint id) =>
Array.Empty<IDatReaderWriter.IdResolution>();
public bool TrySave<T>(T obj, int iteration = 0) where T : IDBObj =>
throw new NotSupportedException();
public bool TrySave<T>(uint regionId, T obj, int iteration = 0) where T : IDBObj =>
throw new NotSupportedException();
[return: MaybeNull]
public T Get<T>(uint fileId) where T : IDBObj =>
_objects.TryGetValue(fileId, out IDBObj? obj) && obj is T typed ? typed : default;
public bool TryGet<T>(uint fileId, [MaybeNullWhen(false)] out T value) where T : IDBObj
{
if (_objects.TryGetValue(fileId, out IDBObj? obj) && obj is T typed)
{
value = typed;
return true;
}
value = default;
return false;
}
public void Dispose()
{
}
}
}