ActionReplay.java

/*
 * actionreplay.c - Cartridge handling, Action Replay cart.
 *
 * Written by
 *  Andreas Boose <viceteam@t-online.de>
 *
 * This file is part of VICE, the Versatile Commodore Emulator.
 * See README for copyright notice.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 *  02111-1307  USA.
 *
 */
package libsidplay.components.cart.supported;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;

import static java.nio.charset.StandardCharsets.US_ASCII;

import libsidplay.common.Event;
import libsidplay.components.cart.Cartridge;
import libsidplay.components.pla.Bank;
import libsidplay.components.pla.PLA;

/**
 * CRT 1: 32 KiB ROM and 8 KiB RAM (Action Replay 4.2/5/6).
 * Mode $22 uses VICE's OR approximation of system/cart RAM bus contention.
 * Reference: https://github.com/VICE-Team/svn-mirror/blob/main/vice/src/c64/cart/actionreplay.c
 */
public class ActionReplay extends Cartridge {

	boolean isActive;

	/**
	 * Currently active ROML bank.
	 */
	protected int currentRomBank;

	/**
	 * ROML banks 0..3 (each of size 0x2000).
	 */
	protected final byte[][] romLBanks;

	protected boolean exportRam;

	private int control;

	protected final byte[] ram = new byte[0x2000];

	public ActionReplay(final DataInputStream dis, final PLA pla) throws IOException {
		super(pla);
		romLBanks = new byte[4][0x2000];
		for (byte[] bank : romLBanks) Arrays.fill(bank, (byte) 0xff);
		final byte[] chipHeader = new byte[0x10];
		for (int i = 0; i < 4; i++) {
			int count = readChipHeader(dis, chipHeader);
			if (count == 0) throw new EOFException("Missing Action Replay CHIP record");
			if (count != chipHeader.length) throw new EOFException("Truncated Action Replay CHIP header");
			if (!"CHIP".equals(new String(chipHeader, 0, 4, US_ASCII))) {
				throw new IOException("Invalid Action Replay CHIP signature");
			}
			long length = (long) u16(chipHeader, 4) << 16 | u16(chipHeader, 6);
			int type = u16(chipHeader, 8);
			int bank = u16(chipHeader, 10);
			int size = u16(chipHeader, 14);
			// Banked hardware ignores the CHIP load-address metadata, as VICE does.
			if (length < chipHeader.length + size || (type != 0 && type != 2) || bank > 3 || size != 0x2000) {
				throw new IOException("Invalid Action Replay CHIP record");
			}
			try {
				dis.readFully(romLBanks[bank]);
			} catch (EOFException e) {
				throw new EOFException("Truncated Action Replay CHIP payload");
			}
			skipFully(dis, length - chipHeader.length - size, "Truncated Action Replay CHIP padding");
		}
		int trailing = readChipHeader(dis, chipHeader);
		if (trailing != 0) {
			if (trailing != chipHeader.length) throw new EOFException("Truncated Action Replay CHIP header");
			throw new IOException("Unexpected extra Action Replay CHIP record");
		}
	}

	private static int u16(byte[] bytes, int offset) {
		return (bytes[offset] & 255) << 8 | bytes[offset + 1] & 255;
	}

	private boolean contendedRam() { return (control & 0x23) == 0x22; }

	private void writeControl(byte value) {
		if (!isActive) return;
		control = value & 255;
		currentRomBank = control >> 3 & 3;
		exportRam = (control & 0x20) != 0;
		isActive = (control & 4) == 0;
		// The hooks must see the new state during the synchronous PLA rebuild.
		boolean contention = contendedRam();
		pla.setGameExrom(contention || (control & 1) == 0, !contention && (control & 2) != 0);
		if ((control & 0x40) != 0) setNMI(false);
	}

	protected final Bank io1Bank = new Bank() {
		@Override
		public byte read(int address) {
			byte value = pla.getDisconnectedBusBank().read(address);
			// R/W is not decoded: a floating IO1 read also clocks the register.
			writeControl(value);
			return value;
		}

		@Override
		public void write(int address, byte value) {
			writeControl(value);
		}
	};

	protected final Bank io2Bank = new Bank() {
		@Override
		public byte read(int address) {
			if (!isActive) {
				return pla.getDisconnectedBusBank().read(address);
			}
			if (exportRam) {
				return ram[address & 0x1fff];
			}

			return romLBanks[currentRomBank][address & 0x1fff];
		}

		@Override
		public void write(int address, byte value) {
			if (isActive) {
				if (exportRam) {
					ram[address & 0x1fff] = value;
				}
			}
		}
	};

	protected final Bank romlBank = new Bank() {
		@Override
		public byte read(int address) {
			if (exportRam) {
				return ram[address & 0x1fff];
			}

			return romLBanks[currentRomBank][address & 0x1fff];
		}

		@Override
		public void write(int address, byte value) {
			if (exportRam) {
				ram[address & 0x1fff] = value;
			}
		}
	};

	protected final Bank romhBank = new Bank() {
		@Override
		public byte read(int address) {
			return romLBanks[currentRomBank][address & 0x1fff];
		}

		@Override
		public void write(int address, byte value) {
		}
	};

	@Override
	public Bank getRomh() {
		return romhBank;
	}

	@Override
	public Bank getRoml() {
		return romlBank;
	}

	@Override
	public Bank getIO1() {
		return io1Bank;
	}

	@Override
	public Bank getIO2() {
		return io2Bank;
	}

	@Override
	public boolean isIO2ReadDriven(int address) { return isActive; }

	@Override
	public void reset() {
		pla.getCPU().getEventScheduler().cancel(newCartRomConfig);
		super.reset();
		isActive = true;
		io1Bank.write(0xde00, (byte) 0);
	}

	@Override
	public void installBankHooks(Bank[] cpuReadMap, Bank[] cpuWriteMap) {
		if (!exportRam) {
			return;
		}

		for (int i = 8; i < 10; i++) {
			final Bank origBank = cpuWriteMap[i];
			if (origBank == romlBank) {
				// Ultimax selects cartridge RAM only; system RAM is disconnected.
				continue;
			}
			if (contendedRam() && cpuReadMap[i] == romlBank) {
				cpuReadMap[i] = new Bank() {
					@Override public byte read(int address) {
						return (byte) (origBank.read(address) | ram[address & 0x1fff]);
					}
					@Override public void write(int address, byte value) { }
				};
			}

			cpuWriteMap[i] = new Bank() {
				@Override
				public void write(int address, byte value) {
					origBank.write(address, value);
					romlBank.write(address, value);
				}
			};
		}
	}

	private final Event newCartRomConfig = Event.of("ActionReplay freeze", event -> {
		isActive = true;
		io1Bank.write(0xde00, (byte) 0x23);
	});

	@Override
	public void doFreeze() {
		var scheduler = pla.getCPU().getEventScheduler();
		if (scheduler.isPending(newCartRomConfig)) return;
		setNMI(true);
		scheduler.schedule(newCartRomConfig, 3, Event.Phase.PHI1);
	}
}