Skip to main content

rustynes_core/
input_device.rs

1// SPDX-License-Identifier: GPL-3.0-or-later
2//
3// Provenance: the Power Pad's serial layout (`PowerPadState` and its `reload`, written in v1.1.0 citing "Mesen's implementation" beside the NESdev "Power Pad" page) is treated as derived from Mesen2 (GPL-3.0-or-later), by the maintainer's decision of 2026-10-21: whether Mesen2 source was read in June 2026 is not recorded, and the conservative reading was chosen. The layout itself is stated verbatim on `nesdev_wiki/Power_Pad.xhtml`. Only the Power Pad region is covered. See docs/originality-and-provenance.md (Section 1)
4// and NOTICE for the complete, audited derivation record.
5//! Optional non-standard input-device overlays for the `$4016`/`$4017`
6//! controller ports: the Arkanoid "Vaus" paddle and the NES Zapper light gun.
7//!
8//! These are **opt-in overlays**. The bus holds an `Option<InputDevice>` per
9//! port; when a port has no overlay device (the default) the standard
10//! controller / Four Score serial path runs completely unchanged, so the
11//! default + Four Score reads stay byte-identical and the determinism
12//! contract is preserved. A device is only consulted when explicitly attached
13//! via [`crate::Nes::set_paddle`] / [`crate::Nes::set_zapper`].
14//!
15//! ## Vaus paddle (Arkanoid controller)
16//!
17//! Per the `NESdev` "Arkanoid controller" page (NES 7-pin version), the device
18//! reports on the player-2 port (`$4017`):
19//!
20//! ```text
21//! 7  bit  0
22//! ---- ----
23//! xxxD Bxxx
24//!    | |
25//!    | +---- Fire button (1: pressed)        -> bit 3
26//!    +------ Serial control knob data        -> bit 4
27//!            (8/9-bit, inverted, MSb first)
28//! ```
29//!
30//! A write of `$4016` bit 0 = 1 -> 0 (the standard controller strobe) starts a
31//! "conversion": the 8-bit potentiometer value is latched MSb-first into the
32//! shift register. Each `$4017` read shifts out the next bit (on bit 4),
33//! **inverted** on the wire. After the register empties, reads repeat the
34//! serial-in bit (the 9th / `LSb`). The fire button (bit 3) is returned directly
35//! and is unaffected by the strobe.
36//!
37//! The in-tree `vaus-test` ROM (Damian Yerrick) documents the NES wiring as
38//! `$4017 D3: Button`, `$4017 D4: Position (8 bits, MSB first)` — matching the
39//! wiki layout above.
40//!
41//! ## Zapper light gun
42//!
43//! Per the `NESdev` "Zapper" page (NES variant), the device reports on its port:
44//!
45//! ```text
46//! 7  bit  0
47//! ---- ----
48//! xxxT Wxxx
49//!    | |
50//!    | +---- Light sensed (0: detected; 1: NOT detected)  -> bit 3
51//!    +------ Trigger (1: pulled/half-pulled; 0: released)  -> bit 4
52//! ```
53//!
54//! Note the inverted light polarity: bit 3 is **0** while light is detected and
55//! **1** otherwise. The light sensor stays active for roughly 19-26 scanlines
56//! after seeing a bright pixel (the photodiode capacitor drains exponentially);
57//! we use a simpler frame-granular model: a luminance threshold sampled at the
58//! aim point once per completed frame (sufficient because games re-sample every
59//! frame). The Zapper has no shift register — its byte is read in parallel and
60//! is independent of the strobe.
61
62/// The Arkanoid "Vaus" paddle overlay state.
63///
64/// Models the NES 7-pin variant on `$4017`: an 8-bit potentiometer value
65/// shifted out MSb-first (inverted on the wire) on bit 4, plus a fire button
66/// on bit 3.
67#[derive(Clone, Copy, Debug)]
68pub struct VausState {
69    /// The raw (pre-inversion) 8-bit potentiometer position. `$00` is the far
70    /// left, `$FF` the far right (per the wiki, turning right increases the
71    /// value).
72    pub(crate) position: u8,
73    /// Whether the fire button is currently held.
74    pub(crate) fire: bool,
75    /// 8-bit shift register, MSb-first readout. Reloaded from `position` on the
76    /// strobe falling edge (conversion latch). The serial-in bit (repeated
77    /// after the register empties) is the current `LSb`.
78    pub(crate) shift: u8,
79    /// Last strobe level written (bit 0 of `$4016`).
80    pub(crate) strobe: bool,
81}
82
83impl Default for VausState {
84    fn default() -> Self {
85        Self::new()
86    }
87}
88
89impl VausState {
90    /// New paddle centered, button released.
91    #[must_use]
92    pub const fn new() -> Self {
93        Self {
94            position: 0x80,
95            fire: false,
96            shift: 0x80,
97            strobe: false,
98        }
99    }
100
101    /// Update the live paddle position + fire state. Takes effect on the next
102    /// conversion (strobe falling edge), matching the standard controller's
103    /// latch-on-strobe semantics.
104    pub const fn set(&mut self, position: u8, fire: bool) {
105        self.position = position;
106        self.fire = fire;
107        if self.strobe {
108            self.shift = position;
109        }
110    }
111
112    /// Handle a `$4016` strobe write. On the rising edge the conversion latches
113    /// the current position into the shift register (we model the conversion as
114    /// instantaneous, which is the standard fixed-position emulation choice).
115    pub const fn write_strobe(&mut self, value: u8) {
116        let new_strobe = value & 1 != 0;
117        if new_strobe {
118            self.shift = self.position;
119        }
120        self.strobe = new_strobe;
121    }
122
123    /// Read the device byte for a `$4017` access, advancing the shift register.
124    /// Returns the full 8-bit value already positioned on bits 3 (fire) and 4
125    /// (knob data); the caller ORs in the open-bus upper bits.
126    ///
127    /// Bit 4 carries the **inverted** `MSb` of the shift register (knob data is
128    /// inverted on the wire per the wiki). Bit 3 carries the fire button (1 =
129    /// pressed). All other bits are 0.
130    pub const fn read(&mut self) -> u8 {
131        // Knob data bit: MSb of the shift register, inverted on the wire.
132        let data_bit = (self.shift >> 7) & 1;
133        let wire_data = data_bit ^ 1;
134        // Shift left, feeding the LSb back into the serial-in position so that
135        // post-empty reads repeat the 9th (serial-in) bit per the wiki.
136        let serial_in = self.shift & 1;
137        self.shift = (self.shift << 1) | serial_in;
138        let fire = self.fire as u8;
139        (wire_data << 4) | (fire << 3)
140    }
141
142    /// Side-effect-free sample of the next device byte (debugger peek).
143    #[must_use]
144    pub const fn peek(&self) -> u8 {
145        let data_bit = (self.shift >> 7) & 1;
146        let wire_data = data_bit ^ 1;
147        let fire = self.fire as u8;
148        (wire_data << 4) | (fire << 3)
149    }
150
151    /// Reconstruct from save-state parts.
152    #[must_use]
153    pub const fn from_parts(position: u8, fire: bool, shift: u8, strobe: bool) -> Self {
154        Self {
155            position,
156            fire,
157            shift,
158            strobe,
159        }
160    }
161
162    /// Raw potentiometer position (save-state).
163    #[must_use]
164    pub const fn position_raw(&self) -> u8 {
165        self.position
166    }
167    /// Raw fire state (save-state).
168    #[must_use]
169    pub const fn fire_raw(&self) -> bool {
170        self.fire
171    }
172    /// Raw shift register (save-state).
173    #[must_use]
174    pub const fn shift_raw(&self) -> u8 {
175        self.shift
176    }
177    /// Raw strobe state (save-state).
178    #[must_use]
179    pub const fn strobe_raw(&self) -> bool {
180        self.strobe
181    }
182}
183
184/// The NES Zapper light-gun overlay state.
185///
186/// Models the NES variant: bit 3 = light sensed (0 detected / 1 not), bit 4 =
187/// trigger (1 pulled). Light detection samples the PPU framebuffer luminance at
188/// the aim point once per frame (a frame-granular model — see `light_seen`).
189#[derive(Clone, Copy, Debug, Default)]
190pub struct ZapperState {
191    /// Aim point X (0..256), screen pixel. Out-of-range = aimed off-screen.
192    pub(crate) x: u16,
193    /// Aim point Y (0..240), screen scanline. Out-of-range = aimed off-screen.
194    pub(crate) y: u16,
195    /// Whether the trigger is currently pulled.
196    pub(crate) trigger: bool,
197    /// Whether the photodiode currently sees light. Set by [`Self::sample_light`]
198    /// each frame from the framebuffer luminance at the aim point; while `true`,
199    /// bit 3 reads 0 (light detected), else bit 3 reads 1 (no light). This is a
200    /// frame-granular model: games re-sample every frame, so per-frame
201    /// resolution is sufficient (the wiki's ~19-26-scanline photodiode hold
202    /// matters only for sub-frame timing tricks, which the supported games do
203    /// not require).
204    pub(crate) light_seen: bool,
205}
206
207/// Luminance threshold (0..255, Rec.601-ish) above which a sampled framebuffer
208/// pixel counts as "bright enough" to trigger the photodiode.
209pub(crate) const ZAPPER_LUMA_THRESHOLD: u16 = 0x80;
210
211/// Photodiode **aperture radius** in pixels (v2.2.0 "Capstone" light-timing
212/// hardening). The real Zapper's lens focuses light from a small solid angle
213/// onto the photodiode, so the sensor integrates a *region* of the CRT phosphor,
214/// not a single dot. Sampling a `(2r+1) x (2r+1)` window around the aim point
215/// (rather than one pixel) hardens detection against sub-pixel aim error and
216/// single-pixel dropouts in the PPU output — matching how the hardware responds
217/// to the bright target the game flashes. Radius 1 = a 3x3 aperture.
218pub(crate) const ZAPPER_APERTURE_RADIUS: i32 = 1;
219
220/// Minimum number of bright pixels within the aperture required to assert
221/// "light detected". Requiring more than one rejects a lone stray-bright pixel
222/// (PPU edge artefact) as a false positive while still firing on the target
223/// flash, which lights the whole aperture. Calibrated for the 3x3 aperture.
224pub(crate) const ZAPPER_APERTURE_MIN_BRIGHT: u32 = 2;
225
226/// Photodiode hold, in scanlines (A3, v2.2.3 — used only by the opt-in
227/// temporal model).
228///
229/// The Zapper's photodiode charges when the CRT beam paints a bright pixel in
230/// its field of view, then drains exponentially: `NESdev` "Zapper" puts the
231/// resulting light-sense window at roughly **19-26 scanlines**. 22 is the
232/// midpoint, and the span is wide enough that no supported title distinguishes
233/// values inside it.
234pub(crate) const ZAPPER_LIGHT_HOLD_SCANLINES: u16 = 22;
235
236impl ZapperState {
237    /// New zapper aimed off-screen, trigger released, no light.
238    #[must_use]
239    pub const fn new() -> Self {
240        Self {
241            x: u16::MAX,
242            y: u16::MAX,
243            trigger: false,
244            light_seen: false,
245        }
246    }
247
248    /// Update the live aim point + trigger state.
249    pub const fn set(&mut self, x: u16, y: u16, trigger: bool) {
250        self.x = x;
251        self.y = y;
252        self.trigger = trigger;
253    }
254
255    /// Sample the framebuffer luminance over the photodiode **aperture** around
256    /// the aim point, setting `light_seen` when enough of the aperture is bright.
257    /// `framebuffer` is the PPU's RGBA8 256x240 buffer. Called once per frame by
258    /// the bus after the frame completes.
259    ///
260    /// v2.2.0 "Capstone" light-timing hardening: rather than sampling a single
261    /// pixel, the sensor integrates a `(2r+1) x (2r+1)` aperture
262    /// (`ZAPPER_APERTURE_RADIUS`) and asserts light only when at least
263    /// `ZAPPER_APERTURE_MIN_BRIGHT` pixels cross `ZAPPER_LUMA_THRESHOLD`. This
264    /// models the lens/photodiode field-of-view against the PPU's per-dot output:
265    /// the bright target the game flashes lights the whole aperture (robust
266    /// detection), while a black "blanked" background frame — or a lone stray
267    /// bright pixel — yields no light (no false positive). The computation is a
268    /// pure, deterministic function of the framebuffer + aim point, so it needs
269    /// no additional save-state and preserves the determinism contract.
270    ///
271    /// The temporal light-sense window (the ~19-26-scanline photodiode hold) is
272    /// finer than the per-frame sample resolution used here; the supported
273    /// light-gun titles re-poll every frame, so frame-granular sampling of the
274    /// presented framebuffer is sufficient. A full per-dot temporal integration
275    /// against the beam position is a documented future refinement — see
276    /// `docs/frontend.md`.
277    pub fn sample_light(&mut self, framebuffer: &[u8]) {
278        self.light_seen = Self::aperture_is_bright(framebuffer, self.x, self.y);
279    }
280
281    /// Shared aperture test: is the `(2r+1)x(2r+1)` photodiode field of view at
282    /// `(x, y)` bright enough to charge the sensor?
283    ///
284    /// A3 (v2.2.3) factored this out of [`Self::sample_light`] so the
285    /// frame-granular and beam-relative models cannot drift apart — the
286    /// temporal model differs from the frame model ONLY in *when* it samples,
287    /// never in what counts as light.
288    fn aperture_is_bright(framebuffer: &[u8], x: u16, y: u16) -> bool {
289        Self::aperture_is_bright_painted(framebuffer, x, y, None)
290    }
291
292    /// [`Self::aperture_is_bright`], restricted to rows the CRT beam has
293    /// **finished painting this frame**.
294    ///
295    /// `painted_before` is the scanline the beam is currently on: rows at or
296    /// after it are excluded, because the current row is only part-way drawn and
297    /// later rows still hold the PREVIOUS frame's pixels. `None` means the whole
298    /// framebuffer is current, which is true only for the end-of-frame sampler.
299    ///
300    /// # Why this is load-bearing
301    ///
302    /// A photodiode can only respond to light the phosphor has already emitted.
303    /// Without this clip the beam-relative model samples stale rows and reports
304    /// light on a screen that is entirely black — measured directly on *Duck
305    /// Hunt*'s light-test frame, where at scanline 96 the beam was 5 dots into
306    /// row 96 and the sampler read the previous frame's bright sky (`aim_luma
307    /// 152` on a frame whose mean luma is 0), then did it again at scanline 97
308    /// via the still-unpainted row 97 of the 3x3 aperture.
309    ///
310    /// That matters because *Duck Hunt* requires the gun to see **nothing** for
311    /// one frame before it will accept a shot, so a false positive here discards
312    /// every shot: the gun fires and nothing can ever be hit (v2.3.6).
313    fn aperture_is_bright_painted(
314        framebuffer: &[u8],
315        x: u16,
316        y: u16,
317        painted_before: Option<u16>,
318    ) -> bool {
319        const W: i32 = 256;
320        const H: i32 = 240;
321        let (ax, ay) = (i32::from(x), i32::from(y));
322        if ax >= W || ay >= H {
323            return false; // aimed off-screen: never sees light
324        }
325        // Rows `>= painted_before` are not yet emitted this frame. `None` (the
326        // end-of-frame sampler) admits the whole screen.
327        let row_limit = painted_before.map_or(H, i32::from);
328        let mut bright = 0u32;
329        let r = ZAPPER_APERTURE_RADIUS;
330        for dy in -r..=r {
331            for dx in -r..=r {
332                let (px, py) = (ax + dx, ay + dy);
333                if !(0..W).contains(&px) || !(0..H).contains(&py) {
334                    continue; // aperture clipped by the screen edge
335                }
336                if py >= row_limit {
337                    continue; // the beam has not finished this row this frame
338                }
339                // px/py are now bounded to the screen, so the linear index is
340                // non-negative and fits a usize.
341                let Ok(idx) = usize::try_from((py * W + px) * 4) else {
342                    continue;
343                };
344                if idx + 2 >= framebuffer.len() {
345                    continue; // guard against a partial framebuffer
346                }
347                let cr = u16::from(framebuffer[idx]);
348                let cg = u16::from(framebuffer[idx + 1]);
349                let cb = u16::from(framebuffer[idx + 2]);
350                // Rec.601 luma approximation (integer): (77*R + 150*G + 29*B) >> 8.
351                let luma = (77 * cr + 150 * cg + 29 * cb) >> 8;
352                if luma >= ZAPPER_LUMA_THRESHOLD {
353                    bright += 1;
354                }
355            }
356        }
357        bright >= ZAPPER_APERTURE_MIN_BRIGHT
358    }
359
360    /// A3 (v2.2.3): does the photodiode see light **right now**, given where
361    /// the CRT beam currently is?
362    ///
363    /// The frame-granular [`Self::sample_light`] answers "was the aim point
364    /// bright in the completed frame", which is constant for the whole frame —
365    /// so a game polling immediately after its flash and one polling 100
366    /// scanlines later get the same answer. Real hardware does not work that
367    /// way: the photodiode charges as the beam *passes* the aim point and
368    /// drains over ~19-26 scanlines afterwards.
369    ///
370    /// This models that directly, as a pure function of
371    /// `(framebuffer, aim, current scanline)`:
372    ///
373    /// * before the beam reaches the aim row (`scanline < y`) — dark, because
374    ///   this frame has not painted it yet;
375    /// * from the aim row until the hold expires — bright iff the aperture is
376    ///   bright **over the rows the beam has already finished**, per
377    ///   `aperture_is_bright_painted` (a plain code span, not an intra-doc link:
378    ///   that item is private and `rustdoc::private_intra_doc_links` is denied);
379    /// * after the hold — dark again, the capacitor having drained.
380    ///
381    /// Holding **no extra state** is deliberate: light is derived on demand at
382    /// read time rather than latched by a per-scanline callback, so it adds no
383    /// field to serialize, cannot desync a save state or a netplay rollback,
384    /// and keeps the determinism contract (same framebuffer + aim + scanline
385    /// always yields the same answer).
386    ///
387    /// # A wrong claim this used to make (v2.3.6)
388    ///
389    /// This doc previously ended: *"One consequence is physically right rather
390    /// than a compromise: the aperture rows below the beam still hold the
391    /// previous frame's pixels, which is exactly what the sensor sees, since the
392    /// beam has not repainted them yet."*
393    ///
394    /// **That is backwards.** A photodiode responds to light the phosphor has
395    /// *emitted*; a row the beam has not reached this frame is emitting nothing,
396    /// and its stale framebuffer contents are an artefact of how the emulator
397    /// stores pixels, not something a sensor could see. Reading those rows made
398    /// the model report light on an all-black screen — measured at scanline 96,
399    /// where the beam was 5 dots into row 96 and the sampler returned the
400    /// previous frame's sky at luma 152 on a frame whose mean luma was 0.
401    ///
402    /// Because *Duck Hunt* requires the gun to see nothing for one frame before
403    /// it will accept a shot, that false positive discarded every shot: the gun
404    /// fired and no duck could ever be hit. The rows are now clipped, and the
405    /// paragraph is kept rather than deleted because the plausible-sounding
406    /// wrong reasoning is what made the defect look intentional.
407    #[must_use]
408    pub fn light_at_scanline(&self, framebuffer: &[u8], scanline: u16) -> bool {
409        let y = self.y;
410        if scanline < y {
411            return false; // beam has not painted the aim row yet this frame
412        }
413        if scanline - y >= ZAPPER_LIGHT_HOLD_SCANLINES {
414            return false; // photodiode has drained
415        }
416        // Only rows the beam has FINISHED this frame can have emitted light —
417        // see `aperture_is_bright_painted` for what goes wrong without this.
418        Self::aperture_is_bright_painted(framebuffer, self.x, y, Some(scanline))
419    }
420
421    /// The device byte as [`Self::read`] would return it, but using the
422    /// beam-relative light state from [`Self::light_at_scanline`].
423    #[must_use]
424    pub fn read_at_scanline(&self, framebuffer: &[u8], scanline: u16) -> u8 {
425        let light_not_detected = u8::from(!self.light_at_scanline(framebuffer, scanline));
426        let trigger = u8::from(self.trigger);
427        (trigger << 4) | (light_not_detected << 3)
428    }
429
430    /// The device byte for a read taken **before the visible frame begins** —
431    /// the answer when the PPU's scanline is *negative*, which no light is
432    /// detectable for (the beam has painted nothing this frame yet).
433    ///
434    /// This is a total-conversion fallback, not a fix for a live defect. In this
435    /// engine `Ppu::scanline()` is non-negative on every region — the pre-render
436    /// line is 261 (NTSC) / 311 (PAL), not -1 — so the visible/vblank path
437    /// through [`Self::read_at_scanline`] already yields no-light for pre-render
438    /// (`prerender - y >= ZAPPER_LIGHT_HOLD_SCANLINES` for every on-screen aim),
439    /// and this branch is not reached. It exists so that the caller's
440    /// `u16::try_from(scanline)` has a *correct* `Err` answer — "no light yet" —
441    /// rather than the row-0 fold a bare `unwrap_or(0)` would produce, should a
442    /// future scanline convention (a -1 pre-render, as some emulators use) ever
443    /// hand this a negative value.
444    #[must_use]
445    pub const fn read_before_visible(&self) -> u8 {
446        let trigger = self.trigger as u8;
447        (trigger << 4) | (1 << 3) // light NOT detected (bit 3 is inverted)
448    }
449
450    /// The device byte for a `$4016`/`$4017` access. Bit 3 = light (0 detected /
451    /// 1 not), bit 4 = trigger (1 pulled). Independent of the strobe (the
452    /// Zapper has no shift register). The caller ORs in the open-bus upper bits.
453    #[must_use]
454    pub const fn read(&self) -> u8 {
455        let light_not_detected = (!self.light_seen) as u8;
456        let trigger = self.trigger as u8;
457        (trigger << 4) | (light_not_detected << 3)
458    }
459
460    /// Reconstruct from save-state parts.
461    #[must_use]
462    pub const fn from_parts(x: u16, y: u16, trigger: bool, light_seen: bool) -> Self {
463        Self {
464            x,
465            y,
466            trigger,
467            light_seen,
468        }
469    }
470
471    /// Raw aim X (save-state).
472    #[must_use]
473    pub const fn x_raw(&self) -> u16 {
474        self.x
475    }
476    /// Raw aim Y (save-state).
477    #[must_use]
478    pub const fn y_raw(&self) -> u16 {
479        self.y
480    }
481    /// Raw trigger state (save-state).
482    #[must_use]
483    pub const fn trigger_raw(&self) -> bool {
484        self.trigger
485    }
486    /// Raw light-seen state (save-state).
487    #[must_use]
488    pub const fn light_seen_raw(&self) -> bool {
489        self.light_seen
490    }
491}
492
493/// The NES Power Pad (a.k.a. Family Fun Fitness / Family Trainer mat) overlay.
494///
495/// A 12-button mat read on the player-2 port (`$4017`) through two 8-bit
496/// parallel-in/serial-out shift registers (a pair of 4021s), strobed by the
497/// standard `$4016` controller strobe. The 12 buttons are indexed 0..=11
498/// (matching the mat's "1".."12" labels); the frontend decides which physical
499/// keys map to which mat button (and any Side-A/Side-B row inversion).
500///
501/// Per the `NESdev` "Power Pad" page (and Mesen's implementation), the button
502/// bits load into two registers and shift out LSb-first on bits 3 and 4 of each
503/// `$4017` read:
504///
505/// - register L (bit 3 of the read): buttons 2, 1, 5, 9, 6, 10, 11, 7;
506/// - register H (bit 4 of the read): buttons 4, 3, 12, 8, then four `1` bits.
507///
508/// (Button numbers are 1-based here, matching the mat labels; the code uses
509/// 0-based indices.) Each read shifts both registers right and feeds `1`s in
510/// from the top, so post-shift reads settle to "no button".
511///
512/// Provenance: derived from Mesen2 (GPL-3.0-or-later); see this file's
513/// header and `docs/originality-and-provenance.md` Section 1.
514#[derive(Clone, Copy, Debug, Default)]
515pub struct PowerPadState {
516    /// Live pressed-button mask: bit `i` (0..=11) set = mat button `i+1` held.
517    pub(crate) buttons: u16,
518    /// Low shift register (read out on bit 3).
519    pub(crate) shift_l: u8,
520    /// High shift register (read out on bit 4).
521    pub(crate) shift_h: u8,
522    /// Last strobe level written (bit 0 of `$4016`).
523    pub(crate) strobe: bool,
524}
525
526impl PowerPadState {
527    /// New mat with no buttons pressed.
528    #[must_use]
529    pub const fn new() -> Self {
530        Self {
531            buttons: 0,
532            shift_l: 0,
533            shift_h: 0,
534            strobe: false,
535        }
536    }
537
538    /// Reload both shift registers from the live button mask (the parallel
539    /// latch). The bit order matches the `NESdev` / Mesen serial layout.
540    ///
541    /// Provenance: the derived region (Mesen2); see this file's header.
542    const fn reload(&mut self) {
543        // bit(i) = (buttons >> i) & 1, as u8. Inlined (no closures in const fn).
544        let p = self.buttons;
545        // L: buttons 2,1,5,9,6,10,11,7 (0-based 1,0,4,8,5,9,10,6).
546        self.shift_l = (((p >> 1) & 1) as u8)
547            | (((p & 1) as u8) << 1)
548            | ((((p >> 4) & 1) as u8) << 2)
549            | ((((p >> 8) & 1) as u8) << 3)
550            | ((((p >> 5) & 1) as u8) << 4)
551            | ((((p >> 9) & 1) as u8) << 5)
552            | ((((p >> 10) & 1) as u8) << 6)
553            | ((((p >> 6) & 1) as u8) << 7);
554        // H: buttons 4,3,12,8 (0-based 3,2,11,7), then four 1 bits (read as H=1).
555        self.shift_h = (((p >> 3) & 1) as u8)
556            | ((((p >> 2) & 1) as u8) << 1)
557            | ((((p >> 11) & 1) as u8) << 2)
558            | ((((p >> 7) & 1) as u8) << 3)
559            | 0xF0;
560    }
561
562    /// Update the live pressed-button mask (bit `i` = mat button `i+1`). While
563    /// the strobe is held high the registers track the live mask (parallel
564    /// load), matching the standard controller's latch-while-strobed semantics.
565    pub const fn set(&mut self, buttons: u16) {
566        self.buttons = buttons & 0x0FFF;
567        if self.strobe {
568            self.reload();
569        }
570    }
571
572    /// Handle a `$4016` strobe write. While bit 0 is high the registers are
573    /// (re)loaded from the live buttons; the falling edge leaves the latched
574    /// snapshot to shift out.
575    pub const fn write_strobe(&mut self, value: u8) {
576        let new_strobe = value & 1 != 0;
577        if new_strobe {
578            self.reload();
579        }
580        self.strobe = new_strobe;
581    }
582
583    /// Read the device byte for a `$4017` access, shifting both registers.
584    /// Bit 4 = the current serial-out (`LSb`) of register H, bit 3 = register L;
585    /// each read then shifts both right (feeding `1`s in from the top). The
586    /// caller ORs in the open-bus upper bits. While the strobe is high the
587    /// registers are continuously reloaded (reads return the first button).
588    pub const fn read(&mut self) -> u8 {
589        if self.strobe {
590            self.reload();
591        }
592        let out = ((self.shift_h & 1) << 4) | ((self.shift_l & 1) << 3);
593        self.shift_l = (self.shift_l >> 1) | 0x80;
594        self.shift_h = (self.shift_h >> 1) | 0x80;
595        out
596    }
597
598    /// Side-effect-free sample of the next device byte (debugger peek).
599    #[must_use]
600    pub const fn peek(&self) -> u8 {
601        ((self.shift_h & 1) << 4) | ((self.shift_l & 1) << 3)
602    }
603
604    /// Reconstruct from save-state parts. `buttons` is masked to the 12 mat
605    /// bits, matching [`Self::set`], so a malformed save-state cannot inject
606    /// out-of-range bits.
607    #[must_use]
608    pub const fn from_parts(buttons: u16, shift_l: u8, shift_h: u8, strobe: bool) -> Self {
609        Self {
610            buttons: buttons & 0x0FFF,
611            shift_l,
612            shift_h,
613            strobe,
614        }
615    }
616
617    /// Raw live button mask (save-state).
618    #[must_use]
619    pub const fn buttons_raw(&self) -> u16 {
620        self.buttons
621    }
622    /// Raw low shift register (save-state).
623    #[must_use]
624    pub const fn shift_l_raw(&self) -> u8 {
625        self.shift_l
626    }
627    /// Raw high shift register (save-state).
628    #[must_use]
629    pub const fn shift_h_raw(&self) -> u8 {
630        self.shift_h
631    }
632    /// Raw strobe state (save-state).
633    #[must_use]
634    pub const fn strobe_raw(&self) -> bool {
635        self.strobe
636    }
637}
638
639/// The (Hyperkin / Nintendo) mouse overlay state — the SNES-style serial mouse
640/// as wired to an NES `$4016`/`$4017` port (D0 serial-out).
641///
642/// Per the `NESdev` "Mouse" page (the SNES mouse, the canonical serial mouse
643/// reused on the NES), a strobe latches a fixed-format 32-bit report that is
644/// then shifted out **MSb-first on D0** (one bit per port read):
645///
646/// ```text
647/// bits 31..28 : signature 0b0001 (device id nibble)
648/// bits 27..26 : 00
649/// bits 25..24 : sensitivity (00 low / 01 medium / 10 high; cycled by pressing
650///               both buttons on real hardware — we expose it as a field)
651/// bit  23     : left button  (1 = pressed)
652/// bit  22     : right button (1 = pressed)
653/// bits 21..16 : 0
654/// bits 15..8  : Y movement — bit 15 = direction sign (1 = up/-), bits 14..8 =
655///               magnitude (0..127); 0 when not moving
656/// bits  7..0  : X movement — bit  7 = direction sign (1 = left/-), bits  6..0 =
657///               magnitude (0..127); 0 when not moving
658/// ```
659///
660/// After the 32 real bits are shifted out, further reads return `1` (the open
661/// serial line idles high), matching the standard controller's post-sequence
662/// behavior. Like the standard controller, while the strobe is held high the
663/// report is continuously re-latched, so reads return the first (signature) bit.
664#[derive(Clone, Copy, Debug, Default)]
665pub struct SnesMouseState {
666    /// Live delta-X this frame (signed; clamped into +/-127 on latch).
667    pub(crate) dx: i16,
668    /// Live delta-Y this frame (signed; clamped into +/-127 on latch).
669    pub(crate) dy: i16,
670    /// Left button held.
671    pub(crate) left: bool,
672    /// Right button held.
673    pub(crate) right: bool,
674    /// Sensitivity (0 low / 1 medium / 2 high). Reported in the latched word.
675    pub(crate) sensitivity: u8,
676    /// 32-bit shift register, MSb-first readout. Reloaded from the live state on
677    /// the strobe (the parallel latch).
678    pub(crate) shift: u32,
679    /// Count of real bits shifted out (0..=32); beyond 32, reads idle high (`1`).
680    pub(crate) read_count: u8,
681    /// Last strobe level written (bit 0 of `$4016`).
682    pub(crate) strobe: bool,
683}
684
685impl SnesMouseState {
686    /// New mouse at rest (no movement, buttons up, low sensitivity).
687    #[must_use]
688    pub const fn new() -> Self {
689        Self {
690            dx: 0,
691            dy: 0,
692            left: false,
693            right: false,
694            sensitivity: 0,
695            shift: 0,
696            read_count: 0,
697            strobe: false,
698        }
699    }
700
701    /// Encode one axis into the 8-bit serial field: bit 7 = direction sign
702    /// (1 = negative), bits 6..0 = magnitude clamped to 0..=127.
703    const fn enc_axis(v: i16) -> u32 {
704        // `v.unsigned_abs()` avoids the `-i16::MIN` overflow panic that `-v`
705        // would hit for `v == i16::MIN` (32768 is unrepresentable as `i16`).
706        let mag = v.unsigned_abs() as u32;
707        let mag = if mag > 127 { 127 } else { mag };
708        let sign = if v < 0 { 1u32 } else { 0 };
709        (sign << 7) | mag
710    }
711
712    /// Encode the current live state into the 32-bit report word (MSb-first
713    /// serial order; bit 31 is shifted out first).
714    const fn encode(&self) -> u32 {
715        let dx = Self::enc_axis(self.dx);
716        let dy = Self::enc_axis(self.dy);
717        let sig = 0b0001u32 << 28;
718        let sens = ((self.sensitivity & 0b11) as u32) << 24;
719        let left = (self.left as u32) << 23;
720        let right = (self.right as u32) << 22;
721        sig | sens | left | right | (dy << 8) | dx
722    }
723
724    /// Update the live movement + button + sensitivity state. Takes effect on
725    /// the next latch (strobe), matching the standard controller semantics.
726    pub const fn set(&mut self, dx: i16, dy: i16, left: bool, right: bool, sensitivity: u8) {
727        self.dx = dx;
728        self.dy = dy;
729        self.left = left;
730        self.right = right;
731        self.sensitivity = sensitivity & 0b11;
732        if self.strobe {
733            self.shift = self.encode();
734            self.read_count = 0;
735        }
736    }
737
738    /// Handle a `$4016` strobe write. On a high level the 32-bit report is
739    /// (re)latched from the live state; the read counter resets.
740    pub const fn write_strobe(&mut self, value: u8) {
741        let new_strobe = value & 1 != 0;
742        if new_strobe {
743            self.shift = self.encode();
744            self.read_count = 0;
745        }
746        self.strobe = new_strobe;
747    }
748
749    /// Read the device byte for a port access, shifting out one MSb-first bit on
750    /// D0. After 32 bits the line idles high (`1` on D0). While the strobe is
751    /// held high the report is continuously re-latched (reads return bit 31).
752    /// The caller ORs in the open-bus upper bits.
753    pub const fn read(&mut self) -> u8 {
754        if self.strobe {
755            self.shift = self.encode();
756            self.read_count = 0;
757        }
758        if self.read_count >= 32 {
759            return 1; // serial line idles high after the report
760        }
761        let bit = (self.shift >> 31) & 1;
762        self.shift <<= 1;
763        self.read_count += 1;
764        bit as u8
765    }
766
767    /// Side-effect-free sample of the next D0 bit (debugger peek).
768    #[must_use]
769    pub const fn peek(&self) -> u8 {
770        if self.read_count >= 32 {
771            return 1;
772        }
773        ((self.shift >> 31) & 1) as u8
774    }
775
776    /// Reconstruct from save-state parts.
777    #[must_use]
778    #[allow(clippy::too_many_arguments)] // one arg per persisted field
779    pub const fn from_parts(
780        dx: i16,
781        dy: i16,
782        left: bool,
783        right: bool,
784        sensitivity: u8,
785        shift: u32,
786        read_count: u8,
787        strobe: bool,
788    ) -> Self {
789        Self {
790            dx,
791            dy,
792            left,
793            right,
794            sensitivity: sensitivity & 0b11,
795            shift,
796            read_count,
797            strobe,
798        }
799    }
800
801    /// Raw delta-X (save-state).
802    #[must_use]
803    pub const fn dx_raw(&self) -> i16 {
804        self.dx
805    }
806    /// Raw delta-Y (save-state).
807    #[must_use]
808    pub const fn dy_raw(&self) -> i16 {
809        self.dy
810    }
811    /// Raw left button (save-state).
812    #[must_use]
813    pub const fn left_raw(&self) -> bool {
814        self.left
815    }
816    /// Raw right button (save-state).
817    #[must_use]
818    pub const fn right_raw(&self) -> bool {
819        self.right
820    }
821    /// Raw sensitivity (save-state).
822    #[must_use]
823    pub const fn sensitivity_raw(&self) -> u8 {
824        self.sensitivity
825    }
826    /// Raw shift register (save-state).
827    #[must_use]
828    pub const fn shift_raw(&self) -> u32 {
829        self.shift
830    }
831    /// Raw read counter (save-state).
832    #[must_use]
833    pub const fn read_count_raw(&self) -> u8 {
834        self.read_count
835    }
836    /// Raw strobe state (save-state).
837    #[must_use]
838    pub const fn strobe_raw(&self) -> bool {
839        self.strobe
840    }
841}
842
843/// Number of physical keys on the Famicom Family BASIC keyboard matrix
844/// (`9 rows x 8 columns / 2` halves; 72 keys, with a handful of unused matrix
845/// positions reported as `1` / not-pressed).
846pub const FAMILY_KEYBOARD_KEYS: usize = 72;
847
848/// Number of selectable rows in the Family BASIC keyboard matrix.
849const FAMILY_KEYBOARD_ROWS: usize = 9;
850
851/// The Famicom **Family BASIC keyboard** overlay state.
852///
853/// Per the `NESdev` "Family BASIC Keyboard" page, the keyboard is a `9 x 8`
854/// switch matrix (with the data-recorder lines unused here) read through the
855/// expansion port but software-visible on `$4017`. The protocol:
856///
857/// - **`$4016` write** — bit 0 (the "column" select; 0 selects the low 4 keys
858///   of the current row, 1 selects the high 4) and bit 1 (a clock; a 0->1
859///   transition advances to the next row). Bit 2 enables the keyboard matrix;
860///   when bit 2 is 0 the matrix is disabled and `$4017` reads `1`s. Writing
861///   bit 1 = 0 while bit 2 = 1 **resets** the row counter to 0.
862/// - **`$4017` read** — bits 4..1 carry the four key switches of the currently
863///   selected (row, column-half), **active-low** (0 = pressed). There are 9
864///   rows x 2 halves = 18 selectable groups of 4 keys = 72 key positions.
865///
866/// We model the live pressed state as a 72-bit key bitmap (`[u8; 9]`, one byte
867/// per row: low nibble = column-half 0, high nibble = column-half 1) and the
868/// row counter + column select per the write protocol. Determinism holds: it is
869/// a pure function of the writes + the live key bitmap.
870#[derive(Clone, Copy, Debug)]
871pub struct FamilyKeyboardState {
872    /// Per-row key bitmap. `keys[row]` bits 0..=3 = column-half 0 keys, bits
873    /// 4..=7 = column-half 1 keys. A set bit = that key is held.
874    pub(crate) keys: [u8; FAMILY_KEYBOARD_ROWS],
875    /// Current matrix row (0..=8); wraps/saturates at the last row.
876    pub(crate) row: u8,
877    /// Column-half select (bit 0 of the last `$4016` write): 0 = low nibble,
878    /// 1 = high nibble.
879    pub(crate) column: bool,
880    /// Whether the matrix is enabled (bit 2 of the last `$4016` write). When
881    /// disabled, `$4017` reads return all-`1` (no keys).
882    pub(crate) enabled: bool,
883    /// Last clock level (bit 1 of `$4016`); a 0->1 edge advances the row.
884    pub(crate) clock: bool,
885}
886
887impl Default for FamilyKeyboardState {
888    fn default() -> Self {
889        Self::new()
890    }
891}
892
893impl FamilyKeyboardState {
894    /// New keyboard with no keys held, matrix reset + disabled.
895    #[must_use]
896    pub const fn new() -> Self {
897        Self {
898            keys: [0; FAMILY_KEYBOARD_ROWS],
899            row: 0,
900            column: false,
901            enabled: false,
902            clock: false,
903        }
904    }
905
906    /// Set the full pressed-key bitmap (one byte per matrix row; low nibble =
907    /// column-half 0, high nibble = column-half 1). The frontend builds this
908    /// from host keys via its key map.
909    pub const fn set_keys(&mut self, keys: [u8; FAMILY_KEYBOARD_ROWS]) {
910        self.keys = keys;
911    }
912
913    /// Set one key by linear index (0..72) — `index = row * 8 + bit`, matching
914    /// the matrix layout (`bit` 0..=3 = column-half 0, 4..=7 = column-half 1).
915    /// Out-of-range indices are ignored.
916    pub const fn set_key(&mut self, index: usize, pressed: bool) {
917        if index >= FAMILY_KEYBOARD_KEYS {
918            return;
919        }
920        let row = index / 8;
921        #[allow(clippy::cast_possible_truncation)] // index % 8 is always 0..=7
922        let bit = (index % 8) as u8;
923        if pressed {
924            self.keys[row] |= 1 << bit;
925        } else {
926            self.keys[row] &= !(1 << bit);
927        }
928    }
929
930    /// Handle a `$4016` write: latch column select (bit 0), advance the row on a
931    /// clock (bit 1) rising edge, set the matrix-enable (bit 2). A clock low
932    /// while enabled resets the row counter to 0.
933    pub const fn write_strobe(&mut self, value: u8) {
934        let column = value & 0x01 != 0;
935        let clock = value & 0x02 != 0;
936        let enabled = value & 0x04 != 0;
937        if enabled {
938            if clock && !self.clock {
939                // Rising clock edge: advance to the next row (saturate at last).
940                if (self.row as usize) < FAMILY_KEYBOARD_ROWS - 1 {
941                    self.row += 1;
942                }
943            } else if !clock {
944                // Clock low (while enabled): reset to the first row.
945                self.row = 0;
946            }
947        }
948        self.column = column;
949        self.enabled = enabled;
950        self.clock = clock;
951    }
952
953    /// Read the device byte for a `$4017` access. The four selected key switches
954    /// are returned on bits 4..1, **active-low** (0 = pressed). When the matrix
955    /// is disabled, all four bits read `1` (no keys). The caller ORs in the
956    /// open-bus upper bits.
957    #[must_use]
958    pub const fn read(&self) -> u8 {
959        if !self.enabled {
960            // Disabled matrix: key switches all read high (not pressed).
961            return 0b0001_1110;
962        }
963        let row = self.row as usize;
964        let byte = self.keys[row];
965        let nibble = if self.column {
966            (byte >> 4) & 0x0F
967        } else {
968            byte & 0x0F
969        };
970        // Active-low: pressed key (1 in our bitmap) reads 0 on the wire.
971        let wire = (!nibble) & 0x0F;
972        wire << 1
973    }
974
975    /// Side-effect-free sample of the device byte (debugger peek) — identical to
976    /// [`Self::read`] (the keyboard read has no side effects).
977    #[must_use]
978    pub const fn peek(&self) -> u8 {
979        self.read()
980    }
981
982    /// Reconstruct from save-state parts.
983    #[must_use]
984    pub const fn from_parts(
985        keys: [u8; FAMILY_KEYBOARD_ROWS],
986        row: u8,
987        column: bool,
988        enabled: bool,
989        clock: bool,
990    ) -> Self {
991        // Clamp the restored row to the matrix bound: a corrupt/malicious
992        // save-state must not be able to drive `read()`'s `self.keys[row]`
993        // out of bounds. The live `write_strobe` path already saturates the
994        // row at `FAMILY_KEYBOARD_ROWS - 1`; mirror that on restore.
995        let row = if (row as usize) >= FAMILY_KEYBOARD_ROWS {
996            #[allow(clippy::cast_possible_truncation)] // ROWS is small (9)
997            {
998                (FAMILY_KEYBOARD_ROWS - 1) as u8
999            }
1000        } else {
1001            row
1002        };
1003        Self {
1004            keys,
1005            row,
1006            column,
1007            enabled,
1008            clock,
1009        }
1010    }
1011
1012    /// Raw per-row key bitmap (save-state).
1013    #[must_use]
1014    pub const fn keys_raw(&self) -> [u8; FAMILY_KEYBOARD_ROWS] {
1015        self.keys
1016    }
1017    /// Raw row counter (save-state).
1018    #[must_use]
1019    pub const fn row_raw(&self) -> u8 {
1020        self.row
1021    }
1022    /// Raw column select (save-state).
1023    #[must_use]
1024    pub const fn column_raw(&self) -> bool {
1025        self.column
1026    }
1027    /// Raw matrix-enable (save-state).
1028    #[must_use]
1029    pub const fn enabled_raw(&self) -> bool {
1030        self.enabled
1031    }
1032    /// Raw clock level (save-state).
1033    #[must_use]
1034    pub const fn clock_raw(&self) -> bool {
1035        self.clock
1036    }
1037}
1038
1039/// The **Konami Hyper Shot** overlay state (v1.3.0 Workstream F1).
1040///
1041/// A simple 4-button expansion controller (two players, each with a Run and a
1042/// Jump button) used by _Hyper Olympic_ / _Hyper Sports_. Per the `NESdev`
1043/// "Konami Hyper Shot" page it is read in **parallel** on `$4017` (no shift
1044/// register), with `$4016` writes selecting which player's buttons are
1045/// enabled:
1046///
1047/// ```text
1048/// $4016 write:               $4017 read:
1049/// 7  bit  0                  7  bit  0
1050/// ---- ----                  ---- ----
1051/// xxxx xEFx                  xxxD CBAx
1052///       ||                      | |||
1053///       |+- 0 = enable P1          | ||+-- P1 Run
1054///       +-- 0 = enable P2          | |+--- P1 Jump
1055///                                  | +---- P2 Run
1056///                                  +------ P2 Jump
1057/// ```
1058///
1059/// The Jump/Run bits for a player read `0` while that player's enable bit
1060/// ($4016 bit 1 for P1, bit 2 for P2) is **set** (i.e. disabled). Determinism
1061/// holds: the read is a pure function of the live button mask + the last write.
1062#[derive(Clone, Copy, Debug, Default)]
1063pub struct KonamiHyperShotState {
1064    /// Live button mask: bit 0 = P1 Run, bit 1 = P1 Jump, bit 2 = P2 Run,
1065    /// bit 3 = P2 Jump.
1066    pub(crate) buttons: u8,
1067    /// `true` if P1's buttons are enabled (`$4016` bit 1 == 0).
1068    pub(crate) p1_enabled: bool,
1069    /// `true` if P2's buttons are enabled (`$4016` bit 2 == 0).
1070    pub(crate) p2_enabled: bool,
1071}
1072
1073impl KonamiHyperShotState {
1074    /// New controller with no buttons held and both players enabled (the
1075    /// power-on `$4016` write has not happened yet; enable is active-low, so the
1076    /// quiescent state matches a write of 0).
1077    #[must_use]
1078    pub const fn new() -> Self {
1079        Self {
1080            buttons: 0,
1081            p1_enabled: true,
1082            p2_enabled: true,
1083        }
1084    }
1085
1086    /// Set the live 4-button mask (bit 0 = P1 Run, 1 = P1 Jump, 2 = P2 Run,
1087    /// 3 = P2 Jump). Bits above 3 are ignored.
1088    pub const fn set(&mut self, buttons: u8) {
1089        self.buttons = buttons & 0x0F;
1090    }
1091
1092    /// Handle a `$4016` write: bit 1 = 0 enables P1, bit 2 = 0 enables P2
1093    /// (active-low).
1094    pub const fn write_strobe(&mut self, value: u8) {
1095        self.p1_enabled = value & 0x02 == 0;
1096        self.p2_enabled = value & 0x04 == 0;
1097    }
1098
1099    /// Read the device byte for a `$4017` access. Bit 1 = P1 Run, bit 2 = P1
1100    /// Jump, bit 3 = P2 Run, bit 4 = P2 Jump; a player's bits read `0` while
1101    /// disabled. The caller ORs in the open-bus upper bits.
1102    #[must_use]
1103    pub const fn read(&self) -> u8 {
1104        let p1_run = (self.buttons & 0x01 != 0) && self.p1_enabled;
1105        let p1_jump = (self.buttons & 0x02 != 0) && self.p1_enabled;
1106        let p2_run = (self.buttons & 0x04 != 0) && self.p2_enabled;
1107        let p2_jump = (self.buttons & 0x08 != 0) && self.p2_enabled;
1108        ((p1_run as u8) << 1)
1109            | ((p1_jump as u8) << 2)
1110            | ((p2_run as u8) << 3)
1111            | ((p2_jump as u8) << 4)
1112    }
1113
1114    /// Side-effect-free sample (debugger peek) — identical to [`Self::read`].
1115    #[must_use]
1116    pub const fn peek(&self) -> u8 {
1117        self.read()
1118    }
1119
1120    /// Reconstruct from save-state parts.
1121    #[must_use]
1122    pub const fn from_parts(buttons: u8, p1_enabled: bool, p2_enabled: bool) -> Self {
1123        Self {
1124            buttons: buttons & 0x0F,
1125            p1_enabled,
1126            p2_enabled,
1127        }
1128    }
1129
1130    /// Raw button mask (save-state).
1131    #[must_use]
1132    pub const fn buttons_raw(&self) -> u8 {
1133        self.buttons
1134    }
1135    /// Raw P1-enable (save-state).
1136    #[must_use]
1137    pub const fn p1_enabled_raw(&self) -> bool {
1138        self.p1_enabled
1139    }
1140    /// Raw P2-enable (save-state).
1141    #[must_use]
1142    pub const fn p2_enabled_raw(&self) -> bool {
1143        self.p2_enabled
1144    }
1145}
1146
1147/// The **Bandai Hyper Shot** (Exciting Boxing punching bag) overlay state
1148/// (v1.3.0 Workstream F1).
1149///
1150/// The punching bag has 8 sensors read on `$4017`, multiplexed by `$4016`
1151/// bit 1 (the "A" select) into two groups of four returned on bits 4..1. Per
1152/// the `NESdev` "Exciting Boxing Punching Bag" page:
1153///
1154/// ```text
1155/// $4016 write:               $4017 read:
1156/// 7  bit  0                  7  bit  0
1157/// ---- ----                  ---- ----
1158/// xxxx xxAx                  xxxE DCBx
1159///        |                      | |||
1160///        +- select group        | ||+-- Left Hook (A=0) / Left Jab  (A=1)
1161///                               | |+--- Move Right (A=0) / Body      (A=1)
1162///                               | +---- Move Left (A=0) / Right Jab  (A=1)
1163///                               +------ Right Hook (A=0) / Straight   (A=1)
1164/// ```
1165///
1166/// We model the 8 sensors as a live bitmask and the `A` select from the last
1167/// `$4016` write; the read is a pure function of both (deterministic).
1168#[derive(Clone, Copy, Debug, Default)]
1169pub struct BandaiHyperShotState {
1170    /// Live sensor mask. Group A=0 (bits 0..=3): Left Hook, Move Right, Move
1171    /// Left, Right Hook. Group A=1 (bits 4..=7): Left Jab, Body, Right Jab,
1172    /// Straight. A set bit = that sensor is active.
1173    pub(crate) sensors: u8,
1174    /// The `A` select latched from the last `$4016` write (bit 1). `false`
1175    /// selects the A=0 group (bits 0..=3), `true` the A=1 group (bits 4..=7).
1176    pub(crate) select: bool,
1177}
1178
1179impl BandaiHyperShotState {
1180    /// New punching bag with no sensor active, group A=0 selected.
1181    #[must_use]
1182    pub const fn new() -> Self {
1183        Self {
1184            sensors: 0,
1185            select: false,
1186        }
1187    }
1188
1189    /// Set the live 8-sensor mask. Bits 0..=3 are the A=0 group (Left Hook,
1190    /// Move Right, Move Left, Right Hook); bits 4..=7 are the A=1 group (Left
1191    /// Jab, Body, Right Jab, Straight).
1192    pub const fn set(&mut self, sensors: u8) {
1193        self.sensors = sensors;
1194    }
1195
1196    /// Handle a `$4016` write: bit 1 (`A`) selects which sensor group is
1197    /// returned on the next reads.
1198    pub const fn write_strobe(&mut self, value: u8) {
1199        self.select = value & 0x02 != 0;
1200    }
1201
1202    /// Read the device byte for a `$4017` access. The selected group's four
1203    /// sensors appear on bits 4..1. The caller ORs in the open-bus upper bits.
1204    #[must_use]
1205    pub const fn read(&self) -> u8 {
1206        let nibble = if self.select {
1207            (self.sensors >> 4) & 0x0F
1208        } else {
1209            self.sensors & 0x0F
1210        };
1211        nibble << 1
1212    }
1213
1214    /// Side-effect-free sample (debugger peek) — identical to [`Self::read`].
1215    #[must_use]
1216    pub const fn peek(&self) -> u8 {
1217        self.read()
1218    }
1219
1220    /// Reconstruct from save-state parts.
1221    #[must_use]
1222    pub const fn from_parts(sensors: u8, select: bool) -> Self {
1223        Self { sensors, select }
1224    }
1225
1226    /// Raw sensor mask (save-state).
1227    #[must_use]
1228    pub const fn sensors_raw(&self) -> u8 {
1229        self.sensors
1230    }
1231    /// Raw `A`-select (save-state).
1232    #[must_use]
1233    pub const fn select_raw(&self) -> bool {
1234        self.select
1235    }
1236}
1237
1238/// An optional non-standard device overlaid on a controller port. When set,
1239/// the bus's `$4016`/`$4017` read path returns this device's byte instead of
1240/// the standard controller / Four Score serial byte.
1241#[derive(Clone, Copy, Debug)]
1242pub enum InputDevice {
1243    /// NES Zapper light gun.
1244    Zapper(ZapperState),
1245    /// Arkanoid "Vaus" paddle.
1246    Vaus(VausState),
1247    /// NES Power Pad / Family Fun Fitness mat (12 buttons).
1248    PowerPad(PowerPadState),
1249    /// SNES-style serial mouse (Hyperkin / Nintendo), D0 serial-out.
1250    SnesMouse(SnesMouseState),
1251    /// Famicom Family BASIC keyboard (72-key matrix on `$4017`).
1252    FamilyKeyboard(FamilyKeyboardState),
1253    /// Bandai **Family Trainer** mat (v1.3.0 Workstream F1). Layout-equivalent
1254    /// to the [`PowerPad`](Self::PowerPad): the Famicom mat reuses the exact
1255    /// 12-button parallel-in/serial-out scan (it differs only in the expansion-
1256    /// port wiring vs the NES controller-port Power Pad), so the same
1257    /// [`PowerPadState`] drives it.
1258    FamilyTrainer(PowerPadState),
1259    /// **Subor keyboard** (v1.3.0 Workstream F1). A Family BASIC keyboard
1260    /// work-alike (the Subor clone matrix), reusing the same
1261    /// [`FamilyKeyboardState`] `9 x 8` matrix scan.
1262    SuborKeyboard(FamilyKeyboardState),
1263    /// **Konami Hyper Shot** (v1.3.0 Workstream F1): a 4-button (2-player
1264    /// Run/Jump) parallel-read expansion controller.
1265    KonamiHyperShot(KonamiHyperShotState),
1266    /// **Bandai Hyper Shot** / Exciting Boxing punching bag (v1.3.0 Workstream
1267    /// F1): an 8-sensor expansion controller multiplexed into two groups.
1268    BandaiHyperShot(BandaiHyperShotState),
1269}
1270
1271impl InputDevice {
1272    /// Forward a `$4016` strobe write to the device (only the Vaus latches on
1273    /// it; the Zapper ignores it).
1274    pub const fn write_strobe(&mut self, value: u8) {
1275        match self {
1276            Self::Vaus(v) => v.write_strobe(value),
1277            Self::PowerPad(p) | Self::FamilyTrainer(p) => p.write_strobe(value),
1278            Self::SnesMouse(m) => m.write_strobe(value),
1279            Self::FamilyKeyboard(k) | Self::SuborKeyboard(k) => k.write_strobe(value),
1280            Self::KonamiHyperShot(h) => h.write_strobe(value),
1281            Self::BandaiHyperShot(b) => b.write_strobe(value),
1282            Self::Zapper(_) => {}
1283        }
1284    }
1285
1286    /// Read the device byte (already bit-positioned), advancing any internal
1287    /// shift register.
1288    pub const fn read(&mut self) -> u8 {
1289        match self {
1290            Self::Vaus(v) => v.read(),
1291            Self::Zapper(z) => z.read(),
1292            Self::PowerPad(p) | Self::FamilyTrainer(p) => p.read(),
1293            Self::SnesMouse(m) => m.read(),
1294            Self::FamilyKeyboard(k) | Self::SuborKeyboard(k) => k.read(),
1295            Self::KonamiHyperShot(h) => h.read(),
1296            Self::BandaiHyperShot(b) => b.read(),
1297        }
1298    }
1299
1300    /// Side-effect-free sample of the device byte (debugger peek).
1301    #[must_use]
1302    pub const fn peek(&self) -> u8 {
1303        match self {
1304            Self::Vaus(v) => v.peek(),
1305            Self::Zapper(z) => z.read(),
1306            Self::PowerPad(p) | Self::FamilyTrainer(p) => p.peek(),
1307            Self::SnesMouse(m) => m.peek(),
1308            Self::FamilyKeyboard(k) | Self::SuborKeyboard(k) => k.peek(),
1309            Self::KonamiHyperShot(h) => h.peek(),
1310            Self::BandaiHyperShot(b) => b.peek(),
1311        }
1312    }
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318
1319    #[test]
1320    fn vaus_fire_button_on_bit3_independent_of_strobe() {
1321        let mut v = VausState::new();
1322        v.set(0x80, true);
1323        // No strobe yet; fire is returned directly regardless.
1324        assert_eq!(v.read() & (1 << 3), 1 << 3, "fire = bit 3 set");
1325        v.set(0x80, false);
1326        assert_eq!(v.read() & (1 << 3), 0, "fire released = bit 3 clear");
1327    }
1328
1329    #[test]
1330    fn vaus_knob_shifts_out_msb_first_inverted_on_bit4() {
1331        let mut v = VausState::new();
1332        // position 0b1010_0000: MSb-first raw bits = 1,0,1,0,0,0,0,0
1333        v.set(0b1010_0000, false);
1334        v.write_strobe(1);
1335        v.write_strobe(0);
1336        // Wire is inverted, so expected wire bits (bit 4) = 0,1,0,1,1,1,1,1.
1337        let expect_raw = [1u8, 0, 1, 0, 0, 0, 0, 0];
1338        for (i, raw) in expect_raw.iter().enumerate() {
1339            let byte = v.read();
1340            let wire_bit = (byte >> 4) & 1;
1341            assert_eq!(wire_bit, raw ^ 1, "read {i}: wire bit must be inverted raw");
1342        }
1343    }
1344
1345    #[test]
1346    fn vaus_post_empty_repeats_serial_in_bit() {
1347        let mut v = VausState::new();
1348        // LSb (serial-in) = 1 -> after the 8 real bits, reads repeat inverted 1 = 0.
1349        v.set(0b0000_0001, false);
1350        v.write_strobe(1);
1351        v.write_strobe(0);
1352        for _ in 0..8 {
1353            let _ = v.read();
1354        }
1355        // Now the register is all serial-in (1); wire bit = inverted = 0.
1356        for _ in 0..4 {
1357            assert_eq!((v.read() >> 4) & 1, 0);
1358        }
1359    }
1360
1361    #[test]
1362    fn zapper_light_detected_for_bright_region() {
1363        let mut z = ZapperState::new();
1364        z.set(10, 10, false);
1365        let mut fb = alloc::vec![0u8; 256 * 240 * 4];
1366        // Bright white 3x3 target block centred on the aim point (10, 10) — the
1367        // target flash lights the whole photodiode aperture.
1368        for py in 9..=11usize {
1369            for px in 9..=11usize {
1370                let idx = (py * 256 + px) * 4;
1371                fb[idx] = 0xFF;
1372                fb[idx + 1] = 0xFF;
1373                fb[idx + 2] = 0xFF;
1374            }
1375        }
1376        z.sample_light(&fb);
1377        // Light detected -> bit 3 = 0.
1378        assert_eq!(
1379            z.read() & (1 << 3),
1380            0,
1381            "bright target region -> light detected (bit3=0)"
1382        );
1383    }
1384
1385    #[test]
1386    fn zapper_aperture_rejects_lone_bright_pixel() {
1387        // A single stray-bright pixel (below ZAPPER_APERTURE_MIN_BRIGHT) is not
1388        // enough to fire the photodiode — the aperture rejects PPU edge noise.
1389        let mut z = ZapperState::new();
1390        z.set(50, 50, false);
1391        let mut fb = alloc::vec![0u8; 256 * 240 * 4];
1392        let idx = (50 * 256 + 50) * 4;
1393        fb[idx] = 0xFF;
1394        fb[idx + 1] = 0xFF;
1395        fb[idx + 2] = 0xFF;
1396        z.sample_light(&fb);
1397        assert_eq!(
1398            z.read() & (1 << 3),
1399            1 << 3,
1400            "lone bright pixel -> no light (bit3=1)"
1401        );
1402    }
1403
1404    #[test]
1405    fn zapper_no_light_for_dark_pixel() {
1406        let mut z = ZapperState::new();
1407        z.set(10, 10, false);
1408        let fb = alloc::vec![0u8; 256 * 240 * 4]; // all black
1409        z.sample_light(&fb);
1410        assert_eq!(
1411            z.read() & (1 << 3),
1412            1 << 3,
1413            "dark pixel -> no light (bit3=1)"
1414        );
1415    }
1416
1417    #[test]
1418    fn zapper_off_screen_never_sees_light() {
1419        let mut z = ZapperState::new();
1420        z.set(1000, 1000, false);
1421        let mut fb = alloc::vec![0u8; 256 * 240 * 4];
1422        fb.fill(0xFF);
1423        z.sample_light(&fb);
1424        assert_eq!(z.read() & (1 << 3), 1 << 3, "off-screen aim -> no light");
1425    }
1426
1427    #[test]
1428    fn zapper_trigger_on_bit4() {
1429        let mut z = ZapperState::new();
1430        z.set(10, 10, true);
1431        assert_eq!(z.read() & (1 << 4), 1 << 4, "trigger pulled -> bit4 set");
1432        z.set(10, 10, false);
1433        assert_eq!(z.read() & (1 << 4), 0, "trigger released -> bit4 clear");
1434    }
1435
1436    /// Read 8 device bytes after a strobe, returning the bit-3 (L) and bit-4 (H)
1437    /// streams as bool arrays.
1438    fn powerpad_read8(p: &mut PowerPadState) -> ([bool; 8], [bool; 8]) {
1439        p.write_strobe(1);
1440        p.write_strobe(0);
1441        let mut l = [false; 8];
1442        let mut h = [false; 8];
1443        for i in 0..8 {
1444            let b = p.read();
1445            l[i] = b & (1 << 3) != 0;
1446            h[i] = b & (1 << 4) != 0;
1447        }
1448        (l, h)
1449    }
1450
1451    #[test]
1452    fn powerpad_no_buttons_reads_clear_then_h_ones() {
1453        // No buttons: L is all 0; H reads 0 for the first 4 (buttons 4,3,12,8),
1454        // then 1 for the trailing "read as H=1" bits.
1455        let mut p = PowerPadState::new();
1456        let (l, h) = powerpad_read8(&mut p);
1457        assert_eq!(l, [false; 8], "no L bits with nothing pressed");
1458        assert_eq!(h, [false, false, false, false, true, true, true, true]);
1459    }
1460
1461    #[test]
1462    fn powerpad_button_maps_to_expected_serial_position() {
1463        // Mat button "1" (index 0) is bit 1 of L -> appears on the 2nd read.
1464        let mut p = PowerPadState::new();
1465        p.set(1 << 0);
1466        let (l, _h) = powerpad_read8(&mut p);
1467        assert_eq!(l, [false, true, false, false, false, false, false, false]);
1468
1469        // Mat button "2" (index 1) is bit 0 of L -> appears on the 1st read.
1470        let mut p = PowerPadState::new();
1471        p.set(1 << 1);
1472        let (l, _h) = powerpad_read8(&mut p);
1473        assert_eq!(l, [true, false, false, false, false, false, false, false]);
1474
1475        // Mat button "4" (index 3) is bit 0 of H -> 1st read on bit 4.
1476        let mut p = PowerPadState::new();
1477        p.set(1 << 3);
1478        let (_l, h) = powerpad_read8(&mut p);
1479        assert_eq!(h, [true, false, false, false, true, true, true, true]);
1480    }
1481
1482    #[test]
1483    fn powerpad_strobe_high_reloads_each_read() {
1484        // While strobe is high, every read re-latches, so the first serial bit
1485        // is returned repeatedly (standard controller strobe semantics).
1486        let mut p = PowerPadState::new();
1487        p.set(1 << 1); // button "2" -> L bit 0 (1st-read position).
1488        p.write_strobe(1); // strobe held high
1489        for _ in 0..5 {
1490            assert_eq!(p.read() & (1 << 3), 1 << 3, "strobe-high repeats bit 0");
1491        }
1492    }
1493
1494    #[test]
1495    fn powerpad_save_state_round_trip() {
1496        let mut p = PowerPadState::new();
1497        p.set(0b1010_0101_0011);
1498        p.write_strobe(1);
1499        p.write_strobe(0);
1500        let _ = p.read(); // advance the registers
1501        let restored = PowerPadState::from_parts(
1502            p.buttons_raw(),
1503            p.shift_l_raw(),
1504            p.shift_h_raw(),
1505            p.strobe_raw(),
1506        );
1507        assert_eq!(restored.peek(), p.peek());
1508        assert_eq!(restored.buttons_raw(), 0b1010_0101_0011);
1509    }
1510
1511    #[test]
1512    fn powerpad_masks_to_12_bits() {
1513        // Bits above 11 are ignored (the mat has 12 buttons).
1514        let mut p = PowerPadState::new();
1515        p.set(0xFFFF);
1516        assert_eq!(p.buttons_raw(), 0x0FFF);
1517    }
1518
1519    #[test]
1520    fn input_device_enum_dispatch() {
1521        let mut d = InputDevice::Vaus(VausState::new());
1522        d.write_strobe(1);
1523        d.write_strobe(0);
1524        let _ = d.read();
1525        let mut z = InputDevice::Zapper(ZapperState::new());
1526        // Strobe is a no-op for the Zapper.
1527        z.write_strobe(1);
1528        assert_eq!(z.read() & (1 << 3), 1 << 3, "zapper: no light by default");
1529    }
1530
1531    /// Shift out `n` D0 bits (MSb-first), returning them packed into a u64 in
1532    /// read order (first bit = most significant of the returned `n`-bit value).
1533    fn mouse_read_bits(m: &mut SnesMouseState, n: usize) -> u64 {
1534        m.write_strobe(1);
1535        m.write_strobe(0);
1536        let mut acc = 0u64;
1537        for _ in 0..n {
1538            acc = (acc << 1) | u64::from(m.read() & 1);
1539        }
1540        acc
1541    }
1542
1543    #[test]
1544    fn snes_mouse_signature_nibble_is_0b0001() {
1545        let mut m = SnesMouseState::new();
1546        // First 4 bits are the device-id signature nibble 0b0001.
1547        let bits = mouse_read_bits(&mut m, 4);
1548        assert_eq!(bits, 0b0001, "signature nibble must be 0b0001");
1549    }
1550
1551    #[test]
1552    fn snes_mouse_full_report_encodes_buttons_and_movement() {
1553        let mut m = SnesMouseState::new();
1554        // dx = +5, dy = -3, left pressed, sensitivity = 2 (high).
1555        m.set(5, -3, true, false, 2);
1556        let word = mouse_read_bits(&mut m, 32);
1557        // Reconstruct the full 32-bit word and check each field.
1558        assert_eq!((word >> 28) & 0x0F, 0b0001, "signature");
1559        assert_eq!((word >> 24) & 0b11, 2, "sensitivity");
1560        assert_eq!((word >> 23) & 1, 1, "left button");
1561        assert_eq!((word >> 22) & 1, 0, "right button");
1562        // Y field (bits 15..8): sign=1 (negative), magnitude 3.
1563        let y = (word >> 8) & 0xFF;
1564        assert_eq!((y >> 7) & 1, 1, "Y sign negative");
1565        assert_eq!(y & 0x7F, 3, "Y magnitude");
1566        // X field (bits 7..0): sign=0 (positive), magnitude 5.
1567        let x = word & 0xFF;
1568        assert_eq!((x >> 7) & 1, 0, "X sign positive");
1569        assert_eq!(x & 0x7F, 5, "X magnitude");
1570    }
1571
1572    #[test]
1573    fn snes_mouse_idles_high_after_32_bits() {
1574        let mut m = SnesMouseState::new();
1575        m.write_strobe(1);
1576        m.write_strobe(0);
1577        for _ in 0..32 {
1578            let _ = m.read();
1579        }
1580        for _ in 0..4 {
1581            assert_eq!(m.read() & 1, 1, "serial line idles high after the report");
1582        }
1583    }
1584
1585    #[test]
1586    fn snes_mouse_clamps_movement_to_127() {
1587        let mut m = SnesMouseState::new();
1588        m.set(1000, -1000, false, false, 0);
1589        let word = mouse_read_bits(&mut m, 32);
1590        assert_eq!(word & 0x7F, 127, "X magnitude clamps to 127");
1591        assert_eq!((word >> 8) & 0x7F, 127, "Y magnitude clamps to 127");
1592    }
1593
1594    #[test]
1595    fn snes_mouse_enc_axis_handles_i16_extremes_without_panic() {
1596        // Regression: `enc_axis(i16::MIN)` must not panic on the `-v` overflow
1597        // (`-(-32768)` is unrepresentable as i16). Both extremes encode sanely:
1598        // sign bit set/clear and magnitude clamped to the 7-bit max of 127.
1599        let mut m = SnesMouseState::new();
1600        m.set(i16::MIN, i16::MAX, false, false, 0);
1601        let word = mouse_read_bits(&mut m, 32);
1602        // X = i16::MIN: negative -> sign bit (bit 7) set, magnitude clamped 127.
1603        assert_eq!(word & 0x80, 0x80, "i16::MIN encodes as negative");
1604        assert_eq!(word & 0x7F, 127, "i16::MIN magnitude clamps to 127");
1605        // Y = i16::MAX: positive -> sign bit clear, magnitude clamped 127.
1606        assert_eq!((word >> 8) & 0x80, 0, "i16::MAX encodes as positive");
1607        assert_eq!((word >> 8) & 0x7F, 127, "i16::MAX magnitude clamps to 127");
1608    }
1609
1610    #[test]
1611    fn snes_mouse_strobe_high_repeats_signature_bit() {
1612        let mut m = SnesMouseState::new();
1613        m.write_strobe(1); // held high
1614        for _ in 0..5 {
1615            // Signature MSb (bit 31 of 0b0001 << 28) is 0; repeats while strobed.
1616            assert_eq!(m.read() & 1, 0, "strobe-high repeats bit 31");
1617        }
1618    }
1619
1620    #[test]
1621    fn family_keyboard_disabled_reads_all_high() {
1622        let k = FamilyKeyboardState::new();
1623        // Not enabled (bit 2 unset): key switches all read high (bits 4..1 set).
1624        assert_eq!(
1625            k.read(),
1626            0b0001_1110,
1627            "disabled matrix -> no keys (bits 4..1=1)"
1628        );
1629    }
1630
1631    #[test]
1632    fn family_keyboard_pressed_key_reads_active_low() {
1633        let mut k = FamilyKeyboardState::new();
1634        // Press key at row 0, column-half 0, switch 0 (linear index 0).
1635        k.set_key(0, true);
1636        // Enable matrix (bit2), select column-half 0 (bit0=0), clock low resets row to 0.
1637        k.write_strobe(0b0000_0100);
1638        let r = k.read();
1639        // The pressed switch (bit 0 of the nibble) appears active-low on bit 1.
1640        assert_eq!(r & (1 << 1), 0, "pressed key reads 0 (active-low) on bit 1");
1641        // The other three switches are not pressed -> read 1.
1642        assert_eq!(r & (1 << 2), 1 << 2);
1643        assert_eq!(r & (1 << 3), 1 << 3);
1644        assert_eq!(r & (1 << 4), 1 << 4);
1645    }
1646
1647    #[test]
1648    fn family_keyboard_column_select_picks_high_nibble() {
1649        let mut k = FamilyKeyboardState::new();
1650        // Key at row 0, column-half 1, switch 0 = linear index 4 (row*8 + 4).
1651        k.set_key(4, true);
1652        // Enable + select column-half 1 (bit0=1), clock low (resets row to 0).
1653        k.write_strobe(0b0000_0101);
1654        let r = k.read();
1655        assert_eq!(
1656            r & (1 << 1),
1657            0,
1658            "column-half-1 key reads active-low on bit 1"
1659        );
1660        // Selecting column-half 0 instead shows nothing pressed there.
1661        k.write_strobe(0b0000_0100);
1662        assert_eq!(k.read() & (1 << 1), 1 << 1, "column-half 0 has no key here");
1663    }
1664
1665    #[test]
1666    fn family_keyboard_clock_edge_advances_row() {
1667        let mut k = FamilyKeyboardState::new();
1668        // Press a key on row 1, column-half 0, switch 0 = linear index 8.
1669        k.set_key(8, true);
1670        // Enable + clock low -> row 0.
1671        k.write_strobe(0b0000_0100);
1672        assert_eq!(k.read() & (1 << 1), 1 << 1, "row 0 has no key");
1673        // Rising clock edge (bit1 0->1) advances to row 1.
1674        k.write_strobe(0b0000_0110);
1675        assert_eq!(
1676            k.read() & (1 << 1),
1677            0,
1678            "row 1 key now selected (active-low)"
1679        );
1680    }
1681
1682    #[test]
1683    fn family_keyboard_save_state_round_trip() {
1684        let mut k = FamilyKeyboardState::new();
1685        k.set_key(8, true);
1686        k.set_key(40, true);
1687        k.write_strobe(0b0000_0110);
1688        let restored = FamilyKeyboardState::from_parts(
1689            k.keys_raw(),
1690            k.row_raw(),
1691            k.column_raw(),
1692            k.enabled_raw(),
1693            k.clock_raw(),
1694        );
1695        assert_eq!(restored.read(), k.read());
1696        assert_eq!(restored.keys_raw(), k.keys_raw());
1697    }
1698
1699    #[test]
1700    fn family_keyboard_from_parts_clamps_out_of_range_row() {
1701        // A corrupt/malicious save-state must not be able to drive a row value
1702        // that would index `self.keys[row]` out of bounds in `read()`.
1703        let keys = [0u8; FAMILY_KEYBOARD_ROWS];
1704        let restored = FamilyKeyboardState::from_parts(keys, 250, false, true, false);
1705        assert!(
1706            (restored.row_raw() as usize) < FAMILY_KEYBOARD_ROWS,
1707            "out-of-range row saturated to the matrix bound"
1708        );
1709        // Must not panic: enabled matrix indexes keys[row] in read().
1710        let _ = restored.read();
1711    }
1712
1713    #[test]
1714    fn family_keyboard_set_key_out_of_range_is_noop() {
1715        let mut k = FamilyKeyboardState::new();
1716        k.set_key(FAMILY_KEYBOARD_KEYS, true); // index == 72, out of range
1717        k.set_key(1000, true);
1718        assert_eq!(k.keys_raw(), [0; FAMILY_KEYBOARD_ROWS]);
1719    }
1720
1721    // --- v1.3.0 Workstream F1 — niche peripheral aliases + Hyper Shots ---
1722
1723    #[test]
1724    fn family_trainer_reuses_power_pad_scan() {
1725        // The Family Trainer is layout-equivalent to the Power Pad: an identical
1726        // PowerPadState must produce an identical serial readout through both
1727        // InputDevice variants.
1728        let mut pad = InputDevice::PowerPad(PowerPadState::new());
1729        let mut mat = InputDevice::FamilyTrainer(PowerPadState::new());
1730        if let (InputDevice::PowerPad(p), InputDevice::FamilyTrainer(m)) = (&mut pad, &mut mat) {
1731            p.set(0b1010_0101_0011);
1732            m.set(0b1010_0101_0011);
1733        }
1734        pad.write_strobe(1);
1735        pad.write_strobe(0);
1736        mat.write_strobe(1);
1737        mat.write_strobe(0);
1738        for i in 0..8 {
1739            assert_eq!(pad.read(), mat.read(), "read {i}: trainer == power pad");
1740        }
1741    }
1742
1743    #[test]
1744    fn subor_keyboard_reuses_family_keyboard_scan() {
1745        // The Subor keyboard reuses the Family BASIC keyboard matrix scan; the
1746        // same key state must read identically through both variants.
1747        let mut fam = FamilyKeyboardState::new();
1748        let mut sub = FamilyKeyboardState::new();
1749        fam.set_key(8, true);
1750        sub.set_key(8, true);
1751        let mut famd = InputDevice::FamilyKeyboard(fam);
1752        let mut subd = InputDevice::SuborKeyboard(sub);
1753        // Enable + clock low (row 0), then rising edge -> row 1.
1754        for v in [0b0000_0100u8, 0b0000_0110] {
1755            famd.write_strobe(v);
1756            subd.write_strobe(v);
1757        }
1758        assert_eq!(famd.read(), subd.read(), "subor == family keyboard read");
1759        assert_eq!(famd.peek(), subd.peek());
1760    }
1761
1762    #[test]
1763    fn konami_hyper_shot_buttons_on_expected_bits() {
1764        let mut h = KonamiHyperShotState::new();
1765        // P1 Run (bit0) -> read bit 1; P2 Jump (bit3) -> read bit 4.
1766        h.set(0b1001);
1767        h.write_strobe(0); // enable both players (active-low)
1768        let r = h.read();
1769        assert_eq!(r & (1 << 1), 1 << 1, "P1 Run on bit 1");
1770        assert_eq!(r & (1 << 4), 1 << 4, "P2 Jump on bit 4");
1771        assert_eq!(r & (1 << 2), 0, "P1 Jump not pressed");
1772        assert_eq!(r & (1 << 3), 0, "P2 Run not pressed");
1773    }
1774
1775    #[test]
1776    fn konami_hyper_shot_disabled_player_reads_zero() {
1777        let mut h = KonamiHyperShotState::new();
1778        h.set(0b1111); // all four buttons held
1779        // Disable P1 (bit 1 set), enable P2 (bit 2 clear).
1780        h.write_strobe(0b0000_0010);
1781        let r = h.read();
1782        assert_eq!(r & (1 << 1), 0, "disabled P1 Run reads 0");
1783        assert_eq!(r & (1 << 2), 0, "disabled P1 Jump reads 0");
1784        assert_eq!(r & (1 << 3), 1 << 3, "enabled P2 Run reads pressed");
1785        assert_eq!(r & (1 << 4), 1 << 4, "enabled P2 Jump reads pressed");
1786    }
1787
1788    #[test]
1789    fn konami_hyper_shot_save_state_round_trip() {
1790        let mut h = KonamiHyperShotState::new();
1791        h.set(0b0110);
1792        h.write_strobe(0b0000_0100); // disable P2
1793        let r = KonamiHyperShotState::from_parts(
1794            h.buttons_raw(),
1795            h.p1_enabled_raw(),
1796            h.p2_enabled_raw(),
1797        );
1798        assert_eq!(r.peek(), h.peek());
1799        assert_eq!(r.buttons_raw(), 0b0110);
1800    }
1801
1802    #[test]
1803    fn bandai_hyper_shot_select_picks_sensor_group() {
1804        let mut b = BandaiHyperShotState::new();
1805        // Group A=0 = bits 0..=3 (Left Hook = bit 0), A=1 = bits 4..=7.
1806        b.set(0b0001_0001); // Left Hook (group0) + Left Jab (group1)
1807        b.write_strobe(0); // A=0 group
1808        assert_eq!(b.read() & (1 << 1), 1 << 1, "group0 sensor 0 on bit 1");
1809        b.write_strobe(0b0000_0010); // A=1 group
1810        assert_eq!(b.read() & (1 << 1), 1 << 1, "group1 sensor 0 on bit 1");
1811        // A sensor only in group0 must vanish when the A=1 group is selected.
1812        let mut b2 = BandaiHyperShotState::new();
1813        b2.set(0b0000_1000); // only group0 bit 3 (Right Hook)
1814        b2.write_strobe(0b0000_0010); // select A=1
1815        assert_eq!(b2.read() & 0b1_1110, 0, "group0-only sensor absent in A=1");
1816    }
1817
1818    #[test]
1819    fn bandai_hyper_shot_save_state_round_trip() {
1820        let mut b = BandaiHyperShotState::new();
1821        b.set(0b1100_0011);
1822        b.write_strobe(0b0000_0010);
1823        let r = BandaiHyperShotState::from_parts(b.sensors_raw(), b.select_raw());
1824        assert_eq!(r.peek(), b.peek());
1825        assert_eq!(r.sensors_raw(), 0b1100_0011);
1826        assert!(r.select_raw());
1827    }
1828
1829    #[test]
1830    fn hyper_shots_dispatch_through_input_device() {
1831        let mut k = InputDevice::KonamiHyperShot(KonamiHyperShotState::new());
1832        k.write_strobe(0);
1833        let _ = k.read();
1834        let _ = k.peek();
1835        let mut bd = InputDevice::BandaiHyperShot(BandaiHyperShotState::new());
1836        bd.write_strobe(0);
1837        let _ = bd.read();
1838        let _ = bd.peek();
1839    }
1840
1841    // ---------------------------------------------------------------
1842    // A3 (v2.2.3): beam-relative temporal light integration.
1843    // ---------------------------------------------------------------
1844
1845    /// Build a framebuffer with a bright 3x3 target centred on `(x, y)`.
1846    /// Clamped at the edges so a target on row/column 0 is expressible (the
1847    /// pre-render regression test needs `y == 0`); the 3x3 aperture is simply
1848    /// clipped there, exactly as it is on hardware at the screen edge.
1849    fn fb_with_target(x: usize, y: usize) -> alloc::vec::Vec<u8> {
1850        let mut fb = alloc::vec![0u8; 256 * 240 * 4];
1851        for py in y.saturating_sub(1)..=(y + 1).min(239) {
1852            for px in x.saturating_sub(1)..=(x + 1).min(255) {
1853                let idx = (py * 256 + px) * 4;
1854                fb[idx] = 0xFF;
1855                fb[idx + 1] = 0xFF;
1856                fb[idx + 2] = 0xFF;
1857            }
1858        }
1859        fb
1860    }
1861
1862    /// The core of A3: light is a function of WHERE THE BEAM IS, not merely of
1863    /// the frame. Before the beam paints the aim row there is no light, however
1864    /// bright the target; during the photodiode hold there is; after it drains
1865    /// there is not.
1866    #[test]
1867    fn zapper_temporal_light_follows_the_beam() {
1868        let mut z = ZapperState::new();
1869        z.set(100, 120, false);
1870        let fb = fb_with_target(100, 120);
1871
1872        // Beam still above the aim row: the row has not been painted yet.
1873        assert!(!z.light_at_scanline(&fb, 0));
1874        assert!(!z.light_at_scanline(&fb, 119));
1875
1876        // Beam reaches the aim row -> charged.
1877        assert!(z.light_at_scanline(&fb, 120));
1878        // Still within the ~19-26 scanline hold.
1879        assert!(z.light_at_scanline(&fb, 120 + ZAPPER_LIGHT_HOLD_SCANLINES - 1));
1880        // Drained.
1881        assert!(!z.light_at_scanline(&fb, 120 + ZAPPER_LIGHT_HOLD_SCANLINES));
1882        assert!(!z.light_at_scanline(&fb, 239));
1883    }
1884
1885    /// The frame-granular model cannot express the above: it reports the SAME
1886    /// answer at every scanline. This test is what makes A3 worth having.
1887    #[test]
1888    fn zapper_frame_model_is_scanline_invariant_but_temporal_is_not() {
1889        let mut z = ZapperState::new();
1890        z.set(100, 120, false);
1891        let fb = fb_with_target(100, 120);
1892        z.sample_light(&fb);
1893        // Frame model: one answer for the whole frame.
1894        assert!(z.light_seen);
1895        // Temporal model: three different answers within that same frame.
1896        let before = z.light_at_scanline(&fb, 10);
1897        let during = z.light_at_scanline(&fb, 125);
1898        let after = z.light_at_scanline(&fb, 200);
1899        assert!(
1900            !before && during && !after,
1901            "temporal model must vary within a frame"
1902        );
1903    }
1904
1905    /// The temporal path must reuse the SAME aperture rule, not a looser one:
1906    /// a lone bright pixel still fails to charge the sensor even at the exact
1907    /// beam position.
1908    #[test]
1909    fn zapper_temporal_rejects_lone_bright_pixel() {
1910        let mut z = ZapperState::new();
1911        z.set(50, 60, false);
1912        let mut fb = alloc::vec![0u8; 256 * 240 * 4];
1913        let idx = (60 * 256 + 50) * 4;
1914        fb[idx] = 0xFF;
1915        fb[idx + 1] = 0xFF;
1916        fb[idx + 2] = 0xFF;
1917        assert!(
1918            !z.light_at_scanline(&fb, 60),
1919            "one pixel must not trip the aperture"
1920        );
1921        z.sample_light(&fb);
1922        assert!(!z.light_seen, "frame model must agree");
1923    }
1924
1925    /// Aiming off-screen never sees light at any beam position.
1926    #[test]
1927    fn zapper_temporal_off_screen_never_sees_light() {
1928        let mut z = ZapperState::new();
1929        z.set(300, 250, false);
1930        let fb = alloc::vec![0xFFu8; 256 * 240 * 4];
1931        for sl in [0u16, 120, 239] {
1932            assert!(!z.light_at_scanline(&fb, sl));
1933        }
1934    }
1935
1936    /// `read_at_scanline` carries the same inverted polarity and trigger bit as
1937    /// `read`, so a caller can swap models without re-deriving the byte format.
1938    #[test]
1939    fn zapper_temporal_read_byte_matches_the_documented_bit_layout() {
1940        let mut z = ZapperState::new();
1941        z.set(100, 120, true); // trigger pulled
1942        let fb = fb_with_target(100, 120);
1943        // In the hold: light detected -> bit 3 = 0; trigger -> bit 4 = 1.
1944        assert_eq!(z.read_at_scanline(&fb, 121) & 0b0001_1000, 0b0001_0000);
1945        // Drained: light NOT detected -> bit 3 = 1.
1946        assert_eq!(z.read_at_scanline(&fb, 200) & 0b0001_1000, 0b0001_1000);
1947    }
1948
1949    /// [`ZapperState::read_before_visible`] — the total-conversion fallback for a
1950    /// negative scanline — reports no light regardless of the framebuffer, and
1951    /// still carries the trigger bit.
1952    ///
1953    /// This pins the fallback's contract, not a live defect: `Ppu::scanline()`
1954    /// is non-negative on every region (pre-render is line 261 NTSC / 311 PAL,
1955    /// not -1), so the bus reaches this only if a future convention ever hands a
1956    /// negative scanline to `u16::try_from`. The paired assertion below shows the
1957    /// difference the fallback guards against — the real pre-render line, being
1958    /// past the photodiode hold window, already reads no-light through the normal
1959    /// `read_at_scanline` path.
1960    #[test]
1961    fn zapper_read_before_visible_reports_no_light() {
1962        let mut z = ZapperState::new();
1963        z.set(100, 0, true); // aim on visible row 0, trigger pulled
1964        let fb = fb_with_target(100, 0);
1965
1966        // v2.3.6: reading WHILE the beam is on the aim row reports no light —
1967        // the row is only part-way painted, so the phosphor has not emitted it
1968        // yet and the framebuffer still holds the previous frame there. (This
1969        // assertion read "light IS detected at row 0" until v2.3.6; sampling
1970        // rows the beam had not finished is what let the sensor report light on
1971        // a fully black screen, which made a Duck Hunt hit impossible. See
1972        // `aperture_is_bright_painted`.)
1973        assert_eq!(
1974            z.read_at_scanline(&fb, 0) & 0b0000_1000,
1975            0b0000_1000,
1976            "the aim row is still being painted at scanline == y: no light yet"
1977        );
1978
1979        // The first scanline PAST the aim row: the row is complete, the
1980        // photodiode is inside its hold window, so light IS detected. This is
1981        // the contrast the fallback below is measured against.
1982        assert_eq!(
1983            z.read_at_scanline(&fb, 1) & 0b0000_1000,
1984            0,
1985            "scanline 1 detects the light emitted by the completed row 0"
1986        );
1987
1988        // The real pre-render line (261 NTSC) is already no-light via the normal
1989        // path — it is past the hold window, so no fallback is needed there.
1990        assert_eq!(
1991            z.read_at_scanline(&fb, 261) & 0b0000_1000,
1992            0b0000_1000,
1993            "the real pre-render line (261) already reads no-light",
1994        );
1995
1996        // The negative-scanline fallback: no light regardless of framebuffer.
1997        assert_eq!(
1998            z.read_before_visible() & 0b0000_1000,
1999            0b0000_1000,
2000            "read_before_visible reports light NOT detected",
2001        );
2002        // ...and it still carries the trigger bit like every other read.
2003        assert_eq!(z.read_before_visible() & 0b0001_0000, 0b0001_0000);
2004    }
2005}