Skip to content

SlopeTextIndicator

roosit edited this page May 31, 2026 · 5 revisions

SlopeTextIndicator

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 SlopeTextIndicator.java: production code stays clean, and the explanations live in the wiki.

package com.velitask.plugin.official;

import com.velitask.plugin.official.slope.SlopeGroupAtom;
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.SlopeSensorAtom;
import com.velitask.sdk.db.PluginDatabase;
import com.velitask.sdk.db.SensorDataManager;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.FontColorProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.SlopeAtomProperty;
import com.velitask.sdk.properties.TextAlignProperty;
import com.velitask.sdk.properties.TextTemplateProperty;
import com.velitask.sdk.properties.measurement.MeasurementProperty;
import com.velitask.units.UnitKind;
import com.velitask.units.angle.Angle;
import com.velitask.units.format.UnitValue;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import org.abricos.core.state.maket.HorizontalAlign;
import org.abricos.core.state.maket.Maket;
import org.abricos.core.state.maket.VerticalAlign;

/*
 * Text slope indicator: shows the current slope type (ascent/descent/flat),
 * slope percentage, covered/total segment length, current/total elevation,
 * and accumulated track ascent/descent. Uses both slope sensor data and
 * slope groups calculated by the plugin when importing a source.
 */
public class SlopeTextIndicator extends Indicator {

    public static final String NAME = "slopeText";

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

    /*
     * Slope data source. By default, SlopeAtomProperty does not have a
     * "slope" manager, so it is added in the init block below to call
     * queryAtom("slope", ...).
     */
    private final SlopeAtomProperty mSlope = new SlopeAtomProperty();

    {
        mSlope.addManager(
                new SensorDataManager.Builder<>("slope", mSlope.getAtomClass())
                        .table(SlopeAtomProperty.TABLE_NAME)
                        .byTime()
                        .build()
        );
    }

    /* Font and color of the main text. */
    private final FontColorProperty mText = new FontColorProperty();

    /* Alignment of the final string inside the layer. */
    private final TextAlignProperty mTextAlign = new TextAlignProperty();

    /*
     * Two unit groups: distance (meters/feet for length and curr) and
     * altitude (meters/feet for height, ele, eleCurr, up, down).
     */
    private final MeasurementProperty mUnits = new MeasurementProperty(
            UnitKind.DISTANCE, UnitKind.ALTITUDE
    );

    /* String template with 14 variables. Two built-in skins: short and detailed. */
    private final SlopeTextTemplateProperty mTemplate = new SlopeTextTemplateProperty();

    private TextTemplateProperty getTemplate() {
        return mTemplate;
    }

    @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-left, 300/100 margins, 600 x 300 size. */
    @Override
    public void defineMaket(Maket maket) {
        maket.setVertical(VerticalAlign.TOP);
        maket.setHorizontal(HorizontalAlign.LEFT);
        maket.setLayerMargin(null, 300d, 100d, null);
        maket.setLayerSize(600d, 300d);
    }

    @Override
    public IProperty[] defineProperties() {
        return new IProperty[]{mSlope, mText, mTextAlign, mUnits, getTemplate()};
    }

    @Override
    public void configureDisplay(DisplayConfig config) {
        config.set(mTextAlign, PropertyGroup.APPEARANCE);
        config.set(mUnits, PropertyGroup.APPEARANCE);
    }

    /*
     * Two skins:
     *   short: compact template with only type and percentage;
     *   detailed: expanded template with segment length, current elevation, and accumulated up/down.
     */
    @Override
    public IndicatorSkin[] defineSkins() {
        return new IndicatorSkin[]{
            IndicatorSkin.builder("short", localized(KEY + ".skin.short"))
            .set(mTemplate.skinShort())
            .build(),
            IndicatorSkin.builder("detailed", localized(KEY + ".skin.detailed"))
            .set(mTemplate.skinDetailed())
            .build()
        };
    }

