three-rs 0.2.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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
//! Port of `three.js/src/materials/nodes/NodeMaterial.js` โ€” `setup()` and the
//! `setupX()` methods it dispatches to. This is where a material turns into the
//! statements the builder flows into the two shader stages.

use super::environment;
use super::phong::{self, LightDesc};
use super::physical::{self, Physical};
use super::toon;
use super::transmission;
use super::{Blending, MaterialKind, MeshBasicNodeMaterial, Side, ToneMapping};
use crate::lights::LightKind;
use crate::nodes::node::{Type, UniformGroup, UniformSource};
use crate::nodes::tsl::FogNode;
use crate::nodes::tsl::*;
use crate::nodes::{MaterialFlow, NodeRef};

/// The per-render-object facts three.js reads off `builder.object` and
/// `builder.geometry` during setup.
///
/// `Hash` is the scene-dependent half of the render object's cache key โ€”
/// `RenderObject.getDynamicCacheKey()`: the lights (with their shadow maps),
/// the instancing branch and the morph entry. Everything `setup()` reads that
/// is not on the material is here, so the derived hash is complete by
/// construction: a field added to this struct is in the key.
#[derive(Clone, Debug, Default, Hash)]
#[doc(hidden)]
pub struct SetupContext {
    /// `scene.environmentNode` โ€” the scene-level environment map, which
    /// `NodeMaterial.setupEnvironment()` falls back to when the material has
    /// no `envNode` of its own. `None` for every pass that is not a scene
    /// draw (the background quad, the shadow pass, `render_quad`).
    pub environment: Option<environment::Environment>,
    /// `Some(count)` when the object is an `InstancedMesh`, which is what makes
    /// `NodeMaterial.setupPosition()` insert the `InstanceNode` transform.
    pub instance_count: Option<usize>,
    /// `InstancedMesh.instanceColor` is present, so `range()` resolves against
    /// the instance index.
    pub instanced: bool,
    /// `Some(count)` when the object is an `InstancedMesh` that has had
    /// `setColorAt()` called on it โ€” `NodeMaterial.setupDiffuseColor()`'s
    /// `if ( object.instanceColor )` branch. The count sizes the instanced
    /// vertex buffer; the colours themselves travel with the draw, not with
    /// the node, so two meshes sharing a material cannot share a fill.
    pub instance_color: Option<usize>,
    /// The pass' lights in `Scene.lights` order โ€” the default `LightsNode` list
    /// when the material sets no `lights_node`. Each entry carries the light's
    /// kind and, when this object receives its shadow, the shadow map to sample;
    /// both change the generated code, so they are part of the program's cache
    /// key by construction.
    pub lights: Vec<LightDesc>,
    /// `getEntry( geometry )` when the geometry has morph attributes: what
    /// `NodeMaterial.setupPosition()` needs to emit `morphReference()`.
    pub morph: Option<crate::nodes::morph::MorphEntry>,
    /// `Some` when the object is a `SkinnedMesh` with a skeleton, which is what
    /// makes `NodeMaterial.setupPosition()` insert `skinning( object )`.
    pub skin: Option<crate::nodes::skinning::SkinEntry>,
    /// `object.isBatchedMesh`: the three data textures `batch()` reads.
    pub batch: Option<crate::nodes::batch::BatchEntry>,
    /// A `LineSegmentsGeometry`'s interleaved instanced attributes, which
    /// `Line2NodeMaterial` reads as `instanceStart` / `instanceEnd` and
    /// `instanceColorStart` / `instanceColorEnd`. See
    /// [`crate::nodes::lines`] for why they travel here rather than on the
    /// geometry.
    pub line_segments: Option<crate::nodes::lines::LineSegmentsAttributes>,
    /// `object.center && object.center.isVector2` โ€” the object is a `Sprite`,
    /// so `SpriteNodeMaterial.setupPositionView()` offsets the quad by
    /// `center - 0.5`. A `SpriteNodeMaterial` on anything else (the
    /// instanced-mesh particles of `webgpu_compute_particles_*`) has no
    /// `center` and skips the step, which changes the WGSL.
    pub sprite: bool,
    /// `renderer.getMRT()` and the names of the bound render target's colour
    /// attachments โ€” the pass-level half of `NodeMaterial.setup()`'s MRT
    /// branch, which only runs `if ( renderTarget !== null )`.
    ///
    /// `None` is every draw into a single-attachment target, and leaves the
    /// fragment stage's `OutputStruct { color }` shape alone.
    pub mrt: Option<MrtContext>,
    /// `geometry.getAttribute( 'color' ).itemSize` โ€”
    /// `VertexColorNode.generate()`'s
    /// `builder.getTypeFromAttribute( geometryAttribute )`. 4 is glTF `COLOR_0`
    /// as `VEC4` and is read whole; anything else โ€” including 0, a geometry
    /// with no `color` attribute โ€” takes the three-component form, widened to a
    /// `vec4` with an alpha of 1. It is part of the program's cache key,
    /// because it changes the vertex attribute's WGSL type.
    pub vertex_color_size: usize,
    /// `builder.renderer.lighting.enabled === false` โ€” the pass was rendered
    /// with its lighting disabled (`PassNode`'s `lighting: false`), so
    /// `NodeMaterial.setupLighting()`'s `sceneLighting` is false: the material
    /// collects no `materialLightings` (the environment among them) and, with
    /// an empty `LightsNode`, emits no lighting chain at all โ€” the outgoing
    /// light is the diffuse colour. `webgpu_deferred`'s G-buffer pass is that
    /// case. The sense is inverted so that `Default` (every ordinary pass)
    /// stays "lighting enabled".
    pub lighting_disabled: bool,
    /// `builder.geometry.attributes.normal === undefined` โ€”
    /// `getGeometryRoughness()` returns `float( 0 )` for a geometry with no
    /// normal attribute instead of the `dFdx`/`dFdy` term, because the
    /// derivative would be taken of a constant. `webgpu_deferred`'s resolve
    /// quad is exactly that case: a `MeshStandardNodeMaterial` on the
    /// two-attribute quad geometry. It changes the generated WGSL, so it
    /// belongs in the dynamic cache key.
    pub geometry_missing_normal: bool,
    /// `builder.geometry.hasAttribute( 'tangent' )`. A glTF primitive with a
    /// `TANGENT` accessor gets three's attribute tangent frame; anything else
    /// gets the screen-derivative one. It changes both stages' code, so it is
    /// part of the program's cache key.
    pub has_tangent_attribute: bool,
    /// The geometry's `InstancedBufferAttribute`s by name โ€”
    /// `isInstancedBufferAttribute`, which sets their vertex buffer's
    /// `stepMode` to `instance`. It changes the pipeline, not the WGSL, and is
    /// in the key for that reason; see
    /// [`NodeProgram::instanced_attributes`](crate::nodes::NodeProgram).
    pub instanced_attributes: Vec<String>,
    /// `viewportOpaqueMipTexture()` โ€” the renderer's mipped copy of the frame
    /// as it stood when the last opaque object had been drawn, which is what a
    /// transmissive material reads through. `None` on every pass that makes no
    /// copy, which takes the transmission branch out of the shader entirely.
    pub viewport_opaque_mip: Option<transmission::OpaqueFrame>,
    /// `builder.context.getOutput` โ€” the renderer's context node, which
    /// `DirectRenderPipeline` sets so that the output transform is applied
    /// **inside every material's fragment shader** instead of in a quad of its
    /// own. See [`OutputContext`].
    pub output: Option<OutputContext>,
    /// `camera.cameras.length` when the pass is drawn through an
    /// `ArrayCamera` (0 otherwise) โ€” `RenderObject.getCacheKey()`'s
    /// `camera.isArrayCamera ? camera.cameras.length : 0`. It sizes the
    /// camera matrix arrays and moves the object group to `@group( 2 )`, so
    /// it is part of the program's cache key. `docs/nodes.md` ยง40.
    pub array_cameras: usize,
}

/// `context.getOutput( materialOutputNode, builder )`.
///
/// three.js passes a closure, which can look at the builder and hand the
/// material's own output straight back when the draw is not going to the
/// output target. The port makes that decision on the renderer instead โ€” the
/// hook only ever reaches a material that is being drawn into the canvas, so
/// what travels here is just the node the closure would return: the
/// pipeline's `outputNode`, already wrapped in `renderOutput( โ€ฆ, toneMapping,
/// outputColorSpace )`, reading the material's result back through the
/// `Output` property (`output_property()`).
///
/// It is part of `SetupContext`, so it is part of the program's cache key by
/// construction, which is what keeps a material drawn with the hook and the
/// same material drawn without it on two different programs.
#[derive(Clone, Debug)]
#[doc(hidden)]
pub struct OutputContext {
    pub node: NodeRef,
}

