Skip to content

SpeedometerIndicator

roosit edited this page May 15, 2026 · 4 revisions

SpeedometerIndicator

Up | Previous | Next | Русский

Full source code with brief explanations

Below is the full class source in documentation form. The comments inside the block explain the purpose of each part of the class, but they are not kept in the working SpeedometerIndicator.java: production code stays clean, and the explanations live in the wiki.

package com.velitask.plugin.official;

import com.velitask.sdk.Indicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.IndicatorSkin;
import com.velitask.sdk.IndicatorSkinTransfer;
import com.velitask.sdk.data.DistanceSensorAtom;
import com.velitask.sdk.properties.ColorProperty;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DistanceSensorProperty;
import com.velitask.sdk.properties.EnumArrayProperty;
import com.velitask.sdk.properties.FontColorProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.SvgProperty;
import com.velitask.sdk.properties.TextTemplateProperty;
import com.velitask.sdk.properties.TransparentColorProperty;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Arc2D;
import java.awt.geom.Rectangle2D;
import org.abricos.core.state.maket.HorizontalAlign;
import org.abricos.core.state.maket.Maket;
import org.abricos.core.state.maket.VerticalAlign;

/*
 * Classic round speedometer with a needle and numeric speed value.
 * Built from SVG parts (background, scale, numbers, needle, tail arc);
 * the user can configure the colors of each part, and the colors are bound
 * to SVG through SvgProperty.bind(...). Speed comes from the distance sensor.
 */
public class SpeedometerIndicator extends Indicator {

    public static final String NAME = "speedometer";

    private static final String KEY = _KEY + "." + NAME;

    /* Base path to speedometer SVG resources in the plugin jar. */
    private static final String SVG_PATH = "svg/speedometer/";

    /* Speed source: distance sensor (the speed field in DistanceSensorAtom). */
    private final DistanceSensorProperty mDistance = new DistanceSensorProperty();

    /*
     * Available scales: 40, 80, 160, 320 km/h. Speed > scale is clamped
     * to scale (the needle stays at the maximum). Each scale has its own
     * SVG with numbers.
     */
    public static enum SpeedScale {
        SCALE_40(40),
        SCALE_80(80),
        SCALE_160(160),
        SCALE_320(320);

        public final int value;

        SpeedScale(int value) {
            this.value = value;
        }
    }

    private static final String SPEED_SCALE = "speedScale";

    /*
     * Scale selector: an anonymous EnumArrayProperty with SCALE_160 as the
     * default and localized labels (just the numbers: "40", "80", "160", "320").
     */
    private final EnumArrayProperty<SpeedScale> mSpeedScale
            = new EnumArrayProperty<>(SpeedScale.class) {
        {
            set(SpeedScale.SCALE_160);
        }

        @Override
        public String getName() {
            return SPEED_SCALE;
        }

        @Override
        public String getTitle() {
            return localized(KEY + "." + SPEED_SCALE + ".title");
        }

        @Override
        protected String[] defineTitles() {
            SpeedScale[] vs = SpeedScale.values();
            String[] t = new String[vs.length];
            for (int i = 0; i < vs.length; i++) {
                t[i] = String.valueOf(vs[i].value);
            }
            return t;
        }
    };

    /* Font and color for the numeric speed value in the center. Default size = 120. */
    private final FontColorProperty mText = new FontColorProperty(120);

    private static final String BACKGROUND = "background";
    /* Round background color (semi-transparent by default: gray, alpha=80). */
    private final TransparentColorProperty mBackground = new TransparentColorProperty(
            BACKGROUND,
            localized(KEY + "." + BACKGROUND + ".title"),
            new Color(204, 204, 204), 80
    );

    private static final String SCALE_COLOR = "scaleColor";
    /* Color of scale numbers and ticks. */
    private final ColorProperty mScaleColor = new ColorProperty(
            Color.WHITE,
            SCALE_COLOR,
            localized(KEY + "." + SCALE_COLOR + ".title")
    );

    private static final String ARROW_FILL_COLOR = "arrowFillColor";
    /* Needle fill color. */
    private final ColorProperty mArrowFillColor = new ColorProperty(
            new Color(0xcc, 0x58, 0x54),
            ARROW_FILL_COLOR,
            localized(KEY + "." + ARROW_FILL_COLOR + ".title")
    );

    private static final String ARROW_STROKE_COLOR = "arrowStrokeColor";
    /* Needle stroke color. */
    private final ColorProperty mArrowStrokeColor = new ColorProperty(
            Color.WHITE,
            ARROW_STROKE_COLOR,
            localized(KEY + "." + ARROW_STROKE_COLOR + ".title")
    );

