three-rs 0.3.0

A port of three.js core and its WebGPURenderer to Rust on wgpu, graded against three.js's own end-to-end pixel comparison.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Port of `three.js/src/nodes/functions/BSDF/BRDF_Lambert.js`,
//! `BRDF_BlinnPhong.js`, `F_Schlick.js`, `D_BlinnPhong.js` and
//! `PhongLightingModel.js`, plus the `LightsNode` per-light loop body for a
//! `PointLight`.
//!
//! Every statement here is read off the dump of `webgpu_lights_phong`'s three
//! Phong programs (`docs/rung5-progress.md` §4 quotes the WGSL); the node graph
//! below is arranged to emit exactly that.

#![allow(dead_code)] // wired into `setup()` by the next step of rung 5

use crate::lights::{
    point_shadow, point_shadow_filtered, LightKind, ShadowFilter, ShadowFilterInputs,
    ShadowFilterMap,
};
use crate::nodes::tsl::*;
use crate::nodes::{NodeRef, Type};
use crate::textures::{CubeDepthTexture, DepthTexture};

/// `1 / π` — three.js' `RECIPROCAL_PI`, which prints as
/// `0.3183098861837907` in the dumps.
pub(crate) const RECIPROCAL_PI: f64 = std::f64::consts::FRAC_1_PI;

/// `getDistanceAttenuation( lightDistance, cutoffDistance, decayExponent )` —
/// the whole thing, including the `if ( cutoffDistance > 0.0 ) { … } else { … }`
/// over a shared temp that the dump shows. `cutoffDistance` is a uniform, so the
/// branch stays in the shader; `Node::Select` already lowers to exactly that
/// shape (`builder.rs`' `Node::Select` arm), so no new node variant is needed.
pub fn distance_attenuation(
    light_distance: NodeRef,
    cutoff_distance: NodeRef,
    decay: NodeRef,
) -> NodeRef {
    cutoff_distance.greater_than(0.0).select(
        distance_attenuation_with_cutoff(
            light_distance.clone(),
            cutoff_distance.clone(),
            decay.clone(),
        ),
        distance_attenuation_no_cutoff(light_distance, decay),
    )
}

/// The `cutoffDistance > 0` branch: inverse-square falloff times the smooth
/// window `clamp( 1 - ( d / cutoff )^4, 0, 1 )^2`.
pub(crate) fn distance_attenuation_with_cutoff(
    light_distance: NodeRef,
    cutoff_distance: NodeRef,
    decay: NodeRef,
) -> NodeRef {
    let t = light_distance.clone().div(cutoff_distance);
    let f = float(1.0)
        .sub(t.clone().mul(t.clone()).mul(t.clone()).mul(t))
        .clamp(0.0, 1.0);
    float(1.0)
        .div(max(light_distance.pow(decay), float(0.01)))
        .mul(f.clone().mul(f))
}

/// `getDistanceAttenuation` with `cutoffDistance == 0`.
pub(crate) fn distance_attenuation_no_cutoff(light_distance: NodeRef, decay: NodeRef) -> NodeRef {
    float(1.0).div(max(light_distance.pow(decay), float(0.01)))
}

/// `BRDF_Lambert( { diffuseColor } )` — `RECIPROCAL_PI * diffuseColor`.
pub fn brdf_lambert(diffuse: NodeRef) -> NodeRef {
    diffuse.mul(RECIPROCAL_PI)
}

/// `F_Schlick( { f0, f90, dotVH } )` with three.js' `exp2` approximation of
/// `pow( 1 - dotVH, 5 )`.
pub fn f_schlick(f0: NodeRef, f90: NodeRef, dot_vh: NodeRef) -> NodeRef {
    let fresnel = exp2(dot_vh.clone().mul(-5.55473).sub(6.98316).mul(dot_vh));
    f0.mul(float(1.0).sub(fresnel.clone()))
        .add(f90.mul(fresnel))
}

