1//! Surface shading beyond the classic material: procedural textures, a secondary material layer,
2//! `MtlPBRUber`, fog and environment coordinate spaces. `SurfaceFx` is copied verbatim into the
3//! mesh uniform, so its layout mirrors `struct SurfaceFx` in `surface_fx.wgsl`.
4
5use bytemuck::{Pod, Zeroable};
6use model::Gradient;
7
8/// Entries in the gradient lookup table shared by `TexGradient` and `FalloffOperator`.
9pub(super) const LUT_SIZE: usize = 16;
10
11/// Procedural colour source replacing the bound texture (`proc_a.x`).
12pub(super) mod proc_kind {
13 pub const GRADIENT: f32 = 1.0;
14 pub const NOISE: f32 = 2.0;
15}
16
17/// How the secondary material in `layer` combines with the base surface (`layer.x`).
18pub(super) mod layer_mode {
19 /// `MtlChanBool` foreground operands.
20 pub const CHAN_BOOL: f32 = 1.0;
21 /// `MtlMerge3D`: foreground over background scaled by `layer.y` (Blend).
22 pub const MERGE: f32 = 2.0;
23 /// `FalloffOperator`: base is face-on, layer is glancing, mixed by `1 - (N.V)^layer.y`.
24 pub const FALLOFF: f32 = 3.0;
25 /// `FALLOFF` times the gradient lookup table at the mix factor.
26 pub const FALLOFF_GRADIENT: f32 = 4.0;
27}
28
29#[repr(C)]
30#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
31pub struct SurfaceFx {
32 /// `[kind, ..]`: gradient `[1, type, scale, offset]`, noise `[2, detail, scale, seethe]`.
33 pub proc_a: [f32; 4],
34 /// Gradient `[repeat, 0, 0, 0]`; noise `[contrast, brightness, inverted, discontinuous]`.
35 pub proc_b: [f32; 4],
36 /// `[mode, amount, lit, tex_slot (2 = bump_tex)]`.
37 pub layer: [f32; 4],
38 /// Layer diffuse colour (straight RGB, alpha).
39 pub layer_col: [f32; 4],
40 /// Layer specular colour and exponent.
41 pub layer_spec: [f32; 4],
42 /// `[specular_intensity, spec_model, falloff glancing alpha, 0]`.
43 pub layer_mtl: [f32; 4],
44 /// `MtlPBRUber` `[metalness, roughness, ior, specular]`.
45 pub pbr: [f32; 4],
46 /// `MtlPBRUber` specular colour and `Base.Base` weight.
47 pub pbr_spec: [f32; 4],
48 /// `MtlPBRUber` `[coat, coat_roughness, coat_ior, sheen]`.
49 pub pbr_layers: [f32; 4],
50 /// `MtlPBRUber` sheen colour and roughness.
51 pub sheen: [f32; 4],
52 /// Emitted colour added after lighting.
53 pub emission: [f32; 4],
54 /// `Fog3D` `[type (1 linear, 2 exp, 3 exp2), near, far, density]`.
55 pub fog: [f32; 4],
56 /// Fog colour and `Radial`.
57 pub fog_col: [f32; 4],
58 /// `[coord_space (0 world, 1 model, 2 camera), 0, 0, 0]` for environment lookups.
59 pub env: [f32; 4],
60 /// Premultiplied gradient samples at `i / (LUT_SIZE - 1)`.
61 pub lut: [[f32; 4]; LUT_SIZE],
62}
63
64/// Premultiplied lookup table of `gradient`, or of `fallback` stops when the input is absent.
65pub(super) fn gradient_lut(gradient: Option<Gradient>, fallback: [[f32; 4]; 2]) -> [[f32; 4]; LUT_SIZE] {
66 std::array::from_fn(|i| {
67 let t = i as f64 / (LUT_SIZE - 1) as f64;
68 let c = match &gradient {
69 Some(g) => g.sample(t),
70 None => std::array::from_fn(|k| fallback[0][k] + (fallback[1][k] - fallback[0][k]) * t as f32),
71 };
72 [c[0] * c[3], c[1] * c[3], c[2] * c[3], c[3]]
73 })
74}
75
76/// Fusion's simplex lattice, shared with the 2D `FastNoise` generator.
77pub(super) fn simplex_wgsl() -> &'static str {
78 const SRC: &str = include_str!("../shaders/keyers_gen.wgsl");
79 let start = SRC.find("const PERM: array<u32, 256>").expect("keyers_gen.wgsl defines PERM");
80 let end = SRC[start..].find("@compute").expect("keyers_gen.wgsl has an entry point after the lattice");
81 &SRC[start..start + end]
82}
83
84pub(super) const SURFACE_FX_WGSL: &str = include_str!("surface_fx.wgsl");
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89 use model::GradientStop;
90
91 #[test]
92 fn surface_fx_matches_wgsl_layout() {
93 let wgsl_vec4s = SURFACE_FX_WGSL
94 .split("struct SurfaceFx {")
95 .nth(1)
96 .and_then(|s| s.split("};").next())
97 .expect("SurfaceFx struct")
98 .lines()
99 .filter(|l| l.trim_end().ends_with(": vec4<f32>,"))
100 .count();
101 assert_eq!(wgsl_vec4s, 14, "scalar vec4 fields");
102 assert_eq!(std::mem::size_of::<SurfaceFx>(), (14 + LUT_SIZE) * 16);
103 assert!(SURFACE_FX_WGSL.contains(&format!("lut: array<vec4<f32>, {LUT_SIZE}>")));
104 }
105
106 #[test]
107 fn simplex_slice_holds_the_lattice_only() {
108 let s = simplex_wgsl();
109 assert!(s.contains("fn simplex3d(") && s.contains("const SIMPLEX_GAIN"));
110 assert!(!s.contains("@compute") && !s.contains("var<uniform>"));
111 }
112
113 #[test]
114 fn gradient_lut_premultiplies_and_falls_back() {
115 let lut = gradient_lut(None, [[1.0; 4], [0.0, 0.0, 0.0, 1.0]]);
116 assert_eq!(lut[0], [1.0; 4]);
117 assert_eq!(lut[LUT_SIZE - 1], [0.0, 0.0, 0.0, 1.0]);
118 let g = Gradient {
119 stops: vec![
120 GradientStop { pos: 0.0, rgba: [1.0, 0.0, 0.0, 0.5] },
121 GradientStop { pos: 1.0, rgba: [0.0, 1.0, 0.0, 0.5] },
122 ],
123 };
124 assert_eq!(gradient_lut(Some(g), [[0.0; 4]; 2])[0], [0.5, 0.0, 0.0, 0.5]);
125 }
126}