viewport-lib 0.19.0

3D viewport rendering library
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
//! Factory functions for the mesh-family pipelines that share a single
//! shader source. The same factories run at startup (from `init.rs` and
//! `postprocess.rs`) and from the deformer registry's pipeline rebuild
//! path, so a registered deformer can swap in a freshly composed
//! `ShaderModule` without duplicating pipeline descriptors.

use crate::resources::types::Vertex;

/// The four LDR `mesh.wgsl` pipelines that draw into the swapchain.
pub(crate) struct LdrMeshPipelines {
    pub solid: wgpu::RenderPipeline,
    pub solid_two_sided: wgpu::RenderPipeline,
    pub transparent: wgpu::RenderPipeline,
    pub wireframe: wgpu::RenderPipeline,
}

pub(crate) fn build_ldr_mesh_pipelines(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
    target_format: wgpu::TextureFormat,
    sample_count: u32,
    cache: Option<&wgpu::PipelineCache>,
) -> LdrMeshPipelines {
    let depth_stencil = wgpu::DepthStencilState {
        format: wgpu::TextureFormat::Depth24PlusStencil8,
        depth_write_enabled: true,
        depth_compare: wgpu::CompareFunction::Less,
        stencil: wgpu::StencilState::default(),
        bias: wgpu::DepthBiasState::default(),
    };

    let make = |label: &str,
                cull: Option<wgpu::Face>,
                blend: Option<wgpu::BlendState>,
                topo: wgpu::PrimitiveTopology,
                depth_write: bool| {
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("vs_main"),
                buffers: &[Vertex::buffer_layout()],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: target_format,
                    blend,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: topo,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: cull,
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                depth_write_enabled: depth_write,
                ..depth_stencil.clone()
            }),
            multisample: wgpu::MultisampleState {
                count: sample_count,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview: None,
            cache,
        })
    };

    LdrMeshPipelines {
        solid: make(
            "solid_pipeline",
            Some(wgpu::Face::Back),
            None,
            wgpu::PrimitiveTopology::TriangleList,
            true,
        ),
        solid_two_sided: make(
            "solid_two_sided_pipeline",
            None,
            None,
            wgpu::PrimitiveTopology::TriangleList,
            true,
        ),
        transparent: make(
            "transparent_pipeline",
            None,
            Some(wgpu::BlendState {
                color: wgpu::BlendComponent {
                    src_factor: wgpu::BlendFactor::SrcAlpha,
                    dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                    operation: wgpu::BlendOperation::Add,
                },
                alpha: wgpu::BlendComponent {
                    src_factor: wgpu::BlendFactor::One,
                    dst_factor: wgpu::BlendFactor::Zero,
                    operation: wgpu::BlendOperation::Add,
                },
            }),
            wgpu::PrimitiveTopology::TriangleList,
            false,
        ),
        wireframe: make(
            "wireframe_pipeline",
            None,
            None,
            wgpu::PrimitiveTopology::LineList,
            true,
        ),
    }
}

/// The four HDR `mesh.wgsl` pipelines that draw into the Rgba16Float
/// intermediate.
pub(crate) struct HdrMeshPipelines {
    pub solid: wgpu::RenderPipeline,
    pub solid_two_sided: wgpu::RenderPipeline,
    pub transparent: wgpu::RenderPipeline,
    pub wireframe: wgpu::RenderPipeline,
}

