awsm-renderer 0.4.0

awsm-renderer
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
//! Render pass orchestration and initialization.

pub mod coverage;
pub mod display;
pub mod effects;
pub mod geometry;
pub mod hzb;
pub mod light_culling;
pub mod lines;
pub mod material_classify;
pub mod material_decal;
pub mod material_opaque;
pub mod material_prep;
pub mod material_transparent;
pub mod occlusion;
pub mod shader_cache_key;
pub mod shader_template;
pub mod shadow_custom_vertex;
pub mod shadow_masked;
pub mod shadow_masked_custom_vertex;
pub mod shared;

use std::ops::Range;

use awsm_renderer_core::renderer::AwsmRendererWebGpu;

use crate::error::Result;
use crate::features::RendererFeatures;
use crate::pipelines::compute_pipeline::{ComputePipelineCacheKey, ComputePipelineKey};
use crate::pipelines::render_pipeline::{RenderPipelineCacheKey, RenderPipelineKey};
use crate::render_passes::effects::render_pass::EffectsRenderPass;
use crate::shaders::ShaderCacheKey;
use crate::{
    bind_group_layout::BindGroupLayouts,
    pipeline_layouts::PipelineLayouts,
    pipelines::Pipelines,
    render_passes::{
        coverage::render_pass::CoverageRenderPass, display::render_pass::DisplayRenderPass,
        geometry::render_pass::GeometryRenderPass, hzb::render_pass::HzbRenderPass,
        light_culling::render_pass::LightCullingRenderPass,
        material_classify::render_pass::MaterialClassifyRenderPass,
        material_decal::render_pass::MaterialDecalRenderPass,
        material_opaque::render_pass::MaterialOpaqueRenderPass,
        material_prep::render_pass::MaterialPrepRenderPass,
        material_transparent::render_pass::MaterialTransparentRenderPass,
        occlusion::compaction::CompactionRenderPass, occlusion::render_pass::OcclusionRenderPass,
    },
    render_textures::RenderTextureFormats,
    shaders::Shaders,
    textures::Textures,
};

/// Collection of render passes used by the renderer.
pub struct RenderPasses {
    pub geometry: GeometryRenderPass,
    /// Masked (alpha-tested) shadow caster resources — bind group + lazy
    /// pipeline pool for hole-shaped (cutout) shadows. Always present; the pool
    /// stays empty (and routing falls back to the plain solid shadow pipeline)
    /// until a masked material's variant is compiled.
    pub shadow_masked: shadow_masked::ShadowMaskedRenderPass,
    /// Custom-vertex shadow caster resources — lazy pipeline pool + shared zero
    /// uv0 buffer for DISPLACED shadows that match the lit geometry. Always
    /// present; the pool stays empty (routing falls back to the plain solid shadow
    /// pipeline → un-displaced shadow) until a custom-vertex material's variant is
    /// compiled. Reuses `shadow_masked.bind_group` for group 0 (vertex-augmented).
    pub shadow_custom_vertex: shadow_custom_vertex::ShadowCustomVertexRenderPass,
    /// COMBINED masked + custom-vertex shadow caster resources — lazy pipeline
    /// pool + shared zero uv0 buffer for shadows that are BOTH displaced AND
    /// cutout (a material that is Mask AND custom-vertex). Always present; the
    /// pool stays empty (routing falls back via precedence) until such a
    /// material's variant is compiled. Reuses `shadow_masked.bind_group` for
    /// group 0 (vertex-augmented).
    pub shadow_masked_custom_vertex:
        shadow_masked_custom_vertex::ShadowMaskedCustomVertexRenderPass,
    /// GPU mesh-pixel-coverage producer. `None` when
    /// `features.coverage_lod == false`. Consumers read the resulting
    /// `MeshCoverage` table via `is_below_threshold`; with the
    /// producer disabled that always returns `false`, which routes
    /// every consumer to its "above threshold / use the expensive
    /// variant" path — the safe default.
    pub coverage: Option<CoverageRenderPass>,
    /// HZB build pass. `None` when `features.gpu_culling == false`.
    pub hzb: Option<HzbRenderPass>,
    /// GPU occlusion-cull pass. `None` when
    /// `features.gpu_culling == false`.
    pub occlusion: Option<OcclusionRenderPass>,
    /// Compaction `IndirectDrawArgs` pass. `None` when
    /// `features.gpu_culling == false`.
    pub occlusion_compaction: Option<CompactionRenderPass>,
    pub light_culling: LightCullingRenderPass,
    pub material_classify: MaterialClassifyRenderPass,
    /// Shared material-prep compute pass (Plan B). Always built (prep is
    /// unconditional); kept as an always-`Some` `Option` so the `if let
    /// Some(prep)` dispatch sites stay valid. Dispatched between classify and
    /// opaque; the opaque deferred path reads its outputs.
    pub material_prep: Option<MaterialPrepRenderPass>,
    /// Decal classify + shading + composite pass. `None` when
    /// `features.decals == false`.
    pub material_decal: Option<MaterialDecalRenderPass>,
    pub material_opaque: MaterialOpaqueRenderPass,
    pub material_transparent: MaterialTransparentRenderPass,
    pub effects: EffectsRenderPass,
    pub display: DisplayRenderPass,
}

/// Phase-1 output of [`RenderPasses::describe_shaders`]: every
/// pass's bind groups + the union of all shader cache keys the
/// pipelines will need. The orchestrator in
/// `AwsmRendererBuilder::build` pools these shader cache keys into
/// one cross-renderer `Shaders::ensure_keys` batch (alongside the
/// tail subsystems' shader cache keys), then hands the result back
/// to [`RenderPasses::describe_pipelines`].
pub struct RenderPassesShaderPlan {
    bindings: RenderPassesBindings,
    pub shader_cache_keys: Vec<ShaderCacheKey>,
}

