neser 0.3.1

NESER - NES Emulator in Rust. Desktop (SDL) and WebAssembly frontends.
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
pub mod background;
pub mod registers;
pub mod rendering;
pub mod screen_buffer;
pub mod sprites;
pub mod timing;
pub mod window;

use registers::Registers;
use screen_buffer::ScreenBuffer;
use timing::{PpuMode, Timing};

/// DMG PPU.
///
/// Owns VRAM ($8000–$9FFF) and OAM ($FE00$FE9F) buffers, all I/O registers,
/// timing state, and the rendered screen buffer.
pub struct Ppu {
    pub vram: [u8; 0x2000],
    pub oam: [u8; 0xA0],
    timing: Timing,
    registers: Registers,
    screen_buffer: ScreenBuffer,
    /// Pending interrupt bits for IF register (bit 0 = VBlank, bit 1 = STAT).
    pending_interrupts: u8,
    /// Internal window-line counter (increments each scanline where window is drawn).
    window_line: u8,
    /// Previous STAT IRQ line state for edge detection.
    prev_stat_irq_line: bool,
}

impl Ppu {
    pub fn new() -> Self {
        Self {
            vram: [0u8; 0x2000],
            oam: [0u8; 0xA0],
            timing: Timing::new(),
            registers: Registers::new(),
            screen_buffer: ScreenBuffer::new(),
            pending_interrupts: 0,
            window_line: 0,
            prev_stat_irq_line: false,
        }
    }

    // ── Dot-level tick ────────────────────────────────────────────────────────

    /// Advance the PPU by `n` dots (T-cycles).
    ///
    /// Call from `DmgBus::tick(m_cycles)` with `n = m_cycles * 4`.
    /// No-op when the LCD is disabled (LCDC bit 7 = 0).
    pub fn tick_dots(&mut self, n: u32) {
        if !self.registers.lcd_enabled() {
            return;
        }
        for _ in 0..n {
            self.tick_one_dot();
        }
    }

    fn tick_one_dot(&mut self) {
        // LCD off (LCDC bit 7 = 0): PPU is completely frozen.
        if self.registers.lcdc & 0x80 == 0 {
            return;
        }
        let lyc = self.registers.lyc;
        let events = self.timing.tick_dot(lyc);

        // Render the current visible scanline when Mode 3→Mode 0 transition fires.
        if events.render_scanline {
            let scanline = self.timing.ly();
            rendering::render_scanline(
                scanline,
                &self.vram,
                &self.oam,
                &self.registers,
                &mut self.window_line,
                &mut self.screen_buffer,
            );
        }

        // V-Blank interrupt (IF bit 0).
        if events.vblank_start {
            self.pending_interrupts |= 0x01;
        }

        // Reset window-line counter at the start of a new frame.
        if events.new_frame {
            self.window_line = 0;
        }

        // STAT interrupt — edge-triggered on the STAT IRQ source line.
        self.update_stat_irq();
    }

    // ── STAT IRQ line ─────────────────────────────────────────────────────────

    fn compose_stat_byte(&self) -> u8 {
        // When LCD is off, mode bits report 0 (H-Blank) and LYC=LY is 0.
        if !self.registers.lcd_enabled() {
            return self.registers.stat_irq_enables & 0x78;
        }
        let mode_bits = self.timing.mode() as u8;
        let lyc_bit = if self.timing.ly() == self.registers.lyc {
            0x04
        } else {
            0x00
        };
        (self.registers.stat_irq_enables & 0x78) | lyc_bit | mode_bits
    }

    /// Evaluate the STAT IRQ source line and fire a STAT interrupt on 0→1 edge.
    fn update_stat_irq(&mut self) {
        let mode = self.timing.mode();
        let ly = self.timing.ly();
        let lyc = self.registers.lyc;
        let en = self.registers.stat_irq_enables;

        // During the first scanline after LCD enable, use
        // mode_for_interrupt = -1, which suppresses all mode-based STAT
        // interrupts. Only the LYC=LY source can fire.
        let suppress_mode_irqs = self.timing.is_first_scanline_after_enable();

        let irq_line = (en & 0x40 != 0 && ly == lyc)
            || (!suppress_mode_irqs && en & 0x20 != 0 && mode == PpuMode::OamScan)
            || (!suppress_mode_irqs && en & 0x10 != 0 && mode == PpuMode::VBlank)
            || (!suppress_mode_irqs && en & 0x08 != 0 && mode == PpuMode::HBlank);

        if irq_line && !self.prev_stat_irq_line {
            self.pending_interrupts |= 0x02;
        }
        self.prev_stat_irq_line = irq_line;
    }

    // ── Memory-mapped I/O ─────────────────────────────────────────────────────

    /// Read from VRAM address $8000–$9FFF.
    ///
    /// Returns 0xFF if the CPU is blocked (Mode 3 — Pixel Transfer while LCD on).
    /// When LCD is disabled VRAM is always accessible.
    pub fn read_vram(&self, addr: u16) -> u8 {
        if self.registers.lcd_enabled() && self.timing.mode() == PpuMode::PixelTransfer {
            return 0xFF;
        }
        self.vram[(addr - 0x8000) as usize]
    }

    /// Write to VRAM address $8000–$9FFF.
    ///
    /// Silently ignored if the CPU is blocked (Mode 3 — Pixel Transfer while LCD on).
    /// When LCD is disabled VRAM is always accessible.
    pub fn write_vram(&mut self, addr: u16, val: u8) {
        if self.registers.lcd_enabled() && self.timing.mode() == PpuMode::PixelTransfer {
            return;
        }
        self.vram[(addr - 0x8000) as usize] = val;
    }

