tetanes 1.0.0

A cross-platform NES Emulator written in Rust using wgpu
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
use crate::nes::{
    event::{ConfigEvent, DebugEvent, EmulationEvent, NesEventProxy},
    renderer::{
        gui::{
            lib::{ViewportOptions, animated_dashed_rect},
            panes::{self, Column, Pane as _},
        },
        painter::RenderState,
        texture::Texture,
    },
};
use egui::{
    CentralPanel, Color32, Context, CursorIcon, DragValue, Grid, Image, Label, Panel,
    PopupCloseBehavior, Pos2, Rect, ScrollArea, Sense, Slider, StrokeKind, Ui, Vec2, ViewportId,
    containers::menu::{MenuButton, MenuConfig},
};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};
use tetanes_core::{
    bus::Bus,
    debug::Debugger,
    ppu::{self, Mirroring, Ppu, addr, cycle, scanline, scroll::Scroll, sprite::Sprite},
};

/// Bytes of the PPU address space a snapshot carries: `$0000-$2FFF`, pattern tables plus
/// nametables.
const CHR_WINDOW: usize = 0x3000;

/// Bytes of a second copy of the pattern tables, `$0000-$1FFF`, for a board that maps sprites
/// through a CHR bank set of their own.
const SPR_CHR_WINDOW: usize = 0x2000;

/// What a pane spends above its image: the heading, the header row, and the separator under it.
const PANE_CHROME: f32 = 62.0;

/// The row naming the background and sprite halves of the palette grid.
const PALETTE_LABELS: f32 = 20.0;

/// The side of one NES tile, which is the step the nametable, pattern and OAM views select by.
const TILE: f32 = 8.0;

/// The side of one palette swatch. The palette grid has no texture behind it, so its cell is
/// whatever reads well rather than a count of NES pixels.
const SWATCH: f32 = 24.0;

/// Which of a pane header's two menus is being drawn.
///
/// Both reach the pane's own state, so they arrive as one closure rather than two, which a single
/// `&mut self` can serve.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[must_use]
enum HeaderMenu {
    /// The toggles that change how the view draws.
    Settings,
    /// What the pane knows about the tile or color the last click selected.
    Detail,
}

/// What this viewer takes from the console when the debugger fires.
///
/// The callback is handed the whole [`Bus`], so this is the viewer's own choice of what to copy
/// across to the render thread - the PPU's registers, and its address space resolved through the
/// board so no mapper knowledge is needed here. A few KiB per frame; rendering the views produces
/// ~1 MiB of pixels and stays on this side.
#[derive(Debug, Clone)]
#[must_use]
pub struct PpuSnapshot {
    pub ppu: Ppu,
    pub chr: Box<[u8; CHR_WINDOW]>,
    /// The pattern tables as the board maps them for a sprite fetch, where it keeps a set apart
    /// from the background's. `None` leaves the sprite views reading `chr`.
    pub chr_spr: Option<Box<[u8; SPR_CHR_WINDOW]>>,
    pub mirroring: Mirroring,
}

impl Default for PpuSnapshot {
    fn default() -> Self {
        Self {
            ppu: Ppu::default(),
            chr: Box::new([0; CHR_WINDOW]),
            chr_spr: None,
            mirroring: Mirroring::default(),
        }
    }
}

impl PpuSnapshot {
    /// Copy what the viewer needs out of the console at a break point.
    pub fn capture(bus: &Bus) -> Self {
        let mut chr = Box::new([0; CHR_WINDOW]);
        bus.copy_ppu_bus(chr.as_mut_slice());
        let mut chr_spr = Box::new([0; SPR_CHR_WINDOW]);
        let chr_spr = bus
            .copy_spr_pattern_tables(chr_spr.as_mut_slice())
            .then_some(chr_spr);
        Self {
            ppu: bus.ppu.snapshot(),
            chr,
            chr_spr,
            mirroring: bus.mirroring(),
        }
    }
}

#[derive(Debug)]
#[must_use]
struct State {
    tx: NesEventProxy,
    panes: Vec<Pane>,
    // TODO: persist in config
    refresh_cycle: u16,
    refresh_scanline: u16,
    nametables: NametablesState,
    pattern_tables: PatternTablesState,
    oam: OamState,
    palette: PalettesState,
    snapshot: PpuSnapshot,
}

#[derive(Debug)]
#[must_use]
struct NametablesState {
    pixels: Vec<u8>,
    texture: Texture,
    zoom: f32,
    selected: Option<Vec2>,
    show_dividers: bool,
    show_tile_grid: bool,
    show_refresh_lines: bool,
    show_scroll_overlay: bool,
    show_attr_grid_16x: bool,
    show_attr_grid_32x: bool,
}

#[derive(Debug)]
#[must_use]
struct PatternTablesState {
    pixels: Vec<u8>,
    texture: Texture,
    zoom: f32,
    selected: Option<Vec2>,
    show_dividers: bool,
    show_tile_grid: bool,
}

#[derive(Debug)]
#[must_use]
struct OamState {
    oam_pixels: Vec<u8>,
    sprite_pixels: Vec<u8>,
    sprites: Vec<Sprite>,
    oam_texture: Texture,
    sprites_texture: Texture,
    zoom: f32,
    oam_selected: Option<Vec2>,
    show_tile_grid: bool,
}

#[derive(Debug)]
#[must_use]
struct PalettesState {
    size: Vec2,
    pixels: Vec<u8>,
    colors: Vec<u8>,
    zoom: f32,
    selected: Option<Vec2>,
}

#[derive(Debug, Copy, Clone)]
#[must_use]
struct NametableTile {
    index: u16,
    uv: Rect,
    col: u16,
    row: u16,
    x: u16, // 0..=248
    y: u16, // 0..=232
    nametable_addr: u16,
    tile_addr: u16,
    palette_index: u8,
    palette_addr: u16,
    attr_addr: u16,
    attr_val: u8,
}

impl Default for NametableTile {
    fn default() -> Self {
        Self {
            index: 0,
            uv: Rect::NOTHING,
            col: 0,
            row: 0,
            x: 0,
            y: 0,
            nametable_addr: 0,
            tile_addr: 0,
            palette_index: 0,
            palette_addr: 0,
            attr_addr: 0,
            attr_val: 0,
        }
    }
}

#[derive(Debug, Copy, Clone)]
#[must_use]
struct ChrTile {
    index: u16,
    uv: Rect,
    tile_addr: u16,
}

impl Default for ChrTile {
    fn default() -> Self {
        Self {
            index: 0,
            uv: Rect::NOTHING,
            tile_addr: 0,
        }
    }
}

#[derive(Debug, Copy, Clone)]
#[must_use]
struct PaletteColor {
    index: u8,
    value: u8,
    addr: u16,
    color: Color32,
}

impl Default for PaletteColor {
    fn default() -> Self {
        Self {
            index: 0,
            value: 0,
            addr: 0,
            color: Color32::BLACK,
        }
    }
}

#[derive(Debug)]
#[must_use]
pub struct PpuViewer {
    pub id: ViewportId,
    open: Arc<AtomicBool>,
    state: Arc<Mutex<State>>,
}

