three_rs/materials/mod.rs
1//! Ports of `three.js/src/materials/nodes` — under `WebGPURenderer` every
2//! material is a `NodeMaterial`, so this is the only material path.
3
4pub(crate) mod blending;
5mod dfg_lut;
6pub mod environment;
7pub(crate) mod fields;
8pub mod lighting_model;
9pub(crate) mod line2;
10mod node_material;
11pub mod phong;
12pub mod physical;
13pub(crate) mod toon;
14pub mod transmission;
15
16pub use node_material::{
17 background_color_node, background_environment_color_node, background_node_color_node,
18 background_pmrem_color_node, background_vertex_node, instanced_range, output_fragment_node,
19 quad_vertex_node, render_output, setup, shadow_material, shadow_material_for,
20 tone_mapping_node, AoContext, MrtContext, OutputContext, SetupContext,
21};
22
23pub use blending::{BlendEquation, BlendFactor, BlendMode, Blending};
24
25use std::cell::Cell;
26
27use crate::math::Color;
28use crate::nodes::NodeRef;
29use crate::textures::{CubeTexture, Texture};
30
31/// `Material.id` — three.js' module-level `let _materialId = 0` counter, handed
32/// out in construction order. It is what the renderer's program cache keys a
33/// material on (`RenderObjects.get()` chains on the material object itself),
34/// so it has to behave like an object identity even though the material is a
35/// value here:
36///
37/// - every `MeshBasicNodeMaterial::new()` / `default()` gets a fresh id;
38/// - **`clone()` gets a fresh id too**, as `Material.clone()` does — `new
39/// this.constructor().copy( this )` is a new object with a new `id`. A clone
40/// that later diverges (a different `map`, say) therefore can never be
41/// served the original's program.
42///
43/// The renderer snapshots a material into its render list by cloning it, and
44/// takes the key from the source before it does, so that per-frame copy is not
45/// a new material as far as the cache is concerned.
46#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
47pub struct MaterialId(usize);
48
49impl MaterialId {
50 fn next() -> Self {
51 thread_local! {
52 static MATERIAL_ID: Cell<usize> = const { Cell::new(0) };
53 }
54 MATERIAL_ID.with(|id| {
55 let next = id.get();
56 id.set(next + 1);
57 MaterialId(next)
58 })
59 }
60
61 /// The number itself, for keying on.
62 pub fn get(&self) -> usize {
63 self.0
64 }
65}
66
67/// A fresh id, never a copy — see the type's docs.
68impl Clone for MaterialId {
69 fn clone(&self) -> Self {
70 Self::next()
71 }
72}
73
74/// `three.js/src/constants.js` sides.
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
76pub enum Side {
77 /// `FrontSide`.
78 Front,
79 /// `BackSide`.
80 Back,
81 /// `DoubleSide` — `_getPrimitiveState()` leaves `cullMode` at `'none'`, so
82 /// the front-face winding no longer matters. `BatchedText`'s material.
83 Double,
84}
85
86/// `three.js/src/constants.js` depth functions — `Material.depthFunc`, which
87/// `WebGPUPipelineUtils._getDepthCompare()` maps one-to-one onto a WebGPU
88/// compare function when `depthTest` is on.
89#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
90pub enum DepthFunc {
91 /// `NeverDepth`.
92 Never,
93 /// `AlwaysDepth`.
94 Always,
95 /// `LessDepth`.
96 Less,
97 /// `LessEqualDepth` — three's default.
98 #[default]
99 LessEqual,
100 /// `EqualDepth`.
101 Equal,
102 /// `GreaterEqualDepth`.
103 GreaterEqual,
104 /// `GreaterDepth`.
105 Greater,
106 /// `NotEqualDepth`.
107 NotEqual,
108}
109
110/// `three.js/src/constants.js` stencil functions — `Material.stencilFunc`,
111/// which `WebGPUPipelineUtils._getStencilCompare()` maps one-to-one onto a
112/// WebGPU compare function while `stencil_write` is on.
113#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
114pub enum StencilFunc {
115 /// `NeverStencilFunc`.
116 Never,
117 /// `LessStencilFunc`.
118 Less,
119 /// `EqualStencilFunc`.
120 Equal,
121 /// `LessEqualStencilFunc`.
122 LessEqual,
123 /// `GreaterStencilFunc`.
124 Greater,
125 /// `NotEqualStencilFunc`.
126 NotEqual,
127 /// `GreaterEqualStencilFunc`.
128 GreaterEqual,
129 /// `AlwaysStencilFunc` — three's default.
130 #[default]
131 Always,
132}
133
134/// `three.js/src/constants.js` stencil operations — `Material.stencilFail`,
135/// `.stencilZFail` and `.stencilZPass`, as `_getStencilOperation()` maps them.
136/// `Increment` and `Decrement` clamp, as WebGPU's `increment-clamp` and
137/// `decrement-clamp` do.
138#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
139pub enum StencilOp {
140 /// `ZeroStencilOp`.
141 Zero,
142 /// `KeepStencilOp` — three's default.
143 #[default]
144 Keep,
145 /// `ReplaceStencilOp` — writes `stencil_ref`.
146 Replace,
147 /// `IncrementStencilOp` (clamped).
148 Increment,
149 /// `DecrementStencilOp` (clamped).
150 Decrement,
151 /// `IncrementWrapStencilOp`.
152 IncrementWrap,
153 /// `DecrementWrapStencilOp`.
154 DecrementWrap,
155 /// `InvertStencilOp`.
156 Invert,
157}
158
159/// `three.js/src/constants.js` tone-mapping modes — the ones the port needs.
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
161#[non_exhaustive]
162pub enum ToneMapping {
163 /// `NoToneMapping`.
164 #[default]
165 None,
166 /// `ReinhardToneMapping`.
167 Reinhard,
168 /// `ACESFilmicToneMapping`.
169 AcesFilmic,
170 /// `LinearToneMapping` — `clamp( color * exposure, 0, 1 )`.
171 Linear,
172 /// `NeutralToneMapping` — the Khronos PBR Neutral tone mapper.
173 Neutral,
174 /// `AgXToneMapping` — Blender's AgX, through Rec. 2020.
175 AgX,
176 /// `CineonToneMapping` — Hejl and Burgess-Dawson's filmic operator,
177 /// [`cineon_tone_mapping`](crate::nodes::tsl::cineon_tone_mapping).
178 Cineon,
179}
180
181/// Which `NodeMaterial` subclass this is — i.e. which `setupLightingModel()`
182/// the fragment flow runs. three.js models it with subclasses; here the flow is
183/// one function with a `match`, so a new lighting model cannot be silently
184/// skipped in one of the setup steps.
185#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
186#[non_exhaustive]
187pub enum MaterialKind {
188 /// `MeshBasicNodeMaterial` — `BasicLightingModel`, `lights = false`.
189 #[default]
190 Basic,
191 /// `MeshPhongNodeMaterial` — `PhongLightingModel`.
192 Phong,
193 /// `MeshLambertNodeMaterial` — `new PhongLightingModel( false )`, three's
194 /// own comment being "( specular ) -> force lambert". The same flow as
195 /// [`Phong`](MaterialKind::Phong) with the Blinn-Phong specular lobe and
196 /// the two material properties that feed it removed.
197 Lambert,
198 /// `SpriteNodeMaterial` — `BasicLightingModel` like `Basic`, but it
199 /// overrides `setupPositionView()` with the billboarded quad.
200 Sprite,
201 /// `MeshStandardNodeMaterial` — `PhysicalLightingModel` with a constant
202 /// dielectric F0 of 0.04 and an F90 of 1.
203 Standard,
204 /// `MeshPhysicalNodeMaterial` — the same lighting model, but
205 /// `setupSpecular()` derives F0 from the `ior` and modulates it by
206 /// `specularColor` / `specularColorMap` / `specularIntensity`. That block
207 /// is the whole delta over `Standard`; `GLTFLoader` picks it whenever the
208 /// asset uses `KHR_materials_specular` or `KHR_materials_ior`.
209 Physical,
210 /// `PointsNodeMaterial extends SpriteNodeMaterial`. `setupVertex()` returns
211 /// `super.setupVertex()` — the plain MVP path — when `object.isPoints`, so
212 /// the sprite quad expansion is *not* taken; the only thing it keeps from
213 /// `SpriteNodeMaterial` is `setupPositionView()` and `transparent = true`.
214 Points,
215 /// `MeshNormalNodeMaterial` — no lighting model at all. It overrides
216 /// `setupDiffuseColor()` outright with the packed view-space normal, so it
217 /// takes neither the `colorNode` path nor the opacity / alpha-test /
218 /// opaque-clamp tail.
219 Normal,
220 /// `Line2NodeMaterial` — the fat line. `BasicLightingModel` like `Basic`,
221 /// plus an overridden `setupPosition()` (the screen-space quad) and
222 /// `setupDiffuseColor()` (round-cap coverage, per-end instance colour).
223 /// See `crate::materials::line2`.
224 Line2,
225 /// `MeshToonNodeMaterial` — `ToonLightingModel`: the Lambert flow with
226 /// the direct light's `dotNL` replaced by a lookup in
227 /// [`gradient_map`](MeshBasicNodeMaterial::gradient_map) (or a fixed
228 /// two-step ramp without one). See `crate::materials::toon`.
229 Toon,
230}
231
232/// Port of `MeshBasicNodeMaterial.js` + the `NodeMaterial.js` / `Material.js`
233/// fields the ladder uses. Defaults mirror three.js: white, opaque,
234/// `FrontSide`, depth test on with `LessEqualDepth`, depth write on,
235/// `reflectivity = 1`.
236///
237/// # Changing a material after its first frame
238///
239/// The renderer builds a material's shader program once and looks it up by
240/// `id` and `version` from then on (`docs/scene-graph.md`, "Program cache"),
241/// exactly as `WebGPURenderer` does. So the rule is three.js':
242///
243/// - a field the *program* depends on — any node (`color_node`,
244/// `position_node`, `fragment_node`, …), any map or `env_map`, `kind`,
245/// `lights`, `lights_node`, `lighting_model`, `environment_specular`, `flat_shading`, `fog`, `transparent`,
246/// `blending`, `alpha_to_coverage`, `world_units`, `size_attenuation`, `mask_node`, `cast_shadow_node` — needs
247/// [`set_needs_update`](Self::set_needs_update) after it changes, which is
248/// `material.needsUpdate = true`. Without it the old program keeps drawing.
249/// - a field the program reads as a **uniform** — `color`, `opacity`,
250/// `specular`, `shininess`, `emissive`, `emissive_intensity`, `metalness`,
251/// `roughness`, `bump_scale`, `rotation`, `reflectivity`, `refraction_ratio` — is uploaded every
252/// frame and needs nothing, as in three.js.
253/// - `side`, `depth_test`, `depth_write`, `color_write`, the `stencil_*`
254/// fields and the blend factors are pipeline state, keyed per draw, and need
255/// nothing either.
256/// - a map's (or `env_map`'s) filters and wrap modes need nothing: they are
257/// part of the program's cache key, read off the textures at every draw, as
258/// three's WebGPU backend reads them in `getMaterialCacheKey()`.
259#[derive(Clone, Debug)]
260pub struct MeshBasicNodeMaterial {
261 /// `Material.id`. Read-only in spirit; see [`MaterialId`] for why a clone
262 /// gets a new one.
263 pub id: MaterialId,
264 /// `Material.version` — "starts at 0 and counts how many times
265 /// `needsUpdate` is set to true". Part of the program cache key.
266 pub version: u32,
267 /// Which `NodeMaterial` subclass this stands in for — see [`MaterialKind`].
268 pub kind: MaterialKind,
269 /// `Material.color` — `MeshBasicMaterial`'s diffuse colour.
270 pub color: Color,
271 /// `Material.opacity`.
272 pub opacity: f64,
273 /// `MeshBasicMaterial.reflectivity` — the mix factor `BasicEnvironmentNode`
274 /// blends the reflected environment colour in by.
275 pub reflectivity: f64,
276 /// `MeshBasicMaterial.refractionRatio` — the index ratio
277 /// [`refract_view`](crate::nodes::tsl::refract_view) bends the view ray by
278 /// (`materialRefractionRatio`).
279 ///
280 /// 0.98 for the kinds whose three.js material has the property — Basic
281 /// ([`new`](Self::new)), [`lambert`](Self::lambert) and
282 /// [`phong`](Self::phong) — and 0 from every other constructor, whose
283 /// material has none. Three's `materialRefractionRatio` is one shared
284 /// `uniform( 0 )` that `onObjectUpdate` leaves alone when
285 /// `material.refractionRatio` is `undefined`, so such a material reads 0
286 /// until a Basic, Lambert or Phong draw writes it, and the last value
287 /// written after that; the port writes this field every draw instead.
288 pub refraction_ratio: f64,
289 /// `MeshBasicMaterial.envMap` — `setupEnvironment()` turns it into
290 /// `BasicEnvironmentNode( cubeTexture( envMap ) )`.
291 pub env_map: Option<CubeTexture>,
292 /// `MeshStandardMaterial.envMap` on a PBR material, which
293 /// `NodeMaterial.setupEnvironment()` turns into `EnvironmentNode(
294 /// pmremTexture( envMap ) )` rather than a plain cube read. The handle
295 /// comes from a
296 /// [`PmremEnvironment`](crate::nodes::pmrem_node::PmremEnvironment), which
297 /// owns the generated atlas; `scene.environment` reaches the same place by
298 /// being copied onto every material that has none of its own.
299 pub pmrem_env: Option<environment::PmremHandle>,
300 /// `NodeMaterial.colorNode` — replaces the `materialColor` uniform in
301 /// `setupDiffuseColor()`.
302 pub color_node: Option<NodeRef>,
303 /// `NodeMaterial.opacityNode` — replaces the `materialOpacity` uniform in
304 /// `setupDiffuseColor()`, so `DiffuseColor.a` is multiplied by a node's
305 /// value instead. `float( opacityNode )` narrows a wider node to its first
306 /// component, which is how `opacityNode = texture( map )` becomes
307 /// `DiffuseColor.w * texel.x`.
308 pub opacity_node: Option<NodeRef>,
309 /// `NodeMaterial.alphaTestNode` — `diffuseColor.a.lessThanEqual( node
310 /// ).discard()` at the end of `setupDiffuseColor()`.
311 ///
312 /// Takes precedence over [`alpha_test`](Self::alpha_test), as in three.
313 pub alpha_test_node: Option<NodeRef>,
314 /// `Material.alphaTest` — when positive, `setupDiffuseColor()` discards
315 /// against the `materialAlphaTest` object uniform
316 /// (`webgpu_shadowmap_pointlight`'s spheres use 0.5). The shadow pass
317 /// copies it onto its override material, so cut-away texels cast no
318 /// shadow either.
319 pub alpha_test: f64,
320 /// `Material.alphaHash` — when set, `setupDiffuseColor()` discards the
321 /// fragments whose alpha is below `getAlphaHashThreshold( positionLocal )`
322 /// (see `crate::nodes::alpha_hash`), the stochastic stand-in for
323 /// blending that `webgpu_materials_alphahash` renders.
324 pub alpha_hash: bool,
325 /// `Material.alphaMap` — `materialOpacity` becomes `opacity * texture(
326 /// alphaMap )` (`MaterialNode.OPACITY`), a `vec4` product that the alpha
327 /// assign narrows back to its `.x`. Copied onto the shadow pass's
328 /// override material like [`alpha_test`](Self::alpha_test).
329 pub alpha_map: Option<Texture>,
330 /// `NodeMaterial.emissiveNode` — `setupLighting()`'s EMISSIVE tail:
331 /// `EmissiveColor = vec3( emissiveNode )` and `outgoingLight +=
332 /// EmissiveColor`. On a Phong or Standard material the `materialEmissive`
333 /// uniform already takes that path; on an unlit `MeshBasicNodeMaterial`
334 /// this node is the only way in, which is what `webgpu_instance_uniform`
335 /// uses it for.
336 pub emissive_node: Option<NodeRef>,
337 /// `MeshPhongMaterial.specular` / `.shininess` / `.emissive` /
338 /// `.emissiveIntensity`. The dumps show all four reaching the shader as
339 /// object-group uniforms on every Phong material, even the ones the example
340 /// never sets.
341 /// `MeshPhongMaterial.specular` — the Blinn-Phong specular tint. Read by
342 /// [`Phong`](MaterialKind::Phong) only; [`Lambert`](MaterialKind::Lambert)
343 /// forces the specular lobe off.
344 pub specular: Color,
345 /// `MeshPhongMaterial.shininess` — the Blinn-Phong specular exponent.
346 pub shininess: f64,
347 /// `Material.emissive` — the uniform tail `NodeMaterial.setupLighting()`
348 /// adds to `outgoingLight` on a lit material.
349 pub emissive: Color,
350 /// `Material.emissiveIntensity` — multiplies [`emissive`](Self::emissive).
351 pub emissive_intensity: f64,
352 /// `Material.flatShading` — `NodeMaterial.setupNormal()` picks `normalFlat`
353 /// (the screen-space derivative frame) over the interpolated vertex normal,
354 /// so there is no `normal` attribute and no normal varying at all.
355 pub flat_shading: bool,
356 /// `NodeMaterial.lights`. `false` is the light spheres' material: no
357 /// lighting flow at all, `outgoingLight = DiffuseColor.rgb`.
358 pub lights: bool,
359 /// `material.lightsNode = lights( [ light1 ] )` — the selective-lights
360 /// form. Indices into `Scene.lights`, since a `PointLight` is owned by the
361 /// scene here rather than shared through an `Rc`. `None` means "every light
362 /// in the scene", which is what `LightsNode` defaults to.
363 pub lights_node: Option<Vec<usize>>,
364 /// The `lightingModel` of `material.lightsNode = lights( [ … ] ).context(
365 /// { lightingModel } )` — a user-defined
366 /// [`LightingModel`](lighting_model::LightingModel) that the `LightsNode`
367 /// drives in place of a built-in one.
368 ///
369 /// `LightingContextNode.setup()` reads `this.lightingModel ||
370 /// builder.context.lightingModel`, so the material's own
371 /// `setupLightingModel()` wins: this is read only by the kinds that have
372 /// none of their own — `Points`, `Sprite`, and `Basic` standing in for a
373 /// bare `NodeMaterial` — and ignored, as in three, by Phong, Lambert,
374 /// Standard and Physical. A program input, like `lights_node`.
375 pub lighting_model: Option<std::rc::Rc<dyn lighting_model::LightingModel>>,
376 /// Whether `PhysicalLightingModel.indirectSpecular()` reads the
377 /// environment's specular radiance. `true` is three's model.
378 ///
379 /// `false` is the patch `webgpu_postprocessing_ssr_denoise` applies to
380 /// `PhysicalLightingModel.prototype.indirectSpecular`, where screen-space
381 /// reflections supply all the specular: `builder.context.radiance =
382 /// vec3( 0 )` and, on a clearcoat model, `clearcoatRadiance.assign(
383 /// vec3( 0 ) )`, before the original method runs. The environment's
384 /// diffuse term (`iblIrradiance`) is untouched, and `EnvironmentNode`
385 /// still samples `radiance`, as three's dump does; only the read in
386 /// `indirectSpecular` becomes the zero vector. Three patches the
387 /// prototype for the whole page; the port scopes it to the material,
388 /// which the page applies to every material in the scene. Read by
389 /// Standard and Physical only, and a program input, like `lights`
390 /// (`docs/nodes.md` §89).
391 pub environment_specular: bool,
392 /// `material.maskNode` — `NodeMaterial.setupDiscard()` turns it into
393 /// `If( mask.not(), () => Discard() )` at the top of the fragment.
394 pub mask_node: Option<NodeRef>,
395 /// `material.castShadowNode` — the colour this material casts into the
396 /// shadow map's colour target, which receivers tint their shadow by when
397 /// `renderer.shadowMap.transmitted` is on (`docs/nodes.md` §43).
398 /// `Renderer._getShadowNodes()` reads its `.rgb` and `.a`.
399 pub cast_shadow_node: Option<NodeRef>,
400 /// `material.receivedShadowPositionNode` —
401 /// `ShadowBaseNode.setupShadowPosition()` assigns it to
402 /// `shadowPositionWorld` instead of `positionWorld`.
403 pub received_shadow_position_node: Option<NodeRef>,
404 /// `Material.fog` — `false` on the shadow-pass material, which is why the
405 /// shadow programs carry no fog mix even though `scene.fog` is set.
406 pub fog: bool,
407 /// `MeshStandardMaterial.metalness` / `.roughness` and the three maps the
408 /// example uses. `map` multiplies the diffuse colour; `roughnessMap` takes
409 /// its green channel and `metalnessMap` its blue, which is the glTF
410 /// packing three.js follows.
411 pub metalness: f64,
412 /// `MeshStandardMaterial.roughness`.
413 pub roughness: f64,
414 /// `Material.map` — the base colour texture; multiplies
415 /// [`color`](Self::color).
416 pub map: Option<Texture>,
417 /// `Material.vertexColors` — `setupDiffuseColor()` multiplies the diffuse
418 /// colour by `vertexColor()`, so one `LineSegments` (or one mesh) can carry
419 /// a colour per vertex instead of one per draw call. The geometry needs a
420 /// three-component `color` attribute; see
421 /// [`vertex_color`](crate::nodes::tsl::vertex_color) for the one divergence
422 /// from three's node.
423 pub vertex_colors: bool,
424 /// `MeshStandardMaterial.roughnessMap` — its green channel multiplies
425 /// [`roughness`](Self::roughness).
426 pub roughness_map: Option<Texture>,
427 /// `MeshStandardMaterial.metalnessMap` — its blue channel multiplies
428 /// [`metalness`](Self::metalness).
429 pub metalness_map: Option<Texture>,
430 /// `MeshStandardMaterial.emissiveMap` — `MaterialNode.EMISSIVE`'s
431 /// `emissiveNode.mul( texture )`, where `emissiveNode` is already
432 /// `emissive * emissiveIntensity`. The multiply is a `vec4` one in three
433 /// (`vec4( emissive, 1 ) * tex`) and the `.xyz` is taken afterwards, which
434 /// is why the port builds it the same way rather than multiplying `vec3`s.
435 pub emissive_map: Option<Texture>,
436 /// `MeshToonMaterial.gradientMap` — the ramp `ToonLightingModel` reads
437 /// the direct light's `dotNL * 0.5 + 0.5` through. Read by the `Toon`
438 /// kind only.
439 pub gradient_map: Option<Texture>,
440 /// `MeshStandardMaterial.aoMap` / `.aoMapIntensity` — `materialAO`,
441 /// `tex.r.sub( 1 ).mul( aoMapIntensity ).add( 1 )`, assigned to the
442 /// `AmbientOcclusion` property by `NodeMaterial.setupAmbientOcclusion()`.
443 /// Read by every lit mesh kind (Basic, Lambert, Phong, Toon, Standard,
444 /// Physical), as three's `aoMap` is.
445 pub ao_map: Option<Texture>,
446 /// `MeshStandardMaterial.aoMapIntensity` — multiplies
447 /// [`ao_map`](Self::ao_map)'s contribution.
448 pub ao_map_intensity: f64,
449 /// `material.lightMap` (`MeshBasicMaterial`, `MeshLambertMaterial`,
450 /// `MeshPhongMaterial`, `MeshStandardMaterial`, `MeshToonMaterial`) —
451 /// read by [`material_light_map`](crate::nodes::tsl::material_light_map)
452 /// only: three's `setupLightMap()` (an `IrradianceNode` in the lights
453 /// list) is not ported, so the material's own flow does not apply it.
454 pub light_map: Option<Texture>,
455 /// `material.lightMapIntensity`, on the same materials as
456 /// [`light_map`](Self::light_map) — the `materialLightMap` scale.
457 pub light_map_intensity: f64,
458 /// `material.specularMap` (`MeshBasicMaterial`, `MeshLambertMaterial`,
459 /// `MeshPhongMaterial`) — read by
460 /// [`material_specular_strength`](crate::nodes::tsl::material_specular_strength)
461 /// only; the Phong flow does not apply it.
462 pub specular_map: Option<Texture>,
463 /// `MeshStandardMaterial.bumpMap` / `.bumpScale` — `BumpMapNode`.
464 pub bump_map: Option<Texture>,
465 /// `MeshStandardMaterial.bumpScale` — scales [`bump_map`](Self::bump_map)'s
466 /// derivative before it perturbs the normal.
467 pub bump_scale: f64,
468 /// `MeshPhysicalMaterial`'s own fields. Nothing on this rung sets them, but
469 /// rung 10's glTF materials will: `KHR_materials_specular` is
470 /// `specularIntensity` + `specularColor`, and `ior` drives the dielectric
471 /// F0. They are carried here so the material API does not have to change
472 /// shape when `MaterialKind::Physical` arrives.
473 pub clearcoat: f64,
474 /// `MeshPhysicalMaterial.clearcoatRoughness`.
475 pub clearcoat_roughness: f64,
476 /// `MeshPhysicalMaterial.clearcoatMap` — `MaterialNode.CLEARCOAT`
477 /// multiplies `clearcoat` by the texel's red channel.
478 pub clearcoat_map: Option<Texture>,
479 /// `MeshPhysicalMaterial.clearcoatRoughnessMap` —
480 /// `MaterialNode.CLEARCOAT_ROUGHNESS` multiplies `clearcoatRoughness` by
481 /// the texel's green channel.
482 pub clearcoat_roughness_map: Option<Texture>,
483 /// `MeshPhysicalMaterial.sheen` / `.sheenColor` / `.sheenRoughness` —
484 /// `KHR_materials_sheen`. `sheen` is the intensity and `sheen_color` the
485 /// tint; `MaterialNode.SHEEN` is `sheenColor.mul( sheen )` and the shader
486 /// carries both as separate uniforms, which is why the multiply is in the
487 /// WGSL and not here.
488 ///
489 /// `sheen > 0` is `MeshPhysicalNodeMaterial.useSheen`: it is what turns the
490 /// whole sheen half of `PhysicalLightingModel` on, so a sheen colour with a
491 /// zero intensity generates exactly the shader it did before.
492 pub sheen: f64,
493 /// `MeshPhysicalMaterial.sheenColor` — the sheen lobe's tint.
494 pub sheen_color: Color,
495 /// `MeshPhysicalMaterial.sheenRoughness`.
496 pub sheen_roughness: f64,
497 /// `MeshPhysicalMaterial.diffuseRoughness` — `KHR_materials_diffuse_roughness`.
498 /// `diffuse_roughness > 0` is `MeshPhysicalNodeMaterial.useDiffuseRoughness`,
499 /// which swaps the Lambert diffuse lobe of `PhysicalLightingModel` for
500 /// the energy-preserving Oren–Nayar one (EON). `diffuseRoughnessMap` is
501 /// not ported: no graded page carries one.
502 pub diffuse_roughness: f64,
503 /// `MeshPhysicalMaterial.ior` — drives the dielectric F0 that
504 /// `setupSpecular()` derives before `specular_color` modulates it.
505 pub ior: f64,
506 /// `MeshPhysicalMaterial.specularIntensity` — `KHR_materials_specular`.
507 pub specular_intensity: f64,
508 /// `MeshPhysicalMaterial.specularColor` — `KHR_materials_specular`.
509 pub specular_color: Color,
510 /// `material.specularNode`.
511 pub specular_node: Option<NodeRef>,
512 /// `MeshStandardMaterial.normalMap` and `.normalScale`. `GLTFLoader`
513 /// flips `normalScale.y` on a geometry that has a normal map but no
514 /// `tangent` attribute (`useDerivativeTangents`), which is where Michelle's
515 /// `( 1, -1 )` comes from — it is not in the asset.
516 pub normal_map: Option<Texture>,
517 /// `Material.normalScale` — scales [`normal_map`](Self::normal_map)'s `x`
518 /// and `y` before it perturbs the surface normal.
519 pub normal_scale: crate::math::Vector2,
520 /// `MeshPhysicalMaterial.specularColorMap` — multiplies `specularColor`.
521 pub specular_color_map: Option<Texture>,
522 /// `MeshPhysicalMaterial.anisotropy` / `.anisotropyRotation` /
523 /// `.anisotropyMap` — `KHR_materials_anisotropy`. The pair reaches the
524 /// shader as one `materialAnisotropyVector` uniform,
525 /// `vec2( anisotropy * cos( rotation ), anisotropy * sin( rotation ) )`,
526 /// exactly as three's `MeshPhysicalNodeMaterial` builds it.
527 pub anisotropy: f64,
528 /// `MeshPhysicalMaterial.anisotropyRotation`, in radians.
529 pub anisotropy_rotation: f64,
530 /// `MeshPhysicalMaterial.anisotropyMap` — its red and green channels give
531 /// the per-texel anisotropy strength and rotation.
532 pub anisotropy_map: Option<Texture>,
533 /// `MeshPhysicalMaterial.iridescence` — `KHR_materials_iridescence`'s
534 /// strength. `iridescence > 0` is `MeshPhysicalNodeMaterial.useIridescence`,
535 /// the flag that turns on `evalIridescence` and the iridescent F0 in
536 /// `computeMultiscattering`, so every material with the default 0
537 /// generates exactly the shader it did before. `iridescenceMap` is not
538 /// ported: `MaterialNode.IRIDESCENCE` has no map branch in three
539 /// (`docs/nodes.md` §95).
540 pub iridescence: f64,
541 /// `MeshPhysicalMaterial.iridescenceIOR` — the thin film's index of
542 /// refraction.
543 pub iridescence_ior: f64,
544 /// `MeshPhysicalMaterial.iridescenceThicknessRange` — `[ minimum, maximum ]`
545 /// in nanometres. With no
546 /// [`iridescence_thickness_map`](Self::iridescence_thickness_map) only the
547 /// maximum is read, which is three's own behaviour, not a typo.
548 pub iridescence_thickness_range: [f64; 2],
549 /// `MeshPhysicalMaterial.iridescenceThicknessMap` — its **green** channel
550 /// interpolates the film thickness between the two ends of
551 /// [`iridescence_thickness_range`](Self::iridescence_thickness_range).
552 pub iridescence_thickness_map: Option<Texture>,
553 /// `MeshPhysicalMaterial.clearcoatNormalMap` / `.clearcoatNormalScale`.
554 /// The clearcoat lobe's own normal, through the same TBN sub-build the
555 /// base normal map uses.
556 pub clearcoat_normal_map: Option<Texture>,
557 /// `MeshPhysicalMaterial.clearcoatNormalScale` — scales
558 /// [`clearcoat_normal_map`](Self::clearcoat_normal_map)'s `x` and `y`.
559 pub clearcoat_normal_scale: crate::math::Vector2,
560 /// `MeshPhysicalMaterial.transmission` / `.thickness` /
561 /// `.attenuationDistance` / `.attenuationColor` —
562 /// `KHR_materials_transmission` and `KHR_materials_volume`. A non-zero
563 /// `transmission` moves the object into the renderer's transmission pass.
564 pub transmission: f64,
565 /// `MeshPhysicalMaterial.transmissionMap` — `MaterialNode.TRANSMISSION`
566 /// multiplies `transmission` by the texel's red channel.
567 pub transmission_map: Option<Texture>,
568 /// `MeshPhysicalMaterial.thickness` — `KHR_materials_volume`; the modelled
569 /// thickness of the transmissive medium.
570 pub thickness: f64,
571 /// `MeshPhysicalMaterial.thicknessMap` — `MaterialNode.THICKNESS`
572 /// multiplies `thickness` by the texel's green channel.
573 pub thickness_map: Option<Texture>,
574 /// `MeshPhysicalMaterial.attenuationDistance` — `KHR_materials_volume`;
575 /// the distance light travels through the medium before it is tinted by
576 /// [`attenuation_color`](Self::attenuation_color).
577 pub attenuation_distance: f64,
578 /// `MeshPhysicalMaterial.attenuationColor` — `KHR_materials_volume`.
579 pub attenuation_color: Color,
580 /// `material.normalNode` — e.g. `normalMap( texture( map ) )`.
581 pub normal_node: Option<NodeRef>,
582 /// `NodeMaterial.positionNode` — replaces `positionLocal`.
583 ///
584 /// **Deviation from r186, deliberate** (plan §5.2, `docs/nodes.md` §10):
585 /// three's `setupPosition()` assigns the instance transform *first* and
586 /// `positionNode` *after*, so `positionNode` discards the instance matrix.
587 /// The port assigns `positionNode` first and then the instance transform.
588 /// `SpriteNodeMaterial` reads it a second time in `setupPositionView()`.
589 pub position_node: Option<NodeRef>,
590 /// `SpriteNodeMaterial.scaleNode` / `.rotationNode`.
591 pub scale_node: Option<NodeRef>,
592 /// `SpriteNodeMaterial.rotationNode` — replaces the `materialRotation`
593 /// uniform.
594 pub rotation_node: Option<NodeRef>,
595 /// `PointsNodeMaterial.sizeNode` — the point size in pixels when the
596 /// material draws a [`Sprite`](crate::objects::Sprite) (instanced quads)
597 /// rather than `Points`. Read by `setupVertexSprite()` only.
598 pub size_node: Option<NodeRef>,
599 /// `PointsMaterial.size` — the `materialPointSize` uniform. Read by
600 /// [`material_point_size`](crate::nodes::tsl::material_point_size) only;
601 /// the points flow sizes a sprite by [`size_node`](Self::size_node).
602 pub size: f64,
603 /// `SpriteMaterial.rotation` — the `materialRotation` uniform.
604 pub rotation: f64,
605 /// `LineBasicMaterial.linewidth` — the `materialLineWidth` uniform.
606 ///
607 /// A hairline `Line` ignores it, as three.js says: "WebGL and WebGPU ignore
608 /// this setting and always render line primitives with a width of one
609 /// pixel". It is read by the fat-line material, which turns each segment
610 /// into a screen-space quad and so can honour a width.
611 pub linewidth: f64,
612 /// `SpriteNodeMaterial.sizeAttenuation`. `true` (the default) is the branch
613 /// that *omits* the `mvPosition.z.negate()` scale factor.
614 pub size_attenuation: bool,
615 /// `NodeMaterial.vertexNode` — replaces the whole clip-position flow.
616 pub vertex_node: Option<NodeRef>,
617 /// `NodeMaterial.fragmentNode` — replaces the whole fragment flow.
618 pub fragment_node: Option<NodeRef>,
619 /// `NodeMaterial.outputNode` — replaces only what `output.color` is written
620 /// from. The standard flow still runs and still writes the `Output`
621 /// property, so the custom node can read `DiffuseColor`, `Output` and the
622 /// normal accessors.
623 pub output_node: Option<NodeRef>,
624 /// `NodeMaterial.backdropNode` — what the diffuse light is replaced
625 /// with: `LightsNode.setup()` assigns it to `totalDiffuse` on a lit
626 /// material, `setupLighting()` makes it the outgoing light on an unlit
627 /// one. Usually a [`viewport_shared_texture`] tap — the scene behind the
628 /// object, read back. A material with one goes in the transparent list
629 /// whatever [`transparent`](Self::transparent) says, so that it draws
630 /// after what it reads.
631 ///
632 /// [`viewport_shared_texture`]: crate::nodes::display::viewport_shared_texture
633 pub backdrop_node: Option<NodeRef>,
634 /// `NodeMaterial.backdropAlphaNode` — blend [`backdrop_node`](Self::backdrop_node)
635 /// over the lit diffuse by this much instead of replacing it.
636 pub backdrop_alpha_node: Option<NodeRef>,
637 /// `NodeMaterial.mrtNode` — the material's own MRT overrides, merged over
638 /// the renderer's (the pass's) by `NodeMaterial.setup()`. Read only when a
639 /// render target with more than one colour attachment is bound, which is
640 /// what makes it inert for every material that is not drawn into one.
641 ///
642 /// `webgpu_postprocessing_bloom_selective` gives each of its fifty spheres
643 /// a material whose `mrtNode` is `mrt( { bloomIntensity: uniform( 0 or 1 )
644 /// } )`, over the pass's `mrt( { output, bloomIntensity: float( 0 ) } )`.
645 pub mrt_node: Option<crate::nodes::MrtNode>,
646 /// `MeshStandardNodeMaterial.metalnessNode` / `.roughnessNode` — the two
647 /// `setupVariants()` inputs, replacing the `materialMetalness` /
648 /// `materialRoughness` uniforms (and their maps). `webgpu_deferred`'s
649 /// resolve material reads both out of the G-buffer.
650 pub metalness_node: Option<NodeRef>,
651 /// `MeshStandardNodeMaterial.roughnessNode` — see
652 /// [`metalness_node`](Self::metalness_node).
653 pub roughness_node: Option<NodeRef>,
654 /// `NodeMaterial.depthNode` — `setupDepth()`'s value, written to the
655 /// fragment stage's `@builtin( frag_depth )` output. Set only when the
656 /// material is drawn with a depth buffer (three checks
657 /// `depthWrite || depthTest` and the target's `depthBuffer`).
658 pub depth_node: Option<NodeRef>,
659 /// `NodeMaterial.contextNode = overrideNodes( [ … ] )` — the three
660 /// accessors `webgpu_deferred`'s resolve material reads out of the
661 /// G-buffer instead of out of the geometry. See `docs/nodes.md` §27.
662 pub context_overrides: Option<crate::nodes::tsl::OverrideNodes>,
663 /// `NodeMaterial.contextNode = context( { … } )` — builder-context keys
664 /// installed for the whole of the material's setup, the way
665 /// [`context`](crate::nodes::tsl::context) installs them for one subgraph.
666 /// The keys the port reads are the ones `RetroPassNode` sets: `getUV`,
667 /// which every [`texture`](crate::nodes::tsl::texture) tap of a material
668 /// map takes in place of its default `uv()`, and `getTextureLevel`, which
669 /// turns its `textureSample` into a `textureSampleLevel`. See
670 /// `docs/nodes.md` §79.
671 pub context_node: Option<crate::nodes::ContextValue>,
672 /// `Material.side` — which face(s) are drawn.
673 pub side: Side,
674 /// `Material.visible` — `_projectObject()` skips an object whose material is
675 /// not visible.
676 pub visible: bool,
677 /// `Material.transparent` — which of the render list's two arrays the object
678 /// goes into, and so whether it is sorted front-to-back or back-to-front.
679 pub transparent: bool,
680 /// `Material.forceSinglePass` — a transparent `DoubleSide` material is
681 /// drawn once, both faces together, instead of as three's back-then-front
682 /// pair.
683 pub force_single_pass: bool,
684 /// `Material.wireframe` — only `MeshBasicMaterial` and its kin expose it.
685 /// It reaches no shader: `WebGPUUtils.getPrimitiveTopology()` turns a
686 /// wireframe `Mesh` into a `line-list`, and `Geometries.getIndex()`
687 /// swaps the geometry's index for `getWireframeIndex()`'s — each
688 /// triangle's three edges as six indices (see `Renderer`'s
689 /// `wireframe_index`).
690 pub wireframe: bool,
691 /// `Material.blending` — `NormalBlending` by default, which together with
692 /// `transparent: false` is what keeps a pipeline blend-state-free.
693 pub blending: Blending,
694 /// `Material.premultipliedAlpha` — selects the other half of the
695 /// `_getBlending()` table.
696 pub premultiplied_alpha: bool,
697 /// `Material.alphaToCoverage` — read by `builder.isOpaque()`, by
698 /// `Line2NodeMaterial`'s `alphaLine`, and by the pipeline's
699 /// `alphaToCoverageEnabled` (with more than one sample).
700 pub alpha_to_coverage: bool,
701 /// `Line2NodeMaterial.worldUnits` (`_useWorldUnits`) — the fat line's
702 /// `linewidth` is in world units rather than screen pixels. Read by
703 /// `setup()` and by `LineSegments2.raycast()`; ignored by every other
704 /// material. A program input: set it before the first frame, or call
705 /// [`set_needs_update`](Self::set_needs_update).
706 pub world_units: bool,
707 /// `Material.blendSrc` / `.blendDst` / `.blendEquation` and the three
708 /// `*Alpha` overrides (`None` is Three's `null`), read only under
709 /// `CustomBlending`.
710 pub blend_src: BlendFactor,
711 /// `Material.blendDst`.
712 pub blend_dst: BlendFactor,
713 /// `Material.blendEquation`.
714 pub blend_equation: BlendEquation,
715 /// `Material.blendSrcAlpha`.
716 pub blend_src_alpha: Option<BlendFactor>,
717 /// `Material.blendDstAlpha`.
718 pub blend_dst_alpha: Option<BlendFactor>,
719 /// `Material.blendEquationAlpha`.
720 pub blend_equation_alpha: Option<BlendEquation>,
721 /// `Material.depthTest`.
722 pub depth_test: bool,
723 /// `Material.depthWrite`.
724 pub depth_write: bool,
725 /// `Material.depthFunc` — the depth compare while `depth_test` is on.
726 pub depth_func: DepthFunc,
727 /// `Material.colorWrite` — `false` masks every colour channel
728 /// (`GPUColorWrite.NONE`), as the stencil-writing caps in
729 /// `webgpu_clipping_stencil` do. Pipeline state.
730 pub color_write: bool,
731 /// `Material.stencilWrite` — turns the stencil test and the `stencil_*`
732 /// operations on. Without it the pipeline keeps WebGPU's default stencil
733 /// face state, as `_getStencilState()` does. Takes effect only on a
734 /// renderer created with
735 /// [`RendererParameters::stencil`](crate::renderer::RendererParameters::stencil),
736 /// whose depth buffer has a stencil aspect. Pipeline state.
737 pub stencil_write: bool,
738 /// `Material.stencilWriteMask` — the pipeline's `stencilWriteMask`.
739 pub stencil_write_mask: u32,
740 /// `Material.stencilFunc` — the stencil compare.
741 pub stencil_func: StencilFunc,
742 /// `Material.stencilRef` — `setStencilReference()` for each draw.
743 pub stencil_ref: u32,
744 /// `Material.stencilFuncMask` — the pipeline's `stencilReadMask`.
745 pub stencil_func_mask: u32,
746 /// `Material.stencilFail` — the op when the stencil test fails.
747 pub stencil_fail: StencilOp,
748 /// `Material.stencilZFail` — the op when the stencil test passes and the
749 /// depth test fails.
750 pub stencil_z_fail: StencilOp,
751 /// `Material.stencilZPass` — the op when both tests pass.
752 pub stencil_z_pass: StencilOp,
753 /// `Background`'s material samples the cube map through the background
754 /// uniforms rather than an env map.
755 pub name: &'static str,
756}
757
758impl Default for MeshBasicNodeMaterial {
759 fn default() -> Self {
760 Self {
761 id: MaterialId::next(),
762 version: 0,
763 kind: MaterialKind::Basic,
764 color: Color::new(1.0, 1.0, 1.0),
765 opacity: 1.0,
766 // `MeshPhongMaterial`'s own defaults: specular 0x111111,
767 // shininess 30, emissive black, emissiveIntensity 1. `new Color(
768 // 0x111111 )` is `setHex( hex, SRGBColorSpace )`, so the stored
769 // value is the *linear* 0.0056, not 17/255 — eleven times dimmer,
770 // and visible as a blown-out highlight on any Phong material that
771 // does not override `specularNode`.
772 specular: Color::from_hex(0x111111),
773 shininess: 30.0,
774 emissive: Color::new(0.0, 0.0, 0.0),
775 emissive_intensity: 1.0,
776 flat_shading: false,
777 lights: false,
778 lights_node: None,
779 lighting_model: None,
780 environment_specular: true,
781 mask_node: None,
782 cast_shadow_node: None,
783 received_shadow_position_node: None,
784 fog: true,
785 // `MeshStandardMaterial` defaults.
786 metalness: 0.0,
787 roughness: 1.0,
788 map: None,
789 vertex_colors: false,
790 roughness_map: None,
791 metalness_map: None,
792 emissive_map: None,
793 gradient_map: None,
794 ao_map: None,
795 ao_map_intensity: 1.0,
796 light_map: None,
797 light_map_intensity: 1.0,
798 specular_map: None,
799 bump_map: None,
800 bump_scale: 1.0,
801 // `MeshPhysicalMaterial` defaults.
802 clearcoat: 0.0,
803 clearcoat_roughness: 0.0,
804 clearcoat_map: None,
805 clearcoat_roughness_map: None,
806 sheen: 0.0,
807 sheen_color: Color::new(0.0, 0.0, 0.0),
808 sheen_roughness: 1.0,
809 diffuse_roughness: 0.0,
810 ior: 1.5,
811 specular_intensity: 1.0,
812 specular_color: Color::new(1.0, 1.0, 1.0),
813 specular_node: None,
814 normal_map: None,
815 normal_scale: crate::math::Vector2::new(1.0, 1.0),
816 specular_color_map: None,
817 anisotropy: 0.0,
818 anisotropy_rotation: 0.0,
819 anisotropy_map: None,
820 iridescence: 0.0,
821 iridescence_ior: 1.3,
822 iridescence_thickness_range: [100.0, 400.0],
823 iridescence_thickness_map: None,
824 clearcoat_normal_map: None,
825 clearcoat_normal_scale: crate::math::Vector2::new(1.0, 1.0),
826 transmission: 0.0,
827 // three's `MeshPhysicalMaterial` defaults: no volume at all.
828 thickness: 0.0,
829 transmission_map: None,
830 thickness_map: None,
831 attenuation_distance: f64::INFINITY,
832 attenuation_color: Color::new(1.0, 1.0, 1.0),
833 normal_node: None,
834 position_node: None,
835 reflectivity: 1.0,
836 refraction_ratio: 0.98,
837 env_map: None,
838 pmrem_env: None,
839 color_node: None,
840 opacity_node: None,
841 alpha_test_node: None,
842 alpha_test: 0.0,
843 alpha_hash: false,
844 alpha_map: None,
845 emissive_node: None,
846 scale_node: None,
847 size_node: None,
848 size: 1.0,
849 rotation_node: None,
850 rotation: 0.0,
851 linewidth: 1.0,
852 size_attenuation: true,
853 vertex_node: None,
854 metalness_node: None,
855 roughness_node: None,
856 depth_node: None,
857 context_overrides: None,
858 context_node: None,
859 fragment_node: None,
860 output_node: None,
861 backdrop_node: None,
862 backdrop_alpha_node: None,
863 mrt_node: None,
864 side: Side::Front,
865 visible: true,
866 transparent: false,
867 force_single_pass: false,
868 wireframe: false,
869 blending: Blending::Normal,
870 premultiplied_alpha: false,
871 alpha_to_coverage: false,
872 world_units: false,
873 blend_src: BlendFactor::SrcAlpha,
874 blend_dst: BlendFactor::OneMinusSrcAlpha,
875 blend_equation: BlendEquation::Add,
876 blend_src_alpha: None,
877 blend_dst_alpha: None,
878 blend_equation_alpha: None,
879 depth_test: true,
880 depth_write: true,
881 depth_func: DepthFunc::LessEqual,
882 color_write: true,
883 stencil_write: false,
884 stencil_write_mask: 0xff,
885 stencil_func: StencilFunc::Always,
886 stencil_ref: 0,
887 stencil_func_mask: 0xff,
888 stencil_fail: StencilOp::Keep,
889 stencil_z_fail: StencilOp::Keep,
890 stencil_z_pass: StencilOp::Keep,
891 name: "",
892 }
893 }
894}
895
896impl MeshBasicNodeMaterial {
897 /// `material.dispose()` — drops this material, and nothing more. A
898 /// material is a value here and the renderer only sees per-frame clones,
899 /// so there is no count to read: what the renderer built for it ages out
900 /// once no render has drawn it for a few renders (`docs/scene-graph.md`,
901 /// "Identity and eviction"). Dropping the material does the same; this
902 /// exists so three.js code ports line for line.
903 pub fn dispose(self) {}
904
905 /// `new MeshBasicMaterial()` — a white, opaque [`Basic`](MaterialKind::Basic)
906 /// material. Equivalent to [`Default::default`].
907 pub fn new() -> Self {
908 Self::default()
909 }
910
911 /// The fields set on this material that nothing in the port reads for its
912 /// [`kind`](Self::kind), by their three.js names — the audit in
913 /// `docs/api.md` ("Material fields the port does not read"). The renderer
914 /// logs each one once per material when it builds the program; call
915 /// [`check_supported`](Self::check_supported) to fail on them instead.
916 ///
917 /// The list is the kind's declared loud fields (the per-kind table in
918 /// `src/materials/fields.rs`, which the flow dispatch in [`setup`] reads
919 /// too) that this material sets, in the table's order. A field three's
920 /// own class for that kind lacks (a `clearcoat` on a Standard material,
921 /// say) is not listed: three ignores it too.
922 pub fn unsupported_fields(&self) -> Vec<&'static str> {
923 self.kind
924 .table()
925 .loud
926 .iter()
927 .filter(|field| field.is_set(self))
928 .map(|field| field.name())
929 .collect()
930 }
931
932 /// The maps set on this material that the built-in lighting flow does not
933 /// apply but that an accessor does read: `lightMap` (three's
934 /// `setupLightMap()`, an `IrradianceNode` in the lights list, is not
935 /// ported) reaches a shader only through
936 /// [`material_light_map`](crate::nodes::tsl::material_light_map), and
937 /// Phong's `specularMap` only through
938 /// [`material_specular_strength`](crate::nodes::tsl::material_specular_strength),
939 /// in a node the application builds. Not in
940 /// [`unsupported_fields`](Self::unsupported_fields), so
941 /// [`check_supported`](Self::check_supported) passes them; the renderer
942 /// still says once per material that the flow leaves them out.
943 pub(crate) fn accessor_only_fields(&self) -> Vec<&'static str> {
944 fields::ACCESSOR_ONLY
945 .iter()
946 .filter(|field| field.is_set(self))
947 .map(|field| field.name())
948 .collect()
949 }
950
951 /// `Err(Error::Unsupported)` for the first of
952 /// [`unsupported_fields`](Self::unsupported_fields), so an application
953 /// that would rather fail than draw a material differently from three can
954 /// ask before its first frame.
955 pub fn check_supported(&self) -> Result<(), crate::Error> {
956 match self.unsupported_fields().first() {
957 Some(&field) => Err(crate::Error::Unsupported {
958 field,
959 kind: self.kind,
960 }),
961 None => Ok(()),
962 }
963 }
964
965 /// `material.needsUpdate = true`: `Material.js`' setter, which bumps
966 /// `version` so the next frame builds the program afresh. Call it after
967 /// changing anything the program depends on — the struct docs list what
968 /// does and does not.
969 pub fn set_needs_update(&mut self) {
970 self.version += 1;
971 }
972
973 /// The sampler half of `RenderObject.getMaterialCacheKey()` on the WebGPU
974 /// backend: for every texture-valued property, its `magFilter`,
975 /// `minFilter`, `wrapS` and `wrapT` (`wrapR` and `mapping` where the
976 /// texture type has them). See [`TextureSamplerKey`].
977 pub(crate) fn texture_sampler_key(&self) -> TextureSamplerKey<'_> {
978 TextureSamplerKey(self)
979 }
980
981 /// The blending fields `WebGPUPipelineUtils._getBlending()` reads, gathered
982 /// into the struct the table takes.
983 pub(crate) fn blend_mode(&self) -> BlendMode {
984 BlendMode {
985 blending: self.blending,
986 premultiplied_alpha: self.premultiplied_alpha,
987 blend_src: self.blend_src,
988 blend_dst: self.blend_dst,
989 blend_equation: self.blend_equation,
990 blend_src_alpha: self.blend_src_alpha,
991 blend_dst_alpha: self.blend_dst_alpha,
992 blend_equation_alpha: self.blend_equation_alpha,
993 }
994 }
995
996 /// `WebGPUPipelineUtils.createRenderPipeline()`'s `materialBlending`: the
997 /// blend state of the colour target, or `None` when the gate says the
998 /// pipeline gets none at all.
999 pub(crate) fn blend_state(&self) -> Option<wgpu::BlendState> {
1000 let mode = self.blend_mode();
1001 if blending::needs_blend_state(&mode, self.transparent) {
1002 blending::blending(&mode)
1003 } else {
1004 None
1005 }
1006 }
1007
1008 /// `_getStencilState()`'s face — the same on both sides, as
1009 /// `gl.stencilOp()` is — or `None` (WebGPU's default face) while
1010 /// `stencil_write` is off, as `createRenderPipeline()` leaves it.
1011 pub(crate) fn stencil_face(&self) -> Option<wgpu::StencilFaceState> {
1012 if !self.stencil_write {
1013 return None;
1014 }
1015 let op = |op: StencilOp| match op {
1016 StencilOp::Zero => wgpu::StencilOperation::Zero,
1017 StencilOp::Keep => wgpu::StencilOperation::Keep,
1018 StencilOp::Replace => wgpu::StencilOperation::Replace,
1019 StencilOp::Increment => wgpu::StencilOperation::IncrementClamp,
1020 StencilOp::Decrement => wgpu::StencilOperation::DecrementClamp,
1021 StencilOp::IncrementWrap => wgpu::StencilOperation::IncrementWrap,
1022 StencilOp::DecrementWrap => wgpu::StencilOperation::DecrementWrap,
1023 StencilOp::Invert => wgpu::StencilOperation::Invert,
1024 };
1025 Some(wgpu::StencilFaceState {
1026 compare: match self.stencil_func {
1027 StencilFunc::Never => wgpu::CompareFunction::Never,
1028 StencilFunc::Less => wgpu::CompareFunction::Less,
1029 StencilFunc::Equal => wgpu::CompareFunction::Equal,
1030 StencilFunc::LessEqual => wgpu::CompareFunction::LessEqual,
1031 StencilFunc::Greater => wgpu::CompareFunction::Greater,
1032 StencilFunc::NotEqual => wgpu::CompareFunction::NotEqual,
1033 StencilFunc::GreaterEqual => wgpu::CompareFunction::GreaterEqual,
1034 StencilFunc::Always => wgpu::CompareFunction::Always,
1035 },
1036 fail_op: op(self.stencil_fail),
1037 depth_fail_op: op(self.stencil_z_fail),
1038 pass_op: op(self.stencil_z_pass),
1039 })
1040 }
1041
1042 /// `RenderList.push()`'s choice of list: `transparent === true ||
1043 /// transmission > 0 || backdropNode` — a material that reads the frame
1044 /// has to be drawn after it.
1045 pub(crate) fn in_transparent_list(&self) -> bool {
1046 self.transparent || self.transmission > 0.0 || self.backdrop_node.is_some()
1047 }
1048
1049 /// `NodeBuilder.isOpaque()` — `transparent === false && blending ===
1050 /// NormalBlending && alphaToCoverage === false`. What decides whether
1051 /// `setupDiffuseColor()` ends with `diffuseColor.a = 1.0`.
1052 pub(crate) fn is_opaque(&self) -> bool {
1053 !self.transparent && self.blending == Blending::Normal && !self.alpha_to_coverage
1054 }
1055
1056 /// `new SpriteNodeMaterial()`. `SpriteNodeMaterial`'s constructor sets
1057 /// `transparent = true` explicitly — "In Sprites, the transparent property
1058 /// is enabled by default" — which also takes it out of `isOpaque()`, so the
1059 /// fragment flow keeps its per-fragment alpha.
1060 pub fn sprite() -> Self {
1061 Self {
1062 kind: MaterialKind::Sprite,
1063 transparent: true,
1064 refraction_ratio: 0.0,
1065 ..Self::default()
1066 }
1067 }
1068
1069 /// `new PointsNodeMaterial()`.
1070 ///
1071 /// `PointsNodeMaterial extends SpriteNodeMaterial`
1072 /// (`src/materials/nodes/PointsNodeMaterial.js`), so it inherits
1073 /// `transparent = true` — which puts a `Points` object in the *transparent*
1074 /// render list, gives its pipeline a `NormalBlending` blend state, and
1075 /// takes it out of `is_opaque` so the fragment flow
1076 /// keeps its per-fragment alpha. `alphaToCoverage` stays **off**: three.js'
1077 /// own dump of this pipeline has `alphaToCoverageEnabled: false`.
1078 pub fn points() -> Self {
1079 Self {
1080 kind: MaterialKind::Points,
1081 transparent: true,
1082 refraction_ratio: 0.0,
1083 ..Self::default()
1084 }
1085 }
1086
1087 /// `new LineBasicNodeMaterial( { color } )`.
1088 ///
1089 /// **No `MaterialKind` of its own, and that is a finding, not a shortcut.**
1090 /// `LineBasicNodeMaterial` is a bare `NodeMaterial` that only calls
1091 /// `setDefaultValues( new LineBasicMaterial() )`, and every default it
1092 /// brings that this port models — `color` white, `opacity` 1, `fog` true,
1093 /// `lights` false (`NodeMaterial`'s own default), `transparent` false — is
1094 /// already `MeshBasicNodeMaterial`'s. `linewidth` / `linecap` / `linejoin`
1095 /// are SVGRenderer-only ("WebGL and WebGPU ignore this setting and always
1096 /// render line primitives with a width of one pixel"). `vertexColors` is on
1097 /// the shared material, since `setupDiffuseColor()` is where three reads
1098 /// it — see [`MeshBasicNodeMaterial::vertex_colors`]. Three's own dump of this
1099 /// material from the d33 page (`docs/lines/LineBasicNodeMaterial_27.*`) is
1100 /// the `Basic` program statement for statement, so a second kind would
1101 /// generate identical WGSL.
1102 ///
1103 /// What makes a line a line is the *object*, not the material:
1104 /// `WebGPUUtils.getPrimitiveTopology( object, material )` reads
1105 /// `object.isLine` / `object.isLineSegments`.
1106 pub fn line(color: Color) -> Self {
1107 Self {
1108 color,
1109 refraction_ratio: 0.0,
1110 ..Self::default()
1111 }
1112 }
1113
1114 /// `new Line2NodeMaterial( { color, linewidth, vertexColors } )` — the
1115 /// fat line.
1116 ///
1117 /// `Line2NodeMaterial.setDefaultValues( new LineBasicMaterial() )` and then
1118 /// `this.blending = NoBlending` — three sets it in the constructor because
1119 /// the material writes its own coverage through the `discard` and must not
1120 /// have the result blended a second time. That default has teeth here: it
1121 /// makes `is_opaque` false, so the fragment flow does
1122 /// **not** emit `DiffuseColor.w = 1.0` (`docs/nodes.md` §8).
1123 ///
1124 /// `this._useAlphaToCoverage = true` is the constructor's other default,
1125 /// so `alpha_to_coverage` starts true; `webgpu_lines_fat` turns it off.
1126 pub fn line2(color: Color) -> Self {
1127 Self {
1128 kind: MaterialKind::Line2,
1129 color,
1130 blending: Blending::No,
1131 alpha_to_coverage: true,
1132 refraction_ratio: 0.0,
1133 ..Self::default()
1134 }
1135 }
1136
1137 /// `new MeshNormalNodeMaterial()` — `MeshNormalMaterial` under
1138 /// `WebGPURenderer`.
1139 ///
1140 /// The whole subclass is one overridden `setupDiffuseColor()`:
1141 /// `diffuseColor = colorSpaceToWorking( vec4( packNormalToRGB( normalView
1142 /// ), opacity ), SRGBColorSpace )`. Nothing else about it differs from a
1143 /// `MeshBasicNodeMaterial`, so it is a [`MaterialKind`] rather than a type.
1144 pub fn normal() -> Self {
1145 Self {
1146 kind: MaterialKind::Normal,
1147 refraction_ratio: 0.0,
1148 ..Self::default()
1149 }
1150 }
1151
1152 /// `new MeshPhongNodeMaterial( { color } )`. `NodeMaterial.lights` is true
1153 /// for every lit material, which is what puts the `LightsNode` flow in the
1154 /// fragment stage.
1155 pub fn phong(color: Color) -> Self {
1156 Self {
1157 kind: MaterialKind::Phong,
1158 color,
1159 lights: true,
1160 ..Self::default()
1161 }
1162 }
1163
1164 /// `new MeshLambertNodeMaterial( { color } )`.
1165 ///
1166 /// `MeshLambertMaterial`'s own defaults over `Material`'s are all shared
1167 /// with the Phong ones the struct already carries, so the constructor is
1168 /// the Phong one under a different [`MaterialKind`].
1169 pub fn lambert(color: Color) -> Self {
1170 Self {
1171 kind: MaterialKind::Lambert,
1172 color,
1173 lights: true,
1174 ..Self::default()
1175 }
1176 }
1177}
1178
1179impl MeshBasicNodeMaterial {
1180 /// `new MeshToonNodeMaterial( { color, gradientMap } )`.
1181 ///
1182 /// `MeshToonMaterial`'s defaults over `Material`'s — white, `emissive`
1183 /// black at intensity 1, no maps — are all ones the struct already
1184 /// carries, and `lights = true` is the constructor's own.
1185 pub fn toon(color: Color, gradient_map: Option<Texture>) -> Self {
1186 Self {
1187 kind: MaterialKind::Toon,
1188 color,
1189 gradient_map,
1190 lights: true,
1191 refraction_ratio: 0.0,
1192 ..Self::default()
1193 }
1194 }
1195
1196 /// `new MeshStandardNodeMaterial( { color, roughness, metalness } )`.
1197 pub fn standard(color: Color, roughness: f64, metalness: f64) -> Self {
1198 Self {
1199 kind: MaterialKind::Standard,
1200 color,
1201 roughness,
1202 metalness,
1203 lights: true,
1204 refraction_ratio: 0.0,
1205 ..Self::default()
1206 }
1207 }
1208
1209 /// `new MeshPhysicalNodeMaterial()` — a Standard material plus
1210 /// `setupSpecular()`'s ior/specular block. `GLTFLoader` builds one whenever
1211 /// the asset declares `KHR_materials_specular` or `KHR_materials_ior`.
1212 pub fn physical(color: Color, roughness: f64, metalness: f64) -> Self {
1213 Self {
1214 kind: MaterialKind::Physical,
1215 ..Self::standard(color, roughness, metalness)
1216 }
1217 }
1218}
1219
1220/// three.js' name for a `NodeMaterial` whose kind is `Phong`. The struct is
1221/// shared because `WebGPURenderer` treats every material as a `NodeMaterial`
1222/// and the renderer must hold them in one list.
1223pub type MeshPhongNodeMaterial = MeshBasicNodeMaterial;
1224
1225/// three.js' name for a `NodeMaterial` whose kind is `Lambert`. The struct is
1226/// shared for the reason [`MeshPhongNodeMaterial`] is.
1227pub type MeshLambertNodeMaterial = MeshBasicNodeMaterial;
1228
1229/// three.js' name for a `NodeMaterial` whose kind is `Toon` — see
1230/// [`MeshBasicNodeMaterial::toon`].
1231pub type MeshToonNodeMaterial = MeshBasicNodeMaterial;
1232
1233/// three.js' name for a `NodeMaterial` whose kind is `Sprite`.
1234pub type SpriteNodeMaterial = MeshBasicNodeMaterial;
1235/// three.js' name for a `NodeMaterial` whose kind is `Points`.
1236pub type PointsNodeMaterial = MeshBasicNodeMaterial;
1237/// three.js' name for a `NodeMaterial` whose kind is `Standard` — one struct,
1238/// one renderer list.
1239pub type MeshStandardNodeMaterial = MeshBasicNodeMaterial;
1240/// three.js' name for a `NodeMaterial` whose kind is `Physical` — see
1241/// [`MeshBasicNodeMaterial::physical`].
1242pub type MeshPhysicalNodeMaterial = MeshBasicNodeMaterial;
1243
1244/// three.js' name for a `NodeMaterial` whose kind is `Normal` — see
1245/// [`MeshBasicNodeMaterial::normal`].
1246pub type MeshNormalNodeMaterial = MeshBasicNodeMaterial;
1247
1248/// three.js' name for a `NodeMaterial` whose kind is `Line2` — see
1249/// [`MeshBasicNodeMaterial::line2`] and [`crate::addons::lines`].
1250pub type Line2NodeMaterial = MeshBasicNodeMaterial;
1251
1252/// three.js' name for the `NodeMaterial` a `Line` / `LineSegments` draws with.
1253/// It carries no state of its own — see [`MeshBasicNodeMaterial::line`].
1254pub type LineBasicNodeMaterial = MeshBasicNodeMaterial;
1255
1256/// What [`MeshBasicNodeMaterial::texture_sampler_key`] hashes: the sampler
1257/// state of every texture the material holds as a property, which is what
1258/// `RenderObject.getMaterialCacheKey()` appends for each `value.isTexture`
1259/// when `renderer.backend.isWebGPUBackend`:
1260///
1261/// ```js
1262/// valueKey += value.mapping;
1263/// valueKey += value.magFilter;
1264/// valueKey += value.minFilter;
1265/// valueKey += value.wrapS;
1266/// valueKey += value.wrapT;
1267/// valueKey += value.wrapR;
1268/// ```
1269///
1270/// They reach the generated WGSL. `NearestFilter` on both filters makes a map
1271/// unfilterable (`isUnfilterable()`): bound `non-filtering`, no sampler, every
1272/// tap a `textureLoad`. And that `textureLoad` wraps its coordinate through
1273/// `generateWrapFunction()`'s `tsl_coord_<s>S_<t>T_2d`, named after the wrap
1274/// pair. A program built before the change is the wrong program after it
1275/// (issue #276).
1276///
1277/// The renderer hashes this into the dynamic half of a draw's cache key at
1278/// every draw, rather than having the `Texture` setters bump
1279/// [`version`](MeshBasicNodeMaterial::version), for three reasons. A texture
1280/// is a shared handle with no way back to the materials that hold it, so a
1281/// setter has no material to bump. It is what three does: the state is read
1282/// off the texture when the key is computed, never pushed into the material.
1283/// And a key keeps both programs: a map toggled between `Linear` and
1284/// `Nearest` finds each in the cache after the first time, where a version
1285/// bump would throw the material's programs away on every toggle.
1286///
1287/// Like three's, it covers the material's own texture properties only, not a
1288/// `texture()` node inside `color_node` or another graph: those are values
1289/// of the node, not of the material. Each property is hashed as `None` or
1290/// its state, so the key is positional, as three's comma-joined string is.
1291pub(crate) struct TextureSamplerKey<'a>(&'a MeshBasicNodeMaterial);
1292
1293impl std::hash::Hash for TextureSamplerKey<'_> {
1294 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1295 let m = self.0;
1296 m.env_map
1297 .as_ref()
1298 .map(|t| {
1299 let t = t.borrow();
1300 (t.mapping, t.mag_filter, t.min_filter)
1301 })
1302 .hash(state);
1303 for map in [
1304 &m.alpha_map,
1305 &m.map,
1306 &m.roughness_map,
1307 &m.metalness_map,
1308 &m.emissive_map,
1309 &m.gradient_map,
1310 &m.ao_map,
1311 &m.light_map,
1312 &m.specular_map,
1313 &m.bump_map,
1314 &m.clearcoat_map,
1315 &m.clearcoat_roughness_map,
1316 &m.normal_map,
1317 &m.specular_color_map,
1318 &m.anisotropy_map,
1319 &m.iridescence_thickness_map,
1320 &m.clearcoat_normal_map,
1321 &m.transmission_map,
1322 &m.thickness_map,
1323 ] {
1324 map.as_ref()
1325 .map(|t| {
1326 let t = t.borrow();
1327 (t.mag_filter, t.min_filter, t.wrap_s, t.wrap_t)
1328 })
1329 .hash(state);
1330 }
1331 }
1332}