1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
use crate::resource::Resource;
use crate::snatch::SnatchGuard;
use crate::{
    api_log,
    binding_model::BindError,
    command::{
        self,
        bind::Binder,
        end_occlusion_query, end_pipeline_statistics_query,
        memory_init::{fixup_discarded_surfaces, SurfacesInDiscardState},
        BasePass, BasePassRef, BindGroupStateChange, CommandBuffer, CommandEncoderError,
        CommandEncoderStatus, DrawError, ExecutionError, MapPassErr, PassErrorScope, QueryUseError,
        RenderCommand, RenderCommandError, StateChange,
    },
    device::{
        AttachmentData, Device, DeviceError, MissingDownlevelFlags, MissingFeatures,
        RenderPassCompatibilityCheckType, RenderPassCompatibilityError, RenderPassContext,
    },
    error::{ErrorFormatter, PrettyError},
    global::Global,
    hal_api::HalApi,
    hal_label, id,
    init_tracker::{MemoryInitKind, TextureInitRange, TextureInitTrackerAction},
    pipeline::{self, PipelineFlags},
    resource::{QuerySet, Texture, TextureView, TextureViewNotRenderableReason},
    storage::Storage,
    track::{TextureSelector, Tracker, UsageConflict, UsageScope},
    validation::{
        check_buffer_usage, check_texture_usage, MissingBufferUsageError, MissingTextureUsageError,
    },
    Label,
};

use arrayvec::ArrayVec;
use hal::CommandEncoder as _;
use thiserror::Error;
use wgt::{
    BufferAddress, BufferSize, BufferUsages, Color, IndexFormat, TextureUsages,
    TextureViewDimension, VertexStepMode,
};

#[cfg(feature = "serde")]
use serde::Deserialize;
#[cfg(feature = "serde")]
use serde::Serialize;

use std::sync::Arc;
use std::{borrow::Cow, fmt, iter, marker::PhantomData, mem, num::NonZeroU32, ops::Range, str};

use super::{
    memory_init::TextureSurfaceDiscard, CommandBufferTextureMemoryActions, CommandEncoder,
    QueryResetMap,
};

/// Operation to perform to the output attachment at the start of a renderpass.
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum LoadOp {
    /// Clear the output attachment with the clear color. Clearing is faster than loading.
    Clear = 0,
    /// Do not clear output attachment.
    Load = 1,
}

/// Operation to perform to the output attachment at the end of a renderpass.
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum StoreOp {
    /// Discards the content of the render target.
    ///
    /// If you don't care about the contents of the target, this can be faster.
    Discard = 0,
    /// Store the result of the renderpass.
    Store = 1,
}

/// Describes an individual channel within a render pass, such as color, depth, or stencil.
#[repr(C)]
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PassChannel<V> {
    /// Operation to perform to the output attachment at the start of a
    /// renderpass.
    ///
    /// This must be clear if it is the first renderpass rendering to a swap
    /// chain image.
    pub load_op: LoadOp,
    /// Operation to perform to the output attachment at the end of a renderpass.
    pub store_op: StoreOp,
    /// If load_op is [`LoadOp::Clear`], the attachment will be cleared to this
    /// color.
    pub clear_value: V,
    /// If true, the relevant channel is not changed by a renderpass, and the
    /// corresponding attachment can be used inside the pass by other read-only
    /// usages.
    pub read_only: bool,
}

impl<V> PassChannel<V> {
    fn hal_ops(&self) -> hal::AttachmentOps {
        let mut ops = hal::AttachmentOps::empty();
        match self.load_op {
            LoadOp::Load => ops |= hal::AttachmentOps::LOAD,
            LoadOp::Clear => (),
        };
        match self.store_op {
            StoreOp::Store => ops |= hal::AttachmentOps::STORE,
            StoreOp::Discard => (),
        };
        ops
    }
}

/// Describes a color attachment to a render pass.
#[repr(C)]
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct RenderPassColorAttachment {
    /// The view to use as an attachment.
    pub view: id::TextureViewId,
    /// The view that will receive the resolved output if multisampling is used.
    pub resolve_target: Option<id::TextureViewId>,
    /// What operations will be performed on this color attachment.
    pub channel: PassChannel<Color>,
}

/// Describes a depth/stencil attachment to a render pass.
#[repr(C)]
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct RenderPassDepthStencilAttachment {
    /// The view to use as an attachment.
    pub view: id::TextureViewId,
    /// What operations will be performed on the depth part of the attachment.
    pub depth: PassChannel<f32>,
    /// What operations will be performed on the stencil part of the attachment.
    pub stencil: PassChannel<u32>,
}

impl RenderPassDepthStencilAttachment {
    /// Validate the given aspects' read-only flags against their load
    /// and store ops.
    ///
    /// When an aspect is read-only, its load and store ops must be
    /// `LoadOp::Load` and `StoreOp::Store`.
    ///
    /// On success, return a pair `(depth, stencil)` indicating
    /// whether the depth and stencil passes are read-only.
    fn depth_stencil_read_only(
        &self,
        aspects: hal::FormatAspects,
    ) -> Result<(bool, bool), RenderPassErrorInner> {
        let mut depth_read_only = true;
        let mut stencil_read_only = true;

        if aspects.contains(hal::FormatAspects::DEPTH) {
            if self.depth.read_only
                && (self.depth.load_op, self.depth.store_op) != (LoadOp::Load, StoreOp::Store)
            {
                return Err(RenderPassErrorInner::InvalidDepthOps);
            }
            depth_read_only = self.depth.read_only;
        }

        if aspects.contains(hal::FormatAspects::STENCIL) {
            if self.stencil.read_only
                && (self.stencil.load_op, self.stencil.store_op) != (LoadOp::Load, StoreOp::Store)
            {
                return Err(RenderPassErrorInner::InvalidStencilOps);
            }
            stencil_read_only = self.stencil.read_only;
        }

        Ok((depth_read_only, stencil_read_only))
    }
}

/// Location to write a timestamp to (beginning or end of the pass).
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum RenderPassTimestampLocation {
    Beginning = 0,
    End = 1,
}

/// Describes the writing of timestamp values in a render pass.
#[repr(C)]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct RenderPassTimestampWrites {
    /// The query set to write the timestamp to.
    pub query_set: id::QuerySetId,
    /// The index of the query set at which a start timestamp of this pass is written, if any.
    pub beginning_of_pass_write_index: Option<u32>,
    /// The index of the query set at which an end timestamp of this pass is written, if any.
    pub end_of_pass_write_index: Option<u32>,
}

/// Describes the attachments of a render pass.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RenderPassDescriptor<'a> {
    pub label: Label<'a>,
    /// The color attachments of the render pass.
    pub color_attachments: Cow<'a, [Option<RenderPassColorAttachment>]>,
    /// The depth and stencil attachment of the render pass, if any.
    pub depth_stencil_attachment: Option<&'a RenderPassDepthStencilAttachment>,
    /// Defines where and when timestamp values will be written for this pass.
    pub timestamp_writes: Option<&'a RenderPassTimestampWrites>,
    /// Defines where the occlusion query results will be stored for this pass.
    pub occlusion_query_set: Option<id::QuerySetId>,
}

#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct RenderPass {
    base: BasePass<RenderCommand>,
    parent_id: id::CommandEncoderId,
    color_targets: ArrayVec<Option<RenderPassColorAttachment>, { hal::MAX_COLOR_ATTACHMENTS }>,
    depth_stencil_target: Option<RenderPassDepthStencilAttachment>,
    timestamp_writes: Option<RenderPassTimestampWrites>,
    occlusion_query_set_id: Option<id::QuerySetId>,

    // Resource binding dedupe state.
    #[cfg_attr(feature = "serde", serde(skip))]
    current_bind_groups: BindGroupStateChange,
    #[cfg_attr(feature = "serde", serde(skip))]
    current_pipeline: StateChange<id::RenderPipelineId>,
}

impl RenderPass {
    pub fn new(parent_id: id::CommandEncoderId, desc: &RenderPassDescriptor) -> Self {
        Self {
            base: BasePass::new(&desc.label),
            parent_id,
            color_targets: desc.color_attachments.iter().cloned().collect(),
            depth_stencil_target: desc.depth_stencil_attachment.cloned(),
            timestamp_writes: desc.timestamp_writes.cloned(),
            occlusion_query_set_id: desc.occlusion_query_set,

            current_bind_groups: BindGroupStateChange::new(),
            current_pipeline: StateChange::new(),
        }
    }

    pub fn parent_id(&self) -> id::CommandEncoderId {
        self.parent_id
    }

    #[cfg(feature = "trace")]
    pub fn into_command(self) -> crate::device::trace::Command {
        crate::device::trace::Command::RunRenderPass {
            base: self.base,
            target_colors: self.color_targets.into_iter().collect(),
            target_depth_stencil: self.depth_stencil_target,
            timestamp_writes: self.timestamp_writes,
            occlusion_query_set_id: self.occlusion_query_set_id,
        }
    }

    pub fn set_index_buffer(
        &mut self,
        buffer_id: id::BufferId,
        index_format: IndexFormat,
        offset: BufferAddress,
        size: Option<BufferSize>,
    ) {
        self.base.commands.push(RenderCommand::SetIndexBuffer {
            buffer_id,
            index_format,
            offset,
            size,
        });
    }
}

impl fmt::Debug for RenderPass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RenderPass")
            .field("encoder_id", &self.parent_id)
            .field("color_targets", &self.color_targets)
            .field("depth_stencil_target", &self.depth_stencil_target)
            .field("command count", &self.base.commands.len())
            .field("dynamic offset count", &self.base.dynamic_offsets.len())
            .field(
                "push constant u32 count",
                &self.base.push_constant_data.len(),
            )
            .finish()
    }
}

#[derive(Debug, PartialEq)]
enum OptionalState {
    Unused,
    Required,
    Set,
}

impl OptionalState {
    fn require(&mut self, require: bool) {
        if require && *self == Self::Unused {
            *self = Self::Required;
        }
    }
}

#[derive(Debug, Default)]
struct IndexState {
    bound_buffer_view: Option<(id::BufferId, Range<BufferAddress>)>,
    format: Option<IndexFormat>,
    pipeline_format: Option<IndexFormat>,
    limit: u64,
}

impl IndexState {
    fn update_limit(&mut self) {
        self.limit = match self.bound_buffer_view {
            Some((_, ref range)) => {
                let format = self
                    .format
                    .expect("IndexState::update_limit must be called after a index buffer is set");
                let shift = match format {
                    IndexFormat::Uint16 => 1,
                    IndexFormat::Uint32 => 2,
                };

                (range.end - range.start) >> shift
            }
            None => 0,
        }
    }

    fn reset(&mut self) {
        self.bound_buffer_view = None;
        self.limit = 0;
    }
}

#[derive(Clone, Copy, Debug)]
struct VertexBufferState {
    total_size: BufferAddress,
    step: pipeline::VertexStep,
    bound: bool,
}

impl VertexBufferState {
    const EMPTY: Self = Self {
        total_size: 0,
        step: pipeline::VertexStep {
            stride: 0,
            last_stride: 0,
            mode: VertexStepMode::Vertex,
        },
        bound: false,
    };
}

