diff --git a/client/public/js/i18n/de.js b/client/public/js/i18n/de.js
index b91a0f5d..ce3ad936 100644
--- a/client/public/js/i18n/de.js
+++ b/client/public/js/i18n/de.js
@@ -108,7 +108,7 @@ export default {
"ride.gap": "Abstand",
"ride.aroundYou": "Um dich herum",
"ride.3dViewOfThe": "3D-Ansicht der Straße hinter deinem Fahrer",
- "ride.ridersAroundYouOne": "Fahrer um dich herum, eine Reihe pro Spur",
+ "ride.mapOfTheRoad": "Draufsicht auf die Straße um dich herum",
"ride.3dViewOfThe2": "3D-Ansicht des Spinning-Studios",
"ride.leftPaddle": "Linkes Paddle",
"ride.rightPaddle": "Rechtes Paddle",
diff --git a/client/public/js/i18n/en.js b/client/public/js/i18n/en.js
index e0f26f55..607ef51e 100644
--- a/client/public/js/i18n/en.js
+++ b/client/public/js/i18n/en.js
@@ -108,7 +108,7 @@ export default {
"ride.gap": "Gap",
"ride.aroundYou": "Around you",
"ride.3dViewOfThe": "3D view of the road behind your rider",
- "ride.ridersAroundYouOne": "Riders around you, one row per lane",
+ "ride.mapOfTheRoad": "Top-down map of the road around you",
"ride.3dViewOfThe2": "3D view of the spin studio",
"ride.leftPaddle": "Left paddle",
"ride.rightPaddle": "Right paddle",
diff --git a/client/public/js/main.js b/client/public/js/main.js
index 1af895c6..bd388271 100644
--- a/client/public/js/main.js
+++ b/client/public/js/main.js
@@ -73,7 +73,7 @@ import {
} from "./view/hud.js";
import { appendFeed, describeEvent, inRace, nearbyRiders, onlineSummary, raceStatus, renderResults, renderRiderList, riderName, riderSections } from "./view/panels.js";
import { PhotoAlbum, canShareFiles, canvasToPng, composePhoto, composeSummary, downloadBlob, grabScene, photoActions, photoFileName, photoStats } from "./view/photos.js";
-import { drawPeloton } from "./view/pelotonView.js";
+import { drawRideMap } from "./view/rideMapView.js";
import { renderSplits } from "./view/splitsView.js";
import { drawProfile, drawUpcoming } from "./view/profileView.js";
import { ftpProvenance } from "./view/ftpProvenance.js";
@@ -398,6 +398,8 @@ const app = {
/** The menu's 3D view, handed over to the ride when it was built for the joined route. */
menuView: null,
viewMode: "2d",
+ /** The selected time of day, also used by the 2D map when there is no 3D view. */
+ timeMode: TIME_MODES.includes(readSetting(TIME_KEY)) ? readSetting(TIME_KEY) : "day",
hud: null,
layoutChoice: "auto",
layout: "cockpit",
@@ -849,7 +851,7 @@ function initMenuStage() {
$("menu-profile").hidden = !route;
// Docked in the corner, the map points at the picked route; with none (Workout, Studio) it is an empty box.
$("menu-map").hidden = !route && $("setup").classList.contains("map-docked");
- drawMapPreview($("menu-map"), { routes, selectedId: route?.id ?? null, network: shown.network ?? null });
+ drawMapPreview($("menu-map"), { routes, selectedId: route?.id ?? null, network: shown.network ?? null, biome: app.biome, timeMode: app.timeMode });
if (route) drawProfile($("menu-profile"), { route, riders: [], myId: null, colors: themeColors() });
};
app.redrawStage = drawStage;
@@ -4130,10 +4132,12 @@ function setQuality(quality) {
}
function setTimeMode(mode) {
- if (!app.view3d) return;
- app.view3d.setTimeMode(mode);
- $("time-mode").value = mode;
- writeSetting(TIME_KEY, mode);
+ const next = TIME_MODES.includes(mode) ? mode : "day";
+ app.timeMode = next;
+ // The 2D map has no view to configure, but it reads the same setting.
+ app.view3d?.setTimeMode(next);
+ $("time-mode").value = next;
+ writeSetting(TIME_KEY, next);
app.viewPopover?.refresh();
}
@@ -4141,7 +4145,7 @@ function setViewMode(mode, { remember = true } = {}) {
const use3d = mode === "3d" && Boolean(app.view3d);
app.viewMode = use3d ? "3d" : "2d";
$("world-wrap").hidden = !use3d;
- $("peloton").hidden = use3d;
+ $("ride-map").hidden = use3d;
$("view-3d").setAttribute("aria-pressed", String(use3d));
$("view-2d").setAttribute("aria-pressed", String(!use3d));
$("scene-controls").hidden = !use3d;
@@ -4420,11 +4424,11 @@ function frame() {
if (app.viewMode === "3d") {
app.view3d.render({ riders: ghost ? [...everyone, ghost] : everyone, myId: app.riderId, myCadence: app.session.latest.cadence, timeS: time, colors });
} else {
- drawPeloton($("peloton"), { route: app.route, riders: ghost ? [...riders, ghost] : riders, me, draft, colors, lemons: app.lemonHunt?.lemons });
+ drawRideMap($("ride-map"), { route: app.route, riders: ghost ? [...riders, ghost] : riders, me, draft, lemons: app.lemonHunt?.lemons, colors, network: app.network, routes: app.routes, biome: app.biome, timeMode: app.timeMode });
}
// Read the canvas now: a WebGL buffer is cleared once the frame is shown.
if (app.sceneRequests.length) {
- const scene = grabScene(app.viewMode === "3d" ? $("world3d") : $("peloton"));
+ const scene = grabScene(app.viewMode === "3d" ? $("world3d") : $("ride-map"));
for (const callback of app.sceneRequests.splice(0)) callback(scene);
}
diff --git a/client/public/js/view/mapPreview.js b/client/public/js/view/mapPreview.js
index 119435ca..af74bcc1 100644
--- a/client/public/js/view/mapPreview.js
+++ b/client/public/js/view/mapPreview.js
@@ -1,7 +1,10 @@
import { prepareCanvas } from "./canvas.js";
+import { MAP_COLORS, rideMapTheme } from "./rideMapTheme.js";
import { islandShape } from "../view3d/island.js";
import { roadNetworkOf } from "../route/worldMap.js";
+export { MAP_COLORS };
+
/**
* Top-down map of the routes on one map: the island, every road, the picked
* route highlighted with its climbs and sprints, and the start. Shown in the
@@ -10,17 +13,6 @@ import { roadNetworkOf } from "../route/worldMap.js";
* for tests.
*/
-export const MAP_COLORS = Object.freeze({
- sea: "#163a4e",
- land: "#2d5b3b",
- sand: "#cdb98a",
- road: "rgba(232, 236, 241, 0.5)",
- accent: "#ff7a1a",
- climb: "#ff5d5d",
- sprint: "#4cc3ff",
- start: "#ffd21f",
-});
-
/** Road samples like the 3D world's (world x/z, north is −z), for the island's shape. */
export function roadSamples(routes, step = 6) {
const samples = [];
@@ -75,13 +67,15 @@ function markerAt(route, distance) {
/**
* @param {HTMLCanvasElement} canvas
- * @param {{routes: object[], selectedId: string | null, colors?: object, island?: object | null, network?: object | null}} options
+ * @param {{routes: object[], selectedId: string | null, colors?: object, island?: object | null, network?: object | null, biome?: string, timeMode?: string, date?: Date}} options
* routes are RouteGeometry objects of one map; with the map's `network`
- * file, the island and every road come from it
+ * file, the island and every road come from it. `biome` and `timeMode`
+ * colour the map like the ride's 2D view.
*/
-export function drawMapPreview(canvas, { routes, selectedId, colors = MAP_COLORS, network = null, island }) {
+export function drawMapPreview(canvas, { routes, selectedId, colors = MAP_COLORS, network = null, island, biome = "temperate", timeMode = "day", date }) {
const { ctx, width, height } = prepareCanvas(canvas);
- ctx.fillStyle = colors.sea;
+ const theme = rideMapTheme({ biome, timeMode, date, colors });
+ ctx.fillStyle = theme.sea;
ctx.fillRect(0, 0, width, height);
if (!routes.length) return;
const roadNetwork = network ? roadNetworkOf(network) : null;
@@ -99,9 +93,9 @@ export function drawMapPreview(canvas, { routes, selectedId, colors = MAP_COLORS
if (coast.length) {
path(coast, true);
- ctx.fillStyle = colors.land;
+ ctx.fillStyle = theme.land;
ctx.fill();
- ctx.strokeStyle = colors.sand;
+ ctx.strokeStyle = theme.sand;
ctx.lineWidth = 3;
ctx.stroke();
}
@@ -112,7 +106,7 @@ export function drawMapPreview(canvas, { routes, selectedId, colors = MAP_COLORS
routes.forEach((route, i) => {
if (route === selected) return;
path(roads[i], route.loop !== false);
- ctx.strokeStyle = colors.road;
+ ctx.strokeStyle = theme.contextRoad;
ctx.lineWidth = 2;
ctx.stroke();
});
@@ -125,7 +119,8 @@ export function drawMapPreview(canvas, { routes, selectedId, colors = MAP_COLORS
ctx.beginPath();
ctx.moveTo(...frame.toScreen(a.x, -a.y));
ctx.lineTo(...frame.toScreen(b.x, -b.y));
- ctx.strokeStyle = kind === "climb" ? colors.climb : kind === "sprint" ? colors.sprint : colors.accent;
+ const accent = kind === "climb" ? (colors.climb ?? MAP_COLORS.climb) : kind === "sprint" ? (colors.sprint ?? MAP_COLORS.sprint) : (colors.accent ?? MAP_COLORS.accent);
+ ctx.strokeStyle = accent;
ctx.lineWidth = 4;
ctx.stroke();
}
@@ -133,9 +128,9 @@ export function drawMapPreview(canvas, { routes, selectedId, colors = MAP_COLORS
const [sx, sy] = frame.toScreen(start.x, -start.y);
ctx.beginPath();
ctx.arc(sx, sy, 5, 0, Math.PI * 2);
- ctx.fillStyle = colors.start;
+ ctx.fillStyle = colors.start ?? MAP_COLORS.start;
ctx.fill();
- ctx.strokeStyle = colors.sea;
+ ctx.strokeStyle = theme.sea;
ctx.lineWidth = 2;
ctx.stroke();
}
diff --git a/client/public/js/view/pelotonView.js b/client/public/js/view/pelotonView.js
deleted file mode 100644
index 76411f6c..00000000
--- a/client/public/js/view/pelotonView.js
+++ /dev/null
@@ -1,144 +0,0 @@
-import { soloRiders, vehicleMarkers } from "../ride/vehicle.js";
-import { prepareCanvas, riderColor } from "./canvas.js";
-import { isRemote, riderLabel } from "./remoteRiders.js";
-import { t } from "../i18n/i18n.js";
-
-/**
- * Close-up of the road around me: distance runs left to right, lanes are
- * rows. Shows who is drafting whom and lane changes.
- */
-
-export const PELOTON_WINDOW = Object.freeze({ behind: 25, ahead: 45 });
-
-/** Riders within the window, with their signed gap to me. */
-export function ridersInWindow(me, riders, route, window = PELOTON_WINDOW) {
- return riders
- .map((rider) => ({ rider, gap: route.signedGap(me.distance, rider.distance) }))
- .filter(({ gap }) => gap >= -window.behind && gap <= window.ahead);
-}
-
-/** The golden lemons not yet collected within the window, with their signed gap to me. */
-export function lemonsInWindow(me, lemons, route, window = PELOTON_WINDOW) {
- return (lemons ?? [])
- .filter((lemon) => !lemon.collected)
- .map((lemon) => ({ lemon, gap: route.signedGap(me.distance, lemon.distance) }))
- .filter(({ gap }) => gap >= -window.behind && gap <= window.ahead);
-}
-
-/** Body length (m) of a vehicle's marker, against 1.8 m for a bike. */
-export const VEHICLE_LENGTH_M = Object.freeze({ tandem: 2.6, beer_bike: 4.5 });
-
-/**
- * What the peloton shows in the window: each solo rider, and one larger marker
- * per vehicle (at its captain) instead of its seated riders.
- * @returns {{rider: object, gap: number, label: string, lengthM: number, big: boolean, mine: boolean}[]}
- */
-export function pelotonItems(me, riders, route, window = PELOTON_WINDOW) {
- const solo = ridersInWindow(me, soloRiders(riders), route, window).map(({ rider, gap }) => ({
- rider,
- gap,
- label: isRemote(rider) ? riderLabel(rider, t) : rider.is_bot ? `${rider.name} · bot` : rider.name,
- lengthM: 1.8,
- big: false,
- mine: rider.id === me.id,
- }));
- const markers = new Map(vehicleMarkers(riders, me.id).map((m) => [m.rider.id, m]));
- const vehicles = ridersInWindow(me, [...markers.values()].map((m) => m.rider), route, window).map(({ rider, gap }) => {
- const marker = markers.get(rider.id);
- return { rider, gap, label: marker.label, lengthM: VEHICLE_LENGTH_M[marker.kind] ?? 3, big: true, mine: marker.mine };
- });
- return [...solo, ...vehicles];
-}
-
-/** True if two label boxes in the same lane row overlap horizontally (with a small margin). */
-export function overlaps(a, b, margin = 6) {
- return a.row === b.row && a.left < b.right + margin && b.left < a.right + margin;
-}
-
-export function drawPeloton(canvas, { route, riders, me, draft, colors, lemons = [] }) {
- const { ctx, width, height } = prepareCanvas(canvas);
- if (!me) return;
-
- const top = 14;
- const bottom = height - 14;
- const laneHeight = (bottom - top) / route.lanes;
- const span = PELOTON_WINDOW.behind + PELOTON_WINDOW.ahead;
- const x = (gap) => ((gap + PELOTON_WINDOW.behind) / span) * width;
- const y = (lane) => top + (lane + 0.5) * laneHeight;
-
- // Road and lane markings.
- ctx.fillStyle = colors.road;
- ctx.fillRect(0, top, width, bottom - top);
- ctx.strokeStyle = colors.grid;
- ctx.setLineDash([10, 10]);
- for (let lane = 1; lane < route.lanes; lane += 1) {
- const ly = top + lane * laneHeight;
- ctx.beginPath();
- ctx.moveTo(0, ly);
- ctx.lineTo(width, ly);
- ctx.stroke();
- }
- ctx.setLineDash([]);
-
- // Draft zone ahead of me.
- if (draft) {
- ctx.fillStyle = colors.me;
- ctx.globalAlpha = 0.15;
- ctx.fillRect(x(0), y(me.lane) - laneHeight / 2 + 3, x(draft.gap) - x(0), laneHeight - 6);
- ctx.globalAlpha = 1;
- }
-
- // Metre ticks.
- ctx.fillStyle = colors.muted;
- ctx.font = "10px system-ui, sans-serif";
- ctx.textAlign = "center";
- for (let m = -20; m <= 40; m += 10) ctx.fillText(m === 0 ? "you" : `${m > 0 ? "+" : ""}${m} m`, x(m), height - 2);
-
- // Golden lemons in their lanes, under the riders.
- for (const { lemon, gap } of lemonsInWindow(me, lemons, route)) {
- const r = Math.min(7, laneHeight * 0.22);
- ctx.fillStyle = "#ffcc14";
- ctx.beginPath();
- ctx.ellipse(x(gap), y(lemon.lane), r * 1.4, r, 0, 0, Math.PI * 2);
- ctx.fill();
- }
-
- // Riders as capsules (≈ 1.8 m long bikes); a vehicle is one longer, thicker capsule.
- // Draw mine first so my label always wins, then the others closest to me.
- const visible = pelotonItems(me, riders, route).sort((a, b) => b.mine - a.mine || Math.abs(a.gap) - Math.abs(b.gap));
- const labelBoxes = [];
- for (const { rider, gap, label, lengthM, big, mine } of visible) {
- const bikeLength = (lengthM / span) * width;
- const cx = x(gap);
- const cy = y(rider.lane);
- const h = Math.min(big ? 22 : 14, laneHeight * (big ? 0.8 : 0.5));
- ctx.fillStyle = riderColor(rider, me.id, colors);
- ctx.beginPath();
- ctx.roundRect(cx - bikeLength, cy - h / 2, bikeLength, h, h / 2);
- // My best lap's ghost: see-through with a dashed outline.
- ctx.globalAlpha = rider.ghost ? 0.35 : 1;
- ctx.fill();
- ctx.globalAlpha = 1;
- if (rider.ghost) {
- ctx.strokeStyle = colors.text;
- ctx.lineWidth = 1;
- ctx.setLineDash([3, 3]);
- ctx.stroke();
- ctx.setLineDash([]);
- }
- if (mine) {
- ctx.strokeStyle = colors.text;
- ctx.lineWidth = 2;
- ctx.stroke();
- }
- ctx.font = `${mine ? "600 " : ""}11px system-ui, sans-serif`;
- const labelWidth = ctx.measureText(label).width;
- const labelBox = { left: cx - bikeLength / 2 - labelWidth / 2, right: cx - bikeLength / 2 + labelWidth / 2, row: Math.round(rider.lane) };
- if (mine || !labelBoxes.some((box) => overlaps(box, labelBox))) {
- labelBoxes.push(labelBox);
- ctx.fillStyle = colors.text;
- ctx.textAlign = "center";
- ctx.fillText(label, cx - bikeLength / 2, cy - h / 2 - 4);
- }
- }
-}
diff --git a/client/public/js/view/rideMapDecor.js b/client/public/js/view/rideMapDecor.js
new file mode 100644
index 00000000..da6a1592
--- /dev/null
+++ b/client/public/js/view/rideMapDecor.js
@@ -0,0 +1,213 @@
+/**
+ * Small map symbols for the 2D ride view: tree dots in and near the forests,
+ * and outline buildings along the villages and at the cafés.
+ *
+ * The 3D world builds trees and houses as meshes, which the 2D view cannot
+ * (and must not) reuse: it runs before the world is built and on devices
+ * without WebGL. This layer uses the route's existing scenery zones and the
+ * map's cafés, so the symbols line up with the roads without a second request.
+ * It is generated once per map and culled to the view each frame, and its
+ * colours always come from the view's theme (the biome's 2D palette).
+ */
+import { seededRandom } from "../view3d/noise.js";
+import { LANE_WIDTH, SHOULDER } from "../view3d/world.js";
+import { inStretch, resolveZones } from "../view3d/zones.js";
+
+const PAVEMENT = 2.4;
+const CAFE_DISTANCE = 45;
+const CAFE_SETBACK = 14;
+
+/** Half the asphalt, shoulders included, from the road's centre line. */
+const roadHalfWidth = (lanes) => (lanes * LANE_WIDTH) / 2 + SHOULDER;
+
+/** Position and 2D direction of the road at `distance`; right is the right-hand side of travel. */
+export function frameAt(route, distance) {
+ const point = route.positionAt(distance);
+ const before = route.positionAt(distance - 2);
+ const after = route.positionAt(distance + 2);
+ const dx = after.x - before.x;
+ const dy = after.y - before.y;
+ const length = Math.hypot(dx, dy);
+ if (length < 1e-9) return { point, forward: { x: 0, y: 1 }, right: { x: 1, y: 0 } };
+ const forward = { x: dx / length, y: dy / length };
+ return { point, forward, right: { x: forward.y, y: -forward.x } };
+}
+
+const angleOf = (frame) => Math.atan2(frame.forward.y, frame.forward.x);
+
+const offsetPoint = (frame, side, metres) => ({
+ x: frame.point.x + frame.right.x * side * metres,
+ y: frame.point.y + frame.right.y * side * metres,
+});
+
+const cache = new WeakMap();
+
+/**
+ * All decorations of a map (or a single route without a map), generated once.
+ * @returns {{ trees: {x: number, y: number, r: number, shade: number}[], buildings: {x: number, y: number, w: number, d: number, angle: number, kind: "house"|"cafe"}[] }}
+ */
+export function roadDecorations(route, network = null) {
+ const key = network ?? route;
+ let decorations = cache.get(key);
+ if (!decorations) {
+ decorations = build(route, network);
+ cache.set(key, decorations);
+ }
+ return decorations;
+}
+
+function build(route, network) {
+ const roads = network ? network.roads() : [route];
+ const zones = new Map(roads.map((road) => [road, resolveZones(road)]));
+ const buildings = [];
+ const cafes = [];
+ if (network) {
+ for (const cafe of network.cafes()) {
+ const road = network.roadFrom(cafe.id);
+ if (road) addCafe(road, buildings, cafes, network);
+ }
+ } else {
+ addCafe(route, buildings, cafes, null);
+ }
+ for (const road of roads) {
+ for (const zone of zones.get(road).villages) addVillage(road, zone, buildings, cafes, network);
+ }
+ const trees = [];
+ for (const road of roads) addTrees(road, zones.get(road), buildings, trees, network);
+ return { trees, buildings };
+}
+
+function addCafe(road, buildings, cafes, network) {
+ const frame = frameAt(road, CAFE_DISTANCE);
+ const center = offsetPoint(frame, 1, roadHalfWidth(road.lanes) + CAFE_SETBACK);
+ if (network && network.heightAt(center.x, center.y) < 2.5) return;
+ if (cafes.some((cafe) => Math.hypot(cafe.x - center.x, cafe.y - center.y) < 30)) return;
+ cafes.push(center);
+ buildings.push({ x: center.x, y: center.y, w: 12, d: 8.5, angle: angleOf(frame), kind: "cafe" });
+}
+
+function addVillage(road, zone, buildings, cafes, network) {
+ const random = seededRandom((road.seed >>> 0) ^ Math.round(zone.from * 7));
+ const half = roadHalfWidth(road.lanes);
+ for (const side of [-1, 1]) {
+ let d = zone.from + 8 + random() * 6;
+ while (d < zone.to - 6) {
+ const frame = frameAt(road, d);
+ const depth = 9;
+ const setback = half + PAVEMENT + 2.5 + random() * 3.5 + depth / 2;
+ const center = offsetPoint(frame, side, setback);
+ const nearCafe = cafes.some((cafe) => Math.hypot(cafe.x - center.x, cafe.y - center.y) < 16);
+ const inWater = network && network.heightAt(center.x, center.y) < 2.5;
+ if (!inWater && !nearCafe && random() < 0.88) {
+ buildings.push({
+ x: center.x,
+ y: center.y,
+ w: 7 + random() * 3.5,
+ d: 6 + random() * 3,
+ angle: angleOf(frame),
+ kind: "house",
+ });
+ }
+ d += 13 + random() * 7;
+ }
+ }
+}
+
+function addTrees(road, zones, buildings, trees, network) {
+ const random = seededRandom((road.seed >>> 0) ^ 0x7ee5);
+ const half = roadHalfWidth(road.lanes);
+ const minOffset = half + 1.1 + 3; // beyond the verge, clear of the road
+ const add = (frame, side, offset, along, forest) => {
+ const center = {
+ x: frame.point.x + frame.right.x * side * offset + frame.forward.x * along,
+ y: frame.point.y + frame.right.y * side * offset + frame.forward.y * along,
+ };
+ if (network && network.heightAt(center.x, center.y) < 2.5) return; // sea and beach
+ // Crown radius in metres; the view scales it with the map's zoom.
+ const radius = forest ? 1.4 + random() * 0.7 : 1.1 + random() * 0.6;
+ const clear = buildings.some((house) => Math.hypot(house.x - center.x, house.y - center.y) < Math.max(house.w, house.d) / 2 + 4);
+ if (clear) return;
+ trees.push({ x: center.x, y: center.y, r: radius, shade: random() < 0.5 ? 0 : 1 });
+ };
+ for (const forest of zones.forests) {
+ for (let d = forest.from; d < forest.to; d += 7) {
+ if (random() > 0.85) continue;
+ const frame = frameAt(road, d);
+ const side = random() < 0.5 ? -1 : 1;
+ const offset = minOffset + 2 + Math.pow(random(), 1.4) * 36;
+ const count = 2 + Math.floor(random() * 3);
+ for (let i = 0; i < count; i += 1) {
+ add(frame, side, offset + (random() - 0.5) * 3, (random() - 0.5) * 7, true);
+ }
+ }
+ }
+ for (let d = 0; d < road.length; d += 3) {
+ if (inStretch(road, zones.villages, d, 20)) continue;
+ if (random() < 0.55) {
+ const frame = frameAt(road, d);
+ add(frame, random() < 0.5 ? -1 : 1, minOffset + Math.pow(random(), 1.5) * 34, 0, false);
+ }
+ }
+}
+
+const CULL_RADIUS = 220;
+
+function buildingPoint(building, camera, forwardOffset, rightOffset) {
+ const cos = Math.cos(building.angle);
+ const sin = Math.sin(building.angle);
+ return camera.toScreen({
+ x: building.x + cos * forwardOffset + sin * rightOffset,
+ y: building.y + sin * forwardOffset - cos * rightOffset,
+ });
+}
+
+function buildingCorners(building, camera) {
+ const w = building.w / 2;
+ const d = building.d / 2;
+ return [
+ buildingPoint(building, camera, -w, -d),
+ buildingPoint(building, camera, w, -d),
+ buildingPoint(building, camera, w, d),
+ buildingPoint(building, camera, -w, d),
+ ];
+}
+
+/** Draws the decorations under the roads, culled to the view. */
+export function drawDecorations(ctx, { decorations, camera, width, height, theme }) {
+ const { center } = camera;
+ for (const tree of decorations.trees) {
+ if (Math.hypot(tree.x - center.x, tree.y - center.y) > CULL_RADIUS) continue;
+ // Tree radii are metres; at any zoom a dot is never smaller than eye can see.
+ const radius = Math.max(1.5, tree.r * camera.scale);
+ const point = camera.toScreen(tree);
+ if (point.x < -radius || point.x > width + radius || point.y < -radius || point.y > height + radius) continue;
+ ctx.beginPath();
+ ctx.arc(point.x, point.y, radius, 0, Math.PI * 2);
+ ctx.fillStyle = theme.trees[tree.shade] ?? theme.trees[0];
+ ctx.fill();
+ }
+ for (const building of decorations.buildings) {
+ if (Math.hypot(building.x - center.x, building.y - center.y) > CULL_RADIUS + Math.max(building.w, building.d)) continue;
+ const points = buildingCorners(building, camera);
+ const xs = points.map((p) => p.x);
+ const ys = points.map((p) => p.y);
+ if (Math.max(...xs) < -20 || Math.min(...xs) > width + 20 || Math.max(...ys) < -20 || Math.min(...ys) > height + 20) continue;
+ ctx.beginPath();
+ points.forEach((p, index) => (index === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y)));
+ ctx.closePath();
+ const cafe = building.kind === "cafe";
+ ctx.fillStyle = cafe ? theme.cafeFill : theme.houseFill;
+ ctx.fill();
+ ctx.strokeStyle = cafe ? theme.cafeEdge : theme.houseEdge;
+ ctx.lineWidth = cafe ? 1.5 : 1;
+ ctx.stroke();
+ const ridgeStart = buildingPoint(building, camera, -building.w / 2, 0);
+ const ridgeEnd = buildingPoint(building, camera, building.w / 2, 0);
+ ctx.beginPath();
+ ctx.moveTo(ridgeStart.x, ridgeStart.y);
+ ctx.lineTo(ridgeEnd.x, ridgeEnd.y);
+ ctx.strokeStyle = cafe ? theme.cafeRidge : theme.houseRidge;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ }
+}
diff --git a/client/public/js/view/rideMapTheme.js b/client/public/js/view/rideMapTheme.js
new file mode 100644
index 00000000..d9693083
--- /dev/null
+++ b/client/public/js/view/rideMapTheme.js
@@ -0,0 +1,106 @@
+/**
+ * The 2D map's colours: the season's ground, water, road and scenery, tinted by
+ * the time of day like the 3D world.
+ *
+ * The map has its own palette because it draws symbols instead of meshes, but
+ * it takes the same inputs as the world: the biome registry supplies the season
+ * (its `map` and `flora.mapColors` are the single source of the season's map
+ * colours, in 0–1 RGB arrays like every other biome colour) and the lighting
+ * presets supply the light. Pure data and pure functions, so a render and a
+ * test can agree on exactly what a winter dusk looks like.
+ */
+import { resolveBiome } from "../view3d/biomes/index.js";
+import { TIME_MODES, resolvePreset, resolvedLight } from "../view3d/lighting.js";
+
+/** The start menu's map palette, kept from the original top-down map. */
+export const MAP_COLORS = Object.freeze({
+ sea: "#163a4e",
+ land: "#2d5b3b",
+ sand: "#cdb98a",
+ road: "rgba(232, 236, 241, 0.5)",
+ accent: "#ff7a1a",
+ climb: "#ff5d5d",
+ sprint: "#4cc3ff",
+ start: "#ffd21f",
+});
+
+/** How strongly each time of day does what to the map. */
+const TIME_TINT = Object.freeze({
+ golden: Object.freeze({ amount: 0.18, dim: 0.96 }),
+ dusk: Object.freeze({ amount: 0.34, dim: 0.74 }),
+});
+
+/** Reads a hex, `rgb()`/`rgba()` string or 0–1 RGB array into channels. */
+function parseColor(value) {
+ if (Array.isArray(value)) return { r: value[0] * 255, g: value[1] * 255, b: value[2] * 255, a: value[3] ?? 1 };
+ const hex = /^#([0-9a-f]{6})$/i.exec(value);
+ if (hex) {
+ const number = Number.parseInt(hex[1], 16);
+ return { r: (number >> 16) & 255, g: (number >> 8) & 255, b: number & 255, a: 1 };
+ }
+ const channels = value.match(/[\d.]+/g)?.map(Number) ?? [0, 0, 0];
+ return { r: channels[0], g: channels[1], b: channels[2], a: channels[3] ?? 1 };
+}
+
+function formatColor({ r, g, b, a }) {
+ if (a >= 1) return `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`;
+ return `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${Math.round(a * 100) / 100})`;
+}
+
+/** Blends a colour towards the light's tint and dims it; day leaves the channels. */
+function lit(color, tint, { amount, dim }, alpha = 1) {
+ const base = parseColor(color);
+ if (!amount) return formatColor({ ...base, a: base.a * alpha });
+ return formatColor({
+ r: (base.r * (1 - amount) + tint[0] * 255 * amount) * dim,
+ g: (base.g * (1 - amount) + tint[1] * 255 * amount) * dim,
+ b: (base.b * (1 - amount) + tint[2] * 255 * amount) * dim,
+ a: base.a * alpha,
+ });
+}
+
+/**
+ * The palette for one frame of the 2D map.
+ * @param {{biome?: string, timeMode?: string, date?: Date, colors?: object}} options
+ * `colors` are the HUD's theme colours, used for the road and lane markings
+ * when the biome does not paint its own.
+ * @returns {object} CSS colours for the ground, water, roads, scenery and buildings
+ */
+export function rideMapTheme({ biome = "temperate", timeMode = "day", date, colors = {} } = {}) {
+ const season = resolveBiome(biome);
+ const map = season.map ?? {};
+ const mode = TIME_MODES.includes(timeMode) ? timeMode : "day";
+ const preset = resolvePreset(mode, date);
+ const light = resolvedLight(preset, season);
+ const tint = preset.key === "dusk" ? light.horizon : light.sunColor;
+ const tinting = TIME_TINT[preset.key] ?? { amount: 0, dim: 1 };
+
+ const building = (kind) => {
+ const spec = map[kind];
+ return {
+ fill: lit(spec.fill, tint, tinting, spec.fillAlpha),
+ edge: lit(spec.edge, tint, tinting, spec.edgeAlpha),
+ ridge: lit(spec.ridge, tint, tinting, spec.ridgeAlpha),
+ };
+ };
+ const house = building("house");
+ const cafe = building("cafe");
+
+ return {
+ land: lit(map.land ?? MAP_COLORS.land, tint, tinting),
+ sea: lit(map.sea ?? MAP_COLORS.sea, tint, tinting),
+ sand: lit(map.sand ?? MAP_COLORS.sand, tint, tinting),
+ road: lit(map.road ?? colors.road ?? MAP_COLORS.road, tint, tinting),
+ contextRoad: lit(map.contextRoad ?? colors.muted ?? MAP_COLORS.road, tint, tinting),
+ marking: lit(map.marking ?? colors.text ?? MAP_COLORS.road, tint, tinting),
+ edge: lit(map.edge ?? colors.text ?? MAP_COLORS.road, tint, tinting),
+ trees: (season.flora?.mapColors ?? []).map((tree) => lit(tree, tint, tinting)),
+ houseFill: house.fill,
+ houseEdge: house.edge,
+ houseRidge: house.ridge,
+ cafeFill: cafe.fill,
+ cafeEdge: cafe.edge,
+ cafeRidge: cafe.ridge,
+ time: preset.key,
+ };
+}
diff --git a/client/public/js/view/rideMapView.js b/client/public/js/view/rideMapView.js
new file mode 100644
index 00000000..9f0d0c7b
--- /dev/null
+++ b/client/public/js/view/rideMapView.js
@@ -0,0 +1,446 @@
+/**
+ * The ride's 2D view: a top-down map of the road around the rider.
+ *
+ * The rider sits mid-screen heading up, so roughly half the map is the road
+ * ahead. The map draws the island (when the road network is known), every
+ * road once, the road being ridden with its lane markings, the golden lemons
+ * still on the road, the draft gap ahead of me when I am drafting, and the
+ * riders around me — including my best lap's ghost. It uses the same
+ * route/rider data as the 3D view, so a device without WebGL 2 can still
+ * follow the ride.
+ */
+import { soloRiders, vehicleMarkers } from "../ride/vehicle.js";
+import { t } from "../i18n/i18n.js";
+import { LANE_WIDTH, SHOULDER } from "../view3d/world.js";
+import { prepareCanvas, riderColor } from "./canvas.js";
+import { coastOutline } from "./mapPreview.js";
+import { riderLabel } from "./remoteRiders.js";
+import { drawDecorations, roadDecorations } from "./rideMapDecor.js";
+import { rideMapTheme } from "./rideMapTheme.js";
+
+/** How much road the canvas height shows, and where on it the rider sits.
+ * The rider sits mid-screen: in the cockpit layout the paddle meter overlays
+ * the lower third, and the arrow must stay clear of its hint card. */
+export const MAP_VIEW = Object.freeze({ spanM: 120, riderY: 0.5 });
+
+/** Width of the 3D road's edge stripe (metres). */
+const EDGE_LINE = 0.12;
+
+/** Offset of a lane centre from the road's centre line; lane 0 is the leftmost. */
+export function laneOffset(lane, lanes) {
+ return (lane - (lanes - 1) / 2) * LANE_WIDTH;
+}
+
+/** World point (x, y) of a lane at `distance`. */
+export function roadPointAt(route, distance, lane) {
+ const point = route.positionAt(distance);
+ if (lane === null || lane === undefined) return point;
+ // The road's direction at this point; the normal is the right-hand side of travel.
+ const before = route.positionAt(distance - 2);
+ const after = route.positionAt(distance + 2);
+ const dx = after.x - before.x;
+ const dy = after.y - before.y;
+ const length = Math.hypot(dx, dy);
+ if (length < 1e-9) return point;
+ const offset = laneOffset(lane, route.lanes);
+ return { x: point.x + (dy / length) * offset, y: point.y - (dx / length) * offset };
+}
+
+/**
+ * A heading-up camera: travel points up the screen, the rider sits `riderY` of
+ * the height down, and the world is scaled so the canvas height spans `spanM`.
+ * @returns {{ center: object, angle: number, scale: number, rider: {x: number, y: number}, toScreen: (point: object) => {x: number, y: number}, fromScreen: (point: object) => {x: number, y: number} }}
+ */
+export function mapCamera(route, me, width, height, { spanM = MAP_VIEW.spanM, riderY = MAP_VIEW.riderY } = {}) {
+ const center = roadPointAt(route, me.distance, me.lane);
+ const before = route.positionAt(me.distance - 2);
+ const after = route.positionAt(me.distance + 2);
+ const dx = after.x - before.x;
+ const dy = after.y - before.y;
+ // Screen y points down and north is +y in world space: turn east into "up".
+ const angle = Math.hypot(dx, dy) > 1e-9 ? Math.atan2(dx, dy) : 0;
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const scale = Math.max(2.5, height / Math.max(1, spanM));
+ const rx = width / 2;
+ const ry = height * riderY;
+ const toScreen = ({ x, y }) => {
+ const sx = (x - center.x) * scale;
+ const sy = -(y - center.y) * scale;
+ return { x: rx + sx * cos + sy * sin, y: ry - sx * sin + sy * cos };
+ };
+ const fromScreen = ({ x, y }) => {
+ const dx = x - rx;
+ const dy = y - ry;
+ const sx = dx * cos - dy * sin;
+ const sy = dx * sin + dy * cos;
+ return { x: center.x + sx / scale, y: center.y - sy / scale };
+ };
+ return { center, angle, scale, rider: { x: rx, y: ry }, toScreen, fromScreen };
+}
+
+/** The route's centre line moved `metres` to the right of travel. */
+export function offsetNodes(route, metres) {
+ const nodes = route.nodes;
+ const count = route.loop ? nodes.length - 1 : nodes.length;
+ const out = [];
+ for (let i = 0; i < count; i += 1) {
+ const before = nodes[route.loop ? (i - 1 + count) % count : Math.max(0, i - 1)];
+ const after = nodes[route.loop ? (i + 1) % count : Math.min(count - 1, i + 1)];
+ const dx = after.x - before.x;
+ const dy = after.y - before.y;
+ const length = Math.hypot(dx, dy);
+ const node = nodes[i];
+ if (length < 1e-9) out.push({ x: node.x, y: node.y });
+ else out.push({ x: node.x + (dy / length) * metres, y: node.y - (dx / length) * metres });
+ }
+ if (route.loop && out.length) out.push({ x: out[0].x, y: out[0].y });
+ return out;
+}
+
+/** A route's offset lines never change: compute each offset once, reuse per frame. */
+const offsetCache = new WeakMap();
+
+/** `offsetNodes` through the per-route cache; drawMarkings uses this each frame. */
+export function cachedOffsetNodes(route, metres) {
+ let perRoute = offsetCache.get(route);
+ if (!perRoute) {
+ perRoute = new Map();
+ offsetCache.set(route, perRoute);
+ }
+ let nodes = perRoute.get(metres);
+ if (!nodes) {
+ nodes = offsetNodes(route, metres);
+ perRoute.set(metres, nodes);
+ }
+ return nodes;
+}
+
+/** One mark per solo rider and per vehicle, labelled as in the rest of the HUD. */
+export function mapRiderMarks(riders, myId) {
+ const solo = soloRiders(riders).map((rider) => ({
+ rider,
+ label: riderLabel(rider, t),
+ big: false,
+ mine: rider.id === myId,
+ }));
+ const vehicles = vehicleMarkers(riders, myId).map((marker) => ({ rider: marker.rider, label: marker.label, big: true, mine: marker.mine }));
+ return [...solo, ...vehicles];
+}
+
+const coastCache = new WeakMap();
+
+/** The network's coast, as world [x, z] points, computed once per map. */
+function coastOf(network) {
+ let coast = coastCache.get(network);
+ if (!coast) {
+ coast = coastOutline(network.island(), 240);
+ coastCache.set(network, coast);
+ }
+ return coast;
+}
+
+const roadWidth = (route) => route.lanes * LANE_WIDTH + 2 * SHOULDER;
+
+function strokePath(ctx, camera, points, { color, width, dash = null }) {
+ if (!points?.length) return;
+ ctx.beginPath();
+ points.forEach((point, index) => {
+ const screen = camera.toScreen(point);
+ if (index === 0) ctx.moveTo(screen.x, screen.y);
+ else ctx.lineTo(screen.x, screen.y);
+ });
+ ctx.strokeStyle = color;
+ ctx.lineWidth = width;
+ if (dash) ctx.setLineDash(dash);
+ ctx.stroke();
+ if (dash) ctx.setLineDash([]);
+}
+
+function drawGround(ctx, { network, width, height, theme }) {
+ if (!network) {
+ ctx.fillStyle = theme.land;
+ ctx.fillRect(0, 0, width, height);
+ return null;
+ }
+ ctx.fillStyle = theme.sea;
+ ctx.fillRect(0, 0, width, height);
+ return coastOf(network);
+}
+
+function landPath(ctx, camera, coast) {
+ ctx.beginPath();
+ coast.forEach(([x, z], index) => {
+ // The map's world y is -z (the same convention as the start menu's map).
+ const screen = camera.toScreen({ x, y: -z });
+ if (index === 0) ctx.moveTo(screen.x, screen.y);
+ else ctx.lineTo(screen.x, screen.y);
+ });
+ ctx.closePath();
+}
+
+const heightRangeCache = new WeakMap();
+
+/** The network's lowest and highest terrain, in metres. */
+function heightRange(network) {
+ let range = heightRangeCache.get(network);
+ if (!range) {
+ let min = Infinity;
+ let max = -Infinity;
+ for (const value of network.heights) {
+ if (value < min) min = value;
+ if (value > max) max = value;
+ }
+ const scale = network.grid.scale;
+ range = { min: min * scale, max: max * scale };
+ heightRangeCache.set(network, range);
+ }
+ return range;
+}
+
+/** Brightness for a terrain cell: a hill facing north-west is lighter, higher ground slightly warmer. */
+function terrainShade(network, x, y, range) {
+ const step = 6;
+ const dx = network.heightAt(x + step, y) - network.heightAt(x - step, y);
+ const dy = network.heightAt(x, y + step) - network.heightAt(x, y - step);
+ const slope = Math.max(-1, Math.min(1, (dx - dy) * 0.8));
+ const high = (network.heightAt(x, y) - range.min) / Math.max(1, range.max - range.min);
+ return Math.max(0.68, Math.min(1.3, 1 + slope * 0.42 + (high - 0.5) * 0.24));
+}
+
+function shadeColor(color, factor) {
+ const channels = /^rgb\((\d+), (\d+), (\d+)\)$/.exec(color);
+ const [r, g, b] = channels
+ ? channels.slice(1).map(Number)
+ : (() => {
+ const value = Number.parseInt(color.slice(1), 16);
+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
+ })();
+ const channel = (value) => Math.max(0, Math.min(255, Math.round(value * factor)));
+ return `rgb(${channel(r)}, ${channel(g)}, ${channel(b)})`;
+}
+
+let terrainSurface = null;
+
+/** Sparse terrain relief, sampled in world space on screen-space cells and smoothed up. */
+function drawTerrain(ctx, { canvas, network, camera, width, height, theme }) {
+ const range = heightRange(network);
+ const cell = Math.max(24, Math.floor(Math.min(width, height) / 30));
+ const columns = Math.ceil(width / cell);
+ const rows = Math.ceil(height / cell);
+ const doc = canvas.ownerDocument;
+ if (!doc) {
+ // Unit tests draw into a fake canvas without a document: keep the cells.
+ for (let row = 0; row < rows; row += 1) {
+ for (let column = 0; column < columns; column += 1) {
+ const world = camera.fromScreen({ x: column * cell + cell / 2, y: row * cell + cell / 2 });
+ ctx.fillStyle = shadeColor(theme.land, terrainShade(network, world.x, world.y, range));
+ ctx.fillRect(column * cell, row * cell, cell + 1, cell + 1);
+ }
+ }
+ return;
+ }
+ terrainSurface ??= doc.createElement("canvas");
+ if (terrainSurface.width !== columns || terrainSurface.height !== rows) {
+ terrainSurface.width = columns;
+ terrainSurface.height = rows;
+ }
+ const surface = terrainSurface.getContext("2d");
+ for (let row = 0; row < rows; row += 1) {
+ for (let column = 0; column < columns; column += 1) {
+ const world = camera.fromScreen({ x: column * cell + cell / 2, y: row * cell + cell / 2 });
+ surface.fillStyle = shadeColor(theme.land, terrainShade(network, world.x, world.y, range));
+ surface.fillRect(column, row, 1, 1);
+ }
+ }
+ ctx.imageSmoothingEnabled = true;
+ ctx.drawImage(terrainSurface, 0, 0, columns, rows, 0, 0, columns * cell, rows * cell);
+}
+
+function contextRoads({ network, routes, route }) {
+ const roads = network ? network.roads() : routes ? [...(routes instanceof Map ? routes.values() : routes)] : [];
+ return roads.filter((road) => road !== route && road.id !== route.id);
+}
+
+/** A road's world bounding box, computed once per road. */
+const boundsCache = new WeakMap();
+
+function roadBounds(road) {
+ let bounds = boundsCache.get(road);
+ if (!bounds) {
+ let minX = Infinity;
+ let maxX = -Infinity;
+ let minY = Infinity;
+ let maxY = -Infinity;
+ for (const { x, y } of road.nodes) {
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ }
+ bounds = { minX, maxX, minY, maxY };
+ boundsCache.set(road, bounds);
+ }
+ return bounds;
+}
+
+/** The world rectangle the camera shows, with a margin for line widths. */
+function viewRect(camera, width, height) {
+ const corners = [camera.fromScreen({ x: 0, y: 0 }), camera.fromScreen({ x: width, y: 0 }), camera.fromScreen({ x: 0, y: height }), camera.fromScreen({ x: width, y: height })];
+ const xs = corners.map((corner) => corner.x);
+ const ys = corners.map((corner) => corner.y);
+ const margin = 20;
+ return { minX: Math.min(...xs) - margin, maxX: Math.max(...xs) + margin, minY: Math.min(...ys) - margin, maxY: Math.max(...ys) + margin };
+}
+
+const outside = (bounds, view) => bounds.maxX < view.minX || bounds.minX > view.maxX || bounds.maxY < view.minY || bounds.minY > view.maxY;
+
+function drawRoads(ctx, { network, routes, route, camera, theme, width, height }) {
+ ctx.lineJoin = "round";
+ ctx.lineCap = "round";
+ // Other roads are context only: thin lines under the road being ridden,
+ // skipped whole when they lie outside the view.
+ const view = viewRect(camera, width, height);
+ ctx.globalAlpha = 0.7;
+ for (const road of contextRoads({ network, routes, route })) {
+ if (outside(roadBounds(road), view)) continue;
+ strokePath(ctx, camera, road.nodes, { color: theme.contextRoad, width: Math.max(2, camera.scale * 0.45) });
+ }
+ ctx.globalAlpha = 1;
+ strokePath(ctx, camera, route.nodes, { color: theme.road, width: roadWidth(route) * camera.scale });
+}
+
+function drawMarkings(ctx, route, camera, theme) {
+ const scale = camera.scale;
+ const line = Math.max(1, 0.12 * scale);
+ for (const side of [-1, 1]) {
+ const offset = side * (route.lanes * LANE_WIDTH) / 2 - side * EDGE_LINE / 2;
+ strokePath(ctx, camera, cachedOffsetNodes(route, offset), { color: theme.edge, width: line });
+ }
+ // Below a few pixels a lane divider is noise, not information.
+ if (LANE_WIDTH * scale < 4) return;
+ for (let lane = 1; lane < route.lanes; lane += 1) {
+ const offset = (lane - route.lanes / 2) * LANE_WIDTH;
+ strokePath(ctx, camera, cachedOffsetNodes(route, offset), { color: theme.marking, width: line, dash: [3 * scale, 3 * scale] });
+ }
+}
+
+/** Golden lemons along the road, under the riders, collected ones gone. */
+function drawLemons(ctx, { route, lemons, camera, width, height }) {
+ for (const lemon of lemons) {
+ if (lemon.collected) continue;
+ const screen = camera.toScreen(roadPointAt(route, lemon.distance, lemon.lane));
+ if (screen.x < -10 || screen.x > width + 10 || screen.y < -10 || screen.y > height + 10) continue;
+ ctx.fillStyle = "#ffcc14";
+ ctx.beginPath();
+ ctx.ellipse(screen.x, screen.y, 7, 5, 0, 0, Math.PI * 2);
+ ctx.fill();
+ }
+}
+
+/** The draft gap, as a soft band from me to the rider ahead (as the lane strip drew it). */
+function drawDraft(ctx, { route, me, draft, camera, colors }) {
+ if (!me || !draft || !(draft.gap > 0)) return;
+ const steps = Math.max(2, Math.ceil(draft.gap / 2));
+ const points = [];
+ for (let i = 0; i <= steps; i += 1) points.push(roadPointAt(route, me.distance + (draft.gap * i) / steps, me.lane));
+ ctx.globalAlpha = 0.18;
+ strokePath(ctx, camera, points, { color: colors.me, width: LANE_WIDTH * 0.8 * camera.scale });
+ ctx.globalAlpha = 1;
+}
+
+const overlaps = (a, b, margin = 4) =>
+ a.left < b.right + margin && b.left < a.right + margin && a.top < b.bottom + margin && b.top < a.bottom + margin;
+
+function drawRiders(ctx, { route, riders, me, myId, camera, colors, width, height }) {
+ const marks = mapRiderMarks(riders, myId);
+ const boxes = [];
+ ctx.textAlign = "center";
+ ctx.textBaseline = "alphabetic";
+ ctx.font = "11px system-ui, sans-serif";
+ // My label is drawn with the arrow; reserve its box so another name does not sit on it.
+ if (me) {
+ const labelWidth = ctx.measureText(me.name).width;
+ boxes.push({ left: camera.rider.x - labelWidth / 2, right: camera.rider.x + labelWidth / 2, top: camera.rider.y - 30, bottom: camera.rider.y - 18 });
+ }
+ for (const mark of marks) {
+ const screen = camera.toScreen(roadPointAt(route, mark.rider.distance, mark.rider.lane));
+ if (screen.x < -40 || screen.x > width + 40 || screen.y < -40 || screen.y > height + 40) continue;
+ const radius = mark.big ? 6 : 4;
+ ctx.beginPath();
+ ctx.arc(screen.x, screen.y, radius, 0, Math.PI * 2);
+ ctx.fillStyle = riderColor(mark.rider, myId, colors);
+ if (mark.rider.ghost) {
+ // My best lap's ghost: see-through with a dashed outline.
+ ctx.globalAlpha = 0.35;
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ ctx.strokeStyle = colors.text;
+ ctx.lineWidth = 1;
+ ctx.setLineDash([3, 3]);
+ ctx.stroke();
+ ctx.setLineDash([]);
+ } else {
+ ctx.fill();
+ }
+ if (mark.big) {
+ ctx.strokeStyle = colors.text;
+ ctx.lineWidth = 1.5;
+ ctx.stroke();
+ }
+ if (mark.rider.id === myId) continue; // my arrow carries my name
+ const labelWidth = ctx.measureText(mark.label).width;
+ const box = { left: screen.x - labelWidth / 2, right: screen.x + labelWidth / 2, top: screen.y - radius - 16, bottom: screen.y - radius - 4 };
+ if (boxes.some((other) => overlaps(other, box))) continue;
+ boxes.push(box);
+ ctx.fillStyle = colors.text;
+ ctx.fillText(mark.label, screen.x, screen.y - radius - 4);
+ }
+
+ // Me: an arrow pointing up (the camera is heading-up and centred on me).
+ if (!me) return;
+ const { x, y } = camera.rider;
+ ctx.beginPath();
+ ctx.moveTo(x, y - 12);
+ ctx.lineTo(x - 7, y + 7);
+ ctx.lineTo(x + 7, y + 7);
+ ctx.closePath();
+ ctx.fillStyle = colors.me;
+ ctx.fill();
+ ctx.strokeStyle = colors.text;
+ ctx.lineWidth = 2.5;
+ ctx.stroke();
+ ctx.fillStyle = colors.text;
+ ctx.fillText(me.name, x, y - 18);
+}
+
+export function drawRideMap(canvas, { route, riders = [], me = null, draft = null, lemons = [], colors, network = null, routes = null, biome = "temperate", timeMode = "day", date }) {
+ const { ctx, width, height } = prepareCanvas(canvas);
+ if (!route) return;
+ const theme = rideMapTheme({ biome, timeMode, date, colors });
+ const at = me ?? { distance: 0, lane: (route.lanes - 1) / 2 };
+ const camera = mapCamera(route, at, width, height);
+ const coast = drawGround(ctx, { network, width, height, theme });
+ if (coast) {
+ landPath(ctx, camera, coast);
+ ctx.fillStyle = theme.land;
+ ctx.fill();
+ if (coast.length >= 3) {
+ ctx.save();
+ landPath(ctx, camera, coast);
+ ctx.clip();
+ drawTerrain(ctx, { canvas, network, camera, width, height, theme });
+ ctx.restore();
+ }
+ landPath(ctx, camera, coast);
+ ctx.strokeStyle = theme.sand;
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ }
+ drawDecorations(ctx, { decorations: roadDecorations(route, network), camera, width, height, theme });
+ drawRoads(ctx, { network, routes, route, camera, theme, width, height });
+ drawMarkings(ctx, route, camera, theme);
+ drawDraft(ctx, { route, me, draft, camera, colors });
+ drawLemons(ctx, { route, lemons, camera, width, height });
+ drawRiders(ctx, { route, riders, me, myId: me?.id ?? null, camera, colors, width, height });
+}
diff --git a/client/public/js/view/workoutStudioView.js b/client/public/js/view/workoutStudioView.js
index 47382faa..5354b8a2 100644
--- a/client/public/js/view/workoutStudioView.js
+++ b/client/public/js/view/workoutStudioView.js
@@ -11,7 +11,7 @@ const exerciseDuration = (plan) => plan.blocks.reduce((sum, block) => sum + (blo
/**
* The view a screen opens in: the workout is the 3D gym whatever 2D/3D
- * preference was saved (its HUD sits on the world, the 2D peloton has nothing
+ * preference was saved (its HUD sits on the world, the 2D map has nothing
* to show), the ride follows the saved preference.
*/
export function startingViewMode(saved, { workout = false } = {}) {
diff --git a/client/public/js/view3d/biomes/temperate.js b/client/public/js/view3d/biomes/temperate.js
index 2e837d38..2d2709b9 100644
--- a/client/public/js/view3d/biomes/temperate.js
+++ b/client/public/js/view3d/biomes/temperate.js
@@ -252,6 +252,25 @@ export const temperate = Object.freeze({
farIslandDark: COLORS.farIslandDark,
rock: COLORS.rock,
sand: SAND,
+ /** Colours of the 2D map's symbols: buildings and their outlines (0–1 RGB like the rest). */
+ map: Object.freeze({
+ house: Object.freeze({
+ fill: Object.freeze([0.455, 0.298, 0.22]),
+ fillAlpha: 0.46,
+ edge: Object.freeze([0.847, 0.78, 0.608]),
+ edgeAlpha: 0.85,
+ ridge: Object.freeze([0.91, 0.839, 0.675]),
+ ridgeAlpha: 0.45,
+ }),
+ cafe: Object.freeze({
+ fill: Object.freeze([0.557, 0.361, 0.243]),
+ fillAlpha: 0.52,
+ edge: Object.freeze([0.91, 0.839, 0.675]),
+ edgeAlpha: 0.95,
+ ridge: Object.freeze([0.949, 0.878, 0.714]),
+ ridgeAlpha: 0.6,
+ }),
+ }),
seaFloor: SEA_FLOOR,
palette: PALETTE,
models,
@@ -265,5 +284,7 @@ export const temperate = Object.freeze({
tree: plantTree,
tuft: plantTuft,
flower: plantFlower,
+ /** The two greens of the 2D map's tree dots. */
+ mapColors: Object.freeze([Object.freeze([0.302, 0.49, 0.227]), Object.freeze([0.376, 0.561, 0.271])]),
}),
});
diff --git a/client/public/js/view3d/biomes/winter/index.js b/client/public/js/view3d/biomes/winter/index.js
index 3edc6738..566e2977 100644
--- a/client/public/js/view3d/biomes/winter/index.js
+++ b/client/public/js/view3d/biomes/winter/index.js
@@ -5,7 +5,7 @@
*/
import { winterModels } from "./buildings.js";
import { plantFlower, plantTree, plantTuft } from "./flora.js";
-import { ICE, SNOW, WINTER_PALETTE } from "./palette.js";
+import { ICE, PINE, SNOW, STONE, TIMBER, WINTER_PALETTE } from "./palette.js";
import { buildPenguin, penguinWorkoutParts } from "./people.js";
import { terrainColor } from "./terrain.js";
@@ -90,6 +90,35 @@ export const winter = Object.freeze({
rock: Object.freeze([0.45, 0.47, 0.5]),
sand: Object.freeze([0.8, 0.86, 0.92]),
seaFloor: Object.freeze([0.18, 0.26, 0.32]),
+ /** The 2D map under snow: pale ground, dark water and ploughed roads. The
+ * ridden road is well below the snow's brightness, so it stays the most
+ * readable thing on the map (also dimmed at dusk), and the white edge
+ * lines and amber markings read against the darker asphalt. */
+ map: Object.freeze({
+ land: SNOW,
+ sea: Object.freeze([0.2, 0.31, 0.42]),
+ sand: Object.freeze([0.8, 0.86, 0.92]),
+ road: Object.freeze([0.45, 0.48, 0.54]),
+ contextRoad: Object.freeze([0.62, 0.65, 0.71]),
+ marking: Object.freeze([0.86, 0.68, 0.28]),
+ edge: Object.freeze([0.96, 0.96, 0.95]),
+ house: Object.freeze({
+ fill: STONE,
+ fillAlpha: 0.5,
+ edge: SNOW,
+ edgeAlpha: 0.95,
+ ridge: ICE,
+ ridgeAlpha: 0.55,
+ }),
+ cafe: Object.freeze({
+ fill: TIMBER,
+ fillAlpha: 0.58,
+ edge: SNOW,
+ edgeAlpha: 1,
+ ridge: ICE,
+ ridgeAlpha: 0.7,
+ }),
+ }),
palette: WINTER_PALETTE,
models: winterModels,
/** The roadside crowd becomes clapping penguins; the scarf takes the per-person tint. */
@@ -133,5 +162,7 @@ export const winter = Object.freeze({
tree: plantTree,
tuft: plantTuft,
flower: plantFlower,
+ /** Dark pines and snow-laden branches for the 2D map's tree dots. */
+ mapColors: Object.freeze([PINE, ICE]),
}),
});
diff --git a/client/public/styles.css b/client/public/styles.css
index e1aa0aa3..37ee055b 100644
--- a/client/public/styles.css
+++ b/client/public/styles.css
@@ -1581,6 +1581,7 @@ button.small {
--hud-muted: #c3cad3;
--num: "Barlow Condensed", "Roboto Condensed", "Arial Narrow", system-ui, sans-serif;
--gap: 20px;
+ --band-height: 250px;
}
body.riding {
@@ -1595,7 +1596,7 @@ body.riding {
}
.world-wrap,
-.canvas-peloton {
+.canvas-ride-map {
position: absolute;
inset: 0;
}
@@ -1606,15 +1607,19 @@ body.riding {
}
.canvas-world,
-.canvas-peloton {
+.canvas-ride-map {
display: block;
width: 100%;
height: 100%;
}
-.ride[data-layout="training"] .world-wrap,
-.ride[data-layout="training"] .canvas-peloton {
- bottom: 250px;
+/* The training layout leaves the view the upper part, as it does for 3D. */
+.ride[data-layout="training"] .world-wrap {
+ bottom: var(--band-height);
+}
+
+.ride[data-layout="training"] .canvas-ride-map {
+ height: calc(100% - var(--band-height));
}
.hud {
@@ -2222,7 +2227,7 @@ body.riding {
.targets {
position: absolute;
left: 50%;
- bottom: 300px;
+ bottom: calc(var(--band-height) + 50px);
transform: translateX(-50%);
display: flex;
overflow: hidden;
@@ -2252,7 +2257,7 @@ body.riding {
left: 0;
right: 0;
bottom: 0;
- height: 250px;
+ height: var(--band-height);
background: #12161b;
border-top: 1px solid var(--glass-line);
display: grid;
@@ -4049,7 +4054,7 @@ body.riding {
.ride:not([data-mode="studio"]) .studio-only,
.ride[data-mode="studio"] .route-only,
.ride[data-mode="studio"] .layout:not(.layout-studio),
-.ride[data-mode="studio"] .canvas-peloton,
+.ride[data-mode="studio"] .canvas-ride-map,
.ride[data-mode="studio"] #world-wrap {
display: none !important;
}
@@ -5365,7 +5370,7 @@ body.aboard #event-call-button {
/* ===================================================================== */
body.working-out #hud,
-body.working-out #peloton,
+body.working-out #ride-map,
body.working-out #paddles {
display: none !important;
}
diff --git a/client/test/biomes.test.js b/client/test/biomes.test.js
index 1f58f2b5..f6f87ab4 100644
--- a/client/test/biomes.test.js
+++ b/client/test/biomes.test.js
@@ -45,6 +45,21 @@ test("a biome brings everything the world draws with", () => {
assert.ok(biome.sky.clouds.count > 0, `${id} has clouds`);
assert.equal(biome.sky.clouds.color.length, 4, `${id} has a cloud colour`);
assert.equal(biome.preview.sky.length, 3, `${id} has a picker swatch`);
+ assert.equal(biome.flora.mapColors.length, 2, `${id} has two 2D tree colours`);
+ for (const color of biome.flora.mapColors) assert.equal(color.length, 3, `${id} has an RGB 2D tree colour`);
+ // The 2D map takes its season's colours from the biome only (rideMapTheme
+ // has no fallbacks): buildings, outlines and the alpha of each.
+ for (const kind of ["house", "cafe"]) {
+ const spec = biome.map?.[kind];
+ assert.ok(spec, `${id} has 2D map colours for a ${kind}`);
+ for (const key of ["fill", "edge", "ridge"]) {
+ assert.equal(spec[key].length, 3, `${id} has an RGB 2D ${kind} ${key}`);
+ assert.ok(spec[key].every((channel) => channel >= 0 && channel <= 1), `${id}'s 2D ${kind} ${key} is in 0–1`);
+ }
+ for (const key of ["fillAlpha", "edgeAlpha", "ridgeAlpha"]) {
+ assert.ok(spec[key] === undefined || (spec[key] > 0 && spec[key] <= 1), `${id}'s 2D ${kind} ${key} is an opacity`);
+ }
+ }
if (biome.weather) {
assert.ok(biome.weather.count > 0, `${id} has weather particles`);
assert.equal(biome.weather.color.length, 4, `${id} has a weather colour`);
diff --git a/client/test/rideMapDecor.test.js b/client/test/rideMapDecor.test.js
new file mode 100644
index 00000000..37070d16
--- /dev/null
+++ b/client/test/rideMapDecor.test.js
@@ -0,0 +1,112 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { RouteGeometry } from "../public/js/route/geometry.js";
+import { RoadNetwork } from "../public/js/route/network.js";
+import { frameAt, drawDecorations, roadDecorations } from "../public/js/view/rideMapDecor.js";
+import { rideMapTheme } from "../public/js/view/rideMapTheme.js";
+import { tinyNetworkFile } from "./helpers.js";
+
+const decorated = () =>
+ new RouteGeometry({
+ id: "decorated",
+ name: "Decorated",
+ lanes: 4,
+ seed: 7,
+ loop: false,
+ points: [[0, 0, 0], [1200, 0, 0]],
+ markers: [],
+ zones: [
+ { type: "village", from: 100, to: 400 },
+ { type: "forest", from: 600, to: 1000 },
+ ],
+ });
+
+test("the road frame points north with the right to its east", () => {
+ const east = frameAt(decorated(), 100);
+ assert.ok(Math.abs(east.forward.x - 1) < 1e-9);
+ assert.ok(Math.abs(east.forward.y) < 1e-9);
+ assert.ok(Math.abs(east.right.x) < 1e-9);
+ assert.ok(Math.abs(east.right.y + 1) < 1e-9);
+
+ const north = frameAt(
+ new RouteGeometry({ id: "north", name: "North", lanes: 4, seed: 7, loop: false, points: [[0, 0, 0], [0, 1200, 0]] }),
+ 100,
+ );
+ assert.ok(Math.abs(north.forward.x) < 1e-9);
+ assert.ok(Math.abs(north.forward.y - 1) < 1e-9);
+ assert.ok(Math.abs(north.right.x - 1) < 1e-9);
+ assert.ok(Math.abs(north.right.y) < 1e-9);
+});
+
+test("a village gets outline buildings and the café, all off the road", () => {
+ const route = decorated();
+ const { buildings } = roadDecorations(route);
+ assert.ok(buildings.some((b) => b.kind === "cafe"), "the route starts at a café");
+ const houses = buildings.filter((b) => b.kind === "house");
+ assert.ok(houses.length > 4, "houses on both sides of the village");
+ assert.ok(houses.some((b) => b.y > 10) && houses.some((b) => b.y < -10), "both sides");
+ for (const b of buildings) {
+ assert.ok(Math.abs(b.y) > 8, "a building is set back from the road");
+ assert.ok(b.w >= 6 && b.d >= 5, "a building has a footprint");
+ }
+});
+
+test("trees are small dots, off the road, and in the forest", () => {
+ const route = decorated();
+ const { trees } = roadDecorations(route);
+ assert.ok(trees.length > 20, "a forest and a roadside scatter");
+ assert.ok(trees.length > 80, "the forest is denser than the roadside");
+ for (const tree of trees) {
+ assert.ok(Math.abs(tree.y) > 7, "no tree on the road");
+ assert.ok(tree.r >= 1 && tree.r <= 2.2, "a crown radius in metres, not a canopy");
+ }
+});
+
+test("tree dots scale with the map's zoom, never below a minimum", () => {
+ const route = decorated();
+ const { trees } = roadDecorations(route);
+ const theme = rideMapTheme({ biome: "temperate", timeMode: "day" });
+ const radii = [];
+ const ctx = new Proxy(
+ {},
+ {
+ get: (_, name) => (name === "arc" ? (...args) => radii.push(args[2]) : () => {}),
+ set: () => true,
+ },
+ );
+ const camera = { center: { x: 700, y: 0 }, toScreen: () => ({ x: 400, y: 300 }) };
+ drawDecorations(ctx, { decorations: { trees, buildings: [] }, camera: { ...camera, scale: 2.5 }, width: 800, height: 600, theme });
+ assert.ok(radii.length > 0, "trees near the centre are drawn");
+ assert.ok(Math.min(...radii) >= 1.5, "a dot stays visible at the smallest zoom");
+ radii.length = 0;
+ drawDecorations(ctx, { decorations: { trees, buildings: [] }, camera: { ...camera, scale: 12 }, width: 800, height: 600, theme });
+ assert.ok(Math.max(...radii) > 12, "a crown grows with the zoom");
+});
+
+test("decorations are deterministic per route", () => {
+ const a = roadDecorations(decorated());
+ const b = roadDecorations(decorated());
+ assert.deepEqual(a, b);
+});
+
+test("a network places its café and does not decorate the sea", () => {
+ const route = new RouteGeometry({
+ id: "tiny-loop",
+ name: "Tiny Loop",
+ lanes: 4,
+ seed: 3,
+ loop: true,
+ points: [[0, 0, 30], [400, 0, 30], [400, 300, 30], [0, 300, 30]],
+ markers: [],
+ zones: [],
+ });
+ const network = new RoadNetwork(tinyNetworkFile());
+ const { buildings, trees } = roadDecorations(route, network);
+ assert.ok(buildings.length > 0, "the network café");
+ for (const building of buildings) {
+ assert.ok(network.heightAt(building.x, building.y) >= 2.5, "no building in the sea or on the beach");
+ }
+ for (const tree of trees) {
+ assert.ok(network.heightAt(tree.x, tree.y) >= 2.5, "no tree in the sea or on the beach");
+ }
+});
diff --git a/client/test/rideMapTheme.test.js b/client/test/rideMapTheme.test.js
new file mode 100644
index 00000000..48eeba97
--- /dev/null
+++ b/client/test/rideMapTheme.test.js
@@ -0,0 +1,66 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { MAP_COLORS } from "../public/js/view/mapPreview.js";
+import { rideMapTheme } from "../public/js/view/rideMapTheme.js";
+
+const COLORS = Object.freeze({
+ text: "#e8ecf1",
+ muted: "#8a94a3",
+ road: "#2b3139",
+});
+
+const hex = (value) => {
+ const number = Number.parseInt(value.slice(1), 16);
+ return `rgb(${(number >> 16) & 255}, ${(number >> 8) & 255}, ${number & 255})`;
+};
+
+test("temperate day keeps the established map palette", () => {
+ const theme = rideMapTheme({ biome: "temperate", timeMode: "day", colors: COLORS });
+ assert.equal(theme.sea, hex(MAP_COLORS.sea));
+ assert.equal(theme.land, hex(MAP_COLORS.land));
+ assert.equal(theme.sand, hex(MAP_COLORS.sand));
+ assert.equal(theme.road, hex(COLORS.road));
+ assert.equal(theme.contextRoad, hex(COLORS.muted));
+ assert.equal(theme.edge, hex(COLORS.text));
+ assert.equal(theme.marking, hex(COLORS.text));
+ // The biome's own building colours, translucent as drawn.
+ assert.equal(theme.houseFill, "rgba(116, 76, 56, 0.46)");
+ assert.equal(theme.cafeEdge, "rgba(232, 214, 172, 0.95)");
+ assert.ok(theme.trees.every((tree) => /^rgb\(/.test(tree)), "tree colours are CSS strings");
+});
+
+test("winter paints the map with the biome's snow, ice, road and trees", () => {
+ const theme = rideMapTheme({ biome: "winter", timeMode: "day", colors: COLORS });
+ assert.equal(theme.land, "rgb(240, 245, 252)");
+ assert.equal(theme.sea, "rgb(51, 79, 107)");
+ assert.equal(theme.marking, "rgb(219, 173, 71)");
+ assert.deepEqual(theme.trees, ["rgb(31, 59, 43)", "rgb(194, 219, 237)"]);
+ assert.notEqual(theme.houseFill, rideMapTheme({ biome: "temperate", timeMode: "day", colors: COLORS }).houseFill);
+ assert.notEqual(theme.road, theme.land, "the road reads against the snow");
+ assert.notEqual(theme.marking, theme.land, "the lane markings read against the snow");
+ const channel = (color) => Number(color.match(/rgb\((\d+), (\d+), (\d+)\)/)[1]);
+ assert.ok(channel(theme.road) < channel(theme.land) * 0.6, "the winter road is clearly darker than the snow");
+ assert.ok(channel(theme.edge) > channel(theme.road), "the edge lines read against the road");
+ const dusk = rideMapTheme({ biome: "winter", timeMode: "dusk", colors: COLORS });
+ assert.ok(channel(dusk.edge) > channel(dusk.road) + 30, "the edge lines still read against the road at dusk");
+});
+
+test("golden hour and dusk tint the map, and auto follows the clock", () => {
+ const day = rideMapTheme({ biome: "temperate", timeMode: "day", colors: COLORS });
+ const golden = rideMapTheme({ biome: "temperate", timeMode: "golden", colors: COLORS });
+ const dusk = rideMapTheme({ biome: "temperate", timeMode: "dusk", colors: COLORS });
+ assert.notEqual(golden.land, day.land);
+ assert.notEqual(dusk.land, day.land);
+ assert.notEqual(dusk.land, golden.land);
+ assert.notEqual(golden.road, day.road);
+ assert.notEqual(dusk.sea, day.sea);
+
+ const noon = new Date(2026, 10, 7, 12, 0);
+ const night = new Date(2026, 10, 7, 22, 0);
+ assert.equal(rideMapTheme({ biome: "temperate", timeMode: "auto", date: noon, colors: COLORS }).land, day.land);
+ assert.equal(rideMapTheme({ biome: "temperate", timeMode: "auto", date: night, colors: COLORS }).land, dusk.land);
+});
+
+test("an unknown biome falls back to the temperate theme", () => {
+ assert.equal(rideMapTheme({ biome: "not-a-biome", timeMode: "day", colors: COLORS }).land, hex(MAP_COLORS.land));
+});
diff --git a/client/test/rideMapView.test.js b/client/test/rideMapView.test.js
new file mode 100644
index 00000000..e06512da
--- /dev/null
+++ b/client/test/rideMapView.test.js
@@ -0,0 +1,207 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { RouteGeometry } from "../public/js/route/geometry.js";
+import { RoadNetwork } from "../public/js/route/network.js";
+import { LANE_WIDTH } from "../public/js/view3d/world.js";
+import { MAP_VIEW, cachedOffsetNodes, drawRideMap, laneOffset, mapCamera, mapRiderMarks, offsetNodes, roadPointAt } from "../public/js/view/rideMapView.js";
+import { tinyLoopFile, tinyNetworkFile } from "./helpers.js";
+
+const COLORS = Object.freeze({
+ text: "#e8ecf1",
+ muted: "#8a94a3",
+ grid: "#3a434f",
+ road: "#2b3139",
+ terrain: "#24402f",
+ terrainEdge: "#5fb47c",
+ me: "#ff7a1a",
+ human: "#4cc3ff",
+ bot: "#8f99a8",
+});
+
+const route = (points, loop = false) =>
+ new RouteGeometry({ id: "test-road", name: "Test Road", lanes: 4, seed: 1, loop, points: points.map(([x, y]) => [x, y, 0]) });
+
+const east = () => route([[0, 0], [1000, 0]]);
+const north = () => route([[0, 0], [0, 1000]]);
+
+const near = (a, b, epsilon = 1e-6) => Math.abs(a - b) <= epsilon;
+
+test("the map puts me at the bottom centre, heading up", () => {
+ const road = east();
+ const camera = mapCamera(road, { distance: 500, lane: 2 }, 1000, 800);
+ const me = camera.toScreen(roadPointAt(road, 500, 2));
+ assert.ok(near(me.x, 500), "centred across the road");
+ assert.ok(near(me.y, 800 * MAP_VIEW.riderY), "lower than the middle");
+ const ahead = camera.toScreen(roadPointAt(road, 520, 2));
+ assert.ok(near(ahead.x, me.x), "straight ahead stays in the middle");
+ assert.ok(ahead.y < me.y, "ahead is up the screen");
+ const behind = camera.toScreen(roadPointAt(road, 480, 2));
+ assert.ok(behind.y > me.y, "behind is down the screen");
+});
+
+test("a road heading north is drawn the same way up", () => {
+ const road = north();
+ const camera = mapCamera(road, { distance: 500, lane: 2 }, 1000, 800);
+ const ahead = camera.toScreen(roadPointAt(road, 520, 2));
+ assert.ok(near(ahead.x, camera.rider.x));
+ assert.ok(ahead.y < camera.rider.y);
+});
+
+test("the map camera turns screen points back into the world", () => {
+ const road = east();
+ const camera = mapCamera(road, { distance: 500, lane: 2 }, 1000, 800);
+ const center = camera.fromScreen(camera.rider);
+ assert.ok(near(center.x, camera.center.x));
+ assert.ok(near(center.y, camera.center.y));
+ // Heading east, the top of the screen is east of me.
+ const ahead = camera.fromScreen({ x: camera.rider.x, y: camera.rider.y - 10 });
+ assert.ok(ahead.x > camera.center.x + 1);
+ assert.ok(near(ahead.y, camera.center.y));
+});
+
+test("lane 0 is left of travel and lane 3 is right", () => {
+ const road = east();
+ const camera = mapCamera(road, { distance: 500, lane: 2 }, 1000, 800);
+ const left = camera.toScreen(roadPointAt(road, 500, 0));
+ const right = camera.toScreen(roadPointAt(road, 500, 3));
+ assert.ok(left.x < camera.rider.x);
+ assert.ok(right.x > camera.rider.x);
+ assert.ok(near(right.x - left.x, (laneOffset(3, 4) - laneOffset(0, 4)) * camera.scale), "lanes are LANE_WIDTH apart");
+ assert.ok(laneOffset(0, 4) < 0 && laneOffset(3, 4) > 0);
+ assert.ok(near(laneOffset(1.5, 4), 0), "the middle of four lanes has no offset");
+});
+
+test("lane markings are offset from the centre line", () => {
+ const road = east();
+ const nodes = offsetNodes(road, LANE_WIDTH);
+ assert.equal(nodes.length, 2);
+ assert.ok(near(nodes[0].x, 0));
+ assert.ok(near(nodes[0].y, -LANE_WIDTH), "a positive offset goes to the right of travel");
+ const loop = route([[0, 0], [100, 0], [100, 100], [0, 100]], true);
+ const ring = offsetNodes(loop, 0);
+ assert.equal(ring.length, loop.nodes.length, "a loop is closed");
+ assert.ok(near(ring[0].x, ring.at(-1).x) && near(ring[0].y, ring.at(-1).y));
+});
+
+test("a vehicle is marked once, at its captain", () => {
+ const riders = [
+ { id: 9, name: "Zed", distance: 30, lane: 0, is_bot: false },
+ { id: 1, name: "Ben", distance: 30, lane: 1, is_bot: false, vehicle: { id: 5, kind: "beer_bike", seat: 0, seats: 5 } },
+ { id: 2, name: "Anna", distance: 30, lane: 1, is_bot: false, vehicle: { id: 5, kind: "beer_bike", seat: 1, seats: 5, captain: true } },
+ ];
+ const marks = mapRiderMarks(riders, 2);
+ assert.equal(marks.length, 2);
+ assert.equal(marks.find((mark) => mark.rider.id === 9).label, "Zed");
+ const vehicle = marks.find((mark) => mark.big);
+ assert.equal(vehicle.label, "Anna's beer bike");
+ assert.ok(vehicle.mine);
+});
+
+function fakeCanvas(width = 800, height = 600) {
+ const calls = { lineTo: 0, fill: 0, fillRect: 0, stroke: 0, arc: 0, fillText: 0 };
+ const fills = [];
+ const strokes = [];
+ const alphas = [];
+ const ctx = new Proxy(
+ {},
+ {
+ get: (_, name) => {
+ if (name === "measureText") return () => ({ width: 20 });
+ if (name in calls) return () => (calls[name] += 1);
+ return () => {};
+ },
+ set: (_, name, value) => {
+ if (name === "fillStyle") fills.push(value);
+ if (name === "strokeStyle") strokes.push(value);
+ if (name === "globalAlpha") alphas.push(value);
+ return true;
+ },
+ },
+ );
+ return { canvas: { clientWidth: width, clientHeight: height, width: 0, height: 0, style: {}, getContext: () => ctx }, calls, fills, strokes, alphas };
+}
+
+test("the map draws the coast, every road, the lane lines and the riders", () => {
+ const { canvas, calls } = fakeCanvas();
+ const road = new RouteGeometry(tinyLoopFile());
+ const me = { id: 1, name: "Me", distance: 30, lane: 2, is_bot: false };
+ drawRideMap(canvas, { route: road, riders: [me], me, colors: COLORS, network: new RoadNetwork(tinyNetworkFile()) });
+ assert.ok(calls.lineTo > 500, "coast, roads and markings");
+ assert.ok(calls.fill >= 2, "the land and my arrow");
+ assert.equal(calls.fillText, 1, "my name");
+});
+
+test("without a network the map still shows the road", () => {
+ const { canvas, calls } = fakeCanvas();
+ const road = new RouteGeometry(tinyLoopFile());
+ drawRideMap(canvas, { route: road, riders: [], me: null, colors: COLORS });
+ assert.ok(calls.lineTo > 100, "the road and its markings");
+ assert.ok(calls.fillRect >= 1, "the land");
+});
+
+test("the map paints its ground and decorations with the selected biome", () => {
+ const { canvas, fills, strokes } = fakeCanvas();
+ const road = new RouteGeometry(tinyLoopFile());
+ drawRideMap(canvas, { route: road, riders: [], me: null, colors: COLORS, network: new RoadNetwork(tinyNetworkFile()), biome: "winter", timeMode: "day" });
+ assert.ok(fills.includes("rgb(240, 245, 252)"), "snow covers the land");
+ assert.ok(strokes.includes("rgb(115, 122, 138)"), "the winter road is a dark ploughed surface");
+ assert.ok(strokes.includes("rgb(219, 173, 71)"), "the lane markings use the biome's paint");
+});
+
+test("drafting draws the gap ahead of me as a band in my lane", () => {
+ const road = north();
+ const me = { id: 1, name: "Me", distance: 500, lane: 2, is_bot: false };
+ const leader = { id: 2, name: "Ana", distance: 503, lane: 2, is_bot: false };
+ const withoutDraft = fakeCanvas();
+ drawRideMap(withoutDraft.canvas, { route: road, riders: [me], me, colors: COLORS });
+ const withDraft = fakeCanvas();
+ drawRideMap(withDraft.canvas, { route: road, riders: [me, leader], me, draft: { gap: 3, savingPercent: 27, leader }, colors: COLORS });
+ assert.ok(withDraft.calls.stroke > withoutDraft.calls.stroke, "one more stroke for the band");
+ assert.ok(withDraft.strokes.includes(COLORS.me), "the band takes my colour");
+});
+
+test("labels follow the rest of the HUD: bots and riders from other apps", () => {
+ const riders = [
+ { id: 2, name: "Ana", distance: 30, lane: 1, is_bot: true },
+ { id: 3, name: "Ben", distance: 30, lane: 2, is_bot: false, app: "incyclist" },
+ ];
+ const marks = mapRiderMarks(riders, 1);
+ assert.equal(marks.find((mark) => mark.rider.id === 2).label, "Ana (bot)");
+ assert.equal(marks.find((mark) => mark.rider.id === 3).label, "Ben · incyclist");
+});
+
+test("my best lap's ghost is drawn see-through, dashed and labelled", () => {
+ const road = north();
+ const me = { id: 1, name: "Me", distance: 500, lane: 2, is_bot: false };
+ const ghost = { id: 99, name: "Best lap", distance: 520, lane: 2, ghost: true };
+ const { canvas, alphas, calls } = fakeCanvas();
+ drawRideMap(canvas, { route: road, riders: [me, ghost], me, colors: COLORS });
+ assert.ok(alphas.includes(0.35), "the ghost is see-through");
+ assert.ok(calls.fillText >= 2, "the ghost keeps its label");
+});
+
+test("the map draws the lemons still on the road and skips collected ones", () => {
+ const road = east();
+ const me = { id: 1, name: "Me", distance: 500, lane: 2, is_bot: false };
+ const { canvas, fills } = fakeCanvas();
+ drawRideMap(canvas, {
+ route: road,
+ riders: [me],
+ me,
+ colors: COLORS,
+ lemons: [
+ { id: "a", distance: 505, lane: 2, collected: false },
+ { id: "b", distance: 506, lane: 2, collected: true },
+ { id: "c", distance: 507, lane: 2, collected: false },
+ ],
+ });
+ assert.equal(fills.filter((fill) => fill === "#ffcc14").length, 2, "two lemons, not the collected one");
+});
+
+test("the view reuses a route's offset lines across frames", () => {
+ const road = east();
+ const cached = cachedOffsetNodes(road, 2);
+ assert.equal(cachedOffsetNodes(road, 2), cached, "the same offset comes from the cache");
+ assert.notEqual(cachedOffsetNodes(road, 2), offsetNodes(road, 2), "the exported maths stays pure");
+ assert.deepEqual(cached, offsetNodes(road, 2), "the cache holds the same points");
+});
diff --git a/client/test/ui.test.js b/client/test/ui.test.js
index 1e9c6061..dca94316 100644
--- a/client/test/ui.test.js
+++ b/client/test/ui.test.js
@@ -4,7 +4,6 @@ import { actionForKey, bindKeyboard } from "../public/js/input/keyboard.js";
import { DEFAULT_PROFILE, ProfileStore, keepValid, validateProfile } from "../public/js/profile/profileStore.js";
import { formatDuration, formatGap, formatGrade, formatSpeed, formatWkg } from "../public/js/util/format.js";
import { describeEvent, inRace, nearbyRiders, onlineSummary, raceStatus, riderSections } from "../public/js/view/panels.js";
-import { lemonsInWindow, ridersInWindow } from "../public/js/view/pelotonView.js";
import { profileScale } from "../public/js/view/profileView.js";
import { minimapTransform } from "../public/js/view/minimapView.js";
import { squareRoute } from "./helpers.js";
@@ -165,14 +164,6 @@ test("describes race status and events", () => {
assert.equal(describeEvent({ kind: "event_finished", event_id: "e", event_kind: "group_ride", results: [result("Ben", 0.5)] }, 1), "Event finished");
});
-test("peloton window keeps riders around me only", () => {
- const route = squareRoute();
- const me = { id: 1, distance: 5 };
- const visible = ridersInWindow(me, [me, { id: 2, distance: 990 }, { id: 3, distance: 60 }, { id: 4, distance: 500 }], route);
- assert.deepEqual(visible.map((v) => v.rider.id), [1, 2]);
- assert.equal(visible[1].gap, -15);
-});
-
test("profile and minimap scales map into the canvas", () => {
const route = squareRoute();
const scale = profileScale(route, 1016, 200);
@@ -186,13 +177,6 @@ test("profile and minimap scales map into the canvas", () => {
assert.deepEqual(project({ x: 250, y: 250 }), { x: 275, y: 25 });
});
-test("peloton labels only collide within the same lane", async () => {
- const { overlaps } = await import("../public/js/view/pelotonView.js");
- assert.equal(overlaps({ left: 0, right: 50, row: 1 }, { left: 40, right: 90, row: 1 }), true);
- assert.equal(overlaps({ left: 0, right: 50, row: 1 }, { left: 40, right: 90, row: 2 }), false);
- assert.equal(overlaps({ left: 0, right: 50, row: 1 }, { left: 70, right: 90, row: 1 }), false);
-});
-
test("shifting and view keys map to actions", () => {
assert.equal(actionForKey({ code: "KeyE", target: {} }), "shiftUp");
assert.equal(actionForKey({ code: "Minus", target: {} }), "shiftDown");
@@ -251,16 +235,3 @@ test("edits are kept as they're typed, each field only once it's valid", () => {
assert.equal(keepValid(previous, { chainring: 5, cog: 16 }).cog, 16);
});
-test("the peloton shows the golden lemons near me that are still there", () => {
- const route = squareRoute();
- const me = { id: 1, distance: 5, lane: 1 };
- const lemons = [
- { id: "a", distance: 30, lane: 2, collected: false },
- { id: "b", distance: 20, lane: 0, collected: true },
- { id: "c", distance: 990, lane: 3, collected: false },
- { id: "d", distance: 400, lane: 1, collected: false },
- ];
- const shown = lemonsInWindow(me, lemons, route);
- assert.deepEqual(shown.map((s) => s.lemon.id), ["a", "c"]);
- assert.equal(shown[1].gap, -15);
-});
diff --git a/client/test/vehicleViews.test.js b/client/test/vehicleViews.test.js
index 2f545368..76aa3075 100644
--- a/client/test/vehicleViews.test.js
+++ b/client/test/vehicleViews.test.js
@@ -5,8 +5,6 @@ import { CAMERA_MODES, vehicleSettings } from "../public/js/view3d/chaseCamera.j
import { layoutOf, placedVehicles, seatCadence } from "../public/js/view3d/vehicleScene.js";
import { vehicleLayout } from "../public/js/view3d/vehicleModel.js";
import { minimapDots } from "../public/js/view/minimapView.js";
-import { PELOTON_WINDOW, pelotonItems } from "../public/js/view/pelotonView.js";
-import { squareRoute } from "./helpers.js";
const seated = (id, name, seat, { vehicleId = 5, kind = "beer_bike", seats = 5, captain = false, distance = 100, ...rest } = {}) => ({
id,
@@ -47,17 +45,8 @@ test("2D markers: one per vehicle at its captain, solo riders left alone", () =>
);
});
-test("peloton and minimap show a vehicle once, larger than a bike", () => {
- const route = squareRoute();
+test("the minimap shows a vehicle once, larger than a bike", () => {
const riders = [solo(9, "Zed", 110), seated(1, "Ben", 0), seated(2, "Anna", 1, { captain: true })];
- const items = pelotonItems(riders[1], riders, route);
- assert.equal(items.length, 2);
- const bike = items.find((i) => i.rider.id === 9);
- const vehicle = items.find((i) => i.big);
- assert.equal(vehicle.label, "Anna's beer bike");
- assert.ok(vehicle.lengthM > bike.lengthM);
- assert.ok(vehicle.mine);
- assert.ok(Math.abs(vehicle.gap) <= PELOTON_WINDOW.ahead);
const dots = minimapDots(riders, 1);
assert.equal(dots.length, 2);
assert.equal(dots.at(-1).label, "Anna's beer bike");
diff --git a/docs/adr/0024-2d-map-view.md b/docs/adr/0024-2d-map-view.md
new file mode 100644
index 00000000..3fb1674f
--- /dev/null
+++ b/docs/adr/0024-2d-map-view.md
@@ -0,0 +1,73 @@
+# 24. The 2D view is a top-down map
+
+Date: 2026-11-02 · Status: accepted
+
+## Context
+
+The 2D view was the POC's first view: a lane strip with distance left to right,
+one row per lane. It was useful while drafting, but it was drawn for a small
+panel and later stretched over the whole window. On a tall screen each lane is
+hundreds of pixels high, the rider is a 14 px capsule, the metre scale ends up
+under the HUD, and on a solo ride nothing in it moves: it reads as a broken,
+empty screen next to the 3D world. It is also the fallback for devices without
+WebGL 2, where it should still show the ride.
+
+The client already has the data for a real map: `RouteGeometry` (the road being
+ridden, including the rider's own road after a turn), the map's `RoadNetwork`
+(every road, the coast and terrain), and the smoothed rider list. The start
+menu already draws such a map (`view/mapPreview.js`).
+
+## Decision
+
+- **Replace the lane strip with a top-down map** (`view/rideMapView.js`) rather
+ than trying to fit the strip to the window.
+- **Heading-up camera**, rider mid-screen, canvas height spanning 120 m. (The
+ cockpit layout's paddle meter overlays the lower third; the arrow must stay
+ clear of its hint card.) The road ahead fills the screen and the map scrolls
+ and turns with the rider, so the view is alive even when riding alone.
+- **Draw what the world has:** the sea and island coast when the network is
+ loaded (one coast path cached per network), minimal tree dots and thin
+ village/café outlines from the route's scenery zones and the network's cafés,
+ every road as a thin context line, the ridden road at full width with
+ shoulders, edge lines and dashed lane dividers, then one mark per rider or
+ vehicle with its name. Me is an orange arrow.
+- **Theme with the world:** `view/rideMapTheme.js` takes the selected biome's
+ 2D colours (ground, water, road, markings, trees and buildings) and the
+ time-of-day preset, and returns the map's palette. The season and the light
+ therefore read the same in 2D as in 3D: winter paints snow, ice and pine dots,
+ golden hour and dusk tint the whole map, and `auto` follows the local clock.
+ The rider and HUD marks keep their own high-contrast colours.
+- **Same data as 3D, no new requests:** the map uses the route and `app.network`
+ / `app.routes` that the ride already loads. Without a network it draws the
+ current route on land, so it works as the WebGL 2 fallback and while the world
+ builds.
+- **Fit the existing layouts:** the map is clipped above the Training layout's
+ workout band, as the 3D view already is. It fills the window in the other
+ layouts and the HUD stays an overlay.
+
+## Consequences
+
+- No server or protocol change; the view consumes the same smoothed riders.
+- The lane close-up (who sits where in which lane) is gone. Drafting stays
+ visible in the HUD pill and as a soft band from the arrow to the rider ahead
+ on the map; the golden lemons and my best lap's ghost keep their marks on the
+ map; the minimap still shows the route and all riders.
+- The map's land is a coarse hillshade sampled from the network's height grid
+ (drawn on a small offscreen canvas and smoothed up), not the 3D terrain
+ render; the coast, roads and riders carry the rest. The start menu's map uses
+ the same theme, so the season and time of day carry from the menu into the
+ ride; the two maps agree on palette, not on every tree or building.
+- The 2D palette has no shaders to reuse: it derives its colours from the biome
+ data and lighting presets in plain JavaScript. The biome is the single source
+ of its map colours (`map`, `flora.mapColors`), in 0–1 RGB like every other
+ biome colour; the biome test requires them, and an unknown biome id falls
+ back to the whole temperate biome.
+- Trees and buildings are symbolic (dots and thin outlines) generated from the
+ route's scenery zones and the network's cafés, not the 3D meshes: they stay
+ cheap and available while the world builds or without WebGL, at the cost of
+ not matching the 3D tree-for-tree. The dots and outlines are placed in metres
+ and scale with the map's zoom. Per-frame work stays light: the offset lane
+ lines are cached per route and off-view context roads are skipped whole, so
+ the WebGL 2 fallback stays cheap on small devices.
+- The 2D view now has a pure camera and offset maths, tested with fake canvases
+ and screenshots at the sizes the lane strip failed on.
diff --git a/docs/architecture.md b/docs/architecture.md
index 41c89e89..7fee1c3e 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -164,6 +164,24 @@ the ride already shows the 2D view.
V toggles 3D and 2D,
C
cycles cameras,
T cycles the time of day; *Graphics: Low* turns off the
shadow map and grass for weaker GPUs. Devices without WebGL 2 fall back to 2D.
+### 2D view
+
+`view/rideMapView.js` draws the alternative view: a top-down map around the
+rider. The camera is heading-up with the rider mid-screen and the canvas height
+spanning 120 m (the cockpit's paddle meter overlays the lower third). Once the
+map network is loaded, the island's coast and a coarse hillshade from the
+network's heights are drawn first; then the map's tree dots and thin outline
+houses (from the route's scenery zones and the map's cafés, scaled with the
+zoom), every road as a thin context line, the road being ridden at full width
+with edge lines and dashed lane dividers, the golden lemons still on the road,
+the draft gap ahead of me when I am drafting, and the riders around me,
+including my best lap's ghost. Without a network it draws the current route
+on land, so the view needs neither WebGL 2 nor an extra request while the world
+builds. `view/rideMapTheme.js` colours it from the selected biome's 2D palette
+(the biome is the palette's only source) and the time-of-day preset, so the 2D
+map follows the same season and light as the 3D world. The map is clipped above
+the workout band in the Training layout, like the 3D view.
+
### Ride screen
The 3D (or 2D) view fills the window and the HUD is an overlay. `#ride` carries