Skip to content

SlopeChartIndicator

roosit edited this page May 15, 2026 · 4 revisions

SlopeChartIndicator

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

package com.velitask.plugin.official;

import com.velitask.plugin.official.charts.MillimetersChart;
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.data.SlopeSensorAtom;
import com.velitask.sdk.db.DataCacheRule;
import com.velitask.sdk.db.DataParams;
import com.velitask.sdk.db.PluginDatabase;
import com.velitask.sdk.db.SensorDataManager;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DisplayHint;
import com.velitask.sdk.properties.GeoZoomProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.IntegerProperty;
import com.velitask.sdk.properties.LineProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.SlopeAtomProperty;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.util.List;
import org.abricos.core.state.maket.HorizontalAlign;
import org.abricos.core.state.maket.Maket;
import org.abricos.core.state.maket.VerticalAlign;
import org.abricos.geo.GeoUtils;

/*
 * Slope chart along distance: elevation profile along the track plus colored
 * fill by slope-group type (green = descent, red = ascent, whitish = flat)
 * with 30/255 transparency. Current position is a ring in the center.
 */
public class SlopeChartIndicator extends Indicator {

    public static final String NAME = "slopeChart";

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

    /* Background group-fill transparency: 30/255, about 12%. Barely visible. */
    private static final int SLOPE_GROUP_COLOR_ALPHA = 30;

    /* Semi-transparent colors for slope-group types. Hard-coded, not configurable. */
    private static final Color FILL_DOWN = setAlpha(Color.GREEN, SLOPE_GROUP_COLOR_ALPHA);
    private static final Color FILL_UP = setAlpha(Color.RED, SLOPE_GROUP_COLOR_ALPHA);
    private static final Color FILL_PLAIN = setAlpha(Color.WHITE, SLOPE_GROUP_COLOR_ALPHA + 10);

    /* Minimum distance in pixels between two neighboring chart points. */
    private static final int MIN_PX_BETWEEN_POINTS = 5;

    private final SlopeAtomProperty mSlope = new SlopeAtomProperty();

    {
        /* Manager for a single time-based query. */
        mSlope.addManager(
                new SensorDataManager.Builder<>("slope", mSlope.getAtomClass())
                        .table(SlopeAtomProperty.TABLE_NAME)
                        .byTime()
                        .build()
        );

        /* Range query for chart building: a distance window with no cache. */
        mSlope.query("slopeRange")
                .where("(distance + distanceDelta) >= {minDistance} "
                        + "AND distance < {maxDistance}")
                .orderBy("timeRaw")
                .cache(DataCacheRule.none())
                .cacheSize(2)
                .buildList();
    }

    /* Geo zoom: X scale (mm/px through MillimetersChart). */
    private final GeoZoomProperty mGeoZoom = new GeoZoomProperty();

    /* Elevation Y-scale multiplier, 1..50. Default is 10 to make relief visible. */
    private final IntegerProperty mEleChartScale = new IntegerProperty() {
        {
            setRange(1, 50);
            setSkinnable(false);
        }

        @Override public String getName() { return "EleChartScale"; }
        @Override public Integer getDefault() { return 10; }
        @Override public String getTitle() { return localized(KEY + ".eleChartScale.title"); }
    };

    /* Chart line style (color, thickness). */
    private final LineProperty mLine = new LineProperty();