#[derive(Debug, Default)]
struct VertexState {
    inputs: ArrayVec<VertexBufferState, { hal::MAX_VERTEX_BUFFERS }>,
    /// Length of the shortest vertex rate vertex buffer
    vertex_limit: u64,
    /// Buffer slot which the shortest vertex rate vertex buffer is bound to
    vertex_limit_slot: u32,
    /// Length of the shortest instance rate vertex buffer
    instance_limit: u64,
    /// Buffer slot which the shortest instance rate vertex buffer is bound to
    instance_limit_slot: u32,
    /// Total amount of buffers required by the pipeline.
    buffers_required: u32,
}

impl VertexState {
    fn update_limits(&mut self) {
        // Implements the validation from https://gpuweb.github.io/gpuweb/#dom-gpurendercommandsmixin-draw
        // Except that the formula is shuffled to extract the number of vertices in order
        // to carry the bulk of the computation when changing states instead of when producing
        // draws. Draw calls tend to happen at a higher frequency. Here we determine vertex
        // limits that can be cheaply checked for each draw call.
        self.vertex_limit = u32::MAX as u64;
        self.instance_limit = u32::MAX as u64;
        for (idx, vbs) in self.inputs.iter().enumerate() {
            if !vbs.bound {
                continue;
            }

            let limit = if vbs.total_size < vbs.step.last_stride {
                // The buffer cannot fit the last vertex.
                0
            } else {
                if vbs.step.stride == 0 {
                    // We already checked that the last stride fits, the same
                    // vertex will be repeated so this slot can accommodate any number of
                    // vertices.
                    continue;
                }

                // The general case.
                (vbs.total_size - vbs.step.last_stride) / vbs.step.stride + 1
            };

            match vbs.step.mode {
                VertexStepMode::Vertex => {
                    if limit < self.vertex_limit {
                        self.vertex_limit = limit;
                        self.vertex_limit_slot = idx as _;
                    }
                }
                VertexStepMode::Instance => {
                    if limit < self.instance_limit {
                        self.instance_limit = limit;
                        self.instance_limit_slot = idx as _;
                    }
                }
            }
        }
    }

    fn reset(&mut self) {
        self.inputs.clear();
        self.vertex_limit = 0;
        self.instance_limit = 0;
    }
}

#[derive(Debug)]
struct State<A: HalApi> {
    pipeline_flags: PipelineFlags,
    binder: Binder<A>,
    blend_constant: OptionalState,
    stencil_reference: u32,
    pipeline: Option<id::RenderPipelineId>,
    index: IndexState,
    vertex: VertexState,
    debug_scope_depth: u32,
}

impl<A: HalApi> State<A> {
    fn is_ready(&self, indexed: bool) -> Result<(), DrawError> {
        // Determine how many vertex buffers have already been bound
        let vertex_buffer_count = self.vertex.inputs.iter().take_while(|v| v.bound).count() as u32;
        // Compare with the needed quantity
        if vertex_buffer_count < self.vertex.buffers_required {
            return Err(DrawError::MissingVertexBuffer {
                index: vertex_buffer_count,
            });
        }

        let bind_mask = self.binder.invalid_mask();
        if bind_mask != 0 {
            //let (expected, provided) = self.binder.entries[index as usize].info();
            return Err(DrawError::IncompatibleBindGroup {
                index: bind_mask.trailing_zeros(),
                diff: self.binder.bgl_diff(),
            });
        }
        if self.pipeline.is_none() {
            return Err(DrawError::MissingPipeline);
        }
        if self.blend_constant == OptionalState::Required {
            return Err(DrawError::MissingBlendConstant);
        }

        if indexed {
            // Pipeline expects an index buffer
            if let Some(pipeline_index_format) = self.index.pipeline_format {
                // We have a buffer bound
                let buffer_index_format = self.index.format.ok_or(DrawError::MissingIndexBuffer)?;

                // The buffers are different formats
                if pipeline_index_format != buffer_index_format {
                    return Err(DrawError::UnmatchedIndexFormats {
                        pipeline: pipeline_index_format,
                        buffer: buffer_index_format,
                    });
                }
            }
        }

        self.binder.check_late_buffer_bindings()?;

        Ok(())
    }

    /// Reset the `RenderBundle`-related states.
    fn reset_bundle(&mut self) {
        self.binder.reset();
        self.pipeline = None;
        self.index.reset();
        self.vertex.reset();
    }
}

/// Describes an attachment location in words.
///
/// Can be used as "the {loc} has..." or "{loc} has..."
#[derive(Debug, Copy, Clone)]
pub enum AttachmentErrorLocation {
    Color { index: usize, resolve: bool },
    Depth,
}

impl fmt::Display for AttachmentErrorLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            AttachmentErrorLocation::Color {
                index,
                resolve: false,
            } => write!(f, "color attachment at index {index}'s texture view"),
            AttachmentErrorLocation::Color {
                index,
                resolve: true,
            } => write!(
                f,
                "color attachment at index {index}'s resolve texture view"
            ),
            AttachmentErrorLocation::Depth => write!(f, "depth attachment's texture view"),
        }
    }
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum ColorAttachmentError {
    #[error("Attachment format {0:?} is not a color format")]
    InvalidFormat(wgt::TextureFormat),
    #[error("The number of color attachments {given} exceeds the limit {limit}")]
    TooMany { given: usize, limit: usize },
    #[error("The total number of bytes per sample in color attachments {total} exceeds the limit {limit}")]
    TooManyBytesPerSample { total: u32, limit: u32 },
}

/// Error encountered when performing a render pass.
#[derive(Clone, Debug, Error)]
pub enum RenderPassErrorInner {
    #[error(transparent)]
    Device(DeviceError),
    #[error(transparent)]
    ColorAttachment(#[from] ColorAttachmentError),
    #[error(transparent)]
    Encoder(#[from] CommandEncoderError),
    #[error("Attachment texture view {0:?} is invalid")]
    InvalidAttachment(id::TextureViewId),
    #[error("Attachment texture view {0:?} is invalid")]
    InvalidResolveTarget(id::TextureViewId),
    #[error("The format of the depth-stencil attachment ({0:?}) is not a depth-stencil format")]
    InvalidDepthStencilAttachmentFormat(wgt::TextureFormat),
    #[error("The format of the {location} ({format:?}) is not resolvable")]
    UnsupportedResolveTargetFormat {
        location: AttachmentErrorLocation,
        format: wgt::TextureFormat,
    },
    #[error("No color attachments or depth attachments were provided, at least one attachment of any kind must be provided")]
    MissingAttachments,
    #[error("The {location} is not renderable:")]
    TextureViewIsNotRenderable {
        location: AttachmentErrorLocation,
        #[source]
        reason: TextureViewNotRenderableReason,
    },
    #[error("Attachments have differing sizes: the {expected_location} has extent {expected_extent:?} but is followed by the {actual_location} which has {actual_extent:?}")]
    AttachmentsDimensionMismatch {
        expected_location: AttachmentErrorLocation,
        expected_extent: wgt::Extent3d,
        actual_location: AttachmentErrorLocation,
        actual_extent: wgt::Extent3d,
    },
    #[error("Attachments have differing sample counts: the {expected_location} has count {expected_samples:?} but is followed by the {actual_location} which has count {actual_samples:?}")]
    AttachmentSampleCountMismatch {
        expected_location: AttachmentErrorLocation,
        expected_samples: u32,
        actual_location: AttachmentErrorLocation,
        actual_samples: u32,
    },
    #[error("The resolve source, {location}, must be multi-sampled (has {src} samples) while the resolve destination must not be multisampled (has {dst} samples)")]
    InvalidResolveSampleCounts {
        location: AttachmentErrorLocation,
        src: u32,
        dst: u32,
    },
    #[error(
        "Resource source, {location}, format ({src:?}) must match the resolve destination format ({dst:?})"
    )]
    MismatchedResolveTextureFormat {
        location: AttachmentErrorLocation,
        src: wgt::TextureFormat,
        dst: wgt::TextureFormat,
    },
    #[error("Surface texture is dropped before the render pass is finished")]
    SurfaceTextureDropped,
    #[error("Not enough memory left for render pass")]
    OutOfMemory,
    #[error("The bind group at index {0:?} is invalid")]
    InvalidBindGroup(usize),
    #[error("Unable to clear non-present/read-only depth")]
    InvalidDepthOps,
    #[error("Unable to clear non-present/read-only stencil")]
    InvalidStencilOps,
    #[error("Setting `values_offset` to be `None` is only for internal use in render bundles")]
    InvalidValuesOffset,
    #[error(transparent)]
    MissingFeatures(#[from] MissingFeatures),
    #[error(transparent)]
    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
    #[error("Indirect draw uses bytes {offset}..{end_offset} {} which overruns indirect buffer of size {buffer_size}",
        count.map_or_else(String::new, |v| format!("(using count {v})")))]
    IndirectBufferOverrun {
        count: Option<NonZeroU32>,
        offset: u64,
        end_offset: u64,
        buffer_size: u64,
    },
    #[error("Indirect draw uses bytes {begin_count_offset}..{end_count_offset} which overruns indirect buffer of size {count_buffer_size}")]
    IndirectCountBufferOverrun {
        begin_count_offset: u64,
        end_count_offset: u64,
        count_buffer_size: u64,
    },
    #[error("Cannot pop debug group, because number of pushed debug groups is zero")]
    InvalidPopDebugGroup,
    #[error(transparent)]
    ResourceUsageConflict(#[from] UsageConflict),
    #[error("Render bundle has incompatible targets, {0}")]
    IncompatibleBundleTargets(#[from] RenderPassCompatibilityError),
    #[error(
        "Render bundle has incompatible read-only flags: \
             bundle has flags depth = {bundle_depth} and stencil = {bundle_stencil}, \
             while the pass has flags depth = {pass_depth} and stencil = {pass_stencil}. \
             Read-only renderpasses are only compatible with read-only bundles for that aspect."
    )]
    IncompatibleBundleReadOnlyDepthStencil {
        pass_depth: bool,
        pass_stencil: bool,
        bundle_depth: bool,
        bundle_stencil: bool,
    },
    #[error(transparent)]
    RenderCommand(#[from] RenderCommandError),
    #[error(transparent)]
    Draw(#[from] DrawError),
    #[error(transparent)]
    Bind(#[from] BindError),
    #[error(transparent)]
    QueryUse(#[from] QueryUseError),
    #[error("Multiview layer count must match")]
    MultiViewMismatch,
    #[error(
        "Multiview pass texture views with more than one array layer must have D2Array dimension"
    )]
    MultiViewDimensionMismatch,
    #[error("QuerySet {0:?} is invalid")]
    InvalidQuerySet(id::QuerySetId),
    #[error("missing occlusion query set")]
    MissingOcclusionQuerySet,
}

impl PrettyError for RenderPassErrorInner {
    fn fmt_pretty(&self, fmt: &mut ErrorFormatter) {
        fmt.error(self);
        if let Self::InvalidAttachment(id) = *self {
            fmt.texture_view_label_with_key(&id, "attachment");
        };
        if let Self::Draw(DrawError::IncompatibleBindGroup { diff, .. }) = self {
            for d in diff {
                fmt.note(&d);
            }
        };
    }
}

impl From<MissingBufferUsageError> for RenderPassErrorInner {
    fn from(error: MissingBufferUsageError) -> Self {
        Self::RenderCommand(error.into())
    }
}

impl From<MissingTextureUsageError> for RenderPassErrorInner {
    fn from(error: MissingTextureUsageError) -> Self {
        Self::RenderCommand(error.into())
    }
}

impl From<DeviceError> for RenderPassErrorInner {
    fn from(error: DeviceError) -> Self {
        Self::Device(error)
    }
}

/// Error encountered when performing a render pass.
#[derive(Clone, Debug, Error)]
#[error("{scope}")]
pub struct RenderPassError {
    pub scope: PassErrorScope,
    #[source]
    inner: RenderPassErrorInner,
}
impl PrettyError for RenderPassError {
    fn fmt_pretty(&self, fmt: &mut ErrorFormatter) {
        // This error is wrapper for the inner error,
        // but the scope has useful labels
        fmt.error(self);
        self.scope.fmt_pretty(fmt);
    }
}

impl<T, E> MapPassErr<T, RenderPassError> for Result<T, E>
where
    E: Into<RenderPassErrorInner>,
{
    fn map_pass_err(self, scope: PassErrorScope) -> Result<T, RenderPassError> {
        self.map_err(|inner| RenderPassError {
            scope,
            inner: inner.into(),
        })
    }
}

struct RenderAttachment<'a, A: HalApi> {
    texture: Arc<Texture<A>>,
    selector: &'a TextureSelector,
    usage: hal::TextureUses,
}

