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>
This commit is contained in:
parent
1f82b7604e
commit
ec1bbb4f43
28 changed files with 2444 additions and 780 deletions
|
|
@ -5,33 +5,18 @@ using System.Numerics;
|
|||
namespace AcDream.Core.Vfx;
|
||||
|
||||
/// <summary>
|
||||
/// Runtime particle orchestrator — port of retail's <c>CParticleManager</c>
|
||||
/// (r04 §2). Owns a pool of active <see cref="ParticleEmitter"/> instances,
|
||||
/// advances each per-frame via one of 13 motion integrators, fades colour /
|
||||
/// scale over life, and exposes a flat particle stream for the renderer.
|
||||
///
|
||||
/// <para>
|
||||
/// Not thread-safe — called only from the render thread (same thread that
|
||||
/// drives TickAnimations).
|
||||
/// </para>
|
||||
///
|
||||
/// <para>
|
||||
/// Handle-based API so callers can stop a specific emitter later (cast
|
||||
/// interrupt, fadeout). <see cref="SpawnEmitter"/> returns a positive
|
||||
/// integer; <see cref="StopEmitter"/> accepts it.
|
||||
/// </para>
|
||||
/// Runtime particle orchestrator. The data and update rules are a direct
|
||||
/// port of retail's <c>ParticleEmitterInfo</c>, <c>ParticleEmitter</c>, and
|
||||
/// <c>Particle::Update</c> paths from the named retail decompilation.
|
||||
/// </summary>
|
||||
public sealed class ParticleSystem : IParticleSystem
|
||||
{
|
||||
private readonly EmitterDescRegistry _registry;
|
||||
private readonly Random _rng;
|
||||
|
||||
// All live emitters keyed by our handle. Lookup is cheap; iteration is
|
||||
// per-frame so we also keep a flat list for stable ordering (draw order).
|
||||
private readonly Dictionary<int, ParticleEmitter> _byHandle = new();
|
||||
private readonly List<int> _handleOrder = new();
|
||||
private int _nextHandle = 1;
|
||||
|
||||
private int _nextHandle = 1;
|
||||
private float _time;
|
||||
private int _activeParticleCount;
|
||||
|
||||
|
|
@ -49,7 +34,8 @@ public sealed class ParticleSystem : IParticleSystem
|
|||
Vector3 anchor,
|
||||
Quaternion? rot = null,
|
||||
uint attachedObjectId = 0,
|
||||
int attachedPartIndex = -1)
|
||||
int attachedPartIndex = -1,
|
||||
ParticleRenderPass renderPass = ParticleRenderPass.Scene)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(desc);
|
||||
|
||||
|
|
@ -61,43 +47,45 @@ public sealed class ParticleSystem : IParticleSystem
|
|||
AnchorRot = rot ?? Quaternion.Identity,
|
||||
AttachedObjectId = attachedObjectId,
|
||||
AttachedPartIndex = attachedPartIndex,
|
||||
RenderPass = renderPass,
|
||||
Particles = new Particle[Math.Max(1, desc.MaxParticles)],
|
||||
StartedAt = _time,
|
||||
LastEmitTime = _time,
|
||||
LastEmitOffset = anchor,
|
||||
};
|
||||
|
||||
_byHandle[handle] = emitter;
|
||||
_handleOrder.Add(handle);
|
||||
|
||||
for (int i = 0; i < desc.InitialParticles; i++)
|
||||
SpawnOne(emitter, allowWhenFull: false);
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convenience: spawn by retail emitter id — the registry resolves to
|
||||
/// the correct <see cref="EmitterDesc"/>, or falls back to the default
|
||||
/// if unknown. Used by the hook sink when a CreateParticleHook arrives.
|
||||
/// </summary>
|
||||
public int SpawnEmitterById(
|
||||
uint emitterId,
|
||||
Vector3 anchor,
|
||||
Quaternion? rot = null,
|
||||
uint attachedObjectId = 0,
|
||||
int attachedPartIndex = -1)
|
||||
int attachedPartIndex = -1,
|
||||
ParticleRenderPass renderPass = ParticleRenderPass.Scene)
|
||||
{
|
||||
var desc = _registry.Get(emitterId);
|
||||
return SpawnEmitter(desc, anchor, rot, attachedObjectId, attachedPartIndex);
|
||||
return SpawnEmitter(desc, anchor, rot, attachedObjectId, attachedPartIndex, renderPass);
|
||||
}
|
||||
|
||||
public void PlayScript(uint scriptId, uint targetObjectId, float modifier = 1f)
|
||||
{
|
||||
// Full PhysicsScript dispatch is on hold until the DatReaderWriter
|
||||
// library exposes ParticleEmitterInfo / PhysicsScript. For now,
|
||||
// this is a no-op — callers use SpawnEmitter or the hook sink.
|
||||
// Full PhysicsScript scheduling lives in PhysicsScriptRunner.
|
||||
}
|
||||
|
||||
public void StopEmitter(int handle, bool fadeOut)
|
||||
{
|
||||
if (!_byHandle.TryGetValue(handle, out var em)) return;
|
||||
if (!_byHandle.TryGetValue(handle, out var em))
|
||||
return;
|
||||
|
||||
em.Finished = true;
|
||||
// fadeOut=false would stop instantly; our renderer currently drops
|
||||
// Finished emitters that have no living particles each tick.
|
||||
if (!fadeOut)
|
||||
{
|
||||
for (int i = 0; i < em.Particles.Length; i++)
|
||||
|
|
@ -105,259 +93,454 @@ public sealed class ParticleSystem : IParticleSystem
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refresh an active emitter's world anchor + orientation. Required for
|
||||
/// retail's <c>is_parent_local=1</c> (acdream's
|
||||
/// <see cref="EmitterFlags.AttachLocal"/>) semantics: retail
|
||||
/// <c>ParticleEmitter::UpdateParticles</c> at <c>0x0051d2d4</c> reads the
|
||||
/// LIVE parent frame each tick when <c>is_parent_local != 0</c>. The
|
||||
/// caller (typically a tick loop tracking a moving parent — the camera
|
||||
/// for sky-PES, an entity for animation hooks) drives this every frame.
|
||||
/// </summary>
|
||||
public void UpdateEmitterAnchor(int handle, Vector3 anchor, Quaternion? rot = null)
|
||||
{
|
||||
if (!_byHandle.TryGetValue(handle, out var em))
|
||||
return;
|
||||
em.AnchorPos = anchor;
|
||||
if (rot.HasValue)
|
||||
em.AnchorRot = rot.Value;
|
||||
}
|
||||
|
||||
/// <summary>True when the given handle still maps to a live emitter.</summary>
|
||||
public bool IsEmitterAlive(int handle) => _byHandle.ContainsKey(handle);
|
||||
|
||||
/// <summary>
|
||||
/// Fired exactly once per emitter when it is removed from the live set
|
||||
/// (either because it finished naturally or was stopped without fade).
|
||||
/// Subscribers (e.g. <see cref="ParticleHookSink"/>) use this to prune
|
||||
/// per-entity handle tracking so the per-entity bag doesn't grow without
|
||||
/// bound during a long session.
|
||||
/// </summary>
|
||||
public event Action<int>? EmitterDied;
|
||||
|
||||
public void Tick(float dt)
|
||||
{
|
||||
if (dt <= 0f) return;
|
||||
if (dt <= 0f)
|
||||
return;
|
||||
|
||||
_time += dt;
|
||||
_activeParticleCount = 0;
|
||||
|
||||
// Iterate handles by a snapshot so StopEmitter-inside-emit is safe.
|
||||
for (int i = 0; i < _handleOrder.Count; i++)
|
||||
{
|
||||
int handle = _handleOrder[i];
|
||||
if (!_byHandle.TryGetValue(handle, out var em)) continue;
|
||||
if (!_byHandle.TryGetValue(handle, out var em))
|
||||
continue;
|
||||
|
||||
AdvanceEmitter(em, dt);
|
||||
_activeParticleCount += CountAlive(em);
|
||||
AdvanceEmitter(em);
|
||||
int live = CountAlive(em);
|
||||
em.ActiveCount = live;
|
||||
_activeParticleCount += live;
|
||||
|
||||
bool durationDone = em.Desc.TotalDuration > 0f
|
||||
&& (_time - em.StartedAt) > em.Desc.TotalDuration;
|
||||
if (durationDone) em.Finished = true;
|
||||
if (em.Desc.TotalDuration > 0f && (_time - em.StartedAt) > em.Desc.TotalDuration)
|
||||
em.Finished = true;
|
||||
|
||||
// Drop emitter entirely when it has no live particles AND is
|
||||
// marked finished (duration elapsed, StopEmitter, etc).
|
||||
if (em.Finished && CountAlive(em) == 0)
|
||||
if (em.Desc.TotalParticles > 0 && em.TotalEmitted >= em.Desc.TotalParticles)
|
||||
em.Finished = true;
|
||||
|
||||
if (em.Finished && live == 0)
|
||||
{
|
||||
_byHandle.Remove(handle);
|
||||
_handleOrder.RemoveAt(i);
|
||||
i--;
|
||||
EmitterDied?.Invoke(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enumerate every live particle with its emitter description for
|
||||
/// the renderer. Yields (emitter, particleIndex) so the caller can
|
||||
/// read <c>em.Particles[idx]</c> directly.
|
||||
/// </summary>
|
||||
public IEnumerable<(ParticleEmitter Emitter, int Index)> EnumerateLive()
|
||||
{
|
||||
foreach (var handle in _handleOrder)
|
||||
{
|
||||
if (!_byHandle.TryGetValue(handle, out var em)) continue;
|
||||
if (!_byHandle.TryGetValue(handle, out var em))
|
||||
continue;
|
||||
|
||||
for (int i = 0; i < em.Particles.Length; i++)
|
||||
{
|
||||
if (em.Particles[i].Alive) yield return (em, i);
|
||||
if (em.Particles[i].Alive)
|
||||
yield return (em, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Private: emission + integration ──────────────────────────────────────
|
||||
|
||||
private void AdvanceEmitter(ParticleEmitter em, float dt)
|
||||
private void AdvanceEmitter(ParticleEmitter em)
|
||||
{
|
||||
if (!em.Finished && em.Desc.EmitRate > 0f)
|
||||
{
|
||||
em.EmittedAccumulator += dt * em.Desc.EmitRate;
|
||||
while (em.EmittedAccumulator >= 1.0f)
|
||||
{
|
||||
em.EmittedAccumulator -= 1.0f;
|
||||
SpawnOne(em);
|
||||
}
|
||||
}
|
||||
|
||||
// Update every particle slot.
|
||||
for (int i = 0; i < em.Particles.Length; i++)
|
||||
{
|
||||
ref var p = ref em.Particles[i];
|
||||
if (!p.Alive) continue;
|
||||
if (!p.Alive)
|
||||
continue;
|
||||
|
||||
p.Age += dt;
|
||||
if (p.Age >= p.Lifetime)
|
||||
p.Age = _time - p.SpawnedAt;
|
||||
if (p.Lifetime <= 0f || p.Age >= p.Lifetime)
|
||||
{
|
||||
p.Alive = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
Integrate(ref p, em, dt);
|
||||
|
||||
p.Position = ComputePosition(em, p);
|
||||
float tLife = Math.Clamp(p.Age / p.Lifetime, 0f, 1f);
|
||||
p.Size = Lerp(em.Desc.StartSize, em.Desc.EndSize, tLife);
|
||||
float alpha = Lerp(em.Desc.StartAlpha, em.Desc.EndAlpha, tLife);
|
||||
p.Size = Lerp(p.StartSize, p.EndSize, tLife);
|
||||
p.Rotation = Lerp(em.Desc.StartRotation, em.Desc.EndRotation, tLife);
|
||||
float alpha = Lerp(p.StartAlpha, p.EndAlpha, tLife);
|
||||
p.ColorArgb = Color32(alpha, em.Desc.StartColorArgb, em.Desc.EndColorArgb, tLife);
|
||||
}
|
||||
|
||||
if (em.Finished || _time < em.StartedAt + em.Desc.StartDelay)
|
||||
return;
|
||||
|
||||
while (ShouldEmitParticle(em))
|
||||
{
|
||||
if (!SpawnOne(em, allowWhenFull: false))
|
||||
break;
|
||||
}
|
||||
|
||||
if (em.Desc.Birthrate <= 0f && em.Desc.EmitRate > 0f)
|
||||
{
|
||||
float dt = _time - em.LastEmitTime;
|
||||
em.EmittedAccumulator += dt * em.Desc.EmitRate;
|
||||
em.LastEmitTime = _time;
|
||||
while (em.EmittedAccumulator >= 1f)
|
||||
{
|
||||
em.EmittedAccumulator -= 1f;
|
||||
if (!SpawnOne(em, allowWhenFull: false))
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SpawnOne(ParticleEmitter em)
|
||||
private bool ShouldEmitParticle(ParticleEmitter em)
|
||||
{
|
||||
// Find a free slot; overwrite the oldest if pool is full.
|
||||
int slot = -1;
|
||||
for (int i = 0; i < em.Particles.Length; i++)
|
||||
var desc = em.Desc;
|
||||
if (desc.TotalParticles > 0 && em.TotalEmitted >= desc.TotalParticles)
|
||||
return false;
|
||||
|
||||
if (CountAlive(em) >= desc.MaxParticles)
|
||||
return false;
|
||||
|
||||
if (desc.Birthrate <= 0f)
|
||||
return false;
|
||||
|
||||
return desc.EmitterKind switch
|
||||
{
|
||||
if (!em.Particles[i].Alive) { slot = i; break; }
|
||||
}
|
||||
ParticleEmitterKind.BirthratePerSec => (_time - em.LastEmitTime) > desc.Birthrate,
|
||||
ParticleEmitterKind.BirthratePerMeter =>
|
||||
Vector3.DistanceSquared(em.AnchorPos, em.LastEmitOffset) > desc.Birthrate * desc.Birthrate,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
private bool SpawnOne(ParticleEmitter em, bool allowWhenFull)
|
||||
{
|
||||
int slot = FindFreeSlot(em);
|
||||
if (slot < 0 && allowWhenFull)
|
||||
slot = FindOldestSlot(em);
|
||||
if (slot < 0)
|
||||
{
|
||||
// Pool saturated; overwrite the slot closest to dying (oldest
|
||||
// by age / lifetime ratio). Matches retail's behaviour of
|
||||
// recycling the expiring particle rather than dropping.
|
||||
float best = -1f;
|
||||
for (int i = 0; i < em.Particles.Length; i++)
|
||||
{
|
||||
ref var p = ref em.Particles[i];
|
||||
float r = p.Lifetime > 0 ? p.Age / p.Lifetime : 1f;
|
||||
if (r > best) { best = r; slot = i; }
|
||||
}
|
||||
if (slot < 0) return;
|
||||
}
|
||||
return false;
|
||||
|
||||
ref var particle = ref em.Particles[slot];
|
||||
particle = default;
|
||||
particle.Alive = true;
|
||||
particle.Age = 0f;
|
||||
particle.Lifetime = Lerp(em.Desc.LifetimeMin, em.Desc.LifetimeMax,
|
||||
(float)_rng.NextDouble());
|
||||
|
||||
// Position = emitter anchor + random offset in a disk perpendicular
|
||||
// to OffsetDir. This models the retail annulus.
|
||||
Vector3 disk = RandomDiskVector(em.Desc.OffsetDir, em.Desc.MaxOffset);
|
||||
particle.Position = em.AnchorPos + disk;
|
||||
particle.SpawnedAt = _time;
|
||||
particle.Lifetime = RandomLifespan(em.Desc);
|
||||
particle.EmissionOrigin = em.AnchorPos;
|
||||
particle.SpawnRotation = em.AnchorRot;
|
||||
|
||||
// Velocity = initial vector ± jitter in all three axes.
|
||||
Vector3 v = em.Desc.InitialVelocity;
|
||||
if (em.Desc.VelocityJitter > 0f)
|
||||
Vector3 localOffset = RandomOffset(em.Desc);
|
||||
Vector3 localA = RandomVector(em.Desc.A, em.Desc.MinA, em.Desc.MaxA);
|
||||
Vector3 localB = RandomVector(em.Desc.B, em.Desc.MinB, em.Desc.MaxB);
|
||||
Vector3 localC = RandomVector(em.Desc.C, em.Desc.MinC, em.Desc.MaxC);
|
||||
|
||||
if (localA == Vector3.Zero && em.Desc.InitialVelocity != Vector3.Zero)
|
||||
{
|
||||
v += new Vector3(
|
||||
RandomCentered(em.Desc.VelocityJitter),
|
||||
RandomCentered(em.Desc.VelocityJitter),
|
||||
RandomCentered(em.Desc.VelocityJitter));
|
||||
localA = em.Desc.InitialVelocity;
|
||||
if (em.Desc.VelocityJitter > 0f)
|
||||
{
|
||||
localA += new Vector3(
|
||||
RandomCentered(em.Desc.VelocityJitter),
|
||||
RandomCentered(em.Desc.VelocityJitter),
|
||||
RandomCentered(em.Desc.VelocityJitter));
|
||||
}
|
||||
}
|
||||
particle.Velocity = v;
|
||||
particle.Size = em.Desc.StartSize;
|
||||
particle.Rotation = em.Desc.StartRotation;
|
||||
particle.ColorArgb = em.Desc.StartColorArgb;
|
||||
if (localB == Vector3.Zero && em.Desc.Gravity != Vector3.Zero)
|
||||
localB = em.Desc.Gravity;
|
||||
|
||||
InitParticleVectors(em, ref particle, localOffset, localA, localB, localC);
|
||||
|
||||
particle.Velocity = particle.A;
|
||||
particle.StartSize = RandomScale(em.Desc.StartSize, em.Desc.ScaleRand);
|
||||
particle.EndSize = RandomScale(em.Desc.EndSize, em.Desc.ScaleRand);
|
||||
particle.StartAlpha = RandomTrans(em.Desc.StartAlpha, em.Desc.TransRand);
|
||||
particle.EndAlpha = RandomTrans(em.Desc.EndAlpha, em.Desc.TransRand);
|
||||
particle.Size = particle.StartSize;
|
||||
particle.ColorArgb = Color32(particle.StartAlpha, em.Desc.StartColorArgb, em.Desc.EndColorArgb, 0f);
|
||||
particle.Position = ComputePosition(em, particle);
|
||||
|
||||
em.TotalEmitted++;
|
||||
em.LastEmitTime = _time;
|
||||
em.LastEmitOffset = em.AnchorPos;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── 13 retail motion integrators (r04 §3) ────────────────────────────────
|
||||
|
||||
private void Integrate(ref Particle p, ParticleEmitter em, float dt)
|
||||
private Vector3 ComputePosition(ParticleEmitter em, Particle p)
|
||||
{
|
||||
float t = p.Age;
|
||||
Vector3 origin = (em.Desc.Flags & EmitterFlags.AttachLocal) != 0
|
||||
? em.AnchorPos
|
||||
: p.EmissionOrigin;
|
||||
Vector3 offset = p.Offset;
|
||||
Vector3 a = p.A;
|
||||
Vector3 b = p.B;
|
||||
Vector3 c = p.C;
|
||||
|
||||
return em.Desc.Type switch
|
||||
{
|
||||
ParticleType.Still => origin + offset,
|
||||
ParticleType.LocalVelocity or ParticleType.GlobalVelocity =>
|
||||
origin + offset + t * a,
|
||||
ParticleType.ParabolicLVGA or ParticleType.ParabolicLVLA or ParticleType.ParabolicGVGA =>
|
||||
origin + offset + t * a + 0.5f * t * t * b,
|
||||
ParticleType.ParabolicLVGAGR or ParticleType.ParabolicLVLALR or ParticleType.ParabolicGVGAGR =>
|
||||
origin + offset + t * a + 0.5f * t * t * b,
|
||||
ParticleType.Swarm =>
|
||||
origin + offset + t * a + new Vector3(
|
||||
MathF.Cos(t * b.X) * c.X,
|
||||
MathF.Sin(t * b.Y) * c.Y,
|
||||
MathF.Cos(t * b.Z) * c.Z),
|
||||
ParticleType.Explode =>
|
||||
origin + offset + new Vector3(
|
||||
(t * b.X + c.X * a.X) * t,
|
||||
(t * b.Y + c.Y * a.X) * t,
|
||||
(t * b.Z + c.Z * a.X + a.Z) * t),
|
||||
ParticleType.Implode =>
|
||||
origin + offset + MathF.Cos(a.X * t) * c + t * t * b,
|
||||
_ => origin + offset + t * a,
|
||||
};
|
||||
}
|
||||
|
||||
private void InitParticleVectors(
|
||||
ParticleEmitter em,
|
||||
ref Particle particle,
|
||||
Vector3 localOffset,
|
||||
Vector3 localA,
|
||||
Vector3 localB,
|
||||
Vector3 localC)
|
||||
{
|
||||
// Retail Particle::Init 0x0051c930 resolves local/global vector
|
||||
// spaces once at spawn; Particle::Update 0x0051c290 then integrates
|
||||
// those stored world-space coefficients each frame.
|
||||
particle.Offset = ToSpawnWorld(em, localOffset);
|
||||
particle.A = localA;
|
||||
particle.B = localB;
|
||||
particle.C = localC;
|
||||
|
||||
switch (em.Desc.Type)
|
||||
{
|
||||
case ParticleType.Still:
|
||||
// No motion. Age + fade only.
|
||||
break;
|
||||
|
||||
case ParticleType.LocalVelocity:
|
||||
// Constant spawn velocity, no acceleration.
|
||||
p.Position += p.Velocity * dt;
|
||||
break;
|
||||
|
||||
case ParticleType.GlobalVelocity:
|
||||
// Uses emitter's InitialVelocity (global/world-space);
|
||||
// each particle keeps its own copy already (set at spawn),
|
||||
// so behaves identically to LocalVelocity at runtime.
|
||||
p.Position += p.Velocity * dt;
|
||||
break;
|
||||
|
||||
case ParticleType.Parabolic:
|
||||
case ParticleType.ParabolicLVGV:
|
||||
case ParticleType.ParabolicLVGA:
|
||||
particle.A = ToSpawnWorld(em, localA);
|
||||
break;
|
||||
|
||||
case ParticleType.ParabolicLVLA:
|
||||
case ParticleType.ParabolicGVGA:
|
||||
case ParticleType.ParabolicGVLA:
|
||||
case ParticleType.ParabolicLALV:
|
||||
// Velocity decays with gravity; position integrates.
|
||||
p.Velocity += em.Desc.Gravity * dt;
|
||||
p.Position += p.Velocity * dt;
|
||||
particle.A = ToSpawnWorld(em, localA);
|
||||
particle.B = ToSpawnWorld(em, localB);
|
||||
break;
|
||||
|
||||
case ParticleType.ParabolicLVGAGR:
|
||||
particle.A = ToSpawnWorld(em, localA);
|
||||
particle.C = localC;
|
||||
break;
|
||||
|
||||
case ParticleType.Swarm:
|
||||
// Orbital drift around anchor. Apply a tangential swirl.
|
||||
{
|
||||
Vector3 toCenter = em.AnchorPos - p.Position;
|
||||
Vector3 axis = em.Desc.OffsetDir == Vector3.Zero ? Vector3.UnitZ : em.Desc.OffsetDir;
|
||||
Vector3 tangent = Vector3.Normalize(Vector3.Cross(axis, toCenter));
|
||||
p.Velocity = Vector3.Lerp(p.Velocity, tangent * em.Desc.InitialVelocity.Length(), dt * 4f);
|
||||
p.Position += p.Velocity * dt;
|
||||
}
|
||||
particle.A = ToSpawnWorld(em, localA);
|
||||
break;
|
||||
|
||||
case ParticleType.Explode:
|
||||
// Push outward along (position - anchor).
|
||||
{
|
||||
Vector3 dir = p.Position - em.AnchorPos;
|
||||
if (dir.LengthSquared() < 1e-6f) dir = Vector3.UnitZ;
|
||||
else dir = Vector3.Normalize(dir);
|
||||
p.Velocity = dir * em.Desc.InitialVelocity.Length();
|
||||
p.Position += p.Velocity * dt;
|
||||
}
|
||||
particle.A = localA;
|
||||
particle.B = localB;
|
||||
particle.C = RandomExplodeDirection(localC);
|
||||
break;
|
||||
|
||||
case ParticleType.Implode:
|
||||
// Pull inward toward anchor.
|
||||
{
|
||||
Vector3 dir = em.AnchorPos - p.Position;
|
||||
float dist = dir.Length();
|
||||
if (dist < 0.01f) { p.Alive = false; break; }
|
||||
dir /= dist;
|
||||
p.Velocity = dir * em.Desc.InitialVelocity.Length();
|
||||
p.Position += p.Velocity * dt;
|
||||
}
|
||||
particle.A = localA;
|
||||
particle.B = localB;
|
||||
particle.Offset = new Vector3(
|
||||
particle.Offset.X * localC.X,
|
||||
particle.Offset.Y * localC.Y,
|
||||
particle.Offset.Z * localC.Z);
|
||||
particle.C = particle.Offset;
|
||||
break;
|
||||
|
||||
default:
|
||||
p.Position += p.Velocity * dt;
|
||||
case ParticleType.ParabolicLVLALR:
|
||||
particle.A = ToSpawnWorld(em, localA);
|
||||
particle.B = ToSpawnWorld(em, localB);
|
||||
particle.C = ToSpawnWorld(em, localC);
|
||||
break;
|
||||
|
||||
case ParticleType.ParabolicGVGAGR:
|
||||
particle.C = localC;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Utility ──────────────────────────────────────────────────────────────
|
||||
private static Vector3 ToSpawnWorld(ParticleEmitter em, Vector3 value)
|
||||
=> em.AnchorRot == Quaternion.Identity ? value : Vector3.Transform(value, em.AnchorRot);
|
||||
|
||||
private Vector3 RandomExplodeDirection(Vector3 localC)
|
||||
{
|
||||
float yaw = RandomRange(-MathF.PI, MathF.PI);
|
||||
float pitch = RandomRange(-MathF.PI, MathF.PI);
|
||||
float cosPitch = MathF.Cos(pitch);
|
||||
Vector3 c = new(
|
||||
MathF.Cos(yaw) * localC.X * cosPitch,
|
||||
MathF.Sin(yaw) * localC.Y * cosPitch,
|
||||
MathF.Sin(pitch) * localC.Z);
|
||||
|
||||
return NormalizeCheckSmall(ref c) ? Vector3.Zero : c;
|
||||
}
|
||||
|
||||
private int FindFreeSlot(ParticleEmitter em)
|
||||
{
|
||||
for (int i = 0; i < em.Particles.Length; i++)
|
||||
{
|
||||
if (!em.Particles[i].Alive)
|
||||
return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static int FindOldestSlot(ParticleEmitter em)
|
||||
{
|
||||
int slot = -1;
|
||||
float best = -1f;
|
||||
for (int i = 0; i < em.Particles.Length; i++)
|
||||
{
|
||||
ref var p = ref em.Particles[i];
|
||||
float r = p.Lifetime > 0f ? p.Age / p.Lifetime : 1f;
|
||||
if (r > best)
|
||||
{
|
||||
best = r;
|
||||
slot = i;
|
||||
}
|
||||
}
|
||||
|
||||
return slot;
|
||||
}
|
||||
|
||||
private static int CountAlive(ParticleEmitter em)
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = 0; i < em.Particles.Length; i++)
|
||||
if (em.Particles[i].Alive) n++;
|
||||
{
|
||||
if (em.Particles[i].Alive)
|
||||
n++;
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
private float RandomLifespan(EmitterDesc desc)
|
||||
{
|
||||
float lifespan = desc.Lifespan > 0f ? desc.Lifespan : (desc.LifetimeMin + desc.LifetimeMax) * 0.5f;
|
||||
float rand = desc.LifespanRand > 0f ? desc.LifespanRand : MathF.Abs(desc.LifetimeMax - desc.LifetimeMin) * 0.5f;
|
||||
float value = lifespan + RandomCentered(rand);
|
||||
if (value <= 0f && desc.LifetimeMax > 0f)
|
||||
value = Lerp(desc.LifetimeMin, desc.LifetimeMax, (float)_rng.NextDouble());
|
||||
return MathF.Max(0f, value);
|
||||
}
|
||||
|
||||
private Vector3 RandomOffset(EmitterDesc desc)
|
||||
{
|
||||
float min = MathF.Min(desc.MinOffset, desc.MaxOffset);
|
||||
float max = MathF.Max(desc.MinOffset, desc.MaxOffset);
|
||||
if (max <= 0f)
|
||||
return Vector3.Zero;
|
||||
|
||||
Vector3 axis = NormalizeOrZero(desc.OffsetDir);
|
||||
Vector3 v = new(
|
||||
RandomCentered(1f),
|
||||
RandomCentered(1f),
|
||||
RandomCentered(1f));
|
||||
|
||||
if (axis != Vector3.Zero)
|
||||
v -= axis * Vector3.Dot(v, axis);
|
||||
|
||||
if (v.LengthSquared() < 1e-8f)
|
||||
v = axis != Vector3.Zero ? Perpendicular(axis) : Vector3.UnitX;
|
||||
else
|
||||
v = Vector3.Normalize(v);
|
||||
|
||||
return v * Lerp(min, max, (float)_rng.NextDouble());
|
||||
}
|
||||
|
||||
private Vector3 RandomVector(Vector3 direction, float min, float max)
|
||||
{
|
||||
if (direction == Vector3.Zero)
|
||||
return Vector3.Zero;
|
||||
|
||||
if (max < min)
|
||||
(min, max) = (max, min);
|
||||
|
||||
return direction * Lerp(min, max, (float)_rng.NextDouble());
|
||||
}
|
||||
|
||||
private float RandomScale(float baseValue, float rand)
|
||||
=> Math.Clamp(baseValue + RandomCentered(rand), 0.1f, 10f);
|
||||
|
||||
private float RandomTrans(float baseValue, float rand)
|
||||
=> Math.Clamp(baseValue + RandomCentered(rand), 0f, 1f);
|
||||
|
||||
private float RandomCentered(float halfWidth)
|
||||
=> ((float)_rng.NextDouble() - 0.5f) * 2f * halfWidth;
|
||||
|
||||
private float RandomRange(float min, float max)
|
||||
=> Lerp(min, max, (float)_rng.NextDouble());
|
||||
|
||||
private static float Lerp(float a, float b, float t) => a + (b - a) * t;
|
||||
|
||||
private static Vector3 NormalizeOrZero(Vector3 v)
|
||||
=> v.LengthSquared() > 1e-8f ? Vector3.Normalize(v) : Vector3.Zero;
|
||||
|
||||
private static bool NormalizeCheckSmall(ref Vector3 v)
|
||||
{
|
||||
float length = v.Length();
|
||||
if (length < 1e-8f)
|
||||
return true;
|
||||
|
||||
v /= length;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Vector3 Perpendicular(Vector3 v)
|
||||
{
|
||||
Vector3 basis = MathF.Abs(v.X) < 0.9f ? Vector3.UnitX : Vector3.UnitY;
|
||||
return Vector3.Normalize(Vector3.Cross(v, basis));
|
||||
}
|
||||
|
||||
private static uint Color32(float alpha, uint startArgb, uint endArgb, float t)
|
||||
{
|
||||
// Blend RGB channels linearly; apply alpha override from fade.
|
||||
byte sa = (byte)((startArgb >> 24) & 0xFF);
|
||||
byte sr = (byte)((startArgb >> 16) & 0xFF);
|
||||
byte sg = (byte)((startArgb >> 8) & 0xFF);
|
||||
byte sb = (byte)( startArgb & 0xFF);
|
||||
byte ea = (byte)((endArgb >> 24) & 0xFF);
|
||||
byte sg = (byte)((startArgb >> 8) & 0xFF);
|
||||
byte sb = (byte)(startArgb & 0xFF);
|
||||
byte er = (byte)((endArgb >> 16) & 0xFF);
|
||||
byte eg = (byte)((endArgb >> 8) & 0xFF);
|
||||
byte eb = (byte)( endArgb & 0xFF);
|
||||
byte eg = (byte)((endArgb >> 8) & 0xFF);
|
||||
byte eb = (byte)(endArgb & 0xFF);
|
||||
|
||||
byte r = (byte)Math.Clamp(sr + (er - sr) * t, 0f, 255f);
|
||||
byte g = (byte)Math.Clamp(sg + (eg - sg) * t, 0f, 255f);
|
||||
byte b = (byte)Math.Clamp(sb + (eb - sb) * t, 0f, 255f);
|
||||
byte a = (byte)Math.Clamp(alpha * 255f, 0f, 255f);
|
||||
return ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | b;
|
||||
}
|
||||
|
||||
private Vector3 RandomDiskVector(Vector3 axis, float maxRadius)
|
||||
{
|
||||
if (maxRadius <= 0f) return Vector3.Zero;
|
||||
// Two perpendicular vectors to axis.
|
||||
Vector3 n = Vector3.Normalize(axis == Vector3.Zero ? Vector3.UnitZ : axis);
|
||||
Vector3 t1 = Math.Abs(n.X) < 0.9f
|
||||
? Vector3.Normalize(Vector3.Cross(n, Vector3.UnitX))
|
||||
: Vector3.Normalize(Vector3.Cross(n, Vector3.UnitY));
|
||||
Vector3 t2 = Vector3.Normalize(Vector3.Cross(n, t1));
|
||||
float theta = (float)(_rng.NextDouble() * Math.PI * 2.0);
|
||||
float r = maxRadius * MathF.Sqrt((float)_rng.NextDouble());
|
||||
return (t1 * MathF.Cos(theta) + t2 * MathF.Sin(theta)) * r;
|
||||
}
|
||||
|
||||
private float RandomCentered(float halfWidth)
|
||||
{
|
||||
return ((float)_rng.NextDouble() - 0.5f) * 2f * halfWidth;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue