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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
//! Port of `three.js/src/renderers/common/RenderList.js` plus
//! `Renderer._projectObject()` — the scene walk that turns a tree of
//! [`Object3D`](crate::core::Object3D) nodes into the ordered lists
//! `Renderer.render()` draws.
//!
//! This is the whole of the renderer that is GPU-free, so it is unit-tested
//! directly (`cargo test -p three-rs --lib`).

use std::cmp::Ordering;
use std::rc::Rc;

use crate::cameras::RenderCamera;
use crate::core::{Group, Layers, Object3D, ObjectRef};
use crate::materials::MeshBasicNodeMaterial;
use crate::math::{CoordinateSystem, Frustum, Matrix4};
use crate::nodes::clipping::{ClippingContext, ClippingView};
use crate::objects::Payload;

/// One entry of `RenderList.opaque` / `RenderList.transparent`.
///
/// three.js' render item also carries `geometry` and `material`, which are
/// reachable through `node.borrow().mesh()` (for a multi-material mesh,
/// through [`material`](Self::material) and [`group`](Self::group)).
#[derive(Clone)]
pub(crate) struct RenderItem {
    /// `renderItem.object`.
    pub node: ObjectRef,
    /// `renderItem.id` — `object.id`, the final sort tie-break.
    pub id: u32,
    /// `renderItem.groupOrder` — the `renderOrder` of the nearest `Group`
    /// ancestor, 0 at the scene root.
    pub group_order: f64,
    /// `renderItem.renderOrder` — `object.renderOrder`.
    pub render_order: f64,
    /// `renderItem.z` — the geometry's bounding-sphere centre in clip space,
    /// unnormalised (three.js keeps `Vector4.z`, with no perspective divide).
    pub z: f64,
    /// `object.matrixWorld` at the time of the walk.
    pub matrix_world: Matrix4,
    /// `renderItem.group` — the `geometry.groups` entry this item draws, for
    /// an object whose `material` is an array; `None` (three's `null`) for
    /// every other object. Its `material_index` picks the item's material and
    /// its `start` / `count` clip the draw range
    /// (`RenderObject.getDrawParameters()`).
    pub group: Option<Group>,
    /// `renderItem.clippingContext` — the planes of the `ClippingGroup`s
    /// above the object, in view space. `None` when no group clips it.
    pub clipping: Option<Rc<ClippingContext>>,
}

impl RenderItem {
    /// `renderItem.material` — `material[ group.materialIndex ]` for a group
    /// item, `object.material` otherwise. `object` is this item's node,
    /// borrowed.
    pub fn material<'a>(&self, object: &'a Object3D) -> Option<&'a MeshBasicNodeMaterial> {
        match self.group {
            Some(group) => object.payload.material_array().get(group.material_index),
            None => object.material(),
        }
    }
}

/// `painterSortStable( a, b )`.
fn painter_sort_stable(a: &RenderItem, b: &RenderItem) -> Ordering {
    compare(a.group_order, b.group_order)
        .then_with(|| compare(a.render_order, b.render_order))
        .then_with(|| compare(a.z, b.z))
        .then_with(|| a.id.cmp(&b.id))
}

/// `reversePainterSortStable( a, b )` — the same, with `z` reversed.
fn reverse_painter_sort_stable(a: &RenderItem, b: &RenderItem) -> Ordering {
    compare(a.group_order, b.group_order)
        .then_with(|| compare(a.render_order, b.render_order))
        .then_with(|| compare(b.z, a.z))
        .then_with(|| a.id.cmp(&b.id))
}

/// `a - b` as a JS comparator sees it. `z` can be any finite float here, and a
/// NaN would come from a degenerate projection matrix; JS treats a NaN
/// comparator result as "equal", so `Ordering::Equal` is the faithful answer.
fn compare(a: f64, b: f64) -> Ordering {
    a.partial_cmp(&b).unwrap_or(Ordering::Equal)
}

/// `class RenderList`, minus the bundles, the transmissive double pass and the
/// occlusion-query bookkeeping.
#[derive(Default)]
pub(crate) struct RenderList {
    /// `RenderList.opaque`.
    pub opaque: Vec<RenderItem>,
    /// `RenderList.transparent`.
    pub transparent: Vec<RenderItem>,
    /// `RenderList.lightsArray` — every visible light in the tree, in traversal
    /// order, which is what `LightsNode.setLights()` receives.
    pub lights: Vec<ObjectRef>,
}

impl RenderList {
    /// `RenderList.begin()`.
    pub fn new() -> Self {
        Self::default()
    }

    /// `RenderList.push( object, geometry, material, groupOrder, z, … )`.
    fn push(&mut self, item: RenderItem, transparent: bool) {
        if transparent {
            self.transparent.push(item);
        } else {
            self.opaque.push(item);
        }
    }

    /// `RenderList.pushLight( light )`.
    fn push_light(&mut self, light: ObjectRef) {
        self.lights.push(light);
    }

    /// `RenderList.sort( null, null )`. `slice::sort_by` is stable, as
    /// `Array.prototype.sort` is.
    pub fn sort(&mut self) {
        if self.opaque.len() > 1 {
            self.opaque.sort_by(painter_sort_stable);
        }
        if self.transparent.len() > 1 {
            self.transparent.sort_by(reverse_painter_sort_stable);
        }
    }

    /// The draw order `Renderer._renderScene()` uses: all the opaque items, then
    /// all the transparent ones.
    pub fn items(&self) -> impl Iterator<Item = &RenderItem> {
        self.opaque.iter().chain(self.transparent.iter())
    }

    /// Total drawable count.
    pub fn len(&self) -> usize {
        self.opaque.len() + self.transparent.len()
    }
}

/// The camera state `_projectObject()` reads: `camera.layers` plus the
/// projection used for the sort `z` and for frustum culling.
pub(crate) struct ProjectCamera {
    /// `camera.layers`.
    pub layers: Layers,
    /// `_projScreenMatrix` — `projectionMatrix * matrixWorldInverse`.
    pub proj_screen_matrix: Matrix4,
    /// `_frustum`, set from `_projScreenMatrix`.
    pub frustum: Frustum,
    /// `_frustumArray.setFromArrayCamera( camera )` — one frustum per
    /// `ArrayCamera` sub-camera, which replaces `frustum` in the culling test:
    /// an object is drawn when any sub-camera sees it. Empty for every other
    /// camera.
    pub sub_frustums: Vec<Frustum>,
    /// `renderContext.clippingContext.updateGlobal( scene, camera )` — the
    /// view matrix the `ClippingGroup` planes are projected with, whether
    /// this is a shadow pass (where only `clipShadows` groups clip), and
    /// whether the device has `clip-distances`.
    pub clipping: ClippingView,
}

impl ProjectCamera {
    /// `_projScreenMatrix.multiplyMatrices( camera.projectionMatrix,
    /// camera.matrixWorldInverse ); _frustum.setFromProjectionMatrix(
    /// _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth )`.
    ///
    /// `camera.matrixWorldInverse` must already be up to date — in three.js
    /// `Renderer.render()` calls `camera.updateMatrixWorld()` just above this.
    /// The same thing for a camera the port models without an `Object3D`
    /// wrapper — the shadow cameras, whose projection and world-inverse
    /// matrices `LightShadow.updateMatrices()` has just refreshed. The walk
    /// is a shadow pass for the clipping context. `hardware_clipping` is
    /// whether the device has the `clip-distances` feature.
    pub fn from_parts(
        layers: Layers,
        projection_matrix: &Matrix4,
        matrix_world_inverse: &Matrix4,
        coordinate_system: CoordinateSystem,
        hardware_clipping: bool,
    ) -> Self {
        let mut proj_screen_matrix = Matrix4::identity();
        proj_screen_matrix.multiply_matrices(projection_matrix, matrix_world_inverse);

        let mut frustum = Frustum::default();
        frustum.set_from_projection_matrix(&proj_screen_matrix, coordinate_system, false);

        Self {
            layers,
            proj_screen_matrix,
            frustum,
            sub_frustums: Vec::new(),
            // Every caller is a shadow pass, which three renders with a
            // `ShadowPassMaterial` as the scene's `overrideMaterial`.
            clipping: ClippingView::new(*matrix_world_inverse, true, hardware_clipping),
        }
    }

    /// The walk for `camera`; `hardware_clipping` is whether the device has
    /// the `clip-distances` feature.
    pub fn new(camera: &dyn RenderCamera, hardware_clipping: bool) -> Self {
        let mut proj_screen_matrix = Matrix4::identity();
        proj_screen_matrix
            .multiply_matrices(&camera.projection_matrix(), &camera.matrix_world_inverse());

        let mut frustum = Frustum::default();
        // `reversedDepth` is off: `Renderer.reversedDepth` defaults to false and
        // nothing in the ladder turns it on.
        frustum.set_from_projection_matrix(&proj_screen_matrix, camera.coordinate_system(), false);

        let sub_frustums = camera
            .sub_cameras()
            .iter()
            .map(|sub| {
                let mut matrix = Matrix4::identity();
                matrix.multiply_matrices(&sub.projection_matrix, &sub.matrix_world_inverse);
                let mut frustum = Frustum::default();
                frustum.set_from_projection_matrix(&matrix, sub.coordinate_system, false);
                frustum
            })
            .collect();

        Self {
            layers: camera.layers(),
            proj_screen_matrix,
            frustum,
            sub_frustums,
            clipping: ClippingView::new(camera.matrix_world_inverse(), false, hardware_clipping),
        }
    }
}

/// `Renderer._projectObject( object, camera, groupOrder, renderList, … )`.
///
/// Walks the subtree under `object` and pushes every visible drawable into
/// `render_list`, with the `z` the sort needs. `sort_objects` mirrors
/// `Renderer.sortObjects`: with it off, three.js leaves `z` at whatever
/// `_vector4` last held, so here it stays 0 and the lists keep traversal order.
///
/// Note which gates stop the recursion and which do not, because three.js is
/// deliberately asymmetric: `visible === false` returns immediately, so a hidden
/// parent hides its whole subtree, while failing the `layers` test only skips
/// *this* object's own render item — its children are still projected.
pub(crate) fn project_object(
    object: &ObjectRef,
    camera: &ProjectCamera,
    group_order: f64,
    render_list: &mut RenderList,
    sort_objects: bool,
) {
    project(object, camera, group_order, render_list, sort_objects, None);
}

/// [`project_object`] with the walk's `clippingContext` argument: the
/// context of the nearest enabled `ClippingGroup` above `object`.
fn project(
    object: &ObjectRef,
    camera: &ProjectCamera,
    group_order: f64,
    render_list: &mut RenderList,
    sort_objects: bool,
    clipping: Option<Rc<ClippingContext>>,
) {
    if !object.borrow().visible {
        return;
    }

    let mut group_order = group_order;
    let mut clipping = clipping;

    let visible = object.borrow().layers.test(&camera.layers);

    if visible {
        let (is_group, is_light, is_drawable) = {
            let o = object.borrow();
            (
                o.is_group,
                o.is_light,
                o.is_mesh() || o.is_line() || o.is_points() || o.payload.is_sprite(),
            )
        };

        if is_group {
            let o = object.borrow();
            group_order = o.render_order;
            // `if ( object.isClippingGroup && object.enabled )
            //      clippingContext = clippingContext.getGroupContext( object )`
            if let Payload::ClippingGroup(group) = &o.payload {
                if group.enabled {
                    clipping = ClippingContext::group_context(&clipping, group, &camera.clipping);
                }
            }
        } else if is_light {
            render_list.push_light(object.clone());
        } else if is_drawable {
            project_drawable(
                object,
                camera,
                group_order,
                render_list,
                sort_objects,
                &clipping,
            );
        }
    }

    for child in object.children() {
        project(
            &child,
            camera,
            group_order,
            render_list,
            sort_objects,
            clipping.clone(),
        );
    }
}

/// The `object.isMesh || object.isLine || object.isPoints` arm of
/// `_projectObject()` — one arm in three.js too, because everything it does
/// reads `object.geometry` and `object.material` and neither the frustum test
/// nor the sort `z` cares which primitive the object draws.
///
/// `object.isSprite` has an arm of its own in three.js, which this one folds
/// in: its frustum test is `Sprite.intersectsFrustum()` —
/// `frustum.intersectsSprite( this )`, reached through
/// [`Payload::bounding_sphere_in`] like everyone else's — and its sort `z` is
/// the object's origin rather than a geometry bounding-sphere centre. The rest
/// is the same.
///
/// `object.isLineLoop` is *not* handled: three.js' own arm above this one calls
/// `error( 'Renderer: Objects of type THREE.LineLoop are not supported…' )`, so
/// the port has no `LineLoop` to reach here.
fn project_drawable(
    object: &ObjectRef,
    camera: &ProjectCamera,
    group_order: f64,
    render_list: &mut RenderList,
    sort_objects: bool,
    clipping: &Option<Rc<ClippingContext>>,
) {
    // `Frustum.intersectsObject( object )` fills `object.boundingSphere` in the
    // first time it is asked for it — `if ( object.boundingSphere === null )
    // object.computeBoundingSphere()`. `InstancedMesh` is the one payload on
    // the ladder that sets `boundingSphere = null` in its constructor, so
    // without this an instanced draw is culled against the single geometry
    // sphere at the object's origin rather than the spread of its instances,
    // and a `RoomEnvironment` loses all six boxes from four of the six PMREM
    // faces. Cached, as three.js caches it: later `setMatrixAt` calls do not
    // invalidate it there either.
    {
        let needs_sphere = {
            let o = object.borrow();
            o.frustum_culled
                && matches!(&o.payload, Payload::InstancedMesh(instanced)
                    if instanced.bounding_sphere.is_none())
        };
        if needs_sphere {
            if let Payload::InstancedMesh(instanced) = &mut object.borrow_mut().payload {
                instanced.compute_bounding_sphere();
            }
        }
    }

    let o = object.borrow();
    let geometry = match o.geometry() {
        Some(geometry) => geometry.clone(),
        None => return,
    };

    // `if ( ! object.frustumCulled || object.intersectsFrustum( _frustum ) )` —
    // `Mesh.intersectsFrustum` / `Line.intersectsFrustum` are both
    // `frustum.intersectsObject( this )`, the geometry's bounding sphere pushed
    // through `matrixWorld`.
    if o.frustum_culled {
        let inside = match o.payload.bounding_sphere_in(&o.matrix_world) {
            // `FrustumArray.intersectsObject()` under an `ArrayCamera`.
            Some(sphere) if !camera.sub_frustums.is_empty() => camera
                .sub_frustums
                .iter()
                .any(|frustum| frustum.intersects_sphere(&sphere)),
            Some(sphere) => camera.frustum.intersects_sphere(&sphere),
            // A geometry with no position attribute has no bounding sphere;
            // three.js would throw, we treat it as nothing to draw.
            None => false,
        };

        if !inside {
            return;
        }
    }

    // `_vector4.copy( geometry.boundingSphere.center )
    //      .applyMatrix4( object.matrixWorld ).applyMatrix4( _projScreenMatrix )`
    let z = if sort_objects && o.payload.is_sprite() {
        // `_vector4.setFromMatrixPosition( object.matrixWorld )
        //      .applyMatrix4( _projScreenMatrix )`
        let e = &o.matrix_world.elements;
        apply_matrix4_vector4(&camera.proj_screen_matrix, [e[12], e[13], e[14], e[15]])[2]
    } else if sort_objects {
        let center = geometry.bounding_sphere_center();
        let v = apply_matrix4_vector4(&o.matrix_world, [center.x, center.y, center.z, 1.0]);
        apply_matrix4_vector4(&camera.proj_screen_matrix, v)[2]
    } else {
        0.0
    };

    // `if ( Array.isArray( material ) )`: one item per `geometry.groups`
    // entry whose `material[ group.materialIndex ]` exists and is visible, in
    // group order, all at the object's one `z`. The painter sort is stable and
    // every item carries the same `id`, so the groups draw in that order.
    let material_array = o.payload.material_array();
    if !material_array.is_empty() {
        let items: Vec<(RenderItem, bool)> = geometry
            .groups
            .iter()
            .filter_map(|group| {
                let material = material_array.get(group.material_index)?;
                material.visible.then(|| {
                    (
                        RenderItem {
                            node: object.clone(),
                            id: o.id,
                            group_order,
                            render_order: o.render_order,
                            z,
                            matrix_world: o.matrix_world,
                            group: Some(*group),
                            clipping: clipping.clone(),
                        },
                        material.in_transparent_list(),
                    )
                })
            })
            .collect();
        drop(o);
        for (item, transparent) in items {
            render_list.push(item, transparent);
        }
        return;
    }

    // `if ( material.visible ) renderList.push( … )`. A mesh with no material of
    // its own is drawn with `scene.overrideMaterial`, which three.js substitutes
    // later (in `_renderObjects`), after the list is built — so a missing
    // material is not a reason to skip the object here.
    // `material.transparent === true || material.transmission > 0` (or a
    // `backdropNode`, see `in_transparent_list`): a
    // transmissive material goes in the transparent list whatever its
    // `transparent` flag says, because it has to be drawn after the frame it
    // reads. The barn lamp's glass is one — the glTF sets no `alphaMode`.
    let (visible, transparent) = match o.material() {
        Some(material) => (material.visible, material.in_transparent_list()),
        None => (true, false),
    };

    if !visible {
        return;
    }

    let item = RenderItem {
        node: object.clone(),
        id: o.id,
        group_order,
        render_order: o.render_order,
        z,
        matrix_world: o.matrix_world,
        group: None,
        clipping: clipping.clone(),
    };

    drop(o);
    render_list.push(item, transparent);
}