    /// Read from OAM address $FE00$FE9F.
    ///
    /// During Mode 2 (OAM Scan) while LCD is on: returns 0xFF and applies
    /// the OAM read-corruption side effect to the PPU's currently scanned row.
    /// During Mode 3 (Pixel Transfer) while LCD is on: returns 0xFF (no corruption).
    /// When LCD is disabled OAM is always accessible without corruption.
    pub fn read_oam(&mut self, addr: u16) -> u8 {
        if self.registers.lcd_enabled() {
            match self.timing.mode() {
                PpuMode::OamScan => {
                    if let Some(row) = self.current_oam_row() {
                        self.apply_oam_read_corruption(row);
                    }
                    return 0xFF;
                }
                PpuMode::PixelTransfer => return 0xFF,
                _ => {}
            }
        }
        self.oam[(addr - 0xFE00) as usize]
    }

    /// Write to OAM address $FE00$FE9F.
    ///
    /// During Mode 2 (OAM Scan) while LCD is on: applies the OAM write-corruption
    /// formula to the PPU's currently scanned row; the actual written value is discarded.
    /// During Mode 3 (Pixel Transfer) while LCD is on: write silently ignored.
    /// When LCD is disabled OAM is always accessible without corruption.
    pub fn write_oam(&mut self, addr: u16, val: u8) {
        if self.registers.lcd_enabled() {
            match self.timing.mode() {
                PpuMode::OamScan => {
                    if let Some(row) = self.current_oam_row() {
                        self.apply_oam_write_corruption(row);
                    }
                    return;
                }
                PpuMode::PixelTransfer => return,
                _ => {}
            }
        }
        self.oam[(addr - 0xFE00) as usize] = val;
    }

    /// Read a PPU I/O register ($FF40$FF4B).
    ///
    /// When LCD is disabled, LY always reads as 0 and STAT mode bits are 0.
    pub fn read_register(&self, addr: u16) -> u8 {
        let stat = self.compose_stat_byte();
        let ly = if self.registers.lcd_enabled() {
            self.timing.ly()
        } else {
            0
        };
        self.registers.read(addr, ly, stat).unwrap_or(0xFF)
    }

    /// Write a PPU I/O register ($FF40$FF4B).
    ///
    /// Detects LCD 0→1 enable transition (LCDC bit 7) and resets PPU timing
    /// to scanline 0 / Mode 2, as the hardware does.
    pub fn write_register(&mut self, addr: u16, val: u8) {
        let was_enabled = self.registers.lcd_enabled();
        self.registers.write(addr, val);
        if !was_enabled && self.registers.lcd_enabled() {
            self.timing = Timing::new();
            self.window_line = 0;
            self.prev_stat_irq_line = false;
        }
    }

    // ── Interrupt interface ───────────────────────────────────────────────────

    /// Take pending interrupt bits and clear them.
    ///
    /// The caller (DmgBus) ORs these into the IF register ($FF0F).
    pub fn take_pending_interrupts(&mut self) -> u8 {
        let flags = self.pending_interrupts;
        self.pending_interrupts = 0;
        flags
    }

    // ── Frame output ──────────────────────────────────────────────────────────

    pub fn screen_buffer(&self) -> &ScreenBuffer {
        &self.screen_buffer
    }

    pub fn is_frame_ready(&self) -> bool {
        self.timing.is_frame_ready()
    }

    pub fn clear_frame_ready(&mut self) {
        self.timing.clear_frame_ready();
    }

    // ── OAM corruption bug helpers ────────────────────────────────────────────

    /// Returns the OAM row currently being scanned by the PPU.
    ///
    /// Returns `Some(row)` during Mode 2 (OAM Scan) when LCD is enabled.
    /// Returns `None` outside Mode 2 or when LCD is disabled.
    /// Row 0 maps to dots 0–3, row 1 to dots 4–7, …, row 19 to dots 76–79.
    pub fn current_oam_row(&self) -> Option<usize> {
        if !self.registers.lcd_enabled() || self.timing.mode() != PpuMode::OamScan {
            return None;
        }
        Some(self.timing.dot() as usize / 4)
    }

    /// Apply OAM write corruption to the given row.
    ///
    /// Row 0 is immune. Formula: `row[0] = ((a^c)&(b^c))^c` where
    /// `a`=row[0], `b`=prev_row[0], `c`=prev_row[2]; words 1–3 copied from prev row.
    pub fn apply_oam_write_corruption(&mut self, row: usize) {
        if row == 0 {
            return;
        }
        let prev = row - 1;
        let a = self.oam_word(row, 0);
        let b = self.oam_word(prev, 0);
        let c = self.oam_word(prev, 2);
        let prev_w1 = self.oam_word(prev, 1);
        let prev_w2 = self.oam_word(prev, 2);
        let prev_w3 = self.oam_word(prev, 3);
        let new_word0 = ((a ^ c) & (b ^ c)) ^ c;
        self.set_oam_word(row, 0, new_word0);
        self.set_oam_word(row, 1, prev_w1);
        self.set_oam_word(row, 2, prev_w2);
        self.set_oam_word(row, 3, prev_w3);
    }

