summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--Cargo.lock9
-rw-r--r--Cargo.toml2
-rw-r--r--crates/gipfel-core/src/hill.rs22
-rw-r--r--crates/gipfel-core/src/metadata.rs43
-rw-r--r--crates/gipfel-core/src/panorama.rs10
-rw-r--r--crates/gipfel-wasm/Cargo.toml14
-rwxr-xr-xcrates/gipfel-wasm/build.sh22
-rw-r--r--crates/gipfel-wasm/demo/index.html39
-rw-r--r--crates/gipfel-wasm/src/lib.rs147
10 files changed, 289 insertions, 20 deletions
diff --git a/.gitignore b/.gitignore
index b478aa0..07849dd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
/target
tests/harness/build/
+crates/gipfel-wasm/pkg/
*.tmp
gipfel-app-bin.tar.gz
diff --git a/Cargo.lock b/Cargo.lock
index 2e3db0d..02fdc71 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1774,6 +1774,15 @@ dependencies = [
]
[[package]]
+name = "gipfel-wasm"
+version = "0.5.5"
+dependencies = [
+ "gipfel-core",
+ "image",
+ "wasm-bindgen",
+]
+
+[[package]]
name = "gl_generator"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git a/Cargo.toml b/Cargo.toml
index e9aa0be..60a554a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
-members = ["crates/gipfel-core", "crates/gipfel-cli", "crates/gipfel-app"]
+members = ["crates/gipfel-core", "crates/gipfel-cli", "crates/gipfel-app", "crates/gipfel-wasm"]
# Single source of truth for metadata inherited by every crate via
# `version.workspace = true` etc. Bump `version` here on release; the
diff --git a/crates/gipfel-core/src/hill.rs b/crates/gipfel-core/src/hill.rs
index a904948..4ae0f89 100644
--- a/crates/gipfel-core/src/hill.rs
+++ b/crates/gipfel-core/src/hill.rs
@@ -2,9 +2,6 @@
//!
//! Faithful port of gipfel's `Hill.cxx`.
-use std::fs::File;
-use std::io::{BufRead, BufReader};
-
pub const FLAG_DUPLIC: u32 = 1 << 0;
pub const FLAG_KNOWN: u32 = 1 << 1;
pub const FLAG_HIDDEN: u32 = 1 << 2;
@@ -77,16 +74,20 @@ fn atof(s: &str) -> f64 {
0.0
}
-/// Load a hill database. Two line formats are accepted:
+/// Load a hill database from a file path.
+pub fn load(path: &str) -> std::io::Result<Vec<Hill>> {
+ load_from_bytes(&std::fs::read(path)?)
+}
+
+/// Load a hill database from raw bytes. Two line formats are accepted:
/// - `SHORT,NAME,DESC,LAT,LON,HEIGHT` (6 fields)
/// - `LAT,LON,HEIGHT` (3 fields, track point)
-pub fn load(path: &str) -> std::io::Result<Vec<Hill>> {
- let file = File::open(path)?;
+///
+/// Byte-oriented entry point (no filesystem): used by the WASM build and
+/// by tests. The database is Latin-1; bytes decode to Unicode code points.
+pub fn load_from_bytes(raw: &[u8]) -> std::io::Result<Vec<Hill>> {
let mut hills = Vec::new();
-
- // the database is Latin-1; decode to Unicode code points
- for line in BufReader::new(file).split(b'\n') {
- let raw = line?;
+ for raw in raw.split(|b| *b == b'\n') {
let line: String = raw.iter().map(|b| *b as char).collect();
// strsep() semantics: split into at most 10 fields, keeping empties
let vals: Vec<&str> = line.split(',').take(10).collect();
@@ -109,7 +110,6 @@ pub fn load(path: &str) -> std::io::Result<Vec<Hill>> {
hills.push(h);
}
}
-
Ok(hills)
}
diff --git a/crates/gipfel-core/src/metadata.rs b/crates/gipfel-core/src/metadata.rs
index e2a888f..f55bf1c 100644
--- a/crates/gipfel-core/src/metadata.rs
+++ b/crates/gipfel-core/src/metadata.rs
@@ -3,9 +3,6 @@
//!
//! Faithful port of gipfel's `ImageMetaData.cxx`.
-use std::fs::File;
-use std::io::{BufReader, Write};
-
use exif::{In, Tag, Value};
pub const NAN: f64 = f64::NAN;
@@ -66,6 +63,16 @@ impl ImageMetaData {
self.load_image_exif(path);
}
+ /// Like [`ImageMetaData::load_image`] but from raw bytes (no filesystem);
+ /// used by the WASM build.
+ pub fn load_image_from_bytes(&mut self, bytes: &[u8]) {
+ *self = ImageMetaData::new();
+ if let Some(com) = read_jpeg_comment_from_bytes(bytes) {
+ self.parse_gipfel_comment(&com);
+ }
+ self.load_image_exif_bytes(bytes);
+ }
+
/// Write the gipfel comment into a copy of `in_img`, saved as `out_img`.
/// Writes atomically via a temp file, like the C original.
pub fn save_image(&self, in_img: &str, out_img: &str) -> std::io::Result<()> {
@@ -76,6 +83,12 @@ impl ImageMetaData {
Ok(())
}
+ /// Like [`ImageMetaData::save_image`] but bytes in / bytes out (no
+ /// filesystem); used by the WASM build.
+ pub fn save_image_to_bytes(&self, in_bytes: &[u8]) -> std::io::Result<Vec<u8>> {
+ write_jpeg_comment_to_bytes(in_bytes, self.format_comment().as_bytes())
+ }
+
pub fn format_comment(&self) -> String {
format!(
"gipfel: longitude {}, latitude {}, height {}, direction {}, nick {}, tilt {}, focal_length_35mm {}, projection type {}, k0 {}, k1 {}, x0 {}",
@@ -149,8 +162,12 @@ impl ImageMetaData {
}
fn load_image_exif(&mut self, path: &str) {
- let Ok(file) = File::open(path) else { return };
- let mut reader = BufReader::new(file);
+ let Ok(bytes) = std::fs::read(path) else { return };
+ self.load_image_exif_bytes(&bytes);
+ }
+
+ fn load_image_exif_bytes(&mut self, bytes: &[u8]) {
+ let mut reader = std::io::Cursor::new(bytes);
let Ok(exif) = exif::Reader::new().read_from_container(&mut reader) else {
return;
};
@@ -366,6 +383,11 @@ fn marker_len_ok(marker: u8) -> bool {
/// Return the payload of the first COM segment before SOS, if any.
pub fn read_jpeg_comment(path: &str) -> Option<Vec<u8>> {
let bytes = std::fs::read(path).ok()?;
+ read_jpeg_comment_from_bytes(&bytes)
+}
+
+/// Byte-oriented twin of [`read_jpeg_comment`] (no filesystem; WASM-safe).
+pub fn read_jpeg_comment_from_bytes(bytes: &[u8]) -> Option<Vec<u8>> {
if bytes.len() < 2 || bytes[0] != 0xFF || bytes[1] != 0xD8 {
return None;
}
@@ -406,6 +428,13 @@ pub fn read_jpeg_comment(path: &str) -> Option<Vec<u8>> {
/// fresh COM segment right after SOI.
pub fn write_jpeg_comment(in_img: &str, out_img: &str, comment: &[u8]) -> std::io::Result<()> {
let bytes = std::fs::read(in_img)?;
+ let out = write_jpeg_comment_to_bytes(&bytes, comment)?;
+ std::fs::write(out_img, out)
+}
+
+/// Byte-oriented twin of [`write_jpeg_comment`] (no filesystem; WASM-safe):
+/// drop all COM segments and insert a fresh COM segment after the last APPn.
+pub fn write_jpeg_comment_to_bytes(bytes: &[u8], comment: &[u8]) -> std::io::Result<Vec<u8>> {
if bytes.len() < 2 || bytes[0] != 0xFF || bytes[1] != 0xD8 {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a JPEG file"));
}
@@ -469,9 +498,7 @@ pub fn write_jpeg_comment(in_img: &str, out_img: &str, comment: &[u8]) -> std::i
out.extend_from_slice(&bytes[copy_rest_from..]);
- let mut f = File::create(out_img)?;
- f.write_all(&out)?;
- f.flush()
+ Ok(out)
}
/// Read raw image dimensions (width, height) of a JPEG.
diff --git a/crates/gipfel-core/src/panorama.rs b/crates/gipfel-core/src/panorama.rs
index 9e27251..9216037 100644
--- a/crates/gipfel-core/src/panorama.rs
+++ b/crates/gipfel-core/src/panorama.rs
@@ -74,6 +74,16 @@ impl Panorama {
Ok(())
}
+ /// Like [`Panorama::load_data`] but from raw bytes (no filesystem);
+ /// used by the WASM build.
+ pub fn load_data_from_bytes(&mut self, raw: &[u8]) -> std::io::Result<()> {
+ let mut hills = crate::hill::load_from_bytes(raw)?;
+ crate::hill::mark_duplicates(&mut hills, 0.00001);
+ self.hills = hills;
+ self.update_angles();
+ Ok(())
+ }
+
pub fn add_hills(&mut self, extra: &[Hill]) {
self.hills.extend_from_slice(extra);
crate::hill::mark_duplicates(&mut self.hills, 0.00001);
diff --git a/crates/gipfel-wasm/Cargo.toml b/crates/gipfel-wasm/Cargo.toml
new file mode 100644
index 0000000..34cbbbd
--- /dev/null
+++ b/crates/gipfel-wasm/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "gipfel-wasm"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "EXPERIMENT: WebAssembly bindings for gipfel-core (browser spike, not part of the app)"
+
+[lib]
+crate-type = ["cdylib", "rlib"]
+
+[dependencies]
+gipfel-core = { path = "../gipfel-core" }
+image.workspace = true
+wasm-bindgen = "0.2"
diff --git a/crates/gipfel-wasm/build.sh b/crates/gipfel-wasm/build.sh
new file mode 100755
index 0000000..8d1d812
--- /dev/null
+++ b/crates/gipfel-wasm/build.sh
@@ -0,0 +1,22 @@
+#!/bin/sh
+# Build the gipfel WASM spike and serve the demo page.
+# Requires: rustup (for the wasm target) and wasm-pack.
+set -e
+cd "$(dirname "$0")"
+
+if ! rustup target list --installed 2>/dev/null | grep -q wasm32-unknown-unknown; then
+ echo "adding wasm32-unknown-unknown target ..."
+ rustup target add wasm32-unknown-unknown
+fi
+command -v wasm-pack >/dev/null 2>&1 || {
+ echo "wasm-pack not found. Install it once with:"
+ echo " cargo install wasm-pack (or: cargo binstall wasm-pack)"
+ exit 1
+}
+
+wasm-pack build --target web
+
+echo
+echo "built. serve the demo with:"
+echo " (cd crates/gipfel-wasm && python3 -m http.server 8080)"
+echo "then open http://localhost:8080/demo/"
diff --git a/crates/gipfel-wasm/demo/index.html b/crates/gipfel-wasm/demo/index.html
new file mode 100644
index 0000000..f8e764d
--- /dev/null
+++ b/crates/gipfel-wasm/demo/index.html
@@ -0,0 +1,39 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <title>gipfel WASM spike</title>
+ <style>
+ body { font-family: system-ui, sans-serif; max-width: 720px; margin: 3em auto; line-height: 1.5; }
+ pre { background: #f4f4f4; padding: 1em; overflow-x: auto; }
+ label { display: block; margin: 0.6em 0; }
+ button { margin-top: 1em; padding: 0.5em 1.2em; }
+ </style>
+</head>
+<body>
+ <h1>gipfel WASM spike</h1>
+ <p>core version: <code id="ver">loading…</code></p>
+ <p>Pick a hill database and a JPEG (ideally one saved by gipfel, or with EXIF GPS data):</p>
+ <label>gipfel.dat: <input type="file" id="db" /></label>
+ <label>image.jpg: <input type="file" id="jpg" /></label>
+ <button id="go" disabled>Run fit pipeline</button>
+ <pre id="out">pick both files, then run</pre>
+
+ <script type="module">
+ import init, { fit_demo, version } from '../pkg/gipfel_wasm.js';
+ const $ = (id) => document.getElementById(id);
+ await init();
+ $('ver').textContent = version();
+ $('go').disabled = false;
+ $('go').onclick = async () => {
+ const f = (id) => $(id).files[0];
+ if (!f('db') || !f('jpg')) { $('out').textContent = 'pick both files first'; return; }
+ const db = new Uint8Array(await f('db').arrayBuffer());
+ const jpg = new Uint8Array(await f('jpg').arrayBuffer());
+ const t0 = performance.now();
+ const res = fit_demo(db, jpg);
+ $('out').textContent = res + `\n\n(wall time: ${(performance.now() - t0).toFixed(1)} ms)`;
+ };
+ </script>
+</body>
+</html>
diff --git a/crates/gipfel-wasm/src/lib.rs b/crates/gipfel-wasm/src/lib.rs
new file mode 100644
index 0000000..b521829
--- /dev/null
+++ b/crates/gipfel-wasm/src/lib.rs
@@ -0,0 +1,147 @@
+//! EXPERIMENT: browser spike exposing the gipfel core pipeline to JavaScript.
+//!
+//! The whole computational core (hill DB, geodesy, projections, LM fit,
+//! JPEG comment + EXIF I/O) is pure Rust and WASM-friendly — the GSL
+//! removal made this possible. This crate proves the pipeline end-to-end
+//! in the browser: bytes in (hill DB + JPEG), fit report out.
+//!
+//! Build (requires rustup):
+//! rustup target add wasm32-unknown-unknown
+//! cargo install wasm-pack # once
+//! cd crates/gipfel-wasm && wasm-pack build --target web
+//! python3 -m http.server 8080 # then open /demo/
+
+use wasm_bindgen::prelude::*;
+
+/// Crate version (from Cargo.toml, via the workspace).
+#[wasm_bindgen]
+pub fn version() -> String {
+ env!("CARGO_PKG_VERSION").to_string()
+}
+
+/// End-to-end pipeline smoke test, all in memory:
+///
+/// 1. parse the hill database (`db` = gipfel.dat bytes, Latin-1 CSV)
+/// 2. read gipfel metadata from the JPEG bytes (comment, else EXIF)
+/// 3. build the panorama, take up to 5 visible hills as synthetic
+/// "user-marked" observations, perturb the view parameters, refit
+/// 4. return a JSON report (recovered parameters + max reprojection error)
+///
+/// This mirrors the native golden fit test; a correct WASM build reports
+/// a reprojection error well below one pixel.
+#[wasm_bindgen]
+pub fn fit_demo(db: &[u8], jpg: &[u8]) -> String {
+ match fit_inner(db, jpg) {
+ Ok(json) => json,
+ Err(e) => format!(r#"{{"ok":false,"error":"{}"}}"#, e.replace('\\', "\\\\").replace('"', "\\\"")),
+ }
+}
+
+fn fit_inner(db: &[u8], jpg: &[u8]) -> Result<String, String> {
+ use gipfel_core::metadata::{apply_image_metadata, ImageMetaData};
+ use gipfel_core::panorama::Panorama;
+ use gipfel_core::projection::projection_from_type;
+
+ let mut pan = Panorama::new();
+ pan.load_data_from_bytes(db).map_err(|e| format!("hill db: {e}"))?;
+
+ let mut md = ImageMetaData::new();
+ md.load_image_from_bytes(jpg);
+
+ let (w, h) = image::ImageReader::new(std::io::Cursor::new(jpg))
+ .with_guessed_format()
+ .map_err(|e| format!("image: {e}"))?
+ .into_dimensions()
+ .map_err(|e| format!("image: {e}"))?;
+ if w == 0 || h == 0 {
+ return Err("image has zero dimensions".into());
+ }
+
+ let have = apply_image_metadata(&mut pan, &md, w, h);
+ if !have {
+ // demo fallback: a fixed Alpine viewpoint so the pipeline always runs
+ pan.set_view_lat(47.36);
+ pan.set_view_long(11.15);
+ pan.set_view_height(2100.0);
+ pan.set_center_angle(20.0);
+ pan.set_pitch_angle(0.0);
+ pan.set_roll_angle(1.0);
+ pan.set_scale(3000.0);
+ }
+
+ let n = pan.visible.len().min(5);
+ if n < 2 {
+ return Err("fewer than 2 hills visible from this viewpoint".into());
+ }
+ // snapshot the "observations" (what a user would have marked)
+ let obs: Vec<_> = pan.visible[..n].iter().map(|&i| pan.hills[i].clone()).collect();
+ let known: Vec<usize> = (0..n).collect();
+
+ // perturb, then refit (distortion stays locked for the spike)
+ let center0 = pan.get_center_angle();
+ let scale0 = pan.get_scale();
+ pan.set_center_angle(center0 + 0.5);
+ pan.set_scale(scale0 * 0.95);
+ pan.comp_params_with(&obs, &known, false)?;
+
+ // reprojection error of the recovered parameters against the snapshot
+ let proj = projection_from_type(pan.projection_type);
+ let mut max_err = 0.0f64;
+ for ob in &obs {
+ let (x, y) = proj.get_coordinates(ob.alph, ob.a_elev, &pan.parms);
+ max_err = max_err.max((x - ob.x).hypot(y - ob.y));
+ }
+
+ Ok(format!(
+ concat!(
+ "{{\"ok\":true,\"hills_in_db\":{},\"image\":\"{}x{}\",\"had_gipfel_info\":{},",
+ "\"observations\":{},\"viewpoint\":{{\"lat\":{:.5},\"lon\":{:.5},\"height_m\":{:.0}}},",
+ "\"perturbed\":{{\"center_deg\":{:.4},\"scale\":{:.1}}},",
+ "\"refitted\":{{\"center_deg\":{:.6},\"pitch_deg\":{:.6},\"roll_deg\":{:.6},\"scale\":{:.2}}},",
+ "\"max_reproj_err_px\":{:.4}}}"
+ ),
+ pan.hills.len(),
+ w,
+ h,
+ have,
+ n,
+ pan.get_view_lat(),
+ pan.get_view_long(),
+ pan.get_view_height(),
+ center0 + 0.5,
+ scale0 * 0.95,
+ pan.get_center_angle(),
+ pan.get_pitch_angle(),
+ pan.get_roll_angle(),
+ pan.get_scale(),
+ max_err,
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::fit_demo;
+
+ /// The spike must also work natively (the wasm-bindgen attribute is a
+ /// no-op off-wasm), so CI here covers the whole byte-oriented pipeline.
+ /// Skips when the repo data files are not present (e.g. stripped checkouts).
+ #[test]
+ fn fit_demo_native_pipeline() {
+ let (Ok(db), Ok(jpg)) = (
+ std::fs::read("../../gipfel.dat"),
+ std::fs::read("../../tests/golden/test.jpg"),
+ ) else {
+ eprintln!("gipfel.dat / test.jpg not found, skipping");
+ return;
+ };
+ let out = fit_demo(&db, &jpg);
+ assert!(out.contains(r#""ok":true"#), "fit_demo failed: {out}");
+ // recovered parameters must reproduce the observations sub-pixel
+ let err = out
+ .split("max_reproj_err_px\":")
+ .nth(1)
+ .and_then(|s| s.trim_end_matches('}').parse::<f64>().ok())
+ .expect("error value present");
+ assert!(err < 0.01, "reprojection error too large: {out}");
+ }
+}