Sprite.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;

/**
 * Sprite class to handle all data for sprites.
 *
 * @author Jörg Jahnke (joergjahnke@users.sourceforge.net)
 * @author Antti S. Lankila (alankila@bel.fi)
 */
public final class Sprite extends Event {

    /**
     * Sprite index
     */
    final int index;

    /**
     * MOS656X instance this sprite belongs to
     */
    private final Sprite linkedListHead;

    /**
     * Visible sprites in a linked list; highest priority sprite first
     */
    Sprite nextVisibleSprite;

    @Override
    public void event() {
        /* already being displayed? ignore event */
        if (consuming) {
            return;
        }

        /*
         * Both edges of the display check reach the X comparator at pixel 4.
         * Earlier comparisons still use the previous latched display state.
         */
        if (!(delayPixels < 4 ? displayLatched : display)) {
            return;
        }

        /*
         * Sprite DMA0/DMA2 blocks the X comparator independently of
         * whether the pixel sequencer is currently active.
         */
        if (fetchHalt) {
            return;
        }

        consuming = true;
        fetchDamagePixel = -1;
        int delayLength = delayPixels;

        if (expandX) {
            firstXRead = (delayLength & 1) == 0;
            delayLength >>= 1;
        } else {
            firstXRead = true;
        }

        if (multiColor) {
            firstMultiColorRead = (delayLength & 1) == 0;
        } else {
            firstMultiColorRead = true;
        }

        consumedLineData = lineData << 8 - delayLength;
        lineData = 0;

        prevColorIndex = 0;
        prevPixel = 0;
        prevPriority = 0;
        expandXLatched = expandX;
        multiColorLatched = multiColor;
        priorityMask = priorityOverForegroundGraphics ? 0xffffffff : 0;

        /* put ourselves in the appropriate place in the sprite linked list */
        Sprite current = linkedListHead;
        /* we are already being rendered? Don't reschedule, or it will jam. */
        while (true) {
            /* find a place to tuck ourselves in */
            if (current.nextVisibleSprite == null || current.nextVisibleSprite.index < index) {
                Sprite.this.nextVisibleSprite = current.nextVisibleSprite;
                current.nextVisibleSprite = Sprite.this;
                break;
            }

            current = current.nextVisibleSprite;
        }
    }

    public Sprite(final Sprite linkedListHead, final int index) {
        super("Sprite " + index);
        this.linkedListHead = linkedListHead;
        this.index = index;
        this.indexBits = (8 | index) * 0x11111111;
    }

    /**
     * Position sprite start within character cell
     */
    private int delayPixels;

    /**
     * Delay sprite data appearance by given count of pixels.
     *
     * @param delayPixels number of pixels to delay sprite data appearance by.
     */
    void setDisplayStart(final int delayPixels) {
        this.delayPixels = delayPixels;
    }

    /**
     * Display state sampled by the raster's sprite display check.
     */
    private boolean display;

    /**
     * Previous display state, used by X comparisons before the pixel-4 latch.
     */
    private boolean displayLatched;

    /**
     * Is sprite pixel pipeline active?
     */
    boolean consuming;

    /**
     * Sprite X-comparator halt caused by the sprite fetch.
     * <p>
     * Unlike fetchDamagePixel this state also exists when the sprite pixel pipeline is not currently active.
     */
    private boolean fetchHalt;

    /**
     * Position inside the damaged sprite-fetch region.
     * <p>
     * -1 means normal sprite sequencer operation.
     * <p>
     * During sprite DMA0 the pixel sequencer is halted after pixel 2. The pixel generated there is repeated through
     * pixel 9. At pixel 10 the currently active sprite pipeline is cut.
     */
    private int fetchDamagePixel = -1;
    /** PAL pointer-bus bit racing the last multicolor sample; -1 retains the NTSC path. */
    private int fetchBusBit = -1;
    /**
     * This is the first read of multicolor pixel? (consuming read)
     */
    private boolean firstMultiColorRead;
    /**
     * 32 bits of sprite data in reversed bit order (LSB = first out)
     */
    private int lineData;
    /**
     * Sprite address byte
     */
    private byte pointerByte;
    /**
     * Data byte to fetch next
     */
    private int mcBase = 63;
    /**
     * Data byte at DMA
     */
    private int mc;
    /**
     * This is the first read of a line for a Y-expanded sprite? (no pointer increment)
     */
    private boolean firstYRead;
    /**
     * This is the first read of a pixel for an X-expanded sprite? (consuming read)
     */
    private boolean firstXRead;

