dotzuki-renderer 0.8.1

A general-purpose JRPG renderer built from Game Boy tile rendering principles
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
//! Indexed (palette-based) framebuffer with packed bitplane storage.
//!
//! [`IndexedFrameBuffer`] stores one palette index per pixel instead of RGBA
//! bytes. It is an additive alternative to the engine's RGBA
//! [`dotzuki_engine::render::FrameBuffer`] for fixed-palette games (the GB-port
//! plan, `docs/low-end-hardware-optimization.md` §5.4, and NES/SNES-style projects):
//! a Game Boy 160×144 screen costs 5,760 bytes instead of 92,160.
//!
//! # Storage format (packed 2bpp, planar bitplanes)
//!
//! Two candidate storages were considered: one byte per pixel (`W*H` bytes)
//! or packed 2bpp (`W*H/4` bytes). Packed 2bpp was chosen:
//!
//! - **VRAM isomorphism.** The packing is the *same planar bitplane layout
//!   used by Game Boy VRAM tiles* and by this crate's tile pipeline
//!   ([`crate::tile::Tile::from_2bpp`], [`crate::resource::png_to_2bpp`]):
//!   each row of 8 pixels is stored as one byte per bitplane, bit 7 =
//!   leftmost pixel, bitplane 0 first. A [`GbColor`] (2-bit) buffer's raw
//!   bytes are literally GB 2bpp tile data — tile blits and buffer contents
//!   are interchangeable, and rendering code translates almost 1:1 to real
//!   GB VRAM (`docs/low-end-hardware-optimization.md` §5.4).
//! - **4× smaller**: 5.7 KiB vs 23 KiB for a 160×144 screen.
//! - The cost — bit twiddling in `set_pixel`/`get_pixel` — is negligible
//!   for a fixed 5.7 KiB buffer.
//!
//! [`LinearIndexedFrameBuffer`] explicitly selects one byte per pixel on any
//! target. It costs 23 KiB for a 160×144 framebuffer and provides a word-aligned
//! source for hardware transfers. The default type always remains packed.
//!
//! The bit width is derived from `C::MAX` (2 bits for [`GbColor`], 4 bits
//! for [`GbaColor`]), so the same type serves both the 4-color DMG and
//! 16-color GBA palettes. RGBA conversion is deferred to display time via
//! [`IndexedFrameBuffer::to_rgba`], which is what makes palette swaps
//! (fades, flashes) nearly free — the way real GB hardware does them.
//!
//! # Memory
//!
//! Dimensions are fixed at construction (runtime values, like the engine's
//! [`dotzuki_engine::render::FrameBuffer`]); [`Default`] is the 160×144 Game
//! Boy screen. Storage is a `Vec` allocated exactly once at construction and
//! never resized: `packed_len` bytes for packed storage, or one byte per pixel
//! for linear storage, rounded up to a whole word. A fixed-array variant is not possible
//! on stable Rust today — array lengths cannot be computed from generic
//! parameters (`generic_const_exprs` is unstable) — so the eventual no_std/GB
//! step can swap the `Vec` for a static buffer without touching other code.

use core::marker::PhantomData;

use crate::palette::{ColorIndex, GbColor, GbaColor, Palette, GRAYSCALE_PALETTE};
use crate::tile::{Tile, TILE_PIXELS};
use dotzuki_engine::render::Rgba;
use dotzuki_engine::render_config::RenderConfig;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Default screen width in pixels (Game Boy DMG resolution).
pub const SCREEN_WIDTH: usize = 160;
/// Default screen height in pixels (Game Boy DMG resolution).
pub const SCREEN_HEIGHT: usize = 144;

/// Number of bits needed to store one palette index of type `C`.
///
/// 2 for [`GbColor`] (4 colors), 4 for [`GbaColor`] (16 colors), at least 1
/// for any index type.
pub const fn index_bits<C: ColorIndex>() -> usize {
    let bits = C::MAX.ilog2();
    if bits < 1 {
        1
    } else {
        bits as usize
    }
}

/// Number of 8-pixel groups per row (rounded up).
///
/// A full Game Boy row is 20 groups; rows not divisible by 8 pack a partial
/// final group whose unused bits stay zero and are never read.
const fn groups_per_row(width: usize) -> usize {
    (width + 7) / 8
}

/// Packed storage length in bytes for a `width × height` buffer of `C`
/// indices: `height * groups_per_row(width) * index_bits::<C>()`.
///
/// 5,760 for a 160×144 [`GbColor`] buffer, 11,520 for [`GbaColor`].
pub const fn packed_len<C: ColorIndex>(width: usize, height: usize) -> usize {
    height * groups_per_row(width) * index_bits::<C>()
}

// ---------------------------------------------------------------------------
// IndexedFrameBuffer
// ---------------------------------------------------------------------------

/// A fixed-size framebuffer storing palette indices instead of RGBA pixels.
///
/// `C` is the palette index type ([`GbColor`] for 4-color DMG, [`GbaColor`]
/// for 16-color GBA). Dimensions are chosen at construction (see
/// [`Default`] for the 160×144 Game Boy screen). `LINEAR = false` selects
/// packed bitplanes; `LINEAR = true` selects word-aligned byte indices on
/// every target (see the [module docs](self)). Index values are masked to the storage
/// width on write.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexedFrameBuffer<C: ColorIndex = GbColor, const LINEAR: bool = false> {
    data: AlignedBytes,
    /// Screen width in pixels.
    width: usize,
    /// Screen height in pixels.
    height: usize,
    #[doc(hidden)]
    _phantom: PhantomData<C>,
}

#[inline(always)]
fn scroll_chunky_row(row: &mut [u8], dx: i32, clear: u8) {
    debug_assert!(dx != 0 && (dx.unsigned_abs() as usize) < row.len());
    let offset = dx.unsigned_abs() as usize;
    let copy_width = row.len() - offset;
    let source_x = if dx < 0 { offset } else { 0 };
    let target_x = if dx > 0 { offset } else { 0 };
    let row_ptr = row.as_mut_ptr();

    // A 2-byte-misaligned source/destination would otherwise require twice
    // as many halfword copies. On the little-endian GBA, combine adjacent
    // aligned words so each iteration still moves four pixels.
    if cfg!(target_endian = "little")
        && row.len() & 3 == 0
        && row_ptr as usize & 3 == 0
        && offset & 3 == 2
    {
        let words = row.len() / 4;
        let word_offset = offset / 4;
        let full_words = copy_width / 4;
        let row_words = row_ptr as *mut u32;
        if dx < 0 {
            for target_word in 0..full_words {
                let source_word = word_offset + target_word;
                let lower = unsafe { row_words.add(source_word).read() };
                let upper = unsafe { row_words.add(source_word + 1).read() };
                unsafe {
                    row_words
                        .add(target_word)
                        .write((lower >> 16) | (upper << 16));
                }
            }
            let tail = unsafe { row_words.add(words - 1).read() } >> 16;
            unsafe { (row_ptr.add(full_words * 4) as *mut u16).write(tail as u16) };
            row[copy_width..].fill(clear);
        } else {
            for source_word in (0..full_words).rev() {
                let lower = unsafe { row_words.add(source_word).read() };
                let upper = unsafe { row_words.add(source_word + 1).read() };
                unsafe {
                    row_words
                        .add(word_offset + 1 + source_word)
                        .write((lower >> 16) | (upper << 16));
                }
            }
            let prefix = unsafe { row_words.read() } as u16;
            unsafe { (row_ptr.add(offset) as *mut u16).write(prefix) };
            row[..offset].fill(clear);
        }
        return;
    }

    let source_address = unsafe { row_ptr.add(source_x) } as usize;
    let target_address = unsafe { row_ptr.add(target_x) } as usize;
    if (source_address | target_address | copy_width) & 3 == 0 {
        let words = copy_width / 4;
        let source = unsafe { row_ptr.add(source_x) as *const u32 };
        let target = unsafe { row_ptr.add(target_x) as *mut u32 };
        if dx > 0 {
            for word in (0..words).rev() {
                unsafe { target.add(word).write(source.add(word).read()) };
            }
        } else {
            for word in 0..words {
                unsafe { target.add(word).write(source.add(word).read()) };
            }
        }
    } else if (source_address | target_address | copy_width) & 1 == 0 {
        let halfwords = copy_width / 2;
        let source = unsafe { row_ptr.add(source_x) as *const u16 };
        let target = unsafe { row_ptr.add(target_x) as *mut u16 };
        if dx > 0 {
            for halfword in (0..halfwords).rev() {
                unsafe { target.add(halfword).write(source.add(halfword).read()) };
            }
        } else {
            for halfword in 0..halfwords {
                unsafe { target.add(halfword).write(source.add(halfword).read()) };
            }
        }
    } else if dx > 0 {
        for byte in (0..copy_width).rev() {
            unsafe {
                row_ptr
                    .add(target_x + byte)
                    .write(row_ptr.add(source_x + byte).read())
            };
        }
    } else {
        for byte in 0..copy_width {
            unsafe {
                row_ptr
                    .add(target_x + byte)
                    .write(row_ptr.add(source_x + byte).read())
            };
        }
    }

    if dx > 0 {
        row[..target_x].fill(clear);
    } else {
        row[copy_width..].fill(clear);
    }
}

fn copy_chunky_rect_within(
    pixels: &mut [u8],
    framebuffer_width: usize,
    source_x: usize,
    source_y: usize,
    copy_width: usize,
    copy_height: usize,
    destination_x: usize,
    destination_y: usize,
) {
    debug_assert!(framebuffer_width != 0);
    debug_assert!(pixels.len() % framebuffer_width == 0);
    debug_assert!(source_x + copy_width <= framebuffer_width);
    debug_assert!(destination_x + copy_width <= framebuffer_width);
    debug_assert!((source_y + copy_height) * framebuffer_width <= pixels.len());
    debug_assert!((destination_y + copy_height) * framebuffer_width <= pixels.len());

    if destination_y > source_y {
        for row in (0..copy_height).rev() {
            let source = (source_y + row) * framebuffer_width + source_x;
            let destination = (destination_y + row) * framebuffer_width + destination_x;
            pixels.copy_within(source..source + copy_width, destination);
        }
    } else {
        for row in 0..copy_height {
            let source = (source_y + row) * framebuffer_width + source_x;
            let destination = (destination_y + row) * framebuffer_width + destination_x;
            pixels.copy_within(source..source + copy_width, destination);
        }
    }
}

impl<C: ColorIndex, const LINEAR: bool> IndexedFrameBuffer<C, LINEAR> {
    /// Create a new `width × height` buffer, cleared to `clear`.
    pub fn new(width: usize, height: usize, clear: C) -> Self {
        let len = if LINEAR {
            width * height
        } else {
            packed_len::<C>(width, height)
        };
        let data = AlignedBytes {
            words: vec![0; (len + 3) / 4],
            len,
        };
        let mut fb = Self {
            data,
            width,
            height,
            _phantom: PhantomData,
        };
        fb.clear(clear);
        fb
    }

    /// Screen width in pixels.
    #[inline]
    pub const fn width(&self) -> usize {
        self.width
    }

    /// Screen height in pixels.
    #[inline]
    pub const fn height(&self) -> usize {
        self.height
    }

    /// Total number of pixels.
    #[inline]
    pub fn len(&self) -> usize {
        self.width * self.height
    }

