1use 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
24fn 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
48fn 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
57fn unary(name: &'static str, x: NodeRef) -> NodeRef {
59 let ty = x.ty();
60 math(name, vec![x], ty)
61}
62
63fn 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
105pub fn color(hex: u32) -> NodeRef {
113 Color::from_hex(hex).into()
114}
115
116pub fn color_rgb(r: f64, g: f64, b: f64) -> NodeRef {
119 constant(Type::Vec3, vec![r, g, b])
120}
121
122pub 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, Type::UVec2, x, y
139);
140vector_ctor!(
141 uvec3, Type::UVec3, x, y, z
143);
144vector_ctor!(
145 uvec4, Type::UVec4, x, y, z, w
147);
148vector_ctor!(
149 ivec3, Type::IVec3, x, y, z
151);
152vector_ctor!(
153 ivec4, Type::IVec4, x, y, z, w
155);
156vector_ctor!(
157 bvec2, Type::BVec2, x, y
159);
160vector_ctor!(
161 bvec3, Type::BVec3, x, y, z
163);
164vector_ctor!(
165 bvec4, Type::BVec4, x, y, z, w
167);
168
169pub fn mat2(m: Matrix2) -> NodeRef {
175 constant(Type::Mat2, m.elements.to_vec())
176}
177
178pub fn mat3(m: Matrix3) -> NodeRef {
180 constant(Type::Mat3, m.elements.to_vec())
181}
182
183pub fn mat4(m: Matrix4) -> NodeRef {
185 constant(Type::Mat4, m.elements.to_vec())
186}
187
188pub fn mat2_join(args: Vec<NodeRef>) -> NodeRef {
190 convert_type(Type::Mat2, args)
191}
192
193pub fn mat3_join(args: Vec<NodeRef>) -> NodeRef {
196 convert_type(Type::Mat3, args)
197}
198
199pub fn mat4_join(args: Vec<NodeRef>) -> NodeRef {
201 convert_type(Type::Mat4, args)
202}
203
204pub fn pi() -> NodeRef {
210 float(std::f64::consts::PI)
211}
212
213pub fn pi2() -> NodeRef {
216 float(std::f64::consts::TAU)
217}
218
219pub fn half_pi() -> NodeRef {
221 float(std::f64::consts::FRAC_PI_2)
222}
223
224pub fn epsilon() -> NodeRef {
226 float(1e-6)
227}
228
229pub fn infinity() -> NodeRef {
232 float(1e6)
233}
234
235macro_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, "atan"
252);
253unary_math!(
254 acos, "acos"
256);
257unary_math!(
258 asin, "asin"
260);
261unary_math!(
262 tan, "tan"
264);
265unary_math!(
266 sinh, "sinh"
268);
269unary_math!(
270 cosh, "cosh"
272);
273unary_math!(
274 tanh, "tanh"
276);
277unary_math!(
278 asinh, "asinh"
280);
281unary_math!(
282 acosh, "acosh"
284);
285unary_math!(
286 atanh, "atanh"
288);
289unary_math!(
290 round, "round"
292);
293unary_math!(
294 trunc, "trunc"
296);
297unary_math!(
298 degrees, "degrees"
300);
301unary_math!(
302 radians, "radians"
304);
305unary_math!(
306 transpose, "transpose"
308);
309unary_math!(
310 count_one_bits, "countOneBits"
313);
314unary_math!(
315 count_trailing_zeros, "countTrailingZeros"
317);
318unary_math!(
319 count_leading_zeros, "countLeadingZeros"
321);
322
323pub fn determinant(m: impl Into<NodeRef>) -> NodeRef {
325 math("determinant", vec![m.into()], Type::F32)
326}
327
328pub 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
342fn pow_of(a: NodeRef, b: NodeRef) -> NodeRef {
348 let ty = input_type(&[&a, &b]);
349 math("pow", vec![a, b], ty)
350}
351
352pub fn pow2(x: impl Into<NodeRef>) -> NodeRef {
354 let x = x.into();
355 x.mul(x.clone())
356}
357
358pub fn pow3(x: impl Into<NodeRef>) -> NodeRef {
360 x.into().pow3()
361}
362
363pub fn pow4(x: impl Into<NodeRef>) -> NodeRef {
365 let x = x.into();
366 x.mul(x.clone()).mul(x.clone()).mul(x)
367}
368
369pub fn difference(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
371 let d = a.into().sub(b);
372 unary("abs", d)
373}
374
375pub 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
381pub fn length_sq(a: impl Into<NodeRef>) -> NodeRef {
383 let a = a.into();
384 super::dot(a.clone(), a)
385}
386
387pub 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
398pub 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
405pub 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
415pub 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
425pub 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
435pub 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
446pub fn inversesqrt(x: impl Into<NodeRef>) -> NodeRef {
450 super::inverse_sqrt(x)
451}
452
453pub fn any(x: impl Into<NodeRef>) -> NodeRef {
456 math("any", vec![x.into()], Type::Bool)
457}
458
459pub 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
471pub 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
488pub 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
509pub 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
521fn float_packing(builtin: &'static str, x: impl Into<NodeRef>, ty: Type) -> NodeRef {
531 math(builtin, vec![x.into()], ty)
532}
533
534pub fn pack_snorm_2x16(v: impl Into<NodeRef>) -> NodeRef {
537 float_packing("pack2x16snorm", v, Type::U32)
538}
539
540pub fn pack_unorm_2x16(v: impl Into<NodeRef>) -> NodeRef {
542 float_packing("pack2x16unorm", v, Type::U32)
543}
544
545pub fn pack_half_2x16(v: impl Into<NodeRef>) -> NodeRef {
548 float_packing("pack2x16float", v, Type::U32)
549}
550
551pub fn pack_snorm_4x8(v: impl Into<NodeRef>) -> NodeRef {
554 float_packing("pack4x8snorm", v, Type::U32)
555}
556
557pub fn pack_unorm_4x8(v: impl Into<NodeRef>) -> NodeRef {
560 float_packing("pack4x8unorm", v, Type::U32)
561}
562
563pub fn unpack_snorm_2x16(u: impl Into<NodeRef>) -> NodeRef {
566 float_packing("unpack2x16snorm", u, Type::Vec2)
567}
568
569pub fn unpack_unorm_2x16(u: impl Into<NodeRef>) -> NodeRef {
572 float_packing("unpack2x16unorm", u, Type::Vec2)
573}
574
575pub fn unpack_half_2x16(u: impl Into<NodeRef>) -> NodeRef {
578 float_packing("unpack2x16float", u, Type::Vec2)
579}
580
581pub fn unpack_snorm_4x8(u: impl Into<NodeRef>) -> NodeRef {
584 float_packing("unpack4x8snorm", u, Type::Vec4)
585}
586
587pub fn unpack_unorm_4x8(u: impl Into<NodeRef>) -> NodeRef {
590 float_packing("unpack4x8unorm", u, Type::Vec4)
591}
592
593fn packed_4x8(method: &'static str, args: Vec<NodeRef>, ty: Type) -> NodeRef {
603 math(method, args, ty)
604}
605
606pub 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
612pub 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
618pub fn pack_4x_i8(v: impl Into<NodeRef>) -> NodeRef {
620 packed_4x8("pack4xI8", vec![v.into()], Type::U32)
621}
622
623pub fn pack_4x_u8(v: impl Into<NodeRef>) -> NodeRef {
625 packed_4x8("pack4xU8", vec![v.into()], Type::U32)
626}
627
628pub fn pack_4x_i8_clamp(v: impl Into<NodeRef>) -> NodeRef {
631 packed_4x8("pack4xI8Clamp", vec![v.into()], Type::U32)
632}
633
634pub fn pack_4x_u8_clamp(v: impl Into<NodeRef>) -> NodeRef {
637 packed_4x8("pack4xU8Clamp", vec![v.into()], Type::U32)
638}
639
640pub fn unpack_4x_i8(u: impl Into<NodeRef>) -> NodeRef {
642 packed_4x8("unpack4xI8", vec![u.into()], Type::IVec4)
643}
644
645pub fn unpack_4x_u8(u: impl Into<NodeRef>) -> NodeRef {
647 packed_4x8("unpack4xU8", vec![u.into()], Type::UVec4)
648}
649
650pub fn xor(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
657 math("tsl_xor", vec![a.into(), b.into()], Type::Bool)
658}
659
660pub 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
667fn 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
689pub fn float_bits_to_int(x: impl Into<NodeRef>) -> NodeRef {
691 bitcast(x.into(), Type::I32)
692}
693
694pub fn float_bits_to_uint(x: impl Into<NodeRef>) -> NodeRef {
696 bitcast(x.into(), Type::U32)
697}
698
699pub fn int_bits_to_float(x: impl Into<NodeRef>) -> NodeRef {
701 bitcast(x.into(), Type::F32)
702}
703
704pub fn uint_bits_to_float(x: impl Into<NodeRef>) -> NodeRef {
706 bitcast(x.into(), Type::F32)
707}
708
709pub 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
716pub 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
723pub fn increment_before(a: &NodeRef) -> NodeRef {
725 block(vec![a.add_assign(1)], a.clone())
726}
727
728pub fn decrement_before(a: &NodeRef) -> NodeRef {
730 block(vec![a.sub_assign(1)], a.clone())
731}
732
733pub 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
754pub 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
777pub fn rand(uv: impl Into<NodeRef>) -> NodeRef {
780 let uv = uv.into();
781 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
789fn 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
805fn 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
826pub 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
887pub fn osc_triangle(t: impl Into<NodeRef>) -> NodeRef {
895 t.into().add(0.5).fract().mul(2.0).sub(1.0).abs()
896}
897
898pub fn osc_square(t: impl Into<NodeRef>) -> NodeRef {
900 unary("round", t.into().fract())
901}
902
903pub fn osc_sawtooth(t: impl Into<NodeRef>) -> NodeRef {
905 t.into().fract()
906}
907
908pub 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
914pub 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
924pub 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
931pub 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
945pub 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
966pub 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
1000pub 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
1020pub 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#[derive(Clone, Debug)]
1044#[non_exhaustive]
1045pub struct Billboarding {
1046 pub position: Option<NodeRef>,
1048 pub horizontal: bool,
1050 pub vertical: bool,
1052 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
1067pub 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, ¢er, &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
1141impl NodeRef {
1146 pub fn to_float(&self) -> NodeRef {
1148 self.to(Type::vector_of(Type::F32, 1))
1149 }
1150 pub fn to_int(&self) -> NodeRef {
1152 self.to(Type::I32)
1153 }
1154 pub fn to_uint(&self) -> NodeRef {
1156 self.to(Type::U32)
1157 }
1158 pub fn to_bool(&self) -> NodeRef {
1160 self.to(Type::Bool)
1161 }
1162 pub fn to_vec2(&self) -> NodeRef {
1164 self.to(Type::Vec2)
1165 }
1166 pub fn to_vec3(&self) -> NodeRef {
1168 self.to(Type::Vec3)
1169 }
1170 pub fn to_vec4(&self) -> NodeRef {
1172 self.to(Type::Vec4)
1173 }
1174 pub fn to_color(&self) -> NodeRef {
1176 self.to(Type::Vec3)
1177 }
1178 pub fn to_ivec2(&self) -> NodeRef {
1180 self.to(Type::IVec2)
1181 }
1182 pub fn to_ivec3(&self) -> NodeRef {
1184 self.to(Type::IVec3)
1185 }
1186 pub fn to_ivec4(&self) -> NodeRef {
1188 self.to(Type::IVec4)
1189 }
1190 pub fn to_uvec2(&self) -> NodeRef {
1192 self.to(Type::UVec2)
1193 }
1194 pub fn to_uvec3(&self) -> NodeRef {
1196 self.to(Type::UVec3)
1197 }
1198 pub fn to_uvec4(&self) -> NodeRef {
1200 self.to(Type::UVec4)
1201 }
1202 pub fn to_bvec2(&self) -> NodeRef {
1204 self.to(Type::BVec2)
1205 }
1206 pub fn to_bvec3(&self) -> NodeRef {
1208 self.to(Type::BVec3)
1209 }
1210 pub fn to_bvec4(&self) -> NodeRef {
1212 self.to(Type::BVec4)
1213 }
1214 pub fn to_mat2(&self) -> NodeRef {
1216 self.to(Type::Mat2)
1217 }
1218 pub fn to_mat3(&self) -> NodeRef {
1221 self.to(Type::Mat3)
1222 }
1223 pub fn to_mat4(&self) -> NodeRef {
1225 self.to(Type::Mat4)
1226 }
1227
1228 pub fn atan(&self) -> NodeRef {
1230 atan(self)
1231 }
1232 pub fn acos(&self) -> NodeRef {
1234 acos(self)
1235 }
1236 pub fn tan(&self) -> NodeRef {
1238 tan(self)
1239 }
1240 pub fn sinh(&self) -> NodeRef {
1242 sinh(self)
1243 }
1244 pub fn cosh(&self) -> NodeRef {
1246 cosh(self)
1247 }
1248 pub fn tanh(&self) -> NodeRef {
1250 tanh(self)
1251 }
1252 pub fn asinh(&self) -> NodeRef {
1254 asinh(self)
1255 }
1256 pub fn acosh(&self) -> NodeRef {
1258 acosh(self)
1259 }
1260 pub fn atanh(&self) -> NodeRef {
1262 atanh(self)
1263 }
1264 pub fn round(&self) -> NodeRef {
1266 round(self)
1267 }
1268 pub fn trunc(&self) -> NodeRef {
1270 trunc(self)
1271 }
1272 pub fn degrees(&self) -> NodeRef {
1274 degrees(self)
1275 }
1276 pub fn radians(&self) -> NodeRef {
1278 radians(self)
1279 }
1280 pub fn determinant(&self) -> NodeRef {
1282 determinant(self)
1283 }
1284 pub fn inverse(&self) -> NodeRef {
1286 inverse(self)
1287 }
1288 pub fn transpose(&self) -> NodeRef {
1290 transpose(self)
1291 }
1292 pub fn pow2(&self) -> NodeRef {
1294 pow2(self)
1295 }
1296 pub fn pow4(&self) -> NodeRef {
1298 pow4(self)
1299 }
1300 pub fn difference(&self, b: impl Into<NodeRef>) -> NodeRef {
1302 difference(self, b)
1303 }
1304 pub fn cbrt(&self) -> NodeRef {
1306 cbrt(self)
1307 }
1308 pub fn length_sq(&self) -> NodeRef {
1310 length_sq(self)
1311 }
1312 pub fn length(&self) -> NodeRef {
1314 super::length(self)
1315 }
1316 pub fn face_forward(&self, i: impl Into<NodeRef>, nref: impl Into<NodeRef>) -> NodeRef {
1318 face_forward(self, i, nref)
1319 }
1320 pub fn all(&self) -> NodeRef {
1322 super::all(self)
1323 }
1324 pub fn any(&self) -> NodeRef {
1326 any(self)
1327 }
1328 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 pub fn transform_normal(&self, matrix: impl Into<NodeRef>) -> NodeRef {
1336 transform_normal(self, matrix)
1337 }
1338 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 pub fn xor(&self, b: impl Into<NodeRef>) -> NodeRef {
1347 xor(self, b)
1348 }
1349 pub fn bit_not(&self) -> NodeRef {
1351 bit_not(self)
1352 }
1353 pub fn count_one_bits(&self) -> NodeRef {
1355 count_one_bits(self)
1356 }
1357 pub fn count_trailing_zeros(&self) -> NodeRef {
1359 count_trailing_zeros(self)
1360 }
1361 pub fn count_leading_zeros(&self) -> NodeRef {
1363 count_leading_zeros(self)
1364 }
1365 pub fn mod_(&self, b: impl Into<NodeRef>) -> NodeRef {
1367 mod_(self, b)
1368 }
1369 pub fn hash(&self) -> NodeRef {
1371 hash(self)
1372 }
1373 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 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 pub fn smoothstep(&self, low: impl Into<NodeRef>, high: impl Into<NodeRef>) -> NodeRef {
1397 super::smoothstep(low, high, self)
1398 }
1399 pub fn step(&self, edge: impl Into<NodeRef>) -> NodeRef {
1401 super::step(edge, self)
1402 }
1403}
1404
1405pub(super) fn math_input_type(args: &[&NodeRef]) -> Type {
1407 input_type(args)
1408}