acdream/src/AcDream.Core/Meshing/TranslucencyKind.cs
Erik ec1bbb4f43 feat(vfx): Phase C.1 — PES particle renderer + post-review fixes
Ports retail's ParticleEmitterInfo / Particle::Init / Particle::Update
(0x005170d0..0x0051d400) and PhysicsScript runtime to a C# data-layer
plus a Silk.NET billboard renderer. Sky-PES path is debug-only behind
ACDREAM_ENABLE_SKY_PES because named-retail decomp confirms GameSky
copies SkyObject.pes_id but never reads it (CreateDeletePhysicsObjects
0x005073c0, MakeObject 0x00506ee0, UseTime 0x005075b0).

Post-review fixes folded into this commit:

H1: AttachLocal (is_parent_local=1) follows live parent each frame.
    ParticleSystem.UpdateEmitterAnchor + ParticleHookSink.UpdateEntityAnchor
    let the owning subsystem refresh AnchorPos every tick — matches
    ParticleEmitter::UpdateParticles 0x0051d2d4 which re-reads the live
    parent frame when is_parent_local != 0. Drops the renderer-side
    cameraOffset hack that only worked when the parent was the camera.

H3: Strip the long stale comment in GfxObjMesh.cs that contradicted the
    retail-faithful (1 - translucency) opacity formula. The code was
    right; the comment was a leftover from an earlier hypothesis and
    would have invited a wrong "fix".

M1: SkyRenderer tracks textures whose wrap mode it set to ClampToEdge
    and restores them to Repeat at end-of-pass, so non-sky renderers
    that share the GL handle can't silently inherit clamped wrap state.

M2: Post-scene Z-offset (-120m) only fires when the SkyObject is
    weather-flagged AND bit 0x08 is clear, matching retail
    GameSky::UpdatePosition 0x00506dd0. The old code applied it to
    every post-scene object — a no-op today (every Dereth post-scene
    entry happens to be weather-flagged) but a future post-scene-only
    sun rim would have been pushed below the camera.

M4: ParticleSystem.EmitterDied event lets ParticleHookSink prune dead
    handles from the per-entity tracking dictionaries, fixing a slow
    leak where naturally-expired emitters' handles stayed in the
    ConcurrentBag forever during long sessions.

M5: SkyPesEntityId moves the post-scene flag bit to 0x08000000 so it
    can't ever overlap the object-index range. Synthetic IDs stay in
    the reserved 0xFxxxxxxx space.

New tests (ParticleSystemTests + ParticleHookSinkTests):
- UpdateEmitterAnchor_AttachLocal_ParticlePositionFollowsLiveAnchor
- UpdateEmitterAnchor_AttachLocalCleared_ParticleFrozenAtSpawnOrigin
- EmitterDied_FiresOncePerHandle_AfterAllParticlesExpire
- Birthrate_PerSec_EmitsOnePerTickWhenIntervalElapsed (retail-faithful
  single-emit-per-frame behavior)
- UpdateEntityAnchor_WithAttachLocal_MovesParticleToLiveAnchor
- EmitterDied_PrunesPerEntityHandleTracking

dotnet build green, dotnet test green: 695 / 393 / 243 = 1331 passed
(up from 1325).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 22:47:11 +02:00

130 lines
5.2 KiB
C#

