VIC.java

/*
 * 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. For the full
 * license text, see http://www.gnu.org/licenses/gpl.html.
 */
package libsidplay.components.mos656x;

import libsidplay.common.Event;
import libsidplay.common.Event.Phase;
import libsidplay.common.EventScheduler;
import libsidplay.common.VICChipModel;
import libsidplay.components.pla.Bank;
import libsidplay.components.pla.PLA;
import sidplay.audio.VideoDriver;

import java.util.Arrays;

/**
 * Implements the functionality of the C64's VIC II chip
 * <p>
 * For good German documentation on the MOS 6567/6569 Videocontroller (VIC-II), see
 *
 * <pre>
 * <a href=
 * 'http://www.minet.uni-jena.de/~andreasg/c64/vic_artikel/vic_artikel_1.htm'>http://www.minet.uni-jena.de/~andreasg/c64/vic_artikel/vic_artikel_1.htm</a>,
 * <a href=
 * 'http://cbmmuseum.kuto.de/zusatz_6569_vic2.html'>http://cbmmuseum.kuto.de/zusatz_6569_vic2.html</a> or
 * <a href=
 * 'http://unusedino.de/ec64/technical/misc/vic656x/vic656x-german.html'>http://unusedino.de/ec64/technical/misc/vic656x/vic656x-german.html</a>.
 * An English version of the documentation you can find at
 * <a href=
 * 'http://www.unusedino.de/ec64/technical/misc/vic656x/vic656x.html'>http://www.unusedino.de/ec64/technical/misc/vic656x/vic656x.html</a>.
 * </pre>
 *
 * @author Jörg Jahnke (joergjahnke@users.sourceforge.net)
 * @author Antti S. Lankila (alankila@bel.fi)
 */
public abstract class VIC extends Bank {
    public static final int MAX_HEIGHT = 312;

    public static final int MAX_WIDTH = 48 * 8;

    /**
     * First line when we check for bad lines
     */
    protected static final int FIRST_DMA_LINE = 0x30;

    /**
     * Last line when we check for bad lines
     */
    protected static final int LAST_DMA_LINE = 0xf7;

    private static final byte COL_D021 = 0;
    private static final byte COL_D022 = 1;
    private static final byte COL_D023 = 2;
    // private static final byte COL_D024 = 3;
    private static final byte COL_CBUF = 4;
    private static final byte COL_CBUF_MC = 5;
    private static final byte COL_VBUF_L = 6;
    private static final byte COL_VBUF_H = 7;
    private static final byte COL_ECM = 8;
    private static final byte COL_NONE = 9;

    private static final byte[] videoModeColorDecoder = {COL_D021, COL_D021, COL_CBUF, COL_CBUF, /*
																									 * ECM=0 BMM=0 MCM=0
																									 */
            COL_D021, COL_D022, COL_D023, COL_CBUF_MC, /* ECM=0 BMM=0 MCM=1 */
            COL_VBUF_L, COL_VBUF_L, COL_VBUF_H, COL_VBUF_H, /* ECM=0 BMM=1 MCM=0 */
            COL_D021, COL_VBUF_H, COL_VBUF_L, COL_CBUF, /* ECM=0 BMM=1 MCM=1 */
            COL_ECM, COL_ECM, COL_CBUF, COL_CBUF, /* ECM=1 BMM=0 MCM=0 */
            COL_NONE, COL_NONE, COL_NONE, COL_NONE, /* ECM=1 BMM=0 MCM=1 */
            COL_NONE, COL_NONE, COL_NONE, COL_NONE, /* ECM=1 BMM=1 MCM=0 */
            COL_NONE, COL_NONE, COL_NONE, COL_NONE /* ECM=1 BMM=1 MCM=1 */
    };

    /* Current video mode */
    private int videoModeColorDecoderOffset;
    // Old PAL BMM falls at dot 5, old NTSC at dot 6. ECM falls at dot 6 on both.
    private final int bitmapModeFallPixel;
    // MOS8565 rises at dot 8 and retains falling bits through dot 0 of the next block.
    private boolean delayedVideoMode;
    // Deterministic DMA-delay idle address; MOS8562 retains the MOS6567R8 fallback.
    private int dmaDelayIdleAddress = 0x38ff;
    private int pendingD011Mode;
    /** D011 mode sampled after the preceding PHI1 access, before CPU PHI2 writes. */
    private int previousD011FetchMode;

    // D016 reaches the color decoder at dot 4, but the data sampler at dot 7.
    private int mcmShifter;
    // Bits left from the last character load; a D016 fine-scroll write can move the next load.
    private int graphicsShifterBits;

    /**
     * Current dynamic colors
     */
    private final byte[] videoModeColors = new byte[10];
    /**
     * Current border color
     */
    private int borderColor;

    // PAL and 65-cycle NTSC D021 writes reach pixel 0 one dot later than the other seven pixels.
    // CPU reads see the new register immediately. The 6569/6567 use the previous
    // color for that dot; MOS8565 and MOS8562 produce a grey dot instead.
    private long backgroundColorWriteCycle = Long.MIN_VALUE;
    private byte previousBackgroundColor;
    private boolean backgroundGreyDotBugEnabled;
    private int ecmColorSource = COL_D021;


    /**
     * Enable the PAL MOS8565 grey-dot artifact on D020/border writes.
     * D021/background writes use backgroundGreyDotBugEnabled for both MOS8565 and MOS8562.
     * Other color-register sources still need their own timing through the graphics and sprite pipelines.
     */
    private boolean greyDotBugEnabled;

    // D020 has the same one-dot color latency, applied only to a border pixel.
    private long borderColorWriteCycle = Long.MIN_VALUE;
    private byte previousBorderColor;

    /**
     * contains the memory fetch data
     */
    protected byte phi1Data;
    /**
     * Pixel color being rendered.
     */
    private int pixelColor;
    /**
     * multicolor flip-flop state
     */
    private boolean mcFlip;
    /**
     * xscroll-delayed phi1 data
     */
    private int phi1DataPipe;

    protected IPALEmulation palEmulation;

    /**
     * PLA chip
     */
    private final PLA pla;

    /**
     * Credits
     */
    private static final String credit = "MOS656X (cycle-exact VICII) Emulation:\n"
            + "\tCopyright (©) 2009 Jörg Jahnke <joergjahnke@users.sourceforge.net>\n"
            + "\tCopyright (©) 2010 Antti S. Lankila <alankila@bel.fi>\n";

    // graphic modes
    /**
     * raster IRQ flag
     */
    private final static byte IRQ_RASTER = 1;
    /**
     * sprite-background collision IRQ flag
     */
    protected final static byte IRQ_SPRITE_BACKGROUND_COLLISION = 2;
    /**
     * sprite-sprite collision IRQ flag
     */
    protected final static byte IRQ_SPRITE_SPRITE_COLLISION = 4;
    /**
     * Light-Pen IRQ flag
     */
    private final static byte MOS656X_INTERRUPT_LP = 1 << 3;

