perf(vfx): port retail particle visibility degradation

Resolve DAT-authored particle ranges from the hardware GfxObj, apply retail distance and completed-cell visibility gates, and preserve the exact finite/infinite off-view update semantics. This removes dense-world simulation work without shortening terrain, entity, fog, or streaming distance.

Publish doorway-clipped outdoor cells through a focused frame controller, retain effect cell identity for outdoor statics, reject hidden emitters before particle-slot scans, and offer an explicit opt-in Extended particle range.

Release build succeeds and all 5,857 tests pass with five intentional skips. Retail-conformance, architecture, and adversarial review cycles are clean; connected Aerlinthe visual/performance gate pending.

Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
Erik 2026-07-17 15:27:36 +02:00
parent 82789eea88
commit f1ba147ac5
29 changed files with 1810 additions and 125 deletions

View file

@ -361,6 +361,7 @@ public sealed class GameWindow : IDisposable
private AcDream.Core.Vfx.EmitterDescRegistry? _emitterRegistry;
private AcDream.Core.Vfx.ParticleSystem? _particleSystem;
private AcDream.Core.Vfx.ParticleHookSink? _particleSink;
private readonly AcDream.App.Rendering.Vfx.ParticleVisibilityController _particleVisibility = new();
private readonly AcDream.App.Rendering.Vfx.EntityEffectPoseRegistry _effectPoses = new();
private AcDream.App.Rendering.Vfx.AnimationHookFrameQueue? _animationHookFrames;
// Phase 6 — retail PhysicsScript runtime. Receives PlayScript (0xF754)
@ -2868,6 +2869,7 @@ public sealed class GameWindow : IDisposable
_itemInteractionController?.ClearBusy();
_selection.Reset();
_pendingPostArrivalAction = null;
_particleVisibility.Reset();
try
{
_liveEntities?.Clear();
@ -7544,6 +7546,7 @@ public sealed class GameWindow : IDisposable
Position = e.Position + worldOffset,
Rotation = e.Rotation,
MeshRefs = meshRefs,
EffectCellId = e.EffectCellId,
IsBuildingShell = e.IsBuildingShell, // Phase A8: preserve dat-level tag
BuildingShellAnchorCellId = e.BuildingShellAnchorCellId,
};
@ -7870,6 +7873,10 @@ public sealed class GameWindow : IDisposable
Rotation = spawn.Rotation,
MeshRefs = meshRefs,
Scale = spawn.Scale,
EffectCellId = AcDream.Core.Physics.TerrainSurface.ComputeOutdoorCellId(
lb.LandblockId,
localX,
localY),
};
if (sceneryBounds.TryGet(out var scbMin, out var scbMax))
hydrated.SetLocalBounds(scbMin, scbMax);
@ -9502,6 +9509,8 @@ public sealed class GameWindow : IDisposable
// normal SmartBox viewport and UIElement_Viewport's portal
// CreatureMode; it does not redraw the world behind portal space.
bool portalViewportVisible = _portalTunnel?.IsVisible == true;
if (portalViewportVisible)
_particleVisibility.Reset();
// Phase G.1: set the clear color from the current sky's fog
// tint so the horizon band continues naturally past the
@ -9623,6 +9632,10 @@ public sealed class GameWindow : IDisposable
// and by the sky renderer (for the camera-centered sky dome).
System.Numerics.Matrix4x4.Invert(camera.View, out var invView);
var camPos = new System.Numerics.Vector3(invView.M41, invView.M42, invView.M43);
_particleVisibility.BeginFrame(camPos);
_terrain?.BeginVisibilityFrame();
if (!IsLiveModeWaitingForLogin)
_particleVisibility.UseWorldView();
// L.0 Audio tab: push the SettingsVM's live AudioDraft into the
// engine each frame, so volume sliders preview audibly while
@ -10205,6 +10218,7 @@ public sealed class GameWindow : IDisposable
clipAssembly = pviewResult.ClipAssembly;
envCellShellFilter = pviewResult.DrawableCells;
_interiorPartition = pviewResult.Partition;
_particleVisibility.MarkVisibleCells(pviewResult.DrawableCells);
// A7.L1: snapshot this frame's drawn cell set for NEXT frame's light-
// pool scoping. DrawableCells is the renderer's own reused scratch set
@ -10517,7 +10531,10 @@ public sealed class GameWindow : IDisposable
// below. Sky has already drawn before this label so the
// pre-login screen shows a live, correctly-tinted sky and
// nothing else.
SkipWorldGeometry: ;
SkipWorldGeometry:
if (_terrain is not null)
_particleVisibility.MarkVisibleCells(_terrain.VisibleCellIds);
_particleVisibility.CompleteFrame();
}
// Retail gmSmartBoxUI swaps the world SmartBox viewport for a
@ -10734,6 +10751,17 @@ public sealed class GameWindow : IDisposable
_particleSink?.RefreshAttachedEmitters();
_liveEntityLights?.Refresh();
if (_particleSystem is not null)
{
var particleRange = _settingsVm?.DisplayDraft.ParticleRange
?? _persistedDisplay.ParticleRange;
float rangeMultiplier = particleRange
== AcDream.UI.Abstractions.Panels.Settings.ParticleRange.Extended
? AcDream.App.Rendering.Vfx.ParticleVisibilityController.ExtendedRangeMultiplier
: 1f;
_particleVisibility.Apply(_particleSystem, rangeMultiplier);
}
// Retail CPhysicsObj::UpdateObjectInternal (0x005156B0) advances
// ParticleManager before ScriptManager. A particle created by a PES
// hook therefore begins simulation on the following object frame.
@ -11527,7 +11555,12 @@ public sealed class GameWindow : IDisposable
EnableClipDistances();
_terrainCpuStopwatch.Restart();
_terrain?.Draw(camera, frustum, neverCullLandblockId: playerLb);
_terrain?.Draw(
camera,
frustum,
neverCullLandblockId: playerLb,
clipPlanes: slice.Planes,
ndcClipAabb: slice.NdcAabb);
_terrainCpuStopwatch.Stop();
_terrainCpuSamples[_terrainCpuSampleCursor] =
(long)(_terrainCpuStopwatch.Elapsed.TotalMicroseconds * 100.0);

View file