/// `D_BlinnPhong( { shininess, dotNH } )` —
/// `RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess )`.
pub(crate) fn d_blinn_phong(shininess_value: NodeRef, dot_nh: NodeRef) -> NodeRef {
    shininess_value
        .clone()
        .mul(0.5)
        .add(1.0)
        .mul(RECIPROCAL_PI)
        .mul(dot_nh.pow(shininess_value))
}

/// `BRDF_BlinnPhong( { lightDirection, specularColor, shininess } )`.
pub(crate) fn brdf_blinn_phong(light_direction: NodeRef) -> NodeRef {
    let half_dir = light_direction.add(position_view_direction()).normalize();
    let dot_nh = normal_view().dot(half_dir.clone()).clamp(0.0, 1.0);
    let dot_vh = position_view_direction().dot(half_dir).clamp(0.0, 1.0);

    let f = f_schlick(specular_color(), float(1.0), dot_vh);
    // `G_BlinnPhong_Implicit()` is the constant 0.25.
    f.mul(0.25).mul(d_blinn_phong(shininess(), dot_nh))
}

/// One light's shadow as the material setup sees it: `ShadowNode`'s 2-D
/// depth texture for a spot or directional light, `PointShadowNode`'s cube
/// for a point light — each read through the filter
/// `renderer.shadowMap.type` (or the light's `shadow.filterNode`) picks — or
/// the light's own `shadow.shadowNode`.
#[derive(Clone, Debug)]
#[doc(hidden)]
pub enum ShadowMap {
    /// A planar depth map through `PCFShadowFilter` — the default type.
    Planar(DepthTexture),
    /// A cube depth map through `PointShadowFilter` — the default type.
    Cube(CubeDepthTexture),
    /// Any map through any filter: `BasicShadowMap`, `VSMShadowMap` (whose
    /// map is the `VSMHorizontal` moments) or `shadow.filterNode`.
    Filtered {
        map: ShadowFilterMap,
        filter: ShadowFilter,
    },
    /// `light.shadow.shadowNode` — `AnalyticLightNode.setupShadow()` uses
    /// it as the shadow factor in place of a `ShadowNode`, so no shadow
    /// position is assigned and no map is rendered.
    Node(NodeRef),
    /// `renderer.shadowMap.transmitted`: a spot or directional light's
    /// depth map (`Planar` or a non-cube `Filtered`) plus the colour target
    /// the shadow pass wrote each caster's `castShadowNode` into, which
    /// tints the shadow (`ShadowNode.setupShadow()`'s `shadowColor` branch).
    Transmitted {
        map: Box<ShadowMap>,
        color: crate::textures::Texture,
    },
    /// `builtinShadowContext( shadow, light )` on the pass drawing the
    /// receiver, for this light: `getShadow` returns `shadowColorNode.mul(
    /// shadow )`, so the light's colour is multiplied by `map`'s factor and
    /// then by `shadow`. The renderer wraps only a light's own map in it,
    /// never another `Context`.
    Context {
        map: Box<ShadowMap>,
        shadow: NodeRef,
    },
}

/// By identity, as a texture contributes its `uuid` to `Node.getCacheKey()`:
/// the map's kind and which map it is are what the program depends on.
impl std::hash::Hash for ShadowMap {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        std::mem::discriminant(self).hash(state);
        match self {
            ShadowMap::Planar(texture) => texture.id().hash(state),
            ShadowMap::Cube(texture) => texture.id().hash(state),
            ShadowMap::Filtered { map, filter } => {
                map.hash(state);
                filter.hash(state);
            }
            ShadowMap::Node(node) => node.key().hash(state),
            ShadowMap::Transmitted { map, color } => {
                map.hash(state);
                color.id().hash(state);
            }
            ShadowMap::Context { map, shadow } => {
                map.hash(state);
                shadow.key().hash(state);
            }
        }
    }
}