    /**
     * memory for chip registers
     */
    protected final byte[] registers = new byte[0x40];
    /**
     * video counter, a 10-bit counter
     */
    protected int vc;
    /**
     * video counter base, a 10-bit data register
     */
    protected int vcBase;
    /**
     * row counter, a 3-bit counter
     */
    protected int rc;
    /**
     * Is the graphics fetcher in display state rather than idle state?
     */
    protected boolean isDisplayActive;

    /**
     * Display state sampled by the previous PHI1 fetch. The decoder consumes that
     * access one cycle later, so a late badline must not advance its buffer index
     * while the graphics data still comes from an idle access.
     */
    protected boolean isDisplayActiveForGraphics;
    /**
     * are bad lines enabled for this frame?
     */
    protected boolean areBadLinesEnabled;
    /**
     * current raster line
     */
    protected int rasterY;
    /**
     * Is rasterYIRQ condition true?
     */
    protected boolean rasterYIRQCondition;
    /**
     * the 8 sprites
     */
    protected final Sprite[] sprites = new Sprite[8];
    /**
     * The head of a sprite linked list. The top is never rendered; it's just an anchor.
     */
    protected final Sprite spriteLinkedListHead = new Sprite(null, -1);
    /**
     * contains the color data of the current character
     */
    private final byte[] colorData = new byte[40];
    /**
     * contains the video matrix data for the current character
     */
    protected final byte[] videoMatrixData = new byte[40];
    /**
     * vertical border flip-flop
     */
    protected boolean showBorderVertical;
    /**
     * main border flip-flop
     */
    private boolean showBorderMain = true;
    /**
     * is the current line a bad line?
     */
    protected boolean isBadLine;
    /**
     * video matrix base address
     */
    protected int videoMatrixBase;
    /**
     * character memory base address
     */
    protected int charMemBase;
    /**
     * bitmap memory base address
     */
    protected int bitmapMemBase;
    /**
     * vertical scrolling value
     */
    private int yscroll;
    /**
     * horizontal scrolling value
     */
    protected byte xscroll;
    /**
     * xscroll value within window region text columns 1 .. 39
     */
    protected int latchedXscroll;
    /**
     * internal IRQ flags
     */
    private byte irqFlags;
    /**
     * masks for the IRQ flags
     */
    private byte irqMask;
    /** Last PAL D01E read; the clear pulse also discards the next twelve sprite pixels. */
    private long spriteCollisionReadCycle = Long.MIN_VALUE;

    /**
     * Current internal raster cycle (1-based).
     */
    protected int lineCycle;
    /**
     * Is display rendering enabled?
     */
    protected boolean graphicsRendering;

    /**
     * Return whether the graphics sequencer is enabled for the current raster line.
     * <p>
     * Most VIC models can use the vertical-border flip-flop directly. PAL overrides this because the graphics sequencer
     * enable is latched for a raster line and must not follow mid-line vertical-border changes.
     */
    protected boolean isGraphicsSequencerActive() {
        return !showBorderVertical;
    }

    /**
     * CPU's event context.
     */
    protected final EventScheduler context;
    /**
     * Light pen coordinates
     */
    private byte lpx, lpy;
    /** PHI2 trigger offset in the half-resolution lightpen X coordinate. */
    private int lightpenPhi2XOffset = 2;
    /**
     * Has light pen IRQ been triggered in this frame already?
     */
    protected boolean lpTriggered;
    /**
     * Set when a new frame starts.
     */
    protected boolean startOfFrame;
    /**
     * Number of cycles per line.
     */
    protected final int CYCLES_PER_LINE;
    /**
     * Number of raster lines
     */
    protected final int MAX_RASTERS;
    /**
     * Is CIA asserting lightpen?
     */
    private boolean lpAsserted;

    private byte latchedColor;

    private byte latchedVmd;

    /**
     * Display memory line index.
     * <p>
     * Unlike the raster-derived render cycle, this advances only while the graphics sequencer is in display state.
     */
    private int dmli;

    /**
     * Initialize a VIC core with the supplied raster timing.
     *
     * @param pla        PLA chip
     * @param context    CPU's event context.
     * @param cpl        cycles per line
     * @param maxRasters raster lines per frame
     */
    public VIC(PLA pla, final EventScheduler context, int cpl, int maxRasters) {
        this.pla = pla;
        this.context = context;

        CYCLES_PER_LINE = cpl;
        MAX_RASTERS = maxRasters;
        bitmapModeFallPixel = cpl == MOS6569.CYCLES_PER_LINE ? 20 : 24;

        for (int i = 0; i < sprites.length; i++) {
            sprites[i] = new Sprite(spriteLinkedListHead, i);
        }
    }

    /**
     * Consumer for VIC screen output as ARGB data
     */
    protected VideoDriver videoDriver = vic -> {
    };

    /**
     * Set consumer of VIC screen output as ARGB data
     *
     * @param videoDriver consumer of C64 screen pixels as ARGB data
     */
    public void setVideoDriver(VideoDriver videoDriver) {
        this.videoDriver = videoDriver;
    }

    /**
     * Read the x-coordinate of a sprite
     *
     * @param spriteNo no of the sprite (0-7)
     * @return x-coordinate
     */
    private int readSpriteXCoordinate(final int spriteNo) {
        return (registers[0x00 + (spriteNo << 1)] & 0xff) + ((registers[0x10] & 1 << spriteNo) != 0 ? 256 : 0);
    }

    /**
     * Read the RSEL flag which determines whether we display 24 or 25 lines of text
     *
     * @return true if RSEL is set and we use 25 lines, otherwise false
     */
    protected boolean readRSEL() {
        return (registers[0x11] & 8) != 0;
    }

    /**
     * Read the CSEL flag which determines whether we display 38 or 40 columns of text
     *
     * @return true if CSEL is set and we use 40 columns, otherwise false
     */
    private boolean readCSEL() {
        return (registers[0x16] & 8) != 0;
    }

    /**
     * Read the DEN flag which tells whether the display is enabled
     *
     * @return true if DEN is set, otherwise false
     */
    protected boolean readDEN() {
        return (registers[0x11] & 0x10) != 0;
    }

    /**
     * Read the value of the raster line IRQ
     *
     * @return raster line when to trigger an IRQ
     */
    protected int readRasterLineIRQ() {
        return (registers[0x12] & 0xff) + ((registers[0x11] & 0x80) << 1);
    }

    protected boolean evaluateIsBadLine() {
        return areBadLinesEnabled && rasterY >= FIRST_DMA_LINE && rasterY <= LAST_DMA_LINE && (rasterY & 7) == yscroll;
    }

    /**
     * Signal CPU interrupt if requested by VIC.
     */
    private void handleIrqState() {
        /* signal an IRQ unless we already signaled it */
        if ((irqFlags & irqMask & 0x0f) != 0) {
            if ((irqFlags & 0x80) == 0) {
                interrupt(true);
                irqFlags |= 0x80;
            }
        } else if ((irqFlags & 0x80) != 0) {
            interrupt(false);
            irqFlags &= 0x7f;
        }
    }