pub(crate) fn build_hdr_mesh_pipelines(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
) -> HdrMeshPipelines {
    let make = |label: &str,
                cull: Option<wgpu::Face>,
                blend: Option<wgpu::BlendState>,
                topo: wgpu::PrimitiveTopology,
                depth_write: bool| {
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("vs_main"),
                buffers: &[Vertex::buffer_layout()],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba16Float,
                    blend,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: topo,
                cull_mode: cull,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: depth_write,
                depth_compare: wgpu::CompareFunction::Less,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: 1,
                ..Default::default()
            },
            multiview: None,
            cache: None,
        })
    };

    HdrMeshPipelines {
        solid: make(
            "hdr_solid_pipeline",
            Some(wgpu::Face::Back),
            None,
            wgpu::PrimitiveTopology::TriangleList,
            true,
        ),
        solid_two_sided: make(
            "hdr_solid_two_sided_pipeline",
            None,
            None,
            wgpu::PrimitiveTopology::TriangleList,
            true,
        ),
        transparent: make(
            "hdr_transparent_pipeline",
            None,
            Some(wgpu::BlendState::ALPHA_BLENDING),
            wgpu::PrimitiveTopology::TriangleList,
            false,
        ),
        wireframe: make(
            "hdr_wireframe_pipeline",
            None,
            None,
            wgpu::PrimitiveTopology::LineList,
            true,
        ),
    }
}

/// `mesh_oit.wgsl`: weighted-blended OIT pipeline. Draws into the
/// `Rgba16Float` accumulation target and the `R8Unorm` reveal target.
pub(crate) fn build_oit_pipeline(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
) -> wgpu::RenderPipeline {
    let accum_blend = wgpu::BlendState {
        color: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::One,
            dst_factor: wgpu::BlendFactor::One,
            operation: wgpu::BlendOperation::Add,
        },
        alpha: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::One,
            dst_factor: wgpu::BlendFactor::One,
            operation: wgpu::BlendOperation::Add,
        },
    };
    let reveal_blend = wgpu::BlendState {
        color: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::Zero,
            dst_factor: wgpu::BlendFactor::OneMinusSrc,
            operation: wgpu::BlendOperation::Add,
        },
        alpha: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::Zero,
            dst_factor: wgpu::BlendFactor::OneMinusSrc,
            operation: wgpu::BlendOperation::Add,
        },
    };
    let depth_stencil = wgpu::DepthStencilState {
        format: wgpu::TextureFormat::Depth24PlusStencil8,
        depth_write_enabled: false,
        depth_compare: wgpu::CompareFunction::LessEqual,
        stencil: wgpu::StencilState::default(),
        bias: wgpu::DepthBiasState::default(),
    };
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("oit_pipeline"),
        layout: Some(layout),
        vertex: wgpu::VertexState {
            module: shader,
            entry_point: Some("vs_main"),
            buffers: &[Vertex::buffer_layout()],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        },
        fragment: Some(wgpu::FragmentState {
            module: shader,
            entry_point: Some("fs_oit_main"),
            targets: &[
                Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba16Float,
                    blend: Some(accum_blend),
                    write_mask: wgpu::ColorWrites::ALL,
                }),
                Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::R8Unorm,
                    blend: Some(reveal_blend),
                    write_mask: wgpu::ColorWrites::RED,
                }),
            ],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            cull_mode: Some(wgpu::Face::Back),
            ..Default::default()
        },
        depth_stencil: Some(depth_stencil),
        multisample: wgpu::MultisampleState {
            count: 1,
            ..Default::default()
        },
        multiview: None,
        cache: None,
    })
}

/// Depth bias values used by every CSM shadow caster pipeline (the per-item
/// pipeline here and the two instanced pipelines in `instancing.rs`). Pulled
/// into one place so the three pipelines stay aligned: a difference in bias
/// between them shows up as a visible step where the active draw path changes.
///
/// `constant` is a fixed depth offset in the cascade's NDC, tiny in
/// Depth32Float (about 5e-7 NDC per unit), enough to close the coplanar
/// leak class without detaching the shadow at contact points.
///
/// `slope_scale` is held at zero on purpose. Receiver-side normal bias in
/// `sample_shadow_csm` already scales `texel_world * 1.5` at grazing
/// angles, which is where slope-scaled caster bias would otherwise earn
/// its keep. Stacking a slope-scaled caster bias on top of that visibly
/// detaches shadows from grazing-angle casters (tall walls lit obliquely
/// were the test case).
pub(crate) const CSM_SHADOW_BIAS: wgpu::DepthBiasState = wgpu::DepthBiasState {
    constant: 2,
    slope_scale: 0.0,
    clamp: 0.0,
};