/// One entry of `LightsNode`'s light list, as the material setup sees it.
///
/// `Hash` is the light's share of the render object's dynamic cache key
/// (`RenderObject.getDynamicCacheKey()` → `lightsNode.getCacheKey()`).
#[derive(Clone, Debug, Hash)]
#[doc(hidden)]
pub struct LightDesc {
    /// The light's index in the renderer's light list, which is what every
    /// `UniformSource::Light*` / `Shadow*` variant keys on.
    pub index: usize,
    pub kind: LightKind,
    /// `light.castShadow && object.receiveShadow && renderer.shadowMap.enabled`
    /// — the shadow map, read with `textureSampleCompare`.
    pub shadow_map: Option<ShadowMap>,
}

/// `ShadowBaseNode.setupShadowPosition()` (a statement, pushed here) followed
/// by the shadow node itself — `ShadowNode` or `PointShadowNode` by map.
pub(crate) fn shadow_node(
    index: usize,
    map: &ShadowMap,
    received_shadow_position: Option<&NodeRef>,
    out: &mut Vec<NodeRef>,
) -> NodeRef {
    if let ShadowMap::Node(node) = map {
        return node.clone();
    }
    let position = match received_shadow_position {
        Some(node) => node.clone(),
        None => position_world(),
    };
    out.push(shadow_position_world().assign(position));
    match map {
        ShadowMap::Planar(map) => shadow_factor(index, map),
        ShadowMap::Cube(map) => point_shadow(index, map),
        ShadowMap::Filtered {
            map: ShadowFilterMap::Cube(map),
            filter,
        } => point_shadow_filtered(index, map, filter),
        ShadowMap::Filtered { map, filter } => shadow_factor_filtered(index, map, filter),
        ShadowMap::Transmitted { map, color } => match &**map {
            ShadowMap::Planar(depth) => shadow_factor_transmitted(
                index,
                &ShadowFilterMap::Depth(depth.clone()),
                &ShadowFilter::Pcf,
                Some(color),
            ),
            ShadowMap::Filtered { map, filter } if !matches!(map, ShadowFilterMap::Cube(_)) => {
                shadow_factor_transmitted(index, map, filter, Some(color))
            }
            _ => unreachable!("three-rs: only a planar shadow map carries a colour target"),
        },
        ShadowMap::Node(_) => unreachable!("three-rs: returned above"),
        ShadowMap::Context { .. } => {
            unreachable!("three-rs: `setup_light` unwraps the shadow context")
        }
    }
}

