wgpu_render_manager 0.2.12

Cached Render/Compute Manager for wgpu (pipelines + bind groups + procedural textures automated)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
// fullscreen.rs
#![allow(dead_code)]
use std::collections::HashMap;
use wgpu::*;
use wgpu::util::DeviceExt;
use crate::compute_system::figure_out_aspect;

const FULLSCREEN_COLOR_SHADER: &str = r#"
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}

@group(0) @binding(0) var s_tex: sampler;
@group(0) @binding(1) var t_tex: texture_2d<f32>;

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    return textureSample(t_tex, s_tex, in.uv);
}
"#;

const FULLSCREEN_DEPTH_SHADER: &str = r#"
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

struct DepthParams {
    near: f32,
    far: f32,
    power: f32,
    reversed_z: u32,
};
@group(0) @binding(0) var s_depth: sampler;
@group(0) @binding(1) var t_depth: texture_depth_2d;
@group(1) @binding(0) var<uniform> params: DepthParams;

fn linearize_depth(d: f32, near: f32, far: f32, reversed: bool) -> f32 {
    if reversed {
        return near / d;
    } else {
        return (near * far) / (far - d * (far - near));
    }
}

@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let d = textureSample(t_depth, s_depth, in.uv);
    let z = linearize_depth(d, params.near, params.far, params.reversed_z != 0u);
    let v01 = 1.0 - clamp(z / params.far, 0.0, 1.0);
    let v = pow(v01, params.power);
    return vec4<f32>(v, v, v, 1.0);
}
"#;
const FULLSCREEN_COLOR_MSAA_SHADER: &str = r#"
struct DepthParams {
    near: f32,
    far: f32,
    power: f32,
    reversed_z: u32,
};
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};
@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}
@group(0) @binding(0) var t_tex: texture_multisampled_2d<f32>;

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let dims = textureDimensions(t_tex);
    let coord = vec2<i32>(in.uv * vec2<f32>(dims));
    var c = vec4<f32>(0.0);
    for (var i = 0u; i < textureNumSamples(t_tex); i++) {
        c += textureLoad(t_tex, coord, i);
    }
    return c / f32(textureNumSamples(t_tex));
}
"#;

const FULLSCREEN_DEPTH_MSAA_SHADER: &str = r#"
struct DepthParams {
    near: f32,
    far: f32,
    power: f32,
    reversed_z: u32,
};
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};
@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}
fn linearize_depth(d: f32, near: f32, far: f32, reversed: bool) -> f32 {
    if reversed {
        return near / d;
    } else {
        return (near * far) / (far - d * (far - near));
    }
}
@group(0) @binding(0) var t_depth: texture_depth_multisampled_2d;
@group(1) @binding(0) var<uniform> params: DepthParams;

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let dims = textureDimensions(t_depth);
    let coord = vec2<i32>(in.uv * vec2<f32>(dims));

    var d = 0.0;
    for (var i = 0u; i < textureNumSamples(t_depth); i++) {
        d += textureLoad(t_depth, coord, i);
    }
    d /= f32(textureNumSamples(t_depth));

    let z = linearize_depth(d, params.near, params.far, params.reversed_z != 0u);
    let v01 = 1.0 - clamp(z / params.far, 0.0, 1.0);
    let v = pow(v01, params.power);
    return vec4<f32>(v, v, v, 1.0);
}
"#;
const FULLSCREEN_RED_TO_GRAYSCALE_SHADER: &str = r#"
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}

@group(0) @binding(0) var s_tex: sampler;
@group(0) @binding(1) var t_tex: texture_2d<f32>;

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let c = textureSample(t_tex, s_tex, in.uv);
    let v = c.r;
    return vec4<f32>(v, v, v, 1.0);
}
"#;

const FULLSCREEN_RED_TO_GRAYSCALE_MSAA_SHADER: &str = r#"
struct DepthParams {
    near: f32,
    far: f32,
    power: f32,
    reversed_z: u32,
};
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};
@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}
@group(0) @binding(0) var t_tex: texture_multisampled_2d<f32>;

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let dims = textureDimensions(t_tex);
    let coord = vec2<i32>(in.uv * vec2<f32>(dims));
    var c = vec4<f32>(0.0);
    for (var i = 0u; i < textureNumSamples(t_tex); i++) {
        c += textureLoad(t_tex, coord, i);
    }

    let v = c.r;
    return vec4<f32>(v, v, v, 1.0);
}
"#;
const FULLSCREEN_COLOR_UNFILTERABLE_SHADER: &str = r#"
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}

