diff options
| author | Johannes Hofmann <Johannes.Hofmann@gmx.de> | 2026-10-27 14:54:05 +0100 |
|---|---|---|
| committer | Johannes Hofmann <Johannes.Hofmann@gmx.de> | 2026-10-27 14:54:22 +0100 |
| commit | f91431fefa0418b80dea1246aecac2c6a9dfc416 (patch) | |
| tree | e0366a87ca243cf1292936ebe44807b301fbc392 /crates | |
| parent | f519a707e32679ec512518afc3c56eeec03c260a (diff) | |
web: GPX track loading
- core: track::load_gpx_from_bytes (path wrapper delegates to it;
same hardening: size cap, no entity expansion, direct-child <ele>)
- sidebar: 'Load GPX Track…' button + hidden .gpx file input; the
track swaps in via remove_hills(FLAG_TRACK_POINT) + add_hills, so
marker hill indices never shift (track hills always live at the end
of the hill list)
- rendering: desktop parity — consecutive visible points joined with
round-cap strokes, width = scale*track_width/(dist_m*10) clamped
to [1,1000] image px, red (blue when hidden by terrain); a Track
width slider (50-1000 m, default 200) appears in Display once a
track is loaded
- track points and duplicates are excluded from guide dots, hover and
click hit-testing (they are scenery, not markable peaks)
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/gipfel-core/src/track.rs | 33 | ||||
| -rw-r--r-- | crates/wipfel/src/app.rs | 94 | ||||
| -rw-r--r-- | crates/wipfel/src/canvas_view.rs | 33 | ||||
| -rw-r--r-- | crates/wipfel/src/markers.rs | 8 |
4 files changed, 160 insertions, 8 deletions
diff --git a/crates/gipfel-core/src/track.rs b/crates/gipfel-core/src/track.rs index 5450aa8..f7bf755 100644 --- a/crates/gipfel-core/src/track.rs +++ b/crates/gipfel-core/src/track.rs @@ -32,7 +32,18 @@ pub fn load_gpx(path: &str, max_points: usize) -> Result<Vec<Hill>, String> { if size.len() > MAX_GPX_BYTES { return Err(format!("{path}: file too large ({} bytes)", size.len())); } - let data = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?; + let data = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; + load_gpx_from_bytes(&data, max_points).map_err(|e| format!("{path}: {e}")) +} + +/// Parse GPX from raw bytes. Same hardening as [`load_gpx`]: size cap, +/// no entity expansion, `<ele>` accepted only as direct child of +/// `<trkpt>`. Used directly by the browser front end. +pub fn load_gpx_from_bytes(data: &[u8], max_points: usize) -> Result<Vec<Hill>, String> { + if data.len() as u64 > MAX_GPX_BYTES { + return Err(format!("file too large ({} bytes)", data.len())); + } + let data = String::from_utf8_lossy(data); let mut reader = quick_xml::Reader::from_str(&data); reader.config_mut().trim_text(true); @@ -55,7 +66,7 @@ pub fn load_gpx(path: &str, max_points: usize) -> Result<Vec<Hill>, String> { } loop { - match reader.read_event().map_err(|e| format!("{path}: {e}"))? { + match reader.read_event().map_err(|e| e.to_string())? { Event::Eof => break, Event::Empty(e) => { if e.local_name().as_ref() == b"trkpt" { @@ -112,7 +123,7 @@ pub fn load_gpx(path: &str, max_points: usize) -> Result<Vec<Hill>, String> { } if pts.is_empty() { - return Err(format!("{path}: no track points")); + return Err("no track points".to_string()); } let stride = pts.len().div_ceil(max_points.max(1)); @@ -173,6 +184,22 @@ mod tests { } #[test] + fn gpx_from_bytes_matches_path_api() { + // the browser front end feeds raw bytes directly + let gpx = br#"<?xml version="1.0" encoding="UTF-8"?> +<gpx version="1.1"><trk><trkseg> + <trkpt lat="47.36" lon="11.15"><ele>2100</ele></trkpt> + <trkpt lat="47.37" lon="11.16"><ele>2150</ele></trkpt> +</trkseg></trk></gpx>"#; + let hills = load_gpx_from_bytes(gpx, 100).unwrap(); + assert_eq!(hills.len(), 2); + assert!(hills.iter().all(|h| h.is_track_point())); + assert!((hills[0].phi - 47.36f64.to_radians()).abs() < 1e-12); + assert!((hills[1].height - 2150.0).abs() < 1e-9); + assert!(load_gpx_from_bytes(b"<gpx></gpx>", 10).is_err()); // no points + } + + #[test] fn gpx_vendor_extensions_ignored() { // Garmin-style files are full of vendor extension blocks; they must // not confuse the parser (and must not contribute elevation). diff --git a/crates/wipfel/src/app.rs b/crates/wipfel/src/app.rs index 2b205fa..d0c8ecd 100644 --- a/crates/wipfel/src/app.rs +++ b/crates/wipfel/src/app.rs @@ -5,7 +5,8 @@ use std::io::Read; use std::rc::Rc; use flate2::read::GzDecoder; -use gipfel_core::hill::{FLAG_DUPLIC, FLAG_HIDDEN, FLAG_TRACK_POINT}; +use gipfel_core::hill::{FLAG_DUPLIC, FLAG_HIDDEN, FLAG_TRACK_POINT, FLAG_VISIBLE}; +use gipfel_core::track as gpx; use gipfel_core::metadata::{apply_image_metadata, ImageMetaData}; use gipfel_core::panorama::Panorama; use wasm_bindgen::closure::Closure; @@ -15,7 +16,7 @@ use web_sys::{DragEvent, Event, HtmlCanvasElement, HtmlInputElement, InputEvent, use yew::prelude::*; use crate::bridge; -use crate::canvas_view::{CanvasView, DotView, MarkerView, ViewCallbacks, ViewState}; +use crate::canvas_view::{CanvasView, DotView, MarkerView, TrackView, ViewCallbacks, ViewState}; use crate::compass::{Compass, CompassData}; use crate::markers::{self, Marker}; use crate::widgets::{NumItem, SliderItem}; @@ -163,6 +164,10 @@ pub fn app() -> Html { let find_peak = use_state(|| Option::<FindPeak>::None); let show_hidden = use_state(|| false); let peak_labels = use_state(|| false); + // hill indices of the GPS track, in file order + let track = use_state(Vec::<usize>::new); + let track_width = use_state(|| 200.0f64); + let track_file_ref = use_node_ref(); // set once the user pans or zooms by hand; auto-fit is then suppressed // until the next image load let user_moved = use_mut_ref(|| false); @@ -433,6 +438,50 @@ pub fn app() -> Html { }) }; + let open_track_picker = { + let track_file_ref = track_file_ref.clone(); + Callback::from(move |_: MouseEvent| { + if let Some(input) = track_file_ref.cast::<HtmlInputElement>() { + input.click(); + } + }) + }; + + // parse a GPX file and swap it into the panorama as track-point hills + // (always appended last, so marker hill indices never shift) + let on_track_file_change = { + let pan = pan.clone(); + let track = track.clone(); + let status = status.clone(); + Callback::from(move |e: Event| { + let input: HtmlInputElement = e.target_unchecked_into(); + let Some(file) = input.files().and_then(|f| f.item(0)) else { + return; + }; + let (pan, track, status) = (pan.clone(), track.clone(), status.clone()); + let name = file.name(); + spawn_local(async move { + match bridge::read_blob(&file).await { + Ok(bytes) => match gpx::load_gpx_from_bytes(&bytes, 2000) { + Ok(hills) => { + let n = hills.len(); + { + let p = &mut *pan.borrow_mut(); + p.remove_hills(FLAG_TRACK_POINT); + p.add_hills(&hills); + track.set((p.hills.len() - n..p.hills.len()).collect()); + } + status.set(format!("Track {name}: {n} points")); + } + Err(err) => status.set(format!("GPX failed: {err}")), + }, + Err(err) => status.set(format!("Failed to read {name}: {err}")), + } + }); + input.set_value(""); // allow re-selecting the same file + }) + }; + let on_distortion_toggle = { let fit_distortion = fit_distortion.clone(); let markers = markers.clone(); @@ -501,6 +550,10 @@ pub fn app() -> Html { peak_labels.set(input.checked()); }) }; + let on_track_width = { + let track_width = track_width.clone(); + Callback::from(move |v: f64| track_width.set(v)) + }; // compass strip: shares the image transform, drag changes azimuth let compass_data = { @@ -720,7 +773,10 @@ pub fn app() -> Html { let marked: Vec<usize> = markers.iter().map(|m| m.hill).collect(); p.visible .iter() - .filter(|&&i| *show_hidden || p.hills[i].flags & FLAG_HIDDEN == 0) + .filter(|&&i| { + p.hills[i].flags & (FLAG_DUPLIC | FLAG_TRACK_POINT) == 0 + && (*show_hidden || p.hills[i].flags & FLAG_HIDDEN == 0) + }) .map(|&i| DotView { x: p.hills[i].x, y: p.hills[i].y, @@ -730,6 +786,24 @@ pub fn app() -> Html { }) .collect() }; + let track_views: Vec<TrackView> = { + let p = pan.borrow(); + track + .iter() + .filter(|&&i| p.hills[i].flags & FLAG_VISIBLE != 0) + .map(|&i| { + let h = &p.hills[i]; + // C: scale * track_width / (dist_m * 10), distance in meters + let dist_m = p.get_real_distance(i).max(1.0); + TrackView { + x: h.x, + y: h.y, + hidden: h.flags & FLAG_HIDDEN != 0, + width: (p.get_scale() * *track_width / (dist_m * 10.0)).clamp(1.0, 1000.0), + } + }) + .collect() + }; let zoom_pct = (view.scale * 100.0).round(); let n_markers = markers.len(); @@ -740,6 +814,7 @@ pub fn app() -> Html { <h1>{ "wipfel" }</h1> <p class="tag">{ "web gipfel photogrammetry" }</p> <button onclick={open_picker}>{ "Open image…" }</button> + <button onclick={open_track_picker}>{ "Load GPX Track…" }</button> <button onclick={fit} disabled={bitmap.is_none()}>{ "Fit to window" }</button> <input type="file" @@ -748,6 +823,13 @@ pub fn app() -> Html { class="hidden-file" onchange={on_file_change} /> + <input + type="file" + ref={track_file_ref} + accept=".gpx,application/gpx+xml" + class="hidden-file" + onchange={on_track_file_change} + /> <p class="status">{ (*status).clone() }</p> <p class="hint">{ (*db_status).clone() }</p> if bitmap.is_some() { @@ -774,6 +856,11 @@ pub fn app() -> Html { { "Fit distortion (needs ≥ 4 markers)" } </label> <div class="section">{ "Display" }</div> + if !track.is_empty() { + <SliderItem label="Track width" display={format!("{:.0} m", *track_width)} + value={*track_width} min={50.0} max={1000.0} step={10.0} + onchange={on_track_width} /> + } <label class="row"> <input type="checkbox" checked={*show_hidden} onchange={on_show_hidden} /> { "Show hidden peaks" } @@ -811,6 +898,7 @@ pub fn app() -> Html { canvas_ref={canvas_ref.clone()} tick={*tick} markers={marker_views} + track={track_views} candidates={candidates} peak_labels={*peak_labels} label_font={vp.label_font} diff --git a/crates/wipfel/src/canvas_view.rs b/crates/wipfel/src/canvas_view.rs index 76aebfc..9ec2267 100644 --- a/crates/wipfel/src/canvas_view.rs +++ b/crates/wipfel/src/canvas_view.rs @@ -36,6 +36,16 @@ pub struct DotView { pub name: String, } +/// One GPS track point in center-relative image coordinates; `width` is +/// the projected stroke width in image pixels (C: scale*width/(dist_m*10)). +#[derive(Clone, Debug, PartialEq)] +pub struct TrackView { + pub x: f64, + pub y: f64, + pub hidden: bool, + pub width: f64, +} + #[derive(Clone, PartialEq)] pub struct ViewCallbacks { pub pan: Callback<(f64, f64)>, @@ -64,6 +74,8 @@ pub struct Props { /// bumped on window resize to force a redraw pub tick: u32, pub markers: Vec<MarkerView>, + /// GPS track points in file order + pub track: Vec<TrackView>, /// guide dots for all visible hills pub candidates: Vec<DotView>, /// draw name labels for unmarked visible peaks too @@ -101,6 +113,7 @@ pub fn canvas_view(props: &Props) -> Html { let view = props.view.clone(); let canvas_ref = props.canvas_ref.clone(); let markers = props.markers.clone(); + let track = props.track.clone(); let candidates = props.candidates.clone(); let label_font = props.label_font; let peak_labels = props.peak_labels; @@ -110,11 +123,12 @@ pub fn canvas_view(props: &Props) -> Html { view, props.tick, markers.clone(), + track.clone(), candidates.clone(), label_font, peak_labels, ), - move |(bitmap, view, _tick, markers, candidates, label_font, peak_labels)| { + move |(bitmap, view, _tick, markers, track, candidates, label_font, peak_labels)| { let Some(canvas) = canvas_ref.cast::<HtmlCanvasElement>() else { return; }; @@ -154,6 +168,23 @@ pub fn canvas_view(props: &Props) -> Html { let sx = |x: f64| (x + hw) * view.scale + view.ox; let sy = |y: f64| (y + hh) * view.scale + view.oy; + // GPS track: consecutive points joined with round-cap + // strokes scaled by distance (desktop parity: red, or + // blue where the point is hidden by terrain) + for w in track.windows(2) { + let (a, b) = (&w[0], &w[1]); + let color = if a.hidden { "rgb(51, 102, 255)" } else { "rgb(255, 51, 51)" }; + #[allow(deprecated)] + ctx.set_stroke_style(&wasm_bindgen::JsValue::from_str(color)); + ctx.set_line_width((a.width * view.scale).max(1.0)); + ctx.set_line_cap("round"); + ctx.begin_path(); + ctx.move_to(sx(a.x), sy(a.y)); + ctx.line_to(sx(b.x), sy(b.y)); + ctx.stroke(); + } + ctx.set_line_cap("butt"); + // guide dots for all visible peaks: dark outline ring + // bright core so they stay visible on any photo content; // peaks hidden by nearer terrain are drawn grey diff --git a/crates/wipfel/src/markers.rs b/crates/wipfel/src/markers.rs index d024f2e..b8c00aa 100644 --- a/crates/wipfel/src/markers.rs +++ b/crates/wipfel/src/markers.rs @@ -46,7 +46,13 @@ pub fn nearest_hill( let mut best = None; let mut best_d = max_dist; for &i in &pan.visible { - if !show_hidden && pan.hills[i].flags & gipfel_core::hill::FLAG_HIDDEN != 0 { + let flags = pan.hills[i].flags; + if flags & gipfel_core::hill::FLAG_DUPLIC != 0 + || flags & gipfel_core::hill::FLAG_TRACK_POINT != 0 + { + continue; + } + if !show_hidden && flags & gipfel_core::hill::FLAG_HIDDEN != 0 { continue; } let h = &pan.hills[i]; |