    /**
     * Get the video memory base address, which is determined by the inverted bits 0-1 of port A on CIA 2, plus the
     * video matrix base address plus the character data base address plus the bitmap memory base address.
     */
    private void determineVideoMemoryBaseAddresses() {
        videoMatrixBase = (registers[0x18] & 0xf0) << 6;
        charMemBase = (registers[0x18] & 0x0e) << 10;
        bitmapMemBase = (registers[0x18] & 0x08) << 10;
    }

    /**
     * Set an IRQ flag and trigger an IRQ if the corresponding IRQ mask is set. The IRQ only gets activated, i.e., flag
     * 0x80 gets set if it was not active before.
     */
    protected void activateIRQFlag(final byte flag) {
        irqFlags |= flag;
        handleIrqState();
    }

    /**
     * Read video matrix and color data for the next character
     */
    protected void doVideoMatrixAccess() {
        final int displayCycle = vc - vcBase & 0x3ff;

        if (displayCycle < 40) {
            final byte vmd = vicReadMemoryPHI2(videoMatrixBase | vc);
            final byte color = vicReadColorMemoryPHI2(vc);

            videoMatrixData[displayCycle] = vmd;
            colorData[displayCycle] = color;
        }
    }

    public int getVideoMatrixBase() {
        return videoMatrixBase;
    }

    /*
     * This table can be used to quadruple every bit, for instance,%1011 ->
     * %1111000011111111. Additionally, the inverse of input is stored on the high
     * pits, making the complete value %00001111000000001111000011111111.
     */
    protected static final int[] singleColorLUT = new int[16];

    /**
     * Expands eight single-color sprite bits into eight packed pixel masks.
     */
    protected static final int[] spriteSingleColorLUT = new int[256];

    static {
        for (int in = 0; in < 16; in++) {
            int out = 0;
            for (int b = 0; b < 4; b++) {
                if ((in & 1 << b) != 0) {
                    out |= 0xf << (b << 2);
                }
            }
            singleColorLUT[in] = out | (0xffff ^ out) << 16;
        }
        for (int in = 0; in < 256; in++) {
            spriteSingleColorLUT[in] = singleColorLUT[in >>> 4] << 16 | singleColorLUT[in & 0xf] & 0xffff;
        }
    }

    private int spriteCollisionMaskAfterRead() {
        if (spriteCollisionReadCycle == Long.MIN_VALUE) {
            return -1;
        }
        long cyclesAfterRead = context.getTime(Phase.PHI2) - spriteCollisionReadCycle;
        if (cyclesAfterRead == 1) {
            return 0;
        }
        // Packed pixels run from high to low nibble: retain pixels 4..7 of the second block.
        return cyclesAfterRead == 2 ? 0x0000ffff : -1;
    }