impl<A: HalApi> TextureView<A> {
    fn to_render_attachment(&self, usage: hal::TextureUses) -> RenderAttachment<A> {
        RenderAttachment {
            texture: self.parent.clone(),
            selector: &self.selector,
            usage,
        }
    }
}

const MAX_TOTAL_ATTACHMENTS: usize = hal::MAX_COLOR_ATTACHMENTS + hal::MAX_COLOR_ATTACHMENTS + 1;
type AttachmentDataVec<T> = ArrayVec<T, MAX_TOTAL_ATTACHMENTS>;

struct RenderPassInfo<'a, 'd, A: HalApi> {
    context: RenderPassContext,
    usage_scope: UsageScope<'d, A>,
    /// All render attachments, including depth/stencil
    render_attachments: AttachmentDataVec<RenderAttachment<'a, A>>,
    is_depth_read_only: bool,
    is_stencil_read_only: bool,
    extent: wgt::Extent3d,
    _phantom: PhantomData<A>,

    pending_discard_init_fixups: SurfacesInDiscardState<A>,
    divergent_discarded_depth_stencil_aspect: Option<(wgt::TextureAspect, &'a TextureView<A>)>,
    multiview: Option<NonZeroU32>,
}

impl<'a, 'd, A: HalApi> RenderPassInfo<'a, 'd, A> {
    fn add_pass_texture_init_actions<V>(
        channel: &PassChannel<V>,
        texture_memory_actions: &mut CommandBufferTextureMemoryActions<A>,
        view: &TextureView<A>,
        pending_discard_init_fixups: &mut SurfacesInDiscardState<A>,
    ) {
        if channel.load_op == LoadOp::Load {
            pending_discard_init_fixups.extend(texture_memory_actions.register_init_action(
                &TextureInitTrackerAction {
                    texture: view.parent.clone(),
                    range: TextureInitRange::from(view.selector.clone()),
                    // Note that this is needed even if the target is discarded,
                    kind: MemoryInitKind::NeedsInitializedMemory,
                },
            ));
        } else if channel.store_op == StoreOp::Store {
            // Clear + Store
            texture_memory_actions.register_implicit_init(
                &view.parent,
                TextureInitRange::from(view.selector.clone()),
            );
        }
        if channel.store_op == StoreOp::Discard {
            // the discard happens at the *end* of a pass, but recording the
            // discard right away be alright since the texture can't be used
            // during the pass anyways
            texture_memory_actions.discard(TextureSurfaceDiscard {
                texture: view.parent.clone(),
                mip_level: view.selector.mips.start,
                layer: view.selector.layers.start,
            });
        }
    }

    fn start(
        device: &'d Device<A>,
        label: Option<&str>,
        color_attachments: &[Option<RenderPassColorAttachment>],
        depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>,
        timestamp_writes: Option<&RenderPassTimestampWrites>,
        occlusion_query_set: Option<id::QuerySetId>,
        encoder: &mut CommandEncoder<A>,
        trackers: &mut Tracker<A>,
        texture_memory_actions: &mut CommandBufferTextureMemoryActions<A>,
        pending_query_resets: &mut QueryResetMap<A>,
        view_guard: &'a Storage<TextureView<A>>,
        query_set_guard: &'a Storage<QuerySet<A>>,
        snatch_guard: &SnatchGuard<'a>,
    ) -> Result<Self, RenderPassErrorInner> {
        profiling::scope!("RenderPassInfo::start");

        // We default to false intentionally, even if depth-stencil isn't used at all.
        // This allows us to use the primary raw pipeline in `RenderPipeline`,
        // instead of the special read-only one, which would be `None`.
        let mut is_depth_read_only = false;
        let mut is_stencil_read_only = false;

        let mut render_attachments = AttachmentDataVec::<RenderAttachment<A>>::new();
        let mut discarded_surfaces = AttachmentDataVec::new();
        let mut pending_discard_init_fixups = SurfacesInDiscardState::new();
        let mut divergent_discarded_depth_stencil_aspect = None;

        let mut attachment_location = AttachmentErrorLocation::Color {
            index: usize::MAX,
            resolve: false,
        };
        let mut extent = None;
        let mut sample_count = 0;

        let mut detected_multiview: Option<Option<NonZeroU32>> = None;

        let mut check_multiview = |view: &TextureView<A>| {
            // Get the multiview configuration for this texture view
            let layers = view.selector.layers.end - view.selector.layers.start;
            let this_multiview = if layers >= 2 {
                // Trivially proven by the if above
                Some(unsafe { NonZeroU32::new_unchecked(layers) })
            } else {
                None
            };

            // Make sure that if this view is a multiview, it is set to be an array
            if this_multiview.is_some() && view.desc.dimension != TextureViewDimension::D2Array {
                return Err(RenderPassErrorInner::MultiViewDimensionMismatch);
            }

            // Validate matching first, or store the first one
            if let Some(multiview) = detected_multiview {
                if multiview != this_multiview {
                    return Err(RenderPassErrorInner::MultiViewMismatch);
                }
            } else {
                // Multiview is only supported if the feature is enabled
                if this_multiview.is_some() {
                    device.require_features(wgt::Features::MULTIVIEW)?;
                }

                detected_multiview = Some(this_multiview);
            }

            Ok(())
        };
        let mut add_view = |view: &TextureView<A>, location| {
            let render_extent = view.render_extent.map_err(|reason| {
                RenderPassErrorInner::TextureViewIsNotRenderable { location, reason }
            })?;
            if let Some(ex) = extent {
                if ex != render_extent {
                    return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
                        expected_location: attachment_location,
                        expected_extent: ex,
                        actual_location: location,
                        actual_extent: render_extent,
                    });
                }
            } else {
                extent = Some(render_extent);
            }
            if sample_count == 0 {
                sample_count = view.samples;
            } else if sample_count != view.samples {
                return Err(RenderPassErrorInner::AttachmentSampleCountMismatch {
                    expected_location: attachment_location,
                    expected_samples: sample_count,
                    actual_location: location,
                    actual_samples: view.samples,
                });
            }
            attachment_location = location;
            Ok(())
        };

        let mut colors =
            ArrayVec::<Option<hal::ColorAttachment<A>>, { hal::MAX_COLOR_ATTACHMENTS }>::new();
        let mut depth_stencil = None;

        if let Some(at) = depth_stencil_attachment {
            let view: &TextureView<A> = trackers
                .views
                .add_single(view_guard, at.view)
                .ok_or(RenderPassErrorInner::InvalidAttachment(at.view))?;
            check_multiview(view)?;
            add_view(view, AttachmentErrorLocation::Depth)?;

            let ds_aspects = view.desc.aspects();
            if ds_aspects.contains(hal::FormatAspects::COLOR) {
                return Err(RenderPassErrorInner::InvalidDepthStencilAttachmentFormat(
                    view.desc.format,
                ));
            }

            if !ds_aspects.contains(hal::FormatAspects::STENCIL)
                || (at.stencil.load_op == at.depth.load_op
                    && at.stencil.store_op == at.depth.store_op)
            {
                Self::add_pass_texture_init_actions(
                    &at.depth,
                    texture_memory_actions,
                    view,
                    &mut pending_discard_init_fixups,
                );
            } else if !ds_aspects.contains(hal::FormatAspects::DEPTH) {
                Self::add_pass_texture_init_actions(
                    &at.stencil,
                    texture_memory_actions,
                    view,
                    &mut pending_discard_init_fixups,
                );
            } else {
                // This is the only place (anywhere in wgpu) where Stencil &
                // Depth init state can diverge.
                //
                // To safe us the overhead of tracking init state of texture
                // aspects everywhere, we're going to cheat a little bit in
                // order to keep the init state of both Stencil and Depth
                // aspects in sync. The expectation is that we hit this path
                // extremely rarely!
                //
                // Diverging LoadOp, i.e. Load + Clear:
                //
                // Record MemoryInitKind::NeedsInitializedMemory for the entire
                // surface, a bit wasteful on unit but no negative effect!
                //
                // Rationale: If the loaded channel is uninitialized it needs
                // clearing, the cleared channel doesn't care. (If everything is
                // already initialized nothing special happens)
                //
                // (possible minor optimization: Clear caused by
                // NeedsInitializedMemory should know that it doesn't need to
                // clear the aspect that was set to C)
                let need_init_beforehand =
                    at.depth.load_op == LoadOp::Load || at.stencil.load_op == LoadOp::Load;
                if need_init_beforehand {
                    pending_discard_init_fixups.extend(
                        texture_memory_actions.register_init_action(&TextureInitTrackerAction {
                            texture: view.parent.clone(),
                            range: TextureInitRange::from(view.selector.clone()),
                            kind: MemoryInitKind::NeedsInitializedMemory,
                        }),
                    );
                }

                // Diverging Store, i.e. Discard + Store:
                //
                // Immediately zero out channel that is set to discard after
                // we're done with the render pass. This allows us to set the
                // entire surface to MemoryInitKind::ImplicitlyInitialized (if
                // it isn't already set to NeedsInitializedMemory).
                //
                // (possible optimization: Delay and potentially drop this zeroing)
                if at.depth.store_op != at.stencil.store_op {
                    if !need_init_beforehand {
                        texture_memory_actions.register_implicit_init(
                            &view.parent,
                            TextureInitRange::from(view.selector.clone()),
                        );
                    }
                    divergent_discarded_depth_stencil_aspect = Some((
                        if at.depth.store_op == StoreOp::Discard {
                            wgt::TextureAspect::DepthOnly
                        } else {
                            wgt::TextureAspect::StencilOnly
                        },
                        view,
                    ));
                } else if at.depth.store_op == StoreOp::Discard {
                    // Both are discarded using the regular path.
                    discarded_surfaces.push(TextureSurfaceDiscard {
                        texture: view.parent.clone(),
                        mip_level: view.selector.mips.start,
                        layer: view.selector.layers.start,
                    });
                }
            }

            (is_depth_read_only, is_stencil_read_only) = at.depth_stencil_read_only(ds_aspects)?;

            let usage = if is_depth_read_only
                && is_stencil_read_only
                && device
                    .downlevel
                    .flags
                    .contains(wgt::DownlevelFlags::READ_ONLY_DEPTH_STENCIL)
            {
                hal::TextureUses::DEPTH_STENCIL_READ | hal::TextureUses::RESOURCE
            } else {
                hal::TextureUses::DEPTH_STENCIL_WRITE
            };
            render_attachments.push(view.to_render_attachment(usage));

            depth_stencil = Some(hal::DepthStencilAttachment {
                target: hal::Attachment {
                    view: view
                        .raw(snatch_guard)
                        .ok_or_else(|| RenderPassErrorInner::InvalidAttachment(view.info.id()))?,
                    usage,
                },
                depth_ops: at.depth.hal_ops(),
                stencil_ops: at.stencil.hal_ops(),
                clear_value: (at.depth.clear_value, at.stencil.clear_value),
            });
        }

