Skip to main content

three_rs/nodes/
tsl.rs

1//! Port of `three.js/src/nodes/tsl/` plus the accessor modules TSL re-exports
2//! (`Position`, `Normal`, `Camera`, `Object3DNode`, `MaterialNode`, `UV`,
3//! `TextureNode`, `Oscillators`, `ColorAdjustment`, …).
4//!
5//! JS property access becomes a method call (`.rgb()`, `.x()`), and the
6//! accessor singletons become zero-argument functions, so ported example code
7//! still reads like the original:
8//!
9//! ```ignore
10//! hue(saturation(tex.rgb(), mouse.x().one_minus()), mouse.y())
11//! ```
12
13use std::cell::RefCell;
14use std::collections::HashMap;
15use std::rc::Rc;
16
17use super::builder::{current_context, push_context};
18use super::node::{
19    BufferNode, BufferSource, Builtin, ContextValue, CustomNode, FnDef, InstanceBuffer, Lazy,
20    LiveValue, Node, NodeRef, Object3DScope, SampleMode, SettableValue, Type, UniformGroup,
21    UniformNode, UniformSource, VarDef, VaryingDef,
22};
23use crate::materials::{MeshBasicNodeMaterial, Side};
24use crate::math::{Color, Matrix3};
25use crate::textures::{
26    CubeDepthTexture, CubeTexture, DataArrayTexture, DataTexture, DepthTexture, Texture,
27};
28
29pub use super::node::TextureSource;
30
31mod depth_aware_blur;
32mod gpgpu;
33mod lighting;
34mod rnoise;
35mod specular_helpers;
36mod utils;
37mod wrappers;
38pub use depth_aware_blur::depth_aware_blur;
39pub use gpgpu::*;
40pub use lighting::*;
41pub use rnoise::*;
42pub use specular_helpers::*;
43pub use utils::*;
44pub use wrappers::*;
45
46// ---------------------------------------------------------------------------
47// sub-builds and the build context (`docs/nodes.md` §7)
48// ---------------------------------------------------------------------------
49
50/// Cache key shared by every cache below that holds a node reading
51/// `normalView`: `(sub_build_layer, normal_value_id, flat_shading,
52/// material_side)`. The flat-shading flag belongs in it because
53/// `normalViewGeometry` reads it and `negateOnBackSide()` is skipped when it
54/// is set, so two materials that differ only there must not share a cached
55/// node; the side is there for the same reason. The fifth flag is
56/// `builder.geometry.hasAttribute( 'tangent' )`, which picks the attribute
57/// tangent frame over the derivative one.
58type NormalViewKey = (
59    Option<&'static str>,
60    Option<usize>,
61    bool,
62    Side,
63    bool,
64    Option<usize>,
65);
66
67/// `overrideNodes( [ [ target, value ], … ] )` — `OverrideContextNode.js`.
68///
69/// Three keys the overrides on the *node objects* `positionView`,
70/// `positionViewDirection` and `normalView`, and `Node.getShared()` swaps the
71/// replacement in the first time the build reaches one, so every later use is
72/// the replacement inlined. This port's TSL is eager and those three accessors
73/// are functions, so the map is a struct of the three the ladder needs and the
74/// accessors read it directly. See `docs/nodes.md` §27.
75#[derive(Clone, Debug, Default)]
76#[non_exhaustive]
77pub struct OverrideNodes {
78    /// Replaces `positionView` for the material's whole setup.
79    pub position_view: Option<NodeRef>,
80    /// Replaces `positionViewDirection` for the material's whole setup.
81    pub position_view_direction: Option<NodeRef>,
82    /// Replaces `normalView` for the material's whole setup.
83    pub normal_view: Option<NodeRef>,
84}
85
86impl std::hash::Hash for OverrideNodes {
87    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
88        for node in [
89            &self.position_view,
90            &self.position_view_direction,
91            &self.normal_view,
92        ] {
93            node.as_ref().map(|n| n.key()).hash(state);
94        }
95    }
96}
97
98/// Install an [`OverrideNodes`] for the duration of one material's setup —
99/// `renderer.contextNode` / `material.contextNode` in three, which live for
100/// exactly that long.
101pub(crate) fn with_override_nodes<R>(
102    overrides: Option<&OverrideNodes>,
103    f: impl FnOnce() -> R,
104) -> R {
105    let _overrides = push_context(|cx| cx.override_nodes = overrides.cloned());
106    f()
107}
108
109/// The override for one of the three accessors, or `None` outside an override
110/// context.
111fn override_node(pick: fn(&OverrideNodes) -> &Option<NodeRef>) -> Option<NodeRef> {
112    current_context(|cx| cx.override_nodes.as_ref().and_then(|o| pick(o).clone()))
113}
114
115thread_local! {
116    /// `normalViewGeometry`'s node per flat-shading flag — the stand-in for
117    /// three.js' per-build `nodeData`, which gives the two forms of the
118    /// accessor's `Fn( … ).once()` separate cache entries.
119    static NORMAL_VIEW_GEOMETRY: RefCell<HashMap<bool, NodeRef>> = RefCell::new(HashMap::new());
120    /// `normalView`'s node per (layer, normal value) — the stand-in for
121    /// three.js' per-build `nodeData` plus its `subBuildsCache`.
122    static NORMAL_VIEW: RefCell<HashMap<NormalViewKey, NodeRef>> =
123        RefCell::new(HashMap::new());
124    /// `tangentView` / `bitangentView`, keyed the same way.
125    static TANGENT_VIEW: RefCell<HashMap<NormalViewKey, (NodeRef, NodeRef)>> =
126        RefCell::new(HashMap::new());
127    /// `normalWorld`, keyed the same way: it reads `normalView`, so a plain
128    /// singleton would bake in whichever material was built first and then
129    /// re-assign `normalView` from the geometric normal in every later one.
130    static NORMAL_WORLD: RefCell<HashMap<NormalViewKey, NodeRef>> =
131        RefCell::new(HashMap::new());
132    /// `positionView` / `modelViewProjection` per context value — three.js' own
133    /// `Fn( … ).once()` cache is per build, so a second material in the same
134    /// process must not inherit the first one's node.
135    static POSITION_VIEW: RefCell<HashMap<Option<usize>, (NodeRef, NodeRef)>> =
136        RefCell::new(HashMap::new());
137}
138
139/// `NodeBuilder.getSubBuildProperty( name )`: inside a layer a var's name is
140/// prefixed with the layer's, which is where `NORMAL_normalView` comes from.
141fn sub_build_name(name: &str) -> String {
142    match current_context(|cx| cx.sub_build) {
143        Some(layer) => format!("{layer}_{name}"),
144        None => name.to_string(),
145    }
146}
147
148/// `context( node, { … } )` — `ContextNode.js`. `node` is built with
149/// `value`'s keys merged into `builder.context`, and the keys in force before
150/// are restored after it.
151///
152/// What reads the keys is whatever is *set up* while `node` is being built: an
153/// inlined `Fn()`'s body ([`range_fog_factor`] reads `getViewZ`) or a
154/// [`CustomNode::setup`]. A node already built when `context` is called was
155/// set up under the context of its own construction, as a JS node that has
156/// already been built once keeps its `nodeData`. See `docs/nodes.md` §45.
157pub fn context(node: impl Into<NodeRef>, value: ContextValue) -> NodeRef {
158    NodeRef::new(Node::Context {
159        node: node.into(),
160        value: Rc::new(value),
161    })
162}
163
164/// `replaceDefaultUV( callback, node )` — `ContextNode.js`: `node` built with
165/// `getUV` in the context, so that every texture tap in it that has no uv of
166/// its own reads `uv` instead of `uv()`.
167///
168/// The taps that honour it are the ones whose uv is decided when they are
169/// built, not when they are made: a [`CustomNode`] that asks
170/// `builder.context( "getUV" )` — the
171/// [`RetroPassNode`](crate::nodes::display::RetroPassNode)'s texture, which is
172/// what `webgpu_postprocessing_retro` wraps — and a [`texture`] call made
173/// inside one's `setup`. A tap already made, `pass( … )`'s among them, has its
174/// uv. Three's `callback` may be a function of the texture node; the port
175/// takes the uv itself, which is what `() => uv` amounts to. See
176/// `docs/nodes.md` §79.
177pub fn replace_default_uv(uv: impl Into<NodeRef>, node: impl Into<NodeRef>) -> NodeRef {
178    context(node, ContextValue::new().set("getUV", uv))
179}
180
181/// `isolate( node )` — `IsolateNode.js`: `node` is built in a `NodeCache` of
182/// its own whose parent is the current one. A node that the subgraph reaches
183/// for the first time is counted, set up and declared there, so the same node
184/// reached again outside is a stranger to it; a node already known outside
185/// is shared. `cache( node, false )`, the deprecated parentless form, is not
186/// ported.
187pub fn isolate(node: impl Into<NodeRef>) -> NodeRef {
188    NodeRef::new(Node::Isolate { node: node.into() })
189}
190
191/// `new MyNode( … )` for a [`CustomNode`] defined outside the crate.
192pub fn custom(node: impl CustomNode + 'static) -> NodeRef {
193    NodeRef::new(Node::Custom(Rc::new(node)))
194}
195
196/// `subBuild( node, name )` — build `f`'s nodes inside the named layer.
197fn in_sub_build<R>(layer: &'static str, f: impl FnOnce() -> R) -> R {
198    let _layer = push_context(|cx| cx.sub_build = Some(layer));
199    f()
200}
201
202/// Install the material's `normalNode` as `builder.context.setupNormal` for the
203/// duration of `f` — `NodeMaterial.setup()` does exactly this before flowing
204/// either stage. Returns what `f` returns.
205pub(crate) fn with_material_normal<R>(
206    normal: Option<NodeRef>,
207    flat_shading: bool,
208    side: Side,
209    f: impl FnOnce() -> R,
210) -> R {
211    let _material = push_context(|cx| {
212        cx.setup_normal = normal;
213        cx.flat_shading = flat_shading;
214        cx.material_side = side;
215    });
216    f()
217}
218
219/// `builder.geometry.hasAttribute( 'tangent' )` for the whole of one
220/// material's setup — installed at the top of `NodeMaterial.setup()`, because
221/// the material's own normal node is built before the flow starts and already
222/// reads the TBN frame.
223pub(crate) fn with_tangent_attribute<R>(has_tangent: bool, f: impl FnOnce() -> R) -> R {
224    let _tangent = push_context(|cx| cx.has_tangent = has_tangent);
225    f()
226}
227
228/// `builder.camera.isOrthographicCamera` for the whole of one material's
229/// setup. Three reads `builder.camera` directly; the port's flow is built
230/// before the builder exists, so the renderer hands the camera's kind down
231/// through `SetupContext::orthographic` and this installs it.
232pub(crate) fn with_orthographic_camera<R>(orthographic: bool, f: impl FnOnce() -> R) -> R {
233    let _camera = push_context(|cx| cx.orthographic_camera = orthographic);
234    f()
235}
236
237/// `builder.material.side` alone, for the window in which
238/// `NodeMaterial.setupNormal()` builds the material's normal node. three.js
239/// calls `setupNormal()` lazily from inside the build, so the side is already
240/// in scope there; the port builds the node up front and so has to open the
241/// scope explicitly, or a `DoubleSide` material's TBN frame would be built
242/// front-sided and then cached.
243pub(crate) fn with_material_side<R>(side: Side, f: impl FnOnce() -> R) -> R {
244    let _side = push_context(|cx| cx.material_side = side);
245    f()
246}
247
248/// `negateOnBackSide( vector )` — `FrontFacingNode.js`. A back-sided material
249/// inverts the vector outright; a double-sided one scales it by
250/// `faceDirection`, so only the back-facing fragments flip. `normalView` and
251/// the tangent frame both go through it, which is why a `DoubleSide` material's
252/// dump multiplies three vectors by the same `( f32( isFront ) * 2 - 1 )`.
253fn negate_on_back_side(vector: NodeRef) -> NodeRef {
254    match current_context(|cx| cx.material_side) {
255        Side::Front => vector,
256        Side::Back => vector.mul(float(-1.0)),
257        Side::Double => vector.mul(face_direction()),
258    }
259}
260
261/// `directionToFaceDirection( vector )` — `FrontFacingNode.js`, the r185
262/// deprecated name of `negateOnBackSide()`: `vector` as is for a front-sided
263/// material, negated for a back-sided one, and scaled by `faceDirection` for
264/// a double-sided one.
265///
266/// Three reads `builder.material.side` while it builds; the port builds the
267/// node before any material is in scope, so the caller passes the side
268/// (`docs/nodes.md` §68.3).
269pub fn direction_to_face_direction(vector: NodeRef, side: Side) -> NodeRef {
270    match side {
271        Side::Front => vector,
272        Side::Back => vector.mul(float(-1.0)),
273        Side::Double => vector.mul(face_direction()),
274    }
275}
276
277/// `builder.context.setupPositionView = () => this.setupPositionView( builder )`
278/// (`NodeMaterial.js:472`), installed for the whole of the material's setup.
279/// `SpriteNodeMaterial` is the only override the ladder needs, and it returns a
280/// **`vec4`** rather than the base class' `vec3`, which is why `v_positionView`
281/// is `vec4<f32>` in the galaxy dump.
282pub(crate) fn with_material_position_view<R>(value: Option<NodeRef>, f: impl FnOnce() -> R) -> R {
283    let _position_view = push_context(|cx| cx.setup_position_view = value);
284    f()
285}
286
287/// `positionView` and `modelViewProjection`, built together because both hang
288/// off the same `builder.context` entry.
289fn position_view_pair() -> (NodeRef, NodeRef) {
290    let value = current_context(|cx| cx.setup_position_view.clone());
291    let key = value.as_ref().map(|v| v.key());
292    if let Some(pair) = POSITION_VIEW.with(|m| m.borrow().get(&key).cloned()) {
293        return pair;
294    }
295    // `NodeMaterial.setupPositionView()`: `modelViewMatrix.mul( positionLocal ).xyz`.
296    let view = value.unwrap_or_else(|| {
297        model_view_matrix()
298            .mul(vec4_join(vec![position_local(), float(1.0)]))
299            .xyz()
300    });
301    let view = to_varying(Some("v_positionView"), view);
302    // `NodeMaterial.setupModelViewProjection()`.
303    let mvp = to_varying(
304        Some("v_modelViewProjection"),
305        camera_projection_matrix().mul(view.clone()),
306    );
307    let pair = (view, mvp);
308    POSITION_VIEW.with(|m| m.borrow_mut().insert(key, pair.clone()));
309    pair
310}
311
312// ---------------------------------------------------------------------------
313// constructors
314// ---------------------------------------------------------------------------
315
316fn constant(ty: Type, values: Vec<f64>) -> NodeRef {
317    NodeRef::new(Node::Const { ty, values })
318}
319
320/// `float( x )`.
321pub fn float(v: impl Into<f64>) -> NodeRef {
322    constant(Type::F32, vec![v.into()])
323}
324
325/// `int( x )`.
326pub fn int(v: i64) -> NodeRef {
327    constant(Type::I32, vec![v as f64])
328}
329
330/// `bool( v )` — a `true` / `false` literal.
331pub fn boolean(v: bool) -> NodeRef {
332    constant(Type::Bool, vec![f64::from(u8::from(v))])
333}
334
335/// `vec2( x, y )`.
336pub fn vec2(x: impl Into<f64>, y: impl Into<f64>) -> NodeRef {
337    constant(Type::Vec2, vec![x.into(), y.into()])
338}
339
340/// `vec3( x, y, z )`.
341pub fn vec3(x: impl Into<f64>, y: impl Into<f64>, z: impl Into<f64>) -> NodeRef {
342    constant(Type::Vec3, vec![x.into(), y.into(), z.into()])
343}
344
345/// `vec3( x )` — the splat form.
346pub fn vec3s(x: impl Into<f64>) -> NodeRef {
347    let x = x.into();
348    constant(Type::Vec3, vec![x, x, x])
349}
350
351/// `vec4( x, y, z, w )`.
352pub fn vec4(x: impl Into<f64>, y: impl Into<f64>, z: impl Into<f64>, w: impl Into<f64>) -> NodeRef {
353    constant(Type::Vec4, vec![x.into(), y.into(), z.into(), w.into()])
354}
355
356/// `vec4( node, w )` — `JoinNode`.
357pub fn join(ty: Type, args: Vec<NodeRef>) -> NodeRef {
358    NodeRef::new(Node::Join { args, ty })
359}
360
361/// `vec2( a, b )` — `JoinNode` into a `vec2`.
362pub fn vec2_join(args: Vec<NodeRef>) -> NodeRef {
363    join(Type::Vec2, args)
364}
365
366/// `vec3( a, b )` where the components add up: `vec3<f32>( x, yz )`.
367pub fn vec3_join(args: Vec<NodeRef>) -> NodeRef {
368    join(Type::Vec3, args)
369}
370
371/// `vec4( vec3Node, w )`.
372pub fn vec4_join(args: Vec<NodeRef>) -> NodeRef {
373    join(Type::Vec4, args)
374}
375
376/// `array( […] ).element( i )`'s array half — `QuadMesh`'s `vertexNode`.
377pub fn const_array(values: Vec<f64>) -> NodeRef {
378    NodeRef::new(Node::ConstArray {
379        element_ty: Type::F32,
380        values,
381    })
382}
383
384/// `array( [ vec2( … ), … ] )` — a literal array of vectors, `values` holding
385/// each element's components in turn. `depthAwareBlend`'s Poisson disk is the
386/// one user: `array< vec2<f32>, 8 >( vec2<f32>( 0.493393, 0.394269 ), … )`,
387/// indexed by a loop's `i` through [`NodeRef::element_node`].
388pub fn const_array_of(element_ty: Type, values: Vec<f64>) -> NodeRef {
389    assert_eq!(
390        values.len() % element_ty.components().max(1),
391        0,
392        "three-rs: const_array_of takes whole elements"
393    );
394    NodeRef::new(Node::ConstArray { element_ty, values })
395}
396
397/// `array( [ … ] )` held in a `var<private> nodeVarN : array< f32, N >`.
398///
399/// Three emits the same literal as [`const_array`] does, but a `TempNode` the
400/// flow reads more than once is promoted to a var, and `BloomNode`'s composite
401/// reads its five bloom factors five times (`dump/m11`). `Node::ArrayVar` is
402/// not a kind the builder promotes on its own, so — as with `radial_blur`'s
403/// result — the caller asks for the var.
404pub fn array_var(values: Vec<f64>) -> NodeRef {
405    NodeRef::new(Node::ArrayVar {
406        element_ty: Type::F32,
407        values,
408    })
409}
410
411/// `attribute( name, type )`.
412pub fn attribute(name: &'static str, ty: Type) -> NodeRef {
413    NodeRef::new(Node::Attribute { name, ty })
414}
415
416/// `uniform( value )` — a plain value uniform in the object group.
417pub fn uniform_value(ty: Type, values: Vec<f64>) -> NodeRef {
418    uniform(UniformSource::Value(values), ty, UniformGroup::Object, None)
419}
420
421/// `uniform( value )` whose value can be written between draws:
422/// `SSAAPassNode`'s `this.sampleWeight.value = …`. The returned cell is the
423/// handle; the node is the graph's view of it and never changes identity, so
424/// the eight accumulation draws of a frame share one program.
425pub fn uniform_settable(ty: Type, values: Vec<f64>) -> (NodeRef, SettableValue) {
426    let cell = SettableValue::new(values);
427    let node = uniform(
428        UniformSource::Settable(cell.clone()),
429        ty,
430        UniformGroup::Object,
431        None,
432    );
433    (node, cell)
434}
435
436/// A `uniform()` whose value is recomputed from the render object it is about
437/// to be drawn for — the whole of a `Node` with `updateType =
438/// NodeUpdateType.OBJECT` wrapping a `uniform()`, which is what
439/// `webgpu_instance_uniform`'s `InstanceUniformNode` is.
440///
441/// The callback is three's `update( frame )` with `frame.object`. It runs once
442/// per draw, just before the object group's bytes are written, so twelve meshes
443/// sharing one material still get twelve different values out of one program.
444pub fn uniform_object(
445    ty: Type,
446    update: impl Fn(&crate::core::Object3D) -> Vec<f64> + 'static,
447) -> NodeRef {
448    uniform(
449        UniformSource::ObjectUpdate(crate::nodes::node::ObjectUpdate::new(update)),
450        ty,
451        UniformGroup::Object,
452        None,
453    )
454}
455
456/// [`uniform_object`] for a node whose `update( frame )` reads more than
457/// `frame.object` — `webgpu_occlusion`'s `OcclusionNode`, which asks
458/// `frame.renderer.isOccluded( testObject )`. See [`NodeFrame`].
459///
460/// [`NodeFrame`]: crate::nodes::NodeFrame
461pub fn uniform_frame(
462    ty: Type,
463    update: impl Fn(&crate::nodes::NodeFrame) -> Vec<f64> + 'static,
464) -> NodeRef {
465    uniform(
466        UniformSource::ObjectUpdate(crate::nodes::node::ObjectUpdate::with_frame(update)),
467        ty,
468        UniformGroup::Object,
469        None,
470    )
471}
472
473/// `userData( name, inputType )` — `UserDataNode`, a `ReferenceNode` on the
474/// render object's own `userData`: an object-group `uniform()` whose value is
475/// `object.userData[ name ]`, re-read before every draw
476/// (`NodeUpdateType.OBJECT`), so every object sharing the material gets its
477/// own value out of one program. `webgpu_sprites` drives each sprite's
478/// `rotationNode` with it.
479///
480/// three's `ReferenceNode` walks a dotted `name` (`'a.b'`) and also accepts an
481/// explicit `userData` object in place of the render object's; the ladder uses
482/// neither, so the port takes a flat key on the render object. A number or a
483/// numeric array is read as the uniform's components; a missing key or any
484/// other value reads as zero, where three would write `undefined` and trip
485/// over it.
486pub fn user_data(name: &str, ty: Type) -> NodeRef {
487    let name = name.to_owned();
488    let length = ty.components();
489    uniform_object(ty, move |object| {
490        let mut values = match object.user_data.get(&name) {
491            Some(serde_json::Value::Number(n)) => vec![n.as_f64().unwrap_or(0.0)],
492            Some(serde_json::Value::Array(items)) => {
493                items.iter().map(|v| v.as_f64().unwrap_or(0.0)).collect()
494            }
495            _ => Vec::new(),
496        };
497        values.resize(length, 0.0);
498        values
499    })
500}
501
502/// `uniform( value, type )` — the low-level constructor every uniform
503/// accessor in this module builds on; `source` says where the renderer reads
504/// the value from.
505pub fn uniform(
506    source: UniformSource,
507    ty: Type,
508    group: UniformGroup,
509    name: Option<&'static str>,
510) -> NodeRef {
511    NodeRef::new(Node::Uniform(Rc::new(UniformNode {
512        source,
513        ty,
514        group,
515        name: std::cell::Cell::new(name),
516    })))
517}
518
519/// `node.toVar( name )`. The name passes through `sub_build_name()`, so a var
520/// declared while a sub-build layer is open takes the layer's prefix.
521pub fn to_var(name: Option<&'static str>, value: NodeRef) -> NodeRef {
522    let ty = value.ty();
523    NodeRef::new(Node::Var(Rc::new(VarDef {
524        name: name.map(sub_build_name),
525        value,
526        ty,
527    })))
528}
529
530/// `node.toConst( name )` — a WGSL `let`. Same shape as [`to_var`], but the
531/// value is written once where it is declared, so it takes its own
532/// `nodeConstN` counter and no `var<private>` declaration.
533pub fn to_const(name: Option<&'static str>, value: NodeRef) -> NodeRef {
534    let ty = value.ty();
535    NodeRef::new(Node::Let(Rc::new(VarDef {
536        name: name.map(sub_build_name),
537        value,
538        ty,
539    })))
540}
541
542/// `node.toVarIntent()` — what `pow()`, `mix()` and the other
543/// `nodeProxyIntent` functions wrap their result in — for a node that is then
544/// assigned to.
545///
546/// Three's intent var is transparent until an `assign()` targets it: built as
547/// a value it is its inner node, and built as an assignment target it becomes
548/// a function-scope `var nodeVarN : T = …;` (`NodeVar.local`). The port
549/// decides at construction rather than at build, so this is the second form
550/// only, and a caller uses it where the JS goes on to `.mulAssign()` (or any
551/// other assign) the result of one of those functions — `SkyMesh`'s
552/// `Lin.mulAssign( … )` is the first. Everywhere else the plain node already
553/// is three's output.
554pub fn to_var_intent(value: NodeRef) -> NodeRef {
555    let ty = value.ty();
556    NodeRef::new(Node::VarIntent(Rc::new(VarDef {
557        name: None,
558        value,
559        ty,
560    })))
561}
562
563/// `toVar( name )` for a var that keeps its name inside a sub-build layer.
564/// Three prefixes only the nodes a layer is *tagged on* — the accessors that
565/// declare the layer and their ancestors — so a var built inside one of those
566/// accessors, like `tangentViewFrame`, stays unprefixed.
567fn to_var_untagged(name: &'static str, value: NodeRef) -> NodeRef {
568    let ty = value.ty();
569    NodeRef::new(Node::Var(Rc::new(VarDef {
570        name: Some(name.to_string()),
571        value,
572        ty,
573    })))
574}
575
576/// `node.toVarying( name )`.
577pub fn to_varying(name: Option<&'static str>, value: NodeRef) -> NodeRef {
578    let ty = value.ty();
579    NodeRef::new(Node::Varying(Rc::new(VaryingDef {
580        name,
581        value,
582        ty,
583        flat: matches!(ty, Type::U32 | Type::I32),
584    })))
585}
586
587/// `outputStruct( ...members )` — `OutputStructNode`, for a material's
588/// `outputNode`: the fragment stage writes `members[ i ]` to `@location( i )`,
589/// each as its own type. See [`Node::OutputStruct`].
590pub fn output_struct(members: Vec<NodeRef>) -> NodeRef {
591    NodeRef::new(Node::OutputStruct { members })
592}
593
594/// `property( type, name )`.
595pub fn property(name: &'static str, ty: Type) -> NodeRef {
596    NodeRef::new(Node::Property { name, ty })
597}
598
599// ---------------------------------------------------------------------------
600// operators
601// ---------------------------------------------------------------------------
602
603const COMPARISONS: [&str; 6] = ["==", "!=", "<", "<=", ">", ">="];
604
605/// `&&` / `||` — `OperatorNode` gives them a `bool` result without padding
606/// either operand.
607const LOGICAL: [&str; 2] = ["&&", "||"];
608
609/// `OperatorNode.getNodeType()` plus the operand padding
610/// `NodeBuilder.format()` performs: `mat4 * vec3` becomes
611/// `mat4 * vec4( v, 1.0 )`.
612fn binary(op: &'static str, a: NodeRef, b: NodeRef) -> NodeRef {
613    let (ta, tb) = (a.ty(), b.ty());
614
615    if LOGICAL.contains(&op) {
616        return NodeRef::new(Node::Op {
617            op,
618            a,
619            b,
620            ty: Type::Bool,
621        });
622    }
623
624    if COMPARISONS.contains(&op) {
625        let n = ta.components().max(tb.components());
626        let ty = if n == 1 {
627            Type::Bool
628        } else {
629            Type::vector_of(Type::Bool, n)
630        };
631        return NodeRef::new(Node::Op { op, a, b, ty });
632    }
633
634    // matrix * vector: the result is a vector as wide as the matrix, and a
635    // too-short vector is padded with 1.0 (`NodeBuilder.format`).
636    if ta.is_matrix() && !tb.is_matrix() && tb.components() > 1 {
637        let want = match ta {
638            Type::Mat4 => 4,
639            Type::Mat2 => 2,
640            _ => 3,
641        };
642        let ty = Type::vector_of(Type::F32, want);
643        let b = pad(b, want);
644        return NodeRef::new(Node::Op { op, a, b, ty });
645    }
646
647    // vector * matrix: the row-vector form three.js uses for inverse-transpose
648    // transforms (`vec4( n, 0.0 ) * cameraViewMatrix`).
649    // A *scalar* times a matrix is not this: `OperatorNode.generate()` keeps
650    // `typeA = 'float'` and scales the matrix (`skinWeight.x * boneMat`), so it
651    // must not be padded into a row vector.
652    if tb.is_matrix() && !ta.is_matrix() && ta.components() > 1 {
653        let want = match tb {
654            Type::Mat4 => 4,
655            Type::Mat2 => 2,
656            _ => 3,
657        };
658        let ty = Type::vector_of(Type::F32, want);
659        let a = pad(a, want);
660        return NodeRef::new(Node::Op { op, a, b, ty });
661    }
662
663    let ty = if ta.is_matrix() {
664        ta
665    } else if tb.is_matrix() || tb.components() > ta.components() {
666        tb
667    } else {
668        ta
669    };
670
671    NodeRef::new(Node::Op { op, a, b, ty })
672}
673
674/// `NodeBuilder.format( snippet, 'vec3', 'vec4' )` — pad with 1.0.
675fn pad(node: NodeRef, want: usize) -> NodeRef {
676    let have = node.ty().components();
677    if have >= want {
678        return node;
679    }
680    let mut args = vec![node];
681    for _ in have..want - 1 {
682        args.push(float(0.0));
683    }
684    args.push(float(1.0));
685    join(Type::vector_of(Type::F32, want), args)
686}
687
688fn math(name: &'static str, args: Vec<NodeRef>, ty: Type) -> NodeRef {
689    NodeRef::new(Node::Math { name, args, ty })
690}
691
692/// `all( x )` — whether every component of a boolean vector is true.
693pub fn all(x: impl Into<NodeRef>) -> NodeRef {
694    math("all", vec![x.into()], Type::Bool)
695}
696
697/// `mix( a, b, t )`.
698pub fn mix(a: impl Into<NodeRef>, b: impl Into<NodeRef>, t: impl Into<NodeRef>) -> NodeRef {
699    let (a, b, t) = (a.into(), b.into(), t.into());
700    let ty = if b.ty().components() > a.ty().components() {
701        b.ty()
702    } else {
703        a.ty()
704    };
705    math("mix", vec![a, b, t], ty)
706}
707
708/// `dot( a, b )`.
709pub fn dot(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
710    math("dot", vec![a.into(), b.into()], Type::F32)
711}
712
713/// `cross( a, b )`.
714pub fn cross(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
715    let a = a.into();
716    let ty = a.ty();
717    math("cross", vec![a, b.into()], ty)
718}
719
720/// `refract( i, n, eta )`.
721pub fn refract(i: impl Into<NodeRef>, n: impl Into<NodeRef>, eta: impl Into<NodeRef>) -> NodeRef {
722    let i = i.into();
723    let ty = i.ty();
724    math("refract", vec![i, n.into(), eta.into()], ty)
725}
726
727/// `ceil( x )`.
728pub fn ceil(x: impl Into<NodeRef>) -> NodeRef {
729    let x = x.into();
730    let ty = x.ty();
731    math("ceil", vec![x], ty)
732}
733
734/// `reflect( i, n )`.
735pub fn reflect(i: impl Into<NodeRef>, n: impl Into<NodeRef>) -> NodeRef {
736    let i = i.into();
737    let ty = i.ty();
738    math("reflect", vec![i, n.into()], ty)
739}
740
741/// `floor( x )`.
742pub fn floor(x: impl Into<NodeRef>) -> NodeRef {
743    let x = x.into();
744    let ty = x.ty();
745    math("floor", vec![x], ty)
746}
747
748/// `fract( x )`.
749pub fn fract(x: impl Into<NodeRef>) -> NodeRef {
750    let x = x.into();
751    let ty = x.ty();
752    math("fract", vec![x], ty)
753}
754
755/// `sign( x )`.
756pub fn sign(x: impl Into<NodeRef>) -> NodeRef {
757    let x = x.into();
758    let ty = x.ty();
759    math("sign", vec![x], ty)
760}
761
762/// `exp2( x )`.
763pub fn exp2(x: impl Into<NodeRef>) -> NodeRef {
764    let x = x.into();
765    let ty = x.ty();
766    math("exp2", vec![x], ty)
767}
768
769/// `log2( x )` — `MathNode.LOG2`.
770pub fn log2(x: impl Into<NodeRef>) -> NodeRef {
771    let x = x.into();
772    let ty = x.ty();
773    math("log2", vec![x], ty)
774}
775
776/// `log( x )` — the natural logarithm, `MathNode.LOG`.
777pub fn log(x: impl Into<NodeRef>) -> NodeRef {
778    let x = x.into();
779    let ty = x.ty();
780    math("log", vec![x], ty)
781}
782
783/// `exp( x )` — `MathNode.EXP`.
784pub fn exp(x: impl Into<NodeRef>) -> NodeRef {
785    let x = x.into();
786    let ty = x.ty();
787    math("exp", vec![x], ty)
788}
789
790/// `min( a, b )` as a free function, to match [`max`].
791pub fn min_of(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
792    let a = a.into();
793    let ty = a.ty();
794    math("min", vec![a, b.into()], ty)
795}
796
797/// `length( v )` — a scalar out of any vector.
798pub fn length(v: impl Into<NodeRef>) -> NodeRef {
799    math("length", vec![v.into()], Type::F32)
800}
801
802/// `a.distance( b )` — `MathNode.DISTANCE`, a scalar out of two vectors.
803///
804/// Both operands are widened to the wider of the two, not to the `f32` result:
805/// `screenUV.distance( 0.5 )` is `distance( uv, vec2<f32>( 0.5 ) )`, and the
806/// splat of the scalar is what the builder's `distance` arm is for.
807pub fn distance(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
808    math("distance", vec![a.into(), b.into()], Type::F32)
809}
810
811/// `TWO_PI` — `three.js/src/nodes/math/MathUtils.js`. A `float` const node, so
812/// `TWO_PI.div( 3 )` is emitted as the division, never folded.
813pub fn two_pi() -> NodeRef {
814    float(std::f64::consts::TAU)
815}
816
817/// `rotate( position, rotation )` — `RotateNode.setup()`
818/// (`src/nodes/utils/RotateNode.js`), with its default `'XYZ'` order.
819///
820/// The `vec2` branch:
821///
822/// ```ignore
823/// mat2( cos, sin, sin.negate(), cos ).mul( position )
824/// ```
825///
826/// `cos`/`sin` are one node each, used twice, so both become `nodeVarN` temps.
827///
828/// The `vec3` branch builds one `mat4` per axis and chains them in the
829/// order's letters, `X.mul( Y ).mul( Z ).mul( vec4( position, 1 ) ).xyz`.
830/// Every `rotation.x` / `cos( rotation.x )` there is a fresh node in three,
831/// so each is emitted inline; only `rotation` itself is shared (twelve uses),
832/// which is what makes the builder hoist it into a temp.
833pub fn rotate(position: impl Into<NodeRef>, rotation: impl Into<NodeRef>) -> NodeRef {
834    let (position, rotation) = (position.into(), rotation.into());
835    match position.ty() {
836        Type::Vec2 => {
837            let cos_angle = rotation.cos();
838            let sin_angle = rotation.sin();
839            join(
840                Type::Mat2,
841                vec![
842                    cos_angle.clone(),
843                    sin_angle.clone(),
844                    sin_angle.negate(),
845                    cos_angle,
846                ],
847            )
848            .mul(position)
849        }
850        Type::Vec3 => {
851            let r = &rotation;
852            let row = |args: Vec<NodeRef>| join(Type::Vec4, args);
853            let mat4 = |rows: Vec<NodeRef>| join(Type::Mat4, rows);
854            let zero = || float(0.0);
855            let rotation_x = mat4(vec![
856                vec4(1.0, 0.0, 0.0, 0.0),
857                row(vec![zero(), r.x().cos(), r.x().sin(), zero()]),
858                row(vec![zero(), r.x().sin().negate(), r.x().cos(), zero()]),
859                vec4(0.0, 0.0, 0.0, 1.0),
860            ]);
861            let rotation_y = mat4(vec![
862                row(vec![r.y().cos(), zero(), r.y().sin().negate(), zero()]),
863                vec4(0.0, 1.0, 0.0, 0.0),
864                row(vec![r.y().sin(), zero(), r.y().cos(), zero()]),
865                vec4(0.0, 0.0, 0.0, 1.0),
866            ]);
867            let rotation_z = mat4(vec![
868                row(vec![r.z().cos(), r.z().sin(), zero(), zero()]),
869                row(vec![r.z().sin().negate(), r.z().cos(), zero(), zero()]),
870                vec4(0.0, 0.0, 1.0, 0.0),
871                vec4(0.0, 0.0, 0.0, 1.0),
872            ]);
873            rotation_x
874                .mul(rotation_y)
875                .mul(rotation_z)
876                .mul(vec4_join(vec![position, float(1.0)]))
877                .xyz()
878        }
879        ty => panic!("three-rs: rotate() of a {ty:?}"),
880    }
881}
882
883/// `abs( x )`.
884pub fn abs(x: impl Into<NodeRef>) -> NodeRef {
885    let x = x.into();
886    let ty = x.ty();
887    math("abs", vec![x], ty)
888}
889
890/// `fwidth( x )`. `WGSLNodeBuilder`'s method table maps `dFdx`/`dFdy` but not
891/// `fwidth`, so `MathNode.FWIDTH` reaches WGSL as the builtin of the same name.
892pub fn fwidth(x: impl Into<NodeRef>) -> NodeRef {
893    let x = x.into();
894    let ty = x.ty();
895    math("fwidth", vec![x], ty)
896}
897
898/// `x.mod( y )` on floats. WGSL has no `%` for floats the way three.js' node
899/// system means it, so `MathNode` emits a helper; see `wgsl::MOD_FLOAT_SNIPPET`.
900pub fn mod_float(x: impl Into<NodeRef>, y: impl Into<NodeRef>) -> NodeRef {
901    math("tsl_mod_float", vec![x.into(), y.into()], Type::F32)
902}
903
904/// `smoothstep( low, high, x )` — `MathNode.SMOOTHSTEP`, typed (and its
905/// operands built) as `MathNode.getInputType()`: `smoothstep( 0, 1, uv )` is
906/// `smoothstep( vec2<f32>( 0.0 ), vec2<f32>( 1.0 ), uv )`.
907pub fn smoothstep(
908    low: impl Into<NodeRef>,
909    high: impl Into<NodeRef>,
910    x: impl Into<NodeRef>,
911) -> NodeRef {
912    let (low, high, x) = (low.into(), high.into(), x.into());
913    let ty = wrappers::math_input_type(&[&low, &high, &x]);
914    math("smoothstep", vec![low, high, x], ty)
915}
916
917/// `dFdx( x )` — WGSL `dpdx`.
918pub fn dpdx(x: impl Into<NodeRef>) -> NodeRef {
919    let x = x.into();
920    let ty = x.ty();
921    math("dpdx", vec![x], ty)
922}
923
924/// `dFdy( x )`. `WGSLNodeBuilder`'s method table maps `dFdy` to the string
925/// `'- dpdy'`, so the emitted call carries the sign flip that takes WGSL's
926/// framebuffer-down derivative back to GLSL's up convention.
927pub fn dpdy(x: impl Into<NodeRef>) -> NodeRef {
928    let x = x.into();
929    let ty = x.ty();
930    math("- dpdy", vec![x], ty)
931}
932
933/// Port of `three.js/src/nodes/procedural/Checker.js`. An `Fn()` with no
934/// layout, so it inlines: `sign( mod( floor( uv.x * 2 ) + floor( uv.y * 2 ), 2 ) )`.
935pub fn checker(coord: impl Into<NodeRef>) -> NodeRef {
936    let uv = coord.into().mul(2.0);
937    let cx = floor(uv.x());
938    let cy = floor(uv.y());
939    sign(mod_float(cx.add(cy), 2.0))
940}
941
942/// Port of `three.js/src/nodes/display/ViewportDepthNode.js`'
943/// `perspectiveDepthToViewZ( depth, near, far )` with `reversedDepthBuffer`
944/// off: `near * far / ( ( far - near ) * depth - far )`.
945pub fn perspective_depth_to_view_z(
946    depth: impl Into<NodeRef>,
947    near: impl Into<NodeRef>,
948    far: impl Into<NodeRef>,
949) -> NodeRef {
950    let (depth, near, far) = (depth.into(), near.into(), far.into());
951    near.clone()
952        .mul(far.clone())
953        .div(far.clone().sub(near).mul(depth).sub(far))
954}
955
956/// Port of `ViewportDepthNode.js`' `viewZToPerspectiveDepth( viewZ, near,
957/// far )` with `reversedDepthBuffer` off: `( near + viewZ ) * far / ( ( far -
958/// near ) * viewZ )`.
959pub fn view_z_to_perspective_depth(
960    view_z: impl Into<NodeRef>,
961    near: impl Into<NodeRef>,
962    far: impl Into<NodeRef>,
963) -> NodeRef {
964    let (view_z, near, far) = (view_z.into(), near.into(), far.into());
965    near.clone()
966        .add(view_z.clone())
967        .mul(far.clone())
968        .div(far.sub(near).mul(view_z))
969}
970
971/// Port of `PostProcessingUtils.js`' `getViewPosition( screenPosition,
972/// depth, projectionMatrixInverse )` for the WebGPU coordinate system: the
973/// view-space position a screen uv and its depth unproject to.
974pub fn get_view_position(
975    screen_position: NodeRef,
976    depth: NodeRef,
977    projection_matrix_inverse: NodeRef,
978) -> NodeRef {
979    let screen_position = vec2_join(vec![screen_position.x(), screen_position.y().one_minus()])
980        .mul(2.0)
981        .sub(1.0);
982    let clip_space_position = vec4_join(vec![vec3_join(vec![screen_position, depth]), float(1.0)]);
983    let view_space_position = projection_matrix_inverse.mul(clip_space_position);
984    view_space_position.xyz().div(view_space_position.w())
985}
986
987/// `getScreenPositionFromClip( clipPosition )` — `PostProcessingUtils.js`: a
988/// clip-space position's screen uv, y down. A `Fn()` with a layout, so it
989/// is a WGSL function.
990pub fn get_screen_position_from_clip(clip_position: NodeRef) -> NodeRef {
991    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
992    let def = CELL.with(|c| {
993        c.get(|| {
994            shader_fn(
995                Some("getScreenPositionFromClip"),
996                vec![("clipPosition", Type::Vec4)],
997                Type::Vec2,
998                |args| {
999                    let clip = &args[0];
1000                    let screen = to_var(None, clip.xy().div(clip.w()).mul(0.5).add(0.5));
1001                    block(
1002                        vec![screen.clone()],
1003                        vec2_join(vec![screen.x(), screen.y().one_minus()]),
1004                    )
1005                },
1006            )
1007        })
1008    });
1009    call(&def, vec![clip_position])
1010}
1011
1012/// `getScreenPosition( viewPosition, projectionMatrix )` —
1013/// `PostProcessingUtils.js`: the screen uv a view-space position projects
1014/// to, `y` flipped (three flips it unconditionally, on every backend). The
1015/// uv before the flip is a `toVar()`.
1016pub fn get_screen_position(view_position: NodeRef, projection_matrix: NodeRef) -> NodeRef {
1017    let sample_clip_pos = projection_matrix.mul(vec4_join(vec![view_position, float(1.0)]));
1018    let sample_uv = to_var(
1019        None,
1020        sample_clip_pos
1021            .xy()
1022            .div(sample_clip_pos.w())
1023            .mul(0.5)
1024            .add(0.5),
1025    );
1026    vec2_join(vec![sample_uv.x(), sample_uv.y().one_minus()])
1027}
1028
1029/// `getNormalFromDepth( uv, depthTexture, projectionMatrixInverse )` —
1030/// `PostProcessingUtils.js`: a view-space normal reconstructed from a depth
1031/// texture, each axis' derivative taken from whichever neighbour pair is the
1032/// more continuous (the 2-tap extrapolation test of
1033/// `https://atyuwen.github.io/posts/normal-reconstruction/`).
1034pub fn get_normal_from_depth(
1035    uv: NodeRef,
1036    depth_texture: &DepthTexture,
1037    projection_matrix_inverse: NodeRef,
1038) -> NodeRef {
1039    let size = texture_size(TextureSource::Depth(depth_texture.clone()), int(0));
1040    let p = to_var(None, uv.clone().mul(size.clone()).to(Type::IVec2));
1041    let load = |coord: NodeRef| to_var(None, depth_texture_load(depth_texture, coord));
1042    let c0 = load(p.clone());
1043    let l2 = load(p.clone().sub(ivec2(2, 0)));
1044    let l1 = load(p.clone().sub(ivec2(1, 0)));
1045    let r1 = load(p.clone().add(ivec2(1, 0)));
1046    let r2 = load(p.clone().add(ivec2(2, 0)));
1047    let b2 = load(p.clone().add(ivec2(0, 2)));
1048    let b1 = load(p.clone().add(ivec2(0, 1)));
1049    let t1 = load(p.clone().sub(ivec2(0, 1)));
1050    let t2 = load(p.sub(ivec2(0, 2)));
1051    let delta = |near: &NodeRef, far: NodeRef| {
1052        to_var(
1053            None,
1054            abs(float(2.0).mul(near.clone()).sub(far).sub(c0.clone())),
1055        )
1056    };
1057    let dl = delta(&l1, l2.clone());
1058    let dr = delta(&r1, r2.clone());
1059    let db = delta(&b1, b2.clone());
1060    let dt = delta(&t1, t2.clone());
1061    let ce = to_var(
1062        None,
1063        get_view_position(uv.clone(), c0.clone(), projection_matrix_inverse.clone()),
1064    );
1065    let at = |coord: NodeRef, depth: NodeRef| {
1066        get_view_position(coord, depth, projection_matrix_inverse.clone())
1067    };
1068    let texel_x = || vec2_join(vec![float(1.0).div(size.x()), float(0.0)]);
1069    let texel_y = || vec2_join(vec![float(0.0), float(1.0).div(size.y())]);
1070    let dpdx = dl.clone().less_than(dr.clone()).select(
1071        ce.clone().sub(at(uv.clone().sub(texel_x()), l1.clone())),
1072        ce.clone()
1073            .negate()
1074            .add(at(uv.clone().add(texel_x()), r1.clone())),
1075    );
1076    let dpdy = db.clone().less_than(dt.clone()).select(
1077        ce.clone().sub(at(uv.clone().add(texel_y()), b1.clone())),
1078        ce.clone().negate().add(at(uv.sub(texel_y()), t1.clone())),
1079    );
1080    // The `toVar()`s are declared in the JS order, not at first read.
1081    block(
1082        vec![p, c0, l2, l1, r1, r2, b2, b1, t1, t2, dl, dr, db, dt, ce],
1083        cross(dpdx, dpdy).normalize(),
1084    )
1085}
1086
1087/// `getParallaxCorrectNormal( normal, cubeSize, cubePos )` —
1088/// `getParallaxCorrectNormal.js`, box-projected cube mapping: `normal` bent
1089/// so that a cube map captured at `cubePos` reads as the inside of a box of
1090/// `cubeSize` around it, from `positionWorld`.
1091pub fn get_parallax_correct_normal(
1092    normal: NodeRef,
1093    cube_size: NodeRef,
1094    cube_pos: NodeRef,
1095) -> NodeRef {
1096    let n_dir = to_var(None, normal.normalize());
1097    let toward = |half: f64| {
1098        to_var(
1099            None,
1100            cube_size
1101                .clone()
1102                .mul(half)
1103                .add(cube_pos.clone())
1104                .sub(position_world())
1105                .div(n_dir.clone()),
1106        )
1107    };
1108    let rbmax = toward(0.5);
1109    let rbmin = toward(-0.5);
1110    let rbminmax = to_var(None, vec3(0.0, 0.0, 0.0));
1111    let axis = |c: &'static str| {
1112        rbminmax.swizzle(c).assign(
1113            n_dir
1114                .swizzle(c)
1115                .greater_than(float(0.0))
1116                .select(rbmax.swizzle(c), rbmin.swizzle(c)),
1117        )
1118    };
1119    let correction = to_var(None, rbminmax.x().min(rbminmax.y()).min(rbminmax.z()));
1120    let box_intersection = to_var(
1121        None,
1122        position_world().add(n_dir.clone().mul(correction.clone())),
1123    );
1124    // The `toVar()`s are declared in the JS order, not at first read.
1125    let axes = vec![axis("x"), axis("y"), axis("z")];
1126    let mut statements = vec![
1127        n_dir.clone(),
1128        rbmax.clone(),
1129        rbmin.clone(),
1130        rbminmax.clone(),
1131    ];
1132    statements.extend(axes);
1133    statements.extend([correction, box_intersection.clone()]);
1134    block(statements, box_intersection.sub(cube_pos))
1135}
1136
1137/// `viewZToOrthographicDepth( viewZ, near, far )` — `ViewportDepthNode.js`:
1138/// `( viewZ + near ) / ( near - far )`, the view-space z mapped to `[0,1]`
1139/// between the clip planes.
1140pub fn view_z_to_orthographic_depth(
1141    view_z: impl Into<NodeRef>,
1142    near: impl Into<NodeRef>,
1143    far: impl Into<NodeRef>,
1144) -> NodeRef {
1145    let (near, far) = (near.into(), far.into());
1146    view_z.into().add(near.clone()).div(near.sub(far))
1147}
1148
1149/// `viewZToReversedOrthographicDepth( viewZ, near, far )` —
1150/// `ViewportDepthNode.js`: `( viewZ + far ) / ( far - near )`, the
1151/// orthographic depth for a reversed depth buffer.
1152pub fn view_z_to_reversed_orthographic_depth(
1153    view_z: impl Into<NodeRef>,
1154    near: impl Into<NodeRef>,
1155    far: impl Into<NodeRef>,
1156) -> NodeRef {
1157    let (near, far) = (near.into(), far.into());
1158    view_z.into().add(far.clone()).div(far.sub(near))
1159}
1160
1161/// `orthographicDepthToViewZ( depth, near, far )` — `ViewportDepthNode.js`
1162/// with `reversedDepthBuffer` off: `( near - far ) * depth - near`.
1163pub fn orthographic_depth_to_view_z(
1164    depth: impl Into<NodeRef>,
1165    near: impl Into<NodeRef>,
1166    far: impl Into<NodeRef>,
1167) -> NodeRef {
1168    let near = near.into();
1169    near.clone().sub(far.into()).mul(depth.into()).sub(near)
1170}
1171
1172/// `viewZToReversedPerspectiveDepth( viewZ, near, far )` —
1173/// `ViewportDepthNode.js`: `near * ( viewZ + far ) / ( viewZ * ( near - far
1174/// ) )`.
1175pub fn view_z_to_reversed_perspective_depth(
1176    view_z: impl Into<NodeRef>,
1177    near: impl Into<NodeRef>,
1178    far: impl Into<NodeRef>,
1179) -> NodeRef {
1180    let (view_z, near, far) = (view_z.into(), near.into(), far.into());
1181    near.clone()
1182        .mul(view_z.clone().add(far.clone()))
1183        .div(view_z.mul(near.sub(far)))
1184}
1185
1186/// `viewZToLogarithmicDepth( viewZ, near, far )` — `ViewportDepthNode.js`:
1187/// Ulrich's logarithmic depth with `K = 1`, `log2( -viewZ / near ) / log2(
1188/// far / near )`, `near` clamped to `1e-6` in a `toVar()`.
1189pub fn view_z_to_logarithmic_depth(
1190    view_z: impl Into<NodeRef>,
1191    near: impl Into<NodeRef>,
1192    far: impl Into<NodeRef>,
1193) -> NodeRef {
1194    let near = to_var(None, near.into().max(1e-6));
1195    let numerator = log2(view_z.into().negate().div(near.clone()));
1196    let denominator = log2(far.into().div(near));
1197    numerator.div(denominator)
1198}
1199
1200/// `logarithmicDepthToViewZ( depth, near, far )` — `ViewportDepthNode.js`:
1201/// the inverse of [`view_z_to_logarithmic_depth`], `-( e ^ ( depth * log(
1202/// far / near ) ) * near )`.
1203pub fn logarithmic_depth_to_view_z(
1204    depth: impl Into<NodeRef>,
1205    near: impl Into<NodeRef>,
1206    far: impl Into<NodeRef>,
1207) -> NodeRef {
1208    let near = near.into();
1209    let exponent = depth.into().mul(log(far.into().div(near.clone())));
1210    float(std::f64::consts::E).pow(exponent).mul(near).negate()
1211}
1212
1213/// `linearDepth()` — `ViewportDepthNode.LINEAR_DEPTH` with no value: the
1214/// fragment's own depth, `viewZToOrthographicDepth( positionView.z,
1215/// cameraNear, cameraFar )`.
1216pub fn linear_depth() -> NodeRef {
1217    view_z_to_orthographic_depth(position_view().z(), camera_near(), camera_far())
1218}
1219
1220/// `linearDepth( value )` — a depth-buffer value made linear:
1221/// `viewZToOrthographicDepth( perspectiveDepthToViewZ( value, cameraNear,
1222/// cameraFar ), cameraNear, cameraFar )`.
1223///
1224/// **Divergence**: three picks the formula from `camera.isPerspectiveCamera`
1225/// at build time and passes the value through untouched for an orthographic
1226/// camera. The port's builder does not see the camera, so this is the
1227/// perspective formula always; every page that reads it renders through a
1228/// `PerspectiveCamera`.
1229pub fn linear_depth_of(value: impl Into<NodeRef>) -> NodeRef {
1230    let view_z = perspective_depth_to_view_z(value, camera_near(), camera_far());
1231    view_z_to_orthographic_depth(view_z, camera_near(), camera_far())
1232}
1233
1234/// `Fog.js`' `getViewZNode( builder )`: `builder.context.getViewZ` if an
1235/// enclosing [`context`] installed one, else `positionView.z`. Read inside a
1236/// fog factor's deferred body (see [`fog_factor_fn`]), so `positionView` is
1237/// the building material's own and the context is the one the builder has
1238/// pushed by then.
1239fn fog_view_z() -> NodeRef {
1240    current_context(|cx| cx.extra.get("getViewZ").cloned()).unwrap_or_else(|| position_view().z())
1241}
1242
1243/// Port of `three.js/src/nodes/fog/Fog.js`' `rangeFogFactor( near, far )`:
1244/// `smoothstep( near, far, viewZ.negate() )`, where `viewZ` is
1245/// `builder.context.getViewZ` or `positionView.z` (three's `getViewZNode`). So
1246/// `range_fog_factor( 2.7, 4.0 ).context( ContextValue::new().set(
1247/// "getViewZ", scene_pass_view_z ) )` is the page's own spelling
1248/// (`docs/nodes.md` §45).
1249///
1250/// Like three's, the factor reads `positionView` when the *material* is built,
1251/// not when the fog is made: it is an inline `Fn()` whose body
1252/// `resolve_fog_factor` runs inside the material's setup, so a
1253/// `SpriteNodeMaterial` fogs by its billboarded `v_positionView`
1254/// (`docs/nodes.md` §41).
1255pub fn range_fog_factor(near: impl Into<NodeRef>, far: impl Into<NodeRef>) -> NodeRef {
1256    let (near, far) = (near.into(), far.into());
1257    fog_factor_fn(move || range_fog_factor_with_view_z(near.clone(), far.clone(), fog_view_z()))
1258}
1259
1260/// `Fog.js`' factors are `Fn()`s whose `getViewZNode( builder )` runs during
1261/// the material's build, when `builder.context.setupPositionView` is the
1262/// material's own. The port's graph is eager, so the body is held in an
1263/// inline, argument-less call and run by [`resolve_fog_factor`] inside
1264/// `NodeMaterial` setup's position-view scope. A factor that reaches the
1265/// builder unresolved (used outside `scene.fogNode`, or wrapped in a
1266/// [`context`]) is inlined there, with the base class' `positionView`, which
1267/// is what it read before.
1268fn fog_factor_fn(body: impl Fn() -> NodeRef + 'static) -> NodeRef {
1269    call(&inline_fn(0, Type::F32, move |_| body()), Vec::new())
1270}
1271
1272/// Runs a fog factor's deferred body (see [`range_fog_factor`]) in the
1273/// current material's context. Any other node is returned as it is.
1274pub(crate) fn resolve_fog_factor(factor: &NodeRef) -> NodeRef {
1275    resolve_fn_call(factor)
1276}
1277
1278/// Runs an argument-less inline `Fn()` call's body in the current material's
1279/// context; any other node is returned as it is.
1280///
1281/// three.js runs every `Fn` body lazily, inside the build of the material that
1282/// uses it, so `normalWorld` in a `material.outputNode = Fn( … )( output )`
1283/// reads *that* material's `normalView` — normal-mapped and `DoubleSide`-
1284/// negated for a GLTF body. The port's graph is eager: built at the call site,
1285/// with no material in scope, `normal_world()` keys on the bare geometric
1286/// normal and the fragment re-assigns `normalView = normalViewGeometry` just
1287/// ahead of it. Holding the body in an argument-less call and resolving it here,
1288/// inside `NodeMaterial` setup, is the same deferral [`resolve_fog_factor`]
1289/// already gives `scene.fogNode`.
1290pub(crate) fn resolve_fn_call(node: &NodeRef) -> NodeRef {
1291    match node.node() {
1292        Node::Call { def, args } if !def.layout && args.is_empty() => (def.body)(&[]),
1293        _ => node.clone(),
1294    }
1295}
1296
1297/// `rangeFogFactor( near, far ).context( { getViewZ: () => viewZ } )`, with
1298/// the override passed as an argument.
1299///
1300/// The form the port had before [`context`] existed (`docs/nodes.md` §24.3);
1301/// the generated WGSL is the same as the context form's.
1302pub fn range_fog_factor_with_view_z(
1303    near: impl Into<NodeRef>,
1304    far: impl Into<NodeRef>,
1305    view_z: impl Into<NodeRef>,
1306) -> NodeRef {
1307    smoothstep(near, far, view_z.into().negate())
1308}
1309
1310/// Port of `three.js/src/nodes/fog/Fog.js`' `densityFogFactor( density )`,
1311/// the exponential squared fog `FogExp2` builds:
1312/// `density.mul( density, viewZ, viewZ ).negate().exp().oneMinus()`.
1313///
1314/// `viewZ` is `positionView.z.negate()` (or `builder.context.getViewZ`, as
1315/// in [`range_fog_factor`]), read twice. three.js' usage count turns it into a
1316/// `let nodeConstN`; the port's builder does not promote a negation on usage
1317/// (`docs/nodes.md` §8, "`toConst` on the shadow filter"), so the const is
1318/// taken here by hand and the WGSL is the same.
1319///
1320/// Deferred to the material's build as [`range_fog_factor`] is.
1321pub fn density_fog_factor(density: impl Into<NodeRef>) -> NodeRef {
1322    let density = density.into();
1323    fog_factor_fn(move || density_fog_factor_with_view_z(density.clone(), fog_view_z()))
1324}
1325
1326/// [`density_fog_factor`] over an explicit view-space z, the
1327/// `.context( { getViewZ } )` form [`range_fog_factor_with_view_z`] documents.
1328pub fn density_fog_factor_with_view_z(
1329    density: impl Into<NodeRef>,
1330    view_z: impl Into<NodeRef>,
1331) -> NodeRef {
1332    let density = density.into();
1333    let view_z = to_const(None, view_z.into().negate());
1334    exp(density
1335        .clone()
1336        .mul(density)
1337        .mul(view_z.clone())
1338        .mul(view_z)
1339        .negate())
1340    .one_minus()
1341}
1342
1343/// Port of `three.js/src/nodes/fog/Fog.js`'
1344/// `exponentialHeightFogFactor( density, height )`: fog only below the world
1345/// height `height`, thickening with the depth below it times the view distance.
1346///
1347/// ```js
1348/// const distance = height.sub( positionWorld.y ).max( 0 ).toConst();
1349/// const m = distance.mul( viewZ ).toConst();
1350/// return density.mul( density, m, m ).negate().exp().oneMinus();
1351/// ```
1352pub fn exponential_height_fog_factor(
1353    density: impl Into<NodeRef>,
1354    height: impl Into<NodeRef>,
1355) -> NodeRef {
1356    let (density, height) = (density.into(), height.into());
1357    fog_factor_fn(move || {
1358        exponential_height_fog_factor_with_view_z(density.clone(), height.clone(), fog_view_z())
1359    })
1360}
1361
1362/// [`exponential_height_fog_factor`] over an explicit view-space z.
1363pub fn exponential_height_fog_factor_with_view_z(
1364    density: impl Into<NodeRef>,
1365    height: impl Into<NodeRef>,
1366    view_z: impl Into<NodeRef>,
1367) -> NodeRef {
1368    let density = density.into();
1369    let view_z = view_z.into().negate();
1370    let distance = to_const(None, height.into().sub(position_world().y()).max(0.0));
1371    let m = to_const(None, distance.mul(view_z));
1372    exp(density.clone().mul(density).mul(m.clone()).mul(m).negate()).one_minus()
1373}
1374
1375/// Port of `three.js/src/nodes/fog/Fog.js`' `fog( color, factor )`. The node it
1376/// mixes into is the material's output, supplied at setup time, so the pair is
1377/// carried as a `FogNode` and unpacked by `NodeMaterial::setup_output()`:
1378/// `vec4( mix( output.rgb, fogColor, factor ), output.a )`.
1379pub fn fog(color: impl Into<NodeRef>, factor: impl Into<NodeRef>) -> FogNode {
1380    FogNode {
1381        color: color.into(),
1382        factor: factor.into(),
1383    }
1384}
1385
1386/// `scene.fogNode = fog( color, factor )`.
1387#[derive(Clone)]
1388pub struct FogNode {
1389    /// The fog color the output is mixed towards.
1390    pub color: NodeRef,
1391    /// How much fog to mix in, 0 (none) to 1 (fully fogged).
1392    pub factor: NodeRef,
1393}
1394
1395/// By node identity — `fogNode.getCacheKey()`'s share of the render object's
1396/// dynamic cache key. A new `fog( … )` is a new program, as in three.js; a
1397/// uniform inside the same one is not.
1398impl std::hash::Hash for FogNode {
1399    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1400        self.color.key().hash(state);
1401        self.factor.key().hash(state);
1402    }
1403}
1404
1405/// `LightsNode`'s four render-group uniforms for the point light at `index` of
1406/// the renderer's light list. Creating them here rather than inside
1407/// `phong.rs` keeps every `UniformSource` in one module.
1408pub(crate) fn light_color_intensity(index: usize) -> NodeRef {
1409    uniform(
1410        UniformSource::LightColorIntensity(index),
1411        Type::Vec3,
1412        UniformGroup::Render,
1413        None,
1414    )
1415}
1416
1417pub(crate) fn light_cutoff_distance(index: usize) -> NodeRef {
1418    uniform(
1419        UniformSource::LightCutoffDistance(index),
1420        Type::F32,
1421        UniformGroup::Render,
1422        None,
1423    )
1424}
1425
1426pub(crate) fn light_decay(index: usize) -> NodeRef {
1427    uniform(
1428        UniformSource::LightDecay(index),
1429        Type::F32,
1430        UniformGroup::Render,
1431        None,
1432    )
1433}
1434
1435/// The point light at `index` of the renderer's light list's **view-space**
1436/// position render-group uniform — `LightsNode`'s per-light view position.
1437pub fn light_view_position(index: usize) -> NodeRef {
1438    uniform(
1439        UniformSource::LightViewPosition(index),
1440        Type::Vec3,
1441        UniformGroup::Render,
1442        None,
1443    )
1444}
1445
1446/// `HemisphereLightNode`'s two extra render-group uniforms: the ground colour
1447/// (already multiplied by the light's intensity) and the light's **world**
1448/// position, which `lightPosition( light )` resolves to.
1449pub(crate) fn light_ground_color(index: usize) -> NodeRef {
1450    uniform(
1451        UniformSource::LightGroundColor(index),
1452        Type::Vec3,
1453        UniformGroup::Render,
1454        None,
1455    )
1456}
1457
1458/// `lightPosition( light )` — `light.matrixWorld`'s translation.
1459pub fn light_world_position(index: usize) -> NodeRef {
1460    uniform(
1461        UniformSource::LightWorldPosition(index),
1462        Type::Vec3,
1463        UniformGroup::Render,
1464        None,
1465    )
1466}
1467
1468/// `lightTargetPosition( light )` — `light.target.matrixWorld`'s translation.
1469pub fn light_target_position(index: usize) -> NodeRef {
1470    uniform(
1471        UniformSource::LightTargetPosition(index),
1472        Type::Vec3,
1473        UniformGroup::Render,
1474        None,
1475    )
1476}
1477
1478/// `SpotLightNode.coneCosNode`.
1479pub(crate) fn light_cone_cos(index: usize) -> NodeRef {
1480    uniform(
1481        UniformSource::LightConeCos(index),
1482        Type::F32,
1483        UniformGroup::Render,
1484        None,
1485    )
1486}
1487
1488/// `SpotLightNode.penumbraCosNode`.
1489pub(crate) fn light_penumbra_cos(index: usize) -> NodeRef {
1490    uniform(
1491        UniformSource::LightPenumbraCos(index),
1492        Type::F32,
1493        UniformGroup::Render,
1494        None,
1495    )
1496}
1497
1498/// `lightShadowMatrix( light )`.
1499///
1500/// One node per light, as three caches it in `light.userData.shadowMatrix`:
1501/// two reads of the same light's matrix in one shader share a uniform.
1502pub fn shadow_matrix(index: usize) -> NodeRef {
1503    thread_local! {
1504        static CACHE: RefCell<HashMap<usize, NodeRef>> = RefCell::new(HashMap::new());
1505    }
1506    CACHE.with(|c| {
1507        c.borrow_mut()
1508            .entry(index)
1509            .or_insert_with(|| {
1510                outside_sub_build(|| {
1511                    uniform(
1512                        UniformSource::ShadowMatrix(index),
1513                        Type::Mat4,
1514                        UniformGroup::Render,
1515                        None,
1516                    )
1517                })
1518            })
1519            .clone()
1520    })
1521}
1522
1523/// `lightProjectionUV( light, position )` — `Lights.js`: `position` through
1524/// the light's shadow matrix, perspective-divided. Three's `position`
1525/// defaults to `positionWorld`; pass it. The light is named by its index,
1526/// as for [`shadow_matrix`].
1527pub fn light_projection_uv(light: usize, position: NodeRef) -> NodeRef {
1528    let position = if position.ty() == Type::Vec3 {
1529        vec4_join(vec![position, float(1.0)])
1530    } else {
1531        position
1532    };
1533    let spot_light_coord = shadow_matrix(light).mul(position);
1534    spot_light_coord.xyz().div(spot_light_coord.w())
1535}
1536
1537/// `directPointLight( { color, lightVector, cutoffDistance, decayExponent } )`
1538/// — `PointLightNode.js`: the `( lightDirection, lightColor )` pair a point
1539/// light contributes, `lightColor` attenuated by
1540/// `getDistanceAttenuation()`.
1541pub fn direct_point_light(
1542    color: NodeRef,
1543    light_vector: NodeRef,
1544    cutoff_distance: NodeRef,
1545    decay_exponent: NodeRef,
1546) -> (NodeRef, NodeRef) {
1547    use crate::materials::phong::{
1548        distance_attenuation_no_cutoff, distance_attenuation_with_cutoff,
1549    };
1550    // `getDistanceAttenuation` is an `If`/`Else`; three re-emits the
1551    // `length()` in each branch, so each branch gets its own node here
1552    // (one shared node would be hoisted into a var per scope).
1553    let attenuation = cutoff_distance.greater_than(0.0).select(
1554        distance_attenuation_with_cutoff(
1555            length(light_vector.clone()),
1556            cutoff_distance,
1557            decay_exponent.clone(),
1558        ),
1559        distance_attenuation_no_cutoff(length(light_vector.clone()), decay_exponent),
1560    );
1561    (light_vector.normalize(), color.mul(attenuation))
1562}
1563
1564/// `PointShadowNode`'s shadow camera clipping planes —
1565/// `uniform( 'float' ).onRenderUpdate( () => shadow.camera.near / far )`.
1566pub(crate) fn shadow_camera_near(index: usize) -> NodeRef {
1567    uniform(
1568        UniformSource::ShadowCameraNear(index),
1569        Type::F32,
1570        UniformGroup::Render,
1571        None,
1572    )
1573}
1574
1575pub(crate) fn shadow_camera_far(index: usize) -> NodeRef {
1576    uniform(
1577        UniformSource::ShadowCameraFar(index),
1578        Type::F32,
1579        UniformGroup::Render,
1580        None,
1581    )
1582}
1583
1584/// `reference( 'bias', 'float', shadow )`.
1585pub(crate) fn shadow_bias(index: usize) -> NodeRef {
1586    uniform(
1587        UniformSource::ShadowBias(index),
1588        Type::F32,
1589        UniformGroup::Render,
1590        None,
1591    )
1592}
1593
1594/// `reference( 'normalBias', 'float', shadow )`.
1595pub(crate) fn shadow_normal_bias(index: usize) -> NodeRef {
1596    uniform(
1597        UniformSource::ShadowNormalBias(index),
1598        Type::F32,
1599        UniformGroup::Render,
1600        None,
1601    )
1602}
1603
1604/// `reference( 'radius', 'float', shadow )`.
1605pub(crate) fn shadow_radius(index: usize) -> NodeRef {
1606    uniform(
1607        UniformSource::ShadowRadius(index),
1608        Type::F32,
1609        UniformGroup::Render,
1610        None,
1611    )
1612}
1613
1614/// `reference( 'blurSamples', 'float', shadow )` — read by the two VSM blur
1615/// passes only.
1616pub(crate) fn shadow_blur_samples(index: usize) -> NodeRef {
1617    uniform(
1618        UniformSource::ShadowBlurSamples(index),
1619        Type::F32,
1620        UniformGroup::Render,
1621        None,
1622    )
1623}
1624
1625/// `reference( 'mapSize', 'vec2', shadow )`.
1626pub(crate) fn shadow_map_size(index: usize) -> NodeRef {
1627    uniform(
1628        UniformSource::ShadowMapSize(index),
1629        Type::Vec2,
1630        UniformGroup::Render,
1631        None,
1632    )
1633}
1634
1635/// `reference( 'intensity', 'float', shadow )`.
1636pub(crate) fn shadow_intensity(index: usize) -> NodeRef {
1637    uniform(
1638        UniformSource::ShadowIntensity(index),
1639        Type::F32,
1640        UniformGroup::Render,
1641        None,
1642    )
1643}
1644
1645/// `materialMetalness` / `materialRoughness`.
1646pub fn material_metalness() -> NodeRef {
1647    uniform(
1648        UniformSource::MaterialMetalness,
1649        Type::F32,
1650        UniformGroup::Object,
1651        None,
1652    )
1653}
1654
1655/// `materialIOR` / `materialSpecularIntensity` / `materialSpecularColor` —
1656/// `MeshPhysicalNodeMaterial.setupSpecular()`'s three uniforms.
1657pub fn material_ior() -> NodeRef {
1658    uniform(
1659        UniformSource::MaterialIor,
1660        Type::F32,
1661        UniformGroup::Object,
1662        None,
1663    )
1664}
1665
1666/// `materialSpecularIntensity`.
1667pub fn material_specular_intensity() -> NodeRef {
1668    uniform(
1669        UniformSource::MaterialSpecularIntensity,
1670        Type::F32,
1671        UniformGroup::Object,
1672        None,
1673    )
1674}
1675
1676/// `materialSpecularColor`.
1677pub fn material_specular_color() -> NodeRef {
1678    uniform(
1679        UniformSource::MaterialSpecularColor,
1680        Type::Vec3,
1681        UniformGroup::Object,
1682        None,
1683    )
1684}
1685
1686/// `materialSheen` — `MaterialNode.SHEEN`'s two halves. Three multiplies them
1687/// in the shader (`sheenColor.mul( sheen )`, with its own "Move this mul() to
1688/// CPU" note beside it), and the dumps carry both uniforms, so the port does
1689/// the same.
1690pub fn material_sheen() -> NodeRef {
1691    uniform(
1692        UniformSource::MaterialSheen,
1693        Type::F32,
1694        UniformGroup::Object,
1695        None,
1696    )
1697}
1698
1699pub(crate) fn material_sheen_color() -> NodeRef {
1700    uniform(
1701        UniformSource::MaterialSheenColor,
1702        Type::Vec3,
1703        UniformGroup::Object,
1704        None,
1705    )
1706}
1707
1708/// `materialSheenRoughness` — the raw uniform. `MaterialNode.SHEEN_ROUGHNESS`
1709/// clamps it to `[ 0.0001, 1 ]`; see [`crate::materials::setup`].
1710pub fn material_sheen_roughness() -> NodeRef {
1711    uniform(
1712        UniformSource::MaterialSheenRoughness,
1713        Type::F32,
1714        UniformGroup::Object,
1715        None,
1716    )
1717}
1718
1719/// `materialIridescence` — `MaterialNode.IRIDESCENCE`, the bare uniform:
1720/// three gives it no map branch (glTF's `iridescenceTexture` reaches
1721/// `material.iridescenceMap` and is then never read).
1722pub fn material_iridescence() -> NodeRef {
1723    uniform(
1724        UniformSource::MaterialIridescence,
1725        Type::F32,
1726        UniformGroup::Object,
1727        None,
1728    )
1729}
1730
1731/// `materialIridescenceIOR` — `MaterialNode.IRIDESCENCE_IOR`.
1732pub fn material_iridescence_ior() -> NodeRef {
1733    uniform(
1734        UniformSource::MaterialIridescenceIor,
1735        Type::F32,
1736        UniformGroup::Object,
1737        None,
1738    )
1739}
1740
1741/// `reference( '1', 'float', material.iridescenceThicknessRange )` — the
1742/// maximum film thickness, which `MaterialNode.IRIDESCENCE_THICKNESS` builds
1743/// first and, with no thickness map, reads alone.
1744pub fn material_iridescence_thickness_max() -> NodeRef {
1745    uniform(
1746        UniformSource::MaterialIridescenceThicknessMax,
1747        Type::F32,
1748        UniformGroup::Object,
1749        None,
1750    )
1751}
1752
1753/// `reference( '0', 'float', material.iridescenceThicknessRange )` — the
1754/// minimum film thickness, read only with a thickness map.
1755pub fn material_iridescence_thickness_min() -> NodeRef {
1756    uniform(
1757        UniformSource::MaterialIridescenceThicknessMin,
1758        Type::F32,
1759        UniformGroup::Object,
1760        None,
1761    )
1762}
1763
1764/// `materialDiffuseRoughness` — `MaterialNode.DIFFUSE_ROUGHNESS` without a
1765/// map, the raw uniform. `setupVariants()` clamps it into `DiffuseRoughness`.
1766pub fn material_diffuse_roughness() -> NodeRef {
1767    uniform(
1768        UniformSource::MaterialDiffuseRoughness,
1769        Type::F32,
1770        UniformGroup::Object,
1771        None,
1772    )
1773}
1774
1775/// `materialNormalScale` — a `vec2`.
1776/// `materialAnisotropyVector` — `vec2( anisotropy * cos( anisotropyRotation ),
1777/// anisotropy * sin( anisotropyRotation ) )`, which three keeps as one uniform
1778/// (`MaterialProperties.js` updates it from the two material fields).
1779pub fn material_anisotropy_vector() -> NodeRef {
1780    uniform(
1781        UniformSource::MaterialAnisotropyVector,
1782        Type::Vec2,
1783        UniformGroup::Object,
1784        None,
1785    )
1786}
1787
1788/// `materialClearcoat`.
1789pub fn material_clearcoat() -> NodeRef {
1790    uniform(
1791        UniformSource::MaterialClearcoat,
1792        Type::F32,
1793        UniformGroup::Object,
1794        None,
1795    )
1796}
1797
1798/// `materialClearcoatRoughness`.
1799pub fn material_clearcoat_roughness() -> NodeRef {
1800    uniform(
1801        UniformSource::MaterialClearcoatRoughness,
1802        Type::F32,
1803        UniformGroup::Object,
1804        None,
1805    )
1806}
1807
1808/// `materialTransmission`.
1809pub fn material_transmission() -> NodeRef {
1810    uniform(
1811        UniformSource::MaterialTransmission,
1812        Type::F32,
1813        UniformGroup::Object,
1814        None,
1815    )
1816}
1817
1818/// `materialThickness`.
1819pub fn material_thickness() -> NodeRef {
1820    uniform(
1821        UniformSource::MaterialThickness,
1822        Type::F32,
1823        UniformGroup::Object,
1824        None,
1825    )
1826}
1827
1828/// `materialAttenuationDistance`.
1829pub fn material_attenuation_distance() -> NodeRef {
1830    uniform(
1831        UniformSource::MaterialAttenuationDistance,
1832        Type::F32,
1833        UniformGroup::Object,
1834        None,
1835    )
1836}
1837
1838/// `materialAttenuationColor`.
1839pub fn material_attenuation_color() -> NodeRef {
1840    uniform(
1841        UniformSource::MaterialAttenuationColor,
1842        Type::Vec3,
1843        UniformGroup::Object,
1844        None,
1845    )
1846}
1847
1848/// `materialClearcoatNormalScale`.
1849pub(crate) fn material_clearcoat_normal_scale() -> NodeRef {
1850    uniform(
1851        UniformSource::MaterialClearcoatNormalScale,
1852        Type::Vec2,
1853        UniformGroup::Object,
1854        None,
1855    )
1856}
1857
1858pub(crate) fn material_normal_scale() -> NodeRef {
1859    uniform(
1860        UniformSource::MaterialNormalScale,
1861        Type::Vec2,
1862        UniformGroup::Object,
1863        None,
1864    )
1865}
1866
1867/// `materialRoughness`.
1868pub fn material_roughness() -> NodeRef {
1869    uniform(
1870        UniformSource::MaterialRoughness,
1871        Type::F32,
1872        UniformGroup::Object,
1873        None,
1874    )
1875}
1876
1877/// `materialMetalness` as `MaterialNode.setup()` builds it for the material
1878/// being set up: `material.metalness`, times `metalnessMap.b` when the
1879/// material has a map (glTF packs metalness in blue).
1880///
1881/// [`material_metalness`] is the uniform alone. This is the node three's
1882/// `materialMetalness` stands for in a graph, and the one a deferred MRT
1883/// output reads, as `webgpu_postprocessing_ssr_denoise`'s `vec4(
1884/// diffuseColor.rgb, materialMetalness )` does. Within one material setup
1885/// every call returns the same node, which the material's own `Metalness`
1886/// also reads, so the map is sampled once. Outside a material setup it is
1887/// the uniform.
1888pub fn material_metalness_value() -> NodeRef {
1889    current_context(|cx| cx.material_metalness.clone()).unwrap_or_else(material_metalness)
1890}
1891
1892/// `materialRoughness` as `MaterialNode.setup()` builds it for the material
1893/// being set up: `material.roughness`, times `roughnessMap.g` when the
1894/// material has a map. The unclamped value, before `getRoughness()` adds the
1895/// geometry term; see [`material_metalness_value`] for when to use it.
1896pub fn material_roughness_value() -> NodeRef {
1897    current_context(|cx| cx.material_roughness.clone()).unwrap_or_else(material_roughness)
1898}
1899
1900/// Install the material's `materialMetalness` / `materialRoughness` nodes for
1901/// the duration of `f`.
1902pub(crate) fn with_material_values<R>(
1903    metalness: NodeRef,
1904    roughness: NodeRef,
1905    f: impl FnOnce() -> R,
1906) -> R {
1907    let _values = push_context(|cx| {
1908        cx.material_metalness = Some(metalness);
1909        cx.material_roughness = Some(roughness);
1910    });
1911    f()
1912}
1913
1914/// `materialBumpScale`.
1915pub(crate) fn material_bump_scale() -> NodeRef {
1916    uniform(
1917        UniformSource::MaterialBumpScale,
1918        Type::F32,
1919        UniformGroup::Object,
1920        None,
1921    )
1922}
1923
1924/// `toneMappingExposure` — `RenderOutputNode`'s render-group `f32`.
1925pub fn tone_mapping_exposure() -> NodeRef {
1926    uniform(
1927        UniformSource::ToneMappingExposure,
1928        Type::F32,
1929        UniformGroup::Render,
1930        None,
1931    )
1932}
1933
1934/// `inverseSqrt( x )`.
1935pub fn inverse_sqrt(x: impl Into<NodeRef>) -> NodeRef {
1936    math("inverseSqrt", vec![x.into()], Type::F32)
1937}
1938
1939/// `AccessorsUtils.js`' `TBNViewMatrix` — `mat3( tangentView, bitangentView,
1940/// normalView ).toVar( 'TBNViewMatrix' )`. Three tags it with whichever
1941/// sub-build layers its descendants declare, which is why the centre teapot's
1942/// dump calls it `NORMAL_TBNViewMatrix`; here the layer is simply still open.
1943pub fn tbn_view_matrix() -> NodeRef {
1944    // Keyed like `tangentView` and `normalWorld`, and for the same reason: the
1945    // frame it joins depends on the material's side, so a singleton would bake
1946    // in whichever material was built first.
1947    thread_local! {
1948        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
1949    }
1950    let key = normal_key();
1951    if let Some(node) = CELL.with(|m| m.borrow().get(&key).cloned()) {
1952        return node;
1953    }
1954    let node = to_var(
1955        Some("TBNViewMatrix"),
1956        join(
1957            Type::Mat3,
1958            vec![tangent_view(), bitangent_view(), normal_view()],
1959        ),
1960    );
1961    CELL.with(|m| m.borrow_mut().insert(key, node.clone()));
1962    node
1963}
1964
1965/// Port of `NormalMapNode` for `TangentSpaceNormalMap` with no scale:
1966/// `normalize( TBNViewMatrix * ( texel * 2 - 1 ).xyz )`.
1967///
1968/// The whole expression is built inside the `NORMAL` sub-build layer, the way
1969/// `NodeMaterial.setup()` wraps `setupNormal()` in `subBuild( …, 'NORMAL' )`:
1970/// that is what stops `normalView` inside the TBN frame from recursing into
1971/// this node, and what prefixes the four vars the layer names.
1972pub fn normal_map(node: impl Into<NodeRef>) -> NodeRef {
1973    let texel = node.into();
1974    in_sub_build("NORMAL", || {
1975        tbn_view_matrix()
1976            .mul(texel.mul(2.0).sub(1.0).xyz())
1977            .normalize()
1978    })
1979}
1980
1981/// `normalMap( node, scale )` — the `scaleNode` branch of `NormalMapNode`:
1982/// `vec3( ( texel * 2 - 1 ).xy * scale, ( texel * 2 - 1 ).z )` through the TBN.
1983///
1984/// The unpacked texel is read twice, so it lands in a var of its own; the
1985/// no-scale [`normal_map`] reads it once and does not.
1986pub fn normal_map_scaled(node: impl Into<NodeRef>, scale: NodeRef) -> NodeRef {
1987    let texel = node.into();
1988    in_sub_build("NORMAL", || normal_map_scaled_unlayered(texel, scale))
1989}
1990
1991/// [`normal_map_scaled`] outside the `NORMAL` layer — `NormalMapNode` as it
1992/// builds in a graph `setupNormal()` does not wrap, such as a
1993/// `fragmentNode`'s [`material_normal`].
1994fn normal_map_scaled_unlayered(texel: NodeRef, scale: NodeRef) -> NodeRef {
1995    let unpacked = to_var(None, texel.mul(2.0).sub(1.0));
1996    tbn_view_matrix()
1997        .mul(vec3_join(vec![unpacked.xy().mul(scale), unpacked.z()]))
1998        .normalize()
1999}
2000
2001/// `sqrt( x )`.
2002pub fn sqrt(x: impl Into<NodeRef>) -> NodeRef {
2003    let x = x.into();
2004    let ty = x.ty();
2005    math("sqrt", vec![x], ty)
2006}
2007
2008/// `max( a, b )`.
2009pub fn max(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
2010    let a = a.into();
2011    let ty = a.ty();
2012    math("max", vec![a, b.into()], ty)
2013}
2014
2015// ---------------------------------------------------------------------------
2016// the fluent surface
2017// ---------------------------------------------------------------------------
2018
2019/// The canonical swizzle for a whole value of this type — `SplitNode` collapses
2020/// `.rgb` on a `vec3` to nothing, which is why the dumped shaders read
2021/// `dot( nodeVar0.xyz, … )` and not `nodeVar0.xyz.xyz`.
2022fn whole(ty: Type) -> &'static str {
2023    match ty.components() {
2024        1 => "x",
2025        2 => "xy",
2026        3 => "xyz",
2027        _ => "xyzw",
2028    }
2029}
2030
2031fn swizzle(node: NodeRef, components: &'static str) -> NodeRef {
2032    if components == whole(node.ty()) {
2033        return node;
2034    }
2035    // `SplitNode.generate()` on a `float` / `int` / `uint`: "ignore
2036    // .components if .node returns float/integer" — the scalar is built at
2037    // the swizzle's own type, which `builder.format()` widens by splatting
2038    // (`vec3<f32>( s )`). `.y` on a scalar is the scalar itself.
2039    if node.ty().components() == 1 {
2040        let ty = Type::vector_of(node.ty().component_type(), components.len());
2041        return node.to(ty);
2042    }
2043    let ty = Type::vector_of(node.ty().component_type(), components.len());
2044    NodeRef::new(Node::Swizzle {
2045        node,
2046        components,
2047        ty,
2048    })
2049}
2050
2051/// `node.rgb` as three's swizzle getter builds it: a `SplitNode` cached on
2052/// its node, kept even when it names the whole vector. [`swizzle`] collapses
2053/// that case into the node itself, which is the same WGSL at one read but not
2054/// at two: the shared `SplitNode` is what is counted twice, and as it is no
2055/// `TempNode` neither it nor its node becomes a var. The builder drops the
2056/// unnecessary suffix when it generates it (`SplitNode.generate()`).
2057fn cached_rgb(node: NodeRef) -> NodeRef {
2058    if node.ty().components() != 3 {
2059        return swizzle(node, "xyz");
2060    }
2061    let ty = Type::vector_of(node.ty().component_type(), 3);
2062    NodeRef::new(Node::Swizzle {
2063        node,
2064        components: "xyz",
2065        ty,
2066    })
2067}
2068
2069impl NodeRef {
2070    // --- arithmetic ---
2071    /// `a.add( b )` — `a + b`.
2072    pub fn add(&self, other: impl Into<NodeRef>) -> NodeRef {
2073        binary("+", self.clone(), other.into())
2074    }
2075    /// `a.sub( b )` — `a - b`.
2076    pub fn sub(&self, other: impl Into<NodeRef>) -> NodeRef {
2077        binary("-", self.clone(), other.into())
2078    }
2079    /// `a.mul( b )` — `a * b`.
2080    pub fn mul(&self, other: impl Into<NodeRef>) -> NodeRef {
2081        binary("*", self.clone(), other.into())
2082    }
2083    /// `a.div( b )` — `a / b`.
2084    pub fn div(&self, other: impl Into<NodeRef>) -> NodeRef {
2085        binary("/", self.clone(), other.into())
2086    }
2087    /// `OperatorNode( '%' )` — integer remainder. (`MathNode`'s float `mod`
2088    /// is [`mod_float`], which lowers to a helper instead.)
2089    pub fn modulo(&self, other: impl Into<NodeRef>) -> NodeRef {
2090        binary("%", self.clone(), other.into())
2091    }
2092    /// `a.equal( b )` — `a == b`.
2093    pub fn equal(&self, other: impl Into<NodeRef>) -> NodeRef {
2094        binary("==", self.clone(), other.into())
2095    }
2096    /// `a.notEqual( b )` — `a != b`.
2097    pub fn not_equal(&self, other: impl Into<NodeRef>) -> NodeRef {
2098        binary("!=", self.clone(), other.into())
2099    }
2100    /// `a.lessThanEqual( b )` — `a <= b`.
2101    pub fn less_than_equal(&self, other: impl Into<NodeRef>) -> NodeRef {
2102        binary("<=", self.clone(), other.into())
2103    }
2104    /// `a.greaterThan( b )` — `a > b`.
2105    pub fn greater_than(&self, other: impl Into<NodeRef>) -> NodeRef {
2106        binary(">", self.clone(), other.into())
2107    }
2108    /// `a.greaterThanEqual( b )` — `a >= b`.
2109    pub fn greater_than_equal(&self, other: impl Into<NodeRef>) -> NodeRef {
2110        binary(">=", self.clone(), other.into())
2111    }
2112    /// `a.lessThan( b )` — `a < b`.
2113    pub fn less_than(&self, other: impl Into<NodeRef>) -> NodeRef {
2114        binary("<", self.clone(), other.into())
2115    }
2116    /// `a.and( b )` — `a && b`.
2117    pub fn and(&self, other: impl Into<NodeRef>) -> NodeRef {
2118        binary("&&", self.clone(), other.into())
2119    }
2120    /// `a.or( b )` — `a || b`.
2121    pub fn or(&self, other: impl Into<NodeRef>) -> NodeRef {
2122        binary("||", self.clone(), other.into())
2123    }
2124    /// `x.not()` — `( ! x )`.
2125    pub fn not(&self) -> NodeRef {
2126        NodeRef::new(Node::Not { node: self.clone() })
2127    }
2128    // --- bitwise (the MaterialX integer hashes) ---
2129    /// `a.shiftLeft( b )` — `a << b`.
2130    pub fn shift_left(&self, other: impl Into<NodeRef>) -> NodeRef {
2131        binary("<<", self.clone(), other.into())
2132    }
2133    /// `a.shiftRight( b )` — `a >> b`.
2134    pub fn shift_right(&self, other: impl Into<NodeRef>) -> NodeRef {
2135        binary(">>", self.clone(), other.into())
2136    }
2137    /// `a.bitAnd( b )` — `a & b`.
2138    pub fn bit_and(&self, other: impl Into<NodeRef>) -> NodeRef {
2139        binary("&", self.clone(), other.into())
2140    }
2141    /// `a.bitOr( b )` — `a | b`.
2142    pub fn bit_or(&self, other: impl Into<NodeRef>) -> NodeRef {
2143        binary("|", self.clone(), other.into())
2144    }
2145    /// `a.bitXor( b )` — `a ^ b`.
2146    pub fn bit_xor(&self, other: impl Into<NodeRef>) -> NodeRef {
2147        binary("^", self.clone(), other.into())
2148    }
2149
2150    /// `oneMinus()` — `1.0 - x`, emitted in that order.
2151    pub fn one_minus(&self) -> NodeRef {
2152        binary("-", float(1.0), self.clone())
2153    }
2154
2155    /// `x.negate()` — `-x`.
2156    pub fn negate(&self) -> NodeRef {
2157        NodeRef::new(Node::Neg {
2158            node: self.clone(),
2159            ty: self.ty(),
2160        })
2161    }
2162
2163    // --- builtins ---
2164    /// `x.normalize()` — `MathNode.NORMALIZE`.
2165    pub fn normalize(&self) -> NodeRef {
2166        math("normalize", vec![self.clone()], self.ty())
2167    }
2168    /// `x.cos()` — `MathNode.COS`.
2169    pub fn cos(&self) -> NodeRef {
2170        math("cos", vec![self.clone()], self.ty())
2171    }
2172    /// `x.sin()` — `MathNode.SIN`.
2173    pub fn sin(&self) -> NodeRef {
2174        math("sin", vec![self.clone()], self.ty())
2175    }
2176    /// `x.asin()` — `MathNode.ASIN`.
2177    pub fn asin(&self) -> NodeRef {
2178        math("asin", vec![self.clone()], self.ty())
2179    }
2180    /// `y.atan( x )` — `MathNode.ATAN` with two arguments, which WGSL spells
2181    /// `atan2( y, x )`. The receiver is the numerator, as in TSL.
2182    pub fn atan2(&self, x: impl Into<NodeRef>) -> NodeRef {
2183        math("atan2", vec![self.clone(), x.into()], self.ty())
2184    }
2185    /// `x.floor()` — `MathNode.FLOOR`.
2186    pub fn floor(&self) -> NodeRef {
2187        math("floor", vec![self.clone()], self.ty())
2188    }
2189    /// `x.fract()` — `MathNode.FRACT`.
2190    pub fn fract(&self) -> NodeRef {
2191        math("fract", vec![self.clone()], self.ty())
2192    }
2193    /// `x.sqrt()` — `MathNode.SQRT`.
2194    pub fn sqrt(&self) -> NodeRef {
2195        math("sqrt", vec![self.clone()], self.ty())
2196    }
2197    /// `x.abs()` — `MathNode.ABS`.
2198    pub fn abs(&self) -> NodeRef {
2199        math("abs", vec![self.clone()], self.ty())
2200    }
2201    /// `saturate()` — `clamp( x, 0, 1 )`, which three.js emits with vector
2202    /// bounds when `x` is a vector.
2203    pub fn saturate(&self) -> NodeRef {
2204        let ty = self.ty();
2205        let lo = if ty.components() > 1 {
2206            constant(ty, vec![0.0; ty.components()])
2207        } else {
2208            float(0.0)
2209        };
2210        let hi = if ty.components() > 1 {
2211            constant(ty, vec![1.0; ty.components()])
2212        } else {
2213            float(1.0)
2214        };
2215        math("clamp", vec![self.clone(), lo, hi], ty)
2216    }
2217    /// `x.pow( y )` — `MathNode.POW`.
2218    pub fn pow(&self, other: impl Into<NodeRef>) -> NodeRef {
2219        math("pow", vec![self.clone(), other.into()], self.ty())
2220    }
2221    /// `pow3( x )` — `MathNode`'s `POW3` is the multiplication chain
2222    /// `x * x * x`, not a `pow()` call.
2223    pub fn pow3(&self) -> NodeRef {
2224        self.mul(self.clone()).mul(self.clone())
2225    }
2226
2227    /// `node.reciprocal()` — `1.0 / node`, which is how `OperatorNode` prints it.
2228    pub fn reciprocal(&self) -> NodeRef {
2229        float(1.0).div(self.clone())
2230    }
2231
2232    /// `x.exp2()` — see [`exp2`].
2233    pub fn exp2(&self) -> NodeRef {
2234        exp2(self.clone())
2235    }
2236    /// `x.max( y )` — `MathNode.MAX`.
2237    pub fn max(&self, other: impl Into<NodeRef>) -> NodeRef {
2238        math("max", vec![self.clone(), other.into()], self.ty())
2239    }
2240    /// `x.min( y )` — `MathNode.MIN`.
2241    pub fn min(&self, other: impl Into<NodeRef>) -> NodeRef {
2242        math("min", vec![self.clone(), other.into()], self.ty())
2243    }
2244    /// `x.clamp( lo, hi )` — `MathNode.CLAMP`.
2245    pub fn clamp(&self, lo: impl Into<NodeRef>, hi: impl Into<NodeRef>) -> NodeRef {
2246        math("clamp", vec![self.clone(), lo.into(), hi.into()], self.ty())
2247    }
2248    /// `a.dot( b )` — see [`dot`].
2249    pub fn dot(&self, other: impl Into<NodeRef>) -> NodeRef {
2250        dot(self.clone(), other)
2251    }
2252    /// `a.cross( b )` — see [`cross`].
2253    pub fn cross(&self, other: impl Into<NodeRef>) -> NodeRef {
2254        cross(self.clone(), other)
2255    }
2256    /// `adjustment.mix( a, b )` — see [`mix`].
2257    pub fn mix(&self, a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
2258        // `adjustment.mix( a, b )` in TSL means `mix( a, b, adjustment )`.
2259        mix(a, b, self.clone())
2260    }
2261
2262    // --- swizzles ---
2263    /// `node[ components ]` — the general form of `.x` / `.xy` / `.rgb`, for
2264    /// when the component is chosen at build time.
2265    pub fn swizzle(&self, components: &'static str) -> NodeRef {
2266        swizzle(self.clone(), components)
2267    }
2268
2269    /// `node.x` — the first component.
2270    pub fn x(&self) -> NodeRef {
2271        swizzle(self.clone(), "x")
2272    }
2273    /// `node.y` — the second component.
2274    pub fn y(&self) -> NodeRef {
2275        swizzle(self.clone(), "y")
2276    }
2277    /// `node.z` — the third component.
2278    pub fn z(&self) -> NodeRef {
2279        swizzle(self.clone(), "z")
2280    }
2281    /// `node.w` — the fourth component.
2282    pub fn w(&self) -> NodeRef {
2283        swizzle(self.clone(), "w")
2284    }
2285    /// `node.xy` — the first two components.
2286    pub fn xy(&self) -> NodeRef {
2287        swizzle(self.clone(), "xy")
2288    }
2289    /// `node.yz` — the second and third components.
2290    pub fn yz(&self) -> NodeRef {
2291        swizzle(self.clone(), "yz")
2292    }
2293    /// `node.zw` — the third and fourth components.
2294    pub fn zw(&self) -> NodeRef {
2295        swizzle(self.clone(), "zw")
2296    }
2297    /// `node.zx` — the third and first components.
2298    pub fn zx(&self) -> NodeRef {
2299        swizzle(self.clone(), "zx")
2300    }
2301    /// `node.xyz` — the first three components.
2302    pub fn xyz(&self) -> NodeRef {
2303        swizzle(self.clone(), "xyz")
2304    }
2305    /// `node.xz` — the first and third components.
2306    pub fn xz(&self) -> NodeRef {
2307        swizzle(self.clone(), "xz")
2308    }
2309    /// `node.zzz` — the third component broadcast to a `vec3`.
2310    pub fn zzz(&self) -> NodeRef {
2311        swizzle(self.clone(), "zzz")
2312    }
2313    /// `node.rgb` — the first three components, spelled for a color.
2314    pub fn rgb(&self) -> NodeRef {
2315        swizzle(self.clone(), "xyz")
2316    }
2317    /// `node.a` — the fourth component, spelled for a color's alpha.
2318    pub fn a(&self) -> NodeRef {
2319        swizzle(self.clone(), "w")
2320    }
2321
2322    /// `vec4( node.x, node.y, z, node.w )` — `SetNode` for `.setZ()`.
2323    pub fn set_z(&self, z: impl Into<NodeRef>) -> NodeRef {
2324        join(Type::Vec4, vec![self.x(), self.y(), z.into(), self.w()])
2325    }
2326
2327    // --- conversion ---
2328    /// `type( node )` — cast to another type, a no-op if `node` is already `ty`.
2329    pub fn to(&self, ty: Type) -> NodeRef {
2330        if self.ty() == ty {
2331            return self.clone();
2332        }
2333        NodeRef::new(Node::Cast {
2334            node: self.clone(),
2335            ty,
2336        })
2337    }
2338
2339    /// `m.element( i )` — a matrix column, or a vector component.
2340    pub fn element(&self, index: usize) -> NodeRef {
2341        let ty = match self.ty() {
2342            Type::Mat4 => Type::Vec4,
2343            Type::Mat3 => Type::Vec3,
2344            Type::Mat2 => Type::Vec2,
2345            other => other.component_type(),
2346        };
2347        NodeRef::new(Node::Element {
2348            node: self.clone(),
2349            index: constant(Type::U32, vec![index as f64]),
2350            ty,
2351        })
2352    }
2353
2354    /// `array( … ).element( node )`.
2355    pub fn element_node(&self, index: NodeRef) -> NodeRef {
2356        let ty = match self.ty() {
2357            Type::Mat4 => Type::Vec4,
2358            Type::Mat3 => Type::Vec3,
2359            Type::Mat2 => Type::Vec2,
2360            // An `array< T, N >`'s element is a whole `T`; indexing anything
2361            // else is a *vector component*, so it is one scalar
2362            // (`ArrayElementNode.getNodeType()` over `getElementType()`).
2363            // Without the distinction a `vec2`'s `[ 0 ]` claims to be a
2364            // `vec2`, which `NodeBuilder.format()` then swizzles down —
2365            // `nodeVar1[ 0 ].x`, which three does not emit.
2366            other if matches!(self.node(), Node::ConstArray { .. } | Node::ArrayVar { .. }) => {
2367                other
2368            }
2369            other => other.component_type(),
2370        };
2371        NodeRef::new(Node::Element {
2372            node: self.clone(),
2373            index,
2374            ty,
2375        })
2376    }
2377
2378    /// `cond.select( a, b )`.
2379    pub fn select(&self, a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
2380        let a = a.into();
2381        let ty = a.ty();
2382        NodeRef::new(Node::Select {
2383            cond: self.clone(),
2384            a,
2385            b: b.into(),
2386            ty,
2387        })
2388    }
2389
2390    /// `.flipY()` — `FlipNode` over the y component: `vec2( v.x, 1.0 - v.y )`.
2391    ///
2392    /// `FlipNode.generate()` does not ask the usage counter for a temp, it
2393    /// takes one unconditionally (`builder.getVarFromNode( this )`) and assigns
2394    /// the *source* snippet into it, because it has to read two components of
2395    /// the source and will not evaluate it twice. So the var here is explicit
2396    /// rather than a `needs_var` promotion, and it is the flip's var, not the
2397    /// source's.
2398    ///
2399    /// **Divergence, cosmetic** (`docs/nodes.md` §8): three writes the flipped
2400    /// component as the bare string `1.0 - v.y`; the port builds it out of
2401    /// `sub`, so it comes out parenthesised as `( 1.0 - v.y )`. Same value,
2402    /// two characters more.
2403    pub fn flip_y(&self) -> NodeRef {
2404        let source = to_var(None, self.clone());
2405        match self.ty() {
2406            Type::Vec2 => vec2_join(vec![source.x(), float(1.0).sub(source.y())]),
2407            Type::Vec3 => vec3_join(vec![source.x(), float(1.0).sub(source.y()), source.z()]),
2408            Type::Vec4 => vec4_join(vec![
2409                source.x(),
2410                float(1.0).sub(source.y()),
2411                source.z(),
2412                source.w(),
2413            ]),
2414            ty => panic!("flipY() on a {ty:?}"),
2415        }
2416    }
2417
2418    /// `.flipX()` — `FlipNode` over the x component: `vec2( 1.0 - v.x, v.y )`.
2419    /// Same var and same cosmetic parenthesisation as [`flip_y`](Self::flip_y);
2420    /// `ReflectorNode`'s default uv, `screenUV.flipX()`, is the caller.
2421    pub fn flip_x(&self) -> NodeRef {
2422        let source = to_var(None, self.clone());
2423        match self.ty() {
2424            Type::Vec2 => vec2_join(vec![float(1.0).sub(source.x()), source.y()]),
2425            Type::Vec3 => vec3_join(vec![float(1.0).sub(source.x()), source.y(), source.z()]),
2426            Type::Vec4 => vec4_join(vec![
2427                float(1.0).sub(source.x()),
2428                source.y(),
2429                source.z(),
2430                source.w(),
2431            ]),
2432            ty => panic!("flipX() on a {ty:?}"),
2433        }
2434    }
2435
2436    /// `node.toVar( name )` — see [`to_var`].
2437    pub fn to_var(&self, name: &'static str) -> NodeRef {
2438        to_var(Some(name), self.clone())
2439    }
2440
2441    /// `node.context( { … } )` — see [`context`].
2442    pub fn context(&self, value: ContextValue) -> NodeRef {
2443        context(self.clone(), value)
2444    }
2445
2446    /// `node.isolate()` — see [`isolate`].
2447    pub fn isolate(&self) -> NodeRef {
2448        isolate(self.clone())
2449    }
2450
2451    /// `node.toVarying( name )` — see [`to_varying`].
2452    pub fn to_varying(&self, name: &'static str) -> NodeRef {
2453        to_varying(Some(name), self.clone())
2454    }
2455
2456    /// `target.addAssign( value )` — `target = ( target + value )`.
2457    pub fn add_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
2458        self.assign(self.add(value))
2459    }
2460
2461    /// `target.subAssign( value )` — `target = ( target - value )`.
2462    pub fn sub_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
2463        self.assign(self.sub(value))
2464    }
2465
2466    /// `target.mulAssign( value )` — `target = ( target * value )`.
2467    pub fn mul_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
2468        self.assign(self.mul(value))
2469    }
2470
2471    /// `target.divAssign( value )` — `target = ( target / value )`.
2472    pub fn div_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
2473        self.assign(self.div(value))
2474    }
2475
2476    /// `target.assign( value )` — a statement.
2477    pub fn assign(&self, value: impl Into<NodeRef>) -> NodeRef {
2478        NodeRef::new(Node::Assign {
2479            target: self.clone(),
2480            value: value.into(),
2481        })
2482    }
2483}
2484
2485// ---------------------------------------------------------------------------
2486// accessors (`three.js/src/nodes/accessors/`)
2487// ---------------------------------------------------------------------------
2488
2489/// A module-level TSL constant: one node per thread, built on first use.
2490///
2491/// The body is built with no sub-build layer open, whoever asks first. Three's
2492/// constants are created at import, outside any layer, so `modelViewMatrix`
2493/// stays `modelViewMatrix` even when the `VERTEX` layer of [`tangent_world`]
2494/// is the first to reach it.
2495macro_rules! accessor {
2496    ($(#[$m:meta])* pub(crate) $name:ident, $body:expr) => {
2497        $(#[$m])*
2498        pub(crate) fn $name() -> NodeRef {
2499            thread_local! {
2500                static CELL: Lazy<NodeRef> = const { Lazy::new() };
2501            }
2502            CELL.with(|c| c.get(|| outside_sub_build(|| $body)))
2503        }
2504    };
2505    ($(#[$m:meta])* $name:ident, $body:expr) => {
2506        $(#[$m])*
2507        pub fn $name() -> NodeRef {
2508            thread_local! {
2509                static CELL: Lazy<NodeRef> = const { Lazy::new() };
2510            }
2511            CELL.with(|c| c.get(|| outside_sub_build(|| $body)))
2512        }
2513    };
2514}
2515
2516/// Run `f` with no sub-build layer open — see [`accessor!`].
2517fn outside_sub_build<R>(f: impl FnOnce() -> R) -> R {
2518    let _top = push_context(|cx| cx.sub_build = None);
2519    f()
2520}
2521
2522accessor!(
2523    /// `positionGeometry` — the `position` attribute.
2524    position_geometry,
2525    attribute("position", Type::Vec3)
2526);
2527accessor!(
2528    /// `normalGeometry` — the `normal` attribute.
2529    normal_geometry,
2530    attribute("normal", Type::Vec3)
2531);
2532accessor!(
2533    /// `uv()` — the `uv` attribute, interpolated.
2534    uv,
2535    to_varying(None, attribute("uv", Type::Vec2))
2536);
2537accessor!(
2538    /// `uv( 1 )` — the `uv1` attribute (glTF's `TEXCOORD_1`), interpolated.
2539    /// `TextureNode.getDefaultUV()` picks between this and [`uv`] by the
2540    /// texture's [`channel`](crate::textures::Texture::channel).
2541    uv1,
2542    to_varying(None, attribute("uv1", Type::Vec2))
2543);
2544accessor!(
2545    /// `vertexColor()` over a three-component `color` attribute, widened to a
2546    /// `vec4` with an alpha of 1. See [`vertex_color`].
2547    pub(crate) vertex_color_rgb,
2548    to_varying(
2549        None,
2550        vec4_join(vec![attribute("color", Type::Vec3), float(1.0)])
2551    )
2552);
2553accessor!(
2554    /// `vertexColor()` over a four-component `color` attribute — three's
2555    /// `vertexAlphas`. See [`vertex_color`].
2556    pub(crate) vertex_color_rgba,
2557    to_varying(None, attribute("color", Type::Vec4))
2558);
2559
2560/// `vertexColor()` — `VertexColorNode`, the `color` attribute interpolated.
2561///
2562/// `VertexColorNode.generate()` declares the node as `vec4` and takes the
2563/// attribute's own type from the geometry
2564/// (`builder.getTypeFromAttribute( geometryAttribute )`), so a three-component
2565/// attribute is widened with an alpha of 1 and a four-component one is read
2566/// whole. glTF `COLOR_0` is either; `PrimaryIonDrive.glb`'s is `VEC4`, which is
2567/// the `float32x4` at location 0 in three's dump of
2568/// `webgpu_postprocessing_bloom`. The widening happens *before* the varying, so
2569/// the interpolated value is a `vec4` both ways and the fragment stage reads it
2570/// whole.
2571///
2572/// **Divergence, deliberate** (`docs/nodes.md` §10): three's
2573/// `VertexColorNode.generate()` falls back to a white constant when the
2574/// geometry has no `color` attribute at all. The port decides on
2575/// `material.vertex_colors`, and the attribute has to be there.
2576pub fn vertex_color(item_size: usize) -> NodeRef {
2577    match item_size {
2578        4 => vertex_color_rgba(),
2579        _ => vertex_color_rgb(),
2580    }
2581}
2582accessor!(
2583    /// `vertexIndex`.
2584    vertex_index,
2585    NodeRef::new(Node::Builtin(Builtin::VertexIndex))
2586);
2587accessor!(
2588    /// `instanceIndex`.
2589    instance_index,
2590    NodeRef::new(Node::Builtin(Builtin::InstanceIndex))
2591);
2592accessor!(
2593    /// `invocationLocalIndex` — `@builtin( local_invocation_index )`, compute
2594    /// only; the entry point declares it only when a kernel reads it.
2595    invocation_local_index,
2596    NodeRef::new(Node::Builtin(Builtin::InvocationLocalIndex))
2597);
2598accessor!(
2599    /// `workgroupId` — `@builtin( workgroup_id )`, compute only.
2600    workgroup_id,
2601    NodeRef::new(Node::Builtin(Builtin::WorkgroupId))
2602);
2603accessor!(
2604    /// `localId` — `@builtin( local_invocation_id )`, compute only.
2605    local_id,
2606    NodeRef::new(Node::Builtin(Builtin::LocalId))
2607);
2608accessor!(
2609    /// `globalId` — `@builtin( global_invocation_id )`, compute only.
2610    global_id,
2611    NodeRef::new(Node::Builtin(Builtin::GlobalId))
2612);
2613accessor!(
2614    /// `numWorkgroups` — `@builtin( num_workgroups )`, compute only.
2615    num_workgroups,
2616    NodeRef::new(Node::Builtin(Builtin::NumWorkgroups))
2617);
2618accessor!(
2619    /// `subgroupSize` — `@builtin( subgroup_size )`, the number of invocations
2620    /// in a subgroup (`src/nodes/gpgpu/ComputeBuiltinNode.js:232`). Compute
2621    /// only, as in three; read in another stage it is three's warning and
2622    /// `0u`. A kernel that reads it gets `enable subgroups;` and needs a device
2623    /// with `wgpu::Features::SUBGROUP` — see [`subgroup_add`].
2624    subgroup_size,
2625    NodeRef::new(Node::Builtin(Builtin::SubgroupSize))
2626);
2627accessor!(
2628    /// `subgroupIndex` — `@builtin( subgroup_id )`, the index of the
2629    /// invocation's subgroup within its workgroup
2630    /// (`src/nodes/core/IndexNode.js:184`). Compute only: three reads it as an
2631    /// attribute builtin in the vertex stage and through a varying in the
2632    /// fragment stage, neither of which WGSL allows, so the port refuses both.
2633    subgroup_index,
2634    NodeRef::new(Node::Builtin(Builtin::SubgroupIndex))
2635);
2636accessor!(
2637    /// `invocationSubgroupIndex` — `@builtin( subgroup_invocation_id )`, the
2638    /// invocation's lane within its subgroup
2639    /// (`src/nodes/core/IndexNode.js:206`). Compute only, like
2640    /// [`subgroup_index`].
2641    invocation_subgroup_index,
2642    NodeRef::new(Node::Builtin(Builtin::InvocationSubgroupIndex))
2643);
2644accessor!(
2645    /// `frontFacing` — `@builtin( front_facing )`, fragment stage only.
2646    front_facing,
2647    NodeRef::new(Node::Builtin(Builtin::FrontFacing))
2648);
2649accessor!(
2650    /// `faceDirection` — `float( frontFacing ).mul( 2 ).sub( 1 )`: `1` on a
2651    /// front face, `-1` on a back face.
2652    face_direction,
2653    front_facing().to(Type::F32).mul(2.0).sub(1.0)
2654);
2655accessor!(
2656    /// `screenCoordinate`'s raw source: `@builtin( position )`.
2657    frag_coord,
2658    NodeRef::new(Node::Builtin(Builtin::FragCoord))
2659);
2660
2661accessor!(
2662    /// `cameraProjectionMatrix`.
2663    camera_projection_matrix,
2664    uniform(
2665        UniformSource::CameraProjectionMatrix,
2666        Type::Mat4,
2667        UniformGroup::Render,
2668        Some("cameraProjectionMatrix")
2669    )
2670);
2671accessor!(
2672    /// `cameraViewMatrix`.
2673    camera_view_matrix,
2674    uniform(
2675        UniformSource::CameraViewMatrix,
2676        Type::Mat4,
2677        UniformGroup::Render,
2678        Some("cameraViewMatrix")
2679    )
2680);
2681accessor!(
2682    /// `cameraWorldMatrix`.
2683    camera_world_matrix,
2684    uniform(
2685        UniformSource::CameraWorldMatrix,
2686        Type::Mat4,
2687        UniformGroup::Render,
2688        Some("cameraWorldMatrix")
2689    )
2690);
2691accessor!(
2692    /// `cameraPosition` — the camera's world position, a `vec3` of its own
2693    /// rather than a column of `cameraWorldMatrix`, because that is the
2694    /// uniform three declares and names.
2695    camera_position,
2696    uniform(
2697        UniformSource::CameraPosition,
2698        Type::Vec3,
2699        UniformGroup::Render,
2700        Some("cameraPosition")
2701    )
2702);
2703accessor!(
2704    /// `modelWorldMatrix`.
2705    model_world_matrix,
2706    uniform(
2707        UniformSource::ModelWorldMatrix,
2708        Type::Mat4,
2709        UniformGroup::Object,
2710        None
2711    )
2712);
2713accessor!(
2714    /// `modelNormalMatrix`.
2715    model_normal_matrix,
2716    uniform(
2717        UniformSource::ModelNormalMatrix,
2718        Type::Mat3,
2719        UniformGroup::Object,
2720        None
2721    )
2722);
2723accessor!(
2724    /// `materialColor`.
2725    material_color,
2726    uniform(
2727        UniformSource::MaterialColor,
2728        Type::Vec3,
2729        UniformGroup::Object,
2730        None
2731    )
2732);
2733accessor!(
2734    /// `materialOpacity`.
2735    material_opacity,
2736    uniform(
2737        UniformSource::MaterialOpacity,
2738        Type::F32,
2739        UniformGroup::Object,
2740        None
2741    )
2742);
2743accessor!(
2744    /// `materialAlphaTest`.
2745    material_alpha_test,
2746    uniform(
2747        UniformSource::MaterialAlphaTest,
2748        Type::F32,
2749        UniformGroup::Object,
2750        None
2751    )
2752);
2753accessor!(
2754    /// `materialRotation` — `SpriteMaterial.rotation`, the angle
2755    /// `SpriteNodeMaterial.setupPositionView()` rotates the quad by when the
2756    /// material sets no `rotationNode`.
2757    material_rotation,
2758    uniform(
2759        UniformSource::MaterialRotation,
2760        Type::F32,
2761        UniformGroup::Object,
2762        None
2763    )
2764);
2765accessor!(
2766    /// `materialShininess`.
2767    material_shininess,
2768    uniform(
2769        UniformSource::MaterialShininess,
2770        Type::F32,
2771        UniformGroup::Object,
2772        None
2773    )
2774);
2775accessor!(
2776    /// `materialSpecular`.
2777    material_specular,
2778    uniform(
2779        UniformSource::MaterialSpecular,
2780        Type::Vec3,
2781        UniformGroup::Object,
2782        None
2783    )
2784);
2785accessor!(
2786    /// `materialEmissive`.
2787    material_emissive,
2788    uniform(
2789        UniformSource::MaterialEmissive,
2790        Type::Vec3,
2791        UniformGroup::Object,
2792        None
2793    )
2794);
2795accessor!(
2796    /// `materialEmissiveIntensity`.
2797    pub(crate) material_emissive_intensity,
2798    uniform(
2799        UniformSource::MaterialEmissiveIntensity,
2800        Type::F32,
2801        UniformGroup::Object,
2802        None
2803    )
2804);
2805accessor!(
2806    /// `materialAOMapIntensity` — the `getFloat( 'aoMapIntensity' )` inside
2807    /// `MaterialNode.AO`.
2808    pub(crate) material_ao_map_intensity,
2809    uniform(
2810        UniformSource::MaterialAoMapIntensity,
2811        Type::F32,
2812        UniformGroup::Object,
2813        None
2814    )
2815);
2816accessor!(
2817    /// `materialLightMapIntensity` — the `getFloat( 'lightMapIntensity' )`
2818    /// inside `MaterialNode.LIGHT_MAP`.
2819    pub(crate) material_light_map_intensity,
2820    uniform(
2821        UniformSource::MaterialLightMapIntensity,
2822        Type::F32,
2823        UniformGroup::Object,
2824        None
2825    )
2826);
2827accessor!(
2828    /// `materialPointSize` — `PointsMaterial.size`, read from
2829    /// [`MeshBasicNodeMaterial::size`].
2830    material_point_size,
2831    uniform(
2832        UniformSource::MaterialPointSize,
2833        Type::F32,
2834        UniformGroup::Object,
2835        None
2836    )
2837);
2838
2839// `MaterialNode`'s map-dependent scopes. Three resolves them against
2840// `builder.material` while the graph builds; the port builds a graph before
2841// it knows its material, so these take the material and read its maps then.
2842// Build the node from the material it is set on.
2843
2844/// `builder.material.side` and `.flatShading` for the window in which a
2845/// [`material_normal`] / [`material_clearcoat_normal`] is built, which is
2846/// what three's build reads them from: the side for `negateOnBackSide()` in
2847/// the TBN frame and `normalView`, flat shading for `normalViewGeometry`.
2848/// `builder.geometry.hasAttribute( 'tangent' )` is not known until a mesh
2849/// draws the material, so it stays whatever the enclosing scope says —
2850/// outside a material setup, no tangent attribute (the derivative frame).
2851/// See `docs/nodes.md` §68.4.
2852fn with_material_normal_scope<R>(material: &MeshBasicNodeMaterial, f: impl FnOnce() -> R) -> R {
2853    let _material = push_context(|cx| {
2854        cx.material_side = material.side;
2855        cx.flat_shading = material.flat_shading;
2856    });
2857    f()
2858}
2859
2860/// `materialNormal` — `MaterialNode.NORMAL`: the material's `normalMap`
2861/// (scaled by `normalScale`), else its `bumpMap`, else `normalView`.
2862///
2863/// Built as three builds it in a `fragmentNode`: outside the `NORMAL`
2864/// sub-build `setupNormal()` opens, so the TBN frame's vars are unprefixed.
2865/// The material's `side` and `flat_shading` are read here, as three reads
2866/// them while it builds; a tangent attribute is not (`docs/nodes.md` §68.4).
2867pub fn material_normal(material: &MeshBasicNodeMaterial) -> NodeRef {
2868    with_material_normal_scope(material, || {
2869        match (&material.normal_map, &material.bump_map) {
2870            (Some(map), _) => normal_map_scaled_unlayered(texture(map), material_normal_scale()),
2871            (None, Some(bump)) => {
2872                bump_map_unlayered(|texture| texture(bump).x(), material_bump_scale())
2873            }
2874            (None, None) => normal_view(),
2875        }
2876    })
2877}
2878
2879/// `materialClearcoatNormal` — `MaterialNode.CLEARCOAT_NORMAL`: the
2880/// material's `clearcoatNormalMap` (scaled by `clearcoatNormalScale`), else
2881/// `normalView`. Side and flat shading as for [`material_normal`].
2882pub fn material_clearcoat_normal(material: &MeshBasicNodeMaterial) -> NodeRef {
2883    with_material_normal_scope(material, || match &material.clearcoat_normal_map {
2884        Some(map) => normal_map_scaled_unlayered(texture(map), material_clearcoat_normal_scale()),
2885        None => normal_view(),
2886    })
2887}
2888
2889/// `materialSpecularStrength` — `MaterialNode.SPECULAR_STRENGTH`: the
2890/// `specularMap`'s red channel, else `1`.
2891pub fn material_specular_strength(material: &MeshBasicNodeMaterial) -> NodeRef {
2892    match &material.specular_map {
2893        Some(map) => texture(map).x(),
2894        None => float(1.0),
2895    }
2896}
2897
2898/// `materialLightMap` — `MaterialNode.LIGHT_MAP`: the `lightMap`'s colour
2899/// times `lightMapIntensity`, else black.
2900pub fn material_light_map(material: &MeshBasicNodeMaterial) -> NodeRef {
2901    match &material.light_map {
2902        Some(map) => texture(map).rgb().mul(material_light_map_intensity()),
2903        None => vec3(0.0, 0.0, 0.0),
2904    }
2905}
2906
2907/// `materialAO` — `MaterialNode.AO`: `( aoMap.r - 1 ) * aoMapIntensity + 1`,
2908/// else `1`.
2909pub fn material_ao(material: &MeshBasicNodeMaterial) -> NodeRef {
2910    match &material.ao_map {
2911        Some(map) => texture(map)
2912            .x()
2913            .sub(float(1.0))
2914            .mul(material_ao_map_intensity())
2915            .add(float(1.0)),
2916        None => float(1.0),
2917    }
2918}
2919
2920accessor!(
2921    /// `materialEnvIntensity` — `MeshStandardMaterial.envMapIntensity`.
2922    material_env_intensity,
2923    uniform(
2924        UniformSource::MaterialEnvIntensity,
2925        Type::F32,
2926        UniformGroup::Object,
2927        None,
2928    )
2929);
2930accessor!(
2931    /// `materialReflectivity`.
2932    material_reflectivity,
2933    uniform(
2934        UniformSource::MaterialReflectivity,
2935        Type::F32,
2936        UniformGroup::Object,
2937        None
2938    )
2939);
2940accessor!(
2941    /// `materialRefractionRatio` — `uniform( 0 ).onObjectUpdate( ( { material
2942    /// } ) => material.refractionRatio )`: the material's
2943    /// [`refraction_ratio`](crate::materials::MeshBasicNodeMaterial::refraction_ratio),
2944    /// per object.
2945    material_refraction_ratio,
2946    uniform(
2947        UniformSource::MaterialRefractionRatio,
2948        Type::F32,
2949        UniformGroup::Object,
2950        None
2951    )
2952);
2953accessor!(
2954    /// `materialEnvRotation` — the env map's rotation matrix.
2955    material_env_rotation,
2956    uniform(
2957        UniformSource::EnvRotationMatrix,
2958        Type::Mat4,
2959        UniformGroup::Object,
2960        None
2961    )
2962);
2963accessor!(
2964    /// `backgroundRotation`.
2965    background_rotation,
2966    uniform(
2967        UniformSource::BackgroundRotation,
2968        Type::Mat4,
2969        UniformGroup::Render,
2970        None
2971    )
2972);
2973accessor!(
2974    /// `backgroundBlurriness`, reused by `Background` as the texture LOD.
2975    background_blurriness,
2976    uniform(
2977        UniformSource::BackgroundBlurriness,
2978        Type::F32,
2979        UniformGroup::Render,
2980        None
2981    )
2982);
2983accessor!(
2984    /// `backgroundIntensity`.
2985    background_intensity,
2986    uniform(
2987        UniformSource::BackgroundIntensity,
2988        Type::F32,
2989        UniformGroup::Render,
2990        None
2991    )
2992);
2993accessor!(
2994    /// `time` — `TimerNode`, seconds since the renderer started.
2995    time,
2996    uniform(UniformSource::Time, Type::F32, UniformGroup::Render, None)
2997);
2998accessor!(
2999    /// `viewportSize` — `ScreenNode.SIZE`, the bound target's dimensions.
3000    viewport_size,
3001    uniform(
3002        UniformSource::ViewportSize,
3003        Type::Vec2,
3004        UniformGroup::Render,
3005        None
3006    )
3007);
3008accessor!(
3009    /// `viewport` — `ScreenNode.VIEWPORT`, `( x, y, width, height )` in
3010    /// physical pixels. `.zw` is the pair a screen-space line width divides by.
3011    viewport,
3012    uniform(UniformSource::Viewport, Type::Vec4, UniformGroup::Render, None)
3013);
3014accessor!(
3015    /// `screenDPR` — `renderer.getPixelRatio()`.
3016    screen_dpr,
3017    uniform(UniformSource::ScreenDpr, Type::F32, UniformGroup::Render, None)
3018);
3019accessor!(
3020    /// `screenSize` — `ScreenNode.SIZE`, the bound target's dimensions in
3021    /// physical pixels. The same node as [`viewport_size`]: three's
3022    /// `viewportSize` is the viewport rectangle's `.zw`, and the two only
3023    /// differ under a viewport smaller than the target, which no page that
3024    /// reads either sets.
3025    screen_size,
3026    viewport_size()
3027);
3028accessor!(
3029    /// `screenCoordinate` — `ScreenNode.COORDINATE`, the fragment's position
3030    /// in physical pixels: `fragCoord.xy`, y down, as WebGPU has it.
3031    screen_coordinate,
3032    frag_coord().xy()
3033);
3034accessor!(
3035    /// `viewportCoordinate` — `ScreenNode.js`: `screenCoordinate.sub(
3036    /// viewport.xy )`, the fragment's position in physical pixels relative
3037    /// to the viewport rectangle's corner.
3038    viewport_coordinate,
3039    screen_coordinate().sub(viewport().xy())
3040);
3041accessor!(
3042    /// `viewportUV` — `ScreenNode.js`: `viewportCoordinate.div( viewportSize
3043    /// )`, normalised into `[0,1]` over the viewport rectangle. Three's
3044    /// `viewportSize` is `viewport.zw`, which is what this divides by
3045    /// (the port's [`viewport_size`] is the target's size).
3046    viewport_uv,
3047    viewport_coordinate().div(viewport().zw())
3048);
3049accessor!(
3050    /// `cameraNear` — `uniform( 'float' ).setName( 'cameraNear' )`, in the
3051    /// render group: the rendering camera's `near`.
3052    camera_near,
3053    uniform(
3054        UniformSource::CameraNear,
3055        Type::F32,
3056        UniformGroup::Render,
3057        Some("cameraNear")
3058    )
3059);
3060accessor!(
3061    /// `cameraFar` — as [`camera_near`], from `camera.far`.
3062    camera_far,
3063    uniform(
3064        UniformSource::CameraFar,
3065        Type::F32,
3066        UniformGroup::Render,
3067        Some("cameraFar")
3068    )
3069);
3070accessor!(
3071    /// `cameraNormalMatrix` — `uniform( camera.normalMatrix ).setName(
3072    /// 'cameraNormalMatrix' )`, in the render group.
3073    ///
3074    /// `WebGPURenderer` never updates a camera's `normalMatrix`, so the value
3075    /// three uploads is the identity the camera was constructed with; the port
3076    /// uploads the same (see [`UniformSource::CameraNormalMatrix`]). Under an
3077    /// `ArrayCamera` three switches to a per-sub-camera array; the port keeps
3078    /// the one uniform, as it does for [`camera_world_matrix`].
3079    camera_normal_matrix,
3080    uniform(
3081        UniformSource::CameraNormalMatrix,
3082        Type::Mat3,
3083        UniformGroup::Render,
3084        Some("cameraNormalMatrix")
3085    )
3086);
3087accessor!(
3088    /// `cameraProjectionMatrixInverse`. Named, like the other camera matrices:
3089    /// `uniform( camera.projectionMatrixInverse ).setName(
3090    /// 'cameraProjectionMatrixInverse' )`.
3091    camera_projection_matrix_inverse,
3092    uniform(
3093        UniformSource::CameraProjectionMatrixInverse,
3094        Type::Mat4,
3095        UniformGroup::Render,
3096        Some("cameraProjectionMatrixInverse")
3097    )
3098);
3099accessor!(
3100    /// `modelWorldMatrixInverse` — `object.matrixWorld` inverted, per object.
3101    /// Unnamed, so it takes a `nodeUniformN` slot.
3102    model_world_matrix_inverse,
3103    uniform(
3104        UniformSource::ModelWorldMatrixInverse,
3105        Type::Mat4,
3106        UniformGroup::Object,
3107        None
3108    )
3109);
3110accessor!(
3111    /// `materialLineWidth` — `material.linewidth`.
3112    material_line_width,
3113    uniform(
3114        UniformSource::MaterialLineWidth,
3115        Type::F32,
3116        UniformGroup::Object,
3117        None
3118    )
3119);
3120
3121accessor!(
3122    /// `screenUV` — `ScreenNode`'s `UV` scope: `screenCoordinate.div(
3123    /// screenSize )`, the fragment's position normalised into `[0,1]`.
3124    ///
3125    /// No Y flip, so y points *down*: `ScreenNode` flips only under WebGL
3126    /// (`builder.renderer.backend.isWebGLBackend`), and `webgpu_skinning`'s
3127    /// dumped background shader reads `( fragCoord.xy / render.nodeUniform0 ).y`
3128    /// straight.
3129    screen_uv,
3130    frag_coord().xy().div(viewport_size())
3131);
3132
3133accessor!(
3134    /// `positionLocal` — `positionGeometry.toVarying( 'positionLocal' )`, so
3135    /// that instancing, morphing and skinning can reassign it and so that a
3136    /// fragment-stage read (the torus knot's `maskNode`) carries it across as a
3137    /// varying. A varying nothing in the fragment stage asks for stays a plain
3138    /// `var<private>` in the vertex shader, which is every other material.
3139    position_local,
3140    to_varying(Some("positionLocal"), position_geometry())
3141);
3142accessor!(
3143    /// `positionPrevious` — `positionGeometry.toVarying( 'positionPrevious' )`:
3144    /// the vertex's local position *last frame*, for
3145    /// [`velocity`](crate::nodes::velocity::velocity). Skinning reassigns it
3146    /// to the position under last frame's bones when the pass's MRT has a
3147    /// `velocity` output (`builder.needsPreviousData()`); everything else
3148    /// leaves it the geometry's position, which is right for a rigid mesh —
3149    /// its motion is all in the previous model matrix.
3150    position_previous,
3151    to_varying(Some("positionPrevious"), position_geometry())
3152);
3153accessor!(
3154    /// `normalLocal`.
3155    normal_local,
3156    to_var(Some("normalLocal"), normal_geometry())
3157);
3158accessor!(
3159    /// `modelViewMatrix` — [`mediump_model_view_matrix`] in a var.
3160    model_view_matrix,
3161    to_var(Some("modelViewMatrix"), mediump_model_view_matrix())
3162);
3163/// `mediumpModelViewMatrix` — `cameraViewMatrix.mul( modelWorldMatrix )`,
3164/// multiplied on the GPU. No var of its own: [`model_view_matrix`] is this
3165/// product `toVar`'d.
3166///
3167/// Three's is one shared node; this builds a fresh product per call. The
3168/// vertex stage always reaches the product through `modelViewMatrix`, and the
3169/// port counts a node's uses across both stages where three counts them per
3170/// stage, so a shared node read once in a fragment would be promoted to a var
3171/// there that three writes inline.
3172pub fn mediump_model_view_matrix() -> NodeRef {
3173    camera_view_matrix().mul(model_world_matrix())
3174}
3175accessor!(
3176    /// `highpModelViewMatrix` — `uniform( 'mat4' ).onObjectUpdate( … )
3177    /// .toVar( 'highpModelViewMatrix' )`: `camera.matrixWorldInverse *
3178    /// object.matrixWorld`, multiplied on the CPU in double precision and
3179    /// uploaded per object.
3180    ///
3181    /// Three's `ArrayCamera` branch (a `uniformArray` indexed by
3182    /// `cameraIndex`) is not ported; under an `ArrayCamera` the product is the
3183    /// array camera's own view matrix, as for [`camera_world_matrix`].
3184    highp_model_view_matrix,
3185    to_var(
3186        Some("highpModelViewMatrix"),
3187        uniform(
3188            UniformSource::HighpModelViewMatrix,
3189            Type::Mat4,
3190            UniformGroup::Object,
3191            None
3192        )
3193    )
3194);
3195accessor!(
3196    /// `highpModelNormalViewMatrix` — `uniform( 'mat3' ).onObjectUpdate( … )
3197    /// .toVar( 'highpModelNormalViewMatrix' )`: the normal matrix of
3198    /// [`highp_model_view_matrix`]'s product, per object. Same `ArrayCamera`
3199    /// caveat.
3200    highp_model_normal_view_matrix,
3201    to_var(
3202        Some("highpModelNormalViewMatrix"),
3203        uniform(
3204            UniformSource::HighpModelNormalViewMatrix,
3205            Type::Mat3,
3206            UniformGroup::Object,
3207            None
3208        )
3209    )
3210);
3211
3212/// `Object3DNode( scope )`'s uniform: unnamed, in the object group, so it
3213/// takes a `nodeUniformN` slot, as three's does.
3214fn object_3d_uniform(scope: Object3DScope, object: Option<LiveValue>) -> NodeRef {
3215    let ty = match scope {
3216        Object3DScope::Radius => Type::F32,
3217        _ => Type::Vec3,
3218    };
3219    uniform(
3220        UniformSource::Object3D { scope, object },
3221        ty,
3222        UniformGroup::Object,
3223        None,
3224    )
3225}
3226accessor!(
3227    /// `modelDirection` — `ModelNode( DIRECTION )`: the drawn object's world
3228    /// direction (`object.getWorldDirection()`), per object.
3229    model_direction,
3230    object_3d_uniform(Object3DScope::Direction, None)
3231);
3232accessor!(
3233    /// `modelPosition` — `ModelNode( POSITION )`: the drawn object's world
3234    /// position, per object.
3235    model_position,
3236    object_3d_uniform(Object3DScope::Position, None)
3237);
3238accessor!(
3239    /// `modelScale` — `ModelNode( SCALE )`: the drawn object's world scale,
3240    /// per object.
3241    model_scale,
3242    object_3d_uniform(Object3DScope::Scale, None)
3243);
3244accessor!(
3245    /// `modelViewPosition` — `ModelNode( VIEW_POSITION )`: the drawn object's
3246    /// world position in the rendering camera's view space, per object.
3247    model_view_position,
3248    object_3d_uniform(Object3DScope::ViewPosition, None)
3249);
3250accessor!(
3251    /// `modelRadius` — `ModelNode( RADIUS )`: the radius of the drawn object's
3252    /// geometry's bounding sphere in world space, per object.
3253    model_radius,
3254    object_3d_uniform(Object3DScope::Radius, None)
3255);
3256/// `clipSpace` — `Position.js`' `Fn( builder => builder.context.clipSpace
3257/// .toVarying( 'v_clipSpace' ) ).once()()`: the material's clip-space vertex
3258/// output (its `vertexNode`, else `modelViewProjection`), carried into the
3259/// fragment stage. Fragment stage only, as in three: set up from a
3260/// vertex-stage node it warns once and yields `vec4()`, where reading the
3261/// varying would feed the vertex output back into itself.
3262///
3263/// The vertex output is not known when the node is made — a material's
3264/// `vertex_node` is set independently of its `fragment_node` — so the varying
3265/// wraps a [`CustomNode`] that reads `builder.context.clipSpace` at build
3266/// time, which [`NodeBuilder::build`](crate::nodes::NodeBuilder::build)
3267/// installs from the flow's position, as `NodeMaterial.setup()` does.
3268///
3269/// Cached in a plain cell, and not filled outside the sub-build layers as an
3270/// `accessor!` is: nothing in it can take a layer prefix (it holds no var,
3271/// and the port never prefixes a varying's name), and the stage test runs
3272/// at build time, not here.
3273pub fn clip_space() -> NodeRef {
3274    /// `builder.context.clipSpace`, the varying's value.
3275    struct ClipSpace;
3276    impl CustomNode for ClipSpace {
3277        fn type_name(&self) -> &'static str {
3278            "ClipSpace"
3279        }
3280        fn node_type(&self) -> Type {
3281            Type::Vec4
3282        }
3283        fn setup(&self, builder: &crate::nodes::NodeBuilder) -> NodeRef {
3284            builder
3285                .context("clipSpace")
3286                .unwrap_or_else(|| vec4(0.0, 0.0, 0.0, 0.0))
3287        }
3288    }
3289    /// The `Fn`'s stage test, around the varying.
3290    struct ClipSpaceFn(NodeRef);
3291    impl CustomNode for ClipSpaceFn {
3292        fn type_name(&self) -> &'static str {
3293            "ClipSpaceFn"
3294        }
3295        fn node_type(&self) -> Type {
3296            Type::Vec4
3297        }
3298        // An inlined `Fn()` call: `ShaderCallNodeInternal` is never cached in
3299        // a var of its own, so `clipSpace` read twice is the varying twice.
3300        fn is_cacheable(&self) -> bool {
3301            false
3302        }
3303        fn setup(&self, builder: &crate::nodes::NodeBuilder) -> NodeRef {
3304            if builder.is_fragment_stage() {
3305                return self.0.clone();
3306            }
3307            thread_local! { static WARNED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
3308            if !WARNED.with(|w| w.replace(true)) {
3309                eprintln!("three-rs: TSL: `clipSpace` is only available in fragment stage.");
3310            }
3311            vec4(0.0, 0.0, 0.0, 0.0)
3312        }
3313    }
3314    thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
3315    CELL.with(|c| {
3316        c.get(|| {
3317            custom(ClipSpaceFn(to_varying(
3318                Some("v_clipSpace"),
3319                custom(ClipSpace),
3320            )))
3321        })
3322    })
3323}
3324/// `positionView` — `Position.js`' `Fn( builder =>
3325/// builder.context.setupPositionView() ).once( [ 'POSITION', 'VERTEX' ] )`.
3326pub fn position_view() -> NodeRef {
3327    if let Some(node) = override_node(|o| &o.position_view) {
3328        return node;
3329    }
3330    position_view_pair().0
3331}
3332accessor!(
3333    /// `positionWorld` — `modelWorldMatrix * vec4( positionLocal, 1 )`, carried
3334    /// to the fragment stage as `v_positionWorld`.
3335    position_world,
3336    to_varying(
3337        Some("v_positionWorld"),
3338        model_world_matrix()
3339            .mul(vec4_join(vec![position_local(), float(1.0)]))
3340            .xyz()
3341    )
3342);
3343accessor!(
3344    /// `positionWorldDirection` — `positionLocal.transformDirection(
3345    /// modelWorldMatrix ).toVarying( 'v_positionWorldDirection' )
3346    /// .normalize().toVar( 'positionWorldDirection' )`.
3347    ///
3348    /// `transformDirection( m )` is `normalize( ( m * vec4( v, 0 ) ).xyz )`, so
3349    /// the direction is normalised twice: once in the vertex stage before it
3350    /// becomes a varying and once after the interpolation, which is what
3351    /// `CubeRenderTarget.fromEquirectangularTexture`'s box shader shows.
3352    position_world_direction,
3353    to_var(
3354        Some("positionWorldDirection"),
3355        to_varying(
3356            Some("v_positionWorldDirection"),
3357            model_world_matrix()
3358                .mul(vec4_join(vec![position_local(), float(0.0)]))
3359                .xyz()
3360                .normalize()
3361        )
3362        .normalize()
3363    )
3364);
3365/// `positionViewDirection`.
3366///
3367/// `vec3( 0, 0, 1 )` when `builder.camera.isOrthographicCamera` — every view
3368/// ray of an orthographic camera is parallel to its axis — and
3369/// `positionView.negate().toVarying( 'v_positionViewDirection' ).normalize()`
3370/// otherwise (`Position.js`). The camera's kind comes from the build context
3371/// (`SetupContext::orthographic`), so the two forms get separate cells.
3372///
3373/// Not an `accessor!`: `overrideNodes` can replace it wholesale (§27), and a
3374/// singleton cell would hand the replacement to the next material too. The
3375/// cell is still filled outside any sub-build layer, as an `accessor!` is,
3376/// so the first caller's layer (`reflect_view` in the `NORMAL` layer, say)
3377/// does not prefix the var for every later one.
3378pub fn position_view_direction() -> NodeRef {
3379    if let Some(node) = override_node(|o| &o.position_view_direction) {
3380        return node;
3381    }
3382    thread_local! {
3383        static PERSPECTIVE: Lazy<NodeRef> = const { Lazy::new() };
3384        static ORTHOGRAPHIC: Lazy<NodeRef> = const { Lazy::new() };
3385    }
3386    if current_context(|cx| cx.orthographic_camera) {
3387        ORTHOGRAPHIC.with(|c| {
3388            c.get(|| {
3389                outside_sub_build(|| to_var(Some("positionViewDirection"), vec3(0.0, 0.0, 1.0)))
3390            })
3391        })
3392    } else {
3393        PERSPECTIVE.with(|c| {
3394            c.get(|| {
3395                outside_sub_build(|| {
3396                    to_var(
3397                        Some("positionViewDirection"),
3398                        to_varying(Some("v_positionViewDirection"), position_view().negate())
3399                            .normalize(),
3400                    )
3401                })
3402            })
3403        })
3404    }
3405}
3406accessor!(
3407    /// `normalFlat` — `positionView.dFdx().cross( positionView.dFdy() )
3408    /// .normalize().toVar( 'normalFlat' )`. `dpdy()` carries WGSL's sign
3409    /// flip, so this prints as `normalize( cross( dpdx( v_positionView ), -
3410    /// dpdy( v_positionView ) ) )`.
3411    normal_flat,
3412    to_var(
3413        Some("normalFlat"),
3414        cross(dpdx(position_view()), dpdy(position_view())).normalize()
3415    )
3416);
3417
3418/// `normalViewGeometry` — `Fn( builder => builder.isFlatShading() ? normalFlat :
3419/// transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry'
3420/// ).normalize() ).once()().toVar( 'normalViewGeometry' )`.
3421pub fn normal_view_geometry() -> NodeRef {
3422    let flat = current_context(|cx| cx.flat_shading);
3423    if let Some(node) = NORMAL_VIEW_GEOMETRY.with(|m| m.borrow().get(&flat).cloned()) {
3424        return node;
3425    }
3426    let value = if flat {
3427        normal_flat()
3428    } else {
3429        to_varying(
3430            Some("v_normalViewGeometry"),
3431            camera_view_matrix()
3432                .mul(vec4_join(vec![
3433                    model_normal_matrix().mul(normal_local()),
3434                    float(0.0),
3435                ]))
3436                .xyz()
3437                .normalize(),
3438        )
3439        .normalize()
3440    };
3441    let node = to_var(Some("normalViewGeometry"), value);
3442    NORMAL_VIEW_GEOMETRY.with(|m| m.borrow_mut().insert(flat, node.clone()));
3443    node
3444}
3445/// `normalView` — `Normal.js`' `Fn( … ).once( [ 'NORMAL', 'VERTEX' ] )`.
3446///
3447/// Inside the `NORMAL` sub-build layer it is the geometric normal, under the
3448/// layer-prefixed name `NORMAL_normalView`; outside it, it is the material's
3449/// `normalNode` (reached through the build context) or, with no normal node,
3450/// the geometric normal again. Keyed by (layer, normal value) so that two
3451/// materials in the same process get their own node, which is what three.js'
3452/// per-build `nodeData` gives it for free.
3453/// The cache key every node that reads `normalView` shares: the open sub-build
3454/// layer plus the material's own normal node.
3455fn normal_key() -> NormalViewKey {
3456    let layer = current_context(|cx| cx.sub_build);
3457    let value = if layer.is_some() {
3458        None
3459    } else {
3460        current_context(|cx| cx.setup_normal.clone())
3461    };
3462    (
3463        layer,
3464        value.as_ref().map(|v| v.key()),
3465        current_context(|cx| cx.flat_shading),
3466        current_context(|cx| cx.material_side),
3467        current_context(|cx| cx.has_tangent),
3468        // An `overrideNodes( [ [ normalView, … ] ] )` material reads a wholly
3469        // different `normalView`, so everything cached off it — `normalWorld`,
3470        // the tangent frame, the TBN matrix — has to be cached separately too.
3471        override_node(|o| &o.normal_view).map(|n| n.key()),
3472    )
3473}
3474
3475/// The material's normal node for the current build, or `None` inside a
3476/// sub-build layer, which runs on the geometric normal.
3477fn normal_value() -> Option<NodeRef> {
3478    let layer = current_context(|cx| cx.sub_build);
3479    if layer.is_some() {
3480        None
3481    } else {
3482        current_context(|cx| cx.setup_normal.clone())
3483    }
3484}
3485
3486/// `normalView` — the surface normal in view space, honouring any override
3487/// installed by [`OverrideNodes::normal_view`].
3488pub fn normal_view() -> NodeRef {
3489    // `Node.getShared()`'s override branch: the replacement is returned *as it
3490    // is*, with no `toVar` of its own, which is why three's deferred resolve
3491    // shader inlines `nodeVar4.xyz` at every use instead of declaring a
3492    // `normalView` var.
3493    if let Some(node) = override_node(|o| &o.normal_view) {
3494        return node;
3495    }
3496    let key = normal_key();
3497    let flat = current_context(|cx| cx.flat_shading);
3498    if let Some(node) = NORMAL_VIEW.with(|m| m.borrow().get(&key).cloned()) {
3499        return node;
3500    }
3501    // Inside the `NORMAL` layer the value is the geometric normal, and
3502    // `negateOnBackSide()` applies unless the material is flat shaded.
3503    let node = to_var(
3504        Some("normalView"),
3505        match normal_value() {
3506            Some(value) => value,
3507            None if flat => normal_view_geometry(),
3508            None => negate_on_back_side(normal_view_geometry()),
3509        },
3510    );
3511    NORMAL_VIEW.with(|m| m.borrow_mut().insert(key, node.clone()));
3512    node
3513}
3514
3515/// `tangentView` / `bitangentView` for a geometry with no `tangent` attribute:
3516/// the derivative frame of `TangentUtils.js`, both `.once( [ 'NORMAL',
3517/// 'VERTEX' ] )` so they take the layer prefix. They are returned as a pair
3518/// because `tangentViewFrame` and `bitangentViewFrame` share the `scale` temp.
3519fn tangent_frame() -> (NodeRef, NodeRef) {
3520    let key = normal_key();
3521    if let Some(pair) = TANGENT_VIEW.with(|m| m.borrow().get(&key).cloned()) {
3522        return pair;
3523    }
3524    // `builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute(
3525    // 'tangent' )`: the vertex layer always takes the attribute, which reads
3526    // as zero on a geometry that has none.
3527    if current_context(|cx| cx.has_tangent || cx.sub_build == Some("VERTEX")) {
3528        let pair = tangent_attribute_frame();
3529        TANGENT_VIEW.with(|m| m.borrow_mut().insert(key, pair.clone()));
3530        return pair;
3531    }
3532    // `q1perp = dFdy( positionView ).cross( N )`, `q0perp = N.cross( dFdx(
3533    // positionView ) )`, with `dFdy` carrying the `- dpdy` sign flip.
3534    let n = normal_view();
3535    let q1perp = cross(dpdy(position_view()), n.clone());
3536    let q0perp = cross(n, dpdx(position_view()));
3537    let st0 = dpdx(uv());
3538    let st1 = dpdy(uv());
3539
3540    let t = q1perp
3541        .clone()
3542        .mul(st0.clone().x())
3543        .add(q0perp.clone().mul(st1.clone().x()));
3544    let b = q1perp.mul(st0.y()).add(q0perp.mul(st1.y()));
3545    let det = max(t.clone().dot(t.clone()), b.clone().dot(b.clone()));
3546    // `det.equal( 0 ).select( 0, det.inverseSqrt() )`, which three.js lowers to
3547    // an if/else over a shared temp — `Node::Select`'s exact shape.
3548    let scale = det
3549        .clone()
3550        .equal(float(0.0))
3551        .select(float(0.0), inverse_sqrt(det));
3552
3553    // `tangentView` / `bitangentView` go through `negateOnBackSide()` too,
3554    // unless the material is flat shaded.
3555    let flat = current_context(|cx| cx.flat_shading);
3556    let frame = |name, value| {
3557        if flat {
3558            value
3559        } else {
3560            let _ = name;
3561            negate_on_back_side(value)
3562        }
3563    };
3564    let pair = (
3565        to_var(
3566            Some("tangentView"),
3567            frame(
3568                "tangentView",
3569                to_var_untagged("tangentViewFrame", t.mul(scale.clone())),
3570            ),
3571        ),
3572        to_var(
3573            Some("bitangentView"),
3574            frame(
3575                "bitangentView",
3576                to_var_untagged("bitangentViewFrame", b.mul(scale)),
3577            ),
3578        ),
3579    );
3580    TANGENT_VIEW.with(|m| m.borrow_mut().insert(key, pair.clone()));
3581    pair
3582}
3583
3584/// `tangentView` / `bitangentView` for a geometry that *has* a `tangent`
3585/// attribute — `Tangent.js` and `Bitangent.js`' first branch:
3586///
3587/// ```text
3588/// tangentView   = normalize( varying( modelViewMatrix * vec4( tangentLocal, 0 ) ).xyz )
3589/// bitangentView = normalize( cross( normalView, tangentView ) * tangentGeometry.w )
3590/// ```
3591///
3592/// The bitangent's cross product is hoisted into a varying — and so computed
3593/// per vertex — only inside the `NORMAL` sub-build, which is
3594/// `getBitangent()`'s `builder.subBuildFn === 'NORMAL'` test. That is why the
3595/// dump has one `v_tangentView` shared by both layers but a separate
3596/// `NORMAL_v_bitangentView`: in the main layer the cross is a fragment
3597/// expression over the *mapped* normal, in the `NORMAL` layer it is a vertex
3598/// expression over the geometric one.
3599fn tangent_attribute_frame() -> (NodeRef, NodeRef) {
3600    let tangent_geometry = tangent_geometry();
3601    let tangent_local = tangent_local();
3602
3603    let flat = current_context(|cx| cx.flat_shading);
3604    let front_side = |value: NodeRef| {
3605        if flat {
3606            value
3607        } else {
3608            negate_on_back_side(value)
3609        }
3610    };
3611
3612    // One varying for both layers: three creates it in the shared `VERTEX`
3613    // sub-build, so the `NORMAL` layer reads the same `v_tangentView` rather
3614    // than declaring a prefixed one of its own. Filled outside any layer, as
3615    // an `accessor!` is. Nothing in it takes a prefix today (a varying's name
3616    // never does, and `modelViewMatrix` is an `accessor!`), so this only keeps
3617    // a future var inside from inheriting the first caller's layer.
3618    thread_local! { static TANGENT_VARYING: Lazy<NodeRef> = const { Lazy::new() }; }
3619    let tangent = TANGENT_VARYING
3620        .with(|c| {
3621            c.get(|| {
3622                outside_sub_build(|| {
3623                    to_varying(
3624                        Some("v_tangentView"),
3625                        model_view_matrix()
3626                            .mul(vec4_join(vec![tangent_local, float(0.0)]))
3627                            .xyz(),
3628                    )
3629                })
3630            })
3631        })
3632        .normalize();
3633    let tangent_view = to_var(Some("tangentView"), front_side(tangent));
3634
3635    // `getBitangent( normalView.cross( tangentView ), 'v_bitangentView' )`.
3636    let cross_normal_tangent = cross(normal_view(), tangent_view.clone()).mul(tangent_geometry.w());
3637    let in_normal_layer = current_context(|cx| cx.sub_build) == Some("NORMAL");
3638    let bitangent = if in_normal_layer && !flat {
3639        // The varying's name goes through `getSubBuildProperty()` here because
3640        // the node carries the layer; `v_tangentView` above does not, because
3641        // it is created in the shared `VERTEX` layer first.
3642        to_varying(Some("NORMAL_v_bitangentView"), cross_normal_tangent)
3643    } else {
3644        cross_normal_tangent
3645    }
3646    .normalize();
3647    let bitangent_view = to_var(Some("bitangentView"), front_side(bitangent));
3648
3649    (tangent_view, bitangent_view)
3650}
3651
3652/// `tangentView`.
3653pub fn tangent_view() -> NodeRef {
3654    tangent_frame().0
3655}
3656
3657/// `bitangentView`.
3658pub fn bitangent_view() -> NodeRef {
3659    tangent_frame().1
3660}
3661
3662accessor!(
3663    /// `tangentGeometry` — `attribute( 'tangent', 'vec4' )`: the geometry's
3664    /// tangent, its handedness in `w`.
3665    tangent_geometry,
3666    attribute("tangent", Type::Vec4)
3667);
3668accessor!(
3669    /// `tangentLocal` — `tangentGeometry.xyz.toVar( 'tangentLocal' )`.
3670    tangent_local,
3671    to_var(Some("tangentLocal"), tangent_geometry().xyz())
3672);
3673
3674/// One node per [`normal_key`]: the stand-in for three's per-build
3675/// `nodeData` that every accessor reading `normalView`, the sub-build layer or
3676/// the material's shading flags needs, so a second material in the process
3677/// does not inherit the first one's node.
3678fn keyed_by_normal(
3679    cell: &'static std::thread::LocalKey<RefCell<HashMap<NormalViewKey, NodeRef>>>,
3680    build: impl FnOnce() -> NodeRef,
3681) -> NodeRef {
3682    let key = normal_key();
3683    if let Some(node) = cell.with(|m| m.borrow().get(&key).cloned()) {
3684        return node;
3685    }
3686    let node = build();
3687    cell.with(|m| m.borrow_mut().insert(key, node.clone()));
3688    node
3689}
3690
3691/// `tangentWorld` — `tangentView.transformDirection( cameraWorldMatrix )
3692/// .toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' )`.
3693///
3694/// The varying's value is built in the `VERTEX` sub-build, as three builds a
3695/// varying's node, so its `tangentView` is the tangent attribute's
3696/// (`VERTEX_tangentView`) whether or not the geometry has one — which is what
3697/// three's dump shows, a zero tangent included.
3698pub fn tangent_world() -> NodeRef {
3699    thread_local! {
3700        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
3701    }
3702    keyed_by_normal(&CELL, || {
3703        let world = in_sub_build("VERTEX", || {
3704            transform_direction(camera_world_matrix(), tangent_view())
3705        });
3706        to_var(
3707            Some("tangentWorld"),
3708            to_varying(Some("v_tangentWorld"), world).normalize(),
3709        )
3710    })
3711}
3712
3713/// `Bitangent.js`' `getBitangent( crossNormalTangent, varyingName )`:
3714/// `crossNormalTangent.mul( tangentGeometry.w ).xyz`, hoisted into a varying
3715/// only inside the `NORMAL` sub-build of a smooth-shaded material — three
3716/// names it through `getSubBuildProperty()`, hence the prefixed name.
3717///
3718/// **Divergence:** three's `getBitangent` is `.once( [ 'NORMAL' ] )`, a cache
3719/// that ignores its arguments, so whichever of `bitangentGeometry`,
3720/// `bitangentLocal` and `bitangentWorld` a material builds first lends its
3721/// cross product to the other two. Each one here keeps its own.
3722fn get_bitangent(cross_normal_tangent: NodeRef, varying_in_normal_layer: &'static str) -> NodeRef {
3723    let bitangent = cross_normal_tangent.mul(tangent_geometry().w());
3724    let in_normal_layer = current_context(|cx| cx.sub_build) == Some("NORMAL");
3725    if in_normal_layer && !current_context(|cx| cx.flat_shading) {
3726        to_varying(Some(varying_in_normal_layer), bitangent)
3727    } else {
3728        bitangent
3729    }
3730}
3731
3732/// `bitangentGeometry` — `getBitangent( normalGeometry.cross( tangentGeometry
3733/// ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' )`.
3734pub fn bitangent_geometry() -> NodeRef {
3735    thread_local! {
3736        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
3737    }
3738    keyed_by_normal(&CELL, || {
3739        to_var(
3740            Some("bitangentGeometry"),
3741            get_bitangent(
3742                cross(normal_geometry(), tangent_geometry().xyz()),
3743                "NORMAL_v_bitangentGeometry",
3744            )
3745            .normalize(),
3746        )
3747    })
3748}
3749
3750/// `bitangentLocal` — `getBitangent( normalLocal.cross( tangentLocal ),
3751/// 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' )`.
3752pub fn bitangent_local() -> NodeRef {
3753    thread_local! {
3754        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
3755    }
3756    keyed_by_normal(&CELL, || {
3757        to_var(
3758            Some("bitangentLocal"),
3759            get_bitangent(
3760                cross(normal_local(), tangent_local()),
3761                "NORMAL_v_bitangentLocal",
3762            )
3763            .normalize(),
3764        )
3765    })
3766}
3767
3768/// `bitangentWorld` — `getBitangent( normalWorld.cross( tangentWorld ),
3769/// 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' )`.
3770pub fn bitangent_world() -> NodeRef {
3771    thread_local! {
3772        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
3773    }
3774    keyed_by_normal(&CELL, || {
3775        to_var(
3776            Some("bitangentWorld"),
3777            get_bitangent(
3778                cross(normal_world(), tangent_world()),
3779                "NORMAL_v_bitangentWorld",
3780            )
3781            .normalize(),
3782        )
3783    })
3784}
3785
3786/// `parallaxDirection` — `AccessorsUtils.js`' `positionViewDirection.mul(
3787/// TBNViewMatrix )`: the view direction in tangent space, unnormalised (three
3788/// leaves its `.normalize()` commented out).
3789pub fn parallax_direction() -> NodeRef {
3790    thread_local! {
3791        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
3792    }
3793    keyed_by_normal(&CELL, || position_view_direction().mul(tbn_view_matrix()))
3794}
3795
3796/// `parallaxUV( uv, scale )` — `uv.sub( parallaxDirection.mul( scale ) )`.
3797/// The difference is a `vec3`, as three's is: the `vec2` uv is widened to
3798/// meet the direction, so take `.xy()` for a texture coordinate.
3799pub fn parallax_uv(uv: impl Into<NodeRef>, scale: impl Into<NodeRef>) -> NodeRef {
3800    uv.into().sub(parallax_direction().mul(scale.into()))
3801}
3802/// `normalWorld` — `normalView` rotated out of view space.
3803pub fn normal_world() -> NodeRef {
3804    let key = normal_key();
3805    if let Some(node) = NORMAL_WORLD.with(|m| m.borrow().get(&key).cloned()) {
3806        return node;
3807    }
3808    let node = to_var(
3809        Some("normalWorld"),
3810        vec4_join(vec![normal_view(), float(0.0)])
3811            .mul(camera_view_matrix())
3812            .xyz()
3813            .normalize(),
3814    );
3815    NORMAL_WORLD.with(|m| m.borrow_mut().insert(key, node.clone()));
3816    node
3817}
3818accessor!(
3819    /// `normalWorldGeometry`.
3820    normal_world_geometry,
3821    to_var(
3822        Some("normalWorldGeometry"),
3823        to_varying(
3824            Some("v_normalWorldGeometry"),
3825            vec4_join(vec![normal_view_geometry(), float(0.0)])
3826                .mul(camera_view_matrix())
3827                .xyz()
3828                .normalize()
3829        )
3830        .normalize()
3831    )
3832);
3833/// `modelViewProjection` — `builder.context.setupModelViewProjection()`.
3834pub fn model_view_projection() -> NodeRef {
3835    position_view_pair().1
3836}
3837/// `reflectView` — `ReflectVector.js`' `positionViewDirection.negate()
3838/// .reflect( normalView )`: the view ray mirrored about the normal, in view
3839/// space.
3840pub fn reflect_view() -> NodeRef {
3841    thread_local! {
3842        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
3843    }
3844    keyed_by_normal(&CELL, || {
3845        reflect(position_view_direction().negate(), normal_view())
3846    })
3847}
3848/// `refractView` — `positionViewDirection.negate().refract( normalView,
3849/// materialRefractionRatio )`: the view ray bent by the material's
3850/// `refraction_ratio`, in view space.
3851pub fn refract_view() -> NodeRef {
3852    thread_local! {
3853        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
3854    }
3855    keyed_by_normal(&CELL, || {
3856        refract(
3857            position_view_direction().negate(),
3858            normal_view(),
3859            material_refraction_ratio(),
3860        )
3861    })
3862}
3863/// `reflectVector` — `reflectView.transformDirection( cameraWorldMatrix )
3864/// .toVar( 'reflectVector' )`, in world space. Keyed on the normal like
3865/// [`reflect_view`], which it reads.
3866pub fn reflect_vector() -> NodeRef {
3867    thread_local! {
3868        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
3869    }
3870    keyed_by_normal(&CELL, || {
3871        to_var(
3872            Some("reflectVector"),
3873            transform_direction(camera_world_matrix(), reflect_view()),
3874        )
3875    })
3876}
3877/// `refractVector` — `refractView.transformDirection( cameraWorldMatrix )
3878/// .toVar( 'refractVector' )`, in world space.
3879pub fn refract_vector() -> NodeRef {
3880    thread_local! {
3881        static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
3882    }
3883    keyed_by_normal(&CELL, || {
3884        to_var(
3885            Some("refractVector"),
3886            transform_direction(camera_world_matrix(), refract_view()),
3887        )
3888    })
3889}
3890
3891// Properties the material setup assigns to explicitly.
3892/// `diffuseColor` — the `DiffuseColor` property, `NodeMaterial::setup_diffuse_color()`'s output.
3893pub fn diffuse_color() -> NodeRef {
3894    thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
3895    CELL.with(|c| c.get(|| property("DiffuseColor", Type::Vec4)))
3896}
3897
3898macro_rules! prop {
3899    ($(#[$meta:meta])* pub(crate) $name:ident, $wgsl:literal, $ty:expr) => {
3900        $(#[$meta])*
3901        pub(crate) fn $name() -> NodeRef {
3902            thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
3903            CELL.with(|c| c.get(|| property($wgsl, $ty)))
3904        }
3905    };
3906    ($(#[$meta:meta])* $name:ident, $wgsl:literal, $ty:expr) => {
3907        $(#[$meta])*
3908        pub fn $name() -> NodeRef {
3909            thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
3910            CELL.with(|c| c.get(|| property($wgsl, $ty)))
3911        }
3912    };
3913}
3914
3915prop!(
3916    /// `output` — the fragment output color property, `Output`.
3917    output_property, "Output", Type::Vec4);
3918prop!(pub(crate) total_diffuse, "totalDiffuse", Type::Vec3);
3919prop!(pub(crate) total_specular, "totalSpecular", Type::Vec3);
3920prop!(pub(crate) outgoing_light, "outgoingLight", Type::Vec3);
3921prop!(
3922    /// `shininess` — `MeshPhongNodeMaterial`'s specular exponent property.
3923    shininess, "Shininess", Type::F32);
3924prop!(
3925    /// `specularColor`.
3926    specular_color, "SpecularColor", Type::Vec3);
3927prop!(
3928    /// `emissive` — the `EmissiveColor` property.
3929    emissive_color, "EmissiveColor", Type::Vec3);
3930prop!(
3931    /// `pointWidth` — `PropertyNode.js`' `float` property `pointWidth`, a
3932    /// `var<private>` a graph assigns and reads; nothing in three writes it.
3933    point_width, "pointWidth", Type::F32);
3934/// `PropertyNode`'s `ambientOcclusion` — the **property** three names
3935/// `AmbientOcclusion`, which `NodeMaterial.setupAmbientOcclusion()` writes from
3936/// `materialAO` and the lighting model's own `ambientOcclusion` *var* then
3937/// multiplies itself by. The two are different names in the WGSL and different
3938/// things here; see [`ambient_occlusion`] for the var.
3939pub(crate) fn ambient_occlusion_property() -> NodeRef {
3940    thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
3941    CELL.with(|c| c.get(|| property("AmbientOcclusion", Type::F32)))
3942}
3943
3944/// `LightingContextNode.getContext()`'s accumulators. These are **vars**, not
3945/// properties: three.js builds them as `vec3().toVar( 'directDiffuse' )` /
3946/// `float( 1 ).toVar( 'ambientOcclusion' )`, so each one's initialiser is
3947/// emitted where the flow first reads it rather than up front — which is why the
3948/// dumps interleave `directSpecular = vec3<f32>( 0.0, 0.0, 0.0 )` with the
3949/// light's own statements.
3950macro_rules! lighting_var {
3951    ($(#[$meta:meta])* pub(crate) $name:ident, $wgsl:literal, $init:expr) => {
3952        $(#[$meta])*
3953        pub(crate) fn $name() -> NodeRef {
3954            thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
3955            CELL.with(|c| c.get(|| to_var_untagged($wgsl, $init)))
3956        }
3957    };
3958    ($(#[$meta:meta])* $name:ident, $wgsl:literal, $init:expr) => {
3959        $(#[$meta])*
3960        pub fn $name() -> NodeRef {
3961            thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
3962            CELL.with(|c| c.get(|| to_var_untagged($wgsl, $init)))
3963        }
3964    };
3965}
3966
3967lighting_var!(pub(crate) direct_diffuse, "directDiffuse", vec3(0.0, 0.0, 0.0));
3968lighting_var!(pub(crate) direct_specular, "directSpecular", vec3(0.0, 0.0, 0.0));
3969lighting_var!(pub(crate) indirect_diffuse, "indirectDiffuse", vec3(0.0, 0.0, 0.0));
3970lighting_var!(pub(crate) indirect_specular, "indirectSpecular", vec3(0.0, 0.0, 0.0));
3971lighting_var!(
3972    /// `LightingContextNode.getContext()`'s `irradiance` accumulator.
3973    irradiance, "irradiance", vec3(0.0, 0.0, 0.0));
3974lighting_var!(
3975    /// `LightingContextNode.getContext()`'s `ambientOcclusion` accumulator.
3976    ambient_occlusion, "ambientOcclusion", float(1.0));
3977// `radiance` / `iblIrradiance` are `vec3().toVar()` on the lighting context
3978// too; nothing adds to them without an environment node.
3979lighting_var!(
3980    /// `LightingContextNode.getContext()`'s `radiance` accumulator.
3981    radiance, "radiance", vec3(0.0, 0.0, 0.0));
3982lighting_var!(
3983    /// `LightingContextNode.getContext()`'s `iblIrradiance` accumulator.
3984    ibl_irradiance, "iblIrradiance", vec3(0.0, 0.0, 0.0));
3985
3986// `PhysicalLightingModel`'s properties.
3987prop!(
3988    /// `metalness` — the `Metalness` property.
3989    metalness, "Metalness", Type::F32);
3990prop!(pub(crate) single_scattering, "singleScattering", Type::Vec3);
3991prop!(pub(crate) multi_scattering, "multiScattering", Type::Vec3);
3992prop!(
3993    /// `roughness` — the `Roughness` property.
3994    roughness, "Roughness", Type::F32);
3995prop!(
3996    /// `specularColorBlended`.
3997    specular_color_blended, "SpecularColorBlended", Type::Vec3);
3998prop!(
3999    /// `specularF90`.
4000    specular_f90, "SpecularF90", Type::F32);
4001// `MeshPhysicalNodeMaterial.setupSpecular()`'s `ior` property.
4002prop!(
4003    /// `ior` — the `IOR` property.
4004    ior, "IOR", Type::F32);
4005prop!(
4006    /// `diffuseContribution`.
4007    diffuse_contribution, "DiffuseContribution", Type::Vec3);
4008// `MeshPhysicalNodeMaterial.setupVariants()`' sheen properties, and the two
4009// accumulators `PhysicalLightingModel.start()` declares for them. The
4010// accumulators are `vec3().toVar( 'sheenSpecularDirect' )` in three; they are
4011// written before anything reads them either way, so a property is the same
4012// WGSL.
4013prop!(
4014    /// `sheen` — the `Sheen` property.
4015    sheen, "Sheen", Type::Vec3);
4016prop!(
4017    /// `sheenRoughness`.
4018    sheen_roughness, "SheenRoughness", Type::F32);
4019prop!(pub(crate) sheen_specular_direct, "sheenSpecularDirect", Type::Vec3);
4020prop!(pub(crate) sheen_specular_indirect, "sheenSpecularIndirect", Type::Vec3);
4021// `MeshPhysicalNodeMaterial.setupVariants()`' diffuse-roughness property.
4022prop!(
4023    /// `diffuseRoughness`.
4024    diffuse_roughness, "DiffuseRoughness", Type::F32);
4025// `MeshPhysicalNodeMaterial.setupVariants()`' iridescence properties.
4026prop!(
4027    /// `iridescence` — the `Iridescence` property.
4028    iridescence, "Iridescence", Type::F32);
4029prop!(
4030    /// `iridescenceIOR` — the `IridescenceIOR` property.
4031    iridescence_ior, "IridescenceIOR", Type::F32);
4032prop!(
4033    /// `iridescenceThickness` — the `IridescenceThickness` property, in
4034    /// nanometres.
4035    iridescence_thickness, "IridescenceThickness", Type::F32);
4036prop!(
4037    pub(crate) single_scattering_dielectric,
4038    "singleScatteringDielectric",
4039    Type::Vec3
4040);
4041prop!(
4042    pub(crate) multi_scattering_dielectric,
4043    "multiScatteringDielectric",
4044    Type::Vec3
4045);
4046prop!(
4047    pub(crate) single_scattering_metallic,
4048    "singleScatteringMetallic",
4049    Type::Vec3
4050);
4051prop!(
4052    pub(crate) multi_scattering_metallic,
4053    "multiScatteringMetallic",
4054    Type::Vec3
4055);
4056
4057// `MeshPhysicalNodeMaterial.setupVariants()`' anisotropy and clearcoat
4058// properties.
4059prop!(
4060    /// `anisotropy` — the `Anisotropy` property.
4061    anisotropy, "Anisotropy", Type::F32);
4062prop!(
4063    /// `alphaT`.
4064    alpha_t, "AlphaT", Type::F32);
4065prop!(
4066    /// `anisotropyT`.
4067    anisotropy_t, "AnisotropyT", Type::Vec3);
4068prop!(
4069    /// `anisotropyB`.
4070    anisotropy_b, "AnisotropyB", Type::Vec3);
4071prop!(
4072    /// `clearcoat` — the `Clearcoat` property.
4073    clearcoat, "Clearcoat", Type::F32);
4074prop!(
4075    /// `clearcoatRoughness`.
4076    clearcoat_roughness, "ClearcoatRoughness", Type::F32);
4077
4078// ... and its transmission ones.
4079prop!(
4080    /// `transmission` — the `Transmission` property.
4081    transmission, "Transmission", Type::F32);
4082prop!(
4083    /// `thickness` — the `Thickness` property.
4084    thickness, "Thickness", Type::F32);
4085prop!(
4086    /// `attenuationDistance`.
4087    attenuation_distance, "AttenuationDistance", Type::F32);
4088prop!(
4089    /// `attenuationColor`.
4090    attenuation_color, "AttenuationColor", Type::Vec3);
4091
4092// `PhysicalLightingModel.start()`'s clearcoat accumulators — vars, like the
4093// lighting context's, so their zeros land at the first read.
4094lighting_var!(pub(crate) clearcoat_radiance, "clearcoatRadiance", vec3(0.0, 0.0, 0.0));
4095lighting_var!(
4096    pub(crate) clearcoat_specular_direct,
4097    "clearcoatSpecularDirect",
4098    vec3(0.0, 0.0, 0.0)
4099);
4100lighting_var!(
4101    pub(crate) clearcoat_specular_indirect,
4102    "clearcoatSpecularIndirect",
4103    vec3(0.0, 0.0, 0.0)
4104);
4105
4106thread_local! {
4107    /// `clearcoatNormalView`'s node per `setupClearcoatNormal` value, the
4108    /// clearcoat twin of `NORMAL_VIEW`.
4109    static CLEARCOAT_NORMAL_VIEW: RefCell<HashMap<Option<usize>, NodeRef>> =
4110        RefCell::new(HashMap::new());
4111}
4112
4113/// Install the material's clearcoat normal node for the duration of `f` —
4114/// `MeshPhysicalNodeMaterial.setup()`'s `builder.context.setupClearcoatNormal`.
4115pub(crate) fn with_clearcoat_normal<R>(normal: Option<NodeRef>, f: impl FnOnce() -> R) -> R {
4116    let _clearcoat = push_context(|cx| cx.setup_clearcoat_normal = normal);
4117    f()
4118}
4119
4120/// `clearcoatNormalView` — `Normal.js`' var, whose value is the material's
4121/// clearcoat normal map through the `NORMAL` sub-build, or — when the material
4122/// has none — `MaterialNode.CLEARCOAT_NORMAL`'s `normalView` *as read inside
4123/// that sub-build*: the geometric normal, `NORMAL_normalView`, not the
4124/// material's normal-mapped one. A coat with no map of its own is smooth over
4125/// a bumpy base, which is the whole look of `webgpu_clearcoat`'s carbon fibre
4126/// and car paint.
4127pub fn clearcoat_normal_view() -> NodeRef {
4128    let value = current_context(|cx| cx.setup_clearcoat_normal.clone());
4129    let key = value.as_ref().map(|v| v.key());
4130    if let Some(node) = CLEARCOAT_NORMAL_VIEW.with(|m| m.borrow().get(&key).cloned()) {
4131        return node;
4132    }
4133    let node = to_var(
4134        Some("clearcoatNormalView"),
4135        value.unwrap_or_else(|| in_sub_build("NORMAL", normal_view)),
4136    );
4137    CLEARCOAT_NORMAL_VIEW.with(|m| m.borrow_mut().insert(key, node.clone()));
4138    node
4139}
4140
4141/// `AccessorsUtils.js`' `bentNormalView` — Filament's anisotropic bent normal,
4142/// the reflection normal an anisotropic surface uses for IBL radiance:
4143///
4144/// ```text
4145/// bentNormal = normalize( cross( cross( anisotropyB, V ), anisotropyB ) )
4146/// bentNormal = normalize( mix( bentNormal, normalView,
4147///                              pow4( 1 - anisotropy * ( 1 - roughness ) ) ) )
4148/// ```
4149pub fn bent_normal_view() -> NodeRef {
4150    let bent = cross(
4151        cross(anisotropy_b(), position_view_direction()),
4152        anisotropy_b(),
4153    )
4154    .normalize();
4155    // `anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2()` — two
4156    // squarings, so the base is a var read twice and the square again.
4157    let base = to_var(None, anisotropy().mul(roughness().one_minus()).one_minus());
4158    let squared = to_var(None, base.clone().mul(base));
4159    mix(bent, normal_view(), squared.clone().mul(squared)).normalize()
4160}
4161
4162// ---------------------------------------------------------------------------
4163// textures
4164// ---------------------------------------------------------------------------
4165
4166pub(crate) fn texture_node(
4167    source: TextureSource,
4168    uv: NodeRef,
4169    mode: SampleMode,
4170    ty: Type,
4171) -> NodeRef {
4172    NodeRef::new(Node::Texture {
4173        texture: Rc::new(source),
4174        uv,
4175        mode,
4176        ty,
4177    })
4178}
4179
4180/// The `texture.matrix * vec3( uv, 1.0 )` transform `TextureNode.setupUV()`
4181/// applies before sampling. `key` identifies the texture the matrix belongs to
4182/// (`(kind tag, texture id)`), so that two samples of the same map share one
4183/// uniform member the way three.js' per-texture `uniform( texture.matrix )`
4184/// does — `BumpMapNode` samples its map three times.
4185fn transformed_uv(uv: NodeRef, key: (u8, usize), matrix: Matrix3) -> NodeRef {
4186    thread_local! {
4187        static CACHE: RefCell<HashMap<(u8, usize), NodeRef>> = RefCell::new(HashMap::new());
4188    }
4189    let matrix_uniform = CACHE.with(|c| {
4190        c.borrow_mut()
4191            .entry(key)
4192            .or_insert_with(|| {
4193                uniform(
4194                    UniformSource::Value(
4195                        matrix
4196                            .to_padded_f32_array()
4197                            .iter()
4198                            .map(|&v| v as f64)
4199                            .collect(),
4200                    ),
4201                    Type::Mat3,
4202                    UniformGroup::Object,
4203                    None,
4204                )
4205            })
4206            .clone()
4207    });
4208    matrix_uniform.mul(vec3_join(vec![uv, float(1.0)])).xy()
4209}
4210
4211/// `TextureNode.getDefaultUV()` — `uv( texture.channel )`.
4212fn default_uv(map: &Texture) -> NodeRef {
4213    match map.channel() {
4214        0 => uv(),
4215        _ => uv1(),
4216    }
4217}
4218
4219/// `texture( map )`.
4220///
4221/// `TextureNode.setup()` asks the builder context before it falls back to
4222/// the default uv: `builder.context.getUV( this )` replaces `uv()` (and the
4223/// map's uv matrix is still applied after it), and
4224/// `builder.context.getTextureLevel( this )` gives the tap a level, which
4225/// makes a filtered `textureSample` a `textureSampleLevel`. Both keys are
4226/// read from the context in force when the tap is made — a material's
4227/// [`context_node`](crate::materials::MeshBasicNodeMaterial::context_node)
4228/// during its setup, or a [`context`] around an inline body. An unfilterable
4229/// map keeps its `textureLoad`, which already reads level 0.
4230pub fn texture(map: &Texture) -> NodeRef {
4231    let (get_uv, level) = current_context(|cx| {
4232        (
4233            cx.extra.get("getUV").cloned(),
4234            cx.extra.get("getTextureLevel").cloned(),
4235        )
4236    });
4237    let uv = get_uv.unwrap_or_else(|| default_uv(map));
4238    let mode = match (sample_mode_for(map), level) {
4239        (SampleMode::Sample, Some(level)) => SampleMode::Level(level),
4240        (mode, _) => mode,
4241    };
4242    texture_node(
4243        TextureSource::Texture2D(map.clone()),
4244        transformed_uv(uv, (0, map.id()), map.matrix()),
4245        mode,
4246        texture_type_for(map),
4247    )
4248}
4249
4250/// `texture( map ).context( { getUV: () => coord } )` — the map read at a
4251/// coordinate the *context* supplies. `TextureNode.setup()` takes `getUV()`'s
4252/// node in place of the default `uv()` and then still applies
4253/// `getTransformedUV()`, so unlike [`texture_uv`] the tap goes through the
4254/// map's `mat3x3` uv matrix — one shared per map, as [`texture`]'s is.
4255/// `ToonLightingModel`'s gradient lookup is the caller.
4256pub fn texture_with_uv(map: &Texture, coord: NodeRef) -> NodeRef {
4257    texture_node(
4258        TextureSource::Texture2D(map.clone()),
4259        transformed_uv(coord, (0, map.id()), map.matrix()),
4260        sample_mode_for(map),
4261        texture_type_for(map),
4262    )
4263}
4264
4265/// `texture3D( texture, null, level )` — `Texture3DNode` with a level, which
4266/// is how both volume pages read their volume: `textureSampleLevel` at a
4267/// fixed level, never the implicit-derivative `textureSample` a raymarch loop
4268/// could not use. The node is a handle for `.sample()` and `.normal()`, the
4269/// two things a raymarcher calls on it.
4270///
4271/// [`texture_3d_sampled`] is `texture3D( texture )`, with no level: the
4272/// colour lookup of `Lut3DNode`, a plain `textureSample`.
4273#[derive(Clone, Debug)]
4274pub struct Texture3DNode {
4275    source: Rc<TextureSource>,
4276    level: Option<NodeRef>,
4277}
4278
4279/// `texture3D( texture, null, level )`.
4280pub fn texture_3d(texture: &crate::textures::Data3DTexture, level: NodeRef) -> Texture3DNode {
4281    Texture3DNode {
4282        source: Rc::new(TextureSource::Texture3D(texture.clone())),
4283        level: Some(level),
4284    }
4285}
4286
4287/// `texture3D( texture )` — no level, so `.sample( uvw )` is
4288/// `textureSample`, with the implicit derivatives only a fragment stage has.
4289/// `webgpu_postprocessing_3dlut` reads its lookup table through one.
4290pub fn texture_3d_sampled(texture: &crate::textures::Data3DTexture) -> Texture3DNode {
4291    Texture3DNode {
4292        source: Rc::new(TextureSource::Texture3D(texture.clone())),
4293        level: None,
4294    }
4295}
4296
4297impl Texture3DNode {
4298    /// `textureSampleLevel` at the node's level, or `textureSample` without
4299    /// one.
4300    fn mode(&self) -> SampleMode {
4301        match &self.level {
4302            Some(level) => SampleMode::Level(level.clone()),
4303            None => SampleMode::Sample,
4304        }
4305    }
4306
4307    /// `node.sample( uv )` — the `vec4` texel at `uv` in `[ 0, 1 ]³`.
4308    pub fn sample(&self, uv: impl Into<NodeRef>) -> NodeRef {
4309        NodeRef::new(Node::Texture {
4310            texture: self.source.clone(),
4311            uv: uv.into(),
4312            mode: self.mode(),
4313            ty: Type::Vec4,
4314        })
4315    }
4316
4317    /// `node.sample( uv ).r`. Three builds the texture node itself as a
4318    /// `float` when only `.r` is read, so its var is an `f32` holding
4319    /// `textureSampleLevel( … ).x` rather than a `vec4` swizzled afterwards;
4320    /// this is the node that reproduces that.
4321    pub fn sample_r(&self, uv: impl Into<NodeRef>) -> NodeRef {
4322        NodeRef::new(Node::Texture {
4323            texture: self.source.clone(),
4324            uv: uv.into(),
4325            mode: self.mode(),
4326            ty: Type::F32,
4327        })
4328    }
4329
4330    /// `Texture3DNode.normal( uv )` — the volume's gradient at `uv` by central
4331    /// differences of `.r`, 0.01 apart, and the inward axis on the six faces
4332    /// of the unit cube. The `If().ElseIf()…Else()` chain nests exactly as
4333    /// three's does.
4334    pub fn normal(&self, uv: NodeRef) -> NodeRef {
4335        let epsilon = 0.0001;
4336        let ret = to_var(None, vec3(0.0, 0.0, 0.0));
4337        let step = 0.01;
4338        let x = self
4339            .sample_r(uv.add(vec3(-step, 0.0, 0.0)))
4340            .sub(self.sample_r(uv.add(vec3(step, 0.0, 0.0))));
4341        let y = self
4342            .sample_r(uv.add(vec3(0.0, -step, 0.0)))
4343            .sub(self.sample_r(uv.add(vec3(0.0, step, 0.0))));
4344        let z = self
4345            .sample_r(uv.add(vec3(0.0, 0.0, -step)))
4346            .sub(self.sample_r(uv.add(vec3(0.0, 0.0, step))));
4347        let arms = [
4348            (uv.x().less_than(epsilon), vec3(1.0, 0.0, 0.0)),
4349            (uv.y().less_than(epsilon), vec3(0.0, 1.0, 0.0)),
4350            (uv.z().less_than(epsilon), vec3(0.0, 0.0, 1.0)),
4351            (uv.x().greater_than(1.0 - epsilon), vec3(-1.0, 0.0, 0.0)),
4352            (uv.y().greater_than(1.0 - epsilon), vec3(0.0, -1.0, 0.0)),
4353            (uv.z().greater_than(1.0 - epsilon), vec3(0.0, 0.0, -1.0)),
4354        ];
4355        let mut chain = vec![ret.assign(vec3_join(vec![x, y, z]))];
4356        for (cond, axis) in arms.into_iter().rev() {
4357            chain = vec![if_else(cond, vec![ret.assign(axis)], chain)];
4358        }
4359        let mut statements = vec![ret.clone()];
4360        statements.extend(chain);
4361        block(statements, ret.normalize())
4362    }
4363}
4364
4365/// `storageTexture( texture )` — a `StorageTextureNode`, write-only until
4366/// [`set_access`](Self::set_access) says otherwise. It is the handle
4367/// [`texture_store`] writes through and [`load`](Self::load) reads through;
4368/// sampling the same texture in a material is `texture( texture )`, a
4369/// different binding.
4370#[derive(Clone, Debug)]
4371pub struct StorageTextureNode {
4372    source: Rc<TextureSource>,
4373}
4374
4375/// `storageTexture( StorageTexture )`.
4376pub fn storage_texture(texture: &Texture) -> StorageTextureNode {
4377    assert!(
4378        texture.is_storage(),
4379        "three-rs: storageTexture() needs a Texture::storage()"
4380    );
4381    StorageTextureNode {
4382        source: Rc::new(TextureSource::Storage(
4383            texture.clone(),
4384            crate::nodes::node::StorageAccess::WriteOnly,
4385        )),
4386    }
4387}
4388
4389/// `storageTexture3D( Storage3DTexture )`
4390/// (`src/nodes/accessors/StorageTexture3DNode.js:100`), the one-argument form;
4391/// the coordinate and value are [`texture_store`]'s, as for
4392/// [`storage_texture`].
4393pub fn storage_texture_3d(texture: &crate::textures::Data3DTexture) -> StorageTextureNode {
4394    assert!(
4395        texture.is_storage(),
4396        "three-rs: storageTexture() needs a Data3DTexture::storage()"
4397    );
4398    StorageTextureNode {
4399        source: Rc::new(TextureSource::Storage3D(
4400            texture.clone(),
4401            crate::nodes::node::StorageAccess::WriteOnly,
4402        )),
4403    }
4404}
4405
4406impl StorageTextureNode {
4407    /// `.setAccess( NodeAccess.* )`.
4408    pub fn set_access(self, access: crate::nodes::node::StorageAccess) -> Self {
4409        let source = match &*self.source {
4410            TextureSource::Storage(t, _) => TextureSource::Storage(t.clone(), access),
4411            TextureSource::Storage3D(t, _) => TextureSource::Storage3D(t.clone(), access),
4412            _ => unreachable!("three-rs: a StorageTextureNode holds a storage source"),
4413        };
4414        Self {
4415            source: Rc::new(source),
4416        }
4417    }
4418
4419    /// `.load( coord )` — `textureLoad( t, coord )`, the texel at an integer
4420    /// coordinate, with no level (`generateStorageTextureLoad()`).
4421    pub fn load(&self, coord: impl Into<NodeRef>) -> NodeRef {
4422        NodeRef::new(Node::Texture {
4423            texture: self.source.clone(),
4424            uv: coord.into(),
4425            mode: SampleMode::StorageLoad,
4426            ty: Type::Vec4,
4427        })
4428    }
4429}
4430
4431/// `textureStore( storageTexture, coord, value )` — a statement. `coord` is a
4432/// `uvec2` (a `uvec3` for a 3D texture) or anything that converts to one;
4433/// `value` is widened to a `vec4`.
4434pub fn texture_store(
4435    texture: &StorageTextureNode,
4436    coord: impl Into<NodeRef>,
4437    value: impl Into<NodeRef>,
4438) -> NodeRef {
4439    NodeRef::new(Node::TextureStore {
4440        texture: texture.source.clone(),
4441        coord: coord.into(),
4442        value: value.into(),
4443    })
4444}
4445
4446/// `NodeUtils.getTextureType( texture )`'s component count: an `RGFormat`
4447/// map (the DFG LUT, VSM's moment targets) is a `vec2` node, so the builder
4448/// caches `textureSample( … ).xy` in a `vec2<f32>` var rather than keeping
4449/// the whole `vec4`; a `RedFormat` map (`DepthOfFieldNode`'s CoC targets, a
4450/// toon gradient ramp) is a `float` node read as `textureSample( … ).x`.
4451///
4452/// A [`Texture`] carries only its wgpu format, not three's `format` / `type`
4453/// pair, so the decision is made from the wgpu format with three's mapping
4454/// spelled out: a depth format is `float` (`isDepthTexture`,
4455/// `DepthFormat`, `DepthStencilFormat`); every block-compressed format is
4456/// `vec4`, because three names them by their own compressed formats
4457/// (`RED_RGTC1_Format`, `R11_EAC_Format`, …) and never `RedFormat` /
4458/// `RGFormat`, even though BC4 / BC5 / EAC are one- or two-channel in wgpu;
4459/// and an integer format takes three's `uint` / `int` component type
4460/// (`UnsignedIntType` / `IntType`).
4461fn texture_type_for(map: &Texture) -> Type {
4462    texture_type_for_format(map.format())
4463}
4464
4465fn texture_type_for_format(format: wgpu::TextureFormat) -> Type {
4466    use wgpu::TextureSampleType as S;
4467    if format.has_depth_aspect() {
4468        return Type::F32;
4469    }
4470    if format.is_compressed() {
4471        return Type::Vec4;
4472    }
4473    let component = match format.sample_type(None, None) {
4474        Some(S::Uint) => Type::U32,
4475        Some(S::Sint) => Type::I32,
4476        _ => Type::F32,
4477    };
4478    let length = match format.components() {
4479        1 => 1,
4480        2 => 2,
4481        _ => 4,
4482    };
4483    Type::vector_of(component, length)
4484}
4485
4486/// `WGSLNodeBuilder.generateTextureSample`'s choice for a colour texture:
4487/// an unfilterable map ([`Texture::is_unfilterable`]) is bound with no
4488/// sampler and read with `textureLoad`; everything else is `textureSample`.
4489/// Every 2D-map entry point goes through this, because the sampler binding
4490/// the builder declares is decided by the same predicate and a
4491/// `textureSample` against a sampler that was never declared is a shader
4492/// compile error, not wrong pixels.
4493fn sample_mode_for(map: &Texture) -> SampleMode {
4494    if map.is_unfilterable() {
4495        SampleMode::Load
4496    } else {
4497        SampleMode::Sample
4498    }
4499}
4500
4501/// `triplanarTexture( textureX, textureY, textureZ, scale )` —
4502/// `TriplanarTextures.js`. Three axis-aligned taps of the map, blended by the
4503/// normal: `bf = normalize( abs( normalLocal ) )`, renormalised so its
4504/// components sum to one, then `texture( x, position.yz * scale ) * bf.x + …`.
4505///
4506/// The `Fn()` has no layout, so three inlines it; this is a plain Rust
4507/// function for the same reason. The taps go through [`texture_uv`], not
4508/// [`texture`]: three calls `texture( value, tx )` with an explicit uv, and
4509/// `TextureNode.setupUV()` only applies the map's uv matrix to the *default*
4510/// uv, so no texture-matrix uniform appears.
4511///
4512/// **Divergence, API shape** (`docs/nodes.md` §8): three takes texture *nodes*
4513/// and reads `.value` back off them to rebuild a tap per axis. A `NodeRef` is
4514/// an opaque `Rc<Node>` here with no way back to the `Texture`, so the port
4515/// takes the maps themselves. `None` for y or z means "sample x", exactly as
4516/// three's `null` does.
4517pub fn triplanar_texture(
4518    map_x: &Texture,
4519    map_y: Option<&Texture>,
4520    map_z: Option<&Texture>,
4521    scale: NodeRef,
4522) -> NodeRef {
4523    triplanar_textures(map_x, map_y, map_z, scale, position_local(), normal_local())
4524}
4525
4526/// Port of `BumpMapNode` — `bumpMap( texture( bumpMap ).r, materialBumpScale )`.
4527///
4528/// `dHdxy_fwd` takes three taps of the height map (at `uv`, `uv + dFdx( uv )`
4529/// and `uv + dFdy( uv )`, each through the map's own uv matrix) and
4530/// `perturbNormalArb` rebuilds the normal from them in the screen-space frame
4531/// of `positionView`, flipping with `faceDirection` on a back face.
4532///
4533/// Built inside the `NORMAL` sub-build layer, the way `NodeMaterial.setup()`
4534/// wraps `setupNormal()`: that is what makes the normal it reads the geometric
4535/// one (`NORMAL_normalView`) instead of recursing into this node.
4536pub fn bump_map(map: &Texture, scale: NodeRef) -> NodeRef {
4537    bump_map_with(|texture| texture(map).x(), scale)
4538}
4539
4540/// `bumpMap( textureNode, scaleNode )` for a height that is any expression of
4541/// texture taps, not just one map's `.r`: `webgpu_tsl_earth`'s
4542/// `bumpMap( max( texture( map ).r, cloudsStrength ) )`.
4543///
4544/// `dHdxy_fwd` samples its `textureNode` three times under a
4545/// `context( { getUV: … , forceUVContext: true } )` that moves every texture
4546/// tap inside it to `uv`, `uv + dFdx( uv )` and `uv + dFdy( uv )`. The port's
4547/// graph has no such context, so `height` is called once per tap with a
4548/// stand-in for `texture( map )` that samples at that tap's uv, through the
4549/// map's uv matrix as three's `setupUV()` does after `getUV`. Anything the
4550/// closure captures instead, such as a tap at an explicit `uv()`, is shared
4551/// by all three, which is what three's dump shows for `cloudsStrength`: the
4552/// same `nodeConst` in all three `max()`es.
4553pub fn bump_map_with(
4554    height: impl Fn(&dyn Fn(&Texture) -> NodeRef) -> NodeRef,
4555    scale: NodeRef,
4556) -> NodeRef {
4557    in_sub_build("NORMAL", || bump_map_unlayered(height, scale))
4558}
4559
4560/// [`bump_map_with`] outside the `NORMAL` layer — see
4561/// [`normal_map_scaled_unlayered`].
4562fn bump_map_unlayered(
4563    height: impl Fn(&dyn Fn(&Texture) -> NodeRef) -> NodeRef,
4564    scale: NodeRef,
4565) -> NodeRef {
4566    let tap = |coord: NodeRef| {
4567        height(&|map: &Texture| {
4568            texture_uv(
4569                map,
4570                transformed_uv(coord.clone(), (0, map.id()), map.matrix()),
4571            )
4572        })
4573    };
4574    let hll = tap(uv());
4575    let dhdxy = join(
4576        Type::Vec2,
4577        vec![
4578            tap(uv().add(dpdx(uv()))).sub(hll.clone()),
4579            tap(uv().add(dpdy(uv()))).sub(hll),
4580        ],
4581    )
4582    .mul(scale);
4583
4584    let surf_norm = normal_view();
4585    let v_sigma_x = dpdx(position_view()).normalize();
4586    let v_sigma_y = dpdy(position_view()).normalize();
4587    let r1 = cross(v_sigma_y, surf_norm.clone());
4588    let r2 = cross(surf_norm.clone(), v_sigma_x.clone());
4589    let f_det = v_sigma_x.dot(r1.clone()).mul(face_direction());
4590    let v_grad = sign(f_det.clone()).mul(dhdxy.clone().x().mul(r1).add(dhdxy.y().mul(r2)));
4591    abs(f_det).mul(surf_norm).sub(v_grad).normalize()
4592}
4593
4594/// `texture( map, uv ).grad( gradX, gradY )` — a 2-D tap with explicit
4595/// screen-space gradients, `textureSampleGrad` (`webgpu_texturegrad`). The uv
4596/// is taken as given, with no uv matrix, as for [`texture_uv`].
4597pub fn texture_grad(map: &Texture, coord: NodeRef, grad_x: NodeRef, grad_y: NodeRef) -> NodeRef {
4598    texture_node(
4599        TextureSource::Texture2D(map.clone()),
4600        coord,
4601        SampleMode::Grad(grad_x, grad_y),
4602        Type::Vec4,
4603    )
4604}
4605
4606/// `texture( map ).sample( uv ).offset( offset ).gather( component )` —
4607/// `textureGather`: channel `component` of the four texels around `uv`, from
4608/// mip level 0 (`webgpu_texturegather`). The uv is taken as given, as for
4609/// [`texture_uv`]; `offset` is a texel offset, `None` for no `.offset()`.
4610pub fn texture_gather(
4611    map: &Texture,
4612    coord: NodeRef,
4613    component: NodeRef,
4614    offset: Option<NodeRef>,
4615) -> NodeRef {
4616    texture_node(
4617        TextureSource::Texture2D(map.clone()),
4618        coord,
4619        SampleMode::Gather { component, offset },
4620        Type::Vec4,
4621    )
4622}
4623
4624/// `texture( depthTexture ).sample( uv ).offset( offset ).gather().compare( z )`
4625/// — `textureGatherCompare` on a depth texture with a comparison sampler:
4626/// the four texels' results, as a `vec4`.
4627///
4628/// The sampler is [`shadow_map_compare`]'s, `LessEqualCompare`: the one
4629/// `compareFunction` a page on the ladder sets on its own `DepthTexture`, so
4630/// the port's `DepthTexture` carries none (`docs/nodes.md` §44).
4631pub fn depth_texture_gather_compare(
4632    map: &DepthTexture,
4633    coord: NodeRef,
4634    compare: NodeRef,
4635    offset: Option<NodeRef>,
4636) -> NodeRef {
4637    texture_node(
4638        TextureSource::ShadowMap(map.clone()),
4639        coord,
4640        SampleMode::GatherCompare { compare, offset },
4641        Type::Vec4,
4642    )
4643}
4644
4645/// `texture( depthTexture ).gather().sample( uv )` — `textureGather` on a
4646/// depth texture with its ordinary (non-comparison) sampler: the four depths
4647/// around `uv`, as a `vec4`. `GTAONode` reads the centre depth this way to
4648/// sidestep the nearest-texel rounding of a half-resolution pass.
4649///
4650/// A depth texture has one channel, so WGSL's `textureGather` takes no
4651/// component; the `vec4<f32>( … )` cast around it is the same
4652/// `UnsignedIntType` quirk as [`depth_texture_gather_compare`]'s.
4653pub fn depth_texture_gather(map: &DepthTexture, coord: NodeRef) -> NodeRef {
4654    texture_node(
4655        TextureSource::Depth(map.clone()),
4656        coord,
4657        SampleMode::Gather {
4658            component: int(0),
4659            offset: None,
4660        },
4661        Type::Vec4,
4662    )
4663}
4664
4665/// `texture( map, uv, level )` — a 2-D tap at an explicit mip level.
4666///
4667/// `PMREMGenerator._getEquirectMaterial` samples the equirect source at level
4668/// `0` rather than letting the implicit derivative pick one: the six quads of
4669/// the lod plane are a wildly non-uniform parameterisation of the sphere, so
4670/// the derivative would pick a different level per face. With
4671/// `generateMipmaps = false` on the decoded HDR the two agree here, but the
4672/// WGSL has to say `textureSampleLevel( …, 0.0 )` to match three's.
4673pub fn texture_level(map: &Texture, coord: NodeRef, level: NodeRef) -> NodeRef {
4674    texture_node(
4675        TextureSource::Texture2D(map.clone()),
4676        coord,
4677        SampleMode::Level(level),
4678        Type::Vec4,
4679    )
4680}
4681
4682/// `texture( map, uv ).bias( value )` — a 2-D tap with a mip bias, the
4683/// uv taken as given (no uv matrix), as for [`texture_uv`].
4684pub fn texture_bias(map: &Texture, coord: NodeRef, bias: NodeRef) -> NodeRef {
4685    texture_node(
4686        TextureSource::Texture2D(map.clone()),
4687        coord,
4688        SampleMode::Bias(bias),
4689        Type::Vec4,
4690    )
4691}
4692
4693/// `texture( map, uv ).depth( layer )` — one layer of a
4694/// `CompressedArrayTexture`, sampled (`webgpu_textures_2d-array_compressed`).
4695/// The uv is taken as given, with no uv matrix, as for [`texture_uv`].
4696pub fn texture_array(map: &Texture, coord: NodeRef, layer: NodeRef) -> NodeRef {
4697    assert!(
4698        map.is_array(),
4699        "three-rs: texture_array needs a texture with array layers"
4700    );
4701    texture_node(
4702        TextureSource::Texture2D(map.clone()),
4703        coord,
4704        SampleMode::SampleLayer(layer),
4705        Type::Vec4,
4706    )
4707}
4708
4709/// `equirectUV( direction )` — `nodes/utils/EquirectUV.js`.
4710///
4711/// The longitude/latitude of a direction, in `[ 0, 1 ]²`. Three writes it as a
4712/// two-line `Fn`; a single-expression `Fn` inlines at its use site, which is
4713/// why three's own dump carries the whole thing on the `textureSampleLevel`
4714/// line rather than as a WGSL function.
4715pub fn equirect_uv(direction: NodeRef) -> NodeRef {
4716    let u = direction
4717        .z()
4718        .atan2(direction.x())
4719        .mul(float(1.0 / (std::f64::consts::PI * 2.0)))
4720        .add(float(0.5));
4721    let v = direction
4722        .y()
4723        .clamp(float(-1.0), float(1.0))
4724        .asin()
4725        .mul(float(1.0 / std::f64::consts::PI))
4726        .add(float(0.5));
4727    vec2_join(vec![u, v])
4728}
4729
4730/// `equirectDirection( uv )` — `nodes/utils/EquirectUV.js`, the inverse of
4731/// [`equirect_uv`]: the unit direction an equirect coordinate in `[ 0, 1 ]²`
4732/// looks along. Three's default argument is `uv()`; pass [`uv`] for it.
4733pub fn equirect_direction(uv: impl Into<NodeRef>) -> NodeRef {
4734    let uv = uv.into();
4735    let theta = uv.x().sub(0.5).mul(std::f64::consts::PI * 2.0);
4736    let phi = uv.y().sub(0.5).mul(std::f64::consts::PI);
4737    let cos_phi = phi.cos();
4738    let x = cos_phi.mul(theta.cos());
4739    let y = phi.sin();
4740    let z = cos_phi.mul(theta.sin());
4741    vec3_join(vec![x, y, z])
4742}
4743
4744/// `matcapUV` — `nodes/utils/MatcapUV.js`: the view-space normal projected
4745/// onto a frame facing the eye, scaled by `0.495` (not `0.5`, to stay off the
4746/// rim of an undersized matcap disk) into `[ 0, 1 ]²`, held in a
4747/// `matcapUV` var.
4748///
4749/// Three's is a module-level node built once (`Fn().once()().toVar()`);
4750/// this builds a fresh one per call, so bind it once per material when it is
4751/// read in several places.
4752pub fn matcap_uv() -> NodeRef {
4753    let view = position_view_direction();
4754    let x = vec3_join(vec![view.z(), float(0.0), view.x().negate()]).normalize();
4755    let y = view.cross(x.clone());
4756    to_var(
4757        Some("matcapUV"),
4758        vec2_join(vec![x.dot(normal_view()), y.dot(normal_view())])
4759            .mul(0.495)
4760            .add(0.5),
4761    )
4762}
4763
4764/// `maxMipLevel( texture( map ) )` — `MaxMipLevelNode`: an object-group
4765/// `float` uniform holding `log2( max( width, height ) )` of the map, read
4766/// each time the uniform buffer is written (three updates it per frame).
4767///
4768/// **Divergence, API shape** (`docs/nodes.md` §8): three takes the texture
4769/// *node* and reads `.value` off it; a `NodeRef` has no way back to its
4770/// `Texture`, so the port takes the map, as [`triplanar_texture`] does.
4771pub fn max_mip_level(map: &Texture) -> NodeRef {
4772    let map = map.clone();
4773    uniform(
4774        UniformSource::Live(crate::nodes::node::LiveValue::new(move || {
4775            let (width, height) = map.size();
4776            vec![f64::from(width.max(height)).log2()]
4777        })),
4778        Type::F32,
4779        UniformGroup::Object,
4780        None,
4781    )
4782}
4783
4784/// `spritesheetUV( count, uv, frame )` — `nodes/utils/SpriteSheetUV.js`: the
4785/// uv of frame `frame` (wrapped to the sheet) in a sheet of `count.x` by
4786/// `count.y` cells, numbered left to right from the top row. Three's
4787/// defaults are `uv()` and `float( 0 )`.
4788pub fn spritesheet_uv(
4789    count: impl Into<NodeRef>,
4790    uv: impl Into<NodeRef>,
4791    frame: impl Into<NodeRef>,
4792) -> NodeRef {
4793    let count = count.into();
4794    let width = count.x();
4795    let height = count.y();
4796    let frame_num = mod_float(frame, width.clone().mul(height.clone())).floor();
4797    let column = mod_float(frame_num.clone(), width.clone());
4798    let row = height.sub(ceil(frame_num.add(1.0).div(width)));
4799    let scale = count.reciprocal();
4800    uv.into().add(vec2_join(vec![column, row])).mul(scale)
4801}
4802
4803/// `triplanarTextures( textureX, textureY, textureZ, scale, position, normal )`
4804/// — `TriplanarTextures.js` with every argument explicit. Three's defaults
4805/// are `float( 1 )`, `positionLocal` and `normalLocal`, which is
4806/// [`triplanar_texture`].
4807///
4808/// **Divergence, API shape** (`docs/nodes.md` §8): the maps themselves rather
4809/// than texture nodes, as for [`triplanar_texture`].
4810pub fn triplanar_textures(
4811    map_x: &Texture,
4812    map_y: Option<&Texture>,
4813    map_z: Option<&Texture>,
4814    scale: NodeRef,
4815    position: NodeRef,
4816    normal: NodeRef,
4817) -> NodeRef {
4818    let map_y = map_y.unwrap_or(map_x);
4819    let map_z = map_z.unwrap_or(map_x);
4820
4821    let bf = normal.abs().normalize();
4822    let bf = bf.clone().div(bf.dot(vec3(1.0, 1.0, 1.0)));
4823
4824    let tx = position.yz().mul(scale.clone());
4825    let ty = position.zx().mul(scale.clone());
4826    let tz = position.xy().mul(scale);
4827
4828    let cx = texture_uv(map_x, tx).mul(bf.x());
4829    let cy = texture_uv(map_y, ty).mul(bf.y());
4830    let cz = texture_uv(map_z, tz).mul(bf.z());
4831
4832    cx.add(cy).add(cz)
4833}
4834
4835/// `textureBicubic( texture( map, uv ), strength )` —
4836/// `TextureBicubic.js`: [`texture_bicubic_level`] at
4837/// `strength * maxMipLevel( map )`.
4838///
4839/// **Divergence, API shape** (`docs/nodes.md` §8): three reads the map and
4840/// the uv back off the texture node; the port takes them separately.
4841pub fn texture_bicubic(map: &Texture, uv: NodeRef, strength: impl Into<NodeRef>) -> NodeRef {
4842    let lod = strength.into().mul(max_mip_level(map));
4843    texture_bicubic_level(map, uv, lod)
4844}
4845
4846/// `textureBicubicLevel( texture( map, uv ), lod )` — N8's mipped bicubic
4847/// filter (`TextureBicubic.js`): four bilinear taps at the floor level and
4848/// four at the ceiling level, weighted by the B-spline, then mixed by the
4849/// fractional part of `lod`.
4850pub fn texture_bicubic_level(map: &Texture, uv: NodeRef, lod: impl Into<NodeRef>) -> NodeRef {
4851    let lod = lod.into();
4852    let size = |level: NodeRef| {
4853        texture_size(TextureSource::Texture2D(map.clone()), level.to_int()).to_vec2()
4854    };
4855    let lod_size = vec4_join(vec![size(lod.clone()), size(lod.add(1.0))]);
4856    let lod_size_inv = float(1.0).div(lod_size.clone());
4857    let uv_scaled = uv.swizzle("xyxy").mul(lod_size).add(0.5);
4858    let iuv = uv_scaled.floor();
4859    let fuv = uv_scaled.fract();
4860
4861    let (g0, g1, h0, h1) = bicubic_weights(&fuv);
4862
4863    let p0 = iuv.clone().add(h0).sub(0.5).mul(lod_size_inv.clone());
4864    let p3 = iuv.add(h1).sub(0.5).mul(lod_size_inv);
4865
4866    let f_sample = bicubic(map, &p0.xy(), &p3.xy(), &g0.xy(), &g1.xy(), lod.floor());
4867    let c_sample = bicubic(
4868        map,
4869        &p0.zw(),
4870        &p3.zw(),
4871        &g0.zw(),
4872        &g1.zw(),
4873        ceil(lod.clone()),
4874    );
4875
4876    lod.fract().mix(f_sample, c_sample)
4877}
4878
4879/// `bicubicWeights( a )` in `TextureBicubic.js`: the cubic B-spline's four
4880/// weights folded into two bilinear taps — `g0`/`g1` the tap weights,
4881/// `h0`/`h1` their offsets.
4882fn bicubic_weights(a: &NodeRef) -> (NodeRef, NodeRef, NodeRef, NodeRef) {
4883    let bc = 1.0 / 6.0;
4884    let w0 = float(bc).mul(a.mul(a.mul(a.negate().add(3.0)).sub(3.0)).add(1.0));
4885    let w1 = float(bc).mul(a.mul(a.mul(float(3.0).mul(a.clone()).sub(6.0))).add(4.0));
4886    let w2 = float(bc).mul(
4887        a.mul(a.mul(float(-3.0).mul(a.clone()).add(3.0)).add(3.0))
4888            .add(1.0),
4889    );
4890    let w3 = float(bc).mul(a.pow(float(3.0)));
4891
4892    let g0 = w0.add(w1.clone());
4893    let g1 = w2.add(w3.clone());
4894    let h0 = float(-1.0).add(w1.div(g0.clone()));
4895    let h1 = float(1.0).add(w3.div(g1.clone()));
4896    (g0, g1, h0, h1)
4897}
4898
4899/// `bicubic( textureNode, p0, p3, g0, g1, lod )` in `TextureBicubic.js`: the
4900/// four taps at one level.
4901fn bicubic(
4902    map: &Texture,
4903    p0: &NodeRef,
4904    p3: &NodeRef,
4905    g0: &NodeRef,
4906    g1: &NodeRef,
4907    lod: NodeRef,
4908) -> NodeRef {
4909    let p1 = vec2_join(vec![p3.x(), p0.y()]);
4910    let p2 = vec2_join(vec![p0.x(), p3.y()]);
4911    let tap = |p: NodeRef| texture_level(map, p, lod.clone());
4912
4913    let a = g0
4914        .y()
4915        .mul(g0.x().mul(tap(p0.clone())).add(g1.x().mul(tap(p1))));
4916    let b = g1
4917        .y()
4918        .mul(g0.x().mul(tap(p2)).add(g1.x().mul(tap(p3.clone()))));
4919    a.add(b)
4920}
4921
4922/// The node type `getTextureType()` gives a volume: `float` for a one-channel
4923/// format, `vec2` for two, `vec4` otherwise.
4924fn texture_3d_type(volume: &crate::textures::Data3DTexture) -> Type {
4925    match volume.format().components() {
4926        1 => Type::F32,
4927        2 => Type::Vec2,
4928        _ => Type::Vec4,
4929    }
4930}
4931
4932/// `texture3DLoad( volume, coord )` — `Texture3DNode` with `setSampler(
4933/// false )`: the texel at integer `coord` of mip 0, a `textureLoad`. The
4934/// node is typed by the volume's format as three's is (a `RedFormat` volume
4935/// is a `float` node, so its var holds `textureLoad( … ).x`).
4936///
4937/// The volume must still be filterable (`LinearFilter`): the binding of a
4938/// `NearestFilter` volume, sampler-less in three, is not ported (see
4939/// [`texture_3d`]).
4940pub fn texture_3d_load(volume: &crate::textures::Data3DTexture, coord: NodeRef) -> NodeRef {
4941    texture_node(
4942        TextureSource::Texture3D(volume.clone()),
4943        coord.to_ivec3(),
4944        SampleMode::LoadTexel,
4945        texture_3d_type(volume),
4946    )
4947}
4948
4949/// `texture3DLevel( volume, uv, level )` — a `textureSampleLevel` of the
4950/// volume at `uv` in `[ 0, 1 ]³` and an explicit mip level, typed by the
4951/// volume's format as [`texture_3d_load`] is.
4952pub fn texture_3d_level(
4953    volume: &crate::textures::Data3DTexture,
4954    uv: NodeRef,
4955    level: impl Into<NodeRef>,
4956) -> NodeRef {
4957    texture_node(
4958        TextureSource::Texture3D(volume.clone()),
4959        uv,
4960        SampleMode::Level(level.into()),
4961        texture_3d_type(volume),
4962    )
4963}
4964
4965/// `texture( map ).sample( uv )` — the same tap as [`texture_uv`], but through
4966/// the map's `mat3x3` uv matrix.
4967///
4968/// `TextureNode.sample()` *clones* the texture node and leaves `updateMatrix`
4969/// on, so every sample of one map carries its **own** `uniform( texture.matrix
4970/// )` — `BloomNode`'s separable blur samples one texture three times and
4971/// three's dump has three `mat3x3` members for it (`dump/m05`). [`texture`]
4972/// shares one matrix per map instead, which is what three does when the same
4973/// *node* is read twice.
4974pub fn texture_sample(map: &Texture, coord: NodeRef) -> NodeRef {
4975    let matrix = uniform(
4976        UniformSource::Value(
4977            map.matrix()
4978                .to_padded_f32_array()
4979                .iter()
4980                .map(|&v| v as f64)
4981                .collect(),
4982        ),
4983        Type::Mat3,
4984        UniformGroup::Object,
4985        None,
4986    );
4987    texture_uv(map, matrix.mul(vec3_join(vec![coord, float(1.0)])).xy())
4988}
4989
4990/// `texture( map, uv )` without the default UV.
4991///
4992/// A map that is `NearestFilter` on both sides is *unfilterable*
4993/// (`Texture::is_unfilterable`): three binds it with no sampler and every
4994/// tap becomes a `textureLoad`, which is why `webgpu_mrt`'s composite shader
4995/// has four bare `texture_2d<f32>` bindings and no `_sampler` beside any of
4996/// them.
4997pub fn texture_uv(map: &Texture, coord: NodeRef) -> NodeRef {
4998    texture_node(
4999        TextureSource::Texture2D(map.clone()),
5000        coord,
5001        sample_mode_for(map),
5002        texture_type_for(map),
5003    )
5004}
5005
5006/// `texture( depthTexture )` — a depth texture is not filterable, so three.js
5007/// emits a `textureLoad` with no sampler binding at all.
5008pub fn depth_texture(map: &DepthTexture) -> NodeRef {
5009    texture_node(
5010        TextureSource::Depth(map.clone()),
5011        transformed_uv(uv(), (1, map.id()), Matrix3::identity()),
5012        SampleMode::Load,
5013        Type::F32,
5014    )
5015}
5016
5017/// `texture( depthTexture ).sample( uv )` — the [`depth_texture`] load at an
5018/// explicit coordinate, through a `mat3x3` uv matrix of its own.
5019///
5020/// As with [`texture_sample`], `TextureNode.sample()` clones the node and
5021/// keeps `updateMatrix` on, so the tap carries a fresh `uniform(
5022/// texture.matrix )` rather than sharing the map's. `ShadowNode`'s
5023/// `VSMPassVertical` reads the shadow map's depth this way.
5024pub fn depth_texture_sample(map: &DepthTexture, coord: NodeRef) -> NodeRef {
5025    let matrix = uniform(
5026        UniformSource::Value(
5027            Matrix3::identity()
5028                .to_padded_f32_array()
5029                .iter()
5030                .map(|&v| v as f64)
5031                .collect(),
5032        ),
5033        Type::Mat3,
5034        UniformGroup::Object,
5035        None,
5036    );
5037    texture_node(
5038        TextureSource::Depth(map.clone()),
5039        matrix.mul(vec3_join(vec![coord, float(1.0)])).xy(),
5040        SampleMode::Load,
5041        Type::F32,
5042    )
5043}
5044
5045/// `passNode.getTextureNode( 'depth' )` — the same `textureLoad` as
5046/// [`depth_texture`], but with the raw `uv()` varying and no texture matrix:
5047/// a `PassTextureNode` calls `setUpdateMatrix( false )`, so the pass's depth
5048/// attachment carries no `mat3x3` in the object uniform block.
5049pub fn pass_depth_texture(map: &DepthTexture) -> NodeRef {
5050    pass_depth_texture_uv(map, uv())
5051}
5052
5053/// `passNode.getTextureNode( 'depth' ).sample( coord )` — the pass's depth
5054/// attachment read at another uv, as `PixelationPassNode`'s neighbour taps
5055/// read it.
5056pub fn pass_depth_texture_uv(map: &DepthTexture, coord: NodeRef) -> NodeRef {
5057    texture_node(
5058        TextureSource::Depth(map.clone()),
5059        coord,
5060        SampleMode::Load,
5061        Type::F32,
5062    )
5063}
5064
5065/// `cubeTexture( map ).sample( dir )`. Cube UVs get their x negated, which is
5066/// `WGSLNodeBuilder.generateTextureSample`'s `vec3( - uv.x, uv.yz )`.
5067pub fn cube_texture(map: &CubeTexture, dir: NodeRef) -> NodeRef {
5068    let dir = vec3_join(vec![dir.x().negate(), dir.yz()]);
5069    texture_node(
5070        TextureSource::Cube(map.clone()),
5071        dir,
5072        SampleMode::Sample,
5073        Type::Vec4,
5074    )
5075}
5076
5077/// `cubeTexture( shadowMap, dir ).compare( dp )` for a `CubeDepthTexture`.
5078///
5079/// `CubeTextureNode.setupUV()` takes the depth-texture branch: no environment
5080/// rotation, and the WebGPU Y flip — `vec3( uv.x, uv.y.negate(), uv.z )`.
5081pub fn cube_depth_texture_compare(map: &CubeDepthTexture, dir: NodeRef, dp: NodeRef) -> NodeRef {
5082    let dir = vec3_join(vec![dir.x(), dir.y().negate(), dir.z()]);
5083    texture_node(
5084        TextureSource::CubeDepth(map.clone()),
5085        dir,
5086        SampleMode::Compare(dp),
5087        Type::F32,
5088    )
5089}
5090
5091/// `cubeTexture( map ).sample( dir ).level( lod )`.
5092pub fn cube_texture_level(map: &CubeTexture, dir: NodeRef, level: NodeRef) -> NodeRef {
5093    let dir = vec3_join(vec![dir.x().negate(), dir.yz()]);
5094    texture_node(
5095        TextureSource::Cube(map.clone()),
5096        dir,
5097        SampleMode::Level(level),
5098        Type::Vec4,
5099    )
5100}
5101
5102// ---------------------------------------------------------------------------
5103// buffers
5104// ---------------------------------------------------------------------------
5105
5106/// `instancedArray( count, type )` — `StorageBufferNode` over a
5107/// `StorageInstancedBufferAttribute` with **no CPU array behind it**
5108/// (`src/nodes/accessors/StorageBufferNode.js:270-290`): the storage is created
5109/// on the GPU, zero-filled once, and only ever written by a compute pass.
5110///
5111/// Held by the caller, because its identity is the buffer: two
5112/// `instancedArray( n, ty )` calls are two buffers, exactly as two
5113/// `StorageBufferNode`s are in three.js, and the renderer keys the GPU buffer
5114/// on it.
5115///
5116/// `per_vertex` is `true` only for [`attribute_array`]: the attribute three
5117/// puts behind the storage node is a plain `StorageBufferAttribute`, so
5118/// [`to_attribute`](StorageArray::to_attribute) steps once per vertex.
5119#[derive(Clone)]
5120pub struct StorageArray {
5121    buffer: Rc<BufferNode>,
5122    per_vertex: bool,
5123}
5124
5125/// `instancedArray( count, type )`.
5126pub fn instanced_array(count: usize, element_ty: Type) -> StorageArray {
5127    StorageArray {
5128        buffer: Rc::new(BufferNode {
5129            id: crate::nodes::node::BufferId::next(),
5130            source: BufferSource::Storage,
5131            element_ty,
5132            count,
5133        }),
5134        per_vertex: false,
5135    }
5136}
5137
5138/// `attributeArray( count, type )` (`src/nodes/accessors/Arrays.js:15`) —
5139/// [`instanced_array`] over a `StorageBufferAttribute` instead of a
5140/// `StorageInstancedBufferAttribute`. A kernel sees the same storage buffer;
5141/// the one difference is [`to_attribute`](StorageArray::to_attribute), which
5142/// reads it once per vertex rather than once per instance. Struct element
5143/// types (`type.isStructTypeNode`) are not ported, as for `instanced_array`.
5144pub fn attribute_array(count: usize, element_ty: Type) -> StorageArray {
5145    StorageArray {
5146        per_vertex: true,
5147        ..instanced_array(count, element_ty)
5148    }
5149}
5150
5151/// `storageElement( storageBufferNode, indexNode )` — a
5152/// `StorageArrayElementNode` (`src/nodes/utils/StorageArrayElementNode.js:143`),
5153/// which is what `.element( index )` builds in three; see
5154/// [`StorageArray::element`].
5155pub fn storage_element(storage: &StorageArray, index: impl Into<NodeRef>) -> NodeRef {
5156    storage.element(index)
5157}
5158
5159impl StorageArray {
5160    /// `.element( index )` — `NodeBuffer_N.value[ index ]`.
5161    pub fn element(&self, index: impl Into<NodeRef>) -> NodeRef {
5162        NodeRef::new(Node::BufferElement {
5163            buffer: self.buffer.clone(),
5164            index: index.into(),
5165        })
5166    }
5167
5168    /// The buffer's identity, which is how the renderer finds its GPU buffer.
5169    pub fn id(&self) -> crate::nodes::node::BufferId {
5170        self.buffer.id
5171    }
5172
5173    /// The element count `instancedArray` was given.
5174    pub fn count(&self) -> usize {
5175        self.buffer.count
5176    }
5177
5178    /// The element type `instancedArray` was given.
5179    pub fn element_ty(&self) -> Type {
5180        self.buffer.element_ty
5181    }
5182}
5183
5184impl StorageArray {
5185    /// `.toAtomic()` — the same buffer, its elements declared `atomic< T >`
5186    /// (`StorageBufferNode.setAtomic( true )`), so they are read and written
5187    /// only through the [atomic functions](atomic_add).
5188    ///
5189    /// Three flips a flag on the node it was called on; here the call hands
5190    /// back the atomic view, which keeps the buffer's identity (and so its GPU
5191    /// buffer) and replaces the plain one. Use one or the other in a program:
5192    /// the declaration is per buffer.
5193    pub fn to_atomic(&self) -> StorageArray {
5194        assert!(
5195            matches!(self.buffer.element_ty, Type::U32 | Type::I32),
5196            "three-rs: an atomic storage array holds u32 or i32 (WGSL atomic<T>)"
5197        );
5198        StorageArray {
5199            buffer: Rc::new(BufferNode {
5200                id: self.buffer.id,
5201                source: BufferSource::AtomicStorage,
5202                element_ty: self.buffer.element_ty,
5203                count: self.buffer.count,
5204            }),
5205            per_vertex: self.per_vertex,
5206        }
5207    }
5208}
5209
5210/// `WebGPUAttributeUtils.createAttribute()`'s storage stride, in floats: a
5211/// `vec3` is padded to four ("WGSL does not support packed vec3 data in
5212/// storage buffers"), everything else is packed.
5213fn storage_item_size(element_ty: Type) -> usize {
5214    match element_ty.components() {
5215        3 => 4,
5216        n => n,
5217    }
5218}
5219
5220/// `storage( attribute, type, attribute.count )` over an attribute that has a
5221/// CPU array: `new StorageInstancedBufferAttribute( array, itemSize )`, or
5222/// `computeSkinning()`'s `new InstancedBufferAttribute( array, itemSize )`.
5223///
5224/// `words` are the array's elements as bits (`f32::to_bits` for a float
5225/// array, the integers themselves for a `Uint32Array`), `itemSize` of them per
5226/// element and unpadded, as the typed array holds them. They are laid out at
5227/// the storage stride here, which is what the GPU buffer gets.
5228pub fn storage_data(words: &[u32], element_ty: Type) -> StorageArray {
5229    let item_size = element_ty.components();
5230    let stride = storage_item_size(element_ty);
5231    let count = words.len() / item_size;
5232    let mut init = vec![0u32; count * stride];
5233    for (i, element) in words.chunks_exact(item_size).enumerate() {
5234        init[i * stride..i * stride + item_size].copy_from_slice(element);
5235    }
5236    StorageArray {
5237        buffer: Rc::new(BufferNode {
5238            id: crate::nodes::node::BufferId::next(),
5239            source: BufferSource::StorageData {
5240                init: Rc::new(init),
5241                read_only: false,
5242            },
5243            element_ty,
5244            count,
5245        }),
5246        per_vertex: false,
5247    }
5248}
5249
5250/// [`storage_data`] over a float array.
5251pub fn storage_f32(array: &[f32], element_ty: Type) -> StorageArray {
5252    let words: Vec<u32> = array.iter().map(|v| v.to_bits()).collect();
5253    storage_data(&words, element_ty)
5254}
5255
5256/// `storage( attribute, type, count )` over a
5257/// [`StorageBufferAttribute`](crate::core::StorageBufferAttribute) — a
5258/// `StorageBufferNode` whose buffer **is** the attribute's: the node takes the
5259/// attribute's [`BufferId`](crate::nodes::node::BufferId) and its contents
5260/// (8- and 16-bit integers widened to 32 bits, at the padded storage stride,
5261/// as `createAttribute()` uploads them) as the buffer's initial data, so a
5262/// kernel writing this node and a draw reading the attribute from the
5263/// geometry meet on one GPU buffer.
5264///
5265/// [`to_attribute`](StorageArray::to_attribute) steps per vertex for a
5266/// `StorageBufferAttribute` and per instance for a
5267/// `StorageInstancedBufferAttribute`, as three's `attributeArray` /
5268/// `instancedArray` do.
5269///
5270/// # Panics
5271///
5272/// If `element_ty` has a different component count from the attribute's
5273/// `item_size`: the node would index the buffer at a stride the attribute
5274/// does not lay it out at.
5275pub fn storage(
5276    attribute: &crate::core::StorageBufferAttribute,
5277    element_ty: Type,
5278    count: usize,
5279) -> StorageArray {
5280    assert_eq!(
5281        element_ty.components(),
5282        attribute.item_size,
5283        "three-rs: storage() over a StorageBufferAttribute of itemSize {} wants a type of that many components, got {element_ty:?}",
5284        attribute.item_size
5285    );
5286    StorageArray {
5287        buffer: Rc::new(BufferNode {
5288            id: attribute.id(),
5289            source: BufferSource::StorageData {
5290                init: Rc::new(attribute.init_words(false)),
5291                read_only: false,
5292            },
5293            element_ty,
5294            count,
5295        }),
5296        per_vertex: !attribute.is_instanced(),
5297    }
5298}
5299
5300impl StorageArray {
5301    /// `.toReadOnly()` — `var<storage, read>` in a kernel as well. The same
5302    /// buffer, so the same GPU buffer; only the declaration changes.
5303    pub fn to_read_only(&self) -> StorageArray {
5304        let source = match &self.buffer.source {
5305            BufferSource::StorageData { init, .. } => BufferSource::StorageData {
5306                init: init.clone(),
5307                read_only: true,
5308            },
5309            _ => panic!("three-rs: to_read_only() is ported for storage over a CPU array"),
5310        };
5311        StorageArray {
5312            buffer: Rc::new(BufferNode {
5313                id: self.buffer.id,
5314                source,
5315                element_ty: self.buffer.element_ty,
5316                count: self.buffer.count,
5317            }),
5318            per_vertex: self.per_vertex,
5319        }
5320    }
5321
5322    /// `.toAttribute()` — `bufferAttribute( storageAttribute, type )`: the
5323    /// storage buffer read as a vertex attribute. For [`instanced_array`] it
5324    /// is an `InstancedBufferAttribute` (`StorageInstancedBufferAttribute`),
5325    /// so it steps once per instance; for [`attribute_array`] it steps once
5326    /// per vertex. Either way it is the *same* GPU buffer the kernels write —
5327    /// the vertex buffer shares the storage node's id. The stride is the
5328    /// padded storage stride: a `vec3` array is read 16 bytes apart.
5329    pub fn to_attribute(&self) -> NodeRef {
5330        let buffer = Rc::new(InstanceBuffer {
5331            id: self.buffer.id,
5332            source: self.buffer.source.clone(),
5333            count: self.buffer.count,
5334            item_size: storage_item_size(self.buffer.element_ty),
5335            per_vertex: self.per_vertex,
5336        });
5337        instanced_attribute(&buffer, 0, self.buffer.element_ty)
5338    }
5339}
5340
5341/// A `ComputeNode` read as a value — `Fn( () => { …; return output } )()
5342/// .compute( count )` set as, say, a material's `positionNode`.
5343///
5344/// Outside the compute stage three's `ComputeNode.generate()` returns its
5345/// `outputComputeNode` (the `Fn`'s return value) and its `updateBefore`
5346/// (`NodeUpdateType.FRAME`) runs `renderer.compute( this )`: the kernel is
5347/// dispatched once per frame before the pass that draws with its result. The
5348/// statements of `flow` are the kernel; `output` is what the vertex stage
5349/// reads. `flow.on_init` runs once, before the first dispatch, as usual.
5350pub fn compute_node(flow: crate::nodes::ComputeFlow, output: NodeRef) -> NodeRef {
5351    NodeRef::new(Node::Compute {
5352        flow: Rc::new(flow),
5353        output,
5354    })
5355}
5356
5357/// The explicit object's `matrixWorld`, read when the buffer is written.
5358fn object_matrix_world(object: &crate::core::ObjectRef, name: &'static str) -> LiveValue {
5359    let object = object.downgrade();
5360    LiveValue::new(move || {
5361        let object = object
5362            .upgrade()
5363            .unwrap_or_else(|| panic!("three-rs: {name}( object ) outlived its object"));
5364        let world = object.borrow().matrix_world;
5365        world.elements.to_vec()
5366    })
5367}
5368
5369/// `objectDirection( object3d )` — `Object3DNode( DIRECTION, object3d )`:
5370/// `object3d.getWorldDirection()`, an object-group `vec3`. As in three, the
5371/// read refreshes `object3d`'s world matrix (`updateWorldMatrix( true, false
5372/// )`) first, and a camera's direction is negated (`Camera.getWorldDirection()`),
5373/// so a camera yields the way it looks. Each call is a uniform of its own, as
5374/// each `Object3DNode` is in three.
5375pub fn object_direction(object: &crate::core::ObjectRef) -> NodeRef {
5376    let object = object.downgrade();
5377    let direction = LiveValue::new(move || {
5378        let object = object
5379            .upgrade()
5380            .unwrap_or_else(|| panic!("three-rs: objectDirection( object ) outlived its object"));
5381        let mut direction = object.get_world_direction();
5382        if object.borrow().is_camera {
5383            direction.negate();
5384        }
5385        vec![direction.x, direction.y, direction.z]
5386    });
5387    object_3d_uniform(Object3DScope::Direction, Some(direction))
5388}
5389
5390/// `objectPosition( object3d )` — `Object3DNode( POSITION, object3d )`:
5391/// `object3d`'s world position.
5392pub fn object_position(object: &crate::core::ObjectRef) -> NodeRef {
5393    object_3d_uniform(
5394        Object3DScope::Position,
5395        Some(object_matrix_world(object, "objectPosition")),
5396    )
5397}
5398
5399/// `objectScale( object3d )` — `Object3DNode( SCALE, object3d )`:
5400/// `object3d`'s world scale.
5401pub fn object_scale(object: &crate::core::ObjectRef) -> NodeRef {
5402    object_3d_uniform(
5403        Object3DScope::Scale,
5404        Some(object_matrix_world(object, "objectScale")),
5405    )
5406}
5407
5408/// `objectViewPosition( object3d )` — `Object3DNode( VIEW_POSITION, object3d
5409/// )`: `object3d`'s world position in the rendering camera's view space.
5410pub fn object_view_position(object: &crate::core::ObjectRef) -> NodeRef {
5411    object_3d_uniform(
5412        Object3DScope::ViewPosition,
5413        Some(object_matrix_world(object, "objectViewPosition")),
5414    )
5415}
5416
5417/// `objectRadius( object3d )` — `Object3DNode( RADIUS, object3d )`. As in
5418/// three, the sphere is the bounding sphere of the *drawn* object's geometry
5419/// (`frame.object.geometry`), scaled by `object3d`'s `matrixWorld`; a draw
5420/// with no geometry uploads 0.
5421pub fn object_radius(object: &crate::core::ObjectRef) -> NodeRef {
5422    object_3d_uniform(
5423        Object3DScope::Radius,
5424        Some(object_matrix_world(object, "objectRadius")),
5425    )
5426}
5427
5428/// `objectWorldMatrix( object3d )` — `Object3DNode( WORLD_MATRIX, object3d )`
5429/// with an explicit object: an object-group `mat4` that reads
5430/// `object3d.matrixWorld` whenever the buffer is written, in a draw or in a
5431/// kernel.
5432pub fn object_world_matrix(object: &crate::core::ObjectRef) -> NodeRef {
5433    uniform(
5434        UniformSource::Live(object_matrix_world(object, "objectWorldMatrix")),
5435        Type::Mat4,
5436        UniformGroup::Object,
5437        None,
5438    )
5439}
5440
5441/// `shapeCircle( coord = uv() )` (`src/nodes/shapes/Shapes.js`): 1 inside the
5442/// unit circle over the quad, 0 outside — softened over one `fwidth` when the
5443/// material has `alphaToCoverage` and the target is multisampled.
5444///
5445/// Three reads `material.alphaToCoverage` and `renderer.currentSamples` inside
5446/// the `Fn` body, i.e. at build time; the body here does the same from the
5447/// [`BuildContext`](crate::nodes::builder) the renderer installs around the
5448/// build, so one node serves both branches.
5449pub fn shape_circle() -> NodeRef {
5450    thread_local! {
5451        static DEF: Rc<FnDef> = inline_fn(1, Type::F32, |args| {
5452            let coord = args[0].clone();
5453            let len2 = length_sq(coord.mul(2.0).sub(1.0));
5454            let smooth = crate::nodes::builder::current_context(|cx| cx.alpha_to_coverage_samples);
5455            if smooth {
5456                let dlen = to_var(None, fwidth(len2.clone()));
5457                smoothstep(dlen.one_minus(), dlen.add(1.0), len2).one_minus()
5458            } else {
5459                len2.greater_than(1.0).select(float(0.0), float(1.0))
5460            }
5461        });
5462    }
5463    DEF.with(|def| call(def, vec![uv()]))
5464}
5465
5466pub use super::node::StructLayout;
5467/// One member of [`struct_type`]'s object — `'uint'`, or `{ type: 'uint',
5468/// atomic: true }` with [`atomic`](StructMember::atomic) set.
5469pub use super::node::StructMember;
5470
5471/// `struct( { name: type, … }, 'Name' )` — `StructTypeNode`, a named WGSL
5472/// struct laid out in the members' order.
5473pub fn struct_type(name: &'static str, members: Vec<StructMember>) -> Rc<StructLayout> {
5474    Rc::new(StructLayout { name, members })
5475}
5476
5477/// `structType( values )` — `StructNode`: a value of `layout`, one value per
5478/// member in member order. See [`Node::StructNew`].
5479pub fn struct_new(layout: &Rc<StructLayout>, values: Vec<NodeRef>) -> NodeRef {
5480    assert_eq!(
5481        values.len(),
5482        layout.members.len(),
5483        "three-rs: a struct value takes one value per member"
5484    );
5485    NodeRef::new(Node::StructNew {
5486        layout: layout.clone(),
5487        values,
5488    })
5489}
5490
5491/// `structNode.get( name )` — one member of a value of `layout`: a
5492/// [`struct_new`], or a [`block`] whose result is one.
5493pub fn struct_get(value: &NodeRef, layout: &Rc<StructLayout>, name: &str) -> NodeRef {
5494    let member = layout
5495        .members
5496        .iter()
5497        .position(|m| m.name == name)
5498        .unwrap_or_else(|| panic!("three-rs: struct {} has no member {name}", layout.name));
5499    NodeRef::new(Node::StructGet {
5500        value: value.clone(),
5501        layout: layout.clone(),
5502        member,
5503    })
5504}
5505
5506impl StructMember {
5507    /// `name: 'type'`.
5508    pub fn new(name: &'static str, ty: Type) -> Self {
5509        Self {
5510            name,
5511            ty,
5512            atomic: false,
5513        }
5514    }
5515
5516    /// `name: { type, atomic: true }`.
5517    pub fn atomic(name: &'static str, ty: Type) -> Self {
5518        Self {
5519            name,
5520            ty,
5521            atomic: true,
5522        }
5523    }
5524}
5525
5526/// `storage( indirectAttribute, structType, count )` over an
5527/// `IndirectStorageBufferAttribute`: a `StorageBufferNode` whose WGSL type is
5528/// the struct itself. Held like a [`StorageArray`]; its identity is the
5529/// attribute's, so the GPU buffer a kernel writes through it is the one
5530/// `geometry.setIndirect()` draws from.
5531#[derive(Clone)]
5532pub struct StorageStruct(Rc<BufferNode>);
5533
5534/// `storage( attribute, struct( … ), attribute.count )`.
5535///
5536/// Three accepts any struct over any storage attribute; the port takes the
5537/// one case the ladder has — a single struct, one `u32` per member, over an
5538/// `IndirectStorageBufferAttribute` — and asserts the sizes agree.
5539pub fn storage_struct(
5540    attribute: &crate::core::IndirectStorageBufferAttribute,
5541    layout: Rc<StructLayout>,
5542) -> StorageStruct {
5543    assert!(
5544        layout
5545            .members
5546            .iter()
5547            .all(|m| matches!(m.ty, Type::U32 | Type::I32 | Type::F32)),
5548        "three-rs: storage_struct() lays out 4-byte scalar members only"
5549    );
5550    assert_eq!(
5551        layout.members.len(),
5552        attribute.array().len(),
5553        "three-rs: struct {} does not cover the indirect attribute's words",
5554        layout.name
5555    );
5556    StorageStruct(Rc::new(BufferNode {
5557        id: attribute.id(),
5558        source: BufferSource::Struct {
5559            layout,
5560            init: attribute.array(),
5561        },
5562        element_ty: Type::U32,
5563        count: attribute.count(),
5564    }))
5565}
5566
5567impl StorageStruct {
5568    /// `.get( 'member' )` — `MemberNode`: `NodeBuffer_N.member`.
5569    pub fn get(&self, member: &str) -> NodeRef {
5570        let BufferSource::Struct { layout, .. } = &self.0.source else {
5571            unreachable!("three-rs: a StorageStruct is always a struct buffer")
5572        };
5573        NodeRef::new(Node::StructMember {
5574            buffer: self.0.clone(),
5575            member: layout.member(member),
5576        })
5577    }
5578}
5579
5580// ---------------------------------------------------------------------------
5581// atomics, workgroup memory and barriers (`src/nodes/gpgpu/`)
5582// ---------------------------------------------------------------------------
5583
5584/// `atomicFunc( method, pointerNode, valueNode )` — an `AtomicFunctionNode`
5585/// for any WGSL atomic builtin (`src/nodes/gpgpu/AtomicFunctionNode.js:228`):
5586/// `method` is its name (`"atomicAdd"`, three's
5587/// `AtomicFunctionNode.ATOMIC_ADD`), `value` its operand, `None` for
5588/// `atomicLoad`. Three's `.toStack()` is the caller putting the node in the
5589/// kernel's statements, as for every function below.
5590pub fn atomic_func(
5591    method: &'static str,
5592    pointer: impl Into<NodeRef>,
5593    value: Option<NodeRef>,
5594) -> NodeRef {
5595    NodeRef::new(Node::Atomic {
5596        method,
5597        pointer: pointer.into(),
5598        value,
5599    })
5600}
5601
5602macro_rules! atomic_fns {
5603    ($($(#[$m:meta])* $name:ident => $method:literal;)*) => {
5604        $(
5605            $(#[$m])*
5606            pub fn $name(pointer: impl Into<NodeRef>, value: impl Into<NodeRef>) -> NodeRef {
5607                atomic_func($method, pointer, Some(value.into()))
5608            }
5609        )*
5610    };
5611}
5612
5613atomic_fns! {
5614    /// `atomicStore( pointer, value )`.
5615    atomic_store => "atomicStore";
5616    /// `atomicAdd( pointer, value )` — returns the old value.
5617    atomic_add => "atomicAdd";
5618    /// `atomicSub( pointer, value )`.
5619    atomic_sub => "atomicSub";
5620    /// `atomicMax( pointer, value )`.
5621    atomic_max => "atomicMax";
5622    /// `atomicMin( pointer, value )`.
5623    atomic_min => "atomicMin";
5624    /// `atomicAnd( pointer, value )`.
5625    atomic_and => "atomicAnd";
5626    /// `atomicOr( pointer, value )`.
5627    atomic_or => "atomicOr";
5628    /// `atomicXor( pointer, value )`.
5629    atomic_xor => "atomicXor";
5630}
5631
5632/// `atomicLoad( pointer )`.
5633pub fn atomic_load(pointer: impl Into<NodeRef>) -> NodeRef {
5634    atomic_func("atomicLoad", pointer, None)
5635}
5636
5637/// `workgroupArray( type, count )` — see [`WorkgroupArrayDef`](super::node::WorkgroupArrayDef).
5638#[derive(Clone)]
5639pub struct WorkgroupArray(Rc<super::node::WorkgroupArrayDef>);
5640
5641/// `workgroupArray( type, count )`.
5642pub fn workgroup_array(element_ty: Type, count: usize) -> WorkgroupArray {
5643    WorkgroupArray(Rc::new(super::node::WorkgroupArrayDef {
5644        element_ty,
5645        count,
5646        atomic: false,
5647    }))
5648}
5649
5650impl WorkgroupArray {
5651    /// `.element( index )` — `WorkgroupArray_N[ index ]`.
5652    pub fn element(&self, index: impl Into<NodeRef>) -> NodeRef {
5653        NodeRef::new(Node::Element {
5654            node: NodeRef::new(Node::Workgroup(self.0.clone())),
5655            index: index.into(),
5656            ty: self.0.element_ty,
5657        })
5658    }
5659
5660    /// `.toAtomic()` — `array< atomic<T>, N >`. Like
5661    /// [`StorageArray::to_atomic`], a new handle rather than a flag: a
5662    /// different array.
5663    pub fn to_atomic(&self) -> WorkgroupArray {
5664        WorkgroupArray(Rc::new(super::node::WorkgroupArrayDef {
5665            atomic: true,
5666            ..*self.0
5667        }))
5668    }
5669}
5670
5671/// `workgroupBarrier()`.
5672pub fn workgroup_barrier() -> NodeRef {
5673    NodeRef::new(Node::Barrier { scope: "workgroup" })
5674}
5675
5676/// `storageBarrier()`.
5677pub fn storage_barrier() -> NodeRef {
5678    NodeRef::new(Node::Barrier { scope: "storage" })
5679}
5680
5681/// `textureBarrier()` — `barrier( 'texture' ).toStack()`
5682/// (`src/nodes/gpgpu/BarrierNode.js:112`): `textureBarrier();`, compute only.
5683pub fn texture_barrier() -> NodeRef {
5684    NodeRef::new(Node::Barrier { scope: "texture" })
5685}
5686
5687/// `uniformArray( values )` — a constant array in a uniform block, one
5688/// `vec4<f32>` per element (`UniformArrayNode.getPaddedType()`).
5689///
5690/// Held by the caller like a [`StorageArray`], because its identity is the
5691/// buffer: all five `element()` calls of `BloomNode`'s composite have to reach
5692/// the *same* `NodeBuffer_N` binding.
5693#[derive(Clone)]
5694pub struct UniformArray(Rc<BufferNode>);
5695
5696/// `uniformArray( [ Vector3, … ] )`.
5697///
5698/// Three takes the element type from `value[ 0 ]`; the port takes the three
5699/// components explicitly, since a `Vec<Vector3>` is the only shape the ladder
5700/// asks for. Each element is padded to a `vec4` and read back as its `.xyz`,
5701/// exactly as `UniformArrayElementNode.generate()` formats it.
5702pub fn uniform_array_vec3(values: &[[f64; 3]]) -> UniformArray {
5703    let mut padded = Vec::with_capacity(values.len() * 4);
5704    for v in values {
5705        padded.extend([v[0] as f32, v[1] as f32, v[2] as f32, 0.0]);
5706    }
5707    UniformArray(Rc::new(BufferNode {
5708        id: crate::nodes::node::BufferId::next(),
5709        source: BufferSource::UniformArray(Rc::new(padded)),
5710        element_ty: Type::Vec4,
5711        count: values.len(),
5712    }))
5713}
5714
5715/// `uniformArray( [ Vector2, … ] )` — each element padded to a `vec4` and
5716/// read back as its `.xy` (`UniformArrayElementNode.generate()`):
5717/// `DepthOfFieldNode`'s two bokeh kernels.
5718pub fn uniform_array_vec2(values: &[[f64; 2]]) -> UniformArray {
5719    let mut padded = Vec::with_capacity(values.len() * 4);
5720    for v in values {
5721        padded.extend([v[0] as f32, v[1] as f32, 0.0, 0.0]);
5722    }
5723    UniformArray(Rc::new(BufferNode {
5724        id: crate::nodes::node::BufferId::next(),
5725        source: BufferSource::UniformArray(Rc::new(padded)),
5726        element_ty: Type::Vec4,
5727        count: values.len(),
5728    }))
5729}
5730
5731/// `uniformArray( [ 1.0, 1.5, … ] )` — an array of floats, each padded to a
5732/// `vec4` and read back as its `.x` (`UniformArrayElementNode.generate()`).
5733pub fn uniform_array_f32(values: &[f64]) -> UniformArray {
5734    let mut padded = Vec::with_capacity(values.len() * 4);
5735    for &v in values {
5736        padded.extend([v as f32, 0.0, 0.0, 0.0]);
5737    }
5738    UniformArray(Rc::new(BufferNode {
5739        id: crate::nodes::node::BufferId::next(),
5740        source: BufferSource::UniformArray(Rc::new(padded)),
5741        element_ty: Type::Vec4,
5742        count: values.len(),
5743    }))
5744}
5745
5746impl UniformArray {
5747    /// `.element( i )` — `NodeBuffer_N.value[ i ].xyz`.
5748    pub fn element(&self, index: usize) -> NodeRef {
5749        NodeRef::new(Node::BufferElement {
5750            buffer: self.0.clone(),
5751            index: constant(Type::U32, vec![index as f64]),
5752        })
5753        .xyz()
5754    }
5755
5756    /// `.element( i )` on a `Vector2` array — `NodeBuffer_N.value[ i ].xy`,
5757    /// the index a node (a loop's `i`).
5758    pub fn element_xy(&self, index: NodeRef) -> NodeRef {
5759        NodeRef::new(Node::BufferElement {
5760            buffer: self.0.clone(),
5761            index,
5762        })
5763        .xy()
5764    }
5765
5766    /// `.element( i )` on a `Vector3` array with a node index (a loop's `i`)
5767    /// — `NodeBuffer_N.value[ i ].xyz`.
5768    pub fn element_xyz(&self, index: NodeRef) -> NodeRef {
5769        NodeRef::new(Node::BufferElement {
5770            buffer: self.0.clone(),
5771            index,
5772        })
5773        .xyz()
5774    }
5775
5776    /// `.element( i )` on a float array — `NodeBuffer_N.value[ i ].x`, the
5777    /// index a node (a loop's `i`, or a `u32` constant).
5778    pub fn element_x(&self, index: NodeRef) -> NodeRef {
5779        NodeRef::new(Node::BufferElement {
5780            buffer: self.0.clone(),
5781            index,
5782        })
5783        .x()
5784    }
5785}
5786
5787/// `uniformArray( array )` over a `Vector3` array the application keeps
5788/// changing — `LightProbeHelper`'s `uniformArray( lightProbe.sh.coefficients
5789/// )`. `read` returns the elements already padded, four floats each, and is
5790/// called every draw; `count` is the element count the WGSL declares.
5791pub(crate) fn uniform_array_live(
5792    count: usize,
5793    read: impl Fn() -> Vec<f64> + 'static,
5794) -> UniformArray {
5795    UniformArray(Rc::new(BufferNode {
5796        id: crate::nodes::node::BufferId::next(),
5797        source: BufferSource::Live(crate::nodes::node::LiveValue::new(read)),
5798        element_ty: Type::Vec4,
5799        count,
5800    }))
5801}
5802
5803/// `LightProbeNode.lightProbe` — the nine coefficients, times the light's
5804/// intensity, of the probe at `index` of the renderer's light list.
5805pub(crate) fn light_probe_sh(index: usize) -> UniformArray {
5806    UniformArray(Rc::new(BufferNode {
5807        id: crate::nodes::node::BufferId::next(),
5808        source: BufferSource::LightProbe(index),
5809        element_ty: Type::Vec4,
5810        count: 9,
5811    }))
5812}
5813
5814/// `getShIrradianceAt( normal, shCoefficients )` — the irradiance an order-2
5815/// spherical-harmonic environment delivers to a surface facing `normal`,
5816/// which is assumed unit length.
5817///
5818/// Ramamoorthi and Hanrahan's quadratic form, "An Efficient Representation
5819/// for Irradiance Environment Maps", equation 13: the Lambert cosine lobe is
5820/// already folded into the constants (`0.886227 = π · 0.282095`,
5821/// `1.023328 = 2π/3 · 0.488603`, …), so the sum is irradiance, not radiance
5822/// — the same as [`SphericalHarmonics3::get_irradiance_at`](crate::math::SphericalHarmonics3::get_irradiance_at)
5823/// on the CPU. The products are built in three's order, `c · k · x · y`, and
5824/// the `2.0 * …` constants are folded the way JavaScript folds them, so the
5825/// WGSL is three's character for character.
5826pub fn get_sh_irradiance_at(normal: NodeRef, sh: &UniformArray) -> NodeRef {
5827    let (x, y, z) = (normal.x(), normal.y(), normal.z());
5828
5829    // band 0
5830    let mut result = sh.element(0).mul(0.886227);
5831
5832    // band 1
5833    result = result.add(sh.element(1).mul(2.0 * 0.511664).mul(y.clone()));
5834    result = result.add(sh.element(2).mul(2.0 * 0.511664).mul(z.clone()));
5835    result = result.add(sh.element(3).mul(2.0 * 0.511664).mul(x.clone()));
5836
5837    // band 2
5838    result = result.add(
5839        sh.element(4)
5840            .mul(2.0 * 0.429043)
5841            .mul(x.clone())
5842            .mul(y.clone()),
5843    );
5844    result = result.add(
5845        sh.element(5)
5846            .mul(2.0 * 0.429043)
5847            .mul(y.clone())
5848            .mul(z.clone()),
5849    );
5850    result = result.add(
5851        sh.element(6)
5852            .mul(z.mul(z.clone()).mul(0.743125).sub(0.247708)),
5853    );
5854    result = result.add(sh.element(7).mul(2.0 * 0.429043).mul(x.clone()).mul(z));
5855    result.add(
5856        sh.element(8)
5857            .mul(0.429043)
5858            .mul(x.mul(x.clone()).sub(y.mul(y.clone()))),
5859    )
5860}
5861
5862fn buffer_element(source: BufferSource, element_ty: Type, count: usize, index: NodeRef) -> NodeRef {
5863    NodeRef::new(Node::BufferElement {
5864        buffer: Rc::new(BufferNode {
5865            id: crate::nodes::node::BufferId::next(),
5866            source,
5867            element_ty,
5868            count,
5869        }),
5870        index,
5871    })
5872}
5873
5874/// `instancedBufferAttribute( buffer, type, stride, offset )`.
5875fn instanced_attribute(buffer: &Rc<InstanceBuffer>, offset: usize, ty: Type) -> NodeRef {
5876    NodeRef::new(Node::InstancedAttribute {
5877        buffer: buffer.clone(),
5878        offset,
5879        ty,
5880    })
5881}
5882
5883/// `createInstanceMatrixNode( builder, instanceMatrix )`
5884/// (`src/nodes/accessors/Instance.js:27`).
5885///
5886/// Under the uniform buffer limit the matrices are a `buffer( array, 'mat4',
5887/// count ).element( instanceIndex )`; over it they are an
5888/// `InstancedInterleavedBuffer( array, 16, 1 )` read as four
5889/// `instancedBufferAttribute( interleaved, 'vec4', 16, offset )` views joined
5890/// back into a `mat4`. The second branch is what lets an `InstancedMesh` go
5891/// past `maxUniformBufferBindingSize / 64` ≈ 1024 instances.
5892pub(crate) fn instance_matrix(count: usize) -> NodeRef {
5893    let matrix_count = count.max(1);
5894    let uniform_buffer_size = matrix_count * 16 * 4;
5895
5896    if uniform_buffer_size <= crate::nodes::builder::uniform_buffer_limit() {
5897        return buffer_element(
5898            BufferSource::InstanceMatrix,
5899            Type::Mat4,
5900            count,
5901            instance_index(),
5902        );
5903    }
5904
5905    let interleaved = Rc::new(InstanceBuffer {
5906        id: crate::nodes::node::BufferId::next(),
5907        source: BufferSource::InstanceMatrix,
5908        count: matrix_count,
5909        item_size: 16,
5910        per_vertex: false,
5911    });
5912    join(
5913        Type::Mat4,
5914        (0..4)
5915            .map(|i| instanced_attribute(&interleaved, i * 4, Type::Vec4))
5916            .collect(),
5917    )
5918}
5919
5920/// `instanceColor` — `varyingProperty( 'vec3', 'vInstanceColor' )` fed by
5921/// `instancedBufferAttribute( new InstancedBufferAttribute( colors.array, 3 ),
5922/// 'vec3', 3, 0 )` (`src/nodes/accessors/Instance.js`).
5923///
5924/// Unlike the matrices there is no uniform-buffer branch: three.js always
5925/// re-wraps the colours as an instanced vertex attribute.
5926pub fn instance_color(count: usize) -> NodeRef {
5927    let buffer = Rc::new(InstanceBuffer {
5928        id: crate::nodes::node::BufferId::next(),
5929        source: BufferSource::InstanceColor,
5930        count: count.max(1),
5931        item_size: 3,
5932        per_vertex: false,
5933    });
5934    to_varying(
5935        Some("vInstanceColor"),
5936        instanced_attribute(&buffer, 0, Type::Vec3),
5937    )
5938}
5939
5940/// One end of a `range( min, max )`, i.e. the value `RangeNode` reads the
5941/// `Vector4` and the node type out of.
5942///
5943/// `RangeNode.setup()` (`src/nodes/geometry/RangeNode.js:122`) widens both ends
5944/// to a `Vector4` by three different rules, and they do not agree on `w`:
5945///
5946/// * a scalar splats into all four components,
5947/// * a `Color` becomes `( r, g, b, 1 )`,
5948/// * any other vector becomes `( x, y, z || 0, w || 0 )`.
5949///
5950/// So `range( vec3( -1 ), vec3( 1 ) )` has `w = 0` at *both* ends — the fourth
5951/// random draw per instance is still consumed, but it lands on a constant 0.
5952#[derive(Clone, Copy, Debug, PartialEq)]
5953pub enum RangeValue {
5954    /// `range( 0, 1 )` — `min.setScalar( value )`.
5955    Scalar(f64),
5956    /// `range( new Color( … ), … )` — `min.set( r, g, b, 1 )`.
5957    Color(Color),
5958    /// `range( vec3( -1 ), vec3( 1 ) )` — `min.set( x, y, z, 0 )`.
5959    Vec3([f64; 3]),
5960}
5961
5962impl From<f64> for RangeValue {
5963    fn from(v: f64) -> Self {
5964        RangeValue::Scalar(v)
5965    }
5966}
5967
5968impl From<Color> for RangeValue {
5969    fn from(v: Color) -> Self {
5970        RangeValue::Color(v)
5971    }
5972}
5973
5974impl From<crate::math::Vector3> for RangeValue {
5975    fn from(v: crate::math::Vector3) -> Self {
5976        RangeValue::Vec3([v.x, v.y, v.z])
5977    }
5978}
5979
5980impl RangeValue {
5981    /// The `Vector4` `RangeNode.setup()` lerps between.
5982    fn vector4(self) -> [f64; 4] {
5983        match self {
5984            RangeValue::Scalar(v) => [v, v, v, v],
5985            RangeValue::Color(c) => [c.r, c.g, c.b, 1.0],
5986            RangeValue::Vec3([x, y, z]) => [x, y, z, 0.0],
5987        }
5988    }
5989
5990    /// `RangeNode.getNodeType()` — the value's own type, which is what the
5991    /// `vec4` the buffer holds is `convert()`ed down to.
5992    fn ty(self) -> Type {
5993        match self {
5994            RangeValue::Scalar(_) => Type::F32,
5995            RangeValue::Color(_) | RangeValue::Vec3(_) => Type::Vec3,
5996        }
5997    }
5998}
5999
6000/// `range( min, max )` — `RangeNode` on an `InstancedMesh` resolves to one
6001/// `vec4` per instance, `lerp( min[c], max[c], Math.random() )` per component.
6002/// The returned node is the raw `vec4`; `instanced_range` narrows it.
6003pub fn range(min: [f64; 4], max: [f64; 4], count: usize, index: NodeRef) -> NodeRef {
6004    buffer_element(BufferSource::Range { min, max }, Type::Vec4, count, index)
6005}
6006
6007/// `RangeNode.setup()` on an object with `count > 1`
6008/// (`src/nodes/geometry/RangeNode.js:122`): the same uniform-or-attribute
6009/// branch as [`instance_matrix`], on `count * 4 * 4` bytes, then
6010/// `.convert( nodeType )` — which for a `vec4` source is a swizzle, so a
6011/// `range( 0, 1 )` reads `…​.x` and a `range( vec3( -1 ), vec3( 1 ) )` reads
6012/// `….xyz`.
6013///
6014/// Each call builds its own buffer node, so two `range( 0, 1 )` calls are two
6015/// buffers with two different random fills — Three's behaviour, and the thing a
6016/// value-keyed cache would silently collapse.
6017pub(crate) fn instanced_range(
6018    min: impl Into<RangeValue>,
6019    max: impl Into<RangeValue>,
6020    count: usize,
6021) -> NodeRef {
6022    let (min, max) = (min.into(), max.into());
6023    let ty = min.ty();
6024    let uniform_buffer_size = count * 4 * 4;
6025
6026    let vec4 = if uniform_buffer_size <= crate::nodes::builder::uniform_buffer_limit() {
6027        // `buffer( array, 'vec4', count ).element( instanceIndex )`. The index
6028        // goes through a varying because the port reads the buffer in the
6029        // fragment stage; see `docs/nodes.md` §9.
6030        range(
6031            min.vector4(),
6032            max.vector4(),
6033            count,
6034            to_varying(None, instance_index()),
6035        )
6036    } else {
6037        let buffer = Rc::new(InstanceBuffer {
6038            id: crate::nodes::node::BufferId::next(),
6039            source: BufferSource::Range {
6040                min: min.vector4(),
6041                max: max.vector4(),
6042            },
6043            count,
6044            item_size: 4,
6045            per_vertex: false,
6046        });
6047        instanced_attribute(&buffer, 0, Type::Vec4)
6048    };
6049
6050    // `ConvertNode` — `NodeBuilder.format( snippet, 'vec4', nodeType )`.
6051    match ty {
6052        Type::F32 => vec4.x(),
6053        Type::Vec2 => vec4.xy(),
6054        Type::Vec3 => vec4.xyz(),
6055        _ => vec4,
6056    }
6057}
6058
6059/// `Loop( count, ( { i } ) => { … } )` — the statement and the index node the
6060/// body reads, which is a plain `i` already in scope.
6061pub fn loop_index() -> NodeRef {
6062    NodeRef::new(Node::Param {
6063        name: "i",
6064        ty: Type::I32,
6065    })
6066}
6067
6068/// `Loop( count, ( { i } ) => { … } )` — a `for` loop from 0 to `count`,
6069/// exclusive, with `index` (see [`loop_index`]) bound to the counter.
6070pub fn loop_statement(count: usize, index: NodeRef, body: Vec<NodeRef>) -> NodeRef {
6071    let count = int(count as i64);
6072    NodeRef::new(Node::Loop {
6073        start: None,
6074        index,
6075        count,
6076        condition: "<",
6077        update: None,
6078        body,
6079    })
6080}
6081
6082/// `If( cond, () => { … } )` with no `Else` — a statement.
6083pub(crate) fn if_statement(cond: NodeRef, body: Vec<NodeRef>) -> NodeRef {
6084    NodeRef::new(Node::If {
6085        cond,
6086        body,
6087        else_body: Vec::new(),
6088    })
6089}
6090
6091/// `ivec2( x, y )`.
6092pub fn ivec2(x: impl Into<NodeRef>, y: impl Into<NodeRef>) -> NodeRef {
6093    join(Type::IVec2, vec![x.into(), y.into()])
6094}
6095
6096/// `textureSize( textureLoad( map ), level )` — `textureDimensions`, a
6097/// `vec2<u32>`.
6098pub fn texture_size(source: TextureSource, level: NodeRef) -> NodeRef {
6099    NodeRef::new(Node::TextureSize {
6100        texture: Rc::new(source),
6101        level,
6102    })
6103}
6104
6105/// `textureLoad( dataTexture, ivec2( x, y ) )` — the unclamped, sampler-less
6106/// texel fetch `Batch.js` reads its three data textures with. `ty` is the
6107/// node's type: `vec4` for the `rgba32float` matrices and colours, and the
6108/// scalar `uint` for the `r32uint` indirect table, whose `.x` Three folds into
6109/// the same cached property.
6110pub fn texture_load_texel(map: &DataTexture, coord: NodeRef, ty: Type) -> NodeRef {
6111    texture_node(
6112        TextureSource::Data(map.clone()),
6113        coord,
6114        SampleMode::LoadTexel,
6115        ty,
6116    )
6117}
6118
6119/// `textureNode.load( coord )` on a colour texture — `textureLoad( t,
6120/// vec2<i32>( coord ), u32( 0u ) )`, the unfiltered, unclamped texel fetch.
6121/// `TRAANode` reads the velocity attachment this way.
6122pub fn texture_load(map: &Texture, coord: NodeRef) -> NodeRef {
6123    texture_node(
6124        TextureSource::Texture2D(map.clone()),
6125        coord.to(Type::IVec2),
6126        SampleMode::LoadTexel,
6127        texture_type_for(map),
6128    )
6129}
6130
6131/// `textureNode.load( coord ).offset( offset )` — [`texture_load`] at
6132/// `ivec2( coord ) + offset`, as three spells it:
6133/// `textureLoad( t, vec2<i32>( coord ) + vec2<i32>( -1, 1 ), u32( 0u ) )`.
6134pub fn texture_load_offset(map: &Texture, coord: NodeRef, offset: NodeRef) -> NodeRef {
6135    texture_node(
6136        TextureSource::Texture2D(map.clone()),
6137        coord.to(Type::IVec2).add(offset),
6138        SampleMode::LoadTexel,
6139        texture_type_for(map),
6140    )
6141}
6142
6143/// `depthTextureNode.load( coord ).r` — the depth at an integer texel,
6144/// `textureLoad( depth, vec2<i32>( coord ), u32( 0u ) )`, an `f32`.
6145pub fn depth_texture_load(map: &DepthTexture, coord: NodeRef) -> NodeRef {
6146    texture_node(
6147        TextureSource::Depth(map.clone()),
6148        coord.to(Type::IVec2),
6149        SampleMode::LoadTexel,
6150        Type::F32,
6151    )
6152}
6153
6154/// `textureLoad( texture( map ), coord )` — a texel fetch through a
6155/// `texture( map )` node that was made without a uv. Three's `texture()` then
6156/// sets `updateMatrix`, and `textureLoad()` clones the node with it, so the
6157/// integer coordinate still goes through `getTransformedUV()`:
6158/// `textureLoad( t, vec2<i32>( ( map.matrix * vec3<f32>( vec2<f32>( coord ),
6159/// 1.0 ) ).xy ), u32( 0u ) )`, one `mat3x3` uniform shared per map as
6160/// [`texture`]'s is. `TemporalReprojectNode` reads its history and previous
6161/// normal this way.
6162pub fn texture_load_transformed(map: &Texture, coord: NodeRef) -> NodeRef {
6163    texture_node(
6164        TextureSource::Texture2D(map.clone()),
6165        transformed_uv(coord.to(Type::Vec2), (0, map.id()), map.matrix()).to(Type::IVec2),
6166        SampleMode::LoadTexel,
6167        texture_type_for(map),
6168    )
6169}
6170
6171/// [`texture_load_transformed`] on a depth texture — `textureLoad( texture(
6172/// depthTexture ), coord ).r`, an `f32` read through the (identity) uv
6173/// matrix `texture()` gives the node. `TemporalReprojectNode`'s previous
6174/// depth.
6175pub fn depth_texture_load_transformed(map: &DepthTexture, coord: NodeRef) -> NodeRef {
6176    texture_node(
6177        TextureSource::Depth(map.clone()),
6178        transformed_uv(coord.to(Type::Vec2), (1, map.id()), Matrix3::identity()).to(Type::IVec2),
6179        SampleMode::LoadTexel,
6180        Type::F32,
6181    )
6182}
6183
6184/// `varyingProperty( type, name )` — a named varying written by assignment.
6185pub fn varying_property(name: &'static str, ty: Type, flat: bool) -> NodeRef {
6186    NodeRef::new(Node::VaryingProperty { name, ty, flat })
6187}
6188
6189/// `textureLoad( dataArrayTexture, ivec2( x, y ) ).depth( layer )` — the
6190/// sampler-less array read `Morph.js`' `getMorph()` performs.
6191pub fn texture_load_array(map: &DataArrayTexture, coord: NodeRef, layer: NodeRef) -> NodeRef {
6192    texture_node(
6193        TextureSource::DataArray(map.clone()),
6194        coord,
6195        SampleMode::LoadLayer(layer),
6196        Type::Vec4,
6197    )
6198}
6199
6200/// `uniformArray( mesh.morphTargetInfluences, 'float' ).element( i )` — one
6201/// `vec4` per morph target, the influence in `.x`.
6202pub(crate) fn morph_influences(count: usize, index: NodeRef) -> NodeRef {
6203    buffer_element(BufferSource::MorphInfluences, Type::Vec4, count, index)
6204}
6205
6206/// `Morph.js`' `base = uniform( 1 )`, in the object group.
6207pub(crate) fn morph_base() -> NodeRef {
6208    uniform(
6209        UniformSource::MorphBase,
6210        Type::F32,
6211        UniformGroup::Object,
6212        None,
6213    )
6214}
6215
6216/// `geometry.setAttribute( name, new InstancedBufferAttribute( array, items ) )`
6217/// read back as `attribute( name, type )`.
6218///
6219/// three.js resolves the name through the geometry; here the data travels with
6220/// the node, because the node graph is built from the material and the renderer
6221/// has no attribute-name table. `item_size` is the stride in floats (the items
6222/// of one instance) and `offset` the component offset inside it, so several
6223/// views of one interleaved buffer share a single `stepMode: 'instance'` vertex
6224/// buffer — the same grouping `instance_matrix` uses above.
6225pub fn instanced_data_attribute(
6226    data: &Rc<Vec<f32>>,
6227    item_size: usize,
6228    offset: usize,
6229    ty: Type,
6230) -> NodeRef {
6231    instanced_buffer_attribute(&instanced_data_buffer(data, item_size), offset, ty)
6232}
6233
6234/// `new InstancedInterleavedBuffer( array, stride, 1 )` — the buffer itself,
6235/// so that several `InterleavedBufferAttribute` views of it can be taken with
6236/// [`instanced_buffer_attribute`] and land in **one** `stepMode: 'instance'`
6237/// vertex buffer.
6238///
6239/// [`NodeProgram::vertex_buffers`](crate::nodes::NodeProgram::vertex_buffers)
6240/// groups on the buffer's `Rc` identity, so two `instanced_data_attribute`
6241/// calls over the same array are two buffers; a fat line's `instanceStart` and
6242/// `instanceEnd` have to be two views of one.
6243pub fn instanced_data_buffer(data: &Rc<Vec<f32>>, item_size: usize) -> Rc<InstanceBuffer> {
6244    let count = data.len().checked_div(item_size).unwrap_or(0);
6245    Rc::new(InstanceBuffer {
6246        id: crate::nodes::node::BufferId::next(),
6247        source: BufferSource::Attribute(data.clone()),
6248        count,
6249        item_size,
6250        per_vertex: false,
6251    })
6252}
6253
6254/// `instancedBufferAttribute( buffer, type, stride, offset )` — one view of a
6255/// buffer from [`instanced_data_buffer`]. `offset` is in components, not bytes.
6256pub fn instanced_buffer_attribute(buffer: &Rc<InstanceBuffer>, offset: usize, ty: Type) -> NodeRef {
6257    assert!(
6258        offset + ty.components() <= buffer.item_size,
6259        "three-rs: instanced attribute reads past the instance stride"
6260    );
6261    instanced_attribute(buffer, offset, ty)
6262}
6263
6264// ---------------------------------------------------------------------------
6265// Fn()
6266// ---------------------------------------------------------------------------
6267
6268/// `Fn( body )` with no layout: the body is inlined at every call site.
6269pub fn inline_fn(
6270    params: usize,
6271    ret: Type,
6272    body: impl Fn(&[NodeRef]) -> NodeRef + 'static,
6273) -> Rc<FnDef> {
6274    Rc::new(FnDef {
6275        name: None,
6276        params: vec![("", Type::Void); params],
6277        ret,
6278        layout: false,
6279        body: Box::new(body),
6280    })
6281}
6282
6283/// `wgslFn( source )` / `wgslFn( source, includes )` — see
6284/// [`crate::nodes::code`]. Re-exported here because every other TSL entry
6285/// point lives in this module.
6286pub use crate::nodes::code::wgsl_fn;
6287
6288/// A `wgslFn` as a *node*, which is the form another one's `includes` list
6289/// wants it in: three's `includes` is an array of nodes, and a nested
6290/// `wgslFn` is a `CodeNode` like any other.
6291pub fn code(def: &Rc<crate::nodes::code::CodeDef>) -> NodeRef {
6292    NodeRef::new(Node::Code(def.clone()))
6293}
6294
6295/// Calling a `wgslFn` — `FunctionCallNode` with three's named-parameter form:
6296/// `getWGSLTextureSample( { tex, tex_sampler, uv } )`. The names are the ones
6297/// the WGSL declaration used, and the order they are given in does not matter.
6298///
6299/// # Panics
6300///
6301/// If a declared parameter has no argument, or an argument names a parameter
6302/// the declaration does not have. Three leaves the first as `undefined` and
6303/// generates a shader that will not compile; the port refuses at setup.
6304pub fn call_wgsl(def: &Rc<crate::nodes::code::CodeDef>, args: Vec<(&str, NodeRef)>) -> NodeRef {
6305    let ordered = def
6306        .params
6307        .iter()
6308        .map(|(name, _)| {
6309            args.iter()
6310                .find(|(given, _)| given == name)
6311                .map(|(_, node)| node.clone())
6312                .unwrap_or_else(|| {
6313                    panic!(
6314                        "three-rs: wgslFn `{}` has no argument for `{name}`",
6315                        def.name
6316                    )
6317                })
6318        })
6319        .collect();
6320    for (given, _) in &args {
6321        assert!(
6322            def.params.iter().any(|(name, _)| name == given),
6323            "three-rs: wgslFn `{}` has no parameter `{given}`",
6324            def.name
6325        );
6326    }
6327    NodeRef::new(Node::CodeCall {
6328        def: def.clone(),
6329        args: ordered,
6330    })
6331}
6332
6333/// `Fn( body, layout )`: a real WGSL `fn` is emitted and called.
6334pub fn shader_fn(
6335    name: Option<&'static str>,
6336    params: Vec<(&'static str, Type)>,
6337    ret: Type,
6338    body: impl Fn(&[NodeRef]) -> NodeRef + 'static,
6339) -> Rc<FnDef> {
6340    Rc::new(FnDef {
6341        name,
6342        params,
6343        ret,
6344        layout: true,
6345        body: Box::new(body),
6346    })
6347}
6348
6349/// `If( cond, () => { … } )` over a result var that was initialised first.
6350///
6351/// `pre` are the statements three.js emits ahead of the result var, `body` the
6352/// statements inside the block (the last of which assigns the result). The
6353/// node's value is the result var, so a second reference reuses it rather than
6354/// re-emitting the block.
6355pub(crate) fn if_node(
6356    pre: Vec<NodeRef>,
6357    result: NodeRef,
6358    cond: NodeRef,
6359    body: Vec<NodeRef>,
6360) -> NodeRef {
6361    NodeRef::new(Node::IfVar {
6362        pre,
6363        result,
6364        cond,
6365        body,
6366    })
6367}
6368
6369/// `Fn( … )( args )` — a call to a [`FnDef`] built by [`inline_fn`] or
6370/// [`shader_fn`], inlined into the current flow or emitted as a real `fn`,
6371/// depending on the def's layout.
6372pub fn call(def: &Rc<FnDef>, args: Vec<NodeRef>) -> NodeRef {
6373    NodeRef::new(Node::Call {
6374        def: def.clone(),
6375        args,
6376    })
6377}
6378
6379// ---------------------------------------------------------------------------
6380// display / math node functions the ladder uses
6381// ---------------------------------------------------------------------------
6382
6383/// `luminance( color )`, with the working (linear-sRGB) coefficients.
6384pub fn luminance(color: NodeRef) -> NodeRef {
6385    dot(color, vec3(0.2126, 0.7152, 0.0722))
6386}
6387
6388/// `saturation( color, adjustment )` — ported verbatim from
6389/// `ColorAdjustment.js`: `adjustment.mix( luminance( color.rgb ), color.rgb ).max( 0.0 )`.
6390///
6391/// Both reads of `color.rgb` are one node: three's swizzle getter caches the
6392/// `SplitNode` on its node (`this._cache[ property ]`), and a `SplitNode` is
6393/// no `TempNode`, so the shared swizzle is counted twice but `color` only
6394/// once and stays inline, even when `color` is already a `vec3` — `webgpu_postprocessing_ssr_denoise`'s grading
6395/// spells its contrast expression out at both reads.
6396pub fn saturation(color: NodeRef, adjustment: NodeRef) -> NodeRef {
6397    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6398    let def = CELL.with(|c| {
6399        c.get(|| {
6400            inline_fn(2, Type::Vec3, |args| {
6401                let (color, adjustment) = (args[0].clone(), args[1].clone());
6402                let rgb = cached_rgb(color);
6403                adjustment.mix(luminance(rgb.clone()), rgb).max(float(0.0))
6404            })
6405        })
6406    });
6407    call(&def, vec![color, adjustment])
6408}
6409
6410/// `hue( color, adjustment )` — ported verbatim from `ColorAdjustment.js`.
6411pub fn hue(color: NodeRef, adjustment: NodeRef) -> NodeRef {
6412    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6413    let def = CELL.with(|c| {
6414        c.get(|| {
6415            inline_fn(2, Type::Vec3, |args| {
6416                let (color, adjustment) = (args[0].clone(), args[1].clone());
6417                let k = vec3(0.57735, 0.57735, 0.57735);
6418                let cos_angle = adjustment.cos();
6419                color
6420                    .rgb()
6421                    .mul(cos_angle.clone())
6422                    .add(
6423                        k.cross(color.rgb())
6424                            .mul(adjustment.sin())
6425                            .add(k.mul(dot(k.clone(), color.rgb()).mul(cos_angle.one_minus()))),
6426                    )
6427                    .max(float(0.0))
6428            })
6429        })
6430    });
6431    call(&def, vec![color, adjustment])
6432}
6433
6434/// `grayscale( color )` — `ColorAdjustment.js`: `luminance( color.rgb )`.
6435/// A `Fn()` with no layout, so inlined.
6436pub fn grayscale(color: NodeRef) -> NodeRef {
6437    luminance(color.rgb())
6438}
6439
6440/// `posterize( source, steps )` — `ColorAdjustment.js`:
6441/// `source.mul( steps ).floor().div( steps )`. A `Fn()` with no layout, so
6442/// inlined, and of `source`'s type.
6443pub fn posterize(source: NodeRef, steps: impl Into<NodeRef>) -> NodeRef {
6444    let steps = steps.into();
6445    source.mul(steps.clone()).floor().div(steps)
6446}
6447
6448/// `blendOverlay( base, blend )` — `BlendModes.js`, a `vec3` `Fn()` with a
6449/// layout: `mix( base * 2 * blend, 1 - ( 1 - base ) * 2 * ( 1 - blend ),
6450/// step( 0.5, base ) )`.
6451pub fn blend_overlay(base: NodeRef, blend: NodeRef) -> NodeRef {
6452    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6453    let def = CELL.with(|c| {
6454        c.get(|| {
6455            shader_fn(
6456                Some("blendOverlay"),
6457                vec![("base", Type::Vec3), ("blend", Type::Vec3)],
6458                Type::Vec3,
6459                |args| {
6460                    let (base, blend) = (args[0].clone(), args[1].clone());
6461                    mix(
6462                        base.mul(float(2.0)).mul(blend.clone()),
6463                        base.one_minus()
6464                            .mul(float(2.0))
6465                            .mul(blend.one_minus())
6466                            .one_minus(),
6467                        step(float(0.5), base),
6468                    )
6469                },
6470            )
6471        })
6472    });
6473    call(&def, vec![base, blend])
6474}
6475
6476/// `blendBurn( base, blend )` — `BlendModes.js`, a `vec3` `Fn()` with a
6477/// layout: `1 - min( 1, ( 1 - base ) / blend )`, darkening `base` by
6478/// `blend`.
6479pub fn blend_burn(base: NodeRef, blend: NodeRef) -> NodeRef {
6480    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6481    let def = CELL.with(|c| {
6482        c.get(|| {
6483            shader_fn(
6484                Some("blendBurn"),
6485                vec![("base", Type::Vec3), ("blend", Type::Vec3)],
6486                Type::Vec3,
6487                |args| {
6488                    let (base, blend) = (args[0].clone(), args[1].clone());
6489                    math(
6490                        "min",
6491                        vec![float(1.0), base.one_minus().div(blend)],
6492                        Type::Vec3,
6493                    )
6494                    .one_minus()
6495                },
6496            )
6497        })
6498    });
6499    call(&def, vec![base, blend])
6500}
6501
6502/// `blendDodge( base, blend )` — `BlendModes.js`, a `vec3` `Fn()` with a
6503/// layout: `min( base / ( 1 - blend ), 1 )`, lightening `base` by `blend`.
6504pub fn blend_dodge(base: NodeRef, blend: NodeRef) -> NodeRef {
6505    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6506    let def = CELL.with(|c| {
6507        c.get(|| {
6508            shader_fn(
6509                Some("blendDodge"),
6510                vec![("base", Type::Vec3), ("blend", Type::Vec3)],
6511                Type::Vec3,
6512                |args| {
6513                    let (base, blend) = (args[0].clone(), args[1].clone());
6514                    base.div(blend.one_minus()).min(float(1.0))
6515                },
6516            )
6517        })
6518    });
6519    call(&def, vec![base, blend])
6520}
6521
6522/// `blendScreen( base, blend )` — `BlendModes.js`, a `vec3` `Fn()` with a
6523/// layout: `1 - ( 1 - base ) * ( 1 - blend )`.
6524pub fn blend_screen(base: NodeRef, blend: NodeRef) -> NodeRef {
6525    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6526    let def = CELL.with(|c| {
6527        c.get(|| {
6528            shader_fn(
6529                Some("blendScreen"),
6530                vec![("base", Type::Vec3), ("blend", Type::Vec3)],
6531                Type::Vec3,
6532                |args| {
6533                    let (base, blend) = (args[0].clone(), args[1].clone());
6534                    base.one_minus().mul(blend.one_minus()).one_minus()
6535                },
6536            )
6537        })
6538    });
6539    call(&def, vec![base, blend])
6540}
6541
6542/// `blendColor( base, blend )` — `BlendModes.js`, a `vec4` `Fn()` with a
6543/// layout: `blend` over `base` as `THREE.NormalBlending` does, both with
6544/// non-premultiplied alpha.
6545pub fn blend_color(base: NodeRef, blend: NodeRef) -> NodeRef {
6546    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6547    let def = CELL.with(|c| {
6548        c.get(|| {
6549            shader_fn(
6550                Some("blendColor"),
6551                vec![("base", Type::Vec4), ("blend", Type::Vec4)],
6552                Type::Vec4,
6553                |args| {
6554                    let (base, blend) = (args[0].clone(), args[1].clone());
6555                    let out_alpha = blend.a().add(base.a().mul(blend.a().one_minus()));
6556                    vec4_join(vec![
6557                        blend
6558                            .rgb()
6559                            .mul(blend.a())
6560                            .add(base.rgb().mul(base.a()).mul(blend.a().one_minus()))
6561                            .div(out_alpha.clone()),
6562                        out_alpha,
6563                    ])
6564                },
6565            )
6566        })
6567    });
6568    call(&def, vec![base, blend])
6569}
6570
6571/// `vibrance( color, adjustment )` — `ColorAdjustment.js`, a `Fn()` with no
6572/// layout, so inlined: saturation that leaves already-saturated colours
6573/// alone. Three's `adjustment` defaults to `float( 0 )`; pass it.
6574pub fn vibrance(color: NodeRef, adjustment: impl Into<NodeRef>) -> NodeRef {
6575    let average = color.x().add(color.y()).add(color.z()).div(float(3.0));
6576    let mx = color.x().max(color.y().max(color.z()));
6577    let amt = mx
6578        .clone()
6579        .sub(average)
6580        .mul(adjustment.into())
6581        .mul(float(-3.0));
6582    mix(color.rgb(), mx, amt).max(float(0.0))
6583}
6584
6585/// `cdl( color, slope, offset, power, saturation, luminanceCoefficients )` —
6586/// `ColorAdjustment.js`, the ASC Color Decision List v1.2 grade, a `Fn()`
6587/// with no layout, so inlined. Three's defaults are `slope = vec3( 1 )`,
6588/// `offset = vec3( 0 )`, `power = vec3( 1 )`, `saturation = float( 1 )` and
6589/// the Rec. 709 coefficients `vec3( 0.2126, 0.7152, 0.0722 )`; pass them.
6590pub fn cdl(
6591    color: NodeRef,
6592    slope: NodeRef,
6593    offset: NodeRef,
6594    power: NodeRef,
6595    saturation: impl Into<NodeRef>,
6596    luminance_coefficients: NodeRef,
6597) -> NodeRef {
6598    let luma = color.rgb().dot(luminance_coefficients);
6599    let v = to_var_intent(color.rgb().mul(slope).add(offset).max(float(0.0)));
6600    // Three's `pv = v.pow( power )` is one node read in three `If` scopes, and
6601    // its builder re-emits it in each; a fresh `pow` per channel does the
6602    // same here, where one shared node would be promoted to a var per scope.
6603    let channel = |c: &'static str| {
6604        if_then(
6605            v.swizzle(c).greater_than(0.0),
6606            vec![v.swizzle(c).assign(v.clone().pow(power.clone()).swizzle(c))],
6607        )
6608    };
6609    let statements = vec![
6610        channel("x"),
6611        channel("y"),
6612        channel("z"),
6613        v.assign(
6614            luma.clone()
6615                .add(v.clone().sub(luma).mul(saturation.into()))
6616                .max(float(0.0)),
6617        ),
6618    ];
6619    block(statements, vec4_join(vec![v.rgb(), color.a()]))
6620}
6621
6622/// `oscSine( t )` — `Oscillators.js`: `t.add( 0.75 ).mul( PI2 ).sin().mul( 0.5 ).add( 0.5 )`.
6623pub fn osc_sine(t: NodeRef) -> NodeRef {
6624    t.add(float(0.75))
6625        .mul(float(std::f64::consts::TAU))
6626        .sin()
6627        .mul(float(0.5))
6628        .add(float(0.5))
6629}
6630
6631/// `sRGBTransferOETF` — `ColorSpaceFunctions.js`, emitted as a real `fn`.
6632pub fn srgb_transfer_oetf(color: NodeRef) -> NodeRef {
6633    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6634    let def = CELL.with(|c| {
6635        c.get(|| {
6636            shader_fn(
6637                Some("sRGBTransferOETF"),
6638                vec![("color", Type::Vec3)],
6639                Type::Vec3,
6640                |args| {
6641                    let color = args[0].clone();
6642                    mix(
6643                        color
6644                            .pow(float(0.41666))
6645                            .mul(float(1.055))
6646                            .sub(float(0.055)),
6647                        color.mul(float(12.92)),
6648                        color.less_than_equal(float(0.0031308)).to(Type::Vec3),
6649                    )
6650                },
6651            )
6652        })
6653    });
6654    call(&def, vec![color])
6655}
6656
6657/// `linearToneMapping` — `ToneMappingFunctions.js`. The cheapest of the three:
6658/// exposure and a clamp, and nothing else.
6659pub fn linear_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
6660    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6661    let def = CELL.with(|c| {
6662        c.get(|| {
6663            shader_fn(
6664                Some("linearToneMapping"),
6665                vec![("color", Type::Vec3), ("exposure", Type::F32)],
6666                Type::Vec3,
6667                |args| {
6668                    args[0]
6669                        .clone()
6670                        .mul(args[1].clone())
6671                        .clamp(float(0.0), float(1.0))
6672                },
6673            )
6674        })
6675    });
6676    call(&def, vec![color, exposure])
6677}
6678
6679/// `cineonToneMapping` — `ToneMappingFunctions.js`, emitted as a real `fn`:
6680/// Hejl and Burgess-Dawson's filmic operator, gamma 2.2 baked in.
6681pub fn cineon_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
6682    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6683    let def = CELL.with(|c| {
6684        c.get(|| {
6685            shader_fn(
6686                Some("cineonToneMapping"),
6687                vec![("color", Type::Vec3), ("exposure", Type::F32)],
6688                Type::Vec3,
6689                |args| {
6690                    let color = args[0]
6691                        .clone()
6692                        .mul(args[1].clone())
6693                        .sub(float(0.004))
6694                        .max(float(0.0));
6695                    let a = color
6696                        .clone()
6697                        .mul(color.clone().mul(float(6.2)).add(float(0.5)));
6698                    let b = color
6699                        .clone()
6700                        .mul(color.mul(float(6.2)).add(float(1.7)))
6701                        .add(float(0.06));
6702                    a.div(b).pow(float(2.2))
6703                },
6704            )
6705        })
6706    });
6707    call(&def, vec![color, exposure])
6708}
6709
6710/// `sRGBTransferEOTF` — `ColorSpaceFunctions.js`, emitted as a real `fn`. The
6711/// inverse of [`srgb_transfer_oetf`]: sRGB in, working (linear-sRGB) out.
6712pub fn srgb_transfer_eotf(color: NodeRef) -> NodeRef {
6713    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6714    let def = CELL.with(|c| {
6715        c.get(|| {
6716            shader_fn(
6717                Some("sRGBTransferEOTF"),
6718                vec![("color", Type::Vec3)],
6719                Type::Vec3,
6720                |args| {
6721                    let color = args[0].clone();
6722                    mix(
6723                        color
6724                            .mul(float(0.9478672986))
6725                            .add(float(0.0521327014))
6726                            .pow(float(2.4)),
6727                        color.mul(float(0.0773993808)),
6728                        color.less_than_equal(float(0.04045)).to(Type::Vec3),
6729                    )
6730                },
6731            )
6732        })
6733    });
6734    call(&def, vec![color])
6735}
6736
6737/// `colorSpaceToWorking( node, SRGBColorSpace )` — `ColorSpaceNode.setup()`'s
6738/// `SRGBTransfer` branch: `vec4( sRGBTransferEOTF( node.rgb ), node.a )`.
6739pub fn srgb_to_working(color: NodeRef) -> NodeRef {
6740    vec4_join(vec![srgb_transfer_eotf(color.rgb()), color.a()])
6741}
6742
6743/// `packNormalToRGB( node )` — `Packing.js`: `node * 0.5 + 0.5`, the
6744/// convention that puts a unit direction in a colour.
6745pub fn pack_normal_to_rgb(node: NodeRef) -> NodeRef {
6746    node.mul(float(0.5)).add(float(0.5))
6747}
6748
6749/// `reinhardToneMapping` — `ToneMappingFunctions.js`, emitted as a real `fn`.
6750pub fn reinhard_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
6751    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6752    let def = CELL.with(|c| {
6753        c.get(|| {
6754            shader_fn(
6755                Some("reinhardToneMapping"),
6756                vec![("color", Type::Vec3), ("exposure", Type::F32)],
6757                Type::Vec3,
6758                |args| {
6759                    // `color = color.mul( exposure )`, a var because it is
6760                    // read twice.
6761                    let color = args[0].clone().mul(args[1].clone());
6762                    color
6763                        .clone()
6764                        .div(color.add(float(1.0)))
6765                        .clamp(float(0.0), float(1.0))
6766                },
6767            )
6768        })
6769    });
6770    call(&def, vec![color, exposure])
6771}
6772
6773/// `premultiplyAlpha` — `PremultiplyAlphaFunctions.js`.
6774pub fn premultiply_alpha(color: NodeRef) -> NodeRef {
6775    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6776    let def = CELL.with(|c| {
6777        c.get(|| {
6778            shader_fn(None, vec![("color", Type::Vec4)], Type::Vec4, |args| {
6779                let color = args[0].clone();
6780                vec4_join(vec![color.rgb().mul(color.a()), color.a()])
6781            })
6782        })
6783    });
6784    call(&def, vec![color])
6785}
6786
6787/// `unpremultiplyAlpha` — `PremultiplyAlphaFunctions.js`.
6788pub fn unpremultiply_alpha(color: NodeRef) -> NodeRef {
6789    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
6790    let def = CELL.with(|c| {
6791        c.get(|| {
6792            shader_fn(None, vec![("color", Type::Vec4)], Type::Vec4, |args| {
6793                let color = args[0].clone();
6794                color.a().equal(float(0.0)).select(
6795                    vec4(0.0, 0.0, 0.0, 0.0),
6796                    vec4_join(vec![color.rgb().div(color.a().to(Type::Vec3)), color.a()]),
6797                )
6798            })
6799        })
6800    });
6801    call(&def, vec![color])
6802}
6803
6804// ---------------------------------------------------------------------------
6805// statements (`Fn()` bodies, `Loop()`, `If()`, `Discard()`)
6806// ---------------------------------------------------------------------------
6807
6808/// A sequence of statements followed by the value they produce — what an
6809/// inlined `Fn()` whose body uses `toVar()` / `assign()` amounts to.
6810pub fn block(statements: Vec<NodeRef>, result: NodeRef) -> NodeRef {
6811    NodeRef::new(Node::Block { statements, result })
6812}
6813
6814/// `Loop( count, ( { i } ) => { … } )`. `body` is called with the loop index.
6815pub fn loop_n(
6816    name: &'static str,
6817    count: NodeRef,
6818    body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
6819) -> NodeRef {
6820    let index = NodeRef::new(Node::Param {
6821        name,
6822        ty: Type::I32,
6823    });
6824    let body = body(&index);
6825    NodeRef::new(Node::Loop {
6826        start: None,
6827        count,
6828        index,
6829        condition: "<",
6830        update: None,
6831        body,
6832    })
6833}
6834
6835/// `Loop( { start, end }, ( { i } ) => { … } )` — the two-bounded form.
6836///
6837/// Three.js writes the start into the loop header exactly as the node builds,
6838/// so a `start` of `halfSamples.negate()` becomes
6839/// `for ( var i : i32 = i32( ( - nodeVar1 ) ); i < i32( nodeVar1 ); i ++ )`
6840/// and not a rebased `0`. Both bounds are the caller's to cast: the loop index
6841/// is `i32` whatever the bounds' own type is.
6842pub fn loop_range(
6843    name: &'static str,
6844    start: NodeRef,
6845    end: NodeRef,
6846    body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
6847) -> NodeRef {
6848    let index = NodeRef::new(Node::Param {
6849        name,
6850        ty: Type::I32,
6851    });
6852    let body = body(&index);
6853    NodeRef::new(Node::Loop {
6854        start: Some(start),
6855        count: end,
6856        condition: "<",
6857        update: None,
6858        index,
6859        body,
6860    })
6861}
6862
6863/// `Loop( { start, end, type, condition, name }, ( { i } ) => { … } )` — the
6864/// full options object.
6865///
6866/// `ty` is the index type: `Type::I32` (three's default `'int'`) or
6867/// `Type::F32` (`type: 'float'`, `hashBlur`'s), which three writes as
6868/// `for ( var i : f32 = 0.0; i < 45.0; i += 1. )`. `condition` is the
6869/// comparison, `"<"` by default and `"<="` in `boxBlur`.
6870pub fn loop_options(
6871    name: &'static str,
6872    ty: Type,
6873    start: NodeRef,
6874    end: NodeRef,
6875    condition: &'static str,
6876    body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
6877) -> NodeRef {
6878    let index = NodeRef::new(Node::Param { name, ty });
6879    let body = body(&index);
6880    NodeRef::new(Node::Loop {
6881        start: Some(start),
6882        count: end,
6883        index,
6884        condition,
6885        update: None,
6886        body,
6887    })
6888}
6889
6890/// `Loop( { type: 'float', start, end, update }, () => { … } )` — a float
6891/// index stepped by `update`: `for ( var i : f32 = start; i < end; i +=
6892/// update )`. `RaymarchingBox` is the one user.
6893pub fn loop_float(
6894    name: &'static str,
6895    start: NodeRef,
6896    end: NodeRef,
6897    update: NodeRef,
6898    body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
6899) -> NodeRef {
6900    let index = NodeRef::new(Node::Param {
6901        name,
6902        ty: Type::F32,
6903    });
6904    let body = body(&index);
6905    NodeRef::new(Node::Loop {
6906        start: Some(start),
6907        count: end,
6908        index,
6909        condition: "<",
6910        update: Some(update),
6911        body,
6912    })
6913}
6914
6915/// `Break()` — out of the innermost `Loop`.
6916pub fn break_loop() -> NodeRef {
6917    NodeRef::new(Node::Break)
6918}
6919
6920/// `Continue()` — on to the next iteration of the innermost `Loop`.
6921pub fn continue_loop() -> NodeRef {
6922    NodeRef::new(Node::Continue)
6923}
6924
6925/// `If( cond, () => { … } )`.
6926pub fn if_then(cond: NodeRef, body: Vec<NodeRef>) -> NodeRef {
6927    NodeRef::new(Node::If {
6928        cond,
6929        body,
6930        else_body: Vec::new(),
6931    })
6932}
6933
6934/// `If( cond, () => { … } ).Else( () => { … } )`.
6935pub fn if_else(cond: NodeRef, body: Vec<NodeRef>, else_body: Vec<NodeRef>) -> NodeRef {
6936    NodeRef::new(Node::If {
6937        cond,
6938        body,
6939        else_body,
6940    })
6941}
6942
6943/// `If( cond, … ).ElseIf( other, … )`.
6944///
6945/// `StackNode.ElseIf()` is `this.Else( () => If( other, … ) )`, so the second
6946/// condition is a whole nested `If` inside the else block and the generated
6947/// WGSL is a nested `if`/`else` rather than an `else if`. Reproducing that
6948/// shape is the point — three's own dumps have the nesting.
6949pub fn if_else_if(
6950    cond: NodeRef,
6951    body: Vec<NodeRef>,
6952    other: NodeRef,
6953    other_body: Vec<NodeRef>,
6954) -> NodeRef {
6955    if_else(cond, body, vec![if_then(other, other_body)])
6956}
6957
6958/// `return value;` inside a `Fn()` body — the statement an early-out `If(
6959/// cond, () => { return x; } )` compiles to.
6960pub fn return_statement(value: NodeRef) -> NodeRef {
6961    NodeRef::new(Node::Return { value })
6962}
6963
6964/// `Discard()`.
6965pub fn discard() -> NodeRef {
6966    NodeRef::new(Node::Discard)
6967}
6968
6969/// `Discard( condition )` — `NodeMaterial.setupDiscard()`'s
6970/// `If( cond.not(), () => Discard() )`.
6971pub fn discard_if(cond: NodeRef) -> NodeRef {
6972    if_then(cond.not(), vec![discard()])
6973}
6974
6975/// WGSL's `select( falseValue, trueValue, condition )` builtin, which is what
6976/// MaterialX's `mx_select` / `mx_negate_if` emit.
6977pub fn wgsl_select(f: NodeRef, t: NodeRef, cond: NodeRef) -> NodeRef {
6978    let ty = t.ty();
6979    math("select", vec![f, t, cond], ty)
6980}
6981
6982/// `step( edge, x )`.
6983pub fn step(edge: impl Into<NodeRef>, x: impl Into<NodeRef>) -> NodeRef {
6984    let (edge, x) = (edge.into(), x.into());
6985    // `MathNode.getNodeType()`: the wider of the two operands.
6986    let ty = if edge.ty().components() > x.ty().components() {
6987        edge.ty()
6988    } else {
6989        x.ty()
6990    };
6991    math("step", vec![edge, x], ty)
6992}
6993
6994/// `uint( x )`.
6995pub fn uint(v: u32) -> NodeRef {
6996    constant(Type::U32, vec![v as f64])
6997}
6998
6999// ---------------------------------------------------------------------------
7000// shadows (`ShadowBaseNode`, `ShadowNode`, `ShadowFilterNode`)
7001// ---------------------------------------------------------------------------
7002
7003prop!(
7004    /// `shadowPositionWorld` — `property( 'vec3', 'shadowPositionWorld' )`,
7005    /// assigned by `ShadowBaseNode.setupShadowPosition()` once per shadow.
7006    shadow_position_world,
7007    "shadowPositionWorld",
7008    Type::Vec3
7009);
7010/// `cameraViewMatrix.transformDirection( dir )` —
7011/// `MathNode.TRANSFORM_DIRECTION`: `normalize( ( m * vec4( dir, 0 ) ).xyz )`.
7012/// Spelt out because the port's `mul` pads a `mat4 * vec3` with `1.0`.
7013pub fn transform_direction(matrix: NodeRef, dir: NodeRef) -> NodeRef {
7014    matrix
7015        .mul(vec4_join(vec![dir, float(0.0)]))
7016        .xyz()
7017        .normalize()
7018}
7019
7020/// `lightTargetDirection( light )` — `Lights.js`.
7021pub fn light_target_direction(index: usize) -> NodeRef {
7022    transform_direction(
7023        camera_view_matrix(),
7024        light_world_position(index).sub(light_target_position(index)),
7025    )
7026}
7027
7028/// `texture( depthTexture, uv ).compare( z )` — `ShadowFilterNode`'s
7029/// `depthCompare`, which lowers to `textureSampleCompare`.
7030pub fn shadow_map_compare(map: &DepthTexture, coord: NodeRef, z: NodeRef) -> NodeRef {
7031    texture_node(
7032        TextureSource::ShadowMap(map.clone()),
7033        coord,
7034        SampleMode::Compare(z),
7035        Type::F32,
7036    )
7037}
7038
7039/// `interleavedGradientNoise( position )` — `PostProcessingUtils.js`.
7040pub fn interleaved_gradient_noise(position: NodeRef) -> NodeRef {
7041    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
7042    let def = CELL.with(|c| {
7043        c.get(|| {
7044            shader_fn(
7045                Some("interleavedGradientNoise"),
7046                vec![("position", Type::Vec2)],
7047                Type::F32,
7048                |args| {
7049                    float(52.9829189)
7050                        .mul(dot(args[0].clone(), vec2(0.06711056, 0.00583715)).fract())
7051                        .fract()
7052                },
7053            )
7054        })
7055    });
7056    call(&def, vec![position])
7057}
7058
7059/// `vogelDiskSample( sampleIndex, samplesCount, phi )` —
7060/// `PostProcessingUtils.js`.
7061pub fn vogel_disk_sample(sample_index: NodeRef, samples_count: NodeRef, phi: NodeRef) -> NodeRef {
7062    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
7063    let def = CELL.with(|c| {
7064        c.get(|| {
7065            shader_fn(
7066                Some("vogelDiskSample"),
7067                vec![
7068                    ("sampleIndex", Type::I32),
7069                    ("samplesCount", Type::I32),
7070                    ("phi", Type::F32),
7071                ],
7072                Type::Vec2,
7073                |args| {
7074                    let (index, count, phi) = (args[0].clone(), args[1].clone(), args[2].clone());
7075                    // `goldenAngle = 2π * ( 2 - φ )`.
7076                    let theta = index
7077                        .clone()
7078                        .to(Type::F32)
7079                        .mul(float(2.399963229728653))
7080                        .add(phi);
7081                    let r = index
7082                        .to(Type::F32)
7083                        .add(float(0.5))
7084                        .div(count.to(Type::F32))
7085                        .sqrt();
7086                    vec2_join(vec![theta.cos(), theta.sin()]).mul(r)
7087                },
7088            )
7089        })
7090    });
7091    call(&def, vec![sample_index, samples_count, phi])
7092}
7093
7094/// `acesFilmicToneMapping( color, exposure )` —
7095/// `ToneMappingFunctions.js`, emitted as a real `fn`.
7096pub fn aces_filmic_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
7097    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
7098    let def = CELL.with(|c| {
7099        c.get(|| {
7100            shader_fn(
7101                Some("acesFilmicToneMapping"),
7102                vec![("color", Type::Vec3), ("exposure", Type::F32)],
7103                Type::Vec3,
7104                |args| {
7105                    let (color, exposure) = (args[0].clone(), args[1].clone());
7106                    // sRGB → ACEScg, with three.js' `/ 0.6` pre-exposure.
7107                    let input = constant(
7108                        Type::Mat3,
7109                        vec![
7110                            0.59719, 0.076, 0.0284, //
7111                            0.35458, 0.90834, 0.13383, //
7112                            0.04823, 0.01566, 0.83777,
7113                        ],
7114                    );
7115                    let output = constant(
7116                        Type::Mat3,
7117                        vec![
7118                            1.60475, -0.10208, -0.00327, //
7119                            -0.53108, 1.10813, -0.07276, //
7120                            -0.07367, -0.00605, 1.07602,
7121                        ],
7122                    );
7123                    let c = input.mul(color.mul(exposure).div(float(0.6)));
7124                    // `RRTAndODTFit( v )`.
7125                    let a = c
7126                        .clone()
7127                        .mul(c.clone().add(float(0.0245786)))
7128                        .sub(float(0.000090537));
7129                    let b = c
7130                        .clone()
7131                        .mul(c.add(float(0.432951)).mul(float(0.983729)))
7132                        .add(float(0.238081));
7133                    output.mul(a.div(b)).saturate()
7134                },
7135            )
7136        })
7137    });
7138    call(&def, vec![color, exposure])
7139}
7140
7141/// `agxToneMapping( color, exposure )` — `ToneMappingFunctions.js`' AgX,
7142/// emitted as a real `fn`. `agxDefaultContrastApprox` has no layout upstream,
7143/// so it inlines here too, with its three `toVar()`s.
7144///
7145/// The matrices are `mat3( vec3, vec3, vec3 )` — columns — and are written
7146/// out column by column, as the WGSL prints them. The first and last are
7147/// `LINEAR_SRGB_TO_LINEAR_REC2020` and its inverse from `ColorSpaceFunctions`.
7148pub fn agx_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
7149    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
7150    let def = CELL.with(|c| {
7151        c.get(|| {
7152            shader_fn(
7153                Some("agxToneMapping"),
7154                vec![("color", Type::Vec3), ("exposure", Type::F32)],
7155                Type::Vec3,
7156                |args| {
7157                    let (color, exposure) = (args[0].clone(), args[1].clone());
7158                    let srgb_to_rec2020 = constant(
7159                        Type::Mat3,
7160                        vec![
7161                            0.6274, 0.0691, 0.0164, //
7162                            0.3293, 0.9195, 0.088, //
7163                            0.0433, 0.0113, 0.8956,
7164                        ],
7165                    );
7166                    let inset = constant(
7167                        Type::Mat3,
7168                        vec![
7169                            0.856627153315983,
7170                            0.137318972929847,
7171                            0.11189821299995,
7172                            0.0951212405381588,
7173                            0.761241990602591,
7174                            0.0767994186031903,
7175                            0.0482516061458583,
7176                            0.101439036467562,
7177                            0.811302368396859,
7178                        ],
7179                    );
7180                    let outset = constant(
7181                        Type::Mat3,
7182                        vec![
7183                            1.1271005818144368,
7184                            -0.1413297634984383,
7185                            -0.14132976349843826,
7186                            -0.11060664309660323,
7187                            1.157823702216272,
7188                            -0.11060664309660294,
7189                            -0.016493938717834573,
7190                            -0.016493938717834257,
7191                            1.2519364065950405,
7192                        ],
7193                    );
7194                    let rec2020_to_srgb = constant(
7195                        Type::Mat3,
7196                        vec![
7197                            1.6605, -0.1246, -0.0182, //
7198                            -0.5876, 1.1329, -0.1006, //
7199                            -0.0728, -0.0083, 1.1187,
7200                        ],
7201                    );
7202                    let min_ev = || float(-12.47393);
7203                    let max_ev = float(4.026069);
7204
7205                    let colortone = to_var(None, color);
7206                    // `agxDefaultContrastApprox( colortone )`, inlined.
7207                    let x = to_var(None, colortone.clone());
7208                    let x2 = to_var(None, x.clone().mul(x.clone()));
7209                    let x4 = to_var(None, x2.clone().mul(x2.clone()));
7210                    let contrast = float(15.5)
7211                        .mul(x4.clone().mul(x2.clone()))
7212                        .sub(float(40.14).mul(x4.clone().mul(x.clone())))
7213                        .add(
7214                            float(31.96)
7215                                .mul(x4)
7216                                .sub(float(6.868).mul(x2.clone().mul(x.clone())))
7217                                .add(
7218                                    float(0.4298)
7219                                        .mul(x2)
7220                                        .add(float(0.1191).mul(x).sub(float(0.00232))),
7221                                ),
7222                        );
7223                    block(
7224                        vec![
7225                            colortone.assign(colortone.mul(exposure)),
7226                            colortone.assign(srgb_to_rec2020.mul(colortone.clone())),
7227                            colortone.assign(inset.mul(colortone.clone())),
7228                            colortone.assign(max(colortone.clone(), float(1e-10))),
7229                            colortone.assign(log2(colortone.clone())),
7230                            colortone.assign(colortone.sub(min_ev()).div(max_ev.sub(min_ev()))),
7231                            colortone.assign(colortone.clamp(0.0, 1.0)),
7232                            colortone.assign(contrast),
7233                            colortone.assign(outset.mul(colortone.clone())),
7234                            colortone.assign(
7235                                max(vec3(0.0, 0.0, 0.0), colortone.clone())
7236                                    .pow(vec3(2.2, 2.2, 2.2)),
7237                            ),
7238                            colortone.assign(rec2020_to_srgb.mul(colortone.clone())),
7239                            colortone.assign(colortone.clamp(0.0, 1.0)),
7240                        ],
7241                        colortone,
7242                    )
7243                },
7244            )
7245        })
7246    });
7247    call(&def, vec![color, exposure])
7248}
7249
7250/// `neutralToneMapping( color, exposure )` — `ToneMappingFunctions.js`'
7251/// Khronos PBR Neutral, emitted as a real `fn`.
7252///
7253/// `StartCompression` is `0.8 - 0.04`; three.js prints the double as `0.76`,
7254/// and `0.76f32` is the same float, so the literal is written out.
7255pub fn neutral_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
7256    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
7257    let def = CELL.with(|c| {
7258        c.get(|| {
7259            shader_fn(
7260                Some("neutralToneMapping"),
7261                vec![("color", Type::Vec3), ("exposure", Type::F32)],
7262                Type::Vec3,
7263                |args| {
7264                    let start_compression = || float(0.76);
7265                    let desaturation = float(0.15);
7266                    // `color = color.mul( exposure )` — reassigned twice
7267                    // below, so it is a var, not a temp.
7268                    let color = to_var(None, args[0].clone().mul(args[1].clone()));
7269                    let x = color.x().min(color.y().min(color.z()));
7270                    let offset = x
7271                        .less_than(float(0.08))
7272                        .select(x.sub(float(6.25).mul(x.mul(x.clone()))), float(0.04));
7273                    let peak = color.x().max(color.y().max(color.z()));
7274                    let d = float(1.0).sub(start_compression());
7275                    let new_peak =
7276                        float(1.0).sub(d.mul(d.clone()).div(peak.add(d.sub(start_compression()))));
7277                    let g = float(1.0).sub(
7278                        float(1.0)
7279                            .div(desaturation.mul(peak.sub(new_peak.clone())).add(float(1.0))),
7280                    );
7281                    block(
7282                        vec![
7283                            color.assign(color.sub(offset)),
7284                            // `If( peak.lessThan( StartCompression ), () => {
7285                            // return color; } )`.
7286                            if_statement(
7287                                peak.less_than(start_compression()),
7288                                vec![return_statement(color.clone())],
7289                            ),
7290                            color.assign(color.mul(new_peak.div(peak))),
7291                        ],
7292                        mix(color, new_peak.to(Type::Vec3), g),
7293                    )
7294                },
7295            )
7296        })
7297    });
7298    call(&def, vec![color, exposure])
7299}
7300
7301#[cfg(test)]
7302mod tests {
7303    use super::*;
7304
7305    #[test]
7306    fn texture_type_follows_threes_format_mapping() {
7307        use wgpu::TextureFormat as F;
7308        let cases = [
7309            (F::R8Unorm, Type::F32),
7310            (F::R16Float, Type::F32),
7311            (F::R32Float, Type::F32),
7312            (F::R32Uint, Type::U32),
7313            (F::R32Sint, Type::I32),
7314            (F::Rg16Float, Type::Vec2),
7315            (F::Rg32Uint, Type::UVec2),
7316            (F::Rgba8Unorm, Type::Vec4),
7317            (F::Rgba16Uint, Type::UVec4),
7318            (F::Depth32Float, Type::F32),
7319            (F::Depth24PlusStencil8, Type::F32),
7320            // One- and two-channel in wgpu, `vec4` in three.
7321            (F::Bc4RUnorm, Type::Vec4),
7322            (F::Bc4RSnorm, Type::Vec4),
7323            (F::Bc5RgUnorm, Type::Vec4),
7324            (F::EacR11Unorm, Type::Vec4),
7325            (F::EacR11Snorm, Type::Vec4),
7326            (F::EacRg11Unorm, Type::Vec4),
7327        ];
7328        for (format, ty) in cases {
7329            assert_eq!(texture_type_for_format(format), ty, "{format:?}");
7330        }
7331    }
7332
7333    #[test]
7334    fn a_swizzle_of_a_scalar_splats_it() {
7335        let s = float(0.5);
7336        // `.x` / `.y` on a float is the float: three ignores the components.
7337        assert!(matches!(s.x().node(), Node::Const { .. }));
7338        assert_eq!(s.y().ty(), Type::F32);
7339        assert!(matches!(s.y().node(), Node::Const { .. }));
7340        // `.xyz` is the float widened to a vec3 — a cast, never `s.xyz`.
7341        let v = s.xyz();
7342        assert_eq!(v.ty(), Type::Vec3);
7343        assert!(matches!(v.node(), Node::Cast { ty: Type::Vec3, .. }));
7344    }
7345}