@ -395,61 +395,66 @@ public sealed unsafe class ParticleRenderer : IDisposable
_meshDrawListScratch.Clear();
_submissionScratch.Clear();
int sequence = 0;
foreach (var (em, idx) in _particles.EnumerateLive())
foreach (var em in _particles.EnumerateEmitters())
{
if (!em.PresentationVisible)
if (!em.PresentationVisible || !em.ViewEligible)
continue;
if (em.RenderPass != renderPass)
continue;
if (emitterFilter is not null && !emitterFilter(em))
continue;
ref var p = ref em.Particles[idx];
// `p.Position` is already in world coordinates: AttachLocal
// emitters get their AnchorPos refreshed each frame by the
// owning subsystem (sky-PES driver, animation tick, etc.) which
// mirrors retail's live-parent-frame read at
// ParticleEmitter::UpdateParticles 0x0051d2d4 for is_parent_local=1.
Vector3 pos = p.Position;
float distSq = Vector3.DistanceSquared(pos, cameraWorldPos);
uint gfxObjId = em.Desc.HwGfxObjId != 0 ? em.Desc.HwGfxObjId : em.Desc.GfxObjId;
if (gfxObjId != 0
&& ResolveGeometryKind(gfxObjId) == RetailParticleGeometryKind.FullMesh
&& TryAppendMeshDraws(em, p, gfxObjId, distSq, ref sequence))
for (int idx = 0; idx < em.Particles.Length; idx++)
{
continue;
}
ref var p = ref em.Particles[idx];
if (!p.Alive)
continue;
// `p.Position` is already in world coordinates: AttachLocal
// emitters get their AnchorPos refreshed each frame by the
// owning subsystem (sky-PES driver, animation tick, etc.) which
// mirrors retail's live-parent-frame read at
// ParticleEmitter::UpdateParticles 0x0051d2d4 for is_parent_local=1.
Vector3 pos = p.Position;
float distSq = Vector3.DistanceSquared(pos, cameraWorldPos);
uint gfxObjId = em.Desc.HwGfxObjId != 0 ? em.Desc.HwGfxObjId : em.Desc.GfxObjId;
if (gfxObjId != 0
&& ResolveGeometryKind(gfxObjId) == RetailParticleGeometryKind.FullMesh
&& TryAppendMeshDraws(em, p, gfxObjId, distSq, ref sequence))
{
continue;
}
var gfxInfo = ResolveParticleGfxInfo(em.Desc);
uint texture = gfxInfo.TextureHandle;
bool useTexture = texture != 0;
bool additive = gfxInfo.HasMaterial
? gfxInfo.Additive
: (em.Desc.Flags & EmitterFlags.Additive) != 0;
var key = new BatchKey(texture, useTexture, additive);
Vector3 axisX;
Vector3 axisY;
if (gfxInfo.IsBillboard)
{
pos += Vector3.UnitZ * (gfxInfo.CenterOffset.Z * p.Size);
axisX = cameraRight * (gfxInfo.Size.X * p.Size);
axisY = cameraUp * (gfxInfo.Size.Y * p.Size);
}
else
{
Quaternion orientation = ParticleOrientation(em, p);
pos += Vector3.Transform(gfxInfo.CenterOffset * p.Size, orientation);
axisX = Vector3.Transform(gfxInfo.AxisX, orientation) * (gfxInfo.Size.X * p.Size);
axisY = Vector3.Transform(gfxInfo.AxisY, orientation) * (gfxInfo.Size.Y * p.Size);
}
var gfxInfo = ResolveParticleGfxInfo(em.Desc);
uint texture = gfxInfo.TextureHandle;
bool useTexture = texture != 0;
bool additive = gfxInfo.HasMaterial
? gfxInfo.Additive
: (em.Desc.Flags & EmitterFlags.Additive) != 0;
var key = new BatchKey(texture, useTexture, additive);
Vector3 axisX;
Vector3 axisY;
if (gfxInfo.IsBillboard)
{
pos += Vector3.UnitZ * (gfxInfo.CenterOffset.Z * p.Size);
axisX = cameraRight * (gfxInfo.Size.X * p.Size);
axisY = cameraUp * (gfxInfo.Size.Y * p.Size);
}
else
{
Quaternion orientation = ParticleOrientation(em, p);
pos += Vector3.Transform(gfxInfo.CenterOffset * p.Size, orientation);
axisX = Vector3.Transform(gfxInfo.AxisX, orientation) * (gfxInfo.Size.X * p.Size);
axisY = Vector3.Transform(gfxInfo.AxisY, orientation) * (gfxInfo.Size.Y * p.Size);
}
int drawIndex = draws.Count;
draws.Add(new ParticleDraw(key, new ParticleInstance(pos, axisX, axisY, p.ColorArgb, distSq)));
_submissionScratch.Add(new ParticleSubmission(
ParticleSubmissionKind.Billboard,
drawIndex,
distSq,
sequence++));
int drawIndex = draws.Count;
draws.Add(new ParticleDraw(key, new ParticleInstance(pos, axisX, axisY, p.ColorArgb, distSq)));
_submissionScratch.Add(new ParticleSubmission(
ParticleSubmissionKind.Billboard,
drawIndex,
distSq,
sequence++));
}
}
}

View file