    /// Apply OAM read corruption to the given row.
    ///
    /// Row 0 is immune. Formula: `row[0] = b|(a&c)` where
    /// `a`=row[0], `b`=prev_row[0], `c`=prev_row[2]; words 1–3 copied from prev row.
    pub fn apply_oam_read_corruption(&mut self, row: usize) {
        if row == 0 {
            return;
        }
        let prev = row - 1;
        let a = self.oam_word(row, 0);
        let b = self.oam_word(prev, 0);
        let c = self.oam_word(prev, 2);
        let prev_w1 = self.oam_word(prev, 1);
        let prev_w2 = self.oam_word(prev, 2);
        let prev_w3 = self.oam_word(prev, 3);
        let new_word0 = b | (a & c);
        self.set_oam_word(row, 0, new_word0);
        self.set_oam_word(row, 1, prev_w1);
        self.set_oam_word(row, 2, prev_w2);
        self.set_oam_word(row, 3, prev_w3);
    }

    /// Apply the OAM Read-During-IDU corruption pattern to the given row.
    ///
    /// For rows 4–18: applies the 4-operand complex formula to the preceding row,
    /// copies it up and down two rows, then applies read corruption on the current row.
    /// For rows 1–3 and row 19: skips the complex part; applies only read corruption.
    /// Row 0 is immune.
    pub fn apply_oam_read_idu_corruption(&mut self, row: usize) {
        const LAST_ROW: usize = 19;
        if row == 0 {
            return;
        }
        // Complex part applies only when row is 4–18 (not first four, not last).
        if (4..LAST_ROW).contains(&row) {
            let n = row;
            let prev = n - 1;
            let prev2 = n - 2;
            let a = self.oam_word(prev2, 0);
            let b = self.oam_word(prev, 0);
            let c = self.oam_word(n, 0);
            let d = self.oam_word(prev, 2);
            let new_b = (b & (a | c | d)) | (a & c & d);
            // Step 1: update word 0 of preceding row.
            self.set_oam_word(prev, 0, new_b);
            // Step 2: copy the (updated) preceding row to row n and row n-2.
            let w0 = self.oam_word(prev, 0);
            let w1 = self.oam_word(prev, 1);
            let w2 = self.oam_word(prev, 2);
            let w3 = self.oam_word(prev, 3);
            self.set_oam_word(prev2, 0, w0);
            self.set_oam_word(prev2, 1, w1);
            self.set_oam_word(prev2, 2, w2);
            self.set_oam_word(prev2, 3, w3);
            self.set_oam_word(n, 0, w0);
            self.set_oam_word(n, 1, w1);
            self.set_oam_word(n, 2, w2);
            self.set_oam_word(n, 3, w3);
        }
        // Always apply normal read corruption to the current row.
        self.apply_oam_read_corruption(row);
    }

    // ── OAM word accessors (used by corruption helpers) ───────────────────────

    fn oam_word(&self, row: usize, word: usize) -> u16 {
        let base = row * 8 + word * 2;
        u16::from_le_bytes([self.oam[base], self.oam[base + 1]])
    }

    fn set_oam_word(&mut self, row: usize, word: usize, val: u16) {
        let base = row * 8 + word * 2;
        let bytes = val.to_le_bytes();
        self.oam[base] = bytes[0];
        self.oam[base + 1] = bytes[1];
    }
}

impl Default for Ppu {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tick_dots(ppu: &mut Ppu, n: u32) {
        ppu.tick_dots(n);
    }

    /// Number of dots in the first scanline after LCD enable (starts at dot 4).
    const FIRST_SCANLINE_DOTS: u32 = 452;

    /// Advance PPU past the first scanline (which has no Mode 2) to the start
    /// of Mode 2 on scanline 1. The first scanline after LCD enable is special:
    /// it starts at dot 4 in Mode 0 with no OAM Scan period.
    fn advance_to_mode_2(ppu: &mut Ppu) {
        tick_dots(ppu, FIRST_SCANLINE_DOTS);
        assert_eq!(ppu.timing.mode(), PpuMode::OamScan);
        assert_eq!(ppu.timing.ly(), 1);
    }

    // ── VRAM bus-conflict blocking ─────────────────────────────────────────────

    #[test]
    fn test_vram_readable_during_hblank() {
        // Given: a Ppu ticked to Mode 0 (H-Blank, dot 252 on scanline 0)
        let mut ppu = Ppu::new();
        ppu.write_vram(0x8010, 0xAB);
        tick_dots(&mut ppu, 252); // dot 252 → Mode 0
        assert_eq!(ppu.timing.mode(), PpuMode::HBlank);
        // When: read VRAM during H-Blank
        // Then: real value returned
        assert_eq!(ppu.read_vram(0x8010), 0xAB);
    }

    #[test]
    fn test_vram_blocked_during_pixel_transfer_returns_0xff() {
        // Given: a Ppu ticked into Mode 3 (dot 80, scanline 0)
        let mut ppu = Ppu::new();
        ppu.vram[0x0010] = 0xAB; // bypass write_vram to seed value
        tick_dots(&mut ppu, 80); // dot 80 → Mode 3
        assert_eq!(ppu.timing.mode(), PpuMode::PixelTransfer);
        // When: CPU attempts to read VRAM
        assert_eq!(ppu.read_vram(0x8010), 0xFF); // blocked
    }

    #[test]
    fn test_vram_write_blocked_during_pixel_transfer() {
        // Given: a Ppu ticked to Mode 3
        let mut ppu = Ppu::new();
        tick_dots(&mut ppu, 80);
        assert_eq!(ppu.timing.mode(), PpuMode::PixelTransfer);
        // When: CPU writes VRAM
        ppu.write_vram(0x8000, 0x42);
        // Then: write is ignored; VRAM unchanged
        tick_dots(&mut ppu, 172); // exit Mode 3
        assert_eq!(ppu.read_vram(0x8000), 0x00);
    }