/// A view in the PPU viewer.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[must_use]
pub enum Pane {
    /// The four nametables as the background they describe.
    Nametables,
    /// Both pattern tables as tiles.
    PatternTables,
    /// The OAM entries as tiles, beside the screen they place.
    Oam,
    /// The background and sprite palettes as swatches.
    Palette,
}

impl Pane {
    /// The id the window's panes and columns are keyed by, which keeps them apart from another
    /// window's.
    const WINDOW: &'static str = "ppu_viewer";

    /// The panes a window opens with.
    ///
    /// All of them. The window exists to show the four at once, and each is cheap enough that
    /// none of them waits to be asked for.
    pub const DEFAULT: [Self; 4] = [
        Self::Nametables,
        Self::PatternTables,
        Self::Oam,
        Self::Palette,
    ];
}

impl panes::Pane for Pane {
    const ALL: &'static [Self] = &Self::DEFAULT;

    fn title(self) -> &'static str {
        match self {
            Self::Nametables => "Nametables",
            Self::PatternTables => "Pattern tables",
            Self::Oam => "OAM",
            Self::Palette => "Palette",
        }
    }

    fn column(self) -> Column {
        match self {
            // A nametable pair is 512x480, which is more than the right column spans.
            Self::Nametables => Column::Center,
            Self::PatternTables | Self::Oam | Self::Palette => Column::Right,
        }
    }

    fn default_size(self) -> f32 {
        // Every pane here draws an image whose height follows its zoom, so `State::pane_size`
        // measures it and applies this as the floor.
        120.0
    }

    fn id(self) -> &'static str {
        match self {
            Self::Nametables => "pane_nametables",
            Self::PatternTables => "pane_pattern_tables",
            Self::Oam => "pane_oam",
            Self::Palette => "pane_palette",
        }
    }
}

impl PpuViewer {
    const TITLE: &'static str = "TetaNES - PPU Viewer";

    /// Build the viewer with `panes` open. The window itself starts closed.
    pub fn new(tx: NesEventProxy, panes: &[Pane], render_state: &mut RenderState) -> Self {
        let panes = Pane::ALL
            .iter()
            .copied()
            .filter(|pane| panes.contains(pane))
            .collect::<Vec<_>>();
        Self {
            id: ViewportId::from_hash_of(Self::TITLE),
            open: Arc::new(AtomicBool::new(false)),
            state: Arc::new(Mutex::new(State {
                tx,
                panes,
                refresh_cycle: 0,
                refresh_scanline: scanline::VBLANK_NTSC,
                nametables: NametablesState {
                    // 4 nametables with 4 color channels (RGBA)
                    pixels: vec![0x00; 4 * 4 * ppu::size::FRAME],
                    texture: Texture::new(
                        render_state,
                        2.0 * Vec2::new(ppu::size::WIDTH as f32, ppu::size::HEIGHT as f32),
                        1.0,
                        Some("nes nametables"),
                    ),
                    zoom: 1.5,
                    selected: None,
                    show_dividers: true,
                    show_tile_grid: false,
                    show_refresh_lines: false,
                    show_scroll_overlay: false,
                    show_attr_grid_16x: false,
                    show_attr_grid_32x: false,
                },
                pattern_tables: PatternTablesState {
                    // 2 pattern tables with 4 color channels (RGBA)
                    pixels: vec![0x00; 2 * 4 * ppu::size::FRAME],
                    texture: Texture::new(
                        render_state,
                        Vec2::new(ppu::size::WIDTH as f32, ppu::size::WIDTH as f32 / 2.0),
                        1.0,
                        Some("nes pattern tables"),
                    ),
                    // 256 wide at 1x, which fits the right column without scrolling it.
                    zoom: 1.0,
                    selected: None,
                    show_dividers: true,
                    show_tile_grid: false,
                },
                oam: OamState {
                    // 64 8x8 sprites with 4 color channels (RGBA)
                    oam_pixels: vec![0x00; 64 * 8 * 8 * 4],
                    // 1 nametable with 4 color channels (RGBA)
                    sprite_pixels: vec![0x00; 4 * ppu::size::FRAME],
                    // 64 sprites
                    sprites: vec![Sprite::new(); 64],
                    oam_texture: Texture::new(
                        render_state,
                        Vec2::splat(64.0),
                        1.0,
                        Some("nes oam"),
                    ),
                    sprites_texture: Texture::new(
                        render_state,
                        Vec2::new(ppu::size::WIDTH as f32, ppu::size::HEIGHT as f32),
                        1.0,
                        Some("nes sprites"),
                    ),
                    // Sets a display height both textures scale to, so the pair spans roughly
                    // the right column.
                    zoom: 1.0,
                    oam_selected: None,
                    show_tile_grid: false,
                },
                palette: PalettesState {
                    // 2 palette tables, 4 colors each, one swatch per cell.
                    size: Vec2::new(8.0 * SWATCH, 4.0 * SWATCH),
                    // 32 palette colors with 4 color channels (RGBA)
                    pixels: vec![0x00; 4 * 32],
                    // 32 colors
                    colors: vec![0x00; 32],
                    zoom: 1.0,
                    selected: None,
                },
                snapshot: PpuSnapshot::default(),
            })),
        }
    }

    pub const fn id(&self) -> ViewportId {
        self.id
    }

    pub fn open(&self) -> bool {
        self.open.load(Ordering::Acquire)
    }

    pub fn set_open(&self, open: bool, ctx: &Context) {
        self.open.store(open, Ordering::Release);
        self.state.lock().update_debugger(open);
        if open {
            ctx.send_viewport_cmd_to(self.id, egui::ViewportCommand::Close);
        }
    }

    pub fn toggle_open(&self, ctx: &Context) {
        let Ok(open) = self
            .open
            .try_update(Ordering::Release, Ordering::Acquire, |open| Some(!open))
        else {
            return;
        };
        self.state.lock().update_debugger(!open);
        if open {
            ctx.send_viewport_cmd_to(self.id, egui::ViewportCommand::Close);
        }
    }

    pub fn update_ppu(&mut self, queue: &wgpu::Queue, snapshot: PpuSnapshot) {
        let mut state = self.state.lock();
        let PpuSnapshot {
            ppu, chr, chr_spr, ..
        } = &snapshot;
        let spr_chr = chr_spr
            .as_ref()
            .map_or(chr.as_slice(), |chr_spr| chr_spr.as_slice());
        // Rendering a view walks its pixels once per frame, so a closed pane is not drawn into.
        let nametables = state.panes.contains(&Pane::Nametables);
        let pattern_tables = state.panes.contains(&Pane::PatternTables);
        let oam = state.panes.contains(&Pane::Oam);
        // The nametable view colors its tiles from the palettes, so it needs them loaded whether
        // or not the palette pane is showing them.
        let palette = nametables || state.panes.contains(&Pane::Palette);
        if nametables {
            ppu.load_nametables(chr.as_slice(), &mut state.nametables.pixels);
            state
                .nametables
                .texture
                .update(queue, &state.nametables.pixels);
        }
        if pattern_tables {
            ppu.load_pattern_tables(chr.as_slice(), &mut state.pattern_tables.pixels);
            state
                .pattern_tables
                .texture
                .update(queue, &state.pattern_tables.pixels);
        }
        if oam {
            let mut oam_pixels = std::mem::take(&mut state.oam.oam_pixels);
            let mut sprite_pixels = std::mem::take(&mut state.oam.sprite_pixels);
            let mut sprites = std::mem::take(&mut state.oam.sprites);

            // Clear to black each frame
            sprite_pixels.chunks_mut(4).for_each(|chunk| {
                chunk[0] = 0;
                chunk[1] = 0;
                chunk[2] = 0;
                chunk[3] = 255;
            });
            ppu.load_oam(spr_chr, &mut oam_pixels, &mut sprite_pixels, &mut sprites);

            state.oam.oam_pixels = oam_pixels;
            state.oam.sprite_pixels = sprite_pixels;
            state.oam.sprites = sprites;

            state.oam.oam_texture.update(queue, &state.oam.oam_pixels);
            state
                .oam
                .sprites_texture
                .update(queue, &state.oam.sprite_pixels);
        }
        if palette {
            let mut pixels = std::mem::take(&mut state.palette.pixels);
            let mut colors = std::mem::take(&mut state.palette.colors);
            ppu.load_palettes(&mut pixels, &mut colors);
            state.palette.pixels = pixels;
            state.palette.colors = colors;
        }
        state.snapshot = snapshot;
    }