    /**
     * This monster method calculates:
     * <ul>
     * <li>graphics sequencer output,
     * <li>sprite sequencer output,
     * <li>border sequencer output
     * </ul>
     * and combines all of them.
     */
    protected void drawSpritesAndGraphics() {
        /* Current graphics fetch cycle number */
        int renderCycle = lineCycle - 26;
        if (renderCycle < 0) {
            renderCycle += CYCLES_PER_LINE;
        }

        /* Graphics sequencer foreground region. 0xf at slot when occupied. */
        int priorityData = 0;
        /* Graphics pixel data. */
        int graphicsDataBuffer = 0;
        boolean backgroundColorWrite = false;
        if (backgroundColorWriteCycle != Long.MIN_VALUE) {
            backgroundColorWrite = context.getTime(Phase.PHI2) == backgroundColorWriteCycle + 1;
            backgroundColorWriteCycle = Long.MIN_VALUE;
        }
        boolean borderColorWrite = false;
        if (borderColorWriteCycle != Long.MIN_VALUE) {
            borderColorWrite = context.getTime(Phase.PHI2) == borderColorWriteCycle + 1;
            borderColorWriteCycle = Long.MIN_VALUE;
        }
        int firstPixelColorSource = COL_NONE;
        final int mcm = (registers[0x16] & 0x10) >> 2;
        final boolean mcmTransition = mcm != mcmShifter;
        final int d011 = (registers[0x11] & 0x60) >> 2;
        final boolean d011Transition = d011 != (videoModeColorDecoderOffset & 0x18)
                || delayedVideoMode && pendingD011Mode != (videoModeColorDecoderOffset & 0x18);

        /* Render eight packed pixels, splitting at mode and fine-scroll edges. */
        for (int pixel = 0; pixel < 32; ) {
            /* Apply mode edges before XSCROLL loads and data sampling. */
            if (delayedVideoMode) {
                if (pixel == 4) {
                    videoModeColorDecoderOffset &= pendingD011Mode | ~0x18;
                }
            } else {
                if (pixel == 16) {
                    videoModeColorDecoderOffset |= d011;
                }
                if (pixel == bitmapModeFallPixel) {
                    videoModeColorDecoderOffset &= d011 | ~8;
                }
                if (pixel == 24) {
                    videoModeColorDecoderOffset &= d011 | ~16;
                }
            }
            if (pixel == 16) {
                videoModeColorDecoderOffset = videoModeColorDecoderOffset & ~4 | mcm;
            }

            if (pixel == 28 && mcmTransition) {
                // A rising MCM edge retains the preceding sample. XSCROLL=7 can
                // re-prime the sampler below, after this edge has reached it.
                if (mcmShifter == 0 && mcm != 0) {
                    mcFlip = false;
                }
                mcmShifter = mcm;
            }

            /* XScroll matched -> load new data. */
            if (pixel == latchedXscroll) {
                videoModeColors[COL_CBUF] = latchedColor;
                videoModeColors[COL_CBUF_MC] = (byte) (latchedColor & 0x7);
                videoModeColors[COL_VBUF_L] = (byte) (latchedVmd & 0xf);
                videoModeColors[COL_VBUF_H] = (byte) (latchedVmd >> 4 & 0xf);
                ecmColorSource = COL_D021 + (latchedVmd >> 6 & 0x3);
                videoModeColors[COL_ECM] = videoModeColors[ecmColorSource];

                mcFlip = true;
                graphicsShifterBits = 8;

                if (renderCycle == 0) {
                    dmli = 0;
                }

                if (renderCycle < 40 && isGraphicsSequencerActive()) {
                    if (isDisplayActiveForGraphics) {
                        final int displayIndex = dmli++;

                        latchedVmd = videoMatrixData[displayIndex];
                        latchedColor = colorData[displayIndex];
                    } else {
                        latchedVmd = 0;
                        latchedColor = 0;
                    }

                    phi1DataPipe ^= (phi1DataPipe ^ phi1Data << 16) & 0xff0000;
                }
            }

            /*
             * Split at the next four-pixel boundary, XSCROLL or mode edge.
             */
            int end = pixel + 16 & 0xf0;
            if (d011Transition) {
                if (delayedVideoMode) {
                    if (pixel < 4) {
                        end = Math.min(end, 4);
                    }
                } else {
                    if (pixel < bitmapModeFallPixel) {
                        end = Math.min(end, bitmapModeFallPixel);
                    }
                    if (pixel < 24) {
                        end = Math.min(end, 24);
                    }
                }
            }
            if (mcmTransition && pixel < 28) {
                end = Math.min(end, 28);
            }
            if (pixel < latchedXscroll) {
                end = Math.min(end, latchedXscroll);
            }

            // ECM affects color decoding, not the choice of hires or paired data.
            boolean multicolorCapable = (videoModeColorDecoderOffset & 8) != 0 || videoModeColors[COL_CBUF] >= 8;
            boolean multicolorData = mcmShifter != 0 && multicolorCapable;
            if (mcmTransition || d011Transition || multicolorData) {

                /*
                 * It would be great if the below expression could be SIMDified, but that has
                 * proven to be very challenging.
                 */
                while (pixel < end) {
                    /* The color decoder can already be multicolor while data is still hires. */
                    if (!multicolorData) {
                        pixelColor = (phi1DataPipe >>> 31) * (multicolorCapable ? 2 : 3);
                    } else if (mcFlip) {
                        pixelColor = phi1DataPipe >>> 30;
                        // The hardware's eight-bit shifter shifts in zero before
                        // XSCROLL reloads it. Do not pair its last bit with the
                        // next glyph already queued in our wider data pipe.
                        if (graphicsShifterBits == 1) {
                            pixelColor &= 2;
                        }
                    }
                    phi1DataPipe <<= 1;
                    graphicsShifterBits--;
                    mcFlip = !mcFlip;

                    graphicsDataBuffer <<= 4;
                    priorityData <<= 4;

                    /*
                     * Convert to one of the 9 possible values VIC can output at a time
                     */
                    int color = videoModeColorDecoder[videoModeColorDecoderOffset | pixelColor];
                    if (backgroundColorWrite && pixel == 0) {
                        firstPixelColorSource = color == COL_ECM ? ecmColorSource : color;
                    }
                    /* Convert to the final color index in the vic-ii palette. */
                    graphicsDataBuffer |= videoModeColors[color];
                    /* Separate data channel for sprite priority handling */
                    priorityData |= pixelColor > 1 ? 0xf : 0;

                    pixel += 4;
                }
            } else {
                int bits = end - pixel;
                /* Number of f's equals the number of pixels. */
                int mask = -1 >>> -bits;

                /* Extract bits of input */
                int inputBits = phi1DataPipe >>> (-bits >> 2);
                if (backgroundColorWrite && pixel == 0) {
                    int firstBit = inputBits >>> ((bits >> 2) - 1);
                    int color = videoModeColorDecoder[videoModeColorDecoderOffset | firstBit * 3];
                    firstPixelColorSource = color == COL_ECM ? ecmColorSource : color;
                }
                phi1DataPipe <<= bits >> 2;
                graphicsShifterBits -= bits >> 2;
                mcFlip ^= (bits & 4) != 0;

                int videoModeColorsSIMD = videoModeColors[videoModeColorDecoder[videoModeColorDecoderOffset]] << 16
                        | videoModeColors[videoModeColorDecoder[videoModeColorDecoderOffset | 3]] & 0xff;
                videoModeColorsSIMD |= videoModeColorsSIMD << 4;
                videoModeColorsSIMD |= videoModeColorsSIMD << 8;

                /* Get decoded value of 0xABCDabcd representing 4-bit input. */
                int priorityBits = singleColorLUT[inputBits];
                /* Generate BG and FG simultaneously. */
                int out = videoModeColorsSIMD & priorityBits;
                /* Merge */
                out |= out >>> 16;
                /* Place merged data where it is wanted. */
                graphicsDataBuffer <<= bits;
                graphicsDataBuffer |= out & mask;
                /* Separate data channel for sprite priority handling */
                priorityData <<= bits;
                priorityData |= priorityBits & mask;

                pixel = end;
            }
        }

        if (delayedVideoMode) {
            // Rising bits reach the decoder now; falling bits survive one more dot.
            videoModeColorDecoderOffset |= d011;
        }
        pendingD011Mode = d011;

        // Correct the graphics source before sprite priority and border masking.
        // Equal RGB values from color RAM, bitmap nibbles or sprites are unrelated.
        if (firstPixelColorSource == COL_D021) {
            int firstColor = backgroundGreyDotBugEnabled ? 0xf : previousBackgroundColor;
            graphicsDataBuffer = graphicsDataBuffer & 0x0fffffff | firstColor << 28;
        }

        /* Sprite sequencer */
        final int graphicsPixels = graphicsDataBuffer;
        final int spriteCollisionMask = spriteCollisionMaskAfterRead();
        int opaqueSpritePixels = 0;
        Sprite prev = spriteLinkedListHead;
        Sprite current = prev.nextVisibleSprite;
        long spriteCycle = CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE
                ? context.getTime(Phase.PHI2) : Long.MIN_VALUE;
        while (current != null) {
            int spriteForegroundMask = current.calculateNext8Pixels(spriteCycle);

            /* Handle sprite-bg collision */
            if ((spriteForegroundMask & priorityData) != 0) {
                if (registers[0x1f] == 0) {
                    activateIRQFlag(IRQ_SPRITE_BACKGROUND_COLLISION);
                }
                registers[0x1f] |= 1 << current.index;
            }

            final int spriteCollisionPixels = spriteForegroundMask & spriteCollisionMask;
            /*
             * Handle sprite-sprite collision. It's easy to detect that a collision
             * occurred, but hard to find which two sprites collided. For this purpose, we
             * store the sprite index which contributed a pixel into the low bits of a pixel
             * slot, and keep the 4th bit as a mask that we can use to reliably identify the
             * collision.
             */
            if ((opaqueSpritePixels & spriteCollisionPixels) != 0) {
                if (registers[0x1e] == 0) {
                    activateIRQFlag(IRQ_SPRITE_SPRITE_COLLISION);
                }
                registers[0x1e] |= 1 << current.index;

                for (int pixel = 0; pixel < 32; pixel += 4) {
                    /* non-transparent from us? */
                    if ((spriteCollisionPixels >> pixel & 0xf) == 0) {
                        continue;
                    }
                    /* non-transparent from others? */
                    int otherSprite = opaqueSpritePixels >> pixel & 0xf;
                    if (otherSprite == 0) {
                        /* no pixel set at that slot? Set ourselves */
                        opaqueSpritePixels |= (current.index | 8) << pixel;
                    } else {
                        /*
                         * Collision; register the other sprite as colliding, but keep the old value, as
                         * it doesn't matter whether it contains the other or ourselves: both collision
                         * bits are set on 0x1e once we finish.
                         */
                        registers[0x1e] |= 1 << (otherSprite & 0x7);
                    }
                }
            } else {
                opaqueSpritePixels |= current.indexBits & spriteCollisionPixels;
            }

            final int priorityMask = current.getNextPriorityMask();
            // A winning sprite behind foreground still hides sprites underneath it.
            final int selectedPixels = graphicsPixels ^ (current.colorBuffer ^ graphicsPixels)
                    & (~priorityData | priorityMask);
            graphicsDataBuffer ^= (selectedPixels ^ graphicsDataBuffer) & spriteForegroundMask;

            /* exhausted this sprite's data? */
            if (current.consuming) {
                prev = current;
            } else {
                prev.nextVisibleSprite = current.nextVisibleSprite;
            }

            current = current.nextVisibleSprite;
        }

        /* Border unit */
        boolean firstPixelUsesD020 = false;

        // Both horizontal comparators see CSEL from the latest CPU write.
        final boolean csel = readCSEL();
        final boolean rightBorder38 = renderCycle == 39 && !csel;
        final boolean rightBorder40 = renderCycle == 40 && csel;

        if ((renderCycle == 1 && !csel) || rightBorder38) {
            if (showBorderMain) {
                graphicsDataBuffer ^= (graphicsDataBuffer ^ borderColor) & 0xfffffff0;
                firstPixelUsesD020 = true;
            }

            // A left-edge match may clear the main flip-flop, but a vertical
            // border must not set it. Only the right-edge match sets it.
            if (rightBorder38) {
                showBorderMain = true;
            } else if (!showBorderVertical) {
                showBorderMain = false;
            }

            if (showBorderMain) {
                graphicsDataBuffer ^= (graphicsDataBuffer ^ borderColor) & 0x0000000f;
            }
        } else {
            if (showBorderMain) {
                graphicsDataBuffer = borderColor;
                firstPixelUsesD020 = true;
            }

            if (rightBorder40) {
                showBorderMain = true;
            } else if (renderCycle == 0 && csel && !showBorderVertical) {
                showBorderMain = false;
            }
        }

        if (borderColorWrite && firstPixelUsesD020) {
            int firstColor = greyDotBugEnabled ? 0xf : previousBorderColor;
            graphicsDataBuffer = graphicsDataBuffer & 0x0fffffff | firstColor << 28;
        }
        if (palEmulation != PALEmulation.NONE && rasterY < getRasterYMax()) {
            /* Pixels arrive in 0x12345678 order. */
            palEmulation.drawPixels(graphicsDataBuffer);
        }
    }