        for (index, attachment) in color_attachments.iter().enumerate() {
            let at = if let Some(attachment) = attachment.as_ref() {
                attachment
            } else {
                colors.push(None);
                continue;
            };
            let color_view: &TextureView<A> = trackers
                .views
                .add_single(view_guard, at.view)
                .ok_or(RenderPassErrorInner::InvalidAttachment(at.view))?;
            check_multiview(color_view)?;
            add_view(
                color_view,
                AttachmentErrorLocation::Color {
                    index,
                    resolve: false,
                },
            )?;

            if !color_view
                .desc
                .aspects()
                .contains(hal::FormatAspects::COLOR)
            {
                return Err(RenderPassErrorInner::ColorAttachment(
                    ColorAttachmentError::InvalidFormat(color_view.desc.format),
                ));
            }

            Self::add_pass_texture_init_actions(
                &at.channel,
                texture_memory_actions,
                color_view,
                &mut pending_discard_init_fixups,
            );
            render_attachments
                .push(color_view.to_render_attachment(hal::TextureUses::COLOR_TARGET));

            let mut hal_resolve_target = None;
            if let Some(resolve_target) = at.resolve_target {
                let resolve_view: &TextureView<A> = trackers
                    .views
                    .add_single(view_guard, resolve_target)
                    .ok_or(RenderPassErrorInner::InvalidAttachment(resolve_target))?;

                check_multiview(resolve_view)?;

                let resolve_location = AttachmentErrorLocation::Color {
                    index,
                    resolve: true,
                };

                let render_extent = resolve_view.render_extent.map_err(|reason| {
                    RenderPassErrorInner::TextureViewIsNotRenderable {
                        location: resolve_location,
                        reason,
                    }
                })?;
                if color_view.render_extent.unwrap() != render_extent {
                    return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
                        expected_location: attachment_location,
                        expected_extent: extent.unwrap_or_default(),
                        actual_location: resolve_location,
                        actual_extent: render_extent,
                    });
                }
                if color_view.samples == 1 || resolve_view.samples != 1 {
                    return Err(RenderPassErrorInner::InvalidResolveSampleCounts {
                        location: resolve_location,
                        src: color_view.samples,
                        dst: resolve_view.samples,
                    });
                }
                if color_view.desc.format != resolve_view.desc.format {
                    return Err(RenderPassErrorInner::MismatchedResolveTextureFormat {
                        location: resolve_location,
                        src: color_view.desc.format,
                        dst: resolve_view.desc.format,
                    });
                }
                if !resolve_view
                    .format_features
                    .flags
                    .contains(wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE)
                {
                    return Err(RenderPassErrorInner::UnsupportedResolveTargetFormat {
                        location: resolve_location,
                        format: resolve_view.desc.format,
                    });
                }

                texture_memory_actions.register_implicit_init(
                    &resolve_view.parent,
                    TextureInitRange::from(resolve_view.selector.clone()),
                );
                render_attachments
                    .push(resolve_view.to_render_attachment(hal::TextureUses::COLOR_TARGET));

                hal_resolve_target = Some(hal::Attachment {
                    view: resolve_view.raw(snatch_guard).ok_or_else(|| {
                        RenderPassErrorInner::InvalidResolveTarget(resolve_view.info.id())
                    })?,
                    usage: hal::TextureUses::COLOR_TARGET,
                });
            }

            colors.push(Some(hal::ColorAttachment {
                target: hal::Attachment {
                    view: color_view.raw(snatch_guard).ok_or_else(|| {
                        RenderPassErrorInner::InvalidAttachment(color_view.info.id())
                    })?,
                    usage: hal::TextureUses::COLOR_TARGET,
                },
                resolve_target: hal_resolve_target,
                ops: at.channel.hal_ops(),
                clear_value: at.channel.clear_value,
            }));
        }

        let extent = extent.ok_or(RenderPassErrorInner::MissingAttachments)?;
        let multiview = detected_multiview.expect("Multiview was not detected, no attachments");

        let view_data = AttachmentData {
            colors: color_attachments
                .iter()
                .map(|at| at.as_ref().map(|at| view_guard.get(at.view).unwrap()))
                .collect(),
            resolves: color_attachments
                .iter()
                .filter_map(|at| match *at {
                    Some(RenderPassColorAttachment {
                        resolve_target: Some(resolve),
                        ..
                    }) => Some(view_guard.get(resolve).unwrap()),
                    _ => None,
                })
                .collect(),
            depth_stencil: depth_stencil_attachment.map(|at| view_guard.get(at.view).unwrap()),
        };

        let context = RenderPassContext {
            attachments: view_data.map(|view| view.desc.format),
            sample_count,
            multiview,
        };

        let timestamp_writes = if let Some(tw) = timestamp_writes {
            let query_set = trackers
                .query_sets
                .add_single(query_set_guard, tw.query_set)
                .ok_or(RenderPassErrorInner::InvalidQuerySet(tw.query_set))?;

            if let Some(index) = tw.beginning_of_pass_write_index {
                pending_query_resets.use_query_set(tw.query_set, query_set, index);
            }
            if let Some(index) = tw.end_of_pass_write_index {
                pending_query_resets.use_query_set(tw.query_set, query_set, index);
            }

            Some(hal::RenderPassTimestampWrites {
                query_set: query_set.raw.as_ref().unwrap(),
                beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
                end_of_pass_write_index: tw.end_of_pass_write_index,
            })
        } else {
            None
        };

        let occlusion_query_set = if let Some(occlusion_query_set) = occlusion_query_set {
            let query_set = trackers
                .query_sets
                .add_single(query_set_guard, occlusion_query_set)
                .ok_or(RenderPassErrorInner::InvalidQuerySet(occlusion_query_set))?;

            Some(query_set.raw.as_ref().unwrap())
        } else {
            None
        };

        let hal_desc = hal::RenderPassDescriptor {
            label: hal_label(label, device.instance_flags),
            extent,
            sample_count,
            color_attachments: &colors,
            depth_stencil_attachment: depth_stencil,
            multiview,
            timestamp_writes,
            occlusion_query_set,
        };
        unsafe {
            encoder.raw.begin_render_pass(&hal_desc);
        };

        Ok(Self {
            context,
            usage_scope: device.new_usage_scope(),
            render_attachments,
            is_depth_read_only,
            is_stencil_read_only,
            extent,
            _phantom: PhantomData,
            pending_discard_init_fixups,
            divergent_discarded_depth_stencil_aspect,
            multiview,
        })
    }

    fn finish(
        mut self,
        raw: &mut A::CommandEncoder,
        snatch_guard: &SnatchGuard,
    ) -> Result<(UsageScope<'d, A>, SurfacesInDiscardState<A>), RenderPassErrorInner> {
        profiling::scope!("RenderPassInfo::finish");
        unsafe {
            raw.end_render_pass();
        }

        for ra in self.render_attachments {
            let texture = &ra.texture;
            check_texture_usage(texture.desc.usage, TextureUsages::RENDER_ATTACHMENT)?;

            // the tracker set of the pass is always in "extend" mode
            unsafe {
                self.usage_scope
                    .textures
                    .merge_single(texture, Some(ra.selector.clone()), ra.usage)
                    .map_err(UsageConflict::from)?
            };
        }

        // If either only stencil or depth was discarded, we put in a special
        // clear pass to keep the init status of the aspects in sync. We do this
        // so we don't need to track init state for depth/stencil aspects
        // individually.
        //
        // Note that we don't go the usual route of "brute force" initializing
        // the texture when need arises here, since this path is actually
        // something a user may genuinely want (where as the other cases are
        // more seen along the lines as gracefully handling a user error).
        if let Some((aspect, view)) = self.divergent_discarded_depth_stencil_aspect {
            let (depth_ops, stencil_ops) = if aspect == wgt::TextureAspect::DepthOnly {
                (
                    hal::AttachmentOps::STORE,                            // clear depth
                    hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, // unchanged stencil
                )
            } else {
                (
                    hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, // unchanged stencil
                    hal::AttachmentOps::STORE,                            // clear depth
                )
            };
            let desc = hal::RenderPassDescriptor {
                label: Some("(wgpu internal) Zero init discarded depth/stencil aspect"),
                extent: view.render_extent.unwrap(),
                sample_count: view.samples,
                color_attachments: &[],
                depth_stencil_attachment: Some(hal::DepthStencilAttachment {
                    target: hal::Attachment {
                        view: view.raw(snatch_guard).ok_or_else(|| {
                            RenderPassErrorInner::InvalidAttachment(view.info.id())
                        })?,
                        usage: hal::TextureUses::DEPTH_STENCIL_WRITE,
                    },
                    depth_ops,
                    stencil_ops,
                    clear_value: (0.0, 0),
                }),
                multiview: self.multiview,
                timestamp_writes: None,
                occlusion_query_set: None,
            };
            unsafe {
                raw.begin_render_pass(&desc);
                raw.end_render_pass();
            }
        }

        Ok((self.usage_scope, self.pending_discard_init_fixups))
    }
}

// Common routines between render/compute

impl Global {
    pub fn command_encoder_run_render_pass<A: HalApi>(
        &self,
        encoder_id: id::CommandEncoderId,
        pass: &RenderPass,
    ) -> Result<(), RenderPassError> {
        self.command_encoder_run_render_pass_impl::<A>(
            encoder_id,
            pass.base.as_ref(),
            &pass.color_targets,
            pass.depth_stencil_target.as_ref(),
            pass.timestamp_writes.as_ref(),
            pass.occlusion_query_set_id,
        )
    }

