# SPDX-License-Identifier: MIT """Save states (docs/save-states.md): a run saved between two 68000 steps and loaded into a fresh system continues exactly as the run that was never interrupted. No ROM is needed: ``tests/examples/`` holds two of the family's own programs (written by megadrive-rust's ``scripts/make_examples.py``, MIT). ``board-tour.bin`` sets the VDP up, runs a 68000-to-VRAM DMA, a VRAM fill and a copy, takes horizontal and vertical interrupts, loads a Z80 program that plays the YM2612 and the PSG through the bus request, and loops reading the HV counter and taking the Z80's bus; ``h32-sprites.bin`` moves sprites with shadow/highlight in H32. States are taken at step counts that fall inside lines, inside the VRAM fill, and with a Z80 instruction held part way by a bus request. Cartridges from a romset are checked by scripts/state_roundtrip.py. """ from __future__ import annotations from pathlib import Path import pytest from fake_devices import FakeAudio, FakeSavedDevice, FakeUnsavedDevice from megadrive_python import state from megadrive_python.cartridge import Cartridge from megadrive_python.io import Pad3, Pad6 from megadrive_python.machine import MACHINES from megadrive_python.system import System EXAMPLES = Path(__file__).parent / "examples" TOUR = (EXAMPLES / "board-tour.bin").read_bytes() SPRITES = (EXAMPLES / "h32-sprites.bin").read_bytes() def _system(image: bytes = TOUR, machine: str = "genesis", pad: type = Pad3) -> System: return System(MACHINES[machine], Cartridge(image), pads=(pad(), Pad3())) def _trail(system: System, steps: int) -> list[tuple]: out = [] for _ in range(steps): system.step() out.append( ( system.mclk, system.m68k.PC, system.z80_mclk, system.z80.pc, system.vdp.v, system.z80_instructions, ) ) out.append( ( bytes(system.board.ram), bytes(system.board.z80_ram), bytes(system.vdp.vram), list(system.vdp.cram), system.vdp.renderer.frame(), system.take_audio(), ) ) return out def _continues(image: bytes, at: int, then: int = 4000, **kwargs: object) -> tuple[System, System]: whole = _system(image, **kwargs) # type: ignore[arg-type] for _ in range(at): whole.step() data = state.save_state(whole) copy = _system(image, **kwargs) # type: ignore[arg-type] state.load_state(copy, data) assert state._body(copy) == state._body(whole), "the loaded state is not the saved one" assert _trail(copy, then) == _trail(whole, then) assert state._body(copy) == state._body(whole) return whole, copy @pytest.mark.parametrize("at", [0, 1, 187, 198, 1409, 5000, 23_456]) def test_a_state_continues_as_the_run(at: int) -> None: _continues(TOUR, at) def test_save_points_fall_where_they_should() -> None: """The step counts above do land mid-DMA and mid-instruction (board-tour.bin).""" system = _system() marks = {} for i in range(1, 1410): system.step() if i == 198: marks["fill"] = system.vdp.fill_running if i == 1409: marks["partial"] = system._z80_partial is not None assert marks == {"fill": True, "partial": True} def test_h32_sprites_on_a_pal_console_with_six_buttons() -> None: _whole, copy = _continues(SPRITES, 30_000, machine="megadrive", pad=Pad6) assert copy.vdp.pal and copy.vdp.hmode.name == "H32" def test_loaded_in_place() -> None: """The host's references -- a pad, the renderer -- stay the system's after a load.""" whole = _system(pad=Pad6) whole.board.io.ports[0].device.pressed = 0x50 for _ in range(900): whole.step() copy = _system(pad=Pad6) pad, renderer = copy.board.io.ports[0].device, copy.vdp.renderer state.load_state(copy, state.save_state(whole)) assert copy.board.io.ports[0].device is pad and pad.pressed == 0x50 assert copy.vdp.renderer is renderer assert copy.board.cartridge is copy.board.slot_cartridge def test_mismatches_are_refused_up_front() -> None: system = _system() for _ in range(100): system.step() data = state.save_state(system) with pytest.raises(state.StateError, match="not a megadrive-python"): state.load_state(_system(), b"garbage" + data) with pytest.raises(state.StateError, match="another cartridge"): state.load_state(_system(SPRITES), data) with pytest.raises(state.StateError, match="not the"): state.load_state(_system(machine="megadrive"), data) with pytest.raises(state.StateError, match="wired otherwise"): state.load_state(_system(pad=Pad6), data) bumped = data.replace(f'"version":{state.VERSION},'.encode(), b'"version":9,', 1) assert bumped != data with pytest.raises(state.StateError, match="version 9"): state.load_state(_system(), bumped) def test_a_damaged_body_changes_nothing() -> None: system = _system() for _ in range(300): system.step() data = state.save_state(system) target = _system() for _ in range(50): target.step() before = state._body(target) with pytest.raises(state.StateError): state.load_state(target, data[:-20]) assert state._body(target) == before def test_the_host_settings_stay_the_hosts() -> None: whole = _system() whole.audio.sample_rate = 22_050 data = state.save_state(whole) copy = _system() copy.audio.sample_rate = 48_000 copy.board.fm.enabled = False copy.vdp.rendering = False state.load_state(copy, data) assert copy.audio.sample_rate == 48_000 and copy.board.fm.enabled is False assert copy.vdp.rendering is False def test_a_second_load_of_one_state_gives_the_same_run() -> None: """Rewind's use: one state loaded again and again into the same system.""" system = _system() for _ in range(2000): system.step() data = state.save_state(system) first = _trail(system, 1500) state.load_state(system, data) assert _trail(system, 1500) == first def _configuration_digest() -> dict[str, str]: import hashlib return { label: hashlib.sha1(repr(obj).encode()).hexdigest() for label, obj in state._configuration().values() if type(obj) in (list, dict, set, bytearray) and not label.endswith("_vsync_cache") } @pytest.mark.parametrize("image", [TOUR, SPRITES], ids=["H40", "H32"]) def test_a_load_never_writes_configuration(image: bytes) -> None: """The VDP holds the line tables' slot lists themselves (``VDP.slots`` is ``H40.slots_active``): a load that wrote them by value would rewrite the table every console in the process shares (found 2026-11-23 on Super Street Fighter II, whose copy loaded in a fresh process parted from the run 50 frames on).""" whole = _system(image) for _ in range(7000): whole.step() data = state.save_state(whole) before = _configuration_digest() copy = _system(image) state.load_state(copy, data) assert _configuration_digest() == before assert any(copy.vdp.slots is value for _label, value in state._configuration().values()) # -- socket 10: a socket device's own state ----------------------------------------------- def _device_system( version: int = 1, cls: type = FakeSavedDevice, sound: bool = True ) -> tuple[System, FakeSavedDevice]: device = cls(Cartridge(TOUR)) if version != 1: device.state_version = version system = System(MACHINES["genesis"], None, slot=device, pads=(Pad3(), Pad3())) if sound: system.audio_sources.append(device.audio) return system, device def _chunks(system: System, chunks: int, steps: int = 700) -> list: """Steps in chunks, the host taking the sound after each (as a frontend does).""" out = [] for _ in range(chunks): for _ in range(steps): system.step() out.append((system.mclk, system.m68k.PC, system.take_audio())) return out def test_a_socket_device_saves_its_own_side() -> None: whole, device = _device_system() _chunks(whole, 4) device.clock_note = [1, 2] # an attribute added at run time is state too data = state.save_state(whole) header, _ = state.read_header(data) assert header["version"] == state.VERSION == 3 assert header["devices"] == {"slot": {"name": "fake_devices.FakeSavedDevice", "version": 1}} copy, fresh = _device_system() state.load_state(copy, data) assert fresh.loads == 1 assert copy.board.slot is fresh and copy.audio_sources == [fresh.audio] assert fresh.clock == device.clock and fresh.log == device.log assert fresh.catch_ups == device.catch_ups and fresh.clock_note == [1, 2] # Its held cartridge is the console's, by reference, not a copy. assert fresh.cartridge is copy.board.slot_cartridge is copy.board.game_cartridge assert state._body(copy) == state._body(whole) assert _chunks(copy, 6) == _chunks(whole, 6) assert state._body(copy) == state._body(whole) assert fresh.log == device.log and len(device.audio.calls) == 10 def test_the_further_sources_leftovers_survive_a_load() -> None: """Socket 8's pending samples and fractional position are the console's state: a load (a rewind, a run-ahead frame) continues the source's interpolation where it was, rather than restarting it from its next list.""" whole, _device = _device_system() _chunks(whole, 3) (record,) = whole.audio._sources assert record[1] and record[2] % 1.0 > 0.0 # samples pending, part way between two data = state.save_state(whole) copy, fresh = _device_system() state.load_state(copy, data) (loaded,) = copy.audio._sources assert loaded[0] is fresh.audio # found again by the loading console's own source assert loaded[1] == record[1] and loaded[2] == record[2] after = _chunks(whole, 3) assert _chunks(copy, 3) == after # Without them the sound parts from the run at once: the click per load. dropped, _ = _device_system() state.load_state(dropped, data) dropped.audio._sources.clear() assert _chunks(dropped, 3)[0][2] != after[0][2] def test_a_device_at_another_state_version_is_refused_before_anything() -> None: whole, _ = _device_system() _chunks(whole, 2) data = state.save_state(whole) target, device = _device_system(version=2) _chunks(target, 1) before = state._body(target) with pytest.raises(state.StateError, match="state version 1, not 2"): state.load_state(target, data) assert state._body(target) == before and device.loads == 0 # Another device, and no device, are other wiring. with pytest.raises(state.StateError, match="wired otherwise"): state.load_state(_system(), data) plain = state.save_state(_system()) with pytest.raises(state.StateError, match="wired otherwise"): state.load_state(_device_system()[0], plain) # A header naming a device version the body was not saved at. forged = data.replace(b'"version":1}', b'"version":7}', 1) assert forged != data with pytest.raises(state.StateError, match="state version 7, not 1"): state.load_state(_device_system()[0], forged) def test_a_device_without_the_socket_cannot_be_saved() -> None: system = System(MACHINES["genesis"], None, slot=FakeUnsavedDevice(Cartridge(TOUR))) with pytest.raises(state.StateError, match="offers no state"): state.save_state(system) def test_a_device_part_in_no_devices_value_is_refused() -> None: """A part of the device the console holds (here a second sound source) that the device's value does not hold would be loaded stale: the save refuses.""" system, _device = _device_system() system.audio_sources.append(FakeAudio(22_050.0, 1.0, (5.0, 5.0))) with pytest.raises(state.StateError, match="no device's state holds"): state.save_state(system) def test_a_device_that_refuses_its_value_changes_nothing() -> None: whole, _ = _device_system() _chunks(whole, 3) data = state.save_state(whole) target, device = _device_system() _chunks(target, 1) before = state._body(target) device.refuse = True with pytest.raises(state.StateError, match="refuses this value"): state.load_state(target, data) assert state._body(target) == before