/// Depth bias for the cull-none variant used by two-sided materials
/// (`BackfacePolicy::Identical` and friends). On the cull-none path the
/// receiver and caster are the same surface (e.g. a plane rasterised into
/// the shadow map at its own depth, then sampled by its own fragment), so
/// the caster-side bias has to outpace the receiver-side normal bias in
/// `sample_shadow_csm` or the receiver self-shadows uniformly. With the
/// default cull-front caster bias this surface reads as a broad dark patch.
///
/// `constant: 1000` in Depth32Float is ~1e-4 NDC, comfortably above the
/// perpendicular-receiver bias floor. `slope_scale: 1.0` tracks the
/// per-shadow-texel depth variation across tilted two-sided surfaces so the
/// receiver-side bias only needs to clear the per-pipeline constant, keeping
/// contact shadows tight instead of detaching them.
///
/// The cost is a small Peter-Panning offset (~1cm at typical cascade scale)
/// at the foot of two-sided contact shadows. That is the trade for getting a
/// two-sided surface to cast on both sides without shadowing itself.
pub(crate) const CSM_SHADOW_BIAS_TWO_SIDED: wgpu::DepthBiasState = wgpu::DepthBiasState {
    constant: 1000,
    slope_scale: 1.0,
    clamp: 0.0,
};

/// `shadow.wgsl`: depth-only shadow pass pipeline.
///
/// `cull_mode` selects which faces are rasterised into the shadow atlas:
/// - `Some(Face::Front)` for closed solids (`BackfacePolicy::Cull`). Back
///   faces become the casters, so a solid's own front face is never compared
///   against itself in the shadow map.
/// - `None` for two-sided surfaces (`BackfacePolicy::Identical` and friends,
///   typically single-quad planes, cloth, foliage). Both sides rasterise so
///   the surface can still cast a shadow regardless of which side faces the
///   light. The receiver-side normal bias is what keeps the self-shadow
///   class quiet on this path.
pub(crate) fn build_shadow_pipeline(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
    cull_mode: Option<wgpu::Face>,
    cache: Option<&wgpu::PipelineCache>,
) -> wgpu::RenderPipeline {
    let label = match cull_mode {
        Some(wgpu::Face::Front) => "shadow_pipeline",
        Some(wgpu::Face::Back) => "shadow_pipeline_cull_back",
        None => "shadow_pipeline_two_sided",
    };
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some(label),
        layout: Some(layout),
        vertex: wgpu::VertexState {
            module: shader,
            entry_point: Some("vs_main"),
            buffers: &[Vertex::buffer_layout()],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        },
        fragment: None,
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            cull_mode,
            unclipped_depth: false,
            polygon_mode: wgpu::PolygonMode::Fill,
            conservative: false,
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: wgpu::TextureFormat::Depth32Float,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: if cull_mode.is_none() {
                CSM_SHADOW_BIAS_TWO_SIDED
            } else {
                CSM_SHADOW_BIAS
            },
        }),
        multisample: wgpu::MultisampleState {
            count: 1,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache,
    })
}