/// `Vector4.applyMatrix4()` — no perspective divide, unlike `Vector3`'s.
fn apply_matrix4_vector4(m: &Matrix4, v: [f64; 4]) -> [f64; 4] {
    let e = &m.elements;
    [
        e[0] * v[0] + e[4] * v[1] + e[8] * v[2] + e[12] * v[3],
        e[1] * v[0] + e[5] * v[1] + e[9] * v[2] + e[13] * v[3],
        e[2] * v[0] + e[6] * v[1] + e[10] * v[2] + e[14] * v[3],
        e[3] * v[0] + e[7] * v[1] + e[11] * v[2] + e[15] * v[3],
    ]
}

#[cfg(test)]
mod tests {
    use std::rc::Rc;

    use super::*;
    use crate::cameras::PerspectiveCamera;
    use crate::core::BufferGeometry;
    use crate::geometries::box_geometry;
    use crate::lights::PointLight;
    use crate::materials::MeshBasicNodeMaterial;
    use crate::math::{Color, Vector3};
    use crate::objects::{Group, Mesh, Scene};

    /// A camera looking down -Z from z = 10, with everything in its frustum.
    fn camera() -> PerspectiveCamera {
        let mut camera = PerspectiveCamera::new(70.0, 2.0, 0.1, 100.0);
        camera.node.borrow_mut().position.z = 10.0;
        camera.update_matrix_world();
        camera
    }

    fn unit_box() -> Rc<BufferGeometry> {
        Rc::new(box_geometry(1.0, 1.0, 1.0, 1, 1, 1))
    }

    fn mesh_at(z: f64) -> ObjectRef {
        let node = Mesh::new(unit_box(), MeshBasicNodeMaterial::new());
        node.borrow_mut().position.z = z;
        node
    }

    fn world_x(node: &ObjectRef) -> f64 {
        let mut position = Vector3::ZERO;
        position.set_from_matrix_position(&node.borrow().matrix_world);
        position.x
    }

    fn project(scene: &Scene, camera: &PerspectiveCamera) -> RenderList {
        scene.update_matrix_world();
        let mut list = RenderList::new();
        project_object(
            &scene.node,
            &ProjectCamera::new(camera, false),
            0.0,
            &mut list,
            true,
        );
        list.sort();
        list
    }

    /// `Array.isArray( material )`: one item per `geometry.groups` entry, in
    /// group order, each routed by *its* material's `transparent`; a group
    /// whose `materialIndex` has no material, or an invisible one, is skipped.
    #[test]
    fn multi_material_mesh_pushes_one_item_per_group() {
        let scene = Scene::new();
        let opaque = MeshBasicNodeMaterial::new();
        let mut transparent = MeshBasicNodeMaterial::new();
        transparent.transparent = true;
        let mut hidden = MeshBasicNodeMaterial::new();
        hidden.visible = false;
        // `BoxGeometry` has six groups, `materialIndex` 0..5; only 0..2 have
        // a material here.
        let mesh = Mesh::with_materials(unit_box(), vec![opaque, transparent.clone(), hidden]);
        scene.add(&mesh);

        let list = project(&scene, &camera());
        let groups = |items: &[RenderItem]| -> Vec<usize> {
            items
                .iter()
                .map(|item| item.group.expect("a group item").material_index)
                .collect()
        };
        assert_eq!(groups(&list.opaque), vec![0]);
        assert_eq!(groups(&list.transparent), vec![1]);

        let object = mesh.borrow();
        let item = &list.transparent[0];
        assert!(item.material(&object).unwrap().transparent);
        assert_eq!(
            (item.group.unwrap().start, item.group.unwrap().count),
            (6, 6)
        );
    }

