MOS6569.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.components.pla.PLA;

/**
 * PAL specialization of the VIC
 */
public final class MOS6569 extends VIC {

    public static final int CYCLES_PER_LINE = 63;
    public static final int MAX_RASTERS = 312;

    public MOS6569(PLA pla, EventScheduler context) {
        super(pla, context, CYCLES_PER_LINE, MAX_RASTERS);
    }

    // Normal PAL viewport, matching VICE: raster lines 16 through 287.
    // The raster engine still runs all 312 lines, including the hidden borders.
    private static final int FIRST_DISPLAY_LINE = 16;
    private static final int LAST_DISPLAY_LINE = 288;
    public static final int BORDER_HEIGHT = LAST_DISPLAY_LINE - FIRST_DISPLAY_LINE;

    @Override
    protected int getFirstSpriteFetchCycle() {
        return 4;
    }

    private void doPHI1Fetch() {
        switch (lineCycle) {
            case 2:
            case 3:
                /* idle gap accesses are cycles outside screen region */
                phi1Data = vicReadMemoryPHI1(0x3fff);
                return;

            case 4:
            case 6:
            case 8:
            case 10:
            case 12:
            case 14:
            case 16:
            case 18: {
                /* sprite data pointer byte */
                final int n = lineCycle - 4 >> 1;
                phi1Data = vicReadMemoryPHI1(videoMatrixBase | 0x03f8 | n);
                return;
            }

            case 5:
            case 7:
            case 9:
            case 11:
            case 13:
            case 15:
            case 17:
            case 19: {
                int n = lineCycle - 5 >> 1;
                if (sprites[n].isDMA()) {
                    int address = sprites[n].getCurrentByteAddress();
                    phi1Data = vicReadMemoryPHI1(address);
                } else {
                    phi1Data = vicReadMemoryPHI1(0x3fff);
                }
                return;
            }

            default: {
                /* 1, 25-63 */
                int address = graphicsIdleFetchAddress();
                if (isDisplayActive) {
                    // Late badlines leave the buffer index behind the raster column.
                    // Use the same column as the paired matrix/color c-access.
                    final int n = vc - vcBase & 0x3ff;
                    address = graphicsFetchAddress(n);
                    vc = vc + 1 & 0x3ff;
                }

                phi1Data = vicReadMemoryPHI1(address);
                return;
            }

            case 20:
            case 21:
            case 22:
            case 23:
            case 24: {
                /* dram refresh. */
                final int n = lineCycle - 20;
                final int offset = 0xff - rasterY * 5 - n & 0xff;
                phi1Data = vicReadMemoryPHI1(0x3f00 | offset);
            }
        }
    }

    /*
     * The PAL VIC-II decides whether the graphics sequencer runs for a raster
     * line independently from later changes of the vertical border flip-flop.
     *
     * In particular, D011 border tricks may change showBorderVertical in the
     * middle of a line. That must affect the border unit, but it must not stop
     * (or start) the graphics sequencer halfway through that line.
     */
    private boolean graphicsSequencerActive;

    @Override
    protected boolean isGraphicsSequencerActive() {
        return graphicsSequencerActive;
    }