/// `shadow_point.wgsl`: depth + fragment pipeline for point-light cubemap
/// shadow faces. Writes linear distance-to-light to `frag_depth`.
///
/// Uses back-face culling (front faces visible to the light are rendered) so
/// the cubemap stores the near-side distance of each occluder. With linear
/// distance and front-face culling, the stored depth is the object's far
/// side, which bakes in an implicit "bias = object thickness" and causes
/// peter-panning on objects sitting flush against receivers. A small slope-
/// scale bias offsets shadow acne on the lit side without re-introducing the
/// gap.
pub(crate) fn build_shadow_point_pipeline(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
    cache: Option<&wgpu::PipelineCache>,
) -> wgpu::RenderPipeline {
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("shadow_point_pipeline"),
        layout: Some(layout),
        vertex: wgpu::VertexState {
            module: shader,
            entry_point: Some("vs_main"),
            buffers: &[Vertex::buffer_layout()],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        },
        fragment: Some(wgpu::FragmentState {
            module: shader,
            entry_point: Some("fs_main"),
            targets: &[],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            // Y-flipped projection reverses triangle winding in screen space:
            // a triangle that's CCW in world space rasterises as CW after the
            // flip. Treating CW as the front face keeps back-face culling
            // (cull_mode: Back) working in the original sense: the surfaces
            // facing the light are kept, the surfaces facing away are culled.
            front_face: wgpu::FrontFace::Cw,
            cull_mode: Some(wgpu::Face::Back),
            unclipped_depth: false,
            polygon_mode: wgpu::PolygonMode::Fill,
            conservative: false,
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: wgpu::TextureFormat::Depth32Float,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState {
            count: 1,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache,
    })
}

/// `outline_mask.wgsl`: two pipelines that rasterise the selection
/// silhouette into the R8 mask texture.
pub(crate) struct OutlineMaskPipelines {
    pub mask: wgpu::RenderPipeline,
    pub mask_two_sided: wgpu::RenderPipeline,
}

pub(crate) fn build_outline_mask_pipelines(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
    mask_format: wgpu::TextureFormat,
    cache: Option<&wgpu::PipelineCache>,
) -> OutlineMaskPipelines {
    let make = |label: &str, cull: Option<wgpu::Face>| {
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("vs_main"),
                buffers: &[Vertex::buffer_layout()],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: mask_format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                cull_mode: cull,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: true,
                depth_compare: wgpu::CompareFunction::Less,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview: None,
            cache,
        })
    };
    OutlineMaskPipelines {
        mask: make("outline_mask_pipeline", Some(wgpu::Face::Back)),
        mask_two_sided: make("outline_mask_two_sided_pipeline", None),
    }
}

/// LDR `mesh_instanced.wgsl` pipelines: solid + transparent, both
/// drawing through `vs_main` with the instance storage buffer at
/// group 1.
pub(crate) struct LdrInstancedMeshPipelines {
    pub solid: wgpu::RenderPipeline,
    /// Same as `solid` but with `cull_mode: None` for two-sided (`Identical`
    /// backface policy) meshes.
    pub solid_two_sided: wgpu::RenderPipeline,
    pub transparent: wgpu::RenderPipeline,
}

pub(crate) fn build_ldr_instanced_mesh_pipelines(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
    target_format: wgpu::TextureFormat,
    sample_count: u32,
) -> LdrInstancedMeshPipelines {
    let make = |label: &str,
                cull: Option<wgpu::Face>,
                blend: Option<wgpu::BlendState>,
                depth_write: bool| {
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("vs_main"),
                buffers: &[Vertex::buffer_layout()],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: target_format,
                    blend,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                cull_mode: cull,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: depth_write,
                depth_compare: wgpu::CompareFunction::Less,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: sample_count,
                ..Default::default()
            },
            multiview: None,
            cache: None,
        })
    };
    LdrInstancedMeshPipelines {
        solid: make(
            "solid_instanced_pipeline",
            Some(wgpu::Face::Back),
            None,
            true,
        ),
        solid_two_sided: make("solid_two_sided_instanced_pipeline", None, None, true),
        transparent: make(
            "transparent_instanced_pipeline",
            None,
            Some(wgpu::BlendState::ALPHA_BLENDING),
            false,
        ),
    }
}

/// HDR `mesh_instanced.wgsl` pipelines, all `vs_main`. Includes the
/// additive and premultiplied variants the particle system draws into.
pub(crate) struct HdrInstancedMeshPipelines {
    pub solid: wgpu::RenderPipeline,
    /// Same as `solid` but with `cull_mode: None` for two-sided (`Identical`
    /// backface policy) meshes.
    pub solid_two_sided: wgpu::RenderPipeline,
    pub transparent: wgpu::RenderPipeline,
    pub additive: wgpu::RenderPipeline,
    pub premultiplied: wgpu::RenderPipeline,
}

