wgsl-rs 0.1.0-beta.4

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

// Note: Use `std::vec::Vec` explicitly throughout this module to avoid
// name collision with our `Vec<N, T>` vector type from vectors.rs.

use crate::std::{
    texture::{Sampler, SamplerComparison},
    vector::Vec4f,
};

/// CPU-side texture data for 1D textures.
///
/// Stores mip levels as a vector of 1D image strips.
#[derive(Clone)]
pub struct TextureData1D<T> {
    /// Mip levels, each containing width pixels.
    pub mips: std::vec::Vec<std::vec::Vec<[T; 4]>>,
}

impl<T: Default + Copy> TextureData1D<T> {
    /// Create a new 1D texture with the given width.
    pub fn new(width: u32) -> Self {
        let pixels: std::vec::Vec<[T; 4]> = (0..width)
            .map(|_| std::array::from_fn(|_| T::default()))
            .collect();
        Self { mips: vec![pixels] }
    }
}

impl<T> TextureData1D<T> {
    /// Get the width at the given mip level.
    pub fn width(&self, level: u32) -> u32 {
        self.mips
            .get(level as usize)
            .map(|m| m.len() as u32)
            .unwrap_or(0)
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.mips.len() as u32
    }

    /// Get a pixel at the given coordinate and mip level.
    pub fn get_pixel(&self, x: u32, level: u32) -> Option<&[T; 4]> {
        self.mips.get(level as usize)?.get(x as usize)
    }

    /// Set a pixel at the given coordinate and mip level.
    pub fn set_pixel(&mut self, x: u32, level: u32, value: [T; 4]) {
        if let Some(mip) = self.mips.get_mut(level as usize)
            && let Some(pixel) = mip.get_mut(x as usize)
        {
            *pixel = value;
        }
    }
}

/// CPU-side texture data for 2D textures.
#[derive(Clone)]
pub struct TextureData2D<T> {
    /// Mip levels, each containing a 2D image
    pub mips: std::vec::Vec<std::vec::Vec<std::vec::Vec<[T; 4]>>>,
}

impl<T: Default + Clone> TextureData2D<T> {
    /// Create a new 2D texture with the given dimensions.
    pub fn new(width: u32, height: u32) -> Self {
        let pixels: std::vec::Vec<std::vec::Vec<[T; 4]>> = (0..height)
            .map(|_| {
                (0..width)
                    .map(|_| std::array::from_fn(|_| T::default()))
                    .collect()
            })
            .collect();
        Self { mips: vec![pixels] }
    }
}

impl<T> TextureData2D<T> {
    /// Get the dimensions at the given mip level.
    pub fn dimensions(&self, level: u32) -> (u32, u32) {
        self.mips
            .get(level as usize)
            .map(|m| {
                let height = m.len() as u32;
                let width = m.first().map(|r| r.len() as u32).unwrap_or(0);
                (width, height)
            })
            .unwrap_or((0, 0))
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.mips.len() as u32
    }

    /// Get a pixel at the given coordinate and mip level.
    pub fn get_pixel(&self, x: u32, y: u32, level: u32) -> Option<&[T; 4]> {
        self.mips
            .get(level as usize)?
            .get(y as usize)?
            .get(x as usize)
    }

    /// Set a pixel at the given coordinate and mip level.
    pub fn set_pixel(&mut self, x: u32, y: u32, level: u32, value: [T; 4]) {
        if let Some(mip) = self.mips.get_mut(level as usize)
            && let Some(row) = mip.get_mut(y as usize)
            && let Some(pixel) = row.get_mut(x as usize)
        {
            *pixel = value;
        }
    }
}

impl<T: Default + Clone> TextureData2D<T> {
    /// Generate mip levels for the texture.
    pub fn generate_mips(&mut self)
    where
        T: Copy + Into<f32> + From<f32>,
    {
        // Start with base level dimensions
        let (mut w, mut h) = self.dimensions(0);

        while w > 1 || h > 1 {
            let new_w = Ord::max(w / 2, 1);
            let new_h = Ord::max(h / 2, 1);

            let prev_level = self.mips.len() - 1;
            let mut new_mip: std::vec::Vec<std::vec::Vec<[T; 4]>> = (0..new_h)
                .map(|_| {
                    (0..new_w)
                        .map(|_| std::array::from_fn(|_| T::default()))
                        .collect()
                })
                .collect();

            for y in 0..new_h {
                for x in 0..new_w {
                    // Sample 2x2 block from previous level
                    let mut sum = [0.0f32; 4];
                    let mut count = 0;

                    for dy in 0..2 {
                        for dx in 0..2 {
                            let sx = Ord::min(x * 2 + dx, w - 1);
                            let sy = Ord::min(y * 2 + dy, h - 1);
                            if let Some(pixel) = self.mips[prev_level]
                                .get(sy as usize)
                                .and_then(|row| row.get(sx as usize))
                            {
                                for c in 0..4 {
                                    sum[c] += pixel[c].into();
                                }
                                count += 1;
                            }
                        }
                    }

                    if count > 0 {
                        let avg = [
                            T::from(sum[0] / count as f32),
                            T::from(sum[1] / count as f32),
                            T::from(sum[2] / count as f32),
                            T::from(sum[3] / count as f32),
                        ];
                        new_mip[y as usize][x as usize] = avg;
                    }
                }
            }

            self.mips.push(new_mip);
            w = new_w;
            h = new_h;
        }
    }
}

/// CPU-side texture data for 2D array textures.
#[derive(Clone)]
pub struct TextureData2DArray<T> {
    /// Array of 2D textures
    pub layers: std::vec::Vec<TextureData2D<T>>,
}

impl<T: Default + Copy> TextureData2DArray<T> {
    /// Create a new 2D array texture.
    pub fn new(width: u32, height: u32, layers: u32) -> Self {
        Self {
            layers: (0..layers)
                .map(|_| TextureData2D::new(width, height))
                .collect(),
        }
    }
}

impl<T> TextureData2DArray<T> {
    /// Get the number of array layers.
    pub fn num_layers(&self) -> u32 {
        self.layers.len() as u32
    }

    /// Get the dimensions at the given mip level.
    pub fn dimensions(&self, level: u32) -> (u32, u32) {
        self.layers
            .first()
            .map(|l| l.dimensions(level))
            .unwrap_or((0, 0))
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.layers.first().map(|l| l.num_levels()).unwrap_or(0)
    }
}

/// CPU-side texture data for 3D textures.
#[derive(Clone)]
pub struct TextureData3D<T> {
    /// Mip levels, each containing a 3D volume
    pub mips: std::vec::Vec<std::vec::Vec<std::vec::Vec<std::vec::Vec<[T; 4]>>>>,
}

impl<T: Default + Copy> TextureData3D<T> {
    /// Create a new 3D texture with the given dimensions.
    pub fn new(width: u32, height: u32, depth: u32) -> Self {
        let volume: std::vec::Vec<std::vec::Vec<std::vec::Vec<[T; 4]>>> = (0..depth)
            .map(|_| {
                (0..height)
                    .map(|_| {
                        (0..width)
                            .map(|_| std::array::from_fn(|_| T::default()))
                            .collect()
                    })
                    .collect()
            })
            .collect();
        Self { mips: vec![volume] }
    }
}

impl<T> TextureData3D<T> {
    /// Get the dimensions at the given mip level.
    pub fn dimensions(&self, level: u32) -> (u32, u32, u32) {
        self.mips
            .get(level as usize)
            .map(|m| {
                let depth = m.len() as u32;
                let height = m.first().map(|s| s.len() as u32).unwrap_or(0);
                let width = m
                    .first()
                    .and_then(|s| s.first())
                    .map(|r| r.len() as u32)
                    .unwrap_or(0);
                (width, height, depth)
            })
            .unwrap_or((0, 0, 0))
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.mips.len() as u32
    }

    /// Get a pixel at the given coordinate and mip level.
    pub fn get_pixel(&self, x: u32, y: u32, z: u32, level: u32) -> Option<&[T; 4]> {
        self.mips
            .get(level as usize)?
            .get(z as usize)?
            .get(y as usize)?
            .get(x as usize)
    }

    /// Set a pixel at the given coordinate and mip level.
    pub fn set_pixel(&mut self, x: u32, y: u32, z: u32, level: u32, value: [T; 4]) {
        if let Some(mip) = self.mips.get_mut(level as usize)
            && let Some(slice) = mip.get_mut(z as usize)
            && let Some(row) = slice.get_mut(y as usize)
            && let Some(pixel) = row.get_mut(x as usize)
        {
            *pixel = value;
        }
    }
}

/// CPU-side texture data for cube textures.
///
/// A cube texture has 6 faces: +X, -X, +Y, -Y, +Z, -Z
#[derive(Clone)]
pub struct TextureDataCube<T> {
    /// The 6 faces of the cube, each is a 2D texture
    pub faces: [TextureData2D<T>; 6],
}

impl<T: Default + Copy> TextureDataCube<T> {
    /// Create a new cube texture with the given face size.
    pub fn new(size: u32) -> Self {
        Self {
            faces: std::array::from_fn(|_| TextureData2D::new(size, size)),
        }
    }
}

impl<T> TextureDataCube<T> {
    /// Get the dimensions (face width/height) at the given mip level.
    pub fn dimensions(&self, level: u32) -> (u32, u32) {
        self.faces[0].dimensions(level)
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.faces[0].num_levels()
    }
}

/// CPU-side texture data for cube array textures.
#[derive(Clone)]
pub struct TextureDataCubeArray<T> {
    /// Array of cube textures
    pub cubes: std::vec::Vec<TextureDataCube<T>>,
}

impl<T: Default + Copy> TextureDataCubeArray<T> {
    /// Create a new cube array texture.
    pub fn new(size: u32, layers: u32) -> Self {
        Self {
            cubes: (0..layers).map(|_| TextureDataCube::new(size)).collect(),
        }
    }
}