@ -69,12 +69,21 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
// Reusable per-frame buffers.
private readonly List<int> _visibleSlots = new();
private readonly HashSet<uint> _visibleCellIds = new();
private DrawElementsIndirectCommand[] _deicScratch = Array.Empty<DrawElementsIndirectCommand>();
// Diag.
public int LoadedSlots => _alloc.LoadedCount;
public int VisibleSlots => _visibleSlots.Count;
public int CapacitySlots => _alloc.Capacity;
/// <summary>
/// Outdoor landcells admitted by the current landscape view. The set is
/// accumulated across doorway landscape slices and consumed after the
/// completed render frame by particle visibility.
/// </summary>
internal HashSet<uint> VisibleCellIds => _visibleCellIds;
public void BeginVisibilityFrame() => _visibleCellIds.Clear();
public TerrainModernRenderer(
GL gl,
@ -208,10 +217,17 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
// No GPU clear: the per-frame DEIC array won't reference this slot.
}
public void Draw(ICamera camera, FrustumPlanes? frustum = null, uint? neverCullLandblockId = null)
public void Draw(
ICamera camera,
FrustumPlanes? frustum = null,
uint? neverCullLandblockId = null,
ReadOnlySpan<Vector4> clipPlanes = default,
Vector4? ndcClipAabb = null)
{
if (_alloc.LoadedCount == 0) return;
Matrix4x4 viewProjection = camera.View * camera.Projection;
// Build visible slot list with per-slot frustum cull.
_visibleSlots.Clear();
for (int slot = 0; slot < _slots.Length; slot++)
@ -224,6 +240,16 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
continue;
}
_visibleSlots.Add(slot);
CollectVisibleCells(
_visibleCellIds,
data.LandblockId,
data.WorldOrigin,
data.AabbMin.Z,
data.AabbMax.Z,
frustum,
viewProjection,
clipPlanes,
ndcClipAabb);
}
if (_visibleSlots.Count == 0) return;
@ -436,6 +462,130 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
_gl.BindVertexArray(0);
}
internal static void CollectVisibleCells(
HashSet<uint> destination,
uint landblockId,
Vector3 worldOrigin,
float zMin,
float zMax,
FrustumPlanes? frustum,
Matrix4x4 viewProjection,
ReadOnlySpan<Vector4> clipPlanes,
Vector4? ndcClipAabb = null)
{
ArgumentNullException.ThrowIfNull(destination);
const float cellSize = AcDream.Core.Physics.TerrainSurface.CellSize;
const int cellsPerSide = AcDream.Core.Physics.TerrainSurface.CellsPerSide;
uint prefix = landblockId & 0xFFFF0000u;
for (int cellX = 0; cellX < cellsPerSide; cellX++)
{
float minX = worldOrigin.X + cellX * cellSize;
float maxX = minX + cellSize;
for (int cellY = 0; cellY < cellsPerSide; cellY++)
{
float minY = worldOrigin.Y + cellY * cellSize;
float maxY = minY + cellSize;
var cellMin = new Vector3(minX, minY, zMin);
var cellMax = new Vector3(maxX, maxY, zMax);
if (frustum is not null
&& !FrustumCuller.IsAabbVisible(frustum.Value, cellMin, cellMax))
{
continue;
}
// Retail publishes landcell in_view from the clipped landscape
// view, not merely from the camera frustum. The modern renderer
// expresses each doorway slice as homogeneous clip-space planes
// plus its scissor AABB; use both products here so particle
// simulation follows the same visible terrain slice as the GPU.
if (!IsAabbVisibleThroughClipRegion(
cellMin,
cellMax,
viewProjection,
clipPlanes,
ndcClipAabb))
{
continue;
}
uint low = AcDream.Core.Physics.TerrainSurface.ComputeOutdoorCellLowId(
cellX * cellSize,
cellY * cellSize);
destination.Add(prefix | low);
}
}
}
private static bool IsAabbVisibleThroughClipRegion(
Vector3 min,
Vector3 max,
Matrix4x4 viewProjection,
ReadOnlySpan<Vector4> clipPlanes,
Vector4? ndcClipAabb)
{
Vector4 aabb = ndcClipAabb.GetValueOrDefault();
bool hasScissorConstraint = ndcClipAabb.HasValue
&& (aabb.X > -1f || aabb.Y > -1f || aabb.Z < 1f || aabb.W < 1f);
if (clipPlanes.IsEmpty && !hasScissorConstraint)
return true;
Span<Vector4> clipCorners = stackalloc Vector4[8];
for (int corner = 0; corner < clipCorners.Length; corner++)
{
var world = new Vector4(
(corner & 1) == 0 ? min.X : max.X,
(corner & 2) == 0 ? min.Y : max.Y,
(corner & 4) == 0 ? min.Z : max.Z,
1f);
clipCorners[corner] = Vector4.Transform(world, viewProjection);
}
for (int planeIndex = 0; planeIndex < clipPlanes.Length; planeIndex++)
{
if (IsAabbOutsideHomogeneousPlane(clipCorners, clipPlanes[planeIndex]))
{
return false;
}
}
if (!hasScissorConstraint)
return true;
Span<Vector4> scissorPlanes = stackalloc Vector4[4]
{
new( 1f, 0f, 0f, -aabb.X),
new(-1f, 0f, 0f, aabb.Z),
new( 0f, 1f, 0f, -aabb.Y),
new( 0f, -1f, 0f, aabb.W),
};
for (int planeIndex = 0; planeIndex < scissorPlanes.Length; planeIndex++)
{
if (IsAabbOutsideHomogeneousPlane(clipCorners, scissorPlanes[planeIndex]))
{
return false;
}
}
return true;
}
private static bool IsAabbOutsideHomogeneousPlane(
ReadOnlySpan<Vector4> clipCorners,
Vector4 plane)
{
// A linear half-space reaches its maximum over the transformed AABB at
// one of the eight corners. If every corner is negative, no point in
// the cell box can survive this GPU clip plane.
for (int corner = 0; corner < clipCorners.Length; corner++)
{
if (Vector4.Dot(plane, clipCorners[corner]) >= 0f)
return false;
}
return true;
}
private void EnsureCapacity(int newCapacity)
{
if (newCapacity <= _alloc.Capacity) return;

View file

@ -45,7 +45,7 @@ public sealed class EntityEffectPoseRegistry : IEntityEffectPoseSource, IEntityE
Matrix4x4.CreateFromQuaternion(entity.Rotation)
* Matrix4x4.CreateTranslation(entity.Position),
partLocal,
entity.ParentCellId ?? 0u,
entity.EffectCellId ?? entity.ParentCellId ?? 0u,
availability);
}
@ -67,7 +67,7 @@ public sealed class EntityEffectPoseRegistry : IEntityEffectPoseSource, IEntityE
}
record.RootWorld = rootWorld;
record.CellId = entity.ParentCellId ?? 0u;
record.CellId = entity.EffectCellId ?? entity.ParentCellId ?? 0u;
if (entity.IndexedPartTransforms.Count > 0)
{
CopyParts(
@ -119,7 +119,7 @@ public sealed class EntityEffectPoseRegistry : IEntityEffectPoseSource, IEntityE
return false;
record.RootWorld = Matrix4x4.CreateFromQuaternion(entity.Rotation)
* Matrix4x4.CreateTranslation(entity.Position);
record.CellId = entity.ParentCellId ?? 0u;
record.CellId = entity.EffectCellId ?? entity.ParentCellId ?? 0u;
return true;
}

View file

@ -0,0 +1,93 @@
using System.Numerics;
using AcDream.Core.Vfx;
namespace AcDream.App.Rendering.Vfx;
/// <summary>
/// Bridges the retained retail PView result into the next physics update's
/// <c>CObjCell::IsInView</c> particle gate. The controller owns only immutable
/// frame meaning: one completed viewer position plus the AC cells admitted by
/// that completed view. It neither creates emitters nor performs rendering.
/// </summary>
public sealed class ParticleVisibilityController
{
public const float ExtendedRangeMultiplier = 2f;
private readonly HashSet<uint> _buildingCellIds = new();
private readonly HashSet<uint> _completedCellIds = new();
private Vector3 _buildingViewerPosition;
private Vector3 _completedViewerPosition;
private bool _frameOpen;
private bool _frameUsesWorldView;
private bool _hasCompletedWorldView;
public void BeginFrame(Vector3 viewerPosition)
{
_buildingCellIds.Clear();
_buildingViewerPosition = viewerPosition;
_frameUsesWorldView = false;
_frameOpen = true;
}
/// <summary>
/// Declares that this frame has an authoritative world-visibility product.
/// That product can come from the unified retail PView or from the outdoor
/// landscape fallback. Login and portal-space frames deliberately omit it;
/// dedicated pass and examination emitters carry explicit bypass policies.
/// </summary>
public void UseWorldView()
{
if (_frameOpen)
_frameUsesWorldView = true;
}
public void MarkVisibleCells(HashSet<uint> cellIds)
{
ArgumentNullException.ThrowIfNull(cellIds);
if (!_frameOpen || !_frameUsesWorldView)
return;
_buildingCellIds.UnionWith(cellIds);
}
public void CompleteFrame()
{
if (!_frameOpen)
return;
_frameOpen = false;
if (!_frameUsesWorldView)
{
_completedCellIds.Clear();
_completedViewerPosition = _buildingViewerPosition;
_hasCompletedWorldView = false;
return;
}
_completedCellIds.Clear();
_completedCellIds.UnionWith(_buildingCellIds);
_completedViewerPosition = _buildingViewerPosition;
_hasCompletedWorldView = true;
}
public void Apply(ParticleSystem particles, float rangeMultiplier)
{
ArgumentNullException.ThrowIfNull(particles);
particles.ApplyRetailView(
_completedViewerPosition,
_completedCellIds,
_hasCompletedWorldView,
rangeMultiplier);
}
public void Reset()
{
_buildingCellIds.Clear();
_completedCellIds.Clear();
_frameOpen = false;
_frameUsesWorldView = false;
_hasCompletedWorldView = false;
_buildingViewerPosition = default;
_completedViewerPosition = default;
}
}

View file

@ -23,8 +23,8 @@ public readonly record struct TerrainSurfacePolygon(
public sealed class TerrainSurface
{
private const int HeightmapSide = 9;
private const float CellSize = 24f;
private const int CellsPerSide = 8; // 192 / 24
public const float CellSize = 24f;
public const int CellsPerSide = 8; // 192 / 24
private readonly float[,] _z; // pre-resolved heights [x, y]
private readonly bool[,] _cornerIsWater; // per-VERTEX water flag [x, y] — SurfChar[(type >> 2) & 0x1F]
@ -508,12 +508,23 @@ public sealed class TerrainSurface
/// Compute the outdoor cell ID for the given landblock-local position.
/// </summary>
public uint ComputeOutdoorCellId(float localX, float localY)
=> ComputeOutdoorCellLowId(localX, localY);
/// <summary>
/// Computes the low 16-bit outdoor landcell index for a landblock-local
/// position using retail's X-major 8x8 cell ordering.
/// </summary>
public static uint ComputeOutdoorCellLowId(float localX, float localY)
{
int cx = Math.Clamp((int)(localX / CellSize), 0, CellsPerSide - 1);
int cy = Math.Clamp((int)(localY / CellSize), 0, CellsPerSide - 1);
return (uint)(1 + cx * CellsPerSide + cy);
}
/// <summary>Composes a full outdoor landcell ID from a landblock ID.</summary>
public static uint ComputeOutdoorCellId(uint landblockId, float localX, float localY)
=> (landblockId & 0xFFFF0000u) | ComputeOutdoorCellLowId(localX, localY);
/// <summary>
/// AC2D's FSplitNESW render formula. Returns true for SW→NE diagonal.
/// Uses global cell coordinates (landblockX*8+cellX, landblockY*8+cellY).

View file

@ -2,9 +2,13 @@ using System;
using System.Collections.Concurrent;
using System.Numerics;
using DatReaderWriter;
using DatReaderWriter.Lib.IO;
using DatParticleEmitter = DatReaderWriter.DBObjs.ParticleEmitter;
using DatGfxObj = DatReaderWriter.DBObjs.GfxObj;
using DatGfxObjDegradeInfo = DatReaderWriter.DBObjs.GfxObjDegradeInfo;
using DatEmitterType = DatReaderWriter.Enums.EmitterType;
using DatParticleType = DatReaderWriter.Enums.ParticleType;
using DatGfxObjFlags = DatReaderWriter.Enums.GfxObjFlags;
namespace AcDream.Core.Vfx;
@ -15,6 +19,7 @@ namespace AcDream.Core.Vfx;
public sealed class EmitterDescRegistry
{
private readonly Func<uint, DatParticleEmitter?>? _resolver;
private readonly Func<DatParticleEmitter, float?>? _degradeDistanceResolver;
private readonly ConcurrentDictionary<uint, EmitterDesc> _byId = new();
public EmitterDescRegistry()
@ -23,8 +28,10 @@ public sealed class EmitterDescRegistry
}
public EmitterDescRegistry(DatCollection dats)
: this(id => SafeGet(dats, id))
{
ArgumentNullException.ThrowIfNull(dats);
_resolver = id => SafeGet<DatParticleEmitter>(dats, id);
_degradeDistanceResolver = emitter => ResolveMaxDegradeDistance(dats, emitter);
}
public EmitterDescRegistry(Func<uint, DatParticleEmitter?>? resolver)
@ -55,7 +62,18 @@ public sealed class EmitterDescRegistry
var dat = _resolver(emitterId);
if (dat is not null)
{
desc = FromDat(emitterId, dat);
float? resolvedDistance = _degradeDistanceResolver?.Invoke(dat);
if (_degradeDistanceResolver is not null && !resolvedDistance.HasValue)
{
// ParticleEmitter::SetInfo (0x0051CE90) fails when the
// authored hardware GfxObj cannot be loaded. It never
// substitutes the software GfxObj.
desc = null!;
return false;
}
float maxDegradeDistance = resolvedDistance
?? RetailParticleDegradeDistance.DefaultDistance;
desc = FromDat(emitterId, dat, maxDegradeDistance);
_byId[emitterId] = desc;
return true;
}
@ -66,7 +84,10 @@ public sealed class EmitterDescRegistry
public int Count => _byId.Count;
public static EmitterDesc FromDat(uint emitterId, DatParticleEmitter dat)
public static EmitterDesc FromDat(
uint emitterId,
DatParticleEmitter dat,
float maxDegradeDistance = RetailParticleDegradeDistance.DefaultDistance)
{
ArgumentNullException.ThrowIfNull(dat);
@ -90,6 +111,7 @@ public sealed class EmitterDescRegistry
return new EmitterDesc
{
MaxDegradeDistance = maxDegradeDistance,
DatId = emitterId,
Type = MapParticleType(dat.ParticleType),
EmitterKind = MapEmitterKind(dat.EmitterType),
@ -132,13 +154,37 @@ public sealed class EmitterDescRegistry
};
}
private static DatParticleEmitter? SafeGet(DatCollection dats, uint id)
private static float? ResolveMaxDegradeDistance(
DatCollection dats,
DatParticleEmitter emitter)
{
uint gfxObjId = GetRetailHardwareGfxObjId(emitter);
if (gfxObjId == 0)
return null;
DatGfxObj? gfx = SafeGet<DatGfxObj>(dats, gfxObjId);
if (gfx is null)
return null;
if (!gfx.Flags.HasFlag(DatGfxObjFlags.HasDIDDegrade)
|| gfx.DIDDegrade == 0)
{
return RetailParticleDegradeDistance.DefaultDistance;
}
DatGfxObjDegradeInfo? degrade = SafeGet<DatGfxObjDegradeInfo>(dats, gfx.DIDDegrade);
return RetailParticleDegradeDistance.FromEntries(degrade?.Degrades);
}
internal static uint GetRetailHardwareGfxObjId(DatParticleEmitter emitter)
=> emitter.HwGfxObjId.DataId;
private static T? SafeGet<T>(DatCollection dats, uint id) where T : class, IDBObj
{
if (dats is null)
return null;
try
{
return dats.Get<DatParticleEmitter>(id);
return dats.Get<T>(id);
}
catch
{
@ -170,3 +216,24 @@ public sealed class EmitterDescRegistry
_ => ParticleType.Unknown,
};
}
/// <summary>
/// Exact retail maximum-distance selection for a particle GfxObj.
/// <c>CPhysicsPart::GetMaxDegradeDistance</c> (0x0050D510) supplies the
/// 100-unit default; <c>GfxObjDegradeInfo::get_max_degrade_distance</c>
/// (0x0051E2D0) selects entry zero for one/two-entry tables and the
/// second-to-last entry for larger tables.
/// </summary>
public static class RetailParticleDegradeDistance
{
public const float DefaultDistance = 100f;
public static float FromEntries(IReadOnlyList<DatReaderWriter.Types.GfxObjInfo>? entries)
{
if (entries is null || entries.Count == 0)
return DefaultDistance;
int index = entries.Count <= 2 ? 0 : entries.Count - 2;
return entries[index].MaxDist;
}
}

View file

@ -28,15 +28,18 @@ public sealed class ParticleHookSink : IAnimationHookSink
{
private readonly ParticleSystem _system;
private readonly IEntityEffectPoseSource _poses;
private readonly IEntityEffectCellSource? _cells;
private readonly ConcurrentDictionary<(uint EntityId, uint EmitterId), int> _handlesByKey = new();
private readonly ConcurrentDictionary<uint, ConcurrentDictionary<int, byte>> _handlesByEntity = new();
private readonly ConcurrentDictionary<int, EmitterBinding> _bindingsByHandle = new();
private readonly ConcurrentDictionary<uint, ParticleRenderPass> _renderPassByEntity = new();
private readonly ConcurrentDictionary<uint, byte> _examinationOwners = new();
private readonly ConcurrentDictionary<uint, byte> _hiddenPresentationOwners = new();
public ParticleHookSink(ParticleSystem system, IEntityEffectPoseSource poses)
{
_system = system ?? throw new ArgumentNullException(nameof(system));
_poses = poses ?? throw new ArgumentNullException(nameof(poses));
_cells = poses as IEntityEffectCellSource;
_system.EmitterDied += OnEmitterDied;
}
@ -52,6 +55,7 @@ public sealed class ParticleHookSink : IAnimationHookSink
public int LogicalEmitterCount => _handlesByKey.Count;
public int TrackedOwnerCount => _handlesByEntity.Count;
public int RenderPassOwnerCount => _renderPassByEntity.Count;
public int ExaminationOwnerCount => _examinationOwners.Count;
public int HiddenPresentationOwnerCount => _hiddenPresentationOwners.Count;
private void OnEmitterDied(int handle)
@ -115,11 +119,32 @@ public sealed class ParticleHookSink : IAnimationHookSink
}
}
public void SetEntityRenderPass(uint entityId, ParticleRenderPass renderPass) =>
public void SetEntityRenderPass(uint entityId, ParticleRenderPass renderPass)
{
_renderPassByEntity[entityId] = renderPass;
RefreshOwnerVisibilityPolicy(entityId);
}
public void ClearEntityRenderPass(uint entityId) =>
public void ClearEntityRenderPass(uint entityId)
{
_renderPassByEntity.TryRemove(entityId, out _);
RefreshOwnerVisibilityPolicy(entityId);
}
/// <summary>
/// Mirrors retail <c>CPhysicsObj::m_bExaminationObject</c>. Examination
/// previews bypass world distance and cell visibility without conflating
/// that policy with attachment identity.
/// </summary>
public void SetEntityExaminationObject(uint entityId, bool isExaminationObject)
{
if (isExaminationObject)
_examinationOwners[entityId] = 0;
else
_examinationOwners.TryRemove(entityId, out _);
RefreshOwnerVisibilityPolicy(entityId);
}
/// <summary>
/// Mirrors live cell membership without ending emitter lifetime. Retail
@ -158,9 +183,18 @@ public sealed class ParticleHookSink : IAnimationHookSink
bool presentationVisible =
!_hiddenPresentationOwners.ContainsKey(binding.OwnerLocalId);
if (TryResolveAnchor(binding.OwnerLocalId, binding.PartIndex,
binding.HookOffsetOrigin, out Vector3 anchor, out Quaternion rotation))
binding.HookOffsetOrigin,
out Vector3 anchor,
out Quaternion rotation,
out Vector3 ownerPosition))
{
_system.UpdateEmitterAnchor(handle, anchor, rotation);
_system.UpdateEmitterOwnerPosition(handle, ownerPosition);
_system.UpdateEmitterOwnerCell(
handle,
_cells is not null && _cells.TryGetCellId(binding.OwnerLocalId, out uint cellId)
? cellId
: 0u);
// Keep the anchor current while spatially paused; re-entry
// resumes at the authoritative pose without generating the
// absent interval's time- or distance-driven emissions.
@ -193,6 +227,7 @@ public sealed class ParticleHookSink : IAnimationHookSink
_handlesByKey.TryRemove(key, out _);
}
ClearEntityRenderPass(entityId);
_examinationOwners.TryRemove(entityId, out _);
_hiddenPresentationOwners.TryRemove(entityId, out _);
}
@ -236,7 +271,9 @@ public sealed class ParticleHookSink : IAnimationHookSink
Vector3 offsetOrigin = offset?.Origin ?? Vector3.Zero;
Quaternion offsetOrientation = offset?.Orientation ?? Quaternion.Identity;
if (!TryResolveAnchor(ownerLocalId, partIndex, offsetOrigin,
out Vector3 anchor, out Quaternion rotation))
out Vector3 anchor,
out Quaternion rotation,
out Vector3 ownerPosition))
{
DiagnosticSink?.Invoke(
$"No live effect pose for owner 0x{ownerLocalId:X8}, part {partIndex}; " +
@ -247,6 +284,7 @@ public sealed class ParticleHookSink : IAnimationHookSink
ParticleRenderPass renderPass = _renderPassByEntity.TryGetValue(ownerLocalId, out var pass)
? pass
: ParticleRenderPass.Scene;
ParticleVisibilityPolicy visibilityPolicy = ResolveVisibilityPolicy(ownerLocalId);
if (!_system.TrySpawnEmitterById(
emitterInfoId,
anchor,
@ -254,6 +292,7 @@ public sealed class ParticleHookSink : IAnimationHookSink
ownerLocalId,
partIndex,
renderPass,
visibilityPolicy,
out int handle))
{
DiagnosticSink?.Invoke(
@ -261,6 +300,12 @@ public sealed class ParticleHookSink : IAnimationHookSink
$"0x{ownerLocalId:X8} was not found; no fallback was created.");
return;
}
_system.UpdateEmitterOwnerPosition(handle, ownerPosition);
_system.UpdateEmitterOwnerCell(
handle,
_cells is not null && _cells.TryGetCellId(ownerLocalId, out uint cellId)
? cellId
: 0u);
if (_hiddenPresentationOwners.ContainsKey(ownerLocalId))
{
_system.SetEmitterPresentationVisible(handle, false);
@ -282,20 +327,45 @@ public sealed class ParticleHookSink : IAnimationHookSink
_handlesByKey[(ownerLocalId, logicalId)] = handle;
}
private ParticleVisibilityPolicy ResolveVisibilityPolicy(uint ownerLocalId)
{
if (_examinationOwners.ContainsKey(ownerLocalId))
return ParticleVisibilityPolicy.Examination;
return _renderPassByEntity.TryGetValue(ownerLocalId, out ParticleRenderPass pass)
&& pass != ParticleRenderPass.Scene
? ParticleVisibilityPolicy.PassOwned
: ParticleVisibilityPolicy.World;
}
private void RefreshOwnerVisibilityPolicy(uint ownerLocalId)
{
if (!_handlesByEntity.TryGetValue(ownerLocalId, out var handles))
return;
ParticleVisibilityPolicy policy = ResolveVisibilityPolicy(ownerLocalId);
foreach (int handle in handles.Keys)
_system.SetEmitterVisibilityPolicy(handle, policy);
}
private bool TryResolveAnchor(
uint ownerLocalId,
int partIndex,
Vector3 offsetOrigin,
out Vector3 anchor,
out Quaternion rotation)
out Quaternion rotation,
out Vector3 ownerPosition)
{
if (!_poses.TryGetRootPose(ownerLocalId, out Matrix4x4 rootWorld))
{
anchor = default;
rotation = default;
ownerPosition = default;
return false;
}
ownerPosition = new Vector3(rootWorld.M41, rootWorld.M42, rootWorld.M43);
Matrix4x4 ownerFrame = rootWorld;
if (partIndex != -1)
{
@ -303,6 +373,7 @@ public sealed class ParticleHookSink : IAnimationHookSink
{
anchor = default;
rotation = default;
ownerPosition = default;
return false;
}
ownerFrame = partLocal * rootWorld;
@ -313,6 +384,7 @@ public sealed class ParticleHookSink : IAnimationHookSink
{
anchor = default;
rotation = default;
ownerPosition = default;
return false;
}
rotation = Quaternion.Normalize(rotation);

View file

@ -35,7 +35,8 @@ public sealed class ParticleSystem : IParticleSystem
Quaternion? rot = null,
uint attachedObjectId = 0,
int attachedPartIndex = -1,
ParticleRenderPass renderPass = ParticleRenderPass.Scene)
ParticleRenderPass renderPass = ParticleRenderPass.Scene,
ParticleVisibilityPolicy visibilityPolicy = ParticleVisibilityPolicy.World)
{
ArgumentNullException.ThrowIfNull(desc);
@ -45,10 +46,12 @@ public sealed class ParticleSystem : IParticleSystem
Handle = handle,
Desc = desc,
AnchorPos = anchor,
OwnerPosition = anchor,
AnchorRot = rot ?? Quaternion.Identity,
AttachedObjectId = attachedObjectId,
AttachedPartIndex = attachedPartIndex,
RenderPass = renderPass,
VisibilityPolicy = visibilityPolicy,
Particles = new Particle[Math.Max(1, desc.MaxParticles)],
StartedAt = _time,
LastEmitTime = _time,
@ -70,10 +73,18 @@ public sealed class ParticleSystem : IParticleSystem
Quaternion? rot = null,
uint attachedObjectId = 0,
int attachedPartIndex = -1,
ParticleRenderPass renderPass = ParticleRenderPass.Scene)
ParticleRenderPass renderPass = ParticleRenderPass.Scene,
ParticleVisibilityPolicy visibilityPolicy = ParticleVisibilityPolicy.World)
{
var desc = _registry.Get(emitterId);
return SpawnEmitter(desc, anchor, rot, attachedObjectId, attachedPartIndex, renderPass);
return SpawnEmitter(
desc,
anchor,
rot,
attachedObjectId,
attachedPartIndex,
renderPass,
visibilityPolicy);
}
public bool TrySpawnEmitterById(
@ -83,6 +94,7 @@ public sealed class ParticleSystem : IParticleSystem
uint attachedObjectId,
int attachedPartIndex,
ParticleRenderPass renderPass,
ParticleVisibilityPolicy visibilityPolicy,
out int handle)
{
if (!_registry.TryGet(emitterId, out EmitterDesc? desc))
@ -97,7 +109,8 @@ public sealed class ParticleSystem : IParticleSystem
rot,
attachedObjectId,
attachedPartIndex,
renderPass);
renderPass,
visibilityPolicy);
return true;
}
@ -116,6 +129,7 @@ public sealed class ParticleSystem : IParticleSystem
{
for (int i = 0; i < em.Particles.Length; i++)
em.Particles[i].Alive = false;
em.ActiveCount = 0;
// Retail DestroyParticleEmitter removes the table entry now; it
// does not wait for the next update. This is also required for a
// hard-stopped emitter whose cell-less simulation is paused.
@ -145,6 +159,77 @@ public sealed class ParticleSystem : IParticleSystem
em.AnchorRot = rot.Value;
}
/// <summary>
/// Refreshes the owning physics object's root used by retail's particle
/// degradation-distance check. This remains distinct from an animated
/// part's emitter anchor.
/// </summary>
public void UpdateEmitterOwnerPosition(int handle, Vector3 ownerPosition)
{
if (_byHandle.TryGetValue(handle, out ParticleEmitter? emitter))
emitter.OwnerPosition = ownerPosition;
}
public void UpdateEmitterOwnerCell(int handle, uint ownerCellId)
{
if (_byHandle.TryGetValue(handle, out ParticleEmitter? emitter))
emitter.OwnerCellId = ownerCellId;
}
public void SetEmitterVisibilityPolicy(
int handle,
ParticleVisibilityPolicy visibilityPolicy)
{
if (_byHandle.TryGetValue(handle, out ParticleEmitter? emitter))
emitter.VisibilityPolicy = visibilityPolicy;
}
/// <summary>
/// Applies <c>CPhysicsObj::ShouldDrawParticles</c> (0x0050FE60) to every
/// live emitter. The App layer supplies the previous completed retail
/// PView's cell set, equivalent to <c>CObjCell::IsInView</c> when the next
/// physics update runs.
/// </summary>
public void ApplyRetailView(
Vector3 viewerPosition,
IReadOnlySet<uint> visibleCellIds,
bool hasCompletedView,
float rangeMultiplier = 1f)
{
ArgumentNullException.ThrowIfNull(visibleCellIds);
if (!float.IsFinite(rangeMultiplier) || rangeMultiplier <= 0f)
rangeMultiplier = 1f;
foreach (int handle in _handleOrder)
{
if (!_byHandle.TryGetValue(handle, out ParticleEmitter? emitter))
continue;
if (emitter.VisibilityPolicy != ParticleVisibilityPolicy.World)
{
emitter.ViewEligible = true;
continue;
}
if (!hasCompletedView)
{
// With no completed world PView (portal space, login, or a
// reset frame), a world cell cannot report IsInView.
emitter.ViewEligible = false;
continue;
}
float maxDistance = emitter.Desc.MaxDegradeDistance * rangeMultiplier;
float distance = RetailDistance(emitter.OwnerPosition, viewerPosition);
emitter.ViewEligible = emitter.OwnerCellId != 0
&& visibleCellIds.Contains(emitter.OwnerCellId)
// The x87 comparison in ShouldDrawParticles admits unordered
// comparisons (NaN) and reject a negative authored range.
&& (float.IsNaN(distance)
|| float.IsNaN(maxDistance)
|| distance <= maxDistance);
}
}
/// <summary>
/// Changes only render presentation. Logical lifetime is unaffected.
/// </summary>
@ -210,10 +295,19 @@ public sealed class ParticleSystem : IParticleSystem
continue;
if (!em.SimulationEnabled)
continue;
bool wasFinishedBeforeUpdate = em.Finished;
AdvanceEmitter(em);
int live = CountAlive(em);
em.ActiveCount = live;
if (em.ViewEligible)
{
em.DegradedOut = false;
AdvanceEmitter(em);
}
else
{
em.DegradedOut = true;
AdvanceDegradedEmitter(em, dt);
}
int live = em.ActiveCount;
_activeParticleCount += live;
if (em.Desc.TotalDuration > 0f && (_time - em.StartedAt) > em.Desc.TotalDuration)
@ -222,7 +316,10 @@ public sealed class ParticleSystem : IParticleSystem
if (em.Desc.TotalParticles > 0 && em.TotalEmitted >= em.Desc.TotalParticles)
em.Finished = true;
if (em.Finished && live == 0)
// UpdateParticles returns true on the exact tick StopEmitter
// first changes state. Only the next update's already-stopped
// branch may return num_particles == 0 and retire the emitter.
if (em.Finished && live == 0 && wasFinishedBeforeUpdate)
{
_byHandle.Remove(handle);
_handleOrder.RemoveAt(i);
@ -253,6 +350,66 @@ public sealed class ParticleSystem : IParticleSystem
/// </summary>
public LiveParticleEnumerable EnumerateLive() => new(this);
/// <summary>
/// Enumerates live emitters in spawn order. The renderer consumes this
/// before particle slots so pass/visibility rejection is O(emitters), not
/// O(all particles in every pass).
/// </summary>
public LiveEmitterEnumerable EnumerateEmitters() => new(this);
public readonly struct LiveEmitterEnumerable : IEnumerable<ParticleEmitter>
{
private readonly ParticleSystem _owner;
internal LiveEmitterEnumerable(ParticleSystem owner) => _owner = owner;
public Enumerator GetEnumerator() => new(_owner);
IEnumerator<ParticleEmitter> IEnumerable<ParticleEmitter>.GetEnumerator()
=> EnumerateBoxed(_owner).GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> EnumerateBoxed(_owner).GetEnumerator();
private static IEnumerable<ParticleEmitter> EnumerateBoxed(ParticleSystem owner)
{
foreach (int handle in owner._handleOrder)
{
if (owner._byHandle.TryGetValue(handle, out ParticleEmitter? emitter))
yield return emitter;
}
}
public struct Enumerator
{
private readonly ParticleSystem _owner;
private int _index;
internal Enumerator(ParticleSystem owner)
{
_owner = owner;
_index = -1;
Current = null!;
}
public ParticleEmitter Current { get; private set; }
public bool MoveNext()
{
while (++_index < _owner._handleOrder.Count)
{
if (_owner._byHandle.TryGetValue(
_owner._handleOrder[_index],
out ParticleEmitter? emitter))
{
Current = emitter;
return true;
}
}
return false;
}
}
}
/// <summary>
/// Struct enumerable returned by <see cref="EnumerateLive"/>. Wraps the
/// owning <see cref="ParticleSystem"/> so <c>foreach</c> gets a
@ -342,10 +499,11 @@ public sealed class ParticleSystem : IParticleSystem
if (!p.Alive)
continue;
p.Age = _time - p.SpawnedAt;
p.Age = EffectiveParticleAge(em, p);
if (p.Lifetime <= 0f || p.Age >= p.Lifetime)
{
p.Alive = false;
em.ActiveCount--;
continue;
}
@ -380,13 +538,63 @@ public sealed class ParticleSystem : IParticleSystem
}
}
/// <summary>
/// Retail <c>ParticleEmitter::UpdateParticles</c> (0x0051D180)
/// degraded branch. Infinite emitters freeze particle age without normal
/// updates or emissions. Finite emitters age/retire existing particles,
/// record at most one due emission without creating a drawable particle,
/// then run retail's conditional stop test.
/// </summary>
private void AdvanceDegradedEmitter(ParticleEmitter em, float dt)
{
bool infinite = em.Desc.TotalParticles == 0 && em.Desc.TotalDuration == 0f;
if (infinite)
{
em.FrozenTime += dt;
// Callback-created descriptors sometimes use the legacy EmitRate
// representation. Rebase that accumulator so it cannot synthesize
// a catch-up burst after degradation; retail performs no backlog.
if (em.Desc.Birthrate <= 0f && em.Desc.EmitRate > 0f)
{
em.LastEmitTime = _time;
em.EmittedAccumulator = 0f;
}
return;
}
for (int i = 0; i < em.Particles.Length; i++)
{
ref Particle particle = ref em.Particles[i];
if (!particle.Alive)
continue;
particle.Age = _time - particle.SpawnedAt;
if (particle.Lifetime <= 0f || particle.Age >= particle.Lifetime)
{
particle.Alive = false;
em.ActiveCount--;
}
}
if (!em.Finished && ShouldEmitParticle(em))
{
// ParticleEmitter::RecordParticleEmission (0x0051C870) advances
// both num_particles and total_emitted while degraded, but no
// PhysicsPart is made visible.
em.ActiveCount++;
em.TotalEmitted++;
em.LastEmitTime = _time;
em.LastEmitOffset = em.AnchorPos;
}
}
private bool ShouldEmitParticle(ParticleEmitter em)
{
var desc = em.Desc;
if (desc.TotalParticles > 0 && em.TotalEmitted >= desc.TotalParticles)
return false;
if (CountAlive(em) >= desc.MaxParticles)
if (em.ActiveCount >= desc.MaxParticles)
return false;
if (desc.Birthrate <= 0f)
@ -410,9 +618,11 @@ public sealed class ParticleSystem : IParticleSystem
return false;
ref var particle = ref em.Particles[slot];
bool replacesLiveParticle = particle.Alive;
particle = default;
particle.Alive = true;
particle.SpawnedAt = _time;
particle.FrozenTimeAtSpawn = em.FrozenTime;
particle.Lifetime = RandomLifespan(em.Desc);
particle.EmissionOrigin = em.AnchorPos;
particle.SpawnRotation = em.AnchorRot;
@ -448,11 +658,17 @@ public sealed class ParticleSystem : IParticleSystem
particle.Position = ComputePosition(em, particle);
em.TotalEmitted++;
if (!replacesLiveParticle)
em.ActiveCount++;
em.LastEmitTime = _time;
em.LastEmitOffset = em.AnchorPos;
return true;
}
private float EffectiveParticleAge(ParticleEmitter emitter, in Particle particle)
=> _time - particle.SpawnedAt
- (emitter.FrozenTime - particle.FrozenTimeAtSpawn);
private Vector3 ComputePosition(ParticleEmitter em, Particle p)
{
float t = p.Age;
@ -599,16 +815,22 @@ public sealed class ParticleSystem : IParticleSystem
return slot;
}
private static int CountAlive(ParticleEmitter em)
private static float RetailDistance(Vector3 a, Vector3 b)
{
int n = 0;
for (int i = 0; i < em.Particles.Length; i++)
{
if (em.Particles[i].Alive)
n++;
}
// Overflow-safe Euclidean length. Vector3.DistanceSquared overflows
// for finite coordinates near FLT_MAX, whereas retail compares its
// already-computed direct distance against max_dist.
float dx = a.X - b.X;
float dy = a.Y - b.Y;
float dz = a.Z - b.Z;
float scale = MathF.Max(MathF.Abs(dx), MathF.Max(MathF.Abs(dy), MathF.Abs(dz)));
if (float.IsNaN(scale) || float.IsInfinity(scale) || scale == 0f)
return scale;
return n;
dx /= scale;
dy /= scale;
dz /= scale;
return scale * MathF.Sqrt(dx * dx + dy * dy + dz * dz);
}
private float RandomLifespan(EmitterDesc desc)

