frust-engine 0.5.2

Sparse-strip GPU render pipeline for Frust: compiles a scene display list into strips and records the draw passes on wgpu.
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
//! The nine render pipelines the engine draws with, as plain values.
//!
//! Six of them rasterize sparse strips out of the one `strip.wgsl` program,
//! differing only in their render state; two more clear and copy intermediate
//! textures, and the last runs one pass of a layer
//! [filter](crate::filters). Each is described by a
//! [`frust_gpu::RenderPipelineDesc`] — a value holding no GPU handle — so the
//! whole set can be listed at start-up and handed to
//! [`frust_gpu::PipelineCache::warm_up`] before the first frame asks for one.
//! That is the substrate's stated contract: a frame is never the first place a
//! pipeline gets compiled.
//!
//! ## The six strip variants
//!
//! | Variant | Target | Blend | Depth |
//! |---|---|---|---|
//! | [`EnginePipeline::StripIntermediate`] | [`INTERMEDIATE_FORMAT`] | premultiplied | none |
//! | [`EnginePipeline::StripAlpha`] | the frame's target format | premultiplied | none |
//! | [`EnginePipeline::StripDepthAlpha`] | the frame's target format | premultiplied | test, no write |
//! | [`EnginePipeline::StripOpaque`] | the frame's target format | none | test and write |
//! | [`EnginePipeline::StripDestOut`] | the frame's target format | [`DEST_OUT_BLEND`] | none |
//! | [`EnginePipeline::StripDepthDestOut`] | the frame's target format | [`DEST_OUT_BLEND`] | test, no write |
//!
//! The depth comparison is [`wgpu::CompareFunction::LessEqual`] against a
//! [`DEPTH_FORMAT`] attachment, which is what the vertex stage's own z
//! encoding expects: `strip.wgsl` maps painter's-order index 0 (the backmost
//! draw) to z = 1.0 and each draw in front of it to a smaller z, so drawing
//! front-to-back lets the opaque pass reject everything already covered.
//!
//! ## The atlas-layer target
//!
//! A pass that rasterizes glyph outlines into one layer of the atlas array
//! draws through [`ATLAS_STRIP_PIPELINE`], which is
//! [`EnginePipeline::StripIntermediate`] itself rather than a variant of its
//! own. An atlas layer is an [`crate::gpu::atlas::ATLAS_FORMAT`] colour target
//! with no depth attachment, composited source-over so a COLR glyph's layers
//! and a re-used slot's clear stack in the order they were recorded — which is
//! the render state `StripIntermediate` already *is*, field for field. A second
//! enum arm carrying identical state would compile a second identical pipeline
//! object, and would break
//! `the_warm_up_list_covers_every_pipeline_exactly_once`, whose whole point is
//! that no two arms describe the same pipeline. What the atlas target gets
//! instead is a name and [`the_atlas_target_reuses_the_intermediate_variant`],
//! which pins the format equality the reuse rests on: if either format is ever
//! moved, that test fails rather than glyphs quietly rendering through a
//! pipeline whose colour target no longer matches its attachment.
//!
//! ## The destination-out pair
//!
//! The hole punch [`crate::compile::clear`] lowers is a strip run like any
//! other — same program, same instance layout — and differs only in its blend
//! state, which is why it is a pipeline variant rather than a shader of its
//! own. [`DEST_OUT_BLEND`] computes `dst · (1 − src.a)` in fixed function, for
//! the colour *and* the alpha component, which is what erases a rectangle to
//! `(0, 0, 0, 0)` without a shader-side composite reading a target it is also
//! writing.
//!
//! There are two of them for the same reason there are two alpha variants: a
//! pipeline's depth state has to agree with whether the pass it runs in
//! attaches a depth buffer at all, and the engine's depth attachment is
//! optional (no attachment, or `FRUST_ENGINE_NO_DEPTH`). The depth-testing one
//! is what restores the paint order the display list recorded; the other is
//! the same trade the two draw passes already make when they collapse into one.
//!
//! ## The filter pass
//!
//! [`EnginePipeline::Filter`] is a genuinely new pipeline rather than a second
//! name for an existing one: a different program (`filter.wgsl`), a different
//! instance layout ([`filter_vertex_layout`], eight words per instance against
//! the strip's six), and a different bind-group shape. It writes
//! [`INTERMEDIATE_FORMAT`] unblended and with no depth, because a filter pass
//! *replaces* the region it writes rather than compositing onto it — the
//! scheduler clears the destination page ahead of every filter round, and the
//! quad overdraws a transparent padding border around the region for the same
//! reason (see [`crate::schedule`]'s *Filter rounds*).
//!
//! It is also where the engine's **first sampler** appears. Every other
//! pipeline reads its textures with `textureLoad` at integer coordinates; the
//! blur kernels sample bilinearly at fractional offsets, which is what lets a
//! decimation cost four samples instead of sixteen and a convolution tap one
//! instead of two. The sampler itself is [`crate::gpu::targets::filter_sampler`]
//! — the layout here only has to know that group 1 carries a texture *and* a
//! sampler.
//!
//! ## Bind groups
//!
//! [`frust_gpu::RenderPipelineDesc`] has no explicit-layout axis: every
//! pipeline uses wgpu's default layout, derived from the shader module. The
//! group structure is therefore whatever the WGSL declares, and it matches the
//! reference renderer's explicit layouts group for group — strip programs bind
//! groups 0..3 (alphas + config + layer input; atlas array + external texture;
//! encoded paints; gradient LUT), which is the WebGL2 ceiling of four exactly,
//! with no headroom. The filter program binds two (the filter-data texture;
//! the source page plus its sampler), well inside it.
//! [`EnginePipeline::layout_desc`] restates each pipeline's shape as the value
//! `frust_gpu::lint::lint_pipeline_layout` checks, so that ceiling is a test
//! rather than a comment.