    private static final String TAIL_COLOR = "tailColor";
    /* Tail color: the filled sector behind the needle, showing progress. */
    private final ColorProperty mTailColor = new ColorProperty(
            new Color(0x67, 0x88, 0xa6, 0xb2),
            TAIL_COLOR,
            localized(KEY + "." + TAIL_COLOR + ".title")
    );

    /* Numeric speed label template. Default is "%.0f"; the float skin uses "%.1f". */
    private final SpeedometerClassicTextTemplateProperty mTemplate = new SpeedometerClassicTextTemplateProperty();

    private TextTemplateProperty getTemplate() {
        return mTemplate;
    }

    /*
     * Background SVG: ".ring" is bound to the background color. Bind means that
     * during SVG rendering, the runtime writes the current mBackground value
     * into the fill attribute of the .ring element.
     */
    private final SvgProperty mBgSvg = new SvgProperty("bgSvg", SVG_PATH + "background.svg")
            .bind(".ring", "fill", mBackground.getColor());

    /* Scale tick marks; ".tick" is bound to mScaleColor. */
    private final SvgProperty mDelimiterSvg = new SvgProperty("delimiterSvg", SVG_PATH + "delimiter.svg")
            .bind(".tick", "fill", mScaleColor);

    /*
     * Scale numbers: four separate SVGs, one for each speed scale.
     * Render chooses one of the four by mSpeedScale.
     */
    private final SvgProperty[] mScaleSvgs = new SvgProperty[]{
        new SvgProperty("scale40", SVG_PATH + "numeric_40.svg")
        .bind(".number", "fill", mScaleColor),
        new SvgProperty("scale80", SVG_PATH + "numeric_80.svg")
        .bind(".number", "fill", mScaleColor),
        new SvgProperty("scale160", SVG_PATH + "numeric_160.svg")
        .bind(".number", "fill", mScaleColor),
        new SvgProperty("scale320", SVG_PATH + "numeric_320.svg")
        .bind(".number", "fill", mScaleColor)
    };

    /* Needle: fill and stroke. */
    private final SvgProperty mArrowSvg = new SvgProperty("arrowSvg", SVG_PATH + "arrow.svg")
            .bind(".arrow-body", "fill", mArrowFillColor)
            .bind(".arrow-body", "stroke", mArrowStrokeColor);

    /* Tail: a line (through stroke) that will be clipped by angle in render(). */
    private final SvgProperty mTailSvg = new SvgProperty("tailSvg", SVG_PATH + "arrow_tail.svg")
            .bind(".tail", "stroke", mTailColor);

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public String getTitle() {
        return localized(KEY + ".title");
    }

    @Override
    public String getDescription() {
        return localized(KEY + ".description");
    }

    @Override
    public String getTags() {
        return localized(KEY + ".tags");
    }

    /* Initial layout: top-right, 50/50 margin, 400 x 400 size (square). */
    @Override
    public void defineMaket(Maket maket) {
        maket.setVertical(VerticalAlign.TOP);
        maket.setHorizontal(HorizontalAlign.RIGHT);
        maket.setLayerMargin(null, null, 50d, 50d);
        maket.setLayerSize(400d, 400d);
    }

    @Override
    public IProperty[] defineProperties() {
        return new IProperty[]{
            mDistance, mSpeedScale,
            mText, getTemplate(),
            mScaleColor,
            mArrowFillColor, mArrowStrokeColor, mTailColor,
            mBackground
        };
    }

    @Override
    public void configureDisplay(DisplayConfig config) {
        config.set(mSpeedScale, PropertyGroup.APPEARANCE);
        config.set(mScaleColor, PropertyGroup.APPEARANCE);
        config.set(mArrowFillColor, PropertyGroup.APPEARANCE);
        config.set(mArrowStrokeColor, PropertyGroup.APPEARANCE);
        config.set(mTailColor, PropertyGroup.APPEARANCE);
        config.set(mBackground, PropertyGroup.APPEARANCE);
    }

    /*
     * One "night" skin: overrides all color properties with dark tones
     * for use on a dark video background.
     */
    @Override
    public IndicatorSkin[] defineSkins() {
        return new IndicatorSkin[]{
            IndicatorSkin.builder("night", localized(KEY + ".skin.night"))
            .set(mText.getColor().skin(0xaa, 0xaa, 0xaa))
            .set(mBackground.getColor().skin(0x11, 0x11, 0x11))
            .set(mBackground.getTransparency().skin(33))
            .set(mScaleColor.skin(0x88, 0x88, 0x88))
            .set(mArrowFillColor.skin(0x55, 0x2b, 0x2a))
            .set(mArrowStrokeColor.skin(0xaa, 0xaa, 0xaa))
            .set(mTailColor.skin(0x33, 0x44, 0x55, 0xaa))
            .build()
        };
    }