    /*
     * Render: queries the current slope atom and the slope group that contains it;
     * computes relative offsets inside the group; formats through the template;
     * draws the string.
     */
    @Override
    public void render(IndicatorContext indicatorContext) {
        SlopeTextContext ctx = (SlopeTextContext) indicatorContext;
        Graphics2D g = ctx.graphics;

        /* UTC -> sensor raw-time + preview clamp. */
        long rawTime = mSlope.convertToRawTime(ctx.player.time);
        if (ctx.player.isPreview) {
            rawTime = mSlope.clampToSensorRange(rawTime);
        }
        SlopeSensorAtom atom = mSlope.queryAtom("slope", rawTime);
        if (atom == null) {
            return;
        }

        /*
         * Group containing this atom. The query goes to the plugin DB
         * (slope_groups), filled by VelitaskPlagin.onSourceImported.
         */
        SlopeGroupAtom group = queryGroupForAtom(ctx.db, mSlope.getSensorId(), atom);
        if (group == null) {
            return;
        }

        /* Relative offsets of the current atom from the group start. */
        long distanceSlope = atom.distance - group.distance;
        long elevationSlope = atom.elevation - group.elevation;

        /* Convert to user-selected units. */
        UnitValue currV = ctx.units.distanceParts(distanceSlope);
        UnitValue lengthV = ctx.units.distanceParts(group.distanceDelta);
        UnitValue heightV = ctx.units.altitudeParts(group.elevationDelta);
        UnitValue eleV = ctx.units.altitudeParts(atom.elevation);
        UnitValue eleCurrV = ctx.units.altitudeParts(Math.abs(elevationSlope));
        UnitValue upV = ctx.units.altitudeParts(atom.eleUp);
        UnitValue downV = ctx.units.altitudeParts(Math.abs(atom.eleDown));

        /*
         * Localized slope type + ASCII arrow (up, down, or empty) +
         * slope percentage converted from internal format to normal percent
         * (slope% * 100).
         */
        String type = slopeTypeToString(group.slopeType);
        String typec = slopeTypeCToString(group.slopeType);
        double pc = Angle.slopePercentToPercent(group.slopePercent);

        /* The template assembles the final string from 14 variables. */
        String text = ctx.template.makeText(
                type, typec, pc,
                currV.value(), currV.unit(),
                lengthV.value(), lengthV.unit(),
                heightV.value(), heightV.unit(),
                eleV.value(), eleV.unit(),
                eleCurrV.value(),
                upV.value(),
                downV.value()
        );

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

        ctx.textAlign.drawText(g, text, ctx.width, ctx.height);
    }

    /*
     * Direct SQL query to the plugin DB: finds the group containing the current
     * distance (group.distance <= atom.distance < group.distance + delta).
     * LIMIT 1: for valid data, groups do not overlap by distance.
     */
    private static SlopeGroupAtom queryGroupForAtom(PluginDatabase db, long sensorId, SlopeSensorAtom atom) {
        if (db == null) {
            return null;
        }
        return db.query(
                "SELECT * FROM ${table:slope_groups}"
                + " WHERE sensor_id = ?"
                + " AND distance <= ?"
                + " AND ? < (distance + distanceDelta)"
                + " LIMIT 1",
                SlopeGroupAtom.class,
                sensorId, atom.distance, atom.distance
        );
    }

    /* Localized type name: ascent / descent / flat. */
    private String slopeTypeToString(int type) {
        return switch (type) {
            case SlopeSensorAtom.TYPE_UP ->
                localized(KEY + ".type.up");
            case SlopeSensorAtom.TYPE_DOWN ->
                localized(KEY + ".type.down");
            default ->
                localized(KEY + ".type.plain");
        };
    }

    /* ASCII arrow for the type: up for UP, down for DOWN, empty for PLAIN. */
    private String slopeTypeCToString(int type) {
        return switch (type) {
            case SlopeSensorAtom.TYPE_UP ->
                "↑";
            case SlopeSensorAtom.TYPE_DOWN ->
                "↓";
            default ->
                "";
        };
    }

    /*
     * Template with 14 variables:
     *   type/typec    : slope type text and arrow
     *   pc            : slope percentage
     *   curr/currUnit : covered length inside the segment
     *   length/lengthUnit : full segment length
     *   height/heightUnit : elevation change on the segment
     *   ele/eleUnit       : current absolute elevation
     *   eleCurr           : covered elevation inside the segment
     *   up/down           : accumulated track ascent/descent
     * Skins: short (minimum), detailed (everything).
     */
    static class SlopeTextTemplateProperty 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";

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