View file

@ -46,6 +46,18 @@ public enum ParticleRenderPass
SkyPostScene = 2,
}
/// <summary>
/// Authority used by retail's particle presentation gate. World-owned
/// emitters follow <c>CPhysicsObj::ShouldDrawParticles</c>; examination and
/// dedicated render-pass emitters are explicitly exempt from world PView.
/// </summary>
public enum ParticleVisibilityPolicy
{
World = 0,
Examination = 1,
PassOwned = 2,
}
[Flags]
public enum EmitterFlags : uint
{
@ -62,6 +74,12 @@ public enum EmitterFlags : uint
/// </summary>
public sealed class EmitterDesc
{
/// <summary>
/// Retail distance at which the owning physics object degrades this
/// emitter out. Sourced from the hardware particle GfxObj's degradation
/// table by <c>CPhysicsPart::GetMaxDegradeDistance</c> (0x0050D510).
/// </summary>
public float MaxDegradeDistance { get; init; } = 100f;
public uint DatId { get; init; }
public ParticleType Type { get; init; }
public ParticleEmitterKind EmitterKind { get; init; } = ParticleEmitterKind.BirthratePerSec;
@ -158,6 +176,12 @@ public struct Particle
public Vector3 B;
public Vector3 C;
public float SpawnedAt;
/// <summary>
/// Emitter-level frozen time at birth. This lets an infinite degraded
/// emitter freeze every particle's age in O(1), equivalent to retail
/// rewriting every live particle birth time to the current game time.
/// </summary>
public float FrozenTimeAtSpawn;
public float Lifetime;
public float Age;
public float StartSize;
@ -184,9 +208,22 @@ public sealed class ParticleEmitter
public int Handle { get; init; }
public EmitterDesc Desc { get; init; } = null!;
public Vector3 AnchorPos { get; set; }
/// <summary>
/// Root position of the owning physics object. Retail measures particle
/// degradation from the owner (<c>CPhysicsObj::CYpt</c>), not from an
/// animated hand/part hook offset.
/// </summary>
public Vector3 OwnerPosition { get; set; }
/// <summary>Current owning AC cell for retail <c>IsInView</c> gating.</summary>
public uint OwnerCellId { get; set; }
public Quaternion AnchorRot { get; set; } = Quaternion.Identity;
public uint AttachedObjectId { get; set; }
/// <summary>
/// Explicit presentation context. Retail's examination-object bypass is
/// object state, not an inference from attachment identity.
/// </summary>
public ParticleVisibilityPolicy VisibilityPolicy { get; set; }
/// <summary>
/// Spatial presentation latch. A cell-less owner submits no particles.
/// </summary>
public bool PresentationVisible { get; set; } = true;
@ -195,6 +232,13 @@ public sealed class ParticleEmitter
/// particles, logical identity, and elapsed-time position until re-entry.
/// </summary>
public bool SimulationEnabled { get; set; } = true;
/// <summary>
/// Result of retail <c>CPhysicsObj::ShouldDrawParticles</c>: authored
/// distance plus the previous completed PView's visibility state.
/// </summary>
public bool ViewEligible { get; set; } = true;
/// <summary>Retail <c>ParticleEmitter::degraded_out</c> latch.</summary>
public bool DegradedOut { get; set; }
public int AttachedPartIndex { get; set; } = -1;
public Particle[] Particles { get; init; } = null!;
public ParticleRenderPass RenderPass { get; init; }
@ -202,6 +246,11 @@ public sealed class ParticleEmitter
public float EmittedAccumulator;
public float StartedAt;
public float LastEmitTime;
/// <summary>
/// Total time this infinite emitter spent degraded. Particles subtract
/// the delta since their own birth rather than being rewritten one by one.
/// </summary>
public float FrozenTime;
public Vector3 LastEmitOffset;
public int TotalEmitted;
public bool Finished;
@ -219,7 +268,8 @@ public interface IParticleSystem
Quaternion? rot = null,
uint attachedObjectId = 0,
int attachedPartIndex = -1,
ParticleRenderPass renderPass = ParticleRenderPass.Scene);
ParticleRenderPass renderPass = ParticleRenderPass.Scene,
ParticleVisibilityPolicy visibilityPolicy = ParticleVisibilityPolicy.World);
/// <summary>Fire a full PhysicsScript at a target.</summary>
void PlayScript(uint scriptId, uint targetObjectId, float modifier = 1f);

