1//! Procedural and environment 3D textures: `TexGradient`, `FastNoiseTexture3D`, `SphereMap` and
2//! `CubeMap`.
3
4use super::collect::{euler_matrix, ResolvedMaterial};
5use super::fx::{gradient_lut, proc_kind, SurfaceFx};
6use super::materials::{flat, Resolve};
7use super::MaterialFx;
8use model::{Comp, ExprEngine, Node};
9
10pub(super) fn tex_gradient(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> ResolvedMaterial {
11 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
12 let kind = match n.static_str("GradientType") {
13 Some("Reflect") => 1.0,
14 Some("Square") => 2.0,
15 Some("Cross") => 3.0,
16 Some("Radial") => 4.0,
17 _ => 0.0,
18 };
19 let repeat = match n.static_str("Repeat") {
20 Some("Repeat") => 1.0,
21 Some("Ping-Pong") => 2.0,
22 _ => 0.0,
23 };
24 let scale = f("Scale", 1.0);
25 let mut mat = flat([1.0; 4]);
26 mat.fx.sfx.proc_a = [proc_kind::GRADIENT, kind, if scale.abs() < 1e-6 { 1e-6 } else { scale }, f("Offset", 0.0)];
27 mat.fx.sfx.proc_b = [repeat, 0.0, 0.0, 0.0];
28 mat.fx.sfx.lut = gradient_lut(comp.eval_gradient(n, "Gradient", time), [[0.0, 0.0, 0.0, 1.0], [1.0; 4]]);
29 mat
30}
31
32/// `FastNoiseTexture3D` over mesh UVW; `ThreeD` output differs only along W, which primitives
33/// leave at 0. A `SourceMaterial` texture is scaled by the noise.
34pub(super) fn fast_noise(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial {
35 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
36 let source = n.connected_node("SourceMaterial").and_then(|s| comp.find_node(s)).map(&mut *resolve);
37 let mut mat = flat([1.0; 4]);
38 if let Some(src) = source {
39 mat.tex_node = src.tex_node;
40 mat.fx.uv = src.fx.uv;
41 mat.fx.uv_wrap = src.fx.uv_wrap;
42 }
43 // Unlike 2D `FastNoise`, `SeetheRate` is per frame without the 0.1 factor.
44 let seethe = f("Seethe", 1.0) + f("SeetheRate", 0.0) * time as f32;
45 mat.fx.sfx.proc_a = [proc_kind::NOISE, f("Detail", 2.0), f("XScale", 1.0), seethe];
46 mat.fx.sfx.proc_b = [f("Contrast", 1.0), f("Brightness", 0.0), f("Invert", 0.0), f("Discontinuous", 0.0)];
47 mat
48}
49
50/// Column-major `R^T` of the node's `Rotate.*`: rotating the environment by `R` samples world
51/// directions through its inverse.
52fn env_rotation(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> [f32; 9] {
53 let rot_deg = ["X", "Y", "Z"].map(|a| comp.eval_number(n, &format!("Rotate.{a}"), time, 0.0, expr) as f32);
54 let r = euler_matrix(rot_deg, n.static_str("Rotate.RotOrder").unwrap_or("XYZ"));
55 [r[0], r[4], r[8], r[1], r[5], r[9], r[2], r[6], r[10]]
56}
57
58fn env_material(tex_node: Option<model::NodeId>, env_rot: [f32; 9], env_map_mode: u32, coord_space: f32) -> ResolvedMaterial {
59 ResolvedMaterial {
60 tex_node,
61 fx: MaterialFx {
62 env_mode: 1,
63 env_map_mode,
64 env_tex_slot: u32::from(tex_node.is_some()),
65 env_rot,
66 sfx: SurfaceFx { env: [coord_space, 0.0, 0.0, 0.0], ..SurfaceFx::default() },
67 ..MaterialFx::default()
68 },
69 ..flat([1.0; 4])
70 }
71}
72
73/// `SphereMap` along the view ray. `StartAngle`/`EndAngle` have no effect in Fusion's renderer.
74pub(super) fn sphere_map(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial {
75 let tex = n.connected_node("Image").and_then(|s| comp.find_node(s)).and_then(|id| resolve(id).tex_node);
76 let map_mode = comp.eval_number(n, "MapMode", time, 0.0, expr).round().clamp(0.0, 1.0) as u32;
77 env_material(tex, env_rotation(comp, n, time, expr), map_mode, 0.0)
78}
79
80/// `CubeMap` from a vertical (`Layout` 1) or horizontal (2) cross, or separate faces (0).
81/// `Convention` does not change Fusion's render.
82pub(super) fn cube_map(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial {
83 let env_rot = env_rotation(comp, n, time, expr);
84 let layout = comp.eval_number(n, "Layout", time, 1.0, expr).round() as i32;
85 let (input, mode) = match layout {
86 // Two texture slots cannot hold six faces, so separate images bind the face that the
87 // rotated forward (-Z) view direction sees.
88 0 => {
89 let fwd = [-env_rot[6], -env_rot[7], -env_rot[8]];
90 let axis = (0..3).max_by(|&a, &b| fwd[a].abs().total_cmp(&fwd[b].abs())).unwrap_or(2);
91 let sign = if fwd[axis] > 0.0 { "Positive" } else { "Negative" };
92 (format!("{sign}{}", ["X", "Y", "Z"][axis]), 4)
93 }
94 2 => ("CrossImage".to_string(), 3),
95 _ => ("CrossImage".to_string(), 2),
96 };
97 let tex = n.connected_node(&input).and_then(|s| comp.find_node(s)).and_then(|id| resolve(id).tex_node);
98 let coord_space = match n.static_str("CoordSystem") {
99 Some("Model") => 1.0,
100 Some("Camera") => 2.0,
101 _ => 0.0,
102 };
103 env_material(tex, env_rot, mode, coord_space)
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109 use crate::scene3d::collect::resolve_test_material as resolve_in;
110
111 #[test]
112 fn tex_gradient_maps_type_repeat_and_default_ramp() {
113 let mat = resolve_in(
114 "X = TexGradient { Inputs = { GradientType = Input { Value = FuID { \"Radial\" }, },
115 Repeat = Input { Value = FuID { \"Ping-Pong\" }, }, Scale = Input { Value = 2, }, Offset = Input { Value = 0.25, }, }, },",
116 );
117 assert!(mat.unlit);
118 assert_eq!(mat.fx.sfx.proc_a, [proc_kind::GRADIENT, 4.0, 2.0, 0.25]);
119 assert_eq!(mat.fx.sfx.proc_b[0], 2.0);
120 assert_eq!(mat.fx.sfx.lut[0], [0.0, 0.0, 0.0, 1.0]);
121 assert_eq!(mat.fx.sfx.lut[15], [1.0; 4]);
122 }
123
124 #[test]
125 fn fast_noise_reads_fbm_params_and_source() {
126 let mat = resolve_in(
127 "Img = Background { },
128 X = FastNoiseTexture3D { Inputs = { Detail = Input { Value = 3, }, XScale = Input { Value = 4, },
129 Contrast = Input { Value = 2, }, Invert = Input { Value = 1, }, Discontinuous = Input { Value = 1, },
130 SourceMaterial = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },",
131 );
132 assert!(mat.tex_node.is_some());
133 assert_eq!(mat.fx.sfx.proc_a, [proc_kind::NOISE, 3.0, 4.0, 1.0]);
134 assert_eq!(mat.fx.sfx.proc_b, [2.0, 0.0, 1.0, 1.0]);
135 }
136
137 #[test]
138 fn fast_noise_seethe_rate_advances_per_frame() {
139 let comp = Comp::from_fusion_str(&crate::scene3d::collect::comp_src(
140 "X = FastNoiseTexture3D { Inputs = { Seethe = Input { Value = 0.5, }, SeetheRate = Input { Value = 0.25, }, }, },",
141 ))
142 .expect("parse comp");
143 let n = comp.node(comp.find_node("X").expect("X"));
144 let mat = fast_noise(&comp, n, 4.0, &ExprEngine::new(), &mut |_| ResolvedMaterial::default());
145 assert_eq!(mat.fx.sfx.proc_a[3], 1.5);
146 }
147
148 #[test]
149 fn sphere_map_ignores_start_end_angles_and_transposes_rotation() {
150 let mat = resolve_in(
151 "Img = Background { },
152 X = SphereMap { Inputs = { [\"Rotate.Y\"] = Input { Value = 90, }, MapMode = Input { Value = 1, },
153 StartAngle = Input { Value = 30, }, Image = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },",
154 );
155 assert_eq!((mat.fx.env_mode, mat.fx.env_map_mode, mat.fx.env_tex_slot), (1, 1, 1));
156 // R_y(90) maps +X to -Z, so R^T's first column is (0, 0, 1).
157 let c0 = &mat.fx.env_rot[0..3];
158 assert!(c0[0].abs() < 1e-6 && (c0[2] - 1.0).abs() < 1e-6, "{c0:?}");
159 }
160
161 #[test]
162 fn cube_map_layouts_and_separate_face_choice() {
163 let cross = resolve_in(
164 "Img = Background { },
165 X = CubeMap { Inputs = { Layout = Input { Value = 2, }, CoordSystem = Input { Value = FuID { \"Model\" }, },
166 CrossImage = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },",
167 );
168 assert_eq!((cross.fx.env_map_mode, cross.fx.env_tex_slot), (3, 1));
169 assert_eq!(cross.fx.sfx.env[0], 1.0);
170 let faces = "PX = Background { }, NZ = Background { },
171 X = CubeMap { Inputs = { Layout = Input { Value = 0, }, [\"Rotate.Y\"] = Input { Value = ROT, },
172 PositiveX = Input { SourceOp = \"PX\", Source = \"Output\", },
173 NegativeZ = Input { SourceOp = \"NZ\", Source = \"Output\", }, }, },";
174 let front = resolve_in(&faces.replace("ROT", "0"));
175 let turned = resolve_in(&faces.replace("ROT", "90"));
176 assert_eq!(front.fx.env_map_mode, 4);
177 assert!(front.tex_node.is_some() && turned.tex_node.is_some());
178 assert_ne!(front.tex_node, turned.tex_node, "rotating the map brings +X to the front");
179 }
180}