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:
Erik 2026-04-28 22:47:11 +02:00
parent 1f82b7604e
commit ec1bbb4f43
28 changed files with 2444 additions and 780 deletions

View file

@ -10,6 +10,8 @@ namespace AcDream.App.Rendering;
public sealed class GameWindow : IDisposable
{
private readonly record struct SkyPesKey(int ObjectIndex, uint PesObjectId, bool PostScene);
private readonly string _datDir;
private readonly WorldGameState _worldGameState;
private readonly WorldEvents _worldEvents;
@ -152,7 +154,7 @@ public sealed class GameWindow : IDisposable
private AcDream.App.Audio.AudioHookSink? _audioSink;
// Phase E.3 particles.
private readonly AcDream.Core.Vfx.EmitterDescRegistry _emitterRegistry = new();
private AcDream.Core.Vfx.EmitterDescRegistry? _emitterRegistry;
private AcDream.Core.Vfx.ParticleSystem? _particleSystem;
private AcDream.Core.Vfx.ParticleHookSink? _particleSink;
// Phase 6 — retail PhysicsScript runtime. Receives PlayScript (0xF754)
@ -160,6 +162,13 @@ public sealed class GameWindow : IDisposable
// sounds, light toggles) at their StartTime offsets.
private AcDream.Core.Vfx.PhysicsScriptRunner? _scriptRunner;
private AcDream.App.Rendering.ParticleRenderer? _particleRenderer;
// Retail GameSky copies SkyObject.PesObjectId into CelestialPosition but
// never consumes it in CreateDeletePhysicsObjects/MakeObject/UseTime.
// Keep the experimental path available for DAT archaeology only.
private readonly bool _enableSkyPesDebug =
string.Equals(Environment.GetEnvironmentVariable("ACDREAM_ENABLE_SKY_PES"), "1", StringComparison.Ordinal);
private readonly HashSet<SkyPesKey> _activeSkyPes = new();
private readonly HashSet<SkyPesKey> _missingSkyPes = new();
// Remote-entity motion inference: tracks when each remote entity last
// moved meaningfully. Used in TickAnimations to swap to Ready when
@ -785,12 +794,13 @@ public sealed class GameWindow : IDisposable
_dats = new DatCollection(_datDir, DatAccessType.Read);
_animLoader = new AcDream.Core.Physics.DatCollectionLoader(_dats);
_emitterRegistry = new AcDream.Core.Vfx.EmitterDescRegistry(_dats);
// Phase E.3 particles: always-on, no driver dependency. Registered
// with the hook router so CreateParticle / DestroyParticle /
// StopParticle hooks fired from motion tables produce visible
// spawns. The Tick call is driven from OnRender.
_particleSystem = new AcDream.Core.Vfx.ParticleSystem(_emitterRegistry);
_particleSystem = new AcDream.Core.Vfx.ParticleSystem(_emitterRegistry!);
_particleSink = new AcDream.Core.Vfx.ParticleHookSink(_particleSystem);
_hookRouter.Register(_particleSink);
@ -1215,7 +1225,7 @@ public sealed class GameWindow : IDisposable
// spawned into the shared ParticleSystem as billboard quads.
// Weather uses AttachLocal emitters so the rain volume follows
// the player.
_particleRenderer = new ParticleRenderer(_gl, shadersDir);
_particleRenderer = new ParticleRenderer(_gl, shadersDir, _textureCache, _dats);
// Phase A.1: replace the one-shot 3×3 preload with a streaming controller.
// Parse runtime radius from environment (default 2 → 5×5 window).
@ -2846,6 +2856,110 @@ public sealed class GameWindow : IDisposable
_scriptRunner.Play(scriptId, guid, camWorldPos);
}
private void UpdateSkyPes(
float dayFraction,
AcDream.Core.World.DayGroupData? dayGroup,
System.Numerics.Vector3 cameraWorldPos,
bool suppressSky)
{
if (_scriptRunner is null || _particleSink is null)
return;
var seen = new HashSet<SkyPesKey>();
if (!suppressSky && dayGroup is not null)
{
for (int i = 0; i < dayGroup.SkyObjects.Count; i++)
{
var obj = dayGroup.SkyObjects[i];
if (obj.PesObjectId == 0 || !obj.IsVisible(dayFraction))
continue;
var key = new SkyPesKey(i, obj.PesObjectId, obj.IsPostScene);
seen.Add(key);
if (_activeSkyPes.Contains(key) || _missingSkyPes.Contains(key))
continue;
uint skyEntityId = SkyPesEntityId(key);
var renderPass = obj.IsPostScene
? AcDream.Core.Vfx.ParticleRenderPass.SkyPostScene
: AcDream.Core.Vfx.ParticleRenderPass.SkyPreScene;
_particleSink.SetEntityRenderPass(skyEntityId, renderPass);
var anchor = SkyPesAnchor(obj, cameraWorldPos);
var rotation = SkyPesRotation(obj, dayFraction);
// Refresh anchor + rotation every frame so AttachLocal
// (is_parent_local=1) particles track the camera. Retail
// ParticleEmitter::UpdateParticles at 0x0051d2d4 reads the
// live parent frame each tick; for sky-PES the parent IS
// the camera. UpdateEntityAnchor is a no-op when no
// emitters yet exist (script just spawned this frame).
_particleSink.UpdateEntityAnchor(skyEntityId, anchor, rotation);
if (_activeSkyPes.Contains(key) || _missingSkyPes.Contains(key))
continue;
if (_scriptRunner.Play(obj.PesObjectId, skyEntityId, anchor))
{
_activeSkyPes.Add(key);
}
else
{
_missingSkyPes.Add(key);
_particleSink.ClearEntityRenderPass(skyEntityId);
}
}
}
foreach (var key in _activeSkyPes.ToArray())
{
if (seen.Contains(key))
continue;
uint skyEntityId = SkyPesEntityId(key);
_scriptRunner.Stop(key.PesObjectId, skyEntityId);
_particleSink.StopAllForEntity(skyEntityId, fadeOut: true);
_activeSkyPes.Remove(key);
}
foreach (var key in _missingSkyPes.ToArray())
{
if (!seen.Contains(key))
_missingSkyPes.Remove(key);
}
}
private static uint SkyPesEntityId(SkyPesKey key)
{
// 0xF0000000 prefix marks synthetic sky-PES entityIds (no real
// server GUID lives in the 0xFxxxxxxx space). Reserve bit
// 0x08000000 for the pre/post-scene flag and the lower 27 bits
// for the object index — keeps the post-scene flag from sliding
// into the index range if a future DayGroup ever ships >65k sky
// objects (current Dereth max is 18, but the constraint is free).
uint postBit = key.PostScene ? 0x08000000u : 0u;
return 0xF0000000u | postBit | ((uint)key.ObjectIndex & 0x07FFFFFFu);
}
private static System.Numerics.Vector3 SkyPesAnchor(
AcDream.Core.World.SkyObjectData obj,
System.Numerics.Vector3 cameraWorldPos)
{
if (obj.IsWeather && (obj.Properties & 0x08u) == 0u)
return cameraWorldPos + new System.Numerics.Vector3(0f, 0f, -120f);
return cameraWorldPos;
}
private static System.Numerics.Quaternion SkyPesRotation(
AcDream.Core.World.SkyObjectData obj,
float dayFraction)
{
float rotationRad = obj.CurrentAngle(dayFraction) * (MathF.PI / 180f);
return System.Numerics.Quaternion.CreateFromAxisAngle(
System.Numerics.Vector3.UnitY,
-rotationRad);
}
/// <summary>
/// Phase 5d — retail <c>AdminEnvirons</c> (0xEA60) dispatcher.
/// Routes fog presets into the weather system's sticky override
@ -4329,6 +4443,7 @@ public sealed class GameWindow : IDisposable
// interpolated keyframe.
var kf = WorldTime.CurrentSky;
var atmo = Weather.Snapshot(in kf);
bool environOverrideActive = atmo.Override != AcDream.Core.World.EnvironOverride.None;
var fogColor = atmo.FogColor;
// Clear to fog color (horizon haze) so if sky meshes have alpha
// gaps or don't cover the full view, the "missing" area reads as
@ -4379,15 +4494,6 @@ public sealed class GameWindow : IDisposable
// and the SkyRenderer.RenderWeather pass both pick up snow
// weather meshes for free.)
// Phase E.3: advance live particle emitters AFTER animation tick
// so emitters spawned by hooks fired this frame get integrated.
// Tick the PhysicsScript runner BEFORE the particle system so any
// CreateParticleHook fired this frame has its emitter alive when
// the particle system advances.
_scriptRunner?.Tick((float)deltaSeconds);
_particleSystem?.Tick((float)deltaSeconds);
int visibleLandblocks = 0;
int totalLandblocks = 0;
@ -4455,6 +4561,15 @@ public sealed class GameWindow : IDisposable
var visibility = _cellVisibility.ComputeVisibility(camPos);
bool cameraInsideCell = visibility?.CameraCell is not null;
// Phase C.1: tick retail PhysicsScript particle hooks. Named
// retail decomp confirms SkyObject.PesObjectId is copied by
// SkyDesc::GetSky but ignored by GameSky, so the sky-PES path is
// debug-only and disabled for normal retail rendering.
if (_enableSkyPesDebug)
UpdateSkyPes((float)WorldTime.DayFraction, _activeDayGroup, camPos, cameraInsideCell);
_scriptRunner?.Tick((float)deltaSeconds);
_particleSystem?.Tick((float)deltaSeconds);
// Phase G.1/G.2: feed the sun, tick LightManager, build + upload
// the scene-lighting UBO once per frame. Every shader that
// consumes binding=1 reads the same data for the rest of the
@ -4490,7 +4605,10 @@ public sealed class GameWindow : IDisposable
if (!cameraInsideCell)
{
_skyRenderer?.RenderSky(camera, camPos, (float)WorldTime.DayFraction,
_activeDayGroup, kf);
_activeDayGroup, kf, environOverrideActive);
if (_particleSystem is not null && _particleRenderer is not null)
_particleRenderer.Draw(_particleSystem, camera, camPos,
AcDream.Core.Vfx.ParticleRenderPass.SkyPreScene);
}
// K-fix1 (2026-04-26): suppress terrain + entity rendering
@ -4523,7 +4641,8 @@ public sealed class GameWindow : IDisposable
// Runs with depth test on (particles occluded by walls)
// but depth write off (no self-occlusion sorting needed).
if (_particleSystem is not null && _particleRenderer is not null)
_particleRenderer.Draw(_particleSystem, camera, camPos);
_particleRenderer.Draw(_particleSystem, camera, camPos,
AcDream.Core.Vfx.ParticleRenderPass.Scene);
// Bug A fix (post-#26 worktree, 2026-04-26): weather sky
// meshes (Properties & 0x04, e.g. the 815m-tall rain
@ -4536,7 +4655,10 @@ public sealed class GameWindow : IDisposable
if (!cameraInsideCell)
{
_skyRenderer?.RenderWeather(camera, camPos, (float)WorldTime.DayFraction,
_activeDayGroup, kf);
_activeDayGroup, kf, environOverrideActive);
if (_particleSystem is not null && _particleRenderer is not null)
_particleRenderer.Draw(_particleSystem, camera, camPos,
AcDream.Core.Vfx.ParticleRenderPass.SkyPostScene);
}
// Debug: draw collision shapes as wireframe cylinders around the