use frust_gpu::lint::PipelineLayoutDesc;
use frust_gpu::{PipelineCache, RenderPipelineDesc, ShaderId, ShaderLibrary, VertexLayout};

use super::GpuStrip;
use super::config::GpuConfig;
use super::shader_src;

/// The format every intermediate (off-screen) strip target uses.
///
/// Fixed rather than negotiated: an intermediate exists only to be sampled or
/// copied by a later pass in the same frame, so it never has to agree with a
/// surface's own format.
pub const INTERMEDIATE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;

/// The fixed-function destination-out blend the punch pass draws with.
///
/// `src · 0 + dst · (1 − src.a)`, applied to the colour *and* the alpha
/// component — the `COMPOSE_DEST_OUT` arm of `shaders/blend.wgsl` evaluated for
/// a premultiplied source, without the shader-side composite that arm would
/// need a readable backdrop for. See [`crate::compile::clear`]'s module doc for
/// why the erase is a destination-out composite rather than a clear op.
pub const DEST_OUT_BLEND: wgpu::BlendState = wgpu::BlendState {
    color: DEST_OUT_COMPONENT,
    alpha: DEST_OUT_COMPONENT,
};

/// The one blend component [`DEST_OUT_BLEND`] applies to both channels.
const DEST_OUT_COMPONENT: wgpu::BlendComponent = wgpu::BlendComponent {
    src_factor: wgpu::BlendFactor::Zero,
    dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
    operation: wgpu::BlendOperation::Add,
};

/// The depth attachment format the depth-testing strip variants use.
///
/// 24 bits is what the vertex stage's z encoding is quantized to (it divides
/// the painter's-order index by `1 << 24`), so a wider format would buy no
/// extra ordering resolution.
pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus;

/// Every strip instance expands to one quad, so every pipeline here draws a
/// four-vertex strip with no index buffer.
pub const TOPOLOGY: wgpu::PrimitiveTopology = wgpu::PrimitiveTopology::TriangleStrip;

/// Vertex entry point of the strip, clear (region) and copy programs alike.
pub const VS_MAIN: &str = "vs_main";

/// Vertex entry point of the scissor-driven atlas clear.
pub const VS_MAIN_FULLSCREEN: &str = "vs_main_fullscreen";

/// Fragment entry point of every program here.
pub const FS_MAIN: &str = "fs_main";

/// Bind groups the strip programs declare: alphas/config/layer input, atlas
/// array/external texture, encoded paints, gradient LUT.
const STRIP_BIND_GROUPS: usize = 4;

/// Bind groups the copy program declares: its source texture.
const COPY_BIND_GROUPS: usize = 1;

/// Bind groups the filter program declares: the filter-data texture, then the
/// source page together with the sampler its kernels read it through.
const FILTER_BIND_GROUPS: usize = 2;

/// The engine's compiled shader modules, by id.
///
/// Registered once at start-up into the [`ShaderLibrary`] a
/// [`PipelineCache`] is built over; a [`RenderPipelineDesc`] then names its
/// program by id rather than by source.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EngineShaders {
    /// The sparse-strip rasterizer, shared by all four strip variants.
    pub strip: ShaderId,
    /// Region and fullscreen clears.
    pub clear: ShaderId,
    /// Rectangular region copies.
    pub copy: ShaderId,
    /// One pass of a layer filter's sequence.
    pub filter: ShaderId,
}

impl EngineShaders {
    /// Compiles every module in [`shader_src::MODULES`] into `library` and
    /// returns their ids.
    ///
    /// Insertion is idempotent per name, so calling this twice against the
    /// same library returns the same ids without recompiling.
    #[must_use]
    pub fn register(library: &mut ShaderLibrary, device: &wgpu::Device) -> Self {
        Self {
            strip: library.insert_wgsl(device, shader_src::STRIP_NAME, shader_src::STRIP),
            clear: library.insert_wgsl(device, shader_src::CLEAR_NAME, shader_src::CLEAR),
            copy: library.insert_wgsl(device, shader_src::COPY_NAME, shader_src::COPY),
            filter: library.insert_wgsl(device, shader_src::FILTER_NAME, shader_src::FILTER),
        }
    }
}