    #[doc(hidden)]
    pub fn command_encoder_run_render_pass_impl<A: HalApi>(
        &self,
        encoder_id: id::CommandEncoderId,
        base: BasePassRef<RenderCommand>,
        color_attachments: &[Option<RenderPassColorAttachment>],
        depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>,
        timestamp_writes: Option<&RenderPassTimestampWrites>,
        occlusion_query_set_id: Option<id::QuerySetId>,
    ) -> Result<(), RenderPassError> {
        profiling::scope!(
            "CommandEncoder::run_render_pass {}",
            base.label.unwrap_or("")
        );

        let discard_hal_labels = self
            .instance
            .flags
            .contains(wgt::InstanceFlags::DISCARD_HAL_LABELS);
        let label = hal_label(base.label, self.instance.flags);

        let pass_scope = PassErrorScope::Pass(encoder_id);

        let hub = A::hub(self);

        let cmd_buf: Arc<CommandBuffer<A>> =
            CommandBuffer::get_encoder(hub, encoder_id).map_pass_err(pass_scope)?;
        let device = &cmd_buf.device;
        let snatch_guard = device.snatchable_lock.read();

        let (scope, pending_discard_init_fixups) = {
            let mut cmd_buf_data = cmd_buf.data.lock();
            let cmd_buf_data = cmd_buf_data.as_mut().unwrap();

            #[cfg(feature = "trace")]
            if let Some(ref mut list) = cmd_buf_data.commands {
                list.push(crate::device::trace::Command::RunRenderPass {
                    base: BasePass::from_ref(base),
                    target_colors: color_attachments.to_vec(),
                    target_depth_stencil: depth_stencil_attachment.cloned(),
                    timestamp_writes: timestamp_writes.cloned(),
                    occlusion_query_set_id,
                });
            }

            if !device.is_valid() {
                return Err(DeviceError::Lost).map_pass_err(pass_scope);
            }

            let encoder = &mut cmd_buf_data.encoder;
            let status = &mut cmd_buf_data.status;
            let tracker = &mut cmd_buf_data.trackers;
            let buffer_memory_init_actions = &mut cmd_buf_data.buffer_memory_init_actions;
            let texture_memory_actions = &mut cmd_buf_data.texture_memory_actions;
            let pending_query_resets = &mut cmd_buf_data.pending_query_resets;

            // We automatically keep extending command buffers over time, and because
            // we want to insert a command buffer _before_ what we're about to record,
            // we need to make sure to close the previous one.
            encoder.close().map_pass_err(pass_scope)?;
            // We will reset this to `Recording` if we succeed, acts as a fail-safe.
            *status = CommandEncoderStatus::Error;
            encoder.open_pass(label).map_pass_err(pass_scope)?;

            let bundle_guard = hub.render_bundles.read();
            let bind_group_guard = hub.bind_groups.read();
            let render_pipeline_guard = hub.render_pipelines.read();
            let query_set_guard = hub.query_sets.read();
            let buffer_guard = hub.buffers.read();
            let view_guard = hub.texture_views.read();

            log::trace!(
                "Encoding render pass begin in command buffer {:?}",
                encoder_id
            );

            let mut info = RenderPassInfo::start(
                device,
                label,
                color_attachments,
                depth_stencil_attachment,
                timestamp_writes,
                occlusion_query_set_id,
                encoder,
                tracker,
                texture_memory_actions,
                pending_query_resets,
                &*view_guard,
                &*query_set_guard,
                &snatch_guard,
            )
            .map_pass_err(pass_scope)?;

            let indices = &device.tracker_indices;
            tracker.buffers.set_size(indices.buffers.size());
            tracker.textures.set_size(indices.textures.size());
            tracker.views.set_size(indices.texture_views.size());
            tracker.bind_groups.set_size(indices.bind_groups.size());
            tracker
                .render_pipelines
                .set_size(indices.render_pipelines.size());
            tracker.bundles.set_size(indices.bundles.size());
            tracker.query_sets.set_size(indices.query_sets.size());

            let raw = &mut encoder.raw;

            let mut state = State {
                pipeline_flags: PipelineFlags::empty(),
                binder: Binder::new(),
                blend_constant: OptionalState::Unused,
                stencil_reference: 0,
                pipeline: None,
                index: IndexState::default(),
                vertex: VertexState::default(),
                debug_scope_depth: 0,
            };
            let mut temp_offsets = Vec::new();
            let mut dynamic_offset_count = 0;
            let mut string_offset = 0;
            let mut active_query = None;

            for command in base.commands {
                match *command {
                    RenderCommand::SetBindGroup {
                        index,
                        num_dynamic_offsets,
                        bind_group_id,
                    } => {
                        api_log!("RenderPass::set_bind_group {index} {bind_group_id:?}");

                        let scope = PassErrorScope::SetBindGroup(bind_group_id);
                        let max_bind_groups = device.limits.max_bind_groups;
                        if index >= max_bind_groups {
                            return Err(RenderCommandError::BindGroupIndexOutOfRange {
                                index,
                                max: max_bind_groups,
                            })
                            .map_pass_err(scope);
                        }

                        temp_offsets.clear();
                        temp_offsets.extend_from_slice(
                            &base.dynamic_offsets
                                [dynamic_offset_count..dynamic_offset_count + num_dynamic_offsets],
                        );
                        dynamic_offset_count += num_dynamic_offsets;

                        let bind_group = tracker
                            .bind_groups
                            .add_single(&*bind_group_guard, bind_group_id)
                            .ok_or(RenderCommandError::InvalidBindGroup(bind_group_id))
                            .map_pass_err(scope)?;

                        if bind_group.device.as_info().id() != device.as_info().id() {
                            return Err(DeviceError::WrongDevice).map_pass_err(scope);
                        }

                        bind_group
                            .validate_dynamic_bindings(index, &temp_offsets, &cmd_buf.limits)
                            .map_pass_err(scope)?;

                        // merge the resource tracker in
                        unsafe {
                            info.usage_scope
                                .merge_bind_group(&bind_group.used)
                                .map_pass_err(scope)?;
                        }
                        //Note: stateless trackers are not merged: the lifetime reference
                        // is held to the bind group itself.

                        buffer_memory_init_actions.extend(
                            bind_group.used_buffer_ranges.iter().filter_map(|action| {
                                action
                                    .buffer
                                    .initialization_status
                                    .read()
                                    .check_action(action)
                            }),
                        );
                        for action in bind_group.used_texture_ranges.iter() {
                            info.pending_discard_init_fixups
                                .extend(texture_memory_actions.register_init_action(action));
                        }

                        let pipeline_layout = state.binder.pipeline_layout.clone();
                        let entries =
                            state
                                .binder
                                .assign_group(index as usize, bind_group, &temp_offsets);
                        if !entries.is_empty() && pipeline_layout.is_some() {
                            let pipeline_layout = pipeline_layout.as_ref().unwrap().raw();
                            for (i, e) in entries.iter().enumerate() {
                                if let Some(group) = e.group.as_ref() {
                                    let raw_bg = group
                                        .raw(&snatch_guard)
                                        .ok_or(RenderPassErrorInner::InvalidBindGroup(i))
                                        .map_pass_err(scope)?;
                                    unsafe {
                                        raw.set_bind_group(
                                            pipeline_layout,
                                            index + i as u32,
                                            raw_bg,
                                            &e.dynamic_offsets,
                                        );
                                    }
                                }
                            }
                        }
                    }
                    RenderCommand::SetPipeline(pipeline_id) => {
                        api_log!("RenderPass::set_pipeline {pipeline_id:?}");

                        let scope = PassErrorScope::SetPipelineRender(pipeline_id);
                        state.pipeline = Some(pipeline_id);

                        let pipeline: &pipeline::RenderPipeline<A> = tracker
                            .render_pipelines
                            .add_single(&*render_pipeline_guard, pipeline_id)
                            .ok_or(RenderCommandError::InvalidPipeline(pipeline_id))
                            .map_pass_err(scope)?;

                        if pipeline.device.as_info().id() != device.as_info().id() {
                            return Err(DeviceError::WrongDevice).map_pass_err(scope);
                        }

                        info.context
                            .check_compatible(
                                &pipeline.pass_context,
                                RenderPassCompatibilityCheckType::RenderPipeline,
                            )
                            .map_err(RenderCommandError::IncompatiblePipelineTargets)
                            .map_pass_err(scope)?;

                        state.pipeline_flags = pipeline.flags;

                        if (pipeline.flags.contains(PipelineFlags::WRITES_DEPTH)
                            && info.is_depth_read_only)
                            || (pipeline.flags.contains(PipelineFlags::WRITES_STENCIL)
                                && info.is_stencil_read_only)
                        {
                            return Err(RenderCommandError::IncompatiblePipelineRods)
                                .map_pass_err(scope);
                        }

                        state
                            .blend_constant
                            .require(pipeline.flags.contains(PipelineFlags::BLEND_CONSTANT));

                        unsafe {
                            raw.set_render_pipeline(pipeline.raw());
                        }

                        if pipeline.flags.contains(PipelineFlags::STENCIL_REFERENCE) {
                            unsafe {
                                raw.set_stencil_reference(state.stencil_reference);
                            }
                        }

                        // Rebind resource
                        if state.binder.pipeline_layout.is_none()
                            || !state
                                .binder
                                .pipeline_layout
                                .as_ref()
                                .unwrap()
                                .is_equal(&pipeline.layout)
                        {
                            let (start_index, entries) = state.binder.change_pipeline_layout(
                                &pipeline.layout,
                                &pipeline.late_sized_buffer_groups,
                            );
                            if !entries.is_empty() {
                                for (i, e) in entries.iter().enumerate() {
                                    if let Some(group) = e.group.as_ref() {
                                        let raw_bg = group
                                            .raw(&snatch_guard)
                                            .ok_or(RenderPassErrorInner::InvalidBindGroup(i))
                                            .map_pass_err(scope)?;
                                        unsafe {
                                            raw.set_bind_group(
                                                pipeline.layout.raw(),
                                                start_index as u32 + i as u32,
                                                raw_bg,
                                                &e.dynamic_offsets,
                                            );
                                        }
                                    }
                                }
                            }

                            // Clear push constant ranges
                            let non_overlapping = super::bind::compute_nonoverlapping_ranges(
                                &pipeline.layout.push_constant_ranges,
                            );
                            for range in non_overlapping {
                                let offset = range.range.start;
                                let size_bytes = range.range.end - offset;
                                super::push_constant_clear(
                                    offset,
                                    size_bytes,
                                    |clear_offset, clear_data| unsafe {
                                        raw.set_push_constants(
                                            pipeline.layout.raw(),
                                            range.stages,
                                            clear_offset,
                                            clear_data,
                                        );
                                    },
                                );
                            }
                        }

                        state.index.pipeline_format = pipeline.strip_index_format;

                        let vertex_steps_len = pipeline.vertex_steps.len();
                        state.vertex.buffers_required = vertex_steps_len as u32;

                        // Initialize each `vertex.inputs[i].step` from
                        // `pipeline.vertex_steps[i]`.  Enlarge `vertex.inputs`
                        // as necessary to accommodate all slots in the
                        // pipeline. If `vertex.inputs` is longer, fill the
                        // extra entries with default `VertexStep`s.
                        while state.vertex.inputs.len() < vertex_steps_len {
                            state.vertex.inputs.push(VertexBufferState::EMPTY);
                        }

                        // This is worse as a `zip`, but it's close.
                        let mut steps = pipeline.vertex_steps.iter();
                        for input in state.vertex.inputs.iter_mut() {
                            input.step = steps.next().cloned().unwrap_or_default();
                        }

                        // Update vertex buffer limits.
                        state.vertex.update_limits();
                    }
                    RenderCommand::SetIndexBuffer {
                        buffer_id,
                        index_format,
                        offset,
                        size,
                    } => {
                        api_log!("RenderPass::set_index_buffer {buffer_id:?}");

                        let scope = PassErrorScope::SetIndexBuffer(buffer_id);
                        let buffer = info
                            .usage_scope
                            .buffers
                            .merge_single(&*buffer_guard, buffer_id, hal::BufferUses::INDEX)
                            .map_pass_err(scope)?;

                        if buffer.device.as_info().id() != device.as_info().id() {
                            return Err(DeviceError::WrongDevice).map_pass_err(scope);
                        }

                        check_buffer_usage(buffer_id, buffer.usage, BufferUsages::INDEX)
                            .map_pass_err(scope)?;
                        let buf_raw = buffer
                            .raw
                            .get(&snatch_guard)
                            .ok_or(RenderCommandError::DestroyedBuffer(buffer_id))
                            .map_pass_err(scope)?;

                        let end = match size {
                            Some(s) => offset + s.get(),
                            None => buffer.size,
                        };
                        state.index.bound_buffer_view = Some((buffer_id, offset..end));

                        state.index.format = Some(index_format);
                        state.index.update_limit();

                        buffer_memory_init_actions.extend(
                            buffer.initialization_status.read().create_action(
                                buffer,
                                offset..end,
                                MemoryInitKind::NeedsInitializedMemory,
                            ),
                        );

                        let bb = hal::BufferBinding {
                            buffer: buf_raw,
                            offset,
                            size,
                        };
                        unsafe {
                            raw.set_index_buffer(bb, index_format);
                        }
                    }
                    RenderCommand::SetVertexBuffer {
                        slot,
                        buffer_id,
                        offset,
                        size,
                    } => {
                        api_log!("RenderPass::set_vertex_buffer {slot} {buffer_id:?}");

                        let scope = PassErrorScope::SetVertexBuffer(buffer_id);
                        let buffer = info
                            .usage_scope
                            .buffers
                            .merge_single(&*buffer_guard, buffer_id, hal::BufferUses::VERTEX)
                            .map_pass_err(scope)?;

                        if buffer.device.as_info().id() != device.as_info().id() {
                            return Err(DeviceError::WrongDevice).map_pass_err(scope);
                        }

                        let max_vertex_buffers = device.limits.max_vertex_buffers;
                        if slot >= max_vertex_buffers {
                            return Err(RenderCommandError::VertexBufferIndexOutOfRange {
                                index: slot,
                                max: max_vertex_buffers,
                            })
                            .map_pass_err(scope);
                        }

                        check_buffer_usage(buffer_id, buffer.usage, BufferUsages::VERTEX)
                            .map_pass_err(scope)?;
                        let buf_raw = buffer
                            .raw
                            .get(&snatch_guard)
                            .ok_or(RenderCommandError::DestroyedBuffer(buffer_id))
                            .map_pass_err(scope)?;

                        let empty_slots =
                            (1 + slot as usize).saturating_sub(state.vertex.inputs.len());
                        state
                            .vertex
                            .inputs
                            .extend(iter::repeat(VertexBufferState::EMPTY).take(empty_slots));
                        let vertex_state = &mut state.vertex.inputs[slot as usize];
                        //TODO: where are we checking that the offset is in bound?
                        vertex_state.total_size = match size {
                            Some(s) => s.get(),
                            None => buffer.size - offset,
                        };
                        vertex_state.bound = true;

                        buffer_memory_init_actions.extend(
                            buffer.initialization_status.read().create_action(
                                buffer,
                                offset..(offset + vertex_state.total_size),
                                MemoryInitKind::NeedsInitializedMemory,
                            ),
                        );

                        let bb = hal::BufferBinding {
                            buffer: buf_raw,
                            offset,
                            size,
                        };
                        unsafe {
                            raw.set_vertex_buffer(slot, bb);
                        }
                        state.vertex.update_limits();
                    }
                    RenderCommand::SetBlendConstant(ref color) => {
                        api_log!("RenderPass::set_blend_constant");

                        state.blend_constant = OptionalState::Set;
                        let array = [
                            color.r as f32,
                            color.g as f32,
                            color.b as f32,
                            color.a as f32,
                        ];
                        unsafe {
                            raw.set_blend_constants(&array);
                        }
                    }
                    RenderCommand::SetStencilReference(value) => {
                        api_log!("RenderPass::set_stencil_reference {value}");

                        state.stencil_reference = value;
                        if state
                            .pipeline_flags
                            .contains(PipelineFlags::STENCIL_REFERENCE)
                        {
                            unsafe {
                                raw.set_stencil_reference(value);
                            }
                        }
                    }
                    RenderCommand::SetViewport {
                        ref rect,
                        depth_min,
                        depth_max,
                    } => {
                        api_log!("RenderPass::set_viewport {rect:?}");

                        let scope = PassErrorScope::SetViewport;
                        if rect.x < 0.0
                            || rect.y < 0.0
                            || rect.w <= 0.0
                            || rect.h <= 0.0
                            || rect.x + rect.w > info.extent.width as f32
                            || rect.y + rect.h > info.extent.height as f32
                        {
                            return Err(RenderCommandError::InvalidViewportRect(
                                *rect,
                                info.extent,
                            ))
                            .map_pass_err(scope);
                        }
                        if !(0.0..=1.0).contains(&depth_min) || !(0.0..=1.0).contains(&depth_max) {
                            return Err(RenderCommandError::InvalidViewportDepth(
                                depth_min, depth_max,
                            ))
                            .map_pass_err(scope);
                        }
                        let r = hal::Rect {
                            x: rect.x,
                            y: rect.y,
                            w: rect.w,
                            h: rect.h,
                        };
                        unsafe {
                            raw.set_viewport(&r, depth_min..depth_max);
                        }
                    }
                    RenderCommand::SetPushConstant {
                        stages,
                        offset,
                        size_bytes,
                        values_offset,
                    } => {
                        api_log!("RenderPass::set_push_constants");

                        let scope = PassErrorScope::SetPushConstant;
                        let values_offset = values_offset
                            .ok_or(RenderPassErrorInner::InvalidValuesOffset)
                            .map_pass_err(scope)?;

                        let end_offset_bytes = offset + size_bytes;
                        let values_end_offset =
                            (values_offset + size_bytes / wgt::PUSH_CONSTANT_ALIGNMENT) as usize;
                        let data_slice =
                            &base.push_constant_data[(values_offset as usize)..values_end_offset];

                        let pipeline_layout = state
                            .binder
                            .pipeline_layout
                            .as_ref()
                            .ok_or(DrawError::MissingPipeline)
                            .map_pass_err(scope)?;

                        pipeline_layout
                            .validate_push_constant_ranges(stages, offset, end_offset_bytes)
                            .map_err(RenderCommandError::from)
                            .map_pass_err(scope)?;

                        unsafe {
                            raw.set_push_constants(
                                pipeline_layout.raw(),
                                stages,
                                offset,
                                data_slice,
                            )
                        }
                    }
                    RenderCommand::SetScissor(ref rect) => {
                        api_log!("RenderPass::set_scissor_rect {rect:?}");

                        let scope = PassErrorScope::SetScissorRect;
                        if rect.x + rect.w > info.extent.width
                            || rect.y + rect.h > info.extent.height
                        {
                            return Err(RenderCommandError::InvalidScissorRect(*rect, info.extent))
                                .map_pass_err(scope);
                        }
                        let r = hal::Rect {
                            x: rect.x,
                            y: rect.y,
                            w: rect.w,
                            h: rect.h,
                        };
                        unsafe {
                            raw.set_scissor_rect(&r);
                        }
                    }
                    RenderCommand::Draw {
                        vertex_count,
                        instance_count,
                        first_vertex,
                        first_instance,
                    } => {
                        api_log!(
                            "RenderPass::draw {vertex_count} {instance_count} {first_vertex} {first_instance}"
                        );

                        let indexed = false;
                        let scope = PassErrorScope::Draw {
                            indexed,
                            indirect: false,
                            pipeline: state.pipeline,
                        };
                        state.is_ready(indexed).map_pass_err(scope)?;

                        let last_vertex = first_vertex as u64 + vertex_count as u64;
                        let vertex_limit = state.vertex.vertex_limit;
                        if last_vertex > vertex_limit {
                            return Err(DrawError::VertexBeyondLimit {
                                last_vertex,
                                vertex_limit,
                                slot: state.vertex.vertex_limit_slot,
                            })
                            .map_pass_err(scope);
                        }
                        let last_instance = first_instance as u64 + instance_count as u64;
                        let instance_limit = state.vertex.instance_limit;
                        if last_instance > instance_limit {
                            return Err(DrawError::InstanceBeyondLimit {
                                last_instance,
                                instance_limit,
                                slot: state.vertex.instance_limit_slot,
                            })
                            .map_pass_err(scope);
                        }

                        unsafe {
                            if instance_count > 0 && vertex_count > 0 {
                                raw.draw(
                                    first_vertex,
                                    vertex_count,
                                    first_instance,
                                    instance_count,
                                );
                            }
                        }
                    }
                    RenderCommand::DrawIndexed {
                        index_count,
                        instance_count,
                        first_index,
                        base_vertex,
                        first_instance,
                    } => {
                        api_log!("RenderPass::draw_indexed {index_count} {instance_count} {first_index} {base_vertex} {first_instance}");

                        let indexed = true;
                        let scope = PassErrorScope::Draw {
                            indexed,
                            indirect: false,
                            pipeline: state.pipeline,
                        };
                        state.is_ready(indexed).map_pass_err(scope)?;

                        let last_index = first_index as u64 + index_count as u64;
                        let index_limit = state.index.limit;
                        if last_index > index_limit {
                            return Err(DrawError::IndexBeyondLimit {
                                last_index,
                                index_limit,
                            })
                            .map_pass_err(scope);
                        }
                        let last_instance = first_instance as u64 + instance_count as u64;
                        let instance_limit = state.vertex.instance_limit;
                        if last_instance > instance_limit {
                            return Err(DrawError::InstanceBeyondLimit {
                                last_instance,
                                instance_limit,
                                slot: state.vertex.instance_limit_slot,
                            })
                            .map_pass_err(scope);
                        }

                        unsafe {
                            if instance_count > 0 && index_count > 0 {
                                raw.draw_indexed(
                                    first_index,
                                    index_count,
                                    base_vertex,
                                    first_instance,
                                    instance_count,
                                );
                            }
                        }
                    }
                    RenderCommand::MultiDrawIndirect {
                        buffer_id,
                        offset,
                        count,
                        indexed,
                    } => {
                        api_log!("RenderPass::draw_indirect (indexed:{indexed}) {buffer_id:?} {offset} {count:?}");

                        let scope = PassErrorScope::Draw {
                            indexed,
                            indirect: true,
                            pipeline: state.pipeline,
                        };
                        state.is_ready(indexed).map_pass_err(scope)?;

                        let stride = match indexed {
                            false => mem::size_of::<wgt::DrawIndirectArgs>(),
                            true => mem::size_of::<wgt::DrawIndexedIndirectArgs>(),
                        };

                        if count.is_some() {
                            device
                                .require_features(wgt::Features::MULTI_DRAW_INDIRECT)
                                .map_pass_err(scope)?;
                        }
                        device
                            .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)
                            .map_pass_err(scope)?;

                        let indirect_buffer = info
                            .usage_scope
                            .buffers
                            .merge_single(&*buffer_guard, buffer_id, hal::BufferUses::INDIRECT)
                            .map_pass_err(scope)?;
                        check_buffer_usage(
                            buffer_id,
                            indirect_buffer.usage,
                            BufferUsages::INDIRECT,
                        )
                        .map_pass_err(scope)?;
                        let indirect_raw = indirect_buffer
                            .raw
                            .get(&snatch_guard)
                            .ok_or(RenderCommandError::DestroyedBuffer(buffer_id))
                            .map_pass_err(scope)?;

                        let actual_count = count.map_or(1, |c| c.get());

                        let end_offset = offset + stride as u64 * actual_count as u64;
                        if end_offset > indirect_buffer.size {
                            return Err(RenderPassErrorInner::IndirectBufferOverrun {
                                count,
                                offset,
                                end_offset,
                                buffer_size: indirect_buffer.size,
                            })
                            .map_pass_err(scope);
                        }

                        buffer_memory_init_actions.extend(
                            indirect_buffer.initialization_status.read().create_action(
                                indirect_buffer,
                                offset..end_offset,
                                MemoryInitKind::NeedsInitializedMemory,
                            ),
                        );

                        match indexed {
                            false => unsafe {
                                raw.draw_indirect(indirect_raw, offset, actual_count);
                            },
                            true => unsafe {
                                raw.draw_indexed_indirect(indirect_raw, offset, actual_count);
                            },
                        }
                    }
                    RenderCommand::MultiDrawIndirectCount {
                        buffer_id,
                        offset,
                        count_buffer_id,
                        count_buffer_offset,
                        max_count,
                        indexed,
                    } => {
                        api_log!("RenderPass::multi_draw_indirect_count (indexed:{indexed}) {buffer_id:?} {offset} {count_buffer_id:?} {count_buffer_offset:?} {max_count:?}");

                        let scope = PassErrorScope::Draw {
                            indexed,
                            indirect: true,
                            pipeline: state.pipeline,
                        };
                        state.is_ready(indexed).map_pass_err(scope)?;

                        let stride = match indexed {
                            false => mem::size_of::<wgt::DrawIndirectArgs>(),
                            true => mem::size_of::<wgt::DrawIndexedIndirectArgs>(),
                        } as u64;

                        device
                            .require_features(wgt::Features::MULTI_DRAW_INDIRECT_COUNT)
                            .map_pass_err(scope)?;
                        device
                            .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)
                            .map_pass_err(scope)?;

                        let indirect_buffer = info
                            .usage_scope
                            .buffers
                            .merge_single(&*buffer_guard, buffer_id, hal::BufferUses::INDIRECT)
                            .map_pass_err(scope)?;
                        check_buffer_usage(
                            buffer_id,
                            indirect_buffer.usage,
                            BufferUsages::INDIRECT,
                        )
                        .map_pass_err(scope)?;
                        let indirect_raw = indirect_buffer
                            .raw
                            .get(&snatch_guard)
                            .ok_or(RenderCommandError::DestroyedBuffer(buffer_id))
                            .map_pass_err(scope)?;

                        let count_buffer = info
                            .usage_scope
                            .buffers
                            .merge_single(
                                &*buffer_guard,
                                count_buffer_id,
                                hal::BufferUses::INDIRECT,
                            )
                            .map_pass_err(scope)?;
                        check_buffer_usage(buffer_id, count_buffer.usage, BufferUsages::INDIRECT)
                            .map_pass_err(scope)?;
                        let count_raw = count_buffer
                            .raw
                            .get(&snatch_guard)
                            .ok_or(RenderCommandError::DestroyedBuffer(count_buffer_id))
                            .map_pass_err(scope)?;

                        let end_offset = offset + stride * max_count as u64;
                        if end_offset > indirect_buffer.size {
                            return Err(RenderPassErrorInner::IndirectBufferOverrun {
                                count: None,
                                offset,
                                end_offset,
                                buffer_size: indirect_buffer.size,
                            })
                            .map_pass_err(scope);
                        }
                        buffer_memory_init_actions.extend(
                            indirect_buffer.initialization_status.read().create_action(
                                indirect_buffer,
                                offset..end_offset,
                                MemoryInitKind::NeedsInitializedMemory,
                            ),
                        );

                        let begin_count_offset = count_buffer_offset;
                        let end_count_offset = count_buffer_offset + 4;
                        if end_count_offset > count_buffer.size {
                            return Err(RenderPassErrorInner::IndirectCountBufferOverrun {
                                begin_count_offset,
                                end_count_offset,
                                count_buffer_size: count_buffer.size,
                            })
                            .map_pass_err(scope);
                        }
                        buffer_memory_init_actions.extend(
                            count_buffer.initialization_status.read().create_action(
                                count_buffer,
                                count_buffer_offset..end_count_offset,
                                MemoryInitKind::NeedsInitializedMemory,
                            ),
                        );

                        match indexed {
                            false => unsafe {
                                raw.draw_indirect_count(
                                    indirect_raw,
                                    offset,
                                    count_raw,
                                    count_buffer_offset,
                                    max_count,
                                );
                            },
                            true => unsafe {
                                raw.draw_indexed_indirect_count(
                                    indirect_raw,
                                    offset,
                                    count_raw,
                                    count_buffer_offset,
                                    max_count,
                                );
                            },
                        }
                    }
                    RenderCommand::PushDebugGroup { color: _, len } => {
                        state.debug_scope_depth += 1;
                        if !discard_hal_labels {
                            let label = str::from_utf8(
                                &base.string_data[string_offset..string_offset + len],
                            )
                            .unwrap();

                            api_log!("RenderPass::push_debug_group {label:?}");
                            unsafe {
                                raw.begin_debug_marker(label);
                            }
                        }
                        string_offset += len;
                    }
                    RenderCommand::PopDebugGroup => {
                        api_log!("RenderPass::pop_debug_group");

                        let scope = PassErrorScope::PopDebugGroup;
                        if state.debug_scope_depth == 0 {
                            return Err(RenderPassErrorInner::InvalidPopDebugGroup)
                                .map_pass_err(scope);
                        }
                        state.debug_scope_depth -= 1;
                        if !discard_hal_labels {
                            unsafe {
                                raw.end_debug_marker();
                            }
                        }
                    }
                    RenderCommand::InsertDebugMarker { color: _, len } => {
                        if !discard_hal_labels {
                            let label = str::from_utf8(
                                &base.string_data[string_offset..string_offset + len],
                            )
                            .unwrap();
                            api_log!("RenderPass::insert_debug_marker {label:?}");
                            unsafe {
                                raw.insert_debug_marker(label);
                            }
                        }
                        string_offset += len;
                    }
                    RenderCommand::WriteTimestamp {
                        query_set_id,
                        query_index,
                    } => {
                        api_log!("RenderPass::write_timestamps {query_set_id:?} {query_index}");
                        let scope = PassErrorScope::WriteTimestamp;

                        device
                            .require_features(wgt::Features::TIMESTAMP_QUERY_INSIDE_PASSES)
                            .map_pass_err(scope)?;

                        let query_set = tracker
                            .query_sets
                            .add_single(&*query_set_guard, query_set_id)
                            .ok_or(RenderCommandError::InvalidQuerySet(query_set_id))
                            .map_pass_err(scope)?;

                        query_set
                            .validate_and_write_timestamp(
                                raw,
                                query_set_id,
                                query_index,
                                Some(&mut cmd_buf_data.pending_query_resets),
                            )
                            .map_pass_err(scope)?;
                    }
                    RenderCommand::BeginOcclusionQuery { query_index } => {
                        api_log!("RenderPass::begin_occlusion_query {query_index}");
                        let scope = PassErrorScope::BeginOcclusionQuery;

                        let query_set_id = occlusion_query_set_id
                            .ok_or(RenderPassErrorInner::MissingOcclusionQuerySet)
                            .map_pass_err(scope)?;

                        let query_set = tracker
                            .query_sets
                            .add_single(&*query_set_guard, query_set_id)
                            .ok_or(RenderCommandError::InvalidQuerySet(query_set_id))
                            .map_pass_err(scope)?;

                        query_set
                            .validate_and_begin_occlusion_query(
                                raw,
                                query_set_id,
                                query_index,
                                Some(&mut cmd_buf_data.pending_query_resets),
                                &mut active_query,
                            )
                            .map_pass_err(scope)?;
                    }
                    RenderCommand::EndOcclusionQuery => {
                        api_log!("RenderPass::end_occlusion_query");
                        let scope = PassErrorScope::EndOcclusionQuery;

                        end_occlusion_query(raw, &*query_set_guard, &mut active_query)
                            .map_pass_err(scope)?;
                    }
                    RenderCommand::BeginPipelineStatisticsQuery {
                        query_set_id,
                        query_index,
                    } => {
                        api_log!("RenderPass::begin_pipeline_statistics_query {query_set_id:?} {query_index}");
                        let scope = PassErrorScope::BeginPipelineStatisticsQuery;

                        let query_set = tracker
                            .query_sets
                            .add_single(&*query_set_guard, query_set_id)
                            .ok_or(RenderCommandError::InvalidQuerySet(query_set_id))
                            .map_pass_err(scope)?;

                        query_set
                            .validate_and_begin_pipeline_statistics_query(
                                raw,
                                query_set_id,
                                query_index,
                                Some(&mut cmd_buf_data.pending_query_resets),
                                &mut active_query,
                            )
                            .map_pass_err(scope)?;
                    }
                    RenderCommand::EndPipelineStatisticsQuery => {
                        api_log!("RenderPass::end_pipeline_statistics_query");
                        let scope = PassErrorScope::EndPipelineStatisticsQuery;

                        end_pipeline_statistics_query(raw, &*query_set_guard, &mut active_query)
                            .map_pass_err(scope)?;
                    }
                    RenderCommand::ExecuteBundle(bundle_id) => {
                        api_log!("RenderPass::execute_bundle {bundle_id:?}");
                        let scope = PassErrorScope::ExecuteBundle;
                        let bundle: &command::RenderBundle<A> = tracker
                            .bundles
                            .add_single(&*bundle_guard, bundle_id)
                            .ok_or(RenderCommandError::InvalidRenderBundle(bundle_id))
                            .map_pass_err(scope)?;

                        if bundle.device.as_info().id() != device.as_info().id() {
                            return Err(DeviceError::WrongDevice).map_pass_err(scope);
                        }

                        info.context
                            .check_compatible(
                                &bundle.context,
                                RenderPassCompatibilityCheckType::RenderBundle,
                            )
                            .map_err(RenderPassErrorInner::IncompatibleBundleTargets)
                            .map_pass_err(scope)?;

                        if (info.is_depth_read_only && !bundle.is_depth_read_only)
                            || (info.is_stencil_read_only && !bundle.is_stencil_read_only)
                        {
                            return Err(
                                RenderPassErrorInner::IncompatibleBundleReadOnlyDepthStencil {
                                    pass_depth: info.is_depth_read_only,
                                    pass_stencil: info.is_stencil_read_only,
                                    bundle_depth: bundle.is_depth_read_only,
                                    bundle_stencil: bundle.is_stencil_read_only,
                                },
                            )
                            .map_pass_err(scope);
                        }

                        buffer_memory_init_actions.extend(
                            bundle
                                .buffer_memory_init_actions
                                .iter()
                                .filter_map(|action| {
                                    action
                                        .buffer
                                        .initialization_status
                                        .read()
                                        .check_action(action)
                                }),
                        );
                        for action in bundle.texture_memory_init_actions.iter() {
                            info.pending_discard_init_fixups
                                .extend(texture_memory_actions.register_init_action(action));
                        }

                        unsafe { bundle.execute(raw, &snatch_guard) }
                            .map_err(|e| match e {
                                ExecutionError::DestroyedBuffer(id) => {
                                    RenderCommandError::DestroyedBuffer(id)
                                }
                                ExecutionError::InvalidBindGroup(id) => {
                                    RenderCommandError::InvalidBindGroup(id)
                                }
                                ExecutionError::Unimplemented(what) => {
                                    RenderCommandError::Unimplemented(what)
                                }
                            })
                            .map_pass_err(scope)?;

                        unsafe {
                            info.usage_scope
                                .merge_render_bundle(&bundle.used)
                                .map_pass_err(scope)?;
                            tracker
                                .add_from_render_bundle(&bundle.used)
                                .map_pass_err(scope)?;
                        };
                        state.reset_bundle();
                    }
                }
            }