    // ── OAM bus-conflict blocking ──────────────────────────────────────────────

    #[test]
    fn test_oam_blocked_during_oam_scan_returns_0xff() {
        // Given: a Ppu advanced to Mode 2 (OAM Scan) on a normal scanline
        let mut ppu = Ppu::new();
        ppu.oam[0] = 0x55;
        advance_to_mode_2(&mut ppu);
        // When: CPU reads OAM during Mode 2
        assert_eq!(ppu.read_oam(0xFE00), 0xFF);
    }

    #[test]
    fn test_oam_readable_during_hblank() {
        // Given: a Ppu at H-Blank (dot 252)
        let mut ppu = Ppu::new();
        ppu.oam[0] = 0x77;
        tick_dots(&mut ppu, 252);
        assert_eq!(ppu.timing.mode(), PpuMode::HBlank);
        // When: CPU reads OAM
        assert_eq!(ppu.read_oam(0xFE00), 0x77);
    }

    #[test]
    fn test_oam_write_blocked_during_oam_scan() {
        // Given: Ppu in Mode 2 on a normal scanline
        let mut ppu = Ppu::new();
        advance_to_mode_2(&mut ppu);
        // When: write OAM
        ppu.write_oam(0xFE00, 0xAA);
        // Then: ignored
        tick_dots(&mut ppu, 252); // advance to H-Blank where reads are unblocked
        assert_eq!(ppu.read_oam(0xFE00), 0x00);
    }

    // ── VBlank interrupt ───────────────────────────────────────────────────────

    #[test]
    fn test_vblank_interrupt_fires_at_scanline_144() {
        // Given: a Ppu ticked to the last dot before scanline 144
        // First scanline is 452 dots, remaining 142 are 456 each
        let mut ppu = Ppu::new();
        tick_dots(&mut ppu, FIRST_SCANLINE_DOTS + 456 * 142 + 455); // dot 455 of scanline 143
        assert_eq!(ppu.take_pending_interrupts() & 0x01, 0);
        // When: tick 1 more dot → scanline 144, Mode 1 entry
        ppu.tick_dots(1);
        // Then: VBlank interrupt pending (bit 0)
        let flags = ppu.take_pending_interrupts();
        assert_eq!(flags & 0x01, 0x01, "expected VBlank interrupt bit set");
    }

    #[test]
    fn test_vblank_interrupt_fires_only_once_per_frame() {
        // Given: a Ppu already past VBlank entry
        let mut ppu = Ppu::new();
        tick_dots(&mut ppu, 456 * 144); // enter VBlank
        let flags = ppu.take_pending_interrupts();
        assert_eq!(flags & 0x01, 0x01);
        // When: tick more dots within VBlank
        tick_dots(&mut ppu, 456);
        // Then: no second VBlank interrupt
        let flags2 = ppu.take_pending_interrupts();
        assert_eq!(flags2 & 0x01, 0x00);
    }

    // ── STAT interrupt ─────────────────────────────────────────────────────────

    #[test]
    fn test_stat_interrupt_fires_on_lyc_ly_match_when_enabled() {
        // Given: LYC = 5, STAT bit 6 (LYC=LY interrupt) enabled
        let mut ppu = Ppu::new();
        ppu.write_register(0xFF45, 5); // LYC = 5
        ppu.write_register(0xFF41, 0x40); // STAT bit 6 = LYC=LY IRQ enable
        // First scanline is 452 dots; scanlines 1-4 are 456 each
        tick_dots(&mut ppu, FIRST_SCANLINE_DOTS + 456 * 3 + 456 - 1); // tick to dot 455 of scanline 4
        // Drain any earlier flags
        let _ = ppu.take_pending_interrupts();
        // When: advance to scanline 5 (LY becomes 5 = LYC)
        ppu.tick_dots(1);
        // Then: STAT interrupt pending (bit 1 of IF)
        let flags = ppu.take_pending_interrupts();
        assert_eq!(
            flags & 0x02,
            0x02,
            "expected STAT interrupt from LYC=LY match"
        );
    }

    #[test]
    fn test_stat_interrupt_not_fired_when_lyc_irq_disabled() {
        // Given: LYC = 5, but STAT LYC IRQ NOT enabled
        let mut ppu = Ppu::new();
        ppu.write_register(0xFF45, 5);
        // STAT bit 6 = 0 (default)
        tick_dots(&mut ppu, 456 * 4 + 456 - 1);
        let _ = ppu.take_pending_interrupts();
        ppu.tick_dots(1); // advance to scanline 5
        let flags = ppu.take_pending_interrupts();
        assert_eq!(flags & 0x02, 0x00);
    }

    // ── Frame ready ───────────────────────────────────────────────────────────

    #[test]
    fn test_frame_not_ready_before_full_frame() {
        let mut ppu = Ppu::new();
        let total = FIRST_SCANLINE_DOTS + 456 * 153;
        tick_dots(&mut ppu, total - 1);
        assert!(!ppu.is_frame_ready());
    }

    #[test]
    fn test_frame_ready_after_154_scanlines() {
        let mut ppu = Ppu::new();
        let total = FIRST_SCANLINE_DOTS + 456 * 153;
        tick_dots(&mut ppu, total);
        assert!(ppu.is_frame_ready());
    }

    #[test]
    fn test_clear_frame_ready_resets_flag() {
        let mut ppu = Ppu::new();
        let total = FIRST_SCANLINE_DOTS + 456 * 153;
        tick_dots(&mut ppu, total);
        assert!(ppu.is_frame_ready());
        ppu.clear_frame_ready();
        assert!(!ppu.is_frame_ready());
    }