impl std::hash::Hash for OutputContext {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.node.key().hash(state);
    }
}

/// What a draw into an MRT render target knows about it: the pass's MRT node
/// (`renderer.getMRT()`) and `renderTarget.textures.map( t => t.name )`, which
/// is what `MRTNode.setup()` resolves its output names against.
#[derive(Clone, Debug, Default, Hash)]
#[doc(hidden)]
pub struct MrtContext {
    pub node: crate::nodes::MrtNode,
    pub attachments: Vec<String>,
}

/// `Renderer._getShadowNodes( material )` composed with
/// `ShadowBaseNode._getShadowMaterial()`: the per-object shadow-pass material.
///
/// three.js mutates one shared `ShadowMaterial` per light in place; the port
/// builds a fresh material per object instead, which is the same thing because
/// the program is keyed on the generated WGSL.
#[doc(hidden)]
pub fn shadow_material(source: &MeshBasicNodeMaterial) -> MeshBasicNodeMaterial {
    shadow_material_for(source, crate::lights::ShadowMapType::Pcf)
}

/// [`shadow_material`] for a given `renderer.shadowMap.type`.
/// `Renderer._renderObjectDirect`'s override differs by one line:
///
/// ```js
/// if ( this.shadowMap.type === VSMShadowMap ) {
///     overrideMaterial.side = material.shadowSide ?? material.side;
/// } else {
///     overrideMaterial.side = material.shadowSide ?? _shadowSide[ material.side ];
/// }
/// ```
///
/// โ€” VSM draws the faces the material itself draws, where every other type
/// draws the opposite ones. (The port has no `material.shadowSide`; it is
/// always `null` on the ladder.)
#[doc(hidden)]
pub fn shadow_material_for(
    source: &MeshBasicNodeMaterial,
    shadow_type: crate::lights::ShadowMapType,
) -> MeshBasicNodeMaterial {
    let mut material = MeshBasicNodeMaterial::new();
    material.name = "ShadowMaterial";
    material.blending = Blending::No;
    material.fog = false;
    // `overrideMaterial.transparent = material.transparent`, and
    // `_shadowSide[ material.side ]` โ€” the shadow pass draws the *back* faces
    // of a front-sided material, which is where the shadow pipelines'
    // `frontFace: cw` comes from.
    material.transparent = source.transparent;
    material.side = match (shadow_type.resolved(), source.side) {
        (crate::lights::ShadowMapType::Vsm, side) => side,
        (_, Side::Front) => Side::Back,
        (_, Side::Back) => Side::Front,
        // `_shadowSide = { [ DoubleSide ]: DoubleSide }`.
        (_, Side::Double) => Side::Double,
    };

    // `shadowRGB = vec3( 0 )`, `shadowAlpha = float( 1 )` โ€” or the
    // `castShadowNode`'s `.rgb` / `.a` โ€” and the source material's own colour
    // only contributes its alpha.
    let cast = &source.cast_shadow_node;
    material.color_node = Some(
        match (&source.color_node, &source.map, &source.mask_node, cast) {
            // `hasMap || hasColorNode || hasCastShadowNode || hasMaskNode` is
            // false: the override material keeps its own `vec4( 0, 0, 0, 1 )`,
            // which is a flat four-component constant rather than a join.
            (None, None, None, None) => vec4(0.0, 0.0, 0.0, 1.0),
            (color, map, _, cast) => {
                // `castShadowNode.a` of a `vec3` is `vec4( node, 1 ).w`, as
                // three's `.a` on a three-component node emits it.
                let (rgb, alpha) = match cast {
                    Some(cast) => (cast.clone().rgb(), to_vec4(cast.clone()).w()),
                    None => (vec3(0.0, 0.0, 0.0), float(1.0)),
                };
                // The colour node's alpha when there is one, else the map's.
                let alpha = match (color, map) {
                    (Some(color), _) => alpha.mul(to_vec4(color.clone()).w()),
                    (None, Some(map)) => alpha.mul(texture(map).a()),
                    (None, None) => alpha,
                };
                vec4_join(vec![rgb, alpha])
            }
        },
    );
    // `overrideMaterial.alphaTest = material.alphaTest` and `.alphaMap =
    // material.alphaMap`: a cut-away texel casts no shadow.
    material.alpha_test = source.alpha_test;
    material.alpha_map = source.alpha_map.clone();
    // `Fn( ( [ color ] ) => { maskNode.not().discard(); return color; } )`.
    material.mask_node = source.mask_node.clone();
    material
}

/// `materialOpacity` โ€” `MaterialNode.OPACITY`: the `opacity` uniform, times
/// `texture( alphaMap )` when the material has one. The product is a `vec4`
/// (three multiplies by the whole texel, not its green channel), and the
/// `DiffuseColor.w` assign narrows it back to `.x`.
fn material_opacity_for(material: &MeshBasicNodeMaterial) -> NodeRef {
    match &material.alpha_map {
        Some(map) => material_opacity().mul(texture(map)),
        None => material_opacity(),
    }
}

/// `vec4( node )` the way `setupDiffuseColor` builds it: a scalar splats, a
/// `vec3` gains an alpha of 1, a `vec4` passes through.
fn to_vec4(node: NodeRef) -> NodeRef {
    match node.ty() {
        Type::Vec4 => node,
        Type::Vec3 => vec4_join(vec![node, float(1.0)]),
        _ => node.to(Type::Vec4),
    }
}

/// `NodeMaterial.setupDiffuseColor()` โ€” the step every lighting model shares.
///
/// `materialColor` is `MaterialNode.COLOR`, which is the material's colour
/// *times the map's texel* when the material has one (`MaterialNode.js:126`):
/// that is why `DiffuseColor` is assigned a `vec4` product rather than a `vec3`
/// promoted to one, and why an unlit `MeshBasicNodeMaterial { map }` is
/// textured on exactly the same terms as a Standard one. A `colorNode`
/// replaces the pair outright, map included โ€”
/// `this.colorNode ? vec4( this.colorNode ) : materialColor`.
fn setup_diffuse_color(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fragment: &mut Vec<NodeRef>,
) {
    let color = match &material.color_node {
        Some(node) => to_vec4(node.clone()),
        // `materialColor` is a vec3 (times `map` when there is one) and stays
        // one until `diffuseColor.assign()` widens it, which is what puts the
        // `vec4<f32>( โ€ฆ , 1.0 )` on the outside of the instance-colour product
        // rather than around the uniform alone.
        None => {
            let base = material_color();
            match &material.map {
                Some(map) => base.mul(texture(map)),
                None => base,
            }
        }
    };

    // `if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) )
    // colorNode = colorNode.mul( vertexColor() )` โ€” the same step for every
    // lighting model, which is what lets one `LineSegments` carry a hue per
    // vertex. See `vertex_color()` for the `hasAttribute` half.
    // `Line2NodeMaterial` is the exception: a `LineSegmentsGeometry` has no
    // `color` attribute (it carries `instanceColorStart` / `instanceColorEnd`),
    // so three's `geometry.hasAttribute( 'color' )` is false and the base
    // multiply is skipped. Its own `setupDiffuseColor()` selects the colour per
    // end instead โ€” see [`crate::materials::line2::setup_diffuse_color`].
    let color = match material.vertex_colors && material.kind != MaterialKind::Line2 {
        true => color.mul(vertex_color(ctx.vertex_color_size)),
        false => color,
    };

    // `if ( object.instanceColor ) colorNode = instanceColor.mul( colorNode )`
    // โ€” the varying multiplies on the *left*, which is what puts
    // `vInstanceColor` first in the dump's `DiffuseColor = vec4<f32>( (
    // vInstanceColor * object.nodeUniform2 ), 1.0 )`.
    let color = match ctx.instance_color {
        Some(count) => instance_color(count).mul(color),
        None => color,
    };

    // `if ( object.isBatchedMesh && object._colorsTexture )
    // colorNode = batchColor.mul( colorNode )` โ€” the varying is the *left*
    // operand, which is what puts `vBatchColor` first in the generated line.
    // three.js runs this after the instanced-colour step, so the port does too.
    let color = match ctx.batch.as_ref().and_then(|b| b.colors.as_ref()) {
        Some(_) => crate::nodes::batch::batch_color().mul(color),
        None => color,
    };

    fragment.push(diffuse_color().assign(color));

    // `const opacityNode = this.opacityNode ? float( this.opacityNode ) :
    // materialOpacity` โ€” a node *replaces* the uniform rather than scaling it,
    // so a material with an `opacityNode` never reads `material.opacity`.
    let opacity = match &material.opacity_node {
        Some(node) => to_float(node.clone()),
        None => material_opacity_for(material),
    };
    fragment.push(diffuse_color().w().assign(diffuse_color().w().mul(opacity)));

    // `if ( this.alphaTestNode !== null || this.alphaTest > 0 )
    // diffuseColor.a.lessThanEqual( alphaTestNode ).discard()`. It is *after*
    // the opacity multiply and *before* the opaque clamp, so the alpha the test
    // sees is the one the opacity node produced, and the fragments that survive
    // still get `w = 1.0` on an opaque material โ€” the alpha-test teapot is not
    // `transparent`, and the dump shows both lines.
    let alpha_test = match &material.alpha_test_node {
        Some(node) => Some(to_float(node.clone())),
        None if material.alpha_test > 0.0 => Some(material_alpha_test()),
        None => None,
    };
    if let Some(alpha_test) = alpha_test {
        fragment.push(if_then(
            diffuse_color().w().less_than_equal(alpha_test),
            vec![discard()],
        ));
    }

    // `if ( this.alphaHash === true ) diffuseColor.a.lessThan(
    // getAlphaHashThreshold( positionLocal ) ).discard()` โ€” after the alpha
    // test, before the opaque clamp. `lessThan`, where the alpha test is
    // `lessThanEqual`.
    if material.alpha_hash {
        fragment.push(if_then(
            diffuse_color()
                .w()
                .less_than(crate::nodes::alpha_hash::get_alpha_hash_threshold(
                    position_local(),
                )),
            vec![discard()],
        ));
    }

    // `builder.isOpaque()` โ€” the material is not transparent, blending is
    // NormalBlending and alphaToCoverage is off. A transparent or blended
    // material keeps its per-fragment alpha instead, all the way to `Output`.
    if material.is_opaque() {
        fragment.push(diffuse_color().w().assign(float(1.0)));
    }

    // `Line2NodeMaterial.setupDiffuseColor()` runs `super.setupDiffuseColor()`
    // first and then adds the coverage multiply and the per-end colour. Its
    // `blending = NoBlending` is why `is_opaque()` above is false and the
    // `DiffuseColor.w = 1.0` line is absent from three's dump.
    if material.kind == MaterialKind::Line2 {
        if let Some(attributes) = &ctx.line_segments {
            crate::materials::line2::setup_diffuse_color(
                material.alpha_to_coverage,
                material.world_units,
                material.vertex_colors,
                attributes,
                fragment,
            );
        }
    }
}

