Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 9 additions & 2 deletions HANDOFF.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,11 @@ src-tauri/ The app (Tauri 2)
mapdata.rs Downloading + caching vector tiles and Overpass data per route
native/ Native renderer (mod.rs, host.rs NSView, shader.wgsl)
diag.rs Diagnostics log + reports; issues.rs: GitHub new-issue links; snapshot.rs: window PNGs (macOS)
strava, geo, photos, smart, group, library, terrain, secrets, store
connectors/ Services a ride is uploaded to, and whose past rides can be raced as ghosts:
mod.rs (Connector trait, registry, descriptor types the settings card is built from),
strava.rs (OAuth, upload, recent rides, segments).
docs/ADDING_A_CONNECTOR.md explains adding one.
geo, photos, smart, group, library, terrain, secrets, store
web/ React + three.js (Vite). ui/ screens, world/ the 3D scene (scene.ts, terrain.ts, trees.ts (tree models, sprite atlas), rider.ts,
barriers.ts, surfaces.ts, weather.ts, native.ts = assets handed to the native renderer)
docs/images/ README screenshots; docs/wiki/ wiki source
Expand All @@ -80,7 +84,8 @@ How a ride flows end to end is in the wiki's [Architecture](https://github.com/p
- **App data folder:** macOS `~/Library/Application Support/org.velopopuli.VeloPopuli`, Windows `%APPDATA%\org.velopopuli.VeloPopuli`, Linux `~/.local/share/org.velopopuli.VeloPopuli`. Override with `VP_DATA_DIR`.
- `data/*.json` (store keys): `settings`, `routes` (library list) + `route-<id>` (name + GPX), `rides`, `profile`, `ghosts-<route>`, `scenery-<route>`, `buildings-<route>`, workouts, segments.
- **Caches have versions:** buildings `FORMAT` (2) and `SCENERY_FORMAT` (4) in `mapdata.rs`; road tags `WAY_TAGS` (3, since trails added `mtb:scale`) in `world/surface.rs`. Bump the relevant one when the cached shape changes, or old caches will be read wrongly.
- **Secrets** (Strava, Home Assistant, GitHub none): OS keychain on macOS/Windows under the service name **"Velo Populi"** (with the space — kept on purpose so saved logins survive the rename), files with 0600 permissions on Linux.
- **Secrets** (Strava, Home Assistant, GitHub none): OS keychain on macOS/Windows under the service name **"Velo Populi"** (with the space — kept on purpose so saved logins survive the rename), files with 0600 permissions on Linux. Each connector's credentials are one entry named after its id (`strava`, …); the Home Assistant token is `homeassistant`.
- **Uploads:** a ride records where it went in `RideSummary.uploads` by connector id. Rides from before v0.3.10 carry `stravaActivityId` instead; `RideSummary::upload()` (Rust) and `uploadOf()` (page) read both, and `connector_upload` copies it into `uploads` when it next writes the list. The old field is kept alongside for a release or two so 0.3.9 still sees the ride as uploaded. The old `stravaAutoUpload` setting becomes `autoUpload: ["strava"]` in `mergeSettings`.
- **Logs:** `logs/diagnostics-<time>.log`, last 12 runs kept.

## 5. Building
Expand Down Expand Up @@ -154,6 +159,8 @@ CI also builds every push to `main`; installers can be downloaded from the run's
- **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.**

- **Connectors are a trait plus a registry** (`src-tauri/src/connectors/`), not a Strava module with ifs, because Dreeve (self-hosted, API key, no activity page) is the next target and differs from Strava in how it links, what an upload returns and what else it offers. The page draws each service's settings card from the connector's own description, so a new service is one Rust file. Listing past rides (for ghosts) and finding segments along a route are optional parts of the trait whose defaults say the service can't, because services offer different subsets: Strava has both, Dreeve's public API has rides but no segments. `SegmentSource::Strava` became `Remote` plus a `connector` field on the segment; stored segments that still say "strava" are read as Remote from Strava.

## 10. Known traps