impl<T> TextureDataCubeArray<T> {
    /// Get the number of array layers.
    pub fn num_layers(&self) -> u32 {
        self.cubes.len() as u32
    }

    /// Get the dimensions at the given mip level.
    pub fn dimensions(&self, level: u32) -> (u32, u32) {
        self.cubes
            .first()
            .map(|c| c.dimensions(level))
            .unwrap_or((0, 0))
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.cubes.first().map(|c| c.num_levels()).unwrap_or(0)
    }
}

/// CPU-side texture data for multisampled 2D textures.
#[derive(Clone)]
pub struct TextureDataMultisampled2D<T> {
    /// Width of the texture
    pub width: u32,
    /// Height of the texture
    pub height: u32,
    /// Number of samples per pixel
    pub sample_count: u32,
    /// Pixel data: `[y][x][sample]`
    pub samples: std::vec::Vec<std::vec::Vec<std::vec::Vec<[T; 4]>>>,
}

impl<T: Default + Clone> TextureDataMultisampled2D<T> {
    /// Create a new multisampled 2D texture.
    pub fn new(width: u32, height: u32, sample_count: u32) -> Self {
        let samples: std::vec::Vec<std::vec::Vec<std::vec::Vec<[T; 4]>>> = (0..height)
            .map(|_| {
                (0..width)
                    .map(|_| {
                        (0..sample_count)
                            .map(|_| std::array::from_fn(|_| T::default()))
                            .collect()
                    })
                    .collect()
            })
            .collect();
        Self {
            width,
            height,
            sample_count,
            samples,
        }
    }
}

impl<T> TextureDataMultisampled2D<T> {
    /// Get the dimensions.
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Get the number of samples.
    pub fn num_samples(&self) -> u32 {
        self.sample_count
    }

    /// Get a sample at the given coordinate.
    pub fn get_sample(&self, x: u32, y: u32, sample: u32) -> Option<&[T; 4]> {
        self.samples
            .get(y as usize)?
            .get(x as usize)?
            .get(sample as usize)
    }
}

/// CPU-side depth texture data for 2D depth textures.
#[derive(Clone)]
pub struct TextureDataDepth2D {
    /// Mip levels
    pub mips: std::vec::Vec<std::vec::Vec<std::vec::Vec<f32>>>,
}

impl TextureDataDepth2D {
    /// Create a new 2D depth texture.
    pub fn new(width: u32, height: u32) -> Self {
        let row = vec![0.0f32; width as usize];
        let pixels = vec![row; height as usize];
        Self { mips: vec![pixels] }
    }

    /// Get the dimensions at the given mip level.
    pub fn dimensions(&self, level: u32) -> (u32, u32) {
        self.mips
            .get(level as usize)
            .map(|m| {
                let height = m.len() as u32;
                let width = m.first().map(|r| r.len() as u32).unwrap_or(0);
                (width, height)
            })
            .unwrap_or((0, 0))
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.mips.len() as u32
    }

    /// Get a depth value at the given coordinate and mip level.
    pub fn get_depth(&self, x: u32, y: u32, level: u32) -> Option<f32> {
        self.mips
            .get(level as usize)?
            .get(y as usize)?
            .get(x as usize)
            .copied()
    }
}

/// CPU-side depth texture data for 2D depth array textures.
#[derive(Clone)]
pub struct TextureDataDepth2DArray {
    /// Array of depth textures
    pub layers: std::vec::Vec<TextureDataDepth2D>,
}

impl TextureDataDepth2DArray {
    /// Create a new 2D depth array texture.
    pub fn new(width: u32, height: u32, layers: u32) -> Self {
        Self {
            layers: (0..layers)
                .map(|_| TextureDataDepth2D::new(width, height))
                .collect(),
        }
    }

    /// Get the number of array layers.
    pub fn num_layers(&self) -> u32 {
        self.layers.len() as u32
    }

    /// Get the dimensions at the given mip level.
    pub fn dimensions(&self, level: u32) -> (u32, u32) {
        self.layers
            .first()
            .map(|l| l.dimensions(level))
            .unwrap_or((0, 0))
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.layers.first().map(|l| l.num_levels()).unwrap_or(0)
    }
}

/// CPU-side depth texture data for cube depth textures.
#[derive(Clone)]
pub struct TextureDataDepthCube {
    /// The 6 faces of the cube
    pub faces: [TextureDataDepth2D; 6],
}

impl TextureDataDepthCube {
    /// Create a new cube depth texture.
    pub fn new(size: u32) -> Self {
        Self {
            faces: std::array::from_fn(|_| TextureDataDepth2D::new(size, size)),
        }
    }

    /// Get the dimensions at the given mip level.
    pub fn dimensions(&self, level: u32) -> (u32, u32) {
        self.faces[0].dimensions(level)
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.faces[0].num_levels()
    }
}

/// CPU-side depth texture data for cube array depth textures.
#[derive(Clone)]
pub struct TextureDataDepthCubeArray {
    /// Array of cube depth textures
    pub cubes: std::vec::Vec<TextureDataDepthCube>,
}

impl TextureDataDepthCubeArray {
    /// Create a new cube array depth texture.
    pub fn new(size: u32, layers: u32) -> Self {
        Self {
            cubes: (0..layers)
                .map(|_| TextureDataDepthCube::new(size))
                .collect(),
        }
    }

    /// Get the number of array layers.
    pub fn num_layers(&self) -> u32 {
        self.cubes.len() as u32
    }

    /// Get the dimensions at the given mip level.
    pub fn dimensions(&self, level: u32) -> (u32, u32) {
        self.cubes
            .first()
            .map(|c| c.dimensions(level))
            .unwrap_or((0, 0))
    }

    /// Get the number of mip levels.
    pub fn num_levels(&self) -> u32 {
        self.cubes.first().map(|c| c.num_levels()).unwrap_or(0)
    }
}

/// CPU-side multisampled depth texture data.
#[derive(Clone)]
pub struct TextureDataDepthMultisampled2D {
    /// Width of the texture
    pub width: u32,
    /// Height of the texture
    pub height: u32,
    /// Number of samples per pixel
    pub sample_count: u32,
    /// Depth samples: `[y][x][sample]`
    pub samples: std::vec::Vec<std::vec::Vec<std::vec::Vec<f32>>>,
}

impl TextureDataDepthMultisampled2D {
    /// Create a new multisampled 2D depth texture.
    pub fn new(width: u32, height: u32, sample_count: u32) -> Self {
        let samples_per_pixel = vec![0.0f32; sample_count as usize];
        let row = vec![samples_per_pixel; width as usize];
        let pixels = vec![row; height as usize];
        Self {
            width,
            height,
            sample_count,
            samples: pixels,
        }
    }

    /// Get the dimensions.
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Get the number of samples.
    pub fn num_samples(&self) -> u32 {
        self.sample_count
    }
}

/// Filter mode for texture sampling.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FilterMode {
    /// Nearest-neighbor filtering (point sampling)
    #[default]
    Nearest,
    /// Linear filtering (bilinear/trilinear interpolation)
    Linear,
}

/// Address mode for texture coordinate wrapping.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AddressMode {
    /// Clamp to edge - coordinates outside [0, 1] are clamped
    #[default]
    ClampToEdge,
    /// Repeat - coordinates wrap around
    Repeat,
    /// Mirror repeat - coordinates mirror at boundaries
    MirrorRepeat,
}

/// CPU-side sampler state.
#[derive(Clone, Debug)]
pub struct SamplerState {
    /// Magnification filter
    pub mag_filter: FilterMode,
    /// Minification filter
    pub min_filter: FilterMode,
    /// Mipmap filter
    pub mipmap_filter: FilterMode,
    /// Address mode for U coordinate
    pub address_mode_u: AddressMode,
    /// Address mode for V coordinate
    pub address_mode_v: AddressMode,
    /// Address mode for W coordinate
    pub address_mode_w: AddressMode,
    /// LOD min clamp
    pub lod_min_clamp: f32,
    /// LOD max clamp
    pub lod_max_clamp: f32,
}

impl Default for SamplerState {
    fn default() -> Self {
        Self {
            mag_filter: FilterMode::Nearest,
            min_filter: FilterMode::Nearest,
            mipmap_filter: FilterMode::Nearest,
            address_mode_u: AddressMode::ClampToEdge,
            address_mode_v: AddressMode::ClampToEdge,
            address_mode_w: AddressMode::ClampToEdge,
            lod_min_clamp: 0.0,
            lod_max_clamp: 1000.0,
        }
    }
}

impl SamplerState {
    /// Create a new sampler state with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a sampler state with linear filtering.
    pub fn linear() -> Self {
        Self {
            mag_filter: FilterMode::Linear,
            min_filter: FilterMode::Linear,
            mipmap_filter: FilterMode::Linear,
            ..Default::default()
        }
    }

    /// Apply address mode to a coordinate.
    pub fn apply_address_mode(mode: AddressMode, coord: f32) -> f32 {
        match mode {
            AddressMode::ClampToEdge => coord.clamp(0.0, 1.0),
            AddressMode::Repeat => coord.rem_euclid(1.0),
            AddressMode::MirrorRepeat => {
                let t = coord.rem_euclid(2.0);
                if t > 1.0 { 2.0 - t } else { t }
            }
        }
    }
}

/// Comparison sampler state.
#[derive(Clone, Debug)]
pub struct SamplerComparisonState {
    /// Base sampler state
    pub sampler: SamplerState,
    /// Comparison function
    pub compare: CompareFunction,
}

/// Comparison function for depth testing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CompareFunction {
    /// Never pass
    Never,
    /// Pass if less than
    Less,
    /// Pass if equal
    Equal,
    /// Pass if less than or equal
    #[default]
    LessEqual,
    /// Pass if greater than
    Greater,
    /// Pass if not equal
    NotEqual,
    /// Pass if greater than or equal
    GreaterEqual,
    /// Always pass
    Always,
}