/// `float( node )` โ€” `NodeBuilder.format()` narrowing to one component, which
/// is what `setupDiffuseColor()` wraps `opacityNode` and `alphaTestNode` in.
fn to_float(node: NodeRef) -> NodeRef {
    match node.ty() {
        Type::F32 => node,
        Type::Vec2 | Type::Vec3 | Type::Vec4 => node.x(),
        _ => node.to(Type::F32),
    }
}

/// `NodeMaterial.setup()`.
#[doc(hidden)]
pub fn setup(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fog: Option<&FogNode>,
) -> MaterialFlow {
    // `builder.geometry.hasAttribute( 'tangent' )` โ€” installed first, because
    // the material's normal node below already reads the TBN frame.
    with_tangent_attribute(ctx.has_tangent_attribute, || {
        setup_tangent(material, ctx, fog)
    })
}

fn setup_tangent(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fog: Option<&FogNode>,
) -> MaterialFlow {
    // `builder.context.setupNormal = () => subBuild( this.setupNormal( builder
    // ), 'NORMAL' )` โ€” installed for the whole of the material's setup, so that
    // every `normalView` the lighting flow reaches resolves to this material's
    // normal map. See `docs/nodes.md` ยง7.
    // `MaterialNode.NORMAL`: with no `normalNode` of its own, a material with a
    // `bumpMap` normal-maps through `BumpMapNode`.
    // `MaterialNode.NORMAL`: `normalMap` first, then `bumpMap`, then the
    // geometry's own `normalView`.
    // `material.contextNode = overrideNodes( [ โ€ฆ ] )`: the replacements are
    // installed for the whole of the material's setup, so every accessor the
    // lighting flow reaches resolves to the G-buffer texture instead of to the
    // geometry. See `docs/nodes.md` ยง27.
    crate::nodes::tsl::with_override_nodes(material.context_overrides.as_ref(), || {
        setup_overridden(material, ctx, fog)
    })
}

fn setup_overridden(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fog: Option<&FogNode>,
) -> MaterialFlow {
    let normal = with_material_side(material.side, || {
        match (
            &material.normal_node,
            &material.normal_map,
            &material.bump_map,
        ) {
            (Some(node), _, _) => Some(node.clone()),
            (None, Some(map), _) => Some(normal_map_scaled(texture(map), material_normal_scale())),
            (None, None, Some(bump)) => Some(bump_map(bump, material_bump_scale())),
            (None, None, None) => None,
        }
    });
    // `builder.context.setupPositionView = () => this.setupPositionView(
    // builder )` โ€” the seam `SpriteNodeMaterial` overrides. Built here, before
    // either stage is flowed, exactly as `NodeMaterial.setup()` installs it.
    let position_view = match material.kind {
        MaterialKind::Sprite => Some(setup_position_view_sprite(material, ctx.sprite)),
        MaterialKind::Points => Some(setup_position_view_points(material)),
        _ => None,
    };
    // `MeshPhysicalNodeMaterial.setup()`'s
    // `builder.context.setupClearcoatNormal = () => subBuild( โ€ฆ, 'NORMAL' )`.
    // `MaterialNode.CLEARCOAT_NORMAL` is the clearcoat normal map through the
    // same `NORMAL` sub-build the base normal map uses, which is why the two
    // share one `NORMAL_TBNViewMatrix` in the dump.
    let clearcoat_normal = with_material_side(material.side, || {
        material
            .clearcoat_normal_map
            .as_ref()
            .map(|map| normal_map_scaled(texture(map), material_clearcoat_normal_scale()))
    });
    with_material_normal(normal, material.flat_shading, material.side, || {
        with_clearcoat_normal(clearcoat_normal, || {
            with_material_position_view(position_view, || setup_inner(material, ctx, fog))
        })
    })
}