- **ANT+ network key** is in `devices/ant.rs`; distributors should register as an ANT+ adopter (free) at thisisant.com.
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/gamify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub const BADGES: [Badge; 23] = [
Badge { id: "workout", name: "Structured", description: "Finish a structured workout" },
Badge { id: "ramp", name: "Lab Rat", description: "Complete an FTP ramp test" },
Badge { id: "ghost-hunter", name: "Ghost Hunter", description: "Finish ahead of someone else's ghost" },
Badge { id: "segment", name: "Segment Hunter", description: "Set a best time on a Strava segment" },
Badge { id: "segment", name: "Segment Hunter", description: "Set a best time on a segment from Strava or another connected service" },
Badge { id: "segments-10", name: "Leaderboard Regular", description: "Set ten segment bests" },
Badge { id: "group", name: "Peloton", description: "Ride with friends in a group ride" },
Badge { id: "night", name: "Night Owl", description: "Start a ride after 9 pm" },
Expand Down
80 changes: 78 additions & 2 deletions crates/core/src/segments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@ pub const SPLIT_M: f64 = 10.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SegmentSource {
/// One of the route's own detected climbs.
Climb,
Strava,
/// Found on a connected service (Strava, Dreeve, …); `Segment::connector` says which.
/// Stored as "strava" by versions that only knew Strava.
#[serde(alias = "strava")]
Remote,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
Expand All @@ -21,16 +25,29 @@ pub struct Segment {
pub id: String,
pub name: String,
pub source: SegmentSource,
/// The connector a remote segment came from. Missing in data from before connectors: Strava.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub connector: Option<String>,
/// Start and end, in metres along the route.
pub start: f64,
pub end: f64,
#[serde(default)]
pub avg_grade: f64,
/// Fastest time on Strava ("KOM"/"QOM"), as Strava formats it, when known.
/// Fastest time on the service ("KOM"/"QOM"), as it formats it, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub record: Option<String>,
}

impl Segment {
/// The connector a remote segment came from, naming Strava for data written before connectors.
pub fn connector_id(&self) -> Option<&str> {
match self.source {
SegmentSource::Climb => None,
SegmentSource::Remote => Some(self.connector.as_deref().unwrap_or("strava")),
}
}
}

/// Best time on a segment, with the elapsed time at every [`SPLIT_M`] metres so it can be raced live.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
Expand Down Expand Up @@ -123,6 +140,65 @@ pub fn follow_track(route: &Route, points: &[(f64, f64)], tolerance: f64) -> Vec
.collect()
}

/// How far along the route a ride's outline (a service's simplified summary polyline) follows
/// it from its start, in metres; 0 if the ride never passes the route's start. Looser than
/// `ghost_trace` because outlines drop most points: it sorts a list of rides, the ghost import
/// still checks the full track.
pub fn outline_follow_distance(route: &Route, outline: &[(f64, f64)]) -> f64 {
const NEAR_START: f64 = 150.0;
const TOLERANCE: f64 = 60.0;
if outline.len() < 2 || route.n < 2 {
return 0.0;
}
// Fill in long straight pieces so the outline meets the route every ~20 m.
let mut pts: Vec<(f64, f64)> = Vec::with_capacity(outline.len() * 4);
for w in outline.windows(2) {
let ((a_lat, a_lon), (b_lat, b_lon)) = (w[0], w[1]);
let dy = (b_lat - a_lat) * crate::gpx::M_PER_DEG;
let dx = (b_lon - a_lon) * crate::gpx::M_PER_DEG * a_lat.to_radians().cos();
let steps = (dx.hypot(dy) / 20.0).ceil().max(1.0) as usize;
for k in 0..steps {
let f = k as f64 / steps as f64;
pts.push((a_lat + (b_lat - a_lat) * f, a_lon + (b_lon - a_lon) * f));
}
}
pts.push(*outline.last().unwrap());
// Cheap rejection first: most rides never pass the route's start.
let (sx, sz) = (route.x[0], route.z[0]);
let Some(begin) = pts.iter().position(|&(lat, lon)| {
let (x, z) = route.to_local(lat, lon);
(x - sx).hypot(z - sz) < NEAR_START
}) else {
return 0.0;
};
let mut reached = 0f64;
let mut off = 0;
for d in follow_track(route, &pts[begin..], TOLERANCE) {
match d {
Some(d) => {
off = 0;
reached = reached.max(d);
}
None => {
off += 1;
// About 300 m away from the route: it has left for good.
if off > 15 {
break;
}
}
}
}
reached
}

/// Whether an outline rides the route from its start for at least half of it (a kilometre on
/// short routes): enough of the route for the ghost to be worth racing. Rides from home that
/// only share the first streets with the route don't count.
pub fn outline_follows_route(route: &Route, outline: &[(f64, f64)]) -> bool {
let need = (route.total * 0.5).max(1000.0).min(route.total * 0.8);
outline_follow_distance(route, outline) >= need
}

/// Places a Strava segment's shape on the route: `(start, end)` in metres, if the route rides all of it.
pub fn place_segment(route: &Route, shape: &[(f64, f64)], length: f64) -> Option<(f64, f64)> {
let (first, last) = (shape.first()?, shape.last()?);
Expand Down
55 changes: 53 additions & 2 deletions crates/core/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,9 @@ pub struct Settings {
pub buildings: bool,
/// Show forests, water, bridges and tunnels from OpenStreetMap.
pub scenery: bool,
pub strava_auto_upload: bool,
/// Connectors (by id, see the app's `connectors` module) every finished ride is sent to without asking.
#[serde(default)]
pub auto_upload: Vec<String>,
pub export_dir: String,
pub goal: Goal,
pub look: WorldLook,
Expand All @@ -268,7 +270,7 @@ impl Default for Settings {
real_terrain: true,
buildings: true,
scenery: true,
strava_auto_upload: false,
auto_upload: Vec::new(),
export_dir: String::new(),
goal: Default::default(),
look: Default::default(),
Expand Down Expand Up @@ -342,6 +344,11 @@ pub struct RideSummary {
pub xp: u64,
pub new_badges: Vec<String>,
pub file_path: String,
/// Where the ride has been sent, by connector id ("strava", "dreeve", …).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub uploads: BTreeMap<String, UploadRecord>,
/// Older profiles recorded a Strava upload here; read through `upload("strava")`. Still written
/// alongside `uploads` so going back to 0.3.9 doesn't offer to upload the ride again.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub strava_activity_id: Option<u64>,
/// Best average power for each of `fitness::CURVE_DURATIONS`.
Expand All @@ -358,3 +365,47 @@ pub struct RideSummary {
#[serde(default)]
pub group: bool,
}

/// One upload of a ride to a connector.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UploadRecord {
pub uploaded_at: u64,
/// The service's own id for the activity (or the upload), when it gives one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
/// Where to see the ride on the service, when it has a page for it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// What the service said, e.g. "queued for import".
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}

impl RideSummary {
/// The upload to `connector`, including a Strava upload recorded by an older version.
pub fn upload(&self, connector: &str) -> Option<UploadRecord> {
if let Some(record) = self.uploads.get(connector) {
return Some(record.clone());
}
if connector == "strava" {
if let Some(id) = self.strava_activity_id {
return Some(UploadRecord { uploaded_at: self.started_at, reference: Some(id.to_string()), url: Some(format!("https://www.strava.com/activities/{id}")), message: None });
}
}
None
}

/// Copies a legacy Strava upload into `uploads`. The old field stays for a release or two, so
/// an older version still sees the ride as uploaded; drop it once 0.3.9 is far enough back.
pub fn migrate_uploads(&mut self) {
if let Some(record) = self.strava_activity_id.map(|id| UploadRecord {
uploaded_at: self.started_at,
reference: Some(id.to_string()),
url: Some(format!("https://www.strava.com/activities/{id}")),
message: None,
}) {
self.uploads.entry("strava".into()).or_insert(record);
}
}
}
3 changes: 2 additions & 1 deletion crates/core/tests/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,8 @@ mod ride {
#[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 segment =
Segment { id: "whole".into(), name: "Whole lap".into(), source: SegmentSource::Remote, connector: Some("strava".into()), 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);
Expand Down
28 changes: 26 additions & 2 deletions crates/core/tests/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use velopopuli_core::fitness::{estimate_ftp, power_curve, power_zone, training_l
use velopopuli_core::gamify::streaks;
use velopopuli_core::gpx::{build_route, parse_gpx_track_times, parse_iso_time, RawPoint, M_PER_DEG};
use velopopuli_core::ride::{GhostTrace, RideEngine, RideInput, RideOptions};
use velopopuli_core::segments::{decode_polyline, follow_track, ghost_trace, place_segment, Segment, SegmentSource};
use velopopuli_core::segments::{decode_polyline, follow_track, ghost_trace, outline_follow_distance, outline_follows_route, place_segment, Segment, SegmentSource};
use velopopuli_core::types::{Settings, TrainerSettings};
use velopopuli_core::workout::{builtin_workouts, parse_erg, parse_zwo, StepKind};

Expand Down Expand Up @@ -233,7 +233,7 @@ fn ghosts_from_recorded_rides() {
#[test]
fn segment_bests_and_live_gap() {
let route = l_route(1.0);
let seg = Segment { id: "s".into(), name: "Sprint".into(), source: SegmentSource::Strava, start: 100.0, end: 600.0, avg_grade: 0.0, record: None };
let seg = Segment { id: "s".into(), name: "Sprint".into(), source: SegmentSource::Remote, connector: Some("strava".into()), start: 100.0, end: 600.0, avg_grade: 0.0, record: None };
let ride = |power: f64, bests| {
let mut e = RideEngine::with_options(route.clone(), &Settings::default(), None, RideOptions { segments: vec![seg.clone()], segment_bests: bests, ..Default::default() });
let mut live_gap = None;
Expand Down Expand Up @@ -465,3 +465,27 @@ fn loop_routes_are_followed_from_their_start() {
let trace = ghost_trace(&route, &track).expect("a ride from just before the start/finish is a ghost of this loop");
assert!(close(*trace.last().unwrap(), 1192.0, 30.0), "{}", trace.last().unwrap());
}

#[test]
fn ride_outlines_are_matched_to_a_route() {
let route = l_route(2.0);
// A sparse outline that rides the route: a few points, as a summary polyline has.
let along: Vec<(f64, f64)> = [0.0, 700.0, 1500.0, 2000.0, 2600.0, 3400.0].iter().map(|&d| route.sample_at(d)).map(|p| (p.lat, p.lon)).collect();
assert!(outline_follows_route(&route, &along));
// The same ride but started 1.5 km into the route: it never passes the start.
assert!(!outline_follows_route(&route, &along[2..]));
// Shares the first 1.5 km of the 4 km route, then turns off: not enough to race.
let shared: Vec<(f64, f64)> = [0.0, 700.0, 1500.0].iter().map(|&d| route.sample_at(d)).map(|p| (p.lat, p.lon)).chain([(45.02, 5.98)]).collect();
assert!(close(outline_follow_distance(&route, &shared), 1500.0, 40.0), "{}", outline_follow_distance(&route, &shared));
assert!(!outline_follows_route(&route, &shared));
assert!(close(outline_follow_distance(&route, &along), 3400.0, 40.0), "{}", outline_follow_distance(&route, &along));
// Passes the start but turns off after 300 m.
let start = route.sample_at(0.0);
let turn = route.sample_at(300.0);
let away = vec![(start.lat, start.lon), (turn.lat, turn.lon), (turn.lat, turn.lon - 0.02), (turn.lat - 0.01, turn.lon - 0.02)];
assert!(!outline_follows_route(&route, &away));
// Somewhere else entirely, and degenerate outlines.
assert!(!outline_follows_route(&route, &[(48.0, 11.0), (48.01, 11.01)]));
assert!(!outline_follows_route(&route, &along[..1]));
assert!(!outline_follows_route(&route, &[]));
}
Loading
Loading