    pub fn show(&mut self, ui: &mut Ui, opts: ViewportOptions) {
        if !self.open.load(Ordering::Relaxed) {
            return;
        }

        let open = Arc::clone(&self.open);
        let state = Arc::clone(&self.state);

        let mut viewport_builder = egui::ViewportBuilder::default()
            .with_title(Self::TITLE)
            // Wide and tall enough for all four nametables at their default zoom, with the right
            // column beside them.
            .with_inner_size(Vec2::new(1180.0, 850.0));
        if opts.always_on_top {
            viewport_builder = viewport_builder.with_always_on_top();
        }

        // `show_viewport_deferred` wraps its callback in a window of its own when viewports embed,
        // and that window carries the builder's title and size but no close button. Drawing the
        // window here instead keeps the title bar, the ✖ and the size on the same window.
        if ui.ctx().embed_viewports() {
            let mut window_open = open.load(Ordering::Acquire);
            egui::Window::new(Self::TITLE)
                .open(&mut window_open)
                .default_rect(ui.content_rect().shrink(16.0))
                .show(ui, |ui| state.lock().ui(ui, opts.enabled));
            open.store(window_open, Ordering::Release);
        } else {
            ui.show_viewport_deferred(self.id, viewport_builder, move |ui, _| {
                CentralPanel::default().show(ui, |ui| state.lock().ui(ui, opts.enabled));
                if ui.input(|i| i.viewport().close_requested()) {
                    open.store(false, Ordering::Release);
                }
            });
        }
    }
}

impl State {
    fn update_debugger(&self, open: bool) {
        self.tx.event(if open {
            let tx = self.tx.clone();
            EmulationEvent::AddDebugger(Debugger {
                cycle: self.refresh_cycle,
                scanline: self.refresh_scanline,
                callback: Arc::new(move |bus| {
                    tx.event(DebugEvent::Ppu(Box::new(PpuSnapshot::capture(bus))))
                }),
            })
        } else {
            EmulationEvent::RemoveDebugger
        });
    }

    fn ui(&mut self, ui: &mut Ui, enabled: bool) {
        let mut closed = None;
        ui.add_enabled_ui(enabled, |ui| {
            Panel::top("ppu_viewer_toolbar").show(ui, |ui| self.toolbar(ui));
            // Drawn through a closure rather than by the layout, since a body reads the window's
            // own state. The pane the closure cannot reach is the one it reports closed.
            let open = self.panes.clone();
            // Measured before the bodies borrow `self` to draw.
            let sizes = Pane::ALL
                .iter()
                .map(|pane| (*pane, self.pane_size(*pane)))
                .collect::<Vec<_>>();
            let size = |pane| {
                sizes
                    .iter()
                    .find_map(|(other, size)| (*other == pane).then_some(*size))
                    .unwrap_or_default()
            };
            closed = panes::columns(ui, Pane::WINDOW, &open, &size, &mut |ui, pane| {
                self.pane(ui, pane)
            });
        });
        if let Some(pane) = closed {
            self.set_pane_open(pane, false);
        }
    }

    /// The dot every pane refreshes on, and which panes are open.
    ///
    /// One [`Debugger`] fires the snapshot all four views read, so the cycle and scanline belong
    /// to the window rather than to any one pane.
    fn toolbar(&mut self, ui: &mut Ui) {
        ui.horizontal(|ui| {
            self.refresh_settings(ui);
            ui.separator();
            ui.strong("Mirroring:");
            ui.label(format!("{:?}", self.snapshot.mirroring));
            ui.separator();
            if let Some((pane, open)) = panes::view_menu(ui, Pane::WINDOW, &self.panes) {
                self.set_pane_open(pane, open);
            }
        });
    }

    /// Open or close `pane`, rebuilding the open list in [`Pane::ALL`] order so a reopened pane
    /// goes back where it was in its column.
    fn set_pane_open(&mut self, pane: Pane, open: bool) {
        self.panes = Pane::ALL
            .iter()
            .copied()
            .filter(|other| {
                if *other == pane {
                    open
                } else {
                    self.panes.contains(other)
                }
            })
            .collect();
        self.tx
            .event(ConfigEvent::PpuViewerPanes(self.panes.clone()));
        // The console stops rendering a closed pane's view, so its texture is as old as the frame
        // it was closed on. Reopening asks for a snapshot rather than waiting for the next dot.
        if open {
            self.update_debugger(true);
        }
    }

    /// How tall `pane` needs to be to show its view whole.
    ///
    /// The right column has no splitters between its panes, so a fixed height would leave every
    /// image scrolled and no way to grow it. Measuring the image instead makes the zoom slider the
    /// resize control, and a pane is exactly as tall as what it draws.
    fn pane_size(&self, pane: Pane) -> f32 {
        let image = match pane {
            // The center column's pane takes what is left, so its height is never asked for.
            Pane::Nametables => 0.0,
            Pane::PatternTables => self.pattern_tables.zoom * self.pattern_tables.texture.size.y,
            // The view scales both textures to one shared display height.
            Pane::Oam => 2.0 * self.oam.zoom * self.oam.oam_texture.size.y,
            // Plus the row naming the two halves.
            Pane::Palette => self.palette.zoom * self.palette.size.y + PALETTE_LABELS,
        };
        (image + PANE_CHROME).max(pane.default_size())
    }

    /// Draw `pane`'s view. The layout draws the heading above it.
    fn pane(&mut self, ui: &mut Ui, pane: Pane) {
        match pane {
            Pane::Nametables => self.nametables(ui),
            Pane::PatternTables => self.pattern_tables(ui),
            Pane::Oam => self.oam(ui),
            Pane::Palette => self.palette_pane(ui),
        }
    }