fn setup_inner(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fog: Option<&FogNode>,
) -> MaterialFlow {
    let mut pre_vertex = Vec::new();
    let mut fragment = Vec::new();

    // `Line2NodeMaterial.setupPosition()` overrides the whole thing and calls
    // `super.setupPosition()` last, so its `positionLocal.assign()` is the
    // first statement of the vertex flow โ€” ahead of morphing and skinning,
    // neither of which a fat line has.
    if material.kind == MaterialKind::Line2 {
        if let Some(attributes) = &ctx.line_segments {
            pre_vertex.push(crate::materials::line2::setup_position(
                attributes,
                material.world_units,
            ));
        }
    }

    // --- setupPosition: the `context.position` stack, flowed into the vertex
    // stage before either stage's own flow. Morphing, skinning and batching
    // plug in here too.
    // `if ( object.morphTargetInfluences ) morphReference( object ).append()` โ€”
    // first in `setupPosition`, before skinning, displacement, batching and
    // instancing.
    if let Some(entry) = &ctx.morph {
        pre_vertex.extend(crate::nodes::morph::morph_reference(entry));
    }

    // `if ( object.isSkinnedMesh === true ) skinning( object ).append()` โ€”
    // second, so the bind matrix sees the morphed position.
    if let Some(entry) = &ctx.skin {
        pre_vertex.extend(crate::nodes::skinning::skinning(entry));
    }

    //
    // `material.positionNode` is applied *before* the instance transform. three
    // r186 does the reverse (`NodeMaterial.js:798` instancing, then `:804`
    // `positionLocal.assign( positionNode )`), which throws the instance matrix
    // away; lib3's `BatchedText` was written against the order here. On the unit
    // `PlaneGeometry( 1, 1 )` the two formulations agree vertex for vertex, so
    // this also reproduces d33's baked-matrix workaround exactly. Recorded as a
    // deviation in `docs/nodes.md` ยง10 and plan ยง5.2.
    if let Some(node) = &material.position_node {
        pre_vertex.push(position_local().assign(to_vec3(node.clone())));
    }
    // `if ( object.isBatchedMesh ) batch( object )` โ€” `NodeMaterial.js:792`,
    // after morphing and displacement and before instancing.
    if let Some(entry) = &ctx.batch {
        pre_vertex.extend(crate::nodes::batch::batch(entry));
    }

    if let Some(count) = ctx.instance_count {
        let matrix = instance_matrix(count);
        pre_vertex.push(
            position_local().assign(
                matrix
                    .mul(vec4_join(vec![position_local(), float(1.0)]))
                    .xyz(),
            ),
        );
        // `InstanceNode`: the normal is transformed by the inverse transpose of
        // the instance matrix' upper 3x3.
        let m3 = join(
            Type::Mat3,
            vec![
                matrix.element(0).xyz(),
                matrix.element(1).xyz(),
                matrix.element(2).xyz(),
            ],
        );
        let inv_t = transpose(inverse(m3));
        pre_vertex.push(normal_local().assign(inv_t.mul(normal_local()).normalize()));
    }

    // --- setupDiscard: `If( maskNode.not(), () => Discard() )`, the first
    // thing in the fragment flow, before `setupDiffuseColor`.
    if let Some(mask) = &material.mask_node {
        fragment.push(discard_if(mask.clone()));
    }

    // --- the fragment flow
    let output = if let Some(fragment_node) = &material.fragment_node {
        fragment_node.clone()
    } else if material.kind == MaterialKind::Phong {
        setup_phong(material, ctx, true, &mut fragment)
    } else if material.kind == MaterialKind::Lambert || material.kind == MaterialKind::Toon {
        setup_phong(material, ctx, false, &mut fragment)
    } else if material.kind == MaterialKind::Standard || material.kind == MaterialKind::Physical {
        setup_standard(material, ctx, &mut fragment)
    } else if material.kind == MaterialKind::Normal {
        // `MeshNormalNodeMaterial.setupDiffuseColor()` replaces the base
        // implementation outright: no `colorNode`, no vertex colours, no alpha
        // test, and no `builder.isOpaque()` clamp โ€” the opacity node (or the
        // `materialOpacity` uniform) lands directly in the `vec4`'s `w`.
        //
        // "By convention, a normal packed to RGB is in sRGB color space", so
        // the packed value is decoded into the working space on the way in;
        // that is where `sRGBTransferEOTF` comes from, and it is the only
        // material on the ladder that emits the EOTF rather than the OETF.
        let opacity = match &material.opacity_node {
            Some(node) => to_float(node.clone()),
            None => material_opacity_for(material),
        };
        fragment.push(diffuse_color().assign(srgb_to_working(vec4_join(vec![
            pack_normal_to_rgb(normal_view()),
            opacity,
        ]))));
        vec4_join(vec![diffuse_color().xyz(), diffuse_color().w()]).max(float(0.0))
    } else {
        setup_diffuse_color(material, ctx, &mut fragment);

        // `NodeMaterial.setupLighting()` for a material with no lighting model
        // of its own: `lights = this.lights || this.lightsNode !== null`, and
        // the `LightsNode` runs only `if ( lightsNode.getScope().hasLights )`.
        // The model then comes from the `lightsNode.context( { lightingModel
        // } )` the example wrapped the lights in.
        let custom_lighting = material.lighting_model.as_ref().and_then(|model| {
            let lights =
                (material.lights && !ctx.lighting_disabled) || material.lights_node.is_some();
            let list = material_lights(material, ctx);
            (lights && !list.is_empty()).then_some((model, list))
        });

        let outgoing = if let Some((model, lights)) = custom_lighting {
            crate::materials::lighting_model::lights_node(
                model.as_ref(),
                &lights,
                material.received_shadow_position_node.as_ref(),
                &mut fragment,
            )
        } else if let Some(env_map) = &material.env_map {
            // `BasicLightingModel` with an indirect environment contribution.
            fragment.push(
                indirect_diffuse().assign(
                    vec4_join(vec![indirect_diffuse(), float(1.0)])
                        .add(vec4(1.0, 1.0, 1.0, 0.0))
                        .xyz(),
                ),
            );
            fragment.push(indirect_diffuse().assign(indirect_diffuse().mul(ambient_occlusion())));
            fragment.push(indirect_diffuse().assign(indirect_diffuse().mul(diffuse_color().xyz())));
            fragment.push(total_diffuse().assign(direct_diffuse().add(indirect_diffuse())));
            fragment.push(total_specular().assign(direct_specular().add(indirect_specular())));
            fragment.push(outgoing_light().assign(total_diffuse().add(total_specular())));

            // `MeshBasicNodeMaterial.setupEnvironment()` โ†’
            // `BasicEnvironmentNode( cubeTexture( envMap ) )`, sampled along the
            // reflect vector and blended in by `reflectivity`.
            let dir = material_env_rotation().mul(vec4_join(vec![reflect_vector(), float(1.0)]));
            let env = cube_texture(env_map, dir);
            fragment.push(outgoing_light().assign(mix(
                outgoing_light(),
                outgoing_light().mul(env.xyz()),
                float(1.0).mul(material_reflectivity()),
            )));
            outgoing_light()
        } else {
            // `setupOutgoingLight()` with `lights === false`.
            diffuse_color().xyz()
        };

        // `setupLighting()`'s EMISSIVE tail. `MeshBasicMaterial` has no
        // `emissive` colour, so an unlit material reaches it only through
        // `emissiveNode`: `EmissiveColor = vec3( emissiveNode )`, then
        // `outgoingLight = outgoingLight + EmissiveColor`.
        let outgoing = match &material.emissive_node {
            Some(node) => {
                fragment.push(emissive_color().assign(to_vec3(node.clone())));
                outgoing.add(emissive_color())
            }
            None => outgoing,
        };

        // `basicOutput = vec4( outgoingLight, diffuseColor.a ).max( 0 )`.
        vec4_join(vec![outgoing, diffuse_color().w()]).max(float(0.0))
    };

    // `NodeMaterial.setupOutput()`: `scene.fogNode` mixes over the colour only,
    // leaving the alpha โ€” `vec4( mix( output.rgb, fogColor, factor ), output.a )`.
    let output = match fog.filter(|_| material.fog) {
        Some(fog) => {
            fragment.push(output_property().assign(output));
            let mixed = vec4_join(vec![
                mix(
                    output_property().xyz(),
                    fog.color.clone(),
                    // Built now, inside this material's `setupPositionView`
                    // scope, as three builds `Fog.js`' `Fn()` (ยง41).
                    crate::nodes::tsl::resolve_fog_factor(&fog.factor),
                ),
                output_property().w(),
            ]);
            // The builder's own `emit_output_property` writes the second
            // `Output = โ€ฆ`, so pushing it here too would double the line.
            mixed
        }
        None => output,
    };

    // `NodeMaterial.setupOutput()`'s second half: `if ( this.premultipliedAlpha
    // === true ) outputNode = premultiplyAlpha( outputNode )`, after the fog
    // and before the output assignment. The SSAA accumulation quad is the one
    // caller โ€” its dump is `output.color = fn0( fn1( โ€ฆ ) )` with `fn0` the
    // premultiply and `fn1` `unpremultiplyAlpha` from its own fragment node.
    let output = if material.premultiplied_alpha {
        premultiply_alpha(output)
    } else {
        output
    };

    // `NodeMaterial.setup()`'s MRT branch, which runs only `if ( renderTarget
    // !== null )`: the pass's MRT and the material's are merged with the
    // material's winning, and the merged node โ€” not the colour โ€” becomes the
    // fragment stage's result. The `Output` property assignment above has
    // already happened, which is what lets the MRT's `output` member read it
    // back (`output.m0 = Output;` in three's dump).
    let mrt = ctx.mrt.as_ref().map(|context| {
        let merged = match &material.mrt_node {
            Some(material_mrt) => context.node.merge(material_mrt),
            None => context.node.clone(),
        };
        merged.members(&context.attachments)
    });

    // --- the vertex flow
    let position = match &material.vertex_node {
        Some(node) => node.clone(),
        None => model_view_projection(),
    };
    // `PointsNodeMaterial.setupVertex()`: on anything but `Points` โ€” a
    // `Sprite` with `count` instances โ€” the clip position is offset into a
    // screen-space quad.
    let position = if material.kind == MaterialKind::Points && ctx.sprite {
        setup_vertex_sprite(material, position)
    } else {
        position
    };

    // `if ( builder.context.getOutput ) resultNode = builder.context.getOutput(
    // resultNode, builder );` โ€” `DirectRenderPipeline`'s hook, which does
    // `output.assign( materialOutputNode )` and then returns its own node. The
    // assign is a *second* write to the `Output` property, on top of
    // `NodeMaterial.setup()`'s own, and three's dump has both lines.
    //
    // The MRT branch runs only with a render target bound, and the hook only
    // without one, so the two never meet.
    // A deferred `Fn()` output node runs here, in this material's context
    // (see `resolve_fn_call`).
    let material_output = material
        .output_node
        .as_ref()
        .map(crate::nodes::tsl::resolve_fn_call);
    let (output_assign, output_node) = match &ctx.output {
        Some(context) => (
            Some(material_output.unwrap_or_else(|| output.clone())),
            Some(context.node.clone()),
        ),
        None => (None, material_output),
    };

    MaterialFlow {
        pre_vertex_statements: pre_vertex,
        // `if ( this.depthWrite === true || this.depthTest === true )` โ€”
        // three's own guard on `setupDepth()`. The port carries only the
        // explicit `depthNode` branch; the logarithmic / orthographic
        // fallbacks want `renderer.logarithmicDepthBuffer`, which no rung sets.
        depth: material
            .depth_node
            .clone()
            .filter(|_| material.depth_write || material.depth_test),
        fragment_statements: fragment,
        output,
        output_assign,
        output_node,
        mrt,
        emit_output_property: material.fragment_node.is_none(),
        vertex_statements: Vec::new(),
        position,
    }
}

