diff --git a/.env.example b/.env.example index bb5bdabb..50dd89d9 100644 --- a/.env.example +++ b/.env.example @@ -157,8 +157,8 @@ OPENRADLR_LANDING_IMPRINT_URL= OPENRADLR_LANDING_PLAUSIBLE_DOMAIN= # --- OpenBikeNet (optional) ----------------------------------------------------- -# Shares the velodrome with riders of other apps. Sent: rider name, position, speed, -# power and cadence of the riders on the velodrome. Empty = not connected. +# Shares the tracks (the velodromes) with riders of other apps. Sent: rider name, position, +# speed, power and cadence of the riders on the tracks. Empty = not connected. # OPENRADLR_OBN_URL=wss://obn.example/v0 OPENRADLR_OBN_URL= diff --git a/README.md b/README.md index 31826f13..c2147a6a 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ All settings live in `.env`; see [`.env.example`](.env.example) for descriptions | `OPENRADLR_REQUIRE_STRAVA` | `false` | Riders must connect Strava to join | | `OPENRADLR_ALLOW_SIMULATED_TRAINER` | `true` | Offer the simulated trainer (set `false` in production) | | `OPENRADLR_ALLOW_PADDLE_MODE` | `true` | Offer phone paddles (tap left/right for power; no Strava, no ride files) | -| `OPENRADLR_OBN_URL` | – | `wss://` URL of an OpenBikeNet server: shares the velodrome with riders of other apps (see [deploy.md](docs/deploy.md#openbikenet-optional)) | +| `OPENRADLR_OBN_URL` | – | `wss://` URL of an OpenBikeNet server: shares the tracks (velodromes) with riders of other apps (see [deploy.md](docs/deploy.md#openbikenet-optional)) | | `OPENRADLR_PRIVACY_URL` | – | Link to your privacy policy in the start menu | | `OPENRADLR_ANALYTICS_DOMAIN` / `_SCRIPT` | – | Opt-in Plausible analytics for the client: your site name, and the script URL if you self-host Plausible (off when the domain is empty) | | `OPENRADLR_STUDIO` | `true` | Host the spin studio (group classes) next to the routes | diff --git a/client/public/index.html b/client/public/index.html index 6fae22b0..13ba4184 100644 --- a/client/public/index.html +++ b/client/public/index.html @@ -244,6 +244,7 @@

Strava

Where do you want to ride?

+

Everyone on the same route rides together — friends, strangers and bots.