    #[test]
    fn collects_meshes_nested_under_groups() {
        let scene = Scene::new();
        let group = Group::new();
        let inner = Group::new();

        let a = mesh_at(0.0);
        let b = mesh_at(1.0);

        scene.add(&group);
        group.add(&inner);
        inner.add(&a);
        scene.add(&b);

        let list = project(&scene, &camera());

        assert_eq!(list.len(), 2, "a mesh two groups deep is still collected");
        assert!(list.transparent.is_empty());
    }

    #[test]
    fn group_world_matrix_reaches_the_nested_mesh() {
        let scene = Scene::new();
        let group = Group::new();
        group.borrow_mut().position.set(3.0, 0.0, 0.0);

        let mesh = mesh_at(0.0);
        mesh.borrow_mut().position.x = 1.0;

        scene.add(&group);
        group.add(&mesh);

        let list = project(&scene, &camera());

        assert_eq!(list.len(), 1);
        let world = list.opaque[0].matrix_world;
        let mut position = Vector3::ZERO;
        position.set_from_matrix_position(&world);
        assert_eq!(position.x, 4.0, "the group's translation is composed in");
    }

    /// `Scene::update_matrix_world` is `Object3D.updateMatrixWorld()` on the
    /// root, so the flags three.js honours there hold for the render path too.
    /// The per-object semantics are covered by `tests/core_object3d.rs`; this is
    /// the scene → group → mesh chain the renderer actually walks.
    #[test]
    fn scene_update_matrix_world_honours_the_auto_update_flags() {
        let scene = Scene::new();
        let group = Group::new();
        let mesh = mesh_at(0.0);

        scene.add(&group);
        group.add(&mesh);

        group.borrow_mut().position.x = 1.0;
        mesh.borrow_mut().position.x = 2.0;
        scene.update_matrix_world();
        assert_eq!(world_x(&mesh), 3.0, "composed through the group");

        // `matrixAutoUpdate = false`: the local matrix is left alone, so nothing
        // downstream moves either.
        group.borrow_mut().matrix_auto_update = false;
        group.borrow_mut().position.x = 10.0;
        scene.update_matrix_world();
        assert_eq!(world_x(&mesh), 3.0, "matrixAutoUpdate = false pins it");

        // …until something raises `matrixWorldNeedsUpdate`, which is what
        // `updateMatrix()` (and the animation setters) do.
        group.borrow_mut().update_matrix();
        scene.update_matrix_world();
        assert_eq!(
            world_x(&mesh),
            12.0,
            "matrixWorldNeedsUpdate forces the walk"
        );

        // `matrixWorldAutoUpdate = false` freezes this object's world matrix and,
        // because its `force` return is unaffected, still lets children recompose
        // against the stale value.
        mesh.borrow_mut().matrix_world_auto_update = false;
        mesh.borrow_mut().position.x = 5.0;
        scene.update_matrix_world();
        assert_eq!(
            world_x(&mesh),
            12.0,
            "matrixWorldAutoUpdate = false freezes it"
        );
    }

    #[test]
    fn invisible_parent_hides_the_whole_subtree() {
        let scene = Scene::new();
        let group = Group::new();
        group.borrow_mut().visible = false;
        scene.add(&group);
        group.add(&mesh_at(0.0));

        assert_eq!(project(&scene, &camera()).len(), 0);
    }

    #[test]
    fn a_layers_miss_skips_the_object_but_not_its_children() {
        // `_projectObject`: the `layers.test` gate wraps only the push, so a
        // child on the camera's layer is still reached through a parent that is
        // not. (An invisible parent, by contrast, returns early.)
        let scene = Scene::new();

        let outer = mesh_at(0.0);
        outer.borrow_mut().layers.set(1);

        let inner = mesh_at(1.0);
        outer.add(&inner);
        scene.add(&outer);

        let list = project(&scene, &camera());

        assert_eq!(list.len(), 1, "only the child is drawn");
        assert_eq!(list.opaque[0].id, inner.borrow().id);
    }