    /**
     * Sprite position
     */
    private int x, y;
    /**
     * Is the sprite current enabled?
     */
    private boolean enabled;
    /**
     * Is the sprite expanded horizontally?
     */
    private boolean expandX;
    /**
     * Is the sprite expanded vertically?
     */
    private boolean expandY;
    /**
     * Multicolor mode on?
     */
    private boolean multiColor;
    /**
     * Does the sprite have priority over the screen background?
     */
    private boolean priorityOverForegroundGraphics;
    /**
     * The masking to be used for migrating color 1 as foreground color during sprite priority bit handling
     */
    private int priorityMask;

    /**
     * Get the X-coordinate of the sprite
     *
     * @return X-coordinate
     */
    public int getX() {
        return x;
    }

    /**
     * Set the X-coordinate of the sprite
     *
     * @param x new X-coordinate
     */
    public void setX(final int x) {
        this.x = x;
    }

    /**
     * Get the Y-coordinate of the sprite
     *
     * @return Y-coordinate
     */
    public int getY() {
        return y;
    }

    /**
     * Set the Y-coordinate of the sprite
     *
     * @param y new Y-coordinate
     */
    public void setY(final int y) {
        this.y = y;
    }

    /**
     * Set whether the sprite has priority over the screen background
     *
     * @param priority true if the sprite has priority over the screen content
     */
    public void setPriorityOverForegroundGraphics(final boolean priority) {
        if (priority == priorityOverForegroundGraphics) {
            return;
        }

        priorityOverForegroundGraphics = priority;

        /*
         * D01B is sampled at pixel 6 of an 8-pixel block.
         * Pixels 0..5 retain the old priority, pixels 6..7
         * use the new one.
         */
        priorityMask = priorityOverForegroundGraphics
                ? 0x000000ff
                : 0xffffff00;
    }

    public int getNextPriorityMask() {
        final int mask = priorityMask;

        /*
         * After the transition block the new state applies
         * to the complete following blocks.
         */
        priorityMask = priorityOverForegroundGraphics
                ? 0xffffffff
                : 0;

        return mask;
    }

    /**
     * Check whether the sprite is currently enabled
     *
     * @return true if enabled
     */
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Set whether the sprite is currently enabled
     *
     * @param enabled true if enabled
     */
    public void setEnabled(final boolean enabled) {
        this.enabled = enabled;
    }

    /**
     * Set expandX flag for horizontal expansion
     *
     * @param expandX true if expanded
     */
    public void setExpandX(final boolean expandX) {
        this.expandX = expandX;
    }

    /**
     * Set expandY flag for vertical expansion
     *
     * @param expandY     true if expanded
     * @param crunchCycle whether to do sprite crunch
     */
    public void setExpandY(final boolean expandY, final boolean crunchCycle) {
        this.expandY = expandY;

        /*
         * Clearing the D017 bit sets the internal expansion flip-flop.
         * This is write-sensitive, not edge-sensitive: even an already clear
         * sprite bit participates when another D017 bit changes.
         */
        if (!expandY && firstYRead) {
            if (crunchCycle) {
                mc = 0x2a & mc & mcBase | 0x15 & (mc | mcBase);
            }
            firstYRead = false;
        }
    }

    /**
     * Change the multicolor flag.
     *
     * @param multiColor true if multicolor
     */
    public void setMulticolor(final boolean multiColor) {
        this.multiColor = multiColor;
    }

    /**
     * Reset current DMA byte and expansion/multicolor flip-flops.
     */
    public void beginDMA() {
        if (isDMA()) {
            return;
        }
        mcBase = 0;
        firstYRead = false;
    }

    public boolean isDMA() {
        return mcBase != 63;
    }

    public void setDisplay(final boolean display) {
        this.display = display;
    }

    /** Whether activation is still pending for the pointer-fetch comparison. */
    public boolean isDisplayPending() {
        return display && !displayLatched;
    }

    public void commitDisplayLatch() {
        displayLatched = display;
    }

    /**
     * Set the address we read the sprite data from
     *
     * @param pointerByte address to read from
     */
    public void setPointerByte(final byte pointerByte) {
        this.pointerByte = pointerByte;
    }

    public int getCurrentByteAddress() {
        final int pointer = (pointerByte & 0xff) << 6;
        int address = pointer | mc;
        mc = mc + 1 & 0x3f;
        return address;
    }

    /**
     * Store a sprite byte into a sprite shift register for use.
     */
    public void setSpriteByte(int idx, byte value) {
        lineData &= ~(0xff << (idx << 3));
        lineData |= (value & 0xff) << (idx << 3);
    }

    /**
     * Begin rendering sprite on a line
     */
    public void initDmaAccess() {
        mc = mcBase;
    }

    /**
     * Increment sprite read pointer during Y expansion
     */
    public void finishDmaAccess() {
        // we have to read this line again if the Y-expansion is set, and this
        // was the first read
        if (!firstYRead) {
            mcBase = mc;
        }
    }