/// Which of the four registered modules a pipeline draws with.
///
/// The module identity a [`RenderPipelineDesc`] carries is a [`ShaderId`],
/// which only a [`ShaderLibrary`] can mint. This names the same distinction
/// without a device in the loop.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EngineShaderModule {
    /// `strip.wgsl` — the sparse-strip rasterizer.
    Strip,
    /// `clear.wgsl` — region and fullscreen clears.
    Clear,
    /// `copy.wgsl` — rectangular region copies.
    Copy,
    /// `filter.wgsl` — one pass of a layer filter's sequence.
    Filter,
}

/// One of the engine's render pipelines.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EnginePipeline {
    /// Strips into an [`INTERMEDIATE_FORMAT`] off-screen target.
    StripIntermediate,
    /// Strips into the frame's own target, alpha-blended, no depth.
    StripAlpha,
    /// Strips into the frame's own target, alpha-blended, depth-tested but
    /// not depth-writing.
    StripDepthAlpha,
    /// Strips into the frame's own target, opaque, depth-tested and
    /// depth-writing.
    StripOpaque,
    /// Hole-punch coverage into the frame's own target, destination-out, no
    /// depth.
    StripDestOut,
    /// Hole-punch coverage into the frame's own target, destination-out,
    /// depth-tested but not depth-writing.
    StripDepthDestOut,
    /// Clears rectangular regions of an intermediate target.
    Clear,
    /// Copies rectangular regions between intermediate targets.
    Copy,
    /// Runs one pass of a layer filter's sequence into an intermediate target,
    /// reading the other page of the pair through a bilinear sampler.
    Filter,
}

impl EnginePipeline {
    /// Every pipeline the engine warms up, in warm-up order.
    pub const ALL: [Self; 9] = [
        Self::StripIntermediate,
        Self::StripAlpha,
        Self::StripDepthAlpha,
        Self::StripOpaque,
        Self::StripDestOut,
        Self::StripDepthDestOut,
        Self::Clear,
        Self::Copy,
        Self::Filter,
    ];