/// `LightsNode.setupLightsNode()`'s per-light half that every lighting model
/// shares: an ambient, hemisphere or probe light adds straight to
/// `irradiance` and yields nothing; an analytic light yields `LightNode.setup()`'s
/// `( lightDirection, lightColor )` pair — shadow factor included — for the
/// model's `direct()`.
pub(crate) fn setup_light(
    light: &LightDesc,
    received_shadow_position: Option<&NodeRef>,
    out: &mut Vec<NodeRef>,
) -> Option<(NodeRef, NodeRef)> {
    let index = light.index;

    match light.kind {
        // `AmbientLightNode.setup()` — `irradiance += lightColor`.
        LightKind::Ambient => {
            out.push(irradiance().assign(irradiance().add(light_color_intensity(index))));
            return None;
        }
        // `HemisphereLightNode.setup()`: a sky/ground mix by the world
        // normal's hemisphere weight.
        LightKind::Hemisphere => {
            let light_direction = light_world_position(index).normalize();
            let dot_nl = normal_world().dot(light_direction);
            let hemi_diffuse_weight = dot_nl.mul(0.5).add(0.5);
            let value = mix(
                light_ground_color(index),
                light_color_intensity(index),
                hemi_diffuse_weight,
            );
            out.push(irradiance().assign(irradiance().add(value)));
            return None;
        }
        // `LightProbeNode.setup()` — `irradiance += getShIrradianceAt(
        // normalWorld, lightProbe )`, the coefficients already scaled by the
        // intensity on the CPU.
        LightKind::Probe => {
            let value = get_sh_irradiance_at(normal_world(), &light_probe_sh(index));
            out.push(irradiance().assign(irradiance().add(value)));
            return None;
        }
        _ => {}
    }

    // `AnalyticLightNode.setupShadow()`'s `colorNode = colorNode.mul( shadow )`
    // — before the light's own attenuation.
    let mut color = light_color_intensity(index);
    if let Some(map) = &light.shadow_map {
        let (map, context) = match map {
            ShadowMap::Context { map, shadow } => (&**map, Some(shadow)),
            map => (map, None),
        };
        color = color.mul(shadow_node(index, map, received_shadow_position, out));
        // `builder.context.getShadow( this, builder )` —
        // `builtinShadowContext`'s `shadowColorNode.mul( shadowNode )`.
        if let Some(shadow) = context {
            color = color.mul(shadow.clone());
        }
    }

    Some(match light.kind {
        LightKind::Ambient | LightKind::Hemisphere | LightKind::Probe => {
            unreachable!("three-rs: the irradiance-only lights are summed above")
        }
        LightKind::Point => {
            let l_vector = light_view_position(index).sub(position_view());
            let attenuation = distance_attenuation(
                length(l_vector.clone()),
                light_cutoff_distance(index),
                light_decay(index),
            );
            (l_vector.normalize(), color.mul(attenuation))
        }
        LightKind::Spot => {
            let l_vector = light_view_position(index).sub(position_view());
            let light_direction = l_vector.clone().normalize();
            let angle_cos = light_direction.clone().dot(light_target_direction(index));
            let spot_attenuation =
                smoothstep(light_cone_cos(index), light_penumbra_cos(index), angle_cos);
            let attenuation = distance_attenuation(
                length(l_vector),
                light_cutoff_distance(index),
                light_decay(index),
            );
            (
                light_direction,
                color.mul(spot_attenuation).mul(attenuation),
            )
        }
        LightKind::Directional => (light_target_direction(index), color),
    })
}

/// `ShadowNode.setupShadowCoord()` + `setupShadowFilter()` + the
/// `mix( 1, shadow, intensity )` of `setupShadow()`, for the light at `index`.
///
/// `shadowPositionWorld` must already have been assigned — that is
/// `ShadowBaseNode.setupShadowPosition()`, which the caller pushes because it is
/// a statement rather than an expression.
pub(crate) fn shadow_factor(index: usize, map: &DepthTexture) -> NodeRef {
    shadow_factor_filtered(
        index,
        &ShadowFilterMap::Depth(map.clone()),
        &ShadowFilter::Pcf,
    )
}

/// [`shadow_factor`] through a given filter and the texture it reads.
pub(crate) fn shadow_factor_filtered(
    index: usize,
    map: &ShadowFilterMap,
    filter: &ShadowFilter,
) -> NodeRef {
    shadow_factor_transmitted(index, map, filter, None)
}