impl CompareFunction {
    /// Evaluate the comparison function per WebGPU spec semantics.
    ///
    /// The `reference` (depth_ref, the "provided value") is compared against
    /// the `sample` (fetched texel, the "sampled value"). Per the WebGPU spec,
    /// `Less` passes when `reference < sample`, etc.
    ///
    /// See <https://www.w3.org/TR/webgpu/#enumdef-gpucomparefunction>.
    pub fn compare(self, sample: f32, reference: f32) -> f32 {
        let result = match self {
            CompareFunction::Never => false,
            CompareFunction::Less => reference < sample,
            CompareFunction::Equal => (sample - reference).abs() < f32::EPSILON,
            CompareFunction::LessEqual => reference <= sample,
            CompareFunction::Greater => reference > sample,
            CompareFunction::NotEqual => (sample - reference).abs() >= f32::EPSILON,
            CompareFunction::GreaterEqual => reference >= sample,
            CompareFunction::Always => true,
        };
        if result { 1.0 } else { 0.0 }
    }
}

impl Default for SamplerComparisonState {
    fn default() -> Self {
        Self {
            sampler: SamplerState::default(),
            compare: CompareFunction::LessEqual,
        }
    }
}

/// Trait for textures that support `textureDimensions`.
pub trait TextureDimensionsQuery {
    /// The output type for dimensions (u32, Vec2u, or Vec3u)
    type Output;

    /// Get the dimensions at the given mip level.
    fn query_dimensions(&self, level: u32) -> Self::Output;
}

/// Trait for textures that support `textureNumLayers`.
pub trait TextureNumLayersQuery {
    /// Get the number of array layers.
    fn query_num_layers(&self) -> u32;
}

/// Trait for textures that support `textureNumLevels`.
pub trait TextureNumLevelsQuery {
    /// Get the number of mip levels.
    fn query_num_levels(&self) -> u32;
}

/// Trait for textures that support `textureNumSamples`.
pub trait TextureNumSamplesQuery {
    /// Get the number of samples.
    fn query_num_samples(&self) -> u32;
}

/// Trait for textures that support `textureLoad`.
pub trait TextureLoad<Coords, Level> {
    /// The output type (`Vec4<T>` for sampled textures, f32 for depth)
    type Output;

    /// Load a texel at the given coordinates and mip level.
    fn load(&self, coords: Coords, level: Level) -> Self::Output;
}

/// Trait for multisampled textures that support `textureLoad` with sample
/// index.
pub trait TextureLoadMultisampled<Coords, SampleIndex> {
    /// The output type
    type Output;

    /// Load a sample at the given coordinates and sample index.
    fn load_multisampled(&self, coords: Coords, sample_index: SampleIndex) -> Self::Output;
}

/// Trait for array textures that support `textureLoad` with array index.
pub trait TextureLoadArray<Coords, ArrayIndex, Level> {
    /// The output type
    type Output;

    /// Load a texel at the given coordinates, array index, and mip level.
    fn load_array(&self, coords: Coords, array_index: ArrayIndex, level: Level) -> Self::Output;
}

/// Trait for textures that support `textureSample`.
pub trait TextureSample<Coords> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates.
    fn sample(&self, sampler: &Sampler, coords: Coords) -> Self::Output;
}

/// Trait for textures that support `textureSample` with offset.
pub trait TextureSampleOffset<Coords, Offset> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates with offset.
    fn sample_offset(&self, sampler: &Sampler, coords: Coords, offset: Offset) -> Self::Output;
}

/// Trait for array textures that support `textureSample` with array index.
pub trait TextureSampleArray<Coords, ArrayIndex> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates and array index.
    fn sample_array(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
    ) -> Self::Output;
}

/// Trait for textures that support `textureSampleLevel`.
///
/// Per the WGSL spec, the `level` parameter must be `f32` for non-depth
/// sampled textures; only depth textures accept `i32`/`u32` levels.
pub trait TextureSampleLevel<Coords, Level> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates and explicit LOD.
    fn sample_level(&self, sampler: &Sampler, coords: Coords, level: Level) -> Self::Output;
}

/// Trait for textures that support `textureSampleBias`.
pub trait TextureSampleBias<Coords, Bias> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates with LOD bias.
    fn sample_bias(&self, sampler: &Sampler, coords: Coords, bias: Bias) -> Self::Output;
}

/// Trait for textures that support `textureSampleGrad`.
pub trait TextureSampleGrad<Coords, Ddx, Ddy> {
    /// The output type
    type Output;

    /// Sample the texture with explicit gradients.
    fn sample_grad(&self, sampler: &Sampler, coords: Coords, ddx: Ddx, ddy: Ddy) -> Self::Output;
}

/// Trait for textures that support `textureSampleCompare`.
pub trait TextureSampleCompare<Coords, DepthRef> {
    /// Sample the depth texture with comparison.
    fn sample_compare(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        depth_ref: DepthRef,
    ) -> f32;
}

/// Trait for textures that support `textureSampleCompareLevel`.
///
/// Per the WGSL spec, `textureSampleCompareLevel` always samples at mip level
/// 0. There is no level parameter.
pub trait TextureSampleCompareLevel<Coords, DepthRef> {
    /// Sample the depth texture with comparison at mip level 0.
    fn sample_compare_level(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        depth_ref: DepthRef,
    ) -> f32;
}

/// Trait for textures that support `textureSampleBaseClampToEdge`.
///
/// Samples a texture at mip level 0 with coordinates clamped to
/// `[0.5/dim, 1.0 - 0.5/dim]` to prevent edge wrapping artifacts.
pub trait TextureSampleBaseClampToEdge<Coords> {
    /// The output type
    type Output;

    /// Sample the texture at base level with coordinates clamped to the edge.
    fn sample_base_clamp_to_edge(&self, sampler: &Sampler, coords: Coords) -> Self::Output;
}

/// Trait for textures that support `textureGather`.
pub trait TextureGather<Coords> {
    /// The output type
    type Output;

    /// Gather one component from 4 texels.
    fn gather(&self, component: u32, sampler: &Sampler, coords: Coords) -> Self::Output;
}

/// Trait for depth textures that support `textureGather` (no component
/// parameter).
pub trait TextureGatherDepth<Coords> {
    /// Gather depth values from 4 texels.
    fn gather_depth(&self, sampler: &Sampler, coords: Coords) -> Vec4f;
}

/// Trait for textures that support `textureGatherCompare`.
pub trait TextureGatherCompare<Coords, DepthRef> {
    /// Gather depth values with comparison from 4 texels.
    fn gather_compare(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        depth_ref: DepthRef,
    ) -> Vec4f;
}

/// Trait for array textures that support `textureSample` with array index and
/// offset.
pub trait TextureSampleArrayOffset<Coords, ArrayIndex, Offset> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates, array index, and offset.
    fn sample_array_offset(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
        offset: Offset,
    ) -> Self::Output;
}

/// Trait for textures that support `textureSampleLevel` with offset.
pub trait TextureSampleLevelOffset<Coords, Level, Offset> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates and explicit LOD with
    /// offset.
    fn sample_level_offset(
        &self,
        sampler: &Sampler,
        coords: Coords,
        level: Level,
        offset: Offset,
    ) -> Self::Output;
}

/// Trait for array textures that support `textureSampleLevel` with array index.
pub trait TextureSampleLevelArray<Coords, ArrayIndex, Level> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates, array index, and explicit
    /// LOD.
    fn sample_level_array(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
        level: Level,
    ) -> Self::Output;
}

/// Trait for array textures that support `textureSampleLevel` with array index
/// and offset.
pub trait TextureSampleLevelArrayOffset<Coords, ArrayIndex, Level, Offset> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates, array index, explicit LOD,
    /// and offset.
    fn sample_level_array_offset(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
        level: Level,
        offset: Offset,
    ) -> Self::Output;
}

/// Trait for textures that support `textureSampleBias` with offset.
pub trait TextureSampleBiasOffset<Coords, Bias, Offset> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates with LOD bias and offset.
    fn sample_bias_offset(
        &self,
        sampler: &Sampler,
        coords: Coords,
        bias: Bias,
        offset: Offset,
    ) -> Self::Output;
}

/// Trait for array textures that support `textureSampleBias` with array index.
pub trait TextureSampleBiasArray<Coords, ArrayIndex, Bias> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates, array index, with LOD bias.
    fn sample_bias_array(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
        bias: Bias,
    ) -> Self::Output;
}

/// Trait for array textures that support `textureSampleBias` with array index
/// and offset.
pub trait TextureSampleBiasArrayOffset<Coords, ArrayIndex, Bias, Offset> {
    /// The output type
    type Output;

    /// Sample the texture at the given coordinates, array index, LOD bias, and
    /// offset.
    fn sample_bias_array_offset(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
        bias: Bias,
        offset: Offset,
    ) -> Self::Output;
}

/// Trait for textures that support `textureSampleGrad` with offset.
pub trait TextureSampleGradOffset<Coords, Ddx, Ddy, Offset> {
    /// The output type
    type Output;

    /// Sample the texture with explicit gradients and offset.
    fn sample_grad_offset(
        &self,
        sampler: &Sampler,
        coords: Coords,
        ddx: Ddx,
        ddy: Ddy,
        offset: Offset,
    ) -> Self::Output;
}

/// Trait for array textures that support `textureSampleGrad` with array index.
pub trait TextureSampleGradArray<Coords, ArrayIndex, Ddx, Ddy> {
    /// The output type
    type Output;

    /// Sample the texture with explicit gradients and array index.
    fn sample_grad_array(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
        ddx: Ddx,
        ddy: Ddy,
    ) -> Self::Output;
}