@group(0) @binding(0) var t_tex: texture_2d<f32>;

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let dims = textureDimensions(t_tex);
    let coord = vec2<i32>(in.uv * vec2<f32>(dims));
    return textureLoad(t_tex, coord, 0);
}
"#;

const FULLSCREEN_RED_TO_GRAYSCALE_UNFILTERABLE_SHADER: &str = r#"
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}

@group(0) @binding(0) var t_tex: texture_2d<f32>;

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let dims = textureDimensions(t_tex);
    let coord = vec2<i32>(in.uv * vec2<f32>(dims));
    let c = textureLoad(t_tex, coord, 0);
    let v = c.r;
    return vec4<f32>(v, v, v, 1.0);
}
"#;
const FULLSCREEN_LINEAR_DEPTH_SHADER: &str = r#"
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

struct DepthParams {
    near: f32,
    far: f32,
    power: f32,
    reversed_z: u32,
};

@group(0) @binding(0) var s_tex: sampler;
@group(0) @binding(1) var t_tex: texture_2d<f32>;
@group(1) @binding(0) var<uniform> params: DepthParams;

@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let linear_z = textureSample(t_tex, s_tex, in.uv).r;
    let v01 = 1.0 - clamp(linear_z / params.far, 0.0, 1.0);
    let v = pow(v01, params.power);
    return vec4<f32>(v, v, v, 1.0);
}
"#;

const FULLSCREEN_LINEAR_DEPTH_UNFILTERABLE_SHADER: &str = r#"
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

struct DepthParams {
    near: f32,
    far: f32,
    power: f32,
    reversed_z: u32,
};

@group(0) @binding(0) var t_tex: texture_2d<f32>;
@group(1) @binding(0) var<uniform> params: DepthParams;

@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 4>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 1.0, -1.0),
        vec2<f32>(-1.0,  1.0),
        vec2<f32>( 1.0,  1.0),
    );
    var uvs = array<vec2<f32>, 4>(
        vec2<f32>(0.0, 1.0),
        vec2<f32>(1.0, 1.0),
        vec2<f32>(0.0, 0.0),
        vec2<f32>(1.0, 0.0),
    );
    var out: VertexOutput;
    out.position = vec4<f32>(positions[idx], 0.0, 1.0);
    out.uv = uvs[idx];
    return out;
}

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let dims = textureDimensions(t_tex);
    let coord = vec2<i32>(in.uv * vec2<f32>(dims));
    let linear_z = textureLoad(t_tex, coord, 0).r;
    let v01 = 1.0 - clamp(linear_z / params.far, 0.0, 1.0);
    let v = pow(v01, params.power);
    return vec4<f32>(v, v, v, 1.0);
}
"#;
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct DepthDebugParams {
    pub near: f32,
    pub far: f32,
    pub power: f32,        // e.g. 20.0
    pub reversed_z: u32,   // 0 or 1
    pub msaa_samples: u32, // 1,2,4,8...
}

/// Type of debug visualization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DebugVisualization {
    Color,
    RedToGrayscale,
    Depth,
    LinearDepth, // NEW: for already-linearized depth in float textures
}

#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct DepthParams {
    near: f32,
    far: f32,
    power: f32,
    reversed_z: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum PipelineKind {
    Color,
    RedToGrayscale,
    Depth,
    LinearDepth,
}