diff --git a/client/public/js/i18n/de.js b/client/public/js/i18n/de.js index ed22d9bd..16997148 100644 --- a/client/public/js/i18n/de.js +++ b/client/public/js/i18n/de.js @@ -218,6 +218,9 @@ export default { "menu.server.unreachable": "Server nicht erreichbar", "menu.shared": "Geteilt", "menu.shared.note": "Fahrer anderer Apps fahren hier mit. Mit ihnen geteilt: dein Name, deine Position, Geschwindigkeit, Leistung und Trittfrequenz.", + "menu.direction.label": "Fahrtrichtung", + "menu.direction.anticlockwise": "Gegen den Uhrzeigersinn", + "menu.direction.clockwise": "Im Uhrzeigersinn", "menu.riders.one": "{n} Fahrer", "menu.riders.other": "{n} Fahrer", "menu.server.full": "Voll · {riders} online", @@ -232,6 +235,8 @@ export default { "route.cape-loop.description": "Entlang der Strände an der Südküste, über die niedrigen Klippen des südöstlichen Kaps und zurück durch das Tal und die westlichen Buchten.", "route.col-de-la-forge.description": "Über die Hügel zur Forge Hut auf dem Pass, dann eine lange, schnelle Abfahrt zurück ins Tal.", "route.forge-circuit.description": "Von der Forge Hut die Westseite hinunter, zurück über die Höhenstraße und wieder hinauf zum Pass.", + "route.herne-hill.description": "Die 450-m-Freiluftbahn des Herne Hill Velodrome in London, gegen den Uhrzeigersinn wie im Rennen; geteilt mit Fahrern aus anderen Apps, wenn dieser Server mit OpenBikeNet verbunden ist.", + "route.herne-hill-clockwise.description": "Herne Hill Velodrome andersherum, von derselben Start-/Ziellinie aus; geteilt mit Fahrern aus anderen Apps, wenn dieser Server mit OpenBikeNet verbunden ist.", "route.island-tour.description": "Der lange Weg rundherum: das Flusstal, der Pass von Westen, die Höhenstraße und zurück durch das westliche Tal.", "route.lanzarote-lava-180.description": "Eine 180-km-Runde um Lanzarote mit etwa 2.500 Höhenmetern, angelehnt an die Raddistanz des berühmten Langdistanz-Triathlons der Insel. Streckenreihenfolge unbestätigt: aus öffentlichen Führern zusammengestellt, wartet auf die Prüfung durch jemanden, der sie kennt.", "route.riverside-flats.description": "Schnell und flach das Flusstal entlang, wie gemacht fürs Windschattenfahren und für Sprints.", diff --git a/client/public/js/i18n/en.js b/client/public/js/i18n/en.js index 9d7b961f..d2832064 100644 --- a/client/public/js/i18n/en.js +++ b/client/public/js/i18n/en.js @@ -218,6 +218,9 @@ export default { "menu.server.unreachable": "Server unreachable", "menu.shared": "Shared", "menu.shared.note": "Riders from other apps ride here too. Shared with them: your name, position, speed, power and cadence.", + "menu.direction.label": "Which way round", + "menu.direction.anticlockwise": "Anticlockwise", + "menu.direction.clockwise": "Clockwise", "menu.riders.one": "{n} rider", "menu.riders.other": "{n} riders", "menu.server.full": "Full · {riders} online", @@ -232,6 +235,8 @@ export default { "route.cape-loop.description": "Along the beaches of the south coast, over the low cliffs of the south-eastern cape and back by the valley and the western bays.", "route.col-de-la-forge.description": "Over the hills to the Forge Hut on the col, then a long, fast descent back to the valley.", "route.forge-circuit.description": "From the Forge Hut down the west side, back along the high road and up to the col again.", + "route.herne-hill.description": "The 450 m outdoor track of Herne Hill Velodrome in London, ridden anticlockwise as in racing; shared with riders from other apps when this server is connected to OpenBikeNet.", + "route.herne-hill-clockwise.description": "Herne Hill Velodrome the other way round, from the same start/finish line; shared with riders from other apps when this server is connected to OpenBikeNet.", "route.island-tour.description": "The long way round: the river valley, the col from the west, the high road and back down the west valley.", "route.lanzarote-lava-180.description": "A 180 km loop around Lanzarote with about 2,500 m of climbing, in the spirit of the island's famous long-distance triathlon bike leg. Course order unconfirmed: built from public guides, pending a check by someone who knows it.", "route.riverside-flats.description": "Fast and flat down the river valley, made for drafting and sprints.", diff --git a/client/public/js/main.js b/client/public/js/main.js index 90bbcff6..9dc3fdc1 100644 --- a/client/public/js/main.js +++ b/client/public/js/main.js @@ -91,7 +91,7 @@ import { drawRaceTimeline } from "./view/raceTimelineView.js"; import { drawMapPreview } from "./view/mapPreview.js"; import { MenuStage } from "./view/menuStage.js"; import { BUILD } from "./build.js"; -import { buildLabel, communityDistance, pickRoute, renderRoutes, routesOf, serverStatus, stageHeadline, stageLede, stageStats, workoutRoute, devicesVisible, privacyUrl, serverName, joinAction, stravaLine, activityOf, activityTabs, pickForActivity, renderActivityTabs, routesFor, shownActivity, showsCards, sharedNote } from "./view/startMenu.js"; +import { buildLabel, communityDistance, pickRoute, renderRoutes, routesOf, serverStatus, stageHeadline, stageLede, stageStats, workoutRoute, devicesVisible, privacyUrl, serverName, joinAction, stravaLine, activityOf, activityTabs, pickForActivity, renderActivityTabs, routesFor, shownActivity, showsCards, sharedNote, rideCards, cardIdOf, cardPick, directionsOf, renderDirections } from "./view/startMenu.js"; import { PRESETS } from "./workout/presets.js"; import { renderWorkoutCards } from "./view/workoutCards.js"; import { WorkoutSession, endAfterAsking } from "./workout/workoutSession.js"; @@ -1058,13 +1058,18 @@ function renderStartMenu() { const shared = sharedNote(selected); $("shared-note").hidden = !shared; $("shared-note").textContent = shared; - const cards = routesFor(activity, routes); + const cards = rideCards(routesFor(activity, routes)); $("route-list").hidden = !showsCards(activity, cards); - renderRoutes($("route-list"), cards, selected?.id ?? null, (id) => { + const pick = (id) => { app.routeId = id; writeSetting(ROUTE_KEY, id); renderStartMenu(); - }); + }; + renderRoutes($("route-list"), cards, cardIdOf(selected, routes), (id) => pick(cardPick(id, selected, routes))); + // A track ridden both ways round: which way, under its name. + const directions = activity === "events" ? [] : directionsOf(selected, routes); + $("route-directions").hidden = directions.length === 0; + renderDirections($("route-directions"), directions, pick); app.menu?.select(routes, selected?.id ?? null); renderEvents(events); renderUnfinished(); diff --git a/client/public/js/view/startMenu.js b/client/public/js/view/startMenu.js index 83ea516e..81c74ec0 100644 --- a/client/public/js/view/startMenu.js +++ b/client/public/js/view/startMenu.js @@ -161,7 +161,7 @@ const activityLabels = () => ({ ride: t("menu.tab.ride"), studio: t("menu.tab.st */ export function activityTabs(routes, events) { const tabs = ["ride", "studio", "workout"] - .map((id) => ({ id, label: activityLabels()[id], count: routesFor(id, routes).length, live: false })) + .map((id) => ({ id, label: activityLabels()[id], count: rideCards(routesFor(id, routes)).length, live: false })) .filter((tab) => tab.count > 0); if (events.length) tabs.push({ id: "events", label: activityLabels().events, count: events.length, live: events.some((row) => row.joinable || row.countdown === t("events.running")) }); return tabs; @@ -231,6 +231,68 @@ export function sharedNote(route) { return route?.shared === true ? t("menu.shared.note") : ""; } +/** `herne-hill-clockwise` is `herne-hill` ridden the other way round (docs/routes.md). */ +const CLOCKWISE = "-clockwise"; +const baseId = (id) => (id.endsWith(CLOCKWISE) ? id.slice(0, -CLOCKWISE.length) : id); + +/** A track and its other way round, both served, or null. */ +function waysRound(route, routes) { + if (!route?.id) return null; + const id = baseId(route.id); + const anticlockwise = routes.find((r) => r.id === id); + const clockwise = routes.find((r) => r.id === `${id}${CLOCKWISE}`); + return anticlockwise && clockwise ? [anticlockwise, clockwise] : null; +} + +/** The cards: a track ridden both ways round is one, with the riders of both. */ +export function rideCards(routes) { + return routes.flatMap((route) => { + const pair = waysRound(route, routes); + if (!pair) return [route]; + if (route === pair[1]) return []; + const [a, b] = pair; + return [{ ...a, players: (a.players ?? 0) + (b.players ?? 0), phone_players: (a.phone_players ?? 0) + (b.phone_players ?? 0) }]; + }); +} + +/** The card a route is on. */ +export function cardIdOf(route, routes) { + return route ? (waysRound(route, routes)?.[0].id ?? route.id) : null; +} + +/** The route a click on a card picks: the track's card keeps the way round already picked. */ +export function cardPick(cardId, selected, routes) { + return selected && cardIdOf(selected, routes) === cardId ? selected.id : cardId; +} + +/** The ways round the picked track, to choose from under its name; none for any other route. */ +export function directionsOf(route, routes) { + const pair = waysRound(route, routes); + if (!pair) return []; + return pair.map((r, i) => ({ id: r.id, label: t(i === 0 ? "menu.direction.anticlockwise" : "menu.direction.clockwise"), riders: routeRiders(r), picked: r.id === route.id })); +} + +/** + * Renders the ways round as chips, the picked one pressed. + * @param {HTMLElement} list + * @param {{id: string, label: string, riders: string, picked: boolean}[]} directions from `directionsOf` + * @param {(id: string) => void} onSelect + */ +export function renderDirections(list, directions, onSelect) { + drawWhenChanged(list, JSON.stringify(directions), onSelect, (select) => + list.replaceChildren( + ...directions.map((direction) => { + const button = element("button", "figure-chip"); + button.type = "button"; + button.setAttribute("aria-pressed", String(direction.picked)); + button.append(element("strong", null, direction.label), element("span", "muted", direction.riders)); + button.addEventListener("click", () => select(direction.id)); + return button; + }), + ), + ); +} + /** What a route card shows. */ export function routeCard(route) { const studio = route.kind === "studio"; diff --git a/client/public/js/view3d/world.js b/client/public/js/view3d/world.js index 282627aa..17d367f9 100644 --- a/client/public/js/view3d/world.js +++ b/client/public/js/view3d/world.js @@ -971,15 +971,17 @@ export function buildWorld(route, { others = [], network = null, biome = tempera biome = resolveBiome(typeof biome === "string" ? biome : biome.id); const density = biome.flora.density; const roads = network ? network.roads() : null; + // Every route of the map keeps its asphalt clear, whichever is ridden, so the world looks the same from all of them. + const mapRoutes = [route, ...others.filter((o) => o.id !== route.id)]; + // Tracks (#107): routes of the map that aren't walks over its roads, drawn and levelled like them. + const tracks = network ? mapRoutes.filter((r) => !network.routes.some((w) => w.id === r.id)) : []; // Everything drawn as a road (the ridden route first), and what the shared // things are built along. - const routes = network ? [route, ...roads] : [route, ...others.filter((o) => o.id !== route.id)]; + const routes = network ? [route, ...roads, ...tracks.filter((t) => t !== route)] : mapRoutes; const ordered = network ? roads : [...routes].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); const seed = network ? network.seed : mapSeed(route); const zonesOf = new Map(routes.map((r) => [r, resolveZones(r)])); - // Every route of the map keeps its asphalt clear, whichever is ridden, so the world looks the same from all of them. - const mapRoutes = [route, ...others.filter((o) => o.id !== route.id)]; - const base = network ? networkTerrain(network, roads, { keepClear: mapRoutes }) : terrainModel(ordered, { seed }); + const base = network ? networkTerrain(network, [...roads, ...tracks], { keepClear: mapRoutes }) : terrainModel(ordered, { seed }); const sea = waterLevel(base.index); const rivers = ordered.flatMap((r) => zonesOf.get(r).rivers.map((z) => ({ ...buildRiverPath(r, base, z.at, r.seed >>> 0, sea), route: r }))); const terrain = rivers.length > 0 ? withRivers(base, rivers, sea - RIVER.mouthDepth) : { ...base, riverDistance: () => Infinity }; diff --git a/client/public/styles.css b/client/public/styles.css index a404a19d..d3ba1303 100644 --- a/client/public/styles.css +++ b/client/public/styles.css @@ -503,6 +503,10 @@ kbd { display: none; } +.route-directions { + margin: 0 0 8px; +} + .stage-head .lede { margin: 0; max-width: 62ch; diff --git a/client/test/startMenu.test.js b/client/test/startMenu.test.js index 81937aeb..870a6277 100644 --- a/client/test/startMenu.test.js +++ b/client/test/startMenu.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { pickRoute, routeCharacter, routeStats, routesOf, serverStatus, studioTagline, buildLabel, communityDistance, routeRiders, workoutRoute, workoutTagline, stageStats, stageHeadline, stageLede, devicesVisible, privacyUrl, serverName, activityOf, routesFor, pickForActivity, activityTabs, shownActivity, showsCards, routeCard, stravaLine, joinAction, routeDescription, sharedNote } from "../public/js/view/startMenu.js"; +import { pickRoute, routeCharacter, routeStats, routesOf, serverStatus, studioTagline, buildLabel, communityDistance, routeRiders, workoutRoute, workoutTagline, stageStats, stageHeadline, stageLede, devicesVisible, privacyUrl, serverName, activityOf, routesFor, pickForActivity, activityTabs, shownActivity, showsCards, routeCard, stravaLine, joinAction, routeDescription, sharedNote, rideCards, cardIdOf, cardPick, directionsOf } from "../public/js/view/startMenu.js"; import { PRESETS } from "../public/js/workout/presets.js"; const routes = [ @@ -260,6 +260,38 @@ test("a shared route shows the shared badge and note", () => { assert.equal(sharedNote(velodrome), "Riders from other apps ride here too. Shared with them: your name, position, speed, power and cadence."); }); +const herneHill = { id: "herne-hill", name: "Herne Hill Velodrome", length_m: 450, players: 2, phone_players: 1, shared: true }; +const clockwise = { id: "herne-hill-clockwise", name: "Herne Hill Velodrome (clockwise)", length_m: 450, players: 1, shared: true }; +const withTrack = [routes[0], herneHill, clockwise]; + +test("a track ridden both ways round is one card, with the riders of both", () => { + const cards = rideCards(withTrack); + assert.deepEqual(cards.map((r) => r.id), ["rolling-hills", "herne-hill"]); + assert.deepEqual([cards[1].players, cards[1].phone_players], [3, 1]); + assert.equal(cardIdOf(clockwise, withTrack), "herne-hill"); + assert.equal(cardIdOf(herneHill, withTrack), "herne-hill"); + assert.equal(cardIdOf(routes[0], withTrack), "rolling-hills"); + assert.equal(cardIdOf(null, withTrack), null); + // A server that has only one way round shows it as it is. + assert.deepEqual(rideCards([clockwise]), [clockwise]); +}); + +test("picking the track's card keeps the way round already picked", () => { + assert.equal(cardPick("herne-hill", clockwise, withTrack), "herne-hill-clockwise"); + assert.equal(cardPick("herne-hill", routes[0], withTrack), "herne-hill"); + assert.equal(cardPick("rolling-hills", clockwise, withTrack), "rolling-hills"); +}); + +test("the way round is a choice of its own, with the riders going each way", () => { + assert.deepEqual(directionsOf(clockwise, withTrack), [ + { id: "herne-hill", label: "Anticlockwise", riders: "2 riders · 1 📱", picked: false }, + { id: "herne-hill-clockwise", label: "Clockwise", riders: "1 rider", picked: true }, + ]); + assert.deepEqual(directionsOf(routes[0], withTrack), []); + assert.deepEqual(directionsOf(clockwise, [clockwise]), []); + assert.deepEqual(directionsOf(null, withTrack), []); +}); + test("other routes don't", () => { assert.equal(routeCard(routes[0]).shared, false); assert.equal(sharedNote(routes[0]), ""); diff --git a/client/test/world3.test.js b/client/test/world3.test.js index 0863b988..77087ee5 100644 --- a/client/test/world3.test.js +++ b/client/test/world3.test.js @@ -361,8 +361,32 @@ test("routes turn on curves where they change roads, never on a corner", () => { // Built once per ridden route: the full map is the most expensive part of the suite. const [flatsRoute, hillsRoute, colRoute] = valley; +// The tracks beside the roads (#107): on the map, off the network. +const tracks = ["velodrome", "herne-hill", "herne-hill-clockwise"].map(loadRoute); // As the client builds it: the map's network and its other routes. -const mapWorld = buildWorld(hillsRoute, { network, others: valley }); +const mapWorld = buildWorld(hillsRoute, { network, others: [...valley, ...tracks] }); + +/** Whether the road mesh of `world` has asphalt within 1.5 m of route coordinates (x, y) at height `elevation`. */ +const asphaltAt = (world, x, y, elevation) => + world.chunks.road.some(({ mesh }) => { + const p = mesh.positions; + for (let i = 0; i < p.length; i += 3) { + if (Math.hypot(p[i] - x, p[i + 2] + y) < 1.5 && Math.abs(p[i + 1] - elevation) < 0.5) return true; + } + return false; + }); + +test("the tracks beside the roads are drawn and the ground is level under them", () => { + for (const track of tracks) { + for (let d = 0; d < track.length; d += 37) { + const { x, y } = track.positionAt(d); + const elevation = track.elevationAt(d); + assert.ok(asphaltAt(mapWorld, x, y, elevation), `${track.id} at ${d} m is drawn`); + const ground = mapWorld.terrain.height(x, -y); + assert.ok(Math.abs(ground - (elevation - 0.35)) < 0.05, `${track.id} at ${d} m: ground ${ground.toFixed(2)} under ${elevation} m`); + } + } +}); test("where a route cuts a junction's corner off the network's roads, it still counts as road", () => { // Routes round their corners at places by up to about 8 m off the network's roads; that asphalt is drawn too. for (const r of valley) { @@ -650,13 +674,14 @@ test("rivers run in valleys, not gorges", () => { }); test("the map world looks the same whichever route you ride", () => { - const fromCol = buildWorld(colRoute, { network, others: valley }); + // From a track, the other way round from the road the world was built from. + const fromTrack = buildWorld(tracks[1], { network, others: [...valley, ...tracks] }); const vertices = (world, name) => world.chunks[name].reduce((sum, c) => sum + c.mesh.vertexCount, 0); // Grass and flowers are thinner along roads you don't ride; the rest is the same. - for (const name of ["terrain", "scenery"]) assert.equal(vertices(fromCol, name), vertices(mapWorld, name), name); - assert.deepEqual(fromCol.rotors.map((r) => r.hub), mapWorld.rotors.map((r) => r.hub)); + for (const name of ["terrain", "scenery"]) assert.equal(vertices(fromTrack, name), vertices(mapWorld, name), name); + assert.deepEqual(fromTrack.rotors.map((r) => r.hub), mapWorld.rotors.map((r) => r.hub)); // Only the ridden route has arches and spectators. - assert.notDeepEqual(fromCol.spectators.map((p) => p.position), mapWorld.spectators.map((p) => p.position)); + assert.notDeepEqual(fromTrack.spectators.map((p) => p.position), mapWorld.spectators.map((p) => p.position)); }); test("one café at the shared start, however many routes start there", () => { diff --git a/docs/adr/0020-sharing-riders-with-openbikenet.md b/docs/adr/0020-sharing-riders-with-openbikenet.md index 225b6f85..c600a696 100644 --- a/docs/adr/0020-sharing-riders-with-openbikenet.md +++ b/docs/adr/0020-sharing-riders-with-openbikenet.md @@ -1,6 +1,6 @@ # 20. Sharing riders with OpenBikeNet -Date: 2026-11-06 · Status: accepted +Date: 2026-11-06 · Status: accepted, amended by [ADR 0027](0027-several-shared-tracks-in-one-world.md) (several shared tracks, bots per route) ## Context diff --git a/docs/adr/0027-several-shared-tracks-in-one-world.md b/docs/adr/0027-several-shared-tracks-in-one-world.md new file mode 100644 index 00000000..642c38ac --- /dev/null +++ b/docs/adr/0027-several-shared-tracks-in-one-world.md @@ -0,0 +1,43 @@ +# 27. Several shared tracks in one world + +Date: 2026-11-15 · Status: accepted · Amends [ADR 0020](0020-sharing-riders-with-openbikenet.md) + +## Context + +ADR 0020 shared exactly one route, the 250 m velodrome, as a world of its own +with no bots. OpenBikeNet now has a second shared track, Herne Hill Velodrome +(`herne-hill-450`, and `herne-hill-450-clockwise` the other way round), which +VeloPopuli rides too (#107). Both velodromes should stand on the island, so +riders on the roads, on the tracks and in other apps all see each other. The +island has bots on its roads, and its world holds many routes. + +## Decision + +- **Bots per route.** A route with `openbikenet` never gets bots, not even for + events (`SimConfig::routes_without_bots`); the other routes of its world keep + theirs. The tracks are not part of the road network, so no bot turns onto one. +- **The shared length is in the route file.** `openbikenet_length` (metres, + required with `openbikenet`) is the track's length as OpenBikeNet publishes + it. Positions are scaled between it and the local route's length and kept + below it. The fixed 250 m is gone. +- **One connection for all shared routes.** Still one link per world (today one + world has shared routes): it subscribes to every shared route and sends one + `update` with the riders of all of them. A rider who moves to another shared + route gets a `leave` first, then a `join` there, since rider keys are unique + per connection. +- **Everybody in the world sees riders of other apps**, nearest first, after + this server's own riders and within `max_visible_riders`, like riders of other + routes. Each shared route hands out its own range of ids (`0x0100_0000` each + from `0xF000_0000`), so the same remote rider id on two tracks is two riders. + `route_riders.remote` still counts those on the viewer's own route. + +Everything else in ADR 0020 stands: what is sent, the opt-in by picking a +shared route, no drafting or races with remote riders. + +## Consequences + +- Placing a shared track on any map is a matter of its route file: `map`, + `openbikenet` and `openbikenet_length`. +- A route file with `openbikenet` but no `openbikenet_length` no longer loads. +- Riders on the roads near a track see the riders of other apps on it, so the + state message carries remote riders for viewers on any route of the world. diff --git a/docs/deploy.md b/docs/deploy.md index 3140e578..48de3ef3 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -28,7 +28,7 @@ OPENRADLR_ALLOW_SIMULATED_TRAINER=false # only real trainers on the start scr OPENRADLR_ALLOW_PADDLE_MODE=true # phone paddles (marked 📱, no Strava, no ride files) OPENRADLR_PRIVACY_URL=https://ride.example.org/privacy/ # your privacy policy, linked in the start menu OPENRADLR_ANALYTICS_DOMAIN= # optional Plausible analytics, off when empty (see .env.example) -# OPENRADLR_OBN_URL=wss://obn.example/v0 # optional: share the velodrome with other apps (see OpenBikeNet below) +# OPENRADLR_OBN_URL=wss://obn.example/v0 # optional: share the tracks with other apps (see OpenBikeNet below) OPENRADLR_HTTP_BIND=127.0.0.1 # only the proxy on this machine can reach it OPENRADLR_HTTP_PORT=8080 COMPOSE_PROFILES= # leave the bundled Caddy off @@ -201,9 +201,10 @@ Things to know: ## OpenBikeNet (optional) Set `OPENRADLR_OBN_URL` (a `ws://` or `wss://` URL of an OpenBikeNet server) to share the -velodrome with riders of other apps. The server then sends the name, position, speed, power -and cadence of the riders on the velodrome, and shows the riders of other apps next to yours -(they have no bots there). Empty or unset = not connected; nothing is sent. If the connection +tracks (routes with `openbikenet`, such as the velodrome) with riders of other apps. The server +then sends the name, position, speed, power and cadence of the riders on those tracks, and shows +the riders of other apps to everyone in the world (the tracks have no bots). One connection +serves all tracks. Empty or unset = not connected; nothing is sent. If the connection drops, the other apps' riders vanish and the server reconnects with a growing pause (1 s up to a minute). `/api/info` marks the route with `"shared": true` while the link is configured. diff --git a/docs/protocol.md b/docs/protocol.md index 31da3c78..1ea72d1a 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -98,7 +98,7 @@ entered it, `next` the road they take at the next junction: their pick, else their route's, straight on off every route), `lap` (in a race, else `null`), `lane` (continuous, 0 = leftmost in riding direction), `speed`, `power`, and `device` (`sim`, `paddle` or `workout`; left out for -trainers and bots, so clients can mark phone paddlers and workouts), `vehicle`? (`id`, `kind`, `seat`, `seats`, `captain`: true for the current captain's seat) and `cadence` (only for seated riders, so each seat pedals at its own rate) and `parked` (true while pulled over for a pause, left out otherwise; always true for a workout rider) and `exercise` (the exercise a workout rider does now, left out at rest) and `side` (`right` or `left`, only for a sided pose, so the view can mirror the left side) and `app` (the id of the other app, for example `incyclist`, on a rider shared through OpenBikeNet; left out for riders of this server). Bots also carry `team` (their kit: `zitrone`, `moos`, `kirsche`, `lavendel`, `kreide`, `schiefer`, `petrol` or `rose`), `style` (their riding type: `rouleur`, `climber`, `sprinter`, `attacker` or `tourer`) and `move` (what they are doing: `pull`, `attack`, `answer` or `sprint`; left out while they just ride), see [bots](superpowers/specs/2026-11-10-bots-design.md) (#64); humans never have these fields. Such a remote rider has `is_bot: false`, an `id` from `0xF000_0000` upwards (never reused while the server runs), no physics, no drafting and no `vehicle`; clients show the name as text and mark the app. They appear only on a shared route (see ADR 0020). A studio rider shown on the road (only to clients who asked with `features`) has `route: null`, `studio` (`room`, `seat`), an `id` from `0xE000_0000` upwards, no `vehicle`, and counts neither in `route_riders` nor against the player limit. Riders of different routes draft each other +trainers and bots, so clients can mark phone paddlers and workouts), `vehicle`? (`id`, `kind`, `seat`, `seats`, `captain`: true for the current captain's seat) and `cadence` (only for seated riders, so each seat pedals at its own rate) and `parked` (true while pulled over for a pause, left out otherwise; always true for a workout rider) and `exercise` (the exercise a workout rider does now, left out at rest) and `side` (`right` or `left`, only for a sided pose, so the view can mirror the left side) and `app` (the id of the other app, for example `incyclist`, on a rider shared through OpenBikeNet; left out for riders of this server). Bots also carry `team` (their kit: `zitrone`, `moos`, `kirsche`, `lavendel`, `kreide`, `schiefer`, `petrol` or `rose`), `style` (their riding type: `rouleur`, `climber`, `sprinter`, `attacker` or `tourer`) and `move` (what they are doing: `pull`, `attack`, `answer` or `sprint`; left out while they just ride), see [bots](superpowers/specs/2026-11-10-bots-design.md) (#64); humans never have these fields. Such a remote rider has `is_bot: false`, an `id` from `0xF000_0000` upwards (each shared route its own range of `0x0100_0000`; never reused while the server runs), no physics, no drafting and no `vehicle`; clients show the name as text and mark the app. They ride only on shared routes, and every rider of that world gets them, nearest first, with their `route` (ADR 0020, 0027). A studio rider shown on the road (only to clients who asked with `features`) has `route: null`, `studio` (`room`, `seat`), an `id` from `0xE000_0000` upwards, no `vehicle`, and counts neither in `route_riders` nor against the player limit. Riders of different routes draft each other where they ride the same road the same way. Studio `riders[]` entries: `id`, `name`, `is_bot`, `seat` (0–7 front row, diff --git a/docs/routes.md b/docs/routes.md index 19ef9c1d..e90abe06 100644 --- a/docs/routes.md +++ b/docs/routes.md @@ -49,7 +49,8 @@ world of its own and is not confirmed against the official course yet (see | `map` | Optional: `{ "id", "seed" }` of the shared map the route belongs to (see below). | | `markers` | `start_finish`, `climb` and `sprint` (with `length`) for display; an optional `name` is shown in the banner (*KOM · Femés*). | | `geo` | Optional: `{ "lat", "lon" }` of the route's (0, 0) for exported rides. Without it, the world origin below. | -| `openbikenet` | Optional: the id of the OpenBikeNet track the route is shared on (the velodrome: `velodrome-250`). Riders of other apps ride it too, so its world has no bots. Passed through unchanged. | +| `openbikenet` | Optional: the id of the OpenBikeNet track the route is shared on (the velodrome: `velodrome-250`). Riders of other apps ride it too, so the route has no bots (the other routes of its world keep theirs, ADR 0027). Passed through unchanged. | +| `openbikenet_length` | Required with `openbikenet`: that track's length in metres as OpenBikeNet publishes it (`250`). Positions are scaled between it and this route's length. | | `zones` | Optional scenery: `village`, `forest` and `cliff` (with `from`/`to`; a cliff gets a guard rail on the sea side), `river` (with `at`, where it crosses under a bridge). | Zones are pure decoration: the server passes them through, clients build the @@ -71,12 +72,24 @@ Distances along the route are horizontal; the grade is rise over horizontal run, measured over 50 m of road around the rider (so it eases from one segment to the next instead of stepping at each point). Keep grades realistic (below about 12 %). -The bundled `velodrome` is the exception to the café rule and to the length -of the others: a 250 m oval of two 50 m straights and two semicircles (flat, -4 lanes, `"zones": []`, no map), generated by `node tools/velodrome-route.mjs > -routes/velodrome.json`. It carries `"openbikenet": "velodrome-250"`, so its -world has no bots and is meant to be shared with riders from other apps when the -server is connected to OpenBikeNet. +The bundled tracks are the exception to the café rule and to the length of +the others, and they aren't walks over the road network: `velodrome`, a 250 m +oval of two 50 m straights and two semicircles, and `herne-hill` with +`herne-hill-clockwise`, the 450 m outdoor track of Herne Hill Velodrome in +London (bend radius 45.3 m as in OpenBikeNet's GPS track), ridden +anticlockwise as in racing and the other way round from the same line. They are +flat, 4 lanes, `"zones": []`, and stand on the island (`map` `valley`) on the +flat strip south of the `valley-west` road, the home straight facing the road, +so a connector road can join them later. `node tools/track-route.mjs > +routes/.json` writes them. Each carries `openbikenet` (`velodrome-250`, +`herne-hill-450`, `herne-hill-450-clockwise`) and `openbikenet_length`, so it +has no bots and is shared with riders from other apps when the server is +connected to OpenBikeNet. A world can hold several shared tracks; one +connection serves them all (ADR 0027). A route whose id is another's with +`-clockwise` added is that track the other way round: the start menu shows the +two as one card, with a choice of the way round. On a map with a road network, +the client draws the map's routes that aren't walks over its roads (the +tracks) along with the roads, and levels the ground under them. Every route starts at a bike café beside the road, 45 m after the start/finish line (on a road network: at its start café). diff --git a/docs/superpowers/plans/2026-11-15-shared-tracks-on-the-island.md b/docs/superpowers/plans/2026-11-15-shared-tracks-on-the-island.md new file mode 100644 index 00000000..6a2959ee --- /dev/null +++ b/docs/superpowers/plans/2026-11-15-shared-tracks-on-the-island.md @@ -0,0 +1,23 @@ +# Shared Tracks on the Island Implementation Plan + +**Goal:** Both velodromes on the island, Herne Hill shared with other apps, everybody seeing each other (#107). + +**Architecture:** Server first: bots per route instead of per world, the shared length from the route file, one OpenBikeNet link for every shared route of a world, riders of other apps shown to the whole world. Then the Herne Hill routes, their place on the island and the client. + +**Spec:** `docs/superpowers/specs/2026-11-15-shared-tracks-on-the-island-design.md` + +## Global Constraints + +- Branch `feat/shared-tracks`, one PR, one commit per task, each green. +- Failing test first (CONTRIBUTING.md). `make check` (via Docker) before every commit. +- Wire stays additive: protocol version unchanged. + +## Tasks + +- [x] **1. Bots per route** — sim: a route can be marked without bots; `balance_population` leaves it at zero, the others at `target_riders`. Server: `sim_config_for` goes, routes with `openbikenet` are marked. Tests: a world of a road and a shared track has bots on the road only. +- [x] **2. Shared length from the route file** — `RouteFile.openbikenet_length`, required with `openbikenet`, positive; `routes/velodrome.json` gets 250. `Outbox` and `Remotes` take lengths per route; `OBN_LENGTH_M` goes. +- [x] **3. One link for several routes** — `LocalRider.route`; `Outbox` keyed by rider with its route: leave and join on a change of route, leaves before joins; `spawn_link` takes the routes and their lengths and subscribes to each. Tests in `outbox.rs` and `tests/openbikenet.rs`. +- [x] **4. Several shared routes in a world, seen by everyone** — `GameCore::with_openbikenet` takes the list; one `Remotes` per route with its own id range; frames carry every shared route's humans; `with_remotes` adds riders of other apps for every viewer, nearest first. `app.rs` wires all shared routes of a world to one link. +- [x] **5. Docs for the server part** — ADR 0027 (amends 0020), `docs/routes.md` (`openbikenet_length`, several shared routes), `docs/architecture.md` if it describes the link. +- [x] **6. Herne Hill routes** (after protocol#6) — generator for the 450 m oval both ways, route files with `map` `valley`; the 250 m velodrome moves onto the island. +- [x] **7. Client** — tracks drawn on the island, start menu (one Herne Hill entry with a direction choice), i18n, screenshots. diff --git a/docs/superpowers/specs/2026-11-15-shared-tracks-on-the-island-design.md b/docs/superpowers/specs/2026-11-15-shared-tracks-on-the-island-design.md new file mode 100644 index 00000000..14a1146e --- /dev/null +++ b/docs/superpowers/specs/2026-11-15-shared-tracks-on-the-island-design.md @@ -0,0 +1,73 @@ +# Shared tracks on the island — design + +Date: 2026-11-15 · Issue: #107 · Status: implemented + +## Goal + +Both velodromes, the 250 m oval (`velodrome-250`) and Herne Hill (`herne-hill-450`, and +`herne-hill-450-clockwise` the other way round, OpenBikeNet/protocol#6), stand on the island, so +everybody sees each other: riders on the roads, riders on the tracks, and riders of other apps on +the tracks. Lanzarote stays a world of its own. + +## Today + +ADR 0020 shares exactly one route, the velodrome, a world of its own: + +- `app.rs` gives a world with a shared route no bots at all (`sim_config_for`) and starts one + OpenBikeNet link for the first shared route it finds. +- `GameCore` keeps one `Obn` (route, frames, remotes) and shows riders of other apps only to + riders on that route (`with_remotes`). +- `obn::OBN_LENGTH_M = 250.0` scales distances both ways; `Outbox` and `Remotes` serve one route. + +## Decisions + +- **Bots per route, not per world.** A route with `openbikenet` gets no bots; the other routes of + its world keep theirs. The tracks aren't part of the road network, so bots can't turn onto them. + Other apps still never see our bots (they are never sent), and riders of other apps on a track + aren't hidden in a crowd of bots. +- **The shared length comes from the route file.** `openbikenet` stays the route id; a new + `openbikenet_length` (metres, required with `openbikenet`) replaces `OBN_LENGTH_M`. The local + route is drawn to that length, but to within a few millimetres, so the protocol's own length is + needed to keep `distance < length`. +- **One link per server, all shared routes.** The protocol allows several `subscribe`s on one + connection, and one `update` carries riders on any routes (spec v0 §3.4, §6). `Outbox` keeps + each joined rider's route: a rider who moves to another shared route gets `leave` and a new + `join`, and leaves go out before joins in a frame, since rider keys are unique per connection. + Today all shared routes are in one world; one link per world stays the rule. +- **Riders of other apps are seen by everyone in the world.** Each shared route keeps its own + `Remotes` (ids in its own range, so two tracks never hand out the same id). Every viewer gets + them added after the local riders, nearest first, within `max_visible_riders`, as riders of + other routes are today. `route_riders.remote` counts those on the viewer's own route. +- **Herne Hill's two directions are two OpenRadlr routes** on the same oval, the points reversed. + +## Place on the island + +- **Off the road network for now, with room for a junction later.** The tracks are plain routes + with `map` `valley`, not network edges, so bots and junction turns stay as they are. But each + oval stands on flat ground with its home straight, the one with the start/finish line, + facing a road 35–50 m away, at about the road's height. A short connector road from that + straight to the road can later be added as an edge with a junction at both ends, without + moving the track (the tracks would then become network edges too). +- **Both on the flat strip south of `valley-west`** (about 35 m above sea level, more than 250 m + from the nearest café): Herne Hill's centre near (−480, −150), the 250 m oval's near + (−210, −120), east of the river that crosses the strip, long axes east–west, the north + straight facing the road. + +## Client + +- **Tracks drawn on the island.** With a road network, `buildWorld` draws the network's roads + only. The map's routes that aren't walks over them (the tracks) are drawn and levelled with + the roads, whichever route is ridden, so the world looks the same from all of them. +- **One Herne Hill card.** A route whose id is another's with `-clockwise` added is that track + the other way round. The start menu shows one card with the riders of both, and under the + picked track's name a choice of the way round, with the riders going each way. + +## Testing + +Unit tests in the sim (routes without bots), `route_file` (the new field), `obn::outbox` (several +routes, a rider changing route), `obn::remote` (id ranges), `game` (bots stay on the roads, +remote riders for viewers on other routes, frames per route), and the end-to-end +`tests/openbikenet.rs` (one connection subscribes to two routes). A sim test rides a track +without a walk on a map with a network. Client tests: the tracks are drawn and the ground is +level under them, the world looks the same from a track, and the start menu's card and choice +of the way round. diff --git a/routes/herne-hill-clockwise.json b/routes/herne-hill-clockwise.json new file mode 100644 index 00000000..5b44b7ed --- /dev/null +++ b/routes/herne-hill-clockwise.json @@ -0,0 +1,137 @@ +{ + "id": "herne-hill-clockwise", + "name": "Herne Hill Velodrome (clockwise)", + "description": "Herne Hill Velodrome the other way round, from the same start/finish line; shared with riders from other apps when this server is connected to OpenBikeNet.", + "loop": true, + "lanes": 4, + "seed": 451, + "map": { + "id": "valley", + "seed": 2026 + }, + "openbikenet": "herne-hill-450-clockwise", + "openbikenet_length": 450, + "zones": [], + "markers": [ + {"type":"start_finish","distance":0} + ], + "points": [ + [-466.998959,-104.696373,35.3], + [-438.653764,-104.696373,35.3], + [-436.158088,-104.765166,35.3], + [-433.669992,-104.971336,35.3], + [-431.197032,-105.314256,35.3], + [-428.746717,-105.792885,35.3], + [-426.32649,-106.40577,35.3], + [-423.9437,-107.151049,35.3], + [-421.605584,-108.026459,35.3], + [-419.319243,-109.029341,35.3], + [-417.091621,-110.156649,35.3], + [-414.929481,-111.404961,35.3], + [-412.839392,-112.770485,35.3], + [-410.8277,-114.249073,35.3], + [-408.900515,-115.836236,35.3], + [-407.06369,-117.527153,35.3], + [-405.322802,-119.316688,35.3], + [-403.68314,-121.199409,35.3], + [-402.149682,-123.169595,35.3], + [-400.727086,-125.221265,35.3], + [-399.419672,-127.348187,35.3], + [-398.231411,-129.543901,35.3], + [-397.165911,-131.80174,35.3], + [-396.226408,-134.114847,35.3], + [-395.415756,-136.476196,35.3], + [-394.736416,-138.878617,35.3], + [-394.190451,-141.314813,35.3], + [-393.779521,-143.777386,35.3], + [-393.504872,-146.258856,35.3], + [-393.367338,-148.751688,35.3], + [-393.367338,-151.248312,35.3], + [-393.504872,-153.741144,35.3], + [-393.779521,-156.222614,35.3], + [-394.190451,-158.685187,35.3], + [-394.736416,-161.121383,35.3], + [-395.415756,-163.523804,35.3], + [-396.226408,-165.885153,35.3], + [-397.165911,-168.19826,35.3], + [-398.231411,-170.456099,35.3], + [-399.419672,-172.651813,35.3], + [-400.727086,-174.778735,35.3], + [-402.149682,-176.830405,35.3], + [-403.68314,-178.800591,35.3], + [-405.322802,-180.683312,35.3], + [-407.06369,-182.472847,35.3], + [-408.900515,-184.163764,35.3], + [-410.8277,-185.750927,35.3], + [-412.839392,-187.229515,35.3], + [-414.929481,-188.595039,35.3], + [-417.091621,-189.843351,35.3], + [-419.319243,-190.970659,35.3], + [-421.605584,-191.973541,35.3], + [-423.9437,-192.848951,35.3], + [-426.32649,-193.59423,35.3], + [-428.746717,-194.207115,35.3], + [-431.197032,-194.685744,35.3], + [-433.669992,-195.028664,35.3], + [-436.158088,-195.234834,35.3], + [-438.653764,-195.303627,35.3], + [-521.346236,-195.303627,35.3], + [-523.841912,-195.234834,35.3], + [-526.330008,-195.028664,35.3], + [-528.802968,-194.685744,35.3], + [-531.253283,-194.207115,35.3], + [-533.67351,-193.59423,35.3], + [-536.0563,-192.848951,35.3], + [-538.394416,-191.973541,35.3], + [-540.680757,-190.970659,35.3], + [-542.908379,-189.843351,35.3], + [-545.070519,-188.595039,35.3], + [-547.160608,-187.229515,35.3], + [-549.1723,-185.750927,35.3], + [-551.099485,-184.163764,35.3], + [-552.93631,-182.472847,35.3], + [-554.677198,-180.683312,35.3], + [-556.31686,-178.800591,35.3], + [-557.850318,-176.830405,35.3], + [-559.272914,-174.778735,35.3], + [-560.580328,-172.651813,35.3], + [-561.768589,-170.456099,35.3], + [-562.834089,-168.19826,35.3], + [-563.773592,-165.885153,35.3], + [-564.584244,-163.523804,35.3], + [-565.263584,-161.121383,35.3], + [-565.809549,-158.685187,35.3], + [-566.220479,-156.222614,35.3], + [-566.495128,-153.741144,35.3], + [-566.632662,-151.248312,35.3], + [-566.632662,-148.751688,35.3], + [-566.495128,-146.258856,35.3], + [-566.220479,-143.777386,35.3], + [-565.809549,-141.314813,35.3], + [-565.263584,-138.878617,35.3], + [-564.584244,-136.476196,35.3], + [-563.773592,-134.114847,35.3], + [-562.834089,-131.80174,35.3], + [-561.768589,-129.543901,35.3], + [-560.580328,-127.348187,35.3], + [-559.272914,-125.221265,35.3], + [-557.850318,-123.169595,35.3], + [-556.31686,-121.199409,35.3], + [-554.677198,-119.316688,35.3], + [-552.93631,-117.527153,35.3], + [-551.099485,-115.836236,35.3], + [-549.1723,-114.249073,35.3], + [-547.160608,-112.770485,35.3], + [-545.070519,-111.404961,35.3], + [-542.908379,-110.156649,35.3], + [-540.680757,-109.029341,35.3], + [-538.394416,-108.026459,35.3], + [-536.0563,-107.151049,35.3], + [-533.67351,-106.40577,35.3], + [-531.253283,-105.792885,35.3], + [-528.802968,-105.314256,35.3], + [-526.330008,-104.971336,35.3], + [-523.841912,-104.765166,35.3], + [-521.346236,-104.696373,35.3] + ] +} diff --git a/routes/herne-hill.json b/routes/herne-hill.json new file mode 100644 index 00000000..3c595cf0 --- /dev/null +++ b/routes/herne-hill.json @@ -0,0 +1,137 @@ +{ + "id": "herne-hill", + "name": "Herne Hill Velodrome", + "description": "The 450 m outdoor track of Herne Hill Velodrome in London, ridden anticlockwise as in racing; shared with riders from other apps when this server is connected to OpenBikeNet.", + "loop": true, + "lanes": 4, + "seed": 450, + "map": { + "id": "valley", + "seed": 2026 + }, + "openbikenet": "herne-hill-450", + "openbikenet_length": 450, + "zones": [], + "markers": [ + {"type":"start_finish","distance":0} + ], + "points": [ + [-466.998959,-104.696373,35.3], + [-521.346236,-104.696373,35.3], + [-523.841912,-104.765166,35.3], + [-526.330008,-104.971336,35.3], + [-528.802968,-105.314256,35.3], + [-531.253283,-105.792885,35.3], + [-533.67351,-106.40577,35.3], + [-536.0563,-107.151049,35.3], + [-538.394416,-108.026459,35.3], + [-540.680757,-109.029341,35.3], + [-542.908379,-110.156649,35.3], + [-545.070519,-111.404961,35.3], + [-547.160608,-112.770485,35.3], + [-549.1723,-114.249073,35.3], + [-551.099485,-115.836236,35.3], + [-552.93631,-117.527153,35.3], + [-554.677198,-119.316688,35.3], + [-556.31686,-121.199409,35.3], + [-557.850318,-123.169595,35.3], + [-559.272914,-125.221265,35.3], + [-560.580328,-127.348187,35.3], + [-561.768589,-129.543901,35.3], + [-562.834089,-131.80174,35.3], + [-563.773592,-134.114847,35.3], + [-564.584244,-136.476196,35.3], + [-565.263584,-138.878617,35.3], + [-565.809549,-141.314813,35.3], + [-566.220479,-143.777386,35.3], + [-566.495128,-146.258856,35.3], + [-566.632662,-148.751688,35.3], + [-566.632662,-151.248312,35.3], + [-566.495128,-153.741144,35.3], + [-566.220479,-156.222614,35.3], + [-565.809549,-158.685187,35.3], + [-565.263584,-161.121383,35.3], + [-564.584244,-163.523804,35.3], + [-563.773592,-165.885153,35.3], + [-562.834089,-168.19826,35.3], + [-561.768589,-170.456099,35.3], + [-560.580328,-172.651813,35.3], + [-559.272914,-174.778735,35.3], + [-557.850318,-176.830405,35.3], + [-556.31686,-178.800591,35.3], + [-554.677198,-180.683312,35.3], + [-552.93631,-182.472847,35.3], + [-551.099485,-184.163764,35.3], + [-549.1723,-185.750927,35.3], + [-547.160608,-187.229515,35.3], + [-545.070519,-188.595039,35.3], + [-542.908379,-189.843351,35.3], + [-540.680757,-190.970659,35.3], + [-538.394416,-191.973541,35.3], + [-536.0563,-192.848951,35.3], + [-533.67351,-193.59423,35.3], + [-531.253283,-194.207115,35.3], + [-528.802968,-194.685744,35.3], + [-526.330008,-195.028664,35.3], + [-523.841912,-195.234834,35.3], + [-521.346236,-195.303627,35.3], + [-438.653764,-195.303627,35.3], + [-436.158088,-195.234834,35.3], + [-433.669992,-195.028664,35.3], + [-431.197032,-194.685744,35.3], + [-428.746717,-194.207115,35.3], + [-426.32649,-193.59423,35.3], + [-423.9437,-192.848951,35.3], + [-421.605584,-191.973541,35.3], + [-419.319243,-190.970659,35.3], + [-417.091621,-189.843351,35.3], + [-414.929481,-188.595039,35.3], + [-412.839392,-187.229515,35.3], + [-410.8277,-185.750927,35.3], + [-408.900515,-184.163764,35.3], + [-407.06369,-182.472847,35.3], + [-405.322802,-180.683312,35.3], + [-403.68314,-178.800591,35.3], + [-402.149682,-176.830405,35.3], + [-400.727086,-174.778735,35.3], + [-399.419672,-172.651813,35.3], + [-398.231411,-170.456099,35.3], + [-397.165911,-168.19826,35.3], + [-396.226408,-165.885153,35.3], + [-395.415756,-163.523804,35.3], + [-394.736416,-161.121383,35.3], + [-394.190451,-158.685187,35.3], + [-393.779521,-156.222614,35.3], + [-393.504872,-153.741144,35.3], + [-393.367338,-151.248312,35.3], + [-393.367338,-148.751688,35.3], + [-393.504872,-146.258856,35.3], + [-393.779521,-143.777386,35.3], + [-394.190451,-141.314813,35.3], + [-394.736416,-138.878617,35.3], + [-395.415756,-136.476196,35.3], + [-396.226408,-134.114847,35.3], + [-397.165911,-131.80174,35.3], + [-398.231411,-129.543901,35.3], + [-399.419672,-127.348187,35.3], + [-400.727086,-125.221265,35.3], + [-402.149682,-123.169595,35.3], + [-403.68314,-121.199409,35.3], + [-405.322802,-119.316688,35.3], + [-407.06369,-117.527153,35.3], + [-408.900515,-115.836236,35.3], + [-410.8277,-114.249073,35.3], + [-412.839392,-112.770485,35.3], + [-414.929481,-111.404961,35.3], + [-417.091621,-110.156649,35.3], + [-419.319243,-109.029341,35.3], + [-421.605584,-108.026459,35.3], + [-423.9437,-107.151049,35.3], + [-426.32649,-106.40577,35.3], + [-428.746717,-105.792885,35.3], + [-431.197032,-105.314256,35.3], + [-433.669992,-104.971336,35.3], + [-436.158088,-104.765166,35.3], + [-438.653764,-104.696373,35.3] + ] +} diff --git a/routes/velodrome.json b/routes/velodrome.json index 8125bdb2..84e115a8 100644 --- a/routes/velodrome.json +++ b/routes/velodrome.json @@ -5,73 +5,78 @@ "loop": true, "lanes": 4, "seed": 250, + "map": { + "id": "valley", + "seed": 2026 + }, "openbikenet": "velodrome-250", + "openbikenet_length": 250, "zones": [], "markers": [ {"type":"start_finish","distance":0} ], "points": [ - [0,0,40], - [50.01371,0,40], - [52.509827,0.130816,40], - [54.978597,0.521831,40], - [57.39297,1.16876,40], - [59.726494,2.064516,40], - [61.953603,3.199285,40], - [64.049896,4.560634,40], - [65.992406,6.133647,40], - [67.75985,7.901091,40], - [69.332863,9.843601,40], - [70.694212,11.939894,40], - [71.828981,14.167003,40], - [72.724737,16.500527,40], - [73.371666,18.9149,40], - [73.762681,21.38367,40], - [73.893497,23.879787,40], - [73.762681,26.375905,40], - [73.371666,28.844674,40], - [72.724737,31.259047,40], - [71.828981,33.592572,40], - [70.694212,35.819681,40], - [69.332863,37.915974,40], - [67.75985,39.858484,40], - [65.992406,41.625928,40], - [64.049896,43.198941,40], - [61.953603,44.56029,40], - [59.726494,45.695059,40], - [57.39297,46.590815,40], - [54.978597,47.237744,40], - [52.509827,47.628759,40], - [50.01371,47.759575,40], - [0,47.759575,40], - [-2.496117,47.628759,40], - [-4.964887,47.237744,40], - [-7.37926,46.590815,40], - [-9.712785,45.695059,40], - [-11.939894,44.56029,40], - [-14.036187,43.198941,40], - [-15.978697,41.625928,40], - [-17.74614,39.858484,40], - [-19.319154,37.915974,40], - [-20.680502,35.819681,40], - [-21.815271,33.592572,40], - [-22.711027,31.259047,40], - [-23.357957,28.844674,40], - [-23.748971,26.375905,40], - [-23.879787,23.879787,40], - [-23.748971,21.38367,40], - [-23.357957,18.9149,40], - [-22.711027,16.500527,40], - [-21.815271,14.167003,40], - [-20.680502,11.939894,40], - [-19.319154,9.843601,40], - [-17.74614,7.901091,40], - [-15.978697,6.133647,40], - [-14.036187,4.560634,40], - [-11.939894,3.199285,40], - [-9.712785,2.064516,40], - [-7.37926,1.16876,40], - [-4.964887,0.521831,40], - [-2.496117,0.130816,40] + [-184.993145,-96.120213,35.4], + [-235.006855,-96.120213,35.4], + [-237.502972,-96.251029,35.4], + [-239.971742,-96.642043,35.4], + [-242.386115,-97.288973,35.4], + [-244.719639,-98.184729,35.4], + [-246.946749,-99.319498,35.4], + [-249.043042,-100.680846,35.4], + [-250.985551,-102.25386,35.4], + [-252.752995,-104.021303,35.4], + [-254.326009,-105.963813,35.4], + [-255.687357,-108.060106,35.4], + [-256.822126,-110.287215,35.4], + [-257.717882,-112.62074,35.4], + [-258.364812,-115.035113,35.4], + [-258.755826,-117.503883,35.4], + [-258.886642,-120,35.4], + [-258.755826,-122.496117,35.4], + [-258.364812,-124.964887,35.4], + [-257.717882,-127.37926,35.4], + [-256.822126,-129.712785,35.4], + [-255.687357,-131.939894,35.4], + [-254.326009,-134.036187,35.4], + [-252.752995,-135.978697,35.4], + [-250.985551,-137.74614,35.4], + [-249.043042,-139.319154,35.4], + [-246.946749,-140.680502,35.4], + [-244.719639,-141.815271,35.4], + [-242.386115,-142.711027,35.4], + [-239.971742,-143.357957,35.4], + [-237.502972,-143.748971,35.4], + [-235.006855,-143.879787,35.4], + [-184.993145,-143.879787,35.4], + [-182.497028,-143.748971,35.4], + [-180.028258,-143.357957,35.4], + [-177.613885,-142.711027,35.4], + [-175.280361,-141.815271,35.4], + [-173.053251,-140.680502,35.4], + [-170.956958,-139.319154,35.4], + [-169.014449,-137.74614,35.4], + [-167.247005,-135.978697,35.4], + [-165.673991,-134.036187,35.4], + [-164.312643,-131.939894,35.4], + [-163.177874,-129.712785,35.4], + [-162.282118,-127.37926,35.4], + [-161.635188,-124.964887,35.4], + [-161.244174,-122.496117,35.4], + [-161.113358,-120,35.4], + [-161.244174,-117.503883,35.4], + [-161.635188,-115.035113,35.4], + [-162.282118,-112.62074,35.4], + [-163.177874,-110.287215,35.4], + [-164.312643,-108.060106,35.4], + [-165.673991,-105.963813,35.4], + [-167.247005,-104.021303,35.4], + [-169.014449,-102.25386,35.4], + [-170.956958,-100.680846,35.4], + [-173.053251,-99.319498,35.4], + [-175.280361,-98.184729,35.4], + [-177.613885,-97.288973,35.4], + [-180.028258,-96.642043,35.4], + [-182.497028,-96.251029,35.4] ] } diff --git a/server/crates/server/src/app.rs b/server/crates/server/src/app.rs index b3853274..50fbf649 100644 --- a/server/crates/server/src/app.rs +++ b/server/crates/server/src/app.rs @@ -9,6 +9,7 @@ use crate::guard::Slots; use crate::http::{router, AppState, Protection}; use crate::map_file::load_maps; use crate::obn::link::spawn_link; +use crate::obn::SharedRoute; use crate::resume::ResumeTokens; use crate::route_file::{load_routes, RouteFile}; use crate::runtime::spawn_game; @@ -40,14 +41,17 @@ const STATS_SAVE_EVERY: Duration = Duration::from_secs(60); pub type BoxError = Box; -/// The simulation settings of one world. A world with a route shared through -/// OpenBikeNet has no bots: its riders come from other apps. +/// The simulation settings of one world. Routes shared through OpenBikeNet get +/// no bots: their riders are humans, of this app or of others. fn sim_config_for(config: &Config, group: &[RouteFile]) -> SimConfig { - let mut sim = config.sim_config(); - if group.iter().any(|file| file.openbikenet.is_some()) { - sim.target_riders = 0; + SimConfig { + routes_without_bots: group + .iter() + .filter(|file| file.openbikenet.is_some()) + .map(|file| file.id.clone()) + .collect(), + ..config.sim_config() } - sim } /// Builds the application. Must be called inside a Tokio runtime because it @@ -175,16 +179,21 @@ pub fn build_with_stats(config: &Config) -> Result<(Router, DistanceStats), BoxE // The map's first route stands for the world: a route id clients can rejoin with. .with_vehicle_codes(vehicle_codes.clone(), route_ids[0].clone()) .with_resume_tokens(resume_tokens.clone()); - // The world with the OpenBikeNet route shares it, if a server is configured. - let shared_index = group + // The world's OpenBikeNet routes are shared, all on one link, if a server is configured. + let shared: Vec<(usize, SharedRoute)> = group .iter() - .position(|f| f.openbikenet.is_some()) - .filter(|_| config.obn_url.is_some()); - let obn_route = shared_index.map(|index| group[index].openbikenet.clone().unwrap_or_default()); + .enumerate() + .filter(|_| config.obn_url.is_some()) + .filter_map(|(index, file)| { + let id = file.openbikenet.clone()?; + let length = file.openbikenet_length.unwrap_or_default(); + Some((index, SharedRoute::new(id, length, routes[index].length()))) + }) + .collect(); let mut link_frames = None; - if let (Some(index), Some(obn_route)) = (shared_index, &obn_route) { + if !shared.is_empty() { let (frames, receiver) = tokio::sync::mpsc::channel(OBN_FRAME_BACKLOG); - core = core.with_openbikenet(index, obn_route, frames); + core = core.with_openbikenet(shared.clone(), frames); link_frames = Some(receiver); } if let (Some(anchor), true) = (studio_anchor, config.studio && !studio_in_valley) { @@ -192,14 +201,17 @@ pub fn build_with_stats(config: &Config) -> Result<(Router, DistanceStats), BoxE studio_in_valley = true; } let game = spawn_game(core); - if let (Some(index), Some(obn_route), Some(receiver), Some(url)) = - (shared_index, obn_route, link_frames, &config.obn_url) - { - tracing::info!(route = %obn_route, "sharing the route through OpenBikeNet"); + if let (Some(receiver), Some(url)) = (link_frames, &config.obn_url) { + let shared_routes: Vec = shared.iter().map(|(_, route)| route.clone()).collect(); + let ids = shared_routes + .iter() + .map(|r| r.id.as_str()) + .collect::>() + .join(", "); + tracing::info!(routes = %ids, "sharing routes through OpenBikeNet"); spawn_link( url.clone(), - obn_route, - routes[index].length(), + shared_routes, config.obn_backoff_unit, config.obn_heartbeat, receiver, @@ -216,7 +228,7 @@ pub fn build_with_stats(config: &Config) -> Result<(Router, DistanceStats), BoxE ); for (position, (file, route)) in group.into_iter().zip(routes).enumerate() { entries.push(WorldEntry { - shared: shared_index == Some(position), + shared: shared.iter().any(|(index, _)| *index == position), length_m: route.length(), elevation_gain_m: file.elevation_gain_m(), file: Arc::new(file), @@ -379,26 +391,28 @@ mod tests { const ROUTES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../../routes"); - fn world_of(config: &Config, id: &str) -> World { - let file = RouteFile::load(&Path::new(ROUTES_DIR).join(format!("{id}.json"))).unwrap(); - let route = file.to_route().unwrap(); - let sim = sim_config_for(config, std::slice::from_ref(&file)); - World::new(route, sim, Box::new(SplitMix64::new(1))) + fn world_of(config: &Config, ids: &[&str]) -> World { + let files: Vec = ids + .iter() + .map(|id| RouteFile::load(&Path::new(ROUTES_DIR).join(format!("{id}.json"))).unwrap()) + .collect(); + let routes = files.iter().map(|f| f.to_route().unwrap()).collect(); + let sim = sim_config_for(config, &files); + World::with_network(routes, None, sim, Box::new(SplitMix64::new(1))) } #[test] - fn shared_route_world_has_no_bots() { + fn shared_routes_have_no_bots_and_the_other_routes_of_their_world_do() { let config = Config { target_riders: 3, ..Config::default() }; - let mut velodrome = world_of(&config, "velodrome"); - let mut other = world_of(&config, "rolling-hills"); + let mut world = world_of(&config, &["rolling-hills", "velodrome"]); for _ in 0..20 { - velodrome.tick(0.1); - other.tick(0.1); + world.tick(0.1); } - assert_eq!(velodrome.bot_count(), 0); - assert_eq!(other.bot_count(), 3); + let bots_on = |route| world.riders().filter(|r| r.route == route && r.is_bot()).count(); + assert_eq!(bots_on(0), 3); + assert_eq!(bots_on(1), 0); } } diff --git a/server/crates/server/src/game.rs b/server/crates/server/src/game.rs index 40223e6c..3e52d797 100644 --- a/server/crates/server/src/game.rs +++ b/server/crates/server/src/game.rs @@ -8,6 +8,7 @@ use crate::obn::outbox::LocalRider; use crate::obn::remote::{RemoteEvent, RemoteRider, Remotes}; +use crate::obn::SharedRoute; use crate::protocol::{ event_info, event_message, event_notice_message, event_state, nearest_riders, state_message, DeviceKind, EventInfoWire, EventState, Exercise, InputAction, PhysicsWire, RiderState, RiderTags, ServerMessage, Side, @@ -208,7 +209,7 @@ pub struct GameCore { departed: HashMap, /// Resume tokens and who is detached (#73). attachments: Attachments, - /// The shared OpenBikeNet route, if this world has one. + /// The routes shared through OpenBikeNet, if this world has any. obn: Option, /// The link to the spin studio building, if this world has one. studio: Option, @@ -244,10 +245,15 @@ impl StudioLink { } } -/// What a world with an OpenBikeNet route needs: where it is, the way out and the riders in. +/// What a world with OpenBikeNet routes needs: the way out and, per route, the riders in. struct Obn { - route: RouteIndex, frames: mpsc::Sender>, + tracks: Vec, +} + +/// One route of the world shared through OpenBikeNet. +struct SharedTrack { + route: RouteIndex, remotes: Remotes, /// The remote riders as of the last tick, shared by all viewers. shown: Vec, @@ -340,22 +346,25 @@ impl GameCore { self } - /// Shares `route` with other apps through OpenBikeNet as `shared_route`: once a second the humans on it go - /// out as a frame on `frames` (dropped if the link is behind), and riders coming back - /// arrive through [`GameCore::remote`]. + /// Shares each route of `routes` with other apps through OpenBikeNet as its + /// [`SharedRoute`]: once a second the humans on them go out as one frame on `frames` + /// (dropped if the link is behind), and riders coming back arrive through + /// [`GameCore::remote`]. Everybody in the world sees them. pub fn with_openbikenet( mut self, - route: RouteIndex, - shared_route: &str, + routes: Vec<(RouteIndex, SharedRoute)>, frames: mpsc::Sender>, ) -> Self { - let remotes = Remotes::new(shared_route, self.world.route(route).length()); - self.obn = Some(Obn { - route, - frames, - remotes, - shown: Vec::new(), - }); + let tracks = routes + .into_iter() + .enumerate() + .map(|(index, (route, shared))| SharedTrack { + route, + remotes: Remotes::new(shared, index as u32), + shown: Vec::new(), + }) + .collect(); + self.obn = Some(Obn { frames, tracks }); self } @@ -363,12 +372,15 @@ impl GameCore { pub fn remote(&mut self, event: RemoteEvent) { let now = self.clock_s(); if let Some(obn) = &mut self.obn { - obn.remotes.apply(event, now); - obn.shown = obn.remotes.riders(now); + // Each track takes the messages about its own route. + for track in &mut obn.tracks { + track.remotes.apply(event.clone(), now); + track.shown = track.remotes.riders(now); + } } } - /// Hands this second's humans on the shared route to the link, without waiting for it. + /// Hands this second's humans on the shared routes to the link, without waiting for it. fn send_obn_frame(&self) { let Some(obn) = &self.obn else { return; @@ -379,14 +391,18 @@ impl GameCore { let frame = self .world .riders() - .filter(|r| r.route == obn.route && r.off_route.is_none() && !r.is_bot() && !r.workout) - .map(|r| LocalRider { - id: r.id, - name: r.name.clone(), - position: r.position, - speed: r.speed, - power: r.power, - cadence: r.cadence, + .filter(|r| r.off_route.is_none() && !r.is_bot() && !r.workout) + .filter_map(|r| { + let track = obn.tracks.iter().find(|t| t.route == r.route)?; + Some(LocalRider { + id: r.id, + route: track.remotes.route().id.clone(), + name: r.name.clone(), + position: r.position, + speed: r.speed, + power: r.power, + cadence: r.cadence, + }) }) .collect(); // A full or closed channel loses the frame; the next one supersedes it. @@ -429,12 +445,12 @@ impl GameCore { self.with_studio(viewer, self.with_remotes(viewer, state)) } - /// `state` with the riders of other apps added, if it is for a rider on the shared route. + /// `state` with the riders of other apps added, nearest first, wherever `viewer` rides. fn with_remotes(&self, viewer: RiderId, state: ServerMessage) -> ServerMessage { let (Some(obn), Some(me)) = (&self.obn, self.world.rider(viewer)) else { return state; }; - if me.route != obn.route || obn.shown.is_empty() { + if obn.tracks.iter().all(|t| t.shown.is_empty()) { return state; } let ServerMessage::State { @@ -448,15 +464,27 @@ impl GameCore { else { return state; }; - let route = self.world.route(obn.route); + let (x, y) = self.world.rider_xy(me); + let mut remotes: Vec<(f64, RiderState)> = obn + .tracks + .iter() + .flat_map(|track| { + let route = self.world.route(track.route); + track.shown.iter().map(move |r| { + let (rx, ry) = route.position_at(r.distance); + ((rx - x).hypot(ry - y), RiderState::remote(r, route.id(), route.lanes())) + }) + }) + .collect(); + remotes.sort_by(|a, b| a.0.total_cmp(&b.0)); let room = self.settings.max_visible_riders.saturating_sub(riders.len()); - riders.extend( - obn.shown - .iter() - .take(room) - .map(|r| RiderState::remote(r, route.id(), route.lanes())), - ); - route_riders.remote = obn.shown.len(); + riders.extend(remotes.into_iter().take(room).map(|(_, rider)| rider)); + route_riders.remote = obn + .tracks + .iter() + .filter(|t| t.route == me.route) + .map(|t| t.shown.len()) + .sum(); ServerMessage::State { tick, riders, @@ -1011,7 +1039,9 @@ impl GameCore { let now = self.clock_s(); if let Some(obn) = &mut self.obn { // Once per tick for everybody, not per viewer. - obn.shown = obn.remotes.riders(now); + for track in &mut obn.tracks { + track.shown = track.remotes.riders(now); + } } self.send_obn_frame(); @@ -2835,11 +2865,166 @@ mod tests { fn obn_game(target_riders: usize, capacity: usize) -> (GameCore, mpsc::Receiver>) { let (frames, receiver) = mpsc::channel(capacity); ( - game(target_riders, 10).with_openbikenet(0, "velodrome-250", frames), + { + let game = game(target_riders, 10); + let length = game.world().route(0).length(); + game.with_openbikenet(vec![(0, SharedRoute::new("velodrome-250", 250.0, length))], frames) + }, receiver, ) } + /// A square track of `side` metres a side, its corner at `(x, 0)`. + fn track(id: &str, x: f64, side: f64) -> Route { + Route::new(RouteSpec { + id: id.into(), + name: id.into(), + lanes: 4, + seed: 1, + points: vec![ + Point::new(x, 0.0, 0.0), + Point::new(x + side, 0.0, 0.0), + Point::new(x + side, side, 0.0), + Point::new(x, side, 0.0), + ], + markers: vec![], + walk: vec![], + }) + .unwrap() + } + + /// A world of the road `test` and two shared tracks, `small` (velodrome-250) + /// and `big` (herne-hill-450), the road keeping 2 bots. + fn island_game() -> (GameCore, mpsc::Receiver>) { + let world = World::with_network( + vec![hilly_route(), track("small", 600.0, 62.5), track("big", 800.0, 112.5)], + None, + SimConfig { + target_riders: 2, + routes_without_bots: vec!["small".into(), "big".into()], + ..SimConfig::default() + }, + Box::new(SplitMix64::new(1)), + ); + let (frames, receiver) = mpsc::channel(4); + let game = GameCore::new(world, GameSettings::default()).with_openbikenet( + vec![ + (1, SharedRoute::new("velodrome-250", 250.0, 250.0)), + (2, SharedRoute::new("herne-hill-450", 450.0, 450.0)), + ], + frames, + ); + (game, receiver) + } + + fn snapshot_on(route: &str, id: &str, name: &str) -> RemoteEvent { + RemoteEvent::Message(crate::obn::wire::ServerMessage::Snapshot { + route: route.into(), + room: "public".into(), + riders: vec![crate::obn::wire::RemoteView { + id: id.into(), + app: "velopopuli".into(), + name: name.into(), + lap: 0, + distance: 10.0, + speed: 0.0, + power: Some(180.0), + cadence: None, + }], + }) + } + + /// The last state message `sink` got after a broadcast. + fn state_after_broadcast(game: &mut GameCore, sink: &RecordingSink) -> ServerMessage { + sink.take(); + for _ in 0..game.settings().broadcast_every() { + game.tick(); + } + sink.take() + .into_iter() + .rev() + .find(|m| matches!(m, ServerMessage::State { .. })) + .expect("a state message") + } + + #[test] + fn riders_of_other_apps_on_every_track_are_seen_from_the_road() { + let (mut game, _frames) = island_game(); + let (_, sink) = join(&mut game, "Anna"); + game.remote(snapshot_on("velodrome-250", "a", "Cleo")); + game.remote(snapshot_on("herne-hill-450", "a", "Dan")); + let ServerMessage::State { + riders, route_riders, .. + } = state_after_broadcast(&mut game, &sink) + else { + unreachable!() + }; + let cleo = riders.iter().find(|r| r.name == "Cleo").expect("Cleo is shown"); + let dan = riders.iter().find(|r| r.name == "Dan").expect("Dan is shown"); + assert_eq!(cleo.route.as_deref(), Some("small")); + assert_eq!(dan.route.as_deref(), Some("big")); + assert!((dan.distance - 10.0).abs() < 0.01); + assert_ne!(cleo.id, dan.id, "the same remote id on two tracks is two riders"); + assert_eq!(route_riders.remote, 0, "none of them is on Anna's road"); + } + + #[test] + fn route_riders_count_the_riders_of_other_apps_on_my_track() { + let (mut game, _frames) = island_game(); + let sink = RecordingSink::default(); + game.join("Anna", 70.0, None, None, Some("big"), None, Box::new(sink.clone())) + .unwrap(); + game.remote(snapshot_on("velodrome-250", "a", "Cleo")); + game.remote(snapshot_on("herne-hill-450", "b", "Dan")); + let ServerMessage::State { route_riders, .. } = state_after_broadcast(&mut game, &sink) else { + unreachable!() + }; + assert_eq!(route_riders.remote, 1); + } + + #[test] + fn frames_carry_the_humans_of_every_track_and_no_one_else() { + let (mut game, mut frames) = island_game(); + let (road, _) = join(&mut game, "Anna"); + let small = game + .join( + "Ben", + 70.0, + None, + None, + Some("small"), + None, + Box::new(RecordingSink::default()), + ) + .unwrap(); + let big = game + .join( + "Cleo", + 70.0, + None, + None, + Some("big"), + None, + Box::new(RecordingSink::default()), + ) + .unwrap(); + for _ in 0..game.settings().tick_hz { + game.tick(); + } + let mut frame: Vec<(RiderId, String)> = frames + .try_recv() + .expect("one frame after a second") + .into_iter() + .map(|r| (r.id, r.route)) + .collect(); + frame.sort(); + assert_eq!(frame, [(small, "velodrome-250".into()), (big, "herne-hill-450".into())]); + assert!(game + .world() + .riders() + .all(|r| r.id == road || !r.is_bot() || r.route == 0)); + } + fn snapshot_of_ben() -> RemoteEvent { RemoteEvent::Message(crate::obn::wire::ServerMessage::Snapshot { route: "velodrome-250".into(), diff --git a/server/crates/server/src/obn/link.rs b/server/crates/server/src/obn/link.rs index 6f302ab1..87e7883a 100644 --- a/server/crates/server/src/obn/link.rs +++ b/server/crates/server/src/obn/link.rs @@ -21,7 +21,7 @@ use tokio_tungstenite::tungstenite::Message; use super::outbox::{LocalRider, Outbox}; use super::remote::RemoteEvent; use super::wire::{AppInfo, AppMessage, ServerMessage}; -use super::OBN_ROOM; +use super::{SharedRoute, OBN_ROOM}; use crate::runtime::{Command, GameHandle}; /// Longest pause between connection attempts, in units. @@ -54,23 +54,23 @@ pub fn backoff(attempt: u32, unit: Duration) -> Duration { unit.saturating_mul(factor.min(MAX_BACKOFF_UNITS)) } -/// Starts the link to `url` for the shared `route`. It ends when the game stops. +/// Starts the link to `url` for the shared `routes`, all on one connection. It ends +/// when the game stops. pub fn spawn_link( url: String, - route: String, - route_length_m: f64, + routes: Vec, backoff_unit: Duration, heartbeat: Heartbeat, mut frames: mpsc::Receiver>, game: GameHandle, ) -> JoinHandle<()> { tokio::spawn(async move { - let mut outbox = Outbox::new(route.clone(), route_length_m); + let mut outbox = Outbox::new(routes); let mut attempt = 0u32; loop { // Frames queued while disconnected are stale: the next one tells the whole story. while frames.try_recv().is_ok() {} - let end = session(&url, &route, heartbeat, &mut outbox, &mut frames, &game).await; + let end = session(&url, heartbeat, &mut outbox, &mut frames, &game).await; if end.stopped { return; } @@ -123,7 +123,6 @@ fn text(message: &AppMessage) -> Message { /// One connection, from connecting to the first failure. async fn session( url: &str, - route: &str, heartbeat: Heartbeat, outbox: &mut Outbox, frames: &mut mpsc::Receiver>, @@ -147,11 +146,12 @@ async fn session( }; tracing::info!("OpenBikeNet: connected"); let (mut sink, mut stream) = socket.split(); - let subscribe = AppMessage::Subscribe { - route: route.to_owned(), + let subscribes = outbox.routes().iter().map(|route| AppMessage::Subscribe { + route: route.id.clone(), room: OBN_ROOM.into(), - }; - for message in [hello(), subscribe] { + }); + let opening: Vec = std::iter::once(hello()).chain(subscribes).collect(); + for message in opening { if sink.send(text(&message)).await.is_err() { tracing::info!("OpenBikeNet: connection dropped"); return end; diff --git a/server/crates/server/src/obn/mod.rs b/server/crates/server/src/obn/mod.rs index c6af73c6..e4fb5f25 100644 --- a/server/crates/server/src/obn/mod.rs +++ b/server/crates/server/src/obn/mod.rs @@ -8,8 +8,52 @@ pub mod outbox; pub mod remote; pub mod wire; -/// Length of the shared route, in metres. The OpenBikeNet route `velodrome-250` is 250 m. -pub const OBN_LENGTH_M: f64 = 250.0; - /// The room every rider joins (spec 6.2). pub const OBN_ROOM: &str = "public"; + +/// A route shared through OpenBikeNet and the local route it is drawn onto. +#[derive(Debug, Clone, PartialEq)] +pub struct SharedRoute { + /// The OpenBikeNet route id, e.g. `velodrome-250`. + pub id: String, + /// Its length as OpenBikeNet publishes it, in metres. + pub length_m: f64, + /// The length of the local route, in metres. + pub local_length_m: f64, +} + +impl SharedRoute { + pub fn new(id: impl Into, length_m: f64, local_length_m: f64) -> Self { + Self { + id: id.into(), + length_m, + local_length_m, + } + } + + /// A local position scaled onto the shared route, kept below its length (spec 6.4). + pub fn shared_distance(&self, position: f64) -> f64 { + let position = if position.is_finite() { position } else { 0.0 }; + (position * self.length_m / self.local_length_m).clamp(0.0, self.length_m - 0.01) + } + + /// Metres on the shared route to metres on the local one. + pub fn local_distance(&self, distance: f64) -> f64 { + distance * self.local_length_m / self.length_m + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn positions_scale_to_the_shared_length_and_stay_below_it() { + let herne_hill = SharedRoute::new("herne-hill-450", 450.0, 450.006); + assert!((herne_hill.shared_distance(225.003) - 225.0).abs() < 0.001); + assert!((herne_hill.shared_distance(450.006) - 449.99).abs() < 0.001); + assert!((herne_hill.shared_distance(460.0) - 449.99).abs() < 0.001); + assert_eq!(herne_hill.shared_distance(f64::NAN), 0.0); + assert!((herne_hill.local_distance(225.0) - 225.003).abs() < 0.001); + } +} diff --git a/server/crates/server/src/obn/outbox.rs b/server/crates/server/src/obn/outbox.rs index f1b0f4b2..cebc1a30 100644 --- a/server/crates/server/src/obn/outbox.rs +++ b/server/crates/server/src/obn/outbox.rs @@ -9,12 +9,14 @@ use std::collections::BTreeMap; use openradlr_sim::RiderId; use super::wire::{AppMessage, RiderEntry, RiderState}; -use super::{OBN_LENGTH_M, OBN_ROOM}; +use super::{SharedRoute, OBN_ROOM}; /// One of this server's riders, as the game loop sees it. #[derive(Debug, Clone, PartialEq)] pub struct LocalRider { pub id: RiderId, + /// The OpenBikeNet id of the shared route the rider is on. + pub route: String, pub name: String, /// Metres along the route from its start line. pub position: f64, @@ -23,84 +25,92 @@ pub struct LocalRider { pub cadence: Option, } -/// A rider this outbox has joined, with its lap count since joining. -#[derive(Debug, Clone, Copy)] +/// A rider this outbox has joined, on which route, with its lap count since joining. +#[derive(Debug, Clone)] struct Joined { + route: String, lap: u32, last_position: f64, } -/// Messages for one OpenBikeNet route, built frame by frame. +/// Messages for the OpenBikeNet routes of one connection, built frame by frame. #[derive(Debug)] pub struct Outbox { - route: String, - route_length_m: f64, + routes: Vec, joined: BTreeMap, } impl Outbox { - pub fn new(route: String, route_length_m: f64) -> Self { + pub fn new(routes: Vec) -> Self { Self { - route, - route_length_m, + routes, joined: BTreeMap::new(), } } - /// The messages for one frame: joins for new riders, one `update` for the - /// riders that joined earlier, and leaves for riders that are gone. Empty when there is + /// The messages for one frame: leaves for riders that are gone or moved to another + /// route (rider keys are unique per connection, so the leave goes first), joins for + /// new riders, and one `update` for the riders that joined earlier, on any route. + /// Riders on routes this outbox doesn't share are left out. Empty when there is /// nothing to say. pub fn frame(&mut self, riders: &[LocalRider]) -> Vec { - let mut joins = Vec::new(); + let riders: Vec<(&LocalRider, &SharedRoute)> = riders + .iter() + .filter_map(|rider| { + let route = self.routes.iter().find(|route| route.id == rider.route)?; + Some((rider, route)) + }) + .collect(); + + let mut messages = Vec::new(); + self.joined.retain(|id, joined| { + let stays = riders + .iter() + .any(|(rider, _)| rider.id == *id && rider.route == joined.route); + if !stays { + messages.push(AppMessage::Leave { rider: rider_key(*id) }); + } + stays + }); + let mut entries = Vec::new(); - for rider in riders { + for (rider, route) in riders { match self.joined.get_mut(&rider.id) { Some(joined) => { // Positions wrap at the start line: a big step back is a crossing. - if joined.last_position - rider.position > self.route_length_m / 2.0 { + if joined.last_position - rider.position > route.local_length_m / 2.0 { joined.lap += 1; } joined.last_position = rider.position; entries.push(RiderEntry { rider: rider_key(rider.id), - state: state_of(joined.lap, rider, self.route_length_m), + state: state_of(joined.lap, rider, route), }); } None => { self.joined.insert( rider.id, Joined { + route: route.id.clone(), lap: 0, last_position: rider.position, }, ); // The join carries the starting state; an update in the same // frame would be rate limited (the server counts the join as one). - joins.push(AppMessage::Join { + messages.push(AppMessage::Join { rider: rider_key(rider.id), - route: self.route.clone(), + route: route.id.clone(), room: OBN_ROOM.into(), name: rider.name.clone(), - state: state_of(0, rider, self.route_length_m), + state: state_of(0, rider, route), }); } } } - - let mut leaves = Vec::new(); - self.joined.retain(|id, _| { - let present = riders.iter().any(|rider| rider.id == *id); - if !present { - leaves.push(AppMessage::Leave { rider: rider_key(*id) }); - } - present - }); - - let mut messages = joins; if !entries.is_empty() { messages.push(AppMessage::Update { riders: entries }); } - messages.extend(leaves); messages } @@ -108,6 +118,11 @@ impl Outbox { pub fn reset(&mut self) { self.joined.clear(); } + + /// The routes this outbox shares, to subscribe to. + pub fn routes(&self) -> &[SharedRoute] { + &self.routes + } } /// The app's rider value for one of this server's riders (spec 6.3: `r`). @@ -115,10 +130,10 @@ fn rider_key(id: RiderId) -> String { format!("r{id}") } -fn state_of(lap: u32, rider: &LocalRider, route_length_m: f64) -> RiderState { +fn state_of(lap: u32, rider: &LocalRider, route: &SharedRoute) -> RiderState { RiderState { lap, - distance: distance_m(rider.position, route_length_m), + distance: route.shared_distance(rider.position), speed: speed_m_s(rider.speed), power: Some(finite_or_zero(rider.power).round().clamp(0.0, 3000.0) as u32), cadence: rider @@ -127,11 +142,6 @@ fn state_of(lap: u32, rider: &LocalRider, route_length_m: f64) -> RiderState { } } -/// Position scaled onto the shared route, kept below its length (spec 6.4). -fn distance_m(position: f64, route_length_m: f64) -> f64 { - (finite_or_zero(position) * OBN_LENGTH_M / route_length_m).clamp(0.0, 249.99) -} - /// Speed in m/s, rounded to centimetres per second and within 0 to 30 (spec 6.4). fn speed_m_s(speed: f64) -> f64 { (finite_or_zero(speed) * 100.0).round().clamp(0.0, 3000.0) / 100.0 @@ -154,8 +164,13 @@ mod tests { const LENGTH: f64 = 250.0; fn rider(id: RiderId, position: f64) -> LocalRider { + rider_on(id, "velodrome-250", position) + } + + fn rider_on(id: RiderId, route: &str, position: f64) -> LocalRider { LocalRider { id, + route: route.into(), name: format!("rider {id}"), position, speed: 10.0, @@ -165,7 +180,14 @@ mod tests { } fn outbox() -> Outbox { - Outbox::new("velodrome-250".into(), LENGTH) + Outbox::new(vec![SharedRoute::new("velodrome-250", 250.0, LENGTH)]) + } + + fn two_tracks() -> Outbox { + Outbox::new(vec![ + SharedRoute::new("velodrome-250", 250.0, 250.0), + SharedRoute::new("herne-hill-450", 450.0, 450.0), + ]) } fn kinds(messages: &[AppMessage]) -> Vec<&'static str> { @@ -217,6 +239,44 @@ mod tests { assert!(matches!(&frame[0], AppMessage::Join { rider, .. } if rider == "r8")); } + #[test] + fn riders_on_two_tracks_join_their_own_and_share_one_update() { + let mut outbox = two_tracks(); + let first = outbox.frame(&[rider_on(7, "velodrome-250", 10.0), rider_on(8, "herne-hill-450", 400.0)]); + assert_eq!(kinds(&first), ["join", "join"]); + let joins: Vec<(&str, f64)> = first + .iter() + .map(|m| match m { + AppMessage::Join { route, state, .. } => (route.as_str(), state.distance), + other => panic!("expected a join, got {other:?}"), + }) + .collect(); + assert_eq!(joins, [("velodrome-250", 10.0), ("herne-hill-450", 400.0)]); + + let second = outbox.frame(&[rider_on(7, "velodrome-250", 20.0), rider_on(8, "herne-hill-450", 410.0)]); + assert_eq!(kinds(&second), ["update"]); + assert_eq!(update_entries(&second).len(), 2); + } + + #[test] + fn a_rider_who_changes_track_leaves_before_joining_the_other() { + let mut outbox = two_tracks(); + outbox.frame(&[rider_on(7, "velodrome-250", 240.0)]); + outbox.frame(&[rider_on(7, "velodrome-250", 0.5)]); // lap 1 + + let moved = outbox.frame(&[rider_on(7, "herne-hill-450", 5.0)]); + assert_eq!(kinds(&moved), ["leave", "join"]); + assert!( + matches!(&moved[1], AppMessage::Join { route, state, .. } if route == "herne-hill-450" && state.lap == 0) + ); + } + + #[test] + fn riders_on_routes_that_are_not_shared_are_left_out() { + let mut outbox = two_tracks(); + assert!(outbox.frame(&[rider_on(7, "rolling-hills", 10.0)]).is_empty()); + } + #[test] fn missing_rider_leaves() { let mut outbox = outbox(); @@ -261,7 +321,7 @@ mod tests { #[test] fn distance_stays_below_length() { - let mut outbox = Outbox::new("velodrome-250".into(), 250.004); + let mut outbox = Outbox::new(vec![SharedRoute::new("velodrome-250", 250.0, 250.004)]); outbox.frame(&[rider(7, 1.0)]); let at_end = update_entries(&outbox.frame(&[rider(7, 250.004)])); assert!(at_end[0].state.distance < 250.0); @@ -270,7 +330,7 @@ mod tests { let beyond = update_entries(&outbox.frame(&[rider(7, 251.0)])); assert!(beyond[0].state.distance < 250.0); - let mut outbox = Outbox::new("velodrome-250".into(), 250.004); + let mut outbox = Outbox::new(vec![SharedRoute::new("velodrome-250", 250.0, 250.004)]); outbox.frame(&[rider(7, 1.0)]); let halfway = update_entries(&outbox.frame(&[rider(7, 125.002)])); assert!((halfway[0].state.distance - 125.0).abs() < 0.01); @@ -282,6 +342,7 @@ mod tests { let mut sample = |speed: f64, power: f64, cadence: Option| { let local = LocalRider { id: 7, + route: "velodrome-250".into(), name: "Anna".into(), position: 10.0, speed, diff --git a/server/crates/server/src/obn/remote.rs b/server/crates/server/src/obn/remote.rs index 1d71ee57..74d9c113 100644 --- a/server/crates/server/src/obn/remote.rs +++ b/server/crates/server/src/obn/remote.rs @@ -10,10 +10,12 @@ use openradlr_sim::RiderId; use crate::game::clean_foreign_name; use super::wire::{RemoteUpdate, RemoteView, ServerMessage}; -use super::{OBN_LENGTH_M, OBN_ROOM}; +use super::{SharedRoute, OBN_ROOM}; /// Remote riders get ids from here upwards, far from the sim's own (which count up from 1). const FIRST_REMOTE_ID: RiderId = 0xF000_0000; +/// Ids each shared route hands out, so that riders on two routes never share one. +const IDS_PER_ROUTE: RiderId = 0x0100_0000; /// Longest time a position is extrapolated from the last update. const MAX_EXTRAPOLATION_S: f64 = 2.0; /// A rider without an update for longer than this is hidden until the next one. @@ -60,24 +62,27 @@ struct Known { #[derive(Debug)] pub struct Remotes { /// The shared route subscribed to; messages about any other route or room are ignored. - route: String, - route_length_m: f64, + route: SharedRoute, next_id: RiderId, riders: HashMap, } impl Remotes { - /// `route` is the shared route's id, `route_length_m` the length of the local route - /// it is drawn onto. - pub fn new(route: impl Into, route_length_m: f64) -> Self { + /// The riders on `route`, the `index`th shared route of the world (0 to 15): it + /// picks the range their ids come from. + pub fn new(route: SharedRoute, index: u32) -> Self { Self { - route: route.into(), - route_length_m, - next_id: FIRST_REMOTE_ID, + route, + next_id: FIRST_REMOTE_ID + index.min(15) * IDS_PER_ROUTE, riders: HashMap::new(), } } + /// The shared route these riders are on. + pub fn route(&self) -> &SharedRoute { + &self.route + } + pub fn len(&self) -> usize { self.riders.len() } @@ -125,7 +130,7 @@ impl Remotes { pub fn riders(&mut self, now_s: f64) -> Vec { self.riders .retain(|_, known| now_s - known.heard_at_s <= FORGET_AFTER_S); - let length = self.route_length_m; + let length = self.route.local_length_m; let mut out: Vec = self .riders .values() @@ -154,7 +159,7 @@ impl Remotes { ServerMessage::Snapshot { route, room, .. } | ServerMessage::Joined { route, room, .. } | ServerMessage::Updated { route, room, .. } - | ServerMessage::Left { route, room, .. } => *route == self.route && room == OBN_ROOM, + | ServerMessage::Left { route, room, .. } => *route == self.route.id && room == OBN_ROOM, _ => true, } } @@ -165,11 +170,6 @@ impl Remotes { id } - /// Metres on the shared route to metres on the local one. - fn local(&self, distance: f64) -> f64 { - distance * self.route_length_m / OBN_LENGTH_M - } - fn insert(&mut self, id: RiderId, view: RemoteView, now_s: f64) { // Names and app ids come from strangers: same filter as local names. let app = clean_foreign_name(&view.app).unwrap_or_else(|| "?".into()); @@ -178,7 +178,7 @@ impl Remotes { id, app, name, - distance: self.local(view.distance), + distance: self.route.local_distance(view.distance), speed: view.speed, power: view.power.unwrap_or(0.0), cadence: view.cadence, @@ -188,7 +188,7 @@ impl Remotes { } fn update(&mut self, update: RemoteUpdate, now_s: f64) { - let distance = self.local(update.distance); + let distance = self.route.local_distance(update.distance); if let Some(known) = self.riders.get_mut(&update.id) { known.distance = distance; known.speed = update.speed; @@ -256,7 +256,7 @@ mod tests { } fn remotes() -> Remotes { - Remotes::new("velodrome-250", 250.0) + Remotes::new(SharedRoute::new("velodrome-250", 250.0, 250.0), 0) } fn named<'a>(riders: &'a [RemoteRider], name: &str) -> &'a RemoteRider { @@ -433,7 +433,7 @@ mod tests { #[test] fn distance_is_scaled_to_the_local_length() { - let mut r = Remotes::new("velodrome-250", 500.0); + let mut r = Remotes::new(SharedRoute::new("velodrome-250", 250.0, 500.0), 0); r.apply(joined(view("a", "Ann", 100.0, 0.0)), 0.0); assert_eq!(r.riders(0.0)[0].distance, 200.0); } diff --git a/server/crates/server/src/route_file.rs b/server/crates/server/src/route_file.rs index 4f68af2c..a5a24fa6 100644 --- a/server/crates/server/src/route_file.rs +++ b/server/crates/server/src/route_file.rs @@ -30,9 +30,13 @@ pub struct RouteFile { #[serde(default, skip_serializing_if = "Option::is_none")] pub zones: Option>, /// The id of the OpenBikeNet track this route is shared on: riders of - /// other apps ride it too, so the world has no bots. Passed through unchanged. + /// other apps ride it too, so it has no bots. Passed through unchanged. #[serde(default, skip_serializing_if = "Option::is_none")] pub openbikenet: Option, + /// The length of that track as OpenBikeNet publishes it, in metres; required + /// with `openbikenet`. Positions are scaled between it and this route's length. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub openbikenet_length: Option, /// The shared map this route belongs to: clients draw all routes with the /// same map id as one world (ADR 0010, stage 1). Passed through unchanged. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -115,6 +119,8 @@ pub enum RouteFileError { Io(std::io::Error), Json(serde_json::Error), Invalid(RouteError), + /// `openbikenet` without a positive `openbikenet_length`. + SharedLength, } impl fmt::Display for RouteFileError { @@ -123,6 +129,9 @@ impl fmt::Display for RouteFileError { RouteFileError::Io(e) => write!(f, "could not read route file: {e}"), RouteFileError::Json(e) => write!(f, "route file is not valid JSON: {e}"), RouteFileError::Invalid(e) => write!(f, "route is invalid: {e}"), + RouteFileError::SharedLength => { + write!(f, "a route with openbikenet needs a positive openbikenet_length") + } } } } @@ -131,7 +140,12 @@ impl std::error::Error for RouteFileError {} impl RouteFile { pub fn parse(json: &str) -> Result { - serde_json::from_str(json).map_err(RouteFileError::Json) + let file: Self = serde_json::from_str(json).map_err(RouteFileError::Json)?; + let length_ok = file.openbikenet_length.is_some_and(|m| m.is_finite() && m > 0.0); + if file.openbikenet.is_some() && !length_ok { + return Err(RouteFileError::SharedLength); + } + Ok(file) } pub fn load(path: &Path) -> Result { @@ -297,11 +311,27 @@ mod tests { assert!(!serde_json::to_string(&file).unwrap().contains("openbikenet")); } + #[test] + fn a_shared_route_needs_the_length_of_the_track_it_is_shared_on() { + let base = r#""id":"x","name":"x","lanes":2,"seed":1,"points":[[0,0,0],[9,0,0]],"openbikenet":"track-9""#; + assert!(matches!( + RouteFile::parse(&format!("{{{base}}}")), + Err(RouteFileError::SharedLength) + )); + assert!(matches!( + RouteFile::parse(&format!(r#"{{{base},"openbikenet_length":0}}"#)), + Err(RouteFileError::SharedLength) + )); + let file = RouteFile::parse(&format!(r#"{{{base},"openbikenet_length":9}}"#)).unwrap(); + assert_eq!(file.openbikenet_length, Some(9.0)); + } + #[test] fn velodrome_is_250_m_and_shared() { let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../../routes/velodrome.json"); let file = RouteFile::load(Path::new(path)).unwrap(); assert_eq!(file.openbikenet.as_deref(), Some("velodrome-250")); + assert_eq!(file.openbikenet_length, Some(250.0)); let route = file.to_route().unwrap(); assert!((route.length() - 250.0).abs() < 0.01, "{}", route.length()); } diff --git a/server/crates/server/tests/openbikenet.rs b/server/crates/server/tests/openbikenet.rs index 9cab546d..086a8e9d 100644 --- a/server/crates/server/tests/openbikenet.rs +++ b/server/crates/server/tests/openbikenet.rs @@ -213,10 +213,10 @@ async fn api_info_marks_the_route_shared() { let linked = serve(config(Some(url))).await; let info: Value = serde_json::from_str(&http_get(linked, "/api/info").await).unwrap(); for route in info["routes"].as_array().unwrap() { - if route["id"] == "velodrome" { - assert_eq!(route["shared"], true); + if ["velodrome", "herne-hill", "herne-hill-clockwise"].contains(&route["id"].as_str().unwrap()) { + assert_eq!(route["shared"], true, "{route}"); } else { - assert!(route.get("shared").is_none(), "only the velodrome is shared: {route}"); + assert!(route.get("shared").is_none(), "only the tracks are shared: {route}"); } } @@ -316,3 +316,47 @@ async fn a_pong_keeps_the_connection() { let again = tokio::time::timeout(Duration::from_millis(300), listener.accept()).await; assert!(again.is_err(), "the app reconnected although the server answered"); } + +/// Two shared tracks on one map, in a fresh directory: the bundled velodrome and a +/// copy of it shared as `herne-hill-450`. +fn two_tracks_dir() -> PathBuf { + let dir = std::env::temp_dir().join(format!("openradlr-two-tracks-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let velodrome = std::fs::read_to_string(PathBuf::from(ROUTES_DIR).join("velodrome.json")).unwrap(); + let mut small: Value = serde_json::from_str(&velodrome).unwrap(); + small["map"] = serde_json::json!({ "id": "tracks", "seed": 1 }); + let mut big = small.clone(); + big["id"] = "big".into(); + big["openbikenet"] = "herne-hill-450".into(); + big["openbikenet_length"] = 450.into(); + std::fs::write(dir.join("velodrome.json"), small.to_string()).unwrap(); + std::fs::write(dir.join("big.json"), big.to_string()).unwrap(); + dir +} + +#[tokio::test] +async fn one_connection_subscribes_to_every_shared_track_of_a_world() { + let dir = two_tracks_dir(); + let (listener, url) = fake_server().await; + let _addr = serve(Config { + route_file: dir.join("velodrome.json"), + routes_dir: Some(dir.clone()), + ..velodrome_config(Some(url)) + }) + .await; + let mut fake = accept(&listener).await; + assert_eq!(recv(&mut fake).await["type"], "hello"); + let mut routes = Vec::new(); + for _ in 0..2 { + let subscribe = recv(&mut fake).await; + assert_eq!(subscribe["type"], "subscribe"); + routes.push(subscribe["route"].as_str().unwrap().to_owned()); + } + routes.sort(); + assert_eq!(routes, ["herne-hill-450", "velodrome-250"]); + // No second connection: both tracks share this one. + assert!(tokio::time::timeout(Duration::from_millis(300), listener.accept()) + .await + .is_err()); + std::fs::remove_dir_all(dir).ok(); +} diff --git a/server/crates/server/tests/websocket_flow.rs b/server/crates/server/tests/websocket_flow.rs index e2f6b201..2ce503b1 100644 --- a/server/crates/server/tests/websocket_flow.rs +++ b/server/crates/server/tests/websocket_flow.rs @@ -204,15 +204,19 @@ async fn info_lists_every_route_with_the_default_first() { assert_eq!(routes[0]["id"], "rolling-hills"); assert_eq!(info["route"]["id"], "rolling-hills"); assert_eq!(info["players"], 0); - // The velodrome is a 250 m oval; every other bundled route is a road route. + // The tracks are short ovals; every other bundled route is a road route. + let length = |r: &&Value| r["length_m"].as_f64().unwrap(); + let mut tracks: Vec<&str> = routes + .iter() + .filter(|r| length(r) < 1000.0) + .map(|r| r["id"].as_str().unwrap()) + .collect(); + tracks.sort_unstable(); + assert_eq!(tracks, ["herne-hill", "herne-hill-clockwise", "velodrome"]); assert!(routes .iter() - .filter(|r| r["id"] != "velodrome") - .all(|r| r["length_m"].as_f64().unwrap() > 3000.0)); - assert!( - routes.iter().any(|r| r["id"] == "velodrome"), - "the velodrome is bundled" - ); + .filter(|r| length(r) >= 1000.0) + .all(|r| length(&r) > 3000.0)); let other = routes[1]["id"].as_str().unwrap(); let (status, body) = http_get(addr, &format!("/api/route?id={other}")).await; diff --git a/server/crates/sim/src/world.rs b/server/crates/sim/src/world.rs index 2c4d3875..d0d5131f 100644 --- a/server/crates/sim/src/world.rs +++ b/server/crates/sim/src/world.rs @@ -44,6 +44,9 @@ pub struct SimConfig { /// Humans plus bots the world keeps riding on every route /// (`OPENRADLR_TARGET_RIDERS`; 0: no bots at all). pub target_riders: usize, + /// Ids of routes that never get bots, not even for events (tracks shared + /// with other apps): their riders are humans only. + pub routes_without_bots: Vec, /// Bots every human riding a route keeps around them: up to /// `company_radius_m` ahead or `company_behind_m` behind. They come out /// of the route's `target_riders`: far bots make room, the count stays. @@ -87,6 +90,7 @@ impl Default for SimConfig { fn default() -> Self { Self { target_riders: 12, + routes_without_bots: Vec::new(), bots_near_human: 6, company_radius_m: 1500.0, company_behind_m: 400.0, @@ -1248,7 +1252,7 @@ impl World { /// Spawns `count` bots on `route` matched to `levels_wkg` (they stay while /// entered or in a group ride). Returns their ids. pub fn spawn_event_bots(&mut self, route: RouteIndex, count: usize, levels_wkg: &[f64]) -> Vec { - if route >= self.routes.len() { + if route >= self.routes.len() || !self.has_bots(route) { return Vec::new(); } (0..count).map(|_| self.spawn_bot_matched(route, levels_wkg)).collect() @@ -1316,12 +1320,22 @@ impl World { && !self.seat_of.contains_key(&r.id) } + /// Whether `route` may have bots (see [`SimConfig::routes_without_bots`]). + fn has_bots(&self, route: RouteIndex) -> bool { + let id = self.routes[route].id(); + !self.config.routes_without_bots.iter().any(|r| r == id) + } + /// Keeps every route at `target_riders`: company for its humans first /// (far bots making room), then groups where the route is emptiest; /// surplus bots leave once no human is nearby. fn balance_population(&mut self) { - let target = self.config.target_riders; for route in 0..self.routes.len() { + let target = if self.has_bots(route) { + self.config.target_riders + } else { + 0 + }; self.keep_company(route, target); while self.population(route) < target { let room = target - self.population(route); @@ -2082,6 +2096,28 @@ mod tests { assert!(after > before + 100.0); } + #[test] + fn routes_without_bots_stay_free_of_them_while_the_others_fill_up() { + let config = SimConfig { + target_riders: 3, + routes_without_bots: vec!["flat".into()], + ..SimConfig::default() + }; + let mut world = World::with_network( + vec![square_loop(), flat_loop(250.0)], + None, + config, + Box::new(SplitMix64::new(7)), + ); + let me = world.join_human_on(1, "Anna", 70.0).unwrap(); + world.spawn_event_bots(1, 4, &[]); + ride(&mut world, 5.0, &[(me, 200.0)]); + let bots_on = |route| world.riders().filter(|r| r.route == route && r.is_bot()).count(); + assert_eq!(bots_on(0), 3); + assert_eq!(bots_on(1), 0); + assert_eq!(world.rider(me).unwrap().route, 1); + } + #[test] fn joining_humans_replace_far_away_bots() { let config = SimConfig { @@ -3060,6 +3096,11 @@ mod tests { /// A 1 km square a→b→c→d with a diagonal b→d. Route 0 rides the square, /// route 1 the triangle a→b→d→a. The diagonal climbs 14 m. pub(super) fn junction_world() -> World { + junction_world_with(vec![]) + } + + /// [`junction_world`] with `extra` routes after the square and the triangle. + fn junction_world_with(extra: Vec) -> World { use crate::network::{EdgeSpec, NodeSpec}; let node = |id: &str, x: f64, y: f64| NodeSpec { id: id.into(), x, y }; let edge = |id: &str, from: &str, to: &str, a: (f64, f64, f64), b: (f64, f64, f64)| EdgeSpec { @@ -3126,7 +3167,7 @@ mod tests { ], ); World::with_network( - vec![square, triangle], + [vec![square, triangle], extra].concat(), Some(network), SimConfig { target_riders: 0, @@ -3164,6 +3205,36 @@ mod tests { assert!(world.grade_for(me).unwrap() > 0.9, "the diagonal climbs"); } + #[test] + fn a_track_off_the_network_is_ridden_round_and_round_without_turns() { + // An oval with no walk, like the velodromes beside the island's roads. + let track = Route::new(RouteSpec { + id: "track".into(), + name: "track".into(), + lanes: 4, + seed: 1, + points: vec![ + Point::new(2000.0, 0.0, 0.0), + Point::new(2100.0, 0.0, 0.0), + Point::new(2100.0, 50.0, 0.0), + Point::new(2000.0, 50.0, 0.0), + ], + markers: vec![], + walk: vec![], + }) + .unwrap(); + let mut world = junction_world_with(vec![track]); + let me = world.join_human_on(2, "Me", 75.0).unwrap(); + place(&mut world, me, 290.0, 10.0); + assert_eq!(world.next_road_of(world.rider(me).unwrap()), None); + assert_eq!(world.choose_turn(me, Some("ab")), Err(WorldError::NoSuchTurn)); + cruise(&mut world, me, 2.0); + let rider = world.rider(me).unwrap(); + assert_eq!((rider.route, rider.off_route), (2, None)); + assert!(rider.position < 30.0, "round the lap: {}", rider.position); + assert_eq!(world.grade_for(me), Some(0.0)); + } + #[test] fn without_a_pick_riders_stay_on_their_route() { let mut world = junction_world(); diff --git a/tools/track-route.mjs b/tools/track-route.mjs new file mode 100644 index 00000000..4074e4d2 --- /dev/null +++ b/tools/track-route.mjs @@ -0,0 +1,122 @@ +#!/usr/bin/env node +/** + * Writes a track route (OpenBikeNet, shared with other apps) to stdout: + * + * node tools/track-route.mjs velodrome > routes/velodrome.json + * node tools/track-route.mjs herne-hill > routes/herne-hill.json + * node tools/track-route.mjs herne-hill-clockwise > routes/herne-hill-clockwise.json + * + * Each track is an oval of two straights and two semicircles, a point every + * ~2.5 m on the bends, ridden anticlockwise unless it says otherwise. The + * closed polyline, closing segment included, is scaled to exactly the shared + * length. It stands on the island (map `valley`) beside a road, off the road + * network: the home straight with the start/finish line faces the road on the + * north, so a connector road can join it later. The track is flat, at the + * height of the ground under its centre. + */ +import { readFileSync } from "node:fs"; +import { RoadNetwork } from "../client/public/js/route/network.js"; + +const SHARED = "shared with riders from other apps when this server is connected to OpenBikeNet."; +const HERNE_HILL = { + name: "Herne Hill Velodrome", + lanes: 4, + openbikenet_length: 450, + // Bend radius fitted to the real track (OpenBikeNet protocol, tools/herne_hill_gpx.py). + radius: 45.3, + // The start/finish line, this far before the middle of the home straight, as in London. + start: 13, + centre: [-480, -150], +}; +const TRACKS = { + velodrome: { + name: "Velodrome", + description: `250 m oval, ${SHARED}`, + lanes: 4, + seed: 250, + openbikenet: "velodrome-250", + openbikenet_length: 250, + straight: 50, + // The start/finish line at the start of the home straight. + start: 25, + centre: [-210, -120], + }, + "herne-hill": { + ...HERNE_HILL, + description: `The 450 m outdoor track of Herne Hill Velodrome in London, ridden anticlockwise as in racing; ${SHARED}`, + seed: 450, + openbikenet: "herne-hill-450", + }, + "herne-hill-clockwise": { + ...HERNE_HILL, + name: "Herne Hill Velodrome (clockwise)", + description: `Herne Hill Velodrome the other way round, from the same start/finish line; ${SHARED}`, + seed: 451, + openbikenet: "herne-hill-450-clockwise", + clockwise: true, + }, +}; +const MAP = { id: "valley", seed: 2026 }; +const BEND_STEP = 2.5; + +const id = process.argv[2]; +const track = TRACKS[id]; +if (!track) { + process.stderr.write(`usage: node tools/track-route.mjs <${Object.keys(TRACKS).join("|")}>\n`); + process.exit(1); +} + +const length = track.openbikenet_length; +// Either the straights or the bend radius is given; the other takes up the rest of the length. +const radius = track.radius ?? (length - 2 * track.straight) / (2 * Math.PI); +const straight = track.straight ?? (length - 2 * Math.PI * radius) / 2; +const half = straight / 2; +const steps = Math.round((Math.PI * radius) / BEND_STEP); + +// x east, y north from the centre: the home straight on the north (y = radius), ridden west. +let points = [[track.start, radius], [-half, radius]]; +for (let i = 1; i < steps; i += 1) { + const a = Math.PI / 2 + (Math.PI * i) / steps; + points.push([-half + radius * Math.cos(a), radius * Math.sin(a)]); +} +points.push([-half, -radius], [half, -radius]); +for (let i = 1; i < steps; i += 1) { + const a = -Math.PI / 2 + (Math.PI * i) / steps; + points.push([half + radius * Math.cos(a), radius * Math.sin(a)]); +} +points.push([half, radius]); +// From the same line the other way round. +if (track.clockwise) points = [points[0], ...points.slice(1).reverse()]; +// The line at the end of the straight is a point already. +points = points.filter((p, i) => i === 0 || Math.hypot(p[0] - points[0][0], p[1] - points[0][1]) > 1e-9); + +const closedLength = points.reduce((sum, p, i) => { + const q = points[(i + 1) % points.length]; + return sum + Math.hypot(q[0] - p[0], q[1] - p[1]); +}, 0); +const scale = length / closedLength; +const network = new RoadNetwork(JSON.parse(readFileSync(new URL("../routes/maps/valley.json", import.meta.url), "utf8"))); +const [cx, cy] = track.centre; +const elevation = Math.round(network.heightAt(cx, cy) * 10) / 10; +const round = (v) => Math.round(v * 1e6) / 1e6; +const placed = points.map(([x, y]) => [round(cx + x * scale), round(cy + y * scale), elevation]); + +const route = { + id, + name: track.name, + description: track.description, + loop: true, + lanes: track.lanes, + seed: track.seed, + map: MAP, + openbikenet: track.openbikenet, + openbikenet_length: length, + zones: [], + markers: [{ type: "start_finish", distance: 0 }], +}; + +const { markers, ...rest } = route; +const head = JSON.stringify(rest, null, 2).slice(0, -2); +const marks = markers.map((m) => ` ${JSON.stringify(m)}`).join(",\n"); +const lines = placed.map((p) => ` ${JSON.stringify(p)}`).join(",\n"); +process.stdout.write(`${head},\n "markers": [\n${marks}\n ],\n "points": [\n${lines}\n ]\n}\n`); diff --git a/tools/velodrome-route.mjs b/tools/velodrome-route.mjs deleted file mode 100644 index 5967d4aa..00000000 --- a/tools/velodrome-route.mjs +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env node -/** - * Writes the velodrome route (OpenBikeNet, shared with other apps) to stdout: - * - * node tools/velodrome-route.mjs > routes/velodrome.json - * - * A 250 m oval: two 50 m straights and two semicircles, a point every ~2.5 m - * on the bends. The closed polyline, closing segment included, is scaled to - * exactly 250 m. - */ -const LENGTH = 250; -const STRAIGHT = 50; -const BEND_STEP = 2.5; -const ELEVATION = 40; - -// Unscaled geometry: straight length 50, bend radius r with 2*pi*r + 2*50 = 250. -const radius = (LENGTH - 2 * STRAIGHT) / (2 * Math.PI); -const steps = Math.round((Math.PI * radius) / BEND_STEP); - -const points = []; -// Bottom straight, left to right, from x = 0 (the start/finish line). -points.push([0, 0]); -// Right bend, from the bottom up to the top. -for (let i = 1; i < steps; i += 1) { - const a = -Math.PI / 2 + (Math.PI * i) / steps; - points.push([STRAIGHT + radius * Math.cos(a), radius + radius * Math.sin(a)]); -} -// Top straight, right to left. -points.push([STRAIGHT, 2 * radius]); -points.push([0, 2 * radius]); -// Left bend, from the top down to the bottom. -for (let i = 1; i < steps; i += 1) { - const a = Math.PI / 2 + (Math.PI * i) / steps; - points.push([radius * Math.cos(a), radius + radius * Math.sin(a)]); -} -// The end of the bottom straight, where the right bend starts. -points.splice(1, 0, [STRAIGHT, 0]); - -const closedLength = points.reduce((sum, p, i) => { - const q = points[(i + 1) % points.length]; - return sum + Math.hypot(q[0] - p[0], q[1] - p[1]); -}, 0); -const scale = LENGTH / closedLength; -const round = (v) => Math.round(v * 1e6) / 1e6; -const scaled = points.map(([x, y]) => [round(x * scale), round(y * scale), ELEVATION]); - -const route = { - id: "velodrome", - name: "Velodrome", - description: "250 m oval, shared with riders from other apps when this server is connected to OpenBikeNet.", - loop: true, - lanes: 4, - seed: 250, - openbikenet: "velodrome-250", - markers: [{ type: "start_finish", distance: 0 }], - zones: [], - points: scaled, -}; - -const { points: pts, markers, ...rest } = route; -const head = JSON.stringify(rest, null, 2).slice(0, -2); -const marks = markers.map((m) => ` ${JSON.stringify(m)}`).join(",\n"); -const lines = pts.map((p) => ` ${JSON.stringify(p)}`).join(",\n"); -process.stdout.write(`${head},\n "markers": [\n${marks}\n ],\n "points": [\n${lines}\n ]\n}\n`);