Skip to main content

three_rs/nodes/tsl/
wrappers.rs

1//! The thin-wrapper tier of TSL (issue #141): the constructors, constants and
2//! named math functions that three.js exports as one-liners over `ConstNode`,
3//! `ConvertNode`, `JoinNode`, `MathNode`, `OperatorNode` and a few inlined
4//! `Fn()`s. Each item's doc comment names the JS it ports; the WGSL each one
5//! emits is pinned against three's own dump in `tests/nodes_tsl_batch.rs`.
6//!
7//! Where three's output and the port's differ only in how a shared
8//! intermediate is named (`let nodeConstN` in three, `var<private> nodeVarN`
9//! here), the divergence is the general one `docs/nodes.md` §8 records, not
10//! something specific to these wrappers.
11
12use std::rc::Rc;
13
14use super::{
15    binary, block, call, constant, float, join, math, rotate, shader_fn, to_const, to_var,
16};
17use super::{
18    camera_position, camera_projection_matrix, camera_view_matrix, model_world_matrix,
19    position_geometry, position_world, uniform,
20};
21use crate::math::{Color, Matrix2, Matrix3, Matrix4};
22use crate::nodes::node::{FnDef, Lazy, Node, NodeRef, Type, UniformGroup, UniformSource};
23
24// ---------------------------------------------------------------------------
25// type helpers
26// ---------------------------------------------------------------------------
27
28/// `MathNode.getInputType()`: the widest operand, matrices counting as
29/// width 0, with `a` winning ties.
30fn input_type(args: &[&NodeRef]) -> Type {
31    let len = |n: Option<&&NodeRef>| match n {
32        Some(n) if !n.ty().is_matrix() => n.ty().components(),
33        _ => 0,
34    };
35    let (a, b, c) = (args.first(), args.get(1), args.get(2));
36    let (la, lb, lc) = (len(a), len(b), len(c));
37    if la > lb && la > lc {
38        a.unwrap().ty()
39    } else if lb > lc {
40        b.unwrap().ty()
41    } else if lc > la {
42        c.unwrap().ty()
43    } else {
44        a.unwrap().ty()
45    }
46}
47
48/// `NodeBuilder.getIntegerType()`: an integer type keeps itself, anything
49/// else becomes the `i32` vector of its width.
50fn integer_type(ty: Type) -> Type {
51    match ty.component_type() {
52        Type::I32 | Type::U32 => ty,
53        _ => Type::vector_of(Type::I32, ty.components()),
54    }
55}
56
57/// A one-operand `MathNode`, typed by its operand.
58fn unary(name: &'static str, x: NodeRef) -> NodeRef {
59    let ty = x.ty();
60    math(name, vec![x], ty)
61}
62
63/// `ConvertType( type, ...params )` from `TSLCore.js`: what `uvec3( … )`,
64/// `bvec2( … )` and friends are.
65///
66/// - Every parameter a number: one `ConstNode` of the target type (a single
67///   scalar splats), which `generateConst()` writes component by component —
68///   `vec3<u32>( 1u, 2u, 3u )`.
69/// - One node: a `ConvertNode` (`u32( x )`), or the node itself when it
70///   already has the type.
71/// - Several nodes: a `JoinNode`.
72///
73/// Rust has no JS-number/node distinction at the call site, so a scalar
74/// `Node::Const` stands in for a JS number. Three would join a `float( 1 )`
75/// *node* rather than fold it; nothing ported passes one, and folding is the
76/// literal three emits for the number form every example uses.
77fn convert_type(ty: Type, params: Vec<NodeRef>) -> NodeRef {
78    let n = ty.components();
79    if params.is_empty() {
80        return constant(ty, vec![0.0; n]);
81    }
82    let all_const = params
83        .iter()
84        .all(|p| matches!(p.node(), Node::Const { .. }));
85    if all_const {
86        let mut values: Vec<f64> = params
87            .iter()
88            .flat_map(|p| match p.node() {
89                Node::Const { values, .. } => values.clone(),
90                _ => unreachable!(),
91            })
92            .collect();
93        if values.len() == 1 {
94            values = vec![values[0]; n];
95        }
96        values.resize(n, 0.0);
97        return constant(ty, values);
98    }
99    if params.len() == 1 {
100        return params[0].to(ty);
101    }
102    join(ty, params)
103}
104
105// ---------------------------------------------------------------------------
106// constructors (`TSLCore.js`)
107// ---------------------------------------------------------------------------
108
109/// `color( 0xff8000 )` — `TSLCore.js`' `color = new ConvertType( 'color' )`
110/// over a `Color`. The hex is sRGB and the const is the working (linear)
111/// value, exactly as `new Color( hex )` stores it.
112pub fn color(hex: u32) -> NodeRef {
113    Color::from_hex(hex).into()
114}
115
116/// `color( r, g, b )` — the three-number form, which `Color.setRGB()` takes
117/// as working-space components unchanged.
118pub fn color_rgb(r: f64, g: f64, b: f64) -> NodeRef {
119    constant(Type::Vec3, vec![r, g, b])
120}
121
122/// `bool( x )` — `TSLCore.js`' `bool = new ConvertType( 'bool' )`.
123pub fn bool(x: impl Into<NodeRef>) -> NodeRef {
124    convert_type(Type::Bool, vec![x.into()])
125}
126
127macro_rules! vector_ctor {
128    ($(#[$m:meta])* $name:ident, $ty:expr, $($arg:ident),+) => {
129        $(#[$m])*
130        pub fn $name($($arg: impl Into<NodeRef>),+) -> NodeRef {
131            convert_type($ty, vec![$($arg.into()),+])
132        }
133    };
134}
135
136vector_ctor!(
137    /// `uvec2( x, y )` — `TSLCore.js`' `ConvertType( 'uvec2' )`.
138    uvec2, Type::UVec2, x, y
139);
140vector_ctor!(
141    /// `uvec3( x, y, z )` — `TSLCore.js`' `ConvertType( 'uvec3' )`.
142    uvec3, Type::UVec3, x, y, z
143);
144vector_ctor!(
145    /// `uvec4( x, y, z, w )` — `TSLCore.js`' `ConvertType( 'uvec4' )`.
146    uvec4, Type::UVec4, x, y, z, w
147);
148vector_ctor!(
149    /// `ivec3( x, y, z )` — `TSLCore.js`' `ConvertType( 'ivec3' )`.
150    ivec3, Type::IVec3, x, y, z
151);
152vector_ctor!(
153    /// `ivec4( x, y, z, w )` — `TSLCore.js`' `ConvertType( 'ivec4' )`.
154    ivec4, Type::IVec4, x, y, z, w
155);
156vector_ctor!(
157    /// `bvec2( x, y )` — `TSLCore.js`' `ConvertType( 'bvec2' )`.
158    bvec2, Type::BVec2, x, y
159);
160vector_ctor!(
161    /// `bvec3( x, y, z )` — `TSLCore.js`' `ConvertType( 'bvec3' )`.
162    bvec3, Type::BVec3, x, y, z
163);
164vector_ctor!(
165    /// `bvec4( x, y, z, w )` — `TSLCore.js`' `ConvertType( 'bvec4' )`.
166    bvec4, Type::BVec4, x, y, z, w
167);
168
169/// `mat2( matrix2 )` / `mat2( a, b, c, d )` with numbers — `TSLCore.js`'
170/// `ConvertType( 'mat2' )`, whose number form goes through `Matrix2.set()`
171/// (row-major arguments). The const is written column-major, as
172/// `generateConst()` reads `matrix.elements`: `mat2( 1, 2, 3, 4 )` is
173/// `mat2x2<f32>( 1.0, 3.0, 2.0, 4.0 )`.
174pub fn mat2(m: Matrix2) -> NodeRef {
175    constant(Type::Mat2, m.elements.to_vec())
176}
177
178/// `mat3( matrix3 )` — `TSLCore.js`' `ConvertType( 'mat3' )` over a value.
179pub fn mat3(m: Matrix3) -> NodeRef {
180    constant(Type::Mat3, m.elements.to_vec())
181}
182
183/// `mat4( matrix4 )` — `TSLCore.js`' `ConvertType( 'mat4' )` over a value.
184pub fn mat4(m: Matrix4) -> NodeRef {
185    constant(Type::Mat4, m.elements.to_vec())
186}
187
188/// `mat2( a, b, c, d )` with nodes — a `JoinNode` in column order.
189pub fn mat2_join(args: Vec<NodeRef>) -> NodeRef {
190    convert_type(Type::Mat2, args)
191}
192
193/// `mat3( … )` with nodes — a `JoinNode` (or a `ConvertNode` for one node:
194/// `mat3( modelWorldMatrix )` is the `mat4` → `mat3` narrowing).
195pub fn mat3_join(args: Vec<NodeRef>) -> NodeRef {
196    convert_type(Type::Mat3, args)
197}
198
199/// `mat4( … )` with nodes.
200pub fn mat4_join(args: Vec<NodeRef>) -> NodeRef {
201    convert_type(Type::Mat4, args)
202}
203
204// ---------------------------------------------------------------------------
205// constants (`math/MathNode.js`)
206// ---------------------------------------------------------------------------
207
208/// `PI` — `MathNode.js`: `float( Math.PI )`.
209pub fn pi() -> NodeRef {
210    float(std::f64::consts::PI)
211}
212
213/// `PI2` — `MathNode.js`: `float( Math.PI * 2 )`, the deprecated spelling of
214/// `TWO_PI` ([`super::two_pi`]).
215pub fn pi2() -> NodeRef {
216    float(std::f64::consts::TAU)
217}
218
219/// `HALF_PI` — `MathNode.js`: `float( Math.PI * 0.5 )`.
220pub fn half_pi() -> NodeRef {
221    float(std::f64::consts::FRAC_PI_2)
222}
223
224/// `EPSILON` — `MathNode.js`: `float( 1e-6 )`.
225pub fn epsilon() -> NodeRef {
226    float(1e-6)
227}
228
229/// `INFINITY` — `MathNode.js`: `float( 1e6 )`. Not IEEE infinity: three's
230/// constant is a large finite number, and so is this.
231pub fn infinity() -> NodeRef {
232    float(1e6)
233}
234
235// ---------------------------------------------------------------------------
236// one-operand math (`math/MathNode.js`)
237// ---------------------------------------------------------------------------
238
239macro_rules! unary_math {
240    ($(#[$m:meta])* $name:ident, $wgsl:literal) => {
241        $(#[$m])*
242        pub fn $name(x: impl Into<NodeRef>) -> NodeRef {
243            unary($wgsl, x.into())
244        }
245    };
246}
247
248unary_math!(
249    /// `atan( x )` — `MathNode.ATAN` with one argument. The two-argument form
250    /// is [`NodeRef::atan2`].
251    atan, "atan"
252);
253unary_math!(
254    /// `acos( x )` — `MathNode.ACOS`.
255    acos, "acos"
256);
257unary_math!(
258    /// `asin( x )` — `MathNode.ASIN`.
259    asin, "asin"
260);
261unary_math!(
262    /// `tan( x )` — `MathNode.TAN`.
263    tan, "tan"
264);
265unary_math!(
266    /// `sinh( x )` — `MathNode.SINH`.
267    sinh, "sinh"
268);
269unary_math!(
270    /// `cosh( x )` — `MathNode.COSH`.
271    cosh, "cosh"
272);
273unary_math!(
274    /// `tanh( x )` — `MathNode.TANH`.
275    tanh, "tanh"
276);
277unary_math!(
278    /// `asinh( x )` — `MathNode.ASINH`.
279    asinh, "asinh"
280);
281unary_math!(
282    /// `acosh( x )` — `MathNode.ACOSH`.
283    acosh, "acosh"
284);
285unary_math!(
286    /// `atanh( x )` — `MathNode.ATANH`.
287    atanh, "atanh"
288);
289unary_math!(
290    /// `round( x )` — `MathNode.ROUND`.
291    round, "round"
292);
293unary_math!(
294    /// `trunc( x )` — `MathNode.TRUNC`.
295    trunc, "trunc"
296);
297unary_math!(
298    /// `degrees( x )` — `MathNode.DEGREES`.
299    degrees, "degrees"
300);
301unary_math!(
302    /// `radians( x )` — `MathNode.RADIANS`.
303    radians, "radians"
304);
305unary_math!(
306    /// `transpose( m )` — `MathNode.TRANSPOSE`.
307    transpose, "transpose"
308);
309unary_math!(
310    /// `countOneBits( x )` — `BitcountNode.COUNT_ONE_BITS`, WGSL's builtin
311    /// of the same name, typed as its operand.
312    count_one_bits, "countOneBits"
313);
314unary_math!(
315    /// `countTrailingZeros( x )` — `BitcountNode.COUNT_TRAILING_ZEROS`.
316    count_trailing_zeros, "countTrailingZeros"
317);
318unary_math!(
319    /// `countLeadingZeros( x )` — `BitcountNode.COUNT_LEADING_ZEROS`.
320    count_leading_zeros, "countLeadingZeros"
321);
322
323/// `determinant( m )` — `MathNode.DETERMINANT`, a `float` out of a matrix.
324pub fn determinant(m: impl Into<NodeRef>) -> NodeRef {
325    math("determinant", vec![m.into()], Type::F32)
326}
327
328/// `inverse( m )` — `MathNode.INVERSE`. WGSL has no `inverse`, so
329/// `WGSLNodeBuilder`'s polyfill table lowers it to `tsl_inverse_mat2/3/4`,
330/// whose code the builder adds on first use (`wgsl::polyfill`).
331pub fn inverse(m: impl Into<NodeRef>) -> NodeRef {
332    let m = m.into();
333    let name = match m.ty() {
334        Type::Mat2 => "tsl_inverse_mat2",
335        Type::Mat3 => "tsl_inverse_mat3",
336        Type::Mat4 => "tsl_inverse_mat4",
337        other => panic!("three-rs: inverse() of a {other:?}"),
338    };
339    unary(name, m)
340}
341
342// ---------------------------------------------------------------------------
343// powers and shaping (`math/MathNode.js`, `math/MathUtils.js`)
344// ---------------------------------------------------------------------------
345
346/// `pow( a, b )` typed by `MathNode.getInputType()`.
347fn pow_of(a: NodeRef, b: NodeRef) -> NodeRef {
348    let ty = input_type(&[&a, &b]);
349    math("pow", vec![a, b], ty)
350}
351
352/// `pow2( x )` — `MathNode.js`: `mul( x, x )`.
353pub fn pow2(x: impl Into<NodeRef>) -> NodeRef {
354    let x = x.into();
355    x.mul(x.clone())
356}
357
358/// `pow3( x )` — `MathNode.js`: `mul( x, x, x )`.
359pub fn pow3(x: impl Into<NodeRef>) -> NodeRef {
360    x.into().pow3()
361}
362
363/// `pow4( x )` — `MathNode.js`: `mul( x, x, x, x )`.
364pub fn pow4(x: impl Into<NodeRef>) -> NodeRef {
365    let x = x.into();
366    x.mul(x.clone()).mul(x.clone()).mul(x)
367}
368
369/// `difference( a, b )` — `MathNode.DIFFERENCE`, `abs( a - b )`.
370pub fn difference(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
371    let d = a.into().sub(b);
372    unary("abs", d)
373}
374
375/// `cbrt( a )` — `MathNode.js`: `mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) )`.
376pub fn cbrt(a: impl Into<NodeRef>) -> NodeRef {
377    let a = a.into();
378    unary("sign", a.clone()).mul(pow_of(unary("abs", a), float(1.0 / 3.0)))
379}
380
381/// `lengthSq( a )` — `MathNode.js`: `dot( a, a )`.
382pub fn length_sq(a: impl Into<NodeRef>) -> NodeRef {
383    let a = a.into();
384    super::dot(a.clone(), a)
385}
386
387/// `faceForward( N, I, Nref )` — `MathNode.FACEFORWARD`, WGSL's builtin.
388pub fn face_forward(
389    n: impl Into<NodeRef>,
390    i: impl Into<NodeRef>,
391    nref: impl Into<NodeRef>,
392) -> NodeRef {
393    let (n, i, nref) = (n.into(), i.into(), nref.into());
394    let ty = input_type(&[&n, &i, &nref]);
395    math("faceForward", vec![n, i, nref], ty)
396}
397
398/// `parabola( x, k )` — `MathUtils.js`:
399/// `pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k )`.
400pub fn parabola(x: impl Into<NodeRef>, k: impl Into<NodeRef>) -> NodeRef {
401    let x = x.into();
402    pow_of(float(4.0).mul(x.mul(float(1.0).sub(x.clone()))), k.into())
403}
404
405/// `gain( x, k )` — `MathUtils.js`: `select( x.lessThan( 0.5 ), pow( mul(
406/// 2.0, x ), k ).mul( 0.5 ), sub( 1.0, pow( mul( 2.0, sub( 1.0, x ) ), k
407/// ).mul( 0.5 ) ) )`, which generates as an `if`/`else` over a result var.
408pub fn gain(x: impl Into<NodeRef>, k: impl Into<NodeRef>) -> NodeRef {
409    let (x, k) = (x.into(), k.into());
410    let low = pow_of(float(2.0).mul(x.clone()), k.clone()).mul(0.5);
411    let high = float(1.0).sub(pow_of(float(2.0).mul(float(1.0).sub(x.clone())), k).mul(0.5));
412    x.less_than(0.5).select(low, high)
413}
414
415/// `pcurve( x, a, b )` — `MathUtils.js`: `pow( div( pow( x, a ), add( pow(
416/// x, a ), pow( sub( 1.0, x ), b ) ) ), div( 1.0, a ) )`. The two `pow( x, a
417/// )` are two nodes in three, so they are two expressions here too.
418pub fn pcurve(x: impl Into<NodeRef>, a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
419    let (x, a, b) = (x.into(), a.into(), b.into());
420    let num = pow_of(x.clone(), a.clone());
421    let den = pow_of(x.clone(), a.clone()).add(pow_of(float(1.0).sub(x), b));
422    pow_of(num.div(den), float(1.0).div(a))
423}
424
425/// `sinc( x, k )` — `MathUtils.js`: `arg = abs( PI.mul( k.mul( x ).sub( 1.0
426/// ) ) ).max( 1e-6 ).toConst()`, then `sin( arg ).div( arg )`. Three calls
427/// `k.mul()`, so `k` must be a node there; here anything `Into<NodeRef>` is.
428pub fn sinc(x: impl Into<NodeRef>, k: impl Into<NodeRef>) -> NodeRef {
429    let (x, k) = (x.into(), k.into());
430    let arg = unary("abs", pi().mul(k.mul(x).sub(1.0))).max(1e-6);
431    let arg = to_const(None, arg);
432    arg.sin().div(arg)
433}
434
435/// `faceforward( N, I, Nref )` — `MathNode.js`' `faceforward = faceForward`,
436/// the deprecated GLSL spelling of [`face_forward`]. Three keeps it as a
437/// plain alias with no warning, and so does this.
438pub fn faceforward(
439    n: impl Into<NodeRef>,
440    i: impl Into<NodeRef>,
441    nref: impl Into<NodeRef>,
442) -> NodeRef {
443    face_forward(n, i, nref)
444}
445
446/// `inversesqrt( x )` — `MathNode.js`' `inversesqrt = inverseSqrt`, the
447/// deprecated GLSL spelling of [`super::inverse_sqrt`]. A plain alias, as in
448/// three.
449pub fn inversesqrt(x: impl Into<NodeRef>) -> NodeRef {
450    super::inverse_sqrt(x)
451}
452
453/// `any( x )` — `MathNode.ANY`: whether any component of a boolean vector is
454/// true. The `all` counterpart is [`super::all`].
455pub fn any(x: impl Into<NodeRef>) -> NodeRef {
456    math("any", vec![x.into()], Type::Bool)
457}
458
459/// `transformNormalByViewMatrix( normal, viewMatrix )` — `MathNode.js`:
460/// `normalize( mul( viewMatrix, vec4( vec3( normal ), 0.0 ) ).xyz )`. The
461/// view matrix's upper 3×3 is taken as orthonormal, so no normal matrix is
462/// involved.
463pub fn transform_normal_by_view_matrix(
464    normal: impl Into<NodeRef>,
465    view_matrix: impl Into<NodeRef>,
466) -> NodeRef {
467    let n = join(Type::Vec4, vec![normal.into().to_vec3(), float(0.0)]);
468    view_matrix.into().mul(n).xyz().normalize()
469}
470
471/// `transformNormal( normal, matrix )` — `Normal.js`: `mat3( matrix )
472/// .inverse().transpose().mul( normal ).normalize()`, the normal through the
473/// inverse transpose of `matrix`'s upper 3×3.
474///
475/// Three's `matrix` defaults to `modelWorldMatrix`. Rust has no default
476/// arguments, so three's one-argument `transformNormal( normal )` is
477/// `transform_normal( normal, model_world_matrix() )` here.
478pub fn transform_normal(normal: impl Into<NodeRef>, matrix: impl Into<NodeRef>) -> NodeRef {
479    matrix
480        .into()
481        .to_mat3()
482        .inverse()
483        .transpose()
484        .mul(normal.into())
485        .normalize()
486}
487
488/// `transformNormalToView( normal )` — `Normal.js`: `normal` from local to
489/// view space, `modelNormalMatrix.mul( normal ).transformNormalByViewMatrix(
490/// cameraViewMatrix )`.
491///
492/// Three takes `normal.transformNormalByViewMatrix( modelNormalViewMatrix )`
493/// instead when `builder.context.modelNormalViewMatrix` is set, which only
494/// `renderer.highPrecision` does. The port reads the same key from the build
495/// context in force when this is called — nothing in the crate sets it.
496pub fn transform_normal_to_view(normal: impl Into<NodeRef>) -> NodeRef {
497    let normal = normal.into();
498    let matrix =
499        crate::nodes::builder::current_context(|cx| cx.extra.get("modelNormalViewMatrix").cloned());
500    match matrix {
501        Some(matrix) => transform_normal_by_view_matrix(normal, matrix),
502        None => transform_normal_by_view_matrix(
503            super::model_normal_matrix().mul(normal),
504            camera_view_matrix(),
505        ),
506    }
507}
508
509/// `transformNormalByInverseViewMatrix( normal, viewMatrix )` —
510/// `MathNode.js`: `normalize( vec4( vec3( normal ), 0.0 ).mul( viewMatrix
511/// ).xyz )`. Post-multiplying by an orthonormal view matrix is
512/// pre-multiplying by its inverse.
513pub fn transform_normal_by_inverse_view_matrix(
514    normal: impl Into<NodeRef>,
515    view_matrix: impl Into<NodeRef>,
516) -> NodeRef {
517    let n = join(Type::Vec4, vec![normal.into().to_vec3(), float(0.0)]);
518    n.mul(view_matrix.into()).xyz().normalize()
519}
520
521// ---------------------------------------------------------------------------
522// packing (`math/PackFloatNode.js`, `math/UnpackFloatNode.js`,
523// `math/Packed4x8IntegerNode.js`)
524// ---------------------------------------------------------------------------
525
526/// `PackFloatNode` / `UnpackFloatNode`: one call to the WGSL builtin
527/// `WGSLNodeBuilder.getFloatPackingMethod()` names, its operand built at its
528/// own type and written with no padding inside the parentheses, as three's
529/// template does (`pack2x16snorm(v)`).
530fn float_packing(builtin: &'static str, x: impl Into<NodeRef>, ty: Type) -> NodeRef {
531    math(builtin, vec![x.into()], ty)
532}
533
534/// `packSnorm2x16( v )` — `PackFloatNode( 'snorm' )`: a `vec2` in `[ -1, 1 ]`
535/// to a `u32`, WGSL's `pack2x16snorm`.
536pub fn pack_snorm_2x16(v: impl Into<NodeRef>) -> NodeRef {
537    float_packing("pack2x16snorm", v, Type::U32)
538}
539
540/// `packUnorm2x16( v )` — `PackFloatNode( 'unorm' )`, WGSL's `pack2x16unorm`.
541pub fn pack_unorm_2x16(v: impl Into<NodeRef>) -> NodeRef {
542    float_packing("pack2x16unorm", v, Type::U32)
543}
544
545/// `packHalf2x16( v )` — `PackFloatNode( 'float16' )`, WGSL's
546/// `pack2x16float`.
547pub fn pack_half_2x16(v: impl Into<NodeRef>) -> NodeRef {
548    float_packing("pack2x16float", v, Type::U32)
549}
550
551/// `packSnorm4x8( v )` — `PackFloatNode( 'snorm', { layout: '4x8' } )`, WGSL's
552/// `pack4x8snorm`.
553pub fn pack_snorm_4x8(v: impl Into<NodeRef>) -> NodeRef {
554    float_packing("pack4x8snorm", v, Type::U32)
555}
556
557/// `packUnorm4x8( v )` — `PackFloatNode( 'unorm', { layout: '4x8' } )`, WGSL's
558/// `pack4x8unorm`.
559pub fn pack_unorm_4x8(v: impl Into<NodeRef>) -> NodeRef {
560    float_packing("pack4x8unorm", v, Type::U32)
561}
562
563/// `unpackSnorm2x16( u )` — `UnpackFloatNode( 'snorm' )`, a `vec2`; WGSL's
564/// `unpack2x16snorm`.
565pub fn unpack_snorm_2x16(u: impl Into<NodeRef>) -> NodeRef {
566    float_packing("unpack2x16snorm", u, Type::Vec2)
567}
568
569/// `unpackUnorm2x16( u )` — `UnpackFloatNode( 'unorm' )`, WGSL's
570/// `unpack2x16unorm`.
571pub fn unpack_unorm_2x16(u: impl Into<NodeRef>) -> NodeRef {
572    float_packing("unpack2x16unorm", u, Type::Vec2)
573}
574
575/// `unpackHalf2x16( u )` — `UnpackFloatNode( 'float16' )`, WGSL's
576/// `unpack2x16float`.
577pub fn unpack_half_2x16(u: impl Into<NodeRef>) -> NodeRef {
578    float_packing("unpack2x16float", u, Type::Vec2)
579}
580
581/// `unpackSnorm4x8( u )` — `UnpackFloatNode( 'snorm', { layout: '4x8' } )`, a
582/// `vec4`; WGSL's `unpack4x8snorm`.
583pub fn unpack_snorm_4x8(u: impl Into<NodeRef>) -> NodeRef {
584    float_packing("unpack4x8snorm", u, Type::Vec4)
585}
586
587/// `unpackUnorm4x8( u )` — `UnpackFloatNode( 'unorm', { layout: '4x8' } )`,
588/// WGSL's `unpack4x8unorm`.
589pub fn unpack_unorm_4x8(u: impl Into<NodeRef>) -> NodeRef {
590    float_packing("unpack4x8unorm", u, Type::Vec4)
591}
592
593/// `Packed4x8IntegerNode`: the WGSL builtin of the same name, operands built
594/// at `getInputType()` — `ivec4` for the signed packs, `uvec4` for the
595/// unsigned ones, `uint` for everything that reads a packed word.
596///
597/// Three emulates these with `tsl_packed4x8_*` functions when
598/// `navigator.gpu.wgslLanguageFeatures` lacks `packed_4x8_integer_dot_product`;
599/// the Chrome the fixtures are dumped from has it, so three's WGSL — and this
600/// — is the native builtin, which naga also implements. The emulation is not
601/// ported: there is no browser to ask.
602fn packed_4x8(method: &'static str, args: Vec<NodeRef>, ty: Type) -> NodeRef {
603    math(method, args, ty)
604}
605
606/// `dot4U8Packed( a, b )` — the dot product of two words' four unsigned
607/// bytes, a `u32`.
608pub fn dot_4u8_packed(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
609    packed_4x8("dot4U8Packed", vec![a.into(), b.into()], Type::U32)
610}
611
612/// `dot4I8Packed( a, b )` — the dot product of two words' four signed bytes,
613/// an `i32`.
614pub fn dot_4i8_packed(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
615    packed_4x8("dot4I8Packed", vec![a.into(), b.into()], Type::I32)
616}
617
618/// `pack4xI8( v )` — the low byte of each `ivec4` component into one `u32`.
619pub fn pack_4x_i8(v: impl Into<NodeRef>) -> NodeRef {
620    packed_4x8("pack4xI8", vec![v.into()], Type::U32)
621}
622
623/// `pack4xU8( v )` — the low byte of each `uvec4` component into one `u32`.
624pub fn pack_4x_u8(v: impl Into<NodeRef>) -> NodeRef {
625    packed_4x8("pack4xU8", vec![v.into()], Type::U32)
626}
627
628/// `pack4xI8Clamp( v )` — [`pack_4x_i8`] after clamping each component to
629/// `[ -128, 127 ]`.
630pub fn pack_4x_i8_clamp(v: impl Into<NodeRef>) -> NodeRef {
631    packed_4x8("pack4xI8Clamp", vec![v.into()], Type::U32)
632}
633
634/// `pack4xU8Clamp( v )` — [`pack_4x_u8`] after clamping each component to
635/// `[ 0, 255 ]`.
636pub fn pack_4x_u8_clamp(v: impl Into<NodeRef>) -> NodeRef {
637    packed_4x8("pack4xU8Clamp", vec![v.into()], Type::U32)
638}
639
640/// `unpack4xI8( u )` — a word's four bytes, sign-extended, as an `ivec4`.
641pub fn unpack_4x_i8(u: impl Into<NodeRef>) -> NodeRef {
642    packed_4x8("unpack4xI8", vec![u.into()], Type::IVec4)
643}
644
645/// `unpack4xU8( u )` — a word's four bytes, zero-extended, as a `uvec4`.
646pub fn unpack_4x_u8(u: impl Into<NodeRef>) -> NodeRef {
647    packed_4x8("unpack4xU8", vec![u.into()], Type::UVec4)
648}
649
650// ---------------------------------------------------------------------------
651// bits and integers (`math/OperatorNode.js`, `math/BitcastNode.js`)
652// ---------------------------------------------------------------------------
653
654/// `xor( a, b )` — `OperatorNode( '^^' )`, the logical exclusive or. WGSL has
655/// no `^^`, so it lowers to `WGSLNodeBuilder`'s `tsl_xor` polyfill.
656pub fn xor(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
657    math("tsl_xor", vec![a.into(), b.into()], Type::Bool)
658}
659
660/// `bitNot( a )` — `OperatorNode( '~' )`, typed `getIntegerType( typeA )`.
661pub fn bit_not(a: impl Into<NodeRef>) -> NodeRef {
662    let node = a.into();
663    let ty = integer_type(node.ty());
664    NodeRef::new(Node::BitNot { node, ty })
665}
666
667/// A `BitcastNode` over `x` into the vector of `component` of `x`'s width:
668/// `bitcast<T>( x )`.
669fn bitcast(x: NodeRef, component: Type) -> NodeRef {
670    let ty = Type::vector_of(component, x.ty().components());
671    let name = match ty {
672        Type::F32 => "bitcast<f32>",
673        Type::I32 => "bitcast<i32>",
674        Type::U32 => "bitcast<u32>",
675        Type::Vec2 => "bitcast<vec2<f32>>",
676        Type::Vec3 => "bitcast<vec3<f32>>",
677        Type::Vec4 => "bitcast<vec4<f32>>",
678        Type::IVec2 => "bitcast<vec2<i32>>",
679        Type::IVec3 => "bitcast<vec3<i32>>",
680        Type::IVec4 => "bitcast<vec4<i32>>",
681        Type::UVec2 => "bitcast<vec2<u32>>",
682        Type::UVec3 => "bitcast<vec3<u32>>",
683        Type::UVec4 => "bitcast<vec4<u32>>",
684        other => panic!("three-rs: bitcast to {other:?}"),
685    };
686    math(name, vec![x], ty)
687}
688
689/// `floatBitsToInt( x )` — `BitcastNode.js`: `new BitcastNode( x, 'int' )`.
690pub fn float_bits_to_int(x: impl Into<NodeRef>) -> NodeRef {
691    bitcast(x.into(), Type::I32)
692}
693
694/// `floatBitsToUint( x )` — `BitcastNode.js`: `new BitcastNode( x, 'uint' )`.
695pub fn float_bits_to_uint(x: impl Into<NodeRef>) -> NodeRef {
696    bitcast(x.into(), Type::U32)
697}
698
699/// `intBitsToFloat( x )` — `BitcastNode.js`: `new BitcastNode( x, 'float' )`.
700pub fn int_bits_to_float(x: impl Into<NodeRef>) -> NodeRef {
701    bitcast(x.into(), Type::F32)
702}
703
704/// `uintBitsToFloat( x )` — `BitcastNode.js`: `new BitcastNode( x, 'float' )`.
705pub fn uint_bits_to_float(x: impl Into<NodeRef>) -> NodeRef {
706    bitcast(x.into(), Type::F32)
707}
708
709/// `increment( a )` — `OperatorNode.js`: `temp = int( a ).toConst();
710/// a.addAssign( 1 ); return temp;`. `a` is a var; the value is `a` as it was.
711pub fn increment(a: &NodeRef) -> NodeRef {
712    let temp = to_const(None, a.to(Type::I32));
713    block(vec![temp.clone(), a.add_assign(1)], temp)
714}
715
716/// `decrement( a )` — `OperatorNode.js`: the post-decrement twin of
717/// [`increment`].
718pub fn decrement(a: &NodeRef) -> NodeRef {
719    let temp = to_const(None, a.to(Type::I32));
720    block(vec![temp.clone(), a.sub_assign(1)], temp)
721}
722
723/// `incrementBefore( a )` — `OperatorNode.js`: `a.addAssign( 1 ); return a;`.
724pub fn increment_before(a: &NodeRef) -> NodeRef {
725    block(vec![a.add_assign(1)], a.clone())
726}
727
728/// `decrementBefore( a )` — `OperatorNode.js`: `a.subAssign( 1 ); return a;`.
729pub fn decrement_before(a: &NodeRef) -> NodeRef {
730    block(vec![a.sub_assign(1)], a.clone())
731}
732
733/// `mod( a, b )` — `MathNode.MOD`. On integers it is the `%` operator; on
734/// floats WGSL's `%` truncates where GLSL's `mod` floors, so
735/// `WGSLNodeBuilder` lowers it to `tsl_mod_float` / `tsl_mod_vec2/3/4`, with
736/// `b` widened to the input type (`uv.mod( 0.5 )` is `tsl_mod_vec2( uv,
737/// vec2<f32>( 0.5 ) )`). `mod` is a Rust keyword, hence the trailing `_`.
738pub fn mod_(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
739    let (a, b) = (a.into(), b.into());
740    let ty = input_type(&[&a, &b]);
741    if matches!(ty.component_type(), Type::I32 | Type::U32) {
742        return binary("%", a, b);
743    }
744    let name = match ty {
745        Type::F32 => "tsl_mod_float",
746        Type::Vec2 => "tsl_mod_vec2",
747        Type::Vec3 => "tsl_mod_vec3",
748        Type::Vec4 => "tsl_mod_vec4",
749        other => panic!("three-rs: mod() of a {other:?}"),
750    };
751    math(name, vec![a, b], ty)
752}
753
754// ---------------------------------------------------------------------------
755// noise and hashing (`math/Hash.js`, `math/MathNode.js`, `math/TriNoise3D.js`)
756// ---------------------------------------------------------------------------
757
758/// `hash( seed )` — `Hash.js`, the PCG hash from shadertoy XlGcRh, inlined:
759///
760/// ```ignore
761/// state = seed.toUint().mul( 747796405 ).add( 2891336453 )
762/// word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 )
763/// return word.shiftRight( 22 ).bitXor( word ).toFloat().mul( 1 / 2 ** 32 )
764/// ```
765pub fn hash(seed: impl Into<NodeRef>) -> NodeRef {
766    let state = seed.into().to_uint().mul(747796405u32).add(2891336453u32);
767    let word = state
768        .shift_right(state.shift_right(28u32).add(4u32))
769        .bit_xor(state.clone())
770        .mul(277803737u32);
771    word.shift_right(22u32)
772        .bit_xor(word)
773        .to_float()
774        .mul(1.0 / 4294967296.0)
775}
776
777/// `rand( uv )` — `MathNode.js`: `fract( sin( mod( dot( uv.xy, vec2(
778/// 12.9898, 78.233 ) ), PI ) ).mul( 43758.5453 ) )`, inlined.
779pub fn rand(uv: impl Into<NodeRef>) -> NodeRef {
780    let uv = uv.into();
781    // `uv.xy` of a `vec2` is `SplitNode` over the whole vector, which three
782    // generates as the vector itself.
783    let uv = if uv.ty() == Type::Vec2 { uv } else { uv.xy() };
784    let dt = super::dot(uv, constant(Type::Vec2, vec![12.9898, 78.233]));
785    let sn = mod_(dt, pi());
786    unary("fract", sn.sin().mul(43758.5453))
787}
788
789/// `tri( x )` — `TriNoise3D.js`, a layout `Fn` (`fn tri`).
790fn tri_def() -> Rc<FnDef> {
791    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
792    CELL.with(|c| {
793        c.get(|| {
794            shader_fn(Some("tri"), vec![("x", Type::F32)], Type::F32, |args| {
795                args[0].fract().sub(0.5).abs()
796            })
797        })
798    })
799}
800
801fn tri(x: NodeRef) -> NodeRef {
802    call(&tri_def(), vec![x])
803}
804
805/// `tri3( p )` — `TriNoise3D.js`, a layout `Fn` (`fn tri3`).
806fn tri3(p: NodeRef) -> NodeRef {
807    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
808    let def = CELL.with(|c| {
809        c.get(|| {
810            shader_fn(Some("tri3"), vec![("p", Type::Vec3)], Type::Vec3, |args| {
811                let p = &args[0];
812                join(
813                    Type::Vec3,
814                    vec![
815                        tri(p.z().add(tri(p.y().mul(1.0)))),
816                        tri(p.z().add(tri(p.x().mul(1.0)))),
817                        tri(p.y().add(tri(p.x().mul(1.0)))),
818                    ],
819                )
820            })
821        })
822    });
823    call(&def, vec![p])
824}
825
826/// `triNoise3D( position, speed, time )` — `TriNoise3D.js`
827/// (cabbibo's glsl-tri-noise-3d), a layout `Fn` emitted as `fn triNoise3D`
828/// with its float `Loop( { start: 0, end: 3, type: 'float', condition: '<='
829/// } )`.
830pub fn tri_noise_3d(
831    position: impl Into<NodeRef>,
832    speed: impl Into<NodeRef>,
833    time: impl Into<NodeRef>,
834) -> NodeRef {
835    thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
836    let def = CELL.with(|c| {
837        c.get(|| {
838            shader_fn(
839                Some("triNoise3D"),
840                vec![
841                    ("position", Type::Vec3),
842                    ("speed", Type::F32),
843                    ("time", Type::F32),
844                ],
845                Type::F32,
846                |args| {
847                    let (position, speed, time) = (&args[0], &args[1], &args[2]);
848                    let p = to_var(None, position.clone());
849                    let z = to_var(None, float(1.4));
850                    let rz = to_var(None, float(0.0));
851                    let bp = to_var(None, p.clone());
852                    let index = NodeRef::new(Node::Param {
853                        name: "i",
854                        ty: Type::F32,
855                    });
856                    let dg = to_var(None, tri3(bp.mul(2.0)));
857                    let t = to_var(None, tri(p.z().add(tri(p.x().add(tri(p.y()))))));
858                    let body = vec![
859                        dg.clone(),
860                        p.add_assign(dg.add(time.mul(float(0.1).mul(speed.clone())))),
861                        bp.mul_assign(1.8),
862                        z.mul_assign(1.5),
863                        p.mul_assign(1.2),
864                        t.clone(),
865                        rz.add_assign(t.div(z.clone())),
866                        bp.add_assign(0.14),
867                    ];
868                    let looped = NodeRef::new(Node::Loop {
869                        start: Some(float(0.0)),
870                        count: float(3.0),
871                        index,
872                        condition: "<=",
873                        update: None,
874                        body,
875                    });
876                    block(vec![p, z, rz.clone(), bp, looped], rz)
877                },
878            )
879        })
880    });
881    call(
882        &def,
883        vec![position.into().to(Type::Vec3), speed.into(), time.into()],
884    )
885}
886
887// ---------------------------------------------------------------------------
888// oscillators and uv utils (`utils/Oscillators.js`, `utils/UVUtils.js`)
889// ---------------------------------------------------------------------------
890
891/// `oscTriangle( t )` — `Oscillators.js`:
892/// `t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs()`. Three defaults `t` to
893/// `time`; pass [`super::time`] for that.
894pub fn osc_triangle(t: impl Into<NodeRef>) -> NodeRef {
895    t.into().add(0.5).fract().mul(2.0).sub(1.0).abs()
896}
897
898/// `oscSquare( t )` — `Oscillators.js`: `t.fract().round()`.
899pub fn osc_square(t: impl Into<NodeRef>) -> NodeRef {
900    unary("round", t.into().fract())
901}
902
903/// `oscSawtooth( t )` — `Oscillators.js`: `t.fract()`.
904pub fn osc_sawtooth(t: impl Into<NodeRef>) -> NodeRef {
905    t.into().fract()
906}
907
908/// `rotateUV( uv, rotation, center = vec2( 0.5 ) )` — `UVUtils.js`:
909/// `rotate( uv.sub( center ), rotation ).add( center )`.
910pub fn rotate_uv(uv: impl Into<NodeRef>, rotation: impl Into<NodeRef>) -> NodeRef {
911    rotate_uv_about(uv, rotation, constant(Type::Vec2, vec![0.5, 0.5]))
912}
913
914/// [`rotate_uv`] with an explicit `center`.
915pub fn rotate_uv_about(
916    uv: impl Into<NodeRef>,
917    rotation: impl Into<NodeRef>,
918    center: impl Into<NodeRef>,
919) -> NodeRef {
920    let center = center.into();
921    rotate(uv.into().sub(center.clone()), rotation).add(center)
922}
923
924/// `spherizeUV( uv, strength, center = vec2( 0.5 ) )` — `UVUtils.js`:
925/// `delta = uv - center; delta4 = dot( delta, delta )²; uv + delta *
926/// delta4 * strength`.
927pub fn spherize_uv(uv: impl Into<NodeRef>, strength: impl Into<NodeRef>) -> NodeRef {
928    spherize_uv_about(uv, strength, constant(Type::Vec2, vec![0.5, 0.5]))
929}
930
931/// [`spherize_uv`] with an explicit `center`.
932pub fn spherize_uv_about(
933    uv: impl Into<NodeRef>,
934    strength: impl Into<NodeRef>,
935    center: impl Into<NodeRef>,
936) -> NodeRef {
937    let uv = uv.into();
938    let delta = uv.sub(center);
939    let delta2 = delta.dot(delta.clone());
940    let delta4 = delta2.mul(delta2.clone());
941    let offset = delta4.mul(strength);
942    uv.add(delta.mul(offset))
943}
944
945/// `remap( node, inLow, inHigh, outLow = 0, outHigh = 1 )` — `Remap.js`:
946/// `node.sub( inLow ).div( inHigh.sub( inLow ) ).mul( outHigh.sub( outLow )
947/// ).add( outLow )`. Rust has no default arguments; pass `0.0, 1.0` for
948/// three's defaults, which is also what three emits for them.
949pub fn remap(
950    node: impl Into<NodeRef>,
951    in_low: impl Into<NodeRef>,
952    in_high: impl Into<NodeRef>,
953    out_low: impl Into<NodeRef>,
954    out_high: impl Into<NodeRef>,
955) -> NodeRef {
956    remap_impl(
957        node.into(),
958        in_low.into(),
959        in_high.into(),
960        out_low.into(),
961        out_high.into(),
962        false,
963    )
964}
965
966/// `remapClamp( … )` — `Remap.js`: [`remap`] with `t.clamp()` before the
967/// output range is applied.
968pub fn remap_clamp(
969    node: impl Into<NodeRef>,
970    in_low: impl Into<NodeRef>,
971    in_high: impl Into<NodeRef>,
972    out_low: impl Into<NodeRef>,
973    out_high: impl Into<NodeRef>,
974) -> NodeRef {
975    remap_impl(
976        node.into(),
977        in_low.into(),
978        in_high.into(),
979        out_low.into(),
980        out_high.into(),
981        true,
982    )
983}
984
985fn remap_impl(
986    node: NodeRef,
987    in_low: NodeRef,
988    in_high: NodeRef,
989    out_low: NodeRef,
990    out_high: NodeRef,
991    clamp: bool,
992) -> NodeRef {
993    let mut t = node.sub(in_low.clone()).div(in_high.sub(in_low));
994    if clamp {
995        t = t.clamp(0.0, 1.0);
996    }
997    t.mul(out_high.sub(out_low.clone())).add(out_low)
998}
999
1000// ---------------------------------------------------------------------------
1001// timers (`utils/Timer.js`)
1002// ---------------------------------------------------------------------------
1003
1004/// `deltaTime` — `Timer.js`' `uniform( 0 ).setGroup( renderGroup ).onRenderUpdate(
1005/// ( frame ) => frame.deltaTime )`: seconds since the previous frame.
1006pub fn delta_time() -> NodeRef {
1007    thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
1008    CELL.with(|c| {
1009        c.get(|| {
1010            uniform(
1011                UniformSource::DeltaTime,
1012                Type::F32,
1013                UniformGroup::Render,
1014                None,
1015            )
1016        })
1017    })
1018}
1019
1020/// `frameId` — `Timer.js`' `uniform( 0, 'uint' ).setGroup( renderGroup
1021/// ).onRenderUpdate( ( frame ) => frame.frameId )`.
1022pub fn frame_id() -> NodeRef {
1023    thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
1024    CELL.with(|c| {
1025        c.get(|| {
1026            uniform(
1027                UniformSource::FrameId,
1028                Type::U32,
1029                UniformGroup::Render,
1030                None,
1031            )
1032        })
1033    })
1034}
1035
1036// ---------------------------------------------------------------------------
1037// billboarding (`utils/SpriteUtils.js`)
1038// ---------------------------------------------------------------------------
1039
1040/// The options object `billboarding( { … } )` takes. `Default` is three's
1041/// defaults: `position: null, horizontal: true, vertical: false,
1042/// horizontalRotation: false`.
1043#[derive(Clone, Debug)]
1044#[non_exhaustive]
1045pub struct Billboarding {
1046    /// The billboard's center; `None` derives it from `positionWorld`.
1047    pub position: Option<NodeRef>,
1048    /// Whether to follow the camera rotation horizontally.
1049    pub horizontal: bool,
1050    /// Whether to follow the camera rotation vertically.
1051    pub vertical: bool,
1052    /// Whether to rotate around the Y axis to face the camera.
1053    pub horizontal_rotation: bool,
1054}
1055
1056impl Default for Billboarding {
1057    fn default() -> Self {
1058        Self {
1059            position: None,
1060            horizontal: true,
1061            vertical: false,
1062            horizontal_rotation: false,
1063        }
1064    }
1065}
1066
1067/// `billboarding( { position, horizontal, vertical, horizontalRotation } )` —
1068/// `SpriteUtils.js`: a clip-space position for a `vertexNode` that turns a
1069/// mesh's local axes toward the camera.
1070///
1071/// **Divergence, cosmetic** (`docs/nodes.md` §8): three assigns into the
1072/// `modelViewMatrix` operator node, which its builder turns into an inline
1073/// `var nodeVarN : mat4x4<f32> = …`; the port asks for the var explicitly,
1074/// so it is a `var<private>` assigned in the flow. Same value.
1075pub fn billboarding(options: Billboarding) -> NodeRef {
1076    let mw = model_world_matrix();
1077    let center = match options.position {
1078        Some(p) => p,
1079        None => position_world().sub(
1080            mw.mul(join(Type::Vec4, vec![position_geometry(), float(0.0)]))
1081                .xyz(),
1082        ),
1083    };
1084
1085    let mut statements = Vec::new();
1086    let world = to_var(None, mw.clone());
1087    let column = |m: &NodeRef, c: usize, v: &NodeRef, out: &mut Vec<NodeRef>| {
1088        out.push(m.element(c).element(0).assign(v.x()));
1089        out.push(m.element(c).element(1).assign(v.y()));
1090        out.push(m.element(c).element(2).assign(v.z()));
1091    };
1092    column(&world, 3, &center, &mut statements);
1093
1094    let model_view = to_var(None, camera_view_matrix().mul(world.clone()));
1095    let scale_x = mw.element(0).length();
1096    let scale_y = mw.element(1).length();
1097    let scale_z = mw.element(2).length();
1098
1099    let (right, up, forward);
1100    if options.horizontal_rotation {
1101        let look = camera_position().sub(world.element(3).xyz());
1102        let look_xz = join(Type::Vec3, vec![look.x(), float(0.0), look.z()]).normalize();
1103        let right_w = join(
1104            Type::Vec3,
1105            vec![look_xz.z(), float(0.0), look_xz.x().negate()],
1106        );
1107        right = Some(
1108            camera_view_matrix()
1109                .mul(join(Type::Vec4, vec![right_w, float(0.0)]))
1110                .xyz()
1111                .mul(scale_x),
1112        );
1113        up = Some(camera_view_matrix().element(1).xyz().mul(scale_y));
1114        forward = camera_view_matrix()
1115            .mul(join(Type::Vec4, vec![look_xz, float(0.0)]))
1116            .xyz()
1117            .mul(scale_z);
1118    } else {
1119        right = options
1120            .horizontal
1121            .then(|| join(Type::Vec3, vec![scale_x, float(0.0), float(0.0)]));
1122        up = options
1123            .vertical
1124            .then(|| join(Type::Vec3, vec![float(0.0), scale_y, float(0.0)]));
1125        forward = constant(Type::Vec3, vec![0.0, 0.0, 1.0]);
1126    }
1127    if let Some(right) = right {
1128        column(&model_view, 0, &right, &mut statements);
1129    }
1130    if let Some(up) = up {
1131        column(&model_view, 1, &up, &mut statements);
1132    }
1133    column(&model_view, 2, &forward, &mut statements);
1134
1135    let result = camera_projection_matrix()
1136        .mul(model_view)
1137        .mul(position_geometry());
1138    block(statements, result)
1139}
1140
1141// ---------------------------------------------------------------------------
1142// methods
1143// ---------------------------------------------------------------------------
1144
1145impl NodeRef {
1146    /// `x.toFloat()` — `TSLCore.js`' `addMethodChaining( 'toFloat', float )`.
1147    pub fn to_float(&self) -> NodeRef {
1148        self.to(Type::vector_of(Type::F32, 1))
1149    }
1150    /// `x.toInt()`.
1151    pub fn to_int(&self) -> NodeRef {
1152        self.to(Type::I32)
1153    }
1154    /// `x.toUint()`.
1155    pub fn to_uint(&self) -> NodeRef {
1156        self.to(Type::U32)
1157    }
1158    /// `x.toBool()`.
1159    pub fn to_bool(&self) -> NodeRef {
1160        self.to(Type::Bool)
1161    }
1162    /// `x.toVec2()`.
1163    pub fn to_vec2(&self) -> NodeRef {
1164        self.to(Type::Vec2)
1165    }
1166    /// `x.toVec3()`.
1167    pub fn to_vec3(&self) -> NodeRef {
1168        self.to(Type::Vec3)
1169    }
1170    /// `x.toVec4()`.
1171    pub fn to_vec4(&self) -> NodeRef {
1172        self.to(Type::Vec4)
1173    }
1174    /// `x.toColor()` — a `vec3`.
1175    pub fn to_color(&self) -> NodeRef {
1176        self.to(Type::Vec3)
1177    }
1178    /// `x.toIVec2()`.
1179    pub fn to_ivec2(&self) -> NodeRef {
1180        self.to(Type::IVec2)
1181    }
1182    /// `x.toIVec3()`.
1183    pub fn to_ivec3(&self) -> NodeRef {
1184        self.to(Type::IVec3)
1185    }
1186    /// `x.toIVec4()`.
1187    pub fn to_ivec4(&self) -> NodeRef {
1188        self.to(Type::IVec4)
1189    }
1190    /// `x.toUVec2()`.
1191    pub fn to_uvec2(&self) -> NodeRef {
1192        self.to(Type::UVec2)
1193    }
1194    /// `x.toUVec3()`.
1195    pub fn to_uvec3(&self) -> NodeRef {
1196        self.to(Type::UVec3)
1197    }
1198    /// `x.toUVec4()`.
1199    pub fn to_uvec4(&self) -> NodeRef {
1200        self.to(Type::UVec4)
1201    }
1202    /// `x.toBVec2()`.
1203    pub fn to_bvec2(&self) -> NodeRef {
1204        self.to(Type::BVec2)
1205    }
1206    /// `x.toBVec3()`.
1207    pub fn to_bvec3(&self) -> NodeRef {
1208        self.to(Type::BVec3)
1209    }
1210    /// `x.toBVec4()`.
1211    pub fn to_bvec4(&self) -> NodeRef {
1212        self.to(Type::BVec4)
1213    }
1214    /// `x.toMat2()`.
1215    pub fn to_mat2(&self) -> NodeRef {
1216        self.to(Type::Mat2)
1217    }
1218    /// `x.toMat3()` — from a `mat4`, `NodeBuilder.format()`'s column
1219    /// narrowing.
1220    pub fn to_mat3(&self) -> NodeRef {
1221        self.to(Type::Mat3)
1222    }
1223    /// `x.toMat4()`.
1224    pub fn to_mat4(&self) -> NodeRef {
1225        self.to(Type::Mat4)
1226    }
1227
1228    /// `x.atan()` — one-argument `MathNode.ATAN`.
1229    pub fn atan(&self) -> NodeRef {
1230        atan(self)
1231    }
1232    /// `x.acos()`.
1233    pub fn acos(&self) -> NodeRef {
1234        acos(self)
1235    }
1236    /// `x.tan()`.
1237    pub fn tan(&self) -> NodeRef {
1238        tan(self)
1239    }
1240    /// `x.sinh()`.
1241    pub fn sinh(&self) -> NodeRef {
1242        sinh(self)
1243    }
1244    /// `x.cosh()`.
1245    pub fn cosh(&self) -> NodeRef {
1246        cosh(self)
1247    }
1248    /// `x.tanh()`.
1249    pub fn tanh(&self) -> NodeRef {
1250        tanh(self)
1251    }
1252    /// `x.asinh()`.
1253    pub fn asinh(&self) -> NodeRef {
1254        asinh(self)
1255    }
1256    /// `x.acosh()`.
1257    pub fn acosh(&self) -> NodeRef {
1258        acosh(self)
1259    }
1260    /// `x.atanh()`.
1261    pub fn atanh(&self) -> NodeRef {
1262        atanh(self)
1263    }
1264    /// `x.round()`.
1265    pub fn round(&self) -> NodeRef {
1266        round(self)
1267    }
1268    /// `x.trunc()`.
1269    pub fn trunc(&self) -> NodeRef {
1270        trunc(self)
1271    }
1272    /// `x.degrees()`.
1273    pub fn degrees(&self) -> NodeRef {
1274        degrees(self)
1275    }
1276    /// `x.radians()`.
1277    pub fn radians(&self) -> NodeRef {
1278        radians(self)
1279    }
1280    /// `m.determinant()`.
1281    pub fn determinant(&self) -> NodeRef {
1282        determinant(self)
1283    }
1284    /// `m.inverse()`.
1285    pub fn inverse(&self) -> NodeRef {
1286        inverse(self)
1287    }
1288    /// `m.transpose()`.
1289    pub fn transpose(&self) -> NodeRef {
1290        transpose(self)
1291    }
1292    /// `x.pow2()`.
1293    pub fn pow2(&self) -> NodeRef {
1294        pow2(self)
1295    }
1296    /// `x.pow4()`.
1297    pub fn pow4(&self) -> NodeRef {
1298        pow4(self)
1299    }
1300    /// `a.difference( b )`.
1301    pub fn difference(&self, b: impl Into<NodeRef>) -> NodeRef {
1302        difference(self, b)
1303    }
1304    /// `x.cbrt()`.
1305    pub fn cbrt(&self) -> NodeRef {
1306        cbrt(self)
1307    }
1308    /// `a.lengthSq()`.
1309    pub fn length_sq(&self) -> NodeRef {
1310        length_sq(self)
1311    }
1312    /// `v.length()` — `MathNode.LENGTH`.
1313    pub fn length(&self) -> NodeRef {
1314        super::length(self)
1315    }
1316    /// `n.faceForward( i, nref )`.
1317    pub fn face_forward(&self, i: impl Into<NodeRef>, nref: impl Into<NodeRef>) -> NodeRef {
1318        face_forward(self, i, nref)
1319    }
1320    /// `b.all()` — `MathNode.ALL`, see [`super::all`].
1321    pub fn all(&self) -> NodeRef {
1322        super::all(self)
1323    }
1324    /// `b.any()` — `MathNode.ANY`, see [`any`].
1325    pub fn any(&self) -> NodeRef {
1326        any(self)
1327    }
1328    /// `n.transformNormalByViewMatrix( viewMatrix )`.
1329    pub fn transform_normal_by_view_matrix(&self, view_matrix: impl Into<NodeRef>) -> NodeRef {
1330        transform_normal_by_view_matrix(self, view_matrix)
1331    }
1332    /// `n.transformNormal( matrix )` — see [`transform_normal`]. Three's
1333    /// `matrix` defaults to `modelWorldMatrix`; pass `model_world_matrix()`
1334    /// for its no-argument form.
1335    pub fn transform_normal(&self, matrix: impl Into<NodeRef>) -> NodeRef {
1336        transform_normal(self, matrix)
1337    }
1338    /// `n.transformNormalByInverseViewMatrix( viewMatrix )`.
1339    pub fn transform_normal_by_inverse_view_matrix(
1340        &self,
1341        view_matrix: impl Into<NodeRef>,
1342    ) -> NodeRef {
1343        transform_normal_by_inverse_view_matrix(self, view_matrix)
1344    }
1345    /// `a.xor( b )`.
1346    pub fn xor(&self, b: impl Into<NodeRef>) -> NodeRef {
1347        xor(self, b)
1348    }
1349    /// `a.bitNot()`.
1350    pub fn bit_not(&self) -> NodeRef {
1351        bit_not(self)
1352    }
1353    /// `x.countOneBits()`.
1354    pub fn count_one_bits(&self) -> NodeRef {
1355        count_one_bits(self)
1356    }
1357    /// `x.countTrailingZeros()`.
1358    pub fn count_trailing_zeros(&self) -> NodeRef {
1359        count_trailing_zeros(self)
1360    }
1361    /// `x.countLeadingZeros()`.
1362    pub fn count_leading_zeros(&self) -> NodeRef {
1363        count_leading_zeros(self)
1364    }
1365    /// `a.mod( b )` — see [`mod_`].
1366    pub fn mod_(&self, b: impl Into<NodeRef>) -> NodeRef {
1367        mod_(self, b)
1368    }
1369    /// `x.hash()`.
1370    pub fn hash(&self) -> NodeRef {
1371        hash(self)
1372    }
1373    /// `x.remap( inLow, inHigh, outLow, outHigh )` — `Remap.js`'
1374    /// `addMethodChaining( 'remap', remap )`.
1375    pub fn remap(
1376        &self,
1377        in_low: impl Into<NodeRef>,
1378        in_high: impl Into<NodeRef>,
1379        out_low: impl Into<NodeRef>,
1380        out_high: impl Into<NodeRef>,
1381    ) -> NodeRef {
1382        remap(self, in_low, in_high, out_low, out_high)
1383    }
1384    /// `x.remapClamp( inLow, inHigh, outLow, outHigh )`.
1385    pub fn remap_clamp(
1386        &self,
1387        in_low: impl Into<NodeRef>,
1388        in_high: impl Into<NodeRef>,
1389        out_low: impl Into<NodeRef>,
1390        out_high: impl Into<NodeRef>,
1391    ) -> NodeRef {
1392        remap_clamp(self, in_low, in_high, out_low, out_high)
1393    }
1394    /// `x.smoothstep( low, high )` — `MathNode.js`' `smoothstepElement`:
1395    /// `smoothstep( low, high, x )`.
1396    pub fn smoothstep(&self, low: impl Into<NodeRef>, high: impl Into<NodeRef>) -> NodeRef {
1397        super::smoothstep(low, high, self)
1398    }
1399    /// `x.step( edge )` — `MathNode.js`' `stepElement`: `step( edge, x )`.
1400    pub fn step(&self, edge: impl Into<NodeRef>) -> NodeRef {
1401        super::step(edge, self)
1402    }
1403}
1404
1405/// `MathNode.getInputType()` for callers elsewhere in `tsl`.
1406pub(super) fn math_input_type(args: &[&NodeRef]) -> Type {
1407    input_type(args)
1408}