    // ── Register interface ────────────────────────────────────────────────────

    #[test]
    fn test_lcdc_register_round_trip() {
        let mut ppu = Ppu::new();
        ppu.write_register(0xFF40, 0x00);
        assert_eq!(ppu.read_register(0xFF40), 0x00);
    }

    #[test]
    fn test_stat_mode_bits_reflect_current_mode() {
        // At startup: first scanline after LCD enable reports Mode 0 (HBlank)
        let ppu = Ppu::new();
        let stat = ppu.read_register(0xFF41);
        assert_eq!(stat & 0x03, PpuMode::HBlank as u8);
    }

    #[test]
    fn test_ly_register_returns_current_scanline() {
        let mut ppu = Ppu::new();
        tick_dots(&mut ppu, 456 * 10); // advance 10 scanlines
        assert_eq!(ppu.read_register(0xFF44), 10);
    }

    // ── LCD disabled (LCDC bit 7 = 0) ─────────────────────────────────────────
    //
    // Per Pan Docs: when LCDC bit 7 is cleared the LCD stops, LY is fixed at 0,
    // the STAT mode bits report Mode 0, and VRAM/OAM become freely accessible.

    /// Helper: advance PPU into Mode 3 then disable the LCD.
    fn ppu_in_mode3_then_lcd_off() -> Ppu {
        let mut ppu = Ppu::new();
        tick_dots(&mut ppu, 80); // dot 80 → Mode 3
        assert_eq!(ppu.timing.mode(), PpuMode::PixelTransfer);
        ppu.write_register(0xFF40, 0x11); // clear bit 7 (LCD off), keep rest
        ppu
    }

    #[test]
    fn test_vram_write_succeeds_when_lcd_disabled() {
        let mut ppu = ppu_in_mode3_then_lcd_off();
        ppu.write_vram(0x8000, 0x42);
        assert_eq!(
            ppu.vram[0], 0x42,
            "VRAM write should succeed when LCD is off"
        );
    }

    #[test]
    fn test_vram_read_returns_actual_value_when_lcd_disabled() {
        let mut ppu = ppu_in_mode3_then_lcd_off();
        ppu.vram[0x10] = 0xAB;
        let val = ppu.read_vram(0x8010);
        assert_eq!(
            val, 0xAB,
            "VRAM read should return actual value when LCD is off"
        );
    }

    #[test]
    fn test_ppu_does_not_advance_when_lcd_disabled() {
        let mut ppu = ppu_in_mode3_then_lcd_off();
        let ly_before = ppu.read_register(0xFF44);
        ppu.tick_dots(456 * 10);
        let ly_after = ppu.read_register(0xFF44);
        assert_eq!(
            ly_before, ly_after,
            "PPU should not advance when LCD is off"
        );
    }

    #[test]
    fn test_ly_reads_zero_when_lcd_disabled() {
        let mut ppu = Ppu::new();
        tick_dots(&mut ppu, 456 * 50);
        assert_eq!(ppu.timing.ly(), 50);
        ppu.write_register(0xFF40, 0x11); // LCD off
        let ly = ppu.read_register(0xFF44);
        assert_eq!(ly, 0, "LY must read as 0 when LCD is disabled");
    }

    #[test]
    fn test_ppu_timing_resets_when_lcd_enabled_after_off() {
        let mut ppu = Ppu::new();
        tick_dots(&mut ppu, FIRST_SCANLINE_DOTS + 456 * 49);
        ppu.write_register(0xFF40, 0x11); // LCD off
        ppu.tick_dots(456 * 20); // no-op
        ppu.write_register(0xFF40, 0x91); // LCD on
        assert_eq!(
            ppu.timing.ly(),
            0,
            "LY should reset to 0 when LCD is re-enabled"
        );
        assert_eq!(
            ppu.timing.mode(),
            PpuMode::HBlank,
            "PPU should start in HBlank mode when re-enabled (first scanline after LCD enable)"
        );
    }

    #[test]
    fn test_stat_mode_bits_report_mode0_when_lcd_disabled() {
        let ppu = ppu_in_mode3_then_lcd_off();
        let stat = ppu.read_register(0xFF41);
        assert_eq!(
            stat & 0x03,
            0,
            "STAT mode bits must be 0 (Mode 0) when LCD is disabled"
        );
    }

    #[test]
    fn test_oam_write_succeeds_when_lcd_disabled() {
        // Given: PPU advanced to Mode 2 on a normal scanline; LCD turned off.
        // Normally Mode 2 blocks OAM writes; LCD-off lifts that restriction.
        let mut ppu = Ppu::new();
        advance_to_mode_2(&mut ppu);
        ppu.write_register(0xFF40, 0x11); // LCD off
        // When: write OAM
        ppu.write_oam(0xFE10, 0xBB);
        // Then: write accepted
        assert_eq!(
            ppu.oam[0x10], 0xBB,
            "OAM write should succeed when LCD is off"
        );
    }

    #[test]
    fn test_oam_read_returns_actual_value_when_lcd_disabled() {
        // Given: PPU in Mode 3 (PixelTransfer), LCD turned off.
        let mut ppu = ppu_in_mode3_then_lcd_off();
        ppu.oam[0x05] = 0xCC;
        // When: read OAM
        let val = ppu.read_oam(0xFE05);
        // Then: actual value returned (not 0xFF)
        assert_eq!(
            val, 0xCC,
            "OAM read should return actual value when LCD is off"
        );
    }

    // ── OAM corruption: current_oam_row ───────────────────────────────────────