/// Trait for array textures that support `textureSampleGrad` with array index
/// and offset.
pub trait TextureSampleGradArrayOffset<Coords, ArrayIndex, Ddx, Ddy, Offset> {
    /// The output type
    type Output;

    /// Sample the texture with explicit gradients, array index, and offset.
    fn sample_grad_array_offset(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
        ddx: Ddx,
        ddy: Ddy,
        offset: Offset,
    ) -> Self::Output;
}

/// Trait for depth textures that support `textureSampleCompare` with offset.
pub trait TextureSampleCompareOffset<Coords, DepthRef, Offset> {
    /// Sample the depth texture with comparison and offset.
    fn sample_compare_offset(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        depth_ref: DepthRef,
        offset: Offset,
    ) -> f32;
}

/// Trait for depth array textures that support `textureSampleCompare` with
/// array index.
pub trait TextureSampleCompareArray<Coords, ArrayIndex, DepthRef> {
    /// Sample the depth array texture with comparison.
    fn sample_compare_array(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        array_index: ArrayIndex,
        depth_ref: DepthRef,
    ) -> f32;
}

/// Trait for depth array textures that support `textureSampleCompare` with
/// array index and offset.
pub trait TextureSampleCompareArrayOffset<Coords, ArrayIndex, DepthRef, Offset> {
    /// Sample the depth array texture with comparison and offset.
    fn sample_compare_array_offset(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        array_index: ArrayIndex,
        depth_ref: DepthRef,
        offset: Offset,
    ) -> f32;
}

/// Trait for depth textures that support `textureSampleCompareLevel` with
/// offset.
pub trait TextureSampleCompareLevelOffset<Coords, DepthRef, Offset> {
    /// Sample the depth texture with comparison at mip level 0, with offset.
    fn sample_compare_level_offset(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        depth_ref: DepthRef,
        offset: Offset,
    ) -> f32;
}

/// Trait for depth array textures that support `textureSampleCompareLevel` with
/// array index.
pub trait TextureSampleCompareLevelArray<Coords, ArrayIndex, DepthRef> {
    /// Sample the depth array texture with comparison at mip level 0.
    fn sample_compare_level_array(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        array_index: ArrayIndex,
        depth_ref: DepthRef,
    ) -> f32;
}

/// Trait for depth array textures that support `textureSampleCompareLevel` with
/// array index and offset.
pub trait TextureSampleCompareLevelArrayOffset<Coords, ArrayIndex, DepthRef, Offset> {
    /// Sample the depth array texture with comparison at mip level 0, with
    /// offset.
    fn sample_compare_level_array_offset(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        array_index: ArrayIndex,
        depth_ref: DepthRef,
        offset: Offset,
    ) -> f32;
}

/// Trait for textures that support `textureGather` with offset.
pub trait TextureGatherOffset<Coords, Offset> {
    /// The output type
    type Output;

    /// Gather one component from 4 texels with offset.
    fn gather_offset(
        &self,
        component: u32,
        sampler: &Sampler,
        coords: Coords,
        offset: Offset,
    ) -> Self::Output;
}

/// Trait for array textures that support `textureGather` with array index.
pub trait TextureGatherArray<Coords, ArrayIndex> {
    /// The output type
    type Output;

    /// Gather one component from 4 texels with array index.
    fn gather_array(
        &self,
        component: u32,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
    ) -> Self::Output;
}

/// Trait for array textures that support `textureGather` with array index and
/// offset.
pub trait TextureGatherArrayOffset<Coords, ArrayIndex, Offset> {
    /// The output type
    type Output;

    /// Gather one component from 4 texels with array index and offset.
    fn gather_array_offset(
        &self,
        component: u32,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
        offset: Offset,
    ) -> Self::Output;
}

/// Trait for depth textures that support `textureGather` with offset (no
/// component).
pub trait TextureGatherDepthOffset<Coords, Offset> {
    /// Gather depth values from 4 texels with offset.
    fn gather_depth_offset(&self, sampler: &Sampler, coords: Coords, offset: Offset) -> Vec4f;
}

/// Trait for depth array textures that support `textureGather` with array index
/// (no component).
pub trait TextureGatherDepthArray<Coords, ArrayIndex> {
    /// Gather depth values from 4 texels with array index.
    fn gather_depth_array(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
    ) -> Vec4f;
}

/// Trait for depth array textures that support `textureGather` with array index
/// and offset.
pub trait TextureGatherDepthArrayOffset<Coords, ArrayIndex, Offset> {
    /// Gather depth values from 4 texels with array index and offset.
    fn gather_depth_array_offset(
        &self,
        sampler: &Sampler,
        coords: Coords,
        array_index: ArrayIndex,
        offset: Offset,
    ) -> Vec4f;
}

/// Trait for depth textures that support `textureGatherCompare` with offset.
pub trait TextureGatherCompareOffset<Coords, DepthRef, Offset> {
    /// Gather depth values with comparison from 4 texels, with offset.
    fn gather_compare_offset(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        depth_ref: DepthRef,
        offset: Offset,
    ) -> Vec4f;
}

/// Trait for depth array textures that support `textureGatherCompare` with
/// array index.
pub trait TextureGatherCompareArray<Coords, ArrayIndex, DepthRef> {
    /// Gather depth values with comparison from 4 texels, with array index.
    fn gather_compare_array(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        array_index: ArrayIndex,
        depth_ref: DepthRef,
    ) -> Vec4f;
}

/// Trait for depth array textures that support `textureGatherCompare` with
/// array index and offset.
pub trait TextureGatherCompareArrayOffset<Coords, ArrayIndex, DepthRef, Offset> {
    /// Gather depth values with comparison from 4 texels, with array index and
    /// offset.
    fn gather_compare_array_offset(
        &self,
        sampler: &SamplerComparison,
        coords: Coords,
        array_index: ArrayIndex,
        depth_ref: DepthRef,
        offset: Offset,
    ) -> Vec4f;
}

/// Trait for storage textures that support `textureStore`.
pub trait TextureStore<Coords, Value> {
    /// Store a value to the storage texture at the given coordinates.
    fn store(&self, coords: Coords, value: Value);
}

/// Trait for storage array textures that support `textureStore` with array
/// index.
pub trait TextureStoreArray<Coords, ArrayIndex, Value> {
    /// Store a value to the storage array texture at the given coordinates and
    /// array index.
    fn store_array(&self, coords: Coords, array_index: ArrayIndex, value: Value);
}

/// Trait for storage textures that support `textureLoad` (no mip level
/// parameter, unlike [`TextureLoad`]). WGSL §17.7.4 storage overloads.
pub trait TextureLoadStorage<Coords> {
    /// The output type (`vec4<f32>`, `vec4<u32>`, or `vec4<i32>` depending on
    /// the texel format).
    type Output;

    /// Load a texel at the given coordinates.
    fn load_storage(&self, coords: Coords) -> Self::Output;
}

/// Trait for storage array textures that support `textureLoad` with array
/// index (no mip level). WGSL §17.7.4 storage overloads.
pub trait TextureLoadStorageArray<Coords, ArrayIndex> {
    /// The output type.
    type Output;

    /// Load a texel at the given coordinates and array index.
    fn load_storage_array(&self, coords: Coords, array_index: ArrayIndex) -> Self::Output;
}

/// Trait for types that can be used as texture coordinates.
pub trait IntoCoord {
    fn into_i32(self) -> i32;
    fn into_u32(self) -> u32;
}

impl IntoCoord for i32 {
    fn into_i32(self) -> i32 {
        self
    }
    fn into_u32(self) -> u32 {
        self.max(0) as u32
    }
}

impl IntoCoord for u32 {
    fn into_i32(self) -> i32 {
        self as i32
    }
    fn into_u32(self) -> u32 {
        self
    }
}

/// Trait for types that can be used as mip levels.
pub trait IntoLevel {
    fn into_level(self) -> u32;
}

impl IntoLevel for i32 {
    fn into_level(self) -> u32 {
        self.max(0) as u32
    }
}

impl IntoLevel for u32 {
    fn into_level(self) -> u32 {
        self
    }
}

/// Returns the dimensions of a texture.
///
/// For 1D textures, returns `u32`.
/// For 2D textures, returns `Vec2u`.
/// For 3D textures, returns `Vec3u`.
///
/// To specify a mipmap level use [`texture_dimensions_level`].
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let dims = textureDimensions(my_texture);
/// ```
pub fn texture_dimensions<T: TextureDimensionsQuery>(t: &T) -> T::Output {
    t.query_dimensions(0)
}

/// Returns the dimensions of a texture at a given mipmap level.
///
/// For 1D textures, returns `u32`.
/// For 2D textures, returns `Vec2u`.
/// For 3D textures, returns `Vec3u`.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let dims_at_level = textureDimensions(my_texture, 2);
/// ```
pub fn texture_dimensions_level<T: TextureDimensionsQuery>(
    t: &T,
    level: impl IntoLevel,
) -> T::Output {
    t.query_dimensions(level.into_level())
}

/// Returns the number of array layers in an array texture.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let layers = textureNumLayers(my_texture_array);
/// ```
pub fn texture_num_layers<T: TextureNumLayersQuery>(t: &T) -> u32 {
    t.query_num_layers()
}

/// Returns the number of mip levels in a texture.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let levels = textureNumLevels(my_texture);
/// ```
pub fn texture_num_levels<T: TextureNumLevelsQuery>(t: &T) -> u32 {
    t.query_num_levels()
}

/// Returns the number of samples in a multisampled texture.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let samples = textureNumSamples(my_multisampled_texture);
/// ```
pub fn texture_num_samples<T: TextureNumSamplesQuery>(t: &T) -> u32 {
    t.query_num_samples()
}

