acdream/tests/AcDream.App.Tests/Rendering/ChargenPreviewEntityBuilderTests.cs
Erik 8dfee1118f feat(chargen): Campaign CC slice CC6b-PRE — idle loop, rotation, zoom (mount-independent half)
Idle animation loop: decomp re-read of gmCGAppearancePage::Update's trailing
StartAnimation/StopAnimation gate (~0x0047EF01-0x0047EF12) plus the ctor
evidence that m_bZoomedIn is a decompiler-elided bool (never explicitly set
away from its zero default, unlike its two sibling bools) establishes that
retail's chargen preview defaults to the idle loop PLAYING, not the frozen
rest pose CC6a shipped as a deliberate simplification (TS-83) — the rest pose
only appears once Zoom In fires. New Core primitive
RetailAnimationCyclePlayback ports CPhysicsObj::set_sequence_animation's
advance-with-wrap + lerp/slerp effect (the same algorithm
LiveEntityAnimationPresenter's legacy NPC-idle branch already carries inline;
not consolidated this round — out of blast radius for a preview-only
feature, noted in the new type's own doc). New ChargenPreviewAnimator drives
the per-tick swap; ChargenPreviewEntityBuilder gained TryBuildAnimated
alongside the byte-behavior-unchanged TryBuild. Olthoi/OlthoiAcid use the
SAME enum key for idle and rest DIDs (decomp-confirmed quirk). TS-83 retired
in the register (§4 count 50->49).

Rotation controller: ChargenPreviewRotationController ports
Rotate/DoRotation (0x0047CB50/0x0047CA80) verbatim — toggle-to-stop,
deltaDegrees = ((now-last)/RotationSecondsPerRevolution)*360, single-pass
+-360 clamp (not a full modulo, matching retail's own tail), the -1.0
invalidation sentinel. Applies to the entity's heading via the existing
MoveToMath.SetHeading port, not the camera, confirming CC6a's own note.

Zoom tween: ChargenPreviewZoomController ports ZoomIn/ZoomOut/
DoZoomAnimation (0x0047CF00/0x0047D050/0x0047C960) — a LINEAR 0.6s tween
(no easing curve in the decomp) between the already-recorded camera eye
profiles, calling into the animator's zoom swap IMMEDIATELY at button-press
time, matching retail's call order exactly.

m_alternateSetupID (research correction): re-reading the decomp
function-by-function found all five m_alternateSetupID write sites —
including the two the CC6a review cited — belong to gmBarberUI (the
post-creation barber shop), not gmCGAppearancePage, which has no
m_pOption1Checkbox-equivalent field and never writes the field. For
character creation the field is always INVALID_DID in retail. TryCompose
still gained a real, decomp-cited alternateSetupIdOverride parameter
(default no-op) implementing gmCG3DView::Update's generic override
precedence, for a future non-chargen consumer.

RetailHeldPose extraction: shared ResolvePoseDid/ComposePartTransform
between RetailPaperdollPoseApplicator and ChargenPreviewEntityBuilder — a
clean mechanical extraction, behavior-identical on the paperdoll side.

Bookkeeping: CC6a ledger row now cites its real commit SHAs (55bfd9ca,
1774d8b2); new CC6b-PRE ledger row records scope done + the page-mount half
still owed.

Tests: RetailAnimationCyclePlaybackTests (10, Core), ChargenAppearanceFactoryTests
(+4), ChargenPreviewRotationControllerTests (9), ChargenPreviewZoomControllerTests
(7), ChargenPreviewAnimatorTests (7, hand-built fixtures), ChargenPreviewEntityBuilderTests
(+5, installed-DAT). Core.Tests 4786/1 skip, Content.Tests 147/0, App.Tests
5149/6 skips — zero failures, full solution Release build green. One
pre-existing, unrelated flake noted: Core.Net.Tests' NakEmissionTests loss
soak failed once in the full-suite run, passed 1/1 isolated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 19:05:56 +02:00

278 lines
13 KiB
C#

using System.Linq;
using System.Numerics;
using AcDream.App.Rendering;
using AcDream.Content;
using AcDream.Content.CharGen;
using AcDream.Content.Vfx;
using AcDream.Core.CharGen;
using DatReaderWriter;
using DatReaderWriter.Options;
using Xunit;
using Xunit.Abstractions;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Installed-DAT gate for <see cref="ChargenPreviewEntityBuilder"/> —
/// mirrors <see cref="CornerFloodReplayTests"/>'s env-gated skip pattern
/// (no unit-testable pure surface exists here the way
/// <see cref="DollEntityBuilder"/> has one, because THIS builder's whole job
/// is resolving Setup/GfxObj/Surface/Animation dat data that
/// <see cref="DollEntityBuilder"/> receives pre-resolved).
/// </summary>
public sealed class ChargenPreviewEntityBuilderTests
{
private readonly ITestOutputHelper _out;
public ChargenPreviewEntityBuilderTests(ITestOutputHelper output) => _out = output;
[Fact]
public void TryBuild_AluvianMaleDefaultSelection_ProducesANonEmptyStaticPoseEntity()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.True(options.TryGetHeritage(1u, out ChargenHeritageOptions? aluvian)); // Aluvian.
Assert.True(aluvian!.GendersByKey.TryGetValue(1, out ChargenGenderOptions? male));
var catalog = new ChargenAppearanceCatalog(adapter);
ChargenAppearanceSelection selection = ChargenAppearanceSelection.Default with
{
HairStyle = male!.HairStyles.Count > 0 ? 0u : ChargenAppearanceSelection.Unset,
SkinShade = 0.5,
};
bool composed = ChargenAppearanceFactory.TryCompose(
options, 1u, 1, selection, catalog, catalog, out ChargenAppearanceResult appearance);
Assert.True(composed);
Assert.Empty(appearance.MissingPalSetIds);
Assert.Empty(appearance.MissingClothingTableIds);
var animations = new RetailAnimationLoader(adapter);
var entity = ChargenPreviewEntityBuilder.TryBuild(
adapter, animations, appearance, heritageId: 1u, Quaternion.Identity, new object());
Assert.NotNull(entity);
Assert.NotEmpty(entity!.MeshRefs);
Assert.Equal(appearance.SetupId, entity.SourceGfxObjOrSetupId);
Assert.Equal(ChargenPreviewEntityBuilder.PreviewServerGuid, entity.ServerGuid);
Assert.Equal(ChargenPreviewEntityBuilder.PreviewRenderId, entity.Id);
Assert.NotNull(entity.PaletteOverride);
Assert.Equal(appearance.BasePaletteId, entity.PaletteOverride!.BasePaletteId);
_out.WriteLine($"setup=0x{appearance.SetupId:X8} meshRefs={entity.MeshRefs.Count} subPalettes={entity.PaletteOverride.SubPalettes.Count}");
}
[Fact]
public void TryBuild_UnknownSetupId_ReturnsNull()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
var animations = new RetailAnimationLoader(adapter);
var bogusAppearance = new ChargenAppearanceResult(
SetupId: 0x0200_FFFFu, // Not a real installed Setup id.
BasePaletteId: 0u,
ObjDesc: ChargenObjDesc.Empty,
MissingPalSetIds: [],
MissingClothingTableIds: [],
ClothingTablesMissingBaseEffectForSetup: []);
var entity = ChargenPreviewEntityBuilder.TryBuild(
adapter, animations, bogusAppearance, heritageId: 1u, Quaternion.Identity, new object());
Assert.Null(entity);
}
[Fact]
public void TryBuild_OlthoiHeritage_ResolvesADifferentRestPoseDidThanStandardHeritages()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.True(options.TryGetHeritage(12u, out ChargenHeritageOptions? olthoi)); // Olthoi.
Assert.True(olthoi!.GendersByKey.TryGetValue(1, out ChargenGenderOptions? male)
|| olthoi.GendersByKey.TryGetValue(2, out male));
Assert.NotNull(male);
int genderKey = olthoi.GendersByKey.First(kv => ReferenceEquals(kv.Value, male)).Key;
var catalog = new ChargenAppearanceCatalog(adapter);
var animations = new RetailAnimationLoader(adapter);
bool composed = ChargenAppearanceFactory.TryCompose(
options, 12u, genderKey, ChargenAppearanceSelection.Default with { SkinShade = 0.5 },
catalog, catalog, out ChargenAppearanceResult appearance);
Assert.True(composed);
var entity = ChargenPreviewEntityBuilder.TryBuild(
adapter, animations, appearance, heritageId: 12u, Quaternion.Identity, new object());
// Just proves the Olthoi branch doesn't throw / silently fall through to
// "no mesh" — the exact pose DID differs internally (0x10000011 vs
// 0x10000005) but both should still resolve a drawable mesh from Olthoi's
// own Setup.
Assert.NotNull(entity);
Assert.NotEmpty(entity!.MeshRefs);
}
/// <summary>
/// CC6b: <c>TryBuildAnimated</c> resolves a real idle Animation (retail's
/// <c>m_didAnimation</c>) against the installed EoR dat, with a usable
/// frame range and a non-empty drawable-part list a
/// <c>ChargenPreviewAnimator</c> can drive.
/// </summary>
[Fact]
public void TryBuildAnimated_AluvianMaleDefaultSelection_ResolvesARealIdleCycle()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.True(options.TryGetHeritage(1u, out ChargenHeritageOptions? aluvian));
Assert.True(aluvian!.GendersByKey.TryGetValue(1, out ChargenGenderOptions? male));
var catalog = new ChargenAppearanceCatalog(adapter);
ChargenAppearanceSelection selection = ChargenAppearanceSelection.Default with
{
HairStyle = male!.HairStyles.Count > 0 ? 0u : ChargenAppearanceSelection.Unset,
SkinShade = 0.5,
};
bool composed = ChargenAppearanceFactory.TryCompose(
options, 1u, 1, selection, catalog, catalog, out ChargenAppearanceResult appearance);
Assert.True(composed);
var animations = new RetailAnimationLoader(adapter);
ChargenPreviewAnimatedBuild? build = ChargenPreviewEntityBuilder.TryBuildAnimated(
adapter, animations, appearance, heritageId: 1u, Quaternion.Identity, new object());
Assert.NotNull(build);
Assert.NotEmpty(build!.DrawableParts);
Assert.NotEmpty(build.RestMeshRefs);
Assert.NotNull(build.IdleAnimation);
Assert.True(build.IdleHighFrame >= build.IdleLowFrame);
Assert.True(build.IdleAnimation!.PartFrames.Count > build.IdleHighFrame);
// Live end-to-end: an Animator built from this resolves a non-empty,
// playable preview — retail's true default (idle playing), not the
// frozen rest pose TryBuild alone still returns.
var animator = new ChargenPreviewAnimator(build);
Assert.False(animator.IsZoomedIn);
Assert.NotEmpty(animator.Entity.MeshRefs);
animator.Tick(1f / 30f); // one frame's worth — must not throw or empty the mesh.
Assert.NotEmpty(animator.Entity.MeshRefs);
}
[Fact]
public void TryBuildAnimated_UnknownSetupId_ReturnsNull()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
var animations = new RetailAnimationLoader(adapter);
var bogusAppearance = new ChargenAppearanceResult(
SetupId: 0x0200_FFFFu,
BasePaletteId: 0u,
ObjDesc: ChargenObjDesc.Empty,
MissingPalSetIds: [],
MissingClothingTableIds: [],
ClothingTablesMissingBaseEffectForSetup: []);
ChargenPreviewAnimatedBuild? build = ChargenPreviewEntityBuilder.TryBuildAnimated(
adapter, animations, bogusAppearance, heritageId: 1u, Quaternion.Identity, new object());
Assert.Null(build);
}
/// <summary>
/// Decomp-verified quirk (<c>gmCG3DView</c>'s ctor / <c>::Update</c>,
/// pseudo-C ~0x004ee7e9/0x004ee7ff and ~0x004ee892/0x004ee8a8): Olthoi
/// and OlthoiAcid use the SAME enum key (0x10000011 / 0x10000013) for
/// BOTH the live idle DID (<c>m_didAnimation</c>) and the rest DID
/// (<c>m_didAnimationRest</c>) — every standard heritage uses two
/// DIFFERENT keys (0x10000006 idle vs 0x10000005 rest). This proves the
/// SHARED enum key resolves to a real installed Animation DID (the same
/// <c>RetailHeldPose.ResolvePoseDid</c> call
/// <c>ChargenPreviewEntityBuilder</c>'s <c>ResolveIdleAnimEnum</c> AND
/// <c>ResolveRestPoseEnum</c> both return for these two heritages) — the
/// enum-key identity itself is source-verified (both private methods
/// literally return the SAME numeric constant for Olthoi/OlthoiAcid, see
/// their own doc comments), so a single resolution here is enough to
/// confirm the shared key is not a dead/unresolvable id.
/// </summary>
[Theory]
[InlineData(0x10000011u)] // Olthoi's shared idle/rest enum key.
[InlineData(0x10000013u)] // OlthoiAcid's shared idle/rest enum key.
public void OlthoiFamily_SharedIdleRestEnumKey_ResolvesToARealInstalledDid(uint sharedEnumKey)
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
uint did = RetailHeldPose.ResolvePoseDid(adapter, sharedEnumKey);
Assert.NotEqual(0u, did);
Assert.Equal(0x03u, did >> 24); // resolves to a real Animation DID.
}
/// <summary>
/// Extends <see cref="TryBuild_OlthoiHeritage_ResolvesADifferentRestPoseDidThanStandardHeritages"/>
/// to the idle side: <c>TryBuildAnimated</c> resolves a real idle
/// Animation for Olthoi too (not just the rest pose the older
/// <c>TryBuild</c>-only test covers), so an Olthoi
/// <c>ChargenPreviewAnimator</c> actually plays instead of silently
/// falling back to the rest-only pose.
/// </summary>
[Fact]
public void TryBuildAnimated_OlthoiHeritage_ResolvesARealIdleAnimationToo()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.True(options.TryGetHeritage(12u, out ChargenHeritageOptions? olthoi));
Assert.True(olthoi!.GendersByKey.TryGetValue(1, out ChargenGenderOptions? male)
|| olthoi.GendersByKey.TryGetValue(2, out male));
Assert.NotNull(male);
int genderKey = olthoi.GendersByKey.First(kv => ReferenceEquals(kv.Value, male)).Key;
var catalog = new ChargenAppearanceCatalog(adapter);
var animations = new RetailAnimationLoader(adapter);
bool composed = ChargenAppearanceFactory.TryCompose(
options, 12u, genderKey, ChargenAppearanceSelection.Default with { SkinShade = 0.5 },
catalog, catalog, out ChargenAppearanceResult appearance);
Assert.True(composed);
ChargenPreviewAnimatedBuild? build = ChargenPreviewEntityBuilder.TryBuildAnimated(
adapter, animations, appearance, heritageId: 12u, Quaternion.Identity, new object());
Assert.NotNull(build);
Assert.NotNull(build!.IdleAnimation);
var animator = new ChargenPreviewAnimator(build);
Assert.False(animator.IsZoomedIn);
Assert.NotEmpty(animator.Entity.MeshRefs);
}
}