Gauge.java

package ui.oscilloscope;

import javafx.fxml.FXML;
import javafx.scene.control.TitledPane;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.WritableImage;
import libsidplay.common.SIDEmu;
import libsidutils.oscilloscope.GaugeUtil;
import libsidutils.oscilloscope.TraceHistory;
import sidplay.Player;
import ui.common.C64VBox;
import ui.common.C64Window;
import ui.common.ImageQueue;
import ui.common.UIPart;

import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Gauge extends C64VBox implements UIPart {

    private static final int BACKGROUND = 0xff11191b;
    private static final int GRID = 0xff2b3b35;
    private static final Map<Long, int[]> backgroundCache = new ConcurrentHashMap<>();
    private static final int[][] WAVE_COLORS = createTracePalette(0xff80e69a);
    private static final int[][] ENVELOPE_COLORS = createTracePalette(0xff8bbcff);
    private static final int[][] FREQUENCY_COLORS = createTracePalette(0xffc6a7f7);
    private static final int[][] LEVEL_COLORS = createTracePalette(0xffedc273);

    // GaugeUtil already applies gamma to its coverage. Blend that coverage into
    // the new colors once, including grid crossings, rather than changing its
    // one-pixel raster algorithm or doing color arithmetic in every frame.
    private static int[][] createTracePalette(int foreground) {
        int[][] colors = new int[2][256];
        for (int layer = 0; layer < colors.length; layer++) {
            int background = layer == 0 ? BACKGROUND : GRID;
            for (int coverage = 0; coverage < 256; coverage++) {
                int color = 0xff000000;
                for (int shift = 0; shift <= 16; shift += 8) {
                    int base = (background >>> shift) & 255;
                    int target = (foreground >>> shift) & 255;
                    color |= (base + (target - base) * coverage / 255) << shift;
                }
                colors[layer][coverage] = color;
            }
        }
        return colors;
    }

    // Every gauge of a given size shares this immutable background. A frame only
    // copies it into the existing raster; grid construction is never on the hot path.
    private static int[] background(int width, int height) {
        return backgroundCache.computeIfAbsent(((long) width << 32) | height, dimensions -> {
            int[] pixels = new int[width * height];
            Arrays.fill(pixels, BACKGROUND);
            for (int division = 1; division < 4; division++) {
                int x = width * division / 4, y = height * division / 4;
                Arrays.fill(pixels, y * width, (y + 1) * width, GRID);
                for (int row = 0; row < height; row++) {
                    pixels[row * width + x] = GRID;
                }
            }
            return pixels;
        });
    }

    private String text;
    private int voice;

    private int[] pixels;
    private int[] background;
    private int[][] tracePalette;

    private GaugeUtil gaugeUtil;
    private WritableImage snapshotImage;

    private int width;
    private int height;

    public Gauge() {
        super();
    }

    public Gauge(C64Window window, Player player) {
        super(window, player);
    }

    @FXML
    @Override
    protected void initialize() {
        width = (int) getArea().getFitWidth();
        height = (int) getArea().getFitHeight();
        background = background(width, height);
        tracePalette = this instanceof WaveGauge ? WAVE_COLORS
                : this instanceof EnvelopeGauge ? ENVELOPE_COLORS
                : this instanceof FrequencyGauge || this instanceof FilterGauge ? FREQUENCY_COLORS : LEVEL_COLORS;
        gaugeUtil = new GaugeUtil(width, height) {

            @Override
            protected void drawLine(int x, int y1, int x2, int y2, int color) {
                Gauge.this.drawLine(pixels, x, y1, x2, y2, color);
            }
        };
    }

    private final ImageQueue<GaugeImage> imageQueue = new ImageQueue<>(3);

    @Override
    public String getBundleName() {
        return Gauge.class.getName();
    }

    @Override
    public URL getFxml() {
        return getClass().getResource(Gauge.class.getSimpleName() + ".fxml");
    }

    public int getVoice() {
        return voice;
    }

    public void setVoice(int voice) {
        this.voice = voice;
    }

    public String getText() {
        return text;
    }

    public void setText(final String text) {
        this.text = text;
    }

    public void setHistory(TraceHistory history) {
        gaugeUtil.setHistory(history);
    }

    public void releaseSnapshot() {
        gaugeUtil.setHistory(TraceHistory.EMPTY);
    }

    public void reset() {
        gaugeUtil.setHistory(TraceHistory.EMPTY);
        imageQueue.clear();
        imageQueue.push(new GaugeImage(background.clone(), text));
        updateGauge();
    }

    public void updateGauge() {
        GaugeImage gaugeImage = imageQueue.pull();
        if (gaugeImage != null) {
            getTitledPane().setText(gaugeImage.getText());

            WritableImage image = new WritableImage(width, height);
            image.getPixelWriter().setPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(),
                    gaugeImage.getPixels(), 0, width);
            getArea().setImage(image);
        }
    }

    /**
     * JavaFX owns the raster; queued frames contain only numeric traces.
     */
    public void renderSnapshot(ByteBuffer frame, int sidOffset, int trace) {
        if (pixels == null) {
            pixels = new int[width * height];
        }
        System.arraycopy(background, 0, pixels, 0, pixels.length);
        int columns = frame.getInt(12);
        gaugeUtil.setSnapshot(frame, sidOffset + 32 + trace * columns * 8, columns);
        if (this instanceof WaveGauge wave) {
            wave.setRegisters(frame.get(sidOffset + 4 + trace * 7), frame.get(sidOffset + 0x17));
        }
        if (this instanceof FilterGauge filter) {
            filter.setRegisters(frame.get(sidOffset + 0x18));
        }
        gaugeUtil.draw(null);
        if (snapshotImage == null) {
            snapshotImage = new WritableImage(width, height);
        }
        snapshotImage.getPixelWriter().setPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
        getArea().setImage(snapshotImage);
        getTitledPane().setText(text);
    }

    public void addImage(SIDEmu sidemu) {
        pixels = background.clone();
        gaugeUtil.draw(sidemu);
        imageQueue.push(new GaugeImage(pixels, text));
    }

    private void drawLine(int[] pixels, int x1, int y1, int x2, int y2, int c) {
        // clip coordinates
        x1 = Math.min(Math.max(0, x1), width - 1);
        x2 = Math.min(Math.max(0, x2), width - 1);
        y1 = Math.min(Math.max(0, y1), height - 1);
        y2 = Math.min(Math.max(0, y2), height - 1);

        // GaugeUtil encodes its existing edge coverage in the green byte.
        // Partial-coverage segments are single pixels; interior spans have full coverage.
        int coverage = (c >>> 8) & 255;
        c = tracePalette[coverage < 255 && background[x1 + width * y1] == GRID ? 1 : 0][coverage];

        // delta of exact value and rounded value of the dependent variable
        int d = 0;

        int dx = Math.abs(x2 - x1);
        int dy = Math.abs(y2 - y1);

        int dx2 = 2 * dx; // slope scaling factors to
        int dy2 = 2 * dy; // avoid floating point

        int ix = x1 < x2 ? 1 : -1; // increment direction
        int iy = y1 < y2 ? 1 : -1;

        int x = x1;
        int y = y1;

        if (dx >= dy) {
            while (true) {
                pixels[x + width * y] = c;
                if (x == x2) {
                    break;
                }
                x += ix;
                d += dy2;
                if (d > dx) {
                    y += iy;
                    d -= dx2;
                }
            }
        } else {
            while (true) {
                pixels[x + width * y] = c;
                if (y == y2) {
                    break;
                }
                y += iy;
                d += dx2;
                if (d > dy) {
                    x += ix;
                    d -= dy2;
                }
            }
        }
    }

    protected TitledPane getTitledPane() {
        return null;
    }

    protected ImageView getArea() {
        return null;
    }

    @Override
    public void doClose() {
        // just in case to not waste ram with frames!
        imageQueue.dispose();
    }
}