impl RenderPassesShaderPlan {
    /// Borrow the geometry bind groups so the orchestrator can pass
    /// them to `Shadows::build_descriptors` (which needs the
    /// geometry transform / meta / animation layouts at shadow
    /// pipeline slots 1..=3) before the typed `RenderPasses` is
    /// assembled.
    pub fn geometry_bind_groups(&self) -> &geometry::bind_group::GeometryBindGroups {
        &self.bindings.geometry_bg
    }
}

/// Bind groups + the pre-built static pipelines (transparent /
/// effects / display) that aren't part of the cross-renderer pool
/// at startup. Internal — the orchestrator never inspects this
/// directly; it flows from describe_shaders → describe_pipelines →
/// from_resolved unchanged.
struct RenderPassesBindings {
    geometry_bg: geometry::bind_group::GeometryBindGroups,
    geometry_masked_bg: geometry::masked_bind_group::GeometryMaskedBindGroup,
    geometry_masked_pipelines: geometry::masked_pipeline::GeometryMaskedPipelines,
    geometry_custom_vertex_pipelines:
        geometry::custom_vertex_pipeline::GeometryCustomVertexPipelines,
    shadow_masked_bg: shadow_masked::bind_group::ShadowMaskedBindGroup,
    shadow_masked_pipelines: shadow_masked::pipeline::ShadowMaskedPipelines,
    shadow_custom_vertex_pipelines: shadow_custom_vertex::pipeline::ShadowCustomVertexPipelines,
    shadow_masked_custom_vertex_pipelines:
        shadow_masked_custom_vertex::pipeline::ShadowMaskedCustomVertexPipelines,
    geometry_masked_custom_vertex_pipelines:
        geometry::masked_custom_vertex_pipeline::GeometryMaskedCustomVertexPipelines,
    coverage_bg_single: Option<coverage::bind_group::CoverageBindGroups>,
    coverage_bg_msaa: Option<coverage::bind_group::CoverageBindGroups>,
    hzb_bg: Option<hzb::bind_group::HzbBindGroups>,
    occlusion_bg: Option<occlusion::bind_group::OcclusionBindGroups>,
    compaction_bg: Option<occlusion::compaction::CompactionBindGroups>,
    light_culling: LightCullingRenderPass,
    /// Built eagerly (like `light_culling`) and passed straight through to
    /// `from_resolved`. Always `Some` (prep is unconditional).
    material_prep: Option<MaterialPrepRenderPass>,
    classify_bg: material_classify::bind_group::MaterialClassifyBindGroups,
    decal_bg: Option<material_decal::bind_group::MaterialDecalBindGroups>,
    decal_classify_bg: Option<material_decal::classify::bind_group::DecalClassifyBindGroups>,
    opaque_bg: material_opaque::bind_group::MaterialOpaqueBindGroups,
    /// Bind-group layouts for the per-shader-id MSAA edge-resolve
    /// pipelines (Priority 3 in https://github.com/dakom/awsm-renderer/pull/99).
    /// Allocated up-front — cheap; the actual edge_resolve pipelines
    /// compile lazily via the scheduler.
    opaque_edge_bind_group_layouts: material_opaque::edge_bind_group::MaterialEdgeBindGroupLayouts,
    transparent_bg: material_transparent::bind_group::MaterialTransparentBindGroups,
    transparent_pipelines: material_transparent::pipeline::MaterialTransparentPipelines,
    effects_bg: effects::bind_group::EffectsBindGroups,
    effects_pipelines: effects::pipeline::EffectsPipelines,
    display_bg: display::bind_group::DisplayBindGroups,
    display_pipelines: display::pipeline::DisplayPipelines,
}

/// Phase-2 output of [`RenderPasses::describe_pipelines`]: the
/// per-pass pipeline cache keys, concatenated into one compute pool
/// plus one render pool, with per-pass ranges recording which slice
/// of the pool belongs to which pass. The orchestrator concatenates
/// these onto the global cross-renderer pools (alongside Picker,
/// LineRenderer, Shadows, Effects, and Display) then runs a single
/// `try_join`'d `ComputePipelines::ensure_keys` paired with
/// `RenderPipelines::ensure_keys`. The resolved keys are sliced
/// back out inside [`RenderPasses::from_resolved`].
pub struct RenderPassesDescriptors {
    bindings: RenderPassesBindings,
    /// Compute pipeline cache keys for every render pass that uses
    /// compute pipelines. The orchestrator concatenates this onto
    /// the cross-renderer compute pool.
    pub compute_pipeline_cache_keys: Vec<ComputePipelineCacheKey>,
    /// Render pipeline cache keys for every render pass that uses
    /// render pipelines (today only `Geometry`). The orchestrator
    /// concatenates this onto the cross-renderer render pool.
    pub render_pipeline_cache_keys: Vec<RenderPipelineCacheKey>,
    ranges: RenderPassesRanges,
    per_pass_descs: RenderPassesPerPassDescs,
    /// Built outside the cross-renderer pool — the composite uses
    /// an inline WGSL source that bypasses the shared shader cache
    /// and is already batched via `create_render_pipeline_promise` +
    /// `try_join` internally. Only present when `features.decals`.
    material_decal_composite: Option<material_decal::composite::MaterialDecalComposite>,
    /// Tiny initial HZB texture allocated against `ctx.gpu` during
    /// `describe_pipelines` so `from_resolved` doesn't need a gpu
    /// handle to assemble the typed `HzbRenderPass`. Per-frame
    /// resize in `render.rs` reallocates against the live viewport.
    hzb_texture: Option<hzb::texture::HzbTexture>,
}