View file

@ -1,6 +1,7 @@
using DatReaderWriter;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Types;
using AcDream.Core.Physics;
namespace AcDream.Core.World;
@ -74,6 +75,7 @@ public static class LandblockLoader
Position = stab.Frame.Origin,
Rotation = stab.Frame.Orientation,
MeshRefs = Array.Empty<MeshRef>(),
EffectCellId = OutdoorCellId(landblockId, stab.Frame.Origin),
};
stabEntity.RefreshAabb(); // A.5 T18: populate cached AABB at construction
result.Add(stabEntity);
@ -90,6 +92,7 @@ public static class LandblockLoader
Position = building.Frame.Origin,
Rotation = building.Frame.Orientation,
MeshRefs = Array.Empty<MeshRef>(),
EffectCellId = OutdoorCellId(landblockId, building.Frame.Origin),
IsBuildingShell = true, // Phase A8: tag at source array boundary
BuildingShellAnchorCellId = FirstBuildingAnchorCellId(building, landblockId),
};
@ -106,6 +109,17 @@ public static class LandblockLoader
return type == GfxObjMask || type == SetupMask;
}
private static uint? OutdoorCellId(uint landblockId, System.Numerics.Vector3 localPosition)
{
if (landblockId == 0)
return null;
return TerrainSurface.ComputeOutdoorCellId(
landblockId,
localPosition.X,
localPosition.Y);
}
private static uint? FirstBuildingAnchorCellId(BuildingInfo building, uint landblockId)
{
if (landblockId == 0)

View file

@ -92,6 +92,15 @@ public sealed class WorldEntity
/// </summary>
public uint? ParentCellId { get; set; }
/// <summary>
/// Owning AC cell used by entity-attached effects. This is separate from
/// <see cref="ParentCellId"/> because outdoor dat stabs deliberately keep
/// a null render parent while retail still gives their physics object an
/// outdoor landcell for <c>CObjCell::IsInView</c> particle gating.
/// Live/interior entities normally use <see cref="ParentCellId"/> instead.
/// </summary>
public uint? EffectCellId { get; set; }
/// <summary>
/// True when this entity originates from <c>LandBlockInfo.Buildings[]</c>
/// (the dat array that carries building shells: cottage walls, smithy walls,

View file

@ -3,6 +3,17 @@ using AcDream.UI.Abstractions.Settings;
namespace AcDream.UI.Abstractions.Panels.Settings;
/// <summary>
/// Particle visibility distance policy. Retail uses the GfxObj-authored
/// distance exactly; Extended is an explicit acdream adaptation for players
/// who prefer longer-lived distant effects with the corresponding CPU cost.
/// </summary>
public enum ParticleRange
{
Retail = 0,
Extended = 1,
}
/// <summary>
/// Display-related preferences persisted to <c>settings.json</c>.
/// Modern addition (no retail equivalent for FOV / vsync etc) — replaces
@ -22,7 +33,8 @@ public sealed record DisplaySettings(
float FieldOfView,
float Gamma,
bool ShowFps,
QualityPreset Quality)
QualityPreset Quality,
ParticleRange ParticleRange)
{
/// <summary>Values used on first launch / when settings.json is absent.
/// Geometry/render defaults preserve the pre-L.0 runtime state — Resolution
@ -36,7 +48,8 @@ public sealed record DisplaySettings(
FieldOfView: 60f,
Gamma: 1.0f,
ShowFps: false,
Quality: QualityPreset.High);
Quality: QualityPreset.High,
ParticleRange: ParticleRange.Retail);
/// <summary>16:9 resolution presets offered in the dropdown.</summary>
public static IReadOnlyList<string> AvailableResolutions { get; } = new[]

