neser 0.1.1

NESER - NES Emulator in Rust - is a NES emulator written in Rust. It aims to be a high-quality, hardware-accurate emulator that is also easy to use and extend. It supports a wide range of NES games and features, including various mappers, audio processing, and input handling. NESER is designed to be modular and extensible, allowing developers to easily add new features or support for additional hardware. It can be run using one of two frontends: a native desktop application using SDL2, or a web application using WebAssembly. The desktop application provides a high-performance, feature-rich experience with support for various input devices and display options, while the web application allows users to play NES games directly in their browsers without needing to install any software in a BYOR manner (Bring Your Own Roms).
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
//! Mapper 81 – NTDEC N715021 (Super Gun)
//!
//! Specifications:
//! - Main: <https://www.nesdev.org/wiki/INES_Mapper_081>
//!
//! Known Limitations:
//! - Only one known game uses this mapper: Super Gun (NTDEC).
//!
//! ## Hardware behavior (unusual)
//!
//! The mapper latches the **four lowest address bits** of a write to $8000–$FFFF;
//! the write *data byte* is ignored entirely.
//!
//! Address bits [3:2] select the 16 KB PRG bank for CPU $8000–$BFFF.
//! Address bits [1:0] select the 8 KB CHR bank for PPU $0000–$1FFF.
//! CPU $C000$FFFF is always fixed to the last 16 KB PRG bank.
//! Mirroring is fixed from the cartridge header (soldered H or V pads).
//!
//! ## Memory map
//!
//! | CPU address  | Description                                |
//! |-------------|---------------------------------------------|
//! | $8000–$BFFF | Switchable 16 KB PRG bank (bits [3:2] of write address) |
//! | $C000$FFFF | Fixed to last 16 KB PRG bank                |
//!
//! | PPU address  | Description                                |
//! |-------------|---------------------------------------------|
//! | $0000–$1FFF | Switchable 8 KB CHR bank (bits [1:0] of write address)  |

use crate::cartridge::{BaseMapper, Mapper, MapperCapabilities};

const PRG_BANK_SIZE: usize = 16 * 1024;
const CHR_BANK_SIZE: usize = 8 * 1024;

/// Mapper 81 – NTDEC N715021
///
/// Specifications: <https://www.nesdev.org/wiki/INES_Mapper_081>
pub struct Mapper81 {
    base: BaseMapper,
    /// Selected 16 KB PRG bank at $8000–$BFFF (address bits [3:2]).
    prg_bank: u8,
    /// Selected 8 KB CHR bank at $0000–$1FFF (address bits [1:0]).
    chr_bank: u8,
}

impl Mapper81 {
    pub fn new(ctx: super::mapper::MapperContext) -> Self {
        let capabilities = MapperCapabilities {
            has_chr_banking: true,
            max_prg_ram_kb: 0,
            prg_bank_size_kb: 16,
            chr_bank_size_kb: 8,
            ..Default::default()
        };
        let mut base = BaseMapper::new(&ctx, capabilities);
        base.configure_prg_banking(PRG_BANK_SIZE);
        base.configure_chr_banking(CHR_BANK_SIZE);
        let mut mapper = Self {
            base,
            prg_bank: 0,
            chr_bank: 0,
        };
        mapper.update_banks();
        mapper
    }

    fn update_banks(&mut self) {
        let last_bank = (self.base.prg_rom().len() / PRG_BANK_SIZE).saturating_sub(1) as i16;
        self.base.select_prg_page(0, self.prg_bank as i16);
        self.base.select_prg_page(1, last_bank);
        self.base.select_chr_page(0, self.chr_bank as i16);
    }
}

impl Mapper for Mapper81 {
    fn base(&self) -> &BaseMapper {
        &self.base
    }

    fn base_mut(&mut self) -> &mut BaseMapper {
        &mut self.base
    }