    /**
     * Toggle sprite Y expansion flag
     */
    public void expandYFlipFlop() {
        if (isDMA() && expandY) {
            firstYRead = !firstYRead;
        }
    }

    /**
     * Read the color number of the next pixel of the current sprite line.
     * <p>
     * Colors 0, 1 are background colors, color 2 sprite color #2, colors 3-&gt; sprite-specific colors.
     */
    private boolean multiColorLatched;
    private int prevColorIndex;
    private int prevPixel;
    private boolean expandXLatched;

    private int consumedLineData;

    /**
     * Sprite colors: 0, 1, and our own color.
     */
    private final int[] color = new int[4];

    private int prevPriority;

    private boolean mos8565;
    private long colorWriteCycle = Long.MIN_VALUE;
    private int colorWriteMask;
    private int firstPixelColors;

    void setMos8565(boolean mos8565) {
        this.mos8565 = mos8565;
    }

    /** PAL color writes reach the output mux one pixel after CPU readback. */
    void writeColor(int idx, int val, long cycle) {
        if (colorWriteCycle != cycle) {
            colorWriteCycle = cycle;
            colorWriteMask = 0;
        }
        int shift = idx << 2;
        firstPixelColors = firstPixelColors & ~(15 << shift)
                | (mos8565 ? 15 : color[idx]) << shift;
        colorWriteMask |= 1 << idx;
        color[idx] = val;
    }

    public void setColor(int idx, int val) {
        color[idx] = val;
    }

    public int getColor(int idx) {
        return color[idx];
    }

    int colorBuffer;

    final int indexBits;

    /**
     * Begin the damaged sprite-fetch region.
     * <p>
     * DMA0 freezes an already active sprite pixel sequencer starting after the third pixel of the following 8-pixel
     * output block.
     */
    public void beginFetchHalt() {
        fetchBusBit = -1;
        /*
         * DMA0 blocks future X-comparator matches even when the sprite
         * pixel sequencer has not started yet.
         */
        fetchHalt = true;

        /*
         * Only an already running sequencer produces the visible
         * repeated-pixel damage.
         */
        if (consuming) {
            fetchDamagePixel = 0;
        }
    }

    /**
     * PAL DMA0 can race a new multicolor pair's low bit with bit 7 of the
     * preceding pointer bus access. Other sampling phases retain their pixel.
     */
    void beginFetchHalt(byte pointerBusData) {
        beginFetchHalt();
        fetchBusBit = (pointerBusData & 0x80) >>> 7;
    }

    /**
     * DMA2 has completed and the X comparator becomes available again.
     */
    public void endFetchHalt() {
        fetchHalt = false;
    }


    /**
     * Generate graphics data for the next 8 pixels for the sprite
     * <p>
     * Foreground pixels are identified by having any bit set.
     *
     * @return packed pixel array with colors 0, 1, 2, 3+index
     */
    public int calculateNext8Pixels() {
        return calculateNext8Pixels(Long.MIN_VALUE);
    }