    /*
     * Render: computes speed, needle angle = speed/scale * 360 degrees,
     * and draws layers in this order: background -> tail -> delimiter -> scale -> arrow -> text.
     */
    @Override
    public void render(IndicatorContext indicatorContext) {
        SpeedometerClassicContext ctx = (SpeedometerClassicContext) indicatorContext;
        Graphics2D g = ctx.graphics;

        /* Square size = the smaller layer dimension; center it. */
        int size = Math.min(ctx.width, ctx.height);
        int x = (ctx.width - size) / 2;
        int y = (ctx.height - size) / 2;

        /* The background is drawn first, with user-configured transparency. */
        ctx.bgSvg.render(g, x, y, size, size, ctx.background.alpha);

        /* Speed: atom -> speed (stored as "1/1000 km/h", so divide by 1000.0). */
        double speedKmh = 0;
        long rawTime = mDistance.convertToRawTime(ctx.player.time);
        if (ctx.player.isPreview) {
            rawTime = mDistance.clampToSensorRange(rawTime);
        }
        DistanceSensorAtom atom = mDistance.queryAtom(rawTime);
        if (atom != null) {
            speedKmh = atom.speed / 1000.0;
        }
        /* Needle angle: 0..scale -> 0..360 degrees. Values above scale are clamped to scale. */
        int scale = Math.max(1, ctx.speedScale.value);
        double angleDeg = Math.min(speedKmh, scale) * 360.0 / scale;

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        /* Tail sector behind the needle (clip arc + SVG render). */
        renderTailArc(g, ctx.tailSvg, x, y, size, angleDeg);

        /* Scale tick marks. */
        ctx.delimiterSvg.render(g, x, y, size, size);

        /* Scale numbers (the SVG selected for the current scale). */
        ctx.scaleSvg.render(g, x, y, size, size);

        /* Needle with rotation = angleDeg. */
        ctx.arrowSvg.render(g, x, y, size, size, angleDeg);

        /* Numeric speed value in the center, formatted by the template. */
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Font font = ctx.text.toFont(ctx.scale);
        g.setFont(font);
        g.setColor(ctx.text.color.value);
        String text = ctx.template.makeText(speedKmh);
        FontMetrics fm = g.getFontMetrics(font);
        Rectangle2D r = fm.getStringBounds(text, g);
        int tx = (ctx.width - (int) r.getWidth()) / 2;
        int ty = (ctx.height - (int) r.getHeight()) / 2 + fm.getAscent();
        g.drawString(text, tx, ty);
    }

    /*
     * The tail is drawn as a pie shape (circular arc), then used as the clip
     * for rendering the tail SVG. The angle starts at 270 degrees (12 o'clock)
     * counterclockwise, with length equal to angleDeg.
     */
    private static void renderTailArc(Graphics2D g, SvgProperty.SvgContext tailSvg,
            int x, int y, int size, double angleDeg) {
        if (angleDeg <= 0) {
            return;
        }
        /* Full circle: no clip is needed; render the SVG directly. */
        if (angleDeg >= 360) {
            tailSvg.render(g, x, y, size, size);
            return;
        }
        float cx = x + size / 2f;
        float cy = y + size / 2f;
        float r = size;
        Arc2D pie = new Arc2D.Float(
                cx - r, cy - r,
                2 * r, 2 * r,
                270f, (float) -angleDeg,
                Arc2D.PIE
        );
        Graphics2D g2 = (Graphics2D) g.create();
        try {
            g2.clip(pie);
            tailSvg.render(g2, x, y, size, size);
        } finally {
            g2.dispose();
        }
    }

    /*
     * Numeric label template: only the "curr" variable.
     * Default format "%.0f"; the float skin changes it to "%.1f".
     */
    static class SpeedometerClassicTextTemplateProperty extends TextTemplateProperty {

        private static final String KEY_PROPERTY = KEY + "." + NAME;
        private static final String KEY_PROPERTY_TEMPLATE = KEY_PROPERTY + ".template";
        private static final String KEY_PROPERTY_VAR = KEY_PROPERTY + ".var";
        private static final String KEY_PROPERTY_VAR_CURR = KEY_PROPERTY_VAR + ".curr";