        @Override
        protected Var[] defineVars() {
            return new Var[]{
                new Var("type", "%s", localized(KEY_PROPERTY_VAR + ".type")),
                new Var("typec", "%s", localized(KEY_PROPERTY_VAR + ".typec")),
                new Var("pc", "%.1f", localized(KEY_PROPERTY_VAR + ".pc")),
                new Var("curr", "%.3f", localized(KEY_PROPERTY_VAR + ".curr")),
                new Var("currUnit", "%s", localized(KEY_PROPERTY_VAR + ".currUnit")),
                new Var("length", "%.2f", localized(KEY_PROPERTY_VAR + ".length")),
                new Var("lengthUnit", "%s", localized(KEY_PROPERTY_VAR + ".lengthUnit")),
                new Var("height", "%.0f", localized(KEY_PROPERTY_VAR + ".height")),
                new Var("heightUnit", "%s", localized(KEY_PROPERTY_VAR + ".heightUnit")),
                new Var("ele", "%.0f", localized(KEY_PROPERTY_VAR + ".ele")),
                new Var("eleUnit", "%s", localized(KEY_PROPERTY_VAR + ".eleUnit")),
                new Var("eleCurr", "%.1f", localized(KEY_PROPERTY_VAR + ".eleCurr")),
                new Var("up", "%.0f", localized(KEY_PROPERTY_VAR + ".up")),
                new Var("down", "%.0f", localized(KEY_PROPERTY_VAR + ".down"))
            };
        }

        public IndicatorSkinTransfer skinShort() {
            return skin(localized(KEY_PROPERTY_TEMPLATE + ".short"));
        }

        public IndicatorSkinTransfer skinDetailed() {
            return skin(localized(KEY_PROPERTY_TEMPLATE + ".detailed"));
        }
    }

    /* Context with snapshots of all properties for the current frame. */
    public class SlopeTextContext extends IndicatorContext {

        public final FontColorProperty.FontColorContext text;
        public final TextAlignProperty.TextAlignContext textAlign;
        public final TextTemplateProperty.TextTemplateContext template;
        public final MeasurementProperty.Context units;

        public SlopeTextContext(Player player, Canvas canvas) {
            super(player, canvas);
            text = mText.createContext();
            textAlign = mTextAlign.createContext();
            template = getTemplate().createContext();
            units = mUnits.createContext();
        }
    }

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

Purpose

SlopeTextIndicator is a text slope indicator. At each playback moment it shows the current slope type (ascent / descent / flat), its percentage, segment length and covered part, elevation change, current absolute elevation, and accumulated ascent/descent for the whole track. The template has 14 variables that can be combined as needed; two built-in skins are available: short (compact) and detailed (everything).

How it works

Data. Through SlopeAtomProperty, the indicator gets the current SlopeSensorAtom (with UTC -> raw-time conversion and preview clamp). It then uses atom.distance to find the slope group in the plugin PluginDatabase (the slope_groups table, filled by VelitaskPlagin.onSourceImported). The sensor and group are two different detail levels: the atom provides current elevation/distance, while the group provides the segment type (UP/DOWN/PLAIN) and boundaries.

Settings. Five properties: slope source, font and color (FontColorProperty), alignment (TextAlignProperty), unit system (MeasurementProperty for DISTANCE and ALTITUDE: length in meters/feet and elevation separately), and a template with 14 variables (TextTemplateProperty).

Drawing. Relative offsets of the current atom from the group start are computed (distanceSlope, elevationSlope); all length/elevation values are converted to the selected units; the slope type is localized into text (ascent / descent / flat) plus an ASCII arrow ↑ / ↓ / empty; the slope percentage is converted from internal format (slope% * 100) through Angle.slopePercentToPercent. The template assembles the string, which is drawn through TextAlign.drawText with antialiasing.

Features and limitations

  • Depends on the plugin DB. Without saved slope groups (VelitaskPlagin.onSourceImported did not run, for example for a source without a slope sensor, or the DB has not been migrated yet), the indicator draws nothing.
  • SlopeAtomProperty has no built-in "slope" manager: it is added in the indicator init block so queryAtom("slope", ...) can be called. This is a namespace for possible future managers with different query logic.
  • Template with 14 variables. In the short skin, most variables are not used, but they are still always formed in render(); this can be optimized with lazy calculation if needed.
  • No sensor -> no group -> no display: the indicator does not show a placeholder, like DistanceTextIndicator.

Clone this wiki locally