    /// A human-readable name for logs and captures.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::StripIntermediate => "strip-intermediate",
            Self::StripAlpha => "strip-alpha",
            Self::StripDepthAlpha => "strip-depth-alpha",
            Self::StripOpaque => "strip-opaque",
            Self::StripDestOut => "strip-dest-out",
            Self::StripDepthDestOut => "strip-depth-dest-out",
            Self::Clear => "clear",
            Self::Copy => "copy",
            Self::Filter => "filter",
        }
    }

    /// Whether this pipeline rasterizes strips (as opposed to clearing or
    /// copying an intermediate).
    #[must_use]
    pub const fn is_strip(self) -> bool {
        matches!(
            self,
            Self::StripIntermediate
                | Self::StripAlpha
                | Self::StripDepthAlpha
                | Self::StripOpaque
                | Self::StripDestOut
                | Self::StripDepthDestOut
        )
    }

    /// How many bind groups the pipeline's program declares.
    ///
    /// Four is the WebGL2 ceiling, which the strip programs sit exactly on.
    #[must_use]
    pub const fn bind_group_count(self) -> usize {
        match self {
            Self::StripIntermediate
            | Self::StripAlpha
            | Self::StripDepthAlpha
            | Self::StripOpaque
            | Self::StripDestOut
            | Self::StripDepthDestOut => STRIP_BIND_GROUPS,
            Self::Clear => 0,
            Self::Copy => COPY_BIND_GROUPS,
            Self::Filter => FILTER_BIND_GROUPS,
        }
    }

    /// The color format this pipeline writes, given the frame's target
    /// format.
    ///
    /// Only the variants that draw into the frame's own target take it; the
    /// rest are pinned to [`INTERMEDIATE_FORMAT`].
    #[must_use]
    pub const fn format(self, target_format: wgpu::TextureFormat) -> wgpu::TextureFormat {
        match self {
            Self::StripAlpha
            | Self::StripDepthAlpha
            | Self::StripOpaque
            | Self::StripDestOut
            | Self::StripDepthDestOut => target_format,
            Self::StripIntermediate | Self::Clear | Self::Copy | Self::Filter => {
                INTERMEDIATE_FORMAT
            }
        }
    }

    /// The color blending this pipeline uses, or `None` for an opaque write.
    #[must_use]
    pub const fn blend(self) -> Option<wgpu::BlendState> {
        match self {
            Self::StripIntermediate | Self::StripAlpha | Self::StripDepthAlpha => {
                Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING)
            }
            Self::StripDestOut | Self::StripDepthDestOut => Some(DEST_OUT_BLEND),
            // A filter pass replaces the region it writes rather than
            // compositing onto it: the round cleared the page first, and the
            // quad's padding border writes transparent black on purpose. A
            // blend would turn that deliberate erase into a no-op.
            Self::StripOpaque | Self::Clear | Self::Copy | Self::Filter => None,
        }
    }

    /// The depth state this pipeline uses, or `None` for a color-only pass.
    #[must_use]
    pub fn depth(self) -> Option<wgpu::DepthStencilState> {
        match self {
            Self::StripDepthAlpha | Self::StripDepthDestOut => Some(depth_state(false)),
            Self::StripOpaque => Some(depth_state(true)),
            Self::StripIntermediate
            | Self::StripAlpha
            | Self::StripDestOut
            | Self::Clear
            | Self::Copy
            | Self::Filter => None,
        }
    }

    /// The vertex buffer layouts this pipeline steps over.
    #[must_use]
    pub fn vertex_layouts(self) -> Vec<VertexLayout> {
        match self {
            Self::StripIntermediate
            | Self::StripAlpha
            | Self::StripDepthAlpha
            | Self::StripOpaque
            | Self::StripDestOut
            | Self::StripDepthDestOut => vec![GpuStrip::vertex_layout()],
            Self::Clear => vec![clear_vertex_layout()],
            Self::Copy => vec![copy_vertex_layout()],
            Self::Filter => vec![filter_vertex_layout()],
        }
    }

    /// Which module this pipeline draws with.
    #[must_use]
    pub const fn module(self) -> EngineShaderModule {
        match self {
            Self::StripIntermediate
            | Self::StripAlpha
            | Self::StripDepthAlpha
            | Self::StripOpaque
            | Self::StripDestOut
            | Self::StripDepthDestOut => EngineShaderModule::Strip,
            Self::Clear => EngineShaderModule::Clear,
            Self::Copy => EngineShaderModule::Copy,
            Self::Filter => EngineShaderModule::Filter,
        }
    }

    /// The registered id of the module this pipeline draws with.
    #[must_use]
    pub const fn shader(self, shaders: &EngineShaders) -> ShaderId {
        match self.module() {
            EngineShaderModule::Strip => shaders.strip,
            EngineShaderModule::Clear => shaders.clear,
            EngineShaderModule::Copy => shaders.copy,
            EngineShaderModule::Filter => shaders.filter,
        }
    }

    /// The full pipeline description, ready for
    /// [`PipelineCache::get_or_create`] or [`PipelineCache::warm_up`].
    ///
    /// `sample_count` is always 1: the engine never multisamples, since a
    /// downlevel target cannot.
    #[must_use]
    pub fn desc(
        self,
        shaders: &EngineShaders,
        target_format: wgpu::TextureFormat,
    ) -> RenderPipelineDesc {
        RenderPipelineDesc {
            shader: self.shader(shaders),
            vs: VS_MAIN.into(),
            fs: FS_MAIN.into(),
            vertex_layouts: self.vertex_layouts(),
            blend: self.blend(),
            format: self.format(target_format),
            sample_count: 1,
            depth: self.depth(),
            topology: TOPOLOGY,
        }
    }

    /// This pipeline's shape as the downlevel lint reads it, so the
    /// bind-group, vertex-topology and sample-count ceilings
    /// (`frust_gpu::lint::lint_pipeline_layout`) are checked against the real
    /// descriptions rather than restated by hand.
    #[must_use]
    pub fn layout_desc(self) -> PipelineLayoutDesc {
        let layouts = self.vertex_layouts();
        PipelineLayoutDesc {
            bind_group_count: self.bind_group_count(),
            max_vertex_buffers: layouts.len(),
            total_vertex_attributes: layouts.iter().map(|l| l.attributes.len()).sum(),
            max_vertex_buffer_stride: layouts
                .iter()
                .map(|l| l.array_stride as usize)
                .max()
                .unwrap_or(0),
            sample_count: 1,
            uniform_buffer_sizes: if self.is_strip() {
                vec![GpuConfig::SIZE as usize]
            } else {
                Vec::new()
            },
        }
    }
}

/// The depth state shared by the two depth-testing strip variants.
///
/// `depth_write_enabled` is the only axis that differs: the opaque pass writes
/// the depth it establishes, the alpha pass only tests against it.
fn depth_state(depth_write_enabled: bool) -> wgpu::DepthStencilState {
    wgpu::DepthStencilState {
        format: DEPTH_FORMAT,
        depth_write_enabled: Some(depth_write_enabled),
        depth_compare: Some(wgpu::CompareFunction::LessEqual),
        stencil: wgpu::StencilState::default(),
        bias: wgpu::DepthBiasState::default(),
    }
}

/// The clear program's instance layout: origin, size and target size, each a
/// pair of `u32`s, 24 bytes per instance.
#[must_use]
pub fn clear_vertex_layout() -> VertexLayout {
    VertexLayout {
        array_stride: 24,
        step_mode: wgpu::VertexStepMode::Instance,
        attributes: wgpu::vertex_attr_array![
            0 => Uint32x2,
            1 => Uint32x2,
            2 => Uint32x2,
        ]
        .to_vec(),
    }
}

