three_rs/materials/environment.rs
1//! Port of `three.js/src/nodes/lighting/EnvironmentNode.js`.
2//!
3//! Image-based lighting: the PMREM sampled twice per fragment — once along the
4//! reflection vector at the surface's roughness, which is `radiance`, and once
5//! along the world normal at roughness 1, which is `iblIrradiance`. Everything
6//! downstream of those two is already in `PhysicalLightingModel`; without an
7//! environment they stay zero and the same arithmetic runs on zeros.
8
9use crate::nodes::node::Type;
10use crate::nodes::pmrem_utils::roughness_to_mip;
11use crate::nodes::tsl::{
12 bent_normal_view, camera_world_matrix, clearcoat_normal_view, clearcoat_roughness,
13 cube_texture_level, float, material_env_intensity, material_env_rotation, mix, normal_view,
14 normal_world, position_view_direction, reflect, roughness, transform_direction, vec4_join,
15};
16use crate::nodes::NodeRef;
17use crate::textures::CubeTexture;
18
19/// What a material needs to read a generated PMREM: the cube and its `maxLod`
20/// uniform.
21///
22/// This is the half of `PMREMNode` that has to travel with a material rather
23/// than with the renderer. [`PmremEnvironment::handle`] hands one out; it is a
24/// cheap clone of the cube the environment renders into, so a handle taken
25/// before the PMREM exists still works afterwards.
26///
27/// [`PmremEnvironment::handle`]: crate::nodes::pmrem_node::PmremEnvironment::handle
28#[derive(Clone, Debug)]
29pub struct PmremHandle {
30 /// The generated PMREM cube.
31 pub texture: CubeTexture,
32 /// The uniform holding the cube's maximum mip level, for
33 /// `roughness_to_mip`.
34 pub max_lod: NodeRef,
35}
36
37/// The handle is part of [`SetupContext`]'s derived hash — the render object's
38/// dynamic cache key — so it needs one, and neither `CubeTexture` nor the
39/// `maxLod` uniform derives `Hash`. What the *program* depends on is only that
40/// there **is** an environment and which texture it reads; `maxLod` is a
41/// uniform and changes no code. So the texture's id is the whole key, which is
42/// also what makes two materials sharing one PMREM share one program.
43///
44/// [`SetupContext`]: crate::materials::node_material::SetupContext
45impl std::hash::Hash for PmremHandle {
46 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
47 self.texture.id().hash(state);
48 }
49}
50
51impl PmremHandle {
52 /// `PMREMNode.setup()` — `this._texture.sample( materialEnvRotation.mul(
53 /// uvNode ) ).level( roughnessToMip( levelNode, this._maxLod ) ).rgb`.
54 ///
55 /// `materialEnvRotation` is a `mat4`, so a `vec3` direction is widened with
56 /// `w = 1` first; the background's `backgroundRotation * normal` is a
57 /// `vec4` already and goes in as it is, which is three's dump of both. The
58 /// cube read's `x` negation is `CubeTextureNode.setupUV()`'s. There is no
59 /// Y flip any more: the PMREM is rendered with the same face cameras every
60 /// other cube render target is.
61 pub fn sample(&self, uv: NodeRef, level: NodeRef) -> NodeRef {
62 let uv = if uv.ty() == Type::Vec4 {
63 uv
64 } else {
65 vec4_join(vec![uv, float(1.0)])
66 };
67 let direction = material_env_rotation().mul(uv);
68 cube_texture_level(
69 &self.texture,
70 direction,
71 roughness_to_mip(level, self.max_lod.clone()),
72 )
73 .xyz()
74 }
75}
76
77/// `scene.environmentNode` set to a node graph rather than a texture:
78/// `EnvironmentNode.setup()`'s non-texture branch, which builds that graph
79/// under each lighting context in turn.
80///
81/// Three reads the environment through context: every `PMREMNode` in the
82/// graph asks `builder.context.getUV()` and `getTextureLevel()` for its
83/// direction and roughness, and `EnvironmentNode` builds the same graph once
84/// under the radiance context and once under the irradiance one. The port has
85/// no node context, so the graph is a function of those two values instead.
86/// [`PmremHandle::sample`] is the `pmremTexture()` leaf it calls. Each call
87/// builds the graph again, which is what three's context build does: its
88/// dump repeats the `mix` and the `oscSine` for radiance and for
89/// `iblIrradiance`.
90///
91/// `webgpu_cubemap_mix`: `mix( pmremTexture( cube2 ), pmremTexture( cube1 ),
92/// oscSine( time.mul( .1 ) ) )`.
93#[derive(Clone)]
94pub struct EnvironmentNode {
95 id: u64,
96 build: std::rc::Rc<dyn Fn(NodeRef, NodeRef) -> NodeRef>,
97}
98
99impl EnvironmentNode {
100 /// `build( uv, level )` is the graph under a context whose `getUV()` is
101 /// `uv` and whose `getTextureLevel()` is `level`.
102 pub fn new(build: impl Fn(NodeRef, NodeRef) -> NodeRef + 'static) -> Self {
103 static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
104 Self {
105 id: NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
106 build: std::rc::Rc::new(build),
107 }
108 }
109
110 /// The graph read along `uv` at roughness `level`.
111 pub fn sample(&self, uv: NodeRef, level: NodeRef) -> NodeRef {
112 (self.build)(uv, level)
113 }
114
115 /// `node.context( { getTextureLevel: () => level } )`: the same graph with
116 /// every `pmremTexture()` in it read at `level`, whatever roughness the
117 /// reader asks for. It is a new node, as `.context()` is.
118 pub fn with_texture_level(&self, level: NodeRef) -> Self {
119 let inner = self.clone();
120 Self::new(move |uv, _| inner.sample(uv, level.clone()))
121 }
122}
123
124impl std::fmt::Debug for EnvironmentNode {
125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126 f.debug_struct("EnvironmentNode")
127 .field("id", &self.id)
128 .finish_non_exhaustive()
129 }
130}
131
132/// Keyed by identity, as every node in a material is: the scene holds it, so
133/// it is the same node, and the same program, every frame.
134impl std::hash::Hash for EnvironmentNode {
135 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
136 self.id.hash(state);
137 }
138}
139
140/// What `EnvironmentNode` is built from: a generated PMREM
141/// (`pmremTexture( envMap )`) or a node graph over PMREMs.
142#[derive(Clone, Debug, Hash)]
143#[doc(hidden)]
144pub enum Environment {
145 Pmrem(PmremHandle),
146 Node(EnvironmentNode),
147}
148
149impl Environment {
150 /// The environment read along `uv` at roughness `level`, under the
151 /// context `EnvironmentNode` gives it.
152 pub fn sample(&self, uv: NodeRef, level: NodeRef) -> NodeRef {
153 match self {
154 Self::Pmrem(pmrem) => pmrem.sample(uv, level),
155 Self::Node(node) => node.sample(uv, level),
156 }
157 }
158}
159
160/// `createRadianceContext( roughness, normalView )`'s `getUV`.
161///
162/// "Mixing the reflection with the normal is more accurate and keeps rough
163/// objects from gathering light from behind their tangent plane" — three's
164/// comment for the `pow4( roughness )` mix.
165/// `createRadianceContext( roughness, normalView )`'s reflect vector over an
166/// arbitrary normal — the anisotropic bent normal, or the clearcoat one.
167fn reflect_vector_of(normal: NodeRef) -> NodeRef {
168 reflect_vector_of_roughness(normal, roughness())
169}
170
171fn reflect_vector_of_roughness(normal: NodeRef, roughness_value: NodeRef) -> NodeRef {
172 let reflect_vec = reflect(position_view_direction().negate(), normal.clone());
173 let reflect_vec = mix(reflect_vec, normal, pow4(roughness_value)).normalize();
174 transform_direction(camera_world_matrix(), reflect_vec)
175}
176
177/// `pow4( x )` — `x.pow(4)` is three's `MathNode.POW` with an integer exponent,
178/// which it unrolls to three multiplies.
179fn pow4(x: NodeRef) -> NodeRef {
180 x.clone().mul(x.clone()).mul(x.clone()).mul(x)
181}
182
183/// `EnvironmentNode.setup()`'s two `addAssign`s, in three's order: `radiance`
184/// first, then `iblIrradiance`.
185///
186/// The two zero assignments are three's `LightingContextNode` properties being
187/// declared at their first use, which is here and not in `indirectSpecular` —
188/// so this function owns them, and `PhysicalLightingModel::indirect_specular`
189/// only writes them when there is no environment.
190pub(crate) fn setup(env: &Environment, anisotropy: bool, clearcoat: bool, out: &mut Vec<NodeRef>) {
191 let radiance_prop = crate::nodes::tsl::radiance();
192 let ibl_prop = crate::nodes::tsl::ibl_irradiance();
193
194 out.push(radiance_prop.assign(crate::nodes::tsl::vec3(0.0, 0.0, 0.0)));
195 // `const radianceNormalView = useAnisotropy ? bentNormalView : normalView`.
196 let radiance_normal = if anisotropy {
197 bent_normal_view()
198 } else {
199 normal_view()
200 };
201 let radiance = env
202 .sample(reflect_vector_of(radiance_normal), roughness())
203 .mul(material_env_intensity());
204 out.push(radiance_prop.assign(radiance_prop.add(radiance)));
205
206 out.push(ibl_prop.assign(crate::nodes::tsl::vec3(0.0, 0.0, 0.0)));
207 // `.mul( Math.PI )`: the PMREM holds radiance, and the lighting
208 // model wants irradiance.
209 let irradiance = env
210 .sample(normal_world(), float(1.0))
211 .mul(float(std::f64::consts::PI))
212 .mul(material_env_intensity());
213 out.push(ibl_prop.assign(ibl_prop.add(irradiance)));
214
215 // `EnvironmentNode`'s third `addAssign`, present only when the lighting
216 // model has a clearcoat lobe: the same radiance context over the coat's
217 // normal and roughness.
218 if clearcoat {
219 let clearcoat_prop = crate::nodes::tsl::clearcoat_radiance();
220 let radiance = env
221 .sample(
222 reflect_vector_of_roughness(clearcoat_normal_view(), clearcoat_roughness()),
223 clearcoat_roughness(),
224 )
225 .mul(material_env_intensity());
226 out.push(clearcoat_prop.assign(clearcoat_prop.add(radiance)));
227 }
228}