1//! Material operators layered on `ResolvedMaterial`: `MtlMerge3D`, `MtlPBRUber`,
2//! `MtlStereoMix3D`, `FalloffOperator`, `TexCatcher`, and the secondary-layer plumbing shared with
3//! `MtlChanBool`.
4
5use super::collect::ResolvedMaterial;
6use super::fx::{gradient_lut, layer_mode, SurfaceFx};
7use super::{MaterialFx, SpecModel};
8use model::{Comp, ExprEngine, Node, NodeId};
9
10pub(super) type Resolve<'a> = dyn FnMut(NodeId) -> ResolvedMaterial + 'a;
11
12/// A material operator's own input: a bare image there renders flat, as Fusion shows it.
13pub(super) fn material_input(comp: &Comp, n: &Node, input: &str, resolve: &mut Resolve) -> Option<ResolvedMaterial> {
14 let id = n.connected_node(input).and_then(|s| comp.find_node(s))?;
15 let mut m = resolve(id);
16 m.unlit |= !m.has_material_shader;
17 Some(m)
18}
19
20/// Flat colour standing in for an unwired material input.
21pub(super) fn flat(rgba: [f32; 4]) -> ResolvedMaterial {
22 ResolvedMaterial { diffuse_col: rgba, unlit: true, has_material_shader: true, ..ResolvedMaterial::default() }
23}
24
25/// Stores `layer` as the secondary material of `base`; its texture takes the bump slot when free.
26pub(super) fn set_layer(base: &mut ResolvedMaterial, layer: &ResolvedMaterial, mode: f32, amount: f32) {
27 let tex_slot = match layer.tex_node.filter(|_| !layer.fx.bump_only) {
28 Some(tex) if base.bump_node.is_none() && base.fx.env_tex_slot != 2 => {
29 base.bump_node = Some(tex);
30 base.fx.bump_wrap = layer.fx.uv_wrap;
31 2.0
32 }
33 _ => 0.0,
34 };
35 let [r, g, b, a] = layer.diffuse_col;
36 let [sr, sg, sb] = layer.specular_col;
37 let sfx = &mut base.fx.sfx;
38 sfx.layer = [mode, amount, if layer.unlit { 0.0 } else { 1.0 }, tex_slot];
39 sfx.layer_col = [r, g, b, a * layer.fx.diffuse_color_alpha];
40 sfx.layer_spec = [sr, sg, sb, layer.specular_exponent];
41 sfx.layer_mtl = [layer.specular_intensity, layer.fx.spec_model as u32 as f32, 0.0, 0.0];
42}
43
44/// `MtlMerge3D`: the foreground over the background, scaled by `Blend`. Mono renders ignore
45/// `MergeType`; Fusion renders `EnablePBRMaterial` merges opaque black.
46pub(super) fn merge3d(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial {
47 if comp.eval_number(n, "EnablePBRMaterial", time, 0.0, expr) > 0.5 {
48 return flat([0.0, 0.0, 0.0, 1.0]);
49 }
50 let mut mat = material_input(comp, n, "BackgroundMaterial", resolve).unwrap_or_else(|| flat([0.0; 4]));
51 let fg = material_input(comp, n, "ForegroundMaterial", resolve).unwrap_or_else(|| flat([0.0; 4]));
52 set_layer(&mut mat, &fg, layer_mode::MERGE, comp.eval_number(n, "Blend", time, 1.0, expr) as f32);
53 mat.has_material_shader = true;
54 mat
55}
56
57/// `MtlStereoMix3D`: mono renders show the left eye whatever `Swap` says.
58pub(super) fn stereo_mix(comp: &Comp, n: &Node, resolve: &mut Resolve) -> ResolvedMaterial {
59 material_input(comp, n, "LeftMaterial", resolve).unwrap_or_else(|| flat([0.0; 4]))
60}
61
62pub(super) fn pbr_uber(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial {
63 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
64 let rgb = |p: &str, d: f64| ["Red", "Green", "Blue"].map(|c| f(&format!("{p}.{c}"), d));
65 let base = rgb("Base.Color", 1.0);
66 let opacity = rgb("Opacity.Opacity", 1.0);
67 let spec = rgb("Specular.Color", 1.0);
68 let sheen = rgb("Sheen.Color", 1.0);
69 let emission = rgb("Emission.Color", 1.0).map(|c| c * f("Emission.Emission", 0.0));
70 let tex = n.connected_node("Base.Color.ColorMtl").and_then(|s| comp.find_node(s)).map(&mut *resolve).unwrap_or_default();
71 ResolvedMaterial {
72 tex_node: tex.tex_node,
73 diffuse_col: [base[0], base[1], base[2], opacity.iter().sum::<f32>() / 3.0],
74 fx: MaterialFx {
75 spec_model: SpecModel::PbrUber,
76 sfx: SurfaceFx {
77 pbr: [f("Metalness.Metalness", 0.0), f("Specular.Roughness", 0.5), f("Specular.IOR", 1.5), f("Specular.Specular", 1.0)],
78 pbr_spec: [spec[0], spec[1], spec[2], f("Base.Base", 1.0)],
79 pbr_layers: [f("Coat.Coat", 0.0), f("Coat.Roughness", 0.0), f("Coat.IOR", 1.5), f("Sheen.Sheen", 0.0)],
80 sheen: [sheen[0], sheen[1], sheen[2], f("Sheen.Roughness", 0.3)],
81 emission: [emission[0], emission[1], emission[2], 0.0],
82 ..SurfaceFx::default()
83 },
84 ..tex.fx
85 },
86 unlit: f("ReceivesLighting", 1.0) < 0.5,
87 receives_shadows: f("ReceivesShadows", 1.0) > 0.5,
88 has_material_shader: true,
89 ..ResolvedMaterial::default()
90 }
91}
92
93/// `FalloffOperator`: `t = 1 - (N.V)^Falloff` blends the face-on material toward the glancing
94/// one (each white when unwired). `TwoTone` tints each by its colour and opacity; `Gradient`
95/// ignores those and multiplies the blend by the gradient at `t`.
96pub(super) fn falloff(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial {
97 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
98 let gradient = n.static_str("ColorVariation") == Some("Gradient");
99 // A tone's alpha scales output alpha only, as a premultiplied colour would.
100 let mut tone = |p: &str, opacity: f64| {
101 let mut m = material_input(comp, n, &format!("{p}Material"), resolve).unwrap_or_else(|| flat([1.0; 4]));
102 if gradient {
103 return (m, 1.0);
104 }
105 let [r, g, b, a] = ["Red", "Green", "Blue", "Alpha"].map(|c| f(&format!("{p}.{c}"), 1.0));
106 for (c, k) in m.diffuse_col.iter_mut().zip([r, g, b, f(&format!("{p}.Opacity"), opacity)]) {
107 *c *= k;
108 }
109 for (c, k) in m.specular_col.iter_mut().zip([r, g, b]) {
110 *c *= k;
111 }
112 (m, a)
113 };
114 let (mut mat, face_alpha) = tone("FaceOn", 0.2);
115 let (glancing, glancing_alpha) = tone("Glancing", 1.0);
116 mat.fx.diffuse_color_alpha *= face_alpha;
117 let mode = if gradient { layer_mode::FALLOFF_GRADIENT } else { layer_mode::FALLOFF };
118 set_layer(&mut mat, &glancing, mode, f("Falloff", 2.0));
119 mat.fx.sfx.layer_mtl[2] = glancing_alpha;
120 if gradient {
121 mat.fx.sfx.lut = gradient_lut(comp.eval_gradient(n, "Gradient", time), [[1.0; 4], [0.0, 0.0, 0.0, 1.0]]);
122 }
123 mat.has_material_shader = true;
124 mat
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130 use crate::scene3d::collect::resolve_test_material as resolve_in;
131
132 #[test]
133 fn merge3d_layers_foreground_over_background() {
134 let mat = resolve_in(
135 "BG = MtlBlinn { Inputs = { [\"Diffuse.Color.Red\"] = Input { Value = 0.5, }, }, },
136 FG = MtlPhong { Inputs = { [\"Specular.Exponent\"] = Input { Value = 12, }, }, },
137 X = MtlMerge3D { Inputs = { Blend = Input { Value = 0.25, },
138 BackgroundMaterial = Input { SourceOp = \"BG\", Source = \"MaterialOutput\", },
139 ForegroundMaterial = Input { SourceOp = \"FG\", Source = \"MaterialOutput\", }, }, },",
140 );
141 assert_eq!(mat.diffuse_col[0], 0.5);
142 assert!(!mat.unlit);
143 let sfx = mat.fx.sfx;
144 assert_eq!(sfx.layer, [layer_mode::MERGE, 0.25, 1.0, 0.0]);
145 assert_eq!(sfx.layer_spec[3], 12.0);
146 assert_eq!(sfx.layer_mtl[1], SpecModel::Phong as u32 as f32);
147 }
148
149 #[test]
150 fn merge3d_unwired_is_transparent_and_bare_images_are_flat() {
151 let empty = resolve_in("X = MtlMerge3D { },");
152 assert_eq!(empty.diffuse_col, [0.0; 4]);
153 assert_eq!(empty.fx.sfx.layer_col, [0.0; 4]);
154 let img = resolve_in(
155 "Img = Background { },
156 X = MtlMerge3D { Inputs = { ForegroundMaterial = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },",
157 );
158 assert_eq!(img.bump_node.map(|_| ()), Some(()), "foreground image takes the bump slot");
159 assert_eq!(img.fx.sfx.layer[2..], [0.0, 2.0]);
160 }
161
162 #[test]
163 fn merge3d_pbr_renders_opaque_black() {
164 let mat = resolve_in("BG = MtlBlinn { }, X = MtlMerge3D { Inputs = { EnablePBRMaterial = Input { Value = 1, },
165 BackgroundMaterial = Input { SourceOp = \"BG\", Source = \"MaterialOutput\", }, }, },");
166 assert_eq!(mat.diffuse_col, [0.0, 0.0, 0.0, 1.0]);
167 assert!(mat.unlit);
168 }
169
170 #[test]
171 fn stereo_mix_always_uses_left() {
172 let mat = resolve_in(
173 "L = MtlBlinn { Inputs = { [\"Diffuse.Color.Green\"] = Input { Value = 0.3, }, }, },
174 R = MtlBlinn { },
175 X = MtlStereoMix3D { Inputs = { Swap = Input { Value = 1, },
176 LeftMaterial = Input { SourceOp = \"L\", Source = \"MaterialOutput\", },
177 RightMaterial = Input { SourceOp = \"R\", Source = \"MaterialOutput\", }, }, },",
178 );
179 assert_eq!(mat.diffuse_col[1], 0.3);
180 }
181
182 #[test]
183 fn pbr_uber_reads_metal_roughness_and_emission() {
184 let mat = resolve_in(
185 "X = MtlPBRUber { Inputs = {
186 [\"Metalness.Metalness\"] = Input { Value = 1, },
187 [\"Specular.Roughness\"] = Input { Value = 0.2, },
188 [\"Emission.Emission\"] = Input { Value = 0.5, },
189 [\"Emission.Color.Red\"] = Input { Value = 0, },
190 [\"Opacity.Opacity.Green\"] = Input { Value = 0.4, }, }, },",
191 );
192 assert_eq!(mat.fx.spec_model, SpecModel::PbrUber);
193 assert_eq!(mat.fx.sfx.pbr, [1.0, 0.2, 1.5, 1.0]);
194 assert_eq!(mat.fx.sfx.emission, [0.0, 0.5, 0.5, 0.0]);
195 assert!((mat.diffuse_col[3] - 0.8).abs() < 1e-6);
196 }
197
198 #[test]
199 fn falloff_two_tone_tints_and_alpha_scales_alpha_only() {
200 let two = resolve_in(
201 "X = FalloffOperator { Inputs = { [\"FaceOn.Red\"] = Input { Value = 0.5, }, [\"FaceOn.Alpha\"] = Input { Value = 0.4, },
202 [\"Glancing.Red\"] = Input { Value = 0, }, [\"Glancing.Alpha\"] = Input { Value = 0.3, }, Falloff = Input { Value = 3, }, }, },",
203 );
204 assert_eq!(two.diffuse_col, [0.5, 1.0, 1.0, 0.2]);
205 assert_eq!(two.fx.diffuse_color_alpha, 0.4);
206 assert!(two.unlit);
207 assert_eq!(two.fx.sfx.layer, [layer_mode::FALLOFF, 3.0, 0.0, 0.0]);
208 assert_eq!(two.fx.sfx.layer_col, [0.0, 1.0, 1.0, 1.0]);
209 assert_eq!(two.fx.sfx.layer_mtl[2], 0.3);
210 let lit = resolve_in(
211 "M = MtlBlinn { }, X = FalloffOperator { Inputs = { [\"FaceOn.Blue\"] = Input { Value = 0.5, },
212 FaceOnMaterial = Input { SourceOp = \"M\", Source = \"MaterialOutput\", }, }, },",
213 );
214 assert_eq!(lit.specular_col[2], lit.specular_col[0] * 0.5, "the tint covers specular light too");
215 }
216
217 #[test]
218 fn falloff_gradient_ignores_tones_and_keeps_materials() {
219 let grad = resolve_in(
220 "M = MtlBlinn { }, X = FalloffOperator { Inputs = { ColorVariation = Input { Value = FuID { \"Gradient\" }, },
221 [\"FaceOn.Red\"] = Input { Value = 0.5, }, [\"Glancing.Alpha\"] = Input { Value = 0.3, },
222 FaceOnMaterial = Input { SourceOp = \"M\", Source = \"MaterialOutput\", }, }, },",
223 );
224 assert!(!grad.unlit);
225 assert_eq!(grad.diffuse_col[0], grad.diffuse_col[1]);
226 assert_eq!(grad.fx.sfx.layer, [layer_mode::FALLOFF_GRADIENT, 2.0, 0.0, 0.0]);
227 assert_eq!(grad.fx.sfx.layer_col, [1.0; 4]);
228 assert_eq!(grad.fx.sfx.layer_mtl[2], 1.0);
229 assert_eq!(grad.fx.sfx.lut[0], [1.0; 4]);
230 assert_eq!(grad.fx.sfx.lut[15], [0.0, 0.0, 0.0, 1.0]);
231 }
232
233 #[test]
234 fn reflect_without_reflection_is_its_background_and_images_lay_on_by_uv() {
235 let bg = "BG = MtlBlinn { Inputs = { [\"Diffuse.Color.Red\"] = Input { Value = 0.3, }, }, }, Img = Background { },";
236 let plain = resolve_in(&format!("{bg} X = MtlReflect {{ Inputs = {{ BackgroundMaterial = Input {{ SourceOp = \"BG\", Source = \"MaterialOutput\", }}, }}, }},"));
237 assert_eq!((plain.fx.env_mode, plain.diffuse_col[0]), (0, 0.3));
238 let img = resolve_in(&format!(
239 "{bg} X = MtlReflect {{ Inputs = {{ BackgroundMaterial = Input {{ SourceOp = \"BG\", Source = \"MaterialOutput\", }},
240 [\"Reflection.Color.Material\"] = Input {{ SourceOp = \"Img\", Source = \"Output\", }}, }}, }},"
241 ));
242 assert_eq!((img.fx.env_mode, img.fx.env_map_mode, img.fx.env_tex_slot), (2, 5, 1));
243 }
244
245 #[test]
246 fn chan_bool_unwired_inputs_are_black_and_bare_images_unlit() {
247 let empty = resolve_in("X = MtlChanBool { },");
248 assert_eq!(empty.diffuse_col, [0.0, 0.0, 0.0, 1.0]);
249 assert_eq!(empty.fx.sfx.layer_col, [0.0, 0.0, 0.0, 1.0]);
250 assert!(empty.fx.cb_enabled);
251 let img = resolve_in("Img = Background { }, X = MtlChanBool { Inputs = { BackgroundMaterial = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },");
252 assert!(img.unlit && img.tex_node.is_some());
253 }
254
255 #[test]
256 fn pbr_uber_reads_coat_and_sheen() {
257 let mat = resolve_in("X = MtlPBRUber { Inputs = { [\"Coat.Coat\"] = Input { Value = 1, }, [\"Sheen.Sheen\"] = Input { Value = 0.5, }, [\"Sheen.Color.Blue\"] = Input { Value = 0, }, }, },");
258 assert_eq!(mat.fx.sfx.pbr_layers, [1.0, 0.0, 1.5, 0.5]);
259 assert_eq!(mat.fx.sfx.sheen, [1.0, 1.0, 0.0, 0.3]);
260 }
261
262 #[test]
263 fn tex_catcher_without_projectors_is_transparent() {
264 let mat = resolve_in("X = TexCatcher { },");
265 assert_eq!(mat.diffuse_col[3], 0.0);
266 assert!(mat.has_material_shader);
267 }
268}