            log::trace!("Merging renderpass into cmd_buf {:?}", encoder_id);
            let (trackers, pending_discard_init_fixups) =
                info.finish(raw, &snatch_guard).map_pass_err(pass_scope)?;

            encoder.close().map_pass_err(pass_scope)?;
            (trackers, pending_discard_init_fixups)
        };

        let cmd_buf = hub
            .command_buffers
            .get(encoder_id.into_command_buffer_id())
            .unwrap();
        let mut cmd_buf_data = cmd_buf.data.lock();
        let cmd_buf_data = cmd_buf_data.as_mut().unwrap();

        let query_set_guard = hub.query_sets.read();

        let encoder = &mut cmd_buf_data.encoder;
        let status = &mut cmd_buf_data.status;
        let tracker = &mut cmd_buf_data.trackers;

        {
            let transit = encoder.open().map_pass_err(pass_scope)?;

            fixup_discarded_surfaces(
                pending_discard_init_fixups.into_iter(),
                transit,
                &mut tracker.textures,
                &cmd_buf.device,
                &snatch_guard,
            );

            cmd_buf_data
                .pending_query_resets
                .reset_queries(
                    transit,
                    &query_set_guard,
                    cmd_buf.device.info.id().backend(),
                )
                .map_err(RenderCommandError::InvalidQuerySet)
                .map_pass_err(PassErrorScope::QueryReset)?;

            super::CommandBuffer::insert_barriers_from_scope(
                transit,
                tracker,
                &scope,
                &snatch_guard,
            );
        }

        *status = CommandEncoderStatus::Recording;
        encoder.close_and_swap().map_pass_err(pass_scope)?;

        Ok(())
    }
}