    /**
     * This version just detects sprite-sprite collisions. It is appropriate to use outside the renderable screen, where
     * the graphics sequencer is known to have quiesced.
     */
    protected final void spriteCollisionsOnly() {
        // Mode writes outside the viewport must not become fresh edges on re-entry.
        int d011 = (registers[0x11] & 0x60) >> 2;
        if (delayedVideoMode) {
            videoModeColorDecoderOffset = videoModeColorDecoderOffset & (pendingD011Mode | ~0x18) | d011;
        } else {
            videoModeColorDecoderOffset = videoModeColorDecoderOffset & ~0x18 | d011;
        }
        pendingD011Mode = d011;
        mcmShifter = (registers[0x16] & 0x10) >> 2;
        videoModeColorDecoderOffset = videoModeColorDecoderOffset & ~4 | mcmShifter;
        graphicsShifterBits = 0;
        final int spriteCollisionMask = spriteCollisionMaskAfterRead();
        int opaqueSpritePixels = 0;

        Sprite prev = spriteLinkedListHead;
        Sprite current = prev.nextVisibleSprite;

        while (current != null) {
            int spriteCollisionPixels = current.calculateNext8Pixels() & spriteCollisionMask;
            if ((opaqueSpritePixels & spriteCollisionPixels) != 0) {
                if (registers[0x1e] == 0) {
                    activateIRQFlag(IRQ_SPRITE_SPRITE_COLLISION);
                }
                registers[0x1e] |= 1 << current.index;

                for (int pixel = 0; pixel < 32; pixel += 4) {
                    if ((spriteCollisionPixels >> pixel & 1) == 0) {
                        continue;
                    }
                    int otherSprite = opaqueSpritePixels >> pixel & 0xf;
                    if (otherSprite == 0) {
                        opaqueSpritePixels |= (current.index | 8) << pixel;
                    } else {
                        registers[0x1e] |= 1 << (otherSprite & 0x7);
                    }
                }
            } else {
                opaqueSpritePixels |= current.indexBits & spriteCollisionPixels;
            }

            if (current.consuming) {
                prev = current;
            } else {
                prev.nextVisibleSprite = current.nextVisibleSprite;
            }

            current = current.nextVisibleSprite;
        }
    }

    /**
     * In certain cases, CPU sees the stale bus data from VIC. VIC reads on every cycle, and this describes what it
     * reads.
     */
    public final byte getLastReadByte() {
        return phi1Data;
    }

    /** X coordinate at the beginning of a sprite's pointer/DMA0 fetch. */
    private int spriteFetchX(final int n) {
        return ((CYCLES_PER_LINE + getFirstSpriteFetchCycle() - 23) << 3) + (n << 4);
    }

    /**
     * Latch the sprite pointer fetched on PHI1 and fetch its first DMA byte on PHI2.
     *
     * @param n sprite number
     */
    protected void fetchSpritePointer(final int n) {
        Sprite sprite = sprites[n];

        /*
         * The sprite pointer is fetched regardless of whether sprite DMA is
         * active.
         */
        sprite.setPointerByte(phi1Data);
        final int x = sprite.getX();
        final int fetchX = spriteFetchX(n);

        /*
         * A newly asserted display bit has not reached the comparator
         * early enough for sprite 0. Other sprites may already
         * use the idle pattern before their own fetch takes place.
         */
        if (!sprite.isDisplayPending() && x >= fetchX && x <= fetchX + 7) {
            sprite.event();
        }
        if (CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE) {
            sprite.beginFetchHalt(phi1Data);
        } else {
            sprite.beginFetchHalt();
        }

        sprite.setSpriteByte(2, fetchSpriteDataPHI2(sprite));
    }

    /**
     * Latch the PHI1 sprite byte and fetch the final DMA byte on PHI2.
     *
     * @param n sprite number
     */
    protected void fetchSpriteData(final int n) {
        Sprite sprite = sprites[n];

        /*
         * DMA1 was fetched on PHI1. Without DMA, phi1Data contains idle data.
         */
        sprite.setSpriteByte(1, phi1Data);

        /*
         * DMA2 only performs a memory access and advances MC while DMA is active.
         */
        sprite.setSpriteByte(0, fetchSpriteDataPHI2(sprite));

        /*
         * DMA2 has completed. Comparator matches are possible again after
         * the damaged fetch window.
         */
        sprite.endFetchHalt();

        final int x = sprite.getX();
        if (x == spriteFetchX(n) + 15) {
            sprite.event();
        } else {
            handleSpriteVisibilityEvent(sprite);
        }
    }

    private byte fetchSpriteDataPHI2(final Sprite sprite) {
        if (sprite.isDMA()) {
            return vicReadMemoryPHI2(sprite.getCurrentByteAddress());
        }
        return (byte) 0xff;
    }