/// The copy program's instance layout: destination origin, source origin,
/// region size and destination size, each a `u16` pair packed into one `u32`,
/// 16 bytes per instance.
#[must_use]
pub fn copy_vertex_layout() -> VertexLayout {
    VertexLayout {
        array_stride: 16,
        step_mode: wgpu::VertexStepMode::Instance,
        attributes: wgpu::vertex_attr_array![
            0 => Uint32,
            1 => Uint32,
            2 => Uint32,
            3 => Uint32,
        ]
        .to_vec(),
    }
}

/// The filter program's instance layout: two `u16`-pair extents each for the
/// source region, the destination region and the destination page, plus the
/// filter's own texel offset, the layer's unscaled extent and the pass kind —
/// eight `u32`s, 32 bytes per instance.
///
/// Byte-identical to [`crate::filters::blur::FilterInstanceData`], which is
/// what the fragment stage unpacks; `shader_src`'s own naga test pins the two
/// against each other.
#[must_use]
pub fn filter_vertex_layout() -> VertexLayout {
    VertexLayout {
        array_stride: 32,
        step_mode: wgpu::VertexStepMode::Instance,
        attributes: wgpu::vertex_attr_array![
            0 => Uint32,
            1 => Uint32,
            2 => Uint32,
            3 => Uint32,
            4 => Uint32,
            5 => Uint32,
            6 => Uint32,
            7 => Uint32,
        ]
        .to_vec(),
    }
}

/// The strip pipeline a pass whose colour attachment is one atlas array layer
/// draws through.
///
/// See the module doc's *The atlas-layer target* for why this is a name for an
/// existing variant rather than a variant of its own.
pub const ATLAS_STRIP_PIPELINE: EnginePipeline = EnginePipeline::StripIntermediate;

/// The description [`ATLAS_STRIP_PIPELINE`] is built from.
///
/// Takes no target format: the atlas array's format is fixed by the array
/// itself, so unlike a pass over the frame's own target there is nothing here
/// to negotiate. Already covered by [`warm_up_descs`] — an atlas pass is
/// therefore never the first place a pipeline is compiled, on the frames that
/// have one.
#[must_use]
pub fn atlas_strip_desc(shaders: &EngineShaders) -> RenderPipelineDesc {
    ATLAS_STRIP_PIPELINE.desc(shaders, INTERMEDIATE_FORMAT)
}

/// The full warm-up list: every pipeline in [`EnginePipeline::ALL`],
/// described against `target_format`.
#[must_use]
pub fn warm_up_descs(
    shaders: &EngineShaders,
    target_format: wgpu::TextureFormat,
) -> Vec<RenderPipelineDesc> {
    EnginePipeline::ALL
        .iter()
        .map(|pipeline| pipeline.desc(shaders, target_format))
        .collect()
}

/// Queues every engine pipeline for background compilation.
///
/// Call it once the device and the frame's target format are known. It
/// returns immediately; a variant the render thread needs before the worker
/// reaches it is stolen out of the queue and built inline rather than waited
/// on.
pub fn warm_up(
    cache: &mut PipelineCache,
    device: &wgpu::Device,
    shaders: &EngineShaders,
    target_format: wgpu::TextureFormat,
) {
    cache.warm_up(device, &warm_up_descs(shaders, target_format));
}

#[cfg(test)]
mod tests {
    use super::*;

    const TARGET: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8Unorm;

    /// Everything about a pipeline that makes it a distinct variant, minus
    /// the [`ShaderId`] — which only a [`ShaderLibrary`] can mint, and which
    /// therefore needs a device. Two pipelines that agree on all of this
    /// would compile to the same object.
    fn variant(
        pipeline: EnginePipeline,
    ) -> (
        EngineShaderModule,
        wgpu::TextureFormat,
        Option<wgpu::BlendState>,
        Option<wgpu::DepthStencilState>,
        Vec<VertexLayout>,
    ) {
        (
            pipeline.module(),
            pipeline.format(TARGET),
            pipeline.blend(),
            pipeline.depth(),
            pipeline.vertex_layouts(),
        )
    }

    #[test]
    fn the_warm_up_list_covers_every_pipeline_exactly_once() {
        assert_eq!(EnginePipeline::ALL.len(), 9);
        for (i, a) in EnginePipeline::ALL.iter().enumerate() {
            for b in EnginePipeline::ALL.iter().skip(i + 1) {
                assert_ne!(a, b, "the warm-up list repeats {}", a.label());
                assert_ne!(
                    variant(*a),
                    variant(*b),
                    "{} and {} describe the same pipeline, so one would never be reached",
                    a.label(),
                    b.label()
                );
            }
        }
    }

    #[test]
    fn every_pipeline_layout_passes_the_downlevel_lint() {
        for pipeline in EnginePipeline::ALL {
            let violations = frust_gpu::lint_pipeline_layout(&pipeline.layout_desc());
            assert!(
                violations.is_empty(),
                "{} violates a downlevel design rule: {violations:?}",
                pipeline.label()
            );
        }
    }

