rustynes_core/game_corrections.rs
1//! Per-game emulation corrections that depart from hardware ON PURPOSE.
2//!
3//! The core emulates the hardware, including the hardware's own glitches. A
4//! correction here exists only where the maintainer decided that a specific
5//! game's authentic glitch should not be drawn by default, and each one is a
6//! [`crate::HardwareOptions`] setting: on by default for the listed dumps
7//! only, switchable off by the host, and recorded in movies and in the
8//! netplay configuration digest, so a replay or a peer runs the same picture.
9//!
10//! # `coherent_midline_copy` (v3.6.2, `T-RADRACER-COHERENT-COPY`)
11//!
12//! *Rad Racer* writes `$2006` in the middle of several scanlines from
13//! sprite-0-timed loops whose timing varies by a few dots from frame to frame.
14//! When the delayed `t -> v` copy of such a write lands inside an 8-dot
15//! background fetch group, that group's tile is fetched from two addresses
16//! (the nametable "Hybrid Addresses" splice, or a pattern row from the new
17//! fine Y), and about one frame in eleven draws an 8-pixel wrong tile in the
18//! sand right of the road (line 139) and at the horizon (line 114). A 2012
19//! nesdev report describes a "very noticable glitch" on the right at that line
20//! on a real NES, so the glitch is the hardware's. The correction holds such a
21//! copy to the next fetch-group boundary (`rustynes_ppu::Ppu`'s
22//! `coherent_midline_copy`), which draws every tile from one address. Decided
23//! by the maintainer on 2026-11-06; see the ADR 0030 withdrawal note.
24//!
25//! The dumps are matched by the CRC32 of the ROM's PRG and CHR data (after
26//! the 16-byte header and any 512-byte trainer, and no further than the sizes
27//! the header declares), the key the vendored game database
28//! (`rustynes-gamedb`'s `rom_crc32`) uses for the same three entries. Hashing
29//! everything after the header instead would miss a dump that carries a
30//! trainer or trailing bytes, which the cartridge parser accepts (review round
31//! 8 on #640). Only the USA dump was available to measure; the other two
32//! CRCs are the database's, and their games are the same program.
33
34/// The headerless CRC32s of the dumps that get the coherent mid-line copy
35/// correction by default, with the game database's names.
36pub const COHERENT_MIDLINE_COPY_DUMPS: [(u32, &str); 3] = [
37 (0x8B9D_3E9C, "Rad Racer (USA)"),
38 (0x654F_4E90, "Rad Racer (Europe)"),
39 (0x0258_9598, "Highway Star (Japan)"),
40];
41
42/// Whether `rom` (a whole iNES / NES 2.0 image, header included) is one of
43/// [`COHERENT_MIDLINE_COPY_DUMPS`].
44#[must_use]
45pub fn coherent_midline_copy_by_default(rom: &[u8]) -> bool {
46 prg_chr(rom).is_some_and(|data| {
47 let crc = crc32(data);
48 COHERENT_MIDLINE_COPY_DUMPS.iter().any(|&(c, _)| c == crc)
49 })
50}
51
52/// The PRG and CHR data of an iNES image, the bytes the database's CRC
53/// covers: after the header and any trainer (header byte 6, bit 2), and
54/// `16 KiB x byte 4 + 8 KiB x byte 5` long. `None` for a file without the
55/// `NES\x1A` magic, with no PRG, or shorter than the header says. The
56/// bounds are `rustynes_gamedb::rom_crc32`'s, so a listed CRC means the
57/// same bytes in both places.
58fn prg_chr(rom: &[u8]) -> Option<&[u8]> {
59 if rom.len() < 16 || &rom[0..4] != b"NES\x1A" {
60 return None;
61 }
62 let prg = usize::from(rom[4]) * 16 * 1024;
63 let chr = usize::from(rom[5]) * 8 * 1024;
64 let start: usize = 16 + if rom[6] & 0x04 != 0 { 512 } else { 0 };
65 let end = start.checked_add(prg)?.checked_add(chr)?;
66 if prg == 0 || end > rom.len() {
67 return None;
68 }
69 Some(&rom[start..end])
70}
71
72/// CRC-32 (IEEE 802.3, reflected, `0xEDB88320`), as `rustynes-gamedb` and
73/// zlib compute it. Bitwise: it runs once per ROM load, so a table would buy
74/// nothing, and `rustynes-core` stays free of a dependency on the database.
75fn crc32(data: &[u8]) -> u32 {
76 let mut crc = !0u32;
77 for &b in data {
78 crc ^= u32::from(b);
79 for _ in 0..8 {
80 crc = (crc >> 1) ^ (0xEDB8_8320 & 0u32.wrapping_sub(crc & 1));
81 }
82 }
83 !crc
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89
90 #[test]
91 fn crc32_matches_the_standard_check_value() {
92 // The CRC-32 check value: crc32("123456789") = 0xCBF43926.
93 assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
94 }
95
96 /// The hashed bytes are the PRG and CHR data, wherever the file puts
97 /// them: a trainer before them and padding after them do not move the
98 /// key (review round 8 on #640), and a truncated or unmarked file has
99 /// none.
100 #[test]
101 fn the_key_covers_prg_and_chr_only() {
102 let mut plain = alloc::vec![0x4Eu8, 0x45, 0x53, 0x1A, 1, 1, 0, 0];
103 plain.resize(16, 0);
104 let body: alloc::vec::Vec<u8> = (0..24 * 1024u32)
105 .map(|i| (i * 7 + 3).to_le_bytes()[0])
106 .collect();
107 plain.extend_from_slice(&body);
108 assert_eq!(prg_chr(&plain), Some(&body[..]));
109
110 let mut trainer = plain[..16].to_vec();
111 trainer[6] |= 0x04;
112 trainer.extend(core::iter::repeat_n(0xAAu8, 512));
113 trainer.extend_from_slice(&body);
114 assert_eq!(prg_chr(&trainer), Some(&body[..]), "a trainer is skipped");
115
116 let mut padded = plain.clone();
117 padded.extend_from_slice(&[0xFF; 128]);
118 assert_eq!(
119 prg_chr(&padded),
120 Some(&body[..]),
121 "trailing bytes are ignored"
122 );
123
124 assert_eq!(
125 prg_chr(&plain[..plain.len() - 1]),
126 None,
127 "short of the header's sizes"
128 );
129 let mut unmarked = plain.clone();
130 unmarked[3] = 0;
131 assert_eq!(prg_chr(&unmarked), None, "no NES magic");
132 }
133
134 #[test]
135 fn only_a_listed_dump_gets_the_correction() {
136 assert!(!coherent_midline_copy_by_default(&[0u8; 16]));
137 let mut rom = alloc::vec![0x4Eu8, 0x45, 0x53, 0x1A];
138 rom.resize(16 + 1024, 0);
139 assert!(!coherent_midline_copy_by_default(&rom));
140 }
141}