View file

@ -236,12 +236,20 @@ public sealed class SettingsPanel : IPanel
if (renderer.Combo("Quality", ref qIdx, presets))
_vm.SetDisplay(d with { Quality = (QualityPreset)qIdx });
int particleRangeIndex = (int)d.ParticleRange;
if (particleRangeIndex < 0 || particleRangeIndex >= s_particleRangeNames.Length)
particleRangeIndex = (int)ParticleRange.Retail;
if (renderer.Combo("Particle Range", ref particleRangeIndex, s_particleRangeNames))
_vm.SetDisplay(d with { ParticleRange = (ParticleRange)particleRangeIndex });
renderer.Spacing();
renderer.TextWrapped(
"Resolution / Fullscreen / V-Sync apply on Save. FOV + Gamma "
+ "preview live as you drag; Cancel reverts to the saved value. "
+ "Quality preset applies streaming radius, anisotropic, and A2C "
+ "immediately on Save; MSAA sample count requires a restart.");
+ "immediately on Save; MSAA sample count requires a restart. "
+ "Particle Range defaults to retail-authored distances; Extended "
+ "doubles effect range and costs additional CPU time.");
}
/// <summary>
@ -474,6 +482,9 @@ public sealed class SettingsPanel : IPanel
private static readonly string[] s_qualityPresetNames =
{ "Low", "Medium", "High", "Ultra" };
private static readonly string[] s_particleRangeNames =
{ "Retail", "Extended" };
private void RenderSection(IPanelRenderer renderer, string label, InputAction[] actions)
{
// Movement defaults open; other sections collapsed for first-run UX.

View file

@ -73,7 +73,9 @@ public sealed class SettingsStore
FieldOfView: ReadFloat (disp, "fieldOfView", d.FieldOfView),
Gamma: ReadFloat (disp, "gamma", d.Gamma),
ShowFps: ReadBool (disp, "showFps", d.ShowFps),
Quality: ReadQuality (disp, "quality", d.Quality));
Quality: ReadQuality (disp, "quality", d.Quality),
ParticleRange: ReadParticleRange(
disp, "particleRange", d.ParticleRange));
}
catch (Exception ex)
{
@ -569,6 +571,7 @@ public sealed class SettingsStore
["fieldOfView"] = d.FieldOfView,
["fullscreen"] = d.Fullscreen,
["gamma"] = d.Gamma,
["particleRange"] = d.ParticleRange.ToString(),
["quality"] = d.Quality.ToString(),
["resolution"] = d.Resolution,
["showFps"] = d.ShowFps,
@ -656,4 +659,18 @@ public sealed class SettingsStore
var s = el.GetString();
return Enum.TryParse<QualityPreset>(s, ignoreCase: true, out var v) ? v : fallback;
}
private static ParticleRange ReadParticleRange(
JsonElement obj,
string name,
ParticleRange fallback)
{
if (!obj.TryGetProperty(name, out var el) || el.ValueKind != JsonValueKind.String)
return fallback;
var value = el.GetString();
return Enum.TryParse(value, ignoreCase: true, out ParticleRange parsed)
&& Enum.IsDefined(parsed)
? parsed
: fallback;
}
}