/// `vec3( node )`: a scalar splats, a wider vector narrows, a `vec3` passes
/// through โ€” `NodeBuilder.format()`'s two cases.
fn to_vec3(node: NodeRef) -> NodeRef {
    match node.ty() {
        Type::Vec3 => node,
        Type::Vec4 => node.xyz(),
        _ => node.to(Type::Vec3),
    }
}

/// `vec2( node )`.
fn to_vec2(node: NodeRef) -> NodeRef {
    match node.ty() {
        Type::Vec2 => node,
        Type::Vec3 | Type::Vec4 => node.xy(),
        _ => node.to(Type::Vec2),
    }
}

/// `SpriteNodeMaterial.setupPositionView()`
/// (`src/materials/nodes/SpriteNodeMaterial.js:110`) โ€” the sprite vertex
/// shader, in view space:
///
/// ```ignore
/// const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
/// let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(),
///                   modelWorldMatrix[ 1 ].xyz.length() );
/// if ( scaleNode !== null ) scale = scale.mul( vec2( scaleNode ) );
/// if ( camera.isPerspectiveCamera && sizeAttenuation === false )
///     scale = scale.mul( mvPosition.z.negate() );
/// let alignedPosition = positionGeometry.xy;
/// if ( object.center && object.center.isVector2 )
///     alignedPosition = alignedPosition.sub( reference( 'center', 'vec2', object ).sub( 0.5 ) );
/// alignedPosition = alignedPosition.mul( scale );
/// const rotation = float( rotationNode || materialRotation );
/// return vec4( mvPosition.xy.add( rotate( alignedPosition, rotation ) ),
///              mvPosition.zw );
/// ```
///
/// `object.center` exists only on a [`Sprite`](crate::objects::Sprite), so
/// `has_center` is [`SetupContext::sprite`].
fn setup_position_view_sprite(material: &MeshBasicNodeMaterial, has_center: bool) -> NodeRef {
    let position = match &material.position_node {
        Some(node) => to_vec3(node.clone()),
        None => vec3(0.0, 0.0, 0.0),
    };
    let mv_position = model_view_matrix().mul(position);

    let mut scale = join(
        Type::Vec2,
        vec![
            length(model_world_matrix().element(0).xyz()),
            length(model_world_matrix().element(1).xyz()),
        ],
    );
    if let Some(scale_node) = &material.scale_node {
        scale = scale.mul(to_vec2(scale_node.clone()));
    }
    if !material.size_attenuation {
        // The perspective-camera branch; the ladder's only sprite material
        // leaves `sizeAttenuation` at its default `true`, which omits it.
        scale = scale.mul(mv_position.z().negate());
    }

    let mut aligned = position_geometry().xy();
    if has_center {
        let center = uniform(
            UniformSource::ObjectCenter,
            Type::Vec2,
            UniformGroup::Object,
            None,
        );
        aligned = aligned.sub(center.sub(0.5));
    }
    let aligned = aligned.mul(scale);
    let rotation = match &material.rotation_node {
        Some(node) => node.clone(),
        None => material_rotation(),
    };

    join(
        Type::Vec4,
        vec![
            mv_position.xy().add(rotate(aligned, rotation)),
            mv_position.zw(),
        ],
    )
}

/// `PointsNodeMaterial.setupVertexSprite()`
/// (`src/materials/nodes/PointsNodeMaterial.js:89-150`) โ€” each instance's
/// quad corner pushed out from the clip position by `sizeNode` pixels:
///
/// ```ignore
/// let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
/// pointSize = pointSize.mul( screenDPR );
/// if ( camera.isPerspectiveCamera && sizeAttenuation === true )
///     pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
/// if ( scaleNode ) pointSize = pointSize.mul( vec2( scaleNode ) );
/// let offset = positionGeometry.xy;
/// if ( rotationNode ) offset = rotate( offset, float( rotationNode ) );
/// offset = offset.mul( pointSize ).div( viewportSize.div( 2 ) ).mul( mvp.w );
/// return mvp.add( vec4( offset, 0, 0 ) );
/// ```
///
/// Ported for what the ladder sets: a `sizeNode` and `sizeAttenuation =
/// false`. `materialPointSize` (no `sizeNode`) and the attenuated branch are
/// reported by the renderer's unsupported-field warning and draw as if
/// `sizeNode` were 1 and attenuation off. `viewportSize` is `viewport.zw`,
/// which is what three's dump reads.
fn setup_vertex_sprite(material: &MeshBasicNodeMaterial, mvp: NodeRef) -> NodeRef {
    let size = match &material.size_node {
        Some(node) => to_vec2(node.clone()),
        None => vec2(1.0, 1.0),
    };
    let mut point_size = size.mul(to_vec2(screen_dpr()));
    if let Some(scale) = &material.scale_node {
        point_size = point_size.mul(to_vec2(scale.clone()));
    }
    let mut offset = position_geometry().xy();
    if let Some(rotation) = &material.rotation_node {
        offset = rotate(offset, rotation.clone());
    }
    let offset = offset
        .mul(point_size)
        .div(viewport().zw().div(vec2(2.0, 2.0)))
        .mul(to_vec2(mvp.w()));
    mvp.add(vec4_join(vec![offset, float(0.0), float(0.0)]))
}

/// `PointsNodeMaterial.setupPositionView()`
/// (`src/materials/nodes/PointsNodeMaterial.js:81-87`):
///
/// ```ignore
/// return modelViewMatrix.mul( vec3( this.positionNode || positionLocal ) ).xyz;
/// ```
///
/// It is `NodeMaterial`'s own formula with one difference that shows in the
/// generated WGSL: the position node is read *again* here rather than through
/// the `positionLocal` var `setupPosition()` just assigned it to, so the
/// vertex shader indexes the storage buffer twice. `mul` on a `mat4` and a
/// `vec3` is `NodeBuilder.format( snippet, 'vec3', 'vec4' )`, i.e.
/// `vec4<f32>( v, 1.0 )` โ€” spelt out here, as
/// [`transform_direction`](crate::nodes::tsl::transform_direction) does.
fn setup_position_view_points(material: &MeshBasicNodeMaterial) -> NodeRef {
    let position = match &material.position_node {
        Some(node) => to_vec3(node.clone()),
        None => position_local(),
    };
    model_view_matrix()
        .mul(vec4_join(vec![position, float(1.0)]))
        .xyz()
}

/// `Background.update()`'s skybox material: the cube map sampled along
/// `normalWorldGeometry` with the background rotation and LOD, on a sphere
/// pinned to the far plane.
#[doc(hidden)]
pub fn background_color_node(map: &crate::textures::CubeTexture) -> NodeRef {
    let dir = material_env_rotation()
        .mul(background_rotation().mul(vec4_join(vec![normal_world_geometry(), float(1.0)])));
    let sample = cube_texture_level(map, dir, background_blurriness());
    sample.mul(background_intensity())
}

/// `scene.background = <a generated PMREM>`: the skybox sphere sampling the
/// PMREM cube, which is the `isNode` branch with
/// `NodeManager.getBackgroundNode()`'s `pmremTexture( background )` inside it
/// and the node context supplying the two accessors.
///
/// `getUV: () => backgroundRotation.mul( normalWorldGeometry )` and
/// `getTextureLevel: () => backgroundBlurriness` are the context; the port has
/// no node context, so they are passed as arguments, which is the same graph.
/// `backgroundRotation` is a `mat4`, so the product is a `vec4`, which
/// `materialEnvRotation` multiplies as it is โ€” three's own dump reads
/// `object.nodeUniform1 * ( render.nodeUniform2 * vec4( normalWorldGeometry,
/// 1.0 ) )` off exactly that.
#[doc(hidden)]
pub fn background_pmrem_color_node(pmrem: &crate::materials::environment::PmremHandle) -> NodeRef {
    let uv = background_rotation().mul(vec4_join(vec![normal_world_geometry(), float(1.0)]));
    background_node_color_node(pmrem.sample(uv, background_blurriness()))
}