    private final Event event = Event.of("MOS6569", event -> {
        if (lineCycle == CYCLES_PER_LINE) {
            lineCycle = 0;
        }
        lineCycle++;

        if (graphicsRendering && (lineCycle >= 23 || lineCycle < 71 - CYCLES_PER_LINE)) {
            drawSpritesAndGraphics();
        } else {
            spriteCollisionsOnly();
        }

        // Latch after rendering: its next cycle consumes this PHI1 access.
        isDisplayActiveForGraphics = isDisplayActive;
        doPHI1Fetch();
        latchD011FetchMode();

        switch (lineCycle) {

            case 1: {
                /* PAL: graphics 39 access */
                boolean sprite0WasDma = sprites[0].isDMA();
                for (final Sprite sprite : sprites) {
                    if (sprite.isEnabled() && sprite.getY() == (rasterY & 0xff)) {
                        sprite.beginDMA();
                    }
                }

                setBA(!sprites[0].isDMA(), !sprite0WasDma && sprites[0].isDMA());
                break;
            }

            case 2:
                /* idle gap access */
                for (final Sprite sprite : sprites) {
                    if (sprite.isEnabled() && sprite.getY() == (rasterY & 0xff)) {
                        sprite.beginDMA();
                    }
                    sprite.expandYFlipFlop();
                }

                setBA(!sprites[0].isDMA());
                break;

            case 3:
                /* idle gap access */
                setBA(!sprites[0].isDMA() && !sprites[1].isDMA());
                break;

            case 4:
                /* sprite 0 pointer access */
                if (rc == 7) {
                    vcBase = vc;
                    isDisplayActive = isBadLine;
                }
                if (isDisplayActive) {
                    rc = rc + 1 & 7;
                }


                for (final Sprite sprite : sprites) {
                    if (sprite.isEnabled() && sprite.getY() == (rasterY & 0xff)) {
                        sprite.setDisplay(true);
                    }
                    if (!sprite.isDMA()) {
                        sprite.setDisplay(false);
                    }

                    sprite.initDmaAccess();
                }
                fetchSpritePointer(0);
                // already done: setBA(!sprites[0].isDMA() &&
                // !sprites[1].isDMA());
                break;

            case 5:
                /*
                 * Both edges of the cycle-58 sprite display check have now
                 * passed the pixel-4 latch. All subsequent X comparisons use
                 * the newly sampled display state.
                 */
                for (final Sprite sprite : sprites) {
                    sprite.commitDisplayLatch();
                }
                /* sprite 0 data access */
                fetchSpriteData(0);
                setBA(!sprites[0].isDMA() && !sprites[1].isDMA() && !sprites[2].isDMA());
                break;

            case 6:
                /* sprite 1 pointer access */
                fetchSpritePointer(1);
                setBA(!sprites[1].isDMA() && !sprites[2].isDMA());
                break;

            case 7:
                /* sprite 1 data access */
                fetchSpriteData(1);
                setBA(!sprites[1].isDMA() && !sprites[2].isDMA() && !sprites[3].isDMA());
                break;

            case 8:
                /* sprite 2 pointer access */
                fetchSpritePointer(2);
                setBA(!sprites[2].isDMA() && !sprites[3].isDMA());
                break;

            case 9:
                /* sprite 2 data access */
                fetchSpriteData(2);
                setBA(!sprites[2].isDMA() && !sprites[3].isDMA() && !sprites[4].isDMA());
                break;

            case 10: {
                if (rasterY == MAX_RASTERS - 1) {
                    vcBase = 0;
                    /*
                     * the last line is 1 cycle longer than it appears to be. To set rasterY = 0 the next
                     * cycle, we use a flag.
                     */
                    startOfFrame = true;
                } else {
                    rasterY++;
                    rasterYIRQEdgeDetector.event();
                }

                // to increase raster counter
                /*
                 * since raster Y just changed, we need to find out if we have entered a
                 * badline. the CPU can change the conditions any time, but since here VIC
                 * changes the raster, we *must* check badline on this cycle. In particular,
                 * linecrunch depends on canceling the bad line between cycles 10 - 24.
                 */
                if (rasterY == FIRST_DMA_LINE) {
                    areBadLinesEnabled = readDEN();
                }

                /*
                 * mysteriously, isDisplayActive is determined already on this cycle. Normally
                 * it takes 1 clock to take effect.
                 */
                isBadLine = evaluateIsBadLine();
                isDisplayActive |= isBadLine;

                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;
                }

                /*
                 * Latch graphics-sequencer enable once per raster line.  Keep this
                 * separate from showBorderVertical: writes to D011 later in the line
                 * are allowed to manipulate the border without changing sequencer state.
                 */
                graphicsSequencerActive = !showBorderVertical;

                latchedXscroll = xscroll << 2;
                if (palEmulation != PALEmulation.NONE) {
                    palEmulation.determineCurrentPalette(rasterY, rasterY == FIRST_DISPLAY_LINE);
                }
                if (rasterY == FIRST_DISPLAY_LINE) {
                    graphicsRendering = true;
                }

                if (rasterY == LAST_DISPLAY_LINE + 1) {
                    graphicsRendering = false;
                    videoDriver.accept(MOS6569.this);
                }

                // reset collision pointer to the first pixel in line
                fetchSpritePointer(3);

                setBA(!sprites[3].isDMA() && !sprites[4].isDMA());
                break;
            }

            case 11: {
                /* sprite 3 data access */
                if (startOfFrame) {
                    startOfFrame = false;
                    rasterY = 0;
                    rasterYIRQEdgeDetector.event();
                    lpTriggered = false;
                    lightpenEdgeDetector();
                }

                setBA(!sprites[3].isDMA() && !sprites[4].isDMA() && !sprites[5].isDMA());
                fetchSpriteData(3);
                break;
            }

            case 12:
                /* sprite 4 pointer access */
                fetchSpritePointer(4);
                setBA(!sprites[4].isDMA() && !sprites[5].isDMA());
                break;

            case 13:
                /* sprite 4 data access */
                fetchSpriteData(4);
                setBA(!sprites[4].isDMA() && !sprites[5].isDMA() && !sprites[6].isDMA());
                break;

            case 14:
                /* sprite 5 pointer access */
                fetchSpritePointer(5);
                setBA(!sprites[5].isDMA() && !sprites[6].isDMA());
                break;

            case 15:
                /* sprite 5 data access */
                fetchSpriteData(5);
                setBA(!sprites[5].isDMA() && !sprites[6].isDMA() && !sprites[7].isDMA());
                break;

            case 16:
                /* sprite 6 pointer & data data access */
                fetchSpritePointer(6);
                setBA(!sprites[6].isDMA() && !sprites[7].isDMA());
                break;

            case 17:
                /* sprite 6 data access */
                fetchSpriteData(6);
                break;

            case 18:
                /* sprite 7 pointer access */
                fetchSpritePointer(7);
                setBA(!sprites[7].isDMA());
                break;

            case 19:
                /* sprite 7 data access */
                fetchSpriteData(7);
                break;

            case 20:
                /* dram refresh 0 cycle */
                setBA(true);
                break;

            case 21:
                /* dram refresh 1 */
                setBA(!isBadLine);
                break;

            case 22:
                /* dram refresh 2 */
                break;

            case 23:
                /* dram refresh 3 */
                vc = vcBase;
                if (isBadLine) {
                    rc = 0;
                }
                break;

            case 24:
                /* dram refresh 4 */
                if (isBadLine) {
                    doVideoMatrixAccess();
                }
                break;

            case 25:
                /* graphics memory access 0 */
                if (isBadLine) {
                    doVideoMatrixAccess();
                }

                for (final Sprite sprite : sprites) {
                    if (sprite.isDMA()) {
                        sprite.finishDmaAccess();
                    }
                }
                break;

            default:
                /* graphics memory access */
                if (isBadLine) {
                    doVideoMatrixAccess();
                }
                break;

        }
        context.schedule(event, 1);
    });

    @Override
    public void reset() {
        super.reset();
        graphicsSequencerActive = false;
        lineCycle = 9; // preincremented at event
        context.schedule(event, 0, Phase.PHI1);
    }

    @Override
    public int getBorderHeight() {
        return BORDER_HEIGHT;
    }

    @Override
    public int getRasterYMax() {
        return LAST_DISPLAY_LINE;
    }
}