    /// The PPU dot the snapshot every pane reads is taken at.
    fn refresh_settings(&mut self, ui: &mut Ui) {
        ui.strong("Refresh on:")
            .on_hover_cursor(CursorIcon::Help)
            .on_hover_text("Change which PPU cycle/scanline viewer state refreshes on.");

        let drag = DragValue::new(&mut self.refresh_cycle)
            .range(0..=cycle::END)
            .suffix(" cycle");
        let res = ui.add(drag);
        if res.changed() {
            self.update_debugger(true);
        }

        let drag = DragValue::new(&mut self.refresh_scanline)
            .range(0..=self.snapshot.ppu.prerender_scanline)
            .suffix(" scanline");
        let res = ui.add(drag);
        if res.changed() {
            self.update_debugger(true);
        }
    }

    fn nametables(&mut self, ui: &mut Ui) {
        let mut zoom = self.nametables.zoom;
        let selected = self.nametables.selected;
        pane_header(
            ui,
            "nametables",
            &mut zoom,
            true,
            selected.is_some(),
            |ui, menu| {
                if menu == HeaderMenu::Detail {
                    self.nametable_tile(ui, "nametable_tile_selected", selected);
                    return;
                }
                let res = ui
                    .checkbox(&mut self.nametables.show_refresh_lines, "Refresh Markers")
                    .on_hover_text("Show lines indicating the current refresh cycle and scanline.");
                if res.changed() {
                    // TODO: update config
                }

                grid_settings(
                    ui,
                    &mut self.nametables.show_dividers,
                    &mut self.nametables.show_tile_grid,
                );

                let res = ui
                    .checkbox(&mut self.nametables.show_scroll_overlay, "Scroll Overlay")
                    .on_hover_text("Show scroll position overlay.");
                if res.changed() {
                    // TODO: update config
                }

                let res = ui
                    .checkbox(
                        &mut self.nametables.show_attr_grid_16x,
                        "Attribute Grid (16x16)",
                    )
                    .on_hover_text("Show grid lines within each attribute block.");
                if res.changed() {
                    // TODO: update config
                }

                let res = ui
                    .checkbox(
                        &mut self.nametables.show_attr_grid_32x,
                        "Attribute Grid (32x32)",
                    )
                    .on_hover_text("Show grid lines between attribute blocks.");
                if res.changed() {
                    // TODO: update config
                }
            },
        );
        self.nametables.zoom = zoom;

        let texture_size = self.nametables.texture.size;
        {
            let scroll = ScrollArea::both()
                .id_salt("nametables_image")
                .min_scrolled_width(texture_size.x)
                .min_scrolled_height(texture_size.y);
            scroll.show(ui, |ui| {
                let image = Image::from_texture(self.nametables.texture.sized())
                    .fit_to_exact_size(self.nametables.zoom * texture_size)
                    .sense(Sense::click());

                let res = ui.add(image).on_hover_cursor(CursorIcon::Cell);
                let image_rect = res.rect;

                if let Some(pos) = res.hover_pos()
                    && image_rect.contains(pos)
                {
                    self.nametable_hover(ui, &res, pos);
                }

                if self.nametables.show_dividers {
                    // Split the 4x4 nametables in half vertically and horizontally
                    ui.painter().vline(
                        image_rect.center().x,
                        image_rect.y_range(),
                        (1.0, Color32::WHITE),
                    );
                    ui.painter().hline(
                        image_rect.x_range(),
                        image_rect.center().y,
                        (1.0, Color32::WHITE),
                    );
                }

                if self.nametables.show_refresh_lines {
                    let cycle_offset =
                        self.refresh_cycle as f32 * image_rect.size().x / 2.0 / cycle::END as f32;
                    let scanline_offset = self.refresh_scanline as f32 * image_rect.size().y
                        / 2.0
                        / self.snapshot.ppu.prerender_scanline as f32;
                    ui.painter().vline(
                        image_rect.left() + cycle_offset,
                        image_rect.y_range(),
                        (1.0, Color32::RED),
                    );
                    ui.painter().vline(
                        image_rect.center().x + cycle_offset,
                        image_rect.y_range(),
                        (1.0, Color32::RED),
                    );
                    ui.painter().hline(
                        image_rect.x_range(),
                        image_rect.top() + scanline_offset,
                        (1.0, Color32::GREEN),
                    );
                    ui.painter().hline(
                        image_rect.x_range(),
                        image_rect.center().y + scanline_offset,
                        (1.0, Color32::GREEN),
                    );
                }

                if self.nametables.show_tile_grid {
                    paint_grid(ui, image_rect, 60.0, 64.0, Color32::LIGHT_BLUE);
                }

                if self.nametables.show_attr_grid_16x {
                    paint_grid(ui, image_rect, 30.0, 32.0, Color32::LIGHT_RED);
                }

                if self.nametables.show_attr_grid_32x {
                    // Because 32x doesn't divide evenly into 240, split this up into two passes with a
                    // dividing line, forcing the leftover attribute space to be at the bottom. Also
                    // halve the number of rows
                    let top_rect = Rect::from_min_max(image_rect.min, image_rect.right_center());
                    let bot_rect =
                        Rect::from_min_max(image_rect.left_center(), image_rect.right_bottom());

                    paint_grid(ui, top_rect, 7.5, 16.0, Color32::LIGHT_GREEN);
                    ui.painter().hline(
                        top_rect.x_range(),
                        top_rect.bottom(),
                        (1.0, Color32::LIGHT_GREEN),
                    );
                    paint_grid(ui, bot_rect, 7.5, 16.0, Color32::LIGHT_GREEN);
                }

                if self.nametables.show_scroll_overlay {
                    self.nametable_scroll_overlay(ui, image_rect);
                }

                if let Some(offset) = self.nametables.selected {
                    let selection =
                        tile_selection(image_rect, self.nametables.texture.size, offset, TILE);
                    animated_dashed_rect(ui, selection, (1.0, Color32::WHITE), 3.0, 3.0);
                }
            });
        }
    }

    fn nametable_hover(&mut self, ui: &mut Ui, res: &egui::Response, pos: Pos2) {
        let image_rect = res.rect;
        let texture_size = self.nametables.texture.size;

        let offset = translate_screen_pos_to_tile(pos, image_rect, texture_size, TILE);
        let selection = tile_selection(image_rect, texture_size, offset, TILE);

        animated_dashed_rect(
            ui,
            selection,
            (1.0, Color32::from_white_alpha(220)),
            3.0,
            3.0,
        );

        res.clone().on_hover_ui_at_pointer(|ui| {
            self.nametable_tile(ui, "nametable_tile_hover", Some(offset));
        });
        if res.clicked() {
            self.nametables.selected = Some(offset);
        }
    }