    /// Whether the buffer holds no pixels.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.width == 0 || self.height == 0
    }

    /// Clear the entire buffer to a single index.
    #[inline]
    pub fn clear(&mut self, color: C) {
        if LINEAR {
            self.clear_linear(color)
        } else {
            self.clear_packed(color)
        }
    }

    #[inline]
    fn clear_linear(&mut self, color: C) {
        self.data
            .words
            .fill(u32::from_ne_bytes([color.to_index() as u8; 4]));
    }

    #[inline]
    fn clear_packed(&mut self, color: C) {
        let value = color.to_index();
        let bits = index_bits::<C>();
        if value == 0 || value + 1 == C::MAX {
            self.data.fill(if value == 0 { 0x00 } else { 0xFF });
            return;
        }
        // In planar layout, byte `i` holds bitplane `i % bits` of a row
        // group, so filling every byte of a plane with 0xFF/0x00 paints
        // that plane across all 8 pixels of each group.
        for (i, byte) in self.data.iter_mut().enumerate() {
            let plane = i % bits;
            *byte = if (value >> plane) & 1 == 1 {
                0xFF
            } else {
                0x00
            };
        }
    }

    /// Set a single pixel. Returns false if out of bounds.
    #[inline]
    pub fn set_pixel(&mut self, x: u32, y: u32, color: C) -> bool {
        if LINEAR {
            self.set_pixel_linear(x, y, color)
        } else {
            self.set_pixel_packed(x, y, color)
        }
    }

    #[inline]
    fn set_pixel_linear(&mut self, x: u32, y: u32, color: C) -> bool {
        if x >= self.width as u32 || y >= self.height as u32 {
            return false;
        }
        let index = y as usize * self.width + x as usize;
        unsafe {
            (self.data.as_mut_ptr() as *mut u8)
                .add(index)
                .write(color.to_index() as u8);
        }
        true
    }

    #[inline]
    fn set_pixel_packed(&mut self, x: u32, y: u32, color: C) -> bool {
        if x >= self.width as u32 || y >= self.height as u32 {
            return false;
        }
        let value = color.to_index();
        let bits = index_bits::<C>();
        let group = (x as usize) / 8;
        let bit = 7 - ((x as usize) % 8);
        let base = ((y as usize) * groups_per_row(self.width) + group) * bits;
        for plane in 0..bits {
            let plane_bit = ((value >> plane) & 1) as u8;
            let byte = &mut self.data[base + plane];
            *byte = (*byte & !(1 << bit)) | (plane_bit << bit);
        }
        true
    }

    /// Get the index of a single pixel. Returns None if out of bounds.
    #[inline]
    pub fn get_pixel(&self, x: u32, y: u32) -> Option<C> {
        if LINEAR {
            self.get_pixel_linear(x, y)
        } else {
            self.get_pixel_packed(x, y)
        }
    }

    #[inline]
    fn get_pixel_linear(&self, x: u32, y: u32) -> Option<C> {
        if x >= self.width as u32 || y >= self.height as u32 {
            return None;
        }
        let index = y as usize * self.width + x as usize;
        let value = unsafe { (self.data.as_ptr() as *const u8).add(index).read() };
        Some(C::from_u8(value))
    }

    #[inline]
    fn get_pixel_packed(&self, x: u32, y: u32) -> Option<C> {
        if x >= self.width as u32 || y >= self.height as u32 {
            return None;
        }
        let bits = index_bits::<C>();
        let group = (x as usize) / 8;
        let bit = 7 - ((x as usize) % 8);
        let base = ((y as usize) * groups_per_row(self.width) + group) * bits;
        let mut value = 0usize;
        for plane in 0..bits {
            if (self.data[base + plane] >> bit) & 1 == 1 {
                value |= 1 << plane;
            }
        }
        Some(C::from_u8(value as u8))
    }

    /// Fill a rectangular region with an index. Coordinates are clamped to
    /// buffer bounds.
    #[inline]
    pub fn fill_rect(&mut self, x: u32, y: u32, rect_width: u32, rect_height: u32, color: C) {
        if LINEAR {
            self.fill_rect_linear(x, y, rect_width, rect_height, color)
        } else {
            self.fill_rect_packed(x, y, rect_width, rect_height, color)
        }
    }

    #[inline]
    fn fill_rect_linear(&mut self, x: u32, y: u32, rect_width: u32, rect_height: u32, color: C) {
        let x_start = (x as usize).min(self.width);
        let y_start = (y as usize).min(self.height);
        let x_end = (x.saturating_add(rect_width) as usize).min(self.width);
        let y_end = (y.saturating_add(rect_height) as usize).min(self.height);
        let value = color.to_index() as u8;
        let pixels = unsafe {
            core::slice::from_raw_parts_mut(self.data.as_mut_ptr() as *mut u8, self.len())
        };
        for row in y_start..y_end {
            pixels[row * self.width + x_start..row * self.width + x_end].fill(value);
        }
    }

    /// Move the existing pixels by `(dx, dy)` and fill the newly exposed
    /// edges with `clear`.
    ///
    /// Positive offsets move pixels right/down. Pixels shifted outside the
    /// framebuffer are discarded. The GBA's chunky backing performs the
    /// move in place, avoiding a second full-screen allocation.
    pub fn scroll(&mut self, dx: i32, dy: i32, clear: C) {
        if dx == 0 && dy == 0 {
            return;
        }
        if self.is_empty()
            || dx.unsigned_abs() as usize >= self.width
            || dy.unsigned_abs() as usize >= self.height
        {
            self.clear(clear);
            return;
        }

        if LINEAR {
            {
                let width = self.width;
                let height = self.height;
                let copy_width = width - dx.unsigned_abs() as usize;
                let source_x = if dx < 0 {
                    dx.unsigned_abs() as usize
                } else {
                    0
                };
                let target_x = if dx > 0 { dx as usize } else { 0 };
                let clear_value = clear.to_index() as u8;
                let pixels = unsafe {
                    core::slice::from_raw_parts_mut(
                        self.data.as_mut_ptr() as *mut u8,
                        width * height,
                    )
                };

                // Vertical-only moves are one contiguous memmove. Horizontal
                // moves need row boundaries, so copy aligned words/halfwords in
                // the overlap-safe direction instead of invoking memmove once
                // per scanline.
                if dx == 0 {
                    if dy > 0 {
                        let offset = dy as usize;
                        pixels.copy_within(0..(height - offset) * width, offset * width);
                        pixels[..offset * width].fill(clear_value);
                    } else {
                        let offset = dy.unsigned_abs() as usize;
                        pixels.copy_within(offset * width..height * width, 0);
                        pixels[(height - offset) * width..].fill(clear_value);
                    }
                    return;
                }

                if dy == 0 {
                    for y in 0..height {
                        let start = y * width;
                        scroll_chunky_row(&mut pixels[start..start + width], dx, clear_value);
                    }
                    return;
                }

                if dy > 0 {
                    let offset = dy as usize;
                    for source_y in (0..height - offset).rev() {
                        let target_y = source_y + offset;
                        let source = source_y * width + source_x;
                        let target = target_y * width + target_x;
                        pixels.copy_within(source..source + copy_width, target);
                        if dx > 0 {
                            pixels[target_y * width..target_y * width + target_x].fill(clear_value);
                        } else if dx < 0 {
                            pixels[target + copy_width..(target_y + 1) * width].fill(clear_value);
                        }
                    }
                    pixels[..offset * width].fill(clear_value);
                } else {
                    let offset = dy.unsigned_abs() as usize;
                    for source_y in offset..height {
                        let target_y = source_y - offset;
                        let source = source_y * width + source_x;
                        let target = target_y * width + target_x;
                        pixels.copy_within(source..source + copy_width, target);
                        if dx > 0 {
                            pixels[target_y * width..target_y * width + target_x].fill(clear_value);
                        } else if dx < 0 {
                            pixels[target + copy_width..(target_y + 1) * width].fill(clear_value);
                        }
                    }
                    pixels[(height - offset) * width..].fill(clear_value);
                }
            }
        }

        if !LINEAR {
            {
                let source = self.clone();
                self.clear(clear);
                for y in 0..self.height as i32 {
                    let source_y = y - dy;
                    if source_y < 0 || source_y >= self.height as i32 {
                        continue;
                    }
                    for x in 0..self.width as i32 {
                        let source_x = x - dx;
                        if source_x < 0 || source_x >= self.width as i32 {
                            continue;
                        }
                        let color = source
                            .get_pixel(source_x as u32, source_y as u32)
                            .expect("scroll source is in bounds");
                        self.set_pixel(x as u32, y as u32, color);
                    }
                }
            }
        }
    }

    /// Copy a clipped pixel rectangle from `other` at the same coordinates.
    /// Pixels outside the rectangle are preserved. Both buffers must have the
    /// same dimensions.
    pub fn copy_rect_from(
        &mut self,
        other: &Self,
        x: u32,
        y: u32,
        rect_width: u32,
        rect_height: u32,
    ) {
        assert_eq!(self.width, other.width, "framebuffer width mismatch");
        assert_eq!(self.height, other.height, "framebuffer height mismatch");
        let x_start = (x as usize).min(self.width);
        let y_start = (y as usize).min(self.height);
        let x_end = (x.saturating_add(rect_width) as usize).min(self.width);
        let y_end = (y.saturating_add(rect_height) as usize).min(self.height);
        if x_start >= x_end || y_start >= y_end {
            return;
        }

        if LINEAR {
            {
                let copy_width = x_end - x_start;
                let destination = self.data.as_mut_ptr().cast::<u8>();
                let source = other.data.as_ptr().cast::<u8>();
                for row in y_start..y_end {
                    let offset = row * self.width + x_start;
                    unsafe {
                        core::ptr::copy_nonoverlapping(
                            source.add(offset),
                            destination.add(offset),
                            copy_width,
                        );
                    }
                }
            }
        }

        if !LINEAR {
            for row in y_start..y_end {
                for column in x_start..x_end {
                    let color = other
                        .get_pixel(column as u32, row as u32)
                        .expect("copy source is in bounds");
                    self.set_pixel(column as u32, row as u32, color);
                }
            }
        }
    }

    /// Copy a clipped pixel rectangle within this framebuffer.
    ///
    /// Source and destination may overlap. The rectangle is clipped against
    /// both origins, so pixels outside the common in-bounds extent are left
    /// unchanged.
    pub fn copy_rect_within(
        &mut self,
        source_x: u32,
        source_y: u32,
        rect_width: u32,
        rect_height: u32,
        destination_x: u32,
        destination_y: u32,
    ) {
        let source_x = (source_x as usize).min(self.width);
        let source_y = (source_y as usize).min(self.height);
        let destination_x = (destination_x as usize).min(self.width);
        let destination_y = (destination_y as usize).min(self.height);
        let copy_width = (rect_width as usize)
            .min(self.width - source_x)
            .min(self.width - destination_x);
        let copy_height = (rect_height as usize)
            .min(self.height - source_y)
            .min(self.height - destination_y);
        if copy_width == 0 || copy_height == 0 {
            return;
        }

        if LINEAR {
            {
                let pixels = unsafe {
                    core::slice::from_raw_parts_mut(
                        self.data.as_mut_ptr().cast::<u8>(),
                        self.width * self.height,
                    )
                };
                copy_chunky_rect_within(
                    pixels,
                    self.width,
                    source_x,
                    source_y,
                    copy_width,
                    copy_height,
                    destination_x,
                    destination_y,
                );
            }
        }

        if !LINEAR {
            {
                let source = self.clone();
                for row in 0..copy_height {
                    for column in 0..copy_width {
                        let color = source
                            .get_pixel((source_x + column) as u32, (source_y + row) as u32)
                            .expect("copy source is in bounds");
                        self.set_pixel(
                            (destination_x + column) as u32,
                            (destination_y + row) as u32,
                            color,
                        );
                    }
                }
            }
        }
    }

    #[inline]
    fn fill_rect_packed(&mut self, x: u32, y: u32, rect_width: u32, rect_height: u32, color: C) {
        let x_start = (x as usize).min(self.width);
        let y_start = (y as usize).min(self.height);
        let x_end = (x.saturating_add(rect_width) as usize).min(self.width);
        let y_end = (y.saturating_add(rect_height) as usize).min(self.height);
        if x_start >= x_end || y_start >= y_end {
            return;
        }

        let value = color.to_index();
        let bits = index_bits::<C>();
        let groups = groups_per_row(self.width);
        let first_group = x_start / 8;
        let last_group = (x_end - 1) / 8;
        for row in y_start..y_end {
            for group in first_group..=last_group {
                let group_x = group * 8;
                let from = x_start.saturating_sub(group_x).min(8);
                let until = x_end.saturating_sub(group_x).min(8);
                let mask = (0xFFu8 >> from) & (0xFFu8 << (8 - until));
                let base = (row * groups + group) * bits;
                for plane in 0..bits {
                    let fill = if (value >> plane) & 1 == 1 {
                        0xFF
                    } else {
                        0x00
                    };
                    if mask == 0xFF {
                        self.data[base + plane] = fill;
                    } else if fill == 0xFF {
                        self.data[base + plane] |= mask;
                    } else {
                        self.data[base + plane] &= !mask;
                    }
                }
            }
        }
    }

    /// Expand the indexed buffer into RGBA using `palette`.
    ///
    /// Writes `width * height * 4` bytes of row-major `[r, g, b, a]` pixel
    /// data into `out`. Returns false (and writes nothing) if `out` is too
    /// small. The palette should define an entry for every index in the
    /// buffer.
    pub fn to_rgba(&self, palette: &Palette<C>, out: &mut [u8]) -> bool {
        let need = self.width * self.height * 4;
        if out.len() < need {
            return false;
        }
        let mut base = 0;
        for y in 0..self.height {
            for x in 0..self.width {
                let index = self.get_pixel(x as u32, y as u32).expect("pixel in bounds");
                out[base..base + 4].copy_from_slice(&palette.color(index).to_array());
                base += 4;
            }
        }
        true
    }
}