    /// Any write to $8000–$FFFF latches the four lowest **address** bits.
    /// The data byte is ignored.
    ///
    /// - Address bits [3:2] → 16 KB PRG bank at $8000–$BFFF
    /// - Address bits [1:0] → 8 KB CHR bank at $0000–$1FFF
    fn write_prg(&mut self, addr: u16, _value: u8) {
        if !(0x8000..=0xFFFF).contains(&addr) {
            return;
        }
        self.prg_bank = (addr >> 2) as u8 & 0x03;
        self.chr_bank = addr as u8 & 0x03;
        self.update_banks();
    }

    fn registers_snapshot(&self) -> Vec<u8> {
        vec![self.prg_bank, self.chr_bank]
    }

    fn restore_registers(&mut self, data: &[u8]) {
        if data.len() >= 2 {
            self.prg_bank = data[0];
            self.chr_bank = data[1];
            self.update_banks();
        }
    }

    fn reset(&mut self) {
        self.prg_bank = 0;
        self.chr_bank = 0;
        self.update_banks();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cartridge::NametableLayout;
    use crate::cartridge::mapper::{MapperContext, create_mapper};
    use crate::cartridge::test_helpers::banked_data;

    // Use non-power-of-two bank counts to prevent false-pass via modulo wrapping.
    // PRG: 3 × 16KB = 48 KB; CHR: 3 × 8KB = 24 KB.
    const PRG_BANKS: usize = 3;
    const CHR_BANKS: usize = 3;

    fn make_mapper() -> Mapper81 {
        let prg = banked_data(16 * 1024, PRG_BANKS);
        let chr = banked_data(8 * 1024, CHR_BANKS);
        Mapper81::new(MapperContext::new_for_test(
            81,
            prg,
            chr,
            NametableLayout::Horizontal,
        ))
    }

    // ── Registration ──────────────────────────────────────────────────────────

    #[test]
    fn mapper_81_is_registered() {
        // Given: valid 48 KB PRG-ROM and 24 KB CHR-ROM
        let prg = banked_data(16 * 1024, PRG_BANKS);
        let chr = banked_data(8 * 1024, CHR_BANKS);
        // When: mapper 81 is created through the factory
        let result = create_mapper(MapperContext::new_for_test(
            81,
            prg,
            chr,
            NametableLayout::Horizontal,
        ));
        // Then: factory must succeed
        assert!(
            result.is_ok(),
            "Mapper 81 must be registered in the factory"
        );
    }

    // ── Power-on state ────────────────────────────────────────────────────────

    #[test]
    fn power_on_prg_8000_is_bank_0() {
        // Given: freshly created mapper
        let mapper = make_mapper();
        // Then: $8000 maps to PRG bank 0 (byte value 0)
        assert_eq!(
            mapper.read_prg(0x8000),
            0,
            "$8000 must start at PRG bank 0 at power-on"
        );
    }

    #[test]
    fn power_on_prg_c000_fixed_to_last_bank() {
        // Given: freshly created mapper with PRG_BANKS=3, last bank = 2
        let mapper = make_mapper();
        // Then: $C000 maps to PRG bank 2 (byte value 2)
        assert_eq!(
            mapper.read_prg(0xC000),
            (PRG_BANKS - 1) as u8,
            "$C000–$FFFF must be fixed to last PRG bank at power-on"
        );
    }

    #[test]
    fn power_on_chr_bank_is_0() {
        // Given: freshly created mapper
        let mut mapper = make_mapper();
        // Then: $0000 maps to CHR bank 0 (byte value 0)
        assert_eq!(
            mapper.read_chr(0x0000),
            0,
            "CHR bank 0 at $0000 must be 0 at power-on"
        );
    }

    // ── PRG bank switching ────────────────────────────────────────────────────

    /// The bank is encoded in bits [3:2] of the *write address*, not the data byte.
    #[test]
    fn prg_bank_selected_by_address_bits_3_2() {
        let mut mapper = make_mapper();

        // Write to address $8000 (bits [3:2] = 0b00): PRG bank 0
        mapper.write_prg(0x8000, 0xFF); // data byte must be ignored
        assert_eq!(
            mapper.read_prg(0x8000),
            0,
            "Address $8000 bits[3:2]=0 must select PRG bank 0"
        );

        // Write to address $8004 (bits [3:2] = 0b01): PRG bank 1
        mapper.write_prg(0x8004, 0xFF);
        assert_eq!(
            mapper.read_prg(0x8000),
            1,
            "Address $8004 bits[3:2]=1 must select PRG bank 1"
        );

        // Write to address $8008 (bits [3:2] = 0b10): PRG bank 2
        mapper.write_prg(0x8008, 0xFF);
        assert_eq!(
            mapper.read_prg(0x8000),
            2,
            "Address $8008 bits[3:2]=2 must select PRG bank 2"
        );
    }

    #[test]
    fn prg_data_byte_is_ignored_for_bank_selection() {
        let mut mapper = make_mapper();
        // Write to $8004 (PRG bank 1), using data byte 0x00 (which would be bank 0 if data used)
        mapper.write_prg(0x8004, 0x00);
        assert_eq!(
            mapper.read_prg(0x8000),
            1,
            "Data byte must be ignored; PRG bank from address bits[3:2]"
        );
    }

    #[test]
    fn prg_c000_stays_fixed_after_prg_bank_change() {
        let mut mapper = make_mapper();
        // Switch PRG bank at $8000 to bank 1
        mapper.write_prg(0x8004, 0xFF); // bits[3:2]=1 → PRG bank 1
        // $C000 must still be the last bank (bank 2)
        assert_eq!(
            mapper.read_prg(0xC000),
            (PRG_BANKS - 1) as u8,
            "$C000–$FFFF must remain fixed to last bank after PRG switch"
        );
    }

    #[test]
    fn prg_register_responds_to_any_address_in_8000_ffff() {
        let mut mapper = make_mapper();
        // Write to $C004 (bits[3:2] = 0b01 → PRG bank 1)
        mapper.write_prg(0xC004, 0xFF);
        assert_eq!(
            mapper.read_prg(0x8000),
            1,
            "Register must respond to writes anywhere in $8000–$FFFF"
        );
    }

    // ── CHR bank switching ────────────────────────────────────────────────────

    /// The CHR bank is encoded in bits [1:0] of the *write address*, not the data byte.
    #[test]
    fn chr_bank_selected_by_address_bits_1_0() {
        let mut mapper = make_mapper();

        // Address $8000 (bits[1:0]=0b00): CHR bank 0
        mapper.write_prg(0x8000, 0xFF);
        assert_eq!(
            mapper.read_chr(0x0000),
            0,
            "Address $8000 bits[1:0]=0 must select CHR bank 0"
        );

        // Address $8001 (bits[1:0]=0b01): CHR bank 1
        mapper.write_prg(0x8001, 0xFF);
        assert_eq!(
            mapper.read_chr(0x0000),
            1,
            "Address $8001 bits[1:0]=1 must select CHR bank 1"
        );

        // Address $8002 (bits[1:0]=0b10): CHR bank 2
        mapper.write_prg(0x8002, 0xFF);
        assert_eq!(
            mapper.read_chr(0x0000),
            2,
            "Address $8002 bits[1:0]=2 must select CHR bank 2"
        );
    }

    #[test]
    fn chr_data_byte_is_ignored_for_bank_selection() {
        let mut mapper = make_mapper();
        // Write to $8001 (CHR bank 1) using data byte 0x00 (which would pick bank 0 if data used)
        mapper.write_prg(0x8001, 0x00);
        assert_eq!(
            mapper.read_chr(0x0000),
            1,
            "Data byte must be ignored; CHR bank from address bits[1:0]"
        );
    }

    #[test]
    fn chr_bank_covers_full_8kb_window() {
        let mut mapper = make_mapper();
        // CHR bank 1: all bytes in that 8KB page have value 1
        mapper.write_prg(0x8001, 0xFF); // bits[1:0]=1 → CHR bank 1
        assert_eq!(mapper.read_chr(0x0000), 1, "CHR start of window");
        assert_eq!(mapper.read_chr(0x1FFF), 1, "CHR end of window");
    }

    #[test]
    fn prg_and_chr_bits_in_same_address_work_independently() {
        let mut mapper = make_mapper();
        // Address $8005 (bits[3:2]=0b01 → PRG 1; bits[1:0]=0b01 → CHR 1)
        mapper.write_prg(0x8005, 0xFF);
        assert_eq!(mapper.read_prg(0x8000), 1, "PRG bank should be 1");
        assert_eq!(mapper.read_chr(0x0000), 1, "CHR bank should be 1");

        // Address $800A (bits[3:2]=0b10 → PRG 2; bits[1:0]=0b10 → CHR 2)
        mapper.write_prg(0x800A, 0xFF);
        assert_eq!(mapper.read_prg(0x8000), 2, "PRG bank should be 2");
        assert_eq!(mapper.read_chr(0x0000), 2, "CHR bank should be 2");
    }

    // ── Mirroring ─────────────────────────────────────────────────────────────

    #[test]
    fn mirroring_fixed_from_header() {
        let mapper = make_mapper(); // created with Horizontal
        assert_eq!(
            mapper.get_mirroring(),
            NametableLayout::Horizontal,
            "Mirroring must be fixed from header for mapper 81"
        );
    }

    #[test]
    fn mirroring_not_changed_by_register_writes() {
        let mut mapper = make_mapper();
        mapper.write_prg(0x8000, 0xFF);
        assert_eq!(
            mapper.get_mirroring(),
            NametableLayout::Horizontal,
            "Mirroring must not change after register write"
        );
    }

    // ── No IRQ ────────────────────────────────────────────────────────────────

    #[test]
    fn irq_never_pending() {
        let mut mapper = make_mapper();
        mapper.write_prg(0x8000, 0xFF);
        assert!(!mapper.irq_pending(), "Mapper 81 must never assert IRQ");
    }

    // ── Reset ─────────────────────────────────────────────────────────────────

    #[test]
    fn reset_returns_to_power_on_state() {
        let mut mapper = make_mapper();
        mapper.write_prg(0x8005, 0xFF); // PRG bank 1, CHR bank 1
        mapper.reset();
        assert_eq!(mapper.read_prg(0x8000), 0, "PRG bank must be 0 after reset");
        assert_eq!(mapper.read_chr(0x0000), 0, "CHR bank must be 0 after reset");
        assert_eq!(
            mapper.read_prg(0xC000),
            (PRG_BANKS - 1) as u8,
            "$C000–$FFFF must be fixed to last bank after reset"
        );
    }

    // ── Snapshot / restore ────────────────────────────────────────────────────

    #[test]
    fn registers_snapshot_round_trips() {
        let mut mapper = make_mapper();
        // PRG bank 1, CHR bank 2
        mapper.write_prg(0x8006, 0xFF); // bits[3:2]=1 → PRG 1; bits[1:0]=2 → CHR 2

        let snap = mapper.registers_snapshot();
        let mut restored = make_mapper();
        restored.restore_registers(&snap);

        assert_eq!(
            restored.read_prg(0x8000),
            mapper.read_prg(0x8000),
            "Restored mapper must have same PRG mapping"
        );
        assert_eq!(
            restored.read_chr(0x0000),
            mapper.read_chr(0x0000),
            "Restored mapper must have same CHR mapping"
        );
        assert_eq!(
            restored.read_prg(0xC000),
            mapper.read_prg(0xC000),
            "Restored mapper must have same fixed PRG window"
        );
    }

    // ── CHR-RAM fallback ──────────────────────────────────────────────────────

    #[test]
    fn chr_ram_works_when_no_chr_rom() {
        // Given: mapper with no CHR-ROM
        let prg = banked_data(16 * 1024, PRG_BANKS);
        let mut mapper = Mapper81::new(MapperContext::new_for_test(
            81,
            prg,
            vec![],
            NametableLayout::Horizontal,
        ));
        // When: writing to CHR space
        mapper.write_chr(0x0100, 0xAB);
        // Then: read back should return the written value
        assert_eq!(
            mapper.read_chr(0x0100),
            0xAB,
            "CHR-RAM must be writable when no CHR-ROM is present"
        );
    }
}