    fn nametable_tile_from_offset(&self, offset: Vec2, texture_size: Vec2) -> NametableTile {
        let Vec2 { x, y } = offset;

        // Get row/column 8x8 tile and the nametable it's in
        let mut col = x as u16 / 8;
        let mut row = y as u16 / 8;
        let nametable = if col >= 32 { 1 } else { 0 } | if row >= 30 { 2 } else { 0 };

        // Wrap row/column to a single nametable
        col &= 31;
        if row >= 30 {
            // Not a power of two, so can't bitwise &
            row -= 30;
        }

        let nametable_index = (row << 5) + col;
        let base_nametable_addr = addr::NAMETABLE_START | (nametable * ppu::size::NAMETABLE);
        let base_attr_addr = base_nametable_addr + addr::ATTR_OFFSET;

        let nametable_addr = base_nametable_addr + nametable_index;
        let tile_index = u16::from(self.snapshot.chr[usize::from(nametable_addr)]);
        let tile_addr = self.snapshot.ppu.ctrl_bg_select + (tile_index << 4);

        let supertile = ((row & 0xFC) << 1) + (col >> 2);
        let attr_addr = base_attr_addr + supertile;
        let attr_val = self.snapshot.chr[usize::from(attr_addr)];

        let attr_shift = (col & 0x02) | ((row & 0x02) << 1);
        // TODO: handle mmc5 extended attributes
        let palette_addr = ((attr_val >> attr_shift) & 0x03) << 2;
        let palette_index = palette_addr >> 2;
        let palette_addr = addr::PALETTE_START + u16::from(palette_addr);

        let tile_uv = Rect::from_min_size(
            (Vec2::new(x, y) / texture_size).to_pos2(),
            Vec2::splat(8.0) / texture_size,
        );

        let x = (x as u16) % ppu::size::WIDTH;
        let y = (y as u16) % ppu::size::HEIGHT;

        NametableTile {
            index: tile_index,
            uv: tile_uv,
            col,
            row,
            x,
            y,
            nametable_addr,
            tile_addr,
            palette_index,
            palette_addr,
            attr_addr,
            attr_val,
        }
    }

    fn nametable_tile(&mut self, ui: &mut Ui, label: &str, offset: Option<Vec2>) {
        let tile = offset
            .map(|offset| self.nametable_tile_from_offset(offset, self.nametables.texture.size));
        let NametableTile {
            uv,
            index,
            col,
            row,
            x,
            y,
            nametable_addr,
            tile_addr,
            palette_index,
            palette_addr,
            attr_addr,
            attr_val,
            ..
        } = tile.unwrap_or_default();

        let grid = Grid::new(label).num_columns(2).spacing([40.0, 6.0]);
        grid.show(ui, |ui| {
            ui.strong("Tile:");
            let tile_image = Image::from_texture(self.nametables.texture.sized())
                .uv(uv)
                .maintain_aspect_ratio(false) // Ignore original aspect ratio
                .fit_to_exact_size(Vec2::splat(64.0))
                .sense(Sense::click());
            ui.add(tile_image);
            ui.end_row();

            ui.strong("Palette:");
            if tile.is_some() {
                self.palette_row(
                    ui,
                    palette_index.into(),
                    ui.cursor().min,
                    Vec2::splat(16.0),
                    true,
                );
            }
            ui.end_row();

            ui.strong("Column, Row:");
            if tile.is_some() {
                ui.label(format!("{col}, {row}"));
            }
            ui.end_row();

            ui.strong("X, Y:");
            if tile.is_some() {
                ui.label(format!("{x}, {y}"));
            }
            ui.end_row();

            ui.strong("Nametable Address:");
            if tile.is_some() {
                ui.label(format!("${nametable_addr:04X}"));
            }
            ui.end_row();

            ui.strong("Tile Index:");
            if tile.is_some() {
                ui.label(format!("${index:02X}"));
            }
            ui.end_row();

            ui.strong("Tile Address:");
            if tile.is_some() {
                ui.label(format!("${tile_addr:04X}"));
            }
            ui.end_row();

            ui.strong("Palette Index:");
            if tile.is_some() {
                ui.label(format!("{palette_index}"));
            }
            ui.end_row();

            ui.strong("Palette Address:");
            if tile.is_some() {
                ui.label(format!("${palette_addr:04X}"));
            }
            ui.end_row();

            ui.strong("Attribute Address:");
            if tile.is_some() {
                ui.label(format!("${attr_addr:04X}"));
            }
            ui.end_row();

            ui.strong("Attribute Value:");
            if tile.is_some() {
                ui.label(format!("${attr_val:02X}"));
            }
            ui.end_row();
        });
    }

    fn nametable_scroll_overlay(&self, ui: &mut Ui, image_rect: Rect) {
        let Ppu {
            cycle,
            scanline,
            vblank_scanline,
            prerender_scanline,
            scroll,
            ..
        } = self.snapshot.ppu;
        let use_scroll_t = scanline >= vblank_scanline
            || (scanline == scanline::VISIBLE_END && cycle >= cycle::SPR_EVAL_END)
            || (scanline == prerender_scanline && cycle < cycle::BG_PREFETCH_START + 7);
        let scroll_v = if use_scroll_t { scroll.t } else { scroll.v };

        let mut scroll_x = ((scroll_v & Scroll::COARSE_X_MASK) << 3)
            | (((scroll_v & Scroll::NT_X_MASK) >> 10) * ppu::size::WIDTH);
        let scroll_y = ((scroll_v & Scroll::COARSE_Y_MASK) >> 2)
            | (((scroll_v & Scroll::NT_Y_MASK) >> 11) * ppu::size::HEIGHT)
            | ((scroll_v & Scroll::FINE_Y_MASK) >> 12);

        if use_scroll_t {
            scroll_x |= scroll.fine_x;
        } else {
            // During rendering, subtract according to current cycle/scanline
            if cycle <= scanline::VISIBLE_END {
                if cycle >= 8 {
                    scroll_x = scroll_x.saturating_sub(cycle & !0x07);
                }
                // Adjust for 2x increments at end of last scanline
                scroll_x = scroll_x.saturating_sub(16);
            } else if cycle >= cycle::BG_PREFETCH_START + 7 {
                scroll_x = scroll_x.saturating_sub(8);
                if cycle >= cycle::BG_PREFETCH_END {
                    scroll_x = scroll_x.saturating_sub(8);
                }
            }
            scroll_x += scroll.fine_x;
        }

        // The 256x240 viewport sits on a 512x480 torus, so it can run off the right edge, the
        // bottom, or both at once. Drawing it at all four wrapped origins under a clip to the
        // image puts each piece where it belongs and cuts away the rest. No two pieces overlap,
        // since they sit a full image apart and each spans half of one.
        let texture_size = self.nametables.texture.size;
        let scroll = Vec2::new(
            f32::from(scroll_x % texture_size.x as u16),
            f32::from(scroll_y % texture_size.y as u16),
        ) * image_rect.size()
            / texture_size;
        let nametable_size = image_rect.size() / 2.0;
        let origin = image_rect.min + scroll;
        let painter = ui.painter().with_clip_rect(image_rect);
        for offset in [
            Vec2::ZERO,
            Vec2::new(-image_rect.width(), 0.0),
            Vec2::new(0.0, -image_rect.height()),
            -image_rect.size(),
        ] {
            painter.rect(
                Rect::from_min_size(origin + offset, nametable_size),
                0.0,
                Color32::from_black_alpha(75),
                (1.0, Color32::WHITE),
                egui::StrokeKind::Inside,
            );
        }
    }