/// [`shadow_factor_filtered`], and with `color` — the shadow pass's colour
/// target under `renderer.shadowMap.transmitted` — tinted by what the casters
/// wrote there:
///
/// ```js
/// shadowColor = texture( shadowMap.texture, shadowCoord );
/// shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
/// ```
///
/// Where nothing was cast the target keeps its `( 0, 0, 0, 0 )` clear, so
/// the alpha zeroes the weight and the light is untouched; where a caster is
/// the nearest surface the depth test passes and the inner mix is 1.
///
/// **Divergence** (`docs/nodes.md` §43): the output is a `vec4` in three, and
/// `lightColor.mul( shadow )` then widens the whole direct term to `vec4`
/// (`vec4( lightColor, 1 ) * shadow`, and `( vec4( directDiffuse, 1 ) + … ).xyz`
/// in the dump). The port takes the `.xyz` here, so the light colour stays a
/// `vec3`; the three channels are the same numbers.
pub(crate) fn shadow_factor_transmitted(
    index: usize,
    map: &ShadowFilterMap,
    filter: &ShadowFilter,
    color: Option<&crate::textures::Texture>,
) -> NodeRef {
    // `shadowPosition = shadowMatrix * vec4( shadowPositionWorld +
    // normalWorld * normalBias, 1 )`.
    let position = shadow_matrix(index).mul(vec4_join(vec![
        shadow_position_world().add(normal_world().mul(shadow_normal_bias(index))),
        float(1.0),
    ]));

    // `setupShadowCoord`: the perspective divide, then the Y flip WebGPU needs
    // and `bias` added to the depth. Both cameras take this branch —
    // `logarithmicDepthBuffer` is off.
    let divided = position.clone().xyz().div(position.w());
    let coord = vec3_join(vec![
        divided.clone().x(),
        float(1.0).sub(divided.clone().y()),
        divided.z().add(shadow_bias(index)),
    ]);

    // `setupShadowFilter`'s frustum test. Note there is no `z >= 0` term.
    let frustum_test = coord
        .clone()
        .x()
        .greater_than_equal(float(0.0))
        .and(coord.clone().x().less_than_equal(float(1.0)))
        .and(coord.clone().y().greater_than_equal(float(0.0)))
        .and(coord.clone().y().less_than_equal(float(1.0)))
        .and(coord.clone().z().less_than_equal(float(1.0)));

    let filtered = filter.apply(&ShadowFilterInputs {
        index,
        map: map.clone(),
        shadow_coord: coord.clone(),
        dp: None,
    });
    let shadow = frustum_test.select(filtered, float(1.0));

    match color {
        None => mix(float(1.0), shadow, shadow_intensity(index)),
        Some(color) => {
            let shadow_color = texture_uv(color, coord.xy());
            let tinted = mix(
                shadow_color.clone(),
                vec4(1.0, 1.0, 1.0, 1.0),
                shadow.to(Type::Vec4),
            );
            mix(
                vec4(1.0, 1.0, 1.0, 1.0),
                tinted,
                shadow_intensity(index).mul(shadow_color.w()),
            )
            .xyz()
        }
    }
}

/// `AmbientLightNode.setup()` — `irradiance += lightColor`, no attenuation.
/// The first one's assign emits `irradiance`'s zero initialiser above it.
pub(crate) fn ambient_lights(indices: &[usize], out: &mut Vec<NodeRef>) {
    for index in indices {
        out.push(irradiance().assign(irradiance().add(light_color_intensity(*index))));
    }
}

/// One direct light's contribution: its `lightDirection` / `lightColor` pair
/// (including the shadow factor when it casts one) fed through
/// `PhongLightingModel.direct()`.
///
/// `specular` is `PhongLightingModel`'s own constructor flag:
/// `MeshLambertNodeMaterial.setupLightingModel()` returns
/// `new PhongLightingModel( false )` — "( specular ) -> force lambert" — and
/// the `if ( this.specular === true )` around the `directSpecular` accumulation
/// is the whole difference between the two materials' direct term.
pub(crate) fn direct_light(
    light: &LightDesc,
    received_shadow_position: Option<&NodeRef>,
    specular: bool,
    out: &mut Vec<NodeRef>,
) {
    let Some((light_direction, light_color)) = setup_light(light, received_shadow_position, out)
    else {
        return;
    };

    // `irradiance = dotNL * lightColor`, clamped — `getLightingIrradiance`.
    let dot_nl = normal_view().dot(light_direction.clone()).clamp(0.0, 1.0);
    let irr = dot_nl.mul(light_color);

    // `PhongLightingModel.direct()`.
    out.push(
        direct_diffuse()
            .assign(direct_diffuse().add(irr.clone().mul(brdf_lambert(diffuse_color().xyz())))),
    );
    if specular {
        out.push(
            direct_specular()
                .assign(direct_specular().add(irr.mul(brdf_blinn_phong(light_direction)).mul(1.0))),
        );
    }
}