    /**
     * Read VIC register.
     *
     * @param register Register to read.
     */
    @Override
    public final byte read(int register) {
        register &= 0x3f;

        final byte value;
        switch (register) {
            // control register 1
            case 0x11: {
                value = (byte) (registers[register] & 0x7f | (rasterY & 0x100) >> 1);
                break;
            }

            // Raster Counter
            case 0x12:
                value = (byte) rasterY;
                break;

            case 0x13:
                value = lpx;
                break;

            case 0x14:
                value = lpy;
                break;

            // Unconnected bits of control register 2 read high.
            case 0x16:
                value = (byte) (registers[register] | 0xc0);
                break;

            // The unused memory-pointer bit reads high.
            case 0x18:
                value = (byte) (registers[register] | 0x01);
                break;

            case 0x19:
                // Interrupt Pending Register
                value = (byte) (irqFlags | 0x70);
                break;

            case 0x1a:
                // Interrupt Mask Register
                value = (byte) (irqMask | 0xf0);
                break;

            case 0x1e:
            case 0x1f: {
                // clear sprite collision registers after read
                final byte result = registers[register];
                registers[register] = 0;
                if (register == 0x1e && CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE) {
                    spriteCollisionReadCycle = context.getTime(Phase.PHI2);
                }
                value = result;
                break;
            }

            // for addresses < $20 read from register directly, when < $2f set
            // bits of high nibble to 1, for >= $2f return $ff
            default:
                if (register < 0x20) {
                    value = registers[register];
                } else if (register < 0x2f) {
                    value = (byte) (registers[register] | 0xf0);
                } else {
                    value = (byte) 0xff;
                }
        }

        setSpriteDataFromCPU(value);
        return value;
    }

    /**
     * Display is enabled because badline condition was on for at least 1 clock
     */
    private final Event makeDisplayActive = Event.of("Activate display due to badline",
            event -> isDisplayActive = true);

    /**
     * AEC state was updated.
     */
    private final Event badLineStateChange = Event.of("Update AEC signal", event -> setBA(!isBadLine));

    /**
     * RasterY IRQ edge detector.
     */
    protected final Event rasterYIRQEdgeDetector = Event.of("RasterY changed", event -> {
        final boolean oldRasterYIRQCondition = rasterYIRQCondition;
        rasterYIRQCondition = rasterY == readRasterLineIRQ();
        if (!oldRasterYIRQCondition && rasterYIRQCondition) {
            activateIRQFlag(IRQ_RASTER);
        }
    });

    /**
     * Handle lightpen state change
     */
    protected void lightpenEdgeDetector() {
        if (rasterY != MAX_RASTERS - 1) {
            if (!lpAsserted) {
                return;
            }

            if (lpTriggered) {
                return;
            }
            lpTriggered = true;

            lpx = (byte) getCurrentSpriteCycle();
            lpx++;
            if (lpx == CYCLES_PER_LINE) {
                lpx = 0;
            }

            lpx <<= 2;
            lpx += context.phase() == Phase.PHI1 ? 1 : lightpenPhi2XOffset;

            lpy = (byte) (rasterY & 0xff);
            if (lineCycle == 9) {
                lpy++;
            }

            activateIRQFlag(MOS656X_INTERRUPT_LP);
        }
    }

    /**
     * Write to VIC register.
     *
     * @param register Register to write to.
     * @param data     Data byte to write.
     */
    @Override
    public final void write(int register, final byte data) {
        register &= 0x3f;

        final byte oldData = registers[register];
        // Collision latches are read-only; RMW writes must not restore cleared flags.
        if (register != 0x1e && register != 0x1f) {
            registers[register] = data;
        }

        setSpriteDataFromCPU(data);

        switch (register) {
            // x-coordinate of a spriteID has been modified
            case 0x00:
            case 0x02:
            case 0x04:
            case 0x06:
            case 0x08:
            case 0x0a:
            case 0x0c:
            case 0x0e: {
                // determine sprite to modify
                final int n = register >> 1;
                sprites[n].setX(readSpriteXCoordinate(n));
                handleSpriteVisibilityEvent(sprites[n]);
                break;
            }

            // y-coordinate of a spriteID has been modified
            case 0x01:
            case 0x03:
            case 0x05:
            case 0x07:
            case 0x09:
            case 0x0b:
            case 0x0d:
            case 0x0f:
                sprites[register >> 1].setY(data & 0xff);
                break;

            case 0x10: {
                // bit 9 of a sprite x-coordinate has been modified
                //  to recalculate all sprite x-coordinates
                for (int i = 0; i < 8; i++) {
                    sprites[i].setX(readSpriteXCoordinate(i));
                    handleSpriteVisibilityEvent(sprites[i]);
                }
                break;
            }

            case 0x11:
                // the graphics mode might have changed plus y-scroll value
                yscroll = data & 7;

                /* display enabled at any cycle of line 48 enables badlines */
                if (rasterY == FIRST_DMA_LINE) {
                    areBadLinesEnabled |= readDEN();
                }

                /*
                 * lineCycle 9 corresponds to PAL cycle 63. At this point no more
                 * PHI1 cycle exists for the current raster line. DEN may still
                 * enable badlines for following raster lines, but YSCROLL must not
                 * change the badline state of the line that is just ending.
                 */
                if (lineCycle != 9) {
                    final int narrowing = readRSEL() ? 0 : 4;
                    if (rasterY == FIRST_DMA_LINE + 3 + narrowing && readDEN()) {
                        showBorderVertical = false;
                    }
                    if (rasterY == LAST_DMA_LINE + 4 - narrowing) {
                        showBorderVertical = true;
                    }

                    final boolean oldBadLine = isBadLine;
                    isBadLine = evaluateIsBadLine();

                    if (!oldBadLine && isBadLine) {
                        context.schedule(makeDisplayActive, 1, Phase.PHI2);
                    }

                    if (isBadLine ^ oldBadLine && lineCycle > 20 && lineCycle < 63) {
                        context.schedule(badLineStateChange, 0, Phase.PHI1);
                    }
                }
                // $FALL-THROUGH$

            case 0x12:
                /* check raster Y irq condition changes at the next PHI1 */
                context.schedule(rasterYIRQEdgeDetector, 0, Phase.PHI1);
                break;

            // the sprite enable byte has changed
            case 0x15:
                for (int i = 0; i < 8; i++) {
                    sprites[i].setEnabled((data & 1 << i) != 0);
                }
                break;

            case 0x16: {
                /* Blank the pixels left side of the character in buffer2. */
                xscroll = (byte) (registers[0x16] & 7);
                int renderCycle = lineCycle - 26;
                if (renderCycle < 0) {
                    renderCycle += CYCLES_PER_LINE;
                }
                /* the xscroll adjustment is not seen on the last cycle. */
                if (renderCycle != 39) {
                    latchedXscroll = xscroll << 2;
                }
                break;
            }

            // the sprite y-expansion byte has changed
            case 0x17: {
                /*
                 * Writing the identical value does nothing. If any D017 bit changes,
                 * however, all sprites whose new expansion bit is clear participate
                 * in expansion-flipflop handling.
                 */
                if (oldData != data) {
                    for (int i = 0; i < 8; i++) {
                        final boolean expandY = (data & 1 << i) != 0;
                        sprites[i].setExpandY(expandY, lineCycle == 24);
                    }
                }
                break;
            }
            // the cached video memory base addresses might have changed
            case 0x18:
                determineVideoMemoryBaseAddresses();
                break;

            // VIC Interrupt Flag Register
            case 0x19:
                irqFlags &= ~data & 0x0f | 0x80;
                handleIrqState();
                break;

            // IRQ Mask Register
            case 0x1a:
                irqMask = (byte) (data & 0x0f);
                handleIrqState();
                break;

            // the sprite priority byte has changed
            case 0x1b: {
                for (int i = 0, m = 1; i < 8; i++, m <<= 1) {
                    this.sprites[i].setPriorityOverForegroundGraphics((data & m) == 0);
                }
                break;
            }

            // Sprites O-7 Multi-Color Mode Selection
            case 0x1c:
                for (int i = 0, m = 1; i < 8; ++i, m <<= 1) {
                    this.sprites[i].setMulticolor((data & m) != 0);
                }
                break;

            // the sprite x-expansion byte has changed
            case 0x1d: {
                for (int i = 0, m = 1; i < 8; i++, m <<= 1) {
                    this.sprites[i].setExpandX((data & m) != 0);
                }
                break;
            }

            // the border color was changed
            case 0x20:
                if (CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE
                        || CYCLES_PER_LINE == MOS6567.CYCLES_PER_LINE || this instanceof MOS6567R56A) {
                    previousBorderColor = (byte) (borderColor & 0xf);
                    borderColorWriteCycle = context.getTime(Phase.PHI2);
                }
                borderColor = (data & 0xf) * 0x11111111;
                break;

            // store color in internal registers
            case 0x21:
            case 0x22:
            case 0x23:
            case 0x24: {
                final int n = register - 0x21;
                if (register == 0x21 && (CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE
                        || CYCLES_PER_LINE == MOS6567.CYCLES_PER_LINE || this instanceof MOS6567R56A)) {
                    previousBackgroundColor = videoModeColors[COL_D021];
                    backgroundColorWriteCycle = context.getTime(Phase.PHI2);
                }
                videoModeColors[n] = (byte) (data & 0xf);
                // ECM latches the register selection at X scroll, not its color value.
                if (n == ecmColorSource) {
                    videoModeColors[COL_ECM] = videoModeColors[n];
                }
                break;
            }

            case 0x25:
                // sprite color one has been changed
                for (int i = 0; i < 8; i++) {
                    writeSpriteColor(sprites[i], 1, data & 0xf);
                }
                registers[register] |= 0xf0;
                break;

            case 0x26:
                // sprite color three has been changed
                for (int i = 0; i < 8; i++) {
                    writeSpriteColor(sprites[i], 3, data & 0xf);
                }
                registers[register] |= 0xf0;
                break;
            case 0x27:
            case 0x28:
            case 0x29:
            case 0x2a:
            case 0x2b:
            case 0x2c:
            case 0x2d:
            case 0x2e:
                // sprite color two has been changed, this can be done per sprite
                writeSpriteColor(sprites[register - 0x27], 2, data & 0xf);
                this.registers[register] |= 0xf0;
                break;
        }
    }