    fn pattern_tables(&mut self, ui: &mut Ui) {
        let mut zoom = self.pattern_tables.zoom;
        let selected = self.pattern_tables.selected;
        pane_header(
            ui,
            "pattern_tables",
            &mut zoom,
            true,
            selected.is_some(),
            |ui, menu| match menu {
                // TODO: Selectable palette/last known palette
                HeaderMenu::Settings => grid_settings(
                    ui,
                    &mut self.pattern_tables.show_dividers,
                    &mut self.pattern_tables.show_tile_grid,
                ),
                HeaderMenu::Detail => {
                    self.pattern_tables_tile(ui, "pattern_tables_tile_selected", selected);
                }
            },
        );
        self.pattern_tables.zoom = zoom;

        let texture_size = self.pattern_tables.texture.size;
        {
            let scroll = ScrollArea::both()
                .id_salt("pattern_tables_image")
                .min_scrolled_width(texture_size.x)
                .min_scrolled_height(texture_size.y);
            scroll.show(ui, |ui| {
                let image = Image::from_texture(self.pattern_tables.texture.sized())
                    .fit_to_exact_size(self.pattern_tables.zoom * texture_size)
                    .sense(Sense::click());

                let res = ui.add(image).on_hover_cursor(CursorIcon::Cell);
                let image_rect = res.rect;

                if let Some(pos) = res.hover_pos()
                    && image_rect.contains(pos)
                {
                    self.pattern_tables_hover(ui, &res, pos);
                }

                if self.pattern_tables.show_dividers {
                    ui.painter().vline(
                        image_rect.center().x,
                        image_rect.y_range(),
                        (1.0, Color32::WHITE),
                    );
                }

                if self.pattern_tables.show_tile_grid {
                    paint_grid(ui, image_rect, 16.0, 32.0, Color32::LIGHT_BLUE);
                }

                if let Some(offset) = self.pattern_tables.selected {
                    let selection =
                        tile_selection(image_rect, self.pattern_tables.texture.size, offset, TILE);
                    animated_dashed_rect(ui, selection, (1.0, Color32::WHITE), 3.0, 3.0);
                }
            });
        }
    }

    fn pattern_tables_hover(&mut self, ui: &mut Ui, res: &egui::Response, pos: Pos2) {
        let image_rect = res.rect;
        let texture_size = self.pattern_tables.texture.size;

        let offset = translate_screen_pos_to_tile(pos, image_rect, texture_size, TILE);
        let selection = tile_selection(image_rect, texture_size, offset, TILE);

        animated_dashed_rect(
            ui,
            selection,
            (1.0, Color32::from_white_alpha(220)),
            3.0,
            3.0,
        );

        res.clone().on_hover_ui_at_pointer(|ui| {
            self.pattern_tables_tile(ui, "pattern_tables_tile_hover", Some(offset));
        });
        if res.clicked() {
            self.pattern_tables.selected = Some(offset);
        }
    }

    fn pattern_chr_tile_from_offset(&self, offset: Vec2, texture_size: Vec2) -> ChrTile {
        let Vec2 { x, y } = offset;

        // Get row/column 8x8 tile and the pattern table it's in
        let mut col = x as u16 / 8;
        let row = y as u16 / 8;
        let pattern_table = if col >= 16 { 1 } else { 0 };

        // Wrap column to a single pattern table
        col &= 15;

        let tile_uv = Rect::from_min_size(
            (Vec2::new(x, y) / texture_size).to_pos2(),
            Vec2::splat(8.0) / texture_size,
        );
        let tile_addr = (pattern_table << 12) | ((col + (row << 4)) << 4);

        ChrTile {
            index: (tile_addr >> 4) & 0xFF,
            uv: tile_uv,
            tile_addr,
        }
    }

    fn pattern_tables_tile(&mut self, ui: &mut Ui, label: &str, offset: Option<Vec2>) {
        let tile = offset.map(|offset| {
            self.pattern_chr_tile_from_offset(offset, self.pattern_tables.texture.size)
        });
        let ChrTile {
            uv,
            index,
            tile_addr,
            ..
        } = tile.unwrap_or_default();

        let grid = Grid::new(label).num_columns(2).spacing([40.0, 6.0]);
        grid.show(ui, |ui| {
            ui.strong("Tile:");
            let tile_image = Image::from_texture(self.pattern_tables.texture.sized())
                .uv(uv)
                .maintain_aspect_ratio(false) // Ignore original aspect ratio
                .fit_to_exact_size(Vec2::splat(64.0))
                .sense(Sense::click());
            ui.add(tile_image);
            ui.end_row();

            ui.strong("Tile Index:");
            if tile.is_some() {
                ui.label(format!("${index:02X}"));
            }
            ui.end_row();

            ui.strong("Tile Address:");
            if tile.is_some() {
                ui.label(format!("${tile_addr:04X}"));
            }
            ui.end_row();
        });
    }

    fn oam(&mut self, ui: &mut Ui) {
        let mut zoom = self.oam.zoom;
        let selected = self.oam.oam_selected;
        pane_header(
            ui,
            "oam",
            &mut zoom,
            true,
            selected.is_some(),
            |ui, menu| {
                if menu == HeaderMenu::Detail {
                    self.oam_tile(ui, "oam_selected", selected);
                    return;
                }
                let res = ui
                    .checkbox(&mut self.oam.show_tile_grid, "Tile Grid")
                    .on_hover_text("Show grid lines between tiles.");
                if res.changed() {
                    // TODO: update config
                }
            },
        );
        self.oam.zoom = zoom;

        let oam_texture_size = self.oam.oam_texture.size;
        let sprites_texture_size = self.oam.sprites_texture.size;
        // The two textures have different dimensions - OAM is a square 8x8 grid of tiles while
        // sprites is a whole 256x240 screen - so zoom sets a shared display height and each keeps
        // its own aspect ratio. Scaling both to a common box instead would either squash the
        // screen or, since `fit_to_exact_size` maintains aspect ratio, silently shrink it to
        // whichever axis fit.
        let display_height = 2.0 * self.oam.zoom * oam_texture_size.y;
        let oam_size = oam_texture_size * (display_height / oam_texture_size.y);
        let sprites_size = sprites_texture_size * (display_height / sprites_texture_size.y);
        {
            let scroll = ScrollArea::both()
                .id_salt("oam_image")
                .min_scrolled_width(oam_texture_size.x + sprites_texture_size.x)
                .min_scrolled_height(oam_texture_size.y.max(sprites_texture_size.y));
            scroll.show(ui, |ui| {
                ui.horizontal(|ui| {
                    // Draw OAM tiles
                    let image = Image::from_texture(self.oam.oam_texture.sized())
                        .fit_to_exact_size(oam_size)
                        .sense(Sense::click());

                    let res = ui.add(image).on_hover_cursor(CursorIcon::Cell);
                    let oam_image_rect = res.rect;

                    if let Some(pos) = res.hover_pos()
                        && oam_image_rect.contains(pos)
                    {
                        self.oam_hover(ui, &res, pos);
                    }

                    if self.oam.show_tile_grid {
                        paint_grid(ui, oam_image_rect, 8.0, 8.0, Color32::LIGHT_BLUE);
                    }

                    // Draw sprites as laid out on screen, at the same height as the OAM tiles
                    let image = Image::from_texture(self.oam.sprites_texture.sized())
                        .fit_to_exact_size(sprites_size)
                        .sense(Sense::click());

                    let res = ui.add(image).on_hover_cursor(CursorIcon::Cell);
                    let spr_image_rect = res.rect;

                    if let Some(pos) = res.hover_pos()
                        && spr_image_rect.contains(pos)
                    {
                        self.sprites_hover(ui, &res, pos);
                    }

                    if self.oam.show_tile_grid {
                        paint_grid(ui, spr_image_rect, 30.0, 32.0, Color32::LIGHT_BLUE);
                    }

                    if let Some(offset) = self.oam.oam_selected {
                        let selection =
                            tile_selection(oam_image_rect, self.oam.oam_texture.size, offset, TILE);
                        animated_dashed_rect(ui, selection, (1.0, Color32::WHITE), 3.0, 3.0);

                        let sprite_index =
                            (offset.x / 8.0) as usize + (offset.y / 8.0) as usize * 8;
                        let sprite = self.oam.sprites.get(sprite_index);
                        if let Some(sprite) = sprite {
                            let offset = Vec2::new(
                                ((sprite.x as f32) / 8.0).floor() * 8.0,
                                ((sprite.y as f32) / 8.0).floor() * 8.0,
                            );
                            if offset.x < ppu::size::WIDTH as f32
                                && offset.y < ppu::size::HEIGHT as f32
                            {
                                let selection = tile_selection(
                                    spr_image_rect,
                                    self.oam.sprites_texture.size,
                                    offset,
                                    TILE,
                                );
                                animated_dashed_rect(
                                    ui,
                                    selection,
                                    (1.0, Color32::WHITE),
                                    3.0,
                                    3.0,
                                );
                            }
                        }
                    }
                });
            });
        }
    }