impl RenderPassesDescriptors {
    /// Borrow the Effects pipelines holder so the orchestrator can
    /// run `EffectsPipelines::build_descriptors` against it before
    /// folding the resulting compute pipeline cache keys into the
    /// cross-renderer pool. `install_resolved` is called later via
    /// `RenderPasses::from_resolved` → field access.
    pub fn effects_pipelines(&self) -> &effects::pipeline::EffectsPipelines {
        &self.bindings.effects_pipelines
    }

    /// Borrow the Display pipelines holder so the orchestrator can
    /// run `DisplayPipelines::build_descriptors` against it.
    pub fn display_pipelines(&self) -> &display::pipeline::DisplayPipelines {
        &self.bindings.display_pipelines
    }
}

/// Each pass's slice ranges into the cross-renderer
/// `(compute_pool, render_pool)`. Indexed by `[range]` to extract
/// the resolved keys inside [`RenderPasses::from_resolved`].
struct RenderPassesRanges {
    geometry: Range<usize>,
    coverage_single: Option<Range<usize>>,
    coverage_msaa: Option<Range<usize>>,
    hzb: Option<Range<usize>>,
    occlusion: Option<Range<usize>>,
    compaction: Option<Range<usize>>,
    classify: Range<usize>,
    decal: Option<Range<usize>>,
    decal_classify: Option<Range<usize>>,
    opaque: Range<usize>,
}

/// Per-pass descriptors carried through to `from_resolved`. Each
/// pass's typed `from_resolved` may need information that wasn't
/// captured in the cache keys themselves (e.g. the opaque pass's
/// `slots`, or the decal pass's `is_msaa`).
struct RenderPassesPerPassDescs {
    geometry: crate::render_passes::geometry::pipeline::GeometryPrewarmDescriptors,
    opaque_slots: Vec<crate::render_passes::material_opaque::pipeline::OpaquePipelineSlot>,
    /// One slot per entry in the classify pass's pipeline pool —
    /// records the `msaa_sample_count` so `from_resolved` can route
    /// each compiled pipeline into the matching `Option` field on
    /// `MaterialClassifyPipelines`. Lazy-pool: the pool typically
    /// has just 1 entry (the live MSAA's variant).
    classify_slot_msaa: Vec<Option<u32>>,
    /// Slot identity per HZB pipeline pool entry. Lazy-pool: the
    /// pool has 2 entries (1 seed + 1 reduce) for the live config.
    hzb_slot: Vec<crate::render_passes::hzb::pipeline::HzbPipelineSlot>,
    decal_is_msaa: Option<Vec<bool>>,
}

