OplView.java

package ui.oscilloscope;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import libsidutils.oscilloscope.OplOscilloscope;
import sidplay.Player;
import ui.common.C64VBox;
import ui.common.C64Window;
import ui.common.UIPart;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * JavaFX-only presentation of copied OPL snapshots. The overview shows all nine channel outputs; selecting a channel
 * supplies its two operator envelopes and base pitch. This view never reads or clocks the live synthesis objects.
 */
public final class OplView extends C64VBox implements UIPart {
    private static final Color[] COLORS = {Color.LIGHTGREEN, Color.LIGHTBLUE, Color.GOLD, Color.PLUM};

    @FXML
    private List<Canvas> waveCanvases, detailCanvases;
    @FXML
    private List<List<Canvas>> allGaugeCanvases;
    @FXML
    private List<Label> channelLabels, parameterLabels, allChannelLabels, operatorLabels;
    @FXML
    private Label titleLabel, selectedChannelLabel;
    @FXML
    private ComboBox<String> layout;
    @FXML
    private VBox overview, allGauges;

    private ResourceBundle bundle;
    private volatile int generation, sourceType, detailMask;
    private int selectedChannel;
    private boolean showAllGauges;
    private int[][] channelMetadata;

    public OplView() {
        super();
    }

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

    @FXML
    @Override
    protected void initialize() {
        bundle = util.getBundle();
        sourceType = -1;
        detailMask = 1;
        channelMetadata = new int[9][12];
        layout.getItems().addAll(text("OPL_OVERVIEW"), text("OPL_ALL_GAUGES"));
        layout.getSelectionModel().select(0);
        layout.valueProperty().addListener((observable, previous, next) -> {
            showAllGauges = layout.getSelectionModel().getSelectedIndex() == 1;
            detailMask = showAllGauges ? 511 : 1 << selectedChannel;
            clearDetails();
            overview.setVisible(!showAllGauges);
            overview.setManaged(!showAllGauges);
            allGauges.setVisible(showAllGauges);
            allGauges.setManaged(showAllGauges);
        });
    }

    @FXML
    private void selectChannel(ActionEvent event) {
        ToggleButton button = (ToggleButton) event.getSource();
        selectedChannel = Integer.parseInt(button.getUserData().toString());
        button.setSelected(true);
        detailMask = showAllGauges ? 511 : 1 << selectedChannel;
        clearDetails();
    }

    public int getDetailMask() {
        return detailMask;
    }

    public void setSource(int type, int nextGeneration) {
        sourceType = type;
        generation = nextGeneration;
        Platform.runLater(() -> {
            if (nextGeneration != generation) {
                return;
            }
            if (type >= 0) {
                titleLabel.setText("FM-OPL · " + (type == 0 ? "YM3526 / OPL1" : "YM3812 / OPL2"));
            }
            setVisible(type >= 0);
            setManaged(type >= 0);
        });
    }

    public void renderSnapshot(ByteBuffer frame) {
        if (frame != null && frame.getInt(4) == generation && sourceType >= 0) {
            render(frame);
        }
    }

    private String text(String key) {
        return bundle.getString(key);
    }

    // A selection/layout change can leave old detail data in an otherwise valid
    // canvas. Clear it until a frame with the new channel mask arrives.
    private void clearDetails() {
        if (detailCanvases != null) {
            for (Canvas canvas : detailCanvases) {
                canvas.getGraphicsContext2D().clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
            }
        }
        if (showAllGauges && allGaugeCanvases != null) {
            for (List<Canvas> row : allGaugeCanvases) {
                for (int i = 1; i < row.size(); i++) {
                    row.get(i).getGraphicsContext2D().clearRect(0, 0, row.get(i).getWidth(), row.get(i).getHeight());
                }
            }
        }
    }