    fn oam_hover(&mut self, ui: &mut Ui, res: &egui::Response, pos: Pos2) {
        let image_rect = res.rect;
        let texture_size = self.oam.oam_texture.size;

        let offset = translate_screen_pos_to_tile(pos, image_rect, texture_size, TILE);
        let selection = tile_selection(image_rect, texture_size, offset, TILE);

        animated_dashed_rect(
            ui,
            selection,
            (1.0, Color32::from_white_alpha(220)),
            3.0,
            3.0,
        );

        let sprite_index = (offset.x / 8.0) as usize + (offset.y / 8.0) as usize * 8;
        let sprite = self.oam.sprites.get(sprite_index);
        if sprite.is_some() {
            res.clone().on_hover_ui_at_pointer(|ui| {
                self.oam_tile(ui, "oam_hover", Some(offset));
            });
            if res.clicked() {
                self.oam.oam_selected = Some(offset);
            }
        }
    }

    fn sprites_hover(&mut self, ui: &mut Ui, res: &egui::Response, pos: Pos2) {
        let image_rect = res.rect;
        let texture_size = self.oam.sprites_texture.size;

        let offset = translate_screen_pos_to_tile(pos, image_rect, texture_size, TILE);
        let selection = tile_selection(image_rect, texture_size, offset, TILE);

        animated_dashed_rect(
            ui,
            selection,
            (1.0, Color32::from_white_alpha(220)),
            3.0,
            3.0,
        );

        let sprite_index = self.oam.sprites.iter().position(|sprite| {
            let grid_x = sprite.x as f32 / 8.0;
            let grid_y = sprite.y as f32 / 8.0;
            let x_min = grid_x.floor() * 8.0;
            let x_max = grid_x.ceil() * 8.0;
            let y_min = grid_y.floor() * 8.0;
            let y_max = grid_y.ceil() * 8.0;
            (x_min..=x_max).contains(&offset.x) && (y_min..=y_max).contains(&offset.y)
        });
        if let Some(index) = sprite_index {
            let offset = Vec2::new((index % 8) as f32, (index / 8) as f32) * 8.0;

            res.clone().on_hover_ui_at_pointer(|ui| {
                self.oam_tile(ui, "oam_hover", Some(offset));
            });
            if res.clicked() {
                self.oam.oam_selected = Some(offset);
            }
        }
    }

    fn oam_tile(&mut self, ui: &mut Ui, label: &str, offsets: Option<Vec2>) {
        let tile =
            offsets.map(|offset| self.oam_tile_from_offset(offset, self.oam.oam_texture.size));
        let ChrTile {
            uv,
            index,
            tile_addr,
            ..
        } = tile.unwrap_or_default();

        let grid = Grid::new(label).num_columns(2).spacing([40.0, 6.0]);
        grid.show(ui, |ui| {
            ui.strong("Tile:");
            let tile_image = Image::from_texture(self.oam.oam_texture.sized())
                .uv(uv)
                .maintain_aspect_ratio(false) // Ignore original aspect ratio
                .fit_to_exact_size(Vec2::splat(64.0))
                .sense(Sense::click());
            ui.add(tile_image);
            ui.end_row();

            ui.strong("Tile Index:");
            if tile.is_some() {
                ui.label(format!("${index:02X}"));
            }
            ui.end_row();

            ui.strong("Tile Address:");
            if tile.is_some() {
                ui.label(format!("${tile_addr:04X}"));
            }
            ui.end_row();

            // TODO: sprite index, palette address, position, horizontal/vertical flip/backgroud
            // priority, palette row
        });
    }

    fn oam_tile_from_offset(&self, offset: Vec2, texture_size: Vec2) -> ChrTile {
        let Vec2 { x, y } = offset;

        // Get row/column 8x8 tile
        let col = x as u16 / 8;
        let row = y as u16 / 8;

        let tile_uv = Rect::from_min_size(
            (Vec2::new(x, y) / texture_size).to_pos2(),
            Vec2::splat(8.0) / texture_size,
        );
        let index = col + (row * 8);
        ChrTile {
            index,
            uv: tile_uv,
            tile_addr: self.oam.sprites[index as usize].tile_addr,
        }
    }

    fn palette_pane(&mut self, ui: &mut Ui) {
        let mut zoom = self.palette.zoom;
        let selected = self.palette.selected;
        pane_header(
            ui,
            "palette",
            &mut zoom,
            false,
            selected.is_some(),
            |ui, menu| {
                if menu == HeaderMenu::Detail {
                    self.palette(ui, "palette_info_selected", selected);
                }
            },
        );
        self.palette.zoom = zoom;

        {
            ScrollArea::both().id_salt("palette_image").show(ui, |ui| {
                ui.horizontal(|ui| {
                    let res = self
                        .palette_grid(ui, self.palette.zoom * self.palette.size)
                        .on_hover_cursor(CursorIcon::Cell);
                    let palette_rect = res.rect;

                    if let Some(pos) = res.hover_pos()
                        && palette_rect.contains(pos)
                    {
                        self.palette_hover(ui, &res, pos);
                    }

                    if let Some(offset) = self.palette.selected {
                        let selection =
                            tile_selection(palette_rect, self.palette.size, offset, SWATCH);
                        animated_dashed_rect(ui, selection, (1.0, Color32::WHITE), 3.0, 3.0);
                    }
                });
            });
        }
    }

    fn palette_hover(&mut self, ui: &mut Ui, res: &egui::Response, pos: Pos2) {
        let image_rect = res.rect;

        let offset = translate_screen_pos_to_tile(pos, image_rect, self.palette.size, SWATCH);
        let selection = tile_selection(image_rect, self.palette.size, offset, SWATCH);

        animated_dashed_rect(
            ui,
            selection,
            (1.0, Color32::from_white_alpha(220)),
            3.0,
            3.0,
        );

        res.clone().on_hover_ui_at_pointer(|ui| {
            self.palette(ui, "palette_hover", Some(offset));
        });
        if res.clicked() {
            self.palette.selected = Some(offset);
        }
    }