    @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, 600x300 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, mGeoZoom, mEleChartScale, mLine};
    }

    @Override
    public void configureDisplay(DisplayConfig config) {
        config.set(mGeoZoom, PropertyGroup.APPEARANCE);
        config.set(mEleChartScale, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
        config.set(mLine, PropertyGroup.APPEARANCE);
    }

    /* One "bold" skin: thick white line (10px) for contrast on dark video. */
    @Override
    public IndicatorSkin[] defineSkins() {
        return new IndicatorSkin[]{
            IndicatorSkin.builder("bold", localized(KEY + ".skin.bold"))
            .set(mLine.getColor().skin(Color.WHITE))
            .set(mLine.getThickness().skin(10))
            .build()
        };
    }

    /*
     * Render: computes the distance/elevation window around the current position
     * and draws three layers: group fills, elevation line, marker.
     */
    @Override
    public void render(IndicatorContext indicatorContext) {
        SlopeChartContext ctx = (SlopeChartContext) indicatorContext;
        Graphics2D g = ctx.graphics;

        long rawTime = mSlope.convertToRawTime(ctx.player.time);
        if (ctx.player.isPreview) {
            rawTime = mSlope.clampToSensorRange(rawTime);
        }
        SlopeSensorAtom currAtom = mSlope.queryAtom("slope", rawTime);
        if (currAtom == null) {
            return;
        }

        /*
         * MillimetersChart is centered on the current position (distance, elevation).
         * Y scale = eleChartScale (1..50), X scale = 1 (through geoZoom inside).
         * LAT_EQUATOR is a simplification; see SpeedChartIndicator.
         */
        MillimetersChart chart = new MillimetersChart(
                ctx.width, ctx.height,
                ctx.geoZoom.value, GeoUtils.LAT_EQUATOR,
                currAtom.distance, currAtom.elevation,
                1, ctx.eleChartScale.value
        );

        long margin = chart.getMmPerPixel() * 50;
        long minDist = chart.getMinMmX() - margin;
        long maxDist = chart.getMaxMmX() + margin;

        /* Range query returns slope atoms in the window. */
        DataParams rangeParams = DataParams
                .of("sensorId", mSlope.getSensorId())
                .set("minDistance", minDist)
                .set("maxDistance", maxDist);

        List<SlopeSensorAtom> atoms = mSlope.queryList("slopeRange", rangeParams);
        /*
         * Slope groups from the plugin DB (slope_groups) are used for background fill.
         * If groups have not been calculated yet (for example, the plugin was just
         * installed), the list is empty: fill is not drawn, but the line is drawn.
         */
        List<SlopeGroupAtom> groups = queryGroups(ctx.db, mSlope.getSensorId(), minDist, maxDist);

        if (atoms == null || atoms.isEmpty()) {
            return;
        }

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        if (groups != null && !groups.isEmpty()) {
            renderGroupFills(g, chart, groups, atoms);
        }

        renderLine(g, chart, atoms, ctx);

        renderMarker(g, chart, currAtom, ctx);
    }

    /*
     * Load slope groups crossing the [minDistance, maxDistance] window.
     * If db == null (plugin without DB), return an empty list.
     */
    private static List<SlopeGroupAtom> queryGroups(PluginDatabase db,
            long sensorId, long minDistance, long maxDistance) {
        if (db == null) {
            return List.of();
        }
        return db.queryList(
                "SELECT * FROM ${table:slope_groups}"
                + " WHERE sensor_id = ?"
                + " AND (distance + distanceDelta) >= ?"
                + " AND distance < ?"
                + " ORDER BY distance",
                SlopeGroupAtom.class,
                sensorId, minDistance, maxDistance
        );
    }

    /*
     * Semi-transparent fill for each slope group: a polygon from current atom
     * elevation down to the bottom of the layer. Color depends on group type
     * (FILL_DOWN/UP/PLAIN). Atoms are filtered by group membership through the
     * distance range.
     */
    private void renderGroupFills(Graphics2D g, MillimetersChart chart,
            List<SlopeGroupAtom> groups,
            List<SlopeSensorAtom> atoms) {
        for (SlopeGroupAtom groupAtom : groups) {
            long groupEndDistance = groupAtom.distance + groupAtom.distanceDelta;
            /* Skip groups left of the window and break after the right edge. */
            if (groupEndDistance < chart.getMinMmX()) continue;
            if (groupAtom.distance > chart.getMaxMmX()) break;

            Polygon polygon = new Polygon();

            int x1 = chart.convertMmToPxX(groupAtom.distance);

            /* Polygon bottom-left plus the first profile point of the group. */
            polygon.addPoint(x1, chart.getHeight());
            polygon.addPoint(x1, chart.convertMmToPxY(groupAtom.elevation));

            /* Profile points inside the group. */
            SlopeSensorAtom item = null;
            for (SlopeSensorAtom point : atoms) {
                if (point.distance < groupAtom.distance || point.distance >= groupEndDistance) {
                    continue;
                }
                int x2 = chart.convertMmToPxX(point.getNextDistance());
                if (x2 == x1) continue;
                x1 = x2;
                item = point;
                polygon.addPoint(x2, chart.convertMmToPxY(point.getNextElevation()));
            }
            if (item == null) continue;
            /* Close the polygon through the bottom. */
            polygon.addPoint(x1, chart.getHeight());

            /* Color by type: <0=DOWN, >0=UP, =0=PLAIN. */
            Color fill;
            if (groupAtom.slopeType < 0) {
                fill = FILL_DOWN;
            } else if (groupAtom.slopeType > 0) {
                fill = FILL_UP;
            } else {
                fill = FILL_PLAIN;
            }
            g.setColor(fill);
            g.fillPolygon(polygon);
        }
    }

    /* Elevation profile line with grouping logic by MIN_PX_BETWEEN_POINTS. */
    private void renderLine(Graphics2D g, MillimetersChart chart,
            List<SlopeSensorAtom> atoms, SlopeChartContext ctx) {
        float depth = (float) (ctx.line.thickness * ctx.scale);
        g.setStroke(new BasicStroke(depth, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND));
        g.setColor(ctx.line.color);

        for (int i = 0; i < atoms.size(); i++) {
            SlopeSensorAtom item = atoms.get(i);

            int x1 = chart.convertMmToPxX(item.distance);
            int y1 = chart.convertMmToPxY(item.elevation);

            int x2, y2;
            boolean hasItem2 = false;
            i++;
            for (; i < atoms.size(); i++) {
                SlopeSensorAtom item2 = atoms.get(i);
                x2 = chart.convertMmToPxX(item2.getNextDistance());
                y2 = chart.convertMmToPxY(item2.getNextElevation());
                if ((x2 - x1) > MIN_PX_BETWEEN_POINTS) {
                    hasItem2 = true;
                    g.drawLine(x1, y1, x2, y2);
                    break;
                }
            }
            if (!hasItem2) {
                x2 = chart.convertMmToPxX(item.getNextDistance());
                y2 = chart.convertMmToPxY(item.getNextElevation());
                g.drawLine(x1, y1, x2, y2);
            }
        }
    }

    /* Current-position marker: a ring, using the same AlphaComposite.Clear trick as SpeedChart. */
    private void renderMarker(Graphics2D g, MillimetersChart chart,
            SlopeSensorAtom atom, SlopeChartContext ctx) {
        float depth = (float) (ctx.line.thickness * ctx.scale);
        int rOut = (int) (depth * 6);
        int rIn = (int) (depth * 4);

        int x = chart.convertMmToPxX(atom.distance);
        int y = chart.convertMmToPxY(atom.elevation);

        g.setColor(ctx.line.color);
        g.fillOval(x - rOut / 2, y - rOut / 2, rOut, rOut);

        g.setComposite(AlphaComposite.Clear);
        g.fillOval(x - rIn / 2, y - rIn / 2, rIn, rIn);
        g.setComposite(AlphaComposite.SrcOver);
    }

    private static Color setAlpha(Color c, int alpha) {
        alpha = Math.max(0, Math.min(255, alpha));
        return new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
    }

    public class SlopeChartContext extends IndicatorContext {

        public final IntegerProperty.IntegerContext geoZoom;
        public final IntegerProperty.IntegerContext eleChartScale;
        public final LineProperty.LineContext line;

        public SlopeChartContext(Player player, Canvas canvas) {
            super(player, canvas);
            geoZoom = mGeoZoom.createContext();
            eleChartScale = mEleChartScale.createContext();
            line = mLine.createContext();
        }
    }

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

Purpose

SlopeChartIndicator is an elevation chart along distance (relief profile) with colored background by slope-group type. Ascents are reddish, descents are greenish, and flats are whitish (semi-transparent, alpha about 30/255, barely visible). The profile line is drawn on top, and the current-position ring is in the center. The window is around the current distance, with X scale through geoZoom and Y scale through eleChartScale (multiplier 1..50).

How it works

Data. SlopeAtomProperty has two managers: "slope" for a single atom (current position) and "slopeRange" for a range query over the [minDistance, maxDistance] window (no cache). Additionally, direct SQL against the plugin PluginDatabase reads slope groups from slope_groups, filled by VelitaskPlagin.onSourceImported. If there are no groups, fill is skipped and the profile line is still drawn.

Settings. Four properties: slope source, GeoZoomProperty (X scale through MillimetersChart), IntegerProperty eleChartScale (Y-elevation multiplier, 1..50, rendered as SLIDER), and LineProperty (profile line style). Background group-fill colors are hard-coded (green/red/white), not user-configurable.

Drawing. Three layers: (1) group fill, a polygon from the profile to the bottom of the layer, colored by slopeType (<0=DOWN/green, >0=UP/red, =0=PLAIN/white); (2) profile line with BasicStroke SQUARE and grouping logic by MIN_PX_BETWEEN_POINTS=5; (3) position marker, a ring in the center through AlphaComposite.Clear (the same technique as in SpeedChartIndicator).

Features and limitations

  • Group-fill colors are hard-coded: FILL_DOWN, FILL_UP, and FILL_PLAIN with the standard 30/255 transparency. To make them user-configurable, add a ColorProperty for each one.
  • MIN_PX_BETWEEN_POINTS = 5 (vs 2 in SpeedChart): slope values change more slowly, so stronger aggregation is acceptable.
  • No plugin DB (ctx.db == null): fill is not drawn, but the profile works. This matters when the plugin is loaded but onSourceImported has not run yet.
  • No atom (null): the indicator is completely empty, without a placeholder.
  • eleChartScale = 10 by default: elevation is visually exaggerated 10x to make relief readable. Set it to 1 for real scale.

Clone this wiki locally