/// The default [`IndexedFrameBuffer`] is a 160×144 Game Boy screen,
/// cleared to index 0.
impl<C: ColorIndex, const LINEAR: bool> Default for IndexedFrameBuffer<C, LINEAR> {
    fn default() -> Self {
        Self::new(SCREEN_WIDTH, SCREEN_HEIGHT, C::from_u8(0))
    }
}

// ---------------------------------------------------------------------------
// Quantization
// ---------------------------------------------------------------------------

/// Find the palette entry closest to `color`.
///
/// Distance is summed squared channel difference over all four channels
/// (r, g, b, a), so transparent palette entries only win for transparent
/// input colors. Only the first `palette.count` entries are considered;
/// ties prefer the lower index.
pub fn quantize<C: ColorIndex>(palette: &Palette<C>, color: Rgba) -> C {
    let mut best = C::from_u8(0);
    let mut best_dist = u32::MAX;
    for i in 0..palette.count as usize {
        let entry = palette.colors[i];
        let dr = entry.r as i32 - color.r as i32;
        let dg = entry.g as i32 - color.g as i32;
        let db = entry.b as i32 - color.b as i32;
        let da = entry.a as i32 - color.a as i32;
        let dist = (dr * dr + dg * dg + db * db + da * da) as u32;
        if dist < best_dist {
            best_dist = dist;
            best = C::from_u8(i as u8);
        }
    }
    best
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn linear_and_packed_storage_agree_through_clipped_moves_and_blits() {
        for (width, height) in [(0, 0), (1, 1), (5, 7), (16, 16), (19, 13)] {
            let config = RenderConfig::new(width, height);
            let mut packed = RgbaIndexedFrameBuffer::<GbColor>::new(config.clone(), Rgba::WHITE);
            let mut linear = LinearRgbaIndexedFrameBuffer::<GbColor>::new(config, Rgba::WHITE);
            assert_eq!(linear.indices().len(), width as usize * height as usize);
            assert_eq!(linear.indices().as_ptr() as usize % 4, 0);
            let equal = |p: &RgbaIndexedFrameBuffer, l: &LinearRgbaIndexedFrameBuffer| {
                for y in 0..height {
                    for x in 0..width {
                        assert_eq!(p.get_index(x, y), l.get_index(x, y), "at {x},{y}");
                    }
                }
            };
            for i in 0..40u32 {
                let color = GbColor::from_u8((i % 4) as u8);
                packed.indexed_mut().fill_rect(i % 21, i % 15, 9, 4, color);
                linear.indexed_mut().fill_rect(i % 21, i % 15, 9, 4, color);
                let dx = i as i32 % 7 - 3;
                let dy = i as i32 % 5 - 2;
                packed.scroll_indices(dx, dy, color);
                linear.scroll_indices(dx, dy, color);
                packed.copy_rect_within(1, 1, 11, 8, i % 4, i % 3);
                linear.copy_rect_within(1, 1, 11, 8, i % 4, i % 3);
                equal(&packed, &linear);
                let tile = Tile::from_2bpp(&[
                    0x59, 0xA7, 0x18, 0xF0, 0xC3, 0x55, 0x0F, 0x88, 0xCC, 0x55, 0x87, 0xE1, 0x44,
                    0x23, 0xF8, 0x62,
                ]);
                packed.blit_gb_tile_indices(dx, dy, &tile, i % 2 == 0, i % 3 == 0, i % 5 == 0);
                linear.blit_gb_tile_indices(dx, dy, &tile, i % 2 == 0, i % 3 == 0, i % 5 == 0);
                equal(&packed, &linear);
            }
        }
    }
    use crate::palette::{GbaColor, GRAYSCALE_PALETTE, GRAYSCALE_SPRITE_PALETTE};
    use crate::tile::Tile;

    #[test]
    fn storage_sizes() {
        // The flagship case from the port plan: 160×144, 2bpp → 5,760 B.
        assert_eq!(packed_len::<GbColor>(SCREEN_WIDTH, SCREEN_HEIGHT), 5760);
        assert_eq!(packed_len::<GbColor>(160, 144), 5760);
        // 4-bit indices double the footprint.
        assert_eq!(packed_len::<GbaColor>(160, 144), 11520);
        assert_eq!(index_bits::<GbColor>(), 2);
        assert_eq!(index_bits::<GbaColor>(), 4);
        // The buffer itself is exactly that many bytes, no slack.
        let fb = IndexedFrameBuffer::<GbColor>::new(160, 144, GbColor::White);
        assert_eq!(fb.packed().len(), 5760);
        let gba = IndexedFrameBuffer::<GbaColor>::new(160, 144, GbaColor(0));
        assert_eq!(gba.packed().len(), 11520);
    }

    #[test]
    fn default_is_screen_sized_cleared() {
        let fb = IndexedFrameBuffer::<GbColor>::default();
        assert_eq!(fb.width(), SCREEN_WIDTH);
        assert_eq!(fb.height(), SCREEN_HEIGHT);
        assert_eq!(fb.len(), 160 * 144);
        assert_eq!(fb.get_pixel(0, 0), Some(GbColor::White));
        assert_eq!(fb.get_pixel(159, 143), Some(GbColor::White));
        let gba = IndexedFrameBuffer::<GbaColor>::default();
        assert_eq!(gba.get_pixel(159, 143), Some(GbaColor(0)));
    }

    #[test]
    fn packing_round_trip_gb() {
        let mut fb = IndexedFrameBuffer::<GbColor>::new(16, 8, GbColor::White);
        let pattern = [
            GbColor::White,
            GbColor::LightGray,
            GbColor::DarkGray,
            GbColor::Black,
        ];
        for y in 0..8u32 {
            for x in 0..16u32 {
                fb.set_pixel(x, y, pattern[((x + y) as usize) % 4]);
            }
        }
        for y in 0..8u32 {
            for x in 0..16u32 {
                assert_eq!(
                    fb.get_pixel(x, y),
                    Some(pattern[((x + y) as usize) % 4]),
                    "mismatch at ({x}, {y})"
                );
            }
        }
    }

    #[test]
    fn packing_round_trip_gba() {
        let mut fb = IndexedFrameBuffer::<GbaColor>::new(8, 4, GbaColor(0));
        for y in 0..4u32 {
            for x in 0..8u32 {
                fb.set_pixel(x, y, GbaColor(((x * 3 + y * 5) % 16) as u8));
            }
        }
        for y in 0..4u32 {
            for x in 0..8u32 {
                assert_eq!(
                    fb.get_pixel(x, y),
                    Some(GbaColor(((x * 3 + y * 5) % 16) as u8))
                );
            }
        }
    }

    #[test]
    fn packing_round_trip_non_multiple_of_8() {
        // 10×7 is not divisible by 8; the partial row group must stay
        // readable and never alias into the next row.
        let mut fb = IndexedFrameBuffer::<GbColor>::new(10, 7, GbColor::White);
        for y in 0..7u32 {
            for x in 0..10u32 {
                fb.set_pixel(x, y, GbColor::from_u8(((x + y) % 4) as u8));
            }
        }
        for y in 0..7u32 {
            for x in 0..10u32 {
                assert_eq!(
                    fb.get_pixel(x, y),
                    Some(GbColor::from_u8(((x + y) % 4) as u8))
                );
            }
        }
        // The unused bits of the partial group must read back as nothing:
        // those pixel positions are out of bounds.
        assert_eq!(fb.get_pixel(10, 0), None);
        assert_eq!(fb.get_pixel(0, 7), None);
    }

    #[test]
    fn packed_layout_is_gb_vram_bitplanes() {
        // Pin the exact byte layout: row of [1,0,3,0,2,0,1,0] packs to
        // plane 0 = 0b10100010 (bits 7,5,1), plane 1 = 0b00101000 (bits 5,3).
        let mut fb = IndexedFrameBuffer::<GbColor>::new(8, 1, GbColor::White);
        let row = [1u8, 0, 3, 0, 2, 0, 1, 0];
        for (x, &v) in row.iter().enumerate() {
            fb.set_pixel(x as u32, 0, GbColor::from_u8(v));
        }
        assert_eq!(fb.packed(), &[0xA2, 0x28]);
    }

    #[test]
    fn packed_data_feeds_tile_decoder() {
        // VRAM isomorphism: a GbColor 8×8 buffer's packed bytes are GB 2bpp
        // tile data, so Tile::from_2bpp decodes them 1:1.
        let mut fb = IndexedFrameBuffer::<GbColor>::new(8, 8, GbColor::White);
        for y in 0..8u32 {
            for x in 0..8u32 {
                fb.set_pixel(x, y, GbColor::from_u8(((x * y) % 4) as u8));
            }
        }
        let tile = Tile::from_2bpp(fb.packed());
        for y in 0..8 {
            for x in 0..8 {
                assert_eq!(tile.pixels[y][x], ((x * y) % 4) as u8);
            }
        }
    }

    #[test]
    fn bounds_are_checked() {
        let mut fb = IndexedFrameBuffer::<GbColor>::new(8, 4, GbColor::White);
        assert!(fb.set_pixel(7, 3, GbColor::Black));
        assert!(!fb.set_pixel(8, 0, GbColor::Black));
        assert!(!fb.set_pixel(0, 4, GbColor::Black));
        assert!(!fb.set_pixel(u32::MAX, 0, GbColor::Black));
        assert_eq!(fb.get_pixel(8, 0), None);
        assert_eq!(fb.get_pixel(0, 4), None);
        assert_eq!(fb.get_pixel(7, 3), Some(GbColor::Black));
    }

    #[test]
    fn clear_fills_every_pixel() {
        let mut fb = IndexedFrameBuffer::<GbColor>::new(10, 7, GbColor::Black);
        // Deface it.
        fb.fill_rect(0, 0, 10, 7, GbColor::LightGray);
        assert_eq!(fb.get_pixel(5, 3), Some(GbColor::LightGray));
        fb.clear(GbColor::Black);
        for y in 0..7u32 {
            for x in 0..10u32 {
                assert_eq!(fb.get_pixel(x, y), Some(GbColor::Black));
            }
        }
        assert_eq!(fb.packed(), &[0xFF; packed_len::<GbColor>(10, 7)]);
    }

    #[test]
    fn fill_rect_clamps_to_bounds() {
        let mut fb = IndexedFrameBuffer::<GbColor>::new(8, 8, GbColor::White);
        // Start beyond the edge and overflow the opposite edge.
        fb.fill_rect(4, 4, 100, 100, GbColor::Black);
        assert_eq!(fb.get_pixel(3, 3), Some(GbColor::White));
        assert_eq!(fb.get_pixel(4, 3), Some(GbColor::White));
        assert_eq!(fb.get_pixel(3, 4), Some(GbColor::White));
        assert_eq!(fb.get_pixel(4, 4), Some(GbColor::Black));
        assert_eq!(fb.get_pixel(7, 7), Some(GbColor::Black));
        // Fully out of bounds: no-op.
        fb.fill_rect(8, 8, 4, 4, GbColor::DarkGray);
        assert_eq!(fb.get_pixel(7, 7), Some(GbColor::Black));
    }

    #[test]
    fn fill_rect_preserves_pixels_outside_partial_groups() {
        let mut fb = IndexedFrameBuffer::<GbColor>::new(19, 3, GbColor::White);
        fb.fill_rect(3, 1, 13, 1, GbColor::DarkGray);
        for y in 0..3 {
            for x in 0..19 {
                let expected = if y == 1 && (3..16).contains(&x) {
                    GbColor::DarkGray
                } else {
                    GbColor::White
                };
                assert_eq!(fb.get_pixel(x, y), Some(expected), "({x}, {y})");
            }
        }
    }

    #[test]
    fn chunky_row_scroll_matches_reference_for_every_offset() {
        let mut storage = [0u32; 10];
        let storage_bytes = unsafe {
            core::slice::from_raw_parts_mut(storage.as_mut_ptr() as *mut u8, storage.len() * 4)
        };
        for width in [37, storage_bytes.len()] {
            let row = &mut storage_bytes[..width];
            let original: Vec<u8> = (0..row.len() as u8).collect();
            for dx in -(row.len() as i32 - 1)..row.len() as i32 {
                if dx == 0 {
                    continue;
                }
                row.copy_from_slice(&original);
                scroll_chunky_row(row, dx, 0xff);
                for (x, &actual) in row.iter().enumerate() {
                    let source_x = x as i32 - dx;
                    let expected = if (0..original.len() as i32).contains(&source_x) {
                        original[source_x as usize]
                    } else {
                        0xff
                    };
                    assert_eq!(actual, expected, "width {width}, offset {dx}, pixel {x}");
                }
            }
        }
    }

    #[test]
    fn scroll_moves_pixels_and_clears_exposed_edges() {
        let mut original = IndexedFrameBuffer::<GbColor>::new(5, 4, GbColor::White);
        for y in 0..4 {
            for x in 0..5 {
                original.set_pixel(x, y, GbColor::from_u8(((y * 5 + x) % 4) as u8));
            }
        }

        for (dx, dy) in [(2, 1), (-2, -1), (1, -2), (-1, 2)] {
            let mut shifted = original.clone();
            shifted.scroll(dx, dy, GbColor::Black);
            for y in 0..4i32 {
                for x in 0..5i32 {
                    let source_x = x - dx;
                    let source_y = y - dy;
                    let expected = if (0..5).contains(&source_x) && (0..4).contains(&source_y) {
                        original
                            .get_pixel(source_x as u32, source_y as u32)
                            .unwrap()
                    } else {
                        GbColor::Black
                    };
                    assert_eq!(
                        shifted.get_pixel(x as u32, y as u32),
                        Some(expected),
                        "offset ({dx}, {dy}), pixel ({x}, {y})"
                    );
                }
            }
        }
    }

    #[test]
    fn scroll_clears_when_offset_exceeds_dimensions() {
        let mut fb = IndexedFrameBuffer::<GbColor>::new(5, 4, GbColor::LightGray);
        fb.scroll(5, 0, GbColor::DarkGray);
        for y in 0..4 {
            for x in 0..5 {
                assert_eq!(fb.get_pixel(x, y), Some(GbColor::DarkGray));
            }
        }
    }

    #[test]
    fn copy_rect_from_preserves_pixels_outside_the_rectangle() {
        let mut source = IndexedFrameBuffer::<GbColor>::new(10, 7, GbColor::White);
        for y in 0..7 {
            for x in 0..10 {
                source.set_pixel(x, y, GbColor::from_u8(((x + y * 3) % 4) as u8));
            }
        }
        let mut destination = IndexedFrameBuffer::<GbColor>::new(10, 7, GbColor::Black);
        destination.copy_rect_from(&source, 2, 1, 5, 4);
        for y in 0..7 {
            for x in 0..10 {
                let expected = if (2..7).contains(&x) && (1..5).contains(&y) {
                    source.get_pixel(x, y).unwrap()
                } else {
                    GbColor::Black
                };
                assert_eq!(destination.get_pixel(x, y), Some(expected), "({x}, {y})");
            }
        }
    }

    #[test]
    fn copy_rect_within_is_overlap_safe_and_clipped() {
        let mut original = IndexedFrameBuffer::<GbColor>::new(10, 7, GbColor::White);
        for y in 0..7 {
            for x in 0..10 {
                original.set_pixel(x, y, GbColor::from_u8(((x + y * 3) % 4) as u8));
            }
        }

        for &(source_x, source_y, width, height, destination_x, destination_y) in &[
            (1, 1, 7, 5, 2, 0),
            (2, 0, 7, 5, 1, 1),
            (0, 0, 10, 6, 0, 1),
            (0, 1, 10, 6, 0, 0),
            (8, 5, 10, 10, 9, 6),
            (20, 20, 4, 4, 0, 0),
        ] {
            let mut actual = original.clone();
            actual.copy_rect_within(
                source_x,
                source_y,
                width,
                height,
                destination_x,
                destination_y,
            );

            let mut expected = original.clone();
            let copy_width = width
                .min(10u32.saturating_sub(source_x))
                .min(10u32.saturating_sub(destination_x));
            let copy_height = height
                .min(7u32.saturating_sub(source_y))
                .min(7u32.saturating_sub(destination_y));
            for row in 0..copy_height {
                for column in 0..copy_width {
                    let color = original
                        .get_pixel(source_x + column, source_y + row)
                        .unwrap();
                    expected.set_pixel(destination_x + column, destination_y + row, color);
                }
            }
            assert_eq!(
                actual, expected,
                "source ({source_x}, {source_y}), destination ({destination_x}, {destination_y})"
            );
        }
    }

    #[test]
    fn chunky_rect_copy_is_overlap_safe_in_every_direction() {
        let original: Vec<u8> = (0..70).map(|index| (index % 251) as u8).collect();
        for &(source_x, source_y, width, height, destination_x, destination_y) in &[
            (1, 1, 7, 5, 2, 0),
            (2, 0, 7, 5, 1, 1),
            (0, 0, 10, 6, 0, 1),
            (0, 1, 10, 6, 0, 0),
        ] {
            let mut actual = original.clone();
            copy_chunky_rect_within(
                &mut actual,
                10,
                source_x,
                source_y,
                width,
                height,
                destination_x,
                destination_y,
            );

            let mut expected = original.clone();
            for row in 0..height {
                for column in 0..width {
                    expected[(destination_y + row) * 10 + destination_x + column] =
                        original[(source_y + row) * 10 + source_x + column];
                }
            }
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn to_rgba_applies_palette() {
        let mut fb = IndexedFrameBuffer::<GbColor>::new(4, 2, GbColor::White);
        fb.set_pixel(0, 0, GbColor::Black);
        fb.set_pixel(3, 1, GbColor::DarkGray);
        let pal = GRAYSCALE_PALETTE;
        let mut out = [0u8; 4 * 2 * 4];
        assert!(fb.to_rgba(&pal, &mut out));
        assert_eq!(&out[0..4], &Rgba::rgb(0x00, 0x00, 0x00).to_array());
        assert_eq!(&out[1 * 4..2 * 4], &Rgba::rgb(0xFF, 0xFF, 0xFF).to_array());
        assert_eq!(
            &out[(3 + 1 * 4) * 4..(3 + 1 * 4) * 4 + 4],
            &Rgba::rgb(0x55, 0x55, 0x55).to_array()
        );
    }

    #[test]
    fn to_rgba_rejects_short_slice() {
        let fb = IndexedFrameBuffer::<GbColor>::new(4, 2, GbColor::White);
        let mut out = [0u8; 4 * 2 * 4 - 1];
        assert!(!fb.to_rgba(&GRAYSCALE_PALETTE, &mut out));
        assert_eq!(out, [0u8; 4 * 2 * 4 - 1]); // untouched
    }

    #[test]
    fn quantize_exact_match() {
        let pal = GRAYSCALE_PALETTE;
        assert_eq!(quantize(&pal, Rgba::rgb(0xFF, 0xFF, 0xFF)), GbColor::White);
        assert_eq!(
            quantize(&pal, Rgba::rgb(0xAA, 0xAA, 0xAA)),
            GbColor::LightGray
        );
        assert_eq!(
            quantize(&pal, Rgba::rgb(0x55, 0x55, 0x55)),
            GbColor::DarkGray
        );
        assert_eq!(quantize(&pal, Rgba::rgb(0x00, 0x00, 0x00)), GbColor::Black);
    }

    #[test]
    fn quantize_picks_nearest() {
        // Midway between white (255) and light gray (170) → light gray.
        let pal = GRAYSCALE_PALETTE;
        assert_eq!(quantize(&pal, Rgba::rgb(200, 200, 200)), GbColor::LightGray);
        // Midway between light gray (170) and dark gray (85) → dark gray.
        assert_eq!(
            quantize(&pal, Rgba::rgb(0x7F, 0x7F, 0x7F)),
            GbColor::DarkGray
        );
        // Darkest possible input → black.
        assert_eq!(quantize(&pal, Rgba::rgb(30, 30, 30)), GbColor::Black);
    }

    #[test]
    fn quantize_alpha_aware() {
        // Sprite palette entry 0 is transparent: an opaque dark pixel must
        // not quantize to it.
        let pal = GRAYSCALE_SPRITE_PALETTE;
        assert_eq!(pal.colors[0], Rgba::TRANSPARENT);
        assert_eq!(quantize(&pal, Rgba::rgb(0x00, 0x00, 0x00)), GbColor::Black);
        // A fully transparent pixel prefers the transparent entry.
        assert_eq!(quantize(&pal, Rgba::TRANSPARENT), GbColor::White);
    }

    #[test]
    fn quantize_gba_palette() {
        let mut colors = [Rgba::BLACK; 16];
        colors[0] = Rgba::rgb(0xFF, 0x00, 0x00);
        colors[1] = Rgba::rgb(0x00, 0xFF, 0x00);
        colors[2] = Rgba::rgb(0x00, 0x00, 0xFF);
        let pal = Palette::<GbaColor>::from_gba_palette(colors);
        assert_eq!(quantize(&pal, Rgba::rgb(0xFF, 0x00, 0x00)), GbaColor(0));
        assert_eq!(quantize(&pal, Rgba::rgb(0x00, 0xFF, 0x00)), GbaColor(1));
        assert_eq!(quantize(&pal, Rgba::rgb(0x00, 0x00, 0xFF)), GbaColor(2));
        // Midway between red and green, the input lands on the closer one.
        assert_eq!(quantize(&pal, Rgba::rgb(0xC0, 0x40, 0x00)), GbaColor(0));
    }
}

// ---------------------------------------------------------------------------
// DefaultPalette — per-index-type construction default
// ---------------------------------------------------------------------------

/// The palette [`RgbaIndexedFrameBuffer`] quantizes against when constructed
/// without an explicit palette.
pub trait DefaultPalette: ColorIndex {
    /// Default quantization/display palette for this index type.
    fn default_palette() -> Palette<Self>;
}

impl DefaultPalette for GbColor {
    fn default_palette() -> Palette<Self> {
        // The pokered render chain draws in GRAYSCALE shades, so quantizing
        // against the grayscale palette is exact for every current draw call.
        GRAYSCALE_PALETTE
    }
}

impl DefaultPalette for GbaColor {
    fn default_palette() -> Palette<Self> {
        let mut colors = [Rgba::BLACK; 16];
        for i in 0..16 {
            let v = (255 - i * 17) as u8;
            colors[i] = Rgba::rgb(v, v, v);
        }
        Palette::<GbaColor>::from_gba_palette(colors)
    }
}

// ---------------------------------------------------------------------------
// FbSurface — shared draw/present surface trait
// ---------------------------------------------------------------------------

/// A framebuffer draw surface shared by the engine's RGBA [`FrameBuffer`]
/// and the indexed [`RgbaIndexedFrameBuffer`].
///
/// Draw code written against RGBA (`set_pixel` / `fill_rect` / `clear`)
/// compiles and behaves identically on both: the indexed surface quantizes
/// every RGBA write through its base palette. `present_into` dumps the
/// final RGBA pixels (applying the display palette for indexed surfaces),
/// and `pixel_rgba` reads a single pixel (used by terminal halfblock
/// presenters).
pub trait FbSurface: Sized {
    /// Create a new `width × height` surface, cleared to black.
    fn new_screen(width: u32, height: u32) -> Self;
    /// Screen width in pixels.
    fn width(&self) -> u32;
    /// Screen height in pixels.
    fn height(&self) -> u32;
    /// Set a single pixel. Returns false if out of bounds.
    fn set_pixel(&mut self, x: u32, y: u32, color: Rgba) -> bool;
    /// Get the current color of a single pixel. Returns None if out of bounds.
    fn get_pixel(&self, x: u32, y: u32) -> Option<Rgba>;
    /// Clear the entire surface to a single color.
    fn clear(&mut self, color: Rgba);
    /// Fill a rectangular region with a color (clamped to bounds).
    fn fill_rect(&mut self, x: u32, y: u32, rect_width: u32, rect_height: u32, color: Rgba);
    /// Blit one decoded Game Boy tile, clipped to the surface.
    ///
    /// The default implementation preserves the ordinary RGBA drawing
    /// semantics. Indexed surfaces override it so the four palette entries
    /// are quantized once per tile rather than once per pixel.
    fn blit_gb_tile(
        &mut self,
        x: i32,
        y: i32,
        tile: &Tile,
        palette: &Palette,
        transparent: bool,
        flip_x: bool,
        flip_y: bool,
    ) {
        let width = self.width() as i32;
        let height = self.height() as i32;
        for dst_row in 0..TILE_PIXELS {
            let dst_y = y + dst_row as i32;
            if dst_y < 0 || dst_y >= height {
                continue;
            }
            let src_row = if flip_y {
                TILE_PIXELS - 1 - dst_row
            } else {
                dst_row
            };
            for dst_col in 0..TILE_PIXELS {
                let dst_x = x + dst_col as i32;
                if dst_x < 0 || dst_x >= width {
                    continue;
                }
                let src_col = if flip_x {
                    TILE_PIXELS - 1 - dst_col
                } else {
                    dst_col
                };
                let color = palette.color(GbColor::from_u8(tile.pixels[src_row][src_col]));
                if transparent && color == Rgba::TRANSPARENT {
                    continue;
                }
                self.set_pixel(dst_x as u32, dst_y as u32, color);
            }
        }
    }
    /// Read a single pixel as RGBA; out-of-bounds reads return transparent.
    fn pixel_rgba(&self, x: u32, y: u32) -> Rgba {
        self.get_pixel(x, y).unwrap_or(Rgba::TRANSPARENT)
    }
    /// Dump the whole surface as row-major RGBA into `out`, which must hold
    /// at least `width * height * 4` bytes.
    fn present_into(&self, out: &mut [u8]);
}

impl FbSurface for dotzuki_engine::render::FrameBuffer {
    fn new_screen(width: u32, height: u32) -> Self {
        Self::new(RenderConfig::new(width, height), Rgba::BLACK)
    }
    fn width(&self) -> u32 {
        self.width
    }
    fn height(&self) -> u32 {
        self.height
    }
    fn set_pixel(&mut self, x: u32, y: u32, color: Rgba) -> bool {
        Self::set_pixel(self, x, y, color)
    }
    fn get_pixel(&self, x: u32, y: u32) -> Option<Rgba> {
        Self::get_pixel(self, x, y)
    }
    fn clear(&mut self, color: Rgba) {
        Self::clear(self, color)
    }
    fn fill_rect(&mut self, x: u32, y: u32, rect_width: u32, rect_height: u32, color: Rgba) {
        Self::fill_rect(self, x, y, rect_width, rect_height, color)
    }
    fn present_into(&self, out: &mut [u8]) {
        assert!(out.len() >= self.data.len(), "present buffer too small");
        out[..self.data.len()].copy_from_slice(&self.data);
    }
}

// ---------------------------------------------------------------------------
// RgbaIndexedFrameBuffer — RGBA facade over IndexedFrameBuffer
// ---------------------------------------------------------------------------

/// An [`IndexedFrameBuffer`] with an RGBA-facing facade: RGBA writes are
/// quantized through a fixed *base* palette (so drawing is stable no matter
/// what display effect is active), while a separate *display* palette is
/// applied at present time.
///
/// Fades and flashes become palette operations, the way real GB hardware
/// does them: swap the display palette ([`Self::set_palette`],
/// [`Self::remap_shades`], [`Self::scale_shades`], [`Self::apply_bgp`])
/// instead of touching every pixel. Hosted buffers stay packed 2bpp — 5,760
/// bytes for a 160×144 screen instead of 92,160 — while GBA builds use the
/// module's DMA-friendly one-byte-per-pixel representation.
///
/// `base` doubles as the initial display palette; [`Self::reset_palette`]
/// restores it. The indexed API remains reachable via [`Self::indexed`] /
/// [`Self::indexed_mut`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RgbaIndexedFrameBuffer<C: ColorIndex = GbColor, const LINEAR: bool = false> {
    /// The indexed pixel storage.
    buffer: IndexedFrameBuffer<C, LINEAR>,
    /// Quantization palette: RGBA writes map to the nearest entry's index.
    base: Palette<C>,
    /// True when `base` is the standard opaque 0/85/170/255 gray ramp.
    /// This enables an O(1) quantizer for the overwhelmingly common path.
    fast_grayscale: bool,
    /// Display palette applied at present time; fades/flashes remap this.
    pub palette: Palette<C>,
}

impl<C: ColorIndex, const LINEAR: bool> RgbaIndexedFrameBuffer<C, LINEAR> {
    /// Create a `config`-sized buffer with an explicit base palette, cleared
    /// to `clear` (quantized through `base`).
    pub fn with_palette(config: RenderConfig, clear: Rgba, base: Palette<C>) -> Self {
        let fast_grayscale = base.count == 4
            && base.colors[0] == Rgba::rgb(0xFF, 0xFF, 0xFF)
            && base.colors[1] == Rgba::rgb(0xAA, 0xAA, 0xAA)
            && base.colors[2] == Rgba::rgb(0x55, 0x55, 0x55)
            && base.colors[3] == Rgba::rgb(0x00, 0x00, 0x00);
        let mut fb = Self {
            buffer: IndexedFrameBuffer::new(
                config.screen_width as usize,
                config.screen_height as usize,
                C::from_u8(0),
            ),
            palette: base,
            base,
            fast_grayscale,
        };
        fb.clear(clear);
        fb
    }

    /// The current display palette.
    #[inline]
    pub fn display_palette(&self) -> &Palette<C> {
        &self.palette
    }

    /// Replace the display palette (fade/flash effect).
    pub fn set_palette(&mut self, palette: Palette<C>) {
        self.palette = palette;
    }

    /// Restore the display palette to the base palette.
    pub fn reset_palette(&mut self) {
        self.palette = self.base;
    }

    /// Remap every display shade through `map`: display color `i` becomes the
    /// base palette entry `map[i]`. This is the indexed-buffer equivalent of
    /// the per-pixel `remap_shades` loops (rBGP-style register writes).
    pub fn remap_shades(&mut self, map: &[u8]) {
        let count = self.palette.count as usize;
        for i in 0..count {
            let mapped = map.get(i).copied().unwrap_or(i as u8) as usize % count;
            self.palette.colors[i] = self.base.colors[mapped];
        }
        self.palette.count = self.base.count;
    }

    /// Scale the display colors toward black by `scale` (0.0 = black,
    /// 1.0 = base palette). Alpha is preserved. Mirrors the per-pixel
    /// "brighten/darken" loops (e.g. the Ghost Marowak reveal).
    pub fn scale_shades(&mut self, scale: f32) {
        let scale = scale.clamp(0.0, 1.0);
        for i in 0..self.palette.count as usize {
            let c = self.base.colors[i];
            self.palette.colors[i] = Rgba::new(
                (c.r as f32 * scale) as u8,
                (c.g as f32 * scale) as u8,
                (c.b as f32 * scale) as u8,
                c.a,
            );
        }
    }

    /// Read-only access to the underlying indexed buffer.
    #[inline]
    pub fn indexed(&self) -> &IndexedFrameBuffer<C, LINEAR> {
        &self.buffer
    }

    /// Mutable access to the underlying indexed buffer (C-index API).
    #[inline]
    pub fn indexed_mut(&mut self) -> &mut IndexedFrameBuffer<C, LINEAR> {
        &mut self.buffer
    }

    /// Expand the buffer into RGBA using the *display* palette.
    /// Writes `width * height * 4` bytes into `out`; returns false (and
    /// writes nothing) if `out` is too small.
    pub fn to_rgba(&self, out: &mut [u8]) -> bool {
        self.buffer.to_rgba(&self.palette, out)
    }

    /// Copy the pixels and display palette of `other` into this buffer.
    /// Both buffers must have the same dimensions.
    pub fn copy_from(&mut self, other: &Self) {
        self.copy_from_with(other, |destination, source| {
            destination.copy_from_slice(source);
        });
    }

    /// Copy from `other`, delegating the backing-storage transfer to
    /// `copy_pixels`.
    ///
    /// Packed buffers pass planar bytes to the callback. Linear buffers pass
    /// their one-byte-per-pixel storage, so a
    /// platform frontend can use a hardware copy engine without exposing
    /// renderer internals. The callback must copy every source byte into the
    /// equally sized destination slice before returning.
    ///
    /// Both buffers must have the same dimensions.
    pub fn copy_from_with<F>(&mut self, other: &Self, copy_pixels: F)
    where
        F: FnOnce(&mut [u8], &[u8]),
    {
        assert_eq!(self.width(), other.width(), "framebuffer width mismatch");
        assert_eq!(self.height(), other.height(), "framebuffer height mismatch");

        copy_pixels(self.buffer.bytes_mut(), other.buffer.bytes());

        self.palette = other.palette;
        self.base = other.base;
        self.fast_grayscale = other.fast_grayscale;
    }

    /// Copy a clipped pixel rectangle from `other` at the same coordinates,
    /// preserving all palette state and pixels outside the rectangle.
    pub fn copy_rect_from(
        &mut self,
        other: &Self,
        x: u32,
        y: u32,
        rect_width: u32,
        rect_height: u32,
    ) {
        self.buffer
            .copy_rect_from(&other.buffer, x, y, rect_width, rect_height);
    }

    /// Copy a clipped, overlap-safe pixel rectangle within this framebuffer.
    /// Palette state is unchanged.
    pub fn copy_rect_within(
        &mut self,
        source_x: u32,
        source_y: u32,
        rect_width: u32,
        rect_height: u32,
        destination_x: u32,
        destination_y: u32,
    ) {
        self.buffer.copy_rect_within(
            source_x,
            source_y,
            rect_width,
            rect_height,
            destination_x,
            destination_y,
        );
    }

    /// Move the indexed pixels by `(dx, dy)`, filling exposed edges with
    /// `clear`. The display and quantization palettes are unchanged.
    pub fn scroll_indices(&mut self, dx: i32, dy: i32, clear: C) {
        self.buffer.scroll(dx, dy, clear);
    }

    /// Set a single pixel by palette index. Returns false if out of bounds.
    pub fn set_pixel_index(&mut self, x: u32, y: u32, color: C) -> bool {
        self.buffer.set_pixel(x, y, color)
    }

    /// Get the palette index of a single pixel. Returns None if out of bounds.
    pub fn get_index(&self, x: u32, y: u32) -> Option<C> {
        self.buffer.get_pixel(x, y)
    }

    /// Clear the entire buffer to a single palette index.
    pub fn clear_index(&mut self, color: C) {
        self.buffer.clear(color);
    }

    /// Total number of pixels.
    #[inline]
    pub fn len(&self) -> usize {
        self.buffer.len()
    }

    /// Screen width in pixels.
    #[inline]
    pub fn width(&self) -> u32 {
        self.buffer.width() as u32
    }

    /// Screen height in pixels.
    #[inline]
    pub fn height(&self) -> u32 {
        self.buffer.height() as u32
    }

    /// Whether the buffer holds no pixels.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }

    /// Set a single pixel, quantized through the base palette.
    /// Returns false if out of bounds.
    pub fn set_pixel(&mut self, x: u32, y: u32, color: Rgba) -> bool {
        let index = self.quantize_color(color);
        self.buffer.set_pixel(x, y, index)
    }

    /// Get the current display color of a single pixel (through the display
    /// palette). Returns None if out of bounds.
    pub fn get_pixel(&self, x: u32, y: u32) -> Option<Rgba> {
        self.buffer.get_pixel(x, y).map(|i| self.palette.color(i))
    }

    /// Clear the entire buffer to a single color (quantized through the base
    /// palette).
    ///
    /// Also restores the display palette to the base palette. This mirrors
    /// the RGBA buffer's contract — after a clear the framebuffer is in a
    /// pristine state — and is what prevents fade/flash palettes from
    /// leaking into the next frame: every frame starts with a clear, so the
    /// display mapping always begins from the base and effects re-apply
    /// their palette at the end of the frame.
    pub fn clear(&mut self, color: Rgba) {
        let index = self.quantize_color(color);
        self.buffer.clear(index);
        self.palette = self.base;
    }

    /// Fill a rectangular region with a color (quantized through the base
    /// palette). Coordinates are clamped to buffer bounds.
    pub fn fill_rect(&mut self, x: u32, y: u32, rect_width: u32, rect_height: u32, color: Rgba) {
        let index = self.quantize_color(color);
        self.buffer.fill_rect(x, y, rect_width, rect_height, index);
    }

    /// Blit one decoded Game Boy tile through `palette`, clipped to the
    /// framebuffer. The four RGBA palette entries are converted to the base
    /// indices once, then reused for every source pixel.
    #[inline]
    pub fn blit_gb_tile(
        &mut self,
        x: i32,
        y: i32,
        tile: &Tile,
        palette: &Palette,
        transparent: bool,
        flip_x: bool,
        flip_y: bool,
    ) {
        let rgba = [
            palette.color(GbColor::White),
            palette.color(GbColor::LightGray),
            palette.color(GbColor::DarkGray),
            palette.color(GbColor::Black),
        ];
        let mapped = [
            self.quantize_color(rgba[0]),
            self.quantize_color(rgba[1]),
            self.quantize_color(rgba[2]),
            self.quantize_color(rgba[3]),
        ];
        let width = self.width() as i32;
        let height = self.height() as i32;

        // Title screens, dialogue portraits and most GB sprites already use
        // the framebuffer's native shade order. On the GBA those tiles can
        // bypass the generic clipped/remapped loop entirely. Palette entry
        // zero is allowed to quantize differently when it is transparent,
        // because that source index is skipped rather than written.
        if LINEAR {
            if !flip_x
                && !flip_y
                && x >= 0
                && y >= 0
                && x + TILE_PIXELS as i32 <= width
                && y + TILE_PIXELS as i32 <= height
            {
                let transparent_zero = transparent && rgba[0] == Rgba::TRANSPARENT;
                let transparent_nonzero =
                    transparent && rgba[1..].iter().any(|color| *color == Rgba::TRANSPARENT);
                let identity_mapping = mapped.iter().enumerate().all(|(index, color)| {
                    (index == 0 && transparent_zero) || color.to_index() == index
                });

                if identity_mapping && !transparent_nonzero {
                    let destination = self.buffer.data.as_mut_ptr() as *mut u8;
                    for row in 0..TILE_PIXELS {
                        let source = tile.pixels[row].as_ptr();
                        let target = unsafe {
                            destination.add((y as usize + row) * width as usize + x as usize)
                        };
                        if transparent_zero {
                            for column in 0..TILE_PIXELS {
                                let value = unsafe { source.add(column).read() };
                                if value != 0 {
                                    unsafe { target.add(column).write(value) };
                                }
                            }
                        } else {
                            unsafe { core::ptr::copy_nonoverlapping(source, target, TILE_PIXELS) };
                        }
                    }
                    return;
                }
            }
        }

        let tile_size = TILE_PIXELS as i32;
        let x_start = x.saturating_neg().clamp(0, tile_size) as usize;
        let y_start = y.saturating_neg().clamp(0, tile_size) as usize;
        let x_end = width.saturating_sub(x).clamp(0, tile_size) as usize;
        let y_end = height.saturating_sub(y).clamp(0, tile_size) as usize;
        if x_start >= x_end || y_start >= y_end {
            return;
        }

        let destination = self.buffer.data.as_mut_ptr() as *mut u8;

        for dst_row in y_start..y_end {
            let src_row = if flip_y {
                TILE_PIXELS - 1 - dst_row
            } else {
                dst_row
            };
            for dst_col in x_start..x_end {
                let src_col = if flip_x {
                    TILE_PIXELS - 1 - dst_col
                } else {
                    dst_col
                };
                let source = (tile.pixels[src_row][src_col] & 0x03) as usize;
                if transparent && rgba[source] == Rgba::TRANSPARENT {
                    continue;
                }
                if LINEAR {
                    unsafe {
                        let offset = (y + dst_row as i32) as usize * width as usize
                            + (x + dst_col as i32) as usize;
                        destination
                            .add(offset)
                            .write(mapped[source].to_index() as u8);
                    }
                }
                if !LINEAR {
                    self.buffer.set_pixel(
                        (x + dst_col as i32) as u32,
                        (y + dst_row as i32) as u32,
                        mapped[source],
                    );
                }
            }
        }
    }

    /// Copy a horizontal line of RGBA data into the buffer (each pixel
    /// quantized through the base palette). `src` must be exactly
    /// `count * 4` bytes. Returns false if the line goes out of bounds.
    pub fn blit_row(&mut self, x: u32, y: u32, src: &[u8], count: u32) -> bool {
        if y >= self.height() || x >= self.width() {
            return false;
        }
        let actual_count = count.min(self.width() - x) as usize;
        let src_bytes = actual_count * 4;
        if src.len() < src_bytes {
            return false;
        }
        for i in 0..actual_count {
            let off = i * 4;
            let c = Rgba::new(src[off], src[off + 1], src[off + 2], src[off + 3]);
            let index = self.quantize_color(c);
            self.buffer.set_pixel(x + i as u32, y, index);
        }
        true
    }

    #[inline]
    fn quantize_color(&self, color: Rgba) -> C {
        if self.fast_grayscale && color.a == 0xFF && color.r == color.g && color.g == color.b {
            // Exact nearest-color boundaries for [255, 170, 85, 0]. At a
            // midpoint the generic quantizer prefers the lower index.
            let index = match color.r {
                213..=255 => 0,
                128..=212 => 1,
                43..=127 => 2,
                _ => 3,
            };
            C::from_u8(index)
        } else {
            quantize(&self.base, color)
        }
    }

    /// Save the framebuffer as a PNG file (display palette applied).
    #[cfg(any(feature = "gpu", feature = "image-assets"))]
    pub fn save_png(&self, path: &std::path::Path) -> std::io::Result<()> {
        use image::{ImageBuffer, Rgba as ImgRgba};
        let w = self.width() as u32;
        let h = self.height() as u32;
        let mut rgba = vec![0u8; (w * h * 4) as usize];
        self.to_rgba(&mut rgba);
        let img: ImageBuffer<ImgRgba<u8>, _> =
            ImageBuffer::from_raw(w, h, rgba).expect("framebuffer size mismatch");
        img.save(path)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
    }
}

impl<const LINEAR: bool> RgbaIndexedFrameBuffer<GbColor, LINEAR> {
    /// Blit a tile whose 2-bit pixel values already use the framebuffer's
    /// index order. This bypasses RGBA palette conversion entirely.
    ///
    /// Use this for GB backgrounds (and other identity-palette tiles). When
    /// `transparent_zero` is set, source index zero leaves the destination
    /// unchanged, matching Game Boy OBJ transparency.
    #[inline]
    pub fn blit_gb_tile_indices(
        &mut self,
        x: i32,
        y: i32,
        tile: &Tile,
        transparent_zero: bool,
        flip_x: bool,
        flip_y: bool,
    ) {
        let width = self.width() as i32;
        let height = self.height() as i32;

        // The GBA framebuffer is one byte per pixel. The overwhelmingly
        // common aligned/background case is eight short row copies with no
        // per-pixel bounds checks or palette work.
        if LINEAR {
            if !transparent_zero
                && !flip_x
                && !flip_y
                && x >= 0
                && y >= 0
                && x + TILE_PIXELS as i32 <= width
                && y + TILE_PIXELS as i32 <= height
            {
                let destination = self.buffer.data.as_mut_ptr() as *mut u8;
                let width = width as usize;
                let x = x as usize;
                let y = y as usize;

                // Pick one copy shape per tile rather than branching for every
                // row. The bounds checks above cover all eight source and
                // destination rows. Tile rows are word-aligned because Tile has
                // 4-byte alignment and every row is eight bytes.
                if width & 3 == 0 && x & 3 == 0 {
                    for row in 0..TILE_PIXELS {
                        unsafe {
                            let source = tile.pixels[row].as_ptr() as *const u32;
                            let destination = destination.add((y + row) * width + x) as *mut u32;
                            destination.write(source.read());
                            destination.add(1).write(source.add(1).read());
                        }
                    }
                } else if width & 1 == 0 && x & 1 == 0 {
                    // Smooth 2 px scrolling keeps halfword alignment even when
                    // the destination is between word boundaries.
                    for row in 0..TILE_PIXELS {
                        unsafe {
                            let source = tile.pixels[row].as_ptr() as *const u16;
                            let destination = destination.add((y + row) * width + x) as *mut u16;
                            for halfword in 0..4 {
                                destination.add(halfword).write(source.add(halfword).read());
                            }
                        }
                    }
                } else {
                    for row in 0..TILE_PIXELS {
                        unsafe {
                            core::ptr::copy_nonoverlapping(
                                tile.pixels[row].as_ptr(),
                                destination.add((y + row) * width + x),
                                TILE_PIXELS,
                            );
                        }
                    }
                }
                return;
            }
        }

        let tile_size = TILE_PIXELS as i32;
        let x_start = x.saturating_neg().clamp(0, tile_size) as usize;
        let y_start = y.saturating_neg().clamp(0, tile_size) as usize;
        let x_end = width.saturating_sub(x).clamp(0, tile_size) as usize;
        let y_end = height.saturating_sub(y).clamp(0, tile_size) as usize;
        if x_start >= x_end || y_start >= y_end {
            return;
        }

        if LINEAR {
            {
                let destination = self.buffer.data.as_mut_ptr() as *mut u8;
                if !transparent_zero && !flip_x && !flip_y {
                    let copy_width = x_end - x_start;
                    let destination_x = (x + x_start as i32) as usize;
                    let destination_y = (y + y_start as i32) as usize;
                    let source = unsafe { tile.pixels[y_start].as_ptr().add(x_start) };
                    let target =
                        unsafe { destination.add(destination_y * width as usize + destination_x) };

                    // Clipped scrolling exposes 2/4/6-pixel strips. Choose the
                    // copy width once per tile so those strips retain the same
                    // aligned halfword/word writes as a fully visible tile.
                    if width as usize & 3 == 0
                        && (source as usize | target as usize | copy_width) & 3 == 0
                    {
                        let words = copy_width / 4;
                        for dst_row in y_start..y_end {
                            unsafe {
                                let source =
                                    tile.pixels[dst_row].as_ptr().add(x_start) as *const u32;
                                let target = destination.add(
                                    (y + dst_row as i32) as usize * width as usize + destination_x,
                                ) as *mut u32;
                                for word in 0..words {
                                    target.add(word).write(source.add(word).read());
                                }
                            }
                        }
                    } else if width as usize & 1 == 0
                        && (source as usize | target as usize | copy_width) & 1 == 0
                    {
                        let halfwords = copy_width / 2;
                        for dst_row in y_start..y_end {
                            unsafe {
                                let source =
                                    tile.pixels[dst_row].as_ptr().add(x_start) as *const u16;
                                let target = destination.add(
                                    (y + dst_row as i32) as usize * width as usize + destination_x,
                                ) as *mut u16;
                                for halfword in 0..halfwords {
                                    target.add(halfword).write(source.add(halfword).read());
                                }
                            }
                        }
                    } else {
                        for dst_row in y_start..y_end {
                            unsafe {
                                core::ptr::copy_nonoverlapping(
                                    tile.pixels[dst_row].as_ptr().add(x_start),
                                    destination.add(
                                        (y + dst_row as i32) as usize * width as usize
                                            + destination_x,
                                    ),
                                    copy_width,
                                );
                            }
                        }
                    }
                    return;
                }

                for dst_row in y_start..y_end {
                    let src_row = if flip_y {
                        TILE_PIXELS - 1 - dst_row
                    } else {
                        dst_row
                    };
                    for dst_col in x_start..x_end {
                        let src_col = if flip_x {
                            TILE_PIXELS - 1 - dst_col
                        } else {
                            dst_col
                        };
                        let source = tile.pixels[src_row][src_col] & 0x03;
                        if transparent_zero && source == 0 {
                            continue;
                        }
                        unsafe {
                            let offset = (y + dst_row as i32) as usize * width as usize
                                + (x + dst_col as i32) as usize;
                            destination.add(offset).write(source);
                        }
                    }
                }
            }
        }
        if !LINEAR {
            for dst_row in y_start..y_end {
                let src_row = if flip_y {
                    TILE_PIXELS - 1 - dst_row
                } else {
                    dst_row
                };
                for dst_col in x_start..x_end {
                    let src_col = if flip_x {
                        TILE_PIXELS - 1 - dst_col
                    } else {
                        dst_col
                    };
                    let source = tile.pixels[src_row][src_col] & 0x03;
                    if transparent_zero && source == 0 {
                        continue;
                    }
                    self.buffer.set_pixel(
                        (x + dst_col as i32) as u32,
                        (y + dst_row as i32) as u32,
                        GbColor::from_u8(source),
                    );
                }
            }
        }
    }
}

impl<C: ColorIndex + DefaultPalette, const LINEAR: bool> RgbaIndexedFrameBuffer<C, LINEAR> {
    /// Create a `config`-sized buffer using the type's default base palette,
    /// cleared to `clear`.
    pub fn new(config: RenderConfig, clear: Rgba) -> Self {
        Self::with_palette(config, clear, C::default_palette())
    }
}

impl<const LINEAR: bool> RgbaIndexedFrameBuffer<GbColor, LINEAR> {
    /// Apply a DMG BGP register byte: display color `i` becomes the base
    /// palette's shade `(bgp >> (2 * i)) & 3`. This is exactly how the
    /// original hardware performs fades (by writing the BGP register).
    pub fn apply_bgp(&mut self, bgp: u8) {
        let mut remapped = [0u8; 4];
        for i in 0..4 {
            remapped[i] = (bgp >> (2 * i)) & 3;
        }
        self.remap_shades(&remapped);
    }
}

impl<C: ColorIndex + DefaultPalette, const LINEAR: bool> FbSurface
    for RgbaIndexedFrameBuffer<C, LINEAR>
{
    fn new_screen(width: u32, height: u32) -> Self {
        Self::new(RenderConfig::new(width, height), Rgba::BLACK)
    }
    fn width(&self) -> u32 {
        self.buffer.width() as u32
    }
    fn height(&self) -> u32 {
        self.buffer.height() as u32
    }
    fn set_pixel(&mut self, x: u32, y: u32, color: Rgba) -> bool {
        self.set_pixel(x, y, color)
    }
    fn get_pixel(&self, x: u32, y: u32) -> Option<Rgba> {
        self.get_pixel(x, y)
    }
    fn clear(&mut self, color: Rgba) {
        self.clear(color)
    }
    fn fill_rect(&mut self, x: u32, y: u32, rect_width: u32, rect_height: u32, color: Rgba) {
        self.fill_rect(x, y, rect_width, rect_height, color)
    }
    fn blit_gb_tile(
        &mut self,
        x: i32,
        y: i32,
        tile: &Tile,
        palette: &Palette,
        transparent: bool,
        flip_x: bool,
        flip_y: bool,
    ) {
        self.blit_gb_tile(x, y, tile, palette, transparent, flip_x, flip_y)
    }
    fn present_into(&self, out: &mut [u8]) {
        assert!(out.len() >= self.len() * 4, "present buffer too small");
        self.to_rgba(out);
    }
}

#[cfg(test)]
mod facade_tests {
    use super::*;
    use crate::palette::GRAYSCALE_SPRITE_PALETTE;

    fn fb() -> RgbaIndexedFrameBuffer<GbColor> {
        RgbaIndexedFrameBuffer::new(RenderConfig::new(160, 144), Rgba::WHITE)
    }

    #[test]
    fn decoded_tiles_are_word_aligned_without_padding() {
        assert_eq!(core::mem::align_of::<Tile>(), 4);
        assert_eq!(core::mem::size_of::<Tile>(), 64);
    }

    #[test]
    fn storage_is_packed() {
        let fb = fb();
        assert_eq!(fb.len(), 160 * 144);
        assert_eq!(fb.packed().len(), 5760);
        assert_eq!(fb.packed().len(), packed_len::<GbColor>(160, 144));
    }

    #[test]
    fn grayscale_round_trips_exactly() {
        let mut fb = fb();
        let colors = [
            Rgba::WHITE,
            Rgba::rgb(0xAA, 0xAA, 0xAA),
            Rgba::rgb(0x55, 0x55, 0x55),
            Rgba::BLACK,
        ];
        for (i, &c) in colors.iter().enumerate() {
            assert!(fb.set_pixel(i as u32, 0, c));
        }
        for (i, &c) in colors.iter().enumerate() {
            assert_eq!(fb.get_pixel(i as u32, 0), Some(c));
            assert_eq!(fb.get_index(i as u32, 0), Some(GbColor::from_u8(i as u8)));
        }
    }

    #[test]
    fn fast_grayscale_quantizer_matches_generic_for_every_gray() {
        let mut fb = RgbaIndexedFrameBuffer::<GbColor>::new(RenderConfig::new(256, 1), Rgba::WHITE);
        assert!(fb.fast_grayscale);
        for gray in 0..=u8::MAX {
            let color = Rgba::rgb(gray, gray, gray);
            assert!(fb.set_pixel(gray as u32, 0, color));
            assert_eq!(
                fb.get_index(gray as u32, 0),
                Some(quantize(&GRAYSCALE_PALETTE, color)),
                "gray {gray}"
            );
        }
    }

    #[test]
    fn near_grays_quantize_to_nearest_shade() {
        let mut fb = fb();
        // 0xC0 → light gray (170), 0x80 → light gray (170), 0x40 → dark gray.
        fb.set_pixel(0, 0, Rgba::rgb(0xC0, 0xC0, 0xC0));
        fb.set_pixel(1, 0, Rgba::rgb(0x80, 0x80, 0x80));
        fb.set_pixel(2, 0, Rgba::rgb(0x40, 0x40, 0x40));
        assert_eq!(fb.get_index(0, 0), Some(GbColor::LightGray));
        assert_eq!(fb.get_index(1, 0), Some(GbColor::LightGray));
        assert_eq!(fb.get_index(2, 0), Some(GbColor::DarkGray));
    }

    #[test]
    fn transparent_writes_pick_nearest_opaque_shade() {
        // GRAYSCALE_PALETTE has no transparent entry, so a transparent write
        // quantizes to the nearest opaque color: black. Presenters ignore
        // alpha (native/web textures, TUI halfblocks), so this matches what
        // the old RGBA buffer displayed for such pixels.
        let mut fb = fb();
        fb.set_pixel(3, 3, Rgba::TRANSPARENT);
        assert_eq!(fb.get_index(3, 3), Some(GbColor::Black));
    }

    #[test]
    fn bounds_checked_rgba_facade() {
        let mut fb = fb();
        assert!(fb.set_pixel(159, 143, Rgba::BLACK));
        assert!(!fb.set_pixel(160, 0, Rgba::BLACK));
        assert!(!fb.set_pixel(0, 144, Rgba::BLACK));
        assert_eq!(fb.get_pixel(160, 0), None);
        assert_eq!(fb.pixel_rgba(160, 0), Rgba::TRANSPARENT);
    }

    #[test]
    fn gb_tile_blit_maps_palette_and_preserves_transparency() {
        let mut tile = Tile::blank();
        tile.pixels[0] = [0, 1, 2, 3, 0, 1, 2, 3];
        let palette = Palette::new(&[
            Rgba::TRANSPARENT,
            Rgba::BLACK,
            Rgba::rgb(0x55, 0x55, 0x55),
            Rgba::rgb(0xAA, 0xAA, 0xAA),
        ]);
        let mut fb = RgbaIndexedFrameBuffer::<GbColor>::new(RenderConfig::new(8, 2), Rgba::WHITE);

        fb.blit_gb_tile(0, 0, &tile, &palette, true, false, false);

        assert_eq!(fb.get_index(0, 0), Some(GbColor::White));
        assert_eq!(fb.get_index(1, 0), Some(GbColor::Black));
        assert_eq!(fb.get_index(2, 0), Some(GbColor::DarkGray));
        assert_eq!(fb.get_index(3, 0), Some(GbColor::LightGray));
    }

    #[test]
    fn gb_tile_blit_clips_and_flips() {
        let mut tile = Tile::blank();
        tile.pixels[7][7] = 3;
        let mut fb = RgbaIndexedFrameBuffer::<GbColor>::new(RenderConfig::new(4, 4), Rgba::WHITE);

        fb.blit_gb_tile(-7, -7, &tile, &GRAYSCALE_PALETTE, false, true, true);

        assert_eq!(fb.get_index(0, 0), Some(GbColor::White));
        assert_eq!(fb.get_index(3, 3), Some(GbColor::White));

        fb.blit_gb_tile(-7, -7, &tile, &GRAYSCALE_PALETTE, false, false, false);
        assert_eq!(fb.get_index(0, 0), Some(GbColor::Black));
    }

    #[test]
    fn gb_tile_index_blit_copies_indices_and_skips_zero() {
        let mut tile = Tile::blank();
        tile.pixels[0] = [0, 1, 2, 3, 0, 1, 2, 3];
        let mut fb = RgbaIndexedFrameBuffer::<GbColor>::new(RenderConfig::new(8, 2), Rgba::BLACK);

        fb.blit_gb_tile_indices(0, 0, &tile, false, false, false);
        assert_eq!(fb.get_index(0, 0), Some(GbColor::White));
        assert_eq!(fb.get_index(1, 0), Some(GbColor::LightGray));
        assert_eq!(fb.get_index(2, 0), Some(GbColor::DarkGray));
        assert_eq!(fb.get_index(3, 0), Some(GbColor::Black));

        fb.clear_index(GbColor::Black);
        fb.blit_gb_tile_indices(0, 0, &tile, true, false, false);
        assert_eq!(fb.get_index(0, 0), Some(GbColor::Black));
        assert_eq!(fb.get_index(1, 0), Some(GbColor::LightGray));
    }

    #[test]
    fn gb_tile_index_blit_clips_opaque_edges() {
        let mut tile = Tile::blank();
        for (row, pixels) in tile.pixels.iter_mut().enumerate() {
            for (column, pixel) in pixels.iter_mut().enumerate() {
                *pixel = ((row * TILE_PIXELS + column) & 3) as u8;
            }
        }

        for (tile_x, tile_y) in [(-6, 0), (6, 0), (0, -6), (0, 6)] {
            let mut fb =
                RgbaIndexedFrameBuffer::<GbColor>::new(RenderConfig::new(8, 8), Rgba::BLACK);
            fb.blit_gb_tile_indices(tile_x, tile_y, &tile, false, false, false);

            for y in 0..8i32 {
                for x in 0..8i32 {
                    let source_x = x - tile_x;
                    let source_y = y - tile_y;
                    let expected = if (0..TILE_PIXELS as i32).contains(&source_x)
                        && (0..TILE_PIXELS as i32).contains(&source_y)
                    {
                        GbColor::from_u8(tile.pixels[source_y as usize][source_x as usize])
                    } else {
                        GbColor::Black
                    };
                    assert_eq!(
                        fb.get_index(x as u32, y as u32),
                        Some(expected),
                        "tile ({tile_x}, {tile_y}), pixel ({x}, {y})"
                    );
                }
            }
        }
    }

    #[test]
    fn clear_and_fill_quantize() {
        let mut fb = fb();
        fb.fill_rect(0, 0, 100, 100, Rgba::rgb(0x55, 0x55, 0x55));
        assert_eq!(fb.get_index(50, 50), Some(GbColor::DarkGray));
        fb.clear(Rgba::BLACK);
        assert_eq!(fb.get_index(0, 0), Some(GbColor::Black));
        assert_eq!(fb.get_index(159, 143), Some(GbColor::Black));
    }

    #[test]
    fn blit_row_quantizes_each_pixel() {
        let mut fb = fb();
        let row = [255u8, 255, 255, 255, 0, 0, 0, 0];
        assert!(fb.blit_row(0, 0, &row, 2));
        assert_eq!(fb.get_index(0, 0), Some(GbColor::White));
        assert_eq!(fb.get_index(1, 0), Some(GbColor::Black));
        assert!(!fb.blit_row(160, 0, &row, 2));
        assert!(!fb.blit_row(0, 0, &row, 3)); // src too short
    }

    #[test]
    fn remap_shades_inverts() {
        let mut fb = fb();
        fb.fill_rect(0, 0, 8, 8, Rgba::BLACK);
        // Invert: 0→3, 1→2, 2→1, 3→0.
        fb.remap_shades(&[3, 2, 1, 0]);
        assert_eq!(fb.get_pixel(0, 0), Some(Rgba::WHITE));
        // Display palette changed; the index underneath is untouched.
        assert_eq!(fb.get_index(0, 0), Some(GbColor::Black));
        fb.reset_palette();
        assert_eq!(fb.get_pixel(0, 0), Some(Rgba::BLACK));
    }

    #[test]
    fn apply_bgp_fade_to_black() {
        let mut fb = fb();
        fb.set_pixel(0, 0, Rgba::WHITE);
        // rBGP = dc 3,3,3,3 → every shade maps to black.
        fb.apply_bgp(0b11111111);
        assert_eq!(fb.get_pixel(0, 0), Some(Rgba::BLACK));
        assert_eq!(fb.get_index(0, 0), Some(GbColor::White));
    }

    #[test]
    fn scale_shades_dims_display() {
        let mut fb = fb();
        fb.fill_rect(0, 0, 8, 8, Rgba::WHITE);
        fb.scale_shades(0.5);
        assert_eq!(fb.get_pixel(0, 0), Some(Rgba::rgb(127, 127, 127)));
        fb.scale_shades(0.0);
        assert_eq!(fb.get_pixel(0, 0), Some(Rgba::BLACK));
    }

    #[test]
    fn palette_swap_does_not_touch_draws() {
        let mut fb = fb();
        fb.set_pixel(4, 4, Rgba::rgb(0x55, 0x55, 0x55));
        fb.apply_bgp(0b11100100); // identity-ish fade state
                                  // Drawing while a display effect is active still quantizes via base.
        fb.set_pixel(5, 4, Rgba::rgb(0xAA, 0xAA, 0xAA));
        fb.reset_palette();
        assert_eq!(fb.get_pixel(5, 4), Some(Rgba::rgb(0xAA, 0xAA, 0xAA)));
    }

    #[test]
    fn copy_from_copies_pixels_and_palette() {
        let mut src = fb();
        src.fill_rect(0, 0, 16, 16, Rgba::BLACK);
        src.apply_bgp(0b00000000); // all white
        let mut dst = fb();
        dst.copy_from(&src);
        assert_eq!(dst.get_index(8, 8), Some(GbColor::Black));
        assert_eq!(dst.get_pixel(8, 8), Some(Rgba::WHITE));
        assert_eq!(dst.packed(), src.packed());
    }

    #[test]
    fn copy_from_with_delegates_storage_transfer() {
        let mut src = fb();
        src.fill_rect(3, 5, 9, 7, Rgba::BLACK);
        src.apply_bgp(0b00000000); // all white
        let mut dst = fb();
        let mut calls = 0;
        dst.copy_from_with(&src, |destination, source| {
            calls += 1;
            assert_eq!(destination.len(), source.len());
            destination.copy_from_slice(source);
        });
        assert_eq!(calls, 1);
        assert_eq!(dst.get_index(4, 6), Some(GbColor::Black));
        assert_eq!(dst.get_pixel(4, 6), Some(Rgba::WHITE));
        assert_eq!(dst.packed(), src.packed());
    }

    #[test]
    fn copy_rect_from_preserves_destination_palette_and_other_pixels() {
        let mut src = fb();
        src.fill_rect(2, 3, 6, 5, Rgba::BLACK);
        src.apply_bgp(0b00000000); // all white
        let mut dst = fb();
        dst.fill_rect(0, 0, 16, 16, Rgba::rgb(0x55, 0x55, 0x55));
        dst.apply_bgp(0b11100100); // identity display palette

        dst.copy_rect_from(&src, 2, 3, 6, 5);

        assert_eq!(dst.get_index(4, 4), Some(GbColor::Black));
        assert_eq!(dst.get_pixel(4, 4), Some(Rgba::BLACK));
        assert_eq!(dst.get_index(1, 4), Some(GbColor::DarkGray));
        assert_eq!(dst.get_pixel(1, 4), Some(Rgba::rgb(0x55, 0x55, 0x55)));
    }

    #[test]
    fn copy_rect_within_preserves_palette_state() {
        let mut fb = fb();
        fb.fill_rect(2, 3, 6, 5, Rgba::BLACK);
        fb.apply_bgp(0b00000000);
        let palette = fb.palette;

        fb.copy_rect_within(2, 3, 6, 5, 4, 5);

        assert_eq!(fb.get_index(5, 6), Some(GbColor::Black));
        assert_eq!(fb.palette, palette);
    }

    #[test]
    fn clear_resets_display_palette() {
        let mut fb = fb();
        fb.apply_bgp(0b00000000); // white-out display palette
        assert_eq!(fb.get_pixel(0, 0), Some(Rgba::WHITE));
        fb.clear(Rgba::BLACK);
        // Clear restores the base display mapping: black stays black.
        assert_eq!(fb.get_pixel(0, 0), Some(Rgba::BLACK));
        fb.set_pixel(1, 0, Rgba::WHITE);
        assert_eq!(fb.get_pixel(1, 0), Some(Rgba::WHITE));
    }

    #[test]
    fn to_rgba_uses_display_palette() {
        let mut fb = RgbaIndexedFrameBuffer::<GbColor>::new(RenderConfig::new(2, 1), Rgba::WHITE);
        fb.set_pixel(0, 0, Rgba::WHITE);
        fb.apply_bgp(0b00000000); // white-out
        let mut out = [0u8; 8];
        assert!(fb.to_rgba(&mut out));
        assert_eq!(&out[0..4], &[0xFF, 0xFF, 0xFF, 0xFF]);
    }

    #[test]
    fn fb_surface_present_and_pixels() {
        let mut fb = RgbaIndexedFrameBuffer::<GbColor>::new_screen(4, 2);
        fb.set_pixel(1, 1, Rgba::WHITE);
        assert_eq!(fb.width(), 4);
        assert_eq!(fb.height(), 2);
        assert_eq!(fb.pixel_rgba(1, 1), Rgba::WHITE);
        assert_eq!(fb.pixel_rgba(0, 0), Rgba::BLACK);
        let mut out = [0u8; 4 * 2 * 4];
        fb.present_into(&mut out);
        assert_eq!(&out[5 * 4..6 * 4], &[0xFF, 0xFF, 0xFF, 0xFF]);
    }

    #[test]
    fn sprite_palette_quantization_matches_draw_palette() {
        // The pokered sprite path draws with GRAYSCALE_SPRITE_PALETTE colors;
        // quantizing those through the facade base must recover the original
        // indices. Color 0 is transparent and quantizes to black (nearest
        // opaque shade in the grayscale base palette) — the same visual the
        // RGBA buffer produced, since presenters ignore alpha.
        let mut fb = fb();
        for (i, &c) in GRAYSCALE_SPRITE_PALETTE.colors[..4].iter().enumerate() {
            fb.set_pixel(i as u32, 0, c);
            let expected = if i == 0 {
                GbColor::Black
            } else {
                GbColor::from_u8(i as u8)
            };
            assert_eq!(fb.get_index(i as u32, 0), Some(expected));
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct AlignedBytes {
    words: Vec<u32>,
    len: usize,
}
impl core::ops::Deref for AlignedBytes {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        // All u32 bit patterns are initialized; len excludes word padding.
        unsafe { core::slice::from_raw_parts(self.words.as_ptr().cast(), self.len) }
    }
}
impl core::ops::DerefMut for AlignedBytes {
    fn deref_mut(&mut self) -> &mut [u8] {
        unsafe { core::slice::from_raw_parts_mut(self.words.as_mut_ptr().cast(), self.len) }
    }
}
/// Explicit one-byte-per-pixel, word-aligned storage on every target.
pub type LinearIndexedFrameBuffer<C = GbColor> = IndexedFrameBuffer<C, true>;
pub type LinearRgbaIndexedFrameBuffer<C = GbColor> = RgbaIndexedFrameBuffer<C, true>;
impl<C: ColorIndex, const LINEAR: bool> IndexedFrameBuffer<C, LINEAR> {
    pub(crate) fn bytes(&self) -> &[u8] {
        &self.data
    }
    pub(crate) fn bytes_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }
}
impl<C: ColorIndex> IndexedFrameBuffer<C, false> {
    /// Planar row-major bytes; available only for explicitly packed storage.
    pub fn packed(&self) -> &[u8] {
        &self.data
    }
    /// Mutable planar bytes, excluding alignment padding.
    pub fn packed_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }
}
impl<C: ColorIndex> IndexedFrameBuffer<C, true> {
    /// One palette index per pixel, row-major and word-aligned on every target.
    pub fn indices(&self) -> &[u8] {
        &self.data
    }
    /// Mutable row-major indices. Writes must stay within the palette's range.
    pub fn indices_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }
}
impl<C: ColorIndex> RgbaIndexedFrameBuffer<C, false> {
    pub fn packed(&self) -> &[u8] {
        self.buffer.packed()
    }
    pub fn packed_mut(&mut self) -> &mut [u8] {
        self.buffer.packed_mut()
    }
}
impl<C: ColorIndex> RgbaIndexedFrameBuffer<C, true> {
    pub fn indices(&self) -> &[u8] {
        self.buffer.indices()
    }
    pub fn indices_mut(&mut self) -> &mut [u8] {
        self.buffer.indices_mut()
    }
}