impl PipelineKind {
    fn from_debug_visualization(visualization: DebugVisualization) -> Self {
        match visualization {
            DebugVisualization::Color => Self::Color,
            DebugVisualization::RedToGrayscale => Self::RedToGrayscale,
            DebugVisualization::Depth => Self::Depth,
            DebugVisualization::LinearDepth => Self::LinearDepth,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct PipelineKey {
    kind: PipelineKind,
    target_format: TextureFormat,
    source_is_msaa: bool,
    source_is_filterable: bool,
    target_sample_count: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct BindGroupKey {
    view_ptr: usize,
    kind: PipelineKind,
    is_filterable: bool,
}

/// Renders textures to fullscreen quads for debugging and visualization.
pub struct FullscreenRenderer {
    device: Device,
    queue: Queue,

    color_shader: ShaderModule,
    color_unfilterable_shader: ShaderModule,
    color_msaa_shader: ShaderModule,
    red_to_grayscale_shader: ShaderModule,
    red_to_grayscale_unfilterable_shader: ShaderModule,
    red_to_grayscale_msaa_shader: ShaderModule,
    depth_shader: ShaderModule,
    depth_msaa_shader: ShaderModule,
    linear_depth_shader: ShaderModule,
    linear_depth_unfilterable_shader: ShaderModule,

    color_bgl: BindGroupLayout,
    color_unfilterable_bgl: BindGroupLayout,
    color_msaa_bgl: BindGroupLayout,
    depth_bgl: BindGroupLayout,
    depth_msaa_bgl: BindGroupLayout,
    depth_params_bgl: BindGroupLayout,

    linear_sampler: Sampler,
    nearest_sampler: Sampler,

    pipelines: HashMap<PipelineKey, RenderPipeline>,
    bind_groups: HashMap<BindGroupKey, BindGroup>,

    depth_params_buffer: Option<Buffer>,
    depth_params_bind_group: Option<BindGroup>,
}

impl FullscreenRenderer {
    pub fn new(device: Device, queue: Queue) -> Self {
        let depth_params_bgl = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
            label: Some("depth params bgl"),
            entries: &[BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                ty: BindingType::Buffer {
                    ty: BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        });
        let color_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen color shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_COLOR_SHADER.into()),
        });
        let color_unfilterable_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen color unfilterable shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_COLOR_UNFILTERABLE_SHADER.into()),
        });
        let color_msaa_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen color MSAA shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_COLOR_MSAA_SHADER.into()),
        });
        let red_to_grayscale_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen grayscale shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_RED_TO_GRAYSCALE_SHADER.into()),
        });
        let red_to_grayscale_unfilterable_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen grayscale unfilterable shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_RED_TO_GRAYSCALE_UNFILTERABLE_SHADER.into()),
        });
        let red_to_grayscale_msaa_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen grayscale shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_RED_TO_GRAYSCALE_MSAA_SHADER.into()),
        });
        let depth_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen depth shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_DEPTH_SHADER.into()),
        });
        let depth_msaa_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen depth MSAA shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_DEPTH_MSAA_SHADER.into()),
        });
        let linear_depth_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen linear depth shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_LINEAR_DEPTH_SHADER.into()),
        });
        let linear_depth_unfilterable_shader = device.create_shader_module(ShaderModuleDescriptor {
            label: Some("fullscreen linear depth unfilterable shader"),
            source: ShaderSource::Wgsl(FULLSCREEN_LINEAR_DEPTH_UNFILTERABLE_SHADER.into()),
        });

        let color_bgl = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
            label: Some("fullscreen color bgl"),
            entries: &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Sampler(SamplerBindingType::Filtering),
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Texture {
                        sample_type: TextureSampleType::Float { filterable: true },
                        view_dimension: TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });

        let color_unfilterable_bgl = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
            label: Some("fullscreen color unfilterable bgl"),
            entries: &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Texture {
                        sample_type: TextureSampleType::Float { filterable: false },
                        view_dimension: TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });

        let color_msaa_bgl = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
            label: Some("fullscreen color msaa bgl"),
            entries: &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Texture {
                        sample_type: TextureSampleType::Float { filterable: false },
                        view_dimension: TextureViewDimension::D2,
                        multisampled: true,
                    },
                    count: None,
                },
            ],
        });

        let depth_bgl = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
            label: Some("fullscreen depth bgl"),
            entries: &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Sampler(SamplerBindingType::NonFiltering),
                    count: None,
                },
                BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Texture {
                        sample_type: TextureSampleType::Depth,
                        view_dimension: TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });
        let depth_msaa_bgl = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
            label: Some("fullscreen depth msaa bgl"),
            entries: &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: BindingType::Texture {
                        sample_type: TextureSampleType::Depth,
                        view_dimension: TextureViewDimension::D2,
                        multisampled: true,
                    },
                    count: None,
                },
            ],
        });

        let linear_sampler = device.create_sampler(&SamplerDescriptor {
            label: Some("Fullscreen Linear Sampler"),
            mag_filter: FilterMode::Linear,
            min_filter: FilterMode::Linear,
            ..Default::default()
        });

        let nearest_sampler = device.create_sampler(&SamplerDescriptor {
            label: Some("Fullscreen Nearest Sampler"),
            mag_filter: FilterMode::Nearest,
            min_filter: FilterMode::Nearest,
            ..Default::default()
        });

        Self {
            device,
            queue,
            color_shader,
            color_unfilterable_shader,
            color_msaa_shader,
            red_to_grayscale_shader,
            red_to_grayscale_unfilterable_shader,
            red_to_grayscale_msaa_shader,
            depth_shader,
            depth_msaa_shader,
            linear_depth_shader,
            linear_depth_unfilterable_shader,
            color_bgl,
            color_unfilterable_bgl,
            color_msaa_bgl,
            depth_bgl,
            depth_msaa_bgl,
            depth_params_bgl,
            linear_sampler,
            nearest_sampler,
            pipelines: HashMap::new(),
            bind_groups: HashMap::new(),
            depth_params_buffer: None,
            depth_params_bind_group: None,
        }
    }

    /// Renders a texture to the current render pass as a fullscreen quad.
    ///
    /// This function is intended for **debugging and visualization** of GPU
    /// textures such as color buffers, depth buffers, or intermediate render
    /// targets.
    ///
    /// ## What this does
    /// - Selects or creates a render pipeline based on [`DebugVisualization`]
    /// - Binds the provided texture as `@group(0)`
    /// - Optionally binds depth visualization parameters at `@group(1)`
    /// - Draws a fullscreen quad using a single draw call and internal shaders
    ///
    /// ## Target View
    /// `target_view` **must match** the color attachment of the render pass.
    /// It is used to infer the render target format and MSAA sample count
    /// for pipeline selection.
    ///
    /// ## Parameters
    /// - `texture`: Texture view to visualize
    /// - `visualization`: What the texture should be interpreted as (color, depth, etc.)
    /// - `target_format`: Format of the render target this pass is writing to
    /// - `pass`: Active render pass to record commands into
    ///
    /// ### Panics
    /// This function may panic if internal pipeline or bind group creation fails.
    ///
    /// ### Errors
    /// wgpu validation errors may occur if the texture, target view,
    /// or render pass configuration are incompatible.
    ///
    /// ## Example
    /// ```no_run
    /// // Inside a render pass
    /// fullscreen_renderer.render(
    ///     &color_view,
    ///     DebugVisualization::Color,
    ///     &target_view,
    ///     &mut render_pass,
    /// );
    /// ```
    pub fn render(
        &mut self,
        texture: &TextureView,
        visualization_type: DebugVisualization,
        target_view: &TextureView,
        pass: &mut RenderPass,
    ) {
        let binding_type = infer_texture_binding_type(texture, &self.device);
        let sample_type = match binding_type {
            BindingType::Texture { sample_type, .. } => sample_type,
            _ => unreachable!("infer_texture_binding_type always returns BindingType::Texture"),
        };

        // Auto-detect depth texture and override kind if needed
        // But don't override if user explicitly requested LinearDepth
        let kind = if matches!(sample_type, TextureSampleType::Depth) {
            PipelineKind::Depth
        } else {
            PipelineKind::from_debug_visualization(visualization_type)
        };

        let is_filterable = matches!(sample_type, TextureSampleType::Float { filterable: true });

        let pipeline_msaa_samples = target_view.texture().sample_count();
        let target_format = target_view.texture().format();

        let pipeline = self.get_or_create_pipeline(texture, kind, target_format, pipeline_msaa_samples, is_filterable);
        pass.set_pipeline(pipeline);

        let bind_group = self.get_or_create_bind_group(texture, kind, is_filterable);
        pass.set_bind_group(0, bind_group, &[]);

        // LinearDepth also needs depth params for normalization
        if kind == PipelineKind::Depth || kind == PipelineKind::LinearDepth {
            if let Some(bg) = &self.depth_params_bind_group {
                pass.set_bind_group(1, bg, &[]);
            }
        }

        pass.draw(0..4, 0..1);
    }

    /// Clear cached bind groups (call when textures are recreated).
    pub(crate) fn invalidate_bind_groups(&mut self) {
        self.bind_groups.clear();
    }

    pub(crate) fn update_depth_params(&mut self, params: DepthDebugParams) {
        if let Some(buf) = &self.depth_params_buffer {
            self.queue.write_buffer(buf, 0, bytemuck::bytes_of(&params));
        } else {
            let buf = self.device.create_buffer_init(&util::BufferInitDescriptor {
                label: Some("depth params buffer"),
                contents: bytemuck::bytes_of(&params),
                usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
            });

            let bg = self.device.create_bind_group(&BindGroupDescriptor {
                label: Some("depth params bind group"),
                layout: &self.depth_params_bgl,
                entries: &[BindGroupEntry {
                    binding: 0,
                    resource: buf.as_entire_binding(),
                }],
            });

            self.depth_params_buffer = Some(buf);
            self.depth_params_bind_group = Some(bg);
        }
    }

    fn get_or_create_pipeline(
        &mut self,
        texture: &TextureView,
        kind: PipelineKind,
        target_format: TextureFormat,
        target_sample_count: u32,
        is_filterable: bool,
    ) -> &RenderPipeline {
        let source_is_msaa = texture.texture().sample_count() > 1;
        let key = PipelineKey {
            kind,
            target_format,
            source_is_msaa,
            source_is_filterable: is_filterable,
            target_sample_count,
        };

        if !self.pipelines.contains_key(&key) {
            let pipeline = self.create_pipeline(kind, target_format, target_sample_count, source_is_msaa, is_filterable);
            self.pipelines.insert(key, pipeline);
        }

        self.pipelines.get(&key).unwrap()
    }

    fn create_pipeline(
        &self,
        kind: PipelineKind,
        target_format: TextureFormat,
        pipeline_msaa_samples: u32,
        source_is_msaa: bool,
        is_filterable: bool,
    ) -> RenderPipeline {
        let (shader, bgl) = match (kind, source_is_msaa, is_filterable) {
            // MSAA sources always use MSAA shaders (they use textureLoad)
            (PipelineKind::Color, true, _) => (&self.color_msaa_shader, &self.color_msaa_bgl),
            (PipelineKind::RedToGrayscale, true, _) => (&self.red_to_grayscale_msaa_shader, &self.color_msaa_bgl),
            (PipelineKind::Depth, true, _) => (&self.depth_msaa_shader, &self.depth_msaa_bgl),
            (PipelineKind::LinearDepth, true, _) => (&self.color_msaa_shader, &self.color_msaa_bgl), // MSAA linear depth unlikely, fallback to color

            // Non-MSAA filterable float textures use sampler-based shaders
            (PipelineKind::Color, false, true) => (&self.color_shader, &self.color_bgl),
            (PipelineKind::RedToGrayscale, false, true) => (&self.red_to_grayscale_shader, &self.color_bgl),
            (PipelineKind::LinearDepth, false, true) => (&self.linear_depth_shader, &self.color_bgl),

            // Non-MSAA non-filterable float textures use textureLoad shaders
            (PipelineKind::Color, false, false) => (&self.color_unfilterable_shader, &self.color_unfilterable_bgl),
            (PipelineKind::RedToGrayscale, false, false) => (&self.red_to_grayscale_unfilterable_shader, &self.color_unfilterable_bgl),
            (PipelineKind::LinearDepth, false, false) => (&self.linear_depth_unfilterable_shader, &self.color_unfilterable_bgl),

            // Depth textures (non-MSAA) use their own sampler-based shader
            (PipelineKind::Depth, false, _) => (&self.depth_shader, &self.depth_bgl),
        };

        // LinearDepth also needs depth_params_bgl for the far plane value
        let bind_group_layouts: Vec<Option<&BindGroupLayout>> = if kind == PipelineKind::Depth || kind == PipelineKind::LinearDepth {
            vec![Some(bgl), Some(&self.depth_params_bgl)]
        } else {
            vec![Some(bgl)]
        };

        let layout = self.device.create_pipeline_layout(&PipelineLayoutDescriptor {
            label: Some("fullscreen pipeline layout"),
            bind_group_layouts: &bind_group_layouts,
            immediate_size: 0,
        });

        self.device.create_render_pipeline(&RenderPipelineDescriptor {
            label: Some("fullscreen pipeline"),
            layout: Some(&layout),
            vertex: VertexState {
                module: shader,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(FragmentState {
                module: shader,
                entry_point: Some("fs_main"),
                targets: &[Some(ColorTargetState {
                    format: target_format,
                    blend: None,
                    write_mask: ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: PrimitiveState {
                topology: PrimitiveTopology::TriangleStrip,
                ..Default::default()
            },
            depth_stencil: None,
            multisample: MultisampleState {
                count: pipeline_msaa_samples,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            cache: None,
            multiview_mask: None,
        })
    }

    fn get_or_create_bind_group(
        &mut self,
        view: &TextureView,
        kind: PipelineKind,
        is_filterable: bool,
    ) -> &BindGroup {
        let key = BindGroupKey {
            view_ptr: view as *const TextureView as usize,
            kind,
            is_filterable,
        };

        let is_msaa = view.texture().sample_count() > 1;

        if !self.bind_groups.contains_key(&key) {
            let bg = match (kind, is_msaa, is_filterable) {
                // MSAA textures: no sampler, just texture at binding 0
                (PipelineKind::Color | PipelineKind::RedToGrayscale | PipelineKind::LinearDepth, true, _) => {
                    self.device.create_bind_group(&BindGroupDescriptor {
                        label: Some("Fullscreen Color MSAA Bind Group"),
                        layout: &self.color_msaa_bgl,
                        entries: &[BindGroupEntry {
                            binding: 0,
                            resource: BindingResource::TextureView(view),
                        }],
                    })
                }
                (PipelineKind::Depth, true, _) => {
                    self.device.create_bind_group(&BindGroupDescriptor {
                        label: Some("Fullscreen Depth MSAA Bind Group"),
                        layout: &self.depth_msaa_bgl,
                        entries: &[BindGroupEntry {
                            binding: 0,
                            resource: BindingResource::TextureView(view),
                        }],
                    })
                }

                // Non-MSAA unfilterable: no sampler, just texture at binding 0
                (PipelineKind::Color | PipelineKind::RedToGrayscale | PipelineKind::LinearDepth, false, false) => {
                    self.device.create_bind_group(&BindGroupDescriptor {
                        label: Some("Fullscreen Color Unfilterable Bind Group"),
                        layout: &self.color_unfilterable_bgl,
                        entries: &[BindGroupEntry {
                            binding: 0,
                            resource: BindingResource::TextureView(view),
                        }],
                    })
                }

                // Non-MSAA filterable: sampler + texture
                (PipelineKind::Color | PipelineKind::RedToGrayscale | PipelineKind::LinearDepth, false, true) => {
                    self.device.create_bind_group(&BindGroupDescriptor {
                        label: Some("Fullscreen Color Bind Group"),
                        layout: &self.color_bgl,
                        entries: &[
                            BindGroupEntry {
                                binding: 0,
                                resource: BindingResource::Sampler(&self.linear_sampler),
                            },
                            BindGroupEntry {
                                binding: 1,
                                resource: BindingResource::TextureView(view),
                            },
                        ],
                    })
                }

                // Depth non-MSAA: nearest sampler + texture
                (PipelineKind::Depth, false, _) => {
                    self.device.create_bind_group(&BindGroupDescriptor {
                        label: Some("Fullscreen Depth Bind Group"),
                        layout: &self.depth_bgl,
                        entries: &[
                            BindGroupEntry {
                                binding: 0,
                                resource: BindingResource::Sampler(&self.nearest_sampler),
                            },
                            BindGroupEntry {
                                binding: 1,
                                resource: BindingResource::TextureView(view),
                            },
                        ],
                    })
                }
            };

            self.bind_groups.insert(key, bg);
        }

        self.bind_groups.get(&key).unwrap()
    }
}

/// Infer a `BindingType::Texture` for a view + device.
/// Automatically determines the correct aspect for depth-stencil formats.
fn infer_texture_binding_type(view: &TextureView, device: &Device) -> BindingType {
    let format = view.texture().format();

    // Determine the appropriate aspect for sampling
    let aspect = figure_out_aspect(format);

    let sample_type = format
        .sample_type(aspect, Some(device.features()))
        .unwrap_or_else(|| {
            panic!(
                "unsupported texture format {:?} with aspect {:?} for sampling",
                format, aspect
            )
        });

    let multisampled = view.texture().sample_count() > 1;

    BindingType::Texture {
        sample_type,
        view_dimension: TextureViewDimension::D2,
        multisampled,
    }
}