    #[test]
    fn test_current_oam_row_returns_row_0_at_mode_2_start() {
        // Given: Ppu advanced to Mode 2 on scanline 1, dot=0 → row 0/4 = 0
        let mut ppu = Ppu::new();
        advance_to_mode_2(&mut ppu);
        assert_eq!(ppu.timing.mode(), PpuMode::OamScan);
        assert_eq!(ppu.current_oam_row(), Some(0));
    }

    #[test]
    fn test_current_oam_row_returns_row_1_after_4_dot_ticks() {
        // Given: Ppu in Mode 2, dot advances by 4 → row 4/4 = 1
        let mut ppu = Ppu::new();
        advance_to_mode_2(&mut ppu);
        tick_dots(&mut ppu, 4);
        assert_eq!(ppu.timing.dot(), 4);
        assert_eq!(ppu.current_oam_row(), Some(1));
    }

    #[test]
    fn test_current_oam_row_returns_row_19_at_dot_76() {
        // Given: Ppu in Mode 2, dot=76 → row 76/4 = 19 (last Mode 2 row)
        let mut ppu = Ppu::new();
        advance_to_mode_2(&mut ppu);
        tick_dots(&mut ppu, 76);
        assert_eq!(ppu.timing.dot(), 76);
        assert_eq!(ppu.current_oam_row(), Some(19));
    }

    #[test]
    fn test_current_oam_row_returns_none_during_mode_3() {
        // Given: ticked to dot=80 → Mode 3 (Pixel Transfer)
        let mut ppu = Ppu::new();
        tick_dots(&mut ppu, 80);
        assert_eq!(ppu.timing.mode(), PpuMode::PixelTransfer);
        assert_eq!(ppu.current_oam_row(), None);
    }

    #[test]
    fn test_current_oam_row_returns_none_when_lcd_disabled() {
        // Given: LCD disabled; mode stays OamScan but LCD is off
        let mut ppu = Ppu::new();
        advance_to_mode_2(&mut ppu);
        assert_eq!(ppu.timing.mode(), PpuMode::OamScan);
        ppu.write_register(0xFF40, 0x00); // clear LCDC bit 7 → LCD off
        assert_eq!(ppu.current_oam_row(), None);
    }

    // ── OAM corruption: helpers ───────────────────────────────────────────────

    /// Write all four 16-bit words of an OAM row (little-endian).
    fn set_row_words(oam: &mut [u8; 0xA0], row: usize, words: [u16; 4]) {
        let base = row * 8;
        for (i, &w) in words.iter().enumerate() {
            oam[base + i * 2] = w as u8;
            oam[base + i * 2 + 1] = (w >> 8) as u8;
        }
    }

    /// Read all four 16-bit words of an OAM row (little-endian).
    fn get_row_words(oam: &[u8; 0xA0], row: usize) -> [u16; 4] {
        let base = row * 8;
        [0, 1, 2, 3].map(|i| u16::from_le_bytes([oam[base + i * 2], oam[base + i * 2 + 1]]))
    }

    // ── apply_oam_write_corruption ────────────────────────────────────────────