impl RenderPasses {
    /// Thin wrapper for callers that don't need to pool with other
    /// subsystems: runs the 3-stage construction
    /// ([`Self::describe_shaders`] →
    /// `ctx.shaders.ensure_keys(...)` →
    /// [`Self::describe_pipelines`] → two `ensure_keys` →
    /// [`Self::from_resolved`]). The cross-renderer pooled path in
    /// `AwsmRendererBuilder::build` drives the three phases
    /// explicitly so it can fold the cache keys into shared pools.
    pub async fn new<'a>(
        ctx: &mut RenderPassInitContext<'a>,
        features: &RendererFeatures,
    ) -> Result<Self> {
        let mut plan = Self::describe_shaders(ctx, features).await?;
        // `mem::take` rather than `clone`: `describe_pipelines`
        // reads `plan.bindings` only, never `plan.shader_cache_keys`,
        // so we can move the Vec out and leave the field empty.
        let shader_keys = std::mem::take(&mut plan.shader_cache_keys);
        ctx.shaders.ensure_keys(ctx.gpu, shader_keys).await?;
        let mut descs = Self::describe_pipelines(plan, ctx, features).await?;
        // Same trick for the pipeline pools: `from_resolved` consumes
        // `descs` but doesn't read either pipeline_cache_keys Vec
        // (it slices the resolved-keys Vecs the orchestrator passes
        // back), so move the pools out instead of cloning.
        let compute_pool = std::mem::take(&mut descs.compute_pipeline_cache_keys);
        let render_pool = std::mem::take(&mut descs.render_pipeline_cache_keys);
        let compute_keys = ctx
            .pipelines
            .compute
            .ensure_keys(ctx.gpu, ctx.shaders, ctx.pipeline_layouts, compute_pool)
            .await?;
        let render_keys = ctx
            .pipelines
            .render
            .ensure_keys(ctx.gpu, ctx.shaders, ctx.pipeline_layouts, render_pool)
            .await?;
        Self::from_resolved(descs, compute_keys, render_keys)
    }

    /// Phase 1 — bind groups + shader cache keys. Sync apart from
    /// the per-pass `BindGroups::new` awaits (which are cheap; they
    /// only register layouts into the shared cache, no Dawn compile).
    /// Returns the union of every pass's shader cache keys for the
    /// orchestrator to pool into one cross-renderer
    /// `Shaders::ensure_keys` batch.
    pub async fn describe_shaders<'a>(
        ctx: &mut RenderPassInitContext<'a>,
        features: &RendererFeatures,
    ) -> Result<RenderPassesShaderPlan> {
        use crate::render_passes::coverage::pipeline::CoveragePipelines;
        use crate::render_passes::geometry::pipeline::GeometryPipelines;
        use crate::render_passes::hzb::pipeline::HzbPipelines;
        use crate::render_passes::material_classify::pipeline::MaterialClassifyPipelines;
        use crate::render_passes::material_decal::classify::pipeline::DecalClassifyPipelines;
        use crate::render_passes::material_decal::pipeline::MaterialDecalPipelines;
        use crate::render_passes::material_opaque::pipeline::MaterialOpaquePipelines;
        use crate::render_passes::occlusion::compaction::CompactionPipeline;
        use crate::render_passes::occlusion::pipeline::OcclusionPipelines;

        // ----------------------------------------------------------
        // Phase 1 — sync bind-group setup + auxiliary resources
        // ----------------------------------------------------------
        let geometry_bg = geometry::bind_group::GeometryBindGroups::new(ctx).await?;
        // Masked (alpha-tested) geometry variant: augmented group-0 bind group +
        // an empty lazy pipeline pool. Pipelines compile later (built-in PBR in
        // the texture-finalize flow; custom via the dynamic scheduler).
        let geometry_masked_bg =
            geometry::masked_bind_group::GeometryMaskedBindGroup::new(ctx).await?;
        let geometry_masked_pipelines = geometry::masked_pipeline::GeometryMaskedPipelines::new(
            ctx,
            &geometry_masked_bg,
            &geometry_bg,
        )?;
        // Custom-vertex geometry variant: reuses the masked group-0 bind group +
        // an empty lazy pipeline pool. Pipelines compile later in the
        // texture-finalize flow (parallel to the geometry masked pool).
        let geometry_custom_vertex_pipelines =
            geometry::custom_vertex_pipeline::GeometryCustomVertexPipelines::new(
                ctx,
                &geometry_masked_bg,
                &geometry_bg,
            )?;
        // Masked (alpha-tested) shadow caster: augmented group-0 bind group +
        // an empty lazy pipeline pool. Pipelines compile later in the
        // texture-finalize flow (parallel to the geometry masked pool).
        let shadow_masked_bg = shadow_masked::bind_group::ShadowMaskedBindGroup::new(ctx)?;
        let shadow_masked_pipelines = shadow_masked::pipeline::ShadowMaskedPipelines::new(
            ctx,
            &shadow_masked_bg,
            &geometry_bg,
        )?;
        // Custom-vertex shadow caster: reuses the (vertex-augmented) masked-shadow
        // group-0 bind group + an empty lazy pipeline pool + a shared zero uv0
        // buffer. Pipelines compile later in the texture-finalize flow (parallel
        // to the masked-shadow pool).
        let shadow_custom_vertex_pipelines =
            shadow_custom_vertex::pipeline::ShadowCustomVertexPipelines::new(
                ctx,
                &shadow_masked_bg,
                &geometry_bg,
            )?;
        // Combined masked + custom-vertex geometry variant: reuses the masked
        // group-0 bind group + an empty lazy pipeline pool. Pipelines compile
        // later in the texture-finalize flow (parallel to the masked + plain
        // custom-vertex pools).
        let geometry_masked_custom_vertex_pipelines =
            geometry::masked_custom_vertex_pipeline::GeometryMaskedCustomVertexPipelines::new(
                ctx,
                &geometry_masked_bg,
                &geometry_bg,
            )?;
        // Combined masked + custom-vertex shadow caster: reuses the
        // (vertex-augmented) masked-shadow group-0 bind group + an empty lazy
        // pipeline pool + a shared zero uv0 buffer. Pipelines compile later in
        // the texture-finalize flow.
        let shadow_masked_custom_vertex_pipelines =
            shadow_masked_custom_vertex::pipeline::ShadowMaskedCustomVertexPipelines::new(
                ctx,
                &shadow_masked_bg,
                &geometry_bg,
            )?;
        let (coverage_bg_single, coverage_bg_msaa) = if features.coverage_lod {
            (
                Some(coverage::bind_group::CoverageBindGroups::new(ctx, false).await?),
                Some(coverage::bind_group::CoverageBindGroups::new(ctx, true).await?),
            )
        } else {
            (None, None)
        };
        let hzb_bg = if features.gpu_culling {
            Some(hzb::bind_group::HzbBindGroups::new(ctx).await?)
        } else {
            None
        };
        let occlusion_bg = if features.gpu_culling {
            Some(occlusion::bind_group::OcclusionBindGroups::new(ctx).await?)
        } else {
            None
        };
        let compaction_bg = if features.gpu_culling {
            Some(occlusion::compaction::CompactionBindGroups::new(ctx).await?)
        } else {
            None
        };
        let light_culling = LightCullingRenderPass::new(ctx).await?;
        // Shared material-prep compute pass (Plan B). The shared prep pass is
        // unconditional now — always built (both MSAA variants). Kept as an
        // `Option` (always-`Some`) so the `if let Some(prep)` dispatch sites
        // stay valid.
        let material_prep = Some(MaterialPrepRenderPass::new(ctx).await?);
        let classify_bg =
            material_classify::bind_group::MaterialClassifyBindGroups::new(ctx).await?;
        let (decal_bg, decal_classify_bg) = if features.decals {
            (
                Some(material_decal::bind_group::MaterialDecalBindGroups::new(ctx).await?),
                Some(
                    material_decal::classify::bind_group::DecalClassifyBindGroups::new(ctx).await?,
                ),
            )
        } else {
            (None, None)
        };
        let opaque_bg = material_opaque::bind_group::MaterialOpaqueBindGroups::new(ctx).await?;
        let opaque_edge_bind_group_layouts =
            material_opaque::edge_bind_group::MaterialEdgeBindGroupLayouts::new(ctx)?;
        let transparent_bg =
            material_transparent::bind_group::MaterialTransparentBindGroups::new(ctx).await?;
        let effects_bg = effects::bind_group::EffectsBindGroups::new(ctx).await?;
        let display_bg = display::bind_group::DisplayBindGroups::new(ctx).await?;

        // Pre-build the static-pipeline subsystems whose pipelines
        // aren't part of the cross-renderer pool: transparent (no
        // per-mesh pipelines at startup; transparents compile
        // during gltf populate via
        // `set_render_pipeline_keys_batched`), effects (5 pipelines
        // compile only after AA + PP config is known, through the
        // orchestrator pool in `AwsmRendererBuilder::build`), and
        // display (1 pipeline, ditto). These constructors only
        // register bind-group + pipeline layouts; no Dawn compile.
        let transparent_pipelines =
            material_transparent::pipeline::MaterialTransparentPipelines::new(ctx, &transparent_bg)
                .await?;
        let effects_pipelines = effects::pipeline::EffectsPipelines::new(ctx, &effects_bg).await?;
        let display_pipelines = display::pipeline::DisplayPipelines::new(ctx, &display_bg).await?;

        // Collect every shader cache key the pipeline-pool phase
        // will need. The orchestrator concatenates this onto the
        // cross-renderer shader pool — see `AwsmRendererBuilder::build`.
        let mut shader_cache_keys: Vec<ShaderCacheKey> = Vec::new();
        // Geometry MSAA-lazy: only the active branch's 3 shader keys
        // at cold-boot. Inactive branch fills on first
        // set_anti_aliasing flip.
        let multisampled_geometry = ctx.anti_aliasing.has_msaa_checked()?;
        shader_cache_keys.extend(GeometryPipelines::shader_cache_keys(multisampled_geometry));
        if features.gpu_culling {
            shader_cache_keys.extend(HzbPipelines::shader_cache_keys(ctx.anti_aliasing));
            shader_cache_keys.extend(OcclusionPipelines::shader_cache_keys());
            shader_cache_keys.extend(CompactionPipeline::shader_cache_keys(features));
        }
        // Builder-time prewarm — no dynamic materials can be registered
        // before `AwsmRendererBuilder::build` returns, so the bucket
        // list is the first-party-only baseline. Mid-session
        // `register_material` changes the bucket list, which changes the
        // classify shader's cache key and triggers a recompile via the
        // same `ensure_keys` plumbing the orchestrator uses.
        let first_party_entries = crate::dynamic_materials::first_party_bucket_entries();
        shader_cache_keys.extend(MaterialClassifyPipelines::shader_cache_keys(
            ctx.gpu,
            &first_party_entries,
            ctx.anti_aliasing,
        ));
        if let Some(bg) = coverage_bg_single.as_ref() {
            shader_cache_keys.extend(CoveragePipelines::shader_cache_keys(bg));
        }
        if let Some(bg) = coverage_bg_msaa.as_ref() {
            shader_cache_keys.extend(CoveragePipelines::shader_cache_keys(bg));
        }
        if let Some(bg) = decal_bg.as_ref() {
            shader_cache_keys.extend(MaterialDecalPipelines::build_shader_cache_keys(ctx, bg)?);
        }
        if let Some(bg) = decal_classify_bg.as_ref() {
            shader_cache_keys.extend(DecalClassifyPipelines::shader_cache_keys(bg));
        }
        shader_cache_keys.extend(MaterialOpaquePipelines::build_shader_cache_keys(
            ctx, &opaque_bg,
        )?);

        Ok(RenderPassesShaderPlan {
            bindings: RenderPassesBindings {
                geometry_bg,
                geometry_masked_bg,
                geometry_masked_pipelines,
                geometry_custom_vertex_pipelines,
                shadow_masked_bg,
                shadow_masked_pipelines,
                shadow_custom_vertex_pipelines,
                shadow_masked_custom_vertex_pipelines,
                geometry_masked_custom_vertex_pipelines,
                coverage_bg_single,
                coverage_bg_msaa,
                hzb_bg,
                occlusion_bg,
                compaction_bg,
                light_culling,
                material_prep,
                classify_bg,
                decal_bg,
                decal_classify_bg,
                opaque_bg,
                opaque_edge_bind_group_layouts,
                transparent_bg,
                transparent_pipelines,
                effects_bg,
                effects_pipelines,
                display_bg,
                display_pipelines,
            },
            shader_cache_keys,
        })
    }

    /// Phase 2 — with the shader cache warm, build every per-pass
    /// pipeline cache key into one compute pool + one render pool,
    /// recording per-pass slice ranges for [`Self::from_resolved`].
    /// Sync apart from cache-hit `shaders.get_key` calls inside each
    /// pass's `build_descriptors` (which the cross-renderer
    /// `Shaders::ensure_keys` makes sub-millisecond) and the
    /// `MaterialDecalComposite::new` call (which uses inline WGSL +
    /// internal `try_join`, staying outside the cross-renderer pool
    /// by design — its 2 pipelines bypass the shared shader cache).
    pub async fn describe_pipelines<'a>(
        plan: RenderPassesShaderPlan,
        ctx: &mut RenderPassInitContext<'a>,
        _features: &RendererFeatures,
    ) -> Result<RenderPassesDescriptors> {
        use crate::render_passes::coverage::pipeline::CoveragePipelines;
        use crate::render_passes::geometry::pipeline::GeometryPipelines;
        use crate::render_passes::hzb::pipeline::HzbPipelines;
        use crate::render_passes::material_classify::pipeline::MaterialClassifyPipelines;
        use crate::render_passes::material_decal::classify::pipeline::DecalClassifyPipelines;
        use crate::render_passes::material_decal::pipeline::MaterialDecalPipelines;
        use crate::render_passes::material_opaque::pipeline::MaterialOpaquePipelines;
        use crate::render_passes::occlusion::compaction::CompactionPipeline;
        use crate::render_passes::occlusion::pipeline::OcclusionPipelines;

        let bindings = plan.bindings;
        let mut compute_pool: Vec<ComputePipelineCacheKey> = Vec::new();
        let mut render_pool: Vec<RenderPipelineCacheKey> = Vec::new();

        // Geometry MSAA-lazy: only the active branch's 9 descriptors.
        let multisampled_geometry = ctx.anti_aliasing.has_msaa_checked()?;
        let geometry_descs =
            GeometryPipelines::build_descriptors(ctx, &bindings.geometry_bg, multisampled_geometry)
                .await?;
        let geometry_range =
            render_pool.len()..render_pool.len() + geometry_descs.pipeline_cache_keys.len();
        render_pool.extend(geometry_descs.pipeline_cache_keys.iter().cloned());

        let (hzb_range, hzb_slot) = if let Some(bg) = bindings.hzb_bg.as_ref() {
            let descs = HzbPipelines::build_descriptors(ctx, bg).await?;
            let start = compute_pool.len();
            let end = start + descs.pipeline_cache_keys.len();
            compute_pool.extend(descs.pipeline_cache_keys.iter().cloned());
            (Some(start..end), descs.slot)
        } else {
            (None, Vec::new())
        };
        let occlusion_range = if let Some(bg) = bindings.occlusion_bg.as_ref() {
            let descs = OcclusionPipelines::build_descriptors(ctx, bg).await?;
            let start = compute_pool.len();
            let end = start + descs.pipeline_cache_keys.len();
            compute_pool.extend(descs.pipeline_cache_keys.iter().cloned());
            Some(start..end)
        } else {
            None
        };
        let compaction_range = if let Some(bg) = bindings.compaction_bg.as_ref() {
            let descs = CompactionPipeline::build_descriptors(ctx, bg).await?;
            let start = compute_pool.len();
            let end = start + descs.pipeline_cache_keys.len();
            compute_pool.extend(descs.pipeline_cache_keys.iter().cloned());
            Some(start..end)
        } else {
            None
        };

        let classify_first_party_entries = crate::dynamic_materials::first_party_bucket_entries();
        let classify_descs = MaterialClassifyPipelines::build_descriptors(
            ctx,
            &bindings.classify_bg,
            &classify_first_party_entries,
        )
        .await?;
        let classify_range =
            compute_pool.len()..compute_pool.len() + classify_descs.pipeline_cache_keys.len();
        compute_pool.extend(classify_descs.pipeline_cache_keys.iter().cloned());

        let coverage_single_range = if let Some(bg) = bindings.coverage_bg_single.as_ref() {
            let descs = CoveragePipelines::build_descriptors(ctx, bg).await?;
            let start = compute_pool.len();
            let end = start + descs.pipeline_cache_keys.len();
            compute_pool.extend(descs.pipeline_cache_keys.iter().cloned());
            Some(start..end)
        } else {
            None
        };
        let coverage_msaa_range = if let Some(bg) = bindings.coverage_bg_msaa.as_ref() {
            let descs = CoveragePipelines::build_descriptors(ctx, bg).await?;
            let start = compute_pool.len();
            let end = start + descs.pipeline_cache_keys.len();
            compute_pool.extend(descs.pipeline_cache_keys.iter().cloned());
            Some(start..end)
        } else {
            None
        };

        let (decal_range, decal_classify_range, decal_is_msaa) =
            if let (Some(decal_bg), Some(decal_classify_bg)) = (
                bindings.decal_bg.as_ref(),
                bindings.decal_classify_bg.as_ref(),
            ) {
                let descs = MaterialDecalPipelines::build_descriptors(ctx, decal_bg).await?;
                let start = compute_pool.len();
                let end = start + descs.pipeline_cache_keys.len();
                compute_pool.extend(descs.pipeline_cache_keys.iter().cloned());
                let decal_range = start..end;
                let is_msaa = descs.is_msaa;

                let classify_descs =
                    DecalClassifyPipelines::build_descriptors(ctx, decal_classify_bg).await?;
                let start = compute_pool.len();
                let end = start + classify_descs.pipeline_cache_keys.len();
                compute_pool.extend(classify_descs.pipeline_cache_keys.iter().cloned());
                let decal_classify_range = start..end;

                (Some(decal_range), Some(decal_classify_range), Some(is_msaa))
            } else {
                (None, None, None)
            };

        let opaque_descs =
            MaterialOpaquePipelines::build_descriptors(ctx, &bindings.opaque_bg).await?;
        let opaque_range =
            compute_pool.len()..compute_pool.len() + opaque_descs.pipeline_cache_keys.len();
        compute_pool.extend(opaque_descs.pipeline_cache_keys.iter().cloned());

        // Decal composite — only the typed handle, no cache keys to
        // pool. The composite uses inline WGSL and internal
        // `try_join` for its 2 pipelines; building it here keeps the
        // construction ordering identical to the pre-refactor flow.
        let material_decal_composite = if bindings.decal_bg.is_some() {
            Some(material_decal::composite::MaterialDecalComposite::new(ctx).await?)
        } else {
            None
        };

        // HZB texture — tiny initial allocation, recreated against
        // the live viewport on the first frame. Allocated here
        // because `from_resolved` is sync and doesn't have a gpu
        // handle; this is sub-millisecond GPU work.
        let hzb_texture = if bindings.hzb_bg.is_some() {
            Some(hzb::texture::HzbTexture::new(ctx.gpu, 1, 1)?)
        } else {
            None
        };

        Ok(RenderPassesDescriptors {
            bindings,
            compute_pipeline_cache_keys: compute_pool,
            render_pipeline_cache_keys: render_pool,
            ranges: RenderPassesRanges {
                geometry: geometry_range,
                coverage_single: coverage_single_range,
                coverage_msaa: coverage_msaa_range,
                hzb: hzb_range,
                occlusion: occlusion_range,
                compaction: compaction_range,
                classify: classify_range,
                decal: decal_range,
                decal_classify: decal_classify_range,
                opaque: opaque_range,
            },
            per_pass_descs: RenderPassesPerPassDescs {
                geometry: geometry_descs,
                opaque_slots: opaque_descs.slots,
                classify_slot_msaa: classify_descs.slot_msaa,
                hzb_slot,
                decal_is_msaa,
            },
            material_decal_composite,
            hzb_texture,
        })
    }

    /// Phase 3 — sync fold-up. Each pass's typed `from_resolved`
    /// consumes its slice of the resolved compute + render keys.
    /// `compute_keys` / `render_keys` are typically the resolved
    /// outputs of the cross-renderer
    /// `ComputePipelines::ensure_keys` / `RenderPipelines::ensure_keys`
    /// in `AwsmRendererBuilder::build`, sliced via
    /// [`RenderPassesDescriptors::compute_pipeline_cache_keys`] /
    /// [`RenderPassesDescriptors::render_pipeline_cache_keys`]
    /// ranges. Sync; no Dawn / GPU calls.
    pub fn from_resolved(
        descs: RenderPassesDescriptors,
        compute_keys: Vec<ComputePipelineKey>,
        render_keys: Vec<RenderPipelineKey>,
    ) -> Result<Self> {
        use crate::render_passes::coverage::pipeline::CoveragePipelines;
        use crate::render_passes::geometry::pipeline::GeometryPipelines;
        use crate::render_passes::hzb::pipeline::HzbPipelines;
        use crate::render_passes::material_decal::classify::pipeline::DecalClassifyPipelines;
        use crate::render_passes::material_decal::pipeline::MaterialDecalPipelines;
        use crate::render_passes::material_opaque::pipeline::MaterialOpaquePipelines;
        use crate::render_passes::occlusion::compaction::CompactionPipeline;
        use crate::render_passes::occlusion::pipeline::OcclusionPipelines;

        let RenderPassesDescriptors {
            bindings,
            ranges,
            per_pass_descs,
            material_decal_composite,
            hzb_texture,
            ..
        } = descs;
        let RenderPassesBindings {
            geometry_bg,
            geometry_masked_bg,
            geometry_masked_pipelines,
            geometry_custom_vertex_pipelines,
            shadow_masked_bg,
            shadow_masked_pipelines,
            shadow_custom_vertex_pipelines,
            shadow_masked_custom_vertex_pipelines,
            geometry_masked_custom_vertex_pipelines,
            coverage_bg_single,
            coverage_bg_msaa,
            hzb_bg,
            occlusion_bg,
            compaction_bg,
            light_culling,
            material_prep,
            classify_bg,
            decal_bg,
            decal_classify_bg,
            opaque_bg,
            opaque_edge_bind_group_layouts,
            transparent_bg,
            transparent_pipelines,
            effects_bg,
            effects_pipelines,
            display_bg,
            display_pipelines,
        } = bindings;

        let geometry = GeometryRenderPass {
            bind_groups: geometry_bg,
            pipelines: GeometryPipelines::from_resolved(
                &per_pass_descs.geometry,
                render_keys[ranges.geometry].to_vec(),
            )?,
            masked_bind_group: geometry_masked_bg,
            masked_pipelines: geometry_masked_pipelines,
            custom_vertex_pipelines: geometry_custom_vertex_pipelines,
            masked_custom_vertex_pipelines: geometry_masked_custom_vertex_pipelines,
        };

        let shadow_masked = shadow_masked::ShadowMaskedRenderPass {
            bind_group: shadow_masked_bg,
            pipelines: shadow_masked_pipelines,
        };

        let shadow_custom_vertex = shadow_custom_vertex::ShadowCustomVertexRenderPass {
            pipelines: shadow_custom_vertex_pipelines,
        };

        let shadow_masked_custom_vertex =
            shadow_masked_custom_vertex::ShadowMaskedCustomVertexRenderPass {
                pipelines: shadow_masked_custom_vertex_pipelines,
            };

        let coverage = match (
            coverage_bg_single,
            ranges.coverage_single,
            coverage_bg_msaa,
            ranges.coverage_msaa,
        ) {
            (Some(bg_s), Some(r_s), Some(bg_m), Some(r_m)) => Some(CoverageRenderPass {
                bind_groups_singlesampled: bg_s,
                bind_groups_multisampled: bg_m,
                pipelines_singlesampled: CoveragePipelines::from_resolved(
                    compute_keys[r_s].to_vec(),
                ),
                pipelines_multisampled: CoveragePipelines::from_resolved(
                    compute_keys[r_m].to_vec(),
                ),
            }),
            _ => None,
        };

        let hzb = match (hzb_bg, ranges.hzb, hzb_texture) {
            (Some(bg), Some(range), Some(texture)) => Some(HzbRenderPass {
                bind_groups: bg,
                pipelines: HzbPipelines::from_resolved(
                    per_pass_descs.hzb_slot,
                    compute_keys[range].to_vec(),
                ),
                texture,
            }),
            _ => None,
        };

        let occlusion = match (occlusion_bg, ranges.occlusion) {
            (Some(bg), Some(range)) => Some(OcclusionRenderPass {
                bind_groups: bg,
                pipelines: OcclusionPipelines::from_resolved(compute_keys[range].to_vec()),
            }),
            _ => None,
        };

        let occlusion_compaction = match (compaction_bg, ranges.compaction) {
            (Some(bg), Some(range)) => Some(CompactionRenderPass {
                bind_groups: bg,
                pipeline: CompactionPipeline::from_resolved(compute_keys[range].to_vec()),
            }),
            _ => None,
        };

        // The boot batch already compiled the classify pipeline into the shared
        // compute pool (warming it); `ensure_scene_pipelines` (via `prewarm`)
        // installs it into `pipeline_cache` before the first frame. So we don't
        // store the resolved key here — the cache is the single source of truth.
        let _ = (&per_pass_descs.classify_slot_msaa, &ranges.classify);
        let material_classify = MaterialClassifyRenderPass {
            bind_groups: classify_bg,
            pipeline_cache: std::cell::RefCell::new(std::collections::HashMap::new()),
        };

        let material_decal = match (
            decal_bg,
            ranges.decal,
            decal_classify_bg,
            ranges.decal_classify,
            per_pass_descs.decal_is_msaa,
            material_decal_composite,
        ) {
            (
                Some(decal_bg),
                Some(decal_range),
                Some(decal_classify_bg),
                Some(decal_classify_range),
                Some(decal_is_msaa),
                Some(composite),
            ) => Some(MaterialDecalRenderPass {
                bind_groups: decal_bg,
                pipelines: MaterialDecalPipelines::from_resolved(
                    decal_is_msaa,
                    compute_keys[decal_range].to_vec(),
                ),
                composite,
                classify_pass: material_decal::classify::render_pass::DecalClassifyRenderPass {
                    bind_groups: decal_classify_bg,
                    pipelines: DecalClassifyPipelines::from_resolved(
                        compute_keys[decal_classify_range].to_vec(),
                    ),
                },
            }),
            _ => None,
        };

        let material_opaque = MaterialOpaqueRenderPass {
            bind_groups: opaque_bg,
            pipelines: MaterialOpaquePipelines::from_resolved(
                per_pass_descs.opaque_slots,
                compute_keys[ranges.opaque].to_vec(),
            ),
            // Edge-resolve pipelines are scheduler-managed — empty
            // at cold-boot, populate lazily as edge_resolve compile
            // futures resolve.
            edge_pipelines:
                crate::render_passes::material_opaque::edge_pipeline::MaterialEdgePipelines::new(),
            edge_bind_group_layouts: opaque_edge_bind_group_layouts,
        };

        let material_transparent = MaterialTransparentRenderPass {
            bind_groups: transparent_bg,
            pipelines: transparent_pipelines,
        };

        let effects = EffectsRenderPass {
            bind_groups: effects_bg,
            pipelines: effects_pipelines,
        };

        let display = DisplayRenderPass {
            bind_groups: display_bg,
            pipelines: display_pipelines,
            last_exposure_scale: std::cell::Cell::new(None),
        };

        Ok(Self {
            geometry,
            shadow_masked,
            shadow_custom_vertex,
            shadow_masked_custom_vertex,
            coverage,
            hzb,
            occlusion,
            occlusion_compaction,
            light_culling,
            material_classify,
            material_prep,
            material_decal,
            material_opaque,
            material_transparent,
            effects,
            display,
        })
    }
}