        @Override
        protected String defineTemplate() {
            return localized(KEY_PROPERTY_TEMPLATE + ".default");
        }

        @Override
        protected Var[] defineVars() {
            return new Var[]{
                new Var("curr", "%.0f", localized(KEY_PROPERTY_VAR_CURR))
            };
        }

        public IndicatorSkinTransfer skinFloat() {
            return skin(localized(KEY_PROPERTY_TEMPLATE + ".float"),
                    new Var[]{new Var("curr", "%.1f", localized(KEY_PROPERTY_VAR_CURR))});
        }
    }

    /* Context with snapshots of all properties and prepared SVG contexts for rendering. */
    public class SpeedometerClassicContext extends IndicatorContext {

        public final SpeedScale speedScale;
        public final FontColorProperty.FontColorContext text;
        public final TextTemplateProperty.TextTemplateContext template;

        public final TransparentColorProperty.TransparentColorContext background;

        public final SvgProperty.SvgContext bgSvg;
        public final SvgProperty.SvgContext delimiterSvg;
        public final SvgProperty.SvgContext scaleSvg;
        public final SvgProperty.SvgContext arrowSvg;
        public final SvgProperty.SvgContext tailSvg;

        public SpeedometerClassicContext(Player player, Canvas canvas) {
            super(player, canvas);
            speedScale = mSpeedScale.get();
            text = mText.createContext();
            template = getTemplate().createContext();
            background = mBackground.createContext();

            bgSvg = mBgSvg.createContext();
            delimiterSvg = mDelimiterSvg.createContext();
            /* Select the SVG whose scale matches the chosen speedScale. */
            scaleSvg = scaleSvgFor(speedScale).createContext();
            arrowSvg = mArrowSvg.createContext();
            tailSvg = mTailSvg.createContext();
        }

        private SvgProperty scaleSvgFor(SpeedScale scale) {
            return mScaleSvgs[scale.ordinal()];
        }
    }

    @Override
    public IndicatorContext createContext(IndicatorContext.Player player, IndicatorContext.Canvas canvas) {
        return new SpeedometerClassicContext(player, canvas);
    }
}

Purpose

SpeedometerIndicator is a classic round speedometer with a needle and a numeric value in the center. Speed comes from the distance sensor (the speed field). The scale is selected from four built-in options: 40 / 80 / 160 / 320 km/h. The graphics are assembled from SVG parts with configurable colors; there is a built-in night skin for dark video themes.

How it works

Data. DistanceSensorProperty provides a DistanceSensorAtom, and the indicator reads atom.speed from it (stored as "1/1000 km/h"). Dividing by 1000.0 gives km/h. The needle angle is min(speed, scale) / scale * 360 degrees (values above the scale are clamped to 360 degrees, so the needle stays at the maximum).

Settings. Nine properties: speed source, scale selector (an anonymous EnumArrayProperty with four default values), FontColorProperty for the center number, TransparentColorProperty for the background (with alpha), four ColorProperty values (scale color, needle fill, needle stroke, tail-sector color), and TextTemplateProperty for the numeric label (one curr parameter). Graphics use five SvgProperty values (background, delimiter, four scale variants, arrow, tail); colors are bound through .bind(selector, attr, color), and the runtime writes the current color into the SVG attribute during rendering.

Drawing. Layers are drawn strictly in this order: background -> tail arc -> delimiter -> scale numbers -> arrow -> text. The tail is the only special case: it is drawn as a pie-arc clip from 270 degrees for angleDeg, then tail.svg is rendered under that clip to produce the filled sector of the covered range. The arrow.svg is rendered with rotation = angleDeg. The numeric value is centered through FontMetrics.

Features and limitations

  • Speed > selected scale: the needle stays at the maximum (360 degrees), while the center number remains the real value. This is intentional: the user sees that the value went beyond the scale and still sees the real value N.
  • No atom means speed = 0: the indicator still draws an empty dial (needle at zero, number 0). This differs from text indicators, which skip rendering entirely when data is missing.
  • speed in DistanceSensorAtom is stored as "1/1000 km/h", so /1000.0 is required for km/h. This is specific to the sensor format, not the SDK.
  • The float skin changes the curr format from %.0f to %.1f, so the user sees 32.5 instead of 33. The base template.float localization is also replaced so the template handles the fractional value correctly.
  • The tail-arc clip uses radius = size (double diameter), an intentional overshoot so the pie definitely covers the visible area even with complex SVG shapes.

Clone this wiki locally