    #[test]
    fn the_strip_pipelines_sit_exactly_on_the_bind_group_ceiling() {
        let ceiling = wgpu::Limits::downlevel_webgl2_defaults().max_bind_groups as usize;
        for pipeline in EnginePipeline::ALL {
            assert!(
                pipeline.bind_group_count() <= ceiling,
                "{} declares {} bind groups, over the WebGL2 ceiling of {ceiling}",
                pipeline.label(),
                pipeline.bind_group_count()
            );
        }
        assert_eq!(
            EnginePipeline::StripAlpha.bind_group_count(),
            ceiling,
            "the strip programs bind the ceiling exactly, with no headroom left"
        );
    }

    #[test]
    fn no_pipeline_multisamples() {
        for pipeline in EnginePipeline::ALL {
            assert_eq!(
                pipeline.layout_desc().sample_count,
                1,
                "{} multisamples",
                pipeline.label()
            );
        }
    }

    #[test]
    fn the_strip_variants_differ_only_in_target_blend_and_depth() {
        let strips = [
            EnginePipeline::StripIntermediate,
            EnginePipeline::StripAlpha,
            EnginePipeline::StripDepthAlpha,
            EnginePipeline::StripOpaque,
            EnginePipeline::StripDestOut,
            EnginePipeline::StripDepthDestOut,
        ];
        for pipeline in strips {
            assert_eq!(pipeline.module(), EngineShaderModule::Strip);
            assert_eq!(pipeline.vertex_layouts(), vec![GpuStrip::vertex_layout()]);
            assert_eq!(pipeline.bind_group_count(), STRIP_BIND_GROUPS);
        }

        assert_eq!(
            EnginePipeline::StripIntermediate.format(TARGET),
            INTERMEDIATE_FORMAT
        );
        assert_eq!(EnginePipeline::StripAlpha.format(TARGET), TARGET);

        let premultiplied = Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING);
        assert_eq!(EnginePipeline::StripIntermediate.blend(), premultiplied);
        assert_eq!(EnginePipeline::StripAlpha.blend(), premultiplied);
        assert_eq!(EnginePipeline::StripDepthAlpha.blend(), premultiplied);
        assert_eq!(
            EnginePipeline::StripOpaque.blend(),
            None,
            "the opaque variant must not blend"
        );