/// Shared context used to initialize render passes.
///
/// `gpu` is `&` (not `&mut`) on purpose — no init path mutates the
/// `AwsmRendererWebGpu` handle; everything goes through the shared
/// `device` / `queue` JS handles which are `Clone`-cheap on
/// `wasm-bindgen` types. Keeping it shared lets `RenderPasses::new`
/// and `RenderTextures::new` run inside the same `futures::try_join`
/// in `lib.rs` — both want `&gpu`, neither contends on the other's
/// `&mut` fields.
pub struct RenderPassInitContext<'a> {
    pub gpu: &'a AwsmRendererWebGpu,
    pub bind_group_layouts: &'a mut BindGroupLayouts,
    pub textures: &'a mut Textures,
    pub pipeline_layouts: &'a mut PipelineLayouts,
    pub pipelines: &'a mut Pipelines,
    pub shaders: &'a mut Shaders,
    pub render_texture_formats: &'a mut RenderTextureFormats,
    /// Active feature gates. Lets construction-time code (e.g. the
    /// decal classify pass's HZB binding switch) pick the variant
    /// that matches the live feature set.
    pub features: &'a RendererFeatures,
    /// Active MSAA + mipmap state. Lazy-pool passes use this to
    /// compile only the variant matching the live config; the
    /// other (msaa, mipmap) combinations get compiled on demand
    /// when the caller invokes `AwsmRenderer::set_anti_aliasing`.
    pub anti_aliasing: &'a crate::anti_alias::AntiAliasing,
    /// Active post-processing state (bloom, tonemapping, DoF, ...).
    /// Same role as `anti_aliasing`: lazy-pool passes only compile
    /// the live-config variant up-front.
    pub post_processing: &'a crate::post_process::PostProcessing,
    /// Plan B shared-prep config (carries the `K` shadow-caster sizing knob).
    /// The prep pass is unconditional.
    pub prep_config: &'a crate::render_passes::material_prep::PrepPassConfig,
    /// Resolved edge-pixel budget (matches `MaterialEdgeBuffers::max_edge_budget`).
    /// Sizes the prep pass's compact per-edge-sample shadow texture (Stage
    /// 5b-shadow); only consulted by the MSAA prep pipeline.
    pub max_edge_budget: u32,
}