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.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Provenance: the post chain, the denoiser's temporal response, the BSDF's energy terms, the atmosphere and the fog volume written again from public sources; docs/PROVENANCE.md (#268)
Evan (Yifeng) Wang5cb95f64d1a9
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..a126267--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,126 @@+# Third-party notices++ThreeRT is MIT-licensed (LICENSE). Parts of it follow formulas or reference code published under licences that ask for+a notice. They are listed here with where they are used.++## Surface BSDF and spot lights (`renderer/shaders/pathtrace.wgsl`, `renderer/shaders/live.wgsl`, `renderer/src/lib.rs`, `renderer/src/scene.rs`)++### Filament (documentation: "Physically Based Rendering in Filament")++`vis_smith_joint_approx` (pathtrace.wgsl), `vis_smith` (live.wgsl) and the same expression in lib.rs+`specular_albedo` evaluate the square-root-free approximation of the height-correlated Smith-GGX visibility in the form+of Filament's `V_SmithGGXCorrelated_Fast` (0.5 / mix(2 n.l n.v, n.l + n.v, alpha); it credits Hammon, "PBR Diffuse+Lighting for GGX+Smith Microsurfaces", GDC 2017). The multiple-scattering scale `1 + f0 (1 / E - 1)` and the grazing reflectance+`saturate(50 x mean(f0))` appear there in the same form (after Turquin 2019 and Lagarde & de Rousiers 2014).++ Filament, https://github.com/google/filament (shaders/src/surface_brdf.fs; documentation:+ https://google.github.io/filament/Filament.md.html)+ Copyright 2023 The Android Open Source Project+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed+ on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for+ the specific language governing permissions and limitations under the License.++### glTF 2.0, KHR_lights_punctual (The Khronos Group)++The spot cone's angular attenuation (pathtrace.wgsl `local_light`, scene.rs `spot_cone`) is the extension's reference+attenuation (scale 1 / max(0.001, cos(inner) - cos(outer)), linear in the cosine, squared), which is `getAngleAtt` of+Lagarde & de Rousiers, "Moving Frostbite to Physically Based Rendering" (SIGGRAPH 2014 course notes), Listing 4.++ Copyright 2014-2021 The Khronos Group Inc. SPDX-License-Identifier: CC-BY-4.0+ https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_lights_punctual++### three.js++`SpotLight.penumbra` has three.js's meaning (the inner cone is `angle x (1 - penumbra)`, three.js `WebGLLights`); no+three.js code is used for the falloff.++ The MIT License. Copyright (c) 2010-2026 three.js authors. https://github.com/mrdoob/three.js++## Sky (`renderer/src/sky.rs`, `tools/three/sky.ts`)++### Precomputed Atmospheric Scattering (Eric Bruneton, 2017)++The constants of Earth's atmosphere in `renderer/src/sky.rs` and `tools/three/sky.ts` (the Rayleigh scattering+coefficient 1.24062e-6 λ⁻⁴ per metre at 680 / 550 / 440 nm, the scale heights 8000 m and 1200 m, the Mie extinction+5.328e-3 / 1200 m per metre with a single-scattering albedo of 0.9, the ozone layer's profile and its absorption for+300 Dobson units) are those of that project's demo (`atmosphere/demo/demo.cc`,+https://ebruneton.github.io/precomputed_atmospheric_scattering/). No code of it is used. Its licence (BSD 3-Clause):++```+Copyright (c) 2017 Eric Bruneton+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions+are met:+1. Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.+2. Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.+3. Neither the name of the copyright holders nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF+THE POSSIBILITY OF SUCH DAMAGE.+```++## Post chain (`renderer/src/post.rs`)++### Academy Color Encoding System (ACES) reference transforms++`renderer/src/post.rs` (colour grading and the tone curve, `Tonemapper`) follows the structure of the Academy's+reference rendering and takes from the ACES 1.3 reference transforms (https://github.com/ampas/aces-dev, tag v1.3:+`RRT.ctl`, `ACESlib.RRT_Common.ctl`, `ACESlib.ODT_Common.ctl`, `ACESlib.Utilities_Color.ctl`,+`LMT.Academy.BlueLightArtifactFix.ctl`): the constants of the "glow" and "red modifier", the desaturation factors,+the AP0 / AP1 chromaticities, the blue-light-artifact-fix matrix, and the functions `glow_fwd`, `sigmoid_shaper` and+`cubic_basis_shaper` re-expressed in Rust. The tone curve itself is not the Academy's.++> License Terms for Academy Color Encoding System Components+>+> Academy Color Encoding System (ACES) software and tools are provided by the Academy under the following terms and+> conditions: A worldwide, royalty-free, non-exclusive right to copy, modify, create derivatives, and use, in source and+> binary forms, is hereby granted, subject to acceptance of this license.+>+> Copyright © 2015 Academy of Motion Picture Arts and Sciences (A.M.P.A.S.). Portions contributed by others as+> indicated. All rights reserved.+>+> Performance of any of the aforementioned acts indicates acceptance to be bound by the following terms and conditions:+>+> * Copies of source code, in whole or in part, must retain the above copyright notice, this list of conditions and the+> Disclaimer of Warranty.+> * Use in binary form must retain the above copyright notice, this list of conditions and the Disclaimer of Warranty+> in the documentation and/or other materials provided with the distribution.+> * Nothing in this license shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or+> any other intellectual property of A.M.P.A.S. or any contributors, except as expressly stated herein.+> * Neither the name "A.M.P.A.S." nor the name of any other contributors to this software may be used to endorse or+> promote products derivative of or based on this software without express prior written permission of A.M.P.A.S.+> or the contributors, as appropriate.+>+> This license shall be construed pursuant to the laws of the State of California, and any disputes related thereto+> shall be subject to the jurisdiction of the courts therein.+>+> Disclaimer of Warranty: THIS SOFTWARE IS PROVIDED BY A.M.P.A.S. AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED+> WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR+> PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL A.M.P.A.S., OR ANY CONTRIBUTORS OR DISTRIBUTORS, BE+> LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, RESITUTIONARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,+> BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS+> INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING+> NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF+> SUCH DAMAGE.+>+> WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE ACADEMY SPECIFICALLY DISCLAIMS ANY REPRESENTATIONS OR WARRANTIES+> WHATSOEVER RELATED TO PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS IN THE ACADEMY COLOR ENCODING SYSTEM, OR+> APPLICATIONS THEREOF, HELD BY PARTIES OTHER THAN A.M.P.A.S.,WHETHER DISCLOSED OR UNDISCLOSED.diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex bc101a8..6852d4c 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -23,9 +23,9 @@| Scene DSL | `packages/scene` | Three.js-compatible API (`Scene`, `Mesh`, `*Geometry`, `MeshStandardMaterial`/`MeshPhysicalMaterial`, `DirectionalLight`/`PointLight`/`SpotLight`/`RectAreaLight`, `PerspectiveCamera`, `GLTFModel`, `SkyAtmosphere`). Physical units (lux / cd / nits). Pure TS, no DOM: runs in Node, Workers and Dynamic Workers. || Engine API | `packages/scene/src/engine.ts`, `renderer/src/{script,world,desc}.rs` | What scene code drives: handles for geometries (typed arrays), textures, materials (PBR + material functions), objects (group / mesh / model / light / camera) and their transform / visibility / power / parameters, the environment and render settings. `SceneBinding` keeps the engine in step with a DSL scene (objects report their own changes). No scene document or interchange format (see `docs/RUNTIME.md`). || Scene runtime (node) | `renderer/src/script.rs`, `packages/gameplay/src/node-host.ts`, `frame.ts` | Game code (`tools/bundle-game.ts` bundles, or the cloud's ES modules) runs in QuickJS inside the renderer: setup builds the scene, `frame(f)` derives it from the committed game state every frame, and the world's changes rewrite GPU tables in place or rebuild in memory. Time of day is in place too: a `dynamic` `SkyAtmosphere`'s sun moves without a rebuild (its light rewritten, the sky re-baked on a worker thread), and a manual exposure that changes value is applied in place. `threert-render play`, `live`, `render`, `serve`. |-| Presets | `presets/*.json` | `cinematic` / `preview`: renderer-neutral intent + the UE5 post chain constants (filmic tonemapper, SOG bloom, vignette, exposure) + per-backend knobs (`native`, `ue`). |+| Presets | `presets/*.json` | `cinematic` / `preview`: renderer-neutral intent + the post chain's settings (`post`: exposure metering, bloom, colour grading, vignette, grain, fringe, local exposure, motion blur; named after Unreal's Post Process Volume settings and meaning what its documentation says, so a look can be compared with the same settings there; `post.tonemapper` holds Unreal's Film values for the comparison scripts in `ue5/` only) + per-backend knobs (`native`, `ue`). || UE5 ground truth | `ue5/` | `bun ue5/capture.ts <project> <job.json>` renders stills of an existing UE level at given cameras (headless UnrealEditor); `ue_dump_level.py` dumps a level's actors for port checks. The reference images of the simple scenes (out/ue) came from an earlier IR → UE adapter, now removed. |-| Native renderer | `renderer/` | Rust + wgpu compute path tracer (Metal / Vulkan / lavapipe). UE DefaultLit BRDF, Hillaire sky identical to UE SkyAtmosphere defaults, HW ray queries when available, OIDN denoising, exact port of UE's bloom/exposure/filmic tonemap/vignette. `render`, `serve` (warm JSON-lines worker), `compare`. |+| Native renderer | `renderer/` | Rust + wgpu compute path tracer (Metal / Vulkan / lavapipe). A metallic-roughness BSDF (GGX microfacets, [below](#the-surface-bsdf)), a physical clear-sky atmosphere (the Earth medium of Bruneton 2017 / Hillaire 2020, scattering orders computed one by one; `renderer/src/sky.rs`), HW ray queries when available, OIDN denoising, a post chain of its own (`renderer/src/post.rs`; `docs/RUNTIME.md` "The post chain": histogram auto exposure, sum-of-Gaussians bloom, local exposure, cos^4 vignette, the Academy's reference rendering around a fitted filmic tone curve). `render`, `serve` (warm JSON-lines worker), `compare`. || Gameplay | `packages/gameplay` | Verse-inspired transactions over the game state: `tx.decide` (failable), `tx.attempt` (nested speculative scope), read/write sets with path versions, OCC commit, deterministic `tx.random`/`tx.now`. Frame scripts (`frame(f)`) present the state on the render node. || Cloud | `cloud/` | Gateway Worker, Room DO, RenderPool DO, Dynamic Worker sandbox, R2. || Render node | `render-node/`, `render-container/` | WS client that feeds a warm `threert-render serve`; Linux image (Vulkan / lavapipe + OIDN) for GPU VMs or CPU fallback in Cloudflare Containers. |@@ -36,4 +36,25 @@* UV: three-style DSL UVs (v up) are flipped to the GPU convention (`1 − v`) when geometry reaches the engine.* Light units are physical (lux / cd / nits). UE quirk: rect-light radiance is `brightness / (0.5·W·H)` (RectLightSceneProxy.cpp); ports convert UE candela to nits over the area.* Exposure: manual EV100 matches UE `AEM_Manual` with the physical camera off and bias = −EV100 (LuminanceMax = 1 with UE5 defaults); native: `2^-EV100`.-* Energy conservation: native GGX has a tunable multiple-scattering compensation; `0` matches UE 5.8 DefaultLit measured against UE's own path tracer, `1` passes the white furnace test.+* Energy conservation: the native specular lobe has a tunable multiple-scattering compensation (`native.energyCompensation`, [below](#the-surface-bsdf)). `0` is the single-scattering lobe, which is what real-time engines render by default (the previous release's pictures at `0` were measured against UE 5.8's path tracer rendering DefaultLit materials and matched; this implementation renders the same pictures as that release). `1` passes the white furnace test.++## The surface BSDF++The kernel's surface model (`renderer/shaders/pathtrace.wgsl`, "BSDF") is the metallic-roughness model of glTF 2.0 and of the real-time literature, written from these public sources (each is cited again where the code uses it):++| term | what it is | source |+|---|---|---|+| roughness | `alpha = roughness²` | Burley, "Physically-Based Shading at Disney", SIGGRAPH 2012 course notes, § 5.4 |+| `d_ggx` | the GGX (Trowbridge-Reitz) distribution of microfacet normals | Walter et al., "Microfacet Models for Refraction through Rough Surfaces", EGSR 2007, eq. 33 |+| `vis_smith_joint_approx` | the visibility `G2 / (4 n·v n·l)` of the height-correlated Smith masking-shadowing, each of its two square roots `sqrt(a² + (1 − a²) c²)` replaced by `a + (1 − a) c` | Heitz, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs", JCGT 2014; the approximation: Hammon, "PBR Diffuse Lighting for GGX+Smith Microsurfaces", GDC 2017, and Filament's documentation (`V_SmithGGXCorrelatedFast`) |+| `f_schlick` | `f0 + (f90 − f0) (1 − v·h)⁵` | Schlick, "An Inexpensive BRDF Model for Physically-based Rendering", 1994 |+| `f0` | dielectrics: `0.08 × specular` (0.5, the default, is 4 %: ior 1.5); metals: the base colour; glass: from its index of refraction | Burley 2012, § 5.4; glTF 2.0, appendix B |+| `f90` | 1, fading to 0 as `f0` falls under 2 % (a material switches its specular off with `specular` 0) | Lagarde & de Rousiers, "Moving Frostbite to Physically Based Rendering", SIGGRAPH 2014 course notes, § 4.10.3, Listing 27 (after Schüler, ShaderX7) |+| `energy_lookup` | the lobe's directional albedo as the split sum's two terms: it reflects `f0 × A + f90 × B` of a uniform surround; a 32 × 32 table over `sqrt(n·v)` and the roughness, integrated at start-up over visible normals (`lib.rs` `specular_albedo`, 10 ms) | Karis, "Real Shading in Unreal Engine 4", SIGGRAPH 2013 course notes, "Environment BRDF"; Lagarde & de Rousiers 2014, eq. 58; Heitz, "Sampling the GGX Distribution of Visible Normals", JCGT 2018; the table's shape: Kulla & Conty 2017, Turquin 2019 |+| multiple scattering | the lobe scaled by `1 + f0 (1 − E) / E`, `E = A + B`, times `energyCompensation` | Turquin, "Practical multiple scattering compensation for microfacet models", 2019, eq. 16; Kulla & Conty, "Revisiting Physically Based Shading at Imageworks", SIGGRAPH 2017 course |+| diffuse under the specular | Lambert × `1 −` the specular's directional albedo toward the view | Kulla & Conty 2017, "Microfacet Dielectrics – Diffuse Term" (theirs uses both directions) |+| clearcoat | a second GGX lobe, `f0` 0.04, over the base, which gets `1 −` the coat's directional albedo (same table) | glTF `KHR_materials_clearcoat`; Burley 2012, § 5.4 |+| glass | a rough dielectric interface with the exact Fresnel reflectance, its own energy table | Walter et al. 2007; Turquin 2019, § 3.2 |+| spot cone | linear in the cosine between the inner and the outer cone, squared; the inner cone is `angle × (1 − penumbra)` | glTF 2.0 `KHR_lights_punctual` (reference attenuation; Lagarde & de Rousiers 2014, Listing 4); `penumbra` as three.js's `SpotLight` |++The live renderer's reflection resolve (`live.wgsl`) weights neighbours' rays with the same `d_ggx` and visibility.diff --git a/docs/MATERIAL_FUNCTIONS.md b/docs/MATERIAL_FUNCTIONS.mdindex e5ed0ab..61335c6 100644--- a/docs/MATERIAL_FUNCTIONS.md+++ b/docs/MATERIAL_FUNCTIONS.md@@ -5,7 +5,7 @@ A material function is a WGSL body attached to a material, run by the path tracea Custom-HLSL node. The DSL declares it once with named parameters and texture slots, and each material instance bindsits own values. Expressiveness lives in code instead of in a growing list of built-in material fields, so a UE mastermaterial can be ported line for line (the standard library's nine street materials, below, were ported this way from-the master materials of a UE 5.8 night-street level).+the master materials we wrote for this project's own UE 5.8 night-street level).```tsimport { MaterialFunction, MeshStandardMaterial, Texture } from "@threert/scene";@@ -341,17 +341,34 @@ any number of times:The kernel compiles all of it out when no scene node is a volume (feature bit F_MEDIA): existing scenes renderbyte-identical and pay nothing.-`FogVolume` in the standard library is UE 5.8's Local Fog Volume, as UE voxelizes it into volumetric fog-(VolumetricFog.usf). It takes UE's settings under the same names and defaults: `radialExtinction`,-`heightExtinction`, `heightFalloff`, `heightOffset`, `albedo`, `emissive` and `phaseG`.-- In the unit sphere (radius 1), the radial part is RadialFogExtinction × saturate(1 − d)^0.82, and the height part is- HeightFogExtinction × exp(−HeightFogFalloff × (z − HeightFogOffset)).-- The two combine as coverages, not as a sum: with A = e^−height and B = e^−radial, the extinction is- −log(A + B − AB) per metre.-- So fog needs both parts: with no height part there is no fog. UE's default falloff of 1000 cuts the sphere flat at- the offset.-- The node's scale is the diameter: UE's scale 1.2 (a 1.2 m radius) is `scale.set(2.4, 2.4, 2.4)`.-- `volume/local-fog` checks the density against the optical depth integrated numerically: 0.2823 for 0.2863.+`FogVolume` is a sphere of fog (the node's scale is its diameter). Its settings have the names and meanings of the+settings of Unreal's Local Fog Volume (its documentation page "Local Fog Volumes"), so a scene can carry the numbers+over:++| option | default | meaning |+|---|---|---|+| `radialExtinction` | 1 | extinction (1/m) at the centre of the part that fades toward the sphere's surface |+| `heightExtinction` | 1 | extinction (1/m) of the part that fades with height, at the height `heightOffset` |+| `heightFalloff` | 1000 | how fast the height part falls off upward, per unit of the unit sphere (radius 1) |+| `heightOffset` | 0 | the height the height part is measured from, in the unit sphere (0 = the centre, 1 = the top) |+| `albedo` | white | scattering / extinction |+| `emissive` | black | emitted radiance per unit extinction, nits |+| `phaseG` | 0.2 | the Henyey-Greenstein g |++The density is ThreeRT's own. With `u` the point in the unit sphere (radius 1, y up):++```+radial = radialExtinction × (1 − |u|²)+height = heightExtinction × exp(−heightFalloff × (u.y − heightOffset))+extinction = radial × (1 − exp(−height / radial))+```++The fog is where both parts are. The combination follows the thinner of the two smoothly, and is never denser than+either: where the height part is thin the fog is the height part, where it is dense the fog is the radial part. With+the default falloff of 1000 the height part is a flat cut: the sphere's fog below `heightOffset`, nothing above it.+A falloff of a few units gives a pool that thins upward. `fogVolumeExtinction(options, u)` gives the same number in+TypeScript. The volume's majorant is set from the options (the radial part at the centre with the height part at+its densest in the sphere), so a `FogVolume` needs none.Layer A checks it against analytic values:- `volume/box-transmittance`: Beer–Lambert;@@ -386,7 +403,7 @@ in front of its wall, lit by the moon alone, reads +5.7 % live over the offlineisotropic phase function (the smoke's is HG 0.2), a third from the 8-step march's transmittance.The standard library has three volume presets:-- `FogVolume`: UE 5.8's Local Fog Volume (its density formula and settings, above).+- `FogVolume`: a sphere of fog that fades towards its edge and with height (above).- `SmokeColumn`: fBm noise drifting upward, thinning toward the edge and top.- `Fireball`: grows from `customData[0]`, emits by temperature, cools to smoke, can repeat.diff --git a/docs/PROVENANCE.md b/docs/PROVENANCE.mdnew file mode 100644index 0000000..7801be5--- /dev/null+++ b/docs/PROVENANCE.md@@ -0,0 +1,84 @@+# Provenance: where the renderer's code comes from++ThreeRT is MIT-licensed, and people build on it. That only works if everything in it may be MIT-licensed. This file+has the rules contributors (people and agents) follow, and the record of the review and replacement of 2026-11.++## Rules++1. **Sources that may be used.** Published papers, books, course notes, talks, standards and vendor documentation;+ code under MIT, BSD, Apache-2.0, zlib, CC0 / public domain, or the Academy's ACES licence. A formula, constant or+ piece of code taken from a source is cited where it is used; a licence that asks for a notice gets one in+ [THIRD_PARTY_NOTICES.md](../THIRD_PARTY_NOTICES.md).+2. **Sources that may not be used.** Source code whose licence does not allow it to be redistributed under MIT,+ whatever form it is read in. In particular Unreal Engine's engine source (the Unreal Engine EULA) and NVIDIA's+ NRD / RTX SDK sources (the NVIDIA RTX SDKs licence). "Used" includes read: a session (a person's or an agent's)+ that has such source open does not write renderer code, and nobody writes renderer code from notes, summaries or+ paraphrases of such source.+3. **Other renderers as black boxes are fine.** Rendering the same scene in Unreal and comparing pictures, using a+ product's documented settings and their documented meaning, driving an editor through its scripting API+ (`ue5/`), and content we author ourselves in another tool are all allowed, and are how ThreeRT's parity work is+ done.+4. **A PR that adds or changes an algorithm names its sources** (in the code, and in the PR description).+5. **If you find code here that should not be**, open an issue. It is replaced, by the procedure below.++Agents: these rules are part of [WORKFLOW.md](WORKFLOW.md), "Sources".++## The review of 2026-11++[Issue #78](https://github.com/meshy-dev/ThreeRT/issues/78) asked whether NVIDIA NRD source had been translated or+followed in the live denoiser, pointing at a roadmap passage that named an NRD source file. We reviewed what the+agent sessions that wrote the renderer had read, from the session records we hold (2026-11-03 to 11-13, one machine).++- **NRD.** No session in those records fetched, cloned or read NRD source, headers or sample code. The denoiser+ rules whose comments named ReBLUR (the per-pixel history lengths, the specular history's bound by parallax, the+ fast-history clamp) came from pull requests written on another machine, whose session records we do not hold, and+ the roadmap entry of one of them named an NRD source file. We could not establish what those sessions had read, so+ we treated those rules as unverified and replaced them.+- **Unreal Engine.** The same records showed that sessions writing the first renderer had Unreal Engine 5.8 source+ files open (the project was developed by comparing against Unreal, on a machine with the engine installed), and+ that some code had been written from them: the post chain, the choice of history in the specular temporal pass,+ the specular lobe's energy terms, part of the atmosphere, and a fog density. The code said so in its comments.+ That is not compatible with rule 2, and we replaced all of it.++### What was replaced, and what it rests on now++| Part | Where | Written from |+|---|---|---|+| Post chain: exposure metering, bloom, local exposure, vignette, colour grading, tone curve, lookup table, the lens's circle of confusion, motion blur length | `renderer/src/post.rs`, the post passes of `renderer/shaders/live.wgsl`, `renderer/src/live/` | Own designs after the documented meaning of the settings; the Academy's ACES 1.3 reference transforms (AMPAS licence) around a tone curve of our own, fitted to the previous release's measured output; Burt & Adelson 1983; Durand & Dorsey 2002; CIE 15, Krystek 1985, Lam 1985; textbook optics. `docs/RUNTIME.md`, "The post chain". |+| Specular temporal accumulation; the diffuse history's length and its response to changing light; the specular filter's reach | `stemporal`, `dtemporal`, `spec_filter_traced` in `renderer/shaders/live.wgsl` | Own designs: a blur budget for histories in motion, an EWMA control chart per pixel for changes of the lighting (NIST e-Handbook of Statistical Methods § 6.3.2.4) with a drift term, the choice between the surface's and the reflection's history from this frame's neighbourhood. From the literature: Schied et al. 2018 (the response to a detected change), Karis 2014 (neighbourhood clamping), Stachowiak 2015 (reprojection through the reflection). No ReBLUR material was used, the published chapter included. `docs/RUNTIME.md`, "The temporal response of the live denoiser". |+| GGX distribution and visibility, Fresnel, the specular lobe's energy compensation and its table, the spot cone | `renderer/shaders/pathtrace.wgsl`, `renderer/src/lib.rs`, `renderer/src/scene.rs` | Walter et al. 2007; Heitz 2014; Lagarde & de Rousiers 2014; Karis 2013 (course notes); Burley 2012; Kulla & Conty 2017; Turquin 2019; Filament (Apache-2.0); glTF `KHR_lights_punctual`. `docs/ARCHITECTURE.md`, "The surface BSDF". |+| Atmosphere model and the sun's transmittance | `renderer/src/sky.rs`, `tools/three/sky.ts` | Hillaire 2020 (the paper); Bruneton & Neyret 2008 and Bruneton's 2017 constants (BSD-3-Clause); own numerics. |+| `FogVolume`'s density | `packages/scene/src/effects.ts` and its twins | Own design. |++### How++1. **Audit.** For every proprietary file the records show was read, we traced what was written after it and where+ that code is now, and classed it: a translation; the same steps with internal constants; only a technique that+ is also in the literature; only a documented setting; nothing.+2. **Removal.** Everything in the first two classes was deleted and replaced by placeholders, together with the+ passages of the docs that described it. The denoiser rules of unverified origin were removed the same way.+3. **Isolated reimplementation.** Each part was written again by a fresh agent session working in a copy of the tree+ that had no history and none of the removed code or the docs describing it, under written rules: no proprietary+ source, no earlier versions of this project, allowed sources only, every source cited, a log of everything+ opened. It was given a specification of behaviour (interfaces, what each setting means, acceptance tests) and,+ where the look had to be kept, measurements of the previous release taken as a black box (input / output tables,+ rendered frames, benchmark results). The session that did the audit had seen the old code and did not write the+ new one; it integrated the results and ran the checks.+ One slip, recorded in the implementer's log: the copy given for the denoiser still had a doc paragraph that named the+ old specular rule's two constants (without values); it was read after the first version of the new pass was+ committed, and the new pass's neighbourhood clamp is the published one (Karis 2014).+4. **Checks.** The merge gate of [WORKFLOW.md](WORKFLOW.md) for a change to the live passes, against the previous+ release.++What was kept, because the records show it was written without such source or it is our own content: the motion+blur and depth-of-field gathers, the à-trous filters, the reflection resolve, the media code, the rain and the+street materials (transcribed from a level we authored ourselves), the sky-light bake, and the rest of the renderer.+The temporal upscaler was written outside the records we hold; its comments compare it with other upscalers but+name no source file, and we have no indication that it was written from one.++### Limits++- The repository's history before this change, and releases built from it (the clients up to 0.5.x, the npm+ packages up to 0.1.1), contain the replaced code. Do not copy from history before this change's merge commit.+- The review covers the session records we hold. For work done elsewhere it rests on what the code and the docs+ say about themselves and on their authors' word.diff --git a/docs/REPORT.md b/docs/REPORT.mdindex 6a2578d..5d7e905 100644--- a/docs/REPORT.md+++ b/docs/REPORT.md@@ -47,10 +47,10 @@ Findings:* Against UE's own ground truth (Path Tracer), the native renderer at 32 spp is **as close as or closer than UE Lumen on 3 of 5scenes** (Cornell, sun room, neon). Lumen under-lights spot-lit and indirectly lit regions (neon luminance ratio 0.66 vs 0.98 native).* `glb-asset` residual is aerial-perspective haze / sky tone in UE PT and distant-texture filtering (UE mip-maps; native supersamples), not material error.-* UE parity required matching engine details found by reading the 5.8 source: rect lights emit `brightness/(0.5·W·H)`- (adapter sets nits/2); DefaultLit's multiscatter compensation is effectively off (fit k = 0 against UE PT; native k = 1- passes the white furnace test at 0.97–1.03); UE's Gaussian bloom, `FilmToneMap` + gamut expansion + blue correction, and- cos⁴ vignette are ported exactly; sun illuminance uses UE's 15-step ground-level transmittance.+* UE parity was measured, not assumed: rect lights' radiance convention (the UE adapter sets nits / 2), the multiple-+ scattering compensation (fit k = 0 against UE's path tracer; native k = 1 passes the white furnace test at 0.97–1.03),+ and the look of the post chain. The renderer's implementations are its own, from public sources+ ([PROVENANCE.md](PROVENANCE.md)); an earlier version of this report described ports, which have been replaced.* Each discrepancy was isolated with A/B renders against the UE path tracer, e.g. Cornell ΔE 8.0 → 0.93 after the rect-light fix.## 3. Speed and cold start@@ -142,8 +142,8 @@ swapchain, no browser, no streaming). It follows the same idea as UE5's real-timtraces 1+ spp with hardware ray queries (primary visibility, GI, soft shadows, reflections; 4 bounces + Russianroulette), reprojects and accumulates history validated per pixel by depth/normal (TSR/Lumen-style temporal reuse),denoises with an edge-avoiding à-trous filter (two extra wide passes where history is short, the role Lumen's radiance-cache plays; directly seen emission bypasses it), and applies UE's post chain (UE auto / local exposure, six-stage-bloom, cos⁴ vignette, filmic tonemap through a 32³ log LUT). The frame is traced, denoised and composed at the render+cache plays; directly seen emission bypasses it), and applies the post chain (auto / local exposure, bloom, cos⁴+vignette, a filmic tone curve through a 3D lookup table; docs/RUNTIME.md). The frame is traced, denoised and composed at the renderresolution with one sub-pixel jitter a frame, and one temporal upscaler takes it to the window's physical pixels (thestructure of UE's TSR after Lumen; ROADMAP § 1a). Dynamic resolution (down to half of the window's points a side) andthen samples per frame adapt to the GPU budget. Scene changes from the game keep history (geometry stays valid) and cap it briefly sodiff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 282928e..d76c508 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -1,5 +1,11 @@# Roadmap+> **Provenance note (2026-11-24).** This file is a log. Entries before that date describe earlier implementations of the+> post chain, the specular temporal pass, the diffuse history rules, the BSDF's energy terms, the atmosphere and the fog+> volume, which have since been replaced by implementations written from public sources+> ([PROVENANCE.md](PROVENANCE.md)). Where an entry names another engine's or SDK's internals, it records how that+> earlier code came about, not how the present code works; do not implement from such entries.+## GoalThreeRT's goal is AAA real-time game rendering: on consumer GPUs (Apple M series first), dynamic, open-world-scale game@@ -1863,12 +1869,7 @@ Measured on the M5 Pro (`out/liveq/gpu-runs-std.md`; single runs unless said):set again from this build's readings with the margins the old ones had (tools/bench-ghosting.ts); the trails'limits and the other shots' stand.-**History lengths (2026-11-12, after it).** The whole frame's history was cut by what happened in the scene: held to-48 frames while the camera moved, every pixel cut to 16 at a lighting edit and to 4 at a geometry edit, 24 for good in-a scene with spark lights. Now one bound while the scene's lighting changes (32 frames, a real-time denoiser's: NRD's-default is 30; `HISTORY_LIVE`), the long history once it has settled, and within it each pixel's own: 48 where it-moves a pixel a frame, and an anti-lag that cuts the irradiance history by how far its fast mean left the slow one-beyond their noise (ReBLUR's form; it was on / off). No edit cuts anything.+**History lengths (2026-11-12, after it).** [Removed 2026-11-24: this passage described an earlier implementation that has been replaced; docs/PROVENANCE.md. The measurements below are that implementation's.]| dE against the offline render or the converged frame | main | this ||---|---|---|@@ -1925,15 +1926,7 @@ hid two faults of the live path's own:- Not done: live GI, reflection and shadow rays still see no media (the stand-in light stays), and a medium has nomotion vector (smoke that drifts is reactive, not followed). (Overlapping media: below.)-**The specular history per pixel (2026-11-13, after it).** `stemporal` still set every pixel's history by what the-camera did: 2 .. 12 frames by roughness whenever it moved or turned at all, 4 for the 8 frames after it translated-(§ 2c's fix). Now each pixel's own, from two things it knows (output pixels a frame): its speed (a resampled history-blurs: 48 frames at a pixel a frame, as the diffuse) and its reflection's parallax, how far what it reflects moved-against the surface: the history may be no longer than keeps its trail (frames × parallax) within 2 px (`SPEC_TRAIL`),-2 frames at least on a mirror, 4 from roughness 0.05. The parallax is the reflected point's where this frame's sample-has one, the farthest possible point's where it has none, and a moving reflector's own speed. A turn has no parallax-and keeps its history; a translation shortens it where the reflection slides, by how fast. NRD's ReBLUR bounds the-specular history per pixel by parallax too (its source, `REBLUR_TemporalAccumulation`).+**The specular history per pixel (2026-11-13, after it).** [Removed 2026-11-24: this passage described an earlier implementation that has been replaced; docs/PROVENANCE.md. The measurements below are that implementation's.]| bench-ghosting --quick, excess over the settled frame / trail px (turn-mid, strafe-mid ground; the two returns + 0.5 s; stop + 0.1 s) | main | this ||---|---|---|@@ -1941,7 +1934,7 @@ specular history per pixel by parallax too (its source, `REBLUR_TemporalAccumula| Bistro | 1.08 / 5, 1.76 / 6, 1.25 / 12, 1.34 / 12, 1.50 / 5 | 0.84 / 7, 1.60 / 6, 1.17 / 12, 1.26 / 11, 1.34 / 5 |- What was tried and left out, each measured (`out/liveq/gpu-runs-std.md`, S1–S20):- - the parallax weighed against the reflection's own blur, as ReBLUR weighs it against the lobe's angle (the+ - the parallax weighed against the reflection's own blur, the lobe's angle (thehistory may trail K lobe footprints behind): a wet street's lobe is 27–245 px wide here, the history ran througha forward move, and the stop dragged a 65–112 px trail (limit 35);- two thresholds instead of one budget (2 .. 12 frames from 0.25 px of parallax, 4 from 2 px): passes, a little@@ -1956,7 +1949,7 @@ specular history per pixel by parallax too (its source, `REBLUR_TemporalAccumulamain's own runs across two days (move40 3.88–4.07). Stated as it is: the ghosting bench counts frames and repeatsto 0.02, this one does not.- Not changed, measured: what makes the scene's lighting "live" for the whole frame. Anything that moves or is edited- does, for 45 frames, so a scene with a walker in it is always at the 32-frame bound (NRD's own: 30), and the rule+ does, for 45 frames, so a scene with a walker in it is always at the 32-frame bound, and the rulefor spark lights adds nothing there (the Bistro slice reads the same without it). The radiance cache's history iscut to 4 frames by the same switch: at 32 the slice reads 2.66 for 2.82 at rest and 5.80 for 6.03 at itsexplosion, and all of test-render passes; what the 4 frames buy is how fast indirect light follows an edit, which@@ -2009,7 +2002,7 @@ A rect light's card and the sun still rebuild (geometry; the sky's bake).as before.- Seen on the way, not this change's: 2 s after a 5,000 cd light is hidden beside a 1,000 cd one the plane underthem still reads 6 % high. 45 frames after a lighting edit the long history comes back, and what is left of the- old light then averages out as 1 / n (NRD's fixed 30 frames would decay it for good). And 0.3 s after a fireball+ old light then averages out as 1 / n. And 0.3 s after a fireballis hidden a faint ring stays where its edge was (the upscaler's history: nothing says a medium went).- Not done: `Explosions` still parks (the voxel line's to change); a mesh hidden by its own `visible` still rebuilds.@@ -2047,12 +2040,7 @@ converged frame of the state after, beside the frame k frames after a history relater (lamp off: 2.24 for 1.66 at 32 frames, 1.38 for 1.12 at 128; lamp on: 0.50 for 0.72, 0.79 for 0.93). The 4frames buy what they were said to and stay; the 0.16 ΔE they cost a scene at rest is the price.-**The fast-history clamp (2026-11-13, after it).** ReBLUR's way of following a lighting change, in `dtemporal`: every-frame, while the scene's lighting is live, the slow means around the pixel (3 × 3 on its surface) are held, a channel-each, to the band of the fast means there (a quarter of each new sample; their mean ± 3 standard errors, from the fast-luminances' spread), and the pixel's history is changed by the same ratios and counts for as many frames less. The-fast mean in colour is kept in the buffer that was the `judge` pass's unread ping-pong partner: no new memory. The-cut by luminance stays beside it. `bench-temporal --shot edit`, ΔE against the converged frame of the state after:+**The fast-history clamp (2026-11-13, after it).** [Removed 2026-11-24: this passage described an earlier implementation that has been replaced; docs/PROVENANCE.md. The measurements below are that implementation's.]| edit, region | 8 frames: before → now | 32 frames | 128 frames | a view with no memory, 32 ||---|---|---|---|---|@@ -3327,14 +3315,7 @@ Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ referencesKabukichō shots below are history.### 2a. Reflection temporal parameters at UE 5.8 defaults-Reference: `Engine/Shaders/Private/Lumen/LumenReflectionDenoiserTemporal.usf`, `LumenReflections.cpp:153-162`,-`LumenReflectionDenoiserSpatial.usf:92`.-- Neighbourhood clamp always on (not only in motion), in YCoCg, 1σ (`NeighborhoodClampScale` = 1).-- At most 12 accumulated frames (`MaxFramesAccumulated`); at full resolution, specular with roughness < 0.05 drops to 2- frames (residual noise left to TSR).-- Virtual-image (mirror reprojection) and surface histories are clamped separately; keep the one closer to the- neighbourhood (`...Temporal.usf` ~l.495).-- Spatial filter radius × saturate(roughness × 8).+[Removed 2026-11-24: this passage described an earlier implementation that has been replaced; docs/PROVENANCE.md.]- Today `live.wgsl` clamps only in motion, at 2–3σ in RGB, with 8–48 frames of history.- Also: at long history the live image is the raw accumulated average (all à-trous stages gated off by history lengthsince round 3: Cornell box at 256 frames SSIM 0.912 vs the UE Path Tracer, 0.98 on Nov 4). Gate on the remaining@@ -3487,7 +3468,7 @@ dynamic-resolution floor, 60 Hz camera input.- The option left: a second emitter sample at near-mirror camera hits in the same pass. It needs the camerahit's surface (a primary ray and a material evaluation), an estimated +0.6–1.0 ms more, so Kabukichōmoving would be ~16.6–17.0 ms.- - UE 5.8's own temporal rules for reflections (`LumenReflectionDenoiserTemporal.usf`), applied while the view+ - UE 5.8's temporal rules for reflections, as an earlier implementation had them (docs/PROVENANCE.md), applied while the viewmoves (2026-11-07):- What changed: no hold after translating; 12 frames; a clamp at 1 σ, doubled for samples reconstructedfrom neighbours (all of ours below 100 %), also tried at 4 and 8 σ; the reflection-hit history only for@@ -3939,9 +3920,9 @@ dynamic-resolution floor, 60 Hz camera input.- Velocity: the temporal pass computes each pixel's motion from the camera and the motion vectors.- Reconstruction: a gather after McGuire et al. 2012 on the HDR image before bloom. A moving object smears overa static background; a static foreground stays sharp.- - Length, as UE's (PostProcessMotionBlur.cpp, UpdateMotionBlurTimeScale): ± amount / 2 × the frame's motion ×- (1 / target FPS) / frame time. At 60 fps that is one frame of motion in total, capped at 5 % of the width.- - Camera cuts (a jump of 2 m or 30° in one frame) don't blur (UE: bCameraCut). Without that check, Kabukichō's+ - Length: from the amount, the frame's motion and the target frame rate (docs/RUNTIME.md, "The post chain"). At 60 fps+ that is one frame of motion in total, capped at 5 % of the width.+ - Camera cuts (a jump of 2 m or 30° in one frame) don't blur. Without that check, Kabukichō'sviewpoint switch smeared the whole frame (horizontal gradient energy 102 vs 363).- Cost at the 0.5 floor, Kabukichō:- 0.44 ms while anything moves: 15.78 ms total vs 15.36 with it off.@@ -3951,7 +3932,7 @@ dynamic-resolution floor, 60 Hz camera input.- Within budget either way.- UE reference: bench-temporal `--motion-blur` against UE renders with the same settings (`MB=1ue5/temporal.ts`). Movie Render Queue replaces the amount with its shutter fraction (0.5) and the target FPS with- the output rate (60) (MoviePipelineImagePassBase.cpp), which is half the real-time blur. Ours at UE's real-time+ the output rate (60), which is half the real-time blur. Ours at UE's real-timedefaults read about twice UE's blur against those frames. Ours at what MRQ rendered (`THREERT_MOTION_BLUR=0.5,5,60`):- excess over UE move20 / move40 / move59 / stopped 1.23 / 1.51 / 1.60 / 2.01 (unblurred 1.43 / 1.75 / 1.75 /2.01);@@ -3960,10 +3941,7 @@ dynamic-resolution floor, 60 Hz camera input.- Depth of field at UE's defaults: done (2026-11-06).- UE's default is off: no focus distance on the camera. A camera's `dof` (focus distance, f-stop, sensor width;UE's defaults f/4, 24.576 mm) switches it on.- - CoC: UE's physical model (DiaphragmDOFUtils.cpp, FPhysicalCocModel):- - focal length from the sensor height (width / aspect) and the vertical FOV;- - CoC of infinity f² / (N (focus − f));- - per pixel (z − focus) / z of that, capped at 2.5 % of the width (r.DOF.Kernel.Max{Fore,Back}groundRadius).+ - CoC: a thin lens (docs/RUNTIME.md, "The post chain"), capped at 2.5 % of the width.- Live: a gather on the composed HDR image, before motion blur as in UE.- The CoC is computed in the compose pass.- A 16 × 16 tile maximum bounds each pixel's search.@@ -4477,10 +4455,8 @@ dynamic-resolution floor, 60 Hz camera input.instead of four (kept, −0.03 ms); no media in the surface cache's training shadows (−0.08 ms with a bias:dropped).- Next (part 3): UE references and the motion metric; cheaper media shadow rays to fit rain + smoke.- - Status, part 3a: UE references, and `FogVolume` is UE's Local Fog Volume.- - `FogVolume` takes UE 5.8's Local Fog Volume density as UE voxelizes it into volumetric fog- (VolumetricFog.usf), with UE's settings and defaults (docs/MATERIAL_FUNCTIONS.md, "Volume functions").- `volume/local-fog` (new): 0.2823 against the numerically integrated 0.2863.+ - Status, part 3a: UE references.+ - [Removed 2026-11-24: this passage described an earlier implementation that has been replaced; docs/PROVENANCE.md.]- UE references, `bun ue5/volumes.ts`: `tools/volume-scene.ts` in a scratch project, path-tracer and Lumen stillsas linear EXR.- Every preset is a Heterogeneous Volume: a Volume-domain material whose Custom nodes are our volume@@ -6131,7 +6107,7 @@ benchmark level. The order follows the dependencies; a step that meets a further- Auto exposure (fixed 2026-11-06): the presets' histogram range was UE's legacy -8 .. 4 (log2 luminance), whichdaylight saturates (a 3000-nit sky pinned the exposure at EV 6.5, the image washed out). UE 5 projects enabler.DefaultFeature.AutoExposure.ExtendDefaultLuminanceRange (every template), giving EV100 -10 .. 20, the same log2- luminance at the default lens attenuation (Scene.cpp, PostProcessEyeAdaptation.cpp EV100ToLog2). The presets use+ luminance at the default lens attenuation. The presets useit now; Kabukichō keeps the legacy range explicitly, as its UE project does. Atomic tests `exposure/auto-daylight`(offline and live; 14.00 vs 14.03 expected) and `exposure/auto-night`. Still different: UE's default exposurecompensation is +1 EV (r.DefaultFeature.AutoExposure.Bias = 1.0); our camera's default is 0.diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex e02b07c..378a04f 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1876,6 +1876,258 @@ On an Apple M1 running macOS 27.2.1, the glass camera move scored 0.909 SSIM witoutput, median GPU frame times with the camera held still were 9.69, 9.78 and 10.22 ms respectively.On the Cornell box the built-in path scored highest for both camera poses.+## The post chain++`renderer/src/post.rs` (offline: `post::finish`, and the reference) and the last passes of+`renderer/shaders/live.wgsl` (`lum_down` .. `post`) take scene-linear radiance in nits (Rec.709 primaries, D65) to+8-bit sRGB. The settings are a preset's `post` block (`desc::PostPreset`), the camera's exposure and depth of field.+Their names follow Unreal's Post Process Volume settings and mean what its public documentation says, so a scene's+look can be compared with the same settings in Unreal; the methods are ours, from public sources, with the free+constants fitted to measurements of the look the presets ask for (`renderer/examples/post_check.rs` is the check;+licences in `THIRD_PARTY_NOTICES.md`).++In the order a pixel goes through it:++| Step | Settings | What it does | From |+|---|---|---|---|+| Exposure | camera `setManualExposure(ev100)` / `setAutoExposure(compensation, minEv100, maxEv100)`; `autoExposure.lowPercent`, `highPercent`, `histogramLogMin`, `histogramLogMax`, `speedUp`, `speedDown` | Manual: scale 2^-EV100 (EV100 0 shows 1 nit as 1.0). Auto: a 64-bin histogram of the log2 luminance of the frame at quarter resolution, within the histogram range (what is outside is not counted); the average luminance between the two percentiles is exposed as middle grey (0.18) x 2^compensation, the average held within what `minEv100` .. `maxEv100` expose as middle grey. Live, the exposure moves to that target at `speedUp` (the scene got brighter) / `speedDown` EV per second, exponentially within the last 1.5 stops, and snaps on a reset. | own design after the settings' documented meaning |+| Depth of field, motion blur | camera `dof`; `motionBlur.amount`, `max`, `targetFps` | Live passes on the exposed-to-be image (`dof`, `mblur`). The lens is a thin lens: circle of confusion r_inf (1 - s / z), at most 2.5 % of the width. The blur is `amount` of a frame's motion, of a frame at `targetFps` when that is set. | thin-lens optics; own design |+| Local exposure | `localExposure.highlightContrast`, `shadowContrast`, `detailStrength`, `blurredLuminanceBlend`, `blurredLuminanceKernel` | Log luminance is split into a base (an edge-aware blur at quarter resolution, blended with a wide Gaussian of `blurredLuminanceKernel` % of the width) and the detail left over; the base's distance from middle grey (x auto exposure's compensation) is scaled above / below it, the detail by `detailStrength`. All 1: off. | Durand & Dorsey 2002 |+| Bloom | `bloom.intensity`, `threshold`, `sizeScale`, `sizes`, `tints` | Added to the picture: `intensity` x 0.175 x the sum over up to six stages of `tints[k]` x a Gaussian blur of standard deviation 0.1 x `sizes[k]` x `sizeScale` percent of the width, of what blooms (everything under a negative threshold; else from the threshold, in exposed luminance, to one unit above it). Offline each Gaussian is taken to its own shape. Live they are a weighted sum of the levels of a 1/4 .. 1/128 pyramid (each stage as the two levels around its width; wider ones summed on the coarsest level; a five-pixel kernel of the output for stages under about two pixels): 12 small passes after `lum_down`. Next to a light hundreds of times brighter than its surroundings the live glow ends a few pixels sooner than offline. | own design; pyramid: Burt & Adelson 1983 |+| Vignette | `vignette` | cos^4 of the field angle, whose tangent at the corner is 1.425 x the setting (0.4: the corners at 57 %). | cos^4 law |+| Chromatic aberration | `chromaticAberration` (0 .. 5) | Red is read from a picture magnified by 0.2 % a unit about the centre, blue from one reduced by as much. | own design |+| Colour grading | `colorGrading.whiteTemp`, `whiteTint`, `saturation`, `contrast`, `shadowsGain`, `highlightsGain` | White balance: Bradford adaptation from the illuminant of that temperature (CIE daylight locus from 4000 K, Planckian below 3000 K; the tint shifts it across the locus) to the 6500 K white. Then, on scene-linear ACEScg: saturation about the luminance, contrast as a power about 0.18, gains weighted to shadows (luminance under 0.09) and highlights (from 0.5, whole from 1). Scalar or RGB; 1 = none. | CIE 15, Krystek 1985, Lam 1985; own design |+| Tone curve | `colorGrading.expandGamut`, `blueCorrection` | The Academy's reference rendering for an sRGB display (ACES 1.x RRT + ODT: its "glow" and "red modifier", per-channel tone scale in ACEScg between its 0.96 and 0.93 desaturations) with a tone curve of our own, two logistic branches in log exposure (`post::ToneCurve`: toe a power law to black, shoulder closing on 1.04). In front of it: the gamut expansion (bright saturated colours re-read in a wider gamut, by `expandGamut`), and the Academy's blue-light-artifact fix by `blueCorrection`, undone after the curve. Live this and the grading are a 48^3 table over log2 exposure (-10.5 .. 6.5 stops). | ACES 1.3 reference transforms (AMPAS licence); curve and expansion fitted |+| Film grain | `filmGrain` (0 .. 1) | Zero-mean luminance noise on the encoded value, strongest in the mid-tones, new each frame (`THREERT_NO_GRAIN=1`: none). | own design |++Measured against the previous release's look (its tables and seven reference pictures): the neutral ramp within 0.0004+in sRGB-encoded value, 6 657 colours at a mean CIE dE2000 of 0.19 (99th percentile 1.1), the grading tables at 0.17 ..+0.26, the pictures at 0.12 .. 0.39 (99th percentile under 1.9). `node tools/post-live.ts` puts the live passes against+`post::finish` of the same frame (mean dE2000 0.15 .. 0.57 on the seven scenes at 960 x 540).++## The temporal response of the live denoiser++The live view traces about one path a pixel and accumulates: the diffuse irradiance in `dtemporal`, the specular+light in `stemporal` (`live.wgsl`; the section "The response of the histories" there has the rules, their sources+and what was tried). A frame bounds every history (`L.misc.y`: `HISTORY_LIVE`, 24 frames, while the scene's+lighting changes, 4096 once it has settled); within that, each pixel's history has a length of its own.++- **In motion.** A history that moves over the grid is resampled bilinearly every frame, and each resampling blurs+ it a little (Karis 2014 calls it reprojection diffusion): a tap at a fraction f of a pixel is a two-point kernel+ of variance f (1 - f) pixels². The length is bounded so that the blur gathered stays under a budget+ (`moving_frames`; `MOVE_BLUR`, `SPEC_MOVE_BLUR` pixels²: 64 and 32 frames at half a pixel a frame and faster, more+ below). Holding still, nothing bounds. The bound trades blur for noise; what a reflection needs in a move of the+ camera is not this bound but the parallax's (below).+- **Animated shading** (signs, screens): `ANIM_FRAMES` for the diffuse history.+- **While the lighting changes** (`L.mode.z`: something moved or was edited in the last 45 frames), a change chart+ per pixel, and a drift. The renderer cannot trace last frame's path again with its random numbers (the temporal+ gradient of Schied et al. 2018), so what it has is each frame's sample against the pixel's own history, and the+ question is a control chart's: has the mean of a noisy stream shifted. The chart is an exponentially weighted+ moving average watched against a band of its own deviations (NIST e-Handbook of Statistical Methods § 6.3.2.4),+ with three choices made for one-sample path tracing:+ - The reading is the sample's *share* against the history, s / (s + h') per channel: 0 for a dark sample, about a+ half at the history's level, towards 1 far above it. A sample is heavy-tailed (most are dark, a few carry the+ light); a share is bounded, so no single sample moves the chart by more than a fixed step, and a run of dark+ samples on a pixel lit by rare bright ones reads as what it is, the usual.+ - The residual is taken from the pixel's own running mean of that share (its level), so it has mean 0 while the+ lighting holds, whatever the surface, and residuals of neighbouring pixels can be pooled.+ - Pooled by recursion: each frame the average is read from the pixel itself and four pixels at distance √5 around+ where it was, and this frame's residual is added with weight 1/8. About 250 residuals stand behind a pooled+ value (a pixel's own average has 15), over a radius of a few pixels and about eight frames.++ The chart signals when the pooled average leaves a band (`CHART_K` of its deviations, from the residuals' pooled+ mean square; at least `CHART_FLOOR`), and the response is Schied et al.'s blend rule (their eq. 15): the weight a+ becomes a + drop (1 - a). The diffuse chart is kept per channel (a red sign switched off beside a white lamp+ moves the red channel's share far more than the luminance); the specular one on the mean of the three.++ **The drift.** A chart whose level follows the history sees a change and then gets used to it: under a light that+ falls a little every frame (a dusk) the shares settle at a lower level, and the history trails the light by its+ whole length for as long as the fall lasts. What does not get used to it is the plain relative residual+ (l - h) / h of the luminance, whose mean is 0 for a history that is the samples' mean and minus the lag for one+ that trails. It is pooled as the chart's average is, each pixel's weighted by how far its samples can be trusted+ (1 / (1 + cv²), cv their relative deviation), and the response is not a shorter history but a moved one: each+ frame the history is scaled by 1 + `DRIFT_GAIN` × the pooled residual, less what the pixel's noise allows the+ pooled value to be by chance. The lag goes and the noise stays that of a full history. The same factor goes to+ the specular history of rough surfaces. Pixels lit by rare bright samples are left out (a bounded mean of a+ skewed sample is biased; their weight is small): there the frame's bound alone follows.++ The state of both lasts in `diffuse_fast` (diffuse) and `diffuse_mom`.z (specular) and is kept up while the+ lighting is settled too, when nothing responds: with `L.mode.z` 0 the diffuse history is the plain mean of its+ frames, and a still view converges on the offline render.++`stemporal` adds what a reflection needs:++- **Where the history is.** A reflection's image does not move with the surface that shows it but by the depth of+ what is reflected (Stachowiak 2015). The history is read where the surface point was and, when the two differ by+ a quarter pixel or more, where the point at the surface's distance plus the reflection's hit distance along the+ view ray was (the image in a plane mirror; for a surface that moved, carried by twice its move along its normal).+ This frame's nine samples around decide: each history counts by its distance from their mean in YCoCg, in bands+ of `SPEC_GAMMA` deviations (Karis 2014's neighbourhood box, as a mean and deviations), times what the roughness+ says beforehand (the reflection's place on a mirror, the surface's from roughness 0.6).+- **How long.** Besides the frame's and the motion's bound: by the parallax, the distance between those two places+ a frame (none in a camera turn), so that the history has not slid against what it shows by more than+ `SPEC_SLIDE` pixels, more with roughness² (a blurred image hides a slide). Where the sample has no hit distance,+ the parallax of a far reflection is assumed; rough surfaces are bound too (a lamp's highlight on wet stones+ slides with the view); on a mirror a share of it counts, and little where the reflection's history was found in+ its place and agrees. While the lighting changes, also by roughness: shortest (`SPEC_LIVE_GLOSS`) where a+ reflection is sharp and the filter already reaches, longer on a mirror (`SPEC_LIVE_MIRROR`), the frame's bound on+ rough surfaces.+- **What it follows**, while the lighting changes or the reflection moves against its surface, and always on+ animated shading (waves): the chart, and the neighbourhood's band: the history is clamped into the nine samples'+ mean ± (`SPEC_GAMMA` deviations + `SPEC_REL` of its own level). Where the light comes by rare bright samples,+ nine dark ones say nothing against a history that holds their mean; the chart's level knows those pixels (their+ mean share is far below a half), and there the band is as wide as the history's level: it can be raised, not+ cut. A reflection that passes is steady while it is there: a history the clamp raises (all nine samples above+ it) has its level set so, and while the lighting changes a pixel takes the highest level among the pixels its+ chart pools from, so a passing reflection's rim goes with its middle. On animated shading half of the allowance+ is kept (`SPEC_ANIM_RARE`): a glint that has moved on is not a rare sample, a glint under a stopped clock is.+- **The filter's reach** (`sfilt*`): `SPEC_REACH` × roughness² traced pixels (the lobe's width): none on a mirror,+ all three passes from roughness 0.25.++**Measured** on the integrated tree, 2026-11-24 (this machine; the previous release, the tree with the first+version of these rules, and now). `test-render`: 271 of 271 pass. The two wall-clock shots (the Bistro move and the+volumes) vary with what else the GPU is doing (the volumes shot, this build, four runs that evening: 0.33 to+0.37 at its first frame, and once 0.52 under another session's load); the others run in lockstep and repeat.++`node tools/bench-ghosting.ts --quick --check` (passes; excess ΔE / p95 excess / trail px):++| | previous | first version | now |+|---|---|---|---|+| turn-mid ground | 0.85 / 2.8 / 5 | 0.92 / 2.79 / 4 | 0.87 / 2.82 / 6 |+| strafe-mid ground | 1.6 / 3.9 / 5 | 1.37 / 3.26 / 5 | 1.38 / 3.41 / 5 |+| turn-return+0.5s all | 1.13 / 3.74 / 10 | 1.13 / 3.65 / 9 | 1.13 / 3.77 / 10 |+| strafe-return+0.5s all | 1.25 / 3.97 / 10 | 1.22 / 3.74 / 9 | 1.22 / 3.95 / 10 |+| stop+0.1s ground | 1.34 / 3.38 / 6 | 1.49 / 3.83 / 5 | 1.36 / 3.53 / 5 |++`node tools/bench-object-ghosting.ts --repeat 3` (ΔE / p95 / trail px over the swept band):++| | previous | first version | now |+|---|---|---|---|+| device-slide mid | 1.78 / 6.10 / 31 | 1.86 / 6.74 / 31 | 1.79 / 6.58 / 31 |+| device-slide end | 1.97 / 6.23 / 29 | 1.75 / 6.85 / 29 | 1.79 / 6.72 / 29 |+| device-slide end+0.1s | 0.95 / 3.38 / 15 | 1.05 / 4.02 / 22 | 1.03 / 3.79 / 23 |+| device-slide end+0.3s | 0.70 / 1.86 / 3 | 0.73 / 1.99 / 3 | 0.70 / 1.89 / 3 |+| device-lift mid | 2.39 / 12.26 / 121 | 2.19 / 10.75 / 119 | 2.17 / 10.72 / 117 |+| device-lift end | 0.96 / 2.60 / 14 | 0.94 / 2.80 / 14 | 0.92 / 2.71 / 14 |+| device-lift end+0.1s | 0.74 / 1.85 / 7 | 0.72 / 1.99 / 6 | 0.71 / 1.80 / 6 |+| device-lift end+0.3s | 0.52 / 1.20 / 2 | 0.52 / 1.33 / 2 | 0.50 / 1.09 / 2 |+| orb-throw mid | 13.12 / 29.26 / 645 | 10.31 / 24.21 / 399 | 9.25 / 23.32 / 346 |+| orb-throw end | 10.21 / 30.77 / 436 | 8.84 / 28.67 / 399 | 7.35 / 23.51 / 295 |+| orb-throw end+0.1s | 5.23 / 15.98 / 173 | 5.48 / 14.68 / 281 | 3.75 / 10.62 / 97 |+| orb-throw end+0.3s | 2.96 / 9.03 / 155 | 3.71 / 9.28 / 191 | 1.96 / 5.72 / 59 |+| walker-run mid | 0.35 / 1.07 / 15 | 0.40 / 1.07 / 39 | 0.39 / 1.07 / 33 |+| walker-run end | 0.44 / 1.09 / 29 | 0.48 / 1.11 / 28 | 0.47 / 1.09 / 28 |+| walker-run end+0.1s | 0.35 / 1.07 / 21 | 0.38 / 1.09 / 15 | 0.37 / 1.08 / 17 |+| walker-run end+0.3s | 0.29 / 0.93 / 6 | 0.32 / 1.06 / 4 | 0.30 / 0.94 / 3 |++`node tools/bench-temporal.ts --shot edit` (ΔE 32 frames after the switch / luminance over the settled frame's at 32 frames / frames until within 2 % for good, 0: never in 256):++| | previous | first version | now |+|---|---|---|---|+| lamp off, pool | 1.39 / 1.137 / 128 | 0.59 / 1.032 / 64 | 0.6 / 1.032 / 64 |+| lamp off, bounce | 1.03 / 1.177 / 128 | 1.2 / 1.215 / 256 | 0.75 / 1.081 / 64 |+| lamp off, room | 0.96 / 1.015 / 32 | 1.08 / 1.034 / 64 | 0.85 / 1.012 / 32 |+| lamp on, pool | 0.93 / 0.977 / 64 | 0.48 / 0.992 / 16 | 0.43 / 0.993 / 16 |+| lamp on, bounce | 2.61 / 0.758 / 0 | 2.04 / 0.819 / 0 | 1.64 / 0.857 / 256 |+| lamp on, room | 1.42 / 0.955 / 128 | 1.35 / 0.965 / 64 | 1.05 / 0.975 / 64 |+| sign off, signfloor | 1.37 / 1.058 / 64 | 0.8 / 0.972 / 128 | 0.9 / 0.972 / 128 |+| sign off, room | 1.23 / 1.029 / 64 | 1.19 / 1.022 / 64 | 1.14 / 1.006 / 32 |+| sign on, signfloor | 3.53 / 0.836 / 256 | 0.8 / 0.97 / 64 | 0.88 / 0.964 / 64 |+| sign on, room | 2.28 / 0.931 / 128 | 1.12 / 0.968 / 64 | 1.14 / 0.97 / 64 |++`node tools/bench-temporal.ts --shot water` (still ΔE / moving ΔE, at scene times 6, 7, 8 s):++| | previous | first version | now |+|---|---|---|---|+| water, time held | 1.67 / 1.55 / 1.45 | 0.68 / 0.66 / 0.62 | 1.36 / 1.28 / 1.2 |+| water, running | 4.62 / 4.71 / 4.48 | 7.08 / 6.99 / 6.77 | 4.15 / 4.11 / 4.13 |+| reflections, time held | 3.08 / 3.01 / 2.77 | 1.16 / 1.16 / 1.11 | 3.22 / 3.04 / 2.88 |+| reflections, running | 13.35 / 12.9 / 12.25 | 20.57 / 20.7 / 20.67 | 12.45 / 12.03 / 11.6 |++`node tools/bench-temporal.ts --shot foliage` (still ΔE / moving ΔE, at scene times 6, 7, 8 s):++| | previous | first version | now |+|---|---|---|---|+| plants, time held | 0.21 / 0.22 / 0.22 | 0.22 / 0.22 / 0.22 | 0.22 / 0.22 / 0.22 |+| plants, running | 0.9 / 0.92 / 0.95 | 0.83 / 0.85 / 0.88 | 0.88 / 0.9 / 0.93 |+| ferns, time held | 0.23 / 0.23 / 0.23 | 0.24 / 0.24 / 0.24 | 0.24 / 0.24 / 0.23 |+| ferns, running | 1.03 / 1.14 / 0.99 | 0.93 / 1.04 / 0.9 | 0.98 / 1.08 / 0.94 |++`node tools/bench-temporal.ts` --shot volumes (ΔE / p95 at move20, move40, move59, 0.5 s after the stop):++| | previous | first version | now |+|---|---|---|---|+| ΔE | 0.33 / 0.36 / 0.37 / 0.22 | 0.42 / 0.56 / 0.56 / 0.32 | 0.33 / 0.36 / 0.36 / 0.22 |+| p95 | 1.04 / 1.12 / 1.08 / 0.82 | 1.32 / 1.99 / 1.79 / 0.84 | 1.03 / 1.12 / 1.06 / 0.82 |++`node tools/bench-temporal.ts` (the Bistro move) (ΔE / p95 at move20, move40, move59, 0.5 s after the stop):++| | previous | first version | now |+|---|---|---|---|+| ΔE | 2.45 / 2.51 / 2.47 / 2.08 | 1.84 / 1.91 / 1.81 / 1.44 | 1.89 / 1.97 / 1.93 / 1.55 |+| p95 | 7.69 / 7.97 / 7.83 / 6.56 | 6.07 / 6.18 / 5.83 / 4.45 | 6.4 / 6.53 / 6.5 / 5.05 |++`node tools/bench-window.ts` (ΔE / p99 against offline, or for the dusk against the same moment held):++| | previous | first version | now |+|---|---|---|---|+| still-bistro, held | 1.81 / 13.62 | 1.83 / 13.93 | 1.83 / 13.92 |+| still-rooms, held | 0.63 / 1.82 | 0.59 / 1.79 | 0.59 / 1.77 |+| still-rooms-wide, held | 0.77 / 1.99 | 0.77 / 2 | 0.76 / 1.95 |+| still-glass, held | 1.28 / 27.19 | 1.27 / 26.89 | 1.27 / 26.87 |+| rooms-turn, last | 0.89 / 3.44 | 0.92 / 3.94 | 3.32 / 0.9942 |+| rooms-turn, stop1 | 0.88 / 3.33 | 0.91 / 3.81 | 3.22 / 0.9944 |+| rooms-turn, stop6 | 0.87 / 3 | 0.9 / 3.43 | 2.9 / 0.995 |+| rooms-turn, stop30 | 0.89 / 2.5 | 0.93 / 2.77 | 2.44 / 0.9954 |+| rooms-turn, settled | 1.03 / 2.36 | 1.05 / 2.39 | 2.31 / 0.9957 |+| slice, 40.5 s | 6.05 / 23.22 | 4.6 / 25.53 | 24.71 / 0.8425 |+| tokyo-dusk, 6 s, skyline | 1.35 / 11.56 | 1.79 / 14.98 | 1.26 / 11.35 |+| tokyo-dusk, 6 s | 1.12 / 8.46 | 2.61 / 16.02 | 1.11 / 8.52 |+| tokyo-dusk, 7 s, skyline | 0.86 / 8.49 | 1.18 / 10.96 | 0.86 / 8.81 |+| tokyo-dusk, 7 s | 0.6 / 5.46 | 1.44 / 10.27 | 0.61 / 5.48 |+| tokyo-dusk, 8 s, skyline | 0.31 / 3.87 | 0.51 / 5.39 | 0.4 / 4.95 |+| tokyo-dusk, 8 s | 0.5 / 5.81 | 0.87 / 6.65 | 0.5 / 5.66 |+| tokyo-turn, last, tower | 2 / 33.29 | 1.99 / 33.22 | 33.24 / 0.9268 |+| tokyo-turn, last | 2.43 / 35.84 | 2.4 / 35.69 | 35.69 / 0.9142 |+| tokyo-turn, stop1, tower | 1.9 / 31.18 | 1.89 / 31.13 | 31.16 / 0.9336 |+| tokyo-turn, stop1 | 2.3 / 34 | 2.27 / 33.82 | 33.82 / 0.9225 |+| tokyo-turn, stop6, tower | 1.66 / 26.59 | 1.64 / 26.61 | 26.64 / 0.9506 |+| tokyo-turn, stop6 | 1.9 / 28.41 | 1.87 / 28.24 | 28.24 / 0.9443 |+| tokyo-turn, stop30, tower | 1.41 / 22.21 | 1.4 / 22.35 | 22.38 / 0.9647 |+| tokyo-turn, stop30 | 1.51 / 22.94 | 1.48 / 22.79 | 22.78 / 0.9607 |+| tokyo-turn, settled, tower | 1.39 / 22.25 | 1.38 / 22.29 | 22.27 / 0.9656 |+| tokyo-turn, settled | 1.37 / 21.43 | 1.34 / 21.37 | 21.34 / 0.9656 |+| tokyo-orbit, last, tower | 3.95 / 51.11 | 3.98 / 50.49 | 50.49 / 0.8647 |+| tokyo-orbit, last | 2.29 / 35.2 | 2.28 / 35.08 | 35.08 / 0.9131 |+| tokyo-orbit, stop1, tower | 3.8 / 49.36 | 3.82 / 49.2 | 49.36 / 0.875 |+| tokyo-orbit, stop1 | 2.16 / 33.39 | 2.15 / 33.29 | 33.31 / 0.9213 |+| tokyo-orbit, stop6, tower | 3.14 / 41.65 | 3.16 / 41.73 | 41.59 / 0.9183 |+| tokyo-orbit, stop6 | 1.77 / 27.28 | 1.76 / 27.2 | 27.2 / 0.9449 |+| tokyo-orbit, stop30, tower | 2.64 / 36.45 | 2.64 / 36.03 | 36.19 / 0.9409 |+| tokyo-orbit, stop30 | 1.4 / 22.1 | 1.39 / 22.01 | 22.05 / 0.9608 |+| tokyo-orbit, settled, tower | 2.52 / 35.5 | 2.51 / 35.38 | 35.38 / 0.9455 |+| tokyo-orbit, settled | 1.28 / 20.67 | 1.26 / 20.64 | 20.64 / 0.9659 |++What is still worse than the previous release, and why it is left: the dragged device's p95 at the middle and the+end of its slide and its row 0.1 s after (the errors there are the screen's text copies and the strip the device+uncovers, which the upscaler owns: with every rule of this section switched off the same rows read p95 6.84 at+the end and 4.07 after); the runner's rows by 0.01 to 0.04 and its trail at mid-run (33 px for 15; 42 with the+rules off); the dusk's skyline at 8 s (the diffuse and specular signals alone read 0.12 and 0.04 there, and the row+does not move with the frame bound, 0.40 to 0.42 from 16 to 32 frames: what differs is in the directly seen sky and+lamps); the slice's p99 (24.7 for 23.2, its mean 4.99 for 6.05); the mid-turn on the street (0.87 for 0.85) and+0.1 s after the stop there (1.36 for 1.34); and+the frames until the floor beside the switched-off sign stays within 2 % (128 for 64: the histories the chart cut+are 1 to 3 % low until the rare bright samples have come in again, where the previous release was 6 % high at 32+frames).++The GPU time of the two passes on Bistro night (1280 × 720, scale 0.5; rounds the project's own check called+quiet; the machine's GPU was shared, and its clock runs at two speeds, so compare within a round), still / on the+perf smoke's move: `dtemporal` 0.11 / 0.14 ms (the first version in this tree: 0.11 / 0.14 to 0.19), `stemporal`+0.12 to 0.13 / 0.19 ms (0.13 / 0.16 to 0.18) with rough surfaces still held to their neighbourhood in a move; with+that dropped, in rounds under another session's load: 0.14 to 0.15 moving (the first version in the same rounds:+0.15).++## Moving objects in the live viewThe live view's histories (the irradiance and specular ones on the traced grid, the upscaler's colour on the output@@ -1895,8 +2147,8 @@ over a polished floor, a character running over a sunlit floor, the camera stilland a carried lock that lands on a moving surface is dropped (`track`): a moving screen's text left copies ofitself for a jitter sequence.- **Reflections follow what moves past them.** While the lighting is live (a moving object sets it), a still- surface's specular history is clipped to this frame's neighbourhood (`SPEC_CLIP` deviations plus `SPEC_CLIP_REL`- of its luminance): a light carried past a polished floor left its reflection along its path.+ surface's specular history is held to this frame's neighbourhood and to its change chart ("The temporal response+ of the live denoiser", `stemporal`): a light carried past a polished floor left its reflection along its path.- **Where the light changed, the history waits for it.** While the lighting is live, a traced sample whose lightjumped since the previous frame (by `LIGHT_CHANGE` of itself and `LIGHT_FLICKER` times its own flicker: a shadow'sedge passed, a lamp's pool moved) starts its flicker count again (`track`), and the output pixels around it hold@@ -1908,13 +2160,10 @@ over a polished floor, a character running over a sunlit floor, the camera still-Not covered: the specular clip also cuts a right history where the lighting is live all the time (a crowd's-reflections are darker than offline's). A short-term specular history to clip against is no answer: at one sample-a pixel it is noise (tried and dropped: `dtemporal`'s anti-lag note). The clip is transitional: it goes when a-change in the lighting can be told from noise (last frame's path traced again with its random numbers). A fast-light's effect on diffuse lighting (a shadow it casts) still lags by a few frames (the diffuse-history and its anti-lag), and the band just uncovered starts from this frame's samples (more aliased for a frame or-two, as any disocclusion).+Not covered: a change of the light too small or too noisy for the change chart and the drift, and any change+where the light comes by rare samples, trail by the frame's bound (`HISTORY_LIVE`). A fast light's effect on diffuse+lighting (a shadow it casts) still lags by the two to four frames the chart needs, and the band just uncovered+starts from this frame's samples (more aliased for a frame or two, as any disocclusion).## Glassdiff --git a/docs/WORKFLOW.md b/docs/WORKFLOW.mdindex 25fbce1..aa04ce8 100644--- a/docs/WORKFLOW.md+++ b/docs/WORKFLOW.md@@ -50,6 +50,24 @@ Why (measured on 2026-11-07, the authoring session's last 24 h):- **Aborted tool calls.** Do not retry the identical command. Take another route (for example a scratch build in atemporary worktree) or skip the step and record the gap in the PR. Stop only when nothing else can be done.+## Sources++What the renderer's code may be written from is in [PROVENANCE.md](PROVENANCE.md); it binds both sessions.++- **Never read source code that cannot be MIT-licensed** while doing renderer work: Unreal Engine's engine source+ (`Engine/Shaders`, `Engine/Source`: the EULA), NVIDIA NRD or other RTX SDK source, any SDK or engine without an+ open-source licence compatible with MIT. Not to "check how they do it", not for a constant, not through a mirror or+ a quoted snippet. A session that has read such source for another purpose does not write renderer code afterwards;+ it says so and hands the item on.+- **Unreal is a black box here.** Its pictures, its documented settings and its scripting API (`ue5/`) are the+ reference; its source is not. When a parity gap needs explaining, measure it (A/B renders), read the public+ documentation, papers and talks, or ask the user.+- **Cite.** A formula, constant or method taken from a paper, a talk or open-source code is cited in a comment where+ it is used; code under a licence that asks for a notice goes in `THIRD_PARTY_NOTICES.md`. The PR description lists+ the sources of any algorithm it adds or changes.+- **The supervisor checks it.** A PR whose diff or description names a proprietary source file, or cites "its+ source" for a product that is not open source, is not merged; it goes back with this section.+## One PR per item- Branch from the latest `origin/main`; open one PR per item with base `main`. No stacked PRs.diff --git a/packages/scene/src/effects.ts b/packages/scene/src/effects.tsindex 362d133..20b6eec 100644--- a/packages/scene/src/effects.ts+++ b/packages/scene/src/effects.ts@@ -3,11 +3,11 @@ import { DensityGrid, GridProgram, Group, MaterialFunction, Mesh, MeshPhysicalMaimport { BoxGeometry, PlaneGeometry } from "./geometry.ts";/**- * Falling rain around the camera, UE's camera-wrapped rain curtain line for line (a UE 5.8 night-street level's rain- * actor + M_Rain: 16 000 streaks in a 32 x 32 x 22 m box that follows the camera; each falls at its own speed+ * Falling rain around the camera: the camera-wrapped rain curtain of this project's own night-street level in Unreal+ * (authored by us there, then transcribed here: its rain actor and material; 16 000 streaks in a 32 x 32 x 22 m box that follows the camera; each falls at its own speed* with the wind, wraps around the box, and turns its long side along its velocity and its face to the camera). Units* are metres (UE's centimetres / 100), y up. The drops shown follow `scene.rain` (0..1): a drop shows while its random- * number is below it, as in UE.+ * number is below it, as in that level.*/const RAIN = new ParticleFunction("rain_curtain", {params: { Box: [32, 22, 32, 0], Wind: [0.9, 0.4, 0, 0], Speed: 9.5, Length: 0.55, Width: 0.009, Opacity: 0.32 },@@ -243,63 +243,82 @@ export class Debris extends Group {}}-/**- * UE 5.8's Local Fog Volume as a participating medium, its density as UE voxelizes it into volumetric fog- * (VolumetricFog.usf, the path Lumen scenes light it through), line for line. In the unit sphere (radius 1; the node's- * scale is the diameter): a radial part `RadialFogExtinction x saturate(1 - d)^0.82`, a height part- * `HeightFogExtinction x exp(-HeightFogFalloff x (z - HeightFogOffset))`, combined as coverages: with A = e^-height and- * B = e^-radial, extinction = -log(A + B - A B) per metre. So fog needs both parts (no height part, no fog), and a- * steep falloff cuts the sphere off above the offset. Lit by every light, it shadows and scatters (path traced; not only- * on camera rays like the scene's height fog).- */+// A local fog volume's density. With u the point in the volume's unit sphere (u = 2 `i.lp`: radius 1, y up; the node's+// scale is the diameter in metres):+// - the radial part, Radial (1 - |u|^2): the extinction at the centre, fading to nothing at the sphere's surface;+// - the height part, Height exp(-Falloff (u.y - Offset)): the extinction at the height Offset, falling off upward;+// - the fog is where both are: extinction = radial (1 - exp(-height / radial)). That follows the thinner of the two+// smoothly (the height part where it is thin, the radial part where the height part is dense) and is never denser+// than either.+// Own design. The settings and what each means are those of Unreal's Local Fog Volume, per its documentation page+// "Local Fog Volumes"; that page gives the two parts' combination in words only ("coverage = 1 - transmittance" of+// both), for a renderer that integrates each part along a view ray. A path tracer needs a density at a point: this.+// `fogVolumeExtinction` below is the same formula in TypeScript, ue5/scripts/ue_volumes.py has it in HLSL.const LOCAL_FOG = new VolumeFunction("local_fog", {params: { Radial: 1, Height: 1, Falloff: 1000, Offset: 0, Albedo: [1, 1, 1, 0], Emissive: [0, 0, 0, 0] },code: `let u = i.lp * 2.0;- let fade = clamp(1.0 - length(u), 0.0, 1.0);- var ext = 0.0;- if (fade > 0.0) {- let height = select(0.0, $Height * exp(min(-$Falloff * (u.y - $Offset), 80.0)), $Height > 0.0);- let a = exp(-height);- let b = exp(-$Radial * pow(fade, 0.82));- ext = max(-log(max(a - a * b + b, 1e-30)), 0.0);- }- o.extinction = ext;+ let radial = max($Radial, 0.0) * max(1.0 - dot(u, u), 0.0);+ let height = max($Height, 0.0) * exp(clamp(-$Falloff * (u.y - $Offset), -40.0, 40.0));+ let x = min(height / max(radial, 1e-9), 40.0);+ // (1 - exp(-x), by its series where x is small: the difference would lose its digits there.)+ o.extinction = radial * select(1.0 - exp(-x), x * (1.0 - x * (0.5 - x / 6.0)), x < 0.02);o.albedo = $Albedo.rgb;- o.emission = $Emissive.rgb * ext;`,+ o.emission = $Emissive.rgb * o.extinction;`,});-/** UE 5.8's Local Fog Volume settings, same names and defaults. */+/** A local fog volume's settings. */export interface FogVolumeOptions {- /** RadialFogExtinction, 1/m. */+ /** Extinction of the part that fades towards the sphere's edge, 1/m: its value at the centre. */radialExtinction?: number;- /** HeightFogExtinction, 1/m. */+ /** Extinction of the part that fades with height, 1/m: its value at the height `heightOffset`. */heightExtinction?: number;- /** HeightFogFalloff and HeightFogOffset, in the unit sphere (radius 1). */+ /** How fast the height part falls off with height, and the height it is measured from, in the unit sphere (radius 1). */heightFalloff?: number;heightOffset?: number;- /** FogAlbedo, FogEmissive (emitted radiance per unit extinction, nits), FogPhaseG (Henyey-Greenstein). */+ /** Albedo, emitted radiance per unit extinction (nits), and the phase function's anisotropy (Henyey-Greenstein). */albedo?: [number, number, number];emissive?: [number, number, number];phaseG?: number;}-/** `scene.add(new FogVolume())`, a sphere sized by its scale (the diameter: `scale.set(4, 4, 4)` is UE's scale 2). */+/** What the two parts of a fog volume give together (the volume function's last step): never more than either. */+function fogOfBoth(radial: number, height: number): number {+ const x = Math.min(height / Math.max(radial, 1e-9), 40);+ return radial * (x < 0.02 ? x * (1 - x * (0.5 - x / 6)) : 1 - Math.exp(-x));+}++/**+ * The extinction (1/m) of a `FogVolume` of these settings at `u`, a point of its unit sphere (radius 1, y up; the+ * volume's local position x 2): the volume function's formula, for tests and for games that ask how thick the fog is+ * somewhere.+ */+export function fogVolumeExtinction(o: FogVolumeOptions, u: readonly [number, number, number]): number {+ const radial = Math.max(o.radialExtinction ?? 1, 0) * Math.max(1 - (u[0] * u[0] + u[1] * u[1] + u[2] * u[2]), 0);+ const height = Math.max(o.heightExtinction ?? 1, 0) * Math.exp(Math.max(-40, Math.min(40, -(o.heightFalloff ?? 1000) * (u[1] - (o.heightOffset ?? 0)))));+ return fogOfBoth(radial, height);+}++/** `scene.add(new FogVolume())`, a sphere sized by its scale (the diameter). */export class FogVolume extends VolumeMesh {constructor(o: FogVolumeOptions = {}) {- const radial = o.radialExtinction ?? 1;+ const radial = Math.max(o.radialExtinction ?? 1, 0), falloff = o.heightFalloff ?? 1000, offset = o.heightOffset ?? 0;+ // The densest the fog gets: the two parts' combination grows with each, so it is at most what their largest+ // values give together: the radial part's at the centre, the height part's at the sphere's bottom (its top with+ // a negative falloff), -falloff (u.y - offset) being at most |falloff| + falloff offset for u.y in -1 .. 1.+ const height = Math.max(o.heightExtinction ?? 1, 0) * Math.exp(Math.max(-40, Math.min(40, Math.abs(falloff) + falloff * offset)));super({shape: "sphere",volume: LOCAL_FOG.with({Radial: radial,Height: o.heightExtinction ?? 1,- Falloff: o.heightFalloff ?? 1000,- Offset: o.heightOffset ?? 0,+ Falloff: falloff,+ Offset: offset,Albedo: [...(o.albedo ?? [1, 1, 1]), 0],Emissive: [...(o.emissive ?? [0, 0, 0]), 0],}),- // The combined extinction never exceeds the radial part: -log(A + B - A B) <= -log(B).- majorant: Math.max(radial, 1e-4),+ // (A hair over, for the shader's single precision.)+ majorant: Math.max(fogOfBoth(radial, height) * 1.0001, 1e-4),anisotropy: o.phaseG ?? 0.2,});this.name = "fog-volume";diff --git a/packages/scene/src/materials.ts b/packages/scene/src/materials.tsindex ee85d3c..b87a7e1 100644--- a/packages/scene/src/materials.ts+++ b/packages/scene/src/materials.ts@@ -1,7 +1,8 @@// Standard material library: Three-like constructors for the materials scenes keep needing (wet ground with puddles and// rain ripples, neon signs, facades with lit windows, LED screens, painted metal, ...), so an agent fills in parameters// instead of writing shading code. Each is a MaterialFunction (docs/MATERIAL_FUNCTIONS.md) taken from the master-// materials of a UE 5.8 night-street level (Custom HLSL, written against UE space via ue_pos / ue_vec, cm); the+// materials of this project's own night-street level in Unreal (Custom HLSL that we wrote there, against UE space via+// ue_pos / ue_vec, cm); the// constructors take metres and three.js names (`map`, `roughnessMap`, `normalMap`, `color`, `roughness` as the map's// multiplier) and convert. Colours: linear triples or sRGB hex, like `Color`. Parameters are read when a material is// made; `set({...})` changes them later.diff --git a/packages/scene/test/effects.test.ts b/packages/scene/test/effects.test.tsindex d65c7fb..57ad16f 100644--- a/packages/scene/test/effects.test.ts+++ b/packages/scene/test/effects.test.ts@@ -49,3 +49,50 @@ test("windSway: the plant becomes movable, its sway reaches the engine once andassert.ok(Math.abs(sum / 10000 - 0.6 * 0.2) < 2e-3, `mean lean ${sum / 10000}`);assert.ok(Math.abs(windAngle(s, 0.7, 0.3) - windAngle(s, 0.7 + 10 * period, 0.3)) < 1e-9, "periodic");});++test("FogVolume: the fog is where its radial and height parts both are, never denser than either; the majorant bounds it", async () => {+ const { FogVolume, fogVolumeExtinction } = await import("../src/index.ts");+ // The defaults (those of the settings' documentation): radial 1, height 1, falloff 1000, offset 0, white, g 0.2.+ const fog = new FogVolume();+ assert.equal(fog.shape, "sphere");+ assert.equal(fog.anisotropy, 0.2);+ assert.deepEqual(fog.volume.params, { Radial: 1, Height: 1, Falloff: 1000, Offset: 0, Albedo: [1, 1, 1, 0], Emissive: [0, 0, 0, 0] });+ // A flat cut at the offset: the radial part below it (1 - |u|^2 of the centre's extinction), nothing above.+ assert.ok(Math.abs(fogVolumeExtinction({}, [0, -0.5, 0]) - 0.75) < 1e-9);+ assert.ok(Math.abs(fogVolumeExtinction({}, [0.6, -0.1, 0]) - (1 - 0.37)) < 1e-9);+ assert.ok(fogVolumeExtinction({}, [0, 0.05, 0]) < 1e-12);+ assert.equal(fogVolumeExtinction({}, [0, -1, 0]), 0);+ assert.equal(fogVolumeExtinction({}, [0.8, -0.7, 0.3]), 0, "outside the sphere");+ let s = 11;+ const rnd = () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296);+ for (let k = 0; k < 400; k++) {+ const o = { radialExtinction: 4 * rnd(), heightExtinction: 3 * rnd(), heightFalloff: k % 7 === 0 ? 1000 : 12 * rnd() - 4, heightOffset: 2 * rnd() - 1 };+ const majorant = new FogVolume(o).majorant;+ assert.ok(majorant > 0 && Number.isFinite(majorant));+ let densest = 0;+ for (let j = 0; j < 300; j++) {+ const u: [number, number, number] = [2 * rnd() - 1, 2 * rnd() - 1, 2 * rnd() - 1];+ const r2 = u[0] * u[0] + u[1] * u[1] + u[2] * u[2];+ const e = fogVolumeExtinction(o, u);+ const radial = o.radialExtinction * Math.max(1 - r2, 0), height = o.heightExtinction * Math.exp(-o.heightFalloff * (u[1] - o.heightOffset));+ assert.ok(e >= 0 && e <= radial + 1e-12 && e <= height * (1 + 1e-9) + 1e-12, `${JSON.stringify(o)} at ${u}: ${e} against ${radial}, ${height}`);+ assert.ok(e <= majorant, `${JSON.stringify(o)} at ${u}: ${e} over the majorant ${majorant}`);+ densest = Math.max(densest, e);+ // Thicker parts, thicker fog.+ const least = e * (1 - 1e-12);+ assert.ok(fogVolumeExtinction({ ...o, radialExtinction: o.radialExtinction * 1.5 }, u) >= least && fogVolumeExtinction({ ...o, heightExtinction: o.heightExtinction * 1.5 }, u) >= least);+ }+ // The bottom of the sphere's axis is where the height part is densest (the top with a negative falloff): the+ // majorant is what the centre's radial part and that give, so no point comes over it, and it is no looser than+ // the radial part alone.+ assert.ok(majorant <= Math.max(o.radialExtinction * 1.0001, 1e-4) + 1e-12);+ }+ // No radial part or no height part: no fog (the smallest majorant a volume may have).+ assert.equal(fogVolumeExtinction({ radialExtinction: 0 }, [0, -0.2, 0]), 0);+ assert.equal(fogVolumeExtinction({ heightExtinction: 0 }, [0, -0.2, 0]), 0);+ assert.equal(new FogVolume({ radialExtinction: 0 }).majorant, 1e-4);+ // A gentle falloff: a pool that thins upward, the height part where it is the thinner one.+ const pool = { radialExtinction: 5, heightExtinction: 0.01, heightFalloff: 2, heightOffset: 0 };+ assert.ok(Math.abs(fogVolumeExtinction(pool, [0, 0.3, 0]) / (0.01 * Math.exp(-0.6)) - 1) < 2e-3);+ assert.ok(fogVolumeExtinction(pool, [0, -0.3, 0]) > fogVolumeExtinction(pool, [0, 0.3, 0]));+});diff --git a/presets/cinematic.json b/presets/cinematic.jsonindex 6bb7f10..4fd1e1d 100644--- a/presets/cinematic.json+++ b/presets/cinematic.json@@ -1,6 +1,6 @@{"name": "cinematic",- "description": "Offline-quality stills: full GI, ray traced reflections/shadows, UE5 filmic post. Default for agent screenshots.",+ "description": "Offline-quality stills: full GI, ray traced reflections/shadows, filmic post (bloom, vignette, ACES-structured tone curve: docs/RUNTIME.md \"The post chain\"). Default for agent screenshots.","intent": {"gi": {"method": "full",@@ -18,6 +18,7 @@},"post": {"tonemapper": {+ "_note": "Unreal's Film settings of the look this preset is compared with (ue5/scripts send them to Unreal). The renderer's tone curve (post.rs ToneCurve) is fitted to that look and reads none of them.","type": "ue-filmic","slope": 0.88,"toe": 0.55,@@ -70,7 +71,7 @@"clampIndirect": 64.0,"russianRouletteDepth": 3,"energyCompensation": 0.0,- "_energyCompensationNote": "0 = UE 5.8 DefaultLit parity (measured vs UE path tracer); 1 = energy-conserving GGX (passes white furnace)"+ "_energyCompensationNote": "how much of the specular lobe's multiple-scattering compensation (Turquin 2019: lobe x (1 + f0 (1 - E) / E)): 0 = the single-scattering GGX lobe, what real-time engines render by default (measured equal to UE 5.8 DefaultLit in UE's path tracer); 1 = energy conserving (passes the white furnace test)"},"ue": {"method": "lumen",diff --git a/presets/preview.json b/presets/preview.jsonindex 96e01f0..e2302bc 100644--- a/presets/preview.json+++ b/presets/preview.json@@ -18,6 +18,7 @@},"post": {"tonemapper": {+ "_note": "Unreal's Film settings of the look this preset is compared with (ue5/scripts send them to Unreal). The renderer's tone curve (post.rs ToneCurve) is fitted to that look and reads none of them.","type": "ue-filmic","slope": 0.88,"toe": 0.55,@@ -70,7 +71,7 @@"clampIndirect": 16.0,"russianRouletteDepth": 2,"energyCompensation": 0.0,- "_energyCompensationNote": "0 = UE 5.8 DefaultLit parity (measured vs UE path tracer); 1 = energy-conserving GGX (passes white furnace)"+ "_energyCompensationNote": "how much of the specular lobe's multiple-scattering compensation (Turquin 2019: lobe x (1 + f0 (1 - E) / E)): 0 = the single-scattering GGX lobe, what real-time engines render by default (measured equal to UE 5.8 DefaultLit in UE's path tracer); 1 = energy conserving (passes the white furnace test)"},"ue": {"method": "lumen",diff --git a/renderer/examples/post_check.rs b/renderer/examples/post_check.rsnew file mode 100644index 0000000..82270f3--- /dev/null+++ b/renderer/examples/post_check.rs@@ -0,0 +1,215 @@+//! Acceptance check of the post chain (src/post.rs) against measured reference data:+//!+//! cargo run --release --example post_check -- <dir> [--preset presets/cinematic.json] [--override JSON]+//! [--out DIR (the chain's pictures of the pairs)] [--json out.json]+//!+//! `<dir>` holds any of (what is absent is skipped; the data is not part of the repository):+//! - `tonemap-default.csv`: colours through colour grading and the tone curve at the preset's settings, rows+//! `in_r,in_g,in_b,out_r,out_g,out_b` (exposed linear sRGB in, display-linear sRGB out), the first 257 a neutral+//! ramp. Reported: the ramp's largest difference in sRGB-encoded value for inputs 1e-3 .. 16, and CIE dE2000 over+//! all rows (mean, 99th percentile, largest).+//! - `grade-<setting>-<value>.csv`: the same with one grading setting changed (`whiteTemp-3000`, `whiteTint-m0.5`,+//! `saturation-1.5`, `contrast-0.8`, `shadowsGain-0.7`, `highlightsGain-1.3`, `shadowsGain-rgb` = 1.2, 1, 0.8).+//! - `pairs/<scene>.hdr.f32` (width x height x 3 little-endian f32, scene-linear nits, rows from the top),+//! `<scene>.png` (the picture it is to become) and `<scene>.stats.json` (`width`, `height`, `ev100`): `post::finish`+//! of the first against the second, dE2000 mean and 99th percentile per scene.+//!+//!+//! cargo run --release --example post_check -- --pictures a.png b.png+//!+//! compares two finished pictures instead (dE2000 mean, 99th percentile, largest; tools/post-live.ts).+//!+//! Exit status 1 if a target is missed (the constants below).++use glam::Vec3;+use std::path::{Path, PathBuf};+use threert_render::desc::{Preset, Rgb};+use threert_render::post;++/// Targets: neutral ramp (sRGB-encoded), colours (dE2000 mean, 99th percentile), each grading table (mean), each+/// pair (mean, 99th percentile).+const RAMP: f32 = 0.004;+const COLOURS: (f32, f32) = (1.0, 4.0);+const GRADE: f32 = 2.0;+const PAIR: (f32, f32) = (1.0, 3.0);++/// CIE 1976 L*a*b* of a display-linear sRGB colour (D65 white; IEC 61966-2-1 primaries, CIE 15).+fn lab(c: Vec3) -> [f32; 3] {+ let c = c.clamp(Vec3::ZERO, Vec3::ONE);+ let xyz = [0.4123908 * c.x + 0.3575843 * c.y + 0.1804808 * c.z, 0.2126390 * c.x + 0.7151687 * c.y + 0.0721923 * c.z, 0.0193308 * c.x + 0.1191948 * c.y + 0.9505322 * c.z];+ let white = [0.9504559, 1.0, 1.0890578];+ let f = |t: f32| if t > (6.0f32 / 29.0).powi(3) { t.cbrt() } else { t / (3.0 * (6.0f32 / 29.0).powi(2)) + 4.0 / 29.0 };+ let (fx, fy, fz) = (f(xyz[0] / white[0]), f(xyz[1] / white[1]), f(xyz[2] / white[2]));+ [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]+}++/// CIE dE2000 (CIE 142-2001; Sharma, Wu & Dalal 2005, "The CIEDE2000 Color-Difference Formula: Implementation Notes,+/// Supplementary Test Data, and Mathematical Observations", Color Research & Application 30).+fn de2000(l1: [f32; 3], l2: [f32; 3]) -> f32 {+ let (c1, c2) = ((l1[1] * l1[1] + l1[2] * l1[2]).sqrt(), (l2[1] * l2[1] + l2[2] * l2[2]).sqrt());+ let cb = (c1 + c2) / 2.0;+ let g = 0.5 * (1.0 - (cb.powi(7) / (cb.powi(7) + 25f32.powi(7))).sqrt());+ let (a1, a2) = ((1.0 + g) * l1[1], (1.0 + g) * l2[1]);+ let (c1p, c2p) = ((a1 * a1 + l1[2] * l1[2]).sqrt(), (a2 * a2 + l2[2] * l2[2]).sqrt());+ let hue = |b: f32, a: f32| if a == 0.0 && b == 0.0 { 0.0 } else { b.atan2(a).to_degrees().rem_euclid(360.0) };+ let (h1, h2) = (hue(l1[2], a1), hue(l2[2], a2));+ let (dl, dc) = (l2[0] - l1[0], c2p - c1p);+ let mut dh = h2 - h1;+ if c1p * c2p == 0.0 {+ dh = 0.0;+ } else if dh > 180.0 {+ dh -= 360.0;+ } else if dh < -180.0 {+ dh += 360.0;+ }+ let dhp = 2.0 * (c1p * c2p).sqrt() * (dh.to_radians() / 2.0).sin();+ let (lb, cbp) = ((l1[0] + l2[0]) / 2.0, (c1p + c2p) / 2.0);+ let hs = h1 + h2;+ let hb = if c1p * c2p == 0.0 {+ hs+ } else if (h1 - h2).abs() > 180.0 {+ if hs < 360.0 { (hs + 360.0) / 2.0 } else { (hs - 360.0) / 2.0 }+ } else {+ hs / 2.0+ };+ let t = 1.0 - 0.17 * (hb - 30.0).to_radians().cos() + 0.24 * (2.0 * hb).to_radians().cos() + 0.32 * (3.0 * hb + 6.0).to_radians().cos() - 0.20 * (4.0 * hb - 63.0).to_radians().cos();+ let dth = 30.0 * (-((hb - 275.0) / 25.0).powi(2)).exp();+ let rc = 2.0 * (cbp.powi(7) / (cbp.powi(7) + 25f32.powi(7))).sqrt();+ let sl = 1.0 + 0.015 * (lb - 50.0).powi(2) / (20.0 + (lb - 50.0).powi(2)).sqrt();+ let (sc, sh) = (1.0 + 0.045 * cbp, 1.0 + 0.015 * cbp * t);+ let rt = -(2.0 * dth).to_radians().sin() * rc;+ ((dl / sl).powi(2) + (dc / sc).powi(2) + (dhp / sh).powi(2) + rt * (dc / sc) * (dhp / sh)).max(0.0).sqrt()+}++fn srgb_decode(v: f32) -> f32 {+ if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }+}++/// Mean, 99th percentile and largest of a set of differences.+fn stats(mut d: Vec<f32>) -> (f32, f32, f32) {+ d.sort_by(|a, b| a.total_cmp(b));+ let mean = d.iter().sum::<f32>() / d.len().max(1) as f32;+ (mean, d[((d.len() as f32 * 0.99) as usize).min(d.len() - 1)], *d.last().unwrap())+}++fn table(path: &Path) -> anyhow::Result<Vec<[f32; 6]>> {+ let mut rows = vec![];+ for line in std::fs::read_to_string(path)?.lines().skip(1) {+ let v: Vec<f32> = line.split(',').map(|x| x.trim().parse::<f32>()).collect::<Result<_, _>>()?;+ anyhow::ensure!(v.len() == 6, "{}: a row of {} numbers", path.display(), v.len());+ rows.push([v[0], v[1], v[2], v[3], v[4], v[5]]);+ }+ Ok(rows)+}++/// The grading a table's name asks for, on `p`.+fn grading(name: &str, p: &mut threert_render::desc::PostPreset) -> anyhow::Result<()> {+ let (setting, value) = name.rsplit_once('-').ok_or_else(|| anyhow::anyhow!("{name}: no value"))?;+ let g = &mut p.color_grading;+ let rgb = if value == "rgb" { Rgb([1.2, 1.0, 0.8]) } else { Rgb([value.replace('m', "-").replace('p', "").parse()?; 3]) };+ match setting {+ "whiteTemp" => g.white_temp = rgb.0[0],+ "whiteTint" => g.white_tint = rgb.0[0],+ "saturation" => g.saturation = rgb,+ "contrast" => g.contrast = rgb,+ "shadowsGain" => g.shadows_gain = rgb,+ "highlightsGain" => g.highlights_gain = rgb,+ _ => anyhow::bail!("{name}: a setting this check does not know"),+ }+ Ok(())+}++fn main() -> anyhow::Result<()> {+ let args: Vec<String> = std::env::args().skip(1).collect();+ if args.first().map(String::as_str) == Some("--pictures") {+ anyhow::ensure!(args.len() == 3, "post_check --pictures a.png b.png");+ let (a, b) = (image::open(&args[1])?.to_rgb8(), image::open(&args[2])?.to_rgb8());+ anyhow::ensure!(a.dimensions() == b.dimensions(), "{} and {} differ in size", args[1], args[2]);+ let dec = |v: &[u8]| lab(Vec3::new(srgb_decode(v[0] as f32 / 255.0), srgb_decode(v[1] as f32 / 255.0), srgb_decode(v[2] as f32 / 255.0)));+ let (mean, p99, max) = stats(a.as_raw().chunks_exact(3).zip(b.as_raw().chunks_exact(3)).map(|(x, y)| de2000(dec(x), dec(y))).collect());+ println!("{}", serde_json::json!({ "mean": mean, "p99": p99, "max": max }));+ return Ok(());+ }+ let flag = |k: &str| args.iter().position(|a| a == k).and_then(|i| args.get(i + 1).cloned());+ let dir = PathBuf::from(args.first().filter(|a| !a.starts_with("--")).ok_or_else(|| anyhow::anyhow!("post_check <dir> [--preset file] [--json out.json]"))?);+ let preset_path = flag("--preset").map(PathBuf::from).unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../presets/cinematic.json"));+ // (`--override`: JSON merged over the preset, as a scene's `overrides` are.)+ let mut preset_json: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&preset_path)?)?;+ if let Some(o) = flag("--override") {+ threert_render::desc::merge_json(&mut preset_json, &serde_json::from_str(&o)?);+ }+ let preset: Preset = serde_json::from_value(preset_json)?;+ let mut report = serde_json::Map::new();+ let mut missed = vec![];++ // Colour grading and the tone curve.+ let default = dir.join("tonemap-default.csv");+ if default.exists() {+ let rows = table(&default)?;+ let tm = post::Tonemapper::new(&preset.post);+ let mut ramp = 0f32;+ for r in rows.iter().take(257).filter(|r| r[0] == r[1] && r[1] == r[2] && r[0] >= 1e-3 && r[0] <= 16.0) {+ let d = tm.apply(Vec3::new(r[0], r[1], r[2]));+ for k in 0..3 {+ ramp = ramp.max((post::linear_to_srgb(d[k].clamp(0.0, 1.0)) - post::linear_to_srgb(r[3 + k].clamp(0.0, 1.0))).abs());+ }+ }+ let (mean, p99, max) = stats(rows.iter().map(|r| de2000(lab(tm.apply(Vec3::new(r[0], r[1], r[2]))), lab(Vec3::new(r[3], r[4], r[5])))).collect());+ println!("tone curve + grading, {} colours: neutral ramp max |d| {ramp:.5} (target {RAMP}); dE2000 mean {mean:.3} (target {}), p99 {p99:.2} (target {}), max {max:.2}", rows.len(), COLOURS.0, COLOURS.1);+ report.insert("tonemap-default".into(), serde_json::json!({ "ramp": ramp, "mean": mean, "p99": p99, "max": max }));+ if ramp > RAMP || mean > COLOURS.0 || p99 > COLOURS.1 {+ missed.push("tonemap-default".to_string());+ }+ }+ let mut grades: Vec<PathBuf> = std::fs::read_dir(&dir)?.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("grade-") && n.ends_with(".csv"))).collect();+ grades.sort();+ for path in grades {+ let name = path.file_stem().unwrap().to_str().unwrap().trim_start_matches("grade-").to_string();+ let mut p = preset.post.clone();+ grading(&name, &mut p)?;+ let tm = post::Tonemapper::new(&p);+ let (mean, p99, max) = stats(table(&path)?.iter().map(|r| de2000(lab(tm.apply(Vec3::new(r[0], r[1], r[2]))), lab(Vec3::new(r[3], r[4], r[5])))).collect());+ println!("grade {name:20} dE2000 mean {mean:.3} (target {GRADE}), p99 {p99:.2}, max {max:.2}");+ report.insert(format!("grade-{name}"), serde_json::json!({ "mean": mean, "p99": p99, "max": max }));+ if mean > GRADE {+ missed.push(format!("grade-{name}"));+ }+ }++ // The whole chain on the reference pairs.+ let pairs = dir.join("pairs");+ if pairs.is_dir() {+ let mut scenes: Vec<String> = std::fs::read_dir(&pairs)?.filter_map(|e| e.ok()).filter_map(|e| e.file_name().to_str().and_then(|n| n.strip_suffix(".hdr.f32").map(String::from))).collect();+ scenes.sort();+ for scene in scenes {+ let stats_json: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(pairs.join(format!("{scene}.stats.json")))?)?;+ let n = |k: &str| stats_json[k].as_f64().ok_or_else(|| anyhow::anyhow!("{scene}.stats.json: no `{k}`"));+ let (w, h, ev100) = (n("width")? as usize, n("height")? as usize, n("ev100")? as f32);+ let raw = std::fs::read(pairs.join(format!("{scene}.hdr.f32")))?;+ anyhow::ensure!(raw.len() == w * h * 12, "{scene}.hdr.f32: {} bytes for {w} x {h}", raw.len());+ let px: Vec<Vec3> = raw.chunks_exact(12).map(|c| Vec3::new(f32::from_le_bytes(c[0..4].try_into().unwrap()), f32::from_le_bytes(c[4..8].try_into().unwrap()), f32::from_le_bytes(c[8..12].try_into().unwrap()))).collect();+ let want = image::open(pairs.join(format!("{scene}.png")))?.to_rgb8();+ anyhow::ensure!(want.width() as usize == w && want.height() as usize == h, "{scene}.png is not {w} x {h}");+ let got = post::finish(&post::Image { w, h, px }, 2f32.powf(-ev100), 1.0, &preset.post);+ if let Some(out) = flag("--out") {+ std::fs::create_dir_all(&out)?;+ image::save_buffer(Path::new(&out).join(format!("{scene}.png")), &got, w as u32, h as u32, image::ExtendedColorType::Rgba8)?;+ }+ let dec = |v: &[u8]| lab(Vec3::new(srgb_decode(v[0] as f32 / 255.0), srgb_decode(v[1] as f32 / 255.0), srgb_decode(v[2] as f32 / 255.0)));+ let (mean, p99, max) = stats(got.chunks_exact(4).zip(want.as_raw().chunks_exact(3)).map(|(a, b)| de2000(dec(a), dec(b))).collect());+ println!("pair {scene:18} EV100 {ev100:5.1}: dE2000 mean {mean:.3} (target {}), p99 {p99:.2} (target {}), max {max:.2}", PAIR.0, PAIR.1);+ report.insert(format!("pair-{scene}"), serde_json::json!({ "mean": mean, "p99": p99, "max": max }));+ if mean > PAIR.0 || p99 > PAIR.1 {+ missed.push(format!("pair-{scene}"));+ }+ }+ }+ if let Some(out) = flag("--json") {+ std::fs::write(out, serde_json::to_string_pretty(&report)?)?;+ }+ if !missed.is_empty() {+ println!("missed: {}", missed.join(", "));+ std::process::exit(1);+ }+ Ok(())+}diff --git a/renderer/shaders/live.wgsl b/renderer/shaders/live.wgslindex d985ad8..7758dec 100644--- a/renderer/shaders/live.wgsl+++ b/renderer/shaders/live.wgsl@@ -8,27 +8,30 @@// judge, reject - what of the output-grid colour history this frame's samples contradict// upscale - the composed frame, by its sub-pixel jitter, into the output grid's one colour history// dof*, mblur - depth of field and motion blur on the output grid-// bloom_* - UE Standard bloom: six Gaussian stages on a 1/4 .. 1/64 downsample chain, summed from the widest up-// post - exposure, bloom, UE cos^4 vignette, UE filmic tonemap via a log-encoded 3D LUT, BGRA8 output+// lum_down, exposure - quarter-resolution luminance: auto exposure's histogram, local exposure's layers, bloom's source+// bloom_* - bloom: a sum of Gaussians on a 1/4 .. 1/128 pyramid, the widest summed directly on its top+// post - exposure, local exposure, bloom, vignette, grading and tone curve (a 3D table), grain, BGRA8 output+// (The post chain is post.rs's, pass for pass: what each step is and where it comes from is said there.)struct Cam { pos: vec4<f32>, fwd: vec4<f32>, right: vec4<f32>, up: vec4<f32> }; // pos.w = tan(fov/2), fwd.w = aspectstruct LiveParams {cur: Cam,prev: Cam,size: vec4<u32>, // width, height, frame, reset history (1)- misc: vec4<f32>, // exposure scale, max history, vignette intensity, bloom on (1) / off (0)- misc2: vec4<f32>, // denoise strength, sample clamp (display units at the current exposure), -, samples this frame+ misc: vec4<f32>, // exposure scale, max history, vignette, the bloom pyramid is needed (1) / not (0)+ misc2: vec4<f32>, // denoise strength, sample clamp (display units at the current exposure), motion blur's length over this frame's motion (0 = none), samples this framemode: vec4<u32>, // view mode (0 lit, 1 base color, 2 world normal, 3 lit no denoise, 4 raw sample, 5 history), display whites a unit of a reconstruction provider's input is (reconstruction.wgsl `rc_radiance_unit`), the scene's lighting is changing (live/mod.rs `live_lighting`), -- post: vec4<f32>, // chromatic aberration (UE scene fringe), film grain, bloom threshold (<= 0 off), -- ae: vec4<f32>, // auto exposure: low / high fraction, histogram log2 min / max+ post: vec4<f32>, // chromatic aberration, film grain, bloom threshold (exposed luminance; < 0: everything blooms), longest motion blur (output pixels)+ ae: vec4<f32>, // auto exposure: low / high fraction of the histogram, its log2 luminance min / maxae2: vec4<f32>, // compensation (2^bias; manual: the exposure), min / max average luminance, mode (1 = auto)- ae3: vec4<f32>, // speed up / down (EV/s), frame time (s), snap to target+ ae3: vec4<f32>, // speed toward brighter / darker scenes (EV/s), frame time (s), snap to targetlx: vec4<f32>, // local exposure: highlight contrast, shadow contrast, blurred-luminance blend, detail strengthisz: vec4<u32>, // traced (internal) width, height (= size.xy at 100% render scale); the previous frame's (0 = none)- br: vec4<f32>, // bloom stage 0..3 Gaussian radius, texels of the stage's level- br2: vec4<f32>, // bloom stage 4, 5 radius, -, -- bt: vec4<f32>, // bloom stage 0..3 tint (BloomN Tint * intensity / 6)- bt2: vec4<f32>, // bloom stage 4, 5 tint, -, -+ bl: vec4<f32>, // bloom (post.rs `BloomPlan`): weight of pyramid level 0..3+ bl2: vec4<f32>, // of level 4, 5; the wide pass's reach (texels of the coarsest level; 0 = nothing to sum); weight of the output's own five-pixel kernel+ bw: array<vec4<f32>, 3>, // the wide Gaussians 0..5: a (weight, 1 / (2 sigma^2)) pair each (sigma in texels of the coarsest level)+ lb: vec4<f32>, // local exposure's wide blur of log luminance: weight of level 0..3+ lb2: vec4<f32>, // of level 4, 5; its wide Gaussian's weight, 1 / (2 sigma^2)dof: vec4<f32>, // depth of field: CoC radius of infinity (output px; 0 = off), focus distance (m), max radius (px), -jit: vec4<f32>, // this frame's sub-pixel jitter (every traced sample's: x, y in 0 .. 1 of a traced pixel), -, -state: vec4<u32>, // which half of the lasting buffers is this frame's (0 / 1; `this_half`), -, -, -@@ -50,8 +53,12 @@ struct LiveParams {// (`this_half`), and the previous frame's, which they read (`last_half`); live/frame.rs alternates them (`L.state.x`). A half// is L.size.x * L.size.y elements, indexed by traced sample (by output pixel: `color_hist`).// diffuse_hist the diffuse irradiance's history: rgb, frames (`dtemporal`; the à-trous passes read its length)-// diffuse_mom its luminance moments: mean, mean square, the fast mean's luminance, 1 where written (`dtemporal`)-// diffuse_fast its fast mean in colour, f16 rgb (`dtemporal`; `fast_load`: ReBLUR's fast history)+// diffuse_mom its luminance moments: mean, mean square, -, 1 where written (`dtemporal`); z: within the frame+// the diffuse history's drift factor (`dtemporal`), then the specular history's change chart+// (`stemporal` reads the one and writes the other into the half `dtemporal` has written: `spec_chart`)+// diffuse_fast the diffuse history's change chart and drift ("The response of the histories"), eight bits each:+// x the level of the samples' share against the history (rgb) and the drift, y the pooled residual+// average (rgb) and the root of its mean square (`dtemporal`)// spec_hist the specular history: rgb, frames (`stemporal`)// gbuffer octahedral normal, view depth (0 = sky), roughness (`stemporal`; `GB`); once the temporal passes// have read the previous half, `lock_carry` puts its locks' depths into it (`judge` reads it)@@ -72,6 +79,9 @@ struct LiveParams {// then in slot 0 `reject`'s verdict// lumq depth of field's tiles (`dof_tiles`, `dof`), then the quarter-resolution log2 luminance// (`lum_down`, `lum_blur`)+// bloom_a the bloom pyramid: its levels one after another (`bloom_at`), each the picture's until its `bloom_up`+// makes it the sum from there down; then the coarsest eight times more: `bloom_wide`'s sum and+// `bloom_wide_rows`' row blurs// lock_fwd per traced sample: the previous frame's lock that lands on it (`lock_carry` writes, `track` reads// and clears it for the next frame)@group(0) @binding(2) var<storage, read_write> diffuse_hist: array<vec4<f32>>;@@ -85,14 +95,13 @@ struct LiveParams {@group(0) @binding(10) var<storage, read_write> out_px: array<u32>;@group(0) @binding(11) var lut: texture_3d<f32>;@group(0) @binding(12) var lut_samp: sampler;-@group(0) @binding(13) var<storage, read_write> ae_bins: array<atomic<u32>, 64>; // fixed point (x 256)+@group(0) @binding(13) var<storage, read_write> ae_bins: array<atomic<u32>, 128>; // the luminance histogram: 64 counts, then 64 sums (`lum_down`)@group(0) @binding(14) var<storage, read_write> ae_state: array<vec4<f32>, 2>; // exposure, target, mean log2 lum, valid@group(0) @binding(15) var<storage, read_write> lumq: array<f32>; // quarter res log2 luminance (unexposed)@group(0) @binding(16) var<storage, read_write> lumb: array<f32>; // edge-aware blur of lumq@group(0) @binding(17) var<storage, read_write> fa: array<vec4<f32>>;@group(0) @binding(18) var<storage, read_write> fb: array<vec4<f32>>;-@group(0) @binding(19) var<storage, read_write> bloom_a: array<vec4<f32>>; // bloom pyramid levels, then stage sums-@group(0) @binding(20) var<storage, read_write> bloom_b: array<vec4<f32>>; // horizontal blur scratch+@group(0) @binding(19) var<storage, read_write> bloom_a: array<vec4<f32>>; // rgb bloom, w log2 luminance@group(0) @binding(21) var<storage, read_write> spec_pp: array<vec2<u32>>;@group(0) @binding(22) var<storage, read_write> sb: array<vec4<f32>>;// What the trace leaves (the kernel's group 1, live/targets.rs `Targets::kernel`). Reflection resolve: the specular-lobe rays,@@ -146,7 +155,8 @@ fn finite_or_zero(v: vec3<f32>) -> vec3<f32> {return select(v, vec3<f32>(0.0), non_finite(v));}-// YCoCg (UE LumenRGBToYCoCg): neighbourhood clamps in a luma / chroma space.+// YCoCg (Malvar & Sullivan 2003, "YCoCg-R: A Color Space with RGB Reversibility and Low Dynamic Range", the lossy form):+// neighbourhood statistics in a luma / chroma space.fn ycocg(c: vec3<f32>) -> vec3<f32> {return vec3<f32>(0.25 * c.r + 0.5 * c.g + 0.25 * c.b, 0.5 * c.r - 0.5 * c.b, -0.25 * c.r + 0.5 * c.g - 0.25 * c.b);}@@ -191,14 +201,16 @@ const NEAR_MIRROR: f32 = 0.2;// ------------------------------------------------------------------------------------------------ reflection resolve+// The specular lobe's distribution and visibility terms, as pathtrace.wgsl has them (`d_ggx`,+// `vis_smith_joint_approx`: GGX of Walter et al. 2007; the height-correlated Smith visibility of Heitz 2014 in Hammon's+// square-root-free form, GDC 2017), for the reflection resolve's weights.fn d_ggx(a2: f32, noh: f32) -> f32 {let d = (noh * a2 - noh) * noh + 1.0;return a2 / (3.14159265 * d * d);}fn vis_smith(a2: f32, nov: f32, nol: f32) -> f32 {- let a = sqrt(a2);- return 0.5 / max(nol * (nov * (1.0 - a) + a) + nov * (nol * (1.0 - a) + a), 1e-7);+ return 0.5 / max(mix(2.0 * nol * nov, nol + nov, sqrt(a2)), 1e-7);}fn oct_dec(u: u32) -> vec3<f32> {@@ -385,13 +397,6 @@ fn medium_share(q: u32) -> f32 {return floor(sample_px[q].normal.w) / 255.0;}-// The diffuse irradiance's fast mean in colour (f16 rgb; a quarter of each new sample, as its luminance in the-// moments), per traced sample (`diffuse_fast`): `dtemporal` reads the previous frame's and writes this frame's.-fn fast_load(j: u32) -> vec3<f32> {- let v = diffuse_fast[last_half(j)];- return vec3<f32>(unpack2x16float(v.x), unpack2x16float(v.y).x);-}-fn sample_color(q: u32) -> vec3<f32> {return (sample_diffuse(q) + sample_specular(q)) * medium_tr(q) + sample_emission(q);}@@ -458,17 +463,187 @@ fn same_surface_n(tx: i32, ty: i32, z: f32, n: vec3<f32>, t: f32, ncos: f32) ->// History length (frames) from which `dtemporal` reprojects the pixel's centre instead of its jittered sample.const HIST_CENTRE: f32 = 16.0;-// The most frames the irradiance history holds where the pixel moves a pixel a frame or more (it is resampled every-// frame, each time a little blurrier), and the relative difference of its fast mean from its slow one, beyond their-// noise, at which anti-lag leaves it two frames (`dtemporal`).-const HIST_MOVING: f32 = 48.0;-const ANTILAG: f32 = 0.15;-// The fast-history clamp's band, in standard errors of the fast means' mean around the pixel (`dtemporal`). At 2 the-// Bistro slice at rest read dE 2.92 for 2.82 (it found noise); at 3, 2.83.-const FAST_BAND: f32 = 3.0;// Diffuse history length from which the firefly cut stops (dtemporal).const FIREFLY_FRAMES: f32 = 16.0;+// ---- The response of the histories: how long a pixel's history may be, and how it follows the lighting.+// (Written 2026-11; docs/RUNTIME.md "The temporal response of the live denoiser". Sources are named where a rule+// rests on one, and only texts that were opened for this work: Schied, Peters and Dachsbacher 2018, "Gradient+// Estimation for Real-Time Adaptive Temporal Filtering"; Karis 2014, "High-Quality Temporal Supersampling",+// SIGGRAPH Advances in Real-Time Rendering course slides; Stachowiak 2015, "Stochastic Screen-Space Reflections",+// same course, slides and notes; the NIST/SEMATECH e-Handbook of Statistical Methods, § 6.3.2.4, "EWMA Control+// Charts". The rest is this project's own.)+//+// Within the frame's bound (`L.misc.y`) a history's length is the pixel's own:+// - In motion. A history that moves over the grid is resampled bilinearly every frame, and each resampling blurs it+// (Karis 2014, slide 47, "reprojection diffusion": reduce the feedback when reprojecting off the pixel). A+// bilinear tap at a fraction f of a pixel is a two-point kernel of variance f (1 - f) pixels^2, so a history n+// frames long has been blurred by about n times that; `moving_frames` bounds n so that the blur stays under a+// variance budget, with f (1 - f) taken at the pixel's speed (its upper envelope beyond half a pixel a frame, so+// the bound does not come and go with the fraction).+// - On animated shading: ANIM_FRAMES.+// - While the scene's lighting changes (`L.mode.z`), by a change chart per pixel, and a drift:+// The renderer cannot re-trace last frame's path with last frame's random numbers, so the temporal gradient of+// Schied et al. 2018 is not to be had; a difference of two independent one-sample estimates carries both their+// variances (their § 3.2). What is to be had is each frame's sample against the pixel's own history. That is the+// setting of a control chart: a stream of noisy readings whose mean may shift, watched by an exponentially+// weighted moving average of the readings, which signals when it leaves a band of k of its own standard+// deviations (NIST e-Handbook § 6.3.2.4, which credits the chart to Roberts 1959).+// - The reading is not the sample but its share against the history, s / (s + h') per channel (`chart_share`): 0+// for a dark sample, about a half for one at the history's level, towards 1 for one far above. A path-traced+// sample is heavy-tailed (most are dark, a few carry the light), and a chart on the samples themselves reads+// every run of dark ones as the light having gone. A share is bounded, so one sample moves the chart by a+// bounded step however bright it is, and the chart counts how many samples changed sides, not by how much.+// - Its residual is taken from the pixel's own running mean of that share (the level: about a half on a steadily+// lit pixel, near 0 on one lit by rare bright samples), so every pixel's residual has mean 0 while its lighting+// holds, whatever its surface, shadow edges or noise are. Residuals of different pixels can then be pooled.+// - Pooled, because one pixel's few frames prove nothing: each frame the average is read from the pixel where+// this one was and four at distance sqrt 5 around it (`chart_tap`), averaged, and this frame's residual added+// with weight CHART_A. That recursion spreads over a few pixels' radius and CHART_A^-1 frames: about 250+// residuals stand behind a pooled value, where one pixel's own average has 15 (the pooled value's deviation,+// measured on white residuals: 0.063 of one residual's, CHART_SD; 0.073 without the pixel's own tap). The+// pooled value is read before this frame's residual is added: the test lags a frame, and is on four times as+// many samples.+// - The band: CHART_K deviations of the pooled value, the residuals' own mean square pooled the same way standing+// in for their variance (a bright sample is in the residual and in the mean square alike), and never less than+// CHART_FLOOR. (K is 3.5 and not the handbook's usual 3: the residuals are not white. A bright sample raises+// the history it is measured against, and the samples after it read low until it has faded.)+// - The response is Schied et al.'s (eq. 15): the blend weight a becomes a + drop (1 - a), `drop` rising from 0 at+// the band to 1 at 1 + CHART_GAIN^-1 bands (`chart_drop`). The history's length is what that weight leaves, so+// the frames after it are plain accumulation from the shorter history. The level starts again with the history+// (its weight is the history's, CHART_LEVEL frames at most), and a history of a frame or two is no level to+// compare with: its residual counts by CHART_MATURE.+// - In colour: the chart is kept per channel, and the largest channel's deviation decides. A red light switched+// off next to a white one moves the red channel's share by far more than the luminance.+// - The drift. A chart whose level follows the history sees a change and then gets used to it: under a light that+// falls a little every frame (a dusk) the shares settle at a lower level, the residuals return to 0, and the+// history trails the light by its whole length for as long as the fall lasts (the model: 2.4 times the light+// after 170 frames of a fall of 2.6 % a frame under a bound of 24 frames; bench-window's tokyo-dusk under 48:+// the city's diffuse light 3.5 times the held frame's). What does not get used to it is the plain relative+// residual (l - h) / h of the luminance: its mean is 0 for a history that is the samples' mean, whatever their+// distribution, and minus the lag for one that trails. It is pooled as the chart's average is, each pixel's+// weighted by 1 / (1 + cv^2), cv its samples' own relative deviation (from the luminance moments; a pixel lit+// by rare bright samples has a large one and counts for little, and its residual is bounded above by+// DRIFT_CLIP besides, which is where a bounded mean of a skewed sample is biased: on such pixels the drift is+// blind, and says so). The response is not to shorten the history but to move it: each frame the history (and+// its moments) is scaled by 1 + DRIFT_GAIN x the pooled residual, less what the pixel's noise allows the+// pooled value to be by chance (DRIFT_ALLOW of its deviations, DRIFT_ALLOW_UP above, where a sample's tail+// is). A proportional correction on a pooled error: it takes the lag out and leaves the noise of a full+// history, where a shorter history took the lag out by letting the noise in. The same factor goes to the+// specular history of a rough surface (`stemporal`).+// The constants are from a model of these rules on synthetic samples (tools/chart-model.py: a grid of pixels;+// steady, exponential, one bright sample in 10 and in 100, a steady half with rare bright ones), then set on the+// benches (docs/RUNTIME.md has the tables). In the model (frame bound 24), the mean of the histories over the+// truth 2 / 4 / 8 / 16 frames after the light fell to 1/13: 7.6 / 1.00 / 1.00 / 1.00 on steady samples, 12.0 /+// 0.99 / 0.99 / 1.01 on exponential ones; halved: 1.90 / 1.48 / 1.01 / 1.00 and 1.92 / 1.80 / 1.20 / 1.04; under+// a fall of 2.6 % a frame, after 170 frames: 1.13 and 1.28 (without the drift 2.41 and 2.21), a steady half with+// one bright sample in 10: 1.49 (2.41), one bright sample in 10 alone: 2.25 (as without); with nothing changing+// the histories kept 24.0 of 24 frames and their mean within 0.5 % on every kind but the last (1.8 % low), and+// histories that started again (a surface uncovered) were 14 to 16 frames long after 16. What was tried and+// dropped there: letting the chart's average give up the share it was acted on (the response stalled at partial+// drops), a level that does not follow the history (false signals on exponential samples, 0.2 % of pixels a+// frame), a level that counts a history's first share (every history that started again read its next frames as+// the light having fallen: 1.3 frames long after 8), a floor of 0.025 (a steady pixel with rare bright samples+// signalled on 1.4 % of pixels a frame), shortening the history by the drift instead of moving it (under a fall of+// 0.7 % a frame, steady samples: 1.10 of the light on 14 frames for 1.07 on 48), and a drift not weighted by the pixels' noise (it darkened pixels lit by+// rare samples by a fifth).+// The chart's and the drift's state lasts in `diffuse_fast` (per traced sample, eight bits each, rounded at+// random so that a weight below a step still moves it in the mean: x the level's three channels and the drift; y+// the residual average's three channels and the root of the mean square) and is kept up whether or not the+// lighting changes, so that it is warm when it does. With `L.mode.z` 0 nothing responds: the history is the+// plain mean of its frames.+// The specular history has the same chart on one channel (the mean of the three, `stemporal`), in `diffuse_mom`.z.++// The blur a moving history may have gathered, as a variance (previous traced pixels^2): diffuse irradiance (64+// frames at half a pixel a frame and faster), and the specular history (32 frames).+// The bound trades blur for noise, and which costs more depends on the scene and on how long the motion lasts; what+// a reflection needs in a move of the camera is not this bound but the parallax's (`stemporal`). Measured on the+// integrated tree, 2026-11-24, bench-ghosting --quick (Bistro night; excess dE over the settled frame: mid-turn,+// mid-strafe, half a second after turning back, after strafing back, 0.1 s after a stop), with the parallax bound+// as it is, for budgets of 8 and 8, 16 and 8, 16 and 16: 0.89 / 1.42 / 1.12 / 1.21 / 1.33, 0.87 / 1.39 / 1.13 /+// 1.22 / 1.31, 0.88 / 1.39 / 1.14 / 1.22 / 1.31 (the previous release: 0.85 / 1.60 / 1.13 / 1.25 / 1.34; these+// with rough surfaces still held to their neighbourhood in a move, which was then dropped for its cost: the last+// figure is 1.36 now). And+// bench-window's rooms-turn (768 lamps, a 24-frame turn out of a settled view) in the tree before it had specular+// light, dE to offline at the last moving frame for a diffuse budget of 4 / 8 / none: 2.23 / 2.12 / 1.99: a turn+// that short gathers little blur, and a history cut for it is that much noisier for seconds. (Not 4 for another+// reason too: its 16 frames are FIREFLY_FRAMES and HIST_CENTRE, and a history held at exactly their threshold+// falls to either side of it by rounding.)+const MOVE_BLUR: f32 = 16.0;+const SPEC_MOVE_BLUR: f32 = 8.0;+// Frames of history on animated shading.+const ANIM_FRAMES: f32 = 4.0;+// The change chart. CHART_A: the weight of a frame's residual in the pooled average. CHART_SD: the pooled average's+// standard deviation, in deviations of one residual (see above). CHART_K: the band, in deviations. CHART_FLOOR: the+// least deviation of the pooled share that counts. CHART_GAIN: `drop` per band beyond the band. CHART_MATURE: the+// history length from which a pixel's residual counts in full (a history of a frame or two is no level to compare+// with). CHART_LEVEL: the frames the level averages over at most. CHART_CHANNEL: the share of the history's+// luminance added to each channel's own level in the share's denominator, so that a channel the light has next to+// none of does not read its own noise as change. CHART_DARK: the light (display units at the current exposure)+// below which a change is none.+const CHART_A: f32 = 0.125;+const CHART_SD: f32 = 0.063;+const CHART_K: f32 = 3.5;+const CHART_FLOOR: f32 = 0.04;+const CHART_GAIN: f32 = 2.0;+const CHART_MATURE: f32 = 4.0;+const CHART_LEVEL: f32 = 32.0;+const CHART_CHANNEL: f32 = 0.25;+const CHART_DARK: f32 = 1.0e-3;+// The drift. DRIFT_GAIN: the share of the pooled relative residual taken out of the history a frame. DRIFT_ALLOW,+// DRIFT_ALLOW_UP: what of it is the noise's, in deviations of the pooled value, below and above (a sample's+// distribution has its tail above). DRIFT_CLIP: the most a sample's relative residual counts for.+const DRIFT_GAIN: f32 = 0.25;+const DRIFT_ALLOW: f32 = 2.0;+const DRIFT_ALLOW_UP: f32 = 4.0;+const DRIFT_CLIP: f32 = 7.0;++// The most frames a history moving `speed` pixels a frame over its grid may hold for its blur to stay under `blur`.+fn moving_frames(speed: f32, blur: f32) -> f32 {+ let f = min(speed, 0.5);+ return blur / max(f * (1.0 - f), 1.0e-6);+}++// The four pixels the chart's average is pooled from, around where the pixel was: a quarter turn apart at distance+// sqrt 5, mirrored every other frame (the recursion's reach is then the same along both diagonals).+fn chart_tap(k: i32) -> vec2<i32> {+ var o = vec2<i32>(-2, -1);+ if (k == 1) { o = vec2<i32>(1, -2); }+ if (k == 2) { o = vec2<i32>(2, 1); }+ if (k == 3) { o = vec2<i32>(-1, 2); }+ if ((L.size.z & 1u) == 1u) { o.x = -o.x; }+ return o;+}++// A sample's share against the history h (`level`: the history's own, luminance or mean), per channel.+fn chart_share(s: vec3<f32>, h: vec3<f32>, level: f32) -> vec3<f32> {+ return s / (s + h + vec3<f32>(CHART_CHANNEL * level + CHART_DARK / max(exposure_scale(), 1.0e-8)));+}++// The weight of this frame's share in the level, the history `frames` long with it: the level is the mean of the+// shares since the history started, but for the first (a share against no history is 1 whatever the light: counted,+// every history that started again read its next frames as the light having fallen, and started again: in the+// model 14 to 23 % of such pixels signalled a frame and their histories were 1.3 frames long after 8).+fn chart_level_weight(frames: f32) -> f32 {+ return 1.0 / clamp(frames - 1.0, 1.0, CHART_LEVEL);+}++fn chart_mature(frames: f32) -> f32 {+ return clamp((frames - 1.0) / (CHART_MATURE - 1.0), 0.0, 1.0);+}++// The share of the history a pooled residual average `dev` (its size) takes, `spread` the pooled mean square: none+// within the band, all of it from 1 + 1 / CHART_GAIN bands on.+fn chart_drop(dev: f32, spread: f32) -> f32 {+ return clamp((dev / max(CHART_K * CHART_SD * sqrt(max(spread, 0.0)), CHART_FLOOR) - 1.0) * CHART_GAIN, 0.0, 1.0);+}++// Three numbers in 0 .. 1 for sample q this frame, to round the chart's level at random.+fn chart_dither(q: u32) -> vec3<f32> {+ let k = q * 2654435761u + L.size.z * 40503u;+ return vec3<f32>(f32((k * 3u) >> 8u), f32((k * 5u + 0x9e3779b9u) >> 8u), f32((k * 7u + 0x3c6ef372u) >> 8u)) / 16777216.0;+}+// Diffuse temporal accumulation on the traced grid: the sample's irradiance (diffuse lighting / albedo) blended into// the previous traced grid's history at its reprojected position (motion vectors for moving objects), with its// moments (variance for the denoiser, firefly and change tests). Writes the denoiser input (fb, traced grid).@@ -489,13 +664,11 @@ fn dtemporal(@builtin(global_invocation_id) gid: vec3<u32>) {var l = lum(irr);var hd = vec4<f32>(0.0);var hm = vec4<f32>(0.0);- var hf = vec3<f32>(0.0); // the fast mean in colour, reprojected- var slow_c = vec3<f32>(0.0); // the slow and the fast means in colour around the point- var fast_c = vec3<f32>(0.0);- var around = vec2<f32>(-1.0);- var fast_sd = 0.0; // of the fast luminances around the point (their spread in space), and how many- var fast_n = 1.0;- var speed = 0.0; // output pixels this frame+ // (For the response below: how far the pixel's centre moved over the previous traced grid this frame, in its+ // pixels; the history tap that counts most, -1: none; and the previous grid's pixel the history was read around.)+ var speed = 0.0;+ var near_tap = -1;+ var around = vec2<i32>(0);let ps = vec2<i32>(L.isz.zw);if (L.size.w == 0u && ps.x > 0) {let mv = motion_in[q];@@ -516,10 +689,14 @@ fn dtemporal(@builtin(global_invocation_id) gid: vec3<u32>) {// (Bistro's street and facades at 256 frames held 8-30). The centre fetch takes 0.5 (depth unchanged).let centred = diffuse_hist[last_half(u32(jc.y * ps.x + jc.x))].w >= HIST_CENTRE;if (centred) { tc = tcc; }+ // (Nothing moved and the grid is the same one: exactly none, not the reprojection's rounding.)+ if (camera_moves() || (mv.w > 0.5 && t > 0.0) || any(ps != vec2<i32>(L.isz.xy))) { speed = length(tcc - vec2<f32>(f32(gid.x), f32(gid.y))); }+ around = vec2<i32>(round(tc));let x0 = i32(floor(tc.x));let y0 = i32(floor(tc.y));let f = tc - floor(tc);var wsum = 0.0;+ var most = 0.0;for (var k = 0; k < 4; k++) {let tx = x0 + (k & 1);let ty = y0 + (k >> 1u);@@ -528,125 +705,117 @@ fn dtemporal(@builtin(global_invocation_id) gid: vec3<u32>) {let j = u32(ty * ps.x + tx);hd += diffuse_hist[last_half(j)] * bw;hm += diffuse_mom[last_half(j)] * bw;- hf += fast_load(j) * bw;wsum += bw;+ if (bw > most) {+ most = bw;+ near_tap = i32(j);+ }}if (wsum > 1e-3) {hd /= wsum;hm /= wsum;- hf /= wsum;} else {hd = vec4<f32>(0.0);hm = vec4<f32>(0.0);}- if (non_finite(hd.rgb) || non_finite(hm.xyz) || non_finite(hf)) {+ if (non_finite(hd.rgb) || non_finite(hm.xyz)) {hd = vec4<f32>(0.0);hm = vec4<f32>(0.0);}- speed = length(sp - 0.5 - pp.xy);- // Slow / fast means over the 3x3 around it on the same surface (anti-lag compares them).- if (t > 0.0 && L.mode.z != 0u) {- var acc = vec2<f32>(0.0);- var acc2 = 0.0;- var na = 0.0;- for (var k = 0; k < 9; k++) {- let tx = i32(round(tc.x)) + k % 3 - 1;- let ty = i32(round(tc.y)) + k / 3 - 1;- if (tx < 0 || ty < 0 || tx >= ps.x || ty >= ps.y || !same_surface(tx, ty, pp.z, n, t)) { continue; }- let j = u32(ty * ps.x + tx);- let m = diffuse_mom[last_half(j)];- if (m.w <= 0.0 || non_finite(m.xyz)) { continue; }- slow_c += diffuse_hist[last_half(j)].rgb;- fast_c += fast_load(j);- acc += vec2<f32>(m.x, m.z);- acc2 += m.z * m.z;- na += 1.0;- }- if (na > 0.0) {- around = acc / na;- slow_c /= na;- fast_c /= na;- fast_sd = sqrt(max(acc2 / na - around.y * around.y, 0.0));- fast_n = na;- }- }+ if (hd.w <= 0.0) { near_tap = -1; }+ }+ }+ // ---- How long this pixel's history may be, and how it follows a change of the lighting ("The response of the+ // histories" above).+ // The change chart's state where this pixel was: its level at the history tap that counts most, the pooled+ // residual and its mean square from that tap and four pixels around (`chart_tap`).+ var level = vec3<f32>(0.0);+ var pooled = vec3<f32>(0.0);+ var spread = 0.0;+ var drift = 0.0;+ if (near_tap >= 0) {+ let own = diffuse_fast[last_half(u32(near_tap))];+ let l0 = unpack4x8snorm(own.x);+ level = l0.xyz * (127.0 / 255.0) + 0.5;+ drift = l0.w;+ let e0 = unpack4x8snorm(own.y);+ pooled = e0.xyz;+ spread = e0.w * e0.w;+ var taps = 1.0;+ for (var k = 0; k < 4; k++) {+ let c = around + chart_tap(k);+ if (c.x < 0 || c.y < 0 || c.x >= ps.x || c.y >= ps.y) { continue; }+ let tap = diffuse_fast[last_half(u32(c.y * ps.x + c.x))];+ let e = unpack4x8snorm(tap.y);+ pooled += e.xyz;+ spread += e.w * e.w;+ drift += unpack4x8snorm(tap.x).w;+ taps += 1.0;}+ pooled /= max(taps, 1.0);+ spread /= max(taps, 1.0);+ drift *= 0.5 / max(taps, 1.0);}- // How long the history may be at most is the frame's (`misc.y`: live/mod.rs HISTORY_LIVE while the scene's lighting- // changes, far longer once it has settled); within it, each pixel's own: less where it moves (until 2026-11-12 the- // whole frame's was held to 48 while the camera moved), a few frames on animated shading, and anti-lag below.- let cap = mix(select(L.misc.y, min(L.misc.y, 4.0), anim), min(L.misc.y, select(HIST_MOVING, 4.0, anim)), clamp(speed, 0.0, 1.0));+ // The drift ("The response of the histories"): what the pooled relative residual says the history is off by,+ // less what the pixel's own noise allows it to be, taken out of the history at DRIFT_GAIN a frame. The+ // luminance moments go with it.+ let cv2 = max(hm.y / max(hm.x * hm.x, 1.0e-12) - 1.0, 0.0);+ let trust = 1.0 / (1.0 + cv2);+ var drifted = 1.0;+ if (L.mode.z != 0u && !anim) {+ let allow = select(DRIFT_ALLOW, DRIFT_ALLOW_UP, drift > 0.0) * CHART_SD * trust * sqrt(cv2);+ drifted = 1.0 + DRIFT_GAIN * sign(drift) * max(abs(drift) - allow, 0.0) / max(trust, 0.5);+ hd = vec4<f32>(hd.rgb * drifted, hd.w);+ hm = vec4<f32>(hm.x * drifted, hm.y * drifted * drifted, hm.z, hm.w);+ }+ let cap = min(select(L.misc.y, min(L.misc.y, ANIM_FRAMES), anim), moving_frames(speed, MOVE_BLUR));var m1 = hm.x;var m2 = hm.y;let sd = sqrt(max(m2 - m1 * m1, 0.0));if (hd.w >= 4.0 && hd.w < FIREFLY_FRAMES) {// Firefly, while the history is young (after a disocclusion or a lighting change): a sample moves the pixel by// (l - mean) / frames; cut only what would show as a sparkle (more than half the mean above it). Not from- // FIREFLY_FRAMES on: histories are capped (48 frames moving, 32 while the scene's lighting changes), so a cut tied to the frame count+ // FIREFLY_FRAMES on: histories are capped while the view moves or the lighting changes, so a cut tied to the frame count// kept clipping the rare bright samples of small strong lights for good. Bistro crowd at 10 s, held: diffuse// 0.70 of our offline render with it, 0.82 without; moving ΔE 15.3 -> 12.9.let hi = m1 + 4.0 * sd + 0.5 * m1 * hd.w + 1e-4;if (l > hi) { irr *= hi / l; l = hi; }}- let fast = select(l, mix(hm.z, l, 0.25), hd.w > 0.0);- var count = min(hd.w + 1.0, cap);- // The fast-history clamp (ReBLUR's), before the cut below: the cut acts once, on luminance, and the history it- // leaves still holds the old light (a lamp switched off left its pool on the wall 3.3 times too bright after half- // a second, 17 % after 4 s, falling as 1 / frames; a sign's, in its colour). So every frame the slow means around- // the point are held, a channel each, to the band of the fast means there: their mean +- FAST_BAND of its standard- // error (the fast luminances' spread over the root of their number; both means are of the same pixels, so what- // differs between neighbours cancels), and this pixel's history is changed as they are: by the same ratios, or- // by the difference itself in a channel the history has next to none of. Its luminance mean follows it (once:- // the cut then moves it toward the fast mean, it does not scale it again). What is left of the history counts- // for as many frames less, by the channel changed most among those that matter (a twentieth of the largest): the- // pixel goes back to the spatial filter. While the lighting is live, as the cut: on a settled scene there is- // nothing to find.- var hist = hd.rgb;- if (L.mode.z != 0u && around.x >= 0.0 && hd.w > 0.0 && !non_finite(fast_c) && !non_finite(slow_c)) {- let rel = FAST_BAND * fast_sd / sqrt(fast_n) / max(around.y, 1e-6);- let to = clamp(slow_c, fast_c * max(1.0 - rel, 0.0), fast_c * (1.0 + rel) + 1e-4);- if (any(to != slow_c)) {- let has = slow_c > vec3<f32>(1e-5);- let r = select(vec3<f32>(1.0), to / slow_c, has);- hist = max(hist * r + select(to - slow_c, vec3<f32>(0.0), has), vec3<f32>(0.0));- let was = lum(slow_c);- if (was > 1e-5) {- let rl = lum(to) / was;- m1 *= rl;- m2 = m1 * m1 + sd * sd * rl * rl;- } else {- m1 = max(m1 + lum(to) - was, 0.0);- m2 = m1 * m1 + sd * sd;- }- let big = max(slow_c, to);- let left = select(vec3<f32>(1.0), min(slow_c, to) / max(big, vec3<f32>(1e-6)), big > vec3<f32>(0.05 * max(big.x, max(big.y, big.z))));- count = max(min(count, hd.w * min(left.x, min(left.y, left.z)) + 1.0), 2.0);- }- }- // Anti-lag (as ReBLUR's): around this point the fast average left the slow one by more than its- // (neighbourhood-averaged) noise allows: the lighting changed here (a sign switched off, a door opened, a wall- // gone, a spark passing). The history is cut by how far, down to two frames at ANTILAG of the mean: a slow change- // shortens it a little every frame until it follows, a sudden one restarts it. While the scene's lighting changes- // (`mode.z`): once it has settled there is nothing to find, and what the test then finds is noise (a still Bistro- // read dE 2.43 against offline with it always on, 2.23 without).- // (The specular has none: at one sample a pixel its fast mean is noise, and cutting by it cost more than the lag:- // the Bistro slice at 5 s read dE 2.98 with it for 2.82.)- if (L.mode.z != 0u && hd.w >= 6.0 && around.x >= 0.0) {- let over = abs(around.y - around.x) - 3.0 * 0.38 * sd / 3.0 - 1e-4;- let keep = 1.0 - clamp(over / (ANTILAG * max(max(around.x, around.y), 1e-6)), 0.0, 1.0);- if (keep < 1.0) {- count = max(min(count, hd.w * keep + 1.0), 2.0);- m1 = mix(around.y, m1, keep);- m2 = m1 * m1 + sd * sd;- }- }- let a = 1.0 / max(count, 1.0);- let mom = vec4<f32>(mix(m1, l, a), mix(m2, l * l, a), fast, 1.0);- let d = mix(hist, irr, a);- let fc = select(irr, mix(hf, irr, 0.25), hd.w > 0.0);- diffuse_fast[this_half(q)] = vec2<u32>(pack2x16float(min(fc.rg, vec2<f32>(6.0e4))), pack2x16float(vec2<f32>(min(fc.b, 6.0e4), 0.0)));+ // This frame's sample against the history, per channel, as a share (`chart_share`), and its residual from the+ // level: by how much more or less of the light the sample holds than this pixel's samples usually do.+ let hist = max(hd.rgb, vec3<f32>(0.0));+ let hist_l = lum(hist);+ let share = chart_share(max(irr, vec3<f32>(0.0)), hist, hist_l);+ let res = (share - level) * chart_mature(hd.w);+ // (The relative residual, for the drift: bounded above, weighted by how far the pixel's samples can be trusted.)+ let rel = clamp((l - hist_l) / (hist_l + CHART_DARK / max(exposure_scale(), 1.0e-8)), -1.0, DRIFT_CLIP) * chart_mature(hd.w) * trust;+ // The response: only while the scene's lighting changes, and not on animated shading (a few frames already).+ var drop = 0.0;+ if (L.mode.z != 0u && !anim) { drop = chart_drop(max(max(abs(pooled.x), abs(pooled.y)), abs(pooled.z)), spread); }+ // (Schied et al. 2018, eq. 15: the blend weight is the plain one, moved towards 1 by the share of the history the+ // change takes.)+ let plain = 1.0 / max(min(hd.w + 1.0, cap), 1.0);+ let a = plain + drop * (1.0 - plain);+ let count = 1.0 / a;+ // (z: the drift's factor this frame, for `stemporal`, which then puts its own chart there.)+ let mom = vec4<f32>(mix(m1, l, a), mix(m2, l * l, a), drifted, 1.0);+ let d = mix(hd.rgb, irr, a);diffuse_hist[this_half(q)] = vec4<f32>(d, count);diffuse_mom[this_half(q)] = mom;+ // The chart's state: the level follows the history (it starts again with it); the pooled averages take this+ // frame's residual. (None on animated shading or the sky.)+ let level_now = mix(level, share, chart_level_weight(count));+ var e_now = vec4<f32>(0.0);+ var drift_now = 0.0;+ if (!anim && t > 0.0) {+ e_now = vec4<f32>(mix(pooled, res, CHART_A), sqrt(mix(spread, max(max(res.x * res.x, res.y * res.y), res.z * res.z), CHART_A)));+ // (Less what a signal of the chart has just acted on: the history it leaves is of this frame, and a drift+ // read before it would be taken out again, an overshoot of a few per cent after a lamp came on.)+ drift_now = clamp(mix(drift, rel, CHART_A), -0.5, 0.5) * (1.0 - drop);+ }+ // (Eight bits each, rounded at random: the level about a half, the drift doubled.)+ let dither = (vec4<f32>(chart_dither(q), fract(chart_dither(q).x * 7.0 + 0.37)) - 0.5) / 127.0;+ diffuse_fast[this_half(q)] = vec2<u32>(pack4x8snorm(vec4<f32>((level_now - 0.5) * (255.0 / 127.0), 2.0 * drift_now) + dither), pack4x8snorm(e_now));// Denoiser input; w = variance of the accumulated mean luminance (its noise estimate).fb[q] = vec4<f32>(max(d, vec3<f32>(0.0)), max(mom.y - mom.x * mom.x, 0.0) / max(count, 1.0));}@@ -798,16 +967,110 @@ fn spec_history(pp: vec3<f32>, n: vec3<f32>, t: f32, rough: f32, virt: bool) ->return h;}-// The most a specular history may trail behind its reflection, output pixels (`stemporal`).-const SPEC_TRAIL: f32 = 2.0;-// How far from this frame's neighbourhood mean a specular history may lie, in deviations of the neighbourhood-// (`stemporal`'s variance clipping).-const SPEC_CLIP: f32 = 2.0;-const SPEC_CLIP_REL: f32 = 0.5;--// Specular temporal accumulation on the traced grid (UE 5.8 Lumen reflections, LumenReflectionDenoiserTemporal.usf): the-// surface history and the reflection-hit one (reprojected through the mirror image of what it shows); the one closer to-// this frame's neighbourhood mean wins. Writes the specular filter's input and the traced grid's g-buffer.+// ---- The specular history's rules (`stemporal`; the lengths and the chart as "The response of the histories").+// Set on the integrated tree, 2026-11-24 (bench-ghosting, bench-object-ghosting, bench-temporal's water and edit,+// bench-window; docs/RUNTIME.md has the tables).+// A reflection's history is tried through the reflection too when the two places lie this far apart (previous traced+// pixels): nearer, they are one fetch.+const SPEC_PAR_MIN: f32 = 0.25;+// The roughness from which the reflection's own place is not tried (no second fetch), and from which the surface's+// history starts to lose against the reflection's below it.+const SPEC_VIRT_ROUGH: f32 = 0.6;+const SPEC_VIRT_FROM: f32 = 0.3;+// What the surface's history counts for on a mirror, where it is right only if nothing in the reflection differs.+const SPEC_SURFACE_MIRROR: f32 = 0.1;+// The neighbourhood's band, in its deviations, and as a share of the history's level.+const SPEC_GAMMA: f32 = 1.25;+const SPEC_REL: f32 = 0.1;+// The chart level below which a pixel counts as lit by rare samples (a dark neighbourhood is then no evidence against+// its history), and from which it counts as steadily lit.+const SPEC_RARE: f32 = 0.3;+const SPEC_STEADY: f32 = 0.45;+// How far a history may have slid against what it shows (previous traced pixels, summed over its frames) on a+// surface of roughness 0, and how much further by roughness squared (the lobe's width: a blurred image hides a+// slide); the share of the parallax that counts on a mirror, where the reflection's own place is known; and the+// share of the bound lifted where the reflection's history is found there and agrees with this frame.+const SPEC_SLIDE: f32 = 4.0;+const SPEC_SLIDE_ROUGH: f32 = 32.0;+const SPEC_PAR_MIRROR: f32 = 0.25;+const SPEC_FOUND: f32 = 0.9;+// On animated shading: the share of the band's allowance for rare samples that is kept. bench-temporal --shot+// water (a canal's waves under two lamps and a sign; dE to the converged frame of the same moment, the water's+// reflections, time held / running), for 1 (no clamp there) / 0.5 / 0.25 / 0: 1.16 / 3.22 / 3.67 / 3.77 and 20.6 /+// 12.5 / 10.8 / 9.0 (the previous release: 3.08 and 13.4); with a bound of 2 frames and no clamp 5.51 and 12.2.+const SPEC_ANIM_RARE: f32 = 0.5;+// The most frames while the scene's lighting changes: on a mirror, at the roughness where a reflection is still+// sharp but the filter already reaches (SPEC_GLOSS), and from SPEC_VIRT_ROUGH on (there the frame's bound alone).+const SPEC_LIVE_MIRROR: f32 = 24.0;+const SPEC_LIVE_GLOSS: f32 = 12.0;+const SPEC_GLOSS: f32 = 0.3;+// A traced sample's specular lighting, as `sample_specular`, the ceiling `cl` (`sample_clamp`) read once.+fn spec_sample(q: u32, cl: f32) -> vec3<f32> {+ var s = sample_px[q].spec.rgb / max(L.misc2.w, 1.0) + refl_res[q].rgb;+ if (non_finite(s)) { s = vec3<f32>(0.0); }+ let l = lum(s);+ if (l > cl) { s *= cl / l; }+ return max(s, vec3<f32>(0.0));+}++// The specular chart's state, a whole number below 2^24 in `diffuse_mom`.z (a float holds it exactly; 0, a cleared+// buffer, is no state): the level (8 bits, rounded at random), the residual average (8 bits, signed) and the root of+// the residuals' mean square (8 bits).+fn spec_chart(v: f32) -> vec3<f32> {+ let u = u32(clamp(v, 0.0, 16777215.0));+ return vec3<f32>(f32(u & 255u) / 255.0, f32(i32(((u >> 8u) & 255u) ^ 128u) - 128) / 127.0, f32((u >> 16u) & 255u) / 255.0);+}++fn spec_chart_pack(level: f32, e: f32, rms: f32, dither: f32) -> f32 {+ let a = u32(clamp(level * 255.0 + dither, 0.0, 255.0));+ let b = u32(i32(round(clamp(e, -1.0, 1.0) * 127.0))) & 255u;+ let c = u32(clamp(round(rms * 255.0), 0.0, 255.0));+ return f32(a | (b << 8u) | (c << 16u));+}++// Specular temporal accumulation on the traced grid: this frame's specular sample (with the resolved reflection,+// `refl`) blended into its history. Writes `spec_hist` (rgb, frames), the specular filter's input (`spec_store(0u, ..)`),+// the specular chart's state (`diffuse_mom`.z of this frame's half, which `dtemporal` has written by then) and the+// traced grid's g-buffer.+// - Where the history is. A reflection's image does not move with the surface that shows it: "reflected objects+// move according to their depth, not the depth of the surface which reflects them", and reprojected by the+// surface they smear (Stachowiak 2015, notes to the slides on temporal reprojection, who reproject by the average+// depth of what is reflected). Here: seen in a plane mirror, a thing at distance d behind the surface point at+// distance t lies at t + d along the view ray. Both places are read when they differ: where the surface point was+// (`prev_pixel`, moving objects by their motion), and where that point behind the surface was (for a surface+// that moved: carried by twice its move along its normal, the law of reflection for an image of what stands+// still). Which to believe is this frame's samples' to say: each history is held against the mean and deviation+// of the nine samples around, in YCoCg (a box along luma, Karis 2014, slide 33; a statistical one in place of his+// minimum and maximum, as Schied et al. 2018 § 2 report of Patney et al. 2016), and counts by exp(-e^2), e its+// distance in bands, times what the roughness says before any sample does (the reflection's place on a mirror,+// the surface's from SPEC_VIRT_ROUGH).+// - How long it may be: the frame's bound; the bound of a history resampled in motion (`moving_frames`); and a bound+// by the parallax, the distance between the two places a frame: a history n frames long has slid n times that+// against one of them, and may by SPEC_SLIDE pixels and more the wider the lobe. The parallax is none in a turn+// of the camera, when nothing bounds, and in a move it is what a reflection needs: where the sample has no hit+// distance the parallax of a far reflection is taken (the most it can be), and rough surfaces are bound too (a+// lamp's highlight on wet stones slides with the view as a mirror's image does, only blurred: without that, the+// street 0.1 s after a stop read an excess dE of 1.78 for 1.33). On a mirror only a share of it counts, and+// little of it where the reflection's history was found in its place and agrees with this frame. While the+// lighting changes, a bound by roughness: shortest where a reflection is sharp enough to show a lag and the+// filter already reaches (SPEC_GLOSS), longer on a mirror, which has the temporal mean alone against its noise,+// and the frame's bound alone on rough surfaces, whose reflection is too blurred to show one. Their histories+// take the diffuse history's drift instead (above).+// - What it follows, while the lighting changes or the reflection moves against its surface, and always on animated+// shading: the chart (above), on the mean of the three channels, pooled around where the surface point was; and+// the neighbourhood's band: the history is clamped into mean +- (SPEC_GAMMA deviations + a share of its own+// level), Karis's neighbourhood clamp (slides 30 to 34) on those statistics, with one more term. One sample a+// pixel is heavy-tailed: where the light comes by rare bright samples, nine dark ones around say nothing against+// a history that holds their mean, and clipping it to them every frame darkens the reflection for good. The+// chart's level knows which pixels those are (the mean share of their samples is far below a half): there the+// band is as wide as the history's level (it cannot be clamped down, only up, when all nine are brighter), and+// tight only where the samples were steady (a mirror's image of a lamp, which nine dark samples do contradict).+// A reflection that passes is steady while it is there: when the clamp raises a history (all nine samples above+// it at once) the level is set to a steady one, and a pixel takes the highest level of the pixels its chart+// pools from, so that the rim of a passing reflection is treated as its middle. (Without the two, a light thrown+// over a polished floor left its reflection along its path, hollowed out: bench-object-ghosting's orb 0.1 s+// after it lands, dE / trail 4.88 / 280 px for 3.63 / 96.) What the clamp takes shortens the history by the same+// share.@compute @workgroup_size(8, 8, 1)fn stemporal(@builtin(global_invocation_id) gid: vec3<u32>) {let iw = L.isz.x;@@ -830,95 +1093,183 @@ fn stemporal(@builtin(global_invocation_id) gid: vec3<u32>) {p = L.cur.pos.xyz + dir * t;depth = dot(p - L.cur.pos.xyz, L.cur.fwd.xyz);}- let cur = sample_specular(q);- // This frame's neighbourhood mean and spread (same surface), in YCoCg.- var m1 = vec3<f32>(0.0);- var m2 = vec3<f32>(0.0);- var mn = 0.0;- for (var k = 0; k < 9; k++) {- let qx = i32(gid.x) + k % 3 - 1;- let qy = i32(gid.y) + k / 3 - 1;- if (qx < 0 || qy < 0 || qx >= i32(iw) || qy >= i32(ih)) { continue; }- let j = u32(qy) * iw + u32(qx);- let s = sample_px[j];- var ok = false;- if (t > 0.0) {- ok = s.color.w > 0.0 && abs(s.color.w - t) < 0.05 * t + 0.01 && dot(normalize(s.normal.xyz + vec3<f32>(1e-6)), n) > 0.8;- } else {- ok = s.color.w == 0.0;- }- if (!ok) { continue; }- let yq = ycocg(sample_specular(j));- m1 += yq;- m2 += yq * yq;- mn += 1.0;- }- let smean = m1 / max(mn, 1.0);- let ssd = sqrt(max(m2 / max(mn, 1.0) - smean * smean, vec3<f32>(0.0)));- // Reflection hit distance for the mirror-image reprojection: on near mirrors the resolved one (pass `refl`).- let st = select(px.spec.w, refl_res[q].w, refl_res[q].w > 0.0 && rough < NEAR_MIRROR);+ let cl = sample_clamp();+ let cur = spec_sample(q, cl);let mv = motion_in[q];- var hs = vec4<f32>(0.0);- var hv = vec4<f32>(0.0);- // What bounds this pixel's history, in output pixels a frame: its own speed (a resampled history blurs a little- // every frame) and its reflection's parallax, how far what it reflects moved against the surface (none in a turn of- // the camera; the history then trails behind the reflection).+ let live = L.mode.z != 0u;+ // The diffuse history's drift factor at this pixel this frame (`dtemporal` left it in this frame's half).+ let drifted = diffuse_mom[this_half(q)].z;+ let ps = vec2<i32>(L.isz.zw);+ var h = vec4<f32>(0.0); // the surface's history+ var hv = vec4<f32>(0.0); // the reflection'svar speed = 0.0;- var parallax = 0.0;- if (L.size.w == 0u && L.isz.z > 0u) {- let pp = prev_pixel(p + select(vec3<f32>(0.0), mv.xyz, mv.w > 0.5 && t > 0.0));- if (pp.z > 0.0) {- hs = spec_history(pp, n, t, rough, false);- speed = length(sp - 0.5 - pp.xy);- // (A moving reflector: the camera-only reprojection ignores its own motion, here and below. Its speed.)- parallax = speed;- if (mv.w <= 0.5) {- // Of the reflected point where this frame has one, else of the farthest (the sample took the diffuse- // lobe, or the sky): the most it can be.- let pf = prev_pixel(L.cur.pos.xyz + dir * (t + select(1.0e3, min(st, 1.0e3), t > 0.0 && st > 0.0)));- parallax = select(0.0, length(pf.xy - pp.xy), pf.z > 0.0);+ var par = 0.0;+ var chart = vec3<f32>(0.0); // the level where the surface point was, the pooled residual average and mean square+ var around_level = 0.0; // the highest level among the pooled pixels+ if (L.size.w == 0u && ps.x > 0) {+ let object_moves = mv.w > 0.5 && t > 0.0;+ let moved = select(vec3<f32>(0.0), mv.xyz, object_moves);+ let pps = prev_pixel(p + moved);+ if (pps.z > 0.0) {+ let k = vec2<f32>(ps) / vec2<f32>(f32(L.size.x), f32(L.size.y));+ let in_motion = camera_moves() || object_moves || any(ps != vec2<i32>(L.isz.xy));+ if (in_motion) { speed = length((pps.xy - (sp - 0.5)) * k); }+ h = spec_history(pps, n, t, rough, false);+ // The reflection's hit distance: this sample's ray's, or the resolved one (`refl`) on a near mirror and+ // where the sample has none (it took the diffuse lobe). With neither, the frame knows nothing of the+ // reflection's place: the surface's history, and for the bound the parallax of a reflection far away,+ // which is the most it can be (none in a turn of the camera, the surface's own motion against the+ // distance in a move).+ var dist = px.spec.w;+ if (rough < NEAR_MIRROR || !(dist > 0.0 && dist < 1.0e3)) { dist = refl_res[q].w; }+ let known = dist > 0.0 && dist < 1.0e3;+ if (t > 0.0 && in_motion) {+ // (Where the reflection's image was: with the camera's move alone for a still surface. A surface+ // that moved carried the image of what stands still by twice its move along its normal, the law of+ // reflection at a plane; not by its move, which slides the mirror under an image that stays.)+ let ppv = prev_pixel(p + dir * select(1.0e4, dist, known) + 2.0 * dot(moved, n) * n);+ if (ppv.z > 0.0) {+ par = length((ppv.xy - pps.xy) * k);+ if (known && par >= SPEC_PAR_MIN && rough < SPEC_VIRT_ROUGH) { hv = spec_history(ppv, n, t, rough, true); }+ }+ }+ // The chart's state: the level at the pixel the surface point was in, the averages from it and four+ // around it.+ let c0 = vec2<i32>(round((pps.xy + 0.5) * k - 0.5));+ if (t > 0.0 && c0.x >= 0 && c0.y >= 0 && c0.x < ps.x && c0.y < ps.y) {+ chart = spec_chart(diffuse_mom[last_half(u32(c0.y * ps.x + c0.x))].z);+ around_level = chart.x;+ chart.z *= chart.z;+ var taps = 1.0;+ for (var j = 0; j < 4; j++) {+ let c = c0 + chart_tap(j);+ if (c.x < 0 || c.y < 0 || c.x >= ps.x || c.y >= ps.y) { continue; }+ let e = spec_chart(diffuse_mom[last_half(u32(c.y * ps.x + c.x))].z);+ around_level = max(around_level, e.x);+ chart.y += e.y;+ chart.z += e.z * e.z;+ taps += 1.0;+ }+ chart.y /= max(taps, 1.0);+ chart.z /= max(taps, 1.0);}}- if (t > 0.0 && st > 0.0 && mv.w <= 0.5) {- let pv = prev_pixel(L.cur.pos.xyz + dir * (t + min(st, 1.0e3)));- if (pv.z > 0.0) { hv = spec_history(pv, n, t, rough, true); }+ }+ // This frame's samples around: needed to choose between two histories, and to hold one to them while the lighting+ // changes or the reflection moves against its surface. (A settled scene seen from a still camera, or in a turn,+ // reads none: its history is the plain mean of its frames.)+ // The light that drifts for the diffuse history drifts for a rough reflection of it too: the same factor, from+ // SPEC_GLOSS on (a sharp reflection is of one thing, and has its own short bound).+ if (live && drifted > 0.0) {+ let share = smoothstep(SPEC_GLOSS, SPEC_VIRT_ROUGH, rough);+ h = vec4<f32>(h.rgb * mix(1.0, drifted, share), h.w);+ hv = vec4<f32>(hv.rgb * mix(1.0, drifted, share), hv.w);+ }+ // Animated shading (waves, ripples): the surface holds still and its normal does not, so what it reflects is+ // another thing each frame. Its history is held to this frame's samples whether or not the lighting changes,+ // with SPEC_ANIM_RARE of the allowance for rare samples (a glint that has moved on is not one; a glint under a+ // stopped clock is). A bound in frames did worse both ways: short, the stopped water is noise; long, the+ // running water is the blur of its waves.+ let anim = px.albedo.w > 1.5 && rough < SPEC_GLOSS;+ let two = hv.w > 0.0;+ // (In a move of the camera: below SPEC_VIRT_ROUGH. A rough surface has the parallax bound alone: held to the+ // nine samples too, the street 0.1 s after a stop read an excess dE of 1.31 for 1.36, for nine more taps on+ // every rough pixel in every move.)+ let held = (live || anim || (par >= SPEC_PAR_MIN && rough < SPEC_VIRT_ROUGH)) && (h.w > 0.0 || two);+ var clamped = 0.0; // the share of the history the clamp took+ var found = 0.0; // how far the reflection's history was found, and agrees with this frame+ var risen = 0.0; // the share by which the clamp raised the history+ if (two || held) {+ var s1 = vec3<f32>(0.0);+ var s2 = vec3<f32>(0.0);+ var sn = 0.0;+ for (var j = 0; j < 9; j++) {+ let qx = i32(gid.x) + j % 3 - 1;+ let qy = i32(gid.y) + j / 3 - 1;+ if (qx < 0 || qy < 0 || qx >= i32(iw) || qy >= i32(ih)) { continue; }+ let y = ycocg(select(spec_sample(u32(qy) * iw + u32(qx), cl), cur, j == 4));+ s1 += y;+ s2 += y * y;+ sn += 1.0;+ }+ let mean = s1 / sn;+ let dev = sqrt(max(s2 / sn - mean * mean, vec3<f32>(0.0)));+ let dark = CHART_DARK / max(exposure_scale(), 1.0e-8);+ if (two) {+ // Each history's distance from the samples' mean, in bands, and what the roughness says of each.+ let band = SPEC_GAMMA * dev + SPEC_REL * mean.x + dark;+ let ds = abs(ycocg(h.rgb) - mean) / band;+ let dv = abs(ycocg(hv.rgb) - mean) / band;+ let es = min(max(max(ds.x, ds.y), ds.z), 3.0);+ let ev = min(max(max(dv.x, dv.y), dv.z), 3.0);+ let of_surface = smoothstep(SPEC_VIRT_FROM, SPEC_VIRT_ROUGH, rough);+ let ws = select(0.0, mix(SPEC_SURFACE_MIRROR, 1.0, smoothstep(0.0, SPEC_VIRT_FROM, rough)) * exp(-es * es), h.w > 0.0);+ let wv = (1.0 - of_surface) * exp(-ev * ev);+ h = (h * ws + hv * wv) / max(ws + wv, 1.0e-6);+ found = wv / max(ws + wv, 1.0e-6) * exp(-ev * ev);+ }+ if (held && h.w > 0.0) {+ let hy = ycocg(h.rgb);+ // (Steadily lit: by the level, and by a history long enough for its level to mean it. While the lighting+ // changes, by the level here or of a pooled pixel beside it, the rim of a passing reflection being lit+ // as its middle is, and from a history half as long. Not so in a move of the camera under a settled+ // light, where the reflections slide but nothing comes or goes: bench-ghosting's strafe read an excess+ // dE of 1.77 with the wider rule for 1.39.)+ let steady = smoothstep(SPEC_RARE, SPEC_STEADY, select(chart.x, around_level, live)) * chart_mature(select(0.5, 1.0, live) * h.w);+ let rare = (1.0 - steady) * select(1.0, SPEC_ANIM_RARE, anim);+ // (Chroma to twice the luma: a saturated colour's Co is.)+ let band = SPEC_GAMMA * dev + (SPEC_REL + rare) * max(hy.x, 0.0) * vec3<f32>(1.0, 2.0, 2.0) + dark;+ let hc = clamp(hy, mean - band, mean + band);+ let took = abs(hc - hy);+ clamped = clamp(max(max(took.x, took.y), took.z) / (max(hy.x, mean.x) + dark), 0.0, 1.0);+ // (Raised: all nine samples are above the history at once. That is no rare sample but a light that+ // has come, a reflection passing: the level is told so below, or when it has passed, the nine dark+ // samples would count for nothing against it: a thrown light's reflection stayed along its path.)+ if (live && hc.x > hy.x) { risen = clamped; }+ h = vec4<f32>(max(ycocg_rgb(hc), vec3<f32>(0.0)), h.w);}}- let cap = select(L.misc.y, min(L.misc.y, 4.0), px.albedo.w > 1.5);- let ys = ycocg(hs.rgb);- let yv = ycocg(hv.rgb);- var surf = select(0.0, 0.8, length(smean - yv) > length(smean - ys) + 0.01 / exposure_scale());- surf = select(surf, 1.0, hv.w <= 0.0);- surf = select(surf, 0.0, hs.w <= 0.0 && hv.w > 0.0);- // The history held within SPEC_CLIP deviations of this frame's neighbourhood (variance clipping, as Lumen's- // reflection temporal clamps its history): what a still surface reflects can move while the surface and the camera- // hold still (a light carried past a polished floor), and nothing else tells its history so. Unclipped, the- // reflection of a thrown orb stayed on the floor along its whole path for the length of the history.- // While the scene's lighting changes (`mode.z`: something moved, a light switched), as the diffuse anti-lag: a- // settled scene has nothing to find, and clipping it cuts what the history averaged out of one sample a pixel.- // (Plus SPEC_CLIP_REL of the neighbourhood's luminance: one sample a pixel is heavy-tailed, most of the nine are- // dark next to a rare bright one, and a deviation's box alone pulled a right history down and let the next bright- // sample flash, a square at a time. What moved past is many times brighter than what is left.)- let slack = SPEC_CLIP * ssd + vec3<f32>(SPEC_CLIP_REL * abs(smean.x) + 0.002 / exposure_scale(), 0.0, 0.0);- var hy = mix(yv, ys, surf);- if (L.mode.z != 0u && mn >= 3.0) { hy = clamp(hy, smean - slack, smean + slack); }- // The history's length is the pixel's own (until 2026-11-13 every pixel's was held to 2 .. 12 frames by roughness- // while the camera moved or turned at all, and to 4 for 8 frames after it translated): HIST_MOVING at a pixel a- // frame, as the diffuse; and no longer than keeps its trail behind the reflection (frames x parallax) within- // SPEC_TRAIL pixels, 2 frames at least on a mirror, 4 from roughness 0.05 (below that the filter has nothing to- // work with).- var max_s = mix(cap, min(cap, HIST_MOVING), clamp(speed, 0.0, 1.0));- max_s = min(max_s, clamp(SPEC_TRAIL / max(parallax, 1e-4), mix(2.0, 4.0, clamp(rough / 0.05, 0.0, 1.0)), cap));- let frames_s = select(hv.w, hs.w, surf > 0.5);- var count_s = 1.0;- var s_out = cur;- if (hs.w > 0.0 || hv.w > 0.0) {- count_s = min(min(frames_s + 1.0, max_s), cap);- s_out = mix(max(ycocg_rgb(hy), vec3<f32>(0.0)), cur, clamp(1.0 / max(count_s, 1e-4), 0.0, 1.0));+ // The chart: this frame's share against the history (one channel: the mean of the three), its residual from the+ // level, and, while the lighting changes, what the pooled average takes of the history.+ let third = vec3<f32>(1.0 / 3.0);+ let level = dot(h.rgb, third);+ let share = chart_share(vec3<f32>(dot(cur, third)), vec3<f32>(level), level).x;+ let res = (share - chart.x) * chart_mature(h.w);+ var drop = 0.0;+ if (live) { drop = chart_drop(abs(chart.y), chart.z); }+ // The history's length.+ var cap = min(L.misc.y, moving_frames(speed, SPEC_MOVE_BLUR));+ if (par > 0.0) {+ // (The share of the parallax that counts: SPEC_PAR_MIRROR on a mirror, all of it from NEAR_MIRROR, none+ // from SPEC_VIRT_ROUGH, where the reflection stays with its surface.)+ // Less where the reflection's history was found where it should be and agrees with this frame's samples:+ // the bound is for a place that is not known.+ let counts = mix(SPEC_PAR_MIRROR, 1.0, smoothstep(0.0, NEAR_MIRROR, rough)) * (1.0 - SPEC_FOUND * found);+ cap = min(cap, 1.0 + (SPEC_SLIDE + SPEC_SLIDE_ROUGH * rough * rough) / max(par * counts, 1.0e-6));}- s_out = select(max(s_out, vec3<f32>(0.0)), vec3<f32>(0.0), non_finite(s_out));+ if (live) {+ let sharp = mix(SPEC_LIVE_MIRROR, SPEC_LIVE_GLOSS, smoothstep(0.0, SPEC_GLOSS, rough));+ cap = min(cap, mix(sharp, max(L.misc.y, sharp), smoothstep(SPEC_GLOSS, SPEC_VIRT_ROUGH, rough)));+ }+ // What the clamp took shortens the history by the same share, as the chart's signal does (the response's rule),+ // but not below CHART_MATURE frames, and the chart's level does not start again for it as it does with a history+ // the chart itself cut. The clamp leaves the history at the band's edge, still off (by several times the light+ // where the samples are noisy), and the chart is what follows the rest: a history too short to count in it, or+ // a level learnt against a history still off, and the chart went quiet. (A synthetic signal through this pass,+ // the lamp's pool 8 frames after it went out, over the settled frame: 1.58 so, 1.23 as it is; and not+ // shortened at all, the pool 8 frames after the lamp came on: 0.88 for 0.94.)+ let plain = 1.0 / max(min(h.w + 1.0, cap), 1.0);+ let a = max(plain + drop * (1.0 - plain), min(plain + clamped * (1.0 - plain), max(plain, 1.0 / CHART_MATURE)));+ let count_s = 1.0 / a;+ let count_chart = 1.0 / (plain + drop * (1.0 - plain));+ let s_out = max(mix(h.rgb, cur, a), vec3<f32>(0.0));spec_hist[this_half(q)] = vec4<f32>(s_out, count_s);spec_store(0u, q, vec4<f32>(s_out, count_s));+ var state = 0.0;+ if (t > 0.0) {+ state = spec_chart_pack(mix(mix(chart.x, share, chart_level_weight(count_chart)), 1.0 / (2.0 + CHART_CHANNEL), risen), mix(chart.y, res, CHART_A), sqrt(mix(chart.z, res * res, CHART_A)), chart_dither(q).x);+ }+ diffuse_mom[this_half(q)].z = state;// `moves`: a moving object's surface that crossed a traced sample this frame. One that moved less (a leaf in the// wind, a walker far away) has not left its place among the nine: what it shows and hides is the jitter's, as at// a still edge, and the rules for what a moving object uncovers made every such edge start again each frame.@@ -931,6 +1282,12 @@ fn stemporal(@builtin(global_invocation_id) gid: vec3<u32>) {gbuffer[this_half(q)] = gb_pack(n, depth, rough, swept);}+// The specular filter's reach (traced pixels) a unit of roughness squared. bench-window's rooms-turn (a floor of+// roughness 0.3 under 768 lamps, turning), p99 dE to offline at the last moving frame and 30 frames after the+// stop: 3.88 and 2.74 at 25 (the floor got the first pass alone), 3.32 and 2.43 from 64 on (all three; the previous+// release: 3.44 and 2.50).+const SPEC_REACH: f32 = 64.0;+// The specular filter (`spec_filter`'s kernel) on the traced grid: three passes over `spec_pp`, slot 0 -> 1 -> 0 -> 1.fn spec_filter_traced(gid: vec3<u32>, step: i32, from_a: bool) {let w = L.isz.x;@@ -942,7 +1299,11 @@ fn spec_filter_traced(gid: vec3<u32>, step: i32, from_a: bool) {let g = gb_unpack(gbuffer[this_half(i)]);let rough = g.rough;let fresh = c.w < 4.0;- let reach = select(4.0 * clamp(rough * 8.0, 0.0, 1.0), 4.0, fresh);+ // How far the filter reaches at this roughness (traced pixels; a pass of `step` runs when that is within it): by+ // the lobe's width, which goes with roughness squared (the alpha of this renderer's microfacet lobe). None on a+ // mirror, whose image has nothing to average with; the first pass from roughness 0.125, the second from 0.18,+ // all three from 0.25.+ let reach = SPEC_REACH * rough * rough;let npow = select(64.0, 8.0, fresh);let strength = (0.25 + smoothstep(0.08, 0.5, rough)) / sqrt(max(c.w, 1.0)) * 4.0;var outv = c.rgb;@@ -1644,79 +2005,129 @@ fn exposure_scale() -> f32 {fn qw() -> u32 { return (L.size.x + 3u) / 4u; }fn qh() -> u32 { return (L.size.y + 3u) / 4u; }-// Quarter-resolution log2 luminance (UE eye adaptation: uniform RGB weights) and the UE histogram (64 buckets over-// [log min, log max], each sample split between its two buckets).+// The exposure the frame's metering and thresholds go by: the manual one, or auto exposure's as the last frame left+// it (its first frame: the exposure the view starts with).+fn metering_exposure() -> f32 {+ if (L.ae2.w > 0.5 && ae_state[0].w > 0.5) { return ae_state[0].x; }+ return L.misc.x;+}++const AE_BINS: u32 = 64u;+// What a sample's position in the histogram's range (0 .. 1) is multiplied by in a bin's sum: as fine as 32 bits hold+// for every quarter-resolution texel in one bin.+fn ae_fix() -> f32 { return min(65536.0, floor(4.0e9 / f32(qw() * qh()))); }++// How much of a pixel blooms (post.rs `bloom_share`): all of it under a negative threshold, else from the threshold+// (exposed luminance) to one unit above it.+fn bloom_share(exposed: f32) -> f32 {+ if (L.post.z < 0.0) { return 1.0; }+ return clamp(exposed - L.post.z, 0.0, 1.0);+}++// The quarter-resolution view of the image (`fa`, unexposed), one read of it for three users. Per 4 x 4 block: the+// log2 of its mean luminance into `lumq` (`lum_blur` and local exposure read it; not under 12 stops below middle grey+// at the frame's exposure, post.rs `log_floor`); the same into auto exposure's histogram (`ae_bins`: a count and the+// sum of the positions in the range per bin; luminances outside the range are not counted, post.rs `exposure_scale`);+// and the mean of what blooms with that log2 luminance as the bloom pyramid's level 0 (post.rs `Pyramid`).@compute @workgroup_size(8, 8, 1)fn lum_down(@builtin(global_invocation_id) gid: vec3<u32>) {if (gid.x >= qw() || gid.y >= qh()) { return; }- var acc = vec3<f32>(0.0);+ let e = metering_exposure();+ var glow = vec3<f32>(0.0);+ var sum = 0.0;var n = 0.0;- for (var y = 0u; y < 4u; y++) {- for (var x = 0u; x < 4u; x++) {- let sx = gid.x * 4u + x;- let sy = gid.y * 4u + y;- if (sx < L.size.x && sy < L.size.y) {- acc += finite_or_zero(fa[sy * L.size.x + sx].rgb);- n += 1.0;- }+ for (var y = gid.y * 4u; y < min(gid.y * 4u + 4u, L.size.y); y++) {+ for (var x = gid.x * 4u; x < min(gid.x * 4u + 4u, L.size.x); x++) {+ let c = finite_or_zero(max(fa[y * L.size.x + x].rgb, vec3<f32>(0.0)));+ let l = lum(c);+ glow += c * bloom_share(l * e);+ sum += l;+ n += 1.0;}}- let c = acc / max(n, 1.0);- let ll = log2(max((c.r + c.g + c.b) / 3.0, 1e-6));- lumq[gid.y * qw() + gid.x] = ll;- if (L.ae2.w > 0.5) {- let fb = clamp((ll - L.ae.z) / (L.ae.w - L.ae.z), 0.0, 1.0) * 63.0;- let b0 = min(u32(floor(fb)), 63u);- let w1 = fb - f32(b0);- atomicAdd(&ae_bins[b0], u32((1.0 - w1) * 256.0 + 0.5));- atomicAdd(&ae_bins[min(b0 + 1u, 63u)], u32(w1 * 256.0 + 0.5));+ let mean = sum / max(n, 1.0);+ let floor_l = log2(0.18 / 4096.0 / max(e, 1e-20));+ var l2 = floor_l;+ if (mean > 0.0) {+ l2 = log2(mean);+ if (L.ae2.w > 0.5) {+ let t = (l2 - L.ae.z) / (L.ae.w - L.ae.z);+ if (t >= 0.0 && t <= 1.0) {+ let b = min(u32(t * f32(AE_BINS)), AE_BINS - 1u);+ atomicAdd(&ae_bins[b], 1u);+ atomicAdd(&ae_bins[AE_BINS + b], u32(t * ae_fix() + 0.5));+ }+ }}+ let q = gid.y * qw() + gid.x;+ lumq[q] = max(l2, floor_l);+ if (L.misc.w > 0.5) { bloom_a[q] = vec4<f32>(glow / max(n, 1.0), max(l2, floor_l)); }}-// UE ComputeAverageLuminanceWithoutOutlier + EyeAdaptationCommon: average log2 luminance between the low / high-// percentiles, target exposure = 2^bias * 0.18 / clamp(average, min, max), adapted at the up / down speed.+// Beyond this distance from its target (stops) auto exposure moves at its speed; within it, it closes in+// exponentially (no stop at the speed's last step). Unreal's documentation describes the same two regimes and this+// default distance.+const AE_EASE: f32 = 1.5;++// Auto exposure (L.ae2.w > 0.5) from the histogram, into `ae_state[0]` = (exposure scale, its target, log2 of the+// metered average luminance, 1 = valid): post.rs `metered_average` (the average luminance between the low and the+// high fraction of the histogram) and `auto_target` (middle grey x compensation over it, the average within its+// limits), then the exposure moved toward the target at the speed for a scene that got brighter / darker (L.ae3;+// snapped on a reset). One invocation does it and clears the histogram for the next frame.@compute @workgroup_size(64, 1, 1)fn exposure(@builtin(local_invocation_id) lid: vec3<u32>) {- if (lid.x != 0u) { return; }- var h: array<f32, 64>;+ if (lid.x != 0u || L.ae2.w < 0.5) { return; }+ let prev = ae_state[0];var total = 0.0;- var mean_sum = 0.0;- for (var i = 0u; i < 64u; i++) {- h[i] = f32(atomicLoad(&ae_bins[i])) / 256.0;- atomicStore(&ae_bins[i], 0u);- total += h[i];- mean_sum += h[i] * (L.ae.z + f32(i) / 63.0 * (L.ae.w - L.ae.z));- }- if (L.ae2.w < 0.5 || total <= 0.0) { return; }- var min_f = min(L.ae.x, L.ae.y) * total;- var max_f = L.ae.y * total;- var sum = 0.0;- var cnt = 0.0;- for (var i = 0u; i < 64u; i++) {- var v = h[i];- let sub = min(v, min_f);- v -= sub;- min_f -= sub;- max_f -= sub;- v = min(v, max_f);- max_f -= v;- sum += v * (L.ae.z + f32(i) / 63.0 * (L.ae.w - L.ae.z));- cnt += v;+ for (var b = 0u; b < AE_BINS; b++) { total += f32(atomicLoad(&ae_bins[b])); }+ var goal = select(L.misc.x, prev.y, prev.w > 0.5);+ var avg_log = prev.z;+ if (total > 0.0) {+ let lo = clamp(L.ae.x, 0.0, 1.0) * total;+ let hi = max(clamp(L.ae.y, 0.0, 1.0), clamp(L.ae.x, 0.0, 1.0)) * total;+ let fix = ae_fix();+ var seen = 0.0;+ var sum = 0.0;+ var n = 0.0;+ var at_low = -1.0;+ for (var b = 0u; b < AE_BINS; b++) {+ let c = f32(atomicLoad(&ae_bins[b]));+ if (c > 0.0) {+ let l = exp2(L.ae.z + f32(atomicLoad(&ae_bins[AE_BINS + b])) / (c * fix) * (L.ae.w - L.ae.z));+ let part = min(seen + c, hi) - max(seen, lo);+ if (part > 0.0) {+ sum += part * l;+ n += part;+ }+ // (A window narrower than one sample: the sample at the low bound.)+ if (at_low < 0.0 && seen + c >= lo) { at_low = l; }+ }+ seen += c;+ }+ var avg = at_low;+ if (n > 0.0) { avg = sum / n; }+ if (avg > 0.0) {+ goal = 0.18 * L.ae2.x / clamp(avg, L.ae2.y, L.ae2.z);+ avg_log = log2(avg);+ }}- let avg = select(L.ae2.y, exp2(sum / cnt), cnt > 0.0);- let target_ = L.ae2.x * 0.18 / clamp(avg, L.ae2.y, L.ae2.z);- var e = target_;- let prev = ae_state[0];- if (prev.w > 0.5 && L.ae3.w < 0.5) {- let d = log2(target_) - log2(prev.x);- let speed = select(L.ae3.y, L.ae3.x, d > 0.0);- let step = speed * L.ae3.z;- e = exp2(log2(prev.x) + clamp(d, -step, step));+ var e = goal;+ if (prev.w > 0.5 && prev.x > 0.0 && L.ae3.w < 0.5) {+ // Stops still to go: positive when the scene got brighter (the exposure has to come down).+ let d = log2(prev.x / goal);+ let speed = select(L.ae3.y, L.ae3.x, d > 0.0) * L.ae3.z;+ let far = max(abs(d) - AE_EASE, 0.0);+ let linear = min(far, speed);+ // (What of the frame's time the linear part did not use closes in exponentially.)+ var rest = abs(d) - linear;+ if (far <= speed) { rest *= exp(-(speed - linear) / AE_EASE); }+ e = goal * exp2(sign(d) * rest);}- ae_state[0] = vec4<f32>(e, target_, mean_sum / total, 1.0);+ ae_state[0] = vec4<f32>(e, goal, avg_log, 1.0);+ for (var b = 0u; b < 2u * AE_BINS; b++) { atomicStore(&ae_bins[b], 0u); }}-// Edge-aware blur of the quarter-res log luminance (stand-in for UE's bilateral grid): range weight on log2 lum.+// Edge-aware blur of the quarter-res log luminance (local exposure's base layer): range weight on log2 lum.@compute @workgroup_size(8, 8, 1)fn lum_blur(@builtin(global_invocation_id) gid: vec3<u32>) {let W = qw();@@ -1739,155 +2150,200 @@ fn lum_blur(@builtin(global_invocation_id) gid: vec3<u32>) {lumb[gid.y * W + gid.x] = acc / ws;}-// UE local exposure (CalculateLogLocalExposure, zero thresholds) for exposed log2 luminance `l`.-fn local_exposure(l: f32, x: f32, y: f32, e: f32) -> f32 {+// Local exposure's factor (post.rs `local_exposure_factor`: a base / detail decomposition of log luminance) for exposed+// log2 luminance `l` at output pixel (x, y), exposure scale `e`: the base is `lumb` (the edge-aware blur of `lumq`)+// blended with `wide` (the wide plain blur, the bloom pyramid's fourth channel) by L.lx.z; its distance from the pivot+// (middle grey, times auto exposure's compensation) is scaled by L.lx.x above and L.lx.y below, the detail by L.lx.w.+fn local_exposure(l: f32, x: f32, y: f32, e: f32, wide: f32) -> f32 {if (L.lx.x == 1.0 && L.lx.y == 1.0 && L.lx.w == 1.0) { return 1.0; }- let qx = clamp(u32(x / 4.0), 0u, qw() - 1u);- let qy = clamp(u32(y / 4.0), 0u, qh() - 1u);- let bil = lumb[qy * qw() + qx] + log2(e);- let wide = select(bil, ae_state[0].z + log2(e), L.ae2.w > 0.5);- let base = mix(bil, wide, L.lx.z);- let mid = log2(0.18 * L.ae2.x);- let contrast = select(L.lx.y, L.lx.x, base > mid);- return exp2((base - mid) * (contrast - 1.0) + (l - base) * (L.lx.w - 1.0));+ let p = (vec2<f32>(x, y) + 0.5) / 4.0 - 0.5;+ let p0 = vec2<i32>(floor(p));+ let f = p - floor(p);+ let hi = vec2<i32>(i32(qw()) - 1, i32(qh()) - 1);+ let a = clamp(p0, vec2<i32>(0), hi);+ let b = clamp(p0 + 1, vec2<i32>(0), hi);+ let W = i32(qw());+ let edge = mix(mix(lumb[a.y * W + a.x], lumb[a.y * W + b.x], f.x), mix(lumb[b.y * W + a.x], lumb[b.y * W + b.x], f.x), f.y);+ let le = log2(max(e, 1e-20));+ let base = mix(edge, wide, L.lx.z) + le;+ let pivot = log2(0.18 * select(1.0, L.ae2.x, L.ae2.w > 0.5));+ let o = pivot + (base - pivot) * select(L.lx.y, L.lx.x, base > pivot) + (l - base) * L.lx.w;+ return exp2(clamp(o - l, -8.0, 8.0));}// ------------------------------------------------------------------------------------------------ bloom-// Pyramid level j (0..4) is 1/4 .. 1/64 resolution; bloom stage k (0..5) blurs level max(k - 1, 0) (UE stage k runs at-// 1/2^(k+1); stage 0 at 1/4 here). bloom_a holds the five levels, then the six stage sums.-fn bw() -> u32 { return (L.size.x + 3u) / 4u; }-fn bh() -> u32 { return (L.size.y + 3u) / 4u; }-fn lvl_dim(j: u32) -> vec2<u32> { return vec2<u32>((bw() + (1u << j) - 1u) >> j, (bh() + (1u << j) - 1u) >> j); }-fn lvl_off(j: u32) -> u32 {+// Bloom (post.rs `BloomPlan`, `Pyramid`: the same arithmetic on the CPU): a sum of Gaussians of the picture, one a+// stage, as a weighted sum of the levels of an image pyramid (Burt & Adelson 1983, "The Laplacian Pyramid as a+// Compact Image Code": each level the one above under a small binomial kernel, at half the resolution) with the+// Gaussians wider than its coarsest level summed directly on that level's few texels. Level 0 is `lum_down`'s+// (a quarter of the output each way), `bloom_down1..5` make the rest, `bloom_wide_rows` and `bloom_wide` the coarsest+// level's part of the sum, `bloom_up4..0` add each level by its weight to the sum from below, bilinearly; `bloom_at`+// reads level 0. The fourth channel carries log2 luminance through the same passes with weights of its own: the wide+// blur local exposure blends its base with. 12 passes after `lum_down`, of 1/64 of the output's pixels and less. A stage+// narrower than level 0 can be (under about 2 output pixels: the first stages of a small output) is blended with a+// five-pixel kernel of the output's own pixels in `post`.+// (The offline chain takes each stage's Gaussian to its own shape, post.rs `gaussian`: next to a light hundreds of+// times brighter than its surroundings the pyramid's compact kernels end sooner than a Gaussian's tail.)+const BLOOM_TOP: u32 = 5u;++fn bloom_size(j: u32) -> vec2<u32> {+ var d = vec2<u32>(qw(), qh());+ for (var k = 0u; k < j; k++) { d = (d + 1u) / 2u; }+ return max(d, vec2<u32>(1u));+}++// Where level j starts in `bloom_a` (BLOOM_TOP + 1: `bloom_wide`'s sum; after it, `bloom_wide_rows`' copies).+fn bloom_base(j: u32) -> u32 {+ var d = max(vec2<u32>(qw(), qh()), vec2<u32>(1u));var o = 0u;- for (var i = 0u; i < j; i++) { let d = lvl_dim(i); o += d.x * d.y; }+ for (var k = 0u; k < j; k++) {+ o += d.x * d.y;+ if (k < BLOOM_TOP) { d = max((d + 1u) / 2u, vec2<u32>(1u)); }+ }return o;}-fn stage_lvl(k: u32) -> u32 { return max(k, 1u) - 1u; }-fn stage_off(k: u32) -> u32 {- var o = lvl_off(5u);- for (var i = 0u; i < k; i++) { let d = lvl_dim(stage_lvl(i)); o += d.x * d.y; }- return o;++fn bloom_texel(base: u32, d: vec2<u32>, x: i32, y: i32) -> vec4<f32> {+ return bloom_a[base + u32(clamp(y, 0, i32(d.y) - 1)) * d.x + u32(clamp(x, 0, i32(d.x) - 1))];}-fn stage_radius(k: u32) -> f32 { return select(L.br2[(k - 4u) & 1u], L.br[k & 3u], k < 4u); }-fn stage_tint(k: u32) -> f32 { return select(L.bt2[(k - 4u) & 1u], L.bt[k & 3u], k < 4u); }-@compute @workgroup_size(8, 8, 1)-fn bloom_down(@builtin(global_invocation_id) gid: vec3<u32>) {- if (gid.x >= bw() || gid.y >= bh()) { return; }- var acc = vec3<f32>(0.0);- var n = 0.0;- for (var y = 0u; y < 4u; y++) {- for (var x = 0u; x < 4u; x++) {- let sx = gid.x * 4u + x;- let sy = gid.y * 4u + y;- if (sx < L.size.x && sy < L.size.y) {- acc += finite_or_zero(fa[sy * L.size.x + sx].rgb);- n += 1.0;- }+fn bloom_bilinear(base: u32, d: vec2<u32>, p: vec2<f32>) -> vec4<f32> {+ let p0 = vec2<i32>(floor(p));+ let f = p - floor(p);+ return mix(mix(bloom_texel(base, d, p0.x, p0.y), bloom_texel(base, d, p0.x + 1, p0.y), f.x), mix(bloom_texel(base, d, p0.x, p0.y + 1), bloom_texel(base, d, p0.x + 1, p0.y + 1), f.x), f.y);+}++// Level j from level j - 1: the binomial [1 3 3 1] / 8 each way, centred between its texels.+fn bloom_down(gid: vec3<u32>, j: u32) {+ let d = bloom_size(j);+ if (L.misc.w < 0.5 || gid.x >= d.x || gid.y >= d.y) { return; }+ let sd = bloom_size(j - 1u);+ let so = bloom_base(j - 1u);+ var s = vec4<f32>(0.0);+ for (var dy = 0; dy < 4; dy++) {+ for (var dx = 0; dx < 4; dx++) {+ let k = select(0.375, 0.125, dx == 0 || dx == 3) * select(0.375, 0.125, dy == 0 || dy == 3);+ s += bloom_texel(so, sd, i32(gid.x) * 2 + dx - 1, i32(gid.y) * 2 + dy - 1) * k;}}- var c = acc / max(n, 1.0) * exposure_scale();- if (L.post.z > 0.0) {- // UE bloom threshold: Color * saturate((Luminance - Threshold) * 0.5), Luminance = dot(c, (0.3, 0.59, 0.11))- c *= clamp((dot(c, vec3<f32>(0.3, 0.59, 0.11)) - L.post.z) * 0.5, 0.0, 1.0);- }- bloom_a[gid.y * bw() + gid.x] = vec4<f32>(c, 1.0);-}--// Level j from level j - 1 (2x2 box, edge clamped).-fn bloom_downsample(gid: vec3<u32>, j: u32) {- let d = lvl_dim(j);- if (gid.x >= d.x || gid.y >= d.y) { return; }- let s = lvl_dim(j - 1u);- let so = lvl_off(j - 1u);- var acc = vec3<f32>(0.0);- for (var k = 0u; k < 4u; k++) {- let x = min(gid.x * 2u + (k & 1u), s.x - 1u);- let y = min(gid.y * 2u + (k >> 1u), s.y - 1u);- acc += bloom_a[so + y * s.x + x].rgb;- }- bloom_a[lvl_off(j) + gid.y * d.x + gid.x] = vec4<f32>(acc * 0.25, 1.0);-}--// UE Compute1DGaussianFilterKernel: weights exp(-16.7 (x/R)^2), R clamped to 31 texels.-fn bloom_blur(gid: vec3<u32>, k: u32, horizontal: bool) {- let j = stage_lvl(k);- let d = lvl_dim(j);- if (gid.x >= d.x || gid.y >= d.y) { return; }- let rf = clamp(stage_radius(k), 1e-4, 31.0);- let r = i32(ceil(rf));- let src = select(0u, lvl_off(j), horizontal);- var acc = vec3<f32>(0.0);- var ws = 0.0;- for (var t = -r; t <= r; t++) {- let x = select(i32(gid.x), clamp(i32(gid.x) + t, 0, i32(d.x) - 1), horizontal);- let y = select(clamp(i32(gid.y) + t, 0, i32(d.y) - 1), i32(gid.y), horizontal);- let wt = exp(-16.7 * (f32(t) / rf) * (f32(t) / rf));- let q = u32(y) * d.x + u32(x);- acc += select(bloom_b[q].rgb, bloom_a[src + q].rgb, horizontal) * wt;- ws += wt;+ bloom_a[bloom_base(j) + gid.y * d.x + gid.x] = s;+}++@compute @workgroup_size(8, 8, 1)+fn bloom_down1(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_down(gid, 1u); }+@compute @workgroup_size(8, 8, 1)+fn bloom_down2(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_down(gid, 2u); }+@compute @workgroup_size(8, 8, 1)+fn bloom_down3(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_down(gid, 3u); }+@compute @workgroup_size(8, 8, 1)+fn bloom_down4(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_down(gid, 4u); }+@compute @workgroup_size(8, 8, 1)+fn bloom_down5(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_down(gid, 5u); }++// The Gaussians wider than the pyramid, summed on the coarsest level's texels within L.bl2.z of each (the edge texels+// repeat outward), each way in turn: a Gaussian is the product of its two axes, so one pass blurs the rows once per+// Gaussian (its own copy of the level behind the pyramid in `bloom_a`: BLOOM_TOP + 2 + k; the last for the fourth+// channel's) and the next the columns, adding them by their weights (L.bw; L.lb2.zw for the fourth channel) to the+// level's own share: the coarsest level's part of the sum (BLOOM_TOP + 1). Each kernel is divided by its own sum.+const BLOOM_WIDE: u32 = 6u;++fn bloom_wide_pair(k: u32) -> vec2<f32> {+ if (k == BLOOM_WIDE) { return L.lb2.zw; }+ let pair = L.bw[k / 2u];+ if ((k & 1u) == 0u) { return pair.xy; }+ return pair.zw;+}++@compute @workgroup_size(8, 8, 1)+fn bloom_wide_rows(@builtin(global_invocation_id) gid: vec3<u32>) {+ let d = bloom_size(BLOOM_TOP);+ let r = i32(L.bl2.z);+ if (L.misc.w < 0.5 || r <= 0 || gid.x >= d.x || gid.y >= d.y) { return; }+ let o = bloom_base(BLOOM_TOP);+ let n = d.x * d.y;+ for (var k = 0u; k <= BLOOM_WIDE; k++) {+ let pair = bloom_wide_pair(k);+ if (pair.x <= 0.0) { continue; }+ var s = vec4<f32>(0.0);+ var ws = 0.0;+ for (var dx = -r; dx <= r; dx++) {+ let g = exp(-f32(dx * dx) * pair.y);+ s += bloom_texel(o, d, i32(gid.x) + dx, i32(gid.y)) * g;+ ws += g;+ }+ bloom_a[o + (2u + k) * n + gid.y * d.x + gid.x] = s / ws;}- let i = gid.y * d.x + gid.x;- if (horizontal) {- bloom_b[i] = vec4<f32>(acc / ws, 1.0);- return;+}++@compute @workgroup_size(8, 8, 1)+fn bloom_wide(@builtin(global_invocation_id) gid: vec3<u32>) {+ let d = bloom_size(BLOOM_TOP);+ if (L.misc.w < 0.5 || gid.x >= d.x || gid.y >= d.y) { return; }+ let o = bloom_base(BLOOM_TOP);+ let n = d.x * d.y;+ let own = bloom_a[o + gid.y * d.x + gid.x];+ var sum = vec4<f32>(own.rgb * L.bl2.y, own.w * L.lb2.y);+ let r = i32(L.bl2.z);+ for (var k = 0u; k <= BLOOM_WIDE; k++) {+ let pair = bloom_wide_pair(k);+ if (r <= 0 || pair.x <= 0.0) { continue; }+ var s = vec4<f32>(0.0);+ var ws = 0.0;+ for (var dy = -r; dy <= r; dy++) {+ let g = exp(-f32(dy * dy) * pair.y);+ s += bloom_texel(o + (2u + k) * n, d, i32(gid.x), i32(gid.y) + dy) * g;+ ws += g;+ }+ s *= pair.x / ws;+ if (k == BLOOM_WIDE) { sum.w += s.w; } else { sum += vec4<f32>(s.rgb, 0.0); }}- // Stage sum: this stage's blur * tint + the next (wider, coarser) stage's sum, bilinearly upsampled.- var c = acc / ws * stage_tint(k);- if (k < 5u) {- let dn = lvl_dim(stage_lvl(k + 1u));- let f = vec2<f32>(dn) / vec2<f32>(d);- let fx = clamp((f32(gid.x) + 0.5) * f.x - 0.5, 0.0, f32(dn.x - 1u));- let fy = clamp((f32(gid.y) + 0.5) * f.y - 0.5, 0.0, f32(dn.y - 1u));- c += sample_level(stage_off(k + 1u), dn, fx, fy);+ bloom_a[o + n + gid.y * d.x + gid.x] = sum;+}++// Level j becomes the sum from it down: itself by its weights, plus the level below's sum, bilinear.+fn bloom_up(gid: vec3<u32>, j: u32) {+ let d = bloom_size(j);+ if (L.misc.w < 0.5 || gid.x >= d.x || gid.y >= d.y) { return; }+ let o = bloom_base(j) + gid.y * d.x + gid.x;+ var src = j + 1u;+ if (src == BLOOM_TOP) { src = BLOOM_TOP + 1u; }+ let below = bloom_bilinear(bloom_base(src), bloom_size(j + 1u), (vec2<f32>(f32(gid.x), f32(gid.y)) + 0.5) / 2.0 - 0.5);+ let own = bloom_a[o];+ var wc = L.bl2[j & 3u];+ var wb = L.lb2[j & 3u];+ if (j < 4u) {+ wc = L.bl[j];+ wb = L.lb[j];}- bloom_a[stage_off(k) + i] = vec4<f32>(c, 1.0);-}--fn sample_level(off: u32, d: vec2<u32>, fx: f32, fy: f32) -> vec3<f32> {- let x0 = u32(floor(fx));- let y0 = u32(floor(fy));- let x1 = min(x0 + 1u, d.x - 1u);- let y1 = min(y0 + 1u, d.y - 1u);- let ax = fx - f32(x0);- let ay = fy - f32(y0);- let a = mix(bloom_a[off + y0 * d.x + x0].rgb, bloom_a[off + y0 * d.x + x1].rgb, ax);- let b = mix(bloom_a[off + y1 * d.x + x0].rgb, bloom_a[off + y1 * d.x + x1].rgb, ax);- return mix(a, b, ay);-}--@compute @workgroup_size(8, 8, 1) fn bloom_dn1(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_downsample(gid, 1u); }-@compute @workgroup_size(8, 8, 1) fn bloom_dn2(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_downsample(gid, 2u); }-@compute @workgroup_size(8, 8, 1) fn bloom_dn3(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_downsample(gid, 3u); }-@compute @workgroup_size(8, 8, 1) fn bloom_dn4(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_downsample(gid, 4u); }-@compute @workgroup_size(8, 8, 1) fn bloom_h5(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 5u, true); }-@compute @workgroup_size(8, 8, 1) fn bloom_v5(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 5u, false); }-@compute @workgroup_size(8, 8, 1) fn bloom_h4(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 4u, true); }-@compute @workgroup_size(8, 8, 1) fn bloom_v4(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 4u, false); }-@compute @workgroup_size(8, 8, 1) fn bloom_h3(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 3u, true); }-@compute @workgroup_size(8, 8, 1) fn bloom_v3(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 3u, false); }-@compute @workgroup_size(8, 8, 1) fn bloom_h2(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 2u, true); }-@compute @workgroup_size(8, 8, 1) fn bloom_v2(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 2u, false); }-@compute @workgroup_size(8, 8, 1) fn bloom_h1(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 1u, true); }-@compute @workgroup_size(8, 8, 1) fn bloom_v1(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 1u, false); }-@compute @workgroup_size(8, 8, 1) fn bloom_h0(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 0u, true); }-@compute @workgroup_size(8, 8, 1) fn bloom_v0(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_blur(gid, 0u, false); }--fn bloom_at(x: f32, y: f32) -> vec3<f32> {- let d = lvl_dim(0u);- return sample_level(stage_off(0u), d, clamp(x / 4.0 - 0.5, 0.0, f32(d.x - 1u)), clamp(y / 4.0 - 0.5, 0.0, f32(d.y - 1u)));+ bloom_a[o] = vec4<f32>(own.rgb * wc + below.rgb, own.w * wb + below.w);+}++@compute @workgroup_size(8, 8, 1)+fn bloom_up4(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_up(gid, 4u); }+@compute @workgroup_size(8, 8, 1)+fn bloom_up3(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_up(gid, 3u); }+@compute @workgroup_size(8, 8, 1)+fn bloom_up2(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_up(gid, 2u); }+@compute @workgroup_size(8, 8, 1)+fn bloom_up1(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_up(gid, 1u); }+@compute @workgroup_size(8, 8, 1)+fn bloom_up0(@builtin(global_invocation_id) gid: vec3<u32>) { bloom_up(gid, 0u); }++// The pyramid's sum at output pixel (x, y): rgb the bloom to add (unexposed), w the wide blur of log2 luminance.+fn bloom_at(x: f32, y: f32) -> vec4<f32> {+ return bloom_bilinear(0u, vec2<u32>(qw(), qh()), (vec2<f32>(x, y) + 0.5) / 4.0 - 0.5);}// ------------------------------------------------------------------------------------------------ depth of field-// Signed circle-of-confusion radius (output px) at view depth z (0 = sky), negative in front of the focus plane: UE's-// physical model (DiaphragmDOFUtils.cpp, FPhysicalCocModel): (z - focus) / z x the CoC of infinity, clamped to-// r.DOF.Kernel.MaxForeground / MaxBackgroundRadius (2.5 % of the width).+// The signed circle-of-confusion radius (output px) at view depth z (0 = sky: as far as can be), negative in front+// of the focus plane: a thin lens' (live/mod.rs `dof_params`: L.dof.x the radius of a point at infinity, L.dof.y the+// focus distance), r_inf (1 - s / z), held to the largest radius L.dof.z.fn dof_coc(z: f32) -> f32 {- let zz = select(1.0e9, z, z > 0.0);- return clamp((zz - L.dof.y) / zz * L.dof.x, -L.dof.z, L.dof.z);+ if (L.dof.x <= 0.0) { return 0.0; }+ if (z <= 0.0) { return min(L.dof.x, L.dof.z); }+ return clamp(L.dof.x * (1.0 - L.dof.y / z), -L.dof.z, L.dof.z);}const DOF_TILE: u32 = 16u;@@ -2093,56 +2549,87 @@ fn view_sample(@builtin(global_invocation_id) gid: vec3<u32>) {// ------------------------------------------------------------------------------------------------ post-// UE LinToLog (PostProcessCombineLUTs): LUT input encoding for the 32^3 tonemap LUT.-fn lin_to_log(c: vec3<f32>) -> vec3<f32> {- return clamp(log2(c) / 14.0 - log2(0.18) / 14.0 + 444.0 / 1023.0, vec3<f32>(0.0), vec3<f32>(1.0));-}-+// The colour table's axis (post.rs `lut_coord`): log2 of the exposed linear value over LUT_LOG_MIN .. LUT_LOG_MAX.+const LUT_LOG_MIN: f32 = -10.5;+const LUT_LOG_MAX: f32 = 6.5;+// post.rs `VIGNETTE_FIELD`, `FRINGE`, `GRAIN`.+const VIGNETTE_FIELD: f32 = 1.425;+const FRINGE: f32 = 0.002;+const GRAIN: f32 = 0.085;++// A 32-bit integer hash (Chris Wellons' "lowbias32", public domain: https://nullprogram.com/blog/2018/07/31/).+fn hash32(v: u32) -> u32 {+ var x = v;+ x ^= x >> 16u;+ x *= 0x7feb352du;+ x ^= x >> 15u;+ x *= 0x846ca68bu;+ x ^= x >> 16u;+ return x;+}++// The image (`fa`) at p (pixels, centres at integers), bilinear.+fn image_bilinear(p: vec2<f32>) -> vec3<f32> {+ let hi = vec2<i32>(i32(L.size.x) - 1, i32(L.size.y) - 1);+ let p0 = vec2<i32>(floor(p));+ let f = p - floor(p);+ let a = clamp(p0, vec2<i32>(0), hi);+ let b = clamp(p0 + 1, vec2<i32>(0), hi);+ let W = i32(L.size.x);+ return mix(mix(fa[a.y * W + a.x].rgb, fa[a.y * W + b.x].rgb, f.x), mix(fa[b.y * W + a.x].rgb, fa[b.y * W + b.x].rgb, f.x), f.y);+}++// The final pass: post.rs `finish`, step for step. Chromatic aberration (red and blue read from where the lens puts+// them: magnified / reduced about the centre), exposure, local exposure, bloom added, the cos^4 vignette, colour+// grading and the tone curve (the `lut` texture, live/targets.rs `tonemap_lut`: sRGB-encoded display values by the+// log2 of the exposed linear colour, trilinear), film grain, 8-bit output (BGRA in memory) into `out_px`.@compute @workgroup_size(8, 8, 1)fn post(@builtin(global_invocation_id) gid: vec3<u32>) {let w = L.size.x;let h = L.size.y;if (gid.x >= w || gid.y >= h) { return; }let i = gid.y * w + gid.x;- let x = f32(gid.x) + 0.5;- let y = f32(gid.y) + 0.5;let mode = L.mode.x;// (The view modes that show a buffer as it is are `view_raw`'s picture.)if (mode == 1u || mode == 2u || mode == 5u) { return; }- var src = fa[i].rgb;- 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;- let d = vec2<f32>(x / f32(w) - 0.5, y / f32(h) - 0.5);- let pr = vec2<i32>((vec2<f32>(0.5) + d * (1.0 + k)) * vec2<f32>(f32(w), f32(h)));- let pb = vec2<i32>((vec2<f32>(0.5) + d * (1.0 - k)) * vec2<f32>(f32(w), f32(h)));- let cr = clamp(pr, vec2<i32>(0), vec2<i32>(i32(w) - 1, i32(h) - 1));- let cb = clamp(pb, vec2<i32>(0), vec2<i32>(i32(w) - 1, i32(h) - 1));- src = vec3<f32>(fa[u32(cr.y) * w + u32(cr.x)].r, src.g, fa[u32(cb.y) * w + u32(cb.x)].b);- }let e = exposure_scale();- let ll = log2(max((src.r + src.g + src.b) / 3.0 * e, 1e-9));- var c = src * e * local_exposure(ll, x, y, e) + bloom_at(x, y) * L.misc.w;- if (L.misc.z > 0.0) {- let aspect = f32(h) / f32(w);- let scale = sqrt(2.0) / sqrt(1.0 + aspect * aspect);- let pos = vec2<f32>(x / f32(w) * 2.0 - 1.0, 1.0 - y / f32(h) * 2.0) * vec2<f32>(1.0, aspect) * scale * L.misc.z;- let t2 = dot(pos, pos);- let v = 1.0 / (t2 + 1.0);- c *= v * v;+ let centre = vec2<f32>(f32(w), f32(h)) * 0.5;+ let at = vec2<f32>(f32(gid.x), f32(gid.y)) + 0.5 - centre;+ var c = fa[i].rgb;+ if (L.post.x > 0.0) {+ let k = L.post.x * FRINGE;+ c = vec3<f32>(image_bilinear(centre + at * (1.0 - k) - 0.5).r, c.g, image_bilinear(centre + at * (1.0 + k) - 0.5).b);+ }+ c = finite_or_zero(max(c, vec3<f32>(0.0))) * e;+ if (L.misc.w > 0.5) {+ let glow = bloom_at(f32(gid.x), f32(gid.y));+ let floor_l = log2(0.18 / 4096.0);+ c *= local_exposure(max(log2(max(lum(c), 1e-30)), floor_l), f32(gid.x), f32(gid.y), e, glow.w);+ c += glow.rgb * e;}- let log_c = lin_to_log(max(c, vec3<f32>(0.0)) + 0.0026883);- let uvw = log_c * (31.0 / 32.0) + 0.5 / 32.0;- var srgb = textureSampleLevel(lut, lut_samp, uvw, 0.0).rgb;+ if (L.bl2.w > 0.0) {+ // The bloom stages narrower than the pyramid's first level (post.rs `BloomPlan::fine`; at output sizes where+ // there are any): the pixel and its four neighbours, a fifth each (a kernel of variance 0.4 each way).+ var s = vec3<f32>(0.0);+ for (var k = 0; k < 5; k++) {+ let x = u32(clamp(i32(gid.x) + select(0, k * 2 - 1, k < 2), 0, i32(w) - 1));+ let y = u32(clamp(i32(gid.y) + select(0, k * 2 - 5, k > 1 && k < 4), 0, i32(h) - 1));+ let t = finite_or_zero(max(fa[y * w + x].rgb, vec3<f32>(0.0)));+ s += t * bloom_share(lum(t) * e);+ }+ c += s * (0.2 * L.bl2.w * e);+ }+ let t = VIGNETTE_FIELD * L.misc.z * length(at) / length(centre);+ c /= (1.0 + t * t) * (1.0 + t * t);+ let n = f32(textureDimensions(lut).x);+ let u = clamp((log2(max(c, vec3<f32>(1e-9))) - LUT_LOG_MIN) / (LUT_LOG_MAX - LUT_LOG_MIN), vec3<f32>(0.0), vec3<f32>(1.0));+ var d = textureSampleLevel(lut, lut_samp, (u * (n - 1.0) + 0.5) / n, 0.0).rgb;if (L.post.y > 0.0) {- // Film grain: mid-tone weighted multiplicative noise, new every frame.- var hsh = (i ^ (L.size.z * 0x9e3779b9u)) * 747796405u + 2891336453u;- hsh = ((hsh >> ((hsh >> 28u) + 4u)) ^ hsh) * 277803737u;- hsh = (hsh >> 22u) ^ hsh;- let n = f32(hsh >> 8u) / 16777216.0 - 0.5;- let l = clamp(lum(srgb), 0.0, 1.0);- srgb *= 1.0 + L.post.y * n * 0.6 * max(1.0 - (2.0 * l - 1.0) * (2.0 * l - 1.0), 0.15);+ // Film grain (post.rs `grain`): zero-mean, triangular, the same on the three channels, most in the mid-tones.+ let r = hash32(gid.x ^ hash32(gid.y ^ hash32(L.size.z)));+ let v = lum(d);+ d += min(L.post.y, 1.0) * GRAIN * (f32(r & 0xffffu) / 65536.0 + f32(r >> 16u) / 65536.0 - 1.0) * 4.0 * v * (1.0 - v);}- let q = vec3<u32>(clamp(srgb, vec3<f32>(0.0), vec3<f32>(1.0)) * 255.0 + 0.5);+ let q = vec3<u32>(clamp(d, vec3<f32>(0.0), vec3<f32>(1.0)) * 255.0 + 0.5);out_px[i] = q.z | (q.y << 8u) | (q.x << 16u) | (255u << 24u); // BGRA in memory}diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgslindex 7211a94..654d053 100644--- a/renderer/shaders/pathtrace.wgsl+++ b/renderer/shaders/pathtrace.wgsl@@ -1,6 +1,6 @@// ThreeRT native path tracer. One sample per pixel per dispatch, accumulated in `accum`.// Shading model mirrors UE5 DefaultLit: Lambert diffuse + GGX / Smith-joint-approx / Schlick(F90 = saturate(50 F0.g)),-// with UE's GGX multi-scattering energy conservation and diffuse energy preservation.+// with GGX multiple-scattering energy compensation and diffuse energy preservation.// Material / atmosphere extensions: texture pages with ray-cone LOD, alpha cutout, world mapping,// wetness / puddles / ripples / grime, procedural facade windows, emissive animation, RIS many-light sampling, height// fog with volumetric single scattering. Each is compiled out when the scene does not use it (FEAT).@@ -185,7 +185,8 @@ struct Medium { w0: vec4<f32>, w1: vec4<f32>, w2: vec4<f32>, a: vec4<u32>, b: ve// - objects, per object (scene node): pivot (world position), world bounds size (UE ObjectPositionWS /// ObjectBounds), then what `OBJECT_STRIDE` says;// - instances (Instance), media (Medium);-// - the GGX energy LUT: (E.x, E.y) for 32 roughness x 32 NoV, two per vec4;+// - the GGX energy table (`energy_lookup`): the specular lobe's two albedo terms at 32 roughnesses x 32 sqrt(NoV), two+// nodes per vec4;// - the glass energy table (`glass_energy`): four values per vec4.// The buffer whole is `tables` in every layout (unsigned words: integers are read as they are, floats by a bit// cast): the light groups, the light tree and the energy LUT are read from it, and what a scene has more of is@@ -1046,9 +1047,9 @@ fn glass_at(h: Hit, d: vec3<f32>, t: f32) -> GlassAt {// through: water/furnace 1.16.)let r = (ior - 1.0) / (ior + 1.0);let f0 = r * r;- let e = energy_lookup(clamp(m.params.y, 0.02, 1.0), c);- let w = 1.0 + P.misc.z * f0 * ((1.0 - e.x) / e.x);- g.share = tr * (1.0 - w * (e.x * f0 + e.y * (clamp(50.0 * f0, 0.0, 1.0) - f0)));+ // What the interface lets through: all but the specular lobe's directional albedo at this roughness and angle (as+ // `lobes` has it: `spec_terms`).+ g.share = tr * (1.0 - spec_terms(vec3<f32>(f0), energy_lookup(clamp(m.params.y, 0.02, 1.0), c), P.misc.z).e.x);return g;}@@ -1564,24 +1565,49 @@ fn surface_proc(o: vec3<f32>, d: vec3<f32>, h: Hit, width: f32) -> Surface {}// -------------------------------------------------------------------------------------------------// BSDF (UE DefaultLit)--fn energy_lookup(roughness: f32, nov: f32) -> vec2<f32> {- let x = clamp(nov * 31.0, 0.0, 31.0);- let y = clamp(roughness * 31.0, 0.0, 31.0);- let x0 = u32(floor(x)); let y0 = u32(floor(y));- let x1 = min(x0 + 1u, 31u); let y1 = min(y0 + 1u, 31u);- let fx = x - f32(x0); let fy = y - f32(y0);- let a = mix(lut(x0, y0), lut(x1, y0), fx);- let b = mix(lut(x0, y1), lut(x1, y1), fx);- return mix(a, b, fy);-}--fn lut(x: u32, y: u32) -> vec2<f32> {- let i = y * 32u + x;- let v = energy_at(i / 2u);+// BSDF++// The specular lobe's directional albedo at a roughness and cos(view), as the two terms of the split sum (Karis,+// "Real Shading in Unreal Engine 4", SIGGRAPH 2013 course notes, "Environment BRDF"; with f90: Lagarde & de Rousiers+// 2014, eq. 58): with Schlick's Fresnel the lobe (`d_ggx` x `vis_smith_joint_approx`, single scattering) reflects+// f0 x .x + f90 x .y of a uniform surround, .x + .y at F = 1.+// From the table lib.rs `energy_lut` computes (`specular_albedo`): ENERGY_N x ENERGY_N nodes over sqrt(cos(view))+// (along a row) and the roughness, two nodes a vec4 (32 x 32 over sqrt(cos) and sqrt(alpha): the tables' shape of+// Kulla & Conty 2017 and Turquin 2019, section 3.1.1); between the nodes, bilinear.+const ENERGY_N: u32 = 32u;+fn energy_node(i: u32) -> vec2<f32> {+ let v = energy_at(i >> 1u);return select(v.xy, v.zw, (i & 1u) == 1u);}+fn energy_lookup(roughness: f32, nov: f32) -> vec2<f32> {+ let x = sqrt(clamp(nov, 0.0, 1.0)) * f32(ENERGY_N - 1u);+ let y = clamp(roughness, 0.0, 1.0) * f32(ENERGY_N - 1u);+ let x0 = min(u32(x), ENERGY_N - 2u);+ let y0 = min(u32(y), ENERGY_N - 2u);+ let i = y0 * ENERGY_N + x0;+ let fx = x - f32(x0);+ return mix(mix(energy_node(i), energy_node(i + 1u), fx), mix(energy_node(i + ENERGY_N), energy_node(i + ENERGY_N + 1u), fx), y - f32(y0));+}++// The specular lobe's Fresnel and energy terms for a reflectance at normal incidence `f0`, from the lobe's albedo terms+// `e` (`energy_lookup`).+// f90, the reflectance at grazing incidence: 1, fading to 0 as f0 falls below 2 %, less than any real material has, so+// that a material can switch its specular off: saturate(50 x the mean of f0) (Lagarde & de Rousiers, "Moving Frostbite+// to Physically Based Rendering", SIGGRAPH 2014 course notes, section 4.10.3, Listing 27, after Schuler, "An Efficient+// and Physically Plausible Real-Time Shading Model", ShaderX7; Filament's documentation, "Specular occlusion").+// w, the lobe's scale for the light that leaves the microsurface after more than one bounce, which the single-+// scattering lobe lacks: 1 + f0 (1 - E) / E, E = e.x + e.y the lobe's albedo at F = 1 (Turquin, "Practical multiple+// scattering compensation for microfacet models", 2019, eq. 16; the energy to return: Kulla & Conty, "Revisiting+// Physically Based Shading at Imageworks", SIGGRAPH 2017 course; Filament's documentation, "Energy loss in specular+// reflectance"). `comp` (P.misc.z) of it: at 0 the lobe is single scattering, at 1 a white (f0 = 1) lobe reflects all+// it receives (the white furnace test).+// e, the lobe's directional albedo with both: (f0 e.x + f90 e.y) w.+struct SpecTerms { f90: f32, w: vec3<f32>, e: vec3<f32> };+fn spec_terms(f0: vec3<f32>, e: vec2<f32>, comp: f32) -> SpecTerms {+ let f90 = clamp(dot(f0, vec3<f32>(50.0 / 3.0)), 0.0, 1.0);+ let w = 1.0 + f0 * (comp * (1.0 / max(e.x + e.y, 1e-3) - 1.0));+ return SpecTerms(f90, w, (f0 * e.x + f90 * e.y) * w);+}// Base layer: diffuse + GGX specular (e_spec: the specular's directional albedo; kd: what it leaves the diffuse// under it; p_spec: the specular share of the base's samples). Over it a clearcoat (GGX, F0 0.04; the base gets what@@ -1702,6 +1728,8 @@ fn lobes(s: Surface, nov: f32) -> Lobes {var l: Lobes;let t = s.transmission * (1.0 - s.metallic);l.diffuse = s.base * (1.0 - s.metallic) * (1.0 - t);+ // The dielectric's reflectance at normal incidence: `specular` 0..1 is 0..8 % (Burley, "Physically-Based Shading at+ // Disney", SIGGRAPH 2012 course notes, section 5.4: 0.5 is the 4 % of common dielectrics, ior 1.5).var f0 = 0.08 * s.specular;if (t > 0.0) {// Glass: F0 from the index of refraction.@@ -1709,11 +1737,14 @@ fn lobes(s: Surface, nov: f32) -> Lobes {f0 = r * r;}l.f0 = mix(vec3<f32>(f0), s.base, s.metallic);- l.f90 = vec3<f32>(clamp(50.0 * l.f0.g, 0.0, 1.0));- let e = energy_lookup(s.roughness, nov);- // misc.z = multiple-scattering compensation amount (1 = energy conserving, matches the white furnace).- l.w = 1.0 + P.misc.z * l.f0 * ((1.0 - e.x) / e.x);- l.e_spec = l.w * (e.x * l.f0 + e.y * (l.f90 - l.f0));+ // The specular lobe's grazing reflectance, its multiple-scattering scale (P.misc.z of it) and its directional+ // albedo (`spec_terms`); the diffuse under it gets what the lobe does not reflect toward the view, 1 - E_spec+ // (the specular's missing energy modulates the diffuse: Kulla & Conty 2017, "Microfacet Dielectrics - Diffuse+ // Term"; here by the view's albedo alone, not theirs of both directions).+ let st = spec_terms(l.f0, energy_lookup(s.roughness, nov), P.misc.z);+ l.f90 = vec3<f32>(st.f90);+ l.w = st.w;+ l.e_spec = st.e;l.kd = 1.0 - l.e_spec;if (has(F_GLASS) && t > 0.0) {// The share that is not the dielectric keeps this specular lobe (the diffuse, 1 - t of it already, under it).@@ -1728,9 +1759,10 @@ fn lobes(s: Surface, nov: f32) -> Lobes {if (wd <= 0.0) { l.p_spec = 1.0; }l.coat_alpha = 1.0;if (has(F_COAT) && s.coat > 0.0) {- let ec = energy_lookup(s.coat_rough, nov);l.coat = s.coat;- l.e_coat = s.coat * (ec.x * 0.04 + ec.y * 0.96);+ // The coat's directional albedo: a single-scattering lobe of F0 0.04 (ior 1.5), F90 1, at its own roughness.+ let ec = energy_lookup(s.coat_rough, nov);+ l.e_coat = s.coat * (0.04 * ec.x + ec.y);l.coat_alpha = s.coat_rough * s.coat_rough;}let under = 1.0 - l.e_coat;@@ -1751,21 +1783,35 @@ fn lobes(s: Surface, nov: f32) -> Lobes {return l;}+// The microfacet terms of the specular lobes (a2 = alpha^2, alpha = roughness^2: Burley 2012).+// The GGX (Trowbridge-Reitz) distribution of microfacet normals: Walter et al., "Microfacet Models for Refraction+// through Rough Surfaces", EGSR 2007, eq. 33, written over cos(theta_h): a2 / (pi ((n.h)^2 (a2 - 1) + 1)^2), the+// denominator arranged as in Lagarde & de Rousiers 2014, Listing 2 (`D_GGX`). (In f32 a mirror's a2, 1.6e-7 at the+// roughness floor of 0.02, is a few steps of n.h below 1: light samples see such a lobe coarsely whatever the+// arrangement; BSDF samples divide by the same D.)fn d_ggx(a2: f32, noh: f32) -> f32 {let d = (noh * a2 - noh) * noh + 1.0;return a2 / (PI * d * d);}+// The visibility V = G2 / (4 n.v n.l) of the height-correlated Smith masking-shadowing for GGX (Heitz, "Understanding+// the Masking-Shadowing Function in Microfacet-Based BRDFs", JCGT 2014: G2 = 1 / (1 + Lambda(v) + Lambda(l)), which is+// V = 0.5 / (n.l sqrt(a2 + (1 - a2) (n.v)^2) + n.v sqrt(a2 + (1 - a2) (n.l)^2))), with each square root+// sqrt(a2 + (1 - a2) c^2) replaced by alpha + (1 - alpha) c, exact at c = 0, c = 1, alpha = 0 and alpha = 1: the+// denominator becomes a blend of 2 n.l n.v and n.l + n.v by alpha (Hammon, "PBR Diffuse Lighting for GGX+Smith+// Microsurfaces", GDC 2017; Filament, `V_SmithGGXCorrelated_Fast`, Apache-2.0,+// https://github.com/google/filament/blob/main/shaders/src/surface_brdf.fs). No square root over the directions; the+// one here turns the lobes' a2 back into alpha. (lib.rs `specular_albedo` and `glass_energy` integrate this form.)fn vis_smith_joint_approx(a2: f32, nov: f32, nol: f32) -> f32 {- let a = sqrt(a2);- let v = nol * (nov * (1.0 - a) + a);- let l = nov * (nol * (1.0 - a) + a);- return 0.5 / max(v + l, 1e-7);+ return 0.5 / max(mix(2.0 * nol * nov, nol + nov, sqrt(a2)), 1e-7);}+// Fresnel reflectance by Schlick's approximation ("An Inexpensive BRDF Model for Physically-based Rendering", 1994)+// with a reflectance at grazing incidence: f0 + (f90 - f0) (1 - v.h)^5.fn f_schlick(f0: vec3<f32>, f90: vec3<f32>, voh: f32) -> vec3<f32> {- let fc = pow(1.0 - voh, 5.0);- return f0 + (f90 - f0) * fc;+ let c = 1.0 - voh;+ let c2 = c * c;+ return f0 + (f90 - f0) * (c2 * c2 * c);}// BSDF * NoL with the specular lobe scaled (per-light specular scale)@@ -2128,8 +2174,13 @@ fn local_light(li: Light, x: vec3<f32>, u: vec2<f32>) -> LS {atten *= win * win;}if (u32(li.pos.w) == 2u) {- let m = clamp((dot(-l, li.dir.xyz) - li.ext.x) * li.ext.y, 0.0, 1.0);- atten *= m * m;+ // The cone: nothing outside its half angle (ext.x its cosine), all of the light inside the inner cone, and+ // between them linear in the cosine of the angle from the axis (ext.y = 1 / the two cosines' difference),+ // squared: the angular attenuation of glTF 2.0 KHR_lights_punctual (its reference code, which is `getAngleAtt`+ // of Lagarde & de Rousiers, "Moving Frostbite to Physically Based Rendering", SIGGRAPH 2014 course notes,+ // Listing 4). The inner cone from `penumbra`: scene.rs `spot_cone`.+ let cone = clamp((dot(-l, li.dir.xyz) - li.ext.x) * li.ext.y, 0.0, 1.0);+ atten *= cone * cone;}let ls = lp - x;let dist = max(length(ls), 1e-6);diff --git a/renderer/src/desc.rs b/renderer/src/desc.rsindex bf22f67..0c90b43 100644--- a/renderer/src/desc.rs+++ b/renderer/src/desc.rs@@ -307,25 +307,30 @@ pub struct Preset {pub native: NativePreset,}+/// The post chain's settings (`post` of a preset; post.rs says what each does). Their names and meanings follow+/// Unreal's Post Process Volume settings as its documentation describes them, so that a scene's look can be compared+/// with the same settings there. The presets also carry a `tonemapper` block (Unreal's Film slope / toe / shoulder /+/// clips) for the comparison scripts in ue5/: the renderer's tone curve (`post::ToneCurve`) is fitted to the look+/// those values give and reads none of them.#[derive(Deserialize, Debug, Clone)]#[serde(rename_all = "camelCase")]pub struct PostPreset {- pub tonemapper: Tonemapper,pub color_grading: ColorGrading,pub bloom: Bloom,+ /// Vignette (0 = off): natural cos^4 falloff toward the corners (`post::vignette`).pub vignette: f32,pub auto_exposure: AutoExposure,- /// UE FilmGrainIntensity (0..1).+ /// Film grain (0..1; 0 = off): zero-mean luminance noise, strongest in the mid-tones, new each frame.#[serde(default)]pub film_grain: f32,- /// UE SceneFringeIntensity (chromatic aberration, 0..5).+ /// Chromatic aberration (0..5; 0 = off): red and blue apart, growing from the centre.#[serde(default)]pub chromatic_aberration: f32,- /// UE local exposure (bilateral): contrast of the low-frequency luminance around middle grey.+ /// Local exposure: contrast of the large-scale luminance about middle grey.#[serde(default)]pub local_exposure: LocalExposure,- /// UE motion blur (amount, max, target FPS; UE's defaults when absent). The presets switch it off, like their UE- /// references (r.MotionBlurQuality 0): stills and temporal benchmarks compare unblurred frames.+ /// Motion blur (amount, max, target FPS). The presets switch it off: stills and temporal benchmarks compare+ /// unblurred frames.#[serde(default)]pub motion_blur: MotionBlur,}@@ -333,11 +338,11 @@ pub struct PostPreset {#[derive(Deserialize, Debug, Clone)]#[serde(rename_all = "camelCase", default)]pub struct MotionBlur {- /// UE MotionBlurAmount: shutter as a fraction of the target frame time (0 = off).+ /// The shutter as a fraction of the frame time (0 = off).pub amount: f32,- /// UE MotionBlurMax: longest blur, percent of the screen width.+ /// Longest blur, percent of the view width.pub max: f32,- /// UE MotionBlurTargetFPS: blur length as if the game ran at this rate.+ /// Blur length as if the frames came at this rate (0: at the rate they come).pub target_fps: f32,}@@ -347,15 +352,18 @@ impl Default for MotionBlur {}}+/// Local exposure (`post::local_exposure_factor`): all three of the first at 1 = off.#[derive(Deserialize, Debug, Clone)]#[serde(rename_all = "camelCase", default)]pub struct LocalExposure {+ /// Scale of the base layer's distance above / below middle grey (< 1 compresses highlights / lifts shadows).pub highlight_contrast: f32,pub shadow_contrast: f32,+ /// Scale of the detail layer (> 1 boosts local detail).pub detail_strength: f32,- /// Base luminance = lerp(bilateral grid, wide blur, blend) (UE BlurredLuminanceBlend 0.6).+ /// The base layer: the edge-aware blur of log luminance, blended by this much with a wide plain blur.pub blurred_luminance_blend: f32,- /// Wide blur kernel, percent of the view width (UE 50).+ /// The wide blur's size, percent of the view width (a bloom stage's measure: `post::BloomPlan`).pub blurred_luminance_kernel: f32,}@@ -365,28 +373,25 @@ impl Default for LocalExposure {}}-#[derive(Deserialize, Debug, Clone)]-#[serde(rename_all = "camelCase")]-pub struct Tonemapper {- pub slope: f32,- pub toe: f32,- pub shoulder: f32,- pub black_clip: f32,- pub white_clip: f32,- pub tone_curve_amount: f32,-}-+/// Colour grading, on scene-linear colour before the tone curve (`post::Tonemapper`).#[derive(Deserialize, Debug, Clone)]#[serde(rename_all = "camelCase")]pub struct ColorGrading {+ /// Gamut expansion (0 = none, 1 = the presets' look): bright saturated colours are pushed beyond sRGB's gamut+ /// before the tone curve.+ #[serde(default = "one")]pub expand_gamut: f32,+ /// How much of the Academy's blue-light-artifact fix the tone curve works under (0 .. 1): bright blues+ /// desaturate instead of turning violet.+ #[serde(default = "blue")]pub blue_correction: f32,- /// UE white balance: the scene illuminant (K) that renders as white, and green-magenta tint.+ /// White balance: the scene illuminant (K) that renders as white, and its green-magenta tint.#[serde(default = "d65")]pub white_temp: f32,#[serde(default)]pub white_tint: f32,- /// UE ColorSaturation / ColorContrast (global), ColorGainShadows / ColorGainHighlights: scalar or RGB.+ /// Saturation and contrast of the whole picture, gain of its shadows and of its highlights: scalar or RGB,+ /// 1 = none.#[serde(default = "one3")]pub saturation: Rgb,#[serde(default = "one3")]@@ -426,29 +431,37 @@ fn d65() -> f32 {6500.0}+fn blue() -> f32 {+ 0.6+}++/// Bloom (`post::BloomPlan`): a sum of Gaussian blurs of the picture, added to it.#[derive(Deserialize, Debug, Clone)]#[serde(rename_all = "camelCase")]pub struct Bloom {+ /// Scale of the whole glow (0 = off).pub intensity: f32,+ /// Exposed luminance from which a pixel blooms, fading in over one unit above it (< 0: everything blooms).pub threshold: f32,+ /// The stages' sizes (percent of the view width, times `size_scale`) and weights: up to six.pub size_scale: f32,pub sizes: Vec<f32>,pub tints: Vec<f32>,}+/// Auto exposure's metering (`post::exposure_scale`).#[derive(Deserialize, Debug, Clone)]#[serde(rename_all = "camelCase")]pub struct AutoExposure {+ /// The percentiles of the luminance histogram between which the average is taken.pub low_percent: f32,pub high_percent: f32,- /// Histogram range, log2 luminance. The presets use UE 5's extended range (EV100 -10 .. 20, which with the default- /// lens attenuation 0.78 is the same log2 luminance: Scene.cpp, r.DefaultFeature.AutoExposure.- /// ExtendDefaultLuminanceRange, on in every UE 5 project template). UE's legacy range, -8 .. 4, saturates in- /// daylight (a 3000-nit sky would pin the exposure at EV 6.5); scenes ported from a project without the extended- /// range set it explicitly.+ /// The histogram's range, log2 luminance (nits). The presets use -10 .. 20, the extended range Unreal's+ /// documentation describes (there in EV100): a range of -8 .. 4 saturates in daylight (a 3000-nit sky would pin+ /// the exposure at its top); scenes ported from a project with that range set it explicitly.pub histogram_log_min: f32,pub histogram_log_max: f32,- /// Eye adaptation speed toward brighter / darker targets, EV per second (UE defaults 3 / 1; real-time only).+ /// Adaptation speed toward brighter / darker scenes, EV per second (real-time only).#[serde(default = "three")]pub speed_up: f32,#[serde(default = "one")]diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex 5e1ddbc..2cc0a10 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -1231,45 +1231,167 @@ pub fn sky_sampled(brightest: f32, floor: f32, has_env: bool) -> bool {brightest >= floor && (!has_env || env_nee_on())}-/// UE GGXEnergyLookup equivalent: E.x = integral of D*Vis*NoL (F = 1), E.y = same weighted by (1-VoH)^5.+/// The energy table's nodes (pathtrace.wgsl `ENERGY_N`): along a row sqrt(cos(view)) from 0 to 1 (the albedo changes+/// fastest at grazing views, where a table over the cosine itself is 20 times further off), over the rows the+/// roughness from 0 to 1.+pub const ENERGY_N: usize = 32;++/// The specular lobe's directional albedo toward a view at cosine `mu`, for `alpha` = roughness^2, as the two terms of+/// Karis's split sum ("Real Shading in Unreal Engine 4", SIGGRAPH 2013 course notes, "Environment BRDF"): with+/// Schlick's Fresnel F = f0 + (f90 - f0) (1 - v.h)^5 the lobe reflects f0 x `.0` + f90 x `.1` of a uniform white+/// surround, and `.0 + .1` at F = 1 (E(mu) of Kulla & Conty 2017). The lobe is the kernel's, single scattering: GGX D+/// (Walter et al. 2007) with the square-root-free height-correlated Smith visibility (`vis_smith_joint_approx`:+/// Hammon 2017).+/// The integral is taken over visible normals (Heitz, "Sampling the GGX Distribution of Visible Normals", JCGT 2018):+/// a light direction mirrored off a visible normal has density G1(v) D / (4 n.v), so the lobe's value x cosine over+/// it is F x (V 4 n.v n.l) / G1(v), bounded. Midpoint rule over the unit disk the normals are drawn from, `nr` rings+/// x 2 `nphi` angles (half of them computed: the lobe is symmetric about the plane of incidence). The rings crowd+/// toward the rim (u = 1 - (1 - t)^2), where the normals tilt far and the reflected ray nears the horizon: the+/// approximate visibility falls to 0 there over a range of n.l about alpha wide, which even rings miss (48 x 16+/// points: 1.6e-4 from the converged value; 24 x 24 even ones: 9e-3).+pub fn specular_albedo(mu: f64, alpha: f64, nr: usize, nphi: usize) -> (f64, f64) {+ let mu = mu.clamp(1e-4, 1.0);+ if alpha < 1e-6 {+ // A mirror: the half vector is the normal.+ let fc = (1.0 - mu).powi(5);+ return (1.0 - fc, fc);+ }+ // The view direction (in the x-z plane, n = +z) in the space where the visible normals' hemisphere is a half ball+ // (Heitz 2018, section 3); the basis around it is t1 = +y, t2 = (-vh.z, 0, vh.x).+ let (vx, vz) = ((1.0 - mu * mu).max(0.0).sqrt(), mu);+ let k = (alpha * alpha * vx * vx + vz * vz).sqrt();+ let (hx, hz) = (alpha * vx / k, vz / k);+ let s = 0.5 * (1.0 + hz);+ // 1 / G1(v) = 1 + Lambda(v) (Heitz 2014, "Understanding the Masking-Shadowing Function", GGX's Lambda).+ let inv_g1 = 0.5 * (1.0 + (1.0 + alpha * alpha * (1.0 - mu * mu) / (mu * mu)).sqrt());+ let (mut a, mut b) = (0.0, 0.0);+ for i in 0..nr {+ let t = (i as f64 + 0.5) / nr as f64;+ let (r, w) = ((1.0 - (1.0 - t) * (1.0 - t)).sqrt(), 2.0 * (1.0 - t));+ for j in 0..nphi {+ let phi = std::f64::consts::PI * ((j as f64 + 0.5) / nphi as f64 - 0.5);+ let p1 = r * phi.cos();+ let p2 = (1.0 - s) * (1.0 - p1 * p1).max(0.0).sqrt() + s * r * phi.sin();+ let pz = (1.0 - p1 * p1 - p2 * p2).max(0.0).sqrt();+ // The visible normal, stretched back.+ let m = [alpha * (pz * hx - p2 * hz), alpha * p1, (p2 * hx + pz * hz).max(0.0)];+ let len = (m[0] * m[0] + m[1] * m[1] + m[2] * m[2]).sqrt();+ let voh = (vx * m[0] + vz * m[2]) / len;+ let nol = 2.0 * voh * m[2] / len - vz;+ if nol <= 0.0 || voh <= 0.0 {+ continue;+ }+ // V x 4 n.v n.l, V = 0.5 / (n.l (n.v (1 - alpha) + alpha) + n.v (n.l (1 - alpha) + alpha)): the kernel's+ // 0.5 / mix(2 n.l n.v, n.l + n.v, alpha).+ let g2 = 2.0 * mu * nol / (nol * (mu * (1.0 - alpha) + alpha) + mu * (nol * (1.0 - alpha) + alpha));+ let fc = (1.0 - voh).powi(5);+ a += w * (1.0 - fc) * g2;+ b += w * fc * g2;+ }+ }+ let k = inv_g1 / (nr * nphi) as f64;+ (a * k, b * k)+}++/// The table pathtrace.wgsl's `energy_lookup` reads (`heap::Table::Energy`): `specular_albedo` at `ENERGY_N` x+/// `ENERGY_N` nodes, node (ix, iy) at cos(view) (ix / 31)^2 and roughness iy / 31, row after row, two nodes (four+/// numbers) a vec4. Computed once a process (about 10 ms).pub fn energy_lut() -> Vec<[f32; 4]> {- let n = 32usize;- let mut vals = vec![[0f32; 2]; n * n];- for ry in 0..n {- let roughness = (ry as f32 / (n - 1) as f32).max(0.02);- let a = roughness * roughness;- let a2 = a * a;- for vx in 0..n {- let nov = (vx as f32 / (n - 1) as f32).max(1e-3);- let v = Vec3::new((1.0 - nov * nov).sqrt(), 0.0, nov);- let (mut ex, mut ey) = (0.0f64, 0.0f64);- let samples = 1024;- for i in 0..samples {- // Hammersley + GGX NDF sampling of H.- let u1 = (i as f32 + 0.5) / samples as f32;- let u2 = (i as u32).reverse_bits() as f32 / 4294967296.0;- let phi = 2.0 * std::f32::consts::PI * u2;- let cos_t = ((1.0 - u1) / (1.0 + (a2 - 1.0) * u1)).sqrt();- let sin_t = (1.0 - cos_t * cos_t).sqrt();- let hv = Vec3::new(sin_t * phi.cos(), sin_t * phi.sin(), cos_t);- let l = 2.0 * v.dot(hv) * hv - v;- let (nol, noh, voh) = (l.z, hv.z, v.dot(hv));- if nol > 0.0 && voh > 0.0 {- let av = a;- let vis_v = nol * (nov * (1.0 - av) + av);- let vis_l = nov * (nol * (1.0 - av) + av);- let vis = 0.5 / (vis_v + vis_l);- // pdf_L = D * NoH / (4 VoH) => D*Vis*NoL / pdf = Vis * NoL * 4 VoH / NoH- let est = (vis * nol * 4.0 * voh / noh) as f64;- let fc = (1.0 - voh).powi(5) as f64;- ex += est;- ey += est * fc;+ static LUT: std::sync::OnceLock<Vec<[f32; 4]>> = std::sync::OnceLock::new();+ LUT.get_or_init(|| {+ let n = ENERGY_N;+ let mut vals = Vec::with_capacity(2 * n * n);+ for iy in 0..n {+ let r = iy as f64 / (n - 1) as f64;+ for ix in 0..n {+ let x = ix as f64 / (n - 1) as f64;+ let (a, b) = specular_albedo(x * x, r * r, 48, 8);+ vals.extend([a as f32, b as f32]);+ }+ }+ vals.chunks(4).map(|c| [c[0], c[1], c[2], c[3]]).collect()+ })+ .clone()+}++#[cfg(test)]+mod energy_tests {+ use super::*;++ /// The kernel's `energy_lookup`: the table between its nodes.+ fn lookup(lut: &[[f32; 4]], roughness: f64, mu: f64) -> (f64, f64) {+ let n = ENERGY_N;+ let node = |i: usize| (lut[i / 2][2 * (i % 2)] as f64, lut[i / 2][2 * (i % 2) + 1] as f64);+ let (x, y) = (mu.clamp(0.0, 1.0).sqrt() * (n - 1) as f64, roughness.clamp(0.0, 1.0) * (n - 1) as f64);+ let (x0, y0) = ((x as usize).min(n - 2), (y as usize).min(n - 2));+ let (fx, fy) = (x - x0 as f64, y - y0 as f64);+ let mix = |p: (f64, f64), q: (f64, f64), t: f64| (p.0 + (q.0 - p.0) * t, p.1 + (q.1 - p.1) * t);+ let i = y0 * n + x0;+ mix(mix(node(i), node(i + 1), fx), mix(node(i + n), node(i + n + 1), fx), fy)+ }++ /// The lobe's value x cosine integrated over the hemisphere of light directions at F = 1 (`n` x 2 `n` points,+ /// midpoint rule over theta and half the azimuth): what the kernel's light samples sum. The table's estimator is+ /// its sampling.+ fn quadrature(mu: f64, alpha: f64, n: usize) -> f64 {+ let a2 = alpha * alpha;+ let v = [(1.0 - mu * mu).sqrt(), mu];+ let mut sum = 0.0;+ for i in 0..n {+ let (st, c) = (std::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / n as f64).sin_cos();+ for j in 0..2 * n {+ let phi = std::f64::consts::PI * (j as f64 + 0.5) / (2 * n) as f64;+ let (x, z) = (st * phi.cos(), st * phi.sin());+ let h = [v[0] + x, v[1] + c, z];+ let noh = h[1] / (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt();+ let d = (noh * a2 - noh) * noh + 1.0;+ let vis = 0.5 / (c * (mu * (1.0 - alpha) + alpha) + mu * (c * (1.0 - alpha) + alpha));+ sum += a2 / (std::f64::consts::PI * d * d) * vis * c * st;+ }+ }+ sum * std::f64::consts::PI * std::f64::consts::PI / (2 * n * n) as f64+ }++ #[test]+ fn the_albedo_is_the_lobes_integral() {+ for (r, mu) in [(0.3, 0.9), (0.5, 0.7071), (0.5, 0.2), (0.8, 0.5), (1.0, 1.0), (1.0, 0.1), (0.25, 0.4)] {+ let ((a, b), q) = (specular_albedo(mu, r * r, 48, 8), quadrature(mu, r * r, 800));+ eprintln!("roughness {r}, cos {mu}: {a:.4} + {b:.4} = {:.4}; quadrature {q:.4}", a + b);+ assert!((a + b - q).abs() < 1e-3, "roughness {r}, cos {mu}: {:.4} for {q:.4}", a + b);+ }+ // A mirror reflects everything, by Fresnel at the view's angle; a smooth lobe nearly so.+ let (a, b) = specular_albedo(0.5, 0.0, 48, 8);+ assert!((a + b - 1.0).abs() < 1e-12 && (b - 0.5f64.powi(5)).abs() < 1e-12);+ let (a, b) = specular_albedo(0.5, 0.02 * 0.02, 48, 8);+ assert!((a + b - 1.0).abs() < 2e-3 && (b - 0.5f64.powi(5)).abs() < 2e-3, "{a} {b}");+ }++ #[test]+ fn the_table_follows_the_albedo_between_its_nodes() {+ let t = std::time::Instant::now();+ let lut = energy_lut();+ let ms = t.elapsed().as_secs_f64() * 1e3;+ assert_eq!(lut.len(), 512);+ assert!(lut.iter().flatten().all(|e| (0.0..=1.0 + 1e-4).contains(e)));+ // Between the nodes, at the kernel's roughnesses (0.02 and up) and all but the last half degree of grazing+ // views (below it a smooth lobe's albedo falls from 1 to a half within a cosine of alpha: no table follows).+ let (mut worst, mut at, mut sum) = (0.0f64, (0.0, 0.0), 0.0);+ for iy in 0..48 {+ let r = 0.02 + 0.98 * (iy as f64 + 0.37) / 48.0;+ for ix in 0..48 {+ let mu = 0.01 + 0.99 * (ix as f64 + 0.61) / 48.0;+ let ((a, b), (ta, tb)) = (specular_albedo(mu, r * r, 96, 12), lookup(&lut, r, mu));+ let e = (ta - a).abs().max((tb - b).abs()).max((ta + tb - a - b).abs() / (a + b));+ sum += e / (48.0 * 48.0);+ if e > worst {+ (worst, at) = (e, (r, mu));}}- vals[ry * n + vx] = [(ex / samples as f64).min(1.0) as f32, (ey / samples as f64) as f32];}+ eprintln!("energy table: {ms:.1} ms; error between nodes: mean {sum:.5}, worst {worst:.5} at roughness {:.3}, cos {:.3}", at.0, at.1);+ assert!(worst < 0.02 && sum < 0.002, "{worst} at {at:?}, mean {sum}");+ assert!(cfg!(debug_assertions) || ms < 50.0, "{ms} ms");}- vals.chunks(2).map(|c| [c[0][0], c[0][1], c[1][0], c[1][1]]).collect()}/// The glass energy table's nodes (pathtrace.wgsl GLASS_E_MU, _ROUGH, _IOR): cos(view) as its square root, roughness,diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex bf69df6..dbe182c 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -1128,7 +1128,7 @@ impl LiveCore {self.sc.up.kernel.features = self.kernel_features();}// Lighting changed: for 45 frames the histories hold HISTORY_LIVE frames at most (`live_lighting`), and where the- // change is strong the temporal pass cuts the history locally (anti-lag).+ // temporal passes' change charts find one they cut the history locally (live.wgsl "The response of the histories").if d.materials || d.lights || d.objects || changes.environment {self.lit_changed = self.frame.max(1);}diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex b53179c..669ba83 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -309,8 +309,8 @@ impl LiveCore {// the cap only bounds smearing of view-dependent shading (glossy reflections).// Diffuse lighting reprojects exactly with the camera; view-dependent specular is handled per pixel (temporal pass).// The most frames a pixel's history holds: HISTORY_LIVE while the scene's lighting changes, HISTORY_FRAMES once- // it has settled. Within it the length is each pixel's own (live.wgsl `dtemporal`: less where it moves, anti-lag- // where its lighting changes, restarted where its surface is new). No edit cuts it: until 2026-11-12 a+ // it has settled. Within it the length is each pixel's own (live.wgsl "The response of the histories": less+ // where it moves, cut by its change chart where its lighting changes, restarted where its surface is new). No edit cuts it: until 2026-11-12 a// lighting edit left every pixel 16 frames and a geometry edit 4, the whole frame for a change in one corner.let cap = if self.reset { 1.0 } else if self.live_lighting() { HISTORY_LIVE } else { HISTORY_FRAMES };self.history_len = if self.reset { 1.0 } else { (self.history_len + 1.0).min(cap) };@@ -563,16 +563,18 @@ impl LiveCore {}g.queue.submit([e.finish()]);}- let (r, t) = self.bloom;+ let b = &self.bloom;+ // Motion blur's length over this frame's motion: the shutter is open `amount` of a frame; with a target+ // frame rate, of a frame at that rate (the blur is as long at any real rate: a frame twice as short moves+ // half as far and is blurred twice its motion). 0 while nothing moves (the pass then costs nothing).+ let dt = self.frame_dt.clamp(1.0 / 240.0, 0.25);+ let shutter = if !blur { 0.0 } else if self.blur.1 > 0.0 { self.blur.0 / (self.blur.1 * dt) } else { self.blur.0 };let lp = LiveParams {cur: cam.uniform(self.aspect),prev: self.prev_cam.uniform(self.aspect),size: [w, h, self.frame, (self.reset || reconstruction.history_free()) as u32],- misc: [self.view.exposure, cap, self.vignette, (self.bloom.1.iter().sum::<f32>() > 0.0) as u32 as f32],- // misc2.z: motion blur, this frame's motion (pixels) -> blur length. UE (PostProcessMotionBlur.cpp,- // UpdateMotionBlurTimeScale) blurs over +- amount / 2 x the motion x (1 / target FPS) / frame time, the- // actual frame time without a target. 0 while nothing moves (the pass then costs nothing).- misc2: [1.0, SAMPLE_CEILING, if !blur { 0.0 } else if self.blur.1 > 0.0 { self.blur.0 / (self.blur.1 * self.frame_dt.clamp(1.0 / 240.0, 0.25)) } else { self.blur.0 }, spp.max(1) as f32],+ misc: [self.view.exposure, cap, self.vignette, b.on as u32 as f32],+ misc2: [1.0, SAMPLE_CEILING, shutter, spp.max(1) as f32],mode: [self.view_mode, self.reconstructor.white_units() as u32, self.live_lighting() as u32, reconstruction.raw_signal() as u32],post: self.post,ae: self.view.exposure_settings.ae,@@ -580,10 +582,11 @@ impl LiveCore {ae3: [self.view.exposure_settings.speed[0], self.view.exposure_settings.speed[1], self.frame_dt.clamp(1.0 / 240.0, 0.25), (self.reset || self.frame == 0 || exposure_snap()) as u32 as f32],lx: self.view.exposure_settings.lx,isz: [iw, ih, self.prev_isz.0, self.prev_isz.1],- br: [r[0], r[1], r[2], r[3]],- br2: [r[4], r[5], 0.0, 0.0],- bt: [t[0], t[1], t[2], t[3]],- bt2: [t[4], t[5], 0.0, 0.0],+ bl: [b.level[0], b.level[1], b.level[2], b.level[3]],+ bl2: [b.level[4], b.level[5], if b.has_wide() { b.radius as f32 } else { 0.0 }, b.fine],+ bw: [[b.wide[0][0], b.wide[0][1], b.wide[1][0], b.wide[1][1]], [b.wide[2][0], b.wide[2][1], b.wide[3][0], b.wide[3][1]], [b.wide[4][0], b.wide[4][1], b.wide[5][0], b.wide[5][1]]],+ lb: [b.base_level[0], b.base_level[1], b.base_level[2], b.base_level[3]],+ lb2: [b.base_level[4], b.base_level[5], b.base_wide[0], b.base_wide[1]],dof: dof_params(self.view.dof.as_ref(), cam.tan_half_fov, w, h),jit: [jitter.0, jitter.1, 0.0, 0.0],state: [1 - self.frame % 2, 0, 0, 0],diff --git a/renderer/src/live/layout.rs b/renderer/src/live/layout.rsindex f795187..20f88f6 100644--- a/renderer/src/live/layout.rs+++ b/renderer/src/live/layout.rs@@ -52,7 +52,7 @@ pub(super) enum Count {Pixels(u64),/// One per texel of the quarter-resolution grid.Quarter,- /// One per texel of the bloom pyramid's levels and stages.+ /// One per texel of the bloom pyramid (`post::bloom_texels`).Bloom,/// The length the shader gives the array.Declared,@@ -80,7 +80,6 @@ pub(super) const RESOURCES: &[(&str, Res)] = &[("fa", Res::Own(Count::Pixels(1))),("fb", Res::Own(Count::Pixels(1))),("bloom_a", Res::Own(Count::Bloom)),- ("bloom_b", Res::Own(Count::Quarter)),("spec_pp", Res::Own(Count::Pixels(2))),("sb", Res::Own(Count::Pixels(1))),("refl_in", Res::KernelRefl),@@ -103,6 +102,8 @@ pub(super) enum Grid {Output,/// A quarter of it each way.Quarter,+ /// Level j of the bloom pyramid (`post::bloom_dim`: 0 the quarter grid, each next one half of it).+ Bloom(usize),/// Its 16 x 16 tiles.Tiles16,/// The light tiles' entries (`light_tiles`: a workgroup a tile, of a grid one tile wider than the traced one).@@ -137,23 +138,18 @@ pub(super) const PASSES: &[(&str, Grid)] = &[("lum_down", Grid::Quarter),("exposure", Grid::One),("lum_blur", Grid::Quarter),- ("bloom_down", Grid::Quarter),- ("bloom_dn1", Grid::Quarter),- ("bloom_dn2", Grid::Quarter),- ("bloom_dn3", Grid::Quarter),- ("bloom_dn4", Grid::Quarter),- ("bloom_h5", Grid::Quarter),- ("bloom_v5", Grid::Quarter),- ("bloom_h4", Grid::Quarter),- ("bloom_v4", Grid::Quarter),- ("bloom_h3", Grid::Quarter),- ("bloom_v3", Grid::Quarter),- ("bloom_h2", Grid::Quarter),- ("bloom_v2", Grid::Quarter),- ("bloom_h1", Grid::Quarter),- ("bloom_v1", Grid::Quarter),- ("bloom_h0", Grid::Quarter),- ("bloom_v0", Grid::Quarter),+ ("bloom_down1", Grid::Bloom(1)),+ ("bloom_down2", Grid::Bloom(2)),+ ("bloom_down3", Grid::Bloom(3)),+ ("bloom_down4", Grid::Bloom(4)),+ ("bloom_down5", Grid::Bloom(5)),+ ("bloom_wide_rows", Grid::Bloom(5)),+ ("bloom_wide", Grid::Bloom(5)),+ ("bloom_up4", Grid::Bloom(4)),+ ("bloom_up3", Grid::Bloom(3)),+ ("bloom_up2", Grid::Bloom(2)),+ ("bloom_up1", Grid::Bloom(1)),+ ("bloom_up0", Grid::Bloom(0)),("view_raw", Grid::Output),("view_hdr", Grid::Output),("view_sample", Grid::Output),@@ -175,6 +171,7 @@ impl Grid {Grid::PrevTraced => (prev.0.max(1), prev.1.max(1)),Grid::Output => out,Grid::Quarter => (out.0.div_ceil(4), out.1.div_ceil(4)),+ Grid::Bloom(j) => crate::post::bloom_dim(out.0, out.1, j),Grid::Tiles16 => (out.0.div_ceil(16), out.1.div_ceil(16)),Grid::LightTiles => (light_tiles(traced.0) * 8, light_tiles(traced.1) * 8),Grid::One => (8, 8),diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex f4e9b4d..e028ddf 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -131,21 +131,25 @@ struct LiveParams {misc2: [f32; 4],mode: [u32; 4],post: [f32; 4],- /// Auto exposure (UE histogram): low / high fraction, histogram log2 min / max.+ /// Auto exposure's metering: low / high fraction of the histogram, its log2 luminance min / max.ae: [f32; 4],/// Compensation (2^bias), min / max average luminance, mode (0 manual, 1 auto).ae2: [f32; 4],- /// Speed up / down (EV/s), frame time (s), snap to target (1).+ /// Speed toward brighter / darker scenes (EV/s), frame time (s), snap to target (1).ae3: [f32; 4],/// Local exposure: highlight contrast, shadow contrast, blurred-luminance blend, detail strength.lx: [f32; 4],/// Traced (internal) width, height.isz: [u32; 4],- /// Bloom stage radii (texels of each stage's level) and tints, stages 0..3 then 4, 5.- br: [f32; 4],- br2: [f32; 4],- bt: [f32; 4],- bt2: [f32; 4],+ /// Bloom (`post::BloomPlan`): the weight of pyramid level 0..3; of 4, 5, the wide pass's reach (texels of the+ /// coarsest level; 0 = nothing to sum), the weight of the five-pixel kernel of the output's own pixels.+ bl: [f32; 4],+ bl2: [f32; 4],+ /// The wide Gaussians 0..5, a (weight, 1 / (2 sigma^2)) pair each.+ bw: [[f32; 4]; 3],+ /// Local exposure's wide blur of log luminance: the weight of level 0..3; of 4, 5, its wide Gaussian's pair.+ lb: [f32; 4],+ lb2: [f32; 4],/// Depth of field: CoC radius of infinity (output px; 0 = off), focus distance (m), max radius (px), -.dof: [f32; 4],/// This frame's sub-pixel jitter (every camera ray's: x, y in 0 .. 1 of a traced pixel), -, -.@@ -267,12 +271,12 @@ pub struct LiveCore {pub frame: u32,pub history_len: f32,reset: bool,- /// Bloom stage radii / tints (`bloom_stages`).- bloom: ([f32; 6], [f32; 6]),+ /// What the bloom passes do for the preset at the view's size.+ bloom: post::BloomPlan,vignette: f32,/// Chromatic aberration, film grain, bloom threshold, longest motion blur (output pixels).post: [f32; 4],- /// Motion blur (UE MotionBlurAmount, MotionBlurTargetFPS; amount 0 = off).+ /// Motion blur: the shutter as a fraction of the frame time (0 = off), the target frame rate (0 = the real one).blur: (f32, f32),/// Last submission of each frame still on the GPU (at most two frames in flight).inflight: std::collections::VecDeque<wgpu::SubmissionIndex>,@@ -449,16 +453,28 @@ fn exposure_snap() -> bool {*F.get_or_init(|| std::env::var("THREERT_EXPOSURE_SNAP").is_ok_and(|v| v == "1"))}-/// UE's physical CoC model (DiaphragmDOFUtils.cpp, FPhysicalCocModel::Compile): focal length from the sensor height-/// (sensor width / aspect) and the vertical FOV, the CoC of infinity on the sensor f^2 / (N (focus - f)), as a radius in-/// output pixels; max radius r.DOF.Kernel.Max{Fore,Back}groundRadius = 2.5 % of the width. Off without a focus distance.+/// The lens for live.wgsl's `dof_coc`, from the camera's depth-of-field settings (`desc::Dof`: focus distance in+/// metres, f-stop, sensor width in mm) and the view (vertical FOV, output size): `LiveParams::dof` = the circle of+/// confusion's radius for a point at infinity (output pixels; 0 = off), the focus distance (m), the largest radius+/// (output pixels: 2.5 % of the width).+///+/// A thin lens of focal length f and aperture diameter f / N focused at distance s images a point at distance z as+/// a disc of diameter c = (f / N) f / (s - f) |z - s| / z on the sensor (the thin-lens equation 1/f = 1/s + 1/s' and+/// similar triangles at the aperture; Potmesil & Chakravarty 1981, "A lens and aperture camera model for synthetic+/// image generation", and any optics text): c_inf (1 - s / z) with c_inf = f^2 / (N (s - f)), negative in front of+/// the focus plane. The focal length is the one that gives the view's+/// vertical FOV on a sensor of the given width and the output's aspect; a sensor width is `w` output pixels.fn dof_params(dof: Option<&crate::desc::Dof>, tan_half_fov: f32, w: u32, h: u32) -> [f32; 4] {- let Some(d) = dof.filter(|d| d.focus_distance > 0.0 && d.f_stop > 0.0 && d.sensor_width > 0.0) else { return [0.0; 4] };- let aspect = w as f32 / h as f32;- let sensor_h = d.sensor_width / aspect;- let f = 0.5 * sensor_h / tan_half_fov;- let diameter = f * f / (d.f_stop * (d.focus_distance * 1000.0 - f).max(1e-3));- [diameter * 0.5 / sensor_h / aspect * w as f32, d.focus_distance, 0.025 * w as f32, 0.0]+ let Some(d) = dof else { return [0.0; 4] };+ if !(d.f_stop > 0.0 && d.sensor_width > 0.0 && d.focus_distance > 0.0 && tan_half_fov > 0.0) {+ return [0.0; 4];+ }+ let sensor_height = d.sensor_width * h as f32 / w as f32;+ let f = 0.5 * sensor_height / tan_half_fov; // mm+ let s = (d.focus_distance * 1000.0).max(f * 1.001); // mm+ let c_inf = f * f / (d.f_stop * (s - f)); // mm on the sensor+ let largest = 0.025 * w as f32;+ [(0.5 * c_inf / d.sensor_width * w as f32).max(1e-6), d.focus_distance, largest, 0.0]}/// Light LOD (`emitter_lod`): emitters within this distance of the camera keep their sampling weight, farther ones@@ -494,13 +510,22 @@ fn halton(mut i: u32, base: u32) -> f32 {const CACHE_SAMPLES: f32 = 256.0;const CACHE_FRAMES: f32 = 32.0;const CACHE_FRAMES_LIT: f32 = 4.0;-/// The most frames a pixel's history holds while the scene's lighting changes: short enough to follow the change by-/// itself (a real-time denoiser's bound: NRD's default is 30), so no edit has to cut it. Against main's rules (24-/// frames for good in a scene with spark lights, every pixel cut to 16 at a lighting edit, an on / off anti-lag), dE-/// against the offline render or the converged frame: the Bistro slice half a second after its explosion 6.04 for-/// 6.58, at rest 2.82 for 2.79; Kabukichō 2 s and 4 s after its signs close 6.70 and 2.92 for 6.56 and 2.82. At 64-/// frames the explosion read 5.72 and the signs 7.82 and 3.37.-const HISTORY_LIVE: f32 = 32.0;+/// The most frames a pixel's history holds while the scene's lighting changes (`live_lighting`). What live.wgsl's+/// change chart follows (a light switched, a shadow that passes) does not wait for this bound, and what its drift+/// follows (a light that falls or rises steadily) is taken out of the history without shortening it ("The response+/// of the histories" there); the bound is for what both leave alone: a change too small or too noisy to tell, and+/// any change on pixels lit by rare bright samples. Those trail the light by this many frames, and every pixel's+/// noise while anything in the scene moves is that of a mean over this many.+/// Measured on the integrated tree, 2026-11-24, with the chart and the drift as they are, for 48 / 32 / 24 frames:+/// bench-window's tokyo-dusk (the sun setting over ten seconds, the frame against the same moment held; dE at 6, 7+/// and 8 s) 1.23 / 0.69 / 0.55, 1.15 / 0.64 / 0.53, 1.11 / 0.61 / 0.51 (the previous release, whose bound was 32:+/// 1.12 / 0.60 / 0.50; without the drift 2.61 / 1.44 / 0.87 at 48 and 1.73 / 0.83 / 0.58 at 32); bench-temporal's+/// lighting edit and bench-object-ghosting moved by 0.05 dE or less between 32 and 24, mostly down (the lamp's+/// bounce 32 frames after it went out 0.79 and 0.76, the runner 0.3 s after its run 0.31 and 0.29). In the tree+/// before it had specular light, the noise a shorter bound costs where nothing changes while something else moves+/// (the top fifth of the frame in the dragged device's shots and in the runner's), for 60 / 48 / 32: dE 0.24 / 0.24 /+/// 0.26 and 0.76 / 0.77 / 0.80.+const HISTORY_LIVE: f32 = 24.0;/// The most once the scene has settled: holding still, the frame converges on the offline render.const HISTORY_FRAMES: f32 = 4096.0;@@ -580,7 +605,7 @@ impl LiveCore {let mut core = LiveCore {kernel: None,more_features: Default::default(),- reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };+ reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: Default::default(), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);core.apply_post();Ok(core)@@ -725,11 +750,11 @@ impl LiveCore {);self.post_key = key;}- self.bloom = bloom_stages(pp, self.w, self.h);+ self.bloom = post::BloomPlan::new(pp, self.w, self.h);self.vignette = pp.vignette;// THREERT_NO_GRAIN=1: no film grain (a fresh random pattern every frame; comparisons between frames see it as error).let grain = if std::env::var("THREERT_NO_GRAIN").is_ok_and(|v| v == "1") { 0.0 } else { pp.film_grain };- // THREERT_MOTION_BLUR=1: UE's default motion blur whatever the preset says; =amount,max,targetFps: those.+ // THREERT_MOTION_BLUR=1: the default motion blur (`desc::MotionBlur`) whatever the preset says; =amount,max,targetFps: those.let mb = match std::env::var("THREERT_MOTION_BLUR").ok().as_deref() {Some("1") => crate::desc::MotionBlur::default(),Some(v) => match v.split(',').map(|x| x.trim().parse::<f32>()).collect::<Result<Vec<_>, _>>().as_deref() {diff --git a/renderer/src/live/state.rs b/renderer/src/live/state.rsindex fee33a3..043fe97 100644--- a/renderer/src/live/state.rs+++ b/renderer/src/live/state.rs@@ -9,28 +9,32 @@use super::*;-/// Auto / local exposure settings (UE PostProcessVolume semantics).+/// The exposure settings as live.wgsl's passes read them (`LiveParams::ae`, `ae2`, `ae3`.xy = `speed`, `lx`).#[derive(Clone, Copy, Default, Debug)]pub(super) struct ExposureSettings {+ /// Auto exposure's metering: low / high fraction of the histogram, its log2 luminance min / max.pub(super) ae: [f32; 4],+ /// The manual exposure scale, or auto exposure's compensation as a factor (2^compensation); the least / most+ /// average luminance auto exposure follows (what its EV100 limits expose as middle grey); 1 = auto.pub(super) ae2: [f32; 4],+ /// Adaptation speed toward brighter / darker scenes, EV per second.pub(super) speed: [f32; 2],+ /// Local exposure: highlight contrast, shadow contrast, blurred-luminance blend, detail strength.pub(super) lx: [f32; 4],}impl ExposureSettings {fn new(exp: &crate::desc::Exposure, pp: &crate::desc::PostPreset) -> Self {- let a = &pp.auto_exposure;- let le = &pp.local_exposure;+ let (ae, lx) = (&pp.auto_exposure, &pp.local_exposure);let ae2 = match exp {crate::desc::Exposure::Manual { ev100 } => [2f32.powf(-ev100), 0.0, 0.0, 0.0],- crate::desc::Exposure::Auto { compensation, min_ev100, max_ev100 } => [2f32.powf(*compensation), 0.18 * 2f32.powf(*min_ev100), 0.18 * 2f32.powf(*max_ev100), 1.0],+ crate::desc::Exposure::Auto { compensation, min_ev100, max_ev100 } => [2f32.powf(*compensation), post::MIDDLE_GREY * 2f32.powf(*min_ev100), post::MIDDLE_GREY * 2f32.powf(max_ev100.max(*min_ev100)), 1.0],};ExposureSettings {- ae: [a.low_percent.clamp(1.0, 99.0) / 100.0, a.high_percent.clamp(1.0, 99.0) / 100.0, a.histogram_log_min, a.histogram_log_max.max(a.histogram_log_min + 1.0)],+ ae: [ae.low_percent / 100.0, ae.high_percent / 100.0, ae.histogram_log_min, ae.histogram_log_max.max(ae.histogram_log_min + 1.0)],ae2,- speed: [a.speed_up.max(0.01), a.speed_down.max(0.01)],- lx: [le.highlight_contrast, le.shadow_contrast, le.blurred_luminance_blend, le.detail_strength],+ speed: [ae.speed_up.max(0.0), ae.speed_down.max(0.0)],+ lx: [lx.highlight_contrast, lx.shadow_contrast, lx.blurred_luminance_blend.clamp(0.0, 1.0), lx.detail_strength],}}}diff --git a/renderer/src/live/targets.rs b/renderer/src/live/targets.rsindex 5aa6d45..07dc721 100644--- a/renderer/src/live/targets.rs+++ b/renderer/src/live/targets.rs@@ -1,43 +1,21 @@//! The live passes' GPU side: the shader module and its pipelines (`Passes`), the screen-size buffers and the bind-//! groups (`Targets`), from the layout live.wgsl declares and `layout`'s table; and the tonemap LUT and bloom pyramid-//! they are sized for.+//! groups (`Targets`), from the layout live.wgsl declares and `layout`'s table; and the colour table of the final pass.use super::*;-/// Bloom pyramid level j (0..4: 1/4 .. 1/64 resolution) size; stage k (0..5) runs on level max(k - 1, 0).-pub(super) fn bloom_dim(w: u32, h: u32, j: u32) -> (u32, u32) {- (w.div_ceil(4).div_ceil(1 << j), h.div_ceil(4).div_ceil(1 << j))-}--pub(super) fn bloom_stage_level(k: u32) -> u32 {- k.max(1) - 1-}--/// UE Standard bloom per stage: Gaussian radius in texels of its level (BloomNSize % of the stage width * size scale-/// / 2, as `post::bloom`) and tint (BloomNTint * intensity / 6).-pub(super) fn bloom_stages(pp: &crate::desc::PostPreset, w: u32, h: u32) -> ([f32; 6], [f32; 6]) {- let (mut r, mut t) = ([0f32; 6], [0f32; 6]);- for k in 0..6 {- let (lw, _) = bloom_dim(w, h, bloom_stage_level(k as u32));- r[k] = lw as f32 * pp.bloom.sizes.get(k).copied().unwrap_or(0.0) * pp.bloom.size_scale * 0.01 * 0.5;- t[k] = pp.bloom.tints.get(k).copied().unwrap_or(0.0) * pp.bloom.intensity / 6.0;- }- (r, t)-}--pub(super) const LOG_OFFSET: f32 = 0.0026883; // must match live.wgsl lin_to_log input offset-pub(super) const LUT: u32 = 32;+/// The colour table the final pass samples (`lut`): colour grading and the tone curve of a preset (`post::Tonemapper`)+/// for exposed linear sRGB on a log2 axis (`post::lut_coord`, the same in live.wgsl `post`), as sRGB-encoded display+/// values (the pass has no encoding left to do; half floats hold them to 1 / 2048). LUT texels a side.+pub(super) const LUT: u32 = post::LUT_SIZE;-/// UE-style 32^3 LUT: log-encoded linear input -> display sRGB, built from the exact CPU port of the filmic tonemapper.pub(super) fn tonemap_lut(p: &crate::desc::PostPreset) -> Vec<u16> {let tm = post::Tonemapper::new(p);let mut out = Vec::with_capacity((LUT * LUT * LUT * 4) as usize);- let log_to_lin = |v: f32| (2f32.powf((v - 444.0 / 1023.0) * 14.0) * 0.18 - LOG_OFFSET).max(0.0);for b in 0..LUT {for g in 0..LUT {for r in 0..LUT {- let enc = |k: u32| log_to_lin(k as f32 / (LUT - 1) as f32);- let d = tm.apply(Vec3::new(enc(r), enc(g), enc(b)));+ let at = |k: u32| post::lut_value(k as f32 / (LUT - 1) as f32);+ let d = tm.apply(Vec3::new(at(r), at(g), at(b)));for c in [d.x, d.y, d.z, 1.0] {out.push(half::f16::from_f32(post::linear_to_srgb(c.clamp(0.0, 1.0))).to_bits());}@@ -196,8 +174,7 @@ impl Targets {let n = (w * h) as u64;let sb = |label: &str, bytes: u64| d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });let quarter = (w.div_ceil(4) * h.div_ceil(4)) as u64;- let texels = |j: u32| bloom_dim(w, h, j).0 as u64 * bloom_dim(w, h, j).1 as u64;- let bloom_texels = (0..5).map(texels).sum::<u64>() + (0..6).map(|k| texels(bloom_stage_level(k))).sum::<u64>();+ let bloom_texels = post::bloom_texels(w, h);let bufs: Vec<(u32, Buf)> = layout::BINDINGS.iter().filter_map(|b| {diff --git a/renderer/src/main.rs b/renderer/src/main.rsindex 3fe06b9..363c006 100644--- a/renderer/src/main.rs+++ b/renderer/src/main.rs@@ -557,10 +557,10 @@ fn render(g: &gpu::Gpu, job: &Job, presets: &Path, init_ms: f64, hosts: &mut Hoslet t = Instant::now();let img = post::Image { w, h, px: color };- // Local exposure's middle grey follows the exposure compensation (UE: auto bias; manual: bias = -EV100).+ // Local exposure's pivot over middle grey (post::finish): auto exposure's compensation; none under manual exposure.let compensation = match &sc.camera.exposure {threert_render::desc::Exposure::Auto { compensation, .. } => 2f32.powf(*compensation),- threert_render::desc::Exposure::Manual { ev100 } => 2f32.powf(-ev100),+ threert_render::desc::Exposure::Manual { .. } => 1.0,};let rgba = post::finish(&img, exposure, compensation, &preset.post);timings.push(("post_ms".into(), t.elapsed().as_secs_f64() * 1000.0));diff --git a/renderer/src/post.rs b/renderer/src/post.rsindex 85195cd..c15a16c 100644--- a/renderer/src/post.rs+++ b/renderer/src/post.rs@@ -1,11 +1,26 @@-//! UE5 post-processing chain ported from the engine shaders (UE 5.8):-//! PostProcessBloomSetup.cpp / PostProcessWeightedSampleSum.cpp (Gaussian "SOG" bloom),-//! PostProcessEyeAdaptation.cpp (manual / histogram exposure),-//! PostProcessTonemap.usf + PostProcessCombineLUTs.usf + TonemapCommon.ush (Filmic tonemapper),-//! PostProcessCommon.ush (cosine-fourth vignette).+//! The post chain of the offline renderer and the reference for the live passes (shaders/live.wgsl): exposure+//! (manual or automatic), local exposure, bloom, vignette, chromatic aberration, colour grading and the tone curve,+//! film grain, display encoding. Input: scene-linear radiance in nits (Rec.709 primaries, D65); output: 8-bit sRGB.+//!+//! What is here, and where each piece comes from (docs/RUNTIME.md "The post chain"; licences in+//! THIRD_PARTY_NOTICES.md):+//! - `exposure_scale`: histogram metering of log2 luminance (own design after the settings' public description).+//! - `Tonemapper`: the Academy's reference rendering as a structure (ACES 1.x RRT + ODT, AMPAS licence: working space+//! AP1, the "glow" and "red modifier", the 0.96 / 0.93 desaturations, the blue-light-artifact-fix matrix) around a+//! tone curve and a gamut expansion of our own whose free parameters are fitted to measurements of the look the+//! presets ask for.+//! - bloom: a sum of Gaussian blurs of the picture, one a stage (`bloom_stages`, `gaussian`). The live passes+//! approximate the same Gaussians on a 1/4 .. 1/128 image pyramid (Burt & Adelson 1983): `BloomPlan` is what they+//! do for a preset and an output size.+//! - local exposure: base / detail decomposition of log luminance (Durand & Dorsey 2002).+//! - vignette (cos^4 law), chromatic aberration, film grain: own designs after the settings' public descriptions.+//!+//! The live passes (shaders/live.wgsl `lum_down` .. `post`) mirror `finish` step by step. They differ in two places:+//! bloom, as said, and colour grading with the tone curve, which they read from a 3D table built here (`lut_coord`,+//! live/targets.rs `tonemap_lut`). tools/post-live.ts measures the two against each other.use crate::desc::{Exposure, PostPreset};-use glam::{Mat3, Vec3};+use glam::{DMat3, DVec3, Mat3, Vec3};use rayon::prelude::*;pub struct Image {@@ -20,10 +35,8 @@ impl Image {let y = y.clamp(0, self.h as isize - 1) as usize;self.px[y * self.w + x]}- fn sample(&self, u: f32, v: f32) -> Vec3 {- // Bilinear, u/v in [0,1] texture space.- let x = u * self.w as f32 - 0.5;- let y = v * self.h as f32 - 0.5;+ /// Bilinear, x / y in pixels (pixel centres at integers).+ fn bilinear(&self, x: f32, y: f32) -> Vec3 {let (x0, y0) = (x.floor(), y.floor());let (fx, fy) = (x - x0, y - y0);let (x0, y0) = (x0 as isize, y0 as isize);@@ -31,408 +44,485 @@ impl Image {let b = self.at(x0, y0 + 1).lerp(self.at(x0 + 1, y0 + 1), fx);a.lerp(b, fy)}- fn downsample(&self) -> Image {- let (w, h) = ((self.w / 2).max(1), (self.h / 2).max(1));- let px = (0..w * h)- .into_par_iter()- .map(|i| {- let (x, y) = ((i % w) as isize * 2, (i / w) as isize * 2);- (self.at(x, y) + self.at(x + 1, y) + self.at(x, y + 1) + self.at(x + 1, y + 1)) * 0.25- })- .collect();- Image { w, h, px }- }}-/// UE Compute1DGaussianFilterKernel: weights exp(-16.7 (x/R)^2), radius clamped to 31 texels.-fn gaussian_kernel(radius: f32) -> Vec<(isize, f32)> {- let r = radius.clamp(1e-4, 31.0);- let ir = r.ceil().min(31.0) as isize;- let mut k: Vec<(isize, f32)> = (-ir..=ir).map(|x| (x, (-16.7 * (x as f32 / r).powi(2)).exp())).collect();- let s: f32 = k.iter().map(|w| w.1).sum();- for w in &mut k {- w.1 /= s;+/// Relative luminance of linear Rec.709 / sRGB (ITU-R BT.709-6, the Y row of its RGB -> XYZ matrix).+pub const LUMA: Vec3 = Vec3::new(0.2126, 0.7152, 0.0722);++/// Middle grey: the 18 % reflectance a metered scene average is exposed to.+pub const MIDDLE_GREY: f32 = 0.18;++// ------------------------------------------------------------------------------------------------ exposure++/// Bins of the metering histogram (the same number as the documented histogram of Unreal's auto exposure).+pub const AE_BINS: usize = 64;++/// The metered average luminance (nits) from a histogram of log2 luminance: `count[b]` samples in bin b of+/// `AE_BINS` equal bins over `log_min .. log_max`, `mean[b]` their mean position in 0 .. 1 of that range. The average+/// is taken over the samples between the `low` and `high` fractions of the sorted population (bins cut by a bound+/// count in part), each bin at the luminance of its mean. None: no sample in range.+///+/// Own design, after the public description of histogram metering ("the average between the low and the high+/// percentile is exposed as middle grey"): the percentile window drops what a few very bright or very dark pixels+/// would do to a plain mean. The live `exposure` pass does the same sum on the GPU.+pub fn metered_average(count: &[f32; AE_BINS], mean: &[f32; AE_BINS], low: f32, high: f32, log_min: f32, log_max: f32) -> Option<f32> {+ let total: f32 = count.iter().sum();+ if total <= 0.0 {+ return None;+ }+ let (lo, hi) = (low.clamp(0.0, 1.0) * total, high.clamp(0.0, 1.0).max(low.clamp(0.0, 1.0)) * total);+ let (mut seen, mut sum, mut n) = (0.0f32, 0.0f32, 0.0f32);+ for b in 0..AE_BINS {+ let part = (seen + count[b]).min(hi) - seen.max(lo);+ if part > 0.0 {+ sum += part * 2f32.powf(log_min + mean[b] * (log_max - log_min));+ n += part;+ }+ seen += count[b];}- k+ // (A window narrower than one sample: the sample at the low bound.)+ if n <= 0.0 {+ let mut seen = 0.0;+ for b in 0..AE_BINS {+ seen += count[b];+ if seen >= lo && count[b] > 0.0 {+ return Some(2f32.powf(log_min + mean[b] * (log_max - log_min)));+ }+ }+ return None;+ }+ Some(sum / n)}-fn blur(img: &Image, radius: f32) -> Image {- let k = gaussian_kernel(radius);- let (w, h) = (img.w, img.h);- let tmp: Vec<Vec3> = (0..w * h)- .into_par_iter()- .map(|i| {- let (x, y) = ((i % w) as isize, (i / w) as isize);- k.iter().map(|(o, wt)| img.at(x + o, y) * *wt).sum()- })- .collect();- let tmp = Image { w, h, px: tmp };- let px = (0..w * h)+/// The exposure auto exposure aims at for a metered average luminance: middle grey x 2^compensation over the average,+/// the average held within the luminances that EV100 `min_ev100` .. `max_ev100` expose as middle grey.+pub fn auto_target(average: f32, compensation: f32, min_ev100: f32, max_ev100: f32) -> f32 {+ let (lo, hi) = (MIDDLE_GREY * 2f32.powf(min_ev100), MIDDLE_GREY * 2f32.powf(max_ev100.max(min_ev100)));+ MIDDLE_GREY * 2f32.powf(compensation) / average.clamp(lo, hi)+}++/// The log2 luminance of each 4 x 4 block of the image (its mean colour's; the last column / row of a size that is+/// no multiple of 4 holds fewer pixels): what auto exposure meters and local exposure decomposes. `-inf` for black.+fn quarter_log_luminance(img: &Image) -> (usize, usize, Vec<f32>) {+ let (qw, qh) = (img.w.div_ceil(4), img.h.div_ceil(4));+ let l = (0..qw * qh).into_par_iter().map(|i| {- let (x, y) = ((i % w) as isize, (i / w) as isize);- k.iter().map(|(o, wt)| tmp.at(x, y + o) * *wt).sum()+ let (bx, by) = (i % qw * 4, i / qw * 4);+ let (mut s, mut n) = (0.0f32, 0.0f32);+ for y in by..(by + 4).min(img.h) {+ for x in bx..(bx + 4).min(img.w) {+ let c = img.px[y * img.w + x];+ if c.is_finite() {+ s += c.max(Vec3::ZERO).dot(LUMA);+ }+ n += 1.0;+ }+ }+ (s / n.max(1.0)).log2()}).collect();- Image { w, h, px }-}--/// Gaussian bloom at half resolution (BloomQuality 5: six stages on a 1/2 .. 1/64 downsample chain).-pub fn bloom(scene: &Image, p: &PostPreset) -> Option<Image> {- if p.bloom.intensity <= 0.0 {- return None;- }- let thresholded = if p.bloom.threshold > 0.0 {- // UE: Color * saturate((Luminance(Color) - Threshold) * 0.5), Luminance = dot(c, (0.3, 0.59, 0.11)).- let t = p.bloom.threshold;- Image { w: scene.w, h: scene.h, px: scene.px.iter().map(|c| *c * ((c.dot(Vec3::new(0.3, 0.59, 0.11)) - t) * 0.5).clamp(0.0, 1.0)).collect() }- } else {- Image { w: scene.w, h: scene.h, px: scene.px.clone() }- };- let mut chain = vec![thresholded.downsample()];- for _ in 1..6 {- let next = chain.last().unwrap().downsample();- chain.push(next);- }- let tint_scale = p.bloom.intensity / 6.0;- let mut out: Option<Image> = None;- // Largest kernel (lowest resolution) first, accumulating upward like UE's additive passes.- for stage in (0..6).rev() {- let src = &chain[stage];- let size = p.bloom.sizes[stage] * p.bloom.size_scale;- let radius = src.w as f32 * size * 0.01 * 0.5;- let blurred = blur(src, radius);- let tint = p.bloom.tints[stage] * tint_scale;- let px: Vec<Vec3> = (0..src.w * src.h)- .into_par_iter()- .map(|i| {- let mut c = blurred.px[i] * tint;- if let Some(prev) = &out {- let (x, y) = ((i % src.w) as f32 + 0.5, (i / src.w) as f32 + 0.5);- c += prev.sample(x / src.w as f32, y / src.h as f32);- }- c- })- .collect();- out = Some(Image { w: src.w, h: src.h, px });- }- out+ (qw, qh, l)}-/// Exposure scale applied to scene radiance (nits). Manual: 2^-EV100 (UE: LuminanceMax = 1 with-/// r.EyeAdaptation.LensAttenuation 0.78 and extended luminance range). Auto: UE histogram method.+/// Exposure scale applied to scene radiance (nits), and the EV100 it corresponds to (-log2 of the scale: at EV100 0+/// one nit is 1.0, the scene DSL's convention). Manual: 2^-EV100. Auto: `metered_average` of the image's+/// quarter-resolution luminance within the preset's histogram range (samples outside it are not counted, as the+/// setting's documentation says), `auto_target` of that. An image with nothing in range is shown at the exposure a+/// view starts with.pub fn exposure_scale(img: &Image, exp: &Exposure, p: &PostPreset) -> (f32, f32) {- match exp {- Exposure::Manual { ev100 } => (2f32.powf(-ev100), *ev100),+ let scale = match exp {+ Exposure::Manual { ev100 } => 2f32.powf(-ev100),Exposure::Auto { compensation, min_ev100, max_ev100 } => {- // UE 5 histogram eye adaptation (PostProcessHistogram.usf / PostProcessHistogramCommon.ush): 64 buckets- // over [HistogramLogMin, HistogramLogMax] (EV100 = log2 luminance with the extended range), uniform RGB- // weights (r.AutoExposure.LuminanceMethod 0), no screen weighting (default meter mask), each sample split- // between its two buckets; the average log luminance between the low / high percentiles.- let (lo, hi) = (p.auto_exposure.histogram_log_min, p.auto_exposure.histogram_log_max.max(p.auto_exposure.histogram_log_min + 1.0));- let bins = 64usize;- let mut hist = vec![0f64; bins];- for c in &img.px {- let l = ((c.x + c.y + c.z) / 3.0).max(1e-10);- let fb = ((l.log2() - lo) / (hi - lo)).clamp(0.0, 1.0) * (bins - 1) as f32;- let b0 = (fb.floor() as usize).min(bins - 1);- let w1 = (fb - b0 as f32) as f64;- hist[b0] += 1.0 - w1;- hist[(b0 + 1).min(bins - 1)] += w1;+ let ae = &p.auto_exposure;+ let (lo, hi) = (ae.histogram_log_min, ae.histogram_log_max.max(ae.histogram_log_min + 1.0));+ let (mut count, mut sum) = ([0f32; AE_BINS], [0f64; AE_BINS]);+ for l in quarter_log_luminance(img).2 {+ let t = (l - lo) / (hi - lo);+ if (0.0..=1.0).contains(&t) {+ let b = ((t * AE_BINS as f32) as usize).min(AE_BINS - 1);+ count[b] += 1.0;+ sum[b] += t as f64;+ }+ }+ let mut mean = [0f32; AE_BINS];+ for b in 0..AE_BINS {+ mean[b] = if count[b] > 0.0 { (sum[b] / count[b] as f64) as f32 } else { 0.0 };}- let total: f64 = hist.iter().sum();- let (mut min_f, mut max_f) = (p.auto_exposure.low_percent.clamp(1.0, 99.0) as f64 / 100.0 * total, p.auto_exposure.high_percent.clamp(1.0, 99.0) as f64 / 100.0 * total);- min_f = min_f.min(max_f);- let (mut sum, mut cnt) = (0f64, 0f64);- for (b, v) in hist.iter().enumerate() {- let mut v = *v;- let sub = v.min(min_f);- v -= sub;- min_f -= sub;- max_f -= sub;- v = v.min(max_f);- max_f -= v;- let log_l = lo + b as f32 / (bins - 1) as f32 * (hi - lo);- sum += v * log_l as f64;- cnt += v;+ match metered_average(&count, &mean, ae.low_percent / 100.0, ae.high_percent / 100.0, lo, hi) {+ Some(avg) => auto_target(avg, *compensation, *min_ev100, *max_ev100),+ None => exp.start(),}- let avg = if cnt > 0.0 { 2f32.powf((sum / cnt) as f32) } else { 0.18 * 2f32.powf(*min_ev100) / 0.18 };- let avg = avg.clamp(0.18 * 2f32.powf(*min_ev100), 0.18 * 2f32.powf(*max_ev100));- let scale = 0.18 * 2f32.powf(*compensation) / avg;- (scale, -scale.log2())}- }+ };+ (scale, -scale.log2())}-// -------------------------------------------------------------------------------------------------// Filmic tonemapper (TonemapCommon.ush FilmToneMap + PostProcessCombineLUTs.usf)+// ------------------------------------------------------------------------------------------------ colour science++/// CIE 1931 xy chromaticities. Rec.709 / sRGB primaries and D65: ITU-R BT.709-6, IEC 61966-2-1. AP0, AP1 and the ACES+/// white: SMPTE ST 2065-1 and Academy S-2014-004 (ACEScg), as tabulated in the Academy's reference transforms+/// (aces-dev 1.3, `ACESlib.Utilities_Color.ctl`).+const REC709: [[f64; 2]; 3] = [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06]];+const D65: [f64; 2] = [0.3127, 0.3290];+const AP0: [[f64; 2]; 3] = [[0.7347, 0.2653], [0.0, 1.0], [0.0001, -0.077]];+const AP1: [[f64; 2]; 3] = [[0.713, 0.293], [0.165, 0.830], [0.128, 0.044]];+const ACES_WHITE: [f64; 2] = [0.32168, 0.33767];-fn m3(r: [[f32; 3]; 3]) -> Mat3 {- // HLSL initializers are row-major; glam is column-major.- Mat3::from_cols_array_2d(&r).transpose()+/// The wide gamut an sRGB colour's coordinates are re-read in by the gamut expansion (`Tonemapper`): primaries+/// fitted to the measured look (white D65), between DCI-P3 and Rec.2020. Own design.+const EXPAND_GAMUT: [[f64; 2]; 3] = [[0.7035, 0.3032], [0.2396, 0.7227], [0.1325, 0.0504]];++/// The Bradford cone response matrix (Lam 1985; the chromatic adaptation the ACES transforms and ICC profiles use).+const BRADFORD: [[f64; 3]; 3] = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]];++/// The Academy's "blue light artifact fix" look (aces-dev 1.3, `LMT.Academy.BlueLightArtifactFix.ctl`, AMPAS+/// licence: THIRD_PARTY_NOTICES.md), an AP0 -> AP0 matrix that desaturates blue hues so that bright blue light does+/// not clip to violet. Written here for column vectors (the CTL file multiplies row vectors).+const BLUE_LIGHT_FIX_AP0: [[f64; 3]; 3] = [+ [0.9404372683, -0.0183068787, 0.0778696104],+ [0.0083786969, 0.8286599939, 0.1629613092],+ [0.0005471261, -0.0008833746, 1.0003362486],+];++fn rows(m: [[f64; 3]; 3]) -> DMat3 {+ DMat3::from_cols_array_2d(&m).transpose()}-struct Matrices {- srgb_to_ap1: Mat3,- ap1_to_srgb: Mat3,- ap0_to_ap1: Mat3,- ap1_to_ap0: Mat3,- expand: Mat3,- blue: Mat3,- blue_inv: Mat3,-}--fn matrices() -> Matrices {- let ap0_to_xyz = m3([[0.9525523959, 0.0, 0.0000936786], [0.3439664498, 0.7281660966, -0.0721325464], [0.0, 0.0, 1.0088251844]]);- let xyz_to_ap0 = m3([[1.0498110175, 0.0, -0.0000974845], [-0.4959030231, 1.3733130458, 0.0982400361], [0.0, 0.0, 0.9912520182]]);- let ap1_to_xyz = m3([[0.6624541811, 0.1340042065, 0.1561876870], [0.2722287168, 0.6740817658, 0.0536895174], [-0.0055746495, 0.0040607335, 1.0103391003]]);- let xyz_to_ap1 = m3([[1.6410233797, -0.3248032942, -0.2364246952], [-0.6636628587, 1.6153315917, 0.0167563477], [0.0117218943, -0.0082844420, 0.9883948585]]);- let xyz_to_srgb = m3([[3.2409699419, -1.5373831776, -0.4986107603], [-0.9692436363, 1.8759675015, 0.0415550574], [0.0556300797, -0.2039769589, 1.0569715142]]);- let srgb_to_xyz = m3([[0.4123907993, 0.3575843394, 0.1804807884], [0.2126390059, 0.7151686788, 0.0721923154], [0.0193308187, 0.1191947798, 0.9505321522]]);- let d65_to_d60 = m3([[1.0130349146, 0.0061052578, -0.0149709436], [0.0076982301, 0.9981633521, -0.0050320385], [-0.0028413174, 0.0046851567, 0.9245061375]]);- let d60_to_d65 = m3([[0.9872240087, -0.0061132286, 0.0159532883], [-0.0075983718, 1.0018614847, 0.0053300358], [0.0030725771, -0.0050959615, 1.0816806031]]);- let srgb_to_ap1 = xyz_to_ap1 * d65_to_d60 * srgb_to_xyz;- let ap1_to_srgb = xyz_to_srgb * d60_to_d65 * ap1_to_xyz;- let wide_to_xyz = m3([[0.5441691, 0.2395926, 0.1666943], [0.2394656, 0.7021530, 0.0583814], [-0.0023439, 0.0361834, 1.0552183]]);- let ap0_to_ap1 = xyz_to_ap1 * ap0_to_xyz;- let ap1_to_ap0 = xyz_to_ap0 * ap1_to_xyz;- let blue_ap0 = m3([[0.9404372683, -0.0183068787, 0.0778696104], [0.0083786969, 0.8286599939, 0.1629613092], [0.0005471261, -0.0008833746, 1.0003362486]]);- let blue_inv_ap0 = m3([[1.06318, 0.0233956, -0.0865726], [-0.0106337, 1.20632, -0.19569], [-0.000590887, 0.00105248, 0.999538]]);- Matrices {- srgb_to_ap1,- ap1_to_srgb,- ap0_to_ap1,- ap1_to_ap0,- expand: (xyz_to_ap1 * wide_to_xyz) * ap1_to_srgb,- blue: ap0_to_ap1 * blue_ap0 * ap1_to_ap0,- blue_inv: ap0_to_ap1 * blue_inv_ap0 * ap1_to_ap0,- }-}--const AP1_RGB2Y: Vec3 = Vec3::new(0.2722287168, 0.6740817658, 0.0536895174);--fn rgb_2_saturation(c: Vec3) -> f32 {- let mn = c.min_element();- let mx = c.max_element();- (mx.max(1e-10) - mn.max(1e-10)) / mx.max(1e-2)-}--fn rgb_2_yc(c: Vec3) -> f32 {- let (r, g, b) = (c.x, c.y, c.z);- let chroma = (b * (b - g) + g * (g - r) + r * (r - b)).max(0.0).sqrt();- (b + g + r + 1.75 * chroma) / 3.0-}--fn sigmoid_shaper(x: f32) -> f32 {- let t = (1.0 - (0.5 * x).abs()).max(0.0);- let y = 1.0 + x.signum() * (1.0 - t * t);- 0.5 * y-}--fn glow_fwd(yc: f32, gain: f32, mid: f32) -> f32 {- if yc <= 2.0 / 3.0 * mid {- gain- } else if yc >= 2.0 * mid {- 0.0+fn xyz_of(xy: [f64; 2]) -> DVec3 {+ DVec3::new(xy[0] / xy[1], 1.0, (1.0 - xy[0] - xy[1]) / xy[1])+}++/// RGB -> CIE XYZ of a colour space given by its primaries and white (the standard derivation: SMPTE RP 177).+fn rgb_to_xyz(primaries: [[f64; 2]; 3], white: [f64; 2]) -> DMat3 {+ let m = DMat3::from_cols(xyz_of(primaries[0]), xyz_of(primaries[1]), xyz_of(primaries[2]));+ let s = m.inverse() * xyz_of(white);+ DMat3::from_cols(m.x_axis * s.x, m.y_axis * s.y, m.z_axis * s.z)+}++/// The von Kries adaptation in Bradford's cone space that takes the white `from` to the white `to` (XYZ -> XYZ).+fn adapt(from: [f64; 2], to: [f64; 2]) -> DMat3 {+ let b = rows(BRADFORD);+ b.inverse() * DMat3::from_diagonal(b * xyz_of(to) / (b * xyz_of(from))) * b+}++/// The matrix that keeps `sat` of a colour and takes the rest from its luminance (weights `y`), as the ACES+/// transforms build their desaturations (`calc_sat_adjust_matrix`).+fn saturation_matrix(sat: f64, y: DVec3) -> DMat3 {+ let grey = DMat3::from_cols(DVec3::splat(y.x), DVec3::splat(y.y), DVec3::splat(y.z));+ grey * (1.0 - sat) + DMat3::IDENTITY * sat+}++fn to_f32(m: DMat3) -> Mat3 {+ m.as_mat3()+}++/// CIE daylight locus: the chromaticity of daylight of correlated colour temperature `t` K (CIE 15 "Colorimetry";+/// Wyszecki & Stiles 1982, section 3.3.4; given for 4000 .. 25000 K), in CIE 1960 uv.+fn daylight_uv(t: f64) -> [f64; 2] {+ let x = if t <= 7000.0 { 0.244063 + 0.09911e3 / t + 2.9678e6 / (t * t) - 4.6070e9 / (t * t * t) } else { 0.237040 + 0.24748e3 / t + 1.9018e6 / (t * t) - 2.0064e9 / (t * t * t) };+ let y = -3.0 * x * x + 2.87 * x - 0.275;+ [4.0 * x / (-2.0 * x + 12.0 * y + 3.0), 6.0 * y / (-2.0 * x + 12.0 * y + 3.0)]+}++/// The Planckian locus in CIE 1960 uv (Krystek 1985, "An algorithm to calculate correlated colour temperature",+/// Color Research & Application 10: rational approximation, 1000 .. 15000 K).+fn planckian_uv(t: f64) -> [f64; 2] {+ [+ (0.860117757 + 1.54118254e-4 * t + 1.28641212e-7 * t * t) / (1.0 + 8.42420235e-4 * t + 7.08145163e-7 * t * t),+ (0.317398726 + 4.22806245e-5 * t + 4.20481691e-8 * t * t) / (1.0 - 2.89741816e-5 * t + 1.61456053e-7 * t * t),+ ]+}++/// CIE 1960 u shift of the white a unit of `whiteTint`: fitted to the measured tint tables (own design: positive tint+/// takes the scene illuminant toward green, so the picture toward magenta).+const TINT_U: f64 = -0.0195;++/// The scene illuminant `whiteTemp` / `whiteTint` name, xy: on the daylight locus from 4000 K up, on the Planckian+/// locus below 3000 K (a lamp), between the two in between; the tint shifts it across the locus.+fn white_point(temp: f64, tint: f64) -> [f64; 2] {+ let t = temp.clamp(1500.0, 25000.0);+ let d = daylight_uv(t.max(4000.0));+ let [u, v] = if t < 4000.0 {+ // Below the daylight locus' range: the Planckian locus, keeping at 4000 K the daylight's offset from it and+ // losing it by 3000 K (so the white is continuous in the temperature).+ let (p, p4) = (planckian_uv(t), planckian_uv(4000.0));+ let f = ((t - 3000.0) / 1000.0).clamp(0.0, 1.0);+ [p[0] + f * (d[0] - p4[0]), p[1] + f * (d[1] - p4[1])]} else {- gain * (mid / yc - 0.5)+ d+ };+ let u = u + TINT_U * tint;+ [3.0 * u / (2.0 * u - 8.0 * v + 4.0), 2.0 * v / (2.0 * u - 8.0 * v + 4.0)]+}++/// White balance as a linear sRGB -> linear sRGB matrix: the Bradford adaptation from the illuminant the settings+/// name to the one 6500 K names, so that light of `temp` K renders white (same meaning as Unreal's "Temp" / "Tint"+/// white balance settings, per its documentation). 6500 / 0: the identity.+fn white_balance(temp: f32, tint: f32) -> DMat3 {+ if temp == 6500.0 && tint == 0.0 {+ return DMat3::IDENTITY;}+ let srgb = rgb_to_xyz(REC709, D65);+ srgb.inverse() * adapt(white_point(temp as f64, tint as f64), white_point(6500.0, 0.0)) * srgb}-fn rgb_2_hue(c: Vec3) -> f32 {- let mut hue = if c.x == c.y && c.y == c.z { 0.0 } else { (180.0 / std::f32::consts::PI) * (3f32.sqrt() * (c.y - c.z)).atan2(2.0 * c.x - c.y - c.z) };- if hue < 0.0 {- hue += 360.0;+// ------------------------------------------------------------------------------------------------ tone curve++/// The tone curve: display-linear output for scene-linear (exposed) input, per channel of the rendering space.+///+/// Own design: a film characteristic curve drawn, as sensitometry draws it, against log10 exposure, made of two+/// logistic branches that meet with equal value and slope at `(mid_in, mid_out)`. The lower branch (the toe) rises+/// from 0 toward `toe`, the upper (the shoulder) from `white - shoulder` toward `white`; a logistic in log exposure+/// is a power law at its far end, so shadows fall to black as x^(toe exponent) and highlights close on `white`+/// without ever clipping. The six numbers are fitted to the measured neutral ramp of the look the presets ask for+/// (257 greys from 1e-4 to 1e3: largest difference 0.0004 in sRGB-encoded value).+#[derive(Clone, Copy, Debug)]+pub struct ToneCurve {+ /// Exposure at which the branches meet, and the output there.+ pub mid_in: f32,+ pub mid_out: f32,+ /// Slope at the meeting point, output per decade of exposure (the film's "gamma" in these axes).+ pub slope: f32,+ /// Height the toe branch would reach, and depth the shoulder branch rises from below `white`.+ pub toe: f32,+ pub shoulder: f32,+ /// The curve's top: display values above 1 are clipped by the display, which sets how soon highlights clip.+ pub white: f32,+}++impl Default for ToneCurve {+ fn default() -> Self {+ ToneCurve { mid_in: 0.345_476, mid_out: 0.386_434, slope: 0.855_193, toe: 0.889_282, shoulder: 1.553_913, white: 1.039_985 }}- hue.clamp(0.0, 360.0)}-fn center_hue(hue: f32, center: f32) -> f32 {- let mut h = hue - center;- if h < -180.0 {- h += 360.0;- } else if h > 180.0 {- h -= 360.0;+/// `ToneCurve` in the form `eval` computes: the two logistics' rates and centres in log10 exposure.+#[derive(Clone, Copy, Debug)]+struct CurveEval {+ mid: f32,+ toe: [f32; 3],+ shoulder: [f32; 3],+ white: f32,+}++impl ToneCurve {+ fn eval(&self) -> CurveEval {+ let mid = self.mid_in.log10();+ // A logistic A / (1 + exp(-k (X - c))) through (mid, y) with slope s there: u = y / A, k = s / (A u (1 - u)),+ // c = mid - ln(u / (1 - u)) / k.+ let branch = |a: f32, y: f32| {+ let u = (y / a).clamp(1e-4, 1.0 - 1e-4);+ let k = self.slope / (a * u * (1.0 - u));+ [a, k, mid - (u / (1.0 - u)).ln() / k]+ };+ let toe = branch(self.toe, self.mid_out);+ // The shoulder is the same logistic turned over: white - A / (1 + exp(k (X - c))).+ let s = branch(self.shoulder, self.white - self.mid_out);+ CurveEval { mid, toe, shoulder: [s[0], s[1], 2.0 * mid - s[2]], white: self.white }+ }+}++impl CurveEval {+ fn at(&self, x: f32) -> f32 {+ let lx = x.max(1e-10).log10();+ if lx < self.mid {+ let [a, k, c] = self.toe;+ a / (1.0 + (-k * (lx - c)).exp())+ } else {+ let [a, k, c] = self.shoulder;+ self.white - a / (1.0 + (k * (lx - c)).exp())+ }}- h}+/// Constants of the Academy's reference rendering transform that the rendering here keeps (aces-dev 1.3,+/// `ACESlib.RRT_Common.ctl`, `ACESlib.ODT_Common.ctl`; AMPAS licence: THIRD_PARTY_NOTICES.md).+const RRT_GLOW_GAIN: f32 = 0.05;+const RRT_GLOW_MID: f32 = 0.08;+const RRT_RED_SCALE: f32 = 0.82;+const RRT_RED_PIVOT: f32 = 0.03;+const RRT_RED_WIDTH: f32 = 135.0;+const RRT_SAT_FACTOR: f64 = 0.96;+const ODT_SAT_FACTOR: f64 = 0.93;++/// The gamut expansion's weight: the luminance (rendering space, exposed) at which it is 1 - 1/e of the way in, and+/// the same for the chroma (the colour's distance from its grey, over its luminance). Fitted with `EXPAND_GAMUT`.+const EXPAND_LUMINANCE: f32 = 0.5867;+const EXPAND_CHROMA: f32 = 0.6134;++/// Colour grading's tonal ranges, as luminance (rendering space, exposed): shadows fade out by `SHADOWS_MAX`,+/// highlights fade in from `HIGHLIGHTS_MIN` to `HIGHLIGHTS_MAX`. Fitted to the measured gain tables (0.0905 / 0.492 /+/// 1.011) and rounded.+const SHADOWS_MAX: f32 = 0.09;+const HIGHLIGHTS_MIN: f32 = 0.5;+const HIGHLIGHTS_MAX: f32 = 1.0;+fn smoothstep(a: f32, b: f32, x: f32) -> f32 {let t = ((x - a) / (b - a)).clamp(0.0, 1.0);t * t * (3.0 - 2.0 * t)}+/// Colour grading and the tone curve of a preset: exposed scene-linear sRGB in, display-linear sRGB out.+///+/// The rendering is the Academy's reference rendering (ACES 1.x RRT then ODT for an sRGB display; the Filmic+/// tonemapper the presets are compatible with "matches the ACES standard", its documentation says) with our own+/// tone curve in place of the Academy's two tone scales and two looks in front of it:+///+/// 1. white balance (`white_balance`), in linear sRGB;+/// 2. to the rendering space AP1 (ACEScg), Bradford-adapted from D65 to the ACES white;+/// 3. colour grading on scene-linear AP1: saturation about the luminance, contrast as a power about middle grey,+/// gains weighted to shadows / highlights by luminance (the settings' documented meanings);+/// 4. the RRT's "glow" (dark saturated colours a little brighter) and "red modifier" (saturated reds toward a pivot),+/// in AP0, with the Academy's constants;+/// 5. gamut expansion (`colorGrading.expandGamut`; own design after the setting's documented purpose, "pushes bright,+/// saturated colours beyond the sRGB gamut"): the colour's sRGB coordinates are re-read as coordinates of the+/// wider `EXPAND_GAMUT`, by a weight that grows with luminance and with chroma;+/// 6. the Academy's blue-light-artifact-fix matrix by `colorGrading.blueCorrection`, undone after the curve, so that+/// only what the curve compresses (bright blue) changes: it desaturates instead of turning violet;+/// 7. negative components clipped, the RRT's 0.96 desaturation, the tone curve per channel, the ODT's 0.93+/// desaturation, back to linear sRGB (adapted to D65).+///+/// Against the measured table of the previous look (6 657 colours): mean CIE dE2000 0.19, 99th percentile 1.1.pub struct Tonemapper {- m: Matrices,- /// White balance (Bradford, scene white -> D65) in linear sRGB; identity at 6500 K / tint 0.- white_balance: Mat3,+ wb_to_ap1: Mat3,+ ap1_to_ap0: Mat3,+ ap0_to_ap1: Mat3,+ /// The gamut expansion in AP1, less the identity.+ expand: Mat3,+ expand_amount: f32,+ /// Blue fix and the RRT desaturation; the ODT desaturation, the blue fix undone and AP1 -> sRGB.+ pre: Mat3,+ blue: Mat3,+ post: Mat3,+ luma: Vec3,+ curve: CurveEval,saturation: Vec3,contrast: Vec3,shadows_gain: Vec3,highlights_gain: Vec3,- slope: f32,- toe: f32,- shoulder: f32,- black_clip: f32,- white_clip: f32,- tone_curve_amount: f32,- expand_gamut: f32,- blue_correction: f32,+ graded: bool,}impl Tonemapper {pub fn new(p: &PostPreset) -> Self {- let t = &p.tonemapper;let g = &p.color_grading;+ let srgb = rgb_to_xyz(REC709, D65);+ let (ap0, ap1) = (rgb_to_xyz(AP0, ACES_WHITE), rgb_to_xyz(AP1, ACES_WHITE));+ let srgb_to_ap1 = ap1.inverse() * adapt(D65, ACES_WHITE) * srgb;+ let ap1_to_srgb = srgb.inverse() * adapt(ACES_WHITE, D65) * ap1;+ let (ap1_to_ap0, ap0_to_ap1) = (ap0.inverse() * ap1, ap1.inverse() * ap0);+ // AP1's luminance weights: the Y row of AP1 -> XYZ.+ let y = ap1.row(1);+ // sRGB coordinates read as the wide gamut's, as an sRGB -> sRGB matrix, then in AP1.+ let widen = srgb.inverse() * rgb_to_xyz(EXPAND_GAMUT, D65);+ let expand = srgb_to_ap1 * widen * ap1_to_srgb - DMat3::IDENTITY;+ let t = g.blue_correction.clamp(0.0, 1.0) as f64;+ let blue = ap0_to_ap1 * (DMat3::IDENTITY * (1.0 - t) + rows(BLUE_LIGHT_FIX_AP0) * t) * ap1_to_ap0;+ let v = |c: crate::desc::Rgb| Vec3::from(c.0);+ let one = Vec3::ONE;Tonemapper {- m: matrices(),- white_balance: white_balance(g.white_temp, g.white_tint),- saturation: Vec3::from(g.saturation.0),- contrast: Vec3::from(g.contrast.0),- shadows_gain: Vec3::from(g.shadows_gain.0),- highlights_gain: Vec3::from(g.highlights_gain.0),- slope: t.slope,- toe: t.toe,- shoulder: t.shoulder,- black_clip: t.black_clip,- white_clip: t.white_clip,- tone_curve_amount: t.tone_curve_amount,- expand_gamut: p.color_grading.expand_gamut,- blue_correction: p.color_grading.blue_correction,+ wb_to_ap1: to_f32(srgb_to_ap1 * white_balance(g.white_temp, g.white_tint)),+ ap1_to_ap0: to_f32(ap1_to_ap0),+ ap0_to_ap1: to_f32(ap0_to_ap1),+ expand: to_f32(expand),+ expand_amount: g.expand_gamut.max(0.0),+ blue: to_f32(blue),+ pre: to_f32(saturation_matrix(RRT_SAT_FACTOR, y)),+ post: to_f32(ap1_to_srgb * blue.inverse() * saturation_matrix(ODT_SAT_FACTOR, y)),+ luma: y.as_vec3(),+ curve: ToneCurve::default().eval(),+ saturation: v(g.saturation),+ contrast: v(g.contrast),+ shadows_gain: v(g.shadows_gain),+ highlights_gain: v(g.highlights_gain),+ graded: v(g.saturation) != one || v(g.contrast) != one || v(g.shadows_gain) != one || v(g.highlights_gain) != one,}}- fn film_tonemap(&self, color_ap1: Vec3) -> Vec3 {- let m = &self.m;- let mut ap0 = m.ap1_to_ap0 * color_ap1;- // ACES RRT glow module- let sat = rgb_2_saturation(ap0);- let yc = rgb_2_yc(ap0);- let s = sigmoid_shaper((sat - 0.4) / 0.2);- let glow = 1.0 + glow_fwd(yc, 0.05 * s, 0.08);- ap0 *= glow;- // Red modifier- let hue = rgb_2_hue(ap0);- let ch = center_hue(hue, 0.0);- let hw = smoothstep(0.0, 1.0, 1.0 - (2.0 * ch / 135.0).abs()).powi(2);- ap0.x += hw * sat * (0.03 - ap0.x) * (1.0 - 0.82);- let mut wc = (m.ap0_to_ap1 * ap0).max(Vec3::ZERO);- wc = Vec3::splat(wc.dot(AP1_RGB2Y)).lerp(wc, 0.96);- let toe_scale = 1.0 + self.black_clip - self.toe;- let shoulder_scale = 1.0 + self.white_clip - self.shoulder;- let (in_match, out_match) = (0.18f32, 0.18f32);- let toe_match = if self.toe > 0.8 {- (1.0 - self.toe - out_match) / self.slope + in_match.log10()+ /// Step 3: saturation, contrast, shadow / highlight gains (1 = none each; scalar or per channel).+ fn grade(&self, a: Vec3) -> Vec3 {+ let l = a.dot(self.luma);+ let a = (Vec3::splat(l) + (a - l) * self.saturation).max(Vec3::ZERO);+ let a = (a / MIDDLE_GREY).powf_each(self.contrast) * MIDDLE_GREY;+ let (shadows, highlights) = (1.0 - smoothstep(0.0, SHADOWS_MAX, l), smoothstep(HIGHLIGHTS_MIN, HIGHLIGHTS_MAX, l));+ a * (Vec3::ONE + (self.shadows_gain - 1.0) * shadows + (self.highlights_gain - 1.0) * highlights)+ }++ /// Step 4: the RRT's glow and red modifier (aces-dev 1.3, `RRT.ctl` and `ACESlib.RRT_Common.ctl`: `glow_fwd`,+ /// `sigmoid_shaper`, `rgb_2_saturation`, `rgb_2_yc`, `rgb_2_hue`, `cubic_basis_shaper`), AP1 in and out.+ fn sweeten(&self, a: Vec3) -> Vec3 {+ let mut aces = self.ap1_to_ap0 * a;+ let (hi, lo) = (aces.max_element(), aces.min_element());+ let saturation = (hi.max(1e-10) - lo.max(1e-10)) / hi.max(1e-2);+ // Glow: a gain on dark colours (below `RRT_GLOW_MID` of the luminance proxy YC), by their saturation.+ let chroma = (aces.z * (aces.z - aces.y) + aces.y * (aces.y - aces.x) + aces.x * (aces.x - aces.z)).max(0.0).sqrt();+ let yc = (aces.x + aces.y + aces.z + 1.75 * chroma) / 3.0;+ let x = (saturation - 0.4) / 0.2;+ let t = (1.0 - (x / 2.0).abs()).max(0.0);+ let shaped = (1.0 + x.signum() * (1.0 - t * t)) / 2.0;+ let gain = RRT_GLOW_GAIN * shaped;+ let glow = if yc <= 2.0 / 3.0 * RRT_GLOW_MID {+ gain+ } else if yc >= 2.0 * RRT_GLOW_MID {+ 0.0} else {- let bt = (out_match + self.black_clip) / toe_scale - 1.0;- in_match.log10() - 0.5 * ((1.0 + bt) / (1.0 - bt)).ln() * (toe_scale / self.slope)+ gain * (RRT_GLOW_MID / yc - 0.5)};- let straight_match = (1.0 - self.toe) / self.slope - toe_match;- let shoulder_match = self.shoulder / self.slope - straight_match;- let f = |c: f32| -> f32 {- let log_c = c.max(1e-10).log10();- let straight = self.slope * (log_c + straight_match);- let mut toe = -self.black_clip + (2.0 * toe_scale) / (1.0 + ((-2.0 * self.slope / toe_scale) * (log_c - toe_match)).exp());- let mut sh = (1.0 + self.white_clip) - (2.0 * shoulder_scale) / (1.0 + ((2.0 * self.slope / shoulder_scale) * (log_c - shoulder_match)).exp());- if log_c >= toe_match {- toe = straight;- }- if log_c <= shoulder_match {- sh = straight;- }- let mut t = ((log_c - toe_match) / (shoulder_match - toe_match)).clamp(0.0, 1.0);- if shoulder_match < toe_match {- t = 1.0 - t;+ aces *= 1.0 + glow;+ // Red modifier: red hues (a cubic B-spline window `RRT_RED_WIDTH` degrees wide about hue 0) move toward+ // `RRT_RED_PIVOT`, by their saturation.+ if aces.x != aces.y || aces.y != aces.z {+ let hue = (3f32.sqrt() * (aces.y - aces.z)).atan2(2.0 * aces.x - aces.y - aces.z).to_degrees();+ let k = (hue + RRT_RED_WIDTH / 2.0) * 4.0 / RRT_RED_WIDTH;+ if k > 0.0 && k < 4.0 {+ let (j, t) = (k.floor(), k - k.floor());+ let window = match j as i32 {+ 0 => t * t * t / 6.0,+ 1 => (-3.0 * t * t * t + 3.0 * t * t + 3.0 * t + 1.0) / 6.0,+ 2 => (3.0 * t * t * t - 6.0 * t * t + 4.0) / 6.0,+ _ => (1.0 - t) * (1.0 - t) * (1.0 - t) / 6.0,+ } * 1.5;+ aces.x += window * saturation * (RRT_RED_PIVOT - aces.x) * (1.0 - RRT_RED_SCALE);}- t = (3.0 - 2.0 * t) * t * t;- toe + (sh - toe) * t- };- let tone = Vec3::new(f(wc.x), f(wc.y), f(wc.z));- Vec3::splat(tone.dot(AP1_RGB2Y)).lerp(tone, 0.93).max(Vec3::ZERO)+ }+ (self.ap0_to_ap1 * aces.max(Vec3::ZERO)).max(Vec3::ZERO)}- /// Exposed linear sRGB scene color -> display-referred linear sRGB (before the sRGB OETF).+ /// Exposed linear sRGB scene colour -> display-referred linear sRGB (before the sRGB encoding; not clipped at 1:+ /// the curve's top is `ToneCurve::white`).pub fn apply(&self, linear: Vec3) -> Vec3 {- let m = &self.m;- let mut ap1 = m.srgb_to_ap1 * (self.white_balance * linear);- ap1 = self.grade(ap1);- let luma = ap1.dot(AP1_RGB2Y);- let chroma = ap1 / luma.max(1e-10);- let cd = (chroma - Vec3::ONE).length_squared();- let expand_amount = (1.0 - (-4.0 * cd).exp2()) * (1.0 - (-4.0 * self.expand_gamut * luma * luma).exp2());- if luma > 0.0 {- ap1 = ap1.lerp(m.expand * ap1, expand_amount);+ let c = if linear.is_finite() { linear.max(Vec3::ZERO) } else { Vec3::ZERO };+ let mut a = self.wb_to_ap1 * c;+ if self.graded {+ a = self.grade(a.max(Vec3::ZERO));}- ap1 = ap1.lerp(m.blue * ap1, self.blue_correction);- let toned = self.film_tonemap(ap1);- ap1 = ap1.lerp(toned, self.tone_curve_amount);- ap1 = ap1.lerp(m.blue_inv * ap1, self.blue_correction);- (m.ap1_to_srgb * ap1).max(Vec3::ZERO)+ a = self.sweeten(a);+ // Gamut expansion: by (1 - exp(-(L / L0)^2)) (1 - exp(-(d / d0)^2)), L the luminance and d the colour's+ // distance from its grey over L.+ let l = a.dot(self.luma).max(1e-9);+ let d = (a - l).length() / l;+ let w = self.expand_amount * (1.0 - (-(l / EXPAND_LUMINANCE).powi(2)).exp()) * (1.0 - (-(d / EXPAND_CHROMA).powi(2)).exp());+ a += self.expand * a * w;+ // (Negatives are clipped before the desaturation, as the RRT does: a colour outside the rendering gamut keeps+ // the grey the desaturation gives it.)+ let v = (self.pre * (self.blue * a).max(Vec3::ZERO)).max(Vec3::ZERO);+ let t = Vec3::new(self.curve.at(v.x), self.curve.at(v.y), self.curve.at(v.z));+ (self.post * t).max(Vec3::ZERO)}}-impl Tonemapper {- /// UE ColorCorrect (PostProcessCombineLUTs): saturation and contrast around 0.18, then shadow / highlight gains- /// weighted by luma (ColorCorrectionShadowsMax 0.09, HighlightsMin 0.5 defaults).- fn grade(&self, ap1: Vec3) -> Vec3 {- let luma = ap1.dot(AP1_RGB2Y);- let mut c = (Vec3::splat(luma) + (ap1 - Vec3::splat(luma)) * self.saturation).max(Vec3::ZERO);- if self.contrast != Vec3::ONE {- let k = c / 0.18;- c = Vec3::new(k.x.powf(self.contrast.x), k.y.powf(self.contrast.y), k.z.powf(self.contrast.z)) * 0.18;- }- let ws = 1.0 - smoothstep(0.0, 0.09, luma);- let wh = smoothstep(0.5, 1.0, luma);- c * (ws * self.shadows_gain + wh * self.highlights_gain + Vec3::splat(1.0 - ws - wh))- }+trait PowfEach {+ fn powf_each(self, e: Vec3) -> Vec3;}-/// UE WhiteBalance: chromaticity of the D-series illuminant (Planckian locus below 4000 K) at `temp`, shifted by-/// `tint` along the isotherm, adapted to D65 with the Bradford transform; returned as a linear-sRGB matrix.-fn white_balance(temp: f32, tint: f32) -> Mat3 {- if (temp - 6500.0).abs() < 1.0 && tint == 0.0 {- return Mat3::IDENTITY;+impl PowfEach for Vec3 {+ fn powf_each(self, e: Vec3) -> Vec3 {+ Vec3::new(self.x.powf(e.x), self.y.powf(e.y), self.z.powf(e.z))}- let t = temp.clamp(1900.0, 25000.0) as f64;- let (mut x, mut y) = if t >= 4000.0 {- let x = if t <= 7000.0 { 0.244063 + 0.09911e3 / t + 2.9678e6 / (t * t) - 4.6070e9 / (t * t * t) } else { 0.237040 + 0.24748e3 / t + 1.9018e6 / (t * t) - 2.0064e9 / (t * t * t) };- (x, -3.0 * x * x + 2.87 * x - 0.275)- } else {- // Krystek 1985 Planckian locus in uv, then to xy.- let u = (0.860117757 + 1.54118254e-4 * t + 1.28641212e-7 * t * t) / (1.0 + 8.42420235e-4 * t + 7.08145163e-7 * t * t);- let v = (0.317398726 + 4.22806245e-5 * t + 4.20481691e-8 * t * t) / (1.0 - 2.89741816e-5 * t + 1.61456053e-7 * t * t);- (3.0 * u / (2.0 * u - 8.0 * v + 4.0), 2.0 * v / (2.0 * u - 8.0 * v + 4.0))- };- if tint != 0.0 {- // Offset perpendicular to the locus in uv (UE: Tint * 0.05 / sqrt(du^2 + dv^2)), approximated in xy.- let k = tint as f64 * 0.05 * 0.5;- let (dx, dy) = (-(y - 0.3290), x - 0.3127);- let l = (dx * dx + dy * dy).sqrt().max(1e-6);- x += k * dx / l;- y += k * dy / l;- }- let xyz = |x: f64, y: f64| Vec3::new((x / y) as f32, 1.0, ((1.0 - x - y) / y) as f32);- let bradford = m3([[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]]);- let src = bradford * xyz(x, y);- let dst = bradford * xyz(0.3127, 0.3290);- let cat = bradford.inverse() * Mat3::from_diagonal(dst / src) * bradford;- let srgb_to_xyz = m3([[0.4123907993, 0.3575843394, 0.1804807884], [0.2126390059, 0.7151686788, 0.0721923154], [0.0193308187, 0.1191947798, 0.9505321522]]);- srgb_to_xyz.inverse() * cat * srgb_to_xyz-}--/// Per-pixel film grain (UE FilmGrainIntensity): mid-tone weighted multiplicative noise.-pub fn grain(d: Vec3, intensity: f32, hash: u32) -> Vec3 {- if intensity <= 0.0 {- return d;- }- let mut h = hash.wrapping_mul(747796405).wrapping_add(2891336453);- h = ((h >> ((h >> 28) + 4)) ^ h).wrapping_mul(277803737);- h = (h >> 22) ^ h;- let n = (h >> 8) as f32 / 16777216.0 - 0.5;- let l = d.dot(Vec3::new(0.2126, 0.7152, 0.0722)).clamp(0.0, 1.0);- d * (1.0 + intensity * n * 0.6 * (1.0 - (2.0 * l - 1.0).powi(2)).max(0.15))}+/// The sRGB encoding (IEC 61966-2-1).pub fn linear_to_srgb(c: f32) -> f32 {if c < 0.0031308 {c * 12.92@@ -441,162 +531,689 @@ pub fn linear_to_srgb(c: f32) -> f32 {}}-/// UE local exposure (PostProcessTonemap / CalculateLogLocalExposure with zero thresholds): per pixel-/// exp2((base - mid) * (contrast - 1) + (L - base) * (detail - 1)), L = log2 of the exposed luminance (uniform RGB-/// weights), base = lerp(bilateral grid of L, wide Gaussian blur of L, blend), mid = log2(0.18 * compensation).-pub fn local_exposure(exposed: &Image, p: &PostPreset, compensation: f32) -> Option<Vec<f32>> {- let le = &p.local_exposure;- if le.highlight_contrast == 1.0 && le.shadow_contrast == 1.0 && le.detail_strength == 1.0 {- return None;+/// The live path's colour table (live/targets.rs `tonemap_lut`): `LUT_SIZE` texels a side, indexed by exposed linear+/// sRGB on a log2 axis, `LUT_LOG_MIN` .. `LUT_LOG_MAX` stops (0.0007 .. 90) over its texels' centres. The tone curve+/// is a function of log exposure, so equal steps of the table are equal steps of the curve (0.36 stops a texel: greys+/// come out within a third of an 8-bit step of `Tonemapper::apply`); below the range the curve is under 2e-5 (black+/// in 8 bits), above it over 1 (white).+pub const LUT_SIZE: u32 = 48;+pub const LUT_LOG_MIN: f32 = -10.5;+pub const LUT_LOG_MAX: f32 = 6.5;++/// The exposed linear value at position `t` (0 .. 1) of the table's axis.+pub fn lut_value(t: f32) -> f32 {+ 2f32.powf(LUT_LOG_MIN + t * (LUT_LOG_MAX - LUT_LOG_MIN))+}++/// Position (0 .. 1) of an exposed linear value on the table's axis (the same in live.wgsl `post`).+pub fn lut_coord(x: f32) -> f32 {+ ((x.max(1e-9).log2() - LUT_LOG_MIN) / (LUT_LOG_MAX - LUT_LOG_MIN)).clamp(0.0, 1.0)+}++// ------------------------------------------------------------------------------------------------ bloom++/// Bloom's pyramid: levels of 1/4, 1/8 .. 1/128 of the output (each way).+pub const BLOOM_LEVELS: usize = 6;++/// Size of level `j` (0 = the quarter-resolution level) of an output of `w` x `h`.+pub fn bloom_dim(w: u32, h: u32, j: usize) -> (u32, u32) {+ let (mut lw, mut lh) = (w.div_ceil(4), h.div_ceil(4));+ for _ in 0..j {+ (lw, lh) = (lw.div_ceil(2), lh.div_ceil(2));}- let (w, h) = (exposed.w, exposed.h);- let lum: Vec<f32> = exposed.px.par_iter().map(|c| ((c.x + c.y + c.z) / 3.0).max(1e-6).log2()).collect();- // Bilateral grid: 32 px cells x 16 log-luminance slices, splat, 3x3x3 blur, trilinear slice.- const CELL: usize = 32;- const Z: usize = 16;- let (gw, gh) = (w.div_ceil(CELL) + 1, h.div_ceil(CELL) + 1);- let (lmin, lmax) = (-16.0f32, 8.0f32);- let zpos = |l: f32| ((l - lmin) / (lmax - lmin)).clamp(0.0, 1.0) * (Z - 1) as f32;- let mut grid = vec![[0f32; 2]; gw * gh * Z];- for y in 0..h {- for x in 0..w {- let l = lum[y * w + x];- let (gx, gy, gz) = ((x as f32 / CELL as f32).round() as usize, (y as f32 / CELL as f32).round() as usize, zpos(l).round() as usize);- let c = &mut grid[(gz * gh + gy) * gw + gx];- c[0] += l;- c[1] += 1.0;- }+ (lw.max(1), lh.max(1))+}++/// Texels of the pyramid's buffer: the levels one after another, then the coarsest eight times more (the wide+/// Gaussians' sum, and their seven row blurs: live.wgsl `bloom_wide`, `bloom_wide_rows`).+pub fn bloom_texels(w: u32, h: u32) -> u64 {+ let n = |j| bloom_dim(w, h, j).0 as u64 * bloom_dim(w, h, j).1 as u64;+ (0..BLOOM_LEVELS).map(n).sum::<u64>() + 8 * n(BLOOM_LEVELS - 1)+}++/// A bloom stage's Gaussian: its standard deviation as a fraction of the stage's size (`sizes[k]` x `sizeScale`,+/// percent of the view width), and the share of `intensity` x `tints[k]` it adds. Both fitted to the reference+/// pictures of the look the presets ask for (seven scenes, with the vignette's reach).+const BLOOM_SIGMA: f32 = 0.1;+const BLOOM_GAIN: f32 = 0.175;++/// Variance (output pixels^2, each way) of the live final pass's kernel of the output's own pixels: the pixel and+/// its four neighbours, a fifth each.+const FINE_VARIANCE: f64 = 0.4;+/// The widest kernel of the direct pass, texels of the coarsest level each way.+const WIDE_RADIUS: u32 = 24;+/// The narrowest Gaussian the direct pass sums on the coarsest level's grid (texels): narrower ones are a blend of+/// it and the level itself.+const WIDE_MIN_SIGMA: f64 = 0.6;++/// What the bloom passes do for a preset and an output size: how much of each pyramid level and of each wide+/// Gaussian the sum takes (`Pyramid`), for the colour (bloom) and for the fourth channel (the wide blur of log+/// luminance local exposure blends its base with).+///+/// A stage is a Gaussian of standard deviation s (output pixels). The pyramid's level j, brought back up to the+/// output, is the image under a kernel of known variance V_j (`level_variance`): a stage between two levels is their+/// blend with the stage's variance (the blend has the right energy and second moment); a stage wider than the+/// coarsest level is a Gaussian summed directly on that level's grid, of the variance that is missing.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct BloomPlan {+ /// Whether the pyramid is needed at all (bloom or local exposure on).+ pub on: bool,+ /// Colour: weight of the five-pixel kernel of the output's own pixels (stages narrower than the first level; 0+ /// at the sizes where no stage is); weight of each level; per wide Gaussian its weight and 1 / (2 sigma^2) in+ /// texels of the coarsest level (weight 0: unused; the passes divide each kernel by its sum over `radius`).+ pub fine: f32,+ pub level: [f32; BLOOM_LEVELS],+ pub wide: [[f32; 2]; 6],+ /// The same for the fourth channel: one Gaussian, weights summing to 1.+ pub base_level: [f32; BLOOM_LEVELS],+ pub base_wide: [f32; 2],+ /// The direct pass's reach, texels of the coarsest level each way.+ pub radius: u32,+ /// Bloom threshold in exposed luminance (< 0: everything blooms).+ pub threshold: f32,+}++/// Variance (output pixels^2) of pyramid level `j` as the final picture samples it. Down: a 4 x 4 box from the output+/// (variance (16 - 1) / 12), then per level the binomial [1 3 3 1] / 8 at the finer level's spacing s (0.75 s^2).+/// Up: each bilinear interpolation is a tent of the coarser spacing (s^2 / 6), down to the output's pixels.+fn level_variance(j: usize) -> f64 {+ let mut v = 1.25;+ for m in 0..j {+ v += 0.75 * 16f64 * 4f64.powi(m as i32);}- let mut blurred_grid = grid.clone();- for axis in 0..3 {- let src = blurred_grid.clone();- for z in 0..Z {- for y in 0..gh {- for x in 0..gw {- let mut acc = [0f32; 2];- for (d, wgt) in [(-1i64, 0.25f32), (0, 0.5), (1, 0.25)] {- let (mut xx, mut yy, mut zz) = (x as i64, y as i64, z as i64);- match axis {- 0 => xx += d,- 1 => yy += d,- _ => zz += d,- }- if xx < 0 || yy < 0 || zz < 0 || xx >= gw as i64 || yy >= gh as i64 || zz >= Z as i64 {- continue;- }- let s = src[(zz as usize * gh + yy as usize) * gw + xx as usize];- acc[0] += s[0] * wgt;- acc[1] += s[1] * wgt;+ for m in 0..=j {+ v += 16f64 * 4f64.powi(m as i32) / 6.0;+ }+ v+}++/// The preset's bloom as Gaussians of an output `w` pixels wide: per stage that adds anything (up to six) its+/// weight and its standard deviation, output pixels.+pub fn bloom_stages(p: &PostPreset, w: u32) -> Vec<(f32, f32)> {+ let b = &p.bloom;+ if b.intensity <= 0.0 {+ return vec![];+ }+ (0..b.sizes.len().min(b.tints.len()).min(6))+ .map(|k| (b.intensity * BLOOM_GAIN * b.tints[k], (BLOOM_SIGMA * b.sizes[k] * b.size_scale / 100.0 * w as f32).max(0.0)))+ .filter(|s| s.0 > 0.0)+ .collect()+}++/// The standard deviation (output pixels) of local exposure's wide blur, if local exposure does anything.+pub fn local_exposure_sigma(p: &PostPreset, w: u32) -> Option<f32> {+ let lx = &p.local_exposure;+ (lx.highlight_contrast != 1.0 || lx.shadow_contrast != 1.0 || lx.detail_strength != 1.0).then(|| (BLOOM_SIGMA * lx.blurred_luminance_kernel / 100.0 * w as f32).max(0.0))+}++/// A Gaussian blur of standard deviation `sigma` pixels of an image (edge pixels repeat outward): the offline+/// chain's bloom stages and wide luminance blur, to the kernel's own shape (the live passes approximate the same+/// Gaussians on a pyramid: `BloomPlan`).+///+/// A wide Gaussian is taken on a smaller image: box-reduced by a power of two until sigma is at most 6 texels,+/// blurred there by the separable kernel (out to 3.5 sigma), and brought back bilinearly, the Gaussian narrowed by+/// the variance the box ((f^2 - 1) / 12) and the bilinear tent (f^2 / 6) add.+pub fn gaussian(src: &[Vec3], w: usize, h: usize, sigma: f32) -> Vec<Vec3> {+ if sigma <= 0.05 {+ return src.to_vec();+ }+ let mut f = 1usize;+ while sigma / f as f32 > 6.0 && w.min(h) / (f * 2) >= 4 {+ f *= 2;+ }+ let (lw, lh) = (w.div_ceil(f), h.div_ceil(f));+ let small: Vec<Vec3> = if f == 1 {+ src.to_vec()+ } else {+ (0..lw * lh)+ .into_par_iter()+ .map(|i| {+ let (bx, by) = (i % lw * f, i / lw * f);+ let (mut s, mut n) = (Vec3::ZERO, 0f32);+ for y in by..(by + f).min(h) {+ for x in bx..(bx + f).min(w) {+ s += src[y * w + x];+ n += 1.0;}- blurred_grid[(z * gh + y) * gw + x] = acc;}- }- }+ s / n+ })+ .collect()+ };+ let ff = (f * f) as f32;+ let var = if f == 1 { sigma * sigma } else { ((sigma * sigma - (ff - 1.0) / 12.0 - ff / 6.0) / ff).max(0.25) };+ let r = (3.5 * var.sqrt()).ceil() as isize;+ let k: Vec<f32> = (-r..=r).map(|d| (-(d * d) as f32 / (2.0 * var)).exp()).collect();+ let norm: f32 = k.iter().sum();+ let pass = |img: &[Vec3], horizontal: bool| -> Vec<Vec3> {+ (0..lw * lh)+ .into_par_iter()+ .map(|i| {+ let (x, y) = ((i % lw) as isize, (i / lw) as isize);+ let mut s = Vec3::ZERO;+ for (j, kj) in k.iter().enumerate() {+ let d = j as isize - r;+ let (sx, sy) = if horizontal { ((x + d).clamp(0, lw as isize - 1), y) } else { (x, (y + d).clamp(0, lh as isize - 1)) };+ s += img[sy as usize * lw + sx as usize] * *kj;+ }+ s / norm+ })+ .collect()+ };+ let blurred = pass(&pass(&small, true), false);+ if f == 1 {+ return blurred;}- // Wide blur of L (separable Gaussian at 1/8 resolution, sigma = kernel% of the width / 4).- let (bw, bh) = (w.div_ceil(8), h.div_ceil(8));- let mut small = vec![0f32; bw * bh];- for y in 0..bh {- for x in 0..bw {- let (mut s, mut n) = (0f32, 0f32);- for yy in y * 8..((y + 1) * 8).min(h) {- for xx in x * 8..((x + 1) * 8).min(w) {- s += lum[yy * w + xx];- n += 1.0;+ let low = Image { w: lw, h: lh, px: blurred };+ (0..w * h).into_par_iter().map(|i| low.bilinear(((i % w) as f32 + 0.5) / f as f32 - 0.5, ((i / w) as f32 + 0.5) / f as f32 - 0.5)).collect()+}++impl BloomPlan {+ pub fn new(p: &PostPreset, w: u32, _h: u32) -> BloomPlan {+ let b = &p.bloom;+ let mut plan = BloomPlan { threshold: b.threshold, ..Default::default() };+ let coarsest = 4f64 * 2f64.powi(BLOOM_LEVELS as i32 - 1);+ let mut sigma_max = 0f64;+ // One Gaussian of variance `var` (output px^2) and weight `a`: into the levels, or the direct pass; narrower+ // than the first level, a blend of it and the five-pixel kernel of the output's own pixels (variance+ // FINE_VARIANCE), where there is one (`fine`: the colour's).+ let mut place = |a: f32, var: f64, fine: Option<&mut f32>, level: &mut [f32; BLOOM_LEVELS], wide: &mut [f32; 2]| {+ let top = level_variance(BLOOM_LEVELS - 1);+ if var <= level_variance(0) {+ let t = match &fine {+ Some(_) => ((var - FINE_VARIANCE) / (level_variance(0) - FINE_VARIANCE)).clamp(0.0, 1.0) as f32,+ None => 1.0,+ };+ level[0] += a * t;+ if let Some(f) = fine {+ *f += a * (1.0 - t);}+ } else if var <= top {+ let j = (0..BLOOM_LEVELS - 1).find(|&j| var <= level_variance(j + 1)).unwrap();+ let t = ((var - level_variance(j)) / (level_variance(j + 1) - level_variance(j))) as f32;+ level[j] += a * (1.0 - t);+ level[j + 1] += a * t;+ } else {+ // Texels^2 of the coarsest level still missing.+ let need = (var - top) / (coarsest * coarsest);+ let min = WIDE_MIN_SIGMA * WIDE_MIN_SIGMA;+ let t = (need / min).min(1.0) as f32;+ let sigma = need.max(min).sqrt();+ level[BLOOM_LEVELS - 1] += a * (1.0 - t);+ *wide = [a * t, (0.5 / (sigma * sigma)) as f32];+ sigma_max = sigma_max.max(sigma);}- small[y * bw + x] = s / n.max(1.0);+ };+ let stages = bloom_stages(p, w);+ for (k, (a, sigma)) in stages.iter().enumerate() {+ let sigma = *sigma as f64;+ place(*a, sigma * sigma, Some(&mut plan.fine), &mut plan.level, &mut plan.wide[k]);+ }+ let local = local_exposure_sigma(p, w);+ if let Some(sigma) = local {+ place(1.0, (sigma * sigma) as f64, None, &mut plan.base_level, &mut plan.base_wide);+ }+ plan.on = !stages.is_empty() || local.is_some();+ plan.radius = ((3.0 * sigma_max).ceil() as u32).clamp(1, WIDE_RADIUS);+ plan+ }++ pub fn has_wide(&self) -> bool {+ self.wide.iter().any(|g| g[0] > 0.0) || self.base_wide[0] > 0.0+ }+}++/// The pyramid on the CPU, as the live passes build it (live.wgsl `lum_down`, `bloom_down`, `bloom_wide`,+/// `bloom_up`): rgb the bloom, w the log2 luminance. The tests' model of the passes' arithmetic (`BloomPlan`'s+/// weights against the Gaussians they stand for).+#[cfg(test)]+struct Pyramid {+ dims: [(usize, usize); BLOOM_LEVELS],+ /// Level 0 after the sum: what the final pass samples.+ sum: Vec<[f32; 4]>,+}++#[cfg(test)]+fn texel(l: &[[f32; 4]], (w, h): (usize, usize), x: isize, y: isize) -> [f32; 4] {+ l[y.clamp(0, h as isize - 1) as usize * w + x.clamp(0, w as isize - 1) as usize]+}++#[cfg(test)]+fn bilinear4(l: &[[f32; 4]], dim: (usize, usize), x: f32, y: f32) -> [f32; 4] {+ let (x0, y0) = (x.floor(), y.floor());+ let (fx, fy) = (x - x0, y - y0);+ let (x0, y0) = (x0 as isize, y0 as isize);+ let (a, b, c, d) = (texel(l, dim, x0, y0), texel(l, dim, x0 + 1, y0), texel(l, dim, x0, y0 + 1), texel(l, dim, x0 + 1, y0 + 1));+ std::array::from_fn(|k| (a[k] * (1.0 - fx) + b[k] * fx) * (1.0 - fy) + (c[k] * (1.0 - fx) + d[k] * fx) * fy)+}++#[cfg(test)]+impl Pyramid {+ /// From the quarter-resolution level (`lum_down`'s).+ fn new(level0: Vec<[f32; 4]>, w: usize, h: usize, plan: &BloomPlan) -> Pyramid {+ let dims: [(usize, usize); BLOOM_LEVELS] = std::array::from_fn(|j| {+ let (lw, lh) = bloom_dim(w as u32, h as u32, j);+ (lw as usize, lh as usize)+ });+ // Down: each level the one above under the binomial [1 3 3 1] / 8 each way, centred between its texels.+ let mut levels = vec![level0];+ for j in 1..BLOOM_LEVELS {+ let (src, sd, (lw, lh)) = (&levels[j - 1], dims[j - 1], dims[j]);+ const K: [f32; 4] = [0.125, 0.375, 0.375, 0.125];+ let next: Vec<[f32; 4]> = (0..lw * lh)+ .into_par_iter()+ .map(|i| {+ let (x, y) = ((i % lw) as isize * 2, (i / lw) as isize * 2);+ let mut s = [0f32; 4];+ for (dy, ky) in K.iter().enumerate() {+ for (dx, kx) in K.iter().enumerate() {+ let t = texel(src, sd, x + dx as isize - 1, y + dy as isize - 1);+ for k in 0..4 {+ s[k] += t[k] * kx * ky;+ }+ }+ }+ s+ })+ .collect();+ levels.push(next);}+ // The coarsest level: its own weight, and the wide Gaussians summed over it (edge texels repeat outward).+ let top = BLOOM_LEVELS - 1;+ let mut up = Self::wide(&levels[top], dims[top], plan);+ // Up: each level by its weight, plus the sum so far, bilinear.+ for j in (0..top).rev() {+ let (lw, lh) = dims[j];+ let (coarse, cd, own) = (&up, dims[j + 1], &levels[j]);+ let (wc, wb) = (plan.level[j], plan.base_level[j]);+ up = (0..lw * lh)+ .into_par_iter()+ .map(|i| {+ let c = bilinear4(coarse, cd, ((i % lw) as f32 + 0.5) / 2.0 - 0.5, ((i / lw) as f32 + 0.5) / 2.0 - 0.5);+ let o = own[i];+ [o[0] * wc + c[0], o[1] * wc + c[1], o[2] * wc + c[2], o[3] * wb + c[3]]+ })+ .collect();+ }+ Pyramid { dims, sum: up }}- let sigma = (le.blurred_luminance_kernel / 100.0 * bw as f32 / 4.0).max(0.5);- let r = (sigma * 2.5).ceil() as i64;- let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();- let blur1 = |src: &[f32], horizontal: bool| -> Vec<f32> {- (0..bw * bh)++ fn wide(l: &[[f32; 4]], dim: (usize, usize), plan: &BloomPlan) -> Vec<[f32; 4]> {+ let (lw, lh) = dim;+ let (wc, wb) = (plan.level[BLOOM_LEVELS - 1], plan.base_level[BLOOM_LEVELS - 1]);+ let r = if plan.has_wide() { plan.radius as isize } else { 0 };+ // (Each kernel over its sum, as the passes divide it: `bloom_wide_rows` the rows', `bloom_wide` the columns'.)+ let norm = |inv: f32| (-r..=r).map(|d| (-(d * d) as f32 * inv).exp()).sum::<f32>().powi(2);+ let pair = |g: [f32; 2]| if g[0] > 0.0 { [g[0] / norm(g[1]), g[1]] } else { g };+ let (wide, base_wide) = (plan.wide.map(pair), pair(plan.base_wide));+ (0..lw * lh).into_par_iter().map(|i| {- let (x, y) = ((i % bw) as i64, (i / bw) as i64);- let (mut s, mut ws) = (0f32, 0f32);- for (j, wgt) in k.iter().enumerate() {- let o = j as i64 - r;- let (xx, yy) = if horizontal { ((x + o).clamp(0, bw as i64 - 1), y) } else { (x, (y + o).clamp(0, bh as i64 - 1)) };- s += src[yy as usize * bw + xx as usize] * wgt;- ws += wgt;+ let (x, y) = ((i % lw) as isize, (i / lw) as isize);+ let o = l[i];+ let mut s = [o[0] * wc, o[1] * wc, o[2] * wc, o[3] * wb];+ if r > 0 {+ for dy in -r..=r {+ for dx in -r..=r {+ let d2 = (dx * dx + dy * dy) as f32;+ let (mut g, gb) = (0f32, base_wide[0] * (-d2 * base_wide[1]).exp());+ for k in wide {+ if k[0] > 0.0 {+ g += k[0] * (-d2 * k[1]).exp();+ }+ }+ let t = texel(l, dim, x + dx, y + dy);+ s = [s[0] + t[0] * g, s[1] + t[1] * g, s[2] + t[2] * g, s[3] + t[3] * gb];+ }+ }}- s / ws+ s}).collect()- };- let wide = blur1(&blur1(&small, true), false);- let mid = (0.18 * compensation).log2();- Some(- (0..w * h)- .into_par_iter()- .map(|i| {- let (x, y) = (i % w, i / w);- let l = lum[i];- // trilinear slice of the bilateral grid at (x, y, l)- let (fx, fy, fz) = (x as f32 / CELL as f32, y as f32 / CELL as f32, zpos(l));- let (x0, y0, z0) = (fx.floor() as usize, fy.floor() as usize, fz.floor() as usize);- let (tx, ty, tz) = (fx - x0 as f32, fy - y0 as f32, fz - z0 as f32);- let mut acc = [0f32; 2];- for c in 0..8 {- let (dx, dy, dz) = (c & 1, (c >> 1) & 1, (c >> 2) & 1);- let (xx, yy, zz) = ((x0 + dx).min(gw - 1), (y0 + dy).min(gh - 1), (z0 + dz).min(Z - 1));- let wgt = (if dx == 1 { tx } else { 1.0 - tx }) * (if dy == 1 { ty } else { 1.0 - ty }) * (if dz == 1 { tz } else { 1.0 - tz });- let g = blurred_grid[(zz * gh + yy) * gw + xx];- acc[0] += g[0] * wgt;- acc[1] += g[1] * wgt;+ }++ /// The sum at output pixel (x, y): rgb the bloom (unexposed), w the wide blur of log2 luminance.+ fn at(&self, x: usize, y: usize) -> [f32; 4] {+ bilinear4(&self.sum, self.dims[0], (x as f32 + 0.5) / 4.0 - 0.5, (y as f32 + 0.5) / 4.0 - 0.5)+ }+}++/// How much of a pixel blooms: all of it under a negative threshold; else nothing up to the threshold (exposed+/// luminance) and all of it one unit above (the setting's documented band).+fn bloom_share(exposed_luminance: f32, threshold: f32) -> f32 {+ if threshold < 0.0 { 1.0 } else { (exposed_luminance - threshold).clamp(0.0, 1.0) }+}++/// The darkest log2 luminance local exposure reasons about: 12 stops under middle grey at the frame's exposure+/// (black, log2 0, would otherwise drag every base around it down without end).+fn log_floor(exposure: f32) -> f32 {+ (MIDDLE_GREY / 4096.0 / exposure.max(1e-20)).log2()+}++// ------------------------------------------------------------------------------------------------ local exposure++/// Local exposure's factor for a pixel of exposed log2 luminance `l`, given the base layer's two estimates there+/// (exposed log2 luminance: `edge`, the edge-aware blur; `wide`, the wide Gaussian blur) and the pivot (log2).+///+/// A base / detail decomposition of log luminance (Durand & Dorsey 2002, "Fast Bilateral Filtering for the Display+/// of High-Dynamic-Range Images", section 6): the base is what an edge-preserving blur leaves, the detail the rest;+/// the base's distance from the pivot is scaled (`highlightContrast` above it, `shadowContrast` below), the detail+/// by `detailStrength`. The base is the edge-aware blur blended with a wide plain blur by `blurredLuminanceBlend`+/// (same meanings as Unreal's Local Exposure settings, per its documentation: the blend keeps highlights' shape+/// and avoids the edge-aware filter's ringing). All 1: factor 1.+pub fn local_exposure_factor(lx: &crate::desc::LocalExposure, l: f32, edge: f32, wide: f32, pivot: f32) -> f32 {+ let base = edge + (wide - edge) * lx.blurred_luminance_blend.clamp(0.0, 1.0);+ let contrast = if base > pivot { lx.highlight_contrast } else { lx.shadow_contrast };+ let out = pivot + (base - pivot) * contrast + (l - base) * lx.detail_strength;+ 2f32.powf((out - l).clamp(-8.0, 8.0))+}++/// The edge-aware blur of the quarter-resolution log2 luminance: live.wgsl `lum_blur`, on the CPU (9 x 9 taps two+/// texels apart, a Gaussian in space times a Gaussian in the difference of log2 luminance).+fn lum_blur(l: &[f32], w: usize, h: usize) -> Vec<f32> {+ (0..w * h)+ .into_par_iter()+ .map(|p| {+ let (px, py) = ((p % w) as isize, (p / w) as isize);+ let c = l[p];+ let (mut acc, mut ws) = (0f32, 0f32);+ for j in -4..=4isize {+ for i in -4..=4isize {+ let x = (px + i * 2).clamp(0, w as isize - 1) as usize;+ let y = (py + j * 2).clamp(0, h as isize - 1) as usize;+ let v = l[y * w + x];+ let d = v - c;+ let wgt = (-((i * i + j * j) as f32) / 18.0 - d * d * 0.5).exp();+ acc += v * wgt;+ ws += wgt;}- let bilateral = if acc[1] > 1e-4 { acc[0] / acc[1] } else { l };- let blurred = wide[(y / 8).min(bh - 1) * bw + (x / 8).min(bw - 1)];- let base = bilateral + (blurred - bilateral) * le.blurred_luminance_blend;- let contrast = if base > mid { le.highlight_contrast } else { le.shadow_contrast };- ((base - mid) * (contrast - 1.0) + (l - base) * (le.detail_strength - 1.0)).exp2()- })- .collect(),- )+ }+ acc / ws+ })+ .collect()}-/// Full chain: exposure, bloom, vignette, tonemap, sRGB encode -> RGBA8. `compensation` = the exposure-/// compensation (2^bias) that sets local exposure's middle grey.+// ------------------------------------------------------------------------------------------------ lens, grain++/// Vignette: the picture's falloff at `r` (distance from the centre over the half diagonal) for the setting `v`.+///+/// Natural vignetting: the illuminance of an image point falls as cos^4 of its field angle (the "cosine fourth"+/// law; e.g. Kingslake, "Optics in Photography", 1992, ch. 6). The setting is the lens' reach: the corner's field+/// angle has the tangent `VIGNETTE_FIELD` x v. Own parametrisation; `VIGNETTE_FIELD` is fitted to the reference+/// pictures at v = 0.4 (their only value: 16:9 frames).+pub fn vignette(v: f32, r: f32) -> f32 {+ let t = VIGNETTE_FIELD * v * r;+ 1.0 / ((1.0 + t * t) * (1.0 + t * t))+}+pub const VIGNETTE_FIELD: f32 = 1.425;++/// Chromatic aberration: how far red is magnified and blue reduced about the centre, a unit of the setting+/// (lateral colour: a lens' magnification varies with wavelength, so the fringe grows with the distance from the+/// centre; own design: a unit moves red and blue 0.2 % of that distance apart each way).+pub const FRINGE: f32 = 0.002;++/// Film grain's amplitude in the encoded picture at setting 1 (the standard deviation it adds to a mid grey, about+/// 9 of 255), own design.+pub const GRAIN: f32 = 0.085;++/// A 32-bit integer hash (Chris Wellons' "lowbias32", public domain: https://nullprogram.com/blog/2018/07/31/).+fn hash(mut x: u32) -> u32 {+ x ^= x >> 16;+ x = x.wrapping_mul(0x7feb352d);+ x ^= x >> 15;+ x = x.wrapping_mul(0x846ca68b);+ x ^= x >> 16;+ x+}++/// Film grain for pixel (x, y) of frame `frame` on an encoded value of luma `v`: zero-mean noise of triangular+/// distribution (the sum of two uniform numbers), the same on the three channels (luminance noise), weighted+/// 4 v (1 - v): none in black or white, most in the mid-tones. The live `post` computes the same number.+pub fn grain(x: u32, y: u32, frame: u32, v: f32, amount: f32) -> f32 {+ let h = hash(x ^ hash(y ^ hash(frame)));+ let (a, b) = ((h & 0xffff) as f32 / 65536.0, (h >> 16) as f32 / 65536.0);+ amount * GRAIN * (a + b - 1.0) * 4.0 * v * (1.0 - v)+}++// ------------------------------------------------------------------------------------------------ the chain++/// Full chain -> RGBA8. `exposure`: the scale `exposure_scale` gave. `compensation`: what local exposure's pivot is+/// over middle grey (auto exposure: 2^compensation, so the pivot is the metered average; manual: 1).+///+/// In the order a pixel goes through it: chromatic aberration (red and blue read from where the lens puts them),+/// exposure, local exposure, bloom added, vignette, colour grading and the tone curve, the sRGB encoding, film grain.+/// (The fringe is taken of the scene's image alone, not of the glow over it, and grain is added to the encoded value:+/// each is the same picture to the eye as the order a camera has them in, and the live final pass reads its inputs+/// once this way.)pub fn finish(img: &Image, exposure: f32, compensation: f32, p: &PostPreset) -> Vec<u8> {- let exposed = Image { w: img.w, h: img.h, px: img.px.iter().map(|c| *c * exposure).collect() };- let bloom = bloom(&exposed, p);- let local = local_exposure(&exposed, p, compensation);- let tm = Tonemapper::new(p);+ finish_frame(img, exposure, compensation, p, 0)+}++/// `finish` for frame `frame` of a sequence (film grain is new each frame).+pub fn finish_frame(img: &Image, exposure: f32, compensation: f32, p: &PostPreset, frame: u32) -> Vec<u8> {let (w, h) = (img.w, img.h);- let aspect = h as f32 / w as f32;- let vscale = 2f32.sqrt() / (1.0 + aspect * aspect).sqrt();- let out: Vec<[u8; 4]> = (0..w * h)- .into_par_iter()- .map(|i| {+ let tm = Tonemapper::new(p);+ let lx = &p.local_exposure;+ let clean = |c: Vec3| if c.is_finite() { c.max(Vec3::ZERO) } else { Vec3::ZERO };+ // Bloom: the sum of the stages' Gaussians of what blooms (unexposed).+ let stages = bloom_stages(p, w as u32);+ let glow: Option<Vec<Vec3>> = (!stages.is_empty()).then(|| {+ let src: Vec<Vec3> = img+ .px+ .par_iter()+ .map(|c| {+ let c = clean(*c);+ c * bloom_share(c.dot(LUMA) * exposure, p.bloom.threshold)+ })+ .collect();+ let mut sum = vec![Vec3::ZERO; w * h];+ for (a, sigma) in stages {+ let g = gaussian(&src, w, h, sigma);+ sum.par_iter_mut().zip(g).for_each(|(s, g)| *s += g * a);+ }+ sum+ });+ // Local exposure's two base layers, on the quarter-resolution log2 luminance: the edge-aware blur and the wide+ // Gaussian.+ let floor = log_floor(exposure);+ let base: Option<(Image, Image)> = local_exposure_sigma(p, w as u32).map(|sigma| {+ let (qw, qh, l) = quarter_log_luminance(img);+ let l: Vec<f32> = l.iter().map(|v| v.max(floor)).collect();+ let wide = gaussian(&l.iter().map(|v| Vec3::splat(*v)).collect::<Vec<_>>(), qw, qh, sigma / 4.0);+ let edge = lum_blur(&l, qw, qh).iter().map(|v| Vec3::splat(*v)).collect();+ (Image { w: qw, h: qh, px: edge }, Image { w: qw, h: qh, px: wide })+ });+ let centre = Vec3::new(w as f32 * 0.5, h as f32 * 0.5, 0.0);+ let half_diagonal = centre.length();+ let (fringe, pivot, log_e) = (p.chromatic_aberration.max(0.0) * FRINGE, (MIDDLE_GREY * compensation).log2(), exposure.log2());+ img.px+ .par_iter()+ .enumerate()+ .flat_map_iter(|(i, c)| {let (x, y) = (i % w, i / w);- let (u, v) = ((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);- let mut c = exposed.px[i];- if let Some(le) = &local {- c *= le[i];+ let at = Vec3::new(x as f32 + 0.5, y as f32 + 0.5, 0.0) - centre;+ let mut c = *c;+ if fringe > 0.0 {+ let (r, b) = (centre + at * (1.0 - fringe) - 0.5, centre + at * (1.0 + fringe) - 0.5);+ c = Vec3::new(img.bilinear(r.x, r.y).x, c.y, img.bilinear(b.x, b.y).z);}- if p.chromatic_aberration > 0.0 {- // UE scene fringe: red / blue sampled radially out / in.- let k = p.chromatic_aberration * 0.0025;- let (du, dv) = (u - 0.5, v - 0.5);- c.x = exposed.sample(0.5 + du * (1.0 + k), 0.5 + dv * (1.0 + k)).x;- c.z = exposed.sample(0.5 + du * (1.0 - k), 0.5 + dv * (1.0 - k)).z;+ let mut c = clean(c) * exposure;+ if let Some((edge, wide)) = &base {+ let (qx, qy) = ((x as f32 + 0.5) / 4.0 - 0.5, (y as f32 + 0.5) / 4.0 - 0.5);+ let l = c.dot(LUMA).log2().max(floor + log_e);+ c *= local_exposure_factor(lx, l, edge.bilinear(qx, qy).x + log_e, wide.bilinear(qx, qy).x + log_e, pivot);}- if let Some(b) = &bloom {- c += b.sample(u, v);+ if let Some(glow) = &glow {+ c += glow[i] * exposure;}- if p.vignette > 0.0 {- let pos = glam::Vec2::new(u * 2.0 - 1.0, 1.0 - v * 2.0) * glam::Vec2::new(1.0, aspect) * vscale * p.vignette;- let t2 = pos.length_squared();- c *= (1.0 / (t2 + 1.0)).powi(2);+ c *= vignette(p.vignette, at.length() / half_diagonal);+ let d = tm.apply(c);+ let mut e = Vec3::new(linear_to_srgb(d.x.clamp(0.0, 1.0)), linear_to_srgb(d.y.clamp(0.0, 1.0)), linear_to_srgb(d.z.clamp(0.0, 1.0)));+ if p.film_grain > 0.0 {+ e += grain(x as u32, y as u32, frame, e.dot(LUMA), p.film_grain.min(1.0));}- let d = grain(tm.apply(c), p.film_grain, i as u32 ^ 0x9e37_79b9);- // UE adds +-0.5 LSB grain quantization noise; use ordered-free rounding instead.- let q = |v: f32| (linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8;- [q(d.x), q(d.y), q(d.z), 255]+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;+ [q(e.x), q(e.y), q(e.z), 255]})- .collect();- out.into_iter().flatten().collect()+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn preset() -> PostPreset {+ let p: crate::desc::Preset = serde_json::from_str(include_str!("../../presets/cinematic.json")).unwrap();+ p.post+ }++ /// Greys stay grey, black is black, the curve is monotonic and ends at its top.+ #[test]+ fn the_tone_curve_is_a_curve() {+ let tm = Tonemapper::new(&preset());+ assert!(tm.apply(Vec3::ZERO).max_element() < 1e-6);+ let mut last = 0.0;+ for k in 0..400 {+ let x = 10f32.powf(-4.0 + k as f32 * 7.0 / 399.0);+ let d = tm.apply(Vec3::splat(x));+ assert!((d.x - d.y).abs() < 2e-4 && (d.y - d.z).abs() < 2e-4, "grey {x} -> {d}");+ assert!(d.y >= last, "not monotonic at {x}");+ last = d.y;+ }+ assert!((last - ToneCurve::default().white).abs() < 1e-3);+ // Middle grey lands near middle grey, and the branches meet where they are said to.+ let mid = ToneCurve::default();+ assert!((tm.apply(Vec3::splat(mid.mid_in)).y - mid.mid_out).abs() < 1e-3);+ assert!((tm.apply(Vec3::splat(0.18)).y - 0.18).abs() < 0.02);+ }++ /// The live table against the function it tabulates, sampled trilinearly as the final pass samples it.+ #[test]+ fn the_table_follows_the_curve() {+ let tm = Tonemapper::new(&preset());+ const N: usize = LUT_SIZE as usize;+ let enc = |d: Vec3| Vec3::new(linear_to_srgb(d.x.clamp(0.0, 1.0)), linear_to_srgb(d.y.clamp(0.0, 1.0)), linear_to_srgb(d.z.clamp(0.0, 1.0)));+ let lut: Vec<Vec3> = (0..N * N * N).map(|i| enc(tm.apply(Vec3::new(lut_value((i % N) as f32 / (N - 1) as f32), lut_value((i / N % N) as f32 / (N - 1) as f32), lut_value((i / N / N) as f32 / (N - 1) as f32))))).collect();+ let sample = |c: Vec3| {+ let t = Vec3::new(lut_coord(c.x), lut_coord(c.y), lut_coord(c.z)) * (N - 1) as f32;+ let i = t.floor().min(Vec3::splat(N as f32 - 2.0));+ let f = t - i;+ let at = |dx: usize, dy: usize, dz: usize| lut[(i.x as usize + dx) + (i.y as usize + dy) * N + (i.z as usize + dz) * N * N];+ let x = |dy, dz| at(0, dy, dz).lerp(at(1, dy, dz), f.x);+ x(0, 0).lerp(x(1, 0), f.y).lerp(x(0, 1).lerp(x(1, 1), f.y), f.z)+ };+ // Greys from 1e-3 to 60: within half an 8-bit step.+ let mut worst = 0f32;+ for k in 0..2000 {+ let x = 10f32.powf(-3.0 + k as f32 * (60f32.log10() + 3.0) / 1999.0);+ worst = worst.max((sample(Vec3::splat(x)) - enc(tm.apply(Vec3::splat(x)))).abs().max_element());+ }+ assert!(worst < 0.5 / 255.0, "greys off by {worst}");+ // Colours: within two 8-bit steps on average over a random set (the table bends where the looks do).+ let (mut sum, mut n) = (0f32, 0);+ for k in 0..20000u32 {+ let r = |s: u32| 10f32.powf(-3.0 + (hash(k * 3 + s) as f32 / u32::MAX as f32) * 4.5);+ let c = Vec3::new(r(0), r(1), r(2));+ sum += (sample(c) - enc(tm.apply(c))).abs().max_element();+ n += 1;+ }+ assert!(sum / (n as f32) < 2.0 / 255.0, "colours off by {} on average", sum / n as f32);+ }++ #[test]+ fn white_balance_at_6500_is_none_and_turns_the_right_way() {+ assert_eq!(white_balance(6500.0, 0.0), DMat3::IDENTITY);+ // A scene lit by a 3000 K lamp rendered white: the picture turns blue; by 12000 K sky: orange.+ let warm = white_balance(3000.0, 0.0) * DVec3::ONE;+ let cold = white_balance(12000.0, 0.0) * DVec3::ONE;+ assert!(warm.z > 2.0 * warm.x && cold.x > 1.5 * cold.z, "{warm} {cold}");+ // Near 6500 K it is nearly none, and continuous across the loci's joint at 4000 K.+ assert!((white_balance(6510.0, 0.0) * DVec3::ONE - DVec3::ONE).abs().max_element() < 0.01);+ assert!((white_balance(3999.0, 0.0) * DVec3::ONE - white_balance(4001.0, 0.0) * DVec3::ONE).abs().max_element() < 0.01);+ }++ #[test]+ fn metering_takes_the_window_of_the_histogram() {+ // A uniform image: its luminance, whatever the window.+ let (mut count, mut mean) = ([0f32; AE_BINS], [0f32; AE_BINS]);+ let t = (3000f32.log2() + 10.0) / 30.0;+ count[(t * 64.0) as usize] = 1000.0;+ mean[(t * 64.0) as usize] = t;+ let avg = metered_average(&count, &mean, 0.1, 0.9, -10.0, 20.0).unwrap();+ assert!((avg / 3000.0 - 1.0).abs() < 1e-3, "{avg}");+ assert!((-auto_target(avg, 0.0, -10.0, 20.0).log2() - (3000f32 / 0.18).log2()).abs() < 1e-3);+ // A tenth of the frame a hundred times brighter is outside a 10 .. 80 % window.+ let b = ((t + 6.6 / 30.0) * 64.0) as usize;+ count[b] = 100.0;+ mean[b] = t + 6.6 / 30.0;+ let avg = metered_average(&count, &mean, 0.1, 0.8, -10.0, 20.0).unwrap();+ assert!((avg / 3000.0 - 1.0).abs() < 1e-3, "{avg}");+ // The limits hold the average.+ assert!((auto_target(1e-6, 0.0, 1.0, 5.0) - 0.5).abs() < 1e-6 && (auto_target(1e9, 1.0, 1.0, 5.0) - 2.0 / 32.0).abs() < 1e-6);+ assert!(metered_average(&[0.0; AE_BINS], &mean, 0.1, 0.9, -10.0, 20.0).is_none());+ }++ /// The pyramid's sum is the sum of Gaussians it stands for: every stage's share is in the plan, and a point's+ /// glow has the narrow stages' energy near it and the second moment of their Gaussians.+ #[test]+ fn bloom_of_a_point_is_the_stages_gaussians() {+ let mut p = preset();+ let (w, h) = (960usize, 540usize);+ let plan = BloomPlan::new(&p, w as u32, h as u32);+ let stages: f32 = p.bloom.tints.iter().sum::<f32>() * p.bloom.intensity * BLOOM_GAIN;+ let wide: f32 = plan.wide.iter().map(|g| g[0]).sum();+ let levels: f32 = plan.fine + plan.level.iter().sum::<f32>();+ assert!((levels + wide - stages).abs() < 1e-4 * stages, "{levels} + {wide} != {stages}");+ // One stage alone, a Gaussian of 3 % of the width (sigma 29.3 px): a point in the middle of a black frame+ // (a unit of energy: one output pixel of 16 in a 4 x 4 block) glows with the stage's energy and variance.+ p.bloom.size_scale = 1.0;+ p.bloom.sizes = vec![30.0];+ p.bloom.tints = vec![1.0];+ let plan = BloomPlan::new(&p, w as u32, h as u32);+ let sigma = (BLOOM_SIGMA * 0.3 * w as f32) as f64;+ let mut level0 = vec![[0f32; 4]; w.div_ceil(4) * h.div_ceil(4)];+ level0[(h / 8) * w.div_ceil(4) + w / 8] = [1.0 / 16.0, 0.0, 0.0, 0.0];+ let py = Pyramid::new(level0, w, h, &plan);+ let (cx, cy) = (w as f64 / 2.0 + 2.0, h as f64 / 2.0 + 2.0);+ let (mut e, mut m2) = (0f64, 0f64);+ for y in 0..h {+ for x in 0..w {+ let v = py.at(x, y)[0] as f64;+ e += v;+ m2 += v * (x as f64 + 0.5 - cx).powi(2);+ }+ }+ let want = (p.bloom.intensity * BLOOM_GAIN) as f64;+ assert!((e / want - 1.0).abs() < 0.02, "energy {e} for {want}");+ assert!(((m2 / e).sqrt() / sigma - 1.0).abs() < 0.05, "sigma {} for {sigma}", (m2 / e).sqrt());+ }++ #[test]+ fn local_exposure_is_none_at_one_and_compresses_below() {+ let mut lx = crate::desc::LocalExposure::default();+ assert_eq!(local_exposure_factor(&lx, 1.0, 2.0, 3.0, 0.0), 1.0);+ lx.highlight_contrast = 0.5;+ lx.shadow_contrast = 0.5;+ // A region two stops over the pivot comes down a stop, one two stops under comes up a stop; detail stays.+ let f = local_exposure_factor(&lx, 2.3, 2.0, 2.0, 0.0);+ assert!((f - 0.5).abs() < 1e-5, "{f}");+ let f = local_exposure_factor(&lx, -2.0, -2.0, -2.0, 0.0);+ assert!((f - 2.0).abs() < 1e-5, "{f}");+ }++ #[test]+ fn the_chain_runs_and_grain_has_no_mean() {+ let mut p = preset();+ let (w, h) = (64usize, 36usize);+ let img = Image { w, h, px: vec![Vec3::splat(0.18); w * h] };+ let plain = finish(&img, 1.0, 1.0, &p);+ p.film_grain = 1.0;+ p.chromatic_aberration = 2.0;+ p.local_exposure.highlight_contrast = 0.8;+ p.local_exposure.shadow_contrast = 0.8;+ let grainy = finish(&img, 1.0, 1.0, &p);+ let mean = |v: &[u8]| v.chunks(4).map(|c| c[1] as f32).sum::<f32>() / (w * h) as f32;+ assert!((mean(&plain) - mean(&grainy)).abs() < 2.0, "{} {}", mean(&plain), mean(&grainy));+ assert!(plain != grainy);+ }}diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 4517a3b..8d2f57a 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -1372,6 +1372,19 @@ pub fn gpu_light_shown(l: &Light, m: Mat4, power: f32, shown: bool) -> Option<GpSome(gl)}+/// A spot light's cone for the kernel (`local_light`): the cosine of the outer cone's half angle `angle` (radians),+/// outside which there is no light, and 1 / (the inner cone's cosine - it): `lightAngleScale` of glTF 2.0+/// KHR_lights_punctual's reference attenuation (the difference no less than 0.001, as there: a cone without penumbra+/// has an edge that wide), the offset left to the kernel's subtraction.+/// `penumbra` (0..1) is the share of the angle over which the light fades: three.js's `SpotLight.penumbra` ("Percent+/// of the spotlight cone that is attenuated due to penumbra"), whose inner cone is `angle` x (1 - `penumbra`) (three.js+/// WebGLLights: `penumbraCos`), glTF's `innerConeAngle`.+pub fn spot_cone(angle: f32, penumbra: f32) -> (f32, f32) {+ let angle = angle.clamp(0.0, std::f32::consts::PI);+ let (cos_outer, cos_inner) = (angle.cos(), (angle * (1.0 - penumbra.clamp(0.0, 1.0))).cos());+ (cos_outer, 1.0 / (cos_inner - cos_outer).max(1e-3))+}+pub fn gpu_light(l: &Light, m: Mat4, power: f32) -> Option<GpuLight> {let pos = m.transform_point3(Vec3::ZERO);let dir = m.transform_vector3(Vec3::NEG_Z).normalize();@@ -1401,14 +1414,12 @@ pub fn gpu_light(l: &Light, m: Mat4, power: f32) -> Option<GpuLight> {}Light::Spot { color, intensity, radius, range, angle, penumbra, cast_shadow, volumetric_scattering, specular_scale } => {let intensity = intensity * power;- // UE: inner = outer * (1 - penumbra); falloff = saturate((cos - cosOuter) / (cosInner - cosOuter))^2- let cos_outer = angle.cos();- let cos_inner = (angle * (1.0 - penumbra)).cos();+ let (cos_outer, inv_width) = spot_cone(*angle, *penumbra);GpuLight {pos: [pos.x, pos.y, pos.z, 2.0],dir: [dir.x, dir.y, dir.z, *radius],color: [color[0] * intensity, color[1] * intensity, color[2] * intensity, *range],- ext: [cos_outer, 1.0 / (cos_inner - cos_outer).max(1e-4), 0.0, *cast_shadow as u32 as f32],+ ext: [cos_outer, inv_width, 0.0, *cast_shadow as u32 as f32],x: [*volumetric_scattering, *specular_scale, 0.0, 0.0],}}@@ -2830,6 +2841,40 @@ pub fn tri_attr(n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<CornerTangents>, ma}}+#[cfg(test)]+mod spot_cone_tests {+ use super::*;++ /// The kernel's falloff (pathtrace.wgsl `local_light`) at an angle from the spot's axis.+ fn falloff(angle: f32, penumbra: f32, at: f32) -> f32 {+ let (cos_outer, inv_width) = spot_cone(angle, penumbra);+ let t = ((at.cos() - cos_outer) * inv_width).clamp(0.0, 1.0);+ t * t+ }++ /// Nothing outside the cone, everything inside the inner cone (angle x (1 - penumbra)), and between them glTF+ /// KHR_lights_punctual's reference attenuation; a cone without penumbra is hard.+ #[test]+ fn the_cone_fades_over_the_penumbra() {+ let (angle, penumbra) = (52f32.to_radians(), 0.4);+ assert_eq!(falloff(angle, penumbra, angle + 1e-3), 0.0);+ assert_eq!(falloff(angle, penumbra, 1.2), 0.0);+ assert_eq!(falloff(angle, penumbra, angle * 0.6 - 1e-3), 1.0);+ assert_eq!(falloff(angle, penumbra, 0.0), 1.0);+ for at in [0.6f32, 0.7, 0.8, 0.9] {+ let (ci, co) = ((angle * 0.6).cos(), angle.cos());+ let scale = 1.0 / (ci - co).max(0.001);+ let want = (at.cos() * scale - co * scale).clamp(0.0, 1.0).powi(2);+ assert!((falloff(angle, penumbra, at) - want).abs() < 1e-5 && want > 0.0 && want < 1.0, "{at}: {want}");+ }+ assert_eq!(falloff(0.35, 0.0, 0.34), 1.0);+ assert_eq!(falloff(0.35, 0.0, 0.3501), 0.0);+ // The kernel reads the pair from the light's `ext.xy`.+ let l = gpu_light(&Light::Spot { color: [1.0; 3], intensity: 1.0, radius: 0.0, range: 0.0, angle, penumbra, cast_shadow: true, volumetric_scattering: 1.0, specular_scale: 1.0 }, Mat4::IDENTITY, 1.0).unwrap();+ assert_eq!((l.ext[0], l.ext[1]), spot_cone(angle, penumbra));+ }+}+#[cfg(test)]mod instance_tests {use super::*;diff --git a/renderer/src/sky.rs b/renderer/src/sky.rsindex 019f5c0..90a34a2 100644--- a/renderer/src/sky.rs+++ b/renderer/src/sky.rs@@ -1,248 +1,590 @@-//! Physical sky matching UE5's SkyAtmosphere (Hillaire 2020): Earth defaults from-//! SkyAtmosphereComponent.cpp, transmittance + multiple-scattering LUTs, radiance baked into an-//! equirectangular environment map (Y-up, upper hemisphere; lower hemisphere black like UE's SkyLight, with its-//! cubemap's fade at the horizon).+//! The sky: a physical atmosphere (the sun's light scattered by air, haze and ozone above a ground), baked into an+//! equirectangular environment map (Y-up; the lower hemisphere black, with a fade at the horizon); analytic domes for+//! night and overcast skies; a cloud layer from a mask.use glam::Vec3;use rayon::prelude::*;use std::f32::consts::PI;+// ------------------------------------------------------------------------------------------------ the atmosphere+//+// The medium is the Earth atmosphere of Bruneton & Neyret 2008 ("Precomputed Atmospheric Scattering", EGSR) in the+// RGB form of Bruneton's 2017 reimplementation and of Hillaire 2020 ("A Scalable and Production Ready Sky and+// Atmosphere Rendering Technique", EGSR), section 4 and Table 1: a spherical planet, air that scatters (Rayleigh),+// haze that scatters and absorbs (Mie), ozone that absorbs, a Lambertian ground. Lengths are km here.+//+// What is computed, and how (the numerical methods are this file's own):+// - `columns_exact`: the amount of each component along a ray to the top of the atmosphere, by Gauss-Legendre+// quadrature; `slant` extends it to rays that point down.+// - `Atmosphere::sun_transmittance`: the transmittance from the ground toward the sun, from those columns.+// - `Luts::build`: the same optical depth as a table for the sky's inner loop, and the light scattered more than+// once as tables over altitude and the sun's zenith angle (the isotropic approximation of Hillaire 2020 section+// 5.5, computed order by order).+// - `Luts::sky`: equation 11 of that paper integrated along the view ray, per texel of the bake, by Simpson's rule.+// The tests at the end of the file hold the model to the same medium path traced.++/// Radii of the ground and of the atmosphere's top, km (Hillaire 2020 section 4: 6360 km and 6460 km).+const R_GROUND: f64 = 6360.0;+const R_TOP: f64 = 6460.0;+/// Scale heights of the air's and the haze's density, km: d(h) = exp(-h / H) (Bruneton & Neyret 2008 section 2.1,+/// H_R = 8 km, H_M = 1.2 km; Hillaire 2020 section 4).+const H_RAYLEIGH: f64 = 8.0;+const H_MIE: f64 = 1.2;+/// Rayleigh scattering at sea level, per km, at 680 / 550 / 440 nm (Hillaire 2020 Table 1; Bruneton 2017 demo.cc:+/// 1.24062e-6 lambda^-4 per m, lambda in micrometres).+const RAYLEIGH_SCATTERING: [f64; 3] = [5.802e-3, 13.558e-3, 33.1e-3];+/// Mie scattering and absorption at sea level, per km (Bruneton 2017 demo.cc: extinction 5.328e-3 / 1200 m = 4.44e-6+/// per m, single-scattering albedo 0.9; the scattering is Hillaire 2020 Table 1's 3.996e-6 per m). The kernel's aerial+/// perspective (pathtrace.wgsl `aerial_tr`) has the same two numbers: they are one air.+const MIE_SCATTERING: f64 = 3.996e-3;+const MIE_ABSORPTION: f64 = 0.444e-3;+/// Ozone absorption at the layer's densest, per km (Hillaire 2020 Table 1; Bruneton 2017: 300 Dobson units), and the+/// layer: a tent of width 30 km centred at 25 km, d(h) = max(0, 1 - |h - 25| / 15) (Hillaire 2020 section 4).+const OZONE_ABSORPTION: [f64; 3] = [0.650e-3, 1.881e-3, 0.085e-3];+const OZONE_CENTRE: f64 = 25.0;+const OZONE_HALF_WIDTH: f64 = 15.0;++/// How far below the ground's surface a ray toward the sun may pass and still carry light, km (own design, see+/// `slant`): the ground is not a hard edge for the sun's light, so that a setting sun fades instead of switching off.+const SOFT_GROUND: f64 = 5.0;+const R_BASE: f64 = R_GROUND - SOFT_GROUND;+/// The soft ground's own optical depth for a ray that passes `depth` km under the surface: (depth / 2 km)^4 (own+/// design: under 6 % at the 1 km a ray 1 degree below the horizon reaches, opaque by 4 km, 2 degrees). Earth's own+/// air does most of the fading (its density continued downward, `densities`); this term keeps a thin or absent+/// atmosphere (`rayleighScale`, `mieScale` near 0) from lighting the ground from below the horizon.+fn ground_depth(p: f64) -> f64 {+ let d = ((R_GROUND - p) / 2.0).max(0.0);+ d * d * d * d+}++/// The sun's light on the ground, calibrated to the previous release (its measured table of the sun's colour by+/// elevation, a black box). That release's sun was dimmer and redder than this medium's transmittance, by an optical+/// depth that fits a thin veil of the sea-level air and haze high in the atmosphere: `SUN_VEIL_COLUMN` km of them+/// (straight up) in a layer at `SUN_VEIL_ALTITUDE` km, which the sun's ray crosses at a slant. With it the sun's+/// transmittance is within 1.1 % of that table from 5 degrees of elevation up, 1.5 % at 2 and 3 degrees, 5 % at 1.+/// Scenes were lit with that sun, so `Atmosphere::sun_transmittance` keeps it: the medium's transmittance times the+/// veil's. It is not part of the published medium, and the sky's own light (`Luts`) has none of it (that release's+/// sky fits the medium without it). A column of 0 gives the medium's own transmittance: +1.6 / +2.8 / +5.9 % (R / G+/// / B) with the sun at the zenith, +7.8 / +14 / +32 % at 10 degrees.+const SUN_VEIL_COLUMN: f64 = 1.65;+const SUN_VEIL_ALTITUDE: f64 = 55.0;+pub struct Atmosphere {- bottom: f32,- top: f32,- rayleigh_scattering: Vec3,- rayleigh_exp: f32,- mie_scattering: Vec3,- mie_extinction: Vec3,- mie_exp: f32,- mie_g: f32,- ozone_absorption: Vec3,- ground_albedo: Vec3,+ /// Scattering and extinction at sea level, per km, with the scene's scales in.+ rayleigh: [f64; 3],+ mie_scattering: f64,+ mie_extinction: f64,+ ozone: [f64; 3],+ mie_g: f64,+ ground_albedo: [f64; 3],+}++/// The densities of air, haze and ozone at altitude `h` km, relative to the constants above. Below the ground (h < 0;+/// only `slant`'s soft ground asks) the exponentials go on.+fn densities(h: f64) -> [f64; 3] {+ [(-h / H_RAYLEIGH).exp(), (-h / H_MIE).exp(), (1.0 - (h - OZONE_CENTRE).abs() / OZONE_HALF_WIDTH).max(0.0)]+}++/// e^x of four numbers at once in single precision (the result's relative error is that of the argument's last bit:+/// under 3e-7 for |x| < 2, 4e-6 at -87), for the inner loops: x = k ln 2 + r with k whole and |r| <= ln 2 / 2, e^r by+/// its Taylor polynomial of degree 7, 2^k by its bits (own code; no branches, so the compiler makes it one vector+/// operation). Arguments are clamped to [-87, 88]: below that the result is 1.6e-38, not 0.+#[inline(always)]+fn exp4(x: [f64; 4]) -> [f64; 4] {+ let mut out = [0.0f64; 4];+ for i in 0..4 {+ let v = (x[i] as f32).clamp(-87.0, 88.0);+ let k = (v * std::f32::consts::LOG2_E + 0.5).floor();+ // (ln 2 in two parts, its leading bits first: k times them has little or nothing to round.)+ let r = (v - k * 0.693_145_75) - k * 1.428_606_8e-6;+ let poly = 1.0 + r * (1.0 + r * (0.5 + r * (1.0 / 6.0 + r * (1.0 / 24.0 + r * (1.0 / 120.0 + r * (1.0 / 720.0 + r * (1.0 / 5040.0)))))));+ out[i] = (poly * f32::from_bits(((k as i32 + 127) as u32) << 23)) as f64;+ }+ out+}++/// The distance from radius `r` along a ray of zenith cosine `mu` to the sphere of radius `to` (the far crossing).+fn distance_out(r: f64, mu: f64, to: f64) -> f64 {+ -r * mu + (r * r * (mu * mu - 1.0) + to * to).max(0.0).sqrt()+}++/// The distance to the ground along a ray that points down, if it reaches it.+fn distance_to_ground(r: f64, mu: f64) -> Option<f64> {+ let disc = r * r * (mu * mu - 1.0) + R_GROUND * R_GROUND;+ (mu < 0.0 && disc >= 0.0).then(|| (-r * mu - disc.sqrt()).max(0.0))+}++/// Gauss-Legendre nodes and weights, 8 points on [-1, 1] (Abramowitz & Stegun 1964, Table 25.4; the positive half).+const GL8: [(f64, f64); 4] = [+ (0.183_434_642_495_649_8, 0.362_683_783_378_362),+ (0.525_532_409_916_329, 0.313_706_645_877_887_3),+ (0.796_666_477_413_626_7, 0.222_381_034_453_374_5),+ (0.960_289_856_497_536_2, 0.101_228_536_290_376_3),+];++/// The columns of air, haze and ozone (km at their reference densities) from radius `r` to the top of the atmosphere+/// along a ray that points up or level (`mu` >= 0): the integral of `densities`, by 8-point Gauss-Legendre quadrature+/// on 12 panels of u, the distance being d u^2 (the nodes crowd the start, where the ray is in the dense air).+fn columns_exact(r: f64, mu: f64) -> [f64; 3] {+ const PANELS: usize = 12;+ let d = distance_out(r, mu, R_TOP);+ let mut n = [0.0f64; 3];+ for p in 0..PANELS {+ let (centre, half) = ((p as f64 + 0.5) / PANELS as f64, 0.5 / PANELS as f64);+ for (x, w) in GL8 {+ for s in [-1.0, 1.0] {+ let u = centre + s * half * x;+ let t = d * u * u;+ let dens = densities((r * r + t * t + 2.0 * r * mu * t).sqrt() - R_GROUND);+ let k = w * half * 2.0 * d * u;+ for c in 0..3 {+ n[c] += k * dens[c];+ }+ }+ }+ }+ n+}++/// The columns from radius `r` to the top along any ray, and the soft ground's optical depth (`ground_depth`). A ray+/// that points down passes its lowest point, at radius p = r sqrt(1 - mu^2), and from there on it is the level ray+/// from p; before that point it is the mirror image of the ray that points up from `r`:+/// columns(r, mu) = 2 columns(p, 0) - columns(r, -mu).+/// Own design for the sun below a point's horizon: the ray is not cut by the ground's sphere. It goes through the+/// ground's first kilometres, where the air's density is continued downward and `ground_depth` is added, so the+/// sun's light falls smoothly to nothing within about two degrees below the horizon instead of at one angle (on the+/// real Earth refraction and the sun's half degree do the like: the sun's upper limb is in view until its centre is+/// 0.83 degrees below the geometric horizon). `None`: the ray is deeper than SOFT_GROUND, no light.+fn slant(r: f64, mu: f64) -> Option<([f64; 3], f64)> {+ if mu >= 0.0 {+ return Some((columns_exact(r, mu), 0.0));+ }+ let p = r * (1.0 - mu * mu).max(0.0).sqrt();+ if p <= R_BASE {+ return None;+ }+ let (level, mirror) = (columns_exact(p, 0.0), columns_exact(r, -mu));+ Some(([0, 1, 2].map(|c| (2.0 * level[c] - mirror[c]).max(0.0)), ground_depth(p)))}impl Atmosphere {+ /// Earth's atmosphere with its Rayleigh and Mie scattering scaled (1 = Earth's), the haze's anisotropy `mie_g`+ /// and the ground's albedo.pub fn earth(rayleigh_scale: f32, mie_scale: f32, mie_g: f32, ground_albedo: Vec3) -> Self {- let mie_s = Vec3::splat(0.003996 * mie_scale);+ let (rs, ms) = (rayleigh_scale.max(0.0) as f64, mie_scale.max(0.0) as f64);Atmosphere {- bottom: 6360.0,- top: 6420.0,- rayleigh_scattering: Vec3::new(0.005802, 0.013558, 0.033100) * rayleigh_scale,- rayleigh_exp: -1.0 / 8.0,- mie_scattering: mie_s,- mie_extinction: mie_s + Vec3::splat(0.000444),- mie_exp: -1.0 / 1.2,- mie_g,- ozone_absorption: Vec3::new(0.000650, 0.001881, 0.000085),- ground_albedo,+ rayleigh: RAYLEIGH_SCATTERING.map(|b| b * rs),+ mie_scattering: MIE_SCATTERING * ms,+ // (The absorption is not scaled: as the kernel's aerial perspective has it.)+ mie_extinction: MIE_SCATTERING * ms + MIE_ABSORPTION,+ ozone: OZONE_ABSORPTION,+ mie_g: (mie_g as f64).clamp(-0.99, 0.99),+ ground_albedo: [ground_albedo.x, ground_albedo.y, ground_albedo.z].map(|v| (v as f64).clamp(0.0, 1.0)),}}- fn medium(&self, h: f32) -> (Vec3, Vec3, Vec3) {- let dr = (self.rayleigh_exp * h).exp();- let dm = (self.mie_exp * h).exp();- let doz = (1.0 - (h - 25.0).abs() / 15.0).clamp(0.0, 1.0);- let sr = self.rayleigh_scattering * dr;- let sm = self.mie_scattering * dm;- let ext = sr + self.mie_extinction * dm + self.ozone_absorption * doz;- (sr, sm, ext)- }-- /// UE FAtmosphereSetup::GetTransmittanceAtGroundLevel: 15-step optical depth from 0.5 km altitude.- pub fn sun_transmittance_ue(&self, sun_dir_y_up: Vec3) -> Vec3 {- let elev = sun_dir_y_up.y.clamp(-1.0, 1.0).asin();- let pos = Vec3::new(0.0, 0.0, self.bottom + 0.5);- let dir = Vec3::new(elev.cos(), 0.0, elev.sin());- let tmax = ray_sphere_nearest(pos, dir, self.top);- let mut od = Vec3::ZERO;- if tmax > 0.0 {- let n = 15;- let step = tmax / n as f32;- for i in 0..n {- let p = pos + dir * (step * i as f32);- let h = p.length() - self.bottom;- let (sr, _, _) = self.medium(h);- let dm = (self.mie_exp * h).exp().max(0.0);- let doz = (1.0 - (h - 25.0).abs() / 15.0).clamp(0.0, 1.0);- od += step * (dm * self.mie_extinction + sr + doz * self.ozone_absorption);- }- }- Vec3::new((-od.x).exp(), (-od.y).exp(), (-od.z).exp())+ /// Extinction (RGB, per km) at densities of air, haze and ozone.+ #[inline(always)]+ fn extinction(&self, dens: [f64; 3]) -> [f64; 3] {+ [0, 1, 2].map(|c| self.rayleigh[c] * dens[0] + self.mie_extinction * dens[1] + self.ozone[c] * dens[2])}- /// Transmittance from point (r = |p|) along mu=cos(zenith) to the top of the atmosphere (0 if it hits ground).- fn transmittance_raw(&self, r: f32, mu: f32, steps: usize) -> Vec3 {- let pos = Vec3::new(0.0, 0.0, r);- let dir = Vec3::new((1.0 - mu * mu).max(0.0).sqrt(), 0.0, mu);- if ray_sphere_nearest(pos, dir, self.bottom) > 0.0 {- return Vec3::ZERO;+ /// Optical depth (RGB) from radius `r` to the top of the atmosphere along a ray of zenith cosine `mu` (`slant`);+ /// `OPAQUE` where the ground lets nothing through.+ fn optical_depth(&self, r: f64, mu: f64) -> [f64; 3] {+ match slant(r, mu) {+ Some((n, ground)) => self.extinction(n).map(|t| (t + ground).min(OPAQUE)),+ None => [OPAQUE; 3],}- let tmax = ray_sphere_nearest(pos, dir, self.top);- if tmax <= 0.0 {- return Vec3::ONE;+ }++ /// The medium's transmittance (RGB) from the ground toward a sun of zenith cosine `mu`, without the sun's veil.+ fn ground_transmittance(&self, mu: f64) -> [f64; 3] {+ self.optical_depth(R_GROUND, mu).map(|t| (-t).exp())+ }++ /// The share of the sun's light (RGB) that reaches the ground from the direction `sun_dir_y_up` (world, Y up):+ /// what a directional sun light of the scene is tinted by. The transmittance of the sky's own medium from sea+ /// level to the top of the atmosphere, smooth through the horizon (`slant`), times the calibration's veil+ /// (`SUN_VEIL_COLUMN`).+ pub fn sun_transmittance(&self, sun_dir_y_up: Vec3) -> Vec3 {+ let mu = (sun_dir_y_up.normalize_or_zero().y as f64).clamp(-1.0, 1.0);+ let medium = self.ground_transmittance(mu);+ // The veil's column along the ray: a thin layer at a radius R, crossed at the angle whose sine is+ // R_GROUND cos(elevation) / R (the same above and below the horizon).+ let level = R_GROUND / (R_GROUND + SUN_VEIL_ALTITUDE);+ let veil = SUN_VEIL_COLUMN / (1.0 - level * level * (1.0 - mu * mu)).sqrt();+ Vec3::from([0, 1, 2].map(|c| (medium[c] * (-veil * (self.rayleigh[c] + self.mie_extinction)).exp()) as f32))+ }++ /// The air's phase function (Rayleigh; Hillaire 2020 section 4), per steradian, for the cosine of the angle+ /// between the light's and the view's directions.+ fn phase_rayleigh(nu: f64) -> f64 {+ 3.0 / (16.0 * std::f64::consts::PI) * (1.0 + nu * nu)+ }++ /// The haze's phase function: Henyey & Greenstein 1941 ("Diffuse radiation in the galaxy", Astrophysical Journal+ /// 93) of anisotropy g, per steradian (Hillaire 2020 section 4 names it as the simpler alternative to its+ /// Cornette-Shanks form).+ fn phase_mie(&self, nu: f64) -> f64 {+ let g = self.mie_g;+ (1.0 - g * g) / (4.0 * std::f64::consts::PI * (1.0 + g * g - 2.0 * g * nu).max(1e-9).powf(1.5))+ }+}++/// The optical depth tables hold where no light gets through.+const OPAQUE: f64 = 80.0;++/// Where a point is in the tables over the sun's zenith cosine and altitude (`Table`), all in 0..1. Own choice of+/// coordinates (Hillaire 2020 section 5.5.2 has both linear):+/// - the altitude as its square root, denser near the ground, where the haze is;+/// - for the scattered light, the sun's zenith cosine as sign(mu) sqrt(|mu|), which puts half the entries within 14+/// degrees of the horizon, where the light turns from day to night;+/// - for the optical depth toward the sun, the same above the level direction; below it, by how far under the point+/// the sun's ray passes at its lowest (radius p), as sqrt((r - p) / (r - R_BASE)): it is that depth which decides+/// how much of the sun's light is left, at any altitude, down to the soft ground's end (Bruneton & Neyret 2008+/// section 4 make the like point for their tables: a direction is best taken by its ray's length to the boundary).+#[derive(Clone, Copy)]+struct At {+ sun: f64,+ scatter: f64,+ altitude: f64,+}++impl At {+ #[inline(always)]+ fn new(mu_sun: f64, r: f64) -> At {+ let root = mu_sun.abs().sqrt();+ let altitude = ((r - R_GROUND) * (1.0 / (R_TOP - R_GROUND))).clamp(0.0, 1.0).sqrt();+ if mu_sun >= 0.0 {+ return At { sun: 0.5 + 0.5 * root, scatter: 0.5 + 0.5 * root, altitude };}- let dt = tmax / steps as f32;- let mut od = Vec3::ZERO;- for i in 0..steps {- let p = pos + dir * (dt * (i as f32 + 0.5));- od += self.medium(p.length() - self.bottom).2 * dt;+ // r - p, p = r sqrt(1 - mu^2), without the difference of two near numbers.+ let under = r * mu_sun * mu_sun / (1.0 + (1.0 - mu_sun * mu_sun).max(0.0).sqrt());+ At { sun: 0.5 - 0.5 * (under / (r - R_BASE)).min(1.0).sqrt(), scatter: 0.5 - 0.5 * root, altitude }+ }+ /// On the ground.+ fn ground(mu_sun: f64) -> At {+ At::new(mu_sun, R_GROUND)+ }+ /// The sun's zenith cosine at a coordinate of the scattered light's tables, and of the sun's table at radius `r`.+ fn mu_of_scatter(x: f64, _r: f64) -> f64 {+ let s = 2.0 * x - 1.0;+ s * s.abs()+ }+ fn mu_of_sun(x: f64, r: f64) -> f64 {+ if x >= 0.5 {+ return (2.0 * x - 1.0).powi(2);}- Vec3::new((-od.x).exp(), (-od.y).exp(), (-od.z).exp())+ let p = r - (r - R_BASE) * (1.0 - 2.0 * x).powi(2);+ -(1.0 - (p / r).powi(2)).max(0.0).sqrt()}}-fn ray_sphere_nearest(o: Vec3, d: Vec3, r: f32) -> f32 {- let b = o.dot(d);- let c = o.dot(o) - r * r;- let disc = b * b - c;- if disc < 0.0 {- return -1.0;+/// An RGB table over the sun's zenith cosine (columns: one of `At`'s two coordinates) and altitude (rows; one row:+/// the ground), linear between entries.+struct Table {+ columns: usize,+ rows: usize,+ data: Vec<[f32; 3]>,+}++impl Table {+ /// `f` of the sun's zenith cosine (`mu_of` the column's coordinate) and the radius of each entry.+ fn fill(columns: usize, rows: usize, mu_of: fn(f64, f64) -> f64, f: impl Fn(f64, f64) -> [f64; 3] + Sync) -> Table {+ let data = (0..columns * rows)+ .into_par_iter()+ .map(|i| {+ let q = if rows > 1 { (i / columns) as f64 / (rows - 1) as f64 } else { 0.0 };+ let r = R_GROUND + q * q * (R_TOP - R_GROUND);+ f(mu_of((i % columns) as f64 / (columns - 1) as f64, r), r).map(|v| v as f32)+ })+ .collect();+ Table { columns, rows, data }}- let s = disc.sqrt();- let (t0, t1) = (-b - s, -b + s);- if t0 < 0.0 && t1 < 0.0 {- -1.0- } else if t0 < 0.0 {- t1.max(0.0)- } else {- t0.max(0.0)++ #[inline(always)]+ fn at(&self, column: f64, altitude: f64) -> [f64; 3] {+ let fu = column * (self.columns - 1) as f64;+ let iu = (fu as usize).min(self.columns - 2);+ let wu = (fu - iu as f64) as f32;+ let row = |v: usize| {+ let (p, q) = (self.data[v * self.columns + iu], self.data[v * self.columns + iu + 1]);+ [0, 1, 2].map(|c| p[c] + (q[c] - p[c]) * wu)+ };+ if self.rows == 1 {+ return row(0).map(|v| v as f64);+ }+ let fv = altitude * (self.rows - 1) as f64;+ let iv = (fv as usize).min(self.rows - 2);+ let (lo, hi, wv) = (row(iv), row(iv + 1), (fv - iv as f64) as f32);+ [0, 1, 2].map(|c| (lo[c] + (hi[c] - lo[c]) * wv) as f64)}}-fn rayleigh_phase(c: f32) -> f32 {- 3.0 / (16.0 * PI) * (1.0 + c * c)+/// A ray in the atmosphere: its start's radius, the zenith cosines of its direction and of the sun's there, the cosine+/// between the two directions, its length.+#[derive(Clone, Copy)]+struct Ray {+ r: f64,+ mu: f64,+ mu_sun: f64,+ nu: f64,+ length: f64,}-fn hg_phase(g: f32, c: f32) -> f32 {- let n = 1.0 - g * g;- let d = 1.0 + g * g - 2.0 * g * c;- n / (4.0 * PI * d * d.sqrt())+impl Ray {+ /// From radius `r` to the ground or to the top of the atmosphere; whether it ends on the ground.+ fn new(r: f64, mu: f64, mu_sun: f64, nu: f64) -> (Ray, bool) {+ let ground = distance_to_ground(r, mu);+ (Ray { r, mu, mu_sun, nu, length: ground.unwrap_or_else(|| distance_out(r, mu, R_TOP)) }, ground.is_some())+ }+ /// The sun's zenith cosine where the ray ends on the ground.+ fn mu_sun_at_ground(&self) -> f64 {+ ((self.r * self.mu_sun + self.length * self.nu) / R_GROUND).clamp(-1.0, 1.0)+ }}-struct Luts {- trans: Vec<Vec3>, // [mu][r]- ms: Vec<Vec3>, // [r][mu_s]+/// How finely the tables of scattered light are computed (`Luts::build`).+#[derive(Clone, Copy)]+struct Quality {+ /// Scattering orders computed one by one, from the second; the last stands for all after it.+ orders: usize,+ /// Azimuths of the directions gathered from, over the half turn (x 16 zenith angles).+ azimuths: usize,+ /// Intervals of Simpson's rule along a gathering ray, and along a view ray of the sky (even numbers).+ steps: usize,+ view_steps: usize,}-const T_MU: usize = 128;-const T_R: usize = 32;-const MS_N: usize = 32;+/// Against several times each (the test `quality_is_enough`): the sky within 1.5 % by day (the most at the horizon) and+/// within 8 % in the last of twilight, the sun 6 degrees down.+const QUALITY: Quality = Quality { orders: 3, azimuths: 2, steps: 12, view_steps: 16 };++/// The sizes of the tables: of the optical depth toward the sun (it turns from clear to opaque within a few degrees+/// at the horizon; an odd number of columns, so that one is the level direction, where its two coordinates meet), and+/// of the scattered light (broad).+const SUN_TABLE: (usize, usize) = (257, 128);+const SCATTER_TABLE: (usize, usize) = (64, 32);+/// The sun's zenith cosine under which the scattered light's tables are left at zero: 17 degrees below the horizon+/// (the sun's own light stops 10 degrees below it for a point at the top of the atmosphere; the scattered light of+/// the lit air beyond reaches a little further).+const NIGHT: f64 = -0.3;++struct Luts {+ /// The optical depth from a point to the top of the atmosphere toward the sun (`Atmosphere::optical_depth`).+ sun: Table,+ /// The light scattered twice or more, as a source: the radiance each point of the air scatters on per unit of+ /// its scattering coefficient, per unit of the sun's illuminance (sr^-1). The Psi_ms of Hillaire 2020 equation+ /// 10 (its use: equation 11); how it is computed here: `Luts::build`.+ scattered: Table,+ /// The radiance of the ground from the light that reaches it scattered (per unit of the sun's illuminance).+ ground: Table,+ view_steps: usize,+}impl Luts {fn build(a: &Atmosphere) -> Luts {- let trans: Vec<Vec3> = (0..T_MU * T_R)- .into_par_iter()- .map(|i| {- let (mi, ri) = (i / T_R, i % T_R);- let r = a.bottom + (a.top - a.bottom) * (ri as f32 / (T_R - 1) as f32);- let mu = -1.0 + 2.0 * (mi as f32 / (T_MU - 1) as f32);- a.transmittance_raw(r, mu, 64)- })- .collect();- let mut l = Luts { trans, ms: vec![Vec3::ZERO; MS_N * MS_N] };- // Multiple scattering transfer (Hillaire 2020, Sec 5.5): psi = L2 / (1 - fms), isotropic phase.- let dirs = sphere_dirs(64);- let ms: Vec<Vec3> = (0..MS_N * MS_N)- .into_par_iter()- .map(|i| {- let (ri, si) = (i / MS_N, i % MS_N);- let r = a.bottom + (a.top - a.bottom) * ((ri as f32 + 0.5) / MS_N as f32);- let mu_s = -1.0 + 2.0 * ((si as f32 + 0.5) / MS_N as f32);- let sun = Vec3::new((1.0 - mu_s * mu_s).max(0.0).sqrt(), 0.0, mu_s);- let pos = Vec3::new(0.0, 0.0, r);- let (mut l2, mut fms) = (Vec3::ZERO, Vec3::ZERO);- for d in &dirs {- let (lum, f) = l.integrate(a, pos, *d, sun, 20, true, None, true);- l2 += lum;- fms += f;+ Luts::build_at(a, QUALITY)+ }++ /// The light of scattering orders two and up (`scattered`, `ground`).+ ///+ /// Hillaire 2020 section 5.5 takes the scattering of orders two and up as isotropic, which makes its source a+ /// function of altitude and the sun's zenith angle alone, and so do the tables here. That paper computes order+ /// two (equations 5 and 6: the light scattered once or sent back by the ground toward a point, averaged over+ /// all directions) and closes the series with one factor per point (equations 7-10), which takes the light around+ /// a point as uniform. Here the next orders are computed like the second, each from the table of the one before+ /// (the order-by-order scheme of Bruneton & Neyret 2008 section 4, Algorithm 4.1, on these small tables), with the ground lit by+ /// each order as well; only what is left after `Quality::orders` is closed as a geometric series, by the ratio of+ /// the last two orders. Against the path-traced medium (the test `against_path_tracing`) the sky holds within 3 %+ /// down to a sun below the horizon, where the one-factor series reads the further orders a third low: there the+ /// light comes down from the air above, which the sun still reaches.+ fn build_at(a: &Atmosphere, quality: Quality) -> Luts {+ let sun = Table::fill(SUN_TABLE.0, SUN_TABLE.1, At::mu_of_sun, |mu_sun, r| a.optical_depth(r, mu_sun));+ let empty = |rows: usize| Table { columns: SCATTER_TABLE.0, rows, data: vec![[0.0; 3]; rows * SCATTER_TABLE.0] };+ let mut luts = Luts { sun, scattered: empty(SCATTER_TABLE.1), ground: empty(1), view_steps: quality.view_steps };+ // Order one as a source: the sun's light at a point, scattered isotropically; the ground lit by the sun.+ let isotropic = 1.0 / (4.0 * std::f64::consts::PI);+ let first = |at: At| luts.sun_transmittance(at).map(|t| t * isotropic);+ let first_ground = |mu_sun: f64| luts.sunlit_ground(a, mu_sun);+ let (mut order, mut order_ground) = (luts.gather(a, quality, first, first_ground), luts.gather_ground(a, quality, first));+ let (mut sum, mut sum_ground) = (order.data.clone(), order_ground.data.clone());+ for n in 3..=quality.orders.max(2) + 1 {+ let source = |at: At| order.at(at.scatter, at.altitude);+ let (next, next_ground) = (luts.gather(a, quality, source, |mu_sun| order_ground.at(At::ground(mu_sun).scatter, 0.0)), luts.gather_ground(a, quality, source));+ // The last one computed stands for all the orders after it: its share of the one before, as a series.+ let last = n == quality.orders.max(2) + 1;+ let add = |sum: &mut Vec<[f32; 3]>, before: &[[f32; 3]], next: &[[f32; 3]]| {+ for (i, s) in sum.iter_mut().enumerate() {+ for c in 0..3 {+ let ratio = if before[i][c] > 0.0 { (next[i][c] / before[i][c]).clamp(0.0, 0.9) } else { 0.0 };+ s[c] += if last { next[i][c] / (1.0 - ratio) } else { next[i][c] };+ }}- let n = dirs.len() as f32;- l2 /= n;- fms /= n;- l2 / (Vec3::ONE - fms)- })- .collect();- l.ms = ms;- l+ };+ add(&mut sum, &order.data, &next.data);+ add(&mut sum_ground, &order_ground.data, &next_ground.data);+ (order, order_ground) = (next, next_ground);+ }+ luts.scattered.data = sum;+ luts.ground.data = sum_ground;+ luts}- fn trans(&self, a: &Atmosphere, r: f32, mu: f32) -> Vec3 {- let x = ((mu + 1.0) * 0.5 * (T_MU - 1) as f32).clamp(0.0, (T_MU - 1) as f32);- let y = ((r - a.bottom) / (a.top - a.bottom) * (T_R - 1) as f32).clamp(0.0, (T_R - 1) as f32);- bilerp(&self.trans, T_MU, T_R, x, y, |mi, ri| mi * T_R + ri)+ /// The transmittance from a point to the top of the atmosphere toward the sun.+ #[inline(always)]+ fn sun_transmittance(&self, at: At) -> [f64; 3] {+ let t = self.sun.at(at.sun, at.altitude);+ let e = exp4([-t[0], -t[1], -t[2], 0.0]);+ // (`exp4` has no zero: the opaque is.)+ [0, 1, 2].map(|c| if t[c] < OPAQUE - 1.0 { e[c] } else { 0.0 })}- fn ms(&self, a: &Atmosphere, r: f32, mu_s: f32) -> Vec3 {- let x = ((mu_s + 1.0) * 0.5 * MS_N as f32 - 0.5).clamp(0.0, (MS_N - 1) as f32);- let y = ((r - a.bottom) / (a.top - a.bottom) * MS_N as f32 - 0.5).clamp(0.0, (MS_N - 1) as f32);- bilerp(&self.ms, MS_N, MS_N, x, y, |si, ri| ri * MS_N + si)+ /// The radiance of the ground lit by the sun through the atmosphere, per unit of the sun's illuminance: a+ /// Lambertian surface (the L_o of Hillaire 2020 equation 6).+ fn sunlit_ground(&self, a: &Atmosphere, mu_sun: f64) -> [f64; 3] {+ let t = self.sun_transmittance(At::ground(mu_sun));+ [0, 1, 2].map(|c| a.ground_albedo[c] / std::f64::consts::PI * mu_sun.max(0.0) * t[c])}- /// Raymarch in-scattering. Returns (luminance for unit sun illuminance, multi-scatter "as 1" term).- #[allow(clippy::too_many_arguments)]- fn integrate(&self, a: &Atmosphere, pos: Vec3, dir: Vec3, sun: Vec3, steps: usize, ground: bool, ms_lut: Option<()>, isotropic: bool) -> (Vec3, Vec3) {- let t_ground = ray_sphere_nearest(pos, dir, a.bottom);- let t_top = ray_sphere_nearest(pos, dir, a.top);- let tmax = if t_ground > 0.0 { t_ground } else { t_top };- if tmax <= 0.0 {- return (Vec3::ZERO, Vec3::ZERO);- }- let cos = dir.dot(sun);- let (pr, pm) = if isotropic { (1.0 / (4.0 * PI), 1.0 / (4.0 * PI)) } else { (rayleigh_phase(cos), hg_phase(a.mie_g, cos)) };- let mut lum = Vec3::ZERO;- let mut fms = Vec3::ZERO;- let mut thr = Vec3::ONE;- let mut t = 0.0f32;- for i in 0..steps {- // Slightly non-linear distribution concentrates samples near the viewer like UE.- let t1 = tmax * ((i as f32 + 1.0) / steps as f32).powf(1.5);- let dt = t1 - t;- let p = pos + dir * (t + 0.3 * dt);- t = t1;- let r = p.length();- let up = p / r;- let mu_s = sun.dot(up);- let (sr, sm, ext) = a.medium(r - a.bottom);- let tsun = self.trans(a, r, mu_s);- let earth_shadow = if ray_sphere_nearest(p, sun, a.bottom) > 0.0 { 0.0 } else { 1.0 };- let ms = if ms_lut.is_some() { self.ms(a, r, mu_s) } else { Vec3::ZERO };- let s = earth_shadow * tsun * (sr * pr + sm * pm) + ms * (sr + sm);- let st = Vec3::new((-ext.x * dt).exp(), (-ext.y * dt).exp(), (-ext.z * dt).exp());- let e = ext.max(Vec3::splat(1e-9));- lum += thr * (s - s * st) / e;- fms += thr * ((sr + sm) - (sr + sm) * st) / e;- thr *= st;- }- if ground && t_ground > 0.0 {- let p = pos + dir * t_ground;- let up = p.normalize();- let mu_s = sun.dot(up);- let tsun = self.trans(a, p.length(), mu_s);- lum += thr * tsun * mu_s.max(0.0) * a.ground_albedo / PI;- }- (lum, fms)+ /// Nodes on the sphere of directions about the zenith at radius `r`, by the sun's side (the other half mirrors+ /// it), with weights that sum to 1 over the sphere: 8-point Gauss-Legendre in the zenith cosine on each side of+ /// the horizon (below it a ray ends on the ground: the radiance jumps there) x midpoints in azimuth. `up`: the+ /// part above the level direction only (for the ground: weights that sum to 1 over the hemisphere).+ fn directions(r: f64, up: bool, azimuths: usize) -> impl Iterator<Item = (f64, f64, f64)> {+ let horizon = -(1.0 - (R_GROUND / r).powi(2)).max(0.0).sqrt();+ let panels = if up { [(0.0, 1.0), (0.0, 0.0)] } else { [(-1.0, horizon), (horizon, 1.0)] };+ let whole = if up { 1.0 } else { 2.0 };+ panels.into_iter().filter(|(lo, hi)| hi > lo).flat_map(move |(lo, hi)| {+ let (centre, half) = (0.5 * (lo + hi), 0.5 * (hi - lo));+ GL8.into_iter().flat_map(move |(x, w)| [-1.0, 1.0].into_iter().flat_map(move |sign| (0..azimuths).map(move |k| (centre + sign * half * x, (k as f64 + 0.5) / azimuths as f64 * std::f64::consts::PI, w * half / whole / azimuths as f64))))+ })}-}-fn bilerp(v: &[Vec3], nx: usize, ny: usize, x: f32, y: f32, idx: impl Fn(usize, usize) -> usize) -> Vec3 {- let (x0, y0) = ((x.floor() as usize).min(nx - 1), (y.floor() as usize).min(ny - 1));- let (x1, y1) = ((x0 + 1).min(nx - 1), (y0 + 1).min(ny - 1));- let (fx, fy) = (x - x0 as f32, y - y0 as f32);- let a = v[idx(x0, y0)].lerp(v[idx(x1, y0)], fx);- let b = v[idx(x0, y1)].lerp(v[idx(x1, y1)], fx);- a.lerp(b, fy)-}+ /// The next order's source from this one's (`source`: the radiance a point scatters on per unit of its scattering+ /// coefficient; `ground`: the ground's radiance, by the sun's zenith cosine): at every entry of the table, the+ /// radiance that arrives from all directions, averaged (the isotropic phase function).+ fn gather(&self, a: &Atmosphere, quality: Quality, source: impl Fn(At) -> [f64; 3] + Sync, ground: impl Fn(f64) -> [f64; 3] + Sync) -> Table {+ Table::fill(SCATTER_TABLE.0, SCATTER_TABLE.1, At::mu_of_scatter, |mu_sun, r| {+ if mu_sun < NIGHT {+ return [0.0; 3];+ }+ let r = r.clamp(R_GROUND + 1e-3, R_TOP - 1e-3);+ let sin_sun = (1.0 - mu_sun * mu_sun).max(0.0).sqrt();+ let mut sum = [0.0f64; 3];+ for (mu, phi, weight) in Self::directions(r, false, quality.azimuths) {+ let nu = (1.0 - mu * mu).max(0.0).sqrt() * phi.cos() * sin_sun + mu * mu_sun;+ let (ray, lands) = Ray::new(r, mu, mu_sun, nu);+ let (l, through) = Self::march(a, ray, quality.steps, |at, air, haze| {+ let s = source(at);+ [0, 1, 2].map(|c| (a.rayleigh[c] * air + a.mie_scattering * haze) * s[c])+ });+ let below = if lands { ground(ray.mu_sun_at_ground()) } else { [0.0; 3] };+ for c in 0..3 {+ sum[c] += weight * (l[c] + through[c] * below[c]);+ }+ }+ sum+ })+ }-fn sphere_dirs(n: usize) -> Vec<Vec3> {- // Fibonacci sphere.- let ga = PI * (3.0 - 5f32.sqrt());- (0..n)- .map(|i| {- let z = 1.0 - 2.0 * (i as f32 + 0.5) / n as f32;- let r = (1.0 - z * z).sqrt();- let phi = ga * i as f32;- Vec3::new(r * phi.cos(), r * phi.sin(), z)+ /// The ground's radiance from the light of `source`: its albedo / pi times the irradiance from the hemisphere.+ fn gather_ground(&self, a: &Atmosphere, quality: Quality, source: impl Fn(At) -> [f64; 3] + Sync) -> Table {+ Table::fill(SCATTER_TABLE.0, 1, At::mu_of_scatter, |mu_sun, _| {+ if mu_sun < NIGHT {+ return [0.0; 3];+ }+ let sin_sun = (1.0 - mu_sun * mu_sun).max(0.0).sqrt();+ let mut sum = [0.0f64; 3];+ for (mu, phi, weight) in Self::directions(R_GROUND, true, quality.azimuths) {+ let nu = (1.0 - mu * mu).max(0.0).sqrt() * phi.cos() * sin_sun + mu * mu_sun;+ let (ray, _) = Ray::new(R_GROUND + 1e-3, mu, mu_sun, nu);+ let (l, _) = Self::march(a, ray, quality.steps, |at, air, haze| {+ let s = source(at);+ [0, 1, 2].map(|c| (a.rayleigh[c] * air + a.mie_scattering * haze) * s[c])+ });+ // (The weights are of a mean over the hemisphere, 2 pi sr: the irradiance is 2 pi x mean(L mu).)+ for c in 0..3 {+ sum[c] += weight * 2.0 * mu * l[c] * a.ground_albedo[c];+ }+ }+ sum})- .collect()+ }++ /// The radiance that arrives at the start of `ray` from the air along it, and the ray's transmittance: the+ /// integral of the view's transmittance times `emitted` (the radiance the air sends along the ray per km, given+ /// where a point is in the tables and the air's and the haze's densities there; Hillaire 2020 equations 1-3 and+ /// 11), by Simpson's rule on `steps` intervals of u, the distance being length u^2: the nodes crowd the ray's+ /// start, where a view ray from the ground is in the dense air and what it gathers is least dimmed. The view's+ /// optical depth at the nodes is the running Simpson integral of the extinction (at the odd nodes, the+ /// three-point rule for half a panel: h (5 f0 + 8 f1 - f2) / 12).+ #[inline(always)]+ fn march(a: &Atmosphere, ray: Ray, steps: usize, emitted: impl Fn(At, f64, f64) -> [f64; 3]) -> ([f64; 3], [f64; 3]) {+ let steps = steps.max(2) & !1;+ let h = 1.0 / steps as f64;+ // A node: where it is in the tables, the air's and the haze's densities, the extinction's integrand (per unit+ // u), the distance's derivative (dt / du).+ let node = |i: usize| {+ let u = i as f64 * h;+ let t = ray.length * u * u;+ let r = (ray.r * ray.r + t * t + 2.0 * ray.r * ray.mu * t).sqrt();+ let altitude = (r - R_GROUND).max(0.0);+ let e = exp4([-altitude * (1.0 / H_RAYLEIGH), -altitude * (1.0 / H_MIE), 0.0, 0.0]);+ let ozone = (1.0 - (altitude - OZONE_CENTRE).abs() * (1.0 / OZONE_HALF_WIDTH)).max(0.0);+ let jacobian = 2.0 * ray.length * u;+ (At::new(((ray.r * ray.mu_sun + t * ray.nu) / r).clamp(-1.0, 1.0), r), e[0], e[1], a.extinction([e[0], e[1], ozone]).map(|x| x * jacobian), jacobian)+ };+ let (mut out, mut depth) = ([0.0f64; 3], [0.0f64; 3]);+ let mut add = |n: &(At, f64, f64, [f64; 3], f64), tau: [f64; 3], simpson: f64| {+ let (e, view) = (emitted(n.0, n.1, n.2), exp4([-tau[0], -tau[1], -tau[2], 0.0]));+ for c in 0..3 {+ out[c] += simpson * h / 3.0 * n.4 * view[c] * e[c];+ }+ };+ // (The first node has no length: dt / du = 0 there.)+ let mut n0 = node(0);+ for k in (0..steps).step_by(2) {+ let (n1, n2) = (node(k + 1), node(k + 2));+ let middle = [0, 1, 2].map(|c| depth[c] + h / 12.0 * (5.0 * n0.3[c] + 8.0 * n1.3[c] - n2.3[c]));+ depth = [0, 1, 2].map(|c| depth[c] + h / 3.0 * (n0.3[c] + 4.0 * n1.3[c] + n2.3[c]));+ add(&n1, middle, 4.0);+ add(&n2, depth, if k + 2 == steps { 1.0 } else { 2.0 });+ n0 = n2;+ }+ let through = exp4([-depth[0], -depth[1], -depth[2], 0.0]);+ (out, [through[0], through[1], through[2]])+ }++ /// The sky's radiance per unit of the sun's illuminance above the atmosphere (sr^-1, RGB), seen from+ /// `altitude_km` above the ground in direction `dir`, the sun in direction `sun` (both unit, planet frame: Z up);+ /// without the sun's disk, with multiple scattering and the ground's bounce.+ fn sky(&self, a: &Atmosphere, altitude_km: f32, dir: Vec3, sun: Vec3) -> Vec3 {+ let r = (R_GROUND + altitude_km.max(0.0) as f64).min(R_TOP - 1e-3);+ let (mu, mu_sun) = ((dir.z as f64).clamp(-1.0, 1.0), (sun.z as f64).clamp(-1.0, 1.0));+ let nu = (dir.dot(sun) as f64).clamp(-1.0, 1.0);+ let (ray, lands) = Ray::new(r, mu, mu_sun, nu);+ let (by_air, by_haze) = (Atmosphere::phase_rayleigh(nu), a.phase_mie(nu) * a.mie_scattering);+ // Equation 11 of Hillaire 2020: at each point the sun's light scattered once toward the viewer, by the air's+ // and the haze's phase functions, and the light of the further orders.+ let (l, through) = Self::march(a, ray, self.view_steps, |at, air, haze| {+ let (sun, further) = (self.sun_transmittance(at), self.scattered.at(at.scatter, at.altitude));+ [0, 1, 2].map(|c| {+ let air = a.rayleigh[c] * air;+ (air * by_air + haze * by_haze) * sun[c] + (air + haze * a.mie_scattering) * further[c]+ })+ });+ // A ray that ends on the ground sees it lit by the sun and by the sky.+ let below = if lands {+ let mu_sun = ray.mu_sun_at_ground();+ let (direct, scattered) = (self.sunlit_ground(a, mu_sun), self.ground.at(At::ground(mu_sun).scatter, 0.0));+ [0, 1, 2].map(|c| direct[c] + scattered[c])+ } else {+ [0.0; 3]+ };+ Vec3::from([0, 1, 2].map(|c| (l[c] + through[c] * below[c]) as f32))+ }}pub struct SkyBake {@@ -254,8 +596,9 @@ pub struct SkyBake {pub sun_illuminance: Vec3,}-/// The sky's size when its sun moves (`desc::Sky::Atmosphere::dynamic`): a bake takes ~10 ms of all cores here-/// against ~70 ms at the static 1024 x 512, so the live view can re-bake it on a worker thread several times a second.+/// The sky's size when its sun moves (`desc::Sky::Atmosphere::dynamic`): a bake takes ~1.5 ms of all cores here (~8 ms+/// of the live view's three) against ~20 ms at the static 1024 x 512, so the live view can re-bake it on a worker+/// thread many times a second./// The sun's disk is not in the bake (the kernel draws directional lights' disks), so the low size only softens the/// sky's own gradients, which are broad.pub const DYNAMIC_SKY: (u32, u32) = (256, 128);@@ -320,7 +663,7 @@ pub fn bake_atmosphere_tables(a: &Atmosphere, t: &SkyTables, sun_dir: Vec3, sun_/// The sun's illuminance at the ground (lux, RGB) for a sun of `sun_lux` above the atmosphere under a cloud `cover`,/// as the bake gives it: what a directional sun light carries when it moves without a new bake.pub fn sun_illuminance(a: &Atmosphere, sun_dir: Vec3, sun_lux: Vec3, cover: f32) -> Vec3 {- sun_lux * a.sun_transmittance_ue(sun_dir) * cloud_transmittance(cover)+ sun_lux * a.sun_transmittance(sun_dir) * cloud_transmittance(cover)}/// The sun's direct light through a cloud deck of `cover` (0..1): the share of time it is not behind a cloud, as a mean@@ -351,7 +694,7 @@ fn bake_atmosphere_with(a: &Atmosphere, luts: &Luts, sun_dir: Vec3, sun_lux: Vec// Planet frame: Z up. Map Y-up world -> planet frame (x, z, y).let to_planet = |d: Vec3| Vec3::new(d.x, d.z, d.y);let sun_p = to_planet(sun_dir).normalize();- let pos = Vec3::new(0.0, 0.0, a.bottom + (altitude_m / 1000.0).max(0.005));+ let altitude_km = (altitude_m / 1000.0).max(0.005);let texels: Vec<[f32; 4]> = (0..(width * height) as usize).into_par_iter().map(|i| {@@ -367,7 +710,7 @@ fn bake_atmosphere_with(a: &Atmosphere, luts: &Luts, sun_dir: Vec3, sun_lux: Vecreturn [0.0, 0.0, 0.0, 0.0];}let (dir, k) = if r < 0.5 { (Vec3::new(d.x, side / SKY_LIGHT_CUBE, d.z).normalize(), r + 0.5) } else { (d, 1.0) };- let (l, _) = luts.integrate(a, pos, to_planet(dir), sun_p, 40, false, Some(()), false);+ let l = luts.sky(a, altitude_km, to_planet(dir), sun_p);let l = (l * sun_lux + glow.at(dir.y.clamp(-1.0, 1.0).asin())) * k;// (w: the horizon fade's factor until the overcast blend below; 1 in the bake.)[l.x, l.y, l.z, k]@@ -578,3 +921,567 @@ mod overcast_tests {assert!((lum(half.texels[k]) - 0.5 * (lum(clear.texels[k]) + lum(oc.texels[k]))).abs() < 1e-3 * lum(clear.texels[k]));}}++#[cfg(test)]+mod atmosphere_tests {+ use super::*;++ fn earth() -> Atmosphere {+ Atmosphere::earth(1.0, 1.0, 0.8, Vec3::splat(0.401978))+ }+ /// Toward a sun at an elevation (degrees) in the world's frame (Y up), and in the planet's (Z up).+ fn sun_at(elevation_deg: f32) -> Vec3 {+ let e = elevation_deg.to_radians();+ Vec3::new(e.cos(), e.sin(), 0.0)+ }+ fn planet(elevation_deg: f32, azimuth_deg: f32) -> Vec3 {+ let (e, a) = (elevation_deg.to_radians(), azimuth_deg.to_radians());+ Vec3::new(e.cos() * a.cos(), e.cos() * a.sin(), e.sin())+ }+ fn luminance(v: Vec3) -> f32 {+ 0.2126 * v.x + 0.7152 * v.y + 0.0722 * v.z+ }++ #[test]+ fn fast_exponential() {+ let mut worst = (0.0f64, 0.0f64);+ for i in -8690..=200 {+ let x = i as f64 * 0.01;+ let e = exp4([x, x - 0.003, 0.0, -1e-9]);+ let error = (e[0] / x.exp() - 1.0).abs().max((e[1] / (x - 0.003).exp() - 1.0).abs());+ worst = (worst.0.max(error), if x.abs() < 2.0 { worst.1.max(error) } else { worst.1 });+ assert!(e[2] == 1.0 && (e[3] - 1.0).abs() < 1e-7);+ }+ // (Single precision in the argument: its last bit is 4e-6 of the result at -87.)+ assert!(worst.0 < 5e-6 && worst.1 < 3e-7, "{worst:?}");+ assert!(exp4([-1000.0, 0.0, 0.0, 0.0])[0] < 2e-38);+ }++ /// The quadrature of the columns against what they are in closed form (straight up: the air's and the haze's+ /// H (1 - exp(-100 km / H)), the ozone tent's area) and against a fine midpoint sum on slanted rays.+ #[test]+ fn columns_are_integrated_exactly() {+ let up = columns_exact(R_GROUND, 1.0);+ assert!((up[0] - 8.0 * (1.0 - (-100.0f64 / 8.0).exp())).abs() < 1e-6, "{up:?}");+ // (The ozone tent's corners are not at panel ends: 0.2 %.)+ assert!((up[1] - 1.2).abs() < 1e-6 && (up[2] - 15.0).abs() < 0.03, "{up:?}");+ for (h, mu) in [(0.0, 0.0), (0.0, 0.02), (0.0, 0.3), (3.0, 0.0), (20.0, 0.05), (60.0, 0.0), (-3.0, 0.0)] {+ let r = R_GROUND + h;+ let (d, n) = (distance_out(r, mu, R_TOP), 400_000);+ let mut sum = [0.0f64; 3];+ for i in 0..n {+ let t = (i as f64 + 0.5) / n as f64 * d;+ let dens = densities((r * r + t * t + 2.0 * r * mu * t).sqrt() - R_GROUND);+ for c in 0..3 {+ sum[c] += dens[c] * d / n as f64;+ }+ }+ let fast = columns_exact(r, mu);+ for c in 0..3 {+ assert!((fast[c] - sum[c]).abs() < if c == 2 { 2e-3 } else { 2e-4 } * sum[c].max(1.0), "{h} {mu}: {fast:?} {sum:?}");+ }+ }+ }++ /// The table of the optical depth toward the sun against the quadrature it tabulates, as transmittance: every+ /// altitude and direction, the sun below the horizon included.+ #[test]+ fn sun_table_matches_the_quadrature() {+ let a = earth();+ let luts = Luts::build(&a);+ let mut worst = (0.0f64, 0.0, 0.0, 0);+ for i in 0..150 {+ let r = R_GROUND + 100.0 * (i as f64 / 150.0).powi(3);+ for k in 0..=500 {+ let mu = -0.25 + 1.25 * (k as f64 / 500.0).powi(2);+ let (exact, t) = (a.optical_depth(r, mu).map(|t| (-t).exp()), luts.sun_transmittance(At::new(mu, r)));+ for c in 0..3 {+ if (exact[c] - t[c]).abs() > worst.0 {+ worst = ((exact[c] - t[c]).abs(), r - R_GROUND, mu, c);+ }+ }+ }+ }+ // (The worst is a ray that grazes the top of the ozone layer.)+ assert!(worst.0 < 6e-3, "{worst:?}");+ }++ /// The sun's light on the ground: redder and dimmer toward the horizon, never rising as the sun goes down,+ /// without a step anywhere (the horizon included), nothing from three degrees below it; the medium's own+ /// transmittance times the calibration's veil.+ #[test]+ fn sun_transmittance_is_smooth_and_reddens() {+ let a = earth();+ let zenith = a.sun_transmittance(sun_at(90.0));+ // Straight up the medium is 8 km of air, 1.2 km of haze and 15 km of ozone at their reference densities; the+ // veil is its column.+ for c in 0..3 {+ let medium = RAYLEIGH_SCATTERING[c] * 8.0 * (1.0 - (-12.5f64).exp()) + (MIE_SCATTERING + MIE_ABSORPTION) * 1.2 + OZONE_ABSORPTION[c] * 15.0;+ let veil = SUN_VEIL_COLUMN * (RAYLEIGH_SCATTERING[c] + MIE_SCATTERING + MIE_ABSORPTION);+ assert!((zenith[c] as f64 - (-(medium + veil)).exp()).abs() < 1e-4, "{zenith:?}");+ assert!((a.ground_transmittance(1.0)[c] - (-medium).exp()).abs() < 1e-4);+ }+ let mut last = zenith;+ for i in 0..=1900 {+ let elevation = 90.0 - i as f32 * 0.05;+ let t = a.sun_transmittance(sun_at(elevation));+ assert!(t.x >= t.y && t.y >= t.z && t.z >= 0.0, "{elevation}: {t:?}");+ assert!(t.cmple(last + 1e-6).all(), "{elevation}: {t:?} {last:?}");+ assert!((last - t).max_element() < 0.012, "a step at {elevation}: {t:?} {last:?}");+ if elevation < -3.0 {+ assert!(t.max_element() < 1e-6, "{elevation}: {t:?}");+ }+ last = t;+ }+ // The sun on the horizon: about a tenth of its red light, a hundredth of its green, none of its blue.+ let level = a.sun_transmittance(sun_at(0.0));+ assert!(level.x > 0.05 && level.x < 0.15 && level.y < 0.02 && level.z < 1e-3, "{level:?}");+ // The scene's scales: no air and no haze leaves the ozone and the haze's absorption, nearly clear.+ let bare = Atmosphere::earth(0.0, 0.0, 0.8, Vec3::ZERO).sun_transmittance(sun_at(45.0));+ assert!(bare.min_element() > 0.95 && bare.y < bare.z, "{bare:?}");+ let hazy = Atmosphere::earth(1.0, 10.0, 0.8, Vec3::ZERO).sun_transmittance(sun_at(45.0));+ assert!(hazy.x < a.sun_transmittance(sun_at(45.0)).x * 0.95, "{hazy:?}");+ }++ /// The three.js side has the same function (tools/three/sky.ts `sunTransmittance`) and the same table in its test+ /// (tools/three/test/sky.test.ts): sun elevation (degrees), rayleigh scale, mie scale, then R, G, B.+ #[test]+ fn sun_transmittance_is_the_same_on_both_sides() {+ const TABLE: [[f64; 6]; 12] = [+ [90.0, 1.0, 1.0, 0.924612, 0.84226, 0.716526],+ [45.0, 1.0, 1.0, 0.89537, 0.784979, 0.624876],+ [20.0, 1.0, 1.0, 0.799125, 0.611592, 0.384148],+ [10.0, 1.0, 1.0, 0.659276, 0.400327, 0.166401],+ [5.0, 1.0, 1.0, 0.488058, 0.206397, 0.042848],+ [2.0, 1.0, 1.0, 0.291951, 0.0684695, 0.00389411],+ [0.0, 1.0, 1.0, 0.0935232, 0.00763352, 3.24136e-05],+ [-1.0, 1.0, 1.0, 0.00821672, 0.000199967, 3.94459e-08],+ [-3.0, 1.0, 1.0, 0.0, 0.0, 0.0],+ [30.0, 2.0, 5.0, 0.700244, 0.50156, 0.250179],+ [3.0, 0.5, 20.0, 0.0428066, 0.0215879, 0.00795393],+ [15.0, 0.0, 0.0, 0.960424, 0.897494, 0.990766],+ ];+ for row in TABLE {+ let e = (row[0] as f32).to_radians();+ // (Any length of the direction, any azimuth.)+ let t = Atmosphere::earth(row[1] as f32, row[2] as f32, 0.8, Vec3::ZERO).sun_transmittance(Vec3::new(e.cos() * 0.6, e.sin(), e.cos() * 0.8) * 3.0);+ for c in 0..3 {+ assert!((t[c] as f64 - row[3 + c]).abs() <= 1e-3 * row[3 + c] + 1e-9, "{row:?}: {t:?}");+ }+ }+ }++ /// The sky of a clear day, by physics: no negative or runaway radiance; what the ground gets from the sky and+ /// the sun is less than what the sun brings to the top of the atmosphere, and most of it (a black ground, so that+ /// nothing is counted twice); bluer at the zenith than at the horizon; the same on both sides of the sun's+ /// meridian and for any azimuth of the sun; brighter around the sun (the haze's lobe).+ #[test]+ fn day_sky_is_physical() {+ let black = Atmosphere::earth(1.0, 1.0, 0.8, Vec3::ZERO);+ let luts = Luts::build(&black);+ for elevation in [75.0f32, 40.0, 15.0] {+ let sun = planet(elevation, 0.0);+ // Horizontal irradiance of the sky: a midpoint grid over the hemisphere.+ let (n, m) = (48, 96);+ let mut sky = Vec3::ZERO;+ for i in 0..n {+ let z = (i as f32 + 0.5) / n as f32;+ for k in 0..m {+ let phi = (k as f32 + 0.5) / m as f32 * 2.0 * PI;+ let h = (1.0 - z * z).sqrt();+ let l = luts.sky(&black, 0.0, Vec3::new(h * phi.cos(), h * phi.sin(), z), sun);+ assert!(l.min_element() >= 0.0 && l.max_element() < 5.0 && l.is_finite(), "{l:?}");+ sky += l * z * (2.0 * PI / (n * m) as f32);+ }+ }+ let direct = Vec3::from(black.ground_transmittance(sun.z as f64).map(|t| t as f32)) * sun.z;+ let (total, top) = (sky + direct, sun.z);+ assert!(total.max_element() < top, "{elevation}: {total:?} of {top}");+ assert!(total.min_element() > 0.6 * top, "{elevation}: {total:?} of {top}");+ assert!(sky.z > sky.y && sky.y > sky.x, "{sky:?}");+ }+ let (a, sun) = (earth(), planet(60.0, 0.0));+ let luts = Luts::build(&a);+ let (zenith, horizon) = (luts.sky(&a, 0.0, planet(90.0, 0.0), sun), luts.sky(&a, 0.0, planet(3.0, 180.0), sun));+ assert!(zenith.z / zenith.x > 1.5 * horizon.z / horizon.x, "{zenith:?} {horizon:?}");+ assert!(luminance(horizon) > 2.0 * luminance(zenith), "{zenith:?} {horizon:?}");+ for (e, az) in [(10.0, 40.0), (45.0, 90.0), (80.0, 170.0), (2.0, 5.0)] {+ let (left, right) = (luts.sky(&a, 0.0, planet(e, az), sun), luts.sky(&a, 0.0, planet(e, -az), sun));+ assert!((left - right).abs().max_element() < 1e-5 * left.max_element(), "{left:?} {right:?}");+ let turned = luts.sky(&a, 0.0, planet(e, az + 77.0), planet(60.0, 77.0));+ assert!((left - turned).abs().max_element() < 1e-4 * left.max_element(), "{left:?} {turned:?}");+ }+ let (near, far) = (luts.sky(&a, 0.0, planet(60.0, 8.0), sun), luts.sky(&a, 0.0, planet(60.0, 120.0), sun));+ assert!(near.x > 3.0 * far.x, "{near:?} {far:?}");+ // From 10 km up there is less air overhead: a darker zenith.+ assert!(luminance(luts.sky(&a, 10.0, planet(90.0, 0.0), sun)) < 0.5 * luminance(zenith));+ // A view that ends on the ground sees it lit: near albedo / pi x the sun's and the sky's light on it.+ let down = luts.sky(&a, 1.0, planet(-60.0, 90.0), sun);+ assert!(down.y > 0.09 && down.y < 0.16, "{down:?}");+ }++ /// A low sun: the sky around it is red, the sky opposite and overhead stays blue, and the whole of it dims as the+ /// sun goes under, without going out at the horizon.+ #[test]+ fn low_sun_reddens_and_twilight_fades() {+ let a = earth();+ let luts = Luts::build(&a);+ let sunset = planet(2.0, 0.0);+ let (glow, overhead) = (luts.sky(&a, 0.0, planet(3.0, 0.0), sunset), luts.sky(&a, 0.0, planet(90.0, 0.0), sunset));+ assert!(glow.x > 2.0 * glow.y && glow.y > 2.0 * glow.z, "{glow:?}");+ assert!(overhead.z > 1.5 * overhead.x, "{overhead:?}");+ let mut last = f32::MAX;+ for elevation in [30.0f32, 10.0, 2.0, 0.0, -2.0, -4.0, -6.0, -9.0, -12.0] {+ let l = luminance(luts.sky(&a, 0.0, planet(60.0, 90.0), planet(elevation, 0.0)));+ assert!(l < last && l >= 0.0, "{elevation}: {l} {last}");+ // (Civil twilight: the sky still has a hundredth of its light of ten minutes before sunset.)+ assert!(elevation < -5.0 || l > 5e-5, "{elevation}: {l}");+ last = l;+ }+ assert!(last < 2e-6, "{last}");+ assert_eq!(luts.sky(&a, 0.0, planet(60.0, 90.0), planet(-30.0, 0.0)), Vec3::ZERO);+ }++ /// The sky along a meridian of the bake, as its second difference between rows relative to the value: the+ /// largest size, and the largest change from one row to the next (a band is a jump of it). Rows from the zenith+ /// down to 11 degrees above the horizon (below that the sky's own profile turns within a row or two).+ fn roughness(texels: &[[f32; 4]], w: u32, h: u32, column: u32) -> (f32, f32) {+ let at = |row: u32| luminance(Vec3::from_slice(&texels[(row * w + column) as usize][..3]));+ let second = |row: u32| (at(row - 1) - 2.0 * at(row) + at(row + 1)) / at(row);+ let last = h / 2 - h / 16;+ ((1..=last).map(|r| second(r).abs()).fold(0.0, f32::max), (1..last).map(|r| (second(r + 1) - second(r)).abs()).fold(0.0, f32::max))+ }++ /// No bands: along meridians of the bake away from the sun's own lobe, the second difference between rows is+ /// small and changes slowly, by day and in twilight.+ #[test]+ fn bake_has_no_bands() {+ let a = earth();+ let t = SkyTables::new(&a);+ let (w, h) = DYNAMIC_SKY;+ for elevation in [60.0f32, 10.0, 2.0, -3.0] {+ let bake = bake_atmosphere_tables(&a, &t, sun_at(elevation), Vec3::ONE, 0.0, w, h, Glow::default(), 0.0);+ assert!(bake.texels.iter().all(|t| t.iter().all(|v| v.is_finite() && *v >= 0.0)));+ // (The sun is at u = 0.75: the meridians a quarter turn from it and opposite it.)+ for column in [0, w / 4, w / 2] {+ let (size, change) = roughness(&bake.texels, w, h, column);+ let (most, jump) = if elevation > 0.0 { (0.02, 0.004) } else { (0.05, 0.015) };+ assert!(size < most && change < jump, "sun {elevation}, column {column}: {size} {change}");+ }+ }+ }++ /// The numerical settings: with twice the orders, four times the directions and steps of the tables and four+ /// times the view's steps the sky changes by under 1.5 % by day and 8 % in twilight.+ #[test]+ fn quality_is_enough() {+ let a = earth();+ let (fast, fine) = (Luts::build(&a), Luts::build_at(&a, Quality { orders: 6, azimuths: 8, steps: 48, view_steps: 64 }));+ for (sun, within) in [(75.0f32, 0.015f32), (30.0, 0.015), (10.0, 0.015), (2.0, 0.015), (-2.0, 0.08), (-6.0, 0.08)] {+ for e in [90.0f32, 30.0, 8.0, 2.0, 0.45] {+ for az in [0.0f32, 3.0, 20.0, 90.0, 180.0] {+ let (x, y) = (fast.sky(&a, 0.005, planet(e, az), planet(sun, 0.0)), fine.sky(&a, 0.005, planet(e, az), planet(sun, 0.0)));+ assert!((x - y).abs().cmple(y * within + 1e-9).all(), "sun {sun}, view {e} {az}: {x:?} {y:?}");+ }+ }+ }+ }++ /// The scene's settings do what they say.+ #[test]+ fn settings() {+ let (sun, view) = (planet(40.0, 0.0), planet(50.0, 150.0));+ let sky = |a: &Atmosphere, dir: Vec3| Luts::build(a).sky(a, 0.0, dir, sun);+ let base = sky(&earth(), view);+ // No air and no haze: nothing scatters.+ assert_eq!(sky(&Atmosphere::earth(0.0, 0.0, 0.8, Vec3::splat(0.4)), view), Vec3::ZERO);+ // Twice the air: a brighter blue. More haze: a brighter, whiter sky around the sun.+ assert!(sky(&Atmosphere::earth(2.0, 1.0, 0.8, Vec3::splat(0.401978)), view).z > 1.3 * base.z);+ let around = planet(40.0, 10.0);+ let (clear, hazy) = (sky(&earth(), around), sky(&Atmosphere::earth(1.0, 5.0, 0.8, Vec3::splat(0.401978)), around));+ assert!(hazy.x > 3.0 * clear.x && hazy.z / hazy.x < clear.z / clear.x, "{clear:?} {hazy:?}");+ // The anisotropy: a tighter lobe is brighter close to the sun and dimmer away from it.+ let tight = Atmosphere::earth(1.0, 5.0, 0.9, Vec3::splat(0.401978));+ assert!(sky(&tight, planet(40.0, 4.0)).x > sky(&Atmosphere::earth(1.0, 5.0, 0.8, Vec3::splat(0.401978)), planet(40.0, 4.0)).x);+ assert!(sky(&tight, planet(40.0, 60.0)).x < sky(&Atmosphere::earth(1.0, 5.0, 0.8, Vec3::splat(0.401978)), planet(40.0, 60.0)).x);+ // The ground's albedo: its bounce lights the sky, a coloured ground tints it.+ let (dark, bright) = (sky(&Atmosphere::earth(1.0, 1.0, 0.8, Vec3::ZERO), view), sky(&Atmosphere::earth(1.0, 1.0, 0.8, Vec3::ONE), view));+ assert!(dark.y < base.y && base.y < bright.y && bright.y > 1.15 * dark.y, "{dark:?} {base:?} {bright:?}");+ let red = sky(&Atmosphere::earth(1.0, 1.0, 0.8, Vec3::new(1.0, 0.0, 0.0)), view);+ assert!(red.x > 1.1 * dark.x && (red.z - dark.z).abs() < 1e-3 * dark.z, "{dark:?} {red:?}");+ }++ /// A random number in [0, 1): xorshift64* (Marsaglia 2003, "Xorshift RNGs"; Vigna 2016 for the multiplier).+ struct Rng(u64);+ impl Rng {+ fn next(&mut self) -> f64 {+ self.0 ^= self.0 >> 12;+ self.0 ^= self.0 << 25;+ self.0 ^= self.0 >> 27;+ (self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64+ }+ }++ /// A unit vector at polar cosine `c` and azimuth `phi` about the axis `n`.+ fn around(n: glam::DVec3, c: f64, phi: f64) -> glam::DVec3 {+ let t = if n.x.abs() < 0.9 { glam::DVec3::X } else { glam::DVec3::Y }.cross(n).normalize();+ let b = n.cross(t);+ let s = (1.0 - c * c).max(0.0).sqrt();+ (t * phi.cos() + b * phi.sin()) * s + n * c+ }++ /// The reference for the model: the same medium path traced (delta tracking with next-event estimation toward+ /// the sun at every collision and ground hit; Novak et al. 2018, "Monte Carlo Methods for Volumetric Light+ /// Transport Simulation", sections 3 and 4), one colour channel at a time, up to `orders` scattering events+ /// with the true phase functions, a Lambertian ground. Returns the mean radiance per unit of the sun's+ /// illuminance over the directions of an `elevation` range (degrees) and an `azimuth` range from the sun's+ /// (degrees, both sides), seen from 5 m, and its standard error.+ /// `soft`: the sun's light below a point's horizon as the model has it (`slant`), or cut by the ground's sphere.+ #[allow(clippy::too_many_arguments)]+ fn path_traced(a: &Atmosphere, luts: &Luts, sun_elevation: f64, elevation: (f64, f64), azimuth: (f64, f64), paths: usize, soft: bool, orders: usize) -> ([f64; 3], [f64; 3]) {+ use glam::DVec3;+ let e = sun_elevation.to_radians();+ let sun = DVec3::new(e.cos(), 0.0, e.sin());+ let origin = DVec3::new(0.0, 0.0, R_GROUND + 0.005);+ let to_sun = |x: DVec3, c: usize| -> f64 {+ let r = x.length().max(R_GROUND);+ let mu = x.dot(sun) / x.length();+ if !soft && distance_to_ground(r, mu).is_some() {+ return 0.0;+ }+ luts.sun_transmittance(At::new(mu, r))[c]+ };+ let chunks = 64usize;+ let sums: Vec<[f64; 3]> = (0..chunks)+ .into_par_iter()+ .map(|chunk| {+ let mut rng = Rng(0x9E37_79B9_7F4A_7C15 ^ ((chunk as u64 + 1) * 0xD1B5_4A32_D192_ED03));+ let mut sum = [0.0f64; 3];+ for (c, sum) in sum.iter_mut().enumerate() {+ // The largest extinction anywhere above the ground: every component at its densest.+ let majorant = a.rayleigh[c] + a.mie_extinction + a.ozone[c];+ for _ in 0..paths / chunks {+ let (s0, s1) = (elevation.0.to_radians().sin(), elevation.1.to_radians().sin());+ let z = s0 + (s1 - s0) * rng.next();+ let phi = (azimuth.0 + (azimuth.1 - azimuth.0) * rng.next()).to_radians() * if rng.next() < 0.5 { -1.0 } else { 1.0 };+ let h = (1.0 - z * z).sqrt();+ let (mut x, mut d) = (origin, DVec3::new(h * phi.cos(), h * phi.sin(), z));+ let mut weight = 1.0f64;+ for _ in 0..orders {+ let (r, mu) = (x.length(), x.dot(d) / x.length());+ let ground = distance_to_ground(r, mu);+ let end = ground.unwrap_or_else(|| distance_out(r, mu, R_TOP));+ // Delta tracking to the next real collision.+ let mut t = 0.0;+ let hit = loop {+ t -= (1.0 - rng.next()).ln() / majorant;+ if t >= end {+ break None;+ }+ let dens = densities(((x + d * t).length() - R_GROUND).max(0.0));+ let extinction = a.extinction(dens)[c];+ if rng.next() * majorant < extinction {+ break Some((dens, extinction));+ }+ };+ match hit {+ Some((dens, extinction)) => {+ x += d * t;+ let (air, haze) = (a.rayleigh[c] * dens[0], a.mie_scattering * dens[1]);+ weight *= (air + haze) / extinction;+ let nu = d.dot(sun);+ *sum += weight * (air * Atmosphere::phase_rayleigh(nu) + haze * a.phase_mie(nu)) / (air + haze) * to_sun(x, c);+ // The next direction: the haze's lobe sampled (Henyey & Greenstein's inversion),+ // the air's uniformly with its phase function as the weight.+ if rng.next() * (air + haze) < haze {+ let g = a.mie_g;+ let cos = if g.abs() < 1e-3 { 1.0 - 2.0 * rng.next() } else {+ let q = (1.0 - g * g) / (1.0 - g + 2.0 * g * rng.next());+ (1.0 + g * g - q * q) / (2.0 * g)+ };+ d = around(d, cos.clamp(-1.0, 1.0), 2.0 * std::f64::consts::PI * rng.next());+ } else {+ let n = around(DVec3::Z, 1.0 - 2.0 * rng.next(), 2.0 * std::f64::consts::PI * rng.next());+ weight *= Atmosphere::phase_rayleigh(d.dot(n)) * 4.0 * std::f64::consts::PI;+ d = n;+ }+ }+ None if ground.is_some() => {+ x = (x + d * end).normalize() * (R_GROUND + 1e-6);+ let n = x.normalize();+ weight *= a.ground_albedo[c];+ *sum += weight / std::f64::consts::PI * n.dot(sun).max(0.0) * to_sun(x, c);+ d = around(n, rng.next().sqrt(), 2.0 * std::f64::consts::PI * rng.next());+ }+ None => break,+ }+ if weight < 1e-4 {+ break;+ }+ }+ }+ }+ sum+ })+ .collect();+ let per = (paths / chunks) as f64;+ let mean = [0, 1, 2].map(|c| sums.iter().map(|s| s[c]).sum::<f64>() / (per * chunks as f64));+ (mean, [0, 1, 2].map(|c| (sums.iter().map(|s| (s[c] / per - mean[c]).powi(2)).sum::<f64>() / (chunks * (chunks - 1)) as f64).sqrt()))+ }++ /// The model's mean over the same directions as `path_traced` (a midpoint grid).+ fn model_mean(a: &Atmosphere, luts: &Luts, sun_elevation: f64, elevation: (f64, f64), azimuth: (f64, f64)) -> [f64; 3] {+ let sun = planet(sun_elevation as f32, 0.0);+ let (n, m) = (64, 64);+ let mut sum = [0.0f64; 3];+ for i in 0..n {+ let (s0, s1) = (elevation.0.to_radians().sin(), elevation.1.to_radians().sin());+ let z = s0 + (s1 - s0) * (i as f64 + 0.5) / n as f64;+ for k in 0..m {+ let phi = (azimuth.0 + (azimuth.1 - azimuth.0) * (k as f64 + 0.5) / m as f64).to_radians();+ let h = (1.0 - z * z).sqrt();+ let l = luts.sky(a, 0.005, Vec3::new((h * phi.cos()) as f32, (h * phi.sin()) as f32, z as f32), sun);+ for c in 0..3 {+ sum[c] += l[c] as f64 / (n * m) as f64;+ }+ }+ }+ sum+ }++ /// The model against the same medium path traced, quickly (the long version: `against_path_tracing`): the mean+ /// of the upper sky with the sun high and low, within 4 % (the path tracing's own noise is 0.5 % here).+ #[test]+ fn sky_matches_path_tracing() {+ let a = earth();+ let luts = Luts::build(&a);+ for sun in [40.0, 5.0] {+ let (model, (traced, noise)) = (model_mean(&a, &luts, sun, (10.0, 90.0), (0.0, 180.0)), path_traced(&a, &luts, sun, (10.0, 90.0), (0.0, 180.0), 192_000, false, 64));+ for c in 0..3 {+ assert!(noise[c] < 0.01 * traced[c], "{noise:?} {traced:?}");+ assert!((model[c] / traced[c] - 1.0).abs() < 0.04, "sun {sun}: {model:?} {traced:?}");+ }+ }+ }++ /// The previous release's bake of the sky (`cleanroom-data/sky`, not part of the repository), if it is here.+ fn previous_release(sun_elevation: i32) -> Option<Vec<[f32; 4]>> {+ let dir = std::env::var("CLEANROOM_SKY_DATA").unwrap_or_else(|_| "../cleanroom-data/sky".into());+ let bytes = std::fs::read(format!("{dir}/sky-{sun_elevation}.f32")).ok()?;+ Some(bytes.as_chunks::<16>().0.iter().map(|c| [0, 1, 2, 3].map(|k| f32::from_le_bytes([c[4 * k], c[4 * k + 1], c[4 * k + 2], c[4 * k + 3]]))).collect())+ }++ /// The mean of a 256 x 128 bake over its first `rows` rows (from the zenith), by solid angle.+ fn bake_mean(texels: &[[f32; 4]], rows: usize) -> [f64; 3] {+ let (mut s, mut n) = ([0.0f64; 3], 0.0f64);+ for (i, t) in texels.iter().enumerate().take(rows * 256) {+ let k = (((i / 256) as f64 + 0.5) / 128.0 * std::f64::consts::PI).sin();+ for c in 0..3 {+ s[c] += k * t[c] as f64;+ }+ n += k;+ }+ s.map(|v| v / n)+ }++ /// `cargo test --release against_path_tracing -- --ignored --nocapture`: the model against the path-traced+ /// medium (a minute), over the sky above the bake's horizon rows and over parts of it; single scattering alone,+ /// and the further orders alone; the previous release's bake against the same reference where its data is here.+ #[test]+ #[ignore]+ fn against_path_tracing() {+ let a = earth();+ let luts = Luts::build(&a);+ let single = Luts { sun: Table::fill(SUN_TABLE.0, SUN_TABLE.1, At::mu_of_sun, |mu_sun, r| a.optical_depth(r, mu_sun)), scattered: Table { columns: 2, rows: 2, data: vec![[0.0; 3]; 4] }, ground: Table { columns: 2, rows: 1, data: vec![[0.0; 3]; 2] }, view_steps: QUALITY.view_steps };+ let paths = std::env::var("SKY_PATHS").ok().and_then(|v| v.parse().ok()).unwrap_or(4_000_000usize);+ println!("sun elevation, part of the sky: model / traced (R G B); single scattering; further orders (their share of the traced light); the path tracing's standard error %");+ for sun in [60.0, 30.0, 10.0, 2.0, -3.0] {+ for (name, elevation, azimuth) in [("above 2.8 deg", (2.8125, 90.0), (0.0, 180.0)), ("above 45 deg", (45.0, 90.0), (0.0, 180.0)), ("3-15 deg, sun side", (2.8125, 15.0), (0.0, 60.0)), ("3-15 deg, opposite", (2.8125, 15.0), (120.0, 180.0))] {+ let (model, once_model) = (model_mean(&a, &luts, sun, elevation, azimuth), model_mean(&a, &single, sun, elevation, azimuth));+ let ((traced, noise), (once, _)) = (path_traced(&a, &luts, sun, elevation, azimuth, paths, true, 64), path_traced(&a, &luts, sun, elevation, azimuth, paths, true, 1));+ let ratio = |x: [f64; 3], y: [f64; 3]| format!("{:.3} {:.3} {:.3}", x[0] / y[0], x[1] / y[1], x[2] / y[2]);+ let (further_model, further) = ([0, 1, 2].map(|c| model[c] - once_model[c]), [0, 1, 2].map(|c| traced[c] - once[c]));+ println!("{sun:5} {name:18}: {} | {} | {} ({}) | {:.2} {:.2} {:.2}", ratio(model, traced), ratio(once_model, once), ratio(further_model, further), ratio(further, traced), 100.0 * noise[0] / traced[0], 100.0 * noise[1] / traced[1], 100.0 * noise[2] / traced[2]);+ if name.starts_with("above 2") {+ if sun < 5.0 {+ let (hard, _) = path_traced(&a, &luts, sun, elevation, azimuth, paths, false, 64);+ println!("{sun:5} with the sun cut at the ground's sphere (no soft ground) the traced light is {} of the above", ratio(hard, traced));+ }+ if let Some(previous) = previous_release(sun as i32) {+ println!("{sun:5} the previous release's bake / traced: {}", ratio(bake_mean(&previous, 62), traced));+ }+ }+ }+ }+ }++ /// `cargo test --release reference_data -- --ignored --nocapture`: the acceptance numbers against the previous+ /// release's measurements (`cleanroom-data/sky`).+ #[test]+ #[ignore]+ fn reference_data() {+ let dir = std::env::var("CLEANROOM_SKY_DATA").unwrap_or_else(|_| "../cleanroom-data/sky".into());+ let a = earth();+ let csv = std::fs::read_to_string(format!("{dir}/sun-transmittance.csv")).expect("reference data");+ println!("sun transmittance: elevation | ours | previous release | difference % | the medium's own (no veil) against the previous release %");+ for line in csv.lines().skip(1) {+ let v: Vec<f32> = line.split(',').map(|x| x.parse().unwrap()).collect();+ let (t, medium) = (a.sun_transmittance(sun_at(v[0])), a.ground_transmittance((v[0] as f64).to_radians().sin()));+ let rel = |o: f32, r: f32| if r > 1e-6 { format!("{:+.2}", (o / r - 1.0) * 100.0) } else { "-".into() };+ println!("{:5} | {:.6} {:.6} {:.6} | {:.6} {:.6} {:.6} | {} {} {} | {} {} {}", v[0], t.x, t.y, t.z, v[1], v[2], v[3], rel(t.x, v[1]), rel(t.y, v[2]), rel(t.z, v[3]), rel(medium[0] as f32, v[1]), rel(medium[1] as f32, v[2]), rel(medium[2] as f32, v[3]));+ }+ let (w, h) = (256u32, 128u32);+ println!("sky bakes: sun elevation | upper hemisphere's mean, ours | previous release | difference % | roughness along the meridians at u = 0, 0.25, 0.5 (largest second difference / value, largest change of it), ours | previous release");+ for e in [60, 30, 10, 2, -3] {+ let reference = previous_release(e).expect("reference data");+ let ours = bake_atmosphere(&a, sun_at(e as f32), Vec3::ONE, 0.0, w, h);+ let (mo, mr) = (bake_mean(&ours.texels, 64), bake_mean(&reference, 64));+ let rough = |t: &[[f32; 4]]| [0, w / 4, w / 2].map(|c| roughness(t, w, h, c)).iter().map(|(a, b)| format!("{a:.4}/{b:.4}")).collect::<Vec<_>>().join(" ");+ println!("{e:3} | {:.5} {:.5} {:.5} | {:.5} {:.5} {:.5} | {:+.2} {:+.2} {:+.2} | {} | {}", mo[0], mo[1], mo[2], mr[0], mr[1], mr[2], (mo[0] / mr[0] - 1.0) * 100.0, (mo[1] / mr[1] - 1.0) * 100.0, (mo[2] / mr[2] - 1.0) * 100.0, rough(&ours.texels), rough(&reference));+ // What the sky gives a horizontal surface (per unit of the sun's illuminance), ours against the previous.+ let irradiance = |t: &[[f32; 4]]| {+ let mut e = Vec3::ZERO;+ for (i, t) in t.iter().enumerate().take((w * h / 2) as usize) {+ let theta = ((i as u32 / w) as f32 + 0.5) / h as f32 * PI;+ e += Vec3::new(t[0], t[1], t[2]) * (theta.cos() * theta.sin() * (PI / h as f32) * (2.0 * PI / w as f32));+ }+ e+ };+ let (eo, er) = (irradiance(&ours.texels), irradiance(&reference));+ println!(" horizontal irradiance from the sky: ours {:.5} {:.5} {:.5}, previous {:.5} {:.5} {:.5}, luminance ours / previous {:.4}", eo.x, eo.y, eo.z, er.x, er.y, er.z, luminance(eo) / luminance(er));+ // Ours / the previous release along the sun's meridian (u = 0.75), the opposite one and one across.+ for (name, col) in [("sun's side", 192u32), ("opposite", 64), ("across", 0)] {+ let mut s = format!(" {name:10} ours / previous, rows from the zenith:");+ for row in [0u32, 16, 32, 44, 52, 58, 61, 62, 63] {+ let (o, r) = (ours.texels[(row * w + col) as usize], reference[(row * w + col) as usize]);+ s += &format!(" {row}: {:.2}/{:.2}/{:.2}", o[0] / r[0], o[1] / r[1], o[2] / r[2]);+ }+ println!("{s}");+ }+ }+ }++ /// `cargo test --release timings -- --ignored --nocapture`: the tables' and the bake's times (the best of 15), on+ /// all cores and on the live view's three; and, for a busy machine, a bake small enough to run between two+ /// interruptions on one thread, the best of many.+ #[test]+ #[ignore]+ fn timings() {+ let a = earth();+ let best = |n: usize, f: &dyn Fn()| (0..n).map(|_| { let t = std::time::Instant::now(); f(); t.elapsed().as_secs_f64() * 1e3 }).fold(f64::MAX, f64::min);+ let run = |name: &str| {+ println!("{name}: tables (SkyTables::new) {:.1} ms", best(15, &|| { SkyTables::new(&a); }));+ let t = SkyTables::new(&a);+ for e in [60.0, 10.0, -3.0] {+ println!("{name}: bake_atmosphere_tables, sun at {e:3}: 256 x 128 {:.1} ms, 1024 x 512 {:.1} ms", best(15, &|| { bake_atmosphere_tables(&a, &t, sun_at(e), Vec3::ONE, 0.0, 256, 128, Glow::default(), 0.0); }), best(5, &|| { bake_atmosphere_tables(&a, &t, sun_at(e), Vec3::ONE, 0.0, 1024, 512, Glow::default(), 0.0); }));+ }+ };+ run("all cores");+ rayon::ThreadPoolBuilder::new().num_threads(3).build().unwrap().install(|| run("3 threads"));+ rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap().install(|| {+ let t = SkyTables::new(&a);+ let small = best(300, &|| { bake_atmosphere_tables(&a, &t, sun_at(10.0), Vec3::ONE, 0.0, 64, 32, Glow::default(), 0.0); });+ println!("one thread: 64 x 32 {small:.3} ms, so 256 x 128 is {:.1} ms of one core and 1024 x 512 {:.0} ms; tables {:.0} ms of one core", small * 16.0, small * 256.0, best(5, &|| { SkyTables::new(&a); }));+ });+ }+}diff --git a/tests/render/volume-local-fog.ts b/tests/render/volume-local-fog.tsindex d44d075..b231887 100644--- a/tests/render/volume-local-fog.ts+++ b/tests/render/volume-local-fog.ts@@ -1,31 +1,41 @@-// FogVolume against UE's Local Fog Volume density (VolumetricFog.usf), integrated here: an absorbing FogVolume of-// radius 1.5 m (radial extinction 1.5 / m, height extinction 2 / m with falloff 1 and offset 0) centred in front of a-// 2-nit emissive wall; the centre pixel's ray crosses the sphere through its centre at u.y = 0, so the height part is-// 2 there and the radial part 1.5 (1 - |t|)^0.82 along t in [-1, 1] (unit-sphere units of 1.5 m).+// FogVolume's density against its formula, written out and integrated here: an absorbing FogVolume of radius 1.5 m in+// front of a 2-nit emissive wall, seen from above through its centre, so that the ray crosses the heights where the+// height part goes from thinner than the radial part (above) to much denser (below). With u the point in the unit+// sphere (radius 1): radial = radialExtinction (1 - |u|^2), height = heightExtinction exp(-heightFalloff (u.y -+// heightOffset)), extinction = radial (1 - exp(-height / radial)). The pixel reads 2 exp(-optical depth).import { BoxGeometry, FogVolume, Mesh, MeshStandardMaterial } from "@threert/scene";-import { CENTER, camera, result, sceneWithSky, type TestMeta } from "./lib.ts";+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";-const R = 1.5, radial = 1.5, height = 2;-let od = 0;-const n = 4000;-for (let k = 0; k < n; k++) {- const t = -1 + (2 * (k + 0.5)) / n;- const a = Math.exp(-height), b = Math.exp(-radial * Math.pow(Math.max(1 - Math.abs(t), 0), 0.82));- od += Math.max(-Math.log(a - a * b + b), 0) * ((2 * R) / n);+const R = 1.5, radial = 1, height = 0.6, falloff = 3, offset = 0.2;+const EYE: [number, number, number] = [0, 3, 6];++/** The optical depth along the ray from EYE through the sphere's centre (Simpson's rule over the chord, 2 R long). */+function opticalDepth(): number {+ const len = Math.hypot(...EYE), dy = -EYE[1] / len;+ const n = 2000;+ let sum = 0;+ for (let k = 0; k <= n; k++) {+ const s = -1 + (2 * k) / n; // along the chord, in the unit sphere: u = s x direction+ const rad = radial * Math.max(1 - s * s, 0);+ const hgt = height * Math.exp(-falloff * (s * dy - offset));+ const ext = rad > 0 ? rad * (1 - Math.exp(-hgt / rad)) : 0;+ sum += ext * (k === 0 || k === n ? 1 : k % 2 ? 4 : 2);+ }+ return (sum * (2 / n) * R) / 3;}export const test: TestMeta = {id: "volume/local-fog", features: ["volume"], reference: "analytic", temporal: false,- metric: { kind: "radiance", region: [0.495, 0.49, 0.505, 0.51], expected: 2 * Math.exp(-od), tolerance: 0.03 },+ metric: { kind: "radiance", region: [0.495, 0.49, 0.505, 0.51], expected: 2 * Math.exp(-opticalDepth()), tolerance: 0.03 },spp: 16384,- note: "UE 5.8 Local Fog Volume density (volumetric fog voxelization), optical depth integrated numerically",+ note: "FogVolume's density (radial part, height part with falloff and offset, their combination), optical depth integrated numerically",};export default function () {const scene = sceneWithSky(0);const wall = new Mesh(new BoxGeometry(12, 12, 0.1), new MeshStandardMaterial({ name: "wall", color: 0x000000, emissive: 0xffffff, emissiveIntensity: 2 }));wall.position.set(0, 0, -3);- const fog = new FogVolume({ radialExtinction: radial, heightExtinction: height, heightFalloff: 1, heightOffset: 0, albedo: [0, 0, 0] });+ const fog = new FogVolume({ radialExtinction: radial, heightExtinction: height, heightFalloff: falloff, heightOffset: offset, albedo: [0, 0, 0] });fog.scale.set(2 * R, 2 * R, 2 * R);- return result(scene, camera(scene, [0, 0, 6], [0, 0, 0]), [wall, fog]);+ return result(scene, camera(scene, EYE, [0, 0, 0]), [wall, fog]);}diff --git a/tools/chart-model.py b/tools/chart-model.pynew file mode 100644index 0000000..90d629d--- /dev/null+++ b/tools/chart-model.py@@ -0,0 +1,143 @@+# A model of the live denoiser's change chart (renderer/shaders/live.wgsl, "The response of the histories"): the+# rules of `dtemporal`'s response on a grid of pixels fed synthetic one-sample noise, to set the chart's constants+# before a GPU is asked (the comment at CHART_A quotes its figures). Per kind of sample noise it prints+# - with nothing changing: the mean history length, the share of pixels the chart signals on a frame, and the+# histories' rms error (the cost of false signals: compare `--k 1e9`, the chart off);+# - after the histories start again with the light unchanged (a surface uncovered): their mean length 4, 8, 16, 32+# frames on (4, 8, 16, 32 if nothing signals) and the share of pixels signalled on a frame of those 32;+# - the mean of the histories over the truth 30, 60, 120, 170 frames into a steady fall of the light by --ramp a+# frame (what the drift is for: the chart's level follows a slow fall and stops seeing it);+# - the mean of the histories over the truth 2, 4, 8, 16, 32 frames after the light is scaled by a factor.+# And, with --sd, the pooled average's standard deviation on white residuals (CHART_SD).+#+# uv run --no-project --with numpy python tools/chart-model.py [--k 3.5] [--floor 0.04] [--gain 2] [--mature 4]+# [--a 0.125] [--cap 24] [--sd] [--ramp 0.026]+# [--drift 0.25] [--allow 2] [--allowup 4]+# (--drift 0: the chart alone.)+#+# Sample kinds (mean 1 before the change): steady (lognormal, sigma 0.2), noisy (exponential), rare0.1 / rare0.01 (one+# bright sample in 10 / 100, else dark), mix0.02 / mix0.1 (a steady half, the other half by one sample in 50 / 10).+import argparse+import numpy as np++ap = argparse.ArgumentParser()+ap.add_argument("--a", type=float, default=0.125) # CHART_A+ap.add_argument("--sdk", type=float, default=0.063) # CHART_SD+ap.add_argument("--k", type=float, default=3.5) # CHART_K+ap.add_argument("--floor", type=float, default=0.04) # CHART_FLOOR+ap.add_argument("--gain", type=float, default=2.0) # CHART_GAIN+ap.add_argument("--mature", type=float, default=4.0) # CHART_MATURE+ap.add_argument("--level", type=float, default=32.0) # CHART_LEVEL+ap.add_argument("--channel", type=float, default=0.25) # CHART_CHANNEL+ap.add_argument("--cap", type=float, default=24.0) # the frame's bound (HISTORY_LIVE)+ap.add_argument("--drift", type=float, default=0.25) # DRIFT_GAIN+ap.add_argument("--allow", type=float, default=2.0) # DRIFT_ALLOW+ap.add_argument("--allowup", type=float, default=4.0) # DRIFT_ALLOW_UP+ap.add_argument("--clip", type=float, default=7.0) # DRIFT_CLIP+ap.add_argument("--ramp", type=float, default=0.026) # the steady fall a frame (the Tokyo dusk's city: about that)+ap.add_argument("--first", type=float, default=1.0) # 1: the first frame's share (against no history) is no part of the level+ap.add_argument("--sd", action="store_true")+o = ap.parse_args()+rng = np.random.default_rng(1)+N = 96+DARK = 1e-3+++def taps(frame): # `chart_tap`+ q = [(-2, -1), (1, -2), (2, 1), (-1, 2)]+ return [(-x, y) for x, y in q] if frame & 1 else q+++def pool(frame, v): # the pixel itself and the four around it+ s = v.copy()+ for dx, dy in taps(frame):+ s += np.roll(v, (dy, dx), (0, 1))+ return s / 5+++def sample(kind, mean):+ if kind == "steady":+ return mean * rng.lognormal(-0.02, 0.2, (N, N))+ if kind == "noisy":+ return mean * rng.exponential(1.0, (N, N))+ if kind.startswith("rare"):+ p = float(kind[4:])+ return mean / p * (rng.random((N, N)) < p)+ p = float(kind[3:])+ return 0.5 * mean + 0.5 * mean / p * (rng.random((N, N)) < p)+++def run(kind, factor, frames=340, edit=300, restart=False, ramp=0.0):+ h = np.zeros((N, N))+ count = np.zeros((N, N))+ level = np.zeros((N, N))+ e = np.zeros((N, N)) # the residual average, as stored+ rms = np.zeros((N, N)) # the root of the residuals' mean square, as stored+ dr = np.zeros((N, N)) # the drift: the pooled relative residual, as stored+ m1 = np.zeros((N, N)) # the samples' mean and mean square (`diffuse_mom`)+ m2 = np.zeros((N, N))+ mean = np.ones((N, N))+ out = []+ for t in range(frames):+ if t == edit:+ mean = mean * factor+ if restart: # the histories start again (a surface uncovered): nothing is known there+ h[:] = 0+ count[:] = 0+ level[:] = 0+ e[:] = 0+ rms[:] = 0+ dr[:] = 0+ m1[:] = 0+ m2[:] = 0+ if t > edit and ramp:+ mean = mean * (1 - ramp)+ s = sample(kind, mean)+ pooled, spread, drift = pool(t, e), pool(t, rms * rms), pool(t, dr)+ # The drift: out of the history at DRIFT_GAIN a frame, less what the pixel's own noise allows.+ cv2 = np.maximum(m2 / np.maximum(m1 * m1, 1e-12) - 1, 0)+ trust = 1 / (1 + cv2)+ if o.drift > 0 and t >= 100:+ allow = np.where(drift > 0, o.allowup, o.allow) * o.sdk * trust * np.sqrt(cv2)+ f = 1 + o.drift * np.sign(drift) * np.maximum(np.abs(drift) - allow, 0) / np.maximum(trust, 0.5)+ h, m1, m2 = h * f, m1 * f, m2 * f * f+ share = s / (s + h * (1 + o.channel) + DARK)+ res = (share - level) * np.clip((count - 1) / (o.mature - 1), 0, 1)+ band = np.maximum(o.k * o.sdk * np.sqrt(spread), o.floor)+ drop = np.clip((np.abs(pooled) / band - 1) * o.gain, 0, 1)+ plain = 1 / np.maximum(np.minimum(count + 1, o.cap), 1)+ a = plain + drop * (1 - plain)+ rel = np.clip((s - h) / (h + DARK), -1, o.clip) * np.clip((count - 1) / (o.mature - 1), 0, 1) * trust+ h += (s - h) * a+ m1 += (s - m1) * a+ m2 += (s * s - m2) * a+ count = 1 / a+ level += (share - level) / np.clip(count - o.first, 1, o.level)+ level = np.floor(level * 1023 + rng.random((N, N))) / 1023+ e = np.round((pooled + (res - pooled) * o.a) * 127) / 127+ rms = np.round(np.sqrt(spread + (res * res - spread) * o.a) * 127) / 127+ dr = np.round(np.clip(drift + (rel - drift) * o.a, -0.5, 0.5) * (1 - drop) * 254) / 254+ out.append((h.mean() / mean.mean(), count.mean(), (drop > 0).mean(), np.sqrt(((h - mean) ** 2).mean()) / mean.mean()))+ return out+++if o.sd:+ e = np.zeros((N, N))+ v = []+ for t in range(400):+ p = pool(t, e)+ if t > 100:+ v.append(p.var())+ e = p + (rng.standard_normal((N, N)) - p) * o.a+ print(f"pooled average: {np.sqrt(np.mean(v)):.4f} of a residual's deviation ({1 / np.mean(v):.0f} residuals behind it)")+for kind in ["steady", "noisy", "mix0.02", "mix0.1", "rare0.1", "rare0.01"]:+ still = run(kind, 1.0, frames=300, edit=1000)[150:]+ print(f"{kind:9s} nothing changes: {np.mean([x[1] for x in still]):5.1f} frames, signalled {100 * np.mean([x[2] for x in still]):5.2f} %, rms {np.mean([x[3] for x in still]):.3f}, mean {np.mean([x[0] for x in still]):.3f}")+ r = run(kind, 1.0, restart=True)+ print(f" restarted: " + " ".join(f"{k}: {r[300 + k - 1][1]:.1f} frames" for k in [4, 8, 16, 32]) + f", signalled {100 * np.mean([x[2] for x in r[300:332]]):.2f} %")+ for g in [o.ramp, -o.ramp]:+ r = run(kind, 1.0, frames=480, ramp=g)+ print(f" {'falling' if g > 0 else 'rising'} {abs(g):.3g} a frame: " + " ".join(f"{k}: {r[300 + k - 1][0]:.2f}" for k in [30, 60, 120, 170]))+ for f in [1 / 13, 0.5, 0.75, 2.0, 13.0]:+ r = run(kind, f)+ print(f" x {f:<6.3g} " + " ".join(f"{k}: {r[300 + k - 1][0]:.2f}" for k in [2, 4, 8, 16, 32]))diff --git a/tools/post-live.ts b/tools/post-live.tsnew file mode 100644index 0000000..d23cc80--- /dev/null+++ b/tools/post-live.ts@@ -0,0 +1,86 @@+// The post chain, real-time against offline (renderer/src/post.rs and its passes in renderer/shaders/live.wgsl): for+// each scene, the real-time renderer held still on the scene's camera until it has converged (a headless session in+// lockstep, animation frozen), and the offline render of the same build. Two comparisons, CIE dE2000 over the picture:+// - post: the live picture against `post::finish` of the same frame's linear radiance at the scene's exposure (the+// post chain alone: bloom on its pyramid, the colour table against the function, the passes' arithmetic);+// - whole: the live picture against the offline picture (everything between a scene and its pixels: sampling,+// denoising, upscaling and the post chain).+// The scenes are taken to have manual exposure (the catalog's reference scenes do): the offline render's EV100 is the+// live frame's.+//+// node tools/post-live.ts [scene | path/to/scene.ts ...] [--frames 600] [--spp 256] [--width 960] [--height 540] [--scale 1] [--out DIR]+// [--override '{"post":{...}}' (the scenes' own preset overrides)] [--json out.json]+//+// Needs the renderer and its example: `cd renderer && cargo build --release && cargo build --release --example post_check`.+import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { basename, join, resolve } from "node:path";+import { bundleGame } from "./bundle-game.ts";+import { rendererBin, repoRoot, waitGpuLock } from "./lib/bench.ts";+import { startLive, type Build } from "./lib/live.ts";++const args = process.argv.slice(2);+const flag = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);+const scenes = args.filter((a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--"));+const list = scenes.length ? scenes : ["bistro", "cornell-box", "lamp-rooms", "material-grid", "neon-reflections", "sun-room", "zero-day"];+const [frames, spp, width, height] = [Number(flag("--frames", "600")), Number(flag("--spp", "256")), Number(flag("--width", "960")), Number(flag("--height", "540"))];+const scale = flag("--scale", "1");+// The preset overrides the scenes set themselves (`options.overrides`), for `post::finish` to have them too.+const override = flag("--override", "");+const out = resolve(flag("--out", join(repoRoot, "out/post-live")));+const presets = join(repoRoot, "presets");+const check = join(repoRoot, "renderer/target/release/examples/post_check");+if (!existsSync(check)) throw new Error(`${check}: build it (cargo build --release --example post_check)`);+const pairs = join(out, "live/pairs");+mkdirSync(pairs, { recursive: true });+mkdirSync(join(out, "offline"), { recursive: true });+await waitGpuLock("post-live");+const build: Build = { bin: rendererBin, assets: repoRoot, presets, bundles: out, label: "post-live" };++for (const [k, arg] of list.entries()) {+ // (A scene of the catalog by name, or any scene module by path.)+ const scene = basename(arg, ".ts");+ list[k] = scene;+ const game = (await bundleGame(arg.endsWith(".ts") ? resolve(arg) : join(repoRoot, `scenes/${arg}.ts`), join(out, `${scene}.js`))).out;+ // Offline: the picture, and the exposure it (and the live frame) is shown at.+ const stats = join(out, `offline/${scene}.json`);+ execFileSync(rendererBin, ["render", game, "-o", join(out, `offline/${scene}.png`), "--assets", repoRoot, "--presets", presets, "--width", String(width), "--height", String(height), "--spp", String(spp), "--stats", stats], { stdio: ["ignore", "ignore", "inherit"] });+ const ev100 = JSON.parse(readFileSync(stats, "utf8")).ev100 as number;+ // Live: `frames` frames held still, then one frame's picture and linear radiance, as a pair `post_check` reads.+ const live = startLive(build, game, { width, height, scale, env: { THREERT_FREEZE_TIME: "1" } });+ await live.firstFrame;+ live.send({ cmd: "lockstep", dt: 1 / 60 });+ const [png, raw] = [join(pairs, `${scene}.png`), join(pairs, `${scene}.raw`)];+ const synced = live.wait((l) => l === "live: sync held");+ live.send({ cmd: "frames", n: frames, sync: "held" });+ await synced;+ const done = Promise.all([live.wait((l) => l.includes(`snapshot ${png}`)), live.wait((l) => l.includes(`snapshot ${raw}`))]);+ live.send({ cmd: "snapshot", path: png });+ live.send({ cmd: "snapshot", path: raw });+ live.send({ cmd: "frames", n: 1, sync: "shot" });+ await done;+ await live.quit();+ renameSync(raw, join(pairs, `${scene}.hdr.f32`));+ writeFileSync(join(pairs, `${scene}.stats.json`), JSON.stringify({ width, height, ev100 }));+ console.log(`${scene}: live ${frames} frames, offline ${spp} spp, EV100 ${ev100.toFixed(2)}`);+}++// The post chain alone: `post::finish` of each live frame's radiance against the live picture. (`post_check`'s pair+// targets are the offline chain's against its reference; here its numbers say how close the passes are to the+// function, and its exit status is not this tool's.)+let post: string;+try {+ post = execFileSync(check, [join(out, "live"), "--out", join(out, "finish"), "--json", join(out, "post.json"), ...(override ? ["--override", override] : [])], { encoding: "utf8" });+} catch (e) {+ post = String((e as { stdout?: string }).stdout ?? e);+}+console.log("\npost chain alone (the live picture against post::finish of the same frame's radiance):");+console.log(post.trimEnd());+console.log("\nwhole picture (live against offline):");+const whole: Record<string, { mean: number; p99: number; max: number }> = {};+for (const scene of list) {+ whole[scene] = JSON.parse(execFileSync(check, ["--pictures", join(pairs, `${scene}.png`), join(out, `offline/${scene}.png`)], { encoding: "utf8" }));+ console.log(` ${scene.padEnd(18)} dE2000 mean ${whole[scene].mean.toFixed(3)}, p99 ${whole[scene].p99.toFixed(2)}`);+}+const json = flag("--json", "");+if (json) writeFileSync(json, JSON.stringify({ post: JSON.parse(readFileSync(join(out, "post.json"), "utf8")), whole }, null, 1));diff --git a/tools/three/sky.ts b/tools/three/sky.tsindex 872f748..3a6e75e 100644--- a/tools/three/sky.ts+++ b/tools/three/sky.ts@@ -2,9 +2,9 @@// native renderer so the *scene's* semantics are the same on both sides:// - `gradientRadiance`: the analytic SkyGradient dome (renderer/src/sky.rs `bake_gradient`), baked into an equirect// DataTexture for the background and a PMREM for image based lighting;-// - `sunTransmittance`: the atmosphere's transmittance toward the sun (sky.rs `sun_transmittance_ue`, UE-// FAtmosphereSetup::GetTransmittanceAtGroundLevel). With a SkyAtmosphere the DSL's DirectionalLight intensity is the-// illuminance above the atmosphere (UE semantics), so the sun reaching the ground is `lux x T`.+// - `sunTransmittance`: the atmosphere's transmittance toward the sun (sky.rs `Atmosphere::sun_transmittance`). With a+// SkyAtmosphere the DSL's DirectionalLight intensity is the illuminance above the atmosphere, so the sun reaching+// the ground is `lux x T`.// The atmosphere's sky radiance itself is three.js's own (the Preetham `Sky` addon), see SKY_NITS_PER_LUX.export type V3 = [number, number, number];@@ -143,35 +143,75 @@ export function bakeEquirect(width: number, height: number, radiance: (d: V3) =>// ------------------------------------------------------------------------------------------------ atmosphere-/** Transmittance from the ground (0.5 km) toward the sun (direction toward the sun, Y up): sky.rs, UE Earth defaults. */-export function sunTransmittance(sunDir: V3, rayleighScale = 1, mieScale = 1): V3 {- const bottom = 6360, top = 6420;- const rayleigh: V3 = [0.005802 * rayleighScale, 0.013558 * rayleighScale, 0.0331 * rayleighScale];- const mieExt = 0.003996 * mieScale + 0.000444;- const ozone: V3 = [0.00065, 0.001881, 0.000085];- const elev = Math.asin(Math.max(-1, Math.min(1, sunDir[1])));- const pos = [0, 0, bottom + 0.5], dir = [Math.cos(elev), 0, Math.sin(elev)];- // ray / sphere (radius top), nearest positive hit- const b = pos[0] * dir[0] + pos[1] * dir[1] + pos[2] * dir[2];- const c = pos[0] * pos[0] + pos[1] * pos[1] + pos[2] * pos[2] - top * top;- const disc = b * b - c;- let tmax = -1;- if (disc >= 0) {- const s = Math.sqrt(disc), t0 = -b - s, t1 = -b + s;- tmax = t0 < 0 && t1 < 0 ? -1 : t0 < 0 ? Math.max(t1, 0) : Math.max(t0, 0);- }- const od: V3 = [0, 0, 0];- if (tmax > 0) {- const n = 15, step = tmax / n;- for (let i = 0; i < n; i++) {- const p = [pos[0] + dir[0] * step * i, pos[1] + dir[1] * step * i, pos[2] + dir[2] * step * i];- const h = Math.hypot(p[0], p[1], p[2]) - bottom;- const dr = Math.exp((-1 / 8) * h), dm = Math.max(Math.exp((-1 / 1.2) * h), 0);- const doz = sat(1 - Math.abs(h - 25) / 15);- for (let k = 0; k < 3; k++) od[k] += step * (dm * mieExt + rayleigh[k] * dr + doz * ozone[k]);+// The share of the sun's light (RGB) that reaches the ground through Earth's atmosphere: the same quantity as the+// native renderer's `Atmosphere::sun_transmittance` (renderer/src/sky.rs), computed the same way, so a scene's sun has+// the same colour on both sides (tools/three/test/sky.test.ts holds the two to the same numbers). See sky.rs for the+// sources of the constants (Hillaire 2020, "A Scalable and Production Ready Sky and Atmosphere Rendering Technique",+// Table 1 and section 4; Bruneton's 2017 "Precomputed Atmospheric Scattering" demo) and for the design. Lengths in km.+const R_GROUND = 6360, R_TOP = 6460;+const H_RAYLEIGH = 8, H_MIE = 1.2;+const RAYLEIGH_SCATTERING: V3 = [5.802e-3, 13.558e-3, 33.1e-3];+const MIE_SCATTERING = 3.996e-3, MIE_ABSORPTION = 0.444e-3;+const OZONE_ABSORPTION: V3 = [0.65e-3, 1.881e-3, 0.085e-3];+const OZONE_CENTRE = 25, OZONE_HALF_WIDTH = 15;+/** sky.rs SOFT_GROUND: how far under the ground's surface the sun's ray may pass, km. */+const SOFT_GROUND = 5;+/** sky.rs SUN_VEIL_COLUMN, SUN_VEIL_ALTITUDE: the calibration of the sun's light on the ground to the previous release. */+const SUN_VEIL_COLUMN = 1.65, SUN_VEIL_ALTITUDE = 55;+/** Gauss-Legendre, 8 points on [-1, 1] (Abramowitz & Stegun 1964, Table 25.4; the positive half): node, weight. */+const GL8 = [+ [0.1834346424956498, 0.362683783378362],+ [0.525532409916329, 0.3137066458778873],+ [0.7966664774136267, 0.2223810344533745],+ [0.9602898564975362, 0.1012285362903763],+];++/** The distance from radius `r` along a ray of zenith cosine `mu` to the top of the atmosphere. */+const distanceToTop = (r: number, mu: number) => -r * mu + Math.sqrt(Math.max(r * r * (mu * mu - 1) + R_TOP * R_TOP, 0));++/** Columns of air, haze and ozone from radius `r` to the top along a ray that points up or level (sky.rs `columns_exact`). */+function columns(r: number, mu: number): V3 {+ const panels = 12, d = distanceToTop(r, mu);+ const n: V3 = [0, 0, 0];+ for (let p = 0; p < panels; p++) {+ const centre = (p + 0.5) / panels, half = 0.5 / panels;+ for (const [x, w] of GL8) {+ for (const s of [-1, 1]) {+ const u = centre + s * half * x;+ const t = d * u * u;+ const h = Math.sqrt(r * r + t * t + 2 * r * mu * t) - R_GROUND;+ const k = w * half * 2 * d * u;+ n[0] += k * Math.exp(-h / H_RAYLEIGH);+ n[1] += k * Math.exp(-h / H_MIE);+ n[2] += k * Math.max(1 - Math.abs(h - OZONE_CENTRE) / OZONE_HALF_WIDTH, 0);+ }}}- return [Math.exp(-od[0]), Math.exp(-od[1]), Math.exp(-od[2])];+ return n;+}++/**+ * The share of the sun's light (RGB) that reaches the ground from `sunDir` (toward the sun, Y up), with the+ * atmosphere's Rayleigh and Mie scattering scaled (SkyAtmosphere `rayleighScale`, `mieScale`).+ */+export function sunTransmittance(sunDir: V3, rayleighScale = 1, mieScale = 1): V3 {+ const mu = Math.max(-1, Math.min(1, sunDir[1] / (Math.hypot(sunDir[0], sunDir[1], sunDir[2]) || 1)));+ // A sun below the horizon: its ray passes under the surface, to radius p at its lowest, through the soft ground+ // (sky.rs `slant`): the columns of the level ray from p twice, less the mirrored ray's from the ground.+ let n: V3, ground = 0;+ if (mu >= 0) n = columns(R_GROUND, mu);+ else {+ const p = R_GROUND * Math.sqrt(Math.max(1 - mu * mu, 0));+ if (p <= R_GROUND - SOFT_GROUND) return [0, 0, 0];+ const level = columns(p, 0), mirror = columns(R_GROUND, -mu);+ n = [0, 1, 2].map((c) => Math.max(2 * level[c] - mirror[c], 0)) as V3;+ ground = ((R_GROUND - p) / 2) ** 4;+ }+ const rayleigh = RAYLEIGH_SCATTERING.map((b) => b * Math.max(rayleighScale, 0));+ const mie = MIE_SCATTERING * Math.max(mieScale, 0) + MIE_ABSORPTION;+ const level = R_GROUND / (R_GROUND + SUN_VEIL_ALTITUDE);+ const veil = SUN_VEIL_COLUMN / Math.sqrt(1 - level * level * (1 - mu * mu));+ return [0, 1, 2].map((c) => Math.exp(-(rayleigh[c] * n[0] + mie * n[1] + OZONE_ABSORPTION[c] * n[2] + ground + veil * (rayleigh[c] + mie)))) as V3;}/**diff --git a/tools/three/test/sky.test.ts b/tools/three/test/sky.test.tsnew file mode 100644index 0000000..791f55a--- /dev/null+++ b/tools/three/test/sky.test.ts@@ -0,0 +1,45 @@+// The sun's transmittance of the three.js side (tools/three/sky.ts `sunTransmittance`) against the native renderer's+// (renderer/src/sky.rs `Atmosphere::sun_transmittance`): the table below is in both tests (sky.rs+// `sun_transmittance_is_the_same_on_both_sides`), so the two functions agree where each agrees with it.+import assert from "node:assert/strict";+import { test } from "node:test";+import { sunTransmittance } from "../sky.ts";++/** Sun elevation (degrees), rayleighScale, mieScale, then R, G, B. */+export const SUN_TRANSMITTANCE = [+ [90, 1, 1, 0.924612, 0.84226, 0.716526],+ [45, 1, 1, 0.89537, 0.784979, 0.624876],+ [20, 1, 1, 0.799125, 0.611592, 0.384148],+ [10, 1, 1, 0.659276, 0.400327, 0.166401],+ [5, 1, 1, 0.488058, 0.206397, 0.042848],+ [2, 1, 1, 0.291951, 0.0684695, 0.00389411],+ [0, 1, 1, 0.0935232, 0.00763352, 3.24136e-05],+ [-1, 1, 1, 0.00821672, 0.000199967, 3.94459e-08],+ [-3, 1, 1, 0, 0, 0],+ [30, 2, 5, 0.700244, 0.50156, 0.250179],+ [3, 0.5, 20, 0.0428066, 0.0215879, 0.00795393],+ [15, 0, 0, 0.960424, 0.897494, 0.990766],+];++test("sunTransmittance is the native renderer's, within 0.1 %", () => {+ for (const [elevation, rayleigh, mie, ...expected] of SUN_TRANSMITTANCE) {+ const e = (elevation * Math.PI) / 180;+ // (Any length of the direction, any azimuth.)+ const t = sunTransmittance([3 * Math.cos(e) * 0.6, 3 * Math.sin(e), 3 * Math.cos(e) * 0.8], rayleigh, mie);+ for (let c = 0; c < 3; c++) assert.ok(Math.abs(t[c] - expected[c]) <= 1e-3 * expected[c] + 1e-9, `${elevation} ${rayleigh} ${mie}: ${t} against ${expected}`);+ }+});++test("sunTransmittance falls smoothly through the horizon and reddens", () => {+ let last = sunTransmittance([0, 1, 0]);+ for (let elevation = 90; elevation >= -5; elevation -= 0.05) {+ const e = (elevation * Math.PI) / 180;+ const t = sunTransmittance([Math.cos(e), Math.sin(e), 0]);+ assert.ok(t[0] >= t[1] && t[1] >= t[2] && t[2] >= 0, `${elevation}: ${t}`);+ for (let c = 0; c < 3; c++) assert.ok(t[c] <= last[c] + 1e-9 && last[c] - t[c] < 0.012, `a step at ${elevation}: ${t} after ${last}`);+ if (elevation < -3) assert.ok(t[0] < 1e-6);+ last = t;+ }+ // The defaults are Earth's.+ assert.deepEqual(sunTransmittance([0, 1, 0]), sunTransmittance([0, 1, 0], 1, 1));+});diff --git a/ue5/scripts/ue_volumes.py b/ue5/scripts/ue_volumes.pyindex 00ad105..73d7e04 100644--- a/ue5/scripts/ue_volumes.py+++ b/ue5/scripts/ue_volumes.py@@ -12,8 +12,7 @@ Scene (mirror of tools/volume-scene.ts; keep in sync): a 30 x 30 m floor and a 1at (0, 1.4, 0), 50-degree vertical field of view, manual exposure EV100 3. Coordinates: ours are Y-up metres,UE = 100 * (x, z, y) cm.-The fog is a Heterogeneous Volume with a Local Fog Volume's density (VolumetricFog.usf's voxelization, as-packages/scene FogVolume): the path tracer does not render Local Fog Volumes, and the Local Fog Volume through Lumen's+The fog is a Heterogeneous Volume with the density of packages/scene's FogVolume (the same formula, below): the path tracer does not render Local Fog Volumes, and the Local Fog Volume through Lumen'svolumetric fog hung the editor on this Mac ("lfv": true tries it). The smoke column and thefireball are Heterogeneous Volumes in both: Volume-domain materials whose Custom nodes are our volume functions inHLSL. A Heterogeneous Volume's extinction and emission are per local cm (before the actor's scale), measured: world@@ -127,16 +126,14 @@ float3 LP = (P - Center) / Size;"""BODIES = {+ # The same density as packages/scene/src/effects.ts LOCAL_FOG (see there), in HLSL: U is the point in the unit+ # sphere (radius 1, y up), the fog is where its radial part and its height part both are."Fog": """float3 U = LP * 2.0;-float fade = saturate(1.0 - length(U));-float ext = 0.0;-if (fade > 0.0) {- float height = Height > 0.0 ? Height * exp(min(-Falloff * (U.y - Offset), 80.0)) : 0.0;- float a = exp(-height);- float b = exp(-Radial * pow(fade, 0.82));- ext = max(-log(max(a - a * b + b, 1e-30)), 0.0);-}+float radial = max(Radial, 0.0) * max(1.0 - dot(U, U), 0.0);+float height = max(Height, 0.0) * exp(clamp(-Falloff * (U.y - Offset), -40.0, 40.0));+float x = min(height / max(radial, 1e-9), 40.0);+float ext = radial * (x < 0.02 ? x * (1.0 - x * (0.5 - x / 6.0)) : 1.0 - exp(-x));float3 alb = Albedo;float3 emi = 0;""",