using DatReaderWriter.Enums;
namespace AcDream.Core.Meshing;
/// <summary>
/// Categorizes how a sub-mesh should be composited into the frame. Determined
/// from the Surface.Type flags on the AC dat surface that owns the sub-mesh.
/// </summary>
public enum TranslucencyKind
{
/// <summary>Standard opaque. Depth write + test, no blend.</summary>
Opaque = 0,
/// <summary>
/// Alpha-keyed (clip-map). Treated as opaque for sorting; the fragment
/// shader discards low-alpha fragments. Matches the current rendering of
/// doors, windows, and vegetation.
/// </summary>
ClipMap = 1,
/// <summary>
/// Standard alpha blend: src*a + dst*(1-a).
/// Depth-write off, depth-test on. Used for semi-transparent glass,
/// water decals, and flame alpha surfaces.
/// </summary>
AlphaBlend = 2,
/// <summary>
/// Additive blend: src*a + dst. Depth-write off, depth-test on.
/// Used for portal swirls, magical glows, and particle effects.
/// </summary>
Additive = 3,
/// <summary>
/// Inverted alpha blend: src*(1-a) + dst*a. Rare but present in
/// the AC dat files.
/// </summary>
InvAlpha = 4,
}
public static class TranslucencyKindExtensions
{
// Translucent override comes FIRST, then the existing priority chain:
// 1. Translucent override — Translucent (0x10) AND (ClipMap OR opaque-base)
// → AlphaBlend (matches retail's blend forcing).
// 2. Additive — SurfaceType.Additive (0x10000)
// 3. InvAlpha — SurfaceType.InvAlpha (0x200)
// 4. AlphaBlend — SurfaceType.Alpha (0x100) OR SurfaceType.Translucent (0x10)
// 5. ClipMap — SurfaceType.Base1ClipMap (0x04)
// 6. Opaque — everything else
//
// The Translucent override matches retail's D3DPolyRender::SetSurface
// at 0x0059c4d0 (decomp lines 425083-425260). Verbatim from the
// Translucent branch at 425246:
//
// if ((curr_surface_type & 0x10) != 0) {
// if (skipChk != 0 || ebx == 0 || arg3 == 1) {
// edi_2 = BLEND_SRCALPHA; // src
// ebp = BLEND_INVSRCALPHA; // dst ← alpha-blend
// ebx = 1; arg1 = 1; arg3 = 0;
// }
// curr_alpha = _ftol2(translucency * 255);
// }
//
// Where `arg3 = 1` after the ClipMap branch and `ebx == 0` happens
// in Branch 2 when the surface would otherwise be opaque (no Additive,
// Alpha, or InvAlpha bits). So Translucent + ClipMap (e.g. cloud
// surface 0x08000023, Type=0x10114) renders ALPHA-BLEND in retail
// even though the Additive flag is also set; previously acdream's
// priority-Additive-first classification mis-routed it as additive.
// Empirically: this is the surface for cloud GfxObj 0x01004C35 in
// every Cloudy/Rainy DayGroup. Misclassifying it as additive made
// acdream's clouds barely-visible "brightness adders" rather than
// the dense alpha-blended sheets retail shows.
/// <summary>
/// Maps a <see cref="SurfaceType"/> flags value to the correct
/// <see cref="TranslucencyKind"/> for the two-pass render split.
/// </summary>
public static TranslucencyKind FromSurfaceType(SurfaceType type)
{
// Step 1: Translucent override — matches retail's branch at
// decomp line 425250 where (skipChk || ebx == 0 || arg3 == 1)
// forces (SrcAlpha, InvSrcAlpha) regardless of Additive.
bool isTranslucent = (type & SurfaceType.Translucent) != 0;
bool isClipMap = (type & SurfaceType.Base1ClipMap) != 0;
bool wouldBeOpaque =
(type & (SurfaceType.Additive
| SurfaceType.Alpha
| SurfaceType.InvAlpha)) == 0;
if (isTranslucent && (isClipMap || wouldBeOpaque))
return TranslucencyKind.AlphaBlend;
// Step 2..6: existing priority order for non-overridden surfaces.
if ((type & SurfaceType.Additive) != 0)
return TranslucencyKind.Additive;
if ((type & SurfaceType.InvAlpha) != 0)
return TranslucencyKind.InvAlpha;
if ((type & (SurfaceType.Alpha | SurfaceType.Translucent)) != 0)
return TranslucencyKind.AlphaBlend;
if ((type & SurfaceType.Base1ClipMap) != 0)
return TranslucencyKind.ClipMap;
return TranslucencyKind.Opaque;
}
/// <summary>
/// Retail translucency is transparency: 0 = opaque, 1 = invisible.
/// CMaterial::SetTranslucencySimple at 0x005396f0 writes material alpha
/// as <c>1 - translucency</c>.
/// </summary>
public static float OpacityFromSurfaceTranslucency(SurfaceType type, float translucency)
{
if ((type & SurfaceType.Translucent) == 0)
return 1f;
return Math.Clamp(1f - translucency, 0f, 1f);
}
/// <summary>
/// D3DPolyRender::SetSurface at 0x0059c882 disables fixed-function fog
/// alpha whenever the raw Additive surface bit is present, even when the
/// Translucent+ClipMap branch later forces alpha blending.
/// </summary>
public static bool DisablesFixedFunctionFog(SurfaceType type)
=> (type & SurfaceType.Additive) != 0;
}