        assert_eq!(EnginePipeline::StripIntermediate.depth(), None);
        assert_eq!(EnginePipeline::StripAlpha.depth(), None);
        assert_eq!(
            EnginePipeline::StripDepthAlpha
                .depth()
                .and_then(|d| d.depth_write_enabled),
            Some(false),
            "the depth-alpha variant tests depth without writing it"
        );
        assert_eq!(
            EnginePipeline::StripOpaque
                .depth()
                .and_then(|d| d.depth_write_enabled),
            Some(true),
            "the opaque variant establishes the depth later passes test against"
        );
        for pipeline in [
            EnginePipeline::StripDepthAlpha,
            EnginePipeline::StripOpaque,
            EnginePipeline::StripDepthDestOut,
        ] {
            let depth = pipeline.depth().expect("a depth-testing variant");
            assert_eq!(depth.format, DEPTH_FORMAT);
            assert_eq!(depth.depth_compare, Some(wgpu::CompareFunction::LessEqual));
        }
    }

    /// The punch pair erases `dst · (1 − src.a)` in fixed function, colour and
    /// alpha alike, and differs from the alpha pair in nothing but that blend
    /// and its depth state.
    ///
    /// Stated as arithmetic over the blend factors rather than as a comparison
    /// against a named `wgpu` preset: `wgpu` has no destination-out preset, and
    /// a punch that darkened colour without erasing alpha (or the reverse)
    /// would leave exactly the residue `compile::clear`'s contract forbids.
    #[test]
    fn the_dest_out_variants_erase_colour_and_alpha_alike() {
        for pipeline in [
            EnginePipeline::StripDestOut,
            EnginePipeline::StripDepthDestOut,
        ] {
            let blend = pipeline.blend().expect("a destination-out variant blends");
            assert_eq!(blend, DEST_OUT_BLEND);
            assert_eq!(
                blend.color,
                blend.alpha,
                "{} must erase alpha exactly as it erases colour",
                pipeline.label()
            );
            for component in [blend.color, blend.alpha] {
                assert_eq!(component.src_factor, wgpu::BlendFactor::Zero);
                assert_eq!(
                    component.dst_factor,
                    wgpu::BlendFactor::OneMinusSrcAlpha,
                    "{} must weight the destination by the source's own coverage",
                    pipeline.label()
                );
                assert_eq!(component.operation, wgpu::BlendOperation::Add);
            }
            assert_eq!(pipeline.format(TARGET), TARGET, "the punch is a frame pass");
            assert_eq!(pipeline.bind_group_count(), STRIP_BIND_GROUPS);
        }

        assert_eq!(
            EnginePipeline::StripDestOut.depth(),
            None,
            "the depth-free punch runs when the frame has no depth attachment"
        );
        assert_eq!(
            EnginePipeline::StripDepthDestOut
                .depth()
                .and_then(|d| d.depth_write_enabled),
            Some(false),
            "a punch tests the depth the opaque pass established without writing it"
        );
    }

    /// The atlas pass reuses the intermediate variant, and the equality that
    /// makes the reuse sound is checked rather than asserted in prose.
    ///
    /// A colour attachment whose format disagrees with its pipeline's is a
    /// validation error, not a mis-render — but the failure would surface on a
    /// device, on the first frame that missed a glyph, rather than here.
    #[test]
    fn the_atlas_target_reuses_the_intermediate_variant() {
        assert_eq!(
            crate::gpu::atlas::ATLAS_FORMAT,
            INTERMEDIATE_FORMAT,
            "an atlas layer is drawn through the intermediate variant, so the two formats are one \
             decision"
        );

        assert_eq!(ATLAS_STRIP_PIPELINE, EnginePipeline::StripIntermediate);
        assert_eq!(
            ATLAS_STRIP_PIPELINE.format(TARGET),
            crate::gpu::atlas::ATLAS_FORMAT,
            "the atlas pipeline writes the atlas format whatever the frame's own target is"
        );
        assert_eq!(
            ATLAS_STRIP_PIPELINE.blend(),
            Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
            "a replayed glyph composites source-over onto whatever the slot already holds"
        );
        assert_eq!(
            ATLAS_STRIP_PIPELINE.depth(),
            None,
            "an atlas layer carries no depth attachment for a pipeline to test against"
        );
        assert!(ATLAS_STRIP_PIPELINE.is_strip());

        // Warmed up with the rest, so an atlas pass never compiles inline.
        let module = ATLAS_STRIP_PIPELINE.module();
        assert_eq!(module, EngineShaderModule::Strip);
        assert!(EnginePipeline::ALL.contains(&ATLAS_STRIP_PIPELINE));
        assert!(
            frust_gpu::lint_pipeline_layout(&ATLAS_STRIP_PIPELINE.layout_desc()).is_empty(),
            "the atlas pass must stay inside the downlevel design rules"
        );
    }

    #[test]
    fn the_clear_and_copy_pipelines_write_the_intermediate_format_unblended() {
        for pipeline in [EnginePipeline::Clear, EnginePipeline::Copy] {
            assert_eq!(pipeline.format(TARGET), INTERMEDIATE_FORMAT);
            assert_eq!(pipeline.blend(), None);
            assert_eq!(pipeline.depth(), None);
            assert!(!pipeline.is_strip());
        }
        assert_eq!(EnginePipeline::Clear.bind_group_count(), 0);
        assert_eq!(EnginePipeline::Copy.bind_group_count(), COPY_BIND_GROUPS);
    }

    /// The filter pass is a pipeline of its own, not a strip variant under
    /// another name: its own program, its own instance layout, and the only
    /// one whose bind groups carry a sampler.
    ///
    /// Its render state is stated here rather than left to the module doc
    /// because each field is load-bearing: an intermediate colour format (a
    /// filter round only ever writes a pooled page), no blend (the pass
    /// replaces the region and deliberately writes transparent black over the
    /// padding border), and no depth (a page carries no depth attachment).
    #[test]
    fn the_filter_pipeline_replaces_an_intermediate_region_unblended_and_undepthed() {
        let filter = EnginePipeline::Filter;

        assert_eq!(filter.module(), EngineShaderModule::Filter);
        assert_eq!(
            filter.format(TARGET),
            INTERMEDIATE_FORMAT,
            "a filter pass writes a pooled page, never the frame's own target"
        );
        assert_eq!(
            filter.blend(),
            None,
            "a blend would turn the padding border's deliberate erase into a no-op"
        );
        assert_eq!(filter.depth(), None);
        assert!(!filter.is_strip());
        assert_eq!(filter.bind_group_count(), FILTER_BIND_GROUPS);
        assert_eq!(filter.vertex_layouts(), vec![filter_vertex_layout()]);
        assert!(
            filter.layout_desc().uniform_buffer_sizes.is_empty(),
            "a filter pass takes its viewport from its own instance, not a uniform"
        );

        // Warmed up with the rest, so a frame that blurs never compiles a
        // pipeline inline.
        assert!(EnginePipeline::ALL.contains(&filter));
        assert!(
            frust_gpu::lint_pipeline_layout(&filter.layout_desc()).is_empty(),
            "the filter pass must stay inside the downlevel design rules"
        );
    }

    #[test]
    fn the_instance_layouts_match_their_shader_declarations() {
        let strip = GpuStrip::vertex_layout();
        assert_eq!(strip.step_mode, wgpu::VertexStepMode::Instance);
        assert_eq!(strip.attributes.len(), 6);

        let clear = clear_vertex_layout();
        assert_eq!(clear.step_mode, wgpu::VertexStepMode::Instance);
        assert_eq!(clear.attributes.len(), 3);
        assert_eq!(clear.array_stride, 24);

        let copy = copy_vertex_layout();
        assert_eq!(copy.step_mode, wgpu::VertexStepMode::Instance);
        assert_eq!(copy.attributes.len(), 4);
        assert_eq!(copy.array_stride, 16);

        let filter = filter_vertex_layout();
        assert_eq!(filter.step_mode, wgpu::VertexStepMode::Instance);
        assert_eq!(filter.attributes.len(), 8);
        assert_eq!(
            filter.array_stride as usize,
            size_of::<crate::filters::blur::FilterInstanceData>()
        );
    }

    /// Blocks on `future` by polling it to completion.
    ///
    /// wgpu's native adapter and device requests resolve without an executor
    /// driving them, so a bare poll loop is enough here; this crate has no
    /// async runtime of its own and the only caller is the ignored
    /// hardware test below.
    fn block_on<F: std::future::Future>(future: F) -> F::Output {
        use std::task::{Context, Poll, Waker};

        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        let mut future = std::pin::pin!(future);
        loop {
            match future.as_mut().poll(&mut cx) {
                Poll::Ready(value) => return value,
                Poll::Pending => std::thread::yield_now(),
            }
        }
    }

    /// Pops a validation error scope, pumping the device until the pop
    /// resolves — the pop is a future a plain poll loop would park on.
    fn drain_error_scope(
        device: &wgpu::Device,
        scope: wgpu::ErrorScopeGuard,
    ) -> Option<wgpu::Error> {
        use std::task::{Context, Poll, Waker};

        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        let mut future = std::pin::pin!(scope.pop());
        loop {
            match future.as_mut().poll(&mut cx) {
                Poll::Ready(error) => return error,
                Poll::Pending => {
                    let _ = device.poll(wgpu::PollType::wait_indefinitely());
                }
            }
        }
    }

    /// Every engine pipeline, built on real hardware.
    ///
    /// The tests above are all device-free, and `shader_src`'s naga tests
    /// prove the modules themselves validate. This is the only case that
    /// proves the *pipelines* are accepted — entry points, derived
    /// bind-group layouts, instance layouts, color targets and depth state
    /// included — and that warming the list up compiles each of them exactly
    /// once.
    #[test]
    #[ignore = "requires a GPU (Vulkan/Metal); run with `cargo test -p frust-engine -- --ignored`"]
    fn every_pipeline_builds_on_a_real_device() {
        let (device, _queue) = block_on(async {
            let instance = wgpu::Instance::new(
                wgpu::InstanceDescriptor::new_without_display_handle_from_env(),
            );
            // The environment-aware initializer, so `WGPU_ADAPTER_NAME` picks
            // the GPU on a multi-adapter host instead of the run silently
            // landing on whichever one enumerates first.
            let adapter = wgpu::util::initialize_adapter_from_env_or_default(&instance, None)
                .await
                .expect("no compatible GPU adapter");
            println!(
                "frust-engine pipeline test adapter: {:?}",
                adapter.get_info()
            );
            adapter
                .request_device(&wgpu::DeviceDescriptor {
                    label: Some("frust-engine pipeline test device"),
                    required_features: wgpu::Features::empty(),
                    required_limits: wgpu::Limits::default(),
                    ..Default::default()
                })
                .await
                .expect("failed to create the device")
        });

        let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);

        let mut library = ShaderLibrary::new();
        let shaders = EngineShaders::register(&mut library, &device);
        assert_eq!(
            library.len(),
            shader_src::MODULES.len(),
            "one module per engine shader source"
        );
        assert_eq!(
            EnginePipeline::ALL
                .iter()
                .filter(|pipeline| pipeline.is_strip())
                .count(),
            6,
            "six render states over the one strip program"
        );

        let mut cache = PipelineCache::new(std::sync::Arc::new(library), None);
        let descs = warm_up_descs(&shaders, TARGET);
        assert_eq!(descs.len(), EnginePipeline::ALL.len());
        // The atlas pass draws through a description the warm-up list already
        // carries, so it never compiles a pipeline inline on a frame that
        // misses a glyph.
        assert!(
            descs.contains(&atlas_strip_desc(&shaders)),
            "the atlas description must be one the warm-up list already covers"
        );
        for desc in &descs {
            let _pipeline = cache.get_or_create(&device, desc);
        }
        // A second pass must be pure cache hits.
        for desc in &descs {
            let _pipeline = cache.get_or_create(&device, desc);
        }

        let error = drain_error_scope(&device, scope);
        assert!(error.is_none(), "pipeline creation raised {error:?}");
        assert_eq!(
            cache.compiled_variants(),
            EnginePipeline::ALL.len() as u64,
            "each engine pipeline must compile exactly once"
        );
    }
}