    private void render(ByteBuffer frame) {
        int width = frame.getInt(12), mask = frame.getInt(16), rhythm = frame.getInt(24), digi = frame.getInt(28);
        int clock = frame.getInt(40);
        for (int channelIndex = 0; channelIndex < 9; channelIndex++) {
            int base = OplOscilloscope.HEADER_BYTES + channelIndex * OplOscilloscope.CHANNEL_BYTES;
            for (int field = 0; field < 12; field++) {
                channelMetadata[channelIndex][field] = frame.getInt(base + field * 4);
            }
            String name = "CH " + (channelIndex + 1);
            if (digi != 0 && channelIndex < 2) {
                name += " · DAC " + (channelIndex == 0 ? "A" : "B");
            } else if ((rhythm & 32) != 0 && channelIndex >= 6) {
                name += " · " + new String[]{"BD", "HH / SD", "TOM / CYM"}[channelIndex - 6];
            }
            String pitch = digi != 0 && channelIndex < 2 ? "DAC" : String.format(Locale.ROOT, "%.1f Hz",
                    OplOscilloscope.frequency(channelMetadata[channelIndex][0], clock));
            String algorithm = channelMetadata[channelIndex][1] == 0 ? "FM" : text("OPL_ADDITIVE");
            channelLabels.get(channelIndex).setText(name + " · " + pitch);
            parameterLabels.get(channelIndex).setText(algorithm + " · " + text("OPL_FEEDBACK") + " " + channelMetadata[channelIndex][2]);
            allChannelLabels.get(channelIndex).setText(name + "\n" + pitch + "\n" + algorithm + " · FB " + channelMetadata[channelIndex][2]);
        }
        selectedChannelLabel.setText(channelLabels.get(selectedChannel).getText() + " · " + parameterLabels.get(selectedChannel).getText() +
                " · " + text(channelMetadata[selectedChannel][3] == 0 ? "OPL_KEY_OFF" : "OPL_KEY_ON"));
        for (int operator = 0; operator < 2; operator++) {
            int base = 4 + operator * 4;
            operatorLabels.get(operator).setText("W" + channelMetadata[selectedChannel][base] + " · ×" + channelMetadata[selectedChannel][base + 1] / 2f +
                    " · TL −" + channelMetadata[selectedChannel][base + 2] * 0.75f + " dB");
        }
        operatorLabels.get(2).setText(text("OPL_BASE_PITCH"));
        int offset = OplOscilloscope.DATA_OFFSET;
        for (int channelIndex = 0; channelIndex < 9; channelIndex++) {
            for (int gauge = 0; gauge < 4; gauge++) {
                if (gauge != 0 && (mask & 1 << channelIndex) == 0) {
                    continue;
                }
                Canvas target = showAllGauges ? allGaugeCanvases.get(channelIndex).get(gauge)
                        : gauge == 0 ? waveCanvases.get(channelIndex)
                        : channelIndex == selectedChannel ? detailCanvases.get(gauge - 1) : null;
                if (target != null) {
                    draw(target, frame, offset, width, COLORS[gauge]);
                }
                offset += width * 8;
            }
        }
    }

    private void draw(Canvas canvas, ByteBuffer frame, int offset, int columns, Color color) {
        GraphicsContext graphics = canvas.getGraphicsContext2D();
        double width = canvas.getWidth(), height = canvas.getHeight();
        graphics.setFill(Color.rgb(17, 25, 27));
        graphics.fillRect(0, 0, width, height);
        graphics.setStroke(Color.rgb(43, 59, 53));
        graphics.setLineWidth(1);
        for (int i = 1; i < 4; i++) {
            graphics.strokeLine(0, height * i / 4, width, height * i / 4);
            graphics.strokeLine(width * i / 4, 0, width * i / 4, height);
        }
        graphics.setStroke(color);
        graphics.beginPath();
        for (int x = 0; x < columns; x++) {
            double px = (x + 0.5) * width / columns;
            double y1 = (1 - frame.getFloat(offset + x * 8 + 4)) * (height - 2) + 1;
            double y2 = (1 - frame.getFloat(offset + x * 8)) * (height - 2) + 1;
            graphics.moveTo(px, y1);
            graphics.lineTo(px, Math.max(y1 + 0.8, y2));
        }
        graphics.stroke();
    }
}