    #[test]
    fn frustum_culling_drops_an_object_behind_the_camera() {
        let scene = Scene::new();
        let behind = mesh_at(40.0); // camera sits at z = 10 looking at -Z
        scene.add(&behind);

        assert_eq!(project(&scene, &camera()).len(), 0, "culled");

        behind.borrow_mut().frustum_culled = false;
        assert_eq!(
            project(&scene, &camera()).len(),
            1,
            "frustumCulled = false keeps it"
        );
    }

    #[test]
    fn opaque_sorts_front_to_back_and_transparent_back_to_front() {
        let scene = Scene::new();

        // Nearer the camera (z = 10) means a smaller clip-space z.
        let near = mesh_at(4.0);
        let far = mesh_at(-4.0);
        scene.add(&far);
        scene.add(&near);

        let list = project(&scene, &camera());
        assert_eq!(
            [list.opaque[0].id, list.opaque[1].id],
            [near.borrow().id, far.borrow().id],
            "painterSortStable: ascending z"
        );

        for node in [&near, &far] {
            node.borrow_mut()
                .mesh_mut()
                .unwrap()
                .material
                .as_mut()
                .unwrap()
                .transparent = true;
        }

        let list = project(&scene, &camera());
        assert!(list.opaque.is_empty());
        assert_eq!(
            [list.transparent[0].id, list.transparent[1].id],
            [far.borrow().id, near.borrow().id],
            "reversePainterSortStable: descending z"
        );
    }

    #[test]
    fn render_order_and_group_order_outrank_z() {
        let scene = Scene::new();

        let near = mesh_at(4.0);
        near.borrow_mut().render_order = 1.0;
        let far = mesh_at(-4.0);

        scene.add(&near);
        scene.add(&far);

        let list = project(&scene, &camera());
        assert_eq!(
            [list.opaque[0].id, list.opaque[1].id],
            [far.borrow().id, near.borrow().id],
            "renderOrder beats z"
        );

        // `groupOrder` comes from the nearest `Group` ancestor's `renderOrder`
        // and beats `renderOrder` in turn.
        let group = Group::new();
        group.borrow_mut().render_order = -1.0;
        scene.add(&group);
        group.add(&near);

        let list = project(&scene, &camera());
        assert_eq!(list.opaque[0].group_order, -1.0);
        assert_eq!(
            [list.opaque[0].id, list.opaque[1].id],
            [near.borrow().id, far.borrow().id],
            "groupOrder beats renderOrder"
        );
    }

    #[test]
    fn an_invisible_material_is_not_pushed() {
        let scene = Scene::new();
        let mesh = mesh_at(0.0);
        mesh.borrow_mut()
            .mesh_mut()
            .unwrap()
            .material
            .as_mut()
            .unwrap()
            .visible = false;
        scene.add(&mesh);

        assert_eq!(project(&scene, &camera()).len(), 0);
    }

    #[test]
    fn lights_are_collected_and_not_drawn_but_their_children_are() {
        let scene = Scene::new();

        let light = PointLight::new(Color::new(1.0, 1.0, 1.0), 1.0, 100.0);
        let bulb = mesh_at(0.0);

        scene.add(&light);
        light.add(&bulb);

        let list = project(&scene, &camera());

        assert_eq!(list.lights.len(), 1, "the light is pushed as a light");
        assert_eq!(list.lights[0].borrow().id, light.borrow().id);
        assert_eq!(list.len(), 1, "and its bulb mesh is still drawn");
        assert_eq!(list.opaque[0].id, bulb.borrow().id);

        // `PointLight.matrixWorld` is what the renderer reads the light's world
        // position from, and the bulb is an ordinary child, so it composes.
        light.borrow_mut().position.x = 2.0;
        let list = project(&scene, &camera());
        assert_eq!(world_x(&list.lights[0]), 2.0);
        assert_eq!(world_x(&bulb), 2.0, "the bulb rides the light's matrix");
    }

    #[test]
    fn unsorted_keeps_traversal_order() {
        let scene = Scene::new();
        let far = mesh_at(-4.0);
        let near = mesh_at(4.0);
        scene.add(&far);
        scene.add(&near);
        scene.update_matrix_world();

        let mut list = RenderList::new();
        project_object(
            &scene.node,
            &ProjectCamera::new(&camera(), false),
            0.0,
            &mut list,
            false,
        );
        list.sort();

        assert_eq!(
            [list.opaque[0].id, list.opaque[1].id],
            [far.borrow().id, near.borrow().id],
            "with sortObjects off, z stays 0 and the id tie-break holds add order"
        );
    }