pub(crate) fn build_hdr_instanced_mesh_pipelines(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
) -> HdrInstancedMeshPipelines {
    let additive_blend = wgpu::BlendState {
        color: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::One,
            dst_factor: wgpu::BlendFactor::One,
            operation: wgpu::BlendOperation::Add,
        },
        alpha: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::One,
            dst_factor: wgpu::BlendFactor::One,
            operation: wgpu::BlendOperation::Add,
        },
    };
    let premultiplied_blend = wgpu::BlendState {
        color: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::One,
            dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
            operation: wgpu::BlendOperation::Add,
        },
        alpha: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::One,
            dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
            operation: wgpu::BlendOperation::Add,
        },
    };
    let make = |label: &str,
                cull: Option<wgpu::Face>,
                blend: Option<wgpu::BlendState>,
                depth_write: bool| {
        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("vs_main"),
                buffers: &[Vertex::buffer_layout()],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba16Float,
                    blend,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                cull_mode: cull,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: depth_write,
                depth_compare: wgpu::CompareFunction::Less,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: 1,
                ..Default::default()
            },
            multiview: None,
            cache: None,
        })
    };
    HdrInstancedMeshPipelines {
        solid: make(
            "hdr_solid_instanced_pipeline",
            Some(wgpu::Face::Back),
            None,
            true,
        ),
        solid_two_sided: make("hdr_solid_two_sided_instanced_pipeline", None, None, true),
        transparent: make(
            "hdr_transparent_instanced_pipeline",
            None,
            Some(wgpu::BlendState::ALPHA_BLENDING),
            false,
        ),
        additive: make(
            "hdr_instanced_additive_pipeline",
            None,
            Some(additive_blend),
            false,
        ),
        premultiplied: make(
            "hdr_instanced_premultiplied_pipeline",
            None,
            Some(premultiplied_blend),
            false,
        ),
    }
}

/// GPU-cull HDR solid pipeline: same as the HDR solid instanced pipeline
/// but using `vs_main_cull` so the compute pass can write
/// visibility indices.
pub(crate) fn build_hdr_instanced_cull_pipeline(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
) -> wgpu::RenderPipeline {
    build_hdr_instanced_cull_pipeline_with(
        device,
        layout,
        shader,
        "hdr_solid_instanced_cull_pipeline",
        Some(wgpu::Face::Back),
    )
}

/// Two-sided (`cull_mode: None`) variant of the GPU-cull HDR solid pipeline,
/// used for instanced batches whose material has the `Identical` backface policy.
pub(crate) fn build_hdr_instanced_cull_two_sided_pipeline(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
) -> wgpu::RenderPipeline {
    build_hdr_instanced_cull_pipeline_with(
        device,
        layout,
        shader,
        "hdr_solid_instanced_cull_two_sided_pipeline",
        None,
    )
}

fn build_hdr_instanced_cull_pipeline_with(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
    label: &str,
    cull_mode: Option<wgpu::Face>,
) -> wgpu::RenderPipeline {
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some(label),
        layout: Some(layout),
        vertex: wgpu::VertexState {
            module: shader,
            entry_point: Some("vs_main_cull"),
            buffers: &[Vertex::buffer_layout()],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        },
        fragment: Some(wgpu::FragmentState {
            module: shader,
            entry_point: Some("fs_main"),
            targets: &[Some(wgpu::ColorTargetState {
                format: wgpu::TextureFormat::Rgba16Float,
                blend: None,
                write_mask: wgpu::ColorWrites::ALL,
            })],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            cull_mode,
            ..Default::default()
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: wgpu::TextureFormat::Depth24PlusStencil8,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState {
            count: 1,
            ..Default::default()
        },
        multiview: None,
        cache: None,
    })
}