    /** Long.MIN_VALUE retains the existing NTSC/collision-only color path. */
    int calculateNext8Pixels(long cycle) {
        final int firstPixelMask = colorWriteCycle != Long.MIN_VALUE && cycle == colorWriteCycle + 1
                ? colorWriteMask : 0;
        int priorityBuffer = 0;

        /*
         * Common case of unexpanded sprite. We happen to know how to do these very
         * efficiently. Watch...
         */
        if (fetchDamagePixel < 0
                && !expandX && !expandXLatched
                && !multiColor && !multiColorLatched) {
            int priority = VIC.spriteSingleColorLUT[consumedLineData >>> 24];
            consumedLineData <<= 8;
            if (consumedLineData == 0) {
                consuming = false;
            }
            colorBuffer = color[2] * 0x11111111 & priority;
            if ((firstPixelMask & 4) != 0) {
                colorBuffer = colorBuffer & 0x0fffffff
                        | (firstPixelColors >>> 8 & 15) << 28 & priority;
            }
            return priority;
        }

        colorBuffer = 0;

        /*
         * sprite state:
         *
         * 1) multicolor 4-state: on, off, turning on, turning off 2) expand-x 4-state:
         * on, off, turning on, turning off 3) expandx current flop 4) multicolor
         * current flop
         *
         * yielding 64 different decoding combinations + first pixel handling for the
         * flop-related cases.
         */

        for (int pixelIndex = 0; pixelIndex < 8; pixelIndex++) {
            /*
             * Register latches continue running even while the sprite pixel
             * sequencer itself is halted.
             */
            switch (pixelIndex) {
                case 6:
                    expandXLatched = expandX;
                    // MOS8565 can sample D01C one pixel earlier when both
                    // repeat flip-flops allow a new pixel. A held pixel keeps
                    // its selector until the later latch.
                    if (mos8565 && firstXRead && firstMultiColorRead) {
                        multiColorLatched = multiColor;
                    }
                    break;

                case 7:
                    if (multiColorLatched != multiColor) {
                        multiColorLatched = multiColor;

                        // The later latch clears the multicolor flip-flop,
                        // including MOS8565 transitions during a held pixel.
                        firstMultiColorRead = false;
                    }
                    break;
            }

            /*
             * DMA0 stops the sprite sequencer after pixel 2.
             *
             * Pixels 3..9 retain the pixel generated at pixel 2.
             * At pixel 10 DMA2 has reached the point where the currently
             * active sprite pipeline disappears.
             */
            final boolean fetchHalted =
                    fetchDamagePixel >= 3 && fetchDamagePixel <= 9;

            final boolean fetchCut =
                    fetchDamagePixel >= 10;

            if (fetchCut) {
                consuming = false;
                prevColorIndex = 0;
                prevPixel = 0;
                prevPriority = 0;

            } else if (!fetchHalted) {
                /*
                 * Normal sprite pixel sequencer.
                 */
                if (firstXRead) {
                    if (multiColorLatched) {
                        if (firstMultiColorRead) {
                            if (consumedLineData == 0) {
                                consuming = false;
                            }

                            prevColorIndex = consumedLineData >>> 30;
                            if (fetchDamagePixel == 2 && fetchBusBit >= 0) {
                                // The next bit races the pointer bus as DMA0 stops the shifter.
                                // Hold the corrected selector, including its opacity, until DMA2 cuts it.
                                prevColorIndex = prevColorIndex & 2 | fetchBusBit;
                                if (prevColorIndex != 0) {
                                    consuming = true;
                                }
                            }
                            prevPriority = prevColorIndex != 0 ? 0xf : 0;
                            prevPixel = color[prevColorIndex];
                        }

                        firstMultiColorRead = !firstMultiColorRead;

                    } else {
                        if (consumedLineData == 0) {
                            consuming = false;
                        }

                        prevPriority =
                                consumedLineData >> 31 & 0xf;
                        prevColorIndex = 2;
                        prevPixel = prevPriority & color[2];
                    }

                    consumedLineData <<= 1;
                }

                /*
                 * X expansion flip-flop.
                 *
                 * Expanded: toggle after every output pixel.
                 * Normal: force the sequencer into consuming state for
                 * the following pixel.
                 */
                if (expandXLatched) {
                    firstXRead = !firstXRead;
                } else {
                    firstXRead = true;
                }
            }

            /*
             * During fetchHalted neither consumedLineData nor either sprite
             * expansion flip-flop advances. The color selector stays constant,
             * but color-register writes still reach the output mux.
             */
            int pixelColor = cycle == Long.MIN_VALUE ? prevPixel : color[prevColorIndex];
            if (pixelIndex == 0 && (firstPixelMask & 1 << prevColorIndex) != 0) {
                pixelColor = firstPixelColors >>> (prevColorIndex << 2) & 15;
            }
            colorBuffer <<= 4;
            colorBuffer |= pixelColor & prevPriority;

            priorityBuffer <<= 4;
            priorityBuffer |= prevPriority;

            if (fetchDamagePixel >= 0) {
                fetchDamagePixel++;

                /*
                 * The two affected 8-pixel blocks have now passed.
                 */
                if (fetchDamagePixel >= 16) {
                    fetchDamagePixel = -1;
                    fetchBusBit = -1;
                }
            }
        }
        return priorityBuffer;
    }

    public void reset() {
        delayPixels = 0;

        display = false;
        displayLatched = false;
        consuming = false;
        fetchHalt = false;
        fetchDamagePixel = -1;
        fetchBusBit = -1;

        firstMultiColorRead = false;
        firstXRead = false;
        firstYRead = false;

        lineData = 0;
        consumedLineData = 0;
        pointerByte = 0;

        mcBase = 63;
        mc = 63;

        x = 0;
        y = 0;

        enabled = false;
        expandX = false;
        expandY = false;
        multiColor = false;
        priorityOverForegroundGraphics = false;

        priorityMask = 0;
        prevPriority = 0;
        prevColorIndex = 0;
        prevPixel = 0;

        expandXLatched = false;
        multiColorLatched = false;

        colorBuffer = 0;
        colorWriteCycle = Long.MIN_VALUE;
        colorWriteMask = 0;
        firstPixelColors = 0;

        for (int i = 0; i < color.length; i++) {
            color[i] = 0;
        }

        nextVisibleSprite = null;
    }
}