    private void writeSpriteColor(Sprite sprite, int color, int value) {
        if (CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE) {
            sprite.writeColor(color, value, context.getTime(Phase.PHI2));
        } else {
            sprite.setColor(color, value);
        }
    }

    /**
     * If CPU reads/writes to VIC at just the cycle VIC is supposed to do a PHI2 fetch for sprite data, the data fetched
     * is set from the interaction with CPU.
     *
     * @param data The {@link Sprite} data to set.
     */
    private void setSpriteDataFromCPU(byte data) {
        final int fetchCycle = lineCycle - getFirstSpriteFetchCycle();
        if (fetchCycle >= 0 && fetchCycle < 16) {
            Sprite damagedSprite = sprites[fetchCycle >> 1];
            damagedSprite.setSpriteByte((fetchCycle & 1) == 0 ? 2 : 0, data);
        }
    }

    /** Internal cycle of sprite 0's pointer/DMA0 fetch; DMA2 follows one cycle later. */
    protected abstract int getFirstSpriteFetchCycle();

    private int getCurrentSpriteCycle() {
        int spriteCoordinate = lineCycle - 23;
        if (spriteCoordinate < 0) {
            spriteCoordinate += CYCLES_PER_LINE;
        }
        return spriteCoordinate;
    }

    /**
     * Schedule the rendering to begin
     *
     * @param sprite The {@link Sprite} to handle the visibility event of.
     */
    private void handleSpriteVisibilityEvent(final Sprite sprite) {
        /* New coordinate in a pipeline: cancel any pending event... */
        context.cancel(sprite);

        /* vic sprite x coordinate comparison will never trigger */
        if (sprite.getX() >> 3 >= CYCLES_PER_LINE) {
            return;
        }

        final int xpos = sprite.getX() >> 3;

        /* calculate cycles until sprite can display */
        int count = xpos - getCurrentSpriteCycle();
        /*
         * Wrap to the nearest CYCLE when comparison matches.
         *
         * VICE test spritex proves that setting location very near will not work: it
         * takes one cycle for VIC to adjust to the new sprite position.
         */
        if (count <= 0) {
            count += CYCLES_PER_LINE;
        }
        if (count > CYCLES_PER_LINE) {
            count -= CYCLES_PER_LINE;
        }

        /* Delay sprite by 0 .. 7 pixels. */
        sprite.setDisplayStart(sprite.getX() & 7);
        context.schedule(sprite, count, Event.Phase.PHI2);
    }

    /**
     * Resets this VIC II Chip.
     */
    public void reset() {
        spriteLinkedListHead.nextVisibleSprite = null;
        for (final Sprite s : sprites) {
            context.cancel(s);
            s.reset();
        }
        if (palEmulation != PALEmulation.NONE) {
            palEmulation.reset();
            palEmulation.updatePalette();
        }
        graphicsRendering = false;
        dmli = 0;
        spriteCollisionReadCycle = Long.MIN_VALUE;
        borderColorWriteCycle = Long.MIN_VALUE;
        previousBorderColor = 0;
        backgroundColorWriteCycle = Long.MIN_VALUE;
        previousBackgroundColor = 0;
        ecmColorSource = COL_D021;
        mcmShifter = 0;
        graphicsShifterBits = 0;
        videoModeColorDecoderOffset = 0;
        pendingD011Mode = 0;
        previousD011FetchMode = 0;
        pixelColor = 0;
        mcFlip = false;

        // reset all registers
        Arrays.fill(registers, (byte) 0);
        vc = 0;
        vcBase = 0;
        rc = 0;
        isBadLine = false;
        isDisplayActive = false;
        isDisplayActiveForGraphics = false;
        areBadLinesEnabled = false;
        rasterY = 0;
        phi1Data = 0;
        showBorderVertical = true;
        showBorderMain = true;
        xscroll = 0;
        yscroll = 0;
        irqFlags = 0;
        irqMask = 0;
        lpx = 0;
        lpy = 0;
        determineVideoMemoryBaseAddresses();
    }