pub mod render_commands {
    use super::{
        super::{Rect, RenderCommand},
        RenderPass,
    };
    use crate::id;
    use std::{convert::TryInto, num::NonZeroU32};
    use wgt::{BufferAddress, BufferSize, Color, DynamicOffset, IndexFormat};

    /// # Safety
    ///
    /// This function is unsafe as there is no guarantee that the given pointer is
    /// valid for `offset_length` elements.
    pub fn wgpu_render_pass_set_bind_group(
        pass: &mut RenderPass,
        index: u32,
        bind_group_id: id::BindGroupId,
        offsets: &[DynamicOffset],
    ) {
        let redundant = pass.current_bind_groups.set_and_check_redundant(
            bind_group_id,
            index,
            &mut pass.base.dynamic_offsets,
            offsets,
        );

        if redundant {
            return;
        }

        pass.base.commands.push(RenderCommand::SetBindGroup {
            index,
            num_dynamic_offsets: offsets.len(),
            bind_group_id,
        });
    }

    pub fn wgpu_render_pass_set_pipeline(pass: &mut RenderPass, pipeline_id: id::RenderPipelineId) {
        if pass.current_pipeline.set_and_check_redundant(pipeline_id) {
            return;
        }

        pass.base
            .commands
            .push(RenderCommand::SetPipeline(pipeline_id));
    }