/// Reads a single texel from a texture without sampling or filtering.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let texel = textureLoad(my_texture, coords, level);
/// ```
pub fn texture_load<T, C, L>(t: &T, coords: C, level: L) -> T::Output
where
    T: TextureLoad<C, L>,
{
    t.load(coords, level)
}

/// Reads a single texel from a multisampled texture.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let texel = textureLoad(my_multisampled_texture, coords, sample_index);
/// ```
pub fn texture_load_multisampled<T, C, S>(t: &T, coords: C, sample_index: S) -> T::Output
where
    T: TextureLoadMultisampled<C, S>,
{
    t.load_multisampled(coords, sample_index)
}

/// Reads a single texel from an array texture.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let texel = textureLoad(my_array_texture, coords, array_index, level);
/// ```
pub fn texture_load_array<T, C, A, L>(t: &T, coords: C, array_index: A, level: L) -> T::Output
where
    T: TextureLoadArray<C, A, L>,
{
    t.load_array(coords, array_index, level)
}

/// Samples a texture.
///
/// Must only be used in a fragment shader stage (enforced by WGSL, not by
/// Rust). On CPU, this samples at mip level 0 since screen-space derivatives
/// are not available.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSample(my_texture, my_sampler, uv);
/// ```
pub fn texture_sample<T, C>(t: &T, s: &Sampler, coords: C) -> T::Output
where
    T: TextureSample<C>,
{
    t.sample(s, coords)
}

/// Samples a texture with an offset applied to the texture coordinates.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSample(my_texture, my_sampler, uv, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_offset<T, C, O>(t: &T, s: &Sampler, coords: C, offset: O) -> T::Output
where
    T: TextureSampleOffset<C, O>,
{
    t.sample_offset(s, coords, offset)
}

/// Samples a texture array.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSample(my_texture_array, my_sampler, uv, array_index);
/// ```
pub fn texture_sample_array<T, C, A>(t: &T, s: &Sampler, coords: C, array_index: A) -> T::Output
where
    T: TextureSampleArray<C, A>,
{
    t.sample_array(s, coords, array_index)
}

/// Samples a texture at an explicit mip level.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleLevel(my_texture, my_sampler, uv, 2.0);
/// ```
pub fn texture_sample_level<T, C, L>(t: &T, s: &Sampler, coords: C, level: L) -> T::Output
where
    T: TextureSampleLevel<C, L>,
{
    t.sample_level(s, coords, level)
}

/// Samples a texture with a bias added to the mip level.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleBias(my_texture, my_sampler, uv, 1.0);
/// ```
pub fn texture_sample_bias<T, C, B>(t: &T, s: &Sampler, coords: C, bias: B) -> T::Output
where
    T: TextureSampleBias<C, B>,
{
    t.sample_bias(s, coords, bias)
}

/// Samples a texture with explicit gradients for LOD calculation.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleGrad(my_texture, my_sampler, uv, ddx, ddy);
/// ```
pub fn texture_sample_grad<T, C, D>(t: &T, s: &Sampler, coords: C, ddx: D, ddy: D) -> T::Output
where
    T: TextureSampleGrad<C, D, D>,
{
    t.sample_grad(s, coords, ddx, ddy)
}

/// Samples a depth texture and compares the result against a reference value.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let shadow = textureSampleCompare(shadow_map, shadow_sampler, uv, depth_ref);
/// ```
pub fn texture_sample_compare<T, C, R>(t: &T, s: &SamplerComparison, coords: C, depth_ref: R) -> f32
where
    T: TextureSampleCompare<C, R>,
{
    t.sample_compare(s, coords, depth_ref)
}

/// Samples a depth texture at mip level 0 and compares the result.
///
/// Per the WGSL spec, `textureSampleCompareLevel` always samples at mip level
/// 0. Unlike `textureSampleCompare`, this function may be invoked in any shader
/// stage.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let shadow = textureSampleCompareLevel(shadow_map, shadow_sampler, uv, depth_ref);
/// ```
pub fn texture_sample_compare_level<T, C, R>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    depth_ref: R,
) -> f32
where
    T: TextureSampleCompareLevel<C, R>,
{
    t.sample_compare_level(s, coords, depth_ref)
}

/// Samples a texture at its base mip level with coordinates clamped to the
/// edge.
///
/// The coordinates are clamped to `[0.5/dim, 1.0 - 0.5/dim]` before sampling,
/// which prevents wrapping artifacts regardless of the sampler's address mode.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleBaseClampToEdge(my_texture, my_sampler, uv);
/// ```
pub fn texture_sample_base_clamp_to_edge<T, C>(t: &T, s: &Sampler, coords: C) -> T::Output
where
    T: TextureSampleBaseClampToEdge<C>,
{
    t.sample_base_clamp_to_edge(s, coords)
}

/// Gathers one component from 4 texels that would be used in bilinear
/// filtering.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGather(0, my_texture, my_sampler, uv);
/// ```
pub fn texture_gather<T, C>(component: impl IntoCoord, t: &T, s: &Sampler, coords: C) -> T::Output
where
    T: TextureGather<C>,
{
    t.gather(component.into_u32(), s, coords)
}

/// Gathers depth values from 4 texels (for depth textures).
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGather(depth_texture, my_sampler, uv);
/// ```
pub fn texture_gather_depth<T, C>(t: &T, s: &Sampler, coords: C) -> Vec4f
where
    T: TextureGatherDepth<C>,
{
    t.gather_depth(s, coords)
}

/// Gathers depth values with comparison from 4 texels.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGatherCompare(depth_texture, shadow_sampler, uv, depth_ref);
/// ```
pub fn texture_gather_compare<T, C, R>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    depth_ref: R,
) -> Vec4f
where
    T: TextureGatherCompare<C, R>,
{
    t.gather_compare(s, coords, depth_ref)
}

/// Samples a texture array with an offset applied.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSample(my_array_tex, my_sampler, uv, array_index, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_array_offset<T, C, A, O>(
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
    offset: O,
) -> T::Output
where
    T: TextureSampleArrayOffset<C, A, O>,
{
    t.sample_array_offset(s, coords, array_index, offset)
}

/// Samples a texture at an explicit mip level with an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleLevel(my_texture, my_sampler, uv, 2.0, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_level_offset<T, C, L, O>(
    t: &T,
    s: &Sampler,
    coords: C,
    level: L,
    offset: O,
) -> T::Output
where
    T: TextureSampleLevelOffset<C, L, O>,
{
    t.sample_level_offset(s, coords, level, offset)
}

/// Samples a texture array at an explicit mip level.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleLevel(my_array_tex, my_sampler, uv, array_index, 2.0);
/// ```
pub fn texture_sample_level_array<T, C, A, L>(
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
    level: L,
) -> T::Output
where
    T: TextureSampleLevelArray<C, A, L>,
{
    t.sample_level_array(s, coords, array_index, level)
}

/// Samples a texture array at an explicit mip level with an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleLevel(my_array_tex, my_sampler, uv, idx, 2.0, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_level_array_offset<T, C, A, L, O>(
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
    level: L,
    offset: O,
) -> T::Output
where
    T: TextureSampleLevelArrayOffset<C, A, L, O>,
{
    t.sample_level_array_offset(s, coords, array_index, level, offset)
}

/// Samples a texture with a bias and an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleBias(my_texture, my_sampler, uv, 1.0, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_bias_offset<T, C, B, O>(
    t: &T,
    s: &Sampler,
    coords: C,
    bias: B,
    offset: O,
) -> T::Output
where
    T: TextureSampleBiasOffset<C, B, O>,
{
    t.sample_bias_offset(s, coords, bias, offset)
}

/// Samples a texture array with a bias.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleBias(my_array_tex, my_sampler, uv, array_index, 1.0);
/// ```
pub fn texture_sample_bias_array<T, C, A, B>(
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
    bias: B,
) -> T::Output
where
    T: TextureSampleBiasArray<C, A, B>,
{
    t.sample_bias_array(s, coords, array_index, bias)
}

/// Samples a texture array with a bias and an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleBias(my_array_tex, my_sampler, uv, idx, 1.0, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_bias_array_offset<T, C, A, B, O>(
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
    bias: B,
    offset: O,
) -> T::Output
where
    T: TextureSampleBiasArrayOffset<C, A, B, O>,
{
    t.sample_bias_array_offset(s, coords, array_index, bias, offset)
}

/// Samples a texture with explicit gradients and an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleGrad(my_texture, my_sampler, uv, ddx, ddy, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_grad_offset<T, C, D, O>(
    t: &T,
    s: &Sampler,
    coords: C,
    ddx: D,
    ddy: D,
    offset: O,
) -> T::Output
where
    T: TextureSampleGradOffset<C, D, D, O>,
{
    t.sample_grad_offset(s, coords, ddx, ddy, offset)
}

/// Samples a texture array with explicit gradients.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleGrad(my_array_tex, my_sampler, uv, array_index, ddx, ddy);
/// ```
pub fn texture_sample_grad_array<T, C, A, D>(
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
    ddx: D,
    ddy: D,
) -> T::Output
where
    T: TextureSampleGradArray<C, A, D, D>,
{
    t.sample_grad_array(s, coords, array_index, ddx, ddy)
}

/// Samples a texture array with explicit gradients and an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let color = textureSampleGrad(my_arr, my_sampler, uv, idx, ddx, ddy, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_grad_array_offset<T, C, A, D, O>(
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
    ddx: D,
    ddy: D,
    offset: O,
) -> T::Output
where
    T: TextureSampleGradArrayOffset<C, A, D, D, O>,
{
    t.sample_grad_array_offset(s, coords, array_index, ddx, ddy, offset)
}

