# SPDX-License-Identifier: MIT """Run a Sega CD: ``python -m segacd_python --bios BIOS --frames N --png out.png``. ``--bios`` is your own BIOS image, or mcd-verificator (which stands in for one). ``--disc`` is a BIN/CUE image.""" from __future__ import annotations import argparse import sys import time from pathlib import Path from megadrive_python.cartridge import Cartridge, load_image from megadrive_python.io import BUTTONS from megadrive_python.machine import MACHINES from megadrive_python.png import write_png from megadrive_python.wav import write_wav from .console import build from .disc import Disc from .memory import formatted_backup_ram from .ramcart import RAMCartridge from .state import load_state, save_state def screen_text(system: object) -> list[str]: """Plane A read as text, for programs whose font tiles are their ASCII codes (mcd-verificator's are).""" vdp = system.vdp # type: ignore[attr-defined] base = (vdp.registers[2] & 0x38) << 10 width = (32, 64, 32, 128)[vdp.registers[16] & 3] lines = [] for row in range(28): text = "" for column in range(40): at = base + (row * width + column) * 2 tile = ((vdp.vram[at] << 8) | vdp.vram[at + 1]) & 0x7FF text += chr(tile) if 32 <= tile < 127 else " " lines.append(text.rstrip()) return lines def rows(system: object, picture: object | None) -> list[list[int]]: """The frame as rows of RGB: the console's own, or through the 32X's composite.""" frame = [list(row) for row in system.vdp.renderer.frame_rgb()] # type: ignore[attr-defined] return picture(frame) if picture is not None else frame # type: ignore[operator] def save(path: Path, system: object, frame: int) -> None: """The whole console as a save state (segacd_python.state), to go on from later (``--load-state``); the frame number is kept in it as the host's.""" path.write_bytes(save_state(system, {"frame": frame})) # type: ignore[arg-type] print(f"[state] saved {path} at frame {frame}", file=sys.stderr, flush=True) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--bios", type=Path, required=True) parser.add_argument("--machine", default="genesis", choices=sorted(MACHINES)) parser.add_argument("--cartridge", type=Path, help="a cartridge in the slot (mode 1)") parser.add_argument("--ram-cart", action="store_true", help="a RAM cartridge in the slot") parser.add_argument("--disc", type=Path, help="a .cue, or a zip of a CUE and its BINs") parser.add_argument("--disc-cache", type=Path, default=Path("runs/discs"), help="where a zipped disc is unpacked") # fmt: skip parser.add_argument("--with-32x", type=Path, metavar="BOOT_ROM_DIR", help="put a 32X (sega32x-python, if installed) in the slot") # fmt: skip parser.add_argument("--backup-ram", type=Path, help="the internal backup RAM's file: read if it exists (else the " "RAM starts formatted and empty), written at the end") # fmt: skip parser.add_argument("--blank-backup-ram", action="store_true", help="start with unformatted backup RAM, as a blank memory is") # fmt: skip parser.add_argument("--save-state", type=Path, help="write the whole console here at the end (a save state: " "docs/save-states.md)") # fmt: skip parser.add_argument("--save-every", type=int, default=0, help="also save SAVE-STATE.fNNNNN every N frames") # fmt: skip parser.add_argument("--load-state", type=Path, help="start from a save state; the console is first built from " "the same --bios, --disc, --cartridge, --ram-cart, --machine") # fmt: skip parser.add_argument("--frames", type=int, default=600, help="frames to run: from power-on, or after a loaded state's " "frame (a state saved at 450 with --frames 450 ends at 900)") # fmt: skip parser.add_argument("--png", type=Path, help="write the last frame here") parser.add_argument("--png-every", type=int, default=0, help="also write PNG-STEM.fNNNNN.png every N frames") # fmt: skip parser.add_argument("--wav", type=Path, help="write the sound here (16-bit stereo)") parser.add_argument("--fm", action="store_true", help="run the YM2612's generator too (slow; on with --wav)") # fmt: skip parser.add_argument("--press", default="", help="buttons to press (e.g. start)") parser.add_argument("--swap", action="append", default=[], metavar="DISC@FRAME", help="lift the lid at FRAME and close it on DISC (repeatable)") # fmt: skip parser.add_argument("--lid-open-for", type=int, default=120, help="frames the lid stays open") parser.add_argument("--press-at", default="", help="frames to press them at (e.g. 520,900)") parser.add_argument("--press-for", type=int, default=6, help="frames each press lasts") parser.add_argument("--text", action="store_true", help="print plane A as text") parser.add_argument("--report", type=int, default=0, help="print progress every N frames") args = parser.parse_args(argv) cartridge: object | None = None if args.cartridge: cartridge = Cartridge.from_image(load_image(args.cartridge)) elif args.ram_cart: cartridge = RAMCartridge() disc = Disc.open(args.disc, args.disc_cache) if args.disc else None slot = None picture = None if args.with_32x: from sega32x_python.bootrom import BootROMs from sega32x_python.composite import rectangle as picture from sega32x_python.slot import Sega32X slot = Sega32X(None, boot_roms=BootROMs.load(args.with_32x)) if slot is not None and args.save_state: # sega32x-python saves its SH-2 side its own way (its savestate.py), which this # board's states do not include (segacd_python.state refuses them). raise SystemExit("--save-state is not supported with --with-32x yet") if slot is not None and args.load_state: raise SystemExit("--load-state is not supported with --with-32x yet") first = 1 backup = None if args.blank_backup_ram else formatted_backup_ram() if args.backup_ram and args.backup_ram.exists(): backup = args.backup_ram.read_bytes() system, device = build( args.machine, args.bios.read_bytes(), cartridge, disc=disc, slot=slot, backup_ram=backup, ) # fmt: skip if slot is not None: system.attach_video_timing(slot) system.attach_picture(slot) system.audio_sources.append(slot.pwm) if args.load_state: # The state holds the backup RAM as it was; --backup-ram is still written at the end. saved = load_state(system, args.load_state.read_bytes()) first = saved["frame"] + 1 print(f"[state] loaded {args.load_state} at frame {saved['frame']}; running frames " f"{first}-{first + args.frames - 1}", file=sys.stderr) # fmt: skip system.board.fm.enabled = args.fm or bool(args.wav) audio: list[tuple[int, int]] = [] pad = system.board.io.ports[0].device pressed = 0 for name in (button.strip().lower() for button in args.press.split(",") if button.strip()): pressed |= BUTTONS[name] press_at = [int(frame) for frame in args.press_at.split(",") if frame] swaps: dict[int, Disc | str] = {} for swap in args.swap: path, _, at = swap.rpartition("@") swaps[int(at)] = "open" swaps[int(at) + args.lid_open_for] = Disc.open(Path(path), args.disc_cache) last = first + args.frames - 1 def drawn(frame: int) -> bool: """Only the frames written out are drawn: megadrive-python's drawing switch gates the pixels alone (its state version 2), so what software sees is the same. With a 32X in the slot every frame is drawn (its picture is laid over the console's).""" if slot is not None: return True every = bool(args.png_every) and frame % args.png_every == 0 return bool(args.png) and (frame == last or every) began = time.time() for frame in range(first, first + args.frames): system.vdp.undrawn_frame = not drawn(frame) if pressed and pad is not None: pad.pressed = pressed if any(0 <= frame - at < args.press_for for at in press_at) else 0 if frame in swaps: if swaps[frame] == "open": device.cdd.open_lid() else: device.cdd.close_lid(swaps[frame]) print(f"[frame {frame}] lid {device.cdd.phase}", file=sys.stderr, flush=True) system.run_frame() if args.wav: audio.extend(system.take_audio()) else: # Keep the sample queues from growing over a long run. system.board.fm.take_samples() system.board.psg.take_samples() for source in device.audio_sources: source.take_samples(system.mclk) if args.png and args.png_every and frame % args.png_every == 0: write_png(args.png.with_suffix(f".f{frame:05d}.png"), rows(system, picture)) if args.save_state and args.save_every and frame % args.save_every == 0: save(args.save_state.with_suffix(f".f{frame:05d}"), system, frame) if args.report and frame % args.report == 0: print(f"[frame {frame}] {time.time() - began:.1f} s, sub instructions " f"{device.sub_instructions:,}", file=sys.stderr, flush=True) # fmt: skip if args.text: print("\n".join(line for line in screen_text(system) if line), flush=True) if args.backup_ram: args.backup_ram.write_bytes(bytes(device.backup_ram.data)) if args.save_state: save(args.save_state, system, last) if args.wav: write_wav(args.wav, audio, system.audio.sample_rate) if args.png: write_png(args.png, rows(system, picture)) if args.text: print("\n".join(line for line in screen_text(system) if line)) return 0 if __name__ == "__main__": sys.exit(main())