/// `scene.backgroundNode` set to an environment graph: the same context as
/// [`background_pmrem_color_node`] โ€” `backgroundRotation.mul(
/// normalWorldGeometry )` and `backgroundBlurriness` โ€” handed to every
/// `pmremTexture()` in it. A `.context( { getTextureLevel } )` on the node
/// itself ([`EnvironmentNode::with_texture_level`]) is inside this one and
/// wins, as the inner context does in three.
///
/// Three calls `getUV()` once per leaf, and its dump repeats the rotation for
/// each; the port builds it once and shares it, which is the same value.
///
/// [`EnvironmentNode::with_texture_level`]: crate::materials::environment::EnvironmentNode::with_texture_level
#[doc(hidden)]
pub fn background_environment_color_node(
    node: &crate::materials::environment::EnvironmentNode,
) -> NodeRef {
    let uv = background_rotation().mul(vec4_join(vec![normal_world_geometry(), float(1.0)]));
    background_node_color_node(node.sample(uv, background_blurriness()))
}

/// `Background.update()`'s `isNode` branch:
/// `vec4( backgroundNode ).mul( backgroundIntensity )`. `vec4()` of a node
/// that already is one is the node itself โ€” `webgpu_equirectangular`'s
/// `texture( map, equirectUV(), 0 )` โ€” and of a colour it appends `1.0`.
#[doc(hidden)]
pub fn background_node_color_node(node: NodeRef) -> NodeRef {
    let color = match node.ty() {
        Type::Vec4 => node,
        _ => vec4_join(vec![node, float(1.0)]),
    };
    color.mul(background_intensity())
}

#[doc(hidden)]
pub fn background_vertex_node() -> NodeRef {
    let is_ortho = camera_projection_matrix()
        .element(3)
        .element(3)
        .equal(float(1.0));
    let ortho_scale = float(1.0)
        .div(camera_projection_matrix().element(1).element(1))
        .mul(float(3.0));
    let modified = is_ortho.select(position_local().mul(ortho_scale), position_local());
    let view_position = model_view_matrix().mul(vec4_join(vec![modified, float(0.0)]));
    let view_proj =
        camera_projection_matrix().mul(vec4_join(vec![view_position.xyz(), float(1.0)]));
    view_proj.set_z(view_proj.w())
}

/// `QuadMesh.render()`'s temporary `vertexNode`: a full-screen triangle driven
/// entirely by `vertexIndex`.
#[doc(hidden)]
pub fn quad_vertex_node() -> NodeRef {
    let x = const_array(vec![-1.0, -1.0, 3.0]).element_node(vertex_index());
    let y = const_array(vec![3.0, -1.0, -1.0]).element_node(vertex_index());
    join(Type::Vec4, vec![x, y, float(0.0), float(1.0)])
}

/// `RangeNode` on an instanced mesh: one `vec4` per instance, from a uniform
/// buffer indexed by a flat `instanceIndex` varying or, past the uniform buffer
/// limit, from an instanced vertex attribute.
pub fn instanced_range(
    min: impl Into<crate::nodes::tsl::RangeValue>,
    max: impl Into<crate::nodes::tsl::RangeValue>,
    count: usize,
) -> NodeRef {
    crate::nodes::tsl::instanced_range(min, max, count)
}

/// `Renderer._renderOutput()`'s material: the framebuffer texture sampled at
/// the fragment coordinate, through `renderOutput()`.
#[doc(hidden)]
pub fn output_fragment_node(
    framebuffer: &crate::textures::Texture,
    tone_mapping: ToneMapping,
) -> NodeRef {
    let coord = frag_coord().xy().div(viewport_size());
    let color = texture_uv(framebuffer, coord);
    render_output(color, tone_mapping)
}

/// `RenderOutputNode.setup()` with an sRGB output space: the alpha clamp and
/// unpremultiply, then `toneMapping` โ€” which `ToneMappingNode` applies to the
/// colour only โ€” then the sRGB OETF and the premultiply back.
pub fn render_output(color: NodeRef, tone_mapping: ToneMapping) -> NodeRef {
    let clamped = vec4_join(vec![color.rgb(), color.a().clamp(float(0.0), float(1.0))]);
    let unpremultiplied = unpremultiply_alpha(clamped);
    // `outputNode.toneMapping( toneMapping )` with the renderer's
    // `toneMappingExposure` uniform.
    let mapped = tone_mapping_node(tone_mapping, tone_mapping_exposure(), unpremultiplied);
    let encoded = vec4_join(vec![srgb_transfer_oetf(mapped.clone().rgb()), mapped.a()]);
    premultiply_alpha(encoded)
}