    pub fn wgpu_render_pass_set_vertex_buffer(
        pass: &mut RenderPass,
        slot: u32,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        size: Option<BufferSize>,
    ) {
        pass.base.commands.push(RenderCommand::SetVertexBuffer {
            slot,
            buffer_id,
            offset,
            size,
        });
    }

    pub fn wgpu_render_pass_set_index_buffer(
        pass: &mut RenderPass,
        buffer: id::BufferId,
        index_format: IndexFormat,
        offset: BufferAddress,
        size: Option<BufferSize>,
    ) {
        pass.set_index_buffer(buffer, index_format, offset, size);
    }

    pub fn wgpu_render_pass_set_blend_constant(pass: &mut RenderPass, color: &Color) {
        pass.base
            .commands
            .push(RenderCommand::SetBlendConstant(*color));
    }

    pub fn wgpu_render_pass_set_stencil_reference(pass: &mut RenderPass, value: u32) {
        pass.base
            .commands
            .push(RenderCommand::SetStencilReference(value));
    }

    pub fn wgpu_render_pass_set_viewport(
        pass: &mut RenderPass,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
        depth_min: f32,
        depth_max: f32,
    ) {
        pass.base.commands.push(RenderCommand::SetViewport {
            rect: Rect { x, y, w, h },
            depth_min,
            depth_max,
        });
    }

    pub fn wgpu_render_pass_set_scissor_rect(
        pass: &mut RenderPass,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) {
        pass.base
            .commands
            .push(RenderCommand::SetScissor(Rect { x, y, w, h }));
    }

    /// # Safety
    ///
    /// This function is unsafe as there is no guarantee that the given pointer is
    /// valid for `size_bytes` bytes.
    pub fn wgpu_render_pass_set_push_constants(
        pass: &mut RenderPass,
        stages: wgt::ShaderStages,
        offset: u32,
        data: &[u8],
    ) {
        assert_eq!(
            offset & (wgt::PUSH_CONSTANT_ALIGNMENT - 1),
            0,
            "Push constant offset must be aligned to 4 bytes."
        );
        assert_eq!(
            data.len() as u32 & (wgt::PUSH_CONSTANT_ALIGNMENT - 1),
            0,
            "Push constant size must be aligned to 4 bytes."
        );
        let value_offset = pass.base.push_constant_data.len().try_into().expect(
            "Ran out of push constant space. Don't set 4gb of push constants per RenderPass.",
        );

        pass.base.push_constant_data.extend(
            data.chunks_exact(wgt::PUSH_CONSTANT_ALIGNMENT as usize)
                .map(|arr| u32::from_ne_bytes([arr[0], arr[1], arr[2], arr[3]])),
        );

        pass.base.commands.push(RenderCommand::SetPushConstant {
            stages,
            offset,
            size_bytes: data.len() as u32,
            values_offset: Some(value_offset),
        });
    }

    pub fn wgpu_render_pass_draw(
        pass: &mut RenderPass,
        vertex_count: u32,
        instance_count: u32,
        first_vertex: u32,
        first_instance: u32,
    ) {
        pass.base.commands.push(RenderCommand::Draw {
            vertex_count,
            instance_count,
            first_vertex,
            first_instance,
        });
    }

    pub fn wgpu_render_pass_draw_indexed(
        pass: &mut RenderPass,
        index_count: u32,
        instance_count: u32,
        first_index: u32,
        base_vertex: i32,
        first_instance: u32,
    ) {
        pass.base.commands.push(RenderCommand::DrawIndexed {
            index_count,
            instance_count,
            first_index,
            base_vertex,
            first_instance,
        });
    }

    pub fn wgpu_render_pass_draw_indirect(
        pass: &mut RenderPass,
        buffer_id: id::BufferId,
        offset: BufferAddress,
    ) {
        pass.base.commands.push(RenderCommand::MultiDrawIndirect {
            buffer_id,
            offset,
            count: None,
            indexed: false,
        });
    }

    pub fn wgpu_render_pass_draw_indexed_indirect(
        pass: &mut RenderPass,
        buffer_id: id::BufferId,
        offset: BufferAddress,
    ) {
        pass.base.commands.push(RenderCommand::MultiDrawIndirect {
            buffer_id,
            offset,
            count: None,
            indexed: true,
        });
    }

    pub fn wgpu_render_pass_multi_draw_indirect(
        pass: &mut RenderPass,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        count: u32,
    ) {
        pass.base.commands.push(RenderCommand::MultiDrawIndirect {
            buffer_id,
            offset,
            count: NonZeroU32::new(count),
            indexed: false,
        });
    }

    pub fn wgpu_render_pass_multi_draw_indexed_indirect(
        pass: &mut RenderPass,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        count: u32,
    ) {
        pass.base.commands.push(RenderCommand::MultiDrawIndirect {
            buffer_id,
            offset,
            count: NonZeroU32::new(count),
            indexed: true,
        });
    }

    pub fn wgpu_render_pass_multi_draw_indirect_count(
        pass: &mut RenderPass,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        count_buffer_id: id::BufferId,
        count_buffer_offset: BufferAddress,
        max_count: u32,
    ) {
        pass.base
            .commands
            .push(RenderCommand::MultiDrawIndirectCount {
                buffer_id,
                offset,
                count_buffer_id,
                count_buffer_offset,
                max_count,
                indexed: false,
            });
    }

    pub fn wgpu_render_pass_multi_draw_indexed_indirect_count(
        pass: &mut RenderPass,
        buffer_id: id::BufferId,
        offset: BufferAddress,
        count_buffer_id: id::BufferId,
        count_buffer_offset: BufferAddress,
        max_count: u32,
    ) {
        pass.base
            .commands
            .push(RenderCommand::MultiDrawIndirectCount {
                buffer_id,
                offset,
                count_buffer_id,
                count_buffer_offset,
                max_count,
                indexed: true,
            });
    }

    pub fn wgpu_render_pass_push_debug_group(pass: &mut RenderPass, label: &str, color: u32) {
        let bytes = label.as_bytes();
        pass.base.string_data.extend_from_slice(bytes);

        pass.base.commands.push(RenderCommand::PushDebugGroup {
            color,
            len: bytes.len(),
        });
    }

    pub fn wgpu_render_pass_pop_debug_group(pass: &mut RenderPass) {
        pass.base.commands.push(RenderCommand::PopDebugGroup);
    }

    pub fn wgpu_render_pass_insert_debug_marker(pass: &mut RenderPass, label: &str, color: u32) {
        let bytes = label.as_bytes();
        pass.base.string_data.extend_from_slice(bytes);

        pass.base.commands.push(RenderCommand::InsertDebugMarker {
            color,
            len: bytes.len(),
        });
    }

    pub fn wgpu_render_pass_write_timestamp(
        pass: &mut RenderPass,
        query_set_id: id::QuerySetId,
        query_index: u32,
    ) {
        pass.base.commands.push(RenderCommand::WriteTimestamp {
            query_set_id,
            query_index,
        });
    }

    pub fn wgpu_render_pass_begin_occlusion_query(pass: &mut RenderPass, query_index: u32) {
        pass.base
            .commands
            .push(RenderCommand::BeginOcclusionQuery { query_index });
    }

    pub fn wgpu_render_pass_end_occlusion_query(pass: &mut RenderPass) {
        pass.base.commands.push(RenderCommand::EndOcclusionQuery);
    }

    pub fn wgpu_render_pass_begin_pipeline_statistics_query(
        pass: &mut RenderPass,
        query_set_id: id::QuerySetId,
        query_index: u32,
    ) {
        pass.base
            .commands
            .push(RenderCommand::BeginPipelineStatisticsQuery {
                query_set_id,
                query_index,
            });
    }

    pub fn wgpu_render_pass_end_pipeline_statistics_query(pass: &mut RenderPass) {
        pass.base
            .commands
            .push(RenderCommand::EndPipelineStatisticsQuery);
    }

    pub fn wgpu_render_pass_execute_bundles(
        pass: &mut RenderPass,
        render_bundle_ids: &[id::RenderBundleId],
    ) {
        for &bundle_id in render_bundle_ids {
            pass.base
                .commands
                .push(RenderCommand::ExecuteBundle(bundle_id));
        }
        pass.current_pipeline.reset();
        pass.current_bind_groups.reset();
    }
}