    /// A `ClippingGroup`'s planes reach the meshes below it in view space,
    /// stored as `( -normal, constant )`; a nested `clipIntersection` group
    /// adds its planes to the intersection list on top of its parent's.
    #[test]
    fn clipping_groups_build_the_context_of_their_descendants() {
        use crate::math::Plane;
        use crate::objects::ClippingGroup;

        let scene = Scene::new();
        let outer = ClippingGroup::of(ClippingGroup {
            clipping_planes: vec![Plane::new(Vector3::new(-1.0, 0.0, 0.0), 0.1)],
            ..Default::default()
        });
        let inner = ClippingGroup::of(ClippingGroup {
            clipping_planes: vec![
                Plane::new(Vector3::new(0.0, -1.0, 0.0), 0.8),
                Plane::new(Vector3::new(0.0, 0.0, -1.0), 0.1),
            ],
            clip_intersection: true,
            ..Default::default()
        });
        let outside = mesh_at(0.0);
        let union_only = mesh_at(0.0);
        let both = mesh_at(0.0);
        scene.add(&outside);
        scene.add(&outer);
        outer.add(&union_only);
        outer.add(&inner);
        inner.add(&both);

        let list = project(&scene, &camera());
        let context = |node: &ObjectRef| {
            list.items()
                .find(|item| item.node.borrow().id == node.borrow().id)
                .unwrap()
                .clipping
                .clone()
        };

        assert!(context(&outside).is_none(), "no group, no context");

        // The camera sits at z = 10 looking down -Z, so the view matrix is a
        // translation by -10 in z: x and y planes keep their constant.
        let union = context(&union_only).unwrap();
        assert_eq!(union.union, vec![[1.0, 0.0, 0.0, 0.1]]);
        assert!(union.intersection.is_empty());

        let nested = context(&both).unwrap();
        assert_eq!(nested.union, union.union, "the parent's planes are kept");
        assert_eq!(nested.intersection.len(), 2);
        assert_eq!(nested.intersection[0], [0.0, 1.0, 0.0, 0.8]);
        // `z = 0.1` in the world is `z = -9.9` in view space.
        let [x, y, z, w] = nested.intersection[1];
        assert_eq!([x, y, z], [0.0, 0.0, 1.0]);
        assert!((w + 9.9).abs() < 1e-5, "{w}");
    }

    /// `getGroupContext()` in a shadow pass: only a `clipShadows` group
    /// clips, and a disabled group never does.
    #[test]
    fn shadow_passes_clip_only_with_clip_shadows() {
        use crate::math::Plane;
        use crate::objects::ClippingGroup;

        let scene = Scene::new();
        let plane = Plane::new(Vector3::new(1.0, 0.0, 0.0), 0.0);
        let unshadowed = ClippingGroup::of(ClippingGroup {
            clipping_planes: vec![plane],
            ..Default::default()
        });
        let shadowed = ClippingGroup::of(ClippingGroup {
            clipping_planes: vec![plane],
            clip_shadows: true,
            ..Default::default()
        });
        let disabled = ClippingGroup::of(ClippingGroup {
            clipping_planes: vec![plane],
            enabled: false,
            ..Default::default()
        });
        let (a, b, c) = (mesh_at(0.0), mesh_at(0.0), mesh_at(0.0));
        scene.add(&unshadowed);
        scene.add(&shadowed);
        scene.add(&disabled);
        unshadowed.add(&a);
        shadowed.add(&b);
        disabled.add(&c);
        scene.update_matrix_world();

        let camera = camera();
        let mut list = RenderList::new();
        project_object(
            &scene.node,
            &ProjectCamera::from_parts(
                camera.layers(),
                &camera.projection_matrix(),
                &camera.matrix_world_inverse(),
                camera.coordinate_system(),
                false,
            ),
            0.0,
            &mut list,
            true,
        );
        let clipped = |node: &ObjectRef| {
            list.items()
                .find(|item| item.node.borrow().id == node.borrow().id)
                .unwrap()
                .clipping
                .is_some()
        };
        assert!(!clipped(&a));
        assert!(clipped(&b));
        assert!(!clipped(&c));
    }
}