    #[test]
    fn test_write_corruption_applies_formula_to_row() {
        // Given: row 1 (preceding), row 2 (current) with known values.
        // row 1: b=word0=0x0002, word1=0x0003, c=word2=0x0004, word3=0x0005
        // row 2: a=word0=0x0001
        // a^c = 0x0001^0x0004 = 0x0005
        // b^c = 0x0002^0x0004 = 0x0006
        // (a^c)&(b^c) = 0x0005 & 0x0006 = 0x0004
        // result = 0x0004 ^ 0x0004 = 0x0000
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 1, [0x0002, 0x0003, 0x0004, 0x0005]);
        set_row_words(&mut ppu.oam, 2, [0x0001, 0x00AA, 0x00BB, 0x00CC]);
        ppu.apply_oam_write_corruption(2);
        let row2 = get_row_words(&ppu.oam, 2);
        // Then: word 0 = formula result; words 1–3 copied from preceding row 1
        assert_eq!(row2[0], 0x0000, "write corruption: word0 formula mismatch");
        assert_eq!(
            row2[1], 0x0003,
            "write corruption: word1 should come from preceding row"
        );
        assert_eq!(
            row2[2], 0x0004,
            "write corruption: word2 should come from preceding row"
        );
        assert_eq!(
            row2[3], 0x0005,
            "write corruption: word3 should come from preceding row"
        );
    }

    #[test]
    fn test_write_corruption_skips_row_0() {
        // Row 0 (first two objects) must never be corrupted.
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 0, [0x1111, 0x2222, 0x3333, 0x4444]);
        let snapshot = ppu.oam;
        ppu.apply_oam_write_corruption(0);
        assert_eq!(ppu.oam, snapshot, "row 0 is immune to write corruption");
    }

    #[test]
    fn test_write_corruption_does_not_modify_preceding_row() {
        // The preceding row is used as source but must not be mutated.
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 1, [0x00BB, 0x00CC, 0x00DD, 0x00EE]);
        set_row_words(&mut ppu.oam, 2, [0x0001, 0x0002, 0x0003, 0x0004]);
        ppu.apply_oam_write_corruption(2);
        assert_eq!(
            get_row_words(&ppu.oam, 1),
            [0x00BB, 0x00CC, 0x00DD, 0x00EE],
            "preceding row must not be modified by write corruption"
        );
    }

    // ── apply_oam_read_corruption ─────────────────────────────────────────────

    #[test]
    fn test_read_corruption_applies_formula_to_row() {
        // Given: row 2 (preceding), row 3 (current).
        // row 2: b=word0=0x0010, word1=0x0020, c=word2=0x0030, word3=0x0040
        // row 3: a=word0=0x00F0
        // a & c = 0x00F0 & 0x0030 = 0x0030
        // b | (a & c) = 0x0010 | 0x0030 = 0x0030
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 2, [0x0010, 0x0020, 0x0030, 0x0040]);
        set_row_words(&mut ppu.oam, 3, [0x00F0, 0x00A0, 0x00B0, 0x00C0]);
        ppu.apply_oam_read_corruption(3);
        let row3 = get_row_words(&ppu.oam, 3);
        assert_eq!(row3[0], 0x0030, "read corruption: word0 formula mismatch");
        assert_eq!(
            row3[1], 0x0020,
            "read corruption: word1 should come from preceding row"
        );
        assert_eq!(
            row3[2], 0x0030,
            "read corruption: word2 should come from preceding row"
        );
        assert_eq!(
            row3[3], 0x0040,
            "read corruption: word3 should come from preceding row"
        );
    }

    #[test]
    fn test_read_corruption_skips_row_0() {
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 0, [0x1111, 0x2222, 0x3333, 0x4444]);
        let snapshot = ppu.oam;
        ppu.apply_oam_read_corruption(0);
        assert_eq!(ppu.oam, snapshot, "row 0 is immune to read corruption");
    }

    // ── apply_oam_read_idu_corruption ─────────────────────────────────────────

    #[test]
    fn test_read_idu_corruption_complex_formula_for_rows_4_to_18() {
        // Given: row 3 (n-2), row 4 (n-1), row 5 (n) with known values.
        // a=row3[word0]=0x00A0, b=row4[word0]=0x0055,
        // c=row5[word0]=0x000F, d=row4[word2]=0x00C0
        // a|c|d = 0x00A0|0x000F|0x00C0 = 0x00EF
        // b&0x00EF = 0x0055&0x00EF = 0x0045
        // a&c&d = 0 → new_b = 0x0045
        // After: row[3] = row[4] = row[5] = [0x0045, 0x0011, 0x00C0, 0x0022]
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 3, [0x00A0, 0x0001, 0x0002, 0x0003]);
        set_row_words(&mut ppu.oam, 4, [0x0055, 0x0011, 0x00C0, 0x0022]);
        set_row_words(&mut ppu.oam, 5, [0x000F, 0x0099, 0x0088, 0x0077]);
        ppu.apply_oam_read_idu_corruption(5);
        let expected = [0x0045u16, 0x0011, 0x00C0, 0x0022];
        assert_eq!(
            get_row_words(&ppu.oam, 3),
            expected,
            "row n-2 should equal corrupted row n-1"
        );
        assert_eq!(
            get_row_words(&ppu.oam, 4),
            expected,
            "row n-1 word0 should be updated by complex formula"
        );
        assert_eq!(
            get_row_words(&ppu.oam, 5),
            expected,
            "row n should be copied from n-1 then read-corrupted"
        );
    }

    #[test]
    fn test_read_idu_corruption_skips_complex_part_for_row_2() {
        // Row 2 is in "first four rows" (0–3) → complex part skipped, read corruption only.
        // row 1: b=0x0010, word1=0x0021, c(word2)=0x0030, word3=0x0041
        // row 2: a=0x00F0
        // read formula: b|(a&c) = 0x0010|(0x00F0&0x0030) = 0x0010|0x0030 = 0x0030
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 1, [0x0010, 0x0021, 0x0030, 0x0041]);
        set_row_words(&mut ppu.oam, 2, [0x00F0, 0x00AA, 0x00BB, 0x00CC]);
        ppu.apply_oam_read_idu_corruption(2);
        // Row 1 must NOT be modified (complex part skipped)
        assert_eq!(
            get_row_words(&ppu.oam, 1),
            [0x0010, 0x0021, 0x0030, 0x0041],
            "row n-1 must not be modified for rows < 4"
        );
        // Row 2 gets read corruption only
        let row2 = get_row_words(&ppu.oam, 2);
        assert_eq!(
            row2[0], 0x0030,
            "row 2: word0 read corruption formula mismatch"
        );
        assert_eq!(row2[1], 0x0021, "row 2: word1 from preceding row");
        assert_eq!(row2[2], 0x0030, "row 2: word2 from preceding row");
        assert_eq!(row2[3], 0x0041, "row 2: word3 from preceding row");
    }

    #[test]
    fn test_read_idu_corruption_skips_row_0() {
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 0, [0x0001, 0x0002, 0x0003, 0x0004]);
        let snapshot = ppu.oam;
        ppu.apply_oam_read_idu_corruption(0);
        assert_eq!(ppu.oam, snapshot, "row 0 is immune to read+IDU corruption");
    }

    #[test]
    fn test_read_idu_corruption_skips_complex_part_for_last_row() {
        // Row 19 is the last row → complex part skipped, read corruption only.
        // row 18: b=0x0008, word1=0x0009, c(word2)=0x000A, word3=0x000B
        // row 19: a=0x0007
        // read formula: b|(a&c) = 0x0008|(0x0007&0x000A) = 0x0008|0x0002 = 0x000A
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 18, [0x0008, 0x0009, 0x000A, 0x000B]);
        set_row_words(&mut ppu.oam, 19, [0x0007, 0x00FF, 0x00FE, 0x00FD]);
        ppu.apply_oam_read_idu_corruption(19);
        // Row 18 must NOT be modified
        assert_eq!(
            get_row_words(&ppu.oam, 18),
            [0x0008, 0x0009, 0x000A, 0x000B],
            "row 18 must not be modified for last row"
        );
        let row19 = get_row_words(&ppu.oam, 19);
        assert_eq!(row19[0], 0x000A, "last row: word0 read corruption mismatch");
        assert_eq!(row19[1], 0x0009, "last row: word1 from preceding row");
        assert_eq!(row19[2], 0x000A, "last row: word2 from preceding row");
        assert_eq!(row19[3], 0x000B, "last row: word3 from preceding row");
    }

    // ── Phase B: write_oam / read_oam apply corruption during Mode 2 ──────────

    #[test]
    fn test_write_oam_applies_write_corruption_during_mode_2() {
        // Given: OAM data set at row 1 (preceding) and row 2 (current scan row).
        // row 1: b=0x0002, w1=0x0003, c=0x0004, w3=0x0005
        // row 2: a=0x0001
        // write formula: ((a^c)&(b^c))^c = ((0x0001^0x0004)&(0x0002^0x0004))^0x0004
        //   = (0x0005 & 0x0006) ^ 0x0004 = 0x0004 ^ 0x0004 = 0x0000
        // Expected row 2 after corruption: [0x0000, 0x0003, 0x0004, 0x0005]
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 1, [0x0002, 0x0003, 0x0004, 0x0005]);
        set_row_words(&mut ppu.oam, 2, [0x0001, 0x00AA, 0x00BB, 0x00CC]);
        // Advance to Mode 2 on a normal scanline, then tick to row 2
        advance_to_mode_2(&mut ppu);
        tick_dots(&mut ppu, 8); // dot 0 + 8 = dot 8 → current_oam_row() = Some(2)
        assert_eq!(ppu.timing.mode(), PpuMode::OamScan);
        assert_eq!(ppu.current_oam_row(), Some(2));
        // When: CPU writes to any OAM address
        ppu.write_oam(0xFE10, 0xFF);
        // Then: write corruption formula applied to row 2 (not the written value)
        let row2 = get_row_words(&ppu.oam, 2);
        assert_eq!(
            row2[0], 0x0000,
            "write_oam in Mode 2 must apply write corruption to word0"
        );
        assert_eq!(
            row2[1], 0x0003,
            "write_oam in Mode 2: word1 should come from preceding row"
        );
        assert_eq!(
            row2[2], 0x0004,
            "write_oam in Mode 2: word2 should come from preceding row"
        );
        assert_eq!(
            row2[3], 0x0005,
            "write_oam in Mode 2: word3 should come from preceding row"
        );
    }

    #[test]
    fn test_write_oam_does_not_write_actual_value_during_mode_2() {
        // The written value should never appear in OAM — only the corruption formula result.
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 1, [0x0002, 0x0003, 0x0004, 0x0005]);
        set_row_words(&mut ppu.oam, 2, [0x0001, 0x00AA, 0x00BB, 0x00CC]);
        advance_to_mode_2(&mut ppu);
        tick_dots(&mut ppu, 8);
        ppu.write_oam(0xFE10, 0xAB); // written value 0xAB must NOT appear in OAM
        // If 0xAB appears anywhere in row 2, that is wrong
        for i in 0..8 {
            assert_ne!(
                ppu.oam[2 * 8 + i],
                0xAB,
                "written value 0xAB should not appear in OAM after write during Mode 2"
            );
        }
    }

    #[test]
    fn test_read_oam_applies_read_corruption_during_mode_2() {
        // Given: same OAM setup as write test.
        // read formula: b|(a&c) = 0x0002|(0x0001&0x0004) = 0x0002|0x0000 = 0x0002
        // Expected row 2 after corruption: [0x0002, 0x0003, 0x0004, 0x0005]
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 1, [0x0002, 0x0003, 0x0004, 0x0005]);
        set_row_words(&mut ppu.oam, 2, [0x0001, 0x00AA, 0x00BB, 0x00CC]);
        advance_to_mode_2(&mut ppu);
        tick_dots(&mut ppu, 8);
        assert_eq!(ppu.timing.mode(), PpuMode::OamScan);
        // When: CPU reads from any OAM address during Mode 2
        let result = ppu.read_oam(0xFE10);
        // Then: returns 0xFF (blocked) AND applies read corruption as side effect
        assert_eq!(result, 0xFF, "read_oam in Mode 2 must return 0xFF");
        let row2 = get_row_words(&ppu.oam, 2);
        assert_eq!(
            row2[0], 0x0002,
            "read_oam in Mode 2 must apply read corruption to word0"
        );
        assert_eq!(
            row2[1], 0x0003,
            "read_oam in Mode 2: word1 from preceding row"
        );
        assert_eq!(
            row2[2], 0x0004,
            "read_oam in Mode 2: word2 from preceding row"
        );
        assert_eq!(
            row2[3], 0x0005,
            "read_oam in Mode 2: word3 from preceding row"
        );
    }

    #[test]
    fn test_write_oam_does_not_corrupt_during_mode_3() {
        // Mode 3 (Pixel Transfer) blocks OAM writes but does NOT apply corruption.
        let mut ppu = Ppu::new();
        set_row_words(&mut ppu.oam, 2, [0xAAAAu16, 0xBBBB, 0xCCCC, 0xDDDD]);
        tick_dots(&mut ppu, 80); // enter Mode 3
        assert_eq!(ppu.timing.mode(), PpuMode::PixelTransfer);
        let snapshot = ppu.oam;
        ppu.write_oam(0xFE10, 0x42);
        assert_eq!(
            ppu.oam, snapshot,
            "write_oam in Mode 3 must not corrupt OAM"
        );
    }
}