diff --git a/HANDOFF.md b/HANDOFF.md
index 603eb7a..6f7cd2b 100644
--- a/HANDOFF.md
+++ b/HANDOFF.md
@@ -14,7 +14,7 @@ It started on 2026-10-13 as "WinterMiles" (an icTrainer alternative for riding G
## 2. Where it stands (November 2026, v0.3.9)
-**Solid and tested:** route building (GPX parsing, resampling, smoothing, climb detection), physics, ride recording and FIT export, workouts (.zwo/.erg/.mrc and built-ins), fitness maths, gamification, the 3D world (terrain with roads cut into hillsides, buildings, forests of six kinds of tree with sprites in the distance, field boundaries and hedge-banked lanes, water, the surrounding road network, bridges, tunnels, overpasses, road surface/width/markings, race barriers that lean with the road and netting round hairpins, landmarks, weather), the virtual-gear maths, diagnostics, the relay. 106 automated tests (plus two that need the network and are skipped by default), plus visual checks through the automated smoke harness (section 6).
+**Solid and tested:** route building (GPX parsing, resampling, smoothing, climb detection), physics, ride recording and FIT export, workouts (.zwo/.erg/.mrc and built-ins), fitness maths, gamification, the 3D world (terrain with roads cut into hillsides, buildings, forests of six kinds of tree with sprites in the distance, field boundaries and hedge-banked lanes, water, the surrounding road network, bridges, tunnels, overpasses, road surface/width/markings, race barriers that lean with the road and netting round hairpins, landmarks, weather), the virtual-gear maths, diagnostics, the relay. 114 automated tests (plus two that need the network and are skipped by default), plus visual checks through the automated smoke harness (section 6).
**Built but not proven with real use:**
@@ -23,6 +23,7 @@ It started on 2026-10-13 as "WinterMiles" (an icTrainer alternative for riding G
| **Trainers and sensors** | Protocols unit-tested against the specs. The first real trainer — a **Tacx Vortex Smart (T2180) over Bluetooth** — connected but **kept dropping out and showed no power**. Not yet diagnosed: a diagnostics report from a ride is needed. This is the top priority. |
| **Virtual gears** | The maths is unit-tested and shifting was checked with the demo rider and the smoke harness (`VP_SMOKE_SHIFT`), but it has **never been felt on a real trainer**. |
| **OpenBikeControl controllers** | Button decoding and the choice of one action per press are unit-tested; never connected to a real controller. |
+| **Laps on loop routes** | Lap engine, bests, segments and renderers unit-tested in `crates/core`; smoke-run across the line on Linux with three.js, not yet with the native renderer (macOS). Group standings don't show who is a lap up. |
| **Strava** (OAuth, upload, segments, activities as ghosts) | Never run against the live API. Users must create their own API key (open source can't ship a secret). Scope is `read,activity:read_all,activity:write`. |
| **Windows and Linux** | Built and packaged by CI on every push (and Arch's package is installed in a container and its libraries checked), but **never run by a person**. |
| **Native renderer** (macOS, opt-in) | wgpu/Metal in an NSView under a transparent webview. Matches three.js in screenshots; HUD-over-native never checked in a real window; no clean release-build performance comparison. |
@@ -107,7 +108,7 @@ The full process is in [CONTRIBUTING.md](CONTRIBUTING.md): issue first → branc
## 6. Testing
-- `cargo test --workspace` — 106 tests: 99 core, 1 relay, 6 app (plus two app tests that need the network: `cargo test -p velopopuli -- --ignored`); `npx tsc --noEmit` for the page. CI runs all of them.
+- `cargo test --workspace` — 114 tests: 107 core, 1 relay, 6 app (plus two app tests that need the network: `cargo test -p velopopuli -- --ignored`); `npx tsc --noEmit` for the page. CI runs all of them.
- **The smoke harness** is how most visual and end-to-end checking has been done: a debug build that rides (or opens a screen) by itself, saves pictures and the visible text, and quits. All the `VP_SMOKE_*` switches are documented in the wiki's [Building from source](https://github.com/pepperstm/velopopuli/wiki/Building-from-source). The most useful: `VP_SMOKE_AT` (start part-way), `VP_SMOKE_CAM=3` (overhead — good for junctions), `VP_SMOKE_WINDOW=1` (whole window with HUD), `VP_SMOKE_CLIP=6` (frames for a demo clip), `VP_SMOKE_SURFACE`, `VP_SKIP_OVERPASS`, `VP_SMOKE_REPORT`. With `"nativeRenderer": true` in the data folder's `settings.json`, the native renderer's own frame is saved too, as `.native.png` — the only way to see it, since window snapshots capture just the web view.
- The ride-start diagnostics line `[ride] surfaces … trails … berms … fords … widths …` shows what the map matching decided; a smoke run also prints each berm and ford.
- Good test routes: Bourg d'Oisans → Alpe d'Huez (town, river, hairpins — route it with BRouter); the Trouée d'Arenberg (OSM track "Drève des Boules d'Hérin", `surface=sett`); Meylan near Grenoble (roundabouts); any city crossing (viaducts). For trails, around Finale Ligure: graded singletrack and switchbacks (berms), Ponte dell'Acqua (OSM way 143650465, a log bridge), Strada Valle del Bosco (way 113195224, a ford over the Rio dell'Ericeto); a hike near Chamonix (grades estimated from `sac_scale`); a field near Chartres (the off-map dirt track). A test route is two files in the data folder: `data/routes.json` and `data/route-.json` (`{name, gpx}`).
@@ -149,6 +150,7 @@ CI also builds every push to `main`; installers can be downloaded from the run's
- **Diagnostics are always on** (raw sensor data optional) so a user can send a useful report after the fact; reports strip names, tokens and locations.
- **GitHub reporting opens a pre-filled issue in the browser** rather than signing in from the app: a device-flow sign-in was started and dropped in favour of the simpler approach.
- **Apple Health removed** for now (no desktop HealthKit; export import was clunky).
+- **Laps are `distance` on the loop plus `ridden` for totals.** `RideEngine` keeps `distance` as the position on the loop, in `[0, route.total]`, and adds `lap` (from 1) and `ridden` (metres across all laps). Everything meaning "where on the road" uses `distance`; everything meaning "how far ridden" (FIT, summary, progress, goal) uses `ridden`. Without laps `ridden == distance`, so ordinary rides are unchanged by construction. The choice is only accepted when the route is a loop (`Route.closed`, offered to the page by `route_is_loop`) and is kept on the ride as `laps`. Agreed with the maintainer (#67): ghosts off on lap rides, climbs and segments timed on each lap and kept fastest, and a lap ride never sets the route's best time.
- **Commits are under the maintainer's name only.**
## 10. Known traps
@@ -165,4 +167,5 @@ CI also builds every push to `main`; installers can be downloaded from the run's
- **Trees are 3D near the camera and sprites beyond about 200 m:** a chunk's trees are `[x, y, z, yaw, width, height, kind, shade]`, grouped by kind; each kind is one set of instances drawn twice, as its 3D model (`tree_model`) and as a camera-facing quad (`sprite_frame`) textured from an atlas that the page renders from the models at ride start (`trees.ts`) and hands to the native renderer as the `trees` texture. The vertex shaders split the trees one by one at each tree's own distance (`SPRITES_FROM` ± `SPRITE_SPREAD`/2, from a hash of its position), so the two copies of the rule — `spriteFrom` in `trees.ts` and `sprite_from` in `shader.wgsl` — must stay identical, or trees vanish or double at the switch. Atlas cells are cleared one at a time (`target.scissorTest`): three.js clears the whole target on every render otherwise.
- **Barrier sections lean with the road:** each is placed by `[x, y, z, yaw, distance, look, pitch]`, tipped about its own x axis first and then turned (`'YXZ'` in three.js, `vs_barrier` in the native shader), so both ends stand on the road and neighbours meet. A new renderer of them must apply the pitch, and in that order. Round a bend tighter than 30 m radius there are no sections; instead fence panels (look `FENCE`, orange netting) are laid evenly along the outside edge, so they meet end to end (`tight_bends` and `bend_fence` in `barriers.rs`). They are just another look, so neither renderer knows about them.
- **Berms tilt the riding surface and fords lower it:** anything standing *on* the route's surface (riders) must add `World::bank_at` (Rust) or `bankAt()` (page) — the lift at its offset (negative in a ford), and the roll. The inside edge of a berm is at the centre-line height; the outside is raised. The route's own `ele` is never changed by either, so gradients and physics are unaffected.
+- **Lap wrap-around:** on a lap ride `distance` jumps from `total` back to near 0 at the line, so anything comparing or extrapolating distances must use wrapped arithmetic. A climb or segment that ends exactly on the line must finish on the crossing tick, or it stays active after the wrap. A slower later lap must not overwrite a faster earlier lap in `new_segment_bests`. The chase camera, rivals just behind, the barriers and the profile behind the rider must come from the end of the loop, not clamp to 0. A remote rider sitting at exactly 0 or `total` must still be drawn on a lap ride.
- **Road looks are numbered across three places:** a new look needs its constant in `surface.rs`, its texture in `SURFACES` in `surfaces.ts` (same order), and its name in the native renderer's match in `native/mod.rs`. Today: 0–4 surfaces, 5 lane, 6 timber, 7 singletrack, 8 ford.
diff --git a/README.md b/README.md
index 0d7805d..281e900 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,7 @@ Free and open source ([GPLv3](LICENSE)) for **Windows, macOS and Linux**. Writte
- **GPX in, virtual ride out.** Import routes from Strava, Komoot, RideWithGPS or a bike computer. Routes with no elevation data (planner exports) get it filled in automatically.
- **A 3D version of the real place.** The road follows your GPX; the surrounding landscape is built from open elevation data, so the mountains on the horizon are the real ones. OpenStreetMap supplies the rest: the towns and villages you pass through, forests where the real forests are, lakes, rivers and streams, the side roads, lanes, footpaths and railways around you, and the bridges and tunnels of the real road — you ride over the river on a bridge deck, into the hillside through a lit tunnel, and under the motorway or railway that crosses overhead. A live OpenStreetMap minimap and a gradient-coloured elevation profile sit alongside. Works offline with generated hills.
+- **Laps.** On a closed route, ride it once, for 2, 3, 5, 10 or 20 laps, or until you stop. The HUD counts the laps and the distance ridden, and the profile, landmarks and riders carry on across the line.
- **A closed road, race-day style.** The road you ride is set apart from the map's road network: steel crowd barriers line both sides (with banners on some, each section standing on its feet and leaning with the road on hills, and orange netting round the outside of tight hairpins instead), its surface is the real one — tarmac, concrete slabs, cobbles, gravel or dirt — and so is its width: a 7 m main road, a 5 m village street, a 3 m farm track. Both come from OpenStreetMap's tags for the roads along the route (`surface`, `width`, `lanes`, and the road class), or are guessed from the road class when those can't be fetched. Where the route leaves the mapped roads for 100 m or more — across a field, along an unmapped trail — it becomes a dirt track. Widths change gradually, and buildings, signs, other riders and the barriers all follow them. Ride the Arenberg trench on its setts and the Strade Bianche on white gravel — and feel them: rougher surfaces roll heavier, so you slow down on screen and the trainer gets harder.
- **Mountain-bike trails.** Where the route follows an unpaved path, a bridleway, a walking trail or a trail graded for mountain bikes (OpenStreetMap's `mtb:scale`, S0–S6, or estimated from the hiking grade), you ride a narrow earth singletrack with no barriers, the HUD shows the grade, and the harder the grade the heavier it rolls — on screen and on the trainer.
- **Find a route in the app.** Search for a place, click waypoints on the map and get a route along bike-friendly roads with real elevation (BRouter), or pick one of eight famous climbs (Alpe d'Huez, Mont Ventoux, Stelvio, Galibier, Tourmalet, Mortirolo, Zoncolan, Box Hill). Mountain bikers can plan along trails, or pick from the **waymarked MTB routes** mapped in the area on screen.
@@ -61,7 +62,8 @@ Be aware of what has and has not been proven:
| Area | Status |
| --- | --- |
-| GPX parsing, route building, climb detection, physics, ride recording, gamification, terrain, building and scenery generation, workouts, fitness maths, segment and ghost matching, landmarks, photo selection | Unit-tested (`cargo test`, 99 core tests) |
+| GPX parsing, route building, climb detection, physics, ride recording, gamification, terrain, building and scenery generation, workouts, fitness maths, segment and ghost matching, landmarks, photo selection | Unit-tested (`cargo test`, 107 core tests) |
+| Laps on loop routes | Unit-tested in `crates/core`: lap counting, distance ridden, climbs and segments timed on every lap, bests kept from the fastest lap, ghosts off. Smoke-run on Linux with the three.js renderer: the lap HUD, and riders, road and barriers across the line. **Not yet** run with the native renderer (macOS). FIT lap messages and ending the ride on the workout are not done |
| Group-ride relay | Tested in-process (`cargo test -p velopopuli-relay`) and with two app instances riding together through a local relay |
| Fan and lights | Requests checked against a pretend device for Home Assistant, Shelly and a webhook; not tried with real plugs |
| Route finder, famous climbs | All eight climbs planned through the live BRouter service and checked against their known length and height gain |
diff --git a/crates/core/src/ride.rs b/crates/core/src/ride.rs
index 3c91e5e..7d0697b 100644
--- a/crates/core/src/ride.rs
+++ b/crates/core/src/ride.rs
@@ -1,6 +1,6 @@
//! The simulation and recorder for one ride.
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde::Serialize;
@@ -90,6 +90,9 @@ pub struct RideOptions {
pub ghosts: Vec,
pub segments: Vec,
pub segment_bests: BTreeMap,
+ /// Laps on a closed route: `None` rides it once, `Some(0)` goes round until stopped,
+ /// `Some(n)` finishes after `n` laps. Ignored on a route that is not a loop.
+ pub laps: Option,
}
#[derive(Debug, Clone)]
@@ -114,7 +117,14 @@ const BOT_COLORS: [u32; 5] = [0x4aa3ff, 0xffb347, 0xc56bff, 0x4ddb8a, 0xff6b9a];
pub struct RideEngine {
pub route: Arc,
pub pb: Option,
+ /// Position on the route, in `[0, route.total]`; on a lap ride it starts again at each lap.
pub distance: f64,
+ /// The lap being ridden, from 1.
+ pub lap: u32,
+ /// Total metres ridden. Equal to `distance` on a ride without laps.
+ pub ridden: f64,
+ /// Laps to ride (`Some(0)` until stopped), or `None` when the route is ridden once.
+ pub laps: Option,
pub speed: f64,
/// Moving time in seconds; the clock stops when the rider does.
pub elapsed: f64,
@@ -149,6 +159,8 @@ pub struct RideEngine {
/// Set on a shift, so the new resistance is sent straight away.
pub gear_shifted: bool,
seg_state: Vec,
+ /// Climbs already timed on this lap.
+ climbs_done: BTreeSet,
params: PhysicsParams,
/// The road surface at each route sample; empty means tarmac all the way.
@@ -186,12 +198,14 @@ impl RideEngine {
pub fn with_options(route: Arc, settings: &Settings, pb: Option, options: RideOptions) -> Self {
let params = PhysicsParams { mass: settings.rider.weight_kg + settings.rider.bike_kg, crr: settings.physics.crr, cda: settings.physics.cda, max_speed: settings.physics.max_speed_kph / 3.6 };
+ let laps = options.laps.filter(|_| route.closed);
let mut rivals = Vec::new();
- if pb.as_ref().is_some_and(|p| p.trace.len() > 1) {
+ // A recorded trace covers one trip along the route, so there are no ghosts on a lap ride.
+ if laps.is_none() && pb.as_ref().is_some_and(|p| p.trace.len() > 1) {
let trace = Arc::new(pb.as_ref().unwrap().trace.clone());
rivals.push(Rival { id: "ghost".into(), name: "Your best".into(), kind: RivalKind::Ghost, color: 0xffffff, distance: 0.0, speed: 0.0, power: 0.0, mass: 0.0, trace: Some(trace) });
}
- for g in &options.ghosts {
+ for g in options.ghosts.iter().filter(|_| laps.is_none()) {
rivals.push(Rival { id: g.id.clone(), name: g.name.clone(), kind: RivalKind::Ghost, color: g.color, distance: 0.0, speed: 0.0, power: 0.0, mass: 0.0, trace: Some(g.trace.clone()) });
}
if settings.bots.enabled {
@@ -214,6 +228,9 @@ impl RideEngine {
route,
pb,
distance: 0.0,
+ lap: 1,
+ ridden: 0.0,
+ laps,
speed: 0.0,
elapsed: 0.0,
moving: false,
@@ -232,6 +249,7 @@ impl RideEngine {
climb_index: None,
last_climb_result: None,
seg_state: vec![SegState::Waiting; options.segments.len()],
+ climbs_done: BTreeSet::new(),
segments: options.segments,
segment_bests: options.segment_bests,
new_segment_bests: BTreeMap::new(),
@@ -291,13 +309,28 @@ impl RideEngine {
let params = self.params_at(self.distance, self.params.mass);
self.speed = step_speed(self.speed, input.power, self.pos.grade, self.pos.ele, ¶ms, dt);
self.distance += self.speed * dt;
+ self.ridden += self.speed * dt;
self.elapsed += dt;
if self.workout.is_some() {
self.workout_time += dt;
}
if self.distance >= self.route.total {
+ let overshoot = self.distance - self.route.total;
self.distance = self.route.total;
- self.finished = true;
+ if self.lap_ride() && self.laps != Some(self.lap) {
+ // Finish anything that ends at the line before the position wraps.
+ self.pos = self.route.sample_at(self.distance);
+ self.track_climbs();
+ self.track_segments();
+ self.distance = overshoot;
+ self.lap += 1;
+ self.climbs_done.clear();
+ self.climb_index = None;
+ self.seg_state.fill(SegState::Waiting);
+ } else {
+ self.ridden -= overshoot;
+ self.finished = true;
+ }
}
self.pos = self.route.sample_at(self.distance);
let d_ele = self.pos.ele - prev_ele;
@@ -324,6 +357,7 @@ impl RideEngine {
}
fn step_rivals(&mut self, dt: f64) {
+ let lap_ride = self.lap_ride();
let params: Vec = self.rivals.iter().map(|r| self.params_at(r.distance, r.mass)).collect();
for (r, params) in self.rivals.iter_mut().zip(params) {
match r.kind {
@@ -333,6 +367,11 @@ impl RideEngine {
r.distance = d;
}
RivalKind::Remote => {}
+ RivalKind::Bot if lap_ride => {
+ let p = self.route.sample_at(r.distance);
+ r.speed = step_speed(r.speed, r.power, p.grade, p.ele, ¶ms, dt);
+ r.distance = (r.distance + r.speed * dt).rem_euclid(self.route.total);
+ }
RivalKind::Bot if r.distance < self.route.total => {
let p = self.route.sample_at(r.distance);
r.speed = step_speed(r.speed, r.power, p.grade, p.ele, ¶ms, dt);
@@ -349,14 +388,16 @@ impl RideEngine {
let c = &climbs[i];
if self.distance >= c.end {
let time_s = self.elapsed - self.climb_entered_at;
- self.climb_times.insert(i, time_s);
+ let fastest = self.climb_times.get(&i).map_or(time_s, |t| t.min(time_s));
+ self.climb_times.insert(i, fastest);
+ self.climbs_done.insert(i);
self.last_climb_result = Some(ClimbResult { index: i, climb: c.clone(), time_s, previous_best: self.pb.as_ref().and_then(|p| p.climbs.get(&i).copied()) });
self.climb_index = None;
}
return;
}
for (i, c) in climbs.iter().enumerate() {
- if !self.climb_times.contains_key(&i) && self.distance >= c.start && self.distance < c.end {
+ if !self.climbs_done.contains(&i) && self.distance >= c.start && self.distance < c.end {
self.climb_index = Some(i);
self.climb_entered_at = self.elapsed;
return;
@@ -369,8 +410,8 @@ impl RideEngine {
let time = (self.last_sample_time + 1000).max(wall_ms / 1000 * 1000);
self.last_sample_time = time;
let power = self.power.round();
- self.samples.push(FitSample { time, lat: self.pos.lat, lon: self.pos.lon, ele: self.pos.ele, dist: self.distance, speed: self.speed, power, hr: self.hr, cadence: self.cadence });
- self.trace.push(self.distance);
+ self.samples.push(FitSample { time, lat: self.pos.lat, lon: self.pos.lon, ele: self.pos.ele, dist: self.ridden, speed: self.speed, power, hr: self.hr, cadence: self.cadence });
+ self.trace.push(self.ridden);
self.n += 1;
self.sum_power += power;
self.joules += power;
@@ -417,7 +458,9 @@ impl RideEngine {
let time_s = self.elapsed - *entered;
splits.push(time_s);
let previous_best = self.segment_bests.get(&seg.id).map(|b| b.time_s).filter(|t| *t > 0.0);
- if previous_best.is_none_or(|b| time_s < b) {
+ // Within a lap ride the bar to beat includes this ride's earlier laps.
+ let bar = [previous_best, self.new_segment_bests.get(&seg.id).map(|b| b.time_s)].into_iter().flatten().reduce(f64::min);
+ if bar.is_none_or(|b| time_s < b) {
self.new_segment_bests.insert(seg.id.clone(), SegmentBest { time_s, splits: std::mem::take(splits) });
}
self.last_segment_result = Some(SegmentResult { id: seg.id.clone(), name: seg.name.clone(), source: seg.source, time_s, previous_best });
@@ -498,8 +541,21 @@ impl RideEngine {
}
}
+ /// Whether this ride goes round a loop for laps.
+ pub fn lap_ride(&self) -> bool {
+ self.laps.is_some()
+ }
+
+ /// Whether finishing this ride can set the route's best time: only a single complete trip does.
+ pub fn counts_for_route_best(&self) -> bool {
+ self.finished && !self.lap_ride()
+ }
+
/// Seconds behind (+) or ahead (−) of the personal-best ghost at the current position.
pub fn ghost_gap(&self) -> Option {
+ if self.lap_ride() {
+ return None;
+ }
let trace = &self.pb.as_ref()?.trace;
if trace.len() < 2 {
return None;
@@ -635,7 +691,7 @@ impl RideEngine {
start_time: self.samples.first().map_or(now_ms, |s| s.time),
end_time: self.samples.last().map_or(now_ms, |s| s.time),
timer_s: self.elapsed,
- distance_m: self.distance,
+ distance_m: self.ridden,
ascent_m: self.ascent,
descent_m: self.descent,
avg_power: self.avg_power(),
diff --git a/crates/core/src/world/mod.rs b/crates/core/src/world/mod.rs
index 91f010f..a54c8ea 100644
--- a/crates/core/src/world/mod.rs
+++ b/crates/core/src/world/mod.rs
@@ -103,7 +103,8 @@ pub struct GridMesh {
pub struct RoadMesh {
/// `ROAD_SECTION` vertices per route sample, left to right: wall base, embankment
- /// foot, tarmac edge, tarmac edge, embankment foot, wall base.
+ /// foot, tarmac edge, tarmac edge, embankment foot, wall base. A closed loop has one
+ /// more section after the last sample: the first again, so the road joins up at the line.
pub positions: Vec,
pub uvs: Vec,
/// How the road is drawn per route sample: `Surface as u8`, or `UNMARKED` for tarmac
@@ -696,9 +697,13 @@ impl World {
Some(s) => *s as u8,
None => 0,
})
- .collect();
- let mut mesh = RoadMesh { positions: Vec::with_capacity(n * ROAD_SECTION * 3), uvs: Vec::with_capacity(n * ROAD_SECTION * 2), looks };
- for i in 0..n {
+ .collect::>();
+ // A closed loop gets one more section, a copy of the first, so the road runs on across the line.
+ let sections = n + usize::from(r.closed);
+ let looks = (0..sections).map(|j| looks[j % n]).collect();
+ let mut mesh = RoadMesh { positions: Vec::with_capacity(sections * ROAD_SECTION * 3), uvs: Vec::with_capacity(sections * ROAD_SECTION * 2), looks };
+ for j in 0..sections {
+ let i = j % n;
let (a, b) = (i.saturating_sub(1), (i + 1).min(n - 1));
let (mut tx, mut tz) = (r.x[b] - r.x[a], r.z[b] - r.z[a]);
let len = tx.hypot(tz).max(1e-9);
@@ -733,7 +738,7 @@ impl World {
}) as f32,
(r.z[i] - tx * offset) as f32,
]);
- mesh.uvs.extend_from_slice(&[us[k], (i as f64 * r.step / 12.0) as f32]);
+ mesh.uvs.extend_from_slice(&[us[k], (j as f64 * r.step / 12.0) as f32]);
}
}
mesh
diff --git a/crates/core/tests/core.rs b/crates/core/tests/core.rs
index 68c742a..df90aa7 100644
--- a/crates/core/tests/core.rs
+++ b/crates/core/tests/core.rs
@@ -4,7 +4,8 @@ use velopopuli_core::fit::{encode_fit, fit_crc, FitSample, FitSession};
use velopopuli_core::gamify::{apply_ride, level_for, RideFacts};
use velopopuli_core::gpx::{build_route, demo_route, parse_gpx, RawPoint, Route, M_PER_DEG};
use velopopuli_core::physics::{step_speed, PhysicsParams};
-use velopopuli_core::ride::{RideEngine, RideInput, RivalKind};
+use velopopuli_core::ride::{GhostTrace, RideEngine, RideInput, RideOptions, RivalKind};
+use velopopuli_core::segments::{Segment, SegmentSource};
use velopopuli_core::types::{BotSettings, PersonalBest, Profile, Settings};
use velopopuli_core::world::{align_dem, Dem, Surface, Trail, World, CELLS, CHUNK, FAR_CELLS, TILE, TREE_FLOATS};
@@ -233,6 +234,162 @@ mod ride {
Arc::new(build_route("flat", &straight(3000.0, |_| Some(100.0))).unwrap())
}
+ /// A closed loop of about `length_m`, a circle of points every ~10 m, with a height by distance round it.
+ fn ring_with(length_m: f64, ele_at: impl Fn(f64) -> f64) -> Arc {
+ let r = length_m / std::f64::consts::TAU;
+ let n = (length_m / 10.0) as usize;
+ let pts: Vec = (0..=n)
+ .map(|i| {
+ let a = i as f64 / n as f64 * std::f64::consts::TAU;
+ RawPoint { lat: 45.0 + r * a.sin() / M_PER_DEG, lon: 7.0 + r * a.cos() / (M_PER_DEG * 45f64.to_radians().cos()), ele: Some(ele_at(a / std::f64::consts::TAU * length_m)) }
+ })
+ .collect();
+ Arc::new(build_route("ring", &pts).unwrap())
+ }
+
+ fn ring(length_m: f64) -> Arc {
+ ring_with(length_m, |_| 100.0)
+ }
+
+ fn lap_engine(route: Arc, laps: Option, pb: Option) -> RideEngine {
+ RideEngine::with_options(route, &settings(), pb, RideOptions { laps, ..Default::default() })
+ }
+
+ /// Rides at `power` until the engine is on lap `lap` (or stops), so one lap can be ridden harder than the next.
+ fn ride_until_lap(engine: &mut RideEngine, lap: u32, power: f64, clock: &mut u64) {
+ for _ in 0..200_000 {
+ if engine.finished || engine.lap >= lap {
+ return;
+ }
+ *clock += 100;
+ engine.tick(0.1, RideInput { power, cadence: Some(90.0), hr: Some(150.0) }, *clock);
+ }
+ panic!("never reached lap {lap}");
+ }
+
+ #[test]
+ fn laps_wrap_at_the_line_and_count_up() {
+ let route = ring(1000.0);
+ assert!(route.closed);
+ let mut clock = 1_700_000_000_000;
+ let mut engine = lap_engine(route.clone(), Some(0), None);
+ run(&mut engine, 300, 250.0, &mut clock);
+ assert!(!engine.finished);
+ assert!(engine.lap >= 2);
+ assert!(engine.distance < route.total);
+ assert!(close(engine.ridden, (engine.lap - 1) as f64 * route.total + engine.distance, 1e-6));
+ assert!(engine.samples.windows(2).all(|w| w[1].dist > w[0].dist));
+ assert!(close(engine.samples.last().unwrap().dist, engine.ridden, 1e-6));
+ assert_eq!(engine.session(clock, 0).distance_m, engine.ridden);
+ }
+
+ #[test]
+ fn finishes_after_the_chosen_laps() {
+ let route = ring(1000.0);
+ let mut clock = 0;
+ let mut engine = lap_engine(route.clone(), Some(2), None);
+ run(&mut engine, 3600, 250.0, &mut clock);
+ assert!(engine.finished);
+ assert_eq!(engine.lap, 2);
+ assert_eq!(engine.distance, route.total);
+ assert!(close(engine.ridden, 2.0 * route.total, 1e-6));
+ assert!(!engine.counts_for_route_best());
+ }
+
+ #[test]
+ fn without_laps_a_loop_finishes_once_as_before() {
+ let route = ring(1000.0);
+ let mut clock = 0;
+ let mut engine = lap_engine(route.clone(), None, None);
+ run(&mut engine, 3600, 250.0, &mut clock);
+ assert!(engine.finished);
+ assert_eq!(engine.lap, 1);
+ assert_eq!(engine.ridden, engine.distance);
+ assert_eq!(engine.distance, route.total);
+ assert!(engine.counts_for_route_best());
+ }
+
+ #[test]
+ fn an_open_route_ignores_laps() {
+ let route = flat();
+ let mut clock = 0;
+ let mut engine = lap_engine(route.clone(), Some(3), None);
+ assert!(engine.laps.is_none());
+ run(&mut engine, 3600, 250.0, &mut clock);
+ assert!(engine.finished);
+ assert_eq!(engine.ridden, route.total);
+ }
+
+ #[test]
+ fn bots_go_round_on_a_lap_ride() {
+ let route = ring(1000.0);
+ let mut clock = 0;
+ let mut engine = lap_engine(route.clone(), Some(0), None);
+ run(&mut engine, 600, 250.0, &mut clock);
+ let bot = engine.rivals.iter().find(|r| r.kind == RivalKind::Bot).unwrap();
+ assert!(bot.distance < route.total);
+ assert!(bot.speed > 1.0);
+ }
+
+ #[test]
+ fn no_ghosts_on_a_lap_ride() {
+ let route = ring(1000.0);
+ let pb = PersonalBest { time_s: 100.0, trace: vec![0.0, 10.0], ..Default::default() };
+ let mut clock = 0;
+ let mut engine = lap_engine(route.clone(), Some(0), Some(pb));
+ run(&mut engine, 30, 250.0, &mut clock);
+ assert!(engine.rivals.iter().all(|r| r.kind != RivalKind::Ghost));
+ assert!(engine.ghost_gap().is_none());
+
+ let ghost = GhostTrace { id: "g".into(), name: "Friend".into(), color: 1, trace: Arc::new(vec![0.0, 10.0]) };
+ let engine = RideEngine::with_options(route, &settings(), None, RideOptions { laps: Some(0), ghosts: vec![ghost], ..Default::default() });
+ assert!(engine.rivals.iter().all(|r| r.kind != RivalKind::Ghost));
+ }
+
+ #[test]
+ fn segments_are_timed_each_lap_and_keep_the_fastest() {
+ let route = ring(1000.0);
+ let segment = Segment { id: "whole".into(), name: "Whole lap".into(), source: SegmentSource::Strava, start: 0.0, end: route.total, avg_grade: 0.0, record: None };
+ let mut engine = RideEngine::with_options(route, &settings(), None, RideOptions { laps: Some(0), segments: vec![segment], ..Default::default() });
+ let mut clock = 0;
+ ride_until_lap(&mut engine, 2, 300.0, &mut clock);
+ let first = engine.last_segment_result.as_ref().expect("timed on the first crossing").time_s;
+ ride_until_lap(&mut engine, 3, 150.0, &mut clock);
+ let second = engine.last_segment_result.as_ref().unwrap().time_s;
+ assert!(second > first);
+ assert_eq!(engine.new_segment_bests["whole"].time_s, first);
+ }
+
+ #[test]
+ fn climbs_are_timed_again_each_lap() {
+ let route = ring_with(3000.0, |d| 100.0 + (d.clamp(500.0, 1500.0) - 500.0) * 0.06 - (d.clamp(1500.0, 2500.0) - 1500.0) * 0.06);
+ assert!(route.closed);
+ assert_eq!(route.climbs.len(), 1);
+ let mut engine = lap_engine(route, Some(0), None);
+ let mut clock = 0;
+ ride_until_lap(&mut engine, 2, 300.0, &mut clock);
+ let first = engine.last_climb_result.as_ref().expect("climb timed on lap 1").time_s;
+ let seen = engine.last_climb_result.as_ref().unwrap().time_s;
+ assert_eq!(seen, first);
+ // Keep riding into lap 2 and past its climb.
+ let mut second = None;
+ for _ in 0..200_000 {
+ clock += 100;
+ engine.tick(0.1, RideInput { power: 180.0, cadence: Some(90.0), hr: Some(150.0) }, clock);
+ if engine.lap >= 3 {
+ break;
+ }
+ let t = engine.last_climb_result.as_ref().unwrap().time_s;
+ if t != first {
+ second = Some(t);
+ break;
+ }
+ }
+ let second = second.expect("climb timed again on lap 2");
+ assert!(second > first);
+ assert_eq!(engine.climb_times[&0], first);
+ }
+
#[test]
fn stays_put_until_the_rider_pedals_then_records_one_sample_per_second() {
let mut clock = 1_700_000_000_000;
@@ -431,8 +588,14 @@ mod world {
let far = world.far(route.x[0], route.z[0]);
assert_eq!(far.positions.len(), (FAR_CELLS + 1).pow(2) * 3);
let road = world.road();
- assert_eq!(road.positions.len(), route.n * 18);
- assert_eq!(road.uvs.len(), route.n * 12);
+ // The demo loop is closed: one more section, the first again, joins the road up at the line.
+ assert!(route.closed);
+ assert_eq!(road.positions.len(), (route.n + 1) * 18);
+ assert_eq!(road.uvs.len(), (route.n + 1) * 12);
+ assert_eq!(road.looks.len(), route.n + 1);
+ assert_eq!(road.positions[route.n * 18..], road.positions[..18]);
+ // The texture carries on along the closing stretch rather than jumping back.
+ assert!(road.uvs[route.n * 12 + 1] > road.uvs[(route.n - 1) * 12 + 1]);
}
#[test]
diff --git a/docs/wiki/Building-from-source.md b/docs/wiki/Building-from-source.md
index dd9bdc1..b399c61 100644
--- a/docs/wiki/Building-from-source.md
+++ b/docs/wiki/Building-from-source.md
@@ -40,6 +40,7 @@ VP_DATA_DIR=/tmp/vp VP_SMOKE=/tmp/vp/shot.png target/debug/velopopuli
| `VP_SMOKE_CAM` | Camera: 0 behind, 1 high behind, 2 alongside, 3 overhead |
| `VP_SMOKE_WORKOUT` | Ride with this workout (e.g. `builtin-sweetspot`) |
| `VP_SMOKE_GHOSTS`, `VP_SMOKE_ROOM` | Race these ghosts / join this group-ride room |
+| `VP_SMOKE_LAPS` | Ride a loop route for this many laps (`0` until stopped) |
| `VP_SMOKE_SURFACE` | Lay the whole route in one surface (0 tarmac, 1 concrete, 2 cobbles, 3 gravel, 4 dirt) |
| *(native renderer)* | With `"nativeRenderer": true` in `data/settings.json`, also saves the native renderer's own frame as `.native.png` (macOS); the app waits for it to be written before quitting |
| `VP_SMOKE_WINDOW` | Also save the whole window, HUD included, as `.window.png` (macOS) |
diff --git a/docs/wiki/Riding.md b/docs/wiki/Riding.md
index 519be53..e939fd9 100644
--- a/docs/wiki/Riding.md
+++ b/docs/wiki/Riding.md
@@ -20,6 +20,16 @@ Power (with W/kg and zone), speed, heart rate and cadence on the left, with what

+## Laps
+
+On a closed route (a loop), the setup screen offers **Laps**: once round (the default), 2, 3, 5, 10 or 20 laps, or until you stop. Open routes don't show it.
+
+- The HUD shows the lap and the distance ridden, such as **Lap 3 of 10 · 24.10 km** (or **Lap 3** until you stop). The profile, the landmarks and the riders around you carry on across the line.
+- Climbs and segments are timed again on every lap, and keep your fastest.
+- Ghosts are off on lap rides, and a lap ride never sets the route's best time. The FIT file, ride summary, season goal and badges count the total distance ridden.
+
+Not yet: laps in the FIT file, ending the ride on the workout instead of the laps, and showing who is a lap up in group standings.
+
## Racing
- **Pace riders** hold a steady W/kg to chase or drop (set them in Settings).
diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs
index 3b4e22a..a57d417 100644
--- a/src-tauri/src/commands.rs
+++ b/src-tauri/src/commands.rs
@@ -519,6 +519,13 @@ pub async fn strava_activities(state: State<'_, AppState>) -> Res, route_id: String) -> Res {
+ Ok(load_route(&state.store, &route_id)?.closed)
+}
+
/// Finds Strava segments the route rides from start to finish and keeps them with the route.
#[tauri::command]
pub async fn segments_fetch(state: State<'_, AppState>, route_id: String) -> Res> {
@@ -883,6 +890,8 @@ pub struct SmokeConfig {
shift: Option,
/// Scroll to the heading with this text before capturing (VP_SMOKE_SCROLL).
scroll: Option,
+ /// Laps to ride on a closed route (VP_SMOKE_LAPS, 0 = until stopped).
+ laps: Option,
}
/// Automated check only: saves window frame `index` as `.frames/NNNN.png`, for demo clips.
@@ -912,6 +921,7 @@ pub fn smoke_config() -> Option {
clip: std::env::var("VP_SMOKE_CLIP").ok().and_then(|v| v.parse().ok()),
shift: std::env::var("VP_SMOKE_SHIFT").ok().and_then(|v| v.parse().ok()),
scroll: std::env::var("VP_SMOKE_SCROLL").ok(),
+ laps: std::env::var("VP_SMOKE_LAPS").ok().and_then(|v| v.parse().ok()),
})
}
diff --git a/src-tauri/src/group.rs b/src-tauri/src/group.rs
index 0162b76..9e44322 100644
--- a/src-tauri/src/group.rs
+++ b/src-tauri/src/group.rs
@@ -57,6 +57,7 @@ impl GroupLink {
link
}
+ /// `distance` is the position on the route (on a lap ride, on the loop), not the total ridden.
pub fn send(&self, distance: f64, speed: f64, power: f64) {
let _ = self.out.send(json!({ "t": "pos", "name": self.name, "key": self.key, "d": (distance * 10.0).round() / 10.0, "v": (speed * 100.0).round() / 100.0, "p": power.round() }).to_string());
}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 8d172b8..e9dfc35 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -125,6 +125,7 @@ fn main() {
commands::gears_preview,
commands::strava_activities,
commands::segments_fetch,
+ commands::route_is_loop,
commands::segments_list,
commands::workouts_list,
commands::workouts_import_dialog,
diff --git a/src-tauri/src/native/mod.rs b/src-tauri/src/native/mod.rs
index 2ecc0fa..bc8afc1 100644
--- a/src-tauri/src/native/mod.rs
+++ b/src-tauri/src/native/mod.rs
@@ -775,6 +775,11 @@ impl Renderer {
#[allow(clippy::too_many_arguments)]
fn run(&mut self, world: Arc, engine: Arc>, assets: Assets, control: Arc>, stop: Arc, app: AppHandle, host: Arc>>) {
let route = world.route.clone();
+ // A lap ride goes round a closed route: distances wrap at the line.
+ let lap_ride = engine.lock().unwrap().lap_ride();
+ let total = route.total;
+ // The signed shortest way from `from` to `to` round the loop.
+ let wrapped = |from: f64, to: f64| (to - from + total / 2.0).rem_euclid(total) - total / 2.0;
let mut look = assets.look;
let mut origin = [route.x[0], route.z[0]];
let mut scene = SceneMeshes::build(&self.device, &world, &assets, origin);
@@ -860,9 +865,13 @@ impl Renderer {
(e.distance, if e.moving { e.speed } else { 0.0 }, e.cadence.unwrap_or(if e.moving && e.power > 20.0 { 80.0 } else { 0.0 }), rivals)
};
shown += speed * dt;
- shown += (distance - shown) * (1.0 - (-dt * 6.0).exp());
- if (distance - shown).abs() > 30.0 {
+ let behind = |shown: f64| if lap_ride { wrapped(shown, distance) } else { distance - shown };
+ shown += behind(shown) * (1.0 - (-dt * 6.0).exp());
+ if behind(shown).abs() > 30.0 {
shown = distance;
+ } else if lap_ride {
+ // Fold back to the start once past the line, but keep the finish (distance == total) as it is.
+ shown = if distance >= total { shown.min(total) } else { shown.rem_euclid(total) };
}
crank += cadence / 60.0 * dt;
let p = sample(&route, shown);
@@ -932,10 +941,15 @@ impl Renderer {
if barriers_for.is_none_or(|(at, o)| (shown - at).abs() > 40.0 || o != origin) {
barriers_for = Some((shown, origin));
let mut per_look: Vec> = vec![Vec::new(); BARRIER_LOOKS];
- let first = barrier_sections.partition_point(|b| (b[4] as f64) < shown - 150.0);
- for b in barrier_sections[first..].iter().take_while(|b| (b[4] as f64) < shown + 900.0) {
- if let Some(list) = per_look.get_mut(b[5] as usize) {
- list.extend_from_slice(&[(b[0] as f64 - origin[0]) as f32, b[1], (b[2] as f64 - origin[1]) as f32, b[3], b[6], 0.0]);
+ // On a lap ride the stretch carries on across the line: the part past the end is the start.
+ let shifts = if lap_ride { vec![0.0, total, -total] } else { vec![0.0] };
+ for shift in shifts {
+ let (from, to) = (shown - 150.0 + shift, shown + 900.0 + shift);
+ let first = barrier_sections.partition_point(|b| (b[4] as f64) < from);
+ for b in barrier_sections[first..].iter().take_while(|b| (b[4] as f64) < to) {
+ if let Some(list) = per_look.get_mut(b[5] as usize) {
+ list.extend_from_slice(&[(b[0] as f64 - origin[0]) as f32, b[1], (b[2] as f64 - origin[1]) as f32, b[3], b[6], 0.0]);
+ }
}
}
for (slot, list) in barrier_instances.iter_mut().zip(per_look) {
@@ -1027,8 +1041,8 @@ impl Renderer {
riders.push((slots.len() - 1, pose, false));
let mut rider_tags: Vec<(String, [f64; 3])> = Vec::new();
for (i, (id, kind, color, d, _)) in rivals.iter().enumerate() {
- let gap = (d - shown).abs();
- if gap > 700.0 || *d <= 0.0 || *d >= route.total || slots.len() as u64 >= MAX_DRAWS {
+ let gap = if lap_ride { wrapped(shown, *d).abs() } else { (d - shown).abs() };
+ if gap > 700.0 || (!lap_ride && (*d <= 0.0 || *d >= route.total)) || slots.len() as u64 >= MAX_DRAWS {
continue;
}
let lane = *lanes.entry(id.clone()).or_insert_with(|| (if i % 2 == 1 { 1.0 } else { -1.0 }) * (1.3 + 0.5 * (i / 2) as f64));
@@ -1398,7 +1412,8 @@ impl SceneMeshes {
let route = &world.route;
let road = world.road();
let section = LAYOUT.road_section;
- let n = route.n;
+ // Road sections: one per sample, and on a closed loop one more that joins the road up at the line.
+ let n = road.looks.len();
// Daylight doesn't follow the road into a tunnel.
let covered = &world.scene.covered;
let dim = |i: usize| {
diff --git a/src-tauri/src/session.rs b/src-tauri/src/session.rs
index db51522..b2d82bd 100644
--- a/src-tauri/src/session.rs
+++ b/src-tauri/src/session.rs
@@ -52,6 +52,8 @@ pub struct RideRequest {
pub ghost_ids: Vec,
/// Join or host this group-ride room.
pub group_room: Option,
+ /// Laps on a closed route: absent for none, 0 to keep going until stopped.
+ pub laps: Option,
}
/// Days since the Unix epoch in local time.
@@ -94,6 +96,8 @@ pub struct RideInit {
/// Local hour when the ride started (for "real time of day").
hour: f64,
landmarks: Vec,
+ /// Laps as the engine understands them (none on an open route).
+ laps: Option,
}
#[derive(Serialize)]
@@ -119,7 +123,12 @@ struct GearHud {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct RideState<'a> {
+ /// Position on the route; on a lap ride, on the loop.
distance: f64,
+ /// Current lap, from 1.
+ lap: u32,
+ /// Total distance ridden, over all laps.
+ ridden: f64,
speed: f64,
power: f64,
hr: Option,
@@ -288,7 +297,7 @@ impl Session {
};
let ghosts = library::load_ghosts(store, route_id, &req.ghost_ids);
let imported_ghosts = ghosts.iter().map(|g| g.id.clone()).collect();
- let options = RideOptions { workout: workout.clone(), ghosts, segments: segments.clone(), segment_bests: pb.as_ref().map(|p| p.segments.clone()).unwrap_or_default() };
+ let options = RideOptions { workout: workout.clone(), ghosts, segments: segments.clone(), segment_bests: pb.as_ref().map(|p| p.segments.clone()).unwrap_or_default(), laps: req.laps };
let mut engine = RideEngine::with_options(route.clone(), &settings, pb.clone(), options);
engine.set_surfaces(world.scene.surfaces.clone());
engine.set_trails(world.scene.trails.clone());
@@ -297,6 +306,7 @@ impl Session {
if let Some(at) = std::env::var("VP_SMOKE_AT").ok().filter(|_| std::env::var_os("VP_SMOKE").is_some()).and_then(|v| v.parse::().ok()) {
engine.distance = at.clamp(0.0, route.total - 50.0);
engine.pos = route.sample_at(engine.distance);
+ engine.ridden = engine.distance;
}
let init = RideInit {
name: route.name.clone(),
@@ -323,6 +333,7 @@ impl Session {
t.hour() as f64 + t.minute() as f64 / 60.0
},
landmarks: if settings.look.landmarks { landmarks(&route, map.scenery.as_ref()) } else { Vec::new() },
+ laps: engine.laps,
};
if std::env::var_os("VP_SMOKE").is_some() {
for m in &init.landmarks {
@@ -469,7 +480,7 @@ impl Session {
let completed = engine.finished;
let prev = engine.pb.clone().unwrap_or_default();
let had_time = prev.time_s > 0.0;
- let is_pb = completed && (!had_time || engine.elapsed < prev.time_s);
+ let is_pb = engine.counts_for_route_best() && (!had_time || engine.elapsed < prev.time_s);
let mut climbs = prev.climbs.clone();
for (i, t) in &engine.climb_times {
let best = climbs.entry(*i).or_insert(*t);
@@ -503,7 +514,7 @@ impl Session {
routes.sort_unstable();
routes.dedup();
let goal_before = library::goal_progress(&settings.goal, &rides, 0.0);
- let goal_after = library::goal_progress(&settings.goal, &rides, engine.distance);
+ let goal_after = library::goal_progress(&settings.goal, &rides, engine.ridden);
let ramp_test = engine.workout.as_ref().is_some_and(|w| w.id == "builtin-ramp-test");
let workout_done = engine.workout.is_some() && engine.workout_pos().is_none();
let curve = power_curve(&engine.samples.iter().map(|s| s.power).collect::>());
@@ -514,7 +525,7 @@ impl Session {
};
let beat_other_ghost = completed && engine.rivals.iter().any(|r| r.kind == RivalKind::Ghost && self.imported_ghosts.contains(&r.id) && r.distance < engine.route.total);
let facts = RideFacts {
- distance_m: engine.distance,
+ distance_m: engine.ridden,
ascent_m: engine.ascent,
duration_s: engine.elapsed,
completed,
@@ -542,7 +553,7 @@ impl Session {
route_name: engine.route.name.clone(),
started_at: session.start_time,
duration_s: engine.elapsed,
- distance_m: engine.distance,
+ distance_m: engine.ridden,
ascent_m: engine.ascent,
avg_power: session.avg_power,
max_power: session.max_power,
@@ -550,7 +561,7 @@ impl Session {
avg_hr: session.avg_hr,
max_hr: session.max_hr,
avg_cadence: session.avg_cadence,
- avg_speed: if engine.elapsed > 0.0 { engine.distance / engine.elapsed } else { 0.0 },
+ avg_speed: if engine.elapsed > 0.0 { engine.ridden / engine.elapsed } else { 0.0 },
kj: session.kj,
tss: engine.tss(),
completed,
@@ -714,6 +725,8 @@ fn run(
};
let state = RideState {
distance: engine.distance,
+ lap: engine.lap,
+ ridden: engine.ridden,
speed: engine.speed,
power: tel.power,
hr: tel.hr,
@@ -755,7 +768,7 @@ fn run(
}
{
let e = engine.lock().unwrap();
- crate::diag::event("ride", format!("end distance_m={:.0} elapsed_s={:.0}", e.distance, e.elapsed));
+ crate::diag::event("ride", format!("end distance_m={:.0} elapsed_s={:.0}", e.ridden, e.elapsed));
}
// Leave the trainer on a flat road rather than stuck on the last gradient.
devices.command_trainer(TrainerCommand::Simulation { grade: 0.0, crr: 0.004, cw: 0.2 });
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 4b661ad..8f37b51 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -33,7 +33,10 @@ async function runSmoke(setScreen: (s: Screen) => void): Promise {
// Ride the newest library route (or the demo) with the simulated rider.
const routes = await api.kv.get('routes')
await api.devices.demoAdd()
- setScreen({ name: 'ride', request: { routeId: routes?.[0]?.id ?? 'demo', workoutId: smoke.workout, groupRoom: smoke.room, ghostIds: smoke.ghosts ?? [] } })
+ setScreen({
+ name: 'ride',
+ request: { routeId: routes?.[0]?.id ?? 'demo', workoutId: smoke.workout, groupRoom: smoke.room, ghostIds: smoke.ghosts ?? [], laps: smoke.laps ?? null }
+ })
} else if (
smoke.screen === 'devices' ||
smoke.screen === 'history' ||
diff --git a/web/src/bridge.ts b/web/src/bridge.ts
index 671d8f0..50bb971 100644
--- a/web/src/bridge.ts
+++ b/web/src/bridge.ts
@@ -38,7 +38,8 @@ export const api = {
routes: {
importDialog: () => invoke<{ added: RouteMeta[]; problems: string[] }>('routes_import_dialog'),
importText: (name: string, text: string) => invoke('routes_import_text', { name, text }),
- demoMeta: () => invoke('demo_meta')
+ demoMeta: () => invoke('demo_meta'),
+ isLoop: (routeId: string) => invoke('route_is_loop', { routeId })
},
badges: () => invoke('badges'),
chooseDir: () => invoke('choose_dir'),
@@ -162,6 +163,7 @@ export const api = {
clip: number | null
shift: number | null
scroll: string | null
+ laps: number | null
} | null>('smoke_config'),
frame: (index: number) => invoke('smoke_frame', { index }),
done: (png: string | null, info: string) => invoke('smoke_done', { png, info })
diff --git a/web/src/core/gpx.ts b/web/src/core/gpx.ts
index 32aca30..409a0d4 100644
--- a/web/src/core/gpx.ts
+++ b/web/src/core/gpx.ts
@@ -33,6 +33,17 @@ export interface Route {
climbs: Climb[]
}
+/** `d` folded into `[0, total)`: where on a loop a distance of any size (or sign) lies. */
+export function wrapDist(total: number, d: number): number {
+ return ((d % total) + total) % total
+}
+
+/** Signed shortest difference `to - from` round a loop, in `(-total/2, total/2]`. */
+export function wrapGap(total: number, from: number, to: number): number {
+ const g = wrapDist(total, to - from)
+ return g > total / 2 ? g - total : g
+}
+
/** Half the road's width at `dist` metres along the route. */
export function halfWidthAt(route: Route, dist: number): number {
const i = Math.max(0, Math.min(route.n - 1, Math.round(dist / route.step)))
diff --git a/web/src/types.ts b/web/src/types.ts
index b353538..1ce4819 100644
--- a/web/src/types.ts
+++ b/web/src/types.ts
@@ -244,6 +244,8 @@ export interface RideRequest {
workoutId?: string | null
ghostIds?: string[]
groupRoom?: string | null
+ /** Laps on a closed route: absent or null = none, 0 = until I stop, n = n laps. Ghosts are off on lap rides. */
+ laps?: number | null
}
export interface Profile {
@@ -340,6 +342,8 @@ export interface RideInit {
/** Local hour when the ride started. */
hour: number
landmarks: Landmark[]
+ /** Laps the ride was started with, as the engine understood them; null on a ride without laps. */
+ laps: number | null
}
export interface Landmark {
@@ -362,7 +366,12 @@ export type ControllerAction = 'shiftHarder' | 'shiftEasier' | 'harder' | 'easie
/** Streamed from the simulation about 20 times a second. */
export interface RideState {
+ /** Position on the route (on a lap ride, on the loop). */
distance: number
+ /** Current lap, from 1 (1 on a ride without laps). */
+ lap: number
+ /** Total metres ridden, across all laps. */
+ ridden: number
speed: number
power: number
hr: number | null
diff --git a/web/src/ui/ProfileChart.tsx b/web/src/ui/ProfileChart.tsx
index 8221eff..313a23e 100644
--- a/web/src/ui/ProfileChart.tsx
+++ b/web/src/ui/ProfileChart.tsx
@@ -1,6 +1,6 @@
import { useEffect, useRef } from 'react'
import { gradeColor } from '../core/fmt'
-import type { Route } from '../core/gpx'
+import { wrapDist, type Route } from '../core/gpx'
export interface ChartMarker {
distance: number
@@ -14,10 +14,12 @@ interface Props {
from?: number
to?: number
markers?: ChartMarker[]
+ /** A lap ride: the road continues past either end, so read the route round the loop. */
+ wrap?: boolean
}
/** Elevation profile coloured by gradient, with the rider's position. */
-export function ProfileChart({ route, distance, from = 0, to = route.total, markers = [] }: Props): React.JSX.Element {
+export function ProfileChart({ route, distance, from = 0, to = route.total, markers = [], wrap = false }: Props): React.JSX.Element {
const ref = useRef(null)
useEffect(() => {
@@ -34,13 +36,14 @@ export function ProfileChart({ route, distance, from = 0, to = route.total, mark
const ctx = canvas.getContext('2d')!
ctx.clearRect(0, 0, w, h)
- const i0 = Math.max(0, Math.floor(from / route.step))
- const i1 = Math.min(route.n - 1, Math.ceil(to / route.step))
+ const i0 = wrap ? Math.floor(from / route.step) : Math.max(0, Math.floor(from / route.step))
+ const i1 = wrap ? Math.ceil(to / route.step) : Math.min(route.n - 1, Math.ceil(to / route.step))
let min = Infinity
let max = -Infinity
for (let i = i0; i <= i1; i++) {
- if (route.ele[i] < min) min = route.ele[i]
- if (route.ele[i] > max) max = route.ele[i]
+ const e = route.ele[wrap ? Math.min(route.n - 1, Math.round(wrapDist(route.total, i * route.step) / route.step)) : i]
+ if (e < min) min = e
+ if (e > max) max = e
}
// Keep some vertical range so a pan-flat stretch doesn't look like a wall.
const range = Math.max(max - min, Math.min((to - from) * 0.03, 60))
@@ -49,22 +52,26 @@ export function ProfileChart({ route, distance, from = 0, to = route.total, mark
const span = to - from
for (let px = 0; px < w; px++) {
- const d = from + (px / w) * span
- if (d < 0 || d > route.total) continue
+ const at = from + (px / w) * span
+ if (!wrap && (at < 0 || at > route.total)) continue
+ const d = wrap ? wrapDist(route.total, at) : at
const f = d / route.step
const i = Math.min(route.n - 2, Math.floor(f))
const ele = route.ele[i] + (route.ele[i + 1] - route.ele[i]) * (f - i)
ctx.fillStyle = gradeColor(route.grade[i])
- ctx.globalAlpha = d <= distance ? 0.35 : 0.95
+ ctx.globalAlpha = at <= distance ? 0.35 : 0.95
const top = y(ele)
ctx.fillRect(px, top, 1, h - top)
}
ctx.globalAlpha = 1
- const mark = (d: number, color: string, radius: number): void => {
- if (d < from || d > to) return
+ const mark = (at: number, color: string, radius: number): void => {
+ // Round a loop the marker may be in view a lap away from where it is reported.
+ const d = wrap ? [at, at - route.total, at + route.total].find((c) => c >= from && c <= to) : at
+ if (d === undefined || d < from || d > to) return
+ const here = wrap ? wrapDist(route.total, d) : d
const px = ((d - from) / span) * w
- const f = Math.min(route.n - 1, d / route.step)
+ const f = Math.min(route.n - 1, here / route.step)
const ele = route.ele[Math.round(f)]
ctx.fillStyle = color
ctx.strokeStyle = '#0e1116'
diff --git a/web/src/ui/Ride.tsx b/web/src/ui/Ride.tsx
index e7b1859..3b506b3 100644
--- a/web/src/ui/Ride.tsx
+++ b/web/src/ui/Ride.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { errorText } from '../bridge'
import { distUnit, distValue, fmtDist, fmtEle, fmtTime, gradeColor, speedUnit, speedValue, zoneColor } from '../core/fmt'
-import type { Route } from '../core/gpx'
+import { wrapDist, wrapGap, type Route } from '../core/gpx'
import { api, smokeHooks, useSettings } from '../state'
import type { RideInit, RideRequest, RideState, RideSummary } from '../types'
import { WorkoutShape } from './Workouts'
@@ -115,7 +115,8 @@ export function Ride({ request, onExit, onDevices, onFinish }: Props): React.JSX
started.covered,
(i) => `${i} ${imperial ? 'mi' : 'km'}`,
imperial ? 1609.344 : 1000,
- started.landmarks
+ started.landmarks,
+ started.laps !== null
)
worldRef.current = world
const native = settingsRef.current.nativeRenderer && (await api.native.available())
@@ -181,6 +182,7 @@ export function Ride({ request, onExit, onDevices, onFinish }: Props): React.JSX
let frames = 0
const recent: number[] = []
let frameFailed = false
+ const lapRide = started.laps !== null
const loop = (now: number): void => {
raf = requestAnimationFrame(loop)
const dt = Math.min(0.1, (now - last) / 1000)
@@ -191,7 +193,7 @@ export function Ride({ request, onExit, onDevices, onFinish }: Props): React.JSX
const ahead = s.moving ? Math.min(0.25, (now - latest.at) / 1000) : 0
try {
world.frame(dt, {
- distance: Math.min(loaded.total, s.distance + s.speed * ahead),
+ distance: lapRide && !s.finished ? wrapDist(loaded.total, s.distance + s.speed * ahead) : Math.min(loaded.total, s.distance + s.speed * ahead),
speed: s.speed,
cadence: s.cadence ?? (s.moving && s.power > 20 ? 80 : 0),
rivals: s.rivals.map((r) => ({
@@ -199,7 +201,7 @@ export function Ride({ request, onExit, onDevices, onFinish }: Props): React.JSX
name: r.name,
color: r.color,
ghost: r.kind === 'ghost',
- distance: Math.min(loaded.total, r.distance + r.speed * ahead),
+ distance: lapRide ? wrapDist(loaded.total, r.distance + r.speed * ahead) : Math.min(loaded.total, r.distance + r.speed * ahead),
speed: r.speed
}))
})
@@ -319,10 +321,24 @@ export function Ride({ request, onExit, onDevices, onFinish }: Props): React.JSX
const climb = ready && hud.climbIndex !== null ? route.climbs[hud.climbIndex] : null
const climbBest = ready && hud.climbIndex !== null ? init.pbClimbs[hud.climbIndex] : undefined
const mode = settings.trainer.mode
+ const lapRide = init?.laps != null
+ const landmarksAhead = ready
+ ? init.landmarks
+ .map((m) => ({ m, ahead: lapRide ? wrapDist(init.total, m.distance - hud.distance) : m.distance - hud.distance }))
+ .filter((l) => l.ahead > 0 && l.ahead < 5000)
+ // Round a loop the next landmark may sit before the first in the list.
+ .sort((a, b) => a.ahead - b.ahead)
+ : []
const standings = ready
? [
{ id: 'me', name: settings.rider.name || 'You', color: '#e9ff60', delta: 0, me: true },
- ...hud.rivals.map((r) => ({ id: r.id, name: r.name, color: hex(r.color), delta: r.distance - hud.distance, me: false }))
+ ...hud.rivals.map((r) => ({
+ id: r.id,
+ name: r.name,
+ color: hex(r.color),
+ delta: lapRide ? wrapGap(init.total, hud.distance, r.distance) : r.distance - hud.distance,
+ me: false
+ }))
].sort((a, b) => b.delta - a.delta)
: []
@@ -343,7 +359,9 @@ export function Ride({ request, onExit, onDevices, onFinish }: Props): React.JSX