/// `color.toneMapping( mode, exposure )` โ€”
/// `three.js/src/nodes/display/ToneMappingNode.js`.
///
/// `NoToneMapping` returns the colour untouched; every other mode is
/// `vec4( toneMappingFn( color.rgb, exposure ), color.a )`. The exposure is a
/// node, so `scenePass.toneMapping( ACESFilmicToneMapping, 1 )` bakes the
/// literal `1.0` into the shader rather than reading the renderer's uniform
/// (`webgpu_custom_fog_background`; `docs/nodes.md` ยง24).
pub fn tone_mapping_node(mode: ToneMapping, exposure: NodeRef, color: NodeRef) -> NodeRef {
    match mode {
        ToneMapping::None => color,
        ToneMapping::Linear => vec4_join(vec![
            linear_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
        ToneMapping::Reinhard => vec4_join(vec![
            reinhard_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
        ToneMapping::AcesFilmic => vec4_join(vec![
            aces_filmic_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
        ToneMapping::Neutral => vec4_join(vec![
            neutral_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
        ToneMapping::AgX => vec4_join(vec![
            agx_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
    }
}

/// `MeshPhongNodeMaterial`'s fragment flow: `setupDiffuseColor`,
/// `setupVariants` (shininess / specular / emissive), then either the
/// `LightsNode` loop with `PhongLightingModel` or, when `lights === false`,
/// nothing but the diffuse colour. Read off the dumps in
/// `docs/rung5-progress.md` ยง4; the fog step (ยง5) is not wired yet.
///
/// `specular == false` is `MeshLambertNodeMaterial`, which is this same flow
/// under `new PhongLightingModel( false )`. Three things fall out of the flag,
/// all of them visible in `dump-postprocessing_ca/m07`:
///
/// * `MeshPhongNodeMaterial.setupVariants()`'s `shininess` and `specularColor`
///   are not emitted โ€” they are the Phong *material*'s, not the model's;
/// * `PhongLightingModel.direct()` skips its `directSpecular.addAssign`;
/// * and so `directSpecular` / `indirectSpecular` are first *read* in the
///   shared tail, which is where three's `PropertyNode` declares them, after
///   `totalDiffuse` rather than before the light loop.
fn setup_phong(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    specular: bool,
    fragment: &mut Vec<NodeRef>,
) -> NodeRef {
    setup_diffuse_color(material, ctx, fragment);

    // setupVariants: `PhongLightingModel` reads these three properties.
    if specular {
        fragment.push(shininess().assign(max(material_shininess(), float(0.0001))));
        let specular_value = match &material.specular_node {
            Some(node) => node.clone().xyz(),
            None => material_specular(),
        };
        fragment.push(specular_color().assign(specular_value));
    }
    fragment.push(emissive_color().assign(material_emissive_value(material)));

    let outgoing = if material.lights {
        // `LightsNode`: the scene's lights, or the selective subset the
        // material's `lights( [ โ€ฆ ] )` node names.
        let lights = material_lights(material, ctx);
        let ambient: Vec<usize> = lights
            .iter()
            .filter(|light| light.kind == LightKind::Ambient)
            .map(|light| light.index)
            .collect();

        // `AmbientLightNode` sorts first in `LightsNode`'s list, and its
        // `irradiance.addAssign()` is what forces `irradiance = vec3( 0 )` up
        // here rather than down in the indirect tail.
        if !ambient.is_empty() {
            phong::ambient_lights(&ambient, fragment);
        }

        fragment.push(direct_diffuse().assign(vec3(0.0, 0.0, 0.0)));
        if specular {
            fragment.push(direct_specular().assign(vec3(0.0, 0.0, 0.0)));
        }
        for light in &lights {
            if light.kind == LightKind::Ambient {
                continue;
            }
            // `ToonLightingModel` is Lambert with its own `direct()`; the
            // rest of the flow โ€” `indirect()` included โ€” is shared.
            if material.kind == MaterialKind::Toon {
                toon::direct_light(
                    light,
                    material.received_shadow_position_node.as_ref(),
                    material.gradient_map.as_ref(),
                    fragment,
                );
            } else {
                phong::direct_light(
                    light,
                    material.received_shadow_position_node.as_ref(),
                    specular,
                    fragment,
                );
            }
        }

        // The tail every lit material shares.
        fragment.push(indirect_diffuse().assign(vec3(0.0, 0.0, 0.0)));
        if ambient.is_empty() {
            fragment.push(irradiance().assign(vec3(0.0, 0.0, 0.0)));
        }
        fragment.push(
            indirect_diffuse().assign(
                vec4_join(vec![indirect_diffuse(), float(1.0)])
                    .add(
                        vec4_join(vec![irradiance(), float(1.0)])
                            .mul(diffuse_color().mul(phong::RECIPROCAL_PI)),
                    )
                    .xyz(),
            ),
        );
        fragment.push(indirect_diffuse().assign(indirect_diffuse().mul(ambient_occlusion())));
        fragment.push(total_diffuse().assign(direct_diffuse().add(indirect_diffuse())));
        if !specular {
            // Lambert reads both specular accumulators for the first time
            // here, so this is where three declares them.
            fragment.push(direct_specular().assign(vec3(0.0, 0.0, 0.0)));
            fragment.push(indirect_specular().assign(vec3(0.0, 0.0, 0.0)));
        }
        fragment.push(total_specular().assign(direct_specular().add(indirect_specular())));
        fragment.push(outgoing_light().assign(total_diffuse().add(total_specular())));
        outgoing_light()
    } else {
        // `lights = false` โ€” the example's light spheres.
        diffuse_color().xyz()
    };

    // `Output = max( vec4( outgoingLight + EmissiveColor, DiffuseColor.w ), 0 )`.
    vec4_join(vec![outgoing.add(emissive_color()), diffuse_color().w()]).max(float(0.0))
}

/// `LightsNode`'s list as one material sees it: the scene's lights, or the
/// selective subset the material's `lights( [ โ€ฆ ] )` node names.
fn material_lights(material: &MeshBasicNodeMaterial, ctx: &SetupContext) -> Vec<LightDesc> {
    match &material.lights_node {
        Some(subset) => ctx
            .lights
            .iter()
            .filter(|light| subset.contains(&light.index))
            .cloned()
            .collect(),
        None => ctx.lights.clone(),
    }
}

/// `NodeMaterial.setupAmbientOcclusion()` โ€” `AmbientOcclusion.assign( aoNode )`
/// when, and only when, the material has an `aoMap`.
///
/// `materialAO` is `texture( aoMap ).r.sub( 1 ).mul( aoMapIntensity ).add( 1 )`.
/// Nothing is emitted without the map: three leaves `aoNode` null, so the
/// property is never declared and the lighting model's own `ambientOcclusion`
/// var stays a bare `1`.
fn setup_ambient_occlusion(material: &MeshBasicNodeMaterial, fragment: &mut Vec<NodeRef>) {
    let Some(map) = &material.ao_map else {
        return;
    };

    fragment.push(
        ambient_occlusion_property().assign(
            texture(map)
                .x()
                .sub(float(1.0))
                .mul(material_ao_map_intensity())
                .add(float(1.0)),
        ),
    );
}

/// `MaterialNode.EMISSIVE` โ€” `emissive * emissiveIntensity`, times the
/// `emissiveMap` when there is one.
///
/// The map multiply is three's `emissiveNode.mul( this.getTexture( scope ) )`:
/// a `vec3` times a `vec4`, which `MathNode`'s type resolution widens to
/// `vec4( emissive, 1 ) * tex` before the assignment to the `vec3` property
/// takes `.xyz`. That is what the dump's
/// `( vec4<f32>( ( emissive * intensity ), 1.0 ) * tex ).xyz` is, and why the
/// port builds the `vec4` explicitly rather than multiplying three components.
///
/// An `emissiveNode` replaces all of it: `setupLighting()` assigns `vec3(
/// emissiveNode ? emissiveNode : materialEmissive )` on every lit kind.
fn material_emissive_value(material: &MeshBasicNodeMaterial) -> NodeRef {
    if let Some(node) = &material.emissive_node {
        return to_vec3(node.clone());
    }
    let emissive = material_emissive().mul(material_emissive_intensity());

    match &material.emissive_map {
        Some(map) => vec4_join(vec![emissive, float(1.0)])
            .mul(texture(map))
            .xyz(),
        None => emissive,
    }
}

/// `MeshStandardNodeMaterial`'s fragment flow: `setupDiffuseColor`,
/// `setupVariants` (metalness / roughness / specular / diffuse contribution),
/// then the `LightsNode` loop with `PhysicalLightingModel`. Read off
/// `handoff/scouts/rung8/MeshStandardMaterial_1{7,8,9}.frag-r186.wgsl`.
fn setup_standard(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fragment: &mut Vec<NodeRef>,
) -> NodeRef {
    // --- setupDiffuseColor
    setup_diffuse_color(material, ctx, fragment);

    // --- setupAmbientOcclusion, between `setupDiffuseColor` and
    // `setupVariants` exactly as `NodeMaterial.setup()` orders them.
    setup_ambient_occlusion(material, fragment);

    // --- setupVariants. `metalnessNode` is reached twice โ€” once for the
    // `Metalness` property and once for `DiffuseContribution` โ€” so the node is
    // shared, exactly as three.js shares the `materialMetalness` node.
    // `const metalnessNode = this.metalnessNode ? float( this.metalnessNode )
    // : materialMetalness` โ€” the explicit node replaces the uniform *and* its
    // map, because `materialMetalness` is what folds the map in.
    //
    // The `float()` matters when the node is wider than a float, as a bare
    // `texture( map )` is: `DiffuseContribution` then takes `1 - map.x` on
    // every channel, not `1 - map.rgb` (`webgpu_lights_selective`, ยง46).
    let metalness_node = match (&material.metalness_node, &material.metalness_map) {
        (Some(node), _) => node.to_float(),
        // glTF packing: metalness in blue, roughness in green.
        (None, Some(map)) => material_metalness().mul(texture(map).z()),
        (None, None) => material_metalness(),
    };
    fragment.push(metalness().assign(metalness_node.clone()));

    let roughness_node = match (&material.roughness_node, &material.roughness_map) {
        (Some(node), _) => node.to_float(),
        (None, Some(map)) => material_roughness().mul(texture(map).y()),
        (None, None) => material_roughness(),
    };
    fragment.push(roughness().assign(physical::get_roughness(
        roughness_node,
        !ctx.geometry_missing_normal,
    )));

    if material.kind == MaterialKind::Physical {
        // `MeshPhysicalNodeMaterial.setupSpecular()`: F0 from the index of
        // refraction rather than the dielectric constant 0.04, tinted by
        // `specularColor` (times `specularColorMap`) and scaled by
        // `specularIntensity` โ€” which is also the F90. This block is the entire
        // delta over the Standard material above.
        fragment.push(ior().assign(material_ior()));
        // `pow2( ior.sub( 1 ).div( ior.add( 1 ) ) )` โ€” the quotient is read
        // twice, so it is a var.
        let f0 = to_var(None, ior().sub(float(1.0)).div(ior().add(float(1.0))));
        let specular = match &material.specular_color_map {
            Some(map) => material_specular_color().mul(texture(map).xyz()),
            None => material_specular_color(),
        };
        fragment.push(
            specular_color().assign(
                f0.clone()
                    .mul(f0)
                    .mul(specular)
                    .min(vec3(1.0, 1.0, 1.0))
                    .mul(material_specular_intensity()),
            ),
        );
        fragment.push(specular_color_blended().assign(mix(
            specular_color(),
            diffuse_color().xyz(),
            metalness(),
        )));
        fragment.push(specular_f90().assign(mix(
            material_specular_intensity(),
            float(1.0),
            metalness(),
        )));
    } else {
        // `setupSpecular()`: a dielectric F0 of 0.04, blended towards the
        // albedo by metalness, and an F90 of 1.
        fragment.push(specular_color().assign(vec3(0.04, 0.04, 0.04)));
        fragment.push(specular_color_blended().assign(mix(
            vec3(0.04, 0.04, 0.04),
            diffuse_color().rgb(),
            metalness(),
        )));
        fragment.push(specular_f90().assign(float(1.0)));
    }
    fragment
        .push(diffuse_contribution().assign(diffuse_color().rgb().mul(metalness_node.one_minus())));

    // `MeshPhysicalNodeMaterial.setupVariants()`, after
    // `MeshStandardNodeMaterial`'s: diffuse roughness, clearcoat, sheen, then
    // anisotropy.
    //
    // DIFFUSE ROUGHNESS โ€” `useDiffuseRoughness` is `diffuseRoughness > 0`, and
    // `DiffuseRoughness` is `materialDiffuseRoughness.clamp()`.
    let use_diffuse_roughness =
        material.kind == MaterialKind::Physical && material.diffuse_roughness > 0.0;
    if use_diffuse_roughness {
        fragment.push(diffuse_roughness().assign(material_diffuse_roughness().clamp(0.0, 1.0)));
    }

    let use_clearcoat = material.kind == MaterialKind::Physical && material.clearcoat > 0.0;
    let use_anisotropy = material.kind == MaterialKind::Physical && material.anisotropy > 0.0;

    if use_clearcoat {
        // `MaterialNode.CLEARCOAT` / `.CLEARCOAT_ROUGHNESS`: the factor
        // times the map's red channel, the roughness times its green one.
        let clearcoat_value = match &material.clearcoat_map {
            Some(map) => material_clearcoat().mul(texture(map).x()),
            None => material_clearcoat(),
        };
        let clearcoat_roughness_value = match &material.clearcoat_roughness_map {
            Some(map) => material_clearcoat_roughness().mul(texture(map).y()),
            None => material_clearcoat_roughness(),
        };
        fragment.push(clearcoat().assign(clearcoat_value));
        fragment.push(clearcoat_roughness().assign(physical::get_roughness(
            clearcoat_roughness_value,
            !ctx.geometry_missing_normal,
        )));
    }

    // `setupVariants()`' SHEEN block, gated on
    // `useSheen` โ€” `this.sheen > 0`. `MaterialNode.SHEEN` is `sheenColor.mul(
    // sheen )` with the multiply left in the shader, and
    // `MaterialNode.SHEEN_ROUGHNESS` clamps to `[ 0.0001, 1 ]` so `1 / alpha`
    // in `D_Charlie` cannot divide by zero.
    let use_sheen = material.kind == MaterialKind::Physical && material.sheen > 0.0;
    if use_sheen {
        fragment.push(sheen().assign(material_sheen_color().mul(material_sheen())));
        fragment.push(sheen_roughness().assign(material_sheen_roughness().clamp(0.0001, 1.0)));
    }

    if use_anisotropy {
        // `materialAnisotropy` โ€” `MaterialNode.ANISOTROPY`. With a map the
        // vector is the map's polar direction rotated by the material's, scaled
        // by the map's blue channel; without one it is the uniform itself.
        let anisotropy_v = match &material.anisotropy_map {
            Some(map) => {
                let polar = texture(map);
                let v = material_anisotropy_vector();
                let rotation = join(
                    Type::Mat2,
                    vec![v.clone().x(), v.clone().y(), v.clone().y().negate(), v.x()],
                );
                rotation.mul(
                    polar
                        .clone()
                        .xy()
                        .mul(2.0)
                        .sub(vec2(1.0, 1.0))
                        .normalize()
                        .mul(polar.z()),
                )
            }
            None => material_anisotropy_vector(),
        };
        let anisotropy_v = to_var(None, anisotropy_v);

        fragment.push(anisotropy().assign(length(anisotropy_v.clone())));
        fragment.push(if_else(
            anisotropy().equal(float(0.0)),
            vec![anisotropy_v.assign(vec2(1.0, 0.0))],
            vec![
                anisotropy_v.assign(anisotropy_v.div(anisotropy())),
                anisotropy().assign(anisotropy().clamp(0.0, 1.0)),
            ],
        ));
        // Roughness along the anisotropy bitangent is the material roughness;
        // along the tangent it grows with anisotropy.
        fragment.push(alpha_t().assign(mix(
            roughness().mul(roughness()),
            float(1.0),
            anisotropy().mul(anisotropy()),
        )));
        fragment.push(
            anisotropy_t().assign(
                tbn_view_matrix()
                    .element(0)
                    .mul(anisotropy_v.clone().x())
                    .add(tbn_view_matrix().element(1).mul(anisotropy_v.clone().y())),
            ),
        );
        fragment.push(
            anisotropy_b().assign(
                tbn_view_matrix()
                    .element(1)
                    .mul(anisotropy_v.clone().x())
                    .sub(tbn_view_matrix().element(0).mul(anisotropy_v.y())),
            ),
        );
    }

    // TRANSMISSION. `useTransmission` is `transmission > 0`; the volume
    // fields ride with it whether or not `KHR_materials_volume` set them,
    // because three assigns all four unconditionally inside the branch.
    let opaque_frame = if material.kind == MaterialKind::Physical && material.transmission > 0.0 {
        ctx.viewport_opaque_mip.as_ref()
    } else {
        None
    };
    if opaque_frame.is_some() {
        fragment.push(transmission().assign(material_transmission()));
        // `MaterialNode.THICKNESS`: the factor times the map's green channel.
        let thickness_value = match &material.thickness_map {
            Some(map) => material_thickness().mul(texture(map).y()),
            None => material_thickness(),
        };
        fragment.push(thickness().assign(thickness_value));
        fragment.push(attenuation_distance().assign(material_attenuation_distance()));
        fragment.push(attenuation_color().assign(material_attenuation_color()));
    }

    fragment.push(emissive_color().assign(material_emissive_value(material)));

    // `NodeMaterial.setupLighting()`: `sceneLighting = this.lights === true &&
    // builder.renderer.lighting.enabled`, `materialLightings = sceneLighting ?
    // this.setupMaterialLightings( builder ) : []` โ€” the environment is one of
    // those, so a pass with lighting disabled drops it too โ€” and the chain is
    // built only `if ( lightsNode && ( materialLightings.length > 0 ||
    // lightsNode.getScope().hasLights ) )`. With neither, `setupOutgoingLight()`
    // stands as it is: `DiffuseColor.rgb`.
    let scene_lighting = material.lights && !ctx.lighting_disabled;
    let material_environment = material
        .pmrem_env
        .clone()
        .map(environment::Environment::Pmrem);
    let environment = material_environment
        .as_ref()
        .or(ctx.environment.as_ref())
        .filter(|_| scene_lighting);
    let lights = if scene_lighting {
        material_lights(material, ctx)
    } else {
        Vec::new()
    };

    let outgoing = if scene_lighting && (environment.is_some() || !lights.is_empty()) {
        let model = Physical::start(
            use_sheen,
            use_clearcoat,
            use_diffuse_roughness,
            opaque_frame,
            fragment,
        );

        // `LightingContextNode`'s five accumulators. three.js declares each at
        // the point of its first use; hoisting the zeros here is the one
        // reordering in this flow (see `docs/nodes.md` ยง8) and reads nothing
        // before it is written either way.
        fragment.push(direct_diffuse().assign(vec3(0.0, 0.0, 0.0)));
        fragment.push(direct_specular().assign(vec3(0.0, 0.0, 0.0)));
        fragment.push(irradiance().assign(vec3(0.0, 0.0, 0.0)));
        fragment.push(indirect_diffuse().assign(vec3(0.0, 0.0, 0.0)));
        fragment.push(indirect_specular().assign(vec3(0.0, 0.0, 0.0)));

        for light in &lights {
            physical::direct_light(
                &model,
                light,
                material.received_shadow_position_node.as_ref(),
                fragment,
            );
        }

        model.indirect_diffuse(fragment);
        // `EnvironmentNode` is a lighting node, so its two `addAssign`s land
        // between `indirectDiffuse()` and `indirectSpecular()` โ€” and with them
        // the declarations of `radiance` and `iblIrradiance`.
        if let Some(environment) = environment {
            environment::setup(environment, use_anisotropy, use_clearcoat, fragment);
        }
        // `AONode( context.ambientOcclusion )`, the last entry
        // `setupLightsNode()` pushes: `ambientOcclusion.mulAssign( aoNode )`,
        // where `aoNode` is the `AmbientOcclusion` property
        // `setup_ambient_occlusion` wrote above. The var's `float( 1 )`
        // initialiser is emitted here, at its first read.
        if material.ao_map.is_some() {
            fragment.push(
                ambient_occlusion().assign(ambient_occlusion().mul(ambient_occlusion_property())),
            );
        }
        model.indirect_specular(environment.is_some(), fragment);
        model.ambient_occlusion(material.ao_map.is_some(), fragment);

        fragment.push(
            total_diffuse().assign(model.total_diffuse(direct_diffuse().add(indirect_diffuse()))),
        );
        fragment.push(total_specular().assign(direct_specular().add(indirect_specular())));
        fragment.push(outgoing_light().assign(total_diffuse().add(total_specular())));
        // `LightingModel.finish()`, which `NodeMaterial.setupLighting()` runs
        // last: the sheen lobe and the clearcoat lobe's Fresnel blend over
        // `outgoingLight`.
        model.finish(fragment);
        outgoing_light()
    } else {
        diffuse_color().xyz()
    };

    vec4_join(vec![outgoing.add(emissive_color()), diffuse_color().w()]).max(float(0.0))
}