    /**
     * Gets the credit string.
     *
     * @return The credit string.
     */
    public static String credits() {
        return credit;
    }

    /**
     * PAL emulation
     */
    public IPALEmulation getPalEmulation() {
        return palEmulation;
    }

    public void setPalEmulation(IPALEmulation palEmulation) {
        this.palEmulation = palEmulation;
    }


    /**
     * Select MOS8565/MOS8562 D021 grey dots. D020 grey dots and MOS8565
     * sprite-mode timing are enabled only on the PAL core.
     *
     * @param enabled true for the selected chip's implemented grey-dot behavior
     */
    public void setGreyDotBugEnabled(boolean enabled) {
        greyDotBugEnabled = enabled && CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE;
        backgroundGreyDotBugEnabled = enabled;
        for (Sprite sprite : sprites) {
            sprite.setMos8565(enabled && CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE);
        }
    }

    /**
     * Select D011 decoder and graphics-fetch timing independently of machine preset and palette.
     * MOS8565 delays graphics-fetch mode selection by one PHI1 cycle and its decoder
     * rises at dot 8 and falls at dot 9. DMA delay reads $3807 on MOS8565,
     * using the documented deterministic profile rather than temperature-dependent
     * variants. Other chips read $38ff; the NTSC identities retain
     * the MOS6567R8 timing fallback, including MOS8562.
     *
     * @param model resolved VIC chip identity
     */
    public void setVideoModeTiming(VICChipModel model) {
        boolean mos8565 = model == VICChipModel.MOS8565
                && CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE;
        delayedVideoMode = mos8565;
        dmaDelayIdleAddress = mos8565 ? 0x3807 : 0x38ff;
    }

    /**
     * Select the implemented lightpen trigger timing independently of rendering.
     * MOS8565 latches one lightpen X unit earlier on PHI2. PHI1 frame-start
     * retriggers keep their existing offset, as do the NTSC models.
     *
     * @param model resolved VIC chip identity
     */
    public void setLightpenTiming(VICChipModel model) {
        lightpenPhi2XOffset = model == VICChipModel.MOS8565
                && CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE ? 1 : 2;
    }

    /**
     * Trigger the lightpen. Sets the lightpen usage flag.
     */
    public void triggerLightpen() {
        lpAsserted = true;
        lightpenEdgeDetector();
    }

    /**
     * Clears the lightpen usage flag.
     */
    public void clearLightpen() {
        lpAsserted = false;
    }

    protected void interrupt(boolean b) {
        pla.setIRQ(b);
    }

    protected void setBA(boolean b) {
        pla.setBA(b);
    }

    protected void setBA(boolean b, boolean lateSpriteDma) {
        pla.setBA(b, lateSpriteDma);
    }

    protected byte vicReadColorMemoryPHI2(int address) {
        return pla.vicReadColorMemoryPHI2(address);
    }

    /** Construct an address without performing a bus access or advancing VC. */
    private int graphicsAddress(int mode, int matrixIndex) {
        int address = (mode & 0x20) != 0 ? bitmapMemBase | vc << 3 | rc
                : charMemBase | (videoMatrixData[matrixIndex] & 0xff) << 3 | rc;
        return (mode & 0x40) != 0 ? address & 0x39ff : address;
    }

    /**
     * Select the PHI1 graphics address using the configured chip's mode latches.
     * Older chips enter bitmap mode immediately and retain it for one cycle on exit.
     * PAL holds ECM on a falling edge; NTSC text holds it on a rising edge.
     * 65-cycle NTSC ECM-text to bitmap entry uses the live ECM sample; keeping
     * the old mask corrupts the first bitmap byte in historical videomode-v.
     * The 64-cycle NTSC fallback retains its previous combined-mode sample.
     * On a RAM-to-character-ROM BMM transition, the low address byte still comes
     * from the previous mode, while the upper address bits use the current mode.
     * See VICE's viciisc/vicii-fetch.c, vicii_fetch_graphics.
     */
    protected final int graphicsFetchAddress(int matrixIndex) {
        int liveMode = registers[0x11] & 0x60;
        if (delayedVideoMode) {
            return graphicsAddress(previousD011FetchMode, matrixIndex);
        }
        int ecm = liveMode & 0x40;
        if (CYCLES_PER_LINE == MOS6569.CYCLES_PER_LINE) {
            ecm |= previousD011FetchMode & 0x40;
        } else if (CYCLES_PER_LINE == MOS6567R56A.CYCLES_PER_LINE
                && previousD011FetchMode == 0x40 && liveMode == 0x20) {
            ecm = 0x40;
        } else if (((liveMode | previousD011FetchMode) & 0x20) == 0) {
            ecm &= previousD011FetchMode;
        }
        // Keep A9/A10 until the selected ECM sample is applied to the final address.
        int address = graphicsAddress((liveMode | previousD011FetchMode) & 0x20, matrixIndex);
        if (((liveMode ^ previousD011FetchMode) & 0x20) != 0) {
            int from = graphicsAddress(previousD011FetchMode, matrixIndex);
            int to = graphicsAddress(liveMode, matrixIndex);
            if (!pla.isCharacterRomPHI1(from) && pla.isCharacterRomPHI1(to)) {
                address = from & 0xff | to & 0x3f00;
            }
        }
        return ecm != 0 ? address & 0x39ff : address;
    }

    /**
     * A late badline changes the idle byte for the PHI1 access before the pending
     * PHI2 display activation. Normal graphics-idle accesses use ECM; ordinary
     * idle and sprite accesses do not. See VICE bug #1855 and vsp-tester/readme.txt.
     */
    protected final int graphicsIdleFetchAddress() {
        if (isBadLine && !isDisplayActive) {
            return dmaDelayIdleAddress;
        }
        int mode = delayedVideoMode ? previousD011FetchMode : registers[0x11];
        return (mode & 0x40) != 0 ? 0x39ff : 0x3fff;
    }

    /** Sample every PHI1 cycle, including sprite, refresh and hidden cycles. */
    protected final void latchD011FetchMode() {
        previousD011FetchMode = registers[0x11] & 0x60;
    }

    protected byte vicReadMemoryPHI1(int address) {
        return pla.vicReadMemoryPHI1(address);
    }

    protected byte vicReadMemoryPHI2(int address) {
        return pla.vicReadMemoryPHI2(address);
    }

    public int getBorderWidth() {
        return (40 + 4 + 4) << 3;
    }

    public final int getCyclesPerLine() {
        return CYCLES_PER_LINE;
    }

    public final int getCyclesPerFrame() {
        return CYCLES_PER_LINE * MAX_RASTERS;
    }

    public abstract int getBorderHeight();

    public abstract int getRasterYMax();

    public byte[] getRegisters() {
        return registers;
    }

}