View file

@ -2,64 +2,69 @@ using System;
using System.Collections.Generic;
using System.Numerics;
using AcDream.Core.Vfx;
using DatReaderWriter;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Enums;
using Silk.NET.OpenGL;
namespace AcDream.App.Rendering;
/// <summary>
/// Simple billboard-quad particle renderer. One draw call per emitter:
/// the CPU streams (position, size, rotation, packed color) into a
/// per-instance VBO; a unit quad VBO gets instanced and the vertex
/// shader rotates the quad around the camera forward vector so it
/// always faces the viewer.
///
/// <para>
/// Not a retail-perfect port of the D3D7 fixed-function particle pipe;
/// good enough for rain, snow, and the basic spell auras we need for
/// Phase G.1's weather + E.3's playback. Trails + spot-light
/// interactions deferred.
/// </para>
///
/// <para>
/// Emitters tagged with <see cref="EmitterFlags.AttachLocal"/> get
/// re-anchored to the current camera position each frame so the rain
/// volume follows the player (r12 §7). This is the cheap version of
/// retail's "IsParentLocal" flag on held emitters.
/// </para>
/// Instanced renderer for retail particle emitters.
/// </summary>
public sealed unsafe class ParticleRenderer : IDisposable
{
private readonly record struct BatchKey(uint TextureHandle, bool UseTexture, bool Additive);
private readonly record struct ParticleDraw(BatchKey Key, ParticleInstance Instance);
private readonly struct ParticleInstance
{
public readonly Vector3 Position;
public readonly Vector3 AxisX;
public readonly Vector3 AxisY;
public readonly uint ColorArgb;
public readonly float DistanceSq;
public ParticleInstance(Vector3 position, Vector3 axisX, Vector3 axisY, uint colorArgb, float distanceSq)
{
Position = position;
AxisX = axisX;
AxisY = axisY;
ColorArgb = colorArgb;
DistanceSq = distanceSq;
}
}
private readonly GL _gl;
private readonly Shader _shader;
private readonly TextureCache? _textures;
private readonly DatCollection? _dats;
private readonly Dictionary<uint, ParticleGfxInfo> _particleGfxInfoByGfxObj = new();
// Unit-quad vertex buffer (-0.5..+0.5 in XY). 4 verts, 6 indices.
private readonly uint _quadVao;
private readonly uint _quadVbo;
private readonly uint _quadEbo;
// Instance buffer — 8 floats per particle: posX,Y,Z, size, colorR,G,B,A.
private readonly uint _instanceVbo;
private float[] _instanceScratch = new float[256 * 8];
public ParticleRenderer(GL gl, string shadersDir)
private float[] _instanceScratch = new float[256 * 16];
public ParticleRenderer(GL gl, string shadersDir, TextureCache? textures = null, DatCollection? dats = null)
{
_gl = gl ?? throw new ArgumentNullException(nameof(gl));
_textures = textures;
_dats = dats;
_shader = new Shader(_gl,
System.IO.Path.Combine(shadersDir, "particle.vert"),
System.IO.Path.Combine(shadersDir, "particle.frag"));
// Unit quad around origin (XY plane, Z = 0). The vertex shader
// reads this, then offsets into world space using the
// per-instance (pos, size) values.
float[] quadVerts = new float[]
float[] quadVerts =
{
// pos x,y uv
-0.5f, -0.5f, 0f, 0f,
0.5f, -0.5f, 1f, 0f,
0.5f, 0.5f, 1f, 1f,
-0.5f, 0.5f, 0f, 1f,
};
uint[] quadIdx = new uint[] { 0, 1, 2, 0, 2, 3 };
uint[] quadIdx = { 0, 1, 2, 0, 2, 3 };
_quadVao = _gl.GenVertexArray();
_gl.BindVertexArray(_quadVao);
@ -67,8 +72,14 @@ public sealed unsafe class ParticleRenderer : IDisposable
_quadVbo = _gl.GenBuffer();
_gl.BindBuffer(BufferTargetARB.ArrayBuffer, _quadVbo);
fixed (void* p = quadVerts)
_gl.BufferData(BufferTargetARB.ArrayBuffer,
(nuint)(quadVerts.Length * sizeof(float)), p, BufferUsageARB.StaticDraw);
{
_gl.BufferData(
BufferTargetARB.ArrayBuffer,
(nuint)(quadVerts.Length * sizeof(float)),
p,
BufferUsageARB.StaticDraw);
}
_gl.EnableVertexAttribArray(0);
_gl.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, 4 * sizeof(float), (void*)0);
_gl.EnableVertexAttribArray(1);
@ -77,135 +88,347 @@ public sealed unsafe class ParticleRenderer : IDisposable
_quadEbo = _gl.GenBuffer();
_gl.BindBuffer(BufferTargetARB.ElementArrayBuffer, _quadEbo);
fixed (void* p = quadIdx)
_gl.BufferData(BufferTargetARB.ElementArrayBuffer,
(nuint)(quadIdx.Length * sizeof(uint)), p, BufferUsageARB.StaticDraw);
{
_gl.BufferData(
BufferTargetARB.ElementArrayBuffer,
(nuint)(quadIdx.Length * sizeof(uint)),
p,
BufferUsageARB.StaticDraw);
}
_instanceVbo = _gl.GenBuffer();
_gl.BindBuffer(BufferTargetARB.ArrayBuffer, _instanceVbo);
_gl.BufferData(BufferTargetARB.ArrayBuffer, (nuint)(256 * 8 * sizeof(float)),
(void*)0, BufferUsageARB.DynamicDraw);
_gl.BufferData(BufferTargetARB.ArrayBuffer, (nuint)(256 * 16 * sizeof(float)), (void*)0, BufferUsageARB.DynamicDraw);
// Per-instance attributes: pos+size at loc 2, color at loc 3.
_gl.EnableVertexAttribArray(2);
_gl.VertexAttribPointer(2, 4, VertexAttribPointerType.Float, false, 8 * sizeof(float), (void*)0);
_gl.VertexAttribPointer(2, 4, VertexAttribPointerType.Float, false, 16 * sizeof(float), (void*)0);
_gl.VertexAttribDivisor(2, 1);
_gl.EnableVertexAttribArray(3);
_gl.VertexAttribPointer(3, 4, VertexAttribPointerType.Float, false, 8 * sizeof(float), (void*)(4 * sizeof(float)));
_gl.VertexAttribPointer(3, 4, VertexAttribPointerType.Float, false, 16 * sizeof(float), (void*)(4 * sizeof(float)));
_gl.VertexAttribDivisor(3, 1);
_gl.EnableVertexAttribArray(4);
_gl.VertexAttribPointer(4, 4, VertexAttribPointerType.Float, false, 16 * sizeof(float), (void*)(8 * sizeof(float)));
_gl.VertexAttribDivisor(4, 1);
_gl.EnableVertexAttribArray(5);
_gl.VertexAttribPointer(5, 4, VertexAttribPointerType.Float, false, 16 * sizeof(float), (void*)(12 * sizeof(float)));
_gl.VertexAttribDivisor(5, 1);
_gl.BindVertexArray(0);
}
/// <summary>
/// Draw every live particle. Splits emitters by blend mode (additive
/// vs alpha-blend) but doesn't sort by depth — particles don't
/// self-occlude enough for sorting to matter for rain/snow.
/// </summary>
public void Draw(ParticleSystem particles, ICamera camera, Vector3 cameraWorldPos)
public void Draw(
ParticleSystem particles,
ICamera camera,
Vector3 cameraWorldPos,
ParticleRenderPass renderPass = ParticleRenderPass.Scene)
{
if (particles is null || camera is null) return;
if (particles is null || camera is null)
return;
Matrix4x4.Invert(camera.View, out var invView);
Vector3 cameraRight = Vector3.Normalize(new Vector3(invView.M11, invView.M12, invView.M13));
Vector3 cameraUp = Vector3.Normalize(new Vector3(invView.M21, invView.M22, invView.M23));
var draws = BuildDrawList(particles, cameraWorldPos, renderPass, cameraRight, cameraUp);
if (draws.Count == 0)
return;
draws.Sort(static (a, b) => b.Instance.DistanceSq.CompareTo(a.Instance.DistanceSq));
_shader.Use();
_shader.SetMatrix4("uViewProjection", camera.View * camera.Projection);
_shader.SetVec3("uCameraRight", GetCameraRight(camera));
_shader.SetVec3("uCameraUp", GetCameraUp(camera));
_shader.SetInt("uParticleTexture", 0);
_gl.Enable(EnableCap.DepthTest);
_gl.Enable(EnableCap.Blend);
_gl.DepthMask(false);
_gl.Disable(EnableCap.CullFace);
_gl.ActiveTexture(TextureUnit.Texture0);
// Group emitters by additive vs alpha-blend so we flip blend state
// once per group rather than per-emitter. Simple two-pass split.
var alphaGroup = new List<ParticleEmitter>(32);
var addGroup = new List<ParticleEmitter>(32);
foreach (var (em, _) in particles.EnumerateLive())
var run = new List<ParticleInstance>(64);
for (int i = 0; i < draws.Count;)
{
var list = (em.Desc.Flags & EmitterFlags.Additive) != 0 ? addGroup : alphaGroup;
if (list.Count == 0 || !ReferenceEquals(list[^1], em))
list.Add(em);
var key = draws[i].Key;
run.Clear();
do
{
run.Add(draws[i].Instance);
i++;
}
while (i < draws.Count && draws[i].Key == key);
_gl.BlendFunc(
BlendingFactor.SrcAlpha,
key.Additive ? BlendingFactor.One : BlendingFactor.OneMinusSrcAlpha);
_shader.SetInt("uUseTexture", key.UseTexture ? 1 : 0);
_gl.BindTexture(TextureTarget.Texture2D, key.UseTexture ? key.TextureHandle : 0);
DrawInstances(run);
}
_gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
foreach (var em in alphaGroup)
DrawEmitter(em, cameraWorldPos);
_gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.One);
foreach (var em in addGroup)
DrawEmitter(em, cameraWorldPos);
_gl.BindTexture(TextureTarget.Texture2D, 0);
_gl.BindVertexArray(0);
_gl.DepthMask(true);
_gl.Disable(EnableCap.Blend);
_gl.BindVertexArray(0);
}
private void DrawEmitter(ParticleEmitter em, Vector3 cameraWorldPos)
private List<ParticleDraw> BuildDrawList(
ParticleSystem particles,
Vector3 cameraWorldPos,
ParticleRenderPass renderPass,
Vector3 cameraRight,
Vector3 cameraUp)
{
int liveCount = 0;
for (int i = 0; i < em.Particles.Length; i++)
if (em.Particles[i].Alive) liveCount++;
if (liveCount == 0) return;
// Ensure instance buffer is big enough.
int needed = liveCount * 8;
if (_instanceScratch.Length < needed)
_instanceScratch = new float[needed + 256 * 8];
// Anchor adjustment for AttachLocal emitters — re-center the
// emission volume on the camera each frame so the rain/snow
// follows the viewer. The emitter's AnchorPos stays at the
// spawn point, but when writing out world-space particles we
// add (camera - emitterAnchor) so they track the camera.
bool attachLocal = (em.Desc.Flags & EmitterFlags.AttachLocal) != 0;
Vector3 cameraOffset = attachLocal ? (cameraWorldPos - em.AnchorPos) : Vector3.Zero;
int idx = 0;
for (int i = 0; i < em.Particles.Length; i++)
var draws = new List<ParticleDraw>(Math.Max(64, particles.ActiveParticleCount));
foreach (var (em, idx) in particles.EnumerateLive())
{
ref var p = ref em.Particles[i];
if (!p.Alive) continue;
if (em.RenderPass != renderPass)
continue;
Vector3 pos = p.Position + cameraOffset;
_instanceScratch[idx * 8 + 0] = pos.X;
_instanceScratch[idx * 8 + 1] = pos.Y;
_instanceScratch[idx * 8 + 2] = pos.Z;
_instanceScratch[idx * 8 + 3] = p.Size;
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);
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);
}
// ARGB → RGBA floats.
float a = ((p.ColorArgb >> 24) & 0xFF) / 255f;
float r = ((p.ColorArgb >> 16) & 0xFF) / 255f;
float g = ((p.ColorArgb >> 8) & 0xFF) / 255f;
float b = ( p.ColorArgb & 0xFF) / 255f;
_instanceScratch[idx * 8 + 4] = r;
_instanceScratch[idx * 8 + 5] = g;
_instanceScratch[idx * 8 + 6] = b;
_instanceScratch[idx * 8 + 7] = a;
draws.Add(new ParticleDraw(key, new ParticleInstance(pos, axisX, axisY, p.ColorArgb, distSq)));
}
idx++;
return draws;
}
private void DrawInstances(List<ParticleInstance> instances)
{
if (instances.Count == 0)
return;
int needed = instances.Count * 16;
if (_instanceScratch.Length < needed)
_instanceScratch = new float[needed + 256 * 16];
for (int i = 0; i < instances.Count; i++)
{
var p = instances[i];
int o = i * 16;
_instanceScratch[o + 0] = p.Position.X;
_instanceScratch[o + 1] = p.Position.Y;
_instanceScratch[o + 2] = p.Position.Z;
_instanceScratch[o + 3] = 0f;
_instanceScratch[o + 4] = p.AxisX.X;
_instanceScratch[o + 5] = p.AxisX.Y;
_instanceScratch[o + 6] = p.AxisX.Z;
_instanceScratch[o + 7] = 0f;
_instanceScratch[o + 8] = p.AxisY.X;
_instanceScratch[o + 9] = p.AxisY.Y;
_instanceScratch[o + 10] = p.AxisY.Z;
_instanceScratch[o + 11] = 0f;
_instanceScratch[o + 12] = ((p.ColorArgb >> 16) & 0xFF) / 255f;
_instanceScratch[o + 13] = ((p.ColorArgb >> 8) & 0xFF) / 255f;
_instanceScratch[o + 14] = (p.ColorArgb & 0xFF) / 255f;
_instanceScratch[o + 15] = ((p.ColorArgb >> 24) & 0xFF) / 255f;
}
_gl.BindBuffer(BufferTargetARB.ArrayBuffer, _instanceVbo);
fixed (void* bp = _instanceScratch)
{
_gl.BufferData(BufferTargetARB.ArrayBuffer,
(nuint)(liveCount * 8 * sizeof(float)),
bp, BufferUsageARB.DynamicDraw);
_gl.BufferData(
BufferTargetARB.ArrayBuffer,
(nuint)(instances.Count * 16 * sizeof(float)),
bp,
BufferUsageARB.DynamicDraw);
}
_gl.BindVertexArray(_quadVao);
_gl.DrawElementsInstanced(PrimitiveType.Triangles, 6,
DrawElementsType.UnsignedInt, (void*)0, (uint)liveCount);
_gl.DrawElementsInstanced(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedInt, (void*)0, (uint)instances.Count);
}
private static Vector3 GetCameraRight(ICamera camera)
private ParticleGfxInfo ResolveParticleGfxInfo(EmitterDesc desc)
{
Matrix4x4.Invert(camera.View, out var inv);
return Vector3.Normalize(new Vector3(inv.M11, inv.M12, inv.M13));
if (_textures is null)
return ParticleGfxInfo.Default;
if (desc.TextureSurfaceId != 0)
return ParticleGfxInfo.Billboard(
_textures.GetOrUpload(desc.TextureSurfaceId),
Vector2.One,
Vector3.Zero,
additive: (desc.Flags & EmitterFlags.Additive) != 0,
hasMaterial: false);
uint gfxObjId = desc.HwGfxObjId != 0 ? desc.HwGfxObjId : desc.GfxObjId;
if (gfxObjId == 0 || _dats is null)
return ParticleGfxInfo.Default;
if (!_particleGfxInfoByGfxObj.TryGetValue(gfxObjId, out var info))
{
info = ReadParticleGfxInfo(gfxObjId);
_particleGfxInfoByGfxObj[gfxObjId] = info;
}
return info.TextureHandle != 0 ? info : ParticleGfxInfo.Default;
}
private static Vector3 GetCameraUp(ICamera camera)
private ParticleGfxInfo ReadParticleGfxInfo(uint gfxObjId)
{
Matrix4x4.Invert(camera.View, out var inv);
return Vector3.Normalize(new Vector3(inv.M21, inv.M22, inv.M23));
try
{
var gfx = _dats?.Get<GfxObj>(gfxObjId);
if (gfx is null)
return ParticleGfxInfo.Default;
uint surfaceId = gfx.Surfaces.Count > 0 ? gfx.Surfaces[0].DataId : 0u;
uint texture = surfaceId != 0 && _textures is not null ? _textures.GetOrUpload(surfaceId) : 0u;
bool additive = false;
if (surfaceId != 0)
{
var surface = _dats?.Get<Surface>(surfaceId);
additive = surface is not null && surface.Type.HasFlag(SurfaceType.Additive);
}
return AuthoredParticleGfxInfo(gfx, texture, additive, surfaceId != 0);
}
catch
{
return ParticleGfxInfo.Default;
}
}
private ParticleGfxInfo AuthoredParticleGfxInfo(GfxObj gfx, uint texture, bool additive, bool hasMaterial)
{
if (gfx.VertexArray.Vertices.Count == 0)
return ParticleGfxInfo.Billboard(texture, Vector2.One, Vector3.Zero, additive, hasMaterial);
var min = new Vector3(float.PositiveInfinity);
var max = new Vector3(float.NegativeInfinity);
foreach (var (_, v) in gfx.VertexArray.Vertices)
{
min = Vector3.Min(min, v.Origin);
max = Vector3.Max(max, v.Origin);
}
var size = max - min;
var center = (min + max) * 0.5f;
if (IsPointSprite(gfx))
{
float sx = FallbackParticleExtent(size.X) * 0.9f;
float sy = FallbackParticleExtent(size.Z) * 0.9f;
return ParticleGfxInfo.Billboard(texture, new Vector2(sx, sy), center, additive, hasMaterial);
}
Vector3 axisX;
Vector3 axisY;
Vector2 planeSize;
if (size.Y > size.X && size.Y > size.Z)
{
if (size.X > size.Z)
{
axisX = Vector3.UnitX;
axisY = Vector3.UnitY;
planeSize = new Vector2(size.X, size.Y);
}
else
{
axisX = Vector3.UnitY;
axisY = Vector3.UnitZ;
planeSize = new Vector2(size.Y, size.Z);
}
}
else if (size.X > size.Y && size.X > size.Z)
{
if (size.Z > size.Y)
{
axisX = Vector3.UnitX;
axisY = Vector3.UnitZ;
planeSize = new Vector2(size.X, size.Z);
}
else
{
axisX = Vector3.UnitX;
axisY = Vector3.UnitY;
planeSize = new Vector2(size.X, size.Y);
}
}
else
{
if (size.X > size.Y)
{
axisX = Vector3.UnitX;
axisY = Vector3.UnitZ;
planeSize = new Vector2(size.X, size.Z);
}
else
{
axisX = Vector3.UnitY;
axisY = Vector3.UnitZ;
planeSize = new Vector2(size.Y, size.Z);
}
}
planeSize.X = FallbackParticleExtent(planeSize.X);
planeSize.Y = FallbackParticleExtent(planeSize.Y);
return new ParticleGfxInfo(texture, planeSize, axisX, axisY, center, false, additive, hasMaterial);
}
private bool IsPointSprite(GfxObj gfx)
{
if (!gfx.Flags.HasFlag(GfxObjFlags.HasDIDDegrade) || gfx.DIDDegrade == 0 || _dats is null)
return false;
try
{
var degrade = _dats.Get<GfxObjDegradeInfo>(gfx.DIDDegrade);
return degrade?.Degrades.Count > 0 && degrade.Degrades[0].DegradeMode == 2;
}
catch
{
return false;
}
}
private static float FallbackParticleExtent(float value)
=> value > 1e-4f ? Math.Clamp(value, 1e-4f, 10_000f) : 1f;
private static Quaternion ParticleOrientation(AcDream.Core.Vfx.ParticleEmitter em, Particle p)
{
Quaternion orientation = (em.Desc.Flags & EmitterFlags.AttachLocal) != 0
? em.AnchorRot
: p.SpawnRotation;
if (em.Desc.Type is AcDream.Core.Vfx.ParticleType.ParabolicLVGAGR
or AcDream.Core.Vfx.ParticleType.ParabolicLVLALR
or AcDream.Core.Vfx.ParticleType.ParabolicGVGAGR)
{
Vector3 angular = p.C * p.Age;
float radians = angular.Length();
if (radians > 1e-6f)
orientation = Quaternion.Normalize(orientation * Quaternion.CreateFromAxisAngle(angular / radians, radians));
}
return orientation;
}
public void Dispose()
@ -216,4 +439,26 @@ public sealed unsafe class ParticleRenderer : IDisposable
_gl.DeleteVertexArray(_quadVao);
_shader.Dispose();
}
private readonly record struct ParticleGfxInfo(
uint TextureHandle,
Vector2 Size,
Vector3 AxisX,
Vector3 AxisY,
Vector3 CenterOffset,
bool IsBillboard,
bool Additive,
bool HasMaterial)
{
public static ParticleGfxInfo Default { get; } =
Billboard(0u, Vector2.One, Vector3.Zero, additive: false, hasMaterial: false);
public static ParticleGfxInfo Billboard(
uint textureHandle,
Vector2 size,
Vector3 centerOffset,
bool additive,
bool hasMaterial) =>
new(textureHandle, size, Vector3.UnitX, Vector3.UnitY, centerOffset, true, additive, hasMaterial);
}
}