/// OIT instanced pipeline shared between the non-cull (`vs_main`) and
/// the cull (`vs_main_cull`) variants. Two color targets, depth-test
/// only.
pub(crate) fn build_oit_instanced_pipeline(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    shader: &wgpu::ShaderModule,
    label: &str,
    vs_entry: &str,
) -> wgpu::RenderPipeline {
    let accum_blend = wgpu::BlendState {
        color: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::One,
            dst_factor: wgpu::BlendFactor::One,
            operation: wgpu::BlendOperation::Add,
        },
        alpha: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::One,
            dst_factor: wgpu::BlendFactor::One,
            operation: wgpu::BlendOperation::Add,
        },
    };
    let reveal_blend = wgpu::BlendState {
        color: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::Zero,
            dst_factor: wgpu::BlendFactor::OneMinusSrc,
            operation: wgpu::BlendOperation::Add,
        },
        alpha: wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::Zero,
            dst_factor: wgpu::BlendFactor::OneMinusSrc,
            operation: wgpu::BlendOperation::Add,
        },
    };
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some(label),
        layout: Some(layout),
        vertex: wgpu::VertexState {
            module: shader,
            entry_point: Some(vs_entry),
            buffers: &[Vertex::buffer_layout()],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        },
        fragment: Some(wgpu::FragmentState {
            module: shader,
            entry_point: Some("fs_oit_main"),
            targets: &[
                Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba16Float,
                    blend: Some(accum_blend),
                    write_mask: wgpu::ColorWrites::ALL,
                }),
                Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::R8Unorm,
                    blend: Some(reveal_blend),
                    write_mask: wgpu::ColorWrites::RED,
                }),
            ],
            compilation_options: wgpu::PipelineCompilationOptions::default(),
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            cull_mode: Some(wgpu::Face::Back),
            ..Default::default()
        },
        depth_stencil: Some(wgpu::DepthStencilState {
            format: wgpu::TextureFormat::Depth24PlusStencil8,
            depth_write_enabled: false,
            depth_compare: wgpu::CompareFunction::LessEqual,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        }),
        multisample: wgpu::MultisampleState {
            count: 1,
            ..Default::default()
        },
        multiview: None,
        cache: None,
    })
}

/// Build a pipeline layout for instanced mesh-family pipelines.
/// Groups: 0=camera, 1=instance/cull, and optionally 2=deform.
/// Pass `None` for `deform_bgl` on devices with max_bind_groups < 3.
pub(crate) fn instanced_pipeline_layout(
    device: &wgpu::Device,
    label: &str,
    camera_bgl: &wgpu::BindGroupLayout,
    instance_bgl: &wgpu::BindGroupLayout,
    deform_bgl: Option<&wgpu::BindGroupLayout>,
) -> wgpu::PipelineLayout {
    let layouts: Vec<&wgpu::BindGroupLayout> = if let Some(d) = deform_bgl {
        vec![camera_bgl, instance_bgl, d]
    } else {
        vec![camera_bgl, instance_bgl]
    };
    device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some(label),
        bind_group_layouts: &layouts,
        push_constant_ranges: &[],
    })
}

/// Build the shared mesh pipeline layout used by both LDR and HDR mesh
/// pipelines. Groups: 0=camera, 1=object+texture, and optionally 2=deform.
/// Pass `None` for `deform_bgl` on devices with max_bind_groups < 3.
pub(crate) fn mesh_pipeline_layout(
    device: &wgpu::Device,
    label: &str,
    camera_bgl: &wgpu::BindGroupLayout,
    object_bgl: &wgpu::BindGroupLayout,
    deform_bgl: Option<&wgpu::BindGroupLayout>,
) -> wgpu::PipelineLayout {
    let layouts: Vec<&wgpu::BindGroupLayout> = if let Some(d) = deform_bgl {
        vec![camera_bgl, object_bgl, d]
    } else {
        vec![camera_bgl, object_bgl]
    };
    device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some(label),
        bind_group_layouts: &layouts,
        push_constant_ranges: &[],
    })
}