/// Samples a depth texture with comparison and an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let shadow = textureSampleCompare(shadow_map, sampler, uv, depth_ref, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_compare_offset<T, C, R, O>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    depth_ref: R,
    offset: O,
) -> f32
where
    T: TextureSampleCompareOffset<C, R, O>,
{
    t.sample_compare_offset(s, coords, depth_ref, offset)
}

/// Samples a depth array texture with comparison.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let shadow = textureSampleCompare(shadow_map, sampler, uv, array_index, depth_ref);
/// ```
pub fn texture_sample_compare_array<T, C, A, R>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    array_index: A,
    depth_ref: R,
) -> f32
where
    T: TextureSampleCompareArray<C, A, R>,
{
    t.sample_compare_array(s, coords, array_index, depth_ref)
}

/// Samples a depth array texture with comparison and an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let shadow = textureSampleCompare(map, s, uv, idx, depth_ref, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_compare_array_offset<T, C, A, R, O>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    array_index: A,
    depth_ref: R,
    offset: O,
) -> f32
where
    T: TextureSampleCompareArrayOffset<C, A, R, O>,
{
    t.sample_compare_array_offset(s, coords, array_index, depth_ref, offset)
}

/// Samples a depth texture at mip level 0 with comparison and an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let shadow = textureSampleCompareLevel(map, sampler, uv, depth_ref, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_compare_level_offset<T, C, R, O>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    depth_ref: R,
    offset: O,
) -> f32
where
    T: TextureSampleCompareLevelOffset<C, R, O>,
{
    t.sample_compare_level_offset(s, coords, depth_ref, offset)
}

/// Samples a depth array texture at mip level 0 with comparison.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let shadow = textureSampleCompareLevel(map, sampler, uv, array_index, depth_ref);
/// ```
pub fn texture_sample_compare_level_array<T, C, A, R>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    array_index: A,
    depth_ref: R,
) -> f32
where
    T: TextureSampleCompareLevelArray<C, A, R>,
{
    t.sample_compare_level_array(s, coords, array_index, depth_ref)
}

/// Samples a depth array texture at mip level 0 with comparison and an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let shadow = textureSampleCompareLevel(map, s, uv, idx, depth_ref, vec2<i32>(1, 0));
/// ```
pub fn texture_sample_compare_level_array_offset<T, C, A, R, O>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    array_index: A,
    depth_ref: R,
    offset: O,
) -> f32
where
    T: TextureSampleCompareLevelArrayOffset<C, A, R, O>,
{
    t.sample_compare_level_array_offset(s, coords, array_index, depth_ref, offset)
}

/// Gathers one component from 4 texels with an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGather(0, my_texture, my_sampler, uv, vec2<i32>(1, 0));
/// ```
pub fn texture_gather_offset<T, C, O>(
    component: impl IntoCoord,
    t: &T,
    s: &Sampler,
    coords: C,
    offset: O,
) -> T::Output
where
    T: TextureGatherOffset<C, O>,
{
    t.gather_offset(component.into_u32(), s, coords, offset)
}

/// Gathers one component from 4 texels of an array texture.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGather(0, my_array_tex, my_sampler, uv, array_index);
/// ```
pub fn texture_gather_array<T, C, A>(
    component: impl IntoCoord,
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
) -> T::Output
where
    T: TextureGatherArray<C, A>,
{
    t.gather_array(component.into_u32(), s, coords, array_index)
}

/// Gathers one component from 4 texels of an array texture with an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGather(0, my_arr, my_sampler, uv, idx, vec2<i32>(1, 0));
/// ```
pub fn texture_gather_array_offset<T, C, A, O>(
    component: impl IntoCoord,
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
    offset: O,
) -> T::Output
where
    T: TextureGatherArrayOffset<C, A, O>,
{
    t.gather_array_offset(component.into_u32(), s, coords, array_index, offset)
}

/// Gathers depth values from 4 texels with an offset (no component).
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGather(depth_texture, my_sampler, uv, vec2<i32>(1, 0));
/// ```
pub fn texture_gather_depth_offset<T, C, O>(t: &T, s: &Sampler, coords: C, offset: O) -> Vec4f
where
    T: TextureGatherDepthOffset<C, O>,
{
    t.gather_depth_offset(s, coords, offset)
}

/// Gathers depth values from 4 texels of an array texture (no component).
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGather(depth_array_texture, my_sampler, uv, array_index);
/// ```
pub fn texture_gather_depth_array<T, C, A>(t: &T, s: &Sampler, coords: C, array_index: A) -> Vec4f
where
    T: TextureGatherDepthArray<C, A>,
{
    t.gather_depth_array(s, coords, array_index)
}

/// Gathers depth values from 4 texels of an array texture with an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGather(depth_arr, my_sampler, uv, idx, vec2<i32>(1, 0));
/// ```
pub fn texture_gather_depth_array_offset<T, C, A, O>(
    t: &T,
    s: &Sampler,
    coords: C,
    array_index: A,
    offset: O,
) -> Vec4f
where
    T: TextureGatherDepthArrayOffset<C, A, O>,
{
    t.gather_depth_array_offset(s, coords, array_index, offset)
}

/// Gathers depth values with comparison from 4 texels, with an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGatherCompare(depth_tex, sampler, uv, depth_ref, vec2<i32>(1, 0));
/// ```
pub fn texture_gather_compare_offset<T, C, R, O>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    depth_ref: R,
    offset: O,
) -> Vec4f
where
    T: TextureGatherCompareOffset<C, R, O>,
{
    t.gather_compare_offset(s, coords, depth_ref, offset)
}

/// Gathers depth values with comparison from 4 texels of an array texture.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGatherCompare(depth_arr, sampler, uv, array_index, depth_ref);
/// ```
pub fn texture_gather_compare_array<T, C, A, R>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    array_index: A,
    depth_ref: R,
) -> Vec4f
where
    T: TextureGatherCompareArray<C, A, R>,
{
    t.gather_compare_array(s, coords, array_index, depth_ref)
}

/// Gathers depth values with comparison from 4 texels of an array texture, with
/// an offset.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let gathered = textureGatherCompare(arr, sampler, uv, idx, depth_ref, vec2<i32>(1, 0));
/// ```
pub fn texture_gather_compare_array_offset<T, C, A, R, O>(
    t: &T,
    s: &SamplerComparison,
    coords: C,
    array_index: A,
    depth_ref: R,
    offset: O,
) -> Vec4f
where
    T: TextureGatherCompareArrayOffset<C, A, R, O>,
{
    t.gather_compare_array_offset(s, coords, array_index, depth_ref, offset)
}

/// Stores a value to a storage texture.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// textureStore(my_storage_texture, coords, value);
/// ```
pub fn texture_store<T, C, V>(t: &T, coords: C, value: V)
where
    T: TextureStore<C, V>,
{
    t.store(coords, value)
}

/// Stores a value to a storage array texture.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// textureStore(my_storage_array_texture, coords, array_index, value);
/// ```
pub fn texture_store_array<T, C, A, V>(t: &T, coords: C, array_index: A, value: V)
where
    T: TextureStoreArray<C, A, V>,
{
    t.store_array(coords, array_index, value)
}

/// Reads a single texel from a storage texture without a mip level.
///
/// Unlike [`texture_load`], this overload takes no `level` parameter —
/// storage textures have no mip levels (WGSL §17.7.4).
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let texel = textureLoad(my_storage_texture, coords);
/// ```
pub fn texture_load_storage<T, C>(t: &T, coords: C) -> T::Output
where
    T: TextureLoadStorage<C>,
{
    t.load_storage(coords)
}

/// Reads a single texel from a storage array texture without a mip level.
///
/// # WGSL Equivalent
///
/// ```wgsl
/// let texel = textureLoad(my_storage_array_texture, coords, array_index);
/// ```
pub fn texture_load_storage_array<T, C, A>(t: &T, coords: C, array_index: A) -> T::Output
where
    T: TextureLoadStorageArray<C, A>,
{
    t.load_storage_array(coords, array_index)
}

/// Helper function for bilinear interpolation.
fn bilinear_interpolate<T: Copy + Default + Into<f32> + From<f32>>(
    tl: [T; 4],
    tr: [T; 4],
    bl: [T; 4],
    br: [T; 4],
    fx: f32,
    fy: f32,
) -> [T; 4] {
    std::array::from_fn(|i| {
        let top = tl[i].into() * (1.0 - fx) + tr[i].into() * fx;
        let bottom = bl[i].into() * (1.0 - fx) + br[i].into() * fx;
        T::from(top * (1.0 - fy) + bottom * fy)
    })
}

/// Helper function to convert normalized coordinates to texel coordinates.
fn normalized_to_texel(coord: f32, size: u32) -> (u32, f32) {
    let scaled = coord * size as f32;
    let texel = (scaled.floor() as i32).clamp(0, (size as i32) - 1) as u32;
    // Use `scaled.fract().abs()` instead of `scaled.fract()` because
    // `f32::fract` returns a negative value for negative inputs (e.g.
    // `(-0.5).fract() == -0.5`), which would produce negative interpolation
    // weights and nonsensical results when sampling below texel 0.
    let frac = scaled.fract().abs();
    (texel, frac)
}

