MagicDesk.java

package libsidplay.components.cart.supported;

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

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

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

/**
 * <PRE>
 *     "Magic Desk" Cartridge (CRT type 19)
 *
 *     - 32KiB to 1MiB, in 4 to 128 banks of 8KiB.
 *     - ROM is always mapped in at $8000-$9FFF.
 *     - Unconnected bank address lines mirror smaller ROM capacities.
 *
 *     - One write-only register throughout IO1 ($DE00-$DEFF):
 *
 *     bit 0-6   bank number
 *     bit 7     exrom (1 = cart disabled, 0 = enabled)
 * </PRE>
 *
 * @author Ken Händel
 *
 */
public class MagicDesk extends Cartridge {

	private static final int BANK_SIZE = 0x2000;
	private static final int BANK_COUNT = 128;

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

	/**
	 * ROML banks 0..127 (each of size 0x2000), with absent banks filled with FF.
	 */
	protected final byte[][] romLBanks;

	private final int bankMask;

	private final boolean starTreuDetector;

	public MagicDesk(final DataInputStream dis, final PLA pla) throws IOException {
		super(pla);
		romLBanks = new byte[BANK_COUNT][BANK_SIZE];
		for (byte[] bank : romLBanks) {
			Arrays.fill(bank, (byte) 0xff);
		}
		bankMask = load(dis);
		// Bank 11, $9700-$97b8: recognise the detector before changing its fallback ID.
		CRC32 crc = new CRC32();
		crc.update(romLBanks[11], 0x1700, 0xb9);
		starTreuDetector = bankMask == 31 && crc.getValue() == 0x7f48b710L;
	}

	/**
	 * Select StarTreu's existing x64sc version for its recognised timing detector.
	 * Our REU implementation returns detector ID 2, which the demo treats as x64.
	 * Only the in-memory ROM changes; disabling the option restores the original byte.
	 * Returns whether the recognised workaround is active, so a bundled REU can
	 * also enable the VICE DMA handoff used by the following portrait effect.
	 * See https://csdb.dk/release/?id=256789 (Ciccioriccio's production notes).
	 */
	public boolean setStarTreuWorkaround(boolean enable) {
		if (starTreuDetector) romLBanks[11][0x1790] = (byte) (enable ? 1 : 2);
		return starTreuDetector && enable;
	}

	private int load(DataInputStream input) throws IOException {
		byte[] header = new byte[16];
		int highestBank = 0;
		int headerLength;
		while ((headerLength = readChipHeader(input, header)) != 0) {
			if (headerLength != header.length) {
				throw new EOFException("Truncated Magic Desk CHIP header");
			}
			if (!"CHIP".equals(new String(header, 0, 4, US_ASCII))) {
				throw new IOException("Invalid Magic Desk CHIP signature");
			}
			long packetLength = (long) u16(header, 4) << 16 | u16(header, 6);
			int type = u16(header, 8);
			int bank = u16(header, 10);
			int address = u16(header, 12);
			int size = u16(header, 14);
			if (packetLength < header.length + size || (type != 0 && type != 2)
					|| bank >= BANK_COUNT || (address != 0x8000 && address != 0xa000) || size != BANK_SIZE) {
				throw new IOException("Invalid Magic Desk CHIP record");
			}
			try {
				input.readFully(romLBanks[bank]);
			} catch (EOFException e) {
				throw new EOFException("Truncated Magic Desk CHIP payload");
			}
			skipFully(input, packetLength - header.length - size, "Truncated Magic Desk CHIP padding");
			highestBank = Math.max(highestBank, bank);
		}
		// CRT records do not declare ROM capacity; round up to 4, 8, ..., 128 banks.
		int mask = 3;
		while (mask < highestBank) {
			mask = (mask << 1) | 1;
		}
		return mask;
	}

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

	private final Bank io1Bank = new Bank() {
		@Override
		public byte read(int address) {
			return pla.getDisconnectedBusBank().read(address);
		}

		@Override
		public void write(int address, byte value) {
			currentRomBank = value & bankMask;
			pla.setGameExrom(true, (value & 0x80) != 0);
		}
	};

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

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

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

	@Override
	public void reset() {
		super.reset();
		io1Bank.write(0xde00, (byte) 0x00);
	}

}