Merge campaign-cc6a: CC6a preview foundation + CC6b-PRE animation half, review-closed

CC6a (index->ObjDesc factory + static-pose offscreen renderer) and
CC6b-PRE (idle loop, rotation, zoom, alternate-setup plumbing) both
closed through dual-lens review -> fix round -> narrow re-review. The
branch carries its own cross-branch renumbering (TS-84, ISSUES #403) so
this merge is number-clean against the CC4 rows.

Notable review outcomes carried in: the barber refutation (chargen has
NO alternate-setup checkbox — all five write sites are gmBarberUI), the
idle-by-default finding with its corrected InitializePage evidence, and
the 180-degree initial heading owed to the mount half.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

# Conflicts:
#	docs/ISSUES.md
#	docs/architecture/retail-divergence-register.md
This commit is contained in:
Erik 2026-08-15 19:40:15 +02:00
commit 11374484dc
27 changed files with 4294 additions and 28 deletions

View file

@ -0,0 +1,157 @@
using System.Collections.Generic;
using System.Numerics;
using AcDream.Core.Physics;
using AcDream.Core.World;
namespace AcDream.App.Rendering;
/// <summary>
/// Owns the chargen preview's per-frame idle-loop ↔ rest-pose playback,
/// mirroring <c>gmCG3DView::StartAnimation</c>/<c>StopAnimation</c>'s swap
/// (<c>0x004EE600</c>/<c>0x004EE640</c>) and
/// <c>gmCGAppearancePage::ZoomIn</c>/<c>ZoomOut</c>'s immediate call into it
/// (<c>0x0047D024</c>/<c>0x0047D160</c> — the swap happens the instant the
/// button is pressed, NOT once the camera's own 0.6s tween finishes).
///
/// <para>
/// <b>Retail default is idle-PLAYING, not frozen</b> — see
/// <see cref="ChargenPreviewEntityBuilder"/>'s class doc for the decomp
/// citations. This class's own default (<see cref="IsZoomedIn"/> starts
/// <c>false</c>) reproduces that: its constructor immediately plays the
/// idle animation's frame 0 when one resolved, matching
/// <c>gmCGAppearancePage::Update</c>'s own trailing
/// <c>if (m_bZoomedIn == 0) StartAnimation()</c> gate
/// (~0x0047EF01-0x0047EF12), which re-fires on every heritage/gender/
/// appearance change too — <see cref="SetZoomedIn"/> restarts the idle loop
/// at frame 0 on every transition INTO the playing state for the same
/// reason: <c>set_sequence_animation</c>'s <c>arg3=1</c> clears the sequence
/// before appending, so every <c>StartAnimation</c> call restarts the clip.
/// The DEFAULT-false claim itself rests on <c>gmCGAppearancePage::InitializePage
/// @ 0x0047FDD0</c>'s explicit <c>this-&gt;m_bZoomedIn = 0;</c> at
/// <c>0x004802C3</c> — written immediately after that same function sets the
/// camera to the zoomed-IN per-heritage eye (<c>0x00480286-0x0048029E</c>),
/// not from the ctor simply never touching the field (heap <c>operator new</c>
/// memory is indeterminate, not zero — that argument doesn't hold on its
/// own). One retail quirk this implies: the character starts framed close-up
/// AND not-zoomed-in at the same time, so the FIRST Zoom In click (once
/// mounted) tweens close-eye→close-eye — visually null — while still
/// freezing the animation; the port reproduces this faithfully rather than
/// treating it as a bug.
/// </para>
///
/// <para>
/// The page-mount half (CC6b, after CC4 merges) wires the Zoom In/Out
/// buttons to <see cref="SetZoomedIn"/> and the render loop to
/// <see cref="Tick"/>; nothing in this repository calls either yet.
/// </para>
/// </summary>
internal sealed class ChargenPreviewAnimator
{
/// <summary>
/// <c>gmCG3DView::StartAnimation</c>'s literal framerate argument
/// (<c>set_sequence_animation(this->m_pPlayerObject,
/// this->m_didAnimation.id, 1, 0, 30f)</c>, pseudo-C ~0x004ee61b).
/// </summary>
public const float IdleFramerate = 30f;
private readonly ChargenPreviewAnimatedBuild _build;
private float _currFrame;
private bool _zoomedIn;
// Double-buffered so a 30fps Tick doesn't allocate a fresh List<MeshRef>
// every frame: one buffer is whatever Entity.MeshRefs currently points
// at (potentially still being read by the renderer's own Render() call
// for this frame), the other is safe to Clear()+refill for the NEXT
// tick and only gets published once fully populated.
private readonly List<MeshRef> _meshRefsBufferA = [];
private readonly List<MeshRef> _meshRefsBufferB = [];
private bool _nextBufferIsA = true;
public ChargenPreviewAnimator(ChargenPreviewAnimatedBuild build)
{
_build = build ?? throw new ArgumentNullException(nameof(build));
_currFrame = build.IdleLowFrame;
if (build.IdleAnimation is not null)
ApplyIdleFrame(); // retail's true default: idle playing, frame 0.
// Else: Entity.MeshRefs already holds RestMeshRefs (set by
// TryBuildAnimated) as the best available fallback.
}
/// <summary>The live preview entity — mutated in place by <see cref="Tick"/>
/// and <see cref="SetZoomedIn"/>; the renderer never needs to re-call
/// <c>SetPreview</c> after the first assignment (<c>WorldEntity.MeshRefs</c>
/// is read fresh every draw — see its own doc comment).</summary>
public WorldEntity Entity => _build.Entity;
public bool IsZoomedIn => _zoomedIn;
/// <summary>
/// <c>gmCGAppearancePage::ZoomIn</c>/<c>ZoomOut</c>'s
/// <c>StopAnimation</c>/<c>StartAnimation</c> call, applied immediately
/// (retail does not wait for the camera tween to finish before swapping
/// animation state — see this class's own doc comment). No-op if
/// already in the requested state, matching retail's own early-return
/// guards (<c>ZoomIn</c>'s <c>if (m_bZoomedIn != 0) return</c>,
/// <c>ZoomOut</c>'s mirror).
/// </summary>
public void SetZoomedIn(bool zoomedIn)
{
if (_zoomedIn == zoomedIn)
return;
_zoomedIn = zoomedIn;
if (zoomedIn)
{
_build.Entity.MeshRefs = _build.RestMeshRefs;
}
else
{
_currFrame = _build.IdleLowFrame;
if (_build.IdleAnimation is not null)
ApplyIdleFrame();
}
}
/// <summary>
/// Advances the idle loop by <paramref name="elapsedSeconds"/>. No-op
/// while zoomed in (the rest pose is frozen — retail's framerate-0
/// <c>set_sequence_animation</c> call never advances) or when no idle
/// Animation resolved (heritage/DID gap; the entity keeps whatever pose
/// the constructor seeded).
/// </summary>
public void Tick(float elapsedSeconds)
{
if (_zoomedIn || _build.IdleAnimation is null || elapsedSeconds <= 0f)
return;
_currFrame = RetailAnimationCyclePlayback.Advance(
_currFrame, _build.IdleLowFrame, _build.IdleHighFrame, IdleFramerate, elapsedSeconds);
ApplyIdleFrame();
}
private void ApplyIdleFrame()
{
DatReaderWriter.DBObjs.Animation animation = _build.IdleAnimation!;
IReadOnlyList<ChargenPreviewDrawablePart> parts = _build.DrawableParts;
List<MeshRef> meshRefs = _nextBufferIsA ? _meshRefsBufferA : _meshRefsBufferB;
_nextBufferIsA = !_nextBufferIsA;
meshRefs.Clear();
foreach (ChargenPreviewDrawablePart part in parts)
{
bool resolved = RetailAnimationCyclePlayback.TryInterpolatePart(
animation, _currFrame, _build.IdleLowFrame, _build.IdleHighFrame,
part.SetupPartIndex, out Vector3 origin, out Quaternion orientation);
// Same defensive default as ApplyHeldPoseTransforms: a part
// index the bracketing frame doesn't cover (a Setup/Animation
// part-count mismatch, never expected in practice) keeps
// identity rather than a degenerate zero quaternion.
if (!resolved)
{
origin = Vector3.Zero;
orientation = Quaternion.Identity;
}
Matrix4x4 transform = RetailHeldPose.ComposePartTransform(part.DefaultScale, origin, orientation);
meshRefs.Add(new MeshRef(part.GfxObjId, transform) { SurfaceOverrides = part.SurfaceOverrides });
}
_build.Entity.MeshRefs = meshRefs;
}
}

View file

@ -0,0 +1,185 @@
using System;
using System.Numerics;
using AcDream.Core.CharGen;
namespace AcDream.App.Rendering;
/// <summary>
/// Heritage-parameterized camera for the chargen 3D preview
/// (<c>gmCG3DView</c>, Appearance page viewport <c>0x100003bb</c> / Summary
/// <c>0x10000406</c>). Retail-exact eye positions, ported from
/// <c>gmCGAppearancePage::Update @ 0x0047E8F0</c> (pseudo-C ~139037-139114,
/// which sets <c>m_vectTargPosition</c>/<c>m_vectCurPosition</c> per
/// heritage and snaps them together with no tween — CC6a's static preview
/// renders that snapped default, the "zoomed-in" framing) and cross-checked
/// against the IDENTICAL literals in <c>gmCGAppearancePage::ZoomIn @
/// 0x0047CF00</c> (pseudo-C ~137618-137638). Direction is always
/// <c>(0,0,0)</c> ⇒ <c>CreatureMode::SetCameraDirection</c> resets the view
/// frame to IDENTITY — the SAME zero-yaw/zero-pitch convention
/// <see cref="DollCamera"/> already established for the paperdoll (look
/// straight down +Y, +Z up); every camera position below is used AS the
/// world-space eye directly, matching that camera's approach.
///
/// <para>
/// <b>Rotation is NOT a camera property.</b> Retail's continuous-rotation
/// button (<c>gmCGAppearancePage::DoRotation @ 0x0047CA80</c>) advances a
/// HEADING applied to the preview CHARACTER (<c>CPhysicsObj::set_heading</c>
/// inside <c>gmCG3DView::Update</c>, pseudo-C ~242088) — the camera's own
/// position/direction never change during a rotation. The heading itself
/// lives on <see cref="ChargenPreviewRotationController"/> (CC6b: the
/// <c>DoRotation</c>/<c>Rotate</c> port) and is applied to the entity via
/// <c>ChargenPreviewEntityBuilder.TryBuild</c>/<c>TryBuildAnimated</c>'s
/// <c>heading</c> parameter, not here; this class stays a fixed-per-heritage
/// eye, exactly like retail's own camera. <see cref="ChargenPreviewZoomController"/>
/// (CC6b: the <c>ZoomIn</c>/<c>ZoomOut</c>/<c>DoZoomAnimation</c> port) DOES
/// mutate this class's <see cref="Eye"/> — zoom is a camera concern, unlike
/// rotation.
/// </para>
/// </summary>
public sealed class ChargenPreviewCamera : ICamera
{
private static readonly Vector3 Up = Vector3.UnitZ; // AC up-axis = +Z, same as DollCamera/ChaseCamera.
private Vector3 _eye;
public ChargenPreviewCamera(uint heritageId = 0u)
{
_eye = ResolveDefaultEye(heritageId);
}
/// <summary>
/// The camera's current world-space eye. Settable so CC6b can react to a
/// heritage change without reconstructing the camera.
/// </summary>
public Vector3 Eye
{
get => _eye;
set => _eye = value;
}
/// <summary>Re-derives <see cref="Eye"/> for the given heritage id (retail's <c>mHeritageGroup</c>).</summary>
public void SetHeritage(uint heritageId) => _eye = ResolveDefaultEye(heritageId);
/// <summary>
/// Retail default (zoomed-in) camera eye per heritage. All four profiles
/// share <c>X=0</c>; only <c>(Y, Z)</c> — the AC world-space forward
/// offset and height — vary. FOUR distinct profiles across the 13
/// heritages, not five: standard heritages (Aluvian, Gharu'ndim, Sho,
/// Viamontian, Shadowbound, Gearknight, Lugian, Empyrean, Penumbraen,
/// Undead — everything except Tumerok/Olthoi/OlthoiAcid) share the SAME
/// numeric offset as Gearknight's own dedicated branch in the decomp.
/// </summary>
public static Vector3 ResolveDefaultEye(uint heritageId) => heritageId switch
{
(uint)ChargenHeritageGroup.Olthoi => new Vector3(0f, -1.85000002f, 1.85000002f),
(uint)ChargenHeritageGroup.OlthoiAcid => new Vector3(0f, -3.04999995f, 2.75f),
(uint)ChargenHeritageGroup.Tumerok => new Vector3(0f, -0.850000024f, 1.64999998f),
_ => new Vector3(0f, -0.550000012f, 1.64999998f),
};
/// <summary>
/// Retail zoomed-OUT camera eye per heritage
/// (<c>gmCGAppearancePage::ZoomOut @ 0x0047D050</c>, pseudo-C
/// ~137671-137687). CC6a does not implement the zoom button (CC6b) —
/// recorded here as the verified target CC6b's tween will animate
/// toward. Olthoi/OlthoiAcid each keep their own dedicated profile;
/// every other heritage — INCLUDING Tumerok, whose zoomed-IN profile is
/// special-cased but whose zoomed-OUT is not — shares one value.
/// </summary>
public static Vector3 ResolveZoomedOutEye(uint heritageId) => heritageId switch
{
(uint)ChargenHeritageGroup.Olthoi => new Vector3(0f, -3.79999995f, 1.14999998f),
(uint)ChargenHeritageGroup.OlthoiAcid => new Vector3(0f, -5.69999981f, 1.64999998f),
_ => new Vector3(0f, -2.5f, 0.95f),
};
/// <summary>
/// Seconds per 360° revolution for the continuous-rotation button
/// (<c>gmCGAppearancePage::m_dRotationPerSec</c>, ctor pseudo-C
/// ~137523-137524 / ~226652-226653: raw double bits low32=0x00000000,
/// high32=0x40080000 → exactly 3.0 — the decompiler shows this cleanly,
/// no reconstruction needed). Retail's own per-tick formula
/// (<c>gmCGAppearancePage::DoRotation @ 0x0047CA80</c>, pseudo-C
/// ~0x0047CAC7): <c>deltaDegrees = ((now - lastRotateTime) /
/// RotationSecondsPerRevolution) * 360</c> — CC6b's rotation controller
/// consumes this constant in exactly that shape, not as a
/// degrees-per-second rate. NOT applied here; see this class's own doc
/// comment on why rotation is not a camera concern.
/// </summary>
public const float RotationSecondsPerRevolution = 3.0f;
/// <summary>
/// Zoom tween duration in seconds
/// (<c>gmCGAppearancePage::DoZoomAnimation @ 0x0047C960</c>'s
/// reset-if-invalid default, cross-confirmed by <c>ZoomIn</c>/<c>ZoomOut</c>'s
/// own <c>-0.1</c> sentinel write, which deliberately invalidates
/// <c>m_dAnimDuration</c> so the very next <c>DoZoomAnimation</c> tick
/// resets it to this same value). The campaign plan flagged this
/// constant as decompiler-garbled (both sites split the raw double
/// across two 32-bit stores, and the decompiler mis-renders the LOW
/// dword's store as a bogus float literal instead of raw bits) — it is
/// NOT unrecoverable: reinterpreting each garbled float literal as its
/// own raw 32-bit pattern and pairing it with the store's (clean) high
/// dword reconstructs an exact IEEE-754 double both times.
/// <c>DoZoomAnimation</c>'s own reset path: low32 from
/// <c>4.17232506e-08f</c> reinterpreted = <c>0x33333333</c>, high32 =
/// <c>0x3fe33333</c> (clean) → exactly <b>0.6</b>. Cross-check via
/// <c>ZoomIn</c>/<c>ZoomOut</c>'s sentinel: low32 from
/// <c>-1.58818684e-23f</c> reinterpreted = <c>0x9999999A</c>, high32 =
/// <c>0xbfb99999</c> (clean) → exactly <b>-0.1</b>, the well-known
/// IEEE-754 bit pattern for -0.1 (<c>0xBFB999999999999A</c>) — confirming
/// the reconstruction technique itself, not just this one value.
/// </summary>
public const float ZoomTweenDurationSeconds = 0.6f;
public float FovRadians { get; set; } = MathF.PI / 4f; // retail CreatureMode default, same as DollCamera.
public float Near { get; set; } = 0.1f;
public float Far { get; set; } = 50f;
public float Aspect { get; set; } = 1f;
public Matrix4x4 View =>
Matrix4x4.CreateLookAt(_eye, _eye + Vector3.UnitY, Up);
public Matrix4x4 Projection =>
Matrix4x4.CreatePerspectiveFieldOfView(FovRadians, Aspect <= 0f ? 1f : Aspect, Near, Far);
}
/// <summary>
/// Internal private-viewport adapter, mirroring <c>DollViewportCamera</c>'s
/// role for <see cref="ChargenPreviewCamera"/>.
/// </summary>
internal sealed class ChargenPreviewViewportCamera : IPrivateEntityViewportCamera
{
private readonly ChargenPreviewCamera _camera;
public ChargenPreviewViewportCamera(uint heritageId = 0u)
{
_camera = new ChargenPreviewCamera(heritageId);
}
public void SetHeritage(uint heritageId) => _camera.SetHeritage(heritageId);
public Vector3 Eye => _camera.Eye;
public float FovRadians
{
get => _camera.FovRadians;
set => _camera.FovRadians = value;
}
public float Near
{
get => _camera.Near;
set => _camera.Near = value;
}
public float Far
{
get => _camera.Far;
set => _camera.Far = value;
}
public float Aspect
{
get => _camera.Aspect;
set => _camera.Aspect = value;
}
public Matrix4x4 View => _camera.View;
public Matrix4x4 Projection => _camera.Projection;
}

View file

@ -0,0 +1,431 @@
using System.Collections.Generic;
using System.Numerics;
using AcDream.Content;
using AcDream.Core.CharGen;
using AcDream.Core.Meshing;
using AcDream.Core.Physics;
using AcDream.Core.World;
using DatReaderWriter.DBObjs;
namespace AcDream.App.Rendering;
/// <summary>
/// One resolved drawable part of the chargen preview body — a Setup part
/// index (needed to sample <c>Animation.PartFrames[frame].Frames[index]</c>
/// and <c>Setup.DefaultScale[index]</c>) paired with its resolved GfxObj id,
/// default scale (captured once at build time — scale never changes across
/// an idle cycle), and surface overrides. <see cref="ChargenPreviewAnimator"/>
/// walks this list every tick without touching the dat source again.
/// </summary>
internal readonly record struct ChargenPreviewDrawablePart(
int SetupPartIndex,
uint GfxObjId,
Vector3 DefaultScale,
IReadOnlyDictionary<uint, uint>? SurfaceOverrides);
/// <summary>
/// The richer sibling of <see cref="ChargenPreviewEntityBuilder.TryBuild"/>'s
/// result: the built <see cref="WorldEntity"/> (seeded with retail's true
/// default pose — see <see cref="ChargenPreviewAnimator"/>) plus everything
/// needed to drive it frame-by-frame without re-touching the dat source —
/// the resolved drawable parts, the precomputed frozen rest pose, and the
/// resolved idle Animation + its frame range.
/// </summary>
internal sealed class ChargenPreviewAnimatedBuild
{
public required WorldEntity Entity { get; init; }
public required IReadOnlyList<ChargenPreviewDrawablePart> DrawableParts { get; init; }
/// <summary>
/// The held final-frame rest pose, precomputed once (retail:
/// <c>gmCG3DView::StopAnimation</c>'s framerate-0
/// <c>set_sequence_animation</c> call never advances, so there is
/// nothing to recompute per tick while zoomed in). Falls back to each
/// part's raw Setup-default transform (no-op) when the rest DID doesn't
/// resolve, matching the pre-CC6b <c>ApplyHeldPose</c> no-op behavior.
/// </summary>
public required IReadOnlyList<MeshRef> RestMeshRefs { get; init; }
/// <summary>Retail's live idle DID (<c>m_didAnimation</c>), or null if unresolved.</summary>
public Animation? IdleAnimation { get; init; }
public int IdleLowFrame { get; init; }
public int IdleHighFrame { get; init; }
}
/// <summary>
/// Builds the chargen preview <see cref="WorldEntity"/> from a
/// <see cref="ChargenAppearanceResult"/> — the App-layer counterpart to
/// <see cref="DollEntityBuilder"/>, except this one resolves its OWN
/// MeshRefs from a Setup + the composed ObjDesc rather than receiving
/// already-resolved refs from a live entity (there is no live entity yet;
/// character creation hasn't happened). DAT-touching, unlike
/// <see cref="DollEntityBuilder"/>'s pure index-agnostic builder — the
/// closest existing precedent for the actual mesh-flatten/apply-changes/
/// resolve-surface-overrides steps is
/// <c>DatLiveEntityProjectionMaterializer.TryMaterialize</c>, trimmed to
/// what a private, non-collision preview scene needs.
///
/// <para>
/// <b>CC6b:</b> retail's chargen preview does NOT default to a frozen pose —
/// <c>gmCGAppearancePage::Update</c>'s own trailing gate
/// (~0x0047EF01-0x0047EF12) calls <c>gmCG3DView::StartAnimation</c> (idle
/// loop playing) whenever <c>m_bZoomedIn == 0</c>, and that default is
/// DIRECTLY ASSIGNED, not inherited:
/// <c>gmCGAppearancePage::InitializePage @0x0047FDD0</c> writes an
/// explicit <c>m_bZoomedIn = 0</c> at <c>0x004802C3</c> (right after
/// setting the camera to the zoomed-IN per-heritage eye at
/// <c>0x00480286-0x0048029E</c> — the null-tween quirk the zoom
/// controller's doc records). The earlier elided-ctor-byte argument was
/// unsound (heap-new members are indeterminate, not zero) and was
/// replaced by this citation at the CC6b-PRE re-review. So retail's
/// chargen preview plays its idle loop (<c>m_didAnimation</c>, 30fps) from
/// the very first frame; the REST pose (<c>m_didAnimationRest</c>, held
/// final frame, this class's pre-CC6b-only behavior) only appears once the
/// user presses Zoom In (<c>gmCGAppearancePage::ZoomIn</c> calls
/// <c>gmCG3DView::StopAnimation</c> immediately, before its camera tween
/// even starts). <see cref="TryBuild"/> keeps its ORIGINAL (rest-only)
/// behavior unchanged for its existing callers; <see cref="TryBuildAnimated"/>
/// plus <see cref="ChargenPreviewAnimator"/> are the new, retail-accurate
/// entry point a live preview (idle-playing by default, freezing on zoom-in)
/// should use.
/// </para>
/// </summary>
internal static class ChargenPreviewEntityBuilder
{
/// <summary>Reserved synthetic guid for the chargen preview clone —
/// same reserved family as <see cref="DollEntityBuilder.DollServerGuid"/>
/// (0xDA11D0xx) and <c>CreatureAppraisalEntityBuilder</c> (0xDA11D02x).</summary>
public const uint PreviewServerGuid = 0xDA11_D031u;
/// <summary>Reserved render-local entity id — passed in
/// <c>animatedEntityIds</c> by the renderer so a re-dress (a new
/// selection) bypasses <c>WbDrawDispatcher</c>'s Tier-1 classification
/// cache, mirroring <see cref="DollEntityBuilder.DollRenderId"/>'s own
/// doc comment.</summary>
public const uint PreviewRenderId = 0xDA11_D032u;
/// <summary>
/// Retail's held-pose (REST) animation DID enum key, resolved through
/// master map slot 7 exactly like <c>RetailPaperdollPoseApplicator.ResolvePoseDid</c>
/// — 0x10000005 for every standard heritage (the SAME enum id the
/// paperdoll's own held pose reads), matching
/// <c>gmCG3DView</c>'s ctor / <c>::Update</c> per-heritage
/// <c>m_didAnimationRest</c> assignment (pseudo-C ~0x004EE948,
/// ~0x004EEC43). Olthoi and OlthoiAcid each get their OWN distinct rest
/// DID — the one divergence from the paperdoll, which never needs an
/// Olthoi branch because a live player can't be one.
/// </summary>
private static uint ResolveRestPoseEnum(uint heritageId) => heritageId switch
{
(uint)ChargenHeritageGroup.Olthoi => 0x10000011u,
(uint)ChargenHeritageGroup.OlthoiAcid => 0x10000013u,
_ => 0x10000005u,
};
/// <summary>
/// Retail's LIVE idle-loop animation DID enum key (<c>m_didAnimation</c>,
/// the one <c>gmCG3DView::StartAnimation</c> plays at 30fps) — 0x10000006
/// for every standard heritage, matching <c>gmCG3DView</c>'s ctor /
/// <c>::Update</c> per-heritage assignment (pseudo-C ~0x004ee6cc,
/// ~0x004eec2d). <b>Olthoi and OlthoiAcid use the SAME did for BOTH idle
/// and rest</b> (0x10000011 / 0x10000013 respectively, pseudo-C
/// ~0x004ee7e9/0x004ee7ff and ~0x004ee892/0x004ee8a8) — a genuine retail
/// quirk, not a porting shortcut: those two heritages show no visible
/// difference between "idle playing" and "zoomed in and frozen" in the
/// chargen preview.
/// </summary>
private static uint ResolveIdleAnimEnum(uint heritageId) => heritageId switch
{
(uint)ChargenHeritageGroup.Olthoi => 0x10000011u,
(uint)ChargenHeritageGroup.OlthoiAcid => 0x10000013u,
_ => 0x10000006u,
};
/// <summary>
/// Builds the STATIC (held rest-pose) preview entity, or null when the
/// resolved body Setup isn't in the dat source (a corrupted/incomplete
/// install — the same failure shape
/// <see cref="DatLiveEntityProjectionMaterializer"/> treats as "drop this
/// spawn"). Unchanged since CC6a for its RESULT — a thin wrapper over
/// <see cref="TryBuildAnimated"/> that returns exactly the same
/// <c>WorldEntity</c> (rest-posed) this method's existing callers already
/// expect; ALL 3 of those callers' tests still pass unmodified. Not
/// byte-identical internally any more — <see cref="TryBuildAnimated"/>
/// also resolves the idle DID and loads the idle Animation before this
/// wrapper discards them, extra dat work the pre-CC6b method never did.
/// New code that wants retail's true default (idle loop playing) should call
/// <see cref="TryBuildAnimated"/> and wrap the result in a
/// <see cref="ChargenPreviewAnimator"/> instead.
/// </summary>
/// <param name="datLock">
/// Shared exclusion object for every dat read this method performs.
/// <c>DatCollection</c> is NOT thread-safe (see
/// <c>claude-memory/feedback_phase_a1_hotfix_saga.md</c>) — every other
/// dat-touching renderer/resolver in this layer
/// (<c>RetailPaperdollPoseApplicator</c>, <c>PlayerModeController</c>,
/// <c>DatProjectileSetupResolver</c>, <c>EquippedChildRenderController</c>)
/// takes the SAME <c>object datLock</c> the composition root threads
/// through as <c>RuntimeOptions</c>/<c>d.DatLock</c>; callers MUST pass
/// that same shared instance, not a private lock, or this method's reads
/// race every other consumer's.
/// </param>
public static WorldEntity? TryBuild(
IDatReaderWriter dats,
IAnimationLoader animations,
ChargenAppearanceResult appearance,
uint heritageId,
Quaternion heading,
object datLock)
{
ChargenPreviewAnimatedBuild? build = TryBuildAnimated(
dats, animations, appearance, heritageId, heading, datLock);
if (build is null)
return null;
build.Entity.MeshRefs = build.RestMeshRefs;
return build.Entity;
}
/// <summary>
/// Builds the preview entity PLUS everything a <see cref="ChargenPreviewAnimator"/>
/// needs to drive retail's idle-loop ↔ rest-pose swap without re-touching
/// the dat source. The returned <see cref="ChargenPreviewAnimatedBuild.Entity"/>
/// is initially posed with <see cref="ChargenPreviewAnimatedBuild.RestMeshRefs"/>
/// (cheap, always available) — <see cref="ChargenPreviewAnimator"/>'s
/// constructor immediately reposes it to the true retail default (idle
/// frame 0) when an idle Animation resolved.
/// </summary>
public static ChargenPreviewAnimatedBuild? TryBuildAnimated(
IDatReaderWriter dats,
IAnimationLoader animations,
ChargenAppearanceResult appearance,
uint heritageId,
Quaternion heading,
object datLock)
{
ArgumentNullException.ThrowIfNull(dats);
ArgumentNullException.ThrowIfNull(animations);
ArgumentNullException.ThrowIfNull(appearance);
ArgumentNullException.ThrowIfNull(datLock);
uint setupId = appearance.SetupId;
List<ChargenPreviewDrawablePart> drawableParts;
List<MeshRef> restMeshRefs;
Animation? idleAnimation;
int idleLowFrame = 0, idleHighFrame = -1;
// Every dat read this method performs — the Setup fetch, both pose
// DID resolutions, the per-part GfxObj drawable checks, and the
// texture-change surface resolution — happens inside this one lock,
// mirroring RetailPaperdollPoseApplicator.Apply's "resolve
// everything under lock, then do pure processing" shape.
lock (datLock)
{
Setup? setup = dats.Get<Setup>(setupId);
if (setup is null)
return null;
var flattened = new List<MeshRef>(SetupMesh.Flatten(setup));
foreach (ChargenAnimPartChange change in appearance.ObjDesc.AnimPartChanges)
{
if (change.PartIndex < flattened.Count)
flattened[change.PartIndex] = new MeshRef(change.PartId, flattened[change.PartIndex].PartTransform);
}
// Rest pose: overwrite flattened's transforms with the held
// final frame (no-op — keeps Setup-default transforms — if the
// rest DID or its Animation don't resolve).
ApplyHeldPoseTransforms(dats, animations, setup, ResolveRestPoseEnum(heritageId), flattened);
Dictionary<int, Dictionary<uint, uint>>? surfaceOverrides =
ResolveSurfaceOverrides(dats, flattened, appearance.ObjDesc.TextureChanges);
drawableParts = new List<ChargenPreviewDrawablePart>(flattened.Count);
restMeshRefs = new List<MeshRef>(flattened.Count);
for (int partIndex = 0; partIndex < flattened.Count; partIndex++)
{
MeshRef part = flattened[partIndex];
if (dats.Get<GfxObj>(part.GfxObjId) is null)
continue; // matches DatLiveEntityProjectionMaterializer's drawable filter.
IReadOnlyDictionary<uint, uint>? overrides = null;
if (surfaceOverrides is not null && surfaceOverrides.TryGetValue(partIndex, out var perPart))
overrides = perPart;
restMeshRefs.Add(new MeshRef(part.GfxObjId, part.PartTransform) { SurfaceOverrides = overrides });
Vector3 defaultScale = partIndex < setup.DefaultScale.Count
? setup.DefaultScale[partIndex]
: Vector3.One;
drawableParts.Add(new ChargenPreviewDrawablePart(partIndex, part.GfxObjId, defaultScale, overrides));
}
if (drawableParts.Count == 0)
return null;
// Idle DID: independent lookup, no mutation of flattened.
uint idleDid = RetailHeldPose.ResolvePoseDid(dats, ResolveIdleAnimEnum(heritageId));
idleAnimation = (idleDid >> 24) == 0x03u ? animations.LoadAnimation(idleDid) : null;
if (idleAnimation is not null && idleAnimation.PartFrames.Count > 0)
{
idleLowFrame = 0;
idleHighFrame = idleAnimation.PartFrames.Count - 1;
}
else
{
idleAnimation = null;
}
}
var entity = new WorldEntity
{
Id = PreviewRenderId,
ServerGuid = PreviewServerGuid,
SourceGfxObjOrSetupId = setupId,
Position = Vector3.Zero,
Rotation = heading,
MeshRefs = restMeshRefs,
PaletteOverride = BuildPaletteOverride(appearance),
PartOverrides = BuildPartOverrides(appearance),
ParentCellId = null,
};
return new ChargenPreviewAnimatedBuild
{
Entity = entity,
DrawableParts = drawableParts,
RestMeshRefs = restMeshRefs,
IdleAnimation = idleAnimation,
IdleLowFrame = idleLowFrame,
IdleHighFrame = idleHighFrame,
};
}
/// <summary>No dat access — pure projection of the already-composed
/// ObjDesc's subpalettes, safe to call outside <c>datLock</c>.</summary>
private static PaletteOverride? BuildPaletteOverride(ChargenAppearanceResult appearance)
{
if (appearance.ObjDesc.SubPalettes.Count == 0)
return null;
var ranges = new PaletteOverride.SubPaletteRange[appearance.ObjDesc.SubPalettes.Count];
for (int i = 0; i < appearance.ObjDesc.SubPalettes.Count; i++)
{
ChargenSubPalette sub = appearance.ObjDesc.SubPalettes[i];
ranges[i] = new PaletteOverride.SubPaletteRange(sub.SubPaletteId, sub.Offset, sub.NumColors);
}
return new PaletteOverride(appearance.BasePaletteId, ranges);
}
/// <summary>No dat access — pure projection, safe to call outside
/// <c>datLock</c>.</summary>
private static PartOverride[] BuildPartOverrides(ChargenAppearanceResult appearance)
{
var partOverrides = new PartOverride[appearance.ObjDesc.AnimPartChanges.Count];
for (int i = 0; i < appearance.ObjDesc.AnimPartChanges.Count; i++)
{
ChargenAnimPartChange change = appearance.ObjDesc.AnimPartChanges[i];
partOverrides[i] = new PartOverride(change.PartIndex, change.PartId);
}
return partOverrides;
}
/// <summary>
/// Overwrites every part's transform from the resolved pose DID's FINAL
/// frame — same "hold the settled last frame at zero frame rate"
/// approach as <c>RetailPaperdollPoseApplicator.Apply</c>
/// (<c>RedressCreature @ 0x004A3C22</c>), applied to the FULL
/// setup-part-indexed array (before drawable filtering) so the index
/// alignment holds even if a later part turns out to have a missing
/// GfxObj. No-ops (keeps the default placement frame) when the pose
/// DID or its animation can't be resolved.
/// </summary>
private static void ApplyHeldPoseTransforms(
IDatReaderWriter dats,
IAnimationLoader animations,
Setup setup,
uint poseEnum,
List<MeshRef> flattened)
{
uint poseDid = RetailHeldPose.ResolvePoseDid(dats, poseEnum);
if ((poseDid >> 24) != 0x03u)
return;
Animation? animation = animations.LoadAnimation(poseDid);
if (animation is null || animation.PartFrames.Count == 0)
return;
var frame = animation.PartFrames[^1];
for (int index = 0; index < flattened.Count; index++)
{
Vector3 scale = index < setup.DefaultScale.Count ? setup.DefaultScale[index] : Vector3.One;
Vector3 origin = Vector3.Zero;
Quaternion orientation = Quaternion.Identity;
if (index < frame.Frames.Count)
{
origin = frame.Frames[index].Origin;
orientation = frame.Frames[index].Orientation;
}
flattened[index] = new MeshRef(
flattened[index].GfxObjId,
RetailHeldPose.ComposePartTransform(scale, origin, orientation));
}
}
/// <summary>
/// Part-index → (old texture id → new texture id) resolution, verbatim
/// port of <c>DatLiveEntityProjectionMaterializer.ResolveSurfaceOverrides</c>'s
/// algorithm against <see cref="ChargenTextureChange"/> instead of the
/// wire's <c>CreateObject.TextureChange</c>.
/// </summary>
private static Dictionary<int, Dictionary<uint, uint>>? ResolveSurfaceOverrides(
IDatReaderWriter dats,
IReadOnlyList<MeshRef> parts,
IReadOnlyList<ChargenTextureChange> textureChanges)
{
if (textureChanges.Count == 0)
return null;
var oldToNewByPart = new Dictionary<int, Dictionary<uint, uint>>();
foreach (ChargenTextureChange change in textureChanges)
{
if (!oldToNewByPart.TryGetValue(change.PartIndex, out var oldToNew))
{
oldToNew = [];
oldToNewByPart.Add(change.PartIndex, oldToNew);
}
oldToNew[change.OldTextureId] = change.NewTextureId;
}
var result = new Dictionary<int, Dictionary<uint, uint>>();
for (int partIndex = 0; partIndex < parts.Count; partIndex++)
{
if (!oldToNewByPart.TryGetValue(partIndex, out var oldToNew))
continue;
GfxObj? gfx = dats.Get<GfxObj>(parts[partIndex].GfxObjId);
if (gfx is null)
continue;
Dictionary<uint, uint>? resolved = null;
foreach (var surfaceQid in gfx.Surfaces)
{
uint surfaceId = (uint)surfaceQid;
Surface? surface = dats.Get<Surface>(surfaceId);
if (surface is null)
continue;
uint originalTexture = (uint)surface.OrigTextureId;
if (originalTexture == 0 || !oldToNew.TryGetValue(originalTexture, out uint newTexture))
continue;
(resolved ??= [])[surfaceId] = newTexture;
}
if (resolved is not null)
result[partIndex] = resolved;
}
return result.Count == 0 ? null : result;
}
}

View file

@ -0,0 +1,90 @@
using AcDream.App.Rendering.Wb;
using AcDream.App.UI;
using AcDream.Core.Lighting;
using AcDream.Core.World;
namespace AcDream.App.Rendering;
/// <summary>
/// Chargen-specific facade over the shared private creature viewport
/// (<see cref="PrivateEntityViewportRenderer"/>) — CC6a's foundation half of
/// the campaign plan's "chargen preview renderer" deliverable. Mirrors
/// <see cref="PaperdollViewportRenderer"/>'s shape exactly, with a
/// heading-capable <see cref="ChargenPreviewViewportCamera"/> in place of the
/// paperdoll's fixed one.
///
/// <para>
/// <b>NOT wired here (CC6b page-mount half, after CC4 merges per the
/// campaign's parallelism contract):</b> mounting into the authored
/// Appearance/Summary viewport ids (<c>0x100003bb</c> / <c>0x10000406</c>)
/// and binding the spin/color-wheel/rotate/zoom widgets to
/// <see cref="ChargenPreviewAnimator"/>/<see cref="ChargenPreviewRotationController"/>/
/// <see cref="ChargenPreviewZoomController"/>. This class is a standalone,
/// composition-root-agnostic renderer — nothing in
/// <c>AcDream.App/UI/Layout/</c> or <c>RetailUiRuntime.cs</c> references it
/// yet.
/// </para>
///
/// <para>
/// <b>CC6b (pre-mount half):</b> the preview now HAS a real live idle loop
/// (<see cref="ChargenPreviewAnimator"/>, retail's <c>m_didAnimation</c> DID
/// at 30fps via <c>set_sequence_animation</c>) instead of the CC6a-only held
/// rest pose — TS-83 is retired. <see cref="SetPreview"/> still accepts a
/// static <c>WorldEntity</c> for callers that only want
/// <c>ChargenPreviewEntityBuilder.TryBuild</c>'s unchanged rest-pose
/// snapshot; a caller that wants the animated preview constructs a
/// <see cref="ChargenPreviewAnimator"/> from
/// <c>ChargenPreviewEntityBuilder.TryBuildAnimated</c> and passes its
/// <c>Entity</c> here once — the animator mutates that SAME entity's
/// <c>MeshRefs</c> in place every <c>Tick</c>, and <c>Render</c> reads it
/// fresh (no re-<c>SetPreview</c> needed per frame; see
/// <c>WorldEntity.MeshRefs</c>'s own "mutable so the animation tick can
/// replace it each frame" doc comment).
/// </para>
/// </summary>
internal sealed class ChargenPreviewRenderer :
IUiViewportRenderer,
IDisposable
{
private readonly PrivateEntityViewportRenderer _renderer;
private readonly ChargenPreviewViewportCamera _camera;
internal ChargenPreviewRenderer(
IWorldPassScope scope,
AcDream.App.Rendering.Gpu.IGpuDevice device,
ICurrentGpuFrameSource frames,
WbDrawDispatcher dispatcher,
SceneLightingUboBinding lightUbo,
IEntityTextureLifetime textureLifetime,
IWbMeshAdapter meshAdapter,
uint heritageId = 0u)
{
_camera = new ChargenPreviewViewportCamera(heritageId);
_renderer = new PrivateEntityViewportRenderer(
scope,
device,
frames,
dispatcher,
lightUbo,
textureLifetime,
meshAdapter,
ChargenPreviewEntityBuilder.PreviewRenderId,
_camera,
"chargen preview");
}
public bool TextureIsBottomUp => _renderer.TextureIsBottomUp;
/// <summary>
/// Re-derives the fixed per-heritage camera eye
/// (<see cref="ChargenPreviewCamera.ResolveDefaultEye"/>) — call whenever
/// the selected heritage changes, BEFORE the next <see cref="Render"/>.
/// </summary>
public void SetHeritage(uint heritageId) => _camera.SetHeritage(heritageId);
public void SetPreview(WorldEntity? entity) => _renderer.SetEntity(entity);
public uint Render(int width, int height) => _renderer.Render(width, height);
public void Dispose() => _renderer.Dispose();
}

View file

@ -0,0 +1,126 @@
using System.Numerics;
using AcDream.Core.Physics.Motion;
namespace AcDream.App.Rendering;
/// <summary>
/// Retail's toggle direction enum
/// (<c>gmBarberUI::ERotateDirection</c>/<c>gmCGAppearancePage::ERotateDirection</c>
/// typedef alias, <c>acclient.h:6848-6852,6960</c>): <c>Invalid=0</c>,
/// <c>Clockwise=1</c>, <c>CounterClockwise=2</c>.
/// </summary>
internal enum ChargenRotateDirection
{
Invalid = 0,
Clockwise = 1,
CounterClockwise = 2,
}
/// <summary>
/// Presentation-free port of <c>gmCGAppearancePage::Rotate</c>
/// (<c>0x0047CB50</c>) + <c>DoRotation</c> (<c>0x0047CA80</c>) — the
/// button-toggled continuous rotation retail applies to the preview
/// CHARACTER's heading (<c>CPhysicsObj::set_heading</c> inside
/// <c>gmCG3DView::Update</c>, pseudo-C ~0x0047eecf1), not the camera (see
/// <see cref="ChargenPreviewCamera"/>'s own doc comment on why rotation
/// lives here instead). Retail drives <see cref="Tick"/> once per frame from
/// a global-message-3 tick while <see cref="IsRotating"/> is set
/// (<c>gmCGAppearancePage::ListenToGlobalMessage @ 0x0047CED0</c>); the
/// CC6b page-mount half will bind the Rotate Clockwise/Counter-Clockwise
/// buttons to <see cref="Toggle"/> and the render loop to <see cref="Tick"/>.
/// </summary>
internal sealed class ChargenPreviewRotationController
{
/// <summary>
/// <c>Rotate</c>'s explicit sentinel write
/// (<c>this->m_dLastRotateTime = -1.0</c>, pseudo-C ~0x0047cba7/0x0047cbb1
/// — the high dword <c>0xbff00000</c> paired with a zero low dword is the
/// exact IEEE-754 bit pattern for <c>-1.0</c>) — invalidates the
/// timestamp so the very next <see cref="Tick"/> resets it to "now"
/// (a zero-length first delta) instead of computing a huge jump from a
/// stale or never-set value.
/// </summary>
private const double InvalidTimeSentinel = -1.0;
private double _lastRotateTime = InvalidTimeSentinel;
private ChargenRotateDirection _direction = ChargenRotateDirection.Invalid;
private bool _rotating;
public bool IsRotating => _rotating;
public ChargenRotateDirection Direction => _direction;
/// <summary>Retail's <c>m_fCurHeading</c>, degrees, ctor default 0 —
/// applied to the preview entity via <c>MoveToMath.SetHeading</c>
/// (<c>CPhysicsObj::set_heading</c>'s exact port).</summary>
public float HeadingDegrees { get; private set; }
/// <summary>
/// <c>gmCGAppearancePage::Rotate @ 0x0047CB50</c>: pressing the SAME
/// direction a second time while already rotating STOPS rotation
/// (retail's button-toggle UX); any other press (opposite direction, or
/// starting from stopped) sets that direction and (re)starts,
/// invalidating <c>m_dLastRotateTime</c> per this class's own sentinel
/// doc.
/// </summary>
public void Toggle(ChargenRotateDirection direction)
{
if (_rotating && direction == _direction)
{
_rotating = false;
return;
}
_direction = direction;
_lastRotateTime = InvalidTimeSentinel;
_rotating = true;
}
/// <summary>
/// <c>gmCGAppearancePage::DoRotation @ 0x0047CA80</c>: per-tick
/// <c>deltaDegrees = ((now - lastRotateTime) / RotationSecondsPerRevolution)
/// * 360</c>, added for <see cref="ChargenRotateDirection.Clockwise"/>
/// and subtracted for every other direction (pseudo-C ~0x0047cacd:
/// <c>if (m_eRotateDir != ECG_ROTATE_CLOCKWISE) heading -= delta; else
/// heading += delta;</c>), then a SINGLE-PASS clamp back into
/// <c>[0, 360)</c> — not a full modulo loop; retail's own tail only
/// adds/subtracts 360 once (pseudo-C ~0x0047caf3-0x0047cb31), which is
/// exactly enough for any realistic per-frame delta and is reproduced
/// here verbatim rather than "improved" into a `%=`. Fix round F3: Binary
/// Ninja literally renders <c>x87_r7_1 = x87_r6_3</c> at <c>0x0047CAEB</c>
/// inside the counter-clockwise branch — reassigning the local that held
/// the "now" timestamp to the just-computed delta-degrees value — which
/// would make the <c>0x0047CB3D</c> store into <c>m_dLastRotateTime</c>
/// write delta-degrees instead of the timestamp for CCW only; that is an
/// x87-FPU-stack modeling artifact of the decompiler, not real retail
/// behavior (a shipped feature where every counter-clockwise rotation
/// visibly diverges from clockwise is implausible, and
/// <c>claude-memory/feedback_bn_decomp_field_names.md</c> names exactly
/// this x87-stack-register mislabeling as a known decompiler artifact
/// class), so this port stores <c>now</c> into <c>_lastRotateTime</c>
/// unconditionally in BOTH directions.
/// </summary>
public void Tick(double now)
{
if (!_rotating)
return;
if (_lastRotateTime <= 0d)
_lastRotateTime = now;
double deltaDegrees = ((now - _lastRotateTime) / ChargenPreviewCamera.RotationSecondsPerRevolution) * 360.0;
HeadingDegrees = _direction == ChargenRotateDirection.Clockwise
? HeadingDegrees + (float)deltaDegrees
: HeadingDegrees - (float)deltaDegrees;
if (HeadingDegrees < 0f)
HeadingDegrees += 360f;
if (HeadingDegrees > 360f)
HeadingDegrees -= 360f;
_lastRotateTime = now;
}
/// <summary><c>CPhysicsObj::set_heading</c>'s exact quaternion
/// construction — the SAME shared Core primitive retail movement already
/// ports (<see cref="MoveToMath.SetHeading"/>).</summary>
public Quaternion ToOrientation() =>
MoveToMath.SetHeading(Quaternion.Identity, HeadingDegrees);
}

View file

@ -0,0 +1,162 @@
using System.Numerics;
namespace AcDream.App.Rendering;
/// <summary>
/// Presentation-free port of <c>gmCGAppearancePage::ZoomIn</c>/<c>ZoomOut</c>
/// (<c>0x0047CF00</c>/<c>0x0047D050</c>) and <c>DoZoomAnimation</c>
/// (<c>0x0047C960</c>): a linear 0.6s tween of the preview camera's eye
/// between <see cref="ChargenPreviewCamera.ResolveDefaultEye"/> (zoomed IN)
/// and <see cref="ChargenPreviewCamera.ResolveZoomedOutEye"/> (zoomed OUT),
/// driving the SAME <see cref="ChargenPreviewAnimator"/> zoom-state swap the
/// button presses trigger in retail — immediately, not once the tween
/// finishes (see <see cref="ChargenPreviewAnimator"/>'s own doc comment).
///
/// <para>
/// <b>One owner of the zoom state (fix round F2):</b> retail's
/// <c>m_bZoomedIn</c> is a SINGLE field on <c>gmCGAppearancePage</c> that
/// gates both the camera target AND the animation swap — there is no way
/// for retail's own camera and animation to disagree about which zoom state
/// they're in. The first cut of this port kept two independent bools (one
/// here, one on <see cref="ChargenPreviewAnimator"/>) synced only by
/// <see cref="ZoomIn"/>/<see cref="ZoomOut"/> calling a NULLABLE animator
/// parameter — a null pass, or any direct
/// <see cref="ChargenPreviewAnimator.SetZoomedIn"/> call bypassing this
/// controller, would desync the camera's target from the animation's pose.
/// This class now takes its <see cref="ChargenPreviewAnimator"/> as a
/// REQUIRED constructor dependency and <see cref="IsZoomedIn"/> reads
/// straight through to <see cref="ChargenPreviewAnimator.IsZoomedIn"/> — the
/// animator is the sole state owner, matching retail's own single-field
/// design, and there is no longer a second bool that could disagree with it.
/// </para>
///
/// <para>
/// Retail drives <see cref="Tick"/> once per frame from a global-message-3
/// tick while <c>m_bShouldZoomAnimate</c> is set
/// (<c>gmCGAppearancePage::ListenToGlobalMessage @ 0x0047CED0</c>); the
/// CC6b page-mount half will bind the Zoom In/Out buttons to
/// <see cref="ZoomIn"/>/<see cref="ZoomOut"/> and the render loop to
/// <see cref="Tick"/>. Direction is always <c>(0,0,0)</c> for this camera
/// (see <see cref="ChargenPreviewCamera"/>'s own remarks), so only the eye
/// position tweens — retail's own <c>m_vectCurDirection</c> lerp is a no-op
/// here and is not reproduced.
/// </para>
/// </summary>
internal sealed class ChargenPreviewZoomController
{
/// <summary>
/// <c>ZoomIn</c>/<c>ZoomOut</c>'s explicit invalidation write
/// (<c>this->m_dAnimDuration = -0.1</c>, pseudo-C ~0x0047cff1/0x0047cffb
/// and ~0x0047d12c/0x0047d136 — the exact IEEE-754 bit pattern for
/// <c>-0.1</c>) so the very next <see cref="Tick"/> resets the duration
/// to <see cref="ChargenPreviewCamera.ZoomTweenDurationSeconds"/> and the
/// start time to "now", matching <c>DoZoomAnimation</c>'s own
/// reset-if-invalid guard exactly.
/// </summary>
private const double InvalidDurationSentinel = -0.1;
private readonly uint _heritageId;
private readonly ChargenPreviewAnimator _animator;
private Vector3 _startEye;
private Vector3 _targetEye;
private double _animStartTime;
private double _animDuration;
private bool _shouldAnimate;
public ChargenPreviewZoomController(uint heritageId, ChargenPreviewCamera camera, ChargenPreviewAnimator animator)
{
ArgumentNullException.ThrowIfNull(camera);
ArgumentNullException.ThrowIfNull(animator);
_heritageId = heritageId;
Camera = camera;
_animator = animator;
}
public ChargenPreviewCamera Camera { get; }
/// <summary>
/// Mirrors retail's <c>m_bZoomedIn</c> — a straight read-through to
/// <see cref="ChargenPreviewAnimator.IsZoomedIn"/> (see this class's own
/// "one owner" doc above), which itself defaults false per
/// <c>gmCGAppearancePage::InitializePage @ 0x0047FDD0</c>'s explicit
/// <c>this-&gt;m_bZoomedIn = 0;</c> at <c>0x004802C3</c> — written right
/// after that same function points the camera at the zoomed-IN
/// per-heritage eye (<c>0x00480286-0x0048029E</c>). One retail quirk
/// this produces: the character starts framed close-up while
/// NOT-zoomed-in, so the first Zoom In click (once mounted) tweens
/// close-eye→close-eye — visually null — while still freezing the
/// animation; this port reproduces it faithfully.
/// </summary>
public bool IsZoomedIn => _animator.IsZoomedIn;
/// <summary>
/// <c>gmCGAppearancePage::ZoomIn @ 0x0047CF00</c>: no-op if already
/// zoomed in (retail's own early-return guard). Otherwise starts a tween
/// from the camera's CURRENT eye to the default (zoomed-IN) per-heritage
/// profile and swaps the animator to the frozen rest pose IMMEDIATELY
/// (<c>gmCG3DView::StopAnimation</c>'s call site, pseudo-C ~0x0047d024,
/// precedes the tween's own completion by definition — it runs once,
/// synchronously, inside <c>ZoomIn</c> itself).
/// </summary>
public void ZoomIn()
{
if (IsZoomedIn)
return;
StartTween(ChargenPreviewCamera.ResolveDefaultEye(_heritageId));
_animator.SetZoomedIn(true);
}
/// <summary>
/// <c>gmCGAppearancePage::ZoomOut @ 0x0047D050</c>: no-op if not
/// currently zoomed in. Otherwise starts a tween toward the zoomed-OUT
/// per-heritage profile and swaps the animator back to the playing idle
/// loop immediately, mirroring <see cref="ZoomIn"/>.
/// </summary>
public void ZoomOut()
{
if (!IsZoomedIn)
return;
StartTween(ChargenPreviewCamera.ResolveZoomedOutEye(_heritageId));
_animator.SetZoomedIn(false);
}
private void StartTween(Vector3 targetEye)
{
_startEye = Camera.Eye;
_targetEye = targetEye;
_shouldAnimate = true;
_animDuration = InvalidDurationSentinel;
}
/// <summary>
/// <c>gmCGAppearancePage::DoZoomAnimation @ 0x0047C960</c>: a LINEAR
/// (not eased) lerp of the eye position from <c>m_vectStartPosition</c>
/// to <c>m_vectTargPosition</c> over
/// <see cref="ChargenPreviewCamera.ZoomTweenDurationSeconds"/>, clamping
/// <c>t</c> to exactly 1.0 (and clearing <c>m_bShouldZoomAnimate</c>) the
/// tick that reaches or passes the duration — the decomp shows a
/// straight <c>(targ - start) * t + start</c> per axis with no easing
/// curve applied anywhere in this function.
/// </summary>
public void Tick(double now)
{
if (!_shouldAnimate)
return;
if (_animDuration <= 0d)
{
_animDuration = ChargenPreviewCamera.ZoomTweenDurationSeconds;
_animStartTime = now;
}
double elapsed = now - _animStartTime;
if (elapsed >= _animDuration)
{
_shouldAnimate = false;
elapsed = _animDuration;
}
float t = (float)(elapsed / _animDuration);
Camera.Eye = Vector3.Lerp(_startEye, _targetEye, t);
}
}

View file

@ -335,29 +335,11 @@ internal sealed class RetailPaperdollPoseApplicator : IPaperdollPoseApplicator
/// <summary>
/// Retail <c>gmPaperDollUI</c> resolves its held pose with
/// <c>DBCache::GetDIDFromEnumStatic(0x10000005, 7)</c>. The master map
/// therefore resolves key 7 to a sub-map, then key 0x10000005 to the
/// Animation DID.
/// <c>DBCache::GetDIDFromEnumStatic(0x10000005, 7)</c>
/// <see cref="RetailHeldPose.ResolvePoseDid"/> parameterized by the
/// paperdoll's own fixed enum key.
/// </summary>
private uint ResolvePoseDid()
{
uint masterDid = (uint)_dats.Portal.Db.Header.MasterMapId;
if (masterDid == 0
|| !_dats.Portal.TryGet<DatReaderWriter.DBObjs.EnumIDMap>(
masterDid,
out var master)
|| !master.ClientEnumToID.TryGetValue(7u, out uint subDid)
|| !_dats.Portal.TryGet<DatReaderWriter.DBObjs.EnumIDMap>(
subDid,
out var sub))
{
return 0u;
}
return sub.ClientEnumToID.TryGetValue(0x10000005u, out uint did)
? did
: 0u;
}
private uint ResolvePoseDid() => RetailHeldPose.ResolvePoseDid(_dats, 0x10000005u);
public void Apply(WorldEntity doll, uint setupId)
{
@ -392,9 +374,7 @@ internal sealed class RetailPaperdollPoseApplicator : IPaperdollPoseApplicator
orientation = frame.Frames[index].Orientation;
}
Matrix4x4 transform = Matrix4x4.CreateScale(scale)
* Matrix4x4.CreateFromQuaternion(orientation)
* Matrix4x4.CreateTranslation(origin);
Matrix4x4 transform = RetailHeldPose.ComposePartTransform(scale, origin, orientation);
MeshRef source = doll.MeshRefs[index];
reposed.Add(new MeshRef(source.GfxObjId, transform)
{

View file

@ -0,0 +1,61 @@
using System.Numerics;
using AcDream.Content;
using DatReaderWriter;
using DatReaderWriter.DBObjs;
namespace AcDream.App.Rendering;
/// <summary>
/// Shared primitives behind retail's "resolve a rest-pose DID via master-map
/// slot 7, load its Animation, hold the final frame" algorithm — the
/// mechanism <see cref="RetailPaperdollPoseApplicator"/> (paperdoll,
/// <c>gmPaperDollUI::RedressCreature @ 0x004A3C22</c>) and
/// <see cref="ChargenPreviewEntityBuilder"/> (chargen preview,
/// <c>gmCG3DView::StopAnimation @ 0x004EE640</c>) both implement. Extracted
/// per the CC6a review's F11/F12 note ("before adding a FOURTH consumer... a
/// shared <c>RetailHeldPose</c> helper is worth extracting before a fourth
/// held-pose consumer exists") — CC6b's own idle-loop work makes chargen's
/// implementation grow enough that mechanically sharing the two primitives
/// BOTH sites already had byte-identical (DID resolution, final-frame
/// transform composition) is a clean win without forcing the two sites'
/// slightly different per-index LOOP shapes (paperdoll walks an
/// already-built, already-filtered <c>WorldEntity.MeshRefs</c>; chargen
/// walks the pre-filter, Setup-part-indexed scratch list) into one method
/// they don't actually share.
/// </summary>
internal static class RetailHeldPose
{
/// <summary>
/// <c>DBCache::GetDIDFromEnumStatic(poseEnum, 7)</c> equivalent: master
/// map → slot 7's sub-map → <paramref name="poseEnum"/>'s Animation DID.
/// Returns 0 if any link in the chain is missing. MUST be called under
/// the caller's dat lock (see <see cref="ChargenPreviewEntityBuilder.TryBuild"/>'s
/// <c>datLock</c> doc — <c>DatCollection</c> is not thread-safe).
/// </summary>
public static uint ResolvePoseDid(IDatReaderWriter dats, uint poseEnum)
{
uint masterDid = (uint)dats.Portal.Db.Header.MasterMapId;
if (masterDid == 0
|| !dats.Portal.TryGet<EnumIDMap>(masterDid, out var master)
|| !master.ClientEnumToID.TryGetValue(7u, out uint subDid)
|| !dats.Portal.TryGet<EnumIDMap>(subDid, out var sub))
{
return 0u;
}
return sub.ClientEnumToID.TryGetValue(poseEnum, out uint did) ? did : 0u;
}
/// <summary>
/// Retail's per-part pose transform: <c>Scale(defaultScale) *
/// Rotate(orientation) * Translate(origin)</c> — the SAME composition
/// both <c>RetailPaperdollPoseApplicator.Apply</c> and
/// <see cref="ChargenPreviewEntityBuilder"/>'s pose steps use, whether
/// the (origin, orientation) pair comes from a held final frame or an
/// interpolated idle-cycle frame.
/// </summary>
public static Matrix4x4 ComposePartTransform(Vector3 defaultScale, Vector3 origin, Quaternion orientation) =>
Matrix4x4.CreateScale(defaultScale)
* Matrix4x4.CreateFromQuaternion(orientation)
* Matrix4x4.CreateTranslation(origin);
}