@threenative/core 0.3.6 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
@@ -0,0 +1,852 @@
1
+ // The tone curve of a fresh Unreal Engine 5.8.3 project, the default tone mapping of `createRenderer`
2
+ // (owner exception to "never own the look", 2026-10-22). The harness keeps a copy while its lanes tune
3
+ // the look (`scripts/unreal-look/scaffold/render/tonemap.ts`); this file is the engine's.
4
+ //
5
+ // Filmic curve with the parameters and defaults of a fresh Unreal Engine 5 project:
6
+ // slope 0.88, toe 0.55, shoulder 0.26, black clip 0, white clip 0.04 (Unreal 5.8.3,
7
+ // `Engine/Source/Runtime/Engine/Private/Scene.cpp:440-448`). Written from the published shape,
8
+ // not from Unreal code: each channel, in the ACEScg (AP1) primaries, follows a straight line in
9
+ // log10 space through mid grey (0.18 in, 0.18 out), and two sigmoids replace the line below the
10
+ // toe and above the shoulder. A small desaturation before and after keeps saturated highlights
11
+ // from shifting hue, as the ACES reference rendering does.
12
+ //
13
+ // Before the curve, as in Unreal's colour LUT, bright saturated colour is expanded toward a wider
14
+ // gamut (`expandGamut`, 1 by default) and the blue correction runs (`blueCorrection`, 0.6).
15
+ // `filmicToneMap()` is the same curve on plain numbers, so a test or a capture script can apply it
16
+ // to a scene-linear image.
17
+ import { CustomToneMapping, Matrix3 } from "three";
18
+ import {
19
+ abs,
20
+ atan,
21
+ clamp,
22
+ dot,
23
+ exp,
24
+ exp2,
25
+ float,
26
+ log,
27
+ max,
28
+ min,
29
+ mix,
30
+ pow,
31
+ screenCoordinate,
32
+ sign,
33
+ sqrt,
34
+ step,
35
+ vec2,
36
+ vec3,
37
+ } from "three/tsl";
38
+ import type { Node } from "three/webgpu";
39
+
40
+ export interface IFilmicCurve {
41
+ readonly slope: number;
42
+ readonly toe: number;
43
+ readonly shoulder: number;
44
+ readonly blackClip: number;
45
+ readonly whiteClip: number;
46
+ readonly blueCorrection: number;
47
+ /**
48
+ * Unreal's "Expand Gamut" (1 in a fresh project, `Engine/Source/Runtime/Engine/Private/Scene.cpp:437`): bright,
49
+ * saturated colour is pushed toward a wider gamut before the blue correction and the curve. 0 turns it off.
50
+ * Unreal's linear EXR frames are taken after this step (`Engine/Shaders/Private/PostProcessCombineLUTs.usf`,
51
+ * the expansion runs before the output-device branches), so a curve applied to an Unreal EXR needs 0 here.
52
+ */
53
+ readonly expandGamut: number;
54
+ /**
55
+ * The ACES reference rendering's glow, which Unreal keeps in its filmic curve (`Engine/Shaders/Private/TonemapCommon.ush`):
56
+ * dark, saturated colour gets up to 5% brighter. 1 is Unreal's amount, 0 turns it off.
57
+ */
58
+ readonly glow: number;
59
+ /**
60
+ * The ACES reference rendering's red modifier, also in Unreal's filmic curve: the red of a saturated red is pulled
61
+ * toward a dark pivot, up to 18%. 1 is Unreal's amount, 0 turns it off.
62
+ */
63
+ readonly redModifier: number;
64
+ /**
65
+ * Output dither in 8-bit steps: triangular grain added to the display colour before the backbuffer rounds it.
66
+ * Unreal 5.8.3 uses one step for an 8-bit backbuffer, so a dim gradient reads as grain of one level instead of
67
+ * contour bands. 0 turns it off. Only the tone-mapping node dithers; `filmicToneMap()` stays noise-free.
68
+ */
69
+ readonly dither: number;
70
+ /**
71
+ * The largest scene-linear value, after exposure, that one channel can hold when the colour goes into Unreal's
72
+ * colour LUT (the top of its 14-stop log shaper, `Engine/Shaders/Private/GammaCorrectionCommon.ush`: `LogToLin(1)`
73
+ * minus `LogToLin(0)`). A channel above it is clipped there, so the sun disc and a hot emitter lose their hue
74
+ * earlier than an unbounded curve would. 0, the default, leaves the channel unbounded; pass `LUT_CLIP` for Unreal's.
75
+ */
76
+ readonly lutClip: number;
77
+ }
78
+
79
+ // Unreal's log shaper: 14 stops about mid grey 0.18, grey at code 444 of 1023.
80
+ /** Unreal's LUT channel clip, 43.7. Off by default (it moves hot-emitter pixels); `filmicCurve: { lutClip: LUT_CLIP }` turns it on. */
81
+ export const LUT_CLIP = 2 ** ((1 - 444 / 1023) * 14) * 0.18 - 2 ** ((-444 / 1023) * 14) * 0.18;
82
+
83
+ /** Unreal 5.8.3 project defaults. Change these numbers to change the curve. */
84
+ export const FILMIC_CURVE: IFilmicCurve = {
85
+ slope: 0.88,
86
+ toe: 0.55,
87
+ shoulder: 0.26,
88
+ blackClip: 0,
89
+ whiteClip: 0.04,
90
+ blueCorrection: 0.6,
91
+ expandGamut: 1,
92
+ glow: 1,
93
+ redModifier: 1,
94
+ dither: 1,
95
+ lutClip: 0,
96
+ };
97
+
98
+ type Vec3 = readonly [number, number, number];
99
+ type Mat3 = readonly [number, number, number, number, number, number, number, number, number];
100
+
101
+ // Linear sRGB (D65) <-> ACEScg (AP1, D60) with a Bradford adaptation, row-major.
102
+ const SRGB_TO_AP1: Mat3 = [
103
+ 0.6130974024, 0.3395231462, 0.0473794514, 0.0701937225, 0.9163538791, 0.0134523985, 0.0206155929,
104
+ 0.1095697729, 0.8698146342,
105
+ ];
106
+ const AP1_TO_SRGB: Mat3 = [
107
+ 1.7050509927, -0.6217921207, -0.083258872, -0.1302564175, 1.1408047366, -0.0105483191,
108
+ -0.0240033568, -0.1289689761, 1.1529723329,
109
+ ];
110
+ // Standard published ACES AP0 -> AP1 matrix (both D60), row-major.
111
+ const AP0_TO_AP1 = new Matrix3().set(
112
+ 1.4514393161,
113
+ -0.2365107469,
114
+ -0.2149285693,
115
+ -0.0765537734,
116
+ 1.1762296998,
117
+ -0.0996759264,
118
+ 0.0083161484,
119
+ -0.0060324498,
120
+ 0.9977163014,
121
+ );
122
+ // ACES LMT Blue Light Artifact Fix, (c) Academy of Motion Picture Arts and Sciences, ACES licence
123
+ // ampas/aces-dev v1.3.1, transforms/ctl/lmt/LMT.Academy.BlueLightArtifactFix.ctl.
124
+ // Transposed from CTL's row-vector matrix for M*v here.
125
+ /*
126
+ # License Terms for Academy Color Encoding System Components #
127
+
128
+ Academy Color Encoding System (ACES) software and tools are provided by the
129
+ Academy under the following terms and conditions: A worldwide, royalty-free,
130
+ non-exclusive right to copy, modify, create derivatives, and use, in source and
131
+ binary forms, is hereby granted, subject to acceptance of this license.
132
+
133
+ Copyright © 2015 Academy of Motion Picture Arts and Sciences (A.M.P.A.S.).
134
+ Portions contributed by others as indicated. All rights reserved.
135
+
136
+ Performance of any of the aforementioned acts indicates acceptance to be bound
137
+ by the following terms and conditions:
138
+
139
+ * Copies of source code, in whole or in part, must retain the above copyright
140
+ notice, this list of conditions and the Disclaimer of Warranty.
141
+
142
+ * Use in binary form must retain the above copyright notice, this list of
143
+ conditions and the Disclaimer of Warranty in the documentation and/or other
144
+ materials provided with the distribution.
145
+
146
+ * Nothing in this license shall be deemed to grant any rights to trademarks,
147
+ copyrights, patents, trade secrets or any other intellectual property of
148
+ A.M.P.A.S. or any contributors, except as expressly stated herein.
149
+
150
+ * Neither the name "A.M.P.A.S." nor the name of any other contributors to this
151
+ software may be used to endorse or promote products derivative of or based on
152
+ this software without express prior written permission of A.M.P.A.S. or the
153
+ contributors, as appropriate.
154
+
155
+ This license shall be construed pursuant to the laws of the State of
156
+ California, and any disputes related thereto shall be subject to the
157
+ jurisdiction of the courts therein.
158
+
159
+ Disclaimer of Warranty: THIS SOFTWARE IS PROVIDED BY A.M.P.A.S. AND CONTRIBUTORS
160
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
161
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
162
+ NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL A.M.P.A.S., OR ANY
163
+ CONTRIBUTORS OR DISTRIBUTORS, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
164
+ SPECIAL, EXEMPLARY, RESITUTIONARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
165
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
166
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
167
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
168
+ OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
169
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
170
+
171
+ WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE ACADEMY SPECIFICALLY
172
+ DISCLAIMS ANY REPRESENTATIONS OR WARRANTIES WHATSOEVER RELATED TO PATENT OR
173
+ OTHER INTELLECTUAL PROPERTY RIGHTS IN THE ACADEMY COLOR ENCODING SYSTEM, OR
174
+ APPLICATIONS THEREOF, HELD BY PARTIES OTHER THAN A.M.P.A.S.,WHETHER DISCLOSED OR
175
+ UNDISCLOSED.
176
+ */
177
+ const blueAP0 = new Matrix3().set(
178
+ 0.9404372683,
179
+ -0.0183068787,
180
+ 0.0778696104,
181
+ 0.0083786969,
182
+ 0.8286599939,
183
+ 0.1629613092,
184
+ 0.0005471261,
185
+ -0.0008833746,
186
+ 1.0003362486,
187
+ );
188
+ const blueAP1 = AP0_TO_AP1.clone().multiply(blueAP0).multiply(AP0_TO_AP1.clone().invert());
189
+ // Transpose only for serialization: Matrix3 stores columns, apply()/multiply() consume rows.
190
+ export const BLUE_CORRECTION_AP1 = blueAP1.clone().transpose().toArray() as Mat3;
191
+ export const BLUE_CORRECTION_INVERSE_AP1 = blueAP1.clone().invert().transpose().toArray() as Mat3;
192
+
193
+ // The glow and the red modifier of the ACES reference rendering (ACES licence as above, ampas/aces-dev
194
+ // v1.3.1, transforms/ctl/rrt/RRT.ctl). Unreal keeps both in its filmic curve: they run in AP0 after the
195
+ // blue correction and before the desaturation (`Engine/Shaders/Private/TonemapCommon.ush`). The glow
196
+ // lifts saturated colour that is dark; the red modifier pulls the red channel of a saturated red toward
197
+ // a pivot, by a weight that is 1 at red and 0 half the width away. The gain, mid level, scale, pivot and
198
+ // width are the published ACES numbers. Without them Unreal's red box is 5 to 7 levels off on red.
199
+ const GLOW_GAIN = 0.05;
200
+ const GLOW_MID = 0.08;
201
+ const RED_SCALE = 0.82;
202
+ const RED_PIVOT = 0.03;
203
+ const RED_WIDTH = (135 * Math.PI) / 180;
204
+ const AP0_TO_AP1_ROWS = AP0_TO_AP1.clone().transpose().toArray() as Mat3;
205
+ const AP1_TO_AP0 = AP0_TO_AP1.clone().invert().transpose().toArray() as Mat3;
206
+
207
+ /** The red modifier's weight at a hue, in radians from red: 1 at red, 0 at half the width away and beyond. */
208
+ export function redModifierWeight(hue: number): number {
209
+ const edge = Math.min(1, Math.max(0, 1 - Math.abs((2 * hue) / RED_WIDTH)));
210
+ return (edge * edge * (3 - 2 * edge)) ** 2;
211
+ }
212
+
213
+ /** The glow and the red modifier on one AP1 colour; `glow` and `red` scale their amounts (1 is Unreal's). */
214
+ function glowAndRed(ap1: Vec3, glow: number, red: number): [number, number, number] {
215
+ const [r, g, b] = multiply(AP1_TO_AP0, ap1);
216
+ const high = Math.max(r, g, b);
217
+ const saturation =
218
+ (Math.max(high, 1e-10) - Math.max(Math.min(r, g, b), 1e-10)) / Math.max(high, 1e-2);
219
+ const spread = 0.5 * ((r - g) ** 2 + (g - b) ** 2 + (b - r) ** 2);
220
+ const brightness = (r + g + b + 1.75 * Math.sqrt(spread)) / 3;
221
+ const x = (saturation - 0.4) / 0.2;
222
+ const tail = Math.max(1 - Math.abs(x / 2), 0);
223
+ const shaper = (1 + Math.sign(x) * (1 - tail * tail)) / 2;
224
+ const fade = Math.min(1, Math.max(0, GLOW_MID / Math.max(brightness, 1e-10) - 0.5));
225
+ const lift = 1 + glow * GLOW_GAIN * shaper * fade;
226
+ const [lr, lg, lb] = [r * lift, g * lift, b * lift];
227
+ const hue = Math.atan2(Math.sqrt(3) * (lg - lb), 2 * lr - lg - lb);
228
+ const pulled =
229
+ lr + red * redModifierWeight(hue) * saturation * (RED_PIVOT - lr) * (1 - RED_SCALE);
230
+ return multiply(AP0_TO_AP1_ROWS, [pulled, lg, lb]);
231
+ }
232
+
233
+ // Gamut expansion, in AP1 -> AP1: the sRGB gamut re-expressed in a wider set of primaries (CIE xy
234
+ // red 0.6965 0.3065, green 0.245 0.718, blue 0.1302 0.0456, white 0.3127 0.329), between P3 and
235
+ // AP1. It is what Unreal's colour LUT mixes in by `expandAmount()`. The matrix takes AP1 to sRGB,
236
+ // reads those numbers as numbers in the wide primaries and carries them to AP1; all of it follows
237
+ // from the chromaticities, and the spec derives it again to 1e-6. Without it the clear sky carries
238
+ // a red excess against the Unreal L2 frames (PRD-632).
239
+ export const EXPAND_AP1: Mat3 = [
240
+ 1.370412273, -0.329292155, -0.063683161, -0.083433332, 1.097092614, -0.010861358, -0.025793271,
241
+ -0.098625844, 1.203694898,
242
+ ];
243
+
244
+ /**
245
+ * How much of the expansion a colour gets: more for saturated colour, and for brighter colour
246
+ * (luminance squared), none for grey. `chroma` is the colour over its luminance.
247
+ */
248
+ export function expandAmount(chromaDistanceSquared: number, luma: number, gamut: number): number {
249
+ return (1 - 2 ** (-4 * chromaDistanceSquared)) * (1 - 2 ** (-4 * gamut * luma * luma));
250
+ }
251
+
252
+ const AP1_LUMA: Vec3 = [0.2722287168, 0.6740817658, 0.0536895174];
253
+
254
+ function expandAp1(ap1: Vec3, gamut: number): Vec3 {
255
+ const luma = ap1[0] * AP1_LUMA[0] + ap1[1] * AP1_LUMA[1] + ap1[2] * AP1_LUMA[2];
256
+ if (luma <= 0) return ap1;
257
+ const d2 = ap1.reduce((sum, v) => sum + (v / luma - 1) ** 2, 0);
258
+ const amount = expandAmount(d2, luma, gamut);
259
+ const wide = multiply(EXPAND_AP1, ap1);
260
+ return ap1.map((v, i) => v + ((wide[i] ?? 0) - v) * amount) as number[] & Vec3;
261
+ }
262
+
263
+ /** The gamut expansion alone, scene-linear sRGB in and out (negative results clip to zero). */
264
+ export function expandGamutLinear(
265
+ rgb: readonly [number, number, number],
266
+ gamut = FILMIC_CURVE.expandGamut,
267
+ ): [number, number, number] {
268
+ const [x, y, z] = multiply(AP1_TO_SRGB, expandAp1(multiply(SRGB_TO_AP1, rgb), gamut));
269
+ return [Math.max(0, x), Math.max(0, y), Math.max(0, z)];
270
+ }
271
+ const PRE_SATURATION = 0.96;
272
+ const POST_SATURATION = 0.93;
273
+ const MID_GREY = 0.18;
274
+ const LOG10 = Math.log(10);
275
+
276
+ /** The constants the curve needs, derived once from its shape parameters. */
277
+ function curveMatches(c: IFilmicCurve): {
278
+ toeScale: number;
279
+ shoulderScale: number;
280
+ toeMatch: number;
281
+ shoulderMatch: number;
282
+ straightMatch: number;
283
+ } {
284
+ const toeScale = 1 + c.blackClip - c.toe;
285
+ const shoulderScale = 1 + c.whiteClip - c.shoulder;
286
+ const logMid = Math.log10(MID_GREY);
287
+ let toeMatch: number;
288
+ if (c.toe > 0.8) {
289
+ // A toe this long never reaches the straight segment through mid grey from below.
290
+ toeMatch = (1 - c.toe - MID_GREY) / c.slope + logMid;
291
+ } else {
292
+ const bt = (MID_GREY + c.blackClip) / toeScale - 1;
293
+ toeMatch = logMid - 0.5 * Math.log((1 + bt) / (1 - bt)) * (toeScale / c.slope);
294
+ }
295
+ const straightMatch = (1 - c.toe) / c.slope - toeMatch;
296
+ const shoulderMatch = c.shoulder / c.slope - straightMatch;
297
+ return { toeScale, shoulderScale, toeMatch, shoulderMatch, straightMatch };
298
+ }
299
+
300
+ function smooth(t: number): number {
301
+ return t * t * (3 - 2 * t);
302
+ }
303
+
304
+ /** One AP1 channel through the curve. Input is scene-linear, output is display-linear. */
305
+ export function filmicCurve(value: number, c: IFilmicCurve = FILMIC_CURVE): number {
306
+ const m = curveMatches(c);
307
+ const logValue = Math.log10(Math.max(value, 1e-10));
308
+ const straight = c.slope * (logValue + m.straightMatch);
309
+ const toe =
310
+ logValue < m.toeMatch
311
+ ? -c.blackClip +
312
+ (2 * m.toeScale) / (1 + Math.exp((-2 * c.slope * (logValue - m.toeMatch)) / m.toeScale))
313
+ : straight;
314
+ const shoulder =
315
+ logValue > m.shoulderMatch
316
+ ? 1 +
317
+ c.whiteClip -
318
+ (2 * m.shoulderScale) /
319
+ (1 + Math.exp((2 * c.slope * (logValue - m.shoulderMatch)) / m.shoulderScale))
320
+ : straight;
321
+ let t = Math.min(1, Math.max(0, (logValue - m.toeMatch) / (m.shoulderMatch - m.toeMatch)));
322
+ if (m.shoulderMatch < m.toeMatch) t = 1 - t;
323
+ return toe + (shoulder - toe) * smooth(t);
324
+ }
325
+
326
+ function multiply(m: Mat3, v: Vec3): [number, number, number] {
327
+ return [
328
+ m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
329
+ m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
330
+ m[6] * v[0] + m[7] * v[1] + m[8] * v[2],
331
+ ];
332
+ }
333
+
334
+ function correctBlue(v: Vec3, matrix: Mat3, amount: number): [number, number, number] {
335
+ const corrected = multiply(matrix, v);
336
+ return [
337
+ v[0] + (corrected[0] - v[0]) * amount,
338
+ v[1] + (corrected[1] - v[1]) * amount,
339
+ v[2] + (corrected[2] - v[2]) * amount,
340
+ ];
341
+ }
342
+
343
+ function saturate(v: Vec3, amount: number): [number, number, number] {
344
+ const y = v[0] * AP1_LUMA[0] + v[1] * AP1_LUMA[1] + v[2] * AP1_LUMA[2];
345
+ return [y + (v[0] - y) * amount, y + (v[1] - y) * amount, y + (v[2] - y) * amount];
346
+ }
347
+
348
+ const at = (v: readonly number[], i: number): number => v[i] ?? 0;
349
+ /** Red, green, blue and a master factor, as Unreal's colour grading panel shows each control. */
350
+ export type Vec4 = readonly [number, number, number, number];
351
+
352
+ /** One set of Unreal's colour grading controls. */
353
+ export interface IGradeControls {
354
+ readonly saturation: Vec4;
355
+ readonly contrast: Vec4;
356
+ readonly gamma: Vec4;
357
+ readonly gain: Vec4;
358
+ readonly offset: Vec4;
359
+ }
360
+
361
+ /**
362
+ * Unreal's colour grading and white balance, run in the combined LUT before the film curve
363
+ * (`Engine/Shaders/Private/PostProcessCombineLUTs.usf:88-140` and `:369-403`; defaults in
364
+ * `Engine/Source/Runtime/Engine/Private/Scene.cpp:405-433`). Every default below is Unreal's, and at the
365
+ * defaults none of it costs a shader instruction.
366
+ */
367
+ export interface IColorGrade {
368
+ /** Kelvin, 1500 to 15000. 6500 with tint 0 is a no-op. */
369
+ readonly whiteTemp: number;
370
+ /** -1 to 1 along the isotherm. */
371
+ readonly whiteTint: number;
372
+ /**
373
+ * `"whiteBalance"`: the temperature is the light the scene was lit by, and it turns neutral.
374
+ * `"colorTemperature"`: neutral turns into that temperature.
375
+ */
376
+ readonly temperatureMode: "whiteBalance" | "colorTemperature";
377
+ /** 1 is the full film curve, 0 the graded colour with no curve. */
378
+ readonly toneCurveAmount: number;
379
+ /** Applied to every pixel, and combined with each range below. */
380
+ readonly global: IGradeControls;
381
+ readonly shadows: IGradeControls;
382
+ readonly midtones: IGradeControls;
383
+ readonly highlights: IGradeControls;
384
+ /** Luma (AP1) up to which the shadows range has full weight, fading out by here. */
385
+ readonly shadowsMax: number;
386
+ /** Luma where the highlights range starts and where it has full weight. */
387
+ readonly highlightsMin: number;
388
+ readonly highlightsMax: number;
389
+ }
390
+
391
+ const ONES: Vec4 = [1, 1, 1, 1];
392
+ const ZEROS: Vec4 = [0, 0, 0, 0];
393
+ const NEUTRAL_CONTROLS: IGradeControls = {
394
+ saturation: ONES,
395
+ contrast: ONES,
396
+ gamma: ONES,
397
+ gain: ONES,
398
+ offset: ZEROS,
399
+ };
400
+
401
+ /** Unreal 5.8.3 project defaults: a neutral grade. */
402
+ export const COLOR_GRADE: IColorGrade = {
403
+ whiteTemp: 6500,
404
+ whiteTint: 0,
405
+ temperatureMode: "whiteBalance",
406
+ toneCurveAmount: 1,
407
+ global: NEUTRAL_CONTROLS,
408
+ shadows: NEUTRAL_CONTROLS,
409
+ midtones: NEUTRAL_CONTROLS,
410
+ highlights: NEUTRAL_CONTROLS,
411
+ shadowsMax: 0.09,
412
+ highlightsMin: 0.5,
413
+ highlightsMax: 1,
414
+ };
415
+
416
+ type RangeName = "global" | "shadows" | "midtones" | "highlights";
417
+ const RANGES: readonly RangeName[] = ["global", "shadows", "midtones", "highlights"];
418
+ const CONTROLS = ["saturation", "contrast", "gamma", "gain", "offset"] as const;
419
+
420
+ /** What a game passes: any field, and any control of a range. */
421
+ export type ColorGradeOptions = {
422
+ readonly [K in keyof IColorGrade]?: K extends RangeName
423
+ ? Partial<IGradeControls>
424
+ : IColorGrade[K];
425
+ };
426
+
427
+ /** Refuses a value Unreal's panel would not allow. */
428
+ function validateGrade(g: IColorGrade): void {
429
+ if (!(g.whiteTemp >= 1500 && g.whiteTemp <= 15000)) {
430
+ throw new Error(`colorGrade.whiteTemp must be 1500 to 15000 K, got ${g.whiteTemp}.`);
431
+ }
432
+ if (!(Math.abs(g.whiteTint) <= 1))
433
+ throw new Error(`colorGrade.whiteTint must be -1 to 1, got ${g.whiteTint}.`);
434
+ if (g.temperatureMode !== "whiteBalance" && g.temperatureMode !== "colorTemperature") {
435
+ throw new Error(`colorGrade.temperatureMode must be "whiteBalance" or "colorTemperature".`);
436
+ }
437
+ if (!(g.toneCurveAmount >= 0 && g.toneCurveAmount <= 1)) {
438
+ throw new Error(`colorGrade.toneCurveAmount must be 0 to 1, got ${g.toneCurveAmount}.`);
439
+ }
440
+ if (!(g.shadowsMax > 0) || !(g.highlightsMin < g.highlightsMax)) {
441
+ throw new Error("colorGrade needs shadowsMax > 0 and highlightsMin < highlightsMax.");
442
+ }
443
+ }
444
+
445
+ /** Fills the defaults and refuses a malformed control, so a typo cannot pass as a neutral grade. */
446
+ export function resolveColorGrade(options: ColorGradeOptions = {}): IColorGrade {
447
+ const out: Record<string, unknown> = { ...COLOR_GRADE, ...options };
448
+ for (const range of RANGES) {
449
+ const given = (options[range] ?? {}) as Partial<IGradeControls>;
450
+ const merged: Record<string, Vec4> = {};
451
+ for (const name of CONTROLS) {
452
+ const v = given[name] ?? NEUTRAL_CONTROLS[name];
453
+ if (v.length !== 4 || !v.every(Number.isFinite)) {
454
+ throw new Error(
455
+ `colorGrade.${range}.${name} needs [red, green, blue, master], got ${JSON.stringify(v)}.`,
456
+ );
457
+ }
458
+ merged[name] = v;
459
+ }
460
+ out[range] = merged;
461
+ }
462
+ const g = out as Record<string, unknown> & IColorGrade;
463
+ validateGrade(g);
464
+ return g;
465
+ }
466
+
467
+ const same = (a: readonly number[], b: readonly number[]): boolean => a.every((v, i) => v === b[i]);
468
+ const neutralControls = (k: IGradeControls): boolean =>
469
+ CONTROLS.every((name) => same(k[name], NEUTRAL_CONTROLS[name]));
470
+ const whiteBalanceActive = (g: IColorGrade): boolean =>
471
+ Math.abs(g.whiteTemp - 6500) > 1e-8 || Math.abs(g.whiteTint) > 1e-8;
472
+ const gradingActive = (g: IColorGrade): boolean => RANGES.some((r) => !neutralControls(g[r]));
473
+ const rangesActive = (g: IColorGrade): boolean =>
474
+ !neutralControls(g.shadows) || !neutralControls(g.midtones) || !neutralControls(g.highlights);
475
+
476
+ /** True when the grade changes nothing, so the tone node emits no grade instruction. */
477
+ export function colorGradeIsIdentity(g: IColorGrade): boolean {
478
+ return !whiteBalanceActive(g) && !gradingActive(g) && g.toneCurveAmount === 1;
479
+ }
480
+
481
+ // ---- White balance: Planckian locus below 4000 K, daylight locus above, Bradford adaptation. ----
482
+ const SRGB_TO_XYZ: Mat3 = [
483
+ 0.4123907993, 0.3575843394, 0.1804807884, 0.2126390059, 0.7151686788, 0.0721923154, 0.0193308187,
484
+ 0.1191947798, 0.9505321522,
485
+ ];
486
+ const XYZ_TO_SRGB: Mat3 = [
487
+ 3.2409699419, -1.5373831776, -0.4986107603, -0.9692436363, 1.8759675015, 0.0415550574,
488
+ 0.0556300797, -0.2039769589, 1.0569715142,
489
+ ];
490
+ const BRADFORD: Mat3 = [0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296];
491
+ const BRADFORD_INVERSE: Mat3 = [
492
+ 0.9869929, -0.1470543, 0.1599627, 0.4323053, 0.5183603, 0.0492912, -0.0085287, 0.0400428,
493
+ 0.9684867,
494
+ ];
495
+ const D65_XY: readonly [number, number] = [0.3127, 0.329];
496
+
497
+ function matMul(a: Mat3, b: Mat3): Mat3 {
498
+ const out: number[] = [];
499
+ for (let r = 0; r < 3; r++) {
500
+ for (let c = 0; c < 3; c++) {
501
+ out.push(
502
+ at(a, r * 3) * at(b, c) + at(a, r * 3 + 1) * at(b, 3 + c) + at(a, r * 3 + 2) * at(b, 6 + c),
503
+ );
504
+ }
505
+ }
506
+ return out as number[] & Mat3;
507
+ }
508
+
509
+ /** Krystek's rational fit of the Planckian locus in CIE 1960 (u, v) [Krystek 1985], 1000 to 15000 K. */
510
+ function planckianUv(t: number): [number, number] {
511
+ const u =
512
+ (0.860117757 + 1.54118254e-4 * t + 1.28641212e-7 * t * t) /
513
+ (1 + 8.42420235e-4 * t + 7.08145163e-7 * t * t);
514
+ const v =
515
+ (0.317398726 + 4.22806245e-5 * t + 4.20481691e-8 * t * t) /
516
+ (1 - 2.89741816e-5 * t + 1.61456053e-7 * t * t);
517
+ return [u, v];
518
+ }
519
+
520
+ function uvToXy([u, v]: readonly [number, number]): [number, number] {
521
+ const d = 2 * u - 8 * v + 4;
522
+ return [(3 * u) / d, (2 * v) / d];
523
+ }
524
+
525
+ /** CIE daylight locus chromaticity. The 1.4388 / 1.438 factor corrects Planck's constant, so 6500 K is D65. */
526
+ function daylightXy(kelvin: number): [number, number] {
527
+ const inv = 1 / (kelvin * (1.4388 / 1.438));
528
+ const x =
529
+ kelvin * (1.4388 / 1.438) <= 7000
530
+ ? 0.244063 + (0.09911e3 + (2.9678e6 - 4.607e9 * inv) * inv) * inv
531
+ : 0.23704 + (0.24748e3 + (1.9018e6 - 2.0064e9 * inv) * inv) * inv;
532
+ return [x, -3 * x * x + 2.87 * x - 0.275];
533
+ }
534
+
535
+ /** The Planckian chromaticity moved along its isotherm by `tint`, up to 0.05 in (u, v). */
536
+ function isothermXy(t: number, tint: number): [number, number] {
537
+ const [u, v] = planckianUv(t);
538
+ const ud =
539
+ (-1.13758118e9 - 1.91615621e6 * t - 1.53177 * t * t) /
540
+ (1.41213984e6 + 1189.62 * t + t * t) ** 2;
541
+ const vd =
542
+ (1.97471536e9 - 705674 * t - 308.607 * t * t) / (6.19363586e6 - 179.456 * t + t * t) ** 2;
543
+ const n = Math.hypot(ud, vd);
544
+ return uvToXy([u + (vd / n) * tint * 0.05, v - (ud / n) * tint * 0.05]);
545
+ }
546
+
547
+ /** The 3x3 on scene-linear sRGB that Unreal's white balance applies (Bradford von Kries). */
548
+ export function whiteBalanceMatrix(g: IColorGrade): Mat3 {
549
+ const locus = uvToXy(planckianUv(g.whiteTemp));
550
+ const white = g.whiteTemp < 4000 ? locus : daylightXy(g.whiteTemp);
551
+ const iso = isothermXy(g.whiteTemp, g.whiteTint);
552
+ const lit: [number, number] = [white[0] + iso[0] - locus[0], white[1] + iso[1] - locus[1]];
553
+ const [from, to] = g.temperatureMode === "whiteBalance" ? [lit, D65_XY] : [D65_XY, lit];
554
+ const cone = (xy: readonly [number, number]): Vec3 =>
555
+ multiply(BRADFORD, [xy[0] / xy[1], 1, (1 - xy[0] - xy[1]) / xy[1]]);
556
+ const [a, b] = [cone(from), cone(to)];
557
+ const scale: Mat3 = [b[0] / a[0], 0, 0, 0, b[1] / a[1], 0, 0, 0, b[2] / a[2]];
558
+ return matMul(
559
+ XYZ_TO_SRGB,
560
+ matMul(BRADFORD_INVERSE, matMul(scale, matMul(BRADFORD, SRGB_TO_XYZ))),
561
+ );
562
+ }
563
+
564
+ // ---- Colour grading, in AP1 (Nuke-style, shadows / midtones / highlights by luma). ----
565
+ interface IEffective {
566
+ readonly saturation: Vec3;
567
+ readonly contrast: Vec3;
568
+ readonly gamma: Vec3;
569
+ readonly gain: Vec3;
570
+ readonly offset: Vec3;
571
+ }
572
+ const channels = (f: (i: number) => number): Vec3 => [f(0), f(1), f(2)];
573
+
574
+ /** One range with the global controls: vectors multiply (master included), offsets add. */
575
+ function effective(range: IGradeControls, global: IGradeControls): IEffective {
576
+ const product = (name: "saturation" | "contrast" | "gamma" | "gain"): Vec3 => {
577
+ const w = range[name][3] * global[name][3];
578
+ return channels((i) => at(range[name], i) * at(global[name], i) * w);
579
+ };
580
+ const offset = range.offset[3] + global.offset[3];
581
+ return {
582
+ saturation: product("saturation"),
583
+ contrast: product("contrast"),
584
+ gamma: product("gamma"),
585
+ gain: product("gain"),
586
+ offset: channels((i) => at(range.offset, i) + at(global.offset, i) + offset),
587
+ };
588
+ }
589
+
590
+ const smoothstep = (lo: number, hi: number, x: number): number => {
591
+ const t = Math.min(1, Math.max(0, (x - lo) / (hi - lo)));
592
+ return t * t * (3 - 2 * t);
593
+ };
594
+ const ap1Luma = (v: Vec3): number => v[0] * AP1_LUMA[0] + v[1] * AP1_LUMA[1] + v[2] * AP1_LUMA[2];
595
+
596
+ function correct(v: Vec3, e: IEffective): Vec3 {
597
+ const y = ap1Luma(v);
598
+ return channels((i) => {
599
+ const saturated = Math.max(0, y + (at(v, i) - y) * at(e.saturation, i));
600
+ const contrasted = Math.max(saturated / MID_GREY, 1e-10) ** at(e.contrast, i) * MID_GREY;
601
+ return contrasted ** (1 / at(e.gamma, i)) * at(e.gain, i) + at(e.offset, i);
602
+ });
603
+ }
604
+
605
+ function correctAll(v: Vec3, g: IColorGrade): Vec3 {
606
+ if (!rangesActive(g)) return correct(v, effective(g.global, NEUTRAL_CONTROLS));
607
+ const y = ap1Luma(v);
608
+ const shadows = 1 - smoothstep(0, g.shadowsMax, y);
609
+ const highlights = smoothstep(g.highlightsMin, g.highlightsMax, y);
610
+ const s = correct(v, effective(g.shadows, g.global));
611
+ const m = correct(v, effective(g.midtones, g.global));
612
+ const h = correct(v, effective(g.highlights, g.global));
613
+ return channels(
614
+ (i) => at(s, i) * shadows + at(m, i) * (1 - shadows - highlights) + at(h, i) * highlights,
615
+ );
616
+ }
617
+
618
+ /** Scene-linear sRGB in, display-linear sRGB out (before the sRGB transfer), on plain numbers. */
619
+ export function filmicToneMap(
620
+ rgb: readonly [number, number, number],
621
+ exposure = 1,
622
+ c: IFilmicCurve = FILMIC_CURVE,
623
+ grade: IColorGrade = COLOR_GRADE,
624
+ ): [number, number, number] {
625
+ const exposed = rgb.map((v) => Math.max(0, v * exposure)) as number[] & Vec3;
626
+ const lit =
627
+ c.lutClip > 0 ? (exposed.map((v) => Math.min(v, c.lutClip)) as number[] & Vec3) : exposed;
628
+ const balanced = whiteBalanceActive(grade) ? multiply(whiteBalanceMatrix(grade), lit) : lit;
629
+ let ap1: Vec3 = multiply(SRGB_TO_AP1, balanced);
630
+ // Order: Engine/Shaders/Private/PostProcessCombineLUTs.usf and TonemapCommon.ush.
631
+ if (c.expandGamut !== 0) ap1 = expandAp1(ap1, c.expandGamut);
632
+ if (gradingActive(grade)) ap1 = correctAll(ap1, grade);
633
+ if (c.blueCorrection !== 0) ap1 = correctBlue(ap1, BLUE_CORRECTION_AP1, c.blueCorrection);
634
+ const corrected = ap1;
635
+ if (c.glow !== 0 || c.redModifier !== 0) ap1 = glowAndRed(ap1, c.glow, c.redModifier);
636
+ const pre = saturate(ap1.map((v) => Math.max(0, v)) as number[] & Vec3, PRE_SATURATION);
637
+ let toned: Vec3 = saturate(
638
+ [filmicCurve(pre[0], c), filmicCurve(pre[1], c), filmicCurve(pre[2], c)],
639
+ POST_SATURATION,
640
+ );
641
+ if (grade.toneCurveAmount !== 1) {
642
+ toned = channels(
643
+ (i) => at(corrected, i) + (at(toned, i) - at(corrected, i)) * grade.toneCurveAmount,
644
+ );
645
+ }
646
+ const restored =
647
+ c.blueCorrection === 0
648
+ ? toned
649
+ : correctBlue(toned, BLUE_CORRECTION_INVERSE_AP1, c.blueCorrection);
650
+ const [x, y, z] = multiply(AP1_TO_SRGB, restored);
651
+ const unit = (v: number): number => Math.min(1, Math.max(0, v));
652
+ return [unit(x), unit(y), unit(z)];
653
+ }
654
+
655
+ /** One 8-bit step of display value. */
656
+ const EIGHT_BIT_STEP = 1 / 255;
657
+ const blend3 = (a: Node<"vec3">, b: Node<"vec3">, w: Node<"vec3">) => a.add(b.sub(a).mul(w));
658
+ const toDisplay = (c: Node<"vec3">) =>
659
+ blend3(
660
+ c.mul(12.92),
661
+ c
662
+ .pow(1 / 2.4)
663
+ .mul(1.055)
664
+ .sub(0.055),
665
+ step(vec3(0.0031308), c),
666
+ );
667
+ const toLinear = (v: Node<"vec3">) =>
668
+ blend3(v.div(12.92), v.add(0.055).div(1.055).pow(2.4), step(vec3(0.04045), v));
669
+
670
+ /**
671
+ * Triangular grain, `steps` 8-bit steps wide, added in display space. Unreal 5.8.3 does this to its 8-bit output
672
+ * (`Engine/Shaders/Private/PostProcessTonemap.usf`, scaled by `BackbufferQuantizationDithering` in
673
+ * `Engine/Source/Runtime/Renderer/Private/PostProcess/PostProcessTonemap.cpp`). The pipeline applies the sRGB
674
+ * transfer after this node, so the grain goes in on the display value and the result comes back to linear.
675
+ * The shape is Unreal's triangle on [-1, 1]. The hash is white noise of the pixel position, with the sine
676
+ * argument kept under pi. Unreal's grain moves every frame; this one stays on its pixel, so two captures of
677
+ * one frame match bit for bit. The hash reads the pixel position: `screenUV` gave no grain in this stage on
678
+ * the owned engine.
679
+ */
680
+ function dithered(linear: Node<"vec3">, steps: number): Node<"vec3"> {
681
+ const uniform = dot(screenCoordinate, vec2(12.9898, 78.233))
682
+ .mod(Math.PI)
683
+ .sin()
684
+ .mul(43758.5453)
685
+ .fract();
686
+ // The inverse of the triangular CDF: one root for each half of the unit interval.
687
+ const grain = mix(
688
+ uniform.mul(2).sqrt().sub(1),
689
+ float(1).sub(float(2).sub(uniform.mul(2)).sqrt()),
690
+ step(0.5, uniform),
691
+ );
692
+ return toLinear(clamp(toDisplay(linear).add(grain.mul(steps * EIGHT_BIT_STEP)), 0, 1));
693
+ }
694
+
695
+ // One dot product per row: no row- or column-major convention to get wrong.
696
+ const applyMatrix = (m: Mat3, v: Node<"vec3">) =>
697
+ vec3(
698
+ dot(vec3(m[0], m[1], m[2]), v),
699
+ dot(vec3(m[3], m[4], m[5]), v),
700
+ dot(vec3(m[6], m[7], m[8]), v),
701
+ );
702
+
703
+ /** The glow and the red modifier on an AP1 colour, as TSL. */
704
+ function glowAndRedNode(ap1: Node<"vec3">, c: IFilmicCurve): Node<"vec3"> {
705
+ const apply = applyMatrix;
706
+ // The same maths as glowAndRed() above, in AP0. The hue's x argument carries a 1e-10 so a grey stays defined.
707
+ const ap0 = apply(AP1_TO_AP0, ap1);
708
+ const [r, g, b] = [ap0.x, ap0.y, ap0.z];
709
+ const high = max(max(r, g), b);
710
+ const saturation = max(high, 1e-10)
711
+ .sub(max(min(min(r, g), b), 1e-10))
712
+ .div(max(high, 1e-2));
713
+ const spread = r.mul(r).add(g.mul(g)).add(b.mul(b)).sub(r.mul(g)).sub(g.mul(b)).sub(b.mul(r));
714
+ const brightness = r
715
+ .add(g)
716
+ .add(b)
717
+ .add(sqrt(max(spread, 0)).mul(1.75))
718
+ .div(3);
719
+ const x = saturation.sub(0.4).div(0.2);
720
+ const tail = max(float(1).sub(abs(x.div(2))), 0);
721
+ const shaper = float(1)
722
+ .add(sign(x).mul(float(1).sub(tail.mul(tail))))
723
+ .div(2);
724
+ const fade = clamp(float(GLOW_MID).div(max(brightness, 1e-10)).sub(0.5), 0, 1);
725
+ const lifted = ap0.mul(
726
+ shaper
727
+ .mul(fade)
728
+ .mul(c.glow * GLOW_GAIN)
729
+ .add(1),
730
+ );
731
+ const hue = atan(
732
+ lifted.y.sub(lifted.z).mul(Math.sqrt(3)),
733
+ lifted.x.mul(2).sub(lifted.y).sub(lifted.z).add(1e-10),
734
+ );
735
+ const edge = clamp(float(1).sub(abs(hue.mul(2 / RED_WIDTH))), 0, 1);
736
+ const smooth = edge.mul(edge).mul(edge.mul(-2).add(3));
737
+ const pulled = lifted.x.add(
738
+ smooth
739
+ .mul(smooth)
740
+ .mul(saturation)
741
+ .mul(float(RED_PIVOT).sub(lifted.x))
742
+ .mul(c.redModifier * (1 - RED_SCALE)),
743
+ );
744
+ return apply(AP0_TO_AP1_ROWS, vec3(pulled, lifted.y, lifted.z));
745
+ }
746
+
747
+ /** Pre-desaturation and the film curve on an AP1 colour, as TSL; the colour comes back before the post desaturation. */
748
+ function curveNode(ap1: Node<"vec3">, c: IFilmicCurve): Node<"vec3"> {
749
+ const m = curveMatches(c);
750
+ const luma = vec3(...AP1_LUMA);
751
+ const pre = mix(vec3(dot(max(ap1, vec3(0)), luma)), max(ap1, vec3(0)), PRE_SATURATION);
752
+ const logValue = log(max(pre, vec3(1e-10))).div(LOG10);
753
+ const straight = logValue.add(m.straightMatch).mul(c.slope);
754
+ const toeCurve = vec3(-c.blackClip).add(
755
+ vec3(2 * m.toeScale).div(exp(logValue.sub(m.toeMatch).mul((-2 * c.slope) / m.toeScale)).add(1)),
756
+ );
757
+ const shoulderCurve = vec3(1 + c.whiteClip).sub(
758
+ vec3(2 * m.shoulderScale).div(
759
+ exp(logValue.sub(m.shoulderMatch).mul((2 * c.slope) / m.shoulderScale)).add(1),
760
+ ),
761
+ );
762
+ // Per channel: the sigmoid below the toe match, the line above it; and the mirror for the
763
+ // shoulder. step() is the vector form of the comparison; mix() takes only a scalar weight.
764
+ const blend = (a: Node<"vec3">, b: Node<"vec3">, w: Node<"vec3">) => a.add(b.sub(a).mul(w));
765
+ const toe = blend(toeCurve, straight, step(vec3(m.toeMatch), logValue));
766
+ const shoulder = blend(straight, shoulderCurve, step(vec3(m.shoulderMatch), logValue));
767
+ const linear = clamp(logValue.sub(m.toeMatch).div(m.shoulderMatch - m.toeMatch), 0, 1);
768
+ const t = m.shoulderMatch < m.toeMatch ? linear.oneMinus() : linear;
769
+ const toned = blend(toe, shoulder, t.mul(t).mul(t.mul(-2).add(3)));
770
+ return toned;
771
+ }
772
+
773
+ /** The same curve as a TSL tone-mapping function, `(color, exposure) => color`. */
774
+ export function filmicToneMappingNode(
775
+ c: IFilmicCurve = FILMIC_CURVE,
776
+ grade: IColorGrade = COLOR_GRADE,
777
+ ): (color: Node<"vec3">, exposure: Node<"float">) => Node<"vec3"> {
778
+ const apply = applyMatrix;
779
+ const luma = vec3(...AP1_LUMA);
780
+ // The grade is constants, so every vector below is built once, and a control at its default adds no node.
781
+ const toAp1 = whiteBalanceActive(grade)
782
+ ? matMul(SRGB_TO_AP1, whiteBalanceMatrix(grade))
783
+ : SRGB_TO_AP1;
784
+ const correctNode = (v: Node<"vec3">, e: IEffective): Node<"vec3"> => {
785
+ const y = dot(v, luma);
786
+ const saturated = max(y.add(v.sub(y).mul(vec3(...e.saturation))), vec3(0));
787
+ const contrasted = pow(max(saturated.div(MID_GREY), vec3(1e-10)), vec3(...e.contrast)).mul(
788
+ MID_GREY,
789
+ );
790
+ return pow(contrasted, vec3(1).div(vec3(...e.gamma)))
791
+ .mul(vec3(...e.gain))
792
+ .add(vec3(...e.offset));
793
+ };
794
+ const smoothstepNode = (lo: number, hi: number, x: Node<"float">) => {
795
+ const t = clamp(x.sub(lo).div(hi - lo), 0, 1);
796
+ return t.mul(t).mul(t.mul(-2).add(3));
797
+ };
798
+ const gradeNode = (v: Node<"vec3">): Node<"vec3"> => {
799
+ if (!rangesActive(grade)) return correctNode(v, effective(grade.global, NEUTRAL_CONTROLS));
800
+ const y = dot(v, luma);
801
+ const shadows = float(1).sub(smoothstepNode(0, grade.shadowsMax, y));
802
+ const highlights = smoothstepNode(grade.highlightsMin, grade.highlightsMax, y);
803
+ const middle = float(1).sub(shadows).sub(highlights);
804
+ return correctNode(v, effective(grade.shadows, grade.global))
805
+ .mul(shadows)
806
+ .add(correctNode(v, effective(grade.midtones, grade.global)).mul(middle))
807
+ .add(correctNode(v, effective(grade.highlights, grade.global)).mul(highlights));
808
+ };
809
+ return (color, exposure) => {
810
+ let lit: Node<"vec3"> = max(color.mul(exposure), vec3(0));
811
+ if (c.lutClip > 0) lit = min(lit, vec3(c.lutClip));
812
+ let ap1: Node<"vec3"> = apply(toAp1, lit);
813
+ if (c.expandGamut !== 0) {
814
+ const luma = max(dot(ap1, vec3(...AP1_LUMA)), 1e-10);
815
+ const chroma = ap1.div(luma).sub(1);
816
+ const amount = float(1)
817
+ .sub(exp2(dot(chroma, chroma).mul(-4)))
818
+ .mul(float(1).sub(exp2(luma.mul(luma).mul(-4 * c.expandGamut))));
819
+ ap1 = mix(ap1, apply(EXPAND_AP1, ap1), amount);
820
+ }
821
+ if (gradingActive(grade)) ap1 = gradeNode(ap1);
822
+ if (c.blueCorrection !== 0) ap1 = mix(ap1, apply(BLUE_CORRECTION_AP1, ap1), c.blueCorrection);
823
+ const corrected = ap1;
824
+ if (c.glow !== 0 || c.redModifier !== 0) ap1 = glowAndRedNode(ap1, c);
825
+ const toned = curveNode(ap1, c);
826
+ const filmed = mix(vec3(dot(toned, luma)), toned, POST_SATURATION);
827
+ const post =
828
+ grade.toneCurveAmount === 1 ? filmed : mix(corrected, filmed, grade.toneCurveAmount);
829
+ const restored =
830
+ c.blueCorrection === 0
831
+ ? post
832
+ : mix(post, apply(BLUE_CORRECTION_INVERSE_AP1, post), c.blueCorrection);
833
+ const display = clamp(apply(AP1_TO_SRGB, restored), 0, 1);
834
+ return c.dither === 0 ? display : dithered(display, c.dither);
835
+ };
836
+ }
837
+
838
+ /**
839
+ * Registers the curve with a WebGPU renderer and returns the tone-mapping constant to assign.
840
+ * A renderer without a node library (the WebGL fallback) keeps ACES and says so.
841
+ */
842
+ export function installFilmicToneMapping(
843
+ raw: unknown,
844
+ c: IFilmicCurve = FILMIC_CURVE,
845
+ grade: IColorGrade = COLOR_GRADE,
846
+ ): number | undefined {
847
+ const library = (raw as { library?: { addToneMapping?(node: unknown, mode: number): void } })
848
+ .library;
849
+ if (library?.addToneMapping === undefined) return undefined;
850
+ library.addToneMapping(filmicToneMappingNode(c, grade), CustomToneMapping);
851
+ return CustomToneMapping;
852
+ }