Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Media in the live frame's histories: the transmittance applied after the denoisers, media that change with time reactive (ROADMAP § 1a) (#37)

Yujia49111620a344
diff --git a/docs/MATERIAL_FUNCTIONS.md b/docs/MATERIAL_FUNCTIONS.md
index 977edf6..d015dec 100644
--- a/docs/MATERIAL_FUNCTIONS.md
+++ b/docs/MATERIAL_FUNCTIONS.md
@@ -315,6 +315,13 @@ return o; }`:
| `albedo` | scattering / extinction |
| `emission` | emitted radiance per metre |
+A function whose medium changes with time is `animated`: by default, one whose code reads `i.time`; `animated: true` or
+`false` in its options says otherwise (a medium that changes only through its node's `customData` sets it; one that
+reads the time for something that does not show clears it). A volume with a simulated `DensityGrid` is animated
+whatever its function. The live view keeps a short history where such a medium fills a quarter of a pixel or more
+(four samples in the upscaler, as for a surface with `o.animated`): without it a fire shows the frames before it. A
+still medium keeps the long history, and its noise falls with it.
+
A `VolumeMesh` has these settings:
- `shape`: box or sphere;
- `volume`: the function binding;
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 27be689..551d246 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -1807,6 +1807,38 @@ beyond their noise (ReBLUR's form; it was on / off). No edit cuts anything.
direct light and the upscaler's own history carry the frame. A geometry edit by night was not measured.
- Cost: none that shows (Bistro's passes 6.64–6.66 ms a frame in both builds).
+**Media in the live frame's histories (2026-11-12, after it).** The fire of § 6 step 10 b read worse after #30 and
+#33 (its box, ΔE at 0.2 / 0.5 / 1 s after it starts: 6.90 / 6.61 / 4.36, then 7.18 / 7.53 / 5.25, then 7.32 / 7.81 /
+5.71). Until #33 a fire's stand-in light changed every frame and so cut the whole frame's history to 16 frames, which
+hid two faults of the live path's own:
+- `media_composite` multiplied the media's transmittance into each frame's diffuse and specular lighting before the
+ denoisers accumulated them, so a surface's history held the medium of the frames before: 16 frames after a medium
+ ends, the wall behind it read 0.88 of its 2 nits (`volume/animated-clears-live`; now 2.00). The transmittance now
+ goes with the sample (`Pixel` `normal.w`) and `compose` applies it to the denoised lighting, as volumetrics are
+ composed over a denoised surface elsewhere. What the camera ray sees and the deterministic direct light have no
+ history before `compose` and take it as before.
+- Nothing said a medium changes. A volume function is `animated` when its code reads `i.time` (or says so), a
+ simulated grid always (the medium table's `a.w`); the march gives the share of the pixel such media take (what they
+ hide, or their light's share of it), and the upscaler's reactive mask rises with it to 1 at a quarter
+ (`UP_MEDIUM`): four samples of history, as for animated shading.
+
+| the fire shot (bench-voxel-fire, lockstep, 0.75), the fireball's box ΔE at 0.2 / 0.5 / 1 s | with the fire light | without |
+|---|---|---|
+| main before | 7.32 / 7.81 / 5.71 | 7.51 / 8.47 / 7.56 |
+| the transmittance out of the histories, alone | 6.78 / 6.35 / 4.59 | 6.86 / 6.42 / 5.02 |
+| animated media reactive, alone | 7.02 / 7.24 / 4.91 | |
+| both | 6.28 / 5.56 / 3.69 | 6.36 / 5.62 / 4.19 |
+| the bound of #33 back at 16 frames instead (what #33 changed for the fire) | 7.18 / 7.55 / 5.27 | |
+
+- The real-time frame against the same moment held: 5.33 / 2.71 / 1.57 (5.74 / 4.65 / 3.52); the held frame against
+ offline 3.64 / 4.32 / 2.70 as before (the march's own picture, not this).
+- Reactive by the share itself, without the quarter: a little worse (6.44 / 5.70 / 3.78).
+- Elsewhere: bench-ghosting passes with the numbers of the table above for Bistro and 2.42, 3.27, 1.17, 1.22, 2.48 for
+ Kabukichō; the Bistro slice half a second after its explosion 6.03 / SSIM 0.832 in both builds (its fireball is a
+ small part of that view). test-render 179 pass.
+- Not done: live GI, reflection and shadow rays still see no media (the stand-in light stays), overlapping media are
+ still taken whole in entry order, and a medium has no motion vector (smoke that drifts is reactive, not followed).
+
Not done here: filters sized by hit distance, which is what would let a short history stand without noise; the
Playground and the page still open a 1280 × 720 view; the live buffers are sized by the output (about 1.7 GB at
2560 × 1440), though the traced grid rarely fills it.
@@ -4424,7 +4456,7 @@ benchmark level. The order follows the dependencies; a step that meets a further
the shared paths are fixed): the stand-in light (live rays have no media code: offline it counts the fire's
light twice unless `lights: 0`, live it lights the fireball a second time); idle objects parked far away
(hiding a volume rebuilds); idle lights reaching 1 mm (a black rangeless light reaches without limit); the
- fire's history once capped by its light's change (gone since #33: see the Open below); the smoke kept by never
+ fire's history once capped by its light's change (gone since #33, and closed at its source: below); the smoke kept by never
rebuilding (a rebuild loses a grid's simulation); and volumes
that must not overlap (`media_track` / `media_march` take media whole in entry order: no smoke grid around
explosions, and two fires close together still overlap).
@@ -4432,12 +4464,10 @@ benchmark level. The order follows the dependencies; a step that meets a further
voxels**, are not done.
- Open: the live march's media are lighter and more see-through than offline (8 steps; in-scattering isotropic
from the cache): the fireball reads lighter than offline.
- - Open (measured on `0a89089`, after #33): the fireball ghosts and nothing mitigates it. #33 bounds each pixel's
- history at 32 frames while the lighting changes instead of cutting the whole frame's to 16, so the fire
- light's change no longer holds the fireball's history down: its region reads ΔE 7.32 / 7.81 / 5.71 at 0.2 /
- 0.5 / 1 s (6.90 / 6.61 / 4.36 before; without the light 7.51 / 8.47 / 7.55); the street as before. The cause
- is the temporal filter's: no per-medium "changes with time" signal; measured again once the shared path has
- one (docs/VOXEL.md, the temporary ways round).
+ - Closed at its source (§ 1a, "Media in the live frame's histories"): the fireball's ghosting. After #33 its
+ region read ΔE 7.32 / 7.81 / 5.71 at 0.2 / 0.5 / 1 s (6.90 / 6.61 / 4.36 when this step merged); now 6.28 /
+ 5.56 / 3.69, without the fire light 6.36 / 5.62 / 4.19, and the whole image meets at 0.2 and 0.5 s (1.77 /
+ 0.964, 2.54 / 0.942; 2.99 / 0.895 at 1 s). What is left is the live march's own picture (the Open above).
- **(c1) Joints and the blast** (branch `vehicles-ropes`; design `out/web-probe/step10/c-design.md`; docs/VOXEL.md
"Joints, the level's anchor and the blast"). (c) split in two (the supervisor, 2026-11-12: engine structure
first, features after). The user's decisions 1-4 (2026-11-12), each the standard structure where the engine did
diff --git a/docs/VOXEL.md b/docs/VOXEL.md
index f8cfe53..782d865 100644
--- a/docs/VOXEL.md
+++ b/docs/VOXEL.md
@@ -576,7 +576,7 @@ takes the pool out of the scene for good.
- **A fire** (`fire(at, r, time)`): the next fireball of the pool, 2.2 r across (5 cm to 40 m), its centre 0.3 r above
the explosion's point, from `time` (now or later); a light at its centre while it burns, from the first step after
it starts (at age 0 it gives none, and takes no light from an older fire). Time going back (a restart) ends every
- fire. Two fires close together make two fireballs that overlap: the engine cannot draw that rightly yet (the sixth
+ fire. Two fires close together make two fireballs that overlap: the engine cannot draw that rightly yet (the last
temporary way round below; nothing in `Explosions` keeps them apart). The fireball's default peak is 30,000 nits (a
flame's; `Fireball`'s own 40 is a stylised night's and does not show by day). Every object of the pool is made in
setup and `movable`: firing moves them in place (a fixed object's first move rebuilds the live scene once: 281 ms on
@@ -620,32 +620,41 @@ fire's emission, and the stand-in light is there as well. The bench's references
`crater` spot, by day (fireballs, no grid), the live frame at render scale 0.75 (never 1: at exactly 1 the live frame has no edge
anti-aliasing), 1280 x 720, lockstep at 60 fps from the start, against our offline render of the same scene time
(2,048 spp, no clamps, no denoiser; 1,024 against 2,048 spp: ΔE 0.40, SSIM 0.993), which has the fireball's own light
-and no fire light. Live in lockstep is bit-reproducible (A/A ΔE 0.00). Targets ΔE ≤ 3, SSIM ≥ 0.9. Measured on main
-`0a89089` (after #33, `f2dfb0b`, which bounds each pixel's history at 32 frames while the lighting changes instead of
-capping the whole frame's at 16), with the numbers from before #33 beside them:
+and no fire light. Live in lockstep is bit-reproducible (A/A ΔE 0.00). Targets ΔE ≤ 3, SSIM ≥ 0.9. Measured with the
+live view telling media that change with time from the surfaces behind them (below), on main `230b0f3`; beside them
+main before that (`0a89089`):
-| after the fire starts | whole image ΔE / SSIM | the fireball (its box) ΔE / p99 / SSIM / luminance | the street below it ΔE / SSIM / luminance | before #33: whole / fireball / street |
+| after the fire starts | whole image ΔE / SSIM | the fireball (its box) ΔE / p99 / SSIM / luminance | the street below it ΔE / SSIM / luminance | main before: whole / fireball / street |
| --- | --- | --- | --- | --- |
-| 0.2 s | **1.86 / 0.963** | 7.32 / 36 / 0.822 / 1.04 | **1.34 / 0.972** / 0.99 | 2.11 / 0.949; 6.90 / 31 / 0.846 / 1.02; 1.38 / 0.960 / 1.00 |
-| 0.5 s | 3.21 / 0.930 | 7.81 / 39 / 0.815 / 1.27 | **0.99 / 0.981** / 1.03 | 3.08 / 0.930; 6.61 / 31 / 0.850 / 1.22; 1.00 / 0.978 / 1.03 |
-| 1.0 s | 4.39 / 0.851 | 5.71 / 41 / 0.796 / 1.16 | (the fireball's box reaches the image's foot) | 3.53 / 0.876; 4.36 / 28 / 0.839 / 1.09 |
+| 0.2 s | **1.77 / 0.964** | 6.28 / 30 / 0.832 / 1.01 | **1.34 / 0.972** / 0.99 | 1.86 / 0.963; 7.32 / 36 / 0.822 / 1.04; 1.34 / 0.972 / 0.99 |
+| 0.5 s | **2.54 / 0.942** | 5.56 / 30 / 0.855 / 1.18 | **0.98 / 0.981** / 1.03 | 3.21 / 0.930; 7.81 / 39 / 0.815 / 1.27; 0.99 / 0.981 / 1.03 |
+| 1.0 s | 2.99 / 0.895 | 3.69 / 26 / 0.861 / 1.08 | (the fireball's box reaches the image's foot) | 4.39 / 0.851; 5.71 / 41 / 0.796 / 1.16 |
Where it falls short, and why:
-- **The fireball** misses at every age, and since #33 by more at 0.5 and 1 s (ΔE 6.61 → 7.81, 4.36 → 5.71). Part of
- it is the live media's own picture, unchanged by #33: the same moment held (time all but stopped, 120 frames)
- against offline reads ΔE 3.63 / 4.34 / 2.73 (3.78 / 4.28 / 2.80 before), SSIM 0.920 / 0.895 / 0.905: the live view
+- **The fireball** misses at every age. Most of it is the live media's own picture: the same moment held (time all
+ but stopped, 120 frames) against offline reads ΔE 3.64 / 4.32 / 2.70, SSIM 0.903 / 0.881 / 0.903: the live view
marches 8 steps through a fireball whose noise is finer than that, and lights it from the radiance cache's voxels
- (isotropic); its cooled smoke reads lighter and more see-through than offline. The rest is the temporal filter:
- the real-time frame against the held one, ΔE 5.74 / 4.65 / 3.51 (5.92 / 3.96 / 2.45 before). The filter does not
- know a procedural medium changes with time, so it keeps the hotter fireball of the frames before (luminance 1.27
- of offline at 0.5 s). Before #33 the fire light's change each frame cut the whole frame's history to 16 frames,
- which held this down; since #33 a lighting change bounds each pixel's history at 32 frames, and the light makes
- little difference to the fireball: without it ΔE 7.51 / 8.47 / 7.55 (11.2 / 9.9 / 9.5 before #33), with it 7.32 /
- 7.81 / 5.71. Nothing mitigates the ghosting now (the temporary ways round below). The light still lights the street
- (the street's numbers as before #33).
-- **The whole image** meets at 0.2 s, is 0.21 over in ΔE at 0.5 s (SSIM met), and misses at 1.0 s (the fireball's box
- now spans the image's height, its smoke over the top cells). Its p99 (19 / 29 / 37) grows with the fireball's box;
- away from the fire the cells' p99 is the level's own at 0.75 (foliage, about 10).
+ (isotropic); its cooled smoke reads lighter and more see-through than offline. The rest is the temporal filter,
+ the real-time frame against the held one: ΔE 5.33 / 2.71 / 1.57 (5.74 / 4.65 / 3.51 on main before). At 0.2 s the
+ fireball is 12 frames old and grows fastest; a pixel there holds four samples of history.
+- **What the temporal filter does with a medium** (the shared live path; `pathtrace.wgsl` `media_composite`,
+ `live.wgsl` `compose`). Two faults were in it, both measured here:
+ - The medium's transmittance was multiplied into each frame's diffuse and specular lighting before those were
+ accumulated, so the surface behind kept the fireball's shadow of the frames before. It now goes with the sample
+ and is applied to the denoised lighting where the frame is composed (alone: the fireball 6.78 / 6.35 / 4.59).
+ `volume/animated-clears-live`: 16 frames after a medium ends, the wall behind it read 0.88 of 2 nits; now 2.00.
+ - Nothing told the filter that a medium changes. A volume function is `animated` when its code reads `i.time` (or
+ says so), a simulated grid always; the march gives the share of each pixel such media take, and the upscaler
+ holds four samples of history there, as it does for a surface with animated shading (alone: 7.02 / 7.24 / 4.91).
+ The fire light no longer matters to the fireball: without it ΔE 6.36 / 5.62 / 4.19. It lights the street.
+- **How the numbers moved** (the fireball's box at 0.2 / 0.5 / 1 s): 6.90 / 6.61 / 4.36 when step 10 b merged, with
+ the fire light's change cutting the whole frame's history to 16 frames (without the light 11.2 / 9.9 / 9.5); 7.18 /
+ 7.53 / 5.25 after #30 (the frame at render resolution and its upscaler, which holds 16 samples of its own;
+ without the light 7.51 / 8.47 / 7.56); 7.32 / 7.81 / 5.71 after #33 (the cut gone, each pixel bounded at 32 frames
+ while the lighting changes); 6.28 / 5.56 / 3.69 now.
+- **The whole image** meets at 0.2 and 0.5 s; at 1.0 s its ΔE meets and its SSIM is 0.005 short (the fireball's box
+ spans the image's height, its smoke over the top cells). Its p99 (16 / 21 / 24) grows with the fireball's box; away
+ from the fire the cells' p99 is the level's own at 0.75 (foliage, about 10).
#### Why volumes must not overlap (measured 2026-11-12, kept as the evidence)
@@ -667,7 +676,7 @@ detail, at 0.5 and 1 s its region ΔE 17.0 and 10.8 with live 1.5 times offline'
live light flecks), against the fireball's 6.9 / 6.6 / 4.4 with a flame's shape; and a grid covers its box only (16 of
the level's 160 wall spots), a small fire is one to four cells, every cell is simulated every frame, and offline has
no reference for a fire that does not start at 0 s (`out/web-probe/step10/b-structure-data.md`). Until the engine
-draws overlapping media together (the sixth temporary way round below), the fire stays out of the grid.
+draws overlapping media together (the last temporary way round below), the fire stays out of the grid.
Cost: `--only cost`, the destruction game's routes at 0.75, lockstep (frames as fast as the GPU goes), GPU ms p50 over
2 s before and 4 s after the explosion; no rebuild in any run.
@@ -749,16 +758,17 @@ wild).
### Temporary ways round on the engine's shared paths
-`Explosions` (step 10 b) works round six faults of the shared renderer, in its own code, until they are fixed
+`Explosions` (step 10 b) works round five faults of the shared renderer, in its own code, until they are fixed
there (the user, 2026-11-12: these are temporary; the shared paths are fixed in their own PRs, then these go, in a PR
-of their own). Each place in `packages/voxel/src/explosions.ts` points here.
+of their own). Each place in `packages/voxel/src/explosions.ts` points here. (A sixth is closed at its source: the
+fireball's ghosting, once held down by its light's change cutting the whole frame's history; "Where it falls short"
+above.)
| What | Now | The fault at its source | Known side effects | It can go when | How to tell |
| --- | --- | --- | --- | --- | --- |
| The stand-in light | a point light at each burning fire, its intensity and colour from `FIRE_LIGHT`, measured against offline | live secondary and shadow rays have no media code: `pathtrace.wgsl` `media_shadows()` is false live (line 796), GI and reflection rays never meet a medium | offline the fire's light counts twice unless the game passes `lights: 0` (`level-destruction-fire` rendered offline has both); live, `media_train` adds the light to the radiance cache's voxels (`point_direct`, `point_sphere`): the fireball (and its smoke) is lit by it a second time; the table holds for the defaults (density, life scaled; measured by day over a floor and a wall, the fireball 0.6 of its size above it; past 8.8 m the 8.8 m values) | live rays see media: a medium's emission lights surfaces and shadows pass through it | `lights: 0`, then `tools/bench-voxel-fire.ts --only quality`: the street and the fireball's regions at least as close to offline as with the light; `voxel/fire-light` replaced by a live test of the fire's own light |
| Idle fireballs parked | at y = −10,000, scale 1e-3, instead of hidden | `World::set_visible` (`world.rs` line 750): hiding anything but particles rebuilds the live scene | parked fireballs keep their slots among the kernel's 32 volumes, and every pixel's march still tests their boxes | hiding a volume or a light is done in place | `visible = false` instead of parking; the bench's cost runs report no rebuild after an explosion |
| Idle lights reach 1 mm | an idle light's `distance` is 1 mm where it is parked | `light_reach` (`lib.rs` line 211): a black light without a range reaches without limit, and the kernel does not skip black lights before the group test (`pathtrace.wgsl` line 1578) | parked lights 10 km away share a group of 16 with lit ones, and groups are not sorted again when lights move (`lib.rs` line 277): the group's sphere is about 5 km wide while any fire burns (the per-light range test still works) | black lights reach nothing (or are hidden in place) and moved lights are grouped again | distance 0 on idle lights; the fire route's GPU time before any explosion within 0.1 ms of the smoke route's |
-| The fire's ghosting: no way round left | nothing: since #33 (`f2dfb0b`) the light's change no longer limits the fireball's history (before, any lighting change cut the whole frame's history to 16 frames, which held the ghosting down; now it bounds each pixel's at 32, `HISTORY_LIVE`). With the light and without, the fireball reads about the same (ΔE 7.32 / 7.81 / 5.71 against 7.51 / 8.47 / 7.55 at 0.2 / 0.5 / 1 s); the light is there for the street, not for this | the temporal filter has no "this medium changes" signal (surfaces have `o.animated`; a procedural medium has nothing) | the fireball ghosts: worse at 0.5 and 1 s than before #33 (ΔE 6.61 → 7.81, 4.36 → 5.71; real-time against held 3.96 → 4.65, 2.45 → 3.51) | the shared path gives media a per-medium "changes with time" signal the temporal pass uses per pixel; then measure again | `--only quality`, with `lights: 0` too: the fire's region within its held (converged) value |
| The smoke kept by never rebuilding | the pool's objects movable from the start; idle ones parked, not hidden (`Explosions` has no grid now: this keeps a game's own `SimulatedSmoke`) | `LiveCore::rebuild` (`live.rs` line 3474) → `load_scene` → `Gpu::upload` makes new grid textures (`gpu.rs` line 1664): the simulated state is not carried over | any other structural change in the game (an object added, a texture, an edit's fallback) wipes the smoke and the fire burning in it | a rebuild carries every simulated grid's state over | the bench's smoke check with a rebuild forced at 1 s (an object added): the smoke at 3 s as without it |
| Volumes must not overlap | `Explosions` has no smoke grid (it refuses one); the smoke is each fireball's own. Two fires close together still make two fireballs that overlap: nothing keeps them apart (no distance rule) | `media_track` (offline) and `media_march` (live) in `pathtrace.wgsl` take the media whole, in the order a ray enters them (at most 32, a 32-bit mask), not their coefficients summed along the ray; hence the rule (`core.ts` `VolumeMesh`, MATERIAL_FUNCTIONS.md) | a fire inside smoke is drawn behind all of it (measured: not seen at all at 0.2 and 0.5 s, "Why volumes must not overlap"); neighbouring fireballs hide each other in the same way; no smoke grid around explosions | overlapping media are drawn together: one march summing every medium's coefficients per step along the ray (or a froxel volume), offline and live | puff a `SimulatedSmoke` around fireballs again (`Explosions` taking a grid) and run the comparison that found it (`bench-voxel-fire` at d7b4e4a, `--only smoke --ages 0.2,0.5`): the fire seen in its smoke offline and live; two overlapping fireballs both seen |
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index 8637b55..d067a1f 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -1416,18 +1416,23 @@ export class GpuParticles extends Object3D {
* `i.lp` (the volume's own space: the box [-0.5, 0.5]^3 or the sphere of radius 0.5), `i.time`, `i.custom` (the node's
* customData); outputs `o.extinction`, `o.albedo`, `o.emission` (defaults 0, white, black). Parameters are `$Name`,
* like a MaterialFunction's. See docs/MATERIAL_FUNCTIONS.md, "Volume functions".
+ *
+ * `animated`: the medium changes with time (fire, drifting smoke), so the live view keeps a short history of the
+ * pixels it fills, as it does for a surface whose shading is animated. By default: whether the code reads `i.time`.
*/
export class VolumeFunction {
readonly name: string;
readonly params: Record<string, number | Vec4Like>;
readonly code: string;
readonly helpers: string;
- constructor(name: string, o: { params?: Record<string, number | Vec4Like>; code: string; helpers?: string }) {
+ readonly animated: boolean;
+ constructor(name: string, o: { params?: Record<string, number | Vec4Like>; code: string; helpers?: string; animated?: boolean }) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error(`VolumeFunction name "${name}" must be an identifier`);
this.name = name;
this.params = o.params ?? {};
this.code = o.code;
this.helpers = o.helpers ?? "";
+ this.animated = o.animated ?? /\bi\.time\b/.test(o.code + this.helpers);
}
/** Binding for a `VolumeMesh`: parameter overrides. */
with(params: Partial<Record<string, number | Vec4Like>> = {}): VolumeBinding {
@@ -1548,6 +1553,10 @@ export class VolumeMesh extends Object3D {
readonly homogeneous: boolean;
/** A density grid across the box, which `volume` reads with `vgrid(i, i.lp)` (`DensityGrid`; box volumes). */
readonly grid: DensityGrid | null;
+ /** The medium changes with time: its function says so (`VolumeFunction` `animated`), or its grid is simulated. */
+ get animated(): boolean {
+ return this.volume.fn.animated || !!this.grid?.program;
+ }
constructor(o: { shape?: "box" | "sphere"; volume: VolumeBinding; majorant: number; anisotropy?: number; homogeneous?: boolean; grid?: DensityGrid | null }) {
super();
if (!(o.majorant > 0)) throw new Error("VolumeMesh: majorant must be > 0 (1/m)");
diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts
index 1e172f9..c4d555c 100644
--- a/packages/scene/src/engine.ts
+++ b/packages/scene/src/engine.ts
@@ -167,7 +167,7 @@ type ObjectKindDesc =
| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "particles"; count: number; emitter: { id: string; params: number[] }; material: number; emitterArea?: number }
/** `GpuParticles`: `program` (its id and 8 vec4 of parameters), `rate` per s, `collide` (plane height, voxels, restitution, friction). */
| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "gpuParticles"; capacity: number; program: { id: string; params: number[] }; material: number; rate: number; collide: { plane?: number; voxels?: boolean; restitution?: number; friction?: number }; emitterArea?: number }
- | { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "volume"; shape: "box" | "sphere"; volume: { id: string; params: number[] }; majorant: number; g: number; homogeneous?: boolean; grid?: number }
+ | { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "volume"; shape: "box" | "sphere"; volume: { id: string; params: number[] }; majorant: number; g: number; homogeneous?: boolean; animated?: boolean; grid?: number }
| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "procedural"; geometry: number; materials: number[] }
/** `InstancedMesh`: `count` instances (its capacity) of triangle geometry (`materials[0]`) or procedural geometry. */
| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "instanced"; geometry: number; procedural?: boolean; materials: number[]; count: number };
@@ -1025,7 +1025,7 @@ export class SceneBinding {
}
if (o instanceof Mesh) return `mesh:${this.geometryId(this.drawnGeometry(o))}:${this.meshMaterials(o).join(",")}:${o.castShadow}:${o.dynamicGeometry || o.geometry.dynamic}`;
if (o instanceof ProceduralMesh) return `procedural:${this.proceduralId(o.geometry)}:${o.materials.map((m) => this.materialId(m)).join(",")}:${o.castShadow}`;
- if (o instanceof VolumeMesh) return `volume:${o.shape}:${JSON.stringify(this.volumeBinding(o.volume))}:${o.majorant}:${o.anisotropy}:${o.homogeneous}:${o.grid ? this.gridId(o.grid) : ""}`;
+ if (o instanceof VolumeMesh) return `volume:${o.shape}:${JSON.stringify(this.volumeBinding(o.volume))}:${o.majorant}:${o.anisotropy}:${o.homogeneous}:${o.animated}:${o.grid ? this.gridId(o.grid) : ""}`;
if (o instanceof GpuParticles) return `gpuParticles:${o.capacity}:${JSON.stringify(this.particleProgram(o.program))}:${this.materialId(o.material)}:${o.castShadow}:${o.emitterArea}:${o.rate}:${JSON.stringify(o.collide)}`;
if (o instanceof Particles) return `particles:${o.count}:${JSON.stringify(this.particleEmitter(o.emitter))}:${this.materialId(o.material)}:${o.castShadow}:${o.emitterArea}`;
if (o instanceof GLTFModel) return `model:${o.uri}:${o.nodes?.join(",") ?? ""}:${o.castShadow}:${o.functions ? JSON.stringify(this.modelFunctions(o)) : ""}`;
@@ -1049,7 +1049,7 @@ export class SceneBinding {
return { ...base, kind: "mesh", geometry: this.geometryId(this.drawnGeometry(o)), material: mats[0], ...(mats.length > 1 ? { materials: mats } : {}), ...(o.dynamicGeometry || o.geometry.dynamic ? { dynamicGeometry: true } : {}) };
}
if (o instanceof ProceduralMesh) return { ...base, kind: "procedural", geometry: this.proceduralId(o.geometry), materials: o.materials.map((m) => this.materialId(m)) };
- if (o instanceof VolumeMesh) return { ...base, kind: "volume", shape: o.shape, volume: this.volumeBinding(o.volume), majorant: o.majorant, g: o.anisotropy, ...(o.homogeneous ? { homogeneous: true } : {}), ...(o.grid ? { grid: this.gridId(o.grid) } : {}) };
+ if (o instanceof VolumeMesh) return { ...base, kind: "volume", shape: o.shape, volume: this.volumeBinding(o.volume), majorant: o.majorant, g: o.anisotropy, ...(o.homogeneous ? { homogeneous: true } : {}), ...(o.animated ? { animated: true } : {}), ...(o.grid ? { grid: this.gridId(o.grid) } : {}) };
if (o instanceof GpuParticles) return { ...base, kind: "gpuParticles", capacity: o.capacity, program: this.particleProgram(o.program), material: this.materialId(o.material), rate: o.rate, collide: { ...o.collide }, ...(o.emitterArea > 0 ? { emitterArea: o.emitterArea } : {}) };
if (o instanceof Particles) return { ...base, kind: "particles", count: o.count, emitter: this.particleEmitter(o.emitter), material: this.materialId(o.material), ...(o.emitterArea > 0 ? { emitterArea: o.emitterArea } : {}) };
if (o instanceof GLTFModel) {
diff --git a/packages/scene/test/engine.test.ts b/packages/scene/test/engine.test.ts
index 31b53d8..0b064d2 100644
--- a/packages/scene/test/engine.test.ts
+++ b/packages/scene/test/engine.test.ts
@@ -380,6 +380,22 @@ test("GpuParticles: the program's WGSL is sent once, the node's desc carries cap
assert.throws(() => new GpuParticles({ capacity: 4, program: prog.with(), material: mat, collide: { friction: 2 } }), /friction/);
});
+test("volume functions: one that reads the time is animated, unless it says otherwise; the volume's description carries it", () => {
+ const still = new VolumeFunction("still_fog", { code: "o.extinction = 1.0;" });
+ const drift = new VolumeFunction("drift", { code: "o.extinction = fract(i.time);" });
+ const helper = new VolumeFunction("drift_helper", { helpers: "fn dh(i: VIn) -> f32 { return fract(i.time); }", code: "o.extinction = dh(i);" });
+ const custom = new VolumeFunction("by_custom", { code: "o.extinction = i.custom.x;", animated: true });
+ const held = new VolumeFunction("held", { code: "o.extinction = 1.0 + 0.0 * i.time;", animated: false });
+ assert.deepEqual([still, drift, helper, custom, held].map((f) => f.animated), [false, true, true, true, false]);
+ const scene = new Scene();
+ scene.add(new VolumeMesh({ volume: still.with(), majorant: 1 }), new VolumeMesh({ volume: drift.with(), majorant: 1 }));
+ const cam = new PerspectiveCamera();
+ scene.add(cam);
+ const { calls } = bind(scene, cam);
+ const volumes = (ofType(calls, "object").map((c) => c[2]) as ObjectDesc[]).filter((o) => o.kind === "volume") as Extract<ObjectDesc, { kind: "volume" }>[];
+ assert.deepEqual(volumes.map((v) => v.animated), [undefined, true]);
+});
+
test("density grids: the grid goes before its volume, with its program's WGSL once; new data and sources go in place", () => {
const scene = new Scene();
const fn = new VolumeFunction("grid_reader", { params: { K: 2 }, code: "o.extinction = $K * vgrid(i, i.lp).x;" });
@@ -400,6 +416,8 @@ test("density grids: the grid goes before its volume, with its program's WGSL on
assert.deepEqual([grids[1][2].size, grids[1][2].channels, grids[1][2].program!.id, grids[1][2].program!.params.slice(0, 8), grids[1][3]], [[4, 2, 2], 4, "fill", [5, 0, 0, 0, 1, 0, 0, 0], null]);
const volumes = (ofType(calls, "object").map((c) => c[2]) as ObjectDesc[]).filter((o) => o.kind === "volume") as Extract<ObjectDesc, { kind: "volume" }>[];
assert.deepEqual(volumes.map((v) => v.grid), [grids[0][1], grids[1][1]]);
+ // A simulated grid's medium changes with time whatever its function reads; stored data alone does not.
+ assert.deepEqual(volumes.map((v) => v.animated), [undefined, true]);
const at = (pred: (c: [string, ...unknown[]]) => boolean) => calls.findIndex(pred);
assert.ok(at((c) => c[0] === "densityGrid") < at((c) => c[0] === "object" && (c[2] as ObjectDesc).kind === "volume"), "the grid before the volume that names it");
// New data: sent again (the engine uploads it in place); sources: after, once.
diff --git a/packages/voxel/src/explosions.ts b/packages/voxel/src/explosions.ts
index 331405d..88dc2ba 100644
--- a/packages/voxel/src/explosions.ts
+++ b/packages/voxel/src/explosions.ts
@@ -272,8 +272,6 @@ export class Explosions extends Group {
l.position.set(...PARK);
continue;
}
- // (Its change each frame also caps the live view's history, which keeps the fire from ghosting: a temporary way
- // round relied on, docs/VOXEL.md "Temporary ways round on the engine's shared paths".)
lit++;
const { k, rgb } = g;
const peak = Math.max(...rgb);
diff --git a/renderer/shaders/live.wgsl b/renderer/shaders/live.wgsl
index 04f2d3d..132360b 100644
--- a/renderer/shaders/live.wgsl
+++ b/renderer/shaders/live.wgsl
@@ -33,7 +33,7 @@ struct LiveParams {
jit: vec4<f32>, // this frame's sub-pixel jitter (every traced sample's: x, y in 0 .. 1 of a traced pixel), -, -
};
// color = diffuse lighting + first-hit distance, emit = directly seen emission / sky + roughness, spec = specular lighting
-// + reflection hit distance (see pathtrace.wgsl).
+// + reflection hit distance, normal.w = the media before the first hit (`medium_tr`, `medium_share`; see pathtrace.wgsl).
struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec4<f32>, spec: vec4<f32> };
@group(0) @binding(0) var<uniform> L: LiveParams;
@@ -286,9 +286,19 @@ fn sample_clamp() -> f32 {
return L.misc2.y / max(exposure_scale(), 1e-8);
}
+// The media between the camera and traced sample q's first hit (pathtrace.wgsl `media_composite`): their
+// transmittance, which the sample's diffuse and specular lighting do not carry (it is applied where they are composed,
+// after their histories and filters), and how much of the pixel is a medium that changes with time.
+fn medium_tr(q: u32) -> f32 {
+ return clamp(fract(sample_px[q].normal.w) * 2.0, 0.0, 1.0);
+}
+fn medium_share(q: u32) -> f32 {
+ return floor(sample_px[q].normal.w) / 255.0;
+}
+
fn sample_color(q: u32) -> vec3<f32> {
let s = sample_parts(q);
- return s[0] + s[1] + s[2];
+ return (s[0] + s[1]) * medium_tr(q) + s[2];
}
// The traced sample under an output pixel (nearest by the pixels' centres).
@@ -765,10 +775,11 @@ fn spec_filter_traced(gid: vec3<u32>, step: i32, from_a: bool) {
@compute @workgroup_size(8, 8, 1) fn sfilt2(@builtin(global_invocation_id) gid: vec3<u32>) { spec_filter_traced(gid, 4, true); }
// The frame at render resolution: each traced sample's colour (its own albedo times the denoised irradiance, the
-// denoised specular, what the camera ray saw directly and the deterministic direct light) into fb (w: first-hit
-// distance), and its motion into `xhist_out`: screen velocity (output pixels this frame; camera and object), view depth,
-// and whether its shading is animated (signs, screens: the upscaler's reactive mask, as FSR 2 and UE's responsive AA
-// take one: what changes there has no motion vector).
+// denoised specular, both through the media before the surface, what the camera ray saw directly and the deterministic
+// direct light) into fb (w: first-hit distance), and its motion into `xhist_out`: screen velocity (output pixels this
+// frame; camera and object), view depth, and the upscaler's reactive mask, as FSR 2 and UE's responsive AA take one
+// (what changes there has no motion vector): 1 where the surface's shading is animated (signs, screens), and up to 1
+// with the share of the pixel that is a medium changing with time (fire, simulated smoke).
@compute @workgroup_size(8, 8, 1)
fn compose(@builtin(global_invocation_id) gid: vec3<u32>) {
let iw = L.isz.x;
@@ -777,7 +788,7 @@ fn compose(@builtin(global_invocation_id) gid: vec3<u32>) {
let q = gid.y * iw + gid.x;
let px = sample_px[q];
let t = px.color.w;
- let c = fa[q].rgb * max(px.albedo.rgb, vec3<f32>(0.02)) + spec_load(1u, q).rgb + sample_parts(q)[2] + direct_in[q].rgb;
+ let c = (fa[q].rgb * max(px.albedo.rgb, vec3<f32>(0.02)) + spec_load(1u, q).rgb) * medium_tr(q) + sample_parts(q)[2] + direct_in[q].rgb;
let sp = sample_pos(i32(gid.x), i32(gid.y));
let dir = ray_dir(L.cur, sp.x, sp.y);
var p = L.cur.pos.xyz + dir * 1.0e6;
@@ -797,7 +808,8 @@ fn compose(@builtin(global_invocation_id) gid: vec3<u32>) {
if (pv.z > 0.0) { vel = clamp(sp - 0.5 - pv.xy, vec2<f32>(-2048.0), vec2<f32>(2048.0)); }
}
fb[q] = vec4<f32>(finite_or_zero(max(c, vec3<f32>(0.0))), t);
- xhist_out[q] = vec4<f32>(vel, depth, select(0.0, 1.0, px.albedo.w > 1.5));
+ let reactive = max(select(0.0, 1.0, px.albedo.w > 1.5), clamp(medium_share(q) / UP_MEDIUM, 0.0, 1.0));
+ xhist_out[q] = vec4<f32>(vel, depth, reactive);
}
// The upscaler works on linear radiance and its means are plain ones. (Weighted by 1 / (1 + luminance x exposure), so
@@ -815,6 +827,8 @@ const UP_SHARP: f32 = 3.5;
const UP_REJECT: f32 = 0.25;
// The same on animated shading (`compose`'s reactive mask): it shows this frame's picture, not a mean of the last ones.
const UP_REACTIVE: f32 = 4.0;
+// The share of a pixel a medium that changes with time takes (`medium_share`) from which the pixel is as reactive.
+const UP_MEDIUM: f32 = 0.25;
// How far outside the range of the history's pixels around it a point sample may lie, in that range's widths (`judge`).
const UP_POINT: f32 = 0.5;
// A surface counts as gone from in front when what is nearest now lies behind what was nearest by this share of its
@@ -1098,7 +1112,7 @@ fn upscale(@builtin(global_invocation_id) gid: vec3<u32>) {
if (kept > 0.0) {
var hc = max(hist.rgb + verdict.xyz, vec3<f32>(0.0));
hc = mix(hc, clamp(hc, xlo, xhi), moving);
- let most = min(mix(UP_SAMPLES, UP_MOVING, moving), select(UP_SAMPLES, UP_REACTIVE, xhist_out[u32(bc.y * iw + bc.x)].w > 0.5));
+ let most = min(mix(UP_SAMPLES, UP_MOVING, moving), mix(UP_SAMPLES, UP_REACTIVE, clamp(xhist_out[u32(bc.y * iw + bc.x)].w, 0.0, 1.0)));
count = min(kept + conf, most);
let a = clamp(conf / max(count, 1e-4), 0.0, 1.0);
outc = mix(hc, cur, a);
@@ -1552,11 +1566,11 @@ fn post(@builtin(global_invocation_id) gid: vec3<u32>) {
// denoised signals apart: diffuse (6: the composed colour less the rest), specular (7), deterministic direct light (8).
// (6 does not hold with depth of field and motion blur both on: the composed colour's buffer is theirs then.)
let tq = sample_under(gid.x, gid.y);
- if (mode == 3u) { src = hist_out[tq].rgb * max(sample_px[tq].albedo.rgb, vec3<f32>(0.02)) + shist_out[tq].rgb + sample_parts(tq)[2] + direct_in[tq].rgb; }
+ if (mode == 3u) { src = (hist_out[tq].rgb * max(sample_px[tq].albedo.rgb, vec3<f32>(0.02)) + shist_out[tq].rgb) * medium_tr(tq) + sample_parts(tq)[2] + direct_in[tq].rgb; }
if (mode == 4u) { src = sample_color(tq); }
- if (mode == 6u) { src = max(fb[tq].rgb - spec_load(1u, tq).rgb - sample_parts(tq)[2] - direct_in[tq].rgb, vec3<f32>(0.0)); }
+ if (mode == 6u) { src = max(fb[tq].rgb - spec_load(1u, tq).rgb * medium_tr(tq) - sample_parts(tq)[2] - direct_in[tq].rgb, vec3<f32>(0.0)); }
if (mode == 8u) { src = direct_in[tq].rgb; }
- if (mode == 7u) { src = spec_load(1u, tq).rgb; }
+ if (mode == 7u) { src = spec_load(1u, tq).rgb * medium_tr(tq); }
if (L.post.x > 0.0 && mode == 0u) {
// Scene fringe: red sampled radially outward, blue inward (nearest texel).
let k = L.post.x * 0.0025;
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 6f7aac6..ef66876 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -98,7 +98,8 @@ struct Material {
struct Light { pos: vec4<f32>, dir: vec4<f32>, color: vec4<f32>, ext: vec4<f32>, x: vec4<f32> };
// Live: color = diffuse lighting at the first hit (+ first-hit distance), emit = what the camera ray sees directly
// (emission, sky; kept out of the denoiser) + first-hit roughness, spec = specular lighting at the first hit +
-// distance to what the first specular bounce hit (reprojection of reflections). Offline: color / albedo / normal sums.
+// distance to what the first specular bounce hit (reprojection of reflections), normal.w = the media before the first
+// hit (`media_composite`: 0.5 = none). Offline: color / albedo / normal sums.
struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec4<f32>, spec: vec4<f32> };
@group(0) @binding(0) var<uniform> P: Params;
@@ -128,7 +129,8 @@ struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec
struct Instance { m0: vec4<f32>, m1: vec4<f32>, m2: vec4<f32>, n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, info: vec4<u32>, p0: vec4<f32>, p1: vec4<f32>, p2: vec4<f32> };
@group(0) @binding(17) var<storage, read> instances: array<Instance>;
// Bounded participating media (`VolumeMesh`, gpu.rs MediumGpu; F_MEDIA), P.time.w of them: world -> local affine rows,
-// (volume function, shape: 0 box / 1 sphere, -, -), (majorant 1/m, HG anisotropy, -, -), customData, parameters.
+// (volume function, shape: 0 box / 1 sphere, homogeneous, 1 = it changes with time: `VolumeFunction` `animated`, a
+// simulated grid), (majorant 1/m, HG anisotropy, -, -), customData, parameters.
struct Medium { w0: vec4<f32>, w1: vec4<f32>, w2: vec4<f32>, a: vec4<u32>, b: vec4<f32>, c: vec4<f32>, p: array<vec4<f32>, 8> };
@group(0) @binding(18) var<storage, read> media: array<Medium>;
@@ -759,7 +761,7 @@ fn occluded_sky(o: vec3<f32>, d: vec3<f32>) -> bool {
// only media code: water and other constant media attenuate reflection, refraction and shadow rays; other media are
// the camera rays' alone (media_composite).
fn media_homogeneous(o: vec3<f32>, d: vec3<f32>, tmax: f32, light: bool) -> March {
- var r = March(1.0, vec3<f32>(0.0));
+ var r = March(1.0, vec3<f32>(0.0), vec2<f32>(1.0, 0.0));
let n = min(u32(P.time.w), 32u);
for (var k = 0u; k < n; k++) {
let m = media[k];
@@ -2080,10 +2082,12 @@ fn media_tr(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> f32 {
const MEDIA_STEPS: u32 = 8u;
const MEDIA_STEPS_INDIRECT: u32 = 4u; // later segments: transmittance only
const MEDIA_TRAIN_POINTS: u32 = 4096u;
-struct March { tr: f32, light: vec3<f32> };
+// tr, light: the transmittance and the light of every medium on the ray; moving: those of the media that change with
+// time alone (their transmittance, their light's luminance).
+struct March { tr: f32, light: vec3<f32>, moving: vec2<f32> };
fn media_march(o: vec3<f32>, d: vec3<f32>, tmax: f32, camera: bool) -> March {
- var r = March(1.0, vec3<f32>(0.0));
+ var r = March(1.0, vec3<f32>(0.0), vec2<f32>(1.0, 0.0));
let n = min(u32(P.time.w), 32u);
let u = rnd();
var done = 0u;
@@ -2122,8 +2126,10 @@ fn media_march(o: vec3<f32>, d: vec3<f32>, tmax: f32, camera: bool) -> March {
lin = jv.rgb;
if (jv.w < CACHE_WARM) { lin = cache_point(x).rgb; }
}
- r.light += r.tr * (v.albedo * st * lin + v.emission) * w;
+ let seen = r.tr * (v.albedo * st * lin + v.emission) * w;
+ r.light += seen;
r.tr *= ti;
+ if (media[best].a.w != 0u) { r.moving = vec2<f32>(r.moving.x * ti, r.moving.y + dot(seen, vec3<f32>(0.2126, 0.7152, 0.0722))); }
}
}
return r;
@@ -2845,10 +2851,15 @@ fn media_train(@builtin(global_invocation_id) gid: vec3<u32>) {
}
// Live participating media, a pass of its own after the frame's last trace sample. Per traced pixel the camera ray
-// of its first sample (the jitter stored with it) is marched up to the pixel's first hit (media_march): the
-// transmittance scales every signal behind the medium (diffuse, specular, direct light, the reflection resolve's
-// rays) and the medium's light joins what the camera sees directly (the emission signal, once per sample). Reflection,
-// GI and shadow rays do not see media live (offline paths do).
+// of its samples (the frame's jitter) is marched up to the pixel's first hit (media_march). The medium's light joins
+// what the camera sees directly (the emission signal, once per sample), and the transmittance scales that signal and
+// the deterministic direct light, which no history holds. The diffuse and specular lighting and the reflection
+// resolve's rays are accumulated over frames (live.wgsl): they stay the surface's own, and the transmittance goes with
+// the sample for `compose` to apply after the denoisers, as volumetrics are composed over a denoised surface
+// elsewhere. Scaled before, a surface's history kept the shadow of the smoke of the frames before. With it goes how
+// much of the pixel is a medium that changes with time (what it hides, or its light's share of the pixel): the
+// upscaler's reactive mask there. normal.w = that share in 8 bits, plus half the transmittance. Reflection, GI and
+// shadow rays do not see media live (offline paths do).
@compute @workgroup_size(8, 8, 1)
fn media_composite(@builtin(global_invocation_id) gid: vec3<u32>) {
let w = P.size.x;
@@ -2858,19 +2869,19 @@ fn media_composite(@builtin(global_invocation_id) gid: vec3<u32>) {
rng_state = pcg(pix ^ pcg(P.size.z * 9781u + P.size.w * 6271u + 0x51ed27u));
mirror_path = false;
var px = accum[pix];
- let jit = u32(px.normal.w);
- let ndc = vec2<f32>((f32(gid.x) + f32(jit / 4096u) / 4095.0) / f32(w) * 2.0 - 1.0, 1.0 - (f32(gid.y) + f32(jit % 4096u) / 4095.0) / f32(h) * 2.0);
+ let ndc = vec2<f32>((f32(gid.x) + P.raster.y) / f32(w) * 2.0 - 1.0, 1.0 - (f32(gid.y) + P.raster.z) / f32(h) * 2.0);
let d = normalize(P.cam_fwd.xyz + P.cam_right.xyz * (ndc.x * P.cam_pos.w * P.cam_fwd.w) + P.cam_up.xyz * (ndc.y * P.cam_pos.w));
let ft = px.color.w;
let mm = media_march(P.cam_pos.xyz, d, select(1.0e30, ft, ft > 0.0), true);
if (mm.tr >= 1.0 && all(mm.light == vec3<f32>(0.0))) { return; }
let samples = P.misc.w + 1.0; // this dispatch runs with the frame's last sample's parameters
- px.color = vec4<f32>(px.color.rgb * mm.tr, px.color.w);
- px.spec = vec4<f32>(px.spec.rgb * mm.tr, px.spec.w);
+ let lw = vec3<f32>(0.2126, 0.7152, 0.0722);
+ let rest = dot(mm.light, lw) - mm.moving.y + dot(px.color.rgb + px.spec.rgb + px.emit.rgb, lw) / samples * mm.tr;
+ let share = max(1.0 - mm.moving.x, mm.moving.y / max(mm.moving.y + max(rest, 0.0), 1e-9));
+ px.normal = vec4<f32>(px.normal.xyz, floor(clamp(share, 0.0, 1.0) * 255.0) + 0.5 * clamp(mm.tr, 0.0, 1.0));
px.emit = vec4<f32>(px.emit.rgb * mm.tr + mm.light * samples, px.emit.w);
accum[pix] = px;
if (arrayLength(&direct_out) >= w * h) { direct_out[pix] = vec4<f32>(direct_out[pix].rgb * mm.tr, direct_out[pix].w); }
- if (resolve_bound()) { refl[pix * 2u] = vec4<f32>(refl[pix * 2u].xyz * mm.tr, refl[pix * 2u].w); }
}
// Once per frame after the trace: folds the frame's training sums into each entry (history capped at P.cache.y
@@ -3291,8 +3302,8 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
}
// misc.w = index of this sample within the frame: the first one also writes the g-buffer.
if (P.misc.w < 0.5) {
- // normal.w = this sample's sub-pixel jitter (12 bits each), for the upsampling reconstruction.
- let jit = round(jx * 4095.0) * 4096.0 + round(jy * 4095.0);
+ // normal.w: no medium before the hit (`media_composite` writes it where there is one).
+ let jit = 0.5;
accum[pix] = Pixel(vec4<f32>(diff, first_t), vec4<f32>(albedo, select(1.0, 2.0, anim)), vec4<f32>(normal, jit), vec4<f32>(e0, rough0), vec4<f32>(spec, spec_t));
} else {
var px = accum[pix];
diff --git a/renderer/src/api.rs b/renderer/src/api.rs
index 4a4521c..655b483 100644
--- a/renderer/src/api.rs
+++ b/renderer/src/api.rs
@@ -188,6 +188,7 @@ pub fn object(w: &mut World, id: u32, j: &Value) -> Result<()> {
majorant: j["majorant"].as_f64().unwrap_or(0.0) as f32,
g: j["g"].as_f64().unwrap_or(0.0) as f32,
homogeneous: j["homogeneous"].as_bool().unwrap_or(false),
+ animated: j["animated"].as_bool().unwrap_or(false),
grid: num("grid"),
},
"instanced" => Kind::Instanced {
diff --git a/renderer/src/live.rs b/renderer/src/live.rs
index 07cb725..da0262b 100644
--- a/renderer/src/live.rs
+++ b/renderer/src/live.rs
@@ -4168,7 +4168,9 @@ impl LiveCore {
for x in 0..w {
// live.wgsl `sample_under`.
let q = (((y as f32 + 0.5) * ih as f32 / h as f32) as usize).min(ih - 1) * iw + (((x as f32 + 0.5) * iw as f32 / w as f32) as usize).min(iw - 1);
- let s = [half(spec[q][0], false), half(spec[q][0], true), half(spec[q][1], false)];
+ // The media before the surface (live.wgsl `medium_tr`): the specular as the frame shows it.
+ let tr = (samples[q][11].fract() * 2.0).clamp(0.0, 1.0);
+ let s = [half(spec[q][0], false), half(spec[q][0], true), half(spec[q][1], false)].map(|v| v * tr);
for c in 0..3 {
let e = finite(samples[q][12 + c] / self.shown_spp as f32);
spe.push(s[c]);
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index faa7cb6..6dab6e1 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -600,7 +600,8 @@ pub struct PoseGroup {
/// What groups posed models into a `PoseGroup`: model, nodes, clip, time (bits), loop.
type PoseKey = (String, Option<Vec<String>>, String, u32, bool);
-/// pathtrace.wgsl `Medium`: world -> local affine rows (the unit box / sphere's space), (function, shape, -, -),
+/// pathtrace.wgsl `Medium`: world -> local affine rows (the unit box / sphere's space), (function, shape, homogeneous,
+/// animated),
/// (majorant 1/m, HG anisotropy, -, -), the node's customData, 32 parameter floats.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
@@ -1559,7 +1560,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
_ => {}
},
- Kind::Volume { function, params, shape, majorant, g, homogeneous, grid } if shown => {
+ Kind::Volume { function, params, shape, majorant, g, homogeneous, animated, grid } if shown => {
let func = volume_fns.iter().position(|(k, _, _)| k == function).ok_or_else(|| anyhow!("object {}: unknown volume function {function}", n.name))? as u32;
let mut p = [0.0f32; 32];
for (k, v) in params.iter().take(32).enumerate() {
@@ -1600,7 +1601,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
if media.len() >= MAX_MEDIA {
return Err(anyhow!("object {}: more than {MAX_MEDIA} volumes shown at once (the kernel takes {MAX_MEDIA}; the rest would not be drawn)", n.name));
}
- media.push(MediumGpu { w: medium_rows(m), a: [func, *shape, *homogeneous as u32, 0], b: [majorant.max(0.0), g.clamp(-0.99, 0.99), at[0], at[1]], c: n.custom, p });
+ media.push(MediumGpu { w: medium_rows(m), a: [func, *shape, *homogeneous as u32, *animated as u32], b: [majorant.max(0.0), g.clamp(-0.99, 0.99), at[0], at[1]], c: n.custom, p });
media_nodes.push(*id);
}
Kind::Procedural { .. } if shown => {
@@ -2328,7 +2329,7 @@ mod instance_tests {
w.set_object(1000, "camera".into(), None, world::Kind::Camera(cam), false, false).unwrap();
w.set_settings(world::Settings { camera: Some(1000), ..Default::default() });
for id in 1..=n + hidden {
- let kind = world::Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant: 1.0, g: 0.0, homogeneous: false, grid: None };
+ let kind = world::Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant: 1.0, g: 0.0, homogeneous: false, animated: false, grid: None };
w.set_object(id, format!("v{id}"), None, kind, false, false).unwrap();
if id > n {
w.set_visible(id, false).unwrap();
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index c0f7461..4a64b50 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -141,8 +141,9 @@ pub enum Kind {
/// its volume function and 32 parameter floats, majorant (1/m) and HG anisotropy.
/// `homogeneous`: constant coefficients in the function's first parameters (albedo rgb + extinction, emission
/// rgb), so the live kernel can use them without the function (pathtrace.wgsl `media_homogeneous`).
+ /// `animated`: it changes with time (the live view keeps a short history of the pixels it fills).
/// `grid`: its density grid (`World::grids`; box volumes), which the volume function reads with `vgrid`.
- Volume { function: String, params: Vec<f32>, shape: u32, majorant: f32, g: f32, homogeneous: bool, grid: Option<u32> },
+ Volume { function: String, params: Vec<f32>, shape: u32, majorant: f32, g: f32, homogeneous: bool, animated: bool, grid: Option<u32> },
/// Procedural geometry (`ProceduralMesh`) under the node's transform, shaded with `materials[k]` for the k its
/// geometry function returns. Always instanced: a move rewrites its transform, never a rebuild.
Procedural { geometry: u32, materials: Vec<u32> },
@@ -1168,7 +1169,7 @@ mod tests {
w.set_grid(1, [2, 2, 4], 1, None, Some(("p".into(), vec![1.0]))).unwrap();
assert!(w.take_changes().structural, "another size");
// Sources.
- let volume = |grid| Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant: 1.0, g: 0.0, homogeneous: false, grid };
+ let volume = |grid| Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant: 1.0, g: 0.0, homogeneous: false, animated: false, grid };
w.set_object(5, "plain".into(), None, volume(None), false, false).unwrap();
w.set_object(6, "smoke".into(), None, volume(Some(1)), false, false).unwrap();
assert!(w.add_grid_sources(5, &[0.0; 12]).is_err());
diff --git a/tests/render/volume-animated-clears-live.ts b/tests/render/volume-animated-clears-live.ts
new file mode 100644
index 0000000..5f81c80
--- /dev/null
+++ b/tests/render/volume-animated-clears-live.ts
@@ -0,0 +1,36 @@
+// A medium that changes with time leaves nothing behind in the live view: an absorbing box (1 m, extinction 1/m, its
+// function reading `i.time`, so `animated`) before a white wall under a uniform 2-nit sky, gone at 2 s. 16 frames
+// later the wall's centre reads the sky's 2 nits again (the white furnace), not the box's shadow (2 e^-1 = 0.74 while
+// it stood). The wall's light is diffuse lighting, which the live view accumulates over frames: the medium's
+// transmittance is applied after that history, and the pixels the medium filled keep a short history of their own.
+import { BoxGeometry, Mesh, MeshStandardMaterial, VolumeFunction, VolumeMesh } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+import { CENTER, camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "volume/animated-clears-live", features: ["volume"], reference: "analytic", temporal: true,
+ metric: { kind: "radiance", region: CENTER, expected: 2, tolerance: 0.03 },
+ live: 136,
+ note: "as volume/box-transmittance before a diffuse wall; the medium ends at 2 s (frame 120), read at frame 136",
+};
+
+const UNTIL = new VolumeFunction("test_until", {
+ params: { Density: 1, Until: 2 },
+ code: `
+ o.extinction = select(0.0, $Density, i.time < $Until);
+ o.albedo = vec3<f32>(0.0);`,
+});
+
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ const scene = sceneWithSky(2);
+ const wall = new Mesh(new BoxGeometry(8, 8, 0.1), new MeshStandardMaterial({ name: "wall", color: 0xffffff, roughness: 1 }));
+ wall.position.set(0, 0, -2);
+ const box = new VolumeMesh({ volume: UNTIL.with({ Density: 1 }), majorant: 1 });
+ box.scale.set(2, 2, 1);
+ return result(scene, camera(scene, [0, 0, 5], [0, 0, 0]), [wall, box]);
+ },
+ frame() {},
+ handlers: {},
+});