/// Sample a 2D texture at the given normalized coordinates.
pub(crate) fn sample_texture_2d<T: Copy + Default + Into<f32> + From<f32>>(
    data: &TextureData2D<T>,
    sampler_state: &SamplerState,
    u: f32,
    v: f32,
    level: u32,
) -> [T; 4] {
    let u = SamplerState::apply_address_mode(sampler_state.address_mode_u, u);
    let v = SamplerState::apply_address_mode(sampler_state.address_mode_v, v);

    let (width, height) = data.dimensions(level);
    if width == 0 || height == 0 {
        return std::array::from_fn(|_| T::default());
    }

    match sampler_state.min_filter {
        FilterMode::Nearest => {
            let x = Ord::min((u * width as f32).floor() as u32, width - 1);
            let y = Ord::min((v * height as f32).floor() as u32, height - 1);
            data.get_pixel(x, y, level)
                .copied()
                .unwrap_or_else(|| std::array::from_fn(|_| T::default()))
        }
        FilterMode::Linear => {
            let (x0, fx) = normalized_to_texel(u - 0.5 / width as f32, width);
            let (y0, fy) = normalized_to_texel(v - 0.5 / height as f32, height);
            let x1 = Ord::min(x0 + 1, width - 1);
            let y1 = Ord::min(y0 + 1, height - 1);

            let default_pixel = || std::array::from_fn(|_| T::default());
            let tl = data
                .get_pixel(x0, y0, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let tr = data
                .get_pixel(x1, y0, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let bl = data
                .get_pixel(x0, y1, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let br = data
                .get_pixel(x1, y1, level)
                .copied()
                .unwrap_or_else(default_pixel);

            bilinear_interpolate(tl, tr, bl, br, fx, fy)
        }
    }
}

/// Sample a depth 2D texture at the given normalized coordinates.
pub(crate) fn sample_depth_texture_2d(
    data: &TextureDataDepth2D,
    sampler_state: &SamplerState,
    u: f32,
    v: f32,
    level: u32,
) -> f32 {
    let u = SamplerState::apply_address_mode(sampler_state.address_mode_u, u);
    let v = SamplerState::apply_address_mode(sampler_state.address_mode_v, v);

    let (width, height) = data.dimensions(level);
    if width == 0 || height == 0 {
        return 0.0;
    }

    match sampler_state.min_filter {
        FilterMode::Nearest => {
            let x = Ord::min((u * width as f32).floor() as u32, width - 1);
            let y = Ord::min((v * height as f32).floor() as u32, height - 1);
            data.get_depth(x, y, level).unwrap_or(0.0)
        }
        FilterMode::Linear => {
            let (x0, fx) = normalized_to_texel(u - 0.5 / width as f32, width);
            let (y0, fy) = normalized_to_texel(v - 0.5 / height as f32, height);
            let x1 = Ord::min(x0 + 1, width - 1);
            let y1 = Ord::min(y0 + 1, height - 1);

            let tl = data.get_depth(x0, y0, level).unwrap_or(0.0);
            let tr = data.get_depth(x1, y0, level).unwrap_or(0.0);
            let bl = data.get_depth(x0, y1, level).unwrap_or(0.0);
            let br = data.get_depth(x1, y1, level).unwrap_or(0.0);

            let top = tl * (1.0 - fx) + tr * fx;
            let bottom = bl * (1.0 - fx) + br * fx;
            top * (1.0 - fy) + bottom * fy
        }
    }
}

/// Gather the 4 depth texels that would be used in bilinear filtering at mip
/// level 0, returning them in the WGSL-specified gather component order:
///   x = (u_min, v_max), y = (u_max, v_max),
///   z = (u_max, v_min), w = (u_min, v_min).
pub(crate) fn gather_4_depth_texels(
    data: &TextureDataDepth2D,
    sampler_state: &SamplerState,
    u: f32,
    v: f32,
) -> [f32; 4] {
    let u = SamplerState::apply_address_mode(sampler_state.address_mode_u, u);
    let v = SamplerState::apply_address_mode(sampler_state.address_mode_v, v);

    let (width, height) = data.dimensions(0);
    if width == 0 || height == 0 {
        return [0.0; 4];
    }

    // Find the 4 texels that bilinear filtering would use.
    // The texel grid center is offset by half a texel from the normalized
    // coordinate origin, so we subtract 0.5/dim before computing the floor.
    let (x0, _fx) = normalized_to_texel(u - 0.5 / width as f32, width);
    let (y0, _fy) = normalized_to_texel(v - 0.5 / height as f32, height);
    let x1 = Ord::min(x0 + 1, width - 1);
    let y1 = Ord::min(y0 + 1, height - 1);

    let tl = data.get_depth(x0, y0, 0).unwrap_or(0.0); // (u_min, v_min)
    let tr = data.get_depth(x1, y0, 0).unwrap_or(0.0); // (u_max, v_min)
    let bl = data.get_depth(x0, y1, 0).unwrap_or(0.0); // (u_min, v_max)
    let br = data.get_depth(x1, y1, 0).unwrap_or(0.0); // (u_max, v_max)

    // WGSL gather order: x=(u_min,v_max), y=(u_max,v_max), z=(u_max,v_min),
    // w=(u_min,v_min)
    [bl, br, tr, tl]
}

/// Helper for trilinear interpolation across the 8 corners of a 3D cell.
///
/// `fx`, `fy`, `fz` are the fractional weights in `[0, 1)` for the +1
/// direction along each axis. The 8 corners are named `(x0|y0|z0)` style:
/// `c000`, `c100`, `c010`, `c110`, `c001`, `c101`, `c011`, `c111`, where
/// a `1` in position `x/y/z` means the +1 texel along that axis.
#[allow(clippy::too_many_arguments)]
fn trilinear_interpolate<T: Copy + Default + Into<f32> + From<f32>>(
    c000: [T; 4],
    c100: [T; 4],
    c010: [T; 4],
    c110: [T; 4],
    c001: [T; 4],
    c101: [T; 4],
    c011: [T; 4],
    c111: [T; 4],
    fx: f32,
    fy: f32,
    fz: f32,
) -> [T; 4] {
    let lerp = |a: f32, b: f32, t: f32| a * (1.0 - t) + b * t;
    std::array::from_fn(|i| {
        let top = lerp(
            lerp(c000[i].into(), c100[i].into(), fx),
            lerp(c010[i].into(), c110[i].into(), fx),
            fy,
        );
        let bottom = lerp(
            lerp(c001[i].into(), c101[i].into(), fx),
            lerp(c011[i].into(), c111[i].into(), fx),
            fy,
        );
        T::from(lerp(top, bottom, fz))
    })
}

/// Sample a 1D texture at the given normalized coordinate.
pub(crate) fn sample_texture_1d<T: Copy + Default + Into<f32> + From<f32>>(
    data: &TextureData1D<T>,
    sampler_state: &SamplerState,
    u: f32,
    level: u32,
) -> [T; 4] {
    let u = SamplerState::apply_address_mode(sampler_state.address_mode_u, u);

    let width = data.width(level);
    if width == 0 {
        return std::array::from_fn(|_| T::default());
    }

    match sampler_state.min_filter {
        FilterMode::Nearest => {
            let x = Ord::min((u * width as f32).floor() as u32, width - 1);
            data.get_pixel(x, level)
                .copied()
                .unwrap_or_else(|| std::array::from_fn(|_| T::default()))
        }
        FilterMode::Linear => {
            let (x0, fx) = normalized_to_texel(u - 0.5 / width as f32, width);
            let x1 = Ord::min(x0 + 1, width - 1);
            let left = data
                .get_pixel(x0, level)
                .copied()
                .unwrap_or_else(|| std::array::from_fn(|_| T::default()));
            let right = data
                .get_pixel(x1, level)
                .copied()
                .unwrap_or_else(|| std::array::from_fn(|_| T::default()));
            std::array::from_fn(|i| T::from(left[i].into() * (1.0 - fx) + right[i].into() * fx))
        }
    }
}

/// Sample a 3D texture at the given normalized coordinates.
///
/// `u`, `v`, `w` are normalized coordinates in `[0, 1]`. The W coordinate
/// uses `address_mode_w` for wrapping. Nearest filtering picks the nearest
/// texel in 3D; linear filtering does trilinear interpolation across the 8
/// surrounding texels.
pub(crate) fn sample_texture_3d<T: Copy + Default + Into<f32> + From<f32>>(
    data: &TextureData3D<T>,
    sampler_state: &SamplerState,
    u: f32,
    v: f32,
    w: f32,
    level: u32,
) -> [T; 4] {
    let u = SamplerState::apply_address_mode(sampler_state.address_mode_u, u);
    let v = SamplerState::apply_address_mode(sampler_state.address_mode_v, v);
    let w = SamplerState::apply_address_mode(sampler_state.address_mode_w, w);

    let (width, height, depth) = data.dimensions(level);
    if width == 0 || height == 0 || depth == 0 {
        return std::array::from_fn(|_| T::default());
    }

    match sampler_state.min_filter {
        FilterMode::Nearest => {
            let x = Ord::min((u * width as f32).floor() as u32, width - 1);
            let y = Ord::min((v * height as f32).floor() as u32, height - 1);
            let z = Ord::min((w * depth as f32).floor() as u32, depth - 1);
            data.get_pixel(x, y, z, level)
                .copied()
                .unwrap_or_else(|| std::array::from_fn(|_| T::default()))
        }
        FilterMode::Linear => {
            let (x0, fx) = normalized_to_texel(u - 0.5 / width as f32, width);
            let (y0, fy) = normalized_to_texel(v - 0.5 / height as f32, height);
            let (z0, fz) = normalized_to_texel(w - 0.5 / depth as f32, depth);
            let x1 = Ord::min(x0 + 1, width - 1);
            let y1 = Ord::min(y0 + 1, height - 1);
            let z1 = Ord::min(z0 + 1, depth - 1);

            let default_pixel = || std::array::from_fn(|_| T::default());
            let c000 = data
                .get_pixel(x0, y0, z0, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let c100 = data
                .get_pixel(x1, y0, z0, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let c010 = data
                .get_pixel(x0, y1, z0, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let c110 = data
                .get_pixel(x1, y1, z0, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let c001 = data
                .get_pixel(x0, y0, z1, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let c101 = data
                .get_pixel(x1, y0, z1, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let c011 = data
                .get_pixel(x0, y1, z1, level)
                .copied()
                .unwrap_or_else(default_pixel);
            let c111 = data
                .get_pixel(x1, y1, z1, level)
                .copied()
                .unwrap_or_else(default_pixel);

            trilinear_interpolate(c000, c100, c010, c110, c001, c101, c011, c111, fx, fy, fz)
        }
    }
}

/// Selects the cube face and projected `(u, v)` coordinates for a given
/// direction vector, using the standard WebGPU cube-map major-axis
/// selection convention.
///
/// Returns `(face_index, u, v)` where `face_index` is in `0..6` following
/// the WebGPU face order: 0=+X, 1=-X, 2=+Y, 3=-Y, 4=+Z, 5=-Z. The returned
/// `u`, `v` are in `[0, 1]` within the selected face, suitable for passing
/// to [`sample_texture_2d`].
///
/// A zero-length direction is degenerate (GPU behavior is undefined);
/// this function returns face 0 at its center as a deterministic
/// fallback rather than producing NaN from division by zero.
///
/// See <https://www.w3.org/TR/webgpu/#texture-view-format-cube>.
fn select_cube_face(dx: f32, dy: f32, dz: f32) -> (usize, f32, f32) {
    let ax = dx.abs();
    let ay = dy.abs();
    let az = dz.abs();
    let ma = ax.max(ay).max(az);

    // A zero-length direction is degenerate. Return a deterministic
    // fallback to avoid division by zero.
    if ma == 0.0 {
        return (0, 0.5, 0.5);
    }

    // Major-axis selection. For each face the projection follows the
    // standard cube-map convention: the two non-major axes are mapped to
    // face (u, v), with sign flips depending on face orientation so that
    // the texture is oriented correctly when viewed from outside the cube.
    // The major axis is `ma`, so we divide by `2.0 * ma` to map the
    // non-major components into [-0.5, 0.5] before centering at 0.5.
    if ax == ma {
        // X major
        if dx >= 0.0 {
            // +X face: u = -dz, v = -dy
            (0, 0.5 - dz / (2.0 * ma), 0.5 - dy / (2.0 * ma))
        } else {
            // -X face: u = +dz, v = -dy
            (1, 0.5 + dz / (2.0 * ma), 0.5 - dy / (2.0 * ma))
        }
    } else if ay == ma {
        // Y major
        if dy >= 0.0 {
            // +Y face: u = +dx, v = +dz
            (2, 0.5 + dx / (2.0 * ma), 0.5 + dz / (2.0 * ma))
        } else {
            // -Y face: u = +dx, v = -dz
            (3, 0.5 + dx / (2.0 * ma), 0.5 - dz / (2.0 * ma))
        }
    } else {
        // Z major
        if dz >= 0.0 {
            // +Z face: u = +dx, v = -dy
            (4, 0.5 + dx / (2.0 * ma), 0.5 - dy / (2.0 * ma))
        } else {
            // -Z face: u = -dx, v = -dy
            (5, 0.5 - dx / (2.0 * ma), 0.5 - dy / (2.0 * ma))
        }
    }
}

/// Sample a cube texture at the given direction.
///
/// The direction `(dx, dy, dz)` is first mapped to a face via
/// [`select_cube_face`], then the face's 2D texture is sampled using
/// [`sample_texture_2d`]. The W component of the sampler's address modes
/// is not applied (cube textures have no W coordinate).
pub(crate) fn sample_texture_cube<T: Copy + Default + Into<f32> + From<f32>>(
    data: &TextureDataCube<T>,
    sampler_state: &SamplerState,
    dx: f32,
    dy: f32,
    dz: f32,
    level: u32,
) -> [T; 4] {
    let (face, u, v) = select_cube_face(dx, dy, dz);
    sample_texture_2d(&data.faces[face], sampler_state, u, v, level)
}

/// Sample a cube array texture at the given direction and array layer.
///
/// The `array_index` is clamped to `[0, num_layers - 1]` before sampling
/// the selected cube via [`sample_texture_cube`].
pub(crate) fn sample_texture_cube_array<T: Copy + Default + Into<f32> + From<f32>>(
    data: &TextureDataCubeArray<T>,
    sampler_state: &SamplerState,
    dx: f32,
    dy: f32,
    dz: f32,
    array_index: u32,
    level: u32,
) -> [T; 4] {
    let layer = (array_index as usize).min(data.cubes.len().saturating_sub(1));
    data.cubes
        .get(layer)
        .map(|cube| sample_texture_cube(cube, sampler_state, dx, dy, dz, level))
        .unwrap_or_else(|| std::array::from_fn(|_| T::default()))
}

/// Gathers one component from the 4 texels that would be used in bilinear
/// filtering of a 2D texture.
///
/// `u` and `v` are normalized coordinates; the sampler's address modes are
/// applied before texel selection. The returned values follow the WGSL
/// `textureGather` component order: `x` = (u_min, v_max), `y` = (u_max,
/// v_max), `z` = (u_max, v_min), `w` = (u_min, v_min). Per the spec, the
/// gather always reads mip level 0.
pub(crate) fn gather_texture_2d<T: Copy + Default>(
    data: &TextureData2D<T>,
    sampler_state: &SamplerState,
    u: f32,
    v: f32,
    component: u32,
) -> [T; 4] {
    let (w, h) = data.dimensions(0);
    if w == 0 || h == 0 {
        return std::array::from_fn(|_| T::default());
    }
    let u = SamplerState::apply_address_mode(sampler_state.address_mode_u, u);
    let v = SamplerState::apply_address_mode(sampler_state.address_mode_v, v);
    let texel_x = (u * w as f32 - 0.5).floor();
    let texel_y = (v * h as f32 - 0.5).floor();
    let c = component.min(3) as usize;
    let get = |x: f32, y: f32| -> T {
        let xi = (x as i32).clamp(0, w as i32 - 1) as u32;
        let yi = (y as i32).clamp(0, h as i32 - 1) as u32;
        data.get_pixel(xi, yi, 0).map(|p| p[c]).unwrap_or_default()
    };
    // WGSL gather component order:
    // x = (u_min, v_max), y = (u_max, v_max), z = (u_max, v_min), w = (u_min,
    // v_min)
    [
        get(texel_x, texel_y + 1.0),
        get(texel_x + 1.0, texel_y + 1.0),
        get(texel_x + 1.0, texel_y),
        get(texel_x, texel_y),
    ]
}

/// Gathers one component from the 4 texels of the cube face selected by the
/// direction `(dx, dy, dz)`.
///
/// Face selection and `(u, v)` projection follow [`select_cube_face`]; the
/// gather itself is performed on the selected face via [`gather_texture_2d`].
pub(crate) fn gather_texture_cube<T: Copy + Default>(
    data: &TextureDataCube<T>,
    sampler_state: &SamplerState,
    dx: f32,
    dy: f32,
    dz: f32,
    component: u32,
) -> [T; 4] {
    let (face, u, v) = select_cube_face(dx, dy, dz);
    gather_texture_2d(&data.faces[face], sampler_state, u, v, component)
}

/// Gathers one component from the 4 texels of the cube layer selected by
/// `array_index`.
///
/// The `array_index` is clamped to `[0, num_layers - 1]` before gathering
/// from the selected cube via [`gather_texture_cube`].
pub(crate) fn gather_texture_cube_array<T: Copy + Default>(
    data: &TextureDataCubeArray<T>,
    sampler_state: &SamplerState,
    dx: f32,
    dy: f32,
    dz: f32,
    array_index: u32,
    component: u32,
) -> [T; 4] {
    let layer = (array_index as usize).min(data.cubes.len().saturating_sub(1));
    data.cubes
        .get(layer)
        .map(|cube| gather_texture_cube(cube, sampler_state, dx, dy, dz, component))
        .unwrap_or_else(|| std::array::from_fn(|_| T::default()))
}

/// Gathers one component from the 4 texels of the 2D array layer selected by
/// `array_index`.
///
/// The `array_index` is clamped to `[0, num_layers - 1]` before gathering
/// from the selected layer via [`gather_texture_2d`].
pub(crate) fn gather_texture_2d_array<T: Copy + Default>(
    data: &TextureData2DArray<T>,
    sampler_state: &SamplerState,
    u: f32,
    v: f32,
    array_index: u32,
    component: u32,
) -> [T; 4] {
    let layer = (array_index as usize).min(data.layers.len().saturating_sub(1));
    data.layers
        .get(layer)
        .map(|layer_data| gather_texture_2d(layer_data, sampler_state, u, v, component))
        .unwrap_or_else(|| std::array::from_fn(|_| T::default()))
}

/// Gathers the depth values of the 4 texels of the cube face selected by
/// the direction `(dx, dy, dz)`.
///
/// Face selection and `(u, v)` projection follow [`select_cube_face`]; the
/// gather itself is performed on the selected face via
/// [`gather_4_depth_texels`].
pub(crate) fn gather_depth_texture_cube(
    data: &TextureDataDepthCube,
    sampler_state: &SamplerState,
    dx: f32,
    dy: f32,
    dz: f32,
) -> [f32; 4] {
    let (face, u, v) = select_cube_face(dx, dy, dz);
    gather_4_depth_texels(&data.faces[face], sampler_state, u, v)
}

/// Gathers the depth values of the 4 texels of the cube layer selected by
/// `array_index`.
///
/// The `array_index` is clamped to `[0, num_layers - 1]` before gathering
/// from the selected cube via [`gather_depth_texture_cube`].
pub(crate) fn gather_depth_texture_cube_array(
    data: &TextureDataDepthCubeArray,
    sampler_state: &SamplerState,
    dx: f32,
    dy: f32,
    dz: f32,
    array_index: u32,
) -> [f32; 4] {
    let layer = (array_index as usize).min(data.cubes.len().saturating_sub(1));
    data.cubes
        .get(layer)
        .map(|cube| gather_depth_texture_cube(cube, sampler_state, dx, dy, dz))
        .unwrap_or([0.0, 0.0, 0.0, 0.0])
}