Skip to main content

sgl_3d/content/
material.rs

1//! A material's values, which `Scene::material` reads and
2//! `Scene::set_material` replaces, and how its alpha is used.
3use super::asset::Material;
4use super::shader::MaterialShader;
5
6/// How a material uses its alpha: glTF's `alphaMode`, with Bevy's
7/// `AlphaMode` names (Bevy 9d12036, its phases and pipeline keys in
8/// `crates/bevy_pbr/src/material.rs`).
9#[derive(Clone, Copy, Debug, Default, PartialEq)]
10pub enum AlphaMode {
11    /// Alpha is ignored.
12    #[default]
13    Opaque,
14    /// Opaque where the base alpha reaches `cutoff` and cut out below it, in
15    /// every view, shadow and ray (glTF `MASK` and its `alphaCutoff`).
16    Mask { cutoff: f32 },
17    /// Blended over what lies behind it, sorted back to front by each mesh's
18    /// bounds centre (glTF `BLEND`, which loads with both fields false). It
19    /// casts no shadow, and rays pass through it. Unmarked, it writes no
20    /// depth or motion. Marked `receives_screen_space_reflections`, it is the
21    /// surface the frame's screen-space reflections trace and its temporal
22    /// effects reproject at the pixels where it is the nearest receiver:
23    /// water or glass that reflects the scene in front of it.
24    Blend {
25        receives_screen_space_reflections: bool,
26        /// Whether alpha fades its reflected and transmitted diffuse light
27        /// and its emission, its reflections and highlights keeping their full
28        /// strength, as glass
29        /// does (Filament's `transparent` blending). False fades all of its
30        /// light, glTF's alpha as coverage (Filament's `fade`).
31        keeps_specular: bool,
32    },
33}
34
35/// One layer of a material's scrolling normals
36/// ([`SurfaceMaterial::normal_layers`]): the material's normal map drawn at
37/// its own scale, moving across the surface.
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub struct NormalLayer {
40    /// The direction and speed the layer moves across the surface, in the
41    /// material's UV units per second along U and V. SGL3D rounds it to a
42    /// whole number of repeats of the layer's map per hour, so the layer is
43    /// where it was an hour earlier and long sessions keep their precision:
44    /// in steps of 1/(3600 × `scale`) UV units per second, at most half a
45    /// step off, and a layer slower than 1/7200 of a repeat per second
46    /// stands still. At most 2^24 repeats per hour (about 4660 a second).
47    pub velocity: [f32; 2],
48    /// How many times the normal map repeats per unit of the material's UVs;
49    /// positive.
50    pub scale: f32,
51    /// How much of the layer's slopes the surface takes, with the
52    /// material's `normal_scale`: 1 as the map is authored, 0 none.
53    pub strength: f32,
54}
55
56impl Default for NormalLayer {
57    /// The map as authored, at the material's UVs, standing still.
58    fn default() -> Self {
59        Self {
60            velocity: [0.; 2],
61            scale: 1.,
62            strength: 1.,
63        }
64    }
65}
66
67/// A material's values, read by [`Scene::material`](crate::Scene::material)
68/// and replaced by [`Scene::set_material`](crate::Scene::set_material).
69/// Author initial content with [`asset::Material`](crate::asset::Material);
70/// the textures it was added with stay as they were.
71#[derive(Clone, Copy, Debug, PartialEq)]
72pub struct SurfaceMaterial {
73    /// Linear RGB base multiplier, each channel finite and nonnegative, and
74    /// alpha in `0..=1`.
75    pub base: [f32; 4],
76    /// Linear RGB emission, each channel finite and nonnegative.
77    pub emission: [f32; 3],
78    /// Metallic factor in `0..=1`.
79    pub metallic: f32,
80    /// Perceptual roughness in `0..=1`.
81    pub roughness: f32,
82    /// Index of refraction, at least 1 or `f32::INFINITY`, which sets the
83    /// dielectric F0, ((ior − 1) / (ior + 1))²: 1.5 gives 0.04, water's 1.33
84    /// 0.02 ([`asset::Material::ior`](crate::asset::Material::ior)).
85    pub ior: f32,
86    /// Strength of the dielectric specular reflection in `0..=1`: 1 as the
87    /// IOR gives it, 0 none. It scales the dielectric F0 and is its
88    /// reflectance at grazing incidence (F90), which metallic mixes toward 1.
89    pub specular: f32,
90    /// Linear tint of the dielectric F0, finite and nonnegative: the F0 is
91    /// the IOR's times this, at most 1, times `specular`.
92    pub specular_color: [f32; 3],
93    /// How much of the material's occlusion map applies, in `0..=1`; nothing
94    /// without one
95    /// ([`asset::Material::occlusion_texture`](crate::asset::Material::occlusion_texture)).
96    pub occlusion_strength: f32,
97    /// Clearcoat intensity in `0..=1`, which a clearcoat map's red channel
98    /// multiplies.
99    pub clearcoat: f32,
100    /// Clearcoat perceptual roughness in `0..=1`, which a clearcoat
101    /// roughness map's green channel multiplies.
102    pub coat_roughness: f32,
103    /// Finite scale applied to the clearcoat normal map's tangent-space X and Y
104    /// components ([`Material::coat_normal_scale`]).
105    pub coat_normal_scale: f32,
106    /// A thin film's strength in `0..=1`, which an iridescence map's red
107    /// channel multiplies ([`Material::iridescence`]).
108    pub iridescence: f32,
109    /// The film's index of refraction, at least 1.
110    pub iridescence_ior: f32,
111    /// The film's thinnest and thickest thickness in nanometres, each finite
112    /// and nonnegative ([`Material::iridescence_thickness`]).
113    pub iridescence_thickness: [f32; 2],
114    /// A sheen's linear colour, each channel in `0..=1`, which a sheen
115    /// colour map's RGB multiplies ([`Material::sheen_color`]): black none.
116    pub sheen_color: [f32; 3],
117    /// The sheen's perceptual roughness in `0..=1`, which a sheen roughness
118    /// map's alpha multiplies ([`Material::sheen_roughness`]).
119    pub sheen_roughness: f32,
120    /// The share in `0..=1` of the light the base diffuses that passes to
121    /// the surface's other side, which a diffuse transmission map's alpha
122    /// multiplies ([`Material::diffuse_transmission`]): 0 none.
123    pub diffuse_transmission: f32,
124    /// The linear colour of the light it passes through, each channel finite
125    /// and nonnegative, which a diffuse transmission colour map's RGB multiplies
126    /// ([`Material::diffuse_transmission_color`]).
127    pub diffuse_transmission_color: [f32; 3],
128    /// Finite scale of the normal map's tangent-space X and Y.
129    pub normal_scale: f32,
130    /// Scrolling normals: the normal map drawn as two layers that move
131    /// across the surface, their slopes added as superposed waves' are, at
132    /// the frame's `FrameInput::elapsed_seconds`: water's moving waves, with
133    /// no geometry uploaded per frame. Needs a normal map that repeats on
134    /// both axes. `None` draws the map once at the material's UVs.
135    pub normal_layers: Option<[NormalLayer; 2]>,
136    /// Finite bump height multiplier: the height change over one pixel times this
137    /// tilts a rasterised surface (the camera's and probe captures'), as
138    /// three.js's `bumpScale`, and over one metre at a world-space
139    /// reflection or dynamic GI ray's hit, which therefore usually shows the
140    /// bump stronger (specs/decisions.md D-45).
141    pub bump_scale: f32,
142    /// The share of the light behind the surface that passes through it,
143    /// refracted, in `0..=1` (`KHR_materials_transmission`), in place of
144    /// that share of its diffuse light: glass, water, clear plastic. The
145    /// sheen and coat dim it with the rest of the base light. A
146    /// material with any transmission is drawn with the blended surfaces
147    /// whatever its alpha mode (its alpha still covers as the mode says): it
148    /// writes no depth, G-buffer or motion unless it is a `Blend` receiver
149    /// of screen-space reflections, takes no ambient occlusion and casts no
150    /// shadow, rays pass through it and probe captures leave it out, and
151    /// what it shows through it is the opaque frame behind it, blurred by
152    /// its roughness, not other blended or transmissive surfaces. Give glass
153    /// its own material: a transmission map's zeros do not make the rest of
154    /// the material opaque. On a device of the `Basic` binding tier, and
155    /// in what screen-space reflections see of it, the light behind it
156    /// passes unrefracted and unblurred, dimmed by the mean over colour
157    /// channels of what the refracted light passes, so without its tint.
158    pub transmission: f32,
159    /// The thickness of the volume beneath the surface, in the mesh's units
160    /// (the instance's scale applies), which the transmitted light crosses
161    /// (`KHR_materials_volume`): 0 is a thin wall, which bends no light; a
162    /// thicker one is a closed volume, whose back faces are not drawn.
163    pub thickness: f32,
164    /// The distance in metres light travels through the volume before white
165    /// light takes `attenuation_color` (Beer-Lambert), positive, or
166    /// `f32::INFINITY` for no attenuation.
167    pub attenuation_distance: f32,
168    /// The linear colour white light turns into at `attenuation_distance`,
169    /// each channel in `0..=1`.
170    pub attenuation_color: [f32; 3],
171    /// How far transmitted light's colours spread, as 20 over the Abbe
172    /// number, nonnegative (`KHR_materials_dispersion`): 0 none, 0.33 crown
173    /// glass, 2 an exaggerated prism.
174    pub dispersion: f32,
175    /// Anisotropy strength in `0..=1`; zero is isotropic.
176    pub anisotropy_strength: f32,
177    /// Counter-clockwise tangent-space rotation of the anisotropy direction,
178    /// in radians.
179    pub anisotropy_rotation: f32,
180    /// Multiplier of the environment's diffuse and specular light, finite
181    /// and nonnegative.
182    pub environment_scale: f32,
183    /// Visibility group: every bit must be enabled by the frame's mask.
184    /// Zero is always visible.
185    pub visibility_group: u32,
186    /// Whether the material bypasses lighting.
187    pub unlit: bool,
188    /// Whether global illumination gathers the light the material gives off
189    /// itself (its emission, and an unlit material's whole colour): today
190    /// the dynamic GI volume's probe rays. Set it false on a fixture that a
191    /// scene light stands for, such as a lamp's glowing panel beside its
192    /// rectangle light, so its light reaches other surfaces once, through
193    /// the light, as Unity's emission "Global Illumination: None" keeps a
194    /// glowing material's light out of its GI. The surface still glows,
195    /// shows in reflections, blocks the probes' rays and, when lit, bounces
196    /// the light that reaches it.
197    pub emits_into_gi: bool,
198    /// Whether both sides of each triangle are drawn.
199    pub double_sided: bool,
200    pub alpha: AlphaMode,
201    /// The game's shader (`Scene::add_shader`) its surfaces are evaluated
202    /// through, which a game names with `Scene::set_material` after adding
203    /// the material (an authored material has none): its vertex function
204    /// places every vertex in every view that rasterises it and its surface
205    /// function finishes every fragment from these values and the maps,
206    /// with what culling allows for its displacement. Its parameters start as zeros
207    /// (`Scene::set_shader_parameters`). A shader material's surface counts
208    /// as moving for the temporal composition mask, and its `double_sided` holds
209    /// even for a volume (`thickness` above 0). Rays, bakes and the static
210    /// layers of local-light shadows see its rest geometry and these values.
211    /// None by default.
212    pub shader: Option<MaterialShader>,
213}
214
215impl Default for SurfaceMaterial {
216    /// The values of the default authored material
217    /// (`asset::Material::default()`, glTF 2.0's), lit by the whole
218    /// environment (`environment_scale` 1). Set what
219    /// differs and take the rest with `..Default::default()`, or from
220    /// [`Scene::material`](crate::Scene::material) to change a material's
221    /// current values.
222    fn default() -> Self {
223        Self::authored(&Material::default())
224    }
225}
226
227impl SurfaceMaterial {
228    /// The values of an authored material, as a scene adds them.
229    pub(crate) fn authored(m: &Material) -> Self {
230        Self {
231            base: m.base,
232            emission: m.emissive,
233            metallic: m.metallic,
234            roughness: m.roughness,
235            ior: m.ior,
236            specular: m.specular,
237            specular_color: m.specular_color,
238            occlusion_strength: m.occlusion_strength,
239            clearcoat: m.clearcoat,
240            coat_roughness: m.coat_roughness,
241            coat_normal_scale: m.coat_normal_scale,
242            iridescence: m.iridescence,
243            iridescence_ior: m.iridescence_ior,
244            iridescence_thickness: m.iridescence_thickness,
245            sheen_color: m.sheen_color,
246            sheen_roughness: m.sheen_roughness,
247            diffuse_transmission: m.diffuse_transmission,
248            diffuse_transmission_color: m.diffuse_transmission_color,
249            normal_scale: m.normal_scale,
250            normal_layers: m.normal_layers,
251            bump_scale: m.bump_scale,
252            transmission: m.transmission,
253            thickness: m.thickness,
254            attenuation_distance: m.attenuation_distance,
255            attenuation_color: m.attenuation_color,
256            dispersion: m.dispersion,
257            anisotropy_strength: m.anisotropy_strength,
258            anisotropy_rotation: m.anisotropy_rotation,
259            environment_scale: 1.,
260            visibility_group: m.visibility_group,
261            unlit: m.unlit,
262            emits_into_gi: m.emits_into_gi,
263            double_sided: m.double_sided,
264            alpha: m.alpha,
265            shader: None,
266        }
267    }
268
269    /// Whether the material is drawn by the transparent stage rather than
270    /// with opaque surfaces: blended, or transmissive whatever its alpha
271    /// mode. This is the population every view, cache and ray takes it by.
272    pub(crate) fn blended(&self) -> bool {
273        matches!(self.alpha, AlphaMode::Blend { .. }) || self.transmissive()
274    }
275
276    /// Whether light behind it passes through it, refracted.
277    pub(crate) fn transmissive(&self) -> bool {
278        self.transmission > 0.
279    }
280
281    /// Whether it bounds a volume, whose back faces are not drawn
282    /// (`KHR_materials_volume`: `doubleSided` does not apply to a volume).
283    /// A material with a shader is the game's to shade on either side
284    /// (its surface context's `front`), so its `double_sided` holds.
285    pub(crate) fn volume(&self) -> bool {
286        self.transmissive() && self.thickness > 0. && self.shader.is_none()
287    }
288
289    /// Whether the material is a blended receiver of screen-space
290    /// reflections.
291    pub(crate) fn receives_screen_space_reflections(&self) -> bool {
292        matches!(
293            self.alpha,
294            AlphaMode::Blend {
295                receives_screen_space_reflections: true,
296                ..
297            }
298        )
299    }
300
301    /// Whether every view draws both faces of its meshes: a double-sided
302    /// material's, but a volume's (`volume`) front faces alone.
303    pub(crate) fn two_sided(&self) -> bool {
304        self.double_sided && !self.volume()
305    }
306
307    /// Whether `other`'s meshes are drawn as other geometry than its, so
308    /// surfaces may appear or depart where nothing moved: other faces, its
309    /// visibility group, alpha mode or cutoff, a masked base alpha, whether
310    /// it is blended or a blended receiver of screen-space reflections
311    /// (which writes the G-buffer's motion), or its shader, whose vertex
312    /// function places vertices and whose surface function may cut texels
313    /// out. A masked shader can derive coverage from every evaluated
314    /// material field, so any edit of such a material counts. Shadow
315    /// casters' caches and the camera's view-wide temporal signal
316    /// (`Scene::set_material`) both take it.
317    pub(crate) fn draws_other_geometry(&self, other: &Self) -> bool {
318        let drawn = |values: &Self| {
319            let (mode, alpha) = match values.alpha {
320                AlphaMode::Mask { .. } => (values.alpha, values.base[3]),
321                // Whether it keeps its specular light is shading alone.
322                AlphaMode::Blend {
323                    receives_screen_space_reflections,
324                    ..
325                } => (
326                    AlphaMode::Blend {
327                        receives_screen_space_reflections,
328                        keeps_specular: false,
329                    },
330                    1.,
331                ),
332                AlphaMode::Opaque => (values.alpha, 1.),
333            };
334            (
335                values.two_sided(),
336                values.visibility_group,
337                mode,
338                values.blended(),
339                alpha,
340                values.shader,
341            )
342        };
343        self != other
344            && (drawn(self) != drawn(other)
345                || (other.shader.is_some() && matches!(other.alpha, AlphaMode::Mask { .. })))
346    }
347}