View file

@ -4,15 +4,23 @@ in vec2 vTex;
in vec4 vColor;
out vec4 fragColor;
// Procedural rain/snow streak — no texture, just a radial falloff
// centred on the quad so droplets read as small soft circles. Good
// enough for weather + basic spell auras without a texture pipeline.
uniform sampler2D uParticleTexture;
uniform bool uUseTexture;
void main() {
// Signed distance from quad center (in UV space).
vec2 d = vTex - vec2(0.5, 0.5);
float r = length(d) * 2.0; // 0 at center, 1 at corner
float falloff = smoothstep(1.0, 0.4, r);
if (falloff < 0.02) discard;
fragColor = vec4(vColor.rgb, vColor.a * falloff);
vec4 texel;
if (uUseTexture) {
texel = texture(uParticleTexture, vTex);
} else {
vec2 d = vTex - vec2(0.5, 0.5);
float r = length(d) * 2.0;
float falloff = smoothstep(1.0, 0.4, r);
texel = vec4(1.0, 1.0, 1.0, falloff);
}
vec4 color = texel * vColor;
if (color.a < 0.02)
discard;
fragColor = color;
}

View file

@ -4,26 +4,21 @@
layout(location = 0) in vec2 aQuad;
layout(location = 1) in vec2 aTex;
// Per-instance: world-space center + size
layout(location = 2) in vec4 aPosAndSize;
layout(location = 3) in vec4 aColor;
// Per-instance: world-space center, authored sheet axes, color.
layout(location = 2) in vec4 aCenter;
layout(location = 3) in vec4 aAxisX;
layout(location = 4) in vec4 aAxisY;
layout(location = 5) in vec4 aColor;
uniform mat4 uViewProjection;
uniform vec3 uCameraRight;
uniform vec3 uCameraUp;
out vec2 vTex;
out vec4 vColor;
void main() {
vec3 center = aPosAndSize.xyz;
float size = aPosAndSize.w;
// Billboard: offset the quad vertex along the camera's right + up
// basis vectors so it always faces the viewer.
vec3 world = center
+ uCameraRight * (aQuad.x * size)
+ uCameraUp * (aQuad.y * size);
vec3 world = aCenter.xyz
+ aAxisX.xyz * aQuad.x
+ aAxisY.xyz * aQuad.y;
vTex = aTex;
vColor = aColor;

View file

@ -1,46 +1,15 @@
#version 430 core
// Sky mesh fragment shader — final composite matching retail's
// D3D fixed-function:
//
// fragment.rgb = texture.rgb × vTint + lightning_flash
// fragment.a = texture.a × (1 - uTransparency) × uSurfTranslucency
// (uSurfTranslucency is OPACITY directly per retail's
// D3DPolyRender::SetSurface at 0x59c7a6, NOT 1-x)
//
// vTint arrives from the vertex shader with retail's per-vertex
// lighting formula baked in (Emissive + lightAmbient + lightDiffuse ×
// max(N·L, 0)) — see sky.vert for the decompile citation. The keyframe
// SkyObjectReplace.Luminosity override is folded into uEmissive on the
// CPU side (SkyRenderer.cs) so vTint already saturates properly for
// bright keyframes; the previous shader had a redundant uLuminosity
// multiply that was double-dimming clouds, removed 2026-04-26.
//
// See `docs/research/2026-04-23-sky-material-state.md`.
in vec2 vTex;
in vec3 vTint;
in float vFogFactor; // 1 = no fog (near), 0 = full fog color (far)
in float vFogFactor; // 1 = no fog, 0 = full fog color
out vec4 fragColor;
uniform sampler2D uDiffuse;
uniform float uTransparency; // 0 = fully visible, 1 = fully transparent
// 1.0 = apply fog mix to this submesh; 0.0 = skip fog (Additive sky
// surfaces — sun/moon/stars per retail SetFFFogAlphaDisabled(1) at
// D3DPolyRender::SetSurface 0x59c882). Set per-submesh on the CPU side.
uniform float uApplyFog;
// Surface.Translucency float (0..1) used DIRECTLY as opacity (NOT 1-x).
// Distinct from uTransparency (per-keyframe Replace override). Retail
// D3DPolyRender::SetSurface at 0x59c7a6 (decomp 425255-425260) reads
// Surface.Translucency when the Translucent (0x10) bit is set and feeds
// _ftol2(translucency × 255) directly as vertex alpha. ACViewer
// (TextureCache.cs:142) + WorldBuilder (ObjectMeshManager.cs:1115) both
// invert it (1-x) and are wrong. For non-Translucent surfaces the CPU
// side (GfxObjMesh.Build) sets uSurfTranslucency = 1.0 ⇒ no effect.
uniform float uSurfTranslucency;
uniform float uTransparency; // keyframe transparency: 0 visible, 1 transparent
uniform float uApplyFog; // 1 for foggable sky layers; raw-additive surfaces keep retail fog disabled
uniform float uSurfOpacity; // final surface opacity multiplier from the CPU
// Shared SceneLighting UBO — fog params drive the mix, flash channel
// bumps sky brightness during lightning strikes. Matches sky.vert's
// declaration exactly.
struct Light {
vec4 posAndKind;
vec4 dirAndRange;
@ -58,79 +27,21 @@ layout(std140, binding = 1) uniform SceneLighting {
void main() {
vec4 sampled = texture(uDiffuse, vTex);
// Composite: texture × per-vertex lit. Replace.Luminosity (per
// keyframe) and Surface.Luminosity are both folded into uEmissive
// on the CPU side (SkyRenderer.cs) so vTint already carries the
// right tint for the time-of-day. Retail's fragment formula
// (FUN_0059da60 non-luminous branch) is texture × litColor ×
// vertex.color(=white), so `texture × vTint` is the retail-faithful
// composite.
vec3 rgb = sampled.rgb * vTint;
// Retail-faithful sky fog mix with a "fog floor" mitigation:
//
// Dereth sky meshes are authored at radii 10501820m. At midnight
// (storm keyframes FogEnd ~400m) the raw vFogFactor saturates to 0
// for every dome pixel — `mix(fogColor, rgb, 0)` would render the
// entire dome as flat fogColor, destroying stars / moon / texture.
// That was the reason fog was disabled on sky 2026-04-24 (issue #4).
//
// Retail clearly DOES apply fog to its sky meshes — distant horizon
// mountains and the dome itself fade toward the fog color in retail
// screenshots. Mechanism unknown (sky-specific FogEnd? elevation-
// weighted? different formula?). Until pinned, the workaround is
// a clamp on the minimum fog factor so the dome NEVER mixes more
// than (1 - SKY_FOG_FLOOR) toward fogColor — preserves stars/moon
// while still letting the horizon haze visibly in low-FogEnd
// keyframes.
//
// SKY_FOG_FLOOR=0.2 means dome shows AT LEAST 20% raw texture, AT
// MOST 80% fog color even at extreme distances. Tuned via dual-
// client visual comparison 2026-04-27 — adjust if night sky goes
// back to flat-fog or stays too vivid vs retail.
// Skip fog mix entirely on Additive surfaces (sun, moon, stars,
// additive cloud sheets) — retail's SetFFFogAlphaDisabled(1) at
// D3DPolyRender::SetSurface 0x59c882. Without this gate the sun
// dims to fog color at horizon, which doesn't match retail.
if (uApplyFog > 0.5) {
const float SKY_FOG_FLOOR = 0.2;
float skyFogFactor = max(vFogFactor, SKY_FOG_FLOOR);
rgb = mix(uFogColor.rgb, rgb, skyFogFactor);
}
// Lightning additive bump — client-driven during storm flashes.
// NOTE: the exact retail mechanism for lightning visual is still
// under research (agent #5, 2026-04-23). Keeping the uFogParams.z
// channel wired so if it ends up being a per-frame flash uniform
// that's what it becomes; if lightning turns out to be a particle
// system effect instead, this bump becomes a no-op (flash stays 0).
float flash = uFogParams.z;
rgb += flash * vec3(1.5, 1.5, 1.8);
// Normal-frame cap at 1.0 (retail D3D framebuffer clamps per-channel
// on output). Flash relaxes ceiling to 3.0 so storm strobes blow
// out visibly.
float cap = mix(1.0, 3.0, clamp(flash, 0.0, 1.0));
rgb = min(rgb, vec3(cap));
// Final fragment alpha:
// uTransparency — keyframe-replace transparency override (0..1).
// 0 = fully visible, 1 = fully transparent.
// Applied as (1 - x).
// uSurfTranslucency — the dat's Surface.Translucency value when the
// Translucent flag is set, else 1.0. Despite the
// name, retail uses this as OPACITY directly (per
// D3DPolyRender::SetSurface at 0x59c7a6 which
// writes _ftol2(translucency × 255) into vertex
// alpha). Multiply directly — NOT (1 - x).
//
// For the rain mesh 0x01004C42/4C44 (translucency=0.5): a = 1*1*0.5 = 0.5
// matches retail curr_alpha=127, halves the additive streak.
// For cloud surface 0x08000023 (translucency=0.25): a = 1*1*0.25 = 0.25
// matches retail curr_alpha=63, dim cloud (was 3× too bright with
// the previous 1-x formula).
// For non-Translucent surfaces uSurfTranslucency = 1.0, no effect.
float a = sampled.a * (1.0 - uTransparency) * uSurfTranslucency;
float a = sampled.a * (1.0 - uTransparency) * uSurfOpacity;
if (a < 0.01) discard;
fragColor = vec4(rgb, a);
}

View file

@ -47,6 +47,7 @@ uniform vec3 uSunDir; // unit vector FROM surface TO sun
// Per-submesh (from Surface.Luminosity float):
uniform float uEmissive;
uniform float uDiffuseFactor;
// Shared SceneLighting UBO — we need uFogParams.xy (fog start/end) to
// compute the vertex fog factor. Must match sky.frag's declaration.
@ -87,7 +88,7 @@ void main() {
float diff = max(dot(worldNormal, uSunDir), 0.0);
vec3 lit = vec3(uEmissive) // material.Emissive
+ uAmbientColor // material.Ambient(1) × light.Ambient
+ uSunColor * diff; // material.Diffuse(1) × light.Diffuse × N·L
+ (uSunColor * uDiffuseFactor) * diff;
vTint = clamp(lit, 0.0, 1.0);
// Retail vertex-fog in 3D-range mode (FOGVERTEXMODE=LINEAR,

View file

@ -106,8 +106,10 @@ public sealed unsafe class SkyRenderer : IDisposable
Vector3 cameraWorldPos,
float dayFraction,
DayGroupData? group,
SkyKeyframe keyframe)
=> RenderPass(camera, cameraWorldPos, dayFraction, group, keyframe, postScenePass: false);
SkyKeyframe keyframe,
bool environOverrideActive = false)
=> RenderPass(camera, cameraWorldPos, dayFraction, group, keyframe,
postScenePass: false, environOverrideActive: environOverrideActive);
/// <summary>
/// Draw the POST-SCENE sky objects (the foreground rain mesh
@ -134,8 +136,10 @@ public sealed unsafe class SkyRenderer : IDisposable
Vector3 cameraWorldPos,
float dayFraction,
DayGroupData? group,
SkyKeyframe keyframe)
=> RenderPass(camera, cameraWorldPos, dayFraction, group, keyframe, postScenePass: true);
SkyKeyframe keyframe,
bool environOverrideActive = false)
=> RenderPass(camera, cameraWorldPos, dayFraction, group, keyframe,
postScenePass: true, environOverrideActive: environOverrideActive);
/// <summary>
/// Shared pass for <see cref="RenderSky"/> and <see cref="RenderWeather"/>.
@ -151,7 +155,8 @@ public sealed unsafe class SkyRenderer : IDisposable
float dayFraction,
DayGroupData? group,
SkyKeyframe keyframe,
bool postScenePass)
bool postScenePass,
bool environOverrideActive)
{
if (group is null || group.SkyObjects.Count == 0) return;
@ -209,6 +214,12 @@ public sealed unsafe class SkyRenderer : IDisposable
float secondsSinceStart = (float)(DateTime.UtcNow - _startedAt).TotalSeconds;
// M1: track texture handles whose wrap mode we set to ClampToEdge
// so we can restore them to Repeat (TextureCache's default upload
// state) at end-of-pass. Without this, any subsequent renderer
// sharing the texture handle would silently inherit ClampToEdge.
var clampedTextures = new HashSet<uint>();
for (int i = 0; i < group.SkyObjects.Count; i++)
{
var obj = group.SkyObjects[i];
@ -227,6 +238,11 @@ public sealed unsafe class SkyRenderer : IDisposable
// foreground rain — double-thick rain not matching retail.
if (obj.IsPostScene != postScenePass) continue;
if (!obj.IsVisible(dayFraction)) continue;
// Retail GameSky::Draw (0x00506ff0) skips Properties bit 0x02
// objects while an AdminEnvirons fog override is active. Normal
// DayGroup fog/tint still draws them.
if (environOverrideActive && (obj.Properties & 0x02u) != 0u)
continue;
// Apply per-keyframe replace overrides.
uint gfxObjId = obj.GfxObjId;
@ -243,20 +259,18 @@ public sealed unsafe class SkyRenderer : IDisposable
// NO Dereth sky surface carries the SurfaceType.Luminous flag
// bit (0x40) — the differentiator is purely the float field.
float replaceLuminosity = float.NaN;
float replaceDiffuse = float.NaN;
if (replaces.TryGetValue((uint)i, out var rep))
{
if (rep.GfxObjId != 0) gfxObjId = rep.GfxObjId;
if (rep.Rotate != 0f) headingDeg = rep.Rotate;
transparent = Math.Clamp(rep.Transparent, 0f, 1f);
if (rep.Luminosity > 0f) replaceLuminosity = rep.Luminosity;
// MaxBright is a CAP: even if the surface authored Lum=1.0,
// a per-keyframe MaxBright trims it. When no explicit
// Luminosity replace exists, MaxBright still acts as the
// ceiling (applied against sub.SurfLuminosity at draw time).
// Retail GameSky::UseTime routes max_bright through
// CPhysicsObj::SetDiffusion, so it replaces material diffuse,
// not emissive/luminosity.
if (rep.MaxBright > 0f)
replaceLuminosity = float.IsNaN(replaceLuminosity)
? rep.MaxBright
: MathF.Min(replaceLuminosity, rep.MaxBright);
replaceDiffuse = rep.MaxBright;
}
if (gfxObjId == 0) continue;
@ -277,18 +291,24 @@ public sealed unsafe class SkyRenderer : IDisposable
// if (((eax_13 & 4) != 0 && (eax_13 & 8) == 0))
// int32_t var_4_1 = 0xc2f00000; // 0xc2f00000 == -120.0f
//
// Weather objects (property bit 0x04 set, bit 0x08 unset)
// have their frame origin set to player_pos + (0, 0, -120m).
// The rain cylinder GfxObjs 0x01004C42/0x01004C44 have local
// Z range 0.11..814.90 (815m tall, 113m radius). Without the
// offset the cylinder bottom sits at z=0.11 ABOVE the camera
// (skyView translation is zeroed so model-origin == camera);
// looking horizontally shows nothing, looking up shows a
// distant cylinder. With -120m the cylinder spans z =
// (camera-119.89)..(camera+694.90) in view space — camera
// is inside, looking in any direction shows surrounding
// walls — the volumetric foreground-rain look retail has.
if (postScenePass)
// Gate: bit 0x04 (weather) set AND bit 0x08 unset. NOT every
// post-scene SkyObject — bit 0x01 (post-scene) is independent
// of bit 0x04 (weather). Today's Dereth ships every post-scene
// entry as also weather-flagged so the previous unconditional
// offset was a no-op divergence, but a future DayGroup with a
// post-scene-but-not-weather entry (e.g. a foreground sun rim)
// would have been pushed 120m below the camera and rendered as
// floor lint.
//
// Without the offset on the rain cylinder GfxObjs
// 0x01004C42/0x01004C44 (local Z range 0.11..814.90) the
// cylinder bottom sits at z=0.11 ABOVE the camera (skyView
// translation is zeroed so model-origin == camera); looking
// horizontally shows nothing. With -120m the cylinder spans z
// = (camera-119.89)..(camera+694.90) — camera is inside,
// looking in any direction shows surrounding walls — the
// volumetric foreground-rain look retail has.
if (postScenePass && obj.IsWeather && (obj.Properties & 0x08u) == 0u)
model = model * Matrix4x4.CreateTranslation(0f, 0f, -120f);
_shader.SetMatrix4("uModel", model);
@ -343,20 +363,17 @@ public sealed unsafe class SkyRenderer : IDisposable
float effEmissive = float.IsNaN(replaceLuminosity)
? sub.SurfLuminosity
: replaceLuminosity;
float effDiffuse = float.IsNaN(replaceDiffuse)
? sub.SurfDiffuse
: replaceDiffuse;
_shader.SetFloat("uEmissive", effEmissive);
_shader.SetFloat("uDiffuseFactor", effDiffuse);
// Retail per-Surface translucency override (D3DPolyRender::SetSurface
// at 0x59c7a6, decomp 425255-425260): when the Surface's
// Translucent (0x10) bit is set, retail computes
// curr_alpha = _ftol2(translucency × 255) and writes it as vertex
// alpha — i.e. the dat's Translucency float is the OPACITY
// directly, NOT inverted. ACViewer and WorldBuilder both invert
// it (1 - x) and are wrong by the same misread. The shader uses
// it directly as an opacity multiplier; for non-Translucent
// surfaces the GfxObjMesh.Build() path keeps SurfTranslucency=1.0
// (no effect). Critical for rain (Translucency=0.5 → opacity 0.5)
// and clouds (Translucency=0.25 → opacity 0.25, dim like retail).
_shader.SetFloat("uSurfTranslucency", sub.SurfTranslucency);
// Material alpha is final opacity: 1 - Surface.Translucency
// for Translucent surfaces, 1 for non-Translucent surfaces.
// The CPU computes it once so the shader just multiplies it
// with texture alpha and keyframe transparency.
_shader.SetFloat("uSurfOpacity", sub.SurfOpacity);
// Retail D3DPolyRender::SetSurface at 0x59c882 calls
// SetFFFogAlphaDisabled(1) when the Additive flag (0x10000)
@ -364,9 +381,12 @@ public sealed unsafe class SkyRenderer : IDisposable
// additive cloud sheet are drawn WITHOUT fog. Skipping fog
// on additive surfaces keeps the sun bright at horizon
// dusk/dawn (where fog would otherwise dim it to fog color).
// Non-additive sky meshes (the dome, opaque cloud layers)
// still mix toward fog with the floor mitigation in sky.frag.
_shader.SetFloat("uApplyFog", sub.IsAdditive ? 0f : 1f);
// Non-additive sky meshes (the dome/background layers)
// still mix toward keyframe fog with the floor mitigation
// in sky.frag. That restores the broad green/purple Rainy
// DayGroup tint behind the cloud sheet while raw-additive
// 0x08000023 remains unfogged and keeps the pink detail.
_shader.SetFloat("uApplyFog", sub.DisableFog ? 0f : 1f);
uint tex = _textures.GetOrUpload(sub.SurfaceId);
_gl.ActiveTexture(TextureUnit.Texture0);
@ -396,11 +416,25 @@ public sealed unsafe class SkyRenderer : IDisposable
bool needsRepeat = sub.NeedsUvRepeat
|| obj.TexVelocityX != 0f
|| obj.TexVelocityY != 0f;
int wrapMode = needsRepeat
? (int)TextureWrapMode.Repeat
: (int)TextureWrapMode.ClampToEdge;
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, wrapMode);
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, wrapMode);
if (!needsRepeat)
{
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS,
(int)TextureWrapMode.ClampToEdge);
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT,
(int)TextureWrapMode.ClampToEdge);
clampedTextures.Add(tex);
}
// No else branch: TextureCache uploads with Repeat, so a
// texture whose wrap was clamped earlier this pass and is
// re-bound now still needs to be told to Repeat.
else if (clampedTextures.Contains(tex))
{
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS,
(int)TextureWrapMode.Repeat);
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT,
(int)TextureWrapMode.Repeat);
clampedTextures.Remove(tex);
}
_gl.BindVertexArray(sub.Vao);
_gl.DrawElements(PrimitiveType.Triangles,
@ -410,6 +444,18 @@ public sealed unsafe class SkyRenderer : IDisposable
}
}
// M1: restore wrap mode on every texture this pass clamped, so
// the rest of the pipeline sees TextureCache's default Repeat
// state regardless of which sky-mesh order we drew.
foreach (var tex in clampedTextures)
{
_gl.BindTexture(TextureTarget.Texture2D, tex);
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS,
(int)TextureWrapMode.Repeat);
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT,
(int)TextureWrapMode.Repeat);
}
// Restore GL state expected by the rest of the pipeline.
_gl.Disable(EnableCap.Blend);
_gl.DepthMask(true);
@ -639,7 +685,7 @@ public sealed unsafe class SkyRenderer : IDisposable
Console.WriteLine(
$"[sky-dump] Surface[{i}] 0x{surfaceId:X8} Type=0x{rawType:X8} ({names}) " +
$"OrigTexture=0x{origTex:X8} Translucency={trans} " +
$"SurfLuminosity={surface.Luminosity:F4} SurfTranslucency={surface.Translucency:F4}");
$"SurfLuminosity={surface.Luminosity:F4} SurfaceTranslucency={surface.Translucency:F4}");
}
}
@ -692,8 +738,10 @@ public sealed unsafe class SkyRenderer : IDisposable
SurfaceId = sm.SurfaceId,
IsAdditive = isAdditive,
SurfLuminosity = sm.Luminosity,
SurfDiffuse = sm.Diffuse,
NeedsUvRepeat = sm.NeedsUvRepeat,
SurfTranslucency = sm.SurfTranslucency,
SurfOpacity = sm.SurfOpacity,
DisableFog = sm.DisableFog,
};
}
@ -733,6 +781,7 @@ public sealed unsafe class SkyRenderer : IDisposable
/// <c>docs/research/2026-04-23-sky-retail-verbatim.md</c> §6.
/// </summary>
public float SurfLuminosity;
public float SurfDiffuse;
/// <summary>
/// True when the source mesh's authored UVs exceed [0,1] (e.g.
/// the inner sky/star layer 0x010015EF and the cloud meshes —
@ -744,17 +793,11 @@ public sealed unsafe class SkyRenderer : IDisposable
/// </summary>
public bool NeedsUvRepeat;
/// <summary>
/// <c>Surface.Translucency</c> float (0..1) carried through from
/// <see cref="GfxObjSubMesh.SurfTranslucency"/>. Passed to the
/// sky fragment shader as <c>uSurfTranslucency</c> and used
/// DIRECTLY as opacity (NOT <c>1 - x</c>). Retail's
/// <c>D3DPolyRender::SetSurface</c> at <c>0x59c7a6</c>
/// (decomp lines 425255-425260) computes
/// <c>curr_alpha = _ftol2(translucency × 255)</c> and writes that
/// as vertex.color.alpha — i.e. translucency is opacity directly.
/// For non-Translucent surfaces the GfxObjMesh.Build() path keeps
/// this at 1.0 so they stay fully opaque.
/// Final surface opacity from <see cref="GfxObjSubMesh.SurfOpacity"/>.
/// Translucent surfaces use <c>1 - Surface.Translucency</c>; other
/// surfaces stay at 1.0.
/// </summary>
public float SurfTranslucency;
public float SurfOpacity;
public bool DisableFog;
}
}

View file

@ -178,8 +178,9 @@ public sealed unsafe class TextureCache : IDisposable
if (surfaceTexture is null || surfaceTexture.Textures.Count == 0)
return DecodedTexture.Magenta;
var rs = _dats.Get<RenderSurface>((uint)surfaceTexture.Textures[0]);
if (rs is null)
uint renderSurfaceId = (uint)surfaceTexture.Textures[0];
if (!_dats.Portal.TryGet<RenderSurface>(renderSurfaceId, out var rs)
&& !_dats.HighRes.TryGet<RenderSurface>(renderSurfaceId, out rs))
return DecodedTexture.Magenta;
// Start with the texture's default palette, then apply overlays.