    fn palette_color_from_offset(&self, offset: Vec2) -> PaletteColor {
        let Vec2 { x, y } = offset;

        // Get row/column 32x32 palette and the palette table it's in
        let mut col = (x as u16 / SWATCH as u16).min(7);
        let row = (y as u16 / SWATCH as u16).min(3);
        let palette = if col >= 4 { 1 } else { 0 };

        // Wrap column to a single palette table
        col &= 3;

        let index = col + row * 4;
        let color_index = palette * 0x10 + index;
        let pixel_idx = color_index as usize * 4;
        PaletteColor {
            index: index as u8,
            addr: addr::PALETTE_START + color_index,
            value: self.palette.colors[color_index as usize],
            color: if let [red, green, blue] = self.palette.pixels[pixel_idx..pixel_idx + 3] {
                Color32::from_rgb(red, green, blue)
            } else {
                Color32::default()
            },
        }
    }

    fn palette(&mut self, ui: &mut Ui, label: &str, offset: Option<Vec2>) {
        let palette = offset.map(|offset| self.palette_color_from_offset(offset));
        let PaletteColor {
            index,
            value,
            color,
            addr,
            ..
        } = palette.unwrap_or_default();

        let grid = Grid::new(label).num_columns(2).spacing([40.0, 6.0]);
        grid.show(ui, |ui| {
            ui.strong("Color:");
            let (rect, _) = ui.allocate_exact_size(Vec2::splat(32.0), Sense::hover());
            ui.painter().rect_filled(rect, 1.0, color);
            ui.end_row();

            ui.strong("Index:");
            if palette.is_some() {
                ui.label(format!("${index:02X}"));
            }
            ui.end_row();

            ui.strong("Value:");
            if palette.is_some() {
                ui.label(format!("${value:02X}"));
            }
            ui.end_row();

            ui.strong("Palette Address:");
            if palette.is_some() {
                ui.label(format!("${addr:02X}"));
            }
            ui.end_row();

            ui.strong("Hex:");
            if palette.is_some() {
                ui.label(&color.to_hex()[0..7]); // Truncate the alpha channel
            }
            ui.end_row();

            ui.strong("RGB:");
            if palette.is_some() {
                let (r, g, b, _) = &color.to_tuple();
                ui.label(format!("({r:03}, {g:03}, {b:03})"));
            }
            ui.end_row();
        });
    }

    fn palette_row(&self, ui: &mut Ui, index: usize, pos: Pos2, size: Vec2, show_backdrop: bool) {
        for x in 0..4 {
            let mut idx = (index * 4 + x) * 4;
            if show_backdrop && x == 0 {
                idx = 0;
            }
            if let [red, green, blue] = self.palette.pixels[idx..idx + 3] {
                let pos = pos + Vec2::new(x as f32 * size.x, 0.0);
                let rect = Rect::from_min_max(pos, pos + size);
                ui.painter()
                    .rect_filled(rect, 0.0, Color32::from_rgb(red, green, blue));
            }
        }
    }

    fn palette_grid(&self, ui: &mut Ui, size: Vec2) -> egui::Response {
        ui.vertical(|ui| {
            ui.horizontal(|ui| {
                let res = ui.add(Label::new("Background"));
                ui.add_space(size.x / 2.0 - res.rect.width());
                ui.add(Label::new("Sprites"));
            });

            let (rect, res) = ui.allocate_exact_size(size, Sense::click());
            ui.painter()
                .rect_stroke(rect, 0.0, (1.0, Color32::BLACK), StrokeKind::Inside);

            let size = Vec2::new(size.x / 8.0, size.y / 4.0);
            for offset in [0, 4] {
                for (y, index) in (offset..offset + 4).enumerate() {
                    let pos =
                        rect.min + Vec2::new(offset as f32 * size.x, y as f32 * size.y).floor();
                    self.palette_row(ui, index, pos, size, false);
                }
            }

            res
        })
        .inner
    }
}

/// The dividers and tile grid one view draws over its image.
fn grid_settings(ui: &mut Ui, dividers: &mut bool, tile_grid: &mut bool) {
    let res = ui
        .checkbox(dividers, "Table Dividers")
        .on_hover_text("Show divider lines between tables.");
    if res.changed() {
        // TODO: update config
    }

    let res = ui
        .checkbox(tile_grid, "Tile Grid")
        .on_hover_text("Show grid lines between tiles.");
    if res.changed() {
        // TODO: update config
    }
}

/// A pane's own controls: how far its view is zoomed, and the two menus `menu` fills.
///
/// One row rather than a side panel, since four panes are on screen at once and each has only its
/// own view's width to work in.
fn pane_header(
    ui: &mut Ui,
    id: &str,
    zoom: &mut f32,
    settings: bool,
    selected: bool,
    mut menu: impl FnMut(&mut Ui, HeaderMenu),
) {
    // Every pane draws the same three widgets, so the pane's name keeps four ⚙ menus apart.
    ui.push_id(id, |ui| {
        ui.horizontal(|ui| {
            let drag = Slider::new(zoom, 0.1..=5.0).step_by(0.05).suffix("x");
            let res = ui.add(drag);
            if res.changed() {
                // TODO: update config
            }
            if settings {
                MenuButton::new("⚙")
                    .config(
                        MenuConfig::new().close_behavior(PopupCloseBehavior::CloseOnClickOutside),
                    )
                    .ui(ui, |ui| menu(ui, HeaderMenu::Settings));
            }
            ui.add_enabled_ui(selected, |ui| {
                MenuButton::new("Selected").ui(ui, |ui| menu(ui, HeaderMenu::Detail));
            });
        });
    });
    ui.separator();
}

/// A grid overlay.
fn paint_grid(ui: &mut Ui, rect: Rect, y_spacing: f32, x_spacing: f32, color: Color32) {
    let min = rect.min;
    let max = rect.max;
    let size = rect.size();
    let x_increment = size.x / x_spacing;
    let mut x = min.x + x_increment;
    while x < max.x {
        ui.painter().vline(x, rect.y_range(), (1.0, color));
        x += x_increment;
    }

    let y_increment = size.y / y_spacing;
    let mut y = min.y + y_increment;
    while y < max.y {
        ui.painter().hline(rect.x_range(), y, (1.0, color));
        y += y_increment;
    }
}

/// Translate position in screen space to texture space and find containing 8x8 tile offset
fn translate_screen_pos_to_tile(
    pos: Pos2,
    image_rect: Rect,
    texture_size: Vec2,
    cell: f32,
) -> Vec2 {
    let normalized_pos = (pos - image_rect.min) / image_rect.size();
    let texture_pos = normalized_pos * texture_size;
    (texture_pos / cell).floor() * cell
}

/// Return tile selection rectangle given an offset.
fn tile_selection(image_rect: Rect, texture_size: Vec2, tile_offset: Vec2, cell: f32) -> Rect {
    let scale = image_rect.size() / texture_size;
    Rect::from_min_size(
        image_rect.min + scale * tile_offset,
        scale * Vec2::splat(cell),
    )
}